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