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