project_search.rs

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