file_finder.rs

   1#[cfg(test)]
   2mod file_finder_tests;
   3
   4use collections::{HashMap, HashSet};
   5use editor::{scroll::Autoscroll, Bias, Editor};
   6use fuzzy::{CharBag, PathMatch, PathMatchCandidate};
   7use gpui::{
   8    actions, rems, Action, AppContext, DismissEvent, EventEmitter, FocusHandle, FocusableView,
   9    Model, Modifiers, ModifiersChangedEvent, ParentElement, Render, Styled, Task, View,
  10    ViewContext, VisualContext, WeakView,
  11};
  12use itertools::Itertools;
  13use picker::{Picker, PickerDelegate};
  14use project::{PathMatchCandidateSet, Project, ProjectPath, WorktreeId};
  15use std::{
  16    cmp,
  17    path::{Path, PathBuf},
  18    sync::{
  19        atomic::{self, AtomicBool},
  20        Arc,
  21    },
  22};
  23use text::Point;
  24use ui::{prelude::*, HighlightedLabel, ListItem, ListItemSpacing};
  25use util::{paths::PathLikeWithPosition, post_inc, ResultExt};
  26use workspace::{ModalView, Workspace};
  27
  28actions!(file_finder, [Toggle, SelectPrev]);
  29
  30impl ModalView for FileFinder {}
  31
  32pub struct FileFinder {
  33    picker: View<Picker<FileFinderDelegate>>,
  34    init_modifiers: Option<Modifiers>,
  35}
  36
  37pub fn init(cx: &mut AppContext) {
  38    cx.observe_new_views(FileFinder::register).detach();
  39}
  40
  41impl FileFinder {
  42    fn register(workspace: &mut Workspace, _: &mut ViewContext<Workspace>) {
  43        workspace.register_action(|workspace, _: &Toggle, cx| {
  44            let Some(file_finder) = workspace.active_modal::<Self>(cx) else {
  45                Self::open(workspace, cx);
  46                return;
  47            };
  48
  49            file_finder.update(cx, |file_finder, cx| {
  50                file_finder.init_modifiers = Some(cx.modifiers());
  51                file_finder.picker.update(cx, |picker, cx| {
  52                    picker.cycle_selection(cx);
  53                });
  54            });
  55        });
  56    }
  57
  58    fn open(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {
  59        let project = workspace.project().read(cx);
  60
  61        let currently_opened_path = workspace
  62            .active_item(cx)
  63            .and_then(|item| item.project_path(cx))
  64            .map(|project_path| {
  65                let abs_path = project
  66                    .worktree_for_id(project_path.worktree_id, cx)
  67                    .map(|worktree| worktree.read(cx).abs_path().join(&project_path.path));
  68                FoundPath::new(project_path, abs_path)
  69            });
  70
  71        let history_items = workspace
  72            .recent_navigation_history(Some(MAX_RECENT_SELECTIONS), cx)
  73            .into_iter()
  74            .filter(|(_, history_abs_path)| match history_abs_path {
  75                Some(abs_path) => history_file_exists(abs_path),
  76                None => true,
  77            })
  78            .map(|(history_path, abs_path)| FoundPath::new(history_path, abs_path))
  79            .collect::<Vec<_>>();
  80
  81        let project = workspace.project().clone();
  82        let weak_workspace = cx.view().downgrade();
  83        workspace.toggle_modal(cx, |cx| {
  84            let delegate = FileFinderDelegate::new(
  85                cx.view().downgrade(),
  86                weak_workspace,
  87                project,
  88                currently_opened_path,
  89                history_items,
  90                cx,
  91            );
  92
  93            FileFinder::new(delegate, cx)
  94        });
  95    }
  96
  97    fn new(delegate: FileFinderDelegate, cx: &mut ViewContext<Self>) -> Self {
  98        Self {
  99            picker: cx.new_view(|cx| Picker::uniform_list(delegate, cx)),
 100            init_modifiers: cx.modifiers().modified().then_some(cx.modifiers()),
 101        }
 102    }
 103
 104    fn handle_modifiers_changed(
 105        &mut self,
 106        event: &ModifiersChangedEvent,
 107        cx: &mut ViewContext<Self>,
 108    ) {
 109        let Some(init_modifiers) = self.init_modifiers.take() else {
 110            return;
 111        };
 112        if self.picker.read(cx).delegate.has_changed_selected_index {
 113            if !event.modified() || !init_modifiers.is_subset_of(&event) {
 114                self.init_modifiers = None;
 115                cx.dispatch_action(menu::Confirm.boxed_clone());
 116            }
 117        }
 118    }
 119
 120    fn handle_select_prev(&mut self, _: &SelectPrev, cx: &mut ViewContext<Self>) {
 121        self.init_modifiers = Some(cx.modifiers());
 122        cx.dispatch_action(Box::new(menu::SelectPrev));
 123    }
 124}
 125
 126impl EventEmitter<DismissEvent> for FileFinder {}
 127
 128impl FocusableView for FileFinder {
 129    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
 130        self.picker.focus_handle(cx)
 131    }
 132}
 133
 134impl Render for FileFinder {
 135    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
 136        v_flex()
 137            .key_context("FileFinder")
 138            .w(rems(34.))
 139            .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
 140            .on_action(cx.listener(Self::handle_select_prev))
 141            .child(self.picker.clone())
 142    }
 143}
 144
 145pub struct FileFinderDelegate {
 146    file_finder: WeakView<FileFinder>,
 147    workspace: WeakView<Workspace>,
 148    project: Model<Project>,
 149    search_count: usize,
 150    latest_search_id: usize,
 151    latest_search_did_cancel: bool,
 152    latest_search_query: Option<PathLikeWithPosition<FileSearchQuery>>,
 153    currently_opened_path: Option<FoundPath>,
 154    matches: Matches,
 155    selected_index: usize,
 156    has_changed_selected_index: bool,
 157    cancel_flag: Arc<AtomicBool>,
 158    history_items: Vec<FoundPath>,
 159}
 160
 161/// Use a custom ordering for file finder: the regular one
 162/// defines max element with the highest score and the latest alphanumerical path (in case of a tie on other params), e.g:
 163/// `[{score: 0.5, path = "c/d" }, { score: 0.5, path = "/a/b" }]`
 164///
 165/// In the file finder, we would prefer to have the max element with the highest score and the earliest alphanumerical path, e.g:
 166/// `[{ score: 0.5, path = "/a/b" }, {score: 0.5, path = "c/d" }]`
 167/// as the files are shown in the project panel lists.
 168#[derive(Debug, Clone, PartialEq, Eq)]
 169struct ProjectPanelOrdMatch(PathMatch);
 170
 171impl Ord for ProjectPanelOrdMatch {
 172    fn cmp(&self, other: &Self) -> cmp::Ordering {
 173        self.0
 174            .score
 175            .partial_cmp(&other.0.score)
 176            .unwrap_or(cmp::Ordering::Equal)
 177            .then_with(|| self.0.worktree_id.cmp(&other.0.worktree_id))
 178            .then_with(|| {
 179                other
 180                    .0
 181                    .distance_to_relative_ancestor
 182                    .cmp(&self.0.distance_to_relative_ancestor)
 183            })
 184            .then_with(|| self.0.path.cmp(&other.0.path).reverse())
 185    }
 186}
 187
 188impl PartialOrd for ProjectPanelOrdMatch {
 189    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
 190        Some(self.cmp(other))
 191    }
 192}
 193
 194#[derive(Debug, Default)]
 195struct Matches {
 196    history: Vec<(FoundPath, Option<ProjectPanelOrdMatch>)>,
 197    search: Vec<ProjectPanelOrdMatch>,
 198}
 199
 200#[derive(Debug)]
 201enum Match<'a> {
 202    History(&'a FoundPath, Option<&'a ProjectPanelOrdMatch>),
 203    Search(&'a ProjectPanelOrdMatch),
 204}
 205
 206impl Matches {
 207    fn len(&self) -> usize {
 208        self.history.len() + self.search.len()
 209    }
 210
 211    fn get(&self, index: usize) -> Option<Match<'_>> {
 212        if index < self.history.len() {
 213            self.history
 214                .get(index)
 215                .map(|(path, path_match)| Match::History(path, path_match.as_ref()))
 216        } else {
 217            self.search
 218                .get(index - self.history.len())
 219                .map(Match::Search)
 220        }
 221    }
 222
 223    fn push_new_matches(
 224        &mut self,
 225        history_items: &Vec<FoundPath>,
 226        currently_opened: Option<&FoundPath>,
 227        query: &PathLikeWithPosition<FileSearchQuery>,
 228        new_search_matches: impl Iterator<Item = ProjectPanelOrdMatch>,
 229        extend_old_matches: bool,
 230    ) {
 231        let matching_history_paths =
 232            matching_history_item_paths(history_items, currently_opened, query);
 233        let new_search_matches = new_search_matches
 234            .filter(|path_match| !matching_history_paths.contains_key(&path_match.0.path));
 235
 236        self.set_new_history(
 237            currently_opened,
 238            Some(&matching_history_paths),
 239            history_items,
 240        );
 241        if extend_old_matches {
 242            self.search
 243                .retain(|path_match| !matching_history_paths.contains_key(&path_match.0.path));
 244        } else {
 245            self.search.clear();
 246        }
 247        util::extend_sorted(&mut self.search, new_search_matches, 100, |a, b| b.cmp(a));
 248    }
 249
 250    fn set_new_history<'a>(
 251        &mut self,
 252        currently_opened: Option<&'a FoundPath>,
 253        query_matches: Option<&'a HashMap<Arc<Path>, ProjectPanelOrdMatch>>,
 254        history_items: impl IntoIterator<Item = &'a FoundPath> + 'a,
 255    ) {
 256        let mut processed_paths = HashSet::default();
 257        self.history = history_items
 258            .into_iter()
 259            .chain(currently_opened)
 260            .filter(|&path| processed_paths.insert(path))
 261            .filter_map(|history_item| match &query_matches {
 262                Some(query_matches) => Some((
 263                    history_item.clone(),
 264                    Some(query_matches.get(&history_item.project.path)?.clone()),
 265                )),
 266                None => Some((history_item.clone(), None)),
 267            })
 268            .enumerate()
 269            .sorted_by(
 270                |(index_a, (path_a, match_a)), (index_b, (path_b, match_b))| match (
 271                    Some(path_a) == currently_opened,
 272                    Some(path_b) == currently_opened,
 273                ) {
 274                    // bubble currently opened files to the top
 275                    (true, false) => cmp::Ordering::Less,
 276                    (false, true) => cmp::Ordering::Greater,
 277                    // arrange the files by their score (best score on top) and by their occurrence in the history
 278                    // (history items visited later are on the top)
 279                    _ => match_b.cmp(match_a).then(index_a.cmp(index_b)),
 280                },
 281            )
 282            .map(|(_, paths)| paths)
 283            .collect();
 284    }
 285}
 286
 287fn matching_history_item_paths(
 288    history_items: &Vec<FoundPath>,
 289    currently_opened: Option<&FoundPath>,
 290    query: &PathLikeWithPosition<FileSearchQuery>,
 291) -> HashMap<Arc<Path>, ProjectPanelOrdMatch> {
 292    let history_items_by_worktrees = history_items
 293        .iter()
 294        .chain(currently_opened)
 295        .filter_map(|found_path| {
 296            let candidate = PathMatchCandidate {
 297                path: &found_path.project.path,
 298                // Only match history items names, otherwise their paths may match too many queries, producing false positives.
 299                // E.g. `foo` would match both `something/foo/bar.rs` and `something/foo/foo.rs` and if the former is a history item,
 300                // it would be shown first always, despite the latter being a better match.
 301                char_bag: CharBag::from_iter(
 302                    found_path
 303                        .project
 304                        .path
 305                        .file_name()?
 306                        .to_string_lossy()
 307                        .to_lowercase()
 308                        .chars(),
 309                ),
 310            };
 311            Some((found_path.project.worktree_id, candidate))
 312        })
 313        .fold(
 314            HashMap::default(),
 315            |mut candidates, (worktree_id, new_candidate)| {
 316                candidates
 317                    .entry(worktree_id)
 318                    .or_insert_with(Vec::new)
 319                    .push(new_candidate);
 320                candidates
 321            },
 322        );
 323    let mut matching_history_paths = HashMap::default();
 324    for (worktree, candidates) in history_items_by_worktrees {
 325        let max_results = candidates.len() + 1;
 326        matching_history_paths.extend(
 327            fuzzy::match_fixed_path_set(
 328                candidates,
 329                worktree.to_usize(),
 330                query.path_like.path_query(),
 331                false,
 332                max_results,
 333            )
 334            .into_iter()
 335            .map(|path_match| {
 336                (
 337                    Arc::clone(&path_match.path),
 338                    ProjectPanelOrdMatch(path_match),
 339                )
 340            }),
 341        );
 342    }
 343    matching_history_paths
 344}
 345
 346#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
 347struct FoundPath {
 348    project: ProjectPath,
 349    absolute: Option<PathBuf>,
 350}
 351
 352impl FoundPath {
 353    fn new(project: ProjectPath, absolute: Option<PathBuf>) -> Self {
 354        Self { project, absolute }
 355    }
 356}
 357
 358const MAX_RECENT_SELECTIONS: usize = 20;
 359
 360#[cfg(not(test))]
 361fn history_file_exists(abs_path: &PathBuf) -> bool {
 362    abs_path.exists()
 363}
 364
 365#[cfg(test)]
 366fn history_file_exists(abs_path: &PathBuf) -> bool {
 367    !abs_path.ends_with("nonexistent.rs")
 368}
 369
 370pub enum Event {
 371    Selected(ProjectPath),
 372    Dismissed,
 373}
 374
 375#[derive(Debug, Clone)]
 376struct FileSearchQuery {
 377    raw_query: String,
 378    file_query_end: Option<usize>,
 379}
 380
 381impl FileSearchQuery {
 382    fn path_query(&self) -> &str {
 383        match self.file_query_end {
 384            Some(file_path_end) => &self.raw_query[..file_path_end],
 385            None => &self.raw_query,
 386        }
 387    }
 388}
 389
 390impl FileFinderDelegate {
 391    fn new(
 392        file_finder: WeakView<FileFinder>,
 393        workspace: WeakView<Workspace>,
 394        project: Model<Project>,
 395        currently_opened_path: Option<FoundPath>,
 396        history_items: Vec<FoundPath>,
 397        cx: &mut ViewContext<FileFinder>,
 398    ) -> Self {
 399        Self::subscribe_to_updates(&project, cx);
 400        Self {
 401            file_finder,
 402            workspace,
 403            project,
 404            search_count: 0,
 405            latest_search_id: 0,
 406            latest_search_did_cancel: false,
 407            latest_search_query: None,
 408            currently_opened_path,
 409            matches: Matches::default(),
 410            has_changed_selected_index: false,
 411            selected_index: 0,
 412            cancel_flag: Arc::new(AtomicBool::new(false)),
 413            history_items,
 414        }
 415    }
 416
 417    fn subscribe_to_updates(project: &Model<Project>, cx: &mut ViewContext<FileFinder>) {
 418        cx.subscribe(project, |file_finder, _, event, cx| {
 419            match event {
 420                project::Event::WorktreeUpdatedEntries(_, _)
 421                | project::Event::WorktreeAdded
 422                | project::Event::WorktreeRemoved(_) => file_finder
 423                    .picker
 424                    .update(cx, |picker, cx| picker.refresh(cx)),
 425                _ => {}
 426            };
 427        })
 428        .detach();
 429    }
 430
 431    fn spawn_search(
 432        &mut self,
 433        query: PathLikeWithPosition<FileSearchQuery>,
 434        cx: &mut ViewContext<Picker<Self>>,
 435    ) -> Task<()> {
 436        let relative_to = self
 437            .currently_opened_path
 438            .as_ref()
 439            .map(|found_path| Arc::clone(&found_path.project.path));
 440        let worktrees = self
 441            .project
 442            .read(cx)
 443            .visible_worktrees(cx)
 444            .collect::<Vec<_>>();
 445        let include_root_name = worktrees.len() > 1;
 446        let candidate_sets = worktrees
 447            .into_iter()
 448            .map(|worktree| {
 449                let worktree = worktree.read(cx);
 450                PathMatchCandidateSet {
 451                    snapshot: worktree.snapshot(),
 452                    include_ignored: worktree
 453                        .root_entry()
 454                        .map_or(false, |entry| entry.is_ignored),
 455                    include_root_name,
 456                }
 457            })
 458            .collect::<Vec<_>>();
 459
 460        let search_id = util::post_inc(&mut self.search_count);
 461        self.cancel_flag.store(true, atomic::Ordering::Relaxed);
 462        self.cancel_flag = Arc::new(AtomicBool::new(false));
 463        let cancel_flag = self.cancel_flag.clone();
 464        cx.spawn(|picker, mut cx| async move {
 465            let matches = fuzzy::match_path_sets(
 466                candidate_sets.as_slice(),
 467                query.path_like.path_query(),
 468                relative_to,
 469                false,
 470                100,
 471                &cancel_flag,
 472                cx.background_executor().clone(),
 473            )
 474            .await
 475            .into_iter()
 476            .map(ProjectPanelOrdMatch);
 477            let did_cancel = cancel_flag.load(atomic::Ordering::Relaxed);
 478            picker
 479                .update(&mut cx, |picker, cx| {
 480                    picker
 481                        .delegate
 482                        .set_search_matches(search_id, did_cancel, query, matches, cx)
 483                })
 484                .log_err();
 485        })
 486    }
 487
 488    fn set_search_matches(
 489        &mut self,
 490        search_id: usize,
 491        did_cancel: bool,
 492        query: PathLikeWithPosition<FileSearchQuery>,
 493        matches: impl IntoIterator<Item = ProjectPanelOrdMatch>,
 494        cx: &mut ViewContext<Picker<Self>>,
 495    ) {
 496        if search_id >= self.latest_search_id {
 497            self.latest_search_id = search_id;
 498            let extend_old_matches = self.latest_search_did_cancel
 499                && Some(query.path_like.path_query())
 500                    == self
 501                        .latest_search_query
 502                        .as_ref()
 503                        .map(|query| query.path_like.path_query());
 504            self.matches.push_new_matches(
 505                &self.history_items,
 506                self.currently_opened_path.as_ref(),
 507                &query,
 508                matches.into_iter(),
 509                extend_old_matches,
 510            );
 511            self.latest_search_query = Some(query);
 512            self.latest_search_did_cancel = did_cancel;
 513            self.selected_index = self.calculate_selected_index();
 514            cx.notify();
 515        }
 516    }
 517
 518    fn labels_for_match(
 519        &self,
 520        path_match: Match,
 521        cx: &AppContext,
 522        ix: usize,
 523    ) -> (String, Vec<usize>, String, Vec<usize>) {
 524        let (file_name, file_name_positions, full_path, full_path_positions) = match path_match {
 525            Match::History(found_path, found_path_match) => {
 526                let worktree_id = found_path.project.worktree_id;
 527                let project_relative_path = &found_path.project.path;
 528                let has_worktree = self
 529                    .project
 530                    .read(cx)
 531                    .worktree_for_id(worktree_id, cx)
 532                    .is_some();
 533
 534                if !has_worktree {
 535                    if let Some(absolute_path) = &found_path.absolute {
 536                        return (
 537                            absolute_path
 538                                .file_name()
 539                                .map_or_else(
 540                                    || project_relative_path.to_string_lossy(),
 541                                    |file_name| file_name.to_string_lossy(),
 542                                )
 543                                .to_string(),
 544                            Vec::new(),
 545                            absolute_path.to_string_lossy().to_string(),
 546                            Vec::new(),
 547                        );
 548                    }
 549                }
 550
 551                let mut path = Arc::clone(project_relative_path);
 552                if project_relative_path.as_ref() == Path::new("") {
 553                    if let Some(absolute_path) = &found_path.absolute {
 554                        path = Arc::from(absolute_path.as_path());
 555                    }
 556                }
 557
 558                let mut path_match = PathMatch {
 559                    score: ix as f64,
 560                    positions: Vec::new(),
 561                    worktree_id: worktree_id.to_usize(),
 562                    path,
 563                    path_prefix: "".into(),
 564                    distance_to_relative_ancestor: usize::MAX,
 565                };
 566                if let Some(found_path_match) = found_path_match {
 567                    path_match
 568                        .positions
 569                        .extend(found_path_match.0.positions.iter())
 570                }
 571
 572                self.labels_for_path_match(&path_match)
 573            }
 574            Match::Search(path_match) => self.labels_for_path_match(&path_match.0),
 575        };
 576
 577        if file_name_positions.is_empty() {
 578            if let Some(user_home_path) = std::env::var("HOME").ok() {
 579                let user_home_path = user_home_path.trim();
 580                if !user_home_path.is_empty() {
 581                    if (&full_path).starts_with(user_home_path) {
 582                        return (
 583                            file_name,
 584                            file_name_positions,
 585                            full_path.replace(user_home_path, "~"),
 586                            full_path_positions,
 587                        );
 588                    }
 589                }
 590            }
 591        }
 592
 593        (
 594            file_name,
 595            file_name_positions,
 596            full_path,
 597            full_path_positions,
 598        )
 599    }
 600
 601    fn labels_for_path_match(
 602        &self,
 603        path_match: &PathMatch,
 604    ) -> (String, Vec<usize>, String, Vec<usize>) {
 605        let path = &path_match.path;
 606        let path_string = path.to_string_lossy();
 607        let full_path = [path_match.path_prefix.as_ref(), path_string.as_ref()].join("");
 608        let mut path_positions = path_match.positions.clone();
 609
 610        let file_name = path.file_name().map_or_else(
 611            || path_match.path_prefix.to_string(),
 612            |file_name| file_name.to_string_lossy().to_string(),
 613        );
 614        let file_name_start = path_match.path_prefix.len() + path_string.len() - file_name.len();
 615        let file_name_positions = path_positions
 616            .iter()
 617            .filter_map(|pos| {
 618                if pos >= &file_name_start {
 619                    Some(pos - file_name_start)
 620                } else {
 621                    None
 622                }
 623            })
 624            .collect();
 625
 626        let full_path = full_path.trim_end_matches(&file_name).to_string();
 627        path_positions.retain(|idx| *idx < full_path.len());
 628
 629        (file_name, file_name_positions, full_path, path_positions)
 630    }
 631
 632    fn lookup_absolute_path(
 633        &self,
 634        query: PathLikeWithPosition<FileSearchQuery>,
 635        cx: &mut ViewContext<'_, Picker<Self>>,
 636    ) -> Task<()> {
 637        cx.spawn(|picker, mut cx| async move {
 638            let Some((project, fs)) = picker
 639                .update(&mut cx, |picker, cx| {
 640                    let fs = Arc::clone(&picker.delegate.project.read(cx).fs());
 641                    (picker.delegate.project.clone(), fs)
 642                })
 643                .log_err()
 644            else {
 645                return;
 646            };
 647
 648            let query_path = Path::new(query.path_like.path_query());
 649            let mut path_matches = Vec::new();
 650            match fs.metadata(query_path).await.log_err() {
 651                Some(Some(_metadata)) => {
 652                    let update_result = project
 653                        .update(&mut cx, |project, cx| {
 654                            if let Some((worktree, relative_path)) =
 655                                project.find_local_worktree(query_path, cx)
 656                            {
 657                                path_matches.push(ProjectPanelOrdMatch(PathMatch {
 658                                    score: 1.0,
 659                                    positions: Vec::new(),
 660                                    worktree_id: worktree.read(cx).id().to_usize(),
 661                                    path: Arc::from(relative_path),
 662                                    path_prefix: "".into(),
 663                                    distance_to_relative_ancestor: usize::MAX,
 664                                }));
 665                            }
 666                        })
 667                        .log_err();
 668                    if update_result.is_none() {
 669                        return;
 670                    }
 671                }
 672                Some(None) => {}
 673                None => return,
 674            }
 675
 676            picker
 677                .update(&mut cx, |picker, cx| {
 678                    let picker_delegate = &mut picker.delegate;
 679                    let search_id = util::post_inc(&mut picker_delegate.search_count);
 680                    picker_delegate.set_search_matches(search_id, false, query, path_matches, cx);
 681
 682                    anyhow::Ok(())
 683                })
 684                .log_err();
 685        })
 686    }
 687
 688    /// Skips first history match (that is displayed topmost) if it's currently opened.
 689    fn calculate_selected_index(&self) -> usize {
 690        if let Some(Match::History(path, _)) = self.matches.get(0) {
 691            if Some(path) == self.currently_opened_path.as_ref() {
 692                let elements_after_first = self.matches.len() - 1;
 693                if elements_after_first > 0 {
 694                    return 1;
 695                }
 696            }
 697        }
 698        0
 699    }
 700}
 701
 702impl PickerDelegate for FileFinderDelegate {
 703    type ListItem = ListItem;
 704
 705    fn placeholder_text(&self, _cx: &mut WindowContext) -> Arc<str> {
 706        "Search project files...".into()
 707    }
 708
 709    fn match_count(&self) -> usize {
 710        self.matches.len()
 711    }
 712
 713    fn selected_index(&self) -> usize {
 714        self.selected_index
 715    }
 716
 717    fn set_selected_index(&mut self, ix: usize, cx: &mut ViewContext<Picker<Self>>) {
 718        self.has_changed_selected_index = true;
 719        self.selected_index = ix;
 720        cx.notify();
 721    }
 722
 723    fn separators_after_indices(&self) -> Vec<usize> {
 724        let history_items = self.matches.history.len();
 725        if history_items == 0 || self.matches.search.is_empty() {
 726            Vec::new()
 727        } else {
 728            vec![history_items - 1]
 729        }
 730    }
 731
 732    fn update_matches(
 733        &mut self,
 734        raw_query: String,
 735        cx: &mut ViewContext<Picker<Self>>,
 736    ) -> Task<()> {
 737        let raw_query = raw_query.replace(' ', "");
 738        let raw_query = raw_query.trim();
 739        if raw_query.is_empty() {
 740            let project = self.project.read(cx);
 741            self.latest_search_id = post_inc(&mut self.search_count);
 742            self.matches = Matches {
 743                history: Vec::new(),
 744                search: Vec::new(),
 745            };
 746            self.matches.set_new_history(
 747                self.currently_opened_path.as_ref(),
 748                None,
 749                self.history_items.iter().filter(|history_item| {
 750                    project
 751                        .worktree_for_id(history_item.project.worktree_id, cx)
 752                        .is_some()
 753                        || (project.is_local() && history_item.absolute.is_some())
 754                }),
 755            );
 756
 757            self.selected_index = 0;
 758            cx.notify();
 759            Task::ready(())
 760        } else {
 761            let query = PathLikeWithPosition::parse_str(raw_query, |path_like_str| {
 762                Ok::<_, std::convert::Infallible>(FileSearchQuery {
 763                    raw_query: raw_query.to_owned(),
 764                    file_query_end: if path_like_str == raw_query {
 765                        None
 766                    } else {
 767                        Some(path_like_str.len())
 768                    },
 769                })
 770            })
 771            .expect("infallible");
 772
 773            if Path::new(query.path_like.path_query()).is_absolute() {
 774                self.lookup_absolute_path(query, cx)
 775            } else {
 776                self.spawn_search(query, cx)
 777            }
 778        }
 779    }
 780
 781    fn confirm(&mut self, secondary: bool, cx: &mut ViewContext<Picker<FileFinderDelegate>>) {
 782        if let Some(m) = self.matches.get(self.selected_index()) {
 783            if let Some(workspace) = self.workspace.upgrade() {
 784                let open_task = workspace.update(cx, move |workspace, cx| {
 785                    let split_or_open = |workspace: &mut Workspace, project_path, cx| {
 786                        if secondary {
 787                            workspace.split_path(project_path, cx)
 788                        } else {
 789                            workspace.open_path(project_path, None, true, cx)
 790                        }
 791                    };
 792                    match m {
 793                        Match::History(history_match, _) => {
 794                            let worktree_id = history_match.project.worktree_id;
 795                            if workspace
 796                                .project()
 797                                .read(cx)
 798                                .worktree_for_id(worktree_id, cx)
 799                                .is_some()
 800                            {
 801                                split_or_open(
 802                                    workspace,
 803                                    ProjectPath {
 804                                        worktree_id,
 805                                        path: Arc::clone(&history_match.project.path),
 806                                    },
 807                                    cx,
 808                                )
 809                            } else {
 810                                match history_match.absolute.as_ref() {
 811                                    Some(abs_path) => {
 812                                        if secondary {
 813                                            workspace.split_abs_path(
 814                                                abs_path.to_path_buf(),
 815                                                false,
 816                                                cx,
 817                                            )
 818                                        } else {
 819                                            workspace.open_abs_path(
 820                                                abs_path.to_path_buf(),
 821                                                false,
 822                                                cx,
 823                                            )
 824                                        }
 825                                    }
 826                                    None => split_or_open(
 827                                        workspace,
 828                                        ProjectPath {
 829                                            worktree_id,
 830                                            path: Arc::clone(&history_match.project.path),
 831                                        },
 832                                        cx,
 833                                    ),
 834                                }
 835                            }
 836                        }
 837                        Match::Search(m) => split_or_open(
 838                            workspace,
 839                            ProjectPath {
 840                                worktree_id: WorktreeId::from_usize(m.0.worktree_id),
 841                                path: m.0.path.clone(),
 842                            },
 843                            cx,
 844                        ),
 845                    }
 846                });
 847
 848                let row = self
 849                    .latest_search_query
 850                    .as_ref()
 851                    .and_then(|query| query.row)
 852                    .map(|row| row.saturating_sub(1));
 853                let col = self
 854                    .latest_search_query
 855                    .as_ref()
 856                    .and_then(|query| query.column)
 857                    .unwrap_or(0)
 858                    .saturating_sub(1);
 859                let finder = self.file_finder.clone();
 860
 861                cx.spawn(|_, mut cx| async move {
 862                    let item = open_task.await.log_err()?;
 863                    if let Some(row) = row {
 864                        if let Some(active_editor) = item.downcast::<Editor>() {
 865                            active_editor
 866                                .downgrade()
 867                                .update(&mut cx, |editor, cx| {
 868                                    let snapshot = editor.snapshot(cx).display_snapshot;
 869                                    let point = snapshot
 870                                        .buffer_snapshot
 871                                        .clip_point(Point::new(row, col), Bias::Left);
 872                                    editor.change_selections(Some(Autoscroll::center()), cx, |s| {
 873                                        s.select_ranges([point..point])
 874                                    });
 875                                })
 876                                .log_err();
 877                        }
 878                    }
 879                    finder.update(&mut cx, |_, cx| cx.emit(DismissEvent)).ok()?;
 880
 881                    Some(())
 882                })
 883                .detach();
 884            }
 885        }
 886    }
 887
 888    fn dismissed(&mut self, cx: &mut ViewContext<Picker<FileFinderDelegate>>) {
 889        self.file_finder
 890            .update(cx, |_, cx| cx.emit(DismissEvent))
 891            .log_err();
 892    }
 893
 894    fn render_match(
 895        &self,
 896        ix: usize,
 897        selected: bool,
 898        cx: &mut ViewContext<Picker<Self>>,
 899    ) -> Option<Self::ListItem> {
 900        let path_match = self
 901            .matches
 902            .get(ix)
 903            .expect("Invalid matches state: no element for index {ix}");
 904
 905        let (file_name, file_name_positions, full_path, full_path_positions) =
 906            self.labels_for_match(path_match, cx, ix);
 907
 908        Some(
 909            ListItem::new(ix)
 910                .spacing(ListItemSpacing::Sparse)
 911                .inset(true)
 912                .selected(selected)
 913                .child(
 914                    h_flex()
 915                        .gap_2()
 916                        .py_px()
 917                        .child(HighlightedLabel::new(file_name, file_name_positions))
 918                        .child(
 919                            HighlightedLabel::new(full_path, full_path_positions)
 920                                .size(LabelSize::Small)
 921                                .color(Color::Muted),
 922                        ),
 923                ),
 924        )
 925    }
 926}
 927
 928#[cfg(test)]
 929mod tests {
 930    use super::*;
 931
 932    #[test]
 933    fn test_custom_project_search_ordering_in_file_finder() {
 934        let mut file_finder_sorted_output = vec![
 935            ProjectPanelOrdMatch(PathMatch {
 936                score: 0.5,
 937                positions: Vec::new(),
 938                worktree_id: 0,
 939                path: Arc::from(Path::new("b0.5")),
 940                path_prefix: Arc::from(""),
 941                distance_to_relative_ancestor: 0,
 942            }),
 943            ProjectPanelOrdMatch(PathMatch {
 944                score: 1.0,
 945                positions: Vec::new(),
 946                worktree_id: 0,
 947                path: Arc::from(Path::new("c1.0")),
 948                path_prefix: Arc::from(""),
 949                distance_to_relative_ancestor: 0,
 950            }),
 951            ProjectPanelOrdMatch(PathMatch {
 952                score: 1.0,
 953                positions: Vec::new(),
 954                worktree_id: 0,
 955                path: Arc::from(Path::new("a1.0")),
 956                path_prefix: Arc::from(""),
 957                distance_to_relative_ancestor: 0,
 958            }),
 959            ProjectPanelOrdMatch(PathMatch {
 960                score: 0.5,
 961                positions: Vec::new(),
 962                worktree_id: 0,
 963                path: Arc::from(Path::new("a0.5")),
 964                path_prefix: Arc::from(""),
 965                distance_to_relative_ancestor: 0,
 966            }),
 967            ProjectPanelOrdMatch(PathMatch {
 968                score: 1.0,
 969                positions: Vec::new(),
 970                worktree_id: 0,
 971                path: Arc::from(Path::new("b1.0")),
 972                path_prefix: Arc::from(""),
 973                distance_to_relative_ancestor: 0,
 974            }),
 975        ];
 976        file_finder_sorted_output.sort_by(|a, b| b.cmp(a));
 977
 978        assert_eq!(
 979            file_finder_sorted_output,
 980            vec![
 981                ProjectPanelOrdMatch(PathMatch {
 982                    score: 1.0,
 983                    positions: Vec::new(),
 984                    worktree_id: 0,
 985                    path: Arc::from(Path::new("a1.0")),
 986                    path_prefix: Arc::from(""),
 987                    distance_to_relative_ancestor: 0,
 988                }),
 989                ProjectPanelOrdMatch(PathMatch {
 990                    score: 1.0,
 991                    positions: Vec::new(),
 992                    worktree_id: 0,
 993                    path: Arc::from(Path::new("b1.0")),
 994                    path_prefix: Arc::from(""),
 995                    distance_to_relative_ancestor: 0,
 996                }),
 997                ProjectPanelOrdMatch(PathMatch {
 998                    score: 1.0,
 999                    positions: Vec::new(),
1000                    worktree_id: 0,
1001                    path: Arc::from(Path::new("c1.0")),
1002                    path_prefix: Arc::from(""),
1003                    distance_to_relative_ancestor: 0,
1004                }),
1005                ProjectPanelOrdMatch(PathMatch {
1006                    score: 0.5,
1007                    positions: Vec::new(),
1008                    worktree_id: 0,
1009                    path: Arc::from(Path::new("a0.5")),
1010                    path_prefix: Arc::from(""),
1011                    distance_to_relative_ancestor: 0,
1012                }),
1013                ProjectPanelOrdMatch(PathMatch {
1014                    score: 0.5,
1015                    positions: Vec::new(),
1016                    worktree_id: 0,
1017                    path: Arc::from(Path::new("b0.5")),
1018                    path_prefix: Arc::from(""),
1019                    distance_to_relative_ancestor: 0,
1020                }),
1021            ]
1022        );
1023    }
1024}