1use crate::{
2 history::SearchHistory,
3 mode::SearchMode,
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 let search = _search.read(cx);
1424 let is_semantic_disabled = search.semantic_state.is_none();
1425 let render_option_button_icon = |path, option, cx: &mut ViewContext<Self>| {
1426 crate::search_bar::render_option_button_icon(
1427 self.is_option_enabled(option, cx),
1428 path,
1429 option.bits as usize,
1430 format!("Toggle {}", option.label()),
1431 option.to_toggle_action(),
1432 move |_, this, cx| {
1433 this.toggle_search_option(option, cx);
1434 },
1435 cx,
1436 )
1437 };
1438 let case_sensitive = is_semantic_disabled.then(|| {
1439 render_option_button_icon(
1440 "icons/case_insensitive_12.svg",
1441 SearchOptions::CASE_SENSITIVE,
1442 cx,
1443 )
1444 });
1445
1446 let whole_word = is_semantic_disabled.then(|| {
1447 render_option_button_icon("icons/word_search_12.svg", SearchOptions::WHOLE_WORD, cx)
1448 });
1449
1450 let search = _search.read(cx);
1451 let icon_style = theme.search.editor_icon.clone();
1452
1453 // Editor Functionality
1454 let query = Flex::row()
1455 .with_child(
1456 Svg::for_style(icon_style.icon)
1457 .contained()
1458 .with_style(icon_style.container),
1459 )
1460 .with_child(ChildView::new(&search.query_editor, cx).flex(1., true))
1461 .with_child(
1462 Flex::row()
1463 .with_child(filter_button)
1464 .with_children(case_sensitive)
1465 .with_children(whole_word)
1466 .flex(1., false)
1467 .constrained()
1468 .contained(),
1469 )
1470 .align_children_center()
1471 .flex(1., true);
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 included_files_view = ChildView::new(&search.included_files_editor, cx)
1490 .contained()
1491 .flex(1., true);
1492 let excluded_files_view = ChildView::new(&search.excluded_files_editor, cx)
1493 .contained()
1494 .flex(1., true);
1495 let filters = search.filters_enabled.then(|| {
1496 Flex::row()
1497 .with_child(
1498 included_files_view
1499 .contained()
1500 .with_style(include_container_style)
1501 .constrained()
1502 .with_height(theme.search.search_bar_row_height)
1503 .with_min_width(theme.search.include_exclude_editor.min_width)
1504 .with_max_width(theme.search.include_exclude_editor.max_width),
1505 )
1506 .with_child(
1507 excluded_files_view
1508 .contained()
1509 .with_style(exclude_container_style)
1510 .constrained()
1511 .with_height(theme.search.search_bar_row_height)
1512 .with_min_width(theme.search.include_exclude_editor.min_width)
1513 .with_max_width(theme.search.include_exclude_editor.max_width),
1514 )
1515 .contained()
1516 .with_padding_top(theme.workspace.toolbar.container.padding.bottom)
1517 });
1518
1519 let editor_column = Flex::column()
1520 .with_child(
1521 query
1522 .contained()
1523 .with_style(query_container_style)
1524 .constrained()
1525 .with_min_width(theme.search.editor.min_width)
1526 .with_max_width(theme.search.editor.max_width)
1527 .with_height(theme.search.search_bar_row_height)
1528 .flex(1., false),
1529 )
1530 .with_children(filters)
1531 .flex(1., false);
1532
1533 let matches = search.active_match_index.map(|match_ix| {
1534 Label::new(
1535 format!(
1536 "{}/{}",
1537 match_ix + 1,
1538 search.model.read(cx).match_ranges.len()
1539 ),
1540 theme.search.match_index.text.clone(),
1541 )
1542 .contained()
1543 .with_style(theme.search.match_index.container)
1544 .aligned()
1545 });
1546
1547 let search_button_for_mode = |mode, cx: &mut ViewContext<ProjectSearchBar>| {
1548 let is_active = if let Some(search) = self.active_project_search.as_ref() {
1549 let search = search.read(cx);
1550 search.current_mode == mode
1551 } else {
1552 false
1553 };
1554 render_search_mode_button(
1555 mode,
1556 is_active,
1557 move |_, this, cx| {
1558 this.activate_search_mode(mode, cx);
1559 },
1560 cx,
1561 )
1562 };
1563 let is_active = search.active_match_index.is_some();
1564 let semantic_index = SemanticIndex::enabled(cx)
1565 .then(|| search_button_for_mode(SearchMode::Semantic, cx));
1566 let nav_button_for_direction = |label, direction, cx: &mut ViewContext<Self>| {
1567 render_nav_button(
1568 label,
1569 direction,
1570 is_active,
1571 move |_, this, cx| {
1572 if let Some(search) = this.active_project_search.as_ref() {
1573 search.update(cx, |search, cx| search.select_match(direction, cx));
1574 }
1575 },
1576 cx,
1577 )
1578 };
1579
1580 let nav_column = Flex::row()
1581 .with_child(nav_button_for_direction("<", Direction::Prev, cx))
1582 .with_child(nav_button_for_direction(">", Direction::Next, cx))
1583 .with_child(Flex::row().with_children(matches))
1584 .constrained()
1585 .with_height(theme.search.search_bar_row_height);
1586
1587 let mode_column = Flex::row()
1588 .with_child(
1589 Flex::row()
1590 .with_child(search_button_for_mode(SearchMode::Text, cx))
1591 .with_children(semantic_index)
1592 .with_child(search_button_for_mode(SearchMode::Regex, cx))
1593 .contained()
1594 .with_style(theme.search.modes_container),
1595 )
1596 .with_child(super::search_bar::render_close_button(
1597 "Dismiss Project Search",
1598 &theme.search,
1599 cx,
1600 |_, this, cx| {
1601 if let Some(search) = this.active_project_search.as_mut() {
1602 search.update(cx, |_, cx| cx.emit(ViewEvent::Dismiss))
1603 }
1604 },
1605 None,
1606 ))
1607 .constrained()
1608 .with_height(theme.search.search_bar_row_height)
1609 .aligned()
1610 .right()
1611 .top()
1612 .flex_float();
1613
1614 Flex::row()
1615 .with_child(editor_column)
1616 .with_child(nav_column)
1617 .with_child(mode_column)
1618 .contained()
1619 .with_style(theme.search.container)
1620 .into_any_named("project search")
1621 } else {
1622 Empty::new().into_any()
1623 }
1624 }
1625}
1626
1627impl ToolbarItemView for ProjectSearchBar {
1628 fn set_active_pane_item(
1629 &mut self,
1630 active_pane_item: Option<&dyn ItemHandle>,
1631 cx: &mut ViewContext<Self>,
1632 ) -> ToolbarItemLocation {
1633 cx.notify();
1634 self.subscription = None;
1635 self.active_project_search = None;
1636 if let Some(search) = active_pane_item.and_then(|i| i.downcast::<ProjectSearchView>()) {
1637 self.subscription = Some(cx.observe(&search, |_, _, cx| cx.notify()));
1638 self.active_project_search = Some(search);
1639 ToolbarItemLocation::PrimaryLeft {
1640 flex: Some((1., false)),
1641 }
1642 } else {
1643 ToolbarItemLocation::Hidden
1644 }
1645 }
1646
1647 fn row_count(&self, cx: &ViewContext<Self>) -> usize {
1648 self.active_project_search
1649 .as_ref()
1650 .map(|search| {
1651 let offset = search.read(cx).filters_enabled as usize;
1652 2 + offset
1653 })
1654 .unwrap_or_else(|| 2)
1655 }
1656}
1657
1658#[cfg(test)]
1659pub mod tests {
1660 use super::*;
1661 use editor::DisplayPoint;
1662 use gpui::{color::Color, executor::Deterministic, TestAppContext};
1663 use project::FakeFs;
1664 use semantic_index::semantic_index_settings::SemanticIndexSettings;
1665 use serde_json::json;
1666 use settings::SettingsStore;
1667 use std::sync::Arc;
1668 use theme::ThemeSettings;
1669
1670 #[gpui::test]
1671 async fn test_project_search(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
1672 init_test(cx);
1673
1674 let fs = FakeFs::new(cx.background());
1675 fs.insert_tree(
1676 "/dir",
1677 json!({
1678 "one.rs": "const ONE: usize = 1;",
1679 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
1680 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
1681 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
1682 }),
1683 )
1684 .await;
1685 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
1686 let search = cx.add_model(|cx| ProjectSearch::new(project, cx));
1687 let search_view = cx
1688 .add_window(|cx| ProjectSearchView::new(search.clone(), cx))
1689 .root(cx);
1690
1691 search_view.update(cx, |search_view, cx| {
1692 search_view
1693 .query_editor
1694 .update(cx, |query_editor, cx| query_editor.set_text("TWO", cx));
1695 search_view.search(cx);
1696 });
1697 deterministic.run_until_parked();
1698 search_view.update(cx, |search_view, cx| {
1699 assert_eq!(
1700 search_view
1701 .results_editor
1702 .update(cx, |editor, cx| editor.display_text(cx)),
1703 "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;"
1704 );
1705 assert_eq!(
1706 search_view
1707 .results_editor
1708 .update(cx, |editor, cx| editor.all_background_highlights(cx)),
1709 &[
1710 (
1711 DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35),
1712 Color::red()
1713 ),
1714 (
1715 DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40),
1716 Color::red()
1717 ),
1718 (
1719 DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9),
1720 Color::red()
1721 )
1722 ]
1723 );
1724 assert_eq!(search_view.active_match_index, Some(0));
1725 assert_eq!(
1726 search_view
1727 .results_editor
1728 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1729 [DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35)]
1730 );
1731
1732 search_view.select_match(Direction::Next, cx);
1733 });
1734
1735 search_view.update(cx, |search_view, cx| {
1736 assert_eq!(search_view.active_match_index, Some(1));
1737 assert_eq!(
1738 search_view
1739 .results_editor
1740 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1741 [DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40)]
1742 );
1743 search_view.select_match(Direction::Next, cx);
1744 });
1745
1746 search_view.update(cx, |search_view, cx| {
1747 assert_eq!(search_view.active_match_index, Some(2));
1748 assert_eq!(
1749 search_view
1750 .results_editor
1751 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1752 [DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9)]
1753 );
1754 search_view.select_match(Direction::Next, cx);
1755 });
1756
1757 search_view.update(cx, |search_view, cx| {
1758 assert_eq!(search_view.active_match_index, Some(0));
1759 assert_eq!(
1760 search_view
1761 .results_editor
1762 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1763 [DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35)]
1764 );
1765 search_view.select_match(Direction::Prev, cx);
1766 });
1767
1768 search_view.update(cx, |search_view, cx| {
1769 assert_eq!(search_view.active_match_index, Some(2));
1770 assert_eq!(
1771 search_view
1772 .results_editor
1773 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1774 [DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9)]
1775 );
1776 search_view.select_match(Direction::Prev, cx);
1777 });
1778
1779 search_view.update(cx, |search_view, cx| {
1780 assert_eq!(search_view.active_match_index, Some(1));
1781 assert_eq!(
1782 search_view
1783 .results_editor
1784 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1785 [DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40)]
1786 );
1787 });
1788 }
1789
1790 #[gpui::test]
1791 async fn test_project_search_focus(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
1792 init_test(cx);
1793
1794 let fs = FakeFs::new(cx.background());
1795 fs.insert_tree(
1796 "/dir",
1797 json!({
1798 "one.rs": "const ONE: usize = 1;",
1799 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
1800 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
1801 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
1802 }),
1803 )
1804 .await;
1805 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
1806 let window = cx.add_window(|cx| Workspace::test_new(project, cx));
1807 let workspace = window.root(cx);
1808
1809 let active_item = cx.read(|cx| {
1810 workspace
1811 .read(cx)
1812 .active_pane()
1813 .read(cx)
1814 .active_item()
1815 .and_then(|item| item.downcast::<ProjectSearchView>())
1816 });
1817 assert!(
1818 active_item.is_none(),
1819 "Expected no search panel to be active, but got: {active_item:?}"
1820 );
1821
1822 workspace.update(cx, |workspace, cx| {
1823 ProjectSearchView::deploy(workspace, &workspace::NewSearch, cx)
1824 });
1825
1826 let Some(search_view) = cx.read(|cx| {
1827 workspace
1828 .read(cx)
1829 .active_pane()
1830 .read(cx)
1831 .active_item()
1832 .and_then(|item| item.downcast::<ProjectSearchView>())
1833 }) else {
1834 panic!("Search view expected to appear after new search event trigger")
1835 };
1836 let search_view_id = search_view.id();
1837
1838 cx.spawn(|mut cx| async move {
1839 window.dispatch_action(search_view_id, &ToggleFocus, &mut cx);
1840 })
1841 .detach();
1842 deterministic.run_until_parked();
1843 search_view.update(cx, |search_view, cx| {
1844 assert!(
1845 search_view.query_editor.is_focused(cx),
1846 "Empty search view should be focused after the toggle focus event: no results panel to focus on",
1847 );
1848 });
1849
1850 search_view.update(cx, |search_view, cx| {
1851 let query_editor = &search_view.query_editor;
1852 assert!(
1853 query_editor.is_focused(cx),
1854 "Search view should be focused after the new search view is activated",
1855 );
1856 let query_text = query_editor.read(cx).text(cx);
1857 assert!(
1858 query_text.is_empty(),
1859 "New search query should be empty but got '{query_text}'",
1860 );
1861 let results_text = search_view
1862 .results_editor
1863 .update(cx, |editor, cx| editor.display_text(cx));
1864 assert!(
1865 results_text.is_empty(),
1866 "Empty search view should have no results but got '{results_text}'"
1867 );
1868 });
1869
1870 search_view.update(cx, |search_view, cx| {
1871 search_view.query_editor.update(cx, |query_editor, cx| {
1872 query_editor.set_text("sOMETHINGtHATsURELYdOESnOTeXIST", cx)
1873 });
1874 search_view.search(cx);
1875 });
1876 deterministic.run_until_parked();
1877 search_view.update(cx, |search_view, cx| {
1878 let results_text = search_view
1879 .results_editor
1880 .update(cx, |editor, cx| editor.display_text(cx));
1881 assert!(
1882 results_text.is_empty(),
1883 "Search view for mismatching query should have no results but got '{results_text}'"
1884 );
1885 assert!(
1886 search_view.query_editor.is_focused(cx),
1887 "Search view should be focused after mismatching query had been used in search",
1888 );
1889 });
1890 cx.spawn(
1891 |mut cx| async move { window.dispatch_action(search_view_id, &ToggleFocus, &mut cx) },
1892 )
1893 .detach();
1894 deterministic.run_until_parked();
1895 search_view.update(cx, |search_view, cx| {
1896 assert!(
1897 search_view.query_editor.is_focused(cx),
1898 "Search view with mismatching query should be focused after the toggle focus event: still no results panel to focus on",
1899 );
1900 });
1901
1902 search_view.update(cx, |search_view, cx| {
1903 search_view
1904 .query_editor
1905 .update(cx, |query_editor, cx| query_editor.set_text("TWO", cx));
1906 search_view.search(cx);
1907 });
1908 deterministic.run_until_parked();
1909 search_view.update(cx, |search_view, cx| {
1910 assert_eq!(
1911 search_view
1912 .results_editor
1913 .update(cx, |editor, cx| editor.display_text(cx)),
1914 "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
1915 "Search view results should match the query"
1916 );
1917 assert!(
1918 search_view.results_editor.is_focused(cx),
1919 "Search view with mismatching query should be focused after search results are available",
1920 );
1921 });
1922 cx.spawn(|mut cx| async move {
1923 window.dispatch_action(search_view_id, &ToggleFocus, &mut cx);
1924 })
1925 .detach();
1926 deterministic.run_until_parked();
1927 search_view.update(cx, |search_view, cx| {
1928 assert!(
1929 search_view.results_editor.is_focused(cx),
1930 "Search view with matching query should still have its results editor focused after the toggle focus event",
1931 );
1932 });
1933
1934 workspace.update(cx, |workspace, cx| {
1935 ProjectSearchView::deploy(workspace, &workspace::NewSearch, cx)
1936 });
1937 search_view.update(cx, |search_view, cx| {
1938 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");
1939 assert_eq!(
1940 search_view
1941 .results_editor
1942 .update(cx, |editor, cx| editor.display_text(cx)),
1943 "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
1944 "Results should be unchanged after search view 2nd open in a row"
1945 );
1946 assert!(
1947 search_view.query_editor.is_focused(cx),
1948 "Focus should be moved into query editor again after search view 2nd open in a row"
1949 );
1950 });
1951
1952 cx.spawn(|mut cx| async move {
1953 window.dispatch_action(search_view_id, &ToggleFocus, &mut cx);
1954 })
1955 .detach();
1956 deterministic.run_until_parked();
1957 search_view.update(cx, |search_view, cx| {
1958 assert!(
1959 search_view.results_editor.is_focused(cx),
1960 "Search view with matching query should switch focus to the results editor after the toggle focus event",
1961 );
1962 });
1963 }
1964
1965 #[gpui::test]
1966 async fn test_new_project_search_in_directory(
1967 deterministic: Arc<Deterministic>,
1968 cx: &mut TestAppContext,
1969 ) {
1970 init_test(cx);
1971
1972 let fs = FakeFs::new(cx.background());
1973 fs.insert_tree(
1974 "/dir",
1975 json!({
1976 "a": {
1977 "one.rs": "const ONE: usize = 1;",
1978 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
1979 },
1980 "b": {
1981 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
1982 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
1983 },
1984 }),
1985 )
1986 .await;
1987 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
1988 let worktree_id = project.read_with(cx, |project, cx| {
1989 project.worktrees(cx).next().unwrap().read(cx).id()
1990 });
1991 let workspace = cx
1992 .add_window(|cx| Workspace::test_new(project, cx))
1993 .root(cx);
1994
1995 let active_item = cx.read(|cx| {
1996 workspace
1997 .read(cx)
1998 .active_pane()
1999 .read(cx)
2000 .active_item()
2001 .and_then(|item| item.downcast::<ProjectSearchView>())
2002 });
2003 assert!(
2004 active_item.is_none(),
2005 "Expected no search panel to be active, but got: {active_item:?}"
2006 );
2007
2008 let one_file_entry = cx.update(|cx| {
2009 workspace
2010 .read(cx)
2011 .project()
2012 .read(cx)
2013 .entry_for_path(&(worktree_id, "a/one.rs").into(), cx)
2014 .expect("no entry for /a/one.rs file")
2015 });
2016 assert!(one_file_entry.is_file());
2017 workspace.update(cx, |workspace, cx| {
2018 ProjectSearchView::new_search_in_directory(workspace, &one_file_entry, cx)
2019 });
2020 let active_search_entry = cx.read(|cx| {
2021 workspace
2022 .read(cx)
2023 .active_pane()
2024 .read(cx)
2025 .active_item()
2026 .and_then(|item| item.downcast::<ProjectSearchView>())
2027 });
2028 assert!(
2029 active_search_entry.is_none(),
2030 "Expected no search panel to be active for file entry"
2031 );
2032
2033 let a_dir_entry = cx.update(|cx| {
2034 workspace
2035 .read(cx)
2036 .project()
2037 .read(cx)
2038 .entry_for_path(&(worktree_id, "a").into(), cx)
2039 .expect("no entry for /a/ directory")
2040 });
2041 assert!(a_dir_entry.is_dir());
2042 workspace.update(cx, |workspace, cx| {
2043 ProjectSearchView::new_search_in_directory(workspace, &a_dir_entry, cx)
2044 });
2045
2046 let Some(search_view) = cx.read(|cx| {
2047 workspace
2048 .read(cx)
2049 .active_pane()
2050 .read(cx)
2051 .active_item()
2052 .and_then(|item| item.downcast::<ProjectSearchView>())
2053 }) else {
2054 panic!("Search view expected to appear after new search in directory event trigger")
2055 };
2056 deterministic.run_until_parked();
2057 search_view.update(cx, |search_view, cx| {
2058 assert!(
2059 search_view.query_editor.is_focused(cx),
2060 "On new search in directory, focus should be moved into query editor"
2061 );
2062 search_view.excluded_files_editor.update(cx, |editor, cx| {
2063 assert!(
2064 editor.display_text(cx).is_empty(),
2065 "New search in directory should not have any excluded files"
2066 );
2067 });
2068 search_view.included_files_editor.update(cx, |editor, cx| {
2069 assert_eq!(
2070 editor.display_text(cx),
2071 a_dir_entry.path.to_str().unwrap(),
2072 "New search in directory should have included dir entry path"
2073 );
2074 });
2075 });
2076
2077 search_view.update(cx, |search_view, cx| {
2078 search_view
2079 .query_editor
2080 .update(cx, |query_editor, cx| query_editor.set_text("const", cx));
2081 search_view.search(cx);
2082 });
2083 deterministic.run_until_parked();
2084 search_view.update(cx, |search_view, cx| {
2085 assert_eq!(
2086 search_view
2087 .results_editor
2088 .update(cx, |editor, cx| editor.display_text(cx)),
2089 "\n\nconst ONE: usize = 1;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
2090 "New search in directory should have a filter that matches a certain directory"
2091 );
2092 });
2093 }
2094
2095 #[gpui::test]
2096 async fn test_search_query_history(cx: &mut TestAppContext) {
2097 init_test(cx);
2098
2099 let fs = FakeFs::new(cx.background());
2100 fs.insert_tree(
2101 "/dir",
2102 json!({
2103 "one.rs": "const ONE: usize = 1;",
2104 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2105 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2106 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2107 }),
2108 )
2109 .await;
2110 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
2111 let window = cx.add_window(|cx| Workspace::test_new(project, cx));
2112 let workspace = window.root(cx);
2113 workspace.update(cx, |workspace, cx| {
2114 ProjectSearchView::deploy(workspace, &workspace::NewSearch, cx)
2115 });
2116
2117 let search_view = cx.read(|cx| {
2118 workspace
2119 .read(cx)
2120 .active_pane()
2121 .read(cx)
2122 .active_item()
2123 .and_then(|item| item.downcast::<ProjectSearchView>())
2124 .expect("Search view expected to appear after new search event trigger")
2125 });
2126
2127 let search_bar = window.add_view(cx, |cx| {
2128 let mut search_bar = ProjectSearchBar::new();
2129 search_bar.set_active_pane_item(Some(&search_view), cx);
2130 // search_bar.show(cx);
2131 search_bar
2132 });
2133
2134 // Add 3 search items into the history + another unsubmitted one.
2135 search_view.update(cx, |search_view, cx| {
2136 search_view.search_options = SearchOptions::CASE_SENSITIVE;
2137 search_view
2138 .query_editor
2139 .update(cx, |query_editor, cx| query_editor.set_text("ONE", cx));
2140 search_view.search(cx);
2141 });
2142 cx.foreground().run_until_parked();
2143 search_view.update(cx, |search_view, cx| {
2144 search_view
2145 .query_editor
2146 .update(cx, |query_editor, cx| query_editor.set_text("TWO", cx));
2147 search_view.search(cx);
2148 });
2149 cx.foreground().run_until_parked();
2150 search_view.update(cx, |search_view, cx| {
2151 search_view
2152 .query_editor
2153 .update(cx, |query_editor, cx| query_editor.set_text("THREE", cx));
2154 search_view.search(cx);
2155 });
2156 cx.foreground().run_until_parked();
2157 search_view.update(cx, |search_view, cx| {
2158 search_view.query_editor.update(cx, |query_editor, cx| {
2159 query_editor.set_text("JUST_TEXT_INPUT", cx)
2160 });
2161 });
2162 cx.foreground().run_until_parked();
2163
2164 // Ensure that the latest input with search settings is active.
2165 search_view.update(cx, |search_view, cx| {
2166 assert_eq!(
2167 search_view.query_editor.read(cx).text(cx),
2168 "JUST_TEXT_INPUT"
2169 );
2170 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2171 });
2172
2173 // Next history query after the latest should set the query to the empty string.
2174 search_bar.update(cx, |search_bar, cx| {
2175 search_bar.next_history_query(&NextHistoryQuery, cx);
2176 });
2177 search_view.update(cx, |search_view, cx| {
2178 assert_eq!(search_view.query_editor.read(cx).text(cx), "");
2179 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2180 });
2181 search_bar.update(cx, |search_bar, cx| {
2182 search_bar.next_history_query(&NextHistoryQuery, cx);
2183 });
2184 search_view.update(cx, |search_view, cx| {
2185 assert_eq!(search_view.query_editor.read(cx).text(cx), "");
2186 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2187 });
2188
2189 // First previous query for empty current query should set the query to the latest submitted one.
2190 search_bar.update(cx, |search_bar, cx| {
2191 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2192 });
2193 search_view.update(cx, |search_view, cx| {
2194 assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
2195 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2196 });
2197
2198 // Further previous items should go over the history in reverse order.
2199 search_bar.update(cx, |search_bar, cx| {
2200 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2201 });
2202 search_view.update(cx, |search_view, cx| {
2203 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
2204 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2205 });
2206
2207 // Previous items should never go behind the first history item.
2208 search_bar.update(cx, |search_bar, cx| {
2209 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2210 });
2211 search_view.update(cx, |search_view, cx| {
2212 assert_eq!(search_view.query_editor.read(cx).text(cx), "ONE");
2213 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2214 });
2215 search_bar.update(cx, |search_bar, cx| {
2216 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2217 });
2218 search_view.update(cx, |search_view, cx| {
2219 assert_eq!(search_view.query_editor.read(cx).text(cx), "ONE");
2220 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2221 });
2222
2223 // Next items should go over the history in the original order.
2224 search_bar.update(cx, |search_bar, cx| {
2225 search_bar.next_history_query(&NextHistoryQuery, cx);
2226 });
2227 search_view.update(cx, |search_view, cx| {
2228 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
2229 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2230 });
2231
2232 search_view.update(cx, |search_view, cx| {
2233 search_view
2234 .query_editor
2235 .update(cx, |query_editor, cx| query_editor.set_text("TWO_NEW", cx));
2236 search_view.search(cx);
2237 });
2238 cx.foreground().run_until_parked();
2239 search_view.update(cx, |search_view, cx| {
2240 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO_NEW");
2241 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2242 });
2243
2244 // New search input should add another entry to history and move the selection to the end of the history.
2245 search_bar.update(cx, |search_bar, cx| {
2246 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2247 });
2248 search_view.update(cx, |search_view, cx| {
2249 assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
2250 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2251 });
2252 search_bar.update(cx, |search_bar, cx| {
2253 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2254 });
2255 search_view.update(cx, |search_view, cx| {
2256 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
2257 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2258 });
2259 search_bar.update(cx, |search_bar, cx| {
2260 search_bar.next_history_query(&NextHistoryQuery, cx);
2261 });
2262 search_view.update(cx, |search_view, cx| {
2263 assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
2264 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2265 });
2266 search_bar.update(cx, |search_bar, cx| {
2267 search_bar.next_history_query(&NextHistoryQuery, cx);
2268 });
2269 search_view.update(cx, |search_view, cx| {
2270 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO_NEW");
2271 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2272 });
2273 search_bar.update(cx, |search_bar, cx| {
2274 search_bar.next_history_query(&NextHistoryQuery, cx);
2275 });
2276 search_view.update(cx, |search_view, cx| {
2277 assert_eq!(search_view.query_editor.read(cx).text(cx), "");
2278 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2279 });
2280 }
2281
2282 pub fn init_test(cx: &mut TestAppContext) {
2283 cx.foreground().forbid_parking();
2284 let fonts = cx.font_cache();
2285 let mut theme = gpui::fonts::with_font_cache(fonts.clone(), theme::Theme::default);
2286 theme.search.match_background = Color::red();
2287
2288 cx.update(|cx| {
2289 cx.set_global(SettingsStore::test(cx));
2290 cx.set_global(ActiveSearches::default());
2291 settings::register::<SemanticIndexSettings>(cx);
2292
2293 theme::init((), cx);
2294 cx.update_global::<SettingsStore, _, _>(|store, _| {
2295 let mut settings = store.get::<ThemeSettings>(None).clone();
2296 settings.theme = Arc::new(theme);
2297 store.override_global(settings)
2298 });
2299
2300 language::init(cx);
2301 client::init_settings(cx);
2302 editor::init(cx);
2303 workspace::init_settings(cx);
2304 Project::init_settings(cx);
2305 super::init(cx);
2306 });
2307 }
2308}