project_search.rs

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