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, MouseState, MutableAppContext,
7 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 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.change_selections(Some(Autoscroll::Center), cx, |s| {
149 s.select_ranges([position..position])
150 });
151 });
152 });
153 Ok::<_, anyhow::Error>(())
154 })
155 .detach_and_log_err(cx);
156 workspace.dismiss_modal(cx);
157 }
158 }
159 }
160}
161
162impl PickerDelegate for ProjectSymbolsView {
163 fn confirm(&mut self, cx: &mut ViewContext<Self>) {
164 if let Some(symbol) = self
165 .matches
166 .get(self.selected_match_index)
167 .map(|mat| self.symbols[mat.candidate_id].clone())
168 {
169 cx.emit(Event::Selected(symbol));
170 }
171 }
172
173 fn dismiss(&mut self, cx: &mut ViewContext<Self>) {
174 cx.emit(Event::Dismissed);
175 }
176
177 fn match_count(&self) -> usize {
178 self.matches.len()
179 }
180
181 fn selected_index(&self) -> usize {
182 self.selected_match_index
183 }
184
185 fn set_selected_index(&mut self, ix: usize, cx: &mut ViewContext<Self>) {
186 self.selected_match_index = ix;
187 cx.notify();
188 }
189
190 fn update_matches(&mut self, query: String, cx: &mut ViewContext<Self>) -> Task<()> {
191 self.filter(&query, cx);
192 self.show_worktree_root_name = self.project.read(cx).visible_worktrees(cx).count() > 1;
193 let symbols = self
194 .project
195 .update(cx, |project, cx| project.symbols(&query, cx));
196 self.pending_update = cx.spawn_weak(|this, mut cx| async move {
197 let symbols = symbols.await.log_err();
198 if let Some(this) = this.upgrade(&cx) {
199 if let Some(symbols) = symbols {
200 this.update(&mut cx, |this, cx| {
201 this.match_candidates = symbols
202 .iter()
203 .enumerate()
204 .map(|(id, symbol)| {
205 StringMatchCandidate::new(
206 id,
207 symbol.label.text[symbol.label.filter_range.clone()]
208 .to_string(),
209 )
210 })
211 .collect();
212 this.symbols = symbols;
213 this.filter(&query, cx);
214 });
215 }
216 }
217 });
218 Task::ready(())
219 }
220
221 fn render_match(
222 &self,
223 ix: usize,
224 mouse_state: MouseState,
225 selected: bool,
226 cx: &AppContext,
227 ) -> ElementBox {
228 let string_match = &self.matches[ix];
229 let settings = cx.global::<Settings>();
230 let style = &settings.theme.picker.item;
231 let current_style = style.style_for(mouse_state, selected);
232 let symbol = &self.symbols[string_match.candidate_id];
233 let syntax_runs = styled_runs_for_code_label(&symbol.label, &settings.theme.editor.syntax);
234
235 let mut path = symbol.path.to_string_lossy();
236 if self.show_worktree_root_name {
237 let project = self.project.read(cx);
238 if let Some(worktree) = project.worktree_for_id(symbol.worktree_id, cx) {
239 path = Cow::Owned(format!(
240 "{}{}{}",
241 worktree.read(cx).root_name(),
242 std::path::MAIN_SEPARATOR,
243 path.as_ref()
244 ));
245 }
246 }
247
248 Flex::column()
249 .with_child(
250 Text::new(symbol.label.text.clone(), current_style.label.text.clone())
251 .with_soft_wrap(false)
252 .with_highlights(combine_syntax_and_fuzzy_match_highlights(
253 &symbol.label.text,
254 current_style.label.text.clone().into(),
255 syntax_runs,
256 &string_match.positions,
257 ))
258 .boxed(),
259 )
260 .with_child(
261 // Avoid styling the path differently when it is selected, since
262 // the symbol's syntax highlighting doesn't change when selected.
263 Label::new(path.to_string(), style.default.label.clone()).boxed(),
264 )
265 .contained()
266 .with_style(current_style.container)
267 .boxed()
268 }
269}
270
271#[cfg(test)]
272mod tests {
273 use super::*;
274 use futures::StreamExt;
275 use gpui::{serde_json::json, TestAppContext};
276 use language::{FakeLspAdapter, Language, LanguageConfig};
277 use project::FakeFs;
278 use std::sync::Arc;
279
280 #[gpui::test]
281 async fn test_project_symbols(cx: &mut TestAppContext) {
282 cx.foreground().forbid_parking();
283 cx.update(|cx| cx.set_global(Settings::test(cx)));
284
285 let mut language = Language::new(
286 LanguageConfig {
287 name: "Rust".into(),
288 path_suffixes: vec!["rs".to_string()],
289 ..Default::default()
290 },
291 None,
292 );
293 let mut fake_servers = language.set_fake_lsp_adapter(FakeLspAdapter::default());
294
295 let fs = FakeFs::new(cx.background());
296 fs.insert_tree("/dir", json!({ "test.rs": "" })).await;
297
298 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
299 project.update(cx, |project, _| project.languages().add(Arc::new(language)));
300
301 let _buffer = project
302 .update(cx, |project, cx| {
303 project.open_local_buffer("/dir/test.rs", cx)
304 })
305 .await
306 .unwrap();
307
308 // Set up fake langauge server to return fuzzy matches against
309 // a fixed set of symbol names.
310 let fake_symbol_names = ["one", "ton", "uno"];
311 let fake_server = fake_servers.next().await.unwrap();
312 fake_server.handle_request::<lsp::request::WorkspaceSymbol, _, _>(
313 move |params: lsp::WorkspaceSymbolParams, cx| {
314 let executor = cx.background();
315 async move {
316 let candidates = fake_symbol_names
317 .into_iter()
318 .map(|name| StringMatchCandidate::new(0, name.into()))
319 .collect::<Vec<_>>();
320 let matches = if params.query.is_empty() {
321 Vec::new()
322 } else {
323 fuzzy::match_strings(
324 &candidates,
325 ¶ms.query,
326 true,
327 100,
328 &Default::default(),
329 executor.clone(),
330 )
331 .await
332 };
333
334 Ok(Some(
335 matches.into_iter().map(|mat| symbol(&mat.string)).collect(),
336 ))
337 }
338 },
339 );
340
341 // Create the project symbols view.
342 let (_, symbols_view) = cx.add_window(|cx| ProjectSymbolsView::new(project.clone(), cx));
343 let picker = symbols_view.read_with(cx, |symbols_view, _| symbols_view.picker.clone());
344
345 // Spawn multiples updates before the first update completes,
346 // such that in the end, there are no matches. Testing for regression:
347 // https://github.com/zed-industries/zed/issues/861
348 picker.update(cx, |p, cx| {
349 p.update_matches("o".to_string(), cx);
350 p.update_matches("on".to_string(), cx);
351 p.update_matches("onex".to_string(), cx);
352 });
353
354 cx.foreground().run_until_parked();
355 symbols_view.read_with(cx, |symbols_view, _| {
356 assert_eq!(symbols_view.matches.len(), 0);
357 });
358
359 // Spawn more updates such that in the end, there are matches.
360 picker.update(cx, |p, cx| {
361 p.update_matches("one".to_string(), cx);
362 p.update_matches("on".to_string(), cx);
363 });
364
365 cx.foreground().run_until_parked();
366 symbols_view.read_with(cx, |symbols_view, _| {
367 assert_eq!(symbols_view.matches.len(), 2);
368 assert_eq!(symbols_view.matches[0].string, "one");
369 assert_eq!(symbols_view.matches[1].string, "ton");
370 });
371
372 // Spawn more updates such that in the end, there are again no matches.
373 picker.update(cx, |p, cx| {
374 p.update_matches("o".to_string(), cx);
375 p.update_matches("".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
384 fn symbol(name: &str) -> lsp::SymbolInformation {
385 #[allow(deprecated)]
386 lsp::SymbolInformation {
387 name: name.to_string(),
388 kind: lsp::SymbolKind::FUNCTION,
389 tags: None,
390 deprecated: None,
391 container_name: None,
392 location: lsp::Location::new(
393 lsp::Url::from_file_path("/a/b").unwrap(),
394 lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 0)),
395 ),
396 }
397 }
398}