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::{Not, 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        let query_text = self.query_editor.read(cx).text(cx);
 246
 247        query_text
 248            .is_empty()
 249            .not()
 250            .then(|| query_text.into())
 251            .or_else(|| Some("Project Search".into()))
 252    }
 253
 254    fn act_as_type<'a>(
 255        &'a self,
 256        type_id: TypeId,
 257        self_handle: &'a ViewHandle<Self>,
 258        _: &'a AppContext,
 259    ) -> Option<&'a AnyViewHandle> {
 260        if type_id == TypeId::of::<Self>() {
 261            Some(self_handle)
 262        } else if type_id == TypeId::of::<Editor>() {
 263            Some(&self.results_editor)
 264        } else {
 265            None
 266        }
 267    }
 268
 269    fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
 270        self.results_editor
 271            .update(cx, |editor, cx| editor.deactivated(cx));
 272    }
 273
 274    fn tab_content<T: View>(
 275        &self,
 276        _detail: Option<usize>,
 277        tab_theme: &theme::Tab,
 278        cx: &AppContext,
 279    ) -> AnyElement<T> {
 280        Flex::row()
 281            .with_child(
 282                Svg::new("icons/magnifying_glass_12.svg")
 283                    .with_color(tab_theme.label.text.color)
 284                    .constrained()
 285                    .with_width(tab_theme.type_icon_width)
 286                    .aligned()
 287                    .contained()
 288                    .with_margin_right(tab_theme.spacing),
 289            )
 290            .with_children(self.model.read(cx).active_query.as_ref().map(|query| {
 291                let query_text = util::truncate_and_trailoff(query.as_str(), MAX_TAB_TITLE_LEN);
 292
 293                Label::new(query_text, tab_theme.label.clone()).aligned()
 294            }))
 295            .into_any()
 296    }
 297
 298    fn for_each_project_item(&self, cx: &AppContext, f: &mut dyn FnMut(usize, &dyn project::Item)) {
 299        self.results_editor.for_each_project_item(cx, f)
 300    }
 301
 302    fn is_singleton(&self, _: &AppContext) -> bool {
 303        false
 304    }
 305
 306    fn can_save(&self, _: &AppContext) -> bool {
 307        true
 308    }
 309
 310    fn is_dirty(&self, cx: &AppContext) -> bool {
 311        self.results_editor.read(cx).is_dirty(cx)
 312    }
 313
 314    fn has_conflict(&self, cx: &AppContext) -> bool {
 315        self.results_editor.read(cx).has_conflict(cx)
 316    }
 317
 318    fn save(
 319        &mut self,
 320        project: ModelHandle<Project>,
 321        cx: &mut ViewContext<Self>,
 322    ) -> Task<anyhow::Result<()>> {
 323        self.results_editor
 324            .update(cx, |editor, cx| editor.save(project, cx))
 325    }
 326
 327    fn save_as(
 328        &mut self,
 329        _: ModelHandle<Project>,
 330        _: PathBuf,
 331        _: &mut ViewContext<Self>,
 332    ) -> Task<anyhow::Result<()>> {
 333        unreachable!("save_as should not have been called")
 334    }
 335
 336    fn reload(
 337        &mut self,
 338        project: ModelHandle<Project>,
 339        cx: &mut ViewContext<Self>,
 340    ) -> Task<anyhow::Result<()>> {
 341        self.results_editor
 342            .update(cx, |editor, cx| editor.reload(project, cx))
 343    }
 344
 345    fn clone_on_split(&self, _workspace_id: WorkspaceId, cx: &mut ViewContext<Self>) -> Option<Self>
 346    where
 347        Self: Sized,
 348    {
 349        let model = self.model.update(cx, |model, cx| model.clone(cx));
 350        Some(Self::new(model, cx))
 351    }
 352
 353    fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
 354        self.results_editor
 355            .update(cx, |editor, cx| editor.added_to_workspace(workspace, cx));
 356    }
 357
 358    fn set_nav_history(&mut self, nav_history: ItemNavHistory, cx: &mut ViewContext<Self>) {
 359        self.results_editor.update(cx, |editor, _| {
 360            editor.set_nav_history(Some(nav_history));
 361        });
 362    }
 363
 364    fn navigate(&mut self, data: Box<dyn Any>, cx: &mut ViewContext<Self>) -> bool {
 365        self.results_editor
 366            .update(cx, |editor, cx| editor.navigate(data, cx))
 367    }
 368
 369    fn to_item_events(event: &Self::Event) -> SmallVec<[ItemEvent; 2]> {
 370        match event {
 371            ViewEvent::UpdateTab => {
 372                smallvec::smallvec![ItemEvent::UpdateBreadcrumbs, ItemEvent::UpdateTab]
 373            }
 374            ViewEvent::EditorEvent(editor_event) => Editor::to_item_events(editor_event),
 375            _ => SmallVec::new(),
 376        }
 377    }
 378
 379    fn breadcrumb_location(&self) -> ToolbarItemLocation {
 380        if self.has_matches() {
 381            ToolbarItemLocation::Secondary
 382        } else {
 383            ToolbarItemLocation::Hidden
 384        }
 385    }
 386
 387    fn breadcrumbs(&self, theme: &theme::Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
 388        self.results_editor.breadcrumbs(theme, cx)
 389    }
 390
 391    fn serialized_item_kind() -> Option<&'static str> {
 392        None
 393    }
 394
 395    fn deserialize(
 396        _project: ModelHandle<Project>,
 397        _workspace: WeakViewHandle<Workspace>,
 398        _workspace_id: workspace::WorkspaceId,
 399        _item_id: workspace::ItemId,
 400        _cx: &mut ViewContext<Pane>,
 401    ) -> Task<anyhow::Result<ViewHandle<Self>>> {
 402        unimplemented!()
 403    }
 404}
 405
 406impl ProjectSearchView {
 407    fn new(model: ModelHandle<ProjectSearch>, cx: &mut ViewContext<Self>) -> Self {
 408        let project;
 409        let excerpts;
 410        let mut query_text = String::new();
 411        let mut regex = false;
 412        let mut case_sensitive = false;
 413        let mut whole_word = false;
 414
 415        {
 416            let model = model.read(cx);
 417            project = model.project.clone();
 418            excerpts = model.excerpts.clone();
 419            if let Some(active_query) = model.active_query.as_ref() {
 420                query_text = active_query.as_str().to_string();
 421                regex = active_query.is_regex();
 422                case_sensitive = active_query.case_sensitive();
 423                whole_word = active_query.whole_word();
 424            }
 425        }
 426        cx.observe(&model, |this, _, cx| this.model_changed(cx))
 427            .detach();
 428
 429        let query_editor = cx.add_view(|cx| {
 430            let mut editor = Editor::single_line(
 431                Some(Arc::new(|theme| theme.search.editor.input.clone())),
 432                cx,
 433            );
 434            editor.set_text(query_text, cx);
 435            editor
 436        });
 437        // Subscribe to query_editor in order to reraise editor events for workspace item activation purposes
 438        cx.subscribe(&query_editor, |_, _, event, cx| {
 439            cx.emit(ViewEvent::EditorEvent(event.clone()))
 440        })
 441        .detach();
 442
 443        let results_editor = cx.add_view(|cx| {
 444            let mut editor = Editor::for_multibuffer(excerpts, Some(project), cx);
 445            editor.set_searchable(false);
 446            editor
 447        });
 448        cx.observe(&results_editor, |_, _, cx| cx.emit(ViewEvent::UpdateTab))
 449            .detach();
 450
 451        cx.subscribe(&results_editor, |this, _, event, cx| {
 452            if matches!(event, editor::Event::SelectionsChanged { .. }) {
 453                this.update_match_index(cx);
 454            }
 455            // Reraise editor events for workspace item activation purposes
 456            cx.emit(ViewEvent::EditorEvent(event.clone()));
 457        })
 458        .detach();
 459
 460        let included_files_editor = cx.add_view(|cx| {
 461            let mut editor = Editor::single_line(
 462                Some(Arc::new(|theme| {
 463                    theme.search.include_exclude_editor.input.clone()
 464                })),
 465                cx,
 466            );
 467            editor.set_placeholder_text("Include: crates/**/*.toml", cx);
 468
 469            editor
 470        });
 471        // Subscribe to include_files_editor in order to reraise editor events for workspace item activation purposes
 472        cx.subscribe(&included_files_editor, |_, _, event, cx| {
 473            cx.emit(ViewEvent::EditorEvent(event.clone()))
 474        })
 475        .detach();
 476
 477        let excluded_files_editor = cx.add_view(|cx| {
 478            let mut editor = Editor::single_line(
 479                Some(Arc::new(|theme| {
 480                    theme.search.include_exclude_editor.input.clone()
 481                })),
 482                cx,
 483            );
 484            editor.set_placeholder_text("Exclude: vendor/*, *.lock", cx);
 485
 486            editor
 487        });
 488        // Subscribe to excluded_files_editor in order to reraise editor events for workspace item activation purposes
 489        cx.subscribe(&excluded_files_editor, |_, _, event, cx| {
 490            cx.emit(ViewEvent::EditorEvent(event.clone()))
 491        })
 492        .detach();
 493
 494        let mut this = ProjectSearchView {
 495            search_id: model.read(cx).search_id,
 496            model,
 497            query_editor,
 498            results_editor,
 499            case_sensitive,
 500            whole_word,
 501            regex,
 502            panels_with_errors: HashSet::new(),
 503            active_match_index: None,
 504            query_editor_was_focused: false,
 505            included_files_editor,
 506            excluded_files_editor,
 507        };
 508        this.model_changed(cx);
 509        this
 510    }
 511
 512    // Re-activate the most recently activated search or the most recent if it has been closed.
 513    // If no search exists in the workspace, create a new one.
 514    fn deploy(
 515        workspace: &mut Workspace,
 516        _: &workspace::NewSearch,
 517        cx: &mut ViewContext<Workspace>,
 518    ) {
 519        // Clean up entries for dropped projects
 520        cx.update_global(|state: &mut ActiveSearches, cx| {
 521            state.0.retain(|project, _| project.is_upgradable(cx))
 522        });
 523
 524        let active_search = cx
 525            .global::<ActiveSearches>()
 526            .0
 527            .get(&workspace.project().downgrade());
 528
 529        let existing = active_search
 530            .and_then(|active_search| {
 531                workspace
 532                    .items_of_type::<ProjectSearchView>(cx)
 533                    .find(|search| search == active_search)
 534            })
 535            .or_else(|| workspace.item_of_type::<ProjectSearchView>(cx));
 536
 537        let query = workspace.active_item(cx).and_then(|item| {
 538            let editor = item.act_as::<Editor>(cx)?;
 539            let query = editor.query_suggestion(cx);
 540            if query.is_empty() {
 541                None
 542            } else {
 543                Some(query)
 544            }
 545        });
 546
 547        let search = if let Some(existing) = existing {
 548            workspace.activate_item(&existing, cx);
 549            existing
 550        } else {
 551            let model = cx.add_model(|cx| ProjectSearch::new(workspace.project().clone(), cx));
 552            let view = cx.add_view(|cx| ProjectSearchView::new(model, cx));
 553            workspace.add_item(Box::new(view.clone()), cx);
 554            view
 555        };
 556
 557        search.update(cx, |search, cx| {
 558            if let Some(query) = query {
 559                search.set_query(&query, cx);
 560            }
 561            search.focus_query_editor(cx)
 562        });
 563    }
 564
 565    fn search(&mut self, cx: &mut ViewContext<Self>) {
 566        if let Some(query) = self.build_search_query(cx) {
 567            self.model.update(cx, |model, cx| model.search(query, cx));
 568        }
 569    }
 570
 571    fn build_search_query(&mut self, cx: &mut ViewContext<Self>) -> Option<SearchQuery> {
 572        let text = self.query_editor.read(cx).text(cx);
 573        let included_files =
 574            match Self::load_glob_set(&self.included_files_editor.read(cx).text(cx)) {
 575                Ok(included_files) => {
 576                    self.panels_with_errors.remove(&InputPanel::Include);
 577                    included_files
 578                }
 579                Err(_e) => {
 580                    self.panels_with_errors.insert(InputPanel::Include);
 581                    cx.notify();
 582                    return None;
 583                }
 584            };
 585        let excluded_files =
 586            match Self::load_glob_set(&self.excluded_files_editor.read(cx).text(cx)) {
 587                Ok(excluded_files) => {
 588                    self.panels_with_errors.remove(&InputPanel::Exclude);
 589                    excluded_files
 590                }
 591                Err(_e) => {
 592                    self.panels_with_errors.insert(InputPanel::Exclude);
 593                    cx.notify();
 594                    return None;
 595                }
 596            };
 597        if self.regex {
 598            match SearchQuery::regex(
 599                text,
 600                self.whole_word,
 601                self.case_sensitive,
 602                included_files,
 603                excluded_files,
 604            ) {
 605                Ok(query) => {
 606                    self.panels_with_errors.remove(&InputPanel::Query);
 607                    Some(query)
 608                }
 609                Err(_e) => {
 610                    self.panels_with_errors.insert(InputPanel::Query);
 611                    cx.notify();
 612                    None
 613                }
 614            }
 615        } else {
 616            Some(SearchQuery::text(
 617                text,
 618                self.whole_word,
 619                self.case_sensitive,
 620                included_files,
 621                excluded_files,
 622            ))
 623        }
 624    }
 625
 626    fn load_glob_set(text: &str) -> Result<Vec<GlobMatcher>> {
 627        text.split(',')
 628            .map(str::trim)
 629            .filter(|glob_str| !glob_str.is_empty())
 630            .map(|glob_str| anyhow::Ok(Glob::new(glob_str)?.compile_matcher()))
 631            .collect()
 632    }
 633
 634    fn select_match(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 635        if let Some(index) = self.active_match_index {
 636            let match_ranges = self.model.read(cx).match_ranges.clone();
 637            let new_index = self.results_editor.update(cx, |editor, cx| {
 638                editor.match_index_for_direction(&match_ranges, index, direction, cx)
 639            });
 640
 641            let range_to_select = match_ranges[new_index].clone();
 642            self.results_editor.update(cx, |editor, cx| {
 643                editor.unfold_ranges([range_to_select.clone()], false, true, cx);
 644                editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 645                    s.select_ranges([range_to_select])
 646                });
 647            });
 648        }
 649    }
 650
 651    fn focus_query_editor(&mut self, cx: &mut ViewContext<Self>) {
 652        self.query_editor.update(cx, |query_editor, cx| {
 653            query_editor.select_all(&SelectAll, cx);
 654        });
 655        self.query_editor_was_focused = true;
 656        cx.focus(&self.query_editor);
 657    }
 658
 659    fn set_query(&mut self, query: &str, cx: &mut ViewContext<Self>) {
 660        self.query_editor
 661            .update(cx, |query_editor, cx| query_editor.set_text(query, cx));
 662    }
 663
 664    fn focus_results_editor(&mut self, cx: &mut ViewContext<Self>) {
 665        self.query_editor.update(cx, |query_editor, cx| {
 666            let cursor = query_editor.selections.newest_anchor().head();
 667            query_editor.change_selections(None, cx, |s| s.select_ranges([cursor.clone()..cursor]));
 668        });
 669        self.query_editor_was_focused = false;
 670        cx.focus(&self.results_editor);
 671    }
 672
 673    fn model_changed(&mut self, cx: &mut ViewContext<Self>) {
 674        let match_ranges = self.model.read(cx).match_ranges.clone();
 675        if match_ranges.is_empty() {
 676            self.active_match_index = None;
 677        } else {
 678            self.active_match_index = Some(0);
 679            self.select_match(Direction::Next, cx);
 680            self.update_match_index(cx);
 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.inactive_state().style_for(state);
 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
 934                .search
 935                .option_button
 936                .in_state(is_active)
 937                .style_for(state);
 938            Label::new(icon, style.text.clone())
 939                .contained()
 940                .with_style(style.container)
 941        })
 942        .on_click(MouseButton::Left, move |_, this, cx| {
 943            this.toggle_search_option(option, cx);
 944        })
 945        .with_cursor_style(CursorStyle::PointingHand)
 946        .with_tooltip::<Self>(
 947            option as usize,
 948            format!("Toggle {}", option.label()),
 949            Some(option.to_toggle_action()),
 950            tooltip_style,
 951            cx,
 952        )
 953        .into_any()
 954    }
 955
 956    fn is_option_enabled(&self, option: SearchOption, cx: &AppContext) -> bool {
 957        if let Some(search) = self.active_project_search.as_ref() {
 958            let search = search.read(cx);
 959            match option {
 960                SearchOption::WholeWord => search.whole_word,
 961                SearchOption::CaseSensitive => search.case_sensitive,
 962                SearchOption::Regex => search.regex,
 963            }
 964        } else {
 965            false
 966        }
 967    }
 968}
 969
 970impl Entity for ProjectSearchBar {
 971    type Event = ();
 972}
 973
 974impl View for ProjectSearchBar {
 975    fn ui_name() -> &'static str {
 976        "ProjectSearchBar"
 977    }
 978
 979    fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
 980        if let Some(search) = self.active_project_search.as_ref() {
 981            let search = search.read(cx);
 982            let theme = theme::current(cx).clone();
 983            let query_container_style = if search.panels_with_errors.contains(&InputPanel::Query) {
 984                theme.search.invalid_editor
 985            } else {
 986                theme.search.editor.input.container
 987            };
 988            let include_container_style =
 989                if search.panels_with_errors.contains(&InputPanel::Include) {
 990                    theme.search.invalid_include_exclude_editor
 991                } else {
 992                    theme.search.include_exclude_editor.input.container
 993                };
 994            let exclude_container_style =
 995                if search.panels_with_errors.contains(&InputPanel::Exclude) {
 996                    theme.search.invalid_include_exclude_editor
 997                } else {
 998                    theme.search.include_exclude_editor.input.container
 999                };
1000
1001            let included_files_view = ChildView::new(&search.included_files_editor, cx)
1002                .aligned()
1003                .left()
1004                .flex(1.0, true);
1005            let excluded_files_view = ChildView::new(&search.excluded_files_editor, cx)
1006                .aligned()
1007                .right()
1008                .flex(1.0, true);
1009
1010            let row_spacing = theme.workspace.toolbar.container.padding.bottom;
1011
1012            Flex::column()
1013                .with_child(
1014                    Flex::row()
1015                        .with_child(
1016                            Flex::row()
1017                                .with_child(
1018                                    ChildView::new(&search.query_editor, cx)
1019                                        .aligned()
1020                                        .left()
1021                                        .flex(1., true),
1022                                )
1023                                .with_children(search.active_match_index.map(|match_ix| {
1024                                    Label::new(
1025                                        format!(
1026                                            "{}/{}",
1027                                            match_ix + 1,
1028                                            search.model.read(cx).match_ranges.len()
1029                                        ),
1030                                        theme.search.match_index.text.clone(),
1031                                    )
1032                                    .contained()
1033                                    .with_style(theme.search.match_index.container)
1034                                    .aligned()
1035                                }))
1036                                .contained()
1037                                .with_style(query_container_style)
1038                                .aligned()
1039                                .constrained()
1040                                .with_min_width(theme.search.editor.min_width)
1041                                .with_max_width(theme.search.editor.max_width)
1042                                .flex(1., false),
1043                        )
1044                        .with_child(
1045                            Flex::row()
1046                                .with_child(self.render_nav_button("<", Direction::Prev, cx))
1047                                .with_child(self.render_nav_button(">", Direction::Next, cx))
1048                                .aligned(),
1049                        )
1050                        .with_child(
1051                            Flex::row()
1052                                .with_child(self.render_option_button(
1053                                    "Case",
1054                                    SearchOption::CaseSensitive,
1055                                    cx,
1056                                ))
1057                                .with_child(self.render_option_button(
1058                                    "Word",
1059                                    SearchOption::WholeWord,
1060                                    cx,
1061                                ))
1062                                .with_child(self.render_option_button(
1063                                    "Regex",
1064                                    SearchOption::Regex,
1065                                    cx,
1066                                ))
1067                                .contained()
1068                                .with_style(theme.search.option_button_group)
1069                                .aligned(),
1070                        )
1071                        .contained()
1072                        .with_margin_bottom(row_spacing),
1073                )
1074                .with_child(
1075                    Flex::row()
1076                        .with_child(
1077                            Flex::row()
1078                                .with_child(included_files_view)
1079                                .contained()
1080                                .with_style(include_container_style)
1081                                .aligned()
1082                                .constrained()
1083                                .with_min_width(theme.search.include_exclude_editor.min_width)
1084                                .with_max_width(theme.search.include_exclude_editor.max_width)
1085                                .flex(1., false),
1086                        )
1087                        .with_child(
1088                            Flex::row()
1089                                .with_child(excluded_files_view)
1090                                .contained()
1091                                .with_style(exclude_container_style)
1092                                .aligned()
1093                                .constrained()
1094                                .with_min_width(theme.search.include_exclude_editor.min_width)
1095                                .with_max_width(theme.search.include_exclude_editor.max_width)
1096                                .flex(1., false),
1097                        ),
1098                )
1099                .contained()
1100                .with_style(theme.search.container)
1101                .aligned()
1102                .left()
1103                .into_any_named("project search")
1104        } else {
1105            Empty::new().into_any()
1106        }
1107    }
1108}
1109
1110impl ToolbarItemView for ProjectSearchBar {
1111    fn set_active_pane_item(
1112        &mut self,
1113        active_pane_item: Option<&dyn ItemHandle>,
1114        cx: &mut ViewContext<Self>,
1115    ) -> ToolbarItemLocation {
1116        cx.notify();
1117        self.subscription = None;
1118        self.active_project_search = None;
1119        if let Some(search) = active_pane_item.and_then(|i| i.downcast::<ProjectSearchView>()) {
1120            self.subscription = Some(cx.observe(&search, |_, _, cx| cx.notify()));
1121            self.active_project_search = Some(search);
1122            ToolbarItemLocation::PrimaryLeft {
1123                flex: Some((1., false)),
1124            }
1125        } else {
1126            ToolbarItemLocation::Hidden
1127        }
1128    }
1129
1130    fn row_count(&self) -> usize {
1131        2
1132    }
1133}
1134
1135#[cfg(test)]
1136pub mod tests {
1137    use super::*;
1138    use editor::DisplayPoint;
1139    use gpui::{color::Color, executor::Deterministic, TestAppContext};
1140    use project::FakeFs;
1141    use serde_json::json;
1142    use settings::SettingsStore;
1143    use std::sync::Arc;
1144    use theme::ThemeSettings;
1145
1146    #[gpui::test]
1147    async fn test_project_search(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
1148        init_test(cx);
1149
1150        let fs = FakeFs::new(cx.background());
1151        fs.insert_tree(
1152            "/dir",
1153            json!({
1154                "one.rs": "const ONE: usize = 1;",
1155                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
1156                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
1157                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
1158            }),
1159        )
1160        .await;
1161        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
1162        let search = cx.add_model(|cx| ProjectSearch::new(project, cx));
1163        let (_, search_view) = cx.add_window(|cx| ProjectSearchView::new(search.clone(), cx));
1164
1165        search_view.update(cx, |search_view, cx| {
1166            search_view
1167                .query_editor
1168                .update(cx, |query_editor, cx| query_editor.set_text("TWO", cx));
1169            search_view.search(cx);
1170        });
1171        deterministic.run_until_parked();
1172        search_view.update(cx, |search_view, cx| {
1173            assert_eq!(
1174                search_view
1175                    .results_editor
1176                    .update(cx, |editor, cx| editor.display_text(cx)),
1177                "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;"
1178            );
1179            assert_eq!(
1180                search_view
1181                    .results_editor
1182                    .update(cx, |editor, cx| editor.all_background_highlights(cx)),
1183                &[
1184                    (
1185                        DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35),
1186                        Color::red()
1187                    ),
1188                    (
1189                        DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40),
1190                        Color::red()
1191                    ),
1192                    (
1193                        DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9),
1194                        Color::red()
1195                    )
1196                ]
1197            );
1198            assert_eq!(search_view.active_match_index, Some(0));
1199            assert_eq!(
1200                search_view
1201                    .results_editor
1202                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1203                [DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35)]
1204            );
1205
1206            search_view.select_match(Direction::Next, cx);
1207        });
1208
1209        search_view.update(cx, |search_view, cx| {
1210            assert_eq!(search_view.active_match_index, Some(1));
1211            assert_eq!(
1212                search_view
1213                    .results_editor
1214                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1215                [DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40)]
1216            );
1217            search_view.select_match(Direction::Next, cx);
1218        });
1219
1220        search_view.update(cx, |search_view, cx| {
1221            assert_eq!(search_view.active_match_index, Some(2));
1222            assert_eq!(
1223                search_view
1224                    .results_editor
1225                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1226                [DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9)]
1227            );
1228            search_view.select_match(Direction::Next, cx);
1229        });
1230
1231        search_view.update(cx, |search_view, cx| {
1232            assert_eq!(search_view.active_match_index, Some(0));
1233            assert_eq!(
1234                search_view
1235                    .results_editor
1236                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1237                [DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35)]
1238            );
1239            search_view.select_match(Direction::Prev, cx);
1240        });
1241
1242        search_view.update(cx, |search_view, cx| {
1243            assert_eq!(search_view.active_match_index, Some(2));
1244            assert_eq!(
1245                search_view
1246                    .results_editor
1247                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1248                [DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9)]
1249            );
1250            search_view.select_match(Direction::Prev, cx);
1251        });
1252
1253        search_view.update(cx, |search_view, cx| {
1254            assert_eq!(search_view.active_match_index, Some(1));
1255            assert_eq!(
1256                search_view
1257                    .results_editor
1258                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1259                [DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40)]
1260            );
1261        });
1262    }
1263
1264    #[gpui::test]
1265    async fn test_project_search_focus(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
1266        init_test(cx);
1267
1268        let fs = FakeFs::new(cx.background());
1269        fs.insert_tree(
1270            "/dir",
1271            json!({
1272                "one.rs": "const ONE: usize = 1;",
1273                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
1274                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
1275                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
1276            }),
1277        )
1278        .await;
1279        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
1280        let (window_id, workspace) = cx.add_window(|cx| Workspace::test_new(project, cx));
1281
1282        let active_item = cx.read(|cx| {
1283            workspace
1284                .read(cx)
1285                .active_pane()
1286                .read(cx)
1287                .active_item()
1288                .and_then(|item| item.downcast::<ProjectSearchView>())
1289        });
1290        assert!(
1291            active_item.is_none(),
1292            "Expected no search panel to be active, but got: {active_item:?}"
1293        );
1294
1295        workspace.update(cx, |workspace, cx| {
1296            ProjectSearchView::deploy(workspace, &workspace::NewSearch, cx)
1297        });
1298
1299        let Some(search_view) = cx.read(|cx| {
1300            workspace
1301                .read(cx)
1302                .active_pane()
1303                .read(cx)
1304                .active_item()
1305                .and_then(|item| item.downcast::<ProjectSearchView>())
1306        }) else {
1307            panic!("Search view expected to appear after new search event trigger")
1308        };
1309        let search_view_id = search_view.id();
1310
1311        cx.spawn(
1312            |mut cx| async move { cx.dispatch_action(window_id, search_view_id, &ToggleFocus) },
1313        )
1314        .detach();
1315        deterministic.run_until_parked();
1316        search_view.update(cx, |search_view, cx| {
1317            assert!(
1318                search_view.query_editor.is_focused(cx),
1319                "Empty search view should be focused after the toggle focus event: no results panel to focus on",
1320            );
1321        });
1322
1323        search_view.update(cx, |search_view, cx| {
1324            let query_editor = &search_view.query_editor;
1325            assert!(
1326                query_editor.is_focused(cx),
1327                "Search view should be focused after the new search view is activated",
1328            );
1329            let query_text = query_editor.read(cx).text(cx);
1330            assert!(
1331                query_text.is_empty(),
1332                "New search query should be empty but got '{query_text}'",
1333            );
1334            let results_text = search_view
1335                .results_editor
1336                .update(cx, |editor, cx| editor.display_text(cx));
1337            assert!(
1338                results_text.is_empty(),
1339                "Empty search view should have no results but got '{results_text}'"
1340            );
1341        });
1342
1343        search_view.update(cx, |search_view, cx| {
1344            search_view.query_editor.update(cx, |query_editor, cx| {
1345                query_editor.set_text("sOMETHINGtHATsURELYdOESnOTeXIST", cx)
1346            });
1347            search_view.search(cx);
1348        });
1349        deterministic.run_until_parked();
1350        search_view.update(cx, |search_view, cx| {
1351            let results_text = search_view
1352                .results_editor
1353                .update(cx, |editor, cx| editor.display_text(cx));
1354            assert!(
1355                results_text.is_empty(),
1356                "Search view for mismatching query should have no results but got '{results_text}'"
1357            );
1358            assert!(
1359                search_view.query_editor.is_focused(cx),
1360                "Search view should be focused after mismatching query had been used in search",
1361            );
1362        });
1363        cx.spawn(
1364            |mut cx| async move { cx.dispatch_action(window_id, search_view_id, &ToggleFocus) },
1365        )
1366        .detach();
1367        deterministic.run_until_parked();
1368        search_view.update(cx, |search_view, cx| {
1369            assert!(
1370                search_view.query_editor.is_focused(cx),
1371                "Search view with mismatching query should be focused after the toggle focus event: still no results panel to focus on",
1372            );
1373        });
1374
1375        search_view.update(cx, |search_view, cx| {
1376            search_view
1377                .query_editor
1378                .update(cx, |query_editor, cx| query_editor.set_text("TWO", cx));
1379            search_view.search(cx);
1380        });
1381        deterministic.run_until_parked();
1382        search_view.update(cx, |search_view, cx| {
1383            assert_eq!(
1384                search_view
1385                    .results_editor
1386                    .update(cx, |editor, cx| editor.display_text(cx)),
1387                "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
1388                "Search view results should match the query"
1389            );
1390            assert!(
1391                search_view.results_editor.is_focused(cx),
1392                "Search view with mismatching query should be focused after search results are available",
1393            );
1394        });
1395        cx.spawn(
1396            |mut cx| async move { cx.dispatch_action(window_id, search_view_id, &ToggleFocus) },
1397        )
1398        .detach();
1399        deterministic.run_until_parked();
1400        search_view.update(cx, |search_view, cx| {
1401            assert!(
1402                search_view.results_editor.is_focused(cx),
1403                "Search view with matching query should still have its results editor focused after the toggle focus event",
1404            );
1405        });
1406
1407        workspace.update(cx, |workspace, cx| {
1408            ProjectSearchView::deploy(workspace, &workspace::NewSearch, cx)
1409        });
1410        search_view.update(cx, |search_view, cx| {
1411            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");
1412            assert_eq!(
1413                search_view
1414                    .results_editor
1415                    .update(cx, |editor, cx| editor.display_text(cx)),
1416                "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
1417                "Results should be unchanged after search view 2nd open in a row"
1418            );
1419            assert!(
1420                search_view.query_editor.is_focused(cx),
1421                "Focus should be moved into query editor again after search view 2nd open in a row"
1422            );
1423        });
1424
1425        cx.spawn(
1426            |mut cx| async move { cx.dispatch_action(window_id, search_view_id, &ToggleFocus) },
1427        )
1428        .detach();
1429        deterministic.run_until_parked();
1430        search_view.update(cx, |search_view, cx| {
1431            assert!(
1432                search_view.results_editor.is_focused(cx),
1433                "Search view with matching query should switch focus to the results editor after the toggle focus event",
1434            );
1435        });
1436    }
1437
1438    pub fn init_test(cx: &mut TestAppContext) {
1439        cx.foreground().forbid_parking();
1440        let fonts = cx.font_cache();
1441        let mut theme = gpui::fonts::with_font_cache(fonts.clone(), theme::Theme::default);
1442        theme.search.match_background = Color::red();
1443
1444        cx.update(|cx| {
1445            cx.set_global(SettingsStore::test(cx));
1446            cx.set_global(ActiveSearches::default());
1447
1448            theme::init((), cx);
1449            cx.update_global::<SettingsStore, _, _>(|store, _| {
1450                let mut settings = store.get::<ThemeSettings>(None).clone();
1451                settings.theme = Arc::new(theme);
1452                store.override_global(settings)
1453            });
1454
1455            language::init(cx);
1456            client::init_settings(cx);
1457            editor::init(cx);
1458            workspace::init_settings(cx);
1459            Project::init_settings(cx);
1460            super::init(cx);
1461        });
1462    }
1463}