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