1use editor::{
2 combine_syntax_and_fuzzy_match_highlights, styled_runs_for_code_label, Autoscroll, Bias, Editor,
3};
4use fuzzy::{StringMatch, StringMatchCandidate};
5use gpui::{
6 actions, elements::*, AppContext, Entity, ModelHandle, MutableAppContext, RenderContext, Task,
7 View, ViewContext, ViewHandle,
8};
9use ordered_float::OrderedFloat;
10use picker::{Picker, PickerDelegate};
11use project::{Project, Symbol};
12use settings::Settings;
13use std::{borrow::Cow, cmp::Reverse};
14use util::ResultExt;
15use workspace::Workspace;
16
17actions!(project_symbols, [Toggle]);
18
19pub fn init(cx: &mut MutableAppContext) {
20 cx.add_action(ProjectSymbolsView::toggle);
21 Picker::<ProjectSymbolsView>::init(cx);
22}
23
24pub struct ProjectSymbolsView {
25 picker: ViewHandle<Picker<Self>>,
26 project: ModelHandle<Project>,
27 selected_match_index: usize,
28 symbols: Vec<Symbol>,
29 match_candidates: Vec<StringMatchCandidate>,
30 show_worktree_root_name: bool,
31 pending_update: Task<()>,
32 matches: Vec<StringMatch>,
33}
34
35pub enum Event {
36 Dismissed,
37 Selected(Symbol),
38}
39
40impl Entity for ProjectSymbolsView {
41 type Event = Event;
42}
43
44impl View for ProjectSymbolsView {
45 fn ui_name() -> &'static str {
46 "ProjectSymbolsView"
47 }
48
49 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
50 ChildView::new(self.picker.clone()).boxed()
51 }
52
53 fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
54 cx.focus(&self.picker);
55 }
56}
57
58impl ProjectSymbolsView {
59 fn new(project: ModelHandle<Project>, cx: &mut ViewContext<Self>) -> Self {
60 let handle = cx.weak_handle();
61 Self {
62 project,
63 picker: cx.add_view(|cx| Picker::new(handle, cx)),
64 selected_match_index: 0,
65 symbols: Default::default(),
66 match_candidates: Default::default(),
67 matches: Default::default(),
68 show_worktree_root_name: false,
69 pending_update: Task::ready(()),
70 }
71 }
72
73 fn toggle(workspace: &mut Workspace, _: &Toggle, cx: &mut ViewContext<Workspace>) {
74 workspace.toggle_modal(cx, |workspace, cx| {
75 let project = workspace.project().clone();
76 let symbols = cx.add_view(|cx| Self::new(project, cx));
77 cx.subscribe(&symbols, Self::on_event).detach();
78 symbols
79 });
80 }
81
82 fn filter(&mut self, query: &str, cx: &mut ViewContext<Self>) {
83 let mut matches = if query.is_empty() {
84 self.match_candidates
85 .iter()
86 .enumerate()
87 .map(|(candidate_id, candidate)| StringMatch {
88 candidate_id,
89 score: Default::default(),
90 positions: Default::default(),
91 string: candidate.string.clone(),
92 })
93 .collect()
94 } else {
95 cx.background_executor().block(fuzzy::match_strings(
96 &self.match_candidates,
97 query,
98 false,
99 100,
100 &Default::default(),
101 cx.background().clone(),
102 ))
103 };
104
105 matches.sort_unstable_by_key(|mat| {
106 let label = &self.symbols[mat.candidate_id].label;
107 (
108 Reverse(OrderedFloat(mat.score)),
109 &label.text[label.filter_range.clone()],
110 )
111 });
112
113 for mat in &mut matches {
114 let filter_start = self.symbols[mat.candidate_id].label.filter_range.start;
115 for position in &mut mat.positions {
116 *position += filter_start;
117 }
118 }
119
120 self.matches = matches;
121 self.set_selected_index(0, cx);
122 cx.notify();
123 }
124
125 fn on_event(
126 workspace: &mut Workspace,
127 _: ViewHandle<Self>,
128 event: &Event,
129 cx: &mut ViewContext<Workspace>,
130 ) {
131 match event {
132 Event::Dismissed => workspace.dismiss_modal(cx),
133 Event::Selected(symbol) => {
134 let buffer = workspace
135 .project()
136 .update(cx, |project, cx| project.open_buffer_for_symbol(symbol, cx));
137
138 let symbol = symbol.clone();
139 cx.spawn(|workspace, mut cx| async move {
140 let buffer = buffer.await?;
141 workspace.update(&mut cx, |workspace, cx| {
142 let position = buffer
143 .read(cx)
144 .clip_point_utf16(symbol.range.start, Bias::Left);
145
146 let editor = workspace.open_project_item::<Editor>(buffer, cx);
147 editor.update(cx, |editor, cx| {
148 editor.select_ranges(
149 [position..position],
150 Some(Autoscroll::Center),
151 cx,
152 );
153 });
154 });
155 Ok::<_, anyhow::Error>(())
156 })
157 .detach_and_log_err(cx);
158 workspace.dismiss_modal(cx);
159 }
160 }
161 }
162}
163
164impl PickerDelegate for ProjectSymbolsView {
165 fn confirm(&mut self, cx: &mut ViewContext<Self>) {
166 if let Some(symbol) = self
167 .matches
168 .get(self.selected_match_index)
169 .map(|mat| self.symbols[mat.candidate_id].clone())
170 {
171 cx.emit(Event::Selected(symbol));
172 }
173 }
174
175 fn dismiss(&mut self, cx: &mut ViewContext<Self>) {
176 cx.emit(Event::Dismissed);
177 }
178
179 fn match_count(&self) -> usize {
180 self.matches.len()
181 }
182
183 fn selected_index(&self) -> usize {
184 self.selected_match_index
185 }
186
187 fn set_selected_index(&mut self, ix: usize, cx: &mut ViewContext<Self>) {
188 self.selected_match_index = ix;
189 cx.notify();
190 }
191
192 fn update_matches(&mut self, query: String, cx: &mut ViewContext<Self>) -> Task<()> {
193 self.filter(&query, cx);
194 self.show_worktree_root_name = self.project.read(cx).visible_worktrees(cx).count() > 1;
195 let symbols = self
196 .project
197 .update(cx, |project, cx| project.symbols(&query, cx));
198 self.pending_update = cx.spawn_weak(|this, mut cx| async move {
199 let symbols = symbols.await.log_err();
200 if let Some(this) = this.upgrade(&cx) {
201 if let Some(symbols) = symbols {
202 this.update(&mut cx, |this, cx| {
203 this.match_candidates = symbols
204 .iter()
205 .enumerate()
206 .map(|(id, symbol)| {
207 StringMatchCandidate::new(
208 id,
209 symbol.label.text[symbol.label.filter_range.clone()]
210 .to_string(),
211 )
212 })
213 .collect();
214 this.symbols = symbols;
215 this.filter(&query, cx);
216 });
217 }
218 }
219 });
220 Task::ready(())
221 }
222
223 fn render_match(
224 &self,
225 ix: usize,
226 mouse_state: &MouseState,
227 selected: bool,
228 cx: &AppContext,
229 ) -> ElementBox {
230 let string_match = &self.matches[ix];
231 let settings = cx.global::<Settings>();
232 let style = &settings.theme.picker.item;
233 let current_style = style.style_for(mouse_state, selected);
234 let symbol = &self.symbols[string_match.candidate_id];
235 let syntax_runs = styled_runs_for_code_label(&symbol.label, &settings.theme.editor.syntax);
236
237 let mut path = symbol.path.to_string_lossy();
238 if self.show_worktree_root_name {
239 let project = self.project.read(cx);
240 if let Some(worktree) = project.worktree_for_id(symbol.worktree_id, cx) {
241 path = Cow::Owned(format!(
242 "{}{}{}",
243 worktree.read(cx).root_name(),
244 std::path::MAIN_SEPARATOR,
245 path.as_ref()
246 ));
247 }
248 }
249
250 Flex::column()
251 .with_child(
252 Text::new(symbol.label.text.clone(), current_style.label.text.clone())
253 .with_soft_wrap(false)
254 .with_highlights(combine_syntax_and_fuzzy_match_highlights(
255 &symbol.label.text,
256 current_style.label.text.clone().into(),
257 syntax_runs,
258 &string_match.positions,
259 ))
260 .boxed(),
261 )
262 .with_child(
263 // Avoid styling the path differently when it is selected, since
264 // the symbol's syntax highlighting doesn't change when selected.
265 Label::new(path.to_string(), style.default.label.clone()).boxed(),
266 )
267 .contained()
268 .with_style(current_style.container)
269 .boxed()
270 }
271}
272
273#[cfg(test)]
274mod tests {
275 use super::*;
276 use futures::StreamExt;
277 use gpui::{serde_json::json, TestAppContext};
278 use language::{FakeLspAdapter, Language, LanguageConfig};
279 use project::FakeFs;
280 use std::sync::Arc;
281
282 #[gpui::test]
283 async fn test_project_symbols(cx: &mut TestAppContext) {
284 cx.foreground().forbid_parking();
285 cx.update(|cx| cx.set_global(Settings::test(cx)));
286
287 let mut language = Language::new(
288 LanguageConfig {
289 name: "Rust".into(),
290 path_suffixes: vec!["rs".to_string()],
291 ..Default::default()
292 },
293 None,
294 );
295 let mut fake_servers = language.set_fake_lsp_adapter(FakeLspAdapter::default());
296
297 let fs = FakeFs::new(cx.background());
298 fs.insert_tree("/dir", json!({ "test.rs": "" })).await;
299
300 let project = Project::test(fs.clone(), ["/dir"], cx).await;
301 project.update(cx, |project, _| project.languages().add(Arc::new(language)));
302
303 let _buffer = project
304 .update(cx, |project, cx| {
305 project.open_local_buffer("/dir/test.rs", cx)
306 })
307 .await
308 .unwrap();
309
310 // Set up fake langauge server to return fuzzy matches against
311 // a fixed set of symbol names.
312 let fake_symbol_names = ["one", "ton", "uno"];
313 let fake_server = fake_servers.next().await.unwrap();
314 fake_server.handle_request::<lsp::request::WorkspaceSymbol, _, _>(
315 move |params: lsp::WorkspaceSymbolParams, cx| {
316 let executor = cx.background();
317 async move {
318 let candidates = fake_symbol_names
319 .into_iter()
320 .map(|name| StringMatchCandidate::new(0, name.into()))
321 .collect::<Vec<_>>();
322 let matches = if params.query.is_empty() {
323 Vec::new()
324 } else {
325 fuzzy::match_strings(
326 &candidates,
327 ¶ms.query,
328 true,
329 100,
330 &Default::default(),
331 executor.clone(),
332 )
333 .await
334 };
335
336 Ok(Some(
337 matches.into_iter().map(|mat| symbol(&mat.string)).collect(),
338 ))
339 }
340 },
341 );
342
343 // Create the project symbols view.
344 let (_, symbols_view) = cx.add_window(|cx| ProjectSymbolsView::new(project.clone(), cx));
345 let picker = symbols_view.read_with(cx, |symbols_view, _| symbols_view.picker.clone());
346
347 // Spawn multiples updates before the first update completes,
348 // such that in the end, there are no matches. Testing for regression:
349 // https://github.com/zed-industries/zed/issues/861
350 picker.update(cx, |p, cx| {
351 p.update_matches("o".to_string(), cx);
352 p.update_matches("on".to_string(), cx);
353 p.update_matches("onex".to_string(), cx);
354 });
355
356 cx.foreground().run_until_parked();
357 symbols_view.read_with(cx, |symbols_view, _| {
358 assert_eq!(symbols_view.matches.len(), 0);
359 });
360
361 // Spawn more updates such that in the end, there are matches.
362 picker.update(cx, |p, cx| {
363 p.update_matches("one".to_string(), cx);
364 p.update_matches("on".to_string(), cx);
365 });
366
367 cx.foreground().run_until_parked();
368 symbols_view.read_with(cx, |symbols_view, _| {
369 assert_eq!(symbols_view.matches.len(), 2);
370 assert_eq!(symbols_view.matches[0].string, "one");
371 assert_eq!(symbols_view.matches[1].string, "ton");
372 });
373
374 // Spawn more updates such that in the end, there are again no matches.
375 picker.update(cx, |p, cx| {
376 p.update_matches("o".to_string(), cx);
377 p.update_matches("".to_string(), cx);
378 });
379
380 cx.foreground().run_until_parked();
381 symbols_view.read_with(cx, |symbols_view, _| {
382 assert_eq!(symbols_view.matches.len(), 0);
383 });
384 }
385
386 fn symbol(name: &str) -> lsp::SymbolInformation {
387 #[allow(deprecated)]
388 lsp::SymbolInformation {
389 name: name.to_string(),
390 kind: lsp::SymbolKind::FUNCTION,
391 tags: None,
392 deprecated: None,
393 container_name: None,
394 location: lsp::Location::new(
395 lsp::Url::from_file_path("/a/b").unwrap(),
396 lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 0)),
397 ),
398 }
399 }
400}