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