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