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