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