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