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 open_buffers = if search_view.included_opened_only {
962 Some(search_view.open_buffers(cx, workspace))
963 } else {
964 None
965 };
966 let new_query = search_view.build_search_query(cx, open_buffers);
967 if new_query.is_some()
968 && let Some(old_query) = search_view.entity.read(cx).active_query.clone()
969 {
970 search_view.query_editor.update(cx, |editor, cx| {
971 editor.set_text(old_query.as_str(), window, cx);
972 });
973 search_view.search_options = SearchOptions::from_query(&old_query);
974 search_view.adjust_query_regex_language(cx);
975 }
976 new_query
977 });
978 if let Some(new_query) = new_query {
979 let entity = cx.new(|cx| {
980 let mut entity = ProjectSearch::new(workspace.project().clone(), cx);
981 entity.search(new_query, cx);
982 entity
983 });
984 let weak_workspace = cx.entity().downgrade();
985 workspace.add_item_to_active_pane(
986 Box::new(cx.new(|cx| {
987 ProjectSearchView::new(weak_workspace, entity, window, cx, None)
988 })),
989 None,
990 true,
991 window,
992 cx,
993 );
994 }
995 }
996 }
997
998 // Add another search tab to the workspace.
999 fn new_search(
1000 workspace: &mut Workspace,
1001 _: &workspace::NewSearch,
1002 window: &mut Window,
1003 cx: &mut Context<Workspace>,
1004 ) {
1005 Self::existing_or_new_search(workspace, None, &DeploySearch::find(), window, cx)
1006 }
1007
1008 fn existing_or_new_search(
1009 workspace: &mut Workspace,
1010 existing: Option<Entity<ProjectSearchView>>,
1011 action: &workspace::DeploySearch,
1012 window: &mut Window,
1013 cx: &mut Context<Workspace>,
1014 ) {
1015 let query = workspace.active_item(cx).and_then(|item| {
1016 if let Some(buffer_search_query) = buffer_search_query(workspace, item.as_ref(), cx) {
1017 return Some(buffer_search_query);
1018 }
1019
1020 let editor = item.act_as::<Editor>(cx)?;
1021 let query = editor.query_suggestion(window, cx);
1022 if query.is_empty() { None } else { Some(query) }
1023 });
1024
1025 let search = if let Some(existing) = existing {
1026 workspace.activate_item(&existing, true, true, window, cx);
1027 existing
1028 } else {
1029 let settings = cx
1030 .global::<ActiveSettings>()
1031 .0
1032 .get(&workspace.project().downgrade());
1033
1034 let settings = settings.cloned();
1035
1036 let weak_workspace = cx.entity().downgrade();
1037
1038 let project_search = cx.new(|cx| ProjectSearch::new(workspace.project().clone(), cx));
1039 let project_search_view = cx.new(|cx| {
1040 ProjectSearchView::new(weak_workspace, project_search, window, cx, settings)
1041 });
1042
1043 workspace.add_item_to_active_pane(
1044 Box::new(project_search_view.clone()),
1045 None,
1046 true,
1047 window,
1048 cx,
1049 );
1050 project_search_view
1051 };
1052
1053 search.update(cx, |search, cx| {
1054 search.replace_enabled = action.replace_enabled;
1055 if let Some(query) = query {
1056 search.set_query(&query, window, cx);
1057 }
1058 if let Some(included_files) = action.included_files.as_deref() {
1059 search
1060 .included_files_editor
1061 .update(cx, |editor, cx| editor.set_text(included_files, window, cx));
1062 search.filters_enabled = true;
1063 }
1064 if let Some(excluded_files) = action.excluded_files.as_deref() {
1065 search
1066 .excluded_files_editor
1067 .update(cx, |editor, cx| editor.set_text(excluded_files, window, cx));
1068 search.filters_enabled = true;
1069 }
1070 search.focus_query_editor(window, cx)
1071 });
1072 }
1073
1074 fn prompt_to_save_if_dirty_then_search(
1075 &mut self,
1076 window: &mut Window,
1077 cx: &mut Context<Self>,
1078 ) -> Task<anyhow::Result<()>> {
1079 let project = self.entity.read(cx).project.clone();
1080
1081 let can_autosave = self.results_editor.can_autosave(cx);
1082 let autosave_setting = self.results_editor.workspace_settings(cx).autosave;
1083
1084 let will_autosave = can_autosave && autosave_setting.should_save_on_close();
1085
1086 let is_dirty = self.is_dirty(cx);
1087
1088 cx.spawn_in(window, async move |this, cx| {
1089 let skip_save_on_close = this
1090 .read_with(cx, |this, cx| {
1091 this.workspace.read_with(cx, |workspace, cx| {
1092 workspace::Pane::skip_save_on_close(&this.results_editor, workspace, cx)
1093 })
1094 })?
1095 .unwrap_or(false);
1096
1097 let should_prompt_to_save = !skip_save_on_close && !will_autosave && is_dirty;
1098
1099 let should_search = if should_prompt_to_save {
1100 let options = &["Save", "Don't Save", "Cancel"];
1101 let result_channel = this.update_in(cx, |_, window, cx| {
1102 window.prompt(
1103 gpui::PromptLevel::Warning,
1104 "Project search buffer contains unsaved edits. Do you want to save it?",
1105 None,
1106 options,
1107 cx,
1108 )
1109 })?;
1110 let result = result_channel.await?;
1111 let should_save = result == 0;
1112 if should_save {
1113 this.update_in(cx, |this, window, cx| {
1114 this.save(
1115 SaveOptions {
1116 format: true,
1117 autosave: false,
1118 },
1119 project,
1120 window,
1121 cx,
1122 )
1123 })?
1124 .await
1125 .log_err();
1126 }
1127
1128 result != 2
1129 } else {
1130 true
1131 };
1132 if should_search {
1133 this.update(cx, |this, cx| {
1134 this.search(cx);
1135 })?;
1136 }
1137 anyhow::Ok(())
1138 })
1139 }
1140
1141 fn search(&mut self, cx: &mut Context<Self>) {
1142 let open_buffers = if self.included_opened_only {
1143 self.workspace
1144 .update(cx, |workspace, cx| self.open_buffers(cx, workspace))
1145 .ok()
1146 } else {
1147 None
1148 };
1149 if let Some(query) = self.build_search_query(cx, open_buffers) {
1150 self.entity.update(cx, |model, cx| model.search(query, cx));
1151 }
1152 }
1153
1154 pub fn search_query_text(&self, cx: &App) -> String {
1155 self.query_editor.read(cx).text(cx)
1156 }
1157
1158 fn build_search_query(
1159 &mut self,
1160 cx: &mut Context<Self>,
1161 open_buffers: Option<Vec<Entity<Buffer>>>,
1162 ) -> Option<SearchQuery> {
1163 // Do not bail early in this function, as we want to fill out `self.panels_with_errors`.
1164 let text = self.search_query_text(cx);
1165 let included_files = self
1166 .filters_enabled
1167 .then(|| {
1168 match Self::parse_path_matches(&self.included_files_editor.read(cx).text(cx)) {
1169 Ok(included_files) => {
1170 let should_unmark_error =
1171 self.panels_with_errors.remove(&InputPanel::Include);
1172 if should_unmark_error.is_some() {
1173 cx.notify();
1174 }
1175 included_files
1176 }
1177 Err(e) => {
1178 let should_mark_error = self
1179 .panels_with_errors
1180 .insert(InputPanel::Include, e.to_string());
1181 if should_mark_error.is_none() {
1182 cx.notify();
1183 }
1184 PathMatcher::default()
1185 }
1186 }
1187 })
1188 .unwrap_or_default();
1189 let excluded_files = self
1190 .filters_enabled
1191 .then(|| {
1192 match Self::parse_path_matches(&self.excluded_files_editor.read(cx).text(cx)) {
1193 Ok(excluded_files) => {
1194 let should_unmark_error =
1195 self.panels_with_errors.remove(&InputPanel::Exclude);
1196 if should_unmark_error.is_some() {
1197 cx.notify();
1198 }
1199
1200 excluded_files
1201 }
1202 Err(e) => {
1203 let should_mark_error = self
1204 .panels_with_errors
1205 .insert(InputPanel::Exclude, e.to_string());
1206 if should_mark_error.is_none() {
1207 cx.notify();
1208 }
1209 PathMatcher::default()
1210 }
1211 }
1212 })
1213 .unwrap_or_default();
1214
1215 // If the project contains multiple visible worktrees, we match the
1216 // include/exclude patterns against full paths to allow them to be
1217 // disambiguated. For single worktree projects we use worktree relative
1218 // paths for convenience.
1219 let match_full_paths = self
1220 .entity
1221 .read(cx)
1222 .project
1223 .read(cx)
1224 .visible_worktrees(cx)
1225 .count()
1226 > 1;
1227
1228 let query = if self.search_options.contains(SearchOptions::REGEX) {
1229 match SearchQuery::regex(
1230 text,
1231 self.search_options.contains(SearchOptions::WHOLE_WORD),
1232 self.search_options.contains(SearchOptions::CASE_SENSITIVE),
1233 self.search_options.contains(SearchOptions::INCLUDE_IGNORED),
1234 self.search_options
1235 .contains(SearchOptions::ONE_MATCH_PER_LINE),
1236 included_files,
1237 excluded_files,
1238 match_full_paths,
1239 open_buffers,
1240 ) {
1241 Ok(query) => {
1242 let should_unmark_error = self.panels_with_errors.remove(&InputPanel::Query);
1243 if should_unmark_error.is_some() {
1244 cx.notify();
1245 }
1246
1247 Some(query)
1248 }
1249 Err(e) => {
1250 let should_mark_error = self
1251 .panels_with_errors
1252 .insert(InputPanel::Query, e.to_string());
1253 if should_mark_error.is_none() {
1254 cx.notify();
1255 }
1256
1257 None
1258 }
1259 }
1260 } else {
1261 match SearchQuery::text(
1262 text,
1263 self.search_options.contains(SearchOptions::WHOLE_WORD),
1264 self.search_options.contains(SearchOptions::CASE_SENSITIVE),
1265 self.search_options.contains(SearchOptions::INCLUDE_IGNORED),
1266 included_files,
1267 excluded_files,
1268 match_full_paths,
1269 open_buffers,
1270 ) {
1271 Ok(query) => {
1272 let should_unmark_error = self.panels_with_errors.remove(&InputPanel::Query);
1273 if should_unmark_error.is_some() {
1274 cx.notify();
1275 }
1276
1277 Some(query)
1278 }
1279 Err(e) => {
1280 let should_mark_error = self
1281 .panels_with_errors
1282 .insert(InputPanel::Query, e.to_string());
1283 if should_mark_error.is_none() {
1284 cx.notify();
1285 }
1286
1287 None
1288 }
1289 }
1290 };
1291 if !self.panels_with_errors.is_empty() {
1292 return None;
1293 }
1294 if query.as_ref().is_some_and(|query| query.is_empty()) {
1295 return None;
1296 }
1297 query
1298 }
1299
1300 fn open_buffers(&self, cx: &App, workspace: &Workspace) -> Vec<Entity<Buffer>> {
1301 let mut buffers = Vec::new();
1302 for editor in workspace.items_of_type::<Editor>(cx) {
1303 if let Some(buffer) = editor.read(cx).buffer().read(cx).as_singleton() {
1304 buffers.push(buffer);
1305 }
1306 }
1307 buffers
1308 }
1309
1310 fn parse_path_matches(text: &str) -> anyhow::Result<PathMatcher> {
1311 let queries = text
1312 .split(',')
1313 .map(str::trim)
1314 .filter(|maybe_glob_str| !maybe_glob_str.is_empty())
1315 .map(str::to_owned)
1316 .collect::<Vec<_>>();
1317 Ok(PathMatcher::new(&queries)?)
1318 }
1319
1320 fn select_match(&mut self, direction: Direction, window: &mut Window, cx: &mut Context<Self>) {
1321 if let Some(index) = self.active_match_index {
1322 let match_ranges = self.entity.read(cx).match_ranges.clone();
1323
1324 if !EditorSettings::get_global(cx).search_wrap
1325 && ((direction == Direction::Next && index + 1 >= match_ranges.len())
1326 || (direction == Direction::Prev && index == 0))
1327 {
1328 crate::show_no_more_matches(window, cx);
1329 return;
1330 }
1331
1332 let new_index = self.results_editor.update(cx, |editor, cx| {
1333 editor.match_index_for_direction(&match_ranges, index, direction, 1, window, cx)
1334 });
1335
1336 let range_to_select = match_ranges[new_index].clone();
1337 self.results_editor.update(cx, |editor, cx| {
1338 let range_to_select = editor.range_for_match(&range_to_select);
1339 editor.unfold_ranges(std::slice::from_ref(&range_to_select), false, true, cx);
1340 editor.change_selections(Default::default(), window, cx, |s| {
1341 s.select_ranges([range_to_select])
1342 });
1343 });
1344 }
1345 }
1346
1347 fn focus_query_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1348 self.query_editor.update(cx, |query_editor, cx| {
1349 query_editor.select_all(&SelectAll, window, cx);
1350 });
1351 let editor_handle = self.query_editor.focus_handle(cx);
1352 window.focus(&editor_handle);
1353 }
1354
1355 fn set_query(&mut self, query: &str, window: &mut Window, cx: &mut Context<Self>) {
1356 self.set_search_editor(SearchInputKind::Query, query, window, cx);
1357 if EditorSettings::get_global(cx).use_smartcase_search
1358 && !query.is_empty()
1359 && self.search_options.contains(SearchOptions::CASE_SENSITIVE)
1360 != contains_uppercase(query)
1361 {
1362 self.toggle_search_option(SearchOptions::CASE_SENSITIVE, cx)
1363 }
1364 }
1365
1366 fn set_search_editor(
1367 &mut self,
1368 kind: SearchInputKind,
1369 text: &str,
1370 window: &mut Window,
1371 cx: &mut Context<Self>,
1372 ) {
1373 let editor = match kind {
1374 SearchInputKind::Query => &self.query_editor,
1375 SearchInputKind::Include => &self.included_files_editor,
1376
1377 SearchInputKind::Exclude => &self.excluded_files_editor,
1378 };
1379 editor.update(cx, |included_editor, cx| {
1380 included_editor.set_text(text, window, cx)
1381 });
1382 }
1383
1384 fn focus_results_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1385 self.query_editor.update(cx, |query_editor, cx| {
1386 let cursor = query_editor.selections.newest_anchor().head();
1387 query_editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1388 s.select_ranges([cursor..cursor])
1389 });
1390 });
1391 let results_handle = self.results_editor.focus_handle(cx);
1392 window.focus(&results_handle);
1393 }
1394
1395 fn entity_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1396 let match_ranges = self.entity.read(cx).match_ranges.clone();
1397 if match_ranges.is_empty() {
1398 self.active_match_index = None;
1399 self.results_editor.update(cx, |editor, cx| {
1400 editor.clear_background_highlights::<Self>(cx);
1401 });
1402 } else {
1403 self.active_match_index = Some(0);
1404 self.update_match_index(cx);
1405 let prev_search_id = mem::replace(&mut self.search_id, self.entity.read(cx).search_id);
1406 let is_new_search = self.search_id != prev_search_id;
1407 self.results_editor.update(cx, |editor, cx| {
1408 if is_new_search {
1409 let range_to_select = match_ranges
1410 .first()
1411 .map(|range| editor.range_for_match(range));
1412 editor.change_selections(Default::default(), window, cx, |s| {
1413 s.select_ranges(range_to_select)
1414 });
1415 editor.scroll(Point::default(), Some(Axis::Vertical), window, cx);
1416 }
1417 editor.highlight_background::<Self>(
1418 &match_ranges,
1419 |theme| theme.colors().search_match_background,
1420 cx,
1421 );
1422 });
1423 if is_new_search && self.query_editor.focus_handle(cx).is_focused(window) {
1424 self.focus_results_editor(window, cx);
1425 }
1426 }
1427
1428 cx.emit(ViewEvent::UpdateTab);
1429 cx.notify();
1430 }
1431
1432 fn update_match_index(&mut self, cx: &mut Context<Self>) {
1433 let results_editor = self.results_editor.read(cx);
1434 let new_index = active_match_index(
1435 Direction::Next,
1436 &self.entity.read(cx).match_ranges,
1437 &results_editor.selections.newest_anchor().head(),
1438 &results_editor.buffer().read(cx).snapshot(cx),
1439 );
1440 if self.active_match_index != new_index {
1441 self.active_match_index = new_index;
1442 cx.notify();
1443 }
1444 }
1445
1446 pub fn has_matches(&self) -> bool {
1447 self.active_match_index.is_some()
1448 }
1449
1450 fn landing_text_minor(&self, window: &mut Window, cx: &App) -> impl IntoElement {
1451 let focus_handle = self.focus_handle.clone();
1452 v_flex()
1453 .gap_1()
1454 .child(
1455 Label::new("Hit enter to search. For more options:")
1456 .color(Color::Muted)
1457 .mb_2(),
1458 )
1459 .child(
1460 Button::new("filter-paths", "Include/exclude specific paths")
1461 .icon(IconName::Filter)
1462 .icon_position(IconPosition::Start)
1463 .icon_size(IconSize::Small)
1464 .key_binding(KeyBinding::for_action_in(
1465 &ToggleFilters,
1466 &focus_handle,
1467 window,
1468 cx,
1469 ))
1470 .on_click(|_event, window, cx| {
1471 window.dispatch_action(ToggleFilters.boxed_clone(), cx)
1472 }),
1473 )
1474 .child(
1475 Button::new("find-replace", "Find and replace")
1476 .icon(IconName::Replace)
1477 .icon_position(IconPosition::Start)
1478 .icon_size(IconSize::Small)
1479 .key_binding(KeyBinding::for_action_in(
1480 &ToggleReplace,
1481 &focus_handle,
1482 window,
1483 cx,
1484 ))
1485 .on_click(|_event, window, cx| {
1486 window.dispatch_action(ToggleReplace.boxed_clone(), cx)
1487 }),
1488 )
1489 .child(
1490 Button::new("regex", "Match with regex")
1491 .icon(IconName::Regex)
1492 .icon_position(IconPosition::Start)
1493 .icon_size(IconSize::Small)
1494 .key_binding(KeyBinding::for_action_in(
1495 &ToggleRegex,
1496 &focus_handle,
1497 window,
1498 cx,
1499 ))
1500 .on_click(|_event, window, cx| {
1501 window.dispatch_action(ToggleRegex.boxed_clone(), cx)
1502 }),
1503 )
1504 .child(
1505 Button::new("match-case", "Match case")
1506 .icon(IconName::CaseSensitive)
1507 .icon_position(IconPosition::Start)
1508 .icon_size(IconSize::Small)
1509 .key_binding(KeyBinding::for_action_in(
1510 &ToggleCaseSensitive,
1511 &focus_handle,
1512 window,
1513 cx,
1514 ))
1515 .on_click(|_event, window, cx| {
1516 window.dispatch_action(ToggleCaseSensitive.boxed_clone(), cx)
1517 }),
1518 )
1519 .child(
1520 Button::new("match-whole-words", "Match whole words")
1521 .icon(IconName::WholeWord)
1522 .icon_position(IconPosition::Start)
1523 .icon_size(IconSize::Small)
1524 .key_binding(KeyBinding::for_action_in(
1525 &ToggleWholeWord,
1526 &focus_handle,
1527 window,
1528 cx,
1529 ))
1530 .on_click(|_event, window, cx| {
1531 window.dispatch_action(ToggleWholeWord.boxed_clone(), cx)
1532 }),
1533 )
1534 }
1535
1536 fn border_color_for(&self, panel: InputPanel, cx: &App) -> Hsla {
1537 if self.panels_with_errors.contains_key(&panel) {
1538 Color::Error.color(cx)
1539 } else {
1540 cx.theme().colors().border
1541 }
1542 }
1543
1544 fn move_focus_to_results(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1545 if !self.results_editor.focus_handle(cx).is_focused(window)
1546 && !self.entity.read(cx).match_ranges.is_empty()
1547 {
1548 cx.stop_propagation();
1549 self.focus_results_editor(window, cx)
1550 }
1551 }
1552
1553 #[cfg(any(test, feature = "test-support"))]
1554 pub fn results_editor(&self) -> &Entity<Editor> {
1555 &self.results_editor
1556 }
1557
1558 fn adjust_query_regex_language(&self, cx: &mut App) {
1559 let enable = self.search_options.contains(SearchOptions::REGEX);
1560 let query_buffer = self
1561 .query_editor
1562 .read(cx)
1563 .buffer()
1564 .read(cx)
1565 .as_singleton()
1566 .expect("query editor should be backed by a singleton buffer");
1567 if enable {
1568 if let Some(regex_language) = self.regex_language.clone() {
1569 query_buffer.update(cx, |query_buffer, cx| {
1570 query_buffer.set_language(Some(regex_language), cx);
1571 })
1572 }
1573 } else {
1574 query_buffer.update(cx, |query_buffer, cx| {
1575 query_buffer.set_language(None, cx);
1576 })
1577 }
1578 }
1579}
1580
1581fn buffer_search_query(
1582 workspace: &mut Workspace,
1583 item: &dyn ItemHandle,
1584 cx: &mut Context<Workspace>,
1585) -> Option<String> {
1586 let buffer_search_bar = workspace
1587 .pane_for(item)
1588 .and_then(|pane| {
1589 pane.read(cx)
1590 .toolbar()
1591 .read(cx)
1592 .item_of_type::<BufferSearchBar>()
1593 })?
1594 .read(cx);
1595 if buffer_search_bar.query_editor_focused() {
1596 let buffer_search_query = buffer_search_bar.query(cx);
1597 if !buffer_search_query.is_empty() {
1598 return Some(buffer_search_query);
1599 }
1600 }
1601 None
1602}
1603
1604impl Default for ProjectSearchBar {
1605 fn default() -> Self {
1606 Self::new()
1607 }
1608}
1609
1610impl ProjectSearchBar {
1611 pub fn new() -> Self {
1612 Self {
1613 active_project_search: None,
1614 subscription: None,
1615 }
1616 }
1617
1618 fn confirm(&mut self, _: &Confirm, window: &mut Window, cx: &mut Context<Self>) {
1619 if let Some(search_view) = self.active_project_search.as_ref() {
1620 search_view.update(cx, |search_view, cx| {
1621 if !search_view
1622 .replacement_editor
1623 .focus_handle(cx)
1624 .is_focused(window)
1625 {
1626 cx.stop_propagation();
1627 search_view
1628 .prompt_to_save_if_dirty_then_search(window, cx)
1629 .detach_and_log_err(cx);
1630 }
1631 });
1632 }
1633 }
1634
1635 fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
1636 self.cycle_field(Direction::Next, window, cx);
1637 }
1638
1639 fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
1640 self.cycle_field(Direction::Prev, window, cx);
1641 }
1642
1643 fn focus_search(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1644 if let Some(search_view) = self.active_project_search.as_ref() {
1645 search_view.update(cx, |search_view, cx| {
1646 search_view.query_editor.focus_handle(cx).focus(window);
1647 });
1648 }
1649 }
1650
1651 fn cycle_field(&mut self, direction: Direction, window: &mut Window, cx: &mut Context<Self>) {
1652 let active_project_search = match &self.active_project_search {
1653 Some(active_project_search) => active_project_search,
1654 None => return,
1655 };
1656
1657 active_project_search.update(cx, |project_view, cx| {
1658 let mut views = vec![project_view.query_editor.focus_handle(cx)];
1659 if project_view.replace_enabled {
1660 views.push(project_view.replacement_editor.focus_handle(cx));
1661 }
1662 if project_view.filters_enabled {
1663 views.extend([
1664 project_view.included_files_editor.focus_handle(cx),
1665 project_view.excluded_files_editor.focus_handle(cx),
1666 ]);
1667 }
1668 let current_index = match views.iter().position(|focus| focus.is_focused(window)) {
1669 Some(index) => index,
1670 None => return,
1671 };
1672
1673 let new_index = match direction {
1674 Direction::Next => (current_index + 1) % views.len(),
1675 Direction::Prev if current_index == 0 => views.len() - 1,
1676 Direction::Prev => (current_index - 1) % views.len(),
1677 };
1678 let next_focus_handle = &views[new_index];
1679 window.focus(next_focus_handle);
1680 cx.stop_propagation();
1681 });
1682 }
1683
1684 pub(crate) fn toggle_search_option(
1685 &mut self,
1686 option: SearchOptions,
1687 window: &mut Window,
1688 cx: &mut Context<Self>,
1689 ) -> bool {
1690 if self.active_project_search.is_none() {
1691 return false;
1692 }
1693
1694 cx.spawn_in(window, async move |this, cx| {
1695 let task = this.update_in(cx, |this, window, cx| {
1696 let search_view = this.active_project_search.as_ref()?;
1697 search_view.update(cx, |search_view, cx| {
1698 search_view.toggle_search_option(option, cx);
1699 search_view
1700 .entity
1701 .read(cx)
1702 .active_query
1703 .is_some()
1704 .then(|| search_view.prompt_to_save_if_dirty_then_search(window, cx))
1705 })
1706 })?;
1707 if let Some(task) = task {
1708 task.await?;
1709 }
1710 this.update(cx, |_, cx| {
1711 cx.notify();
1712 })?;
1713 anyhow::Ok(())
1714 })
1715 .detach();
1716 true
1717 }
1718
1719 fn toggle_replace(&mut self, _: &ToggleReplace, window: &mut Window, cx: &mut Context<Self>) {
1720 if let Some(search) = &self.active_project_search {
1721 search.update(cx, |this, cx| {
1722 this.replace_enabled = !this.replace_enabled;
1723 let editor_to_focus = if this.replace_enabled {
1724 this.replacement_editor.focus_handle(cx)
1725 } else {
1726 this.query_editor.focus_handle(cx)
1727 };
1728 window.focus(&editor_to_focus);
1729 cx.notify();
1730 });
1731 }
1732 }
1733
1734 fn toggle_filters(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
1735 if let Some(search_view) = self.active_project_search.as_ref() {
1736 search_view.update(cx, |search_view, cx| {
1737 search_view.toggle_filters(cx);
1738 search_view
1739 .included_files_editor
1740 .update(cx, |_, cx| cx.notify());
1741 search_view
1742 .excluded_files_editor
1743 .update(cx, |_, cx| cx.notify());
1744 window.refresh();
1745 cx.notify();
1746 });
1747 cx.notify();
1748 true
1749 } else {
1750 false
1751 }
1752 }
1753
1754 fn toggle_opened_only(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
1755 if self.active_project_search.is_none() {
1756 return false;
1757 }
1758
1759 cx.spawn_in(window, async move |this, cx| {
1760 let task = this.update_in(cx, |this, window, cx| {
1761 let search_view = this.active_project_search.as_ref()?;
1762 search_view.update(cx, |search_view, cx| {
1763 search_view.toggle_opened_only(window, cx);
1764 search_view
1765 .entity
1766 .read(cx)
1767 .active_query
1768 .is_some()
1769 .then(|| search_view.prompt_to_save_if_dirty_then_search(window, cx))
1770 })
1771 })?;
1772 if let Some(task) = task {
1773 task.await?;
1774 }
1775 this.update(cx, |_, cx| {
1776 cx.notify();
1777 })?;
1778 anyhow::Ok(())
1779 })
1780 .detach();
1781 true
1782 }
1783
1784 fn is_opened_only_enabled(&self, cx: &App) -> bool {
1785 if let Some(search_view) = self.active_project_search.as_ref() {
1786 search_view.read(cx).included_opened_only
1787 } else {
1788 false
1789 }
1790 }
1791
1792 fn move_focus_to_results(&self, window: &mut Window, cx: &mut Context<Self>) {
1793 if let Some(search_view) = self.active_project_search.as_ref() {
1794 search_view.update(cx, |search_view, cx| {
1795 search_view.move_focus_to_results(window, cx);
1796 });
1797 cx.notify();
1798 }
1799 }
1800
1801 fn next_history_query(
1802 &mut self,
1803 _: &NextHistoryQuery,
1804 window: &mut Window,
1805 cx: &mut Context<Self>,
1806 ) {
1807 if let Some(search_view) = self.active_project_search.as_ref() {
1808 search_view.update(cx, |search_view, cx| {
1809 for (editor, kind) in [
1810 (search_view.query_editor.clone(), SearchInputKind::Query),
1811 (
1812 search_view.included_files_editor.clone(),
1813 SearchInputKind::Include,
1814 ),
1815 (
1816 search_view.excluded_files_editor.clone(),
1817 SearchInputKind::Exclude,
1818 ),
1819 ] {
1820 if editor.focus_handle(cx).is_focused(window) {
1821 let new_query = search_view.entity.update(cx, |model, cx| {
1822 let project = model.project.clone();
1823
1824 if let Some(new_query) = project.update(cx, |project, _| {
1825 project
1826 .search_history_mut(kind)
1827 .next(model.cursor_mut(kind))
1828 .map(str::to_string)
1829 }) {
1830 new_query
1831 } else {
1832 model.cursor_mut(kind).reset();
1833 String::new()
1834 }
1835 });
1836 search_view.set_search_editor(kind, &new_query, window, cx);
1837 }
1838 }
1839 });
1840 }
1841 }
1842
1843 fn previous_history_query(
1844 &mut self,
1845 _: &PreviousHistoryQuery,
1846 window: &mut Window,
1847 cx: &mut Context<Self>,
1848 ) {
1849 if let Some(search_view) = self.active_project_search.as_ref() {
1850 search_view.update(cx, |search_view, cx| {
1851 for (editor, kind) in [
1852 (search_view.query_editor.clone(), SearchInputKind::Query),
1853 (
1854 search_view.included_files_editor.clone(),
1855 SearchInputKind::Include,
1856 ),
1857 (
1858 search_view.excluded_files_editor.clone(),
1859 SearchInputKind::Exclude,
1860 ),
1861 ] {
1862 if editor.focus_handle(cx).is_focused(window) {
1863 if editor.read(cx).text(cx).is_empty()
1864 && let Some(new_query) = search_view
1865 .entity
1866 .read(cx)
1867 .project
1868 .read(cx)
1869 .search_history(kind)
1870 .current(search_view.entity.read(cx).cursor(kind))
1871 .map(str::to_string)
1872 {
1873 search_view.set_search_editor(kind, &new_query, window, cx);
1874 return;
1875 }
1876
1877 if let Some(new_query) = search_view.entity.update(cx, |model, cx| {
1878 let project = model.project.clone();
1879 project.update(cx, |project, _| {
1880 project
1881 .search_history_mut(kind)
1882 .previous(model.cursor_mut(kind))
1883 .map(str::to_string)
1884 })
1885 }) {
1886 search_view.set_search_editor(kind, &new_query, window, cx);
1887 }
1888 }
1889 }
1890 });
1891 }
1892 }
1893
1894 fn select_next_match(
1895 &mut self,
1896 _: &SelectNextMatch,
1897 window: &mut Window,
1898 cx: &mut Context<Self>,
1899 ) {
1900 if let Some(search) = self.active_project_search.as_ref() {
1901 search.update(cx, |this, cx| {
1902 this.select_match(Direction::Next, window, cx);
1903 })
1904 }
1905 }
1906
1907 fn select_prev_match(
1908 &mut self,
1909 _: &SelectPreviousMatch,
1910 window: &mut Window,
1911 cx: &mut Context<Self>,
1912 ) {
1913 if let Some(search) = self.active_project_search.as_ref() {
1914 search.update(cx, |this, cx| {
1915 this.select_match(Direction::Prev, window, cx);
1916 })
1917 }
1918 }
1919}
1920
1921impl Render for ProjectSearchBar {
1922 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1923 let Some(search) = self.active_project_search.clone() else {
1924 return div();
1925 };
1926 let search = search.read(cx);
1927 let focus_handle = search.focus_handle(cx);
1928
1929 let container_width = window.viewport_size().width;
1930 let input_width = SearchInputWidth::calc_width(container_width);
1931
1932 let input_base_styles = |panel: InputPanel| {
1933 input_base_styles(search.border_color_for(panel, cx), |div| match panel {
1934 InputPanel::Query | InputPanel::Replacement => div.w(input_width),
1935 InputPanel::Include | InputPanel::Exclude => div.flex_grow(),
1936 })
1937 };
1938 let theme_colors = cx.theme().colors();
1939 let project_search = search.entity.read(cx);
1940 let limit_reached = project_search.limit_reached;
1941
1942 let color_override = match (
1943 &project_search.pending_search,
1944 project_search.no_results,
1945 &project_search.active_query,
1946 &project_search.last_search_query_text,
1947 ) {
1948 (None, Some(true), Some(q), Some(p)) if q.as_str() == p => Some(Color::Error),
1949 _ => None,
1950 };
1951
1952 let match_text = search
1953 .active_match_index
1954 .and_then(|index| {
1955 let index = index + 1;
1956 let match_quantity = project_search.match_ranges.len();
1957 if match_quantity > 0 {
1958 debug_assert!(match_quantity >= index);
1959 if limit_reached {
1960 Some(format!("{index}/{match_quantity}+"))
1961 } else {
1962 Some(format!("{index}/{match_quantity}"))
1963 }
1964 } else {
1965 None
1966 }
1967 })
1968 .unwrap_or_else(|| "0/0".to_string());
1969
1970 let query_column = input_base_styles(InputPanel::Query)
1971 .on_action(cx.listener(|this, action, window, cx| this.confirm(action, window, cx)))
1972 .on_action(cx.listener(|this, action, window, cx| {
1973 this.previous_history_query(action, window, cx)
1974 }))
1975 .on_action(
1976 cx.listener(|this, action, window, cx| this.next_history_query(action, window, cx)),
1977 )
1978 .child(render_text_input(&search.query_editor, color_override, cx))
1979 .child(
1980 h_flex()
1981 .gap_1()
1982 .child(SearchOption::CaseSensitive.as_button(
1983 search.search_options,
1984 SearchSource::Project(cx),
1985 focus_handle.clone(),
1986 ))
1987 .child(SearchOption::WholeWord.as_button(
1988 search.search_options,
1989 SearchSource::Project(cx),
1990 focus_handle.clone(),
1991 ))
1992 .child(SearchOption::Regex.as_button(
1993 search.search_options,
1994 SearchSource::Project(cx),
1995 focus_handle.clone(),
1996 )),
1997 );
1998
1999 let query_focus = search.query_editor.focus_handle(cx);
2000
2001 let matches_column = h_flex()
2002 .pl_2()
2003 .ml_2()
2004 .border_l_1()
2005 .border_color(theme_colors.border_variant)
2006 .child(render_action_button(
2007 "project-search-nav-button",
2008 IconName::ChevronLeft,
2009 search
2010 .active_match_index
2011 .is_none()
2012 .then_some(ActionButtonState::Disabled),
2013 "Select Previous Match",
2014 &SelectPreviousMatch,
2015 query_focus.clone(),
2016 ))
2017 .child(render_action_button(
2018 "project-search-nav-button",
2019 IconName::ChevronRight,
2020 search
2021 .active_match_index
2022 .is_none()
2023 .then_some(ActionButtonState::Disabled),
2024 "Select Next Match",
2025 &SelectNextMatch,
2026 query_focus,
2027 ))
2028 .child(
2029 div()
2030 .id("matches")
2031 .ml_2()
2032 .min_w(rems_from_px(40.))
2033 .child(Label::new(match_text).size(LabelSize::Small).color(
2034 if search.active_match_index.is_some() {
2035 Color::Default
2036 } else {
2037 Color::Disabled
2038 },
2039 ))
2040 .when(limit_reached, |el| {
2041 el.tooltip(Tooltip::text(
2042 "Search limits reached.\nTry narrowing your search.",
2043 ))
2044 }),
2045 );
2046
2047 let mode_column = h_flex()
2048 .gap_1()
2049 .min_w_64()
2050 .child(
2051 IconButton::new("project-search-filter-button", IconName::Filter)
2052 .shape(IconButtonShape::Square)
2053 .tooltip(|window, cx| {
2054 Tooltip::for_action("Toggle Filters", &ToggleFilters, window, cx)
2055 })
2056 .on_click(cx.listener(|this, _, window, cx| {
2057 this.toggle_filters(window, cx);
2058 }))
2059 .toggle_state(
2060 self.active_project_search
2061 .as_ref()
2062 .map(|search| search.read(cx).filters_enabled)
2063 .unwrap_or_default(),
2064 )
2065 .tooltip({
2066 let focus_handle = focus_handle.clone();
2067 move |window, cx| {
2068 Tooltip::for_action_in(
2069 "Toggle Filters",
2070 &ToggleFilters,
2071 &focus_handle,
2072 window,
2073 cx,
2074 )
2075 }
2076 }),
2077 )
2078 .child(render_action_button(
2079 "project-search",
2080 IconName::Replace,
2081 self.active_project_search
2082 .as_ref()
2083 .map(|search| search.read(cx).replace_enabled)
2084 .and_then(|enabled| enabled.then_some(ActionButtonState::Toggled)),
2085 "Toggle Replace",
2086 &ToggleReplace,
2087 focus_handle.clone(),
2088 ))
2089 .child(matches_column);
2090
2091 let search_line = h_flex()
2092 .w_full()
2093 .gap_2()
2094 .child(query_column)
2095 .child(mode_column);
2096
2097 let replace_line = search.replace_enabled.then(|| {
2098 let replace_column = input_base_styles(InputPanel::Replacement)
2099 .child(render_text_input(&search.replacement_editor, None, cx));
2100
2101 let focus_handle = search.replacement_editor.read(cx).focus_handle(cx);
2102
2103 let replace_actions = h_flex()
2104 .min_w_64()
2105 .gap_1()
2106 .child(render_action_button(
2107 "project-search-replace-button",
2108 IconName::ReplaceNext,
2109 Default::default(),
2110 "Replace Next Match",
2111 &ReplaceNext,
2112 focus_handle.clone(),
2113 ))
2114 .child(render_action_button(
2115 "project-search-replace-button",
2116 IconName::ReplaceAll,
2117 Default::default(),
2118 "Replace All Matches",
2119 &ReplaceAll,
2120 focus_handle,
2121 ));
2122
2123 h_flex()
2124 .w_full()
2125 .gap_2()
2126 .child(replace_column)
2127 .child(replace_actions)
2128 });
2129
2130 let filter_line = search.filters_enabled.then(|| {
2131 let include = input_base_styles(InputPanel::Include)
2132 .on_action(cx.listener(|this, action, window, cx| {
2133 this.previous_history_query(action, window, cx)
2134 }))
2135 .on_action(cx.listener(|this, action, window, cx| {
2136 this.next_history_query(action, window, cx)
2137 }))
2138 .child(render_text_input(&search.included_files_editor, None, cx));
2139 let exclude = input_base_styles(InputPanel::Exclude)
2140 .on_action(cx.listener(|this, action, window, cx| {
2141 this.previous_history_query(action, window, cx)
2142 }))
2143 .on_action(cx.listener(|this, action, window, cx| {
2144 this.next_history_query(action, window, cx)
2145 }))
2146 .child(render_text_input(&search.excluded_files_editor, None, cx));
2147 let mode_column = h_flex()
2148 .gap_1()
2149 .min_w_64()
2150 .child(
2151 IconButton::new("project-search-opened-only", IconName::FolderSearch)
2152 .shape(IconButtonShape::Square)
2153 .toggle_state(self.is_opened_only_enabled(cx))
2154 .tooltip(Tooltip::text("Only Search Open Files"))
2155 .on_click(cx.listener(|this, _, window, cx| {
2156 this.toggle_opened_only(window, cx);
2157 })),
2158 )
2159 .child(SearchOption::IncludeIgnored.as_button(
2160 search.search_options,
2161 SearchSource::Project(cx),
2162 focus_handle.clone(),
2163 ));
2164 h_flex()
2165 .w_full()
2166 .gap_2()
2167 .child(
2168 h_flex()
2169 .gap_2()
2170 .w(input_width)
2171 .child(include)
2172 .child(exclude),
2173 )
2174 .child(mode_column)
2175 });
2176
2177 let mut key_context = KeyContext::default();
2178 key_context.add("ProjectSearchBar");
2179 if search
2180 .replacement_editor
2181 .focus_handle(cx)
2182 .is_focused(window)
2183 {
2184 key_context.add("in_replace");
2185 }
2186
2187 let query_error_line = search
2188 .panels_with_errors
2189 .get(&InputPanel::Query)
2190 .map(|error| {
2191 Label::new(error)
2192 .size(LabelSize::Small)
2193 .color(Color::Error)
2194 .mt_neg_1()
2195 .ml_2()
2196 });
2197
2198 let filter_error_line = search
2199 .panels_with_errors
2200 .get(&InputPanel::Include)
2201 .or_else(|| search.panels_with_errors.get(&InputPanel::Exclude))
2202 .map(|error| {
2203 Label::new(error)
2204 .size(LabelSize::Small)
2205 .color(Color::Error)
2206 .mt_neg_1()
2207 .ml_2()
2208 });
2209
2210 v_flex()
2211 .gap_2()
2212 .py(px(1.0))
2213 .w_full()
2214 .key_context(key_context)
2215 .on_action(cx.listener(|this, _: &ToggleFocus, window, cx| {
2216 this.move_focus_to_results(window, cx)
2217 }))
2218 .on_action(cx.listener(|this, _: &ToggleFilters, window, cx| {
2219 this.toggle_filters(window, cx);
2220 }))
2221 .capture_action(cx.listener(Self::tab))
2222 .capture_action(cx.listener(Self::backtab))
2223 .on_action(cx.listener(|this, action, window, cx| this.confirm(action, window, cx)))
2224 .on_action(cx.listener(|this, action, window, cx| {
2225 this.toggle_replace(action, window, cx);
2226 }))
2227 .on_action(cx.listener(|this, _: &ToggleWholeWord, window, cx| {
2228 this.toggle_search_option(SearchOptions::WHOLE_WORD, window, cx);
2229 }))
2230 .on_action(cx.listener(|this, _: &ToggleCaseSensitive, window, cx| {
2231 this.toggle_search_option(SearchOptions::CASE_SENSITIVE, window, cx);
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_next(action, window, cx);
2237 })
2238 }
2239 }))
2240 .on_action(cx.listener(|this, action, window, cx| {
2241 if let Some(search) = this.active_project_search.as_ref() {
2242 search.update(cx, |this, cx| {
2243 this.replace_all(action, window, cx);
2244 })
2245 }
2246 }))
2247 .when(search.filters_enabled, |this| {
2248 this.on_action(cx.listener(|this, _: &ToggleIncludeIgnored, window, cx| {
2249 this.toggle_search_option(SearchOptions::INCLUDE_IGNORED, window, cx);
2250 }))
2251 })
2252 .on_action(cx.listener(Self::select_next_match))
2253 .on_action(cx.listener(Self::select_prev_match))
2254 .child(search_line)
2255 .children(query_error_line)
2256 .children(replace_line)
2257 .children(filter_line)
2258 .children(filter_error_line)
2259 }
2260}
2261
2262impl EventEmitter<ToolbarItemEvent> for ProjectSearchBar {}
2263
2264impl ToolbarItemView for ProjectSearchBar {
2265 fn set_active_pane_item(
2266 &mut self,
2267 active_pane_item: Option<&dyn ItemHandle>,
2268 _: &mut Window,
2269 cx: &mut Context<Self>,
2270 ) -> ToolbarItemLocation {
2271 cx.notify();
2272 self.subscription = None;
2273 self.active_project_search = None;
2274 if let Some(search) = active_pane_item.and_then(|i| i.downcast::<ProjectSearchView>()) {
2275 self.subscription = Some(cx.observe(&search, |_, _, cx| cx.notify()));
2276 self.active_project_search = Some(search);
2277 ToolbarItemLocation::PrimaryLeft {}
2278 } else {
2279 ToolbarItemLocation::Hidden
2280 }
2281 }
2282}
2283
2284fn register_workspace_action<A: Action>(
2285 workspace: &mut Workspace,
2286 callback: fn(&mut ProjectSearchBar, &A, &mut Window, &mut Context<ProjectSearchBar>),
2287) {
2288 workspace.register_action(move |workspace, action: &A, window, cx| {
2289 if workspace.has_active_modal(window, cx) {
2290 cx.propagate();
2291 return;
2292 }
2293
2294 workspace.active_pane().update(cx, |pane, cx| {
2295 pane.toolbar().update(cx, move |workspace, cx| {
2296 if let Some(search_bar) = workspace.item_of_type::<ProjectSearchBar>() {
2297 search_bar.update(cx, move |search_bar, cx| {
2298 if search_bar.active_project_search.is_some() {
2299 callback(search_bar, action, window, cx);
2300 cx.notify();
2301 } else {
2302 cx.propagate();
2303 }
2304 });
2305 }
2306 });
2307 })
2308 });
2309}
2310
2311fn register_workspace_action_for_present_search<A: Action>(
2312 workspace: &mut Workspace,
2313 callback: fn(&mut Workspace, &A, &mut Window, &mut Context<Workspace>),
2314) {
2315 workspace.register_action(move |workspace, action: &A, window, cx| {
2316 if workspace.has_active_modal(window, cx) {
2317 cx.propagate();
2318 return;
2319 }
2320
2321 let should_notify = workspace
2322 .active_pane()
2323 .read(cx)
2324 .toolbar()
2325 .read(cx)
2326 .item_of_type::<ProjectSearchBar>()
2327 .map(|search_bar| search_bar.read(cx).active_project_search.is_some())
2328 .unwrap_or(false);
2329 if should_notify {
2330 callback(workspace, action, window, cx);
2331 cx.notify();
2332 } else {
2333 cx.propagate();
2334 }
2335 });
2336}
2337
2338#[cfg(any(test, feature = "test-support"))]
2339pub fn perform_project_search(
2340 search_view: &Entity<ProjectSearchView>,
2341 text: impl Into<std::sync::Arc<str>>,
2342 cx: &mut gpui::VisualTestContext,
2343) {
2344 cx.run_until_parked();
2345 search_view.update_in(cx, |search_view, window, cx| {
2346 search_view.query_editor.update(cx, |query_editor, cx| {
2347 query_editor.set_text(text, window, cx)
2348 });
2349 search_view.search(cx);
2350 });
2351 cx.run_until_parked();
2352}
2353
2354#[cfg(test)]
2355pub mod tests {
2356 use std::{ops::Deref as _, sync::Arc, time::Duration};
2357
2358 use super::*;
2359 use editor::{DisplayPoint, display_map::DisplayRow};
2360 use gpui::{Action, TestAppContext, VisualTestContext, WindowHandle};
2361 use project::FakeFs;
2362 use serde_json::json;
2363 use settings::SettingsStore;
2364 use util::path;
2365 use workspace::DeploySearch;
2366
2367 #[gpui::test]
2368 async fn test_project_search(cx: &mut TestAppContext) {
2369 init_test(cx);
2370
2371 let fs = FakeFs::new(cx.background_executor.clone());
2372 fs.insert_tree(
2373 path!("/dir"),
2374 json!({
2375 "one.rs": "const ONE: usize = 1;",
2376 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2377 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2378 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2379 }),
2380 )
2381 .await;
2382 let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
2383 let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
2384 let workspace = window.root(cx).unwrap();
2385 let search = cx.new(|cx| ProjectSearch::new(project.clone(), cx));
2386 let search_view = cx.add_window(|window, cx| {
2387 ProjectSearchView::new(workspace.downgrade(), search.clone(), window, cx, None)
2388 });
2389
2390 perform_search(search_view, "TWO", cx);
2391 search_view.update(cx, |search_view, window, cx| {
2392 assert_eq!(
2393 search_view
2394 .results_editor
2395 .update(cx, |editor, cx| editor.display_text(cx)),
2396 "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;"
2397 );
2398 let match_background_color = cx.theme().colors().search_match_background;
2399 let selection_background_color = cx.theme().colors().editor_document_highlight_bracket_background;
2400 assert_eq!(
2401 search_view
2402 .results_editor
2403 .update(cx, |editor, cx| editor.all_text_background_highlights(window, cx)),
2404 &[
2405 (
2406 DisplayPoint::new(DisplayRow(2), 32)..DisplayPoint::new(DisplayRow(2), 35),
2407 match_background_color
2408 ),
2409 (
2410 DisplayPoint::new(DisplayRow(2), 37)..DisplayPoint::new(DisplayRow(2), 40),
2411 selection_background_color
2412 ),
2413 (
2414 DisplayPoint::new(DisplayRow(2), 37)..DisplayPoint::new(DisplayRow(2), 40),
2415 match_background_color
2416 ),
2417 (
2418 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(5), 9),
2419 selection_background_color
2420 ),
2421 (
2422 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(5), 9),
2423 match_background_color
2424 ),
2425
2426 ]
2427 );
2428 assert_eq!(search_view.active_match_index, Some(0));
2429 assert_eq!(
2430 search_view
2431 .results_editor
2432 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2433 [DisplayPoint::new(DisplayRow(2), 32)..DisplayPoint::new(DisplayRow(2), 35)]
2434 );
2435
2436 search_view.select_match(Direction::Next, window, cx);
2437 }).unwrap();
2438
2439 search_view
2440 .update(cx, |search_view, window, cx| {
2441 assert_eq!(search_view.active_match_index, Some(1));
2442 assert_eq!(
2443 search_view
2444 .results_editor
2445 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2446 [DisplayPoint::new(DisplayRow(2), 37)..DisplayPoint::new(DisplayRow(2), 40)]
2447 );
2448 search_view.select_match(Direction::Next, window, cx);
2449 })
2450 .unwrap();
2451
2452 search_view
2453 .update(cx, |search_view, window, cx| {
2454 assert_eq!(search_view.active_match_index, Some(2));
2455 assert_eq!(
2456 search_view
2457 .results_editor
2458 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2459 [DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(5), 9)]
2460 );
2461 search_view.select_match(Direction::Next, window, cx);
2462 })
2463 .unwrap();
2464
2465 search_view
2466 .update(cx, |search_view, window, cx| {
2467 assert_eq!(search_view.active_match_index, Some(0));
2468 assert_eq!(
2469 search_view
2470 .results_editor
2471 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2472 [DisplayPoint::new(DisplayRow(2), 32)..DisplayPoint::new(DisplayRow(2), 35)]
2473 );
2474 search_view.select_match(Direction::Prev, window, cx);
2475 })
2476 .unwrap();
2477
2478 search_view
2479 .update(cx, |search_view, window, cx| {
2480 assert_eq!(search_view.active_match_index, Some(2));
2481 assert_eq!(
2482 search_view
2483 .results_editor
2484 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2485 [DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(5), 9)]
2486 );
2487 search_view.select_match(Direction::Prev, window, cx);
2488 })
2489 .unwrap();
2490
2491 search_view
2492 .update(cx, |search_view, _, cx| {
2493 assert_eq!(search_view.active_match_index, Some(1));
2494 assert_eq!(
2495 search_view
2496 .results_editor
2497 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2498 [DisplayPoint::new(DisplayRow(2), 37)..DisplayPoint::new(DisplayRow(2), 40)]
2499 );
2500 })
2501 .unwrap();
2502 }
2503
2504 #[gpui::test]
2505 async fn test_deploy_project_search_focus(cx: &mut TestAppContext) {
2506 init_test(cx);
2507
2508 let fs = FakeFs::new(cx.background_executor.clone());
2509 fs.insert_tree(
2510 "/dir",
2511 json!({
2512 "one.rs": "const ONE: usize = 1;",
2513 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2514 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2515 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2516 }),
2517 )
2518 .await;
2519 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
2520 let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
2521 let workspace = window;
2522 let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
2523
2524 let active_item = cx.read(|cx| {
2525 workspace
2526 .read(cx)
2527 .unwrap()
2528 .active_pane()
2529 .read(cx)
2530 .active_item()
2531 .and_then(|item| item.downcast::<ProjectSearchView>())
2532 });
2533 assert!(
2534 active_item.is_none(),
2535 "Expected no search panel to be active"
2536 );
2537
2538 window
2539 .update(cx, move |workspace, window, cx| {
2540 assert_eq!(workspace.panes().len(), 1);
2541 workspace.panes()[0].update(cx, |pane, cx| {
2542 pane.toolbar()
2543 .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
2544 });
2545
2546 ProjectSearchView::deploy_search(
2547 workspace,
2548 &workspace::DeploySearch::find(),
2549 window,
2550 cx,
2551 )
2552 })
2553 .unwrap();
2554
2555 let Some(search_view) = cx.read(|cx| {
2556 workspace
2557 .read(cx)
2558 .unwrap()
2559 .active_pane()
2560 .read(cx)
2561 .active_item()
2562 .and_then(|item| item.downcast::<ProjectSearchView>())
2563 }) else {
2564 panic!("Search view expected to appear after new search event trigger")
2565 };
2566
2567 cx.spawn(|mut cx| async move {
2568 window
2569 .update(&mut cx, |_, window, cx| {
2570 window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2571 })
2572 .unwrap();
2573 })
2574 .detach();
2575 cx.background_executor.run_until_parked();
2576 window
2577 .update(cx, |_, window, cx| {
2578 search_view.update(cx, |search_view, cx| {
2579 assert!(
2580 search_view.query_editor.focus_handle(cx).is_focused(window),
2581 "Empty search view should be focused after the toggle focus event: no results panel to focus on",
2582 );
2583 });
2584 }).unwrap();
2585
2586 window
2587 .update(cx, |_, window, cx| {
2588 search_view.update(cx, |search_view, cx| {
2589 let query_editor = &search_view.query_editor;
2590 assert!(
2591 query_editor.focus_handle(cx).is_focused(window),
2592 "Search view should be focused after the new search view is activated",
2593 );
2594 let query_text = query_editor.read(cx).text(cx);
2595 assert!(
2596 query_text.is_empty(),
2597 "New search query should be empty but got '{query_text}'",
2598 );
2599 let results_text = search_view
2600 .results_editor
2601 .update(cx, |editor, cx| editor.display_text(cx));
2602 assert!(
2603 results_text.is_empty(),
2604 "Empty search view should have no results but got '{results_text}'"
2605 );
2606 });
2607 })
2608 .unwrap();
2609
2610 window
2611 .update(cx, |_, window, cx| {
2612 search_view.update(cx, |search_view, cx| {
2613 search_view.query_editor.update(cx, |query_editor, cx| {
2614 query_editor.set_text("sOMETHINGtHATsURELYdOESnOTeXIST", window, cx)
2615 });
2616 search_view.search(cx);
2617 });
2618 })
2619 .unwrap();
2620 cx.background_executor.run_until_parked();
2621 window
2622 .update(cx, |_, window, cx| {
2623 search_view.update(cx, |search_view, cx| {
2624 let results_text = search_view
2625 .results_editor
2626 .update(cx, |editor, cx| editor.display_text(cx));
2627 assert!(
2628 results_text.is_empty(),
2629 "Search view for mismatching query should have no results but got '{results_text}'"
2630 );
2631 assert!(
2632 search_view.query_editor.focus_handle(cx).is_focused(window),
2633 "Search view should be focused after mismatching query had been used in search",
2634 );
2635 });
2636 }).unwrap();
2637
2638 cx.spawn(|mut cx| async move {
2639 window.update(&mut cx, |_, window, cx| {
2640 window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2641 })
2642 })
2643 .detach();
2644 cx.background_executor.run_until_parked();
2645 window.update(cx, |_, window, cx| {
2646 search_view.update(cx, |search_view, cx| {
2647 assert!(
2648 search_view.query_editor.focus_handle(cx).is_focused(window),
2649 "Search view with mismatching query should be focused after the toggle focus event: still no results panel to focus on",
2650 );
2651 });
2652 }).unwrap();
2653
2654 window
2655 .update(cx, |_, window, cx| {
2656 search_view.update(cx, |search_view, cx| {
2657 search_view.query_editor.update(cx, |query_editor, cx| {
2658 query_editor.set_text("TWO", window, cx)
2659 });
2660 search_view.search(cx);
2661 });
2662 })
2663 .unwrap();
2664 cx.background_executor.run_until_parked();
2665 window.update(cx, |_, window, cx| {
2666 search_view.update(cx, |search_view, cx| {
2667 assert_eq!(
2668 search_view
2669 .results_editor
2670 .update(cx, |editor, cx| editor.display_text(cx)),
2671 "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
2672 "Search view results should match the query"
2673 );
2674 assert!(
2675 search_view.results_editor.focus_handle(cx).is_focused(window),
2676 "Search view with mismatching query should be focused after search results are available",
2677 );
2678 });
2679 }).unwrap();
2680 cx.spawn(|mut cx| async move {
2681 window
2682 .update(&mut cx, |_, window, cx| {
2683 window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2684 })
2685 .unwrap();
2686 })
2687 .detach();
2688 cx.background_executor.run_until_parked();
2689 window.update(cx, |_, window, cx| {
2690 search_view.update(cx, |search_view, cx| {
2691 assert!(
2692 search_view.results_editor.focus_handle(cx).is_focused(window),
2693 "Search view with matching query should still have its results editor focused after the toggle focus event",
2694 );
2695 });
2696 }).unwrap();
2697
2698 workspace
2699 .update(cx, |workspace, window, cx| {
2700 ProjectSearchView::deploy_search(
2701 workspace,
2702 &workspace::DeploySearch::find(),
2703 window,
2704 cx,
2705 )
2706 })
2707 .unwrap();
2708 window.update(cx, |_, window, cx| {
2709 search_view.update(cx, |search_view, cx| {
2710 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");
2711 assert_eq!(
2712 search_view
2713 .results_editor
2714 .update(cx, |editor, cx| editor.display_text(cx)),
2715 "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
2716 "Results should be unchanged after search view 2nd open in a row"
2717 );
2718 assert!(
2719 search_view.query_editor.focus_handle(cx).is_focused(window),
2720 "Focus should be moved into query editor again after search view 2nd open in a row"
2721 );
2722 });
2723 }).unwrap();
2724
2725 cx.spawn(|mut cx| async move {
2726 window
2727 .update(&mut cx, |_, window, cx| {
2728 window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2729 })
2730 .unwrap();
2731 })
2732 .detach();
2733 cx.background_executor.run_until_parked();
2734 window.update(cx, |_, window, cx| {
2735 search_view.update(cx, |search_view, cx| {
2736 assert!(
2737 search_view.results_editor.focus_handle(cx).is_focused(window),
2738 "Search view with matching query should switch focus to the results editor after the toggle focus event",
2739 );
2740 });
2741 }).unwrap();
2742 }
2743
2744 #[gpui::test]
2745 async fn test_filters_consider_toggle_state(cx: &mut TestAppContext) {
2746 init_test(cx);
2747
2748 let fs = FakeFs::new(cx.background_executor.clone());
2749 fs.insert_tree(
2750 "/dir",
2751 json!({
2752 "one.rs": "const ONE: usize = 1;",
2753 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2754 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2755 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2756 }),
2757 )
2758 .await;
2759 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
2760 let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
2761 let workspace = window;
2762 let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
2763
2764 window
2765 .update(cx, move |workspace, window, cx| {
2766 workspace.panes()[0].update(cx, |pane, cx| {
2767 pane.toolbar()
2768 .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
2769 });
2770
2771 ProjectSearchView::deploy_search(
2772 workspace,
2773 &workspace::DeploySearch::find(),
2774 window,
2775 cx,
2776 )
2777 })
2778 .unwrap();
2779
2780 let Some(search_view) = cx.read(|cx| {
2781 workspace
2782 .read(cx)
2783 .unwrap()
2784 .active_pane()
2785 .read(cx)
2786 .active_item()
2787 .and_then(|item| item.downcast::<ProjectSearchView>())
2788 }) else {
2789 panic!("Search view expected to appear after new search event trigger")
2790 };
2791
2792 cx.spawn(|mut cx| async move {
2793 window
2794 .update(&mut cx, |_, window, cx| {
2795 window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2796 })
2797 .unwrap();
2798 })
2799 .detach();
2800 cx.background_executor.run_until_parked();
2801
2802 window
2803 .update(cx, |_, window, cx| {
2804 search_view.update(cx, |search_view, cx| {
2805 search_view.query_editor.update(cx, |query_editor, cx| {
2806 query_editor.set_text("const FOUR", window, cx)
2807 });
2808 search_view.toggle_filters(cx);
2809 search_view
2810 .excluded_files_editor
2811 .update(cx, |exclude_editor, cx| {
2812 exclude_editor.set_text("four.rs", window, cx)
2813 });
2814 search_view.search(cx);
2815 });
2816 })
2817 .unwrap();
2818 cx.background_executor.run_until_parked();
2819 window
2820 .update(cx, |_, _, cx| {
2821 search_view.update(cx, |search_view, cx| {
2822 let results_text = search_view
2823 .results_editor
2824 .update(cx, |editor, cx| editor.display_text(cx));
2825 assert!(
2826 results_text.is_empty(),
2827 "Search view for query with the only match in an excluded file should have no results but got '{results_text}'"
2828 );
2829 });
2830 }).unwrap();
2831
2832 cx.spawn(|mut cx| async move {
2833 window.update(&mut cx, |_, window, cx| {
2834 window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2835 })
2836 })
2837 .detach();
2838 cx.background_executor.run_until_parked();
2839
2840 window
2841 .update(cx, |_, _, cx| {
2842 search_view.update(cx, |search_view, cx| {
2843 search_view.toggle_filters(cx);
2844 search_view.search(cx);
2845 });
2846 })
2847 .unwrap();
2848 cx.background_executor.run_until_parked();
2849 window
2850 .update(cx, |_, _, cx| {
2851 search_view.update(cx, |search_view, cx| {
2852 assert_eq!(
2853 search_view
2854 .results_editor
2855 .update(cx, |editor, cx| editor.display_text(cx)),
2856 "\n\nconst FOUR: usize = one::ONE + three::THREE;",
2857 "Search view results should contain the queried result in the previously excluded file with filters toggled off"
2858 );
2859 });
2860 })
2861 .unwrap();
2862 }
2863
2864 #[gpui::test]
2865 async fn test_new_project_search_focus(cx: &mut TestAppContext) {
2866 init_test(cx);
2867
2868 let fs = FakeFs::new(cx.background_executor.clone());
2869 fs.insert_tree(
2870 path!("/dir"),
2871 json!({
2872 "one.rs": "const ONE: usize = 1;",
2873 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2874 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2875 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2876 }),
2877 )
2878 .await;
2879 let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
2880 let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
2881 let workspace = window;
2882 let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
2883
2884 let active_item = cx.read(|cx| {
2885 workspace
2886 .read(cx)
2887 .unwrap()
2888 .active_pane()
2889 .read(cx)
2890 .active_item()
2891 .and_then(|item| item.downcast::<ProjectSearchView>())
2892 });
2893 assert!(
2894 active_item.is_none(),
2895 "Expected no search panel to be active"
2896 );
2897
2898 window
2899 .update(cx, move |workspace, window, cx| {
2900 assert_eq!(workspace.panes().len(), 1);
2901 workspace.panes()[0].update(cx, |pane, cx| {
2902 pane.toolbar()
2903 .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
2904 });
2905
2906 ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
2907 })
2908 .unwrap();
2909
2910 let Some(search_view) = cx.read(|cx| {
2911 workspace
2912 .read(cx)
2913 .unwrap()
2914 .active_pane()
2915 .read(cx)
2916 .active_item()
2917 .and_then(|item| item.downcast::<ProjectSearchView>())
2918 }) else {
2919 panic!("Search view expected to appear after new search event trigger")
2920 };
2921
2922 cx.spawn(|mut cx| async move {
2923 window
2924 .update(&mut cx, |_, window, cx| {
2925 window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2926 })
2927 .unwrap();
2928 })
2929 .detach();
2930 cx.background_executor.run_until_parked();
2931
2932 window.update(cx, |_, window, cx| {
2933 search_view.update(cx, |search_view, cx| {
2934 assert!(
2935 search_view.query_editor.focus_handle(cx).is_focused(window),
2936 "Empty search view should be focused after the toggle focus event: no results panel to focus on",
2937 );
2938 });
2939 }).unwrap();
2940
2941 window
2942 .update(cx, |_, window, cx| {
2943 search_view.update(cx, |search_view, cx| {
2944 let query_editor = &search_view.query_editor;
2945 assert!(
2946 query_editor.focus_handle(cx).is_focused(window),
2947 "Search view should be focused after the new search view is activated",
2948 );
2949 let query_text = query_editor.read(cx).text(cx);
2950 assert!(
2951 query_text.is_empty(),
2952 "New search query should be empty but got '{query_text}'",
2953 );
2954 let results_text = search_view
2955 .results_editor
2956 .update(cx, |editor, cx| editor.display_text(cx));
2957 assert!(
2958 results_text.is_empty(),
2959 "Empty search view should have no results but got '{results_text}'"
2960 );
2961 });
2962 })
2963 .unwrap();
2964
2965 window
2966 .update(cx, |_, window, cx| {
2967 search_view.update(cx, |search_view, cx| {
2968 search_view.query_editor.update(cx, |query_editor, cx| {
2969 query_editor.set_text("sOMETHINGtHATsURELYdOESnOTeXIST", window, cx)
2970 });
2971 search_view.search(cx);
2972 });
2973 })
2974 .unwrap();
2975
2976 cx.background_executor.run_until_parked();
2977 window
2978 .update(cx, |_, window, cx| {
2979 search_view.update(cx, |search_view, cx| {
2980 let results_text = search_view
2981 .results_editor
2982 .update(cx, |editor, cx| editor.display_text(cx));
2983 assert!(
2984 results_text.is_empty(),
2985 "Search view for mismatching query should have no results but got '{results_text}'"
2986 );
2987 assert!(
2988 search_view.query_editor.focus_handle(cx).is_focused(window),
2989 "Search view should be focused after mismatching query had been used in search",
2990 );
2991 });
2992 })
2993 .unwrap();
2994 cx.spawn(|mut cx| async move {
2995 window.update(&mut cx, |_, window, cx| {
2996 window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2997 })
2998 })
2999 .detach();
3000 cx.background_executor.run_until_parked();
3001 window.update(cx, |_, window, cx| {
3002 search_view.update(cx, |search_view, cx| {
3003 assert!(
3004 search_view.query_editor.focus_handle(cx).is_focused(window),
3005 "Search view with mismatching query should be focused after the toggle focus event: still no results panel to focus on",
3006 );
3007 });
3008 }).unwrap();
3009
3010 window
3011 .update(cx, |_, window, cx| {
3012 search_view.update(cx, |search_view, cx| {
3013 search_view.query_editor.update(cx, |query_editor, cx| {
3014 query_editor.set_text("TWO", window, cx)
3015 });
3016 search_view.search(cx);
3017 })
3018 })
3019 .unwrap();
3020 cx.background_executor.run_until_parked();
3021 window.update(cx, |_, window, cx|
3022 search_view.update(cx, |search_view, cx| {
3023 assert_eq!(
3024 search_view
3025 .results_editor
3026 .update(cx, |editor, cx| editor.display_text(cx)),
3027 "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
3028 "Search view results should match the query"
3029 );
3030 assert!(
3031 search_view.results_editor.focus_handle(cx).is_focused(window),
3032 "Search view with mismatching query should be focused after search results are available",
3033 );
3034 })).unwrap();
3035 cx.spawn(|mut cx| async move {
3036 window
3037 .update(&mut cx, |_, window, cx| {
3038 window.dispatch_action(ToggleFocus.boxed_clone(), cx)
3039 })
3040 .unwrap();
3041 })
3042 .detach();
3043 cx.background_executor.run_until_parked();
3044 window.update(cx, |_, window, cx| {
3045 search_view.update(cx, |search_view, cx| {
3046 assert!(
3047 search_view.results_editor.focus_handle(cx).is_focused(window),
3048 "Search view with matching query should still have its results editor focused after the toggle focus event",
3049 );
3050 });
3051 }).unwrap();
3052
3053 workspace
3054 .update(cx, |workspace, window, cx| {
3055 ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3056 })
3057 .unwrap();
3058 cx.background_executor.run_until_parked();
3059 let Some(search_view_2) = cx.read(|cx| {
3060 workspace
3061 .read(cx)
3062 .unwrap()
3063 .active_pane()
3064 .read(cx)
3065 .active_item()
3066 .and_then(|item| item.downcast::<ProjectSearchView>())
3067 }) else {
3068 panic!("Search view expected to appear after new search event trigger")
3069 };
3070 assert!(
3071 search_view_2 != search_view,
3072 "New search view should be open after `workspace::NewSearch` event"
3073 );
3074
3075 window.update(cx, |_, window, cx| {
3076 search_view.update(cx, |search_view, cx| {
3077 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO", "First search view should not have an updated query");
3078 assert_eq!(
3079 search_view
3080 .results_editor
3081 .update(cx, |editor, cx| editor.display_text(cx)),
3082 "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
3083 "Results of the first search view should not update too"
3084 );
3085 assert!(
3086 !search_view.query_editor.focus_handle(cx).is_focused(window),
3087 "Focus should be moved away from the first search view"
3088 );
3089 });
3090 }).unwrap();
3091
3092 window.update(cx, |_, window, cx| {
3093 search_view_2.update(cx, |search_view_2, cx| {
3094 assert_eq!(
3095 search_view_2.query_editor.read(cx).text(cx),
3096 "two",
3097 "New search view should get the query from the text cursor was at during the event spawn (first search view's first result)"
3098 );
3099 assert_eq!(
3100 search_view_2
3101 .results_editor
3102 .update(cx, |editor, cx| editor.display_text(cx)),
3103 "",
3104 "No search results should be in the 2nd view yet, as we did not spawn a search for it"
3105 );
3106 assert!(
3107 search_view_2.query_editor.focus_handle(cx).is_focused(window),
3108 "Focus should be moved into query editor of the new window"
3109 );
3110 });
3111 }).unwrap();
3112
3113 window
3114 .update(cx, |_, window, cx| {
3115 search_view_2.update(cx, |search_view_2, cx| {
3116 search_view_2.query_editor.update(cx, |query_editor, cx| {
3117 query_editor.set_text("FOUR", window, cx)
3118 });
3119 search_view_2.search(cx);
3120 });
3121 })
3122 .unwrap();
3123
3124 cx.background_executor.run_until_parked();
3125 window.update(cx, |_, window, cx| {
3126 search_view_2.update(cx, |search_view_2, cx| {
3127 assert_eq!(
3128 search_view_2
3129 .results_editor
3130 .update(cx, |editor, cx| editor.display_text(cx)),
3131 "\n\nconst FOUR: usize = one::ONE + three::THREE;",
3132 "New search view with the updated query should have new search results"
3133 );
3134 assert!(
3135 search_view_2.results_editor.focus_handle(cx).is_focused(window),
3136 "Search view with mismatching query should be focused after search results are available",
3137 );
3138 });
3139 }).unwrap();
3140
3141 cx.spawn(|mut cx| async move {
3142 window
3143 .update(&mut cx, |_, window, cx| {
3144 window.dispatch_action(ToggleFocus.boxed_clone(), cx)
3145 })
3146 .unwrap();
3147 })
3148 .detach();
3149 cx.background_executor.run_until_parked();
3150 window.update(cx, |_, window, cx| {
3151 search_view_2.update(cx, |search_view_2, cx| {
3152 assert!(
3153 search_view_2.results_editor.focus_handle(cx).is_focused(window),
3154 "Search view with matching query should switch focus to the results editor after the toggle focus event",
3155 );
3156 });}).unwrap();
3157 }
3158
3159 #[gpui::test]
3160 async fn test_new_project_search_in_directory(cx: &mut TestAppContext) {
3161 init_test(cx);
3162
3163 let fs = FakeFs::new(cx.background_executor.clone());
3164 fs.insert_tree(
3165 path!("/dir"),
3166 json!({
3167 "a": {
3168 "one.rs": "const ONE: usize = 1;",
3169 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
3170 },
3171 "b": {
3172 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
3173 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
3174 },
3175 }),
3176 )
3177 .await;
3178 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
3179 let worktree_id = project.read_with(cx, |project, cx| {
3180 project.worktrees(cx).next().unwrap().read(cx).id()
3181 });
3182 let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
3183 let workspace = window.root(cx).unwrap();
3184 let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
3185
3186 let active_item = cx.read(|cx| {
3187 workspace
3188 .read(cx)
3189 .active_pane()
3190 .read(cx)
3191 .active_item()
3192 .and_then(|item| item.downcast::<ProjectSearchView>())
3193 });
3194 assert!(
3195 active_item.is_none(),
3196 "Expected no search panel to be active"
3197 );
3198
3199 window
3200 .update(cx, move |workspace, window, cx| {
3201 assert_eq!(workspace.panes().len(), 1);
3202 workspace.panes()[0].update(cx, move |pane, cx| {
3203 pane.toolbar()
3204 .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3205 });
3206 })
3207 .unwrap();
3208
3209 let a_dir_entry = cx.update(|cx| {
3210 workspace
3211 .read(cx)
3212 .project()
3213 .read(cx)
3214 .entry_for_path(&(worktree_id, "a").into(), cx)
3215 .expect("no entry for /a/ directory")
3216 .clone()
3217 });
3218 assert!(a_dir_entry.is_dir());
3219 window
3220 .update(cx, |workspace, window, cx| {
3221 ProjectSearchView::new_search_in_directory(workspace, &a_dir_entry.path, window, cx)
3222 })
3223 .unwrap();
3224
3225 let Some(search_view) = cx.read(|cx| {
3226 workspace
3227 .read(cx)
3228 .active_pane()
3229 .read(cx)
3230 .active_item()
3231 .and_then(|item| item.downcast::<ProjectSearchView>())
3232 }) else {
3233 panic!("Search view expected to appear after new search in directory event trigger")
3234 };
3235 cx.background_executor.run_until_parked();
3236 window
3237 .update(cx, |_, window, cx| {
3238 search_view.update(cx, |search_view, cx| {
3239 assert!(
3240 search_view.query_editor.focus_handle(cx).is_focused(window),
3241 "On new search in directory, focus should be moved into query editor"
3242 );
3243 search_view.excluded_files_editor.update(cx, |editor, cx| {
3244 assert!(
3245 editor.display_text(cx).is_empty(),
3246 "New search in directory should not have any excluded files"
3247 );
3248 });
3249 search_view.included_files_editor.update(cx, |editor, cx| {
3250 assert_eq!(
3251 editor.display_text(cx),
3252 a_dir_entry.path.to_str().unwrap(),
3253 "New search in directory should have included dir entry path"
3254 );
3255 });
3256 });
3257 })
3258 .unwrap();
3259 window
3260 .update(cx, |_, window, cx| {
3261 search_view.update(cx, |search_view, cx| {
3262 search_view.query_editor.update(cx, |query_editor, cx| {
3263 query_editor.set_text("const", window, cx)
3264 });
3265 search_view.search(cx);
3266 });
3267 })
3268 .unwrap();
3269 cx.background_executor.run_until_parked();
3270 window
3271 .update(cx, |_, _, cx| {
3272 search_view.update(cx, |search_view, cx| {
3273 assert_eq!(
3274 search_view
3275 .results_editor
3276 .update(cx, |editor, cx| editor.display_text(cx)),
3277 "\n\nconst ONE: usize = 1;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
3278 "New search in directory should have a filter that matches a certain directory"
3279 );
3280 })
3281 })
3282 .unwrap();
3283 }
3284
3285 #[gpui::test]
3286 async fn test_search_query_history(cx: &mut TestAppContext) {
3287 init_test(cx);
3288
3289 let fs = FakeFs::new(cx.background_executor.clone());
3290 fs.insert_tree(
3291 path!("/dir"),
3292 json!({
3293 "one.rs": "const ONE: usize = 1;",
3294 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
3295 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
3296 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
3297 }),
3298 )
3299 .await;
3300 let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
3301 let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
3302 let workspace = window.root(cx).unwrap();
3303 let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
3304
3305 window
3306 .update(cx, {
3307 let search_bar = search_bar.clone();
3308 |workspace, window, cx| {
3309 assert_eq!(workspace.panes().len(), 1);
3310 workspace.panes()[0].update(cx, |pane, cx| {
3311 pane.toolbar()
3312 .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3313 });
3314
3315 ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3316 }
3317 })
3318 .unwrap();
3319
3320 let search_view = cx.read(|cx| {
3321 workspace
3322 .read(cx)
3323 .active_pane()
3324 .read(cx)
3325 .active_item()
3326 .and_then(|item| item.downcast::<ProjectSearchView>())
3327 .expect("Search view expected to appear after new search event trigger")
3328 });
3329
3330 // Add 3 search items into the history + another unsubmitted one.
3331 window
3332 .update(cx, |_, window, cx| {
3333 search_view.update(cx, |search_view, cx| {
3334 search_view.search_options = SearchOptions::CASE_SENSITIVE;
3335 search_view.query_editor.update(cx, |query_editor, cx| {
3336 query_editor.set_text("ONE", window, cx)
3337 });
3338 search_view.search(cx);
3339 });
3340 })
3341 .unwrap();
3342
3343 cx.background_executor.run_until_parked();
3344 window
3345 .update(cx, |_, window, cx| {
3346 search_view.update(cx, |search_view, cx| {
3347 search_view.query_editor.update(cx, |query_editor, cx| {
3348 query_editor.set_text("TWO", window, cx)
3349 });
3350 search_view.search(cx);
3351 });
3352 })
3353 .unwrap();
3354 cx.background_executor.run_until_parked();
3355 window
3356 .update(cx, |_, window, cx| {
3357 search_view.update(cx, |search_view, cx| {
3358 search_view.query_editor.update(cx, |query_editor, cx| {
3359 query_editor.set_text("THREE", window, cx)
3360 });
3361 search_view.search(cx);
3362 })
3363 })
3364 .unwrap();
3365 cx.background_executor.run_until_parked();
3366 window
3367 .update(cx, |_, window, cx| {
3368 search_view.update(cx, |search_view, cx| {
3369 search_view.query_editor.update(cx, |query_editor, cx| {
3370 query_editor.set_text("JUST_TEXT_INPUT", window, cx)
3371 });
3372 })
3373 })
3374 .unwrap();
3375 cx.background_executor.run_until_parked();
3376
3377 // Ensure that the latest input with search settings is active.
3378 window
3379 .update(cx, |_, _, cx| {
3380 search_view.update(cx, |search_view, cx| {
3381 assert_eq!(
3382 search_view.query_editor.read(cx).text(cx),
3383 "JUST_TEXT_INPUT"
3384 );
3385 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3386 });
3387 })
3388 .unwrap();
3389
3390 // Next history query after the latest should set the query to the empty string.
3391 window
3392 .update(cx, |_, window, cx| {
3393 search_bar.update(cx, |search_bar, cx| {
3394 search_bar.focus_search(window, cx);
3395 search_bar.next_history_query(&NextHistoryQuery, window, cx);
3396 })
3397 })
3398 .unwrap();
3399 window
3400 .update(cx, |_, _, cx| {
3401 search_view.update(cx, |search_view, cx| {
3402 assert_eq!(search_view.query_editor.read(cx).text(cx), "");
3403 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3404 });
3405 })
3406 .unwrap();
3407 window
3408 .update(cx, |_, window, cx| {
3409 search_bar.update(cx, |search_bar, cx| {
3410 search_bar.focus_search(window, cx);
3411 search_bar.next_history_query(&NextHistoryQuery, window, cx);
3412 })
3413 })
3414 .unwrap();
3415 window
3416 .update(cx, |_, _, cx| {
3417 search_view.update(cx, |search_view, cx| {
3418 assert_eq!(search_view.query_editor.read(cx).text(cx), "");
3419 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3420 });
3421 })
3422 .unwrap();
3423
3424 // First previous query for empty current query should set the query to the latest submitted one.
3425 window
3426 .update(cx, |_, window, cx| {
3427 search_bar.update(cx, |search_bar, cx| {
3428 search_bar.focus_search(window, cx);
3429 search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3430 });
3431 })
3432 .unwrap();
3433 window
3434 .update(cx, |_, _, cx| {
3435 search_view.update(cx, |search_view, cx| {
3436 assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
3437 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3438 });
3439 })
3440 .unwrap();
3441
3442 // Further previous items should go over the history in reverse order.
3443 window
3444 .update(cx, |_, window, cx| {
3445 search_bar.update(cx, |search_bar, cx| {
3446 search_bar.focus_search(window, cx);
3447 search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3448 });
3449 })
3450 .unwrap();
3451 window
3452 .update(cx, |_, _, cx| {
3453 search_view.update(cx, |search_view, cx| {
3454 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
3455 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3456 });
3457 })
3458 .unwrap();
3459
3460 // Previous items should never go behind the first history item.
3461 window
3462 .update(cx, |_, window, cx| {
3463 search_bar.update(cx, |search_bar, cx| {
3464 search_bar.focus_search(window, cx);
3465 search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3466 });
3467 })
3468 .unwrap();
3469 window
3470 .update(cx, |_, _, cx| {
3471 search_view.update(cx, |search_view, cx| {
3472 assert_eq!(search_view.query_editor.read(cx).text(cx), "ONE");
3473 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3474 });
3475 })
3476 .unwrap();
3477 window
3478 .update(cx, |_, window, cx| {
3479 search_bar.update(cx, |search_bar, cx| {
3480 search_bar.focus_search(window, cx);
3481 search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3482 });
3483 })
3484 .unwrap();
3485 window
3486 .update(cx, |_, _, cx| {
3487 search_view.update(cx, |search_view, cx| {
3488 assert_eq!(search_view.query_editor.read(cx).text(cx), "ONE");
3489 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3490 });
3491 })
3492 .unwrap();
3493
3494 // Next items should go over the history in the original order.
3495 window
3496 .update(cx, |_, window, cx| {
3497 search_bar.update(cx, |search_bar, cx| {
3498 search_bar.focus_search(window, cx);
3499 search_bar.next_history_query(&NextHistoryQuery, window, cx);
3500 });
3501 })
3502 .unwrap();
3503 window
3504 .update(cx, |_, _, cx| {
3505 search_view.update(cx, |search_view, cx| {
3506 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
3507 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3508 });
3509 })
3510 .unwrap();
3511
3512 window
3513 .update(cx, |_, window, cx| {
3514 search_view.update(cx, |search_view, cx| {
3515 search_view.query_editor.update(cx, |query_editor, cx| {
3516 query_editor.set_text("TWO_NEW", window, cx)
3517 });
3518 search_view.search(cx);
3519 });
3520 })
3521 .unwrap();
3522 cx.background_executor.run_until_parked();
3523 window
3524 .update(cx, |_, _, cx| {
3525 search_view.update(cx, |search_view, cx| {
3526 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO_NEW");
3527 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3528 });
3529 })
3530 .unwrap();
3531
3532 // New search input should add another entry to history and move the selection to the end of the history.
3533 window
3534 .update(cx, |_, window, cx| {
3535 search_bar.update(cx, |search_bar, cx| {
3536 search_bar.focus_search(window, cx);
3537 search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3538 });
3539 })
3540 .unwrap();
3541 window
3542 .update(cx, |_, _, cx| {
3543 search_view.update(cx, |search_view, cx| {
3544 assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
3545 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3546 });
3547 })
3548 .unwrap();
3549 window
3550 .update(cx, |_, window, cx| {
3551 search_bar.update(cx, |search_bar, cx| {
3552 search_bar.focus_search(window, cx);
3553 search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3554 });
3555 })
3556 .unwrap();
3557 window
3558 .update(cx, |_, _, cx| {
3559 search_view.update(cx, |search_view, cx| {
3560 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
3561 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3562 });
3563 })
3564 .unwrap();
3565 window
3566 .update(cx, |_, window, cx| {
3567 search_bar.update(cx, |search_bar, cx| {
3568 search_bar.focus_search(window, cx);
3569 search_bar.next_history_query(&NextHistoryQuery, window, cx);
3570 });
3571 })
3572 .unwrap();
3573 window
3574 .update(cx, |_, _, cx| {
3575 search_view.update(cx, |search_view, cx| {
3576 assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
3577 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3578 });
3579 })
3580 .unwrap();
3581 window
3582 .update(cx, |_, window, cx| {
3583 search_bar.update(cx, |search_bar, cx| {
3584 search_bar.focus_search(window, cx);
3585 search_bar.next_history_query(&NextHistoryQuery, window, cx);
3586 });
3587 })
3588 .unwrap();
3589 window
3590 .update(cx, |_, _, cx| {
3591 search_view.update(cx, |search_view, cx| {
3592 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO_NEW");
3593 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3594 });
3595 })
3596 .unwrap();
3597 window
3598 .update(cx, |_, window, cx| {
3599 search_bar.update(cx, |search_bar, cx| {
3600 search_bar.focus_search(window, cx);
3601 search_bar.next_history_query(&NextHistoryQuery, window, cx);
3602 });
3603 })
3604 .unwrap();
3605 window
3606 .update(cx, |_, _, cx| {
3607 search_view.update(cx, |search_view, cx| {
3608 assert_eq!(search_view.query_editor.read(cx).text(cx), "");
3609 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3610 });
3611 })
3612 .unwrap();
3613 }
3614
3615 #[gpui::test]
3616 async fn test_search_query_history_with_multiple_views(cx: &mut TestAppContext) {
3617 init_test(cx);
3618
3619 let fs = FakeFs::new(cx.background_executor.clone());
3620 fs.insert_tree(
3621 path!("/dir"),
3622 json!({
3623 "one.rs": "const ONE: usize = 1;",
3624 }),
3625 )
3626 .await;
3627 let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
3628 let worktree_id = project.update(cx, |this, cx| {
3629 this.worktrees(cx).next().unwrap().read(cx).id()
3630 });
3631
3632 let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
3633 let workspace = window.root(cx).unwrap();
3634
3635 let panes: Vec<_> = window
3636 .update(cx, |this, _, _| this.panes().to_owned())
3637 .unwrap();
3638
3639 let search_bar_1 = window.build_entity(cx, |_, _| ProjectSearchBar::new());
3640 let search_bar_2 = window.build_entity(cx, |_, _| ProjectSearchBar::new());
3641
3642 assert_eq!(panes.len(), 1);
3643 let first_pane = panes.first().cloned().unwrap();
3644 assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 0);
3645 window
3646 .update(cx, |workspace, window, cx| {
3647 workspace.open_path(
3648 (worktree_id, "one.rs"),
3649 Some(first_pane.downgrade()),
3650 true,
3651 window,
3652 cx,
3653 )
3654 })
3655 .unwrap()
3656 .await
3657 .unwrap();
3658 assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 1);
3659
3660 // Add a project search item to the first pane
3661 window
3662 .update(cx, {
3663 let search_bar = search_bar_1.clone();
3664 |workspace, window, cx| {
3665 first_pane.update(cx, |pane, cx| {
3666 pane.toolbar()
3667 .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3668 });
3669
3670 ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3671 }
3672 })
3673 .unwrap();
3674 let search_view_1 = cx.read(|cx| {
3675 workspace
3676 .read(cx)
3677 .active_item(cx)
3678 .and_then(|item| item.downcast::<ProjectSearchView>())
3679 .expect("Search view expected to appear after new search event trigger")
3680 });
3681
3682 let second_pane = window
3683 .update(cx, |workspace, window, cx| {
3684 workspace.split_and_clone(
3685 first_pane.clone(),
3686 workspace::SplitDirection::Right,
3687 window,
3688 cx,
3689 )
3690 })
3691 .unwrap()
3692 .unwrap();
3693 assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 1);
3694
3695 assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 1);
3696 assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 2);
3697
3698 // Add a project search item to the second pane
3699 window
3700 .update(cx, {
3701 let search_bar = search_bar_2.clone();
3702 let pane = second_pane.clone();
3703 move |workspace, window, cx| {
3704 assert_eq!(workspace.panes().len(), 2);
3705 pane.update(cx, |pane, cx| {
3706 pane.toolbar()
3707 .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3708 });
3709
3710 ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3711 }
3712 })
3713 .unwrap();
3714
3715 let search_view_2 = cx.read(|cx| {
3716 workspace
3717 .read(cx)
3718 .active_item(cx)
3719 .and_then(|item| item.downcast::<ProjectSearchView>())
3720 .expect("Search view expected to appear after new search event trigger")
3721 });
3722
3723 cx.run_until_parked();
3724 assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 2);
3725 assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 2);
3726
3727 let update_search_view =
3728 |search_view: &Entity<ProjectSearchView>, query: &str, cx: &mut TestAppContext| {
3729 window
3730 .update(cx, |_, window, cx| {
3731 search_view.update(cx, |search_view, cx| {
3732 search_view.query_editor.update(cx, |query_editor, cx| {
3733 query_editor.set_text(query, window, cx)
3734 });
3735 search_view.search(cx);
3736 });
3737 })
3738 .unwrap();
3739 };
3740
3741 let active_query =
3742 |search_view: &Entity<ProjectSearchView>, cx: &mut TestAppContext| -> String {
3743 window
3744 .update(cx, |_, _, cx| {
3745 search_view.update(cx, |search_view, cx| {
3746 search_view.query_editor.read(cx).text(cx)
3747 })
3748 })
3749 .unwrap()
3750 };
3751
3752 let select_prev_history_item =
3753 |search_bar: &Entity<ProjectSearchBar>, cx: &mut TestAppContext| {
3754 window
3755 .update(cx, |_, window, cx| {
3756 search_bar.update(cx, |search_bar, cx| {
3757 search_bar.focus_search(window, cx);
3758 search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3759 })
3760 })
3761 .unwrap();
3762 };
3763
3764 let select_next_history_item =
3765 |search_bar: &Entity<ProjectSearchBar>, cx: &mut TestAppContext| {
3766 window
3767 .update(cx, |_, window, cx| {
3768 search_bar.update(cx, |search_bar, cx| {
3769 search_bar.focus_search(window, cx);
3770 search_bar.next_history_query(&NextHistoryQuery, window, cx);
3771 })
3772 })
3773 .unwrap();
3774 };
3775
3776 update_search_view(&search_view_1, "ONE", cx);
3777 cx.background_executor.run_until_parked();
3778
3779 update_search_view(&search_view_2, "TWO", cx);
3780 cx.background_executor.run_until_parked();
3781
3782 assert_eq!(active_query(&search_view_1, cx), "ONE");
3783 assert_eq!(active_query(&search_view_2, cx), "TWO");
3784
3785 // Selecting previous history item should select the query from search view 1.
3786 select_prev_history_item(&search_bar_2, cx);
3787 assert_eq!(active_query(&search_view_2, cx), "ONE");
3788
3789 // Selecting the previous history item should not change the query as it is already the first item.
3790 select_prev_history_item(&search_bar_2, cx);
3791 assert_eq!(active_query(&search_view_2, cx), "ONE");
3792
3793 // Changing the query in search view 2 should not affect the history of search view 1.
3794 assert_eq!(active_query(&search_view_1, cx), "ONE");
3795
3796 // Deploying a new search in search view 2
3797 update_search_view(&search_view_2, "THREE", cx);
3798 cx.background_executor.run_until_parked();
3799
3800 select_next_history_item(&search_bar_2, cx);
3801 assert_eq!(active_query(&search_view_2, cx), "");
3802
3803 select_prev_history_item(&search_bar_2, cx);
3804 assert_eq!(active_query(&search_view_2, cx), "THREE");
3805
3806 select_prev_history_item(&search_bar_2, cx);
3807 assert_eq!(active_query(&search_view_2, cx), "TWO");
3808
3809 select_prev_history_item(&search_bar_2, cx);
3810 assert_eq!(active_query(&search_view_2, cx), "ONE");
3811
3812 select_prev_history_item(&search_bar_2, cx);
3813 assert_eq!(active_query(&search_view_2, cx), "ONE");
3814
3815 // Search view 1 should now see the query from search view 2.
3816 assert_eq!(active_query(&search_view_1, cx), "ONE");
3817
3818 select_next_history_item(&search_bar_2, cx);
3819 assert_eq!(active_query(&search_view_2, cx), "TWO");
3820
3821 // Here is the new query from search view 2
3822 select_next_history_item(&search_bar_2, cx);
3823 assert_eq!(active_query(&search_view_2, cx), "THREE");
3824
3825 select_next_history_item(&search_bar_2, cx);
3826 assert_eq!(active_query(&search_view_2, cx), "");
3827
3828 select_next_history_item(&search_bar_1, cx);
3829 assert_eq!(active_query(&search_view_1, cx), "TWO");
3830
3831 select_next_history_item(&search_bar_1, cx);
3832 assert_eq!(active_query(&search_view_1, cx), "THREE");
3833
3834 select_next_history_item(&search_bar_1, cx);
3835 assert_eq!(active_query(&search_view_1, cx), "");
3836 }
3837
3838 #[gpui::test]
3839 async fn test_deploy_search_with_multiple_panes(cx: &mut TestAppContext) {
3840 init_test(cx);
3841
3842 // Setup 2 panes, both with a file open and one with a project search.
3843 let fs = FakeFs::new(cx.background_executor.clone());
3844 fs.insert_tree(
3845 path!("/dir"),
3846 json!({
3847 "one.rs": "const ONE: usize = 1;",
3848 }),
3849 )
3850 .await;
3851 let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
3852 let worktree_id = project.update(cx, |this, cx| {
3853 this.worktrees(cx).next().unwrap().read(cx).id()
3854 });
3855 let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
3856 let panes: Vec<_> = window
3857 .update(cx, |this, _, _| this.panes().to_owned())
3858 .unwrap();
3859 assert_eq!(panes.len(), 1);
3860 let first_pane = panes.first().cloned().unwrap();
3861 assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 0);
3862 window
3863 .update(cx, |workspace, window, cx| {
3864 workspace.open_path(
3865 (worktree_id, "one.rs"),
3866 Some(first_pane.downgrade()),
3867 true,
3868 window,
3869 cx,
3870 )
3871 })
3872 .unwrap()
3873 .await
3874 .unwrap();
3875 assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 1);
3876 let second_pane = window
3877 .update(cx, |workspace, window, cx| {
3878 workspace.split_and_clone(
3879 first_pane.clone(),
3880 workspace::SplitDirection::Right,
3881 window,
3882 cx,
3883 )
3884 })
3885 .unwrap()
3886 .unwrap();
3887 assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 1);
3888 assert!(
3889 window
3890 .update(cx, |_, window, cx| second_pane
3891 .focus_handle(cx)
3892 .contains_focused(window, cx))
3893 .unwrap()
3894 );
3895 let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
3896 window
3897 .update(cx, {
3898 let search_bar = search_bar.clone();
3899 let pane = first_pane.clone();
3900 move |workspace, window, cx| {
3901 assert_eq!(workspace.panes().len(), 2);
3902 pane.update(cx, move |pane, cx| {
3903 pane.toolbar()
3904 .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3905 });
3906 }
3907 })
3908 .unwrap();
3909
3910 // Add a project search item to the second pane
3911 window
3912 .update(cx, {
3913 |workspace, window, cx| {
3914 assert_eq!(workspace.panes().len(), 2);
3915 second_pane.update(cx, |pane, cx| {
3916 pane.toolbar()
3917 .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3918 });
3919
3920 ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3921 }
3922 })
3923 .unwrap();
3924
3925 cx.run_until_parked();
3926 assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 2);
3927 assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 1);
3928
3929 // Focus the first pane
3930 window
3931 .update(cx, |workspace, window, cx| {
3932 assert_eq!(workspace.active_pane(), &second_pane);
3933 second_pane.update(cx, |this, cx| {
3934 assert_eq!(this.active_item_index(), 1);
3935 this.activate_previous_item(&Default::default(), window, cx);
3936 assert_eq!(this.active_item_index(), 0);
3937 });
3938 workspace.activate_pane_in_direction(workspace::SplitDirection::Left, window, cx);
3939 })
3940 .unwrap();
3941 window
3942 .update(cx, |workspace, _, cx| {
3943 assert_eq!(workspace.active_pane(), &first_pane);
3944 assert_eq!(first_pane.read(cx).items_len(), 1);
3945 assert_eq!(second_pane.read(cx).items_len(), 2);
3946 })
3947 .unwrap();
3948
3949 // Deploy a new search
3950 cx.dispatch_action(window.into(), DeploySearch::find());
3951
3952 // Both panes should now have a project search in them
3953 window
3954 .update(cx, |workspace, window, cx| {
3955 assert_eq!(workspace.active_pane(), &first_pane);
3956 first_pane.read_with(cx, |this, _| {
3957 assert_eq!(this.active_item_index(), 1);
3958 assert_eq!(this.items_len(), 2);
3959 });
3960 second_pane.update(cx, |this, cx| {
3961 assert!(!cx.focus_handle().contains_focused(window, cx));
3962 assert_eq!(this.items_len(), 2);
3963 });
3964 })
3965 .unwrap();
3966
3967 // Focus the second pane's non-search item
3968 window
3969 .update(cx, |_workspace, window, cx| {
3970 second_pane.update(cx, |pane, cx| {
3971 pane.activate_next_item(&Default::default(), window, cx)
3972 });
3973 })
3974 .unwrap();
3975
3976 // Deploy a new search
3977 cx.dispatch_action(window.into(), DeploySearch::find());
3978
3979 // The project search view should now be focused in the second pane
3980 // And the number of items should be unchanged.
3981 window
3982 .update(cx, |_workspace, _, cx| {
3983 second_pane.update(cx, |pane, _cx| {
3984 assert!(
3985 pane.active_item()
3986 .unwrap()
3987 .downcast::<ProjectSearchView>()
3988 .is_some()
3989 );
3990
3991 assert_eq!(pane.items_len(), 2);
3992 });
3993 })
3994 .unwrap();
3995 }
3996
3997 #[gpui::test]
3998 async fn test_scroll_search_results_to_top(cx: &mut TestAppContext) {
3999 init_test(cx);
4000
4001 // We need many lines in the search results to be able to scroll the window
4002 let fs = FakeFs::new(cx.background_executor.clone());
4003 fs.insert_tree(
4004 path!("/dir"),
4005 json!({
4006 "1.txt": "\n\n\n\n\n A \n\n\n\n\n",
4007 "2.txt": "\n\n\n\n\n A \n\n\n\n\n",
4008 "3.rs": "\n\n\n\n\n A \n\n\n\n\n",
4009 "4.rs": "\n\n\n\n\n A \n\n\n\n\n",
4010 "5.rs": "\n\n\n\n\n A \n\n\n\n\n",
4011 "6.rs": "\n\n\n\n\n A \n\n\n\n\n",
4012 "7.rs": "\n\n\n\n\n A \n\n\n\n\n",
4013 "8.rs": "\n\n\n\n\n A \n\n\n\n\n",
4014 "9.rs": "\n\n\n\n\n A \n\n\n\n\n",
4015 "a.rs": "\n\n\n\n\n A \n\n\n\n\n",
4016 "b.rs": "\n\n\n\n\n B \n\n\n\n\n",
4017 "c.rs": "\n\n\n\n\n B \n\n\n\n\n",
4018 "d.rs": "\n\n\n\n\n B \n\n\n\n\n",
4019 "e.rs": "\n\n\n\n\n B \n\n\n\n\n",
4020 "f.rs": "\n\n\n\n\n B \n\n\n\n\n",
4021 "g.rs": "\n\n\n\n\n B \n\n\n\n\n",
4022 "h.rs": "\n\n\n\n\n B \n\n\n\n\n",
4023 "i.rs": "\n\n\n\n\n B \n\n\n\n\n",
4024 "j.rs": "\n\n\n\n\n B \n\n\n\n\n",
4025 "k.rs": "\n\n\n\n\n B \n\n\n\n\n",
4026 }),
4027 )
4028 .await;
4029 let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
4030 let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
4031 let workspace = window.root(cx).unwrap();
4032 let search = cx.new(|cx| ProjectSearch::new(project, cx));
4033 let search_view = cx.add_window(|window, cx| {
4034 ProjectSearchView::new(workspace.downgrade(), search.clone(), window, cx, None)
4035 });
4036
4037 // First search
4038 perform_search(search_view, "A", cx);
4039 search_view
4040 .update(cx, |search_view, window, cx| {
4041 search_view.results_editor.update(cx, |results_editor, cx| {
4042 // Results are correct and scrolled to the top
4043 assert_eq!(
4044 results_editor.display_text(cx).match_indices(" A ").count(),
4045 10
4046 );
4047 assert_eq!(results_editor.scroll_position(cx), Point::default());
4048
4049 // Scroll results all the way down
4050 results_editor.scroll(
4051 Point::new(0., f32::MAX),
4052 Some(Axis::Vertical),
4053 window,
4054 cx,
4055 );
4056 });
4057 })
4058 .expect("unable to update search view");
4059
4060 // Second search
4061 perform_search(search_view, "B", cx);
4062 search_view
4063 .update(cx, |search_view, _, cx| {
4064 search_view.results_editor.update(cx, |results_editor, cx| {
4065 // Results are correct...
4066 assert_eq!(
4067 results_editor.display_text(cx).match_indices(" B ").count(),
4068 10
4069 );
4070 // ...and scrolled back to the top
4071 assert_eq!(results_editor.scroll_position(cx), Point::default());
4072 });
4073 })
4074 .expect("unable to update search view");
4075 }
4076
4077 #[gpui::test]
4078 async fn test_buffer_search_query_reused(cx: &mut TestAppContext) {
4079 init_test(cx);
4080
4081 let fs = FakeFs::new(cx.background_executor.clone());
4082 fs.insert_tree(
4083 path!("/dir"),
4084 json!({
4085 "one.rs": "const ONE: usize = 1;",
4086 }),
4087 )
4088 .await;
4089 let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
4090 let worktree_id = project.update(cx, |this, cx| {
4091 this.worktrees(cx).next().unwrap().read(cx).id()
4092 });
4093 let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
4094 let workspace = window.root(cx).unwrap();
4095 let mut cx = VisualTestContext::from_window(*window.deref(), cx);
4096
4097 let editor = workspace
4098 .update_in(&mut cx, |workspace, window, cx| {
4099 workspace.open_path((worktree_id, "one.rs"), None, true, window, cx)
4100 })
4101 .await
4102 .unwrap()
4103 .downcast::<Editor>()
4104 .unwrap();
4105
4106 // Wait for the unstaged changes to be loaded
4107 cx.run_until_parked();
4108
4109 let buffer_search_bar = cx.new_window_entity(|window, cx| {
4110 let mut search_bar =
4111 BufferSearchBar::new(Some(project.read(cx).languages().clone()), window, cx);
4112 search_bar.set_active_pane_item(Some(&editor), window, cx);
4113 search_bar.show(window, cx);
4114 search_bar
4115 });
4116
4117 let panes: Vec<_> = window
4118 .update(&mut cx, |this, _, _| this.panes().to_owned())
4119 .unwrap();
4120 assert_eq!(panes.len(), 1);
4121 let pane = panes.first().cloned().unwrap();
4122 pane.update_in(&mut cx, |pane, window, cx| {
4123 pane.toolbar().update(cx, |toolbar, cx| {
4124 toolbar.add_item(buffer_search_bar.clone(), window, cx);
4125 })
4126 });
4127
4128 let buffer_search_query = "search bar query";
4129 buffer_search_bar
4130 .update_in(&mut cx, |buffer_search_bar, window, cx| {
4131 buffer_search_bar.focus_handle(cx).focus(window);
4132 buffer_search_bar.search(buffer_search_query, None, true, window, cx)
4133 })
4134 .await
4135 .unwrap();
4136
4137 workspace.update_in(&mut cx, |workspace, window, cx| {
4138 ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
4139 });
4140 cx.run_until_parked();
4141 let project_search_view = pane
4142 .read_with(&cx, |pane, _| {
4143 pane.active_item()
4144 .and_then(|item| item.downcast::<ProjectSearchView>())
4145 })
4146 .expect("should open a project search view after spawning a new search");
4147 project_search_view.update(&mut cx, |search_view, cx| {
4148 assert_eq!(
4149 search_view.search_query_text(cx),
4150 buffer_search_query,
4151 "Project search should take the query from the buffer search bar since it got focused and had a query inside"
4152 );
4153 });
4154 }
4155
4156 fn init_test(cx: &mut TestAppContext) {
4157 cx.update(|cx| {
4158 let settings = SettingsStore::test(cx);
4159 cx.set_global(settings);
4160
4161 theme::init(theme::LoadThemes::JustBase, cx);
4162
4163 language::init(cx);
4164 client::init_settings(cx);
4165 editor::init(cx);
4166 workspace::init_settings(cx);
4167 Project::init_settings(cx);
4168 crate::init(cx);
4169 });
4170 }
4171
4172 fn perform_search(
4173 search_view: WindowHandle<ProjectSearchView>,
4174 text: impl Into<Arc<str>>,
4175 cx: &mut TestAppContext,
4176 ) {
4177 search_view
4178 .update(cx, |search_view, window, cx| {
4179 search_view.query_editor.update(cx, |query_editor, cx| {
4180 query_editor.set_text(text, window, cx)
4181 });
4182 search_view.search(cx);
4183 })
4184 .unwrap();
4185 // Ensure editor highlights appear after the search is done
4186 cx.executor().advance_clock(
4187 editor::SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT + Duration::from_millis(100),
4188 );
4189 cx.background_executor.run_until_parked();
4190 }
4191}