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