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