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