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, cx);
 958                    } else {
 959                        this.query_editor.focus_handle(cx).focus(window, cx);
 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, cx);
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, cx);
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 newest_anchor = results_editor.selections.newest_anchor().head();
1535        let buffer_snapshot = results_editor.buffer().read(cx).snapshot(cx);
1536        let new_index = self.entity.update(cx, |this, cx| {
1537            let new_index = active_match_index(
1538                Direction::Next,
1539                &this.match_ranges,
1540                &newest_anchor,
1541                &buffer_snapshot,
1542            );
1543
1544            self.highlight_matches(&this.match_ranges, new_index, cx);
1545            new_index
1546        });
1547
1548        if self.active_match_index != new_index {
1549            self.active_match_index = new_index;
1550            cx.notify();
1551        }
1552    }
1553
1554    #[ztracing::instrument(skip_all)]
1555    fn highlight_matches(
1556        &self,
1557        match_ranges: &[Range<Anchor>],
1558        active_index: Option<usize>,
1559        cx: &mut App,
1560    ) {
1561        self.results_editor.update(cx, |editor, cx| {
1562            editor.highlight_background::<Self>(
1563                match_ranges,
1564                move |index, theme| {
1565                    if active_index == Some(*index) {
1566                        theme.colors().search_active_match_background
1567                    } else {
1568                        theme.colors().search_match_background
1569                    }
1570                },
1571                cx,
1572            );
1573        });
1574    }
1575
1576    pub fn has_matches(&self) -> bool {
1577        self.active_match_index.is_some()
1578    }
1579
1580    fn landing_text_minor(&self, cx: &App) -> impl IntoElement {
1581        let focus_handle = self.focus_handle.clone();
1582        v_flex()
1583            .gap_1()
1584            .child(
1585                Label::new("Hit enter to search. For more options:")
1586                    .color(Color::Muted)
1587                    .mb_2(),
1588            )
1589            .child(
1590                Button::new("filter-paths", "Include/exclude specific paths")
1591                    .icon(IconName::Filter)
1592                    .icon_position(IconPosition::Start)
1593                    .icon_size(IconSize::Small)
1594                    .key_binding(KeyBinding::for_action_in(&ToggleFilters, &focus_handle, cx))
1595                    .on_click(|_event, window, cx| {
1596                        window.dispatch_action(ToggleFilters.boxed_clone(), cx)
1597                    }),
1598            )
1599            .child(
1600                Button::new("find-replace", "Find and replace")
1601                    .icon(IconName::Replace)
1602                    .icon_position(IconPosition::Start)
1603                    .icon_size(IconSize::Small)
1604                    .key_binding(KeyBinding::for_action_in(&ToggleReplace, &focus_handle, cx))
1605                    .on_click(|_event, window, cx| {
1606                        window.dispatch_action(ToggleReplace.boxed_clone(), cx)
1607                    }),
1608            )
1609            .child(
1610                Button::new("regex", "Match with regex")
1611                    .icon(IconName::Regex)
1612                    .icon_position(IconPosition::Start)
1613                    .icon_size(IconSize::Small)
1614                    .key_binding(KeyBinding::for_action_in(&ToggleRegex, &focus_handle, cx))
1615                    .on_click(|_event, window, cx| {
1616                        window.dispatch_action(ToggleRegex.boxed_clone(), cx)
1617                    }),
1618            )
1619            .child(
1620                Button::new("match-case", "Match case")
1621                    .icon(IconName::CaseSensitive)
1622                    .icon_position(IconPosition::Start)
1623                    .icon_size(IconSize::Small)
1624                    .key_binding(KeyBinding::for_action_in(
1625                        &ToggleCaseSensitive,
1626                        &focus_handle,
1627                        cx,
1628                    ))
1629                    .on_click(|_event, window, cx| {
1630                        window.dispatch_action(ToggleCaseSensitive.boxed_clone(), cx)
1631                    }),
1632            )
1633            .child(
1634                Button::new("match-whole-words", "Match whole words")
1635                    .icon(IconName::WholeWord)
1636                    .icon_position(IconPosition::Start)
1637                    .icon_size(IconSize::Small)
1638                    .key_binding(KeyBinding::for_action_in(
1639                        &ToggleWholeWord,
1640                        &focus_handle,
1641                        cx,
1642                    ))
1643                    .on_click(|_event, window, cx| {
1644                        window.dispatch_action(ToggleWholeWord.boxed_clone(), cx)
1645                    }),
1646            )
1647    }
1648
1649    fn border_color_for(&self, panel: InputPanel, cx: &App) -> Hsla {
1650        if self.panels_with_errors.contains_key(&panel) {
1651            Color::Error.color(cx)
1652        } else {
1653            cx.theme().colors().border
1654        }
1655    }
1656
1657    fn move_focus_to_results(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1658        if !self.results_editor.focus_handle(cx).is_focused(window)
1659            && !self.entity.read(cx).match_ranges.is_empty()
1660        {
1661            cx.stop_propagation();
1662            self.focus_results_editor(window, cx)
1663        }
1664    }
1665
1666    #[cfg(any(test, feature = "test-support"))]
1667    pub fn results_editor(&self) -> &Entity<Editor> {
1668        &self.results_editor
1669    }
1670
1671    fn adjust_query_regex_language(&self, cx: &mut App) {
1672        let enable = self.search_options.contains(SearchOptions::REGEX);
1673        let query_buffer = self
1674            .query_editor
1675            .read(cx)
1676            .buffer()
1677            .read(cx)
1678            .as_singleton()
1679            .expect("query editor should be backed by a singleton buffer");
1680        if enable {
1681            if let Some(regex_language) = self.regex_language.clone() {
1682                query_buffer.update(cx, |query_buffer, cx| {
1683                    query_buffer.set_language(Some(regex_language), cx);
1684                })
1685            }
1686        } else {
1687            query_buffer.update(cx, |query_buffer, cx| {
1688                query_buffer.set_language(None, cx);
1689            })
1690        }
1691    }
1692}
1693
1694fn buffer_search_query(
1695    workspace: &mut Workspace,
1696    item: &dyn ItemHandle,
1697    cx: &mut Context<Workspace>,
1698) -> Option<String> {
1699    let buffer_search_bar = workspace
1700        .pane_for(item)
1701        .and_then(|pane| {
1702            pane.read(cx)
1703                .toolbar()
1704                .read(cx)
1705                .item_of_type::<BufferSearchBar>()
1706        })?
1707        .read(cx);
1708    if buffer_search_bar.query_editor_focused() {
1709        let buffer_search_query = buffer_search_bar.query(cx);
1710        if !buffer_search_query.is_empty() {
1711            return Some(buffer_search_query);
1712        }
1713    }
1714    None
1715}
1716
1717impl Default for ProjectSearchBar {
1718    fn default() -> Self {
1719        Self::new()
1720    }
1721}
1722
1723impl ProjectSearchBar {
1724    pub fn new() -> Self {
1725        Self {
1726            active_project_search: None,
1727            subscription: None,
1728        }
1729    }
1730
1731    fn confirm(&mut self, _: &Confirm, window: &mut Window, cx: &mut Context<Self>) {
1732        if let Some(search_view) = self.active_project_search.as_ref() {
1733            search_view.update(cx, |search_view, cx| {
1734                if !search_view
1735                    .replacement_editor
1736                    .focus_handle(cx)
1737                    .is_focused(window)
1738                {
1739                    cx.stop_propagation();
1740                    search_view
1741                        .prompt_to_save_if_dirty_then_search(window, cx)
1742                        .detach_and_log_err(cx);
1743                }
1744            });
1745        }
1746    }
1747
1748    fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
1749        self.cycle_field(Direction::Next, window, cx);
1750    }
1751
1752    fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
1753        self.cycle_field(Direction::Prev, window, cx);
1754    }
1755
1756    fn focus_search(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1757        if let Some(search_view) = self.active_project_search.as_ref() {
1758            search_view.update(cx, |search_view, cx| {
1759                search_view.query_editor.focus_handle(cx).focus(window, cx);
1760            });
1761        }
1762    }
1763
1764    fn cycle_field(&mut self, direction: Direction, window: &mut Window, cx: &mut Context<Self>) {
1765        let active_project_search = match &self.active_project_search {
1766            Some(active_project_search) => active_project_search,
1767            None => return,
1768        };
1769
1770        active_project_search.update(cx, |project_view, cx| {
1771            let mut views = vec![project_view.query_editor.focus_handle(cx)];
1772            if project_view.replace_enabled {
1773                views.push(project_view.replacement_editor.focus_handle(cx));
1774            }
1775            if project_view.filters_enabled {
1776                views.extend([
1777                    project_view.included_files_editor.focus_handle(cx),
1778                    project_view.excluded_files_editor.focus_handle(cx),
1779                ]);
1780            }
1781            let current_index = match views.iter().position(|focus| focus.is_focused(window)) {
1782                Some(index) => index,
1783                None => return,
1784            };
1785
1786            let new_index = match direction {
1787                Direction::Next => (current_index + 1) % views.len(),
1788                Direction::Prev if current_index == 0 => views.len() - 1,
1789                Direction::Prev => (current_index - 1) % views.len(),
1790            };
1791            let next_focus_handle = &views[new_index];
1792            window.focus(next_focus_handle, cx);
1793            cx.stop_propagation();
1794        });
1795    }
1796
1797    pub(crate) fn toggle_search_option(
1798        &mut self,
1799        option: SearchOptions,
1800        window: &mut Window,
1801        cx: &mut Context<Self>,
1802    ) -> bool {
1803        if self.active_project_search.is_none() {
1804            return false;
1805        }
1806
1807        cx.spawn_in(window, async move |this, cx| {
1808            let task = this.update_in(cx, |this, window, cx| {
1809                let search_view = this.active_project_search.as_ref()?;
1810                search_view.update(cx, |search_view, cx| {
1811                    search_view.toggle_search_option(option, cx);
1812                    search_view
1813                        .entity
1814                        .read(cx)
1815                        .active_query
1816                        .is_some()
1817                        .then(|| search_view.prompt_to_save_if_dirty_then_search(window, cx))
1818                })
1819            })?;
1820            if let Some(task) = task {
1821                task.await?;
1822            }
1823            this.update(cx, |_, cx| {
1824                cx.notify();
1825            })?;
1826            anyhow::Ok(())
1827        })
1828        .detach();
1829        true
1830    }
1831
1832    fn toggle_replace(&mut self, _: &ToggleReplace, window: &mut Window, cx: &mut Context<Self>) {
1833        if let Some(search) = &self.active_project_search {
1834            search.update(cx, |this, cx| {
1835                this.replace_enabled = !this.replace_enabled;
1836                let editor_to_focus = if this.replace_enabled {
1837                    this.replacement_editor.focus_handle(cx)
1838                } else {
1839                    this.query_editor.focus_handle(cx)
1840                };
1841                window.focus(&editor_to_focus, cx);
1842                cx.notify();
1843            });
1844        }
1845    }
1846
1847    fn toggle_filters(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
1848        if let Some(search_view) = self.active_project_search.as_ref() {
1849            search_view.update(cx, |search_view, cx| {
1850                search_view.toggle_filters(cx);
1851                search_view
1852                    .included_files_editor
1853                    .update(cx, |_, cx| cx.notify());
1854                search_view
1855                    .excluded_files_editor
1856                    .update(cx, |_, cx| cx.notify());
1857                window.refresh();
1858                cx.notify();
1859            });
1860            cx.notify();
1861            true
1862        } else {
1863            false
1864        }
1865    }
1866
1867    fn toggle_opened_only(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
1868        if self.active_project_search.is_none() {
1869            return false;
1870        }
1871
1872        cx.spawn_in(window, async move |this, cx| {
1873            let task = this.update_in(cx, |this, window, cx| {
1874                let search_view = this.active_project_search.as_ref()?;
1875                search_view.update(cx, |search_view, cx| {
1876                    search_view.toggle_opened_only(window, cx);
1877                    search_view
1878                        .entity
1879                        .read(cx)
1880                        .active_query
1881                        .is_some()
1882                        .then(|| search_view.prompt_to_save_if_dirty_then_search(window, cx))
1883                })
1884            })?;
1885            if let Some(task) = task {
1886                task.await?;
1887            }
1888            this.update(cx, |_, cx| {
1889                cx.notify();
1890            })?;
1891            anyhow::Ok(())
1892        })
1893        .detach();
1894        true
1895    }
1896
1897    fn is_opened_only_enabled(&self, cx: &App) -> bool {
1898        if let Some(search_view) = self.active_project_search.as_ref() {
1899            search_view.read(cx).included_opened_only
1900        } else {
1901            false
1902        }
1903    }
1904
1905    fn move_focus_to_results(&self, window: &mut Window, cx: &mut Context<Self>) {
1906        if let Some(search_view) = self.active_project_search.as_ref() {
1907            search_view.update(cx, |search_view, cx| {
1908                search_view.move_focus_to_results(window, cx);
1909            });
1910            cx.notify();
1911        }
1912    }
1913
1914    fn next_history_query(
1915        &mut self,
1916        _: &NextHistoryQuery,
1917        window: &mut Window,
1918        cx: &mut Context<Self>,
1919    ) {
1920        if let Some(search_view) = self.active_project_search.as_ref() {
1921            search_view.update(cx, |search_view, cx| {
1922                for (editor, kind) in [
1923                    (search_view.query_editor.clone(), SearchInputKind::Query),
1924                    (
1925                        search_view.included_files_editor.clone(),
1926                        SearchInputKind::Include,
1927                    ),
1928                    (
1929                        search_view.excluded_files_editor.clone(),
1930                        SearchInputKind::Exclude,
1931                    ),
1932                ] {
1933                    if editor.focus_handle(cx).is_focused(window) {
1934                        let new_query = search_view.entity.update(cx, |model, cx| {
1935                            let project = model.project.clone();
1936
1937                            if let Some(new_query) = project.update(cx, |project, _| {
1938                                project
1939                                    .search_history_mut(kind)
1940                                    .next(model.cursor_mut(kind))
1941                                    .map(str::to_string)
1942                            }) {
1943                                new_query
1944                            } else {
1945                                model.cursor_mut(kind).reset();
1946                                String::new()
1947                            }
1948                        });
1949                        search_view.set_search_editor(kind, &new_query, window, cx);
1950                    }
1951                }
1952            });
1953        }
1954    }
1955
1956    fn previous_history_query(
1957        &mut self,
1958        _: &PreviousHistoryQuery,
1959        window: &mut Window,
1960        cx: &mut Context<Self>,
1961    ) {
1962        if let Some(search_view) = self.active_project_search.as_ref() {
1963            search_view.update(cx, |search_view, cx| {
1964                for (editor, kind) in [
1965                    (search_view.query_editor.clone(), SearchInputKind::Query),
1966                    (
1967                        search_view.included_files_editor.clone(),
1968                        SearchInputKind::Include,
1969                    ),
1970                    (
1971                        search_view.excluded_files_editor.clone(),
1972                        SearchInputKind::Exclude,
1973                    ),
1974                ] {
1975                    if editor.focus_handle(cx).is_focused(window) {
1976                        if editor.read(cx).text(cx).is_empty()
1977                            && let Some(new_query) = search_view
1978                                .entity
1979                                .read(cx)
1980                                .project
1981                                .read(cx)
1982                                .search_history(kind)
1983                                .current(search_view.entity.read(cx).cursor(kind))
1984                                .map(str::to_string)
1985                        {
1986                            search_view.set_search_editor(kind, &new_query, window, cx);
1987                            return;
1988                        }
1989
1990                        if let Some(new_query) = search_view.entity.update(cx, |model, cx| {
1991                            let project = model.project.clone();
1992                            project.update(cx, |project, _| {
1993                                project
1994                                    .search_history_mut(kind)
1995                                    .previous(model.cursor_mut(kind))
1996                                    .map(str::to_string)
1997                            })
1998                        }) {
1999                            search_view.set_search_editor(kind, &new_query, window, cx);
2000                        }
2001                    }
2002                }
2003            });
2004        }
2005    }
2006
2007    fn select_next_match(
2008        &mut self,
2009        _: &SelectNextMatch,
2010        window: &mut Window,
2011        cx: &mut Context<Self>,
2012    ) {
2013        if let Some(search) = self.active_project_search.as_ref() {
2014            search.update(cx, |this, cx| {
2015                this.select_match(Direction::Next, window, cx);
2016            })
2017        }
2018    }
2019
2020    fn select_prev_match(
2021        &mut self,
2022        _: &SelectPreviousMatch,
2023        window: &mut Window,
2024        cx: &mut Context<Self>,
2025    ) {
2026        if let Some(search) = self.active_project_search.as_ref() {
2027            search.update(cx, |this, cx| {
2028                this.select_match(Direction::Prev, window, cx);
2029            })
2030        }
2031    }
2032}
2033
2034impl Render for ProjectSearchBar {
2035    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2036        let Some(search) = self.active_project_search.clone() else {
2037            return div();
2038        };
2039        let search = search.read(cx);
2040        let focus_handle = search.focus_handle(cx);
2041
2042        let container_width = window.viewport_size().width;
2043        let input_width = SearchInputWidth::calc_width(container_width);
2044
2045        let input_base_styles = |panel: InputPanel| {
2046            input_base_styles(search.border_color_for(panel, cx), |div| match panel {
2047                InputPanel::Query | InputPanel::Replacement => div.w(input_width),
2048                InputPanel::Include | InputPanel::Exclude => div.flex_grow(),
2049            })
2050        };
2051        let theme_colors = cx.theme().colors();
2052        let project_search = search.entity.read(cx);
2053        let limit_reached = project_search.limit_reached;
2054
2055        let color_override = match (
2056            &project_search.pending_search,
2057            project_search.no_results,
2058            &project_search.active_query,
2059            &project_search.last_search_query_text,
2060        ) {
2061            (None, Some(true), Some(q), Some(p)) if q.as_str() == p => Some(Color::Error),
2062            _ => None,
2063        };
2064
2065        let match_text = search
2066            .active_match_index
2067            .and_then(|index| {
2068                let index = index + 1;
2069                let match_quantity = project_search.match_ranges.len();
2070                if match_quantity > 0 {
2071                    debug_assert!(match_quantity >= index);
2072                    if limit_reached {
2073                        Some(format!("{index}/{match_quantity}+"))
2074                    } else {
2075                        Some(format!("{index}/{match_quantity}"))
2076                    }
2077                } else {
2078                    None
2079                }
2080            })
2081            .unwrap_or_else(|| "0/0".to_string());
2082
2083        let query_focus = search.query_editor.focus_handle(cx);
2084
2085        let query_column = input_base_styles(InputPanel::Query)
2086            .on_action(cx.listener(|this, action, window, cx| this.confirm(action, window, cx)))
2087            .on_action(cx.listener(|this, action, window, cx| {
2088                this.previous_history_query(action, window, cx)
2089            }))
2090            .on_action(
2091                cx.listener(|this, action, window, cx| this.next_history_query(action, window, cx)),
2092            )
2093            .child(render_text_input(&search.query_editor, color_override, cx))
2094            .child(
2095                h_flex()
2096                    .gap_1()
2097                    .child(SearchOption::CaseSensitive.as_button(
2098                        search.search_options,
2099                        SearchSource::Project(cx),
2100                        focus_handle.clone(),
2101                    ))
2102                    .child(SearchOption::WholeWord.as_button(
2103                        search.search_options,
2104                        SearchSource::Project(cx),
2105                        focus_handle.clone(),
2106                    ))
2107                    .child(SearchOption::Regex.as_button(
2108                        search.search_options,
2109                        SearchSource::Project(cx),
2110                        focus_handle.clone(),
2111                    )),
2112            );
2113
2114        let matches_column = h_flex()
2115            .ml_1()
2116            .pl_1p5()
2117            .border_l_1()
2118            .border_color(theme_colors.border_variant)
2119            .child(render_action_button(
2120                "project-search-nav-button",
2121                IconName::ChevronLeft,
2122                search
2123                    .active_match_index
2124                    .is_none()
2125                    .then_some(ActionButtonState::Disabled),
2126                "Select Previous Match",
2127                &SelectPreviousMatch,
2128                query_focus.clone(),
2129            ))
2130            .child(render_action_button(
2131                "project-search-nav-button",
2132                IconName::ChevronRight,
2133                search
2134                    .active_match_index
2135                    .is_none()
2136                    .then_some(ActionButtonState::Disabled),
2137                "Select Next Match",
2138                &SelectNextMatch,
2139                query_focus,
2140            ))
2141            .child(
2142                div()
2143                    .id("matches")
2144                    .ml_2()
2145                    .min_w(rems_from_px(40.))
2146                    .child(Label::new(match_text).size(LabelSize::Small).color(
2147                        if search.active_match_index.is_some() {
2148                            Color::Default
2149                        } else {
2150                            Color::Disabled
2151                        },
2152                    ))
2153                    .when(limit_reached, |el| {
2154                        el.tooltip(Tooltip::text(
2155                            "Search limits reached.\nTry narrowing your search.",
2156                        ))
2157                    }),
2158            );
2159
2160        let mode_column = h_flex()
2161            .gap_1()
2162            .min_w_64()
2163            .child(
2164                IconButton::new("project-search-filter-button", IconName::Filter)
2165                    .shape(IconButtonShape::Square)
2166                    .tooltip(|_window, cx| {
2167                        Tooltip::for_action("Toggle Filters", &ToggleFilters, cx)
2168                    })
2169                    .on_click(cx.listener(|this, _, window, cx| {
2170                        this.toggle_filters(window, cx);
2171                    }))
2172                    .toggle_state(
2173                        self.active_project_search
2174                            .as_ref()
2175                            .map(|search| search.read(cx).filters_enabled)
2176                            .unwrap_or_default(),
2177                    )
2178                    .tooltip({
2179                        let focus_handle = focus_handle.clone();
2180                        move |_window, cx| {
2181                            Tooltip::for_action_in(
2182                                "Toggle Filters",
2183                                &ToggleFilters,
2184                                &focus_handle,
2185                                cx,
2186                            )
2187                        }
2188                    }),
2189            )
2190            .child(render_action_button(
2191                "project-search",
2192                IconName::Replace,
2193                self.active_project_search
2194                    .as_ref()
2195                    .map(|search| search.read(cx).replace_enabled)
2196                    .and_then(|enabled| enabled.then_some(ActionButtonState::Toggled)),
2197                "Toggle Replace",
2198                &ToggleReplace,
2199                focus_handle.clone(),
2200            ))
2201            .child(matches_column);
2202
2203        let search_line = h_flex()
2204            .w_full()
2205            .gap_2()
2206            .child(query_column)
2207            .child(mode_column);
2208
2209        let replace_line = search.replace_enabled.then(|| {
2210            let replace_column = input_base_styles(InputPanel::Replacement)
2211                .child(render_text_input(&search.replacement_editor, None, cx));
2212
2213            let focus_handle = search.replacement_editor.read(cx).focus_handle(cx);
2214
2215            let replace_actions = h_flex()
2216                .min_w_64()
2217                .gap_1()
2218                .child(render_action_button(
2219                    "project-search-replace-button",
2220                    IconName::ReplaceNext,
2221                    Default::default(),
2222                    "Replace Next Match",
2223                    &ReplaceNext,
2224                    focus_handle.clone(),
2225                ))
2226                .child(render_action_button(
2227                    "project-search-replace-button",
2228                    IconName::ReplaceAll,
2229                    Default::default(),
2230                    "Replace All Matches",
2231                    &ReplaceAll,
2232                    focus_handle,
2233                ));
2234
2235            h_flex()
2236                .w_full()
2237                .gap_2()
2238                .child(replace_column)
2239                .child(replace_actions)
2240        });
2241
2242        let filter_line = search.filters_enabled.then(|| {
2243            let include = input_base_styles(InputPanel::Include)
2244                .on_action(cx.listener(|this, action, window, cx| {
2245                    this.previous_history_query(action, window, cx)
2246                }))
2247                .on_action(cx.listener(|this, action, window, cx| {
2248                    this.next_history_query(action, window, cx)
2249                }))
2250                .child(render_text_input(&search.included_files_editor, None, cx));
2251            let exclude = input_base_styles(InputPanel::Exclude)
2252                .on_action(cx.listener(|this, action, window, cx| {
2253                    this.previous_history_query(action, window, cx)
2254                }))
2255                .on_action(cx.listener(|this, action, window, cx| {
2256                    this.next_history_query(action, window, cx)
2257                }))
2258                .child(render_text_input(&search.excluded_files_editor, None, cx));
2259            let mode_column = h_flex()
2260                .gap_1()
2261                .min_w_64()
2262                .child(
2263                    IconButton::new("project-search-opened-only", IconName::FolderSearch)
2264                        .shape(IconButtonShape::Square)
2265                        .toggle_state(self.is_opened_only_enabled(cx))
2266                        .tooltip(Tooltip::text("Only Search Open Files"))
2267                        .on_click(cx.listener(|this, _, window, cx| {
2268                            this.toggle_opened_only(window, cx);
2269                        })),
2270                )
2271                .child(SearchOption::IncludeIgnored.as_button(
2272                    search.search_options,
2273                    SearchSource::Project(cx),
2274                    focus_handle.clone(),
2275                ));
2276            h_flex()
2277                .w_full()
2278                .gap_2()
2279                .child(
2280                    h_flex()
2281                        .gap_2()
2282                        .w(input_width)
2283                        .child(include)
2284                        .child(exclude),
2285                )
2286                .child(mode_column)
2287        });
2288
2289        let mut key_context = KeyContext::default();
2290        key_context.add("ProjectSearchBar");
2291        if search
2292            .replacement_editor
2293            .focus_handle(cx)
2294            .is_focused(window)
2295        {
2296            key_context.add("in_replace");
2297        }
2298
2299        let query_error_line = search
2300            .panels_with_errors
2301            .get(&InputPanel::Query)
2302            .map(|error| {
2303                Label::new(error)
2304                    .size(LabelSize::Small)
2305                    .color(Color::Error)
2306                    .mt_neg_1()
2307                    .ml_2()
2308            });
2309
2310        let filter_error_line = search
2311            .panels_with_errors
2312            .get(&InputPanel::Include)
2313            .or_else(|| search.panels_with_errors.get(&InputPanel::Exclude))
2314            .map(|error| {
2315                Label::new(error)
2316                    .size(LabelSize::Small)
2317                    .color(Color::Error)
2318                    .mt_neg_1()
2319                    .ml_2()
2320            });
2321
2322        v_flex()
2323            .gap_2()
2324            .py(px(1.0))
2325            .w_full()
2326            .key_context(key_context)
2327            .on_action(cx.listener(|this, _: &ToggleFocus, window, cx| {
2328                this.move_focus_to_results(window, cx)
2329            }))
2330            .on_action(cx.listener(|this, _: &ToggleFilters, window, cx| {
2331                this.toggle_filters(window, cx);
2332            }))
2333            .capture_action(cx.listener(Self::tab))
2334            .capture_action(cx.listener(Self::backtab))
2335            .on_action(cx.listener(|this, action, window, cx| this.confirm(action, window, cx)))
2336            .on_action(cx.listener(|this, action, window, cx| {
2337                this.toggle_replace(action, window, cx);
2338            }))
2339            .on_action(cx.listener(|this, _: &ToggleWholeWord, window, cx| {
2340                this.toggle_search_option(SearchOptions::WHOLE_WORD, window, cx);
2341            }))
2342            .on_action(cx.listener(|this, _: &ToggleCaseSensitive, window, cx| {
2343                this.toggle_search_option(SearchOptions::CASE_SENSITIVE, window, cx);
2344            }))
2345            .on_action(cx.listener(|this, action, window, cx| {
2346                if let Some(search) = this.active_project_search.as_ref() {
2347                    search.update(cx, |this, cx| {
2348                        this.replace_next(action, window, cx);
2349                    })
2350                }
2351            }))
2352            .on_action(cx.listener(|this, action, window, cx| {
2353                if let Some(search) = this.active_project_search.as_ref() {
2354                    search.update(cx, |this, cx| {
2355                        this.replace_all(action, window, cx);
2356                    })
2357                }
2358            }))
2359            .when(search.filters_enabled, |this| {
2360                this.on_action(cx.listener(|this, _: &ToggleIncludeIgnored, window, cx| {
2361                    this.toggle_search_option(SearchOptions::INCLUDE_IGNORED, window, cx);
2362                }))
2363            })
2364            .on_action(cx.listener(Self::select_next_match))
2365            .on_action(cx.listener(Self::select_prev_match))
2366            .child(search_line)
2367            .children(query_error_line)
2368            .children(replace_line)
2369            .children(filter_line)
2370            .children(filter_error_line)
2371    }
2372}
2373
2374impl EventEmitter<ToolbarItemEvent> for ProjectSearchBar {}
2375
2376impl ToolbarItemView for ProjectSearchBar {
2377    fn set_active_pane_item(
2378        &mut self,
2379        active_pane_item: Option<&dyn ItemHandle>,
2380        _: &mut Window,
2381        cx: &mut Context<Self>,
2382    ) -> ToolbarItemLocation {
2383        cx.notify();
2384        self.subscription = None;
2385        self.active_project_search = None;
2386        if let Some(search) = active_pane_item.and_then(|i| i.downcast::<ProjectSearchView>()) {
2387            self.subscription = Some(cx.observe(&search, |_, _, cx| cx.notify()));
2388            self.active_project_search = Some(search);
2389            ToolbarItemLocation::PrimaryLeft {}
2390        } else {
2391            ToolbarItemLocation::Hidden
2392        }
2393    }
2394}
2395
2396fn register_workspace_action<A: Action>(
2397    workspace: &mut Workspace,
2398    callback: fn(&mut ProjectSearchBar, &A, &mut Window, &mut Context<ProjectSearchBar>),
2399) {
2400    workspace.register_action(move |workspace, action: &A, window, cx| {
2401        if workspace.has_active_modal(window, cx) && !workspace.hide_modal(window, cx) {
2402            cx.propagate();
2403            return;
2404        }
2405
2406        workspace.active_pane().update(cx, |pane, cx| {
2407            pane.toolbar().update(cx, move |workspace, cx| {
2408                if let Some(search_bar) = workspace.item_of_type::<ProjectSearchBar>() {
2409                    search_bar.update(cx, move |search_bar, cx| {
2410                        if search_bar.active_project_search.is_some() {
2411                            callback(search_bar, action, window, cx);
2412                            cx.notify();
2413                        } else {
2414                            cx.propagate();
2415                        }
2416                    });
2417                }
2418            });
2419        })
2420    });
2421}
2422
2423fn register_workspace_action_for_present_search<A: Action>(
2424    workspace: &mut Workspace,
2425    callback: fn(&mut Workspace, &A, &mut Window, &mut Context<Workspace>),
2426) {
2427    workspace.register_action(move |workspace, action: &A, window, cx| {
2428        if workspace.has_active_modal(window, cx) && !workspace.hide_modal(window, cx) {
2429            cx.propagate();
2430            return;
2431        }
2432
2433        let should_notify = workspace
2434            .active_pane()
2435            .read(cx)
2436            .toolbar()
2437            .read(cx)
2438            .item_of_type::<ProjectSearchBar>()
2439            .map(|search_bar| search_bar.read(cx).active_project_search.is_some())
2440            .unwrap_or(false);
2441        if should_notify {
2442            callback(workspace, action, window, cx);
2443            cx.notify();
2444        } else {
2445            cx.propagate();
2446        }
2447    });
2448}
2449
2450#[cfg(any(test, feature = "test-support"))]
2451pub fn perform_project_search(
2452    search_view: &Entity<ProjectSearchView>,
2453    text: impl Into<std::sync::Arc<str>>,
2454    cx: &mut gpui::VisualTestContext,
2455) {
2456    cx.run_until_parked();
2457    search_view.update_in(cx, |search_view, window, cx| {
2458        search_view.query_editor.update(cx, |query_editor, cx| {
2459            query_editor.set_text(text, window, cx)
2460        });
2461        search_view.search(cx);
2462    });
2463    cx.run_until_parked();
2464}
2465
2466#[cfg(test)]
2467pub mod tests {
2468    use std::{
2469        ops::Deref as _,
2470        path::PathBuf,
2471        sync::{
2472            Arc,
2473            atomic::{self, AtomicUsize},
2474        },
2475        time::Duration,
2476    };
2477
2478    use super::*;
2479    use editor::{DisplayPoint, display_map::DisplayRow};
2480    use gpui::{Action, TestAppContext, VisualTestContext, WindowHandle};
2481    use language::{FakeLspAdapter, rust_lang};
2482    use pretty_assertions::assert_eq;
2483    use project::FakeFs;
2484    use serde_json::json;
2485    use settings::{
2486        InlayHintSettingsContent, SettingsStore, ThemeColorsContent, ThemeStyleContent,
2487    };
2488    use util::{path, paths::PathStyle, rel_path::rel_path};
2489    use util_macros::perf;
2490    use workspace::DeploySearch;
2491
2492    #[perf]
2493    #[gpui::test]
2494    async fn test_project_search(cx: &mut TestAppContext) {
2495        fn dp(row: u32, col: u32) -> DisplayPoint {
2496            DisplayPoint::new(DisplayRow(row), col)
2497        }
2498
2499        fn assert_active_match_index(
2500            search_view: &WindowHandle<ProjectSearchView>,
2501            cx: &mut TestAppContext,
2502            expected_index: usize,
2503        ) {
2504            search_view
2505                .update(cx, |search_view, _window, _cx| {
2506                    assert_eq!(search_view.active_match_index, Some(expected_index));
2507                })
2508                .unwrap();
2509        }
2510
2511        fn assert_selection_range(
2512            search_view: &WindowHandle<ProjectSearchView>,
2513            cx: &mut TestAppContext,
2514            expected_range: Range<DisplayPoint>,
2515        ) {
2516            search_view
2517                .update(cx, |search_view, _window, cx| {
2518                    assert_eq!(
2519                        search_view.results_editor.update(cx, |editor, cx| editor
2520                            .selections
2521                            .display_ranges(&editor.display_snapshot(cx))),
2522                        [expected_range]
2523                    );
2524                })
2525                .unwrap();
2526        }
2527
2528        fn assert_highlights(
2529            search_view: &WindowHandle<ProjectSearchView>,
2530            cx: &mut TestAppContext,
2531            expected_highlights: Vec<(Range<DisplayPoint>, &str)>,
2532        ) {
2533            search_view
2534                .update(cx, |search_view, window, cx| {
2535                    let match_bg = cx.theme().colors().search_match_background;
2536                    let active_match_bg = cx.theme().colors().search_active_match_background;
2537                    let selection_bg = cx
2538                        .theme()
2539                        .colors()
2540                        .editor_document_highlight_bracket_background;
2541
2542                    let highlights: Vec<_> = expected_highlights
2543                        .into_iter()
2544                        .map(|(range, color_type)| {
2545                            let color = match color_type {
2546                                "active" => active_match_bg,
2547                                "match" => match_bg,
2548                                "selection" => selection_bg,
2549                                _ => panic!("Unknown color type"),
2550                            };
2551                            (range, color)
2552                        })
2553                        .collect();
2554
2555                    assert_eq!(
2556                        search_view.results_editor.update(cx, |editor, cx| editor
2557                            .all_text_background_highlights(window, cx)),
2558                        highlights.as_slice()
2559                    );
2560                })
2561                .unwrap();
2562        }
2563
2564        fn select_match(
2565            search_view: &WindowHandle<ProjectSearchView>,
2566            cx: &mut TestAppContext,
2567            direction: Direction,
2568        ) {
2569            search_view
2570                .update(cx, |search_view, window, cx| {
2571                    search_view.select_match(direction, window, cx);
2572                })
2573                .unwrap();
2574        }
2575
2576        init_test(cx);
2577
2578        // Override active search match color since the fallback theme uses the same color
2579        // for normal search match and active one, which can make this test less robust.
2580        cx.update(|cx| {
2581            SettingsStore::update_global(cx, |settings, cx| {
2582                settings.update_user_settings(cx, |settings| {
2583                    settings.theme.experimental_theme_overrides = Some(ThemeStyleContent {
2584                        colors: ThemeColorsContent {
2585                            search_active_match_background: Some("#ff0000ff".to_string()),
2586                            ..Default::default()
2587                        },
2588                        ..Default::default()
2589                    });
2590                });
2591            });
2592        });
2593
2594        let fs = FakeFs::new(cx.background_executor.clone());
2595        fs.insert_tree(
2596            path!("/dir"),
2597            json!({
2598                "one.rs": "const ONE: usize = 1;",
2599                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2600                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2601                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2602            }),
2603        )
2604        .await;
2605        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
2606        let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
2607        let workspace = window.root(cx).unwrap();
2608        let search = cx.new(|cx| ProjectSearch::new(project.clone(), cx));
2609        let search_view = cx.add_window(|window, cx| {
2610            ProjectSearchView::new(workspace.downgrade(), search.clone(), window, cx, None)
2611        });
2612
2613        perform_search(search_view, "TWO", cx);
2614        cx.run_until_parked();
2615
2616        search_view
2617            .update(cx, |search_view, _window, cx| {
2618                assert_eq!(
2619                    search_view
2620                        .results_editor
2621                        .update(cx, |editor, cx| editor.display_text(cx)),
2622                    "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;"
2623                );
2624            })
2625            .unwrap();
2626
2627        assert_active_match_index(&search_view, cx, 0);
2628        assert_selection_range(&search_view, cx, dp(2, 32)..dp(2, 35));
2629        assert_highlights(
2630            &search_view,
2631            cx,
2632            vec![
2633                (dp(2, 32)..dp(2, 35), "active"),
2634                (dp(2, 37)..dp(2, 40), "selection"),
2635                (dp(2, 37)..dp(2, 40), "match"),
2636                (dp(5, 6)..dp(5, 9), "match"),
2637                // TODO: we should be getting selection highlight here after project search
2638                // but for some reason we are not getting it here
2639            ],
2640        );
2641        select_match(&search_view, cx, Direction::Next);
2642        cx.run_until_parked();
2643
2644        assert_active_match_index(&search_view, cx, 1);
2645        assert_selection_range(&search_view, cx, dp(2, 37)..dp(2, 40));
2646        assert_highlights(
2647            &search_view,
2648            cx,
2649            vec![
2650                (dp(2, 32)..dp(2, 35), "selection"),
2651                (dp(2, 32)..dp(2, 35), "match"),
2652                (dp(2, 37)..dp(2, 40), "active"),
2653                (dp(5, 6)..dp(5, 9), "selection"),
2654                (dp(5, 6)..dp(5, 9), "match"),
2655            ],
2656        );
2657        select_match(&search_view, cx, Direction::Next);
2658        cx.run_until_parked();
2659
2660        assert_active_match_index(&search_view, cx, 2);
2661        assert_selection_range(&search_view, cx, dp(5, 6)..dp(5, 9));
2662        assert_highlights(
2663            &search_view,
2664            cx,
2665            vec![
2666                (dp(2, 32)..dp(2, 35), "selection"),
2667                (dp(2, 32)..dp(2, 35), "match"),
2668                (dp(2, 37)..dp(2, 40), "selection"),
2669                (dp(2, 37)..dp(2, 40), "match"),
2670                (dp(5, 6)..dp(5, 9), "active"),
2671            ],
2672        );
2673        select_match(&search_view, cx, Direction::Next);
2674        cx.run_until_parked();
2675
2676        assert_active_match_index(&search_view, cx, 0);
2677        assert_selection_range(&search_view, cx, dp(2, 32)..dp(2, 35));
2678        assert_highlights(
2679            &search_view,
2680            cx,
2681            vec![
2682                (dp(2, 32)..dp(2, 35), "active"),
2683                (dp(2, 37)..dp(2, 40), "selection"),
2684                (dp(2, 37)..dp(2, 40), "match"),
2685                (dp(5, 6)..dp(5, 9), "selection"),
2686                (dp(5, 6)..dp(5, 9), "match"),
2687            ],
2688        );
2689        select_match(&search_view, cx, Direction::Prev);
2690        cx.run_until_parked();
2691
2692        assert_active_match_index(&search_view, cx, 2);
2693        assert_selection_range(&search_view, cx, dp(5, 6)..dp(5, 9));
2694        assert_highlights(
2695            &search_view,
2696            cx,
2697            vec![
2698                (dp(2, 32)..dp(2, 35), "selection"),
2699                (dp(2, 32)..dp(2, 35), "match"),
2700                (dp(2, 37)..dp(2, 40), "selection"),
2701                (dp(2, 37)..dp(2, 40), "match"),
2702                (dp(5, 6)..dp(5, 9), "active"),
2703            ],
2704        );
2705        select_match(&search_view, cx, Direction::Prev);
2706        cx.run_until_parked();
2707
2708        assert_active_match_index(&search_view, cx, 1);
2709        assert_selection_range(&search_view, cx, dp(2, 37)..dp(2, 40));
2710        assert_highlights(
2711            &search_view,
2712            cx,
2713            vec![
2714                (dp(2, 32)..dp(2, 35), "selection"),
2715                (dp(2, 32)..dp(2, 35), "match"),
2716                (dp(2, 37)..dp(2, 40), "active"),
2717                (dp(5, 6)..dp(5, 9), "selection"),
2718                (dp(5, 6)..dp(5, 9), "match"),
2719            ],
2720        );
2721    }
2722
2723    #[perf]
2724    #[gpui::test]
2725    async fn test_deploy_project_search_focus(cx: &mut TestAppContext) {
2726        init_test(cx);
2727
2728        let fs = FakeFs::new(cx.background_executor.clone());
2729        fs.insert_tree(
2730            "/dir",
2731            json!({
2732                "one.rs": "const ONE: usize = 1;",
2733                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2734                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2735                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2736            }),
2737        )
2738        .await;
2739        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
2740        let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
2741        let workspace = window;
2742        let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
2743
2744        let active_item = cx.read(|cx| {
2745            workspace
2746                .read(cx)
2747                .unwrap()
2748                .active_pane()
2749                .read(cx)
2750                .active_item()
2751                .and_then(|item| item.downcast::<ProjectSearchView>())
2752        });
2753        assert!(
2754            active_item.is_none(),
2755            "Expected no search panel to be active"
2756        );
2757
2758        window
2759            .update(cx, move |workspace, window, cx| {
2760                assert_eq!(workspace.panes().len(), 1);
2761                workspace.panes()[0].update(cx, |pane, cx| {
2762                    pane.toolbar()
2763                        .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
2764                });
2765
2766                ProjectSearchView::deploy_search(
2767                    workspace,
2768                    &workspace::DeploySearch::find(),
2769                    window,
2770                    cx,
2771                )
2772            })
2773            .unwrap();
2774
2775        let Some(search_view) = cx.read(|cx| {
2776            workspace
2777                .read(cx)
2778                .unwrap()
2779                .active_pane()
2780                .read(cx)
2781                .active_item()
2782                .and_then(|item| item.downcast::<ProjectSearchView>())
2783        }) else {
2784            panic!("Search view expected to appear after new search event trigger")
2785        };
2786
2787        cx.spawn(|mut cx| async move {
2788            window
2789                .update(&mut cx, |_, window, cx| {
2790                    window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2791                })
2792                .unwrap();
2793        })
2794        .detach();
2795        cx.background_executor.run_until_parked();
2796        window
2797            .update(cx, |_, window, cx| {
2798                search_view.update(cx, |search_view, cx| {
2799                    assert!(
2800                        search_view.query_editor.focus_handle(cx).is_focused(window),
2801                        "Empty search view should be focused after the toggle focus event: no results panel to focus on",
2802                    );
2803                });
2804        }).unwrap();
2805
2806        window
2807            .update(cx, |_, window, cx| {
2808                search_view.update(cx, |search_view, cx| {
2809                    let query_editor = &search_view.query_editor;
2810                    assert!(
2811                        query_editor.focus_handle(cx).is_focused(window),
2812                        "Search view should be focused after the new search view is activated",
2813                    );
2814                    let query_text = query_editor.read(cx).text(cx);
2815                    assert!(
2816                        query_text.is_empty(),
2817                        "New search query should be empty but got '{query_text}'",
2818                    );
2819                    let results_text = search_view
2820                        .results_editor
2821                        .update(cx, |editor, cx| editor.display_text(cx));
2822                    assert!(
2823                        results_text.is_empty(),
2824                        "Empty search view should have no results but got '{results_text}'"
2825                    );
2826                });
2827            })
2828            .unwrap();
2829
2830        window
2831            .update(cx, |_, window, cx| {
2832                search_view.update(cx, |search_view, cx| {
2833                    search_view.query_editor.update(cx, |query_editor, cx| {
2834                        query_editor.set_text("sOMETHINGtHATsURELYdOESnOTeXIST", window, cx)
2835                    });
2836                    search_view.search(cx);
2837                });
2838            })
2839            .unwrap();
2840        cx.background_executor.run_until_parked();
2841        window
2842            .update(cx, |_, window, cx| {
2843                search_view.update(cx, |search_view, cx| {
2844                    let results_text = search_view
2845                        .results_editor
2846                        .update(cx, |editor, cx| editor.display_text(cx));
2847                    assert!(
2848                        results_text.is_empty(),
2849                        "Search view for mismatching query should have no results but got '{results_text}'"
2850                    );
2851                    assert!(
2852                        search_view.query_editor.focus_handle(cx).is_focused(window),
2853                        "Search view should be focused after mismatching query had been used in search",
2854                    );
2855                });
2856            }).unwrap();
2857
2858        cx.spawn(|mut cx| async move {
2859            window.update(&mut cx, |_, window, cx| {
2860                window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2861            })
2862        })
2863        .detach();
2864        cx.background_executor.run_until_parked();
2865        window.update(cx, |_, window, cx| {
2866            search_view.update(cx, |search_view, cx| {
2867                assert!(
2868                    search_view.query_editor.focus_handle(cx).is_focused(window),
2869                    "Search view with mismatching query should be focused after the toggle focus event: still no results panel to focus on",
2870                );
2871            });
2872        }).unwrap();
2873
2874        window
2875            .update(cx, |_, window, cx| {
2876                search_view.update(cx, |search_view, cx| {
2877                    search_view.query_editor.update(cx, |query_editor, cx| {
2878                        query_editor.set_text("TWO", window, cx)
2879                    });
2880                    search_view.search(cx);
2881                });
2882            })
2883            .unwrap();
2884        cx.background_executor.run_until_parked();
2885        window.update(cx, |_, window, cx| {
2886            search_view.update(cx, |search_view, cx| {
2887                assert_eq!(
2888                    search_view
2889                        .results_editor
2890                        .update(cx, |editor, cx| editor.display_text(cx)),
2891                    "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
2892                    "Search view results should match the query"
2893                );
2894                assert!(
2895                    search_view.results_editor.focus_handle(cx).is_focused(window),
2896                    "Search view with mismatching query should be focused after search results are available",
2897                );
2898            });
2899        }).unwrap();
2900        cx.spawn(|mut cx| async move {
2901            window
2902                .update(&mut cx, |_, window, cx| {
2903                    window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2904                })
2905                .unwrap();
2906        })
2907        .detach();
2908        cx.background_executor.run_until_parked();
2909        window.update(cx, |_, window, cx| {
2910            search_view.update(cx, |search_view, cx| {
2911                assert!(
2912                    search_view.results_editor.focus_handle(cx).is_focused(window),
2913                    "Search view with matching query should still have its results editor focused after the toggle focus event",
2914                );
2915            });
2916        }).unwrap();
2917
2918        workspace
2919            .update(cx, |workspace, window, cx| {
2920                ProjectSearchView::deploy_search(
2921                    workspace,
2922                    &workspace::DeploySearch::find(),
2923                    window,
2924                    cx,
2925                )
2926            })
2927            .unwrap();
2928        window.update(cx, |_, window, cx| {
2929            search_view.update(cx, |search_view, cx| {
2930                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");
2931                assert_eq!(
2932                    search_view
2933                        .results_editor
2934                        .update(cx, |editor, cx| editor.display_text(cx)),
2935                    "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
2936                    "Results should be unchanged after search view 2nd open in a row"
2937                );
2938                assert!(
2939                    search_view.query_editor.focus_handle(cx).is_focused(window),
2940                    "Focus should be moved into query editor again after search view 2nd open in a row"
2941                );
2942            });
2943        }).unwrap();
2944
2945        cx.spawn(|mut cx| async move {
2946            window
2947                .update(&mut cx, |_, window, cx| {
2948                    window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2949                })
2950                .unwrap();
2951        })
2952        .detach();
2953        cx.background_executor.run_until_parked();
2954        window.update(cx, |_, window, cx| {
2955            search_view.update(cx, |search_view, cx| {
2956                assert!(
2957                    search_view.results_editor.focus_handle(cx).is_focused(window),
2958                    "Search view with matching query should switch focus to the results editor after the toggle focus event",
2959                );
2960            });
2961        }).unwrap();
2962    }
2963
2964    #[perf]
2965    #[gpui::test]
2966    async fn test_filters_consider_toggle_state(cx: &mut TestAppContext) {
2967        init_test(cx);
2968
2969        let fs = FakeFs::new(cx.background_executor.clone());
2970        fs.insert_tree(
2971            "/dir",
2972            json!({
2973                "one.rs": "const ONE: usize = 1;",
2974                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2975                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2976                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2977            }),
2978        )
2979        .await;
2980        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
2981        let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
2982        let workspace = window;
2983        let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
2984
2985        window
2986            .update(cx, move |workspace, window, cx| {
2987                workspace.panes()[0].update(cx, |pane, cx| {
2988                    pane.toolbar()
2989                        .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
2990                });
2991
2992                ProjectSearchView::deploy_search(
2993                    workspace,
2994                    &workspace::DeploySearch::find(),
2995                    window,
2996                    cx,
2997                )
2998            })
2999            .unwrap();
3000
3001        let Some(search_view) = cx.read(|cx| {
3002            workspace
3003                .read(cx)
3004                .unwrap()
3005                .active_pane()
3006                .read(cx)
3007                .active_item()
3008                .and_then(|item| item.downcast::<ProjectSearchView>())
3009        }) else {
3010            panic!("Search view expected to appear after new search event trigger")
3011        };
3012
3013        cx.spawn(|mut cx| async move {
3014            window
3015                .update(&mut cx, |_, window, cx| {
3016                    window.dispatch_action(ToggleFocus.boxed_clone(), cx)
3017                })
3018                .unwrap();
3019        })
3020        .detach();
3021        cx.background_executor.run_until_parked();
3022
3023        window
3024            .update(cx, |_, window, cx| {
3025                search_view.update(cx, |search_view, cx| {
3026                    search_view.query_editor.update(cx, |query_editor, cx| {
3027                        query_editor.set_text("const FOUR", window, cx)
3028                    });
3029                    search_view.toggle_filters(cx);
3030                    search_view
3031                        .excluded_files_editor
3032                        .update(cx, |exclude_editor, cx| {
3033                            exclude_editor.set_text("four.rs", window, cx)
3034                        });
3035                    search_view.search(cx);
3036                });
3037            })
3038            .unwrap();
3039        cx.background_executor.run_until_parked();
3040        window
3041            .update(cx, |_, _, cx| {
3042                search_view.update(cx, |search_view, cx| {
3043                    let results_text = search_view
3044                        .results_editor
3045                        .update(cx, |editor, cx| editor.display_text(cx));
3046                    assert!(
3047                        results_text.is_empty(),
3048                        "Search view for query with the only match in an excluded file should have no results but got '{results_text}'"
3049                    );
3050                });
3051            }).unwrap();
3052
3053        cx.spawn(|mut cx| async move {
3054            window.update(&mut cx, |_, window, cx| {
3055                window.dispatch_action(ToggleFocus.boxed_clone(), cx)
3056            })
3057        })
3058        .detach();
3059        cx.background_executor.run_until_parked();
3060
3061        window
3062            .update(cx, |_, _, cx| {
3063                search_view.update(cx, |search_view, cx| {
3064                    search_view.toggle_filters(cx);
3065                    search_view.search(cx);
3066                });
3067            })
3068            .unwrap();
3069        cx.background_executor.run_until_parked();
3070        window
3071            .update(cx, |_, _, cx| {
3072                search_view.update(cx, |search_view, cx| {
3073                assert_eq!(
3074                    search_view
3075                        .results_editor
3076                        .update(cx, |editor, cx| editor.display_text(cx)),
3077                    "\n\nconst FOUR: usize = one::ONE + three::THREE;",
3078                    "Search view results should contain the queried result in the previously excluded file with filters toggled off"
3079                );
3080            });
3081            })
3082            .unwrap();
3083    }
3084
3085    #[perf]
3086    #[gpui::test]
3087    async fn test_new_project_search_focus(cx: &mut TestAppContext) {
3088        init_test(cx);
3089
3090        let fs = FakeFs::new(cx.background_executor.clone());
3091        fs.insert_tree(
3092            path!("/dir"),
3093            json!({
3094                "one.rs": "const ONE: usize = 1;",
3095                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
3096                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
3097                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
3098            }),
3099        )
3100        .await;
3101        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
3102        let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
3103        let workspace = window;
3104        let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
3105
3106        let active_item = cx.read(|cx| {
3107            workspace
3108                .read(cx)
3109                .unwrap()
3110                .active_pane()
3111                .read(cx)
3112                .active_item()
3113                .and_then(|item| item.downcast::<ProjectSearchView>())
3114        });
3115        assert!(
3116            active_item.is_none(),
3117            "Expected no search panel to be active"
3118        );
3119
3120        window
3121            .update(cx, move |workspace, window, cx| {
3122                assert_eq!(workspace.panes().len(), 1);
3123                workspace.panes()[0].update(cx, |pane, cx| {
3124                    pane.toolbar()
3125                        .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3126                });
3127
3128                ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3129            })
3130            .unwrap();
3131
3132        let Some(search_view) = cx.read(|cx| {
3133            workspace
3134                .read(cx)
3135                .unwrap()
3136                .active_pane()
3137                .read(cx)
3138                .active_item()
3139                .and_then(|item| item.downcast::<ProjectSearchView>())
3140        }) else {
3141            panic!("Search view expected to appear after new search event trigger")
3142        };
3143
3144        cx.spawn(|mut cx| async move {
3145            window
3146                .update(&mut cx, |_, window, cx| {
3147                    window.dispatch_action(ToggleFocus.boxed_clone(), cx)
3148                })
3149                .unwrap();
3150        })
3151        .detach();
3152        cx.background_executor.run_until_parked();
3153
3154        window.update(cx, |_, window, cx| {
3155            search_view.update(cx, |search_view, cx| {
3156                    assert!(
3157                        search_view.query_editor.focus_handle(cx).is_focused(window),
3158                        "Empty search view should be focused after the toggle focus event: no results panel to focus on",
3159                    );
3160                });
3161        }).unwrap();
3162
3163        window
3164            .update(cx, |_, window, cx| {
3165                search_view.update(cx, |search_view, cx| {
3166                    let query_editor = &search_view.query_editor;
3167                    assert!(
3168                        query_editor.focus_handle(cx).is_focused(window),
3169                        "Search view should be focused after the new search view is activated",
3170                    );
3171                    let query_text = query_editor.read(cx).text(cx);
3172                    assert!(
3173                        query_text.is_empty(),
3174                        "New search query should be empty but got '{query_text}'",
3175                    );
3176                    let results_text = search_view
3177                        .results_editor
3178                        .update(cx, |editor, cx| editor.display_text(cx));
3179                    assert!(
3180                        results_text.is_empty(),
3181                        "Empty search view should have no results but got '{results_text}'"
3182                    );
3183                });
3184            })
3185            .unwrap();
3186
3187        window
3188            .update(cx, |_, window, cx| {
3189                search_view.update(cx, |search_view, cx| {
3190                    search_view.query_editor.update(cx, |query_editor, cx| {
3191                        query_editor.set_text("sOMETHINGtHATsURELYdOESnOTeXIST", window, cx)
3192                    });
3193                    search_view.search(cx);
3194                });
3195            })
3196            .unwrap();
3197
3198        cx.background_executor.run_until_parked();
3199        window
3200            .update(cx, |_, window, cx| {
3201                search_view.update(cx, |search_view, cx| {
3202                    let results_text = search_view
3203                        .results_editor
3204                        .update(cx, |editor, cx| editor.display_text(cx));
3205                    assert!(
3206                results_text.is_empty(),
3207                "Search view for mismatching query should have no results but got '{results_text}'"
3208            );
3209                    assert!(
3210                search_view.query_editor.focus_handle(cx).is_focused(window),
3211                "Search view should be focused after mismatching query had been used in search",
3212            );
3213                });
3214            })
3215            .unwrap();
3216        cx.spawn(|mut cx| async move {
3217            window.update(&mut cx, |_, window, cx| {
3218                window.dispatch_action(ToggleFocus.boxed_clone(), cx)
3219            })
3220        })
3221        .detach();
3222        cx.background_executor.run_until_parked();
3223        window.update(cx, |_, window, cx| {
3224            search_view.update(cx, |search_view, cx| {
3225                    assert!(
3226                        search_view.query_editor.focus_handle(cx).is_focused(window),
3227                        "Search view with mismatching query should be focused after the toggle focus event: still no results panel to focus on",
3228                    );
3229                });
3230        }).unwrap();
3231
3232        window
3233            .update(cx, |_, window, cx| {
3234                search_view.update(cx, |search_view, cx| {
3235                    search_view.query_editor.update(cx, |query_editor, cx| {
3236                        query_editor.set_text("TWO", window, cx)
3237                    });
3238                    search_view.search(cx);
3239                })
3240            })
3241            .unwrap();
3242        cx.background_executor.run_until_parked();
3243        window.update(cx, |_, window, cx|
3244        search_view.update(cx, |search_view, cx| {
3245                assert_eq!(
3246                    search_view
3247                        .results_editor
3248                        .update(cx, |editor, cx| editor.display_text(cx)),
3249                    "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
3250                    "Search view results should match the query"
3251                );
3252                assert!(
3253                    search_view.results_editor.focus_handle(cx).is_focused(window),
3254                    "Search view with mismatching query should be focused after search results are available",
3255                );
3256            })).unwrap();
3257        cx.spawn(|mut cx| async move {
3258            window
3259                .update(&mut cx, |_, window, cx| {
3260                    window.dispatch_action(ToggleFocus.boxed_clone(), cx)
3261                })
3262                .unwrap();
3263        })
3264        .detach();
3265        cx.background_executor.run_until_parked();
3266        window.update(cx, |_, window, cx| {
3267            search_view.update(cx, |search_view, cx| {
3268                    assert!(
3269                        search_view.results_editor.focus_handle(cx).is_focused(window),
3270                        "Search view with matching query should still have its results editor focused after the toggle focus event",
3271                    );
3272                });
3273        }).unwrap();
3274
3275        workspace
3276            .update(cx, |workspace, window, cx| {
3277                ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3278            })
3279            .unwrap();
3280        cx.background_executor.run_until_parked();
3281        let Some(search_view_2) = cx.read(|cx| {
3282            workspace
3283                .read(cx)
3284                .unwrap()
3285                .active_pane()
3286                .read(cx)
3287                .active_item()
3288                .and_then(|item| item.downcast::<ProjectSearchView>())
3289        }) else {
3290            panic!("Search view expected to appear after new search event trigger")
3291        };
3292        assert!(
3293            search_view_2 != search_view,
3294            "New search view should be open after `workspace::NewSearch` event"
3295        );
3296
3297        window.update(cx, |_, window, cx| {
3298            search_view.update(cx, |search_view, cx| {
3299                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO", "First search view should not have an updated query");
3300                    assert_eq!(
3301                        search_view
3302                            .results_editor
3303                            .update(cx, |editor, cx| editor.display_text(cx)),
3304                        "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
3305                        "Results of the first search view should not update too"
3306                    );
3307                    assert!(
3308                        !search_view.query_editor.focus_handle(cx).is_focused(window),
3309                        "Focus should be moved away from the first search view"
3310                    );
3311                });
3312        }).unwrap();
3313
3314        window.update(cx, |_, window, cx| {
3315            search_view_2.update(cx, |search_view_2, cx| {
3316                    assert_eq!(
3317                        search_view_2.query_editor.read(cx).text(cx),
3318                        "two",
3319                        "New search view should get the query from the text cursor was at during the event spawn (first search view's first result)"
3320                    );
3321                    assert_eq!(
3322                        search_view_2
3323                            .results_editor
3324                            .update(cx, |editor, cx| editor.display_text(cx)),
3325                        "",
3326                        "No search results should be in the 2nd view yet, as we did not spawn a search for it"
3327                    );
3328                    assert!(
3329                        search_view_2.query_editor.focus_handle(cx).is_focused(window),
3330                        "Focus should be moved into query editor of the new window"
3331                    );
3332                });
3333        }).unwrap();
3334
3335        window
3336            .update(cx, |_, window, cx| {
3337                search_view_2.update(cx, |search_view_2, cx| {
3338                    search_view_2.query_editor.update(cx, |query_editor, cx| {
3339                        query_editor.set_text("FOUR", window, cx)
3340                    });
3341                    search_view_2.search(cx);
3342                });
3343            })
3344            .unwrap();
3345
3346        cx.background_executor.run_until_parked();
3347        window.update(cx, |_, window, cx| {
3348            search_view_2.update(cx, |search_view_2, cx| {
3349                    assert_eq!(
3350                        search_view_2
3351                            .results_editor
3352                            .update(cx, |editor, cx| editor.display_text(cx)),
3353                        "\n\nconst FOUR: usize = one::ONE + three::THREE;",
3354                        "New search view with the updated query should have new search results"
3355                    );
3356                    assert!(
3357                        search_view_2.results_editor.focus_handle(cx).is_focused(window),
3358                        "Search view with mismatching query should be focused after search results are available",
3359                    );
3360                });
3361        }).unwrap();
3362
3363        cx.spawn(|mut cx| async move {
3364            window
3365                .update(&mut cx, |_, window, cx| {
3366                    window.dispatch_action(ToggleFocus.boxed_clone(), cx)
3367                })
3368                .unwrap();
3369        })
3370        .detach();
3371        cx.background_executor.run_until_parked();
3372        window.update(cx, |_, window, cx| {
3373            search_view_2.update(cx, |search_view_2, cx| {
3374                    assert!(
3375                        search_view_2.results_editor.focus_handle(cx).is_focused(window),
3376                        "Search view with matching query should switch focus to the results editor after the toggle focus event",
3377                    );
3378                });}).unwrap();
3379    }
3380
3381    #[perf]
3382    #[gpui::test]
3383    async fn test_new_project_search_in_directory(cx: &mut TestAppContext) {
3384        init_test(cx);
3385
3386        let fs = FakeFs::new(cx.background_executor.clone());
3387        fs.insert_tree(
3388            path!("/dir"),
3389            json!({
3390                "a": {
3391                    "one.rs": "const ONE: usize = 1;",
3392                    "two.rs": "const TWO: usize = one::ONE + one::ONE;",
3393                },
3394                "b": {
3395                    "three.rs": "const THREE: usize = one::ONE + two::TWO;",
3396                    "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
3397                },
3398            }),
3399        )
3400        .await;
3401        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
3402        let worktree_id = project.read_with(cx, |project, cx| {
3403            project.worktrees(cx).next().unwrap().read(cx).id()
3404        });
3405        let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
3406        let workspace = window.root(cx).unwrap();
3407        let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
3408
3409        let active_item = cx.read(|cx| {
3410            workspace
3411                .read(cx)
3412                .active_pane()
3413                .read(cx)
3414                .active_item()
3415                .and_then(|item| item.downcast::<ProjectSearchView>())
3416        });
3417        assert!(
3418            active_item.is_none(),
3419            "Expected no search panel to be active"
3420        );
3421
3422        window
3423            .update(cx, move |workspace, window, cx| {
3424                assert_eq!(workspace.panes().len(), 1);
3425                workspace.panes()[0].update(cx, move |pane, cx| {
3426                    pane.toolbar()
3427                        .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3428                });
3429            })
3430            .unwrap();
3431
3432        let a_dir_entry = cx.update(|cx| {
3433            workspace
3434                .read(cx)
3435                .project()
3436                .read(cx)
3437                .entry_for_path(&(worktree_id, rel_path("a")).into(), cx)
3438                .expect("no entry for /a/ directory")
3439                .clone()
3440        });
3441        assert!(a_dir_entry.is_dir());
3442        window
3443            .update(cx, |workspace, window, cx| {
3444                ProjectSearchView::new_search_in_directory(workspace, &a_dir_entry.path, window, cx)
3445            })
3446            .unwrap();
3447
3448        let Some(search_view) = cx.read(|cx| {
3449            workspace
3450                .read(cx)
3451                .active_pane()
3452                .read(cx)
3453                .active_item()
3454                .and_then(|item| item.downcast::<ProjectSearchView>())
3455        }) else {
3456            panic!("Search view expected to appear after new search in directory event trigger")
3457        };
3458        cx.background_executor.run_until_parked();
3459        window
3460            .update(cx, |_, window, cx| {
3461                search_view.update(cx, |search_view, cx| {
3462                    assert!(
3463                        search_view.query_editor.focus_handle(cx).is_focused(window),
3464                        "On new search in directory, focus should be moved into query editor"
3465                    );
3466                    search_view.excluded_files_editor.update(cx, |editor, cx| {
3467                        assert!(
3468                            editor.display_text(cx).is_empty(),
3469                            "New search in directory should not have any excluded files"
3470                        );
3471                    });
3472                    search_view.included_files_editor.update(cx, |editor, cx| {
3473                        assert_eq!(
3474                            editor.display_text(cx),
3475                            a_dir_entry.path.display(PathStyle::local()),
3476                            "New search in directory should have included dir entry path"
3477                        );
3478                    });
3479                });
3480            })
3481            .unwrap();
3482        window
3483            .update(cx, |_, window, cx| {
3484                search_view.update(cx, |search_view, cx| {
3485                    search_view.query_editor.update(cx, |query_editor, cx| {
3486                        query_editor.set_text("const", window, cx)
3487                    });
3488                    search_view.search(cx);
3489                });
3490            })
3491            .unwrap();
3492        cx.background_executor.run_until_parked();
3493        window
3494            .update(cx, |_, _, cx| {
3495                search_view.update(cx, |search_view, cx| {
3496                    assert_eq!(
3497                search_view
3498                    .results_editor
3499                    .update(cx, |editor, cx| editor.display_text(cx)),
3500                "\n\nconst ONE: usize = 1;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
3501                "New search in directory should have a filter that matches a certain directory"
3502            );
3503                })
3504            })
3505            .unwrap();
3506    }
3507
3508    #[perf]
3509    #[gpui::test]
3510    async fn test_search_query_history(cx: &mut TestAppContext) {
3511        init_test(cx);
3512
3513        let fs = FakeFs::new(cx.background_executor.clone());
3514        fs.insert_tree(
3515            path!("/dir"),
3516            json!({
3517                "one.rs": "const ONE: usize = 1;",
3518                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
3519                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
3520                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
3521            }),
3522        )
3523        .await;
3524        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
3525        let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
3526        let workspace = window.root(cx).unwrap();
3527        let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
3528
3529        window
3530            .update(cx, {
3531                let search_bar = search_bar.clone();
3532                |workspace, window, cx| {
3533                    assert_eq!(workspace.panes().len(), 1);
3534                    workspace.panes()[0].update(cx, |pane, cx| {
3535                        pane.toolbar()
3536                            .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3537                    });
3538
3539                    ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3540                }
3541            })
3542            .unwrap();
3543
3544        let search_view = cx.read(|cx| {
3545            workspace
3546                .read(cx)
3547                .active_pane()
3548                .read(cx)
3549                .active_item()
3550                .and_then(|item| item.downcast::<ProjectSearchView>())
3551                .expect("Search view expected to appear after new search event trigger")
3552        });
3553
3554        // Add 3 search items into the history + another unsubmitted one.
3555        window
3556            .update(cx, |_, window, cx| {
3557                search_view.update(cx, |search_view, cx| {
3558                    search_view.search_options = SearchOptions::CASE_SENSITIVE;
3559                    search_view.query_editor.update(cx, |query_editor, cx| {
3560                        query_editor.set_text("ONE", window, cx)
3561                    });
3562                    search_view.search(cx);
3563                });
3564            })
3565            .unwrap();
3566
3567        cx.background_executor.run_until_parked();
3568        window
3569            .update(cx, |_, window, cx| {
3570                search_view.update(cx, |search_view, cx| {
3571                    search_view.query_editor.update(cx, |query_editor, cx| {
3572                        query_editor.set_text("TWO", window, cx)
3573                    });
3574                    search_view.search(cx);
3575                });
3576            })
3577            .unwrap();
3578        cx.background_executor.run_until_parked();
3579        window
3580            .update(cx, |_, window, cx| {
3581                search_view.update(cx, |search_view, cx| {
3582                    search_view.query_editor.update(cx, |query_editor, cx| {
3583                        query_editor.set_text("THREE", window, cx)
3584                    });
3585                    search_view.search(cx);
3586                })
3587            })
3588            .unwrap();
3589        cx.background_executor.run_until_parked();
3590        window
3591            .update(cx, |_, window, cx| {
3592                search_view.update(cx, |search_view, cx| {
3593                    search_view.query_editor.update(cx, |query_editor, cx| {
3594                        query_editor.set_text("JUST_TEXT_INPUT", window, cx)
3595                    });
3596                })
3597            })
3598            .unwrap();
3599        cx.background_executor.run_until_parked();
3600
3601        // Ensure that the latest input with search settings is active.
3602        window
3603            .update(cx, |_, _, cx| {
3604                search_view.update(cx, |search_view, cx| {
3605                    assert_eq!(
3606                        search_view.query_editor.read(cx).text(cx),
3607                        "JUST_TEXT_INPUT"
3608                    );
3609                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3610                });
3611            })
3612            .unwrap();
3613
3614        // Next history query after the latest should set the query to the empty string.
3615        window
3616            .update(cx, |_, window, cx| {
3617                search_bar.update(cx, |search_bar, cx| {
3618                    search_bar.focus_search(window, cx);
3619                    search_bar.next_history_query(&NextHistoryQuery, window, cx);
3620                })
3621            })
3622            .unwrap();
3623        window
3624            .update(cx, |_, _, cx| {
3625                search_view.update(cx, |search_view, cx| {
3626                    assert_eq!(search_view.query_editor.read(cx).text(cx), "");
3627                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3628                });
3629            })
3630            .unwrap();
3631        window
3632            .update(cx, |_, window, cx| {
3633                search_bar.update(cx, |search_bar, cx| {
3634                    search_bar.focus_search(window, cx);
3635                    search_bar.next_history_query(&NextHistoryQuery, window, cx);
3636                })
3637            })
3638            .unwrap();
3639        window
3640            .update(cx, |_, _, cx| {
3641                search_view.update(cx, |search_view, cx| {
3642                    assert_eq!(search_view.query_editor.read(cx).text(cx), "");
3643                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3644                });
3645            })
3646            .unwrap();
3647
3648        // First previous query for empty current query should set the query to the latest submitted one.
3649        window
3650            .update(cx, |_, window, cx| {
3651                search_bar.update(cx, |search_bar, cx| {
3652                    search_bar.focus_search(window, cx);
3653                    search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3654                });
3655            })
3656            .unwrap();
3657        window
3658            .update(cx, |_, _, cx| {
3659                search_view.update(cx, |search_view, cx| {
3660                    assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
3661                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3662                });
3663            })
3664            .unwrap();
3665
3666        // Further previous items should go over the history in reverse order.
3667        window
3668            .update(cx, |_, window, cx| {
3669                search_bar.update(cx, |search_bar, cx| {
3670                    search_bar.focus_search(window, cx);
3671                    search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3672                });
3673            })
3674            .unwrap();
3675        window
3676            .update(cx, |_, _, cx| {
3677                search_view.update(cx, |search_view, cx| {
3678                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
3679                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3680                });
3681            })
3682            .unwrap();
3683
3684        // Previous items should never go behind the first history item.
3685        window
3686            .update(cx, |_, window, cx| {
3687                search_bar.update(cx, |search_bar, cx| {
3688                    search_bar.focus_search(window, cx);
3689                    search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3690                });
3691            })
3692            .unwrap();
3693        window
3694            .update(cx, |_, _, cx| {
3695                search_view.update(cx, |search_view, cx| {
3696                    assert_eq!(search_view.query_editor.read(cx).text(cx), "ONE");
3697                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3698                });
3699            })
3700            .unwrap();
3701        window
3702            .update(cx, |_, window, cx| {
3703                search_bar.update(cx, |search_bar, cx| {
3704                    search_bar.focus_search(window, cx);
3705                    search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3706                });
3707            })
3708            .unwrap();
3709        window
3710            .update(cx, |_, _, cx| {
3711                search_view.update(cx, |search_view, cx| {
3712                    assert_eq!(search_view.query_editor.read(cx).text(cx), "ONE");
3713                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3714                });
3715            })
3716            .unwrap();
3717
3718        // Next items should go over the history in the original order.
3719        window
3720            .update(cx, |_, window, cx| {
3721                search_bar.update(cx, |search_bar, cx| {
3722                    search_bar.focus_search(window, cx);
3723                    search_bar.next_history_query(&NextHistoryQuery, window, cx);
3724                });
3725            })
3726            .unwrap();
3727        window
3728            .update(cx, |_, _, cx| {
3729                search_view.update(cx, |search_view, cx| {
3730                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
3731                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3732                });
3733            })
3734            .unwrap();
3735
3736        window
3737            .update(cx, |_, window, cx| {
3738                search_view.update(cx, |search_view, cx| {
3739                    search_view.query_editor.update(cx, |query_editor, cx| {
3740                        query_editor.set_text("TWO_NEW", window, cx)
3741                    });
3742                    search_view.search(cx);
3743                });
3744            })
3745            .unwrap();
3746        cx.background_executor.run_until_parked();
3747        window
3748            .update(cx, |_, _, cx| {
3749                search_view.update(cx, |search_view, cx| {
3750                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO_NEW");
3751                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3752                });
3753            })
3754            .unwrap();
3755
3756        // New search input should add another entry to history and move the selection to the end of the history.
3757        window
3758            .update(cx, |_, window, cx| {
3759                search_bar.update(cx, |search_bar, cx| {
3760                    search_bar.focus_search(window, cx);
3761                    search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3762                });
3763            })
3764            .unwrap();
3765        window
3766            .update(cx, |_, _, cx| {
3767                search_view.update(cx, |search_view, cx| {
3768                    assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
3769                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3770                });
3771            })
3772            .unwrap();
3773        window
3774            .update(cx, |_, window, cx| {
3775                search_bar.update(cx, |search_bar, cx| {
3776                    search_bar.focus_search(window, cx);
3777                    search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3778                });
3779            })
3780            .unwrap();
3781        window
3782            .update(cx, |_, _, cx| {
3783                search_view.update(cx, |search_view, cx| {
3784                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
3785                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3786                });
3787            })
3788            .unwrap();
3789        window
3790            .update(cx, |_, window, cx| {
3791                search_bar.update(cx, |search_bar, cx| {
3792                    search_bar.focus_search(window, cx);
3793                    search_bar.next_history_query(&NextHistoryQuery, window, cx);
3794                });
3795            })
3796            .unwrap();
3797        window
3798            .update(cx, |_, _, cx| {
3799                search_view.update(cx, |search_view, cx| {
3800                    assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
3801                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3802                });
3803            })
3804            .unwrap();
3805        window
3806            .update(cx, |_, window, cx| {
3807                search_bar.update(cx, |search_bar, cx| {
3808                    search_bar.focus_search(window, cx);
3809                    search_bar.next_history_query(&NextHistoryQuery, window, cx);
3810                });
3811            })
3812            .unwrap();
3813        window
3814            .update(cx, |_, _, cx| {
3815                search_view.update(cx, |search_view, cx| {
3816                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO_NEW");
3817                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3818                });
3819            })
3820            .unwrap();
3821        window
3822            .update(cx, |_, window, cx| {
3823                search_bar.update(cx, |search_bar, cx| {
3824                    search_bar.focus_search(window, cx);
3825                    search_bar.next_history_query(&NextHistoryQuery, window, cx);
3826                });
3827            })
3828            .unwrap();
3829        window
3830            .update(cx, |_, _, cx| {
3831                search_view.update(cx, |search_view, cx| {
3832                    assert_eq!(search_view.query_editor.read(cx).text(cx), "");
3833                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3834                });
3835            })
3836            .unwrap();
3837    }
3838
3839    #[perf]
3840    #[gpui::test]
3841    async fn test_search_query_history_with_multiple_views(cx: &mut TestAppContext) {
3842        init_test(cx);
3843
3844        let fs = FakeFs::new(cx.background_executor.clone());
3845        fs.insert_tree(
3846            path!("/dir"),
3847            json!({
3848                "one.rs": "const ONE: usize = 1;",
3849            }),
3850        )
3851        .await;
3852        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
3853        let worktree_id = project.update(cx, |this, cx| {
3854            this.worktrees(cx).next().unwrap().read(cx).id()
3855        });
3856
3857        let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
3858        let workspace = window.root(cx).unwrap();
3859
3860        let panes: Vec<_> = window
3861            .update(cx, |this, _, _| this.panes().to_owned())
3862            .unwrap();
3863
3864        let search_bar_1 = window.build_entity(cx, |_, _| ProjectSearchBar::new());
3865        let search_bar_2 = window.build_entity(cx, |_, _| ProjectSearchBar::new());
3866
3867        assert_eq!(panes.len(), 1);
3868        let first_pane = panes.first().cloned().unwrap();
3869        assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 0);
3870        window
3871            .update(cx, |workspace, window, cx| {
3872                workspace.open_path(
3873                    (worktree_id, rel_path("one.rs")),
3874                    Some(first_pane.downgrade()),
3875                    true,
3876                    window,
3877                    cx,
3878                )
3879            })
3880            .unwrap()
3881            .await
3882            .unwrap();
3883        assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 1);
3884
3885        // Add a project search item to the first pane
3886        window
3887            .update(cx, {
3888                let search_bar = search_bar_1.clone();
3889                |workspace, window, cx| {
3890                    first_pane.update(cx, |pane, cx| {
3891                        pane.toolbar()
3892                            .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3893                    });
3894
3895                    ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3896                }
3897            })
3898            .unwrap();
3899        let search_view_1 = cx.read(|cx| {
3900            workspace
3901                .read(cx)
3902                .active_item(cx)
3903                .and_then(|item| item.downcast::<ProjectSearchView>())
3904                .expect("Search view expected to appear after new search event trigger")
3905        });
3906
3907        let second_pane = window
3908            .update(cx, |workspace, window, cx| {
3909                workspace.split_and_clone(
3910                    first_pane.clone(),
3911                    workspace::SplitDirection::Right,
3912                    window,
3913                    cx,
3914                )
3915            })
3916            .unwrap()
3917            .await
3918            .unwrap();
3919        assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 1);
3920
3921        assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 1);
3922        assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 2);
3923
3924        // Add a project search item to the second pane
3925        window
3926            .update(cx, {
3927                let search_bar = search_bar_2.clone();
3928                let pane = second_pane.clone();
3929                move |workspace, window, cx| {
3930                    assert_eq!(workspace.panes().len(), 2);
3931                    pane.update(cx, |pane, cx| {
3932                        pane.toolbar()
3933                            .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3934                    });
3935
3936                    ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3937                }
3938            })
3939            .unwrap();
3940
3941        let search_view_2 = cx.read(|cx| {
3942            workspace
3943                .read(cx)
3944                .active_item(cx)
3945                .and_then(|item| item.downcast::<ProjectSearchView>())
3946                .expect("Search view expected to appear after new search event trigger")
3947        });
3948
3949        cx.run_until_parked();
3950        assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 2);
3951        assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 2);
3952
3953        let update_search_view =
3954            |search_view: &Entity<ProjectSearchView>, query: &str, cx: &mut TestAppContext| {
3955                window
3956                    .update(cx, |_, window, cx| {
3957                        search_view.update(cx, |search_view, cx| {
3958                            search_view.query_editor.update(cx, |query_editor, cx| {
3959                                query_editor.set_text(query, window, cx)
3960                            });
3961                            search_view.search(cx);
3962                        });
3963                    })
3964                    .unwrap();
3965            };
3966
3967        let active_query =
3968            |search_view: &Entity<ProjectSearchView>, cx: &mut TestAppContext| -> String {
3969                window
3970                    .update(cx, |_, _, cx| {
3971                        search_view.update(cx, |search_view, cx| {
3972                            search_view.query_editor.read(cx).text(cx)
3973                        })
3974                    })
3975                    .unwrap()
3976            };
3977
3978        let select_prev_history_item =
3979            |search_bar: &Entity<ProjectSearchBar>, cx: &mut TestAppContext| {
3980                window
3981                    .update(cx, |_, window, cx| {
3982                        search_bar.update(cx, |search_bar, cx| {
3983                            search_bar.focus_search(window, cx);
3984                            search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3985                        })
3986                    })
3987                    .unwrap();
3988            };
3989
3990        let select_next_history_item =
3991            |search_bar: &Entity<ProjectSearchBar>, cx: &mut TestAppContext| {
3992                window
3993                    .update(cx, |_, window, cx| {
3994                        search_bar.update(cx, |search_bar, cx| {
3995                            search_bar.focus_search(window, cx);
3996                            search_bar.next_history_query(&NextHistoryQuery, window, cx);
3997                        })
3998                    })
3999                    .unwrap();
4000            };
4001
4002        update_search_view(&search_view_1, "ONE", cx);
4003        cx.background_executor.run_until_parked();
4004
4005        update_search_view(&search_view_2, "TWO", cx);
4006        cx.background_executor.run_until_parked();
4007
4008        assert_eq!(active_query(&search_view_1, cx), "ONE");
4009        assert_eq!(active_query(&search_view_2, cx), "TWO");
4010
4011        // Selecting previous history item should select the query from search view 1.
4012        select_prev_history_item(&search_bar_2, cx);
4013        assert_eq!(active_query(&search_view_2, cx), "ONE");
4014
4015        // Selecting the previous history item should not change the query as it is already the first item.
4016        select_prev_history_item(&search_bar_2, cx);
4017        assert_eq!(active_query(&search_view_2, cx), "ONE");
4018
4019        // Changing the query in search view 2 should not affect the history of search view 1.
4020        assert_eq!(active_query(&search_view_1, cx), "ONE");
4021
4022        // Deploying a new search in search view 2
4023        update_search_view(&search_view_2, "THREE", cx);
4024        cx.background_executor.run_until_parked();
4025
4026        select_next_history_item(&search_bar_2, cx);
4027        assert_eq!(active_query(&search_view_2, cx), "");
4028
4029        select_prev_history_item(&search_bar_2, cx);
4030        assert_eq!(active_query(&search_view_2, cx), "THREE");
4031
4032        select_prev_history_item(&search_bar_2, cx);
4033        assert_eq!(active_query(&search_view_2, cx), "TWO");
4034
4035        select_prev_history_item(&search_bar_2, cx);
4036        assert_eq!(active_query(&search_view_2, cx), "ONE");
4037
4038        select_prev_history_item(&search_bar_2, cx);
4039        assert_eq!(active_query(&search_view_2, cx), "ONE");
4040
4041        // Search view 1 should now see the query from search view 2.
4042        assert_eq!(active_query(&search_view_1, cx), "ONE");
4043
4044        select_next_history_item(&search_bar_2, cx);
4045        assert_eq!(active_query(&search_view_2, cx), "TWO");
4046
4047        // Here is the new query from search view 2
4048        select_next_history_item(&search_bar_2, cx);
4049        assert_eq!(active_query(&search_view_2, cx), "THREE");
4050
4051        select_next_history_item(&search_bar_2, cx);
4052        assert_eq!(active_query(&search_view_2, cx), "");
4053
4054        select_next_history_item(&search_bar_1, cx);
4055        assert_eq!(active_query(&search_view_1, cx), "TWO");
4056
4057        select_next_history_item(&search_bar_1, cx);
4058        assert_eq!(active_query(&search_view_1, cx), "THREE");
4059
4060        select_next_history_item(&search_bar_1, cx);
4061        assert_eq!(active_query(&search_view_1, cx), "");
4062    }
4063
4064    #[perf]
4065    #[gpui::test]
4066    async fn test_deploy_search_with_multiple_panes(cx: &mut TestAppContext) {
4067        init_test(cx);
4068
4069        // Setup 2 panes, both with a file open and one with a project search.
4070        let fs = FakeFs::new(cx.background_executor.clone());
4071        fs.insert_tree(
4072            path!("/dir"),
4073            json!({
4074                "one.rs": "const ONE: usize = 1;",
4075            }),
4076        )
4077        .await;
4078        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
4079        let worktree_id = project.update(cx, |this, cx| {
4080            this.worktrees(cx).next().unwrap().read(cx).id()
4081        });
4082        let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
4083        let panes: Vec<_> = window
4084            .update(cx, |this, _, _| this.panes().to_owned())
4085            .unwrap();
4086        assert_eq!(panes.len(), 1);
4087        let first_pane = panes.first().cloned().unwrap();
4088        assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 0);
4089        window
4090            .update(cx, |workspace, window, cx| {
4091                workspace.open_path(
4092                    (worktree_id, rel_path("one.rs")),
4093                    Some(first_pane.downgrade()),
4094                    true,
4095                    window,
4096                    cx,
4097                )
4098            })
4099            .unwrap()
4100            .await
4101            .unwrap();
4102        assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 1);
4103        let second_pane = window
4104            .update(cx, |workspace, window, cx| {
4105                workspace.split_and_clone(
4106                    first_pane.clone(),
4107                    workspace::SplitDirection::Right,
4108                    window,
4109                    cx,
4110                )
4111            })
4112            .unwrap()
4113            .await
4114            .unwrap();
4115        assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 1);
4116        assert!(
4117            window
4118                .update(cx, |_, window, cx| second_pane
4119                    .focus_handle(cx)
4120                    .contains_focused(window, cx))
4121                .unwrap()
4122        );
4123        let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
4124        window
4125            .update(cx, {
4126                let search_bar = search_bar.clone();
4127                let pane = first_pane.clone();
4128                move |workspace, window, cx| {
4129                    assert_eq!(workspace.panes().len(), 2);
4130                    pane.update(cx, move |pane, cx| {
4131                        pane.toolbar()
4132                            .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
4133                    });
4134                }
4135            })
4136            .unwrap();
4137
4138        // Add a project search item to the second pane
4139        window
4140            .update(cx, {
4141                |workspace, window, cx| {
4142                    assert_eq!(workspace.panes().len(), 2);
4143                    second_pane.update(cx, |pane, cx| {
4144                        pane.toolbar()
4145                            .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
4146                    });
4147
4148                    ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
4149                }
4150            })
4151            .unwrap();
4152
4153        cx.run_until_parked();
4154        assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 2);
4155        assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 1);
4156
4157        // Focus the first pane
4158        window
4159            .update(cx, |workspace, window, cx| {
4160                assert_eq!(workspace.active_pane(), &second_pane);
4161                second_pane.update(cx, |this, cx| {
4162                    assert_eq!(this.active_item_index(), 1);
4163                    this.activate_previous_item(&Default::default(), window, cx);
4164                    assert_eq!(this.active_item_index(), 0);
4165                });
4166                workspace.activate_pane_in_direction(workspace::SplitDirection::Left, window, cx);
4167            })
4168            .unwrap();
4169        window
4170            .update(cx, |workspace, _, cx| {
4171                assert_eq!(workspace.active_pane(), &first_pane);
4172                assert_eq!(first_pane.read(cx).items_len(), 1);
4173                assert_eq!(second_pane.read(cx).items_len(), 2);
4174            })
4175            .unwrap();
4176
4177        // Deploy a new search
4178        cx.dispatch_action(window.into(), DeploySearch::find());
4179
4180        // Both panes should now have a project search in them
4181        window
4182            .update(cx, |workspace, window, cx| {
4183                assert_eq!(workspace.active_pane(), &first_pane);
4184                first_pane.read_with(cx, |this, _| {
4185                    assert_eq!(this.active_item_index(), 1);
4186                    assert_eq!(this.items_len(), 2);
4187                });
4188                second_pane.update(cx, |this, cx| {
4189                    assert!(!cx.focus_handle().contains_focused(window, cx));
4190                    assert_eq!(this.items_len(), 2);
4191                });
4192            })
4193            .unwrap();
4194
4195        // Focus the second pane's non-search item
4196        window
4197            .update(cx, |_workspace, window, cx| {
4198                second_pane.update(cx, |pane, cx| {
4199                    pane.activate_next_item(&Default::default(), window, cx)
4200                });
4201            })
4202            .unwrap();
4203
4204        // Deploy a new search
4205        cx.dispatch_action(window.into(), DeploySearch::find());
4206
4207        // The project search view should now be focused in the second pane
4208        // And the number of items should be unchanged.
4209        window
4210            .update(cx, |_workspace, _, cx| {
4211                second_pane.update(cx, |pane, _cx| {
4212                    assert!(
4213                        pane.active_item()
4214                            .unwrap()
4215                            .downcast::<ProjectSearchView>()
4216                            .is_some()
4217                    );
4218
4219                    assert_eq!(pane.items_len(), 2);
4220                });
4221            })
4222            .unwrap();
4223    }
4224
4225    #[perf]
4226    #[gpui::test]
4227    async fn test_scroll_search_results_to_top(cx: &mut TestAppContext) {
4228        init_test(cx);
4229
4230        // We need many lines in the search results to be able to scroll the window
4231        let fs = FakeFs::new(cx.background_executor.clone());
4232        fs.insert_tree(
4233            path!("/dir"),
4234            json!({
4235                "1.txt": "\n\n\n\n\n A \n\n\n\n\n",
4236                "2.txt": "\n\n\n\n\n A \n\n\n\n\n",
4237                "3.rs": "\n\n\n\n\n A \n\n\n\n\n",
4238                "4.rs": "\n\n\n\n\n A \n\n\n\n\n",
4239                "5.rs": "\n\n\n\n\n A \n\n\n\n\n",
4240                "6.rs": "\n\n\n\n\n A \n\n\n\n\n",
4241                "7.rs": "\n\n\n\n\n A \n\n\n\n\n",
4242                "8.rs": "\n\n\n\n\n A \n\n\n\n\n",
4243                "9.rs": "\n\n\n\n\n A \n\n\n\n\n",
4244                "a.rs": "\n\n\n\n\n A \n\n\n\n\n",
4245                "b.rs": "\n\n\n\n\n B \n\n\n\n\n",
4246                "c.rs": "\n\n\n\n\n B \n\n\n\n\n",
4247                "d.rs": "\n\n\n\n\n B \n\n\n\n\n",
4248                "e.rs": "\n\n\n\n\n B \n\n\n\n\n",
4249                "f.rs": "\n\n\n\n\n B \n\n\n\n\n",
4250                "g.rs": "\n\n\n\n\n B \n\n\n\n\n",
4251                "h.rs": "\n\n\n\n\n B \n\n\n\n\n",
4252                "i.rs": "\n\n\n\n\n B \n\n\n\n\n",
4253                "j.rs": "\n\n\n\n\n B \n\n\n\n\n",
4254                "k.rs": "\n\n\n\n\n B \n\n\n\n\n",
4255            }),
4256        )
4257        .await;
4258        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
4259        let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
4260        let workspace = window.root(cx).unwrap();
4261        let search = cx.new(|cx| ProjectSearch::new(project, cx));
4262        let search_view = cx.add_window(|window, cx| {
4263            ProjectSearchView::new(workspace.downgrade(), search.clone(), window, cx, None)
4264        });
4265
4266        // First search
4267        perform_search(search_view, "A", cx);
4268        search_view
4269            .update(cx, |search_view, window, cx| {
4270                search_view.results_editor.update(cx, |results_editor, cx| {
4271                    // Results are correct and scrolled to the top
4272                    assert_eq!(
4273                        results_editor.display_text(cx).match_indices(" A ").count(),
4274                        10
4275                    );
4276                    assert_eq!(results_editor.scroll_position(cx), Point::default());
4277
4278                    // Scroll results all the way down
4279                    results_editor.scroll(
4280                        Point::new(0., f64::MAX),
4281                        Some(Axis::Vertical),
4282                        window,
4283                        cx,
4284                    );
4285                });
4286            })
4287            .expect("unable to update search view");
4288
4289        // Second search
4290        perform_search(search_view, "B", cx);
4291        search_view
4292            .update(cx, |search_view, _, cx| {
4293                search_view.results_editor.update(cx, |results_editor, cx| {
4294                    // Results are correct...
4295                    assert_eq!(
4296                        results_editor.display_text(cx).match_indices(" B ").count(),
4297                        10
4298                    );
4299                    // ...and scrolled back to the top
4300                    assert_eq!(results_editor.scroll_position(cx), Point::default());
4301                });
4302            })
4303            .expect("unable to update search view");
4304    }
4305
4306    #[perf]
4307    #[gpui::test]
4308    async fn test_buffer_search_query_reused(cx: &mut TestAppContext) {
4309        init_test(cx);
4310
4311        let fs = FakeFs::new(cx.background_executor.clone());
4312        fs.insert_tree(
4313            path!("/dir"),
4314            json!({
4315                "one.rs": "const ONE: usize = 1;",
4316            }),
4317        )
4318        .await;
4319        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
4320        let worktree_id = project.update(cx, |this, cx| {
4321            this.worktrees(cx).next().unwrap().read(cx).id()
4322        });
4323        let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
4324        let workspace = window.root(cx).unwrap();
4325        let mut cx = VisualTestContext::from_window(*window.deref(), cx);
4326
4327        let editor = workspace
4328            .update_in(&mut cx, |workspace, window, cx| {
4329                workspace.open_path((worktree_id, rel_path("one.rs")), None, true, window, cx)
4330            })
4331            .await
4332            .unwrap()
4333            .downcast::<Editor>()
4334            .unwrap();
4335
4336        // Wait for the unstaged changes to be loaded
4337        cx.run_until_parked();
4338
4339        let buffer_search_bar = cx.new_window_entity(|window, cx| {
4340            let mut search_bar =
4341                BufferSearchBar::new(Some(project.read(cx).languages().clone()), window, cx);
4342            search_bar.set_active_pane_item(Some(&editor), window, cx);
4343            search_bar.show(window, cx);
4344            search_bar
4345        });
4346
4347        let panes: Vec<_> = window
4348            .update(&mut cx, |this, _, _| this.panes().to_owned())
4349            .unwrap();
4350        assert_eq!(panes.len(), 1);
4351        let pane = panes.first().cloned().unwrap();
4352        pane.update_in(&mut cx, |pane, window, cx| {
4353            pane.toolbar().update(cx, |toolbar, cx| {
4354                toolbar.add_item(buffer_search_bar.clone(), window, cx);
4355            })
4356        });
4357
4358        let buffer_search_query = "search bar query";
4359        buffer_search_bar
4360            .update_in(&mut cx, |buffer_search_bar, window, cx| {
4361                buffer_search_bar.focus_handle(cx).focus(window, cx);
4362                buffer_search_bar.search(buffer_search_query, None, true, window, cx)
4363            })
4364            .await
4365            .unwrap();
4366
4367        workspace.update_in(&mut cx, |workspace, window, cx| {
4368            ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
4369        });
4370        cx.run_until_parked();
4371        let project_search_view = pane
4372            .read_with(&cx, |pane, _| {
4373                pane.active_item()
4374                    .and_then(|item| item.downcast::<ProjectSearchView>())
4375            })
4376            .expect("should open a project search view after spawning a new search");
4377        project_search_view.update(&mut cx, |search_view, cx| {
4378            assert_eq!(
4379                search_view.search_query_text(cx),
4380                buffer_search_query,
4381                "Project search should take the query from the buffer search bar since it got focused and had a query inside"
4382            );
4383        });
4384    }
4385
4386    #[gpui::test]
4387    async fn test_search_dismisses_modal(cx: &mut TestAppContext) {
4388        init_test(cx);
4389
4390        let fs = FakeFs::new(cx.background_executor.clone());
4391        fs.insert_tree(
4392            path!("/dir"),
4393            json!({
4394                "one.rs": "const ONE: usize = 1;",
4395            }),
4396        )
4397        .await;
4398        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
4399        let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
4400
4401        struct EmptyModalView {
4402            focus_handle: gpui::FocusHandle,
4403        }
4404        impl EventEmitter<gpui::DismissEvent> for EmptyModalView {}
4405        impl Render for EmptyModalView {
4406            fn render(&mut self, _: &mut Window, _: &mut Context<'_, Self>) -> impl IntoElement {
4407                div()
4408            }
4409        }
4410        impl Focusable for EmptyModalView {
4411            fn focus_handle(&self, _cx: &App) -> gpui::FocusHandle {
4412                self.focus_handle.clone()
4413            }
4414        }
4415        impl workspace::ModalView for EmptyModalView {}
4416
4417        window
4418            .update(cx, |workspace, window, cx| {
4419                workspace.toggle_modal(window, cx, |_, cx| EmptyModalView {
4420                    focus_handle: cx.focus_handle(),
4421                });
4422                assert!(workspace.has_active_modal(window, cx));
4423            })
4424            .unwrap();
4425
4426        cx.dispatch_action(window.into(), Deploy::find());
4427
4428        window
4429            .update(cx, |workspace, window, cx| {
4430                assert!(!workspace.has_active_modal(window, cx));
4431                workspace.toggle_modal(window, cx, |_, cx| EmptyModalView {
4432                    focus_handle: cx.focus_handle(),
4433                });
4434                assert!(workspace.has_active_modal(window, cx));
4435            })
4436            .unwrap();
4437
4438        cx.dispatch_action(window.into(), DeploySearch::find());
4439
4440        window
4441            .update(cx, |workspace, window, cx| {
4442                assert!(!workspace.has_active_modal(window, cx));
4443            })
4444            .unwrap();
4445    }
4446
4447    #[perf]
4448    #[gpui::test]
4449    async fn test_search_with_inlays(cx: &mut TestAppContext) {
4450        init_test(cx);
4451        cx.update(|cx| {
4452            SettingsStore::update_global(cx, |store, cx| {
4453                store.update_user_settings(cx, |settings| {
4454                    settings.project.all_languages.defaults.inlay_hints =
4455                        Some(InlayHintSettingsContent {
4456                            enabled: Some(true),
4457                            ..InlayHintSettingsContent::default()
4458                        })
4459                });
4460            });
4461        });
4462
4463        let fs = FakeFs::new(cx.background_executor.clone());
4464        fs.insert_tree(
4465            path!("/dir"),
4466            // `\n` , a trailing line on the end, is important for the test case
4467            json!({
4468                "main.rs": "fn main() { let a = 2; }\n",
4469            }),
4470        )
4471        .await;
4472
4473        let requests_count = Arc::new(AtomicUsize::new(0));
4474        let closure_requests_count = requests_count.clone();
4475        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
4476        let language_registry = project.read_with(cx, |project, _| project.languages().clone());
4477        let language = rust_lang();
4478        language_registry.add(language);
4479        let mut fake_servers = language_registry.register_fake_lsp(
4480            "Rust",
4481            FakeLspAdapter {
4482                capabilities: lsp::ServerCapabilities {
4483                    inlay_hint_provider: Some(lsp::OneOf::Left(true)),
4484                    ..lsp::ServerCapabilities::default()
4485                },
4486                initializer: Some(Box::new(move |fake_server| {
4487                    let requests_count = closure_requests_count.clone();
4488                    fake_server.set_request_handler::<lsp::request::InlayHintRequest, _, _>({
4489                        move |_, _| {
4490                            let requests_count = requests_count.clone();
4491                            async move {
4492                                requests_count.fetch_add(1, atomic::Ordering::Release);
4493                                Ok(Some(vec![lsp::InlayHint {
4494                                    position: lsp::Position::new(0, 17),
4495                                    label: lsp::InlayHintLabel::String(": i32".to_owned()),
4496                                    kind: Some(lsp::InlayHintKind::TYPE),
4497                                    text_edits: None,
4498                                    tooltip: None,
4499                                    padding_left: None,
4500                                    padding_right: None,
4501                                    data: None,
4502                                }]))
4503                            }
4504                        }
4505                    });
4506                })),
4507                ..FakeLspAdapter::default()
4508            },
4509        );
4510
4511        let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
4512        let workspace = window.root(cx).unwrap();
4513        let search = cx.new(|cx| ProjectSearch::new(project.clone(), cx));
4514        let search_view = cx.add_window(|window, cx| {
4515            ProjectSearchView::new(workspace.downgrade(), search.clone(), window, cx, None)
4516        });
4517
4518        perform_search(search_view, "let ", cx);
4519        let fake_server = fake_servers.next().await.unwrap();
4520        cx.executor().advance_clock(Duration::from_secs(1));
4521        cx.executor().run_until_parked();
4522        search_view
4523            .update(cx, |search_view, _, cx| {
4524                assert_eq!(
4525                    search_view
4526                        .results_editor
4527                        .update(cx, |editor, cx| editor.display_text(cx)),
4528                    "\n\nfn main() { let a: i32 = 2; }\n"
4529                );
4530            })
4531            .unwrap();
4532        assert_eq!(
4533            requests_count.load(atomic::Ordering::Acquire),
4534            1,
4535            "New hints should have been queried",
4536        );
4537
4538        // Can do the 2nd search without any panics
4539        perform_search(search_view, "let ", cx);
4540        cx.executor().advance_clock(Duration::from_secs(1));
4541        cx.executor().run_until_parked();
4542        search_view
4543            .update(cx, |search_view, _, cx| {
4544                assert_eq!(
4545                    search_view
4546                        .results_editor
4547                        .update(cx, |editor, cx| editor.display_text(cx)),
4548                    "\n\nfn main() { let a: i32 = 2; }\n"
4549                );
4550            })
4551            .unwrap();
4552        assert_eq!(
4553            requests_count.load(atomic::Ordering::Acquire),
4554            2,
4555            "We did drop the previous buffer when cleared the old project search results, hence another query was made",
4556        );
4557
4558        let singleton_editor = window
4559            .update(cx, |workspace, window, cx| {
4560                workspace.open_abs_path(
4561                    PathBuf::from(path!("/dir/main.rs")),
4562                    workspace::OpenOptions::default(),
4563                    window,
4564                    cx,
4565                )
4566            })
4567            .unwrap()
4568            .await
4569            .unwrap()
4570            .downcast::<Editor>()
4571            .unwrap();
4572        cx.executor().advance_clock(Duration::from_millis(100));
4573        cx.executor().run_until_parked();
4574        singleton_editor.update(cx, |editor, cx| {
4575            assert_eq!(
4576                editor.display_text(cx),
4577                "fn main() { let a: i32 = 2; }\n",
4578                "Newly opened editor should have the correct text with hints",
4579            );
4580        });
4581        assert_eq!(
4582            requests_count.load(atomic::Ordering::Acquire),
4583            2,
4584            "Opening the same buffer again should reuse the cached hints",
4585        );
4586
4587        window
4588            .update(cx, |_, window, cx| {
4589                singleton_editor.update(cx, |editor, cx| {
4590                    editor.handle_input("test", window, cx);
4591                });
4592            })
4593            .unwrap();
4594
4595        cx.executor().advance_clock(Duration::from_secs(1));
4596        cx.executor().run_until_parked();
4597        singleton_editor.update(cx, |editor, cx| {
4598            assert_eq!(
4599                editor.display_text(cx),
4600                "testfn main() { l: i32et a = 2; }\n",
4601                "Newly opened editor should have the correct text with hints",
4602            );
4603        });
4604        assert_eq!(
4605            requests_count.load(atomic::Ordering::Acquire),
4606            3,
4607            "We have edited the buffer and should send a new request",
4608        );
4609
4610        window
4611            .update(cx, |_, window, cx| {
4612                singleton_editor.update(cx, |editor, cx| {
4613                    editor.undo(&editor::actions::Undo, window, cx);
4614                });
4615            })
4616            .unwrap();
4617        cx.executor().advance_clock(Duration::from_secs(1));
4618        cx.executor().run_until_parked();
4619        assert_eq!(
4620            requests_count.load(atomic::Ordering::Acquire),
4621            4,
4622            "We have edited the buffer again and should send a new request again",
4623        );
4624        singleton_editor.update(cx, |editor, cx| {
4625            assert_eq!(
4626                editor.display_text(cx),
4627                "fn main() { let a: i32 = 2; }\n",
4628                "Newly opened editor should have the correct text with hints",
4629            );
4630        });
4631        project.update(cx, |_, cx| {
4632            cx.emit(project::Event::RefreshInlayHints {
4633                server_id: fake_server.server.server_id(),
4634                request_id: Some(1),
4635            });
4636        });
4637        cx.executor().advance_clock(Duration::from_secs(1));
4638        cx.executor().run_until_parked();
4639        assert_eq!(
4640            requests_count.load(atomic::Ordering::Acquire),
4641            5,
4642            "After a simulated server refresh request, we should have sent another request",
4643        );
4644
4645        perform_search(search_view, "let ", cx);
4646        cx.executor().advance_clock(Duration::from_secs(1));
4647        cx.executor().run_until_parked();
4648        assert_eq!(
4649            requests_count.load(atomic::Ordering::Acquire),
4650            5,
4651            "New project search should reuse the cached hints",
4652        );
4653        search_view
4654            .update(cx, |search_view, _, cx| {
4655                assert_eq!(
4656                    search_view
4657                        .results_editor
4658                        .update(cx, |editor, cx| editor.display_text(cx)),
4659                    "\n\nfn main() { let a: i32 = 2; }\n"
4660                );
4661            })
4662            .unwrap();
4663    }
4664
4665    fn init_test(cx: &mut TestAppContext) {
4666        cx.update(|cx| {
4667            let settings = SettingsStore::test(cx);
4668            cx.set_global(settings);
4669
4670            theme::init(theme::LoadThemes::JustBase, cx);
4671
4672            editor::init(cx);
4673            crate::init(cx);
4674        });
4675    }
4676
4677    fn perform_search(
4678        search_view: WindowHandle<ProjectSearchView>,
4679        text: impl Into<Arc<str>>,
4680        cx: &mut TestAppContext,
4681    ) {
4682        search_view
4683            .update(cx, |search_view, window, cx| {
4684                search_view.query_editor.update(cx, |query_editor, cx| {
4685                    query_editor.set_text(text, window, cx)
4686                });
4687                search_view.search(cx);
4688            })
4689            .unwrap();
4690        // Ensure editor highlights appear after the search is done
4691        cx.executor().advance_clock(
4692            editor::SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT + Duration::from_millis(100),
4693        );
4694        cx.background_executor.run_until_parked();
4695    }
4696}