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