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