project_search.rs

   1use crate::{
   2    BufferSearchBar, FocusSearch, NextHistoryQuery, PreviousHistoryQuery, ReplaceAll, ReplaceNext,
   3    SearchOption, SearchOptions, SearchSource, SelectNextMatch, SelectPreviousMatch,
   4    ToggleCaseSensitive, ToggleIncludeIgnored, ToggleRegex, ToggleReplace, ToggleWholeWord,
   5    buffer_search::Deploy,
   6    search_bar::{ActionButtonState, input_base_styles, render_action_button, render_text_input},
   7};
   8use anyhow::Context as _;
   9use collections::HashMap;
  10use editor::{
  11    Anchor, Editor, EditorEvent, EditorSettings, MAX_TAB_TITLE_LEN, MultiBuffer, PathKey,
  12    SelectionEffects, VimFlavor,
  13    actions::{Backtab, SelectAll, Tab},
  14    items::active_match_index,
  15    multibuffer_context_lines, vim_flavor,
  16};
  17use futures::{StreamExt, stream::FuturesOrdered};
  18use gpui::{
  19    Action, AnyElement, AnyView, App, Axis, Context, Entity, EntityId, EventEmitter, FocusHandle,
  20    Focusable, Global, Hsla, InteractiveElement, IntoElement, KeyContext, ParentElement, Point,
  21    Render, SharedString, Styled, Subscription, Task, UpdateGlobal, WeakEntity, Window, actions,
  22    div,
  23};
  24use language::{Buffer, Language};
  25use menu::Confirm;
  26use project::{
  27    Project, ProjectPath,
  28    search::{SearchInputKind, SearchQuery},
  29    search_history::SearchHistoryCursor,
  30};
  31use settings::Settings;
  32use std::{
  33    any::{Any, TypeId},
  34    mem,
  35    ops::{Not, Range},
  36    pin::pin,
  37    sync::Arc,
  38};
  39use ui::{IconButtonShape, KeyBinding, Toggleable, Tooltip, prelude::*, utils::SearchInputWidth};
  40use util::{ResultExt as _, paths::PathMatcher, rel_path::RelPath};
  41use workspace::{
  42    DeploySearch, ItemNavHistory, NewSearch, ToolbarItemEvent, ToolbarItemLocation,
  43    ToolbarItemView, Workspace, WorkspaceId,
  44    item::{BreadcrumbText, Item, ItemEvent, ItemHandle, SaveOptions},
  45    searchable::{Direction, SearchableItem, SearchableItemHandle},
  46};
  47
  48actions!(
  49    project_search,
  50    [
  51        /// Searches in a new project search tab.
  52        SearchInNew,
  53        /// Toggles focus between the search bar and the search results.
  54        ToggleFocus,
  55        /// Moves to the next input field.
  56        NextField,
  57        /// Toggles the search filters panel.
  58        ToggleFilters
  59    ]
  60);
  61
  62#[derive(Default)]
  63struct ActiveSettings(HashMap<WeakEntity<Project>, ProjectSearchSettings>);
  64
  65impl Global for ActiveSettings {}
  66
  67pub fn init(cx: &mut App) {
  68    cx.set_global(ActiveSettings::default());
  69    cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
  70        register_workspace_action(workspace, move |search_bar, _: &Deploy, window, cx| {
  71            search_bar.focus_search(window, cx);
  72        });
  73        register_workspace_action(workspace, move |search_bar, _: &FocusSearch, window, cx| {
  74            search_bar.focus_search(window, cx);
  75        });
  76        register_workspace_action(
  77            workspace,
  78            move |search_bar, _: &ToggleFilters, window, cx| {
  79                search_bar.toggle_filters(window, cx);
  80            },
  81        );
  82        register_workspace_action(
  83            workspace,
  84            move |search_bar, _: &ToggleCaseSensitive, window, cx| {
  85                search_bar.toggle_search_option(SearchOptions::CASE_SENSITIVE, window, cx);
  86            },
  87        );
  88        register_workspace_action(
  89            workspace,
  90            move |search_bar, _: &ToggleWholeWord, window, cx| {
  91                search_bar.toggle_search_option(SearchOptions::WHOLE_WORD, window, cx);
  92            },
  93        );
  94        register_workspace_action(workspace, move |search_bar, _: &ToggleRegex, window, cx| {
  95            search_bar.toggle_search_option(SearchOptions::REGEX, window, cx);
  96        });
  97        register_workspace_action(
  98            workspace,
  99            move |search_bar, action: &ToggleReplace, window, cx| {
 100                search_bar.toggle_replace(action, window, cx)
 101            },
 102        );
 103        register_workspace_action(
 104            workspace,
 105            move |search_bar, action: &SelectPreviousMatch, window, cx| {
 106                search_bar.select_prev_match(action, window, cx)
 107            },
 108        );
 109        register_workspace_action(
 110            workspace,
 111            move |search_bar, action: &SelectNextMatch, window, cx| {
 112                search_bar.select_next_match(action, window, cx)
 113            },
 114        );
 115
 116        // Only handle search_in_new if there is a search present
 117        register_workspace_action_for_present_search(workspace, |workspace, action, window, cx| {
 118            ProjectSearchView::search_in_new(workspace, action, window, cx)
 119        });
 120
 121        register_workspace_action_for_present_search(
 122            workspace,
 123            |workspace, _: &menu::Cancel, window, cx| {
 124                if let Some(project_search_bar) = workspace
 125                    .active_pane()
 126                    .read(cx)
 127                    .toolbar()
 128                    .read(cx)
 129                    .item_of_type::<ProjectSearchBar>()
 130                {
 131                    project_search_bar.update(cx, |project_search_bar, cx| {
 132                        let search_is_focused = project_search_bar
 133                            .active_project_search
 134                            .as_ref()
 135                            .is_some_and(|search_view| {
 136                                search_view
 137                                    .read(cx)
 138                                    .query_editor
 139                                    .read(cx)
 140                                    .focus_handle(cx)
 141                                    .is_focused(window)
 142                            });
 143                        if search_is_focused {
 144                            project_search_bar.move_focus_to_results(window, cx);
 145                        } else {
 146                            project_search_bar.focus_search(window, cx)
 147                        }
 148                    });
 149                } else {
 150                    cx.propagate();
 151                }
 152            },
 153        );
 154
 155        // Both on present and dismissed search, we need to unconditionally handle those actions to focus from the editor.
 156        workspace.register_action(move |workspace, action: &DeploySearch, window, cx| {
 157            if workspace.has_active_modal(window, cx) && !workspace.hide_modal(window, cx) {
 158                cx.propagate();
 159                return;
 160            }
 161            ProjectSearchView::deploy_search(workspace, action, window, cx);
 162            cx.notify();
 163        });
 164        workspace.register_action(move |workspace, action: &NewSearch, window, cx| {
 165            if workspace.has_active_modal(window, cx) && !workspace.hide_modal(window, cx) {
 166                cx.propagate();
 167                return;
 168            }
 169            ProjectSearchView::new_search(workspace, action, window, cx);
 170            cx.notify();
 171        });
 172    })
 173    .detach();
 174}
 175
 176fn contains_uppercase(str: &str) -> bool {
 177    str.chars().any(|c| c.is_uppercase())
 178}
 179
 180pub struct ProjectSearch {
 181    project: Entity<Project>,
 182    excerpts: Entity<MultiBuffer>,
 183    pending_search: Option<Task<Option<()>>>,
 184    match_ranges: Vec<Range<Anchor>>,
 185    active_query: Option<SearchQuery>,
 186    last_search_query_text: Option<String>,
 187    search_id: usize,
 188    no_results: Option<bool>,
 189    limit_reached: bool,
 190    search_history_cursor: SearchHistoryCursor,
 191    search_included_history_cursor: SearchHistoryCursor,
 192    search_excluded_history_cursor: SearchHistoryCursor,
 193}
 194
 195#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
 196enum InputPanel {
 197    Query,
 198    Replacement,
 199    Exclude,
 200    Include,
 201}
 202
 203pub struct ProjectSearchView {
 204    workspace: WeakEntity<Workspace>,
 205    focus_handle: FocusHandle,
 206    entity: Entity<ProjectSearch>,
 207    query_editor: Entity<Editor>,
 208    replacement_editor: Entity<Editor>,
 209    results_editor: Entity<Editor>,
 210    search_options: SearchOptions,
 211    panels_with_errors: HashMap<InputPanel, String>,
 212    active_match_index: Option<usize>,
 213    search_id: usize,
 214    included_files_editor: Entity<Editor>,
 215    excluded_files_editor: Entity<Editor>,
 216    filters_enabled: bool,
 217    replace_enabled: bool,
 218    included_opened_only: bool,
 219    regex_language: Option<Arc<Language>>,
 220    _subscriptions: Vec<Subscription>,
 221}
 222
 223#[derive(Debug, Clone)]
 224pub struct ProjectSearchSettings {
 225    search_options: SearchOptions,
 226    filters_enabled: bool,
 227}
 228
 229pub struct ProjectSearchBar {
 230    active_project_search: Option<Entity<ProjectSearchView>>,
 231    subscription: Option<Subscription>,
 232}
 233
 234impl ProjectSearch {
 235    pub fn new(project: Entity<Project>, cx: &mut Context<Self>) -> Self {
 236        let capability = project.read(cx).capability();
 237
 238        Self {
 239            project,
 240            excerpts: cx.new(|_| MultiBuffer::new(capability)),
 241            pending_search: Default::default(),
 242            match_ranges: Default::default(),
 243            active_query: None,
 244            last_search_query_text: None,
 245            search_id: 0,
 246            no_results: None,
 247            limit_reached: false,
 248            search_history_cursor: Default::default(),
 249            search_included_history_cursor: Default::default(),
 250            search_excluded_history_cursor: Default::default(),
 251        }
 252    }
 253
 254    fn clone(&self, cx: &mut Context<Self>) -> Entity<Self> {
 255        cx.new(|cx| Self {
 256            project: self.project.clone(),
 257            excerpts: self
 258                .excerpts
 259                .update(cx, |excerpts, cx| cx.new(|cx| excerpts.clone(cx))),
 260            pending_search: Default::default(),
 261            match_ranges: self.match_ranges.clone(),
 262            active_query: self.active_query.clone(),
 263            last_search_query_text: self.last_search_query_text.clone(),
 264            search_id: self.search_id,
 265            no_results: self.no_results,
 266            limit_reached: self.limit_reached,
 267            search_history_cursor: self.search_history_cursor.clone(),
 268            search_included_history_cursor: self.search_included_history_cursor.clone(),
 269            search_excluded_history_cursor: self.search_excluded_history_cursor.clone(),
 270        })
 271    }
 272    fn cursor(&self, kind: SearchInputKind) -> &SearchHistoryCursor {
 273        match kind {
 274            SearchInputKind::Query => &self.search_history_cursor,
 275            SearchInputKind::Include => &self.search_included_history_cursor,
 276            SearchInputKind::Exclude => &self.search_excluded_history_cursor,
 277        }
 278    }
 279    fn cursor_mut(&mut self, kind: SearchInputKind) -> &mut SearchHistoryCursor {
 280        match kind {
 281            SearchInputKind::Query => &mut self.search_history_cursor,
 282            SearchInputKind::Include => &mut self.search_included_history_cursor,
 283            SearchInputKind::Exclude => &mut self.search_excluded_history_cursor,
 284        }
 285    }
 286
 287    fn search(&mut self, query: SearchQuery, cx: &mut Context<Self>) {
 288        let search = self.project.update(cx, |project, cx| {
 289            project
 290                .search_history_mut(SearchInputKind::Query)
 291                .add(&mut self.search_history_cursor, query.as_str().to_string());
 292            let included = query.as_inner().files_to_include().sources().join(",");
 293            if !included.is_empty() {
 294                project
 295                    .search_history_mut(SearchInputKind::Include)
 296                    .add(&mut self.search_included_history_cursor, included);
 297            }
 298            let excluded = query.as_inner().files_to_exclude().sources().join(",");
 299            if !excluded.is_empty() {
 300                project
 301                    .search_history_mut(SearchInputKind::Exclude)
 302                    .add(&mut self.search_excluded_history_cursor, excluded);
 303            }
 304            project.search(query.clone(), cx)
 305        });
 306        self.last_search_query_text = Some(query.as_str().to_string());
 307        self.search_id += 1;
 308        self.active_query = Some(query);
 309        self.match_ranges.clear();
 310        self.pending_search = Some(cx.spawn(async move |project_search, cx| {
 311            let mut matches = pin!(search.ready_chunks(1024));
 312            project_search
 313                .update(cx, |project_search, cx| {
 314                    project_search.match_ranges.clear();
 315                    project_search
 316                        .excerpts
 317                        .update(cx, |excerpts, cx| excerpts.clear(cx));
 318                    project_search.no_results = Some(true);
 319                    project_search.limit_reached = false;
 320                })
 321                .ok()?;
 322
 323            let mut limit_reached = false;
 324            while let Some(results) = matches.next().await {
 325                let (buffers_with_ranges, has_reached_limit) = cx
 326                    .background_executor()
 327                    .spawn(async move {
 328                        let mut limit_reached = false;
 329                        let mut buffers_with_ranges = Vec::with_capacity(results.len());
 330                        for result in results {
 331                            match result {
 332                                project::search::SearchResult::Buffer { buffer, ranges } => {
 333                                    buffers_with_ranges.push((buffer, ranges));
 334                                }
 335                                project::search::SearchResult::LimitReached => {
 336                                    limit_reached = true;
 337                                }
 338                            }
 339                        }
 340                        (buffers_with_ranges, limit_reached)
 341                    })
 342                    .await;
 343                limit_reached |= has_reached_limit;
 344                let mut new_ranges = project_search
 345                    .update(cx, |project_search, cx| {
 346                        project_search.excerpts.update(cx, |excerpts, cx| {
 347                            buffers_with_ranges
 348                                .into_iter()
 349                                .map(|(buffer, ranges)| {
 350                                    excerpts.set_anchored_excerpts_for_path(
 351                                        PathKey::for_buffer(&buffer, cx),
 352                                        buffer,
 353                                        ranges,
 354                                        multibuffer_context_lines(cx),
 355                                        cx,
 356                                    )
 357                                })
 358                                .collect::<FuturesOrdered<_>>()
 359                        })
 360                    })
 361                    .ok()?;
 362                while let Some(new_ranges) = new_ranges.next().await {
 363                    project_search
 364                        .update(cx, |project_search, cx| {
 365                            project_search.match_ranges.extend(new_ranges);
 366                            cx.notify();
 367                        })
 368                        .ok()?;
 369                }
 370            }
 371
 372            project_search
 373                .update(cx, |project_search, cx| {
 374                    if !project_search.match_ranges.is_empty() {
 375                        project_search.no_results = Some(false);
 376                    }
 377                    project_search.limit_reached = limit_reached;
 378                    project_search.pending_search.take();
 379                    cx.notify();
 380                })
 381                .ok()?;
 382
 383            None
 384        }));
 385        cx.notify();
 386    }
 387}
 388
 389#[derive(Clone, Debug, PartialEq, Eq)]
 390pub enum ViewEvent {
 391    UpdateTab,
 392    Activate,
 393    EditorEvent(editor::EditorEvent),
 394    Dismiss,
 395}
 396
 397impl EventEmitter<ViewEvent> for ProjectSearchView {}
 398
 399impl Render for ProjectSearchView {
 400    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 401        if self.has_matches() {
 402            div()
 403                .flex_1()
 404                .size_full()
 405                .track_focus(&self.focus_handle(cx))
 406                .child(self.results_editor.clone())
 407        } else {
 408            let model = self.entity.read(cx);
 409            let has_no_results = model.no_results.unwrap_or(false);
 410            let is_search_underway = model.pending_search.is_some();
 411
 412            let heading_text = if is_search_underway {
 413                "Searching…"
 414            } else if has_no_results {
 415                "No Results"
 416            } else {
 417                "Search All Files"
 418            };
 419
 420            let heading_text = div()
 421                .justify_center()
 422                .child(Label::new(heading_text).size(LabelSize::Large));
 423
 424            let page_content: Option<AnyElement> = if let Some(no_results) = model.no_results {
 425                if model.pending_search.is_none() && no_results {
 426                    Some(
 427                        Label::new("No results found in this project for the provided query")
 428                            .size(LabelSize::Small)
 429                            .into_any_element(),
 430                    )
 431                } else {
 432                    None
 433                }
 434            } else {
 435                Some(self.landing_text_minor(cx).into_any_element())
 436            };
 437
 438            let page_content = page_content.map(|text| div().child(text));
 439
 440            h_flex()
 441                .size_full()
 442                .items_center()
 443                .justify_center()
 444                .overflow_hidden()
 445                .bg(cx.theme().colors().editor_background)
 446                .track_focus(&self.focus_handle(cx))
 447                .child(
 448                    v_flex()
 449                        .id("project-search-landing-page")
 450                        .overflow_y_scroll()
 451                        .gap_1()
 452                        .child(heading_text)
 453                        .children(page_content),
 454                )
 455        }
 456    }
 457}
 458
 459impl Focusable for ProjectSearchView {
 460    fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
 461        self.focus_handle.clone()
 462    }
 463}
 464
 465impl Item for ProjectSearchView {
 466    type Event = ViewEvent;
 467    fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString> {
 468        let query_text = self.query_editor.read(cx).text(cx);
 469
 470        query_text
 471            .is_empty()
 472            .not()
 473            .then(|| query_text.into())
 474            .or_else(|| Some("Project Search".into()))
 475    }
 476
 477    fn act_as_type<'a>(
 478        &'a self,
 479        type_id: TypeId,
 480        self_handle: &'a Entity<Self>,
 481        _: &'a App,
 482    ) -> Option<AnyView> {
 483        if type_id == TypeId::of::<Self>() {
 484            Some(self_handle.clone().into())
 485        } else if type_id == TypeId::of::<Editor>() {
 486            Some(self.results_editor.clone().into())
 487        } else {
 488            None
 489        }
 490    }
 491    fn as_searchable(&self, _: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
 492        Some(Box::new(self.results_editor.clone()))
 493    }
 494
 495    fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 496        self.results_editor
 497            .update(cx, |editor, cx| editor.deactivated(window, cx));
 498    }
 499
 500    fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
 501        Some(Icon::new(IconName::MagnifyingGlass))
 502    }
 503
 504    fn tab_content_text(&self, _detail: usize, cx: &App) -> SharedString {
 505        let last_query: Option<SharedString> = self
 506            .entity
 507            .read(cx)
 508            .last_search_query_text
 509            .as_ref()
 510            .map(|query| {
 511                let query = query.replace('\n', "");
 512                let query_text = util::truncate_and_trailoff(&query, MAX_TAB_TITLE_LEN);
 513                query_text.into()
 514            });
 515
 516        last_query
 517            .filter(|query| !query.is_empty())
 518            .unwrap_or_else(|| "Project Search".into())
 519    }
 520
 521    fn telemetry_event_text(&self) -> Option<&'static str> {
 522        Some("Project Search Opened")
 523    }
 524
 525    fn for_each_project_item(
 526        &self,
 527        cx: &App,
 528        f: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
 529    ) {
 530        self.results_editor.for_each_project_item(cx, f)
 531    }
 532
 533    fn can_save(&self, _: &App) -> bool {
 534        true
 535    }
 536
 537    fn is_dirty(&self, cx: &App) -> bool {
 538        self.results_editor.read(cx).is_dirty(cx)
 539    }
 540
 541    fn has_conflict(&self, cx: &App) -> bool {
 542        self.results_editor.read(cx).has_conflict(cx)
 543    }
 544
 545    fn save(
 546        &mut self,
 547        options: SaveOptions,
 548        project: Entity<Project>,
 549        window: &mut Window,
 550        cx: &mut Context<Self>,
 551    ) -> Task<anyhow::Result<()>> {
 552        self.results_editor
 553            .update(cx, |editor, cx| editor.save(options, project, window, cx))
 554    }
 555
 556    fn save_as(
 557        &mut self,
 558        _: Entity<Project>,
 559        _: ProjectPath,
 560        _window: &mut Window,
 561        _: &mut Context<Self>,
 562    ) -> Task<anyhow::Result<()>> {
 563        unreachable!("save_as should not have been called")
 564    }
 565
 566    fn reload(
 567        &mut self,
 568        project: Entity<Project>,
 569        window: &mut Window,
 570        cx: &mut Context<Self>,
 571    ) -> Task<anyhow::Result<()>> {
 572        self.results_editor
 573            .update(cx, |editor, cx| editor.reload(project, window, cx))
 574    }
 575
 576    fn can_split(&self) -> bool {
 577        true
 578    }
 579
 580    fn clone_on_split(
 581        &self,
 582        _workspace_id: Option<WorkspaceId>,
 583        window: &mut Window,
 584        cx: &mut Context<Self>,
 585    ) -> Task<Option<Entity<Self>>>
 586    where
 587        Self: Sized,
 588    {
 589        let model = self.entity.update(cx, |model, cx| model.clone(cx));
 590        Task::ready(Some(cx.new(|cx| {
 591            Self::new(self.workspace.clone(), model, window, cx, None)
 592        })))
 593    }
 594
 595    fn added_to_workspace(
 596        &mut self,
 597        workspace: &mut Workspace,
 598        window: &mut Window,
 599        cx: &mut Context<Self>,
 600    ) {
 601        self.results_editor.update(cx, |editor, cx| {
 602            editor.added_to_workspace(workspace, window, cx)
 603        });
 604    }
 605
 606    fn set_nav_history(
 607        &mut self,
 608        nav_history: ItemNavHistory,
 609        _: &mut Window,
 610        cx: &mut Context<Self>,
 611    ) {
 612        self.results_editor.update(cx, |editor, _| {
 613            editor.set_nav_history(Some(nav_history));
 614        });
 615    }
 616
 617    fn navigate(
 618        &mut self,
 619        data: Box<dyn Any>,
 620        window: &mut Window,
 621        cx: &mut Context<Self>,
 622    ) -> bool {
 623        self.results_editor
 624            .update(cx, |editor, cx| editor.navigate(data, window, cx))
 625    }
 626
 627    fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
 628        match event {
 629            ViewEvent::UpdateTab => {
 630                f(ItemEvent::UpdateBreadcrumbs);
 631                f(ItemEvent::UpdateTab);
 632            }
 633            ViewEvent::EditorEvent(editor_event) => {
 634                Editor::to_item_events(editor_event, f);
 635            }
 636            ViewEvent::Dismiss => f(ItemEvent::CloseItem),
 637            _ => {}
 638        }
 639    }
 640
 641    fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
 642        if self.has_matches() {
 643            ToolbarItemLocation::Secondary
 644        } else {
 645            ToolbarItemLocation::Hidden
 646        }
 647    }
 648
 649    fn breadcrumbs(&self, theme: &theme::Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
 650        self.results_editor.breadcrumbs(theme, cx)
 651    }
 652}
 653
 654impl ProjectSearchView {
 655    pub fn get_matches(&self, cx: &App) -> Vec<Range<Anchor>> {
 656        self.entity.read(cx).match_ranges.clone()
 657    }
 658
 659    fn toggle_filters(&mut self, cx: &mut Context<Self>) {
 660        self.filters_enabled = !self.filters_enabled;
 661        ActiveSettings::update_global(cx, |settings, cx| {
 662            settings.0.insert(
 663                self.entity.read(cx).project.downgrade(),
 664                self.current_settings(),
 665            );
 666        });
 667    }
 668
 669    fn current_settings(&self) -> ProjectSearchSettings {
 670        ProjectSearchSettings {
 671            search_options: self.search_options,
 672            filters_enabled: self.filters_enabled,
 673        }
 674    }
 675
 676    fn toggle_search_option(&mut self, option: SearchOptions, cx: &mut Context<Self>) {
 677        self.search_options.toggle(option);
 678        ActiveSettings::update_global(cx, |settings, cx| {
 679            settings.0.insert(
 680                self.entity.read(cx).project.downgrade(),
 681                self.current_settings(),
 682            );
 683        });
 684        self.adjust_query_regex_language(cx);
 685    }
 686
 687    fn toggle_opened_only(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {
 688        self.included_opened_only = !self.included_opened_only;
 689    }
 690
 691    pub fn replacement(&self, cx: &App) -> String {
 692        self.replacement_editor.read(cx).text(cx)
 693    }
 694
 695    fn replace_next(&mut self, _: &ReplaceNext, window: &mut Window, cx: &mut Context<Self>) {
 696        if let Some(last_search_query_text) = &self.entity.read(cx).last_search_query_text
 697            && self.query_editor.read(cx).text(cx) != *last_search_query_text
 698        {
 699            // search query has changed, restart search and bail
 700            self.search(cx);
 701            return;
 702        }
 703        if self.entity.read(cx).match_ranges.is_empty() {
 704            return;
 705        }
 706        let Some(active_index) = self.active_match_index else {
 707            return;
 708        };
 709
 710        let query = self.entity.read(cx).active_query.clone();
 711        if let Some(query) = query {
 712            let query = query.with_replacement(self.replacement(cx));
 713
 714            // TODO: Do we need the clone here?
 715            let mat = self.entity.read(cx).match_ranges[active_index].clone();
 716            self.results_editor.update(cx, |editor, cx| {
 717                editor.replace(&mat, &query, window, cx);
 718            });
 719            self.select_match(Direction::Next, window, cx)
 720        }
 721    }
 722    fn replace_all(&mut self, _: &ReplaceAll, window: &mut Window, cx: &mut Context<Self>) {
 723        if let Some(last_search_query_text) = &self.entity.read(cx).last_search_query_text
 724            && self.query_editor.read(cx).text(cx) != *last_search_query_text
 725        {
 726            // search query has changed, restart search and bail
 727            self.search(cx);
 728            return;
 729        }
 730        if self.active_match_index.is_none() {
 731            return;
 732        }
 733        let Some(query) = self.entity.read(cx).active_query.as_ref() else {
 734            return;
 735        };
 736        let query = query.clone().with_replacement(self.replacement(cx));
 737
 738        let match_ranges = self
 739            .entity
 740            .update(cx, |model, _| mem::take(&mut model.match_ranges));
 741        if match_ranges.is_empty() {
 742            return;
 743        }
 744
 745        self.results_editor.update(cx, |editor, cx| {
 746            editor.replace_all(&mut match_ranges.iter(), &query, window, cx);
 747        });
 748
 749        self.entity.update(cx, |model, _cx| {
 750            model.match_ranges = match_ranges;
 751        });
 752    }
 753
 754    pub fn new(
 755        workspace: WeakEntity<Workspace>,
 756        entity: Entity<ProjectSearch>,
 757        window: &mut Window,
 758        cx: &mut Context<Self>,
 759        settings: Option<ProjectSearchSettings>,
 760    ) -> Self {
 761        let project;
 762        let excerpts;
 763        let mut replacement_text = None;
 764        let mut query_text = String::new();
 765        let mut subscriptions = Vec::new();
 766
 767        // Read in settings if available
 768        let (mut options, filters_enabled) = if let Some(settings) = settings {
 769            (settings.search_options, settings.filters_enabled)
 770        } else {
 771            let search_options =
 772                SearchOptions::from_settings(&EditorSettings::get_global(cx).search);
 773            (search_options, false)
 774        };
 775
 776        {
 777            let entity = entity.read(cx);
 778            project = entity.project.clone();
 779            excerpts = entity.excerpts.clone();
 780            if let Some(active_query) = entity.active_query.as_ref() {
 781                query_text = active_query.as_str().to_string();
 782                replacement_text = active_query.replacement().map(ToOwned::to_owned);
 783                options = SearchOptions::from_query(active_query);
 784            }
 785        }
 786        subscriptions.push(cx.observe_in(&entity, window, |this, _, window, cx| {
 787            this.entity_changed(window, cx)
 788        }));
 789
 790        let query_editor = cx.new(|cx| {
 791            let mut editor = Editor::single_line(window, cx);
 792            editor.set_placeholder_text("Search all files…", window, cx);
 793            editor.set_text(query_text, window, cx);
 794            editor
 795        });
 796        // Subscribe to query_editor in order to reraise editor events for workspace item activation purposes
 797        subscriptions.push(
 798            cx.subscribe(&query_editor, |this, _, event: &EditorEvent, cx| {
 799                if let EditorEvent::Edited { .. } = event
 800                    && EditorSettings::get_global(cx).use_smartcase_search
 801                {
 802                    let query = this.search_query_text(cx);
 803                    if !query.is_empty()
 804                        && this.search_options.contains(SearchOptions::CASE_SENSITIVE)
 805                            != contains_uppercase(&query)
 806                    {
 807                        this.toggle_search_option(SearchOptions::CASE_SENSITIVE, cx);
 808                    }
 809                }
 810                cx.emit(ViewEvent::EditorEvent(event.clone()))
 811            }),
 812        );
 813        let replacement_editor = cx.new(|cx| {
 814            let mut editor = Editor::single_line(window, cx);
 815            editor.set_placeholder_text("Replace in project…", window, cx);
 816            if let Some(text) = replacement_text {
 817                editor.set_text(text, window, cx);
 818            }
 819            editor
 820        });
 821        let results_editor = cx.new(|cx| {
 822            let mut editor = Editor::for_multibuffer(excerpts, Some(project.clone()), window, cx);
 823            editor.set_searchable(false);
 824            editor.set_in_project_search(true);
 825            editor
 826        });
 827        subscriptions.push(cx.observe(&results_editor, |_, _, cx| cx.emit(ViewEvent::UpdateTab)));
 828
 829        subscriptions.push(
 830            cx.subscribe(&results_editor, |this, _, event: &EditorEvent, cx| {
 831                if matches!(event, editor::EditorEvent::SelectionsChanged { .. }) {
 832                    this.update_match_index(cx);
 833                }
 834                // Reraise editor events for workspace item activation purposes
 835                cx.emit(ViewEvent::EditorEvent(event.clone()));
 836            }),
 837        );
 838
 839        let included_files_editor = cx.new(|cx| {
 840            let mut editor = Editor::single_line(window, cx);
 841            editor.set_placeholder_text("Include: crates/**/*.toml", window, cx);
 842
 843            editor
 844        });
 845        // Subscribe to include_files_editor in order to reraise editor events for workspace item activation purposes
 846        subscriptions.push(
 847            cx.subscribe(&included_files_editor, |_, _, event: &EditorEvent, cx| {
 848                cx.emit(ViewEvent::EditorEvent(event.clone()))
 849            }),
 850        );
 851
 852        let excluded_files_editor = cx.new(|cx| {
 853            let mut editor = Editor::single_line(window, cx);
 854            editor.set_placeholder_text("Exclude: vendor/*, *.lock", window, cx);
 855
 856            editor
 857        });
 858        // Subscribe to excluded_files_editor in order to reraise editor events for workspace item activation purposes
 859        subscriptions.push(
 860            cx.subscribe(&excluded_files_editor, |_, _, event: &EditorEvent, cx| {
 861                cx.emit(ViewEvent::EditorEvent(event.clone()))
 862            }),
 863        );
 864
 865        let focus_handle = cx.focus_handle();
 866        subscriptions.push(cx.on_focus(&focus_handle, window, |_, window, cx| {
 867            cx.on_next_frame(window, |this, window, cx| {
 868                if this.focus_handle.is_focused(window) {
 869                    if this.has_matches() {
 870                        this.results_editor.focus_handle(cx).focus(window);
 871                    } else {
 872                        this.query_editor.focus_handle(cx).focus(window);
 873                    }
 874                }
 875            });
 876        }));
 877
 878        let languages = project.read(cx).languages().clone();
 879        cx.spawn(async move |project_search_view, cx| {
 880            let regex_language = languages
 881                .language_for_name("regex")
 882                .await
 883                .context("loading regex language")?;
 884            project_search_view
 885                .update(cx, |project_search_view, cx| {
 886                    project_search_view.regex_language = Some(regex_language);
 887                    project_search_view.adjust_query_regex_language(cx);
 888                })
 889                .ok();
 890            anyhow::Ok(())
 891        })
 892        .detach_and_log_err(cx);
 893
 894        // Check if Worktrees have all been previously indexed
 895        let mut this = ProjectSearchView {
 896            workspace,
 897            focus_handle,
 898            replacement_editor,
 899            search_id: entity.read(cx).search_id,
 900            entity,
 901            query_editor,
 902            results_editor,
 903            search_options: options,
 904            panels_with_errors: HashMap::default(),
 905            active_match_index: None,
 906            included_files_editor,
 907            excluded_files_editor,
 908            filters_enabled,
 909            replace_enabled: false,
 910            included_opened_only: false,
 911            regex_language: None,
 912            _subscriptions: subscriptions,
 913        };
 914        this.entity_changed(window, cx);
 915        this
 916    }
 917
 918    pub fn new_search_in_directory(
 919        workspace: &mut Workspace,
 920        dir_path: &RelPath,
 921        window: &mut Window,
 922        cx: &mut Context<Workspace>,
 923    ) {
 924        let filter_str = dir_path.display(workspace.path_style(cx));
 925
 926        let weak_workspace = cx.entity().downgrade();
 927
 928        let entity = cx.new(|cx| ProjectSearch::new(workspace.project().clone(), cx));
 929        let search = cx.new(|cx| ProjectSearchView::new(weak_workspace, entity, window, cx, None));
 930        workspace.add_item_to_active_pane(Box::new(search.clone()), None, true, window, cx);
 931        search.update(cx, |search, cx| {
 932            search
 933                .included_files_editor
 934                .update(cx, |editor, cx| editor.set_text(filter_str, window, cx));
 935            search.filters_enabled = true;
 936            search.focus_query_editor(window, cx)
 937        });
 938    }
 939
 940    /// Re-activate the most recently activated search in this pane or the most recent if it has been closed.
 941    /// If no search exists in the workspace, create a new one.
 942    pub fn deploy_search(
 943        workspace: &mut Workspace,
 944        action: &workspace::DeploySearch,
 945        window: &mut Window,
 946        cx: &mut Context<Workspace>,
 947    ) {
 948        let existing = workspace
 949            .active_pane()
 950            .read(cx)
 951            .items()
 952            .find_map(|item| item.downcast::<ProjectSearchView>());
 953
 954        Self::existing_or_new_search(workspace, existing, action, window, cx);
 955    }
 956
 957    fn search_in_new(
 958        workspace: &mut Workspace,
 959        _: &SearchInNew,
 960        window: &mut Window,
 961        cx: &mut Context<Workspace>,
 962    ) {
 963        if let Some(search_view) = workspace
 964            .active_item(cx)
 965            .and_then(|item| item.downcast::<ProjectSearchView>())
 966        {
 967            let new_query = search_view.update(cx, |search_view, cx| {
 968                let open_buffers = if search_view.included_opened_only {
 969                    Some(search_view.open_buffers(cx, workspace))
 970                } else {
 971                    None
 972                };
 973                let new_query = search_view.build_search_query(cx, open_buffers);
 974                if new_query.is_some()
 975                    && let Some(old_query) = search_view.entity.read(cx).active_query.clone()
 976                {
 977                    search_view.query_editor.update(cx, |editor, cx| {
 978                        editor.set_text(old_query.as_str(), window, cx);
 979                    });
 980                    search_view.search_options = SearchOptions::from_query(&old_query);
 981                    search_view.adjust_query_regex_language(cx);
 982                }
 983                new_query
 984            });
 985            if let Some(new_query) = new_query {
 986                let entity = cx.new(|cx| {
 987                    let mut entity = ProjectSearch::new(workspace.project().clone(), cx);
 988                    entity.search(new_query, cx);
 989                    entity
 990                });
 991                let weak_workspace = cx.entity().downgrade();
 992                workspace.add_item_to_active_pane(
 993                    Box::new(cx.new(|cx| {
 994                        ProjectSearchView::new(weak_workspace, entity, window, cx, None)
 995                    })),
 996                    None,
 997                    true,
 998                    window,
 999                    cx,
1000                );
1001            }
1002        }
1003    }
1004
1005    // Add another search tab to the workspace.
1006    fn new_search(
1007        workspace: &mut Workspace,
1008        _: &workspace::NewSearch,
1009        window: &mut Window,
1010        cx: &mut Context<Workspace>,
1011    ) {
1012        Self::existing_or_new_search(workspace, None, &DeploySearch::find(), window, cx)
1013    }
1014
1015    fn existing_or_new_search(
1016        workspace: &mut Workspace,
1017        existing: Option<Entity<ProjectSearchView>>,
1018        action: &workspace::DeploySearch,
1019        window: &mut Window,
1020        cx: &mut Context<Workspace>,
1021    ) {
1022        let query = workspace.active_item(cx).and_then(|item| {
1023            if let Some(buffer_search_query) = buffer_search_query(workspace, item.as_ref(), cx) {
1024                return Some(buffer_search_query);
1025            }
1026
1027            let editor = item.act_as::<Editor>(cx)?;
1028            let query = editor.query_suggestion(window, cx);
1029            if query.is_empty() { None } else { Some(query) }
1030        });
1031
1032        let search = if let Some(existing) = existing {
1033            workspace.activate_item(&existing, true, true, window, cx);
1034            existing
1035        } else {
1036            let settings = cx
1037                .global::<ActiveSettings>()
1038                .0
1039                .get(&workspace.project().downgrade());
1040
1041            let settings = settings.cloned();
1042
1043            let weak_workspace = cx.entity().downgrade();
1044
1045            let project_search = cx.new(|cx| ProjectSearch::new(workspace.project().clone(), cx));
1046            let project_search_view = cx.new(|cx| {
1047                ProjectSearchView::new(weak_workspace, project_search, window, cx, settings)
1048            });
1049
1050            workspace.add_item_to_active_pane(
1051                Box::new(project_search_view.clone()),
1052                None,
1053                true,
1054                window,
1055                cx,
1056            );
1057            project_search_view
1058        };
1059
1060        search.update(cx, |search, cx| {
1061            search.replace_enabled = action.replace_enabled;
1062            if let Some(query) = query {
1063                search.set_query(&query, window, cx);
1064            }
1065            if let Some(included_files) = action.included_files.as_deref() {
1066                search
1067                    .included_files_editor
1068                    .update(cx, |editor, cx| editor.set_text(included_files, window, cx));
1069                search.filters_enabled = true;
1070            }
1071            if let Some(excluded_files) = action.excluded_files.as_deref() {
1072                search
1073                    .excluded_files_editor
1074                    .update(cx, |editor, cx| editor.set_text(excluded_files, window, cx));
1075                search.filters_enabled = true;
1076            }
1077            search.focus_query_editor(window, cx)
1078        });
1079    }
1080
1081    fn prompt_to_save_if_dirty_then_search(
1082        &mut self,
1083        window: &mut Window,
1084        cx: &mut Context<Self>,
1085    ) -> Task<anyhow::Result<()>> {
1086        let project = self.entity.read(cx).project.clone();
1087
1088        let can_autosave = self.results_editor.can_autosave(cx);
1089        let autosave_setting = self.results_editor.workspace_settings(cx).autosave;
1090
1091        let will_autosave = can_autosave && autosave_setting.should_save_on_close();
1092
1093        let is_dirty = self.is_dirty(cx);
1094
1095        cx.spawn_in(window, async move |this, cx| {
1096            let skip_save_on_close = this
1097                .read_with(cx, |this, cx| {
1098                    this.workspace.read_with(cx, |workspace, cx| {
1099                        workspace::Pane::skip_save_on_close(&this.results_editor, workspace, cx)
1100                    })
1101                })?
1102                .unwrap_or(false);
1103
1104            let should_prompt_to_save = !skip_save_on_close && !will_autosave && is_dirty;
1105
1106            let should_search = if should_prompt_to_save {
1107                let options = &["Save", "Don't Save", "Cancel"];
1108                let result_channel = this.update_in(cx, |_, window, cx| {
1109                    window.prompt(
1110                        gpui::PromptLevel::Warning,
1111                        "Project search buffer contains unsaved edits. Do you want to save it?",
1112                        None,
1113                        options,
1114                        cx,
1115                    )
1116                })?;
1117                let result = result_channel.await?;
1118                let should_save = result == 0;
1119                if should_save {
1120                    this.update_in(cx, |this, window, cx| {
1121                        this.save(
1122                            SaveOptions {
1123                                format: true,
1124                                autosave: false,
1125                            },
1126                            project,
1127                            window,
1128                            cx,
1129                        )
1130                    })?
1131                    .await
1132                    .log_err();
1133                }
1134
1135                result != 2
1136            } else {
1137                true
1138            };
1139            if should_search {
1140                this.update(cx, |this, cx| {
1141                    this.search(cx);
1142                })?;
1143            }
1144            anyhow::Ok(())
1145        })
1146    }
1147
1148    fn search(&mut self, cx: &mut Context<Self>) {
1149        let open_buffers = if self.included_opened_only {
1150            self.workspace
1151                .update(cx, |workspace, cx| self.open_buffers(cx, workspace))
1152                .ok()
1153        } else {
1154            None
1155        };
1156        if let Some(query) = self.build_search_query(cx, open_buffers) {
1157            self.entity.update(cx, |model, cx| model.search(query, cx));
1158        }
1159    }
1160
1161    pub fn search_query_text(&self, cx: &App) -> String {
1162        self.query_editor.read(cx).text(cx)
1163    }
1164
1165    fn build_search_query(
1166        &mut self,
1167        cx: &mut Context<Self>,
1168        open_buffers: Option<Vec<Entity<Buffer>>>,
1169    ) -> Option<SearchQuery> {
1170        // Do not bail early in this function, as we want to fill out `self.panels_with_errors`.
1171
1172        let text = self.search_query_text(cx);
1173        let included_files = self
1174            .filters_enabled
1175            .then(|| {
1176                match self.parse_path_matches(self.included_files_editor.read(cx).text(cx), cx) {
1177                    Ok(included_files) => {
1178                        let should_unmark_error =
1179                            self.panels_with_errors.remove(&InputPanel::Include);
1180                        if should_unmark_error.is_some() {
1181                            cx.notify();
1182                        }
1183                        included_files
1184                    }
1185                    Err(e) => {
1186                        let should_mark_error = self
1187                            .panels_with_errors
1188                            .insert(InputPanel::Include, e.to_string());
1189                        if should_mark_error.is_none() {
1190                            cx.notify();
1191                        }
1192                        PathMatcher::default()
1193                    }
1194                }
1195            })
1196            .unwrap_or(PathMatcher::default());
1197        let excluded_files = self
1198            .filters_enabled
1199            .then(|| {
1200                match self.parse_path_matches(self.excluded_files_editor.read(cx).text(cx), cx) {
1201                    Ok(excluded_files) => {
1202                        let should_unmark_error =
1203                            self.panels_with_errors.remove(&InputPanel::Exclude);
1204                        if should_unmark_error.is_some() {
1205                            cx.notify();
1206                        }
1207
1208                        excluded_files
1209                    }
1210                    Err(e) => {
1211                        let should_mark_error = self
1212                            .panels_with_errors
1213                            .insert(InputPanel::Exclude, e.to_string());
1214                        if should_mark_error.is_none() {
1215                            cx.notify();
1216                        }
1217                        PathMatcher::default()
1218                    }
1219                }
1220            })
1221            .unwrap_or(PathMatcher::default());
1222
1223        // If the project contains multiple visible worktrees, we match the
1224        // include/exclude patterns against full paths to allow them to be
1225        // disambiguated. For single worktree projects we use worktree relative
1226        // paths for convenience.
1227        let match_full_paths = self
1228            .entity
1229            .read(cx)
1230            .project
1231            .read(cx)
1232            .visible_worktrees(cx)
1233            .count()
1234            > 1;
1235
1236        let query = if self.search_options.contains(SearchOptions::REGEX) {
1237            match SearchQuery::regex(
1238                text,
1239                self.search_options.contains(SearchOptions::WHOLE_WORD),
1240                self.search_options.contains(SearchOptions::CASE_SENSITIVE),
1241                self.search_options.contains(SearchOptions::INCLUDE_IGNORED),
1242                self.search_options
1243                    .contains(SearchOptions::ONE_MATCH_PER_LINE),
1244                included_files,
1245                excluded_files,
1246                match_full_paths,
1247                open_buffers,
1248            ) {
1249                Ok(query) => {
1250                    let should_unmark_error = self.panels_with_errors.remove(&InputPanel::Query);
1251                    if should_unmark_error.is_some() {
1252                        cx.notify();
1253                    }
1254
1255                    Some(query)
1256                }
1257                Err(e) => {
1258                    let should_mark_error = self
1259                        .panels_with_errors
1260                        .insert(InputPanel::Query, e.to_string());
1261                    if should_mark_error.is_none() {
1262                        cx.notify();
1263                    }
1264
1265                    None
1266                }
1267            }
1268        } else {
1269            match SearchQuery::text(
1270                text,
1271                self.search_options.contains(SearchOptions::WHOLE_WORD),
1272                self.search_options.contains(SearchOptions::CASE_SENSITIVE),
1273                self.search_options.contains(SearchOptions::INCLUDE_IGNORED),
1274                included_files,
1275                excluded_files,
1276                match_full_paths,
1277                open_buffers,
1278            ) {
1279                Ok(query) => {
1280                    let should_unmark_error = self.panels_with_errors.remove(&InputPanel::Query);
1281                    if should_unmark_error.is_some() {
1282                        cx.notify();
1283                    }
1284
1285                    Some(query)
1286                }
1287                Err(e) => {
1288                    let should_mark_error = self
1289                        .panels_with_errors
1290                        .insert(InputPanel::Query, e.to_string());
1291                    if should_mark_error.is_none() {
1292                        cx.notify();
1293                    }
1294
1295                    None
1296                }
1297            }
1298        };
1299        if !self.panels_with_errors.is_empty() {
1300            return None;
1301        }
1302        if query.as_ref().is_some_and(|query| query.is_empty()) {
1303            return None;
1304        }
1305        query
1306    }
1307
1308    fn open_buffers(&self, cx: &App, workspace: &Workspace) -> Vec<Entity<Buffer>> {
1309        let mut buffers = Vec::new();
1310        for editor in workspace.items_of_type::<Editor>(cx) {
1311            if let Some(buffer) = editor.read(cx).buffer().read(cx).as_singleton() {
1312                buffers.push(buffer);
1313            }
1314        }
1315        buffers
1316    }
1317
1318    fn parse_path_matches(&self, text: String, cx: &App) -> anyhow::Result<PathMatcher> {
1319        let path_style = self.entity.read(cx).project.read(cx).path_style(cx);
1320        let queries = text
1321            .split(',')
1322            .map(str::trim)
1323            .filter(|maybe_glob_str| !maybe_glob_str.is_empty())
1324            .map(str::to_owned)
1325            .collect::<Vec<_>>();
1326        Ok(PathMatcher::new(&queries, path_style)?)
1327    }
1328
1329    fn select_match(&mut self, direction: Direction, window: &mut Window, cx: &mut Context<Self>) {
1330        if let Some(index) = self.active_match_index {
1331            let match_ranges = self.entity.read(cx).match_ranges.clone();
1332
1333            if !EditorSettings::get_global(cx).search_wrap
1334                && ((direction == Direction::Next && index + 1 >= match_ranges.len())
1335                    || (direction == Direction::Prev && index == 0))
1336            {
1337                crate::show_no_more_matches(window, cx);
1338                return;
1339            }
1340
1341            let new_index = self.results_editor.update(cx, |editor, cx| {
1342                editor.match_index_for_direction(&match_ranges, index, direction, 1, window, cx)
1343            });
1344
1345            let range_to_select = match_ranges[new_index].clone();
1346            self.results_editor.update(cx, |editor, cx| {
1347                let collapse = vim_flavor(cx) == Some(VimFlavor::Vim);
1348                let range_to_select = editor.range_for_match(&range_to_select, collapse);
1349                editor.unfold_ranges(std::slice::from_ref(&range_to_select), false, true, cx);
1350                editor.change_selections(Default::default(), window, cx, |s| {
1351                    s.select_ranges([range_to_select])
1352                });
1353            });
1354        }
1355    }
1356
1357    fn focus_query_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1358        self.query_editor.update(cx, |query_editor, cx| {
1359            query_editor.select_all(&SelectAll, window, cx);
1360        });
1361        let editor_handle = self.query_editor.focus_handle(cx);
1362        window.focus(&editor_handle);
1363    }
1364
1365    fn set_query(&mut self, query: &str, window: &mut Window, cx: &mut Context<Self>) {
1366        self.set_search_editor(SearchInputKind::Query, query, window, cx);
1367        if EditorSettings::get_global(cx).use_smartcase_search
1368            && !query.is_empty()
1369            && self.search_options.contains(SearchOptions::CASE_SENSITIVE)
1370                != contains_uppercase(query)
1371        {
1372            self.toggle_search_option(SearchOptions::CASE_SENSITIVE, cx)
1373        }
1374    }
1375
1376    fn set_search_editor(
1377        &mut self,
1378        kind: SearchInputKind,
1379        text: &str,
1380        window: &mut Window,
1381        cx: &mut Context<Self>,
1382    ) {
1383        let editor = match kind {
1384            SearchInputKind::Query => &self.query_editor,
1385            SearchInputKind::Include => &self.included_files_editor,
1386
1387            SearchInputKind::Exclude => &self.excluded_files_editor,
1388        };
1389        editor.update(cx, |included_editor, cx| {
1390            included_editor.set_text(text, window, cx)
1391        });
1392    }
1393
1394    fn focus_results_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1395        self.query_editor.update(cx, |query_editor, cx| {
1396            let cursor = query_editor.selections.newest_anchor().head();
1397            query_editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1398                s.select_ranges([cursor..cursor])
1399            });
1400        });
1401        let results_handle = self.results_editor.focus_handle(cx);
1402        window.focus(&results_handle);
1403    }
1404
1405    fn entity_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1406        let match_ranges = self.entity.read(cx).match_ranges.clone();
1407        if match_ranges.is_empty() {
1408            self.active_match_index = None;
1409            self.results_editor.update(cx, |editor, cx| {
1410                editor.clear_background_highlights::<Self>(cx);
1411            });
1412        } else {
1413            self.active_match_index = Some(0);
1414            self.update_match_index(cx);
1415            let prev_search_id = mem::replace(&mut self.search_id, self.entity.read(cx).search_id);
1416            let is_new_search = self.search_id != prev_search_id;
1417            self.results_editor.update(cx, |editor, cx| {
1418                if is_new_search {
1419                    let collapse = vim_flavor(cx) == Some(VimFlavor::Vim);
1420                    let range_to_select = match_ranges
1421                        .first()
1422                        .map(|range| editor.range_for_match(range, collapse));
1423                    editor.change_selections(Default::default(), window, cx, |s| {
1424                        s.select_ranges(range_to_select)
1425                    });
1426                    editor.scroll(Point::default(), Some(Axis::Vertical), window, cx);
1427                }
1428                editor.highlight_background::<Self>(
1429                    &match_ranges,
1430                    |theme| theme.colors().search_match_background,
1431                    cx,
1432                );
1433            });
1434            if is_new_search && self.query_editor.focus_handle(cx).is_focused(window) {
1435                self.focus_results_editor(window, cx);
1436            }
1437        }
1438
1439        cx.emit(ViewEvent::UpdateTab);
1440        cx.notify();
1441    }
1442
1443    fn update_match_index(&mut self, cx: &mut Context<Self>) {
1444        let results_editor = self.results_editor.read(cx);
1445        let new_index = active_match_index(
1446            Direction::Next,
1447            &self.entity.read(cx).match_ranges,
1448            &results_editor.selections.newest_anchor().head(),
1449            &results_editor.buffer().read(cx).snapshot(cx),
1450        );
1451        if self.active_match_index != new_index {
1452            self.active_match_index = new_index;
1453            cx.notify();
1454        }
1455    }
1456
1457    pub fn has_matches(&self) -> bool {
1458        self.active_match_index.is_some()
1459    }
1460
1461    fn landing_text_minor(&self, cx: &App) -> impl IntoElement {
1462        let focus_handle = self.focus_handle.clone();
1463        v_flex()
1464            .gap_1()
1465            .child(
1466                Label::new("Hit enter to search. For more options:")
1467                    .color(Color::Muted)
1468                    .mb_2(),
1469            )
1470            .child(
1471                Button::new("filter-paths", "Include/exclude specific paths")
1472                    .icon(IconName::Filter)
1473                    .icon_position(IconPosition::Start)
1474                    .icon_size(IconSize::Small)
1475                    .key_binding(KeyBinding::for_action_in(&ToggleFilters, &focus_handle, cx))
1476                    .on_click(|_event, window, cx| {
1477                        window.dispatch_action(ToggleFilters.boxed_clone(), cx)
1478                    }),
1479            )
1480            .child(
1481                Button::new("find-replace", "Find and replace")
1482                    .icon(IconName::Replace)
1483                    .icon_position(IconPosition::Start)
1484                    .icon_size(IconSize::Small)
1485                    .key_binding(KeyBinding::for_action_in(&ToggleReplace, &focus_handle, cx))
1486                    .on_click(|_event, window, cx| {
1487                        window.dispatch_action(ToggleReplace.boxed_clone(), cx)
1488                    }),
1489            )
1490            .child(
1491                Button::new("regex", "Match with regex")
1492                    .icon(IconName::Regex)
1493                    .icon_position(IconPosition::Start)
1494                    .icon_size(IconSize::Small)
1495                    .key_binding(KeyBinding::for_action_in(&ToggleRegex, &focus_handle, cx))
1496                    .on_click(|_event, window, cx| {
1497                        window.dispatch_action(ToggleRegex.boxed_clone(), cx)
1498                    }),
1499            )
1500            .child(
1501                Button::new("match-case", "Match case")
1502                    .icon(IconName::CaseSensitive)
1503                    .icon_position(IconPosition::Start)
1504                    .icon_size(IconSize::Small)
1505                    .key_binding(KeyBinding::for_action_in(
1506                        &ToggleCaseSensitive,
1507                        &focus_handle,
1508                        cx,
1509                    ))
1510                    .on_click(|_event, window, cx| {
1511                        window.dispatch_action(ToggleCaseSensitive.boxed_clone(), cx)
1512                    }),
1513            )
1514            .child(
1515                Button::new("match-whole-words", "Match whole words")
1516                    .icon(IconName::WholeWord)
1517                    .icon_position(IconPosition::Start)
1518                    .icon_size(IconSize::Small)
1519                    .key_binding(KeyBinding::for_action_in(
1520                        &ToggleWholeWord,
1521                        &focus_handle,
1522                        cx,
1523                    ))
1524                    .on_click(|_event, window, cx| {
1525                        window.dispatch_action(ToggleWholeWord.boxed_clone(), cx)
1526                    }),
1527            )
1528    }
1529
1530    fn border_color_for(&self, panel: InputPanel, cx: &App) -> Hsla {
1531        if self.panels_with_errors.contains_key(&panel) {
1532            Color::Error.color(cx)
1533        } else {
1534            cx.theme().colors().border
1535        }
1536    }
1537
1538    fn move_focus_to_results(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1539        if !self.results_editor.focus_handle(cx).is_focused(window)
1540            && !self.entity.read(cx).match_ranges.is_empty()
1541        {
1542            cx.stop_propagation();
1543            self.focus_results_editor(window, cx)
1544        }
1545    }
1546
1547    #[cfg(any(test, feature = "test-support"))]
1548    pub fn results_editor(&self) -> &Entity<Editor> {
1549        &self.results_editor
1550    }
1551
1552    fn adjust_query_regex_language(&self, cx: &mut App) {
1553        let enable = self.search_options.contains(SearchOptions::REGEX);
1554        let query_buffer = self
1555            .query_editor
1556            .read(cx)
1557            .buffer()
1558            .read(cx)
1559            .as_singleton()
1560            .expect("query editor should be backed by a singleton buffer");
1561        if enable {
1562            if let Some(regex_language) = self.regex_language.clone() {
1563                query_buffer.update(cx, |query_buffer, cx| {
1564                    query_buffer.set_language(Some(regex_language), cx);
1565                })
1566            }
1567        } else {
1568            query_buffer.update(cx, |query_buffer, cx| {
1569                query_buffer.set_language(None, cx);
1570            })
1571        }
1572    }
1573}
1574
1575fn buffer_search_query(
1576    workspace: &mut Workspace,
1577    item: &dyn ItemHandle,
1578    cx: &mut Context<Workspace>,
1579) -> Option<String> {
1580    let buffer_search_bar = workspace
1581        .pane_for(item)
1582        .and_then(|pane| {
1583            pane.read(cx)
1584                .toolbar()
1585                .read(cx)
1586                .item_of_type::<BufferSearchBar>()
1587        })?
1588        .read(cx);
1589    if buffer_search_bar.query_editor_focused() {
1590        let buffer_search_query = buffer_search_bar.query(cx);
1591        if !buffer_search_query.is_empty() {
1592            return Some(buffer_search_query);
1593        }
1594    }
1595    None
1596}
1597
1598impl Default for ProjectSearchBar {
1599    fn default() -> Self {
1600        Self::new()
1601    }
1602}
1603
1604impl ProjectSearchBar {
1605    pub fn new() -> Self {
1606        Self {
1607            active_project_search: None,
1608            subscription: None,
1609        }
1610    }
1611
1612    fn confirm(&mut self, _: &Confirm, window: &mut Window, cx: &mut Context<Self>) {
1613        if let Some(search_view) = self.active_project_search.as_ref() {
1614            search_view.update(cx, |search_view, cx| {
1615                if !search_view
1616                    .replacement_editor
1617                    .focus_handle(cx)
1618                    .is_focused(window)
1619                {
1620                    cx.stop_propagation();
1621                    search_view
1622                        .prompt_to_save_if_dirty_then_search(window, cx)
1623                        .detach_and_log_err(cx);
1624                }
1625            });
1626        }
1627    }
1628
1629    fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
1630        self.cycle_field(Direction::Next, window, cx);
1631    }
1632
1633    fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
1634        self.cycle_field(Direction::Prev, window, cx);
1635    }
1636
1637    fn focus_search(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1638        if let Some(search_view) = self.active_project_search.as_ref() {
1639            search_view.update(cx, |search_view, cx| {
1640                search_view.query_editor.focus_handle(cx).focus(window);
1641            });
1642        }
1643    }
1644
1645    fn cycle_field(&mut self, direction: Direction, window: &mut Window, cx: &mut Context<Self>) {
1646        let active_project_search = match &self.active_project_search {
1647            Some(active_project_search) => active_project_search,
1648            None => return,
1649        };
1650
1651        active_project_search.update(cx, |project_view, cx| {
1652            let mut views = vec![project_view.query_editor.focus_handle(cx)];
1653            if project_view.replace_enabled {
1654                views.push(project_view.replacement_editor.focus_handle(cx));
1655            }
1656            if project_view.filters_enabled {
1657                views.extend([
1658                    project_view.included_files_editor.focus_handle(cx),
1659                    project_view.excluded_files_editor.focus_handle(cx),
1660                ]);
1661            }
1662            let current_index = match views.iter().position(|focus| focus.is_focused(window)) {
1663                Some(index) => index,
1664                None => return,
1665            };
1666
1667            let new_index = match direction {
1668                Direction::Next => (current_index + 1) % views.len(),
1669                Direction::Prev if current_index == 0 => views.len() - 1,
1670                Direction::Prev => (current_index - 1) % views.len(),
1671            };
1672            let next_focus_handle = &views[new_index];
1673            window.focus(next_focus_handle);
1674            cx.stop_propagation();
1675        });
1676    }
1677
1678    pub(crate) fn toggle_search_option(
1679        &mut self,
1680        option: SearchOptions,
1681        window: &mut Window,
1682        cx: &mut Context<Self>,
1683    ) -> bool {
1684        if self.active_project_search.is_none() {
1685            return false;
1686        }
1687
1688        cx.spawn_in(window, async move |this, cx| {
1689            let task = this.update_in(cx, |this, window, cx| {
1690                let search_view = this.active_project_search.as_ref()?;
1691                search_view.update(cx, |search_view, cx| {
1692                    search_view.toggle_search_option(option, cx);
1693                    search_view
1694                        .entity
1695                        .read(cx)
1696                        .active_query
1697                        .is_some()
1698                        .then(|| search_view.prompt_to_save_if_dirty_then_search(window, cx))
1699                })
1700            })?;
1701            if let Some(task) = task {
1702                task.await?;
1703            }
1704            this.update(cx, |_, cx| {
1705                cx.notify();
1706            })?;
1707            anyhow::Ok(())
1708        })
1709        .detach();
1710        true
1711    }
1712
1713    fn toggle_replace(&mut self, _: &ToggleReplace, window: &mut Window, cx: &mut Context<Self>) {
1714        if let Some(search) = &self.active_project_search {
1715            search.update(cx, |this, cx| {
1716                this.replace_enabled = !this.replace_enabled;
1717                let editor_to_focus = if this.replace_enabled {
1718                    this.replacement_editor.focus_handle(cx)
1719                } else {
1720                    this.query_editor.focus_handle(cx)
1721                };
1722                window.focus(&editor_to_focus);
1723                cx.notify();
1724            });
1725        }
1726    }
1727
1728    fn toggle_filters(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
1729        if let Some(search_view) = self.active_project_search.as_ref() {
1730            search_view.update(cx, |search_view, cx| {
1731                search_view.toggle_filters(cx);
1732                search_view
1733                    .included_files_editor
1734                    .update(cx, |_, cx| cx.notify());
1735                search_view
1736                    .excluded_files_editor
1737                    .update(cx, |_, cx| cx.notify());
1738                window.refresh();
1739                cx.notify();
1740            });
1741            cx.notify();
1742            true
1743        } else {
1744            false
1745        }
1746    }
1747
1748    fn toggle_opened_only(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
1749        if self.active_project_search.is_none() {
1750            return false;
1751        }
1752
1753        cx.spawn_in(window, async move |this, cx| {
1754            let task = this.update_in(cx, |this, window, cx| {
1755                let search_view = this.active_project_search.as_ref()?;
1756                search_view.update(cx, |search_view, cx| {
1757                    search_view.toggle_opened_only(window, cx);
1758                    search_view
1759                        .entity
1760                        .read(cx)
1761                        .active_query
1762                        .is_some()
1763                        .then(|| search_view.prompt_to_save_if_dirty_then_search(window, cx))
1764                })
1765            })?;
1766            if let Some(task) = task {
1767                task.await?;
1768            }
1769            this.update(cx, |_, cx| {
1770                cx.notify();
1771            })?;
1772            anyhow::Ok(())
1773        })
1774        .detach();
1775        true
1776    }
1777
1778    fn is_opened_only_enabled(&self, cx: &App) -> bool {
1779        if let Some(search_view) = self.active_project_search.as_ref() {
1780            search_view.read(cx).included_opened_only
1781        } else {
1782            false
1783        }
1784    }
1785
1786    fn move_focus_to_results(&self, window: &mut Window, cx: &mut Context<Self>) {
1787        if let Some(search_view) = self.active_project_search.as_ref() {
1788            search_view.update(cx, |search_view, cx| {
1789                search_view.move_focus_to_results(window, cx);
1790            });
1791            cx.notify();
1792        }
1793    }
1794
1795    fn next_history_query(
1796        &mut self,
1797        _: &NextHistoryQuery,
1798        window: &mut Window,
1799        cx: &mut Context<Self>,
1800    ) {
1801        if let Some(search_view) = self.active_project_search.as_ref() {
1802            search_view.update(cx, |search_view, cx| {
1803                for (editor, kind) in [
1804                    (search_view.query_editor.clone(), SearchInputKind::Query),
1805                    (
1806                        search_view.included_files_editor.clone(),
1807                        SearchInputKind::Include,
1808                    ),
1809                    (
1810                        search_view.excluded_files_editor.clone(),
1811                        SearchInputKind::Exclude,
1812                    ),
1813                ] {
1814                    if editor.focus_handle(cx).is_focused(window) {
1815                        let new_query = search_view.entity.update(cx, |model, cx| {
1816                            let project = model.project.clone();
1817
1818                            if let Some(new_query) = project.update(cx, |project, _| {
1819                                project
1820                                    .search_history_mut(kind)
1821                                    .next(model.cursor_mut(kind))
1822                                    .map(str::to_string)
1823                            }) {
1824                                new_query
1825                            } else {
1826                                model.cursor_mut(kind).reset();
1827                                String::new()
1828                            }
1829                        });
1830                        search_view.set_search_editor(kind, &new_query, window, cx);
1831                    }
1832                }
1833            });
1834        }
1835    }
1836
1837    fn previous_history_query(
1838        &mut self,
1839        _: &PreviousHistoryQuery,
1840        window: &mut Window,
1841        cx: &mut Context<Self>,
1842    ) {
1843        if let Some(search_view) = self.active_project_search.as_ref() {
1844            search_view.update(cx, |search_view, cx| {
1845                for (editor, kind) in [
1846                    (search_view.query_editor.clone(), SearchInputKind::Query),
1847                    (
1848                        search_view.included_files_editor.clone(),
1849                        SearchInputKind::Include,
1850                    ),
1851                    (
1852                        search_view.excluded_files_editor.clone(),
1853                        SearchInputKind::Exclude,
1854                    ),
1855                ] {
1856                    if editor.focus_handle(cx).is_focused(window) {
1857                        if editor.read(cx).text(cx).is_empty()
1858                            && let Some(new_query) = search_view
1859                                .entity
1860                                .read(cx)
1861                                .project
1862                                .read(cx)
1863                                .search_history(kind)
1864                                .current(search_view.entity.read(cx).cursor(kind))
1865                                .map(str::to_string)
1866                        {
1867                            search_view.set_search_editor(kind, &new_query, window, cx);
1868                            return;
1869                        }
1870
1871                        if let Some(new_query) = search_view.entity.update(cx, |model, cx| {
1872                            let project = model.project.clone();
1873                            project.update(cx, |project, _| {
1874                                project
1875                                    .search_history_mut(kind)
1876                                    .previous(model.cursor_mut(kind))
1877                                    .map(str::to_string)
1878                            })
1879                        }) {
1880                            search_view.set_search_editor(kind, &new_query, window, cx);
1881                        }
1882                    }
1883                }
1884            });
1885        }
1886    }
1887
1888    fn select_next_match(
1889        &mut self,
1890        _: &SelectNextMatch,
1891        window: &mut Window,
1892        cx: &mut Context<Self>,
1893    ) {
1894        if let Some(search) = self.active_project_search.as_ref() {
1895            search.update(cx, |this, cx| {
1896                this.select_match(Direction::Next, window, cx);
1897            })
1898        }
1899    }
1900
1901    fn select_prev_match(
1902        &mut self,
1903        _: &SelectPreviousMatch,
1904        window: &mut Window,
1905        cx: &mut Context<Self>,
1906    ) {
1907        if let Some(search) = self.active_project_search.as_ref() {
1908            search.update(cx, |this, cx| {
1909                this.select_match(Direction::Prev, window, cx);
1910            })
1911        }
1912    }
1913}
1914
1915impl Render for ProjectSearchBar {
1916    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1917        let Some(search) = self.active_project_search.clone() else {
1918            return div();
1919        };
1920        let search = search.read(cx);
1921        let focus_handle = search.focus_handle(cx);
1922
1923        let container_width = window.viewport_size().width;
1924        let input_width = SearchInputWidth::calc_width(container_width);
1925
1926        let input_base_styles = |panel: InputPanel| {
1927            input_base_styles(search.border_color_for(panel, cx), |div| match panel {
1928                InputPanel::Query | InputPanel::Replacement => div.w(input_width),
1929                InputPanel::Include | InputPanel::Exclude => div.flex_grow(),
1930            })
1931        };
1932        let theme_colors = cx.theme().colors();
1933        let project_search = search.entity.read(cx);
1934        let limit_reached = project_search.limit_reached;
1935
1936        let color_override = match (
1937            &project_search.pending_search,
1938            project_search.no_results,
1939            &project_search.active_query,
1940            &project_search.last_search_query_text,
1941        ) {
1942            (None, Some(true), Some(q), Some(p)) if q.as_str() == p => Some(Color::Error),
1943            _ => None,
1944        };
1945
1946        let match_text = search
1947            .active_match_index
1948            .and_then(|index| {
1949                let index = index + 1;
1950                let match_quantity = project_search.match_ranges.len();
1951                if match_quantity > 0 {
1952                    debug_assert!(match_quantity >= index);
1953                    if limit_reached {
1954                        Some(format!("{index}/{match_quantity}+"))
1955                    } else {
1956                        Some(format!("{index}/{match_quantity}"))
1957                    }
1958                } else {
1959                    None
1960                }
1961            })
1962            .unwrap_or_else(|| "0/0".to_string());
1963
1964        let query_column = input_base_styles(InputPanel::Query)
1965            .on_action(cx.listener(|this, action, window, cx| this.confirm(action, window, cx)))
1966            .on_action(cx.listener(|this, action, window, cx| {
1967                this.previous_history_query(action, window, cx)
1968            }))
1969            .on_action(
1970                cx.listener(|this, action, window, cx| this.next_history_query(action, window, cx)),
1971            )
1972            .child(render_text_input(&search.query_editor, color_override, cx))
1973            .child(
1974                h_flex()
1975                    .gap_1()
1976                    .child(SearchOption::CaseSensitive.as_button(
1977                        search.search_options,
1978                        SearchSource::Project(cx),
1979                        focus_handle.clone(),
1980                    ))
1981                    .child(SearchOption::WholeWord.as_button(
1982                        search.search_options,
1983                        SearchSource::Project(cx),
1984                        focus_handle.clone(),
1985                    ))
1986                    .child(SearchOption::Regex.as_button(
1987                        search.search_options,
1988                        SearchSource::Project(cx),
1989                        focus_handle.clone(),
1990                    )),
1991            );
1992
1993        let query_focus = search.query_editor.focus_handle(cx);
1994
1995        let matches_column = h_flex()
1996            .pl_2()
1997            .ml_2()
1998            .border_l_1()
1999            .border_color(theme_colors.border_variant)
2000            .child(render_action_button(
2001                "project-search-nav-button",
2002                IconName::ChevronLeft,
2003                search
2004                    .active_match_index
2005                    .is_none()
2006                    .then_some(ActionButtonState::Disabled),
2007                "Select Previous Match",
2008                &SelectPreviousMatch,
2009                query_focus.clone(),
2010            ))
2011            .child(render_action_button(
2012                "project-search-nav-button",
2013                IconName::ChevronRight,
2014                search
2015                    .active_match_index
2016                    .is_none()
2017                    .then_some(ActionButtonState::Disabled),
2018                "Select Next Match",
2019                &SelectNextMatch,
2020                query_focus,
2021            ))
2022            .child(
2023                div()
2024                    .id("matches")
2025                    .ml_2()
2026                    .min_w(rems_from_px(40.))
2027                    .child(Label::new(match_text).size(LabelSize::Small).color(
2028                        if search.active_match_index.is_some() {
2029                            Color::Default
2030                        } else {
2031                            Color::Disabled
2032                        },
2033                    ))
2034                    .when(limit_reached, |el| {
2035                        el.tooltip(Tooltip::text(
2036                            "Search limits reached.\nTry narrowing your search.",
2037                        ))
2038                    }),
2039            );
2040
2041        let mode_column = h_flex()
2042            .gap_1()
2043            .min_w_64()
2044            .child(
2045                IconButton::new("project-search-filter-button", IconName::Filter)
2046                    .shape(IconButtonShape::Square)
2047                    .tooltip(|_window, cx| {
2048                        Tooltip::for_action("Toggle Filters", &ToggleFilters, cx)
2049                    })
2050                    .on_click(cx.listener(|this, _, window, cx| {
2051                        this.toggle_filters(window, cx);
2052                    }))
2053                    .toggle_state(
2054                        self.active_project_search
2055                            .as_ref()
2056                            .map(|search| search.read(cx).filters_enabled)
2057                            .unwrap_or_default(),
2058                    )
2059                    .tooltip({
2060                        let focus_handle = focus_handle.clone();
2061                        move |_window, cx| {
2062                            Tooltip::for_action_in(
2063                                "Toggle Filters",
2064                                &ToggleFilters,
2065                                &focus_handle,
2066                                cx,
2067                            )
2068                        }
2069                    }),
2070            )
2071            .child(render_action_button(
2072                "project-search",
2073                IconName::Replace,
2074                self.active_project_search
2075                    .as_ref()
2076                    .map(|search| search.read(cx).replace_enabled)
2077                    .and_then(|enabled| enabled.then_some(ActionButtonState::Toggled)),
2078                "Toggle Replace",
2079                &ToggleReplace,
2080                focus_handle.clone(),
2081            ))
2082            .child(matches_column);
2083
2084        let search_line = h_flex()
2085            .w_full()
2086            .gap_2()
2087            .child(query_column)
2088            .child(mode_column);
2089
2090        let replace_line = search.replace_enabled.then(|| {
2091            let replace_column = input_base_styles(InputPanel::Replacement)
2092                .child(render_text_input(&search.replacement_editor, None, cx));
2093
2094            let focus_handle = search.replacement_editor.read(cx).focus_handle(cx);
2095
2096            let replace_actions = h_flex()
2097                .min_w_64()
2098                .gap_1()
2099                .child(render_action_button(
2100                    "project-search-replace-button",
2101                    IconName::ReplaceNext,
2102                    Default::default(),
2103                    "Replace Next Match",
2104                    &ReplaceNext,
2105                    focus_handle.clone(),
2106                ))
2107                .child(render_action_button(
2108                    "project-search-replace-button",
2109                    IconName::ReplaceAll,
2110                    Default::default(),
2111                    "Replace All Matches",
2112                    &ReplaceAll,
2113                    focus_handle,
2114                ));
2115
2116            h_flex()
2117                .w_full()
2118                .gap_2()
2119                .child(replace_column)
2120                .child(replace_actions)
2121        });
2122
2123        let filter_line = search.filters_enabled.then(|| {
2124            let include = input_base_styles(InputPanel::Include)
2125                .on_action(cx.listener(|this, action, window, cx| {
2126                    this.previous_history_query(action, window, cx)
2127                }))
2128                .on_action(cx.listener(|this, action, window, cx| {
2129                    this.next_history_query(action, window, cx)
2130                }))
2131                .child(render_text_input(&search.included_files_editor, None, cx));
2132            let exclude = input_base_styles(InputPanel::Exclude)
2133                .on_action(cx.listener(|this, action, window, cx| {
2134                    this.previous_history_query(action, window, cx)
2135                }))
2136                .on_action(cx.listener(|this, action, window, cx| {
2137                    this.next_history_query(action, window, cx)
2138                }))
2139                .child(render_text_input(&search.excluded_files_editor, None, cx));
2140            let mode_column = h_flex()
2141                .gap_1()
2142                .min_w_64()
2143                .child(
2144                    IconButton::new("project-search-opened-only", IconName::FolderSearch)
2145                        .shape(IconButtonShape::Square)
2146                        .toggle_state(self.is_opened_only_enabled(cx))
2147                        .tooltip(Tooltip::text("Only Search Open Files"))
2148                        .on_click(cx.listener(|this, _, window, cx| {
2149                            this.toggle_opened_only(window, cx);
2150                        })),
2151                )
2152                .child(SearchOption::IncludeIgnored.as_button(
2153                    search.search_options,
2154                    SearchSource::Project(cx),
2155                    focus_handle.clone(),
2156                ));
2157            h_flex()
2158                .w_full()
2159                .gap_2()
2160                .child(
2161                    h_flex()
2162                        .gap_2()
2163                        .w(input_width)
2164                        .child(include)
2165                        .child(exclude),
2166                )
2167                .child(mode_column)
2168        });
2169
2170        let mut key_context = KeyContext::default();
2171        key_context.add("ProjectSearchBar");
2172        if search
2173            .replacement_editor
2174            .focus_handle(cx)
2175            .is_focused(window)
2176        {
2177            key_context.add("in_replace");
2178        }
2179
2180        let query_error_line = search
2181            .panels_with_errors
2182            .get(&InputPanel::Query)
2183            .map(|error| {
2184                Label::new(error)
2185                    .size(LabelSize::Small)
2186                    .color(Color::Error)
2187                    .mt_neg_1()
2188                    .ml_2()
2189            });
2190
2191        let filter_error_line = search
2192            .panels_with_errors
2193            .get(&InputPanel::Include)
2194            .or_else(|| search.panels_with_errors.get(&InputPanel::Exclude))
2195            .map(|error| {
2196                Label::new(error)
2197                    .size(LabelSize::Small)
2198                    .color(Color::Error)
2199                    .mt_neg_1()
2200                    .ml_2()
2201            });
2202
2203        v_flex()
2204            .gap_2()
2205            .py(px(1.0))
2206            .w_full()
2207            .key_context(key_context)
2208            .on_action(cx.listener(|this, _: &ToggleFocus, window, cx| {
2209                this.move_focus_to_results(window, cx)
2210            }))
2211            .on_action(cx.listener(|this, _: &ToggleFilters, window, cx| {
2212                this.toggle_filters(window, cx);
2213            }))
2214            .capture_action(cx.listener(Self::tab))
2215            .capture_action(cx.listener(Self::backtab))
2216            .on_action(cx.listener(|this, action, window, cx| this.confirm(action, window, cx)))
2217            .on_action(cx.listener(|this, action, window, cx| {
2218                this.toggle_replace(action, window, cx);
2219            }))
2220            .on_action(cx.listener(|this, _: &ToggleWholeWord, window, cx| {
2221                this.toggle_search_option(SearchOptions::WHOLE_WORD, window, cx);
2222            }))
2223            .on_action(cx.listener(|this, _: &ToggleCaseSensitive, window, cx| {
2224                this.toggle_search_option(SearchOptions::CASE_SENSITIVE, window, cx);
2225            }))
2226            .on_action(cx.listener(|this, action, window, cx| {
2227                if let Some(search) = this.active_project_search.as_ref() {
2228                    search.update(cx, |this, cx| {
2229                        this.replace_next(action, window, cx);
2230                    })
2231                }
2232            }))
2233            .on_action(cx.listener(|this, action, window, cx| {
2234                if let Some(search) = this.active_project_search.as_ref() {
2235                    search.update(cx, |this, cx| {
2236                        this.replace_all(action, window, cx);
2237                    })
2238                }
2239            }))
2240            .when(search.filters_enabled, |this| {
2241                this.on_action(cx.listener(|this, _: &ToggleIncludeIgnored, window, cx| {
2242                    this.toggle_search_option(SearchOptions::INCLUDE_IGNORED, window, cx);
2243                }))
2244            })
2245            .on_action(cx.listener(Self::select_next_match))
2246            .on_action(cx.listener(Self::select_prev_match))
2247            .child(search_line)
2248            .children(query_error_line)
2249            .children(replace_line)
2250            .children(filter_line)
2251            .children(filter_error_line)
2252    }
2253}
2254
2255impl EventEmitter<ToolbarItemEvent> for ProjectSearchBar {}
2256
2257impl ToolbarItemView for ProjectSearchBar {
2258    fn set_active_pane_item(
2259        &mut self,
2260        active_pane_item: Option<&dyn ItemHandle>,
2261        _: &mut Window,
2262        cx: &mut Context<Self>,
2263    ) -> ToolbarItemLocation {
2264        cx.notify();
2265        self.subscription = None;
2266        self.active_project_search = None;
2267        if let Some(search) = active_pane_item.and_then(|i| i.downcast::<ProjectSearchView>()) {
2268            self.subscription = Some(cx.observe(&search, |_, _, cx| cx.notify()));
2269            self.active_project_search = Some(search);
2270            ToolbarItemLocation::PrimaryLeft {}
2271        } else {
2272            ToolbarItemLocation::Hidden
2273        }
2274    }
2275}
2276
2277fn register_workspace_action<A: Action>(
2278    workspace: &mut Workspace,
2279    callback: fn(&mut ProjectSearchBar, &A, &mut Window, &mut Context<ProjectSearchBar>),
2280) {
2281    workspace.register_action(move |workspace, action: &A, window, cx| {
2282        if workspace.has_active_modal(window, cx) && !workspace.hide_modal(window, cx) {
2283            cx.propagate();
2284            return;
2285        }
2286
2287        workspace.active_pane().update(cx, |pane, cx| {
2288            pane.toolbar().update(cx, move |workspace, cx| {
2289                if let Some(search_bar) = workspace.item_of_type::<ProjectSearchBar>() {
2290                    search_bar.update(cx, move |search_bar, cx| {
2291                        if search_bar.active_project_search.is_some() {
2292                            callback(search_bar, action, window, cx);
2293                            cx.notify();
2294                        } else {
2295                            cx.propagate();
2296                        }
2297                    });
2298                }
2299            });
2300        })
2301    });
2302}
2303
2304fn register_workspace_action_for_present_search<A: Action>(
2305    workspace: &mut Workspace,
2306    callback: fn(&mut Workspace, &A, &mut Window, &mut Context<Workspace>),
2307) {
2308    workspace.register_action(move |workspace, action: &A, window, cx| {
2309        if workspace.has_active_modal(window, cx) && !workspace.hide_modal(window, cx) {
2310            cx.propagate();
2311            return;
2312        }
2313
2314        let should_notify = workspace
2315            .active_pane()
2316            .read(cx)
2317            .toolbar()
2318            .read(cx)
2319            .item_of_type::<ProjectSearchBar>()
2320            .map(|search_bar| search_bar.read(cx).active_project_search.is_some())
2321            .unwrap_or(false);
2322        if should_notify {
2323            callback(workspace, action, window, cx);
2324            cx.notify();
2325        } else {
2326            cx.propagate();
2327        }
2328    });
2329}
2330
2331#[cfg(any(test, feature = "test-support"))]
2332pub fn perform_project_search(
2333    search_view: &Entity<ProjectSearchView>,
2334    text: impl Into<std::sync::Arc<str>>,
2335    cx: &mut gpui::VisualTestContext,
2336) {
2337    cx.run_until_parked();
2338    search_view.update_in(cx, |search_view, window, cx| {
2339        search_view.query_editor.update(cx, |query_editor, cx| {
2340            query_editor.set_text(text, window, cx)
2341        });
2342        search_view.search(cx);
2343    });
2344    cx.run_until_parked();
2345}
2346
2347#[cfg(test)]
2348pub mod tests {
2349    use std::{ops::Deref as _, sync::Arc, time::Duration};
2350
2351    use super::*;
2352    use editor::{DisplayPoint, display_map::DisplayRow};
2353    use gpui::{Action, TestAppContext, VisualTestContext, WindowHandle};
2354    use language::{FakeLspAdapter, rust_lang};
2355    use project::FakeFs;
2356    use serde_json::json;
2357    use settings::{InlayHintSettingsContent, SettingsStore};
2358    use util::{path, paths::PathStyle, rel_path::rel_path};
2359    use util_macros::perf;
2360    use workspace::DeploySearch;
2361
2362    #[perf]
2363    #[gpui::test]
2364    async fn test_project_search(cx: &mut TestAppContext) {
2365        init_test(cx);
2366
2367        let fs = FakeFs::new(cx.background_executor.clone());
2368        fs.insert_tree(
2369            path!("/dir"),
2370            json!({
2371                "one.rs": "const ONE: usize = 1;",
2372                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2373                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2374                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2375            }),
2376        )
2377        .await;
2378        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
2379        let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
2380        let workspace = window.root(cx).unwrap();
2381        let search = cx.new(|cx| ProjectSearch::new(project.clone(), cx));
2382        let search_view = cx.add_window(|window, cx| {
2383            ProjectSearchView::new(workspace.downgrade(), search.clone(), window, cx, None)
2384        });
2385
2386        perform_search(search_view, "TWO", cx);
2387        search_view.update(cx, |search_view, window, cx| {
2388            assert_eq!(
2389                search_view
2390                    .results_editor
2391                    .update(cx, |editor, cx| editor.display_text(cx)),
2392                "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;"
2393            );
2394            let match_background_color = cx.theme().colors().search_match_background;
2395            let selection_background_color = cx.theme().colors().editor_document_highlight_bracket_background;
2396            assert_eq!(
2397                search_view
2398                    .results_editor
2399                    .update(cx, |editor, cx| editor.all_text_background_highlights(window, cx)),
2400                &[
2401                    (
2402                        DisplayPoint::new(DisplayRow(2), 32)..DisplayPoint::new(DisplayRow(2), 35),
2403                        match_background_color
2404                    ),
2405                    (
2406                        DisplayPoint::new(DisplayRow(2), 37)..DisplayPoint::new(DisplayRow(2), 40),
2407                        selection_background_color
2408                    ),
2409                    (
2410                        DisplayPoint::new(DisplayRow(2), 37)..DisplayPoint::new(DisplayRow(2), 40),
2411                        match_background_color
2412                    ),
2413                    (
2414                        DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(5), 9),
2415                        selection_background_color
2416                    ),
2417                    (
2418                        DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(5), 9),
2419                        match_background_color
2420                    ),
2421
2422                ]
2423            );
2424            assert_eq!(search_view.active_match_index, Some(0));
2425            assert_eq!(
2426                search_view
2427                    .results_editor
2428                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2429                [DisplayPoint::new(DisplayRow(2), 32)..DisplayPoint::new(DisplayRow(2), 35)]
2430            );
2431
2432            search_view.select_match(Direction::Next, window, cx);
2433        }).unwrap();
2434
2435        search_view
2436            .update(cx, |search_view, window, cx| {
2437                assert_eq!(search_view.active_match_index, Some(1));
2438                assert_eq!(
2439                    search_view
2440                        .results_editor
2441                        .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2442                    [DisplayPoint::new(DisplayRow(2), 37)..DisplayPoint::new(DisplayRow(2), 40)]
2443                );
2444                search_view.select_match(Direction::Next, window, cx);
2445            })
2446            .unwrap();
2447
2448        search_view
2449            .update(cx, |search_view, window, cx| {
2450                assert_eq!(search_view.active_match_index, Some(2));
2451                assert_eq!(
2452                    search_view
2453                        .results_editor
2454                        .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2455                    [DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(5), 9)]
2456                );
2457                search_view.select_match(Direction::Next, window, cx);
2458            })
2459            .unwrap();
2460
2461        search_view
2462            .update(cx, |search_view, window, cx| {
2463                assert_eq!(search_view.active_match_index, Some(0));
2464                assert_eq!(
2465                    search_view
2466                        .results_editor
2467                        .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2468                    [DisplayPoint::new(DisplayRow(2), 32)..DisplayPoint::new(DisplayRow(2), 35)]
2469                );
2470                search_view.select_match(Direction::Prev, window, cx);
2471            })
2472            .unwrap();
2473
2474        search_view
2475            .update(cx, |search_view, window, cx| {
2476                assert_eq!(search_view.active_match_index, Some(2));
2477                assert_eq!(
2478                    search_view
2479                        .results_editor
2480                        .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2481                    [DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(5), 9)]
2482                );
2483                search_view.select_match(Direction::Prev, window, cx);
2484            })
2485            .unwrap();
2486
2487        search_view
2488            .update(cx, |search_view, _, cx| {
2489                assert_eq!(search_view.active_match_index, Some(1));
2490                assert_eq!(
2491                    search_view
2492                        .results_editor
2493                        .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2494                    [DisplayPoint::new(DisplayRow(2), 37)..DisplayPoint::new(DisplayRow(2), 40)]
2495                );
2496            })
2497            .unwrap();
2498    }
2499
2500    #[perf]
2501    #[gpui::test]
2502    async fn test_deploy_project_search_focus(cx: &mut TestAppContext) {
2503        init_test(cx);
2504
2505        let fs = FakeFs::new(cx.background_executor.clone());
2506        fs.insert_tree(
2507            "/dir",
2508            json!({
2509                "one.rs": "const ONE: usize = 1;",
2510                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2511                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2512                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2513            }),
2514        )
2515        .await;
2516        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
2517        let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
2518        let workspace = window;
2519        let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
2520
2521        let active_item = cx.read(|cx| {
2522            workspace
2523                .read(cx)
2524                .unwrap()
2525                .active_pane()
2526                .read(cx)
2527                .active_item()
2528                .and_then(|item| item.downcast::<ProjectSearchView>())
2529        });
2530        assert!(
2531            active_item.is_none(),
2532            "Expected no search panel to be active"
2533        );
2534
2535        window
2536            .update(cx, move |workspace, window, cx| {
2537                assert_eq!(workspace.panes().len(), 1);
2538                workspace.panes()[0].update(cx, |pane, cx| {
2539                    pane.toolbar()
2540                        .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
2541                });
2542
2543                ProjectSearchView::deploy_search(
2544                    workspace,
2545                    &workspace::DeploySearch::find(),
2546                    window,
2547                    cx,
2548                )
2549            })
2550            .unwrap();
2551
2552        let Some(search_view) = cx.read(|cx| {
2553            workspace
2554                .read(cx)
2555                .unwrap()
2556                .active_pane()
2557                .read(cx)
2558                .active_item()
2559                .and_then(|item| item.downcast::<ProjectSearchView>())
2560        }) else {
2561            panic!("Search view expected to appear after new search event trigger")
2562        };
2563
2564        cx.spawn(|mut cx| async move {
2565            window
2566                .update(&mut cx, |_, window, cx| {
2567                    window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2568                })
2569                .unwrap();
2570        })
2571        .detach();
2572        cx.background_executor.run_until_parked();
2573        window
2574            .update(cx, |_, window, cx| {
2575                search_view.update(cx, |search_view, cx| {
2576                    assert!(
2577                        search_view.query_editor.focus_handle(cx).is_focused(window),
2578                        "Empty search view should be focused after the toggle focus event: no results panel to focus on",
2579                    );
2580                });
2581        }).unwrap();
2582
2583        window
2584            .update(cx, |_, window, cx| {
2585                search_view.update(cx, |search_view, cx| {
2586                    let query_editor = &search_view.query_editor;
2587                    assert!(
2588                        query_editor.focus_handle(cx).is_focused(window),
2589                        "Search view should be focused after the new search view is activated",
2590                    );
2591                    let query_text = query_editor.read(cx).text(cx);
2592                    assert!(
2593                        query_text.is_empty(),
2594                        "New search query should be empty but got '{query_text}'",
2595                    );
2596                    let results_text = search_view
2597                        .results_editor
2598                        .update(cx, |editor, cx| editor.display_text(cx));
2599                    assert!(
2600                        results_text.is_empty(),
2601                        "Empty search view should have no results but got '{results_text}'"
2602                    );
2603                });
2604            })
2605            .unwrap();
2606
2607        window
2608            .update(cx, |_, window, cx| {
2609                search_view.update(cx, |search_view, cx| {
2610                    search_view.query_editor.update(cx, |query_editor, cx| {
2611                        query_editor.set_text("sOMETHINGtHATsURELYdOESnOTeXIST", window, cx)
2612                    });
2613                    search_view.search(cx);
2614                });
2615            })
2616            .unwrap();
2617        cx.background_executor.run_until_parked();
2618        window
2619            .update(cx, |_, window, cx| {
2620                search_view.update(cx, |search_view, cx| {
2621                    let results_text = search_view
2622                        .results_editor
2623                        .update(cx, |editor, cx| editor.display_text(cx));
2624                    assert!(
2625                        results_text.is_empty(),
2626                        "Search view for mismatching query should have no results but got '{results_text}'"
2627                    );
2628                    assert!(
2629                        search_view.query_editor.focus_handle(cx).is_focused(window),
2630                        "Search view should be focused after mismatching query had been used in search",
2631                    );
2632                });
2633            }).unwrap();
2634
2635        cx.spawn(|mut cx| async move {
2636            window.update(&mut cx, |_, window, cx| {
2637                window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2638            })
2639        })
2640        .detach();
2641        cx.background_executor.run_until_parked();
2642        window.update(cx, |_, window, cx| {
2643            search_view.update(cx, |search_view, cx| {
2644                assert!(
2645                    search_view.query_editor.focus_handle(cx).is_focused(window),
2646                    "Search view with mismatching query should be focused after the toggle focus event: still no results panel to focus on",
2647                );
2648            });
2649        }).unwrap();
2650
2651        window
2652            .update(cx, |_, window, cx| {
2653                search_view.update(cx, |search_view, cx| {
2654                    search_view.query_editor.update(cx, |query_editor, cx| {
2655                        query_editor.set_text("TWO", window, cx)
2656                    });
2657                    search_view.search(cx);
2658                });
2659            })
2660            .unwrap();
2661        cx.background_executor.run_until_parked();
2662        window.update(cx, |_, window, cx| {
2663            search_view.update(cx, |search_view, cx| {
2664                assert_eq!(
2665                    search_view
2666                        .results_editor
2667                        .update(cx, |editor, cx| editor.display_text(cx)),
2668                    "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
2669                    "Search view results should match the query"
2670                );
2671                assert!(
2672                    search_view.results_editor.focus_handle(cx).is_focused(window),
2673                    "Search view with mismatching query should be focused after search results are available",
2674                );
2675            });
2676        }).unwrap();
2677        cx.spawn(|mut cx| async move {
2678            window
2679                .update(&mut cx, |_, window, cx| {
2680                    window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2681                })
2682                .unwrap();
2683        })
2684        .detach();
2685        cx.background_executor.run_until_parked();
2686        window.update(cx, |_, window, cx| {
2687            search_view.update(cx, |search_view, cx| {
2688                assert!(
2689                    search_view.results_editor.focus_handle(cx).is_focused(window),
2690                    "Search view with matching query should still have its results editor focused after the toggle focus event",
2691                );
2692            });
2693        }).unwrap();
2694
2695        workspace
2696            .update(cx, |workspace, window, cx| {
2697                ProjectSearchView::deploy_search(
2698                    workspace,
2699                    &workspace::DeploySearch::find(),
2700                    window,
2701                    cx,
2702                )
2703            })
2704            .unwrap();
2705        window.update(cx, |_, window, cx| {
2706            search_view.update(cx, |search_view, cx| {
2707                assert_eq!(search_view.query_editor.read(cx).text(cx), "two", "Query should be updated to first search result after search view 2nd open in a row");
2708                assert_eq!(
2709                    search_view
2710                        .results_editor
2711                        .update(cx, |editor, cx| editor.display_text(cx)),
2712                    "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
2713                    "Results should be unchanged after search view 2nd open in a row"
2714                );
2715                assert!(
2716                    search_view.query_editor.focus_handle(cx).is_focused(window),
2717                    "Focus should be moved into query editor again after search view 2nd open in a row"
2718                );
2719            });
2720        }).unwrap();
2721
2722        cx.spawn(|mut cx| async move {
2723            window
2724                .update(&mut cx, |_, window, cx| {
2725                    window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2726                })
2727                .unwrap();
2728        })
2729        .detach();
2730        cx.background_executor.run_until_parked();
2731        window.update(cx, |_, window, cx| {
2732            search_view.update(cx, |search_view, cx| {
2733                assert!(
2734                    search_view.results_editor.focus_handle(cx).is_focused(window),
2735                    "Search view with matching query should switch focus to the results editor after the toggle focus event",
2736                );
2737            });
2738        }).unwrap();
2739    }
2740
2741    #[perf]
2742    #[gpui::test]
2743    async fn test_filters_consider_toggle_state(cx: &mut TestAppContext) {
2744        init_test(cx);
2745
2746        let fs = FakeFs::new(cx.background_executor.clone());
2747        fs.insert_tree(
2748            "/dir",
2749            json!({
2750                "one.rs": "const ONE: usize = 1;",
2751                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2752                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2753                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2754            }),
2755        )
2756        .await;
2757        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
2758        let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
2759        let workspace = window;
2760        let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
2761
2762        window
2763            .update(cx, move |workspace, window, cx| {
2764                workspace.panes()[0].update(cx, |pane, cx| {
2765                    pane.toolbar()
2766                        .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
2767                });
2768
2769                ProjectSearchView::deploy_search(
2770                    workspace,
2771                    &workspace::DeploySearch::find(),
2772                    window,
2773                    cx,
2774                )
2775            })
2776            .unwrap();
2777
2778        let Some(search_view) = cx.read(|cx| {
2779            workspace
2780                .read(cx)
2781                .unwrap()
2782                .active_pane()
2783                .read(cx)
2784                .active_item()
2785                .and_then(|item| item.downcast::<ProjectSearchView>())
2786        }) else {
2787            panic!("Search view expected to appear after new search event trigger")
2788        };
2789
2790        cx.spawn(|mut cx| async move {
2791            window
2792                .update(&mut cx, |_, window, cx| {
2793                    window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2794                })
2795                .unwrap();
2796        })
2797        .detach();
2798        cx.background_executor.run_until_parked();
2799
2800        window
2801            .update(cx, |_, window, cx| {
2802                search_view.update(cx, |search_view, cx| {
2803                    search_view.query_editor.update(cx, |query_editor, cx| {
2804                        query_editor.set_text("const FOUR", window, cx)
2805                    });
2806                    search_view.toggle_filters(cx);
2807                    search_view
2808                        .excluded_files_editor
2809                        .update(cx, |exclude_editor, cx| {
2810                            exclude_editor.set_text("four.rs", window, cx)
2811                        });
2812                    search_view.search(cx);
2813                });
2814            })
2815            .unwrap();
2816        cx.background_executor.run_until_parked();
2817        window
2818            .update(cx, |_, _, cx| {
2819                search_view.update(cx, |search_view, cx| {
2820                    let results_text = search_view
2821                        .results_editor
2822                        .update(cx, |editor, cx| editor.display_text(cx));
2823                    assert!(
2824                        results_text.is_empty(),
2825                        "Search view for query with the only match in an excluded file should have no results but got '{results_text}'"
2826                    );
2827                });
2828            }).unwrap();
2829
2830        cx.spawn(|mut cx| async move {
2831            window.update(&mut cx, |_, window, cx| {
2832                window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2833            })
2834        })
2835        .detach();
2836        cx.background_executor.run_until_parked();
2837
2838        window
2839            .update(cx, |_, _, cx| {
2840                search_view.update(cx, |search_view, cx| {
2841                    search_view.toggle_filters(cx);
2842                    search_view.search(cx);
2843                });
2844            })
2845            .unwrap();
2846        cx.background_executor.run_until_parked();
2847        window
2848            .update(cx, |_, _, cx| {
2849                search_view.update(cx, |search_view, cx| {
2850                assert_eq!(
2851                    search_view
2852                        .results_editor
2853                        .update(cx, |editor, cx| editor.display_text(cx)),
2854                    "\n\nconst FOUR: usize = one::ONE + three::THREE;",
2855                    "Search view results should contain the queried result in the previously excluded file with filters toggled off"
2856                );
2857            });
2858            })
2859            .unwrap();
2860    }
2861
2862    #[perf]
2863    #[gpui::test]
2864    async fn test_new_project_search_focus(cx: &mut TestAppContext) {
2865        init_test(cx);
2866
2867        let fs = FakeFs::new(cx.background_executor.clone());
2868        fs.insert_tree(
2869            path!("/dir"),
2870            json!({
2871                "one.rs": "const ONE: usize = 1;",
2872                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2873                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2874                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2875            }),
2876        )
2877        .await;
2878        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
2879        let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
2880        let workspace = window;
2881        let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
2882
2883        let active_item = cx.read(|cx| {
2884            workspace
2885                .read(cx)
2886                .unwrap()
2887                .active_pane()
2888                .read(cx)
2889                .active_item()
2890                .and_then(|item| item.downcast::<ProjectSearchView>())
2891        });
2892        assert!(
2893            active_item.is_none(),
2894            "Expected no search panel to be active"
2895        );
2896
2897        window
2898            .update(cx, move |workspace, window, cx| {
2899                assert_eq!(workspace.panes().len(), 1);
2900                workspace.panes()[0].update(cx, |pane, cx| {
2901                    pane.toolbar()
2902                        .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
2903                });
2904
2905                ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
2906            })
2907            .unwrap();
2908
2909        let Some(search_view) = cx.read(|cx| {
2910            workspace
2911                .read(cx)
2912                .unwrap()
2913                .active_pane()
2914                .read(cx)
2915                .active_item()
2916                .and_then(|item| item.downcast::<ProjectSearchView>())
2917        }) else {
2918            panic!("Search view expected to appear after new search event trigger")
2919        };
2920
2921        cx.spawn(|mut cx| async move {
2922            window
2923                .update(&mut cx, |_, window, cx| {
2924                    window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2925                })
2926                .unwrap();
2927        })
2928        .detach();
2929        cx.background_executor.run_until_parked();
2930
2931        window.update(cx, |_, window, cx| {
2932            search_view.update(cx, |search_view, cx| {
2933                    assert!(
2934                        search_view.query_editor.focus_handle(cx).is_focused(window),
2935                        "Empty search view should be focused after the toggle focus event: no results panel to focus on",
2936                    );
2937                });
2938        }).unwrap();
2939
2940        window
2941            .update(cx, |_, window, cx| {
2942                search_view.update(cx, |search_view, cx| {
2943                    let query_editor = &search_view.query_editor;
2944                    assert!(
2945                        query_editor.focus_handle(cx).is_focused(window),
2946                        "Search view should be focused after the new search view is activated",
2947                    );
2948                    let query_text = query_editor.read(cx).text(cx);
2949                    assert!(
2950                        query_text.is_empty(),
2951                        "New search query should be empty but got '{query_text}'",
2952                    );
2953                    let results_text = search_view
2954                        .results_editor
2955                        .update(cx, |editor, cx| editor.display_text(cx));
2956                    assert!(
2957                        results_text.is_empty(),
2958                        "Empty search view should have no results but got '{results_text}'"
2959                    );
2960                });
2961            })
2962            .unwrap();
2963
2964        window
2965            .update(cx, |_, window, cx| {
2966                search_view.update(cx, |search_view, cx| {
2967                    search_view.query_editor.update(cx, |query_editor, cx| {
2968                        query_editor.set_text("sOMETHINGtHATsURELYdOESnOTeXIST", window, cx)
2969                    });
2970                    search_view.search(cx);
2971                });
2972            })
2973            .unwrap();
2974
2975        cx.background_executor.run_until_parked();
2976        window
2977            .update(cx, |_, window, cx| {
2978                search_view.update(cx, |search_view, cx| {
2979                    let results_text = search_view
2980                        .results_editor
2981                        .update(cx, |editor, cx| editor.display_text(cx));
2982                    assert!(
2983                results_text.is_empty(),
2984                "Search view for mismatching query should have no results but got '{results_text}'"
2985            );
2986                    assert!(
2987                search_view.query_editor.focus_handle(cx).is_focused(window),
2988                "Search view should be focused after mismatching query had been used in search",
2989            );
2990                });
2991            })
2992            .unwrap();
2993        cx.spawn(|mut cx| async move {
2994            window.update(&mut cx, |_, window, cx| {
2995                window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2996            })
2997        })
2998        .detach();
2999        cx.background_executor.run_until_parked();
3000        window.update(cx, |_, window, cx| {
3001            search_view.update(cx, |search_view, cx| {
3002                    assert!(
3003                        search_view.query_editor.focus_handle(cx).is_focused(window),
3004                        "Search view with mismatching query should be focused after the toggle focus event: still no results panel to focus on",
3005                    );
3006                });
3007        }).unwrap();
3008
3009        window
3010            .update(cx, |_, window, cx| {
3011                search_view.update(cx, |search_view, cx| {
3012                    search_view.query_editor.update(cx, |query_editor, cx| {
3013                        query_editor.set_text("TWO", window, cx)
3014                    });
3015                    search_view.search(cx);
3016                })
3017            })
3018            .unwrap();
3019        cx.background_executor.run_until_parked();
3020        window.update(cx, |_, window, cx|
3021        search_view.update(cx, |search_view, cx| {
3022                assert_eq!(
3023                    search_view
3024                        .results_editor
3025                        .update(cx, |editor, cx| editor.display_text(cx)),
3026                    "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
3027                    "Search view results should match the query"
3028                );
3029                assert!(
3030                    search_view.results_editor.focus_handle(cx).is_focused(window),
3031                    "Search view with mismatching query should be focused after search results are available",
3032                );
3033            })).unwrap();
3034        cx.spawn(|mut cx| async move {
3035            window
3036                .update(&mut cx, |_, window, cx| {
3037                    window.dispatch_action(ToggleFocus.boxed_clone(), cx)
3038                })
3039                .unwrap();
3040        })
3041        .detach();
3042        cx.background_executor.run_until_parked();
3043        window.update(cx, |_, window, cx| {
3044            search_view.update(cx, |search_view, cx| {
3045                    assert!(
3046                        search_view.results_editor.focus_handle(cx).is_focused(window),
3047                        "Search view with matching query should still have its results editor focused after the toggle focus event",
3048                    );
3049                });
3050        }).unwrap();
3051
3052        workspace
3053            .update(cx, |workspace, window, cx| {
3054                ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3055            })
3056            .unwrap();
3057        cx.background_executor.run_until_parked();
3058        let Some(search_view_2) = cx.read(|cx| {
3059            workspace
3060                .read(cx)
3061                .unwrap()
3062                .active_pane()
3063                .read(cx)
3064                .active_item()
3065                .and_then(|item| item.downcast::<ProjectSearchView>())
3066        }) else {
3067            panic!("Search view expected to appear after new search event trigger")
3068        };
3069        assert!(
3070            search_view_2 != search_view,
3071            "New search view should be open after `workspace::NewSearch` event"
3072        );
3073
3074        window.update(cx, |_, window, cx| {
3075            search_view.update(cx, |search_view, cx| {
3076                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO", "First search view should not have an updated query");
3077                    assert_eq!(
3078                        search_view
3079                            .results_editor
3080                            .update(cx, |editor, cx| editor.display_text(cx)),
3081                        "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
3082                        "Results of the first search view should not update too"
3083                    );
3084                    assert!(
3085                        !search_view.query_editor.focus_handle(cx).is_focused(window),
3086                        "Focus should be moved away from the first search view"
3087                    );
3088                });
3089        }).unwrap();
3090
3091        window.update(cx, |_, window, cx| {
3092            search_view_2.update(cx, |search_view_2, cx| {
3093                    assert_eq!(
3094                        search_view_2.query_editor.read(cx).text(cx),
3095                        "two",
3096                        "New search view should get the query from the text cursor was at during the event spawn (first search view's first result)"
3097                    );
3098                    assert_eq!(
3099                        search_view_2
3100                            .results_editor
3101                            .update(cx, |editor, cx| editor.display_text(cx)),
3102                        "",
3103                        "No search results should be in the 2nd view yet, as we did not spawn a search for it"
3104                    );
3105                    assert!(
3106                        search_view_2.query_editor.focus_handle(cx).is_focused(window),
3107                        "Focus should be moved into query editor of the new window"
3108                    );
3109                });
3110        }).unwrap();
3111
3112        window
3113            .update(cx, |_, window, cx| {
3114                search_view_2.update(cx, |search_view_2, cx| {
3115                    search_view_2.query_editor.update(cx, |query_editor, cx| {
3116                        query_editor.set_text("FOUR", window, cx)
3117                    });
3118                    search_view_2.search(cx);
3119                });
3120            })
3121            .unwrap();
3122
3123        cx.background_executor.run_until_parked();
3124        window.update(cx, |_, window, cx| {
3125            search_view_2.update(cx, |search_view_2, cx| {
3126                    assert_eq!(
3127                        search_view_2
3128                            .results_editor
3129                            .update(cx, |editor, cx| editor.display_text(cx)),
3130                        "\n\nconst FOUR: usize = one::ONE + three::THREE;",
3131                        "New search view with the updated query should have new search results"
3132                    );
3133                    assert!(
3134                        search_view_2.results_editor.focus_handle(cx).is_focused(window),
3135                        "Search view with mismatching query should be focused after search results are available",
3136                    );
3137                });
3138        }).unwrap();
3139
3140        cx.spawn(|mut cx| async move {
3141            window
3142                .update(&mut cx, |_, window, cx| {
3143                    window.dispatch_action(ToggleFocus.boxed_clone(), cx)
3144                })
3145                .unwrap();
3146        })
3147        .detach();
3148        cx.background_executor.run_until_parked();
3149        window.update(cx, |_, window, cx| {
3150            search_view_2.update(cx, |search_view_2, cx| {
3151                    assert!(
3152                        search_view_2.results_editor.focus_handle(cx).is_focused(window),
3153                        "Search view with matching query should switch focus to the results editor after the toggle focus event",
3154                    );
3155                });}).unwrap();
3156    }
3157
3158    #[perf]
3159    #[gpui::test]
3160    async fn test_new_project_search_in_directory(cx: &mut TestAppContext) {
3161        init_test(cx);
3162
3163        let fs = FakeFs::new(cx.background_executor.clone());
3164        fs.insert_tree(
3165            path!("/dir"),
3166            json!({
3167                "a": {
3168                    "one.rs": "const ONE: usize = 1;",
3169                    "two.rs": "const TWO: usize = one::ONE + one::ONE;",
3170                },
3171                "b": {
3172                    "three.rs": "const THREE: usize = one::ONE + two::TWO;",
3173                    "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
3174                },
3175            }),
3176        )
3177        .await;
3178        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
3179        let worktree_id = project.read_with(cx, |project, cx| {
3180            project.worktrees(cx).next().unwrap().read(cx).id()
3181        });
3182        let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
3183        let workspace = window.root(cx).unwrap();
3184        let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
3185
3186        let active_item = cx.read(|cx| {
3187            workspace
3188                .read(cx)
3189                .active_pane()
3190                .read(cx)
3191                .active_item()
3192                .and_then(|item| item.downcast::<ProjectSearchView>())
3193        });
3194        assert!(
3195            active_item.is_none(),
3196            "Expected no search panel to be active"
3197        );
3198
3199        window
3200            .update(cx, move |workspace, window, cx| {
3201                assert_eq!(workspace.panes().len(), 1);
3202                workspace.panes()[0].update(cx, move |pane, cx| {
3203                    pane.toolbar()
3204                        .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3205                });
3206            })
3207            .unwrap();
3208
3209        let a_dir_entry = cx.update(|cx| {
3210            workspace
3211                .read(cx)
3212                .project()
3213                .read(cx)
3214                .entry_for_path(&(worktree_id, rel_path("a")).into(), cx)
3215                .expect("no entry for /a/ directory")
3216                .clone()
3217        });
3218        assert!(a_dir_entry.is_dir());
3219        window
3220            .update(cx, |workspace, window, cx| {
3221                ProjectSearchView::new_search_in_directory(workspace, &a_dir_entry.path, window, cx)
3222            })
3223            .unwrap();
3224
3225        let Some(search_view) = cx.read(|cx| {
3226            workspace
3227                .read(cx)
3228                .active_pane()
3229                .read(cx)
3230                .active_item()
3231                .and_then(|item| item.downcast::<ProjectSearchView>())
3232        }) else {
3233            panic!("Search view expected to appear after new search in directory event trigger")
3234        };
3235        cx.background_executor.run_until_parked();
3236        window
3237            .update(cx, |_, window, cx| {
3238                search_view.update(cx, |search_view, cx| {
3239                    assert!(
3240                        search_view.query_editor.focus_handle(cx).is_focused(window),
3241                        "On new search in directory, focus should be moved into query editor"
3242                    );
3243                    search_view.excluded_files_editor.update(cx, |editor, cx| {
3244                        assert!(
3245                            editor.display_text(cx).is_empty(),
3246                            "New search in directory should not have any excluded files"
3247                        );
3248                    });
3249                    search_view.included_files_editor.update(cx, |editor, cx| {
3250                        assert_eq!(
3251                            editor.display_text(cx),
3252                            a_dir_entry.path.display(PathStyle::local()),
3253                            "New search in directory should have included dir entry path"
3254                        );
3255                    });
3256                });
3257            })
3258            .unwrap();
3259        window
3260            .update(cx, |_, window, cx| {
3261                search_view.update(cx, |search_view, cx| {
3262                    search_view.query_editor.update(cx, |query_editor, cx| {
3263                        query_editor.set_text("const", window, cx)
3264                    });
3265                    search_view.search(cx);
3266                });
3267            })
3268            .unwrap();
3269        cx.background_executor.run_until_parked();
3270        window
3271            .update(cx, |_, _, cx| {
3272                search_view.update(cx, |search_view, cx| {
3273                    assert_eq!(
3274                search_view
3275                    .results_editor
3276                    .update(cx, |editor, cx| editor.display_text(cx)),
3277                "\n\nconst ONE: usize = 1;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
3278                "New search in directory should have a filter that matches a certain directory"
3279            );
3280                })
3281            })
3282            .unwrap();
3283    }
3284
3285    #[perf]
3286    #[gpui::test]
3287    async fn test_search_query_history(cx: &mut TestAppContext) {
3288        init_test(cx);
3289
3290        let fs = FakeFs::new(cx.background_executor.clone());
3291        fs.insert_tree(
3292            path!("/dir"),
3293            json!({
3294                "one.rs": "const ONE: usize = 1;",
3295                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
3296                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
3297                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
3298            }),
3299        )
3300        .await;
3301        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
3302        let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
3303        let workspace = window.root(cx).unwrap();
3304        let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
3305
3306        window
3307            .update(cx, {
3308                let search_bar = search_bar.clone();
3309                |workspace, window, cx| {
3310                    assert_eq!(workspace.panes().len(), 1);
3311                    workspace.panes()[0].update(cx, |pane, cx| {
3312                        pane.toolbar()
3313                            .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3314                    });
3315
3316                    ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3317                }
3318            })
3319            .unwrap();
3320
3321        let search_view = cx.read(|cx| {
3322            workspace
3323                .read(cx)
3324                .active_pane()
3325                .read(cx)
3326                .active_item()
3327                .and_then(|item| item.downcast::<ProjectSearchView>())
3328                .expect("Search view expected to appear after new search event trigger")
3329        });
3330
3331        // Add 3 search items into the history + another unsubmitted one.
3332        window
3333            .update(cx, |_, window, cx| {
3334                search_view.update(cx, |search_view, cx| {
3335                    search_view.search_options = SearchOptions::CASE_SENSITIVE;
3336                    search_view.query_editor.update(cx, |query_editor, cx| {
3337                        query_editor.set_text("ONE", window, cx)
3338                    });
3339                    search_view.search(cx);
3340                });
3341            })
3342            .unwrap();
3343
3344        cx.background_executor.run_until_parked();
3345        window
3346            .update(cx, |_, window, cx| {
3347                search_view.update(cx, |search_view, cx| {
3348                    search_view.query_editor.update(cx, |query_editor, cx| {
3349                        query_editor.set_text("TWO", window, cx)
3350                    });
3351                    search_view.search(cx);
3352                });
3353            })
3354            .unwrap();
3355        cx.background_executor.run_until_parked();
3356        window
3357            .update(cx, |_, window, cx| {
3358                search_view.update(cx, |search_view, cx| {
3359                    search_view.query_editor.update(cx, |query_editor, cx| {
3360                        query_editor.set_text("THREE", window, cx)
3361                    });
3362                    search_view.search(cx);
3363                })
3364            })
3365            .unwrap();
3366        cx.background_executor.run_until_parked();
3367        window
3368            .update(cx, |_, window, cx| {
3369                search_view.update(cx, |search_view, cx| {
3370                    search_view.query_editor.update(cx, |query_editor, cx| {
3371                        query_editor.set_text("JUST_TEXT_INPUT", window, cx)
3372                    });
3373                })
3374            })
3375            .unwrap();
3376        cx.background_executor.run_until_parked();
3377
3378        // Ensure that the latest input with search settings is active.
3379        window
3380            .update(cx, |_, _, cx| {
3381                search_view.update(cx, |search_view, cx| {
3382                    assert_eq!(
3383                        search_view.query_editor.read(cx).text(cx),
3384                        "JUST_TEXT_INPUT"
3385                    );
3386                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3387                });
3388            })
3389            .unwrap();
3390
3391        // Next history query after the latest should set the query to the empty string.
3392        window
3393            .update(cx, |_, window, cx| {
3394                search_bar.update(cx, |search_bar, cx| {
3395                    search_bar.focus_search(window, cx);
3396                    search_bar.next_history_query(&NextHistoryQuery, window, cx);
3397                })
3398            })
3399            .unwrap();
3400        window
3401            .update(cx, |_, _, cx| {
3402                search_view.update(cx, |search_view, cx| {
3403                    assert_eq!(search_view.query_editor.read(cx).text(cx), "");
3404                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3405                });
3406            })
3407            .unwrap();
3408        window
3409            .update(cx, |_, window, cx| {
3410                search_bar.update(cx, |search_bar, cx| {
3411                    search_bar.focus_search(window, cx);
3412                    search_bar.next_history_query(&NextHistoryQuery, window, cx);
3413                })
3414            })
3415            .unwrap();
3416        window
3417            .update(cx, |_, _, cx| {
3418                search_view.update(cx, |search_view, cx| {
3419                    assert_eq!(search_view.query_editor.read(cx).text(cx), "");
3420                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3421                });
3422            })
3423            .unwrap();
3424
3425        // First previous query for empty current query should set the query to the latest submitted one.
3426        window
3427            .update(cx, |_, window, cx| {
3428                search_bar.update(cx, |search_bar, cx| {
3429                    search_bar.focus_search(window, cx);
3430                    search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3431                });
3432            })
3433            .unwrap();
3434        window
3435            .update(cx, |_, _, cx| {
3436                search_view.update(cx, |search_view, cx| {
3437                    assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
3438                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3439                });
3440            })
3441            .unwrap();
3442
3443        // Further previous items should go over the history in reverse order.
3444        window
3445            .update(cx, |_, window, cx| {
3446                search_bar.update(cx, |search_bar, cx| {
3447                    search_bar.focus_search(window, cx);
3448                    search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3449                });
3450            })
3451            .unwrap();
3452        window
3453            .update(cx, |_, _, cx| {
3454                search_view.update(cx, |search_view, cx| {
3455                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
3456                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3457                });
3458            })
3459            .unwrap();
3460
3461        // Previous items should never go behind the first history item.
3462        window
3463            .update(cx, |_, window, cx| {
3464                search_bar.update(cx, |search_bar, cx| {
3465                    search_bar.focus_search(window, cx);
3466                    search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3467                });
3468            })
3469            .unwrap();
3470        window
3471            .update(cx, |_, _, cx| {
3472                search_view.update(cx, |search_view, cx| {
3473                    assert_eq!(search_view.query_editor.read(cx).text(cx), "ONE");
3474                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3475                });
3476            })
3477            .unwrap();
3478        window
3479            .update(cx, |_, window, cx| {
3480                search_bar.update(cx, |search_bar, cx| {
3481                    search_bar.focus_search(window, cx);
3482                    search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3483                });
3484            })
3485            .unwrap();
3486        window
3487            .update(cx, |_, _, cx| {
3488                search_view.update(cx, |search_view, cx| {
3489                    assert_eq!(search_view.query_editor.read(cx).text(cx), "ONE");
3490                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3491                });
3492            })
3493            .unwrap();
3494
3495        // Next items should go over the history in the original order.
3496        window
3497            .update(cx, |_, window, cx| {
3498                search_bar.update(cx, |search_bar, cx| {
3499                    search_bar.focus_search(window, cx);
3500                    search_bar.next_history_query(&NextHistoryQuery, window, cx);
3501                });
3502            })
3503            .unwrap();
3504        window
3505            .update(cx, |_, _, cx| {
3506                search_view.update(cx, |search_view, cx| {
3507                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
3508                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3509                });
3510            })
3511            .unwrap();
3512
3513        window
3514            .update(cx, |_, window, cx| {
3515                search_view.update(cx, |search_view, cx| {
3516                    search_view.query_editor.update(cx, |query_editor, cx| {
3517                        query_editor.set_text("TWO_NEW", window, cx)
3518                    });
3519                    search_view.search(cx);
3520                });
3521            })
3522            .unwrap();
3523        cx.background_executor.run_until_parked();
3524        window
3525            .update(cx, |_, _, cx| {
3526                search_view.update(cx, |search_view, cx| {
3527                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO_NEW");
3528                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3529                });
3530            })
3531            .unwrap();
3532
3533        // New search input should add another entry to history and move the selection to the end of the history.
3534        window
3535            .update(cx, |_, window, cx| {
3536                search_bar.update(cx, |search_bar, cx| {
3537                    search_bar.focus_search(window, cx);
3538                    search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3539                });
3540            })
3541            .unwrap();
3542        window
3543            .update(cx, |_, _, cx| {
3544                search_view.update(cx, |search_view, cx| {
3545                    assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
3546                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3547                });
3548            })
3549            .unwrap();
3550        window
3551            .update(cx, |_, window, cx| {
3552                search_bar.update(cx, |search_bar, cx| {
3553                    search_bar.focus_search(window, cx);
3554                    search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3555                });
3556            })
3557            .unwrap();
3558        window
3559            .update(cx, |_, _, cx| {
3560                search_view.update(cx, |search_view, cx| {
3561                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
3562                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3563                });
3564            })
3565            .unwrap();
3566        window
3567            .update(cx, |_, window, cx| {
3568                search_bar.update(cx, |search_bar, cx| {
3569                    search_bar.focus_search(window, cx);
3570                    search_bar.next_history_query(&NextHistoryQuery, window, cx);
3571                });
3572            })
3573            .unwrap();
3574        window
3575            .update(cx, |_, _, cx| {
3576                search_view.update(cx, |search_view, cx| {
3577                    assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
3578                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3579                });
3580            })
3581            .unwrap();
3582        window
3583            .update(cx, |_, window, cx| {
3584                search_bar.update(cx, |search_bar, cx| {
3585                    search_bar.focus_search(window, cx);
3586                    search_bar.next_history_query(&NextHistoryQuery, window, cx);
3587                });
3588            })
3589            .unwrap();
3590        window
3591            .update(cx, |_, _, cx| {
3592                search_view.update(cx, |search_view, cx| {
3593                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO_NEW");
3594                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3595                });
3596            })
3597            .unwrap();
3598        window
3599            .update(cx, |_, window, cx| {
3600                search_bar.update(cx, |search_bar, cx| {
3601                    search_bar.focus_search(window, cx);
3602                    search_bar.next_history_query(&NextHistoryQuery, window, cx);
3603                });
3604            })
3605            .unwrap();
3606        window
3607            .update(cx, |_, _, cx| {
3608                search_view.update(cx, |search_view, cx| {
3609                    assert_eq!(search_view.query_editor.read(cx).text(cx), "");
3610                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3611                });
3612            })
3613            .unwrap();
3614    }
3615
3616    #[perf]
3617    #[gpui::test]
3618    async fn test_search_query_history_with_multiple_views(cx: &mut TestAppContext) {
3619        init_test(cx);
3620
3621        let fs = FakeFs::new(cx.background_executor.clone());
3622        fs.insert_tree(
3623            path!("/dir"),
3624            json!({
3625                "one.rs": "const ONE: usize = 1;",
3626            }),
3627        )
3628        .await;
3629        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
3630        let worktree_id = project.update(cx, |this, cx| {
3631            this.worktrees(cx).next().unwrap().read(cx).id()
3632        });
3633
3634        let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
3635        let workspace = window.root(cx).unwrap();
3636
3637        let panes: Vec<_> = window
3638            .update(cx, |this, _, _| this.panes().to_owned())
3639            .unwrap();
3640
3641        let search_bar_1 = window.build_entity(cx, |_, _| ProjectSearchBar::new());
3642        let search_bar_2 = window.build_entity(cx, |_, _| ProjectSearchBar::new());
3643
3644        assert_eq!(panes.len(), 1);
3645        let first_pane = panes.first().cloned().unwrap();
3646        assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 0);
3647        window
3648            .update(cx, |workspace, window, cx| {
3649                workspace.open_path(
3650                    (worktree_id, rel_path("one.rs")),
3651                    Some(first_pane.downgrade()),
3652                    true,
3653                    window,
3654                    cx,
3655                )
3656            })
3657            .unwrap()
3658            .await
3659            .unwrap();
3660        assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 1);
3661
3662        // Add a project search item to the first pane
3663        window
3664            .update(cx, {
3665                let search_bar = search_bar_1.clone();
3666                |workspace, window, cx| {
3667                    first_pane.update(cx, |pane, cx| {
3668                        pane.toolbar()
3669                            .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3670                    });
3671
3672                    ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3673                }
3674            })
3675            .unwrap();
3676        let search_view_1 = cx.read(|cx| {
3677            workspace
3678                .read(cx)
3679                .active_item(cx)
3680                .and_then(|item| item.downcast::<ProjectSearchView>())
3681                .expect("Search view expected to appear after new search event trigger")
3682        });
3683
3684        let second_pane = window
3685            .update(cx, |workspace, window, cx| {
3686                workspace.split_and_clone(
3687                    first_pane.clone(),
3688                    workspace::SplitDirection::Right,
3689                    window,
3690                    cx,
3691                )
3692            })
3693            .unwrap()
3694            .await
3695            .unwrap();
3696        assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 1);
3697
3698        assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 1);
3699        assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 2);
3700
3701        // Add a project search item to the second pane
3702        window
3703            .update(cx, {
3704                let search_bar = search_bar_2.clone();
3705                let pane = second_pane.clone();
3706                move |workspace, window, cx| {
3707                    assert_eq!(workspace.panes().len(), 2);
3708                    pane.update(cx, |pane, cx| {
3709                        pane.toolbar()
3710                            .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3711                    });
3712
3713                    ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3714                }
3715            })
3716            .unwrap();
3717
3718        let search_view_2 = cx.read(|cx| {
3719            workspace
3720                .read(cx)
3721                .active_item(cx)
3722                .and_then(|item| item.downcast::<ProjectSearchView>())
3723                .expect("Search view expected to appear after new search event trigger")
3724        });
3725
3726        cx.run_until_parked();
3727        assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 2);
3728        assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 2);
3729
3730        let update_search_view =
3731            |search_view: &Entity<ProjectSearchView>, query: &str, cx: &mut TestAppContext| {
3732                window
3733                    .update(cx, |_, window, cx| {
3734                        search_view.update(cx, |search_view, cx| {
3735                            search_view.query_editor.update(cx, |query_editor, cx| {
3736                                query_editor.set_text(query, window, cx)
3737                            });
3738                            search_view.search(cx);
3739                        });
3740                    })
3741                    .unwrap();
3742            };
3743
3744        let active_query =
3745            |search_view: &Entity<ProjectSearchView>, cx: &mut TestAppContext| -> String {
3746                window
3747                    .update(cx, |_, _, cx| {
3748                        search_view.update(cx, |search_view, cx| {
3749                            search_view.query_editor.read(cx).text(cx)
3750                        })
3751                    })
3752                    .unwrap()
3753            };
3754
3755        let select_prev_history_item =
3756            |search_bar: &Entity<ProjectSearchBar>, cx: &mut TestAppContext| {
3757                window
3758                    .update(cx, |_, window, cx| {
3759                        search_bar.update(cx, |search_bar, cx| {
3760                            search_bar.focus_search(window, cx);
3761                            search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3762                        })
3763                    })
3764                    .unwrap();
3765            };
3766
3767        let select_next_history_item =
3768            |search_bar: &Entity<ProjectSearchBar>, cx: &mut TestAppContext| {
3769                window
3770                    .update(cx, |_, window, cx| {
3771                        search_bar.update(cx, |search_bar, cx| {
3772                            search_bar.focus_search(window, cx);
3773                            search_bar.next_history_query(&NextHistoryQuery, window, cx);
3774                        })
3775                    })
3776                    .unwrap();
3777            };
3778
3779        update_search_view(&search_view_1, "ONE", cx);
3780        cx.background_executor.run_until_parked();
3781
3782        update_search_view(&search_view_2, "TWO", cx);
3783        cx.background_executor.run_until_parked();
3784
3785        assert_eq!(active_query(&search_view_1, cx), "ONE");
3786        assert_eq!(active_query(&search_view_2, cx), "TWO");
3787
3788        // Selecting previous history item should select the query from search view 1.
3789        select_prev_history_item(&search_bar_2, cx);
3790        assert_eq!(active_query(&search_view_2, cx), "ONE");
3791
3792        // Selecting the previous history item should not change the query as it is already the first item.
3793        select_prev_history_item(&search_bar_2, cx);
3794        assert_eq!(active_query(&search_view_2, cx), "ONE");
3795
3796        // Changing the query in search view 2 should not affect the history of search view 1.
3797        assert_eq!(active_query(&search_view_1, cx), "ONE");
3798
3799        // Deploying a new search in search view 2
3800        update_search_view(&search_view_2, "THREE", cx);
3801        cx.background_executor.run_until_parked();
3802
3803        select_next_history_item(&search_bar_2, cx);
3804        assert_eq!(active_query(&search_view_2, cx), "");
3805
3806        select_prev_history_item(&search_bar_2, cx);
3807        assert_eq!(active_query(&search_view_2, cx), "THREE");
3808
3809        select_prev_history_item(&search_bar_2, cx);
3810        assert_eq!(active_query(&search_view_2, cx), "TWO");
3811
3812        select_prev_history_item(&search_bar_2, cx);
3813        assert_eq!(active_query(&search_view_2, cx), "ONE");
3814
3815        select_prev_history_item(&search_bar_2, cx);
3816        assert_eq!(active_query(&search_view_2, cx), "ONE");
3817
3818        // Search view 1 should now see the query from search view 2.
3819        assert_eq!(active_query(&search_view_1, cx), "ONE");
3820
3821        select_next_history_item(&search_bar_2, cx);
3822        assert_eq!(active_query(&search_view_2, cx), "TWO");
3823
3824        // Here is the new query from search view 2
3825        select_next_history_item(&search_bar_2, cx);
3826        assert_eq!(active_query(&search_view_2, cx), "THREE");
3827
3828        select_next_history_item(&search_bar_2, cx);
3829        assert_eq!(active_query(&search_view_2, cx), "");
3830
3831        select_next_history_item(&search_bar_1, cx);
3832        assert_eq!(active_query(&search_view_1, cx), "TWO");
3833
3834        select_next_history_item(&search_bar_1, cx);
3835        assert_eq!(active_query(&search_view_1, cx), "THREE");
3836
3837        select_next_history_item(&search_bar_1, cx);
3838        assert_eq!(active_query(&search_view_1, cx), "");
3839    }
3840
3841    #[perf]
3842    #[gpui::test]
3843    async fn test_deploy_search_with_multiple_panes(cx: &mut TestAppContext) {
3844        init_test(cx);
3845
3846        // Setup 2 panes, both with a file open and one with a project search.
3847        let fs = FakeFs::new(cx.background_executor.clone());
3848        fs.insert_tree(
3849            path!("/dir"),
3850            json!({
3851                "one.rs": "const ONE: usize = 1;",
3852            }),
3853        )
3854        .await;
3855        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
3856        let worktree_id = project.update(cx, |this, cx| {
3857            this.worktrees(cx).next().unwrap().read(cx).id()
3858        });
3859        let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
3860        let panes: Vec<_> = window
3861            .update(cx, |this, _, _| this.panes().to_owned())
3862            .unwrap();
3863        assert_eq!(panes.len(), 1);
3864        let first_pane = panes.first().cloned().unwrap();
3865        assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 0);
3866        window
3867            .update(cx, |workspace, window, cx| {
3868                workspace.open_path(
3869                    (worktree_id, rel_path("one.rs")),
3870                    Some(first_pane.downgrade()),
3871                    true,
3872                    window,
3873                    cx,
3874                )
3875            })
3876            .unwrap()
3877            .await
3878            .unwrap();
3879        assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 1);
3880        let second_pane = window
3881            .update(cx, |workspace, window, cx| {
3882                workspace.split_and_clone(
3883                    first_pane.clone(),
3884                    workspace::SplitDirection::Right,
3885                    window,
3886                    cx,
3887                )
3888            })
3889            .unwrap()
3890            .await
3891            .unwrap();
3892        assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 1);
3893        assert!(
3894            window
3895                .update(cx, |_, window, cx| second_pane
3896                    .focus_handle(cx)
3897                    .contains_focused(window, cx))
3898                .unwrap()
3899        );
3900        let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
3901        window
3902            .update(cx, {
3903                let search_bar = search_bar.clone();
3904                let pane = first_pane.clone();
3905                move |workspace, window, cx| {
3906                    assert_eq!(workspace.panes().len(), 2);
3907                    pane.update(cx, move |pane, cx| {
3908                        pane.toolbar()
3909                            .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3910                    });
3911                }
3912            })
3913            .unwrap();
3914
3915        // Add a project search item to the second pane
3916        window
3917            .update(cx, {
3918                |workspace, window, cx| {
3919                    assert_eq!(workspace.panes().len(), 2);
3920                    second_pane.update(cx, |pane, cx| {
3921                        pane.toolbar()
3922                            .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3923                    });
3924
3925                    ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3926                }
3927            })
3928            .unwrap();
3929
3930        cx.run_until_parked();
3931        assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 2);
3932        assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 1);
3933
3934        // Focus the first pane
3935        window
3936            .update(cx, |workspace, window, cx| {
3937                assert_eq!(workspace.active_pane(), &second_pane);
3938                second_pane.update(cx, |this, cx| {
3939                    assert_eq!(this.active_item_index(), 1);
3940                    this.activate_previous_item(&Default::default(), window, cx);
3941                    assert_eq!(this.active_item_index(), 0);
3942                });
3943                workspace.activate_pane_in_direction(workspace::SplitDirection::Left, window, cx);
3944            })
3945            .unwrap();
3946        window
3947            .update(cx, |workspace, _, cx| {
3948                assert_eq!(workspace.active_pane(), &first_pane);
3949                assert_eq!(first_pane.read(cx).items_len(), 1);
3950                assert_eq!(second_pane.read(cx).items_len(), 2);
3951            })
3952            .unwrap();
3953
3954        // Deploy a new search
3955        cx.dispatch_action(window.into(), DeploySearch::find());
3956
3957        // Both panes should now have a project search in them
3958        window
3959            .update(cx, |workspace, window, cx| {
3960                assert_eq!(workspace.active_pane(), &first_pane);
3961                first_pane.read_with(cx, |this, _| {
3962                    assert_eq!(this.active_item_index(), 1);
3963                    assert_eq!(this.items_len(), 2);
3964                });
3965                second_pane.update(cx, |this, cx| {
3966                    assert!(!cx.focus_handle().contains_focused(window, cx));
3967                    assert_eq!(this.items_len(), 2);
3968                });
3969            })
3970            .unwrap();
3971
3972        // Focus the second pane's non-search item
3973        window
3974            .update(cx, |_workspace, window, cx| {
3975                second_pane.update(cx, |pane, cx| {
3976                    pane.activate_next_item(&Default::default(), window, cx)
3977                });
3978            })
3979            .unwrap();
3980
3981        // Deploy a new search
3982        cx.dispatch_action(window.into(), DeploySearch::find());
3983
3984        // The project search view should now be focused in the second pane
3985        // And the number of items should be unchanged.
3986        window
3987            .update(cx, |_workspace, _, cx| {
3988                second_pane.update(cx, |pane, _cx| {
3989                    assert!(
3990                        pane.active_item()
3991                            .unwrap()
3992                            .downcast::<ProjectSearchView>()
3993                            .is_some()
3994                    );
3995
3996                    assert_eq!(pane.items_len(), 2);
3997                });
3998            })
3999            .unwrap();
4000    }
4001
4002    #[perf]
4003    #[gpui::test]
4004    async fn test_scroll_search_results_to_top(cx: &mut TestAppContext) {
4005        init_test(cx);
4006
4007        // We need many lines in the search results to be able to scroll the window
4008        let fs = FakeFs::new(cx.background_executor.clone());
4009        fs.insert_tree(
4010            path!("/dir"),
4011            json!({
4012                "1.txt": "\n\n\n\n\n A \n\n\n\n\n",
4013                "2.txt": "\n\n\n\n\n A \n\n\n\n\n",
4014                "3.rs": "\n\n\n\n\n A \n\n\n\n\n",
4015                "4.rs": "\n\n\n\n\n A \n\n\n\n\n",
4016                "5.rs": "\n\n\n\n\n A \n\n\n\n\n",
4017                "6.rs": "\n\n\n\n\n A \n\n\n\n\n",
4018                "7.rs": "\n\n\n\n\n A \n\n\n\n\n",
4019                "8.rs": "\n\n\n\n\n A \n\n\n\n\n",
4020                "9.rs": "\n\n\n\n\n A \n\n\n\n\n",
4021                "a.rs": "\n\n\n\n\n A \n\n\n\n\n",
4022                "b.rs": "\n\n\n\n\n B \n\n\n\n\n",
4023                "c.rs": "\n\n\n\n\n B \n\n\n\n\n",
4024                "d.rs": "\n\n\n\n\n B \n\n\n\n\n",
4025                "e.rs": "\n\n\n\n\n B \n\n\n\n\n",
4026                "f.rs": "\n\n\n\n\n B \n\n\n\n\n",
4027                "g.rs": "\n\n\n\n\n B \n\n\n\n\n",
4028                "h.rs": "\n\n\n\n\n B \n\n\n\n\n",
4029                "i.rs": "\n\n\n\n\n B \n\n\n\n\n",
4030                "j.rs": "\n\n\n\n\n B \n\n\n\n\n",
4031                "k.rs": "\n\n\n\n\n B \n\n\n\n\n",
4032            }),
4033        )
4034        .await;
4035        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
4036        let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
4037        let workspace = window.root(cx).unwrap();
4038        let search = cx.new(|cx| ProjectSearch::new(project, cx));
4039        let search_view = cx.add_window(|window, cx| {
4040            ProjectSearchView::new(workspace.downgrade(), search.clone(), window, cx, None)
4041        });
4042
4043        // First search
4044        perform_search(search_view, "A", cx);
4045        search_view
4046            .update(cx, |search_view, window, cx| {
4047                search_view.results_editor.update(cx, |results_editor, cx| {
4048                    // Results are correct and scrolled to the top
4049                    assert_eq!(
4050                        results_editor.display_text(cx).match_indices(" A ").count(),
4051                        10
4052                    );
4053                    assert_eq!(results_editor.scroll_position(cx), Point::default());
4054
4055                    // Scroll results all the way down
4056                    results_editor.scroll(
4057                        Point::new(0., f64::MAX),
4058                        Some(Axis::Vertical),
4059                        window,
4060                        cx,
4061                    );
4062                });
4063            })
4064            .expect("unable to update search view");
4065
4066        // Second search
4067        perform_search(search_view, "B", cx);
4068        search_view
4069            .update(cx, |search_view, _, cx| {
4070                search_view.results_editor.update(cx, |results_editor, cx| {
4071                    // Results are correct...
4072                    assert_eq!(
4073                        results_editor.display_text(cx).match_indices(" B ").count(),
4074                        10
4075                    );
4076                    // ...and scrolled back to the top
4077                    assert_eq!(results_editor.scroll_position(cx), Point::default());
4078                });
4079            })
4080            .expect("unable to update search view");
4081    }
4082
4083    #[perf]
4084    #[gpui::test]
4085    async fn test_buffer_search_query_reused(cx: &mut TestAppContext) {
4086        init_test(cx);
4087
4088        let fs = FakeFs::new(cx.background_executor.clone());
4089        fs.insert_tree(
4090            path!("/dir"),
4091            json!({
4092                "one.rs": "const ONE: usize = 1;",
4093            }),
4094        )
4095        .await;
4096        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
4097        let worktree_id = project.update(cx, |this, cx| {
4098            this.worktrees(cx).next().unwrap().read(cx).id()
4099        });
4100        let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
4101        let workspace = window.root(cx).unwrap();
4102        let mut cx = VisualTestContext::from_window(*window.deref(), cx);
4103
4104        let editor = workspace
4105            .update_in(&mut cx, |workspace, window, cx| {
4106                workspace.open_path((worktree_id, rel_path("one.rs")), None, true, window, cx)
4107            })
4108            .await
4109            .unwrap()
4110            .downcast::<Editor>()
4111            .unwrap();
4112
4113        // Wait for the unstaged changes to be loaded
4114        cx.run_until_parked();
4115
4116        let buffer_search_bar = cx.new_window_entity(|window, cx| {
4117            let mut search_bar =
4118                BufferSearchBar::new(Some(project.read(cx).languages().clone()), window, cx);
4119            search_bar.set_active_pane_item(Some(&editor), window, cx);
4120            search_bar.show(window, cx);
4121            search_bar
4122        });
4123
4124        let panes: Vec<_> = window
4125            .update(&mut cx, |this, _, _| this.panes().to_owned())
4126            .unwrap();
4127        assert_eq!(panes.len(), 1);
4128        let pane = panes.first().cloned().unwrap();
4129        pane.update_in(&mut cx, |pane, window, cx| {
4130            pane.toolbar().update(cx, |toolbar, cx| {
4131                toolbar.add_item(buffer_search_bar.clone(), window, cx);
4132            })
4133        });
4134
4135        let buffer_search_query = "search bar query";
4136        buffer_search_bar
4137            .update_in(&mut cx, |buffer_search_bar, window, cx| {
4138                buffer_search_bar.focus_handle(cx).focus(window);
4139                buffer_search_bar.search(buffer_search_query, None, true, window, cx)
4140            })
4141            .await
4142            .unwrap();
4143
4144        workspace.update_in(&mut cx, |workspace, window, cx| {
4145            ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
4146        });
4147        cx.run_until_parked();
4148        let project_search_view = pane
4149            .read_with(&cx, |pane, _| {
4150                pane.active_item()
4151                    .and_then(|item| item.downcast::<ProjectSearchView>())
4152            })
4153            .expect("should open a project search view after spawning a new search");
4154        project_search_view.update(&mut cx, |search_view, cx| {
4155            assert_eq!(
4156                search_view.search_query_text(cx),
4157                buffer_search_query,
4158                "Project search should take the query from the buffer search bar since it got focused and had a query inside"
4159            );
4160        });
4161    }
4162
4163    #[gpui::test]
4164    async fn test_search_dismisses_modal(cx: &mut TestAppContext) {
4165        init_test(cx);
4166
4167        let fs = FakeFs::new(cx.background_executor.clone());
4168        fs.insert_tree(
4169            path!("/dir"),
4170            json!({
4171                "one.rs": "const ONE: usize = 1;",
4172            }),
4173        )
4174        .await;
4175        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
4176        let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
4177
4178        struct EmptyModalView {
4179            focus_handle: gpui::FocusHandle,
4180        }
4181        impl EventEmitter<gpui::DismissEvent> for EmptyModalView {}
4182        impl Render for EmptyModalView {
4183            fn render(&mut self, _: &mut Window, _: &mut Context<'_, Self>) -> impl IntoElement {
4184                div()
4185            }
4186        }
4187        impl Focusable for EmptyModalView {
4188            fn focus_handle(&self, _cx: &App) -> gpui::FocusHandle {
4189                self.focus_handle.clone()
4190            }
4191        }
4192        impl workspace::ModalView for EmptyModalView {}
4193
4194        window
4195            .update(cx, |workspace, window, cx| {
4196                workspace.toggle_modal(window, cx, |_, cx| EmptyModalView {
4197                    focus_handle: cx.focus_handle(),
4198                });
4199                assert!(workspace.has_active_modal(window, cx));
4200            })
4201            .unwrap();
4202
4203        cx.dispatch_action(window.into(), Deploy::find());
4204
4205        window
4206            .update(cx, |workspace, window, cx| {
4207                assert!(!workspace.has_active_modal(window, cx));
4208                workspace.toggle_modal(window, cx, |_, cx| EmptyModalView {
4209                    focus_handle: cx.focus_handle(),
4210                });
4211                assert!(workspace.has_active_modal(window, cx));
4212            })
4213            .unwrap();
4214
4215        cx.dispatch_action(window.into(), DeploySearch::find());
4216
4217        window
4218            .update(cx, |workspace, window, cx| {
4219                assert!(!workspace.has_active_modal(window, cx));
4220            })
4221            .unwrap();
4222    }
4223
4224    #[perf]
4225    #[gpui::test]
4226    async fn test_search_with_inlays(cx: &mut TestAppContext) {
4227        init_test(cx);
4228        cx.update(|cx| {
4229            SettingsStore::update_global(cx, |store, cx| {
4230                store.update_user_settings(cx, |settings| {
4231                    settings.project.all_languages.defaults.inlay_hints =
4232                        Some(InlayHintSettingsContent {
4233                            enabled: Some(true),
4234                            ..InlayHintSettingsContent::default()
4235                        })
4236                });
4237            });
4238        });
4239
4240        let fs = FakeFs::new(cx.background_executor.clone());
4241        fs.insert_tree(
4242            path!("/dir"),
4243            // `\n` , a trailing line on the end, is important for the test case
4244            json!({
4245                "main.rs": "fn main() { let a = 2; }\n",
4246            }),
4247        )
4248        .await;
4249
4250        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
4251        let language_registry = project.read_with(cx, |project, _| project.languages().clone());
4252        let language = rust_lang();
4253        language_registry.add(language);
4254        let mut fake_servers = language_registry.register_fake_lsp(
4255            "Rust",
4256            FakeLspAdapter {
4257                capabilities: lsp::ServerCapabilities {
4258                    inlay_hint_provider: Some(lsp::OneOf::Left(true)),
4259                    ..lsp::ServerCapabilities::default()
4260                },
4261                initializer: Some(Box::new(|fake_server| {
4262                    fake_server.set_request_handler::<lsp::request::InlayHintRequest, _, _>(
4263                        move |_, _| async move {
4264                            Ok(Some(vec![lsp::InlayHint {
4265                                position: lsp::Position::new(0, 17),
4266                                label: lsp::InlayHintLabel::String(": i32".to_owned()),
4267                                kind: Some(lsp::InlayHintKind::TYPE),
4268                                text_edits: None,
4269                                tooltip: None,
4270                                padding_left: None,
4271                                padding_right: None,
4272                                data: None,
4273                            }]))
4274                        },
4275                    );
4276                })),
4277                ..FakeLspAdapter::default()
4278            },
4279        );
4280
4281        let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
4282        let workspace = window.root(cx).unwrap();
4283        let search = cx.new(|cx| ProjectSearch::new(project.clone(), cx));
4284        let search_view = cx.add_window(|window, cx| {
4285            ProjectSearchView::new(workspace.downgrade(), search.clone(), window, cx, None)
4286        });
4287
4288        perform_search(search_view, "let ", cx);
4289        let _fake_server = fake_servers.next().await.unwrap();
4290        cx.executor().advance_clock(Duration::from_secs(1));
4291        cx.executor().run_until_parked();
4292        search_view
4293            .update(cx, |search_view, _, cx| {
4294                assert_eq!(
4295                    search_view
4296                        .results_editor
4297                        .update(cx, |editor, cx| editor.display_text(cx)),
4298                    "\n\nfn main() { let a: i32 = 2; }\n"
4299                );
4300            })
4301            .unwrap();
4302
4303        // Can do the 2nd search without any panics
4304        perform_search(search_view, "let ", cx);
4305        cx.executor().advance_clock(Duration::from_millis(100));
4306        cx.executor().run_until_parked();
4307        search_view
4308            .update(cx, |search_view, _, cx| {
4309                assert_eq!(
4310                    search_view
4311                        .results_editor
4312                        .update(cx, |editor, cx| editor.display_text(cx)),
4313                    "\n\nfn main() { let a: i32 = 2; }\n"
4314                );
4315            })
4316            .unwrap();
4317    }
4318
4319    fn init_test(cx: &mut TestAppContext) {
4320        cx.update(|cx| {
4321            let settings = SettingsStore::test(cx);
4322            cx.set_global(settings);
4323
4324            theme::init(theme::LoadThemes::JustBase, cx);
4325
4326            language::init(cx);
4327            client::init_settings(cx);
4328            editor::init(cx);
4329            workspace::init_settings(cx);
4330            Project::init_settings(cx);
4331            crate::init(cx);
4332        });
4333    }
4334
4335    fn perform_search(
4336        search_view: WindowHandle<ProjectSearchView>,
4337        text: impl Into<Arc<str>>,
4338        cx: &mut TestAppContext,
4339    ) {
4340        search_view
4341            .update(cx, |search_view, window, cx| {
4342                search_view.query_editor.update(cx, |query_editor, cx| {
4343                    query_editor.set_text(text, window, cx)
4344                });
4345                search_view.search(cx);
4346            })
4347            .unwrap();
4348        // Ensure editor highlights appear after the search is done
4349        cx.executor().advance_clock(
4350            editor::SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT + Duration::from_millis(100),
4351        );
4352        cx.background_executor.run_until_parked();
4353    }
4354}