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 matches = search.await.log_err()?;
 189            let this = this.upgrade(&cx)?;
 190            let mut matches = matches.into_iter().collect::<Vec<_>>();
 191            let (_task, mut match_ranges) = this.update(&mut cx, |this, cx| {
 192                this.match_ranges.clear();
 193                this.no_results = Some(true);
 194                matches.sort_by_key(|(buffer, _)| buffer.read(cx).file().map(|file| file.path()));
 195                this.excerpts.update(cx, |excerpts, cx| {
 196                    excerpts.clear(cx);
 197                    excerpts.stream_excerpts_with_context_lines(matches, 1, cx)
 198                })
 199            });
 200
 201            while let Some(match_range) = match_ranges.next().await {
 202                this.update(&mut cx, |this, cx| {
 203                    this.match_ranges.push(match_range);
 204                    while let Ok(Some(match_range)) = match_ranges.try_next() {
 205                        this.match_ranges.push(match_range);
 206                    }
 207                    this.no_results = Some(false);
 208                    cx.notify();
 209                });
 210            }
 211
 212            this.update(&mut cx, |this, cx| {
 213                this.pending_search.take();
 214                cx.notify();
 215            });
 216
 217            None
 218        }));
 219        cx.notify();
 220    }
 221
 222    fn semantic_search(&mut self, inputs: &SearchInputs, cx: &mut ModelContext<Self>) {
 223        let search = SemanticIndex::global(cx).map(|index| {
 224            index.update(cx, |semantic_index, cx| {
 225                semantic_index.search_project(
 226                    self.project.clone(),
 227                    inputs.as_str().to_owned(),
 228                    10,
 229                    inputs.files_to_include().to_vec(),
 230                    inputs.files_to_exclude().to_vec(),
 231                    cx,
 232                )
 233            })
 234        });
 235        self.search_id += 1;
 236        self.match_ranges.clear();
 237        self.search_history.add(inputs.as_str().to_string());
 238        self.no_results = Some(true);
 239        self.pending_search = Some(cx.spawn(|this, mut cx| async move {
 240            let results = search?.await.log_err()?;
 241
 242            let (_task, mut match_ranges) = this.update(&mut cx, |this, cx| {
 243                this.excerpts.update(cx, |excerpts, cx| {
 244                    excerpts.clear(cx);
 245
 246                    let matches = results
 247                        .into_iter()
 248                        .map(|result| (result.buffer, vec![result.range.start..result.range.start]))
 249                        .collect();
 250
 251                    excerpts.stream_excerpts_with_context_lines(matches, 3, cx)
 252                })
 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                    this.no_results = Some(false);
 262                    cx.notify();
 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 { return; };
 889
 890        let model = cx.add_model(|cx| ProjectSearch::new(workspace.project().clone(), cx));
 891        let search = cx.add_view(|cx| ProjectSearchView::new(model, cx));
 892        workspace.add_item(Box::new(search.clone()), cx);
 893        search.update(cx, |search, cx| {
 894            search
 895                .included_files_editor
 896                .update(cx, |editor, cx| editor.set_text(filter_str, cx));
 897            search.filters_enabled = true;
 898            search.focus_query_editor(cx)
 899        });
 900    }
 901
 902    // Re-activate the most recently activated search or the most recent if it has been closed.
 903    // If no search exists in the workspace, create a new one.
 904    fn deploy(
 905        workspace: &mut Workspace,
 906        _: &workspace::NewSearch,
 907        cx: &mut ViewContext<Workspace>,
 908    ) {
 909        // Clean up entries for dropped projects
 910        cx.update_global(|state: &mut ActiveSearches, cx| {
 911            state.0.retain(|project, _| project.is_upgradable(cx))
 912        });
 913
 914        let active_search = cx
 915            .global::<ActiveSearches>()
 916            .0
 917            .get(&workspace.project().downgrade());
 918
 919        let existing = active_search
 920            .and_then(|active_search| {
 921                workspace
 922                    .items_of_type::<ProjectSearchView>(cx)
 923                    .find(|search| search == active_search)
 924            })
 925            .or_else(|| workspace.item_of_type::<ProjectSearchView>(cx));
 926
 927        let query = workspace.active_item(cx).and_then(|item| {
 928            let editor = item.act_as::<Editor>(cx)?;
 929            let query = editor.query_suggestion(cx);
 930            if query.is_empty() {
 931                None
 932            } else {
 933                Some(query)
 934            }
 935        });
 936
 937        let search = if let Some(existing) = existing {
 938            workspace.activate_item(&existing, cx);
 939            existing
 940        } else {
 941            let model = cx.add_model(|cx| ProjectSearch::new(workspace.project().clone(), cx));
 942            let view = cx.add_view(|cx| ProjectSearchView::new(model, cx));
 943            workspace.add_item(Box::new(view.clone()), cx);
 944            view
 945        };
 946
 947        search.update(cx, |search, cx| {
 948            if let Some(query) = query {
 949                search.set_query(&query, cx);
 950            }
 951            search.focus_query_editor(cx)
 952        });
 953    }
 954
 955    fn search(&mut self, cx: &mut ViewContext<Self>) {
 956        let mode = self.current_mode;
 957        match mode {
 958            SearchMode::Semantic => {
 959                if let Some(semantic) = &mut self.semantic_state {
 960                    if semantic.outstanding_file_count > 0 {
 961                        return;
 962                    }
 963
 964                    if let Some(query) = self.build_search_query(cx) {
 965                        self.model
 966                            .update(cx, |model, cx| model.semantic_search(query.as_inner(), cx));
 967                    }
 968                }
 969            }
 970
 971            _ => {
 972                if let Some(query) = self.build_search_query(cx) {
 973                    self.model.update(cx, |model, cx| model.search(query, cx));
 974                }
 975            }
 976        }
 977    }
 978
 979    fn build_search_query(&mut self, cx: &mut ViewContext<Self>) -> Option<SearchQuery> {
 980        let text = self.query_editor.read(cx).text(cx);
 981        let included_files =
 982            match Self::parse_path_matches(&self.included_files_editor.read(cx).text(cx)) {
 983                Ok(included_files) => {
 984                    self.panels_with_errors.remove(&InputPanel::Include);
 985                    included_files
 986                }
 987                Err(_e) => {
 988                    self.panels_with_errors.insert(InputPanel::Include);
 989                    cx.notify();
 990                    return None;
 991                }
 992            };
 993        let excluded_files =
 994            match Self::parse_path_matches(&self.excluded_files_editor.read(cx).text(cx)) {
 995                Ok(excluded_files) => {
 996                    self.panels_with_errors.remove(&InputPanel::Exclude);
 997                    excluded_files
 998                }
 999                Err(_e) => {
1000                    self.panels_with_errors.insert(InputPanel::Exclude);
1001                    cx.notify();
1002                    return None;
1003                }
1004            };
1005        let current_mode = self.current_mode;
1006        match current_mode {
1007            SearchMode::Regex => {
1008                match SearchQuery::regex(
1009                    text,
1010                    self.search_options.contains(SearchOptions::WHOLE_WORD),
1011                    self.search_options.contains(SearchOptions::CASE_SENSITIVE),
1012                    included_files,
1013                    excluded_files,
1014                ) {
1015                    Ok(query) => {
1016                        self.panels_with_errors.remove(&InputPanel::Query);
1017                        Some(query)
1018                    }
1019                    Err(_e) => {
1020                        self.panels_with_errors.insert(InputPanel::Query);
1021                        cx.notify();
1022                        None
1023                    }
1024                }
1025            }
1026            _ => Some(SearchQuery::text(
1027                text,
1028                self.search_options.contains(SearchOptions::WHOLE_WORD),
1029                self.search_options.contains(SearchOptions::CASE_SENSITIVE),
1030                included_files,
1031                excluded_files,
1032            )),
1033        }
1034    }
1035
1036    fn parse_path_matches(text: &str) -> anyhow::Result<Vec<PathMatcher>> {
1037        text.split(',')
1038            .map(str::trim)
1039            .filter(|maybe_glob_str| !maybe_glob_str.is_empty())
1040            .map(|maybe_glob_str| {
1041                PathMatcher::new(maybe_glob_str)
1042                    .with_context(|| format!("parsing {maybe_glob_str} as path matcher"))
1043            })
1044            .collect()
1045    }
1046
1047    fn select_match(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
1048        if let Some(index) = self.active_match_index {
1049            let match_ranges = self.model.read(cx).match_ranges.clone();
1050            let new_index = self.results_editor.update(cx, |editor, cx| {
1051                editor.match_index_for_direction(&match_ranges, index, direction, 1, cx)
1052            });
1053
1054            let range_to_select = match_ranges[new_index].clone();
1055            self.results_editor.update(cx, |editor, cx| {
1056                let range_to_select = editor.range_for_match(&range_to_select);
1057                editor.unfold_ranges([range_to_select.clone()], false, true, cx);
1058                editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
1059                    s.select_ranges([range_to_select])
1060                });
1061            });
1062        }
1063    }
1064
1065    fn focus_query_editor(&mut self, cx: &mut ViewContext<Self>) {
1066        self.query_editor.update(cx, |query_editor, cx| {
1067            query_editor.select_all(&SelectAll, cx);
1068        });
1069        self.query_editor_was_focused = true;
1070        cx.focus(&self.query_editor);
1071    }
1072
1073    fn set_query(&mut self, query: &str, cx: &mut ViewContext<Self>) {
1074        self.query_editor
1075            .update(cx, |query_editor, cx| query_editor.set_text(query, cx));
1076    }
1077
1078    fn focus_results_editor(&mut self, cx: &mut ViewContext<Self>) {
1079        self.query_editor.update(cx, |query_editor, cx| {
1080            let cursor = query_editor.selections.newest_anchor().head();
1081            query_editor.change_selections(None, cx, |s| s.select_ranges([cursor.clone()..cursor]));
1082        });
1083        self.query_editor_was_focused = false;
1084        cx.focus(&self.results_editor);
1085    }
1086
1087    fn model_changed(&mut self, cx: &mut ViewContext<Self>) {
1088        let match_ranges = self.model.read(cx).match_ranges.clone();
1089        if match_ranges.is_empty() {
1090            self.active_match_index = None;
1091        } else {
1092            self.active_match_index = Some(0);
1093            self.update_match_index(cx);
1094            let prev_search_id = mem::replace(&mut self.search_id, self.model.read(cx).search_id);
1095            let is_new_search = self.search_id != prev_search_id;
1096            self.results_editor.update(cx, |editor, cx| {
1097                if is_new_search {
1098                    let range_to_select = match_ranges
1099                        .first()
1100                        .clone()
1101                        .map(|range| editor.range_for_match(range));
1102                    editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
1103                        s.select_ranges(range_to_select)
1104                    });
1105                }
1106                editor.highlight_background::<Self>(
1107                    match_ranges,
1108                    |theme| theme.search.match_background,
1109                    cx,
1110                );
1111            });
1112            if is_new_search && self.query_editor.is_focused(cx) {
1113                self.focus_results_editor(cx);
1114            }
1115        }
1116
1117        cx.emit(ViewEvent::UpdateTab);
1118        cx.notify();
1119    }
1120
1121    fn update_match_index(&mut self, cx: &mut ViewContext<Self>) {
1122        let results_editor = self.results_editor.read(cx);
1123        let new_index = active_match_index(
1124            &self.model.read(cx).match_ranges,
1125            &results_editor.selections.newest_anchor().head(),
1126            &results_editor.buffer().read(cx).snapshot(cx),
1127        );
1128        if self.active_match_index != new_index {
1129            self.active_match_index = new_index;
1130            cx.notify();
1131        }
1132    }
1133
1134    pub fn has_matches(&self) -> bool {
1135        self.active_match_index.is_some()
1136    }
1137
1138    fn move_focus_to_results(pane: &mut Pane, _: &ToggleFocus, cx: &mut ViewContext<Pane>) {
1139        if let Some(search_view) = pane
1140            .active_item()
1141            .and_then(|item| item.downcast::<ProjectSearchView>())
1142        {
1143            search_view.update(cx, |search_view, cx| {
1144                if !search_view.results_editor.is_focused(cx)
1145                    && !search_view.model.read(cx).match_ranges.is_empty()
1146                {
1147                    return search_view.focus_results_editor(cx);
1148                }
1149            });
1150        }
1151
1152        cx.propagate_action();
1153    }
1154}
1155
1156impl Default for ProjectSearchBar {
1157    fn default() -> Self {
1158        Self::new()
1159    }
1160}
1161
1162impl ProjectSearchBar {
1163    pub fn new() -> Self {
1164        Self {
1165            active_project_search: Default::default(),
1166            subscription: Default::default(),
1167        }
1168    }
1169    fn cycle_mode(workspace: &mut Workspace, _: &CycleMode, cx: &mut ViewContext<Workspace>) {
1170        if let Some(search_view) = workspace
1171            .active_item(cx)
1172            .and_then(|item| item.downcast::<ProjectSearchView>())
1173        {
1174            search_view.update(cx, |this, cx| {
1175                let new_mode =
1176                    crate::mode::next_mode(&this.current_mode, SemanticIndex::enabled(cx));
1177                this.activate_search_mode(new_mode, cx);
1178                cx.focus(&this.query_editor);
1179            })
1180        }
1181    }
1182    fn search(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
1183        if let Some(search_view) = self.active_project_search.as_ref() {
1184            search_view.update(cx, |search_view, cx| search_view.search(cx));
1185        }
1186    }
1187
1188    fn search_in_new(workspace: &mut Workspace, _: &SearchInNew, cx: &mut ViewContext<Workspace>) {
1189        if let Some(search_view) = workspace
1190            .active_item(cx)
1191            .and_then(|item| item.downcast::<ProjectSearchView>())
1192        {
1193            let new_query = search_view.update(cx, |search_view, cx| {
1194                let new_query = search_view.build_search_query(cx);
1195                if new_query.is_some() {
1196                    if let Some(old_query) = search_view.model.read(cx).active_query.clone() {
1197                        search_view.query_editor.update(cx, |editor, cx| {
1198                            editor.set_text(old_query.as_str(), cx);
1199                        });
1200                        search_view.search_options = SearchOptions::from_query(&old_query);
1201                    }
1202                }
1203                new_query
1204            });
1205            if let Some(new_query) = new_query {
1206                let model = cx.add_model(|cx| {
1207                    let mut model = ProjectSearch::new(workspace.project().clone(), cx);
1208                    model.search(new_query, cx);
1209                    model
1210                });
1211                workspace.add_item(
1212                    Box::new(cx.add_view(|cx| ProjectSearchView::new(model, cx))),
1213                    cx,
1214                );
1215            }
1216        }
1217    }
1218
1219    fn select_next_match(pane: &mut Pane, _: &SelectNextMatch, cx: &mut ViewContext<Pane>) {
1220        if let Some(search_view) = pane
1221            .active_item()
1222            .and_then(|item| item.downcast::<ProjectSearchView>())
1223        {
1224            search_view.update(cx, |view, cx| view.select_match(Direction::Next, cx));
1225        } else {
1226            cx.propagate_action();
1227        }
1228    }
1229
1230    fn select_prev_match(pane: &mut Pane, _: &SelectPrevMatch, cx: &mut ViewContext<Pane>) {
1231        if let Some(search_view) = pane
1232            .active_item()
1233            .and_then(|item| item.downcast::<ProjectSearchView>())
1234        {
1235            search_view.update(cx, |view, cx| view.select_match(Direction::Prev, cx));
1236        } else {
1237            cx.propagate_action();
1238        }
1239    }
1240
1241    fn tab(&mut self, _: &editor::Tab, cx: &mut ViewContext<Self>) {
1242        self.cycle_field(Direction::Next, cx);
1243    }
1244
1245    fn tab_previous(&mut self, _: &editor::TabPrev, cx: &mut ViewContext<Self>) {
1246        self.cycle_field(Direction::Prev, cx);
1247    }
1248
1249    fn cycle_field(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
1250        let active_project_search = match &self.active_project_search {
1251            Some(active_project_search) => active_project_search,
1252
1253            None => {
1254                cx.propagate_action();
1255                return;
1256            }
1257        };
1258
1259        active_project_search.update(cx, |project_view, cx| {
1260            let views = &[
1261                &project_view.query_editor,
1262                &project_view.included_files_editor,
1263                &project_view.excluded_files_editor,
1264            ];
1265
1266            let current_index = match views
1267                .iter()
1268                .enumerate()
1269                .find(|(_, view)| view.is_focused(cx))
1270            {
1271                Some((index, _)) => index,
1272
1273                None => {
1274                    cx.propagate_action();
1275                    return;
1276                }
1277            };
1278
1279            let new_index = match direction {
1280                Direction::Next => (current_index + 1) % views.len(),
1281                Direction::Prev if current_index == 0 => views.len() - 1,
1282                Direction::Prev => (current_index - 1) % views.len(),
1283            };
1284            cx.focus(views[new_index]);
1285        });
1286    }
1287
1288    fn toggle_search_option(&mut self, option: SearchOptions, cx: &mut ViewContext<Self>) -> bool {
1289        if let Some(search_view) = self.active_project_search.as_ref() {
1290            search_view.update(cx, |search_view, cx| {
1291                search_view.toggle_search_option(option);
1292                search_view.search(cx);
1293            });
1294            cx.notify();
1295            true
1296        } else {
1297            false
1298        }
1299    }
1300
1301    fn activate_regex_mode(pane: &mut Pane, _: &ActivateRegexMode, cx: &mut ViewContext<Pane>) {
1302        if let Some(search_view) = pane
1303            .active_item()
1304            .and_then(|item| item.downcast::<ProjectSearchView>())
1305        {
1306            search_view.update(cx, |view, cx| {
1307                view.activate_search_mode(SearchMode::Regex, cx)
1308            });
1309        } else {
1310            cx.propagate_action();
1311        }
1312    }
1313
1314    fn toggle_filters(&mut self, cx: &mut ViewContext<Self>) -> bool {
1315        if let Some(search_view) = self.active_project_search.as_ref() {
1316            search_view.update(cx, |search_view, cx| {
1317                search_view.filters_enabled = !search_view.filters_enabled;
1318                search_view
1319                    .included_files_editor
1320                    .update(cx, |_, cx| cx.notify());
1321                search_view
1322                    .excluded_files_editor
1323                    .update(cx, |_, cx| cx.notify());
1324                cx.refresh_windows();
1325                cx.notify();
1326            });
1327            cx.notify();
1328            true
1329        } else {
1330            false
1331        }
1332    }
1333
1334    fn activate_search_mode(&self, mode: SearchMode, cx: &mut ViewContext<Self>) {
1335        // Update Current Mode
1336        if let Some(search_view) = self.active_project_search.as_ref() {
1337            search_view.update(cx, |search_view, cx| {
1338                search_view.activate_search_mode(mode, cx);
1339            });
1340            cx.notify();
1341        }
1342    }
1343
1344    fn is_option_enabled(&self, option: SearchOptions, cx: &AppContext) -> bool {
1345        if let Some(search) = self.active_project_search.as_ref() {
1346            search.read(cx).search_options.contains(option)
1347        } else {
1348            false
1349        }
1350    }
1351
1352    fn next_history_query(&mut self, _: &NextHistoryQuery, cx: &mut ViewContext<Self>) {
1353        if let Some(search_view) = self.active_project_search.as_ref() {
1354            search_view.update(cx, |search_view, cx| {
1355                let new_query = search_view.model.update(cx, |model, _| {
1356                    if let Some(new_query) = model.search_history.next().map(str::to_string) {
1357                        new_query
1358                    } else {
1359                        model.search_history.reset_selection();
1360                        String::new()
1361                    }
1362                });
1363                search_view.set_query(&new_query, cx);
1364            });
1365        }
1366    }
1367
1368    fn previous_history_query(&mut self, _: &PreviousHistoryQuery, cx: &mut ViewContext<Self>) {
1369        if let Some(search_view) = self.active_project_search.as_ref() {
1370            search_view.update(cx, |search_view, cx| {
1371                if search_view.query_editor.read(cx).text(cx).is_empty() {
1372                    if let Some(new_query) = search_view
1373                        .model
1374                        .read(cx)
1375                        .search_history
1376                        .current()
1377                        .map(str::to_string)
1378                    {
1379                        search_view.set_query(&new_query, cx);
1380                        return;
1381                    }
1382                }
1383
1384                if let Some(new_query) = search_view.model.update(cx, |model, _| {
1385                    model.search_history.previous().map(str::to_string)
1386                }) {
1387                    search_view.set_query(&new_query, cx);
1388                }
1389            });
1390        }
1391    }
1392}
1393
1394impl Entity for ProjectSearchBar {
1395    type Event = ();
1396}
1397
1398impl View for ProjectSearchBar {
1399    fn ui_name() -> &'static str {
1400        "ProjectSearchBar"
1401    }
1402
1403    fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
1404        if let Some(_search) = self.active_project_search.as_ref() {
1405            let search = _search.read(cx);
1406            let theme = theme::current(cx).clone();
1407            let query_container_style = if search.panels_with_errors.contains(&InputPanel::Query) {
1408                theme.search.invalid_editor
1409            } else {
1410                theme.search.editor.input.container
1411            };
1412
1413            let search = _search.read(cx);
1414            let filter_button = render_option_button_icon(
1415                search.filters_enabled,
1416                "icons/filter_12.svg",
1417                0,
1418                "Toggle filters",
1419                Box::new(ToggleFilters),
1420                move |_, this, cx| {
1421                    this.toggle_filters(cx);
1422                },
1423                cx,
1424            );
1425            let search = _search.read(cx);
1426            let is_semantic_disabled = search.semantic_state.is_none();
1427            let render_option_button_icon = |path, option, cx: &mut ViewContext<Self>| {
1428                crate::search_bar::render_option_button_icon(
1429                    self.is_option_enabled(option, cx),
1430                    path,
1431                    option.bits as usize,
1432                    format!("Toggle {}", option.label()),
1433                    option.to_toggle_action(),
1434                    move |_, this, cx| {
1435                        this.toggle_search_option(option, cx);
1436                    },
1437                    cx,
1438                )
1439            };
1440            let case_sensitive = is_semantic_disabled.then(|| {
1441                render_option_button_icon(
1442                    "icons/case_insensitive_12.svg",
1443                    SearchOptions::CASE_SENSITIVE,
1444                    cx,
1445                )
1446            });
1447
1448            let whole_word = is_semantic_disabled.then(|| {
1449                render_option_button_icon("icons/word_search_12.svg", SearchOptions::WHOLE_WORD, cx)
1450            });
1451
1452            let search = _search.read(cx);
1453            let icon_style = theme.search.editor_icon.clone();
1454
1455            // Editor Functionality
1456            let query = Flex::row()
1457                .with_child(
1458                    Svg::for_style(icon_style.icon)
1459                        .contained()
1460                        .with_style(icon_style.container),
1461                )
1462                .with_child(ChildView::new(&search.query_editor, cx).flex(1., true))
1463                .with_child(
1464                    Flex::row()
1465                        .with_child(filter_button)
1466                        .with_children(case_sensitive)
1467                        .with_children(whole_word)
1468                        .flex(1., false)
1469                        .constrained()
1470                        .contained(),
1471                )
1472                .align_children_center()
1473                .flex(1., true);
1474
1475            let search = _search.read(cx);
1476
1477            let include_container_style =
1478                if search.panels_with_errors.contains(&InputPanel::Include) {
1479                    theme.search.invalid_include_exclude_editor
1480                } else {
1481                    theme.search.include_exclude_editor.input.container
1482                };
1483
1484            let exclude_container_style =
1485                if search.panels_with_errors.contains(&InputPanel::Exclude) {
1486                    theme.search.invalid_include_exclude_editor
1487                } else {
1488                    theme.search.include_exclude_editor.input.container
1489                };
1490
1491            let included_files_view = ChildView::new(&search.included_files_editor, cx)
1492                .contained()
1493                .flex(1., true);
1494            let excluded_files_view = ChildView::new(&search.excluded_files_editor, cx)
1495                .contained()
1496                .flex(1., true);
1497            let filters = search.filters_enabled.then(|| {
1498                Flex::row()
1499                    .with_child(
1500                        included_files_view
1501                            .contained()
1502                            .with_style(include_container_style)
1503                            .constrained()
1504                            .with_height(theme.search.search_bar_row_height)
1505                            .with_min_width(theme.search.include_exclude_editor.min_width)
1506                            .with_max_width(theme.search.include_exclude_editor.max_width),
1507                    )
1508                    .with_child(
1509                        excluded_files_view
1510                            .contained()
1511                            .with_style(exclude_container_style)
1512                            .constrained()
1513                            .with_height(theme.search.search_bar_row_height)
1514                            .with_min_width(theme.search.include_exclude_editor.min_width)
1515                            .with_max_width(theme.search.include_exclude_editor.max_width),
1516                    )
1517                    .contained()
1518                    .with_padding_top(theme.workspace.toolbar.container.padding.bottom)
1519            });
1520
1521            let editor_column = Flex::column()
1522                .with_child(
1523                    query
1524                        .contained()
1525                        .with_style(query_container_style)
1526                        .constrained()
1527                        .with_min_width(theme.search.editor.min_width)
1528                        .with_max_width(theme.search.editor.max_width)
1529                        .with_height(theme.search.search_bar_row_height)
1530                        .flex(1., false),
1531                )
1532                .with_children(filters)
1533                .flex(1., false);
1534
1535            let matches = search.active_match_index.map(|match_ix| {
1536                Label::new(
1537                    format!(
1538                        "{}/{}",
1539                        match_ix + 1,
1540                        search.model.read(cx).match_ranges.len()
1541                    ),
1542                    theme.search.match_index.text.clone(),
1543                )
1544                .contained()
1545                .with_style(theme.search.match_index.container)
1546                .aligned()
1547            });
1548
1549            let search_button_for_mode = |mode, cx: &mut ViewContext<ProjectSearchBar>| {
1550                let is_active = if let Some(search) = self.active_project_search.as_ref() {
1551                    let search = search.read(cx);
1552                    search.current_mode == mode
1553                } else {
1554                    false
1555                };
1556                render_search_mode_button(
1557                    mode,
1558                    is_active,
1559                    move |_, this, cx| {
1560                        this.activate_search_mode(mode, cx);
1561                    },
1562                    cx,
1563                )
1564            };
1565            let is_active = search.active_match_index.is_some();
1566            let semantic_index = SemanticIndex::enabled(cx)
1567                .then(|| search_button_for_mode(SearchMode::Semantic, cx));
1568            let nav_button_for_direction = |label, direction, cx: &mut ViewContext<Self>| {
1569                render_nav_button(
1570                    label,
1571                    direction,
1572                    is_active,
1573                    move |_, this, cx| {
1574                        if let Some(search) = this.active_project_search.as_ref() {
1575                            search.update(cx, |search, cx| search.select_match(direction, cx));
1576                        }
1577                    },
1578                    cx,
1579                )
1580            };
1581
1582            let nav_column = Flex::row()
1583                .with_child(nav_button_for_direction("<", Direction::Prev, cx))
1584                .with_child(nav_button_for_direction(">", Direction::Next, cx))
1585                .with_child(Flex::row().with_children(matches))
1586                .constrained()
1587                .with_height(theme.search.search_bar_row_height);
1588
1589            let mode_column = Flex::row()
1590                .with_child(
1591                    Flex::row()
1592                        .with_child(search_button_for_mode(SearchMode::Text, cx))
1593                        .with_children(semantic_index)
1594                        .with_child(search_button_for_mode(SearchMode::Regex, cx))
1595                        .contained()
1596                        .with_style(theme.search.modes_container),
1597                )
1598                .with_child(super::search_bar::render_close_button(
1599                    "Dismiss Project Search",
1600                    &theme.search,
1601                    cx,
1602                    |_, this, cx| {
1603                        if let Some(search) = this.active_project_search.as_mut() {
1604                            search.update(cx, |_, cx| cx.emit(ViewEvent::Dismiss))
1605                        }
1606                    },
1607                    None,
1608                ))
1609                .constrained()
1610                .with_height(theme.search.search_bar_row_height)
1611                .aligned()
1612                .right()
1613                .top()
1614                .flex_float();
1615
1616            Flex::row()
1617                .with_child(editor_column)
1618                .with_child(nav_column)
1619                .with_child(mode_column)
1620                .contained()
1621                .with_style(theme.search.container)
1622                .into_any_named("project search")
1623        } else {
1624            Empty::new().into_any()
1625        }
1626    }
1627}
1628
1629impl ToolbarItemView for ProjectSearchBar {
1630    fn set_active_pane_item(
1631        &mut self,
1632        active_pane_item: Option<&dyn ItemHandle>,
1633        cx: &mut ViewContext<Self>,
1634    ) -> ToolbarItemLocation {
1635        cx.notify();
1636        self.subscription = None;
1637        self.active_project_search = None;
1638        if let Some(search) = active_pane_item.and_then(|i| i.downcast::<ProjectSearchView>()) {
1639            search.update(cx, |search, cx| {
1640                if search.current_mode == SearchMode::Semantic {
1641                    search.index_project(cx);
1642                }
1643            });
1644
1645            self.subscription = Some(cx.observe(&search, |_, _, cx| cx.notify()));
1646            self.active_project_search = Some(search);
1647            ToolbarItemLocation::PrimaryLeft {
1648                flex: Some((1., false)),
1649            }
1650        } else {
1651            ToolbarItemLocation::Hidden
1652        }
1653    }
1654
1655    fn row_count(&self, cx: &ViewContext<Self>) -> usize {
1656        self.active_project_search
1657            .as_ref()
1658            .map(|search| {
1659                let offset = search.read(cx).filters_enabled as usize;
1660                2 + offset
1661            })
1662            .unwrap_or_else(|| 2)
1663    }
1664}
1665
1666#[cfg(test)]
1667pub mod tests {
1668    use super::*;
1669    use editor::DisplayPoint;
1670    use gpui::{color::Color, executor::Deterministic, TestAppContext};
1671    use project::FakeFs;
1672    use semantic_index::semantic_index_settings::SemanticIndexSettings;
1673    use serde_json::json;
1674    use settings::SettingsStore;
1675    use std::sync::Arc;
1676    use theme::ThemeSettings;
1677
1678    #[gpui::test]
1679    async fn test_project_search(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
1680        init_test(cx);
1681
1682        let fs = FakeFs::new(cx.background());
1683        fs.insert_tree(
1684            "/dir",
1685            json!({
1686                "one.rs": "const ONE: usize = 1;",
1687                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
1688                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
1689                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
1690            }),
1691        )
1692        .await;
1693        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
1694        let search = cx.add_model(|cx| ProjectSearch::new(project, cx));
1695        let search_view = cx
1696            .add_window(|cx| ProjectSearchView::new(search.clone(), cx))
1697            .root(cx);
1698
1699        search_view.update(cx, |search_view, cx| {
1700            search_view
1701                .query_editor
1702                .update(cx, |query_editor, cx| query_editor.set_text("TWO", cx));
1703            search_view.search(cx);
1704        });
1705        deterministic.run_until_parked();
1706        search_view.update(cx, |search_view, cx| {
1707            assert_eq!(
1708                search_view
1709                    .results_editor
1710                    .update(cx, |editor, cx| editor.display_text(cx)),
1711                "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;"
1712            );
1713            assert_eq!(
1714                search_view
1715                    .results_editor
1716                    .update(cx, |editor, cx| editor.all_background_highlights(cx)),
1717                &[
1718                    (
1719                        DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35),
1720                        Color::red()
1721                    ),
1722                    (
1723                        DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40),
1724                        Color::red()
1725                    ),
1726                    (
1727                        DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9),
1728                        Color::red()
1729                    )
1730                ]
1731            );
1732            assert_eq!(search_view.active_match_index, Some(0));
1733            assert_eq!(
1734                search_view
1735                    .results_editor
1736                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1737                [DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35)]
1738            );
1739
1740            search_view.select_match(Direction::Next, cx);
1741        });
1742
1743        search_view.update(cx, |search_view, cx| {
1744            assert_eq!(search_view.active_match_index, Some(1));
1745            assert_eq!(
1746                search_view
1747                    .results_editor
1748                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1749                [DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40)]
1750            );
1751            search_view.select_match(Direction::Next, cx);
1752        });
1753
1754        search_view.update(cx, |search_view, cx| {
1755            assert_eq!(search_view.active_match_index, Some(2));
1756            assert_eq!(
1757                search_view
1758                    .results_editor
1759                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1760                [DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9)]
1761            );
1762            search_view.select_match(Direction::Next, cx);
1763        });
1764
1765        search_view.update(cx, |search_view, cx| {
1766            assert_eq!(search_view.active_match_index, Some(0));
1767            assert_eq!(
1768                search_view
1769                    .results_editor
1770                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1771                [DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35)]
1772            );
1773            search_view.select_match(Direction::Prev, cx);
1774        });
1775
1776        search_view.update(cx, |search_view, cx| {
1777            assert_eq!(search_view.active_match_index, Some(2));
1778            assert_eq!(
1779                search_view
1780                    .results_editor
1781                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1782                [DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9)]
1783            );
1784            search_view.select_match(Direction::Prev, cx);
1785        });
1786
1787        search_view.update(cx, |search_view, cx| {
1788            assert_eq!(search_view.active_match_index, Some(1));
1789            assert_eq!(
1790                search_view
1791                    .results_editor
1792                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1793                [DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40)]
1794            );
1795        });
1796    }
1797
1798    #[gpui::test]
1799    async fn test_project_search_focus(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
1800        init_test(cx);
1801
1802        let fs = FakeFs::new(cx.background());
1803        fs.insert_tree(
1804            "/dir",
1805            json!({
1806                "one.rs": "const ONE: usize = 1;",
1807                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
1808                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
1809                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
1810            }),
1811        )
1812        .await;
1813        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
1814        let window = cx.add_window(|cx| Workspace::test_new(project, cx));
1815        let workspace = window.root(cx);
1816
1817        let active_item = cx.read(|cx| {
1818            workspace
1819                .read(cx)
1820                .active_pane()
1821                .read(cx)
1822                .active_item()
1823                .and_then(|item| item.downcast::<ProjectSearchView>())
1824        });
1825        assert!(
1826            active_item.is_none(),
1827            "Expected no search panel to be active, but got: {active_item:?}"
1828        );
1829
1830        workspace.update(cx, |workspace, cx| {
1831            ProjectSearchView::deploy(workspace, &workspace::NewSearch, cx)
1832        });
1833
1834        let Some(search_view) = cx.read(|cx| {
1835            workspace
1836                .read(cx)
1837                .active_pane()
1838                .read(cx)
1839                .active_item()
1840                .and_then(|item| item.downcast::<ProjectSearchView>())
1841        }) else {
1842            panic!("Search view expected to appear after new search event trigger")
1843        };
1844        let search_view_id = search_view.id();
1845
1846        cx.spawn(|mut cx| async move {
1847            window.dispatch_action(search_view_id, &ToggleFocus, &mut cx);
1848        })
1849        .detach();
1850        deterministic.run_until_parked();
1851        search_view.update(cx, |search_view, cx| {
1852            assert!(
1853                search_view.query_editor.is_focused(cx),
1854                "Empty search view should be focused after the toggle focus event: no results panel to focus on",
1855            );
1856        });
1857
1858        search_view.update(cx, |search_view, cx| {
1859            let query_editor = &search_view.query_editor;
1860            assert!(
1861                query_editor.is_focused(cx),
1862                "Search view should be focused after the new search view is activated",
1863            );
1864            let query_text = query_editor.read(cx).text(cx);
1865            assert!(
1866                query_text.is_empty(),
1867                "New search query should be empty but got '{query_text}'",
1868            );
1869            let results_text = search_view
1870                .results_editor
1871                .update(cx, |editor, cx| editor.display_text(cx));
1872            assert!(
1873                results_text.is_empty(),
1874                "Empty search view should have no results but got '{results_text}'"
1875            );
1876        });
1877
1878        search_view.update(cx, |search_view, cx| {
1879            search_view.query_editor.update(cx, |query_editor, cx| {
1880                query_editor.set_text("sOMETHINGtHATsURELYdOESnOTeXIST", cx)
1881            });
1882            search_view.search(cx);
1883        });
1884        deterministic.run_until_parked();
1885        search_view.update(cx, |search_view, cx| {
1886            let results_text = search_view
1887                .results_editor
1888                .update(cx, |editor, cx| editor.display_text(cx));
1889            assert!(
1890                results_text.is_empty(),
1891                "Search view for mismatching query should have no results but got '{results_text}'"
1892            );
1893            assert!(
1894                search_view.query_editor.is_focused(cx),
1895                "Search view should be focused after mismatching query had been used in search",
1896            );
1897        });
1898        cx.spawn(
1899            |mut cx| async move { window.dispatch_action(search_view_id, &ToggleFocus, &mut cx) },
1900        )
1901        .detach();
1902        deterministic.run_until_parked();
1903        search_view.update(cx, |search_view, cx| {
1904            assert!(
1905                search_view.query_editor.is_focused(cx),
1906                "Search view with mismatching query should be focused after the toggle focus event: still no results panel to focus on",
1907            );
1908        });
1909
1910        search_view.update(cx, |search_view, cx| {
1911            search_view
1912                .query_editor
1913                .update(cx, |query_editor, cx| query_editor.set_text("TWO", cx));
1914            search_view.search(cx);
1915        });
1916        deterministic.run_until_parked();
1917        search_view.update(cx, |search_view, cx| {
1918            assert_eq!(
1919                search_view
1920                    .results_editor
1921                    .update(cx, |editor, cx| editor.display_text(cx)),
1922                "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
1923                "Search view results should match the query"
1924            );
1925            assert!(
1926                search_view.results_editor.is_focused(cx),
1927                "Search view with mismatching query should be focused after search results are available",
1928            );
1929        });
1930        cx.spawn(|mut cx| async move {
1931            window.dispatch_action(search_view_id, &ToggleFocus, &mut cx);
1932        })
1933        .detach();
1934        deterministic.run_until_parked();
1935        search_view.update(cx, |search_view, cx| {
1936            assert!(
1937                search_view.results_editor.is_focused(cx),
1938                "Search view with matching query should still have its results editor focused after the toggle focus event",
1939            );
1940        });
1941
1942        workspace.update(cx, |workspace, cx| {
1943            ProjectSearchView::deploy(workspace, &workspace::NewSearch, cx)
1944        });
1945        search_view.update(cx, |search_view, cx| {
1946            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");
1947            assert_eq!(
1948                search_view
1949                    .results_editor
1950                    .update(cx, |editor, cx| editor.display_text(cx)),
1951                "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
1952                "Results should be unchanged after search view 2nd open in a row"
1953            );
1954            assert!(
1955                search_view.query_editor.is_focused(cx),
1956                "Focus should be moved into query editor again after search view 2nd open in a row"
1957            );
1958        });
1959
1960        cx.spawn(|mut cx| async move {
1961            window.dispatch_action(search_view_id, &ToggleFocus, &mut cx);
1962        })
1963        .detach();
1964        deterministic.run_until_parked();
1965        search_view.update(cx, |search_view, cx| {
1966            assert!(
1967                search_view.results_editor.is_focused(cx),
1968                "Search view with matching query should switch focus to the results editor after the toggle focus event",
1969            );
1970        });
1971    }
1972
1973    #[gpui::test]
1974    async fn test_new_project_search_in_directory(
1975        deterministic: Arc<Deterministic>,
1976        cx: &mut TestAppContext,
1977    ) {
1978        init_test(cx);
1979
1980        let fs = FakeFs::new(cx.background());
1981        fs.insert_tree(
1982            "/dir",
1983            json!({
1984                "a": {
1985                    "one.rs": "const ONE: usize = 1;",
1986                    "two.rs": "const TWO: usize = one::ONE + one::ONE;",
1987                },
1988                "b": {
1989                    "three.rs": "const THREE: usize = one::ONE + two::TWO;",
1990                    "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
1991                },
1992            }),
1993        )
1994        .await;
1995        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
1996        let worktree_id = project.read_with(cx, |project, cx| {
1997            project.worktrees(cx).next().unwrap().read(cx).id()
1998        });
1999        let workspace = cx
2000            .add_window(|cx| Workspace::test_new(project, cx))
2001            .root(cx);
2002
2003        let active_item = cx.read(|cx| {
2004            workspace
2005                .read(cx)
2006                .active_pane()
2007                .read(cx)
2008                .active_item()
2009                .and_then(|item| item.downcast::<ProjectSearchView>())
2010        });
2011        assert!(
2012            active_item.is_none(),
2013            "Expected no search panel to be active, but got: {active_item:?}"
2014        );
2015
2016        let one_file_entry = cx.update(|cx| {
2017            workspace
2018                .read(cx)
2019                .project()
2020                .read(cx)
2021                .entry_for_path(&(worktree_id, "a/one.rs").into(), cx)
2022                .expect("no entry for /a/one.rs file")
2023        });
2024        assert!(one_file_entry.is_file());
2025        workspace.update(cx, |workspace, cx| {
2026            ProjectSearchView::new_search_in_directory(workspace, &one_file_entry, cx)
2027        });
2028        let active_search_entry = cx.read(|cx| {
2029            workspace
2030                .read(cx)
2031                .active_pane()
2032                .read(cx)
2033                .active_item()
2034                .and_then(|item| item.downcast::<ProjectSearchView>())
2035        });
2036        assert!(
2037            active_search_entry.is_none(),
2038            "Expected no search panel to be active for file entry"
2039        );
2040
2041        let a_dir_entry = cx.update(|cx| {
2042            workspace
2043                .read(cx)
2044                .project()
2045                .read(cx)
2046                .entry_for_path(&(worktree_id, "a").into(), cx)
2047                .expect("no entry for /a/ directory")
2048        });
2049        assert!(a_dir_entry.is_dir());
2050        workspace.update(cx, |workspace, cx| {
2051            ProjectSearchView::new_search_in_directory(workspace, &a_dir_entry, cx)
2052        });
2053
2054        let Some(search_view) = cx.read(|cx| {
2055            workspace
2056                .read(cx)
2057                .active_pane()
2058                .read(cx)
2059                .active_item()
2060                .and_then(|item| item.downcast::<ProjectSearchView>())
2061        }) else {
2062            panic!("Search view expected to appear after new search in directory event trigger")
2063        };
2064        deterministic.run_until_parked();
2065        search_view.update(cx, |search_view, cx| {
2066            assert!(
2067                search_view.query_editor.is_focused(cx),
2068                "On new search in directory, focus should be moved into query editor"
2069            );
2070            search_view.excluded_files_editor.update(cx, |editor, cx| {
2071                assert!(
2072                    editor.display_text(cx).is_empty(),
2073                    "New search in directory should not have any excluded files"
2074                );
2075            });
2076            search_view.included_files_editor.update(cx, |editor, cx| {
2077                assert_eq!(
2078                    editor.display_text(cx),
2079                    a_dir_entry.path.to_str().unwrap(),
2080                    "New search in directory should have included dir entry path"
2081                );
2082            });
2083        });
2084
2085        search_view.update(cx, |search_view, cx| {
2086            search_view
2087                .query_editor
2088                .update(cx, |query_editor, cx| query_editor.set_text("const", cx));
2089            search_view.search(cx);
2090        });
2091        deterministic.run_until_parked();
2092        search_view.update(cx, |search_view, cx| {
2093            assert_eq!(
2094                search_view
2095                    .results_editor
2096                    .update(cx, |editor, cx| editor.display_text(cx)),
2097                "\n\nconst ONE: usize = 1;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
2098                "New search in directory should have a filter that matches a certain directory"
2099            );
2100        });
2101    }
2102
2103    #[gpui::test]
2104    async fn test_search_query_history(cx: &mut TestAppContext) {
2105        init_test(cx);
2106
2107        let fs = FakeFs::new(cx.background());
2108        fs.insert_tree(
2109            "/dir",
2110            json!({
2111                "one.rs": "const ONE: usize = 1;",
2112                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2113                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2114                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2115            }),
2116        )
2117        .await;
2118        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
2119        let window = cx.add_window(|cx| Workspace::test_new(project, cx));
2120        let workspace = window.root(cx);
2121        workspace.update(cx, |workspace, cx| {
2122            ProjectSearchView::deploy(workspace, &workspace::NewSearch, cx)
2123        });
2124
2125        let search_view = cx.read(|cx| {
2126            workspace
2127                .read(cx)
2128                .active_pane()
2129                .read(cx)
2130                .active_item()
2131                .and_then(|item| item.downcast::<ProjectSearchView>())
2132                .expect("Search view expected to appear after new search event trigger")
2133        });
2134
2135        let search_bar = window.add_view(cx, |cx| {
2136            let mut search_bar = ProjectSearchBar::new();
2137            search_bar.set_active_pane_item(Some(&search_view), cx);
2138            // search_bar.show(cx);
2139            search_bar
2140        });
2141
2142        // Add 3 search items into the history + another unsubmitted one.
2143        search_view.update(cx, |search_view, cx| {
2144            search_view.search_options = SearchOptions::CASE_SENSITIVE;
2145            search_view
2146                .query_editor
2147                .update(cx, |query_editor, cx| query_editor.set_text("ONE", cx));
2148            search_view.search(cx);
2149        });
2150        cx.foreground().run_until_parked();
2151        search_view.update(cx, |search_view, cx| {
2152            search_view
2153                .query_editor
2154                .update(cx, |query_editor, cx| query_editor.set_text("TWO", cx));
2155            search_view.search(cx);
2156        });
2157        cx.foreground().run_until_parked();
2158        search_view.update(cx, |search_view, cx| {
2159            search_view
2160                .query_editor
2161                .update(cx, |query_editor, cx| query_editor.set_text("THREE", cx));
2162            search_view.search(cx);
2163        });
2164        cx.foreground().run_until_parked();
2165        search_view.update(cx, |search_view, cx| {
2166            search_view.query_editor.update(cx, |query_editor, cx| {
2167                query_editor.set_text("JUST_TEXT_INPUT", cx)
2168            });
2169        });
2170        cx.foreground().run_until_parked();
2171
2172        // Ensure that the latest input with search settings is active.
2173        search_view.update(cx, |search_view, cx| {
2174            assert_eq!(
2175                search_view.query_editor.read(cx).text(cx),
2176                "JUST_TEXT_INPUT"
2177            );
2178            assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2179        });
2180
2181        // Next history query after the latest should set the query to the empty string.
2182        search_bar.update(cx, |search_bar, cx| {
2183            search_bar.next_history_query(&NextHistoryQuery, cx);
2184        });
2185        search_view.update(cx, |search_view, cx| {
2186            assert_eq!(search_view.query_editor.read(cx).text(cx), "");
2187            assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2188        });
2189        search_bar.update(cx, |search_bar, cx| {
2190            search_bar.next_history_query(&NextHistoryQuery, cx);
2191        });
2192        search_view.update(cx, |search_view, cx| {
2193            assert_eq!(search_view.query_editor.read(cx).text(cx), "");
2194            assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2195        });
2196
2197        // First previous query for empty current query should set the query to the latest submitted one.
2198        search_bar.update(cx, |search_bar, cx| {
2199            search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2200        });
2201        search_view.update(cx, |search_view, cx| {
2202            assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
2203            assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2204        });
2205
2206        // Further previous items should go over the history in reverse order.
2207        search_bar.update(cx, |search_bar, cx| {
2208            search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2209        });
2210        search_view.update(cx, |search_view, cx| {
2211            assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
2212            assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2213        });
2214
2215        // Previous items should never go behind the first history item.
2216        search_bar.update(cx, |search_bar, cx| {
2217            search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2218        });
2219        search_view.update(cx, |search_view, cx| {
2220            assert_eq!(search_view.query_editor.read(cx).text(cx), "ONE");
2221            assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2222        });
2223        search_bar.update(cx, |search_bar, cx| {
2224            search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2225        });
2226        search_view.update(cx, |search_view, cx| {
2227            assert_eq!(search_view.query_editor.read(cx).text(cx), "ONE");
2228            assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2229        });
2230
2231        // Next items should go over the history in the original order.
2232        search_bar.update(cx, |search_bar, cx| {
2233            search_bar.next_history_query(&NextHistoryQuery, cx);
2234        });
2235        search_view.update(cx, |search_view, cx| {
2236            assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
2237            assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2238        });
2239
2240        search_view.update(cx, |search_view, cx| {
2241            search_view
2242                .query_editor
2243                .update(cx, |query_editor, cx| query_editor.set_text("TWO_NEW", cx));
2244            search_view.search(cx);
2245        });
2246        cx.foreground().run_until_parked();
2247        search_view.update(cx, |search_view, cx| {
2248            assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO_NEW");
2249            assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2250        });
2251
2252        // New search input should add another entry to history and move the selection to the end of the history.
2253        search_bar.update(cx, |search_bar, cx| {
2254            search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2255        });
2256        search_view.update(cx, |search_view, cx| {
2257            assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
2258            assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2259        });
2260        search_bar.update(cx, |search_bar, cx| {
2261            search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2262        });
2263        search_view.update(cx, |search_view, cx| {
2264            assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
2265            assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2266        });
2267        search_bar.update(cx, |search_bar, cx| {
2268            search_bar.next_history_query(&NextHistoryQuery, cx);
2269        });
2270        search_view.update(cx, |search_view, cx| {
2271            assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
2272            assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2273        });
2274        search_bar.update(cx, |search_bar, cx| {
2275            search_bar.next_history_query(&NextHistoryQuery, cx);
2276        });
2277        search_view.update(cx, |search_view, cx| {
2278            assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO_NEW");
2279            assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2280        });
2281        search_bar.update(cx, |search_bar, cx| {
2282            search_bar.next_history_query(&NextHistoryQuery, cx);
2283        });
2284        search_view.update(cx, |search_view, cx| {
2285            assert_eq!(search_view.query_editor.read(cx).text(cx), "");
2286            assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2287        });
2288    }
2289
2290    pub fn init_test(cx: &mut TestAppContext) {
2291        cx.foreground().forbid_parking();
2292        let fonts = cx.font_cache();
2293        let mut theme = gpui::fonts::with_font_cache(fonts.clone(), theme::Theme::default);
2294        theme.search.match_background = Color::red();
2295
2296        cx.update(|cx| {
2297            cx.set_global(SettingsStore::test(cx));
2298            cx.set_global(ActiveSearches::default());
2299            settings::register::<SemanticIndexSettings>(cx);
2300
2301            theme::init((), cx);
2302            cx.update_global::<SettingsStore, _, _>(|store, _| {
2303                let mut settings = store.get::<ThemeSettings>(None).clone();
2304                settings.theme = Arc::new(theme);
2305                store.override_global(settings)
2306            });
2307
2308            language::init(cx);
2309            client::init_settings(cx);
2310            editor::init(cx);
2311            workspace::init_settings(cx);
2312            Project::init_settings(cx);
2313            super::init(cx);
2314        });
2315    }
2316}