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
644 let index_task = semantic_index.update(cx, |semantic_index, cx| {
645 semantic_index.index_project(project, cx)
646 });
647
648 cx.spawn(|search_view, mut cx| async move {
649 let (files_to_index, mut files_remaining_rx) = index_task.await?;
650
651 search_view.update(&mut cx, |search_view, cx| {
652 cx.notify();
653 search_view.semantic_state = Some(SemanticSearchState {
654 file_count: files_to_index,
655 outstanding_file_count: files_to_index,
656 _progress_task: cx.spawn(|search_view, mut cx| async move {
657 while let Some(count) = files_remaining_rx.recv().await {
658 search_view
659 .update(&mut cx, |search_view, cx| {
660 if let Some(semantic_search_state) =
661 &mut search_view.semantic_state
662 {
663 semantic_search_state.outstanding_file_count = count;
664 cx.notify();
665 if count == 0 {
666 return;
667 }
668 }
669 })
670 .ok();
671 }
672 }),
673 });
674 })?;
675 anyhow::Ok(())
676 })
677 .detach_and_log_err(cx);
678 }
679 }
680
681 fn clear_search(&mut self, cx: &mut ViewContext<Self>) {
682 self.model.update(cx, |model, cx| {
683 model.pending_search = None;
684 model.no_results = None;
685 model.match_ranges.clear();
686
687 model.excerpts.update(cx, |excerpts, cx| {
688 excerpts.clear(cx);
689 });
690 });
691 }
692
693 fn activate_search_mode(&mut self, mode: SearchMode, cx: &mut ViewContext<Self>) {
694 let previous_mode = self.current_mode;
695 if previous_mode == mode {
696 return;
697 }
698
699 self.clear_search(cx);
700 self.current_mode = mode;
701 self.active_match_index = None;
702
703 match mode {
704 SearchMode::Semantic => {
705 let has_permission = self.semantic_permissioned(cx);
706 self.active_match_index = None;
707 cx.spawn(|this, mut cx| async move {
708 let has_permission = has_permission.await?;
709
710 if !has_permission {
711 let mut answer = this.update(&mut cx, |this, cx| {
712 let project = this.model.read(cx).project.clone();
713 let project_name = project
714 .read(cx)
715 .worktree_root_names(cx)
716 .collect::<Vec<&str>>()
717 .join("/");
718 let is_plural =
719 project_name.chars().filter(|letter| *letter == '/').count() > 0;
720 let prompt_text = format!("Would you like to index the '{}' project{} for semantic search? This requires sending code to the OpenAI API", project_name,
721 if is_plural {
722 "s"
723 } else {""});
724 cx.prompt(
725 PromptLevel::Info,
726 prompt_text.as_str(),
727 &["Continue", "Cancel"],
728 )
729 })?;
730
731 if answer.next().await == Some(0) {
732 this.update(&mut cx, |this, _| {
733 this.semantic_permissioned = Some(true);
734 })?;
735 } else {
736 this.update(&mut cx, |this, cx| {
737 this.semantic_permissioned = Some(false);
738 debug_assert_ne!(previous_mode, SearchMode::Semantic, "Tried to re-enable semantic search mode after user modal was rejected");
739 this.activate_search_mode(previous_mode, cx);
740 })?;
741 return anyhow::Ok(());
742 }
743 }
744
745 this.update(&mut cx, |this, cx| {
746 this.index_project(cx);
747 })?;
748
749 anyhow::Ok(())
750 }).detach_and_log_err(cx);
751 }
752 SearchMode::Regex | SearchMode::Text => {
753 self.semantic_state = None;
754 self.active_match_index = None;
755 self.search(cx);
756 }
757 }
758
759 cx.notify();
760 }
761
762 fn new(model: ModelHandle<ProjectSearch>, cx: &mut ViewContext<Self>) -> Self {
763 let mut project;
764 let excerpts;
765 let mut query_text = String::new();
766 let mut options = SearchOptions::NONE;
767
768 {
769 let model = model.read(cx);
770 project = model.project.clone();
771 excerpts = model.excerpts.clone();
772 if let Some(active_query) = model.active_query.as_ref() {
773 query_text = active_query.as_str().to_string();
774 options = SearchOptions::from_query(active_query);
775 }
776 }
777 cx.observe(&model, |this, _, cx| this.model_changed(cx))
778 .detach();
779
780 let query_editor = cx.add_view(|cx| {
781 let mut editor = Editor::single_line(
782 Some(Arc::new(|theme| theme.search.editor.input.clone())),
783 cx,
784 );
785 editor.set_placeholder_text("Text search all files", cx);
786 editor.set_text(query_text, cx);
787 editor
788 });
789 // Subscribe to query_editor in order to reraise editor events for workspace item activation purposes
790 cx.subscribe(&query_editor, |_, _, event, cx| {
791 cx.emit(ViewEvent::EditorEvent(event.clone()))
792 })
793 .detach();
794
795 let results_editor = cx.add_view(|cx| {
796 let mut editor = Editor::for_multibuffer(excerpts, Some(project.clone()), cx);
797 editor.set_searchable(false);
798 editor
799 });
800 cx.observe(&results_editor, |_, _, cx| cx.emit(ViewEvent::UpdateTab))
801 .detach();
802
803 cx.subscribe(&results_editor, |this, _, event, cx| {
804 if matches!(event, editor::Event::SelectionsChanged { .. }) {
805 this.update_match_index(cx);
806 }
807 // Reraise editor events for workspace item activation purposes
808 cx.emit(ViewEvent::EditorEvent(event.clone()));
809 })
810 .detach();
811
812 let included_files_editor = cx.add_view(|cx| {
813 let mut editor = Editor::single_line(
814 Some(Arc::new(|theme| {
815 theme.search.include_exclude_editor.input.clone()
816 })),
817 cx,
818 );
819 editor.set_placeholder_text("Include: crates/**/*.toml", cx);
820
821 editor
822 });
823 // Subscribe to include_files_editor in order to reraise editor events for workspace item activation purposes
824 cx.subscribe(&included_files_editor, |_, _, event, cx| {
825 cx.emit(ViewEvent::EditorEvent(event.clone()))
826 })
827 .detach();
828
829 let excluded_files_editor = cx.add_view(|cx| {
830 let mut editor = Editor::single_line(
831 Some(Arc::new(|theme| {
832 theme.search.include_exclude_editor.input.clone()
833 })),
834 cx,
835 );
836 editor.set_placeholder_text("Exclude: vendor/*, *.lock", cx);
837
838 editor
839 });
840 // Subscribe to excluded_files_editor in order to reraise editor events for workspace item activation purposes
841 cx.subscribe(&excluded_files_editor, |_, _, event, cx| {
842 cx.emit(ViewEvent::EditorEvent(event.clone()))
843 })
844 .detach();
845 let filters_enabled = false;
846
847 // Check if Worktrees have all been previously indexed
848 let mut this = ProjectSearchView {
849 search_id: model.read(cx).search_id,
850 model,
851 query_editor,
852 results_editor,
853 semantic_state: None,
854 semantic_permissioned: None,
855 search_options: options,
856 panels_with_errors: HashSet::new(),
857 active_match_index: None,
858 query_editor_was_focused: false,
859 included_files_editor,
860 excluded_files_editor,
861 filters_enabled,
862 current_mode: Default::default(),
863 };
864 this.model_changed(cx);
865 this
866 }
867
868 fn semantic_permissioned(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<bool>> {
869 if let Some(value) = self.semantic_permissioned {
870 return Task::ready(Ok(value));
871 }
872
873 SemanticIndex::global(cx)
874 .map(|semantic| {
875 let project = self.model.read(cx).project.clone();
876 semantic.update(cx, |this, cx| this.project_previously_indexed(project, cx))
877 })
878 .unwrap_or(Task::ready(Ok(false)))
879 }
880 pub fn new_search_in_directory(
881 workspace: &mut Workspace,
882 dir_entry: &Entry,
883 cx: &mut ViewContext<Workspace>,
884 ) {
885 if !dir_entry.is_dir() {
886 return;
887 }
888 let Some(filter_str) = dir_entry.path.to_str() else { return; };
889
890 let model = cx.add_model(|cx| ProjectSearch::new(workspace.project().clone(), cx));
891 let search = cx.add_view(|cx| ProjectSearchView::new(model, cx));
892 workspace.add_item(Box::new(search.clone()), cx);
893 search.update(cx, |search, cx| {
894 search
895 .included_files_editor
896 .update(cx, |editor, cx| editor.set_text(filter_str, cx));
897 search.focus_query_editor(cx)
898 });
899 }
900
901 // Re-activate the most recently activated search or the most recent if it has been closed.
902 // If no search exists in the workspace, create a new one.
903 fn deploy(
904 workspace: &mut Workspace,
905 _: &workspace::NewSearch,
906 cx: &mut ViewContext<Workspace>,
907 ) {
908 // Clean up entries for dropped projects
909 cx.update_global(|state: &mut ActiveSearches, cx| {
910 state.0.retain(|project, _| project.is_upgradable(cx))
911 });
912
913 let active_search = cx
914 .global::<ActiveSearches>()
915 .0
916 .get(&workspace.project().downgrade());
917
918 let existing = active_search
919 .and_then(|active_search| {
920 workspace
921 .items_of_type::<ProjectSearchView>(cx)
922 .find(|search| search == active_search)
923 })
924 .or_else(|| workspace.item_of_type::<ProjectSearchView>(cx));
925
926 let query = workspace.active_item(cx).and_then(|item| {
927 let editor = item.act_as::<Editor>(cx)?;
928 let query = editor.query_suggestion(cx);
929 if query.is_empty() {
930 None
931 } else {
932 Some(query)
933 }
934 });
935
936 let search = if let Some(existing) = existing {
937 workspace.activate_item(&existing, cx);
938 existing
939 } else {
940 let model = cx.add_model(|cx| ProjectSearch::new(workspace.project().clone(), cx));
941 let view = cx.add_view(|cx| ProjectSearchView::new(model, cx));
942 workspace.add_item(Box::new(view.clone()), cx);
943 view
944 };
945
946 search.update(cx, |search, cx| {
947 if let Some(query) = query {
948 search.set_query(&query, cx);
949 }
950 search.focus_query_editor(cx)
951 });
952 }
953
954 fn search(&mut self, cx: &mut ViewContext<Self>) {
955 let mode = self.current_mode;
956 match mode {
957 SearchMode::Semantic => {
958 if let Some(semantic) = &mut self.semantic_state {
959 if semantic.outstanding_file_count > 0 {
960 return;
961 }
962
963 if let Some(query) = self.build_search_query(cx) {
964 self.model
965 .update(cx, |model, cx| model.semantic_search(query.as_inner(), cx));
966 }
967 }
968 }
969
970 _ => {
971 if let Some(query) = self.build_search_query(cx) {
972 self.model.update(cx, |model, cx| model.search(query, cx));
973 }
974 }
975 }
976 }
977
978 fn build_search_query(&mut self, cx: &mut ViewContext<Self>) -> Option<SearchQuery> {
979 let text = self.query_editor.read(cx).text(cx);
980 let included_files =
981 match Self::parse_path_matches(&self.included_files_editor.read(cx).text(cx)) {
982 Ok(included_files) => {
983 self.panels_with_errors.remove(&InputPanel::Include);
984 included_files
985 }
986 Err(_e) => {
987 self.panels_with_errors.insert(InputPanel::Include);
988 cx.notify();
989 return None;
990 }
991 };
992 let excluded_files =
993 match Self::parse_path_matches(&self.excluded_files_editor.read(cx).text(cx)) {
994 Ok(excluded_files) => {
995 self.panels_with_errors.remove(&InputPanel::Exclude);
996 excluded_files
997 }
998 Err(_e) => {
999 self.panels_with_errors.insert(InputPanel::Exclude);
1000 cx.notify();
1001 return None;
1002 }
1003 };
1004 let current_mode = self.current_mode;
1005 match current_mode {
1006 SearchMode::Regex => {
1007 match SearchQuery::regex(
1008 text,
1009 self.search_options.contains(SearchOptions::WHOLE_WORD),
1010 self.search_options.contains(SearchOptions::CASE_SENSITIVE),
1011 included_files,
1012 excluded_files,
1013 ) {
1014 Ok(query) => {
1015 self.panels_with_errors.remove(&InputPanel::Query);
1016 Some(query)
1017 }
1018 Err(_e) => {
1019 self.panels_with_errors.insert(InputPanel::Query);
1020 cx.notify();
1021 None
1022 }
1023 }
1024 }
1025 _ => Some(SearchQuery::text(
1026 text,
1027 self.search_options.contains(SearchOptions::WHOLE_WORD),
1028 self.search_options.contains(SearchOptions::CASE_SENSITIVE),
1029 included_files,
1030 excluded_files,
1031 )),
1032 }
1033 }
1034
1035 fn parse_path_matches(text: &str) -> anyhow::Result<Vec<PathMatcher>> {
1036 text.split(',')
1037 .map(str::trim)
1038 .filter(|maybe_glob_str| !maybe_glob_str.is_empty())
1039 .map(|maybe_glob_str| {
1040 PathMatcher::new(maybe_glob_str)
1041 .with_context(|| format!("parsing {maybe_glob_str} as path matcher"))
1042 })
1043 .collect()
1044 }
1045
1046 fn select_match(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
1047 if let Some(index) = self.active_match_index {
1048 let match_ranges = self.model.read(cx).match_ranges.clone();
1049 let new_index = self.results_editor.update(cx, |editor, cx| {
1050 editor.match_index_for_direction(&match_ranges, index, direction, 1, cx)
1051 });
1052
1053 let range_to_select = match_ranges[new_index].clone();
1054 self.results_editor.update(cx, |editor, cx| {
1055 let range_to_select = editor.range_for_match(&range_to_select);
1056 editor.unfold_ranges([range_to_select.clone()], false, true, cx);
1057 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
1058 s.select_ranges([range_to_select])
1059 });
1060 });
1061 }
1062 }
1063
1064 fn focus_query_editor(&mut self, cx: &mut ViewContext<Self>) {
1065 self.query_editor.update(cx, |query_editor, cx| {
1066 query_editor.select_all(&SelectAll, cx);
1067 });
1068 self.query_editor_was_focused = true;
1069 cx.focus(&self.query_editor);
1070 }
1071
1072 fn set_query(&mut self, query: &str, cx: &mut ViewContext<Self>) {
1073 self.query_editor
1074 .update(cx, |query_editor, cx| query_editor.set_text(query, cx));
1075 }
1076
1077 fn focus_results_editor(&mut self, cx: &mut ViewContext<Self>) {
1078 self.query_editor.update(cx, |query_editor, cx| {
1079 let cursor = query_editor.selections.newest_anchor().head();
1080 query_editor.change_selections(None, cx, |s| s.select_ranges([cursor.clone()..cursor]));
1081 });
1082 self.query_editor_was_focused = false;
1083 cx.focus(&self.results_editor);
1084 }
1085
1086 fn model_changed(&mut self, cx: &mut ViewContext<Self>) {
1087 let match_ranges = self.model.read(cx).match_ranges.clone();
1088 if match_ranges.is_empty() {
1089 self.active_match_index = None;
1090 } else {
1091 self.active_match_index = Some(0);
1092 self.update_match_index(cx);
1093 let prev_search_id = mem::replace(&mut self.search_id, self.model.read(cx).search_id);
1094 let is_new_search = self.search_id != prev_search_id;
1095 self.results_editor.update(cx, |editor, cx| {
1096 if is_new_search {
1097 let range_to_select = match_ranges
1098 .first()
1099 .clone()
1100 .map(|range| editor.range_for_match(range));
1101 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
1102 s.select_ranges(range_to_select)
1103 });
1104 }
1105 editor.highlight_background::<Self>(
1106 match_ranges,
1107 |theme| theme.search.match_background,
1108 cx,
1109 );
1110 });
1111 if is_new_search && self.query_editor.is_focused(cx) {
1112 self.focus_results_editor(cx);
1113 }
1114 }
1115
1116 cx.emit(ViewEvent::UpdateTab);
1117 cx.notify();
1118 }
1119
1120 fn update_match_index(&mut self, cx: &mut ViewContext<Self>) {
1121 let results_editor = self.results_editor.read(cx);
1122 let new_index = active_match_index(
1123 &self.model.read(cx).match_ranges,
1124 &results_editor.selections.newest_anchor().head(),
1125 &results_editor.buffer().read(cx).snapshot(cx),
1126 );
1127 if self.active_match_index != new_index {
1128 self.active_match_index = new_index;
1129 cx.notify();
1130 }
1131 }
1132
1133 pub fn has_matches(&self) -> bool {
1134 self.active_match_index.is_some()
1135 }
1136
1137 fn move_focus_to_results(pane: &mut Pane, _: &ToggleFocus, cx: &mut ViewContext<Pane>) {
1138 if let Some(search_view) = pane
1139 .active_item()
1140 .and_then(|item| item.downcast::<ProjectSearchView>())
1141 {
1142 search_view.update(cx, |search_view, cx| {
1143 if !search_view.results_editor.is_focused(cx)
1144 && !search_view.model.read(cx).match_ranges.is_empty()
1145 {
1146 return search_view.focus_results_editor(cx);
1147 }
1148 });
1149 }
1150
1151 cx.propagate_action();
1152 }
1153}
1154
1155impl Default for ProjectSearchBar {
1156 fn default() -> Self {
1157 Self::new()
1158 }
1159}
1160
1161impl ProjectSearchBar {
1162 pub fn new() -> Self {
1163 Self {
1164 active_project_search: Default::default(),
1165 subscription: Default::default(),
1166 }
1167 }
1168 fn cycle_mode(workspace: &mut Workspace, _: &CycleMode, cx: &mut ViewContext<Workspace>) {
1169 if let Some(search_view) = workspace
1170 .active_item(cx)
1171 .and_then(|item| item.downcast::<ProjectSearchView>())
1172 {
1173 search_view.update(cx, |this, cx| {
1174 let new_mode =
1175 crate::mode::next_mode(&this.current_mode, SemanticIndex::enabled(cx));
1176 this.activate_search_mode(new_mode, cx);
1177 cx.focus(&this.query_editor);
1178 })
1179 }
1180 }
1181 fn search(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
1182 if let Some(search_view) = self.active_project_search.as_ref() {
1183 search_view.update(cx, |search_view, cx| search_view.search(cx));
1184 }
1185 }
1186
1187 fn search_in_new(workspace: &mut Workspace, _: &SearchInNew, cx: &mut ViewContext<Workspace>) {
1188 if let Some(search_view) = workspace
1189 .active_item(cx)
1190 .and_then(|item| item.downcast::<ProjectSearchView>())
1191 {
1192 let new_query = search_view.update(cx, |search_view, cx| {
1193 let new_query = search_view.build_search_query(cx);
1194 if new_query.is_some() {
1195 if let Some(old_query) = search_view.model.read(cx).active_query.clone() {
1196 search_view.query_editor.update(cx, |editor, cx| {
1197 editor.set_text(old_query.as_str(), cx);
1198 });
1199 search_view.search_options = SearchOptions::from_query(&old_query);
1200 }
1201 }
1202 new_query
1203 });
1204 if let Some(new_query) = new_query {
1205 let model = cx.add_model(|cx| {
1206 let mut model = ProjectSearch::new(workspace.project().clone(), cx);
1207 model.search(new_query, cx);
1208 model
1209 });
1210 workspace.add_item(
1211 Box::new(cx.add_view(|cx| ProjectSearchView::new(model, cx))),
1212 cx,
1213 );
1214 }
1215 }
1216 }
1217
1218 fn select_next_match(pane: &mut Pane, _: &SelectNextMatch, cx: &mut ViewContext<Pane>) {
1219 if let Some(search_view) = pane
1220 .active_item()
1221 .and_then(|item| item.downcast::<ProjectSearchView>())
1222 {
1223 search_view.update(cx, |view, cx| view.select_match(Direction::Next, cx));
1224 } else {
1225 cx.propagate_action();
1226 }
1227 }
1228
1229 fn select_prev_match(pane: &mut Pane, _: &SelectPrevMatch, cx: &mut ViewContext<Pane>) {
1230 if let Some(search_view) = pane
1231 .active_item()
1232 .and_then(|item| item.downcast::<ProjectSearchView>())
1233 {
1234 search_view.update(cx, |view, cx| view.select_match(Direction::Prev, cx));
1235 } else {
1236 cx.propagate_action();
1237 }
1238 }
1239
1240 fn tab(&mut self, _: &editor::Tab, cx: &mut ViewContext<Self>) {
1241 self.cycle_field(Direction::Next, cx);
1242 }
1243
1244 fn tab_previous(&mut self, _: &editor::TabPrev, cx: &mut ViewContext<Self>) {
1245 self.cycle_field(Direction::Prev, cx);
1246 }
1247
1248 fn cycle_field(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
1249 let active_project_search = match &self.active_project_search {
1250 Some(active_project_search) => active_project_search,
1251
1252 None => {
1253 cx.propagate_action();
1254 return;
1255 }
1256 };
1257
1258 active_project_search.update(cx, |project_view, cx| {
1259 let views = &[
1260 &project_view.query_editor,
1261 &project_view.included_files_editor,
1262 &project_view.excluded_files_editor,
1263 ];
1264
1265 let current_index = match views
1266 .iter()
1267 .enumerate()
1268 .find(|(_, view)| view.is_focused(cx))
1269 {
1270 Some((index, _)) => index,
1271
1272 None => {
1273 cx.propagate_action();
1274 return;
1275 }
1276 };
1277
1278 let new_index = match direction {
1279 Direction::Next => (current_index + 1) % views.len(),
1280 Direction::Prev if current_index == 0 => views.len() - 1,
1281 Direction::Prev => (current_index - 1) % views.len(),
1282 };
1283 cx.focus(views[new_index]);
1284 });
1285 }
1286
1287 fn toggle_search_option(&mut self, option: SearchOptions, cx: &mut ViewContext<Self>) -> bool {
1288 if let Some(search_view) = self.active_project_search.as_ref() {
1289 search_view.update(cx, |search_view, cx| {
1290 search_view.toggle_search_option(option);
1291 search_view.search(cx);
1292 });
1293 cx.notify();
1294 true
1295 } else {
1296 false
1297 }
1298 }
1299
1300 fn activate_regex_mode(pane: &mut Pane, _: &ActivateRegexMode, cx: &mut ViewContext<Pane>) {
1301 if let Some(search_view) = pane
1302 .active_item()
1303 .and_then(|item| item.downcast::<ProjectSearchView>())
1304 {
1305 search_view.update(cx, |view, cx| {
1306 view.activate_search_mode(SearchMode::Regex, cx)
1307 });
1308 } else {
1309 cx.propagate_action();
1310 }
1311 }
1312
1313 fn toggle_filters(&mut self, cx: &mut ViewContext<Self>) -> bool {
1314 if let Some(search_view) = self.active_project_search.as_ref() {
1315 search_view.update(cx, |search_view, cx| {
1316 search_view.filters_enabled = !search_view.filters_enabled;
1317 search_view
1318 .included_files_editor
1319 .update(cx, |_, cx| cx.notify());
1320 search_view
1321 .excluded_files_editor
1322 .update(cx, |_, cx| cx.notify());
1323 cx.refresh_windows();
1324 cx.notify();
1325 });
1326 cx.notify();
1327 true
1328 } else {
1329 false
1330 }
1331 }
1332
1333 fn activate_search_mode(&self, mode: SearchMode, cx: &mut ViewContext<Self>) {
1334 // Update Current Mode
1335 if let Some(search_view) = self.active_project_search.as_ref() {
1336 search_view.update(cx, |search_view, cx| {
1337 search_view.activate_search_mode(mode, cx);
1338 });
1339 cx.notify();
1340 }
1341 }
1342
1343 fn is_option_enabled(&self, option: SearchOptions, cx: &AppContext) -> bool {
1344 if let Some(search) = self.active_project_search.as_ref() {
1345 search.read(cx).search_options.contains(option)
1346 } else {
1347 false
1348 }
1349 }
1350
1351 fn next_history_query(&mut self, _: &NextHistoryQuery, cx: &mut ViewContext<Self>) {
1352 if let Some(search_view) = self.active_project_search.as_ref() {
1353 search_view.update(cx, |search_view, cx| {
1354 let new_query = search_view.model.update(cx, |model, _| {
1355 if let Some(new_query) = model.search_history.next().map(str::to_string) {
1356 new_query
1357 } else {
1358 model.search_history.reset_selection();
1359 String::new()
1360 }
1361 });
1362 search_view.set_query(&new_query, cx);
1363 });
1364 }
1365 }
1366
1367 fn previous_history_query(&mut self, _: &PreviousHistoryQuery, cx: &mut ViewContext<Self>) {
1368 if let Some(search_view) = self.active_project_search.as_ref() {
1369 search_view.update(cx, |search_view, cx| {
1370 if search_view.query_editor.read(cx).text(cx).is_empty() {
1371 if let Some(new_query) = search_view
1372 .model
1373 .read(cx)
1374 .search_history
1375 .current()
1376 .map(str::to_string)
1377 {
1378 search_view.set_query(&new_query, cx);
1379 return;
1380 }
1381 }
1382
1383 if let Some(new_query) = search_view.model.update(cx, |model, _| {
1384 model.search_history.previous().map(str::to_string)
1385 }) {
1386 search_view.set_query(&new_query, cx);
1387 }
1388 });
1389 }
1390 }
1391}
1392
1393impl Entity for ProjectSearchBar {
1394 type Event = ();
1395}
1396
1397impl View for ProjectSearchBar {
1398 fn ui_name() -> &'static str {
1399 "ProjectSearchBar"
1400 }
1401
1402 fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
1403 if let Some(_search) = self.active_project_search.as_ref() {
1404 let search = _search.read(cx);
1405 let theme = theme::current(cx).clone();
1406 let query_container_style = if search.panels_with_errors.contains(&InputPanel::Query) {
1407 theme.search.invalid_editor
1408 } else {
1409 theme.search.editor.input.container
1410 };
1411
1412 let search = _search.read(cx);
1413 let filter_button = render_option_button_icon(
1414 search.filters_enabled,
1415 "icons/filter_12.svg",
1416 0,
1417 "Toggle filters",
1418 Box::new(ToggleFilters),
1419 move |_, this, cx| {
1420 this.toggle_filters(cx);
1421 },
1422 cx,
1423 );
1424 let search = _search.read(cx);
1425 let is_semantic_disabled = search.semantic_state.is_none();
1426 let render_option_button_icon = |path, option, cx: &mut ViewContext<Self>| {
1427 crate::search_bar::render_option_button_icon(
1428 self.is_option_enabled(option, cx),
1429 path,
1430 option.bits as usize,
1431 format!("Toggle {}", option.label()),
1432 option.to_toggle_action(),
1433 move |_, this, cx| {
1434 this.toggle_search_option(option, cx);
1435 },
1436 cx,
1437 )
1438 };
1439 let case_sensitive = is_semantic_disabled.then(|| {
1440 render_option_button_icon(
1441 "icons/case_insensitive_12.svg",
1442 SearchOptions::CASE_SENSITIVE,
1443 cx,
1444 )
1445 });
1446
1447 let whole_word = is_semantic_disabled.then(|| {
1448 render_option_button_icon("icons/word_search_12.svg", SearchOptions::WHOLE_WORD, cx)
1449 });
1450
1451 let search = _search.read(cx);
1452 let icon_style = theme.search.editor_icon.clone();
1453
1454 // Editor Functionality
1455 let query = Flex::row()
1456 .with_child(
1457 Svg::for_style(icon_style.icon)
1458 .contained()
1459 .with_style(icon_style.container),
1460 )
1461 .with_child(ChildView::new(&search.query_editor, cx).flex(1., true))
1462 .with_child(
1463 Flex::row()
1464 .with_child(filter_button)
1465 .with_children(case_sensitive)
1466 .with_children(whole_word)
1467 .flex(1., false)
1468 .constrained()
1469 .contained(),
1470 )
1471 .align_children_center()
1472 .flex(1., true);
1473
1474 let search = _search.read(cx);
1475
1476 let include_container_style =
1477 if search.panels_with_errors.contains(&InputPanel::Include) {
1478 theme.search.invalid_include_exclude_editor
1479 } else {
1480 theme.search.include_exclude_editor.input.container
1481 };
1482
1483 let exclude_container_style =
1484 if search.panels_with_errors.contains(&InputPanel::Exclude) {
1485 theme.search.invalid_include_exclude_editor
1486 } else {
1487 theme.search.include_exclude_editor.input.container
1488 };
1489
1490 let included_files_view = ChildView::new(&search.included_files_editor, cx)
1491 .contained()
1492 .flex(1., true);
1493 let excluded_files_view = ChildView::new(&search.excluded_files_editor, cx)
1494 .contained()
1495 .flex(1., true);
1496 let filters = search.filters_enabled.then(|| {
1497 Flex::row()
1498 .with_child(
1499 included_files_view
1500 .contained()
1501 .with_style(include_container_style)
1502 .constrained()
1503 .with_height(theme.search.search_bar_row_height)
1504 .with_min_width(theme.search.include_exclude_editor.min_width)
1505 .with_max_width(theme.search.include_exclude_editor.max_width),
1506 )
1507 .with_child(
1508 excluded_files_view
1509 .contained()
1510 .with_style(exclude_container_style)
1511 .constrained()
1512 .with_height(theme.search.search_bar_row_height)
1513 .with_min_width(theme.search.include_exclude_editor.min_width)
1514 .with_max_width(theme.search.include_exclude_editor.max_width),
1515 )
1516 .contained()
1517 .with_padding_top(theme.workspace.toolbar.container.padding.bottom)
1518 });
1519
1520 let editor_column = Flex::column()
1521 .with_child(
1522 query
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(filters)
1532 .flex(1., false);
1533
1534 let matches = search.active_match_index.map(|match_ix| {
1535 Label::new(
1536 format!(
1537 "{}/{}",
1538 match_ix + 1,
1539 search.model.read(cx).match_ranges.len()
1540 ),
1541 theme.search.match_index.text.clone(),
1542 )
1543 .contained()
1544 .with_style(theme.search.match_index.container)
1545 .aligned()
1546 });
1547
1548 let search_button_for_mode = |mode, cx: &mut ViewContext<ProjectSearchBar>| {
1549 let is_active = if let Some(search) = self.active_project_search.as_ref() {
1550 let search = search.read(cx);
1551 search.current_mode == mode
1552 } else {
1553 false
1554 };
1555 render_search_mode_button(
1556 mode,
1557 is_active,
1558 move |_, this, cx| {
1559 this.activate_search_mode(mode, cx);
1560 },
1561 cx,
1562 )
1563 };
1564 let is_active = search.active_match_index.is_some();
1565 let semantic_index = SemanticIndex::enabled(cx)
1566 .then(|| search_button_for_mode(SearchMode::Semantic, cx));
1567 let nav_button_for_direction = |label, direction, cx: &mut ViewContext<Self>| {
1568 render_nav_button(
1569 label,
1570 direction,
1571 is_active,
1572 move |_, this, cx| {
1573 if let Some(search) = this.active_project_search.as_ref() {
1574 search.update(cx, |search, cx| search.select_match(direction, cx));
1575 }
1576 },
1577 cx,
1578 )
1579 };
1580
1581 let nav_column = Flex::row()
1582 .with_child(nav_button_for_direction("<", Direction::Prev, cx))
1583 .with_child(nav_button_for_direction(">", Direction::Next, cx))
1584 .with_child(Flex::row().with_children(matches))
1585 .constrained()
1586 .with_height(theme.search.search_bar_row_height);
1587
1588 let mode_column = Flex::row()
1589 .with_child(
1590 Flex::row()
1591 .with_child(search_button_for_mode(SearchMode::Text, cx))
1592 .with_children(semantic_index)
1593 .with_child(search_button_for_mode(SearchMode::Regex, cx))
1594 .contained()
1595 .with_style(theme.search.modes_container),
1596 )
1597 .with_child(super::search_bar::render_close_button(
1598 "Dismiss Project Search",
1599 &theme.search,
1600 cx,
1601 |_, this, cx| {
1602 if let Some(search) = this.active_project_search.as_mut() {
1603 search.update(cx, |_, cx| cx.emit(ViewEvent::Dismiss))
1604 }
1605 },
1606 None,
1607 ))
1608 .constrained()
1609 .with_height(theme.search.search_bar_row_height)
1610 .aligned()
1611 .right()
1612 .top()
1613 .flex_float();
1614
1615 Flex::row()
1616 .with_child(editor_column)
1617 .with_child(nav_column)
1618 .with_child(mode_column)
1619 .contained()
1620 .with_style(theme.search.container)
1621 .into_any_named("project search")
1622 } else {
1623 Empty::new().into_any()
1624 }
1625 }
1626}
1627
1628impl ToolbarItemView for ProjectSearchBar {
1629 fn set_active_pane_item(
1630 &mut self,
1631 active_pane_item: Option<&dyn ItemHandle>,
1632 cx: &mut ViewContext<Self>,
1633 ) -> ToolbarItemLocation {
1634 cx.notify();
1635 self.subscription = None;
1636 self.active_project_search = None;
1637 if let Some(search) = active_pane_item.and_then(|i| i.downcast::<ProjectSearchView>()) {
1638 search.update(cx, |search, cx| {
1639 if search.current_mode == SearchMode::Semantic {
1640 search.index_project(cx);
1641 }
1642 });
1643
1644 self.subscription = Some(cx.observe(&search, |_, _, cx| cx.notify()));
1645 self.active_project_search = Some(search);
1646 ToolbarItemLocation::PrimaryLeft {
1647 flex: Some((1., false)),
1648 }
1649 } else {
1650 ToolbarItemLocation::Hidden
1651 }
1652 }
1653
1654 fn row_count(&self, cx: &ViewContext<Self>) -> usize {
1655 self.active_project_search
1656 .as_ref()
1657 .map(|search| {
1658 let offset = search.read(cx).filters_enabled as usize;
1659 2 + offset
1660 })
1661 .unwrap_or_else(|| 2)
1662 }
1663}
1664
1665#[cfg(test)]
1666pub mod tests {
1667 use super::*;
1668 use editor::DisplayPoint;
1669 use gpui::{color::Color, executor::Deterministic, TestAppContext};
1670 use project::FakeFs;
1671 use semantic_index::semantic_index_settings::SemanticIndexSettings;
1672 use serde_json::json;
1673 use settings::SettingsStore;
1674 use std::sync::Arc;
1675 use theme::ThemeSettings;
1676
1677 #[gpui::test]
1678 async fn test_project_search(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
1679 init_test(cx);
1680
1681 let fs = FakeFs::new(cx.background());
1682 fs.insert_tree(
1683 "/dir",
1684 json!({
1685 "one.rs": "const ONE: usize = 1;",
1686 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
1687 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
1688 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
1689 }),
1690 )
1691 .await;
1692 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
1693 let search = cx.add_model(|cx| ProjectSearch::new(project, cx));
1694 let search_view = cx
1695 .add_window(|cx| ProjectSearchView::new(search.clone(), cx))
1696 .root(cx);
1697
1698 search_view.update(cx, |search_view, cx| {
1699 search_view
1700 .query_editor
1701 .update(cx, |query_editor, cx| query_editor.set_text("TWO", cx));
1702 search_view.search(cx);
1703 });
1704 deterministic.run_until_parked();
1705 search_view.update(cx, |search_view, cx| {
1706 assert_eq!(
1707 search_view
1708 .results_editor
1709 .update(cx, |editor, cx| editor.display_text(cx)),
1710 "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;"
1711 );
1712 assert_eq!(
1713 search_view
1714 .results_editor
1715 .update(cx, |editor, cx| editor.all_background_highlights(cx)),
1716 &[
1717 (
1718 DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35),
1719 Color::red()
1720 ),
1721 (
1722 DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40),
1723 Color::red()
1724 ),
1725 (
1726 DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9),
1727 Color::red()
1728 )
1729 ]
1730 );
1731 assert_eq!(search_view.active_match_index, Some(0));
1732 assert_eq!(
1733 search_view
1734 .results_editor
1735 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1736 [DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35)]
1737 );
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(1));
1744 assert_eq!(
1745 search_view
1746 .results_editor
1747 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1748 [DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40)]
1749 );
1750 search_view.select_match(Direction::Next, 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::Next, cx);
1762 });
1763
1764 search_view.update(cx, |search_view, cx| {
1765 assert_eq!(search_view.active_match_index, Some(0));
1766 assert_eq!(
1767 search_view
1768 .results_editor
1769 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1770 [DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35)]
1771 );
1772 search_view.select_match(Direction::Prev, cx);
1773 });
1774
1775 search_view.update(cx, |search_view, cx| {
1776 assert_eq!(search_view.active_match_index, Some(2));
1777 assert_eq!(
1778 search_view
1779 .results_editor
1780 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1781 [DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9)]
1782 );
1783 search_view.select_match(Direction::Prev, cx);
1784 });
1785
1786 search_view.update(cx, |search_view, cx| {
1787 assert_eq!(search_view.active_match_index, Some(1));
1788 assert_eq!(
1789 search_view
1790 .results_editor
1791 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
1792 [DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40)]
1793 );
1794 });
1795 }
1796
1797 #[gpui::test]
1798 async fn test_project_search_focus(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
1799 init_test(cx);
1800
1801 let fs = FakeFs::new(cx.background());
1802 fs.insert_tree(
1803 "/dir",
1804 json!({
1805 "one.rs": "const ONE: usize = 1;",
1806 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
1807 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
1808 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
1809 }),
1810 )
1811 .await;
1812 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
1813 let window = cx.add_window(|cx| Workspace::test_new(project, cx));
1814 let workspace = window.root(cx);
1815
1816 let active_item = cx.read(|cx| {
1817 workspace
1818 .read(cx)
1819 .active_pane()
1820 .read(cx)
1821 .active_item()
1822 .and_then(|item| item.downcast::<ProjectSearchView>())
1823 });
1824 assert!(
1825 active_item.is_none(),
1826 "Expected no search panel to be active, but got: {active_item:?}"
1827 );
1828
1829 workspace.update(cx, |workspace, cx| {
1830 ProjectSearchView::deploy(workspace, &workspace::NewSearch, cx)
1831 });
1832
1833 let Some(search_view) = cx.read(|cx| {
1834 workspace
1835 .read(cx)
1836 .active_pane()
1837 .read(cx)
1838 .active_item()
1839 .and_then(|item| item.downcast::<ProjectSearchView>())
1840 }) else {
1841 panic!("Search view expected to appear after new search event trigger")
1842 };
1843 let search_view_id = search_view.id();
1844
1845 cx.spawn(|mut cx| async move {
1846 window.dispatch_action(search_view_id, &ToggleFocus, &mut cx);
1847 })
1848 .detach();
1849 deterministic.run_until_parked();
1850 search_view.update(cx, |search_view, cx| {
1851 assert!(
1852 search_view.query_editor.is_focused(cx),
1853 "Empty search view should be focused after the toggle focus event: no results panel to focus on",
1854 );
1855 });
1856
1857 search_view.update(cx, |search_view, cx| {
1858 let query_editor = &search_view.query_editor;
1859 assert!(
1860 query_editor.is_focused(cx),
1861 "Search view should be focused after the new search view is activated",
1862 );
1863 let query_text = query_editor.read(cx).text(cx);
1864 assert!(
1865 query_text.is_empty(),
1866 "New search query should be empty but got '{query_text}'",
1867 );
1868 let results_text = search_view
1869 .results_editor
1870 .update(cx, |editor, cx| editor.display_text(cx));
1871 assert!(
1872 results_text.is_empty(),
1873 "Empty search view should have no results but got '{results_text}'"
1874 );
1875 });
1876
1877 search_view.update(cx, |search_view, cx| {
1878 search_view.query_editor.update(cx, |query_editor, cx| {
1879 query_editor.set_text("sOMETHINGtHATsURELYdOESnOTeXIST", cx)
1880 });
1881 search_view.search(cx);
1882 });
1883 deterministic.run_until_parked();
1884 search_view.update(cx, |search_view, cx| {
1885 let results_text = search_view
1886 .results_editor
1887 .update(cx, |editor, cx| editor.display_text(cx));
1888 assert!(
1889 results_text.is_empty(),
1890 "Search view for mismatching query should have no results but got '{results_text}'"
1891 );
1892 assert!(
1893 search_view.query_editor.is_focused(cx),
1894 "Search view should be focused after mismatching query had been used in search",
1895 );
1896 });
1897 cx.spawn(
1898 |mut cx| async move { window.dispatch_action(search_view_id, &ToggleFocus, &mut cx) },
1899 )
1900 .detach();
1901 deterministic.run_until_parked();
1902 search_view.update(cx, |search_view, cx| {
1903 assert!(
1904 search_view.query_editor.is_focused(cx),
1905 "Search view with mismatching query should be focused after the toggle focus event: still no results panel to focus on",
1906 );
1907 });
1908
1909 search_view.update(cx, |search_view, cx| {
1910 search_view
1911 .query_editor
1912 .update(cx, |query_editor, cx| query_editor.set_text("TWO", cx));
1913 search_view.search(cx);
1914 });
1915 deterministic.run_until_parked();
1916 search_view.update(cx, |search_view, cx| {
1917 assert_eq!(
1918 search_view
1919 .results_editor
1920 .update(cx, |editor, cx| editor.display_text(cx)),
1921 "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
1922 "Search view results should match the query"
1923 );
1924 assert!(
1925 search_view.results_editor.is_focused(cx),
1926 "Search view with mismatching query should be focused after search results are available",
1927 );
1928 });
1929 cx.spawn(|mut cx| async move {
1930 window.dispatch_action(search_view_id, &ToggleFocus, &mut cx);
1931 })
1932 .detach();
1933 deterministic.run_until_parked();
1934 search_view.update(cx, |search_view, cx| {
1935 assert!(
1936 search_view.results_editor.is_focused(cx),
1937 "Search view with matching query should still have its results editor focused after the toggle focus event",
1938 );
1939 });
1940
1941 workspace.update(cx, |workspace, cx| {
1942 ProjectSearchView::deploy(workspace, &workspace::NewSearch, cx)
1943 });
1944 search_view.update(cx, |search_view, cx| {
1945 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");
1946 assert_eq!(
1947 search_view
1948 .results_editor
1949 .update(cx, |editor, cx| editor.display_text(cx)),
1950 "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
1951 "Results should be unchanged after search view 2nd open in a row"
1952 );
1953 assert!(
1954 search_view.query_editor.is_focused(cx),
1955 "Focus should be moved into query editor again after search view 2nd open in a row"
1956 );
1957 });
1958
1959 cx.spawn(|mut cx| async move {
1960 window.dispatch_action(search_view_id, &ToggleFocus, &mut cx);
1961 })
1962 .detach();
1963 deterministic.run_until_parked();
1964 search_view.update(cx, |search_view, cx| {
1965 assert!(
1966 search_view.results_editor.is_focused(cx),
1967 "Search view with matching query should switch focus to the results editor after the toggle focus event",
1968 );
1969 });
1970 }
1971
1972 #[gpui::test]
1973 async fn test_new_project_search_in_directory(
1974 deterministic: Arc<Deterministic>,
1975 cx: &mut TestAppContext,
1976 ) {
1977 init_test(cx);
1978
1979 let fs = FakeFs::new(cx.background());
1980 fs.insert_tree(
1981 "/dir",
1982 json!({
1983 "a": {
1984 "one.rs": "const ONE: usize = 1;",
1985 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
1986 },
1987 "b": {
1988 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
1989 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
1990 },
1991 }),
1992 )
1993 .await;
1994 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
1995 let worktree_id = project.read_with(cx, |project, cx| {
1996 project.worktrees(cx).next().unwrap().read(cx).id()
1997 });
1998 let workspace = cx
1999 .add_window(|cx| Workspace::test_new(project, cx))
2000 .root(cx);
2001
2002 let active_item = cx.read(|cx| {
2003 workspace
2004 .read(cx)
2005 .active_pane()
2006 .read(cx)
2007 .active_item()
2008 .and_then(|item| item.downcast::<ProjectSearchView>())
2009 });
2010 assert!(
2011 active_item.is_none(),
2012 "Expected no search panel to be active, but got: {active_item:?}"
2013 );
2014
2015 let one_file_entry = cx.update(|cx| {
2016 workspace
2017 .read(cx)
2018 .project()
2019 .read(cx)
2020 .entry_for_path(&(worktree_id, "a/one.rs").into(), cx)
2021 .expect("no entry for /a/one.rs file")
2022 });
2023 assert!(one_file_entry.is_file());
2024 workspace.update(cx, |workspace, cx| {
2025 ProjectSearchView::new_search_in_directory(workspace, &one_file_entry, cx)
2026 });
2027 let active_search_entry = cx.read(|cx| {
2028 workspace
2029 .read(cx)
2030 .active_pane()
2031 .read(cx)
2032 .active_item()
2033 .and_then(|item| item.downcast::<ProjectSearchView>())
2034 });
2035 assert!(
2036 active_search_entry.is_none(),
2037 "Expected no search panel to be active for file entry"
2038 );
2039
2040 let a_dir_entry = cx.update(|cx| {
2041 workspace
2042 .read(cx)
2043 .project()
2044 .read(cx)
2045 .entry_for_path(&(worktree_id, "a").into(), cx)
2046 .expect("no entry for /a/ directory")
2047 });
2048 assert!(a_dir_entry.is_dir());
2049 workspace.update(cx, |workspace, cx| {
2050 ProjectSearchView::new_search_in_directory(workspace, &a_dir_entry, cx)
2051 });
2052
2053 let Some(search_view) = cx.read(|cx| {
2054 workspace
2055 .read(cx)
2056 .active_pane()
2057 .read(cx)
2058 .active_item()
2059 .and_then(|item| item.downcast::<ProjectSearchView>())
2060 }) else {
2061 panic!("Search view expected to appear after new search in directory event trigger")
2062 };
2063 deterministic.run_until_parked();
2064 search_view.update(cx, |search_view, cx| {
2065 assert!(
2066 search_view.query_editor.is_focused(cx),
2067 "On new search in directory, focus should be moved into query editor"
2068 );
2069 search_view.excluded_files_editor.update(cx, |editor, cx| {
2070 assert!(
2071 editor.display_text(cx).is_empty(),
2072 "New search in directory should not have any excluded files"
2073 );
2074 });
2075 search_view.included_files_editor.update(cx, |editor, cx| {
2076 assert_eq!(
2077 editor.display_text(cx),
2078 a_dir_entry.path.to_str().unwrap(),
2079 "New search in directory should have included dir entry path"
2080 );
2081 });
2082 });
2083
2084 search_view.update(cx, |search_view, cx| {
2085 search_view
2086 .query_editor
2087 .update(cx, |query_editor, cx| query_editor.set_text("const", cx));
2088 search_view.search(cx);
2089 });
2090 deterministic.run_until_parked();
2091 search_view.update(cx, |search_view, cx| {
2092 assert_eq!(
2093 search_view
2094 .results_editor
2095 .update(cx, |editor, cx| editor.display_text(cx)),
2096 "\n\nconst ONE: usize = 1;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
2097 "New search in directory should have a filter that matches a certain directory"
2098 );
2099 });
2100 }
2101
2102 #[gpui::test]
2103 async fn test_search_query_history(cx: &mut TestAppContext) {
2104 init_test(cx);
2105
2106 let fs = FakeFs::new(cx.background());
2107 fs.insert_tree(
2108 "/dir",
2109 json!({
2110 "one.rs": "const ONE: usize = 1;",
2111 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2112 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2113 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2114 }),
2115 )
2116 .await;
2117 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
2118 let window = cx.add_window(|cx| Workspace::test_new(project, cx));
2119 let workspace = window.root(cx);
2120 workspace.update(cx, |workspace, cx| {
2121 ProjectSearchView::deploy(workspace, &workspace::NewSearch, cx)
2122 });
2123
2124 let search_view = cx.read(|cx| {
2125 workspace
2126 .read(cx)
2127 .active_pane()
2128 .read(cx)
2129 .active_item()
2130 .and_then(|item| item.downcast::<ProjectSearchView>())
2131 .expect("Search view expected to appear after new search event trigger")
2132 });
2133
2134 let search_bar = window.add_view(cx, |cx| {
2135 let mut search_bar = ProjectSearchBar::new();
2136 search_bar.set_active_pane_item(Some(&search_view), cx);
2137 // search_bar.show(cx);
2138 search_bar
2139 });
2140
2141 // Add 3 search items into the history + another unsubmitted one.
2142 search_view.update(cx, |search_view, cx| {
2143 search_view.search_options = SearchOptions::CASE_SENSITIVE;
2144 search_view
2145 .query_editor
2146 .update(cx, |query_editor, cx| query_editor.set_text("ONE", 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("TWO", cx));
2154 search_view.search(cx);
2155 });
2156 cx.foreground().run_until_parked();
2157 search_view.update(cx, |search_view, cx| {
2158 search_view
2159 .query_editor
2160 .update(cx, |query_editor, cx| query_editor.set_text("THREE", cx));
2161 search_view.search(cx);
2162 });
2163 cx.foreground().run_until_parked();
2164 search_view.update(cx, |search_view, cx| {
2165 search_view.query_editor.update(cx, |query_editor, cx| {
2166 query_editor.set_text("JUST_TEXT_INPUT", cx)
2167 });
2168 });
2169 cx.foreground().run_until_parked();
2170
2171 // Ensure that the latest input with search settings is active.
2172 search_view.update(cx, |search_view, cx| {
2173 assert_eq!(
2174 search_view.query_editor.read(cx).text(cx),
2175 "JUST_TEXT_INPUT"
2176 );
2177 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2178 });
2179
2180 // Next history query after the latest should set the query to the empty string.
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 search_bar.update(cx, |search_bar, cx| {
2189 search_bar.next_history_query(&NextHistoryQuery, cx);
2190 });
2191 search_view.update(cx, |search_view, cx| {
2192 assert_eq!(search_view.query_editor.read(cx).text(cx), "");
2193 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2194 });
2195
2196 // First previous query for empty current query should set the query to the latest submitted one.
2197 search_bar.update(cx, |search_bar, cx| {
2198 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2199 });
2200 search_view.update(cx, |search_view, cx| {
2201 assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
2202 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2203 });
2204
2205 // Further previous items should go over the history in reverse order.
2206 search_bar.update(cx, |search_bar, cx| {
2207 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2208 });
2209 search_view.update(cx, |search_view, cx| {
2210 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
2211 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2212 });
2213
2214 // Previous items should never go behind the first history item.
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 search_bar.update(cx, |search_bar, cx| {
2223 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2224 });
2225 search_view.update(cx, |search_view, cx| {
2226 assert_eq!(search_view.query_editor.read(cx).text(cx), "ONE");
2227 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2228 });
2229
2230 // Next items should go over the history in the original order.
2231 search_bar.update(cx, |search_bar, cx| {
2232 search_bar.next_history_query(&NextHistoryQuery, cx);
2233 });
2234 search_view.update(cx, |search_view, cx| {
2235 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
2236 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2237 });
2238
2239 search_view.update(cx, |search_view, cx| {
2240 search_view
2241 .query_editor
2242 .update(cx, |query_editor, cx| query_editor.set_text("TWO_NEW", cx));
2243 search_view.search(cx);
2244 });
2245 cx.foreground().run_until_parked();
2246 search_view.update(cx, |search_view, cx| {
2247 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO_NEW");
2248 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2249 });
2250
2251 // New search input should add another entry to history and move the selection to the end of the history.
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), "THREE");
2257 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2258 });
2259 search_bar.update(cx, |search_bar, cx| {
2260 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2261 });
2262 search_view.update(cx, |search_view, cx| {
2263 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
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), "THREE");
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), "TWO_NEW");
2278 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2279 });
2280 search_bar.update(cx, |search_bar, cx| {
2281 search_bar.next_history_query(&NextHistoryQuery, cx);
2282 });
2283 search_view.update(cx, |search_view, cx| {
2284 assert_eq!(search_view.query_editor.read(cx).text(cx), "");
2285 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2286 });
2287 }
2288
2289 pub fn init_test(cx: &mut TestAppContext) {
2290 cx.foreground().forbid_parking();
2291 let fonts = cx.font_cache();
2292 let mut theme = gpui::fonts::with_font_cache(fonts.clone(), theme::Theme::default);
2293 theme.search.match_background = Color::red();
2294
2295 cx.update(|cx| {
2296 cx.set_global(SettingsStore::test(cx));
2297 cx.set_global(ActiveSearches::default());
2298 settings::register::<SemanticIndexSettings>(cx);
2299
2300 theme::init((), cx);
2301 cx.update_global::<SettingsStore, _, _>(|store, _| {
2302 let mut settings = store.get::<ThemeSettings>(None).clone();
2303 settings.theme = Arc::new(theme);
2304 store.override_global(settings)
2305 });
2306
2307 language::init(cx);
2308 client::init_settings(cx);
2309 editor::init(cx);
2310 workspace::init_settings(cx);
2311 Project::init_settings(cx);
2312 super::init(cx);
2313 });
2314 }
2315}