project_search.rs

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