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, |cx, workspace| {
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(&self, ix: usize, selected: bool, cx: &AppContext) -> ElementBox {
224 let string_match = &self.matches[ix];
225 let settings = cx.global::<Settings>();
226 let style = if selected {
227 &settings.theme.selector.active_item
228 } else {
229 &settings.theme.selector.item
230 };
231 let symbol = &self.symbols[string_match.candidate_id];
232 let syntax_runs = styled_runs_for_code_label(&symbol.label, &settings.theme.editor.syntax);
233
234 let mut path = symbol.path.to_string_lossy();
235 if self.show_worktree_root_name {
236 let project = self.project.read(cx);
237 if let Some(worktree) = project.worktree_for_id(symbol.worktree_id, cx) {
238 path = Cow::Owned(format!(
239 "{}{}{}",
240 worktree.read(cx).root_name(),
241 std::path::MAIN_SEPARATOR,
242 path.as_ref()
243 ));
244 }
245 }
246
247 Flex::column()
248 .with_child(
249 Text::new(symbol.label.text.clone(), style.label.text.clone())
250 .with_soft_wrap(false)
251 .with_highlights(combine_syntax_and_fuzzy_match_highlights(
252 &symbol.label.text,
253 style.label.text.clone().into(),
254 syntax_runs,
255 &string_match.positions,
256 ))
257 .boxed(),
258 )
259 .with_child(
260 // Avoid styling the path differently when it is selected, since
261 // the symbol's syntax highlighting doesn't change when selected.
262 Label::new(path.to_string(), settings.theme.selector.item.label.clone()).boxed(),
263 )
264 .contained()
265 .with_style(style.container)
266 .boxed()
267 }
268}
269
270#[cfg(test)]
271mod tests {
272 use super::*;
273 use futures::StreamExt;
274 use gpui::{serde_json::json, TestAppContext};
275 use language::{FakeLspAdapter, Language, LanguageConfig};
276 use project::FakeFs;
277 use std::sync::Arc;
278
279 #[gpui::test]
280 async fn test_project_symbols(cx: &mut TestAppContext) {
281 cx.foreground().forbid_parking();
282 cx.update(|cx| cx.set_global(Settings::test(cx)));
283
284 let mut language = Language::new(
285 LanguageConfig {
286 name: "Rust".into(),
287 path_suffixes: vec!["rs".to_string()],
288 ..Default::default()
289 },
290 None,
291 );
292 let mut fake_servers = language.set_fake_lsp_adapter(FakeLspAdapter::default());
293
294 let fs = FakeFs::new(cx.background());
295 fs.insert_tree("/dir", json!({ "test.rs": "" })).await;
296
297 let project = Project::test(fs.clone(), cx);
298 project.update(cx, |project, _| {
299 project.languages().add(Arc::new(language));
300 });
301
302 let worktree_id = project
303 .update(cx, |project, cx| {
304 project.find_or_create_local_worktree("/dir", true, cx)
305 })
306 .await
307 .unwrap()
308 .0
309 .read_with(cx, |tree, _| tree.id());
310
311 let _buffer = project
312 .update(cx, |project, cx| {
313 project.open_buffer((worktree_id, "test.rs"), cx)
314 })
315 .await
316 .unwrap();
317
318 // Set up fake langauge server to return fuzzy matches against
319 // a fixed set of symbol names.
320 let fake_symbol_names = ["one", "ton", "uno"];
321 let fake_server = fake_servers.next().await.unwrap();
322 fake_server.handle_request::<lsp::request::WorkspaceSymbol, _, _>(
323 move |params: lsp::WorkspaceSymbolParams, cx| {
324 let executor = cx.background();
325 async move {
326 let candidates = fake_symbol_names
327 .into_iter()
328 .map(|name| StringMatchCandidate::new(0, name.into()))
329 .collect::<Vec<_>>();
330 let matches = fuzzy::match_strings(
331 &candidates,
332 ¶ms.query,
333 true,
334 100,
335 &Default::default(),
336 executor.clone(),
337 )
338 .await;
339 Ok(Some(
340 matches.into_iter().map(|mat| symbol(&mat.string)).collect(),
341 ))
342 }
343 },
344 );
345
346 // Create the project symbols view.
347 let (_, symbols_view) = cx.add_window(|cx| ProjectSymbolsView::new(project.clone(), cx));
348 let picker = symbols_view.read_with(cx, |symbols_view, _| symbols_view.picker.clone());
349
350 // Spawn multiples updates before the first update completes,
351 // such that in the end, there are no matches. Testing for regression:
352 // https://github.com/zed-industries/zed/issues/861
353 picker.update(cx, |p, cx| {
354 p.update_matches("o".to_string(), cx);
355 p.update_matches("on".to_string(), cx);
356 p.update_matches("onex".to_string(), cx);
357 });
358
359 cx.foreground().run_until_parked();
360 symbols_view.read_with(cx, |symbols_view, _| {
361 assert_eq!(symbols_view.matches.len(), 0);
362 });
363
364 // Spawn more updates such that in the end, there are matches.
365 picker.update(cx, |p, cx| {
366 p.update_matches("one".to_string(), cx);
367 p.update_matches("on".to_string(), cx);
368 });
369
370 cx.foreground().run_until_parked();
371 symbols_view.read_with(cx, |symbols_view, _| {
372 assert_eq!(symbols_view.matches.len(), 2);
373 assert_eq!(symbols_view.matches[0].string, "one");
374 assert_eq!(symbols_view.matches[1].string, "ton");
375 });
376
377 // Spawn more updates such that in the end, there are again no matches.
378 picker.update(cx, |p, cx| {
379 p.update_matches("o".to_string(), cx);
380 p.update_matches("".to_string(), cx);
381 });
382
383 cx.foreground().run_until_parked();
384 symbols_view.read_with(cx, |symbols_view, _| {
385 assert_eq!(symbols_view.matches.len(), 0);
386 });
387 }
388
389 fn symbol(name: &str) -> lsp::SymbolInformation {
390 #[allow(deprecated)]
391 lsp::SymbolInformation {
392 name: name.to_string(),
393 kind: lsp::SymbolKind::FUNCTION,
394 tags: None,
395 deprecated: None,
396 container_name: None,
397 location: lsp::Location::new(
398 lsp::Url::from_file_path("/a/b").unwrap(),
399 lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 0)),
400 ),
401 }
402 }
403}