1use crate::{
2 history::SearchHistory, mode::SearchMode, ActivateRegexMode, ActivateSemanticMode,
3 ActivateTextMode, CycleMode, NextHistoryQuery, PreviousHistoryQuery, ReplaceAll, ReplaceNext,
4 SearchOptions, SelectNextMatch, SelectPrevMatch, ToggleCaseSensitive, ToggleIncludeIgnored,
5 ToggleReplace, ToggleWholeWord,
6};
7use anyhow::{Context as _, Result};
8use collections::HashMap;
9use editor::{
10 actions::SelectAll,
11 items::active_match_index,
12 scroll::{Autoscroll, Axis},
13 Anchor, Editor, EditorEvent, MultiBuffer, MAX_TAB_TITLE_LEN,
14};
15use editor::{EditorElement, EditorStyle};
16use gpui::{
17 actions, div, Action, AnyElement, AnyView, AppContext, Context as _, Element, EntityId,
18 EventEmitter, FocusHandle, FocusableView, FontStyle, FontWeight, Global, Hsla,
19 InteractiveElement, IntoElement, KeyContext, Model, ModelContext, ParentElement, Point,
20 PromptLevel, Render, SharedString, Styled, Subscription, Task, TextStyle, View, ViewContext,
21 VisualContext, WeakModel, WeakView, WhiteSpace, WindowContext,
22};
23use menu::Confirm;
24use project::{
25 search::{SearchInputs, SearchQuery},
26 Entry, Project,
27};
28use semantic_index::{SemanticIndex, SemanticIndexStatus};
29
30use collections::HashSet;
31use settings::Settings;
32use smol::stream::StreamExt;
33use std::{
34 any::{Any, TypeId},
35 mem,
36 ops::{Not, Range},
37 path::PathBuf,
38 time::{Duration, Instant},
39};
40use theme::ThemeSettings;
41use workspace::{DeploySearch, NewSearch};
42
43use ui::{
44 h_flex, prelude::*, v_flex, Icon, IconButton, IconName, Label, LabelCommon, LabelSize,
45 Selectable, ToggleButton, Tooltip,
46};
47use util::{paths::PathMatcher, ResultExt as _};
48use workspace::{
49 item::{BreadcrumbText, Item, ItemEvent, ItemHandle},
50 searchable::{Direction, SearchableItem, SearchableItemHandle},
51 ItemNavHistory, Pane, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView, Workspace,
52 WorkspaceId,
53};
54
55const MIN_INPUT_WIDTH_REMS: f32 = 15.;
56const MAX_INPUT_WIDTH_REMS: f32 = 30.;
57
58actions!(
59 project_search,
60 [SearchInNew, ToggleFocus, NextField, ToggleFilters]
61);
62
63#[derive(Default)]
64struct ActiveSettings(HashMap<WeakModel<Project>, ProjectSearchSettings>);
65
66impl Global for ActiveSettings {}
67
68pub fn init(cx: &mut AppContext) {
69 cx.set_global(ActiveSettings::default());
70 cx.observe_new_views(|workspace: &mut Workspace, _cx| {
71 register_workspace_action(workspace, move |search_bar, _: &ToggleFilters, cx| {
72 search_bar.toggle_filters(cx);
73 });
74 register_workspace_action(workspace, move |search_bar, _: &ToggleCaseSensitive, cx| {
75 search_bar.toggle_search_option(SearchOptions::CASE_SENSITIVE, cx);
76 });
77 register_workspace_action(workspace, move |search_bar, _: &ToggleWholeWord, cx| {
78 search_bar.toggle_search_option(SearchOptions::WHOLE_WORD, cx);
79 });
80 register_workspace_action(workspace, move |search_bar, action: &ToggleReplace, cx| {
81 search_bar.toggle_replace(action, cx)
82 });
83 register_workspace_action(workspace, move |search_bar, _: &ActivateRegexMode, cx| {
84 search_bar.activate_search_mode(SearchMode::Regex, cx)
85 });
86 register_workspace_action(workspace, move |search_bar, _: &ActivateTextMode, cx| {
87 search_bar.activate_search_mode(SearchMode::Text, cx)
88 });
89 register_workspace_action(
90 workspace,
91 move |search_bar, _: &ActivateSemanticMode, cx| {
92 search_bar.activate_search_mode(SearchMode::Semantic, cx)
93 },
94 );
95 register_workspace_action(workspace, move |search_bar, action: &CycleMode, cx| {
96 search_bar.cycle_mode(action, cx)
97 });
98 register_workspace_action(
99 workspace,
100 move |search_bar, action: &SelectPrevMatch, cx| {
101 search_bar.select_prev_match(action, cx)
102 },
103 );
104 register_workspace_action(
105 workspace,
106 move |search_bar, action: &SelectNextMatch, cx| {
107 search_bar.select_next_match(action, cx)
108 },
109 );
110
111 // Only handle search_in_new if there is a search present
112 register_workspace_action_for_present_search(workspace, |workspace, action, cx| {
113 ProjectSearchView::search_in_new(workspace, action, cx)
114 });
115
116 // Both on present and dismissed search, we need to unconditionally handle those actions to focus from the editor.
117 workspace.register_action(move |workspace, action: &DeploySearch, cx| {
118 if workspace.has_active_modal(cx) {
119 cx.propagate();
120 return;
121 }
122 ProjectSearchView::deploy_search(workspace, action, cx);
123 cx.notify();
124 });
125 workspace.register_action(move |workspace, action: &NewSearch, cx| {
126 if workspace.has_active_modal(cx) {
127 cx.propagate();
128 return;
129 }
130 ProjectSearchView::new_search(workspace, action, cx);
131 cx.notify();
132 });
133 })
134 .detach();
135}
136
137struct ProjectSearch {
138 project: Model<Project>,
139 excerpts: Model<MultiBuffer>,
140 pending_search: Option<Task<Option<()>>>,
141 match_ranges: Vec<Range<Anchor>>,
142 active_query: Option<SearchQuery>,
143 search_id: usize,
144 search_history: SearchHistory,
145 no_results: Option<bool>,
146}
147
148#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
149enum InputPanel {
150 Query,
151 Exclude,
152 Include,
153}
154
155pub struct ProjectSearchView {
156 focus_handle: FocusHandle,
157 model: Model<ProjectSearch>,
158 query_editor: View<Editor>,
159 replacement_editor: View<Editor>,
160 results_editor: View<Editor>,
161 semantic_state: Option<SemanticState>,
162 semantic_permissioned: Option<bool>,
163 search_options: SearchOptions,
164 panels_with_errors: HashSet<InputPanel>,
165 active_match_index: Option<usize>,
166 search_id: usize,
167 query_editor_was_focused: bool,
168 included_files_editor: View<Editor>,
169 excluded_files_editor: View<Editor>,
170 filters_enabled: bool,
171 replace_enabled: bool,
172 current_mode: SearchMode,
173 _subscriptions: Vec<Subscription>,
174}
175
176struct SemanticState {
177 index_status: SemanticIndexStatus,
178 maintain_rate_limit: Option<Task<()>>,
179 _subscription: Subscription,
180}
181
182#[derive(Debug, Clone)]
183struct ProjectSearchSettings {
184 search_options: SearchOptions,
185 filters_enabled: bool,
186 current_mode: SearchMode,
187}
188
189pub struct ProjectSearchBar {
190 active_project_search: Option<View<ProjectSearchView>>,
191 subscription: Option<Subscription>,
192}
193
194impl ProjectSearch {
195 fn new(project: Model<Project>, cx: &mut ModelContext<Self>) -> Self {
196 let replica_id = project.read(cx).replica_id();
197 let capability = project.read(cx).capability();
198
199 Self {
200 project,
201 excerpts: cx.new_model(|_| MultiBuffer::new(replica_id, capability)),
202 pending_search: Default::default(),
203 match_ranges: Default::default(),
204 active_query: None,
205 search_id: 0,
206 search_history: SearchHistory::default(),
207 no_results: None,
208 }
209 }
210
211 fn clone(&self, cx: &mut ModelContext<Self>) -> Model<Self> {
212 cx.new_model(|cx| Self {
213 project: self.project.clone(),
214 excerpts: self
215 .excerpts
216 .update(cx, |excerpts, cx| cx.new_model(|cx| excerpts.clone(cx))),
217 pending_search: Default::default(),
218 match_ranges: self.match_ranges.clone(),
219 active_query: self.active_query.clone(),
220 search_id: self.search_id,
221 search_history: self.search_history.clone(),
222 no_results: self.no_results,
223 })
224 }
225
226 fn search(&mut self, query: SearchQuery, cx: &mut ModelContext<Self>) {
227 let search = self
228 .project
229 .update(cx, |project, cx| project.search(query.clone(), cx));
230 self.search_id += 1;
231 self.search_history.add(query.as_str().to_string());
232 self.active_query = Some(query);
233 self.match_ranges.clear();
234 self.pending_search = Some(cx.spawn(|this, mut cx| async move {
235 let mut matches = search;
236 let this = this.upgrade()?;
237 this.update(&mut cx, |this, cx| {
238 this.match_ranges.clear();
239 this.excerpts.update(cx, |this, cx| this.clear(cx));
240 this.no_results = Some(true);
241 })
242 .ok()?;
243
244 while let Some((buffer, anchors)) = matches.next().await {
245 let mut ranges = this
246 .update(&mut cx, |this, cx| {
247 this.no_results = Some(false);
248 this.excerpts.update(cx, |excerpts, cx| {
249 excerpts.stream_excerpts_with_context_lines(buffer, anchors, 1, cx)
250 })
251 })
252 .ok()?;
253
254 while let Some(range) = ranges.next().await {
255 this.update(&mut cx, |this, _| this.match_ranges.push(range))
256 .ok()?;
257 }
258 this.update(&mut cx, |_, cx| cx.notify()).ok()?;
259 }
260
261 this.update(&mut cx, |this, cx| {
262 this.pending_search.take();
263 cx.notify();
264 })
265 .ok()?;
266
267 None
268 }));
269 cx.notify();
270 }
271
272 fn semantic_search(&mut self, inputs: &SearchInputs, cx: &mut ModelContext<Self>) {
273 let search = SemanticIndex::global(cx).map(|index| {
274 index.update(cx, |semantic_index, cx| {
275 semantic_index.search_project(
276 self.project.clone(),
277 inputs.as_str().to_owned(),
278 10,
279 inputs.files_to_include().to_vec(),
280 inputs.files_to_exclude().to_vec(),
281 cx,
282 )
283 })
284 });
285 self.search_id += 1;
286 self.match_ranges.clear();
287 self.search_history.add(inputs.as_str().to_string());
288 self.no_results = None;
289 self.pending_search = Some(cx.spawn(|this, mut cx| async move {
290 let results = search?.await.log_err()?;
291 let matches = results
292 .into_iter()
293 .map(|result| (result.buffer, vec![result.range.start..result.range.start]));
294
295 this.update(&mut cx, |this, cx| {
296 this.no_results = Some(true);
297 this.excerpts.update(cx, |excerpts, cx| {
298 excerpts.clear(cx);
299 });
300 })
301 .ok()?;
302 for (buffer, ranges) in matches {
303 let mut match_ranges = this
304 .update(&mut cx, |this, cx| {
305 this.no_results = Some(false);
306 this.excerpts.update(cx, |excerpts, cx| {
307 excerpts.stream_excerpts_with_context_lines(buffer, ranges, 3, cx)
308 })
309 })
310 .ok()?;
311 while let Some(match_range) = match_ranges.next().await {
312 this.update(&mut cx, |this, cx| {
313 this.match_ranges.push(match_range);
314 while let Ok(Some(match_range)) = match_ranges.try_next() {
315 this.match_ranges.push(match_range);
316 }
317 cx.notify();
318 })
319 .ok()?;
320 }
321 }
322
323 this.update(&mut cx, |this, cx| {
324 this.pending_search.take();
325 cx.notify();
326 })
327 .ok()?;
328
329 None
330 }));
331 cx.notify();
332 }
333}
334
335#[derive(Clone, Debug, PartialEq, Eq)]
336pub enum ViewEvent {
337 UpdateTab,
338 Activate,
339 EditorEvent(editor::EditorEvent),
340 Dismiss,
341}
342
343impl EventEmitter<ViewEvent> for ProjectSearchView {}
344
345impl Render for ProjectSearchView {
346 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
347 const PLEASE_AUTHENTICATE: &str = "API Key Missing: Please set 'OPENAI_API_KEY' in Environment Variables. If you authenticated using the Assistant Panel, please restart Zed to Authenticate.";
348
349 if self.has_matches() {
350 div()
351 .flex_1()
352 .size_full()
353 .track_focus(&self.focus_handle)
354 .child(self.results_editor.clone())
355 } else {
356 let model = self.model.read(cx);
357 let has_no_results = model.no_results.unwrap_or(false);
358 let is_search_underway = model.pending_search.is_some();
359 let mut major_text = if is_search_underway {
360 Label::new("Searching...")
361 } else if has_no_results {
362 Label::new("No results")
363 } else {
364 Label::new(format!("{} search all files", self.current_mode.label()))
365 };
366
367 let mut show_minor_text = true;
368 let semantic_status = self.semantic_state.as_ref().and_then(|semantic| {
369 let status = semantic.index_status;
370 match status {
371 SemanticIndexStatus::NotAuthenticated => {
372 major_text = Label::new("Not Authenticated");
373 show_minor_text = false;
374 Some(PLEASE_AUTHENTICATE.to_string())
375 }
376 SemanticIndexStatus::Indexed => Some("Indexing complete".to_string()),
377 SemanticIndexStatus::Indexing {
378 remaining_files,
379 rate_limit_expiry,
380 } => {
381 if remaining_files == 0 {
382 Some("Indexing...".to_string())
383 } else {
384 if let Some(rate_limit_expiry) = rate_limit_expiry {
385 let remaining_seconds =
386 rate_limit_expiry.duration_since(Instant::now());
387 if remaining_seconds > Duration::from_secs(0) {
388 Some(format!(
389 "Remaining files to index (rate limit resets in {}s): {}",
390 remaining_seconds.as_secs(),
391 remaining_files
392 ))
393 } else {
394 Some(format!("Remaining files to index: {}", remaining_files))
395 }
396 } else {
397 Some(format!("Remaining files to index: {}", remaining_files))
398 }
399 }
400 }
401 SemanticIndexStatus::NotIndexed => None,
402 }
403 });
404 let major_text = div().justify_center().max_w_96().child(major_text);
405
406 let minor_text: Option<SharedString> = if let Some(no_results) = model.no_results {
407 if model.pending_search.is_none() && no_results {
408 Some("No results found in this project for the provided query".into())
409 } else {
410 None
411 }
412 } else {
413 if let Some(mut semantic_status) = semantic_status {
414 semantic_status.extend(self.landing_text_minor().chars());
415 Some(semantic_status.into())
416 } else {
417 Some(self.landing_text_minor())
418 }
419 };
420 let minor_text = minor_text.map(|text| {
421 div()
422 .items_center()
423 .max_w_96()
424 .child(Label::new(text).size(LabelSize::Small))
425 });
426 v_flex()
427 .flex_1()
428 .size_full()
429 .justify_center()
430 .bg(cx.theme().colors().editor_background)
431 .track_focus(&self.focus_handle)
432 .child(
433 h_flex()
434 .size_full()
435 .justify_center()
436 .child(h_flex().flex_1())
437 .child(v_flex().child(major_text).children(minor_text))
438 .child(h_flex().flex_1()),
439 )
440 }
441 }
442}
443
444impl FocusableView for ProjectSearchView {
445 fn focus_handle(&self, _: &AppContext) -> gpui::FocusHandle {
446 self.focus_handle.clone()
447 }
448}
449
450impl Item for ProjectSearchView {
451 type Event = ViewEvent;
452 fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
453 let query_text = self.query_editor.read(cx).text(cx);
454
455 query_text
456 .is_empty()
457 .not()
458 .then(|| query_text.into())
459 .or_else(|| Some("Project Search".into()))
460 }
461
462 fn act_as_type<'a>(
463 &'a self,
464 type_id: TypeId,
465 self_handle: &'a View<Self>,
466 _: &'a AppContext,
467 ) -> Option<AnyView> {
468 if type_id == TypeId::of::<Self>() {
469 Some(self_handle.clone().into())
470 } else if type_id == TypeId::of::<Editor>() {
471 Some(self.results_editor.clone().into())
472 } else {
473 None
474 }
475 }
476
477 fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
478 self.results_editor
479 .update(cx, |editor, cx| editor.deactivated(cx));
480 }
481
482 fn tab_content(&self, _: Option<usize>, selected: bool, cx: &WindowContext<'_>) -> AnyElement {
483 let last_query: Option<SharedString> = self
484 .model
485 .read(cx)
486 .search_history
487 .current()
488 .as_ref()
489 .map(|query| {
490 let query = query.replace('\n', "");
491 let query_text = util::truncate_and_trailoff(&query, MAX_TAB_TITLE_LEN);
492 query_text.into()
493 });
494 let tab_name = last_query
495 .filter(|query| !query.is_empty())
496 .unwrap_or_else(|| "Project Search".into());
497 h_flex()
498 .gap_2()
499 .child(Icon::new(IconName::MagnifyingGlass).color(if selected {
500 Color::Default
501 } else {
502 Color::Muted
503 }))
504 .child(Label::new(tab_name).color(if selected {
505 Color::Default
506 } else {
507 Color::Muted
508 }))
509 .into_any()
510 }
511
512 fn telemetry_event_text(&self) -> Option<&'static str> {
513 Some("project search")
514 }
515
516 fn for_each_project_item(
517 &self,
518 cx: &AppContext,
519 f: &mut dyn FnMut(EntityId, &dyn project::Item),
520 ) {
521 self.results_editor.for_each_project_item(cx, f)
522 }
523
524 fn is_singleton(&self, _: &AppContext) -> bool {
525 false
526 }
527
528 fn can_save(&self, _: &AppContext) -> bool {
529 true
530 }
531
532 fn is_dirty(&self, cx: &AppContext) -> bool {
533 self.results_editor.read(cx).is_dirty(cx)
534 }
535
536 fn has_conflict(&self, cx: &AppContext) -> bool {
537 self.results_editor.read(cx).has_conflict(cx)
538 }
539
540 fn save(
541 &mut self,
542 format: bool,
543 project: Model<Project>,
544 cx: &mut ViewContext<Self>,
545 ) -> Task<anyhow::Result<()>> {
546 self.results_editor
547 .update(cx, |editor, cx| editor.save(format, project, cx))
548 }
549
550 fn save_as(
551 &mut self,
552 _: Model<Project>,
553 _: PathBuf,
554 _: &mut ViewContext<Self>,
555 ) -> Task<anyhow::Result<()>> {
556 unreachable!("save_as should not have been called")
557 }
558
559 fn reload(
560 &mut self,
561 project: Model<Project>,
562 cx: &mut ViewContext<Self>,
563 ) -> Task<anyhow::Result<()>> {
564 self.results_editor
565 .update(cx, |editor, cx| editor.reload(project, cx))
566 }
567
568 fn clone_on_split(
569 &self,
570 _workspace_id: WorkspaceId,
571 cx: &mut ViewContext<Self>,
572 ) -> Option<View<Self>>
573 where
574 Self: Sized,
575 {
576 let model = self.model.update(cx, |model, cx| model.clone(cx));
577 Some(cx.new_view(|cx| Self::new(model, cx, None)))
578 }
579
580 fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
581 self.results_editor
582 .update(cx, |editor, cx| editor.added_to_workspace(workspace, cx));
583 }
584
585 fn set_nav_history(&mut self, nav_history: ItemNavHistory, cx: &mut ViewContext<Self>) {
586 self.results_editor.update(cx, |editor, _| {
587 editor.set_nav_history(Some(nav_history));
588 });
589 }
590
591 fn navigate(&mut self, data: Box<dyn Any>, cx: &mut ViewContext<Self>) -> bool {
592 self.results_editor
593 .update(cx, |editor, cx| editor.navigate(data, cx))
594 }
595
596 fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
597 match event {
598 ViewEvent::UpdateTab => {
599 f(ItemEvent::UpdateBreadcrumbs);
600 f(ItemEvent::UpdateTab);
601 }
602 ViewEvent::EditorEvent(editor_event) => {
603 Editor::to_item_events(editor_event, f);
604 }
605 ViewEvent::Dismiss => f(ItemEvent::CloseItem),
606 _ => {}
607 }
608 }
609
610 fn breadcrumb_location(&self) -> ToolbarItemLocation {
611 if self.has_matches() {
612 ToolbarItemLocation::Secondary
613 } else {
614 ToolbarItemLocation::Hidden
615 }
616 }
617
618 fn breadcrumbs(&self, theme: &theme::Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
619 self.results_editor.breadcrumbs(theme, cx)
620 }
621
622 fn serialized_item_kind() -> Option<&'static str> {
623 None
624 }
625
626 fn deserialize(
627 _project: Model<Project>,
628 _workspace: WeakView<Workspace>,
629 _workspace_id: workspace::WorkspaceId,
630 _item_id: workspace::ItemId,
631 _cx: &mut ViewContext<Pane>,
632 ) -> Task<anyhow::Result<View<Self>>> {
633 unimplemented!()
634 }
635}
636
637impl ProjectSearchView {
638 fn toggle_filters(&mut self, cx: &mut ViewContext<Self>) {
639 self.filters_enabled = !self.filters_enabled;
640 cx.update_global(|state: &mut ActiveSettings, cx| {
641 state.0.insert(
642 self.model.read(cx).project.downgrade(),
643 self.current_settings(),
644 );
645 });
646 }
647
648 fn current_settings(&self) -> ProjectSearchSettings {
649 ProjectSearchSettings {
650 search_options: self.search_options,
651 filters_enabled: self.filters_enabled,
652 current_mode: self.current_mode,
653 }
654 }
655 fn toggle_search_option(&mut self, option: SearchOptions, cx: &mut ViewContext<Self>) {
656 self.search_options.toggle(option);
657 cx.update_global(|state: &mut ActiveSettings, cx| {
658 state.0.insert(
659 self.model.read(cx).project.downgrade(),
660 self.current_settings(),
661 );
662 });
663 }
664
665 fn index_project(&mut self, cx: &mut ViewContext<Self>) {
666 if let Some(semantic_index) = SemanticIndex::global(cx) {
667 // Semantic search uses no options
668 self.search_options = SearchOptions::none();
669
670 let project = self.model.read(cx).project.clone();
671
672 semantic_index.update(cx, |semantic_index, cx| {
673 semantic_index
674 .index_project(project.clone(), cx)
675 .detach_and_log_err(cx);
676 });
677
678 self.semantic_state = Some(SemanticState {
679 index_status: semantic_index.read(cx).status(&project),
680 maintain_rate_limit: None,
681 _subscription: cx.observe(&semantic_index, Self::semantic_index_changed),
682 });
683 self.semantic_index_changed(semantic_index, cx);
684 }
685 }
686
687 fn semantic_index_changed(
688 &mut self,
689 semantic_index: Model<SemanticIndex>,
690 cx: &mut ViewContext<Self>,
691 ) {
692 let project = self.model.read(cx).project.clone();
693 if let Some(semantic_state) = self.semantic_state.as_mut() {
694 cx.notify();
695 semantic_state.index_status = semantic_index.read(cx).status(&project);
696 if let SemanticIndexStatus::Indexing {
697 rate_limit_expiry: Some(_),
698 ..
699 } = &semantic_state.index_status
700 {
701 if semantic_state.maintain_rate_limit.is_none() {
702 semantic_state.maintain_rate_limit =
703 Some(cx.spawn(|this, mut cx| async move {
704 loop {
705 cx.background_executor().timer(Duration::from_secs(1)).await;
706 this.update(&mut cx, |_, cx| cx.notify()).log_err();
707 }
708 }));
709 return;
710 }
711 } else {
712 semantic_state.maintain_rate_limit = None;
713 }
714 }
715 }
716
717 fn clear_search(&mut self, cx: &mut ViewContext<Self>) {
718 self.model.update(cx, |model, cx| {
719 model.pending_search = None;
720 model.no_results = None;
721 model.match_ranges.clear();
722
723 model.excerpts.update(cx, |excerpts, cx| {
724 excerpts.clear(cx);
725 });
726 });
727 }
728
729 fn activate_search_mode(&mut self, mode: SearchMode, cx: &mut ViewContext<Self>) {
730 let previous_mode = self.current_mode;
731 if previous_mode == mode {
732 return;
733 }
734
735 self.clear_search(cx);
736 self.current_mode = mode;
737 self.active_match_index = None;
738
739 match mode {
740 SearchMode::Semantic => {
741 let has_permission = self.semantic_permissioned(cx);
742 self.active_match_index = None;
743 cx.spawn(|this, mut cx| async move {
744 let has_permission = has_permission.await?;
745
746 if !has_permission {
747 let answer = this.update(&mut cx, |this, cx| {
748 let project = this.model.read(cx).project.clone();
749 let project_name = project
750 .read(cx)
751 .worktree_root_names(cx)
752 .collect::<Vec<&str>>()
753 .join("/");
754 let is_plural =
755 project_name.chars().filter(|letter| *letter == '/').count() > 0;
756 let prompt_text = format!("Would you like to index the '{}' project{} for semantic search? This requires sending code to the OpenAI API", project_name,
757 if is_plural {
758 "s"
759 } else {""});
760 cx.prompt(
761 PromptLevel::Info,
762 prompt_text.as_str(),
763 None,
764 &["Continue", "Cancel"],
765 )
766 })?;
767
768 if answer.await? == 0 {
769 this.update(&mut cx, |this, _| {
770 this.semantic_permissioned = Some(true);
771 })?;
772 } else {
773 this.update(&mut cx, |this, cx| {
774 this.semantic_permissioned = Some(false);
775 debug_assert_ne!(previous_mode, SearchMode::Semantic, "Tried to re-enable semantic search mode after user modal was rejected");
776 this.activate_search_mode(previous_mode, cx);
777 })?;
778 return anyhow::Ok(());
779 }
780 }
781
782 this.update(&mut cx, |this, cx| {
783 this.index_project(cx);
784 })?;
785
786 anyhow::Ok(())
787 }).detach_and_log_err(cx);
788 }
789 SearchMode::Regex | SearchMode::Text => {
790 self.semantic_state = None;
791 self.active_match_index = None;
792 self.search(cx);
793 }
794 }
795
796 cx.update_global(|state: &mut ActiveSettings, cx| {
797 state.0.insert(
798 self.model.read(cx).project.downgrade(),
799 self.current_settings(),
800 );
801 });
802
803 cx.notify();
804 }
805 fn replace_next(&mut self, _: &ReplaceNext, cx: &mut ViewContext<Self>) {
806 let model = self.model.read(cx);
807 if let Some(query) = model.active_query.as_ref() {
808 if model.match_ranges.is_empty() {
809 return;
810 }
811 if let Some(active_index) = self.active_match_index {
812 let query = query.clone().with_replacement(self.replacement(cx));
813 self.results_editor.replace(
814 &(Box::new(model.match_ranges[active_index].clone()) as _),
815 &query,
816 cx,
817 );
818 self.select_match(Direction::Next, cx)
819 }
820 }
821 }
822 pub fn replacement(&self, cx: &AppContext) -> String {
823 self.replacement_editor.read(cx).text(cx)
824 }
825 fn replace_all(&mut self, _: &ReplaceAll, cx: &mut ViewContext<Self>) {
826 let model = self.model.read(cx);
827 if let Some(query) = model.active_query.as_ref() {
828 if model.match_ranges.is_empty() {
829 return;
830 }
831 if self.active_match_index.is_some() {
832 let query = query.clone().with_replacement(self.replacement(cx));
833 let matches = model
834 .match_ranges
835 .iter()
836 .map(|item| Box::new(item.clone()) as _)
837 .collect::<Vec<_>>();
838 for item in matches {
839 self.results_editor.replace(&item, &query, cx);
840 }
841 }
842 }
843 }
844
845 fn new(
846 model: Model<ProjectSearch>,
847 cx: &mut ViewContext<Self>,
848 settings: Option<ProjectSearchSettings>,
849 ) -> Self {
850 let project;
851 let excerpts;
852 let mut replacement_text = None;
853 let mut query_text = String::new();
854 let mut subscriptions = Vec::new();
855
856 // Read in settings if available
857 let (mut options, current_mode, filters_enabled) = if let Some(settings) = settings {
858 (
859 settings.search_options,
860 settings.current_mode,
861 settings.filters_enabled,
862 )
863 } else {
864 (SearchOptions::NONE, Default::default(), false)
865 };
866
867 {
868 let model = model.read(cx);
869 project = model.project.clone();
870 excerpts = model.excerpts.clone();
871 if let Some(active_query) = model.active_query.as_ref() {
872 query_text = active_query.as_str().to_string();
873 replacement_text = active_query.replacement().map(ToOwned::to_owned);
874 options = SearchOptions::from_query(active_query);
875 }
876 }
877 subscriptions.push(cx.observe(&model, |this, _, cx| this.model_changed(cx)));
878
879 let query_editor = cx.new_view(|cx| {
880 let mut editor = Editor::single_line(cx);
881 editor.set_placeholder_text("Text search all files", cx);
882 editor.set_text(query_text, cx);
883 editor
884 });
885 // Subscribe to query_editor in order to reraise editor events for workspace item activation purposes
886 subscriptions.push(
887 cx.subscribe(&query_editor, |_, _, event: &EditorEvent, cx| {
888 cx.emit(ViewEvent::EditorEvent(event.clone()))
889 }),
890 );
891 let replacement_editor = cx.new_view(|cx| {
892 let mut editor = Editor::single_line(cx);
893 editor.set_placeholder_text("Replace in project..", cx);
894 if let Some(text) = replacement_text {
895 editor.set_text(text, cx);
896 }
897 editor
898 });
899 let results_editor = cx.new_view(|cx| {
900 let mut editor = Editor::for_multibuffer(excerpts, Some(project.clone()), cx);
901 editor.set_searchable(false);
902 editor
903 });
904 subscriptions.push(cx.observe(&results_editor, |_, _, cx| cx.emit(ViewEvent::UpdateTab)));
905
906 subscriptions.push(
907 cx.subscribe(&results_editor, |this, _, event: &EditorEvent, cx| {
908 if matches!(event, editor::EditorEvent::SelectionsChanged { .. }) {
909 this.update_match_index(cx);
910 }
911 // Reraise editor events for workspace item activation purposes
912 cx.emit(ViewEvent::EditorEvent(event.clone()));
913 }),
914 );
915
916 let included_files_editor = cx.new_view(|cx| {
917 let mut editor = Editor::single_line(cx);
918 editor.set_placeholder_text("Include: crates/**/*.toml", cx);
919
920 editor
921 });
922 // Subscribe to include_files_editor in order to reraise editor events for workspace item activation purposes
923 subscriptions.push(
924 cx.subscribe(&included_files_editor, |_, _, event: &EditorEvent, cx| {
925 cx.emit(ViewEvent::EditorEvent(event.clone()))
926 }),
927 );
928
929 let excluded_files_editor = cx.new_view(|cx| {
930 let mut editor = Editor::single_line(cx);
931 editor.set_placeholder_text("Exclude: vendor/*, *.lock", cx);
932
933 editor
934 });
935 // Subscribe to excluded_files_editor in order to reraise editor events for workspace item activation purposes
936 subscriptions.push(
937 cx.subscribe(&excluded_files_editor, |_, _, event: &EditorEvent, cx| {
938 cx.emit(ViewEvent::EditorEvent(event.clone()))
939 }),
940 );
941
942 let focus_handle = cx.focus_handle();
943 subscriptions.push(cx.on_focus_in(&focus_handle, |this, cx| {
944 if this.focus_handle.is_focused(cx) {
945 if this.has_matches() {
946 this.results_editor.focus_handle(cx).focus(cx);
947 } else {
948 this.query_editor.focus_handle(cx).focus(cx);
949 }
950 }
951 }));
952
953 // Check if Worktrees have all been previously indexed
954 let mut this = ProjectSearchView {
955 focus_handle,
956 replacement_editor,
957 search_id: model.read(cx).search_id,
958 model,
959 query_editor,
960 results_editor,
961 semantic_state: None,
962 semantic_permissioned: None,
963 search_options: options,
964 panels_with_errors: HashSet::default(),
965 active_match_index: None,
966 query_editor_was_focused: false,
967 included_files_editor,
968 excluded_files_editor,
969 filters_enabled,
970 current_mode,
971 replace_enabled: false,
972 _subscriptions: subscriptions,
973 };
974 this.model_changed(cx);
975 this
976 }
977
978 fn semantic_permissioned(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<bool>> {
979 if let Some(value) = self.semantic_permissioned {
980 return Task::ready(Ok(value));
981 }
982
983 SemanticIndex::global(cx)
984 .map(|semantic| {
985 let project = self.model.read(cx).project.clone();
986 semantic.update(cx, |this, cx| this.project_previously_indexed(&project, cx))
987 })
988 .unwrap_or(Task::ready(Ok(false)))
989 }
990
991 pub fn new_search_in_directory(
992 workspace: &mut Workspace,
993 dir_entry: &Entry,
994 cx: &mut ViewContext<Workspace>,
995 ) {
996 if !dir_entry.is_dir() {
997 return;
998 }
999 let Some(filter_str) = dir_entry.path.to_str() else {
1000 return;
1001 };
1002
1003 let model = cx.new_model(|cx| ProjectSearch::new(workspace.project().clone(), cx));
1004 let search = cx.new_view(|cx| ProjectSearchView::new(model, cx, None));
1005 workspace.add_item_to_active_pane(Box::new(search.clone()), cx);
1006 search.update(cx, |search, cx| {
1007 search
1008 .included_files_editor
1009 .update(cx, |editor, cx| editor.set_text(filter_str, cx));
1010 search.filters_enabled = true;
1011 search.focus_query_editor(cx)
1012 });
1013 }
1014
1015 // Re-activate the most recently activated search in this pane or the most recent if it has been closed.
1016 // If no search exists in the workspace, create a new one.
1017 fn deploy_search(
1018 workspace: &mut Workspace,
1019 _: &workspace::DeploySearch,
1020 cx: &mut ViewContext<Workspace>,
1021 ) {
1022 let existing = workspace
1023 .active_pane()
1024 .read(cx)
1025 .items()
1026 .find_map(|item| item.downcast::<ProjectSearchView>());
1027
1028 Self::existing_or_new_search(workspace, existing, cx)
1029 }
1030
1031 fn search_in_new(workspace: &mut Workspace, _: &SearchInNew, cx: &mut ViewContext<Workspace>) {
1032 if let Some(search_view) = workspace
1033 .active_item(cx)
1034 .and_then(|item| item.downcast::<ProjectSearchView>())
1035 {
1036 let new_query = search_view.update(cx, |search_view, cx| {
1037 let new_query = search_view.build_search_query(cx);
1038 if new_query.is_some() {
1039 if let Some(old_query) = search_view.model.read(cx).active_query.clone() {
1040 search_view.query_editor.update(cx, |editor, cx| {
1041 editor.set_text(old_query.as_str(), cx);
1042 });
1043 search_view.search_options = SearchOptions::from_query(&old_query);
1044 }
1045 }
1046 new_query
1047 });
1048 if let Some(new_query) = new_query {
1049 let model = cx.new_model(|cx| {
1050 let mut model = ProjectSearch::new(workspace.project().clone(), cx);
1051 model.search(new_query, cx);
1052 model
1053 });
1054 workspace.add_item_to_active_pane(
1055 Box::new(cx.new_view(|cx| ProjectSearchView::new(model, cx, None))),
1056 cx,
1057 );
1058 }
1059 }
1060 }
1061
1062 // Add another search tab to the workspace.
1063 fn new_search(
1064 workspace: &mut Workspace,
1065 _: &workspace::NewSearch,
1066 cx: &mut ViewContext<Workspace>,
1067 ) {
1068 Self::existing_or_new_search(workspace, None, cx)
1069 }
1070
1071 fn existing_or_new_search(
1072 workspace: &mut Workspace,
1073 existing: Option<View<ProjectSearchView>>,
1074 cx: &mut ViewContext<Workspace>,
1075 ) {
1076 let query = workspace.active_item(cx).and_then(|item| {
1077 let editor = item.act_as::<Editor>(cx)?;
1078 let query = editor.query_suggestion(cx);
1079 if query.is_empty() {
1080 None
1081 } else {
1082 Some(query)
1083 }
1084 });
1085
1086 let search = if let Some(existing) = existing {
1087 workspace.activate_item(&existing, cx);
1088 existing
1089 } else {
1090 let settings = cx
1091 .global::<ActiveSettings>()
1092 .0
1093 .get(&workspace.project().downgrade());
1094
1095 let settings = if let Some(settings) = settings {
1096 Some(settings.clone())
1097 } else {
1098 None
1099 };
1100
1101 let model = cx.new_model(|cx| ProjectSearch::new(workspace.project().clone(), cx));
1102 let view = cx.new_view(|cx| ProjectSearchView::new(model, cx, settings));
1103
1104 workspace.add_item_to_active_pane(Box::new(view.clone()), cx);
1105 view
1106 };
1107
1108 search.update(cx, |search, cx| {
1109 if let Some(query) = query {
1110 search.set_query(&query, cx);
1111 }
1112 search.focus_query_editor(cx)
1113 });
1114 }
1115
1116 fn search(&mut self, cx: &mut ViewContext<Self>) {
1117 let mode = self.current_mode;
1118 match mode {
1119 SearchMode::Semantic => {
1120 if self.semantic_state.is_some() {
1121 if let Some(query) = self.build_search_query(cx) {
1122 self.model
1123 .update(cx, |model, cx| model.semantic_search(query.as_inner(), cx));
1124 }
1125 }
1126 }
1127
1128 _ => {
1129 if let Some(query) = self.build_search_query(cx) {
1130 self.model.update(cx, |model, cx| model.search(query, cx));
1131 }
1132 }
1133 }
1134 }
1135
1136 fn build_search_query(&mut self, cx: &mut ViewContext<Self>) -> Option<SearchQuery> {
1137 // Do not bail early in this function, as we want to fill out `self.panels_with_errors`.
1138 let text = self.query_editor.read(cx).text(cx);
1139 let included_files =
1140 match Self::parse_path_matches(&self.included_files_editor.read(cx).text(cx)) {
1141 Ok(included_files) => {
1142 let should_unmark_error = self.panels_with_errors.remove(&InputPanel::Include);
1143 if should_unmark_error {
1144 cx.notify();
1145 }
1146 included_files
1147 }
1148 Err(_e) => {
1149 let should_mark_error = self.panels_with_errors.insert(InputPanel::Include);
1150 if should_mark_error {
1151 cx.notify();
1152 }
1153 vec![]
1154 }
1155 };
1156 let excluded_files =
1157 match Self::parse_path_matches(&self.excluded_files_editor.read(cx).text(cx)) {
1158 Ok(excluded_files) => {
1159 let should_unmark_error = self.panels_with_errors.remove(&InputPanel::Exclude);
1160 if should_unmark_error {
1161 cx.notify();
1162 }
1163
1164 excluded_files
1165 }
1166 Err(_e) => {
1167 let should_mark_error = self.panels_with_errors.insert(InputPanel::Exclude);
1168 if should_mark_error {
1169 cx.notify();
1170 }
1171 vec![]
1172 }
1173 };
1174
1175 let current_mode = self.current_mode;
1176 let query = match current_mode {
1177 SearchMode::Regex => {
1178 match SearchQuery::regex(
1179 text,
1180 self.search_options.contains(SearchOptions::WHOLE_WORD),
1181 self.search_options.contains(SearchOptions::CASE_SENSITIVE),
1182 self.search_options.contains(SearchOptions::INCLUDE_IGNORED),
1183 included_files,
1184 excluded_files,
1185 ) {
1186 Ok(query) => {
1187 let should_unmark_error =
1188 self.panels_with_errors.remove(&InputPanel::Query);
1189 if should_unmark_error {
1190 cx.notify();
1191 }
1192
1193 Some(query)
1194 }
1195 Err(_e) => {
1196 let should_mark_error = self.panels_with_errors.insert(InputPanel::Query);
1197 if should_mark_error {
1198 cx.notify();
1199 }
1200
1201 None
1202 }
1203 }
1204 }
1205 _ => match SearchQuery::text(
1206 text,
1207 self.search_options.contains(SearchOptions::WHOLE_WORD),
1208 self.search_options.contains(SearchOptions::CASE_SENSITIVE),
1209 self.search_options.contains(SearchOptions::INCLUDE_IGNORED),
1210 included_files,
1211 excluded_files,
1212 ) {
1213 Ok(query) => {
1214 let should_unmark_error = self.panels_with_errors.remove(&InputPanel::Query);
1215 if should_unmark_error {
1216 cx.notify();
1217 }
1218
1219 Some(query)
1220 }
1221 Err(_e) => {
1222 let should_mark_error = self.panels_with_errors.insert(InputPanel::Query);
1223 if should_mark_error {
1224 cx.notify();
1225 }
1226
1227 None
1228 }
1229 },
1230 };
1231 if !self.panels_with_errors.is_empty() {
1232 return None;
1233 }
1234 query
1235 }
1236
1237 fn parse_path_matches(text: &str) -> anyhow::Result<Vec<PathMatcher>> {
1238 text.split(',')
1239 .map(str::trim)
1240 .filter(|maybe_glob_str| !maybe_glob_str.is_empty())
1241 .map(|maybe_glob_str| {
1242 PathMatcher::new(maybe_glob_str)
1243 .with_context(|| format!("parsing {maybe_glob_str} as path matcher"))
1244 })
1245 .collect()
1246 }
1247
1248 fn select_match(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
1249 if let Some(index) = self.active_match_index {
1250 let match_ranges = self.model.read(cx).match_ranges.clone();
1251 let new_index = self.results_editor.update(cx, |editor, cx| {
1252 editor.match_index_for_direction(&match_ranges, index, direction, 1, cx)
1253 });
1254
1255 let range_to_select = match_ranges[new_index].clone();
1256 self.results_editor.update(cx, |editor, cx| {
1257 let range_to_select = editor.range_for_match(&range_to_select);
1258 editor.unfold_ranges([range_to_select.clone()], false, true, cx);
1259 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
1260 s.select_ranges([range_to_select])
1261 });
1262 });
1263 }
1264 }
1265
1266 fn focus_query_editor(&mut self, cx: &mut ViewContext<Self>) {
1267 self.query_editor.update(cx, |query_editor, cx| {
1268 query_editor.select_all(&SelectAll, cx);
1269 });
1270 self.query_editor_was_focused = true;
1271 let editor_handle = self.query_editor.focus_handle(cx);
1272 cx.focus(&editor_handle);
1273 }
1274
1275 fn set_query(&mut self, query: &str, cx: &mut ViewContext<Self>) {
1276 self.query_editor
1277 .update(cx, |query_editor, cx| query_editor.set_text(query, cx));
1278 }
1279
1280 fn focus_results_editor(&mut self, cx: &mut ViewContext<Self>) {
1281 self.query_editor.update(cx, |query_editor, cx| {
1282 let cursor = query_editor.selections.newest_anchor().head();
1283 query_editor.change_selections(None, cx, |s| s.select_ranges([cursor..cursor]));
1284 });
1285 self.query_editor_was_focused = false;
1286 let results_handle = self.results_editor.focus_handle(cx);
1287 cx.focus(&results_handle);
1288 }
1289
1290 fn model_changed(&mut self, cx: &mut ViewContext<Self>) {
1291 let match_ranges = self.model.read(cx).match_ranges.clone();
1292 if match_ranges.is_empty() {
1293 self.active_match_index = None;
1294 } else {
1295 self.active_match_index = Some(0);
1296 self.update_match_index(cx);
1297 let prev_search_id = mem::replace(&mut self.search_id, self.model.read(cx).search_id);
1298 let is_new_search = self.search_id != prev_search_id;
1299 self.results_editor.update(cx, |editor, cx| {
1300 if is_new_search {
1301 let range_to_select = match_ranges
1302 .first()
1303 .map(|range| editor.range_for_match(range));
1304 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
1305 s.select_ranges(range_to_select)
1306 });
1307 editor.scroll(Point::default(), Some(Axis::Vertical), cx);
1308 }
1309 editor.highlight_background::<Self>(
1310 match_ranges,
1311 |theme| theme.search_match_background,
1312 cx,
1313 );
1314 });
1315 if is_new_search && self.query_editor.focus_handle(cx).is_focused(cx) {
1316 self.focus_results_editor(cx);
1317 }
1318 }
1319
1320 cx.emit(ViewEvent::UpdateTab);
1321 cx.notify();
1322 }
1323
1324 fn update_match_index(&mut self, cx: &mut ViewContext<Self>) {
1325 let results_editor = self.results_editor.read(cx);
1326 let new_index = active_match_index(
1327 &self.model.read(cx).match_ranges,
1328 &results_editor.selections.newest_anchor().head(),
1329 &results_editor.buffer().read(cx).snapshot(cx),
1330 );
1331 if self.active_match_index != new_index {
1332 self.active_match_index = new_index;
1333 cx.notify();
1334 }
1335 }
1336
1337 pub fn has_matches(&self) -> bool {
1338 self.active_match_index.is_some()
1339 }
1340
1341 fn landing_text_minor(&self) -> SharedString {
1342 match self.current_mode {
1343 SearchMode::Text | SearchMode::Regex => "Include/exclude specific paths with the filter option. Matching exact word and/or casing is available too.".into(),
1344 SearchMode::Semantic => "\nSimply explain the code you are looking to find. ex. 'prompt user for permissions to index their project'".into()
1345 }
1346 }
1347 fn border_color_for(&self, panel: InputPanel, cx: &WindowContext) -> Hsla {
1348 if self.panels_with_errors.contains(&panel) {
1349 Color::Error.color(cx)
1350 } else {
1351 cx.theme().colors().border
1352 }
1353 }
1354 fn move_focus_to_results(&mut self, cx: &mut ViewContext<Self>) {
1355 if !self.results_editor.focus_handle(cx).is_focused(cx)
1356 && !self.model.read(cx).match_ranges.is_empty()
1357 {
1358 cx.stop_propagation();
1359 return self.focus_results_editor(cx);
1360 }
1361 }
1362}
1363
1364impl ProjectSearchBar {
1365 pub fn new() -> Self {
1366 Self {
1367 active_project_search: None,
1368 subscription: None,
1369 }
1370 }
1371
1372 fn cycle_mode(&self, _: &CycleMode, cx: &mut ViewContext<Self>) {
1373 if let Some(view) = self.active_project_search.as_ref() {
1374 view.update(cx, |this, cx| {
1375 let new_mode =
1376 crate::mode::next_mode(&this.current_mode, SemanticIndex::enabled(cx));
1377 this.activate_search_mode(new_mode, cx);
1378 let editor_handle = this.query_editor.focus_handle(cx);
1379 cx.focus(&editor_handle);
1380 });
1381 }
1382 }
1383
1384 fn confirm(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
1385 if let Some(search_view) = self.active_project_search.as_ref() {
1386 search_view.update(cx, |search_view, cx| {
1387 if !search_view
1388 .replacement_editor
1389 .focus_handle(cx)
1390 .is_focused(cx)
1391 {
1392 cx.stop_propagation();
1393 search_view.search(cx);
1394 }
1395 });
1396 }
1397 }
1398
1399 fn tab(&mut self, _: &editor::actions::Tab, cx: &mut ViewContext<Self>) {
1400 self.cycle_field(Direction::Next, cx);
1401 }
1402
1403 fn tab_previous(&mut self, _: &editor::actions::TabPrev, cx: &mut ViewContext<Self>) {
1404 self.cycle_field(Direction::Prev, cx);
1405 }
1406
1407 fn cycle_field(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
1408 let active_project_search = match &self.active_project_search {
1409 Some(active_project_search) => active_project_search,
1410
1411 None => {
1412 return;
1413 }
1414 };
1415
1416 active_project_search.update(cx, |project_view, cx| {
1417 let mut views = vec![&project_view.query_editor];
1418 if project_view.replace_enabled {
1419 views.push(&project_view.replacement_editor);
1420 }
1421 if project_view.filters_enabled {
1422 views.extend([
1423 &project_view.included_files_editor,
1424 &project_view.excluded_files_editor,
1425 ]);
1426 }
1427 let current_index = match views
1428 .iter()
1429 .enumerate()
1430 .find(|(_, view)| view.focus_handle(cx).is_focused(cx))
1431 {
1432 Some((index, _)) => index,
1433 None => return,
1434 };
1435
1436 let new_index = match direction {
1437 Direction::Next => (current_index + 1) % views.len(),
1438 Direction::Prev if current_index == 0 => views.len() - 1,
1439 Direction::Prev => (current_index - 1) % views.len(),
1440 };
1441 let next_focus_handle = views[new_index].focus_handle(cx);
1442 cx.focus(&next_focus_handle);
1443 cx.stop_propagation();
1444 });
1445 }
1446
1447 fn toggle_search_option(&mut self, option: SearchOptions, cx: &mut ViewContext<Self>) -> bool {
1448 if let Some(search_view) = self.active_project_search.as_ref() {
1449 search_view.update(cx, |search_view, cx| {
1450 search_view.toggle_search_option(option, cx);
1451 search_view.search(cx);
1452 });
1453
1454 cx.notify();
1455 true
1456 } else {
1457 false
1458 }
1459 }
1460
1461 fn toggle_replace(&mut self, _: &ToggleReplace, cx: &mut ViewContext<Self>) {
1462 if let Some(search) = &self.active_project_search {
1463 search.update(cx, |this, cx| {
1464 this.replace_enabled = !this.replace_enabled;
1465 let editor_to_focus = if !this.replace_enabled {
1466 this.query_editor.focus_handle(cx)
1467 } else {
1468 this.replacement_editor.focus_handle(cx)
1469 };
1470 cx.focus(&editor_to_focus);
1471 cx.notify();
1472 });
1473 }
1474 }
1475
1476 fn toggle_filters(&mut self, cx: &mut ViewContext<Self>) -> bool {
1477 if let Some(search_view) = self.active_project_search.as_ref() {
1478 search_view.update(cx, |search_view, cx| {
1479 search_view.toggle_filters(cx);
1480 search_view
1481 .included_files_editor
1482 .update(cx, |_, cx| cx.notify());
1483 search_view
1484 .excluded_files_editor
1485 .update(cx, |_, cx| cx.notify());
1486 cx.refresh();
1487 cx.notify();
1488 });
1489 cx.notify();
1490 true
1491 } else {
1492 false
1493 }
1494 }
1495
1496 fn move_focus_to_results(&self, cx: &mut ViewContext<Self>) {
1497 if let Some(search_view) = self.active_project_search.as_ref() {
1498 search_view.update(cx, |search_view, cx| {
1499 search_view.move_focus_to_results(cx);
1500 });
1501 cx.notify();
1502 }
1503 }
1504
1505 fn activate_search_mode(&self, mode: SearchMode, cx: &mut ViewContext<Self>) {
1506 // Update Current Mode
1507 if let Some(search_view) = self.active_project_search.as_ref() {
1508 search_view.update(cx, |search_view, cx| {
1509 search_view.activate_search_mode(mode, cx);
1510 });
1511 cx.notify();
1512 }
1513 }
1514
1515 fn is_option_enabled(&self, option: SearchOptions, cx: &AppContext) -> bool {
1516 if let Some(search) = self.active_project_search.as_ref() {
1517 search.read(cx).search_options.contains(option)
1518 } else {
1519 false
1520 }
1521 }
1522
1523 fn next_history_query(&mut self, _: &NextHistoryQuery, cx: &mut ViewContext<Self>) {
1524 if let Some(search_view) = self.active_project_search.as_ref() {
1525 search_view.update(cx, |search_view, cx| {
1526 let new_query = search_view.model.update(cx, |model, _| {
1527 if let Some(new_query) = model.search_history.next().map(str::to_string) {
1528 new_query
1529 } else {
1530 model.search_history.reset_selection();
1531 String::new()
1532 }
1533 });
1534 search_view.set_query(&new_query, cx);
1535 });
1536 }
1537 }
1538
1539 fn previous_history_query(&mut self, _: &PreviousHistoryQuery, cx: &mut ViewContext<Self>) {
1540 if let Some(search_view) = self.active_project_search.as_ref() {
1541 search_view.update(cx, |search_view, cx| {
1542 if search_view.query_editor.read(cx).text(cx).is_empty() {
1543 if let Some(new_query) = search_view
1544 .model
1545 .read(cx)
1546 .search_history
1547 .current()
1548 .map(str::to_string)
1549 {
1550 search_view.set_query(&new_query, cx);
1551 return;
1552 }
1553 }
1554
1555 if let Some(new_query) = search_view.model.update(cx, |model, _| {
1556 model.search_history.previous().map(str::to_string)
1557 }) {
1558 search_view.set_query(&new_query, cx);
1559 }
1560 });
1561 }
1562 }
1563
1564 fn select_next_match(&mut self, _: &SelectNextMatch, cx: &mut ViewContext<Self>) {
1565 if let Some(search) = self.active_project_search.as_ref() {
1566 search.update(cx, |this, cx| {
1567 this.select_match(Direction::Next, cx);
1568 })
1569 }
1570 }
1571
1572 fn select_prev_match(&mut self, _: &SelectPrevMatch, cx: &mut ViewContext<Self>) {
1573 if let Some(search) = self.active_project_search.as_ref() {
1574 search.update(cx, |this, cx| {
1575 this.select_match(Direction::Prev, cx);
1576 })
1577 }
1578 }
1579
1580 fn new_placeholder_text(&self, cx: &mut ViewContext<Self>) -> Option<String> {
1581 let previous_query_keystrokes = cx
1582 .bindings_for_action(&PreviousHistoryQuery {})
1583 .into_iter()
1584 .next()
1585 .map(|binding| {
1586 binding
1587 .keystrokes()
1588 .iter()
1589 .map(|k| k.to_string())
1590 .collect::<Vec<_>>()
1591 });
1592 let next_query_keystrokes = cx
1593 .bindings_for_action(&NextHistoryQuery {})
1594 .into_iter()
1595 .next()
1596 .map(|binding| {
1597 binding
1598 .keystrokes()
1599 .iter()
1600 .map(|k| k.to_string())
1601 .collect::<Vec<_>>()
1602 });
1603 let new_placeholder_text = match (previous_query_keystrokes, next_query_keystrokes) {
1604 (Some(previous_query_keystrokes), Some(next_query_keystrokes)) => Some(format!(
1605 "Search ({}/{} for previous/next query)",
1606 previous_query_keystrokes.join(" "),
1607 next_query_keystrokes.join(" ")
1608 )),
1609 (None, Some(next_query_keystrokes)) => Some(format!(
1610 "Search ({} for next query)",
1611 next_query_keystrokes.join(" ")
1612 )),
1613 (Some(previous_query_keystrokes), None) => Some(format!(
1614 "Search ({} for previous query)",
1615 previous_query_keystrokes.join(" ")
1616 )),
1617 (None, None) => None,
1618 };
1619 new_placeholder_text
1620 }
1621
1622 fn render_text_input(&self, editor: &View<Editor>, cx: &ViewContext<Self>) -> impl IntoElement {
1623 let settings = ThemeSettings::get_global(cx);
1624 let text_style = TextStyle {
1625 color: if editor.read(cx).read_only(cx) {
1626 cx.theme().colors().text_disabled
1627 } else {
1628 cx.theme().colors().text
1629 },
1630 font_family: settings.ui_font.family.clone(),
1631 font_features: settings.ui_font.features,
1632 font_size: rems(0.875).into(),
1633 font_weight: FontWeight::NORMAL,
1634 font_style: FontStyle::Normal,
1635 line_height: relative(1.3),
1636 background_color: None,
1637 underline: None,
1638 strikethrough: None,
1639 white_space: WhiteSpace::Normal,
1640 };
1641
1642 EditorElement::new(
1643 &editor,
1644 EditorStyle {
1645 background: cx.theme().colors().editor_background,
1646 local_player: cx.theme().players().local(),
1647 text: text_style,
1648 ..Default::default()
1649 },
1650 )
1651 }
1652}
1653
1654impl Render for ProjectSearchBar {
1655 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
1656 let Some(search) = self.active_project_search.clone() else {
1657 return div();
1658 };
1659 let mut key_context = KeyContext::default();
1660 key_context.add("ProjectSearchBar");
1661 if let Some(placeholder_text) = self.new_placeholder_text(cx) {
1662 search.update(cx, |search, cx| {
1663 search.query_editor.update(cx, |this, cx| {
1664 this.set_placeholder_text(placeholder_text, cx)
1665 })
1666 });
1667 }
1668 let search = search.read(cx);
1669 let semantic_is_available = SemanticIndex::enabled(cx);
1670
1671 let query_column = h_flex()
1672 .flex_1()
1673 .px_2()
1674 .py_1()
1675 .border_1()
1676 .border_color(search.border_color_for(InputPanel::Query, cx))
1677 .rounded_lg()
1678 .min_w(rems(MIN_INPUT_WIDTH_REMS))
1679 .max_w(rems(MAX_INPUT_WIDTH_REMS))
1680 .on_action(cx.listener(|this, action, cx| this.confirm(action, cx)))
1681 .on_action(cx.listener(|this, action, cx| this.previous_history_query(action, cx)))
1682 .on_action(cx.listener(|this, action, cx| this.next_history_query(action, cx)))
1683 .child(self.render_text_input(&search.query_editor, cx))
1684 .child(
1685 h_flex()
1686 .child(
1687 IconButton::new("project-search-filter-button", IconName::Filter)
1688 .tooltip(|cx| Tooltip::for_action("Toggle filters", &ToggleFilters, cx))
1689 .on_click(cx.listener(|this, _, cx| {
1690 this.toggle_filters(cx);
1691 }))
1692 .selected(
1693 self.active_project_search
1694 .as_ref()
1695 .map(|search| search.read(cx).filters_enabled)
1696 .unwrap_or_default(),
1697 ),
1698 )
1699 .when(search.current_mode != SearchMode::Semantic, |this| {
1700 this.child(
1701 IconButton::new(
1702 "project-search-case-sensitive",
1703 IconName::CaseSensitive,
1704 )
1705 .tooltip(|cx| {
1706 Tooltip::for_action(
1707 "Toggle case sensitive",
1708 &ToggleCaseSensitive,
1709 cx,
1710 )
1711 })
1712 .selected(self.is_option_enabled(SearchOptions::CASE_SENSITIVE, cx))
1713 .on_click(cx.listener(|this, _, cx| {
1714 this.toggle_search_option(SearchOptions::CASE_SENSITIVE, cx);
1715 })),
1716 )
1717 .child(
1718 IconButton::new("project-search-whole-word", IconName::WholeWord)
1719 .tooltip(|cx| {
1720 Tooltip::for_action("Toggle whole word", &ToggleWholeWord, cx)
1721 })
1722 .selected(self.is_option_enabled(SearchOptions::WHOLE_WORD, cx))
1723 .on_click(cx.listener(|this, _, cx| {
1724 this.toggle_search_option(SearchOptions::WHOLE_WORD, cx);
1725 })),
1726 )
1727 }),
1728 );
1729
1730 let mode_column = v_flex().items_start().justify_start().child(
1731 h_flex()
1732 .gap_2()
1733 .child(
1734 h_flex()
1735 .child(
1736 ToggleButton::new("project-search-text-button", "Text")
1737 .style(ButtonStyle::Filled)
1738 .size(ButtonSize::Large)
1739 .selected(search.current_mode == SearchMode::Text)
1740 .on_click(cx.listener(|this, _, cx| {
1741 this.activate_search_mode(SearchMode::Text, cx)
1742 }))
1743 .tooltip(|cx| {
1744 Tooltip::for_action("Toggle text search", &ActivateTextMode, cx)
1745 })
1746 .first(),
1747 )
1748 .child(
1749 ToggleButton::new("project-search-regex-button", "Regex")
1750 .style(ButtonStyle::Filled)
1751 .size(ButtonSize::Large)
1752 .selected(search.current_mode == SearchMode::Regex)
1753 .on_click(cx.listener(|this, _, cx| {
1754 this.activate_search_mode(SearchMode::Regex, cx)
1755 }))
1756 .tooltip(|cx| {
1757 Tooltip::for_action(
1758 "Toggle regular expression search",
1759 &ActivateRegexMode,
1760 cx,
1761 )
1762 })
1763 .map(|this| {
1764 if semantic_is_available {
1765 this.middle()
1766 } else {
1767 this.last()
1768 }
1769 }),
1770 )
1771 .when(semantic_is_available, |this| {
1772 this.child(
1773 ToggleButton::new("project-search-semantic-button", "Semantic")
1774 .style(ButtonStyle::Filled)
1775 .size(ButtonSize::Large)
1776 .selected(search.current_mode == SearchMode::Semantic)
1777 .on_click(cx.listener(|this, _, cx| {
1778 this.activate_search_mode(SearchMode::Semantic, cx)
1779 }))
1780 .tooltip(|cx| {
1781 Tooltip::for_action(
1782 "Toggle semantic search",
1783 &ActivateSemanticMode,
1784 cx,
1785 )
1786 })
1787 .last(),
1788 )
1789 }),
1790 )
1791 .child(
1792 IconButton::new("project-search-toggle-replace", IconName::Replace)
1793 .on_click(cx.listener(|this, _, cx| {
1794 this.toggle_replace(&ToggleReplace, cx);
1795 }))
1796 .tooltip(|cx| Tooltip::for_action("Toggle replace", &ToggleReplace, cx)),
1797 ),
1798 );
1799
1800 let match_text = search
1801 .active_match_index
1802 .and_then(|index| {
1803 let index = index + 1;
1804 let match_quantity = search.model.read(cx).match_ranges.len();
1805 if match_quantity > 0 {
1806 debug_assert!(match_quantity >= index);
1807 Some(format!("{index}/{match_quantity}").to_string())
1808 } else {
1809 None
1810 }
1811 })
1812 .unwrap_or_else(|| "No matches".to_string());
1813
1814 let matches_column = h_flex()
1815 .child(div().min_w(rems(6.)).child(Label::new(match_text)))
1816 .child(
1817 IconButton::new("project-search-prev-match", IconName::ChevronLeft)
1818 .disabled(search.active_match_index.is_none())
1819 .on_click(cx.listener(|this, _, cx| {
1820 if let Some(search) = this.active_project_search.as_ref() {
1821 search.update(cx, |this, cx| {
1822 this.select_match(Direction::Prev, cx);
1823 })
1824 }
1825 }))
1826 .tooltip(|cx| {
1827 Tooltip::for_action("Go to previous match", &SelectPrevMatch, cx)
1828 }),
1829 )
1830 .child(
1831 IconButton::new("project-search-next-match", IconName::ChevronRight)
1832 .disabled(search.active_match_index.is_none())
1833 .on_click(cx.listener(|this, _, cx| {
1834 if let Some(search) = this.active_project_search.as_ref() {
1835 search.update(cx, |this, cx| {
1836 this.select_match(Direction::Next, cx);
1837 })
1838 }
1839 }))
1840 .tooltip(|cx| Tooltip::for_action("Go to next match", &SelectNextMatch, cx)),
1841 );
1842
1843 let search_line = h_flex()
1844 .gap_2()
1845 .flex_1()
1846 .child(query_column)
1847 .child(mode_column)
1848 .child(matches_column);
1849
1850 let replace_line = search.replace_enabled.then(|| {
1851 let replace_column = h_flex()
1852 .flex_1()
1853 .min_w(rems(MIN_INPUT_WIDTH_REMS))
1854 .max_w(rems(MAX_INPUT_WIDTH_REMS))
1855 .h_8()
1856 .px_2()
1857 .py_1()
1858 .border_1()
1859 .border_color(cx.theme().colors().border)
1860 .rounded_lg()
1861 .child(self.render_text_input(&search.replacement_editor, cx));
1862 let replace_actions = h_flex().when(search.replace_enabled, |this| {
1863 this.child(
1864 IconButton::new("project-search-replace-next", IconName::ReplaceNext)
1865 .on_click(cx.listener(|this, _, cx| {
1866 if let Some(search) = this.active_project_search.as_ref() {
1867 search.update(cx, |this, cx| {
1868 this.replace_next(&ReplaceNext, cx);
1869 })
1870 }
1871 }))
1872 .tooltip(|cx| Tooltip::for_action("Replace next match", &ReplaceNext, cx)),
1873 )
1874 .child(
1875 IconButton::new("project-search-replace-all", IconName::ReplaceAll)
1876 .on_click(cx.listener(|this, _, cx| {
1877 if let Some(search) = this.active_project_search.as_ref() {
1878 search.update(cx, |this, cx| {
1879 this.replace_all(&ReplaceAll, cx);
1880 })
1881 }
1882 }))
1883 .tooltip(|cx| Tooltip::for_action("Replace all matches", &ReplaceAll, cx)),
1884 )
1885 });
1886 h_flex()
1887 .gap_2()
1888 .child(replace_column)
1889 .child(replace_actions)
1890 });
1891
1892 let filter_line = search.filters_enabled.then(|| {
1893 h_flex()
1894 .w_full()
1895 .gap_2()
1896 .child(
1897 h_flex()
1898 .flex_1()
1899 .min_w(rems(MIN_INPUT_WIDTH_REMS))
1900 .max_w(rems(MAX_INPUT_WIDTH_REMS))
1901 .h_8()
1902 .px_2()
1903 .py_1()
1904 .border_1()
1905 .border_color(search.border_color_for(InputPanel::Include, cx))
1906 .rounded_lg()
1907 .child(self.render_text_input(&search.included_files_editor, cx))
1908 .when(search.current_mode != SearchMode::Semantic, |this| {
1909 this.child(
1910 SearchOptions::INCLUDE_IGNORED.as_button(
1911 search
1912 .search_options
1913 .contains(SearchOptions::INCLUDE_IGNORED),
1914 cx.listener(|this, _, cx| {
1915 this.toggle_search_option(
1916 SearchOptions::INCLUDE_IGNORED,
1917 cx,
1918 );
1919 }),
1920 ),
1921 )
1922 }),
1923 )
1924 .child(
1925 h_flex()
1926 .flex_1()
1927 .min_w(rems(MIN_INPUT_WIDTH_REMS))
1928 .max_w(rems(MAX_INPUT_WIDTH_REMS))
1929 .h_8()
1930 .px_2()
1931 .py_1()
1932 .border_1()
1933 .border_color(search.border_color_for(InputPanel::Exclude, cx))
1934 .rounded_lg()
1935 .child(self.render_text_input(&search.excluded_files_editor, cx)),
1936 )
1937 });
1938
1939 v_flex()
1940 .key_context(key_context)
1941 .on_action(cx.listener(|this, _: &ToggleFocus, cx| this.move_focus_to_results(cx)))
1942 .on_action(cx.listener(|this, _: &ToggleFilters, cx| {
1943 this.toggle_filters(cx);
1944 }))
1945 .on_action(cx.listener(|this, _: &ActivateTextMode, cx| {
1946 this.activate_search_mode(SearchMode::Text, cx)
1947 }))
1948 .on_action(cx.listener(|this, _: &ActivateRegexMode, cx| {
1949 this.activate_search_mode(SearchMode::Regex, cx)
1950 }))
1951 .on_action(cx.listener(|this, _: &ActivateSemanticMode, cx| {
1952 this.activate_search_mode(SearchMode::Semantic, cx)
1953 }))
1954 .capture_action(cx.listener(|this, action, cx| {
1955 this.tab(action, cx);
1956 cx.stop_propagation();
1957 }))
1958 .capture_action(cx.listener(|this, action, cx| {
1959 this.tab_previous(action, cx);
1960 cx.stop_propagation();
1961 }))
1962 .on_action(cx.listener(|this, action, cx| this.confirm(action, cx)))
1963 .on_action(cx.listener(|this, action, cx| {
1964 this.cycle_mode(action, cx);
1965 }))
1966 .when(search.current_mode != SearchMode::Semantic, |this| {
1967 this.on_action(cx.listener(|this, action, cx| {
1968 this.toggle_replace(action, cx);
1969 }))
1970 .on_action(cx.listener(|this, _: &ToggleWholeWord, cx| {
1971 this.toggle_search_option(SearchOptions::WHOLE_WORD, cx);
1972 }))
1973 .on_action(cx.listener(|this, _: &ToggleCaseSensitive, cx| {
1974 this.toggle_search_option(SearchOptions::CASE_SENSITIVE, cx);
1975 }))
1976 .on_action(cx.listener(|this, action, cx| {
1977 if let Some(search) = this.active_project_search.as_ref() {
1978 search.update(cx, |this, cx| {
1979 this.replace_next(action, cx);
1980 })
1981 }
1982 }))
1983 .on_action(cx.listener(|this, action, cx| {
1984 if let Some(search) = this.active_project_search.as_ref() {
1985 search.update(cx, |this, cx| {
1986 this.replace_all(action, cx);
1987 })
1988 }
1989 }))
1990 .when(search.filters_enabled, |this| {
1991 this.on_action(cx.listener(|this, _: &ToggleIncludeIgnored, cx| {
1992 this.toggle_search_option(SearchOptions::INCLUDE_IGNORED, cx);
1993 }))
1994 })
1995 })
1996 .on_action(cx.listener(Self::select_next_match))
1997 .on_action(cx.listener(Self::select_prev_match))
1998 .gap_2()
1999 .w_full()
2000 .child(search_line)
2001 .children(replace_line)
2002 .children(filter_line)
2003 }
2004}
2005
2006impl EventEmitter<ToolbarItemEvent> for ProjectSearchBar {}
2007
2008impl ToolbarItemView for ProjectSearchBar {
2009 fn set_active_pane_item(
2010 &mut self,
2011 active_pane_item: Option<&dyn ItemHandle>,
2012 cx: &mut ViewContext<Self>,
2013 ) -> ToolbarItemLocation {
2014 cx.notify();
2015 self.subscription = None;
2016 self.active_project_search = None;
2017 if let Some(search) = active_pane_item.and_then(|i| i.downcast::<ProjectSearchView>()) {
2018 search.update(cx, |search, cx| {
2019 if search.current_mode == SearchMode::Semantic {
2020 search.index_project(cx);
2021 }
2022 });
2023
2024 self.subscription = Some(cx.observe(&search, |_, _, cx| cx.notify()));
2025 self.active_project_search = Some(search);
2026 ToolbarItemLocation::PrimaryLeft {}
2027 } else {
2028 ToolbarItemLocation::Hidden
2029 }
2030 }
2031
2032 fn row_count(&self, cx: &WindowContext<'_>) -> usize {
2033 if let Some(search) = self.active_project_search.as_ref() {
2034 if search.read(cx).filters_enabled {
2035 return 2;
2036 }
2037 }
2038 1
2039 }
2040}
2041
2042fn register_workspace_action<A: Action>(
2043 workspace: &mut Workspace,
2044 callback: fn(&mut ProjectSearchBar, &A, &mut ViewContext<ProjectSearchBar>),
2045) {
2046 workspace.register_action(move |workspace, action: &A, cx| {
2047 if workspace.has_active_modal(cx) {
2048 cx.propagate();
2049 return;
2050 }
2051
2052 workspace.active_pane().update(cx, |pane, cx| {
2053 pane.toolbar().update(cx, move |workspace, cx| {
2054 if let Some(search_bar) = workspace.item_of_type::<ProjectSearchBar>() {
2055 search_bar.update(cx, move |search_bar, cx| {
2056 if search_bar.active_project_search.is_some() {
2057 callback(search_bar, action, cx);
2058 cx.notify();
2059 } else {
2060 cx.propagate();
2061 }
2062 });
2063 }
2064 });
2065 })
2066 });
2067}
2068
2069fn register_workspace_action_for_present_search<A: Action>(
2070 workspace: &mut Workspace,
2071 callback: fn(&mut Workspace, &A, &mut ViewContext<Workspace>),
2072) {
2073 workspace.register_action(move |workspace, action: &A, cx| {
2074 if workspace.has_active_modal(cx) {
2075 cx.propagate();
2076 return;
2077 }
2078
2079 let should_notify = workspace
2080 .active_pane()
2081 .read(cx)
2082 .toolbar()
2083 .read(cx)
2084 .item_of_type::<ProjectSearchBar>()
2085 .map(|search_bar| search_bar.read(cx).active_project_search.is_some())
2086 .unwrap_or(false);
2087 if should_notify {
2088 callback(workspace, action, cx);
2089 cx.notify();
2090 } else {
2091 cx.propagate();
2092 }
2093 });
2094}
2095
2096#[cfg(test)]
2097pub mod tests {
2098 use super::*;
2099 use editor::DisplayPoint;
2100 use gpui::{Action, TestAppContext, WindowHandle};
2101 use project::FakeFs;
2102 use semantic_index::semantic_index_settings::SemanticIndexSettings;
2103 use serde_json::json;
2104 use settings::{Settings, SettingsStore};
2105 use std::sync::Arc;
2106 use workspace::DeploySearch;
2107
2108 #[gpui::test]
2109 async fn test_project_search(cx: &mut TestAppContext) {
2110 init_test(cx);
2111
2112 let fs = FakeFs::new(cx.background_executor.clone());
2113 fs.insert_tree(
2114 "/dir",
2115 json!({
2116 "one.rs": "const ONE: usize = 1;",
2117 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2118 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2119 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2120 }),
2121 )
2122 .await;
2123 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
2124 let search = cx.new_model(|cx| ProjectSearch::new(project, cx));
2125 let search_view = cx.add_window(|cx| ProjectSearchView::new(search.clone(), cx, None));
2126
2127 perform_search(search_view, "TWO", cx);
2128 search_view.update(cx, |search_view, cx| {
2129 assert_eq!(
2130 search_view
2131 .results_editor
2132 .update(cx, |editor, cx| editor.display_text(cx)),
2133 "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;"
2134 );
2135 let match_background_color = cx.theme().colors().search_match_background;
2136 assert_eq!(
2137 search_view
2138 .results_editor
2139 .update(cx, |editor, cx| editor.all_text_background_highlights(cx)),
2140 &[
2141 (
2142 DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35),
2143 match_background_color
2144 ),
2145 (
2146 DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40),
2147 match_background_color
2148 ),
2149 (
2150 DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9),
2151 match_background_color
2152 )
2153 ]
2154 );
2155 assert_eq!(search_view.active_match_index, Some(0));
2156 assert_eq!(
2157 search_view
2158 .results_editor
2159 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2160 [DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35)]
2161 );
2162
2163 search_view.select_match(Direction::Next, cx);
2164 }).unwrap();
2165
2166 search_view
2167 .update(cx, |search_view, cx| {
2168 assert_eq!(search_view.active_match_index, Some(1));
2169 assert_eq!(
2170 search_view
2171 .results_editor
2172 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2173 [DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40)]
2174 );
2175 search_view.select_match(Direction::Next, cx);
2176 })
2177 .unwrap();
2178
2179 search_view
2180 .update(cx, |search_view, cx| {
2181 assert_eq!(search_view.active_match_index, Some(2));
2182 assert_eq!(
2183 search_view
2184 .results_editor
2185 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2186 [DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9)]
2187 );
2188 search_view.select_match(Direction::Next, cx);
2189 })
2190 .unwrap();
2191
2192 search_view
2193 .update(cx, |search_view, cx| {
2194 assert_eq!(search_view.active_match_index, Some(0));
2195 assert_eq!(
2196 search_view
2197 .results_editor
2198 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2199 [DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35)]
2200 );
2201 search_view.select_match(Direction::Prev, cx);
2202 })
2203 .unwrap();
2204
2205 search_view
2206 .update(cx, |search_view, cx| {
2207 assert_eq!(search_view.active_match_index, Some(2));
2208 assert_eq!(
2209 search_view
2210 .results_editor
2211 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2212 [DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9)]
2213 );
2214 search_view.select_match(Direction::Prev, cx);
2215 })
2216 .unwrap();
2217
2218 search_view
2219 .update(cx, |search_view, cx| {
2220 assert_eq!(search_view.active_match_index, Some(1));
2221 assert_eq!(
2222 search_view
2223 .results_editor
2224 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2225 [DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40)]
2226 );
2227 })
2228 .unwrap();
2229 }
2230
2231 #[gpui::test]
2232 async fn test_deploy_project_search_focus(cx: &mut TestAppContext) {
2233 init_test(cx);
2234
2235 let fs = FakeFs::new(cx.background_executor.clone());
2236 fs.insert_tree(
2237 "/dir",
2238 json!({
2239 "one.rs": "const ONE: usize = 1;",
2240 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2241 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2242 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2243 }),
2244 )
2245 .await;
2246 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
2247 let window = cx.add_window(|cx| Workspace::test_new(project, cx));
2248 let workspace = window;
2249 let search_bar = window.build_view(cx, |_| ProjectSearchBar::new());
2250
2251 let active_item = cx.read(|cx| {
2252 workspace
2253 .read(cx)
2254 .unwrap()
2255 .active_pane()
2256 .read(cx)
2257 .active_item()
2258 .and_then(|item| item.downcast::<ProjectSearchView>())
2259 });
2260 assert!(
2261 active_item.is_none(),
2262 "Expected no search panel to be active"
2263 );
2264
2265 window
2266 .update(cx, move |workspace, cx| {
2267 assert_eq!(workspace.panes().len(), 1);
2268 workspace.panes()[0].update(cx, move |pane, cx| {
2269 pane.toolbar()
2270 .update(cx, |toolbar, cx| toolbar.add_item(search_bar, cx))
2271 });
2272
2273 ProjectSearchView::deploy_search(workspace, &workspace::DeploySearch, cx)
2274 })
2275 .unwrap();
2276
2277 let Some(search_view) = cx.read(|cx| {
2278 workspace
2279 .read(cx)
2280 .unwrap()
2281 .active_pane()
2282 .read(cx)
2283 .active_item()
2284 .and_then(|item| item.downcast::<ProjectSearchView>())
2285 }) else {
2286 panic!("Search view expected to appear after new search event trigger")
2287 };
2288
2289 cx.spawn(|mut cx| async move {
2290 window
2291 .update(&mut cx, |_, cx| {
2292 cx.dispatch_action(ToggleFocus.boxed_clone())
2293 })
2294 .unwrap();
2295 })
2296 .detach();
2297 cx.background_executor.run_until_parked();
2298 window
2299 .update(cx, |_, cx| {
2300 search_view.update(cx, |search_view, cx| {
2301 assert!(
2302 search_view.query_editor.focus_handle(cx).is_focused(cx),
2303 "Empty search view should be focused after the toggle focus event: no results panel to focus on",
2304 );
2305 });
2306 }).unwrap();
2307
2308 window
2309 .update(cx, |_, cx| {
2310 search_view.update(cx, |search_view, cx| {
2311 let query_editor = &search_view.query_editor;
2312 assert!(
2313 query_editor.focus_handle(cx).is_focused(cx),
2314 "Search view should be focused after the new search view is activated",
2315 );
2316 let query_text = query_editor.read(cx).text(cx);
2317 assert!(
2318 query_text.is_empty(),
2319 "New search query should be empty but got '{query_text}'",
2320 );
2321 let results_text = search_view
2322 .results_editor
2323 .update(cx, |editor, cx| editor.display_text(cx));
2324 assert!(
2325 results_text.is_empty(),
2326 "Empty search view should have no results but got '{results_text}'"
2327 );
2328 });
2329 })
2330 .unwrap();
2331
2332 window
2333 .update(cx, |_, cx| {
2334 search_view.update(cx, |search_view, cx| {
2335 search_view.query_editor.update(cx, |query_editor, cx| {
2336 query_editor.set_text("sOMETHINGtHATsURELYdOESnOTeXIST", cx)
2337 });
2338 search_view.search(cx);
2339 });
2340 })
2341 .unwrap();
2342 cx.background_executor.run_until_parked();
2343 window
2344 .update(cx, |_, cx| {
2345 search_view.update(cx, |search_view, cx| {
2346 let results_text = search_view
2347 .results_editor
2348 .update(cx, |editor, cx| editor.display_text(cx));
2349 assert!(
2350 results_text.is_empty(),
2351 "Search view for mismatching query should have no results but got '{results_text}'"
2352 );
2353 assert!(
2354 search_view.query_editor.focus_handle(cx).is_focused(cx),
2355 "Search view should be focused after mismatching query had been used in search",
2356 );
2357 });
2358 }).unwrap();
2359
2360 cx.spawn(|mut cx| async move {
2361 window.update(&mut cx, |_, cx| {
2362 cx.dispatch_action(ToggleFocus.boxed_clone())
2363 })
2364 })
2365 .detach();
2366 cx.background_executor.run_until_parked();
2367 window.update(cx, |_, cx| {
2368 search_view.update(cx, |search_view, cx| {
2369 assert!(
2370 search_view.query_editor.focus_handle(cx).is_focused(cx),
2371 "Search view with mismatching query should be focused after the toggle focus event: still no results panel to focus on",
2372 );
2373 });
2374 }).unwrap();
2375
2376 window
2377 .update(cx, |_, cx| {
2378 search_view.update(cx, |search_view, cx| {
2379 search_view
2380 .query_editor
2381 .update(cx, |query_editor, cx| query_editor.set_text("TWO", cx));
2382 search_view.search(cx);
2383 });
2384 })
2385 .unwrap();
2386 cx.background_executor.run_until_parked();
2387 window.update(cx, |_, cx| {
2388 search_view.update(cx, |search_view, cx| {
2389 assert_eq!(
2390 search_view
2391 .results_editor
2392 .update(cx, |editor, cx| editor.display_text(cx)),
2393 "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
2394 "Search view results should match the query"
2395 );
2396 assert!(
2397 search_view.results_editor.focus_handle(cx).is_focused(cx),
2398 "Search view with mismatching query should be focused after search results are available",
2399 );
2400 });
2401 }).unwrap();
2402 cx.spawn(|mut cx| async move {
2403 window
2404 .update(&mut cx, |_, cx| {
2405 cx.dispatch_action(ToggleFocus.boxed_clone())
2406 })
2407 .unwrap();
2408 })
2409 .detach();
2410 cx.background_executor.run_until_parked();
2411 window.update(cx, |_, cx| {
2412 search_view.update(cx, |search_view, cx| {
2413 assert!(
2414 search_view.results_editor.focus_handle(cx).is_focused(cx),
2415 "Search view with matching query should still have its results editor focused after the toggle focus event",
2416 );
2417 });
2418 }).unwrap();
2419
2420 workspace
2421 .update(cx, |workspace, cx| {
2422 ProjectSearchView::deploy_search(workspace, &workspace::DeploySearch, cx)
2423 })
2424 .unwrap();
2425 window.update(cx, |_, cx| {
2426 search_view.update(cx, |search_view, cx| {
2427 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");
2428 assert_eq!(
2429 search_view
2430 .results_editor
2431 .update(cx, |editor, cx| editor.display_text(cx)),
2432 "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
2433 "Results should be unchanged after search view 2nd open in a row"
2434 );
2435 assert!(
2436 search_view.query_editor.focus_handle(cx).is_focused(cx),
2437 "Focus should be moved into query editor again after search view 2nd open in a row"
2438 );
2439 });
2440 }).unwrap();
2441
2442 cx.spawn(|mut cx| async move {
2443 window
2444 .update(&mut cx, |_, cx| {
2445 cx.dispatch_action(ToggleFocus.boxed_clone())
2446 })
2447 .unwrap();
2448 })
2449 .detach();
2450 cx.background_executor.run_until_parked();
2451 window.update(cx, |_, cx| {
2452 search_view.update(cx, |search_view, cx| {
2453 assert!(
2454 search_view.results_editor.focus_handle(cx).is_focused(cx),
2455 "Search view with matching query should switch focus to the results editor after the toggle focus event",
2456 );
2457 });
2458 }).unwrap();
2459 }
2460
2461 #[gpui::test]
2462 async fn test_new_project_search_focus(cx: &mut TestAppContext) {
2463 init_test(cx);
2464
2465 let fs = FakeFs::new(cx.background_executor.clone());
2466 fs.insert_tree(
2467 "/dir",
2468 json!({
2469 "one.rs": "const ONE: usize = 1;",
2470 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2471 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2472 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2473 }),
2474 )
2475 .await;
2476 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
2477 let window = cx.add_window(|cx| Workspace::test_new(project, cx));
2478 let workspace = window;
2479 let search_bar = window.build_view(cx, |_| ProjectSearchBar::new());
2480
2481 let active_item = cx.read(|cx| {
2482 workspace
2483 .read(cx)
2484 .unwrap()
2485 .active_pane()
2486 .read(cx)
2487 .active_item()
2488 .and_then(|item| item.downcast::<ProjectSearchView>())
2489 });
2490 assert!(
2491 active_item.is_none(),
2492 "Expected no search panel to be active"
2493 );
2494
2495 window
2496 .update(cx, move |workspace, cx| {
2497 assert_eq!(workspace.panes().len(), 1);
2498 workspace.panes()[0].update(cx, move |pane, cx| {
2499 pane.toolbar()
2500 .update(cx, |toolbar, cx| toolbar.add_item(search_bar, cx))
2501 });
2502
2503 ProjectSearchView::new_search(workspace, &workspace::NewSearch, cx)
2504 })
2505 .unwrap();
2506
2507 let Some(search_view) = cx.read(|cx| {
2508 workspace
2509 .read(cx)
2510 .unwrap()
2511 .active_pane()
2512 .read(cx)
2513 .active_item()
2514 .and_then(|item| item.downcast::<ProjectSearchView>())
2515 }) else {
2516 panic!("Search view expected to appear after new search event trigger")
2517 };
2518
2519 cx.spawn(|mut cx| async move {
2520 window
2521 .update(&mut cx, |_, cx| {
2522 cx.dispatch_action(ToggleFocus.boxed_clone())
2523 })
2524 .unwrap();
2525 })
2526 .detach();
2527 cx.background_executor.run_until_parked();
2528
2529 window.update(cx, |_, cx| {
2530 search_view.update(cx, |search_view, cx| {
2531 assert!(
2532 search_view.query_editor.focus_handle(cx).is_focused(cx),
2533 "Empty search view should be focused after the toggle focus event: no results panel to focus on",
2534 );
2535 });
2536 }).unwrap();
2537
2538 window
2539 .update(cx, |_, cx| {
2540 search_view.update(cx, |search_view, cx| {
2541 let query_editor = &search_view.query_editor;
2542 assert!(
2543 query_editor.focus_handle(cx).is_focused(cx),
2544 "Search view should be focused after the new search view is activated",
2545 );
2546 let query_text = query_editor.read(cx).text(cx);
2547 assert!(
2548 query_text.is_empty(),
2549 "New search query should be empty but got '{query_text}'",
2550 );
2551 let results_text = search_view
2552 .results_editor
2553 .update(cx, |editor, cx| editor.display_text(cx));
2554 assert!(
2555 results_text.is_empty(),
2556 "Empty search view should have no results but got '{results_text}'"
2557 );
2558 });
2559 })
2560 .unwrap();
2561
2562 window
2563 .update(cx, |_, cx| {
2564 search_view.update(cx, |search_view, cx| {
2565 search_view.query_editor.update(cx, |query_editor, cx| {
2566 query_editor.set_text("sOMETHINGtHATsURELYdOESnOTeXIST", cx)
2567 });
2568 search_view.search(cx);
2569 });
2570 })
2571 .unwrap();
2572
2573 cx.background_executor.run_until_parked();
2574 window
2575 .update(cx, |_, cx| {
2576 search_view.update(cx, |search_view, cx| {
2577 let results_text = search_view
2578 .results_editor
2579 .update(cx, |editor, cx| editor.display_text(cx));
2580 assert!(
2581 results_text.is_empty(),
2582 "Search view for mismatching query should have no results but got '{results_text}'"
2583 );
2584 assert!(
2585 search_view.query_editor.focus_handle(cx).is_focused(cx),
2586 "Search view should be focused after mismatching query had been used in search",
2587 );
2588 });
2589 })
2590 .unwrap();
2591 cx.spawn(|mut cx| async move {
2592 window.update(&mut cx, |_, cx| {
2593 cx.dispatch_action(ToggleFocus.boxed_clone())
2594 })
2595 })
2596 .detach();
2597 cx.background_executor.run_until_parked();
2598 window.update(cx, |_, cx| {
2599 search_view.update(cx, |search_view, cx| {
2600 assert!(
2601 search_view.query_editor.focus_handle(cx).is_focused(cx),
2602 "Search view with mismatching query should be focused after the toggle focus event: still no results panel to focus on",
2603 );
2604 });
2605 }).unwrap();
2606
2607 window
2608 .update(cx, |_, cx| {
2609 search_view.update(cx, |search_view, cx| {
2610 search_view
2611 .query_editor
2612 .update(cx, |query_editor, cx| query_editor.set_text("TWO", cx));
2613 search_view.search(cx);
2614 })
2615 })
2616 .unwrap();
2617 cx.background_executor.run_until_parked();
2618 window.update(cx, |_, cx|
2619 search_view.update(cx, |search_view, cx| {
2620 assert_eq!(
2621 search_view
2622 .results_editor
2623 .update(cx, |editor, cx| editor.display_text(cx)),
2624 "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
2625 "Search view results should match the query"
2626 );
2627 assert!(
2628 search_view.results_editor.focus_handle(cx).is_focused(cx),
2629 "Search view with mismatching query should be focused after search results are available",
2630 );
2631 })).unwrap();
2632 cx.spawn(|mut cx| async move {
2633 window
2634 .update(&mut cx, |_, cx| {
2635 cx.dispatch_action(ToggleFocus.boxed_clone())
2636 })
2637 .unwrap();
2638 })
2639 .detach();
2640 cx.background_executor.run_until_parked();
2641 window.update(cx, |_, cx| {
2642 search_view.update(cx, |search_view, cx| {
2643 assert!(
2644 search_view.results_editor.focus_handle(cx).is_focused(cx),
2645 "Search view with matching query should still have its results editor focused after the toggle focus event",
2646 );
2647 });
2648 }).unwrap();
2649
2650 workspace
2651 .update(cx, |workspace, cx| {
2652 ProjectSearchView::new_search(workspace, &workspace::NewSearch, cx)
2653 })
2654 .unwrap();
2655 cx.background_executor.run_until_parked();
2656 let Some(search_view_2) = cx.read(|cx| {
2657 workspace
2658 .read(cx)
2659 .unwrap()
2660 .active_pane()
2661 .read(cx)
2662 .active_item()
2663 .and_then(|item| item.downcast::<ProjectSearchView>())
2664 }) else {
2665 panic!("Search view expected to appear after new search event trigger")
2666 };
2667 assert!(
2668 search_view_2 != search_view,
2669 "New search view should be open after `workspace::NewSearch` event"
2670 );
2671
2672 window.update(cx, |_, cx| {
2673 search_view.update(cx, |search_view, cx| {
2674 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO", "First search view should not have an updated query");
2675 assert_eq!(
2676 search_view
2677 .results_editor
2678 .update(cx, |editor, cx| editor.display_text(cx)),
2679 "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
2680 "Results of the first search view should not update too"
2681 );
2682 assert!(
2683 !search_view.query_editor.focus_handle(cx).is_focused(cx),
2684 "Focus should be moved away from the first search view"
2685 );
2686 });
2687 }).unwrap();
2688
2689 window.update(cx, |_, cx| {
2690 search_view_2.update(cx, |search_view_2, cx| {
2691 assert_eq!(
2692 search_view_2.query_editor.read(cx).text(cx),
2693 "two",
2694 "New search view should get the query from the text cursor was at during the event spawn (first search view's first result)"
2695 );
2696 assert_eq!(
2697 search_view_2
2698 .results_editor
2699 .update(cx, |editor, cx| editor.display_text(cx)),
2700 "",
2701 "No search results should be in the 2nd view yet, as we did not spawn a search for it"
2702 );
2703 assert!(
2704 search_view_2.query_editor.focus_handle(cx).is_focused(cx),
2705 "Focus should be moved into query editor of the new window"
2706 );
2707 });
2708 }).unwrap();
2709
2710 window
2711 .update(cx, |_, cx| {
2712 search_view_2.update(cx, |search_view_2, cx| {
2713 search_view_2
2714 .query_editor
2715 .update(cx, |query_editor, cx| query_editor.set_text("FOUR", cx));
2716 search_view_2.search(cx);
2717 });
2718 })
2719 .unwrap();
2720
2721 cx.background_executor.run_until_parked();
2722 window.update(cx, |_, cx| {
2723 search_view_2.update(cx, |search_view_2, cx| {
2724 assert_eq!(
2725 search_view_2
2726 .results_editor
2727 .update(cx, |editor, cx| editor.display_text(cx)),
2728 "\n\nconst FOUR: usize = one::ONE + three::THREE;",
2729 "New search view with the updated query should have new search results"
2730 );
2731 assert!(
2732 search_view_2.results_editor.focus_handle(cx).is_focused(cx),
2733 "Search view with mismatching query should be focused after search results are available",
2734 );
2735 });
2736 }).unwrap();
2737
2738 cx.spawn(|mut cx| async move {
2739 window
2740 .update(&mut cx, |_, cx| {
2741 cx.dispatch_action(ToggleFocus.boxed_clone())
2742 })
2743 .unwrap();
2744 })
2745 .detach();
2746 cx.background_executor.run_until_parked();
2747 window.update(cx, |_, cx| {
2748 search_view_2.update(cx, |search_view_2, cx| {
2749 assert!(
2750 search_view_2.results_editor.focus_handle(cx).is_focused(cx),
2751 "Search view with matching query should switch focus to the results editor after the toggle focus event",
2752 );
2753 });}).unwrap();
2754 }
2755
2756 #[gpui::test]
2757 async fn test_new_project_search_in_directory(cx: &mut TestAppContext) {
2758 init_test(cx);
2759
2760 let fs = FakeFs::new(cx.background_executor.clone());
2761 fs.insert_tree(
2762 "/dir",
2763 json!({
2764 "a": {
2765 "one.rs": "const ONE: usize = 1;",
2766 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2767 },
2768 "b": {
2769 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2770 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2771 },
2772 }),
2773 )
2774 .await;
2775 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
2776 let worktree_id = project.read_with(cx, |project, cx| {
2777 project.worktrees().next().unwrap().read(cx).id()
2778 });
2779 let window = cx.add_window(|cx| Workspace::test_new(project, cx));
2780 let workspace = window.root(cx).unwrap();
2781 let search_bar = window.build_view(cx, |_| ProjectSearchBar::new());
2782
2783 let active_item = cx.read(|cx| {
2784 workspace
2785 .read(cx)
2786 .active_pane()
2787 .read(cx)
2788 .active_item()
2789 .and_then(|item| item.downcast::<ProjectSearchView>())
2790 });
2791 assert!(
2792 active_item.is_none(),
2793 "Expected no search panel to be active"
2794 );
2795
2796 window
2797 .update(cx, move |workspace, cx| {
2798 assert_eq!(workspace.panes().len(), 1);
2799 workspace.panes()[0].update(cx, move |pane, cx| {
2800 pane.toolbar()
2801 .update(cx, |toolbar, cx| toolbar.add_item(search_bar, cx))
2802 });
2803 })
2804 .unwrap();
2805
2806 let one_file_entry = cx.update(|cx| {
2807 workspace
2808 .read(cx)
2809 .project()
2810 .read(cx)
2811 .entry_for_path(&(worktree_id, "a/one.rs").into(), cx)
2812 .expect("no entry for /a/one.rs file")
2813 });
2814 assert!(one_file_entry.is_file());
2815 window
2816 .update(cx, |workspace, cx| {
2817 ProjectSearchView::new_search_in_directory(workspace, &one_file_entry, cx)
2818 })
2819 .unwrap();
2820 let active_search_entry = cx.read(|cx| {
2821 workspace
2822 .read(cx)
2823 .active_pane()
2824 .read(cx)
2825 .active_item()
2826 .and_then(|item| item.downcast::<ProjectSearchView>())
2827 });
2828 assert!(
2829 active_search_entry.is_none(),
2830 "Expected no search panel to be active for file entry"
2831 );
2832
2833 let a_dir_entry = cx.update(|cx| {
2834 workspace
2835 .read(cx)
2836 .project()
2837 .read(cx)
2838 .entry_for_path(&(worktree_id, "a").into(), cx)
2839 .expect("no entry for /a/ directory")
2840 });
2841 assert!(a_dir_entry.is_dir());
2842 window
2843 .update(cx, |workspace, cx| {
2844 ProjectSearchView::new_search_in_directory(workspace, &a_dir_entry, cx)
2845 })
2846 .unwrap();
2847
2848 let Some(search_view) = cx.read(|cx| {
2849 workspace
2850 .read(cx)
2851 .active_pane()
2852 .read(cx)
2853 .active_item()
2854 .and_then(|item| item.downcast::<ProjectSearchView>())
2855 }) else {
2856 panic!("Search view expected to appear after new search in directory event trigger")
2857 };
2858 cx.background_executor.run_until_parked();
2859 window
2860 .update(cx, |_, cx| {
2861 search_view.update(cx, |search_view, cx| {
2862 assert!(
2863 search_view.query_editor.focus_handle(cx).is_focused(cx),
2864 "On new search in directory, focus should be moved into query editor"
2865 );
2866 search_view.excluded_files_editor.update(cx, |editor, cx| {
2867 assert!(
2868 editor.display_text(cx).is_empty(),
2869 "New search in directory should not have any excluded files"
2870 );
2871 });
2872 search_view.included_files_editor.update(cx, |editor, cx| {
2873 assert_eq!(
2874 editor.display_text(cx),
2875 a_dir_entry.path.to_str().unwrap(),
2876 "New search in directory should have included dir entry path"
2877 );
2878 });
2879 });
2880 })
2881 .unwrap();
2882 window
2883 .update(cx, |_, cx| {
2884 search_view.update(cx, |search_view, cx| {
2885 search_view
2886 .query_editor
2887 .update(cx, |query_editor, cx| query_editor.set_text("const", cx));
2888 search_view.search(cx);
2889 });
2890 })
2891 .unwrap();
2892 cx.background_executor.run_until_parked();
2893 window
2894 .update(cx, |_, cx| {
2895 search_view.update(cx, |search_view, cx| {
2896 assert_eq!(
2897 search_view
2898 .results_editor
2899 .update(cx, |editor, cx| editor.display_text(cx)),
2900 "\n\nconst ONE: usize = 1;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
2901 "New search in directory should have a filter that matches a certain directory"
2902 );
2903 })
2904 })
2905 .unwrap();
2906 }
2907
2908 #[gpui::test]
2909 async fn test_search_query_history(cx: &mut TestAppContext) {
2910 init_test(cx);
2911
2912 let fs = FakeFs::new(cx.background_executor.clone());
2913 fs.insert_tree(
2914 "/dir",
2915 json!({
2916 "one.rs": "const ONE: usize = 1;",
2917 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2918 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2919 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2920 }),
2921 )
2922 .await;
2923 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
2924 let window = cx.add_window(|cx| Workspace::test_new(project, cx));
2925 let workspace = window.root(cx).unwrap();
2926 let search_bar = window.build_view(cx, |_| ProjectSearchBar::new());
2927
2928 window
2929 .update(cx, {
2930 let search_bar = search_bar.clone();
2931 move |workspace, cx| {
2932 assert_eq!(workspace.panes().len(), 1);
2933 workspace.panes()[0].update(cx, move |pane, cx| {
2934 pane.toolbar()
2935 .update(cx, |toolbar, cx| toolbar.add_item(search_bar, cx))
2936 });
2937
2938 ProjectSearchView::new_search(workspace, &workspace::NewSearch, cx)
2939 }
2940 })
2941 .unwrap();
2942
2943 let search_view = cx.read(|cx| {
2944 workspace
2945 .read(cx)
2946 .active_pane()
2947 .read(cx)
2948 .active_item()
2949 .and_then(|item| item.downcast::<ProjectSearchView>())
2950 .expect("Search view expected to appear after new search event trigger")
2951 });
2952
2953 // Add 3 search items into the history + another unsubmitted one.
2954 window
2955 .update(cx, |_, cx| {
2956 search_view.update(cx, |search_view, cx| {
2957 search_view.search_options = SearchOptions::CASE_SENSITIVE;
2958 search_view
2959 .query_editor
2960 .update(cx, |query_editor, cx| query_editor.set_text("ONE", cx));
2961 search_view.search(cx);
2962 });
2963 })
2964 .unwrap();
2965
2966 cx.background_executor.run_until_parked();
2967 window
2968 .update(cx, |_, cx| {
2969 search_view.update(cx, |search_view, cx| {
2970 search_view
2971 .query_editor
2972 .update(cx, |query_editor, cx| query_editor.set_text("TWO", cx));
2973 search_view.search(cx);
2974 });
2975 })
2976 .unwrap();
2977 cx.background_executor.run_until_parked();
2978 window
2979 .update(cx, |_, cx| {
2980 search_view.update(cx, |search_view, cx| {
2981 search_view
2982 .query_editor
2983 .update(cx, |query_editor, cx| query_editor.set_text("THREE", cx));
2984 search_view.search(cx);
2985 })
2986 })
2987 .unwrap();
2988 cx.background_executor.run_until_parked();
2989 window
2990 .update(cx, |_, cx| {
2991 search_view.update(cx, |search_view, cx| {
2992 search_view.query_editor.update(cx, |query_editor, cx| {
2993 query_editor.set_text("JUST_TEXT_INPUT", cx)
2994 });
2995 })
2996 })
2997 .unwrap();
2998 cx.background_executor.run_until_parked();
2999
3000 // Ensure that the latest input with search settings is active.
3001 window
3002 .update(cx, |_, cx| {
3003 search_view.update(cx, |search_view, cx| {
3004 assert_eq!(
3005 search_view.query_editor.read(cx).text(cx),
3006 "JUST_TEXT_INPUT"
3007 );
3008 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3009 });
3010 })
3011 .unwrap();
3012
3013 // Next history query after the latest should set the query to the empty string.
3014 window
3015 .update(cx, |_, cx| {
3016 search_bar.update(cx, |search_bar, cx| {
3017 search_bar.next_history_query(&NextHistoryQuery, cx);
3018 })
3019 })
3020 .unwrap();
3021 window
3022 .update(cx, |_, cx| {
3023 search_view.update(cx, |search_view, cx| {
3024 assert_eq!(search_view.query_editor.read(cx).text(cx), "");
3025 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3026 });
3027 })
3028 .unwrap();
3029 window
3030 .update(cx, |_, cx| {
3031 search_bar.update(cx, |search_bar, cx| {
3032 search_bar.next_history_query(&NextHistoryQuery, cx);
3033 })
3034 })
3035 .unwrap();
3036 window
3037 .update(cx, |_, cx| {
3038 search_view.update(cx, |search_view, cx| {
3039 assert_eq!(search_view.query_editor.read(cx).text(cx), "");
3040 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3041 });
3042 })
3043 .unwrap();
3044
3045 // First previous query for empty current query should set the query to the latest submitted one.
3046 window
3047 .update(cx, |_, cx| {
3048 search_bar.update(cx, |search_bar, cx| {
3049 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
3050 });
3051 })
3052 .unwrap();
3053 window
3054 .update(cx, |_, cx| {
3055 search_view.update(cx, |search_view, cx| {
3056 assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
3057 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3058 });
3059 })
3060 .unwrap();
3061
3062 // Further previous items should go over the history in reverse order.
3063 window
3064 .update(cx, |_, cx| {
3065 search_bar.update(cx, |search_bar, cx| {
3066 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
3067 });
3068 })
3069 .unwrap();
3070 window
3071 .update(cx, |_, cx| {
3072 search_view.update(cx, |search_view, cx| {
3073 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
3074 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3075 });
3076 })
3077 .unwrap();
3078
3079 // Previous items should never go behind the first history item.
3080 window
3081 .update(cx, |_, cx| {
3082 search_bar.update(cx, |search_bar, cx| {
3083 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
3084 });
3085 })
3086 .unwrap();
3087 window
3088 .update(cx, |_, cx| {
3089 search_view.update(cx, |search_view, cx| {
3090 assert_eq!(search_view.query_editor.read(cx).text(cx), "ONE");
3091 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3092 });
3093 })
3094 .unwrap();
3095 window
3096 .update(cx, |_, cx| {
3097 search_bar.update(cx, |search_bar, cx| {
3098 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
3099 });
3100 })
3101 .unwrap();
3102 window
3103 .update(cx, |_, cx| {
3104 search_view.update(cx, |search_view, cx| {
3105 assert_eq!(search_view.query_editor.read(cx).text(cx), "ONE");
3106 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3107 });
3108 })
3109 .unwrap();
3110
3111 // Next items should go over the history in the original order.
3112 window
3113 .update(cx, |_, cx| {
3114 search_bar.update(cx, |search_bar, cx| {
3115 search_bar.next_history_query(&NextHistoryQuery, cx);
3116 });
3117 })
3118 .unwrap();
3119 window
3120 .update(cx, |_, cx| {
3121 search_view.update(cx, |search_view, cx| {
3122 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
3123 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3124 });
3125 })
3126 .unwrap();
3127
3128 window
3129 .update(cx, |_, cx| {
3130 search_view.update(cx, |search_view, cx| {
3131 search_view
3132 .query_editor
3133 .update(cx, |query_editor, cx| query_editor.set_text("TWO_NEW", cx));
3134 search_view.search(cx);
3135 });
3136 })
3137 .unwrap();
3138 cx.background_executor.run_until_parked();
3139 window
3140 .update(cx, |_, cx| {
3141 search_view.update(cx, |search_view, cx| {
3142 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO_NEW");
3143 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3144 });
3145 })
3146 .unwrap();
3147
3148 // New search input should add another entry to history and move the selection to the end of the history.
3149 window
3150 .update(cx, |_, cx| {
3151 search_bar.update(cx, |search_bar, cx| {
3152 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
3153 });
3154 })
3155 .unwrap();
3156 window
3157 .update(cx, |_, cx| {
3158 search_view.update(cx, |search_view, cx| {
3159 assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
3160 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3161 });
3162 })
3163 .unwrap();
3164 window
3165 .update(cx, |_, cx| {
3166 search_bar.update(cx, |search_bar, cx| {
3167 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
3168 });
3169 })
3170 .unwrap();
3171 window
3172 .update(cx, |_, cx| {
3173 search_view.update(cx, |search_view, cx| {
3174 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
3175 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3176 });
3177 })
3178 .unwrap();
3179 window
3180 .update(cx, |_, cx| {
3181 search_bar.update(cx, |search_bar, cx| {
3182 search_bar.next_history_query(&NextHistoryQuery, cx);
3183 });
3184 })
3185 .unwrap();
3186 window
3187 .update(cx, |_, cx| {
3188 search_view.update(cx, |search_view, cx| {
3189 assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
3190 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3191 });
3192 })
3193 .unwrap();
3194 window
3195 .update(cx, |_, cx| {
3196 search_bar.update(cx, |search_bar, cx| {
3197 search_bar.next_history_query(&NextHistoryQuery, cx);
3198 });
3199 })
3200 .unwrap();
3201 window
3202 .update(cx, |_, cx| {
3203 search_view.update(cx, |search_view, cx| {
3204 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO_NEW");
3205 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3206 });
3207 })
3208 .unwrap();
3209 window
3210 .update(cx, |_, cx| {
3211 search_bar.update(cx, |search_bar, cx| {
3212 search_bar.next_history_query(&NextHistoryQuery, cx);
3213 });
3214 })
3215 .unwrap();
3216 window
3217 .update(cx, |_, cx| {
3218 search_view.update(cx, |search_view, cx| {
3219 assert_eq!(search_view.query_editor.read(cx).text(cx), "");
3220 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
3221 });
3222 })
3223 .unwrap();
3224 }
3225
3226 #[gpui::test]
3227 async fn test_deploy_search_with_multiple_panes(cx: &mut TestAppContext) {
3228 init_test(cx);
3229
3230 // Setup 2 panes, both with a file open and one with a project search.
3231 let fs = FakeFs::new(cx.background_executor.clone());
3232 fs.insert_tree(
3233 "/dir",
3234 json!({
3235 "one.rs": "const ONE: usize = 1;",
3236 }),
3237 )
3238 .await;
3239 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
3240 let worktree_id = project.update(cx, |this, cx| {
3241 this.worktrees().next().unwrap().read(cx).id()
3242 });
3243 let window = cx.add_window(|cx| Workspace::test_new(project, cx));
3244 let panes: Vec<_> = window
3245 .update(cx, |this, _| this.panes().to_owned())
3246 .unwrap();
3247 assert_eq!(panes.len(), 1);
3248 let first_pane = panes.get(0).cloned().unwrap();
3249 assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 0);
3250 window
3251 .update(cx, |workspace, cx| {
3252 workspace.open_path(
3253 (worktree_id, "one.rs"),
3254 Some(first_pane.downgrade()),
3255 true,
3256 cx,
3257 )
3258 })
3259 .unwrap()
3260 .await
3261 .unwrap();
3262 assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 1);
3263 let second_pane = window
3264 .update(cx, |workspace, cx| {
3265 workspace.split_and_clone(first_pane.clone(), workspace::SplitDirection::Right, cx)
3266 })
3267 .unwrap()
3268 .unwrap();
3269 assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 1);
3270 assert!(window
3271 .update(cx, |_, cx| second_pane
3272 .focus_handle(cx)
3273 .contains_focused(cx))
3274 .unwrap());
3275 let search_bar = window.build_view(cx, |_| ProjectSearchBar::new());
3276 window
3277 .update(cx, {
3278 let search_bar = search_bar.clone();
3279 let pane = first_pane.clone();
3280 move |workspace, cx| {
3281 assert_eq!(workspace.panes().len(), 2);
3282 pane.update(cx, move |pane, cx| {
3283 pane.toolbar()
3284 .update(cx, |toolbar, cx| toolbar.add_item(search_bar, cx))
3285 });
3286 }
3287 })
3288 .unwrap();
3289
3290 // Add a project search item to the second pane
3291 window
3292 .update(cx, {
3293 let search_bar = search_bar.clone();
3294 let pane = second_pane.clone();
3295 move |workspace, cx| {
3296 assert_eq!(workspace.panes().len(), 2);
3297 pane.update(cx, move |pane, cx| {
3298 pane.toolbar()
3299 .update(cx, |toolbar, cx| toolbar.add_item(search_bar, cx))
3300 });
3301
3302 ProjectSearchView::new_search(workspace, &workspace::NewSearch, cx)
3303 }
3304 })
3305 .unwrap();
3306
3307 cx.run_until_parked();
3308 assert_eq!(cx.update(|cx| second_pane.read(cx).items_len()), 2);
3309 assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 1);
3310
3311 // Focus the first pane
3312 window
3313 .update(cx, |workspace, cx| {
3314 assert_eq!(workspace.active_pane(), &second_pane);
3315 second_pane.update(cx, |this, cx| {
3316 assert_eq!(this.active_item_index(), 1);
3317 this.activate_prev_item(false, cx);
3318 assert_eq!(this.active_item_index(), 0);
3319 });
3320 workspace.activate_pane_in_direction(workspace::SplitDirection::Left, cx);
3321 })
3322 .unwrap();
3323 window
3324 .update(cx, |workspace, cx| {
3325 assert_eq!(workspace.active_pane(), &first_pane);
3326 assert_eq!(first_pane.read(cx).items_len(), 1);
3327 assert_eq!(second_pane.read(cx).items_len(), 2);
3328 })
3329 .unwrap();
3330
3331 // Deploy a new search
3332 cx.dispatch_action(window.into(), DeploySearch);
3333
3334 // Both panes should now have a project search in them
3335 window
3336 .update(cx, |workspace, cx| {
3337 assert_eq!(workspace.active_pane(), &first_pane);
3338 first_pane.update(cx, |this, _| {
3339 assert_eq!(this.active_item_index(), 1);
3340 assert_eq!(this.items_len(), 2);
3341 });
3342 second_pane.update(cx, |this, cx| {
3343 assert!(!cx.focus_handle().contains_focused(cx));
3344 assert_eq!(this.items_len(), 2);
3345 });
3346 })
3347 .unwrap();
3348
3349 // Focus the second pane's non-search item
3350 window
3351 .update(cx, |_workspace, cx| {
3352 second_pane.update(cx, |pane, cx| pane.activate_next_item(true, cx));
3353 })
3354 .unwrap();
3355
3356 // Deploy a new search
3357 cx.dispatch_action(window.into(), DeploySearch);
3358
3359 // The project search view should now be focused in the second pane
3360 // And the number of items should be unchanged.
3361 window
3362 .update(cx, |_workspace, cx| {
3363 second_pane.update(cx, |pane, _cx| {
3364 assert!(pane
3365 .active_item()
3366 .unwrap()
3367 .downcast::<ProjectSearchView>()
3368 .is_some());
3369
3370 assert_eq!(pane.items_len(), 2);
3371 });
3372 })
3373 .unwrap();
3374 }
3375
3376 #[gpui::test]
3377 async fn test_scroll_search_results_to_top(cx: &mut TestAppContext) {
3378 init_test(cx);
3379
3380 // We need many lines in the search results to be able to scroll the window
3381 let fs = FakeFs::new(cx.background_executor.clone());
3382 fs.insert_tree(
3383 "/dir",
3384 json!({
3385 "1.txt": "\n\n\n\n\n A \n\n\n\n\n",
3386 "2.txt": "\n\n\n\n\n A \n\n\n\n\n",
3387 "3.rs": "\n\n\n\n\n A \n\n\n\n\n",
3388 "4.rs": "\n\n\n\n\n A \n\n\n\n\n",
3389 "5.rs": "\n\n\n\n\n A \n\n\n\n\n",
3390 "6.rs": "\n\n\n\n\n A \n\n\n\n\n",
3391 "7.rs": "\n\n\n\n\n A \n\n\n\n\n",
3392 "8.rs": "\n\n\n\n\n A \n\n\n\n\n",
3393 "9.rs": "\n\n\n\n\n A \n\n\n\n\n",
3394 "a.rs": "\n\n\n\n\n A \n\n\n\n\n",
3395 "b.rs": "\n\n\n\n\n B \n\n\n\n\n",
3396 "c.rs": "\n\n\n\n\n B \n\n\n\n\n",
3397 "d.rs": "\n\n\n\n\n B \n\n\n\n\n",
3398 "e.rs": "\n\n\n\n\n B \n\n\n\n\n",
3399 "f.rs": "\n\n\n\n\n B \n\n\n\n\n",
3400 "g.rs": "\n\n\n\n\n B \n\n\n\n\n",
3401 "h.rs": "\n\n\n\n\n B \n\n\n\n\n",
3402 "i.rs": "\n\n\n\n\n B \n\n\n\n\n",
3403 "j.rs": "\n\n\n\n\n B \n\n\n\n\n",
3404 "k.rs": "\n\n\n\n\n B \n\n\n\n\n",
3405 }),
3406 )
3407 .await;
3408 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
3409 let search = cx.new_model(|cx| ProjectSearch::new(project, cx));
3410 let search_view = cx.add_window(|cx| ProjectSearchView::new(search.clone(), cx, None));
3411
3412 // First search
3413 perform_search(search_view, "A", cx);
3414 search_view
3415 .update(cx, |search_view, cx| {
3416 search_view.results_editor.update(cx, |results_editor, cx| {
3417 // Results are correct and scrolled to the top
3418 assert_eq!(
3419 results_editor.display_text(cx).match_indices(" A ").count(),
3420 10
3421 );
3422 assert_eq!(results_editor.scroll_position(cx), Point::default());
3423
3424 // Scroll results all the way down
3425 results_editor.scroll(Point::new(0., f32::MAX), Some(Axis::Vertical), cx);
3426 });
3427 })
3428 .expect("unable to update search view");
3429
3430 // Second search
3431 perform_search(search_view, "B", cx);
3432 search_view
3433 .update(cx, |search_view, cx| {
3434 search_view.results_editor.update(cx, |results_editor, cx| {
3435 // Results are correct...
3436 assert_eq!(
3437 results_editor.display_text(cx).match_indices(" B ").count(),
3438 10
3439 );
3440 // ...and scrolled back to the top
3441 assert_eq!(results_editor.scroll_position(cx), Point::default());
3442 });
3443 })
3444 .expect("unable to update search view");
3445 }
3446
3447 fn init_test(cx: &mut TestAppContext) {
3448 cx.update(|cx| {
3449 let settings = SettingsStore::test(cx);
3450 cx.set_global(settings);
3451
3452 SemanticIndexSettings::register(cx);
3453
3454 theme::init(theme::LoadThemes::JustBase, cx);
3455
3456 language::init(cx);
3457 client::init_settings(cx);
3458 editor::init(cx);
3459 workspace::init_settings(cx);
3460 Project::init_settings(cx);
3461 super::init(cx);
3462 });
3463 }
3464
3465 fn perform_search(
3466 search_view: WindowHandle<ProjectSearchView>,
3467 text: impl Into<Arc<str>>,
3468 cx: &mut TestAppContext,
3469 ) {
3470 search_view
3471 .update(cx, |search_view, cx| {
3472 search_view
3473 .query_editor
3474 .update(cx, |query_editor, cx| query_editor.set_text(text, cx));
3475 search_view.search(cx);
3476 })
3477 .unwrap();
3478 cx.background_executor.run_until_parked();
3479 }
3480}