1use crate::{
2 history::SearchHistory,
3 mode::{SearchMode, Side},
4 search_bar::{render_nav_button, render_option_button_icon, render_search_mode_button},
5 ActivateRegexMode, CycleMode, NextHistoryQuery, PreviousHistoryQuery, SearchOptions,
6 SelectNextMatch, SelectPrevMatch, ToggleCaseSensitive, ToggleWholeWord,
7};
8use anyhow::{Context, Result};
9use collections::HashMap;
10use editor::{
11 items::active_match_index, scroll::autoscroll::Autoscroll, Anchor, Editor, MultiBuffer,
12 SelectAll, MAX_TAB_TITLE_LEN,
13};
14use futures::StreamExt;
15
16use gpui::platform::PromptLevel;
17
18use gpui::{
19 actions, elements::*, platform::MouseButton, Action, AnyElement, AnyViewHandle, AppContext,
20 Entity, ModelContext, ModelHandle, Subscription, Task, View, ViewContext, ViewHandle,
21 WeakModelHandle, WeakViewHandle,
22};
23
24use menu::Confirm;
25use postage::stream::Stream;
26use project::{
27 search::{PathMatcher, SearchInputs, SearchQuery},
28 Entry, Project,
29};
30use semantic_index::SemanticIndex;
31use smallvec::SmallVec;
32use std::{
33 any::{Any, TypeId},
34 borrow::Cow,
35 collections::HashSet,
36 mem,
37 ops::{Not, Range},
38 path::PathBuf,
39 sync::Arc,
40};
41use util::ResultExt as _;
42use workspace::{
43 item::{BreadcrumbText, Item, ItemEvent, ItemHandle},
44 searchable::{Direction, SearchableItem, SearchableItemHandle},
45 ItemNavHistory, Pane, ToolbarItemLocation, ToolbarItemView, Workspace, WorkspaceId,
46};
47
48actions!(
49 project_search,
50 [SearchInNew, ToggleFocus, NextField, ToggleFilters,]
51);
52
53#[derive(Default)]
54struct ActiveSearches(HashMap<WeakModelHandle<Project>, WeakViewHandle<ProjectSearchView>>);
55
56pub fn init(cx: &mut AppContext) {
57 cx.set_global(ActiveSearches::default());
58 cx.add_action(ProjectSearchView::deploy);
59 cx.add_action(ProjectSearchView::move_focus_to_results);
60 cx.add_action(ProjectSearchBar::search);
61 cx.add_action(ProjectSearchBar::search_in_new);
62 cx.add_action(ProjectSearchBar::select_next_match);
63 cx.add_action(ProjectSearchBar::select_prev_match);
64 cx.add_action(ProjectSearchBar::cycle_mode);
65 cx.add_action(ProjectSearchBar::next_history_query);
66 cx.add_action(ProjectSearchBar::previous_history_query);
67 cx.add_action(ProjectSearchBar::activate_regex_mode);
68 cx.capture_action(ProjectSearchBar::tab);
69 cx.capture_action(ProjectSearchBar::tab_previous);
70 add_toggle_option_action::<ToggleCaseSensitive>(SearchOptions::CASE_SENSITIVE, cx);
71 add_toggle_option_action::<ToggleWholeWord>(SearchOptions::WHOLE_WORD, cx);
72 add_toggle_filters_action::<ToggleFilters>(cx);
73}
74
75fn add_toggle_filters_action<A: Action>(cx: &mut AppContext) {
76 cx.add_action(move |pane: &mut Pane, _: &A, cx: &mut ViewContext<Pane>| {
77 if let Some(search_bar) = pane.toolbar().read(cx).item_of_type::<ProjectSearchBar>() {
78 if search_bar.update(cx, |search_bar, cx| search_bar.toggle_filters(cx)) {
79 return;
80 }
81 }
82 cx.propagate_action();
83 });
84}
85
86fn add_toggle_option_action<A: Action>(option: SearchOptions, cx: &mut AppContext) {
87 cx.add_action(move |pane: &mut Pane, _: &A, cx: &mut ViewContext<Pane>| {
88 if let Some(search_bar) = pane.toolbar().read(cx).item_of_type::<ProjectSearchBar>() {
89 if search_bar.update(cx, |search_bar, cx| {
90 search_bar.toggle_search_option(option, cx)
91 }) {
92 return;
93 }
94 }
95 cx.propagate_action();
96 });
97}
98
99struct ProjectSearch {
100 project: ModelHandle<Project>,
101 excerpts: ModelHandle<MultiBuffer>,
102 pending_search: Option<Task<Option<()>>>,
103 match_ranges: Vec<Range<Anchor>>,
104 active_query: Option<SearchQuery>,
105 search_id: usize,
106 search_history: SearchHistory,
107 no_results: Option<bool>,
108}
109
110#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
111enum InputPanel {
112 Query,
113 Exclude,
114 Include,
115}
116
117pub struct ProjectSearchView {
118 model: ModelHandle<ProjectSearch>,
119 query_editor: ViewHandle<Editor>,
120 results_editor: ViewHandle<Editor>,
121 semantic_state: Option<SemanticSearchState>,
122 semantic_permissioned: Option<bool>,
123 search_options: SearchOptions,
124 panels_with_errors: HashSet<InputPanel>,
125 active_match_index: Option<usize>,
126 search_id: usize,
127 query_editor_was_focused: bool,
128 included_files_editor: ViewHandle<Editor>,
129 excluded_files_editor: ViewHandle<Editor>,
130 filters_enabled: bool,
131 current_mode: SearchMode,
132}
133
134struct SemanticSearchState {
135 file_count: usize,
136 outstanding_file_count: usize,
137 _progress_task: Task<()>,
138}
139
140pub struct ProjectSearchBar {
141 active_project_search: Option<ViewHandle<ProjectSearchView>>,
142 subscription: Option<Subscription>,
143}
144
145impl Entity for ProjectSearch {
146 type Event = ();
147}
148
149impl ProjectSearch {
150 fn new(project: ModelHandle<Project>, cx: &mut ModelContext<Self>) -> Self {
151 let replica_id = project.read(cx).replica_id();
152 Self {
153 project,
154 excerpts: cx.add_model(|_| MultiBuffer::new(replica_id)),
155 pending_search: Default::default(),
156 match_ranges: Default::default(),
157 active_query: None,
158 search_id: 0,
159 search_history: SearchHistory::default(),
160 no_results: None,
161 }
162 }
163
164 fn clone(&self, cx: &mut ModelContext<Self>) -> ModelHandle<Self> {
165 cx.add_model(|cx| Self {
166 project: self.project.clone(),
167 excerpts: self
168 .excerpts
169 .update(cx, |excerpts, cx| cx.add_model(|cx| excerpts.clone(cx))),
170 pending_search: Default::default(),
171 match_ranges: self.match_ranges.clone(),
172 active_query: self.active_query.clone(),
173 search_id: self.search_id,
174 search_history: self.search_history.clone(),
175 no_results: self.no_results.clone(),
176 })
177 }
178
179 fn search(&mut self, query: SearchQuery, cx: &mut ModelContext<Self>) {
180 let search = self
181 .project
182 .update(cx, |project, cx| project.search(query.clone(), cx));
183 self.search_id += 1;
184 self.search_history.add(query.as_str().to_string());
185 self.active_query = Some(query);
186 self.match_ranges.clear();
187 self.pending_search = Some(cx.spawn_weak(|this, mut cx| async move {
188 let matches = search.await.log_err()?;
189 let this = this.upgrade(&cx)?;
190 let mut matches = matches.into_iter().collect::<Vec<_>>();
191 let (_task, mut match_ranges) = this.update(&mut cx, |this, cx| {
192 this.match_ranges.clear();
193 this.no_results = Some(true);
194 matches.sort_by_key(|(buffer, _)| buffer.read(cx).file().map(|file| file.path()));
195 this.excerpts.update(cx, |excerpts, cx| {
196 excerpts.clear(cx);
197 excerpts.stream_excerpts_with_context_lines(matches, 1, cx)
198 })
199 });
200
201 while let Some(match_range) = match_ranges.next().await {
202 this.update(&mut cx, |this, cx| {
203 this.match_ranges.push(match_range);
204 while let Ok(Some(match_range)) = match_ranges.try_next() {
205 this.match_ranges.push(match_range);
206 }
207 this.no_results = Some(false);
208 cx.notify();
209 });
210 }
211
212 this.update(&mut cx, |this, cx| {
213 this.pending_search.take();
214 cx.notify();
215 });
216
217 None
218 }));
219 cx.notify();
220 }
221
222 fn semantic_search(&mut self, inputs: &SearchInputs, cx: &mut ModelContext<Self>) {
223 let search = SemanticIndex::global(cx).map(|index| {
224 index.update(cx, |semantic_index, cx| {
225 semantic_index.search_project(
226 self.project.clone(),
227 inputs.as_str().to_owned(),
228 10,
229 inputs.files_to_include().to_vec(),
230 inputs.files_to_exclude().to_vec(),
231 cx,
232 )
233 })
234 });
235 self.search_id += 1;
236 self.match_ranges.clear();
237 self.search_history.add(inputs.as_str().to_string());
238 self.no_results = Some(true);
239 self.pending_search = Some(cx.spawn(|this, mut cx| async move {
240 let results = search?.await.log_err()?;
241
242 let (_task, mut match_ranges) = this.update(&mut cx, |this, cx| {
243 this.excerpts.update(cx, |excerpts, cx| {
244 excerpts.clear(cx);
245
246 let matches = results
247 .into_iter()
248 .map(|result| (result.buffer, vec![result.range.start..result.range.start]))
249 .collect();
250
251 excerpts.stream_excerpts_with_context_lines(matches, 3, cx)
252 })
253 });
254
255 while let Some(match_range) = match_ranges.next().await {
256 this.update(&mut cx, |this, cx| {
257 this.match_ranges.push(match_range);
258 while let Ok(Some(match_range)) = match_ranges.try_next() {
259 this.match_ranges.push(match_range);
260 }
261 this.no_results = Some(false);
262 cx.notify();
263 });
264 }
265
266 this.update(&mut cx, |this, cx| {
267 this.pending_search.take();
268 cx.notify();
269 });
270
271 None
272 }));
273 cx.notify();
274 }
275}
276
277#[derive(Clone, Debug, PartialEq, Eq)]
278pub enum ViewEvent {
279 UpdateTab,
280 Activate,
281 EditorEvent(editor::Event),
282 Dismiss,
283}
284
285impl Entity for ProjectSearchView {
286 type Event = ViewEvent;
287}
288
289impl View for ProjectSearchView {
290 fn ui_name() -> &'static str {
291 "ProjectSearchView"
292 }
293
294 fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
295 let model = &self.model.read(cx);
296 if model.match_ranges.is_empty() {
297 enum Status {}
298
299 let theme = theme::current(cx).clone();
300
301 // If Search is Active -> Major: Searching..., Minor: None
302 // If Semantic -> Major: "Search using Natural Language", Minor: {Status}/n{ex...}/n{ex...}
303 // If Regex -> Major: "Search using Regex", Minor: {ex...}
304 // If Text -> Major: "Text search all files and folders", Minor: {...}
305
306 let current_mode = self.current_mode;
307 let major_text = if model.pending_search.is_some() {
308 Cow::Borrowed("Searching...")
309 } else if model.no_results.is_some_and(|v| v) {
310 Cow::Borrowed("No Results")
311 } else {
312 match current_mode {
313 SearchMode::Text => Cow::Borrowed("Text search all files and folders"),
314 SearchMode::Semantic => {
315 Cow::Borrowed("Search all code objects using Natural Language")
316 }
317 SearchMode::Regex => Cow::Borrowed("Regex search all files and folders"),
318 }
319 };
320
321 let semantic_status = if let Some(semantic) = &self.semantic_state {
322 if semantic.outstanding_file_count > 0 {
323 format!(
324 "Indexing: {} of {}...",
325 semantic.file_count - semantic.outstanding_file_count,
326 semantic.file_count
327 )
328 } else {
329 "Indexing complete".to_string()
330 }
331 } else {
332 "Indexing: ...".to_string()
333 };
334
335 let minor_text = if let Some(no_results) = model.no_results {
336 if model.pending_search.is_none() && no_results {
337 vec!["No results found in this project for the provided query".to_owned()]
338 } else {
339 vec![]
340 }
341 } else {
342 match current_mode {
343 SearchMode::Semantic => vec![
344 "".to_owned(),
345 semantic_status,
346 "Simply explain the code you are looking to find.".to_owned(),
347 "ex. 'prompt user for permissions to index their project'".to_owned(),
348 ],
349 _ => vec![
350 "".to_owned(),
351 "Include/exclude specific paths with the filter option.".to_owned(),
352 "Matching exact word and/or casing is available too.".to_owned(),
353 ],
354 }
355 };
356
357 let previous_query_keystrokes =
358 cx.binding_for_action(&PreviousHistoryQuery {})
359 .map(|binding| {
360 binding
361 .keystrokes()
362 .iter()
363 .map(|k| k.to_string())
364 .collect::<Vec<_>>()
365 });
366 let next_query_keystrokes =
367 cx.binding_for_action(&NextHistoryQuery {}).map(|binding| {
368 binding
369 .keystrokes()
370 .iter()
371 .map(|k| k.to_string())
372 .collect::<Vec<_>>()
373 });
374 let new_placeholder_text = match (previous_query_keystrokes, next_query_keystrokes) {
375 (Some(previous_query_keystrokes), Some(next_query_keystrokes)) => {
376 format!(
377 "Search ({}/{} for previous/next query)",
378 previous_query_keystrokes.join(" "),
379 next_query_keystrokes.join(" ")
380 )
381 }
382 (None, Some(next_query_keystrokes)) => {
383 format!(
384 "Search ({} for next query)",
385 next_query_keystrokes.join(" ")
386 )
387 }
388 (Some(previous_query_keystrokes), None) => {
389 format!(
390 "Search ({} for previous query)",
391 previous_query_keystrokes.join(" ")
392 )
393 }
394 (None, None) => String::new(),
395 };
396 self.query_editor.update(cx, |editor, cx| {
397 editor.set_placeholder_text(new_placeholder_text, cx);
398 });
399
400 MouseEventHandler::new::<Status, _>(0, cx, |_, _| {
401 Flex::column()
402 .with_child(Flex::column().contained().flex(1., true))
403 .with_child(
404 Flex::column()
405 .align_children_center()
406 .with_child(Label::new(
407 major_text,
408 theme.search.major_results_status.clone(),
409 ))
410 .with_children(
411 minor_text.into_iter().map(|x| {
412 Label::new(x, theme.search.minor_results_status.clone())
413 }),
414 )
415 .aligned()
416 .top()
417 .contained()
418 .flex(7., true),
419 )
420 .contained()
421 .with_background_color(theme.editor.background)
422 })
423 .on_down(MouseButton::Left, |_, _, cx| {
424 cx.focus_parent();
425 })
426 .into_any_named("project search view")
427 } else {
428 ChildView::new(&self.results_editor, cx)
429 .flex(1., true)
430 .into_any_named("project search view")
431 }
432 }
433
434 fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
435 let handle = cx.weak_handle();
436 cx.update_global(|state: &mut ActiveSearches, cx| {
437 state
438 .0
439 .insert(self.model.read(cx).project.downgrade(), handle)
440 });
441
442 if cx.is_self_focused() {
443 if self.query_editor_was_focused {
444 cx.focus(&self.query_editor);
445 } else {
446 cx.focus(&self.results_editor);
447 }
448 }
449 }
450}
451
452impl Item for ProjectSearchView {
453 fn tab_tooltip_text(&self, cx: &AppContext) -> Option<Cow<str>> {
454 let query_text = self.query_editor.read(cx).text(cx);
455
456 query_text
457 .is_empty()
458 .not()
459 .then(|| query_text.into())
460 .or_else(|| Some("Project Search".into()))
461 }
462 fn should_close_item_on_event(event: &Self::Event) -> bool {
463 event == &Self::Event::Dismiss
464 }
465 fn act_as_type<'a>(
466 &'a self,
467 type_id: TypeId,
468 self_handle: &'a ViewHandle<Self>,
469 _: &'a AppContext,
470 ) -> Option<&'a AnyViewHandle> {
471 if type_id == TypeId::of::<Self>() {
472 Some(self_handle)
473 } else if type_id == TypeId::of::<Editor>() {
474 Some(&self.results_editor)
475 } else {
476 None
477 }
478 }
479
480 fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
481 self.results_editor
482 .update(cx, |editor, cx| editor.deactivated(cx));
483 }
484
485 fn tab_content<T: 'static>(
486 &self,
487 _detail: Option<usize>,
488 tab_theme: &theme::Tab,
489 cx: &AppContext,
490 ) -> AnyElement<T> {
491 Flex::row()
492 .with_child(
493 Svg::new("icons/magnifying_glass_12.svg")
494 .with_color(tab_theme.label.text.color)
495 .constrained()
496 .with_width(tab_theme.type_icon_width)
497 .aligned()
498 .contained()
499 .with_margin_right(tab_theme.spacing),
500 )
501 .with_child({
502 let tab_name: Option<Cow<_>> = self
503 .model
504 .read(cx)
505 .search_history
506 .current()
507 .as_ref()
508 .map(|query| {
509 let query_text = util::truncate_and_trailoff(query, MAX_TAB_TITLE_LEN);
510 query_text.into()
511 });
512 Label::new(
513 tab_name
514 .filter(|name| !name.is_empty())
515 .unwrap_or("Project search".into()),
516 tab_theme.label.clone(),
517 )
518 .aligned()
519 })
520 .into_any()
521 }
522
523 fn for_each_project_item(&self, cx: &AppContext, f: &mut dyn FnMut(usize, &dyn project::Item)) {
524 self.results_editor.for_each_project_item(cx, f)
525 }
526
527 fn is_singleton(&self, _: &AppContext) -> bool {
528 false
529 }
530
531 fn can_save(&self, _: &AppContext) -> bool {
532 true
533 }
534
535 fn is_dirty(&self, cx: &AppContext) -> bool {
536 self.results_editor.read(cx).is_dirty(cx)
537 }
538
539 fn has_conflict(&self, cx: &AppContext) -> bool {
540 self.results_editor.read(cx).has_conflict(cx)
541 }
542
543 fn save(
544 &mut self,
545 project: ModelHandle<Project>,
546 cx: &mut ViewContext<Self>,
547 ) -> Task<anyhow::Result<()>> {
548 self.results_editor
549 .update(cx, |editor, cx| editor.save(project, cx))
550 }
551
552 fn save_as(
553 &mut self,
554 _: ModelHandle<Project>,
555 _: PathBuf,
556 _: &mut ViewContext<Self>,
557 ) -> Task<anyhow::Result<()>> {
558 unreachable!("save_as should not have been called")
559 }
560
561 fn reload(
562 &mut self,
563 project: ModelHandle<Project>,
564 cx: &mut ViewContext<Self>,
565 ) -> Task<anyhow::Result<()>> {
566 self.results_editor
567 .update(cx, |editor, cx| editor.reload(project, cx))
568 }
569
570 fn clone_on_split(&self, _workspace_id: WorkspaceId, cx: &mut ViewContext<Self>) -> Option<Self>
571 where
572 Self: Sized,
573 {
574 let model = self.model.update(cx, |model, cx| model.clone(cx));
575 Some(Self::new(model, cx))
576 }
577
578 fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
579 self.results_editor
580 .update(cx, |editor, cx| editor.added_to_workspace(workspace, cx));
581 }
582
583 fn set_nav_history(&mut self, nav_history: ItemNavHistory, cx: &mut ViewContext<Self>) {
584 self.results_editor.update(cx, |editor, _| {
585 editor.set_nav_history(Some(nav_history));
586 });
587 }
588
589 fn navigate(&mut self, data: Box<dyn Any>, cx: &mut ViewContext<Self>) -> bool {
590 self.results_editor
591 .update(cx, |editor, cx| editor.navigate(data, cx))
592 }
593
594 fn to_item_events(event: &Self::Event) -> SmallVec<[ItemEvent; 2]> {
595 match event {
596 ViewEvent::UpdateTab => {
597 smallvec::smallvec![ItemEvent::UpdateBreadcrumbs, ItemEvent::UpdateTab]
598 }
599 ViewEvent::EditorEvent(editor_event) => Editor::to_item_events(editor_event),
600 ViewEvent::Dismiss => smallvec::smallvec![ItemEvent::CloseItem],
601 _ => SmallVec::new(),
602 }
603 }
604
605 fn breadcrumb_location(&self) -> ToolbarItemLocation {
606 if self.has_matches() {
607 ToolbarItemLocation::Secondary
608 } else {
609 ToolbarItemLocation::Hidden
610 }
611 }
612
613 fn breadcrumbs(&self, theme: &theme::Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
614 self.results_editor.breadcrumbs(theme, cx)
615 }
616
617 fn serialized_item_kind() -> Option<&'static str> {
618 None
619 }
620
621 fn deserialize(
622 _project: ModelHandle<Project>,
623 _workspace: WeakViewHandle<Workspace>,
624 _workspace_id: workspace::WorkspaceId,
625 _item_id: workspace::ItemId,
626 _cx: &mut ViewContext<Pane>,
627 ) -> Task<anyhow::Result<ViewHandle<Self>>> {
628 unimplemented!()
629 }
630}
631
632impl ProjectSearchView {
633 fn toggle_search_option(&mut self, option: SearchOptions) {
634 self.search_options.toggle(option);
635 }
636
637 fn index_project(&mut self, cx: &mut ViewContext<Self>) {
638 if let Some(semantic_index) = SemanticIndex::global(cx) {
639 // Semantic search uses no options
640 self.search_options = SearchOptions::none();
641
642 let project = self.model.read(cx).project.clone();
643 let index_task = semantic_index.update(cx, |semantic_index, cx| {
644 semantic_index.index_project(project, cx)
645 });
646
647 cx.spawn(|search_view, mut cx| async move {
648 let (files_to_index, mut files_remaining_rx) = index_task.await?;
649
650 search_view.update(&mut cx, |search_view, cx| {
651 cx.notify();
652 search_view.semantic_state = Some(SemanticSearchState {
653 file_count: files_to_index,
654 outstanding_file_count: files_to_index,
655 _progress_task: cx.spawn(|search_view, mut cx| async move {
656 while let Some(count) = files_remaining_rx.recv().await {
657 search_view
658 .update(&mut cx, |search_view, cx| {
659 if let Some(semantic_search_state) =
660 &mut search_view.semantic_state
661 {
662 semantic_search_state.outstanding_file_count = count;
663 cx.notify();
664 if count == 0 {
665 return;
666 }
667 }
668 })
669 .ok();
670 }
671 }),
672 });
673 })?;
674 anyhow::Ok(())
675 })
676 .detach_and_log_err(cx);
677 }
678 }
679
680 fn clear_search(&mut self, cx: &mut ViewContext<Self>) {
681 self.model.update(cx, |model, cx| {
682 model.pending_search = None;
683 model.no_results = None;
684 model.match_ranges.clear();
685
686 model.excerpts.update(cx, |excerpts, cx| {
687 excerpts.clear(cx);
688 });
689 });
690 }
691
692 fn activate_search_mode(&mut self, mode: SearchMode, cx: &mut ViewContext<Self>) {
693 let previous_mode = self.current_mode;
694 if previous_mode == mode {
695 return;
696 }
697
698 self.clear_search(cx);
699 self.current_mode = mode;
700 self.active_match_index = None;
701
702 match mode {
703 SearchMode::Semantic => {
704 let has_permission = self.semantic_permissioned(cx);
705 self.active_match_index = None;
706 cx.spawn(|this, mut cx| async move {
707 let has_permission = has_permission.await?;
708
709 if !has_permission {
710 let mut answer = this.update(&mut cx, |this, cx| {
711 let project = this.model.read(cx).project.clone();
712 let project_name = project
713 .read(cx)
714 .worktree_root_names(cx)
715 .collect::<Vec<&str>>()
716 .join("/");
717 let is_plural =
718 project_name.chars().filter(|letter| *letter == '/').count() > 0;
719 let prompt_text = format!("Would you like to index the '{}' project{} for semantic search? This requires sending code to the OpenAI API", project_name,
720 if is_plural {
721 "s"
722 } else {""});
723 cx.prompt(
724 PromptLevel::Info,
725 prompt_text.as_str(),
726 &["Continue", "Cancel"],
727 )
728 })?;
729
730 if answer.next().await == Some(0) {
731 this.update(&mut cx, |this, _| {
732 this.semantic_permissioned = Some(true);
733 })?;
734 } else {
735 this.update(&mut cx, |this, cx| {
736 this.semantic_permissioned = Some(false);
737 debug_assert_ne!(previous_mode, SearchMode::Semantic, "Tried to re-enable semantic search mode after user modal was rejected");
738 this.activate_search_mode(previous_mode, cx);
739 })?;
740 return anyhow::Ok(());
741 }
742 }
743
744 this.update(&mut cx, |this, cx| {
745 this.index_project(cx);
746 })?;
747
748 anyhow::Ok(())
749 }).detach_and_log_err(cx);
750 }
751 SearchMode::Regex | SearchMode::Text => {
752 self.semantic_state = None;
753 self.active_match_index = None;
754 self.search(cx);
755 }
756 }
757
758 cx.notify();
759 }
760
761 fn new(model: ModelHandle<ProjectSearch>, cx: &mut ViewContext<Self>) -> Self {
762 let project;
763 let excerpts;
764 let mut query_text = String::new();
765 let mut options = SearchOptions::NONE;
766
767 {
768 let model = model.read(cx);
769 project = model.project.clone();
770 excerpts = model.excerpts.clone();
771 if let Some(active_query) = model.active_query.as_ref() {
772 query_text = active_query.as_str().to_string();
773 options = SearchOptions::from_query(active_query);
774 }
775 }
776 cx.observe(&model, |this, _, cx| this.model_changed(cx))
777 .detach();
778
779 let query_editor = cx.add_view(|cx| {
780 let mut editor = Editor::single_line(
781 Some(Arc::new(|theme| theme.search.editor.input.clone())),
782 cx,
783 );
784 editor.set_placeholder_text("Text search all files", cx);
785 editor.set_text(query_text, cx);
786 editor
787 });
788 // Subscribe to query_editor in order to reraise editor events for workspace item activation purposes
789 cx.subscribe(&query_editor, |_, _, event, cx| {
790 cx.emit(ViewEvent::EditorEvent(event.clone()))
791 })
792 .detach();
793
794 let results_editor = cx.add_view(|cx| {
795 let mut editor = Editor::for_multibuffer(excerpts, Some(project.clone()), cx);
796 editor.set_searchable(false);
797 editor
798 });
799 cx.observe(&results_editor, |_, _, cx| cx.emit(ViewEvent::UpdateTab))
800 .detach();
801
802 cx.subscribe(&results_editor, |this, _, event, cx| {
803 if matches!(event, editor::Event::SelectionsChanged { .. }) {
804 this.update_match_index(cx);
805 }
806 // Reraise editor events for workspace item activation purposes
807 cx.emit(ViewEvent::EditorEvent(event.clone()));
808 })
809 .detach();
810
811 let included_files_editor = cx.add_view(|cx| {
812 let mut editor = Editor::single_line(
813 Some(Arc::new(|theme| {
814 theme.search.include_exclude_editor.input.clone()
815 })),
816 cx,
817 );
818 editor.set_placeholder_text("Include: crates/**/*.toml", cx);
819
820 editor
821 });
822 // Subscribe to include_files_editor in order to reraise editor events for workspace item activation purposes
823 cx.subscribe(&included_files_editor, |_, _, event, cx| {
824 cx.emit(ViewEvent::EditorEvent(event.clone()))
825 })
826 .detach();
827
828 let excluded_files_editor = cx.add_view(|cx| {
829 let mut editor = Editor::single_line(
830 Some(Arc::new(|theme| {
831 theme.search.include_exclude_editor.input.clone()
832 })),
833 cx,
834 );
835 editor.set_placeholder_text("Exclude: vendor/*, *.lock", cx);
836
837 editor
838 });
839 // Subscribe to excluded_files_editor in order to reraise editor events for workspace item activation purposes
840 cx.subscribe(&excluded_files_editor, |_, _, event, cx| {
841 cx.emit(ViewEvent::EditorEvent(event.clone()))
842 })
843 .detach();
844 let filters_enabled = false;
845
846 // Check if Worktrees have all been previously indexed
847 let mut this = ProjectSearchView {
848 search_id: model.read(cx).search_id,
849 model,
850 query_editor,
851 results_editor,
852 semantic_state: None,
853 semantic_permissioned: None,
854 search_options: options,
855 panels_with_errors: HashSet::new(),
856 active_match_index: None,
857 query_editor_was_focused: false,
858 included_files_editor,
859 excluded_files_editor,
860 filters_enabled,
861 current_mode: Default::default(),
862 };
863 this.model_changed(cx);
864 this
865 }
866
867 fn semantic_permissioned(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<bool>> {
868 if let Some(value) = self.semantic_permissioned {
869 return Task::ready(Ok(value));
870 }
871
872 SemanticIndex::global(cx)
873 .map(|semantic| {
874 let project = self.model.read(cx).project.clone();
875 semantic.update(cx, |this, cx| this.project_previously_indexed(project, cx))
876 })
877 .unwrap_or(Task::ready(Ok(false)))
878 }
879 pub fn new_search_in_directory(
880 workspace: &mut Workspace,
881 dir_entry: &Entry,
882 cx: &mut ViewContext<Workspace>,
883 ) {
884 if !dir_entry.is_dir() {
885 return;
886 }
887 let Some(filter_str) = dir_entry.path.to_str() else { return; };
888
889 let model = cx.add_model(|cx| ProjectSearch::new(workspace.project().clone(), cx));
890 let search = cx.add_view(|cx| ProjectSearchView::new(model, cx));
891 workspace.add_item(Box::new(search.clone()), cx);
892 search.update(cx, |search, cx| {
893 search
894 .included_files_editor
895 .update(cx, |editor, cx| editor.set_text(filter_str, cx));
896 search.focus_query_editor(cx)
897 });
898 }
899
900 // Re-activate the most recently activated search or the most recent if it has been closed.
901 // If no search exists in the workspace, create a new one.
902 fn deploy(
903 workspace: &mut Workspace,
904 _: &workspace::NewSearch,
905 cx: &mut ViewContext<Workspace>,
906 ) {
907 // Clean up entries for dropped projects
908 cx.update_global(|state: &mut ActiveSearches, cx| {
909 state.0.retain(|project, _| project.is_upgradable(cx))
910 });
911
912 let active_search = cx
913 .global::<ActiveSearches>()
914 .0
915 .get(&workspace.project().downgrade());
916
917 let existing = active_search
918 .and_then(|active_search| {
919 workspace
920 .items_of_type::<ProjectSearchView>(cx)
921 .find(|search| search == active_search)
922 })
923 .or_else(|| workspace.item_of_type::<ProjectSearchView>(cx));
924
925 let query = workspace.active_item(cx).and_then(|item| {
926 let editor = item.act_as::<Editor>(cx)?;
927 let query = editor.query_suggestion(cx);
928 if query.is_empty() {
929 None
930 } else {
931 Some(query)
932 }
933 });
934
935 let search = if let Some(existing) = existing {
936 workspace.activate_item(&existing, cx);
937 existing
938 } else {
939 let model = cx.add_model(|cx| ProjectSearch::new(workspace.project().clone(), cx));
940 let view = cx.add_view(|cx| ProjectSearchView::new(model, cx));
941 workspace.add_item(Box::new(view.clone()), cx);
942 view
943 };
944
945 search.update(cx, |search, cx| {
946 if let Some(query) = query {
947 search.set_query(&query, cx);
948 }
949 search.focus_query_editor(cx)
950 });
951 }
952
953 fn search(&mut self, cx: &mut ViewContext<Self>) {
954 let mode = self.current_mode;
955 match mode {
956 SearchMode::Semantic => {
957 if let Some(semantic) = &mut self.semantic_state {
958 if semantic.outstanding_file_count > 0 {
959 return;
960 }
961
962 if let Some(query) = self.build_search_query(cx) {
963 self.model
964 .update(cx, |model, cx| model.semantic_search(query.as_inner(), cx));
965 }
966 }
967 }
968
969 _ => {
970 if let Some(query) = self.build_search_query(cx) {
971 self.model.update(cx, |model, cx| model.search(query, cx));
972 }
973 }
974 }
975 }
976
977 fn build_search_query(&mut self, cx: &mut ViewContext<Self>) -> Option<SearchQuery> {
978 let text = self.query_editor.read(cx).text(cx);
979 let included_files =
980 match Self::parse_path_matches(&self.included_files_editor.read(cx).text(cx)) {
981 Ok(included_files) => {
982 self.panels_with_errors.remove(&InputPanel::Include);
983 included_files
984 }
985 Err(_e) => {
986 self.panels_with_errors.insert(InputPanel::Include);
987 cx.notify();
988 return None;
989 }
990 };
991 let excluded_files =
992 match Self::parse_path_matches(&self.excluded_files_editor.read(cx).text(cx)) {
993 Ok(excluded_files) => {
994 self.panels_with_errors.remove(&InputPanel::Exclude);
995 excluded_files
996 }
997 Err(_e) => {
998 self.panels_with_errors.insert(InputPanel::Exclude);
999 cx.notify();
1000 return None;
1001 }
1002 };
1003 let current_mode = self.current_mode;
1004 match current_mode {
1005 SearchMode::Regex => {
1006 match SearchQuery::regex(
1007 text,
1008 self.search_options.contains(SearchOptions::WHOLE_WORD),
1009 self.search_options.contains(SearchOptions::CASE_SENSITIVE),
1010 included_files,
1011 excluded_files,
1012 ) {
1013 Ok(query) => {
1014 self.panels_with_errors.remove(&InputPanel::Query);
1015 Some(query)
1016 }
1017 Err(_e) => {
1018 self.panels_with_errors.insert(InputPanel::Query);
1019 cx.notify();
1020 None
1021 }
1022 }
1023 }
1024 _ => Some(SearchQuery::text(
1025 text,
1026 self.search_options.contains(SearchOptions::WHOLE_WORD),
1027 self.search_options.contains(SearchOptions::CASE_SENSITIVE),
1028 included_files,
1029 excluded_files,
1030 )),
1031 }
1032 }
1033
1034 fn parse_path_matches(text: &str) -> anyhow::Result<Vec<PathMatcher>> {
1035 text.split(',')
1036 .map(str::trim)
1037 .filter(|maybe_glob_str| !maybe_glob_str.is_empty())
1038 .map(|maybe_glob_str| {
1039 PathMatcher::new(maybe_glob_str)
1040 .with_context(|| format!("parsing {maybe_glob_str} as path matcher"))
1041 })
1042 .collect()
1043 }
1044
1045 fn select_match(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
1046 if let Some(index) = self.active_match_index {
1047 let match_ranges = self.model.read(cx).match_ranges.clone();
1048 let new_index = self.results_editor.update(cx, |editor, cx| {
1049 editor.match_index_for_direction(&match_ranges, index, direction, 1, cx)
1050 });
1051
1052 let range_to_select = match_ranges[new_index].clone();
1053 self.results_editor.update(cx, |editor, cx| {
1054 let range_to_select = editor.range_for_match(&range_to_select);
1055 editor.unfold_ranges([range_to_select.clone()], false, true, cx);
1056 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
1057 s.select_ranges([range_to_select])
1058 });
1059 });
1060 }
1061 }
1062
1063 fn focus_query_editor(&mut self, cx: &mut ViewContext<Self>) {
1064 self.query_editor.update(cx, |query_editor, cx| {
1065 query_editor.select_all(&SelectAll, cx);
1066 });
1067 self.query_editor_was_focused = true;
1068 cx.focus(&self.query_editor);
1069 }
1070
1071 fn set_query(&mut self, query: &str, cx: &mut ViewContext<Self>) {
1072 self.query_editor
1073 .update(cx, |query_editor, cx| query_editor.set_text(query, cx));
1074 }
1075
1076 fn focus_results_editor(&mut self, cx: &mut ViewContext<Self>) {
1077 self.query_editor.update(cx, |query_editor, cx| {
1078 let cursor = query_editor.selections.newest_anchor().head();
1079 query_editor.change_selections(None, cx, |s| s.select_ranges([cursor.clone()..cursor]));
1080 });
1081 self.query_editor_was_focused = false;
1082 cx.focus(&self.results_editor);
1083 }
1084
1085 fn model_changed(&mut self, cx: &mut ViewContext<Self>) {
1086 let match_ranges = self.model.read(cx).match_ranges.clone();
1087 if match_ranges.is_empty() {
1088 self.active_match_index = None;
1089 } else {
1090 self.active_match_index = Some(0);
1091 self.update_match_index(cx);
1092 let prev_search_id = mem::replace(&mut self.search_id, self.model.read(cx).search_id);
1093 let is_new_search = self.search_id != prev_search_id;
1094 self.results_editor.update(cx, |editor, cx| {
1095 if is_new_search {
1096 let range_to_select = match_ranges
1097 .first()
1098 .clone()
1099 .map(|range| editor.range_for_match(range));
1100 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
1101 s.select_ranges(range_to_select)
1102 });
1103 }
1104 editor.highlight_background::<Self>(
1105 match_ranges,
1106 |theme| theme.search.match_background,
1107 cx,
1108 );
1109 });
1110 if is_new_search && self.query_editor.is_focused(cx) {
1111 self.focus_results_editor(cx);
1112 }
1113 }
1114
1115 cx.emit(ViewEvent::UpdateTab);
1116 cx.notify();
1117 }
1118
1119 fn update_match_index(&mut self, cx: &mut ViewContext<Self>) {
1120 let results_editor = self.results_editor.read(cx);
1121 let new_index = active_match_index(
1122 &self.model.read(cx).match_ranges,
1123 &results_editor.selections.newest_anchor().head(),
1124 &results_editor.buffer().read(cx).snapshot(cx),
1125 );
1126 if self.active_match_index != new_index {
1127 self.active_match_index = new_index;
1128 cx.notify();
1129 }
1130 }
1131
1132 pub fn has_matches(&self) -> bool {
1133 self.active_match_index.is_some()
1134 }
1135
1136 fn move_focus_to_results(pane: &mut Pane, _: &ToggleFocus, cx: &mut ViewContext<Pane>) {
1137 if let Some(search_view) = pane
1138 .active_item()
1139 .and_then(|item| item.downcast::<ProjectSearchView>())
1140 {
1141 search_view.update(cx, |search_view, cx| {
1142 if !search_view.results_editor.is_focused(cx)
1143 && !search_view.model.read(cx).match_ranges.is_empty()
1144 {
1145 return search_view.focus_results_editor(cx);
1146 }
1147 });
1148 }
1149
1150 cx.propagate_action();
1151 }
1152}
1153
1154impl Default for ProjectSearchBar {
1155 fn default() -> Self {
1156 Self::new()
1157 }
1158}
1159
1160impl ProjectSearchBar {
1161 pub fn new() -> Self {
1162 Self {
1163 active_project_search: Default::default(),
1164 subscription: Default::default(),
1165 }
1166 }
1167 fn cycle_mode(workspace: &mut Workspace, _: &CycleMode, cx: &mut ViewContext<Workspace>) {
1168 if let Some(search_view) = workspace
1169 .active_item(cx)
1170 .and_then(|item| item.downcast::<ProjectSearchView>())
1171 {
1172 search_view.update(cx, |this, cx| {
1173 let new_mode =
1174 crate::mode::next_mode(&this.current_mode, SemanticIndex::enabled(cx));
1175 this.activate_search_mode(new_mode, cx);
1176 cx.focus(&this.query_editor);
1177 })
1178 }
1179 }
1180 fn search(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
1181 if let Some(search_view) = self.active_project_search.as_ref() {
1182 search_view.update(cx, |search_view, cx| search_view.search(cx));
1183 }
1184 }
1185
1186 fn search_in_new(workspace: &mut Workspace, _: &SearchInNew, cx: &mut ViewContext<Workspace>) {
1187 if let Some(search_view) = workspace
1188 .active_item(cx)
1189 .and_then(|item| item.downcast::<ProjectSearchView>())
1190 {
1191 let new_query = search_view.update(cx, |search_view, cx| {
1192 let new_query = search_view.build_search_query(cx);
1193 if new_query.is_some() {
1194 if let Some(old_query) = search_view.model.read(cx).active_query.clone() {
1195 search_view.query_editor.update(cx, |editor, cx| {
1196 editor.set_text(old_query.as_str(), cx);
1197 });
1198 search_view.search_options = SearchOptions::from_query(&old_query);
1199 }
1200 }
1201 new_query
1202 });
1203 if let Some(new_query) = new_query {
1204 let model = cx.add_model(|cx| {
1205 let mut model = ProjectSearch::new(workspace.project().clone(), cx);
1206 model.search(new_query, cx);
1207 model
1208 });
1209 workspace.add_item(
1210 Box::new(cx.add_view(|cx| ProjectSearchView::new(model, cx))),
1211 cx,
1212 );
1213 }
1214 }
1215 }
1216
1217 fn select_next_match(pane: &mut Pane, _: &SelectNextMatch, cx: &mut ViewContext<Pane>) {
1218 if let Some(search_view) = pane
1219 .active_item()
1220 .and_then(|item| item.downcast::<ProjectSearchView>())
1221 {
1222 search_view.update(cx, |view, cx| view.select_match(Direction::Next, cx));
1223 } else {
1224 cx.propagate_action();
1225 }
1226 }
1227
1228 fn select_prev_match(pane: &mut Pane, _: &SelectPrevMatch, cx: &mut ViewContext<Pane>) {
1229 if let Some(search_view) = pane
1230 .active_item()
1231 .and_then(|item| item.downcast::<ProjectSearchView>())
1232 {
1233 search_view.update(cx, |view, cx| view.select_match(Direction::Prev, cx));
1234 } else {
1235 cx.propagate_action();
1236 }
1237 }
1238
1239 fn tab(&mut self, _: &editor::Tab, cx: &mut ViewContext<Self>) {
1240 self.cycle_field(Direction::Next, cx);
1241 }
1242
1243 fn tab_previous(&mut self, _: &editor::TabPrev, cx: &mut ViewContext<Self>) {
1244 self.cycle_field(Direction::Prev, cx);
1245 }
1246
1247 fn cycle_field(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
1248 let active_project_search = match &self.active_project_search {
1249 Some(active_project_search) => active_project_search,
1250
1251 None => {
1252 cx.propagate_action();
1253 return;
1254 }
1255 };
1256
1257 active_project_search.update(cx, |project_view, cx| {
1258 let views = &[
1259 &project_view.query_editor,
1260 &project_view.included_files_editor,
1261 &project_view.excluded_files_editor,
1262 ];
1263
1264 let current_index = match views
1265 .iter()
1266 .enumerate()
1267 .find(|(_, view)| view.is_focused(cx))
1268 {
1269 Some((index, _)) => index,
1270
1271 None => {
1272 cx.propagate_action();
1273 return;
1274 }
1275 };
1276
1277 let new_index = match direction {
1278 Direction::Next => (current_index + 1) % views.len(),
1279 Direction::Prev if current_index == 0 => views.len() - 1,
1280 Direction::Prev => (current_index - 1) % views.len(),
1281 };
1282 cx.focus(views[new_index]);
1283 });
1284 }
1285
1286 fn toggle_search_option(&mut self, option: SearchOptions, cx: &mut ViewContext<Self>) -> bool {
1287 if let Some(search_view) = self.active_project_search.as_ref() {
1288 search_view.update(cx, |search_view, cx| {
1289 search_view.toggle_search_option(option);
1290 search_view.search(cx);
1291 });
1292 cx.notify();
1293 true
1294 } else {
1295 false
1296 }
1297 }
1298
1299 fn activate_regex_mode(pane: &mut Pane, _: &ActivateRegexMode, cx: &mut ViewContext<Pane>) {
1300 if let Some(search_view) = pane
1301 .active_item()
1302 .and_then(|item| item.downcast::<ProjectSearchView>())
1303 {
1304 search_view.update(cx, |view, cx| {
1305 view.activate_search_mode(SearchMode::Regex, cx)
1306 });
1307 } else {
1308 cx.propagate_action();
1309 }
1310 }
1311
1312 fn toggle_filters(&mut self, cx: &mut ViewContext<Self>) -> bool {
1313 if let Some(search_view) = self.active_project_search.as_ref() {
1314 search_view.update(cx, |search_view, cx| {
1315 search_view.filters_enabled = !search_view.filters_enabled;
1316 search_view
1317 .included_files_editor
1318 .update(cx, |_, cx| cx.notify());
1319 search_view
1320 .excluded_files_editor
1321 .update(cx, |_, cx| cx.notify());
1322 cx.refresh_windows();
1323 cx.notify();
1324 });
1325 cx.notify();
1326 true
1327 } else {
1328 false
1329 }
1330 }
1331
1332 fn activate_search_mode(&self, mode: SearchMode, cx: &mut ViewContext<Self>) {
1333 // Update Current Mode
1334 if let Some(search_view) = self.active_project_search.as_ref() {
1335 search_view.update(cx, |search_view, cx| {
1336 search_view.activate_search_mode(mode, cx);
1337 });
1338 cx.notify();
1339 }
1340 }
1341
1342 fn is_option_enabled(&self, option: SearchOptions, cx: &AppContext) -> bool {
1343 if let Some(search) = self.active_project_search.as_ref() {
1344 search.read(cx).search_options.contains(option)
1345 } else {
1346 false
1347 }
1348 }
1349
1350 fn next_history_query(&mut self, _: &NextHistoryQuery, cx: &mut ViewContext<Self>) {
1351 if let Some(search_view) = self.active_project_search.as_ref() {
1352 search_view.update(cx, |search_view, cx| {
1353 let new_query = search_view.model.update(cx, |model, _| {
1354 if let Some(new_query) = model.search_history.next().map(str::to_string) {
1355 new_query
1356 } else {
1357 model.search_history.reset_selection();
1358 String::new()
1359 }
1360 });
1361 search_view.set_query(&new_query, cx);
1362 });
1363 }
1364 }
1365
1366 fn previous_history_query(&mut self, _: &PreviousHistoryQuery, cx: &mut ViewContext<Self>) {
1367 if let Some(search_view) = self.active_project_search.as_ref() {
1368 search_view.update(cx, |search_view, cx| {
1369 if search_view.query_editor.read(cx).text(cx).is_empty() {
1370 if let Some(new_query) = search_view
1371 .model
1372 .read(cx)
1373 .search_history
1374 .current()
1375 .map(str::to_string)
1376 {
1377 search_view.set_query(&new_query, cx);
1378 return;
1379 }
1380 }
1381
1382 if let Some(new_query) = search_view.model.update(cx, |model, _| {
1383 model.search_history.previous().map(str::to_string)
1384 }) {
1385 search_view.set_query(&new_query, cx);
1386 }
1387 });
1388 }
1389 }
1390}
1391
1392impl Entity for ProjectSearchBar {
1393 type Event = ();
1394}
1395
1396impl View for ProjectSearchBar {
1397 fn ui_name() -> &'static str {
1398 "ProjectSearchBar"
1399 }
1400
1401 fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
1402 if let Some(_search) = self.active_project_search.as_ref() {
1403 let search = _search.read(cx);
1404 let theme = theme::current(cx).clone();
1405 let query_container_style = if search.panels_with_errors.contains(&InputPanel::Query) {
1406 theme.search.invalid_editor
1407 } else {
1408 theme.search.editor.input.container
1409 };
1410
1411 let search = _search.read(cx);
1412 let filter_button = render_option_button_icon(
1413 search.filters_enabled,
1414 "icons/filter_12.svg",
1415 0,
1416 "Toggle filters",
1417 Box::new(ToggleFilters),
1418 move |_, this, cx| {
1419 this.toggle_filters(cx);
1420 },
1421 cx,
1422 );
1423
1424 let search = _search.read(cx);
1425 let is_semantic_available = SemanticIndex::enabled(cx);
1426 let is_semantic_disabled = search.semantic_state.is_none();
1427 let icon_style = theme.search.editor_icon.clone();
1428 let is_active = search.active_match_index.is_some();
1429
1430 let render_option_button_icon = |path, option, cx: &mut ViewContext<Self>| {
1431 crate::search_bar::render_option_button_icon(
1432 self.is_option_enabled(option, cx),
1433 path,
1434 option.bits as usize,
1435 format!("Toggle {}", option.label()),
1436 option.to_toggle_action(),
1437 move |_, this, cx| {
1438 this.toggle_search_option(option, cx);
1439 },
1440 cx,
1441 )
1442 };
1443 let case_sensitive = is_semantic_disabled.then(|| {
1444 render_option_button_icon(
1445 "icons/case_insensitive_12.svg",
1446 SearchOptions::CASE_SENSITIVE,
1447 cx,
1448 )
1449 });
1450
1451 let whole_word = is_semantic_disabled.then(|| {
1452 render_option_button_icon("icons/word_search_12.svg", SearchOptions::WHOLE_WORD, cx)
1453 });
1454
1455 let search_button_for_mode = |mode, side, cx: &mut ViewContext<ProjectSearchBar>| {
1456 let is_active = if let Some(search) = self.active_project_search.as_ref() {
1457 let search = search.read(cx);
1458 search.current_mode == mode
1459 } else {
1460 false
1461 };
1462 render_search_mode_button(
1463 mode,
1464 side,
1465 is_active,
1466 move |_, this, cx| {
1467 this.activate_search_mode(mode, cx);
1468 },
1469 cx,
1470 )
1471 };
1472
1473 let search = _search.read(cx);
1474
1475 let include_container_style =
1476 if search.panels_with_errors.contains(&InputPanel::Include) {
1477 theme.search.invalid_include_exclude_editor
1478 } else {
1479 theme.search.include_exclude_editor.input.container
1480 };
1481
1482 let exclude_container_style =
1483 if search.panels_with_errors.contains(&InputPanel::Exclude) {
1484 theme.search.invalid_include_exclude_editor
1485 } else {
1486 theme.search.include_exclude_editor.input.container
1487 };
1488
1489 let matches = search.active_match_index.map(|match_ix| {
1490 Label::new(
1491 format!(
1492 "{}/{}",
1493 match_ix + 1,
1494 search.model.read(cx).match_ranges.len()
1495 ),
1496 theme.search.match_index.text.clone(),
1497 )
1498 .contained()
1499 .with_style(theme.search.match_index.container)
1500 .aligned()
1501 });
1502
1503 let query_column = Flex::column()
1504 .with_spacing(theme.search.search_row_spacing)
1505 .with_child(
1506 Flex::row()
1507 .with_child(
1508 Svg::for_style(icon_style.icon)
1509 .contained()
1510 .with_style(icon_style.container),
1511 )
1512 .with_child(ChildView::new(&search.query_editor, cx).flex(1., true))
1513 .with_child(
1514 Flex::row()
1515 .with_child(filter_button)
1516 .with_children(case_sensitive)
1517 .with_children(whole_word)
1518 .flex(1., false)
1519 .constrained()
1520 .contained(),
1521 )
1522 .align_children_center()
1523 .contained()
1524 .with_style(query_container_style)
1525 .constrained()
1526 .with_min_width(theme.search.editor.min_width)
1527 .with_max_width(theme.search.editor.max_width)
1528 .with_height(theme.search.search_bar_row_height)
1529 .flex(1., false),
1530 )
1531 .with_children(search.filters_enabled.then(|| {
1532 Flex::row()
1533 .with_child(
1534 ChildView::new(&search.included_files_editor, cx)
1535 .contained()
1536 .with_style(include_container_style)
1537 .constrained()
1538 .with_height(theme.search.search_bar_row_height)
1539 .flex(1., true),
1540 )
1541 .with_child(
1542 ChildView::new(&search.excluded_files_editor, cx)
1543 .contained()
1544 .with_style(exclude_container_style)
1545 .constrained()
1546 .with_height(theme.search.search_bar_row_height)
1547 .flex(1., true),
1548 )
1549 .constrained()
1550 .with_min_width(theme.search.editor.min_width)
1551 .with_max_width(theme.search.editor.max_width)
1552 .flex(1., false)
1553 }))
1554 .flex(1., false);
1555
1556 let mode_column =
1557 Flex::row()
1558 .with_child(search_button_for_mode(
1559 SearchMode::Text,
1560 Some(Side::Left),
1561 cx,
1562 ))
1563 .with_child(search_button_for_mode(
1564 SearchMode::Regex,
1565 if is_semantic_available {
1566 None
1567 } else {
1568 Some(Side::Right)
1569 },
1570 cx,
1571 ))
1572 .with_children(is_semantic_available.then(|| {
1573 search_button_for_mode(SearchMode::Semantic, Some(Side::Right), cx)
1574 }))
1575 .contained()
1576 .with_style(theme.search.modes_container);
1577
1578 let nav_button_for_direction = |label, direction, cx: &mut ViewContext<Self>| {
1579 render_nav_button(
1580 label,
1581 direction,
1582 is_active,
1583 move |_, this, cx| {
1584 if let Some(search) = this.active_project_search.as_ref() {
1585 search.update(cx, |search, cx| search.select_match(direction, cx));
1586 }
1587 },
1588 cx,
1589 )
1590 };
1591
1592 let nav_column = Flex::row()
1593 .with_child(Flex::row().with_children(matches))
1594 .with_child(nav_button_for_direction("<", Direction::Prev, cx))
1595 .with_child(nav_button_for_direction(">", Direction::Next, cx))
1596 .constrained()
1597 .with_height(theme.search.search_bar_row_height)
1598 .flex_float();
1599
1600 Flex::row()
1601 .with_child(query_column)
1602 .with_child(mode_column)
1603 .with_child(nav_column)
1604 .contained()
1605 .with_style(theme.search.container)
1606 .into_any_named("project search")
1607 } else {
1608 Empty::new().into_any()
1609 }
1610 }
1611}
1612
1613impl ToolbarItemView for ProjectSearchBar {
1614 fn set_active_pane_item(
1615 &mut self,
1616 active_pane_item: Option<&dyn ItemHandle>,
1617 cx: &mut ViewContext<Self>,
1618 ) -> ToolbarItemLocation {
1619 cx.notify();
1620 self.subscription = None;
1621 self.active_project_search = None;
1622 if let Some(search) = active_pane_item.and_then(|i| i.downcast::<ProjectSearchView>()) {
1623 self.subscription = Some(cx.observe(&search, |_, _, cx| cx.notify()));
1624 self.active_project_search = Some(search);
1625 ToolbarItemLocation::PrimaryLeft {
1626 flex: Some((1., true)),
1627 }
1628 } else {
1629 ToolbarItemLocation::Hidden
1630 }
1631 }
1632
1633 fn row_count(&self, cx: &ViewContext<Self>) -> usize {
1634 if let Some(search) = self.active_project_search.as_ref() {
1635 if search.read(cx).filters_enabled {
1636 return 2;
1637 }
1638 }
1639 1
1640 }
1641}
1642
1643#[cfg(test)]
1644pub mod tests {
1645 use super::*;
1646 use editor::DisplayPoint;
1647 use gpui::{color::Color, executor::Deterministic, TestAppContext};
1648 use project::FakeFs;
1649 use semantic_index::semantic_index_settings::SemanticIndexSettings;
1650 use serde_json::json;
1651 use settings::SettingsStore;
1652 use std::sync::Arc;
1653 use theme::ThemeSettings;
1654
1655 #[gpui::test]
1656 async fn test_project_search(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
1657 init_test(cx);
1658
1659 let fs = FakeFs::new(cx.background());
1660 fs.insert_tree(
1661 "/dir",
1662 json!({
1663 "one.rs": "const ONE: usize = 1;",
1664 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
1665 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
1666 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
1667 }),
1668 )
1669 .await;
1670 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
1671 let search = cx.add_model(|cx| ProjectSearch::new(project, cx));
1672 let search_view = cx
1673 .add_window(|cx| ProjectSearchView::new(search.clone(), cx))
1674 .root(cx);
1675
1676 search_view.update(cx, |search_view, cx| {
1677 search_view
1678 .query_editor
1679 .update(cx, |query_editor, cx| query_editor.set_text("TWO", cx));
1680 search_view.search(cx);
1681 });
1682 deterministic.run_until_parked();
1683 search_view.update(cx, |search_view, cx| {
1684 assert_eq!(
1685 search_view
1686 .results_editor
1687 .update(cx, |editor, cx| editor.display_text(cx)),
1688 "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;"
1689 );
1690 assert_eq!(
1691 search_view
1692 .results_editor
1693 .update(cx, |editor, cx| editor.all_background_highlights(cx)),
1694 &[
1695 (
1696 DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35),
1697 Color::red()
1698 ),
1699 (
1700 DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40),
1701 Color::red()
1702 ),
1703 (
1704 DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9),
1705 Color::red()
1706 )
1707 ]
1708 );
1709 assert_eq!(search_view.active_match_index, Some(0));
1710 assert_eq!(
1711 search_view
1712 .results_editor
1713 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1714 [DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35)]
1715 );
1716
1717 search_view.select_match(Direction::Next, cx);
1718 });
1719
1720 search_view.update(cx, |search_view, cx| {
1721 assert_eq!(search_view.active_match_index, Some(1));
1722 assert_eq!(
1723 search_view
1724 .results_editor
1725 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1726 [DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40)]
1727 );
1728 search_view.select_match(Direction::Next, cx);
1729 });
1730
1731 search_view.update(cx, |search_view, cx| {
1732 assert_eq!(search_view.active_match_index, Some(2));
1733 assert_eq!(
1734 search_view
1735 .results_editor
1736 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1737 [DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9)]
1738 );
1739 search_view.select_match(Direction::Next, cx);
1740 });
1741
1742 search_view.update(cx, |search_view, cx| {
1743 assert_eq!(search_view.active_match_index, Some(0));
1744 assert_eq!(
1745 search_view
1746 .results_editor
1747 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1748 [DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35)]
1749 );
1750 search_view.select_match(Direction::Prev, cx);
1751 });
1752
1753 search_view.update(cx, |search_view, cx| {
1754 assert_eq!(search_view.active_match_index, Some(2));
1755 assert_eq!(
1756 search_view
1757 .results_editor
1758 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1759 [DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9)]
1760 );
1761 search_view.select_match(Direction::Prev, cx);
1762 });
1763
1764 search_view.update(cx, |search_view, cx| {
1765 assert_eq!(search_view.active_match_index, Some(1));
1766 assert_eq!(
1767 search_view
1768 .results_editor
1769 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1770 [DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40)]
1771 );
1772 });
1773 }
1774
1775 #[gpui::test]
1776 async fn test_project_search_focus(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
1777 init_test(cx);
1778
1779 let fs = FakeFs::new(cx.background());
1780 fs.insert_tree(
1781 "/dir",
1782 json!({
1783 "one.rs": "const ONE: usize = 1;",
1784 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
1785 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
1786 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
1787 }),
1788 )
1789 .await;
1790 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
1791 let window = cx.add_window(|cx| Workspace::test_new(project, cx));
1792 let workspace = window.root(cx);
1793
1794 let active_item = cx.read(|cx| {
1795 workspace
1796 .read(cx)
1797 .active_pane()
1798 .read(cx)
1799 .active_item()
1800 .and_then(|item| item.downcast::<ProjectSearchView>())
1801 });
1802 assert!(
1803 active_item.is_none(),
1804 "Expected no search panel to be active, but got: {active_item:?}"
1805 );
1806
1807 workspace.update(cx, |workspace, cx| {
1808 ProjectSearchView::deploy(workspace, &workspace::NewSearch, cx)
1809 });
1810
1811 let Some(search_view) = cx.read(|cx| {
1812 workspace
1813 .read(cx)
1814 .active_pane()
1815 .read(cx)
1816 .active_item()
1817 .and_then(|item| item.downcast::<ProjectSearchView>())
1818 }) else {
1819 panic!("Search view expected to appear after new search event trigger")
1820 };
1821 let search_view_id = search_view.id();
1822
1823 cx.spawn(|mut cx| async move {
1824 window.dispatch_action(search_view_id, &ToggleFocus, &mut cx);
1825 })
1826 .detach();
1827 deterministic.run_until_parked();
1828 search_view.update(cx, |search_view, cx| {
1829 assert!(
1830 search_view.query_editor.is_focused(cx),
1831 "Empty search view should be focused after the toggle focus event: no results panel to focus on",
1832 );
1833 });
1834
1835 search_view.update(cx, |search_view, cx| {
1836 let query_editor = &search_view.query_editor;
1837 assert!(
1838 query_editor.is_focused(cx),
1839 "Search view should be focused after the new search view is activated",
1840 );
1841 let query_text = query_editor.read(cx).text(cx);
1842 assert!(
1843 query_text.is_empty(),
1844 "New search query should be empty but got '{query_text}'",
1845 );
1846 let results_text = search_view
1847 .results_editor
1848 .update(cx, |editor, cx| editor.display_text(cx));
1849 assert!(
1850 results_text.is_empty(),
1851 "Empty search view should have no results but got '{results_text}'"
1852 );
1853 });
1854
1855 search_view.update(cx, |search_view, cx| {
1856 search_view.query_editor.update(cx, |query_editor, cx| {
1857 query_editor.set_text("sOMETHINGtHATsURELYdOESnOTeXIST", cx)
1858 });
1859 search_view.search(cx);
1860 });
1861 deterministic.run_until_parked();
1862 search_view.update(cx, |search_view, cx| {
1863 let results_text = search_view
1864 .results_editor
1865 .update(cx, |editor, cx| editor.display_text(cx));
1866 assert!(
1867 results_text.is_empty(),
1868 "Search view for mismatching query should have no results but got '{results_text}'"
1869 );
1870 assert!(
1871 search_view.query_editor.is_focused(cx),
1872 "Search view should be focused after mismatching query had been used in search",
1873 );
1874 });
1875 cx.spawn(
1876 |mut cx| async move { window.dispatch_action(search_view_id, &ToggleFocus, &mut cx) },
1877 )
1878 .detach();
1879 deterministic.run_until_parked();
1880 search_view.update(cx, |search_view, cx| {
1881 assert!(
1882 search_view.query_editor.is_focused(cx),
1883 "Search view with mismatching query should be focused after the toggle focus event: still no results panel to focus on",
1884 );
1885 });
1886
1887 search_view.update(cx, |search_view, cx| {
1888 search_view
1889 .query_editor
1890 .update(cx, |query_editor, cx| query_editor.set_text("TWO", cx));
1891 search_view.search(cx);
1892 });
1893 deterministic.run_until_parked();
1894 search_view.update(cx, |search_view, cx| {
1895 assert_eq!(
1896 search_view
1897 .results_editor
1898 .update(cx, |editor, cx| editor.display_text(cx)),
1899 "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
1900 "Search view results should match the query"
1901 );
1902 assert!(
1903 search_view.results_editor.is_focused(cx),
1904 "Search view with mismatching query should be focused after search results are available",
1905 );
1906 });
1907 cx.spawn(|mut cx| async move {
1908 window.dispatch_action(search_view_id, &ToggleFocus, &mut cx);
1909 })
1910 .detach();
1911 deterministic.run_until_parked();
1912 search_view.update(cx, |search_view, cx| {
1913 assert!(
1914 search_view.results_editor.is_focused(cx),
1915 "Search view with matching query should still have its results editor focused after the toggle focus event",
1916 );
1917 });
1918
1919 workspace.update(cx, |workspace, cx| {
1920 ProjectSearchView::deploy(workspace, &workspace::NewSearch, cx)
1921 });
1922 search_view.update(cx, |search_view, cx| {
1923 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");
1924 assert_eq!(
1925 search_view
1926 .results_editor
1927 .update(cx, |editor, cx| editor.display_text(cx)),
1928 "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
1929 "Results should be unchanged after search view 2nd open in a row"
1930 );
1931 assert!(
1932 search_view.query_editor.is_focused(cx),
1933 "Focus should be moved into query editor again after search view 2nd open in a row"
1934 );
1935 });
1936
1937 cx.spawn(|mut cx| async move {
1938 window.dispatch_action(search_view_id, &ToggleFocus, &mut cx);
1939 })
1940 .detach();
1941 deterministic.run_until_parked();
1942 search_view.update(cx, |search_view, cx| {
1943 assert!(
1944 search_view.results_editor.is_focused(cx),
1945 "Search view with matching query should switch focus to the results editor after the toggle focus event",
1946 );
1947 });
1948 }
1949
1950 #[gpui::test]
1951 async fn test_new_project_search_in_directory(
1952 deterministic: Arc<Deterministic>,
1953 cx: &mut TestAppContext,
1954 ) {
1955 init_test(cx);
1956
1957 let fs = FakeFs::new(cx.background());
1958 fs.insert_tree(
1959 "/dir",
1960 json!({
1961 "a": {
1962 "one.rs": "const ONE: usize = 1;",
1963 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
1964 },
1965 "b": {
1966 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
1967 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
1968 },
1969 }),
1970 )
1971 .await;
1972 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
1973 let worktree_id = project.read_with(cx, |project, cx| {
1974 project.worktrees(cx).next().unwrap().read(cx).id()
1975 });
1976 let workspace = cx
1977 .add_window(|cx| Workspace::test_new(project, cx))
1978 .root(cx);
1979
1980 let active_item = cx.read(|cx| {
1981 workspace
1982 .read(cx)
1983 .active_pane()
1984 .read(cx)
1985 .active_item()
1986 .and_then(|item| item.downcast::<ProjectSearchView>())
1987 });
1988 assert!(
1989 active_item.is_none(),
1990 "Expected no search panel to be active, but got: {active_item:?}"
1991 );
1992
1993 let one_file_entry = cx.update(|cx| {
1994 workspace
1995 .read(cx)
1996 .project()
1997 .read(cx)
1998 .entry_for_path(&(worktree_id, "a/one.rs").into(), cx)
1999 .expect("no entry for /a/one.rs file")
2000 });
2001 assert!(one_file_entry.is_file());
2002 workspace.update(cx, |workspace, cx| {
2003 ProjectSearchView::new_search_in_directory(workspace, &one_file_entry, cx)
2004 });
2005 let active_search_entry = cx.read(|cx| {
2006 workspace
2007 .read(cx)
2008 .active_pane()
2009 .read(cx)
2010 .active_item()
2011 .and_then(|item| item.downcast::<ProjectSearchView>())
2012 });
2013 assert!(
2014 active_search_entry.is_none(),
2015 "Expected no search panel to be active for file entry"
2016 );
2017
2018 let a_dir_entry = cx.update(|cx| {
2019 workspace
2020 .read(cx)
2021 .project()
2022 .read(cx)
2023 .entry_for_path(&(worktree_id, "a").into(), cx)
2024 .expect("no entry for /a/ directory")
2025 });
2026 assert!(a_dir_entry.is_dir());
2027 workspace.update(cx, |workspace, cx| {
2028 ProjectSearchView::new_search_in_directory(workspace, &a_dir_entry, cx)
2029 });
2030
2031 let Some(search_view) = cx.read(|cx| {
2032 workspace
2033 .read(cx)
2034 .active_pane()
2035 .read(cx)
2036 .active_item()
2037 .and_then(|item| item.downcast::<ProjectSearchView>())
2038 }) else {
2039 panic!("Search view expected to appear after new search in directory event trigger")
2040 };
2041 deterministic.run_until_parked();
2042 search_view.update(cx, |search_view, cx| {
2043 assert!(
2044 search_view.query_editor.is_focused(cx),
2045 "On new search in directory, focus should be moved into query editor"
2046 );
2047 search_view.excluded_files_editor.update(cx, |editor, cx| {
2048 assert!(
2049 editor.display_text(cx).is_empty(),
2050 "New search in directory should not have any excluded files"
2051 );
2052 });
2053 search_view.included_files_editor.update(cx, |editor, cx| {
2054 assert_eq!(
2055 editor.display_text(cx),
2056 a_dir_entry.path.to_str().unwrap(),
2057 "New search in directory should have included dir entry path"
2058 );
2059 });
2060 });
2061
2062 search_view.update(cx, |search_view, cx| {
2063 search_view
2064 .query_editor
2065 .update(cx, |query_editor, cx| query_editor.set_text("const", cx));
2066 search_view.search(cx);
2067 });
2068 deterministic.run_until_parked();
2069 search_view.update(cx, |search_view, cx| {
2070 assert_eq!(
2071 search_view
2072 .results_editor
2073 .update(cx, |editor, cx| editor.display_text(cx)),
2074 "\n\nconst ONE: usize = 1;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
2075 "New search in directory should have a filter that matches a certain directory"
2076 );
2077 });
2078 }
2079
2080 #[gpui::test]
2081 async fn test_search_query_history(cx: &mut TestAppContext) {
2082 init_test(cx);
2083
2084 let fs = FakeFs::new(cx.background());
2085 fs.insert_tree(
2086 "/dir",
2087 json!({
2088 "one.rs": "const ONE: usize = 1;",
2089 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2090 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2091 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2092 }),
2093 )
2094 .await;
2095 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
2096 let window = cx.add_window(|cx| Workspace::test_new(project, cx));
2097 let workspace = window.root(cx);
2098 workspace.update(cx, |workspace, cx| {
2099 ProjectSearchView::deploy(workspace, &workspace::NewSearch, cx)
2100 });
2101
2102 let search_view = cx.read(|cx| {
2103 workspace
2104 .read(cx)
2105 .active_pane()
2106 .read(cx)
2107 .active_item()
2108 .and_then(|item| item.downcast::<ProjectSearchView>())
2109 .expect("Search view expected to appear after new search event trigger")
2110 });
2111
2112 let search_bar = window.add_view(cx, |cx| {
2113 let mut search_bar = ProjectSearchBar::new();
2114 search_bar.set_active_pane_item(Some(&search_view), cx);
2115 // search_bar.show(cx);
2116 search_bar
2117 });
2118
2119 // Add 3 search items into the history + another unsubmitted one.
2120 search_view.update(cx, |search_view, cx| {
2121 search_view.search_options = SearchOptions::CASE_SENSITIVE;
2122 search_view
2123 .query_editor
2124 .update(cx, |query_editor, cx| query_editor.set_text("ONE", cx));
2125 search_view.search(cx);
2126 });
2127 cx.foreground().run_until_parked();
2128 search_view.update(cx, |search_view, cx| {
2129 search_view
2130 .query_editor
2131 .update(cx, |query_editor, cx| query_editor.set_text("TWO", cx));
2132 search_view.search(cx);
2133 });
2134 cx.foreground().run_until_parked();
2135 search_view.update(cx, |search_view, cx| {
2136 search_view
2137 .query_editor
2138 .update(cx, |query_editor, cx| query_editor.set_text("THREE", cx));
2139 search_view.search(cx);
2140 });
2141 cx.foreground().run_until_parked();
2142 search_view.update(cx, |search_view, cx| {
2143 search_view.query_editor.update(cx, |query_editor, cx| {
2144 query_editor.set_text("JUST_TEXT_INPUT", cx)
2145 });
2146 });
2147 cx.foreground().run_until_parked();
2148
2149 // Ensure that the latest input with search settings is active.
2150 search_view.update(cx, |search_view, cx| {
2151 assert_eq!(
2152 search_view.query_editor.read(cx).text(cx),
2153 "JUST_TEXT_INPUT"
2154 );
2155 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2156 });
2157
2158 // Next history query after the latest should set the query to the empty string.
2159 search_bar.update(cx, |search_bar, cx| {
2160 search_bar.next_history_query(&NextHistoryQuery, cx);
2161 });
2162 search_view.update(cx, |search_view, cx| {
2163 assert_eq!(search_view.query_editor.read(cx).text(cx), "");
2164 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2165 });
2166 search_bar.update(cx, |search_bar, cx| {
2167 search_bar.next_history_query(&NextHistoryQuery, cx);
2168 });
2169 search_view.update(cx, |search_view, cx| {
2170 assert_eq!(search_view.query_editor.read(cx).text(cx), "");
2171 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2172 });
2173
2174 // First previous query for empty current query should set the query to the latest submitted one.
2175 search_bar.update(cx, |search_bar, cx| {
2176 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2177 });
2178 search_view.update(cx, |search_view, cx| {
2179 assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
2180 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2181 });
2182
2183 // Further previous items should go over the history in reverse order.
2184 search_bar.update(cx, |search_bar, cx| {
2185 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2186 });
2187 search_view.update(cx, |search_view, cx| {
2188 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
2189 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2190 });
2191
2192 // Previous items should never go behind the first history item.
2193 search_bar.update(cx, |search_bar, cx| {
2194 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2195 });
2196 search_view.update(cx, |search_view, cx| {
2197 assert_eq!(search_view.query_editor.read(cx).text(cx), "ONE");
2198 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2199 });
2200 search_bar.update(cx, |search_bar, cx| {
2201 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2202 });
2203 search_view.update(cx, |search_view, cx| {
2204 assert_eq!(search_view.query_editor.read(cx).text(cx), "ONE");
2205 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2206 });
2207
2208 // Next items should go over the history in the original order.
2209 search_bar.update(cx, |search_bar, cx| {
2210 search_bar.next_history_query(&NextHistoryQuery, cx);
2211 });
2212 search_view.update(cx, |search_view, cx| {
2213 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
2214 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2215 });
2216
2217 search_view.update(cx, |search_view, cx| {
2218 search_view
2219 .query_editor
2220 .update(cx, |query_editor, cx| query_editor.set_text("TWO_NEW", cx));
2221 search_view.search(cx);
2222 });
2223 cx.foreground().run_until_parked();
2224 search_view.update(cx, |search_view, cx| {
2225 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO_NEW");
2226 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2227 });
2228
2229 // New search input should add another entry to history and move the selection to the end of the history.
2230 search_bar.update(cx, |search_bar, cx| {
2231 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2232 });
2233 search_view.update(cx, |search_view, cx| {
2234 assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
2235 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2236 });
2237 search_bar.update(cx, |search_bar, cx| {
2238 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2239 });
2240 search_view.update(cx, |search_view, cx| {
2241 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
2242 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2243 });
2244 search_bar.update(cx, |search_bar, cx| {
2245 search_bar.next_history_query(&NextHistoryQuery, cx);
2246 });
2247 search_view.update(cx, |search_view, cx| {
2248 assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
2249 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2250 });
2251 search_bar.update(cx, |search_bar, cx| {
2252 search_bar.next_history_query(&NextHistoryQuery, cx);
2253 });
2254 search_view.update(cx, |search_view, cx| {
2255 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO_NEW");
2256 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2257 });
2258 search_bar.update(cx, |search_bar, cx| {
2259 search_bar.next_history_query(&NextHistoryQuery, cx);
2260 });
2261 search_view.update(cx, |search_view, cx| {
2262 assert_eq!(search_view.query_editor.read(cx).text(cx), "");
2263 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2264 });
2265 }
2266
2267 pub fn init_test(cx: &mut TestAppContext) {
2268 cx.foreground().forbid_parking();
2269 let fonts = cx.font_cache();
2270 let mut theme = gpui::fonts::with_font_cache(fonts.clone(), theme::Theme::default);
2271 theme.search.match_background = Color::red();
2272
2273 cx.update(|cx| {
2274 cx.set_global(SettingsStore::test(cx));
2275 cx.set_global(ActiveSearches::default());
2276 settings::register::<SemanticIndexSettings>(cx);
2277
2278 theme::init((), cx);
2279 cx.update_global::<SettingsStore, _, _>(|store, _| {
2280 let mut settings = store.get::<ThemeSettings>(None).clone();
2281 settings.theme = Arc::new(theme);
2282 store.override_global(settings)
2283 });
2284
2285 language::init(cx);
2286 client::init_settings(cx);
2287 editor::init(cx);
2288 workspace::init_settings(cx);
2289 Project::init_settings(cx);
2290 super::init(cx);
2291 });
2292 }
2293}