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