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