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