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