project_search.rs

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