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