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