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