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