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