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