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