project_search.rs

   1use crate::{
   2    active_match_index, match_index_for_direction, query_suggestion_for_editor, Direction,
   3    SearchOption, SelectNextMatch, SelectPrevMatch, ToggleCaseSensitive, ToggleRegex,
   4    ToggleWholeWord,
   5};
   6use collections::HashMap;
   7use editor::{Anchor, Autoscroll, Editor, MultiBuffer, SelectAll, MAX_TAB_TITLE_LEN};
   8use gpui::{
   9    actions, elements::*, platform::CursorStyle, Action, AppContext, ElementBox, Entity,
  10    ModelContext, ModelHandle, MouseButton, MutableAppContext, RenderContext, Subscription, Task,
  11    View, ViewContext, ViewHandle, WeakModelHandle, WeakViewHandle,
  12};
  13use menu::Confirm;
  14use project::{search::SearchQuery, Project};
  15use settings::Settings;
  16use smallvec::SmallVec;
  17use std::{
  18    any::{Any, TypeId},
  19    ops::Range,
  20    path::PathBuf,
  21};
  22use util::ResultExt as _;
  23use workspace::{
  24    Item, ItemHandle, ItemNavHistory, Pane, ToolbarItemLocation, ToolbarItemView, Workspace,
  25};
  26
  27actions!(project_search, [Deploy, SearchInNew, ToggleFocus]);
  28
  29#[derive(Default)]
  30struct ActiveSearches(HashMap<WeakModelHandle<Project>, WeakViewHandle<ProjectSearchView>>);
  31
  32pub fn init(cx: &mut MutableAppContext) {
  33    cx.set_global(ActiveSearches::default());
  34    cx.add_action(ProjectSearchView::deploy);
  35    cx.add_action(ProjectSearchBar::search);
  36    cx.add_action(ProjectSearchBar::search_in_new);
  37    cx.add_action(ProjectSearchBar::select_next_match);
  38    cx.add_action(ProjectSearchBar::select_prev_match);
  39    cx.add_action(ProjectSearchBar::toggle_focus);
  40    cx.capture_action(ProjectSearchBar::tab);
  41    add_toggle_option_action::<ToggleCaseSensitive>(SearchOption::CaseSensitive, cx);
  42    add_toggle_option_action::<ToggleWholeWord>(SearchOption::WholeWord, cx);
  43    add_toggle_option_action::<ToggleRegex>(SearchOption::Regex, cx);
  44}
  45
  46fn add_toggle_option_action<A: Action>(option: SearchOption, cx: &mut MutableAppContext) {
  47    cx.add_action(move |pane: &mut Pane, _: &A, cx: &mut ViewContext<Pane>| {
  48        if let Some(search_bar) = pane.toolbar().read(cx).item_of_type::<ProjectSearchBar>() {
  49            if search_bar.update(cx, |search_bar, cx| {
  50                search_bar.toggle_search_option(option, cx)
  51            }) {
  52                return;
  53            }
  54        }
  55        cx.propagate_action();
  56    });
  57}
  58
  59struct ProjectSearch {
  60    project: ModelHandle<Project>,
  61    excerpts: ModelHandle<MultiBuffer>,
  62    pending_search: Option<Task<Option<()>>>,
  63    match_ranges: Vec<Range<Anchor>>,
  64    active_query: Option<SearchQuery>,
  65}
  66
  67pub struct ProjectSearchView {
  68    model: ModelHandle<ProjectSearch>,
  69    query_editor: ViewHandle<Editor>,
  70    results_editor: ViewHandle<Editor>,
  71    case_sensitive: bool,
  72    whole_word: bool,
  73    regex: bool,
  74    query_contains_error: bool,
  75    active_match_index: Option<usize>,
  76    results_editor_was_focused: bool,
  77}
  78
  79pub struct ProjectSearchBar {
  80    active_project_search: Option<ViewHandle<ProjectSearchView>>,
  81    subscription: Option<Subscription>,
  82}
  83
  84impl Entity for ProjectSearch {
  85    type Event = ();
  86}
  87
  88impl ProjectSearch {
  89    fn new(project: ModelHandle<Project>, cx: &mut ModelContext<Self>) -> Self {
  90        let replica_id = project.read(cx).replica_id();
  91        Self {
  92            project,
  93            excerpts: cx.add_model(|_| MultiBuffer::new(replica_id)),
  94            pending_search: Default::default(),
  95            match_ranges: Default::default(),
  96            active_query: None,
  97        }
  98    }
  99
 100    fn clone(&self, cx: &mut ModelContext<Self>) -> ModelHandle<Self> {
 101        cx.add_model(|cx| Self {
 102            project: self.project.clone(),
 103            excerpts: self
 104                .excerpts
 105                .update(cx, |excerpts, cx| cx.add_model(|cx| excerpts.clone(cx))),
 106            pending_search: Default::default(),
 107            match_ranges: self.match_ranges.clone(),
 108            active_query: self.active_query.clone(),
 109        })
 110    }
 111
 112    fn search(&mut self, query: SearchQuery, cx: &mut ModelContext<Self>) {
 113        let search = self
 114            .project
 115            .update(cx, |project, cx| project.search(query.clone(), cx));
 116        self.active_query = Some(query);
 117        self.match_ranges.clear();
 118        self.pending_search = Some(cx.spawn_weak(|this, mut cx| async move {
 119            let matches = search.await.log_err()?;
 120            if let Some(this) = this.upgrade(&cx) {
 121                this.update(&mut cx, |this, cx| {
 122                    this.match_ranges.clear();
 123                    let mut matches = matches.into_iter().collect::<Vec<_>>();
 124                    matches
 125                        .sort_by_key(|(buffer, _)| buffer.read(cx).file().map(|file| file.path()));
 126                    this.excerpts.update(cx, |excerpts, cx| {
 127                        excerpts.clear(cx);
 128                        for (buffer, buffer_matches) in matches {
 129                            let ranges_to_highlight = excerpts.push_excerpts_with_context_lines(
 130                                buffer,
 131                                buffer_matches.clone(),
 132                                1,
 133                                cx,
 134                            );
 135                            this.match_ranges.extend(ranges_to_highlight);
 136                        }
 137                    });
 138                    this.pending_search.take();
 139                    cx.notify();
 140                });
 141            }
 142            None
 143        }));
 144        cx.notify();
 145    }
 146}
 147
 148pub enum ViewEvent {
 149    UpdateTab,
 150    Activate,
 151    EditorEvent(editor::Event),
 152}
 153
 154impl Entity for ProjectSearchView {
 155    type Event = ViewEvent;
 156}
 157
 158impl View for ProjectSearchView {
 159    fn ui_name() -> &'static str {
 160        "ProjectSearchView"
 161    }
 162
 163    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
 164        let model = &self.model.read(cx);
 165        if model.match_ranges.is_empty() {
 166            enum Status {}
 167
 168            let theme = cx.global::<Settings>().theme.clone();
 169            let text = if self.query_editor.read(cx).text(cx).is_empty() {
 170                ""
 171            } else if model.pending_search.is_some() {
 172                "Searching..."
 173            } else {
 174                "No results"
 175            };
 176            MouseEventHandler::new::<Status, _, _>(0, cx, |_, _| {
 177                Label::new(text.to_string(), theme.search.results_status.clone())
 178                    .aligned()
 179                    .contained()
 180                    .with_background_color(theme.editor.background)
 181                    .flex(1., true)
 182                    .boxed()
 183            })
 184            .on_down(MouseButton::Left, |_, cx| {
 185                cx.focus_parent_view();
 186            })
 187            .boxed()
 188        } else {
 189            ChildView::new(&self.results_editor).flex(1., true).boxed()
 190        }
 191    }
 192
 193    fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
 194        let handle = cx.weak_handle();
 195        cx.update_global(|state: &mut ActiveSearches, cx| {
 196            state
 197                .0
 198                .insert(self.model.read(cx).project.downgrade(), handle)
 199        });
 200
 201        if self.results_editor_was_focused && !self.model.read(cx).match_ranges.is_empty() {
 202            self.focus_results_editor(cx);
 203        } else {
 204            cx.focus(&self.query_editor);
 205        }
 206    }
 207}
 208
 209impl Item for ProjectSearchView {
 210    fn act_as_type(
 211        &self,
 212        type_id: TypeId,
 213        self_handle: &ViewHandle<Self>,
 214        _: &gpui::AppContext,
 215    ) -> Option<gpui::AnyViewHandle> {
 216        if type_id == TypeId::of::<Self>() {
 217            Some(self_handle.into())
 218        } else if type_id == TypeId::of::<Editor>() {
 219            Some((&self.results_editor).into())
 220        } else {
 221            None
 222        }
 223    }
 224
 225    fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
 226        self.results_editor
 227            .update(cx, |editor, cx| editor.deactivated(cx));
 228    }
 229
 230    fn tab_content(
 231        &self,
 232        _detail: Option<usize>,
 233        tab_theme: &theme::Tab,
 234        cx: &gpui::AppContext,
 235    ) -> ElementBox {
 236        let settings = cx.global::<Settings>();
 237        let search_theme = &settings.theme.search;
 238        Flex::row()
 239            .with_child(
 240                Svg::new("icons/magnifying_glass_12.svg")
 241                    .with_color(tab_theme.label.text.color)
 242                    .constrained()
 243                    .with_width(search_theme.tab_icon_width)
 244                    .aligned()
 245                    .boxed(),
 246            )
 247            .with_children(self.model.read(cx).active_query.as_ref().map(|query| {
 248                let query_text = if query.as_str().len() > MAX_TAB_TITLE_LEN {
 249                    query.as_str()[..MAX_TAB_TITLE_LEN].to_string() + ""
 250                } else {
 251                    query.as_str().to_string()
 252                };
 253
 254                Label::new(query_text, tab_theme.label.clone())
 255                    .aligned()
 256                    .contained()
 257                    .with_margin_left(search_theme.tab_icon_spacing)
 258                    .boxed()
 259            }))
 260            .boxed()
 261    }
 262
 263    fn project_path(&self, _: &gpui::AppContext) -> Option<project::ProjectPath> {
 264        None
 265    }
 266
 267    fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[project::ProjectEntryId; 3]> {
 268        self.results_editor.project_entry_ids(cx)
 269    }
 270
 271    fn is_singleton(&self, _: &AppContext) -> bool {
 272        false
 273    }
 274
 275    fn can_save(&self, _: &gpui::AppContext) -> bool {
 276        true
 277    }
 278
 279    fn is_dirty(&self, cx: &AppContext) -> bool {
 280        self.results_editor.read(cx).is_dirty(cx)
 281    }
 282
 283    fn has_conflict(&self, cx: &AppContext) -> bool {
 284        self.results_editor.read(cx).has_conflict(cx)
 285    }
 286
 287    fn save(
 288        &mut self,
 289        project: ModelHandle<Project>,
 290        cx: &mut ViewContext<Self>,
 291    ) -> Task<anyhow::Result<()>> {
 292        self.results_editor
 293            .update(cx, |editor, cx| editor.save(project, cx))
 294    }
 295
 296    fn save_as(
 297        &mut self,
 298        _: ModelHandle<Project>,
 299        _: PathBuf,
 300        _: &mut ViewContext<Self>,
 301    ) -> Task<anyhow::Result<()>> {
 302        unreachable!("save_as should not have been called")
 303    }
 304
 305    fn reload(
 306        &mut self,
 307        project: ModelHandle<Project>,
 308        cx: &mut ViewContext<Self>,
 309    ) -> Task<anyhow::Result<()>> {
 310        self.results_editor
 311            .update(cx, |editor, cx| editor.reload(project, cx))
 312    }
 313
 314    fn clone_on_split(&self, cx: &mut ViewContext<Self>) -> Option<Self>
 315    where
 316        Self: Sized,
 317    {
 318        let model = self.model.update(cx, |model, cx| model.clone(cx));
 319        Some(Self::new(model, cx))
 320    }
 321
 322    fn set_nav_history(&mut self, nav_history: ItemNavHistory, cx: &mut ViewContext<Self>) {
 323        self.results_editor.update(cx, |editor, _| {
 324            editor.set_nav_history(Some(nav_history));
 325        });
 326    }
 327
 328    fn navigate(&mut self, data: Box<dyn Any>, cx: &mut ViewContext<Self>) -> bool {
 329        self.results_editor
 330            .update(cx, |editor, cx| editor.navigate(data, cx))
 331    }
 332
 333    fn should_activate_item_on_event(event: &Self::Event) -> bool {
 334        if let ViewEvent::EditorEvent(editor_event) = event {
 335            Editor::should_activate_item_on_event(editor_event)
 336        } else {
 337            false
 338        }
 339    }
 340
 341    fn should_update_tab_on_event(event: &ViewEvent) -> bool {
 342        matches!(event, ViewEvent::UpdateTab)
 343    }
 344
 345    fn is_edit_event(event: &Self::Event) -> bool {
 346        if let ViewEvent::EditorEvent(editor_event) = event {
 347            Editor::is_edit_event(editor_event)
 348        } else {
 349            false
 350        }
 351    }
 352}
 353
 354impl ProjectSearchView {
 355    fn new(model: ModelHandle<ProjectSearch>, cx: &mut ViewContext<Self>) -> Self {
 356        let project;
 357        let excerpts;
 358        let mut query_text = String::new();
 359        let mut regex = false;
 360        let mut case_sensitive = false;
 361        let mut whole_word = false;
 362
 363        {
 364            let model = model.read(cx);
 365            project = model.project.clone();
 366            excerpts = model.excerpts.clone();
 367            if let Some(active_query) = model.active_query.as_ref() {
 368                query_text = active_query.as_str().to_string();
 369                regex = active_query.is_regex();
 370                case_sensitive = active_query.case_sensitive();
 371                whole_word = active_query.whole_word();
 372            }
 373        }
 374        cx.observe(&model, |this, _, cx| this.model_changed(true, cx))
 375            .detach();
 376
 377        let query_editor = cx.add_view(|cx| {
 378            let mut editor =
 379                Editor::single_line(Some(|theme| theme.search.editor.input.clone()), cx);
 380            editor.set_text(query_text, cx);
 381            editor
 382        });
 383        // Subcribe to query_editor in order to reraise editor events for workspace item activation purposes
 384        cx.subscribe(&query_editor, |_, _, event, cx| {
 385            cx.emit(ViewEvent::EditorEvent(event.clone()))
 386        })
 387        .detach();
 388        cx.observe_focus(&query_editor, |this, _, focused, _| {
 389            if focused {
 390                this.results_editor_was_focused = false;
 391            }
 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        cx.observe_focus(&results_editor, |this, _, focused, _| {
 403            if focused {
 404                this.results_editor_was_focused = true;
 405            }
 406        })
 407        .detach();
 408        cx.subscribe(&results_editor, |this, _, event, cx| {
 409            if matches!(event, editor::Event::SelectionsChanged { .. }) {
 410                this.update_match_index(cx);
 411            }
 412            // Reraise editor events for workspace item activation purposes
 413            cx.emit(ViewEvent::EditorEvent(event.clone()));
 414        })
 415        .detach();
 416
 417        let mut this = ProjectSearchView {
 418            model,
 419            query_editor,
 420            results_editor,
 421            case_sensitive,
 422            whole_word,
 423            regex,
 424            query_contains_error: false,
 425            active_match_index: None,
 426            results_editor_was_focused: false,
 427        };
 428        this.model_changed(false, cx);
 429        this
 430    }
 431
 432    // Re-activate the most recently activated search or the most recent if it has been closed.
 433    // If no search exists in the workspace, create a new one.
 434    fn deploy(workspace: &mut Workspace, _: &Deploy, cx: &mut ViewContext<Workspace>) {
 435        // Clean up entries for dropped projects
 436        cx.update_global(|state: &mut ActiveSearches, cx| {
 437            state.0.retain(|project, _| project.is_upgradable(cx))
 438        });
 439
 440        let active_search = cx
 441            .global::<ActiveSearches>()
 442            .0
 443            .get(&workspace.project().downgrade());
 444
 445        let existing = active_search
 446            .and_then(|active_search| {
 447                workspace
 448                    .items_of_type::<ProjectSearchView>(cx)
 449                    .find(|search| search == active_search)
 450            })
 451            .or_else(|| workspace.item_of_type::<ProjectSearchView>(cx));
 452
 453        let query = workspace.active_item(cx).and_then(|item| {
 454            let editor = item.act_as::<Editor>(cx)?;
 455            let query = query_suggestion_for_editor(&editor, cx);
 456            if query.is_empty() {
 457                None
 458            } else {
 459                Some(query)
 460            }
 461        });
 462
 463        let search = if let Some(existing) = existing {
 464            workspace.activate_item(&existing, cx);
 465            existing
 466        } else {
 467            let model = cx.add_model(|cx| ProjectSearch::new(workspace.project().clone(), cx));
 468            let view = cx.add_view(|cx| ProjectSearchView::new(model, cx));
 469            workspace.add_item(Box::new(view.clone()), cx);
 470            view
 471        };
 472
 473        search.update(cx, |search, cx| {
 474            if let Some(query) = query {
 475                search.set_query(&query, cx);
 476            }
 477            search.focus_query_editor(cx)
 478        });
 479    }
 480
 481    fn search(&mut self, cx: &mut ViewContext<Self>) {
 482        if let Some(query) = self.build_search_query(cx) {
 483            self.model.update(cx, |model, cx| model.search(query, cx));
 484        }
 485    }
 486
 487    fn build_search_query(&mut self, cx: &mut ViewContext<Self>) -> Option<SearchQuery> {
 488        let text = self.query_editor.read(cx).text(cx);
 489        if self.regex {
 490            match SearchQuery::regex(text, self.whole_word, self.case_sensitive) {
 491                Ok(query) => Some(query),
 492                Err(_) => {
 493                    self.query_contains_error = true;
 494                    cx.notify();
 495                    None
 496                }
 497            }
 498        } else {
 499            Some(SearchQuery::text(
 500                text,
 501                self.whole_word,
 502                self.case_sensitive,
 503            ))
 504        }
 505    }
 506
 507    fn select_match(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 508        if let Some(index) = self.active_match_index {
 509            let model = self.model.read(cx);
 510            let results_editor = self.results_editor.read(cx);
 511            let new_index = match_index_for_direction(
 512                &model.match_ranges,
 513                &results_editor.selections.newest_anchor().head(),
 514                index,
 515                direction,
 516                &results_editor.buffer().read(cx).snapshot(cx),
 517            );
 518            let range_to_select = model.match_ranges[new_index].clone();
 519            self.results_editor.update(cx, |editor, cx| {
 520                editor.unfold_ranges([range_to_select.clone()], false, cx);
 521                editor.change_selections(Some(Autoscroll::Fit), cx, |s| {
 522                    s.select_ranges([range_to_select])
 523                });
 524            });
 525        }
 526    }
 527
 528    fn focus_query_editor(&self, cx: &mut ViewContext<Self>) {
 529        self.query_editor.update(cx, |query_editor, cx| {
 530            query_editor.select_all(&SelectAll, cx);
 531        });
 532        cx.focus(&self.query_editor);
 533    }
 534
 535    fn set_query(&mut self, query: &str, cx: &mut ViewContext<Self>) {
 536        self.query_editor
 537            .update(cx, |query_editor, cx| query_editor.set_text(query, cx));
 538    }
 539
 540    fn focus_results_editor(&self, cx: &mut ViewContext<Self>) {
 541        self.query_editor.update(cx, |query_editor, cx| {
 542            let cursor = query_editor.selections.newest_anchor().head();
 543            query_editor.change_selections(None, cx, |s| s.select_ranges([cursor.clone()..cursor]));
 544        });
 545        cx.focus(&self.results_editor);
 546    }
 547
 548    fn model_changed(&mut self, reset_selections: bool, cx: &mut ViewContext<Self>) {
 549        let match_ranges = self.model.read(cx).match_ranges.clone();
 550        if match_ranges.is_empty() {
 551            self.active_match_index = None;
 552        } else {
 553            self.results_editor.update(cx, |editor, cx| {
 554                if reset_selections {
 555                    editor.change_selections(Some(Autoscroll::Fit), cx, |s| {
 556                        s.select_ranges(match_ranges.first().cloned())
 557                    });
 558                }
 559                editor.highlight_background::<Self>(
 560                    match_ranges,
 561                    |theme| theme.search.match_background,
 562                    cx,
 563                );
 564            });
 565            if self.query_editor.is_focused(cx) {
 566                self.focus_results_editor(cx);
 567            }
 568        }
 569
 570        cx.emit(ViewEvent::UpdateTab);
 571        cx.notify();
 572    }
 573
 574    fn update_match_index(&mut self, cx: &mut ViewContext<Self>) {
 575        let results_editor = self.results_editor.read(cx);
 576        let new_index = active_match_index(
 577            &self.model.read(cx).match_ranges,
 578            &results_editor.selections.newest_anchor().head(),
 579            &results_editor.buffer().read(cx).snapshot(cx),
 580        );
 581        if self.active_match_index != new_index {
 582            self.active_match_index = new_index;
 583            cx.notify();
 584        }
 585    }
 586
 587    pub fn has_matches(&self) -> bool {
 588        self.active_match_index.is_some()
 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::new::<NavButton, _, _>(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::new::<Self, _, _>(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)
 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            self.subscription = Some(cx.observe(&search, |_, _, cx| cx.notify()));
 904            self.active_project_search = Some(search);
 905            ToolbarItemLocation::PrimaryLeft {
 906                flex: Some((1., false)),
 907            }
 908        } else {
 909            ToolbarItemLocation::Hidden
 910        }
 911    }
 912}
 913
 914#[cfg(test)]
 915mod tests {
 916    use super::*;
 917    use editor::DisplayPoint;
 918    use gpui::{color::Color, TestAppContext};
 919    use project::FakeFs;
 920    use serde_json::json;
 921    use std::sync::Arc;
 922
 923    #[gpui::test]
 924    async fn test_project_search(cx: &mut TestAppContext) {
 925        let fonts = cx.font_cache();
 926        let mut theme = gpui::fonts::with_font_cache(fonts.clone(), || theme::Theme::default());
 927        theme.search.match_background = Color::red();
 928        cx.update(|cx| {
 929            let mut settings = Settings::test(cx);
 930            settings.theme = Arc::new(theme);
 931            cx.set_global(settings)
 932        });
 933
 934        let fs = FakeFs::new(cx.background());
 935        fs.insert_tree(
 936            "/dir",
 937            json!({
 938                "one.rs": "const ONE: usize = 1;",
 939                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
 940                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
 941                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
 942            }),
 943        )
 944        .await;
 945        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
 946        let search = cx.add_model(|cx| ProjectSearch::new(project, cx));
 947        let search_view = cx.add_view(Default::default(), |cx| {
 948            ProjectSearchView::new(search.clone(), cx)
 949        });
 950
 951        search_view.update(cx, |search_view, cx| {
 952            search_view
 953                .query_editor
 954                .update(cx, |query_editor, cx| query_editor.set_text("TWO", cx));
 955            search_view.search(cx);
 956        });
 957        search_view.next_notification(&cx).await;
 958        search_view.update(cx, |search_view, cx| {
 959            assert_eq!(
 960                search_view
 961                    .results_editor
 962                    .update(cx, |editor, cx| editor.display_text(cx)),
 963                "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;"
 964            );
 965            assert_eq!(
 966                search_view
 967                    .results_editor
 968                    .update(cx, |editor, cx| editor.all_background_highlights(cx)),
 969                &[
 970                    (
 971                        DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35),
 972                        Color::red()
 973                    ),
 974                    (
 975                        DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40),
 976                        Color::red()
 977                    ),
 978                    (
 979                        DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9),
 980                        Color::red()
 981                    )
 982                ]
 983            );
 984            assert_eq!(search_view.active_match_index, Some(0));
 985            assert_eq!(
 986                search_view
 987                    .results_editor
 988                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
 989                [DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35)]
 990            );
 991
 992            search_view.select_match(Direction::Next, cx);
 993        });
 994
 995        search_view.update(cx, |search_view, cx| {
 996            assert_eq!(search_view.active_match_index, Some(1));
 997            assert_eq!(
 998                search_view
 999                    .results_editor
1000                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1001                [DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40)]
1002            );
1003            search_view.select_match(Direction::Next, cx);
1004        });
1005
1006        search_view.update(cx, |search_view, cx| {
1007            assert_eq!(search_view.active_match_index, Some(2));
1008            assert_eq!(
1009                search_view
1010                    .results_editor
1011                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1012                [DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9)]
1013            );
1014            search_view.select_match(Direction::Next, cx);
1015        });
1016
1017        search_view.update(cx, |search_view, cx| {
1018            assert_eq!(search_view.active_match_index, Some(0));
1019            assert_eq!(
1020                search_view
1021                    .results_editor
1022                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1023                [DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35)]
1024            );
1025            search_view.select_match(Direction::Prev, cx);
1026        });
1027
1028        search_view.update(cx, |search_view, cx| {
1029            assert_eq!(search_view.active_match_index, Some(2));
1030            assert_eq!(
1031                search_view
1032                    .results_editor
1033                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1034                [DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9)]
1035            );
1036            search_view.select_match(Direction::Prev, cx);
1037        });
1038
1039        search_view.update(cx, |search_view, cx| {
1040            assert_eq!(search_view.active_match_index, Some(1));
1041            assert_eq!(
1042                search_view
1043                    .results_editor
1044                    .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1045                [DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40)]
1046            );
1047        });
1048    }
1049}