project_symbols.rs

  1use editor::{Bias, Editor, scroll::Autoscroll, styled_runs_for_code_label};
  2use fuzzy::{StringMatch, StringMatchCandidate};
  3use gpui::{
  4    App, Context, DismissEvent, Entity, FontWeight, ParentElement, StyledText, Task, WeakEntity,
  5    Window, rems,
  6};
  7use ordered_float::OrderedFloat;
  8use picker::{Picker, PickerDelegate};
  9use project::{Project, Symbol};
 10use std::{borrow::Cow, cmp::Reverse, sync::Arc};
 11use theme::ActiveTheme;
 12use util::ResultExt;
 13use workspace::{
 14    Workspace,
 15    ui::{Color, Label, LabelCommon, LabelLike, ListItem, ListItemSpacing, Toggleable, v_flex},
 16};
 17
 18pub fn init(cx: &mut App) {
 19    cx.observe_new(
 20        |workspace: &mut Workspace, _window, _: &mut Context<Workspace>| {
 21            workspace.register_action(
 22                |workspace, _: &workspace::ToggleProjectSymbols, window, cx| {
 23                    let project = workspace.project().clone();
 24                    let handle = cx.entity().downgrade();
 25                    workspace.toggle_modal(window, cx, move |window, cx| {
 26                        let delegate = ProjectSymbolsDelegate::new(handle, project);
 27                        Picker::uniform_list(delegate, window, cx).width(rems(34.))
 28                    })
 29                },
 30            );
 31        },
 32    )
 33    .detach();
 34}
 35
 36pub type ProjectSymbols = Entity<Picker<ProjectSymbolsDelegate>>;
 37
 38pub struct ProjectSymbolsDelegate {
 39    workspace: WeakEntity<Workspace>,
 40    project: Entity<Project>,
 41    selected_match_index: usize,
 42    symbols: Vec<Symbol>,
 43    visible_match_candidates: Vec<StringMatchCandidate>,
 44    external_match_candidates: Vec<StringMatchCandidate>,
 45    show_worktree_root_name: bool,
 46    matches: Vec<StringMatch>,
 47}
 48
 49impl ProjectSymbolsDelegate {
 50    fn new(workspace: WeakEntity<Workspace>, project: Entity<Project>) -> Self {
 51        Self {
 52            workspace,
 53            project,
 54            selected_match_index: 0,
 55            symbols: Default::default(),
 56            visible_match_candidates: Default::default(),
 57            external_match_candidates: Default::default(),
 58            matches: Default::default(),
 59            show_worktree_root_name: false,
 60        }
 61    }
 62
 63    fn filter(&mut self, query: &str, window: &mut Window, cx: &mut Context<Picker<Self>>) {
 64        const MAX_MATCHES: usize = 100;
 65        let mut visible_matches = cx.background_executor().block(fuzzy::match_strings(
 66            &self.visible_match_candidates,
 67            query,
 68            false,
 69            true,
 70            MAX_MATCHES,
 71            &Default::default(),
 72            cx.background_executor().clone(),
 73        ));
 74        let mut external_matches = cx.background_executor().block(fuzzy::match_strings(
 75            &self.external_match_candidates,
 76            query,
 77            false,
 78            true,
 79            MAX_MATCHES - visible_matches.len().min(MAX_MATCHES),
 80            &Default::default(),
 81            cx.background_executor().clone(),
 82        ));
 83        let sort_key_for_match = |mat: &StringMatch| {
 84            let symbol = &self.symbols[mat.candidate_id];
 85            (Reverse(OrderedFloat(mat.score)), symbol.label.filter_text())
 86        };
 87
 88        visible_matches.sort_unstable_by_key(sort_key_for_match);
 89        external_matches.sort_unstable_by_key(sort_key_for_match);
 90        let mut matches = visible_matches;
 91        matches.append(&mut external_matches);
 92
 93        for mat in &mut matches {
 94            let symbol = &self.symbols[mat.candidate_id];
 95            let filter_start = symbol.label.filter_range.start;
 96            for position in &mut mat.positions {
 97                *position += filter_start;
 98            }
 99        }
100
101        self.matches = matches;
102        self.set_selected_index(0, window, cx);
103    }
104}
105
106impl PickerDelegate for ProjectSymbolsDelegate {
107    type ListItem = ListItem;
108    fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
109        "Search project symbols...".into()
110    }
111
112    fn confirm(&mut self, secondary: bool, window: &mut Window, cx: &mut Context<Picker<Self>>) {
113        if let Some(symbol) = self
114            .matches
115            .get(self.selected_match_index)
116            .map(|mat| self.symbols[mat.candidate_id].clone())
117        {
118            let buffer = self.project.update(cx, |project, cx| {
119                project.open_buffer_for_symbol(&symbol, cx)
120            });
121            let symbol = symbol.clone();
122            let workspace = self.workspace.clone();
123            cx.spawn_in(window, async move |_, cx| {
124                let buffer = buffer.await?;
125                workspace.update_in(cx, |workspace, window, cx| {
126                    let position = buffer
127                        .read(cx)
128                        .clip_point_utf16(symbol.range.start, Bias::Left);
129                    let pane = if secondary {
130                        workspace.adjacent_pane(window, cx)
131                    } else {
132                        workspace.active_pane().clone()
133                    };
134
135                    let editor =
136                        workspace.open_project_item::<Editor>(pane, buffer, true, true, window, cx);
137
138                    editor.update(cx, |editor, cx| {
139                        editor.change_selections(Some(Autoscroll::center()), window, cx, |s| {
140                            s.select_ranges([position..position])
141                        });
142                    });
143                })?;
144                anyhow::Ok(())
145            })
146            .detach_and_log_err(cx);
147            cx.emit(DismissEvent);
148        }
149    }
150
151    fn dismissed(&mut self, _window: &mut Window, _cx: &mut Context<Picker<Self>>) {}
152
153    fn match_count(&self) -> usize {
154        self.matches.len()
155    }
156
157    fn selected_index(&self) -> usize {
158        self.selected_match_index
159    }
160
161    fn set_selected_index(
162        &mut self,
163        ix: usize,
164        _window: &mut Window,
165        _cx: &mut Context<Picker<Self>>,
166    ) {
167        self.selected_match_index = ix;
168    }
169
170    fn update_matches(
171        &mut self,
172        query: String,
173        window: &mut Window,
174        cx: &mut Context<Picker<Self>>,
175    ) -> Task<()> {
176        self.filter(&query, window, cx);
177        self.show_worktree_root_name = self.project.read(cx).visible_worktrees(cx).count() > 1;
178        let symbols = self
179            .project
180            .update(cx, |project, cx| project.symbols(&query, cx));
181        cx.spawn_in(window, async move |this, cx| {
182            let symbols = symbols.await.log_err();
183            if let Some(symbols) = symbols {
184                this.update_in(cx, |this, window, cx| {
185                    let delegate = &mut this.delegate;
186                    let project = delegate.project.read(cx);
187                    let (visible_match_candidates, external_match_candidates) = symbols
188                        .iter()
189                        .enumerate()
190                        .map(|(id, symbol)| {
191                            StringMatchCandidate::new(id, &symbol.label.filter_text())
192                        })
193                        .partition(|candidate| {
194                            project
195                                .entry_for_path(&symbols[candidate.id].path, cx)
196                                .map_or(false, |e| !e.is_ignored)
197                        });
198
199                    delegate.visible_match_candidates = visible_match_candidates;
200                    delegate.external_match_candidates = external_match_candidates;
201                    delegate.symbols = symbols;
202                    delegate.filter(&query, window, cx);
203                })
204                .log_err();
205            }
206        })
207    }
208
209    fn render_match(
210        &self,
211        ix: usize,
212        selected: bool,
213        window: &mut Window,
214        cx: &mut Context<Picker<Self>>,
215    ) -> Option<Self::ListItem> {
216        let string_match = &self.matches[ix];
217        let symbol = &self.symbols[string_match.candidate_id];
218        let syntax_runs = styled_runs_for_code_label(&symbol.label, cx.theme().syntax());
219
220        let mut path = symbol.path.path.to_string_lossy();
221        if self.show_worktree_root_name {
222            let project = self.project.read(cx);
223            if let Some(worktree) = project.worktree_for_id(symbol.path.worktree_id, cx) {
224                path = Cow::Owned(format!(
225                    "{}{}{}",
226                    worktree.read(cx).root_name(),
227                    std::path::MAIN_SEPARATOR,
228                    path.as_ref()
229                ));
230            }
231        }
232        let label = symbol.label.text.clone();
233        let path = path.to_string().clone();
234
235        let highlights = gpui::combine_highlights(
236            string_match
237                .positions
238                .iter()
239                .map(|pos| (*pos..pos + 1, FontWeight::BOLD.into())),
240            syntax_runs.map(|(range, mut highlight)| {
241                // Ignore font weight for syntax highlighting, as we'll use it
242                // for fuzzy matches.
243                highlight.font_weight = None;
244                (range, highlight)
245            }),
246        );
247
248        Some(
249            ListItem::new(ix)
250                .inset(true)
251                .spacing(ListItemSpacing::Sparse)
252                .toggle_state(selected)
253                .child(
254                    v_flex()
255                        .child(
256                            LabelLike::new().child(
257                                StyledText::new(label).with_default_highlights(
258                                    &window.text_style().clone(),
259                                    highlights,
260                                ),
261                            ),
262                        )
263                        .child(Label::new(path).color(Color::Muted)),
264                ),
265        )
266    }
267}
268
269#[cfg(test)]
270mod tests {
271    use super::*;
272    use futures::StreamExt;
273    use gpui::{SemanticVersion, TestAppContext, VisualContext};
274    use language::{FakeLspAdapter, Language, LanguageConfig, LanguageMatcher};
275    use lsp::OneOf;
276    use project::FakeFs;
277    use serde_json::json;
278    use settings::SettingsStore;
279    use std::{path::Path, sync::Arc};
280    use util::path;
281
282    #[gpui::test]
283    async fn test_project_symbols(cx: &mut TestAppContext) {
284        init_test(cx);
285
286        let fs = FakeFs::new(cx.executor());
287        fs.insert_tree(path!("/dir"), json!({ "test.rs": "" }))
288            .await;
289
290        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
291
292        let language_registry = project.read_with(cx, |project, _| project.languages().clone());
293        language_registry.add(Arc::new(Language::new(
294            LanguageConfig {
295                name: "Rust".into(),
296                matcher: LanguageMatcher {
297                    path_suffixes: vec!["rs".to_string()],
298                    ..Default::default()
299                },
300                ..Default::default()
301            },
302            None,
303        )));
304        let mut fake_servers = language_registry.register_fake_lsp(
305            "Rust",
306            FakeLspAdapter {
307                capabilities: lsp::ServerCapabilities {
308                    workspace_symbol_provider: Some(OneOf::Left(true)),
309                    ..Default::default()
310                },
311                ..Default::default()
312            },
313        );
314
315        let _buffer = project
316            .update(cx, |project, cx| {
317                project.open_local_buffer_with_lsp(path!("/dir/test.rs"), cx)
318            })
319            .await
320            .unwrap();
321
322        // Set up fake language server to return fuzzy matches against
323        // a fixed set of symbol names.
324        let fake_symbols = [
325            symbol("one", path!("/external")),
326            symbol("ton", path!("/dir/test.rs")),
327            symbol("uno", path!("/dir/test.rs")),
328        ];
329        let fake_server = fake_servers.next().await.unwrap();
330        fake_server.set_request_handler::<lsp::WorkspaceSymbolRequest, _, _>(
331            move |params: lsp::WorkspaceSymbolParams, cx| {
332                let executor = cx.background_executor().clone();
333                let fake_symbols = fake_symbols.clone();
334                async move {
335                    let candidates = fake_symbols
336                        .iter()
337                        .enumerate()
338                        .map(|(id, symbol)| StringMatchCandidate::new(id, &symbol.name))
339                        .collect::<Vec<_>>();
340                    let matches = if params.query.is_empty() {
341                        Vec::new()
342                    } else {
343                        fuzzy::match_strings(
344                            &candidates,
345                            &params.query,
346                            true,
347                            true,
348                            100,
349                            &Default::default(),
350                            executor.clone(),
351                        )
352                        .await
353                    };
354
355                    Ok(Some(lsp::WorkspaceSymbolResponse::Flat(
356                        matches
357                            .into_iter()
358                            .map(|mat| fake_symbols[mat.candidate_id].clone())
359                            .collect(),
360                    )))
361                }
362            },
363        );
364
365        let (workspace, cx) =
366            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
367
368        // Create the project symbols view.
369        let symbols = cx.new_window_entity(|window, cx| {
370            Picker::uniform_list(
371                ProjectSymbolsDelegate::new(workspace.downgrade(), project.clone()),
372                window,
373                cx,
374            )
375        });
376
377        // Spawn multiples updates before the first update completes,
378        // such that in the end, there are no matches. Testing for regression:
379        // https://github.com/zed-industries/zed/issues/861
380        symbols.update_in(cx, |p, window, cx| {
381            p.update_matches("o".to_string(), window, cx);
382            p.update_matches("on".to_string(), window, cx);
383            p.update_matches("onex".to_string(), window, cx);
384        });
385
386        cx.run_until_parked();
387        symbols.read_with(cx, |symbols, _| {
388            assert_eq!(symbols.delegate.matches.len(), 0);
389        });
390
391        // Spawn more updates such that in the end, there are matches.
392        symbols.update_in(cx, |p, window, cx| {
393            p.update_matches("one".to_string(), window, cx);
394            p.update_matches("on".to_string(), window, cx);
395        });
396
397        cx.run_until_parked();
398        symbols.read_with(cx, |symbols, _| {
399            let delegate = &symbols.delegate;
400            assert_eq!(delegate.matches.len(), 2);
401            assert_eq!(delegate.matches[0].string, "ton");
402            assert_eq!(delegate.matches[1].string, "one");
403        });
404
405        // Spawn more updates such that in the end, there are again no matches.
406        symbols.update_in(cx, |p, window, cx| {
407            p.update_matches("o".to_string(), window, cx);
408            p.update_matches("".to_string(), window, cx);
409        });
410
411        cx.run_until_parked();
412        symbols.read_with(cx, |symbols, _| {
413            assert_eq!(symbols.delegate.matches.len(), 0);
414        });
415    }
416
417    fn init_test(cx: &mut TestAppContext) {
418        cx.update(|cx| {
419            let store = SettingsStore::test(cx);
420            cx.set_global(store);
421            theme::init(theme::LoadThemes::JustBase, cx);
422            release_channel::init(SemanticVersion::default(), cx);
423            language::init(cx);
424            Project::init_settings(cx);
425            workspace::init_settings(cx);
426            editor::init(cx);
427        });
428    }
429
430    fn symbol(name: &str, path: impl AsRef<Path>) -> lsp::SymbolInformation {
431        #[allow(deprecated)]
432        lsp::SymbolInformation {
433            name: name.to_string(),
434            kind: lsp::SymbolKind::FUNCTION,
435            tags: None,
436            deprecated: None,
437            container_name: None,
438            location: lsp::Location::new(
439                lsp::Url::from_file_path(path.as_ref()).unwrap(),
440                lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 0)),
441            ),
442        }
443    }
444}