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 .min_w_64()
2013 .child(
2014 IconButton::new("project-search-filter-button", IconName::Filter)
2015 .shape(IconButtonShape::Square)
2016 .tooltip(|window, cx| {
2017 Tooltip::for_action("Toggle Filters", &ToggleFilters, window, cx)
2018 })
2019 .on_click(cx.listener(|this, _, window, cx| {
2020 this.toggle_filters(window, cx);
2021 }))
2022 .toggle_state(
2023 self.active_project_search
2024 .as_ref()
2025 .map(|search| search.read(cx).filters_enabled)
2026 .unwrap_or_default(),
2027 )
2028 .tooltip({
2029 let focus_handle = focus_handle.clone();
2030 move |window, cx| {
2031 Tooltip::for_action_in(
2032 "Toggle Filters",
2033 &ToggleFilters,
2034 &focus_handle,
2035 window,
2036 cx,
2037 )
2038 }
2039 }),
2040 )
2041 .child(toggle_replace_button(
2042 "project-search-toggle-replace",
2043 focus_handle.clone(),
2044 self.active_project_search
2045 .as_ref()
2046 .map(|search| search.read(cx).replace_enabled)
2047 .unwrap_or_default(),
2048 cx.listener(|this, _, window, cx| {
2049 this.toggle_replace(&ToggleReplace, window, cx);
2050 }),
2051 ));
2052
2053 let query_focus = search.query_editor.focus_handle(cx);
2054
2055 let matches_column = h_flex()
2056 .pl_2()
2057 .ml_2()
2058 .border_l_1()
2059 .border_color(cx.theme().colors().border_variant)
2060 .child(render_action_button(
2061 "project-search-nav-button",
2062 IconName::ChevronLeft,
2063 search.active_match_index.is_some(),
2064 "Select Previous Match",
2065 &SelectPreviousMatch,
2066 query_focus.clone(),
2067 ))
2068 .child(render_action_button(
2069 "project-search-nav-button",
2070 IconName::ChevronRight,
2071 search.active_match_index.is_some(),
2072 "Select Next Match",
2073 &SelectNextMatch,
2074 query_focus,
2075 ))
2076 .child(
2077 div()
2078 .id("matches")
2079 .ml_2()
2080 .min_w(rems_from_px(40.))
2081 .child(Label::new(match_text).size(LabelSize::Small).color(
2082 if search.active_match_index.is_some() {
2083 Color::Default
2084 } else {
2085 Color::Disabled
2086 },
2087 ))
2088 .when(limit_reached, |el| {
2089 el.tooltip(Tooltip::text(
2090 "Search limits reached.\nTry narrowing your search.",
2091 ))
2092 }),
2093 );
2094
2095 let search_line = h_flex()
2096 .w_full()
2097 .gap_2()
2098 .child(query_column)
2099 .child(h_flex().min_w_64().child(mode_column).child(matches_column));
2100
2101 let replace_line = search.replace_enabled.then(|| {
2102 let replace_column = input_base_styles(BaseStyle::SingleInput, InputPanel::Replacement)
2103 .child(render_text_input(&search.replacement_editor, None, cx));
2104
2105 let focus_handle = search.replacement_editor.read(cx).focus_handle(cx);
2106
2107 let replace_actions = h_flex()
2108 .min_w_64()
2109 .gap_1()
2110 .child(render_action_button(
2111 "project-search-replace-button",
2112 IconName::ReplaceNext,
2113 true,
2114 "Replace Next Match",
2115 &ReplaceNext,
2116 focus_handle.clone(),
2117 ))
2118 .child(render_action_button(
2119 "project-search-replace-button",
2120 IconName::ReplaceAll,
2121 true,
2122 "Replace All Matches",
2123 &ReplaceAll,
2124 focus_handle,
2125 ));
2126
2127 h_flex()
2128 .w_full()
2129 .gap_2()
2130 .child(replace_column)
2131 .child(replace_actions)
2132 });
2133
2134 let filter_line = search.filters_enabled.then(|| {
2135 let include = input_base_styles(BaseStyle::MultipleInputs, InputPanel::Include)
2136 .on_action(cx.listener(|this, action, window, cx| {
2137 this.previous_history_query(action, window, cx)
2138 }))
2139 .on_action(cx.listener(|this, action, window, cx| {
2140 this.next_history_query(action, window, cx)
2141 }))
2142 .child(render_text_input(&search.included_files_editor, None, cx));
2143 let exclude = input_base_styles(BaseStyle::MultipleInputs, InputPanel::Exclude)
2144 .on_action(cx.listener(|this, action, window, cx| {
2145 this.previous_history_query(action, window, cx)
2146 }))
2147 .on_action(cx.listener(|this, action, window, cx| {
2148 this.next_history_query(action, window, cx)
2149 }))
2150 .child(render_text_input(&search.excluded_files_editor, None, cx));
2151 let mode_column = h_flex()
2152 .gap_1()
2153 .min_w_64()
2154 .child(
2155 IconButton::new("project-search-opened-only", IconName::FolderSearch)
2156 .shape(IconButtonShape::Square)
2157 .toggle_state(self.is_opened_only_enabled(cx))
2158 .tooltip(Tooltip::text("Only Search Open Files"))
2159 .on_click(cx.listener(|this, _, window, cx| {
2160 this.toggle_opened_only(window, cx);
2161 })),
2162 )
2163 .child(
2164 SearchOptions::INCLUDE_IGNORED.as_button(
2165 search
2166 .search_options
2167 .contains(SearchOptions::INCLUDE_IGNORED),
2168 focus_handle.clone(),
2169 cx.listener(|this, _, window, cx| {
2170 this.toggle_search_option(SearchOptions::INCLUDE_IGNORED, window, cx);
2171 }),
2172 ),
2173 );
2174 h_flex()
2175 .w_full()
2176 .gap_2()
2177 .child(
2178 h_flex()
2179 .gap_2()
2180 .w(input_width)
2181 .child(include)
2182 .child(exclude),
2183 )
2184 .child(mode_column)
2185 });
2186
2187 let mut key_context = KeyContext::default();
2188 key_context.add("ProjectSearchBar");
2189 if search
2190 .replacement_editor
2191 .focus_handle(cx)
2192 .is_focused(window)
2193 {
2194 key_context.add("in_replace");
2195 }
2196
2197 let query_error_line = search.query_error.as_ref().map(|error| {
2198 Label::new(error)
2199 .size(LabelSize::Small)
2200 .color(Color::Error)
2201 .mt_neg_1()
2202 .ml_2()
2203 });
2204
2205 v_flex()
2206 .gap_2()
2207 .py(px(1.0))
2208 .w_full()
2209 .key_context(key_context)
2210 .on_action(cx.listener(|this, _: &ToggleFocus, window, cx| {
2211 this.move_focus_to_results(window, cx)
2212 }))
2213 .on_action(cx.listener(|this, _: &ToggleFilters, window, cx| {
2214 this.toggle_filters(window, cx);
2215 }))
2216 .capture_action(cx.listener(|this, action, window, cx| {
2217 this.tab(action, window, cx);
2218 cx.stop_propagation();
2219 }))
2220 .capture_action(cx.listener(|this, action, window, cx| {
2221 this.backtab(action, window, cx);
2222 cx.stop_propagation();
2223 }))
2224 .on_action(cx.listener(|this, action, window, cx| this.confirm(action, window, cx)))
2225 .on_action(cx.listener(|this, action, window, cx| {
2226 this.toggle_replace(action, window, cx);
2227 }))
2228 .on_action(cx.listener(|this, _: &ToggleWholeWord, window, cx| {
2229 this.toggle_search_option(SearchOptions::WHOLE_WORD, window, cx);
2230 }))
2231 .on_action(cx.listener(|this, _: &ToggleCaseSensitive, window, cx| {
2232 this.toggle_search_option(SearchOptions::CASE_SENSITIVE, window, cx);
2233 }))
2234 .on_action(cx.listener(|this, action, window, cx| {
2235 if let Some(search) = this.active_project_search.as_ref() {
2236 search.update(cx, |this, cx| {
2237 this.replace_next(action, window, cx);
2238 })
2239 }
2240 }))
2241 .on_action(cx.listener(|this, action, window, cx| {
2242 if let Some(search) = this.active_project_search.as_ref() {
2243 search.update(cx, |this, cx| {
2244 this.replace_all(action, window, cx);
2245 })
2246 }
2247 }))
2248 .when(search.filters_enabled, |this| {
2249 this.on_action(cx.listener(|this, _: &ToggleIncludeIgnored, window, cx| {
2250 this.toggle_search_option(SearchOptions::INCLUDE_IGNORED, window, cx);
2251 }))
2252 })
2253 .on_action(cx.listener(Self::select_next_match))
2254 .on_action(cx.listener(Self::select_prev_match))
2255 .child(search_line)
2256 .children(query_error_line)
2257 .children(replace_line)
2258 .children(filter_line)
2259 }
2260}
2261
2262impl EventEmitter<ToolbarItemEvent> for ProjectSearchBar {}
2263
2264impl ToolbarItemView for ProjectSearchBar {
2265 fn set_active_pane_item(
2266 &mut self,
2267 active_pane_item: Option<&dyn ItemHandle>,
2268 _: &mut Window,
2269 cx: &mut Context<Self>,
2270 ) -> ToolbarItemLocation {
2271 cx.notify();
2272 self.subscription = None;
2273 self.active_project_search = None;
2274 if let Some(search) = active_pane_item.and_then(|i| i.downcast::<ProjectSearchView>()) {
2275 self.subscription = Some(cx.observe(&search, |_, _, cx| cx.notify()));
2276 self.active_project_search = Some(search);
2277 ToolbarItemLocation::PrimaryLeft {}
2278 } else {
2279 ToolbarItemLocation::Hidden
2280 }
2281 }
2282}
2283
2284fn register_workspace_action<A: Action>(
2285 workspace: &mut Workspace,
2286 callback: fn(&mut ProjectSearchBar, &A, &mut Window, &mut Context<ProjectSearchBar>),
2287) {
2288 workspace.register_action(move |workspace, action: &A, window, cx| {
2289 if workspace.has_active_modal(window, cx) {
2290 cx.propagate();
2291 return;
2292 }
2293
2294 workspace.active_pane().update(cx, |pane, cx| {
2295 pane.toolbar().update(cx, move |workspace, cx| {
2296 if let Some(search_bar) = workspace.item_of_type::<ProjectSearchBar>() {
2297 search_bar.update(cx, move |search_bar, cx| {
2298 if search_bar.active_project_search.is_some() {
2299 callback(search_bar, action, window, cx);
2300 cx.notify();
2301 } else {
2302 cx.propagate();
2303 }
2304 });
2305 }
2306 });
2307 })
2308 });
2309}
2310
2311fn register_workspace_action_for_present_search<A: Action>(
2312 workspace: &mut Workspace,
2313 callback: fn(&mut Workspace, &A, &mut Window, &mut Context<Workspace>),
2314) {
2315 workspace.register_action(move |workspace, action: &A, window, cx| {
2316 if workspace.has_active_modal(window, cx) {
2317 cx.propagate();
2318 return;
2319 }
2320
2321 let should_notify = workspace
2322 .active_pane()
2323 .read(cx)
2324 .toolbar()
2325 .read(cx)
2326 .item_of_type::<ProjectSearchBar>()
2327 .map(|search_bar| search_bar.read(cx).active_project_search.is_some())
2328 .unwrap_or(false);
2329 if should_notify {
2330 callback(workspace, action, window, cx);
2331 cx.notify();
2332 } else {
2333 cx.propagate();
2334 }
2335 });
2336}
2337
2338#[cfg(any(test, feature = "test-support"))]
2339pub fn perform_project_search(
2340 search_view: &Entity<ProjectSearchView>,
2341 text: impl Into<std::sync::Arc<str>>,
2342 cx: &mut gpui::VisualTestContext,
2343) {
2344 cx.run_until_parked();
2345 search_view.update_in(cx, |search_view, window, cx| {
2346 search_view.query_editor.update(cx, |query_editor, cx| {
2347 query_editor.set_text(text, window, cx)
2348 });
2349 search_view.search(cx);
2350 });
2351 cx.run_until_parked();
2352}
2353
2354#[cfg(test)]
2355pub mod tests {
2356 use std::{ops::Deref as _, sync::Arc};
2357
2358 use super::*;
2359 use editor::{DisplayPoint, display_map::DisplayRow};
2360 use gpui::{Action, TestAppContext, VisualTestContext, WindowHandle};
2361 use project::FakeFs;
2362 use serde_json::json;
2363 use settings::SettingsStore;
2364 use util::path;
2365 use workspace::DeploySearch;
2366
2367 #[gpui::test]
2368 async fn test_project_search(cx: &mut TestAppContext) {
2369 init_test(cx);
2370
2371 let fs = FakeFs::new(cx.background_executor.clone());
2372 fs.insert_tree(
2373 path!("/dir"),
2374 json!({
2375 "one.rs": "const ONE: usize = 1;",
2376 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2377 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2378 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2379 }),
2380 )
2381 .await;
2382 let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
2383 let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
2384 let workspace = window.root(cx).unwrap();
2385 let search = cx.new(|cx| ProjectSearch::new(project.clone(), cx));
2386 let search_view = cx.add_window(|window, cx| {
2387 ProjectSearchView::new(workspace.downgrade(), search.clone(), window, cx, None)
2388 });
2389
2390 perform_search(search_view, "TWO", cx);
2391 search_view.update(cx, |search_view, window, cx| {
2392 assert_eq!(
2393 search_view
2394 .results_editor
2395 .update(cx, |editor, cx| editor.display_text(cx)),
2396 "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;"
2397 );
2398 let match_background_color = cx.theme().colors().search_match_background;
2399 assert_eq!(
2400 search_view
2401 .results_editor
2402 .update(cx, |editor, cx| editor.all_text_background_highlights(window, cx)),
2403 &[
2404 (
2405 DisplayPoint::new(DisplayRow(2), 32)..DisplayPoint::new(DisplayRow(2), 35),
2406 match_background_color
2407 ),
2408 (
2409 DisplayPoint::new(DisplayRow(2), 37)..DisplayPoint::new(DisplayRow(2), 40),
2410 match_background_color
2411 ),
2412 (
2413 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(5), 9),
2414 match_background_color
2415 )
2416 ]
2417 );
2418 assert_eq!(search_view.active_match_index, Some(0));
2419 assert_eq!(
2420 search_view
2421 .results_editor
2422 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2423 [DisplayPoint::new(DisplayRow(2), 32)..DisplayPoint::new(DisplayRow(2), 35)]
2424 );
2425
2426 search_view.select_match(Direction::Next, window, cx);
2427 }).unwrap();
2428
2429 search_view
2430 .update(cx, |search_view, window, cx| {
2431 assert_eq!(search_view.active_match_index, Some(1));
2432 assert_eq!(
2433 search_view
2434 .results_editor
2435 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2436 [DisplayPoint::new(DisplayRow(2), 37)..DisplayPoint::new(DisplayRow(2), 40)]
2437 );
2438 search_view.select_match(Direction::Next, window, cx);
2439 })
2440 .unwrap();
2441
2442 search_view
2443 .update(cx, |search_view, window, cx| {
2444 assert_eq!(search_view.active_match_index, Some(2));
2445 assert_eq!(
2446 search_view
2447 .results_editor
2448 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2449 [DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(5), 9)]
2450 );
2451 search_view.select_match(Direction::Next, window, cx);
2452 })
2453 .unwrap();
2454
2455 search_view
2456 .update(cx, |search_view, window, cx| {
2457 assert_eq!(search_view.active_match_index, Some(0));
2458 assert_eq!(
2459 search_view
2460 .results_editor
2461 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2462 [DisplayPoint::new(DisplayRow(2), 32)..DisplayPoint::new(DisplayRow(2), 35)]
2463 );
2464 search_view.select_match(Direction::Prev, window, cx);
2465 })
2466 .unwrap();
2467
2468 search_view
2469 .update(cx, |search_view, window, cx| {
2470 assert_eq!(search_view.active_match_index, Some(2));
2471 assert_eq!(
2472 search_view
2473 .results_editor
2474 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2475 [DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(5), 9)]
2476 );
2477 search_view.select_match(Direction::Prev, window, cx);
2478 })
2479 .unwrap();
2480
2481 search_view
2482 .update(cx, |search_view, _, cx| {
2483 assert_eq!(search_view.active_match_index, Some(1));
2484 assert_eq!(
2485 search_view
2486 .results_editor
2487 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2488 [DisplayPoint::new(DisplayRow(2), 37)..DisplayPoint::new(DisplayRow(2), 40)]
2489 );
2490 })
2491 .unwrap();
2492 }
2493
2494 #[gpui::test]
2495 async fn test_deploy_project_search_focus(cx: &mut TestAppContext) {
2496 init_test(cx);
2497
2498 let fs = FakeFs::new(cx.background_executor.clone());
2499 fs.insert_tree(
2500 "/dir",
2501 json!({
2502 "one.rs": "const ONE: usize = 1;",
2503 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2504 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2505 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2506 }),
2507 )
2508 .await;
2509 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
2510 let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
2511 let workspace = window;
2512 let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
2513
2514 let active_item = cx.read(|cx| {
2515 workspace
2516 .read(cx)
2517 .unwrap()
2518 .active_pane()
2519 .read(cx)
2520 .active_item()
2521 .and_then(|item| item.downcast::<ProjectSearchView>())
2522 });
2523 assert!(
2524 active_item.is_none(),
2525 "Expected no search panel to be active"
2526 );
2527
2528 window
2529 .update(cx, move |workspace, window, cx| {
2530 assert_eq!(workspace.panes().len(), 1);
2531 workspace.panes()[0].update(cx, |pane, cx| {
2532 pane.toolbar()
2533 .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
2534 });
2535
2536 ProjectSearchView::deploy_search(
2537 workspace,
2538 &workspace::DeploySearch::find(),
2539 window,
2540 cx,
2541 )
2542 })
2543 .unwrap();
2544
2545 let Some(search_view) = cx.read(|cx| {
2546 workspace
2547 .read(cx)
2548 .unwrap()
2549 .active_pane()
2550 .read(cx)
2551 .active_item()
2552 .and_then(|item| item.downcast::<ProjectSearchView>())
2553 }) else {
2554 panic!("Search view expected to appear after new search event trigger")
2555 };
2556
2557 cx.spawn(|mut cx| async move {
2558 window
2559 .update(&mut cx, |_, window, cx| {
2560 window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2561 })
2562 .unwrap();
2563 })
2564 .detach();
2565 cx.background_executor.run_until_parked();
2566 window
2567 .update(cx, |_, window, cx| {
2568 search_view.update(cx, |search_view, cx| {
2569 assert!(
2570 search_view.query_editor.focus_handle(cx).is_focused(window),
2571 "Empty search view should be focused after the toggle focus event: no results panel to focus on",
2572 );
2573 });
2574 }).unwrap();
2575
2576 window
2577 .update(cx, |_, window, cx| {
2578 search_view.update(cx, |search_view, cx| {
2579 let query_editor = &search_view.query_editor;
2580 assert!(
2581 query_editor.focus_handle(cx).is_focused(window),
2582 "Search view should be focused after the new search view is activated",
2583 );
2584 let query_text = query_editor.read(cx).text(cx);
2585 assert!(
2586 query_text.is_empty(),
2587 "New search query should be empty but got '{query_text}'",
2588 );
2589 let results_text = search_view
2590 .results_editor
2591 .update(cx, |editor, cx| editor.display_text(cx));
2592 assert!(
2593 results_text.is_empty(),
2594 "Empty search view should have no results but got '{results_text}'"
2595 );
2596 });
2597 })
2598 .unwrap();
2599
2600 window
2601 .update(cx, |_, window, cx| {
2602 search_view.update(cx, |search_view, cx| {
2603 search_view.query_editor.update(cx, |query_editor, cx| {
2604 query_editor.set_text("sOMETHINGtHATsURELYdOESnOTeXIST", window, cx)
2605 });
2606 search_view.search(cx);
2607 });
2608 })
2609 .unwrap();
2610 cx.background_executor.run_until_parked();
2611 window
2612 .update(cx, |_, window, cx| {
2613 search_view.update(cx, |search_view, cx| {
2614 let results_text = search_view
2615 .results_editor
2616 .update(cx, |editor, cx| editor.display_text(cx));
2617 assert!(
2618 results_text.is_empty(),
2619 "Search view for mismatching query should have no results but got '{results_text}'"
2620 );
2621 assert!(
2622 search_view.query_editor.focus_handle(cx).is_focused(window),
2623 "Search view should be focused after mismatching query had been used in search",
2624 );
2625 });
2626 }).unwrap();
2627
2628 cx.spawn(|mut cx| async move {
2629 window.update(&mut cx, |_, window, cx| {
2630 window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2631 })
2632 })
2633 .detach();
2634 cx.background_executor.run_until_parked();
2635 window.update(cx, |_, window, cx| {
2636 search_view.update(cx, |search_view, cx| {
2637 assert!(
2638 search_view.query_editor.focus_handle(cx).is_focused(window),
2639 "Search view with mismatching query should be focused after the toggle focus event: still no results panel to focus on",
2640 );
2641 });
2642 }).unwrap();
2643
2644 window
2645 .update(cx, |_, window, cx| {
2646 search_view.update(cx, |search_view, cx| {
2647 search_view.query_editor.update(cx, |query_editor, cx| {
2648 query_editor.set_text("TWO", window, cx)
2649 });
2650 search_view.search(cx);
2651 });
2652 })
2653 .unwrap();
2654 cx.background_executor.run_until_parked();
2655 window.update(cx, |_, window, cx| {
2656 search_view.update(cx, |search_view, cx| {
2657 assert_eq!(
2658 search_view
2659 .results_editor
2660 .update(cx, |editor, cx| editor.display_text(cx)),
2661 "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
2662 "Search view results should match the query"
2663 );
2664 assert!(
2665 search_view.results_editor.focus_handle(cx).is_focused(window),
2666 "Search view with mismatching query should be focused after search results are available",
2667 );
2668 });
2669 }).unwrap();
2670 cx.spawn(|mut cx| async move {
2671 window
2672 .update(&mut cx, |_, window, cx| {
2673 window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2674 })
2675 .unwrap();
2676 })
2677 .detach();
2678 cx.background_executor.run_until_parked();
2679 window.update(cx, |_, window, cx| {
2680 search_view.update(cx, |search_view, cx| {
2681 assert!(
2682 search_view.results_editor.focus_handle(cx).is_focused(window),
2683 "Search view with matching query should still have its results editor focused after the toggle focus event",
2684 );
2685 });
2686 }).unwrap();
2687
2688 workspace
2689 .update(cx, |workspace, window, cx| {
2690 ProjectSearchView::deploy_search(
2691 workspace,
2692 &workspace::DeploySearch::find(),
2693 window,
2694 cx,
2695 )
2696 })
2697 .unwrap();
2698 window.update(cx, |_, window, cx| {
2699 search_view.update(cx, |search_view, cx| {
2700 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");
2701 assert_eq!(
2702 search_view
2703 .results_editor
2704 .update(cx, |editor, cx| editor.display_text(cx)),
2705 "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
2706 "Results should be unchanged after search view 2nd open in a row"
2707 );
2708 assert!(
2709 search_view.query_editor.focus_handle(cx).is_focused(window),
2710 "Focus should be moved into query editor again after search view 2nd open in a row"
2711 );
2712 });
2713 }).unwrap();
2714
2715 cx.spawn(|mut cx| async move {
2716 window
2717 .update(&mut cx, |_, window, cx| {
2718 window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2719 })
2720 .unwrap();
2721 })
2722 .detach();
2723 cx.background_executor.run_until_parked();
2724 window.update(cx, |_, window, cx| {
2725 search_view.update(cx, |search_view, cx| {
2726 assert!(
2727 search_view.results_editor.focus_handle(cx).is_focused(window),
2728 "Search view with matching query should switch focus to the results editor after the toggle focus event",
2729 );
2730 });
2731 }).unwrap();
2732 }
2733
2734 #[gpui::test]
2735 async fn test_filters_consider_toggle_state(cx: &mut TestAppContext) {
2736 init_test(cx);
2737
2738 let fs = FakeFs::new(cx.background_executor.clone());
2739 fs.insert_tree(
2740 "/dir",
2741 json!({
2742 "one.rs": "const ONE: usize = 1;",
2743 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2744 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2745 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2746 }),
2747 )
2748 .await;
2749 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
2750 let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
2751 let workspace = window;
2752 let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
2753
2754 window
2755 .update(cx, move |workspace, window, cx| {
2756 workspace.panes()[0].update(cx, |pane, cx| {
2757 pane.toolbar()
2758 .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
2759 });
2760
2761 ProjectSearchView::deploy_search(
2762 workspace,
2763 &workspace::DeploySearch::find(),
2764 window,
2765 cx,
2766 )
2767 })
2768 .unwrap();
2769
2770 let Some(search_view) = cx.read(|cx| {
2771 workspace
2772 .read(cx)
2773 .unwrap()
2774 .active_pane()
2775 .read(cx)
2776 .active_item()
2777 .and_then(|item| item.downcast::<ProjectSearchView>())
2778 }) else {
2779 panic!("Search view expected to appear after new search event trigger")
2780 };
2781
2782 cx.spawn(|mut cx| async move {
2783 window
2784 .update(&mut cx, |_, window, cx| {
2785 window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2786 })
2787 .unwrap();
2788 })
2789 .detach();
2790 cx.background_executor.run_until_parked();
2791
2792 window
2793 .update(cx, |_, window, cx| {
2794 search_view.update(cx, |search_view, cx| {
2795 search_view.query_editor.update(cx, |query_editor, cx| {
2796 query_editor.set_text("const FOUR", window, cx)
2797 });
2798 search_view.toggle_filters(cx);
2799 search_view
2800 .excluded_files_editor
2801 .update(cx, |exclude_editor, cx| {
2802 exclude_editor.set_text("four.rs", window, cx)
2803 });
2804 search_view.search(cx);
2805 });
2806 })
2807 .unwrap();
2808 cx.background_executor.run_until_parked();
2809 window
2810 .update(cx, |_, _, cx| {
2811 search_view.update(cx, |search_view, cx| {
2812 let results_text = search_view
2813 .results_editor
2814 .update(cx, |editor, cx| editor.display_text(cx));
2815 assert!(
2816 results_text.is_empty(),
2817 "Search view for query with the only match in an excluded file should have no results but got '{results_text}'"
2818 );
2819 });
2820 }).unwrap();
2821
2822 cx.spawn(|mut cx| async move {
2823 window.update(&mut cx, |_, window, cx| {
2824 window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2825 })
2826 })
2827 .detach();
2828 cx.background_executor.run_until_parked();
2829
2830 window
2831 .update(cx, |_, _, cx| {
2832 search_view.update(cx, |search_view, cx| {
2833 search_view.toggle_filters(cx);
2834 search_view.search(cx);
2835 });
2836 })
2837 .unwrap();
2838 cx.background_executor.run_until_parked();
2839 window
2840 .update(cx, |_, _, cx| {
2841 search_view.update(cx, |search_view, cx| {
2842 assert_eq!(
2843 search_view
2844 .results_editor
2845 .update(cx, |editor, cx| editor.display_text(cx)),
2846 "\n\nconst FOUR: usize = one::ONE + three::THREE;",
2847 "Search view results should contain the queried result in the previously excluded file with filters toggled off"
2848 );
2849 });
2850 })
2851 .unwrap();
2852 }
2853
2854 #[gpui::test]
2855 async fn test_new_project_search_focus(cx: &mut TestAppContext) {
2856 init_test(cx);
2857
2858 let fs = FakeFs::new(cx.background_executor.clone());
2859 fs.insert_tree(
2860 path!("/dir"),
2861 json!({
2862 "one.rs": "const ONE: usize = 1;",
2863 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2864 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2865 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2866 }),
2867 )
2868 .await;
2869 let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
2870 let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
2871 let workspace = window;
2872 let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
2873
2874 let active_item = cx.read(|cx| {
2875 workspace
2876 .read(cx)
2877 .unwrap()
2878 .active_pane()
2879 .read(cx)
2880 .active_item()
2881 .and_then(|item| item.downcast::<ProjectSearchView>())
2882 });
2883 assert!(
2884 active_item.is_none(),
2885 "Expected no search panel to be active"
2886 );
2887
2888 window
2889 .update(cx, move |workspace, window, cx| {
2890 assert_eq!(workspace.panes().len(), 1);
2891 workspace.panes()[0].update(cx, |pane, cx| {
2892 pane.toolbar()
2893 .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
2894 });
2895
2896 ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
2897 })
2898 .unwrap();
2899
2900 let Some(search_view) = cx.read(|cx| {
2901 workspace
2902 .read(cx)
2903 .unwrap()
2904 .active_pane()
2905 .read(cx)
2906 .active_item()
2907 .and_then(|item| item.downcast::<ProjectSearchView>())
2908 }) else {
2909 panic!("Search view expected to appear after new search event trigger")
2910 };
2911
2912 cx.spawn(|mut cx| async move {
2913 window
2914 .update(&mut cx, |_, window, cx| {
2915 window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2916 })
2917 .unwrap();
2918 })
2919 .detach();
2920 cx.background_executor.run_until_parked();
2921
2922 window.update(cx, |_, window, cx| {
2923 search_view.update(cx, |search_view, cx| {
2924 assert!(
2925 search_view.query_editor.focus_handle(cx).is_focused(window),
2926 "Empty search view should be focused after the toggle focus event: no results panel to focus on",
2927 );
2928 });
2929 }).unwrap();
2930
2931 window
2932 .update(cx, |_, window, cx| {
2933 search_view.update(cx, |search_view, cx| {
2934 let query_editor = &search_view.query_editor;
2935 assert!(
2936 query_editor.focus_handle(cx).is_focused(window),
2937 "Search view should be focused after the new search view is activated",
2938 );
2939 let query_text = query_editor.read(cx).text(cx);
2940 assert!(
2941 query_text.is_empty(),
2942 "New search query should be empty but got '{query_text}'",
2943 );
2944 let results_text = search_view
2945 .results_editor
2946 .update(cx, |editor, cx| editor.display_text(cx));
2947 assert!(
2948 results_text.is_empty(),
2949 "Empty search view should have no results but got '{results_text}'"
2950 );
2951 });
2952 })
2953 .unwrap();
2954
2955 window
2956 .update(cx, |_, window, cx| {
2957 search_view.update(cx, |search_view, cx| {
2958 search_view.query_editor.update(cx, |query_editor, cx| {
2959 query_editor.set_text("sOMETHINGtHATsURELYdOESnOTeXIST", window, cx)
2960 });
2961 search_view.search(cx);
2962 });
2963 })
2964 .unwrap();
2965
2966 cx.background_executor.run_until_parked();
2967 window
2968 .update(cx, |_, window, cx| {
2969 search_view.update(cx, |search_view, cx| {
2970 let results_text = search_view
2971 .results_editor
2972 .update(cx, |editor, cx| editor.display_text(cx));
2973 assert!(
2974 results_text.is_empty(),
2975 "Search view for mismatching query should have no results but got '{results_text}'"
2976 );
2977 assert!(
2978 search_view.query_editor.focus_handle(cx).is_focused(window),
2979 "Search view should be focused after mismatching query had been used in search",
2980 );
2981 });
2982 })
2983 .unwrap();
2984 cx.spawn(|mut cx| async move {
2985 window.update(&mut cx, |_, window, cx| {
2986 window.dispatch_action(ToggleFocus.boxed_clone(), cx)
2987 })
2988 })
2989 .detach();
2990 cx.background_executor.run_until_parked();
2991 window.update(cx, |_, window, cx| {
2992 search_view.update(cx, |search_view, cx| {
2993 assert!(
2994 search_view.query_editor.focus_handle(cx).is_focused(window),
2995 "Search view with mismatching query should be focused after the toggle focus event: still no results panel to focus on",
2996 );
2997 });
2998 }).unwrap();
2999
3000 window
3001 .update(cx, |_, window, cx| {
3002 search_view.update(cx, |search_view, cx| {
3003 search_view.query_editor.update(cx, |query_editor, cx| {
3004 query_editor.set_text("TWO", window, cx)
3005 });
3006 search_view.search(cx);
3007 })
3008 })
3009 .unwrap();
3010 cx.background_executor.run_until_parked();
3011 window.update(cx, |_, window, cx|
3012 search_view.update(cx, |search_view, cx| {
3013 assert_eq!(
3014 search_view
3015 .results_editor
3016 .update(cx, |editor, cx| editor.display_text(cx)),
3017 "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
3018 "Search view results should match the query"
3019 );
3020 assert!(
3021 search_view.results_editor.focus_handle(cx).is_focused(window),
3022 "Search view with mismatching query should be focused after search results are available",
3023 );
3024 })).unwrap();
3025 cx.spawn(|mut cx| async move {
3026 window
3027 .update(&mut cx, |_, window, cx| {
3028 window.dispatch_action(ToggleFocus.boxed_clone(), cx)
3029 })
3030 .unwrap();
3031 })
3032 .detach();
3033 cx.background_executor.run_until_parked();
3034 window.update(cx, |_, window, cx| {
3035 search_view.update(cx, |search_view, cx| {
3036 assert!(
3037 search_view.results_editor.focus_handle(cx).is_focused(window),
3038 "Search view with matching query should still have its results editor focused after the toggle focus event",
3039 );
3040 });
3041 }).unwrap();
3042
3043 workspace
3044 .update(cx, |workspace, window, cx| {
3045 ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3046 })
3047 .unwrap();
3048 cx.background_executor.run_until_parked();
3049 let Some(search_view_2) = cx.read(|cx| {
3050 workspace
3051 .read(cx)
3052 .unwrap()
3053 .active_pane()
3054 .read(cx)
3055 .active_item()
3056 .and_then(|item| item.downcast::<ProjectSearchView>())
3057 }) else {
3058 panic!("Search view expected to appear after new search event trigger")
3059 };
3060 assert!(
3061 search_view_2 != search_view,
3062 "New search view should be open after `workspace::NewSearch` event"
3063 );
3064
3065 window.update(cx, |_, window, cx| {
3066 search_view.update(cx, |search_view, cx| {
3067 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO", "First search view should not have an updated query");
3068 assert_eq!(
3069 search_view
3070 .results_editor
3071 .update(cx, |editor, cx| editor.display_text(cx)),
3072 "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
3073 "Results of the first search view should not update too"
3074 );
3075 assert!(
3076 !search_view.query_editor.focus_handle(cx).is_focused(window),
3077 "Focus should be moved away from the first search view"
3078 );
3079 });
3080 }).unwrap();
3081
3082 window.update(cx, |_, window, cx| {
3083 search_view_2.update(cx, |search_view_2, cx| {
3084 assert_eq!(
3085 search_view_2.query_editor.read(cx).text(cx),
3086 "two",
3087 "New search view should get the query from the text cursor was at during the event spawn (first search view's first result)"
3088 );
3089 assert_eq!(
3090 search_view_2
3091 .results_editor
3092 .update(cx, |editor, cx| editor.display_text(cx)),
3093 "",
3094 "No search results should be in the 2nd view yet, as we did not spawn a search for it"
3095 );
3096 assert!(
3097 search_view_2.query_editor.focus_handle(cx).is_focused(window),
3098 "Focus should be moved into query editor of the new window"
3099 );
3100 });
3101 }).unwrap();
3102
3103 window
3104 .update(cx, |_, window, cx| {
3105 search_view_2.update(cx, |search_view_2, cx| {
3106 search_view_2.query_editor.update(cx, |query_editor, cx| {
3107 query_editor.set_text("FOUR", window, cx)
3108 });
3109 search_view_2.search(cx);
3110 });
3111 })
3112 .unwrap();
3113
3114 cx.background_executor.run_until_parked();
3115 window.update(cx, |_, window, cx| {
3116 search_view_2.update(cx, |search_view_2, cx| {
3117 assert_eq!(
3118 search_view_2
3119 .results_editor
3120 .update(cx, |editor, cx| editor.display_text(cx)),
3121 "\n\nconst FOUR: usize = one::ONE + three::THREE;",
3122 "New search view with the updated query should have new search results"
3123 );
3124 assert!(
3125 search_view_2.results_editor.focus_handle(cx).is_focused(window),
3126 "Search view with mismatching query should be focused after search results are available",
3127 );
3128 });
3129 }).unwrap();
3130
3131 cx.spawn(|mut cx| async move {
3132 window
3133 .update(&mut cx, |_, window, cx| {
3134 window.dispatch_action(ToggleFocus.boxed_clone(), cx)
3135 })
3136 .unwrap();
3137 })
3138 .detach();
3139 cx.background_executor.run_until_parked();
3140 window.update(cx, |_, window, cx| {
3141 search_view_2.update(cx, |search_view_2, cx| {
3142 assert!(
3143 search_view_2.results_editor.focus_handle(cx).is_focused(window),
3144 "Search view with matching query should switch focus to the results editor after the toggle focus event",
3145 );
3146 });}).unwrap();
3147 }
3148
3149 #[gpui::test]
3150 async fn test_new_project_search_in_directory(cx: &mut TestAppContext) {
3151 init_test(cx);
3152
3153 let fs = FakeFs::new(cx.background_executor.clone());
3154 fs.insert_tree(
3155 path!("/dir"),
3156 json!({
3157 "a": {
3158 "one.rs": "const ONE: usize = 1;",
3159 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
3160 },
3161 "b": {
3162 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
3163 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
3164 },
3165 }),
3166 )
3167 .await;
3168 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
3169 let worktree_id = project.read_with(cx, |project, cx| {
3170 project.worktrees(cx).next().unwrap().read(cx).id()
3171 });
3172 let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
3173 let workspace = window.root(cx).unwrap();
3174 let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
3175
3176 let active_item = cx.read(|cx| {
3177 workspace
3178 .read(cx)
3179 .active_pane()
3180 .read(cx)
3181 .active_item()
3182 .and_then(|item| item.downcast::<ProjectSearchView>())
3183 });
3184 assert!(
3185 active_item.is_none(),
3186 "Expected no search panel to be active"
3187 );
3188
3189 window
3190 .update(cx, move |workspace, window, cx| {
3191 assert_eq!(workspace.panes().len(), 1);
3192 workspace.panes()[0].update(cx, move |pane, cx| {
3193 pane.toolbar()
3194 .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3195 });
3196 })
3197 .unwrap();
3198
3199 let a_dir_entry = cx.update(|cx| {
3200 workspace
3201 .read(cx)
3202 .project()
3203 .read(cx)
3204 .entry_for_path(&(worktree_id, "a").into(), cx)
3205 .expect("no entry for /a/ directory")
3206 });
3207 assert!(a_dir_entry.is_dir());
3208 window
3209 .update(cx, |workspace, window, cx| {
3210 ProjectSearchView::new_search_in_directory(workspace, &a_dir_entry.path, window, cx)
3211 })
3212 .unwrap();
3213
3214 let Some(search_view) = cx.read(|cx| {
3215 workspace
3216 .read(cx)
3217 .active_pane()
3218 .read(cx)
3219 .active_item()
3220 .and_then(|item| item.downcast::<ProjectSearchView>())
3221 }) else {
3222 panic!("Search view expected to appear after new search in directory event trigger")
3223 };
3224 cx.background_executor.run_until_parked();
3225 window
3226 .update(cx, |_, window, cx| {
3227 search_view.update(cx, |search_view, cx| {
3228 assert!(
3229 search_view.query_editor.focus_handle(cx).is_focused(window),
3230 "On new search in directory, focus should be moved into query editor"
3231 );
3232 search_view.excluded_files_editor.update(cx, |editor, cx| {
3233 assert!(
3234 editor.display_text(cx).is_empty(),
3235 "New search in directory should not have any excluded files"
3236 );
3237 });
3238 search_view.included_files_editor.update(cx, |editor, cx| {
3239 assert_eq!(
3240 editor.display_text(cx),
3241 a_dir_entry.path.to_str().unwrap(),
3242 "New search in directory should have included dir entry path"
3243 );
3244 });
3245 });
3246 })
3247 .unwrap();
3248 window
3249 .update(cx, |_, window, cx| {
3250 search_view.update(cx, |search_view, cx| {
3251 search_view.query_editor.update(cx, |query_editor, cx| {
3252 query_editor.set_text("const", window, cx)
3253 });
3254 search_view.search(cx);
3255 });
3256 })
3257 .unwrap();
3258 cx.background_executor.run_until_parked();
3259 window
3260 .update(cx, |_, _, cx| {
3261 search_view.update(cx, |search_view, cx| {
3262 assert_eq!(
3263 search_view
3264 .results_editor
3265 .update(cx, |editor, cx| editor.display_text(cx)),
3266 "\n\nconst ONE: usize = 1;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
3267 "New search in directory should have a filter that matches a certain directory"
3268 );
3269 })
3270 })
3271 .unwrap();
3272 }
3273
3274 #[gpui::test]
3275 async fn test_search_query_history(cx: &mut TestAppContext) {
3276 init_test(cx);
3277
3278 let fs = FakeFs::new(cx.background_executor.clone());
3279 fs.insert_tree(
3280 path!("/dir"),
3281 json!({
3282 "one.rs": "const ONE: usize = 1;",
3283 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
3284 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
3285 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
3286 }),
3287 )
3288 .await;
3289 let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
3290 let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
3291 let workspace = window.root(cx).unwrap();
3292 let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
3293
3294 window
3295 .update(cx, {
3296 let search_bar = search_bar.clone();
3297 |workspace, window, cx| {
3298 assert_eq!(workspace.panes().len(), 1);
3299 workspace.panes()[0].update(cx, |pane, cx| {
3300 pane.toolbar()
3301 .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3302 });
3303
3304 ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3305 }
3306 })
3307 .unwrap();
3308
3309 let search_view = cx.read(|cx| {
3310 workspace
3311 .read(cx)
3312 .active_pane()
3313 .read(cx)
3314 .active_item()
3315 .and_then(|item| item.downcast::<ProjectSearchView>())
3316 .expect("Search view expected to appear after new search event trigger")
3317 });
3318
3319 // Add 3 search items into the history + another unsubmitted one.
3320 window
3321 .update(cx, |_, window, cx| {
3322 search_view.update(cx, |search_view, cx| {
3323 search_view.search_options = SearchOptions::CASE_SENSITIVE;
3324 search_view.query_editor.update(cx, |query_editor, cx| {
3325 query_editor.set_text("ONE", window, cx)
3326 });
3327 search_view.search(cx);
3328 });
3329 })
3330 .unwrap();
3331
3332 cx.background_executor.run_until_parked();
3333 window
3334 .update(cx, |_, window, cx| {
3335 search_view.update(cx, |search_view, cx| {
3336 search_view.query_editor.update(cx, |query_editor, cx| {
3337 query_editor.set_text("TWO", window, cx)
3338 });
3339 search_view.search(cx);
3340 });
3341 })
3342 .unwrap();
3343 cx.background_executor.run_until_parked();
3344 window
3345 .update(cx, |_, window, cx| {
3346 search_view.update(cx, |search_view, cx| {
3347 search_view.query_editor.update(cx, |query_editor, cx| {
3348 query_editor.set_text("THREE", window, cx)
3349 });
3350 search_view.search(cx);
3351 })
3352 })
3353 .unwrap();
3354 cx.background_executor.run_until_parked();
3355 window
3356 .update(cx, |_, window, cx| {
3357 search_view.update(cx, |search_view, cx| {
3358 search_view.query_editor.update(cx, |query_editor, cx| {
3359 query_editor.set_text("JUST_TEXT_INPUT", window, cx)
3360 });
3361 })
3362 })
3363 .unwrap();
3364 cx.background_executor.run_until_parked();
3365
3366 // Ensure that the latest input with search settings is active.
3367 window
3368 .update(cx, |_, _, cx| {
3369 search_view.update(cx, |search_view, cx| {
3370 assert_eq!(
3371 search_view.query_editor.read(cx).text(cx),
3372 "JUST_TEXT_INPUT"
3373 );
3374 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3375 });
3376 })
3377 .unwrap();
3378
3379 // Next history query after the latest should set the query to the empty string.
3380 window
3381 .update(cx, |_, window, cx| {
3382 search_bar.update(cx, |search_bar, cx| {
3383 search_bar.focus_search(window, cx);
3384 search_bar.next_history_query(&NextHistoryQuery, window, cx);
3385 })
3386 })
3387 .unwrap();
3388 window
3389 .update(cx, |_, _, cx| {
3390 search_view.update(cx, |search_view, cx| {
3391 assert_eq!(search_view.query_editor.read(cx).text(cx), "");
3392 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3393 });
3394 })
3395 .unwrap();
3396 window
3397 .update(cx, |_, window, cx| {
3398 search_bar.update(cx, |search_bar, cx| {
3399 search_bar.focus_search(window, cx);
3400 search_bar.next_history_query(&NextHistoryQuery, window, cx);
3401 })
3402 })
3403 .unwrap();
3404 window
3405 .update(cx, |_, _, cx| {
3406 search_view.update(cx, |search_view, cx| {
3407 assert_eq!(search_view.query_editor.read(cx).text(cx), "");
3408 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3409 });
3410 })
3411 .unwrap();
3412
3413 // First previous query for empty current query should set the query to the latest submitted one.
3414 window
3415 .update(cx, |_, window, cx| {
3416 search_bar.update(cx, |search_bar, cx| {
3417 search_bar.focus_search(window, cx);
3418 search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3419 });
3420 })
3421 .unwrap();
3422 window
3423 .update(cx, |_, _, cx| {
3424 search_view.update(cx, |search_view, cx| {
3425 assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
3426 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3427 });
3428 })
3429 .unwrap();
3430
3431 // Further previous items should go over the history in reverse order.
3432 window
3433 .update(cx, |_, window, cx| {
3434 search_bar.update(cx, |search_bar, cx| {
3435 search_bar.focus_search(window, cx);
3436 search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3437 });
3438 })
3439 .unwrap();
3440 window
3441 .update(cx, |_, _, cx| {
3442 search_view.update(cx, |search_view, cx| {
3443 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
3444 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3445 });
3446 })
3447 .unwrap();
3448
3449 // Previous items should never go behind the first history item.
3450 window
3451 .update(cx, |_, window, cx| {
3452 search_bar.update(cx, |search_bar, cx| {
3453 search_bar.focus_search(window, cx);
3454 search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3455 });
3456 })
3457 .unwrap();
3458 window
3459 .update(cx, |_, _, cx| {
3460 search_view.update(cx, |search_view, cx| {
3461 assert_eq!(search_view.query_editor.read(cx).text(cx), "ONE");
3462 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3463 });
3464 })
3465 .unwrap();
3466 window
3467 .update(cx, |_, window, cx| {
3468 search_bar.update(cx, |search_bar, cx| {
3469 search_bar.focus_search(window, cx);
3470 search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3471 });
3472 })
3473 .unwrap();
3474 window
3475 .update(cx, |_, _, cx| {
3476 search_view.update(cx, |search_view, cx| {
3477 assert_eq!(search_view.query_editor.read(cx).text(cx), "ONE");
3478 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3479 });
3480 })
3481 .unwrap();
3482
3483 // Next items should go over the history in the original order.
3484 window
3485 .update(cx, |_, window, cx| {
3486 search_bar.update(cx, |search_bar, cx| {
3487 search_bar.focus_search(window, cx);
3488 search_bar.next_history_query(&NextHistoryQuery, window, cx);
3489 });
3490 })
3491 .unwrap();
3492 window
3493 .update(cx, |_, _, cx| {
3494 search_view.update(cx, |search_view, cx| {
3495 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
3496 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3497 });
3498 })
3499 .unwrap();
3500
3501 window
3502 .update(cx, |_, window, cx| {
3503 search_view.update(cx, |search_view, cx| {
3504 search_view.query_editor.update(cx, |query_editor, cx| {
3505 query_editor.set_text("TWO_NEW", window, cx)
3506 });
3507 search_view.search(cx);
3508 });
3509 })
3510 .unwrap();
3511 cx.background_executor.run_until_parked();
3512 window
3513 .update(cx, |_, _, cx| {
3514 search_view.update(cx, |search_view, cx| {
3515 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO_NEW");
3516 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3517 });
3518 })
3519 .unwrap();
3520
3521 // New search input should add another entry to history and move the selection to the end of the history.
3522 window
3523 .update(cx, |_, window, cx| {
3524 search_bar.update(cx, |search_bar, cx| {
3525 search_bar.focus_search(window, cx);
3526 search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3527 });
3528 })
3529 .unwrap();
3530 window
3531 .update(cx, |_, _, cx| {
3532 search_view.update(cx, |search_view, cx| {
3533 assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
3534 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3535 });
3536 })
3537 .unwrap();
3538 window
3539 .update(cx, |_, window, cx| {
3540 search_bar.update(cx, |search_bar, cx| {
3541 search_bar.focus_search(window, cx);
3542 search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3543 });
3544 })
3545 .unwrap();
3546 window
3547 .update(cx, |_, _, cx| {
3548 search_view.update(cx, |search_view, cx| {
3549 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
3550 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3551 });
3552 })
3553 .unwrap();
3554 window
3555 .update(cx, |_, window, cx| {
3556 search_bar.update(cx, |search_bar, cx| {
3557 search_bar.focus_search(window, cx);
3558 search_bar.next_history_query(&NextHistoryQuery, window, cx);
3559 });
3560 })
3561 .unwrap();
3562 window
3563 .update(cx, |_, _, cx| {
3564 search_view.update(cx, |search_view, cx| {
3565 assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
3566 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3567 });
3568 })
3569 .unwrap();
3570 window
3571 .update(cx, |_, window, cx| {
3572 search_bar.update(cx, |search_bar, cx| {
3573 search_bar.focus_search(window, cx);
3574 search_bar.next_history_query(&NextHistoryQuery, window, cx);
3575 });
3576 })
3577 .unwrap();
3578 window
3579 .update(cx, |_, _, cx| {
3580 search_view.update(cx, |search_view, cx| {
3581 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO_NEW");
3582 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3583 });
3584 })
3585 .unwrap();
3586 window
3587 .update(cx, |_, window, cx| {
3588 search_bar.update(cx, |search_bar, cx| {
3589 search_bar.focus_search(window, cx);
3590 search_bar.next_history_query(&NextHistoryQuery, window, cx);
3591 });
3592 })
3593 .unwrap();
3594 window
3595 .update(cx, |_, _, cx| {
3596 search_view.update(cx, |search_view, cx| {
3597 assert_eq!(search_view.query_editor.read(cx).text(cx), "");
3598 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3599 });
3600 })
3601 .unwrap();
3602 }
3603
3604 #[gpui::test]
3605 async fn test_search_query_history_with_multiple_views(cx: &mut TestAppContext) {
3606 init_test(cx);
3607
3608 let fs = FakeFs::new(cx.background_executor.clone());
3609 fs.insert_tree(
3610 path!("/dir"),
3611 json!({
3612 "one.rs": "const ONE: usize = 1;",
3613 }),
3614 )
3615 .await;
3616 let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
3617 let worktree_id = project.update(cx, |this, cx| {
3618 this.worktrees(cx).next().unwrap().read(cx).id()
3619 });
3620
3621 let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
3622 let workspace = window.root(cx).unwrap();
3623
3624 let panes: Vec<_> = window
3625 .update(cx, |this, _, _| this.panes().to_owned())
3626 .unwrap();
3627
3628 let search_bar_1 = window.build_entity(cx, |_, _| ProjectSearchBar::new());
3629 let search_bar_2 = window.build_entity(cx, |_, _| ProjectSearchBar::new());
3630
3631 assert_eq!(panes.len(), 1);
3632 let first_pane = panes.first().cloned().unwrap();
3633 assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 0);
3634 window
3635 .update(cx, |workspace, window, cx| {
3636 workspace.open_path(
3637 (worktree_id, "one.rs"),
3638 Some(first_pane.downgrade()),
3639 true,
3640 window,
3641 cx,
3642 )
3643 })
3644 .unwrap()
3645 .await
3646 .unwrap();
3647 assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 1);
3648
3649 // Add a project search item to the first pane
3650 window
3651 .update(cx, {
3652 let search_bar = search_bar_1.clone();
3653 |workspace, window, cx| {
3654 first_pane.update(cx, |pane, cx| {
3655 pane.toolbar()
3656 .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3657 });
3658
3659 ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3660 }
3661 })
3662 .unwrap();
3663 let search_view_1 = cx.read(|cx| {
3664 workspace
3665 .read(cx)
3666 .active_item(cx)
3667 .and_then(|item| item.downcast::<ProjectSearchView>())
3668 .expect("Search view expected to appear after new search event trigger")
3669 });
3670
3671 let second_pane = window
3672 .update(cx, |workspace, window, cx| {
3673 workspace.split_and_clone(
3674 first_pane.clone(),
3675 workspace::SplitDirection::Right,
3676 window,
3677 cx,
3678 )
3679 })
3680 .unwrap()
3681 .unwrap();
3682 assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 1);
3683
3684 assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 1);
3685 assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 2);
3686
3687 // Add a project search item to the second pane
3688 window
3689 .update(cx, {
3690 let search_bar = search_bar_2.clone();
3691 let pane = second_pane.clone();
3692 move |workspace, window, cx| {
3693 assert_eq!(workspace.panes().len(), 2);
3694 pane.update(cx, |pane, cx| {
3695 pane.toolbar()
3696 .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3697 });
3698
3699 ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3700 }
3701 })
3702 .unwrap();
3703
3704 let search_view_2 = cx.read(|cx| {
3705 workspace
3706 .read(cx)
3707 .active_item(cx)
3708 .and_then(|item| item.downcast::<ProjectSearchView>())
3709 .expect("Search view expected to appear after new search event trigger")
3710 });
3711
3712 cx.run_until_parked();
3713 assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 2);
3714 assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 2);
3715
3716 let update_search_view =
3717 |search_view: &Entity<ProjectSearchView>, query: &str, cx: &mut TestAppContext| {
3718 window
3719 .update(cx, |_, window, cx| {
3720 search_view.update(cx, |search_view, cx| {
3721 search_view.query_editor.update(cx, |query_editor, cx| {
3722 query_editor.set_text(query, window, cx)
3723 });
3724 search_view.search(cx);
3725 });
3726 })
3727 .unwrap();
3728 };
3729
3730 let active_query =
3731 |search_view: &Entity<ProjectSearchView>, cx: &mut TestAppContext| -> String {
3732 window
3733 .update(cx, |_, _, cx| {
3734 search_view.update(cx, |search_view, cx| {
3735 search_view.query_editor.read(cx).text(cx).to_string()
3736 })
3737 })
3738 .unwrap()
3739 };
3740
3741 let select_prev_history_item =
3742 |search_bar: &Entity<ProjectSearchBar>, cx: &mut TestAppContext| {
3743 window
3744 .update(cx, |_, window, cx| {
3745 search_bar.update(cx, |search_bar, cx| {
3746 search_bar.focus_search(window, cx);
3747 search_bar.previous_history_query(&PreviousHistoryQuery, window, cx);
3748 })
3749 })
3750 .unwrap();
3751 };
3752
3753 let select_next_history_item =
3754 |search_bar: &Entity<ProjectSearchBar>, cx: &mut TestAppContext| {
3755 window
3756 .update(cx, |_, window, cx| {
3757 search_bar.update(cx, |search_bar, cx| {
3758 search_bar.focus_search(window, cx);
3759 search_bar.next_history_query(&NextHistoryQuery, window, cx);
3760 })
3761 })
3762 .unwrap();
3763 };
3764
3765 update_search_view(&search_view_1, "ONE", cx);
3766 cx.background_executor.run_until_parked();
3767
3768 update_search_view(&search_view_2, "TWO", cx);
3769 cx.background_executor.run_until_parked();
3770
3771 assert_eq!(active_query(&search_view_1, cx), "ONE");
3772 assert_eq!(active_query(&search_view_2, cx), "TWO");
3773
3774 // Selecting previous history item should select the query from search view 1.
3775 select_prev_history_item(&search_bar_2, cx);
3776 assert_eq!(active_query(&search_view_2, cx), "ONE");
3777
3778 // Selecting the previous history item should not change the query as it is already the first item.
3779 select_prev_history_item(&search_bar_2, cx);
3780 assert_eq!(active_query(&search_view_2, cx), "ONE");
3781
3782 // Changing the query in search view 2 should not affect the history of search view 1.
3783 assert_eq!(active_query(&search_view_1, cx), "ONE");
3784
3785 // Deploying a new search in search view 2
3786 update_search_view(&search_view_2, "THREE", cx);
3787 cx.background_executor.run_until_parked();
3788
3789 select_next_history_item(&search_bar_2, cx);
3790 assert_eq!(active_query(&search_view_2, cx), "");
3791
3792 select_prev_history_item(&search_bar_2, cx);
3793 assert_eq!(active_query(&search_view_2, cx), "THREE");
3794
3795 select_prev_history_item(&search_bar_2, cx);
3796 assert_eq!(active_query(&search_view_2, cx), "TWO");
3797
3798 select_prev_history_item(&search_bar_2, cx);
3799 assert_eq!(active_query(&search_view_2, cx), "ONE");
3800
3801 select_prev_history_item(&search_bar_2, cx);
3802 assert_eq!(active_query(&search_view_2, cx), "ONE");
3803
3804 // Search view 1 should now see the query from search view 2.
3805 assert_eq!(active_query(&search_view_1, cx), "ONE");
3806
3807 select_next_history_item(&search_bar_2, cx);
3808 assert_eq!(active_query(&search_view_2, cx), "TWO");
3809
3810 // Here is the new query from search view 2
3811 select_next_history_item(&search_bar_2, cx);
3812 assert_eq!(active_query(&search_view_2, cx), "THREE");
3813
3814 select_next_history_item(&search_bar_2, cx);
3815 assert_eq!(active_query(&search_view_2, cx), "");
3816
3817 select_next_history_item(&search_bar_1, cx);
3818 assert_eq!(active_query(&search_view_1, cx), "TWO");
3819
3820 select_next_history_item(&search_bar_1, cx);
3821 assert_eq!(active_query(&search_view_1, cx), "THREE");
3822
3823 select_next_history_item(&search_bar_1, cx);
3824 assert_eq!(active_query(&search_view_1, cx), "");
3825 }
3826
3827 #[gpui::test]
3828 async fn test_deploy_search_with_multiple_panes(cx: &mut TestAppContext) {
3829 init_test(cx);
3830
3831 // Setup 2 panes, both with a file open and one with a project search.
3832 let fs = FakeFs::new(cx.background_executor.clone());
3833 fs.insert_tree(
3834 path!("/dir"),
3835 json!({
3836 "one.rs": "const ONE: usize = 1;",
3837 }),
3838 )
3839 .await;
3840 let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
3841 let worktree_id = project.update(cx, |this, cx| {
3842 this.worktrees(cx).next().unwrap().read(cx).id()
3843 });
3844 let window = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
3845 let panes: Vec<_> = window
3846 .update(cx, |this, _, _| this.panes().to_owned())
3847 .unwrap();
3848 assert_eq!(panes.len(), 1);
3849 let first_pane = panes.first().cloned().unwrap();
3850 assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 0);
3851 window
3852 .update(cx, |workspace, window, cx| {
3853 workspace.open_path(
3854 (worktree_id, "one.rs"),
3855 Some(first_pane.downgrade()),
3856 true,
3857 window,
3858 cx,
3859 )
3860 })
3861 .unwrap()
3862 .await
3863 .unwrap();
3864 assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 1);
3865 let second_pane = window
3866 .update(cx, |workspace, window, cx| {
3867 workspace.split_and_clone(
3868 first_pane.clone(),
3869 workspace::SplitDirection::Right,
3870 window,
3871 cx,
3872 )
3873 })
3874 .unwrap()
3875 .unwrap();
3876 assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 1);
3877 assert!(
3878 window
3879 .update(cx, |_, window, cx| second_pane
3880 .focus_handle(cx)
3881 .contains_focused(window, cx))
3882 .unwrap()
3883 );
3884 let search_bar = window.build_entity(cx, |_, _| ProjectSearchBar::new());
3885 window
3886 .update(cx, {
3887 let search_bar = search_bar.clone();
3888 let pane = first_pane.clone();
3889 move |workspace, window, cx| {
3890 assert_eq!(workspace.panes().len(), 2);
3891 pane.update(cx, move |pane, cx| {
3892 pane.toolbar()
3893 .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3894 });
3895 }
3896 })
3897 .unwrap();
3898
3899 // Add a project search item to the second pane
3900 window
3901 .update(cx, {
3902 let search_bar = search_bar.clone();
3903 |workspace, window, cx| {
3904 assert_eq!(workspace.panes().len(), 2);
3905 second_pane.update(cx, |pane, cx| {
3906 pane.toolbar()
3907 .update(cx, |toolbar, cx| toolbar.add_item(search_bar, window, cx))
3908 });
3909
3910 ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
3911 }
3912 })
3913 .unwrap();
3914
3915 cx.run_until_parked();
3916 assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 2);
3917 assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 1);
3918
3919 // Focus the first pane
3920 window
3921 .update(cx, |workspace, window, cx| {
3922 assert_eq!(workspace.active_pane(), &second_pane);
3923 second_pane.update(cx, |this, cx| {
3924 assert_eq!(this.active_item_index(), 1);
3925 this.activate_prev_item(false, window, cx);
3926 assert_eq!(this.active_item_index(), 0);
3927 });
3928 workspace.activate_pane_in_direction(workspace::SplitDirection::Left, window, cx);
3929 })
3930 .unwrap();
3931 window
3932 .update(cx, |workspace, _, cx| {
3933 assert_eq!(workspace.active_pane(), &first_pane);
3934 assert_eq!(first_pane.read(cx).items_len(), 1);
3935 assert_eq!(second_pane.read(cx).items_len(), 2);
3936 })
3937 .unwrap();
3938
3939 // Deploy a new search
3940 cx.dispatch_action(window.into(), DeploySearch::find());
3941
3942 // Both panes should now have a project search in them
3943 window
3944 .update(cx, |workspace, window, cx| {
3945 assert_eq!(workspace.active_pane(), &first_pane);
3946 first_pane.read_with(cx, |this, _| {
3947 assert_eq!(this.active_item_index(), 1);
3948 assert_eq!(this.items_len(), 2);
3949 });
3950 second_pane.update(cx, |this, cx| {
3951 assert!(!cx.focus_handle().contains_focused(window, cx));
3952 assert_eq!(this.items_len(), 2);
3953 });
3954 })
3955 .unwrap();
3956
3957 // Focus the second pane's non-search item
3958 window
3959 .update(cx, |_workspace, window, cx| {
3960 second_pane.update(cx, |pane, cx| pane.activate_next_item(true, window, cx));
3961 })
3962 .unwrap();
3963
3964 // Deploy a new search
3965 cx.dispatch_action(window.into(), DeploySearch::find());
3966
3967 // The project search view should now be focused in the second pane
3968 // And the number of items should be unchanged.
3969 window
3970 .update(cx, |_workspace, _, cx| {
3971 second_pane.update(cx, |pane, _cx| {
3972 assert!(
3973 pane.active_item()
3974 .unwrap()
3975 .downcast::<ProjectSearchView>()
3976 .is_some()
3977 );
3978
3979 assert_eq!(pane.items_len(), 2);
3980 });
3981 })
3982 .unwrap();
3983 }
3984
3985 #[gpui::test]
3986 async fn test_scroll_search_results_to_top(cx: &mut TestAppContext) {
3987 init_test(cx);
3988
3989 // We need many lines in the search results to be able to scroll the window
3990 let fs = FakeFs::new(cx.background_executor.clone());
3991 fs.insert_tree(
3992 path!("/dir"),
3993 json!({
3994 "1.txt": "\n\n\n\n\n A \n\n\n\n\n",
3995 "2.txt": "\n\n\n\n\n A \n\n\n\n\n",
3996 "3.rs": "\n\n\n\n\n A \n\n\n\n\n",
3997 "4.rs": "\n\n\n\n\n A \n\n\n\n\n",
3998 "5.rs": "\n\n\n\n\n A \n\n\n\n\n",
3999 "6.rs": "\n\n\n\n\n A \n\n\n\n\n",
4000 "7.rs": "\n\n\n\n\n A \n\n\n\n\n",
4001 "8.rs": "\n\n\n\n\n A \n\n\n\n\n",
4002 "9.rs": "\n\n\n\n\n A \n\n\n\n\n",
4003 "a.rs": "\n\n\n\n\n A \n\n\n\n\n",
4004 "b.rs": "\n\n\n\n\n B \n\n\n\n\n",
4005 "c.rs": "\n\n\n\n\n B \n\n\n\n\n",
4006 "d.rs": "\n\n\n\n\n B \n\n\n\n\n",
4007 "e.rs": "\n\n\n\n\n B \n\n\n\n\n",
4008 "f.rs": "\n\n\n\n\n B \n\n\n\n\n",
4009 "g.rs": "\n\n\n\n\n B \n\n\n\n\n",
4010 "h.rs": "\n\n\n\n\n B \n\n\n\n\n",
4011 "i.rs": "\n\n\n\n\n B \n\n\n\n\n",
4012 "j.rs": "\n\n\n\n\n B \n\n\n\n\n",
4013 "k.rs": "\n\n\n\n\n B \n\n\n\n\n",
4014 }),
4015 )
4016 .await;
4017 let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
4018 let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
4019 let workspace = window.root(cx).unwrap();
4020 let search = cx.new(|cx| ProjectSearch::new(project, cx));
4021 let search_view = cx.add_window(|window, cx| {
4022 ProjectSearchView::new(workspace.downgrade(), search.clone(), window, cx, None)
4023 });
4024
4025 // First search
4026 perform_search(search_view, "A", cx);
4027 search_view
4028 .update(cx, |search_view, window, cx| {
4029 search_view.results_editor.update(cx, |results_editor, cx| {
4030 // Results are correct and scrolled to the top
4031 assert_eq!(
4032 results_editor.display_text(cx).match_indices(" A ").count(),
4033 10
4034 );
4035 assert_eq!(results_editor.scroll_position(cx), Point::default());
4036
4037 // Scroll results all the way down
4038 results_editor.scroll(
4039 Point::new(0., f32::MAX),
4040 Some(Axis::Vertical),
4041 window,
4042 cx,
4043 );
4044 });
4045 })
4046 .expect("unable to update search view");
4047
4048 // Second search
4049 perform_search(search_view, "B", cx);
4050 search_view
4051 .update(cx, |search_view, _, cx| {
4052 search_view.results_editor.update(cx, |results_editor, cx| {
4053 // Results are correct...
4054 assert_eq!(
4055 results_editor.display_text(cx).match_indices(" B ").count(),
4056 10
4057 );
4058 // ...and scrolled back to the top
4059 assert_eq!(results_editor.scroll_position(cx), Point::default());
4060 });
4061 })
4062 .expect("unable to update search view");
4063 }
4064
4065 #[gpui::test]
4066 async fn test_buffer_search_query_reused(cx: &mut TestAppContext) {
4067 init_test(cx);
4068
4069 let fs = FakeFs::new(cx.background_executor.clone());
4070 fs.insert_tree(
4071 path!("/dir"),
4072 json!({
4073 "one.rs": "const ONE: usize = 1;",
4074 }),
4075 )
4076 .await;
4077 let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
4078 let worktree_id = project.update(cx, |this, cx| {
4079 this.worktrees(cx).next().unwrap().read(cx).id()
4080 });
4081 let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
4082 let workspace = window.root(cx).unwrap();
4083 let mut cx = VisualTestContext::from_window(*window.deref(), cx);
4084
4085 let editor = workspace
4086 .update_in(&mut cx, |workspace, window, cx| {
4087 workspace.open_path((worktree_id, "one.rs"), None, true, window, cx)
4088 })
4089 .await
4090 .unwrap()
4091 .downcast::<Editor>()
4092 .unwrap();
4093
4094 // Wait for the unstaged changes to be loaded
4095 cx.run_until_parked();
4096
4097 let buffer_search_bar = cx.new_window_entity(|window, cx| {
4098 let mut search_bar =
4099 BufferSearchBar::new(Some(project.read(cx).languages().clone()), window, cx);
4100 search_bar.set_active_pane_item(Some(&editor), window, cx);
4101 search_bar.show(window, cx);
4102 search_bar
4103 });
4104
4105 let panes: Vec<_> = window
4106 .update(&mut cx, |this, _, _| this.panes().to_owned())
4107 .unwrap();
4108 assert_eq!(panes.len(), 1);
4109 let pane = panes.first().cloned().unwrap();
4110 pane.update_in(&mut cx, |pane, window, cx| {
4111 pane.toolbar().update(cx, |toolbar, cx| {
4112 toolbar.add_item(buffer_search_bar.clone(), window, cx);
4113 })
4114 });
4115
4116 let buffer_search_query = "search bar query";
4117 buffer_search_bar
4118 .update_in(&mut cx, |buffer_search_bar, window, cx| {
4119 buffer_search_bar.focus_handle(cx).focus(window);
4120 buffer_search_bar.search(buffer_search_query, None, window, cx)
4121 })
4122 .await
4123 .unwrap();
4124
4125 workspace.update_in(&mut cx, |workspace, window, cx| {
4126 ProjectSearchView::new_search(workspace, &workspace::NewSearch, window, cx)
4127 });
4128 cx.run_until_parked();
4129 let project_search_view = pane
4130 .read_with(&mut cx, |pane, _| {
4131 pane.active_item()
4132 .and_then(|item| item.downcast::<ProjectSearchView>())
4133 })
4134 .expect("should open a project search view after spawning a new search");
4135 project_search_view.update(&mut cx, |search_view, cx| {
4136 assert_eq!(
4137 search_view.search_query_text(cx),
4138 buffer_search_query,
4139 "Project search should take the query from the buffer search bar since it got focused and had a query inside"
4140 );
4141 });
4142 }
4143
4144 fn init_test(cx: &mut TestAppContext) {
4145 cx.update(|cx| {
4146 let settings = SettingsStore::test(cx);
4147 cx.set_global(settings);
4148
4149 theme::init(theme::LoadThemes::JustBase, cx);
4150
4151 language::init(cx);
4152 client::init_settings(cx);
4153 editor::init(cx);
4154 workspace::init_settings(cx);
4155 Project::init_settings(cx);
4156 crate::init(cx);
4157 });
4158 }
4159
4160 fn perform_search(
4161 search_view: WindowHandle<ProjectSearchView>,
4162 text: impl Into<Arc<str>>,
4163 cx: &mut TestAppContext,
4164 ) {
4165 search_view
4166 .update(cx, |search_view, window, cx| {
4167 search_view.query_editor.update(cx, |query_editor, cx| {
4168 query_editor.set_text(text, window, cx)
4169 });
4170 search_view.search(cx);
4171 })
4172 .unwrap();
4173 cx.background_executor.run_until_parked();
4174 }
4175}