project_search.rs

   1use crate::{
   2    history::SearchHistory,
   3    mode::SearchMode,
   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            let search = _search.read(cx);
1428            let is_semantic_disabled = search.semantic_state.is_none();
1429            let render_option_button_icon = |path, option, cx: &mut ViewContext<Self>| {
1430                crate::search_bar::render_option_button_icon(
1431                    self.is_option_enabled(option, cx),
1432                    path,
1433                    option.bits as usize,
1434                    format!("Toggle {}", option.label()),
1435                    option.to_toggle_action(),
1436                    move |_, this, cx| {
1437                        this.toggle_search_option(option, cx);
1438                    },
1439                    cx,
1440                )
1441            };
1442            let case_sensitive = is_semantic_disabled.then(|| {
1443                render_option_button_icon(
1444                    "icons/case_insensitive_12.svg",
1445                    SearchOptions::CASE_SENSITIVE,
1446                    cx,
1447                )
1448            });
1449
1450            let whole_word = is_semantic_disabled.then(|| {
1451                render_option_button_icon("icons/word_search_12.svg", SearchOptions::WHOLE_WORD, cx)
1452            });
1453
1454            let search = _search.read(cx);
1455            let icon_style = theme.search.editor_icon.clone();
1456
1457            // Editor Functionality
1458            let query = Flex::row()
1459                .with_child(
1460                    Svg::for_style(icon_style.icon)
1461                        .contained()
1462                        .with_style(icon_style.container),
1463                )
1464                .with_child(ChildView::new(&search.query_editor, cx).flex(1., true))
1465                .with_child(
1466                    Flex::row()
1467                        .with_child(filter_button)
1468                        .with_children(case_sensitive)
1469                        .with_children(whole_word)
1470                        .flex(1., false)
1471                        .constrained()
1472                        .contained(),
1473                )
1474                .align_children_center()
1475                .flex(1., true);
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 included_files_view = ChildView::new(&search.included_files_editor, cx)
1494                .contained()
1495                .flex(1., true);
1496            let excluded_files_view = ChildView::new(&search.excluded_files_editor, cx)
1497                .contained()
1498                .flex(1., true);
1499            let filters = search.filters_enabled.then(|| {
1500                Flex::row()
1501                    .with_child(
1502                        included_files_view
1503                            .contained()
1504                            .with_style(include_container_style)
1505                            .constrained()
1506                            .with_height(theme.search.search_bar_row_height)
1507                            .with_min_width(theme.search.include_exclude_editor.min_width)
1508                            .with_max_width(theme.search.include_exclude_editor.max_width),
1509                    )
1510                    .with_child(
1511                        excluded_files_view
1512                            .contained()
1513                            .with_style(exclude_container_style)
1514                            .constrained()
1515                            .with_height(theme.search.search_bar_row_height)
1516                            .with_min_width(theme.search.include_exclude_editor.min_width)
1517                            .with_max_width(theme.search.include_exclude_editor.max_width),
1518                    )
1519                    .contained()
1520                    .with_padding_top(theme.workspace.toolbar.container.padding.bottom)
1521            });
1522
1523            let editor_column = Flex::column()
1524                .with_child(
1525                    query
1526                        .contained()
1527                        .with_style(query_container_style)
1528                        .constrained()
1529                        .with_min_width(theme.search.editor.min_width)
1530                        .with_max_width(theme.search.editor.max_width)
1531                        .with_height(theme.search.search_bar_row_height)
1532                        .flex(1., false),
1533                )
1534                .with_children(filters)
1535                .flex(1., false);
1536
1537            let matches = search.active_match_index.map(|match_ix| {
1538                Label::new(
1539                    format!(
1540                        "{}/{}",
1541                        match_ix + 1,
1542                        search.model.read(cx).match_ranges.len()
1543                    ),
1544                    theme.search.match_index.text.clone(),
1545                )
1546                .contained()
1547                .with_style(theme.search.match_index.container)
1548                .aligned()
1549            });
1550
1551            let search_button_for_mode = |mode, cx: &mut ViewContext<ProjectSearchBar>| {
1552                let is_active = if let Some(search) = self.active_project_search.as_ref() {
1553                    let search = search.read(cx);
1554                    search.current_mode == mode
1555                } else {
1556                    false
1557                };
1558                render_search_mode_button(
1559                    mode,
1560                    is_active,
1561                    move |_, this, cx| {
1562                        this.activate_search_mode(mode, cx);
1563                    },
1564                    cx,
1565                )
1566            };
1567            let is_active = search.active_match_index.is_some();
1568            let semantic_index = SemanticIndex::enabled(cx)
1569                .then(|| search_button_for_mode(SearchMode::Semantic, cx));
1570            let nav_button_for_direction = |label, direction, cx: &mut ViewContext<Self>| {
1571                render_nav_button(
1572                    label,
1573                    direction,
1574                    is_active,
1575                    move |_, this, cx| {
1576                        if let Some(search) = this.active_project_search.as_ref() {
1577                            search.update(cx, |search, cx| search.select_match(direction, cx));
1578                        }
1579                    },
1580                    cx,
1581                )
1582            };
1583
1584            let nav_column = Flex::row()
1585                .with_child(nav_button_for_direction("<", Direction::Prev, cx))
1586                .with_child(nav_button_for_direction(">", Direction::Next, cx))
1587                .with_child(Flex::row().with_children(matches))
1588                .constrained()
1589                .with_height(theme.search.search_bar_row_height);
1590
1591            let mode_column = Flex::row()
1592                .with_child(
1593                    Flex::row()
1594                        .with_child(search_button_for_mode(SearchMode::Text, cx))
1595                        .with_children(semantic_index)
1596                        .with_child(search_button_for_mode(SearchMode::Regex, cx))
1597                        .contained()
1598                        .with_style(theme.search.modes_container),
1599                )
1600                .with_child(super::search_bar::render_close_button(
1601                    "Dismiss Project Search",
1602                    &theme.search,
1603                    cx,
1604                    |_, this, cx| {
1605                        if let Some(search) = this.active_project_search.as_mut() {
1606                            search.update(cx, |_, cx| cx.emit(ViewEvent::Dismiss))
1607                        }
1608                    },
1609                    None,
1610                ))
1611                .constrained()
1612                .with_height(theme.search.search_bar_row_height)
1613                .aligned()
1614                .right()
1615                .top()
1616                .flex_float();
1617
1618            Flex::row()
1619                .with_child(editor_column)
1620                .with_child(nav_column)
1621                .with_child(mode_column)
1622                .contained()
1623                .with_style(theme.search.container)
1624                .into_any_named("project search")
1625        } else {
1626            Empty::new().into_any()
1627        }
1628    }
1629}
1630
1631impl ToolbarItemView for ProjectSearchBar {
1632    fn set_active_pane_item(
1633        &mut self,
1634        active_pane_item: Option<&dyn ItemHandle>,
1635        cx: &mut ViewContext<Self>,
1636    ) -> ToolbarItemLocation {
1637        cx.notify();
1638        self.subscription = None;
1639        self.active_project_search = None;
1640        if let Some(search) = active_pane_item.and_then(|i| i.downcast::<ProjectSearchView>()) {
1641            search.update(cx, |search, cx| {
1642                if search.current_mode == SearchMode::Semantic {
1643                    search.index_project(cx);
1644                }
1645            });
1646
1647            self.subscription = Some(cx.observe(&search, |_, _, cx| cx.notify()));
1648            self.active_project_search = Some(search);
1649            ToolbarItemLocation::PrimaryLeft {
1650                flex: Some((1., false)),
1651            }
1652        } else {
1653            ToolbarItemLocation::Hidden
1654        }
1655    }
1656
1657    fn row_count(&self, cx: &ViewContext<Self>) -> usize {
1658        self.active_project_search
1659            .as_ref()
1660            .map(|search| {
1661                let offset = search.read(cx).filters_enabled as usize;
1662                2 + offset
1663            })
1664            .unwrap_or_else(|| 2)
1665    }
1666}
1667
1668#[cfg(test)]
1669pub mod tests {
1670    use super::*;
1671    use editor::DisplayPoint;
1672    use gpui::{color::Color, executor::Deterministic, TestAppContext};
1673    use project::FakeFs;
1674    use semantic_index::semantic_index_settings::SemanticIndexSettings;
1675    use serde_json::json;
1676    use settings::SettingsStore;
1677    use std::sync::Arc;
1678    use theme::ThemeSettings;
1679
1680    #[gpui::test]
1681    async fn test_project_search(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
1682        init_test(cx);
1683
1684        let fs = FakeFs::new(cx.background());
1685        fs.insert_tree(
1686            "/dir",
1687            json!({
1688                "one.rs": "const ONE: usize = 1;",
1689                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
1690                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
1691                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
1692            }),
1693        )
1694        .await;
1695        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
1696        let search = cx.add_model(|cx| ProjectSearch::new(project, cx));
1697        let search_view = cx
1698            .add_window(|cx| ProjectSearchView::new(search.clone(), cx))
1699            .root(cx);
1700
1701        search_view.update(cx, |search_view, cx| {
1702            search_view
1703                .query_editor
1704                .update(cx, |query_editor, cx| query_editor.set_text("TWO", cx));
1705            search_view.search(cx);
1706        });
1707        deterministic.run_until_parked();
1708        search_view.update(cx, |search_view, cx| {
1709            assert_eq!(
1710                search_view
1711                    .results_editor
1712                    .update(cx, |editor, cx| editor.display_text(cx)),
1713                "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;"
1714            );
1715            assert_eq!(
1716                search_view
1717                    .results_editor
1718                    .update(cx, |editor, cx| editor.all_background_highlights(cx)),
1719                &[
1720                    (
1721                        DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35),
1722                        Color::red()
1723                    ),
1724                    (
1725                        DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40),
1726                        Color::red()
1727                    ),
1728                    (
1729                        DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9),
1730                        Color::red()
1731                    )
1732                ]
1733            );
1734            assert_eq!(search_view.active_match_index, Some(0));
1735            assert_eq!(
1736                search_view
1737                    .results_editor
1738                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1739                [DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35)]
1740            );
1741
1742            search_view.select_match(Direction::Next, cx);
1743        });
1744
1745        search_view.update(cx, |search_view, cx| {
1746            assert_eq!(search_view.active_match_index, Some(1));
1747            assert_eq!(
1748                search_view
1749                    .results_editor
1750                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1751                [DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40)]
1752            );
1753            search_view.select_match(Direction::Next, cx);
1754        });
1755
1756        search_view.update(cx, |search_view, cx| {
1757            assert_eq!(search_view.active_match_index, Some(2));
1758            assert_eq!(
1759                search_view
1760                    .results_editor
1761                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1762                [DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9)]
1763            );
1764            search_view.select_match(Direction::Next, cx);
1765        });
1766
1767        search_view.update(cx, |search_view, cx| {
1768            assert_eq!(search_view.active_match_index, Some(0));
1769            assert_eq!(
1770                search_view
1771                    .results_editor
1772                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1773                [DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35)]
1774            );
1775            search_view.select_match(Direction::Prev, cx);
1776        });
1777
1778        search_view.update(cx, |search_view, cx| {
1779            assert_eq!(search_view.active_match_index, Some(2));
1780            assert_eq!(
1781                search_view
1782                    .results_editor
1783                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1784                [DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9)]
1785            );
1786            search_view.select_match(Direction::Prev, cx);
1787        });
1788
1789        search_view.update(cx, |search_view, cx| {
1790            assert_eq!(search_view.active_match_index, Some(1));
1791            assert_eq!(
1792                search_view
1793                    .results_editor
1794                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1795                [DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40)]
1796            );
1797        });
1798    }
1799
1800    #[gpui::test]
1801    async fn test_project_search_focus(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
1802        init_test(cx);
1803
1804        let fs = FakeFs::new(cx.background());
1805        fs.insert_tree(
1806            "/dir",
1807            json!({
1808                "one.rs": "const ONE: usize = 1;",
1809                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
1810                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
1811                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
1812            }),
1813        )
1814        .await;
1815        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
1816        let window = cx.add_window(|cx| Workspace::test_new(project, cx));
1817        let workspace = window.root(cx);
1818
1819        let active_item = cx.read(|cx| {
1820            workspace
1821                .read(cx)
1822                .active_pane()
1823                .read(cx)
1824                .active_item()
1825                .and_then(|item| item.downcast::<ProjectSearchView>())
1826        });
1827        assert!(
1828            active_item.is_none(),
1829            "Expected no search panel to be active, but got: {active_item:?}"
1830        );
1831
1832        workspace.update(cx, |workspace, cx| {
1833            ProjectSearchView::deploy(workspace, &workspace::NewSearch, cx)
1834        });
1835
1836        let Some(search_view) = cx.read(|cx| {
1837            workspace
1838                .read(cx)
1839                .active_pane()
1840                .read(cx)
1841                .active_item()
1842                .and_then(|item| item.downcast::<ProjectSearchView>())
1843        }) else {
1844            panic!("Search view expected to appear after new search event trigger")
1845        };
1846        let search_view_id = search_view.id();
1847
1848        cx.spawn(|mut cx| async move {
1849            window.dispatch_action(search_view_id, &ToggleFocus, &mut cx);
1850        })
1851        .detach();
1852        deterministic.run_until_parked();
1853        search_view.update(cx, |search_view, cx| {
1854            assert!(
1855                search_view.query_editor.is_focused(cx),
1856                "Empty search view should be focused after the toggle focus event: no results panel to focus on",
1857            );
1858        });
1859
1860        search_view.update(cx, |search_view, cx| {
1861            let query_editor = &search_view.query_editor;
1862            assert!(
1863                query_editor.is_focused(cx),
1864                "Search view should be focused after the new search view is activated",
1865            );
1866            let query_text = query_editor.read(cx).text(cx);
1867            assert!(
1868                query_text.is_empty(),
1869                "New search query should be empty but got '{query_text}'",
1870            );
1871            let results_text = search_view
1872                .results_editor
1873                .update(cx, |editor, cx| editor.display_text(cx));
1874            assert!(
1875                results_text.is_empty(),
1876                "Empty search view should have no results but got '{results_text}'"
1877            );
1878        });
1879
1880        search_view.update(cx, |search_view, cx| {
1881            search_view.query_editor.update(cx, |query_editor, cx| {
1882                query_editor.set_text("sOMETHINGtHATsURELYdOESnOTeXIST", cx)
1883            });
1884            search_view.search(cx);
1885        });
1886        deterministic.run_until_parked();
1887        search_view.update(cx, |search_view, cx| {
1888            let results_text = search_view
1889                .results_editor
1890                .update(cx, |editor, cx| editor.display_text(cx));
1891            assert!(
1892                results_text.is_empty(),
1893                "Search view for mismatching query should have no results but got '{results_text}'"
1894            );
1895            assert!(
1896                search_view.query_editor.is_focused(cx),
1897                "Search view should be focused after mismatching query had been used in search",
1898            );
1899        });
1900        cx.spawn(
1901            |mut cx| async move { window.dispatch_action(search_view_id, &ToggleFocus, &mut cx) },
1902        )
1903        .detach();
1904        deterministic.run_until_parked();
1905        search_view.update(cx, |search_view, cx| {
1906            assert!(
1907                search_view.query_editor.is_focused(cx),
1908                "Search view with mismatching query should be focused after the toggle focus event: still no results panel to focus on",
1909            );
1910        });
1911
1912        search_view.update(cx, |search_view, cx| {
1913            search_view
1914                .query_editor
1915                .update(cx, |query_editor, cx| query_editor.set_text("TWO", cx));
1916            search_view.search(cx);
1917        });
1918        deterministic.run_until_parked();
1919        search_view.update(cx, |search_view, cx| {
1920            assert_eq!(
1921                search_view
1922                    .results_editor
1923                    .update(cx, |editor, cx| editor.display_text(cx)),
1924                "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
1925                "Search view results should match the query"
1926            );
1927            assert!(
1928                search_view.results_editor.is_focused(cx),
1929                "Search view with mismatching query should be focused after search results are available",
1930            );
1931        });
1932        cx.spawn(|mut cx| async move {
1933            window.dispatch_action(search_view_id, &ToggleFocus, &mut cx);
1934        })
1935        .detach();
1936        deterministic.run_until_parked();
1937        search_view.update(cx, |search_view, cx| {
1938            assert!(
1939                search_view.results_editor.is_focused(cx),
1940                "Search view with matching query should still have its results editor focused after the toggle focus event",
1941            );
1942        });
1943
1944        workspace.update(cx, |workspace, cx| {
1945            ProjectSearchView::deploy(workspace, &workspace::NewSearch, cx)
1946        });
1947        search_view.update(cx, |search_view, cx| {
1948            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");
1949            assert_eq!(
1950                search_view
1951                    .results_editor
1952                    .update(cx, |editor, cx| editor.display_text(cx)),
1953                "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
1954                "Results should be unchanged after search view 2nd open in a row"
1955            );
1956            assert!(
1957                search_view.query_editor.is_focused(cx),
1958                "Focus should be moved into query editor again after search view 2nd open in a row"
1959            );
1960        });
1961
1962        cx.spawn(|mut cx| async move {
1963            window.dispatch_action(search_view_id, &ToggleFocus, &mut cx);
1964        })
1965        .detach();
1966        deterministic.run_until_parked();
1967        search_view.update(cx, |search_view, cx| {
1968            assert!(
1969                search_view.results_editor.is_focused(cx),
1970                "Search view with matching query should switch focus to the results editor after the toggle focus event",
1971            );
1972        });
1973    }
1974
1975    #[gpui::test]
1976    async fn test_new_project_search_in_directory(
1977        deterministic: Arc<Deterministic>,
1978        cx: &mut TestAppContext,
1979    ) {
1980        init_test(cx);
1981
1982        let fs = FakeFs::new(cx.background());
1983        fs.insert_tree(
1984            "/dir",
1985            json!({
1986                "a": {
1987                    "one.rs": "const ONE: usize = 1;",
1988                    "two.rs": "const TWO: usize = one::ONE + one::ONE;",
1989                },
1990                "b": {
1991                    "three.rs": "const THREE: usize = one::ONE + two::TWO;",
1992                    "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
1993                },
1994            }),
1995        )
1996        .await;
1997        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
1998        let worktree_id = project.read_with(cx, |project, cx| {
1999            project.worktrees(cx).next().unwrap().read(cx).id()
2000        });
2001        let workspace = cx
2002            .add_window(|cx| Workspace::test_new(project, cx))
2003            .root(cx);
2004
2005        let active_item = cx.read(|cx| {
2006            workspace
2007                .read(cx)
2008                .active_pane()
2009                .read(cx)
2010                .active_item()
2011                .and_then(|item| item.downcast::<ProjectSearchView>())
2012        });
2013        assert!(
2014            active_item.is_none(),
2015            "Expected no search panel to be active, but got: {active_item:?}"
2016        );
2017
2018        let one_file_entry = cx.update(|cx| {
2019            workspace
2020                .read(cx)
2021                .project()
2022                .read(cx)
2023                .entry_for_path(&(worktree_id, "a/one.rs").into(), cx)
2024                .expect("no entry for /a/one.rs file")
2025        });
2026        assert!(one_file_entry.is_file());
2027        workspace.update(cx, |workspace, cx| {
2028            ProjectSearchView::new_search_in_directory(workspace, &one_file_entry, cx)
2029        });
2030        let active_search_entry = cx.read(|cx| {
2031            workspace
2032                .read(cx)
2033                .active_pane()
2034                .read(cx)
2035                .active_item()
2036                .and_then(|item| item.downcast::<ProjectSearchView>())
2037        });
2038        assert!(
2039            active_search_entry.is_none(),
2040            "Expected no search panel to be active for file entry"
2041        );
2042
2043        let a_dir_entry = cx.update(|cx| {
2044            workspace
2045                .read(cx)
2046                .project()
2047                .read(cx)
2048                .entry_for_path(&(worktree_id, "a").into(), cx)
2049                .expect("no entry for /a/ directory")
2050        });
2051        assert!(a_dir_entry.is_dir());
2052        workspace.update(cx, |workspace, cx| {
2053            ProjectSearchView::new_search_in_directory(workspace, &a_dir_entry, cx)
2054        });
2055
2056        let Some(search_view) = cx.read(|cx| {
2057            workspace
2058                .read(cx)
2059                .active_pane()
2060                .read(cx)
2061                .active_item()
2062                .and_then(|item| item.downcast::<ProjectSearchView>())
2063        }) else {
2064            panic!("Search view expected to appear after new search in directory event trigger")
2065        };
2066        deterministic.run_until_parked();
2067        search_view.update(cx, |search_view, cx| {
2068            assert!(
2069                search_view.query_editor.is_focused(cx),
2070                "On new search in directory, focus should be moved into query editor"
2071            );
2072            search_view.excluded_files_editor.update(cx, |editor, cx| {
2073                assert!(
2074                    editor.display_text(cx).is_empty(),
2075                    "New search in directory should not have any excluded files"
2076                );
2077            });
2078            search_view.included_files_editor.update(cx, |editor, cx| {
2079                assert_eq!(
2080                    editor.display_text(cx),
2081                    a_dir_entry.path.to_str().unwrap(),
2082                    "New search in directory should have included dir entry path"
2083                );
2084            });
2085        });
2086
2087        search_view.update(cx, |search_view, cx| {
2088            search_view
2089                .query_editor
2090                .update(cx, |query_editor, cx| query_editor.set_text("const", cx));
2091            search_view.search(cx);
2092        });
2093        deterministic.run_until_parked();
2094        search_view.update(cx, |search_view, cx| {
2095            assert_eq!(
2096                search_view
2097                    .results_editor
2098                    .update(cx, |editor, cx| editor.display_text(cx)),
2099                "\n\nconst ONE: usize = 1;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
2100                "New search in directory should have a filter that matches a certain directory"
2101            );
2102        });
2103    }
2104
2105    #[gpui::test]
2106    async fn test_search_query_history(cx: &mut TestAppContext) {
2107        init_test(cx);
2108
2109        let fs = FakeFs::new(cx.background());
2110        fs.insert_tree(
2111            "/dir",
2112            json!({
2113                "one.rs": "const ONE: usize = 1;",
2114                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2115                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2116                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2117            }),
2118        )
2119        .await;
2120        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
2121        let window = cx.add_window(|cx| Workspace::test_new(project, cx));
2122        let workspace = window.root(cx);
2123        workspace.update(cx, |workspace, cx| {
2124            ProjectSearchView::deploy(workspace, &workspace::NewSearch, cx)
2125        });
2126
2127        let search_view = cx.read(|cx| {
2128            workspace
2129                .read(cx)
2130                .active_pane()
2131                .read(cx)
2132                .active_item()
2133                .and_then(|item| item.downcast::<ProjectSearchView>())
2134                .expect("Search view expected to appear after new search event trigger")
2135        });
2136
2137        let search_bar = window.add_view(cx, |cx| {
2138            let mut search_bar = ProjectSearchBar::new();
2139            search_bar.set_active_pane_item(Some(&search_view), cx);
2140            // search_bar.show(cx);
2141            search_bar
2142        });
2143
2144        // Add 3 search items into the history + another unsubmitted one.
2145        search_view.update(cx, |search_view, cx| {
2146            search_view.search_options = SearchOptions::CASE_SENSITIVE;
2147            search_view
2148                .query_editor
2149                .update(cx, |query_editor, cx| query_editor.set_text("ONE", cx));
2150            search_view.search(cx);
2151        });
2152        cx.foreground().run_until_parked();
2153        search_view.update(cx, |search_view, cx| {
2154            search_view
2155                .query_editor
2156                .update(cx, |query_editor, cx| query_editor.set_text("TWO", cx));
2157            search_view.search(cx);
2158        });
2159        cx.foreground().run_until_parked();
2160        search_view.update(cx, |search_view, cx| {
2161            search_view
2162                .query_editor
2163                .update(cx, |query_editor, cx| query_editor.set_text("THREE", cx));
2164            search_view.search(cx);
2165        });
2166        cx.foreground().run_until_parked();
2167        search_view.update(cx, |search_view, cx| {
2168            search_view.query_editor.update(cx, |query_editor, cx| {
2169                query_editor.set_text("JUST_TEXT_INPUT", cx)
2170            });
2171        });
2172        cx.foreground().run_until_parked();
2173
2174        // Ensure that the latest input with search settings is active.
2175        search_view.update(cx, |search_view, cx| {
2176            assert_eq!(
2177                search_view.query_editor.read(cx).text(cx),
2178                "JUST_TEXT_INPUT"
2179            );
2180            assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2181        });
2182
2183        // Next history query after the latest should set the query to the empty string.
2184        search_bar.update(cx, |search_bar, cx| {
2185            search_bar.next_history_query(&NextHistoryQuery, cx);
2186        });
2187        search_view.update(cx, |search_view, cx| {
2188            assert_eq!(search_view.query_editor.read(cx).text(cx), "");
2189            assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2190        });
2191        search_bar.update(cx, |search_bar, cx| {
2192            search_bar.next_history_query(&NextHistoryQuery, cx);
2193        });
2194        search_view.update(cx, |search_view, cx| {
2195            assert_eq!(search_view.query_editor.read(cx).text(cx), "");
2196            assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2197        });
2198
2199        // First previous query for empty current query should set the query to the latest submitted one.
2200        search_bar.update(cx, |search_bar, cx| {
2201            search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2202        });
2203        search_view.update(cx, |search_view, cx| {
2204            assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
2205            assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2206        });
2207
2208        // Further previous items should go over the history in reverse order.
2209        search_bar.update(cx, |search_bar, cx| {
2210            search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2211        });
2212        search_view.update(cx, |search_view, cx| {
2213            assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
2214            assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2215        });
2216
2217        // Previous items should never go behind the first history item.
2218        search_bar.update(cx, |search_bar, cx| {
2219            search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2220        });
2221        search_view.update(cx, |search_view, cx| {
2222            assert_eq!(search_view.query_editor.read(cx).text(cx), "ONE");
2223            assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2224        });
2225        search_bar.update(cx, |search_bar, cx| {
2226            search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2227        });
2228        search_view.update(cx, |search_view, cx| {
2229            assert_eq!(search_view.query_editor.read(cx).text(cx), "ONE");
2230            assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2231        });
2232
2233        // Next items should go over the history in the original order.
2234        search_bar.update(cx, |search_bar, cx| {
2235            search_bar.next_history_query(&NextHistoryQuery, cx);
2236        });
2237        search_view.update(cx, |search_view, cx| {
2238            assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
2239            assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2240        });
2241
2242        search_view.update(cx, |search_view, cx| {
2243            search_view
2244                .query_editor
2245                .update(cx, |query_editor, cx| query_editor.set_text("TWO_NEW", cx));
2246            search_view.search(cx);
2247        });
2248        cx.foreground().run_until_parked();
2249        search_view.update(cx, |search_view, cx| {
2250            assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO_NEW");
2251            assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2252        });
2253
2254        // New search input should add another entry to history and move the selection to the end of the history.
2255        search_bar.update(cx, |search_bar, cx| {
2256            search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2257        });
2258        search_view.update(cx, |search_view, cx| {
2259            assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
2260            assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2261        });
2262        search_bar.update(cx, |search_bar, cx| {
2263            search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2264        });
2265        search_view.update(cx, |search_view, cx| {
2266            assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
2267            assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2268        });
2269        search_bar.update(cx, |search_bar, cx| {
2270            search_bar.next_history_query(&NextHistoryQuery, cx);
2271        });
2272        search_view.update(cx, |search_view, cx| {
2273            assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
2274            assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2275        });
2276        search_bar.update(cx, |search_bar, cx| {
2277            search_bar.next_history_query(&NextHistoryQuery, cx);
2278        });
2279        search_view.update(cx, |search_view, cx| {
2280            assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO_NEW");
2281            assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2282        });
2283        search_bar.update(cx, |search_bar, cx| {
2284            search_bar.next_history_query(&NextHistoryQuery, cx);
2285        });
2286        search_view.update(cx, |search_view, cx| {
2287            assert_eq!(search_view.query_editor.read(cx).text(cx), "");
2288            assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2289        });
2290    }
2291
2292    pub fn init_test(cx: &mut TestAppContext) {
2293        cx.foreground().forbid_parking();
2294        let fonts = cx.font_cache();
2295        let mut theme = gpui::fonts::with_font_cache(fonts.clone(), theme::Theme::default);
2296        theme.search.match_background = Color::red();
2297
2298        cx.update(|cx| {
2299            cx.set_global(SettingsStore::test(cx));
2300            cx.set_global(ActiveSearches::default());
2301            settings::register::<SemanticIndexSettings>(cx);
2302
2303            theme::init((), cx);
2304            cx.update_global::<SettingsStore, _, _>(|store, _| {
2305                let mut settings = store.get::<ThemeSettings>(None).clone();
2306                settings.theme = Arc::new(theme);
2307                store.override_global(settings)
2308            });
2309
2310            language::init(cx);
2311            client::init_settings(cx);
2312            editor::init(cx);
2313            workspace::init_settings(cx);
2314            Project::init_settings(cx);
2315            super::init(cx);
2316        });
2317    }
2318}