project_search.rs

   1use crate::{
   2    SearchOption, SelectNextMatch, SelectPrevMatch, ToggleCaseSensitive, ToggleRegex,
   3    ToggleWholeWord,
   4};
   5use anyhow::Result;
   6use collections::HashMap;
   7use editor::{
   8    items::active_match_index, scroll::autoscroll::Autoscroll, Anchor, Editor, MultiBuffer,
   9    SelectAll, MAX_TAB_TITLE_LEN,
  10};
  11use futures::StreamExt;
  12use globset::{Glob, GlobMatcher};
  13use gpui::{
  14    actions,
  15    elements::*,
  16    platform::{CursorStyle, MouseButton},
  17    Action, AnyElement, AnyViewHandle, AppContext, Entity, ModelContext, ModelHandle, Subscription,
  18    Task, View, ViewContext, ViewHandle, WeakModelHandle, WeakViewHandle,
  19};
  20use menu::Confirm;
  21use project::{search::SearchQuery, Project};
  22use smallvec::SmallVec;
  23use std::{
  24    any::{Any, TypeId},
  25    borrow::Cow,
  26    collections::HashSet,
  27    mem,
  28    ops::Range,
  29    path::PathBuf,
  30    sync::Arc,
  31};
  32use util::ResultExt as _;
  33use workspace::{
  34    item::{BreadcrumbText, Item, ItemEvent, ItemHandle},
  35    searchable::{Direction, SearchableItem, SearchableItemHandle},
  36    ItemNavHistory, Pane, ToolbarItemLocation, ToolbarItemView, Workspace, WorkspaceId,
  37};
  38
  39actions!(project_search, [SearchInNew, ToggleFocus, NextField]);
  40
  41#[derive(Default)]
  42struct ActiveSearches(HashMap<WeakModelHandle<Project>, WeakViewHandle<ProjectSearchView>>);
  43
  44pub fn init(cx: &mut AppContext) {
  45    cx.set_global(ActiveSearches::default());
  46    cx.add_action(ProjectSearchView::deploy);
  47    cx.add_action(ProjectSearchView::move_focus_to_results);
  48    cx.add_action(ProjectSearchBar::search);
  49    cx.add_action(ProjectSearchBar::search_in_new);
  50    cx.add_action(ProjectSearchBar::select_next_match);
  51    cx.add_action(ProjectSearchBar::select_prev_match);
  52    cx.capture_action(ProjectSearchBar::tab);
  53    cx.capture_action(ProjectSearchBar::tab_previous);
  54    add_toggle_option_action::<ToggleCaseSensitive>(SearchOption::CaseSensitive, cx);
  55    add_toggle_option_action::<ToggleWholeWord>(SearchOption::WholeWord, cx);
  56    add_toggle_option_action::<ToggleRegex>(SearchOption::Regex, cx);
  57}
  58
  59fn add_toggle_option_action<A: Action>(option: SearchOption, cx: &mut AppContext) {
  60    cx.add_action(move |pane: &mut Pane, _: &A, cx: &mut ViewContext<Pane>| {
  61        if let Some(search_bar) = pane.toolbar().read(cx).item_of_type::<ProjectSearchBar>() {
  62            if search_bar.update(cx, |search_bar, cx| {
  63                search_bar.toggle_search_option(option, cx)
  64            }) {
  65                return;
  66            }
  67        }
  68        cx.propagate_action();
  69    });
  70}
  71
  72struct ProjectSearch {
  73    project: ModelHandle<Project>,
  74    excerpts: ModelHandle<MultiBuffer>,
  75    pending_search: Option<Task<Option<()>>>,
  76    match_ranges: Vec<Range<Anchor>>,
  77    active_query: Option<SearchQuery>,
  78    search_id: usize,
  79}
  80
  81#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
  82enum InputPanel {
  83    Query,
  84    Exclude,
  85    Include,
  86}
  87
  88pub struct ProjectSearchView {
  89    model: ModelHandle<ProjectSearch>,
  90    query_editor: ViewHandle<Editor>,
  91    results_editor: ViewHandle<Editor>,
  92    case_sensitive: bool,
  93    whole_word: bool,
  94    regex: bool,
  95    panels_with_errors: HashSet<InputPanel>,
  96    active_match_index: Option<usize>,
  97    search_id: usize,
  98    query_editor_was_focused: bool,
  99    included_files_editor: ViewHandle<Editor>,
 100    excluded_files_editor: ViewHandle<Editor>,
 101}
 102
 103pub struct ProjectSearchBar {
 104    active_project_search: Option<ViewHandle<ProjectSearchView>>,
 105    subscription: Option<Subscription>,
 106}
 107
 108impl Entity for ProjectSearch {
 109    type Event = ();
 110}
 111
 112impl ProjectSearch {
 113    fn new(project: ModelHandle<Project>, cx: &mut ModelContext<Self>) -> Self {
 114        let replica_id = project.read(cx).replica_id();
 115        Self {
 116            project,
 117            excerpts: cx.add_model(|_| MultiBuffer::new(replica_id)),
 118            pending_search: Default::default(),
 119            match_ranges: Default::default(),
 120            active_query: None,
 121            search_id: 0,
 122        }
 123    }
 124
 125    fn clone(&self, cx: &mut ModelContext<Self>) -> ModelHandle<Self> {
 126        cx.add_model(|cx| Self {
 127            project: self.project.clone(),
 128            excerpts: self
 129                .excerpts
 130                .update(cx, |excerpts, cx| cx.add_model(|cx| excerpts.clone(cx))),
 131            pending_search: Default::default(),
 132            match_ranges: self.match_ranges.clone(),
 133            active_query: self.active_query.clone(),
 134            search_id: self.search_id,
 135        })
 136    }
 137
 138    fn search(&mut self, query: SearchQuery, cx: &mut ModelContext<Self>) {
 139        let search = self
 140            .project
 141            .update(cx, |project, cx| project.search(query.clone(), cx));
 142        self.search_id += 1;
 143        self.active_query = Some(query);
 144        self.match_ranges.clear();
 145        self.pending_search = Some(cx.spawn_weak(|this, mut cx| async move {
 146            let matches = search.await.log_err()?;
 147            let this = this.upgrade(&cx)?;
 148            let mut matches = matches.into_iter().collect::<Vec<_>>();
 149            let (_task, mut match_ranges) = this.update(&mut cx, |this, cx| {
 150                this.match_ranges.clear();
 151                matches.sort_by_key(|(buffer, _)| buffer.read(cx).file().map(|file| file.path()));
 152                this.excerpts.update(cx, |excerpts, cx| {
 153                    excerpts.clear(cx);
 154                    excerpts.stream_excerpts_with_context_lines(matches, 1, cx)
 155                })
 156            });
 157
 158            while let Some(match_range) = match_ranges.next().await {
 159                this.update(&mut cx, |this, cx| {
 160                    this.match_ranges.push(match_range);
 161                    while let Ok(Some(match_range)) = match_ranges.try_next() {
 162                        this.match_ranges.push(match_range);
 163                    }
 164                    cx.notify();
 165                });
 166            }
 167
 168            this.update(&mut cx, |this, cx| {
 169                this.pending_search.take();
 170                cx.notify();
 171            });
 172
 173            None
 174        }));
 175        cx.notify();
 176    }
 177}
 178
 179pub enum ViewEvent {
 180    UpdateTab,
 181    Activate,
 182    EditorEvent(editor::Event),
 183}
 184
 185impl Entity for ProjectSearchView {
 186    type Event = ViewEvent;
 187}
 188
 189impl View for ProjectSearchView {
 190    fn ui_name() -> &'static str {
 191        "ProjectSearchView"
 192    }
 193
 194    fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
 195        let model = &self.model.read(cx);
 196        if model.match_ranges.is_empty() {
 197            enum Status {}
 198
 199            let theme = theme::current(cx).clone();
 200            let text = if self.query_editor.read(cx).text(cx).is_empty() {
 201                ""
 202            } else if model.pending_search.is_some() {
 203                "Searching..."
 204            } else {
 205                "No results"
 206            };
 207            MouseEventHandler::<Status, _>::new(0, cx, |_, _| {
 208                Label::new(text, theme.search.results_status.clone())
 209                    .aligned()
 210                    .contained()
 211                    .with_background_color(theme.editor.background)
 212                    .flex(1., true)
 213            })
 214            .on_down(MouseButton::Left, |_, _, cx| {
 215                cx.focus_parent();
 216            })
 217            .into_any_named("project search view")
 218        } else {
 219            ChildView::new(&self.results_editor, cx)
 220                .flex(1., true)
 221                .into_any_named("project search view")
 222        }
 223    }
 224
 225    fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
 226        let handle = cx.weak_handle();
 227        cx.update_global(|state: &mut ActiveSearches, cx| {
 228            state
 229                .0
 230                .insert(self.model.read(cx).project.downgrade(), handle)
 231        });
 232
 233        if cx.is_self_focused() {
 234            if self.query_editor_was_focused {
 235                cx.focus(&self.query_editor);
 236            } else {
 237                cx.focus(&self.results_editor);
 238            }
 239        }
 240    }
 241}
 242
 243impl Item for ProjectSearchView {
 244    fn tab_tooltip_text(&self, cx: &AppContext) -> Option<Cow<str>> {
 245        Some(self.query_editor.read(cx).text(cx).into())
 246    }
 247
 248    fn act_as_type<'a>(
 249        &'a self,
 250        type_id: TypeId,
 251        self_handle: &'a ViewHandle<Self>,
 252        _: &'a AppContext,
 253    ) -> Option<&'a AnyViewHandle> {
 254        if type_id == TypeId::of::<Self>() {
 255            Some(self_handle)
 256        } else if type_id == TypeId::of::<Editor>() {
 257            Some(&self.results_editor)
 258        } else {
 259            None
 260        }
 261    }
 262
 263    fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
 264        self.results_editor
 265            .update(cx, |editor, cx| editor.deactivated(cx));
 266    }
 267
 268    fn tab_content<T: View>(
 269        &self,
 270        _detail: Option<usize>,
 271        tab_theme: &theme::Tab,
 272        cx: &AppContext,
 273    ) -> AnyElement<T> {
 274        Flex::row()
 275            .with_child(
 276                Svg::new("icons/magnifying_glass_12.svg")
 277                    .with_color(tab_theme.label.text.color)
 278                    .constrained()
 279                    .with_width(tab_theme.type_icon_width)
 280                    .aligned()
 281                    .contained()
 282                    .with_margin_right(tab_theme.spacing),
 283            )
 284            .with_children(self.model.read(cx).active_query.as_ref().map(|query| {
 285                let query_text = util::truncate_and_trailoff(query.as_str(), MAX_TAB_TITLE_LEN);
 286
 287                Label::new(query_text, tab_theme.label.clone()).aligned()
 288            }))
 289            .into_any()
 290    }
 291
 292    fn for_each_project_item(&self, cx: &AppContext, f: &mut dyn FnMut(usize, &dyn project::Item)) {
 293        self.results_editor.for_each_project_item(cx, f)
 294    }
 295
 296    fn is_singleton(&self, _: &AppContext) -> bool {
 297        false
 298    }
 299
 300    fn can_save(&self, _: &AppContext) -> bool {
 301        true
 302    }
 303
 304    fn is_dirty(&self, cx: &AppContext) -> bool {
 305        self.results_editor.read(cx).is_dirty(cx)
 306    }
 307
 308    fn has_conflict(&self, cx: &AppContext) -> bool {
 309        self.results_editor.read(cx).has_conflict(cx)
 310    }
 311
 312    fn save(
 313        &mut self,
 314        project: ModelHandle<Project>,
 315        cx: &mut ViewContext<Self>,
 316    ) -> Task<anyhow::Result<()>> {
 317        self.results_editor
 318            .update(cx, |editor, cx| editor.save(project, cx))
 319    }
 320
 321    fn save_as(
 322        &mut self,
 323        _: ModelHandle<Project>,
 324        _: PathBuf,
 325        _: &mut ViewContext<Self>,
 326    ) -> Task<anyhow::Result<()>> {
 327        unreachable!("save_as should not have been called")
 328    }
 329
 330    fn reload(
 331        &mut self,
 332        project: ModelHandle<Project>,
 333        cx: &mut ViewContext<Self>,
 334    ) -> Task<anyhow::Result<()>> {
 335        self.results_editor
 336            .update(cx, |editor, cx| editor.reload(project, cx))
 337    }
 338
 339    fn clone_on_split(&self, _workspace_id: WorkspaceId, cx: &mut ViewContext<Self>) -> Option<Self>
 340    where
 341        Self: Sized,
 342    {
 343        let model = self.model.update(cx, |model, cx| model.clone(cx));
 344        Some(Self::new(model, cx))
 345    }
 346
 347    fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
 348        self.results_editor
 349            .update(cx, |editor, cx| editor.added_to_workspace(workspace, cx));
 350    }
 351
 352    fn set_nav_history(&mut self, nav_history: ItemNavHistory, cx: &mut ViewContext<Self>) {
 353        self.results_editor.update(cx, |editor, _| {
 354            editor.set_nav_history(Some(nav_history));
 355        });
 356    }
 357
 358    fn navigate(&mut self, data: Box<dyn Any>, cx: &mut ViewContext<Self>) -> bool {
 359        self.results_editor
 360            .update(cx, |editor, cx| editor.navigate(data, cx))
 361    }
 362
 363    fn git_diff_recalc(
 364        &mut self,
 365        project: ModelHandle<Project>,
 366        cx: &mut ViewContext<Self>,
 367    ) -> Task<anyhow::Result<()>> {
 368        self.results_editor
 369            .update(cx, |editor, cx| editor.git_diff_recalc(project, cx))
 370    }
 371
 372    fn to_item_events(event: &Self::Event) -> SmallVec<[ItemEvent; 2]> {
 373        match event {
 374            ViewEvent::UpdateTab => {
 375                smallvec::smallvec![ItemEvent::UpdateBreadcrumbs, ItemEvent::UpdateTab]
 376            }
 377            ViewEvent::EditorEvent(editor_event) => Editor::to_item_events(editor_event),
 378            _ => SmallVec::new(),
 379        }
 380    }
 381
 382    fn breadcrumb_location(&self) -> ToolbarItemLocation {
 383        if self.has_matches() {
 384            ToolbarItemLocation::Secondary
 385        } else {
 386            ToolbarItemLocation::Hidden
 387        }
 388    }
 389
 390    fn breadcrumbs(&self, theme: &theme::Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
 391        self.results_editor.breadcrumbs(theme, cx)
 392    }
 393
 394    fn serialized_item_kind() -> Option<&'static str> {
 395        None
 396    }
 397
 398    fn deserialize(
 399        _project: ModelHandle<Project>,
 400        _workspace: WeakViewHandle<Workspace>,
 401        _workspace_id: workspace::WorkspaceId,
 402        _item_id: workspace::ItemId,
 403        _cx: &mut ViewContext<Pane>,
 404    ) -> Task<anyhow::Result<ViewHandle<Self>>> {
 405        unimplemented!()
 406    }
 407}
 408
 409impl ProjectSearchView {
 410    fn new(model: ModelHandle<ProjectSearch>, cx: &mut ViewContext<Self>) -> Self {
 411        let project;
 412        let excerpts;
 413        let mut query_text = String::new();
 414        let mut regex = false;
 415        let mut case_sensitive = false;
 416        let mut whole_word = false;
 417
 418        {
 419            let model = model.read(cx);
 420            project = model.project.clone();
 421            excerpts = model.excerpts.clone();
 422            if let Some(active_query) = model.active_query.as_ref() {
 423                query_text = active_query.as_str().to_string();
 424                regex = active_query.is_regex();
 425                case_sensitive = active_query.case_sensitive();
 426                whole_word = active_query.whole_word();
 427            }
 428        }
 429        cx.observe(&model, |this, _, cx| this.model_changed(cx))
 430            .detach();
 431
 432        let query_editor = cx.add_view(|cx| {
 433            let mut editor = Editor::single_line(
 434                Some(Arc::new(|theme| theme.search.editor.input.clone())),
 435                cx,
 436            );
 437            editor.set_text(query_text, cx);
 438            editor
 439        });
 440        // Subscribe to query_editor in order to reraise editor events for workspace item activation purposes
 441        cx.subscribe(&query_editor, |_, _, event, cx| {
 442            cx.emit(ViewEvent::EditorEvent(event.clone()))
 443        })
 444        .detach();
 445
 446        let results_editor = cx.add_view(|cx| {
 447            let mut editor = Editor::for_multibuffer(excerpts, Some(project), cx);
 448            editor.set_searchable(false);
 449            editor
 450        });
 451        cx.observe(&results_editor, |_, _, cx| cx.emit(ViewEvent::UpdateTab))
 452            .detach();
 453
 454        cx.subscribe(&results_editor, |this, _, event, cx| {
 455            if matches!(event, editor::Event::SelectionsChanged { .. }) {
 456                this.update_match_index(cx);
 457            }
 458            // Reraise editor events for workspace item activation purposes
 459            cx.emit(ViewEvent::EditorEvent(event.clone()));
 460        })
 461        .detach();
 462
 463        let included_files_editor = cx.add_view(|cx| {
 464            let mut editor = Editor::single_line(
 465                Some(Arc::new(|theme| {
 466                    theme.search.include_exclude_editor.input.clone()
 467                })),
 468                cx,
 469            );
 470            editor.set_placeholder_text("Include: crates/**/*.toml", cx);
 471
 472            editor
 473        });
 474        // Subscribe to include_files_editor in order to reraise editor events for workspace item activation purposes
 475        cx.subscribe(&included_files_editor, |_, _, event, cx| {
 476            cx.emit(ViewEvent::EditorEvent(event.clone()))
 477        })
 478        .detach();
 479
 480        let excluded_files_editor = cx.add_view(|cx| {
 481            let mut editor = Editor::single_line(
 482                Some(Arc::new(|theme| {
 483                    theme.search.include_exclude_editor.input.clone()
 484                })),
 485                cx,
 486            );
 487            editor.set_placeholder_text("Exclude: vendor/*, *.lock", cx);
 488
 489            editor
 490        });
 491        // Subscribe to excluded_files_editor in order to reraise editor events for workspace item activation purposes
 492        cx.subscribe(&excluded_files_editor, |_, _, event, cx| {
 493            cx.emit(ViewEvent::EditorEvent(event.clone()))
 494        })
 495        .detach();
 496
 497        let mut this = ProjectSearchView {
 498            search_id: model.read(cx).search_id,
 499            model,
 500            query_editor,
 501            results_editor,
 502            case_sensitive,
 503            whole_word,
 504            regex,
 505            panels_with_errors: HashSet::new(),
 506            active_match_index: None,
 507            query_editor_was_focused: false,
 508            included_files_editor,
 509            excluded_files_editor,
 510        };
 511        this.model_changed(cx);
 512        this
 513    }
 514
 515    // Re-activate the most recently activated search or the most recent if it has been closed.
 516    // If no search exists in the workspace, create a new one.
 517    fn deploy(
 518        workspace: &mut Workspace,
 519        _: &workspace::NewSearch,
 520        cx: &mut ViewContext<Workspace>,
 521    ) {
 522        // Clean up entries for dropped projects
 523        cx.update_global(|state: &mut ActiveSearches, cx| {
 524            state.0.retain(|project, _| project.is_upgradable(cx))
 525        });
 526
 527        let active_search = cx
 528            .global::<ActiveSearches>()
 529            .0
 530            .get(&workspace.project().downgrade());
 531
 532        let existing = active_search
 533            .and_then(|active_search| {
 534                workspace
 535                    .items_of_type::<ProjectSearchView>(cx)
 536                    .find(|search| search == active_search)
 537            })
 538            .or_else(|| workspace.item_of_type::<ProjectSearchView>(cx));
 539
 540        let query = workspace.active_item(cx).and_then(|item| {
 541            let editor = item.act_as::<Editor>(cx)?;
 542            let query = editor.query_suggestion(cx);
 543            if query.is_empty() {
 544                None
 545            } else {
 546                Some(query)
 547            }
 548        });
 549
 550        let search = if let Some(existing) = existing {
 551            workspace.activate_item(&existing, cx);
 552            existing
 553        } else {
 554            let model = cx.add_model(|cx| ProjectSearch::new(workspace.project().clone(), cx));
 555            let view = cx.add_view(|cx| ProjectSearchView::new(model, cx));
 556            workspace.add_item(Box::new(view.clone()), cx);
 557            view
 558        };
 559
 560        search.update(cx, |search, cx| {
 561            if let Some(query) = query {
 562                search.set_query(&query, cx);
 563            }
 564            search.focus_query_editor(cx)
 565        });
 566    }
 567
 568    fn search(&mut self, cx: &mut ViewContext<Self>) {
 569        if let Some(query) = self.build_search_query(cx) {
 570            self.model.update(cx, |model, cx| model.search(query, cx));
 571        }
 572    }
 573
 574    fn build_search_query(&mut self, cx: &mut ViewContext<Self>) -> Option<SearchQuery> {
 575        let text = self.query_editor.read(cx).text(cx);
 576        let included_files =
 577            match Self::load_glob_set(&self.included_files_editor.read(cx).text(cx)) {
 578                Ok(included_files) => {
 579                    self.panels_with_errors.remove(&InputPanel::Include);
 580                    included_files
 581                }
 582                Err(_e) => {
 583                    self.panels_with_errors.insert(InputPanel::Include);
 584                    cx.notify();
 585                    return None;
 586                }
 587            };
 588        let excluded_files =
 589            match Self::load_glob_set(&self.excluded_files_editor.read(cx).text(cx)) {
 590                Ok(excluded_files) => {
 591                    self.panels_with_errors.remove(&InputPanel::Exclude);
 592                    excluded_files
 593                }
 594                Err(_e) => {
 595                    self.panels_with_errors.insert(InputPanel::Exclude);
 596                    cx.notify();
 597                    return None;
 598                }
 599            };
 600        if self.regex {
 601            match SearchQuery::regex(
 602                text,
 603                self.whole_word,
 604                self.case_sensitive,
 605                included_files,
 606                excluded_files,
 607            ) {
 608                Ok(query) => {
 609                    self.panels_with_errors.remove(&InputPanel::Query);
 610                    Some(query)
 611                }
 612                Err(_e) => {
 613                    self.panels_with_errors.insert(InputPanel::Query);
 614                    cx.notify();
 615                    None
 616                }
 617            }
 618        } else {
 619            Some(SearchQuery::text(
 620                text,
 621                self.whole_word,
 622                self.case_sensitive,
 623                included_files,
 624                excluded_files,
 625            ))
 626        }
 627    }
 628
 629    fn load_glob_set(text: &str) -> Result<Vec<GlobMatcher>> {
 630        text.split(',')
 631            .map(str::trim)
 632            .filter(|glob_str| !glob_str.is_empty())
 633            .map(|glob_str| anyhow::Ok(Glob::new(glob_str)?.compile_matcher()))
 634            .collect()
 635    }
 636
 637    fn select_match(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 638        if let Some(index) = self.active_match_index {
 639            let match_ranges = self.model.read(cx).match_ranges.clone();
 640            let new_index = self.results_editor.update(cx, |editor, cx| {
 641                editor.match_index_for_direction(&match_ranges, index, direction, cx)
 642            });
 643
 644            let range_to_select = match_ranges[new_index].clone();
 645            self.results_editor.update(cx, |editor, cx| {
 646                editor.unfold_ranges([range_to_select.clone()], false, true, cx);
 647                editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 648                    s.select_ranges([range_to_select])
 649                });
 650            });
 651        }
 652    }
 653
 654    fn focus_query_editor(&mut self, cx: &mut ViewContext<Self>) {
 655        self.query_editor.update(cx, |query_editor, cx| {
 656            query_editor.select_all(&SelectAll, cx);
 657        });
 658        self.query_editor_was_focused = true;
 659        cx.focus(&self.query_editor);
 660    }
 661
 662    fn set_query(&mut self, query: &str, cx: &mut ViewContext<Self>) {
 663        self.query_editor
 664            .update(cx, |query_editor, cx| query_editor.set_text(query, cx));
 665    }
 666
 667    fn focus_results_editor(&mut self, cx: &mut ViewContext<Self>) {
 668        self.query_editor.update(cx, |query_editor, cx| {
 669            let cursor = query_editor.selections.newest_anchor().head();
 670            query_editor.change_selections(None, cx, |s| s.select_ranges([cursor.clone()..cursor]));
 671        });
 672        self.query_editor_was_focused = false;
 673        cx.focus(&self.results_editor);
 674    }
 675
 676    fn model_changed(&mut self, cx: &mut ViewContext<Self>) {
 677        let match_ranges = self.model.read(cx).match_ranges.clone();
 678        if match_ranges.is_empty() {
 679            self.active_match_index = None;
 680        } else {
 681            let prev_search_id = mem::replace(&mut self.search_id, self.model.read(cx).search_id);
 682            let is_new_search = self.search_id != prev_search_id;
 683            self.results_editor.update(cx, |editor, cx| {
 684                if is_new_search {
 685                    editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 686                        s.select_ranges(match_ranges.first().cloned())
 687                    });
 688                }
 689                editor.highlight_background::<Self>(
 690                    match_ranges,
 691                    |theme| theme.search.match_background,
 692                    cx,
 693                );
 694            });
 695            if is_new_search && self.query_editor.is_focused(cx) {
 696                self.focus_results_editor(cx);
 697            }
 698        }
 699
 700        cx.emit(ViewEvent::UpdateTab);
 701        cx.notify();
 702    }
 703
 704    fn update_match_index(&mut self, cx: &mut ViewContext<Self>) {
 705        let results_editor = self.results_editor.read(cx);
 706        let new_index = active_match_index(
 707            &self.model.read(cx).match_ranges,
 708            &results_editor.selections.newest_anchor().head(),
 709            &results_editor.buffer().read(cx).snapshot(cx),
 710        );
 711        if self.active_match_index != new_index {
 712            self.active_match_index = new_index;
 713            cx.notify();
 714        }
 715    }
 716
 717    pub fn has_matches(&self) -> bool {
 718        self.active_match_index.is_some()
 719    }
 720
 721    fn move_focus_to_results(pane: &mut Pane, _: &ToggleFocus, cx: &mut ViewContext<Pane>) {
 722        if let Some(search_view) = pane
 723            .active_item()
 724            .and_then(|item| item.downcast::<ProjectSearchView>())
 725        {
 726            search_view.update(cx, |search_view, cx| {
 727                if !search_view.results_editor.is_focused(cx)
 728                    && !search_view.model.read(cx).match_ranges.is_empty()
 729                {
 730                    return search_view.focus_results_editor(cx);
 731                }
 732            });
 733        }
 734
 735        cx.propagate_action();
 736    }
 737}
 738
 739impl Default for ProjectSearchBar {
 740    fn default() -> Self {
 741        Self::new()
 742    }
 743}
 744
 745impl ProjectSearchBar {
 746    pub fn new() -> Self {
 747        Self {
 748            active_project_search: Default::default(),
 749            subscription: Default::default(),
 750        }
 751    }
 752
 753    fn search(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
 754        if let Some(search_view) = self.active_project_search.as_ref() {
 755            search_view.update(cx, |search_view, cx| search_view.search(cx));
 756        }
 757    }
 758
 759    fn search_in_new(workspace: &mut Workspace, _: &SearchInNew, cx: &mut ViewContext<Workspace>) {
 760        if let Some(search_view) = workspace
 761            .active_item(cx)
 762            .and_then(|item| item.downcast::<ProjectSearchView>())
 763        {
 764            let new_query = search_view.update(cx, |search_view, cx| {
 765                let new_query = search_view.build_search_query(cx);
 766                if new_query.is_some() {
 767                    if let Some(old_query) = search_view.model.read(cx).active_query.clone() {
 768                        search_view.query_editor.update(cx, |editor, cx| {
 769                            editor.set_text(old_query.as_str(), cx);
 770                        });
 771                        search_view.regex = old_query.is_regex();
 772                        search_view.whole_word = old_query.whole_word();
 773                        search_view.case_sensitive = old_query.case_sensitive();
 774                    }
 775                }
 776                new_query
 777            });
 778            if let Some(new_query) = new_query {
 779                let model = cx.add_model(|cx| {
 780                    let mut model = ProjectSearch::new(workspace.project().clone(), cx);
 781                    model.search(new_query, cx);
 782                    model
 783                });
 784                workspace.add_item(
 785                    Box::new(cx.add_view(|cx| ProjectSearchView::new(model, cx))),
 786                    cx,
 787                );
 788            }
 789        }
 790    }
 791
 792    fn select_next_match(pane: &mut Pane, _: &SelectNextMatch, cx: &mut ViewContext<Pane>) {
 793        if let Some(search_view) = pane
 794            .active_item()
 795            .and_then(|item| item.downcast::<ProjectSearchView>())
 796        {
 797            search_view.update(cx, |view, cx| view.select_match(Direction::Next, cx));
 798        } else {
 799            cx.propagate_action();
 800        }
 801    }
 802
 803    fn select_prev_match(pane: &mut Pane, _: &SelectPrevMatch, cx: &mut ViewContext<Pane>) {
 804        if let Some(search_view) = pane
 805            .active_item()
 806            .and_then(|item| item.downcast::<ProjectSearchView>())
 807        {
 808            search_view.update(cx, |view, cx| view.select_match(Direction::Prev, cx));
 809        } else {
 810            cx.propagate_action();
 811        }
 812    }
 813
 814    fn tab(&mut self, _: &editor::Tab, cx: &mut ViewContext<Self>) {
 815        self.cycle_field(Direction::Next, cx);
 816    }
 817
 818    fn tab_previous(&mut self, _: &editor::TabPrev, cx: &mut ViewContext<Self>) {
 819        self.cycle_field(Direction::Prev, cx);
 820    }
 821
 822    fn cycle_field(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 823        let active_project_search = match &self.active_project_search {
 824            Some(active_project_search) => active_project_search,
 825
 826            None => {
 827                cx.propagate_action();
 828                return;
 829            }
 830        };
 831
 832        active_project_search.update(cx, |project_view, cx| {
 833            let views = &[
 834                &project_view.query_editor,
 835                &project_view.included_files_editor,
 836                &project_view.excluded_files_editor,
 837            ];
 838
 839            let current_index = match views
 840                .iter()
 841                .enumerate()
 842                .find(|(_, view)| view.is_focused(cx))
 843            {
 844                Some((index, _)) => index,
 845
 846                None => {
 847                    cx.propagate_action();
 848                    return;
 849                }
 850            };
 851
 852            let new_index = match direction {
 853                Direction::Next => (current_index + 1) % views.len(),
 854                Direction::Prev if current_index == 0 => views.len() - 1,
 855                Direction::Prev => (current_index - 1) % views.len(),
 856            };
 857            cx.focus(views[new_index]);
 858        });
 859    }
 860
 861    fn toggle_search_option(&mut self, option: SearchOption, cx: &mut ViewContext<Self>) -> bool {
 862        if let Some(search_view) = self.active_project_search.as_ref() {
 863            search_view.update(cx, |search_view, cx| {
 864                let value = match option {
 865                    SearchOption::WholeWord => &mut search_view.whole_word,
 866                    SearchOption::CaseSensitive => &mut search_view.case_sensitive,
 867                    SearchOption::Regex => &mut search_view.regex,
 868                };
 869                *value = !*value;
 870                search_view.search(cx);
 871            });
 872            cx.notify();
 873            true
 874        } else {
 875            false
 876        }
 877    }
 878
 879    fn render_nav_button(
 880        &self,
 881        icon: &'static str,
 882        direction: Direction,
 883        cx: &mut ViewContext<Self>,
 884    ) -> AnyElement<Self> {
 885        let action: Box<dyn Action>;
 886        let tooltip;
 887        match direction {
 888            Direction::Prev => {
 889                action = Box::new(SelectPrevMatch);
 890                tooltip = "Select Previous Match";
 891            }
 892            Direction::Next => {
 893                action = Box::new(SelectNextMatch);
 894                tooltip = "Select Next Match";
 895            }
 896        };
 897        let tooltip_style = theme::current(cx).tooltip.clone();
 898
 899        enum NavButton {}
 900        MouseEventHandler::<NavButton, _>::new(direction as usize, cx, |state, cx| {
 901            let theme = theme::current(cx);
 902            let style = theme.search.option_button.style_for(state, false);
 903            Label::new(icon, style.text.clone())
 904                .contained()
 905                .with_style(style.container)
 906        })
 907        .on_click(MouseButton::Left, move |_, this, cx| {
 908            if let Some(search) = this.active_project_search.as_ref() {
 909                search.update(cx, |search, cx| search.select_match(direction, cx));
 910            }
 911        })
 912        .with_cursor_style(CursorStyle::PointingHand)
 913        .with_tooltip::<NavButton>(
 914            direction as usize,
 915            tooltip.to_string(),
 916            Some(action),
 917            tooltip_style,
 918            cx,
 919        )
 920        .into_any()
 921    }
 922
 923    fn render_option_button(
 924        &self,
 925        icon: &'static str,
 926        option: SearchOption,
 927        cx: &mut ViewContext<Self>,
 928    ) -> AnyElement<Self> {
 929        let tooltip_style = theme::current(cx).tooltip.clone();
 930        let is_active = self.is_option_enabled(option, cx);
 931        MouseEventHandler::<Self, _>::new(option as usize, cx, |state, cx| {
 932            let theme = theme::current(cx);
 933            let style = theme.search.option_button.style_for(state, is_active);
 934            Label::new(icon, style.text.clone())
 935                .contained()
 936                .with_style(style.container)
 937        })
 938        .on_click(MouseButton::Left, move |_, this, cx| {
 939            this.toggle_search_option(option, cx);
 940        })
 941        .with_cursor_style(CursorStyle::PointingHand)
 942        .with_tooltip::<Self>(
 943            option as usize,
 944            format!("Toggle {}", option.label()),
 945            Some(option.to_toggle_action()),
 946            tooltip_style,
 947            cx,
 948        )
 949        .into_any()
 950    }
 951
 952    fn is_option_enabled(&self, option: SearchOption, cx: &AppContext) -> bool {
 953        if let Some(search) = self.active_project_search.as_ref() {
 954            let search = search.read(cx);
 955            match option {
 956                SearchOption::WholeWord => search.whole_word,
 957                SearchOption::CaseSensitive => search.case_sensitive,
 958                SearchOption::Regex => search.regex,
 959            }
 960        } else {
 961            false
 962        }
 963    }
 964}
 965
 966impl Entity for ProjectSearchBar {
 967    type Event = ();
 968}
 969
 970impl View for ProjectSearchBar {
 971    fn ui_name() -> &'static str {
 972        "ProjectSearchBar"
 973    }
 974
 975    fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
 976        if let Some(search) = self.active_project_search.as_ref() {
 977            let search = search.read(cx);
 978            let theme = theme::current(cx).clone();
 979            let query_container_style = if search.panels_with_errors.contains(&InputPanel::Query) {
 980                theme.search.invalid_editor
 981            } else {
 982                theme.search.editor.input.container
 983            };
 984            let include_container_style =
 985                if search.panels_with_errors.contains(&InputPanel::Include) {
 986                    theme.search.invalid_include_exclude_editor
 987                } else {
 988                    theme.search.include_exclude_editor.input.container
 989                };
 990            let exclude_container_style =
 991                if search.panels_with_errors.contains(&InputPanel::Exclude) {
 992                    theme.search.invalid_include_exclude_editor
 993                } else {
 994                    theme.search.include_exclude_editor.input.container
 995                };
 996
 997            let included_files_view = ChildView::new(&search.included_files_editor, cx)
 998                .aligned()
 999                .left()
1000                .flex(1.0, true);
1001            let excluded_files_view = ChildView::new(&search.excluded_files_editor, cx)
1002                .aligned()
1003                .right()
1004                .flex(1.0, true);
1005
1006            let row_spacing = theme.workspace.toolbar.container.padding.bottom;
1007
1008            Flex::column()
1009                .with_child(
1010                    Flex::row()
1011                        .with_child(
1012                            Flex::row()
1013                                .with_child(
1014                                    ChildView::new(&search.query_editor, cx)
1015                                        .aligned()
1016                                        .left()
1017                                        .flex(1., true),
1018                                )
1019                                .with_children(search.active_match_index.map(|match_ix| {
1020                                    Label::new(
1021                                        format!(
1022                                            "{}/{}",
1023                                            match_ix + 1,
1024                                            search.model.read(cx).match_ranges.len()
1025                                        ),
1026                                        theme.search.match_index.text.clone(),
1027                                    )
1028                                    .contained()
1029                                    .with_style(theme.search.match_index.container)
1030                                    .aligned()
1031                                }))
1032                                .contained()
1033                                .with_style(query_container_style)
1034                                .aligned()
1035                                .constrained()
1036                                .with_min_width(theme.search.editor.min_width)
1037                                .with_max_width(theme.search.editor.max_width)
1038                                .flex(1., false),
1039                        )
1040                        .with_child(
1041                            Flex::row()
1042                                .with_child(self.render_nav_button("<", Direction::Prev, cx))
1043                                .with_child(self.render_nav_button(">", Direction::Next, cx))
1044                                .aligned(),
1045                        )
1046                        .with_child(
1047                            Flex::row()
1048                                .with_child(self.render_option_button(
1049                                    "Case",
1050                                    SearchOption::CaseSensitive,
1051                                    cx,
1052                                ))
1053                                .with_child(self.render_option_button(
1054                                    "Word",
1055                                    SearchOption::WholeWord,
1056                                    cx,
1057                                ))
1058                                .with_child(self.render_option_button(
1059                                    "Regex",
1060                                    SearchOption::Regex,
1061                                    cx,
1062                                ))
1063                                .contained()
1064                                .with_style(theme.search.option_button_group)
1065                                .aligned(),
1066                        )
1067                        .contained()
1068                        .with_margin_bottom(row_spacing),
1069                )
1070                .with_child(
1071                    Flex::row()
1072                        .with_child(
1073                            Flex::row()
1074                                .with_child(included_files_view)
1075                                .contained()
1076                                .with_style(include_container_style)
1077                                .aligned()
1078                                .constrained()
1079                                .with_min_width(theme.search.include_exclude_editor.min_width)
1080                                .with_max_width(theme.search.include_exclude_editor.max_width)
1081                                .flex(1., false),
1082                        )
1083                        .with_child(
1084                            Flex::row()
1085                                .with_child(excluded_files_view)
1086                                .contained()
1087                                .with_style(exclude_container_style)
1088                                .aligned()
1089                                .constrained()
1090                                .with_min_width(theme.search.include_exclude_editor.min_width)
1091                                .with_max_width(theme.search.include_exclude_editor.max_width)
1092                                .flex(1., false),
1093                        ),
1094                )
1095                .contained()
1096                .with_style(theme.search.container)
1097                .aligned()
1098                .left()
1099                .into_any_named("project search")
1100        } else {
1101            Empty::new().into_any()
1102        }
1103    }
1104}
1105
1106impl ToolbarItemView for ProjectSearchBar {
1107    fn set_active_pane_item(
1108        &mut self,
1109        active_pane_item: Option<&dyn ItemHandle>,
1110        cx: &mut ViewContext<Self>,
1111    ) -> ToolbarItemLocation {
1112        cx.notify();
1113        self.subscription = None;
1114        self.active_project_search = None;
1115        if let Some(search) = active_pane_item.and_then(|i| i.downcast::<ProjectSearchView>()) {
1116            self.subscription = Some(cx.observe(&search, |_, _, cx| cx.notify()));
1117            self.active_project_search = Some(search);
1118            ToolbarItemLocation::PrimaryLeft {
1119                flex: Some((1., false)),
1120            }
1121        } else {
1122            ToolbarItemLocation::Hidden
1123        }
1124    }
1125
1126    fn row_count(&self) -> usize {
1127        2
1128    }
1129}
1130
1131#[cfg(test)]
1132pub mod tests {
1133    use super::*;
1134    use editor::DisplayPoint;
1135    use gpui::{color::Color, executor::Deterministic, TestAppContext};
1136    use project::FakeFs;
1137    use serde_json::json;
1138    use settings::SettingsStore;
1139    use std::sync::Arc;
1140    use theme::ThemeSettings;
1141
1142    #[gpui::test]
1143    async fn test_project_search(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
1144        init_test(cx);
1145
1146        let fs = FakeFs::new(cx.background());
1147        fs.insert_tree(
1148            "/dir",
1149            json!({
1150                "one.rs": "const ONE: usize = 1;",
1151                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
1152                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
1153                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
1154            }),
1155        )
1156        .await;
1157        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
1158        let search = cx.add_model(|cx| ProjectSearch::new(project, cx));
1159        let (_, search_view) = cx.add_window(|cx| ProjectSearchView::new(search.clone(), cx));
1160
1161        search_view.update(cx, |search_view, cx| {
1162            search_view
1163                .query_editor
1164                .update(cx, |query_editor, cx| query_editor.set_text("TWO", cx));
1165            search_view.search(cx);
1166        });
1167        deterministic.run_until_parked();
1168        search_view.update(cx, |search_view, cx| {
1169            assert_eq!(
1170                search_view
1171                    .results_editor
1172                    .update(cx, |editor, cx| editor.display_text(cx)),
1173                "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;"
1174            );
1175            assert_eq!(
1176                search_view
1177                    .results_editor
1178                    .update(cx, |editor, cx| editor.all_background_highlights(cx)),
1179                &[
1180                    (
1181                        DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35),
1182                        Color::red()
1183                    ),
1184                    (
1185                        DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40),
1186                        Color::red()
1187                    ),
1188                    (
1189                        DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9),
1190                        Color::red()
1191                    )
1192                ]
1193            );
1194            assert_eq!(search_view.active_match_index, Some(0));
1195            assert_eq!(
1196                search_view
1197                    .results_editor
1198                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1199                [DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35)]
1200            );
1201
1202            search_view.select_match(Direction::Next, cx);
1203        });
1204
1205        search_view.update(cx, |search_view, cx| {
1206            assert_eq!(search_view.active_match_index, Some(1));
1207            assert_eq!(
1208                search_view
1209                    .results_editor
1210                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1211                [DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40)]
1212            );
1213            search_view.select_match(Direction::Next, cx);
1214        });
1215
1216        search_view.update(cx, |search_view, cx| {
1217            assert_eq!(search_view.active_match_index, Some(2));
1218            assert_eq!(
1219                search_view
1220                    .results_editor
1221                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1222                [DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9)]
1223            );
1224            search_view.select_match(Direction::Next, cx);
1225        });
1226
1227        search_view.update(cx, |search_view, cx| {
1228            assert_eq!(search_view.active_match_index, Some(0));
1229            assert_eq!(
1230                search_view
1231                    .results_editor
1232                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1233                [DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35)]
1234            );
1235            search_view.select_match(Direction::Prev, cx);
1236        });
1237
1238        search_view.update(cx, |search_view, cx| {
1239            assert_eq!(search_view.active_match_index, Some(2));
1240            assert_eq!(
1241                search_view
1242                    .results_editor
1243                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1244                [DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9)]
1245            );
1246            search_view.select_match(Direction::Prev, cx);
1247        });
1248
1249        search_view.update(cx, |search_view, cx| {
1250            assert_eq!(search_view.active_match_index, Some(1));
1251            assert_eq!(
1252                search_view
1253                    .results_editor
1254                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1255                [DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40)]
1256            );
1257        });
1258    }
1259
1260    #[gpui::test]
1261    async fn test_project_search_focus(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
1262        init_test(cx);
1263
1264        let fs = FakeFs::new(cx.background());
1265        fs.insert_tree(
1266            "/dir",
1267            json!({
1268                "one.rs": "const ONE: usize = 1;",
1269                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
1270                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
1271                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
1272            }),
1273        )
1274        .await;
1275        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
1276        let (window_id, workspace) = cx.add_window(|cx| Workspace::test_new(project, cx));
1277
1278        let active_item = cx.read(|cx| {
1279            workspace
1280                .read(cx)
1281                .active_pane()
1282                .read(cx)
1283                .active_item()
1284                .and_then(|item| item.downcast::<ProjectSearchView>())
1285        });
1286        assert!(
1287            active_item.is_none(),
1288            "Expected no search panel to be active, but got: {active_item:?}"
1289        );
1290
1291        workspace.update(cx, |workspace, cx| {
1292            ProjectSearchView::deploy(workspace, &workspace::NewSearch, cx)
1293        });
1294
1295        let Some(search_view) = cx.read(|cx| {
1296            workspace
1297                .read(cx)
1298                .active_pane()
1299                .read(cx)
1300                .active_item()
1301                .and_then(|item| item.downcast::<ProjectSearchView>())
1302        }) else {
1303            panic!("Search view expected to appear after new search event trigger")
1304        };
1305        let search_view_id = search_view.id();
1306
1307        cx.spawn(
1308            |mut cx| async move { cx.dispatch_action(window_id, search_view_id, &ToggleFocus) },
1309        )
1310        .detach();
1311        deterministic.run_until_parked();
1312        search_view.update(cx, |search_view, cx| {
1313            assert!(
1314                search_view.query_editor.is_focused(cx),
1315                "Empty search view should be focused after the toggle focus event: no results panel to focus on",
1316            );
1317        });
1318
1319        search_view.update(cx, |search_view, cx| {
1320            let query_editor = &search_view.query_editor;
1321            assert!(
1322                query_editor.is_focused(cx),
1323                "Search view should be focused after the new search view is activated",
1324            );
1325            let query_text = query_editor.read(cx).text(cx);
1326            assert!(
1327                query_text.is_empty(),
1328                "New search query should be empty but got '{query_text}'",
1329            );
1330            let results_text = search_view
1331                .results_editor
1332                .update(cx, |editor, cx| editor.display_text(cx));
1333            assert!(
1334                results_text.is_empty(),
1335                "Empty search view should have no results but got '{results_text}'"
1336            );
1337        });
1338
1339        search_view.update(cx, |search_view, cx| {
1340            search_view.query_editor.update(cx, |query_editor, cx| {
1341                query_editor.set_text("sOMETHINGtHATsURELYdOESnOTeXIST", cx)
1342            });
1343            search_view.search(cx);
1344        });
1345        deterministic.run_until_parked();
1346        search_view.update(cx, |search_view, cx| {
1347            let results_text = search_view
1348                .results_editor
1349                .update(cx, |editor, cx| editor.display_text(cx));
1350            assert!(
1351                results_text.is_empty(),
1352                "Search view for mismatching query should have no results but got '{results_text}'"
1353            );
1354            assert!(
1355                search_view.query_editor.is_focused(cx),
1356                "Search view should be focused after mismatching query had been used in search",
1357            );
1358        });
1359        cx.spawn(
1360            |mut cx| async move { cx.dispatch_action(window_id, search_view_id, &ToggleFocus) },
1361        )
1362        .detach();
1363        deterministic.run_until_parked();
1364        search_view.update(cx, |search_view, cx| {
1365            assert!(
1366                search_view.query_editor.is_focused(cx),
1367                "Search view with mismatching query should be focused after the toggle focus event: still no results panel to focus on",
1368            );
1369        });
1370
1371        search_view.update(cx, |search_view, cx| {
1372            search_view
1373                .query_editor
1374                .update(cx, |query_editor, cx| query_editor.set_text("TWO", cx));
1375            search_view.search(cx);
1376        });
1377        deterministic.run_until_parked();
1378        search_view.update(cx, |search_view, cx| {
1379            assert_eq!(
1380                search_view
1381                    .results_editor
1382                    .update(cx, |editor, cx| editor.display_text(cx)),
1383                "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
1384                "Search view results should match the query"
1385            );
1386            assert!(
1387                search_view.results_editor.is_focused(cx),
1388                "Search view with mismatching query should be focused after search results are available",
1389            );
1390        });
1391        cx.spawn(
1392            |mut cx| async move { cx.dispatch_action(window_id, search_view_id, &ToggleFocus) },
1393        )
1394        .detach();
1395        deterministic.run_until_parked();
1396        search_view.update(cx, |search_view, cx| {
1397            assert!(
1398                search_view.results_editor.is_focused(cx),
1399                "Search view with matching query should still have its results editor focused after the toggle focus event",
1400            );
1401        });
1402
1403        workspace.update(cx, |workspace, cx| {
1404            ProjectSearchView::deploy(workspace, &workspace::NewSearch, cx)
1405        });
1406        search_view.update(cx, |search_view, cx| {
1407            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");
1408            assert_eq!(
1409                search_view
1410                    .results_editor
1411                    .update(cx, |editor, cx| editor.display_text(cx)),
1412                "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
1413                "Results should be unchanged after search view 2nd open in a row"
1414            );
1415            assert!(
1416                search_view.query_editor.is_focused(cx),
1417                "Focus should be moved into query editor again after search view 2nd open in a row"
1418            );
1419        });
1420
1421        cx.spawn(
1422            |mut cx| async move { cx.dispatch_action(window_id, search_view_id, &ToggleFocus) },
1423        )
1424        .detach();
1425        deterministic.run_until_parked();
1426        search_view.update(cx, |search_view, cx| {
1427            assert!(
1428                search_view.results_editor.is_focused(cx),
1429                "Search view with matching query should switch focus to the results editor after the toggle focus event",
1430            );
1431        });
1432    }
1433
1434    pub fn init_test(cx: &mut TestAppContext) {
1435        cx.foreground().forbid_parking();
1436        let fonts = cx.font_cache();
1437        let mut theme = gpui::fonts::with_font_cache(fonts.clone(), theme::Theme::default);
1438        theme.search.match_background = Color::red();
1439
1440        cx.update(|cx| {
1441            cx.set_global(SettingsStore::test(cx));
1442            cx.set_global(ActiveSearches::default());
1443
1444            theme::init((), cx);
1445            cx.update_global::<SettingsStore, _, _>(|store, _| {
1446                let mut settings = store.get::<ThemeSettings>(None).clone();
1447                settings.theme = Arc::new(theme);
1448                store.override_global(settings)
1449            });
1450
1451            language::init(cx);
1452            client::init_settings(cx);
1453            editor::init(cx);
1454            workspace::init_settings(cx);
1455            Project::init_settings(cx);
1456            super::init(cx);
1457        });
1458    }
1459}