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, items::active_match_index, scroll::Autoscroll, Anchor, Editor,
9 EditorElement, EditorEvent, EditorSettings, EditorStyle, MultiBuffer, MAX_TAB_TITLE_LEN,
10};
11use futures::StreamExt;
12use gpui::{
13 actions, div, Action, AnyElement, AnyView, AppContext, Axis, Context as _, EntityId,
14 EventEmitter, FocusHandle, FocusableView, Global, Hsla, InteractiveElement, IntoElement,
15 KeyContext, Model, ModelContext, ParentElement, Point, Render, SharedString, Styled,
16 Subscription, Task, TextStyle, UpdateGlobal, View, ViewContext, VisualContext, WeakModel,
17 WeakView, WindowContext,
18};
19use language::Buffer;
20use menu::Confirm;
21use project::{
22 search::{SearchInputKind, SearchQuery},
23 search_history::SearchHistoryCursor,
24 Project, ProjectPath,
25};
26use settings::Settings;
27use std::{
28 any::{Any, TypeId},
29 mem,
30 ops::{Not, Range},
31 path::Path,
32};
33use theme::ThemeSettings;
34use ui::{
35 h_flex, prelude::*, utils::SearchInputWidth, v_flex, Icon, IconButton, IconButtonShape,
36 IconName, KeyBinding, Label, LabelCommon, LabelSize, Toggleable, Tooltip,
37};
38use util::paths::PathMatcher;
39use workspace::{
40 item::{BreadcrumbText, Item, ItemEvent, ItemHandle},
41 searchable::{Direction, SearchableItem, SearchableItemHandle},
42 DeploySearch, ItemNavHistory, NewSearch, ToolbarItemEvent, ToolbarItemLocation,
43 ToolbarItemView, Workspace, WorkspaceId,
44};
45
46actions!(
47 project_search,
48 [SearchInNew, ToggleFocus, NextField, ToggleFilters]
49);
50
51#[derive(Default)]
52struct ActiveSettings(HashMap<WeakModel<Project>, ProjectSearchSettings>);
53
54impl Global for ActiveSettings {}
55
56pub fn init(cx: &mut AppContext) {
57 cx.set_global(ActiveSettings::default());
58 cx.observe_new_views(|workspace: &mut Workspace, _cx| {
59 register_workspace_action(workspace, move |search_bar, _: &Deploy, cx| {
60 search_bar.focus_search(cx);
61 });
62 register_workspace_action(workspace, move |search_bar, _: &FocusSearch, cx| {
63 search_bar.focus_search(cx);
64 });
65 register_workspace_action(workspace, move |search_bar, _: &ToggleFilters, cx| {
66 search_bar.toggle_filters(cx);
67 });
68 register_workspace_action(workspace, move |search_bar, _: &ToggleCaseSensitive, cx| {
69 search_bar.toggle_search_option(SearchOptions::CASE_SENSITIVE, cx);
70 });
71 register_workspace_action(workspace, move |search_bar, _: &ToggleWholeWord, cx| {
72 search_bar.toggle_search_option(SearchOptions::WHOLE_WORD, cx);
73 });
74 register_workspace_action(workspace, move |search_bar, _: &ToggleRegex, cx| {
75 search_bar.toggle_search_option(SearchOptions::REGEX, cx);
76 });
77 register_workspace_action(workspace, move |search_bar, action: &ToggleReplace, cx| {
78 search_bar.toggle_replace(action, cx)
79 });
80 register_workspace_action(
81 workspace,
82 move |search_bar, action: &SelectPrevMatch, cx| {
83 search_bar.select_prev_match(action, cx)
84 },
85 );
86 register_workspace_action(
87 workspace,
88 move |search_bar, action: &SelectNextMatch, cx| {
89 search_bar.select_next_match(action, cx)
90 },
91 );
92
93 // Only handle search_in_new if there is a search present
94 register_workspace_action_for_present_search(workspace, |workspace, action, cx| {
95 ProjectSearchView::search_in_new(workspace, action, cx)
96 });
97
98 // Both on present and dismissed search, we need to unconditionally handle those actions to focus from the editor.
99 workspace.register_action(move |workspace, action: &DeploySearch, cx| {
100 if workspace.has_active_modal(cx) {
101 cx.propagate();
102 return;
103 }
104 ProjectSearchView::deploy_search(workspace, action, cx);
105 cx.notify();
106 });
107 workspace.register_action(move |workspace, action: &NewSearch, cx| {
108 if workspace.has_active_modal(cx) {
109 cx.propagate();
110 return;
111 }
112 ProjectSearchView::new_search(workspace, action, cx);
113 cx.notify();
114 });
115 })
116 .detach();
117}
118
119fn is_contains_uppercase(str: &str) -> bool {
120 str.chars().any(|c| c.is_uppercase())
121}
122
123pub struct ProjectSearch {
124 project: Model<Project>,
125 excerpts: Model<MultiBuffer>,
126 pending_search: Option<Task<Option<()>>>,
127 match_ranges: Vec<Range<Anchor>>,
128 active_query: Option<SearchQuery>,
129 last_search_query_text: Option<String>,
130 search_id: usize,
131 no_results: Option<bool>,
132 limit_reached: bool,
133 search_history_cursor: SearchHistoryCursor,
134 search_included_history_cursor: SearchHistoryCursor,
135 search_excluded_history_cursor: SearchHistoryCursor,
136}
137
138#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
139enum InputPanel {
140 Query,
141 Exclude,
142 Include,
143}
144
145pub struct ProjectSearchView {
146 workspace: WeakView<Workspace>,
147 focus_handle: FocusHandle,
148 model: Model<ProjectSearch>,
149 query_editor: View<Editor>,
150 replacement_editor: View<Editor>,
151 results_editor: View<Editor>,
152 search_options: SearchOptions,
153 panels_with_errors: HashSet<InputPanel>,
154 active_match_index: Option<usize>,
155 search_id: usize,
156 included_files_editor: View<Editor>,
157 excluded_files_editor: View<Editor>,
158 filters_enabled: bool,
159 replace_enabled: bool,
160 included_opened_only: bool,
161 _subscriptions: Vec<Subscription>,
162}
163
164#[derive(Debug, Clone)]
165pub struct ProjectSearchSettings {
166 search_options: SearchOptions,
167 filters_enabled: bool,
168}
169
170pub struct ProjectSearchBar {
171 active_project_search: Option<View<ProjectSearchView>>,
172 subscription: Option<Subscription>,
173}
174
175impl ProjectSearch {
176 pub fn new(project: Model<Project>, cx: &mut ModelContext<Self>) -> Self {
177 let capability = project.read(cx).capability();
178
179 Self {
180 project,
181 excerpts: cx.new_model(|_| MultiBuffer::new(capability)),
182 pending_search: Default::default(),
183 match_ranges: Default::default(),
184 active_query: None,
185 last_search_query_text: None,
186 search_id: 0,
187 no_results: None,
188 limit_reached: false,
189 search_history_cursor: Default::default(),
190 search_included_history_cursor: Default::default(),
191 search_excluded_history_cursor: Default::default(),
192 }
193 }
194
195 fn clone(&self, cx: &mut ModelContext<Self>) -> Model<Self> {
196 cx.new_model(|cx| Self {
197 project: self.project.clone(),
198 excerpts: self
199 .excerpts
200 .update(cx, |excerpts, cx| cx.new_model(|cx| excerpts.clone(cx))),
201 pending_search: Default::default(),
202 match_ranges: self.match_ranges.clone(),
203 active_query: self.active_query.clone(),
204 last_search_query_text: self.last_search_query_text.clone(),
205 search_id: self.search_id,
206 no_results: self.no_results,
207 limit_reached: self.limit_reached,
208 search_history_cursor: self.search_history_cursor.clone(),
209 search_included_history_cursor: self.search_included_history_cursor.clone(),
210 search_excluded_history_cursor: self.search_excluded_history_cursor.clone(),
211 })
212 }
213 fn cursor(&self, kind: SearchInputKind) -> &SearchHistoryCursor {
214 match kind {
215 SearchInputKind::Query => &self.search_history_cursor,
216 SearchInputKind::Include => &self.search_included_history_cursor,
217 SearchInputKind::Exclude => &self.search_excluded_history_cursor,
218 }
219 }
220 fn cursor_mut(&mut self, kind: SearchInputKind) -> &mut SearchHistoryCursor {
221 match kind {
222 SearchInputKind::Query => &mut self.search_history_cursor,
223 SearchInputKind::Include => &mut self.search_included_history_cursor,
224 SearchInputKind::Exclude => &mut self.search_excluded_history_cursor,
225 }
226 }
227
228 fn search(&mut self, query: SearchQuery, cx: &mut ModelContext<Self>) {
229 let search = self.project.update(cx, |project, cx| {
230 project
231 .search_history_mut(SearchInputKind::Query)
232 .add(&mut self.search_history_cursor, query.as_str().to_string());
233 let included = query.as_inner().files_to_include().sources().join(",");
234 if !included.is_empty() {
235 project
236 .search_history_mut(SearchInputKind::Include)
237 .add(&mut self.search_included_history_cursor, included);
238 }
239 let excluded = query.as_inner().files_to_exclude().sources().join(",");
240 if !excluded.is_empty() {
241 project
242 .search_history_mut(SearchInputKind::Exclude)
243 .add(&mut self.search_excluded_history_cursor, excluded);
244 }
245 project.search(query.clone(), cx)
246 });
247 self.last_search_query_text = Some(query.as_str().to_string());
248 self.search_id += 1;
249 self.active_query = Some(query);
250 self.match_ranges.clear();
251 self.pending_search = Some(cx.spawn(|this, mut cx| async move {
252 let mut matches = search.ready_chunks(1024);
253 let this = this.upgrade()?;
254 this.update(&mut cx, |this, cx| {
255 this.match_ranges.clear();
256 this.excerpts.update(cx, |this, cx| this.clear(cx));
257 this.no_results = Some(true);
258 this.limit_reached = false;
259 })
260 .ok()?;
261
262 let mut limit_reached = false;
263 while let Some(results) = matches.next().await {
264 let mut buffers_with_ranges = Vec::with_capacity(results.len());
265 for result in results {
266 match result {
267 project::search::SearchResult::Buffer { buffer, ranges } => {
268 buffers_with_ranges.push((buffer, ranges));
269 }
270 project::search::SearchResult::LimitReached => {
271 limit_reached = true;
272 }
273 }
274 }
275
276 let match_ranges = this
277 .update(&mut cx, |this, cx| {
278 this.excerpts.update(cx, |excerpts, cx| {
279 excerpts.push_multiple_excerpts_with_context_lines(
280 buffers_with_ranges,
281 editor::DEFAULT_MULTIBUFFER_CONTEXT,
282 cx,
283 )
284 })
285 })
286 .ok()?
287 .await;
288
289 this.update(&mut cx, |this, cx| {
290 this.match_ranges.extend(match_ranges);
291 cx.notify();
292 })
293 .ok()?;
294 }
295
296 this.update(&mut cx, |this, cx| {
297 if !this.match_ranges.is_empty() {
298 this.no_results = Some(false);
299 }
300 this.limit_reached = limit_reached;
301 this.pending_search.take();
302 cx.notify();
303 })
304 .ok()?;
305
306 None
307 }));
308 cx.notify();
309 }
310}
311
312#[derive(Clone, Debug, PartialEq, Eq)]
313pub enum ViewEvent {
314 UpdateTab,
315 Activate,
316 EditorEvent(editor::EditorEvent),
317 Dismiss,
318}
319
320impl EventEmitter<ViewEvent> for ProjectSearchView {}
321
322impl Render for ProjectSearchView {
323 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
324 if self.has_matches() {
325 div()
326 .flex_1()
327 .size_full()
328 .track_focus(&self.focus_handle(cx))
329 .child(self.results_editor.clone())
330 } else {
331 let model = self.model.read(cx);
332 let has_no_results = model.no_results.unwrap_or(false);
333 let is_search_underway = model.pending_search.is_some();
334
335 let heading_text = if is_search_underway {
336 "Searching…"
337 } else if has_no_results {
338 "No Results"
339 } else {
340 "Search All Files"
341 };
342
343 let heading_text = div()
344 .justify_center()
345 .child(Label::new(heading_text).size(LabelSize::Large));
346
347 let page_content: Option<AnyElement> = if let Some(no_results) = model.no_results {
348 if model.pending_search.is_none() && no_results {
349 Some(
350 Label::new("No results found in this project for the provided query")
351 .size(LabelSize::Small)
352 .into_any_element(),
353 )
354 } else {
355 None
356 }
357 } else {
358 Some(self.landing_text_minor(cx).into_any_element())
359 };
360
361 let page_content = page_content.map(|text| div().child(text));
362
363 v_flex()
364 .size_full()
365 .items_center()
366 .justify_center()
367 .overflow_hidden()
368 .bg(cx.theme().colors().editor_background)
369 .track_focus(&self.focus_handle(cx))
370 .child(
371 v_flex()
372 .id("project-search-landing-page")
373 .overflow_y_scroll()
374 .max_w_80()
375 .gap_1()
376 .child(heading_text)
377 .children(page_content),
378 )
379 }
380 }
381}
382
383impl FocusableView for ProjectSearchView {
384 fn focus_handle(&self, _: &AppContext) -> gpui::FocusHandle {
385 self.focus_handle.clone()
386 }
387}
388
389impl Item for ProjectSearchView {
390 type Event = ViewEvent;
391 fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
392 let query_text = self.query_editor.read(cx).text(cx);
393
394 query_text
395 .is_empty()
396 .not()
397 .then(|| query_text.into())
398 .or_else(|| Some("Project Search".into()))
399 }
400
401 fn act_as_type<'a>(
402 &'a self,
403 type_id: TypeId,
404 self_handle: &'a View<Self>,
405 _: &'a AppContext,
406 ) -> Option<AnyView> {
407 if type_id == TypeId::of::<Self>() {
408 Some(self_handle.clone().into())
409 } else if type_id == TypeId::of::<Editor>() {
410 Some(self.results_editor.clone().into())
411 } else {
412 None
413 }
414 }
415
416 fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
417 self.results_editor
418 .update(cx, |editor, cx| editor.deactivated(cx));
419 }
420
421 fn tab_icon(&self, _cx: &WindowContext) -> Option<Icon> {
422 Some(Icon::new(IconName::MagnifyingGlass))
423 }
424
425 fn tab_content_text(&self, cx: &WindowContext) -> Option<SharedString> {
426 let last_query: Option<SharedString> = self
427 .model
428 .read(cx)
429 .last_search_query_text
430 .as_ref()
431 .map(|query| {
432 let query = query.replace('\n', "");
433 let query_text = util::truncate_and_trailoff(&query, MAX_TAB_TITLE_LEN);
434 query_text.into()
435 });
436 Some(
437 last_query
438 .filter(|query| !query.is_empty())
439 .unwrap_or_else(|| "Project Search".into()),
440 )
441 }
442
443 fn telemetry_event_text(&self) -> Option<&'static str> {
444 Some("project search")
445 }
446
447 fn for_each_project_item(
448 &self,
449 cx: &AppContext,
450 f: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
451 ) {
452 self.results_editor.for_each_project_item(cx, f)
453 }
454
455 fn is_singleton(&self, _: &AppContext) -> bool {
456 false
457 }
458
459 fn can_save(&self, _: &AppContext) -> bool {
460 true
461 }
462
463 fn is_dirty(&self, cx: &AppContext) -> bool {
464 self.results_editor.read(cx).is_dirty(cx)
465 }
466
467 fn has_conflict(&self, cx: &AppContext) -> bool {
468 self.results_editor.read(cx).has_conflict(cx)
469 }
470
471 fn save(
472 &mut self,
473 format: bool,
474 project: Model<Project>,
475 cx: &mut ViewContext<Self>,
476 ) -> Task<anyhow::Result<()>> {
477 self.results_editor
478 .update(cx, |editor, cx| editor.save(format, project, cx))
479 }
480
481 fn save_as(
482 &mut self,
483 _: Model<Project>,
484 _: ProjectPath,
485 _: &mut ViewContext<Self>,
486 ) -> Task<anyhow::Result<()>> {
487 unreachable!("save_as should not have been called")
488 }
489
490 fn reload(
491 &mut self,
492 project: Model<Project>,
493 cx: &mut ViewContext<Self>,
494 ) -> Task<anyhow::Result<()>> {
495 self.results_editor
496 .update(cx, |editor, cx| editor.reload(project, cx))
497 }
498
499 fn clone_on_split(
500 &self,
501 _workspace_id: Option<WorkspaceId>,
502 cx: &mut ViewContext<Self>,
503 ) -> Option<View<Self>>
504 where
505 Self: Sized,
506 {
507 let model = self.model.update(cx, |model, cx| model.clone(cx));
508 Some(cx.new_view(|cx| Self::new(self.workspace.clone(), model, cx, None)))
509 }
510
511 fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
512 self.results_editor
513 .update(cx, |editor, cx| editor.added_to_workspace(workspace, cx));
514 }
515
516 fn set_nav_history(&mut self, nav_history: ItemNavHistory, cx: &mut ViewContext<Self>) {
517 self.results_editor.update(cx, |editor, _| {
518 editor.set_nav_history(Some(nav_history));
519 });
520 }
521
522 fn navigate(&mut self, data: Box<dyn Any>, cx: &mut ViewContext<Self>) -> bool {
523 self.results_editor
524 .update(cx, |editor, cx| editor.navigate(data, cx))
525 }
526
527 fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
528 match event {
529 ViewEvent::UpdateTab => {
530 f(ItemEvent::UpdateBreadcrumbs);
531 f(ItemEvent::UpdateTab);
532 }
533 ViewEvent::EditorEvent(editor_event) => {
534 Editor::to_item_events(editor_event, f);
535 }
536 ViewEvent::Dismiss => f(ItemEvent::CloseItem),
537 _ => {}
538 }
539 }
540
541 fn breadcrumb_location(&self, _: &AppContext) -> ToolbarItemLocation {
542 if self.has_matches() {
543 ToolbarItemLocation::Secondary
544 } else {
545 ToolbarItemLocation::Hidden
546 }
547 }
548
549 fn breadcrumbs(&self, theme: &theme::Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
550 self.results_editor.breadcrumbs(theme, cx)
551 }
552}
553
554impl ProjectSearchView {
555 pub fn get_matches(&self, cx: &AppContext) -> Vec<Range<Anchor>> {
556 self.model.read(cx).match_ranges.clone()
557 }
558
559 fn toggle_filters(&mut self, cx: &mut ViewContext<Self>) {
560 self.filters_enabled = !self.filters_enabled;
561 ActiveSettings::update_global(cx, |settings, cx| {
562 settings.0.insert(
563 self.model.read(cx).project.downgrade(),
564 self.current_settings(),
565 );
566 });
567 }
568
569 fn current_settings(&self) -> ProjectSearchSettings {
570 ProjectSearchSettings {
571 search_options: self.search_options,
572 filters_enabled: self.filters_enabled,
573 }
574 }
575
576 fn toggle_search_option(&mut self, option: SearchOptions, cx: &mut ViewContext<Self>) {
577 self.search_options.toggle(option);
578 ActiveSettings::update_global(cx, |settings, cx| {
579 settings.0.insert(
580 self.model.read(cx).project.downgrade(),
581 self.current_settings(),
582 );
583 });
584 }
585
586 fn toggle_opened_only(&mut self, _cx: &mut ViewContext<Self>) {
587 self.included_opened_only = !self.included_opened_only;
588 }
589
590 fn replace_next(&mut self, _: &ReplaceNext, cx: &mut ViewContext<Self>) {
591 if self.model.read(cx).match_ranges.is_empty() {
592 return;
593 }
594 let Some(active_index) = self.active_match_index else {
595 return;
596 };
597
598 let query = self.model.read(cx).active_query.clone();
599 if let Some(query) = query {
600 let query = query.with_replacement(self.replacement(cx));
601
602 // TODO: Do we need the clone here?
603 let mat = self.model.read(cx).match_ranges[active_index].clone();
604 self.results_editor.update(cx, |editor, cx| {
605 editor.replace(&mat, &query, cx);
606 });
607 self.select_match(Direction::Next, cx)
608 }
609 }
610 pub fn replacement(&self, cx: &AppContext) -> String {
611 self.replacement_editor.read(cx).text(cx)
612 }
613 fn replace_all(&mut self, _: &ReplaceAll, cx: &mut ViewContext<Self>) {
614 if self.active_match_index.is_none() {
615 return;
616 }
617
618 let Some(query) = self.model.read(cx).active_query.as_ref() else {
619 return;
620 };
621 let query = query.clone().with_replacement(self.replacement(cx));
622
623 let match_ranges = self
624 .model
625 .update(cx, |model, _| mem::take(&mut model.match_ranges));
626 if match_ranges.is_empty() {
627 return;
628 }
629
630 self.results_editor.update(cx, |editor, cx| {
631 editor.replace_all(&mut match_ranges.iter(), &query, cx);
632 });
633
634 self.model.update(cx, |model, _cx| {
635 model.match_ranges = match_ranges;
636 });
637 }
638
639 pub fn new(
640 workspace: WeakView<Workspace>,
641 model: Model<ProjectSearch>,
642 cx: &mut ViewContext<Self>,
643 settings: Option<ProjectSearchSettings>,
644 ) -> Self {
645 let project;
646 let excerpts;
647 let mut replacement_text = None;
648 let mut query_text = String::new();
649 let mut subscriptions = Vec::new();
650
651 // Read in settings if available
652 let (mut options, filters_enabled) = if let Some(settings) = settings {
653 (settings.search_options, settings.filters_enabled)
654 } else {
655 let search_options =
656 SearchOptions::from_settings(&EditorSettings::get_global(cx).search);
657 (search_options, false)
658 };
659
660 {
661 let model = model.read(cx);
662 project = model.project.clone();
663 excerpts = model.excerpts.clone();
664 if let Some(active_query) = model.active_query.as_ref() {
665 query_text = active_query.as_str().to_string();
666 replacement_text = active_query.replacement().map(ToOwned::to_owned);
667 options = SearchOptions::from_query(active_query);
668 }
669 }
670 subscriptions.push(cx.observe(&model, |this, _, cx| this.model_changed(cx)));
671
672 let query_editor = cx.new_view(|cx| {
673 let mut editor = Editor::single_line(cx);
674 editor.set_placeholder_text("Search all files…", cx);
675 editor.set_text(query_text, cx);
676 editor
677 });
678 // Subscribe to query_editor in order to reraise editor events for workspace item activation purposes
679 subscriptions.push(
680 cx.subscribe(&query_editor, |this, _, event: &EditorEvent, cx| {
681 if let EditorEvent::Edited { .. } = event {
682 if EditorSettings::get_global(cx).use_smartcase_search {
683 let query = this.search_query_text(cx);
684 if !query.is_empty()
685 && this.search_options.contains(SearchOptions::CASE_SENSITIVE)
686 != is_contains_uppercase(&query)
687 {
688 this.toggle_search_option(SearchOptions::CASE_SENSITIVE, cx);
689 }
690 }
691 }
692 cx.emit(ViewEvent::EditorEvent(event.clone()))
693 }),
694 );
695 let replacement_editor = cx.new_view(|cx| {
696 let mut editor = Editor::single_line(cx);
697 editor.set_placeholder_text("Replace in project…", cx);
698 if let Some(text) = replacement_text {
699 editor.set_text(text, cx);
700 }
701 editor
702 });
703 let results_editor = cx.new_view(|cx| {
704 let mut editor = Editor::for_multibuffer(excerpts, Some(project.clone()), true, cx);
705 editor.set_searchable(false);
706 editor
707 });
708 subscriptions.push(cx.observe(&results_editor, |_, _, cx| cx.emit(ViewEvent::UpdateTab)));
709
710 subscriptions.push(
711 cx.subscribe(&results_editor, |this, _, event: &EditorEvent, cx| {
712 if matches!(event, editor::EditorEvent::SelectionsChanged { .. }) {
713 this.update_match_index(cx);
714 }
715 // Reraise editor events for workspace item activation purposes
716 cx.emit(ViewEvent::EditorEvent(event.clone()));
717 }),
718 );
719
720 let included_files_editor = cx.new_view(|cx| {
721 let mut editor = Editor::single_line(cx);
722 editor.set_placeholder_text("Include: crates/**/*.toml", cx);
723
724 editor
725 });
726 // Subscribe to include_files_editor in order to reraise editor events for workspace item activation purposes
727 subscriptions.push(
728 cx.subscribe(&included_files_editor, |_, _, event: &EditorEvent, cx| {
729 cx.emit(ViewEvent::EditorEvent(event.clone()))
730 }),
731 );
732
733 let excluded_files_editor = cx.new_view(|cx| {
734 let mut editor = Editor::single_line(cx);
735 editor.set_placeholder_text("Exclude: vendor/*, *.lock", cx);
736
737 editor
738 });
739 // Subscribe to excluded_files_editor in order to reraise editor events for workspace item activation purposes
740 subscriptions.push(
741 cx.subscribe(&excluded_files_editor, |_, _, event: &EditorEvent, cx| {
742 cx.emit(ViewEvent::EditorEvent(event.clone()))
743 }),
744 );
745
746 let focus_handle = cx.focus_handle();
747 subscriptions.push(cx.on_focus_in(&focus_handle, |this, cx| {
748 if this.focus_handle.is_focused(cx) {
749 if this.has_matches() {
750 this.results_editor.focus_handle(cx).focus(cx);
751 } else {
752 this.query_editor.focus_handle(cx).focus(cx);
753 }
754 }
755 }));
756
757 // Check if Worktrees have all been previously indexed
758 let mut this = ProjectSearchView {
759 workspace,
760 focus_handle,
761 replacement_editor,
762 search_id: model.read(cx).search_id,
763 model,
764 query_editor,
765 results_editor,
766 search_options: options,
767 panels_with_errors: HashSet::default(),
768 active_match_index: None,
769 included_files_editor,
770 excluded_files_editor,
771 filters_enabled,
772 replace_enabled: false,
773 included_opened_only: false,
774 _subscriptions: subscriptions,
775 };
776 this.model_changed(cx);
777 this
778 }
779
780 pub fn new_search_in_directory(
781 workspace: &mut Workspace,
782 dir_path: &Path,
783 cx: &mut ViewContext<Workspace>,
784 ) {
785 let Some(filter_str) = dir_path.to_str() else {
786 return;
787 };
788
789 let weak_workspace = cx.view().downgrade();
790
791 let model = cx.new_model(|cx| ProjectSearch::new(workspace.project().clone(), cx));
792 let search = cx.new_view(|cx| ProjectSearchView::new(weak_workspace, model, cx, None));
793 workspace.add_item_to_active_pane(Box::new(search.clone()), None, true, cx);
794 search.update(cx, |search, cx| {
795 search
796 .included_files_editor
797 .update(cx, |editor, cx| editor.set_text(filter_str, cx));
798 search.filters_enabled = true;
799 search.focus_query_editor(cx)
800 });
801 }
802
803 /// Re-activate the most recently activated search in this pane or the most recent if it has been closed.
804 /// If no search exists in the workspace, create a new one.
805 pub fn deploy_search(
806 workspace: &mut Workspace,
807 action: &workspace::DeploySearch,
808 cx: &mut ViewContext<Workspace>,
809 ) {
810 let existing = workspace
811 .active_pane()
812 .read(cx)
813 .items()
814 .find_map(|item| item.downcast::<ProjectSearchView>());
815
816 Self::existing_or_new_search(workspace, existing, action, cx);
817 }
818
819 fn search_in_new(workspace: &mut Workspace, _: &SearchInNew, cx: &mut ViewContext<Workspace>) {
820 if let Some(search_view) = workspace
821 .active_item(cx)
822 .and_then(|item| item.downcast::<ProjectSearchView>())
823 {
824 let new_query = search_view.update(cx, |search_view, cx| {
825 let new_query = search_view.build_search_query(cx);
826 if new_query.is_some() {
827 if let Some(old_query) = search_view.model.read(cx).active_query.clone() {
828 search_view.query_editor.update(cx, |editor, cx| {
829 editor.set_text(old_query.as_str(), cx);
830 });
831 search_view.search_options = SearchOptions::from_query(&old_query);
832 }
833 }
834 new_query
835 });
836 if let Some(new_query) = new_query {
837 let model = cx.new_model(|cx| {
838 let mut model = ProjectSearch::new(workspace.project().clone(), cx);
839 model.search(new_query, cx);
840 model
841 });
842 let weak_workspace = cx.view().downgrade();
843 workspace.add_item_to_active_pane(
844 Box::new(
845 cx.new_view(|cx| ProjectSearchView::new(weak_workspace, model, cx, None)),
846 ),
847 None,
848 true,
849 cx,
850 );
851 }
852 }
853 }
854
855 // Add another search tab to the workspace.
856 fn new_search(
857 workspace: &mut Workspace,
858 _: &workspace::NewSearch,
859 cx: &mut ViewContext<Workspace>,
860 ) {
861 Self::existing_or_new_search(workspace, None, &DeploySearch::find(), cx)
862 }
863
864 fn existing_or_new_search(
865 workspace: &mut Workspace,
866 existing: Option<View<ProjectSearchView>>,
867 action: &workspace::DeploySearch,
868 cx: &mut ViewContext<Workspace>,
869 ) {
870 let query = workspace.active_item(cx).and_then(|item| {
871 if let Some(buffer_search_query) = buffer_search_query(workspace, item.as_ref(), cx) {
872 return Some(buffer_search_query);
873 }
874
875 let editor = item.act_as::<Editor>(cx)?;
876 let query = editor.query_suggestion(cx);
877 if query.is_empty() {
878 None
879 } else {
880 Some(query)
881 }
882 });
883
884 let search = if let Some(existing) = existing {
885 workspace.activate_item(&existing, true, true, cx);
886 existing
887 } else {
888 let settings = cx
889 .global::<ActiveSettings>()
890 .0
891 .get(&workspace.project().downgrade());
892
893 let settings = settings.cloned();
894
895 let weak_workspace = cx.view().downgrade();
896
897 let model = cx.new_model(|cx| ProjectSearch::new(workspace.project().clone(), cx));
898 let view =
899 cx.new_view(|cx| ProjectSearchView::new(weak_workspace, model, cx, settings));
900
901 workspace.add_item_to_active_pane(Box::new(view.clone()), None, true, cx);
902 view
903 };
904
905 search.update(cx, |search, cx| {
906 search.replace_enabled = action.replace_enabled;
907 if let Some(query) = query {
908 search.set_query(&query, cx);
909 }
910 search.focus_query_editor(cx)
911 });
912 }
913
914 fn search(&mut self, cx: &mut ViewContext<Self>) {
915 if let Some(query) = self.build_search_query(cx) {
916 self.model.update(cx, |model, cx| model.search(query, cx));
917 }
918 }
919
920 pub fn search_query_text(&self, cx: &WindowContext) -> String {
921 self.query_editor.read(cx).text(cx)
922 }
923
924 fn build_search_query(&mut self, cx: &mut ViewContext<Self>) -> Option<SearchQuery> {
925 // Do not bail early in this function, as we want to fill out `self.panels_with_errors`.
926 let text = self.query_editor.read(cx).text(cx);
927 let open_buffers = if self.included_opened_only {
928 Some(self.open_buffers(cx))
929 } else {
930 None
931 };
932 let included_files =
933 match Self::parse_path_matches(&self.included_files_editor.read(cx).text(cx)) {
934 Ok(included_files) => {
935 let should_unmark_error = self.panels_with_errors.remove(&InputPanel::Include);
936 if should_unmark_error {
937 cx.notify();
938 }
939 included_files
940 }
941 Err(_e) => {
942 let should_mark_error = self.panels_with_errors.insert(InputPanel::Include);
943 if should_mark_error {
944 cx.notify();
945 }
946 PathMatcher::default()
947 }
948 };
949 let excluded_files =
950 match Self::parse_path_matches(&self.excluded_files_editor.read(cx).text(cx)) {
951 Ok(excluded_files) => {
952 let should_unmark_error = self.panels_with_errors.remove(&InputPanel::Exclude);
953 if should_unmark_error {
954 cx.notify();
955 }
956
957 excluded_files
958 }
959 Err(_e) => {
960 let should_mark_error = self.panels_with_errors.insert(InputPanel::Exclude);
961 if should_mark_error {
962 cx.notify();
963 }
964 PathMatcher::default()
965 }
966 };
967
968 let query = if self.search_options.contains(SearchOptions::REGEX) {
969 match SearchQuery::regex(
970 text,
971 self.search_options.contains(SearchOptions::WHOLE_WORD),
972 self.search_options.contains(SearchOptions::CASE_SENSITIVE),
973 self.search_options.contains(SearchOptions::INCLUDE_IGNORED),
974 included_files,
975 excluded_files,
976 open_buffers,
977 ) {
978 Ok(query) => {
979 let should_unmark_error = self.panels_with_errors.remove(&InputPanel::Query);
980 if should_unmark_error {
981 cx.notify();
982 }
983
984 Some(query)
985 }
986 Err(_e) => {
987 let should_mark_error = self.panels_with_errors.insert(InputPanel::Query);
988 if should_mark_error {
989 cx.notify();
990 }
991
992 None
993 }
994 }
995 } else {
996 match SearchQuery::text(
997 text,
998 self.search_options.contains(SearchOptions::WHOLE_WORD),
999 self.search_options.contains(SearchOptions::CASE_SENSITIVE),
1000 self.search_options.contains(SearchOptions::INCLUDE_IGNORED),
1001 included_files,
1002 excluded_files,
1003 open_buffers,
1004 ) {
1005 Ok(query) => {
1006 let should_unmark_error = self.panels_with_errors.remove(&InputPanel::Query);
1007 if should_unmark_error {
1008 cx.notify();
1009 }
1010
1011 Some(query)
1012 }
1013 Err(_e) => {
1014 let should_mark_error = self.panels_with_errors.insert(InputPanel::Query);
1015 if should_mark_error {
1016 cx.notify();
1017 }
1018
1019 None
1020 }
1021 }
1022 };
1023 if !self.panels_with_errors.is_empty() {
1024 return None;
1025 }
1026 if query.as_ref().is_some_and(|query| query.is_empty()) {
1027 return None;
1028 }
1029 query
1030 }
1031
1032 fn open_buffers(&self, cx: &mut ViewContext<Self>) -> Vec<Model<Buffer>> {
1033 let mut buffers = Vec::new();
1034 self.workspace
1035 .update(cx, |workspace, cx| {
1036 for editor in workspace.items_of_type::<Editor>(cx) {
1037 if let Some(buffer) = editor.read(cx).buffer().read(cx).as_singleton() {
1038 buffers.push(buffer);
1039 }
1040 }
1041 })
1042 .ok();
1043 buffers
1044 }
1045
1046 fn parse_path_matches(text: &str) -> anyhow::Result<PathMatcher> {
1047 let queries = text
1048 .split(',')
1049 .map(str::trim)
1050 .filter(|maybe_glob_str| !maybe_glob_str.is_empty())
1051 .map(str::to_owned)
1052 .collect::<Vec<_>>();
1053 Ok(PathMatcher::new(&queries)?)
1054 }
1055
1056 fn select_match(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
1057 if let Some(index) = self.active_match_index {
1058 let match_ranges = self.model.read(cx).match_ranges.clone();
1059
1060 if !EditorSettings::get_global(cx).search_wrap
1061 && ((direction == Direction::Next && index + 1 >= match_ranges.len())
1062 || (direction == Direction::Prev && index == 0))
1063 {
1064 crate::show_no_more_matches(cx);
1065 return;
1066 }
1067
1068 let new_index = self.results_editor.update(cx, |editor, cx| {
1069 editor.match_index_for_direction(&match_ranges, index, direction, 1, cx)
1070 });
1071
1072 let range_to_select = match_ranges[new_index].clone();
1073 self.results_editor.update(cx, |editor, cx| {
1074 let range_to_select = editor.range_for_match(&range_to_select);
1075 editor.unfold_ranges(&[range_to_select.clone()], false, true, cx);
1076 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
1077 s.select_ranges([range_to_select])
1078 });
1079 });
1080 }
1081 }
1082
1083 fn focus_query_editor(&mut self, cx: &mut ViewContext<Self>) {
1084 self.query_editor.update(cx, |query_editor, cx| {
1085 query_editor.select_all(&SelectAll, cx);
1086 });
1087 let editor_handle = self.query_editor.focus_handle(cx);
1088 cx.focus(&editor_handle);
1089 }
1090
1091 fn set_query(&mut self, query: &str, cx: &mut ViewContext<Self>) {
1092 self.set_search_editor(SearchInputKind::Query, query, cx);
1093 if EditorSettings::get_global(cx).use_smartcase_search
1094 && !query.is_empty()
1095 && self.search_options.contains(SearchOptions::CASE_SENSITIVE)
1096 != is_contains_uppercase(query)
1097 {
1098 self.toggle_search_option(SearchOptions::CASE_SENSITIVE, cx)
1099 }
1100 }
1101
1102 fn set_search_editor(&mut self, kind: SearchInputKind, text: &str, cx: &mut ViewContext<Self>) {
1103 let editor = match kind {
1104 SearchInputKind::Query => &self.query_editor,
1105 SearchInputKind::Include => &self.included_files_editor,
1106
1107 SearchInputKind::Exclude => &self.excluded_files_editor,
1108 };
1109 editor.update(cx, |included_editor, cx| included_editor.set_text(text, cx));
1110 }
1111
1112 fn focus_results_editor(&mut self, cx: &mut ViewContext<Self>) {
1113 self.query_editor.update(cx, |query_editor, cx| {
1114 let cursor = query_editor.selections.newest_anchor().head();
1115 query_editor.change_selections(None, cx, |s| s.select_ranges([cursor..cursor]));
1116 });
1117 let results_handle = self.results_editor.focus_handle(cx);
1118 cx.focus(&results_handle);
1119 }
1120
1121 fn model_changed(&mut self, cx: &mut ViewContext<Self>) {
1122 let match_ranges = self.model.read(cx).match_ranges.clone();
1123 if match_ranges.is_empty() {
1124 self.active_match_index = None;
1125 } else {
1126 self.active_match_index = Some(0);
1127 self.update_match_index(cx);
1128 let prev_search_id = mem::replace(&mut self.search_id, self.model.read(cx).search_id);
1129 let is_new_search = self.search_id != prev_search_id;
1130 self.results_editor.update(cx, |editor, cx| {
1131 if is_new_search {
1132 let range_to_select = match_ranges
1133 .first()
1134 .map(|range| editor.range_for_match(range));
1135 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
1136 s.select_ranges(range_to_select)
1137 });
1138 editor.scroll(Point::default(), Some(Axis::Vertical), cx);
1139 }
1140 editor.highlight_background::<Self>(
1141 &match_ranges,
1142 |theme| theme.search_match_background,
1143 cx,
1144 );
1145 });
1146 if is_new_search && self.query_editor.focus_handle(cx).is_focused(cx) {
1147 self.focus_results_editor(cx);
1148 }
1149 }
1150
1151 cx.emit(ViewEvent::UpdateTab);
1152 cx.notify();
1153 }
1154
1155 fn update_match_index(&mut self, cx: &mut ViewContext<Self>) {
1156 let results_editor = self.results_editor.read(cx);
1157 let new_index = active_match_index(
1158 &self.model.read(cx).match_ranges,
1159 &results_editor.selections.newest_anchor().head(),
1160 &results_editor.buffer().read(cx).snapshot(cx),
1161 );
1162 if self.active_match_index != new_index {
1163 self.active_match_index = new_index;
1164 cx.notify();
1165 }
1166 }
1167
1168 pub fn has_matches(&self) -> bool {
1169 self.active_match_index.is_some()
1170 }
1171
1172 fn landing_text_minor(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
1173 let focus_handle = self.focus_handle.clone();
1174 v_flex()
1175 .gap_1()
1176 .child(
1177 Label::new("Hit enter to search. For more options:")
1178 .color(Color::Muted)
1179 .mb_2(),
1180 )
1181 .child(
1182 Button::new("filter-paths", "Include/exclude specific paths")
1183 .icon(IconName::Filter)
1184 .icon_position(IconPosition::Start)
1185 .icon_size(IconSize::Small)
1186 .key_binding(KeyBinding::for_action_in(&ToggleFilters, &focus_handle, cx))
1187 .on_click(|_event, cx| cx.dispatch_action(ToggleFilters.boxed_clone())),
1188 )
1189 .child(
1190 Button::new("find-replace", "Find and replace")
1191 .icon(IconName::Replace)
1192 .icon_position(IconPosition::Start)
1193 .icon_size(IconSize::Small)
1194 .key_binding(KeyBinding::for_action_in(&ToggleReplace, &focus_handle, cx))
1195 .on_click(|_event, cx| cx.dispatch_action(ToggleReplace.boxed_clone())),
1196 )
1197 .child(
1198 Button::new("regex", "Match with regex")
1199 .icon(IconName::Regex)
1200 .icon_position(IconPosition::Start)
1201 .icon_size(IconSize::Small)
1202 .key_binding(KeyBinding::for_action_in(&ToggleRegex, &focus_handle, cx))
1203 .on_click(|_event, cx| cx.dispatch_action(ToggleRegex.boxed_clone())),
1204 )
1205 .child(
1206 Button::new("match-case", "Match case")
1207 .icon(IconName::CaseSensitive)
1208 .icon_position(IconPosition::Start)
1209 .icon_size(IconSize::Small)
1210 .key_binding(KeyBinding::for_action_in(
1211 &ToggleCaseSensitive,
1212 &focus_handle,
1213 cx,
1214 ))
1215 .on_click(|_event, cx| cx.dispatch_action(ToggleCaseSensitive.boxed_clone())),
1216 )
1217 .child(
1218 Button::new("match-whole-words", "Match whole words")
1219 .icon(IconName::WholeWord)
1220 .icon_position(IconPosition::Start)
1221 .icon_size(IconSize::Small)
1222 .key_binding(KeyBinding::for_action_in(
1223 &ToggleWholeWord,
1224 &focus_handle,
1225 cx,
1226 ))
1227 .on_click(|_event, cx| cx.dispatch_action(ToggleWholeWord.boxed_clone())),
1228 )
1229 }
1230
1231 fn border_color_for(&self, panel: InputPanel, cx: &WindowContext) -> Hsla {
1232 if self.panels_with_errors.contains(&panel) {
1233 Color::Error.color(cx)
1234 } else {
1235 cx.theme().colors().border
1236 }
1237 }
1238
1239 fn move_focus_to_results(&mut self, cx: &mut ViewContext<Self>) {
1240 if !self.results_editor.focus_handle(cx).is_focused(cx)
1241 && !self.model.read(cx).match_ranges.is_empty()
1242 {
1243 cx.stop_propagation();
1244 self.focus_results_editor(cx)
1245 }
1246 }
1247
1248 #[cfg(any(test, feature = "test-support"))]
1249 pub fn results_editor(&self) -> &View<Editor> {
1250 &self.results_editor
1251 }
1252}
1253
1254fn buffer_search_query(
1255 workspace: &mut Workspace,
1256 item: &dyn ItemHandle,
1257 cx: &mut ViewContext<Workspace>,
1258) -> Option<String> {
1259 let buffer_search_bar = workspace
1260 .pane_for(item)
1261 .and_then(|pane| {
1262 pane.read(cx)
1263 .toolbar()
1264 .read(cx)
1265 .item_of_type::<BufferSearchBar>()
1266 })?
1267 .read(cx);
1268 if buffer_search_bar.query_editor_focused() {
1269 let buffer_search_query = buffer_search_bar.query(cx);
1270 if !buffer_search_query.is_empty() {
1271 return Some(buffer_search_query);
1272 }
1273 }
1274 None
1275}
1276
1277impl Default for ProjectSearchBar {
1278 fn default() -> Self {
1279 Self::new()
1280 }
1281}
1282
1283impl ProjectSearchBar {
1284 pub fn new() -> Self {
1285 Self {
1286 active_project_search: None,
1287 subscription: None,
1288 }
1289 }
1290
1291 fn confirm(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
1292 if let Some(search_view) = self.active_project_search.as_ref() {
1293 search_view.update(cx, |search_view, cx| {
1294 if !search_view
1295 .replacement_editor
1296 .focus_handle(cx)
1297 .is_focused(cx)
1298 {
1299 cx.stop_propagation();
1300 search_view.search(cx);
1301 }
1302 });
1303 }
1304 }
1305
1306 fn tab(&mut self, _: &editor::actions::Tab, cx: &mut ViewContext<Self>) {
1307 self.cycle_field(Direction::Next, cx);
1308 }
1309
1310 fn tab_previous(&mut self, _: &editor::actions::TabPrev, cx: &mut ViewContext<Self>) {
1311 self.cycle_field(Direction::Prev, cx);
1312 }
1313
1314 fn focus_search(&mut self, cx: &mut ViewContext<Self>) {
1315 if let Some(search_view) = self.active_project_search.as_ref() {
1316 search_view.update(cx, |search_view, cx| {
1317 search_view.query_editor.focus_handle(cx).focus(cx);
1318 });
1319 }
1320 }
1321
1322 fn cycle_field(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
1323 let active_project_search = match &self.active_project_search {
1324 Some(active_project_search) => active_project_search,
1325
1326 None => {
1327 return;
1328 }
1329 };
1330
1331 active_project_search.update(cx, |project_view, cx| {
1332 let mut views = vec![&project_view.query_editor];
1333 if project_view.replace_enabled {
1334 views.push(&project_view.replacement_editor);
1335 }
1336 if project_view.filters_enabled {
1337 views.extend([
1338 &project_view.included_files_editor,
1339 &project_view.excluded_files_editor,
1340 ]);
1341 }
1342 let current_index = match views
1343 .iter()
1344 .enumerate()
1345 .find(|(_, view)| view.focus_handle(cx).is_focused(cx))
1346 {
1347 Some((index, _)) => index,
1348 None => return,
1349 };
1350
1351 let new_index = match direction {
1352 Direction::Next => (current_index + 1) % views.len(),
1353 Direction::Prev if current_index == 0 => views.len() - 1,
1354 Direction::Prev => (current_index - 1) % views.len(),
1355 };
1356 let next_focus_handle = views[new_index].focus_handle(cx);
1357 cx.focus(&next_focus_handle);
1358 cx.stop_propagation();
1359 });
1360 }
1361
1362 fn toggle_search_option(&mut self, option: SearchOptions, cx: &mut ViewContext<Self>) -> bool {
1363 if let Some(search_view) = self.active_project_search.as_ref() {
1364 search_view.update(cx, |search_view, cx| {
1365 search_view.toggle_search_option(option, cx);
1366 if search_view.model.read(cx).active_query.is_some() {
1367 search_view.search(cx);
1368 }
1369 });
1370
1371 cx.notify();
1372 true
1373 } else {
1374 false
1375 }
1376 }
1377
1378 fn toggle_replace(&mut self, _: &ToggleReplace, cx: &mut ViewContext<Self>) {
1379 if let Some(search) = &self.active_project_search {
1380 search.update(cx, |this, cx| {
1381 this.replace_enabled = !this.replace_enabled;
1382 let editor_to_focus = if this.replace_enabled {
1383 this.replacement_editor.focus_handle(cx)
1384 } else {
1385 this.query_editor.focus_handle(cx)
1386 };
1387 cx.focus(&editor_to_focus);
1388 cx.notify();
1389 });
1390 }
1391 }
1392
1393 fn toggle_filters(&mut self, cx: &mut ViewContext<Self>) -> bool {
1394 if let Some(search_view) = self.active_project_search.as_ref() {
1395 search_view.update(cx, |search_view, cx| {
1396 search_view.toggle_filters(cx);
1397 search_view
1398 .included_files_editor
1399 .update(cx, |_, cx| cx.notify());
1400 search_view
1401 .excluded_files_editor
1402 .update(cx, |_, cx| cx.notify());
1403 cx.refresh();
1404 cx.notify();
1405 });
1406 cx.notify();
1407 true
1408 } else {
1409 false
1410 }
1411 }
1412
1413 fn toggle_opened_only(&mut self, cx: &mut ViewContext<Self>) -> bool {
1414 if let Some(search_view) = self.active_project_search.as_ref() {
1415 search_view.update(cx, |search_view, cx| {
1416 search_view.toggle_opened_only(cx);
1417 if search_view.model.read(cx).active_query.is_some() {
1418 search_view.search(cx);
1419 }
1420 });
1421
1422 cx.notify();
1423 true
1424 } else {
1425 false
1426 }
1427 }
1428
1429 fn is_opened_only_enabled(&self, cx: &AppContext) -> bool {
1430 if let Some(search_view) = self.active_project_search.as_ref() {
1431 search_view.read(cx).included_opened_only
1432 } else {
1433 false
1434 }
1435 }
1436
1437 fn move_focus_to_results(&self, cx: &mut ViewContext<Self>) {
1438 if let Some(search_view) = self.active_project_search.as_ref() {
1439 search_view.update(cx, |search_view, cx| {
1440 search_view.move_focus_to_results(cx);
1441 });
1442 cx.notify();
1443 }
1444 }
1445
1446 fn is_option_enabled(&self, option: SearchOptions, cx: &AppContext) -> bool {
1447 if let Some(search) = self.active_project_search.as_ref() {
1448 search.read(cx).search_options.contains(option)
1449 } else {
1450 false
1451 }
1452 }
1453
1454 fn next_history_query(&mut self, _: &NextHistoryQuery, cx: &mut ViewContext<Self>) {
1455 if let Some(search_view) = self.active_project_search.as_ref() {
1456 search_view.update(cx, |search_view, cx| {
1457 for (editor, kind) in [
1458 (search_view.query_editor.clone(), SearchInputKind::Query),
1459 (
1460 search_view.included_files_editor.clone(),
1461 SearchInputKind::Include,
1462 ),
1463 (
1464 search_view.excluded_files_editor.clone(),
1465 SearchInputKind::Exclude,
1466 ),
1467 ] {
1468 if editor.focus_handle(cx).is_focused(cx) {
1469 let new_query = search_view.model.update(cx, |model, cx| {
1470 let project = model.project.clone();
1471
1472 if let Some(new_query) = project.update(cx, |project, _| {
1473 project
1474 .search_history_mut(kind)
1475 .next(model.cursor_mut(kind))
1476 .map(str::to_string)
1477 }) {
1478 new_query
1479 } else {
1480 model.cursor_mut(kind).reset();
1481 String::new()
1482 }
1483 });
1484 search_view.set_search_editor(kind, &new_query, cx);
1485 }
1486 }
1487 });
1488 }
1489 }
1490
1491 fn previous_history_query(&mut self, _: &PreviousHistoryQuery, cx: &mut ViewContext<Self>) {
1492 if let Some(search_view) = self.active_project_search.as_ref() {
1493 search_view.update(cx, |search_view, cx| {
1494 for (editor, kind) in [
1495 (search_view.query_editor.clone(), SearchInputKind::Query),
1496 (
1497 search_view.included_files_editor.clone(),
1498 SearchInputKind::Include,
1499 ),
1500 (
1501 search_view.excluded_files_editor.clone(),
1502 SearchInputKind::Exclude,
1503 ),
1504 ] {
1505 if editor.focus_handle(cx).is_focused(cx) {
1506 if editor.read(cx).text(cx).is_empty() {
1507 if let Some(new_query) = search_view
1508 .model
1509 .read(cx)
1510 .project
1511 .read(cx)
1512 .search_history(kind)
1513 .current(search_view.model.read(cx).cursor(kind))
1514 .map(str::to_string)
1515 {
1516 search_view.set_search_editor(kind, &new_query, cx);
1517 return;
1518 }
1519 }
1520
1521 if let Some(new_query) = search_view.model.update(cx, |model, cx| {
1522 let project = model.project.clone();
1523 project.update(cx, |project, _| {
1524 project
1525 .search_history_mut(kind)
1526 .previous(model.cursor_mut(kind))
1527 .map(str::to_string)
1528 })
1529 }) {
1530 search_view.set_search_editor(kind, &new_query, cx);
1531 }
1532 }
1533 }
1534 });
1535 }
1536 }
1537
1538 fn select_next_match(&mut self, _: &SelectNextMatch, cx: &mut ViewContext<Self>) {
1539 if let Some(search) = self.active_project_search.as_ref() {
1540 search.update(cx, |this, cx| {
1541 this.select_match(Direction::Next, cx);
1542 })
1543 }
1544 }
1545
1546 fn select_prev_match(&mut self, _: &SelectPrevMatch, cx: &mut ViewContext<Self>) {
1547 if let Some(search) = self.active_project_search.as_ref() {
1548 search.update(cx, |this, cx| {
1549 this.select_match(Direction::Prev, cx);
1550 })
1551 }
1552 }
1553
1554 fn render_text_input(&self, editor: &View<Editor>, cx: &ViewContext<Self>) -> impl IntoElement {
1555 let settings = ThemeSettings::get_global(cx);
1556 let text_style = TextStyle {
1557 color: if editor.read(cx).read_only(cx) {
1558 cx.theme().colors().text_disabled
1559 } else {
1560 cx.theme().colors().text
1561 },
1562 font_family: settings.buffer_font.family.clone(),
1563 font_features: settings.buffer_font.features.clone(),
1564 font_fallbacks: settings.buffer_font.fallbacks.clone(),
1565 font_size: rems(0.875).into(),
1566 font_weight: settings.buffer_font.weight,
1567 line_height: relative(1.3),
1568 ..Default::default()
1569 };
1570
1571 EditorElement::new(
1572 editor,
1573 EditorStyle {
1574 background: cx.theme().colors().editor_background,
1575 local_player: cx.theme().players().local(),
1576 text: text_style,
1577 ..Default::default()
1578 },
1579 )
1580 }
1581}
1582
1583impl Render for ProjectSearchBar {
1584 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
1585 let Some(search) = self.active_project_search.clone() else {
1586 return div();
1587 };
1588 let search = search.read(cx);
1589 let focus_handle = search.focus_handle(cx);
1590
1591 let container_width = cx.viewport_size().width;
1592 let input_width = SearchInputWidth::calc_width(container_width);
1593
1594 let input_base_styles = || {
1595 h_flex()
1596 .min_w_32()
1597 .w(input_width)
1598 .h_8()
1599 .px_2()
1600 .py_1()
1601 .border_1()
1602 .border_color(search.border_color_for(InputPanel::Query, cx))
1603 .rounded_lg()
1604 };
1605
1606 let query_column = input_base_styles()
1607 .on_action(cx.listener(|this, action, cx| this.confirm(action, cx)))
1608 .on_action(cx.listener(|this, action, cx| this.previous_history_query(action, cx)))
1609 .on_action(cx.listener(|this, action, cx| this.next_history_query(action, cx)))
1610 .child(self.render_text_input(&search.query_editor, cx))
1611 .child(
1612 h_flex()
1613 .gap_0p5()
1614 .child(SearchOptions::CASE_SENSITIVE.as_button(
1615 self.is_option_enabled(SearchOptions::CASE_SENSITIVE, cx),
1616 focus_handle.clone(),
1617 cx.listener(|this, _, cx| {
1618 this.toggle_search_option(SearchOptions::CASE_SENSITIVE, cx);
1619 }),
1620 ))
1621 .child(SearchOptions::WHOLE_WORD.as_button(
1622 self.is_option_enabled(SearchOptions::WHOLE_WORD, cx),
1623 focus_handle.clone(),
1624 cx.listener(|this, _, cx| {
1625 this.toggle_search_option(SearchOptions::WHOLE_WORD, cx);
1626 }),
1627 ))
1628 .child(SearchOptions::REGEX.as_button(
1629 self.is_option_enabled(SearchOptions::REGEX, cx),
1630 focus_handle.clone(),
1631 cx.listener(|this, _, cx| {
1632 this.toggle_search_option(SearchOptions::REGEX, cx);
1633 }),
1634 )),
1635 );
1636
1637 let mode_column = h_flex()
1638 .gap_1()
1639 .child(
1640 IconButton::new("project-search-filter-button", IconName::Filter)
1641 .shape(IconButtonShape::Square)
1642 .tooltip(|cx| Tooltip::for_action("Toggle Filters", &ToggleFilters, cx))
1643 .on_click(cx.listener(|this, _, cx| {
1644 this.toggle_filters(cx);
1645 }))
1646 .toggle_state(
1647 self.active_project_search
1648 .as_ref()
1649 .map(|search| search.read(cx).filters_enabled)
1650 .unwrap_or_default(),
1651 )
1652 .tooltip({
1653 let focus_handle = focus_handle.clone();
1654 move |cx| {
1655 Tooltip::for_action_in(
1656 "Toggle Filters",
1657 &ToggleFilters,
1658 &focus_handle,
1659 cx,
1660 )
1661 }
1662 }),
1663 )
1664 .child(
1665 IconButton::new("project-search-toggle-replace", IconName::Replace)
1666 .shape(IconButtonShape::Square)
1667 .on_click(cx.listener(|this, _, cx| {
1668 this.toggle_replace(&ToggleReplace, cx);
1669 }))
1670 .toggle_state(
1671 self.active_project_search
1672 .as_ref()
1673 .map(|search| search.read(cx).replace_enabled)
1674 .unwrap_or_default(),
1675 )
1676 .tooltip({
1677 let focus_handle = focus_handle.clone();
1678 move |cx| {
1679 Tooltip::for_action_in(
1680 "Toggle Replace",
1681 &ToggleReplace,
1682 &focus_handle,
1683 cx,
1684 )
1685 }
1686 }),
1687 );
1688
1689 let limit_reached = search.model.read(cx).limit_reached;
1690
1691 let match_text = search
1692 .active_match_index
1693 .and_then(|index| {
1694 let index = index + 1;
1695 let match_quantity = search.model.read(cx).match_ranges.len();
1696 if match_quantity > 0 {
1697 debug_assert!(match_quantity >= index);
1698 if limit_reached {
1699 Some(format!("{index}/{match_quantity}+").to_string())
1700 } else {
1701 Some(format!("{index}/{match_quantity}").to_string())
1702 }
1703 } else {
1704 None
1705 }
1706 })
1707 .unwrap_or_else(|| "0/0".to_string());
1708
1709 let matches_column = h_flex()
1710 .pl_2()
1711 .ml_2()
1712 .border_l_1()
1713 .border_color(cx.theme().colors().border_variant)
1714 .child(
1715 IconButton::new("project-search-prev-match", IconName::ChevronLeft)
1716 .shape(IconButtonShape::Square)
1717 .disabled(search.active_match_index.is_none())
1718 .on_click(cx.listener(|this, _, cx| {
1719 if let Some(search) = this.active_project_search.as_ref() {
1720 search.update(cx, |this, cx| {
1721 this.select_match(Direction::Prev, cx);
1722 })
1723 }
1724 }))
1725 .tooltip({
1726 let focus_handle = focus_handle.clone();
1727 move |cx| {
1728 Tooltip::for_action_in(
1729 "Go To Previous Match",
1730 &SelectPrevMatch,
1731 &focus_handle,
1732 cx,
1733 )
1734 }
1735 }),
1736 )
1737 .child(
1738 IconButton::new("project-search-next-match", IconName::ChevronRight)
1739 .shape(IconButtonShape::Square)
1740 .disabled(search.active_match_index.is_none())
1741 .on_click(cx.listener(|this, _, cx| {
1742 if let Some(search) = this.active_project_search.as_ref() {
1743 search.update(cx, |this, cx| {
1744 this.select_match(Direction::Next, cx);
1745 })
1746 }
1747 }))
1748 .tooltip({
1749 let focus_handle = focus_handle.clone();
1750 move |cx| {
1751 Tooltip::for_action_in(
1752 "Go To Next Match",
1753 &SelectNextMatch,
1754 &focus_handle,
1755 cx,
1756 )
1757 }
1758 }),
1759 )
1760 .child(
1761 div()
1762 .id("matches")
1763 .ml_1()
1764 .child(Label::new(match_text).size(LabelSize::Small).color(
1765 if search.active_match_index.is_some() {
1766 Color::Default
1767 } else {
1768 Color::Disabled
1769 },
1770 ))
1771 .when(limit_reached, |el| {
1772 el.tooltip(|cx| {
1773 Tooltip::text("Search limits reached.\nTry narrowing your search.", cx)
1774 })
1775 }),
1776 );
1777
1778 let search_line = h_flex()
1779 .w_full()
1780 .gap_2()
1781 .child(query_column)
1782 .child(h_flex().min_w_64().child(mode_column).child(matches_column));
1783
1784 let replace_line = search.replace_enabled.then(|| {
1785 let replace_column =
1786 input_base_styles().child(self.render_text_input(&search.replacement_editor, cx));
1787
1788 let focus_handle = search.replacement_editor.read(cx).focus_handle(cx);
1789
1790 let replace_actions =
1791 h_flex()
1792 .min_w_64()
1793 .gap_1()
1794 .when(search.replace_enabled, |this| {
1795 this.child(
1796 IconButton::new("project-search-replace-next", IconName::ReplaceNext)
1797 .shape(IconButtonShape::Square)
1798 .on_click(cx.listener(|this, _, cx| {
1799 if let Some(search) = this.active_project_search.as_ref() {
1800 search.update(cx, |this, cx| {
1801 this.replace_next(&ReplaceNext, cx);
1802 })
1803 }
1804 }))
1805 .tooltip({
1806 let focus_handle = focus_handle.clone();
1807 move |cx| {
1808 Tooltip::for_action_in(
1809 "Replace Next Match",
1810 &ReplaceNext,
1811 &focus_handle,
1812 cx,
1813 )
1814 }
1815 }),
1816 )
1817 .child(
1818 IconButton::new("project-search-replace-all", IconName::ReplaceAll)
1819 .shape(IconButtonShape::Square)
1820 .on_click(cx.listener(|this, _, cx| {
1821 if let Some(search) = this.active_project_search.as_ref() {
1822 search.update(cx, |this, cx| {
1823 this.replace_all(&ReplaceAll, cx);
1824 })
1825 }
1826 }))
1827 .tooltip({
1828 let focus_handle = focus_handle.clone();
1829 move |cx| {
1830 Tooltip::for_action_in(
1831 "Replace All Matches",
1832 &ReplaceAll,
1833 &focus_handle,
1834 cx,
1835 )
1836 }
1837 }),
1838 )
1839 });
1840
1841 h_flex()
1842 .w_full()
1843 .gap_2()
1844 .child(replace_column)
1845 .child(replace_actions)
1846 });
1847
1848 let filter_line = search.filters_enabled.then(|| {
1849 h_flex()
1850 .w_full()
1851 .gap_2()
1852 .child(
1853 input_base_styles()
1854 .on_action(
1855 cx.listener(|this, action, cx| this.previous_history_query(action, cx)),
1856 )
1857 .on_action(
1858 cx.listener(|this, action, cx| this.next_history_query(action, cx)),
1859 )
1860 .child(self.render_text_input(&search.included_files_editor, cx)),
1861 )
1862 .child(
1863 input_base_styles()
1864 .on_action(
1865 cx.listener(|this, action, cx| this.previous_history_query(action, cx)),
1866 )
1867 .on_action(
1868 cx.listener(|this, action, cx| this.next_history_query(action, cx)),
1869 )
1870 .child(self.render_text_input(&search.excluded_files_editor, cx)),
1871 )
1872 .child(
1873 h_flex()
1874 .min_w_64()
1875 .gap_1()
1876 .child(
1877 IconButton::new("project-search-opened-only", IconName::FileSearch)
1878 .shape(IconButtonShape::Square)
1879 .toggle_state(self.is_opened_only_enabled(cx))
1880 .tooltip(|cx| Tooltip::text("Only Search Open Files", cx))
1881 .on_click(cx.listener(|this, _, cx| {
1882 this.toggle_opened_only(cx);
1883 })),
1884 )
1885 .child(
1886 SearchOptions::INCLUDE_IGNORED.as_button(
1887 search
1888 .search_options
1889 .contains(SearchOptions::INCLUDE_IGNORED),
1890 focus_handle.clone(),
1891 cx.listener(|this, _, cx| {
1892 this.toggle_search_option(SearchOptions::INCLUDE_IGNORED, cx);
1893 }),
1894 ),
1895 ),
1896 )
1897 });
1898
1899 let mut key_context = KeyContext::default();
1900
1901 key_context.add("ProjectSearchBar");
1902
1903 if search.replacement_editor.focus_handle(cx).is_focused(cx) {
1904 key_context.add("in_replace");
1905 }
1906
1907 v_flex()
1908 .py(px(1.0))
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}