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::{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 include_ignored = is_semantic_disabled.then(|| {
1771 render_option_button_icon(
1772 "icons/file_icons/git.svg",
1773 SearchOptions::INCLUDE_IGNORED,
1774 cx,
1775 )
1776 });
1777
1778 let search_button_for_mode = |mode, side, cx: &mut ViewContext<ProjectSearchBar>| {
1779 let is_active = if let Some(search) = self.active_project_search.as_ref() {
1780 let search = search.read(cx);
1781 search.current_mode == mode
1782 } else {
1783 false
1784 };
1785 render_search_mode_button(
1786 mode,
1787 side,
1788 is_active,
1789 move |_, this, cx| {
1790 this.activate_search_mode(mode, cx);
1791 },
1792 cx,
1793 )
1794 };
1795
1796 let search = _search.read(cx);
1797
1798 let include_container_style =
1799 if search.panels_with_errors.contains(&InputPanel::Include) {
1800 theme.search.invalid_include_exclude_editor
1801 } else {
1802 theme.search.include_exclude_editor.input.container
1803 };
1804
1805 let exclude_container_style =
1806 if search.panels_with_errors.contains(&InputPanel::Exclude) {
1807 theme.search.invalid_include_exclude_editor
1808 } else {
1809 theme.search.include_exclude_editor.input.container
1810 };
1811
1812 let matches = search.active_match_index.map(|match_ix| {
1813 Label::new(
1814 format!(
1815 "{}/{}",
1816 match_ix + 1,
1817 search.model.read(cx).match_ranges.len()
1818 ),
1819 theme.search.match_index.text.clone(),
1820 )
1821 .contained()
1822 .with_style(theme.search.match_index.container)
1823 .aligned()
1824 });
1825 let should_show_replace_input = search.replace_enabled;
1826 let replacement = should_show_replace_input.then(|| {
1827 Flex::row()
1828 .with_child(
1829 Svg::for_style(theme.search.replace_icon.clone().icon)
1830 .contained()
1831 .with_style(theme.search.replace_icon.clone().container),
1832 )
1833 .with_child(ChildView::new(&search.replacement_editor, cx).flex(1., true))
1834 .align_children_center()
1835 .flex(1., true)
1836 .contained()
1837 .with_style(query_container_style)
1838 .constrained()
1839 .with_min_width(theme.search.editor.min_width)
1840 .with_max_width(theme.search.editor.max_width)
1841 .with_height(theme.search.search_bar_row_height)
1842 .flex(1., false)
1843 });
1844 let replace_all = should_show_replace_input.then(|| {
1845 super::replace_action(
1846 ReplaceAll,
1847 "Replace all",
1848 "icons/replace_all.svg",
1849 theme.tooltip.clone(),
1850 theme.search.action_button.clone(),
1851 )
1852 });
1853 let replace_next = should_show_replace_input.then(|| {
1854 super::replace_action(
1855 ReplaceNext,
1856 "Replace next",
1857 "icons/replace_next.svg",
1858 theme.tooltip.clone(),
1859 theme.search.action_button.clone(),
1860 )
1861 });
1862 let query_column = Flex::column()
1863 .with_spacing(theme.search.search_row_spacing)
1864 .with_child(
1865 Flex::row()
1866 .with_child(
1867 Svg::for_style(icon_style.icon)
1868 .contained()
1869 .with_style(icon_style.container),
1870 )
1871 .with_child(ChildView::new(&search.query_editor, cx).flex(1., true))
1872 .with_child(
1873 Flex::row()
1874 .with_child(filter_button)
1875 .with_children(case_sensitive)
1876 .with_children(whole_word)
1877 .flex(1., false)
1878 .constrained()
1879 .contained(),
1880 )
1881 .align_children_center()
1882 .contained()
1883 .with_style(query_container_style)
1884 .constrained()
1885 .with_min_width(theme.search.editor.min_width)
1886 .with_max_width(theme.search.editor.max_width)
1887 .with_height(theme.search.search_bar_row_height)
1888 .flex(1., false),
1889 )
1890 .with_children(search.filters_enabled.then(|| {
1891 Flex::row()
1892 .with_child(
1893 Flex::row()
1894 .with_child(
1895 ChildView::new(&search.included_files_editor, cx)
1896 .contained()
1897 .constrained()
1898 .with_height(theme.search.search_bar_row_height)
1899 .flex(1., true),
1900 )
1901 .with_children(include_ignored)
1902 .contained()
1903 .with_style(include_container_style)
1904 .constrained()
1905 .with_height(theme.search.search_bar_row_height)
1906 .flex(1., true),
1907 )
1908 .with_child(
1909 ChildView::new(&search.excluded_files_editor, cx)
1910 .contained()
1911 .with_style(exclude_container_style)
1912 .constrained()
1913 .with_height(theme.search.search_bar_row_height)
1914 .flex(1., true),
1915 )
1916 .constrained()
1917 .with_min_width(theme.search.editor.min_width)
1918 .with_max_width(theme.search.editor.max_width)
1919 .flex(1., false)
1920 }))
1921 .flex(1., false);
1922 let switches_column = Flex::row()
1923 .align_children_center()
1924 .with_child(super::toggle_replace_button(
1925 search.replace_enabled,
1926 theme.tooltip.clone(),
1927 theme.search.option_button_component.clone(),
1928 ))
1929 .constrained()
1930 .with_height(theme.search.search_bar_row_height)
1931 .contained()
1932 .with_style(theme.search.option_button_group);
1933 let mode_column =
1934 Flex::row()
1935 .with_child(search_button_for_mode(
1936 SearchMode::Text,
1937 Some(Side::Left),
1938 cx,
1939 ))
1940 .with_child(search_button_for_mode(
1941 SearchMode::Regex,
1942 if is_semantic_available {
1943 None
1944 } else {
1945 Some(Side::Right)
1946 },
1947 cx,
1948 ))
1949 .with_children(is_semantic_available.then(|| {
1950 search_button_for_mode(SearchMode::Semantic, Some(Side::Right), cx)
1951 }))
1952 .contained()
1953 .with_style(theme.search.modes_container);
1954
1955 let nav_button_for_direction = |label, direction, cx: &mut ViewContext<Self>| {
1956 render_nav_button(
1957 label,
1958 direction,
1959 is_active,
1960 move |_, this, cx| {
1961 if let Some(search) = this.active_project_search.as_ref() {
1962 search.update(cx, |search, cx| search.select_match(direction, cx));
1963 }
1964 },
1965 cx,
1966 )
1967 };
1968
1969 let nav_column = Flex::row()
1970 .with_children(replace_next)
1971 .with_children(replace_all)
1972 .with_child(Flex::row().with_children(matches))
1973 .with_child(nav_button_for_direction("<", Direction::Prev, cx))
1974 .with_child(nav_button_for_direction(">", Direction::Next, cx))
1975 .constrained()
1976 .with_height(theme.search.search_bar_row_height)
1977 .flex_float();
1978
1979 Flex::row()
1980 .with_child(query_column)
1981 .with_child(mode_column)
1982 .with_child(switches_column)
1983 .with_children(replacement)
1984 .with_child(nav_column)
1985 .contained()
1986 .with_style(theme.search.container)
1987 .into_any_named("project search")
1988 } else {
1989 Empty::new().into_any()
1990 }
1991 }
1992}
1993
1994impl ToolbarItemView for ProjectSearchBar {
1995 fn set_active_pane_item(
1996 &mut self,
1997 active_pane_item: Option<&dyn ItemHandle>,
1998 cx: &mut ViewContext<Self>,
1999 ) -> ToolbarItemLocation {
2000 cx.notify();
2001 self.subscription = None;
2002 self.active_project_search = None;
2003 if let Some(search) = active_pane_item.and_then(|i| i.downcast::<ProjectSearchView>()) {
2004 search.update(cx, |search, cx| {
2005 if search.current_mode == SearchMode::Semantic {
2006 search.index_project(cx);
2007 }
2008 });
2009
2010 self.subscription = Some(cx.observe(&search, |_, _, cx| cx.notify()));
2011 self.active_project_search = Some(search);
2012 ToolbarItemLocation::PrimaryLeft {
2013 flex: Some((1., true)),
2014 }
2015 } else {
2016 ToolbarItemLocation::Hidden
2017 }
2018 }
2019
2020 fn row_count(&self, cx: &ViewContext<Self>) -> usize {
2021 if let Some(search) = self.active_project_search.as_ref() {
2022 if search.read(cx).filters_enabled {
2023 return 2;
2024 }
2025 }
2026 1
2027 }
2028}
2029
2030#[cfg(test)]
2031pub mod tests {
2032 use super::*;
2033 use editor::DisplayPoint;
2034 use gpui::{color::Color, executor::Deterministic, TestAppContext};
2035 use project::FakeFs;
2036 use semantic_index::semantic_index_settings::SemanticIndexSettings;
2037 use serde_json::json;
2038 use settings::SettingsStore;
2039 use std::sync::Arc;
2040 use theme::ThemeSettings;
2041
2042 #[gpui::test]
2043 async fn test_project_search(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
2044 init_test(cx);
2045
2046 let fs = FakeFs::new(cx.background());
2047 fs.insert_tree(
2048 "/dir",
2049 json!({
2050 "one.rs": "const ONE: usize = 1;",
2051 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2052 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2053 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2054 }),
2055 )
2056 .await;
2057 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
2058 let search = cx.add_model(|cx| ProjectSearch::new(project, cx));
2059 let search_view = cx
2060 .add_window(|cx| ProjectSearchView::new(search.clone(), cx, None))
2061 .root(cx);
2062
2063 search_view.update(cx, |search_view, cx| {
2064 search_view
2065 .query_editor
2066 .update(cx, |query_editor, cx| query_editor.set_text("TWO", cx));
2067 search_view.search(cx);
2068 });
2069 deterministic.run_until_parked();
2070 search_view.update(cx, |search_view, cx| {
2071 assert_eq!(
2072 search_view
2073 .results_editor
2074 .update(cx, |editor, cx| editor.display_text(cx)),
2075 "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;"
2076 );
2077 assert_eq!(
2078 search_view
2079 .results_editor
2080 .update(cx, |editor, cx| editor.all_text_background_highlights(cx)),
2081 &[
2082 (
2083 DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35),
2084 Color::red()
2085 ),
2086 (
2087 DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40),
2088 Color::red()
2089 ),
2090 (
2091 DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9),
2092 Color::red()
2093 )
2094 ]
2095 );
2096 assert_eq!(search_view.active_match_index, Some(0));
2097 assert_eq!(
2098 search_view
2099 .results_editor
2100 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2101 [DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35)]
2102 );
2103
2104 search_view.select_match(Direction::Next, cx);
2105 });
2106
2107 search_view.update(cx, |search_view, cx| {
2108 assert_eq!(search_view.active_match_index, Some(1));
2109 assert_eq!(
2110 search_view
2111 .results_editor
2112 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2113 [DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40)]
2114 );
2115 search_view.select_match(Direction::Next, cx);
2116 });
2117
2118 search_view.update(cx, |search_view, cx| {
2119 assert_eq!(search_view.active_match_index, Some(2));
2120 assert_eq!(
2121 search_view
2122 .results_editor
2123 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2124 [DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9)]
2125 );
2126 search_view.select_match(Direction::Next, cx);
2127 });
2128
2129 search_view.update(cx, |search_view, cx| {
2130 assert_eq!(search_view.active_match_index, Some(0));
2131 assert_eq!(
2132 search_view
2133 .results_editor
2134 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2135 [DisplayPoint::new(2, 32)..DisplayPoint::new(2, 35)]
2136 );
2137 search_view.select_match(Direction::Prev, cx);
2138 });
2139
2140 search_view.update(cx, |search_view, cx| {
2141 assert_eq!(search_view.active_match_index, Some(2));
2142 assert_eq!(
2143 search_view
2144 .results_editor
2145 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2146 [DisplayPoint::new(5, 6)..DisplayPoint::new(5, 9)]
2147 );
2148 search_view.select_match(Direction::Prev, cx);
2149 });
2150
2151 search_view.update(cx, |search_view, cx| {
2152 assert_eq!(search_view.active_match_index, Some(1));
2153 assert_eq!(
2154 search_view
2155 .results_editor
2156 .update(cx, |editor, cx| editor.selections.display_ranges(cx)),
2157 [DisplayPoint::new(2, 37)..DisplayPoint::new(2, 40)]
2158 );
2159 });
2160 }
2161
2162 #[gpui::test]
2163 async fn test_project_search_focus(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
2164 init_test(cx);
2165
2166 let fs = FakeFs::new(cx.background());
2167 fs.insert_tree(
2168 "/dir",
2169 json!({
2170 "one.rs": "const ONE: usize = 1;",
2171 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2172 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2173 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2174 }),
2175 )
2176 .await;
2177 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
2178 let window = cx.add_window(|cx| Workspace::test_new(project, cx));
2179 let workspace = window.root(cx);
2180
2181 let active_item = cx.read(|cx| {
2182 workspace
2183 .read(cx)
2184 .active_pane()
2185 .read(cx)
2186 .active_item()
2187 .and_then(|item| item.downcast::<ProjectSearchView>())
2188 });
2189 assert!(
2190 active_item.is_none(),
2191 "Expected no search panel to be active, but got: {active_item:?}"
2192 );
2193
2194 workspace.update(cx, |workspace, cx| {
2195 ProjectSearchView::deploy(workspace, &workspace::NewSearch, cx)
2196 });
2197
2198 let Some(search_view) = cx.read(|cx| {
2199 workspace
2200 .read(cx)
2201 .active_pane()
2202 .read(cx)
2203 .active_item()
2204 .and_then(|item| item.downcast::<ProjectSearchView>())
2205 }) else {
2206 panic!("Search view expected to appear after new search event trigger")
2207 };
2208 let search_view_id = search_view.id();
2209
2210 cx.spawn(|mut cx| async move {
2211 window.dispatch_action(search_view_id, &ToggleFocus, &mut cx);
2212 })
2213 .detach();
2214 deterministic.run_until_parked();
2215 search_view.update(cx, |search_view, cx| {
2216 assert!(
2217 search_view.query_editor.is_focused(cx),
2218 "Empty search view should be focused after the toggle focus event: no results panel to focus on",
2219 );
2220 });
2221
2222 search_view.update(cx, |search_view, cx| {
2223 let query_editor = &search_view.query_editor;
2224 assert!(
2225 query_editor.is_focused(cx),
2226 "Search view should be focused after the new search view is activated",
2227 );
2228 let query_text = query_editor.read(cx).text(cx);
2229 assert!(
2230 query_text.is_empty(),
2231 "New search query should be empty but got '{query_text}'",
2232 );
2233 let results_text = search_view
2234 .results_editor
2235 .update(cx, |editor, cx| editor.display_text(cx));
2236 assert!(
2237 results_text.is_empty(),
2238 "Empty search view should have no results but got '{results_text}'"
2239 );
2240 });
2241
2242 search_view.update(cx, |search_view, cx| {
2243 search_view.query_editor.update(cx, |query_editor, cx| {
2244 query_editor.set_text("sOMETHINGtHATsURELYdOESnOTeXIST", cx)
2245 });
2246 search_view.search(cx);
2247 });
2248 deterministic.run_until_parked();
2249 search_view.update(cx, |search_view, cx| {
2250 let results_text = search_view
2251 .results_editor
2252 .update(cx, |editor, cx| editor.display_text(cx));
2253 assert!(
2254 results_text.is_empty(),
2255 "Search view for mismatching query should have no results but got '{results_text}'"
2256 );
2257 assert!(
2258 search_view.query_editor.is_focused(cx),
2259 "Search view should be focused after mismatching query had been used in search",
2260 );
2261 });
2262 cx.spawn(
2263 |mut cx| async move { window.dispatch_action(search_view_id, &ToggleFocus, &mut cx) },
2264 )
2265 .detach();
2266 deterministic.run_until_parked();
2267 search_view.update(cx, |search_view, cx| {
2268 assert!(
2269 search_view.query_editor.is_focused(cx),
2270 "Search view with mismatching query should be focused after the toggle focus event: still no results panel to focus on",
2271 );
2272 });
2273
2274 search_view.update(cx, |search_view, cx| {
2275 search_view
2276 .query_editor
2277 .update(cx, |query_editor, cx| query_editor.set_text("TWO", cx));
2278 search_view.search(cx);
2279 });
2280 deterministic.run_until_parked();
2281 search_view.update(cx, |search_view, cx| {
2282 assert_eq!(
2283 search_view
2284 .results_editor
2285 .update(cx, |editor, cx| editor.display_text(cx)),
2286 "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
2287 "Search view results should match the query"
2288 );
2289 assert!(
2290 search_view.results_editor.is_focused(cx),
2291 "Search view with mismatching query should be focused after search results are available",
2292 );
2293 });
2294 cx.spawn(|mut cx| async move {
2295 window.dispatch_action(search_view_id, &ToggleFocus, &mut cx);
2296 })
2297 .detach();
2298 deterministic.run_until_parked();
2299 search_view.update(cx, |search_view, cx| {
2300 assert!(
2301 search_view.results_editor.is_focused(cx),
2302 "Search view with matching query should still have its results editor focused after the toggle focus event",
2303 );
2304 });
2305
2306 workspace.update(cx, |workspace, cx| {
2307 ProjectSearchView::deploy(workspace, &workspace::NewSearch, cx)
2308 });
2309 search_view.update(cx, |search_view, cx| {
2310 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");
2311 assert_eq!(
2312 search_view
2313 .results_editor
2314 .update(cx, |editor, cx| editor.display_text(cx)),
2315 "\n\nconst THREE: usize = one::ONE + two::TWO;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
2316 "Results should be unchanged after search view 2nd open in a row"
2317 );
2318 assert!(
2319 search_view.query_editor.is_focused(cx),
2320 "Focus should be moved into query editor again after search view 2nd open in a row"
2321 );
2322 });
2323
2324 cx.spawn(|mut cx| async move {
2325 window.dispatch_action(search_view_id, &ToggleFocus, &mut cx);
2326 })
2327 .detach();
2328 deterministic.run_until_parked();
2329 search_view.update(cx, |search_view, cx| {
2330 assert!(
2331 search_view.results_editor.is_focused(cx),
2332 "Search view with matching query should switch focus to the results editor after the toggle focus event",
2333 );
2334 });
2335 }
2336
2337 #[gpui::test]
2338 async fn test_new_project_search_in_directory(
2339 deterministic: Arc<Deterministic>,
2340 cx: &mut TestAppContext,
2341 ) {
2342 init_test(cx);
2343
2344 let fs = FakeFs::new(cx.background());
2345 fs.insert_tree(
2346 "/dir",
2347 json!({
2348 "a": {
2349 "one.rs": "const ONE: usize = 1;",
2350 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2351 },
2352 "b": {
2353 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2354 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2355 },
2356 }),
2357 )
2358 .await;
2359 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
2360 let worktree_id = project.read_with(cx, |project, cx| {
2361 project.worktrees(cx).next().unwrap().read(cx).id()
2362 });
2363 let workspace = cx
2364 .add_window(|cx| Workspace::test_new(project, cx))
2365 .root(cx);
2366
2367 let active_item = cx.read(|cx| {
2368 workspace
2369 .read(cx)
2370 .active_pane()
2371 .read(cx)
2372 .active_item()
2373 .and_then(|item| item.downcast::<ProjectSearchView>())
2374 });
2375 assert!(
2376 active_item.is_none(),
2377 "Expected no search panel to be active, but got: {active_item:?}"
2378 );
2379
2380 let one_file_entry = cx.update(|cx| {
2381 workspace
2382 .read(cx)
2383 .project()
2384 .read(cx)
2385 .entry_for_path(&(worktree_id, "a/one.rs").into(), cx)
2386 .expect("no entry for /a/one.rs file")
2387 });
2388 assert!(one_file_entry.is_file());
2389 workspace.update(cx, |workspace, cx| {
2390 ProjectSearchView::new_search_in_directory(workspace, &one_file_entry, cx)
2391 });
2392 let active_search_entry = cx.read(|cx| {
2393 workspace
2394 .read(cx)
2395 .active_pane()
2396 .read(cx)
2397 .active_item()
2398 .and_then(|item| item.downcast::<ProjectSearchView>())
2399 });
2400 assert!(
2401 active_search_entry.is_none(),
2402 "Expected no search panel to be active for file entry"
2403 );
2404
2405 let a_dir_entry = cx.update(|cx| {
2406 workspace
2407 .read(cx)
2408 .project()
2409 .read(cx)
2410 .entry_for_path(&(worktree_id, "a").into(), cx)
2411 .expect("no entry for /a/ directory")
2412 });
2413 assert!(a_dir_entry.is_dir());
2414 workspace.update(cx, |workspace, cx| {
2415 ProjectSearchView::new_search_in_directory(workspace, &a_dir_entry, cx)
2416 });
2417
2418 let Some(search_view) = cx.read(|cx| {
2419 workspace
2420 .read(cx)
2421 .active_pane()
2422 .read(cx)
2423 .active_item()
2424 .and_then(|item| item.downcast::<ProjectSearchView>())
2425 }) else {
2426 panic!("Search view expected to appear after new search in directory event trigger")
2427 };
2428 deterministic.run_until_parked();
2429 search_view.update(cx, |search_view, cx| {
2430 assert!(
2431 search_view.query_editor.is_focused(cx),
2432 "On new search in directory, focus should be moved into query editor"
2433 );
2434 search_view.excluded_files_editor.update(cx, |editor, cx| {
2435 assert!(
2436 editor.display_text(cx).is_empty(),
2437 "New search in directory should not have any excluded files"
2438 );
2439 });
2440 search_view.included_files_editor.update(cx, |editor, cx| {
2441 assert_eq!(
2442 editor.display_text(cx),
2443 a_dir_entry.path.to_str().unwrap(),
2444 "New search in directory should have included dir entry path"
2445 );
2446 });
2447 });
2448
2449 search_view.update(cx, |search_view, cx| {
2450 search_view
2451 .query_editor
2452 .update(cx, |query_editor, cx| query_editor.set_text("const", cx));
2453 search_view.search(cx);
2454 });
2455 deterministic.run_until_parked();
2456 search_view.update(cx, |search_view, cx| {
2457 assert_eq!(
2458 search_view
2459 .results_editor
2460 .update(cx, |editor, cx| editor.display_text(cx)),
2461 "\n\nconst ONE: usize = 1;\n\n\nconst TWO: usize = one::ONE + one::ONE;",
2462 "New search in directory should have a filter that matches a certain directory"
2463 );
2464 });
2465 }
2466
2467 #[gpui::test]
2468 async fn test_search_query_history(cx: &mut TestAppContext) {
2469 init_test(cx);
2470
2471 let fs = FakeFs::new(cx.background());
2472 fs.insert_tree(
2473 "/dir",
2474 json!({
2475 "one.rs": "const ONE: usize = 1;",
2476 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2477 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
2478 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
2479 }),
2480 )
2481 .await;
2482 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
2483 let window = cx.add_window(|cx| Workspace::test_new(project, cx));
2484 let workspace = window.root(cx);
2485 workspace.update(cx, |workspace, cx| {
2486 ProjectSearchView::deploy(workspace, &workspace::NewSearch, cx)
2487 });
2488
2489 let search_view = cx.read(|cx| {
2490 workspace
2491 .read(cx)
2492 .active_pane()
2493 .read(cx)
2494 .active_item()
2495 .and_then(|item| item.downcast::<ProjectSearchView>())
2496 .expect("Search view expected to appear after new search event trigger")
2497 });
2498
2499 let search_bar = window.add_view(cx, |cx| {
2500 let mut search_bar = ProjectSearchBar::new();
2501 search_bar.set_active_pane_item(Some(&search_view), cx);
2502 // search_bar.show(cx);
2503 search_bar
2504 });
2505
2506 // Add 3 search items into the history + another unsubmitted one.
2507 search_view.update(cx, |search_view, cx| {
2508 search_view.search_options = SearchOptions::CASE_SENSITIVE;
2509 search_view
2510 .query_editor
2511 .update(cx, |query_editor, cx| query_editor.set_text("ONE", cx));
2512 search_view.search(cx);
2513 });
2514 cx.foreground().run_until_parked();
2515 search_view.update(cx, |search_view, cx| {
2516 search_view
2517 .query_editor
2518 .update(cx, |query_editor, cx| query_editor.set_text("TWO", cx));
2519 search_view.search(cx);
2520 });
2521 cx.foreground().run_until_parked();
2522 search_view.update(cx, |search_view, cx| {
2523 search_view
2524 .query_editor
2525 .update(cx, |query_editor, cx| query_editor.set_text("THREE", cx));
2526 search_view.search(cx);
2527 });
2528 cx.foreground().run_until_parked();
2529 search_view.update(cx, |search_view, cx| {
2530 search_view.query_editor.update(cx, |query_editor, cx| {
2531 query_editor.set_text("JUST_TEXT_INPUT", cx)
2532 });
2533 });
2534 cx.foreground().run_until_parked();
2535
2536 // Ensure that the latest input with search settings is active.
2537 search_view.update(cx, |search_view, cx| {
2538 assert_eq!(
2539 search_view.query_editor.read(cx).text(cx),
2540 "JUST_TEXT_INPUT"
2541 );
2542 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2543 });
2544
2545 // Next history query after the latest should set the query to the empty string.
2546 search_bar.update(cx, |search_bar, cx| {
2547 search_bar.next_history_query(&NextHistoryQuery, cx);
2548 });
2549 search_view.update(cx, |search_view, cx| {
2550 assert_eq!(search_view.query_editor.read(cx).text(cx), "");
2551 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2552 });
2553 search_bar.update(cx, |search_bar, cx| {
2554 search_bar.next_history_query(&NextHistoryQuery, cx);
2555 });
2556 search_view.update(cx, |search_view, cx| {
2557 assert_eq!(search_view.query_editor.read(cx).text(cx), "");
2558 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2559 });
2560
2561 // First previous query for empty current query should set the query to the latest submitted one.
2562 search_bar.update(cx, |search_bar, cx| {
2563 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2564 });
2565 search_view.update(cx, |search_view, cx| {
2566 assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
2567 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2568 });
2569
2570 // Further previous items should go over the history in reverse order.
2571 search_bar.update(cx, |search_bar, cx| {
2572 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2573 });
2574 search_view.update(cx, |search_view, cx| {
2575 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
2576 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2577 });
2578
2579 // Previous items should never go behind the first history item.
2580 search_bar.update(cx, |search_bar, cx| {
2581 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2582 });
2583 search_view.update(cx, |search_view, cx| {
2584 assert_eq!(search_view.query_editor.read(cx).text(cx), "ONE");
2585 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2586 });
2587 search_bar.update(cx, |search_bar, cx| {
2588 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2589 });
2590 search_view.update(cx, |search_view, cx| {
2591 assert_eq!(search_view.query_editor.read(cx).text(cx), "ONE");
2592 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2593 });
2594
2595 // Next items should go over the history in the original order.
2596 search_bar.update(cx, |search_bar, cx| {
2597 search_bar.next_history_query(&NextHistoryQuery, cx);
2598 });
2599 search_view.update(cx, |search_view, cx| {
2600 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
2601 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2602 });
2603
2604 search_view.update(cx, |search_view, cx| {
2605 search_view
2606 .query_editor
2607 .update(cx, |query_editor, cx| query_editor.set_text("TWO_NEW", cx));
2608 search_view.search(cx);
2609 });
2610 cx.foreground().run_until_parked();
2611 search_view.update(cx, |search_view, cx| {
2612 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO_NEW");
2613 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2614 });
2615
2616 // New search input should add another entry to history and move the selection to the end of the history.
2617 search_bar.update(cx, |search_bar, cx| {
2618 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2619 });
2620 search_view.update(cx, |search_view, cx| {
2621 assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
2622 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2623 });
2624 search_bar.update(cx, |search_bar, cx| {
2625 search_bar.previous_history_query(&PreviousHistoryQuery, cx);
2626 });
2627 search_view.update(cx, |search_view, cx| {
2628 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO");
2629 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2630 });
2631 search_bar.update(cx, |search_bar, cx| {
2632 search_bar.next_history_query(&NextHistoryQuery, cx);
2633 });
2634 search_view.update(cx, |search_view, cx| {
2635 assert_eq!(search_view.query_editor.read(cx).text(cx), "THREE");
2636 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2637 });
2638 search_bar.update(cx, |search_bar, cx| {
2639 search_bar.next_history_query(&NextHistoryQuery, cx);
2640 });
2641 search_view.update(cx, |search_view, cx| {
2642 assert_eq!(search_view.query_editor.read(cx).text(cx), "TWO_NEW");
2643 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2644 });
2645 search_bar.update(cx, |search_bar, cx| {
2646 search_bar.next_history_query(&NextHistoryQuery, cx);
2647 });
2648 search_view.update(cx, |search_view, cx| {
2649 assert_eq!(search_view.query_editor.read(cx).text(cx), "");
2650 assert_eq!(search_view.search_options, SearchOptions::CASE_SENSITIVE);
2651 });
2652 }
2653
2654 pub fn init_test(cx: &mut TestAppContext) {
2655 cx.foreground().forbid_parking();
2656 let fonts = cx.font_cache();
2657 let mut theme = gpui::fonts::with_font_cache(fonts.clone(), theme::Theme::default);
2658 theme.search.match_background = Color::red();
2659
2660 cx.update(|cx| {
2661 cx.set_global(SettingsStore::test(cx));
2662 cx.set_global(ActiveSearches::default());
2663 settings::register::<SemanticIndexSettings>(cx);
2664
2665 theme::init((), cx);
2666 cx.update_global::<SettingsStore, _, _>(|store, _| {
2667 let mut settings = store.get::<ThemeSettings>(None).clone();
2668 settings.theme = Arc::new(theme);
2669 store.override_global(settings)
2670 });
2671
2672 language::init(cx);
2673 client::init_settings(cx);
2674 editor::init(cx);
2675 workspace::init_settings(cx);
2676 Project::init_settings(cx);
2677 super::init(cx);
2678 });
2679 }
2680}