file_finder.rs

   1use collections::HashMap;
   2use editor::{scroll::autoscroll::Autoscroll, Bias, Editor};
   3use fuzzy::{CharBag, PathMatch, PathMatchCandidate};
   4use gpui::{
   5    actions, div, AppContext, Div, EventEmitter, FocusHandle, FocusableView, InteractiveElement,
   6    Manager, Model, ParentElement, Render, RenderOnce, Styled, Task, View, ViewContext,
   7    VisualContext, WeakView,
   8};
   9use picker::{Picker, PickerDelegate};
  10use project::{PathMatchCandidateSet, Project, ProjectPath, WorktreeId};
  11use std::{
  12    path::{Path, PathBuf},
  13    sync::{
  14        atomic::{self, AtomicBool},
  15        Arc,
  16    },
  17};
  18use text::Point;
  19use theme::ActiveTheme;
  20use ui::{v_stack, HighlightedLabel, StyledExt};
  21use util::{paths::PathLikeWithPosition, post_inc, ResultExt};
  22use workspace::Workspace;
  23
  24actions!(Toggle);
  25
  26pub struct FileFinder {
  27    picker: View<Picker<FileFinderDelegate>>,
  28}
  29
  30pub fn init(cx: &mut AppContext) {
  31    cx.observe_new_views(FileFinder::register).detach();
  32}
  33
  34impl FileFinder {
  35    fn register(workspace: &mut Workspace, _: &mut ViewContext<Workspace>) {
  36        workspace.register_action(|workspace, _: &Toggle, cx| {
  37            let Some(file_finder) = workspace.active_modal::<Self>(cx) else {
  38                Self::open(workspace, cx);
  39                return;
  40            };
  41
  42            file_finder.update(cx, |file_finder, cx| {
  43                file_finder
  44                    .picker
  45                    .update(cx, |picker, cx| picker.cycle_selection(cx))
  46            });
  47        });
  48    }
  49
  50    fn open(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {
  51        let project = workspace.project().read(cx);
  52
  53        let currently_opened_path = workspace
  54            .active_item(cx)
  55            .and_then(|item| item.project_path(cx))
  56            .map(|project_path| {
  57                let abs_path = project
  58                    .worktree_for_id(project_path.worktree_id, cx)
  59                    .map(|worktree| worktree.read(cx).abs_path().join(&project_path.path));
  60                FoundPath::new(project_path, abs_path)
  61            });
  62
  63        // if exists, bubble the currently opened path to the top
  64        let history_items = currently_opened_path
  65            .clone()
  66            .into_iter()
  67            .chain(
  68                workspace
  69                    .recent_navigation_history(Some(MAX_RECENT_SELECTIONS), cx)
  70                    .into_iter()
  71                    .filter(|(history_path, _)| {
  72                        Some(history_path)
  73                            != currently_opened_path
  74                                .as_ref()
  75                                .map(|found_path| &found_path.project)
  76                    })
  77                    .filter(|(_, history_abs_path)| {
  78                        history_abs_path.as_ref()
  79                            != currently_opened_path
  80                                .as_ref()
  81                                .and_then(|found_path| found_path.absolute.as_ref())
  82                    })
  83                    .filter(|(_, history_abs_path)| match history_abs_path {
  84                        Some(abs_path) => history_file_exists(abs_path),
  85                        None => true,
  86                    })
  87                    .map(|(history_path, abs_path)| FoundPath::new(history_path, abs_path)),
  88            )
  89            .collect();
  90
  91        let project = workspace.project().clone();
  92        let weak_workspace = cx.view().downgrade();
  93        workspace.toggle_modal(cx, |cx| {
  94            let delegate = FileFinderDelegate::new(
  95                cx.view().downgrade(),
  96                weak_workspace,
  97                project,
  98                currently_opened_path,
  99                history_items,
 100                cx,
 101            );
 102
 103            FileFinder::new(delegate, cx)
 104        });
 105    }
 106
 107    fn new(delegate: FileFinderDelegate, cx: &mut ViewContext<Self>) -> Self {
 108        Self {
 109            picker: cx.build_view(|cx| Picker::new(delegate, cx)),
 110        }
 111    }
 112}
 113
 114impl EventEmitter<Manager> for FileFinder {}
 115impl FocusableView for FileFinder {
 116    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
 117        self.picker.focus_handle(cx)
 118    }
 119}
 120impl Render for FileFinder {
 121    type Element = Div;
 122
 123    fn render(&mut self, _cx: &mut ViewContext<Self>) -> Self::Element {
 124        v_stack().w_96().child(self.picker.clone())
 125    }
 126}
 127
 128pub struct FileFinderDelegate {
 129    file_finder: WeakView<FileFinder>,
 130    workspace: WeakView<Workspace>,
 131    project: Model<Project>,
 132    search_count: usize,
 133    latest_search_id: usize,
 134    latest_search_did_cancel: bool,
 135    latest_search_query: Option<PathLikeWithPosition<FileSearchQuery>>,
 136    currently_opened_path: Option<FoundPath>,
 137    matches: Matches,
 138    selected_index: Option<usize>,
 139    cancel_flag: Arc<AtomicBool>,
 140    history_items: Vec<FoundPath>,
 141}
 142
 143#[derive(Debug, Default)]
 144struct Matches {
 145    history: Vec<(FoundPath, Option<PathMatch>)>,
 146    search: Vec<PathMatch>,
 147}
 148
 149#[derive(Debug)]
 150enum Match<'a> {
 151    History(&'a FoundPath, Option<&'a PathMatch>),
 152    Search(&'a PathMatch),
 153}
 154
 155impl Matches {
 156    fn len(&self) -> usize {
 157        self.history.len() + self.search.len()
 158    }
 159
 160    fn get(&self, index: usize) -> Option<Match<'_>> {
 161        if index < self.history.len() {
 162            self.history
 163                .get(index)
 164                .map(|(path, path_match)| Match::History(path, path_match.as_ref()))
 165        } else {
 166            self.search
 167                .get(index - self.history.len())
 168                .map(Match::Search)
 169        }
 170    }
 171
 172    fn push_new_matches(
 173        &mut self,
 174        history_items: &Vec<FoundPath>,
 175        query: &PathLikeWithPosition<FileSearchQuery>,
 176        mut new_search_matches: Vec<PathMatch>,
 177        extend_old_matches: bool,
 178    ) {
 179        let matching_history_paths = matching_history_item_paths(history_items, query);
 180        new_search_matches
 181            .retain(|path_match| !matching_history_paths.contains_key(&path_match.path));
 182        let history_items_to_show = history_items
 183            .iter()
 184            .filter_map(|history_item| {
 185                Some((
 186                    history_item.clone(),
 187                    Some(
 188                        matching_history_paths
 189                            .get(&history_item.project.path)?
 190                            .clone(),
 191                    ),
 192                ))
 193            })
 194            .collect::<Vec<_>>();
 195        self.history = history_items_to_show;
 196        if extend_old_matches {
 197            self.search
 198                .retain(|path_match| !matching_history_paths.contains_key(&path_match.path));
 199            util::extend_sorted(
 200                &mut self.search,
 201                new_search_matches.into_iter(),
 202                100,
 203                |a, b| b.cmp(a),
 204            )
 205        } else {
 206            self.search = new_search_matches;
 207        }
 208    }
 209}
 210
 211fn matching_history_item_paths(
 212    history_items: &Vec<FoundPath>,
 213    query: &PathLikeWithPosition<FileSearchQuery>,
 214) -> HashMap<Arc<Path>, PathMatch> {
 215    let history_items_by_worktrees = history_items
 216        .iter()
 217        .filter_map(|found_path| {
 218            let candidate = PathMatchCandidate {
 219                path: &found_path.project.path,
 220                // Only match history items names, otherwise their paths may match too many queries, producing false positives.
 221                // E.g. `foo` would match both `something/foo/bar.rs` and `something/foo/foo.rs` and if the former is a history item,
 222                // it would be shown first always, despite the latter being a better match.
 223                char_bag: CharBag::from_iter(
 224                    found_path
 225                        .project
 226                        .path
 227                        .file_name()?
 228                        .to_string_lossy()
 229                        .to_lowercase()
 230                        .chars(),
 231                ),
 232            };
 233            Some((found_path.project.worktree_id, candidate))
 234        })
 235        .fold(
 236            HashMap::default(),
 237            |mut candidates, (worktree_id, new_candidate)| {
 238                candidates
 239                    .entry(worktree_id)
 240                    .or_insert_with(Vec::new)
 241                    .push(new_candidate);
 242                candidates
 243            },
 244        );
 245    let mut matching_history_paths = HashMap::default();
 246    for (worktree, candidates) in history_items_by_worktrees {
 247        let max_results = candidates.len() + 1;
 248        matching_history_paths.extend(
 249            fuzzy::match_fixed_path_set(
 250                candidates,
 251                worktree.to_usize(),
 252                query.path_like.path_query(),
 253                false,
 254                max_results,
 255            )
 256            .into_iter()
 257            .map(|path_match| (Arc::clone(&path_match.path), path_match)),
 258        );
 259    }
 260    matching_history_paths
 261}
 262
 263#[derive(Debug, Clone, PartialEq, Eq)]
 264struct FoundPath {
 265    project: ProjectPath,
 266    absolute: Option<PathBuf>,
 267}
 268
 269impl FoundPath {
 270    fn new(project: ProjectPath, absolute: Option<PathBuf>) -> Self {
 271        Self { project, absolute }
 272    }
 273}
 274
 275const MAX_RECENT_SELECTIONS: usize = 20;
 276
 277#[cfg(not(test))]
 278fn history_file_exists(abs_path: &PathBuf) -> bool {
 279    abs_path.exists()
 280}
 281
 282#[cfg(test)]
 283fn history_file_exists(abs_path: &PathBuf) -> bool {
 284    !abs_path.ends_with("nonexistent.rs")
 285}
 286
 287pub enum Event {
 288    Selected(ProjectPath),
 289    Dismissed,
 290}
 291
 292#[derive(Debug, Clone)]
 293struct FileSearchQuery {
 294    raw_query: String,
 295    file_query_end: Option<usize>,
 296}
 297
 298impl FileSearchQuery {
 299    fn path_query(&self) -> &str {
 300        match self.file_query_end {
 301            Some(file_path_end) => &self.raw_query[..file_path_end],
 302            None => &self.raw_query,
 303        }
 304    }
 305}
 306
 307impl FileFinderDelegate {
 308    fn new(
 309        file_finder: WeakView<FileFinder>,
 310        workspace: WeakView<Workspace>,
 311        project: Model<Project>,
 312        currently_opened_path: Option<FoundPath>,
 313        history_items: Vec<FoundPath>,
 314        cx: &mut ViewContext<FileFinder>,
 315    ) -> Self {
 316        cx.observe(&project, |file_finder, _, cx| {
 317            //todo!() We should probably not re-render on every project anything
 318            file_finder
 319                .picker
 320                .update(cx, |picker, cx| picker.refresh(cx))
 321        })
 322        .detach();
 323
 324        Self {
 325            file_finder,
 326            workspace,
 327            project,
 328            search_count: 0,
 329            latest_search_id: 0,
 330            latest_search_did_cancel: false,
 331            latest_search_query: None,
 332            currently_opened_path,
 333            matches: Matches::default(),
 334            selected_index: None,
 335            cancel_flag: Arc::new(AtomicBool::new(false)),
 336            history_items,
 337        }
 338    }
 339
 340    fn spawn_search(
 341        &mut self,
 342        query: PathLikeWithPosition<FileSearchQuery>,
 343        cx: &mut ViewContext<Picker<Self>>,
 344    ) -> Task<()> {
 345        let relative_to = self
 346            .currently_opened_path
 347            .as_ref()
 348            .map(|found_path| Arc::clone(&found_path.project.path));
 349        let worktrees = self
 350            .project
 351            .read(cx)
 352            .visible_worktrees(cx)
 353            .collect::<Vec<_>>();
 354        let include_root_name = worktrees.len() > 1;
 355        let candidate_sets = worktrees
 356            .into_iter()
 357            .map(|worktree| {
 358                let worktree = worktree.read(cx);
 359                PathMatchCandidateSet {
 360                    snapshot: worktree.snapshot(),
 361                    include_ignored: worktree
 362                        .root_entry()
 363                        .map_or(false, |entry| entry.is_ignored),
 364                    include_root_name,
 365                }
 366            })
 367            .collect::<Vec<_>>();
 368
 369        let search_id = util::post_inc(&mut self.search_count);
 370        self.cancel_flag.store(true, atomic::Ordering::Relaxed);
 371        self.cancel_flag = Arc::new(AtomicBool::new(false));
 372        let cancel_flag = self.cancel_flag.clone();
 373        cx.spawn(|picker, mut cx| async move {
 374            let matches = fuzzy::match_path_sets(
 375                candidate_sets.as_slice(),
 376                query.path_like.path_query(),
 377                relative_to,
 378                false,
 379                100,
 380                &cancel_flag,
 381                cx.background_executor().clone(),
 382            )
 383            .await;
 384            let did_cancel = cancel_flag.load(atomic::Ordering::Relaxed);
 385            picker
 386                .update(&mut cx, |picker, cx| {
 387                    picker
 388                        .delegate
 389                        .set_search_matches(search_id, did_cancel, query, matches, cx)
 390                })
 391                .log_err();
 392        })
 393    }
 394
 395    fn set_search_matches(
 396        &mut self,
 397        search_id: usize,
 398        did_cancel: bool,
 399        query: PathLikeWithPosition<FileSearchQuery>,
 400        matches: Vec<PathMatch>,
 401        cx: &mut ViewContext<Picker<Self>>,
 402    ) {
 403        if search_id >= self.latest_search_id {
 404            self.latest_search_id = search_id;
 405            let extend_old_matches = self.latest_search_did_cancel
 406                && Some(query.path_like.path_query())
 407                    == self
 408                        .latest_search_query
 409                        .as_ref()
 410                        .map(|query| query.path_like.path_query());
 411            self.matches
 412                .push_new_matches(&self.history_items, &query, matches, extend_old_matches);
 413            self.latest_search_query = Some(query);
 414            self.latest_search_did_cancel = did_cancel;
 415            cx.notify();
 416        }
 417    }
 418
 419    fn labels_for_match(
 420        &self,
 421        path_match: Match,
 422        cx: &AppContext,
 423        ix: usize,
 424    ) -> (String, Vec<usize>, String, Vec<usize>) {
 425        let (file_name, file_name_positions, full_path, full_path_positions) = match path_match {
 426            Match::History(found_path, found_path_match) => {
 427                let worktree_id = found_path.project.worktree_id;
 428                let project_relative_path = &found_path.project.path;
 429                let has_worktree = self
 430                    .project
 431                    .read(cx)
 432                    .worktree_for_id(worktree_id, cx)
 433                    .is_some();
 434
 435                if !has_worktree {
 436                    if let Some(absolute_path) = &found_path.absolute {
 437                        return (
 438                            absolute_path
 439                                .file_name()
 440                                .map_or_else(
 441                                    || project_relative_path.to_string_lossy(),
 442                                    |file_name| file_name.to_string_lossy(),
 443                                )
 444                                .to_string(),
 445                            Vec::new(),
 446                            absolute_path.to_string_lossy().to_string(),
 447                            Vec::new(),
 448                        );
 449                    }
 450                }
 451
 452                let mut path = Arc::clone(project_relative_path);
 453                if project_relative_path.as_ref() == Path::new("") {
 454                    if let Some(absolute_path) = &found_path.absolute {
 455                        path = Arc::from(absolute_path.as_path());
 456                    }
 457                }
 458
 459                let mut path_match = PathMatch {
 460                    score: ix as f64,
 461                    positions: Vec::new(),
 462                    worktree_id: worktree_id.to_usize(),
 463                    path,
 464                    path_prefix: "".into(),
 465                    distance_to_relative_ancestor: usize::MAX,
 466                };
 467                if let Some(found_path_match) = found_path_match {
 468                    path_match
 469                        .positions
 470                        .extend(found_path_match.positions.iter())
 471                }
 472
 473                self.labels_for_path_match(&path_match)
 474            }
 475            Match::Search(path_match) => self.labels_for_path_match(path_match),
 476        };
 477
 478        if file_name_positions.is_empty() {
 479            if let Some(user_home_path) = std::env::var("HOME").ok() {
 480                let user_home_path = user_home_path.trim();
 481                if !user_home_path.is_empty() {
 482                    if (&full_path).starts_with(user_home_path) {
 483                        return (
 484                            file_name,
 485                            file_name_positions,
 486                            full_path.replace(user_home_path, "~"),
 487                            full_path_positions,
 488                        );
 489                    }
 490                }
 491            }
 492        }
 493
 494        (
 495            file_name,
 496            file_name_positions,
 497            full_path,
 498            full_path_positions,
 499        )
 500    }
 501
 502    fn labels_for_path_match(
 503        &self,
 504        path_match: &PathMatch,
 505    ) -> (String, Vec<usize>, String, Vec<usize>) {
 506        let path = &path_match.path;
 507        let path_string = path.to_string_lossy();
 508        let full_path = [path_match.path_prefix.as_ref(), path_string.as_ref()].join("");
 509        let path_positions = path_match.positions.clone();
 510
 511        let file_name = path.file_name().map_or_else(
 512            || path_match.path_prefix.to_string(),
 513            |file_name| file_name.to_string_lossy().to_string(),
 514        );
 515        let file_name_start = path_match.path_prefix.chars().count() + path_string.chars().count()
 516            - file_name.chars().count();
 517        let file_name_positions = path_positions
 518            .iter()
 519            .filter_map(|pos| {
 520                if pos >= &file_name_start {
 521                    Some(pos - file_name_start)
 522                } else {
 523                    None
 524                }
 525            })
 526            .collect();
 527
 528        (file_name, file_name_positions, full_path, path_positions)
 529    }
 530}
 531
 532impl PickerDelegate for FileFinderDelegate {
 533    type ListItem = Div;
 534
 535    fn placeholder_text(&self) -> Arc<str> {
 536        "Search project files...".into()
 537    }
 538
 539    fn match_count(&self) -> usize {
 540        self.matches.len()
 541    }
 542
 543    fn selected_index(&self) -> usize {
 544        self.selected_index.unwrap_or(0)
 545    }
 546
 547    fn set_selected_index(&mut self, ix: usize, cx: &mut ViewContext<Picker<Self>>) {
 548        self.selected_index = Some(ix);
 549        cx.notify();
 550    }
 551
 552    fn update_matches(
 553        &mut self,
 554        raw_query: String,
 555        cx: &mut ViewContext<Picker<Self>>,
 556    ) -> Task<()> {
 557        if raw_query.is_empty() {
 558            let project = self.project.read(cx);
 559            self.latest_search_id = post_inc(&mut self.search_count);
 560            self.matches = Matches {
 561                history: self
 562                    .history_items
 563                    .iter()
 564                    .filter(|history_item| {
 565                        project
 566                            .worktree_for_id(history_item.project.worktree_id, cx)
 567                            .is_some()
 568                            || (project.is_local() && history_item.absolute.is_some())
 569                    })
 570                    .cloned()
 571                    .map(|p| (p, None))
 572                    .collect(),
 573                search: Vec::new(),
 574            };
 575            cx.notify();
 576            Task::ready(())
 577        } else {
 578            let raw_query = &raw_query;
 579            let query = PathLikeWithPosition::parse_str(raw_query, |path_like_str| {
 580                Ok::<_, std::convert::Infallible>(FileSearchQuery {
 581                    raw_query: raw_query.to_owned(),
 582                    file_query_end: if path_like_str == raw_query {
 583                        None
 584                    } else {
 585                        Some(path_like_str.len())
 586                    },
 587                })
 588            })
 589            .expect("infallible");
 590            self.spawn_search(query, cx)
 591        }
 592    }
 593
 594    fn confirm(&mut self, secondary: bool, cx: &mut ViewContext<Picker<FileFinderDelegate>>) {
 595        if let Some(m) = self.matches.get(self.selected_index()) {
 596            if let Some(workspace) = self.workspace.upgrade() {
 597                let open_task = workspace.update(cx, move |workspace, cx| {
 598                    let split_or_open = |workspace: &mut Workspace, project_path, cx| {
 599                        if secondary {
 600                            workspace.split_path(project_path, cx)
 601                        } else {
 602                            workspace.open_path(project_path, None, true, cx)
 603                        }
 604                    };
 605                    match m {
 606                        Match::History(history_match, _) => {
 607                            let worktree_id = history_match.project.worktree_id;
 608                            if workspace
 609                                .project()
 610                                .read(cx)
 611                                .worktree_for_id(worktree_id, cx)
 612                                .is_some()
 613                            {
 614                                split_or_open(
 615                                    workspace,
 616                                    ProjectPath {
 617                                        worktree_id,
 618                                        path: Arc::clone(&history_match.project.path),
 619                                    },
 620                                    cx,
 621                                )
 622                            } else {
 623                                match history_match.absolute.as_ref() {
 624                                    Some(abs_path) => {
 625                                        if secondary {
 626                                            workspace.split_abs_path(
 627                                                abs_path.to_path_buf(),
 628                                                false,
 629                                                cx,
 630                                            )
 631                                        } else {
 632                                            workspace.open_abs_path(
 633                                                abs_path.to_path_buf(),
 634                                                false,
 635                                                cx,
 636                                            )
 637                                        }
 638                                    }
 639                                    None => split_or_open(
 640                                        workspace,
 641                                        ProjectPath {
 642                                            worktree_id,
 643                                            path: Arc::clone(&history_match.project.path),
 644                                        },
 645                                        cx,
 646                                    ),
 647                                }
 648                            }
 649                        }
 650                        Match::Search(m) => split_or_open(
 651                            workspace,
 652                            ProjectPath {
 653                                worktree_id: WorktreeId::from_usize(m.worktree_id),
 654                                path: m.path.clone(),
 655                            },
 656                            cx,
 657                        ),
 658                    }
 659                });
 660
 661                let row = self
 662                    .latest_search_query
 663                    .as_ref()
 664                    .and_then(|query| query.row)
 665                    .map(|row| row.saturating_sub(1));
 666                let col = self
 667                    .latest_search_query
 668                    .as_ref()
 669                    .and_then(|query| query.column)
 670                    .unwrap_or(0)
 671                    .saturating_sub(1);
 672                let finder = self.file_finder.clone();
 673
 674                cx.spawn(|_, mut cx| async move {
 675                    let item = open_task.await.log_err()?;
 676                    if let Some(row) = row {
 677                        if let Some(active_editor) = item.downcast::<Editor>() {
 678                            active_editor
 679                                .downgrade()
 680                                .update(&mut cx, |editor, cx| {
 681                                    let snapshot = editor.snapshot(cx).display_snapshot;
 682                                    let point = snapshot
 683                                        .buffer_snapshot
 684                                        .clip_point(Point::new(row, col), Bias::Left);
 685                                    editor.change_selections(Some(Autoscroll::center()), cx, |s| {
 686                                        s.select_ranges([point..point])
 687                                    });
 688                                })
 689                                .log_err();
 690                        }
 691                    }
 692                    finder
 693                        .update(&mut cx, |_, cx| cx.emit(Manager::Dismiss))
 694                        .ok()?;
 695
 696                    Some(())
 697                })
 698                .detach();
 699            }
 700        }
 701    }
 702
 703    fn dismissed(&mut self, cx: &mut ViewContext<Picker<FileFinderDelegate>>) {
 704        self.file_finder
 705            .update(cx, |_, cx| cx.emit(Manager::Dismiss))
 706            .log_err();
 707    }
 708
 709    fn render_match(
 710        &self,
 711        ix: usize,
 712        selected: bool,
 713        cx: &mut ViewContext<Picker<Self>>,
 714    ) -> Self::ListItem {
 715        let path_match = self
 716            .matches
 717            .get(ix)
 718            .expect("Invalid matches state: no element for index {ix}");
 719        let theme = cx.theme();
 720        let colors = theme.colors();
 721
 722        let (file_name, file_name_positions, full_path, full_path_positions) =
 723            self.labels_for_match(path_match, cx, ix);
 724
 725        div()
 726            .px_1()
 727            .text_color(colors.text)
 728            .text_ui()
 729            .bg(colors.ghost_element_background)
 730            .rounded_md()
 731            .when(selected, |this| this.bg(colors.ghost_element_selected))
 732            .hover(|this| this.bg(colors.ghost_element_hover))
 733            .child(
 734                v_stack()
 735                    .child(HighlightedLabel::new(file_name, file_name_positions))
 736                    .child(HighlightedLabel::new(full_path, full_path_positions)),
 737            )
 738    }
 739}
 740
 741#[cfg(test)]
 742mod tests {
 743    use std::{assert_eq, path::Path, time::Duration};
 744
 745    use super::*;
 746    use editor::Editor;
 747    use gpui::{Entity, TestAppContext, VisualTestContext};
 748    use menu::{Confirm, SelectNext};
 749    use serde_json::json;
 750    use workspace::{AppState, Workspace};
 751
 752    #[ctor::ctor]
 753    fn init_logger() {
 754        if std::env::var("RUST_LOG").is_ok() {
 755            env_logger::init();
 756        }
 757    }
 758
 759    #[gpui::test]
 760    async fn test_matching_paths(cx: &mut TestAppContext) {
 761        let app_state = init_test(cx);
 762        app_state
 763            .fs
 764            .as_fake()
 765            .insert_tree(
 766                "/root",
 767                json!({
 768                    "a": {
 769                        "banana": "",
 770                        "bandana": "",
 771                    }
 772                }),
 773            )
 774            .await;
 775
 776        let project = Project::test(app_state.fs.clone(), ["/root".as_ref()], cx).await;
 777
 778        let (picker, workspace, cx) = build_find_picker(project, cx);
 779
 780        cx.simulate_input("bna");
 781
 782        picker.update(cx, |picker, _| {
 783            assert_eq!(picker.delegate.matches.len(), 2);
 784        });
 785
 786        cx.dispatch_action(SelectNext);
 787        cx.dispatch_action(Confirm);
 788
 789        cx.read(|cx| {
 790            let active_editor = workspace.read(cx).active_item_as::<Editor>(cx).unwrap();
 791            assert_eq!(active_editor.read(cx).title(cx), "bandana");
 792        });
 793    }
 794
 795    #[gpui::test]
 796    async fn test_row_column_numbers_query_inside_file(cx: &mut TestAppContext) {
 797        let app_state = init_test(cx);
 798
 799        let first_file_name = "first.rs";
 800        let first_file_contents = "// First Rust file";
 801        app_state
 802            .fs
 803            .as_fake()
 804            .insert_tree(
 805                "/src",
 806                json!({
 807                    "test": {
 808                        first_file_name: first_file_contents,
 809                        "second.rs": "// Second Rust file",
 810                    }
 811                }),
 812            )
 813            .await;
 814
 815        let project = Project::test(app_state.fs.clone(), ["/src".as_ref()], cx).await;
 816
 817        let (picker, workspace, cx) = build_find_picker(project, cx);
 818
 819        let file_query = &first_file_name[..3];
 820        let file_row = 1;
 821        let file_column = 3;
 822        assert!(file_column <= first_file_contents.len());
 823        let query_inside_file = format!("{file_query}:{file_row}:{file_column}");
 824        picker
 825            .update(cx, |finder, cx| {
 826                finder
 827                    .delegate
 828                    .update_matches(query_inside_file.to_string(), cx)
 829            })
 830            .await;
 831        picker.update(cx, |finder, _| {
 832            let finder = &finder.delegate;
 833            assert_eq!(finder.matches.len(), 1);
 834            let latest_search_query = finder
 835                .latest_search_query
 836                .as_ref()
 837                .expect("Finder should have a query after the update_matches call");
 838            assert_eq!(latest_search_query.path_like.raw_query, query_inside_file);
 839            assert_eq!(
 840                latest_search_query.path_like.file_query_end,
 841                Some(file_query.len())
 842            );
 843            assert_eq!(latest_search_query.row, Some(file_row));
 844            assert_eq!(latest_search_query.column, Some(file_column as u32));
 845        });
 846
 847        cx.dispatch_action(SelectNext);
 848        cx.dispatch_action(Confirm);
 849
 850        let editor = cx.update(|cx| workspace.read(cx).active_item_as::<Editor>(cx).unwrap());
 851        cx.executor().advance_clock(Duration::from_secs(2));
 852
 853        editor.update(cx, |editor, cx| {
 854                let all_selections = editor.selections.all_adjusted(cx);
 855                assert_eq!(
 856                    all_selections.len(),
 857                    1,
 858                    "Expected to have 1 selection (caret) after file finder confirm, but got: {all_selections:?}"
 859                );
 860                let caret_selection = all_selections.into_iter().next().unwrap();
 861                assert_eq!(caret_selection.start, caret_selection.end,
 862                    "Caret selection should have its start and end at the same position");
 863                assert_eq!(file_row, caret_selection.start.row + 1,
 864                    "Query inside file should get caret with the same focus row");
 865                assert_eq!(file_column, caret_selection.start.column as usize + 1,
 866                    "Query inside file should get caret with the same focus column");
 867            });
 868    }
 869
 870    #[gpui::test]
 871    async fn test_row_column_numbers_query_outside_file(cx: &mut TestAppContext) {
 872        let app_state = init_test(cx);
 873
 874        let first_file_name = "first.rs";
 875        let first_file_contents = "// First Rust file";
 876        app_state
 877            .fs
 878            .as_fake()
 879            .insert_tree(
 880                "/src",
 881                json!({
 882                    "test": {
 883                        first_file_name: first_file_contents,
 884                        "second.rs": "// Second Rust file",
 885                    }
 886                }),
 887            )
 888            .await;
 889
 890        let project = Project::test(app_state.fs.clone(), ["/src".as_ref()], cx).await;
 891
 892        let (picker, workspace, cx) = build_find_picker(project, cx);
 893
 894        let file_query = &first_file_name[..3];
 895        let file_row = 200;
 896        let file_column = 300;
 897        assert!(file_column > first_file_contents.len());
 898        let query_outside_file = format!("{file_query}:{file_row}:{file_column}");
 899        picker
 900            .update(cx, |picker, cx| {
 901                picker
 902                    .delegate
 903                    .update_matches(query_outside_file.to_string(), cx)
 904            })
 905            .await;
 906        picker.update(cx, |finder, _| {
 907            let delegate = &finder.delegate;
 908            assert_eq!(delegate.matches.len(), 1);
 909            let latest_search_query = delegate
 910                .latest_search_query
 911                .as_ref()
 912                .expect("Finder should have a query after the update_matches call");
 913            assert_eq!(latest_search_query.path_like.raw_query, query_outside_file);
 914            assert_eq!(
 915                latest_search_query.path_like.file_query_end,
 916                Some(file_query.len())
 917            );
 918            assert_eq!(latest_search_query.row, Some(file_row));
 919            assert_eq!(latest_search_query.column, Some(file_column as u32));
 920        });
 921
 922        cx.dispatch_action(SelectNext);
 923        cx.dispatch_action(Confirm);
 924
 925        let editor = cx.update(|cx| workspace.read(cx).active_item_as::<Editor>(cx).unwrap());
 926        cx.executor().advance_clock(Duration::from_secs(2));
 927
 928        editor.update(cx, |editor, cx| {
 929                let all_selections = editor.selections.all_adjusted(cx);
 930                assert_eq!(
 931                    all_selections.len(),
 932                    1,
 933                    "Expected to have 1 selection (caret) after file finder confirm, but got: {all_selections:?}"
 934                );
 935                let caret_selection = all_selections.into_iter().next().unwrap();
 936                assert_eq!(caret_selection.start, caret_selection.end,
 937                    "Caret selection should have its start and end at the same position");
 938                assert_eq!(0, caret_selection.start.row,
 939                    "Excessive rows (as in query outside file borders) should get trimmed to last file row");
 940                assert_eq!(first_file_contents.len(), caret_selection.start.column as usize,
 941                    "Excessive columns (as in query outside file borders) should get trimmed to selected row's last column");
 942            });
 943    }
 944
 945    #[gpui::test]
 946    async fn test_matching_cancellation(cx: &mut TestAppContext) {
 947        let app_state = init_test(cx);
 948        app_state
 949            .fs
 950            .as_fake()
 951            .insert_tree(
 952                "/dir",
 953                json!({
 954                    "hello": "",
 955                    "goodbye": "",
 956                    "halogen-light": "",
 957                    "happiness": "",
 958                    "height": "",
 959                    "hi": "",
 960                    "hiccup": "",
 961                }),
 962            )
 963            .await;
 964
 965        let project = Project::test(app_state.fs.clone(), ["/dir".as_ref()], cx).await;
 966
 967        let (picker, _, cx) = build_find_picker(project, cx);
 968
 969        let query = test_path_like("hi");
 970        picker
 971            .update(cx, |picker, cx| {
 972                picker.delegate.spawn_search(query.clone(), cx)
 973            })
 974            .await;
 975
 976        picker.update(cx, |picker, _cx| {
 977            assert_eq!(picker.delegate.matches.len(), 5)
 978        });
 979
 980        picker.update(cx, |picker, cx| {
 981            let delegate = &mut picker.delegate;
 982            assert!(
 983                delegate.matches.history.is_empty(),
 984                "Search matches expected"
 985            );
 986            let matches = delegate.matches.search.clone();
 987
 988            // Simulate a search being cancelled after the time limit,
 989            // returning only a subset of the matches that would have been found.
 990            drop(delegate.spawn_search(query.clone(), cx));
 991            delegate.set_search_matches(
 992                delegate.latest_search_id,
 993                true, // did-cancel
 994                query.clone(),
 995                vec![matches[1].clone(), matches[3].clone()],
 996                cx,
 997            );
 998
 999            // Simulate another cancellation.
1000            drop(delegate.spawn_search(query.clone(), cx));
1001            delegate.set_search_matches(
1002                delegate.latest_search_id,
1003                true, // did-cancel
1004                query.clone(),
1005                vec![matches[0].clone(), matches[2].clone(), matches[3].clone()],
1006                cx,
1007            );
1008
1009            assert!(
1010                delegate.matches.history.is_empty(),
1011                "Search matches expected"
1012            );
1013            assert_eq!(delegate.matches.search.as_slice(), &matches[0..4]);
1014        });
1015    }
1016
1017    #[gpui::test]
1018    async fn test_ignored_files(cx: &mut TestAppContext) {
1019        let app_state = init_test(cx);
1020        app_state
1021            .fs
1022            .as_fake()
1023            .insert_tree(
1024                "/ancestor",
1025                json!({
1026                    ".gitignore": "ignored-root",
1027                    "ignored-root": {
1028                        "happiness": "",
1029                        "height": "",
1030                        "hi": "",
1031                        "hiccup": "",
1032                    },
1033                    "tracked-root": {
1034                        ".gitignore": "height",
1035                        "happiness": "",
1036                        "height": "",
1037                        "hi": "",
1038                        "hiccup": "",
1039                    },
1040                }),
1041            )
1042            .await;
1043
1044        let project = Project::test(
1045            app_state.fs.clone(),
1046            [
1047                "/ancestor/tracked-root".as_ref(),
1048                "/ancestor/ignored-root".as_ref(),
1049            ],
1050            cx,
1051        )
1052        .await;
1053
1054        let (picker, _, cx) = build_find_picker(project, cx);
1055
1056        picker
1057            .update(cx, |picker, cx| {
1058                picker.delegate.spawn_search(test_path_like("hi"), cx)
1059            })
1060            .await;
1061        picker.update(cx, |picker, _| assert_eq!(picker.delegate.matches.len(), 7));
1062    }
1063
1064    #[gpui::test]
1065    async fn test_single_file_worktrees(cx: &mut TestAppContext) {
1066        let app_state = init_test(cx);
1067        app_state
1068            .fs
1069            .as_fake()
1070            .insert_tree("/root", json!({ "the-parent-dir": { "the-file": "" } }))
1071            .await;
1072
1073        let project = Project::test(
1074            app_state.fs.clone(),
1075            ["/root/the-parent-dir/the-file".as_ref()],
1076            cx,
1077        )
1078        .await;
1079
1080        let (picker, _, cx) = build_find_picker(project, cx);
1081
1082        // Even though there is only one worktree, that worktree's filename
1083        // is included in the matching, because the worktree is a single file.
1084        picker
1085            .update(cx, |picker, cx| {
1086                picker.delegate.spawn_search(test_path_like("thf"), cx)
1087            })
1088            .await;
1089        cx.read(|cx| {
1090            let picker = picker.read(cx);
1091            let delegate = &picker.delegate;
1092            assert!(
1093                delegate.matches.history.is_empty(),
1094                "Search matches expected"
1095            );
1096            let matches = delegate.matches.search.clone();
1097            assert_eq!(matches.len(), 1);
1098
1099            let (file_name, file_name_positions, full_path, full_path_positions) =
1100                delegate.labels_for_path_match(&matches[0]);
1101            assert_eq!(file_name, "the-file");
1102            assert_eq!(file_name_positions, &[0, 1, 4]);
1103            assert_eq!(full_path, "the-file");
1104            assert_eq!(full_path_positions, &[0, 1, 4]);
1105        });
1106
1107        // Since the worktree root is a file, searching for its name followed by a slash does
1108        // not match anything.
1109        picker
1110            .update(cx, |f, cx| {
1111                f.delegate.spawn_search(test_path_like("thf/"), cx)
1112            })
1113            .await;
1114        picker.update(cx, |f, _| assert_eq!(f.delegate.matches.len(), 0));
1115    }
1116
1117    #[gpui::test]
1118    async fn test_path_distance_ordering(cx: &mut TestAppContext) {
1119        let app_state = init_test(cx);
1120        app_state
1121            .fs
1122            .as_fake()
1123            .insert_tree(
1124                "/root",
1125                json!({
1126                    "dir1": { "a.txt": "" },
1127                    "dir2": {
1128                        "a.txt": "",
1129                        "b.txt": ""
1130                    }
1131                }),
1132            )
1133            .await;
1134
1135        let project = Project::test(app_state.fs.clone(), ["/root".as_ref()], cx).await;
1136        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project, cx));
1137
1138        let worktree_id = cx.read(|cx| {
1139            let worktrees = workspace.read(cx).worktrees(cx).collect::<Vec<_>>();
1140            assert_eq!(worktrees.len(), 1);
1141            WorktreeId::from_usize(worktrees[0].entity_id().as_u64() as usize)
1142        });
1143
1144        // When workspace has an active item, sort items which are closer to that item
1145        // first when they have the same name. In this case, b.txt is closer to dir2's a.txt
1146        // so that one should be sorted earlier
1147        let b_path = ProjectPath {
1148            worktree_id,
1149            path: Arc::from(Path::new("/root/dir2/b.txt")),
1150        };
1151        workspace
1152            .update(cx, |workspace, cx| {
1153                workspace.open_path(b_path, None, true, cx)
1154            })
1155            .await
1156            .unwrap();
1157        let finder = open_file_picker(&workspace, cx);
1158        finder
1159            .update(cx, |f, cx| {
1160                f.delegate.spawn_search(test_path_like("a.txt"), cx)
1161            })
1162            .await;
1163
1164        finder.update(cx, |f, _| {
1165            let delegate = &f.delegate;
1166            assert!(
1167                delegate.matches.history.is_empty(),
1168                "Search matches expected"
1169            );
1170            let matches = delegate.matches.search.clone();
1171            assert_eq!(matches[0].path.as_ref(), Path::new("dir2/a.txt"));
1172            assert_eq!(matches[1].path.as_ref(), Path::new("dir1/a.txt"));
1173        });
1174    }
1175
1176    #[gpui::test]
1177    async fn test_search_worktree_without_files(cx: &mut TestAppContext) {
1178        let app_state = init_test(cx);
1179        app_state
1180            .fs
1181            .as_fake()
1182            .insert_tree(
1183                "/root",
1184                json!({
1185                    "dir1": {},
1186                    "dir2": {
1187                        "dir3": {}
1188                    }
1189                }),
1190            )
1191            .await;
1192
1193        let project = Project::test(app_state.fs.clone(), ["/root".as_ref()], cx).await;
1194        let (picker, _workspace, cx) = build_find_picker(project, cx);
1195
1196        picker
1197            .update(cx, |f, cx| {
1198                f.delegate.spawn_search(test_path_like("dir"), cx)
1199            })
1200            .await;
1201        cx.read(|cx| {
1202            let finder = picker.read(cx);
1203            assert_eq!(finder.delegate.matches.len(), 0);
1204        });
1205    }
1206
1207    #[gpui::test]
1208    async fn test_query_history(cx: &mut gpui::TestAppContext) {
1209        let app_state = init_test(cx);
1210
1211        app_state
1212            .fs
1213            .as_fake()
1214            .insert_tree(
1215                "/src",
1216                json!({
1217                    "test": {
1218                        "first.rs": "// First Rust file",
1219                        "second.rs": "// Second Rust file",
1220                        "third.rs": "// Third Rust file",
1221                    }
1222                }),
1223            )
1224            .await;
1225
1226        let project = Project::test(app_state.fs.clone(), ["/src".as_ref()], cx).await;
1227        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project, cx));
1228        let worktree_id = cx.read(|cx| {
1229            let worktrees = workspace.read(cx).worktrees(cx).collect::<Vec<_>>();
1230            assert_eq!(worktrees.len(), 1);
1231            WorktreeId::from_usize(worktrees[0].entity_id().as_u64() as usize)
1232        });
1233
1234        // Open and close panels, getting their history items afterwards.
1235        // Ensure history items get populated with opened items, and items are kept in a certain order.
1236        // The history lags one opened buffer behind, since it's updated in the search panel only on its reopen.
1237        //
1238        // TODO: without closing, the opened items do not propagate their history changes for some reason
1239        // it does work in real app though, only tests do not propagate.
1240        workspace.update(cx, |_, cx| dbg!(cx.focused()));
1241
1242        let initial_history = open_close_queried_buffer("fir", 1, "first.rs", &workspace, cx).await;
1243        assert!(
1244            initial_history.is_empty(),
1245            "Should have no history before opening any files"
1246        );
1247
1248        let history_after_first =
1249            open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
1250        assert_eq!(
1251            history_after_first,
1252            vec![FoundPath::new(
1253                ProjectPath {
1254                    worktree_id,
1255                    path: Arc::from(Path::new("test/first.rs")),
1256                },
1257                Some(PathBuf::from("/src/test/first.rs"))
1258            )],
1259            "Should show 1st opened item in the history when opening the 2nd item"
1260        );
1261
1262        let history_after_second =
1263            open_close_queried_buffer("thi", 1, "third.rs", &workspace, cx).await;
1264        assert_eq!(
1265            history_after_second,
1266            vec![
1267                FoundPath::new(
1268                    ProjectPath {
1269                        worktree_id,
1270                        path: Arc::from(Path::new("test/second.rs")),
1271                    },
1272                    Some(PathBuf::from("/src/test/second.rs"))
1273                ),
1274                FoundPath::new(
1275                    ProjectPath {
1276                        worktree_id,
1277                        path: Arc::from(Path::new("test/first.rs")),
1278                    },
1279                    Some(PathBuf::from("/src/test/first.rs"))
1280                ),
1281            ],
1282            "Should show 1st and 2nd opened items in the history when opening the 3rd item. \
1283    2nd item should be the first in the history, as the last opened."
1284        );
1285
1286        let history_after_third =
1287            open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
1288        assert_eq!(
1289                history_after_third,
1290                vec![
1291                    FoundPath::new(
1292                        ProjectPath {
1293                            worktree_id,
1294                            path: Arc::from(Path::new("test/third.rs")),
1295                        },
1296                        Some(PathBuf::from("/src/test/third.rs"))
1297                    ),
1298                    FoundPath::new(
1299                        ProjectPath {
1300                            worktree_id,
1301                            path: Arc::from(Path::new("test/second.rs")),
1302                        },
1303                        Some(PathBuf::from("/src/test/second.rs"))
1304                    ),
1305                    FoundPath::new(
1306                        ProjectPath {
1307                            worktree_id,
1308                            path: Arc::from(Path::new("test/first.rs")),
1309                        },
1310                        Some(PathBuf::from("/src/test/first.rs"))
1311                    ),
1312                ],
1313                "Should show 1st, 2nd and 3rd opened items in the history when opening the 2nd item again. \
1314    3rd item should be the first in the history, as the last opened."
1315            );
1316
1317        let history_after_second_again =
1318            open_close_queried_buffer("thi", 1, "third.rs", &workspace, cx).await;
1319        assert_eq!(
1320                history_after_second_again,
1321                vec![
1322                    FoundPath::new(
1323                        ProjectPath {
1324                            worktree_id,
1325                            path: Arc::from(Path::new("test/second.rs")),
1326                        },
1327                        Some(PathBuf::from("/src/test/second.rs"))
1328                    ),
1329                    FoundPath::new(
1330                        ProjectPath {
1331                            worktree_id,
1332                            path: Arc::from(Path::new("test/third.rs")),
1333                        },
1334                        Some(PathBuf::from("/src/test/third.rs"))
1335                    ),
1336                    FoundPath::new(
1337                        ProjectPath {
1338                            worktree_id,
1339                            path: Arc::from(Path::new("test/first.rs")),
1340                        },
1341                        Some(PathBuf::from("/src/test/first.rs"))
1342                    ),
1343                ],
1344                "Should show 1st, 2nd and 3rd opened items in the history when opening the 3rd item again. \
1345    2nd item, as the last opened, 3rd item should go next as it was opened right before."
1346            );
1347    }
1348
1349    #[gpui::test]
1350    async fn test_external_files_history(cx: &mut gpui::TestAppContext) {
1351        let app_state = init_test(cx);
1352
1353        app_state
1354            .fs
1355            .as_fake()
1356            .insert_tree(
1357                "/src",
1358                json!({
1359                    "test": {
1360                        "first.rs": "// First Rust file",
1361                        "second.rs": "// Second Rust file",
1362                    }
1363                }),
1364            )
1365            .await;
1366
1367        app_state
1368            .fs
1369            .as_fake()
1370            .insert_tree(
1371                "/external-src",
1372                json!({
1373                    "test": {
1374                        "third.rs": "// Third Rust file",
1375                        "fourth.rs": "// Fourth Rust file",
1376                    }
1377                }),
1378            )
1379            .await;
1380
1381        let project = Project::test(app_state.fs.clone(), ["/src".as_ref()], cx).await;
1382        cx.update(|cx| {
1383            project.update(cx, |project, cx| {
1384                project.find_or_create_local_worktree("/external-src", false, cx)
1385            })
1386        })
1387        .detach();
1388        cx.background_executor.run_until_parked();
1389
1390        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project, cx));
1391        let worktree_id = cx.read(|cx| {
1392            let worktrees = workspace.read(cx).worktrees(cx).collect::<Vec<_>>();
1393            assert_eq!(worktrees.len(), 1,);
1394
1395            WorktreeId::from_usize(worktrees[0].entity_id().as_u64() as usize)
1396        });
1397        workspace
1398            .update(cx, |workspace, cx| {
1399                workspace.open_abs_path(PathBuf::from("/external-src/test/third.rs"), false, cx)
1400            })
1401            .detach();
1402        cx.background_executor.run_until_parked();
1403        let external_worktree_id = cx.read(|cx| {
1404            let worktrees = workspace.read(cx).worktrees(cx).collect::<Vec<_>>();
1405            assert_eq!(
1406                worktrees.len(),
1407                2,
1408                "External file should get opened in a new worktree"
1409            );
1410
1411            WorktreeId::from_usize(
1412                worktrees
1413                    .into_iter()
1414                    .find(|worktree| {
1415                        worktree.entity_id().as_u64() as usize != worktree_id.to_usize()
1416                    })
1417                    .expect("New worktree should have a different id")
1418                    .entity_id()
1419                    .as_u64() as usize,
1420            )
1421        });
1422        cx.dispatch_action(workspace::CloseActiveItem { save_intent: None });
1423
1424        let initial_history_items =
1425            open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
1426        assert_eq!(
1427            initial_history_items,
1428            vec![FoundPath::new(
1429                ProjectPath {
1430                    worktree_id: external_worktree_id,
1431                    path: Arc::from(Path::new("")),
1432                },
1433                Some(PathBuf::from("/external-src/test/third.rs"))
1434            )],
1435            "Should show external file with its full path in the history after it was open"
1436        );
1437
1438        let updated_history_items =
1439            open_close_queried_buffer("fir", 1, "first.rs", &workspace, cx).await;
1440        assert_eq!(
1441            updated_history_items,
1442            vec![
1443                FoundPath::new(
1444                    ProjectPath {
1445                        worktree_id,
1446                        path: Arc::from(Path::new("test/second.rs")),
1447                    },
1448                    Some(PathBuf::from("/src/test/second.rs"))
1449                ),
1450                FoundPath::new(
1451                    ProjectPath {
1452                        worktree_id: external_worktree_id,
1453                        path: Arc::from(Path::new("")),
1454                    },
1455                    Some(PathBuf::from("/external-src/test/third.rs"))
1456                ),
1457            ],
1458            "Should keep external file with history updates",
1459        );
1460    }
1461
1462    #[gpui::test]
1463    async fn test_toggle_panel_new_selections(cx: &mut gpui::TestAppContext) {
1464        let app_state = init_test(cx);
1465
1466        app_state
1467            .fs
1468            .as_fake()
1469            .insert_tree(
1470                "/src",
1471                json!({
1472                    "test": {
1473                        "first.rs": "// First Rust file",
1474                        "second.rs": "// Second Rust file",
1475                        "third.rs": "// Third Rust file",
1476                    }
1477                }),
1478            )
1479            .await;
1480
1481        let project = Project::test(app_state.fs.clone(), ["/src".as_ref()], cx).await;
1482        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project, cx));
1483
1484        // generate some history to select from
1485        open_close_queried_buffer("fir", 1, "first.rs", &workspace, cx).await;
1486        cx.executor().run_until_parked();
1487        open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
1488        open_close_queried_buffer("thi", 1, "third.rs", &workspace, cx).await;
1489        let current_history =
1490            open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
1491
1492        for expected_selected_index in 0..current_history.len() {
1493            cx.dispatch_action(Toggle);
1494            let picker = active_file_picker(&workspace, cx);
1495            let selected_index = picker.update(cx, |picker, _| picker.delegate.selected_index());
1496            assert_eq!(
1497                selected_index, expected_selected_index,
1498                "Should select the next item in the history"
1499            );
1500        }
1501
1502        cx.dispatch_action(Toggle);
1503        let selected_index = workspace.update(cx, |workspace, cx| {
1504            workspace
1505                .active_modal::<FileFinder>(cx)
1506                .unwrap()
1507                .read(cx)
1508                .picker
1509                .read(cx)
1510                .delegate
1511                .selected_index()
1512        });
1513        assert_eq!(
1514            selected_index, 0,
1515            "Should wrap around the history and start all over"
1516        );
1517    }
1518
1519    #[gpui::test]
1520    async fn test_search_preserves_history_items(cx: &mut gpui::TestAppContext) {
1521        let app_state = init_test(cx);
1522
1523        app_state
1524            .fs
1525            .as_fake()
1526            .insert_tree(
1527                "/src",
1528                json!({
1529                    "test": {
1530                        "first.rs": "// First Rust file",
1531                        "second.rs": "// Second Rust file",
1532                        "third.rs": "// Third Rust file",
1533                        "fourth.rs": "// Fourth Rust file",
1534                    }
1535                }),
1536            )
1537            .await;
1538
1539        let project = Project::test(app_state.fs.clone(), ["/src".as_ref()], cx).await;
1540        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project, cx));
1541        let worktree_id = cx.read(|cx| {
1542            let worktrees = workspace.read(cx).worktrees(cx).collect::<Vec<_>>();
1543            assert_eq!(worktrees.len(), 1,);
1544
1545            WorktreeId::from_usize(worktrees[0].entity_id().as_u64() as usize)
1546        });
1547
1548        // generate some history to select from
1549        open_close_queried_buffer("fir", 1, "first.rs", &workspace, cx).await;
1550        open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
1551        open_close_queried_buffer("thi", 1, "third.rs", &workspace, cx).await;
1552        open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
1553
1554        let finder = open_file_picker(&workspace, cx);
1555        let first_query = "f";
1556        finder
1557            .update(cx, |finder, cx| {
1558                finder.delegate.update_matches(first_query.to_string(), cx)
1559            })
1560            .await;
1561        finder.update(cx, |finder, _| {
1562            let delegate = &finder.delegate;
1563            assert_eq!(delegate.matches.history.len(), 1, "Only one history item contains {first_query}, it should be present and others should be filtered out");
1564            let history_match = delegate.matches.history.first().unwrap();
1565            assert!(history_match.1.is_some(), "Should have path matches for history items after querying");
1566            assert_eq!(history_match.0, FoundPath::new(
1567                ProjectPath {
1568                    worktree_id,
1569                    path: Arc::from(Path::new("test/first.rs")),
1570                },
1571                Some(PathBuf::from("/src/test/first.rs"))
1572            ));
1573            assert_eq!(delegate.matches.search.len(), 1, "Only one non-history item contains {first_query}, it should be present");
1574            assert_eq!(delegate.matches.search.first().unwrap().path.as_ref(), Path::new("test/fourth.rs"));
1575        });
1576
1577        let second_query = "fsdasdsa";
1578        let finder = active_file_picker(&workspace, cx);
1579        finder
1580            .update(cx, |finder, cx| {
1581                finder.delegate.update_matches(second_query.to_string(), cx)
1582            })
1583            .await;
1584        finder.update(cx, |finder, _| {
1585            let delegate = &finder.delegate;
1586            assert!(
1587                delegate.matches.history.is_empty(),
1588                "No history entries should match {second_query}"
1589            );
1590            assert!(
1591                delegate.matches.search.is_empty(),
1592                "No search entries should match {second_query}"
1593            );
1594        });
1595
1596        let first_query_again = first_query;
1597
1598        let finder = active_file_picker(&workspace, cx);
1599        finder
1600            .update(cx, |finder, cx| {
1601                finder
1602                    .delegate
1603                    .update_matches(first_query_again.to_string(), cx)
1604            })
1605            .await;
1606        finder.update(cx, |finder, _| {
1607            let delegate = &finder.delegate;
1608            assert_eq!(delegate.matches.history.len(), 1, "Only one history item contains {first_query_again}, it should be present and others should be filtered out, even after non-matching query");
1609            let history_match = delegate.matches.history.first().unwrap();
1610            assert!(history_match.1.is_some(), "Should have path matches for history items after querying");
1611            assert_eq!(history_match.0, FoundPath::new(
1612                ProjectPath {
1613                    worktree_id,
1614                    path: Arc::from(Path::new("test/first.rs")),
1615                },
1616                Some(PathBuf::from("/src/test/first.rs"))
1617            ));
1618            assert_eq!(delegate.matches.search.len(), 1, "Only one non-history item contains {first_query_again}, it should be present, even after non-matching query");
1619            assert_eq!(delegate.matches.search.first().unwrap().path.as_ref(), Path::new("test/fourth.rs"));
1620        });
1621    }
1622
1623    #[gpui::test]
1624    async fn test_history_items_vs_very_good_external_match(cx: &mut gpui::TestAppContext) {
1625        let app_state = init_test(cx);
1626
1627        app_state
1628            .fs
1629            .as_fake()
1630            .insert_tree(
1631                "/src",
1632                json!({
1633                    "collab_ui": {
1634                        "first.rs": "// First Rust file",
1635                        "second.rs": "// Second Rust file",
1636                        "third.rs": "// Third Rust file",
1637                        "collab_ui.rs": "// Fourth Rust file",
1638                    }
1639                }),
1640            )
1641            .await;
1642
1643        let project = Project::test(app_state.fs.clone(), ["/src".as_ref()], cx).await;
1644        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project, cx));
1645        // generate some history to select from
1646        open_close_queried_buffer("fir", 1, "first.rs", &workspace, cx).await;
1647        open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
1648        open_close_queried_buffer("thi", 1, "third.rs", &workspace, cx).await;
1649        open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
1650
1651        let finder = open_file_picker(&workspace, cx);
1652        let query = "collab_ui";
1653        cx.simulate_input(query);
1654        finder.update(cx, |finder, _| {
1655            let delegate = &finder.delegate;
1656            assert!(
1657                delegate.matches.history.is_empty(),
1658                "History items should not math query {query}, they should be matched by name only"
1659            );
1660
1661            let search_entries = delegate
1662                .matches
1663                .search
1664                .iter()
1665                .map(|path_match| path_match.path.to_path_buf())
1666                .collect::<Vec<_>>();
1667            assert_eq!(
1668                search_entries,
1669                vec![
1670                    PathBuf::from("collab_ui/collab_ui.rs"),
1671                    PathBuf::from("collab_ui/third.rs"),
1672                    PathBuf::from("collab_ui/first.rs"),
1673                    PathBuf::from("collab_ui/second.rs"),
1674                ],
1675                "Despite all search results having the same directory name, the most matching one should be on top"
1676            );
1677        });
1678    }
1679
1680    #[gpui::test]
1681    async fn test_nonexistent_history_items_not_shown(cx: &mut gpui::TestAppContext) {
1682        let app_state = init_test(cx);
1683
1684        app_state
1685            .fs
1686            .as_fake()
1687            .insert_tree(
1688                "/src",
1689                json!({
1690                    "test": {
1691                        "first.rs": "// First Rust file",
1692                        "nonexistent.rs": "// Second Rust file",
1693                        "third.rs": "// Third Rust file",
1694                    }
1695                }),
1696            )
1697            .await;
1698
1699        let project = Project::test(app_state.fs.clone(), ["/src".as_ref()], cx).await;
1700        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project, cx)); // generate some history to select from
1701        open_close_queried_buffer("fir", 1, "first.rs", &workspace, cx).await;
1702        open_close_queried_buffer("non", 1, "nonexistent.rs", &workspace, cx).await;
1703        open_close_queried_buffer("thi", 1, "third.rs", &workspace, cx).await;
1704        open_close_queried_buffer("fir", 1, "first.rs", &workspace, cx).await;
1705
1706        let picker = open_file_picker(&workspace, cx);
1707        cx.simulate_input("rs");
1708
1709        picker.update(cx, |finder, _| {
1710            let history_entries = finder.delegate
1711                .matches
1712                .history
1713                .iter()
1714                .map(|(_, path_match)| path_match.as_ref().expect("should have a path match").path.to_path_buf())
1715                .collect::<Vec<_>>();
1716            assert_eq!(
1717                history_entries,
1718                vec![
1719                    PathBuf::from("test/first.rs"),
1720                    PathBuf::from("test/third.rs"),
1721                ],
1722                "Should have all opened files in the history, except the ones that do not exist on disk"
1723            );
1724        });
1725    }
1726
1727    async fn open_close_queried_buffer(
1728        input: &str,
1729        expected_matches: usize,
1730        expected_editor_title: &str,
1731        workspace: &View<Workspace>,
1732        cx: &mut gpui::VisualTestContext<'_>,
1733    ) -> Vec<FoundPath> {
1734        let picker = open_file_picker(&workspace, cx);
1735        cx.simulate_input(input);
1736
1737        let history_items = picker.update(cx, |finder, _| {
1738            assert_eq!(
1739                finder.delegate.matches.len(),
1740                expected_matches,
1741                "Unexpected number of matches found for query {input}"
1742            );
1743            finder.delegate.history_items.clone()
1744        });
1745
1746        cx.dispatch_action(SelectNext);
1747        cx.dispatch_action(Confirm);
1748
1749        cx.read(|cx| {
1750            let active_editor = workspace.read(cx).active_item_as::<Editor>(cx).unwrap();
1751            let active_editor_title = active_editor.read(cx).title(cx);
1752            assert_eq!(
1753                expected_editor_title, active_editor_title,
1754                "Unexpected editor title for query {input}"
1755            );
1756        });
1757
1758        cx.dispatch_action(workspace::CloseActiveItem { save_intent: None });
1759
1760        history_items
1761    }
1762
1763    fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
1764        cx.update(|cx| {
1765            let state = AppState::test(cx);
1766            theme::init(theme::LoadThemes::JustBase, cx);
1767            language::init(cx);
1768            super::init(cx);
1769            editor::init(cx);
1770            workspace::init_settings(cx);
1771            Project::init_settings(cx);
1772            state
1773        })
1774    }
1775
1776    fn test_path_like(test_str: &str) -> PathLikeWithPosition<FileSearchQuery> {
1777        PathLikeWithPosition::parse_str(test_str, |path_like_str| {
1778            Ok::<_, std::convert::Infallible>(FileSearchQuery {
1779                raw_query: test_str.to_owned(),
1780                file_query_end: if path_like_str == test_str {
1781                    None
1782                } else {
1783                    Some(path_like_str.len())
1784                },
1785            })
1786        })
1787        .unwrap()
1788    }
1789
1790    fn build_find_picker(
1791        project: Model<Project>,
1792        cx: &mut TestAppContext,
1793    ) -> (
1794        View<Picker<FileFinderDelegate>>,
1795        View<Workspace>,
1796        &mut VisualTestContext,
1797    ) {
1798        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project, cx));
1799        let picker = open_file_picker(&workspace, cx);
1800        (picker, workspace, cx)
1801    }
1802
1803    #[track_caller]
1804    fn open_file_picker(
1805        workspace: &View<Workspace>,
1806        cx: &mut VisualTestContext,
1807    ) -> View<Picker<FileFinderDelegate>> {
1808        cx.dispatch_action(Toggle);
1809        active_file_picker(workspace, cx)
1810    }
1811
1812    #[track_caller]
1813    fn active_file_picker(
1814        workspace: &View<Workspace>,
1815        cx: &mut VisualTestContext,
1816    ) -> View<Picker<FileFinderDelegate>> {
1817        workspace.update(cx, |workspace, cx| {
1818            workspace
1819                .active_modal::<FileFinder>(cx)
1820                .unwrap()
1821                .read(cx)
1822                .picker
1823                .clone()
1824        })
1825    }
1826}