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