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