project_search.rs

   1use crate::{
   2    history::SearchHistory, mode::SearchMode, ActivateRegexMode, ActivateSemanticMode,
   3    ActivateTextMode, CycleMode, NextHistoryQuery, PreviousHistoryQuery, ReplaceAll, ReplaceNext,
   4    SearchOptions, SelectNextMatch, SelectPrevMatch, ToggleCaseSensitive, ToggleIncludeIgnored,
   5    ToggleReplace, ToggleWholeWord,
   6};
   7use anyhow::{Context as _, Result};
   8use collections::HashMap;
   9use editor::{
  10    items::active_match_index, scroll::autoscroll::Autoscroll, Anchor, Editor, EditorEvent,
  11    MultiBuffer, SelectAll, MAX_TAB_TITLE_LEN,
  12};
  13use editor::{EditorElement, EditorStyle};
  14use gpui::{
  15    actions, div, AnyElement, AnyView, AppContext, Context as _, Element, EntityId, EventEmitter,
  16    FocusHandle, FocusableView, FontStyle, FontWeight, InteractiveElement, IntoElement, KeyContext,
  17    Model, ModelContext, ParentElement, PromptLevel, Render, SharedString, Styled, Subscription,
  18    Task, TextStyle, View, ViewContext, VisualContext, WeakModel, WeakView, WhiteSpace,
  19    WindowContext,
  20};
  21use menu::Confirm;
  22use project::{
  23    search::{SearchInputs, SearchQuery},
  24    Entry, Project,
  25};
  26use semantic_index::{SemanticIndex, SemanticIndexStatus};
  27
  28use settings::Settings;
  29use smol::stream::StreamExt;
  30use std::{
  31    any::{Any, TypeId},
  32    collections::HashSet,
  33    mem,
  34    ops::{Not, Range},
  35    path::PathBuf,
  36    time::{Duration, Instant},
  37};
  38use theme::ThemeSettings;
  39
  40use ui::{
  41    h_stack, prelude::*, v_stack, Button, Icon, IconButton, IconElement, Label, LabelCommon,
  42    LabelSize, Selectable, Tooltip,
  43};
  44use util::{paths::PathMatcher, ResultExt as _};
  45use workspace::{
  46    item::{BreadcrumbText, Item, ItemEvent, ItemHandle},
  47    searchable::{Direction, SearchableItem, SearchableItemHandle},
  48    ItemNavHistory, Pane, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView, Workspace,
  49    WorkspaceId,
  50};
  51
  52actions!(
  53    project_search,
  54    [SearchInNew, ToggleFocus, NextField, ToggleFilters]
  55);
  56
  57#[derive(Default)]
  58struct ActiveSearches(HashMap<WeakModel<Project>, WeakView<ProjectSearchView>>);
  59
  60#[derive(Default)]
  61struct ActiveSettings(HashMap<WeakModel<Project>, ProjectSearchSettings>);
  62
  63pub fn init(cx: &mut AppContext) {
  64    // todo!() po
  65    cx.set_global(ActiveSearches::default());
  66    cx.set_global(ActiveSettings::default());
  67    cx.observe_new_views(|workspace: &mut Workspace, _cx| {
  68        workspace
  69            .register_action(ProjectSearchView::deploy)
  70            .register_action(ProjectSearchBar::search_in_new);
  71    })
  72    .detach();
  73}
  74
  75struct ProjectSearch {
  76    project: Model<Project>,
  77    excerpts: Model<MultiBuffer>,
  78    pending_search: Option<Task<Option<()>>>,
  79    match_ranges: Vec<Range<Anchor>>,
  80    active_query: Option<SearchQuery>,
  81    search_id: usize,
  82    search_history: SearchHistory,
  83    no_results: Option<bool>,
  84}
  85
  86#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
  87enum InputPanel {
  88    Query,
  89    Exclude,
  90    Include,
  91}
  92
  93pub struct ProjectSearchView {
  94    focus_handle: FocusHandle,
  95    model: Model<ProjectSearch>,
  96    query_editor: View<Editor>,
  97    replacement_editor: View<Editor>,
  98    results_editor: View<Editor>,
  99    semantic_state: Option<SemanticState>,
 100    semantic_permissioned: Option<bool>,
 101    search_options: SearchOptions,
 102    panels_with_errors: HashSet<InputPanel>,
 103    active_match_index: Option<usize>,
 104    search_id: usize,
 105    query_editor_was_focused: bool,
 106    included_files_editor: View<Editor>,
 107    excluded_files_editor: View<Editor>,
 108    filters_enabled: bool,
 109    replace_enabled: bool,
 110    current_mode: SearchMode,
 111    _subscriptions: Vec<Subscription>,
 112}
 113
 114struct SemanticState {
 115    index_status: SemanticIndexStatus,
 116    maintain_rate_limit: Option<Task<()>>,
 117    _subscription: Subscription,
 118}
 119
 120#[derive(Debug, Clone)]
 121struct ProjectSearchSettings {
 122    search_options: SearchOptions,
 123    filters_enabled: bool,
 124    current_mode: SearchMode,
 125}
 126
 127pub struct ProjectSearchBar {
 128    active_project_search: Option<View<ProjectSearchView>>,
 129    subscription: Option<Subscription>,
 130}
 131
 132impl ProjectSearch {
 133    fn new(project: Model<Project>, cx: &mut ModelContext<Self>) -> Self {
 134        let replica_id = project.read(cx).replica_id();
 135        Self {
 136            project,
 137            excerpts: cx.build_model(|_| MultiBuffer::new(replica_id)),
 138            pending_search: Default::default(),
 139            match_ranges: Default::default(),
 140            active_query: None,
 141            search_id: 0,
 142            search_history: SearchHistory::default(),
 143            no_results: None,
 144        }
 145    }
 146
 147    fn clone(&self, cx: &mut ModelContext<Self>) -> Model<Self> {
 148        cx.build_model(|cx| Self {
 149            project: self.project.clone(),
 150            excerpts: self
 151                .excerpts
 152                .update(cx, |excerpts, cx| cx.build_model(|cx| excerpts.clone(cx))),
 153            pending_search: Default::default(),
 154            match_ranges: self.match_ranges.clone(),
 155            active_query: self.active_query.clone(),
 156            search_id: self.search_id,
 157            search_history: self.search_history.clone(),
 158            no_results: self.no_results.clone(),
 159        })
 160    }
 161
 162    fn search(&mut self, query: SearchQuery, cx: &mut ModelContext<Self>) {
 163        let search = self
 164            .project
 165            .update(cx, |project, cx| project.search(query.clone(), cx));
 166        self.search_id += 1;
 167        self.search_history.add(query.as_str().to_string());
 168        self.active_query = Some(query);
 169        self.match_ranges.clear();
 170        self.pending_search = Some(cx.spawn(|this, mut cx| async move {
 171            let mut matches = search;
 172            let this = this.upgrade()?;
 173            this.update(&mut cx, |this, cx| {
 174                this.match_ranges.clear();
 175                this.excerpts.update(cx, |this, cx| this.clear(cx));
 176                this.no_results = Some(true);
 177            })
 178            .ok()?;
 179
 180            while let Some((buffer, anchors)) = matches.next().await {
 181                let mut ranges = this
 182                    .update(&mut cx, |this, cx| {
 183                        this.no_results = Some(false);
 184                        this.excerpts.update(cx, |excerpts, cx| {
 185                            excerpts.stream_excerpts_with_context_lines(buffer, anchors, 1, cx)
 186                        })
 187                    })
 188                    .ok()?;
 189
 190                while let Some(range) = ranges.next().await {
 191                    this.update(&mut cx, |this, _| this.match_ranges.push(range))
 192                        .ok()?;
 193                }
 194                this.update(&mut cx, |_, cx| cx.notify()).ok()?;
 195            }
 196
 197            this.update(&mut cx, |this, cx| {
 198                this.pending_search.take();
 199                cx.notify();
 200            })
 201            .ok()?;
 202
 203            None
 204        }));
 205        cx.notify();
 206    }
 207
 208    fn semantic_search(&mut self, inputs: &SearchInputs, cx: &mut ModelContext<Self>) {
 209        let search = SemanticIndex::global(cx).map(|index| {
 210            index.update(cx, |semantic_index, cx| {
 211                semantic_index.search_project(
 212                    self.project.clone(),
 213                    inputs.as_str().to_owned(),
 214                    10,
 215                    inputs.files_to_include().to_vec(),
 216                    inputs.files_to_exclude().to_vec(),
 217                    cx,
 218                )
 219            })
 220        });
 221        self.search_id += 1;
 222        self.match_ranges.clear();
 223        self.search_history.add(inputs.as_str().to_string());
 224        self.no_results = None;
 225        self.pending_search = Some(cx.spawn(|this, mut cx| async move {
 226            let results = search?.await.log_err()?;
 227            let matches = results
 228                .into_iter()
 229                .map(|result| (result.buffer, vec![result.range.start..result.range.start]));
 230
 231            this.update(&mut cx, |this, cx| {
 232                this.no_results = Some(true);
 233                this.excerpts.update(cx, |excerpts, cx| {
 234                    excerpts.clear(cx);
 235                });
 236            })
 237            .ok()?;
 238            for (buffer, ranges) in matches {
 239                let mut match_ranges = this
 240                    .update(&mut cx, |this, cx| {
 241                        this.no_results = Some(false);
 242                        this.excerpts.update(cx, |excerpts, cx| {
 243                            excerpts.stream_excerpts_with_context_lines(buffer, ranges, 3, cx)
 244                        })
 245                    })
 246                    .ok()?;
 247                while let Some(match_range) = match_ranges.next().await {
 248                    this.update(&mut cx, |this, cx| {
 249                        this.match_ranges.push(match_range);
 250                        while let Ok(Some(match_range)) = match_ranges.try_next() {
 251                            this.match_ranges.push(match_range);
 252                        }
 253                        cx.notify();
 254                    })
 255                    .ok()?;
 256                }
 257            }
 258
 259            this.update(&mut cx, |this, cx| {
 260                this.pending_search.take();
 261                cx.notify();
 262            })
 263            .ok()?;
 264
 265            None
 266        }));
 267        cx.notify();
 268    }
 269}
 270
 271#[derive(Clone, Debug, PartialEq, Eq)]
 272pub enum ViewEvent {
 273    UpdateTab,
 274    Activate,
 275    EditorEvent(editor::EditorEvent),
 276    Dismiss,
 277}
 278
 279impl EventEmitter<ViewEvent> for ProjectSearchView {}
 280
 281impl Render for ProjectSearchView {
 282    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl Element {
 283        if self.has_matches() {
 284            div()
 285                .flex_1()
 286                .size_full()
 287                .track_focus(&self.focus_handle)
 288                .child(self.results_editor.clone())
 289                .into_any()
 290        } else {
 291            let model = self.model.read(cx);
 292            let has_no_results = model.no_results.unwrap_or(false);
 293            let is_search_underway = model.pending_search.is_some();
 294            let mut major_text = if is_search_underway {
 295                Label::new("Searching...")
 296            } else if has_no_results {
 297                Label::new("No results")
 298            } else {
 299                Label::new(format!("{} search all files", self.current_mode.label()))
 300            };
 301
 302            let mut show_minor_text = true;
 303            let semantic_status = self.semantic_state.as_ref().and_then(|semantic| {
 304                let status = semantic.index_status;
 305                                match status {
 306                                    SemanticIndexStatus::NotAuthenticated => {
 307                                        major_text = Label::new("Not Authenticated");
 308                                        show_minor_text = false;
 309                                        Some(
 310                                            "API Key Missing: Please set 'OPENAI_API_KEY' in Environment Variables. If you authenticated using the Assistant Panel, please restart Zed to Authenticate.".to_string())
 311                                    }
 312                                    SemanticIndexStatus::Indexed => Some("Indexing complete".to_string()),
 313                                    SemanticIndexStatus::Indexing {
 314                                        remaining_files,
 315                                        rate_limit_expiry,
 316                                    } => {
 317                                        if remaining_files == 0 {
 318                                            Some("Indexing...".to_string())
 319                                        } else {
 320                                            if let Some(rate_limit_expiry) = rate_limit_expiry {
 321                                                let remaining_seconds =
 322                                                    rate_limit_expiry.duration_since(Instant::now());
 323                                                if remaining_seconds > Duration::from_secs(0) {
 324                                                    Some(format!(
 325                                                        "Remaining files to index (rate limit resets in {}s): {}",
 326                                                        remaining_seconds.as_secs(),
 327                                                        remaining_files
 328                                                    ))
 329                                                } else {
 330                                                    Some(format!("Remaining files to index: {}", remaining_files))
 331                                                }
 332                                            } else {
 333                                                Some(format!("Remaining files to index: {}", remaining_files))
 334                                            }
 335                                        }
 336                                    }
 337                                    SemanticIndexStatus::NotIndexed => None,
 338                                }
 339            });
 340            let major_text = div().justify_center().max_w_96().child(major_text);
 341
 342            let minor_text: Option<SharedString> = if let Some(no_results) = model.no_results {
 343                if model.pending_search.is_none() && no_results {
 344                    Some("No results found in this project for the provided query".into())
 345                } else {
 346                    None
 347                }
 348            } else {
 349                if let Some(mut semantic_status) = semantic_status {
 350                    semantic_status.extend(self.landing_text_minor().chars());
 351                    Some(semantic_status.into())
 352                } else {
 353                    Some(self.landing_text_minor())
 354                }
 355            };
 356            let minor_text = minor_text.map(|text| {
 357                div()
 358                    .items_center()
 359                    .max_w_96()
 360                    .child(Label::new(text).size(LabelSize::Small))
 361            });
 362            v_stack()
 363                .flex_1()
 364                .size_full()
 365                .justify_center()
 366                .track_focus(&self.focus_handle)
 367                .child(
 368                    h_stack()
 369                        .size_full()
 370                        .justify_center()
 371                        .child(h_stack().flex_1())
 372                        .child(v_stack().child(major_text).children(minor_text))
 373                        .child(h_stack().flex_1()),
 374                )
 375                .into_any()
 376        }
 377    }
 378}
 379
 380impl FocusableView for ProjectSearchView {
 381    fn focus_handle(&self, _: &AppContext) -> gpui::FocusHandle {
 382        self.focus_handle.clone()
 383    }
 384}
 385
 386impl Item for ProjectSearchView {
 387    type Event = ViewEvent;
 388    fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
 389        let query_text = self.query_editor.read(cx).text(cx);
 390
 391        query_text
 392            .is_empty()
 393            .not()
 394            .then(|| query_text.into())
 395            .or_else(|| Some("Project Search".into()))
 396    }
 397
 398    fn act_as_type<'a>(
 399        &'a self,
 400        type_id: TypeId,
 401        self_handle: &'a View<Self>,
 402        _: &'a AppContext,
 403    ) -> Option<AnyView> {
 404        if type_id == TypeId::of::<Self>() {
 405            Some(self_handle.clone().into())
 406        } else if type_id == TypeId::of::<Editor>() {
 407            Some(self.results_editor.clone().into())
 408        } else {
 409            None
 410        }
 411    }
 412
 413    fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
 414        self.results_editor
 415            .update(cx, |editor, cx| editor.deactivated(cx));
 416    }
 417
 418    fn tab_content(&self, _: Option<usize>, selected: bool, cx: &WindowContext<'_>) -> AnyElement {
 419        let last_query: Option<SharedString> = self
 420            .model
 421            .read(cx)
 422            .search_history
 423            .current()
 424            .as_ref()
 425            .map(|query| {
 426                let query_text = util::truncate_and_trailoff(query, MAX_TAB_TITLE_LEN);
 427                query_text.into()
 428            });
 429        let tab_name = last_query
 430            .filter(|query| !query.is_empty())
 431            .unwrap_or_else(|| "Project search".into());
 432        h_stack()
 433            .gap_2()
 434            .child(IconElement::new(Icon::MagnifyingGlass).color(if selected {
 435                Color::Default
 436            } else {
 437                Color::Muted
 438            }))
 439            .child(Label::new(tab_name).color(if selected {
 440                Color::Default
 441            } else {
 442                Color::Muted
 443            }))
 444            .into_any()
 445    }
 446
 447    fn for_each_project_item(
 448        &self,
 449        cx: &AppContext,
 450        f: &mut dyn FnMut(EntityId, &dyn project::Item),
 451    ) {
 452        self.results_editor.for_each_project_item(cx, f)
 453    }
 454
 455    fn is_singleton(&self, _: &AppContext) -> bool {
 456        false
 457    }
 458
 459    fn can_save(&self, _: &AppContext) -> bool {
 460        true
 461    }
 462
 463    fn is_dirty(&self, cx: &AppContext) -> bool {
 464        self.results_editor.read(cx).is_dirty(cx)
 465    }
 466
 467    fn has_conflict(&self, cx: &AppContext) -> bool {
 468        self.results_editor.read(cx).has_conflict(cx)
 469    }
 470
 471    fn save(
 472        &mut self,
 473        project: Model<Project>,
 474        cx: &mut ViewContext<Self>,
 475    ) -> Task<anyhow::Result<()>> {
 476        self.results_editor
 477            .update(cx, |editor, cx| editor.save(project, cx))
 478    }
 479
 480    fn save_as(
 481        &mut self,
 482        _: Model<Project>,
 483        _: PathBuf,
 484        _: &mut ViewContext<Self>,
 485    ) -> Task<anyhow::Result<()>> {
 486        unreachable!("save_as should not have been called")
 487    }
 488
 489    fn reload(
 490        &mut self,
 491        project: Model<Project>,
 492        cx: &mut ViewContext<Self>,
 493    ) -> Task<anyhow::Result<()>> {
 494        self.results_editor
 495            .update(cx, |editor, cx| editor.reload(project, cx))
 496    }
 497
 498    fn clone_on_split(
 499        &self,
 500        _workspace_id: WorkspaceId,
 501        cx: &mut ViewContext<Self>,
 502    ) -> Option<View<Self>>
 503    where
 504        Self: Sized,
 505    {
 506        let model = self.model.update(cx, |model, cx| model.clone(cx));
 507        Some(cx.build_view(|cx| Self::new(model, cx, None)))
 508    }
 509
 510    fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
 511        self.results_editor
 512            .update(cx, |editor, cx| editor.added_to_workspace(workspace, cx));
 513    }
 514
 515    fn set_nav_history(&mut self, nav_history: ItemNavHistory, cx: &mut ViewContext<Self>) {
 516        self.results_editor.update(cx, |editor, _| {
 517            editor.set_nav_history(Some(nav_history));
 518        });
 519    }
 520
 521    fn navigate(&mut self, data: Box<dyn Any>, cx: &mut ViewContext<Self>) -> bool {
 522        self.results_editor
 523            .update(cx, |editor, cx| editor.navigate(data, cx))
 524    }
 525
 526    fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
 527        match event {
 528            ViewEvent::UpdateTab => {
 529                f(ItemEvent::UpdateBreadcrumbs);
 530                f(ItemEvent::UpdateTab);
 531            }
 532            ViewEvent::EditorEvent(editor_event) => {
 533                Editor::to_item_events(editor_event, f);
 534            }
 535            ViewEvent::Dismiss => f(ItemEvent::CloseItem),
 536            _ => {}
 537        }
 538    }
 539
 540    fn breadcrumb_location(&self) -> ToolbarItemLocation {
 541        if self.has_matches() {
 542            ToolbarItemLocation::Secondary
 543        } else {
 544            ToolbarItemLocation::Hidden
 545        }
 546    }
 547
 548    fn breadcrumbs(&self, theme: &theme::Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
 549        self.results_editor.breadcrumbs(theme, cx)
 550    }
 551
 552    fn serialized_item_kind() -> Option<&'static str> {
 553        None
 554    }
 555
 556    fn deserialize(
 557        _project: Model<Project>,
 558        _workspace: WeakView<Workspace>,
 559        _workspace_id: workspace::WorkspaceId,
 560        _item_id: workspace::ItemId,
 561        _cx: &mut ViewContext<Pane>,
 562    ) -> Task<anyhow::Result<View<Self>>> {
 563        unimplemented!()
 564    }
 565}
 566
 567impl ProjectSearchView {
 568    fn toggle_filters(&mut self, cx: &mut ViewContext<Self>) {
 569        self.filters_enabled = !self.filters_enabled;
 570        cx.update_global(|state: &mut ActiveSettings, cx| {
 571            state.0.insert(
 572                self.model.read(cx).project.downgrade(),
 573                self.current_settings(),
 574            );
 575        });
 576    }
 577
 578    fn current_settings(&self) -> ProjectSearchSettings {
 579        ProjectSearchSettings {
 580            search_options: self.search_options,
 581            filters_enabled: self.filters_enabled,
 582            current_mode: self.current_mode,
 583        }
 584    }
 585    fn toggle_search_option(&mut self, option: SearchOptions, cx: &mut ViewContext<Self>) {
 586        self.search_options.toggle(option);
 587        cx.update_global(|state: &mut ActiveSettings, cx| {
 588            state.0.insert(
 589                self.model.read(cx).project.downgrade(),
 590                self.current_settings(),
 591            );
 592        });
 593    }
 594
 595    fn index_project(&mut self, cx: &mut ViewContext<Self>) {
 596        if let Some(semantic_index) = SemanticIndex::global(cx) {
 597            // Semantic search uses no options
 598            self.search_options = SearchOptions::none();
 599
 600            let project = self.model.read(cx).project.clone();
 601
 602            semantic_index.update(cx, |semantic_index, cx| {
 603                semantic_index
 604                    .index_project(project.clone(), cx)
 605                    .detach_and_log_err(cx);
 606            });
 607
 608            self.semantic_state = Some(SemanticState {
 609                index_status: semantic_index.read(cx).status(&project),
 610                maintain_rate_limit: None,
 611                _subscription: cx.observe(&semantic_index, Self::semantic_index_changed),
 612            });
 613            self.semantic_index_changed(semantic_index, cx);
 614        }
 615    }
 616
 617    fn semantic_index_changed(
 618        &mut self,
 619        semantic_index: Model<SemanticIndex>,
 620        cx: &mut ViewContext<Self>,
 621    ) {
 622        let project = self.model.read(cx).project.clone();
 623        if let Some(semantic_state) = self.semantic_state.as_mut() {
 624            cx.notify();
 625            semantic_state.index_status = semantic_index.read(cx).status(&project);
 626            if let SemanticIndexStatus::Indexing {
 627                rate_limit_expiry: Some(_),
 628                ..
 629            } = &semantic_state.index_status
 630            {
 631                if semantic_state.maintain_rate_limit.is_none() {
 632                    semantic_state.maintain_rate_limit =
 633                        Some(cx.spawn(|this, mut cx| async move {
 634                            loop {
 635                                cx.background_executor().timer(Duration::from_secs(1)).await;
 636                                this.update(&mut cx, |_, cx| cx.notify()).log_err();
 637                            }
 638                        }));
 639                    return;
 640                }
 641            } else {
 642                semantic_state.maintain_rate_limit = None;
 643            }
 644        }
 645    }
 646
 647    fn clear_search(&mut self, cx: &mut ViewContext<Self>) {
 648        self.model.update(cx, |model, cx| {
 649            model.pending_search = None;
 650            model.no_results = None;
 651            model.match_ranges.clear();
 652
 653            model.excerpts.update(cx, |excerpts, cx| {
 654                excerpts.clear(cx);
 655            });
 656        });
 657    }
 658
 659    fn activate_search_mode(&mut self, mode: SearchMode, cx: &mut ViewContext<Self>) {
 660        let previous_mode = self.current_mode;
 661        if previous_mode == mode {
 662            return;
 663        }
 664
 665        self.clear_search(cx);
 666        self.current_mode = mode;
 667        self.active_match_index = None;
 668
 669        match mode {
 670            SearchMode::Semantic => {
 671                let has_permission = self.semantic_permissioned(cx);
 672                self.active_match_index = None;
 673                cx.spawn(|this, mut cx| async move {
 674                    let has_permission = has_permission.await?;
 675
 676                    if !has_permission {
 677                        let answer = this.update(&mut cx, |this, cx| {
 678                            let project = this.model.read(cx).project.clone();
 679                            let project_name = project
 680                                .read(cx)
 681                                .worktree_root_names(cx)
 682                                .collect::<Vec<&str>>()
 683                                .join("/");
 684                            let is_plural =
 685                                project_name.chars().filter(|letter| *letter == '/').count() > 0;
 686                            let prompt_text = format!("Would you like to index the '{}' project{} for semantic search? This requires sending code to the OpenAI API", project_name,
 687                                if is_plural {
 688                                    "s"
 689                                } else {""});
 690                            cx.prompt(
 691                                PromptLevel::Info,
 692                                prompt_text.as_str(),
 693                                &["Continue", "Cancel"],
 694                            )
 695                        })?;
 696
 697                        if answer.await? == 0 {
 698                            this.update(&mut cx, |this, _| {
 699                                this.semantic_permissioned = Some(true);
 700                            })?;
 701                        } else {
 702                            this.update(&mut cx, |this, cx| {
 703                                this.semantic_permissioned = Some(false);
 704                                debug_assert_ne!(previous_mode, SearchMode::Semantic, "Tried to re-enable semantic search mode after user modal was rejected");
 705                                this.activate_search_mode(previous_mode, cx);
 706                            })?;
 707                            return anyhow::Ok(());
 708                        }
 709                    }
 710
 711                    this.update(&mut cx, |this, cx| {
 712                        this.index_project(cx);
 713                    })?;
 714
 715                    anyhow::Ok(())
 716                }).detach_and_log_err(cx);
 717            }
 718            SearchMode::Regex | SearchMode::Text => {
 719                self.semantic_state = None;
 720                self.active_match_index = None;
 721                self.search(cx);
 722            }
 723        }
 724
 725        cx.update_global(|state: &mut ActiveSettings, cx| {
 726            state.0.insert(
 727                self.model.read(cx).project.downgrade(),
 728                self.current_settings(),
 729            );
 730        });
 731
 732        cx.notify();
 733    }
 734    fn replace_next(&mut self, _: &ReplaceNext, cx: &mut ViewContext<Self>) {
 735        let model = self.model.read(cx);
 736        if let Some(query) = model.active_query.as_ref() {
 737            if model.match_ranges.is_empty() {
 738                return;
 739            }
 740            if let Some(active_index) = self.active_match_index {
 741                let query = query.clone().with_replacement(self.replacement(cx));
 742                self.results_editor.replace(
 743                    &(Box::new(model.match_ranges[active_index].clone()) as _),
 744                    &query,
 745                    cx,
 746                );
 747                self.select_match(Direction::Next, cx)
 748            }
 749        }
 750    }
 751    pub fn replacement(&self, cx: &AppContext) -> String {
 752        self.replacement_editor.read(cx).text(cx)
 753    }
 754    fn replace_all(&mut self, _: &ReplaceAll, cx: &mut ViewContext<Self>) {
 755        let model = self.model.read(cx);
 756        if let Some(query) = model.active_query.as_ref() {
 757            if model.match_ranges.is_empty() {
 758                return;
 759            }
 760            if self.active_match_index.is_some() {
 761                let query = query.clone().with_replacement(self.replacement(cx));
 762                let matches = model
 763                    .match_ranges
 764                    .iter()
 765                    .map(|item| Box::new(item.clone()) as _)
 766                    .collect::<Vec<_>>();
 767                for item in matches {
 768                    self.results_editor.replace(&item, &query, cx);
 769                }
 770            }
 771        }
 772    }
 773
 774    fn new(
 775        model: Model<ProjectSearch>,
 776        cx: &mut ViewContext<Self>,
 777        settings: Option<ProjectSearchSettings>,
 778    ) -> Self {
 779        let project;
 780        let excerpts;
 781        let mut replacement_text = None;
 782        let mut query_text = String::new();
 783        let mut subscriptions = Vec::new();
 784
 785        // Read in settings if available
 786        let (mut options, current_mode, filters_enabled) = if let Some(settings) = settings {
 787            (
 788                settings.search_options,
 789                settings.current_mode,
 790                settings.filters_enabled,
 791            )
 792        } else {
 793            (SearchOptions::NONE, Default::default(), false)
 794        };
 795
 796        {
 797            let model = model.read(cx);
 798            project = model.project.clone();
 799            excerpts = model.excerpts.clone();
 800            if let Some(active_query) = model.active_query.as_ref() {
 801                query_text = active_query.as_str().to_string();
 802                replacement_text = active_query.replacement().map(ToOwned::to_owned);
 803                options = SearchOptions::from_query(active_query);
 804            }
 805        }
 806        subscriptions.push(cx.observe(&model, |this, _, cx| this.model_changed(cx)));
 807
 808        let query_editor = cx.build_view(|cx| {
 809            let mut editor = Editor::single_line(cx);
 810            editor.set_placeholder_text("Text search all files", cx);
 811            editor.set_text(query_text, cx);
 812            editor
 813        });
 814        // Subscribe to query_editor in order to reraise editor events for workspace item activation purposes
 815        subscriptions.push(
 816            cx.subscribe(&query_editor, |_, _, event: &EditorEvent, cx| {
 817                cx.emit(ViewEvent::EditorEvent(event.clone()))
 818            }),
 819        );
 820        let replacement_editor = cx.build_view(|cx| {
 821            let mut editor = Editor::single_line(cx);
 822            editor.set_placeholder_text("Replace in project..", cx);
 823            if let Some(text) = replacement_text {
 824                editor.set_text(text, cx);
 825            }
 826            editor
 827        });
 828        let results_editor = cx.build_view(|cx| {
 829            let mut editor = Editor::for_multibuffer(excerpts, Some(project.clone()), cx);
 830            editor.set_searchable(false);
 831            editor
 832        });
 833        subscriptions.push(cx.observe(&results_editor, |_, _, cx| cx.emit(ViewEvent::UpdateTab)));
 834
 835        subscriptions.push(
 836            cx.subscribe(&results_editor, |this, _, event: &EditorEvent, cx| {
 837                if matches!(event, editor::EditorEvent::SelectionsChanged { .. }) {
 838                    this.update_match_index(cx);
 839                }
 840                // Reraise editor events for workspace item activation purposes
 841                cx.emit(ViewEvent::EditorEvent(event.clone()));
 842            }),
 843        );
 844
 845        let included_files_editor = cx.build_view(|cx| {
 846            let mut editor = Editor::single_line(cx);
 847            editor.set_placeholder_text("Include: crates/**/*.toml", cx);
 848
 849            editor
 850        });
 851        // Subscribe to include_files_editor in order to reraise editor events for workspace item activation purposes
 852        subscriptions.push(
 853            cx.subscribe(&included_files_editor, |_, _, event: &EditorEvent, cx| {
 854                cx.emit(ViewEvent::EditorEvent(event.clone()))
 855            }),
 856        );
 857
 858        let excluded_files_editor = cx.build_view(|cx| {
 859            let mut editor = Editor::single_line(cx);
 860            editor.set_placeholder_text("Exclude: vendor/*, *.lock", cx);
 861
 862            editor
 863        });
 864        // Subscribe to excluded_files_editor in order to reraise editor events for workspace item activation purposes
 865        subscriptions.push(
 866            cx.subscribe(&excluded_files_editor, |_, _, event: &EditorEvent, cx| {
 867                cx.emit(ViewEvent::EditorEvent(event.clone()))
 868            }),
 869        );
 870
 871        let focus_handle = cx.focus_handle();
 872        subscriptions.push(cx.on_focus_in(&focus_handle, |this, cx| {
 873            if this.focus_handle.is_focused(cx) {
 874                if this.has_matches() {
 875                    this.results_editor.focus_handle(cx).focus(cx);
 876                } else {
 877                    this.query_editor.focus_handle(cx).focus(cx);
 878                }
 879            }
 880        }));
 881
 882        // Check if Worktrees have all been previously indexed
 883        let mut this = ProjectSearchView {
 884            focus_handle,
 885            replacement_editor,
 886            search_id: model.read(cx).search_id,
 887            model,
 888            query_editor,
 889            results_editor,
 890            semantic_state: None,
 891            semantic_permissioned: None,
 892            search_options: options,
 893            panels_with_errors: HashSet::new(),
 894            active_match_index: None,
 895            query_editor_was_focused: false,
 896            included_files_editor,
 897            excluded_files_editor,
 898            filters_enabled,
 899            current_mode,
 900            replace_enabled: false,
 901            _subscriptions: subscriptions,
 902        };
 903        this.model_changed(cx);
 904        this
 905    }
 906
 907    fn semantic_permissioned(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<bool>> {
 908        if let Some(value) = self.semantic_permissioned {
 909            return Task::ready(Ok(value));
 910        }
 911
 912        SemanticIndex::global(cx)
 913            .map(|semantic| {
 914                let project = self.model.read(cx).project.clone();
 915                semantic.update(cx, |this, cx| this.project_previously_indexed(&project, cx))
 916            })
 917            .unwrap_or(Task::ready(Ok(false)))
 918    }
 919
 920    pub fn new_search_in_directory(
 921        workspace: &mut Workspace,
 922        dir_entry: &Entry,
 923        cx: &mut ViewContext<Workspace>,
 924    ) {
 925        if !dir_entry.is_dir() {
 926            return;
 927        }
 928        let Some(filter_str) = dir_entry.path.to_str() else {
 929            return;
 930        };
 931
 932        let model = cx.build_model(|cx| ProjectSearch::new(workspace.project().clone(), cx));
 933        let search = cx.build_view(|cx| ProjectSearchView::new(model, cx, None));
 934        workspace.add_item(Box::new(search.clone()), cx);
 935        search.update(cx, |search, cx| {
 936            search
 937                .included_files_editor
 938                .update(cx, |editor, cx| editor.set_text(filter_str, cx));
 939            search.filters_enabled = true;
 940            search.focus_query_editor(cx)
 941        });
 942    }
 943
 944    // Add another search tab to the workspace.
 945    fn deploy(
 946        workspace: &mut Workspace,
 947        _: &workspace::NewSearch,
 948        cx: &mut ViewContext<Workspace>,
 949    ) {
 950        // Clean up entries for dropped projects
 951        cx.update_global(|state: &mut ActiveSearches, _cx| {
 952            state.0.retain(|project, _| project.is_upgradable())
 953        });
 954
 955        let query = workspace.active_item(cx).and_then(|item| {
 956            let editor = item.act_as::<Editor>(cx)?;
 957            let query = editor.query_suggestion(cx);
 958            if query.is_empty() {
 959                None
 960            } else {
 961                Some(query)
 962            }
 963        });
 964
 965        let settings = cx
 966            .global::<ActiveSettings>()
 967            .0
 968            .get(&workspace.project().downgrade());
 969
 970        let settings = if let Some(settings) = settings {
 971            Some(settings.clone())
 972        } else {
 973            None
 974        };
 975
 976        let model = cx.build_model(|cx| ProjectSearch::new(workspace.project().clone(), cx));
 977        let search = cx.build_view(|cx| ProjectSearchView::new(model, cx, settings));
 978
 979        workspace.add_item(Box::new(search.clone()), cx);
 980
 981        search.update(cx, |search, cx| {
 982            if let Some(query) = query {
 983                search.set_query(&query, cx);
 984            }
 985            search.focus_query_editor(cx)
 986        });
 987    }
 988
 989    fn search(&mut self, cx: &mut ViewContext<Self>) {
 990        let mode = self.current_mode;
 991        match mode {
 992            SearchMode::Semantic => {
 993                if self.semantic_state.is_some() {
 994                    if let Some(query) = self.build_search_query(cx) {
 995                        self.model
 996                            .update(cx, |model, cx| model.semantic_search(query.as_inner(), cx));
 997                    }
 998                }
 999            }
1000
1001            _ => {
1002                if let Some(query) = self.build_search_query(cx) {
1003                    self.model.update(cx, |model, cx| model.search(query, cx));
1004                }
1005            }
1006        }
1007    }
1008
1009    fn build_search_query(&mut self, cx: &mut ViewContext<Self>) -> Option<SearchQuery> {
1010        let text = self.query_editor.read(cx).text(cx);
1011        let included_files =
1012            match Self::parse_path_matches(&self.included_files_editor.read(cx).text(cx)) {
1013                Ok(included_files) => {
1014                    self.panels_with_errors.remove(&InputPanel::Include);
1015                    included_files
1016                }
1017                Err(_e) => {
1018                    self.panels_with_errors.insert(InputPanel::Include);
1019                    cx.notify();
1020                    return None;
1021                }
1022            };
1023        let excluded_files =
1024            match Self::parse_path_matches(&self.excluded_files_editor.read(cx).text(cx)) {
1025                Ok(excluded_files) => {
1026                    self.panels_with_errors.remove(&InputPanel::Exclude);
1027                    excluded_files
1028                }
1029                Err(_e) => {
1030                    self.panels_with_errors.insert(InputPanel::Exclude);
1031                    cx.notify();
1032                    return None;
1033                }
1034            };
1035        let current_mode = self.current_mode;
1036        match current_mode {
1037            SearchMode::Regex => {
1038                match SearchQuery::regex(
1039                    text,
1040                    self.search_options.contains(SearchOptions::WHOLE_WORD),
1041                    self.search_options.contains(SearchOptions::CASE_SENSITIVE),
1042                    self.search_options.contains(SearchOptions::INCLUDE_IGNORED),
1043                    included_files,
1044                    excluded_files,
1045                ) {
1046                    Ok(query) => {
1047                        self.panels_with_errors.remove(&InputPanel::Query);
1048                        Some(query)
1049                    }
1050                    Err(_e) => {
1051                        self.panels_with_errors.insert(InputPanel::Query);
1052                        cx.notify();
1053                        None
1054                    }
1055                }
1056            }
1057            _ => match SearchQuery::text(
1058                text,
1059                self.search_options.contains(SearchOptions::WHOLE_WORD),
1060                self.search_options.contains(SearchOptions::CASE_SENSITIVE),
1061                self.search_options.contains(SearchOptions::INCLUDE_IGNORED),
1062                included_files,
1063                excluded_files,
1064            ) {
1065                Ok(query) => {
1066                    self.panels_with_errors.remove(&InputPanel::Query);
1067                    Some(query)
1068                }
1069                Err(_e) => {
1070                    self.panels_with_errors.insert(InputPanel::Query);
1071                    cx.notify();
1072                    None
1073                }
1074            },
1075        }
1076    }
1077
1078    fn parse_path_matches(text: &str) -> anyhow::Result<Vec<PathMatcher>> {
1079        text.split(',')
1080            .map(str::trim)
1081            .filter(|maybe_glob_str| !maybe_glob_str.is_empty())
1082            .map(|maybe_glob_str| {
1083                PathMatcher::new(maybe_glob_str)
1084                    .with_context(|| format!("parsing {maybe_glob_str} as path matcher"))
1085            })
1086            .collect()
1087    }
1088
1089    fn select_match(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
1090        if let Some(index) = self.active_match_index {
1091            let match_ranges = self.model.read(cx).match_ranges.clone();
1092            let new_index = self.results_editor.update(cx, |editor, cx| {
1093                editor.match_index_for_direction(&match_ranges, index, direction, 1, cx)
1094            });
1095
1096            let range_to_select = match_ranges[new_index].clone();
1097            self.results_editor.update(cx, |editor, cx| {
1098                let range_to_select = editor.range_for_match(&range_to_select);
1099                editor.unfold_ranges([range_to_select.clone()], false, true, cx);
1100                editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
1101                    s.select_ranges([range_to_select])
1102                });
1103            });
1104        }
1105    }
1106
1107    fn focus_query_editor(&mut self, cx: &mut ViewContext<Self>) {
1108        self.query_editor.update(cx, |query_editor, cx| {
1109            query_editor.select_all(&SelectAll, cx);
1110        });
1111        self.query_editor_was_focused = true;
1112        let editor_handle = self.query_editor.focus_handle(cx);
1113        cx.focus(&editor_handle);
1114    }
1115
1116    fn set_query(&mut self, query: &str, cx: &mut ViewContext<Self>) {
1117        self.query_editor
1118            .update(cx, |query_editor, cx| query_editor.set_text(query, cx));
1119    }
1120
1121    fn focus_results_editor(&mut self, cx: &mut ViewContext<Self>) {
1122        self.query_editor.update(cx, |query_editor, cx| {
1123            let cursor = query_editor.selections.newest_anchor().head();
1124            query_editor.change_selections(None, cx, |s| s.select_ranges([cursor.clone()..cursor]));
1125        });
1126        self.query_editor_was_focused = false;
1127        let results_handle = self.results_editor.focus_handle(cx);
1128        cx.focus(&results_handle);
1129    }
1130
1131    fn model_changed(&mut self, cx: &mut ViewContext<Self>) {
1132        let match_ranges = self.model.read(cx).match_ranges.clone();
1133        if match_ranges.is_empty() {
1134            self.active_match_index = None;
1135        } else {
1136            self.active_match_index = Some(0);
1137            self.update_match_index(cx);
1138            let prev_search_id = mem::replace(&mut self.search_id, self.model.read(cx).search_id);
1139            let is_new_search = self.search_id != prev_search_id;
1140            self.results_editor.update(cx, |editor, cx| {
1141                if is_new_search {
1142                    let range_to_select = match_ranges
1143                        .first()
1144                        .clone()
1145                        .map(|range| editor.range_for_match(range));
1146                    editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
1147                        s.select_ranges(range_to_select)
1148                    });
1149                }
1150                editor.highlight_background::<Self>(
1151                    match_ranges,
1152                    |theme| theme.search_match_background,
1153                    cx,
1154                );
1155            });
1156            if is_new_search && self.query_editor.focus_handle(cx).is_focused(cx) {
1157                self.focus_results_editor(cx);
1158            }
1159        }
1160
1161        cx.emit(ViewEvent::UpdateTab);
1162        cx.notify();
1163    }
1164
1165    fn update_match_index(&mut self, cx: &mut ViewContext<Self>) {
1166        let results_editor = self.results_editor.read(cx);
1167        let new_index = active_match_index(
1168            &self.model.read(cx).match_ranges,
1169            &results_editor.selections.newest_anchor().head(),
1170            &results_editor.buffer().read(cx).snapshot(cx),
1171        );
1172        if self.active_match_index != new_index {
1173            self.active_match_index = new_index;
1174            cx.notify();
1175        }
1176    }
1177
1178    pub fn has_matches(&self) -> bool {
1179        self.active_match_index.is_some()
1180    }
1181
1182    fn landing_text_minor(&self) -> SharedString {
1183        match self.current_mode {
1184            SearchMode::Text | SearchMode::Regex => "Include/exclude specific paths with the filter option. Matching exact word and/or casing is available too.".into(),
1185            SearchMode::Semantic => "\nSimply explain the code you are looking to find. ex. 'prompt user for permissions to index their project'".into()
1186        }
1187    }
1188}
1189
1190impl Default for ProjectSearchBar {
1191    fn default() -> Self {
1192        Self::new()
1193    }
1194}
1195
1196impl ProjectSearchBar {
1197    pub fn new() -> Self {
1198        Self {
1199            active_project_search: Default::default(),
1200            subscription: Default::default(),
1201        }
1202    }
1203
1204    fn cycle_mode(&self, _: &CycleMode, cx: &mut ViewContext<Self>) {
1205        if let Some(view) = self.active_project_search.as_ref() {
1206            view.update(cx, |this, cx| {
1207                let new_mode =
1208                    crate::mode::next_mode(&this.current_mode, SemanticIndex::enabled(cx));
1209                this.activate_search_mode(new_mode, cx);
1210                let editor_handle = this.query_editor.focus_handle(cx);
1211                cx.focus(&editor_handle);
1212            });
1213        }
1214    }
1215
1216    fn confirm(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
1217        if let Some(search_view) = self.active_project_search.as_ref() {
1218            search_view.update(cx, |search_view, cx| {
1219                if !search_view
1220                    .replacement_editor
1221                    .focus_handle(cx)
1222                    .is_focused(cx)
1223                {
1224                    cx.stop_propagation();
1225                    search_view.search(cx);
1226                }
1227            });
1228        }
1229    }
1230
1231    fn search_in_new(workspace: &mut Workspace, _: &SearchInNew, cx: &mut ViewContext<Workspace>) {
1232        if let Some(search_view) = workspace
1233            .active_item(cx)
1234            .and_then(|item| item.downcast::<ProjectSearchView>())
1235        {
1236            let new_query = search_view.update(cx, |search_view, cx| {
1237                let new_query = search_view.build_search_query(cx);
1238                if new_query.is_some() {
1239                    if let Some(old_query) = search_view.model.read(cx).active_query.clone() {
1240                        search_view.query_editor.update(cx, |editor, cx| {
1241                            editor.set_text(old_query.as_str(), cx);
1242                        });
1243                        search_view.search_options = SearchOptions::from_query(&old_query);
1244                    }
1245                }
1246                new_query
1247            });
1248            if let Some(new_query) = new_query {
1249                let model = cx.build_model(|cx| {
1250                    let mut model = ProjectSearch::new(workspace.project().clone(), cx);
1251                    model.search(new_query, cx);
1252                    model
1253                });
1254                workspace.add_item(
1255                    Box::new(cx.build_view(|cx| ProjectSearchView::new(model, cx, None))),
1256                    cx,
1257                );
1258            }
1259        }
1260    }
1261
1262    fn tab(&mut self, _: &editor::Tab, cx: &mut ViewContext<Self>) {
1263        self.cycle_field(Direction::Next, cx);
1264    }
1265
1266    fn tab_previous(&mut self, _: &editor::TabPrev, cx: &mut ViewContext<Self>) {
1267        self.cycle_field(Direction::Prev, cx);
1268    }
1269
1270    fn cycle_field(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
1271        let active_project_search = match &self.active_project_search {
1272            Some(active_project_search) => active_project_search,
1273
1274            None => {
1275                return;
1276            }
1277        };
1278
1279        active_project_search.update(cx, |project_view, cx| {
1280            let mut views = vec![&project_view.query_editor];
1281            if project_view.filters_enabled {
1282                views.extend([
1283                    &project_view.included_files_editor,
1284                    &project_view.excluded_files_editor,
1285                ]);
1286            }
1287            if project_view.replace_enabled {
1288                views.push(&project_view.replacement_editor);
1289            }
1290            let current_index = match views
1291                .iter()
1292                .enumerate()
1293                .find(|(_, view)| view.focus_handle(cx).is_focused(cx))
1294            {
1295                Some((index, _)) => index,
1296
1297                None => {
1298                    return;
1299                }
1300            };
1301
1302            let new_index = match direction {
1303                Direction::Next => (current_index + 1) % views.len(),
1304                Direction::Prev if current_index == 0 => views.len() - 1,
1305                Direction::Prev => (current_index - 1) % views.len(),
1306            };
1307            let next_focus_handle = views[new_index].focus_handle(cx);
1308            cx.focus(&next_focus_handle);
1309            cx.stop_propagation();
1310        });
1311    }
1312
1313    fn toggle_search_option(&mut self, option: SearchOptions, cx: &mut ViewContext<Self>) -> bool {
1314        if let Some(search_view) = self.active_project_search.as_ref() {
1315            search_view.update(cx, |search_view, cx| {
1316                search_view.toggle_search_option(option, cx);
1317                search_view.search(cx);
1318            });
1319
1320            cx.notify();
1321            true
1322        } else {
1323            false
1324        }
1325    }
1326
1327    fn toggle_replace(&mut self, _: &ToggleReplace, cx: &mut ViewContext<Self>) {
1328        if let Some(search) = &self.active_project_search {
1329            search.update(cx, |this, cx| {
1330                this.replace_enabled = !this.replace_enabled;
1331                let editor_to_focus = if !this.replace_enabled {
1332                    this.query_editor.focus_handle(cx)
1333                } else {
1334                    this.replacement_editor.focus_handle(cx)
1335                };
1336                cx.focus(&editor_to_focus);
1337                cx.notify();
1338            });
1339        }
1340    }
1341
1342    fn toggle_filters(&mut self, cx: &mut ViewContext<Self>) -> bool {
1343        if let Some(search_view) = self.active_project_search.as_ref() {
1344            search_view.update(cx, |search_view, cx| {
1345                search_view.toggle_filters(cx);
1346                search_view
1347                    .included_files_editor
1348                    .update(cx, |_, cx| cx.notify());
1349                search_view
1350                    .excluded_files_editor
1351                    .update(cx, |_, cx| cx.notify());
1352                cx.refresh();
1353                cx.notify();
1354            });
1355            cx.notify();
1356            true
1357        } else {
1358            false
1359        }
1360    }
1361
1362    fn activate_search_mode(&self, mode: SearchMode, cx: &mut ViewContext<Self>) {
1363        // Update Current Mode
1364        if let Some(search_view) = self.active_project_search.as_ref() {
1365            search_view.update(cx, |search_view, cx| {
1366                search_view.activate_search_mode(mode, cx);
1367            });
1368            cx.notify();
1369        }
1370    }
1371
1372    fn is_option_enabled(&self, option: SearchOptions, cx: &AppContext) -> bool {
1373        if let Some(search) = self.active_project_search.as_ref() {
1374            search.read(cx).search_options.contains(option)
1375        } else {
1376            false
1377        }
1378    }
1379
1380    fn next_history_query(&mut self, _: &NextHistoryQuery, cx: &mut ViewContext<Self>) {
1381        if let Some(search_view) = self.active_project_search.as_ref() {
1382            search_view.update(cx, |search_view, cx| {
1383                let new_query = search_view.model.update(cx, |model, _| {
1384                    if let Some(new_query) = model.search_history.next().map(str::to_string) {
1385                        new_query
1386                    } else {
1387                        model.search_history.reset_selection();
1388                        String::new()
1389                    }
1390                });
1391                search_view.set_query(&new_query, cx);
1392            });
1393        }
1394    }
1395
1396    fn previous_history_query(&mut self, _: &PreviousHistoryQuery, cx: &mut ViewContext<Self>) {
1397        if let Some(search_view) = self.active_project_search.as_ref() {
1398            search_view.update(cx, |search_view, cx| {
1399                if search_view.query_editor.read(cx).text(cx).is_empty() {
1400                    if let Some(new_query) = search_view
1401                        .model
1402                        .read(cx)
1403                        .search_history
1404                        .current()
1405                        .map(str::to_string)
1406                    {
1407                        search_view.set_query(&new_query, cx);
1408                        return;
1409                    }
1410                }
1411
1412                if let Some(new_query) = search_view.model.update(cx, |model, _| {
1413                    model.search_history.previous().map(str::to_string)
1414                }) {
1415                    search_view.set_query(&new_query, cx);
1416                }
1417            });
1418        }
1419    }
1420
1421    fn new_placeholder_text(&self, cx: &mut ViewContext<Self>) -> Option<String> {
1422        let previous_query_keystrokes = cx
1423            .bindings_for_action(&PreviousHistoryQuery {})
1424            .into_iter()
1425            .next()
1426            .map(|binding| {
1427                binding
1428                    .keystrokes()
1429                    .iter()
1430                    .map(|k| k.to_string())
1431                    .collect::<Vec<_>>()
1432            });
1433        let next_query_keystrokes = cx
1434            .bindings_for_action(&NextHistoryQuery {})
1435            .into_iter()
1436            .next()
1437            .map(|binding| {
1438                binding
1439                    .keystrokes()
1440                    .iter()
1441                    .map(|k| k.to_string())
1442                    .collect::<Vec<_>>()
1443            });
1444        let new_placeholder_text = match (previous_query_keystrokes, next_query_keystrokes) {
1445            (Some(previous_query_keystrokes), Some(next_query_keystrokes)) => Some(format!(
1446                "Search ({}/{} for previous/next query)",
1447                previous_query_keystrokes.join(" "),
1448                next_query_keystrokes.join(" ")
1449            )),
1450            (None, Some(next_query_keystrokes)) => Some(format!(
1451                "Search ({} for next query)",
1452                next_query_keystrokes.join(" ")
1453            )),
1454            (Some(previous_query_keystrokes), None) => Some(format!(
1455                "Search ({} for previous query)",
1456                previous_query_keystrokes.join(" ")
1457            )),
1458            (None, None) => None,
1459        };
1460        new_placeholder_text
1461    }
1462
1463    fn render_text_input(&self, editor: &View<Editor>, cx: &ViewContext<Self>) -> impl IntoElement {
1464        let settings = ThemeSettings::get_global(cx);
1465        let text_style = TextStyle {
1466            color: if editor.read(cx).read_only() {
1467                cx.theme().colors().text_disabled
1468            } else {
1469                cx.theme().colors().text
1470            },
1471            font_family: settings.ui_font.family.clone(),
1472            font_features: settings.ui_font.features,
1473            font_size: rems(0.875).into(),
1474            font_weight: FontWeight::NORMAL,
1475            font_style: FontStyle::Normal,
1476            line_height: relative(1.3).into(),
1477            background_color: None,
1478            underline: None,
1479            white_space: WhiteSpace::Normal,
1480        };
1481
1482        EditorElement::new(
1483            &editor,
1484            EditorStyle {
1485                background: cx.theme().colors().editor_background,
1486                local_player: cx.theme().players().local(),
1487                text: text_style,
1488                ..Default::default()
1489            },
1490        )
1491    }
1492}
1493
1494impl Render for ProjectSearchBar {
1495    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl Element {
1496        let Some(search) = self.active_project_search.clone() else {
1497            return div();
1498        };
1499        let mut key_context = KeyContext::default();
1500        key_context.add("ProjectSearchBar");
1501        if let Some(placeholder_text) = self.new_placeholder_text(cx) {
1502            search.update(cx, |search, cx| {
1503                search.query_editor.update(cx, |this, cx| {
1504                    this.set_placeholder_text(placeholder_text, cx)
1505                })
1506            });
1507        }
1508        let search = search.read(cx);
1509        let semantic_is_available = SemanticIndex::enabled(cx);
1510        let query_column = v_stack().child(
1511            h_stack()
1512                .min_w(rems(512. / 16.))
1513                .px_2()
1514                .py_1()
1515                .gap_2()
1516                .bg(cx.theme().colors().editor_background)
1517                .border_1()
1518                .border_color(cx.theme().colors().border)
1519                .rounded_lg()
1520                .on_action(cx.listener(|this, action, cx| this.confirm(action, cx)))
1521                .on_action(cx.listener(|this, action, cx| this.previous_history_query(action, cx)))
1522                .on_action(cx.listener(|this, action, cx| this.next_history_query(action, cx)))
1523                .child(IconElement::new(Icon::MagnifyingGlass))
1524                .child(self.render_text_input(&search.query_editor, cx))
1525                .child(
1526                    h_stack()
1527                        .child(
1528                            IconButton::new("project-search-filter-button", Icon::Filter)
1529                                .tooltip(|cx| {
1530                                    Tooltip::for_action("Toggle filters", &ToggleFilters, cx)
1531                                })
1532                                .on_click(cx.listener(|this, _, cx| {
1533                                    this.toggle_filters(cx);
1534                                }))
1535                                .selected(
1536                                    self.active_project_search
1537                                        .as_ref()
1538                                        .map(|search| search.read(cx).filters_enabled)
1539                                        .unwrap_or_default(),
1540                                ),
1541                        )
1542                        .when(search.current_mode != SearchMode::Semantic, |this| {
1543                            this.child(
1544                                IconButton::new(
1545                                    "project-search-case-sensitive",
1546                                    Icon::CaseSensitive,
1547                                )
1548                                .tooltip(|cx| {
1549                                    Tooltip::for_action(
1550                                        "Toggle case sensitive",
1551                                        &ToggleCaseSensitive,
1552                                        cx,
1553                                    )
1554                                })
1555                                .selected(self.is_option_enabled(SearchOptions::CASE_SENSITIVE, cx))
1556                                .on_click(cx.listener(
1557                                    |this, _, cx| {
1558                                        this.toggle_search_option(
1559                                            SearchOptions::CASE_SENSITIVE,
1560                                            cx,
1561                                        );
1562                                    },
1563                                )),
1564                            )
1565                            .child(
1566                                IconButton::new("project-search-whole-word", Icon::WholeWord)
1567                                    .tooltip(|cx| {
1568                                        Tooltip::for_action(
1569                                            "Toggle whole word",
1570                                            &ToggleWholeWord,
1571                                            cx,
1572                                        )
1573                                    })
1574                                    .selected(self.is_option_enabled(SearchOptions::WHOLE_WORD, cx))
1575                                    .on_click(cx.listener(|this, _, cx| {
1576                                        this.toggle_search_option(SearchOptions::WHOLE_WORD, cx);
1577                                    })),
1578                            )
1579                        }),
1580                ),
1581        );
1582
1583        let mode_column = v_stack().items_start().justify_start().child(
1584            h_stack()
1585                .child(
1586                    h_stack()
1587                        .child(
1588                            Button::new("project-search-text-button", "Text")
1589                                .selected(search.current_mode == SearchMode::Text)
1590                                .on_click(cx.listener(|this, _, cx| {
1591                                    this.activate_search_mode(SearchMode::Text, cx)
1592                                }))
1593                                .tooltip(|cx| {
1594                                    Tooltip::for_action("Toggle text search", &ActivateTextMode, cx)
1595                                }),
1596                        )
1597                        .child(
1598                            Button::new("project-search-regex-button", "Regex")
1599                                .selected(search.current_mode == SearchMode::Regex)
1600                                .on_click(cx.listener(|this, _, cx| {
1601                                    this.activate_search_mode(SearchMode::Regex, cx)
1602                                }))
1603                                .tooltip(|cx| {
1604                                    Tooltip::for_action(
1605                                        "Toggle regular expression search",
1606                                        &ActivateRegexMode,
1607                                        cx,
1608                                    )
1609                                }),
1610                        )
1611                        .when(semantic_is_available, |this| {
1612                            this.child(
1613                                Button::new("project-search-semantic-button", "Semantic")
1614                                    .selected(search.current_mode == SearchMode::Semantic)
1615                                    .on_click(cx.listener(|this, _, cx| {
1616                                        this.activate_search_mode(SearchMode::Semantic, cx)
1617                                    }))
1618                                    .tooltip(|cx| {
1619                                        Tooltip::for_action(
1620                                            "Toggle semantic search",
1621                                            &ActivateSemanticMode,
1622                                            cx,
1623                                        )
1624                                    }),
1625                            )
1626                        }),
1627                )
1628                .child(
1629                    IconButton::new("project-search-toggle-replace", Icon::Replace)
1630                        .on_click(cx.listener(|this, _, cx| {
1631                            this.toggle_replace(&ToggleReplace, cx);
1632                        }))
1633                        .tooltip(|cx| Tooltip::for_action("Toggle replace", &ToggleReplace, cx)),
1634                ),
1635        );
1636        let replace_column = if search.replace_enabled {
1637            h_stack()
1638                .flex_1()
1639                .h_full()
1640                .gap_2()
1641                .px_2()
1642                .py_1()
1643                .border_1()
1644                .border_color(cx.theme().colors().border)
1645                .rounded_lg()
1646                .child(IconElement::new(Icon::Replace).size(ui::IconSize::Small))
1647                .child(self.render_text_input(&search.replacement_editor, cx))
1648        } else {
1649            // Fill out the space if we don't have a replacement editor.
1650            h_stack().flex_1()
1651        };
1652        let actions_column = h_stack()
1653            .when(search.replace_enabled, |this| {
1654                this.child(
1655                    IconButton::new("project-search-replace-next", Icon::ReplaceNext)
1656                        .on_click(cx.listener(|this, _, cx| {
1657                            if let Some(search) = this.active_project_search.as_ref() {
1658                                search.update(cx, |this, cx| {
1659                                    this.replace_next(&ReplaceNext, cx);
1660                                })
1661                            }
1662                        }))
1663                        .tooltip(|cx| Tooltip::for_action("Replace next match", &ReplaceNext, cx)),
1664                )
1665                .child(
1666                    IconButton::new("project-search-replace-all", Icon::ReplaceAll)
1667                        .on_click(cx.listener(|this, _, cx| {
1668                            if let Some(search) = this.active_project_search.as_ref() {
1669                                search.update(cx, |this, cx| {
1670                                    this.replace_all(&ReplaceAll, cx);
1671                                })
1672                            }
1673                        }))
1674                        .tooltip(|cx| Tooltip::for_action("Replace all matches", &ReplaceAll, cx)),
1675                )
1676            })
1677            .when_some(search.active_match_index, |mut this, index| {
1678                let index = index + 1;
1679                let match_quantity = search.model.read(cx).match_ranges.len();
1680                if match_quantity > 0 {
1681                    debug_assert!(match_quantity >= index);
1682                    this = this.child(Label::new(format!("{index}/{match_quantity}")))
1683                }
1684                this
1685            })
1686            .child(
1687                IconButton::new("project-search-prev-match", Icon::ChevronLeft)
1688                    .disabled(search.active_match_index.is_none())
1689                    .on_click(cx.listener(|this, _, cx| {
1690                        if let Some(search) = this.active_project_search.as_ref() {
1691                            search.update(cx, |this, cx| {
1692                                this.select_match(Direction::Prev, cx);
1693                            })
1694                        }
1695                    }))
1696                    .tooltip(|cx| {
1697                        Tooltip::for_action("Go to previous match", &SelectPrevMatch, cx)
1698                    }),
1699            )
1700            .child(
1701                IconButton::new("project-search-next-match", Icon::ChevronRight)
1702                    .disabled(search.active_match_index.is_none())
1703                    .on_click(cx.listener(|this, _, cx| {
1704                        if let Some(search) = this.active_project_search.as_ref() {
1705                            search.update(cx, |this, cx| {
1706                                this.select_match(Direction::Next, cx);
1707                            })
1708                        }
1709                    }))
1710                    .tooltip(|cx| Tooltip::for_action("Go to next match", &SelectNextMatch, cx)),
1711            );
1712
1713        v_stack()
1714            .key_context(key_context)
1715            .flex_grow()
1716            .gap_2()
1717            .on_action(cx.listener(|this, _: &ToggleFilters, cx| {
1718                this.toggle_filters(cx);
1719            }))
1720            .on_action(cx.listener(|this, _: &ActivateTextMode, cx| {
1721                this.activate_search_mode(SearchMode::Text, cx)
1722            }))
1723            .on_action(cx.listener(|this, _: &ActivateRegexMode, cx| {
1724                this.activate_search_mode(SearchMode::Regex, cx)
1725            }))
1726            .on_action(cx.listener(|this, _: &ActivateSemanticMode, cx| {
1727                this.activate_search_mode(SearchMode::Semantic, cx)
1728            }))
1729            .capture_action(cx.listener(|this, action, cx| {
1730                this.tab(action, cx);
1731                cx.stop_propagation();
1732            }))
1733            .capture_action(cx.listener(|this, action, cx| {
1734                this.tab_previous(action, cx);
1735                cx.stop_propagation();
1736            }))
1737            .on_action(cx.listener(|this, action, cx| this.confirm(action, cx)))
1738            .on_action(cx.listener(|this, action, cx| {
1739                this.cycle_mode(action, cx);
1740            }))
1741            .when(search.current_mode != SearchMode::Semantic, |this| {
1742                this.on_action(cx.listener(|this, action, cx| {
1743                    this.toggle_replace(action, cx);
1744                }))
1745                .on_action(cx.listener(|this, _: &ToggleWholeWord, cx| {
1746                    this.toggle_search_option(SearchOptions::WHOLE_WORD, cx);
1747                }))
1748                .on_action(cx.listener(|this, _: &ToggleCaseSensitive, cx| {
1749                    this.toggle_search_option(SearchOptions::CASE_SENSITIVE, cx);
1750                }))
1751                .on_action(cx.listener(|this, action, cx| {
1752                    if let Some(search) = this.active_project_search.as_ref() {
1753                        search.update(cx, |this, cx| {
1754                            this.replace_next(action, cx);
1755                        })
1756                    }
1757                }))
1758                .on_action(cx.listener(|this, action, cx| {
1759                    if let Some(search) = this.active_project_search.as_ref() {
1760                        search.update(cx, |this, cx| {
1761                            this.replace_all(action, cx);
1762                        })
1763                    }
1764                }))
1765                .when(search.filters_enabled, |this| {
1766                    this.on_action(cx.listener(|this, _: &ToggleIncludeIgnored, cx| {
1767                        this.toggle_search_option(SearchOptions::INCLUDE_IGNORED, cx);
1768                    }))
1769                })
1770            })
1771            .child(
1772                h_stack()
1773                    .justify_between()
1774                    .child(query_column)
1775                    .child(mode_column)
1776                    .child(replace_column)
1777                    .child(actions_column),
1778            )
1779            .when(search.filters_enabled, |this| {
1780                this.child(
1781                    h_stack()
1782                        .flex_1()
1783                        .gap_2()
1784                        .justify_between()
1785                        .child(
1786                            h_stack()
1787                                .flex_1()
1788                                .h_full()
1789                                .px_2()
1790                                .py_1()
1791                                .border_1()
1792                                .border_color(cx.theme().colors().border)
1793                                .rounded_lg()
1794                                .child(self.render_text_input(&search.included_files_editor, cx))
1795                                .when(search.current_mode != SearchMode::Semantic, |this| {
1796                                    this.child(
1797                                        SearchOptions::INCLUDE_IGNORED.as_button(
1798                                            search
1799                                                .search_options
1800                                                .contains(SearchOptions::INCLUDE_IGNORED),
1801                                            cx.listener(|this, _, cx| {
1802                                                this.toggle_search_option(
1803                                                    SearchOptions::INCLUDE_IGNORED,
1804                                                    cx,
1805                                                );
1806                                            }),
1807                                        ),
1808                                    )
1809                                }),
1810                        )
1811                        .child(
1812                            h_stack()
1813                                .flex_1()
1814                                .h_full()
1815                                .px_2()
1816                                .py_1()
1817                                .border_1()
1818                                .border_color(cx.theme().colors().border)
1819                                .rounded_lg()
1820                                .child(self.render_text_input(&search.excluded_files_editor, cx)),
1821                        ),
1822                )
1823            })
1824    }
1825}
1826
1827impl EventEmitter<ToolbarItemEvent> for ProjectSearchBar {}
1828
1829impl ToolbarItemView for ProjectSearchBar {
1830    fn set_active_pane_item(
1831        &mut self,
1832        active_pane_item: Option<&dyn ItemHandle>,
1833        cx: &mut ViewContext<Self>,
1834    ) -> ToolbarItemLocation {
1835        cx.notify();
1836        self.subscription = None;
1837        self.active_project_search = None;
1838        if let Some(search) = active_pane_item.and_then(|i| i.downcast::<ProjectSearchView>()) {
1839            search.update(cx, |search, cx| {
1840                if search.current_mode == SearchMode::Semantic {
1841                    search.index_project(cx);
1842                }
1843            });
1844
1845            self.subscription = Some(cx.observe(&search, |_, _, cx| cx.notify()));
1846            self.active_project_search = Some(search);
1847            ToolbarItemLocation::PrimaryLeft {}
1848        } else {
1849            ToolbarItemLocation::Hidden
1850        }
1851    }
1852
1853    fn row_count(&self, cx: &WindowContext<'_>) -> usize {
1854        if let Some(search) = self.active_project_search.as_ref() {
1855            if search.read(cx).filters_enabled {
1856                return 2;
1857            }
1858        }
1859        1
1860    }
1861}
1862
1863#[cfg(test)]
1864pub mod tests {
1865    use super::*;
1866    use editor::DisplayPoint;
1867    use gpui::{Action, TestAppContext};
1868    use project::FakeFs;
1869    use semantic_index::semantic_index_settings::SemanticIndexSettings;
1870    use serde_json::json;
1871    use settings::{Settings, SettingsStore};
1872
1873    #[gpui::test]
1874    async fn test_project_search(cx: &mut TestAppContext) {
1875        init_test(cx);
1876
1877        let fs = FakeFs::new(cx.background_executor.clone());
1878        fs.insert_tree(
1879            "/dir",
1880            json!({
1881                "one.rs": "const ONE: usize = 1;",
1882                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
1883                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
1884                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
1885            }),
1886        )
1887        .await;
1888        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
1889        let search = cx.build_model(|cx| ProjectSearch::new(project, cx));
1890        let search_view = cx.add_window(|cx| ProjectSearchView::new(search.clone(), cx, None));
1891
1892        search_view
1893            .update(cx, |search_view, cx| {
1894                search_view
1895                    .query_editor
1896                    .update(cx, |query_editor, cx| query_editor.set_text("TWO", cx));
1897                search_view.search(cx);
1898            })
1899            .unwrap();
1900        cx.background_executor.run_until_parked();
1901        search_view.update(cx, |search_view, cx| {
1902            assert_eq!(
1903                search_view
1904                    .results_editor
1905                    .update(cx, |editor, cx| editor.display_text(cx)),
1906                "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;"
1907            );
1908            let match_background_color = cx.theme().colors().search_match_background;
1909            assert_eq!(
1910                search_view
1911                    .results_editor
1912                    .update(cx, |editor, cx| editor.all_text_background_highlights(cx)),
1913                &[
1914                    (
1915                        DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35),
1916                        match_background_color
1917                    ),
1918                    (
1919                        DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40),
1920                        match_background_color
1921                    ),
1922                    (
1923                        DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9),
1924                        match_background_color
1925                    )
1926                ]
1927            );
1928            assert_eq!(search_view.active_match_index, Some(0));
1929            assert_eq!(
1930                search_view
1931                    .results_editor
1932                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1933                [DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35)]
1934            );
1935
1936            search_view.select_match(Direction::Next, cx);
1937        }).unwrap();
1938
1939        search_view
1940            .update(cx, |search_view, cx| {
1941                assert_eq!(search_view.active_match_index, Some(1));
1942                assert_eq!(
1943                    search_view
1944                        .results_editor
1945                        .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1946                    [DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40)]
1947                );
1948                search_view.select_match(Direction::Next, cx);
1949            })
1950            .unwrap();
1951
1952        search_view
1953            .update(cx, |search_view, cx| {
1954                assert_eq!(search_view.active_match_index, Some(2));
1955                assert_eq!(
1956                    search_view
1957                        .results_editor
1958                        .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1959                    [DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9)]
1960                );
1961                search_view.select_match(Direction::Next, cx);
1962            })
1963            .unwrap();
1964
1965        search_view
1966            .update(cx, |search_view, cx| {
1967                assert_eq!(search_view.active_match_index, Some(0));
1968                assert_eq!(
1969                    search_view
1970                        .results_editor
1971                        .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1972                    [DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35)]
1973                );
1974                search_view.select_match(Direction::Prev, cx);
1975            })
1976            .unwrap();
1977
1978        search_view
1979            .update(cx, |search_view, cx| {
1980                assert_eq!(search_view.active_match_index, Some(2));
1981                assert_eq!(
1982                    search_view
1983                        .results_editor
1984                        .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1985                    [DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9)]
1986                );
1987                search_view.select_match(Direction::Prev, cx);
1988            })
1989            .unwrap();
1990
1991        search_view
1992            .update(cx, |search_view, cx| {
1993                assert_eq!(search_view.active_match_index, Some(1));
1994                assert_eq!(
1995                    search_view
1996                        .results_editor
1997                        .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1998                    [DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40)]
1999                );
2000            })
2001            .unwrap();
2002    }
2003
2004    #[gpui::test]
2005    async fn test_project_search_focus(cx: &mut TestAppContext) {
2006        init_test(cx);
2007
2008        let fs = FakeFs::new(cx.background_executor.clone());
2009        fs.insert_tree(
2010            "/dir",
2011            json!({
2012                "one.rs": "const ONE: usize = 1;",
2013                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2014                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2015                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2016            }),
2017        )
2018        .await;
2019        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
2020        let window = cx.add_window(|cx| Workspace::test_new(project, cx));
2021        let workspace = window.clone();
2022        let search_bar = window.build_view(cx, |_| ProjectSearchBar::new());
2023
2024        let active_item = cx.read(|cx| {
2025            workspace
2026                .read(cx)
2027                .unwrap()
2028                .active_pane()
2029                .read(cx)
2030                .active_item()
2031                .and_then(|item| item.downcast::<ProjectSearchView>())
2032        });
2033        assert!(
2034            active_item.is_none(),
2035            "Expected no search panel to be active"
2036        );
2037
2038        window
2039            .update(cx, move |workspace, cx| {
2040                assert_eq!(workspace.panes().len(), 1);
2041                workspace.panes()[0].update(cx, move |pane, cx| {
2042                    pane.toolbar()
2043                        .update(cx, |toolbar, cx| toolbar.add_item(search_bar, cx))
2044                });
2045
2046                ProjectSearchView::deploy(workspace, &workspace::NewSearch, cx)
2047            })
2048            .unwrap();
2049
2050        let Some(search_view) = cx.read(|cx| {
2051            workspace
2052                .read(cx)
2053                .unwrap()
2054                .active_pane()
2055                .read(cx)
2056                .active_item()
2057                .and_then(|item| item.downcast::<ProjectSearchView>())
2058        }) else {
2059            panic!("Search view expected to appear after new search event trigger")
2060        };
2061
2062        cx.spawn(|mut cx| async move {
2063            window
2064                .update(&mut cx, |_, cx| {
2065                    cx.dispatch_action(ToggleFocus.boxed_clone())
2066                })
2067                .unwrap();
2068        })
2069        .detach();
2070        cx.background_executor.run_until_parked();
2071
2072        window.update(cx, |_, cx| {
2073            search_view.update(cx, |search_view, cx| {
2074                    assert!(
2075                        search_view.query_editor.focus_handle(cx).is_focused(cx),
2076                        "Empty search view should be focused after the toggle focus event: no results panel to focus on",
2077                    );
2078                });
2079        }).unwrap();
2080
2081        window
2082            .update(cx, |_, cx| {
2083                search_view.update(cx, |search_view, cx| {
2084                    let query_editor = &search_view.query_editor;
2085                    assert!(
2086                        query_editor.focus_handle(cx).is_focused(cx),
2087                        "Search view should be focused after the new search view is activated",
2088                    );
2089                    let query_text = query_editor.read(cx).text(cx);
2090                    assert!(
2091                        query_text.is_empty(),
2092                        "New search query should be empty but got '{query_text}'",
2093                    );
2094                    let results_text = search_view
2095                        .results_editor
2096                        .update(cx, |editor, cx| editor.display_text(cx));
2097                    assert!(
2098                        results_text.is_empty(),
2099                        "Empty search view should have no results but got '{results_text}'"
2100                    );
2101                });
2102            })
2103            .unwrap();
2104
2105        window
2106            .update(cx, |_, cx| {
2107                search_view.update(cx, |search_view, cx| {
2108                    search_view.query_editor.update(cx, |query_editor, cx| {
2109                        query_editor.set_text("sOMETHINGtHATsURELYdOESnOTeXIST", cx)
2110                    });
2111                    search_view.search(cx);
2112                });
2113            })
2114            .unwrap();
2115
2116        cx.background_executor.run_until_parked();
2117        window
2118            .update(cx, |_, cx| {
2119                search_view.update(cx, |search_view, cx| {
2120                    let results_text = search_view
2121                        .results_editor
2122                        .update(cx, |editor, cx| editor.display_text(cx));
2123                    assert!(
2124                results_text.is_empty(),
2125                "Search view for mismatching query should have no results but got '{results_text}'"
2126            );
2127                    assert!(
2128                search_view.query_editor.focus_handle(cx).is_focused(cx),
2129                "Search view should be focused after mismatching query had been used in search",
2130            );
2131                });
2132            })
2133            .unwrap();
2134        cx.spawn(|mut cx| async move {
2135            window.update(&mut cx, |_, cx| {
2136                cx.dispatch_action(ToggleFocus.boxed_clone())
2137            })
2138        })
2139        .detach();
2140        cx.background_executor.run_until_parked();
2141        window.update(cx, |_, cx| {
2142            search_view.update(cx, |search_view, cx| {
2143                    assert!(
2144                        search_view.query_editor.focus_handle(cx).is_focused(cx),
2145                        "Search view with mismatching query should be focused after the toggle focus event: still no results panel to focus on",
2146                    );
2147                });
2148        }).unwrap();
2149
2150        window
2151            .update(cx, |_, cx| {
2152                search_view.update(cx, |search_view, cx| {
2153                    search_view
2154                        .query_editor
2155                        .update(cx, |query_editor, cx| query_editor.set_text("TWO", cx));
2156                    search_view.search(cx);
2157                })
2158            })
2159            .unwrap();
2160        cx.background_executor.run_until_parked();
2161        window.update(cx, |_, cx|
2162        search_view.update(cx, |search_view, cx| {
2163                assert_eq!(
2164                    search_view
2165                        .results_editor
2166                        .update(cx, |editor, cx| editor.display_text(cx)),
2167                    "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
2168                    "Search view results should match the query"
2169                );
2170                assert!(
2171                    search_view.results_editor.focus_handle(cx).is_focused(cx),
2172                    "Search view with mismatching query should be focused after search results are available",
2173                );
2174            })).unwrap();
2175        cx.spawn(|mut cx| async move {
2176            window
2177                .update(&mut cx, |_, cx| {
2178                    cx.dispatch_action(ToggleFocus.boxed_clone())
2179                })
2180                .unwrap();
2181        })
2182        .detach();
2183        cx.background_executor.run_until_parked();
2184        window.update(cx, |_, cx| {
2185            search_view.update(cx, |search_view, cx| {
2186                    assert!(
2187                        search_view.results_editor.focus_handle(cx).is_focused(cx),
2188                        "Search view with matching query should still have its results editor focused after the toggle focus event",
2189                    );
2190                });
2191        }).unwrap();
2192
2193        workspace
2194            .update(cx, |workspace, cx| {
2195                ProjectSearchView::deploy(workspace, &workspace::NewSearch, cx)
2196            })
2197            .unwrap();
2198        cx.background_executor.run_until_parked();
2199        let Some(search_view_2) = cx.read(|cx| {
2200            workspace
2201                .read(cx)
2202                .unwrap()
2203                .active_pane()
2204                .read(cx)
2205                .active_item()
2206                .and_then(|item| item.downcast::<ProjectSearchView>())
2207        }) else {
2208            panic!("Search view expected to appear after new search event trigger")
2209        };
2210        assert!(
2211            search_view_2 != search_view,
2212            "New search view should be open after `workspace::NewSearch` event"
2213        );
2214
2215        window.update(cx, |_, cx| {
2216            search_view.update(cx, |search_view, cx| {
2217                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO", "First search view should not have an updated query");
2218                    assert_eq!(
2219                        search_view
2220                            .results_editor
2221                            .update(cx, |editor, cx| editor.display_text(cx)),
2222                        "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
2223                        "Results of the first search view should not update too"
2224                    );
2225                    assert!(
2226                        !search_view.query_editor.focus_handle(cx).is_focused(cx),
2227                        "Focus should be moved away from the first search view"
2228                    );
2229                });
2230        }).unwrap();
2231
2232        window.update(cx, |_, cx| {
2233            search_view_2.update(cx, |search_view_2, cx| {
2234                    assert_eq!(
2235                        search_view_2.query_editor.read(cx).text(cx),
2236                        "two",
2237                        "New search view should get the query from the text cursor was at during the event spawn (first search view's first result)"
2238                    );
2239                    assert_eq!(
2240                        search_view_2
2241                            .results_editor
2242                            .update(cx, |editor, cx| editor.display_text(cx)),
2243                        "",
2244                        "No search results should be in the 2nd view yet, as we did not spawn a search for it"
2245                    );
2246                    assert!(
2247                        search_view_2.query_editor.focus_handle(cx).is_focused(cx),
2248                        "Focus should be moved into query editor fo the new window"
2249                    );
2250                });
2251        }).unwrap();
2252
2253        window
2254            .update(cx, |_, cx| {
2255                search_view_2.update(cx, |search_view_2, cx| {
2256                    search_view_2
2257                        .query_editor
2258                        .update(cx, |query_editor, cx| query_editor.set_text("FOUR", cx));
2259                    search_view_2.search(cx);
2260                });
2261            })
2262            .unwrap();
2263
2264        cx.background_executor.run_until_parked();
2265        window.update(cx, |_, cx| {
2266            search_view_2.update(cx, |search_view_2, cx| {
2267                    assert_eq!(
2268                        search_view_2
2269                            .results_editor
2270                            .update(cx, |editor, cx| editor.display_text(cx)),
2271                        "\n\nconst FOUR: usize = one::ONE + three::THREE;",
2272                        "New search view with the updated query should have new search results"
2273                    );
2274                    assert!(
2275                        search_view_2.results_editor.focus_handle(cx).is_focused(cx),
2276                        "Search view with mismatching query should be focused after search results are available",
2277                    );
2278                });
2279        }).unwrap();
2280
2281        cx.spawn(|mut cx| async move {
2282            window
2283                .update(&mut cx, |_, cx| {
2284                    cx.dispatch_action(ToggleFocus.boxed_clone())
2285                })
2286                .unwrap();
2287        })
2288        .detach();
2289        cx.background_executor.run_until_parked();
2290        window.update(cx, |_, cx| {
2291            search_view_2.update(cx, |search_view_2, cx| {
2292                    assert!(
2293                        search_view_2.results_editor.focus_handle(cx).is_focused(cx),
2294                        "Search view with matching query should switch focus to the results editor after the toggle focus event",
2295                    );
2296                });}).unwrap();
2297    }
2298
2299    #[gpui::test]
2300    async fn test_new_project_search_in_directory(cx: &mut TestAppContext) {
2301        init_test(cx);
2302
2303        let fs = FakeFs::new(cx.background_executor.clone());
2304        fs.insert_tree(
2305            "/dir",
2306            json!({
2307                "a": {
2308                    "one.rs": "const ONE: usize = 1;",
2309                    "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2310                },
2311                "b": {
2312                    "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2313                    "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2314                },
2315            }),
2316        )
2317        .await;
2318        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
2319        let worktree_id = project.read_with(cx, |project, cx| {
2320            project.worktrees().next().unwrap().read(cx).id()
2321        });
2322        let window = cx.add_window(|cx| Workspace::test_new(project, cx));
2323        let workspace = window.root(cx).unwrap();
2324        let search_bar = window.build_view(cx, |_| ProjectSearchBar::new());
2325
2326        let active_item = cx.read(|cx| {
2327            workspace
2328                .read(cx)
2329                .active_pane()
2330                .read(cx)
2331                .active_item()
2332                .and_then(|item| item.downcast::<ProjectSearchView>())
2333        });
2334        assert!(
2335            active_item.is_none(),
2336            "Expected no search panel to be active"
2337        );
2338
2339        window
2340            .update(cx, move |workspace, cx| {
2341                assert_eq!(workspace.panes().len(), 1);
2342                workspace.panes()[0].update(cx, move |pane, cx| {
2343                    pane.toolbar()
2344                        .update(cx, |toolbar, cx| toolbar.add_item(search_bar, cx))
2345                });
2346            })
2347            .unwrap();
2348
2349        let one_file_entry = cx.update(|cx| {
2350            workspace
2351                .read(cx)
2352                .project()
2353                .read(cx)
2354                .entry_for_path(&(worktree_id, "a/one.rs").into(), cx)
2355                .expect("no entry for /a/one.rs file")
2356        });
2357        assert!(one_file_entry.is_file());
2358        window
2359            .update(cx, |workspace, cx| {
2360                ProjectSearchView::new_search_in_directory(workspace, &one_file_entry, cx)
2361            })
2362            .unwrap();
2363        let active_search_entry = cx.read(|cx| {
2364            workspace
2365                .read(cx)
2366                .active_pane()
2367                .read(cx)
2368                .active_item()
2369                .and_then(|item| item.downcast::<ProjectSearchView>())
2370        });
2371        assert!(
2372            active_search_entry.is_none(),
2373            "Expected no search panel to be active for file entry"
2374        );
2375
2376        let a_dir_entry = cx.update(|cx| {
2377            workspace
2378                .read(cx)
2379                .project()
2380                .read(cx)
2381                .entry_for_path(&(worktree_id, "a").into(), cx)
2382                .expect("no entry for /a/ directory")
2383        });
2384        assert!(a_dir_entry.is_dir());
2385        window
2386            .update(cx, |workspace, cx| {
2387                ProjectSearchView::new_search_in_directory(workspace, &a_dir_entry, cx)
2388            })
2389            .unwrap();
2390
2391        let Some(search_view) = cx.read(|cx| {
2392            workspace
2393                .read(cx)
2394                .active_pane()
2395                .read(cx)
2396                .active_item()
2397                .and_then(|item| item.downcast::<ProjectSearchView>())
2398        }) else {
2399            panic!("Search view expected to appear after new search in directory event trigger")
2400        };
2401        cx.background_executor.run_until_parked();
2402        window
2403            .update(cx, |_, cx| {
2404                search_view.update(cx, |search_view, cx| {
2405                    assert!(
2406                        search_view.query_editor.focus_handle(cx).is_focused(cx),
2407                        "On new search in directory, focus should be moved into query editor"
2408                    );
2409                    search_view.excluded_files_editor.update(cx, |editor, cx| {
2410                        assert!(
2411                            editor.display_text(cx).is_empty(),
2412                            "New search in directory should not have any excluded files"
2413                        );
2414                    });
2415                    search_view.included_files_editor.update(cx, |editor, cx| {
2416                        assert_eq!(
2417                            editor.display_text(cx),
2418                            a_dir_entry.path.to_str().unwrap(),
2419                            "New search in directory should have included dir entry path"
2420                        );
2421                    });
2422                });
2423            })
2424            .unwrap();
2425        window
2426            .update(cx, |_, cx| {
2427                search_view.update(cx, |search_view, cx| {
2428                    search_view
2429                        .query_editor
2430                        .update(cx, |query_editor, cx| query_editor.set_text("const", cx));
2431                    search_view.search(cx);
2432                });
2433            })
2434            .unwrap();
2435        cx.background_executor.run_until_parked();
2436        window
2437            .update(cx, |_, cx| {
2438                search_view.update(cx, |search_view, cx| {
2439                    assert_eq!(
2440                search_view
2441                    .results_editor
2442                    .update(cx, |editor, cx| editor.display_text(cx)),
2443                "\n\nconst ONE: usize = 1;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
2444                "New search in directory should have a filter that matches a certain directory"
2445            );
2446                })
2447            })
2448            .unwrap();
2449    }
2450
2451    #[gpui::test]
2452    async fn test_search_query_history(cx: &mut TestAppContext) {
2453        init_test(cx);
2454
2455        let fs = FakeFs::new(cx.background_executor.clone());
2456        fs.insert_tree(
2457            "/dir",
2458            json!({
2459                "one.rs": "const ONE: usize = 1;",
2460                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2461                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2462                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2463            }),
2464        )
2465        .await;
2466        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
2467        let window = cx.add_window(|cx| Workspace::test_new(project, cx));
2468        let workspace = window.root(cx).unwrap();
2469        let search_bar = window.build_view(cx, |_| ProjectSearchBar::new());
2470
2471        window
2472            .update(cx, {
2473                let search_bar = search_bar.clone();
2474                move |workspace, cx| {
2475                    assert_eq!(workspace.panes().len(), 1);
2476                    workspace.panes()[0].update(cx, move |pane, cx| {
2477                        pane.toolbar()
2478                            .update(cx, |toolbar, cx| toolbar.add_item(search_bar, cx))
2479                    });
2480
2481                    ProjectSearchView::deploy(workspace, &workspace::NewSearch, cx)
2482                }
2483            })
2484            .unwrap();
2485
2486        let search_view = cx.read(|cx| {
2487            workspace
2488                .read(cx)
2489                .active_pane()
2490                .read(cx)
2491                .active_item()
2492                .and_then(|item| item.downcast::<ProjectSearchView>())
2493                .expect("Search view expected to appear after new search event trigger")
2494        });
2495
2496        // Add 3 search items into the history + another unsubmitted one.
2497        window
2498            .update(cx, |_, cx| {
2499                search_view.update(cx, |search_view, cx| {
2500                    search_view.search_options = SearchOptions::CASE_SENSITIVE;
2501                    search_view
2502                        .query_editor
2503                        .update(cx, |query_editor, cx| query_editor.set_text("ONE", cx));
2504                    search_view.search(cx);
2505                });
2506            })
2507            .unwrap();
2508
2509        cx.background_executor.run_until_parked();
2510        window
2511            .update(cx, |_, cx| {
2512                search_view.update(cx, |search_view, cx| {
2513                    search_view
2514                        .query_editor
2515                        .update(cx, |query_editor, cx| query_editor.set_text("TWO", cx));
2516                    search_view.search(cx);
2517                });
2518            })
2519            .unwrap();
2520        cx.background_executor.run_until_parked();
2521        window
2522            .update(cx, |_, cx| {
2523                search_view.update(cx, |search_view, cx| {
2524                    search_view
2525                        .query_editor
2526                        .update(cx, |query_editor, cx| query_editor.set_text("THREE", cx));
2527                    search_view.search(cx);
2528                })
2529            })
2530            .unwrap();
2531        cx.background_executor.run_until_parked();
2532        window
2533            .update(cx, |_, cx| {
2534                search_view.update(cx, |search_view, cx| {
2535                    search_view.query_editor.update(cx, |query_editor, cx| {
2536                        query_editor.set_text("JUST_TEXT_INPUT", cx)
2537                    });
2538                })
2539            })
2540            .unwrap();
2541        cx.background_executor.run_until_parked();
2542
2543        // Ensure that the latest input with search settings is active.
2544        window
2545            .update(cx, |_, cx| {
2546                search_view.update(cx, |search_view, cx| {
2547                    assert_eq!(
2548                        search_view.query_editor.read(cx).text(cx),
2549                        "JUST_TEXT_INPUT"
2550                    );
2551                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2552                });
2553            })
2554            .unwrap();
2555
2556        // Next history query after the latest should set the query to the empty string.
2557        window
2558            .update(cx, |_, cx| {
2559                search_bar.update(cx, |search_bar, cx| {
2560                    search_bar.next_history_query(&NextHistoryQuery, cx);
2561                })
2562            })
2563            .unwrap();
2564        window
2565            .update(cx, |_, cx| {
2566                search_view.update(cx, |search_view, cx| {
2567                    assert_eq!(search_view.query_editor.read(cx).text(cx), "");
2568                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2569                });
2570            })
2571            .unwrap();
2572        window
2573            .update(cx, |_, cx| {
2574                search_bar.update(cx, |search_bar, cx| {
2575                    search_bar.next_history_query(&NextHistoryQuery, cx);
2576                })
2577            })
2578            .unwrap();
2579        window
2580            .update(cx, |_, cx| {
2581                search_view.update(cx, |search_view, cx| {
2582                    assert_eq!(search_view.query_editor.read(cx).text(cx), "");
2583                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2584                });
2585            })
2586            .unwrap();
2587
2588        // First previous query for empty current query should set the query to the latest submitted one.
2589        window
2590            .update(cx, |_, cx| {
2591                search_bar.update(cx, |search_bar, cx| {
2592                    search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2593                });
2594            })
2595            .unwrap();
2596        window
2597            .update(cx, |_, cx| {
2598                search_view.update(cx, |search_view, cx| {
2599                    assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
2600                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2601                });
2602            })
2603            .unwrap();
2604
2605        // Further previous items should go over the history in reverse order.
2606        window
2607            .update(cx, |_, cx| {
2608                search_bar.update(cx, |search_bar, cx| {
2609                    search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2610                });
2611            })
2612            .unwrap();
2613        window
2614            .update(cx, |_, cx| {
2615                search_view.update(cx, |search_view, cx| {
2616                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
2617                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2618                });
2619            })
2620            .unwrap();
2621
2622        // Previous items should never go behind the first history item.
2623        window
2624            .update(cx, |_, cx| {
2625                search_bar.update(cx, |search_bar, cx| {
2626                    search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2627                });
2628            })
2629            .unwrap();
2630        window
2631            .update(cx, |_, cx| {
2632                search_view.update(cx, |search_view, cx| {
2633                    assert_eq!(search_view.query_editor.read(cx).text(cx), "ONE");
2634                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2635                });
2636            })
2637            .unwrap();
2638        window
2639            .update(cx, |_, cx| {
2640                search_bar.update(cx, |search_bar, cx| {
2641                    search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2642                });
2643            })
2644            .unwrap();
2645        window
2646            .update(cx, |_, cx| {
2647                search_view.update(cx, |search_view, cx| {
2648                    assert_eq!(search_view.query_editor.read(cx).text(cx), "ONE");
2649                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2650                });
2651            })
2652            .unwrap();
2653
2654        // Next items should go over the history in the original order.
2655        window
2656            .update(cx, |_, cx| {
2657                search_bar.update(cx, |search_bar, cx| {
2658                    search_bar.next_history_query(&NextHistoryQuery, cx);
2659                });
2660            })
2661            .unwrap();
2662        window
2663            .update(cx, |_, cx| {
2664                search_view.update(cx, |search_view, cx| {
2665                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
2666                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2667                });
2668            })
2669            .unwrap();
2670
2671        window
2672            .update(cx, |_, cx| {
2673                search_view.update(cx, |search_view, cx| {
2674                    search_view
2675                        .query_editor
2676                        .update(cx, |query_editor, cx| query_editor.set_text("TWO_NEW", cx));
2677                    search_view.search(cx);
2678                });
2679            })
2680            .unwrap();
2681        cx.background_executor.run_until_parked();
2682        window
2683            .update(cx, |_, cx| {
2684                search_view.update(cx, |search_view, cx| {
2685                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO_NEW");
2686                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2687                });
2688            })
2689            .unwrap();
2690
2691        // New search input should add another entry to history and move the selection to the end of the history.
2692        window
2693            .update(cx, |_, cx| {
2694                search_bar.update(cx, |search_bar, cx| {
2695                    search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2696                });
2697            })
2698            .unwrap();
2699        window
2700            .update(cx, |_, cx| {
2701                search_view.update(cx, |search_view, cx| {
2702                    assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
2703                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2704                });
2705            })
2706            .unwrap();
2707        window
2708            .update(cx, |_, cx| {
2709                search_bar.update(cx, |search_bar, cx| {
2710                    search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2711                });
2712            })
2713            .unwrap();
2714        window
2715            .update(cx, |_, cx| {
2716                search_view.update(cx, |search_view, cx| {
2717                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
2718                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2719                });
2720            })
2721            .unwrap();
2722        window
2723            .update(cx, |_, cx| {
2724                search_bar.update(cx, |search_bar, cx| {
2725                    search_bar.next_history_query(&NextHistoryQuery, cx);
2726                });
2727            })
2728            .unwrap();
2729        window
2730            .update(cx, |_, cx| {
2731                search_view.update(cx, |search_view, cx| {
2732                    assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
2733                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2734                });
2735            })
2736            .unwrap();
2737        window
2738            .update(cx, |_, cx| {
2739                search_bar.update(cx, |search_bar, cx| {
2740                    search_bar.next_history_query(&NextHistoryQuery, cx);
2741                });
2742            })
2743            .unwrap();
2744        window
2745            .update(cx, |_, cx| {
2746                search_view.update(cx, |search_view, cx| {
2747                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO_NEW");
2748                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2749                });
2750            })
2751            .unwrap();
2752        window
2753            .update(cx, |_, cx| {
2754                search_bar.update(cx, |search_bar, cx| {
2755                    search_bar.next_history_query(&NextHistoryQuery, cx);
2756                });
2757            })
2758            .unwrap();
2759        window
2760            .update(cx, |_, cx| {
2761                search_view.update(cx, |search_view, cx| {
2762                    assert_eq!(search_view.query_editor.read(cx).text(cx), "");
2763                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2764                });
2765            })
2766            .unwrap();
2767    }
2768
2769    pub fn init_test(cx: &mut TestAppContext) {
2770        cx.update(|cx| {
2771            let settings = SettingsStore::test(cx);
2772            cx.set_global(settings);
2773            cx.set_global(ActiveSearches::default());
2774            SemanticIndexSettings::register(cx);
2775
2776            theme::init(theme::LoadThemes::JustBase, cx);
2777
2778            language::init(cx);
2779            client::init_settings(cx);
2780            editor::init(cx);
2781            workspace::init_settings(cx);
2782            Project::init_settings(cx);
2783            super::init(cx);
2784        });
2785    }
2786}