project_search.rs

   1use crate::{
   2    SearchOption, SelectNextMatch, SelectPrevMatch, ToggleCaseSensitive, ToggleRegex,
   3    ToggleWholeWord,
   4};
   5use collections::HashMap;
   6use editor::{
   7    items::active_match_index, Anchor, Autoscroll, Editor, MultiBuffer, SelectAll,
   8    MAX_TAB_TITLE_LEN,
   9};
  10use gpui::{
  11    actions, elements::*, platform::CursorStyle, Action, AnyViewHandle, AppContext, ElementBox,
  12    Entity, ModelContext, ModelHandle, MouseButton, MutableAppContext, RenderContext, Subscription,
  13    Task, View, ViewContext, ViewHandle, WeakModelHandle, WeakViewHandle,
  14};
  15use menu::Confirm;
  16use project::{search::SearchQuery, Project};
  17use settings::Settings;
  18use smallvec::SmallVec;
  19use std::{
  20    any::{Any, TypeId},
  21    ops::Range,
  22    path::PathBuf,
  23    sync::Arc,
  24};
  25use util::ResultExt as _;
  26use workspace::{
  27    searchable::{Direction, SearchableItem, SearchableItemHandle},
  28    Item, ItemEvent, ItemHandle, ItemNavHistory, Pane, ToolbarItemLocation, ToolbarItemView,
  29    Workspace,
  30};
  31
  32actions!(project_search, [SearchInNew, ToggleFocus]);
  33
  34#[derive(Default)]
  35struct ActiveSearches(HashMap<WeakModelHandle<Project>, WeakViewHandle<ProjectSearchView>>);
  36
  37pub fn init(cx: &mut MutableAppContext) {
  38    cx.set_global(ActiveSearches::default());
  39    cx.add_action(ProjectSearchView::deploy);
  40    cx.add_action(ProjectSearchBar::search);
  41    cx.add_action(ProjectSearchBar::search_in_new);
  42    cx.add_action(ProjectSearchBar::select_next_match);
  43    cx.add_action(ProjectSearchBar::select_prev_match);
  44    cx.add_action(ProjectSearchBar::toggle_focus);
  45    cx.capture_action(ProjectSearchBar::tab);
  46    add_toggle_option_action::<ToggleCaseSensitive>(SearchOption::CaseSensitive, cx);
  47    add_toggle_option_action::<ToggleWholeWord>(SearchOption::WholeWord, cx);
  48    add_toggle_option_action::<ToggleRegex>(SearchOption::Regex, cx);
  49}
  50
  51fn add_toggle_option_action<A: Action>(option: SearchOption, cx: &mut MutableAppContext) {
  52    cx.add_action(move |pane: &mut Pane, _: &A, cx: &mut ViewContext<Pane>| {
  53        if let Some(search_bar) = pane.toolbar().read(cx).item_of_type::<ProjectSearchBar>() {
  54            if search_bar.update(cx, |search_bar, cx| {
  55                search_bar.toggle_search_option(option, cx)
  56            }) {
  57                return;
  58            }
  59        }
  60        cx.propagate_action();
  61    });
  62}
  63
  64struct ProjectSearch {
  65    project: ModelHandle<Project>,
  66    excerpts: ModelHandle<MultiBuffer>,
  67    pending_search: Option<Task<Option<()>>>,
  68    match_ranges: Vec<Range<Anchor>>,
  69    active_query: Option<SearchQuery>,
  70}
  71
  72pub struct ProjectSearchView {
  73    model: ModelHandle<ProjectSearch>,
  74    query_editor: ViewHandle<Editor>,
  75    results_editor: ViewHandle<Editor>,
  76    case_sensitive: bool,
  77    whole_word: bool,
  78    regex: bool,
  79    query_contains_error: bool,
  80    active_match_index: Option<usize>,
  81}
  82
  83pub struct ProjectSearchBar {
  84    active_project_search: Option<ViewHandle<ProjectSearchView>>,
  85    subscription: Option<Subscription>,
  86}
  87
  88impl Entity for ProjectSearch {
  89    type Event = ();
  90}
  91
  92impl ProjectSearch {
  93    fn new(project: ModelHandle<Project>, cx: &mut ModelContext<Self>) -> Self {
  94        let replica_id = project.read(cx).replica_id();
  95        Self {
  96            project,
  97            excerpts: cx.add_model(|_| MultiBuffer::new(replica_id)),
  98            pending_search: Default::default(),
  99            match_ranges: Default::default(),
 100            active_query: None,
 101        }
 102    }
 103
 104    fn clone(&self, cx: &mut ModelContext<Self>) -> ModelHandle<Self> {
 105        cx.add_model(|cx| Self {
 106            project: self.project.clone(),
 107            excerpts: self
 108                .excerpts
 109                .update(cx, |excerpts, cx| cx.add_model(|cx| excerpts.clone(cx))),
 110            pending_search: Default::default(),
 111            match_ranges: self.match_ranges.clone(),
 112            active_query: self.active_query.clone(),
 113        })
 114    }
 115
 116    fn search(&mut self, query: SearchQuery, cx: &mut ModelContext<Self>) {
 117        let search = self
 118            .project
 119            .update(cx, |project, cx| project.search(query.clone(), cx));
 120        self.active_query = Some(query);
 121        self.match_ranges.clear();
 122        self.pending_search = Some(cx.spawn_weak(|this, mut cx| async move {
 123            let matches = search.await.log_err()?;
 124            if let Some(this) = this.upgrade(&cx) {
 125                this.update(&mut cx, |this, cx| {
 126                    this.match_ranges.clear();
 127                    let mut matches = matches.into_iter().collect::<Vec<_>>();
 128                    matches
 129                        .sort_by_key(|(buffer, _)| buffer.read(cx).file().map(|file| file.path()));
 130                    this.excerpts.update(cx, |excerpts, cx| {
 131                        excerpts.clear(cx);
 132                        for (buffer, buffer_matches) in matches {
 133                            let ranges_to_highlight = excerpts.push_excerpts_with_context_lines(
 134                                buffer,
 135                                buffer_matches.clone(),
 136                                1,
 137                                cx,
 138                            );
 139                            this.match_ranges.extend(ranges_to_highlight);
 140                        }
 141                    });
 142                    this.pending_search.take();
 143                    cx.notify();
 144                });
 145            }
 146            None
 147        }));
 148        cx.notify();
 149    }
 150}
 151
 152pub enum ViewEvent {
 153    UpdateTab,
 154    Activate,
 155    EditorEvent(editor::Event),
 156}
 157
 158impl Entity for ProjectSearchView {
 159    type Event = ViewEvent;
 160}
 161
 162impl View for ProjectSearchView {
 163    fn ui_name() -> &'static str {
 164        "ProjectSearchView"
 165    }
 166
 167    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
 168        let model = &self.model.read(cx);
 169        if model.match_ranges.is_empty() {
 170            enum Status {}
 171
 172            let theme = cx.global::<Settings>().theme.clone();
 173            let text = if self.query_editor.read(cx).text(cx).is_empty() {
 174                ""
 175            } else if model.pending_search.is_some() {
 176                "Searching..."
 177            } else {
 178                "No results"
 179            };
 180            MouseEventHandler::<Status>::new(0, cx, |_, _| {
 181                Label::new(text.to_string(), theme.search.results_status.clone())
 182                    .aligned()
 183                    .contained()
 184                    .with_background_color(theme.editor.background)
 185                    .flex(1., true)
 186                    .boxed()
 187            })
 188            .on_down(MouseButton::Left, |_, cx| {
 189                cx.focus_parent_view();
 190            })
 191            .boxed()
 192        } else {
 193            ChildView::new(&self.results_editor, cx)
 194                .flex(1., true)
 195                .boxed()
 196        }
 197    }
 198
 199    fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
 200        let handle = cx.weak_handle();
 201        cx.update_global(|state: &mut ActiveSearches, cx| {
 202            state
 203                .0
 204                .insert(self.model.read(cx).project.downgrade(), handle)
 205        });
 206
 207        if cx.is_self_focused() {
 208            self.focus_query_editor(cx);
 209        }
 210    }
 211}
 212
 213impl Item for ProjectSearchView {
 214    fn act_as_type(
 215        &self,
 216        type_id: TypeId,
 217        self_handle: &ViewHandle<Self>,
 218        _: &gpui::AppContext,
 219    ) -> Option<gpui::AnyViewHandle> {
 220        if type_id == TypeId::of::<Self>() {
 221            Some(self_handle.into())
 222        } else if type_id == TypeId::of::<Editor>() {
 223            Some((&self.results_editor).into())
 224        } else {
 225            None
 226        }
 227    }
 228
 229    fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
 230        self.results_editor
 231            .update(cx, |editor, cx| editor.deactivated(cx));
 232    }
 233
 234    fn tab_content(
 235        &self,
 236        _detail: Option<usize>,
 237        tab_theme: &theme::Tab,
 238        cx: &gpui::AppContext,
 239    ) -> ElementBox {
 240        let settings = cx.global::<Settings>();
 241        let search_theme = &settings.theme.search;
 242        Flex::row()
 243            .with_child(
 244                Svg::new("icons/magnifying_glass_12.svg")
 245                    .with_color(tab_theme.label.text.color)
 246                    .constrained()
 247                    .with_width(search_theme.tab_icon_width)
 248                    .aligned()
 249                    .boxed(),
 250            )
 251            .with_children(self.model.read(cx).active_query.as_ref().map(|query| {
 252                let query_text = if query.as_str().len() > MAX_TAB_TITLE_LEN {
 253                    query.as_str()[..MAX_TAB_TITLE_LEN].to_string() + ""
 254                } else {
 255                    query.as_str().to_string()
 256                };
 257
 258                Label::new(query_text, tab_theme.label.clone())
 259                    .aligned()
 260                    .contained()
 261                    .with_margin_left(search_theme.tab_icon_spacing)
 262                    .boxed()
 263            }))
 264            .boxed()
 265    }
 266
 267    fn project_path(&self, _: &gpui::AppContext) -> Option<project::ProjectPath> {
 268        None
 269    }
 270
 271    fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[project::ProjectEntryId; 3]> {
 272        self.results_editor.project_entry_ids(cx)
 273    }
 274
 275    fn is_singleton(&self, _: &AppContext) -> bool {
 276        false
 277    }
 278
 279    fn can_save(&self, _: &gpui::AppContext) -> bool {
 280        true
 281    }
 282
 283    fn is_dirty(&self, cx: &AppContext) -> bool {
 284        self.results_editor.read(cx).is_dirty(cx)
 285    }
 286
 287    fn has_conflict(&self, cx: &AppContext) -> bool {
 288        self.results_editor.read(cx).has_conflict(cx)
 289    }
 290
 291    fn save(
 292        &mut self,
 293        project: ModelHandle<Project>,
 294        cx: &mut ViewContext<Self>,
 295    ) -> Task<anyhow::Result<()>> {
 296        self.results_editor
 297            .update(cx, |editor, cx| editor.save(project, cx))
 298    }
 299
 300    fn save_as(
 301        &mut self,
 302        _: ModelHandle<Project>,
 303        _: PathBuf,
 304        _: &mut ViewContext<Self>,
 305    ) -> Task<anyhow::Result<()>> {
 306        unreachable!("save_as should not have been called")
 307    }
 308
 309    fn reload(
 310        &mut self,
 311        project: ModelHandle<Project>,
 312        cx: &mut ViewContext<Self>,
 313    ) -> Task<anyhow::Result<()>> {
 314        self.results_editor
 315            .update(cx, |editor, cx| editor.reload(project, cx))
 316    }
 317
 318    fn clone_on_split(&self, cx: &mut ViewContext<Self>) -> Option<Self>
 319    where
 320        Self: Sized,
 321    {
 322        let model = self.model.update(cx, |model, cx| model.clone(cx));
 323        Some(Self::new(model, cx))
 324    }
 325
 326    fn set_nav_history(&mut self, nav_history: ItemNavHistory, cx: &mut ViewContext<Self>) {
 327        self.results_editor.update(cx, |editor, _| {
 328            editor.set_nav_history(Some(nav_history));
 329        });
 330    }
 331
 332    fn navigate(&mut self, data: Box<dyn Any>, cx: &mut ViewContext<Self>) -> bool {
 333        self.results_editor
 334            .update(cx, |editor, cx| editor.navigate(data, cx))
 335    }
 336
 337    fn to_item_events(event: &Self::Event) -> Vec<ItemEvent> {
 338        match event {
 339            ViewEvent::UpdateTab => vec![ItemEvent::UpdateBreadcrumbs, ItemEvent::UpdateTab],
 340            ViewEvent::EditorEvent(editor_event) => Editor::to_item_events(editor_event),
 341            _ => Vec::new(),
 342        }
 343    }
 344
 345    fn breadcrumb_location(&self) -> ToolbarItemLocation {
 346        if self.has_matches() {
 347            ToolbarItemLocation::Secondary
 348        } else {
 349            ToolbarItemLocation::Hidden
 350        }
 351    }
 352
 353    fn breadcrumbs(&self, theme: &theme::Theme, cx: &AppContext) -> Option<Vec<ElementBox>> {
 354        self.results_editor.breadcrumbs(theme, cx)
 355    }
 356}
 357
 358impl ProjectSearchView {
 359    fn new(model: ModelHandle<ProjectSearch>, cx: &mut ViewContext<Self>) -> Self {
 360        let project;
 361        let excerpts;
 362        let mut query_text = String::new();
 363        let mut regex = false;
 364        let mut case_sensitive = false;
 365        let mut whole_word = false;
 366
 367        {
 368            let model = model.read(cx);
 369            project = model.project.clone();
 370            excerpts = model.excerpts.clone();
 371            if let Some(active_query) = model.active_query.as_ref() {
 372                query_text = active_query.as_str().to_string();
 373                regex = active_query.is_regex();
 374                case_sensitive = active_query.case_sensitive();
 375                whole_word = active_query.whole_word();
 376            }
 377        }
 378        cx.observe(&model, |this, _, cx| this.model_changed(true, cx))
 379            .detach();
 380
 381        let query_editor = cx.add_view(|cx| {
 382            let mut editor = Editor::single_line(
 383                Some(Arc::new(|theme| theme.search.editor.input.clone())),
 384                cx,
 385            );
 386            editor.set_text(query_text, cx);
 387            editor
 388        });
 389        // Subcribe to query_editor in order to reraise editor events for workspace item activation purposes
 390        cx.subscribe(&query_editor, |_, _, event, cx| {
 391            cx.emit(ViewEvent::EditorEvent(*event))
 392        })
 393        .detach();
 394
 395        let results_editor = cx.add_view(|cx| {
 396            let mut editor = Editor::for_multibuffer(excerpts, Some(project), cx);
 397            editor.set_searchable(false);
 398            editor
 399        });
 400        cx.observe(&results_editor, |_, _, cx| cx.emit(ViewEvent::UpdateTab))
 401            .detach();
 402
 403        cx.subscribe(&results_editor, |this, _, event, cx| {
 404            if matches!(event, editor::Event::SelectionsChanged { .. }) {
 405                this.update_match_index(cx);
 406            }
 407            // Reraise editor events for workspace item activation purposes
 408            cx.emit(ViewEvent::EditorEvent(*event));
 409        })
 410        .detach();
 411
 412        let mut this = ProjectSearchView {
 413            model,
 414            query_editor,
 415            results_editor,
 416            case_sensitive,
 417            whole_word,
 418            regex,
 419            query_contains_error: false,
 420            active_match_index: None,
 421        };
 422        this.model_changed(false, cx);
 423        this
 424    }
 425
 426    // Re-activate the most recently activated search or the most recent if it has been closed.
 427    // If no search exists in the workspace, create a new one.
 428    fn deploy(
 429        workspace: &mut Workspace,
 430        _: &workspace::NewSearch,
 431        cx: &mut ViewContext<Workspace>,
 432    ) {
 433        // Clean up entries for dropped projects
 434        cx.update_global(|state: &mut ActiveSearches, cx| {
 435            state.0.retain(|project, _| project.is_upgradable(cx))
 436        });
 437
 438        let active_search = cx
 439            .global::<ActiveSearches>()
 440            .0
 441            .get(&workspace.project().downgrade());
 442
 443        let existing = active_search
 444            .and_then(|active_search| {
 445                workspace
 446                    .items_of_type::<ProjectSearchView>(cx)
 447                    .find(|search| search == active_search)
 448            })
 449            .or_else(|| workspace.item_of_type::<ProjectSearchView>(cx));
 450
 451        let query = workspace.active_item(cx).and_then(|item| {
 452            let editor = item.act_as::<Editor>(cx)?;
 453            let query = editor.query_suggestion(cx);
 454            if query.is_empty() {
 455                None
 456            } else {
 457                Some(query)
 458            }
 459        });
 460
 461        let search = if let Some(existing) = existing {
 462            workspace.activate_item(&existing, cx);
 463            existing
 464        } else {
 465            let model = cx.add_model(|cx| ProjectSearch::new(workspace.project().clone(), cx));
 466            let view = cx.add_view(|cx| ProjectSearchView::new(model, cx));
 467            workspace.add_item(Box::new(view.clone()), cx);
 468            view
 469        };
 470
 471        search.update(cx, |search, cx| {
 472            if let Some(query) = query {
 473                search.set_query(&query, cx);
 474            }
 475            search.focus_query_editor(cx)
 476        });
 477    }
 478
 479    fn search(&mut self, cx: &mut ViewContext<Self>) {
 480        if let Some(query) = self.build_search_query(cx) {
 481            self.model.update(cx, |model, cx| model.search(query, cx));
 482        }
 483    }
 484
 485    fn build_search_query(&mut self, cx: &mut ViewContext<Self>) -> Option<SearchQuery> {
 486        let text = self.query_editor.read(cx).text(cx);
 487        if self.regex {
 488            match SearchQuery::regex(text, self.whole_word, self.case_sensitive) {
 489                Ok(query) => Some(query),
 490                Err(_) => {
 491                    self.query_contains_error = true;
 492                    cx.notify();
 493                    None
 494                }
 495            }
 496        } else {
 497            Some(SearchQuery::text(
 498                text,
 499                self.whole_word,
 500                self.case_sensitive,
 501            ))
 502        }
 503    }
 504
 505    fn select_match(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 506        if let Some(index) = self.active_match_index {
 507            let match_ranges = self.model.read(cx).match_ranges.clone();
 508            let new_index = self.results_editor.update(cx, |editor, cx| {
 509                editor.match_index_for_direction(&match_ranges, index, direction, cx)
 510            });
 511
 512            let range_to_select = match_ranges[new_index].clone();
 513            self.results_editor.update(cx, |editor, cx| {
 514                editor.unfold_ranges([range_to_select.clone()], false, cx);
 515                editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 516                    s.select_ranges([range_to_select])
 517                });
 518            });
 519        }
 520    }
 521
 522    fn focus_query_editor(&self, cx: &mut ViewContext<Self>) {
 523        self.query_editor.update(cx, |query_editor, cx| {
 524            query_editor.select_all(&SelectAll, cx);
 525        });
 526        cx.focus(&self.query_editor);
 527    }
 528
 529    fn set_query(&mut self, query: &str, cx: &mut ViewContext<Self>) {
 530        self.query_editor
 531            .update(cx, |query_editor, cx| query_editor.set_text(query, cx));
 532    }
 533
 534    fn focus_results_editor(&self, cx: &mut ViewContext<Self>) {
 535        self.query_editor.update(cx, |query_editor, cx| {
 536            let cursor = query_editor.selections.newest_anchor().head();
 537            query_editor.change_selections(None, cx, |s| s.select_ranges([cursor.clone()..cursor]));
 538        });
 539        cx.focus(&self.results_editor);
 540    }
 541
 542    fn model_changed(&mut self, reset_selections: bool, cx: &mut ViewContext<Self>) {
 543        let match_ranges = self.model.read(cx).match_ranges.clone();
 544        if match_ranges.is_empty() {
 545            self.active_match_index = None;
 546        } else {
 547            self.results_editor.update(cx, |editor, cx| {
 548                if reset_selections {
 549                    editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 550                        s.select_ranges(match_ranges.first().cloned())
 551                    });
 552                }
 553                editor.highlight_background::<Self>(
 554                    match_ranges,
 555                    |theme| theme.search.match_background,
 556                    cx,
 557                );
 558            });
 559            if self.query_editor.is_focused(cx) {
 560                self.focus_results_editor(cx);
 561            }
 562        }
 563
 564        cx.emit(ViewEvent::UpdateTab);
 565        cx.notify();
 566    }
 567
 568    fn update_match_index(&mut self, cx: &mut ViewContext<Self>) {
 569        let results_editor = self.results_editor.read(cx);
 570        let new_index = active_match_index(
 571            &self.model.read(cx).match_ranges,
 572            &results_editor.selections.newest_anchor().head(),
 573            &results_editor.buffer().read(cx).snapshot(cx),
 574        );
 575        if self.active_match_index != new_index {
 576            self.active_match_index = new_index;
 577            cx.notify();
 578        }
 579    }
 580
 581    pub fn has_matches(&self) -> bool {
 582        self.active_match_index.is_some()
 583    }
 584}
 585
 586impl Default for ProjectSearchBar {
 587    fn default() -> Self {
 588        Self::new()
 589    }
 590}
 591
 592impl ProjectSearchBar {
 593    pub fn new() -> Self {
 594        Self {
 595            active_project_search: Default::default(),
 596            subscription: Default::default(),
 597        }
 598    }
 599
 600    fn search(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
 601        if let Some(search_view) = self.active_project_search.as_ref() {
 602            search_view.update(cx, |search_view, cx| search_view.search(cx));
 603        }
 604    }
 605
 606    fn search_in_new(workspace: &mut Workspace, _: &SearchInNew, cx: &mut ViewContext<Workspace>) {
 607        if let Some(search_view) = workspace
 608            .active_item(cx)
 609            .and_then(|item| item.downcast::<ProjectSearchView>())
 610        {
 611            let new_query = search_view.update(cx, |search_view, cx| {
 612                let new_query = search_view.build_search_query(cx);
 613                if new_query.is_some() {
 614                    if let Some(old_query) = search_view.model.read(cx).active_query.clone() {
 615                        search_view.query_editor.update(cx, |editor, cx| {
 616                            editor.set_text(old_query.as_str(), cx);
 617                        });
 618                        search_view.regex = old_query.is_regex();
 619                        search_view.whole_word = old_query.whole_word();
 620                        search_view.case_sensitive = old_query.case_sensitive();
 621                    }
 622                }
 623                new_query
 624            });
 625            if let Some(new_query) = new_query {
 626                let model = cx.add_model(|cx| {
 627                    let mut model = ProjectSearch::new(workspace.project().clone(), cx);
 628                    model.search(new_query, cx);
 629                    model
 630                });
 631                workspace.add_item(
 632                    Box::new(cx.add_view(|cx| ProjectSearchView::new(model, cx))),
 633                    cx,
 634                );
 635            }
 636        }
 637    }
 638
 639    fn select_next_match(pane: &mut Pane, _: &SelectNextMatch, cx: &mut ViewContext<Pane>) {
 640        if let Some(search_view) = pane
 641            .active_item()
 642            .and_then(|item| item.downcast::<ProjectSearchView>())
 643        {
 644            search_view.update(cx, |view, cx| view.select_match(Direction::Next, cx));
 645        } else {
 646            cx.propagate_action();
 647        }
 648    }
 649
 650    fn select_prev_match(pane: &mut Pane, _: &SelectPrevMatch, cx: &mut ViewContext<Pane>) {
 651        if let Some(search_view) = pane
 652            .active_item()
 653            .and_then(|item| item.downcast::<ProjectSearchView>())
 654        {
 655            search_view.update(cx, |view, cx| view.select_match(Direction::Prev, cx));
 656        } else {
 657            cx.propagate_action();
 658        }
 659    }
 660
 661    fn toggle_focus(pane: &mut Pane, _: &ToggleFocus, cx: &mut ViewContext<Pane>) {
 662        if let Some(search_view) = pane
 663            .active_item()
 664            .and_then(|item| item.downcast::<ProjectSearchView>())
 665        {
 666            search_view.update(cx, |search_view, cx| {
 667                if search_view.query_editor.is_focused(cx) {
 668                    if !search_view.model.read(cx).match_ranges.is_empty() {
 669                        search_view.focus_results_editor(cx);
 670                    }
 671                } else {
 672                    search_view.focus_query_editor(cx);
 673                }
 674            });
 675        } else {
 676            cx.propagate_action();
 677        }
 678    }
 679
 680    fn tab(&mut self, _: &editor::Tab, cx: &mut ViewContext<Self>) {
 681        if let Some(search_view) = self.active_project_search.as_ref() {
 682            search_view.update(cx, |search_view, cx| {
 683                if search_view.query_editor.is_focused(cx) {
 684                    if !search_view.model.read(cx).match_ranges.is_empty() {
 685                        search_view.focus_results_editor(cx);
 686                    }
 687                } else {
 688                    cx.propagate_action();
 689                }
 690            });
 691        } else {
 692            cx.propagate_action();
 693        }
 694    }
 695
 696    fn toggle_search_option(&mut self, option: SearchOption, cx: &mut ViewContext<Self>) -> bool {
 697        if let Some(search_view) = self.active_project_search.as_ref() {
 698            search_view.update(cx, |search_view, cx| {
 699                let value = match option {
 700                    SearchOption::WholeWord => &mut search_view.whole_word,
 701                    SearchOption::CaseSensitive => &mut search_view.case_sensitive,
 702                    SearchOption::Regex => &mut search_view.regex,
 703                };
 704                *value = !*value;
 705                search_view.search(cx);
 706            });
 707            cx.notify();
 708            true
 709        } else {
 710            false
 711        }
 712    }
 713
 714    fn render_nav_button(
 715        &self,
 716        icon: &str,
 717        direction: Direction,
 718        cx: &mut RenderContext<Self>,
 719    ) -> ElementBox {
 720        let action: Box<dyn Action>;
 721        let tooltip;
 722        match direction {
 723            Direction::Prev => {
 724                action = Box::new(SelectPrevMatch);
 725                tooltip = "Select Previous Match";
 726            }
 727            Direction::Next => {
 728                action = Box::new(SelectNextMatch);
 729                tooltip = "Select Next Match";
 730            }
 731        };
 732        let tooltip_style = cx.global::<Settings>().theme.tooltip.clone();
 733
 734        enum NavButton {}
 735        MouseEventHandler::<NavButton>::new(direction as usize, cx, |state, cx| {
 736            let style = &cx
 737                .global::<Settings>()
 738                .theme
 739                .search
 740                .option_button
 741                .style_for(state, false);
 742            Label::new(icon.to_string(), style.text.clone())
 743                .contained()
 744                .with_style(style.container)
 745                .boxed()
 746        })
 747        .on_click(MouseButton::Left, {
 748            let action = action.boxed_clone();
 749            move |_, cx| cx.dispatch_any_action(action.boxed_clone())
 750        })
 751        .with_cursor_style(CursorStyle::PointingHand)
 752        .with_tooltip::<NavButton, _>(
 753            direction as usize,
 754            tooltip.to_string(),
 755            Some(action),
 756            tooltip_style,
 757            cx,
 758        )
 759        .boxed()
 760    }
 761
 762    fn render_option_button(
 763        &self,
 764        icon: &str,
 765        option: SearchOption,
 766        cx: &mut RenderContext<Self>,
 767    ) -> ElementBox {
 768        let tooltip_style = cx.global::<Settings>().theme.tooltip.clone();
 769        let is_active = self.is_option_enabled(option, cx);
 770        MouseEventHandler::<Self>::new(option as usize, cx, |state, cx| {
 771            let style = &cx
 772                .global::<Settings>()
 773                .theme
 774                .search
 775                .option_button
 776                .style_for(state, is_active);
 777            Label::new(icon.to_string(), style.text.clone())
 778                .contained()
 779                .with_style(style.container)
 780                .boxed()
 781        })
 782        .on_click(MouseButton::Left, move |_, cx| {
 783            cx.dispatch_any_action(option.to_toggle_action())
 784        })
 785        .with_cursor_style(CursorStyle::PointingHand)
 786        .with_tooltip::<Self, _>(
 787            option as usize,
 788            format!("Toggle {}", option.label()),
 789            Some(option.to_toggle_action()),
 790            tooltip_style,
 791            cx,
 792        )
 793        .boxed()
 794    }
 795
 796    fn is_option_enabled(&self, option: SearchOption, cx: &AppContext) -> bool {
 797        if let Some(search) = self.active_project_search.as_ref() {
 798            let search = search.read(cx);
 799            match option {
 800                SearchOption::WholeWord => search.whole_word,
 801                SearchOption::CaseSensitive => search.case_sensitive,
 802                SearchOption::Regex => search.regex,
 803            }
 804        } else {
 805            false
 806        }
 807    }
 808}
 809
 810impl Entity for ProjectSearchBar {
 811    type Event = ();
 812}
 813
 814impl View for ProjectSearchBar {
 815    fn ui_name() -> &'static str {
 816        "ProjectSearchBar"
 817    }
 818
 819    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
 820        if let Some(search) = self.active_project_search.as_ref() {
 821            let search = search.read(cx);
 822            let theme = cx.global::<Settings>().theme.clone();
 823            let editor_container = if search.query_contains_error {
 824                theme.search.invalid_editor
 825            } else {
 826                theme.search.editor.input.container
 827            };
 828            Flex::row()
 829                .with_child(
 830                    Flex::row()
 831                        .with_child(
 832                            ChildView::new(&search.query_editor, cx)
 833                                .aligned()
 834                                .left()
 835                                .flex(1., true)
 836                                .boxed(),
 837                        )
 838                        .with_children(search.active_match_index.map(|match_ix| {
 839                            Label::new(
 840                                format!(
 841                                    "{}/{}",
 842                                    match_ix + 1,
 843                                    search.model.read(cx).match_ranges.len()
 844                                ),
 845                                theme.search.match_index.text.clone(),
 846                            )
 847                            .contained()
 848                            .with_style(theme.search.match_index.container)
 849                            .aligned()
 850                            .boxed()
 851                        }))
 852                        .contained()
 853                        .with_style(editor_container)
 854                        .aligned()
 855                        .constrained()
 856                        .with_min_width(theme.search.editor.min_width)
 857                        .with_max_width(theme.search.editor.max_width)
 858                        .flex(1., false)
 859                        .boxed(),
 860                )
 861                .with_child(
 862                    Flex::row()
 863                        .with_child(self.render_nav_button("<", Direction::Prev, cx))
 864                        .with_child(self.render_nav_button(">", Direction::Next, cx))
 865                        .aligned()
 866                        .boxed(),
 867                )
 868                .with_child(
 869                    Flex::row()
 870                        .with_child(self.render_option_button(
 871                            "Case",
 872                            SearchOption::CaseSensitive,
 873                            cx,
 874                        ))
 875                        .with_child(self.render_option_button("Word", SearchOption::WholeWord, cx))
 876                        .with_child(self.render_option_button("Regex", SearchOption::Regex, cx))
 877                        .contained()
 878                        .with_style(theme.search.option_button_group)
 879                        .aligned()
 880                        .boxed(),
 881                )
 882                .contained()
 883                .with_style(theme.search.container)
 884                .aligned()
 885                .left()
 886                .named("project search")
 887        } else {
 888            Empty::new().boxed()
 889        }
 890    }
 891}
 892
 893impl ToolbarItemView for ProjectSearchBar {
 894    fn set_active_pane_item(
 895        &mut self,
 896        active_pane_item: Option<&dyn workspace::ItemHandle>,
 897        cx: &mut ViewContext<Self>,
 898    ) -> ToolbarItemLocation {
 899        cx.notify();
 900        self.subscription = None;
 901        self.active_project_search = None;
 902        if let Some(search) = active_pane_item.and_then(|i| i.downcast::<ProjectSearchView>()) {
 903            let query_editor = search.read(cx).query_editor.clone();
 904            cx.reparent(query_editor);
 905            self.subscription = Some(cx.observe(&search, |_, _, cx| cx.notify()));
 906            self.active_project_search = Some(search);
 907            ToolbarItemLocation::PrimaryLeft {
 908                flex: Some((1., false)),
 909            }
 910        } else {
 911            ToolbarItemLocation::Hidden
 912        }
 913    }
 914}
 915
 916#[cfg(test)]
 917mod tests {
 918    use super::*;
 919    use editor::DisplayPoint;
 920    use gpui::{color::Color, TestAppContext};
 921    use project::FakeFs;
 922    use serde_json::json;
 923    use std::sync::Arc;
 924
 925    #[gpui::test]
 926    async fn test_project_search(cx: &mut TestAppContext) {
 927        let fonts = cx.font_cache();
 928        let mut theme = gpui::fonts::with_font_cache(fonts.clone(), theme::Theme::default);
 929        theme.search.match_background = Color::red();
 930        cx.update(|cx| {
 931            let mut settings = Settings::test(cx);
 932            settings.theme = Arc::new(theme);
 933            cx.set_global(settings);
 934            cx.set_global(ActiveSearches::default());
 935        });
 936
 937        let fs = FakeFs::new(cx.background());
 938        fs.insert_tree(
 939            "/dir",
 940            json!({
 941                "one.rs": "const ONE: usize = 1;",
 942                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
 943                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
 944                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
 945            }),
 946        )
 947        .await;
 948        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
 949        let search = cx.add_model(|cx| ProjectSearch::new(project, cx));
 950        let (_, search_view) = cx.add_window(|cx| ProjectSearchView::new(search.clone(), cx));
 951
 952        search_view.update(cx, |search_view, cx| {
 953            search_view
 954                .query_editor
 955                .update(cx, |query_editor, cx| query_editor.set_text("TWO", cx));
 956            search_view.search(cx);
 957        });
 958        search_view.next_notification(cx).await;
 959        search_view.update(cx, |search_view, cx| {
 960            assert_eq!(
 961                search_view
 962                    .results_editor
 963                    .update(cx, |editor, cx| editor.display_text(cx)),
 964                "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;"
 965            );
 966            assert_eq!(
 967                search_view
 968                    .results_editor
 969                    .update(cx, |editor, cx| editor.all_background_highlights(cx)),
 970                &[
 971                    (
 972                        DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35),
 973                        Color::red()
 974                    ),
 975                    (
 976                        DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40),
 977                        Color::red()
 978                    ),
 979                    (
 980                        DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9),
 981                        Color::red()
 982                    )
 983                ]
 984            );
 985            assert_eq!(search_view.active_match_index, Some(0));
 986            assert_eq!(
 987                search_view
 988                    .results_editor
 989                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
 990                [DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35)]
 991            );
 992
 993            search_view.select_match(Direction::Next, cx);
 994        });
 995
 996        search_view.update(cx, |search_view, cx| {
 997            assert_eq!(search_view.active_match_index, Some(1));
 998            assert_eq!(
 999                search_view
1000                    .results_editor
1001                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1002                [DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40)]
1003            );
1004            search_view.select_match(Direction::Next, cx);
1005        });
1006
1007        search_view.update(cx, |search_view, cx| {
1008            assert_eq!(search_view.active_match_index, Some(2));
1009            assert_eq!(
1010                search_view
1011                    .results_editor
1012                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1013                [DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9)]
1014            );
1015            search_view.select_match(Direction::Next, cx);
1016        });
1017
1018        search_view.update(cx, |search_view, cx| {
1019            assert_eq!(search_view.active_match_index, Some(0));
1020            assert_eq!(
1021                search_view
1022                    .results_editor
1023                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1024                [DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35)]
1025            );
1026            search_view.select_match(Direction::Prev, cx);
1027        });
1028
1029        search_view.update(cx, |search_view, cx| {
1030            assert_eq!(search_view.active_match_index, Some(2));
1031            assert_eq!(
1032                search_view
1033                    .results_editor
1034                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1035                [DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9)]
1036            );
1037            search_view.select_match(Direction::Prev, cx);
1038        });
1039
1040        search_view.update(cx, |search_view, cx| {
1041            assert_eq!(search_view.active_match_index, Some(1));
1042            assert_eq!(
1043                search_view
1044                    .results_editor
1045                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1046                [DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40)]
1047            );
1048        });
1049    }
1050}