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