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