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            self.results_editor.update(cx, |editor, cx| {
1388                editor.clear_background_highlights::<Self>(cx);
1389            });
1390        } else {
1391            self.active_match_index = Some(0);
1392            self.update_match_index(cx);
1393            let prev_search_id = mem::replace(&mut self.search_id, self.entity.read(cx).search_id);
1394            let is_new_search = self.search_id != prev_search_id;
1395            self.results_editor.update(cx, |editor, cx| {
1396                if is_new_search {
1397                    let range_to_select = match_ranges
1398                        .first()
1399                        .map(|range| editor.range_for_match(range));
1400                    editor.change_selections(Default::default(), window, cx, |s| {
1401                        s.select_ranges(range_to_select)
1402                    });
1403                    editor.scroll(Point::default(), Some(Axis::Vertical), window, cx);
1404                }
1405                editor.highlight_background::<Self>(
1406                    &match_ranges,
1407                    |theme| theme.colors().search_match_background,
1408                    cx,
1409                );
1410            });
1411            if is_new_search && self.query_editor.focus_handle(cx).is_focused(window) {
1412                self.focus_results_editor(window, cx);
1413            }
1414        }
1415
1416        cx.emit(ViewEvent::UpdateTab);
1417        cx.notify();
1418    }
1419
1420    fn update_match_index(&mut self, cx: &mut Context<Self>) {
1421        let results_editor = self.results_editor.read(cx);
1422        let new_index = active_match_index(
1423            Direction::Next,
1424            &self.entity.read(cx).match_ranges,
1425            &results_editor.selections.newest_anchor().head(),
1426            &results_editor.buffer().read(cx).snapshot(cx),
1427        );
1428        if self.active_match_index != new_index {
1429            self.active_match_index = new_index;
1430            cx.notify();
1431        }
1432    }
1433
1434    pub fn has_matches(&self) -> bool {
1435        self.active_match_index.is_some()
1436    }
1437
1438    fn landing_text_minor(&self, window: &mut Window, cx: &App) -> impl IntoElement {
1439        let focus_handle = self.focus_handle.clone();
1440        v_flex()
1441            .gap_1()
1442            .child(
1443                Label::new("Hit enter to search. For more options:")
1444                    .color(Color::Muted)
1445                    .mb_2(),
1446            )
1447            .child(
1448                Button::new("filter-paths", "Include/exclude specific paths")
1449                    .icon(IconName::Filter)
1450                    .icon_position(IconPosition::Start)
1451                    .icon_size(IconSize::Small)
1452                    .key_binding(KeyBinding::for_action_in(
1453                        &ToggleFilters,
1454                        &focus_handle,
1455                        window,
1456                        cx,
1457                    ))
1458                    .on_click(|_event, window, cx| {
1459                        window.dispatch_action(ToggleFilters.boxed_clone(), cx)
1460                    }),
1461            )
1462            .child(
1463                Button::new("find-replace", "Find and replace")
1464                    .icon(IconName::Replace)
1465                    .icon_position(IconPosition::Start)
1466                    .icon_size(IconSize::Small)
1467                    .key_binding(KeyBinding::for_action_in(
1468                        &ToggleReplace,
1469                        &focus_handle,
1470                        window,
1471                        cx,
1472                    ))
1473                    .on_click(|_event, window, cx| {
1474                        window.dispatch_action(ToggleReplace.boxed_clone(), cx)
1475                    }),
1476            )
1477            .child(
1478                Button::new("regex", "Match with regex")
1479                    .icon(IconName::Regex)
1480                    .icon_position(IconPosition::Start)
1481                    .icon_size(IconSize::Small)
1482                    .key_binding(KeyBinding::for_action_in(
1483                        &ToggleRegex,
1484                        &focus_handle,
1485                        window,
1486                        cx,
1487                    ))
1488                    .on_click(|_event, window, cx| {
1489                        window.dispatch_action(ToggleRegex.boxed_clone(), cx)
1490                    }),
1491            )
1492            .child(
1493                Button::new("match-case", "Match case")
1494                    .icon(IconName::CaseSensitive)
1495                    .icon_position(IconPosition::Start)
1496                    .icon_size(IconSize::Small)
1497                    .key_binding(KeyBinding::for_action_in(
1498                        &ToggleCaseSensitive,
1499                        &focus_handle,
1500                        window,
1501                        cx,
1502                    ))
1503                    .on_click(|_event, window, cx| {
1504                        window.dispatch_action(ToggleCaseSensitive.boxed_clone(), cx)
1505                    }),
1506            )
1507            .child(
1508                Button::new("match-whole-words", "Match whole words")
1509                    .icon(IconName::WholeWord)
1510                    .icon_position(IconPosition::Start)
1511                    .icon_size(IconSize::Small)
1512                    .key_binding(KeyBinding::for_action_in(
1513                        &ToggleWholeWord,
1514                        &focus_handle,
1515                        window,
1516                        cx,
1517                    ))
1518                    .on_click(|_event, window, cx| {
1519                        window.dispatch_action(ToggleWholeWord.boxed_clone(), cx)
1520                    }),
1521            )
1522    }
1523
1524    fn border_color_for(&self, panel: InputPanel, cx: &App) -> Hsla {
1525        if self.panels_with_errors.contains_key(&panel) {
1526            Color::Error.color(cx)
1527        } else {
1528            cx.theme().colors().border
1529        }
1530    }
1531
1532    fn move_focus_to_results(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1533        if !self.results_editor.focus_handle(cx).is_focused(window)
1534            && !self.entity.read(cx).match_ranges.is_empty()
1535        {
1536            cx.stop_propagation();
1537            self.focus_results_editor(window, cx)
1538        }
1539    }
1540
1541    #[cfg(any(test, feature = "test-support"))]
1542    pub fn results_editor(&self) -> &Entity<Editor> {
1543        &self.results_editor
1544    }
1545
1546    fn adjust_query_regex_language(&self, cx: &mut App) {
1547        let enable = self.search_options.contains(SearchOptions::REGEX);
1548        let query_buffer = self
1549            .query_editor
1550            .read(cx)
1551            .buffer()
1552            .read(cx)
1553            .as_singleton()
1554            .expect("query editor should be backed by a singleton buffer");
1555        if enable {
1556            if let Some(regex_language) = self.regex_language.clone() {
1557                query_buffer.update(cx, |query_buffer, cx| {
1558                    query_buffer.set_language(Some(regex_language), cx);
1559                })
1560            }
1561        } else {
1562            query_buffer.update(cx, |query_buffer, cx| {
1563                query_buffer.set_language(None, cx);
1564            })
1565        }
1566    }
1567}
1568
1569fn buffer_search_query(
1570    workspace: &mut Workspace,
1571    item: &dyn ItemHandle,
1572    cx: &mut Context<Workspace>,
1573) -> Option<String> {
1574    let buffer_search_bar = workspace
1575        .pane_for(item)
1576        .and_then(|pane| {
1577            pane.read(cx)
1578                .toolbar()
1579                .read(cx)
1580                .item_of_type::<BufferSearchBar>()
1581        })?
1582        .read(cx);
1583    if buffer_search_bar.query_editor_focused() {
1584        let buffer_search_query = buffer_search_bar.query(cx);
1585        if !buffer_search_query.is_empty() {
1586            return Some(buffer_search_query);
1587        }
1588    }
1589    None
1590}
1591
1592impl Default for ProjectSearchBar {
1593    fn default() -> Self {
1594        Self::new()
1595    }
1596}
1597
1598impl ProjectSearchBar {
1599    pub fn new() -> Self {
1600        Self {
1601            active_project_search: None,
1602            subscription: None,
1603        }
1604    }
1605
1606    fn confirm(&mut self, _: &Confirm, window: &mut Window, cx: &mut Context<Self>) {
1607        if let Some(search_view) = self.active_project_search.as_ref() {
1608            search_view.update(cx, |search_view, cx| {
1609                if !search_view
1610                    .replacement_editor
1611                    .focus_handle(cx)
1612                    .is_focused(window)
1613                {
1614                    cx.stop_propagation();
1615                    search_view
1616                        .prompt_to_save_if_dirty_then_search(window, cx)
1617                        .detach_and_log_err(cx);
1618                }
1619            });
1620        }
1621    }
1622
1623    fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
1624        self.cycle_field(Direction::Next, window, cx);
1625    }
1626
1627    fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
1628        self.cycle_field(Direction::Prev, window, cx);
1629    }
1630
1631    fn focus_search(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1632        if let Some(search_view) = self.active_project_search.as_ref() {
1633            search_view.update(cx, |search_view, cx| {
1634                search_view.query_editor.focus_handle(cx).focus(window);
1635            });
1636        }
1637    }
1638
1639    fn cycle_field(&mut self, direction: Direction, window: &mut Window, cx: &mut Context<Self>) {
1640        let active_project_search = match &self.active_project_search {
1641            Some(active_project_search) => active_project_search,
1642            None => return,
1643        };
1644
1645        active_project_search.update(cx, |project_view, cx| {
1646            let mut views = vec![project_view.query_editor.focus_handle(cx)];
1647            if project_view.replace_enabled {
1648                views.push(project_view.replacement_editor.focus_handle(cx));
1649            }
1650            if project_view.filters_enabled {
1651                views.extend([
1652                    project_view.included_files_editor.focus_handle(cx),
1653                    project_view.excluded_files_editor.focus_handle(cx),
1654                ]);
1655            }
1656            let current_index = match views.iter().position(|focus| focus.is_focused(window)) {
1657                Some(index) => index,
1658                None => return,
1659            };
1660
1661            let new_index = match direction {
1662                Direction::Next => (current_index + 1) % views.len(),
1663                Direction::Prev if current_index == 0 => views.len() - 1,
1664                Direction::Prev => (current_index - 1) % views.len(),
1665            };
1666            let next_focus_handle = &views[new_index];
1667            window.focus(next_focus_handle);
1668            cx.stop_propagation();
1669        });
1670    }
1671
1672    pub(crate) fn toggle_search_option(
1673        &mut self,
1674        option: SearchOptions,
1675        window: &mut Window,
1676        cx: &mut Context<Self>,
1677    ) -> bool {
1678        if self.active_project_search.is_none() {
1679            return false;
1680        }
1681
1682        cx.spawn_in(window, async move |this, cx| {
1683            let task = this.update_in(cx, |this, window, cx| {
1684                let search_view = this.active_project_search.as_ref()?;
1685                search_view.update(cx, |search_view, cx| {
1686                    search_view.toggle_search_option(option, cx);
1687                    search_view
1688                        .entity
1689                        .read(cx)
1690                        .active_query
1691                        .is_some()
1692                        .then(|| search_view.prompt_to_save_if_dirty_then_search(window, cx))
1693                })
1694            })?;
1695            if let Some(task) = task {
1696                task.await?;
1697            }
1698            this.update(cx, |_, cx| {
1699                cx.notify();
1700            })?;
1701            anyhow::Ok(())
1702        })
1703        .detach();
1704        true
1705    }
1706
1707    fn toggle_replace(&mut self, _: &ToggleReplace, window: &mut Window, cx: &mut Context<Self>) {
1708        if let Some(search) = &self.active_project_search {
1709            search.update(cx, |this, cx| {
1710                this.replace_enabled = !this.replace_enabled;
1711                let editor_to_focus = if this.replace_enabled {
1712                    this.replacement_editor.focus_handle(cx)
1713                } else {
1714                    this.query_editor.focus_handle(cx)
1715                };
1716                window.focus(&editor_to_focus);
1717                cx.notify();
1718            });
1719        }
1720    }
1721
1722    fn toggle_filters(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
1723        if let Some(search_view) = self.active_project_search.as_ref() {
1724            search_view.update(cx, |search_view, cx| {
1725                search_view.toggle_filters(cx);
1726                search_view
1727                    .included_files_editor
1728                    .update(cx, |_, cx| cx.notify());
1729                search_view
1730                    .excluded_files_editor
1731                    .update(cx, |_, cx| cx.notify());
1732                window.refresh();
1733                cx.notify();
1734            });
1735            cx.notify();
1736            true
1737        } else {
1738            false
1739        }
1740    }
1741
1742    fn toggle_opened_only(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
1743        if self.active_project_search.is_none() {
1744            return false;
1745        }
1746
1747        cx.spawn_in(window, async move |this, cx| {
1748            let task = this.update_in(cx, |this, window, cx| {
1749                let search_view = this.active_project_search.as_ref()?;
1750                search_view.update(cx, |search_view, cx| {
1751                    search_view.toggle_opened_only(window, cx);
1752                    search_view
1753                        .entity
1754                        .read(cx)
1755                        .active_query
1756                        .is_some()
1757                        .then(|| search_view.prompt_to_save_if_dirty_then_search(window, cx))
1758                })
1759            })?;
1760            if let Some(task) = task {
1761                task.await?;
1762            }
1763            this.update(cx, |_, cx| {
1764                cx.notify();
1765            })?;
1766            anyhow::Ok(())
1767        })
1768        .detach();
1769        true
1770    }
1771
1772    fn is_opened_only_enabled(&self, cx: &App) -> bool {
1773        if let Some(search_view) = self.active_project_search.as_ref() {
1774            search_view.read(cx).included_opened_only
1775        } else {
1776            false
1777        }
1778    }
1779
1780    fn move_focus_to_results(&self, window: &mut Window, cx: &mut Context<Self>) {
1781        if let Some(search_view) = self.active_project_search.as_ref() {
1782            search_view.update(cx, |search_view, cx| {
1783                search_view.move_focus_to_results(window, cx);
1784            });
1785            cx.notify();
1786        }
1787    }
1788
1789    fn next_history_query(
1790        &mut self,
1791        _: &NextHistoryQuery,
1792        window: &mut Window,
1793        cx: &mut Context<Self>,
1794    ) {
1795        if let Some(search_view) = self.active_project_search.as_ref() {
1796            search_view.update(cx, |search_view, cx| {
1797                for (editor, kind) in [
1798                    (search_view.query_editor.clone(), SearchInputKind::Query),
1799                    (
1800                        search_view.included_files_editor.clone(),
1801                        SearchInputKind::Include,
1802                    ),
1803                    (
1804                        search_view.excluded_files_editor.clone(),
1805                        SearchInputKind::Exclude,
1806                    ),
1807                ] {
1808                    if editor.focus_handle(cx).is_focused(window) {
1809                        let new_query = search_view.entity.update(cx, |model, cx| {
1810                            let project = model.project.clone();
1811
1812                            if let Some(new_query) = project.update(cx, |project, _| {
1813                                project
1814                                    .search_history_mut(kind)
1815                                    .next(model.cursor_mut(kind))
1816                                    .map(str::to_string)
1817                            }) {
1818                                new_query
1819                            } else {
1820                                model.cursor_mut(kind).reset();
1821                                String::new()
1822                            }
1823                        });
1824                        search_view.set_search_editor(kind, &new_query, window, cx);
1825                    }
1826                }
1827            });
1828        }
1829    }
1830
1831    fn previous_history_query(
1832        &mut self,
1833        _: &PreviousHistoryQuery,
1834        window: &mut Window,
1835        cx: &mut Context<Self>,
1836    ) {
1837        if let Some(search_view) = self.active_project_search.as_ref() {
1838            search_view.update(cx, |search_view, cx| {
1839                for (editor, kind) in [
1840                    (search_view.query_editor.clone(), SearchInputKind::Query),
1841                    (
1842                        search_view.included_files_editor.clone(),
1843                        SearchInputKind::Include,
1844                    ),
1845                    (
1846                        search_view.excluded_files_editor.clone(),
1847                        SearchInputKind::Exclude,
1848                    ),
1849                ] {
1850                    if editor.focus_handle(cx).is_focused(window) {
1851                        if editor.read(cx).text(cx).is_empty()
1852                            && let Some(new_query) = search_view
1853                                .entity
1854                                .read(cx)
1855                                .project
1856                                .read(cx)
1857                                .search_history(kind)
1858                                .current(search_view.entity.read(cx).cursor(kind))
1859                                .map(str::to_string)
1860                        {
1861                            search_view.set_search_editor(kind, &new_query, window, cx);
1862                            return;
1863                        }
1864
1865                        if let Some(new_query) = search_view.entity.update(cx, |model, cx| {
1866                            let project = model.project.clone();
1867                            project.update(cx, |project, _| {
1868                                project
1869                                    .search_history_mut(kind)
1870                                    .previous(model.cursor_mut(kind))
1871                                    .map(str::to_string)
1872                            })
1873                        }) {
1874                            search_view.set_search_editor(kind, &new_query, window, cx);
1875                        }
1876                    }
1877                }
1878            });
1879        }
1880    }
1881
1882    fn select_next_match(
1883        &mut self,
1884        _: &SelectNextMatch,
1885        window: &mut Window,
1886        cx: &mut Context<Self>,
1887    ) {
1888        if let Some(search) = self.active_project_search.as_ref() {
1889            search.update(cx, |this, cx| {
1890                this.select_match(Direction::Next, window, cx);
1891            })
1892        }
1893    }
1894
1895    fn select_prev_match(
1896        &mut self,
1897        _: &SelectPreviousMatch,
1898        window: &mut Window,
1899        cx: &mut Context<Self>,
1900    ) {
1901        if let Some(search) = self.active_project_search.as_ref() {
1902            search.update(cx, |this, cx| {
1903                this.select_match(Direction::Prev, window, cx);
1904            })
1905        }
1906    }
1907}
1908
1909impl Render for ProjectSearchBar {
1910    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1911        let Some(search) = self.active_project_search.clone() else {
1912            return div();
1913        };
1914        let search = search.read(cx);
1915        let focus_handle = search.focus_handle(cx);
1916
1917        let container_width = window.viewport_size().width;
1918        let input_width = SearchInputWidth::calc_width(container_width);
1919
1920        let input_base_styles = |panel: InputPanel| {
1921            input_base_styles(search.border_color_for(panel, cx), |div| match panel {
1922                InputPanel::Query | InputPanel::Replacement => div.w(input_width),
1923                InputPanel::Include | InputPanel::Exclude => div.flex_grow(),
1924            })
1925        };
1926        let theme_colors = cx.theme().colors();
1927        let project_search = search.entity.read(cx);
1928        let limit_reached = project_search.limit_reached;
1929
1930        let color_override = match (
1931            &project_search.pending_search,
1932            project_search.no_results,
1933            &project_search.active_query,
1934            &project_search.last_search_query_text,
1935        ) {
1936            (None, Some(true), Some(q), Some(p)) if q.as_str() == p => Some(Color::Error),
1937            _ => None,
1938        };
1939
1940        let match_text = search
1941            .active_match_index
1942            .and_then(|index| {
1943                let index = index + 1;
1944                let match_quantity = project_search.match_ranges.len();
1945                if match_quantity > 0 {
1946                    debug_assert!(match_quantity >= index);
1947                    if limit_reached {
1948                        Some(format!("{index}/{match_quantity}+"))
1949                    } else {
1950                        Some(format!("{index}/{match_quantity}"))
1951                    }
1952                } else {
1953                    None
1954                }
1955            })
1956            .unwrap_or_else(|| "0/0".to_string());
1957
1958        let query_column = input_base_styles(InputPanel::Query)
1959            .on_action(cx.listener(|this, action, window, cx| this.confirm(action, window, cx)))
1960            .on_action(cx.listener(|this, action, window, cx| {
1961                this.previous_history_query(action, window, cx)
1962            }))
1963            .on_action(
1964                cx.listener(|this, action, window, cx| this.next_history_query(action, window, cx)),
1965            )
1966            .child(render_text_input(&search.query_editor, color_override, cx))
1967            .child(
1968                h_flex()
1969                    .gap_1()
1970                    .child(SearchOption::CaseSensitive.as_button(
1971                        search.search_options,
1972                        SearchSource::Project(cx),
1973                        focus_handle.clone(),
1974                    ))
1975                    .child(SearchOption::WholeWord.as_button(
1976                        search.search_options,
1977                        SearchSource::Project(cx),
1978                        focus_handle.clone(),
1979                    ))
1980                    .child(SearchOption::Regex.as_button(
1981                        search.search_options,
1982                        SearchSource::Project(cx),
1983                        focus_handle.clone(),
1984                    )),
1985            );
1986
1987        let query_focus = search.query_editor.focus_handle(cx);
1988
1989        let matches_column = h_flex()
1990            .pl_2()
1991            .ml_2()
1992            .border_l_1()
1993            .border_color(theme_colors.border_variant)
1994            .child(render_action_button(
1995                "project-search-nav-button",
1996                IconName::ChevronLeft,
1997                search
1998                    .active_match_index
1999                    .is_none()
2000                    .then_some(ActionButtonState::Disabled),
2001                "Select Previous Match",
2002                &SelectPreviousMatch,
2003                query_focus.clone(),
2004            ))
2005            .child(render_action_button(
2006                "project-search-nav-button",
2007                IconName::ChevronRight,
2008                search
2009                    .active_match_index
2010                    .is_none()
2011                    .then_some(ActionButtonState::Disabled),
2012                "Select Next Match",
2013                &SelectNextMatch,
2014                query_focus,
2015            ))
2016            .child(
2017                div()
2018                    .id("matches")
2019                    .ml_2()
2020                    .min_w(rems_from_px(40.))
2021                    .child(Label::new(match_text).size(LabelSize::Small).color(
2022                        if search.active_match_index.is_some() {
2023                            Color::Default
2024                        } else {
2025                            Color::Disabled
2026                        },
2027                    ))
2028                    .when(limit_reached, |el| {
2029                        el.tooltip(Tooltip::text(
2030                            "Search limits reached.\nTry narrowing your search.",
2031                        ))
2032                    }),
2033            );
2034
2035        let mode_column = h_flex()
2036            .gap_1()
2037            .min_w_64()
2038            .child(
2039                IconButton::new("project-search-filter-button", IconName::Filter)
2040                    .shape(IconButtonShape::Square)
2041                    .tooltip(|window, cx| {
2042                        Tooltip::for_action("Toggle Filters", &ToggleFilters, window, cx)
2043                    })
2044                    .on_click(cx.listener(|this, _, window, cx| {
2045                        this.toggle_filters(window, cx);
2046                    }))
2047                    .toggle_state(
2048                        self.active_project_search
2049                            .as_ref()
2050                            .map(|search| search.read(cx).filters_enabled)
2051                            .unwrap_or_default(),
2052                    )
2053                    .tooltip({
2054                        let focus_handle = focus_handle.clone();
2055                        move |window, cx| {
2056                            Tooltip::for_action_in(
2057                                "Toggle Filters",
2058                                &ToggleFilters,
2059                                &focus_handle,
2060                                window,
2061                                cx,
2062                            )
2063                        }
2064                    }),
2065            )
2066            .child(render_action_button(
2067                "project-search",
2068                IconName::Replace,
2069                self.active_project_search
2070                    .as_ref()
2071                    .map(|search| search.read(cx).replace_enabled)
2072                    .and_then(|enabled| enabled.then_some(ActionButtonState::Toggled)),
2073                "Toggle Replace",
2074                &ToggleReplace,
2075                focus_handle.clone(),
2076            ))
2077            .child(matches_column);
2078
2079        let search_line = h_flex()
2080            .w_full()
2081            .gap_2()
2082            .child(query_column)
2083            .child(mode_column);
2084
2085        let replace_line = search.replace_enabled.then(|| {
2086            let replace_column = input_base_styles(InputPanel::Replacement)
2087                .child(render_text_input(&search.replacement_editor, None, cx));
2088
2089            let focus_handle = search.replacement_editor.read(cx).focus_handle(cx);
2090
2091            let replace_actions = h_flex()
2092                .min_w_64()
2093                .gap_1()
2094                .child(render_action_button(
2095                    "project-search-replace-button",
2096                    IconName::ReplaceNext,
2097                    Default::default(),
2098                    "Replace Next Match",
2099                    &ReplaceNext,
2100                    focus_handle.clone(),
2101                ))
2102                .child(render_action_button(
2103                    "project-search-replace-button",
2104                    IconName::ReplaceAll,
2105                    Default::default(),
2106                    "Replace All Matches",
2107                    &ReplaceAll,
2108                    focus_handle,
2109                ));
2110
2111            h_flex()
2112                .w_full()
2113                .gap_2()
2114                .child(replace_column)
2115                .child(replace_actions)
2116        });
2117
2118        let filter_line = search.filters_enabled.then(|| {
2119            let include = input_base_styles(InputPanel::Include)
2120                .on_action(cx.listener(|this, action, window, cx| {
2121                    this.previous_history_query(action, window, cx)
2122                }))
2123                .on_action(cx.listener(|this, action, window, cx| {
2124                    this.next_history_query(action, window, cx)
2125                }))
2126                .child(render_text_input(&search.included_files_editor, None, cx));
2127            let exclude = input_base_styles(InputPanel::Exclude)
2128                .on_action(cx.listener(|this, action, window, cx| {
2129                    this.previous_history_query(action, window, cx)
2130                }))
2131                .on_action(cx.listener(|this, action, window, cx| {
2132                    this.next_history_query(action, window, cx)
2133                }))
2134                .child(render_text_input(&search.excluded_files_editor, None, cx));
2135            let mode_column = h_flex()
2136                .gap_1()
2137                .min_w_64()
2138                .child(
2139                    IconButton::new("project-search-opened-only", IconName::FolderSearch)
2140                        .shape(IconButtonShape::Square)
2141                        .toggle_state(self.is_opened_only_enabled(cx))
2142                        .tooltip(Tooltip::text("Only Search Open Files"))
2143                        .on_click(cx.listener(|this, _, window, cx| {
2144                            this.toggle_opened_only(window, cx);
2145                        })),
2146                )
2147                .child(SearchOption::IncludeIgnored.as_button(
2148                    search.search_options,
2149                    SearchSource::Project(cx),
2150                    focus_handle.clone(),
2151                ));
2152            h_flex()
2153                .w_full()
2154                .gap_2()
2155                .child(
2156                    h_flex()
2157                        .gap_2()
2158                        .w(input_width)
2159                        .child(include)
2160                        .child(exclude),
2161                )
2162                .child(mode_column)
2163        });
2164
2165        let mut key_context = KeyContext::default();
2166        key_context.add("ProjectSearchBar");
2167        if search
2168            .replacement_editor
2169            .focus_handle(cx)
2170            .is_focused(window)
2171        {
2172            key_context.add("in_replace");
2173        }
2174
2175        let query_error_line = search
2176            .panels_with_errors
2177            .get(&InputPanel::Query)
2178            .map(|error| {
2179                Label::new(error)
2180                    .size(LabelSize::Small)
2181                    .color(Color::Error)
2182                    .mt_neg_1()
2183                    .ml_2()
2184            });
2185
2186        let filter_error_line = search
2187            .panels_with_errors
2188            .get(&InputPanel::Include)
2189            .or_else(|| search.panels_with_errors.get(&InputPanel::Exclude))
2190            .map(|error| {
2191                Label::new(error)
2192                    .size(LabelSize::Small)
2193                    .color(Color::Error)
2194                    .mt_neg_1()
2195                    .ml_2()
2196            });
2197
2198        v_flex()
2199            .gap_2()
2200            .py(px(1.0))
2201            .w_full()
2202            .key_context(key_context)
2203            .on_action(cx.listener(|this, _: &ToggleFocus, window, cx| {
2204                this.move_focus_to_results(window, cx)
2205            }))
2206            .on_action(cx.listener(|this, _: &ToggleFilters, window, cx| {
2207                this.toggle_filters(window, cx);
2208            }))
2209            .capture_action(cx.listener(Self::tab))
2210            .capture_action(cx.listener(Self::backtab))
2211            .on_action(cx.listener(|this, action, window, cx| this.confirm(action, window, cx)))
2212            .on_action(cx.listener(|this, action, window, cx| {
2213                this.toggle_replace(action, window, cx);
2214            }))
2215            .on_action(cx.listener(|this, _: &ToggleWholeWord, window, cx| {
2216                this.toggle_search_option(SearchOptions::WHOLE_WORD, window, cx);
2217            }))
2218            .on_action(cx.listener(|this, _: &ToggleCaseSensitive, window, cx| {
2219                this.toggle_search_option(SearchOptions::CASE_SENSITIVE, window, cx);
2220            }))
2221            .on_action(cx.listener(|this, action, window, cx| {
2222                if let Some(search) = this.active_project_search.as_ref() {
2223                    search.update(cx, |this, cx| {
2224                        this.replace_next(action, window, cx);
2225                    })
2226                }
2227            }))
2228            .on_action(cx.listener(|this, action, window, cx| {
2229                if let Some(search) = this.active_project_search.as_ref() {
2230                    search.update(cx, |this, cx| {
2231                        this.replace_all(action, window, cx);
2232                    })
2233                }
2234            }))
2235            .when(search.filters_enabled, |this| {
2236                this.on_action(cx.listener(|this, _: &ToggleIncludeIgnored, window, cx| {
2237                    this.toggle_search_option(SearchOptions::INCLUDE_IGNORED, window, cx);
2238                }))
2239            })
2240            .on_action(cx.listener(Self::select_next_match))
2241            .on_action(cx.listener(Self::select_prev_match))
2242            .child(search_line)
2243            .children(query_error_line)
2244            .children(replace_line)
2245            .children(filter_line)
2246            .children(filter_error_line)
2247    }
2248}
2249
2250impl EventEmitter<ToolbarItemEvent> for ProjectSearchBar {}
2251
2252impl ToolbarItemView for ProjectSearchBar {
2253    fn set_active_pane_item(
2254        &mut self,
2255        active_pane_item: Option<&dyn ItemHandle>,
2256        _: &mut Window,
2257        cx: &mut Context<Self>,
2258    ) -> ToolbarItemLocation {
2259        cx.notify();
2260        self.subscription = None;
2261        self.active_project_search = None;
2262        if let Some(search) = active_pane_item.and_then(|i| i.downcast::<ProjectSearchView>()) {
2263            self.subscription = Some(cx.observe(&search, |_, _, cx| cx.notify()));
2264            self.active_project_search = Some(search);
2265            ToolbarItemLocation::PrimaryLeft {}
2266        } else {
2267            ToolbarItemLocation::Hidden
2268        }
2269    }
2270}
2271
2272fn register_workspace_action<A: Action>(
2273    workspace: &mut Workspace,
2274    callback: fn(&mut ProjectSearchBar, &A, &mut Window, &mut Context<ProjectSearchBar>),
2275) {
2276    workspace.register_action(move |workspace, action: &A, window, cx| {
2277        if workspace.has_active_modal(window, cx) {
2278            cx.propagate();
2279            return;
2280        }
2281
2282        workspace.active_pane().update(cx, |pane, cx| {
2283            pane.toolbar().update(cx, move |workspace, cx| {
2284                if let Some(search_bar) = workspace.item_of_type::<ProjectSearchBar>() {
2285                    search_bar.update(cx, move |search_bar, cx| {
2286                        if search_bar.active_project_search.is_some() {
2287                            callback(search_bar, action, window, cx);
2288                            cx.notify();
2289                        } else {
2290                            cx.propagate();
2291                        }
2292                    });
2293                }
2294            });
2295        })
2296    });
2297}
2298
2299fn register_workspace_action_for_present_search<A: Action>(
2300    workspace: &mut Workspace,
2301    callback: fn(&mut Workspace, &A, &mut Window, &mut Context<Workspace>),
2302) {
2303    workspace.register_action(move |workspace, action: &A, window, cx| {
2304        if workspace.has_active_modal(window, cx) {
2305            cx.propagate();
2306            return;
2307        }
2308
2309        let should_notify = workspace
2310            .active_pane()
2311            .read(cx)
2312            .toolbar()
2313            .read(cx)
2314            .item_of_type::<ProjectSearchBar>()
2315            .map(|search_bar| search_bar.read(cx).active_project_search.is_some())
2316            .unwrap_or(false);
2317        if should_notify {
2318            callback(workspace, action, window, cx);
2319            cx.notify();
2320        } else {
2321            cx.propagate();
2322        }
2323    });
2324}
2325
2326#[cfg(any(test, feature = "test-support"))]
2327pub fn perform_project_search(
2328    search_view: &Entity<ProjectSearchView>,
2329    text: impl Into<std::sync::Arc<str>>,
2330    cx: &mut gpui::VisualTestContext,
2331) {
2332    cx.run_until_parked();
2333    search_view.update_in(cx, |search_view, window, cx| {
2334        search_view.query_editor.update(cx, |query_editor, cx| {
2335            query_editor.set_text(text, window, cx)
2336        });
2337        search_view.search(cx);
2338    });
2339    cx.run_until_parked();
2340}
2341
2342#[cfg(test)]
2343pub mod tests {
2344    use std::{ops::Deref as _, sync::Arc, time::Duration};
2345
2346    use super::*;
2347    use editor::{DisplayPoint, display_map::DisplayRow};
2348    use gpui::{Action, TestAppContext, VisualTestContext, WindowHandle};
2349    use project::FakeFs;
2350    use serde_json::json;
2351    use settings::SettingsStore;
2352    use util::path;
2353    use workspace::DeploySearch;
2354
2355    #[gpui::test]
2356    async fn test_project_search(cx: &mut TestAppContext) {
2357        init_test(cx);
2358
2359        let fs = FakeFs::new(cx.background_executor.clone());
2360        fs.insert_tree(
2361            path!("/dir"),
2362            json!({
2363                "one.rs": "const ONE: usize = 1;",
2364                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2365                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2366                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2367            }),
2368        )
2369        .await;
2370        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
2371        let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
2372        let workspace = window.root(cx).unwrap();
2373        let search = cx.new(|cx| ProjectSearch::new(project.clone(), cx));
2374        let search_view = cx.add_window(|window, cx| {
2375            ProjectSearchView::new(workspace.downgrade(), search.clone(), window, cx, None)
2376        });
2377
2378        perform_search(search_view, "TWO", cx);
2379        search_view.update(cx, |search_view, window, cx| {
2380            assert_eq!(
2381                search_view
2382                    .results_editor
2383                    .update(cx, |editor, cx| editor.display_text(cx)),
2384                "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;"
2385            );
2386            let match_background_color = cx.theme().colors().search_match_background;
2387            let selection_background_color = cx.theme().colors().editor_document_highlight_bracket_background;
2388            assert_eq!(
2389                search_view
2390                    .results_editor
2391                    .update(cx, |editor, cx| editor.all_text_background_highlights(window, cx)),
2392                &[
2393                    (
2394                        DisplayPoint::new(DisplayRow(2), 32)..DisplayPoint::new(DisplayRow(2), 35),
2395                        match_background_color
2396                    ),
2397                    (
2398                        DisplayPoint::new(DisplayRow(2), 37)..DisplayPoint::new(DisplayRow(2), 40),
2399                        selection_background_color
2400                    ),
2401                    (
2402                        DisplayPoint::new(DisplayRow(2), 37)..DisplayPoint::new(DisplayRow(2), 40),
2403                        match_background_color
2404                    ),
2405                    (
2406                        DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(5), 9),
2407                        selection_background_color
2408                    ),
2409                    (
2410                        DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(5), 9),
2411                        match_background_color
2412                    ),
2413
2414                ]
2415            );
2416            assert_eq!(search_view.active_match_index, Some(0));
2417            assert_eq!(
2418                search_view
2419                    .results_editor
2420                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2421                [DisplayPoint::new(DisplayRow(2), 32)..DisplayPoint::new(DisplayRow(2), 35)]
2422            );
2423
2424            search_view.select_match(Direction::Next, window, cx);
2425        }).unwrap();
2426
2427        search_view
2428            .update(cx, |search_view, window, cx| {
2429                assert_eq!(search_view.active_match_index, Some(1));
2430                assert_eq!(
2431                    search_view
2432                        .results_editor
2433                        .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2434                    [DisplayPoint::new(DisplayRow(2), 37)..DisplayPoint::new(DisplayRow(2), 40)]
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(2));
2443                assert_eq!(
2444                    search_view
2445                        .results_editor
2446                        .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2447                    [DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(5), 9)]
2448                );
2449                search_view.select_match(Direction::Next, window, cx);
2450            })
2451            .unwrap();
2452
2453        search_view
2454            .update(cx, |search_view, window, cx| {
2455                assert_eq!(search_view.active_match_index, Some(0));
2456                assert_eq!(
2457                    search_view
2458                        .results_editor
2459                        .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2460                    [DisplayPoint::new(DisplayRow(2), 32)..DisplayPoint::new(DisplayRow(2), 35)]
2461                );
2462                search_view.select_match(Direction::Prev, window, cx);
2463            })
2464            .unwrap();
2465
2466        search_view
2467            .update(cx, |search_view, window, cx| {
2468                assert_eq!(search_view.active_match_index, Some(2));
2469                assert_eq!(
2470                    search_view
2471                        .results_editor
2472                        .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2473                    [DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(5), 9)]
2474                );
2475                search_view.select_match(Direction::Prev, window, cx);
2476            })
2477            .unwrap();
2478
2479        search_view
2480            .update(cx, |search_view, _, cx| {
2481                assert_eq!(search_view.active_match_index, Some(1));
2482                assert_eq!(
2483                    search_view
2484                        .results_editor
2485                        .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2486                    [DisplayPoint::new(DisplayRow(2), 37)..DisplayPoint::new(DisplayRow(2), 40)]
2487                );
2488            })
2489            .unwrap();
2490    }
2491
2492    #[gpui::test]
2493    async fn test_deploy_project_search_focus(cx: &mut TestAppContext) {
2494        init_test(cx);
2495
2496        let fs = FakeFs::new(cx.background_executor.clone());
2497        fs.insert_tree(
2498            "/dir",
2499            json!({
2500                "one.rs": "const ONE: usize = 1;",
2501                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2502                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2503                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2504            }),
2505        )
2506        .await;
2507        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
2508        let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
2509        let workspace = window;
2510        let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
2511
2512        let active_item = cx.read(|cx| {
2513            workspace
2514                .read(cx)
2515                .unwrap()
2516                .active_pane()
2517                .read(cx)
2518                .active_item()
2519                .and_then(|item| item.downcast::<ProjectSearchView>())
2520        });
2521        assert!(
2522            active_item.is_none(),
2523            "Expected no search panel to be active"
2524        );
2525
2526        window
2527            .update(cx, move |workspace, window, cx| {
2528                assert_eq!(workspace.panes().len(), 1);
2529                workspace.panes()[0].update(cx, |pane, cx| {
2530                    pane.toolbar()
2531                        .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
2532                });
2533
2534                ProjectSearchView::deploy_search(
2535                    workspace,
2536                    &workspace::DeploySearch::find(),
2537                    window,
2538                    cx,
2539                )
2540            })
2541            .unwrap();
2542
2543        let Some(search_view) = cx.read(|cx| {
2544            workspace
2545                .read(cx)
2546                .unwrap()
2547                .active_pane()
2548                .read(cx)
2549                .active_item()
2550                .and_then(|item| item.downcast::<ProjectSearchView>())
2551        }) else {
2552            panic!("Search view expected to appear after new search event trigger")
2553        };
2554
2555        cx.spawn(|mut cx| async move {
2556            window
2557                .update(&mut cx, |_, window, cx| {
2558                    window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2559                })
2560                .unwrap();
2561        })
2562        .detach();
2563        cx.background_executor.run_until_parked();
2564        window
2565            .update(cx, |_, window, cx| {
2566                search_view.update(cx, |search_view, cx| {
2567                    assert!(
2568                        search_view.query_editor.focus_handle(cx).is_focused(window),
2569                        "Empty search view should be focused after the toggle focus event: no results panel to focus on",
2570                    );
2571                });
2572        }).unwrap();
2573
2574        window
2575            .update(cx, |_, window, cx| {
2576                search_view.update(cx, |search_view, cx| {
2577                    let query_editor = &search_view.query_editor;
2578                    assert!(
2579                        query_editor.focus_handle(cx).is_focused(window),
2580                        "Search view should be focused after the new search view is activated",
2581                    );
2582                    let query_text = query_editor.read(cx).text(cx);
2583                    assert!(
2584                        query_text.is_empty(),
2585                        "New search query should be empty but got '{query_text}'",
2586                    );
2587                    let results_text = search_view
2588                        .results_editor
2589                        .update(cx, |editor, cx| editor.display_text(cx));
2590                    assert!(
2591                        results_text.is_empty(),
2592                        "Empty search view should have no results but got '{results_text}'"
2593                    );
2594                });
2595            })
2596            .unwrap();
2597
2598        window
2599            .update(cx, |_, window, cx| {
2600                search_view.update(cx, |search_view, cx| {
2601                    search_view.query_editor.update(cx, |query_editor, cx| {
2602                        query_editor.set_text("sOMETHINGtHATsURELYdOESnOTeXIST", window, cx)
2603                    });
2604                    search_view.search(cx);
2605                });
2606            })
2607            .unwrap();
2608        cx.background_executor.run_until_parked();
2609        window
2610            .update(cx, |_, window, cx| {
2611                search_view.update(cx, |search_view, cx| {
2612                    let results_text = search_view
2613                        .results_editor
2614                        .update(cx, |editor, cx| editor.display_text(cx));
2615                    assert!(
2616                        results_text.is_empty(),
2617                        "Search view for mismatching query should have no results but got '{results_text}'"
2618                    );
2619                    assert!(
2620                        search_view.query_editor.focus_handle(cx).is_focused(window),
2621                        "Search view should be focused after mismatching query had been used in search",
2622                    );
2623                });
2624            }).unwrap();
2625
2626        cx.spawn(|mut cx| async move {
2627            window.update(&mut cx, |_, window, cx| {
2628                window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2629            })
2630        })
2631        .detach();
2632        cx.background_executor.run_until_parked();
2633        window.update(cx, |_, window, cx| {
2634            search_view.update(cx, |search_view, cx| {
2635                assert!(
2636                    search_view.query_editor.focus_handle(cx).is_focused(window),
2637                    "Search view with mismatching query should be focused after the toggle focus event: still no results panel to focus on",
2638                );
2639            });
2640        }).unwrap();
2641
2642        window
2643            .update(cx, |_, window, cx| {
2644                search_view.update(cx, |search_view, cx| {
2645                    search_view.query_editor.update(cx, |query_editor, cx| {
2646                        query_editor.set_text("TWO", window, cx)
2647                    });
2648                    search_view.search(cx);
2649                });
2650            })
2651            .unwrap();
2652        cx.background_executor.run_until_parked();
2653        window.update(cx, |_, window, cx| {
2654            search_view.update(cx, |search_view, cx| {
2655                assert_eq!(
2656                    search_view
2657                        .results_editor
2658                        .update(cx, |editor, cx| editor.display_text(cx)),
2659                    "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
2660                    "Search view results should match the query"
2661                );
2662                assert!(
2663                    search_view.results_editor.focus_handle(cx).is_focused(window),
2664                    "Search view with mismatching query should be focused after search results are available",
2665                );
2666            });
2667        }).unwrap();
2668        cx.spawn(|mut cx| async move {
2669            window
2670                .update(&mut cx, |_, window, cx| {
2671                    window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2672                })
2673                .unwrap();
2674        })
2675        .detach();
2676        cx.background_executor.run_until_parked();
2677        window.update(cx, |_, window, cx| {
2678            search_view.update(cx, |search_view, cx| {
2679                assert!(
2680                    search_view.results_editor.focus_handle(cx).is_focused(window),
2681                    "Search view with matching query should still have its results editor focused after the toggle focus event",
2682                );
2683            });
2684        }).unwrap();
2685
2686        workspace
2687            .update(cx, |workspace, window, cx| {
2688                ProjectSearchView::deploy_search(
2689                    workspace,
2690                    &workspace::DeploySearch::find(),
2691                    window,
2692                    cx,
2693                )
2694            })
2695            .unwrap();
2696        window.update(cx, |_, window, cx| {
2697            search_view.update(cx, |search_view, cx| {
2698                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");
2699                assert_eq!(
2700                    search_view
2701                        .results_editor
2702                        .update(cx, |editor, cx| editor.display_text(cx)),
2703                    "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
2704                    "Results should be unchanged after search view 2nd open in a row"
2705                );
2706                assert!(
2707                    search_view.query_editor.focus_handle(cx).is_focused(window),
2708                    "Focus should be moved into query editor again after search view 2nd open in a row"
2709                );
2710            });
2711        }).unwrap();
2712
2713        cx.spawn(|mut cx| async move {
2714            window
2715                .update(&mut cx, |_, window, cx| {
2716                    window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2717                })
2718                .unwrap();
2719        })
2720        .detach();
2721        cx.background_executor.run_until_parked();
2722        window.update(cx, |_, window, cx| {
2723            search_view.update(cx, |search_view, cx| {
2724                assert!(
2725                    search_view.results_editor.focus_handle(cx).is_focused(window),
2726                    "Search view with matching query should switch focus to the results editor after the toggle focus event",
2727                );
2728            });
2729        }).unwrap();
2730    }
2731
2732    #[gpui::test]
2733    async fn test_filters_consider_toggle_state(cx: &mut TestAppContext) {
2734        init_test(cx);
2735
2736        let fs = FakeFs::new(cx.background_executor.clone());
2737        fs.insert_tree(
2738            "/dir",
2739            json!({
2740                "one.rs": "const ONE: usize = 1;",
2741                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2742                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2743                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2744            }),
2745        )
2746        .await;
2747        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
2748        let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
2749        let workspace = window;
2750        let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
2751
2752        window
2753            .update(cx, move |workspace, window, cx| {
2754                workspace.panes()[0].update(cx, |pane, cx| {
2755                    pane.toolbar()
2756                        .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
2757                });
2758
2759                ProjectSearchView::deploy_search(
2760                    workspace,
2761                    &workspace::DeploySearch::find(),
2762                    window,
2763                    cx,
2764                )
2765            })
2766            .unwrap();
2767
2768        let Some(search_view) = cx.read(|cx| {
2769            workspace
2770                .read(cx)
2771                .unwrap()
2772                .active_pane()
2773                .read(cx)
2774                .active_item()
2775                .and_then(|item| item.downcast::<ProjectSearchView>())
2776        }) else {
2777            panic!("Search view expected to appear after new search event trigger")
2778        };
2779
2780        cx.spawn(|mut cx| async move {
2781            window
2782                .update(&mut cx, |_, window, cx| {
2783                    window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2784                })
2785                .unwrap();
2786        })
2787        .detach();
2788        cx.background_executor.run_until_parked();
2789
2790        window
2791            .update(cx, |_, window, cx| {
2792                search_view.update(cx, |search_view, cx| {
2793                    search_view.query_editor.update(cx, |query_editor, cx| {
2794                        query_editor.set_text("const FOUR", window, cx)
2795                    });
2796                    search_view.toggle_filters(cx);
2797                    search_view
2798                        .excluded_files_editor
2799                        .update(cx, |exclude_editor, cx| {
2800                            exclude_editor.set_text("four.rs", window, cx)
2801                        });
2802                    search_view.search(cx);
2803                });
2804            })
2805            .unwrap();
2806        cx.background_executor.run_until_parked();
2807        window
2808            .update(cx, |_, _, cx| {
2809                search_view.update(cx, |search_view, cx| {
2810                    let results_text = search_view
2811                        .results_editor
2812                        .update(cx, |editor, cx| editor.display_text(cx));
2813                    assert!(
2814                        results_text.is_empty(),
2815                        "Search view for query with the only match in an excluded file should have no results but got '{results_text}'"
2816                    );
2817                });
2818            }).unwrap();
2819
2820        cx.spawn(|mut cx| async move {
2821            window.update(&mut cx, |_, window, cx| {
2822                window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2823            })
2824        })
2825        .detach();
2826        cx.background_executor.run_until_parked();
2827
2828        window
2829            .update(cx, |_, _, cx| {
2830                search_view.update(cx, |search_view, cx| {
2831                    search_view.toggle_filters(cx);
2832                    search_view.search(cx);
2833                });
2834            })
2835            .unwrap();
2836        cx.background_executor.run_until_parked();
2837        window
2838            .update(cx, |_, _, cx| {
2839                search_view.update(cx, |search_view, cx| {
2840                assert_eq!(
2841                    search_view
2842                        .results_editor
2843                        .update(cx, |editor, cx| editor.display_text(cx)),
2844                    "\n\nconst FOUR: usize = one::ONE + three::THREE;",
2845                    "Search view results should contain the queried result in the previously excluded file with filters toggled off"
2846                );
2847            });
2848            })
2849            .unwrap();
2850    }
2851
2852    #[gpui::test]
2853    async fn test_new_project_search_focus(cx: &mut TestAppContext) {
2854        init_test(cx);
2855
2856        let fs = FakeFs::new(cx.background_executor.clone());
2857        fs.insert_tree(
2858            path!("/dir"),
2859            json!({
2860                "one.rs": "const ONE: usize = 1;",
2861                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2862                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2863                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2864            }),
2865        )
2866        .await;
2867        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
2868        let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
2869        let workspace = window;
2870        let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
2871
2872        let active_item = cx.read(|cx| {
2873            workspace
2874                .read(cx)
2875                .unwrap()
2876                .active_pane()
2877                .read(cx)
2878                .active_item()
2879                .and_then(|item| item.downcast::<ProjectSearchView>())
2880        });
2881        assert!(
2882            active_item.is_none(),
2883            "Expected no search panel to be active"
2884        );
2885
2886        window
2887            .update(cx, move |workspace, window, cx| {
2888                assert_eq!(workspace.panes().len(), 1);
2889                workspace.panes()[0].update(cx, |pane, cx| {
2890                    pane.toolbar()
2891                        .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
2892                });
2893
2894                ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
2895            })
2896            .unwrap();
2897
2898        let Some(search_view) = cx.read(|cx| {
2899            workspace
2900                .read(cx)
2901                .unwrap()
2902                .active_pane()
2903                .read(cx)
2904                .active_item()
2905                .and_then(|item| item.downcast::<ProjectSearchView>())
2906        }) else {
2907            panic!("Search view expected to appear after new search event trigger")
2908        };
2909
2910        cx.spawn(|mut cx| async move {
2911            window
2912                .update(&mut cx, |_, window, cx| {
2913                    window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2914                })
2915                .unwrap();
2916        })
2917        .detach();
2918        cx.background_executor.run_until_parked();
2919
2920        window.update(cx, |_, window, cx| {
2921            search_view.update(cx, |search_view, cx| {
2922                    assert!(
2923                        search_view.query_editor.focus_handle(cx).is_focused(window),
2924                        "Empty search view should be focused after the toggle focus event: no results panel to focus on",
2925                    );
2926                });
2927        }).unwrap();
2928
2929        window
2930            .update(cx, |_, window, cx| {
2931                search_view.update(cx, |search_view, cx| {
2932                    let query_editor = &search_view.query_editor;
2933                    assert!(
2934                        query_editor.focus_handle(cx).is_focused(window),
2935                        "Search view should be focused after the new search view is activated",
2936                    );
2937                    let query_text = query_editor.read(cx).text(cx);
2938                    assert!(
2939                        query_text.is_empty(),
2940                        "New search query should be empty but got '{query_text}'",
2941                    );
2942                    let results_text = search_view
2943                        .results_editor
2944                        .update(cx, |editor, cx| editor.display_text(cx));
2945                    assert!(
2946                        results_text.is_empty(),
2947                        "Empty search view should have no results but got '{results_text}'"
2948                    );
2949                });
2950            })
2951            .unwrap();
2952
2953        window
2954            .update(cx, |_, window, cx| {
2955                search_view.update(cx, |search_view, cx| {
2956                    search_view.query_editor.update(cx, |query_editor, cx| {
2957                        query_editor.set_text("sOMETHINGtHATsURELYdOESnOTeXIST", window, cx)
2958                    });
2959                    search_view.search(cx);
2960                });
2961            })
2962            .unwrap();
2963
2964        cx.background_executor.run_until_parked();
2965        window
2966            .update(cx, |_, window, cx| {
2967                search_view.update(cx, |search_view, cx| {
2968                    let results_text = search_view
2969                        .results_editor
2970                        .update(cx, |editor, cx| editor.display_text(cx));
2971                    assert!(
2972                results_text.is_empty(),
2973                "Search view for mismatching query should have no results but got '{results_text}'"
2974            );
2975                    assert!(
2976                search_view.query_editor.focus_handle(cx).is_focused(window),
2977                "Search view should be focused after mismatching query had been used in search",
2978            );
2979                });
2980            })
2981            .unwrap();
2982        cx.spawn(|mut cx| async move {
2983            window.update(&mut cx, |_, window, cx| {
2984                window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2985            })
2986        })
2987        .detach();
2988        cx.background_executor.run_until_parked();
2989        window.update(cx, |_, window, cx| {
2990            search_view.update(cx, |search_view, cx| {
2991                    assert!(
2992                        search_view.query_editor.focus_handle(cx).is_focused(window),
2993                        "Search view with mismatching query should be focused after the toggle focus event: still no results panel to focus on",
2994                    );
2995                });
2996        }).unwrap();
2997
2998        window
2999            .update(cx, |_, window, cx| {
3000                search_view.update(cx, |search_view, cx| {
3001                    search_view.query_editor.update(cx, |query_editor, cx| {
3002                        query_editor.set_text("TWO", window, cx)
3003                    });
3004                    search_view.search(cx);
3005                })
3006            })
3007            .unwrap();
3008        cx.background_executor.run_until_parked();
3009        window.update(cx, |_, window, cx|
3010        search_view.update(cx, |search_view, cx| {
3011                assert_eq!(
3012                    search_view
3013                        .results_editor
3014                        .update(cx, |editor, cx| editor.display_text(cx)),
3015                    "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
3016                    "Search view results should match the query"
3017                );
3018                assert!(
3019                    search_view.results_editor.focus_handle(cx).is_focused(window),
3020                    "Search view with mismatching query should be focused after search results are available",
3021                );
3022            })).unwrap();
3023        cx.spawn(|mut cx| async move {
3024            window
3025                .update(&mut cx, |_, window, cx| {
3026                    window.dispatch_action(ToggleFocus.boxed_clone(), cx)
3027                })
3028                .unwrap();
3029        })
3030        .detach();
3031        cx.background_executor.run_until_parked();
3032        window.update(cx, |_, window, cx| {
3033            search_view.update(cx, |search_view, cx| {
3034                    assert!(
3035                        search_view.results_editor.focus_handle(cx).is_focused(window),
3036                        "Search view with matching query should still have its results editor focused after the toggle focus event",
3037                    );
3038                });
3039        }).unwrap();
3040
3041        workspace
3042            .update(cx, |workspace, window, cx| {
3043                ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3044            })
3045            .unwrap();
3046        cx.background_executor.run_until_parked();
3047        let Some(search_view_2) = cx.read(|cx| {
3048            workspace
3049                .read(cx)
3050                .unwrap()
3051                .active_pane()
3052                .read(cx)
3053                .active_item()
3054                .and_then(|item| item.downcast::<ProjectSearchView>())
3055        }) else {
3056            panic!("Search view expected to appear after new search event trigger")
3057        };
3058        assert!(
3059            search_view_2 != search_view,
3060            "New search view should be open after `workspace::NewSearch` event"
3061        );
3062
3063        window.update(cx, |_, window, cx| {
3064            search_view.update(cx, |search_view, cx| {
3065                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO", "First search view should not have an updated query");
3066                    assert_eq!(
3067                        search_view
3068                            .results_editor
3069                            .update(cx, |editor, cx| editor.display_text(cx)),
3070                        "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
3071                        "Results of the first search view should not update too"
3072                    );
3073                    assert!(
3074                        !search_view.query_editor.focus_handle(cx).is_focused(window),
3075                        "Focus should be moved away from the first search view"
3076                    );
3077                });
3078        }).unwrap();
3079
3080        window.update(cx, |_, window, cx| {
3081            search_view_2.update(cx, |search_view_2, cx| {
3082                    assert_eq!(
3083                        search_view_2.query_editor.read(cx).text(cx),
3084                        "two",
3085                        "New search view should get the query from the text cursor was at during the event spawn (first search view's first result)"
3086                    );
3087                    assert_eq!(
3088                        search_view_2
3089                            .results_editor
3090                            .update(cx, |editor, cx| editor.display_text(cx)),
3091                        "",
3092                        "No search results should be in the 2nd view yet, as we did not spawn a search for it"
3093                    );
3094                    assert!(
3095                        search_view_2.query_editor.focus_handle(cx).is_focused(window),
3096                        "Focus should be moved into query editor of the new window"
3097                    );
3098                });
3099        }).unwrap();
3100
3101        window
3102            .update(cx, |_, window, cx| {
3103                search_view_2.update(cx, |search_view_2, cx| {
3104                    search_view_2.query_editor.update(cx, |query_editor, cx| {
3105                        query_editor.set_text("FOUR", window, cx)
3106                    });
3107                    search_view_2.search(cx);
3108                });
3109            })
3110            .unwrap();
3111
3112        cx.background_executor.run_until_parked();
3113        window.update(cx, |_, window, cx| {
3114            search_view_2.update(cx, |search_view_2, cx| {
3115                    assert_eq!(
3116                        search_view_2
3117                            .results_editor
3118                            .update(cx, |editor, cx| editor.display_text(cx)),
3119                        "\n\nconst FOUR: usize = one::ONE + three::THREE;",
3120                        "New search view with the updated query should have new search results"
3121                    );
3122                    assert!(
3123                        search_view_2.results_editor.focus_handle(cx).is_focused(window),
3124                        "Search view with mismatching query should be focused after search results are available",
3125                    );
3126                });
3127        }).unwrap();
3128
3129        cx.spawn(|mut cx| async move {
3130            window
3131                .update(&mut cx, |_, window, cx| {
3132                    window.dispatch_action(ToggleFocus.boxed_clone(), cx)
3133                })
3134                .unwrap();
3135        })
3136        .detach();
3137        cx.background_executor.run_until_parked();
3138        window.update(cx, |_, window, cx| {
3139            search_view_2.update(cx, |search_view_2, cx| {
3140                    assert!(
3141                        search_view_2.results_editor.focus_handle(cx).is_focused(window),
3142                        "Search view with matching query should switch focus to the results editor after the toggle focus event",
3143                    );
3144                });}).unwrap();
3145    }
3146
3147    #[gpui::test]
3148    async fn test_new_project_search_in_directory(cx: &mut TestAppContext) {
3149        init_test(cx);
3150
3151        let fs = FakeFs::new(cx.background_executor.clone());
3152        fs.insert_tree(
3153            path!("/dir"),
3154            json!({
3155                "a": {
3156                    "one.rs": "const ONE: usize = 1;",
3157                    "two.rs": "const TWO: usize = one::ONE + one::ONE;",
3158                },
3159                "b": {
3160                    "three.rs": "const THREE: usize = one::ONE + two::TWO;",
3161                    "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
3162                },
3163            }),
3164        )
3165        .await;
3166        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
3167        let worktree_id = project.read_with(cx, |project, cx| {
3168            project.worktrees(cx).next().unwrap().read(cx).id()
3169        });
3170        let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
3171        let workspace = window.root(cx).unwrap();
3172        let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
3173
3174        let active_item = cx.read(|cx| {
3175            workspace
3176                .read(cx)
3177                .active_pane()
3178                .read(cx)
3179                .active_item()
3180                .and_then(|item| item.downcast::<ProjectSearchView>())
3181        });
3182        assert!(
3183            active_item.is_none(),
3184            "Expected no search panel to be active"
3185        );
3186
3187        window
3188            .update(cx, move |workspace, window, cx| {
3189                assert_eq!(workspace.panes().len(), 1);
3190                workspace.panes()[0].update(cx, move |pane, cx| {
3191                    pane.toolbar()
3192                        .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3193                });
3194            })
3195            .unwrap();
3196
3197        let a_dir_entry = cx.update(|cx| {
3198            workspace
3199                .read(cx)
3200                .project()
3201                .read(cx)
3202                .entry_for_path(&(worktree_id, "a").into(), cx)
3203                .expect("no entry for /a/ directory")
3204        });
3205        assert!(a_dir_entry.is_dir());
3206        window
3207            .update(cx, |workspace, window, cx| {
3208                ProjectSearchView::new_search_in_directory(workspace, &a_dir_entry.path, window, cx)
3209            })
3210            .unwrap();
3211
3212        let Some(search_view) = cx.read(|cx| {
3213            workspace
3214                .read(cx)
3215                .active_pane()
3216                .read(cx)
3217                .active_item()
3218                .and_then(|item| item.downcast::<ProjectSearchView>())
3219        }) else {
3220            panic!("Search view expected to appear after new search in directory event trigger")
3221        };
3222        cx.background_executor.run_until_parked();
3223        window
3224            .update(cx, |_, window, cx| {
3225                search_view.update(cx, |search_view, cx| {
3226                    assert!(
3227                        search_view.query_editor.focus_handle(cx).is_focused(window),
3228                        "On new search in directory, focus should be moved into query editor"
3229                    );
3230                    search_view.excluded_files_editor.update(cx, |editor, cx| {
3231                        assert!(
3232                            editor.display_text(cx).is_empty(),
3233                            "New search in directory should not have any excluded files"
3234                        );
3235                    });
3236                    search_view.included_files_editor.update(cx, |editor, cx| {
3237                        assert_eq!(
3238                            editor.display_text(cx),
3239                            a_dir_entry.path.to_str().unwrap(),
3240                            "New search in directory should have included dir entry path"
3241                        );
3242                    });
3243                });
3244            })
3245            .unwrap();
3246        window
3247            .update(cx, |_, window, cx| {
3248                search_view.update(cx, |search_view, cx| {
3249                    search_view.query_editor.update(cx, |query_editor, cx| {
3250                        query_editor.set_text("const", window, cx)
3251                    });
3252                    search_view.search(cx);
3253                });
3254            })
3255            .unwrap();
3256        cx.background_executor.run_until_parked();
3257        window
3258            .update(cx, |_, _, cx| {
3259                search_view.update(cx, |search_view, cx| {
3260                    assert_eq!(
3261                search_view
3262                    .results_editor
3263                    .update(cx, |editor, cx| editor.display_text(cx)),
3264                "\n\nconst ONE: usize = 1;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
3265                "New search in directory should have a filter that matches a certain directory"
3266            );
3267                })
3268            })
3269            .unwrap();
3270    }
3271
3272    #[gpui::test]
3273    async fn test_search_query_history(cx: &mut TestAppContext) {
3274        init_test(cx);
3275
3276        let fs = FakeFs::new(cx.background_executor.clone());
3277        fs.insert_tree(
3278            path!("/dir"),
3279            json!({
3280                "one.rs": "const ONE: usize = 1;",
3281                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
3282                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
3283                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
3284            }),
3285        )
3286        .await;
3287        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
3288        let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
3289        let workspace = window.root(cx).unwrap();
3290        let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
3291
3292        window
3293            .update(cx, {
3294                let search_bar = search_bar.clone();
3295                |workspace, window, cx| {
3296                    assert_eq!(workspace.panes().len(), 1);
3297                    workspace.panes()[0].update(cx, |pane, cx| {
3298                        pane.toolbar()
3299                            .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3300                    });
3301
3302                    ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3303                }
3304            })
3305            .unwrap();
3306
3307        let search_view = cx.read(|cx| {
3308            workspace
3309                .read(cx)
3310                .active_pane()
3311                .read(cx)
3312                .active_item()
3313                .and_then(|item| item.downcast::<ProjectSearchView>())
3314                .expect("Search view expected to appear after new search event trigger")
3315        });
3316
3317        // Add 3 search items into the history + another unsubmitted one.
3318        window
3319            .update(cx, |_, window, cx| {
3320                search_view.update(cx, |search_view, cx| {
3321                    search_view.search_options = SearchOptions::CASE_SENSITIVE;
3322                    search_view.query_editor.update(cx, |query_editor, cx| {
3323                        query_editor.set_text("ONE", window, cx)
3324                    });
3325                    search_view.search(cx);
3326                });
3327            })
3328            .unwrap();
3329
3330        cx.background_executor.run_until_parked();
3331        window
3332            .update(cx, |_, window, cx| {
3333                search_view.update(cx, |search_view, cx| {
3334                    search_view.query_editor.update(cx, |query_editor, cx| {
3335                        query_editor.set_text("TWO", window, cx)
3336                    });
3337                    search_view.search(cx);
3338                });
3339            })
3340            .unwrap();
3341        cx.background_executor.run_until_parked();
3342        window
3343            .update(cx, |_, window, cx| {
3344                search_view.update(cx, |search_view, cx| {
3345                    search_view.query_editor.update(cx, |query_editor, cx| {
3346                        query_editor.set_text("THREE", window, cx)
3347                    });
3348                    search_view.search(cx);
3349                })
3350            })
3351            .unwrap();
3352        cx.background_executor.run_until_parked();
3353        window
3354            .update(cx, |_, window, cx| {
3355                search_view.update(cx, |search_view, cx| {
3356                    search_view.query_editor.update(cx, |query_editor, cx| {
3357                        query_editor.set_text("JUST_TEXT_INPUT", window, cx)
3358                    });
3359                })
3360            })
3361            .unwrap();
3362        cx.background_executor.run_until_parked();
3363
3364        // Ensure that the latest input with search settings is active.
3365        window
3366            .update(cx, |_, _, cx| {
3367                search_view.update(cx, |search_view, cx| {
3368                    assert_eq!(
3369                        search_view.query_editor.read(cx).text(cx),
3370                        "JUST_TEXT_INPUT"
3371                    );
3372                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3373                });
3374            })
3375            .unwrap();
3376
3377        // Next history query after the latest should set the query to the empty string.
3378        window
3379            .update(cx, |_, window, cx| {
3380                search_bar.update(cx, |search_bar, cx| {
3381                    search_bar.focus_search(window, cx);
3382                    search_bar.next_history_query(&NextHistoryQuery, window, cx);
3383                })
3384            })
3385            .unwrap();
3386        window
3387            .update(cx, |_, _, cx| {
3388                search_view.update(cx, |search_view, cx| {
3389                    assert_eq!(search_view.query_editor.read(cx).text(cx), "");
3390                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3391                });
3392            })
3393            .unwrap();
3394        window
3395            .update(cx, |_, window, cx| {
3396                search_bar.update(cx, |search_bar, cx| {
3397                    search_bar.focus_search(window, cx);
3398                    search_bar.next_history_query(&NextHistoryQuery, window, cx);
3399                })
3400            })
3401            .unwrap();
3402        window
3403            .update(cx, |_, _, cx| {
3404                search_view.update(cx, |search_view, cx| {
3405                    assert_eq!(search_view.query_editor.read(cx).text(cx), "");
3406                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3407                });
3408            })
3409            .unwrap();
3410
3411        // First previous query for empty current query should set the query to the latest submitted one.
3412        window
3413            .update(cx, |_, window, cx| {
3414                search_bar.update(cx, |search_bar, cx| {
3415                    search_bar.focus_search(window, cx);
3416                    search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3417                });
3418            })
3419            .unwrap();
3420        window
3421            .update(cx, |_, _, cx| {
3422                search_view.update(cx, |search_view, cx| {
3423                    assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
3424                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3425                });
3426            })
3427            .unwrap();
3428
3429        // Further previous items should go over the history in reverse order.
3430        window
3431            .update(cx, |_, window, cx| {
3432                search_bar.update(cx, |search_bar, cx| {
3433                    search_bar.focus_search(window, cx);
3434                    search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3435                });
3436            })
3437            .unwrap();
3438        window
3439            .update(cx, |_, _, cx| {
3440                search_view.update(cx, |search_view, cx| {
3441                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
3442                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3443                });
3444            })
3445            .unwrap();
3446
3447        // Previous items should never go behind the first history item.
3448        window
3449            .update(cx, |_, window, cx| {
3450                search_bar.update(cx, |search_bar, cx| {
3451                    search_bar.focus_search(window, cx);
3452                    search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3453                });
3454            })
3455            .unwrap();
3456        window
3457            .update(cx, |_, _, cx| {
3458                search_view.update(cx, |search_view, cx| {
3459                    assert_eq!(search_view.query_editor.read(cx).text(cx), "ONE");
3460                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3461                });
3462            })
3463            .unwrap();
3464        window
3465            .update(cx, |_, window, cx| {
3466                search_bar.update(cx, |search_bar, cx| {
3467                    search_bar.focus_search(window, cx);
3468                    search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3469                });
3470            })
3471            .unwrap();
3472        window
3473            .update(cx, |_, _, cx| {
3474                search_view.update(cx, |search_view, cx| {
3475                    assert_eq!(search_view.query_editor.read(cx).text(cx), "ONE");
3476                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3477                });
3478            })
3479            .unwrap();
3480
3481        // Next items should go over the history in the original order.
3482        window
3483            .update(cx, |_, window, cx| {
3484                search_bar.update(cx, |search_bar, cx| {
3485                    search_bar.focus_search(window, cx);
3486                    search_bar.next_history_query(&NextHistoryQuery, window, cx);
3487                });
3488            })
3489            .unwrap();
3490        window
3491            .update(cx, |_, _, cx| {
3492                search_view.update(cx, |search_view, cx| {
3493                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
3494                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3495                });
3496            })
3497            .unwrap();
3498
3499        window
3500            .update(cx, |_, window, cx| {
3501                search_view.update(cx, |search_view, cx| {
3502                    search_view.query_editor.update(cx, |query_editor, cx| {
3503                        query_editor.set_text("TWO_NEW", window, cx)
3504                    });
3505                    search_view.search(cx);
3506                });
3507            })
3508            .unwrap();
3509        cx.background_executor.run_until_parked();
3510        window
3511            .update(cx, |_, _, cx| {
3512                search_view.update(cx, |search_view, cx| {
3513                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO_NEW");
3514                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3515                });
3516            })
3517            .unwrap();
3518
3519        // New search input should add another entry to history and move the selection to the end of the history.
3520        window
3521            .update(cx, |_, window, cx| {
3522                search_bar.update(cx, |search_bar, cx| {
3523                    search_bar.focus_search(window, cx);
3524                    search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3525                });
3526            })
3527            .unwrap();
3528        window
3529            .update(cx, |_, _, cx| {
3530                search_view.update(cx, |search_view, cx| {
3531                    assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
3532                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3533                });
3534            })
3535            .unwrap();
3536        window
3537            .update(cx, |_, window, cx| {
3538                search_bar.update(cx, |search_bar, cx| {
3539                    search_bar.focus_search(window, cx);
3540                    search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3541                });
3542            })
3543            .unwrap();
3544        window
3545            .update(cx, |_, _, cx| {
3546                search_view.update(cx, |search_view, cx| {
3547                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
3548                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3549                });
3550            })
3551            .unwrap();
3552        window
3553            .update(cx, |_, window, cx| {
3554                search_bar.update(cx, |search_bar, cx| {
3555                    search_bar.focus_search(window, cx);
3556                    search_bar.next_history_query(&NextHistoryQuery, window, cx);
3557                });
3558            })
3559            .unwrap();
3560        window
3561            .update(cx, |_, _, cx| {
3562                search_view.update(cx, |search_view, cx| {
3563                    assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
3564                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3565                });
3566            })
3567            .unwrap();
3568        window
3569            .update(cx, |_, window, cx| {
3570                search_bar.update(cx, |search_bar, cx| {
3571                    search_bar.focus_search(window, cx);
3572                    search_bar.next_history_query(&NextHistoryQuery, window, cx);
3573                });
3574            })
3575            .unwrap();
3576        window
3577            .update(cx, |_, _, cx| {
3578                search_view.update(cx, |search_view, cx| {
3579                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO_NEW");
3580                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3581                });
3582            })
3583            .unwrap();
3584        window
3585            .update(cx, |_, window, cx| {
3586                search_bar.update(cx, |search_bar, cx| {
3587                    search_bar.focus_search(window, cx);
3588                    search_bar.next_history_query(&NextHistoryQuery, window, cx);
3589                });
3590            })
3591            .unwrap();
3592        window
3593            .update(cx, |_, _, cx| {
3594                search_view.update(cx, |search_view, cx| {
3595                    assert_eq!(search_view.query_editor.read(cx).text(cx), "");
3596                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3597                });
3598            })
3599            .unwrap();
3600    }
3601
3602    #[gpui::test]
3603    async fn test_search_query_history_with_multiple_views(cx: &mut TestAppContext) {
3604        init_test(cx);
3605
3606        let fs = FakeFs::new(cx.background_executor.clone());
3607        fs.insert_tree(
3608            path!("/dir"),
3609            json!({
3610                "one.rs": "const ONE: usize = 1;",
3611            }),
3612        )
3613        .await;
3614        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
3615        let worktree_id = project.update(cx, |this, cx| {
3616            this.worktrees(cx).next().unwrap().read(cx).id()
3617        });
3618
3619        let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
3620        let workspace = window.root(cx).unwrap();
3621
3622        let panes: Vec<_> = window
3623            .update(cx, |this, _, _| this.panes().to_owned())
3624            .unwrap();
3625
3626        let search_bar_1 = window.build_entity(cx, |_, _| ProjectSearchBar::new());
3627        let search_bar_2 = window.build_entity(cx, |_, _| ProjectSearchBar::new());
3628
3629        assert_eq!(panes.len(), 1);
3630        let first_pane = panes.first().cloned().unwrap();
3631        assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 0);
3632        window
3633            .update(cx, |workspace, window, cx| {
3634                workspace.open_path(
3635                    (worktree_id, "one.rs"),
3636                    Some(first_pane.downgrade()),
3637                    true,
3638                    window,
3639                    cx,
3640                )
3641            })
3642            .unwrap()
3643            .await
3644            .unwrap();
3645        assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 1);
3646
3647        // Add a project search item to the first pane
3648        window
3649            .update(cx, {
3650                let search_bar = search_bar_1.clone();
3651                |workspace, window, cx| {
3652                    first_pane.update(cx, |pane, cx| {
3653                        pane.toolbar()
3654                            .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3655                    });
3656
3657                    ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3658                }
3659            })
3660            .unwrap();
3661        let search_view_1 = cx.read(|cx| {
3662            workspace
3663                .read(cx)
3664                .active_item(cx)
3665                .and_then(|item| item.downcast::<ProjectSearchView>())
3666                .expect("Search view expected to appear after new search event trigger")
3667        });
3668
3669        let second_pane = window
3670            .update(cx, |workspace, window, cx| {
3671                workspace.split_and_clone(
3672                    first_pane.clone(),
3673                    workspace::SplitDirection::Right,
3674                    window,
3675                    cx,
3676                )
3677            })
3678            .unwrap()
3679            .unwrap();
3680        assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 1);
3681
3682        assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 1);
3683        assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 2);
3684
3685        // Add a project search item to the second pane
3686        window
3687            .update(cx, {
3688                let search_bar = search_bar_2.clone();
3689                let pane = second_pane.clone();
3690                move |workspace, window, cx| {
3691                    assert_eq!(workspace.panes().len(), 2);
3692                    pane.update(cx, |pane, cx| {
3693                        pane.toolbar()
3694                            .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3695                    });
3696
3697                    ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3698                }
3699            })
3700            .unwrap();
3701
3702        let search_view_2 = cx.read(|cx| {
3703            workspace
3704                .read(cx)
3705                .active_item(cx)
3706                .and_then(|item| item.downcast::<ProjectSearchView>())
3707                .expect("Search view expected to appear after new search event trigger")
3708        });
3709
3710        cx.run_until_parked();
3711        assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 2);
3712        assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 2);
3713
3714        let update_search_view =
3715            |search_view: &Entity<ProjectSearchView>, query: &str, cx: &mut TestAppContext| {
3716                window
3717                    .update(cx, |_, window, cx| {
3718                        search_view.update(cx, |search_view, cx| {
3719                            search_view.query_editor.update(cx, |query_editor, cx| {
3720                                query_editor.set_text(query, window, cx)
3721                            });
3722                            search_view.search(cx);
3723                        });
3724                    })
3725                    .unwrap();
3726            };
3727
3728        let active_query =
3729            |search_view: &Entity<ProjectSearchView>, cx: &mut TestAppContext| -> String {
3730                window
3731                    .update(cx, |_, _, cx| {
3732                        search_view.update(cx, |search_view, cx| {
3733                            search_view.query_editor.read(cx).text(cx)
3734                        })
3735                    })
3736                    .unwrap()
3737            };
3738
3739        let select_prev_history_item =
3740            |search_bar: &Entity<ProjectSearchBar>, cx: &mut TestAppContext| {
3741                window
3742                    .update(cx, |_, window, cx| {
3743                        search_bar.update(cx, |search_bar, cx| {
3744                            search_bar.focus_search(window, cx);
3745                            search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3746                        })
3747                    })
3748                    .unwrap();
3749            };
3750
3751        let select_next_history_item =
3752            |search_bar: &Entity<ProjectSearchBar>, cx: &mut TestAppContext| {
3753                window
3754                    .update(cx, |_, window, cx| {
3755                        search_bar.update(cx, |search_bar, cx| {
3756                            search_bar.focus_search(window, cx);
3757                            search_bar.next_history_query(&NextHistoryQuery, window, cx);
3758                        })
3759                    })
3760                    .unwrap();
3761            };
3762
3763        update_search_view(&search_view_1, "ONE", cx);
3764        cx.background_executor.run_until_parked();
3765
3766        update_search_view(&search_view_2, "TWO", cx);
3767        cx.background_executor.run_until_parked();
3768
3769        assert_eq!(active_query(&search_view_1, cx), "ONE");
3770        assert_eq!(active_query(&search_view_2, cx), "TWO");
3771
3772        // Selecting previous history item should select the query from search view 1.
3773        select_prev_history_item(&search_bar_2, cx);
3774        assert_eq!(active_query(&search_view_2, cx), "ONE");
3775
3776        // Selecting the previous history item should not change the query as it is already the first item.
3777        select_prev_history_item(&search_bar_2, cx);
3778        assert_eq!(active_query(&search_view_2, cx), "ONE");
3779
3780        // Changing the query in search view 2 should not affect the history of search view 1.
3781        assert_eq!(active_query(&search_view_1, cx), "ONE");
3782
3783        // Deploying a new search in search view 2
3784        update_search_view(&search_view_2, "THREE", cx);
3785        cx.background_executor.run_until_parked();
3786
3787        select_next_history_item(&search_bar_2, cx);
3788        assert_eq!(active_query(&search_view_2, cx), "");
3789
3790        select_prev_history_item(&search_bar_2, cx);
3791        assert_eq!(active_query(&search_view_2, cx), "THREE");
3792
3793        select_prev_history_item(&search_bar_2, cx);
3794        assert_eq!(active_query(&search_view_2, cx), "TWO");
3795
3796        select_prev_history_item(&search_bar_2, cx);
3797        assert_eq!(active_query(&search_view_2, cx), "ONE");
3798
3799        select_prev_history_item(&search_bar_2, cx);
3800        assert_eq!(active_query(&search_view_2, cx), "ONE");
3801
3802        // Search view 1 should now see the query from search view 2.
3803        assert_eq!(active_query(&search_view_1, cx), "ONE");
3804
3805        select_next_history_item(&search_bar_2, cx);
3806        assert_eq!(active_query(&search_view_2, cx), "TWO");
3807
3808        // Here is the new query from search view 2
3809        select_next_history_item(&search_bar_2, cx);
3810        assert_eq!(active_query(&search_view_2, cx), "THREE");
3811
3812        select_next_history_item(&search_bar_2, cx);
3813        assert_eq!(active_query(&search_view_2, cx), "");
3814
3815        select_next_history_item(&search_bar_1, cx);
3816        assert_eq!(active_query(&search_view_1, cx), "TWO");
3817
3818        select_next_history_item(&search_bar_1, cx);
3819        assert_eq!(active_query(&search_view_1, cx), "THREE");
3820
3821        select_next_history_item(&search_bar_1, cx);
3822        assert_eq!(active_query(&search_view_1, cx), "");
3823    }
3824
3825    #[gpui::test]
3826    async fn test_deploy_search_with_multiple_panes(cx: &mut TestAppContext) {
3827        init_test(cx);
3828
3829        // Setup 2 panes, both with a file open and one with a project search.
3830        let fs = FakeFs::new(cx.background_executor.clone());
3831        fs.insert_tree(
3832            path!("/dir"),
3833            json!({
3834                "one.rs": "const ONE: usize = 1;",
3835            }),
3836        )
3837        .await;
3838        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
3839        let worktree_id = project.update(cx, |this, cx| {
3840            this.worktrees(cx).next().unwrap().read(cx).id()
3841        });
3842        let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
3843        let panes: Vec<_> = window
3844            .update(cx, |this, _, _| this.panes().to_owned())
3845            .unwrap();
3846        assert_eq!(panes.len(), 1);
3847        let first_pane = panes.first().cloned().unwrap();
3848        assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 0);
3849        window
3850            .update(cx, |workspace, window, cx| {
3851                workspace.open_path(
3852                    (worktree_id, "one.rs"),
3853                    Some(first_pane.downgrade()),
3854                    true,
3855                    window,
3856                    cx,
3857                )
3858            })
3859            .unwrap()
3860            .await
3861            .unwrap();
3862        assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 1);
3863        let second_pane = window
3864            .update(cx, |workspace, window, cx| {
3865                workspace.split_and_clone(
3866                    first_pane.clone(),
3867                    workspace::SplitDirection::Right,
3868                    window,
3869                    cx,
3870                )
3871            })
3872            .unwrap()
3873            .unwrap();
3874        assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 1);
3875        assert!(
3876            window
3877                .update(cx, |_, window, cx| second_pane
3878                    .focus_handle(cx)
3879                    .contains_focused(window, cx))
3880                .unwrap()
3881        );
3882        let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
3883        window
3884            .update(cx, {
3885                let search_bar = search_bar.clone();
3886                let pane = first_pane.clone();
3887                move |workspace, window, cx| {
3888                    assert_eq!(workspace.panes().len(), 2);
3889                    pane.update(cx, move |pane, cx| {
3890                        pane.toolbar()
3891                            .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3892                    });
3893                }
3894            })
3895            .unwrap();
3896
3897        // Add a project search item to the second pane
3898        window
3899            .update(cx, {
3900                |workspace, window, cx| {
3901                    assert_eq!(workspace.panes().len(), 2);
3902                    second_pane.update(cx, |pane, cx| {
3903                        pane.toolbar()
3904                            .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3905                    });
3906
3907                    ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3908                }
3909            })
3910            .unwrap();
3911
3912        cx.run_until_parked();
3913        assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 2);
3914        assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 1);
3915
3916        // Focus the first pane
3917        window
3918            .update(cx, |workspace, window, cx| {
3919                assert_eq!(workspace.active_pane(), &second_pane);
3920                second_pane.update(cx, |this, cx| {
3921                    assert_eq!(this.active_item_index(), 1);
3922                    this.activate_previous_item(&Default::default(), window, cx);
3923                    assert_eq!(this.active_item_index(), 0);
3924                });
3925                workspace.activate_pane_in_direction(workspace::SplitDirection::Left, window, cx);
3926            })
3927            .unwrap();
3928        window
3929            .update(cx, |workspace, _, cx| {
3930                assert_eq!(workspace.active_pane(), &first_pane);
3931                assert_eq!(first_pane.read(cx).items_len(), 1);
3932                assert_eq!(second_pane.read(cx).items_len(), 2);
3933            })
3934            .unwrap();
3935
3936        // Deploy a new search
3937        cx.dispatch_action(window.into(), DeploySearch::find());
3938
3939        // Both panes should now have a project search in them
3940        window
3941            .update(cx, |workspace, window, cx| {
3942                assert_eq!(workspace.active_pane(), &first_pane);
3943                first_pane.read_with(cx, |this, _| {
3944                    assert_eq!(this.active_item_index(), 1);
3945                    assert_eq!(this.items_len(), 2);
3946                });
3947                second_pane.update(cx, |this, cx| {
3948                    assert!(!cx.focus_handle().contains_focused(window, cx));
3949                    assert_eq!(this.items_len(), 2);
3950                });
3951            })
3952            .unwrap();
3953
3954        // Focus the second pane's non-search item
3955        window
3956            .update(cx, |_workspace, window, cx| {
3957                second_pane.update(cx, |pane, cx| {
3958                    pane.activate_next_item(&Default::default(), window, cx)
3959                });
3960            })
3961            .unwrap();
3962
3963        // Deploy a new search
3964        cx.dispatch_action(window.into(), DeploySearch::find());
3965
3966        // The project search view should now be focused in the second pane
3967        // And the number of items should be unchanged.
3968        window
3969            .update(cx, |_workspace, _, cx| {
3970                second_pane.update(cx, |pane, _cx| {
3971                    assert!(
3972                        pane.active_item()
3973                            .unwrap()
3974                            .downcast::<ProjectSearchView>()
3975                            .is_some()
3976                    );
3977
3978                    assert_eq!(pane.items_len(), 2);
3979                });
3980            })
3981            .unwrap();
3982    }
3983
3984    #[gpui::test]
3985    async fn test_scroll_search_results_to_top(cx: &mut TestAppContext) {
3986        init_test(cx);
3987
3988        // We need many lines in the search results to be able to scroll the window
3989        let fs = FakeFs::new(cx.background_executor.clone());
3990        fs.insert_tree(
3991            path!("/dir"),
3992            json!({
3993                "1.txt": "\n\n\n\n\n A \n\n\n\n\n",
3994                "2.txt": "\n\n\n\n\n A \n\n\n\n\n",
3995                "3.rs": "\n\n\n\n\n A \n\n\n\n\n",
3996                "4.rs": "\n\n\n\n\n A \n\n\n\n\n",
3997                "5.rs": "\n\n\n\n\n A \n\n\n\n\n",
3998                "6.rs": "\n\n\n\n\n A \n\n\n\n\n",
3999                "7.rs": "\n\n\n\n\n A \n\n\n\n\n",
4000                "8.rs": "\n\n\n\n\n A \n\n\n\n\n",
4001                "9.rs": "\n\n\n\n\n A \n\n\n\n\n",
4002                "a.rs": "\n\n\n\n\n A \n\n\n\n\n",
4003                "b.rs": "\n\n\n\n\n B \n\n\n\n\n",
4004                "c.rs": "\n\n\n\n\n B \n\n\n\n\n",
4005                "d.rs": "\n\n\n\n\n B \n\n\n\n\n",
4006                "e.rs": "\n\n\n\n\n B \n\n\n\n\n",
4007                "f.rs": "\n\n\n\n\n B \n\n\n\n\n",
4008                "g.rs": "\n\n\n\n\n B \n\n\n\n\n",
4009                "h.rs": "\n\n\n\n\n B \n\n\n\n\n",
4010                "i.rs": "\n\n\n\n\n B \n\n\n\n\n",
4011                "j.rs": "\n\n\n\n\n B \n\n\n\n\n",
4012                "k.rs": "\n\n\n\n\n B \n\n\n\n\n",
4013            }),
4014        )
4015        .await;
4016        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
4017        let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
4018        let workspace = window.root(cx).unwrap();
4019        let search = cx.new(|cx| ProjectSearch::new(project, cx));
4020        let search_view = cx.add_window(|window, cx| {
4021            ProjectSearchView::new(workspace.downgrade(), search.clone(), window, cx, None)
4022        });
4023
4024        // First search
4025        perform_search(search_view, "A", cx);
4026        search_view
4027            .update(cx, |search_view, window, cx| {
4028                search_view.results_editor.update(cx, |results_editor, cx| {
4029                    // Results are correct and scrolled to the top
4030                    assert_eq!(
4031                        results_editor.display_text(cx).match_indices(" A ").count(),
4032                        10
4033                    );
4034                    assert_eq!(results_editor.scroll_position(cx), Point::default());
4035
4036                    // Scroll results all the way down
4037                    results_editor.scroll(
4038                        Point::new(0., f32::MAX),
4039                        Some(Axis::Vertical),
4040                        window,
4041                        cx,
4042                    );
4043                });
4044            })
4045            .expect("unable to update search view");
4046
4047        // Second search
4048        perform_search(search_view, "B", cx);
4049        search_view
4050            .update(cx, |search_view, _, cx| {
4051                search_view.results_editor.update(cx, |results_editor, cx| {
4052                    // Results are correct...
4053                    assert_eq!(
4054                        results_editor.display_text(cx).match_indices(" B ").count(),
4055                        10
4056                    );
4057                    // ...and scrolled back to the top
4058                    assert_eq!(results_editor.scroll_position(cx), Point::default());
4059                });
4060            })
4061            .expect("unable to update search view");
4062    }
4063
4064    #[gpui::test]
4065    async fn test_buffer_search_query_reused(cx: &mut TestAppContext) {
4066        init_test(cx);
4067
4068        let fs = FakeFs::new(cx.background_executor.clone());
4069        fs.insert_tree(
4070            path!("/dir"),
4071            json!({
4072                "one.rs": "const ONE: usize = 1;",
4073            }),
4074        )
4075        .await;
4076        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
4077        let worktree_id = project.update(cx, |this, cx| {
4078            this.worktrees(cx).next().unwrap().read(cx).id()
4079        });
4080        let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
4081        let workspace = window.root(cx).unwrap();
4082        let mut cx = VisualTestContext::from_window(*window.deref(), cx);
4083
4084        let editor = workspace
4085            .update_in(&mut cx, |workspace, window, cx| {
4086                workspace.open_path((worktree_id, "one.rs"), None, true, window, cx)
4087            })
4088            .await
4089            .unwrap()
4090            .downcast::<Editor>()
4091            .unwrap();
4092
4093        // Wait for the unstaged changes to be loaded
4094        cx.run_until_parked();
4095
4096        let buffer_search_bar = cx.new_window_entity(|window, cx| {
4097            let mut search_bar =
4098                BufferSearchBar::new(Some(project.read(cx).languages().clone()), window, cx);
4099            search_bar.set_active_pane_item(Some(&editor), window, cx);
4100            search_bar.show(window, cx);
4101            search_bar
4102        });
4103
4104        let panes: Vec<_> = window
4105            .update(&mut cx, |this, _, _| this.panes().to_owned())
4106            .unwrap();
4107        assert_eq!(panes.len(), 1);
4108        let pane = panes.first().cloned().unwrap();
4109        pane.update_in(&mut cx, |pane, window, cx| {
4110            pane.toolbar().update(cx, |toolbar, cx| {
4111                toolbar.add_item(buffer_search_bar.clone(), window, cx);
4112            })
4113        });
4114
4115        let buffer_search_query = "search bar query";
4116        buffer_search_bar
4117            .update_in(&mut cx, |buffer_search_bar, window, cx| {
4118                buffer_search_bar.focus_handle(cx).focus(window);
4119                buffer_search_bar.search(buffer_search_query, None, window, cx)
4120            })
4121            .await
4122            .unwrap();
4123
4124        workspace.update_in(&mut cx, |workspace, window, cx| {
4125            ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
4126        });
4127        cx.run_until_parked();
4128        let project_search_view = pane
4129            .read_with(&cx, |pane, _| {
4130                pane.active_item()
4131                    .and_then(|item| item.downcast::<ProjectSearchView>())
4132            })
4133            .expect("should open a project search view after spawning a new search");
4134        project_search_view.update(&mut cx, |search_view, cx| {
4135            assert_eq!(
4136                search_view.search_query_text(cx),
4137                buffer_search_query,
4138                "Project search should take the query from the buffer search bar since it got focused and had a query inside"
4139            );
4140        });
4141    }
4142
4143    fn init_test(cx: &mut TestAppContext) {
4144        cx.update(|cx| {
4145            let settings = SettingsStore::test(cx);
4146            cx.set_global(settings);
4147
4148            theme::init(theme::LoadThemes::JustBase, cx);
4149
4150            language::init(cx);
4151            client::init_settings(cx);
4152            editor::init(cx);
4153            workspace::init_settings(cx);
4154            Project::init_settings(cx);
4155            crate::init(cx);
4156        });
4157    }
4158
4159    fn perform_search(
4160        search_view: WindowHandle<ProjectSearchView>,
4161        text: impl Into<Arc<str>>,
4162        cx: &mut TestAppContext,
4163    ) {
4164        search_view
4165            .update(cx, |search_view, window, cx| {
4166                search_view.query_editor.update(cx, |query_editor, cx| {
4167                    query_editor.set_text(text, window, cx)
4168                });
4169                search_view.search(cx);
4170            })
4171            .unwrap();
4172        // Ensure editor highlights appear after the search is done
4173        cx.executor().advance_clock(
4174            editor::SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT + Duration::from_millis(100),
4175        );
4176        cx.background_executor.run_until_parked();
4177    }
4178}