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, 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_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                OpenOptions {
 955                    visible: Some(OpenVisible::None),
 956                    ..Default::default()
 957                },
 958                window,
 959                cx,
 960            )
 961        })
 962        .detach();
 963    cx.background_executor.run_until_parked();
 964    let external_worktree_id = cx.read(|cx| {
 965        let worktrees = workspace.read(cx).worktrees(cx).collect::<Vec<_>>();
 966        assert_eq!(
 967            worktrees.len(),
 968            2,
 969            "External file should get opened in a new worktree"
 970        );
 971
 972        WorktreeId::from_usize(
 973            worktrees
 974                .into_iter()
 975                .find(|worktree| worktree.entity_id().as_u64() as usize != worktree_id.to_usize())
 976                .expect("New worktree should have a different id")
 977                .entity_id()
 978                .as_u64() as usize,
 979        )
 980    });
 981    cx.dispatch_action(workspace::CloseActiveItem {
 982        save_intent: None,
 983        close_pinned: false,
 984    });
 985
 986    let initial_history_items =
 987        open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
 988    assert_eq!(
 989        initial_history_items,
 990        vec![FoundPath::new(
 991            ProjectPath {
 992                worktree_id: external_worktree_id,
 993                path: Arc::from(Path::new("")),
 994            },
 995            Some(PathBuf::from(path!("/external-src/test/third.rs")))
 996        )],
 997        "Should show external file with its full path in the history after it was open"
 998    );
 999
1000    let updated_history_items =
1001        open_close_queried_buffer("fir", 1, "first.rs", &workspace, cx).await;
1002    assert_eq!(
1003        updated_history_items,
1004        vec![
1005            FoundPath::new(
1006                ProjectPath {
1007                    worktree_id,
1008                    path: Arc::from(Path::new("test/second.rs")),
1009                },
1010                Some(PathBuf::from(path!("/src/test/second.rs")))
1011            ),
1012            FoundPath::new(
1013                ProjectPath {
1014                    worktree_id: external_worktree_id,
1015                    path: Arc::from(Path::new("")),
1016                },
1017                Some(PathBuf::from(path!("/external-src/test/third.rs")))
1018            ),
1019        ],
1020        "Should keep external file with history updates",
1021    );
1022}
1023
1024#[gpui::test]
1025async fn test_toggle_panel_new_selections(cx: &mut gpui::TestAppContext) {
1026    let app_state = init_test(cx);
1027
1028    app_state
1029        .fs
1030        .as_fake()
1031        .insert_tree(
1032            path!("/src"),
1033            json!({
1034                "test": {
1035                    "first.rs": "// First Rust file",
1036                    "second.rs": "// Second Rust file",
1037                    "third.rs": "// Third Rust file",
1038                }
1039            }),
1040        )
1041        .await;
1042
1043    let project = Project::test(app_state.fs.clone(), [path!("/src").as_ref()], cx).await;
1044    let (workspace, cx) = cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
1045
1046    // generate some history to select from
1047    open_close_queried_buffer("fir", 1, "first.rs", &workspace, cx).await;
1048    open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
1049    open_close_queried_buffer("thi", 1, "third.rs", &workspace, cx).await;
1050    let current_history = open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
1051
1052    for expected_selected_index in 0..current_history.len() {
1053        cx.dispatch_action(ToggleFileFinder::default());
1054        let picker = active_file_picker(&workspace, cx);
1055        let selected_index = picker.update(cx, |picker, _| picker.delegate.selected_index());
1056        assert_eq!(
1057            selected_index, expected_selected_index,
1058            "Should select the next item in the history"
1059        );
1060    }
1061
1062    cx.dispatch_action(ToggleFileFinder::default());
1063    let selected_index = workspace.update(cx, |workspace, cx| {
1064        workspace
1065            .active_modal::<FileFinder>(cx)
1066            .unwrap()
1067            .read(cx)
1068            .picker
1069            .read(cx)
1070            .delegate
1071            .selected_index()
1072    });
1073    assert_eq!(
1074        selected_index, 0,
1075        "Should wrap around the history and start all over"
1076    );
1077}
1078
1079#[gpui::test]
1080async fn test_search_preserves_history_items(cx: &mut gpui::TestAppContext) {
1081    let app_state = init_test(cx);
1082
1083    app_state
1084        .fs
1085        .as_fake()
1086        .insert_tree(
1087            path!("/src"),
1088            json!({
1089                "test": {
1090                    "first.rs": "// First Rust file",
1091                    "second.rs": "// Second Rust file",
1092                    "third.rs": "// Third Rust file",
1093                    "fourth.rs": "// Fourth Rust file",
1094                }
1095            }),
1096        )
1097        .await;
1098
1099    let project = Project::test(app_state.fs.clone(), [path!("/src").as_ref()], cx).await;
1100    let (workspace, cx) = cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
1101    let worktree_id = cx.read(|cx| {
1102        let worktrees = workspace.read(cx).worktrees(cx).collect::<Vec<_>>();
1103        assert_eq!(worktrees.len(), 1,);
1104
1105        WorktreeId::from_usize(worktrees[0].entity_id().as_u64() as usize)
1106    });
1107
1108    // generate some history to select from
1109    open_close_queried_buffer("fir", 1, "first.rs", &workspace, cx).await;
1110    open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
1111    open_close_queried_buffer("thi", 1, "third.rs", &workspace, cx).await;
1112    open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
1113
1114    let finder = open_file_picker(&workspace, cx);
1115    let first_query = "f";
1116    finder
1117        .update_in(cx, |finder, window, cx| {
1118            finder
1119                .delegate
1120                .update_matches(first_query.to_string(), window, cx)
1121        })
1122        .await;
1123    finder.update(cx, |picker, _| {
1124            let matches = collect_search_matches(picker);
1125            assert_eq!(matches.history.len(), 1, "Only one history item contains {first_query}, it should be present and others should be filtered out");
1126            let history_match = matches.history_found_paths.first().expect("Should have path matches for history items after querying");
1127            assert_eq!(history_match, &FoundPath::new(
1128                ProjectPath {
1129                    worktree_id,
1130                    path: Arc::from(Path::new("test/first.rs")),
1131                },
1132                Some(PathBuf::from(path!("/src/test/first.rs")))
1133            ));
1134            assert_eq!(matches.search.len(), 1, "Only one non-history item contains {first_query}, it should be present");
1135            assert_eq!(matches.search.first().unwrap(), Path::new("test/fourth.rs"));
1136        });
1137
1138    let second_query = "fsdasdsa";
1139    let finder = active_file_picker(&workspace, cx);
1140    finder
1141        .update_in(cx, |finder, window, cx| {
1142            finder
1143                .delegate
1144                .update_matches(second_query.to_string(), window, cx)
1145        })
1146        .await;
1147    finder.update(cx, |picker, _| {
1148        assert!(
1149            collect_search_matches(picker)
1150                .search_paths_only()
1151                .is_empty(),
1152            "No search entries should match {second_query}"
1153        );
1154    });
1155
1156    let first_query_again = first_query;
1157
1158    let finder = active_file_picker(&workspace, cx);
1159    finder
1160        .update_in(cx, |finder, window, cx| {
1161            finder
1162                .delegate
1163                .update_matches(first_query_again.to_string(), window, cx)
1164        })
1165        .await;
1166    finder.update(cx, |picker, _| {
1167            let matches = collect_search_matches(picker);
1168            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");
1169            let history_match = matches.history_found_paths.first().expect("Should have path matches for history items after querying");
1170            assert_eq!(history_match, &FoundPath::new(
1171                ProjectPath {
1172                    worktree_id,
1173                    path: Arc::from(Path::new("test/first.rs")),
1174                },
1175                Some(PathBuf::from(path!("/src/test/first.rs")))
1176            ));
1177            assert_eq!(matches.search.len(), 1, "Only one non-history item contains {first_query_again}, it should be present, even after non-matching query");
1178            assert_eq!(matches.search.first().unwrap(), Path::new("test/fourth.rs"));
1179        });
1180}
1181
1182#[gpui::test]
1183async fn test_search_sorts_history_items(cx: &mut gpui::TestAppContext) {
1184    let app_state = init_test(cx);
1185
1186    app_state
1187        .fs
1188        .as_fake()
1189        .insert_tree(
1190            path!("/root"),
1191            json!({
1192                "test": {
1193                    "1_qw": "// First file that matches the query",
1194                    "2_second": "// Second file",
1195                    "3_third": "// Third file",
1196                    "4_fourth": "// Fourth file",
1197                    "5_qwqwqw": "// A file with 3 more matches than the first one",
1198                    "6_qwqwqw": "// Same query matches as above, but closer to the end of the list due to the name",
1199                    "7_qwqwqw": "// One more, same amount of query matches as above",
1200                }
1201            }),
1202        )
1203        .await;
1204
1205    let project = Project::test(app_state.fs.clone(), [path!("/root").as_ref()], cx).await;
1206    let (workspace, cx) = cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
1207    // generate some history to select from
1208    open_close_queried_buffer("1", 1, "1_qw", &workspace, cx).await;
1209    open_close_queried_buffer("2", 1, "2_second", &workspace, cx).await;
1210    open_close_queried_buffer("3", 1, "3_third", &workspace, cx).await;
1211    open_close_queried_buffer("2", 1, "2_second", &workspace, cx).await;
1212    open_close_queried_buffer("6", 1, "6_qwqwqw", &workspace, cx).await;
1213
1214    let finder = open_file_picker(&workspace, cx);
1215    let query = "qw";
1216    finder
1217        .update_in(cx, |finder, window, cx| {
1218            finder
1219                .delegate
1220                .update_matches(query.to_string(), window, cx)
1221        })
1222        .await;
1223    finder.update(cx, |finder, _| {
1224        let search_matches = collect_search_matches(finder);
1225        assert_eq!(
1226            search_matches.history,
1227            vec![PathBuf::from("test/1_qw"), PathBuf::from("test/6_qwqwqw"),],
1228        );
1229        assert_eq!(
1230            search_matches.search,
1231            vec![
1232                PathBuf::from("test/5_qwqwqw"),
1233                PathBuf::from("test/7_qwqwqw"),
1234            ],
1235        );
1236    });
1237}
1238
1239#[gpui::test]
1240async fn test_select_current_open_file_when_no_history(cx: &mut gpui::TestAppContext) {
1241    let app_state = init_test(cx);
1242
1243    app_state
1244        .fs
1245        .as_fake()
1246        .insert_tree(
1247            path!("/root"),
1248            json!({
1249                "test": {
1250                    "1_qw": "",
1251                }
1252            }),
1253        )
1254        .await;
1255
1256    let project = Project::test(app_state.fs.clone(), [path!("/root").as_ref()], cx).await;
1257    let (workspace, cx) = cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
1258    // Open new buffer
1259    open_queried_buffer("1", 1, "1_qw", &workspace, cx).await;
1260
1261    let picker = open_file_picker(&workspace, cx);
1262    picker.update(cx, |finder, _| {
1263        assert_match_selection(&finder, 0, "1_qw");
1264    });
1265}
1266
1267#[gpui::test]
1268async fn test_keep_opened_file_on_top_of_search_results_and_select_next_one(
1269    cx: &mut TestAppContext,
1270) {
1271    let app_state = init_test(cx);
1272
1273    app_state
1274        .fs
1275        .as_fake()
1276        .insert_tree(
1277            path!("/src"),
1278            json!({
1279                "test": {
1280                    "bar.rs": "// Bar file",
1281                    "lib.rs": "// Lib file",
1282                    "maaa.rs": "// Maaaaaaa",
1283                    "main.rs": "// Main file",
1284                    "moo.rs": "// Moooooo",
1285                }
1286            }),
1287        )
1288        .await;
1289
1290    let project = Project::test(app_state.fs.clone(), [path!("/src").as_ref()], cx).await;
1291    let (workspace, cx) = cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
1292
1293    open_close_queried_buffer("bar", 1, "bar.rs", &workspace, cx).await;
1294    open_close_queried_buffer("lib", 1, "lib.rs", &workspace, cx).await;
1295    open_queried_buffer("main", 1, "main.rs", &workspace, cx).await;
1296
1297    // main.rs is on top, previously used is selected
1298    let picker = open_file_picker(&workspace, cx);
1299    picker.update(cx, |finder, _| {
1300        assert_eq!(finder.delegate.matches.len(), 3);
1301        assert_match_selection(finder, 0, "main.rs");
1302        assert_match_at_position(finder, 1, "lib.rs");
1303        assert_match_at_position(finder, 2, "bar.rs");
1304    });
1305
1306    // all files match, main.rs is still on top, but the second item is selected
1307    picker
1308        .update_in(cx, |finder, window, cx| {
1309            finder
1310                .delegate
1311                .update_matches(".rs".to_string(), window, cx)
1312        })
1313        .await;
1314    picker.update(cx, |finder, _| {
1315        assert_eq!(finder.delegate.matches.len(), 5);
1316        assert_match_at_position(finder, 0, "main.rs");
1317        assert_match_selection(finder, 1, "bar.rs");
1318        assert_match_at_position(finder, 2, "lib.rs");
1319        assert_match_at_position(finder, 3, "moo.rs");
1320        assert_match_at_position(finder, 4, "maaa.rs");
1321    });
1322
1323    // main.rs is not among matches, select top item
1324    picker
1325        .update_in(cx, |finder, window, cx| {
1326            finder.delegate.update_matches("b".to_string(), window, cx)
1327        })
1328        .await;
1329    picker.update(cx, |finder, _| {
1330        assert_eq!(finder.delegate.matches.len(), 2);
1331        assert_match_at_position(finder, 0, "bar.rs");
1332        assert_match_at_position(finder, 1, "lib.rs");
1333    });
1334
1335    // main.rs is back, put it on top and select next item
1336    picker
1337        .update_in(cx, |finder, window, cx| {
1338            finder.delegate.update_matches("m".to_string(), window, cx)
1339        })
1340        .await;
1341    picker.update(cx, |finder, _| {
1342        assert_eq!(finder.delegate.matches.len(), 3);
1343        assert_match_at_position(finder, 0, "main.rs");
1344        assert_match_selection(finder, 1, "moo.rs");
1345        assert_match_at_position(finder, 2, "maaa.rs");
1346    });
1347
1348    // get back to the initial state
1349    picker
1350        .update_in(cx, |finder, window, cx| {
1351            finder.delegate.update_matches("".to_string(), window, cx)
1352        })
1353        .await;
1354    picker.update(cx, |finder, _| {
1355        assert_eq!(finder.delegate.matches.len(), 3);
1356        assert_match_selection(finder, 0, "main.rs");
1357        assert_match_at_position(finder, 1, "lib.rs");
1358        assert_match_at_position(finder, 2, "bar.rs");
1359    });
1360}
1361
1362#[gpui::test]
1363async fn test_non_separate_history_items(cx: &mut TestAppContext) {
1364    let app_state = init_test(cx);
1365
1366    app_state
1367        .fs
1368        .as_fake()
1369        .insert_tree(
1370            path!("/src"),
1371            json!({
1372                "test": {
1373                    "bar.rs": "// Bar file",
1374                    "lib.rs": "// Lib file",
1375                    "maaa.rs": "// Maaaaaaa",
1376                    "main.rs": "// Main file",
1377                    "moo.rs": "// Moooooo",
1378                }
1379            }),
1380        )
1381        .await;
1382
1383    let project = Project::test(app_state.fs.clone(), [path!("/src").as_ref()], cx).await;
1384    let (workspace, cx) = cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
1385
1386    open_close_queried_buffer("bar", 1, "bar.rs", &workspace, cx).await;
1387    open_close_queried_buffer("lib", 1, "lib.rs", &workspace, cx).await;
1388    open_queried_buffer("main", 1, "main.rs", &workspace, cx).await;
1389
1390    cx.dispatch_action(ToggleFileFinder::default());
1391    let picker = active_file_picker(&workspace, cx);
1392    // main.rs is on top, previously used is selected
1393    picker.update(cx, |finder, _| {
1394        assert_eq!(finder.delegate.matches.len(), 3);
1395        assert_match_selection(finder, 0, "main.rs");
1396        assert_match_at_position(finder, 1, "lib.rs");
1397        assert_match_at_position(finder, 2, "bar.rs");
1398    });
1399
1400    // all files match, main.rs is still on top, but the second item is selected
1401    picker
1402        .update_in(cx, |finder, window, cx| {
1403            finder
1404                .delegate
1405                .update_matches(".rs".to_string(), window, cx)
1406        })
1407        .await;
1408    picker.update(cx, |finder, _| {
1409        assert_eq!(finder.delegate.matches.len(), 5);
1410        assert_match_at_position(finder, 0, "main.rs");
1411        assert_match_selection(finder, 1, "moo.rs");
1412        assert_match_at_position(finder, 2, "bar.rs");
1413        assert_match_at_position(finder, 3, "lib.rs");
1414        assert_match_at_position(finder, 4, "maaa.rs");
1415    });
1416
1417    // main.rs is not among matches, select top item
1418    picker
1419        .update_in(cx, |finder, window, cx| {
1420            finder.delegate.update_matches("b".to_string(), window, cx)
1421        })
1422        .await;
1423    picker.update(cx, |finder, _| {
1424        assert_eq!(finder.delegate.matches.len(), 2);
1425        assert_match_at_position(finder, 0, "bar.rs");
1426        assert_match_at_position(finder, 1, "lib.rs");
1427    });
1428
1429    // main.rs is back, put it on top and select next item
1430    picker
1431        .update_in(cx, |finder, window, cx| {
1432            finder.delegate.update_matches("m".to_string(), window, cx)
1433        })
1434        .await;
1435    picker.update(cx, |finder, _| {
1436        assert_eq!(finder.delegate.matches.len(), 3);
1437        assert_match_at_position(finder, 0, "main.rs");
1438        assert_match_selection(finder, 1, "moo.rs");
1439        assert_match_at_position(finder, 2, "maaa.rs");
1440    });
1441
1442    // get back to the initial state
1443    picker
1444        .update_in(cx, |finder, window, cx| {
1445            finder.delegate.update_matches("".to_string(), window, cx)
1446        })
1447        .await;
1448    picker.update(cx, |finder, _| {
1449        assert_eq!(finder.delegate.matches.len(), 3);
1450        assert_match_selection(finder, 0, "main.rs");
1451        assert_match_at_position(finder, 1, "lib.rs");
1452        assert_match_at_position(finder, 2, "bar.rs");
1453    });
1454}
1455
1456#[gpui::test]
1457async fn test_history_items_shown_in_order_of_open(cx: &mut TestAppContext) {
1458    let app_state = init_test(cx);
1459
1460    app_state
1461        .fs
1462        .as_fake()
1463        .insert_tree(
1464            path!("/test"),
1465            json!({
1466                "test": {
1467                    "1.txt": "// One",
1468                    "2.txt": "// Two",
1469                    "3.txt": "// Three",
1470                }
1471            }),
1472        )
1473        .await;
1474
1475    let project = Project::test(app_state.fs.clone(), [path!("/test").as_ref()], cx).await;
1476    let (workspace, cx) = cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
1477
1478    open_queried_buffer("1", 1, "1.txt", &workspace, cx).await;
1479    open_queried_buffer("2", 1, "2.txt", &workspace, cx).await;
1480    open_queried_buffer("3", 1, "3.txt", &workspace, cx).await;
1481
1482    let picker = open_file_picker(&workspace, cx);
1483    picker.update(cx, |finder, _| {
1484        assert_eq!(finder.delegate.matches.len(), 3);
1485        assert_match_selection(finder, 0, "3.txt");
1486        assert_match_at_position(finder, 1, "2.txt");
1487        assert_match_at_position(finder, 2, "1.txt");
1488    });
1489
1490    cx.dispatch_action(SelectNext);
1491    cx.dispatch_action(Confirm); // Open 2.txt
1492
1493    let picker = open_file_picker(&workspace, cx);
1494    picker.update(cx, |finder, _| {
1495        assert_eq!(finder.delegate.matches.len(), 3);
1496        assert_match_selection(finder, 0, "2.txt");
1497        assert_match_at_position(finder, 1, "3.txt");
1498        assert_match_at_position(finder, 2, "1.txt");
1499    });
1500
1501    cx.dispatch_action(SelectNext);
1502    cx.dispatch_action(SelectNext);
1503    cx.dispatch_action(Confirm); // Open 1.txt
1504
1505    let picker = open_file_picker(&workspace, cx);
1506    picker.update(cx, |finder, _| {
1507        assert_eq!(finder.delegate.matches.len(), 3);
1508        assert_match_selection(finder, 0, "1.txt");
1509        assert_match_at_position(finder, 1, "2.txt");
1510        assert_match_at_position(finder, 2, "3.txt");
1511    });
1512}
1513
1514#[gpui::test]
1515async fn test_selected_history_item_stays_selected_on_worktree_updated(cx: &mut TestAppContext) {
1516    let app_state = init_test(cx);
1517
1518    app_state
1519        .fs
1520        .as_fake()
1521        .insert_tree(
1522            path!("/test"),
1523            json!({
1524                "test": {
1525                    "1.txt": "// One",
1526                    "2.txt": "// Two",
1527                    "3.txt": "// Three",
1528                }
1529            }),
1530        )
1531        .await;
1532
1533    let project = Project::test(app_state.fs.clone(), [path!("/test").as_ref()], cx).await;
1534    let (workspace, cx) = cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
1535
1536    open_close_queried_buffer("1", 1, "1.txt", &workspace, cx).await;
1537    open_close_queried_buffer("2", 1, "2.txt", &workspace, cx).await;
1538    open_close_queried_buffer("3", 1, "3.txt", &workspace, cx).await;
1539
1540    let picker = open_file_picker(&workspace, cx);
1541    picker.update(cx, |finder, _| {
1542        assert_eq!(finder.delegate.matches.len(), 3);
1543        assert_match_selection(finder, 0, "3.txt");
1544        assert_match_at_position(finder, 1, "2.txt");
1545        assert_match_at_position(finder, 2, "1.txt");
1546    });
1547
1548    cx.dispatch_action(SelectNext);
1549
1550    // Add more files to the worktree to trigger update matches
1551    for i in 0..5 {
1552        let filename = if cfg!(windows) {
1553            format!("C:/test/{}.txt", 4 + i)
1554        } else {
1555            format!("/test/{}.txt", 4 + i)
1556        };
1557        app_state
1558            .fs
1559            .create_file(Path::new(&filename), Default::default())
1560            .await
1561            .expect("unable to create file");
1562    }
1563
1564    cx.executor().advance_clock(FS_WATCH_LATENCY);
1565
1566    picker.update(cx, |finder, _| {
1567        assert_eq!(finder.delegate.matches.len(), 3);
1568        assert_match_at_position(finder, 0, "3.txt");
1569        assert_match_selection(finder, 1, "2.txt");
1570        assert_match_at_position(finder, 2, "1.txt");
1571    });
1572}
1573
1574#[gpui::test]
1575async fn test_history_items_vs_very_good_external_match(cx: &mut gpui::TestAppContext) {
1576    let app_state = init_test(cx);
1577
1578    app_state
1579        .fs
1580        .as_fake()
1581        .insert_tree(
1582            path!("/src"),
1583            json!({
1584                "collab_ui": {
1585                    "first.rs": "// First Rust file",
1586                    "second.rs": "// Second Rust file",
1587                    "third.rs": "// Third Rust file",
1588                    "collab_ui.rs": "// Fourth Rust file",
1589                }
1590            }),
1591        )
1592        .await;
1593
1594    let project = Project::test(app_state.fs.clone(), [path!("/src").as_ref()], cx).await;
1595    let (workspace, cx) = cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
1596    // generate some history to select from
1597    open_close_queried_buffer("fir", 1, "first.rs", &workspace, cx).await;
1598    open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
1599    open_close_queried_buffer("thi", 1, "third.rs", &workspace, cx).await;
1600    open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
1601
1602    let finder = open_file_picker(&workspace, cx);
1603    let query = "collab_ui";
1604    cx.simulate_input(query);
1605    finder.update(cx, |picker, _| {
1606            let search_entries = collect_search_matches(picker).search_paths_only();
1607            assert_eq!(
1608                search_entries,
1609                vec![
1610                    PathBuf::from("collab_ui/collab_ui.rs"),
1611                    PathBuf::from("collab_ui/first.rs"),
1612                    PathBuf::from("collab_ui/third.rs"),
1613                    PathBuf::from("collab_ui/second.rs"),
1614                ],
1615                "Despite all search results having the same directory name, the most matching one should be on top"
1616            );
1617        });
1618}
1619
1620#[gpui::test]
1621async fn test_nonexistent_history_items_not_shown(cx: &mut gpui::TestAppContext) {
1622    let app_state = init_test(cx);
1623
1624    app_state
1625        .fs
1626        .as_fake()
1627        .insert_tree(
1628            path!("/src"),
1629            json!({
1630                "test": {
1631                    "first.rs": "// First Rust file",
1632                    "nonexistent.rs": "// Second Rust file",
1633                    "third.rs": "// Third Rust file",
1634                }
1635            }),
1636        )
1637        .await;
1638
1639    let project = Project::test(app_state.fs.clone(), [path!("/src").as_ref()], cx).await;
1640    let (workspace, cx) = cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx)); // generate some history to select from
1641    open_close_queried_buffer("fir", 1, "first.rs", &workspace, cx).await;
1642    open_close_queried_buffer("non", 1, "nonexistent.rs", &workspace, cx).await;
1643    open_close_queried_buffer("thi", 1, "third.rs", &workspace, cx).await;
1644    open_close_queried_buffer("fir", 1, "first.rs", &workspace, cx).await;
1645    app_state
1646        .fs
1647        .remove_file(
1648            Path::new(path!("/src/test/nonexistent.rs")),
1649            RemoveOptions::default(),
1650        )
1651        .await
1652        .unwrap();
1653    cx.run_until_parked();
1654
1655    let picker = open_file_picker(&workspace, cx);
1656    cx.simulate_input("rs");
1657
1658    picker.update(cx, |picker, _| {
1659        assert_eq!(
1660            collect_search_matches(picker).history,
1661            vec![
1662                PathBuf::from("test/first.rs"),
1663                PathBuf::from("test/third.rs"),
1664            ],
1665            "Should have all opened files in the history, except the ones that do not exist on disk"
1666        );
1667    });
1668}
1669
1670#[gpui::test]
1671async fn test_search_results_refreshed_on_worktree_updates(cx: &mut gpui::TestAppContext) {
1672    let app_state = init_test(cx);
1673
1674    app_state
1675        .fs
1676        .as_fake()
1677        .insert_tree(
1678            "/src",
1679            json!({
1680                "lib.rs": "// Lib file",
1681                "main.rs": "// Bar file",
1682                "read.me": "// Readme file",
1683            }),
1684        )
1685        .await;
1686
1687    let project = Project::test(app_state.fs.clone(), ["/src".as_ref()], cx).await;
1688    let (workspace, cx) =
1689        cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1690
1691    // Initial state
1692    let picker = open_file_picker(&workspace, cx);
1693    cx.simulate_input("rs");
1694    picker.update(cx, |finder, _| {
1695        assert_eq!(finder.delegate.matches.len(), 2);
1696        assert_match_at_position(finder, 0, "lib.rs");
1697        assert_match_at_position(finder, 1, "main.rs");
1698    });
1699
1700    // Delete main.rs
1701    app_state
1702        .fs
1703        .remove_file("/src/main.rs".as_ref(), Default::default())
1704        .await
1705        .expect("unable to remove file");
1706    cx.executor().advance_clock(FS_WATCH_LATENCY);
1707
1708    // main.rs is in not among search results anymore
1709    picker.update(cx, |finder, _| {
1710        assert_eq!(finder.delegate.matches.len(), 1);
1711        assert_match_at_position(finder, 0, "lib.rs");
1712    });
1713
1714    // Create util.rs
1715    app_state
1716        .fs
1717        .create_file("/src/util.rs".as_ref(), Default::default())
1718        .await
1719        .expect("unable to create file");
1720    cx.executor().advance_clock(FS_WATCH_LATENCY);
1721
1722    // util.rs is among search results
1723    picker.update(cx, |finder, _| {
1724        assert_eq!(finder.delegate.matches.len(), 2);
1725        assert_match_at_position(finder, 0, "lib.rs");
1726        assert_match_at_position(finder, 1, "util.rs");
1727    });
1728}
1729
1730#[gpui::test]
1731async fn test_search_results_refreshed_on_adding_and_removing_worktrees(
1732    cx: &mut gpui::TestAppContext,
1733) {
1734    let app_state = init_test(cx);
1735
1736    app_state
1737        .fs
1738        .as_fake()
1739        .insert_tree(
1740            "/test",
1741            json!({
1742                "project_1": {
1743                    "bar.rs": "// Bar file",
1744                    "lib.rs": "// Lib file",
1745                },
1746                "project_2": {
1747                    "Cargo.toml": "// Cargo file",
1748                    "main.rs": "// Main file",
1749                }
1750            }),
1751        )
1752        .await;
1753
1754    let project = Project::test(app_state.fs.clone(), ["/test/project_1".as_ref()], cx).await;
1755    let (workspace, cx) =
1756        cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1757    let worktree_1_id = project.update(cx, |project, cx| {
1758        let worktree = project.worktrees(cx).last().expect("worktree not found");
1759        worktree.read(cx).id()
1760    });
1761
1762    // Initial state
1763    let picker = open_file_picker(&workspace, cx);
1764    cx.simulate_input("rs");
1765    picker.update(cx, |finder, _| {
1766        assert_eq!(finder.delegate.matches.len(), 2);
1767        assert_match_at_position(finder, 0, "bar.rs");
1768        assert_match_at_position(finder, 1, "lib.rs");
1769    });
1770
1771    // Add new worktree
1772    project
1773        .update(cx, |project, cx| {
1774            project
1775                .find_or_create_worktree("/test/project_2", true, cx)
1776                .into_future()
1777        })
1778        .await
1779        .expect("unable to create workdir");
1780    cx.executor().advance_clock(FS_WATCH_LATENCY);
1781
1782    // main.rs is among search results
1783    picker.update(cx, |finder, _| {
1784        assert_eq!(finder.delegate.matches.len(), 3);
1785        assert_match_at_position(finder, 0, "bar.rs");
1786        assert_match_at_position(finder, 1, "lib.rs");
1787        assert_match_at_position(finder, 2, "main.rs");
1788    });
1789
1790    // Remove the first worktree
1791    project.update(cx, |project, cx| {
1792        project.remove_worktree(worktree_1_id, cx);
1793    });
1794    cx.executor().advance_clock(FS_WATCH_LATENCY);
1795
1796    // Files from the first worktree are not in the search results anymore
1797    picker.update(cx, |finder, _| {
1798        assert_eq!(finder.delegate.matches.len(), 1);
1799        assert_match_at_position(finder, 0, "main.rs");
1800    });
1801}
1802
1803#[gpui::test]
1804async fn test_selected_match_stays_selected_after_matches_refreshed(cx: &mut gpui::TestAppContext) {
1805    let app_state = init_test(cx);
1806
1807    app_state.fs.as_fake().insert_tree("/src", json!({})).await;
1808
1809    app_state
1810        .fs
1811        .create_dir("/src/even".as_ref())
1812        .await
1813        .expect("unable to create dir");
1814
1815    let initial_files_num = 5;
1816    for i in 0..initial_files_num {
1817        let filename = format!("/src/even/file_{}.txt", 10 + i);
1818        app_state
1819            .fs
1820            .create_file(Path::new(&filename), Default::default())
1821            .await
1822            .expect("unable to create file");
1823    }
1824
1825    let project = Project::test(app_state.fs.clone(), ["/src".as_ref()], cx).await;
1826    let (workspace, cx) =
1827        cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1828
1829    // Initial state
1830    let picker = open_file_picker(&workspace, cx);
1831    cx.simulate_input("file");
1832    let selected_index = 3;
1833    // Checking only the filename, not the whole path
1834    let selected_file = format!("file_{}.txt", 10 + selected_index);
1835    // Select even/file_13.txt
1836    for _ in 0..selected_index {
1837        cx.dispatch_action(SelectNext);
1838    }
1839
1840    picker.update(cx, |finder, _| {
1841        assert_match_selection(finder, selected_index, &selected_file)
1842    });
1843
1844    // Add more matches to the search results
1845    let files_to_add = 10;
1846    for i in 0..files_to_add {
1847        let filename = format!("/src/file_{}.txt", 20 + i);
1848        app_state
1849            .fs
1850            .create_file(Path::new(&filename), Default::default())
1851            .await
1852            .expect("unable to create file");
1853    }
1854    cx.executor().advance_clock(FS_WATCH_LATENCY);
1855
1856    // file_13.txt is still selected
1857    picker.update(cx, |finder, _| {
1858        let expected_selected_index = selected_index + files_to_add;
1859        assert_match_selection(finder, expected_selected_index, &selected_file);
1860    });
1861}
1862
1863#[gpui::test]
1864async fn test_first_match_selected_if_previous_one_is_not_in_the_match_list(
1865    cx: &mut gpui::TestAppContext,
1866) {
1867    let app_state = init_test(cx);
1868
1869    app_state
1870        .fs
1871        .as_fake()
1872        .insert_tree(
1873            "/src",
1874            json!({
1875                "file_1.txt": "// file_1",
1876                "file_2.txt": "// file_2",
1877                "file_3.txt": "// file_3",
1878            }),
1879        )
1880        .await;
1881
1882    let project = Project::test(app_state.fs.clone(), ["/src".as_ref()], cx).await;
1883    let (workspace, cx) =
1884        cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1885
1886    // Initial state
1887    let picker = open_file_picker(&workspace, cx);
1888    cx.simulate_input("file");
1889    // Select even/file_2.txt
1890    cx.dispatch_action(SelectNext);
1891
1892    // Remove the selected entry
1893    app_state
1894        .fs
1895        .remove_file("/src/file_2.txt".as_ref(), Default::default())
1896        .await
1897        .expect("unable to remove file");
1898    cx.executor().advance_clock(FS_WATCH_LATENCY);
1899
1900    // file_1.txt is now selected
1901    picker.update(cx, |finder, _| {
1902        assert_match_selection(finder, 0, "file_1.txt");
1903    });
1904}
1905
1906#[gpui::test]
1907async fn test_keeps_file_finder_open_after_modifier_keys_release(cx: &mut gpui::TestAppContext) {
1908    let app_state = init_test(cx);
1909
1910    app_state
1911        .fs
1912        .as_fake()
1913        .insert_tree(
1914            path!("/test"),
1915            json!({
1916                "1.txt": "// One",
1917            }),
1918        )
1919        .await;
1920
1921    let project = Project::test(app_state.fs.clone(), [path!("/test").as_ref()], cx).await;
1922    let (workspace, cx) = cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
1923
1924    open_queried_buffer("1", 1, "1.txt", &workspace, cx).await;
1925
1926    cx.simulate_modifiers_change(Modifiers::secondary_key());
1927    open_file_picker(&workspace, cx);
1928
1929    cx.simulate_modifiers_change(Modifiers::none());
1930    active_file_picker(&workspace, cx);
1931}
1932
1933#[gpui::test]
1934async fn test_opens_file_on_modifier_keys_release(cx: &mut gpui::TestAppContext) {
1935    let app_state = init_test(cx);
1936
1937    app_state
1938        .fs
1939        .as_fake()
1940        .insert_tree(
1941            path!("/test"),
1942            json!({
1943                "1.txt": "// One",
1944                "2.txt": "// Two",
1945            }),
1946        )
1947        .await;
1948
1949    let project = Project::test(app_state.fs.clone(), [path!("/test").as_ref()], cx).await;
1950    let (workspace, cx) = cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
1951
1952    open_queried_buffer("1", 1, "1.txt", &workspace, cx).await;
1953    open_queried_buffer("2", 1, "2.txt", &workspace, cx).await;
1954
1955    cx.simulate_modifiers_change(Modifiers::secondary_key());
1956    let picker = open_file_picker(&workspace, cx);
1957    picker.update(cx, |finder, _| {
1958        assert_eq!(finder.delegate.matches.len(), 2);
1959        assert_match_selection(finder, 0, "2.txt");
1960        assert_match_at_position(finder, 1, "1.txt");
1961    });
1962
1963    cx.dispatch_action(SelectNext);
1964    cx.simulate_modifiers_change(Modifiers::none());
1965    cx.read(|cx| {
1966        let active_editor = workspace.read(cx).active_item_as::<Editor>(cx).unwrap();
1967        assert_eq!(active_editor.read(cx).title(cx), "1.txt");
1968    });
1969}
1970
1971#[gpui::test]
1972async fn test_switches_between_release_norelease_modes_on_forward_nav(
1973    cx: &mut gpui::TestAppContext,
1974) {
1975    let app_state = init_test(cx);
1976
1977    app_state
1978        .fs
1979        .as_fake()
1980        .insert_tree(
1981            path!("/test"),
1982            json!({
1983                "1.txt": "// One",
1984                "2.txt": "// Two",
1985            }),
1986        )
1987        .await;
1988
1989    let project = Project::test(app_state.fs.clone(), [path!("/test").as_ref()], cx).await;
1990    let (workspace, cx) = cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
1991
1992    open_queried_buffer("1", 1, "1.txt", &workspace, cx).await;
1993    open_queried_buffer("2", 1, "2.txt", &workspace, cx).await;
1994
1995    // Open with a shortcut
1996    cx.simulate_modifiers_change(Modifiers::secondary_key());
1997    let picker = open_file_picker(&workspace, cx);
1998    picker.update(cx, |finder, _| {
1999        assert_eq!(finder.delegate.matches.len(), 2);
2000        assert_match_selection(finder, 0, "2.txt");
2001        assert_match_at_position(finder, 1, "1.txt");
2002    });
2003
2004    // Switch to navigating with other shortcuts
2005    // Don't open file on modifiers release
2006    cx.simulate_modifiers_change(Modifiers::control());
2007    cx.dispatch_action(SelectNext);
2008    cx.simulate_modifiers_change(Modifiers::none());
2009    picker.update(cx, |finder, _| {
2010        assert_eq!(finder.delegate.matches.len(), 2);
2011        assert_match_at_position(finder, 0, "2.txt");
2012        assert_match_selection(finder, 1, "1.txt");
2013    });
2014
2015    // Back to navigation with initial shortcut
2016    // Open file on modifiers release
2017    cx.simulate_modifiers_change(Modifiers::secondary_key());
2018    cx.dispatch_action(ToggleFileFinder::default());
2019    cx.simulate_modifiers_change(Modifiers::none());
2020    cx.read(|cx| {
2021        let active_editor = workspace.read(cx).active_item_as::<Editor>(cx).unwrap();
2022        assert_eq!(active_editor.read(cx).title(cx), "2.txt");
2023    });
2024}
2025
2026#[gpui::test]
2027async fn test_switches_between_release_norelease_modes_on_backward_nav(
2028    cx: &mut gpui::TestAppContext,
2029) {
2030    let app_state = init_test(cx);
2031
2032    app_state
2033        .fs
2034        .as_fake()
2035        .insert_tree(
2036            path!("/test"),
2037            json!({
2038                "1.txt": "// One",
2039                "2.txt": "// Two",
2040                "3.txt": "// Three"
2041            }),
2042        )
2043        .await;
2044
2045    let project = Project::test(app_state.fs.clone(), [path!("/test").as_ref()], cx).await;
2046    let (workspace, cx) = cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
2047
2048    open_queried_buffer("1", 1, "1.txt", &workspace, cx).await;
2049    open_queried_buffer("2", 1, "2.txt", &workspace, cx).await;
2050    open_queried_buffer("3", 1, "3.txt", &workspace, cx).await;
2051
2052    // Open with a shortcut
2053    cx.simulate_modifiers_change(Modifiers::secondary_key());
2054    let picker = open_file_picker(&workspace, cx);
2055    picker.update(cx, |finder, _| {
2056        assert_eq!(finder.delegate.matches.len(), 3);
2057        assert_match_selection(finder, 0, "3.txt");
2058        assert_match_at_position(finder, 1, "2.txt");
2059        assert_match_at_position(finder, 2, "1.txt");
2060    });
2061
2062    // Switch to navigating with other shortcuts
2063    // Don't open file on modifiers release
2064    cx.simulate_modifiers_change(Modifiers::control());
2065    cx.dispatch_action(menu::SelectPrevious);
2066    cx.simulate_modifiers_change(Modifiers::none());
2067    picker.update(cx, |finder, _| {
2068        assert_eq!(finder.delegate.matches.len(), 3);
2069        assert_match_at_position(finder, 0, "3.txt");
2070        assert_match_at_position(finder, 1, "2.txt");
2071        assert_match_selection(finder, 2, "1.txt");
2072    });
2073
2074    // Back to navigation with initial shortcut
2075    // Open file on modifiers release
2076    cx.simulate_modifiers_change(Modifiers::secondary_key());
2077    cx.dispatch_action(SelectPrevious); // <-- File Finder's SelectPrevious, not menu's
2078    cx.simulate_modifiers_change(Modifiers::none());
2079    cx.read(|cx| {
2080        let active_editor = workspace.read(cx).active_item_as::<Editor>(cx).unwrap();
2081        assert_eq!(active_editor.read(cx).title(cx), "3.txt");
2082    });
2083}
2084
2085#[gpui::test]
2086async fn test_extending_modifiers_does_not_confirm_selection(cx: &mut gpui::TestAppContext) {
2087    let app_state = init_test(cx);
2088
2089    app_state
2090        .fs
2091        .as_fake()
2092        .insert_tree(
2093            path!("/test"),
2094            json!({
2095                "1.txt": "// One",
2096            }),
2097        )
2098        .await;
2099
2100    let project = Project::test(app_state.fs.clone(), [path!("/test").as_ref()], cx).await;
2101    let (workspace, cx) = cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
2102
2103    open_queried_buffer("1", 1, "1.txt", &workspace, cx).await;
2104
2105    cx.simulate_modifiers_change(Modifiers::secondary_key());
2106    open_file_picker(&workspace, cx);
2107
2108    cx.simulate_modifiers_change(Modifiers::command_shift());
2109    active_file_picker(&workspace, cx);
2110}
2111
2112#[gpui::test]
2113async fn test_repeat_toggle_action(cx: &mut gpui::TestAppContext) {
2114    let app_state = init_test(cx);
2115    app_state
2116        .fs
2117        .as_fake()
2118        .insert_tree(
2119            "/test",
2120            json!({
2121                "00.txt": "",
2122                "01.txt": "",
2123                "02.txt": "",
2124                "03.txt": "",
2125                "04.txt": "",
2126                "05.txt": "",
2127            }),
2128        )
2129        .await;
2130
2131    let project = Project::test(app_state.fs.clone(), ["/test".as_ref()], cx).await;
2132    let (workspace, cx) = cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
2133
2134    cx.dispatch_action(ToggleFileFinder::default());
2135    let picker = active_file_picker(&workspace, cx);
2136
2137    picker.update_in(cx, |picker, window, cx| {
2138        picker.update_matches(".txt".to_string(), window, cx)
2139    });
2140
2141    cx.run_until_parked();
2142
2143    picker.update(cx, |picker, _| {
2144        assert_eq!(picker.delegate.matches.len(), 6);
2145        assert_eq!(picker.delegate.selected_index, 0);
2146    });
2147
2148    // When toggling repeatedly, the picker scrolls to reveal the selected item.
2149    cx.dispatch_action(ToggleFileFinder::default());
2150    cx.dispatch_action(ToggleFileFinder::default());
2151    cx.dispatch_action(ToggleFileFinder::default());
2152
2153    cx.run_until_parked();
2154
2155    picker.update(cx, |picker, _| {
2156        assert_eq!(picker.delegate.matches.len(), 6);
2157        assert_eq!(picker.delegate.selected_index, 3);
2158    });
2159}
2160
2161async fn open_close_queried_buffer(
2162    input: &str,
2163    expected_matches: usize,
2164    expected_editor_title: &str,
2165    workspace: &Entity<Workspace>,
2166    cx: &mut gpui::VisualTestContext,
2167) -> Vec<FoundPath> {
2168    let history_items = open_queried_buffer(
2169        input,
2170        expected_matches,
2171        expected_editor_title,
2172        workspace,
2173        cx,
2174    )
2175    .await;
2176
2177    cx.dispatch_action(workspace::CloseActiveItem {
2178        save_intent: None,
2179        close_pinned: false,
2180    });
2181
2182    history_items
2183}
2184
2185async fn open_queried_buffer(
2186    input: &str,
2187    expected_matches: usize,
2188    expected_editor_title: &str,
2189    workspace: &Entity<Workspace>,
2190    cx: &mut gpui::VisualTestContext,
2191) -> Vec<FoundPath> {
2192    let picker = open_file_picker(&workspace, cx);
2193    cx.simulate_input(input);
2194
2195    let history_items = picker.update(cx, |finder, _| {
2196        assert_eq!(
2197            finder.delegate.matches.len(),
2198            expected_matches,
2199            "Unexpected number of matches found for query `{input}`, matches: {:?}",
2200            finder.delegate.matches
2201        );
2202        finder.delegate.history_items.clone()
2203    });
2204
2205    cx.dispatch_action(Confirm);
2206
2207    cx.read(|cx| {
2208        let active_editor = workspace.read(cx).active_item_as::<Editor>(cx).unwrap();
2209        let active_editor_title = active_editor.read(cx).title(cx);
2210        assert_eq!(
2211            expected_editor_title, active_editor_title,
2212            "Unexpected editor title for query `{input}`"
2213        );
2214    });
2215
2216    history_items
2217}
2218
2219fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
2220    cx.update(|cx| {
2221        let state = AppState::test(cx);
2222        theme::init(theme::LoadThemes::JustBase, cx);
2223        language::init(cx);
2224        super::init(cx);
2225        editor::init(cx);
2226        workspace::init_settings(cx);
2227        Project::init_settings(cx);
2228        state
2229    })
2230}
2231
2232fn test_path_position(test_str: &str) -> FileSearchQuery {
2233    let path_position = PathWithPosition::parse_str(test_str);
2234
2235    FileSearchQuery {
2236        raw_query: test_str.to_owned(),
2237        file_query_end: if path_position.path.to_str().unwrap() == test_str {
2238            None
2239        } else {
2240            Some(path_position.path.to_str().unwrap().len())
2241        },
2242        path_position,
2243    }
2244}
2245
2246fn build_find_picker(
2247    project: Entity<Project>,
2248    cx: &mut TestAppContext,
2249) -> (
2250    Entity<Picker<FileFinderDelegate>>,
2251    Entity<Workspace>,
2252    &mut VisualTestContext,
2253) {
2254    let (workspace, cx) = cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
2255    let picker = open_file_picker(&workspace, cx);
2256    (picker, workspace, cx)
2257}
2258
2259#[track_caller]
2260fn open_file_picker(
2261    workspace: &Entity<Workspace>,
2262    cx: &mut VisualTestContext,
2263) -> Entity<Picker<FileFinderDelegate>> {
2264    cx.dispatch_action(ToggleFileFinder {
2265        separate_history: true,
2266    });
2267    active_file_picker(workspace, cx)
2268}
2269
2270#[track_caller]
2271fn active_file_picker(
2272    workspace: &Entity<Workspace>,
2273    cx: &mut VisualTestContext,
2274) -> Entity<Picker<FileFinderDelegate>> {
2275    workspace.update(cx, |workspace, cx| {
2276        workspace
2277            .active_modal::<FileFinder>(cx)
2278            .expect("file finder is not open")
2279            .read(cx)
2280            .picker
2281            .clone()
2282    })
2283}
2284
2285#[derive(Debug, Default)]
2286struct SearchEntries {
2287    history: Vec<PathBuf>,
2288    history_found_paths: Vec<FoundPath>,
2289    search: Vec<PathBuf>,
2290    search_matches: Vec<PathMatch>,
2291}
2292
2293impl SearchEntries {
2294    #[track_caller]
2295    fn search_paths_only(self) -> Vec<PathBuf> {
2296        assert!(
2297            self.history.is_empty(),
2298            "Should have no history matches, but got: {:?}",
2299            self.history
2300        );
2301        self.search
2302    }
2303
2304    #[track_caller]
2305    fn search_matches_only(self) -> Vec<PathMatch> {
2306        assert!(
2307            self.history.is_empty(),
2308            "Should have no history matches, but got: {:?}",
2309            self.history
2310        );
2311        self.search_matches
2312    }
2313}
2314
2315fn collect_search_matches(picker: &Picker<FileFinderDelegate>) -> SearchEntries {
2316    let mut search_entries = SearchEntries::default();
2317    for m in &picker.delegate.matches.matches {
2318        match &m {
2319            Match::History {
2320                path: history_path,
2321                panel_match: path_match,
2322            } => {
2323                search_entries.history.push(
2324                    path_match
2325                        .as_ref()
2326                        .map(|path_match| {
2327                            Path::new(path_match.0.path_prefix.as_ref()).join(&path_match.0.path)
2328                        })
2329                        .unwrap_or_else(|| {
2330                            history_path
2331                                .absolute
2332                                .as_deref()
2333                                .unwrap_or_else(|| &history_path.project.path)
2334                                .to_path_buf()
2335                        }),
2336                );
2337                search_entries
2338                    .history_found_paths
2339                    .push(history_path.clone());
2340            }
2341            Match::Search(path_match) => {
2342                search_entries
2343                    .search
2344                    .push(Path::new(path_match.0.path_prefix.as_ref()).join(&path_match.0.path));
2345                search_entries.search_matches.push(path_match.0.clone());
2346            }
2347        }
2348    }
2349    search_entries
2350}
2351
2352#[track_caller]
2353fn assert_match_selection(
2354    finder: &Picker<FileFinderDelegate>,
2355    expected_selection_index: usize,
2356    expected_file_name: &str,
2357) {
2358    assert_eq!(
2359        finder.delegate.selected_index(),
2360        expected_selection_index,
2361        "Match is not selected"
2362    );
2363    assert_match_at_position(finder, expected_selection_index, expected_file_name);
2364}
2365
2366#[track_caller]
2367fn assert_match_at_position(
2368    finder: &Picker<FileFinderDelegate>,
2369    match_index: usize,
2370    expected_file_name: &str,
2371) {
2372    let match_item = finder
2373        .delegate
2374        .matches
2375        .get(match_index)
2376        .unwrap_or_else(|| panic!("Finder has no match for index {match_index}"));
2377    let match_file_name = match &match_item {
2378        Match::History { path, .. } => path.absolute.as_deref().unwrap().file_name(),
2379        Match::Search(path_match) => path_match.0.path.file_name(),
2380    }
2381    .unwrap()
2382    .to_string_lossy();
2383    assert_eq!(match_file_name, expected_file_name);
2384}
2385
2386#[gpui::test]
2387async fn test_filename_precedence(cx: &mut TestAppContext) {
2388    let app_state = init_test(cx);
2389
2390    app_state
2391        .fs
2392        .as_fake()
2393        .insert_tree(
2394            path!("/src"),
2395            json!({
2396                "layout": {
2397                    "app.css": "",
2398                    "app.d.ts": "",
2399                    "app.html": "",
2400                    "+page.svelte": "",
2401                },
2402                "routes": {
2403                    "+layout.svelte": "",
2404                }
2405            }),
2406        )
2407        .await;
2408
2409    let project = Project::test(app_state.fs.clone(), [path!("/src").as_ref()], cx).await;
2410    let (picker, _, cx) = build_find_picker(project, cx);
2411
2412    cx.simulate_input("layout");
2413
2414    picker.update(cx, |finder, _| {
2415        let search_matches = collect_search_matches(finder).search_paths_only();
2416
2417        assert_eq!(
2418            search_matches,
2419            vec![
2420                PathBuf::from("routes/+layout.svelte"),
2421                PathBuf::from("layout/app.css"),
2422                PathBuf::from("layout/app.d.ts"),
2423                PathBuf::from("layout/app.html"),
2424                PathBuf::from("layout/+page.svelte"),
2425            ],
2426            "File with 'layout' in filename should be prioritized over files in 'layout' directory"
2427        );
2428    });
2429}