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