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