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