Rename "find" to "search"

Search is both a verb and a noun, which makes it more natural to use in situations where we need to name a thing rather than a process.
This commit is contained in:
Nathan Sobo
2022-02-27 08:15:38 -07:00
parent dd6f8d20a3
commit ec317159d7
9 changed files with 197 additions and 197 deletions
+860
View File
@@ -0,0 +1,860 @@
use crate::SearchOption;
use collections::HashMap;
use editor::{display_map::ToDisplayPoint, Anchor, Autoscroll, Bias, Editor};
use gpui::{
action, elements::*, keymap::Binding, platform::CursorStyle, Entity, MutableAppContext,
RenderContext, Subscription, Task, View, ViewContext, ViewHandle, WeakViewHandle,
};
use language::AnchorRangeExt;
use postage::watch;
use project::search::SearchQuery;
use std::{
cmp::{self, Ordering},
ops::Range,
};
use workspace::{ItemViewHandle, Pane, Settings, Toolbar, Workspace};
action!(Deploy, bool);
action!(Dismiss);
action!(FocusEditor);
action!(ToggleSearchOption, SearchOption);
action!(GoToMatch, Direction);
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Direction {
Prev,
Next,
}
pub fn init(cx: &mut MutableAppContext) {
cx.add_bindings([
Binding::new("cmd-f", Deploy(true), Some("Editor && mode == full")),
Binding::new("cmd-e", Deploy(false), Some("Editor && mode == full")),
Binding::new("escape", Dismiss, Some("SearchBar")),
Binding::new("cmd-f", FocusEditor, Some("SearchBar")),
Binding::new("enter", GoToMatch(Direction::Next), Some("SearchBar")),
Binding::new("shift-enter", GoToMatch(Direction::Prev), Some("SearchBar")),
Binding::new("cmd-g", GoToMatch(Direction::Next), Some("Pane")),
Binding::new("cmd-shift-G", GoToMatch(Direction::Prev), Some("Pane")),
]);
cx.add_action(SearchBar::deploy);
cx.add_action(SearchBar::dismiss);
cx.add_action(SearchBar::focus_editor);
cx.add_action(SearchBar::toggle_search_option);
cx.add_action(SearchBar::go_to_match);
cx.add_action(SearchBar::go_to_match_on_pane);
}
struct SearchBar {
settings: watch::Receiver<Settings>,
query_editor: ViewHandle<Editor>,
active_editor: Option<ViewHandle<Editor>>,
active_match_index: Option<usize>,
active_editor_subscription: Option<Subscription>,
editors_with_matches: HashMap<WeakViewHandle<Editor>, Vec<Range<Anchor>>>,
pending_search: Option<Task<()>>,
case_sensitive: bool,
whole_word: bool,
regex: bool,
query_contains_error: bool,
dismissed: bool,
}
impl Entity for SearchBar {
type Event = ();
}
impl View for SearchBar {
fn ui_name() -> &'static str {
"SearchBar"
}
fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
cx.focus(&self.query_editor);
}
fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
let theme = &self.settings.borrow().theme;
let editor_container = if self.query_contains_error {
theme.search.invalid_editor
} else {
theme.search.editor.input.container
};
Flex::row()
.with_child(
ChildView::new(&self.query_editor)
.contained()
.with_style(editor_container)
.aligned()
.constrained()
.with_max_width(theme.search.editor.max_width)
.boxed(),
)
.with_child(
Flex::row()
.with_child(self.render_search_option("Case", SearchOption::CaseSensitive, cx))
.with_child(self.render_search_option("Word", SearchOption::WholeWord, cx))
.with_child(self.render_search_option("Regex", SearchOption::Regex, cx))
.contained()
.with_style(theme.search.option_button_group)
.aligned()
.boxed(),
)
.with_child(
Flex::row()
.with_child(self.render_nav_button("<", Direction::Prev, cx))
.with_child(self.render_nav_button(">", Direction::Next, cx))
.aligned()
.boxed(),
)
.with_children(self.active_editor.as_ref().and_then(|editor| {
let matches = self.editors_with_matches.get(&editor.downgrade())?;
let message = if let Some(match_ix) = self.active_match_index {
format!("{}/{}", match_ix + 1, matches.len())
} else {
"No matches".to_string()
};
Some(
Label::new(message, theme.search.match_index.text.clone())
.contained()
.with_style(theme.search.match_index.container)
.aligned()
.boxed(),
)
}))
.contained()
.with_style(theme.search.container)
.constrained()
.with_height(theme.workspace.toolbar.height)
.named("search bar")
}
}
impl Toolbar for SearchBar {
fn active_item_changed(
&mut self,
item: Option<Box<dyn ItemViewHandle>>,
cx: &mut ViewContext<Self>,
) -> bool {
self.active_editor_subscription.take();
self.active_editor.take();
self.pending_search.take();
if let Some(editor) = item.and_then(|item| item.act_as::<Editor>(cx)) {
if editor.read(cx).searchable() {
self.active_editor_subscription =
Some(cx.subscribe(&editor, Self::on_active_editor_event));
self.active_editor = Some(editor);
self.update_matches(false, cx);
return true;
}
}
false
}
fn on_dismiss(&mut self, cx: &mut ViewContext<Self>) {
self.dismissed = true;
for (editor, _) in &self.editors_with_matches {
if let Some(editor) = editor.upgrade(cx) {
editor.update(cx, |editor, cx| editor.clear_highlighted_ranges::<Self>(cx));
}
}
}
}
impl SearchBar {
fn new(settings: watch::Receiver<Settings>, cx: &mut ViewContext<Self>) -> Self {
let query_editor = cx.add_view(|cx| {
Editor::auto_height(
2,
settings.clone(),
Some(|theme| theme.search.editor.input.clone()),
cx,
)
});
cx.subscribe(&query_editor, Self::on_query_editor_event)
.detach();
Self {
query_editor,
active_editor: None,
active_editor_subscription: None,
active_match_index: None,
editors_with_matches: Default::default(),
case_sensitive: false,
whole_word: false,
regex: false,
settings,
pending_search: None,
query_contains_error: false,
dismissed: false,
}
}
fn set_query(&mut self, query: &str, cx: &mut ViewContext<Self>) {
self.query_editor.update(cx, |query_editor, cx| {
query_editor.buffer().update(cx, |query_buffer, cx| {
let len = query_buffer.read(cx).len();
query_buffer.edit([0..len], query, cx);
});
});
}
fn render_search_option(
&self,
icon: &str,
search_option: SearchOption,
cx: &mut RenderContext<Self>,
) -> ElementBox {
let theme = &self.settings.borrow().theme.search;
let is_active = self.is_search_option_enabled(search_option);
MouseEventHandler::new::<Self, _, _>(search_option as usize, cx, |state, _| {
let style = match (is_active, state.hovered) {
(false, false) => &theme.option_button,
(false, true) => &theme.hovered_option_button,
(true, false) => &theme.active_option_button,
(true, true) => &theme.active_hovered_option_button,
};
Label::new(icon.to_string(), style.text.clone())
.contained()
.with_style(style.container)
.boxed()
})
.on_click(move |cx| cx.dispatch_action(ToggleSearchOption(search_option)))
.with_cursor_style(CursorStyle::PointingHand)
.boxed()
}
fn render_nav_button(
&self,
icon: &str,
direction: Direction,
cx: &mut RenderContext<Self>,
) -> ElementBox {
let theme = &self.settings.borrow().theme.search;
enum NavButton {}
MouseEventHandler::new::<NavButton, _, _>(direction as usize, cx, |state, _| {
let style = if state.hovered {
&theme.hovered_option_button
} else {
&theme.option_button
};
Label::new(icon.to_string(), style.text.clone())
.contained()
.with_style(style.container)
.boxed()
})
.on_click(move |cx| cx.dispatch_action(GoToMatch(direction)))
.with_cursor_style(CursorStyle::PointingHand)
.boxed()
}
fn deploy(workspace: &mut Workspace, Deploy(focus): &Deploy, cx: &mut ViewContext<Workspace>) {
let settings = workspace.settings();
workspace.active_pane().update(cx, |pane, cx| {
pane.show_toolbar(cx, |cx| SearchBar::new(settings, cx));
if let Some(search_bar) = pane
.active_toolbar()
.and_then(|toolbar| toolbar.downcast::<Self>())
{
search_bar.update(cx, |search_bar, _| search_bar.dismissed = false);
let editor = pane.active_item().unwrap().act_as::<Editor>(cx).unwrap();
let display_map = editor
.update(cx, |editor, cx| editor.snapshot(cx))
.display_snapshot;
let selection = editor
.read(cx)
.newest_selection::<usize>(&display_map.buffer_snapshot);
let mut text: String;
if selection.start == selection.end {
let point = selection.start.to_display_point(&display_map);
let range = editor::movement::surrounding_word(&display_map, point);
let range = range.start.to_offset(&display_map, Bias::Left)
..range.end.to_offset(&display_map, Bias::Right);
text = display_map.buffer_snapshot.text_for_range(range).collect();
if text.trim().is_empty() {
text = String::new();
}
} else {
text = display_map
.buffer_snapshot
.text_for_range(selection.start..selection.end)
.collect();
}
if !text.is_empty() {
search_bar.update(cx, |search_bar, cx| search_bar.set_query(&text, cx));
}
if *focus {
let query_editor = search_bar.read(cx).query_editor.clone();
query_editor.update(cx, |query_editor, cx| {
query_editor.select_all(&editor::SelectAll, cx);
});
cx.focus(&search_bar);
}
} else {
cx.propagate_action();
}
});
}
fn dismiss(pane: &mut Pane, _: &Dismiss, cx: &mut ViewContext<Pane>) {
if pane.toolbar::<SearchBar>().is_some() {
pane.dismiss_toolbar(cx);
}
}
fn focus_editor(&mut self, _: &FocusEditor, cx: &mut ViewContext<Self>) {
if let Some(active_editor) = self.active_editor.as_ref() {
cx.focus(active_editor);
}
}
fn is_search_option_enabled(&self, search_option: SearchOption) -> bool {
match search_option {
SearchOption::WholeWord => self.whole_word,
SearchOption::CaseSensitive => self.case_sensitive,
SearchOption::Regex => self.regex,
}
}
fn toggle_search_option(
&mut self,
ToggleSearchOption(search_option): &ToggleSearchOption,
cx: &mut ViewContext<Self>,
) {
let value = match search_option {
SearchOption::WholeWord => &mut self.whole_word,
SearchOption::CaseSensitive => &mut self.case_sensitive,
SearchOption::Regex => &mut self.regex,
};
*value = !*value;
self.update_matches(true, cx);
cx.notify();
}
fn go_to_match(&mut self, GoToMatch(direction): &GoToMatch, cx: &mut ViewContext<Self>) {
if let Some(mut index) = self.active_match_index {
if let Some(editor) = self.active_editor.as_ref() {
editor.update(cx, |editor, cx| {
let newest_selection = editor.newest_anchor_selection().clone();
if let Some(ranges) = self.editors_with_matches.get(&cx.weak_handle()) {
let position = newest_selection.head();
let buffer = editor.buffer().read(cx).read(cx);
if ranges[index].start.cmp(&position, &buffer).unwrap().is_gt() {
if *direction == Direction::Prev {
if index == 0 {
index = ranges.len() - 1;
} else {
index -= 1;
}
}
} else if ranges[index].end.cmp(&position, &buffer).unwrap().is_lt() {
if *direction == Direction::Next {
index = 0;
}
} else if *direction == Direction::Prev {
if index == 0 {
index = ranges.len() - 1;
} else {
index -= 1;
}
} else if *direction == Direction::Next {
if index == ranges.len() - 1 {
index = 0
} else {
index += 1;
}
}
let range_to_select = ranges[index].clone();
drop(buffer);
editor.select_ranges([range_to_select], Some(Autoscroll::Fit), cx);
}
});
}
}
}
fn go_to_match_on_pane(pane: &mut Pane, action: &GoToMatch, cx: &mut ViewContext<Pane>) {
if let Some(search_bar) = pane.toolbar::<SearchBar>() {
search_bar.update(cx, |search_bar, cx| search_bar.go_to_match(action, cx));
}
}
fn on_query_editor_event(
&mut self,
_: ViewHandle<Editor>,
event: &editor::Event,
cx: &mut ViewContext<Self>,
) {
match event {
editor::Event::Edited => {
self.query_contains_error = false;
self.clear_matches(cx);
self.update_matches(true, cx);
cx.notify();
}
_ => {}
}
}
fn on_active_editor_event(
&mut self,
_: ViewHandle<Editor>,
event: &editor::Event,
cx: &mut ViewContext<Self>,
) {
match event {
editor::Event::Edited => self.update_matches(false, cx),
editor::Event::SelectionsChanged => self.update_match_index(cx),
_ => {}
}
}
fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
let mut active_editor_matches = None;
for (editor, ranges) in self.editors_with_matches.drain() {
if let Some(editor) = editor.upgrade(cx) {
if Some(&editor) == self.active_editor.as_ref() {
active_editor_matches = Some((editor.downgrade(), ranges));
} else {
editor.update(cx, |editor, cx| editor.clear_highlighted_ranges::<Self>(cx));
}
}
}
self.editors_with_matches.extend(active_editor_matches);
}
fn update_matches(&mut self, select_closest_match: bool, cx: &mut ViewContext<Self>) {
let query = self.query_editor.read(cx).text(cx);
self.pending_search.take();
if let Some(editor) = self.active_editor.as_ref() {
if query.is_empty() {
self.active_match_index.take();
editor.update(cx, |editor, cx| editor.clear_highlighted_ranges::<Self>(cx));
} else {
let buffer = editor.read(cx).buffer().read(cx).snapshot(cx);
let query = if self.regex {
match SearchQuery::regex(query, self.whole_word, self.case_sensitive) {
Ok(query) => query,
Err(_) => {
self.query_contains_error = true;
cx.notify();
return;
}
}
} else {
SearchQuery::text(query, self.whole_word, self.case_sensitive)
};
let ranges = cx.background().spawn(async move {
let mut ranges = Vec::new();
if let Some((_, _, excerpt_buffer)) = buffer.as_singleton() {
ranges.extend(
query
.search(excerpt_buffer.as_rope())
.await
.into_iter()
.map(|range| {
buffer.anchor_after(range.start)
..buffer.anchor_before(range.end)
}),
);
} else {
for excerpt in buffer.excerpt_boundaries_in_range(0..buffer.len()) {
let excerpt_range = excerpt.range.to_offset(&excerpt.buffer);
let rope = excerpt.buffer.as_rope().slice(excerpt_range.clone());
ranges.extend(query.search(&rope).await.into_iter().map(|range| {
let start = excerpt
.buffer
.anchor_after(excerpt_range.start + range.start);
let end = excerpt
.buffer
.anchor_before(excerpt_range.start + range.end);
buffer.anchor_in_excerpt(excerpt.id.clone(), start)
..buffer.anchor_in_excerpt(excerpt.id.clone(), end)
}));
}
}
ranges
});
let editor = editor.downgrade();
self.pending_search = Some(cx.spawn_weak(|this, mut cx| async move {
let ranges = ranges.await;
if let Some((this, editor)) = this.upgrade(&cx).zip(editor.upgrade(&cx)) {
this.update(&mut cx, |this, cx| {
this.editors_with_matches
.insert(editor.downgrade(), ranges.clone());
this.update_match_index(cx);
if !this.dismissed {
editor.update(cx, |editor, cx| {
let theme = &this.settings.borrow().theme.search;
if select_closest_match {
if let Some(match_ix) = this.active_match_index {
editor.select_ranges(
[ranges[match_ix].clone()],
Some(Autoscroll::Fit),
cx,
);
}
}
editor.highlight_ranges::<Self>(
ranges,
theme.match_background,
cx,
);
});
}
});
}
}));
}
}
}
fn update_match_index(&mut self, cx: &mut ViewContext<Self>) {
self.active_match_index = self.active_match_index(cx);
cx.notify();
}
fn active_match_index(&mut self, cx: &mut ViewContext<Self>) -> Option<usize> {
let editor = self.active_editor.as_ref()?;
let ranges = self.editors_with_matches.get(&editor.downgrade())?;
let editor = editor.read(cx);
let position = editor.newest_anchor_selection().head();
if ranges.is_empty() {
None
} else {
let buffer = editor.buffer().read(cx).read(cx);
match ranges.binary_search_by(|probe| {
if probe.end.cmp(&position, &*buffer).unwrap().is_lt() {
Ordering::Less
} else if probe.start.cmp(&position, &*buffer).unwrap().is_gt() {
Ordering::Greater
} else {
Ordering::Equal
}
}) {
Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use editor::{DisplayPoint, Editor, MultiBuffer};
use gpui::{color::Color, TestAppContext};
use std::sync::Arc;
use unindent::Unindent as _;
#[gpui::test]
async fn test_search_simple(mut cx: TestAppContext) {
let fonts = cx.font_cache();
let mut theme = gpui::fonts::with_font_cache(fonts.clone(), || theme::Theme::default());
theme.search.match_background = Color::red();
let settings = Settings::new("Courier", &fonts, Arc::new(theme)).unwrap();
let settings = watch::channel_with(settings).1;
let buffer = cx.update(|cx| {
MultiBuffer::build_simple(
&r#"
A regular expression (shortened as regex or regexp;[1] also referred to as
rational expression[2][3]) is a sequence of characters that specifies a search
pattern in text. Usually such patterns are used by string-searching algorithms
for "find" or "find and replace" operations on strings, or for input validation.
"#
.unindent(),
cx,
)
});
let editor = cx.add_view(Default::default(), |cx| {
Editor::for_buffer(buffer.clone(), None, settings.clone(), cx)
});
let search_bar = cx.add_view(Default::default(), |cx| {
let mut search_bar = SearchBar::new(settings, cx);
search_bar.active_item_changed(Some(Box::new(editor.clone())), cx);
search_bar
});
// Search for a string that appears with different casing.
// By default, search is case-insensitive.
search_bar.update(&mut cx, |search_bar, cx| {
search_bar.set_query("us", cx);
});
editor.next_notification(&cx).await;
editor.update(&mut cx, |editor, cx| {
assert_eq!(
editor.all_highlighted_ranges(cx),
&[
(
DisplayPoint::new(2, 17)..DisplayPoint::new(2, 19),
Color::red(),
),
(
DisplayPoint::new(2, 43)..DisplayPoint::new(2, 45),
Color::red(),
),
]
);
});
// Switch to a case sensitive search.
search_bar.update(&mut cx, |search_bar, cx| {
search_bar.toggle_search_option(&ToggleSearchOption(SearchOption::CaseSensitive), cx);
});
editor.next_notification(&cx).await;
editor.update(&mut cx, |editor, cx| {
assert_eq!(
editor.all_highlighted_ranges(cx),
&[(
DisplayPoint::new(2, 43)..DisplayPoint::new(2, 45),
Color::red(),
)]
);
});
// Search for a string that appears both as a whole word and
// within other words. By default, all results are found.
search_bar.update(&mut cx, |search_bar, cx| {
search_bar.set_query("or", cx);
});
editor.next_notification(&cx).await;
editor.update(&mut cx, |editor, cx| {
assert_eq!(
editor.all_highlighted_ranges(cx),
&[
(
DisplayPoint::new(0, 24)..DisplayPoint::new(0, 26),
Color::red(),
),
(
DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43),
Color::red(),
),
(
DisplayPoint::new(2, 71)..DisplayPoint::new(2, 73),
Color::red(),
),
(
DisplayPoint::new(3, 1)..DisplayPoint::new(3, 3),
Color::red(),
),
(
DisplayPoint::new(3, 11)..DisplayPoint::new(3, 13),
Color::red(),
),
(
DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58),
Color::red(),
),
(
DisplayPoint::new(3, 60)..DisplayPoint::new(3, 62),
Color::red(),
),
]
);
});
// Switch to a whole word search.
search_bar.update(&mut cx, |search_bar, cx| {
search_bar.toggle_search_option(&ToggleSearchOption(SearchOption::WholeWord), cx);
});
editor.next_notification(&cx).await;
editor.update(&mut cx, |editor, cx| {
assert_eq!(
editor.all_highlighted_ranges(cx),
&[
(
DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43),
Color::red(),
),
(
DisplayPoint::new(3, 11)..DisplayPoint::new(3, 13),
Color::red(),
),
(
DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58),
Color::red(),
),
]
);
});
editor.update(&mut cx, |editor, cx| {
editor.select_display_ranges(&[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)], cx);
});
search_bar.update(&mut cx, |search_bar, cx| {
assert_eq!(search_bar.active_match_index, Some(0));
search_bar.go_to_match(&GoToMatch(Direction::Next), cx);
assert_eq!(
editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
[DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43)]
);
});
search_bar.read_with(&cx, |search_bar, _| {
assert_eq!(search_bar.active_match_index, Some(0));
});
search_bar.update(&mut cx, |search_bar, cx| {
search_bar.go_to_match(&GoToMatch(Direction::Next), cx);
assert_eq!(
editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
[DisplayPoint::new(3, 11)..DisplayPoint::new(3, 13)]
);
});
search_bar.read_with(&cx, |search_bar, _| {
assert_eq!(search_bar.active_match_index, Some(1));
});
search_bar.update(&mut cx, |search_bar, cx| {
search_bar.go_to_match(&GoToMatch(Direction::Next), cx);
assert_eq!(
editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
[DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58)]
);
});
search_bar.read_with(&cx, |search_bar, _| {
assert_eq!(search_bar.active_match_index, Some(2));
});
search_bar.update(&mut cx, |search_bar, cx| {
search_bar.go_to_match(&GoToMatch(Direction::Next), cx);
assert_eq!(
editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
[DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43)]
);
});
search_bar.read_with(&cx, |search_bar, _| {
assert_eq!(search_bar.active_match_index, Some(0));
});
search_bar.update(&mut cx, |search_bar, cx| {
search_bar.go_to_match(&GoToMatch(Direction::Prev), cx);
assert_eq!(
editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
[DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58)]
);
});
search_bar.read_with(&cx, |search_bar, _| {
assert_eq!(search_bar.active_match_index, Some(2));
});
search_bar.update(&mut cx, |search_bar, cx| {
search_bar.go_to_match(&GoToMatch(Direction::Prev), cx);
assert_eq!(
editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
[DisplayPoint::new(3, 11)..DisplayPoint::new(3, 13)]
);
});
search_bar.read_with(&cx, |search_bar, _| {
assert_eq!(search_bar.active_match_index, Some(1));
});
search_bar.update(&mut cx, |search_bar, cx| {
search_bar.go_to_match(&GoToMatch(Direction::Prev), cx);
assert_eq!(
editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
[DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43)]
);
});
search_bar.read_with(&cx, |search_bar, _| {
assert_eq!(search_bar.active_match_index, Some(0));
});
// Park the cursor in between matches and ensure that going to the previous match selects
// the closest match to the left.
editor.update(&mut cx, |editor, cx| {
editor.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
});
search_bar.update(&mut cx, |search_bar, cx| {
assert_eq!(search_bar.active_match_index, Some(1));
search_bar.go_to_match(&GoToMatch(Direction::Prev), cx);
assert_eq!(
editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
[DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43)]
);
});
search_bar.read_with(&cx, |search_bar, _| {
assert_eq!(search_bar.active_match_index, Some(0));
});
// Park the cursor in between matches and ensure that going to the next match selects the
// closest match to the right.
editor.update(&mut cx, |editor, cx| {
editor.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
});
search_bar.update(&mut cx, |search_bar, cx| {
assert_eq!(search_bar.active_match_index, Some(1));
search_bar.go_to_match(&GoToMatch(Direction::Next), cx);
assert_eq!(
editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
[DisplayPoint::new(3, 11)..DisplayPoint::new(3, 13)]
);
});
search_bar.read_with(&cx, |search_bar, _| {
assert_eq!(search_bar.active_match_index, Some(1));
});
// Park the cursor after the last match and ensure that going to the previous match selects
// the last match.
editor.update(&mut cx, |editor, cx| {
editor.select_display_ranges(&[DisplayPoint::new(3, 60)..DisplayPoint::new(3, 60)], cx);
});
search_bar.update(&mut cx, |search_bar, cx| {
assert_eq!(search_bar.active_match_index, Some(2));
search_bar.go_to_match(&GoToMatch(Direction::Prev), cx);
assert_eq!(
editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
[DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58)]
);
});
search_bar.read_with(&cx, |search_bar, _| {
assert_eq!(search_bar.active_match_index, Some(2));
});
// Park the cursor after the last match and ensure that going to the next match selects the
// first match.
editor.update(&mut cx, |editor, cx| {
editor.select_display_ranges(&[DisplayPoint::new(3, 60)..DisplayPoint::new(3, 60)], cx);
});
search_bar.update(&mut cx, |search_bar, cx| {
assert_eq!(search_bar.active_match_index, Some(2));
search_bar.go_to_match(&GoToMatch(Direction::Next), cx);
assert_eq!(
editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
[DisplayPoint::new(0, 41)..DisplayPoint::new(0, 43)]
);
});
search_bar.read_with(&cx, |search_bar, _| {
assert_eq!(search_bar.active_match_index, Some(0));
});
// Park the cursor before the first match and ensure that going to the previous match
// selects the last match.
editor.update(&mut cx, |editor, cx| {
editor.select_display_ranges(&[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)], cx);
});
search_bar.update(&mut cx, |search_bar, cx| {
assert_eq!(search_bar.active_match_index, Some(0));
search_bar.go_to_match(&GoToMatch(Direction::Prev), cx);
assert_eq!(
editor.update(cx, |editor, cx| editor.selected_display_ranges(cx)),
[DisplayPoint::new(3, 56)..DisplayPoint::new(3, 58)]
);
});
search_bar.read_with(&cx, |search_bar, _| {
assert_eq!(search_bar.active_match_index, Some(2));
});
}
}
+577
View File
@@ -0,0 +1,577 @@
use crate::SearchOption;
use editor::{Anchor, Autoscroll, Editor, MultiBuffer, SelectAll};
use gpui::{
action, elements::*, keymap::Binding, platform::CursorStyle, AppContext, ElementBox, Entity,
ModelContext, ModelHandle, MutableAppContext, RenderContext, Task, View, ViewContext,
ViewHandle,
};
use postage::watch;
use project::{search::SearchQuery, Project};
use std::{
any::{Any, TypeId},
ops::Range,
path::PathBuf,
};
use util::ResultExt as _;
use workspace::{Item, ItemHandle, ItemNavHistory, ItemView, Settings, Workspace};
action!(Deploy);
action!(Search);
action!(SearchInNew);
action!(ToggleSearchOption, SearchOption);
action!(ToggleFocus);
pub fn init(cx: &mut MutableAppContext) {
cx.add_bindings([
Binding::new("cmd-shift-F", ToggleFocus, Some("ProjectSearchView")),
Binding::new("cmd-f", ToggleFocus, Some("ProjectSearchView")),
Binding::new("cmd-shift-F", Deploy, Some("Workspace")),
Binding::new("enter", Search, Some("ProjectSearchView")),
Binding::new("cmd-enter", SearchInNew, Some("ProjectSearchView")),
]);
cx.add_action(ProjectSearchView::deploy);
cx.add_action(ProjectSearchView::search);
cx.add_action(ProjectSearchView::search_in_new);
cx.add_action(ProjectSearchView::toggle_search_option);
cx.add_action(ProjectSearchView::toggle_focus);
}
struct ProjectSearch {
project: ModelHandle<Project>,
excerpts: ModelHandle<MultiBuffer>,
pending_search: Option<Task<Option<()>>>,
highlighted_ranges: Vec<Range<Anchor>>,
active_query: Option<SearchQuery>,
}
struct ProjectSearchView {
model: ModelHandle<ProjectSearch>,
query_editor: ViewHandle<Editor>,
results_editor: ViewHandle<Editor>,
case_sensitive: bool,
whole_word: bool,
regex: bool,
query_contains_error: bool,
settings: watch::Receiver<Settings>,
}
impl Entity for ProjectSearch {
type Event = ();
}
impl ProjectSearch {
fn new(project: ModelHandle<Project>, cx: &mut ModelContext<Self>) -> Self {
let replica_id = project.read(cx).replica_id();
Self {
project,
excerpts: cx.add_model(|_| MultiBuffer::new(replica_id)),
pending_search: Default::default(),
highlighted_ranges: Default::default(),
active_query: None,
}
}
fn clone(&self, new_cx: &mut ModelContext<Self>) -> Self {
Self {
project: self.project.clone(),
excerpts: self
.excerpts
.update(new_cx, |excerpts, cx| cx.add_model(|cx| excerpts.clone(cx))),
pending_search: Default::default(),
highlighted_ranges: self.highlighted_ranges.clone(),
active_query: self.active_query.clone(),
}
}
fn search(&mut self, query: SearchQuery, cx: &mut ModelContext<Self>) {
let search = self
.project
.update(cx, |project, cx| project.search(query.clone(), cx));
self.active_query = Some(query);
self.highlighted_ranges.clear();
self.pending_search = Some(cx.spawn_weak(|this, mut cx| async move {
let matches = search.await.log_err()?;
if let Some(this) = this.upgrade(&cx) {
this.update(&mut cx, |this, cx| {
this.highlighted_ranges.clear();
let mut matches = matches.into_iter().collect::<Vec<_>>();
matches
.sort_by_key(|(buffer, _)| buffer.read(cx).file().map(|file| file.path()));
this.excerpts.update(cx, |excerpts, cx| {
excerpts.clear(cx);
for (buffer, buffer_matches) in matches {
let ranges_to_highlight = excerpts.push_excerpts_with_context_lines(
buffer,
buffer_matches.clone(),
1,
cx,
);
this.highlighted_ranges.extend(ranges_to_highlight);
}
});
this.pending_search.take();
cx.notify();
});
}
None
}));
cx.notify();
}
}
impl Item for ProjectSearch {
type View = ProjectSearchView;
fn build_view(
model: ModelHandle<Self>,
workspace: &Workspace,
nav_history: ItemNavHistory,
cx: &mut gpui::ViewContext<Self::View>,
) -> Self::View {
let settings = workspace.settings();
let excerpts = model.read(cx).excerpts.clone();
let mut query_text = String::new();
let mut regex = false;
let mut case_sensitive = false;
let mut whole_word = false;
if let Some(active_query) = model.read(cx).active_query.as_ref() {
query_text = active_query.as_str().to_string();
regex = active_query.is_regex();
case_sensitive = active_query.case_sensitive();
whole_word = active_query.whole_word();
}
let query_editor = cx.add_view(|cx| {
let mut editor = Editor::single_line(
settings.clone(),
Some(|theme| theme.search.editor.input.clone()),
cx,
);
editor.set_text(query_text, cx);
editor
});
let results_editor = cx.add_view(|cx| {
let mut editor = Editor::for_buffer(
excerpts,
Some(workspace.project().clone()),
settings.clone(),
cx,
);
editor.set_searchable(false);
editor.set_nav_history(Some(nav_history));
editor
});
cx.observe(&results_editor, |_, _, cx| cx.emit(ViewEvent::UpdateTab))
.detach();
cx.observe(&model, |this, _, cx| this.model_changed(true, cx))
.detach();
ProjectSearchView {
model,
query_editor,
results_editor,
case_sensitive,
whole_word,
regex,
query_contains_error: false,
settings,
}
}
fn project_path(&self) -> Option<project::ProjectPath> {
None
}
}
enum ViewEvent {
UpdateTab,
}
impl Entity for ProjectSearchView {
type Event = ViewEvent;
}
impl View for ProjectSearchView {
fn ui_name() -> &'static str {
"ProjectSearchView"
}
fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
let model = &self.model.read(cx);
let results = if model.highlighted_ranges.is_empty() {
let theme = &self.settings.borrow().theme;
let text = if self.query_editor.read(cx).text(cx).is_empty() {
""
} else if model.pending_search.is_some() {
"Searching..."
} else {
"No results"
};
Label::new(text.to_string(), theme.search.results_status.clone())
.aligned()
.contained()
.with_background_color(theme.editor.background)
.flexible(1., true)
.boxed()
} else {
ChildView::new(&self.results_editor)
.flexible(1., true)
.boxed()
};
Flex::column()
.with_child(self.render_query_editor(cx))
.with_child(results)
.boxed()
}
fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
if self.model.read(cx).highlighted_ranges.is_empty() {
cx.focus(&self.query_editor);
} else {
self.focus_results_editor(cx);
}
}
}
impl ItemView for ProjectSearchView {
fn act_as_type(
&self,
type_id: TypeId,
self_handle: &ViewHandle<Self>,
_: &gpui::AppContext,
) -> Option<gpui::AnyViewHandle> {
if type_id == TypeId::of::<Self>() {
Some(self_handle.into())
} else if type_id == TypeId::of::<Editor>() {
Some((&self.results_editor).into())
} else {
None
}
}
fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
self.results_editor
.update(cx, |editor, cx| editor.deactivated(cx));
}
fn item(&self, _: &gpui::AppContext) -> Box<dyn ItemHandle> {
Box::new(self.model.clone())
}
fn tab_content(&self, tab_theme: &theme::Tab, cx: &gpui::AppContext) -> ElementBox {
let settings = self.settings.borrow();
let search_theme = &settings.theme.search;
Flex::row()
.with_child(
Svg::new("icons/magnifier.svg")
.with_color(tab_theme.label.text.color)
.constrained()
.with_width(search_theme.tab_icon_width)
.aligned()
.boxed(),
)
.with_children(self.model.read(cx).active_query.as_ref().map(|query| {
Label::new(query.as_str().to_string(), tab_theme.label.clone())
.aligned()
.contained()
.with_margin_left(search_theme.tab_icon_spacing)
.boxed()
}))
.boxed()
}
fn project_path(&self, _: &gpui::AppContext) -> Option<project::ProjectPath> {
None
}
fn can_save(&self, _: &gpui::AppContext) -> bool {
true
}
fn is_dirty(&self, cx: &AppContext) -> bool {
self.results_editor.read(cx).is_dirty(cx)
}
fn has_conflict(&self, cx: &AppContext) -> bool {
self.results_editor.read(cx).has_conflict(cx)
}
fn save(
&mut self,
project: ModelHandle<Project>,
cx: &mut ViewContext<Self>,
) -> Task<anyhow::Result<()>> {
self.results_editor
.update(cx, |editor, cx| editor.save(project, cx))
}
fn can_save_as(&self, _: &gpui::AppContext) -> bool {
false
}
fn save_as(
&mut self,
_: ModelHandle<Project>,
_: PathBuf,
_: &mut ViewContext<Self>,
) -> Task<anyhow::Result<()>> {
unreachable!("save_as should not have been called")
}
fn clone_on_split(
&self,
nav_history: ItemNavHistory,
cx: &mut ViewContext<Self>,
) -> Option<Self>
where
Self: Sized,
{
let query_editor = cx.add_view(|cx| {
let query = self.query_editor.read(cx).text(cx);
let editor = Editor::single_line(
self.settings.clone(),
Some(|theme| theme.search.editor.input.clone()),
cx,
);
editor
.buffer()
.update(cx, |buffer, cx| buffer.edit([0..0], query, cx));
editor
});
let model = self
.model
.update(cx, |model, cx| cx.add_model(|cx| model.clone(cx)));
cx.observe(&model, |this, _, cx| this.model_changed(true, cx))
.detach();
let results_editor = cx.add_view(|cx| {
let model = model.read(cx);
let excerpts = model.excerpts.clone();
let project = model.project.clone();
let scroll_position = self
.results_editor
.update(cx, |editor, cx| editor.scroll_position(cx));
let mut editor = Editor::for_buffer(excerpts, Some(project), self.settings.clone(), cx);
editor.set_searchable(false);
editor.set_nav_history(Some(nav_history));
editor.set_scroll_position(scroll_position, cx);
editor
});
let mut view = Self {
model,
query_editor,
results_editor,
case_sensitive: self.case_sensitive,
whole_word: self.whole_word,
regex: self.regex,
query_contains_error: self.query_contains_error,
settings: self.settings.clone(),
};
view.model_changed(false, cx);
Some(view)
}
fn navigate(&mut self, data: Box<dyn Any>, cx: &mut ViewContext<Self>) {
self.results_editor
.update(cx, |editor, cx| editor.navigate(data, cx));
}
fn should_update_tab_on_event(event: &ViewEvent) -> bool {
matches!(event, ViewEvent::UpdateTab)
}
}
impl ProjectSearchView {
fn deploy(workspace: &mut Workspace, _: &Deploy, cx: &mut ViewContext<Workspace>) {
if let Some(existing) = workspace
.items_of_type::<ProjectSearch>(cx)
.max_by_key(|existing| existing.id())
{
workspace.activate_item(&existing, cx);
} else {
let model = cx.add_model(|cx| ProjectSearch::new(workspace.project().clone(), cx));
workspace.open_item(model, cx);
}
}
fn search(&mut self, _: &Search, cx: &mut ViewContext<Self>) {
if let Some(query) = self.build_search_query(cx) {
self.model.update(cx, |model, cx| model.search(query, cx));
}
}
fn search_in_new(workspace: &mut Workspace, _: &SearchInNew, cx: &mut ViewContext<Workspace>) {
if let Some(search_view) = workspace
.active_item(cx)
.and_then(|item| item.downcast::<ProjectSearchView>())
{
let new_query = search_view.update(cx, |search_view, cx| {
let new_query = search_view.build_search_query(cx);
if new_query.is_some() {
if let Some(old_query) = search_view.model.read(cx).active_query.clone() {
search_view.query_editor.update(cx, |editor, cx| {
editor.set_text(old_query.as_str(), cx);
});
search_view.regex = old_query.is_regex();
search_view.whole_word = old_query.whole_word();
search_view.case_sensitive = old_query.case_sensitive();
}
}
new_query
});
if let Some(new_query) = new_query {
let model = cx.add_model(|cx| {
let mut model = ProjectSearch::new(workspace.project().clone(), cx);
model.search(new_query, cx);
model
});
workspace.open_item(model, cx);
}
}
}
fn build_search_query(&mut self, cx: &mut ViewContext<Self>) -> Option<SearchQuery> {
let text = self.query_editor.read(cx).text(cx);
if self.regex {
match SearchQuery::regex(text, self.whole_word, self.case_sensitive) {
Ok(query) => Some(query),
Err(_) => {
self.query_contains_error = true;
cx.notify();
None
}
}
} else {
Some(SearchQuery::text(
text,
self.whole_word,
self.case_sensitive,
))
}
}
fn toggle_search_option(
&mut self,
ToggleSearchOption(option): &ToggleSearchOption,
cx: &mut ViewContext<Self>,
) {
let value = match option {
SearchOption::WholeWord => &mut self.whole_word,
SearchOption::CaseSensitive => &mut self.case_sensitive,
SearchOption::Regex => &mut self.regex,
};
*value = !*value;
self.search(&Search, cx);
cx.notify();
}
fn toggle_focus(&mut self, _: &ToggleFocus, cx: &mut ViewContext<Self>) {
if self.query_editor.is_focused(cx) {
if !self.model.read(cx).highlighted_ranges.is_empty() {
self.focus_results_editor(cx);
}
} else {
self.query_editor.update(cx, |query_editor, cx| {
query_editor.select_all(&SelectAll, cx);
});
cx.focus(&self.query_editor);
}
}
fn focus_results_editor(&self, cx: &mut ViewContext<Self>) {
self.query_editor.update(cx, |query_editor, cx| {
let head = query_editor.newest_anchor_selection().head();
query_editor.select_ranges([head.clone()..head], None, cx);
});
cx.focus(&self.results_editor);
}
fn model_changed(&mut self, reset_selections: bool, cx: &mut ViewContext<Self>) {
let highlighted_ranges = self.model.read(cx).highlighted_ranges.clone();
if !highlighted_ranges.is_empty() {
let theme = &self.settings.borrow().theme.search;
self.results_editor.update(cx, |editor, cx| {
editor.highlight_ranges::<Self>(highlighted_ranges, theme.match_background, cx);
if reset_selections {
editor.select_ranges([0..0], Some(Autoscroll::Fit), cx);
}
});
if self.query_editor.is_focused(cx) {
self.focus_results_editor(cx);
}
}
cx.emit(ViewEvent::UpdateTab);
cx.notify();
}
fn render_query_editor(&self, cx: &mut RenderContext<Self>) -> ElementBox {
let theme = &self.settings.borrow().theme;
let editor_container = if self.query_contains_error {
theme.search.invalid_editor
} else {
theme.search.editor.input.container
};
Flex::row()
.with_child(
ChildView::new(&self.query_editor)
.contained()
.with_style(editor_container)
.aligned()
.constrained()
.with_max_width(theme.search.editor.max_width)
.boxed(),
)
.with_child(
Flex::row()
.with_child(self.render_option_button("Case", SearchOption::CaseSensitive, cx))
.with_child(self.render_option_button("Word", SearchOption::WholeWord, cx))
.with_child(self.render_option_button("Regex", SearchOption::Regex, cx))
.contained()
.with_style(theme.search.option_button_group)
.aligned()
.boxed(),
)
.contained()
.with_style(theme.search.container)
.constrained()
.with_height(theme.workspace.toolbar.height)
.named("project search")
}
fn render_option_button(
&self,
icon: &str,
option: SearchOption,
cx: &mut RenderContext<Self>,
) -> ElementBox {
let theme = &self.settings.borrow().theme.search;
let is_active = self.is_option_enabled(option);
MouseEventHandler::new::<Self, _, _>(option as usize, cx, |state, _| {
let style = match (is_active, state.hovered) {
(false, false) => &theme.option_button,
(false, true) => &theme.hovered_option_button,
(true, false) => &theme.active_option_button,
(true, true) => &theme.active_hovered_option_button,
};
Label::new(icon.to_string(), style.text.clone())
.contained()
.with_style(style.container)
.boxed()
})
.on_click(move |cx| cx.dispatch_action(ToggleSearchOption(option)))
.with_cursor_style(CursorStyle::PointingHand)
.boxed()
}
fn is_option_enabled(&self, option: SearchOption) -> bool {
match option {
SearchOption::WholeWord => self.whole_word,
SearchOption::CaseSensitive => self.case_sensitive,
SearchOption::Regex => self.regex,
}
}
}
+16
View File
@@ -0,0 +1,16 @@
use gpui::MutableAppContext;
mod buffer_search;
mod project_search;
pub fn init(cx: &mut MutableAppContext) {
buffer_search::init(cx);
project_search::init(cx);
}
#[derive(Clone, Copy)]
pub enum SearchOption {
WholeWord,
CaseSensitive,
Regex,
}