Port project_symbols (#3634)

Release Notes:

- N/A
This commit is contained in:
Conrad Irwin 2023-12-13 14:13:25 -07:00 committed by GitHub
commit 426d298173
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 491 additions and 4 deletions

25
Cargo.lock generated
View File

@ -6510,6 +6510,7 @@ dependencies = [
"theme2", "theme2",
"ui2", "ui2",
"util", "util",
"workspace2",
] ]
[[package]] [[package]]
@ -7019,6 +7020,29 @@ dependencies = [
"workspace", "workspace",
] ]
[[package]]
name = "project_symbols2"
version = "0.1.0"
dependencies = [
"anyhow",
"editor2",
"futures 0.3.28",
"fuzzy2",
"gpui2",
"language2",
"lsp2",
"ordered-float 2.10.0",
"picker2",
"postage",
"project2",
"settings2",
"smol",
"text2",
"theme2",
"util",
"workspace2",
]
[[package]] [[package]]
name = "prometheus" name = "prometheus"
version = "0.13.3" version = "0.13.3"
@ -12081,6 +12105,7 @@ dependencies = [
"postage", "postage",
"project2", "project2",
"project_panel2", "project_panel2",
"project_symbols2",
"quick_action_bar2", "quick_action_bar2",
"rand 0.8.5", "rand 0.8.5",
"recent_projects2", "recent_projects2",

View File

@ -90,6 +90,7 @@ members = [
"crates/project_panel", "crates/project_panel",
"crates/project_panel2", "crates/project_panel2",
"crates/project_symbols", "crates/project_symbols",
"crates/project_symbols2",
"crates/quick_action_bar2", "crates/quick_action_bar2",
"crates/recent_projects", "crates/recent_projects",
"crates/recent_projects2", "crates/recent_projects2",

View File

@ -16,6 +16,7 @@ menu = { package = "menu2", path = "../menu2" }
settings = { package = "settings2", path = "../settings2" } settings = { package = "settings2", path = "../settings2" }
util = { path = "../util" } util = { path = "../util" }
theme = { package = "theme2", path = "../theme2" } theme = { package = "theme2", path = "../theme2" }
workspace = { package = "workspace2", path = "../workspace2"}
parking_lot.workspace = true parking_lot.workspace = true

View File

@ -1,11 +1,12 @@
use editor::Editor; use editor::Editor;
use gpui::{ use gpui::{
div, prelude::*, rems, uniform_list, AnyElement, AppContext, DismissEvent, Div, EventEmitter, div, prelude::*, rems, uniform_list, AnyElement, AppContext, DismissEvent, Div, EventEmitter,
FocusHandle, FocusableView, MouseButton, MouseDownEvent, Render, Task, UniformListScrollHandle, FocusHandle, FocusableView, Length, MouseButton, MouseDownEvent, Render, Task,
View, ViewContext, WindowContext, UniformListScrollHandle, View, ViewContext, WindowContext,
}; };
use std::{cmp, sync::Arc}; use std::{cmp, sync::Arc};
use ui::{prelude::*, v_stack, Color, Divider, Label}; use ui::{prelude::*, v_stack, Color, Divider, Label};
use workspace::ModalView;
pub struct Picker<D: PickerDelegate> { pub struct Picker<D: PickerDelegate> {
pub delegate: D, pub delegate: D,
@ -13,6 +14,7 @@ pub struct Picker<D: PickerDelegate> {
editor: View<Editor>, editor: View<Editor>,
pending_update_matches: Option<Task<()>>, pending_update_matches: Option<Task<()>>,
confirm_on_update: Option<bool>, confirm_on_update: Option<bool>,
width: Option<Length>,
} }
pub trait PickerDelegate: Sized + 'static { pub trait PickerDelegate: Sized + 'static {
@ -55,11 +57,17 @@ impl<D: PickerDelegate> Picker<D> {
scroll_handle: UniformListScrollHandle::new(), scroll_handle: UniformListScrollHandle::new(),
pending_update_matches: None, pending_update_matches: None,
confirm_on_update: None, confirm_on_update: None,
width: None,
}; };
this.update_matches("".to_string(), cx); this.update_matches("".to_string(), cx);
this this
} }
pub fn width(mut self, width: impl Into<gpui::Length>) -> Self {
self.width = Some(width.into());
self
}
pub fn focus(&self, cx: &mut WindowContext) { pub fn focus(&self, cx: &mut WindowContext) {
self.editor.update(cx, |editor, cx| editor.focus(cx)); self.editor.update(cx, |editor, cx| editor.focus(cx));
} }
@ -197,6 +205,7 @@ impl<D: PickerDelegate> Picker<D> {
} }
impl<D: PickerDelegate> EventEmitter<DismissEvent> for Picker<D> {} impl<D: PickerDelegate> EventEmitter<DismissEvent> for Picker<D> {}
impl<D: PickerDelegate> ModalView for Picker<D> {}
impl<D: PickerDelegate> Render for Picker<D> { impl<D: PickerDelegate> Render for Picker<D> {
type Element = Div; type Element = Div;
@ -221,6 +230,9 @@ impl<D: PickerDelegate> Render for Picker<D> {
div() div()
.key_context("picker") .key_context("picker")
.size_full() .size_full()
.when_some(self.width, |el, width| {
el.w(width)
})
.overflow_hidden() .overflow_hidden()
.elevation_3(cx) .elevation_3(cx)
.on_action(cx.listener(Self::select_next)) .on_action(cx.listener(Self::select_next))

View File

@ -0,0 +1,37 @@
[package]
name = "project_symbols2"
version = "0.1.0"
edition = "2021"
publish = false
[lib]
path = "src/project_symbols.rs"
doctest = false
[dependencies]
editor = { package = "editor2", path = "../editor2" }
fuzzy = {package = "fuzzy2", path = "../fuzzy2" }
gpui = {package = "gpui2", path = "../gpui2" }
picker = {package = "picker2", path = "../picker2" }
project = { package = "project2", path = "../project2" }
text = {package = "text2", path = "../text2" }
settings = {package = "settings2", path = "../settings2" }
workspace = {package = "workspace2", path = "../workspace2" }
theme = { package = "theme2", path = "../theme2" }
util = { path = "../util" }
anyhow.workspace = true
ordered-float.workspace = true
postage.workspace = true
smol.workspace = true
[dev-dependencies]
futures.workspace = true
editor = { package = "editor2", path = "../editor2", features = ["test-support"] }
settings = { package = "settings2", path = "../settings2", features = ["test-support"] }
gpui = { package = "gpui2", path = "../gpui2", features = ["test-support"] }
language = { package = "language2", path = "../language2", features = ["test-support"] }
lsp = { package = "lsp2", path = "../lsp2", features = ["test-support"] }
project = { package = "project2", path = "../project2", features = ["test-support"] }
theme = { package = "theme2", path = "../theme2", features = ["test-support"] }
workspace = { package = "workspace2", path = "../workspace2", features = ["test-support"] }

View File

@ -0,0 +1,411 @@
use editor::{scroll::autoscroll::Autoscroll, styled_runs_for_code_label, Bias, Editor};
use fuzzy::{StringMatch, StringMatchCandidate};
use gpui::{
actions, rems, AppContext, DismissEvent, FontWeight, Model, ParentElement, StyledText, Task,
View, ViewContext, WeakView,
};
use ordered_float::OrderedFloat;
use picker::{Picker, PickerDelegate};
use project::{Project, Symbol};
use std::{borrow::Cow, cmp::Reverse, sync::Arc};
use theme::ActiveTheme;
use util::ResultExt;
use workspace::{
ui::{v_stack, Color, Label, LabelCommon, LabelLike, ListItem, Selectable},
Workspace,
};
actions!(project_symbols, [Toggle]);
pub fn init(cx: &mut AppContext) {
cx.observe_new_views(
|workspace: &mut Workspace, _: &mut ViewContext<Workspace>| {
workspace.register_action(|workspace, _: &Toggle, cx| {
let project = workspace.project().clone();
let handle = cx.view().downgrade();
workspace.toggle_modal(cx, move |cx| {
let delegate = ProjectSymbolsDelegate::new(handle, project);
Picker::new(delegate, cx).width(rems(34.))
})
});
},
)
.detach();
}
pub type ProjectSymbols = View<Picker<ProjectSymbolsDelegate>>;
pub struct ProjectSymbolsDelegate {
workspace: WeakView<Workspace>,
project: Model<Project>,
selected_match_index: usize,
symbols: Vec<Symbol>,
visible_match_candidates: Vec<StringMatchCandidate>,
external_match_candidates: Vec<StringMatchCandidate>,
show_worktree_root_name: bool,
matches: Vec<StringMatch>,
}
impl ProjectSymbolsDelegate {
fn new(workspace: WeakView<Workspace>, project: Model<Project>) -> Self {
Self {
workspace,
project,
selected_match_index: 0,
symbols: Default::default(),
visible_match_candidates: Default::default(),
external_match_candidates: Default::default(),
matches: Default::default(),
show_worktree_root_name: false,
}
}
fn filter(&mut self, query: &str, cx: &mut ViewContext<Picker<Self>>) {
const MAX_MATCHES: usize = 100;
let mut visible_matches = cx.background_executor().block(fuzzy::match_strings(
&self.visible_match_candidates,
query,
false,
MAX_MATCHES,
&Default::default(),
cx.background_executor().clone(),
));
let mut external_matches = cx.background_executor().block(fuzzy::match_strings(
&self.external_match_candidates,
query,
false,
MAX_MATCHES - visible_matches.len().min(MAX_MATCHES),
&Default::default(),
cx.background_executor().clone(),
));
let sort_key_for_match = |mat: &StringMatch| {
let symbol = &self.symbols[mat.candidate_id];
(
Reverse(OrderedFloat(mat.score)),
&symbol.label.text[symbol.label.filter_range.clone()],
)
};
visible_matches.sort_unstable_by_key(sort_key_for_match);
external_matches.sort_unstable_by_key(sort_key_for_match);
let mut matches = visible_matches;
matches.append(&mut external_matches);
for mat in &mut matches {
let symbol = &self.symbols[mat.candidate_id];
let filter_start = symbol.label.filter_range.start;
for position in &mut mat.positions {
*position += filter_start;
}
}
self.matches = matches;
self.set_selected_index(0, cx);
}
}
impl PickerDelegate for ProjectSymbolsDelegate {
type ListItem = ListItem;
fn placeholder_text(&self) -> Arc<str> {
"Search project symbols...".into()
}
fn confirm(&mut self, secondary: bool, cx: &mut ViewContext<Picker<Self>>) {
if let Some(symbol) = self
.matches
.get(self.selected_match_index)
.map(|mat| self.symbols[mat.candidate_id].clone())
{
let buffer = self.project.update(cx, |project, cx| {
project.open_buffer_for_symbol(&symbol, cx)
});
let symbol = symbol.clone();
let workspace = self.workspace.clone();
cx.spawn(|_, mut cx| async move {
let buffer = buffer.await?;
workspace.update(&mut cx, |workspace, cx| {
let position = buffer
.read(cx)
.clip_point_utf16(symbol.range.start, Bias::Left);
let editor = if secondary {
workspace.split_project_item::<Editor>(buffer, cx)
} else {
workspace.open_project_item::<Editor>(buffer, cx)
};
editor.update(cx, |editor, cx| {
editor.change_selections(Some(Autoscroll::center()), cx, |s| {
s.select_ranges([position..position])
});
});
})?;
Ok::<_, anyhow::Error>(())
})
.detach_and_log_err(cx);
cx.emit(DismissEvent);
}
}
fn dismissed(&mut self, _cx: &mut ViewContext<Picker<Self>>) {}
fn match_count(&self) -> usize {
self.matches.len()
}
fn selected_index(&self) -> usize {
self.selected_match_index
}
fn set_selected_index(&mut self, ix: usize, _cx: &mut ViewContext<Picker<Self>>) {
self.selected_match_index = ix;
}
fn update_matches(&mut self, query: String, cx: &mut ViewContext<Picker<Self>>) -> Task<()> {
self.filter(&query, cx);
self.show_worktree_root_name = self.project.read(cx).visible_worktrees(cx).count() > 1;
let symbols = self
.project
.update(cx, |project, cx| project.symbols(&query, cx));
cx.spawn(|this, mut cx| async move {
let symbols = symbols.await.log_err();
if let Some(symbols) = symbols {
this.update(&mut cx, |this, cx| {
let delegate = &mut this.delegate;
let project = delegate.project.read(cx);
let (visible_match_candidates, external_match_candidates) = symbols
.iter()
.enumerate()
.map(|(id, symbol)| {
StringMatchCandidate::new(
id,
symbol.label.text[symbol.label.filter_range.clone()].to_string(),
)
})
.partition(|candidate| {
project
.entry_for_path(&symbols[candidate.id].path, cx)
.map_or(false, |e| !e.is_ignored)
});
delegate.visible_match_candidates = visible_match_candidates;
delegate.external_match_candidates = external_match_candidates;
delegate.symbols = symbols;
delegate.filter(&query, cx);
})
.log_err();
}
})
}
fn render_match(
&self,
ix: usize,
selected: bool,
cx: &mut ViewContext<Picker<Self>>,
) -> Option<Self::ListItem> {
let string_match = &self.matches[ix];
let symbol = &self.symbols[string_match.candidate_id];
let syntax_runs = styled_runs_for_code_label(&symbol.label, cx.theme().syntax());
let mut path = symbol.path.path.to_string_lossy();
if self.show_worktree_root_name {
let project = self.project.read(cx);
if let Some(worktree) = project.worktree_for_id(symbol.path.worktree_id, cx) {
path = Cow::Owned(format!(
"{}{}{}",
worktree.read(cx).root_name(),
std::path::MAIN_SEPARATOR,
path.as_ref()
));
}
}
let label = symbol.label.text.clone();
let path = path.to_string().clone();
let highlights = gpui::combine_highlights(
string_match
.positions
.iter()
.map(|pos| (*pos..pos + 1, FontWeight::BOLD.into())),
syntax_runs.map(|(range, mut highlight)| {
// Ignore font weight for syntax highlighting, as we'll use it
// for fuzzy matches.
highlight.font_weight = None;
(range, highlight)
}),
);
Some(
ListItem::new(ix).inset(true).selected(selected).child(
// todo!() combine_syntax_and_fuzzy_match_highlights()
v_stack()
.child(
LabelLike::new().child(
StyledText::new(label)
.with_highlights(&cx.text_style().clone(), highlights),
),
)
.child(Label::new(path).color(Color::Muted)),
),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use futures::StreamExt;
use gpui::{serde_json::json, TestAppContext, VisualContext};
use language::{FakeLspAdapter, Language, LanguageConfig};
use project::FakeFs;
use settings::SettingsStore;
use std::{path::Path, sync::Arc};
#[gpui::test]
async fn test_project_symbols(cx: &mut TestAppContext) {
init_test(cx);
let mut language = Language::new(
LanguageConfig {
name: "Rust".into(),
path_suffixes: vec!["rs".to_string()],
..Default::default()
},
None,
);
let mut fake_servers = language
.set_fake_lsp_adapter(Arc::<FakeLspAdapter>::default())
.await;
let fs = FakeFs::new(cx.executor());
fs.insert_tree("/dir", json!({ "test.rs": "" })).await;
let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
project.update(cx, |project, _| project.languages().add(Arc::new(language)));
let _buffer = project
.update(cx, |project, cx| {
project.open_local_buffer("/dir/test.rs", cx)
})
.await
.unwrap();
// Set up fake language server to return fuzzy matches against
// a fixed set of symbol names.
let fake_symbols = [
symbol("one", "/external"),
symbol("ton", "/dir/test.rs"),
symbol("uno", "/dir/test.rs"),
];
let fake_server = fake_servers.next().await.unwrap();
fake_server.handle_request::<lsp::WorkspaceSymbolRequest, _, _>(
move |params: lsp::WorkspaceSymbolParams, cx| {
let executor = cx.background_executor().clone();
let fake_symbols = fake_symbols.clone();
async move {
let candidates = fake_symbols
.iter()
.enumerate()
.map(|(id, symbol)| StringMatchCandidate::new(id, symbol.name.clone()))
.collect::<Vec<_>>();
let matches = if params.query.is_empty() {
Vec::new()
} else {
fuzzy::match_strings(
&candidates,
&params.query,
true,
100,
&Default::default(),
executor.clone(),
)
.await
};
Ok(Some(lsp::WorkspaceSymbolResponse::Flat(
matches
.into_iter()
.map(|mat| fake_symbols[mat.candidate_id].clone())
.collect(),
)))
}
},
);
let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
// Create the project symbols view.
let symbols = cx.build_view(|cx| {
Picker::new(
ProjectSymbolsDelegate::new(workspace.downgrade(), project.clone()),
cx,
)
});
// Spawn multiples updates before the first update completes,
// such that in the end, there are no matches. Testing for regression:
// https://github.com/zed-industries/zed/issues/861
symbols.update(cx, |p, cx| {
p.update_matches("o".to_string(), cx);
p.update_matches("on".to_string(), cx);
p.update_matches("onex".to_string(), cx);
});
cx.run_until_parked();
symbols.update(cx, |symbols, _| {
assert_eq!(symbols.delegate.matches.len(), 0);
});
// Spawn more updates such that in the end, there are matches.
symbols.update(cx, |p, cx| {
p.update_matches("one".to_string(), cx);
p.update_matches("on".to_string(), cx);
});
cx.run_until_parked();
symbols.update(cx, |symbols, _| {
let delegate = &symbols.delegate;
assert_eq!(delegate.matches.len(), 2);
assert_eq!(delegate.matches[0].string, "ton");
assert_eq!(delegate.matches[1].string, "one");
});
// Spawn more updates such that in the end, there are again no matches.
symbols.update(cx, |p, cx| {
p.update_matches("o".to_string(), cx);
p.update_matches("".to_string(), cx);
});
cx.run_until_parked();
symbols.update(cx, |symbols, _| {
assert_eq!(symbols.delegate.matches.len(), 0);
});
}
fn init_test(cx: &mut TestAppContext) {
cx.update(|cx| {
let store = SettingsStore::test(cx);
cx.set_global(store);
theme::init(theme::LoadThemes::JustBase, cx);
language::init(cx);
Project::init_settings(cx);
workspace::init_settings(cx);
});
}
fn symbol(name: &str, path: impl AsRef<Path>) -> lsp::SymbolInformation {
#[allow(deprecated)]
lsp::SymbolInformation {
name: name.to_string(),
kind: lsp::SymbolKind::FUNCTION,
tags: None,
deprecated: None,
container_name: None,
location: lsp::Location::new(
lsp::Url::from_file_path(path.as_ref()).unwrap(),
lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 0)),
),
}
}
}

View File

@ -55,7 +55,7 @@ outline = { package = "outline2", path = "../outline2" }
# plugin_runtime = { path = "../plugin_runtime",optional = true } # plugin_runtime = { path = "../plugin_runtime",optional = true }
project = { package = "project2", path = "../project2" } project = { package = "project2", path = "../project2" }
project_panel = { package = "project_panel2", path = "../project_panel2" } project_panel = { package = "project_panel2", path = "../project_panel2" }
# project_symbols = { path = "../project_symbols" } project_symbols = { package = "project_symbols2", path = "../project_symbols2" }
quick_action_bar = { package = "quick_action_bar2", path = "../quick_action_bar2" } quick_action_bar = { package = "quick_action_bar2", path = "../quick_action_bar2" }
recent_projects = { package = "recent_projects2", path = "../recent_projects2" } recent_projects = { package = "recent_projects2", path = "../recent_projects2" }
rope = { package = "rope2", path = "../rope2"} rope = { package = "rope2", path = "../rope2"}

View File

@ -205,7 +205,7 @@ fn main() {
go_to_line::init(cx); go_to_line::init(cx);
file_finder::init(cx); file_finder::init(cx);
outline::init(cx); outline::init(cx);
// project_symbols::init(cx); project_symbols::init(cx);
project_panel::init(Assets, cx); project_panel::init(Assets, cx);
channel::init(&client, user_store.clone(), cx); channel::init(&client, user_store.clone(), cx);
// diagnostics::init(cx); // diagnostics::init(cx);