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