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