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