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