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, Hsla, InteractiveElement, IntoElement,
  17    KeyContext, Model, ModelContext, ParentElement, PromptLevel, Render, SharedString, Styled,
  18    Subscription, Task, TextStyle, View, ViewContext, VisualContext, WeakModel, WeakView,
  19    WhiteSpace, 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.new_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.new_model(|cx| Self {
 149            project: self.project.clone(),
 150            excerpts: self
 151                .excerpts
 152                .update(cx, |excerpts, cx| cx.new_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 IntoElement {
 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.new_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.new_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.new_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.new_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.new_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.new_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.new_model(|cx| ProjectSearch::new(workspace.project().clone(), cx));
 933        let search = cx.new_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.new_model(|cx| ProjectSearch::new(workspace.project().clone(), cx));
 977        let search = cx.new_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        // Do not bail early in this function, as we want to fill out `self.panels_with_errors`.
1011        let text = self.query_editor.read(cx).text(cx);
1012        let included_files =
1013            match Self::parse_path_matches(&self.included_files_editor.read(cx).text(cx)) {
1014                Ok(included_files) => {
1015                    let should_unmark_error = self.panels_with_errors.remove(&InputPanel::Include);
1016                    if should_unmark_error {
1017                        cx.notify();
1018                    }
1019                    included_files
1020                }
1021                Err(_e) => {
1022                    let should_mark_error = self.panels_with_errors.insert(InputPanel::Include);
1023                    if should_mark_error {
1024                        cx.notify();
1025                    }
1026                    vec![]
1027                }
1028            };
1029        let excluded_files =
1030            match Self::parse_path_matches(&self.excluded_files_editor.read(cx).text(cx)) {
1031                Ok(excluded_files) => {
1032                    let should_unmark_error = self.panels_with_errors.remove(&InputPanel::Exclude);
1033                    if should_unmark_error {
1034                        cx.notify();
1035                    }
1036
1037                    excluded_files
1038                }
1039                Err(_e) => {
1040                    let should_mark_error = self.panels_with_errors.insert(InputPanel::Exclude);
1041                    if should_mark_error {
1042                        cx.notify();
1043                    }
1044                    vec![]
1045                }
1046            };
1047
1048        let current_mode = self.current_mode;
1049        let query = match current_mode {
1050            SearchMode::Regex => {
1051                match SearchQuery::regex(
1052                    text,
1053                    self.search_options.contains(SearchOptions::WHOLE_WORD),
1054                    self.search_options.contains(SearchOptions::CASE_SENSITIVE),
1055                    self.search_options.contains(SearchOptions::INCLUDE_IGNORED),
1056                    included_files,
1057                    excluded_files,
1058                ) {
1059                    Ok(query) => {
1060                        let should_unmark_error =
1061                            self.panels_with_errors.remove(&InputPanel::Query);
1062                        if should_unmark_error {
1063                            cx.notify();
1064                        }
1065
1066                        Some(query)
1067                    }
1068                    Err(_e) => {
1069                        let should_mark_error = self.panels_with_errors.insert(InputPanel::Query);
1070                        if should_mark_error {
1071                            cx.notify();
1072                        }
1073
1074                        None
1075                    }
1076                }
1077            }
1078            _ => match SearchQuery::text(
1079                text,
1080                self.search_options.contains(SearchOptions::WHOLE_WORD),
1081                self.search_options.contains(SearchOptions::CASE_SENSITIVE),
1082                self.search_options.contains(SearchOptions::INCLUDE_IGNORED),
1083                included_files,
1084                excluded_files,
1085            ) {
1086                Ok(query) => {
1087                    let should_unmark_error = self.panels_with_errors.remove(&InputPanel::Query);
1088                    if should_unmark_error {
1089                        cx.notify();
1090                    }
1091
1092                    Some(query)
1093                }
1094                Err(_e) => {
1095                    let should_mark_error = self.panels_with_errors.insert(InputPanel::Query);
1096                    if should_mark_error {
1097                        cx.notify();
1098                    }
1099
1100                    None
1101                }
1102            },
1103        };
1104        if !self.panels_with_errors.is_empty() {
1105            return None;
1106        }
1107        query
1108    }
1109
1110    fn parse_path_matches(text: &str) -> anyhow::Result<Vec<PathMatcher>> {
1111        text.split(',')
1112            .map(str::trim)
1113            .filter(|maybe_glob_str| !maybe_glob_str.is_empty())
1114            .map(|maybe_glob_str| {
1115                PathMatcher::new(maybe_glob_str)
1116                    .with_context(|| format!("parsing {maybe_glob_str} as path matcher"))
1117            })
1118            .collect()
1119    }
1120
1121    fn select_match(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
1122        if let Some(index) = self.active_match_index {
1123            let match_ranges = self.model.read(cx).match_ranges.clone();
1124            let new_index = self.results_editor.update(cx, |editor, cx| {
1125                editor.match_index_for_direction(&match_ranges, index, direction, 1, cx)
1126            });
1127
1128            let range_to_select = match_ranges[new_index].clone();
1129            self.results_editor.update(cx, |editor, cx| {
1130                let range_to_select = editor.range_for_match(&range_to_select);
1131                editor.unfold_ranges([range_to_select.clone()], false, true, cx);
1132                editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
1133                    s.select_ranges([range_to_select])
1134                });
1135            });
1136        }
1137    }
1138
1139    fn focus_query_editor(&mut self, cx: &mut ViewContext<Self>) {
1140        self.query_editor.update(cx, |query_editor, cx| {
1141            query_editor.select_all(&SelectAll, cx);
1142        });
1143        self.query_editor_was_focused = true;
1144        let editor_handle = self.query_editor.focus_handle(cx);
1145        cx.focus(&editor_handle);
1146    }
1147
1148    fn set_query(&mut self, query: &str, cx: &mut ViewContext<Self>) {
1149        self.query_editor
1150            .update(cx, |query_editor, cx| query_editor.set_text(query, cx));
1151    }
1152
1153    fn focus_results_editor(&mut self, cx: &mut ViewContext<Self>) {
1154        self.query_editor.update(cx, |query_editor, cx| {
1155            let cursor = query_editor.selections.newest_anchor().head();
1156            query_editor.change_selections(None, cx, |s| s.select_ranges([cursor.clone()..cursor]));
1157        });
1158        self.query_editor_was_focused = false;
1159        let results_handle = self.results_editor.focus_handle(cx);
1160        cx.focus(&results_handle);
1161    }
1162
1163    fn model_changed(&mut self, cx: &mut ViewContext<Self>) {
1164        let match_ranges = self.model.read(cx).match_ranges.clone();
1165        if match_ranges.is_empty() {
1166            self.active_match_index = None;
1167        } else {
1168            self.active_match_index = Some(0);
1169            self.update_match_index(cx);
1170            let prev_search_id = mem::replace(&mut self.search_id, self.model.read(cx).search_id);
1171            let is_new_search = self.search_id != prev_search_id;
1172            self.results_editor.update(cx, |editor, cx| {
1173                if is_new_search {
1174                    let range_to_select = match_ranges
1175                        .first()
1176                        .clone()
1177                        .map(|range| editor.range_for_match(range));
1178                    editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
1179                        s.select_ranges(range_to_select)
1180                    });
1181                }
1182                editor.highlight_background::<Self>(
1183                    match_ranges,
1184                    |theme| theme.search_match_background,
1185                    cx,
1186                );
1187            });
1188            if is_new_search && self.query_editor.focus_handle(cx).is_focused(cx) {
1189                self.focus_results_editor(cx);
1190            }
1191        }
1192
1193        cx.emit(ViewEvent::UpdateTab);
1194        cx.notify();
1195    }
1196
1197    fn update_match_index(&mut self, cx: &mut ViewContext<Self>) {
1198        let results_editor = self.results_editor.read(cx);
1199        let new_index = active_match_index(
1200            &self.model.read(cx).match_ranges,
1201            &results_editor.selections.newest_anchor().head(),
1202            &results_editor.buffer().read(cx).snapshot(cx),
1203        );
1204        if self.active_match_index != new_index {
1205            self.active_match_index = new_index;
1206            cx.notify();
1207        }
1208    }
1209
1210    pub fn has_matches(&self) -> bool {
1211        self.active_match_index.is_some()
1212    }
1213
1214    fn landing_text_minor(&self) -> SharedString {
1215        match self.current_mode {
1216            SearchMode::Text | SearchMode::Regex => "Include/exclude specific paths with the filter option. Matching exact word and/or casing is available too.".into(),
1217            SearchMode::Semantic => "\nSimply explain the code you are looking to find. ex. 'prompt user for permissions to index their project'".into()
1218        }
1219    }
1220    fn border_color_for(&self, panel: InputPanel, cx: &WindowContext) -> Hsla {
1221        if self.panels_with_errors.contains(&panel) {
1222            Color::Error.color(cx)
1223        } else {
1224            cx.theme().colors().border
1225        }
1226    }
1227    fn move_focus_to_results(&mut self, cx: &mut ViewContext<Self>) {
1228        if !self.results_editor.focus_handle(cx).is_focused(cx)
1229            && !self.model.read(cx).match_ranges.is_empty()
1230        {
1231            cx.stop_propagation();
1232            return self.focus_results_editor(cx);
1233        }
1234    }
1235}
1236
1237impl Default for ProjectSearchBar {
1238    fn default() -> Self {
1239        Self::new()
1240    }
1241}
1242
1243impl ProjectSearchBar {
1244    pub fn new() -> Self {
1245        Self {
1246            active_project_search: Default::default(),
1247            subscription: Default::default(),
1248        }
1249    }
1250
1251    fn cycle_mode(&self, _: &CycleMode, cx: &mut ViewContext<Self>) {
1252        if let Some(view) = self.active_project_search.as_ref() {
1253            view.update(cx, |this, cx| {
1254                let new_mode =
1255                    crate::mode::next_mode(&this.current_mode, SemanticIndex::enabled(cx));
1256                this.activate_search_mode(new_mode, cx);
1257                let editor_handle = this.query_editor.focus_handle(cx);
1258                cx.focus(&editor_handle);
1259            });
1260        }
1261    }
1262
1263    fn confirm(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
1264        if let Some(search_view) = self.active_project_search.as_ref() {
1265            search_view.update(cx, |search_view, cx| {
1266                if !search_view
1267                    .replacement_editor
1268                    .focus_handle(cx)
1269                    .is_focused(cx)
1270                {
1271                    cx.stop_propagation();
1272                    search_view.search(cx);
1273                }
1274            });
1275        }
1276    }
1277
1278    fn search_in_new(workspace: &mut Workspace, _: &SearchInNew, cx: &mut ViewContext<Workspace>) {
1279        if let Some(search_view) = workspace
1280            .active_item(cx)
1281            .and_then(|item| item.downcast::<ProjectSearchView>())
1282        {
1283            let new_query = search_view.update(cx, |search_view, cx| {
1284                let new_query = search_view.build_search_query(cx);
1285                if new_query.is_some() {
1286                    if let Some(old_query) = search_view.model.read(cx).active_query.clone() {
1287                        search_view.query_editor.update(cx, |editor, cx| {
1288                            editor.set_text(old_query.as_str(), cx);
1289                        });
1290                        search_view.search_options = SearchOptions::from_query(&old_query);
1291                    }
1292                }
1293                new_query
1294            });
1295            if let Some(new_query) = new_query {
1296                let model = cx.new_model(|cx| {
1297                    let mut model = ProjectSearch::new(workspace.project().clone(), cx);
1298                    model.search(new_query, cx);
1299                    model
1300                });
1301                workspace.add_item(
1302                    Box::new(cx.new_view(|cx| ProjectSearchView::new(model, cx, None))),
1303                    cx,
1304                );
1305            }
1306        }
1307    }
1308
1309    fn tab(&mut self, _: &editor::Tab, cx: &mut ViewContext<Self>) {
1310        self.cycle_field(Direction::Next, cx);
1311    }
1312
1313    fn tab_previous(&mut self, _: &editor::TabPrev, cx: &mut ViewContext<Self>) {
1314        self.cycle_field(Direction::Prev, cx);
1315    }
1316
1317    fn cycle_field(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
1318        let active_project_search = match &self.active_project_search {
1319            Some(active_project_search) => active_project_search,
1320
1321            None => {
1322                return;
1323            }
1324        };
1325
1326        active_project_search.update(cx, |project_view, cx| {
1327            let mut views = vec![&project_view.query_editor];
1328            if project_view.filters_enabled {
1329                views.extend([
1330                    &project_view.included_files_editor,
1331                    &project_view.excluded_files_editor,
1332                ]);
1333            }
1334            if project_view.replace_enabled {
1335                views.push(&project_view.replacement_editor);
1336            }
1337            let current_index = match views
1338                .iter()
1339                .enumerate()
1340                .find(|(_, view)| view.focus_handle(cx).is_focused(cx))
1341            {
1342                Some((index, _)) => index,
1343
1344                None => {
1345                    return;
1346                }
1347            };
1348
1349            let new_index = match direction {
1350                Direction::Next => (current_index + 1) % views.len(),
1351                Direction::Prev if current_index == 0 => views.len() - 1,
1352                Direction::Prev => (current_index - 1) % views.len(),
1353            };
1354            let next_focus_handle = views[new_index].focus_handle(cx);
1355            cx.focus(&next_focus_handle);
1356            cx.stop_propagation();
1357        });
1358    }
1359
1360    fn toggle_search_option(&mut self, option: SearchOptions, cx: &mut ViewContext<Self>) -> bool {
1361        if let Some(search_view) = self.active_project_search.as_ref() {
1362            search_view.update(cx, |search_view, cx| {
1363                search_view.toggle_search_option(option, cx);
1364                search_view.search(cx);
1365            });
1366
1367            cx.notify();
1368            true
1369        } else {
1370            false
1371        }
1372    }
1373
1374    fn toggle_replace(&mut self, _: &ToggleReplace, cx: &mut ViewContext<Self>) {
1375        if let Some(search) = &self.active_project_search {
1376            search.update(cx, |this, cx| {
1377                this.replace_enabled = !this.replace_enabled;
1378                let editor_to_focus = if !this.replace_enabled {
1379                    this.query_editor.focus_handle(cx)
1380                } else {
1381                    this.replacement_editor.focus_handle(cx)
1382                };
1383                cx.focus(&editor_to_focus);
1384                cx.notify();
1385            });
1386        }
1387    }
1388
1389    fn toggle_filters(&mut self, cx: &mut ViewContext<Self>) -> bool {
1390        if let Some(search_view) = self.active_project_search.as_ref() {
1391            search_view.update(cx, |search_view, cx| {
1392                search_view.toggle_filters(cx);
1393                search_view
1394                    .included_files_editor
1395                    .update(cx, |_, cx| cx.notify());
1396                search_view
1397                    .excluded_files_editor
1398                    .update(cx, |_, cx| cx.notify());
1399                cx.refresh();
1400                cx.notify();
1401            });
1402            cx.notify();
1403            true
1404        } else {
1405            false
1406        }
1407    }
1408
1409    fn move_focus_to_results(&self, cx: &mut ViewContext<Self>) {
1410        if let Some(search_view) = self.active_project_search.as_ref() {
1411            search_view.update(cx, |search_view, cx| {
1412                search_view.move_focus_to_results(cx);
1413            });
1414            cx.notify();
1415        }
1416    }
1417
1418    fn activate_search_mode(&self, mode: SearchMode, cx: &mut ViewContext<Self>) {
1419        // Update Current Mode
1420        if let Some(search_view) = self.active_project_search.as_ref() {
1421            search_view.update(cx, |search_view, cx| {
1422                search_view.activate_search_mode(mode, cx);
1423            });
1424            cx.notify();
1425        }
1426    }
1427
1428    fn is_option_enabled(&self, option: SearchOptions, cx: &AppContext) -> bool {
1429        if let Some(search) = self.active_project_search.as_ref() {
1430            search.read(cx).search_options.contains(option)
1431        } else {
1432            false
1433        }
1434    }
1435
1436    fn next_history_query(&mut self, _: &NextHistoryQuery, cx: &mut ViewContext<Self>) {
1437        if let Some(search_view) = self.active_project_search.as_ref() {
1438            search_view.update(cx, |search_view, cx| {
1439                let new_query = search_view.model.update(cx, |model, _| {
1440                    if let Some(new_query) = model.search_history.next().map(str::to_string) {
1441                        new_query
1442                    } else {
1443                        model.search_history.reset_selection();
1444                        String::new()
1445                    }
1446                });
1447                search_view.set_query(&new_query, cx);
1448            });
1449        }
1450    }
1451
1452    fn previous_history_query(&mut self, _: &PreviousHistoryQuery, cx: &mut ViewContext<Self>) {
1453        if let Some(search_view) = self.active_project_search.as_ref() {
1454            search_view.update(cx, |search_view, cx| {
1455                if search_view.query_editor.read(cx).text(cx).is_empty() {
1456                    if let Some(new_query) = search_view
1457                        .model
1458                        .read(cx)
1459                        .search_history
1460                        .current()
1461                        .map(str::to_string)
1462                    {
1463                        search_view.set_query(&new_query, cx);
1464                        return;
1465                    }
1466                }
1467
1468                if let Some(new_query) = search_view.model.update(cx, |model, _| {
1469                    model.search_history.previous().map(str::to_string)
1470                }) {
1471                    search_view.set_query(&new_query, cx);
1472                }
1473            });
1474        }
1475    }
1476
1477    fn new_placeholder_text(&self, cx: &mut ViewContext<Self>) -> Option<String> {
1478        let previous_query_keystrokes = cx
1479            .bindings_for_action(&PreviousHistoryQuery {})
1480            .into_iter()
1481            .next()
1482            .map(|binding| {
1483                binding
1484                    .keystrokes()
1485                    .iter()
1486                    .map(|k| k.to_string())
1487                    .collect::<Vec<_>>()
1488            });
1489        let next_query_keystrokes = cx
1490            .bindings_for_action(&NextHistoryQuery {})
1491            .into_iter()
1492            .next()
1493            .map(|binding| {
1494                binding
1495                    .keystrokes()
1496                    .iter()
1497                    .map(|k| k.to_string())
1498                    .collect::<Vec<_>>()
1499            });
1500        let new_placeholder_text = match (previous_query_keystrokes, next_query_keystrokes) {
1501            (Some(previous_query_keystrokes), Some(next_query_keystrokes)) => Some(format!(
1502                "Search ({}/{} for previous/next query)",
1503                previous_query_keystrokes.join(" "),
1504                next_query_keystrokes.join(" ")
1505            )),
1506            (None, Some(next_query_keystrokes)) => Some(format!(
1507                "Search ({} for next query)",
1508                next_query_keystrokes.join(" ")
1509            )),
1510            (Some(previous_query_keystrokes), None) => Some(format!(
1511                "Search ({} for previous query)",
1512                previous_query_keystrokes.join(" ")
1513            )),
1514            (None, None) => None,
1515        };
1516        new_placeholder_text
1517    }
1518
1519    fn render_text_input(&self, editor: &View<Editor>, cx: &ViewContext<Self>) -> impl IntoElement {
1520        let settings = ThemeSettings::get_global(cx);
1521        let text_style = TextStyle {
1522            color: if editor.read(cx).read_only() {
1523                cx.theme().colors().text_disabled
1524            } else {
1525                cx.theme().colors().text
1526            },
1527            font_family: settings.ui_font.family.clone(),
1528            font_features: settings.ui_font.features,
1529            font_size: rems(0.875).into(),
1530            font_weight: FontWeight::NORMAL,
1531            font_style: FontStyle::Normal,
1532            line_height: relative(1.3).into(),
1533            background_color: None,
1534            underline: None,
1535            white_space: WhiteSpace::Normal,
1536        };
1537
1538        EditorElement::new(
1539            &editor,
1540            EditorStyle {
1541                background: cx.theme().colors().editor_background,
1542                local_player: cx.theme().players().local(),
1543                text: text_style,
1544                ..Default::default()
1545            },
1546        )
1547    }
1548}
1549
1550impl Render for ProjectSearchBar {
1551    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
1552        let Some(search) = self.active_project_search.clone() else {
1553            return div();
1554        };
1555        let mut key_context = KeyContext::default();
1556        key_context.add("ProjectSearchBar");
1557        if let Some(placeholder_text) = self.new_placeholder_text(cx) {
1558            search.update(cx, |search, cx| {
1559                search.query_editor.update(cx, |this, cx| {
1560                    this.set_placeholder_text(placeholder_text, cx)
1561                })
1562            });
1563        }
1564        let search = search.read(cx);
1565        let semantic_is_available = SemanticIndex::enabled(cx);
1566
1567        let query_column = v_stack().child(
1568            h_stack()
1569                .min_w(rems(512. / 16.))
1570                .px_2()
1571                .py_1()
1572                .gap_2()
1573                .bg(cx.theme().colors().editor_background)
1574                .border_1()
1575                .border_color(search.border_color_for(InputPanel::Query, cx))
1576                .rounded_lg()
1577                .on_action(cx.listener(|this, action, cx| this.confirm(action, cx)))
1578                .on_action(cx.listener(|this, action, cx| this.previous_history_query(action, cx)))
1579                .on_action(cx.listener(|this, action, cx| this.next_history_query(action, cx)))
1580                .child(IconElement::new(Icon::MagnifyingGlass))
1581                .child(self.render_text_input(&search.query_editor, cx))
1582                .child(
1583                    h_stack()
1584                        .child(
1585                            IconButton::new("project-search-filter-button", Icon::Filter)
1586                                .tooltip(|cx| {
1587                                    Tooltip::for_action("Toggle filters", &ToggleFilters, cx)
1588                                })
1589                                .on_click(cx.listener(|this, _, cx| {
1590                                    this.toggle_filters(cx);
1591                                }))
1592                                .selected(
1593                                    self.active_project_search
1594                                        .as_ref()
1595                                        .map(|search| search.read(cx).filters_enabled)
1596                                        .unwrap_or_default(),
1597                                ),
1598                        )
1599                        .when(search.current_mode != SearchMode::Semantic, |this| {
1600                            this.child(
1601                                IconButton::new(
1602                                    "project-search-case-sensitive",
1603                                    Icon::CaseSensitive,
1604                                )
1605                                .tooltip(|cx| {
1606                                    Tooltip::for_action(
1607                                        "Toggle case sensitive",
1608                                        &ToggleCaseSensitive,
1609                                        cx,
1610                                    )
1611                                })
1612                                .selected(self.is_option_enabled(SearchOptions::CASE_SENSITIVE, cx))
1613                                .on_click(cx.listener(
1614                                    |this, _, cx| {
1615                                        this.toggle_search_option(
1616                                            SearchOptions::CASE_SENSITIVE,
1617                                            cx,
1618                                        );
1619                                    },
1620                                )),
1621                            )
1622                            .child(
1623                                IconButton::new("project-search-whole-word", Icon::WholeWord)
1624                                    .tooltip(|cx| {
1625                                        Tooltip::for_action(
1626                                            "Toggle whole word",
1627                                            &ToggleWholeWord,
1628                                            cx,
1629                                        )
1630                                    })
1631                                    .selected(self.is_option_enabled(SearchOptions::WHOLE_WORD, cx))
1632                                    .on_click(cx.listener(|this, _, cx| {
1633                                        this.toggle_search_option(SearchOptions::WHOLE_WORD, cx);
1634                                    })),
1635                            )
1636                        }),
1637                ),
1638        );
1639
1640        let mode_column = v_stack().items_start().justify_start().child(
1641            h_stack()
1642                .child(
1643                    h_stack()
1644                        .child(
1645                            Button::new("project-search-text-button", "Text")
1646                                .selected(search.current_mode == SearchMode::Text)
1647                                .on_click(cx.listener(|this, _, cx| {
1648                                    this.activate_search_mode(SearchMode::Text, cx)
1649                                }))
1650                                .tooltip(|cx| {
1651                                    Tooltip::for_action("Toggle text search", &ActivateTextMode, cx)
1652                                }),
1653                        )
1654                        .child(
1655                            Button::new("project-search-regex-button", "Regex")
1656                                .selected(search.current_mode == SearchMode::Regex)
1657                                .on_click(cx.listener(|this, _, cx| {
1658                                    this.activate_search_mode(SearchMode::Regex, cx)
1659                                }))
1660                                .tooltip(|cx| {
1661                                    Tooltip::for_action(
1662                                        "Toggle regular expression search",
1663                                        &ActivateRegexMode,
1664                                        cx,
1665                                    )
1666                                }),
1667                        )
1668                        .when(semantic_is_available, |this| {
1669                            this.child(
1670                                Button::new("project-search-semantic-button", "Semantic")
1671                                    .selected(search.current_mode == SearchMode::Semantic)
1672                                    .on_click(cx.listener(|this, _, cx| {
1673                                        this.activate_search_mode(SearchMode::Semantic, cx)
1674                                    }))
1675                                    .tooltip(|cx| {
1676                                        Tooltip::for_action(
1677                                            "Toggle semantic search",
1678                                            &ActivateSemanticMode,
1679                                            cx,
1680                                        )
1681                                    }),
1682                            )
1683                        }),
1684                )
1685                .child(
1686                    IconButton::new("project-search-toggle-replace", Icon::Replace)
1687                        .on_click(cx.listener(|this, _, cx| {
1688                            this.toggle_replace(&ToggleReplace, cx);
1689                        }))
1690                        .tooltip(|cx| Tooltip::for_action("Toggle replace", &ToggleReplace, cx)),
1691                ),
1692        );
1693        let replace_column = if search.replace_enabled {
1694            h_stack()
1695                .flex_1()
1696                .h_full()
1697                .gap_2()
1698                .px_2()
1699                .py_1()
1700                .border_1()
1701                .border_color(cx.theme().colors().border)
1702                .rounded_lg()
1703                .child(IconElement::new(Icon::Replace).size(ui::IconSize::Small))
1704                .child(self.render_text_input(&search.replacement_editor, cx))
1705        } else {
1706            // Fill out the space if we don't have a replacement editor.
1707            h_stack().flex_1()
1708        };
1709        let actions_column = h_stack()
1710            .when(search.replace_enabled, |this| {
1711                this.child(
1712                    IconButton::new("project-search-replace-next", Icon::ReplaceNext)
1713                        .on_click(cx.listener(|this, _, cx| {
1714                            if let Some(search) = this.active_project_search.as_ref() {
1715                                search.update(cx, |this, cx| {
1716                                    this.replace_next(&ReplaceNext, cx);
1717                                })
1718                            }
1719                        }))
1720                        .tooltip(|cx| Tooltip::for_action("Replace next match", &ReplaceNext, cx)),
1721                )
1722                .child(
1723                    IconButton::new("project-search-replace-all", Icon::ReplaceAll)
1724                        .on_click(cx.listener(|this, _, cx| {
1725                            if let Some(search) = this.active_project_search.as_ref() {
1726                                search.update(cx, |this, cx| {
1727                                    this.replace_all(&ReplaceAll, cx);
1728                                })
1729                            }
1730                        }))
1731                        .tooltip(|cx| Tooltip::for_action("Replace all matches", &ReplaceAll, cx)),
1732                )
1733            })
1734            .when_some(search.active_match_index, |mut this, index| {
1735                let index = index + 1;
1736                let match_quantity = search.model.read(cx).match_ranges.len();
1737                if match_quantity > 0 {
1738                    debug_assert!(match_quantity >= index);
1739                    this = this.child(Label::new(format!("{index}/{match_quantity}")))
1740                }
1741                this
1742            })
1743            .child(
1744                IconButton::new("project-search-prev-match", Icon::ChevronLeft)
1745                    .disabled(search.active_match_index.is_none())
1746                    .on_click(cx.listener(|this, _, cx| {
1747                        if let Some(search) = this.active_project_search.as_ref() {
1748                            search.update(cx, |this, cx| {
1749                                this.select_match(Direction::Prev, cx);
1750                            })
1751                        }
1752                    }))
1753                    .tooltip(|cx| {
1754                        Tooltip::for_action("Go to previous match", &SelectPrevMatch, cx)
1755                    }),
1756            )
1757            .child(
1758                IconButton::new("project-search-next-match", Icon::ChevronRight)
1759                    .disabled(search.active_match_index.is_none())
1760                    .on_click(cx.listener(|this, _, cx| {
1761                        if let Some(search) = this.active_project_search.as_ref() {
1762                            search.update(cx, |this, cx| {
1763                                this.select_match(Direction::Next, cx);
1764                            })
1765                        }
1766                    }))
1767                    .tooltip(|cx| Tooltip::for_action("Go to next match", &SelectNextMatch, cx)),
1768            );
1769
1770        v_stack()
1771            .key_context(key_context)
1772            .flex_grow()
1773            .gap_2()
1774            .on_action(cx.listener(|this, _: &ToggleFocus, cx| this.move_focus_to_results(cx)))
1775            .on_action(cx.listener(|this, _: &ToggleFilters, cx| {
1776                this.toggle_filters(cx);
1777            }))
1778            .on_action(cx.listener(|this, _: &ActivateTextMode, cx| {
1779                this.activate_search_mode(SearchMode::Text, cx)
1780            }))
1781            .on_action(cx.listener(|this, _: &ActivateRegexMode, cx| {
1782                this.activate_search_mode(SearchMode::Regex, cx)
1783            }))
1784            .on_action(cx.listener(|this, _: &ActivateSemanticMode, cx| {
1785                this.activate_search_mode(SearchMode::Semantic, cx)
1786            }))
1787            .capture_action(cx.listener(|this, action, cx| {
1788                this.tab(action, cx);
1789                cx.stop_propagation();
1790            }))
1791            .capture_action(cx.listener(|this, action, cx| {
1792                this.tab_previous(action, cx);
1793                cx.stop_propagation();
1794            }))
1795            .on_action(cx.listener(|this, action, cx| this.confirm(action, cx)))
1796            .on_action(cx.listener(|this, action, cx| {
1797                this.cycle_mode(action, cx);
1798            }))
1799            .when(search.current_mode != SearchMode::Semantic, |this| {
1800                this.on_action(cx.listener(|this, action, cx| {
1801                    this.toggle_replace(action, cx);
1802                }))
1803                .on_action(cx.listener(|this, _: &ToggleWholeWord, cx| {
1804                    this.toggle_search_option(SearchOptions::WHOLE_WORD, cx);
1805                }))
1806                .on_action(cx.listener(|this, _: &ToggleCaseSensitive, cx| {
1807                    this.toggle_search_option(SearchOptions::CASE_SENSITIVE, cx);
1808                }))
1809                .on_action(cx.listener(|this, action, cx| {
1810                    if let Some(search) = this.active_project_search.as_ref() {
1811                        search.update(cx, |this, cx| {
1812                            this.replace_next(action, cx);
1813                        })
1814                    }
1815                }))
1816                .on_action(cx.listener(|this, action, cx| {
1817                    if let Some(search) = this.active_project_search.as_ref() {
1818                        search.update(cx, |this, cx| {
1819                            this.replace_all(action, cx);
1820                        })
1821                    }
1822                }))
1823                .when(search.filters_enabled, |this| {
1824                    this.on_action(cx.listener(|this, _: &ToggleIncludeIgnored, cx| {
1825                        this.toggle_search_option(SearchOptions::INCLUDE_IGNORED, cx);
1826                    }))
1827                })
1828            })
1829            .child(
1830                h_stack()
1831                    .justify_between()
1832                    .child(query_column)
1833                    .child(mode_column)
1834                    .child(replace_column)
1835                    .child(actions_column),
1836            )
1837            .when(search.filters_enabled, |this| {
1838                this.child(
1839                    h_stack()
1840                        .flex_1()
1841                        .gap_2()
1842                        .justify_between()
1843                        .child(
1844                            h_stack()
1845                                .flex_1()
1846                                .h_full()
1847                                .px_2()
1848                                .py_1()
1849                                .border_1()
1850                                .border_color(search.border_color_for(InputPanel::Include, cx))
1851                                .rounded_lg()
1852                                .child(self.render_text_input(&search.included_files_editor, cx))
1853                                .when(search.current_mode != SearchMode::Semantic, |this| {
1854                                    this.child(
1855                                        SearchOptions::INCLUDE_IGNORED.as_button(
1856                                            search
1857                                                .search_options
1858                                                .contains(SearchOptions::INCLUDE_IGNORED),
1859                                            cx.listener(|this, _, cx| {
1860                                                this.toggle_search_option(
1861                                                    SearchOptions::INCLUDE_IGNORED,
1862                                                    cx,
1863                                                );
1864                                            }),
1865                                        ),
1866                                    )
1867                                }),
1868                        )
1869                        .child(
1870                            h_stack()
1871                                .flex_1()
1872                                .h_full()
1873                                .px_2()
1874                                .py_1()
1875                                .border_1()
1876                                .border_color(search.border_color_for(InputPanel::Exclude, cx))
1877                                .rounded_lg()
1878                                .child(self.render_text_input(&search.excluded_files_editor, cx)),
1879                        ),
1880                )
1881            })
1882    }
1883}
1884
1885impl EventEmitter<ToolbarItemEvent> for ProjectSearchBar {}
1886
1887impl ToolbarItemView for ProjectSearchBar {
1888    fn set_active_pane_item(
1889        &mut self,
1890        active_pane_item: Option<&dyn ItemHandle>,
1891        cx: &mut ViewContext<Self>,
1892    ) -> ToolbarItemLocation {
1893        cx.notify();
1894        self.subscription = None;
1895        self.active_project_search = None;
1896        if let Some(search) = active_pane_item.and_then(|i| i.downcast::<ProjectSearchView>()) {
1897            search.update(cx, |search, cx| {
1898                if search.current_mode == SearchMode::Semantic {
1899                    search.index_project(cx);
1900                }
1901            });
1902
1903            self.subscription = Some(cx.observe(&search, |_, _, cx| cx.notify()));
1904            self.active_project_search = Some(search);
1905            ToolbarItemLocation::PrimaryLeft {}
1906        } else {
1907            ToolbarItemLocation::Hidden
1908        }
1909    }
1910
1911    fn row_count(&self, cx: &WindowContext<'_>) -> usize {
1912        if let Some(search) = self.active_project_search.as_ref() {
1913            if search.read(cx).filters_enabled {
1914                return 2;
1915            }
1916        }
1917        1
1918    }
1919}
1920
1921#[cfg(test)]
1922pub mod tests {
1923    use super::*;
1924    use editor::DisplayPoint;
1925    use gpui::{Action, TestAppContext};
1926    use project::FakeFs;
1927    use semantic_index::semantic_index_settings::SemanticIndexSettings;
1928    use serde_json::json;
1929    use settings::{Settings, SettingsStore};
1930
1931    #[gpui::test]
1932    async fn test_project_search(cx: &mut TestAppContext) {
1933        init_test(cx);
1934
1935        let fs = FakeFs::new(cx.background_executor.clone());
1936        fs.insert_tree(
1937            "/dir",
1938            json!({
1939                "one.rs": "const ONE: usize = 1;",
1940                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
1941                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
1942                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
1943            }),
1944        )
1945        .await;
1946        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
1947        let search = cx.new_model(|cx| ProjectSearch::new(project, cx));
1948        let search_view = cx.add_window(|cx| ProjectSearchView::new(search.clone(), cx, None));
1949
1950        search_view
1951            .update(cx, |search_view, cx| {
1952                search_view
1953                    .query_editor
1954                    .update(cx, |query_editor, cx| query_editor.set_text("TWO", cx));
1955                search_view.search(cx);
1956            })
1957            .unwrap();
1958        cx.background_executor.run_until_parked();
1959        search_view.update(cx, |search_view, cx| {
1960            assert_eq!(
1961                search_view
1962                    .results_editor
1963                    .update(cx, |editor, cx| editor.display_text(cx)),
1964                "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;"
1965            );
1966            let match_background_color = cx.theme().colors().search_match_background;
1967            assert_eq!(
1968                search_view
1969                    .results_editor
1970                    .update(cx, |editor, cx| editor.all_text_background_highlights(cx)),
1971                &[
1972                    (
1973                        DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35),
1974                        match_background_color
1975                    ),
1976                    (
1977                        DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40),
1978                        match_background_color
1979                    ),
1980                    (
1981                        DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9),
1982                        match_background_color
1983                    )
1984                ]
1985            );
1986            assert_eq!(search_view.active_match_index, Some(0));
1987            assert_eq!(
1988                search_view
1989                    .results_editor
1990                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1991                [DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35)]
1992            );
1993
1994            search_view.select_match(Direction::Next, cx);
1995        }).unwrap();
1996
1997        search_view
1998            .update(cx, |search_view, cx| {
1999                assert_eq!(search_view.active_match_index, Some(1));
2000                assert_eq!(
2001                    search_view
2002                        .results_editor
2003                        .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2004                    [DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40)]
2005                );
2006                search_view.select_match(Direction::Next, cx);
2007            })
2008            .unwrap();
2009
2010        search_view
2011            .update(cx, |search_view, cx| {
2012                assert_eq!(search_view.active_match_index, Some(2));
2013                assert_eq!(
2014                    search_view
2015                        .results_editor
2016                        .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2017                    [DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9)]
2018                );
2019                search_view.select_match(Direction::Next, cx);
2020            })
2021            .unwrap();
2022
2023        search_view
2024            .update(cx, |search_view, cx| {
2025                assert_eq!(search_view.active_match_index, Some(0));
2026                assert_eq!(
2027                    search_view
2028                        .results_editor
2029                        .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2030                    [DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35)]
2031                );
2032                search_view.select_match(Direction::Prev, cx);
2033            })
2034            .unwrap();
2035
2036        search_view
2037            .update(cx, |search_view, cx| {
2038                assert_eq!(search_view.active_match_index, Some(2));
2039                assert_eq!(
2040                    search_view
2041                        .results_editor
2042                        .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2043                    [DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9)]
2044                );
2045                search_view.select_match(Direction::Prev, cx);
2046            })
2047            .unwrap();
2048
2049        search_view
2050            .update(cx, |search_view, cx| {
2051                assert_eq!(search_view.active_match_index, Some(1));
2052                assert_eq!(
2053                    search_view
2054                        .results_editor
2055                        .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2056                    [DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40)]
2057                );
2058            })
2059            .unwrap();
2060    }
2061
2062    #[gpui::test]
2063    async fn test_project_search_focus(cx: &mut TestAppContext) {
2064        init_test(cx);
2065
2066        let fs = FakeFs::new(cx.background_executor.clone());
2067        fs.insert_tree(
2068            "/dir",
2069            json!({
2070                "one.rs": "const ONE: usize = 1;",
2071                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2072                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2073                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2074            }),
2075        )
2076        .await;
2077        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
2078        let window = cx.add_window(|cx| Workspace::test_new(project, cx));
2079        let workspace = window.clone();
2080        let search_bar = window.build_view(cx, |_| ProjectSearchBar::new());
2081
2082        let active_item = cx.read(|cx| {
2083            workspace
2084                .read(cx)
2085                .unwrap()
2086                .active_pane()
2087                .read(cx)
2088                .active_item()
2089                .and_then(|item| item.downcast::<ProjectSearchView>())
2090        });
2091        assert!(
2092            active_item.is_none(),
2093            "Expected no search panel to be active"
2094        );
2095
2096        window
2097            .update(cx, move |workspace, cx| {
2098                assert_eq!(workspace.panes().len(), 1);
2099                workspace.panes()[0].update(cx, move |pane, cx| {
2100                    pane.toolbar()
2101                        .update(cx, |toolbar, cx| toolbar.add_item(search_bar, cx))
2102                });
2103
2104                ProjectSearchView::deploy(workspace, &workspace::NewSearch, cx)
2105            })
2106            .unwrap();
2107
2108        let Some(search_view) = cx.read(|cx| {
2109            workspace
2110                .read(cx)
2111                .unwrap()
2112                .active_pane()
2113                .read(cx)
2114                .active_item()
2115                .and_then(|item| item.downcast::<ProjectSearchView>())
2116        }) else {
2117            panic!("Search view expected to appear after new search event trigger")
2118        };
2119
2120        cx.spawn(|mut cx| async move {
2121            window
2122                .update(&mut cx, |_, cx| {
2123                    cx.dispatch_action(ToggleFocus.boxed_clone())
2124                })
2125                .unwrap();
2126        })
2127        .detach();
2128        cx.background_executor.run_until_parked();
2129
2130        window.update(cx, |_, cx| {
2131            search_view.update(cx, |search_view, cx| {
2132                    assert!(
2133                        search_view.query_editor.focus_handle(cx).is_focused(cx),
2134                        "Empty search view should be focused after the toggle focus event: no results panel to focus on",
2135                    );
2136                });
2137        }).unwrap();
2138
2139        window
2140            .update(cx, |_, cx| {
2141                search_view.update(cx, |search_view, cx| {
2142                    let query_editor = &search_view.query_editor;
2143                    assert!(
2144                        query_editor.focus_handle(cx).is_focused(cx),
2145                        "Search view should be focused after the new search view is activated",
2146                    );
2147                    let query_text = query_editor.read(cx).text(cx);
2148                    assert!(
2149                        query_text.is_empty(),
2150                        "New search query should be empty but got '{query_text}'",
2151                    );
2152                    let results_text = search_view
2153                        .results_editor
2154                        .update(cx, |editor, cx| editor.display_text(cx));
2155                    assert!(
2156                        results_text.is_empty(),
2157                        "Empty search view should have no results but got '{results_text}'"
2158                    );
2159                });
2160            })
2161            .unwrap();
2162
2163        window
2164            .update(cx, |_, cx| {
2165                search_view.update(cx, |search_view, cx| {
2166                    search_view.query_editor.update(cx, |query_editor, cx| {
2167                        query_editor.set_text("sOMETHINGtHATsURELYdOESnOTeXIST", cx)
2168                    });
2169                    search_view.search(cx);
2170                });
2171            })
2172            .unwrap();
2173
2174        cx.background_executor.run_until_parked();
2175        window
2176            .update(cx, |_, cx| {
2177                search_view.update(cx, |search_view, cx| {
2178                    let results_text = search_view
2179                        .results_editor
2180                        .update(cx, |editor, cx| editor.display_text(cx));
2181                    assert!(
2182                results_text.is_empty(),
2183                "Search view for mismatching query should have no results but got '{results_text}'"
2184            );
2185                    assert!(
2186                search_view.query_editor.focus_handle(cx).is_focused(cx),
2187                "Search view should be focused after mismatching query had been used in search",
2188            );
2189                });
2190            })
2191            .unwrap();
2192        cx.spawn(|mut cx| async move {
2193            window.update(&mut cx, |_, cx| {
2194                cx.dispatch_action(ToggleFocus.boxed_clone())
2195            })
2196        })
2197        .detach();
2198        cx.background_executor.run_until_parked();
2199        window.update(cx, |_, cx| {
2200            search_view.update(cx, |search_view, cx| {
2201                    assert!(
2202                        search_view.query_editor.focus_handle(cx).is_focused(cx),
2203                        "Search view with mismatching query should be focused after the toggle focus event: still no results panel to focus on",
2204                    );
2205                });
2206        }).unwrap();
2207
2208        window
2209            .update(cx, |_, cx| {
2210                search_view.update(cx, |search_view, cx| {
2211                    search_view
2212                        .query_editor
2213                        .update(cx, |query_editor, cx| query_editor.set_text("TWO", cx));
2214                    search_view.search(cx);
2215                })
2216            })
2217            .unwrap();
2218        cx.background_executor.run_until_parked();
2219        window.update(cx, |_, cx|
2220        search_view.update(cx, |search_view, cx| {
2221                assert_eq!(
2222                    search_view
2223                        .results_editor
2224                        .update(cx, |editor, cx| editor.display_text(cx)),
2225                    "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
2226                    "Search view results should match the query"
2227                );
2228                assert!(
2229                    search_view.results_editor.focus_handle(cx).is_focused(cx),
2230                    "Search view with mismatching query should be focused after search results are available",
2231                );
2232            })).unwrap();
2233        cx.spawn(|mut cx| async move {
2234            window
2235                .update(&mut cx, |_, cx| {
2236                    cx.dispatch_action(ToggleFocus.boxed_clone())
2237                })
2238                .unwrap();
2239        })
2240        .detach();
2241        cx.background_executor.run_until_parked();
2242        window.update(cx, |_, cx| {
2243            search_view.update(cx, |search_view, cx| {
2244                    assert!(
2245                        search_view.results_editor.focus_handle(cx).is_focused(cx),
2246                        "Search view with matching query should still have its results editor focused after the toggle focus event",
2247                    );
2248                });
2249        }).unwrap();
2250
2251        workspace
2252            .update(cx, |workspace, cx| {
2253                ProjectSearchView::deploy(workspace, &workspace::NewSearch, cx)
2254            })
2255            .unwrap();
2256        cx.background_executor.run_until_parked();
2257        let Some(search_view_2) = cx.read(|cx| {
2258            workspace
2259                .read(cx)
2260                .unwrap()
2261                .active_pane()
2262                .read(cx)
2263                .active_item()
2264                .and_then(|item| item.downcast::<ProjectSearchView>())
2265        }) else {
2266            panic!("Search view expected to appear after new search event trigger")
2267        };
2268        assert!(
2269            search_view_2 != search_view,
2270            "New search view should be open after `workspace::NewSearch` event"
2271        );
2272
2273        window.update(cx, |_, cx| {
2274            search_view.update(cx, |search_view, cx| {
2275                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO", "First search view should not have an updated query");
2276                    assert_eq!(
2277                        search_view
2278                            .results_editor
2279                            .update(cx, |editor, cx| editor.display_text(cx)),
2280                        "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
2281                        "Results of the first search view should not update too"
2282                    );
2283                    assert!(
2284                        !search_view.query_editor.focus_handle(cx).is_focused(cx),
2285                        "Focus should be moved away from the first search view"
2286                    );
2287                });
2288        }).unwrap();
2289
2290        window.update(cx, |_, cx| {
2291            search_view_2.update(cx, |search_view_2, cx| {
2292                    assert_eq!(
2293                        search_view_2.query_editor.read(cx).text(cx),
2294                        "two",
2295                        "New search view should get the query from the text cursor was at during the event spawn (first search view's first result)"
2296                    );
2297                    assert_eq!(
2298                        search_view_2
2299                            .results_editor
2300                            .update(cx, |editor, cx| editor.display_text(cx)),
2301                        "",
2302                        "No search results should be in the 2nd view yet, as we did not spawn a search for it"
2303                    );
2304                    assert!(
2305                        search_view_2.query_editor.focus_handle(cx).is_focused(cx),
2306                        "Focus should be moved into query editor fo the new window"
2307                    );
2308                });
2309        }).unwrap();
2310
2311        window
2312            .update(cx, |_, cx| {
2313                search_view_2.update(cx, |search_view_2, cx| {
2314                    search_view_2
2315                        .query_editor
2316                        .update(cx, |query_editor, cx| query_editor.set_text("FOUR", cx));
2317                    search_view_2.search(cx);
2318                });
2319            })
2320            .unwrap();
2321
2322        cx.background_executor.run_until_parked();
2323        window.update(cx, |_, cx| {
2324            search_view_2.update(cx, |search_view_2, cx| {
2325                    assert_eq!(
2326                        search_view_2
2327                            .results_editor
2328                            .update(cx, |editor, cx| editor.display_text(cx)),
2329                        "\n\nconst FOUR: usize = one::ONE + three::THREE;",
2330                        "New search view with the updated query should have new search results"
2331                    );
2332                    assert!(
2333                        search_view_2.results_editor.focus_handle(cx).is_focused(cx),
2334                        "Search view with mismatching query should be focused after search results are available",
2335                    );
2336                });
2337        }).unwrap();
2338
2339        cx.spawn(|mut cx| async move {
2340            window
2341                .update(&mut cx, |_, cx| {
2342                    cx.dispatch_action(ToggleFocus.boxed_clone())
2343                })
2344                .unwrap();
2345        })
2346        .detach();
2347        cx.background_executor.run_until_parked();
2348        window.update(cx, |_, cx| {
2349            search_view_2.update(cx, |search_view_2, cx| {
2350                    assert!(
2351                        search_view_2.results_editor.focus_handle(cx).is_focused(cx),
2352                        "Search view with matching query should switch focus to the results editor after the toggle focus event",
2353                    );
2354                });}).unwrap();
2355    }
2356
2357    #[gpui::test]
2358    async fn test_new_project_search_in_directory(cx: &mut TestAppContext) {
2359        init_test(cx);
2360
2361        let fs = FakeFs::new(cx.background_executor.clone());
2362        fs.insert_tree(
2363            "/dir",
2364            json!({
2365                "a": {
2366                    "one.rs": "const ONE: usize = 1;",
2367                    "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2368                },
2369                "b": {
2370                    "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2371                    "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2372                },
2373            }),
2374        )
2375        .await;
2376        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
2377        let worktree_id = project.read_with(cx, |project, cx| {
2378            project.worktrees().next().unwrap().read(cx).id()
2379        });
2380        let window = cx.add_window(|cx| Workspace::test_new(project, cx));
2381        let workspace = window.root(cx).unwrap();
2382        let search_bar = window.build_view(cx, |_| ProjectSearchBar::new());
2383
2384        let active_item = cx.read(|cx| {
2385            workspace
2386                .read(cx)
2387                .active_pane()
2388                .read(cx)
2389                .active_item()
2390                .and_then(|item| item.downcast::<ProjectSearchView>())
2391        });
2392        assert!(
2393            active_item.is_none(),
2394            "Expected no search panel to be active"
2395        );
2396
2397        window
2398            .update(cx, move |workspace, cx| {
2399                assert_eq!(workspace.panes().len(), 1);
2400                workspace.panes()[0].update(cx, move |pane, cx| {
2401                    pane.toolbar()
2402                        .update(cx, |toolbar, cx| toolbar.add_item(search_bar, cx))
2403                });
2404            })
2405            .unwrap();
2406
2407        let one_file_entry = cx.update(|cx| {
2408            workspace
2409                .read(cx)
2410                .project()
2411                .read(cx)
2412                .entry_for_path(&(worktree_id, "a/one.rs").into(), cx)
2413                .expect("no entry for /a/one.rs file")
2414        });
2415        assert!(one_file_entry.is_file());
2416        window
2417            .update(cx, |workspace, cx| {
2418                ProjectSearchView::new_search_in_directory(workspace, &one_file_entry, cx)
2419            })
2420            .unwrap();
2421        let active_search_entry = cx.read(|cx| {
2422            workspace
2423                .read(cx)
2424                .active_pane()
2425                .read(cx)
2426                .active_item()
2427                .and_then(|item| item.downcast::<ProjectSearchView>())
2428        });
2429        assert!(
2430            active_search_entry.is_none(),
2431            "Expected no search panel to be active for file entry"
2432        );
2433
2434        let a_dir_entry = cx.update(|cx| {
2435            workspace
2436                .read(cx)
2437                .project()
2438                .read(cx)
2439                .entry_for_path(&(worktree_id, "a").into(), cx)
2440                .expect("no entry for /a/ directory")
2441        });
2442        assert!(a_dir_entry.is_dir());
2443        window
2444            .update(cx, |workspace, cx| {
2445                ProjectSearchView::new_search_in_directory(workspace, &a_dir_entry, cx)
2446            })
2447            .unwrap();
2448
2449        let Some(search_view) = cx.read(|cx| {
2450            workspace
2451                .read(cx)
2452                .active_pane()
2453                .read(cx)
2454                .active_item()
2455                .and_then(|item| item.downcast::<ProjectSearchView>())
2456        }) else {
2457            panic!("Search view expected to appear after new search in directory event trigger")
2458        };
2459        cx.background_executor.run_until_parked();
2460        window
2461            .update(cx, |_, cx| {
2462                search_view.update(cx, |search_view, cx| {
2463                    assert!(
2464                        search_view.query_editor.focus_handle(cx).is_focused(cx),
2465                        "On new search in directory, focus should be moved into query editor"
2466                    );
2467                    search_view.excluded_files_editor.update(cx, |editor, cx| {
2468                        assert!(
2469                            editor.display_text(cx).is_empty(),
2470                            "New search in directory should not have any excluded files"
2471                        );
2472                    });
2473                    search_view.included_files_editor.update(cx, |editor, cx| {
2474                        assert_eq!(
2475                            editor.display_text(cx),
2476                            a_dir_entry.path.to_str().unwrap(),
2477                            "New search in directory should have included dir entry path"
2478                        );
2479                    });
2480                });
2481            })
2482            .unwrap();
2483        window
2484            .update(cx, |_, cx| {
2485                search_view.update(cx, |search_view, cx| {
2486                    search_view
2487                        .query_editor
2488                        .update(cx, |query_editor, cx| query_editor.set_text("const", cx));
2489                    search_view.search(cx);
2490                });
2491            })
2492            .unwrap();
2493        cx.background_executor.run_until_parked();
2494        window
2495            .update(cx, |_, cx| {
2496                search_view.update(cx, |search_view, cx| {
2497                    assert_eq!(
2498                search_view
2499                    .results_editor
2500                    .update(cx, |editor, cx| editor.display_text(cx)),
2501                "\n\nconst ONE: usize = 1;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
2502                "New search in directory should have a filter that matches a certain directory"
2503            );
2504                })
2505            })
2506            .unwrap();
2507    }
2508
2509    #[gpui::test]
2510    async fn test_search_query_history(cx: &mut TestAppContext) {
2511        init_test(cx);
2512
2513        let fs = FakeFs::new(cx.background_executor.clone());
2514        fs.insert_tree(
2515            "/dir",
2516            json!({
2517                "one.rs": "const ONE: usize = 1;",
2518                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2519                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2520                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2521            }),
2522        )
2523        .await;
2524        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
2525        let window = cx.add_window(|cx| Workspace::test_new(project, cx));
2526        let workspace = window.root(cx).unwrap();
2527        let search_bar = window.build_view(cx, |_| ProjectSearchBar::new());
2528
2529        window
2530            .update(cx, {
2531                let search_bar = search_bar.clone();
2532                move |workspace, cx| {
2533                    assert_eq!(workspace.panes().len(), 1);
2534                    workspace.panes()[0].update(cx, move |pane, cx| {
2535                        pane.toolbar()
2536                            .update(cx, |toolbar, cx| toolbar.add_item(search_bar, cx))
2537                    });
2538
2539                    ProjectSearchView::deploy(workspace, &workspace::NewSearch, cx)
2540                }
2541            })
2542            .unwrap();
2543
2544        let search_view = cx.read(|cx| {
2545            workspace
2546                .read(cx)
2547                .active_pane()
2548                .read(cx)
2549                .active_item()
2550                .and_then(|item| item.downcast::<ProjectSearchView>())
2551                .expect("Search view expected to appear after new search event trigger")
2552        });
2553
2554        // Add 3 search items into the history + another unsubmitted one.
2555        window
2556            .update(cx, |_, cx| {
2557                search_view.update(cx, |search_view, cx| {
2558                    search_view.search_options = SearchOptions::CASE_SENSITIVE;
2559                    search_view
2560                        .query_editor
2561                        .update(cx, |query_editor, cx| query_editor.set_text("ONE", cx));
2562                    search_view.search(cx);
2563                });
2564            })
2565            .unwrap();
2566
2567        cx.background_executor.run_until_parked();
2568        window
2569            .update(cx, |_, cx| {
2570                search_view.update(cx, |search_view, cx| {
2571                    search_view
2572                        .query_editor
2573                        .update(cx, |query_editor, cx| query_editor.set_text("TWO", cx));
2574                    search_view.search(cx);
2575                });
2576            })
2577            .unwrap();
2578        cx.background_executor.run_until_parked();
2579        window
2580            .update(cx, |_, cx| {
2581                search_view.update(cx, |search_view, cx| {
2582                    search_view
2583                        .query_editor
2584                        .update(cx, |query_editor, cx| query_editor.set_text("THREE", cx));
2585                    search_view.search(cx);
2586                })
2587            })
2588            .unwrap();
2589        cx.background_executor.run_until_parked();
2590        window
2591            .update(cx, |_, cx| {
2592                search_view.update(cx, |search_view, cx| {
2593                    search_view.query_editor.update(cx, |query_editor, cx| {
2594                        query_editor.set_text("JUST_TEXT_INPUT", cx)
2595                    });
2596                })
2597            })
2598            .unwrap();
2599        cx.background_executor.run_until_parked();
2600
2601        // Ensure that the latest input with search settings is active.
2602        window
2603            .update(cx, |_, cx| {
2604                search_view.update(cx, |search_view, cx| {
2605                    assert_eq!(
2606                        search_view.query_editor.read(cx).text(cx),
2607                        "JUST_TEXT_INPUT"
2608                    );
2609                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2610                });
2611            })
2612            .unwrap();
2613
2614        // Next history query after the latest should set the query to the empty string.
2615        window
2616            .update(cx, |_, cx| {
2617                search_bar.update(cx, |search_bar, cx| {
2618                    search_bar.next_history_query(&NextHistoryQuery, cx);
2619                })
2620            })
2621            .unwrap();
2622        window
2623            .update(cx, |_, cx| {
2624                search_view.update(cx, |search_view, cx| {
2625                    assert_eq!(search_view.query_editor.read(cx).text(cx), "");
2626                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2627                });
2628            })
2629            .unwrap();
2630        window
2631            .update(cx, |_, cx| {
2632                search_bar.update(cx, |search_bar, cx| {
2633                    search_bar.next_history_query(&NextHistoryQuery, cx);
2634                })
2635            })
2636            .unwrap();
2637        window
2638            .update(cx, |_, cx| {
2639                search_view.update(cx, |search_view, cx| {
2640                    assert_eq!(search_view.query_editor.read(cx).text(cx), "");
2641                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2642                });
2643            })
2644            .unwrap();
2645
2646        // First previous query for empty current query should set the query to the latest submitted one.
2647        window
2648            .update(cx, |_, cx| {
2649                search_bar.update(cx, |search_bar, cx| {
2650                    search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2651                });
2652            })
2653            .unwrap();
2654        window
2655            .update(cx, |_, cx| {
2656                search_view.update(cx, |search_view, cx| {
2657                    assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
2658                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2659                });
2660            })
2661            .unwrap();
2662
2663        // Further previous items should go over the history in reverse order.
2664        window
2665            .update(cx, |_, cx| {
2666                search_bar.update(cx, |search_bar, cx| {
2667                    search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2668                });
2669            })
2670            .unwrap();
2671        window
2672            .update(cx, |_, cx| {
2673                search_view.update(cx, |search_view, cx| {
2674                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
2675                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2676                });
2677            })
2678            .unwrap();
2679
2680        // Previous items should never go behind the first history item.
2681        window
2682            .update(cx, |_, cx| {
2683                search_bar.update(cx, |search_bar, cx| {
2684                    search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2685                });
2686            })
2687            .unwrap();
2688        window
2689            .update(cx, |_, cx| {
2690                search_view.update(cx, |search_view, cx| {
2691                    assert_eq!(search_view.query_editor.read(cx).text(cx), "ONE");
2692                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2693                });
2694            })
2695            .unwrap();
2696        window
2697            .update(cx, |_, cx| {
2698                search_bar.update(cx, |search_bar, cx| {
2699                    search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2700                });
2701            })
2702            .unwrap();
2703        window
2704            .update(cx, |_, cx| {
2705                search_view.update(cx, |search_view, cx| {
2706                    assert_eq!(search_view.query_editor.read(cx).text(cx), "ONE");
2707                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2708                });
2709            })
2710            .unwrap();
2711
2712        // Next items should go over the history in the original order.
2713        window
2714            .update(cx, |_, cx| {
2715                search_bar.update(cx, |search_bar, cx| {
2716                    search_bar.next_history_query(&NextHistoryQuery, cx);
2717                });
2718            })
2719            .unwrap();
2720        window
2721            .update(cx, |_, cx| {
2722                search_view.update(cx, |search_view, cx| {
2723                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
2724                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2725                });
2726            })
2727            .unwrap();
2728
2729        window
2730            .update(cx, |_, cx| {
2731                search_view.update(cx, |search_view, cx| {
2732                    search_view
2733                        .query_editor
2734                        .update(cx, |query_editor, cx| query_editor.set_text("TWO_NEW", cx));
2735                    search_view.search(cx);
2736                });
2737            })
2738            .unwrap();
2739        cx.background_executor.run_until_parked();
2740        window
2741            .update(cx, |_, cx| {
2742                search_view.update(cx, |search_view, cx| {
2743                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO_NEW");
2744                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2745                });
2746            })
2747            .unwrap();
2748
2749        // New search input should add another entry to history and move the selection to the end of the history.
2750        window
2751            .update(cx, |_, cx| {
2752                search_bar.update(cx, |search_bar, cx| {
2753                    search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2754                });
2755            })
2756            .unwrap();
2757        window
2758            .update(cx, |_, cx| {
2759                search_view.update(cx, |search_view, cx| {
2760                    assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
2761                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2762                });
2763            })
2764            .unwrap();
2765        window
2766            .update(cx, |_, cx| {
2767                search_bar.update(cx, |search_bar, cx| {
2768                    search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2769                });
2770            })
2771            .unwrap();
2772        window
2773            .update(cx, |_, cx| {
2774                search_view.update(cx, |search_view, cx| {
2775                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
2776                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2777                });
2778            })
2779            .unwrap();
2780        window
2781            .update(cx, |_, cx| {
2782                search_bar.update(cx, |search_bar, cx| {
2783                    search_bar.next_history_query(&NextHistoryQuery, cx);
2784                });
2785            })
2786            .unwrap();
2787        window
2788            .update(cx, |_, cx| {
2789                search_view.update(cx, |search_view, cx| {
2790                    assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
2791                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2792                });
2793            })
2794            .unwrap();
2795        window
2796            .update(cx, |_, cx| {
2797                search_bar.update(cx, |search_bar, cx| {
2798                    search_bar.next_history_query(&NextHistoryQuery, cx);
2799                });
2800            })
2801            .unwrap();
2802        window
2803            .update(cx, |_, cx| {
2804                search_view.update(cx, |search_view, cx| {
2805                    assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO_NEW");
2806                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2807                });
2808            })
2809            .unwrap();
2810        window
2811            .update(cx, |_, cx| {
2812                search_bar.update(cx, |search_bar, cx| {
2813                    search_bar.next_history_query(&NextHistoryQuery, cx);
2814                });
2815            })
2816            .unwrap();
2817        window
2818            .update(cx, |_, cx| {
2819                search_view.update(cx, |search_view, cx| {
2820                    assert_eq!(search_view.query_editor.read(cx).text(cx), "");
2821                    assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2822                });
2823            })
2824            .unwrap();
2825    }
2826
2827    pub fn init_test(cx: &mut TestAppContext) {
2828        cx.update(|cx| {
2829            let settings = SettingsStore::test(cx);
2830            cx.set_global(settings);
2831            cx.set_global(ActiveSearches::default());
2832            SemanticIndexSettings::register(cx);
2833
2834            theme::init(theme::LoadThemes::JustBase, cx);
2835
2836            language::init(cx);
2837            client::init_settings(cx);
2838            editor::init(cx);
2839            workspace::init_settings(cx);
2840            Project::init_settings(cx);
2841            super::init(cx);
2842        });
2843    }
2844}