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