project_search.rs

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