1use crate::{
2 BufferSearchBar, FocusSearch, NextHistoryQuery, PreviousHistoryQuery, ReplaceAll, ReplaceNext,
3 SearchOption, SearchOptions, SearchSource, SelectNextMatch, SelectPreviousMatch,
4 ToggleCaseSensitive, ToggleIncludeIgnored, ToggleRegex, ToggleReplace, ToggleWholeWord,
5 buffer_search::Deploy,
6 search_bar::{ActionButtonState, input_base_styles, render_action_button, render_text_input},
7};
8use anyhow::Context as _;
9use collections::HashMap;
10use editor::{
11 Anchor, Editor, EditorEvent, EditorSettings, MAX_TAB_TITLE_LEN, MultiBuffer, PathKey,
12 SelectionEffects, VimFlavor,
13 actions::{Backtab, SelectAll, Tab},
14 items::active_match_index,
15 multibuffer_context_lines,
16 scroll::Autoscroll,
17 vim_flavor,
18};
19use futures::{StreamExt, stream::FuturesOrdered};
20use gpui::{
21 Action, AnyElement, AnyView, App, Axis, Context, Entity, EntityId, EventEmitter, FocusHandle,
22 Focusable, Global, Hsla, InteractiveElement, IntoElement, KeyContext, ParentElement, Point,
23 Render, SharedString, Styled, Subscription, Task, UpdateGlobal, WeakEntity, Window, actions,
24 div,
25};
26use language::{Buffer, Language};
27use menu::Confirm;
28use project::{
29 Project, ProjectPath,
30 search::{SearchInputKind, SearchQuery},
31 search_history::SearchHistoryCursor,
32};
33use settings::Settings;
34use std::{
35 any::{Any, TypeId},
36 mem,
37 ops::{Not, Range},
38 pin::pin,
39 sync::Arc,
40};
41use ui::{IconButtonShape, KeyBinding, Toggleable, Tooltip, prelude::*, utils::SearchInputWidth};
42use util::{ResultExt as _, paths::PathMatcher, rel_path::RelPath};
43use workspace::{
44 DeploySearch, ItemNavHistory, NewSearch, ToolbarItemEvent, ToolbarItemLocation,
45 ToolbarItemView, Workspace, WorkspaceId,
46 item::{BreadcrumbText, Item, ItemEvent, ItemHandle, SaveOptions},
47 searchable::{Direction, SearchableItem, SearchableItemHandle},
48};
49
50actions!(
51 project_search,
52 [
53 /// Searches in a new project search tab.
54 SearchInNew,
55 /// Toggles focus between the search bar and the search results.
56 ToggleFocus,
57 /// Moves to the next input field.
58 NextField,
59 /// Toggles the search filters panel.
60 ToggleFilters,
61 /// Toggles collapse/expand state of all search result excerpts.
62 ToggleAllSearchResults
63 ]
64);
65
66#[derive(Default)]
67struct ActiveSettings(HashMap<WeakEntity<Project>, ProjectSearchSettings>);
68
69impl Global for ActiveSettings {}
70
71pub fn init(cx: &mut App) {
72 cx.set_global(ActiveSettings::default());
73 cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
74 register_workspace_action(workspace, move |search_bar, _: &Deploy, window, cx| {
75 search_bar.focus_search(window, cx);
76 });
77 register_workspace_action(workspace, move |search_bar, _: &FocusSearch, window, cx| {
78 search_bar.focus_search(window, cx);
79 });
80 register_workspace_action(
81 workspace,
82 move |search_bar, _: &ToggleFilters, window, cx| {
83 search_bar.toggle_filters(window, cx);
84 },
85 );
86 register_workspace_action(
87 workspace,
88 move |search_bar, _: &ToggleCaseSensitive, window, cx| {
89 search_bar.toggle_search_option(SearchOptions::CASE_SENSITIVE, window, cx);
90 },
91 );
92 register_workspace_action(
93 workspace,
94 move |search_bar, _: &ToggleWholeWord, window, cx| {
95 search_bar.toggle_search_option(SearchOptions::WHOLE_WORD, window, cx);
96 },
97 );
98 register_workspace_action(workspace, move |search_bar, _: &ToggleRegex, window, cx| {
99 search_bar.toggle_search_option(SearchOptions::REGEX, window, cx);
100 });
101 register_workspace_action(
102 workspace,
103 move |search_bar, action: &ToggleReplace, window, cx| {
104 search_bar.toggle_replace(action, window, cx)
105 },
106 );
107 register_workspace_action(
108 workspace,
109 move |search_bar, action: &SelectPreviousMatch, window, cx| {
110 search_bar.select_prev_match(action, window, cx)
111 },
112 );
113 register_workspace_action(
114 workspace,
115 move |search_bar, action: &SelectNextMatch, window, cx| {
116 search_bar.select_next_match(action, window, cx)
117 },
118 );
119
120 // Only handle search_in_new if there is a search present
121 register_workspace_action_for_present_search(workspace, |workspace, action, window, cx| {
122 ProjectSearchView::search_in_new(workspace, action, window, cx)
123 });
124
125 register_workspace_action_for_present_search(
126 workspace,
127 |workspace, action: &ToggleAllSearchResults, window, cx| {
128 if let Some(search_view) = workspace
129 .active_item(cx)
130 .and_then(|item| item.downcast::<ProjectSearchView>())
131 {
132 search_view.update(cx, |search_view, cx| {
133 search_view.toggle_all_search_results(action, window, cx);
134 });
135 }
136 },
137 );
138
139 register_workspace_action_for_present_search(
140 workspace,
141 |workspace, _: &menu::Cancel, window, cx| {
142 if let Some(project_search_bar) = workspace
143 .active_pane()
144 .read(cx)
145 .toolbar()
146 .read(cx)
147 .item_of_type::<ProjectSearchBar>()
148 {
149 project_search_bar.update(cx, |project_search_bar, cx| {
150 let search_is_focused = project_search_bar
151 .active_project_search
152 .as_ref()
153 .is_some_and(|search_view| {
154 search_view
155 .read(cx)
156 .query_editor
157 .read(cx)
158 .focus_handle(cx)
159 .is_focused(window)
160 });
161 if search_is_focused {
162 project_search_bar.move_focus_to_results(window, cx);
163 } else {
164 project_search_bar.focus_search(window, cx)
165 }
166 });
167 } else {
168 cx.propagate();
169 }
170 },
171 );
172
173 // Both on present and dismissed search, we need to unconditionally handle those actions to focus from the editor.
174 workspace.register_action(move |workspace, action: &DeploySearch, window, cx| {
175 if workspace.has_active_modal(window, cx) && !workspace.hide_modal(window, cx) {
176 cx.propagate();
177 return;
178 }
179 ProjectSearchView::deploy_search(workspace, action, window, cx);
180 cx.notify();
181 });
182 workspace.register_action(move |workspace, action: &NewSearch, window, cx| {
183 if workspace.has_active_modal(window, cx) && !workspace.hide_modal(window, cx) {
184 cx.propagate();
185 return;
186 }
187 ProjectSearchView::new_search(workspace, action, window, cx);
188 cx.notify();
189 });
190 })
191 .detach();
192}
193
194fn contains_uppercase(str: &str) -> bool {
195 str.chars().any(|c| c.is_uppercase())
196}
197
198pub struct ProjectSearch {
199 project: Entity<Project>,
200 excerpts: Entity<MultiBuffer>,
201 pending_search: Option<Task<Option<()>>>,
202 match_ranges: Vec<Range<Anchor>>,
203 active_query: Option<SearchQuery>,
204 last_search_query_text: Option<String>,
205 search_id: usize,
206 no_results: Option<bool>,
207 limit_reached: bool,
208 search_history_cursor: SearchHistoryCursor,
209 search_included_history_cursor: SearchHistoryCursor,
210 search_excluded_history_cursor: SearchHistoryCursor,
211}
212
213#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
214enum InputPanel {
215 Query,
216 Replacement,
217 Exclude,
218 Include,
219}
220
221pub struct ProjectSearchView {
222 workspace: WeakEntity<Workspace>,
223 focus_handle: FocusHandle,
224 entity: Entity<ProjectSearch>,
225 query_editor: Entity<Editor>,
226 replacement_editor: Entity<Editor>,
227 results_editor: Entity<Editor>,
228 search_options: SearchOptions,
229 panels_with_errors: HashMap<InputPanel, String>,
230 active_match_index: Option<usize>,
231 search_id: usize,
232 included_files_editor: Entity<Editor>,
233 excluded_files_editor: Entity<Editor>,
234 filters_enabled: bool,
235 replace_enabled: bool,
236 included_opened_only: bool,
237 regex_language: Option<Arc<Language>>,
238 results_collapsed: bool,
239 _subscriptions: Vec<Subscription>,
240}
241
242#[derive(Debug, Clone)]
243pub struct ProjectSearchSettings {
244 search_options: SearchOptions,
245 filters_enabled: bool,
246}
247
248pub struct ProjectSearchBar {
249 active_project_search: Option<Entity<ProjectSearchView>>,
250 subscription: Option<Subscription>,
251}
252
253impl ProjectSearch {
254 pub fn new(project: Entity<Project>, cx: &mut Context<Self>) -> Self {
255 let capability = project.read(cx).capability();
256
257 Self {
258 project,
259 excerpts: cx.new(|_| MultiBuffer::new(capability)),
260 pending_search: Default::default(),
261 match_ranges: Default::default(),
262 active_query: None,
263 last_search_query_text: None,
264 search_id: 0,
265 no_results: None,
266 limit_reached: false,
267 search_history_cursor: Default::default(),
268 search_included_history_cursor: Default::default(),
269 search_excluded_history_cursor: Default::default(),
270 }
271 }
272
273 fn clone(&self, cx: &mut Context<Self>) -> Entity<Self> {
274 cx.new(|cx| Self {
275 project: self.project.clone(),
276 excerpts: self
277 .excerpts
278 .update(cx, |excerpts, cx| cx.new(|cx| excerpts.clone(cx))),
279 pending_search: Default::default(),
280 match_ranges: self.match_ranges.clone(),
281 active_query: self.active_query.clone(),
282 last_search_query_text: self.last_search_query_text.clone(),
283 search_id: self.search_id,
284 no_results: self.no_results,
285 limit_reached: self.limit_reached,
286 search_history_cursor: self.search_history_cursor.clone(),
287 search_included_history_cursor: self.search_included_history_cursor.clone(),
288 search_excluded_history_cursor: self.search_excluded_history_cursor.clone(),
289 })
290 }
291 fn cursor(&self, kind: SearchInputKind) -> &SearchHistoryCursor {
292 match kind {
293 SearchInputKind::Query => &self.search_history_cursor,
294 SearchInputKind::Include => &self.search_included_history_cursor,
295 SearchInputKind::Exclude => &self.search_excluded_history_cursor,
296 }
297 }
298 fn cursor_mut(&mut self, kind: SearchInputKind) -> &mut SearchHistoryCursor {
299 match kind {
300 SearchInputKind::Query => &mut self.search_history_cursor,
301 SearchInputKind::Include => &mut self.search_included_history_cursor,
302 SearchInputKind::Exclude => &mut self.search_excluded_history_cursor,
303 }
304 }
305
306 fn search(&mut self, query: SearchQuery, cx: &mut Context<Self>) {
307 let search = self.project.update(cx, |project, cx| {
308 project
309 .search_history_mut(SearchInputKind::Query)
310 .add(&mut self.search_history_cursor, query.as_str().to_string());
311 let included = query.as_inner().files_to_include().sources().join(",");
312 if !included.is_empty() {
313 project
314 .search_history_mut(SearchInputKind::Include)
315 .add(&mut self.search_included_history_cursor, included);
316 }
317 let excluded = query.as_inner().files_to_exclude().sources().join(",");
318 if !excluded.is_empty() {
319 project
320 .search_history_mut(SearchInputKind::Exclude)
321 .add(&mut self.search_excluded_history_cursor, excluded);
322 }
323 project.search(query.clone(), cx)
324 });
325 self.last_search_query_text = Some(query.as_str().to_string());
326 self.search_id += 1;
327 self.active_query = Some(query);
328 self.match_ranges.clear();
329 self.pending_search = Some(cx.spawn(async move |project_search, cx| {
330 let mut matches = pin!(search.ready_chunks(1024));
331 project_search
332 .update(cx, |project_search, cx| {
333 project_search.match_ranges.clear();
334 project_search
335 .excerpts
336 .update(cx, |excerpts, cx| excerpts.clear(cx));
337 project_search.no_results = Some(true);
338 project_search.limit_reached = false;
339 })
340 .ok()?;
341
342 let mut limit_reached = false;
343 while let Some(results) = matches.next().await {
344 let (buffers_with_ranges, has_reached_limit) = cx
345 .background_executor()
346 .spawn(async move {
347 let mut limit_reached = false;
348 let mut buffers_with_ranges = Vec::with_capacity(results.len());
349 for result in results {
350 match result {
351 project::search::SearchResult::Buffer { buffer, ranges } => {
352 buffers_with_ranges.push((buffer, ranges));
353 }
354 project::search::SearchResult::LimitReached => {
355 limit_reached = true;
356 }
357 }
358 }
359 (buffers_with_ranges, limit_reached)
360 })
361 .await;
362 limit_reached |= has_reached_limit;
363 let mut new_ranges = project_search
364 .update(cx, |project_search, cx| {
365 project_search.excerpts.update(cx, |excerpts, cx| {
366 buffers_with_ranges
367 .into_iter()
368 .map(|(buffer, ranges)| {
369 excerpts.set_anchored_excerpts_for_path(
370 PathKey::for_buffer(&buffer, cx),
371 buffer,
372 ranges,
373 multibuffer_context_lines(cx),
374 cx,
375 )
376 })
377 .collect::<FuturesOrdered<_>>()
378 })
379 })
380 .ok()?;
381 while let Some(new_ranges) = new_ranges.next().await {
382 project_search
383 .update(cx, |project_search, cx| {
384 project_search.match_ranges.extend(new_ranges);
385 cx.notify();
386 })
387 .ok()?;
388 }
389 }
390
391 project_search
392 .update(cx, |project_search, cx| {
393 if !project_search.match_ranges.is_empty() {
394 project_search.no_results = Some(false);
395 }
396 project_search.limit_reached = limit_reached;
397 project_search.pending_search.take();
398 cx.notify();
399 })
400 .ok()?;
401
402 None
403 }));
404 cx.notify();
405 }
406}
407
408#[derive(Clone, Debug, PartialEq, Eq)]
409pub enum ViewEvent {
410 UpdateTab,
411 Activate,
412 EditorEvent(editor::EditorEvent),
413 Dismiss,
414}
415
416impl EventEmitter<ViewEvent> for ProjectSearchView {}
417
418impl Render for ProjectSearchView {
419 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
420 if self.has_matches() {
421 div()
422 .flex_1()
423 .size_full()
424 .track_focus(&self.focus_handle(cx))
425 .child(self.results_editor.clone())
426 } else {
427 let model = self.entity.read(cx);
428 let has_no_results = model.no_results.unwrap_or(false);
429 let is_search_underway = model.pending_search.is_some();
430
431 let heading_text = if is_search_underway {
432 "Searching…"
433 } else if has_no_results {
434 "No Results"
435 } else {
436 "Search All Files"
437 };
438
439 let heading_text = div()
440 .justify_center()
441 .child(Label::new(heading_text).size(LabelSize::Large));
442
443 let page_content: Option<AnyElement> = if let Some(no_results) = model.no_results {
444 if model.pending_search.is_none() && no_results {
445 Some(
446 Label::new("No results found in this project for the provided query")
447 .size(LabelSize::Small)
448 .into_any_element(),
449 )
450 } else {
451 None
452 }
453 } else {
454 Some(self.landing_text_minor(cx).into_any_element())
455 };
456
457 let page_content = page_content.map(|text| div().child(text));
458
459 h_flex()
460 .size_full()
461 .items_center()
462 .justify_center()
463 .overflow_hidden()
464 .bg(cx.theme().colors().editor_background)
465 .track_focus(&self.focus_handle(cx))
466 .child(
467 v_flex()
468 .id("project-search-landing-page")
469 .overflow_y_scroll()
470 .gap_1()
471 .child(heading_text)
472 .children(page_content),
473 )
474 }
475 }
476}
477
478impl Focusable for ProjectSearchView {
479 fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
480 self.focus_handle.clone()
481 }
482}
483
484impl Item for ProjectSearchView {
485 type Event = ViewEvent;
486 fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString> {
487 let query_text = self.query_editor.read(cx).text(cx);
488
489 query_text
490 .is_empty()
491 .not()
492 .then(|| query_text.into())
493 .or_else(|| Some("Project Search".into()))
494 }
495
496 fn act_as_type<'a>(
497 &'a self,
498 type_id: TypeId,
499 self_handle: &'a Entity<Self>,
500 _: &'a App,
501 ) -> Option<AnyView> {
502 if type_id == TypeId::of::<Self>() {
503 Some(self_handle.clone().into())
504 } else if type_id == TypeId::of::<Editor>() {
505 Some(self.results_editor.clone().into())
506 } else {
507 None
508 }
509 }
510 fn as_searchable(&self, _: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
511 Some(Box::new(self.results_editor.clone()))
512 }
513
514 fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
515 self.results_editor
516 .update(cx, |editor, cx| editor.deactivated(window, cx));
517 }
518
519 fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
520 Some(Icon::new(IconName::MagnifyingGlass))
521 }
522
523 fn tab_content_text(&self, _detail: usize, cx: &App) -> SharedString {
524 let last_query: Option<SharedString> = self
525 .entity
526 .read(cx)
527 .last_search_query_text
528 .as_ref()
529 .map(|query| {
530 let query = query.replace('\n', "");
531 let query_text = util::truncate_and_trailoff(&query, MAX_TAB_TITLE_LEN);
532 query_text.into()
533 });
534
535 last_query
536 .filter(|query| !query.is_empty())
537 .unwrap_or_else(|| "Project Search".into())
538 }
539
540 fn telemetry_event_text(&self) -> Option<&'static str> {
541 Some("Project Search Opened")
542 }
543
544 fn for_each_project_item(
545 &self,
546 cx: &App,
547 f: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
548 ) {
549 self.results_editor.for_each_project_item(cx, f)
550 }
551
552 fn can_save(&self, _: &App) -> bool {
553 true
554 }
555
556 fn is_dirty(&self, cx: &App) -> bool {
557 self.results_editor.read(cx).is_dirty(cx)
558 }
559
560 fn has_conflict(&self, cx: &App) -> bool {
561 self.results_editor.read(cx).has_conflict(cx)
562 }
563
564 fn save(
565 &mut self,
566 options: SaveOptions,
567 project: Entity<Project>,
568 window: &mut Window,
569 cx: &mut Context<Self>,
570 ) -> Task<anyhow::Result<()>> {
571 self.results_editor
572 .update(cx, |editor, cx| editor.save(options, project, window, cx))
573 }
574
575 fn save_as(
576 &mut self,
577 _: Entity<Project>,
578 _: ProjectPath,
579 _window: &mut Window,
580 _: &mut Context<Self>,
581 ) -> Task<anyhow::Result<()>> {
582 unreachable!("save_as should not have been called")
583 }
584
585 fn reload(
586 &mut self,
587 project: Entity<Project>,
588 window: &mut Window,
589 cx: &mut Context<Self>,
590 ) -> Task<anyhow::Result<()>> {
591 self.results_editor
592 .update(cx, |editor, cx| editor.reload(project, window, cx))
593 }
594
595 fn can_split(&self) -> bool {
596 true
597 }
598
599 fn clone_on_split(
600 &self,
601 _workspace_id: Option<WorkspaceId>,
602 window: &mut Window,
603 cx: &mut Context<Self>,
604 ) -> Task<Option<Entity<Self>>>
605 where
606 Self: Sized,
607 {
608 let model = self.entity.update(cx, |model, cx| model.clone(cx));
609 Task::ready(Some(cx.new(|cx| {
610 Self::new(self.workspace.clone(), model, window, cx, None)
611 })))
612 }
613
614 fn added_to_workspace(
615 &mut self,
616 workspace: &mut Workspace,
617 window: &mut Window,
618 cx: &mut Context<Self>,
619 ) {
620 self.results_editor.update(cx, |editor, cx| {
621 editor.added_to_workspace(workspace, window, cx)
622 });
623 }
624
625 fn set_nav_history(
626 &mut self,
627 nav_history: ItemNavHistory,
628 _: &mut Window,
629 cx: &mut Context<Self>,
630 ) {
631 self.results_editor.update(cx, |editor, _| {
632 editor.set_nav_history(Some(nav_history));
633 });
634 }
635
636 fn navigate(
637 &mut self,
638 data: Box<dyn Any>,
639 window: &mut Window,
640 cx: &mut Context<Self>,
641 ) -> bool {
642 self.results_editor
643 .update(cx, |editor, cx| editor.navigate(data, window, cx))
644 }
645
646 fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
647 match event {
648 ViewEvent::UpdateTab => {
649 f(ItemEvent::UpdateBreadcrumbs);
650 f(ItemEvent::UpdateTab);
651 }
652 ViewEvent::EditorEvent(editor_event) => {
653 Editor::to_item_events(editor_event, f);
654 }
655 ViewEvent::Dismiss => f(ItemEvent::CloseItem),
656 _ => {}
657 }
658 }
659
660 fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
661 if self.has_matches() {
662 ToolbarItemLocation::Secondary
663 } else {
664 ToolbarItemLocation::Hidden
665 }
666 }
667
668 fn breadcrumbs(&self, theme: &theme::Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
669 self.results_editor.breadcrumbs(theme, cx)
670 }
671
672 fn breadcrumb_prefix(
673 &self,
674 _window: &mut Window,
675 cx: &mut Context<Self>,
676 ) -> Option<gpui::AnyElement> {
677 if !self.has_matches() {
678 return None;
679 }
680
681 let is_collapsed = self.results_collapsed;
682
683 let (icon, tooltip_label) = if is_collapsed {
684 (IconName::ChevronUpDown, "Expand All Search Results")
685 } else {
686 (IconName::ChevronDownUp, "Collapse All Search Results")
687 };
688
689 let focus_handle = self.query_editor.focus_handle(cx);
690
691 Some(
692 IconButton::new("project-search-collapse-expand", icon)
693 .shape(IconButtonShape::Square)
694 .icon_size(IconSize::Small)
695 .tooltip(move |_, cx| {
696 Tooltip::for_action_in(
697 tooltip_label,
698 &ToggleAllSearchResults,
699 &focus_handle,
700 cx,
701 )
702 })
703 .on_click(cx.listener(|this, _, window, cx| {
704 this.toggle_all_search_results(&ToggleAllSearchResults, window, cx);
705 }))
706 .into_any_element(),
707 )
708 }
709}
710
711impl ProjectSearchView {
712 pub fn get_matches(&self, cx: &App) -> Vec<Range<Anchor>> {
713 self.entity.read(cx).match_ranges.clone()
714 }
715
716 fn toggle_filters(&mut self, cx: &mut Context<Self>) {
717 self.filters_enabled = !self.filters_enabled;
718 ActiveSettings::update_global(cx, |settings, cx| {
719 settings.0.insert(
720 self.entity.read(cx).project.downgrade(),
721 self.current_settings(),
722 );
723 });
724 }
725
726 fn current_settings(&self) -> ProjectSearchSettings {
727 ProjectSearchSettings {
728 search_options: self.search_options,
729 filters_enabled: self.filters_enabled,
730 }
731 }
732
733 fn toggle_search_option(&mut self, option: SearchOptions, cx: &mut Context<Self>) {
734 self.search_options.toggle(option);
735 ActiveSettings::update_global(cx, |settings, cx| {
736 settings.0.insert(
737 self.entity.read(cx).project.downgrade(),
738 self.current_settings(),
739 );
740 });
741 self.adjust_query_regex_language(cx);
742 }
743
744 fn toggle_opened_only(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {
745 self.included_opened_only = !self.included_opened_only;
746 }
747
748 pub fn replacement(&self, cx: &App) -> String {
749 self.replacement_editor.read(cx).text(cx)
750 }
751
752 fn replace_next(&mut self, _: &ReplaceNext, window: &mut Window, cx: &mut Context<Self>) {
753 if let Some(last_search_query_text) = &self.entity.read(cx).last_search_query_text
754 && self.query_editor.read(cx).text(cx) != *last_search_query_text
755 {
756 // search query has changed, restart search and bail
757 self.search(cx);
758 return;
759 }
760 if self.entity.read(cx).match_ranges.is_empty() {
761 return;
762 }
763 let Some(active_index) = self.active_match_index else {
764 return;
765 };
766
767 let query = self.entity.read(cx).active_query.clone();
768 if let Some(query) = query {
769 let query = query.with_replacement(self.replacement(cx));
770
771 // TODO: Do we need the clone here?
772 let mat = self.entity.read(cx).match_ranges[active_index].clone();
773 self.results_editor.update(cx, |editor, cx| {
774 editor.replace(&mat, &query, window, cx);
775 });
776 self.select_match(Direction::Next, window, cx)
777 }
778 }
779 fn replace_all(&mut self, _: &ReplaceAll, window: &mut Window, cx: &mut Context<Self>) {
780 if let Some(last_search_query_text) = &self.entity.read(cx).last_search_query_text
781 && self.query_editor.read(cx).text(cx) != *last_search_query_text
782 {
783 // search query has changed, restart search and bail
784 self.search(cx);
785 return;
786 }
787 if self.active_match_index.is_none() {
788 return;
789 }
790 let Some(query) = self.entity.read(cx).active_query.as_ref() else {
791 return;
792 };
793 let query = query.clone().with_replacement(self.replacement(cx));
794
795 let match_ranges = self
796 .entity
797 .update(cx, |model, _| mem::take(&mut model.match_ranges));
798 if match_ranges.is_empty() {
799 return;
800 }
801
802 self.results_editor.update(cx, |editor, cx| {
803 editor.replace_all(&mut match_ranges.iter(), &query, window, cx);
804 });
805
806 self.entity.update(cx, |model, _cx| {
807 model.match_ranges = match_ranges;
808 });
809 }
810
811 fn toggle_all_search_results(
812 &mut self,
813 _: &ToggleAllSearchResults,
814 _window: &mut Window,
815 cx: &mut Context<Self>,
816 ) {
817 self.results_collapsed = !self.results_collapsed;
818 self.update_results_visibility(cx);
819 }
820
821 fn update_results_visibility(&mut self, cx: &mut Context<Self>) {
822 self.results_editor.update(cx, |editor, cx| {
823 let multibuffer = editor.buffer().read(cx);
824 let buffer_ids = multibuffer.excerpt_buffer_ids();
825
826 if self.results_collapsed {
827 for buffer_id in buffer_ids {
828 editor.fold_buffer(buffer_id, cx);
829 }
830 } else {
831 for buffer_id in buffer_ids {
832 editor.unfold_buffer(buffer_id, cx);
833 }
834 }
835 });
836 cx.notify();
837 }
838
839 pub fn new(
840 workspace: WeakEntity<Workspace>,
841 entity: Entity<ProjectSearch>,
842 window: &mut Window,
843 cx: &mut Context<Self>,
844 settings: Option<ProjectSearchSettings>,
845 ) -> Self {
846 let project;
847 let excerpts;
848 let mut replacement_text = None;
849 let mut query_text = String::new();
850 let mut subscriptions = Vec::new();
851
852 // Read in settings if available
853 let (mut options, filters_enabled) = if let Some(settings) = settings {
854 (settings.search_options, settings.filters_enabled)
855 } else {
856 let search_options =
857 SearchOptions::from_settings(&EditorSettings::get_global(cx).search);
858 (search_options, false)
859 };
860
861 {
862 let entity = entity.read(cx);
863 project = entity.project.clone();
864 excerpts = entity.excerpts.clone();
865 if let Some(active_query) = entity.active_query.as_ref() {
866 query_text = active_query.as_str().to_string();
867 replacement_text = active_query.replacement().map(ToOwned::to_owned);
868 options = SearchOptions::from_query(active_query);
869 }
870 }
871 subscriptions.push(cx.observe_in(&entity, window, |this, _, window, cx| {
872 this.entity_changed(window, cx)
873 }));
874
875 let query_editor = cx.new(|cx| {
876 let mut editor = Editor::single_line(window, cx);
877 editor.set_placeholder_text("Search all files…", window, cx);
878 editor.set_text(query_text, window, cx);
879 editor
880 });
881 // Subscribe to query_editor in order to reraise editor events for workspace item activation purposes
882 subscriptions.push(
883 cx.subscribe(&query_editor, |this, _, event: &EditorEvent, cx| {
884 if let EditorEvent::Edited { .. } = event
885 && EditorSettings::get_global(cx).use_smartcase_search
886 {
887 let query = this.search_query_text(cx);
888 if !query.is_empty()
889 && this.search_options.contains(SearchOptions::CASE_SENSITIVE)
890 != contains_uppercase(&query)
891 {
892 this.toggle_search_option(SearchOptions::CASE_SENSITIVE, cx);
893 }
894 }
895 cx.emit(ViewEvent::EditorEvent(event.clone()))
896 }),
897 );
898 let replacement_editor = cx.new(|cx| {
899 let mut editor = Editor::single_line(window, cx);
900 editor.set_placeholder_text("Replace in project…", window, cx);
901 if let Some(text) = replacement_text {
902 editor.set_text(text, window, cx);
903 }
904 editor
905 });
906 let results_editor = cx.new(|cx| {
907 let mut editor = Editor::for_multibuffer(excerpts, Some(project.clone()), window, cx);
908 editor.set_searchable(false);
909 editor.set_in_project_search(true);
910 editor
911 });
912 subscriptions.push(cx.observe(&results_editor, |_, _, cx| cx.emit(ViewEvent::UpdateTab)));
913
914 subscriptions.push(
915 cx.subscribe(&results_editor, |this, _, event: &EditorEvent, cx| {
916 if matches!(event, editor::EditorEvent::SelectionsChanged { .. }) {
917 this.update_match_index(cx);
918 }
919 // Reraise editor events for workspace item activation purposes
920 cx.emit(ViewEvent::EditorEvent(event.clone()));
921 }),
922 );
923
924 let included_files_editor = cx.new(|cx| {
925 let mut editor = Editor::single_line(window, cx);
926 editor.set_placeholder_text("Include: crates/**/*.toml", window, cx);
927
928 editor
929 });
930 // Subscribe to include_files_editor in order to reraise editor events for workspace item activation purposes
931 subscriptions.push(
932 cx.subscribe(&included_files_editor, |_, _, event: &EditorEvent, cx| {
933 cx.emit(ViewEvent::EditorEvent(event.clone()))
934 }),
935 );
936
937 let excluded_files_editor = cx.new(|cx| {
938 let mut editor = Editor::single_line(window, cx);
939 editor.set_placeholder_text("Exclude: vendor/*, *.lock", window, cx);
940
941 editor
942 });
943 // Subscribe to excluded_files_editor in order to reraise editor events for workspace item activation purposes
944 subscriptions.push(
945 cx.subscribe(&excluded_files_editor, |_, _, event: &EditorEvent, cx| {
946 cx.emit(ViewEvent::EditorEvent(event.clone()))
947 }),
948 );
949
950 let focus_handle = cx.focus_handle();
951 subscriptions.push(cx.on_focus(&focus_handle, window, |_, window, cx| {
952 cx.on_next_frame(window, |this, window, cx| {
953 if this.focus_handle.is_focused(window) {
954 if this.has_matches() {
955 this.results_editor.focus_handle(cx).focus(window);
956 } else {
957 this.query_editor.focus_handle(cx).focus(window);
958 }
959 }
960 });
961 }));
962
963 let languages = project.read(cx).languages().clone();
964 cx.spawn(async move |project_search_view, cx| {
965 let regex_language = languages
966 .language_for_name("regex")
967 .await
968 .context("loading regex language")?;
969 project_search_view
970 .update(cx, |project_search_view, cx| {
971 project_search_view.regex_language = Some(regex_language);
972 project_search_view.adjust_query_regex_language(cx);
973 })
974 .ok();
975 anyhow::Ok(())
976 })
977 .detach_and_log_err(cx);
978
979 // Check if Worktrees have all been previously indexed
980 let mut this = ProjectSearchView {
981 workspace,
982 focus_handle,
983 replacement_editor,
984 search_id: entity.read(cx).search_id,
985 entity,
986 query_editor,
987 results_editor,
988 search_options: options,
989 panels_with_errors: HashMap::default(),
990 active_match_index: None,
991 included_files_editor,
992 excluded_files_editor,
993 filters_enabled,
994 replace_enabled: false,
995 included_opened_only: false,
996 regex_language: None,
997 results_collapsed: false,
998 _subscriptions: subscriptions,
999 };
1000
1001 this.entity_changed(window, cx);
1002 this
1003 }
1004
1005 pub fn new_search_in_directory(
1006 workspace: &mut Workspace,
1007 dir_path: &RelPath,
1008 window: &mut Window,
1009 cx: &mut Context<Workspace>,
1010 ) {
1011 let filter_str = dir_path.display(workspace.path_style(cx));
1012
1013 let weak_workspace = cx.entity().downgrade();
1014
1015 let entity = cx.new(|cx| ProjectSearch::new(workspace.project().clone(), cx));
1016 let search = cx.new(|cx| ProjectSearchView::new(weak_workspace, entity, window, cx, None));
1017 workspace.add_item_to_active_pane(Box::new(search.clone()), None, true, window, cx);
1018 search.update(cx, |search, cx| {
1019 search
1020 .included_files_editor
1021 .update(cx, |editor, cx| editor.set_text(filter_str, window, cx));
1022 search.filters_enabled = true;
1023 search.focus_query_editor(window, cx)
1024 });
1025 }
1026
1027 /// Re-activate the most recently activated search in this pane or the most recent if it has been closed.
1028 /// If no search exists in the workspace, create a new one.
1029 pub fn deploy_search(
1030 workspace: &mut Workspace,
1031 action: &workspace::DeploySearch,
1032 window: &mut Window,
1033 cx: &mut Context<Workspace>,
1034 ) {
1035 let existing = workspace
1036 .active_pane()
1037 .read(cx)
1038 .items()
1039 .find_map(|item| item.downcast::<ProjectSearchView>());
1040
1041 Self::existing_or_new_search(workspace, existing, action, window, cx);
1042 }
1043
1044 fn search_in_new(
1045 workspace: &mut Workspace,
1046 _: &SearchInNew,
1047 window: &mut Window,
1048 cx: &mut Context<Workspace>,
1049 ) {
1050 if let Some(search_view) = workspace
1051 .active_item(cx)
1052 .and_then(|item| item.downcast::<ProjectSearchView>())
1053 {
1054 let new_query = search_view.update(cx, |search_view, cx| {
1055 let open_buffers = if search_view.included_opened_only {
1056 Some(search_view.open_buffers(cx, workspace))
1057 } else {
1058 None
1059 };
1060 let new_query = search_view.build_search_query(cx, open_buffers);
1061 if new_query.is_some()
1062 && let Some(old_query) = search_view.entity.read(cx).active_query.clone()
1063 {
1064 search_view.query_editor.update(cx, |editor, cx| {
1065 editor.set_text(old_query.as_str(), window, cx);
1066 });
1067 search_view.search_options = SearchOptions::from_query(&old_query);
1068 search_view.adjust_query_regex_language(cx);
1069 }
1070 new_query
1071 });
1072 if let Some(new_query) = new_query {
1073 let entity = cx.new(|cx| {
1074 let mut entity = ProjectSearch::new(workspace.project().clone(), cx);
1075 entity.search(new_query, cx);
1076 entity
1077 });
1078 let weak_workspace = cx.entity().downgrade();
1079 workspace.add_item_to_active_pane(
1080 Box::new(cx.new(|cx| {
1081 ProjectSearchView::new(weak_workspace, entity, window, cx, None)
1082 })),
1083 None,
1084 true,
1085 window,
1086 cx,
1087 );
1088 }
1089 }
1090 }
1091
1092 // Add another search tab to the workspace.
1093 fn new_search(
1094 workspace: &mut Workspace,
1095 _: &workspace::NewSearch,
1096 window: &mut Window,
1097 cx: &mut Context<Workspace>,
1098 ) {
1099 Self::existing_or_new_search(workspace, None, &DeploySearch::find(), window, cx)
1100 }
1101
1102 fn existing_or_new_search(
1103 workspace: &mut Workspace,
1104 existing: Option<Entity<ProjectSearchView>>,
1105 action: &workspace::DeploySearch,
1106 window: &mut Window,
1107 cx: &mut Context<Workspace>,
1108 ) {
1109 let query = workspace.active_item(cx).and_then(|item| {
1110 if let Some(buffer_search_query) = buffer_search_query(workspace, item.as_ref(), cx) {
1111 return Some(buffer_search_query);
1112 }
1113
1114 let editor = item.act_as::<Editor>(cx)?;
1115 let query = editor.query_suggestion(window, cx);
1116 if query.is_empty() { None } else { Some(query) }
1117 });
1118
1119 let search = if let Some(existing) = existing {
1120 workspace.activate_item(&existing, true, true, window, cx);
1121 existing
1122 } else {
1123 let settings = cx
1124 .global::<ActiveSettings>()
1125 .0
1126 .get(&workspace.project().downgrade());
1127
1128 let settings = settings.cloned();
1129
1130 let weak_workspace = cx.entity().downgrade();
1131
1132 let project_search = cx.new(|cx| ProjectSearch::new(workspace.project().clone(), cx));
1133 let project_search_view = cx.new(|cx| {
1134 ProjectSearchView::new(weak_workspace, project_search, window, cx, settings)
1135 });
1136
1137 workspace.add_item_to_active_pane(
1138 Box::new(project_search_view.clone()),
1139 None,
1140 true,
1141 window,
1142 cx,
1143 );
1144 project_search_view
1145 };
1146
1147 search.update(cx, |search, cx| {
1148 search.replace_enabled = action.replace_enabled;
1149 if let Some(query) = query {
1150 search.set_query(&query, window, cx);
1151 }
1152 if let Some(included_files) = action.included_files.as_deref() {
1153 search
1154 .included_files_editor
1155 .update(cx, |editor, cx| editor.set_text(included_files, window, cx));
1156 search.filters_enabled = true;
1157 }
1158 if let Some(excluded_files) = action.excluded_files.as_deref() {
1159 search
1160 .excluded_files_editor
1161 .update(cx, |editor, cx| editor.set_text(excluded_files, window, cx));
1162 search.filters_enabled = true;
1163 }
1164 search.focus_query_editor(window, cx)
1165 });
1166 }
1167
1168 fn prompt_to_save_if_dirty_then_search(
1169 &mut self,
1170 window: &mut Window,
1171 cx: &mut Context<Self>,
1172 ) -> Task<anyhow::Result<()>> {
1173 let project = self.entity.read(cx).project.clone();
1174
1175 let can_autosave = self.results_editor.can_autosave(cx);
1176 let autosave_setting = self.results_editor.workspace_settings(cx).autosave;
1177
1178 let will_autosave = can_autosave && autosave_setting.should_save_on_close();
1179
1180 let is_dirty = self.is_dirty(cx);
1181
1182 cx.spawn_in(window, async move |this, cx| {
1183 let skip_save_on_close = this
1184 .read_with(cx, |this, cx| {
1185 this.workspace.read_with(cx, |workspace, cx| {
1186 workspace::Pane::skip_save_on_close(&this.results_editor, workspace, cx)
1187 })
1188 })?
1189 .unwrap_or(false);
1190
1191 let should_prompt_to_save = !skip_save_on_close && !will_autosave && is_dirty;
1192
1193 let should_search = if should_prompt_to_save {
1194 let options = &["Save", "Don't Save", "Cancel"];
1195 let result_channel = this.update_in(cx, |_, window, cx| {
1196 window.prompt(
1197 gpui::PromptLevel::Warning,
1198 "Project search buffer contains unsaved edits. Do you want to save it?",
1199 None,
1200 options,
1201 cx,
1202 )
1203 })?;
1204 let result = result_channel.await?;
1205 let should_save = result == 0;
1206 if should_save {
1207 this.update_in(cx, |this, window, cx| {
1208 this.save(
1209 SaveOptions {
1210 format: true,
1211 autosave: false,
1212 },
1213 project,
1214 window,
1215 cx,
1216 )
1217 })?
1218 .await
1219 .log_err();
1220 }
1221
1222 result != 2
1223 } else {
1224 true
1225 };
1226 if should_search {
1227 this.update(cx, |this, cx| {
1228 this.search(cx);
1229 })?;
1230 }
1231 anyhow::Ok(())
1232 })
1233 }
1234
1235 fn search(&mut self, cx: &mut Context<Self>) {
1236 let open_buffers = if self.included_opened_only {
1237 self.workspace
1238 .update(cx, |workspace, cx| self.open_buffers(cx, workspace))
1239 .ok()
1240 } else {
1241 None
1242 };
1243 if let Some(query) = self.build_search_query(cx, open_buffers) {
1244 self.entity.update(cx, |model, cx| model.search(query, cx));
1245 }
1246 }
1247
1248 pub fn search_query_text(&self, cx: &App) -> String {
1249 self.query_editor.read(cx).text(cx)
1250 }
1251
1252 fn build_search_query(
1253 &mut self,
1254 cx: &mut Context<Self>,
1255 open_buffers: Option<Vec<Entity<Buffer>>>,
1256 ) -> Option<SearchQuery> {
1257 // Do not bail early in this function, as we want to fill out `self.panels_with_errors`.
1258
1259 let text = self.search_query_text(cx);
1260 let included_files = self
1261 .filters_enabled
1262 .then(|| {
1263 match self.parse_path_matches(self.included_files_editor.read(cx).text(cx), cx) {
1264 Ok(included_files) => {
1265 let should_unmark_error =
1266 self.panels_with_errors.remove(&InputPanel::Include);
1267 if should_unmark_error.is_some() {
1268 cx.notify();
1269 }
1270 included_files
1271 }
1272 Err(e) => {
1273 let should_mark_error = self
1274 .panels_with_errors
1275 .insert(InputPanel::Include, e.to_string());
1276 if should_mark_error.is_none() {
1277 cx.notify();
1278 }
1279 PathMatcher::default()
1280 }
1281 }
1282 })
1283 .unwrap_or(PathMatcher::default());
1284 let excluded_files = self
1285 .filters_enabled
1286 .then(|| {
1287 match self.parse_path_matches(self.excluded_files_editor.read(cx).text(cx), cx) {
1288 Ok(excluded_files) => {
1289 let should_unmark_error =
1290 self.panels_with_errors.remove(&InputPanel::Exclude);
1291 if should_unmark_error.is_some() {
1292 cx.notify();
1293 }
1294
1295 excluded_files
1296 }
1297 Err(e) => {
1298 let should_mark_error = self
1299 .panels_with_errors
1300 .insert(InputPanel::Exclude, e.to_string());
1301 if should_mark_error.is_none() {
1302 cx.notify();
1303 }
1304 PathMatcher::default()
1305 }
1306 }
1307 })
1308 .unwrap_or(PathMatcher::default());
1309
1310 // If the project contains multiple visible worktrees, we match the
1311 // include/exclude patterns against full paths to allow them to be
1312 // disambiguated. For single worktree projects we use worktree relative
1313 // paths for convenience.
1314 let match_full_paths = self
1315 .entity
1316 .read(cx)
1317 .project
1318 .read(cx)
1319 .visible_worktrees(cx)
1320 .count()
1321 > 1;
1322
1323 let query = if self.search_options.contains(SearchOptions::REGEX) {
1324 match SearchQuery::regex(
1325 text,
1326 self.search_options.contains(SearchOptions::WHOLE_WORD),
1327 self.search_options.contains(SearchOptions::CASE_SENSITIVE),
1328 self.search_options.contains(SearchOptions::INCLUDE_IGNORED),
1329 self.search_options
1330 .contains(SearchOptions::ONE_MATCH_PER_LINE),
1331 included_files,
1332 excluded_files,
1333 match_full_paths,
1334 open_buffers,
1335 ) {
1336 Ok(query) => {
1337 let should_unmark_error = self.panels_with_errors.remove(&InputPanel::Query);
1338 if should_unmark_error.is_some() {
1339 cx.notify();
1340 }
1341
1342 Some(query)
1343 }
1344 Err(e) => {
1345 let should_mark_error = self
1346 .panels_with_errors
1347 .insert(InputPanel::Query, e.to_string());
1348 if should_mark_error.is_none() {
1349 cx.notify();
1350 }
1351
1352 None
1353 }
1354 }
1355 } else {
1356 match SearchQuery::text(
1357 text,
1358 self.search_options.contains(SearchOptions::WHOLE_WORD),
1359 self.search_options.contains(SearchOptions::CASE_SENSITIVE),
1360 self.search_options.contains(SearchOptions::INCLUDE_IGNORED),
1361 included_files,
1362 excluded_files,
1363 match_full_paths,
1364 open_buffers,
1365 ) {
1366 Ok(query) => {
1367 let should_unmark_error = self.panels_with_errors.remove(&InputPanel::Query);
1368 if should_unmark_error.is_some() {
1369 cx.notify();
1370 }
1371
1372 Some(query)
1373 }
1374 Err(e) => {
1375 let should_mark_error = self
1376 .panels_with_errors
1377 .insert(InputPanel::Query, e.to_string());
1378 if should_mark_error.is_none() {
1379 cx.notify();
1380 }
1381
1382 None
1383 }
1384 }
1385 };
1386 if !self.panels_with_errors.is_empty() {
1387 return None;
1388 }
1389 if query.as_ref().is_some_and(|query| query.is_empty()) {
1390 return None;
1391 }
1392 query
1393 }
1394
1395 fn open_buffers(&self, cx: &App, workspace: &Workspace) -> Vec<Entity<Buffer>> {
1396 let mut buffers = Vec::new();
1397 for editor in workspace.items_of_type::<Editor>(cx) {
1398 if let Some(buffer) = editor.read(cx).buffer().read(cx).as_singleton() {
1399 buffers.push(buffer);
1400 }
1401 }
1402 buffers
1403 }
1404
1405 fn parse_path_matches(&self, text: String, cx: &App) -> anyhow::Result<PathMatcher> {
1406 let path_style = self.entity.read(cx).project.read(cx).path_style(cx);
1407 let queries = text
1408 .split(',')
1409 .map(str::trim)
1410 .filter(|maybe_glob_str| !maybe_glob_str.is_empty())
1411 .map(str::to_owned)
1412 .collect::<Vec<_>>();
1413 Ok(PathMatcher::new(&queries, path_style)?)
1414 }
1415
1416 fn select_match(&mut self, direction: Direction, window: &mut Window, cx: &mut Context<Self>) {
1417 if let Some(index) = self.active_match_index {
1418 let match_ranges = self.entity.read(cx).match_ranges.clone();
1419
1420 if !EditorSettings::get_global(cx).search_wrap
1421 && ((direction == Direction::Next && index + 1 >= match_ranges.len())
1422 || (direction == Direction::Prev && index == 0))
1423 {
1424 crate::show_no_more_matches(window, cx);
1425 return;
1426 }
1427
1428 let new_index = self.results_editor.update(cx, |editor, cx| {
1429 editor.match_index_for_direction(&match_ranges, index, direction, 1, window, cx)
1430 });
1431
1432 let range_to_select = match_ranges[new_index].clone();
1433 self.results_editor.update(cx, |editor, cx| {
1434 let collapse = vim_flavor(cx) == Some(VimFlavor::Vim);
1435 let range_to_select = editor.range_for_match(&range_to_select, collapse);
1436 let autoscroll = if EditorSettings::get_global(cx).search.center_on_match {
1437 Autoscroll::center()
1438 } else {
1439 Autoscroll::fit()
1440 };
1441 editor.unfold_ranges(std::slice::from_ref(&range_to_select), false, true, cx);
1442 editor.change_selections(SelectionEffects::scroll(autoscroll), window, cx, |s| {
1443 s.select_ranges([range_to_select])
1444 });
1445 });
1446 }
1447 }
1448
1449 fn focus_query_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1450 self.query_editor.update(cx, |query_editor, cx| {
1451 query_editor.select_all(&SelectAll, window, cx);
1452 });
1453 let editor_handle = self.query_editor.focus_handle(cx);
1454 window.focus(&editor_handle);
1455 }
1456
1457 fn set_query(&mut self, query: &str, window: &mut Window, cx: &mut Context<Self>) {
1458 self.set_search_editor(SearchInputKind::Query, query, window, cx);
1459 if EditorSettings::get_global(cx).use_smartcase_search
1460 && !query.is_empty()
1461 && self.search_options.contains(SearchOptions::CASE_SENSITIVE)
1462 != contains_uppercase(query)
1463 {
1464 self.toggle_search_option(SearchOptions::CASE_SENSITIVE, cx)
1465 }
1466 }
1467
1468 fn set_search_editor(
1469 &mut self,
1470 kind: SearchInputKind,
1471 text: &str,
1472 window: &mut Window,
1473 cx: &mut Context<Self>,
1474 ) {
1475 let editor = match kind {
1476 SearchInputKind::Query => &self.query_editor,
1477 SearchInputKind::Include => &self.included_files_editor,
1478
1479 SearchInputKind::Exclude => &self.excluded_files_editor,
1480 };
1481 editor.update(cx, |included_editor, cx| {
1482 included_editor.set_text(text, window, cx)
1483 });
1484 }
1485
1486 fn focus_results_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1487 self.query_editor.update(cx, |query_editor, cx| {
1488 let cursor = query_editor.selections.newest_anchor().head();
1489 query_editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1490 s.select_ranges([cursor..cursor])
1491 });
1492 });
1493 let results_handle = self.results_editor.focus_handle(cx);
1494 window.focus(&results_handle);
1495 }
1496
1497 fn entity_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1498 let match_ranges = self.entity.read(cx).match_ranges.clone();
1499
1500 if match_ranges.is_empty() {
1501 self.active_match_index = None;
1502 self.results_editor.update(cx, |editor, cx| {
1503 editor.clear_background_highlights::<Self>(cx);
1504 });
1505 } else {
1506 self.active_match_index = Some(0);
1507 self.update_match_index(cx);
1508 let prev_search_id = mem::replace(&mut self.search_id, self.entity.read(cx).search_id);
1509 let is_new_search = self.search_id != prev_search_id;
1510 self.results_editor.update(cx, |editor, cx| {
1511 if is_new_search {
1512 let collapse = vim_flavor(cx) == Some(VimFlavor::Vim);
1513 let range_to_select = match_ranges
1514 .first()
1515 .map(|range| editor.range_for_match(range, collapse));
1516 editor.change_selections(Default::default(), window, cx, |s| {
1517 s.select_ranges(range_to_select)
1518 });
1519 editor.scroll(Point::default(), Some(Axis::Vertical), window, cx);
1520 }
1521 editor.highlight_background::<Self>(
1522 &match_ranges,
1523 |theme| theme.colors().search_match_background,
1524 cx,
1525 );
1526 });
1527 if is_new_search && self.query_editor.focus_handle(cx).is_focused(window) {
1528 self.focus_results_editor(window, cx);
1529 }
1530 }
1531
1532 cx.emit(ViewEvent::UpdateTab);
1533 cx.notify();
1534 }
1535
1536 fn update_match_index(&mut self, cx: &mut Context<Self>) {
1537 let results_editor = self.results_editor.read(cx);
1538 let new_index = active_match_index(
1539 Direction::Next,
1540 &self.entity.read(cx).match_ranges,
1541 &results_editor.selections.newest_anchor().head(),
1542 &results_editor.buffer().read(cx).snapshot(cx),
1543 );
1544 if self.active_match_index != new_index {
1545 self.active_match_index = new_index;
1546 cx.notify();
1547 }
1548 }
1549
1550 pub fn has_matches(&self) -> bool {
1551 self.active_match_index.is_some()
1552 }
1553
1554 fn landing_text_minor(&self, cx: &App) -> impl IntoElement {
1555 let focus_handle = self.focus_handle.clone();
1556 v_flex()
1557 .gap_1()
1558 .child(
1559 Label::new("Hit enter to search. For more options:")
1560 .color(Color::Muted)
1561 .mb_2(),
1562 )
1563 .child(
1564 Button::new("filter-paths", "Include/exclude specific paths")
1565 .icon(IconName::Filter)
1566 .icon_position(IconPosition::Start)
1567 .icon_size(IconSize::Small)
1568 .key_binding(KeyBinding::for_action_in(&ToggleFilters, &focus_handle, cx))
1569 .on_click(|_event, window, cx| {
1570 window.dispatch_action(ToggleFilters.boxed_clone(), cx)
1571 }),
1572 )
1573 .child(
1574 Button::new("find-replace", "Find and replace")
1575 .icon(IconName::Replace)
1576 .icon_position(IconPosition::Start)
1577 .icon_size(IconSize::Small)
1578 .key_binding(KeyBinding::for_action_in(&ToggleReplace, &focus_handle, cx))
1579 .on_click(|_event, window, cx| {
1580 window.dispatch_action(ToggleReplace.boxed_clone(), cx)
1581 }),
1582 )
1583 .child(
1584 Button::new("regex", "Match with regex")
1585 .icon(IconName::Regex)
1586 .icon_position(IconPosition::Start)
1587 .icon_size(IconSize::Small)
1588 .key_binding(KeyBinding::for_action_in(&ToggleRegex, &focus_handle, cx))
1589 .on_click(|_event, window, cx| {
1590 window.dispatch_action(ToggleRegex.boxed_clone(), cx)
1591 }),
1592 )
1593 .child(
1594 Button::new("match-case", "Match case")
1595 .icon(IconName::CaseSensitive)
1596 .icon_position(IconPosition::Start)
1597 .icon_size(IconSize::Small)
1598 .key_binding(KeyBinding::for_action_in(
1599 &ToggleCaseSensitive,
1600 &focus_handle,
1601 cx,
1602 ))
1603 .on_click(|_event, window, cx| {
1604 window.dispatch_action(ToggleCaseSensitive.boxed_clone(), cx)
1605 }),
1606 )
1607 .child(
1608 Button::new("match-whole-words", "Match whole words")
1609 .icon(IconName::WholeWord)
1610 .icon_position(IconPosition::Start)
1611 .icon_size(IconSize::Small)
1612 .key_binding(KeyBinding::for_action_in(
1613 &ToggleWholeWord,
1614 &focus_handle,
1615 cx,
1616 ))
1617 .on_click(|_event, window, cx| {
1618 window.dispatch_action(ToggleWholeWord.boxed_clone(), cx)
1619 }),
1620 )
1621 }
1622
1623 fn border_color_for(&self, panel: InputPanel, cx: &App) -> Hsla {
1624 if self.panels_with_errors.contains_key(&panel) {
1625 Color::Error.color(cx)
1626 } else {
1627 cx.theme().colors().border
1628 }
1629 }
1630
1631 fn move_focus_to_results(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1632 if !self.results_editor.focus_handle(cx).is_focused(window)
1633 && !self.entity.read(cx).match_ranges.is_empty()
1634 {
1635 cx.stop_propagation();
1636 self.focus_results_editor(window, cx)
1637 }
1638 }
1639
1640 #[cfg(any(test, feature = "test-support"))]
1641 pub fn results_editor(&self) -> &Entity<Editor> {
1642 &self.results_editor
1643 }
1644
1645 fn adjust_query_regex_language(&self, cx: &mut App) {
1646 let enable = self.search_options.contains(SearchOptions::REGEX);
1647 let query_buffer = self
1648 .query_editor
1649 .read(cx)
1650 .buffer()
1651 .read(cx)
1652 .as_singleton()
1653 .expect("query editor should be backed by a singleton buffer");
1654 if enable {
1655 if let Some(regex_language) = self.regex_language.clone() {
1656 query_buffer.update(cx, |query_buffer, cx| {
1657 query_buffer.set_language(Some(regex_language), cx);
1658 })
1659 }
1660 } else {
1661 query_buffer.update(cx, |query_buffer, cx| {
1662 query_buffer.set_language(None, cx);
1663 })
1664 }
1665 }
1666}
1667
1668fn buffer_search_query(
1669 workspace: &mut Workspace,
1670 item: &dyn ItemHandle,
1671 cx: &mut Context<Workspace>,
1672) -> Option<String> {
1673 let buffer_search_bar = workspace
1674 .pane_for(item)
1675 .and_then(|pane| {
1676 pane.read(cx)
1677 .toolbar()
1678 .read(cx)
1679 .item_of_type::<BufferSearchBar>()
1680 })?
1681 .read(cx);
1682 if buffer_search_bar.query_editor_focused() {
1683 let buffer_search_query = buffer_search_bar.query(cx);
1684 if !buffer_search_query.is_empty() {
1685 return Some(buffer_search_query);
1686 }
1687 }
1688 None
1689}
1690
1691impl Default for ProjectSearchBar {
1692 fn default() -> Self {
1693 Self::new()
1694 }
1695}
1696
1697impl ProjectSearchBar {
1698 pub fn new() -> Self {
1699 Self {
1700 active_project_search: None,
1701 subscription: None,
1702 }
1703 }
1704
1705 fn confirm(&mut self, _: &Confirm, window: &mut Window, cx: &mut Context<Self>) {
1706 if let Some(search_view) = self.active_project_search.as_ref() {
1707 search_view.update(cx, |search_view, cx| {
1708 if !search_view
1709 .replacement_editor
1710 .focus_handle(cx)
1711 .is_focused(window)
1712 {
1713 cx.stop_propagation();
1714 search_view
1715 .prompt_to_save_if_dirty_then_search(window, cx)
1716 .detach_and_log_err(cx);
1717 }
1718 });
1719 }
1720 }
1721
1722 fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
1723 self.cycle_field(Direction::Next, window, cx);
1724 }
1725
1726 fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
1727 self.cycle_field(Direction::Prev, window, cx);
1728 }
1729
1730 fn focus_search(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1731 if let Some(search_view) = self.active_project_search.as_ref() {
1732 search_view.update(cx, |search_view, cx| {
1733 search_view.query_editor.focus_handle(cx).focus(window);
1734 });
1735 }
1736 }
1737
1738 fn cycle_field(&mut self, direction: Direction, window: &mut Window, cx: &mut Context<Self>) {
1739 let active_project_search = match &self.active_project_search {
1740 Some(active_project_search) => active_project_search,
1741 None => return,
1742 };
1743
1744 active_project_search.update(cx, |project_view, cx| {
1745 let mut views = vec![project_view.query_editor.focus_handle(cx)];
1746 if project_view.replace_enabled {
1747 views.push(project_view.replacement_editor.focus_handle(cx));
1748 }
1749 if project_view.filters_enabled {
1750 views.extend([
1751 project_view.included_files_editor.focus_handle(cx),
1752 project_view.excluded_files_editor.focus_handle(cx),
1753 ]);
1754 }
1755 let current_index = match views.iter().position(|focus| focus.is_focused(window)) {
1756 Some(index) => index,
1757 None => return,
1758 };
1759
1760 let new_index = match direction {
1761 Direction::Next => (current_index + 1) % views.len(),
1762 Direction::Prev if current_index == 0 => views.len() - 1,
1763 Direction::Prev => (current_index - 1) % views.len(),
1764 };
1765 let next_focus_handle = &views[new_index];
1766 window.focus(next_focus_handle);
1767 cx.stop_propagation();
1768 });
1769 }
1770
1771 pub(crate) fn toggle_search_option(
1772 &mut self,
1773 option: SearchOptions,
1774 window: &mut Window,
1775 cx: &mut Context<Self>,
1776 ) -> bool {
1777 if self.active_project_search.is_none() {
1778 return false;
1779 }
1780
1781 cx.spawn_in(window, async move |this, cx| {
1782 let task = this.update_in(cx, |this, window, cx| {
1783 let search_view = this.active_project_search.as_ref()?;
1784 search_view.update(cx, |search_view, cx| {
1785 search_view.toggle_search_option(option, cx);
1786 search_view
1787 .entity
1788 .read(cx)
1789 .active_query
1790 .is_some()
1791 .then(|| search_view.prompt_to_save_if_dirty_then_search(window, cx))
1792 })
1793 })?;
1794 if let Some(task) = task {
1795 task.await?;
1796 }
1797 this.update(cx, |_, cx| {
1798 cx.notify();
1799 })?;
1800 anyhow::Ok(())
1801 })
1802 .detach();
1803 true
1804 }
1805
1806 fn toggle_replace(&mut self, _: &ToggleReplace, window: &mut Window, cx: &mut Context<Self>) {
1807 if let Some(search) = &self.active_project_search {
1808 search.update(cx, |this, cx| {
1809 this.replace_enabled = !this.replace_enabled;
1810 let editor_to_focus = if this.replace_enabled {
1811 this.replacement_editor.focus_handle(cx)
1812 } else {
1813 this.query_editor.focus_handle(cx)
1814 };
1815 window.focus(&editor_to_focus);
1816 cx.notify();
1817 });
1818 }
1819 }
1820
1821 fn toggle_filters(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
1822 if let Some(search_view) = self.active_project_search.as_ref() {
1823 search_view.update(cx, |search_view, cx| {
1824 search_view.toggle_filters(cx);
1825 search_view
1826 .included_files_editor
1827 .update(cx, |_, cx| cx.notify());
1828 search_view
1829 .excluded_files_editor
1830 .update(cx, |_, cx| cx.notify());
1831 window.refresh();
1832 cx.notify();
1833 });
1834 cx.notify();
1835 true
1836 } else {
1837 false
1838 }
1839 }
1840
1841 fn toggle_opened_only(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
1842 if self.active_project_search.is_none() {
1843 return false;
1844 }
1845
1846 cx.spawn_in(window, async move |this, cx| {
1847 let task = this.update_in(cx, |this, window, cx| {
1848 let search_view = this.active_project_search.as_ref()?;
1849 search_view.update(cx, |search_view, cx| {
1850 search_view.toggle_opened_only(window, cx);
1851 search_view
1852 .entity
1853 .read(cx)
1854 .active_query
1855 .is_some()
1856 .then(|| search_view.prompt_to_save_if_dirty_then_search(window, cx))
1857 })
1858 })?;
1859 if let Some(task) = task {
1860 task.await?;
1861 }
1862 this.update(cx, |_, cx| {
1863 cx.notify();
1864 })?;
1865 anyhow::Ok(())
1866 })
1867 .detach();
1868 true
1869 }
1870
1871 fn is_opened_only_enabled(&self, cx: &App) -> bool {
1872 if let Some(search_view) = self.active_project_search.as_ref() {
1873 search_view.read(cx).included_opened_only
1874 } else {
1875 false
1876 }
1877 }
1878
1879 fn move_focus_to_results(&self, window: &mut Window, cx: &mut Context<Self>) {
1880 if let Some(search_view) = self.active_project_search.as_ref() {
1881 search_view.update(cx, |search_view, cx| {
1882 search_view.move_focus_to_results(window, cx);
1883 });
1884 cx.notify();
1885 }
1886 }
1887
1888 fn next_history_query(
1889 &mut self,
1890 _: &NextHistoryQuery,
1891 window: &mut Window,
1892 cx: &mut Context<Self>,
1893 ) {
1894 if let Some(search_view) = self.active_project_search.as_ref() {
1895 search_view.update(cx, |search_view, cx| {
1896 for (editor, kind) in [
1897 (search_view.query_editor.clone(), SearchInputKind::Query),
1898 (
1899 search_view.included_files_editor.clone(),
1900 SearchInputKind::Include,
1901 ),
1902 (
1903 search_view.excluded_files_editor.clone(),
1904 SearchInputKind::Exclude,
1905 ),
1906 ] {
1907 if editor.focus_handle(cx).is_focused(window) {
1908 let new_query = search_view.entity.update(cx, |model, cx| {
1909 let project = model.project.clone();
1910
1911 if let Some(new_query) = project.update(cx, |project, _| {
1912 project
1913 .search_history_mut(kind)
1914 .next(model.cursor_mut(kind))
1915 .map(str::to_string)
1916 }) {
1917 new_query
1918 } else {
1919 model.cursor_mut(kind).reset();
1920 String::new()
1921 }
1922 });
1923 search_view.set_search_editor(kind, &new_query, window, cx);
1924 }
1925 }
1926 });
1927 }
1928 }
1929
1930 fn previous_history_query(
1931 &mut self,
1932 _: &PreviousHistoryQuery,
1933 window: &mut Window,
1934 cx: &mut Context<Self>,
1935 ) {
1936 if let Some(search_view) = self.active_project_search.as_ref() {
1937 search_view.update(cx, |search_view, cx| {
1938 for (editor, kind) in [
1939 (search_view.query_editor.clone(), SearchInputKind::Query),
1940 (
1941 search_view.included_files_editor.clone(),
1942 SearchInputKind::Include,
1943 ),
1944 (
1945 search_view.excluded_files_editor.clone(),
1946 SearchInputKind::Exclude,
1947 ),
1948 ] {
1949 if editor.focus_handle(cx).is_focused(window) {
1950 if editor.read(cx).text(cx).is_empty()
1951 && let Some(new_query) = search_view
1952 .entity
1953 .read(cx)
1954 .project
1955 .read(cx)
1956 .search_history(kind)
1957 .current(search_view.entity.read(cx).cursor(kind))
1958 .map(str::to_string)
1959 {
1960 search_view.set_search_editor(kind, &new_query, window, cx);
1961 return;
1962 }
1963
1964 if let Some(new_query) = search_view.entity.update(cx, |model, cx| {
1965 let project = model.project.clone();
1966 project.update(cx, |project, _| {
1967 project
1968 .search_history_mut(kind)
1969 .previous(model.cursor_mut(kind))
1970 .map(str::to_string)
1971 })
1972 }) {
1973 search_view.set_search_editor(kind, &new_query, window, cx);
1974 }
1975 }
1976 }
1977 });
1978 }
1979 }
1980
1981 fn select_next_match(
1982 &mut self,
1983 _: &SelectNextMatch,
1984 window: &mut Window,
1985 cx: &mut Context<Self>,
1986 ) {
1987 if let Some(search) = self.active_project_search.as_ref() {
1988 search.update(cx, |this, cx| {
1989 this.select_match(Direction::Next, window, cx);
1990 })
1991 }
1992 }
1993
1994 fn select_prev_match(
1995 &mut self,
1996 _: &SelectPreviousMatch,
1997 window: &mut Window,
1998 cx: &mut Context<Self>,
1999 ) {
2000 if let Some(search) = self.active_project_search.as_ref() {
2001 search.update(cx, |this, cx| {
2002 this.select_match(Direction::Prev, window, cx);
2003 })
2004 }
2005 }
2006}
2007
2008impl Render for ProjectSearchBar {
2009 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2010 let Some(search) = self.active_project_search.clone() else {
2011 return div();
2012 };
2013 let search = search.read(cx);
2014 let focus_handle = search.focus_handle(cx);
2015
2016 let container_width = window.viewport_size().width;
2017 let input_width = SearchInputWidth::calc_width(container_width);
2018
2019 let input_base_styles = |panel: InputPanel| {
2020 input_base_styles(search.border_color_for(panel, cx), |div| match panel {
2021 InputPanel::Query | InputPanel::Replacement => div.w(input_width),
2022 InputPanel::Include | InputPanel::Exclude => div.flex_grow(),
2023 })
2024 };
2025 let theme_colors = cx.theme().colors();
2026 let project_search = search.entity.read(cx);
2027 let limit_reached = project_search.limit_reached;
2028
2029 let color_override = match (
2030 &project_search.pending_search,
2031 project_search.no_results,
2032 &project_search.active_query,
2033 &project_search.last_search_query_text,
2034 ) {
2035 (None, Some(true), Some(q), Some(p)) if q.as_str() == p => Some(Color::Error),
2036 _ => None,
2037 };
2038
2039 let match_text = search
2040 .active_match_index
2041 .and_then(|index| {
2042 let index = index + 1;
2043 let match_quantity = project_search.match_ranges.len();
2044 if match_quantity > 0 {
2045 debug_assert!(match_quantity >= index);
2046 if limit_reached {
2047 Some(format!("{index}/{match_quantity}+"))
2048 } else {
2049 Some(format!("{index}/{match_quantity}"))
2050 }
2051 } else {
2052 None
2053 }
2054 })
2055 .unwrap_or_else(|| "0/0".to_string());
2056
2057 let query_focus = search.query_editor.focus_handle(cx);
2058
2059 let query_column = input_base_styles(InputPanel::Query)
2060 .on_action(cx.listener(|this, action, window, cx| this.confirm(action, window, cx)))
2061 .on_action(cx.listener(|this, action, window, cx| {
2062 this.previous_history_query(action, window, cx)
2063 }))
2064 .on_action(
2065 cx.listener(|this, action, window, cx| this.next_history_query(action, window, cx)),
2066 )
2067 .child(render_text_input(&search.query_editor, color_override, cx))
2068 .child(
2069 h_flex()
2070 .gap_1()
2071 .child(SearchOption::CaseSensitive.as_button(
2072 search.search_options,
2073 SearchSource::Project(cx),
2074 focus_handle.clone(),
2075 ))
2076 .child(SearchOption::WholeWord.as_button(
2077 search.search_options,
2078 SearchSource::Project(cx),
2079 focus_handle.clone(),
2080 ))
2081 .child(SearchOption::Regex.as_button(
2082 search.search_options,
2083 SearchSource::Project(cx),
2084 focus_handle.clone(),
2085 )),
2086 );
2087
2088 let matches_column = h_flex()
2089 .ml_1()
2090 .pl_1p5()
2091 .border_l_1()
2092 .border_color(theme_colors.border_variant)
2093 .child(render_action_button(
2094 "project-search-nav-button",
2095 IconName::ChevronLeft,
2096 search
2097 .active_match_index
2098 .is_none()
2099 .then_some(ActionButtonState::Disabled),
2100 "Select Previous Match",
2101 &SelectPreviousMatch,
2102 query_focus.clone(),
2103 ))
2104 .child(render_action_button(
2105 "project-search-nav-button",
2106 IconName::ChevronRight,
2107 search
2108 .active_match_index
2109 .is_none()
2110 .then_some(ActionButtonState::Disabled),
2111 "Select Next Match",
2112 &SelectNextMatch,
2113 query_focus,
2114 ))
2115 .child(
2116 div()
2117 .id("matches")
2118 .ml_2()
2119 .min_w(rems_from_px(40.))
2120 .child(Label::new(match_text).size(LabelSize::Small).color(
2121 if search.active_match_index.is_some() {
2122 Color::Default
2123 } else {
2124 Color::Disabled
2125 },
2126 ))
2127 .when(limit_reached, |el| {
2128 el.tooltip(Tooltip::text(
2129 "Search limits reached.\nTry narrowing your search.",
2130 ))
2131 }),
2132 );
2133
2134 let mode_column = h_flex()
2135 .gap_1()
2136 .min_w_64()
2137 .child(
2138 IconButton::new("project-search-filter-button", IconName::Filter)
2139 .shape(IconButtonShape::Square)
2140 .tooltip(|_window, cx| {
2141 Tooltip::for_action("Toggle Filters", &ToggleFilters, cx)
2142 })
2143 .on_click(cx.listener(|this, _, window, cx| {
2144 this.toggle_filters(window, cx);
2145 }))
2146 .toggle_state(
2147 self.active_project_search
2148 .as_ref()
2149 .map(|search| search.read(cx).filters_enabled)
2150 .unwrap_or_default(),
2151 )
2152 .tooltip({
2153 let focus_handle = focus_handle.clone();
2154 move |_window, cx| {
2155 Tooltip::for_action_in(
2156 "Toggle Filters",
2157 &ToggleFilters,
2158 &focus_handle,
2159 cx,
2160 )
2161 }
2162 }),
2163 )
2164 .child(render_action_button(
2165 "project-search",
2166 IconName::Replace,
2167 self.active_project_search
2168 .as_ref()
2169 .map(|search| search.read(cx).replace_enabled)
2170 .and_then(|enabled| enabled.then_some(ActionButtonState::Toggled)),
2171 "Toggle Replace",
2172 &ToggleReplace,
2173 focus_handle.clone(),
2174 ))
2175 .child(matches_column);
2176
2177 let search_line = h_flex()
2178 .w_full()
2179 .gap_2()
2180 .child(query_column)
2181 .child(mode_column);
2182
2183 let replace_line = search.replace_enabled.then(|| {
2184 let replace_column = input_base_styles(InputPanel::Replacement)
2185 .child(render_text_input(&search.replacement_editor, None, cx));
2186
2187 let focus_handle = search.replacement_editor.read(cx).focus_handle(cx);
2188
2189 let replace_actions = h_flex()
2190 .min_w_64()
2191 .gap_1()
2192 .child(render_action_button(
2193 "project-search-replace-button",
2194 IconName::ReplaceNext,
2195 Default::default(),
2196 "Replace Next Match",
2197 &ReplaceNext,
2198 focus_handle.clone(),
2199 ))
2200 .child(render_action_button(
2201 "project-search-replace-button",
2202 IconName::ReplaceAll,
2203 Default::default(),
2204 "Replace All Matches",
2205 &ReplaceAll,
2206 focus_handle,
2207 ));
2208
2209 h_flex()
2210 .w_full()
2211 .gap_2()
2212 .child(replace_column)
2213 .child(replace_actions)
2214 });
2215
2216 let filter_line = search.filters_enabled.then(|| {
2217 let include = input_base_styles(InputPanel::Include)
2218 .on_action(cx.listener(|this, action, window, cx| {
2219 this.previous_history_query(action, window, cx)
2220 }))
2221 .on_action(cx.listener(|this, action, window, cx| {
2222 this.next_history_query(action, window, cx)
2223 }))
2224 .child(render_text_input(&search.included_files_editor, None, cx));
2225 let exclude = input_base_styles(InputPanel::Exclude)
2226 .on_action(cx.listener(|this, action, window, cx| {
2227 this.previous_history_query(action, window, cx)
2228 }))
2229 .on_action(cx.listener(|this, action, window, cx| {
2230 this.next_history_query(action, window, cx)
2231 }))
2232 .child(render_text_input(&search.excluded_files_editor, None, cx));
2233 let mode_column = h_flex()
2234 .gap_1()
2235 .min_w_64()
2236 .child(
2237 IconButton::new("project-search-opened-only", IconName::FolderSearch)
2238 .shape(IconButtonShape::Square)
2239 .toggle_state(self.is_opened_only_enabled(cx))
2240 .tooltip(Tooltip::text("Only Search Open Files"))
2241 .on_click(cx.listener(|this, _, window, cx| {
2242 this.toggle_opened_only(window, cx);
2243 })),
2244 )
2245 .child(SearchOption::IncludeIgnored.as_button(
2246 search.search_options,
2247 SearchSource::Project(cx),
2248 focus_handle.clone(),
2249 ));
2250 h_flex()
2251 .w_full()
2252 .gap_2()
2253 .child(
2254 h_flex()
2255 .gap_2()
2256 .w(input_width)
2257 .child(include)
2258 .child(exclude),
2259 )
2260 .child(mode_column)
2261 });
2262
2263 let mut key_context = KeyContext::default();
2264 key_context.add("ProjectSearchBar");
2265 if search
2266 .replacement_editor
2267 .focus_handle(cx)
2268 .is_focused(window)
2269 {
2270 key_context.add("in_replace");
2271 }
2272
2273 let query_error_line = search
2274 .panels_with_errors
2275 .get(&InputPanel::Query)
2276 .map(|error| {
2277 Label::new(error)
2278 .size(LabelSize::Small)
2279 .color(Color::Error)
2280 .mt_neg_1()
2281 .ml_2()
2282 });
2283
2284 let filter_error_line = search
2285 .panels_with_errors
2286 .get(&InputPanel::Include)
2287 .or_else(|| search.panels_with_errors.get(&InputPanel::Exclude))
2288 .map(|error| {
2289 Label::new(error)
2290 .size(LabelSize::Small)
2291 .color(Color::Error)
2292 .mt_neg_1()
2293 .ml_2()
2294 });
2295
2296 v_flex()
2297 .gap_2()
2298 .py(px(1.0))
2299 .w_full()
2300 .key_context(key_context)
2301 .on_action(cx.listener(|this, _: &ToggleFocus, window, cx| {
2302 this.move_focus_to_results(window, cx)
2303 }))
2304 .on_action(cx.listener(|this, _: &ToggleFilters, window, cx| {
2305 this.toggle_filters(window, cx);
2306 }))
2307 .capture_action(cx.listener(Self::tab))
2308 .capture_action(cx.listener(Self::backtab))
2309 .on_action(cx.listener(|this, action, window, cx| this.confirm(action, window, cx)))
2310 .on_action(cx.listener(|this, action, window, cx| {
2311 this.toggle_replace(action, window, cx);
2312 }))
2313 .on_action(cx.listener(|this, _: &ToggleWholeWord, window, cx| {
2314 this.toggle_search_option(SearchOptions::WHOLE_WORD, window, cx);
2315 }))
2316 .on_action(cx.listener(|this, _: &ToggleCaseSensitive, window, cx| {
2317 this.toggle_search_option(SearchOptions::CASE_SENSITIVE, window, cx);
2318 }))
2319 .on_action(cx.listener(|this, action, window, cx| {
2320 if let Some(search) = this.active_project_search.as_ref() {
2321 search.update(cx, |this, cx| {
2322 this.replace_next(action, window, cx);
2323 })
2324 }
2325 }))
2326 .on_action(cx.listener(|this, action, window, cx| {
2327 if let Some(search) = this.active_project_search.as_ref() {
2328 search.update(cx, |this, cx| {
2329 this.replace_all(action, window, cx);
2330 })
2331 }
2332 }))
2333 .when(search.filters_enabled, |this| {
2334 this.on_action(cx.listener(|this, _: &ToggleIncludeIgnored, window, cx| {
2335 this.toggle_search_option(SearchOptions::INCLUDE_IGNORED, window, cx);
2336 }))
2337 })
2338 .on_action(cx.listener(Self::select_next_match))
2339 .on_action(cx.listener(Self::select_prev_match))
2340 .child(search_line)
2341 .children(query_error_line)
2342 .children(replace_line)
2343 .children(filter_line)
2344 .children(filter_error_line)
2345 }
2346}
2347
2348impl EventEmitter<ToolbarItemEvent> for ProjectSearchBar {}
2349
2350impl ToolbarItemView for ProjectSearchBar {
2351 fn set_active_pane_item(
2352 &mut self,
2353 active_pane_item: Option<&dyn ItemHandle>,
2354 _: &mut Window,
2355 cx: &mut Context<Self>,
2356 ) -> ToolbarItemLocation {
2357 cx.notify();
2358 self.subscription = None;
2359 self.active_project_search = None;
2360 if let Some(search) = active_pane_item.and_then(|i| i.downcast::<ProjectSearchView>()) {
2361 self.subscription = Some(cx.observe(&search, |_, _, cx| cx.notify()));
2362 self.active_project_search = Some(search);
2363 ToolbarItemLocation::PrimaryLeft {}
2364 } else {
2365 ToolbarItemLocation::Hidden
2366 }
2367 }
2368}
2369
2370fn register_workspace_action<A: Action>(
2371 workspace: &mut Workspace,
2372 callback: fn(&mut ProjectSearchBar, &A, &mut Window, &mut Context<ProjectSearchBar>),
2373) {
2374 workspace.register_action(move |workspace, action: &A, window, cx| {
2375 if workspace.has_active_modal(window, cx) && !workspace.hide_modal(window, cx) {
2376 cx.propagate();
2377 return;
2378 }
2379
2380 workspace.active_pane().update(cx, |pane, cx| {
2381 pane.toolbar().update(cx, move |workspace, cx| {
2382 if let Some(search_bar) = workspace.item_of_type::<ProjectSearchBar>() {
2383 search_bar.update(cx, move |search_bar, cx| {
2384 if search_bar.active_project_search.is_some() {
2385 callback(search_bar, action, window, cx);
2386 cx.notify();
2387 } else {
2388 cx.propagate();
2389 }
2390 });
2391 }
2392 });
2393 })
2394 });
2395}
2396
2397fn register_workspace_action_for_present_search<A: Action>(
2398 workspace: &mut Workspace,
2399 callback: fn(&mut Workspace, &A, &mut Window, &mut Context<Workspace>),
2400) {
2401 workspace.register_action(move |workspace, action: &A, window, cx| {
2402 if workspace.has_active_modal(window, cx) && !workspace.hide_modal(window, cx) {
2403 cx.propagate();
2404 return;
2405 }
2406
2407 let should_notify = workspace
2408 .active_pane()
2409 .read(cx)
2410 .toolbar()
2411 .read(cx)
2412 .item_of_type::<ProjectSearchBar>()
2413 .map(|search_bar| search_bar.read(cx).active_project_search.is_some())
2414 .unwrap_or(false);
2415 if should_notify {
2416 callback(workspace, action, window, cx);
2417 cx.notify();
2418 } else {
2419 cx.propagate();
2420 }
2421 });
2422}
2423
2424#[cfg(any(test, feature = "test-support"))]
2425pub fn perform_project_search(
2426 search_view: &Entity<ProjectSearchView>,
2427 text: impl Into<std::sync::Arc<str>>,
2428 cx: &mut gpui::VisualTestContext,
2429) {
2430 cx.run_until_parked();
2431 search_view.update_in(cx, |search_view, window, cx| {
2432 search_view.query_editor.update(cx, |query_editor, cx| {
2433 query_editor.set_text(text, window, cx)
2434 });
2435 search_view.search(cx);
2436 });
2437 cx.run_until_parked();
2438}
2439
2440#[cfg(test)]
2441pub mod tests {
2442 use std::{
2443 ops::Deref as _,
2444 path::PathBuf,
2445 sync::{
2446 Arc,
2447 atomic::{self, AtomicUsize},
2448 },
2449 time::Duration,
2450 };
2451
2452 use super::*;
2453 use editor::{DisplayPoint, display_map::DisplayRow};
2454 use gpui::{Action, TestAppContext, VisualTestContext, WindowHandle};
2455 use language::{FakeLspAdapter, rust_lang};
2456 use project::FakeFs;
2457 use serde_json::json;
2458 use settings::{InlayHintSettingsContent, SettingsStore};
2459 use util::{path, paths::PathStyle, rel_path::rel_path};
2460 use util_macros::perf;
2461 use workspace::DeploySearch;
2462
2463 #[perf]
2464 #[gpui::test]
2465 async fn test_project_search(cx: &mut TestAppContext) {
2466 init_test(cx);
2467
2468 let fs = FakeFs::new(cx.background_executor.clone());
2469 fs.insert_tree(
2470 path!("/dir"),
2471 json!({
2472 "one.rs": "const ONE: usize = 1;",
2473 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2474 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2475 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2476 }),
2477 )
2478 .await;
2479 let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
2480 let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
2481 let workspace = window.root(cx).unwrap();
2482 let search = cx.new(|cx| ProjectSearch::new(project.clone(), cx));
2483 let search_view = cx.add_window(|window, cx| {
2484 ProjectSearchView::new(workspace.downgrade(), search.clone(), window, cx, None)
2485 });
2486
2487 perform_search(search_view, "TWO", cx);
2488 search_view.update(cx, |search_view, window, cx| {
2489 assert_eq!(
2490 search_view
2491 .results_editor
2492 .update(cx, |editor, cx| editor.display_text(cx)),
2493 "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;"
2494 );
2495 let match_background_color = cx.theme().colors().search_match_background;
2496 let selection_background_color = cx.theme().colors().editor_document_highlight_bracket_background;
2497 assert_eq!(
2498 search_view
2499 .results_editor
2500 .update(cx, |editor, cx| editor.all_text_background_highlights(window, cx)),
2501 &[
2502 (
2503 DisplayPoint::new(DisplayRow(2), 32)..DisplayPoint::new(DisplayRow(2), 35),
2504 match_background_color
2505 ),
2506 (
2507 DisplayPoint::new(DisplayRow(2), 37)..DisplayPoint::new(DisplayRow(2), 40),
2508 selection_background_color
2509 ),
2510 (
2511 DisplayPoint::new(DisplayRow(2), 37)..DisplayPoint::new(DisplayRow(2), 40),
2512 match_background_color
2513 ),
2514 (
2515 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(5), 9),
2516 selection_background_color
2517 ),
2518 (
2519 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(5), 9),
2520 match_background_color
2521 ),
2522
2523 ]
2524 );
2525 assert_eq!(search_view.active_match_index, Some(0));
2526 assert_eq!(
2527 search_view
2528 .results_editor
2529 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2530 [DisplayPoint::new(DisplayRow(2), 32)..DisplayPoint::new(DisplayRow(2), 35)]
2531 );
2532
2533 search_view.select_match(Direction::Next, window, cx);
2534 }).unwrap();
2535
2536 search_view
2537 .update(cx, |search_view, window, cx| {
2538 assert_eq!(search_view.active_match_index, Some(1));
2539 assert_eq!(
2540 search_view
2541 .results_editor
2542 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2543 [DisplayPoint::new(DisplayRow(2), 37)..DisplayPoint::new(DisplayRow(2), 40)]
2544 );
2545 search_view.select_match(Direction::Next, window, cx);
2546 })
2547 .unwrap();
2548
2549 search_view
2550 .update(cx, |search_view, window, cx| {
2551 assert_eq!(search_view.active_match_index, Some(2));
2552 assert_eq!(
2553 search_view
2554 .results_editor
2555 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2556 [DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(5), 9)]
2557 );
2558 search_view.select_match(Direction::Next, window, cx);
2559 })
2560 .unwrap();
2561
2562 search_view
2563 .update(cx, |search_view, window, cx| {
2564 assert_eq!(search_view.active_match_index, Some(0));
2565 assert_eq!(
2566 search_view
2567 .results_editor
2568 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2569 [DisplayPoint::new(DisplayRow(2), 32)..DisplayPoint::new(DisplayRow(2), 35)]
2570 );
2571 search_view.select_match(Direction::Prev, window, cx);
2572 })
2573 .unwrap();
2574
2575 search_view
2576 .update(cx, |search_view, window, cx| {
2577 assert_eq!(search_view.active_match_index, Some(2));
2578 assert_eq!(
2579 search_view
2580 .results_editor
2581 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2582 [DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(5), 9)]
2583 );
2584 search_view.select_match(Direction::Prev, window, cx);
2585 })
2586 .unwrap();
2587
2588 search_view
2589 .update(cx, |search_view, _, cx| {
2590 assert_eq!(search_view.active_match_index, Some(1));
2591 assert_eq!(
2592 search_view
2593 .results_editor
2594 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2595 [DisplayPoint::new(DisplayRow(2), 37)..DisplayPoint::new(DisplayRow(2), 40)]
2596 );
2597 })
2598 .unwrap();
2599 }
2600
2601 #[perf]
2602 #[gpui::test]
2603 async fn test_deploy_project_search_focus(cx: &mut TestAppContext) {
2604 init_test(cx);
2605
2606 let fs = FakeFs::new(cx.background_executor.clone());
2607 fs.insert_tree(
2608 "/dir",
2609 json!({
2610 "one.rs": "const ONE: usize = 1;",
2611 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2612 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2613 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2614 }),
2615 )
2616 .await;
2617 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
2618 let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
2619 let workspace = window;
2620 let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
2621
2622 let active_item = cx.read(|cx| {
2623 workspace
2624 .read(cx)
2625 .unwrap()
2626 .active_pane()
2627 .read(cx)
2628 .active_item()
2629 .and_then(|item| item.downcast::<ProjectSearchView>())
2630 });
2631 assert!(
2632 active_item.is_none(),
2633 "Expected no search panel to be active"
2634 );
2635
2636 window
2637 .update(cx, move |workspace, window, cx| {
2638 assert_eq!(workspace.panes().len(), 1);
2639 workspace.panes()[0].update(cx, |pane, cx| {
2640 pane.toolbar()
2641 .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
2642 });
2643
2644 ProjectSearchView::deploy_search(
2645 workspace,
2646 &workspace::DeploySearch::find(),
2647 window,
2648 cx,
2649 )
2650 })
2651 .unwrap();
2652
2653 let Some(search_view) = cx.read(|cx| {
2654 workspace
2655 .read(cx)
2656 .unwrap()
2657 .active_pane()
2658 .read(cx)
2659 .active_item()
2660 .and_then(|item| item.downcast::<ProjectSearchView>())
2661 }) else {
2662 panic!("Search view expected to appear after new search event trigger")
2663 };
2664
2665 cx.spawn(|mut cx| async move {
2666 window
2667 .update(&mut cx, |_, window, cx| {
2668 window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2669 })
2670 .unwrap();
2671 })
2672 .detach();
2673 cx.background_executor.run_until_parked();
2674 window
2675 .update(cx, |_, window, cx| {
2676 search_view.update(cx, |search_view, cx| {
2677 assert!(
2678 search_view.query_editor.focus_handle(cx).is_focused(window),
2679 "Empty search view should be focused after the toggle focus event: no results panel to focus on",
2680 );
2681 });
2682 }).unwrap();
2683
2684 window
2685 .update(cx, |_, window, cx| {
2686 search_view.update(cx, |search_view, cx| {
2687 let query_editor = &search_view.query_editor;
2688 assert!(
2689 query_editor.focus_handle(cx).is_focused(window),
2690 "Search view should be focused after the new search view is activated",
2691 );
2692 let query_text = query_editor.read(cx).text(cx);
2693 assert!(
2694 query_text.is_empty(),
2695 "New search query should be empty but got '{query_text}'",
2696 );
2697 let results_text = search_view
2698 .results_editor
2699 .update(cx, |editor, cx| editor.display_text(cx));
2700 assert!(
2701 results_text.is_empty(),
2702 "Empty search view should have no results but got '{results_text}'"
2703 );
2704 });
2705 })
2706 .unwrap();
2707
2708 window
2709 .update(cx, |_, window, cx| {
2710 search_view.update(cx, |search_view, cx| {
2711 search_view.query_editor.update(cx, |query_editor, cx| {
2712 query_editor.set_text("sOMETHINGtHATsURELYdOESnOTeXIST", window, cx)
2713 });
2714 search_view.search(cx);
2715 });
2716 })
2717 .unwrap();
2718 cx.background_executor.run_until_parked();
2719 window
2720 .update(cx, |_, window, cx| {
2721 search_view.update(cx, |search_view, cx| {
2722 let results_text = search_view
2723 .results_editor
2724 .update(cx, |editor, cx| editor.display_text(cx));
2725 assert!(
2726 results_text.is_empty(),
2727 "Search view for mismatching query should have no results but got '{results_text}'"
2728 );
2729 assert!(
2730 search_view.query_editor.focus_handle(cx).is_focused(window),
2731 "Search view should be focused after mismatching query had been used in search",
2732 );
2733 });
2734 }).unwrap();
2735
2736 cx.spawn(|mut cx| async move {
2737 window.update(&mut cx, |_, window, cx| {
2738 window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2739 })
2740 })
2741 .detach();
2742 cx.background_executor.run_until_parked();
2743 window.update(cx, |_, window, cx| {
2744 search_view.update(cx, |search_view, cx| {
2745 assert!(
2746 search_view.query_editor.focus_handle(cx).is_focused(window),
2747 "Search view with mismatching query should be focused after the toggle focus event: still no results panel to focus on",
2748 );
2749 });
2750 }).unwrap();
2751
2752 window
2753 .update(cx, |_, window, cx| {
2754 search_view.update(cx, |search_view, cx| {
2755 search_view.query_editor.update(cx, |query_editor, cx| {
2756 query_editor.set_text("TWO", window, cx)
2757 });
2758 search_view.search(cx);
2759 });
2760 })
2761 .unwrap();
2762 cx.background_executor.run_until_parked();
2763 window.update(cx, |_, window, cx| {
2764 search_view.update(cx, |search_view, cx| {
2765 assert_eq!(
2766 search_view
2767 .results_editor
2768 .update(cx, |editor, cx| editor.display_text(cx)),
2769 "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
2770 "Search view results should match the query"
2771 );
2772 assert!(
2773 search_view.results_editor.focus_handle(cx).is_focused(window),
2774 "Search view with mismatching query should be focused after search results are available",
2775 );
2776 });
2777 }).unwrap();
2778 cx.spawn(|mut cx| async move {
2779 window
2780 .update(&mut cx, |_, window, cx| {
2781 window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2782 })
2783 .unwrap();
2784 })
2785 .detach();
2786 cx.background_executor.run_until_parked();
2787 window.update(cx, |_, window, cx| {
2788 search_view.update(cx, |search_view, cx| {
2789 assert!(
2790 search_view.results_editor.focus_handle(cx).is_focused(window),
2791 "Search view with matching query should still have its results editor focused after the toggle focus event",
2792 );
2793 });
2794 }).unwrap();
2795
2796 workspace
2797 .update(cx, |workspace, window, cx| {
2798 ProjectSearchView::deploy_search(
2799 workspace,
2800 &workspace::DeploySearch::find(),
2801 window,
2802 cx,
2803 )
2804 })
2805 .unwrap();
2806 window.update(cx, |_, window, cx| {
2807 search_view.update(cx, |search_view, cx| {
2808 assert_eq!(search_view.query_editor.read(cx).text(cx), "two", "Query should be updated to first search result after search view 2nd open in a row");
2809 assert_eq!(
2810 search_view
2811 .results_editor
2812 .update(cx, |editor, cx| editor.display_text(cx)),
2813 "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
2814 "Results should be unchanged after search view 2nd open in a row"
2815 );
2816 assert!(
2817 search_view.query_editor.focus_handle(cx).is_focused(window),
2818 "Focus should be moved into query editor again after search view 2nd open in a row"
2819 );
2820 });
2821 }).unwrap();
2822
2823 cx.spawn(|mut cx| async move {
2824 window
2825 .update(&mut cx, |_, window, cx| {
2826 window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2827 })
2828 .unwrap();
2829 })
2830 .detach();
2831 cx.background_executor.run_until_parked();
2832 window.update(cx, |_, window, cx| {
2833 search_view.update(cx, |search_view, cx| {
2834 assert!(
2835 search_view.results_editor.focus_handle(cx).is_focused(window),
2836 "Search view with matching query should switch focus to the results editor after the toggle focus event",
2837 );
2838 });
2839 }).unwrap();
2840 }
2841
2842 #[perf]
2843 #[gpui::test]
2844 async fn test_filters_consider_toggle_state(cx: &mut TestAppContext) {
2845 init_test(cx);
2846
2847 let fs = FakeFs::new(cx.background_executor.clone());
2848 fs.insert_tree(
2849 "/dir",
2850 json!({
2851 "one.rs": "const ONE: usize = 1;",
2852 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2853 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2854 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2855 }),
2856 )
2857 .await;
2858 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
2859 let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
2860 let workspace = window;
2861 let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
2862
2863 window
2864 .update(cx, move |workspace, window, cx| {
2865 workspace.panes()[0].update(cx, |pane, cx| {
2866 pane.toolbar()
2867 .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
2868 });
2869
2870 ProjectSearchView::deploy_search(
2871 workspace,
2872 &workspace::DeploySearch::find(),
2873 window,
2874 cx,
2875 )
2876 })
2877 .unwrap();
2878
2879 let Some(search_view) = cx.read(|cx| {
2880 workspace
2881 .read(cx)
2882 .unwrap()
2883 .active_pane()
2884 .read(cx)
2885 .active_item()
2886 .and_then(|item| item.downcast::<ProjectSearchView>())
2887 }) else {
2888 panic!("Search view expected to appear after new search event trigger")
2889 };
2890
2891 cx.spawn(|mut cx| async move {
2892 window
2893 .update(&mut cx, |_, window, cx| {
2894 window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2895 })
2896 .unwrap();
2897 })
2898 .detach();
2899 cx.background_executor.run_until_parked();
2900
2901 window
2902 .update(cx, |_, window, cx| {
2903 search_view.update(cx, |search_view, cx| {
2904 search_view.query_editor.update(cx, |query_editor, cx| {
2905 query_editor.set_text("const FOUR", window, cx)
2906 });
2907 search_view.toggle_filters(cx);
2908 search_view
2909 .excluded_files_editor
2910 .update(cx, |exclude_editor, cx| {
2911 exclude_editor.set_text("four.rs", window, cx)
2912 });
2913 search_view.search(cx);
2914 });
2915 })
2916 .unwrap();
2917 cx.background_executor.run_until_parked();
2918 window
2919 .update(cx, |_, _, cx| {
2920 search_view.update(cx, |search_view, cx| {
2921 let results_text = search_view
2922 .results_editor
2923 .update(cx, |editor, cx| editor.display_text(cx));
2924 assert!(
2925 results_text.is_empty(),
2926 "Search view for query with the only match in an excluded file should have no results but got '{results_text}'"
2927 );
2928 });
2929 }).unwrap();
2930
2931 cx.spawn(|mut cx| async move {
2932 window.update(&mut cx, |_, window, cx| {
2933 window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2934 })
2935 })
2936 .detach();
2937 cx.background_executor.run_until_parked();
2938
2939 window
2940 .update(cx, |_, _, cx| {
2941 search_view.update(cx, |search_view, cx| {
2942 search_view.toggle_filters(cx);
2943 search_view.search(cx);
2944 });
2945 })
2946 .unwrap();
2947 cx.background_executor.run_until_parked();
2948 window
2949 .update(cx, |_, _, cx| {
2950 search_view.update(cx, |search_view, cx| {
2951 assert_eq!(
2952 search_view
2953 .results_editor
2954 .update(cx, |editor, cx| editor.display_text(cx)),
2955 "\n\nconst FOUR: usize = one::ONE + three::THREE;",
2956 "Search view results should contain the queried result in the previously excluded file with filters toggled off"
2957 );
2958 });
2959 })
2960 .unwrap();
2961 }
2962
2963 #[perf]
2964 #[gpui::test]
2965 async fn test_new_project_search_focus(cx: &mut TestAppContext) {
2966 init_test(cx);
2967
2968 let fs = FakeFs::new(cx.background_executor.clone());
2969 fs.insert_tree(
2970 path!("/dir"),
2971 json!({
2972 "one.rs": "const ONE: usize = 1;",
2973 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2974 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2975 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2976 }),
2977 )
2978 .await;
2979 let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
2980 let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
2981 let workspace = window;
2982 let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
2983
2984 let active_item = cx.read(|cx| {
2985 workspace
2986 .read(cx)
2987 .unwrap()
2988 .active_pane()
2989 .read(cx)
2990 .active_item()
2991 .and_then(|item| item.downcast::<ProjectSearchView>())
2992 });
2993 assert!(
2994 active_item.is_none(),
2995 "Expected no search panel to be active"
2996 );
2997
2998 window
2999 .update(cx, move |workspace, window, cx| {
3000 assert_eq!(workspace.panes().len(), 1);
3001 workspace.panes()[0].update(cx, |pane, cx| {
3002 pane.toolbar()
3003 .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3004 });
3005
3006 ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3007 })
3008 .unwrap();
3009
3010 let Some(search_view) = cx.read(|cx| {
3011 workspace
3012 .read(cx)
3013 .unwrap()
3014 .active_pane()
3015 .read(cx)
3016 .active_item()
3017 .and_then(|item| item.downcast::<ProjectSearchView>())
3018 }) else {
3019 panic!("Search view expected to appear after new search event trigger")
3020 };
3021
3022 cx.spawn(|mut cx| async move {
3023 window
3024 .update(&mut cx, |_, window, cx| {
3025 window.dispatch_action(ToggleFocus.boxed_clone(), cx)
3026 })
3027 .unwrap();
3028 })
3029 .detach();
3030 cx.background_executor.run_until_parked();
3031
3032 window.update(cx, |_, window, cx| {
3033 search_view.update(cx, |search_view, cx| {
3034 assert!(
3035 search_view.query_editor.focus_handle(cx).is_focused(window),
3036 "Empty search view should be focused after the toggle focus event: no results panel to focus on",
3037 );
3038 });
3039 }).unwrap();
3040
3041 window
3042 .update(cx, |_, window, cx| {
3043 search_view.update(cx, |search_view, cx| {
3044 let query_editor = &search_view.query_editor;
3045 assert!(
3046 query_editor.focus_handle(cx).is_focused(window),
3047 "Search view should be focused after the new search view is activated",
3048 );
3049 let query_text = query_editor.read(cx).text(cx);
3050 assert!(
3051 query_text.is_empty(),
3052 "New search query should be empty but got '{query_text}'",
3053 );
3054 let results_text = search_view
3055 .results_editor
3056 .update(cx, |editor, cx| editor.display_text(cx));
3057 assert!(
3058 results_text.is_empty(),
3059 "Empty search view should have no results but got '{results_text}'"
3060 );
3061 });
3062 })
3063 .unwrap();
3064
3065 window
3066 .update(cx, |_, window, cx| {
3067 search_view.update(cx, |search_view, cx| {
3068 search_view.query_editor.update(cx, |query_editor, cx| {
3069 query_editor.set_text("sOMETHINGtHATsURELYdOESnOTeXIST", window, cx)
3070 });
3071 search_view.search(cx);
3072 });
3073 })
3074 .unwrap();
3075
3076 cx.background_executor.run_until_parked();
3077 window
3078 .update(cx, |_, window, cx| {
3079 search_view.update(cx, |search_view, cx| {
3080 let results_text = search_view
3081 .results_editor
3082 .update(cx, |editor, cx| editor.display_text(cx));
3083 assert!(
3084 results_text.is_empty(),
3085 "Search view for mismatching query should have no results but got '{results_text}'"
3086 );
3087 assert!(
3088 search_view.query_editor.focus_handle(cx).is_focused(window),
3089 "Search view should be focused after mismatching query had been used in search",
3090 );
3091 });
3092 })
3093 .unwrap();
3094 cx.spawn(|mut cx| async move {
3095 window.update(&mut cx, |_, window, cx| {
3096 window.dispatch_action(ToggleFocus.boxed_clone(), cx)
3097 })
3098 })
3099 .detach();
3100 cx.background_executor.run_until_parked();
3101 window.update(cx, |_, window, cx| {
3102 search_view.update(cx, |search_view, cx| {
3103 assert!(
3104 search_view.query_editor.focus_handle(cx).is_focused(window),
3105 "Search view with mismatching query should be focused after the toggle focus event: still no results panel to focus on",
3106 );
3107 });
3108 }).unwrap();
3109
3110 window
3111 .update(cx, |_, window, cx| {
3112 search_view.update(cx, |search_view, cx| {
3113 search_view.query_editor.update(cx, |query_editor, cx| {
3114 query_editor.set_text("TWO", window, cx)
3115 });
3116 search_view.search(cx);
3117 })
3118 })
3119 .unwrap();
3120 cx.background_executor.run_until_parked();
3121 window.update(cx, |_, window, cx|
3122 search_view.update(cx, |search_view, cx| {
3123 assert_eq!(
3124 search_view
3125 .results_editor
3126 .update(cx, |editor, cx| editor.display_text(cx)),
3127 "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
3128 "Search view results should match the query"
3129 );
3130 assert!(
3131 search_view.results_editor.focus_handle(cx).is_focused(window),
3132 "Search view with mismatching query should be focused after search results are available",
3133 );
3134 })).unwrap();
3135 cx.spawn(|mut cx| async move {
3136 window
3137 .update(&mut cx, |_, window, cx| {
3138 window.dispatch_action(ToggleFocus.boxed_clone(), cx)
3139 })
3140 .unwrap();
3141 })
3142 .detach();
3143 cx.background_executor.run_until_parked();
3144 window.update(cx, |_, window, cx| {
3145 search_view.update(cx, |search_view, cx| {
3146 assert!(
3147 search_view.results_editor.focus_handle(cx).is_focused(window),
3148 "Search view with matching query should still have its results editor focused after the toggle focus event",
3149 );
3150 });
3151 }).unwrap();
3152
3153 workspace
3154 .update(cx, |workspace, window, cx| {
3155 ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3156 })
3157 .unwrap();
3158 cx.background_executor.run_until_parked();
3159 let Some(search_view_2) = cx.read(|cx| {
3160 workspace
3161 .read(cx)
3162 .unwrap()
3163 .active_pane()
3164 .read(cx)
3165 .active_item()
3166 .and_then(|item| item.downcast::<ProjectSearchView>())
3167 }) else {
3168 panic!("Search view expected to appear after new search event trigger")
3169 };
3170 assert!(
3171 search_view_2 != search_view,
3172 "New search view should be open after `workspace::NewSearch` event"
3173 );
3174
3175 window.update(cx, |_, window, cx| {
3176 search_view.update(cx, |search_view, cx| {
3177 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO", "First search view should not have an updated query");
3178 assert_eq!(
3179 search_view
3180 .results_editor
3181 .update(cx, |editor, cx| editor.display_text(cx)),
3182 "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
3183 "Results of the first search view should not update too"
3184 );
3185 assert!(
3186 !search_view.query_editor.focus_handle(cx).is_focused(window),
3187 "Focus should be moved away from the first search view"
3188 );
3189 });
3190 }).unwrap();
3191
3192 window.update(cx, |_, window, cx| {
3193 search_view_2.update(cx, |search_view_2, cx| {
3194 assert_eq!(
3195 search_view_2.query_editor.read(cx).text(cx),
3196 "two",
3197 "New search view should get the query from the text cursor was at during the event spawn (first search view's first result)"
3198 );
3199 assert_eq!(
3200 search_view_2
3201 .results_editor
3202 .update(cx, |editor, cx| editor.display_text(cx)),
3203 "",
3204 "No search results should be in the 2nd view yet, as we did not spawn a search for it"
3205 );
3206 assert!(
3207 search_view_2.query_editor.focus_handle(cx).is_focused(window),
3208 "Focus should be moved into query editor of the new window"
3209 );
3210 });
3211 }).unwrap();
3212
3213 window
3214 .update(cx, |_, window, cx| {
3215 search_view_2.update(cx, |search_view_2, cx| {
3216 search_view_2.query_editor.update(cx, |query_editor, cx| {
3217 query_editor.set_text("FOUR", window, cx)
3218 });
3219 search_view_2.search(cx);
3220 });
3221 })
3222 .unwrap();
3223
3224 cx.background_executor.run_until_parked();
3225 window.update(cx, |_, window, cx| {
3226 search_view_2.update(cx, |search_view_2, cx| {
3227 assert_eq!(
3228 search_view_2
3229 .results_editor
3230 .update(cx, |editor, cx| editor.display_text(cx)),
3231 "\n\nconst FOUR: usize = one::ONE + three::THREE;",
3232 "New search view with the updated query should have new search results"
3233 );
3234 assert!(
3235 search_view_2.results_editor.focus_handle(cx).is_focused(window),
3236 "Search view with mismatching query should be focused after search results are available",
3237 );
3238 });
3239 }).unwrap();
3240
3241 cx.spawn(|mut cx| async move {
3242 window
3243 .update(&mut cx, |_, window, cx| {
3244 window.dispatch_action(ToggleFocus.boxed_clone(), cx)
3245 })
3246 .unwrap();
3247 })
3248 .detach();
3249 cx.background_executor.run_until_parked();
3250 window.update(cx, |_, window, cx| {
3251 search_view_2.update(cx, |search_view_2, cx| {
3252 assert!(
3253 search_view_2.results_editor.focus_handle(cx).is_focused(window),
3254 "Search view with matching query should switch focus to the results editor after the toggle focus event",
3255 );
3256 });}).unwrap();
3257 }
3258
3259 #[perf]
3260 #[gpui::test]
3261 async fn test_new_project_search_in_directory(cx: &mut TestAppContext) {
3262 init_test(cx);
3263
3264 let fs = FakeFs::new(cx.background_executor.clone());
3265 fs.insert_tree(
3266 path!("/dir"),
3267 json!({
3268 "a": {
3269 "one.rs": "const ONE: usize = 1;",
3270 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
3271 },
3272 "b": {
3273 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
3274 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
3275 },
3276 }),
3277 )
3278 .await;
3279 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
3280 let worktree_id = project.read_with(cx, |project, cx| {
3281 project.worktrees(cx).next().unwrap().read(cx).id()
3282 });
3283 let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
3284 let workspace = window.root(cx).unwrap();
3285 let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
3286
3287 let active_item = cx.read(|cx| {
3288 workspace
3289 .read(cx)
3290 .active_pane()
3291 .read(cx)
3292 .active_item()
3293 .and_then(|item| item.downcast::<ProjectSearchView>())
3294 });
3295 assert!(
3296 active_item.is_none(),
3297 "Expected no search panel to be active"
3298 );
3299
3300 window
3301 .update(cx, move |workspace, window, cx| {
3302 assert_eq!(workspace.panes().len(), 1);
3303 workspace.panes()[0].update(cx, move |pane, cx| {
3304 pane.toolbar()
3305 .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3306 });
3307 })
3308 .unwrap();
3309
3310 let a_dir_entry = cx.update(|cx| {
3311 workspace
3312 .read(cx)
3313 .project()
3314 .read(cx)
3315 .entry_for_path(&(worktree_id, rel_path("a")).into(), cx)
3316 .expect("no entry for /a/ directory")
3317 .clone()
3318 });
3319 assert!(a_dir_entry.is_dir());
3320 window
3321 .update(cx, |workspace, window, cx| {
3322 ProjectSearchView::new_search_in_directory(workspace, &a_dir_entry.path, window, cx)
3323 })
3324 .unwrap();
3325
3326 let Some(search_view) = cx.read(|cx| {
3327 workspace
3328 .read(cx)
3329 .active_pane()
3330 .read(cx)
3331 .active_item()
3332 .and_then(|item| item.downcast::<ProjectSearchView>())
3333 }) else {
3334 panic!("Search view expected to appear after new search in directory event trigger")
3335 };
3336 cx.background_executor.run_until_parked();
3337 window
3338 .update(cx, |_, window, cx| {
3339 search_view.update(cx, |search_view, cx| {
3340 assert!(
3341 search_view.query_editor.focus_handle(cx).is_focused(window),
3342 "On new search in directory, focus should be moved into query editor"
3343 );
3344 search_view.excluded_files_editor.update(cx, |editor, cx| {
3345 assert!(
3346 editor.display_text(cx).is_empty(),
3347 "New search in directory should not have any excluded files"
3348 );
3349 });
3350 search_view.included_files_editor.update(cx, |editor, cx| {
3351 assert_eq!(
3352 editor.display_text(cx),
3353 a_dir_entry.path.display(PathStyle::local()),
3354 "New search in directory should have included dir entry path"
3355 );
3356 });
3357 });
3358 })
3359 .unwrap();
3360 window
3361 .update(cx, |_, window, cx| {
3362 search_view.update(cx, |search_view, cx| {
3363 search_view.query_editor.update(cx, |query_editor, cx| {
3364 query_editor.set_text("const", window, cx)
3365 });
3366 search_view.search(cx);
3367 });
3368 })
3369 .unwrap();
3370 cx.background_executor.run_until_parked();
3371 window
3372 .update(cx, |_, _, cx| {
3373 search_view.update(cx, |search_view, cx| {
3374 assert_eq!(
3375 search_view
3376 .results_editor
3377 .update(cx, |editor, cx| editor.display_text(cx)),
3378 "\n\nconst ONE: usize = 1;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
3379 "New search in directory should have a filter that matches a certain directory"
3380 );
3381 })
3382 })
3383 .unwrap();
3384 }
3385
3386 #[perf]
3387 #[gpui::test]
3388 async fn test_search_query_history(cx: &mut TestAppContext) {
3389 init_test(cx);
3390
3391 let fs = FakeFs::new(cx.background_executor.clone());
3392 fs.insert_tree(
3393 path!("/dir"),
3394 json!({
3395 "one.rs": "const ONE: usize = 1;",
3396 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
3397 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
3398 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
3399 }),
3400 )
3401 .await;
3402 let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
3403 let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
3404 let workspace = window.root(cx).unwrap();
3405 let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
3406
3407 window
3408 .update(cx, {
3409 let search_bar = search_bar.clone();
3410 |workspace, window, cx| {
3411 assert_eq!(workspace.panes().len(), 1);
3412 workspace.panes()[0].update(cx, |pane, cx| {
3413 pane.toolbar()
3414 .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3415 });
3416
3417 ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3418 }
3419 })
3420 .unwrap();
3421
3422 let search_view = cx.read(|cx| {
3423 workspace
3424 .read(cx)
3425 .active_pane()
3426 .read(cx)
3427 .active_item()
3428 .and_then(|item| item.downcast::<ProjectSearchView>())
3429 .expect("Search view expected to appear after new search event trigger")
3430 });
3431
3432 // Add 3 search items into the history + another unsubmitted one.
3433 window
3434 .update(cx, |_, window, cx| {
3435 search_view.update(cx, |search_view, cx| {
3436 search_view.search_options = SearchOptions::CASE_SENSITIVE;
3437 search_view.query_editor.update(cx, |query_editor, cx| {
3438 query_editor.set_text("ONE", window, cx)
3439 });
3440 search_view.search(cx);
3441 });
3442 })
3443 .unwrap();
3444
3445 cx.background_executor.run_until_parked();
3446 window
3447 .update(cx, |_, window, cx| {
3448 search_view.update(cx, |search_view, cx| {
3449 search_view.query_editor.update(cx, |query_editor, cx| {
3450 query_editor.set_text("TWO", window, cx)
3451 });
3452 search_view.search(cx);
3453 });
3454 })
3455 .unwrap();
3456 cx.background_executor.run_until_parked();
3457 window
3458 .update(cx, |_, window, cx| {
3459 search_view.update(cx, |search_view, cx| {
3460 search_view.query_editor.update(cx, |query_editor, cx| {
3461 query_editor.set_text("THREE", window, cx)
3462 });
3463 search_view.search(cx);
3464 })
3465 })
3466 .unwrap();
3467 cx.background_executor.run_until_parked();
3468 window
3469 .update(cx, |_, window, cx| {
3470 search_view.update(cx, |search_view, cx| {
3471 search_view.query_editor.update(cx, |query_editor, cx| {
3472 query_editor.set_text("JUST_TEXT_INPUT", window, cx)
3473 });
3474 })
3475 })
3476 .unwrap();
3477 cx.background_executor.run_until_parked();
3478
3479 // Ensure that the latest input with search settings is active.
3480 window
3481 .update(cx, |_, _, cx| {
3482 search_view.update(cx, |search_view, cx| {
3483 assert_eq!(
3484 search_view.query_editor.read(cx).text(cx),
3485 "JUST_TEXT_INPUT"
3486 );
3487 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3488 });
3489 })
3490 .unwrap();
3491
3492 // Next history query after the latest should set the query to the empty string.
3493 window
3494 .update(cx, |_, window, cx| {
3495 search_bar.update(cx, |search_bar, cx| {
3496 search_bar.focus_search(window, cx);
3497 search_bar.next_history_query(&NextHistoryQuery, window, cx);
3498 })
3499 })
3500 .unwrap();
3501 window
3502 .update(cx, |_, _, cx| {
3503 search_view.update(cx, |search_view, cx| {
3504 assert_eq!(search_view.query_editor.read(cx).text(cx), "");
3505 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3506 });
3507 })
3508 .unwrap();
3509 window
3510 .update(cx, |_, window, cx| {
3511 search_bar.update(cx, |search_bar, cx| {
3512 search_bar.focus_search(window, cx);
3513 search_bar.next_history_query(&NextHistoryQuery, window, cx);
3514 })
3515 })
3516 .unwrap();
3517 window
3518 .update(cx, |_, _, cx| {
3519 search_view.update(cx, |search_view, cx| {
3520 assert_eq!(search_view.query_editor.read(cx).text(cx), "");
3521 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3522 });
3523 })
3524 .unwrap();
3525
3526 // First previous query for empty current query should set the query to the latest submitted one.
3527 window
3528 .update(cx, |_, window, cx| {
3529 search_bar.update(cx, |search_bar, cx| {
3530 search_bar.focus_search(window, cx);
3531 search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3532 });
3533 })
3534 .unwrap();
3535 window
3536 .update(cx, |_, _, cx| {
3537 search_view.update(cx, |search_view, cx| {
3538 assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
3539 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3540 });
3541 })
3542 .unwrap();
3543
3544 // Further previous items should go over the history in reverse order.
3545 window
3546 .update(cx, |_, window, cx| {
3547 search_bar.update(cx, |search_bar, cx| {
3548 search_bar.focus_search(window, cx);
3549 search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3550 });
3551 })
3552 .unwrap();
3553 window
3554 .update(cx, |_, _, cx| {
3555 search_view.update(cx, |search_view, cx| {
3556 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
3557 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3558 });
3559 })
3560 .unwrap();
3561
3562 // Previous items should never go behind the first history item.
3563 window
3564 .update(cx, |_, window, cx| {
3565 search_bar.update(cx, |search_bar, cx| {
3566 search_bar.focus_search(window, cx);
3567 search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3568 });
3569 })
3570 .unwrap();
3571 window
3572 .update(cx, |_, _, cx| {
3573 search_view.update(cx, |search_view, cx| {
3574 assert_eq!(search_view.query_editor.read(cx).text(cx), "ONE");
3575 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3576 });
3577 })
3578 .unwrap();
3579 window
3580 .update(cx, |_, window, cx| {
3581 search_bar.update(cx, |search_bar, cx| {
3582 search_bar.focus_search(window, cx);
3583 search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3584 });
3585 })
3586 .unwrap();
3587 window
3588 .update(cx, |_, _, cx| {
3589 search_view.update(cx, |search_view, cx| {
3590 assert_eq!(search_view.query_editor.read(cx).text(cx), "ONE");
3591 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3592 });
3593 })
3594 .unwrap();
3595
3596 // Next items should go over the history in the original order.
3597 window
3598 .update(cx, |_, window, cx| {
3599 search_bar.update(cx, |search_bar, cx| {
3600 search_bar.focus_search(window, cx);
3601 search_bar.next_history_query(&NextHistoryQuery, window, cx);
3602 });
3603 })
3604 .unwrap();
3605 window
3606 .update(cx, |_, _, cx| {
3607 search_view.update(cx, |search_view, cx| {
3608 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
3609 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3610 });
3611 })
3612 .unwrap();
3613
3614 window
3615 .update(cx, |_, window, cx| {
3616 search_view.update(cx, |search_view, cx| {
3617 search_view.query_editor.update(cx, |query_editor, cx| {
3618 query_editor.set_text("TWO_NEW", window, cx)
3619 });
3620 search_view.search(cx);
3621 });
3622 })
3623 .unwrap();
3624 cx.background_executor.run_until_parked();
3625 window
3626 .update(cx, |_, _, cx| {
3627 search_view.update(cx, |search_view, cx| {
3628 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO_NEW");
3629 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3630 });
3631 })
3632 .unwrap();
3633
3634 // New search input should add another entry to history and move the selection to the end of the history.
3635 window
3636 .update(cx, |_, window, cx| {
3637 search_bar.update(cx, |search_bar, cx| {
3638 search_bar.focus_search(window, cx);
3639 search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3640 });
3641 })
3642 .unwrap();
3643 window
3644 .update(cx, |_, _, cx| {
3645 search_view.update(cx, |search_view, cx| {
3646 assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
3647 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3648 });
3649 })
3650 .unwrap();
3651 window
3652 .update(cx, |_, window, cx| {
3653 search_bar.update(cx, |search_bar, cx| {
3654 search_bar.focus_search(window, cx);
3655 search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3656 });
3657 })
3658 .unwrap();
3659 window
3660 .update(cx, |_, _, cx| {
3661 search_view.update(cx, |search_view, cx| {
3662 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
3663 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3664 });
3665 })
3666 .unwrap();
3667 window
3668 .update(cx, |_, window, cx| {
3669 search_bar.update(cx, |search_bar, cx| {
3670 search_bar.focus_search(window, cx);
3671 search_bar.next_history_query(&NextHistoryQuery, window, cx);
3672 });
3673 })
3674 .unwrap();
3675 window
3676 .update(cx, |_, _, cx| {
3677 search_view.update(cx, |search_view, cx| {
3678 assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
3679 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3680 });
3681 })
3682 .unwrap();
3683 window
3684 .update(cx, |_, window, cx| {
3685 search_bar.update(cx, |search_bar, cx| {
3686 search_bar.focus_search(window, cx);
3687 search_bar.next_history_query(&NextHistoryQuery, window, cx);
3688 });
3689 })
3690 .unwrap();
3691 window
3692 .update(cx, |_, _, cx| {
3693 search_view.update(cx, |search_view, cx| {
3694 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO_NEW");
3695 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3696 });
3697 })
3698 .unwrap();
3699 window
3700 .update(cx, |_, window, cx| {
3701 search_bar.update(cx, |search_bar, cx| {
3702 search_bar.focus_search(window, cx);
3703 search_bar.next_history_query(&NextHistoryQuery, window, cx);
3704 });
3705 })
3706 .unwrap();
3707 window
3708 .update(cx, |_, _, cx| {
3709 search_view.update(cx, |search_view, cx| {
3710 assert_eq!(search_view.query_editor.read(cx).text(cx), "");
3711 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3712 });
3713 })
3714 .unwrap();
3715 }
3716
3717 #[perf]
3718 #[gpui::test]
3719 async fn test_search_query_history_with_multiple_views(cx: &mut TestAppContext) {
3720 init_test(cx);
3721
3722 let fs = FakeFs::new(cx.background_executor.clone());
3723 fs.insert_tree(
3724 path!("/dir"),
3725 json!({
3726 "one.rs": "const ONE: usize = 1;",
3727 }),
3728 )
3729 .await;
3730 let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
3731 let worktree_id = project.update(cx, |this, cx| {
3732 this.worktrees(cx).next().unwrap().read(cx).id()
3733 });
3734
3735 let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
3736 let workspace = window.root(cx).unwrap();
3737
3738 let panes: Vec<_> = window
3739 .update(cx, |this, _, _| this.panes().to_owned())
3740 .unwrap();
3741
3742 let search_bar_1 = window.build_entity(cx, |_, _| ProjectSearchBar::new());
3743 let search_bar_2 = window.build_entity(cx, |_, _| ProjectSearchBar::new());
3744
3745 assert_eq!(panes.len(), 1);
3746 let first_pane = panes.first().cloned().unwrap();
3747 assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 0);
3748 window
3749 .update(cx, |workspace, window, cx| {
3750 workspace.open_path(
3751 (worktree_id, rel_path("one.rs")),
3752 Some(first_pane.downgrade()),
3753 true,
3754 window,
3755 cx,
3756 )
3757 })
3758 .unwrap()
3759 .await
3760 .unwrap();
3761 assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 1);
3762
3763 // Add a project search item to the first pane
3764 window
3765 .update(cx, {
3766 let search_bar = search_bar_1.clone();
3767 |workspace, window, cx| {
3768 first_pane.update(cx, |pane, cx| {
3769 pane.toolbar()
3770 .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3771 });
3772
3773 ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3774 }
3775 })
3776 .unwrap();
3777 let search_view_1 = cx.read(|cx| {
3778 workspace
3779 .read(cx)
3780 .active_item(cx)
3781 .and_then(|item| item.downcast::<ProjectSearchView>())
3782 .expect("Search view expected to appear after new search event trigger")
3783 });
3784
3785 let second_pane = window
3786 .update(cx, |workspace, window, cx| {
3787 workspace.split_and_clone(
3788 first_pane.clone(),
3789 workspace::SplitDirection::Right,
3790 window,
3791 cx,
3792 )
3793 })
3794 .unwrap()
3795 .await
3796 .unwrap();
3797 assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 1);
3798
3799 assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 1);
3800 assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 2);
3801
3802 // Add a project search item to the second pane
3803 window
3804 .update(cx, {
3805 let search_bar = search_bar_2.clone();
3806 let pane = second_pane.clone();
3807 move |workspace, window, cx| {
3808 assert_eq!(workspace.panes().len(), 2);
3809 pane.update(cx, |pane, cx| {
3810 pane.toolbar()
3811 .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3812 });
3813
3814 ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3815 }
3816 })
3817 .unwrap();
3818
3819 let search_view_2 = cx.read(|cx| {
3820 workspace
3821 .read(cx)
3822 .active_item(cx)
3823 .and_then(|item| item.downcast::<ProjectSearchView>())
3824 .expect("Search view expected to appear after new search event trigger")
3825 });
3826
3827 cx.run_until_parked();
3828 assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 2);
3829 assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 2);
3830
3831 let update_search_view =
3832 |search_view: &Entity<ProjectSearchView>, query: &str, cx: &mut TestAppContext| {
3833 window
3834 .update(cx, |_, window, cx| {
3835 search_view.update(cx, |search_view, cx| {
3836 search_view.query_editor.update(cx, |query_editor, cx| {
3837 query_editor.set_text(query, window, cx)
3838 });
3839 search_view.search(cx);
3840 });
3841 })
3842 .unwrap();
3843 };
3844
3845 let active_query =
3846 |search_view: &Entity<ProjectSearchView>, cx: &mut TestAppContext| -> String {
3847 window
3848 .update(cx, |_, _, cx| {
3849 search_view.update(cx, |search_view, cx| {
3850 search_view.query_editor.read(cx).text(cx)
3851 })
3852 })
3853 .unwrap()
3854 };
3855
3856 let select_prev_history_item =
3857 |search_bar: &Entity<ProjectSearchBar>, cx: &mut TestAppContext| {
3858 window
3859 .update(cx, |_, window, cx| {
3860 search_bar.update(cx, |search_bar, cx| {
3861 search_bar.focus_search(window, cx);
3862 search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3863 })
3864 })
3865 .unwrap();
3866 };
3867
3868 let select_next_history_item =
3869 |search_bar: &Entity<ProjectSearchBar>, cx: &mut TestAppContext| {
3870 window
3871 .update(cx, |_, window, cx| {
3872 search_bar.update(cx, |search_bar, cx| {
3873 search_bar.focus_search(window, cx);
3874 search_bar.next_history_query(&NextHistoryQuery, window, cx);
3875 })
3876 })
3877 .unwrap();
3878 };
3879
3880 update_search_view(&search_view_1, "ONE", cx);
3881 cx.background_executor.run_until_parked();
3882
3883 update_search_view(&search_view_2, "TWO", cx);
3884 cx.background_executor.run_until_parked();
3885
3886 assert_eq!(active_query(&search_view_1, cx), "ONE");
3887 assert_eq!(active_query(&search_view_2, cx), "TWO");
3888
3889 // Selecting previous history item should select the query from search view 1.
3890 select_prev_history_item(&search_bar_2, cx);
3891 assert_eq!(active_query(&search_view_2, cx), "ONE");
3892
3893 // Selecting the previous history item should not change the query as it is already the first item.
3894 select_prev_history_item(&search_bar_2, cx);
3895 assert_eq!(active_query(&search_view_2, cx), "ONE");
3896
3897 // Changing the query in search view 2 should not affect the history of search view 1.
3898 assert_eq!(active_query(&search_view_1, cx), "ONE");
3899
3900 // Deploying a new search in search view 2
3901 update_search_view(&search_view_2, "THREE", cx);
3902 cx.background_executor.run_until_parked();
3903
3904 select_next_history_item(&search_bar_2, cx);
3905 assert_eq!(active_query(&search_view_2, cx), "");
3906
3907 select_prev_history_item(&search_bar_2, cx);
3908 assert_eq!(active_query(&search_view_2, cx), "THREE");
3909
3910 select_prev_history_item(&search_bar_2, cx);
3911 assert_eq!(active_query(&search_view_2, cx), "TWO");
3912
3913 select_prev_history_item(&search_bar_2, cx);
3914 assert_eq!(active_query(&search_view_2, cx), "ONE");
3915
3916 select_prev_history_item(&search_bar_2, cx);
3917 assert_eq!(active_query(&search_view_2, cx), "ONE");
3918
3919 // Search view 1 should now see the query from search view 2.
3920 assert_eq!(active_query(&search_view_1, cx), "ONE");
3921
3922 select_next_history_item(&search_bar_2, cx);
3923 assert_eq!(active_query(&search_view_2, cx), "TWO");
3924
3925 // Here is the new query from search view 2
3926 select_next_history_item(&search_bar_2, cx);
3927 assert_eq!(active_query(&search_view_2, cx), "THREE");
3928
3929 select_next_history_item(&search_bar_2, cx);
3930 assert_eq!(active_query(&search_view_2, cx), "");
3931
3932 select_next_history_item(&search_bar_1, cx);
3933 assert_eq!(active_query(&search_view_1, cx), "TWO");
3934
3935 select_next_history_item(&search_bar_1, cx);
3936 assert_eq!(active_query(&search_view_1, cx), "THREE");
3937
3938 select_next_history_item(&search_bar_1, cx);
3939 assert_eq!(active_query(&search_view_1, cx), "");
3940 }
3941
3942 #[perf]
3943 #[gpui::test]
3944 async fn test_deploy_search_with_multiple_panes(cx: &mut TestAppContext) {
3945 init_test(cx);
3946
3947 // Setup 2 panes, both with a file open and one with a project search.
3948 let fs = FakeFs::new(cx.background_executor.clone());
3949 fs.insert_tree(
3950 path!("/dir"),
3951 json!({
3952 "one.rs": "const ONE: usize = 1;",
3953 }),
3954 )
3955 .await;
3956 let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
3957 let worktree_id = project.update(cx, |this, cx| {
3958 this.worktrees(cx).next().unwrap().read(cx).id()
3959 });
3960 let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
3961 let panes: Vec<_> = window
3962 .update(cx, |this, _, _| this.panes().to_owned())
3963 .unwrap();
3964 assert_eq!(panes.len(), 1);
3965 let first_pane = panes.first().cloned().unwrap();
3966 assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 0);
3967 window
3968 .update(cx, |workspace, window, cx| {
3969 workspace.open_path(
3970 (worktree_id, rel_path("one.rs")),
3971 Some(first_pane.downgrade()),
3972 true,
3973 window,
3974 cx,
3975 )
3976 })
3977 .unwrap()
3978 .await
3979 .unwrap();
3980 assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 1);
3981 let second_pane = window
3982 .update(cx, |workspace, window, cx| {
3983 workspace.split_and_clone(
3984 first_pane.clone(),
3985 workspace::SplitDirection::Right,
3986 window,
3987 cx,
3988 )
3989 })
3990 .unwrap()
3991 .await
3992 .unwrap();
3993 assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 1);
3994 assert!(
3995 window
3996 .update(cx, |_, window, cx| second_pane
3997 .focus_handle(cx)
3998 .contains_focused(window, cx))
3999 .unwrap()
4000 );
4001 let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
4002 window
4003 .update(cx, {
4004 let search_bar = search_bar.clone();
4005 let pane = first_pane.clone();
4006 move |workspace, window, cx| {
4007 assert_eq!(workspace.panes().len(), 2);
4008 pane.update(cx, move |pane, cx| {
4009 pane.toolbar()
4010 .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
4011 });
4012 }
4013 })
4014 .unwrap();
4015
4016 // Add a project search item to the second pane
4017 window
4018 .update(cx, {
4019 |workspace, window, cx| {
4020 assert_eq!(workspace.panes().len(), 2);
4021 second_pane.update(cx, |pane, cx| {
4022 pane.toolbar()
4023 .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
4024 });
4025
4026 ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
4027 }
4028 })
4029 .unwrap();
4030
4031 cx.run_until_parked();
4032 assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 2);
4033 assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 1);
4034
4035 // Focus the first pane
4036 window
4037 .update(cx, |workspace, window, cx| {
4038 assert_eq!(workspace.active_pane(), &second_pane);
4039 second_pane.update(cx, |this, cx| {
4040 assert_eq!(this.active_item_index(), 1);
4041 this.activate_previous_item(&Default::default(), window, cx);
4042 assert_eq!(this.active_item_index(), 0);
4043 });
4044 workspace.activate_pane_in_direction(workspace::SplitDirection::Left, window, cx);
4045 })
4046 .unwrap();
4047 window
4048 .update(cx, |workspace, _, cx| {
4049 assert_eq!(workspace.active_pane(), &first_pane);
4050 assert_eq!(first_pane.read(cx).items_len(), 1);
4051 assert_eq!(second_pane.read(cx).items_len(), 2);
4052 })
4053 .unwrap();
4054
4055 // Deploy a new search
4056 cx.dispatch_action(window.into(), DeploySearch::find());
4057
4058 // Both panes should now have a project search in them
4059 window
4060 .update(cx, |workspace, window, cx| {
4061 assert_eq!(workspace.active_pane(), &first_pane);
4062 first_pane.read_with(cx, |this, _| {
4063 assert_eq!(this.active_item_index(), 1);
4064 assert_eq!(this.items_len(), 2);
4065 });
4066 second_pane.update(cx, |this, cx| {
4067 assert!(!cx.focus_handle().contains_focused(window, cx));
4068 assert_eq!(this.items_len(), 2);
4069 });
4070 })
4071 .unwrap();
4072
4073 // Focus the second pane's non-search item
4074 window
4075 .update(cx, |_workspace, window, cx| {
4076 second_pane.update(cx, |pane, cx| {
4077 pane.activate_next_item(&Default::default(), window, cx)
4078 });
4079 })
4080 .unwrap();
4081
4082 // Deploy a new search
4083 cx.dispatch_action(window.into(), DeploySearch::find());
4084
4085 // The project search view should now be focused in the second pane
4086 // And the number of items should be unchanged.
4087 window
4088 .update(cx, |_workspace, _, cx| {
4089 second_pane.update(cx, |pane, _cx| {
4090 assert!(
4091 pane.active_item()
4092 .unwrap()
4093 .downcast::<ProjectSearchView>()
4094 .is_some()
4095 );
4096
4097 assert_eq!(pane.items_len(), 2);
4098 });
4099 })
4100 .unwrap();
4101 }
4102
4103 #[perf]
4104 #[gpui::test]
4105 async fn test_scroll_search_results_to_top(cx: &mut TestAppContext) {
4106 init_test(cx);
4107
4108 // We need many lines in the search results to be able to scroll the window
4109 let fs = FakeFs::new(cx.background_executor.clone());
4110 fs.insert_tree(
4111 path!("/dir"),
4112 json!({
4113 "1.txt": "\n\n\n\n\n A \n\n\n\n\n",
4114 "2.txt": "\n\n\n\n\n A \n\n\n\n\n",
4115 "3.rs": "\n\n\n\n\n A \n\n\n\n\n",
4116 "4.rs": "\n\n\n\n\n A \n\n\n\n\n",
4117 "5.rs": "\n\n\n\n\n A \n\n\n\n\n",
4118 "6.rs": "\n\n\n\n\n A \n\n\n\n\n",
4119 "7.rs": "\n\n\n\n\n A \n\n\n\n\n",
4120 "8.rs": "\n\n\n\n\n A \n\n\n\n\n",
4121 "9.rs": "\n\n\n\n\n A \n\n\n\n\n",
4122 "a.rs": "\n\n\n\n\n A \n\n\n\n\n",
4123 "b.rs": "\n\n\n\n\n B \n\n\n\n\n",
4124 "c.rs": "\n\n\n\n\n B \n\n\n\n\n",
4125 "d.rs": "\n\n\n\n\n B \n\n\n\n\n",
4126 "e.rs": "\n\n\n\n\n B \n\n\n\n\n",
4127 "f.rs": "\n\n\n\n\n B \n\n\n\n\n",
4128 "g.rs": "\n\n\n\n\n B \n\n\n\n\n",
4129 "h.rs": "\n\n\n\n\n B \n\n\n\n\n",
4130 "i.rs": "\n\n\n\n\n B \n\n\n\n\n",
4131 "j.rs": "\n\n\n\n\n B \n\n\n\n\n",
4132 "k.rs": "\n\n\n\n\n B \n\n\n\n\n",
4133 }),
4134 )
4135 .await;
4136 let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
4137 let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
4138 let workspace = window.root(cx).unwrap();
4139 let search = cx.new(|cx| ProjectSearch::new(project, cx));
4140 let search_view = cx.add_window(|window, cx| {
4141 ProjectSearchView::new(workspace.downgrade(), search.clone(), window, cx, None)
4142 });
4143
4144 // First search
4145 perform_search(search_view, "A", cx);
4146 search_view
4147 .update(cx, |search_view, window, cx| {
4148 search_view.results_editor.update(cx, |results_editor, cx| {
4149 // Results are correct and scrolled to the top
4150 assert_eq!(
4151 results_editor.display_text(cx).match_indices(" A ").count(),
4152 10
4153 );
4154 assert_eq!(results_editor.scroll_position(cx), Point::default());
4155
4156 // Scroll results all the way down
4157 results_editor.scroll(
4158 Point::new(0., f64::MAX),
4159 Some(Axis::Vertical),
4160 window,
4161 cx,
4162 );
4163 });
4164 })
4165 .expect("unable to update search view");
4166
4167 // Second search
4168 perform_search(search_view, "B", cx);
4169 search_view
4170 .update(cx, |search_view, _, cx| {
4171 search_view.results_editor.update(cx, |results_editor, cx| {
4172 // Results are correct...
4173 assert_eq!(
4174 results_editor.display_text(cx).match_indices(" B ").count(),
4175 10
4176 );
4177 // ...and scrolled back to the top
4178 assert_eq!(results_editor.scroll_position(cx), Point::default());
4179 });
4180 })
4181 .expect("unable to update search view");
4182 }
4183
4184 #[perf]
4185 #[gpui::test]
4186 async fn test_buffer_search_query_reused(cx: &mut TestAppContext) {
4187 init_test(cx);
4188
4189 let fs = FakeFs::new(cx.background_executor.clone());
4190 fs.insert_tree(
4191 path!("/dir"),
4192 json!({
4193 "one.rs": "const ONE: usize = 1;",
4194 }),
4195 )
4196 .await;
4197 let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
4198 let worktree_id = project.update(cx, |this, cx| {
4199 this.worktrees(cx).next().unwrap().read(cx).id()
4200 });
4201 let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
4202 let workspace = window.root(cx).unwrap();
4203 let mut cx = VisualTestContext::from_window(*window.deref(), cx);
4204
4205 let editor = workspace
4206 .update_in(&mut cx, |workspace, window, cx| {
4207 workspace.open_path((worktree_id, rel_path("one.rs")), None, true, window, cx)
4208 })
4209 .await
4210 .unwrap()
4211 .downcast::<Editor>()
4212 .unwrap();
4213
4214 // Wait for the unstaged changes to be loaded
4215 cx.run_until_parked();
4216
4217 let buffer_search_bar = cx.new_window_entity(|window, cx| {
4218 let mut search_bar =
4219 BufferSearchBar::new(Some(project.read(cx).languages().clone()), window, cx);
4220 search_bar.set_active_pane_item(Some(&editor), window, cx);
4221 search_bar.show(window, cx);
4222 search_bar
4223 });
4224
4225 let panes: Vec<_> = window
4226 .update(&mut cx, |this, _, _| this.panes().to_owned())
4227 .unwrap();
4228 assert_eq!(panes.len(), 1);
4229 let pane = panes.first().cloned().unwrap();
4230 pane.update_in(&mut cx, |pane, window, cx| {
4231 pane.toolbar().update(cx, |toolbar, cx| {
4232 toolbar.add_item(buffer_search_bar.clone(), window, cx);
4233 })
4234 });
4235
4236 let buffer_search_query = "search bar query";
4237 buffer_search_bar
4238 .update_in(&mut cx, |buffer_search_bar, window, cx| {
4239 buffer_search_bar.focus_handle(cx).focus(window);
4240 buffer_search_bar.search(buffer_search_query, None, true, window, cx)
4241 })
4242 .await
4243 .unwrap();
4244
4245 workspace.update_in(&mut cx, |workspace, window, cx| {
4246 ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
4247 });
4248 cx.run_until_parked();
4249 let project_search_view = pane
4250 .read_with(&cx, |pane, _| {
4251 pane.active_item()
4252 .and_then(|item| item.downcast::<ProjectSearchView>())
4253 })
4254 .expect("should open a project search view after spawning a new search");
4255 project_search_view.update(&mut cx, |search_view, cx| {
4256 assert_eq!(
4257 search_view.search_query_text(cx),
4258 buffer_search_query,
4259 "Project search should take the query from the buffer search bar since it got focused and had a query inside"
4260 );
4261 });
4262 }
4263
4264 #[gpui::test]
4265 async fn test_search_dismisses_modal(cx: &mut TestAppContext) {
4266 init_test(cx);
4267
4268 let fs = FakeFs::new(cx.background_executor.clone());
4269 fs.insert_tree(
4270 path!("/dir"),
4271 json!({
4272 "one.rs": "const ONE: usize = 1;",
4273 }),
4274 )
4275 .await;
4276 let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
4277 let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
4278
4279 struct EmptyModalView {
4280 focus_handle: gpui::FocusHandle,
4281 }
4282 impl EventEmitter<gpui::DismissEvent> for EmptyModalView {}
4283 impl Render for EmptyModalView {
4284 fn render(&mut self, _: &mut Window, _: &mut Context<'_, Self>) -> impl IntoElement {
4285 div()
4286 }
4287 }
4288 impl Focusable for EmptyModalView {
4289 fn focus_handle(&self, _cx: &App) -> gpui::FocusHandle {
4290 self.focus_handle.clone()
4291 }
4292 }
4293 impl workspace::ModalView for EmptyModalView {}
4294
4295 window
4296 .update(cx, |workspace, window, cx| {
4297 workspace.toggle_modal(window, cx, |_, cx| EmptyModalView {
4298 focus_handle: cx.focus_handle(),
4299 });
4300 assert!(workspace.has_active_modal(window, cx));
4301 })
4302 .unwrap();
4303
4304 cx.dispatch_action(window.into(), Deploy::find());
4305
4306 window
4307 .update(cx, |workspace, window, cx| {
4308 assert!(!workspace.has_active_modal(window, cx));
4309 workspace.toggle_modal(window, cx, |_, cx| EmptyModalView {
4310 focus_handle: cx.focus_handle(),
4311 });
4312 assert!(workspace.has_active_modal(window, cx));
4313 })
4314 .unwrap();
4315
4316 cx.dispatch_action(window.into(), DeploySearch::find());
4317
4318 window
4319 .update(cx, |workspace, window, cx| {
4320 assert!(!workspace.has_active_modal(window, cx));
4321 })
4322 .unwrap();
4323 }
4324
4325 #[perf]
4326 #[gpui::test]
4327 async fn test_search_with_inlays(cx: &mut TestAppContext) {
4328 init_test(cx);
4329 cx.update(|cx| {
4330 SettingsStore::update_global(cx, |store, cx| {
4331 store.update_user_settings(cx, |settings| {
4332 settings.project.all_languages.defaults.inlay_hints =
4333 Some(InlayHintSettingsContent {
4334 enabled: Some(true),
4335 ..InlayHintSettingsContent::default()
4336 })
4337 });
4338 });
4339 });
4340
4341 let fs = FakeFs::new(cx.background_executor.clone());
4342 fs.insert_tree(
4343 path!("/dir"),
4344 // `\n` , a trailing line on the end, is important for the test case
4345 json!({
4346 "main.rs": "fn main() { let a = 2; }\n",
4347 }),
4348 )
4349 .await;
4350
4351 let requests_count = Arc::new(AtomicUsize::new(0));
4352 let closure_requests_count = requests_count.clone();
4353 let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
4354 let language_registry = project.read_with(cx, |project, _| project.languages().clone());
4355 let language = rust_lang();
4356 language_registry.add(language);
4357 let mut fake_servers = language_registry.register_fake_lsp(
4358 "Rust",
4359 FakeLspAdapter {
4360 capabilities: lsp::ServerCapabilities {
4361 inlay_hint_provider: Some(lsp::OneOf::Left(true)),
4362 ..lsp::ServerCapabilities::default()
4363 },
4364 initializer: Some(Box::new(move |fake_server| {
4365 let requests_count = closure_requests_count.clone();
4366 fake_server.set_request_handler::<lsp::request::InlayHintRequest, _, _>({
4367 move |_, _| {
4368 let requests_count = requests_count.clone();
4369 async move {
4370 requests_count.fetch_add(1, atomic::Ordering::Release);
4371 Ok(Some(vec![lsp::InlayHint {
4372 position: lsp::Position::new(0, 17),
4373 label: lsp::InlayHintLabel::String(": i32".to_owned()),
4374 kind: Some(lsp::InlayHintKind::TYPE),
4375 text_edits: None,
4376 tooltip: None,
4377 padding_left: None,
4378 padding_right: None,
4379 data: None,
4380 }]))
4381 }
4382 }
4383 });
4384 })),
4385 ..FakeLspAdapter::default()
4386 },
4387 );
4388
4389 let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
4390 let workspace = window.root(cx).unwrap();
4391 let search = cx.new(|cx| ProjectSearch::new(project.clone(), cx));
4392 let search_view = cx.add_window(|window, cx| {
4393 ProjectSearchView::new(workspace.downgrade(), search.clone(), window, cx, None)
4394 });
4395
4396 perform_search(search_view, "let ", cx);
4397 let fake_server = fake_servers.next().await.unwrap();
4398 cx.executor().advance_clock(Duration::from_secs(1));
4399 cx.executor().run_until_parked();
4400 search_view
4401 .update(cx, |search_view, _, cx| {
4402 assert_eq!(
4403 search_view
4404 .results_editor
4405 .update(cx, |editor, cx| editor.display_text(cx)),
4406 "\n\nfn main() { let a: i32 = 2; }\n"
4407 );
4408 })
4409 .unwrap();
4410 assert_eq!(
4411 requests_count.load(atomic::Ordering::Acquire),
4412 1,
4413 "New hints should have been queried",
4414 );
4415
4416 // Can do the 2nd search without any panics
4417 perform_search(search_view, "let ", cx);
4418 cx.executor().advance_clock(Duration::from_secs(1));
4419 cx.executor().run_until_parked();
4420 search_view
4421 .update(cx, |search_view, _, cx| {
4422 assert_eq!(
4423 search_view
4424 .results_editor
4425 .update(cx, |editor, cx| editor.display_text(cx)),
4426 "\n\nfn main() { let a: i32 = 2; }\n"
4427 );
4428 })
4429 .unwrap();
4430 assert_eq!(
4431 requests_count.load(atomic::Ordering::Acquire),
4432 2,
4433 "We did drop the previous buffer when cleared the old project search results, hence another query was made",
4434 );
4435
4436 let singleton_editor = window
4437 .update(cx, |workspace, window, cx| {
4438 workspace.open_abs_path(
4439 PathBuf::from(path!("/dir/main.rs")),
4440 workspace::OpenOptions::default(),
4441 window,
4442 cx,
4443 )
4444 })
4445 .unwrap()
4446 .await
4447 .unwrap()
4448 .downcast::<Editor>()
4449 .unwrap();
4450 cx.executor().advance_clock(Duration::from_millis(100));
4451 cx.executor().run_until_parked();
4452 singleton_editor.update(cx, |editor, cx| {
4453 assert_eq!(
4454 editor.display_text(cx),
4455 "fn main() { let a: i32 = 2; }\n",
4456 "Newly opened editor should have the correct text with hints",
4457 );
4458 });
4459 assert_eq!(
4460 requests_count.load(atomic::Ordering::Acquire),
4461 2,
4462 "Opening the same buffer again should reuse the cached hints",
4463 );
4464
4465 window
4466 .update(cx, |_, window, cx| {
4467 singleton_editor.update(cx, |editor, cx| {
4468 editor.handle_input("test", window, cx);
4469 });
4470 })
4471 .unwrap();
4472
4473 cx.executor().advance_clock(Duration::from_secs(1));
4474 cx.executor().run_until_parked();
4475 singleton_editor.update(cx, |editor, cx| {
4476 assert_eq!(
4477 editor.display_text(cx),
4478 "testfn main() { l: i32et a = 2; }\n",
4479 "Newly opened editor should have the correct text with hints",
4480 );
4481 });
4482 assert_eq!(
4483 requests_count.load(atomic::Ordering::Acquire),
4484 3,
4485 "We have edited the buffer and should send a new request",
4486 );
4487
4488 window
4489 .update(cx, |_, window, cx| {
4490 singleton_editor.update(cx, |editor, cx| {
4491 editor.undo(&editor::actions::Undo, window, cx);
4492 });
4493 })
4494 .unwrap();
4495 cx.executor().advance_clock(Duration::from_secs(1));
4496 cx.executor().run_until_parked();
4497 assert_eq!(
4498 requests_count.load(atomic::Ordering::Acquire),
4499 4,
4500 "We have edited the buffer again and should send a new request again",
4501 );
4502 singleton_editor.update(cx, |editor, cx| {
4503 assert_eq!(
4504 editor.display_text(cx),
4505 "fn main() { let a: i32 = 2; }\n",
4506 "Newly opened editor should have the correct text with hints",
4507 );
4508 });
4509 project.update(cx, |_, cx| {
4510 cx.emit(project::Event::RefreshInlayHints {
4511 server_id: fake_server.server.server_id(),
4512 request_id: Some(1),
4513 });
4514 });
4515 cx.executor().advance_clock(Duration::from_secs(1));
4516 cx.executor().run_until_parked();
4517 assert_eq!(
4518 requests_count.load(atomic::Ordering::Acquire),
4519 5,
4520 "After a simulated server refresh request, we should have sent another request",
4521 );
4522
4523 perform_search(search_view, "let ", cx);
4524 cx.executor().advance_clock(Duration::from_secs(1));
4525 cx.executor().run_until_parked();
4526 assert_eq!(
4527 requests_count.load(atomic::Ordering::Acquire),
4528 5,
4529 "New project search should reuse the cached hints",
4530 );
4531 search_view
4532 .update(cx, |search_view, _, cx| {
4533 assert_eq!(
4534 search_view
4535 .results_editor
4536 .update(cx, |editor, cx| editor.display_text(cx)),
4537 "\n\nfn main() { let a: i32 = 2; }\n"
4538 );
4539 })
4540 .unwrap();
4541 }
4542
4543 fn init_test(cx: &mut TestAppContext) {
4544 cx.update(|cx| {
4545 let settings = SettingsStore::test(cx);
4546 cx.set_global(settings);
4547
4548 theme::init(theme::LoadThemes::JustBase, cx);
4549
4550 language::init(cx);
4551 client::init_settings(cx);
4552 editor::init(cx);
4553 workspace::init_settings(cx);
4554 Project::init_settings(cx);
4555 crate::init(cx);
4556 });
4557 }
4558
4559 fn perform_search(
4560 search_view: WindowHandle<ProjectSearchView>,
4561 text: impl Into<Arc<str>>,
4562 cx: &mut TestAppContext,
4563 ) {
4564 search_view
4565 .update(cx, |search_view, window, cx| {
4566 search_view.query_editor.update(cx, |query_editor, cx| {
4567 query_editor.set_text(text, window, cx)
4568 });
4569 search_view.search(cx);
4570 })
4571 .unwrap();
4572 // Ensure editor highlights appear after the search is done
4573 cx.executor().advance_clock(
4574 editor::SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT + Duration::from_millis(100),
4575 );
4576 cx.background_executor.run_until_parked();
4577 }
4578}