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