project_search.rs

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