project_search.rs

   1use crate::{
   2    BufferSearchBar, FocusSearch, NextHistoryQuery, PreviousHistoryQuery, ReplaceAll, ReplaceNext,
   3    SearchOption, SearchOptions, SearchSource, SelectNextMatch, SelectPreviousMatch,
   4    ToggleCaseSensitive, ToggleIncludeIgnored, ToggleRegex, ToggleReplace, ToggleWholeWord,
   5    buffer_search::Deploy,
   6    search_bar::{ActionButtonState, input_base_styles, render_action_button, render_text_input},
   7};
   8use anyhow::Context as _;
   9use collections::HashMap;
  10use editor::{
  11    Anchor, Editor, EditorEvent, EditorSettings, MAX_TAB_TITLE_LEN, MultiBuffer, SelectionEffects,
  12    actions::{Backtab, SelectAll, Tab},
  13    items::active_match_index,
  14    multibuffer_context_lines,
  15};
  16use futures::{StreamExt, stream::FuturesOrdered};
  17use gpui::{
  18    Action, AnyElement, AnyView, App, Axis, Context, Entity, EntityId, EventEmitter, FocusHandle,
  19    Focusable, Global, Hsla, InteractiveElement, IntoElement, KeyContext, ParentElement, Point,
  20    Render, SharedString, Styled, Subscription, Task, UpdateGlobal, WeakEntity, Window, actions,
  21    div,
  22};
  23use language::{Buffer, Language};
  24use menu::Confirm;
  25use project::{
  26    Project, ProjectPath,
  27    search::{SearchInputKind, SearchQuery},
  28    search_history::SearchHistoryCursor,
  29};
  30use settings::Settings;
  31use std::{
  32    any::{Any, TypeId},
  33    mem,
  34    ops::{Not, Range},
  35    path::Path,
  36    pin::pin,
  37    sync::Arc,
  38};
  39use ui::{IconButtonShape, KeyBinding, Toggleable, Tooltip, prelude::*, utils::SearchInputWidth};
  40use util::{ResultExt as _, paths::PathMatcher};
  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) {
 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) {
 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                                        buffer,
 345                                        ranges,
 346                                        multibuffer_context_lines(cx),
 347                                        cx,
 348                                    )
 349                                })
 350                                .collect::<FuturesOrdered<_>>()
 351                        })
 352                    })
 353                    .ok()?;
 354
 355                while let Some(new_ranges) = new_ranges.next().await {
 356                    project_search
 357                        .update(cx, |project_search, cx| {
 358                            project_search.match_ranges.extend(new_ranges);
 359                            cx.notify();
 360                        })
 361                        .ok()?;
 362                }
 363            }
 364
 365            project_search
 366                .update(cx, |project_search, cx| {
 367                    if !project_search.match_ranges.is_empty() {
 368                        project_search.no_results = Some(false);
 369                    }
 370                    project_search.limit_reached = limit_reached;
 371                    project_search.pending_search.take();
 372                    cx.notify();
 373                })
 374                .ok()?;
 375
 376            None
 377        }));
 378        cx.notify();
 379    }
 380}
 381
 382#[derive(Clone, Debug, PartialEq, Eq)]
 383pub enum ViewEvent {
 384    UpdateTab,
 385    Activate,
 386    EditorEvent(editor::EditorEvent),
 387    Dismiss,
 388}
 389
 390impl EventEmitter<ViewEvent> for ProjectSearchView {}
 391
 392impl Render for ProjectSearchView {
 393    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 394        if self.has_matches() {
 395            div()
 396                .flex_1()
 397                .size_full()
 398                .track_focus(&self.focus_handle(cx))
 399                .child(self.results_editor.clone())
 400        } else {
 401            let model = self.entity.read(cx);
 402            let has_no_results = model.no_results.unwrap_or(false);
 403            let is_search_underway = model.pending_search.is_some();
 404
 405            let heading_text = if is_search_underway {
 406                "Searching…"
 407            } else if has_no_results {
 408                "No Results"
 409            } else {
 410                "Search All Files"
 411            };
 412
 413            let heading_text = div()
 414                .justify_center()
 415                .child(Label::new(heading_text).size(LabelSize::Large));
 416
 417            let page_content: Option<AnyElement> = if let Some(no_results) = model.no_results {
 418                if model.pending_search.is_none() && no_results {
 419                    Some(
 420                        Label::new("No results found in this project for the provided query")
 421                            .size(LabelSize::Small)
 422                            .into_any_element(),
 423                    )
 424                } else {
 425                    None
 426                }
 427            } else {
 428                Some(self.landing_text_minor(window, cx).into_any_element())
 429            };
 430
 431            let page_content = page_content.map(|text| div().child(text));
 432
 433            h_flex()
 434                .size_full()
 435                .items_center()
 436                .justify_center()
 437                .overflow_hidden()
 438                .bg(cx.theme().colors().editor_background)
 439                .track_focus(&self.focus_handle(cx))
 440                .child(
 441                    v_flex()
 442                        .id("project-search-landing-page")
 443                        .overflow_y_scroll()
 444                        .gap_1()
 445                        .child(heading_text)
 446                        .children(page_content),
 447                )
 448        }
 449    }
 450}
 451
 452impl Focusable for ProjectSearchView {
 453    fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
 454        self.focus_handle.clone()
 455    }
 456}
 457
 458impl Item for ProjectSearchView {
 459    type Event = ViewEvent;
 460    fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString> {
 461        let query_text = self.query_editor.read(cx).text(cx);
 462
 463        query_text
 464            .is_empty()
 465            .not()
 466            .then(|| query_text.into())
 467            .or_else(|| Some("Project Search".into()))
 468    }
 469
 470    fn act_as_type<'a>(
 471        &'a self,
 472        type_id: TypeId,
 473        self_handle: &'a Entity<Self>,
 474        _: &'a App,
 475    ) -> Option<AnyView> {
 476        if type_id == TypeId::of::<Self>() {
 477            Some(self_handle.clone().into())
 478        } else if type_id == TypeId::of::<Editor>() {
 479            Some(self.results_editor.clone().into())
 480        } else {
 481            None
 482        }
 483    }
 484    fn as_searchable(&self, _: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
 485        Some(Box::new(self.results_editor.clone()))
 486    }
 487
 488    fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 489        self.results_editor
 490            .update(cx, |editor, cx| editor.deactivated(window, cx));
 491    }
 492
 493    fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
 494        Some(Icon::new(IconName::MagnifyingGlass))
 495    }
 496
 497    fn tab_content_text(&self, _detail: usize, cx: &App) -> SharedString {
 498        let last_query: Option<SharedString> = self
 499            .entity
 500            .read(cx)
 501            .last_search_query_text
 502            .as_ref()
 503            .map(|query| {
 504                let query = query.replace('\n', "");
 505                let query_text = util::truncate_and_trailoff(&query, MAX_TAB_TITLE_LEN);
 506                query_text.into()
 507            });
 508
 509        last_query
 510            .filter(|query| !query.is_empty())
 511            .unwrap_or_else(|| "Project Search".into())
 512    }
 513
 514    fn telemetry_event_text(&self) -> Option<&'static str> {
 515        Some("Project Search Opened")
 516    }
 517
 518    fn for_each_project_item(
 519        &self,
 520        cx: &App,
 521        f: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
 522    ) {
 523        self.results_editor.for_each_project_item(cx, f)
 524    }
 525
 526    fn is_singleton(&self, _: &App) -> bool {
 527        false
 528    }
 529
 530    fn can_save(&self, _: &App) -> bool {
 531        true
 532    }
 533
 534    fn is_dirty(&self, cx: &App) -> bool {
 535        self.results_editor.read(cx).is_dirty(cx)
 536    }
 537
 538    fn has_conflict(&self, cx: &App) -> bool {
 539        self.results_editor.read(cx).has_conflict(cx)
 540    }
 541
 542    fn save(
 543        &mut self,
 544        options: SaveOptions,
 545        project: Entity<Project>,
 546        window: &mut Window,
 547        cx: &mut Context<Self>,
 548    ) -> Task<anyhow::Result<()>> {
 549        self.results_editor
 550            .update(cx, |editor, cx| editor.save(options, project, window, cx))
 551    }
 552
 553    fn save_as(
 554        &mut self,
 555        _: Entity<Project>,
 556        _: ProjectPath,
 557        _window: &mut Window,
 558        _: &mut Context<Self>,
 559    ) -> Task<anyhow::Result<()>> {
 560        unreachable!("save_as should not have been called")
 561    }
 562
 563    fn reload(
 564        &mut self,
 565        project: Entity<Project>,
 566        window: &mut Window,
 567        cx: &mut Context<Self>,
 568    ) -> Task<anyhow::Result<()>> {
 569        self.results_editor
 570            .update(cx, |editor, cx| editor.reload(project, window, cx))
 571    }
 572
 573    fn clone_on_split(
 574        &self,
 575        _workspace_id: Option<WorkspaceId>,
 576        window: &mut Window,
 577        cx: &mut Context<Self>,
 578    ) -> Option<Entity<Self>>
 579    where
 580        Self: Sized,
 581    {
 582        let model = self.entity.update(cx, |model, cx| model.clone(cx));
 583        Some(cx.new(|cx| Self::new(self.workspace.clone(), model, window, cx, None)))
 584    }
 585
 586    fn added_to_workspace(
 587        &mut self,
 588        workspace: &mut Workspace,
 589        window: &mut Window,
 590        cx: &mut Context<Self>,
 591    ) {
 592        self.results_editor.update(cx, |editor, cx| {
 593            editor.added_to_workspace(workspace, window, cx)
 594        });
 595    }
 596
 597    fn set_nav_history(
 598        &mut self,
 599        nav_history: ItemNavHistory,
 600        _: &mut Window,
 601        cx: &mut Context<Self>,
 602    ) {
 603        self.results_editor.update(cx, |editor, _| {
 604            editor.set_nav_history(Some(nav_history));
 605        });
 606    }
 607
 608    fn navigate(
 609        &mut self,
 610        data: Box<dyn Any>,
 611        window: &mut Window,
 612        cx: &mut Context<Self>,
 613    ) -> bool {
 614        self.results_editor
 615            .update(cx, |editor, cx| editor.navigate(data, window, cx))
 616    }
 617
 618    fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
 619        match event {
 620            ViewEvent::UpdateTab => {
 621                f(ItemEvent::UpdateBreadcrumbs);
 622                f(ItemEvent::UpdateTab);
 623            }
 624            ViewEvent::EditorEvent(editor_event) => {
 625                Editor::to_item_events(editor_event, f);
 626            }
 627            ViewEvent::Dismiss => f(ItemEvent::CloseItem),
 628            _ => {}
 629        }
 630    }
 631
 632    fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
 633        if self.has_matches() {
 634            ToolbarItemLocation::Secondary
 635        } else {
 636            ToolbarItemLocation::Hidden
 637        }
 638    }
 639
 640    fn breadcrumbs(&self, theme: &theme::Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
 641        self.results_editor.breadcrumbs(theme, cx)
 642    }
 643}
 644
 645impl ProjectSearchView {
 646    pub fn get_matches(&self, cx: &App) -> Vec<Range<Anchor>> {
 647        self.entity.read(cx).match_ranges.clone()
 648    }
 649
 650    fn toggle_filters(&mut self, cx: &mut Context<Self>) {
 651        self.filters_enabled = !self.filters_enabled;
 652        ActiveSettings::update_global(cx, |settings, cx| {
 653            settings.0.insert(
 654                self.entity.read(cx).project.downgrade(),
 655                self.current_settings(),
 656            );
 657        });
 658    }
 659
 660    fn current_settings(&self) -> ProjectSearchSettings {
 661        ProjectSearchSettings {
 662            search_options: self.search_options,
 663            filters_enabled: self.filters_enabled,
 664        }
 665    }
 666
 667    fn toggle_search_option(&mut self, option: SearchOptions, cx: &mut Context<Self>) {
 668        self.search_options.toggle(option);
 669        ActiveSettings::update_global(cx, |settings, cx| {
 670            settings.0.insert(
 671                self.entity.read(cx).project.downgrade(),
 672                self.current_settings(),
 673            );
 674        });
 675        self.adjust_query_regex_language(cx);
 676    }
 677
 678    fn toggle_opened_only(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {
 679        self.included_opened_only = !self.included_opened_only;
 680    }
 681
 682    pub fn replacement(&self, cx: &App) -> String {
 683        self.replacement_editor.read(cx).text(cx)
 684    }
 685
 686    fn replace_next(&mut self, _: &ReplaceNext, window: &mut Window, cx: &mut Context<Self>) {
 687        if let Some(last_search_query_text) = &self.entity.read(cx).last_search_query_text
 688            && self.query_editor.read(cx).text(cx) != *last_search_query_text
 689        {
 690            // search query has changed, restart search and bail
 691            self.search(cx);
 692            return;
 693        }
 694        if self.entity.read(cx).match_ranges.is_empty() {
 695            return;
 696        }
 697        let Some(active_index) = self.active_match_index else {
 698            return;
 699        };
 700
 701        let query = self.entity.read(cx).active_query.clone();
 702        if let Some(query) = query {
 703            let query = query.with_replacement(self.replacement(cx));
 704
 705            // TODO: Do we need the clone here?
 706            let mat = self.entity.read(cx).match_ranges[active_index].clone();
 707            self.results_editor.update(cx, |editor, cx| {
 708                editor.replace(&mat, &query, window, cx);
 709            });
 710            self.select_match(Direction::Next, window, cx)
 711        }
 712    }
 713    fn replace_all(&mut self, _: &ReplaceAll, window: &mut Window, cx: &mut Context<Self>) {
 714        if let Some(last_search_query_text) = &self.entity.read(cx).last_search_query_text
 715            && self.query_editor.read(cx).text(cx) != *last_search_query_text
 716        {
 717            // search query has changed, restart search and bail
 718            self.search(cx);
 719            return;
 720        }
 721        if self.active_match_index.is_none() {
 722            return;
 723        }
 724        let Some(query) = self.entity.read(cx).active_query.as_ref() else {
 725            return;
 726        };
 727        let query = query.clone().with_replacement(self.replacement(cx));
 728
 729        let match_ranges = self
 730            .entity
 731            .update(cx, |model, _| mem::take(&mut model.match_ranges));
 732        if match_ranges.is_empty() {
 733            return;
 734        }
 735
 736        self.results_editor.update(cx, |editor, cx| {
 737            editor.replace_all(&mut match_ranges.iter(), &query, window, cx);
 738        });
 739
 740        self.entity.update(cx, |model, _cx| {
 741            model.match_ranges = match_ranges;
 742        });
 743    }
 744
 745    pub fn new(
 746        workspace: WeakEntity<Workspace>,
 747        entity: Entity<ProjectSearch>,
 748        window: &mut Window,
 749        cx: &mut Context<Self>,
 750        settings: Option<ProjectSearchSettings>,
 751    ) -> Self {
 752        let project;
 753        let excerpts;
 754        let mut replacement_text = None;
 755        let mut query_text = String::new();
 756        let mut subscriptions = Vec::new();
 757
 758        // Read in settings if available
 759        let (mut options, filters_enabled) = if let Some(settings) = settings {
 760            (settings.search_options, settings.filters_enabled)
 761        } else {
 762            let search_options =
 763                SearchOptions::from_settings(&EditorSettings::get_global(cx).search);
 764            (search_options, false)
 765        };
 766
 767        {
 768            let entity = entity.read(cx);
 769            project = entity.project.clone();
 770            excerpts = entity.excerpts.clone();
 771            if let Some(active_query) = entity.active_query.as_ref() {
 772                query_text = active_query.as_str().to_string();
 773                replacement_text = active_query.replacement().map(ToOwned::to_owned);
 774                options = SearchOptions::from_query(active_query);
 775            }
 776        }
 777        subscriptions.push(cx.observe_in(&entity, window, |this, _, window, cx| {
 778            this.entity_changed(window, cx)
 779        }));
 780
 781        let query_editor = cx.new(|cx| {
 782            let mut editor = Editor::single_line(window, cx);
 783            editor.set_placeholder_text("Search all files…", window, cx);
 784            editor.set_text(query_text, window, cx);
 785            editor
 786        });
 787        // Subscribe to query_editor in order to reraise editor events for workspace item activation purposes
 788        subscriptions.push(
 789            cx.subscribe(&query_editor, |this, _, event: &EditorEvent, cx| {
 790                if let EditorEvent::Edited { .. } = event
 791                    && EditorSettings::get_global(cx).use_smartcase_search
 792                {
 793                    let query = this.search_query_text(cx);
 794                    if !query.is_empty()
 795                        && this.search_options.contains(SearchOptions::CASE_SENSITIVE)
 796                            != contains_uppercase(&query)
 797                    {
 798                        this.toggle_search_option(SearchOptions::CASE_SENSITIVE, cx);
 799                    }
 800                }
 801                cx.emit(ViewEvent::EditorEvent(event.clone()))
 802            }),
 803        );
 804        let replacement_editor = cx.new(|cx| {
 805            let mut editor = Editor::single_line(window, cx);
 806            editor.set_placeholder_text("Replace in project…", window, cx);
 807            if let Some(text) = replacement_text {
 808                editor.set_text(text, window, cx);
 809            }
 810            editor
 811        });
 812        let results_editor = cx.new(|cx| {
 813            let mut editor = Editor::for_multibuffer(excerpts, Some(project.clone()), window, cx);
 814            editor.set_searchable(false);
 815            editor.set_in_project_search(true);
 816            editor
 817        });
 818        subscriptions.push(cx.observe(&results_editor, |_, _, cx| cx.emit(ViewEvent::UpdateTab)));
 819
 820        subscriptions.push(
 821            cx.subscribe(&results_editor, |this, _, event: &EditorEvent, cx| {
 822                if matches!(event, editor::EditorEvent::SelectionsChanged { .. }) {
 823                    this.update_match_index(cx);
 824                }
 825                // Reraise editor events for workspace item activation purposes
 826                cx.emit(ViewEvent::EditorEvent(event.clone()));
 827            }),
 828        );
 829
 830        let included_files_editor = cx.new(|cx| {
 831            let mut editor = Editor::single_line(window, cx);
 832            editor.set_placeholder_text("Include: crates/**/*.toml", window, cx);
 833
 834            editor
 835        });
 836        // Subscribe to include_files_editor in order to reraise editor events for workspace item activation purposes
 837        subscriptions.push(
 838            cx.subscribe(&included_files_editor, |_, _, event: &EditorEvent, cx| {
 839                cx.emit(ViewEvent::EditorEvent(event.clone()))
 840            }),
 841        );
 842
 843        let excluded_files_editor = cx.new(|cx| {
 844            let mut editor = Editor::single_line(window, cx);
 845            editor.set_placeholder_text("Exclude: vendor/*, *.lock", window, cx);
 846
 847            editor
 848        });
 849        // Subscribe to excluded_files_editor in order to reraise editor events for workspace item activation purposes
 850        subscriptions.push(
 851            cx.subscribe(&excluded_files_editor, |_, _, event: &EditorEvent, cx| {
 852                cx.emit(ViewEvent::EditorEvent(event.clone()))
 853            }),
 854        );
 855
 856        let focus_handle = cx.focus_handle();
 857        subscriptions.push(cx.on_focus(&focus_handle, window, |_, window, cx| {
 858            cx.on_next_frame(window, |this, window, cx| {
 859                if this.focus_handle.is_focused(window) {
 860                    if this.has_matches() {
 861                        this.results_editor.focus_handle(cx).focus(window);
 862                    } else {
 863                        this.query_editor.focus_handle(cx).focus(window);
 864                    }
 865                }
 866            });
 867        }));
 868
 869        let languages = project.read(cx).languages().clone();
 870        cx.spawn(async move |project_search_view, cx| {
 871            let regex_language = languages
 872                .language_for_name("regex")
 873                .await
 874                .context("loading regex language")?;
 875            project_search_view
 876                .update(cx, |project_search_view, cx| {
 877                    project_search_view.regex_language = Some(regex_language);
 878                    project_search_view.adjust_query_regex_language(cx);
 879                })
 880                .ok();
 881            anyhow::Ok(())
 882        })
 883        .detach_and_log_err(cx);
 884
 885        // Check if Worktrees have all been previously indexed
 886        let mut this = ProjectSearchView {
 887            workspace,
 888            focus_handle,
 889            replacement_editor,
 890            search_id: entity.read(cx).search_id,
 891            entity,
 892            query_editor,
 893            results_editor,
 894            search_options: options,
 895            panels_with_errors: HashMap::default(),
 896            active_match_index: None,
 897            included_files_editor,
 898            excluded_files_editor,
 899            filters_enabled,
 900            replace_enabled: false,
 901            included_opened_only: false,
 902            regex_language: None,
 903            _subscriptions: subscriptions,
 904        };
 905        this.entity_changed(window, cx);
 906        this
 907    }
 908
 909    pub fn new_search_in_directory(
 910        workspace: &mut Workspace,
 911        dir_path: &Path,
 912        window: &mut Window,
 913        cx: &mut Context<Workspace>,
 914    ) {
 915        let Some(filter_str) = dir_path.to_str() else {
 916            return;
 917        };
 918
 919        let weak_workspace = cx.entity().downgrade();
 920
 921        let entity = cx.new(|cx| ProjectSearch::new(workspace.project().clone(), cx));
 922        let search = cx.new(|cx| ProjectSearchView::new(weak_workspace, entity, window, cx, None));
 923        workspace.add_item_to_active_pane(Box::new(search.clone()), None, true, window, cx);
 924        search.update(cx, |search, cx| {
 925            search
 926                .included_files_editor
 927                .update(cx, |editor, cx| editor.set_text(filter_str, window, cx));
 928            search.filters_enabled = true;
 929            search.focus_query_editor(window, cx)
 930        });
 931    }
 932
 933    /// Re-activate the most recently activated search in this pane or the most recent if it has been closed.
 934    /// If no search exists in the workspace, create a new one.
 935    pub fn deploy_search(
 936        workspace: &mut Workspace,
 937        action: &workspace::DeploySearch,
 938        window: &mut Window,
 939        cx: &mut Context<Workspace>,
 940    ) {
 941        let existing = workspace
 942            .active_pane()
 943            .read(cx)
 944            .items()
 945            .find_map(|item| item.downcast::<ProjectSearchView>());
 946
 947        Self::existing_or_new_search(workspace, existing, action, window, cx);
 948    }
 949
 950    fn search_in_new(
 951        workspace: &mut Workspace,
 952        _: &SearchInNew,
 953        window: &mut Window,
 954        cx: &mut Context<Workspace>,
 955    ) {
 956        if let Some(search_view) = workspace
 957            .active_item(cx)
 958            .and_then(|item| item.downcast::<ProjectSearchView>())
 959        {
 960            let new_query = search_view.update(cx, |search_view, cx| {
 961                let new_query = search_view.build_search_query(cx);
 962                if new_query.is_some()
 963                    && let Some(old_query) = search_view.entity.read(cx).active_query.clone()
 964                {
 965                    search_view.query_editor.update(cx, |editor, cx| {
 966                        editor.set_text(old_query.as_str(), window, cx);
 967                    });
 968                    search_view.search_options = SearchOptions::from_query(&old_query);
 969                    search_view.adjust_query_regex_language(cx);
 970                }
 971                new_query
 972            });
 973            if let Some(new_query) = new_query {
 974                let entity = cx.new(|cx| {
 975                    let mut entity = ProjectSearch::new(workspace.project().clone(), cx);
 976                    entity.search(new_query, cx);
 977                    entity
 978                });
 979                let weak_workspace = cx.entity().downgrade();
 980                workspace.add_item_to_active_pane(
 981                    Box::new(cx.new(|cx| {
 982                        ProjectSearchView::new(weak_workspace, entity, window, cx, None)
 983                    })),
 984                    None,
 985                    true,
 986                    window,
 987                    cx,
 988                );
 989            }
 990        }
 991    }
 992
 993    // Add another search tab to the workspace.
 994    fn new_search(
 995        workspace: &mut Workspace,
 996        _: &workspace::NewSearch,
 997        window: &mut Window,
 998        cx: &mut Context<Workspace>,
 999    ) {
1000        Self::existing_or_new_search(workspace, None, &DeploySearch::find(), window, cx)
1001    }
1002
1003    fn existing_or_new_search(
1004        workspace: &mut Workspace,
1005        existing: Option<Entity<ProjectSearchView>>,
1006        action: &workspace::DeploySearch,
1007        window: &mut Window,
1008        cx: &mut Context<Workspace>,
1009    ) {
1010        let query = workspace.active_item(cx).and_then(|item| {
1011            if let Some(buffer_search_query) = buffer_search_query(workspace, item.as_ref(), cx) {
1012                return Some(buffer_search_query);
1013            }
1014
1015            let editor = item.act_as::<Editor>(cx)?;
1016            let query = editor.query_suggestion(window, cx);
1017            if query.is_empty() { None } else { Some(query) }
1018        });
1019
1020        let search = if let Some(existing) = existing {
1021            workspace.activate_item(&existing, true, true, window, cx);
1022            existing
1023        } else {
1024            let settings = cx
1025                .global::<ActiveSettings>()
1026                .0
1027                .get(&workspace.project().downgrade());
1028
1029            let settings = settings.cloned();
1030
1031            let weak_workspace = cx.entity().downgrade();
1032
1033            let project_search = cx.new(|cx| ProjectSearch::new(workspace.project().clone(), cx));
1034            let project_search_view = cx.new(|cx| {
1035                ProjectSearchView::new(weak_workspace, project_search, window, cx, settings)
1036            });
1037
1038            workspace.add_item_to_active_pane(
1039                Box::new(project_search_view.clone()),
1040                None,
1041                true,
1042                window,
1043                cx,
1044            );
1045            project_search_view
1046        };
1047
1048        search.update(cx, |search, cx| {
1049            search.replace_enabled = action.replace_enabled;
1050            if let Some(query) = query {
1051                search.set_query(&query, window, cx);
1052            }
1053            if let Some(included_files) = action.included_files.as_deref() {
1054                search
1055                    .included_files_editor
1056                    .update(cx, |editor, cx| editor.set_text(included_files, window, cx));
1057                search.filters_enabled = true;
1058            }
1059            if let Some(excluded_files) = action.excluded_files.as_deref() {
1060                search
1061                    .excluded_files_editor
1062                    .update(cx, |editor, cx| editor.set_text(excluded_files, window, cx));
1063                search.filters_enabled = true;
1064            }
1065            search.focus_query_editor(window, cx)
1066        });
1067    }
1068
1069    fn prompt_to_save_if_dirty_then_search(
1070        &mut self,
1071        window: &mut Window,
1072        cx: &mut Context<Self>,
1073    ) -> Task<anyhow::Result<()>> {
1074        use workspace::AutosaveSetting;
1075
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
1082            && matches!(
1083                autosave_setting,
1084                AutosaveSetting::OnFocusChange | AutosaveSetting::OnWindowChange
1085            );
1086
1087        let is_dirty = self.is_dirty(cx);
1088
1089        cx.spawn_in(window, async move |this, cx| {
1090            let skip_save_on_close = this
1091                .read_with(cx, |this, cx| {
1092                    this.workspace.read_with(cx, |workspace, cx| {
1093                        workspace::Pane::skip_save_on_close(&this.results_editor, workspace, cx)
1094                    })
1095                })?
1096                .unwrap_or(false);
1097
1098            let should_prompt_to_save = !skip_save_on_close && !will_autosave && is_dirty;
1099
1100            let should_search = if should_prompt_to_save {
1101                let options = &["Save", "Don't Save", "Cancel"];
1102                let result_channel = this.update_in(cx, |_, window, cx| {
1103                    window.prompt(
1104                        gpui::PromptLevel::Warning,
1105                        "Project search buffer contains unsaved edits. Do you want to save it?",
1106                        None,
1107                        options,
1108                        cx,
1109                    )
1110                })?;
1111                let result = result_channel.await?;
1112                let should_save = result == 0;
1113                if should_save {
1114                    this.update_in(cx, |this, window, cx| {
1115                        this.save(
1116                            SaveOptions {
1117                                format: true,
1118                                autosave: false,
1119                            },
1120                            project,
1121                            window,
1122                            cx,
1123                        )
1124                    })?
1125                    .await
1126                    .log_err();
1127                }
1128
1129                result != 2
1130            } else {
1131                true
1132            };
1133            if should_search {
1134                this.update(cx, |this, cx| {
1135                    this.search(cx);
1136                })?;
1137            }
1138            anyhow::Ok(())
1139        })
1140    }
1141
1142    fn search(&mut self, cx: &mut Context<Self>) {
1143        if let Some(query) = self.build_search_query(cx) {
1144            self.entity.update(cx, |model, cx| model.search(query, cx));
1145        }
1146    }
1147
1148    pub fn search_query_text(&self, cx: &App) -> String {
1149        self.query_editor.read(cx).text(cx)
1150    }
1151
1152    fn build_search_query(&mut self, cx: &mut Context<Self>) -> Option<SearchQuery> {
1153        // Do not bail early in this function, as we want to fill out `self.panels_with_errors`.
1154        let text = self.search_query_text(cx);
1155        let open_buffers = if self.included_opened_only {
1156            Some(self.open_buffers(cx))
1157        } else {
1158            None
1159        };
1160        let included_files = self
1161            .filters_enabled
1162            .then(|| {
1163                match Self::parse_path_matches(&self.included_files_editor.read(cx).text(cx)) {
1164                    Ok(included_files) => {
1165                        let should_unmark_error =
1166                            self.panels_with_errors.remove(&InputPanel::Include);
1167                        if should_unmark_error.is_some() {
1168                            cx.notify();
1169                        }
1170                        included_files
1171                    }
1172                    Err(e) => {
1173                        let should_mark_error = self
1174                            .panels_with_errors
1175                            .insert(InputPanel::Include, e.to_string());
1176                        if should_mark_error.is_none() {
1177                            cx.notify();
1178                        }
1179                        PathMatcher::default()
1180                    }
1181                }
1182            })
1183            .unwrap_or_default();
1184        let excluded_files = self
1185            .filters_enabled
1186            .then(|| {
1187                match Self::parse_path_matches(&self.excluded_files_editor.read(cx).text(cx)) {
1188                    Ok(excluded_files) => {
1189                        let should_unmark_error =
1190                            self.panels_with_errors.remove(&InputPanel::Exclude);
1191                        if should_unmark_error.is_some() {
1192                            cx.notify();
1193                        }
1194
1195                        excluded_files
1196                    }
1197                    Err(e) => {
1198                        let should_mark_error = self
1199                            .panels_with_errors
1200                            .insert(InputPanel::Exclude, e.to_string());
1201                        if should_mark_error.is_none() {
1202                            cx.notify();
1203                        }
1204                        PathMatcher::default()
1205                    }
1206                }
1207            })
1208            .unwrap_or_default();
1209
1210        // If the project contains multiple visible worktrees, we match the
1211        // include/exclude patterns against full paths to allow them to be
1212        // disambiguated. For single worktree projects we use worktree relative
1213        // paths for convenience.
1214        let match_full_paths = self
1215            .entity
1216            .read(cx)
1217            .project
1218            .read(cx)
1219            .visible_worktrees(cx)
1220            .count()
1221            > 1;
1222
1223        let query = if self.search_options.contains(SearchOptions::REGEX) {
1224            match SearchQuery::regex(
1225                text,
1226                self.search_options.contains(SearchOptions::WHOLE_WORD),
1227                self.search_options.contains(SearchOptions::CASE_SENSITIVE),
1228                self.search_options.contains(SearchOptions::INCLUDE_IGNORED),
1229                self.search_options
1230                    .contains(SearchOptions::ONE_MATCH_PER_LINE),
1231                included_files,
1232                excluded_files,
1233                match_full_paths,
1234                open_buffers,
1235            ) {
1236                Ok(query) => {
1237                    let should_unmark_error = self.panels_with_errors.remove(&InputPanel::Query);
1238                    if should_unmark_error.is_some() {
1239                        cx.notify();
1240                    }
1241
1242                    Some(query)
1243                }
1244                Err(e) => {
1245                    let should_mark_error = self
1246                        .panels_with_errors
1247                        .insert(InputPanel::Query, e.to_string());
1248                    if should_mark_error.is_none() {
1249                        cx.notify();
1250                    }
1251
1252                    None
1253                }
1254            }
1255        } else {
1256            match SearchQuery::text(
1257                text,
1258                self.search_options.contains(SearchOptions::WHOLE_WORD),
1259                self.search_options.contains(SearchOptions::CASE_SENSITIVE),
1260                self.search_options.contains(SearchOptions::INCLUDE_IGNORED),
1261                included_files,
1262                excluded_files,
1263                match_full_paths,
1264                open_buffers,
1265            ) {
1266                Ok(query) => {
1267                    let should_unmark_error = self.panels_with_errors.remove(&InputPanel::Query);
1268                    if should_unmark_error.is_some() {
1269                        cx.notify();
1270                    }
1271
1272                    Some(query)
1273                }
1274                Err(e) => {
1275                    let should_mark_error = self
1276                        .panels_with_errors
1277                        .insert(InputPanel::Query, e.to_string());
1278                    if should_mark_error.is_none() {
1279                        cx.notify();
1280                    }
1281
1282                    None
1283                }
1284            }
1285        };
1286        if !self.panels_with_errors.is_empty() {
1287            return None;
1288        }
1289        if query.as_ref().is_some_and(|query| query.is_empty()) {
1290            return None;
1291        }
1292        query
1293    }
1294
1295    fn open_buffers(&self, cx: &mut Context<Self>) -> Vec<Entity<Buffer>> {
1296        let mut buffers = Vec::new();
1297        self.workspace
1298            .update(cx, |workspace, cx| {
1299                for editor in workspace.items_of_type::<Editor>(cx) {
1300                    if let Some(buffer) = editor.read(cx).buffer().read(cx).as_singleton() {
1301                        buffers.push(buffer);
1302                    }
1303                }
1304            })
1305            .ok();
1306        buffers
1307    }
1308
1309    fn parse_path_matches(text: &str) -> anyhow::Result<PathMatcher> {
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)?)
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) {
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) {
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 project::FakeFs;
2361    use serde_json::json;
2362    use settings::SettingsStore;
2363    use util::path;
2364    use workspace::DeploySearch;
2365
2366    #[gpui::test]
2367    async fn test_project_search(cx: &mut TestAppContext) {
2368        init_test(cx);
2369
2370        let fs = FakeFs::new(cx.background_executor.clone());
2371        fs.insert_tree(
2372            path!("/dir"),
2373            json!({
2374                "one.rs": "const ONE: usize = 1;",
2375                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2376                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2377                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2378            }),
2379        )
2380        .await;
2381        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
2382        let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
2383        let workspace = window.root(cx).unwrap();
2384        let search = cx.new(|cx| ProjectSearch::new(project.clone(), cx));
2385        let search_view = cx.add_window(|window, cx| {
2386            ProjectSearchView::new(workspace.downgrade(), search.clone(), window, cx, None)
2387        });
2388
2389        perform_search(search_view, "TWO", cx);
2390        search_view.update(cx, |search_view, window, cx| {
2391            assert_eq!(
2392                search_view
2393                    .results_editor
2394                    .update(cx, |editor, cx| editor.display_text(cx)),
2395                "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;"
2396            );
2397            let match_background_color = cx.theme().colors().search_match_background;
2398            let selection_background_color = cx.theme().colors().editor_document_highlight_bracket_background;
2399            assert_eq!(
2400                search_view
2401                    .results_editor
2402                    .update(cx, |editor, cx| editor.all_text_background_highlights(window, cx)),
2403                &[
2404                    (
2405                        DisplayPoint::new(DisplayRow(2), 32)..DisplayPoint::new(DisplayRow(2), 35),
2406                        match_background_color
2407                    ),
2408                    (
2409                        DisplayPoint::new(DisplayRow(2), 37)..DisplayPoint::new(DisplayRow(2), 40),
2410                        selection_background_color
2411                    ),
2412                    (
2413                        DisplayPoint::new(DisplayRow(2), 37)..DisplayPoint::new(DisplayRow(2), 40),
2414                        match_background_color
2415                    ),
2416                    (
2417                        DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(5), 9),
2418                        selection_background_color
2419                    ),
2420                    (
2421                        DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(5), 9),
2422                        match_background_color
2423                    ),
2424
2425                ]
2426            );
2427            assert_eq!(search_view.active_match_index, Some(0));
2428            assert_eq!(
2429                search_view
2430                    .results_editor
2431                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2432                [DisplayPoint::new(DisplayRow(2), 32)..DisplayPoint::new(DisplayRow(2), 35)]
2433            );
2434
2435            search_view.select_match(Direction::Next, window, cx);
2436        }).unwrap();
2437
2438        search_view
2439            .update(cx, |search_view, window, cx| {
2440                assert_eq!(search_view.active_match_index, Some(1));
2441                assert_eq!(
2442                    search_view
2443                        .results_editor
2444                        .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2445                    [DisplayPoint::new(DisplayRow(2), 37)..DisplayPoint::new(DisplayRow(2), 40)]
2446                );
2447                search_view.select_match(Direction::Next, window, cx);
2448            })
2449            .unwrap();
2450
2451        search_view
2452            .update(cx, |search_view, window, cx| {
2453                assert_eq!(search_view.active_match_index, Some(2));
2454                assert_eq!(
2455                    search_view
2456                        .results_editor
2457                        .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2458                    [DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(5), 9)]
2459                );
2460                search_view.select_match(Direction::Next, window, cx);
2461            })
2462            .unwrap();
2463
2464        search_view
2465            .update(cx, |search_view, window, cx| {
2466                assert_eq!(search_view.active_match_index, Some(0));
2467                assert_eq!(
2468                    search_view
2469                        .results_editor
2470                        .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2471                    [DisplayPoint::new(DisplayRow(2), 32)..DisplayPoint::new(DisplayRow(2), 35)]
2472                );
2473                search_view.select_match(Direction::Prev, window, cx);
2474            })
2475            .unwrap();
2476
2477        search_view
2478            .update(cx, |search_view, window, cx| {
2479                assert_eq!(search_view.active_match_index, Some(2));
2480                assert_eq!(
2481                    search_view
2482                        .results_editor
2483                        .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2484                    [DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(5), 9)]
2485                );
2486                search_view.select_match(Direction::Prev, window, cx);
2487            })
2488            .unwrap();
2489
2490        search_view
2491            .update(cx, |search_view, _, cx| {
2492                assert_eq!(search_view.active_match_index, Some(1));
2493                assert_eq!(
2494                    search_view
2495                        .results_editor
2496                        .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2497                    [DisplayPoint::new(DisplayRow(2), 37)..DisplayPoint::new(DisplayRow(2), 40)]
2498                );
2499            })
2500            .unwrap();
2501    }
2502
2503    #[gpui::test]
2504    async fn test_deploy_project_search_focus(cx: &mut TestAppContext) {
2505        init_test(cx);
2506
2507        let fs = FakeFs::new(cx.background_executor.clone());
2508        fs.insert_tree(
2509            "/dir",
2510            json!({
2511                "one.rs": "const ONE: usize = 1;",
2512                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2513                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2514                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2515            }),
2516        )
2517        .await;
2518        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
2519        let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
2520        let workspace = window;
2521        let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
2522
2523        let active_item = cx.read(|cx| {
2524            workspace
2525                .read(cx)
2526                .unwrap()
2527                .active_pane()
2528                .read(cx)
2529                .active_item()
2530                .and_then(|item| item.downcast::<ProjectSearchView>())
2531        });
2532        assert!(
2533            active_item.is_none(),
2534            "Expected no search panel to be active"
2535        );
2536
2537        window
2538            .update(cx, move |workspace, window, cx| {
2539                assert_eq!(workspace.panes().len(), 1);
2540                workspace.panes()[0].update(cx, |pane, cx| {
2541                    pane.toolbar()
2542                        .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
2543                });
2544
2545                ProjectSearchView::deploy_search(
2546                    workspace,
2547                    &workspace::DeploySearch::find(),
2548                    window,
2549                    cx,
2550                )
2551            })
2552            .unwrap();
2553
2554        let Some(search_view) = cx.read(|cx| {
2555            workspace
2556                .read(cx)
2557                .unwrap()
2558                .active_pane()
2559                .read(cx)
2560                .active_item()
2561                .and_then(|item| item.downcast::<ProjectSearchView>())
2562        }) else {
2563            panic!("Search view expected to appear after new search event trigger")
2564        };
2565
2566        cx.spawn(|mut cx| async move {
2567            window
2568                .update(&mut cx, |_, window, cx| {
2569                    window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2570                })
2571                .unwrap();
2572        })
2573        .detach();
2574        cx.background_executor.run_until_parked();
2575        window
2576            .update(cx, |_, window, cx| {
2577                search_view.update(cx, |search_view, cx| {
2578                    assert!(
2579                        search_view.query_editor.focus_handle(cx).is_focused(window),
2580                        "Empty search view should be focused after the toggle focus event: no results panel to focus on",
2581                    );
2582                });
2583        }).unwrap();
2584
2585        window
2586            .update(cx, |_, window, cx| {
2587                search_view.update(cx, |search_view, cx| {
2588                    let query_editor = &search_view.query_editor;
2589                    assert!(
2590                        query_editor.focus_handle(cx).is_focused(window),
2591                        "Search view should be focused after the new search view is activated",
2592                    );
2593                    let query_text = query_editor.read(cx).text(cx);
2594                    assert!(
2595                        query_text.is_empty(),
2596                        "New search query should be empty but got '{query_text}'",
2597                    );
2598                    let results_text = search_view
2599                        .results_editor
2600                        .update(cx, |editor, cx| editor.display_text(cx));
2601                    assert!(
2602                        results_text.is_empty(),
2603                        "Empty search view should have no results but got '{results_text}'"
2604                    );
2605                });
2606            })
2607            .unwrap();
2608
2609        window
2610            .update(cx, |_, window, cx| {
2611                search_view.update(cx, |search_view, cx| {
2612                    search_view.query_editor.update(cx, |query_editor, cx| {
2613                        query_editor.set_text("sOMETHINGtHATsURELYdOESnOTeXIST", window, cx)
2614                    });
2615                    search_view.search(cx);
2616                });
2617            })
2618            .unwrap();
2619        cx.background_executor.run_until_parked();
2620        window
2621            .update(cx, |_, window, cx| {
2622                search_view.update(cx, |search_view, cx| {
2623                    let results_text = search_view
2624                        .results_editor
2625                        .update(cx, |editor, cx| editor.display_text(cx));
2626                    assert!(
2627                        results_text.is_empty(),
2628                        "Search view for mismatching query should have no results but got '{results_text}'"
2629                    );
2630                    assert!(
2631                        search_view.query_editor.focus_handle(cx).is_focused(window),
2632                        "Search view should be focused after mismatching query had been used in search",
2633                    );
2634                });
2635            }).unwrap();
2636
2637        cx.spawn(|mut cx| async move {
2638            window.update(&mut cx, |_, window, cx| {
2639                window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2640            })
2641        })
2642        .detach();
2643        cx.background_executor.run_until_parked();
2644        window.update(cx, |_, window, cx| {
2645            search_view.update(cx, |search_view, cx| {
2646                assert!(
2647                    search_view.query_editor.focus_handle(cx).is_focused(window),
2648                    "Search view with mismatching query should be focused after the toggle focus event: still no results panel to focus on",
2649                );
2650            });
2651        }).unwrap();
2652
2653        window
2654            .update(cx, |_, window, cx| {
2655                search_view.update(cx, |search_view, cx| {
2656                    search_view.query_editor.update(cx, |query_editor, cx| {
2657                        query_editor.set_text("TWO", window, cx)
2658                    });
2659                    search_view.search(cx);
2660                });
2661            })
2662            .unwrap();
2663        cx.background_executor.run_until_parked();
2664        window.update(cx, |_, window, cx| {
2665            search_view.update(cx, |search_view, cx| {
2666                assert_eq!(
2667                    search_view
2668                        .results_editor
2669                        .update(cx, |editor, cx| editor.display_text(cx)),
2670                    "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
2671                    "Search view results should match the query"
2672                );
2673                assert!(
2674                    search_view.results_editor.focus_handle(cx).is_focused(window),
2675                    "Search view with mismatching query should be focused after search results are available",
2676                );
2677            });
2678        }).unwrap();
2679        cx.spawn(|mut cx| async move {
2680            window
2681                .update(&mut cx, |_, window, cx| {
2682                    window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2683                })
2684                .unwrap();
2685        })
2686        .detach();
2687        cx.background_executor.run_until_parked();
2688        window.update(cx, |_, window, cx| {
2689            search_view.update(cx, |search_view, cx| {
2690                assert!(
2691                    search_view.results_editor.focus_handle(cx).is_focused(window),
2692                    "Search view with matching query should still have its results editor focused after the toggle focus event",
2693                );
2694            });
2695        }).unwrap();
2696
2697        workspace
2698            .update(cx, |workspace, window, cx| {
2699                ProjectSearchView::deploy_search(
2700                    workspace,
2701                    &workspace::DeploySearch::find(),
2702                    window,
2703                    cx,
2704                )
2705            })
2706            .unwrap();
2707        window.update(cx, |_, window, cx| {
2708            search_view.update(cx, |search_view, cx| {
2709                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");
2710                assert_eq!(
2711                    search_view
2712                        .results_editor
2713                        .update(cx, |editor, cx| editor.display_text(cx)),
2714                    "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
2715                    "Results should be unchanged after search view 2nd open in a row"
2716                );
2717                assert!(
2718                    search_view.query_editor.focus_handle(cx).is_focused(window),
2719                    "Focus should be moved into query editor again after search view 2nd open in a row"
2720                );
2721            });
2722        }).unwrap();
2723
2724        cx.spawn(|mut cx| async move {
2725            window
2726                .update(&mut cx, |_, window, cx| {
2727                    window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2728                })
2729                .unwrap();
2730        })
2731        .detach();
2732        cx.background_executor.run_until_parked();
2733        window.update(cx, |_, window, cx| {
2734            search_view.update(cx, |search_view, cx| {
2735                assert!(
2736                    search_view.results_editor.focus_handle(cx).is_focused(window),
2737                    "Search view with matching query should switch focus to the results editor after the toggle focus event",
2738                );
2739            });
2740        }).unwrap();
2741    }
2742
2743    #[gpui::test]
2744    async fn test_filters_consider_toggle_state(cx: &mut TestAppContext) {
2745        init_test(cx);
2746
2747        let fs = FakeFs::new(cx.background_executor.clone());
2748        fs.insert_tree(
2749            "/dir",
2750            json!({
2751                "one.rs": "const ONE: usize = 1;",
2752                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2753                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2754                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2755            }),
2756        )
2757        .await;
2758        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
2759        let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
2760        let workspace = window;
2761        let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
2762
2763        window
2764            .update(cx, move |workspace, window, cx| {
2765                workspace.panes()[0].update(cx, |pane, cx| {
2766                    pane.toolbar()
2767                        .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
2768                });
2769
2770                ProjectSearchView::deploy_search(
2771                    workspace,
2772                    &workspace::DeploySearch::find(),
2773                    window,
2774                    cx,
2775                )
2776            })
2777            .unwrap();
2778
2779        let Some(search_view) = cx.read(|cx| {
2780            workspace
2781                .read(cx)
2782                .unwrap()
2783                .active_pane()
2784                .read(cx)
2785                .active_item()
2786                .and_then(|item| item.downcast::<ProjectSearchView>())
2787        }) else {
2788            panic!("Search view expected to appear after new search event trigger")
2789        };
2790
2791        cx.spawn(|mut cx| async move {
2792            window
2793                .update(&mut cx, |_, window, cx| {
2794                    window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2795                })
2796                .unwrap();
2797        })
2798        .detach();
2799        cx.background_executor.run_until_parked();
2800
2801        window
2802            .update(cx, |_, window, cx| {
2803                search_view.update(cx, |search_view, cx| {
2804                    search_view.query_editor.update(cx, |query_editor, cx| {
2805                        query_editor.set_text("const FOUR", window, cx)
2806                    });
2807                    search_view.toggle_filters(cx);
2808                    search_view
2809                        .excluded_files_editor
2810                        .update(cx, |exclude_editor, cx| {
2811                            exclude_editor.set_text("four.rs", window, cx)
2812                        });
2813                    search_view.search(cx);
2814                });
2815            })
2816            .unwrap();
2817        cx.background_executor.run_until_parked();
2818        window
2819            .update(cx, |_, _, cx| {
2820                search_view.update(cx, |search_view, cx| {
2821                    let results_text = search_view
2822                        .results_editor
2823                        .update(cx, |editor, cx| editor.display_text(cx));
2824                    assert!(
2825                        results_text.is_empty(),
2826                        "Search view for query with the only match in an excluded file should have no results but got '{results_text}'"
2827                    );
2828                });
2829            }).unwrap();
2830
2831        cx.spawn(|mut cx| async move {
2832            window.update(&mut cx, |_, window, cx| {
2833                window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2834            })
2835        })
2836        .detach();
2837        cx.background_executor.run_until_parked();
2838
2839        window
2840            .update(cx, |_, _, cx| {
2841                search_view.update(cx, |search_view, cx| {
2842                    search_view.toggle_filters(cx);
2843                    search_view.search(cx);
2844                });
2845            })
2846            .unwrap();
2847        cx.background_executor.run_until_parked();
2848        window
2849            .update(cx, |_, _, cx| {
2850                search_view.update(cx, |search_view, cx| {
2851                assert_eq!(
2852                    search_view
2853                        .results_editor
2854                        .update(cx, |editor, cx| editor.display_text(cx)),
2855                    "\n\nconst FOUR: usize = one::ONE + three::THREE;",
2856                    "Search view results should contain the queried result in the previously excluded file with filters toggled off"
2857                );
2858            });
2859            })
2860            .unwrap();
2861    }
2862
2863    #[gpui::test]
2864    async fn test_new_project_search_focus(cx: &mut TestAppContext) {
2865        init_test(cx);
2866
2867        let fs = FakeFs::new(cx.background_executor.clone());
2868        fs.insert_tree(
2869            path!("/dir"),
2870            json!({
2871                "one.rs": "const ONE: usize = 1;",
2872                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2873                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2874                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2875            }),
2876        )
2877        .await;
2878        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
2879        let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
2880        let workspace = window;
2881        let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
2882
2883        let active_item = cx.read(|cx| {
2884            workspace
2885                .read(cx)
2886                .unwrap()
2887                .active_pane()
2888                .read(cx)
2889                .active_item()
2890                .and_then(|item| item.downcast::<ProjectSearchView>())
2891        });
2892        assert!(
2893            active_item.is_none(),
2894            "Expected no search panel to be active"
2895        );
2896
2897        window
2898            .update(cx, move |workspace, window, cx| {
2899                assert_eq!(workspace.panes().len(), 1);
2900                workspace.panes()[0].update(cx, |pane, cx| {
2901                    pane.toolbar()
2902                        .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
2903                });
2904
2905                ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
2906            })
2907            .unwrap();
2908
2909        let Some(search_view) = cx.read(|cx| {
2910            workspace
2911                .read(cx)
2912                .unwrap()
2913                .active_pane()
2914                .read(cx)
2915                .active_item()
2916                .and_then(|item| item.downcast::<ProjectSearchView>())
2917        }) else {
2918            panic!("Search view expected to appear after new search event trigger")
2919        };
2920
2921        cx.spawn(|mut cx| async move {
2922            window
2923                .update(&mut cx, |_, window, cx| {
2924                    window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2925                })
2926                .unwrap();
2927        })
2928        .detach();
2929        cx.background_executor.run_until_parked();
2930
2931        window.update(cx, |_, window, cx| {
2932            search_view.update(cx, |search_view, cx| {
2933                    assert!(
2934                        search_view.query_editor.focus_handle(cx).is_focused(window),
2935                        "Empty search view should be focused after the toggle focus event: no results panel to focus on",
2936                    );
2937                });
2938        }).unwrap();
2939
2940        window
2941            .update(cx, |_, window, cx| {
2942                search_view.update(cx, |search_view, cx| {
2943                    let query_editor = &search_view.query_editor;
2944                    assert!(
2945                        query_editor.focus_handle(cx).is_focused(window),
2946                        "Search view should be focused after the new search view is activated",
2947                    );
2948                    let query_text = query_editor.read(cx).text(cx);
2949                    assert!(
2950                        query_text.is_empty(),
2951                        "New search query should be empty but got '{query_text}'",
2952                    );
2953                    let results_text = search_view
2954                        .results_editor
2955                        .update(cx, |editor, cx| editor.display_text(cx));
2956                    assert!(
2957                        results_text.is_empty(),
2958                        "Empty search view should have no results but got '{results_text}'"
2959                    );
2960                });
2961            })
2962            .unwrap();
2963
2964        window
2965            .update(cx, |_, window, cx| {
2966                search_view.update(cx, |search_view, cx| {
2967                    search_view.query_editor.update(cx, |query_editor, cx| {
2968                        query_editor.set_text("sOMETHINGtHATsURELYdOESnOTeXIST", window, cx)
2969                    });
2970                    search_view.search(cx);
2971                });
2972            })
2973            .unwrap();
2974
2975        cx.background_executor.run_until_parked();
2976        window
2977            .update(cx, |_, window, cx| {
2978                search_view.update(cx, |search_view, cx| {
2979                    let results_text = search_view
2980                        .results_editor
2981                        .update(cx, |editor, cx| editor.display_text(cx));
2982                    assert!(
2983                results_text.is_empty(),
2984                "Search view for mismatching query should have no results but got '{results_text}'"
2985            );
2986                    assert!(
2987                search_view.query_editor.focus_handle(cx).is_focused(window),
2988                "Search view should be focused after mismatching query had been used in search",
2989            );
2990                });
2991            })
2992            .unwrap();
2993        cx.spawn(|mut cx| async move {
2994            window.update(&mut cx, |_, window, cx| {
2995                window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2996            })
2997        })
2998        .detach();
2999        cx.background_executor.run_until_parked();
3000        window.update(cx, |_, window, cx| {
3001            search_view.update(cx, |search_view, cx| {
3002                    assert!(
3003                        search_view.query_editor.focus_handle(cx).is_focused(window),
3004                        "Search view with mismatching query should be focused after the toggle focus event: still no results panel to focus on",
3005                    );
3006                });
3007        }).unwrap();
3008
3009        window
3010            .update(cx, |_, window, cx| {
3011                search_view.update(cx, |search_view, cx| {
3012                    search_view.query_editor.update(cx, |query_editor, cx| {
3013                        query_editor.set_text("TWO", window, cx)
3014                    });
3015                    search_view.search(cx);
3016                })
3017            })
3018            .unwrap();
3019        cx.background_executor.run_until_parked();
3020        window.update(cx, |_, window, cx|
3021        search_view.update(cx, |search_view, cx| {
3022                assert_eq!(
3023                    search_view
3024                        .results_editor
3025                        .update(cx, |editor, cx| editor.display_text(cx)),
3026                    "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
3027                    "Search view results should match the query"
3028                );
3029                assert!(
3030                    search_view.results_editor.focus_handle(cx).is_focused(window),
3031                    "Search view with mismatching query should be focused after search results are available",
3032                );
3033            })).unwrap();
3034        cx.spawn(|mut cx| async move {
3035            window
3036                .update(&mut cx, |_, window, cx| {
3037                    window.dispatch_action(ToggleFocus.boxed_clone(), cx)
3038                })
3039                .unwrap();
3040        })
3041        .detach();
3042        cx.background_executor.run_until_parked();
3043        window.update(cx, |_, window, cx| {
3044            search_view.update(cx, |search_view, cx| {
3045                    assert!(
3046                        search_view.results_editor.focus_handle(cx).is_focused(window),
3047                        "Search view with matching query should still have its results editor focused after the toggle focus event",
3048                    );
3049                });
3050        }).unwrap();
3051
3052        workspace
3053            .update(cx, |workspace, window, cx| {
3054                ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3055            })
3056            .unwrap();
3057        cx.background_executor.run_until_parked();
3058        let Some(search_view_2) = cx.read(|cx| {
3059            workspace
3060                .read(cx)
3061                .unwrap()
3062                .active_pane()
3063                .read(cx)
3064                .active_item()
3065                .and_then(|item| item.downcast::<ProjectSearchView>())
3066        }) else {
3067            panic!("Search view expected to appear after new search event trigger")
3068        };
3069        assert!(
3070            search_view_2 != search_view,
3071            "New search view should be open after `workspace::NewSearch` event"
3072        );
3073
3074        window.update(cx, |_, window, cx| {
3075            search_view.update(cx, |search_view, cx| {
3076                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO", "First search view should not have an updated query");
3077                    assert_eq!(
3078                        search_view
3079                            .results_editor
3080                            .update(cx, |editor, cx| editor.display_text(cx)),
3081                        "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
3082                        "Results of the first search view should not update too"
3083                    );
3084                    assert!(
3085                        !search_view.query_editor.focus_handle(cx).is_focused(window),
3086                        "Focus should be moved away from the first search view"
3087                    );
3088                });
3089        }).unwrap();
3090
3091        window.update(cx, |_, window, cx| {
3092            search_view_2.update(cx, |search_view_2, cx| {
3093                    assert_eq!(
3094                        search_view_2.query_editor.read(cx).text(cx),
3095                        "two",
3096                        "New search view should get the query from the text cursor was at during the event spawn (first search view's first result)"
3097                    );
3098                    assert_eq!(
3099                        search_view_2
3100                            .results_editor
3101                            .update(cx, |editor, cx| editor.display_text(cx)),
3102                        "",
3103                        "No search results should be in the 2nd view yet, as we did not spawn a search for it"
3104                    );
3105                    assert!(
3106                        search_view_2.query_editor.focus_handle(cx).is_focused(window),
3107                        "Focus should be moved into query editor of the new window"
3108                    );
3109                });
3110        }).unwrap();
3111
3112        window
3113            .update(cx, |_, window, cx| {
3114                search_view_2.update(cx, |search_view_2, cx| {
3115                    search_view_2.query_editor.update(cx, |query_editor, cx| {
3116                        query_editor.set_text("FOUR", window, cx)
3117                    });
3118                    search_view_2.search(cx);
3119                });
3120            })
3121            .unwrap();
3122
3123        cx.background_executor.run_until_parked();
3124        window.update(cx, |_, window, cx| {
3125            search_view_2.update(cx, |search_view_2, cx| {
3126                    assert_eq!(
3127                        search_view_2
3128                            .results_editor
3129                            .update(cx, |editor, cx| editor.display_text(cx)),
3130                        "\n\nconst FOUR: usize = one::ONE + three::THREE;",
3131                        "New search view with the updated query should have new search results"
3132                    );
3133                    assert!(
3134                        search_view_2.results_editor.focus_handle(cx).is_focused(window),
3135                        "Search view with mismatching query should be focused after search results are available",
3136                    );
3137                });
3138        }).unwrap();
3139
3140        cx.spawn(|mut cx| async move {
3141            window
3142                .update(&mut cx, |_, window, cx| {
3143                    window.dispatch_action(ToggleFocus.boxed_clone(), cx)
3144                })
3145                .unwrap();
3146        })
3147        .detach();
3148        cx.background_executor.run_until_parked();
3149        window.update(cx, |_, window, cx| {
3150            search_view_2.update(cx, |search_view_2, cx| {
3151                    assert!(
3152                        search_view_2.results_editor.focus_handle(cx).is_focused(window),
3153                        "Search view with matching query should switch focus to the results editor after the toggle focus event",
3154                    );
3155                });}).unwrap();
3156    }
3157
3158    #[gpui::test]
3159    async fn test_new_project_search_in_directory(cx: &mut TestAppContext) {
3160        init_test(cx);
3161
3162        let fs = FakeFs::new(cx.background_executor.clone());
3163        fs.insert_tree(
3164            path!("/dir"),
3165            json!({
3166                "a": {
3167                    "one.rs": "const ONE: usize = 1;",
3168                    "two.rs": "const TWO: usize = one::ONE + one::ONE;",
3169                },
3170                "b": {
3171                    "three.rs": "const THREE: usize = one::ONE + two::TWO;",
3172                    "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
3173                },
3174            }),
3175        )
3176        .await;
3177        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
3178        let worktree_id = project.read_with(cx, |project, cx| {
3179            project.worktrees(cx).next().unwrap().read(cx).id()
3180        });
3181        let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
3182        let workspace = window.root(cx).unwrap();
3183        let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
3184
3185        let active_item = cx.read(|cx| {
3186            workspace
3187                .read(cx)
3188                .active_pane()
3189                .read(cx)
3190                .active_item()
3191                .and_then(|item| item.downcast::<ProjectSearchView>())
3192        });
3193        assert!(
3194            active_item.is_none(),
3195            "Expected no search panel to be active"
3196        );
3197
3198        window
3199            .update(cx, move |workspace, window, cx| {
3200                assert_eq!(workspace.panes().len(), 1);
3201                workspace.panes()[0].update(cx, move |pane, cx| {
3202                    pane.toolbar()
3203                        .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3204                });
3205            })
3206            .unwrap();
3207
3208        let a_dir_entry = cx.update(|cx| {
3209            workspace
3210                .read(cx)
3211                .project()
3212                .read(cx)
3213                .entry_for_path(&(worktree_id, "a").into(), cx)
3214                .expect("no entry for /a/ directory")
3215                .clone()
3216        });
3217        assert!(a_dir_entry.is_dir());
3218        window
3219            .update(cx, |workspace, window, cx| {
3220                ProjectSearchView::new_search_in_directory(workspace, &a_dir_entry.path, window, cx)
3221            })
3222            .unwrap();
3223
3224        let Some(search_view) = cx.read(|cx| {
3225            workspace
3226                .read(cx)
3227                .active_pane()
3228                .read(cx)
3229                .active_item()
3230                .and_then(|item| item.downcast::<ProjectSearchView>())
3231        }) else {
3232            panic!("Search view expected to appear after new search in directory event trigger")
3233        };
3234        cx.background_executor.run_until_parked();
3235        window
3236            .update(cx, |_, window, cx| {
3237                search_view.update(cx, |search_view, cx| {
3238                    assert!(
3239                        search_view.query_editor.focus_handle(cx).is_focused(window),
3240                        "On new search in directory, focus should be moved into query editor"
3241                    );
3242                    search_view.excluded_files_editor.update(cx, |editor, cx| {
3243                        assert!(
3244                            editor.display_text(cx).is_empty(),
3245                            "New search in directory should not have any excluded files"
3246                        );
3247                    });
3248                    search_view.included_files_editor.update(cx, |editor, cx| {
3249                        assert_eq!(
3250                            editor.display_text(cx),
3251                            a_dir_entry.path.to_str().unwrap(),
3252                            "New search in directory should have included dir entry path"
3253                        );
3254                    });
3255                });
3256            })
3257            .unwrap();
3258        window
3259            .update(cx, |_, window, cx| {
3260                search_view.update(cx, |search_view, cx| {
3261                    search_view.query_editor.update(cx, |query_editor, cx| {
3262                        query_editor.set_text("const", window, cx)
3263                    });
3264                    search_view.search(cx);
3265                });
3266            })
3267            .unwrap();
3268        cx.background_executor.run_until_parked();
3269        window
3270            .update(cx, |_, _, cx| {
3271                search_view.update(cx, |search_view, cx| {
3272                    assert_eq!(
3273                search_view
3274                    .results_editor
3275                    .update(cx, |editor, cx| editor.display_text(cx)),
3276                "\n\nconst ONE: usize = 1;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
3277                "New search in directory should have a filter that matches a certain directory"
3278            );
3279                })
3280            })
3281            .unwrap();
3282    }
3283
3284    #[gpui::test]
3285    async fn test_search_query_history(cx: &mut TestAppContext) {
3286        init_test(cx);
3287
3288        let fs = FakeFs::new(cx.background_executor.clone());
3289        fs.insert_tree(
3290            path!("/dir"),
3291            json!({
3292                "one.rs": "const ONE: usize = 1;",
3293                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
3294                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
3295                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
3296            }),
3297        )
3298        .await;
3299        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
3300        let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
3301        let workspace = window.root(cx).unwrap();
3302        let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
3303
3304        window
3305            .update(cx, {
3306                let search_bar = search_bar.clone();
3307                |workspace, window, cx| {
3308                    assert_eq!(workspace.panes().len(), 1);
3309                    workspace.panes()[0].update(cx, |pane, cx| {
3310                        pane.toolbar()
3311                            .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3312                    });
3313
3314                    ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3315                }
3316            })
3317            .unwrap();
3318
3319        let search_view = cx.read(|cx| {
3320            workspace
3321                .read(cx)
3322                .active_pane()
3323                .read(cx)
3324                .active_item()
3325                .and_then(|item| item.downcast::<ProjectSearchView>())
3326                .expect("Search view expected to appear after new search event trigger")
3327        });
3328
3329        // Add 3 search items into the history + another unsubmitted one.
3330        window
3331            .update(cx, |_, window, cx| {
3332                search_view.update(cx, |search_view, cx| {
3333                    search_view.search_options = SearchOptions::CASE_SENSITIVE;
3334                    search_view.query_editor.update(cx, |query_editor, cx| {
3335                        query_editor.set_text("ONE", window, cx)
3336                    });
3337                    search_view.search(cx);
3338                });
3339            })
3340            .unwrap();
3341
3342        cx.background_executor.run_until_parked();
3343        window
3344            .update(cx, |_, window, cx| {
3345                search_view.update(cx, |search_view, cx| {
3346                    search_view.query_editor.update(cx, |query_editor, cx| {
3347                        query_editor.set_text("TWO", window, cx)
3348                    });
3349                    search_view.search(cx);
3350                });
3351            })
3352            .unwrap();
3353        cx.background_executor.run_until_parked();
3354        window
3355            .update(cx, |_, window, cx| {
3356                search_view.update(cx, |search_view, cx| {
3357                    search_view.query_editor.update(cx, |query_editor, cx| {
3358                        query_editor.set_text("THREE", window, cx)
3359                    });
3360                    search_view.search(cx);
3361                })
3362            })
3363            .unwrap();
3364        cx.background_executor.run_until_parked();
3365        window
3366            .update(cx, |_, window, cx| {
3367                search_view.update(cx, |search_view, cx| {
3368                    search_view.query_editor.update(cx, |query_editor, cx| {
3369                        query_editor.set_text("JUST_TEXT_INPUT", window, cx)
3370                    });
3371                })
3372            })
3373            .unwrap();
3374        cx.background_executor.run_until_parked();
3375
3376        // Ensure that the latest input with search settings is active.
3377        window
3378            .update(cx, |_, _, cx| {
3379                search_view.update(cx, |search_view, cx| {
3380                    assert_eq!(
3381                        search_view.query_editor.read(cx).text(cx),
3382                        "JUST_TEXT_INPUT"
3383                    );
3384                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3385                });
3386            })
3387            .unwrap();
3388
3389        // Next history query after the latest should set the query to the empty string.
3390        window
3391            .update(cx, |_, window, cx| {
3392                search_bar.update(cx, |search_bar, cx| {
3393                    search_bar.focus_search(window, cx);
3394                    search_bar.next_history_query(&NextHistoryQuery, window, cx);
3395                })
3396            })
3397            .unwrap();
3398        window
3399            .update(cx, |_, _, cx| {
3400                search_view.update(cx, |search_view, cx| {
3401                    assert_eq!(search_view.query_editor.read(cx).text(cx), "");
3402                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3403                });
3404            })
3405            .unwrap();
3406        window
3407            .update(cx, |_, window, cx| {
3408                search_bar.update(cx, |search_bar, cx| {
3409                    search_bar.focus_search(window, cx);
3410                    search_bar.next_history_query(&NextHistoryQuery, window, cx);
3411                })
3412            })
3413            .unwrap();
3414        window
3415            .update(cx, |_, _, cx| {
3416                search_view.update(cx, |search_view, cx| {
3417                    assert_eq!(search_view.query_editor.read(cx).text(cx), "");
3418                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3419                });
3420            })
3421            .unwrap();
3422
3423        // First previous query for empty current query should set the query to the latest submitted one.
3424        window
3425            .update(cx, |_, window, cx| {
3426                search_bar.update(cx, |search_bar, cx| {
3427                    search_bar.focus_search(window, cx);
3428                    search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3429                });
3430            })
3431            .unwrap();
3432        window
3433            .update(cx, |_, _, cx| {
3434                search_view.update(cx, |search_view, cx| {
3435                    assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
3436                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3437                });
3438            })
3439            .unwrap();
3440
3441        // Further previous items should go over the history in reverse order.
3442        window
3443            .update(cx, |_, window, cx| {
3444                search_bar.update(cx, |search_bar, cx| {
3445                    search_bar.focus_search(window, cx);
3446                    search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3447                });
3448            })
3449            .unwrap();
3450        window
3451            .update(cx, |_, _, cx| {
3452                search_view.update(cx, |search_view, cx| {
3453                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
3454                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3455                });
3456            })
3457            .unwrap();
3458
3459        // Previous items should never go behind the first history item.
3460        window
3461            .update(cx, |_, window, cx| {
3462                search_bar.update(cx, |search_bar, cx| {
3463                    search_bar.focus_search(window, cx);
3464                    search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3465                });
3466            })
3467            .unwrap();
3468        window
3469            .update(cx, |_, _, cx| {
3470                search_view.update(cx, |search_view, cx| {
3471                    assert_eq!(search_view.query_editor.read(cx).text(cx), "ONE");
3472                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3473                });
3474            })
3475            .unwrap();
3476        window
3477            .update(cx, |_, window, cx| {
3478                search_bar.update(cx, |search_bar, cx| {
3479                    search_bar.focus_search(window, cx);
3480                    search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3481                });
3482            })
3483            .unwrap();
3484        window
3485            .update(cx, |_, _, cx| {
3486                search_view.update(cx, |search_view, cx| {
3487                    assert_eq!(search_view.query_editor.read(cx).text(cx), "ONE");
3488                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3489                });
3490            })
3491            .unwrap();
3492
3493        // Next items should go over the history in the original order.
3494        window
3495            .update(cx, |_, window, cx| {
3496                search_bar.update(cx, |search_bar, cx| {
3497                    search_bar.focus_search(window, cx);
3498                    search_bar.next_history_query(&NextHistoryQuery, window, cx);
3499                });
3500            })
3501            .unwrap();
3502        window
3503            .update(cx, |_, _, cx| {
3504                search_view.update(cx, |search_view, cx| {
3505                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
3506                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3507                });
3508            })
3509            .unwrap();
3510
3511        window
3512            .update(cx, |_, window, cx| {
3513                search_view.update(cx, |search_view, cx| {
3514                    search_view.query_editor.update(cx, |query_editor, cx| {
3515                        query_editor.set_text("TWO_NEW", window, cx)
3516                    });
3517                    search_view.search(cx);
3518                });
3519            })
3520            .unwrap();
3521        cx.background_executor.run_until_parked();
3522        window
3523            .update(cx, |_, _, cx| {
3524                search_view.update(cx, |search_view, cx| {
3525                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO_NEW");
3526                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3527                });
3528            })
3529            .unwrap();
3530
3531        // New search input should add another entry to history and move the selection to the end of the history.
3532        window
3533            .update(cx, |_, window, cx| {
3534                search_bar.update(cx, |search_bar, cx| {
3535                    search_bar.focus_search(window, cx);
3536                    search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3537                });
3538            })
3539            .unwrap();
3540        window
3541            .update(cx, |_, _, cx| {
3542                search_view.update(cx, |search_view, cx| {
3543                    assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
3544                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3545                });
3546            })
3547            .unwrap();
3548        window
3549            .update(cx, |_, window, cx| {
3550                search_bar.update(cx, |search_bar, cx| {
3551                    search_bar.focus_search(window, cx);
3552                    search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3553                });
3554            })
3555            .unwrap();
3556        window
3557            .update(cx, |_, _, cx| {
3558                search_view.update(cx, |search_view, cx| {
3559                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
3560                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3561                });
3562            })
3563            .unwrap();
3564        window
3565            .update(cx, |_, window, cx| {
3566                search_bar.update(cx, |search_bar, cx| {
3567                    search_bar.focus_search(window, cx);
3568                    search_bar.next_history_query(&NextHistoryQuery, window, cx);
3569                });
3570            })
3571            .unwrap();
3572        window
3573            .update(cx, |_, _, cx| {
3574                search_view.update(cx, |search_view, cx| {
3575                    assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
3576                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3577                });
3578            })
3579            .unwrap();
3580        window
3581            .update(cx, |_, window, cx| {
3582                search_bar.update(cx, |search_bar, cx| {
3583                    search_bar.focus_search(window, cx);
3584                    search_bar.next_history_query(&NextHistoryQuery, window, cx);
3585                });
3586            })
3587            .unwrap();
3588        window
3589            .update(cx, |_, _, cx| {
3590                search_view.update(cx, |search_view, cx| {
3591                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO_NEW");
3592                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3593                });
3594            })
3595            .unwrap();
3596        window
3597            .update(cx, |_, window, cx| {
3598                search_bar.update(cx, |search_bar, cx| {
3599                    search_bar.focus_search(window, cx);
3600                    search_bar.next_history_query(&NextHistoryQuery, window, cx);
3601                });
3602            })
3603            .unwrap();
3604        window
3605            .update(cx, |_, _, cx| {
3606                search_view.update(cx, |search_view, cx| {
3607                    assert_eq!(search_view.query_editor.read(cx).text(cx), "");
3608                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3609                });
3610            })
3611            .unwrap();
3612    }
3613
3614    #[gpui::test]
3615    async fn test_search_query_history_with_multiple_views(cx: &mut TestAppContext) {
3616        init_test(cx);
3617
3618        let fs = FakeFs::new(cx.background_executor.clone());
3619        fs.insert_tree(
3620            path!("/dir"),
3621            json!({
3622                "one.rs": "const ONE: usize = 1;",
3623            }),
3624        )
3625        .await;
3626        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
3627        let worktree_id = project.update(cx, |this, cx| {
3628            this.worktrees(cx).next().unwrap().read(cx).id()
3629        });
3630
3631        let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
3632        let workspace = window.root(cx).unwrap();
3633
3634        let panes: Vec<_> = window
3635            .update(cx, |this, _, _| this.panes().to_owned())
3636            .unwrap();
3637
3638        let search_bar_1 = window.build_entity(cx, |_, _| ProjectSearchBar::new());
3639        let search_bar_2 = window.build_entity(cx, |_, _| ProjectSearchBar::new());
3640
3641        assert_eq!(panes.len(), 1);
3642        let first_pane = panes.first().cloned().unwrap();
3643        assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 0);
3644        window
3645            .update(cx, |workspace, window, cx| {
3646                workspace.open_path(
3647                    (worktree_id, "one.rs"),
3648                    Some(first_pane.downgrade()),
3649                    true,
3650                    window,
3651                    cx,
3652                )
3653            })
3654            .unwrap()
3655            .await
3656            .unwrap();
3657        assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 1);
3658
3659        // Add a project search item to the first pane
3660        window
3661            .update(cx, {
3662                let search_bar = search_bar_1.clone();
3663                |workspace, window, cx| {
3664                    first_pane.update(cx, |pane, cx| {
3665                        pane.toolbar()
3666                            .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3667                    });
3668
3669                    ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3670                }
3671            })
3672            .unwrap();
3673        let search_view_1 = cx.read(|cx| {
3674            workspace
3675                .read(cx)
3676                .active_item(cx)
3677                .and_then(|item| item.downcast::<ProjectSearchView>())
3678                .expect("Search view expected to appear after new search event trigger")
3679        });
3680
3681        let second_pane = window
3682            .update(cx, |workspace, window, cx| {
3683                workspace.split_and_clone(
3684                    first_pane.clone(),
3685                    workspace::SplitDirection::Right,
3686                    window,
3687                    cx,
3688                )
3689            })
3690            .unwrap()
3691            .unwrap();
3692        assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 1);
3693
3694        assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 1);
3695        assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 2);
3696
3697        // Add a project search item to the second pane
3698        window
3699            .update(cx, {
3700                let search_bar = search_bar_2.clone();
3701                let pane = second_pane.clone();
3702                move |workspace, window, cx| {
3703                    assert_eq!(workspace.panes().len(), 2);
3704                    pane.update(cx, |pane, cx| {
3705                        pane.toolbar()
3706                            .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3707                    });
3708
3709                    ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3710                }
3711            })
3712            .unwrap();
3713
3714        let search_view_2 = cx.read(|cx| {
3715            workspace
3716                .read(cx)
3717                .active_item(cx)
3718                .and_then(|item| item.downcast::<ProjectSearchView>())
3719                .expect("Search view expected to appear after new search event trigger")
3720        });
3721
3722        cx.run_until_parked();
3723        assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 2);
3724        assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 2);
3725
3726        let update_search_view =
3727            |search_view: &Entity<ProjectSearchView>, query: &str, cx: &mut TestAppContext| {
3728                window
3729                    .update(cx, |_, window, cx| {
3730                        search_view.update(cx, |search_view, cx| {
3731                            search_view.query_editor.update(cx, |query_editor, cx| {
3732                                query_editor.set_text(query, window, cx)
3733                            });
3734                            search_view.search(cx);
3735                        });
3736                    })
3737                    .unwrap();
3738            };
3739
3740        let active_query =
3741            |search_view: &Entity<ProjectSearchView>, cx: &mut TestAppContext| -> String {
3742                window
3743                    .update(cx, |_, _, cx| {
3744                        search_view.update(cx, |search_view, cx| {
3745                            search_view.query_editor.read(cx).text(cx)
3746                        })
3747                    })
3748                    .unwrap()
3749            };
3750
3751        let select_prev_history_item =
3752            |search_bar: &Entity<ProjectSearchBar>, cx: &mut TestAppContext| {
3753                window
3754                    .update(cx, |_, window, cx| {
3755                        search_bar.update(cx, |search_bar, cx| {
3756                            search_bar.focus_search(window, cx);
3757                            search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3758                        })
3759                    })
3760                    .unwrap();
3761            };
3762
3763        let select_next_history_item =
3764            |search_bar: &Entity<ProjectSearchBar>, cx: &mut TestAppContext| {
3765                window
3766                    .update(cx, |_, window, cx| {
3767                        search_bar.update(cx, |search_bar, cx| {
3768                            search_bar.focus_search(window, cx);
3769                            search_bar.next_history_query(&NextHistoryQuery, window, cx);
3770                        })
3771                    })
3772                    .unwrap();
3773            };
3774
3775        update_search_view(&search_view_1, "ONE", cx);
3776        cx.background_executor.run_until_parked();
3777
3778        update_search_view(&search_view_2, "TWO", cx);
3779        cx.background_executor.run_until_parked();
3780
3781        assert_eq!(active_query(&search_view_1, cx), "ONE");
3782        assert_eq!(active_query(&search_view_2, cx), "TWO");
3783
3784        // Selecting previous history item should select the query from search view 1.
3785        select_prev_history_item(&search_bar_2, cx);
3786        assert_eq!(active_query(&search_view_2, cx), "ONE");
3787
3788        // Selecting the previous history item should not change the query as it is already the first item.
3789        select_prev_history_item(&search_bar_2, cx);
3790        assert_eq!(active_query(&search_view_2, cx), "ONE");
3791
3792        // Changing the query in search view 2 should not affect the history of search view 1.
3793        assert_eq!(active_query(&search_view_1, cx), "ONE");
3794
3795        // Deploying a new search in search view 2
3796        update_search_view(&search_view_2, "THREE", cx);
3797        cx.background_executor.run_until_parked();
3798
3799        select_next_history_item(&search_bar_2, cx);
3800        assert_eq!(active_query(&search_view_2, cx), "");
3801
3802        select_prev_history_item(&search_bar_2, cx);
3803        assert_eq!(active_query(&search_view_2, cx), "THREE");
3804
3805        select_prev_history_item(&search_bar_2, cx);
3806        assert_eq!(active_query(&search_view_2, cx), "TWO");
3807
3808        select_prev_history_item(&search_bar_2, cx);
3809        assert_eq!(active_query(&search_view_2, cx), "ONE");
3810
3811        select_prev_history_item(&search_bar_2, cx);
3812        assert_eq!(active_query(&search_view_2, cx), "ONE");
3813
3814        // Search view 1 should now see the query from search view 2.
3815        assert_eq!(active_query(&search_view_1, cx), "ONE");
3816
3817        select_next_history_item(&search_bar_2, cx);
3818        assert_eq!(active_query(&search_view_2, cx), "TWO");
3819
3820        // Here is the new query from search view 2
3821        select_next_history_item(&search_bar_2, cx);
3822        assert_eq!(active_query(&search_view_2, cx), "THREE");
3823
3824        select_next_history_item(&search_bar_2, cx);
3825        assert_eq!(active_query(&search_view_2, cx), "");
3826
3827        select_next_history_item(&search_bar_1, cx);
3828        assert_eq!(active_query(&search_view_1, cx), "TWO");
3829
3830        select_next_history_item(&search_bar_1, cx);
3831        assert_eq!(active_query(&search_view_1, cx), "THREE");
3832
3833        select_next_history_item(&search_bar_1, cx);
3834        assert_eq!(active_query(&search_view_1, cx), "");
3835    }
3836
3837    #[gpui::test]
3838    async fn test_deploy_search_with_multiple_panes(cx: &mut TestAppContext) {
3839        init_test(cx);
3840
3841        // Setup 2 panes, both with a file open and one with a project search.
3842        let fs = FakeFs::new(cx.background_executor.clone());
3843        fs.insert_tree(
3844            path!("/dir"),
3845            json!({
3846                "one.rs": "const ONE: usize = 1;",
3847            }),
3848        )
3849        .await;
3850        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
3851        let worktree_id = project.update(cx, |this, cx| {
3852            this.worktrees(cx).next().unwrap().read(cx).id()
3853        });
3854        let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
3855        let panes: Vec<_> = window
3856            .update(cx, |this, _, _| this.panes().to_owned())
3857            .unwrap();
3858        assert_eq!(panes.len(), 1);
3859        let first_pane = panes.first().cloned().unwrap();
3860        assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 0);
3861        window
3862            .update(cx, |workspace, window, cx| {
3863                workspace.open_path(
3864                    (worktree_id, "one.rs"),
3865                    Some(first_pane.downgrade()),
3866                    true,
3867                    window,
3868                    cx,
3869                )
3870            })
3871            .unwrap()
3872            .await
3873            .unwrap();
3874        assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 1);
3875        let second_pane = window
3876            .update(cx, |workspace, window, cx| {
3877                workspace.split_and_clone(
3878                    first_pane.clone(),
3879                    workspace::SplitDirection::Right,
3880                    window,
3881                    cx,
3882                )
3883            })
3884            .unwrap()
3885            .unwrap();
3886        assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 1);
3887        assert!(
3888            window
3889                .update(cx, |_, window, cx| second_pane
3890                    .focus_handle(cx)
3891                    .contains_focused(window, cx))
3892                .unwrap()
3893        );
3894        let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
3895        window
3896            .update(cx, {
3897                let search_bar = search_bar.clone();
3898                let pane = first_pane.clone();
3899                move |workspace, window, cx| {
3900                    assert_eq!(workspace.panes().len(), 2);
3901                    pane.update(cx, move |pane, cx| {
3902                        pane.toolbar()
3903                            .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3904                    });
3905                }
3906            })
3907            .unwrap();
3908
3909        // Add a project search item to the second pane
3910        window
3911            .update(cx, {
3912                |workspace, window, cx| {
3913                    assert_eq!(workspace.panes().len(), 2);
3914                    second_pane.update(cx, |pane, cx| {
3915                        pane.toolbar()
3916                            .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3917                    });
3918
3919                    ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3920                }
3921            })
3922            .unwrap();
3923
3924        cx.run_until_parked();
3925        assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 2);
3926        assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 1);
3927
3928        // Focus the first pane
3929        window
3930            .update(cx, |workspace, window, cx| {
3931                assert_eq!(workspace.active_pane(), &second_pane);
3932                second_pane.update(cx, |this, cx| {
3933                    assert_eq!(this.active_item_index(), 1);
3934                    this.activate_previous_item(&Default::default(), window, cx);
3935                    assert_eq!(this.active_item_index(), 0);
3936                });
3937                workspace.activate_pane_in_direction(workspace::SplitDirection::Left, window, cx);
3938            })
3939            .unwrap();
3940        window
3941            .update(cx, |workspace, _, cx| {
3942                assert_eq!(workspace.active_pane(), &first_pane);
3943                assert_eq!(first_pane.read(cx).items_len(), 1);
3944                assert_eq!(second_pane.read(cx).items_len(), 2);
3945            })
3946            .unwrap();
3947
3948        // Deploy a new search
3949        cx.dispatch_action(window.into(), DeploySearch::find());
3950
3951        // Both panes should now have a project search in them
3952        window
3953            .update(cx, |workspace, window, cx| {
3954                assert_eq!(workspace.active_pane(), &first_pane);
3955                first_pane.read_with(cx, |this, _| {
3956                    assert_eq!(this.active_item_index(), 1);
3957                    assert_eq!(this.items_len(), 2);
3958                });
3959                second_pane.update(cx, |this, cx| {
3960                    assert!(!cx.focus_handle().contains_focused(window, cx));
3961                    assert_eq!(this.items_len(), 2);
3962                });
3963            })
3964            .unwrap();
3965
3966        // Focus the second pane's non-search item
3967        window
3968            .update(cx, |_workspace, window, cx| {
3969                second_pane.update(cx, |pane, cx| {
3970                    pane.activate_next_item(&Default::default(), window, cx)
3971                });
3972            })
3973            .unwrap();
3974
3975        // Deploy a new search
3976        cx.dispatch_action(window.into(), DeploySearch::find());
3977
3978        // The project search view should now be focused in the second pane
3979        // And the number of items should be unchanged.
3980        window
3981            .update(cx, |_workspace, _, cx| {
3982                second_pane.update(cx, |pane, _cx| {
3983                    assert!(
3984                        pane.active_item()
3985                            .unwrap()
3986                            .downcast::<ProjectSearchView>()
3987                            .is_some()
3988                    );
3989
3990                    assert_eq!(pane.items_len(), 2);
3991                });
3992            })
3993            .unwrap();
3994    }
3995
3996    #[gpui::test]
3997    async fn test_scroll_search_results_to_top(cx: &mut TestAppContext) {
3998        init_test(cx);
3999
4000        // We need many lines in the search results to be able to scroll the window
4001        let fs = FakeFs::new(cx.background_executor.clone());
4002        fs.insert_tree(
4003            path!("/dir"),
4004            json!({
4005                "1.txt": "\n\n\n\n\n A \n\n\n\n\n",
4006                "2.txt": "\n\n\n\n\n A \n\n\n\n\n",
4007                "3.rs": "\n\n\n\n\n A \n\n\n\n\n",
4008                "4.rs": "\n\n\n\n\n A \n\n\n\n\n",
4009                "5.rs": "\n\n\n\n\n A \n\n\n\n\n",
4010                "6.rs": "\n\n\n\n\n A \n\n\n\n\n",
4011                "7.rs": "\n\n\n\n\n A \n\n\n\n\n",
4012                "8.rs": "\n\n\n\n\n A \n\n\n\n\n",
4013                "9.rs": "\n\n\n\n\n A \n\n\n\n\n",
4014                "a.rs": "\n\n\n\n\n A \n\n\n\n\n",
4015                "b.rs": "\n\n\n\n\n B \n\n\n\n\n",
4016                "c.rs": "\n\n\n\n\n B \n\n\n\n\n",
4017                "d.rs": "\n\n\n\n\n B \n\n\n\n\n",
4018                "e.rs": "\n\n\n\n\n B \n\n\n\n\n",
4019                "f.rs": "\n\n\n\n\n B \n\n\n\n\n",
4020                "g.rs": "\n\n\n\n\n B \n\n\n\n\n",
4021                "h.rs": "\n\n\n\n\n B \n\n\n\n\n",
4022                "i.rs": "\n\n\n\n\n B \n\n\n\n\n",
4023                "j.rs": "\n\n\n\n\n B \n\n\n\n\n",
4024                "k.rs": "\n\n\n\n\n B \n\n\n\n\n",
4025            }),
4026        )
4027        .await;
4028        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
4029        let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
4030        let workspace = window.root(cx).unwrap();
4031        let search = cx.new(|cx| ProjectSearch::new(project, cx));
4032        let search_view = cx.add_window(|window, cx| {
4033            ProjectSearchView::new(workspace.downgrade(), search.clone(), window, cx, None)
4034        });
4035
4036        // First search
4037        perform_search(search_view, "A", cx);
4038        search_view
4039            .update(cx, |search_view, window, cx| {
4040                search_view.results_editor.update(cx, |results_editor, cx| {
4041                    // Results are correct and scrolled to the top
4042                    assert_eq!(
4043                        results_editor.display_text(cx).match_indices(" A ").count(),
4044                        10
4045                    );
4046                    assert_eq!(results_editor.scroll_position(cx), Point::default());
4047
4048                    // Scroll results all the way down
4049                    results_editor.scroll(
4050                        Point::new(0., f32::MAX),
4051                        Some(Axis::Vertical),
4052                        window,
4053                        cx,
4054                    );
4055                });
4056            })
4057            .expect("unable to update search view");
4058
4059        // Second search
4060        perform_search(search_view, "B", cx);
4061        search_view
4062            .update(cx, |search_view, _, cx| {
4063                search_view.results_editor.update(cx, |results_editor, cx| {
4064                    // Results are correct...
4065                    assert_eq!(
4066                        results_editor.display_text(cx).match_indices(" B ").count(),
4067                        10
4068                    );
4069                    // ...and scrolled back to the top
4070                    assert_eq!(results_editor.scroll_position(cx), Point::default());
4071                });
4072            })
4073            .expect("unable to update search view");
4074    }
4075
4076    #[gpui::test]
4077    async fn test_buffer_search_query_reused(cx: &mut TestAppContext) {
4078        init_test(cx);
4079
4080        let fs = FakeFs::new(cx.background_executor.clone());
4081        fs.insert_tree(
4082            path!("/dir"),
4083            json!({
4084                "one.rs": "const ONE: usize = 1;",
4085            }),
4086        )
4087        .await;
4088        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
4089        let worktree_id = project.update(cx, |this, cx| {
4090            this.worktrees(cx).next().unwrap().read(cx).id()
4091        });
4092        let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
4093        let workspace = window.root(cx).unwrap();
4094        let mut cx = VisualTestContext::from_window(*window.deref(), cx);
4095
4096        let editor = workspace
4097            .update_in(&mut cx, |workspace, window, cx| {
4098                workspace.open_path((worktree_id, "one.rs"), None, true, window, cx)
4099            })
4100            .await
4101            .unwrap()
4102            .downcast::<Editor>()
4103            .unwrap();
4104
4105        // Wait for the unstaged changes to be loaded
4106        cx.run_until_parked();
4107
4108        let buffer_search_bar = cx.new_window_entity(|window, cx| {
4109            let mut search_bar =
4110                BufferSearchBar::new(Some(project.read(cx).languages().clone()), window, cx);
4111            search_bar.set_active_pane_item(Some(&editor), window, cx);
4112            search_bar.show(window, cx);
4113            search_bar
4114        });
4115
4116        let panes: Vec<_> = window
4117            .update(&mut cx, |this, _, _| this.panes().to_owned())
4118            .unwrap();
4119        assert_eq!(panes.len(), 1);
4120        let pane = panes.first().cloned().unwrap();
4121        pane.update_in(&mut cx, |pane, window, cx| {
4122            pane.toolbar().update(cx, |toolbar, cx| {
4123                toolbar.add_item(buffer_search_bar.clone(), window, cx);
4124            })
4125        });
4126
4127        let buffer_search_query = "search bar query";
4128        buffer_search_bar
4129            .update_in(&mut cx, |buffer_search_bar, window, cx| {
4130                buffer_search_bar.focus_handle(cx).focus(window);
4131                buffer_search_bar.search(buffer_search_query, None, true, window, cx)
4132            })
4133            .await
4134            .unwrap();
4135
4136        workspace.update_in(&mut cx, |workspace, window, cx| {
4137            ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
4138        });
4139        cx.run_until_parked();
4140        let project_search_view = pane
4141            .read_with(&cx, |pane, _| {
4142                pane.active_item()
4143                    .and_then(|item| item.downcast::<ProjectSearchView>())
4144            })
4145            .expect("should open a project search view after spawning a new search");
4146        project_search_view.update(&mut cx, |search_view, cx| {
4147            assert_eq!(
4148                search_view.search_query_text(cx),
4149                buffer_search_query,
4150                "Project search should take the query from the buffer search bar since it got focused and had a query inside"
4151            );
4152        });
4153    }
4154
4155    fn init_test(cx: &mut TestAppContext) {
4156        cx.update(|cx| {
4157            let settings = SettingsStore::test(cx);
4158            cx.set_global(settings);
4159
4160            theme::init(theme::LoadThemes::JustBase, cx);
4161
4162            language::init(cx);
4163            client::init_settings(cx);
4164            editor::init(cx);
4165            workspace::init_settings(cx);
4166            Project::init_settings(cx);
4167            crate::init(cx);
4168        });
4169    }
4170
4171    fn perform_search(
4172        search_view: WindowHandle<ProjectSearchView>,
4173        text: impl Into<Arc<str>>,
4174        cx: &mut TestAppContext,
4175    ) {
4176        search_view
4177            .update(cx, |search_view, window, cx| {
4178                search_view.query_editor.update(cx, |query_editor, cx| {
4179                    query_editor.set_text(text, window, cx)
4180                });
4181                search_view.search(cx);
4182            })
4183            .unwrap();
4184        // Ensure editor highlights appear after the search is done
4185        cx.executor().advance_clock(
4186            editor::SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT + Duration::from_millis(100),
4187        );
4188        cx.background_executor.run_until_parked();
4189    }
4190}