Skip to repository content627 lines · 23.8 KB · rust
tenant.openagents/omega
No repository description is available.
OpenAgents Git authority 2026-07-28T03:01:06.023Z Public web read
NIP-34 coordinate
30617:7649603503856e5148d571eac2766b288a8ff1e9e35d380337a1d2b0015b4f92:omegaMaintainersHidden in public view
References2 branches · 1 tag
Read-only clone
git clone https://openagents.com/git/tenant.openagents/omega.gitBrowse files
project_symbols.rs
1use editor::{Bias, Editor, SelectionEffects, scroll::Autoscroll, styled_runs_for_code_label};
2use fuzzy::{StringMatch, StringMatchCandidate};
3use gpui::{
4 App, Context, DismissEvent, Entity, HighlightStyle, ParentElement, StyledText, Task, TaskExt,
5 TextStyle, WeakEntity, Window, relative,
6};
7use ordered_float::OrderedFloat;
8use picker::{Picker, PickerDelegate, PreviewUpdate};
9use project::{Project, Symbol, lsp_store::SymbolLocation};
10use settings::Settings;
11use std::{cmp::Reverse, sync::Arc};
12use theme::ActiveTheme;
13use theme_settings::ThemeSettings;
14use util::ResultExt;
15use workspace::{
16 Workspace,
17 ui::{LabelLike, ListItem, ListItemSpacing, prelude::*},
18};
19
20pub fn init(cx: &mut App) {
21 cx.observe_new(
22 |workspace: &mut Workspace, _window, _: &mut Context<Workspace>| {
23 workspace.register_action(
24 |workspace, _: &workspace::ToggleProjectSymbols, window, cx| {
25 let project = workspace.project().clone();
26 let handle = cx.entity().downgrade();
27 workspace.toggle_modal(window, cx, move |window, cx| {
28 let delegate = ProjectSymbolsDelegate::new(handle, project.clone());
29 let preview = picker_preview::editor_preview(project, window, cx);
30 Picker::uniform_list_with_preview(delegate, preview, window, cx)
31 })
32 },
33 );
34 },
35 )
36 .detach();
37}
38
39pub type ProjectSymbols = Entity<Picker<ProjectSymbolsDelegate>>;
40
41pub struct ProjectSymbolsDelegate {
42 workspace: WeakEntity<Workspace>,
43 project: Entity<Project>,
44 selected_match_index: usize,
45 symbols: Vec<Symbol>,
46 visible_match_candidates: Vec<StringMatchCandidate>,
47 external_match_candidates: Vec<StringMatchCandidate>,
48 show_worktree_root_name: bool,
49 matches: Vec<StringMatch>,
50}
51
52impl ProjectSymbolsDelegate {
53 fn new(workspace: WeakEntity<Workspace>, project: Entity<Project>) -> Self {
54 Self {
55 workspace,
56 project,
57 selected_match_index: 0,
58 symbols: Default::default(),
59 visible_match_candidates: Default::default(),
60 external_match_candidates: Default::default(),
61 matches: Default::default(),
62 show_worktree_root_name: false,
63 }
64 }
65
66 // Note if you make changes to this, also change `agent_ui::completion_provider::search_symbols`
67 fn filter(&mut self, query: &str, window: &mut Window, cx: &mut Context<Picker<Self>>) {
68 const MAX_MATCHES: usize = 100;
69 let mut visible_matches = cx.foreground_executor().block_on(fuzzy::match_strings(
70 &self.visible_match_candidates,
71 query,
72 false,
73 true,
74 MAX_MATCHES,
75 &Default::default(),
76 cx.background_executor().clone(),
77 ));
78 let mut external_matches = cx.foreground_executor().block_on(fuzzy::match_strings(
79 &self.external_match_candidates,
80 query,
81 false,
82 true,
83 MAX_MATCHES - visible_matches.len().min(MAX_MATCHES),
84 &Default::default(),
85 cx.background_executor().clone(),
86 ));
87 let sort_key_for_match = |mat: &StringMatch| {
88 let symbol = &self.symbols[mat.candidate_id];
89 (Reverse(OrderedFloat(mat.score)), symbol.label.filter_text())
90 };
91
92 visible_matches.sort_unstable_by_key(sort_key_for_match);
93 external_matches.sort_unstable_by_key(sort_key_for_match);
94 let mut matches = visible_matches;
95 matches.append(&mut external_matches);
96
97 for mat in &mut matches {
98 let symbol = &self.symbols[mat.candidate_id];
99 let filter_start = symbol.label.filter_range.start;
100 for position in &mut mat.positions {
101 *position += filter_start;
102 }
103 }
104
105 self.matches = matches;
106 self.set_selected_index(0, window, cx);
107 }
108}
109
110impl PickerDelegate for ProjectSymbolsDelegate {
111 type ListItem = ListItem;
112
113 fn name() -> &'static str {
114 "project symbols"
115 }
116 fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
117 "Search project symbols...".into()
118 }
119
120 fn confirm(&mut self, secondary: bool, window: &mut Window, cx: &mut Context<Picker<Self>>) {
121 if let Some(symbol) = self
122 .matches
123 .get(self.selected_match_index)
124 .map(|mat| self.symbols[mat.candidate_id].clone())
125 {
126 let buffer = self.project.update(cx, |project, cx| {
127 project.open_buffer_for_symbol(&symbol, cx)
128 });
129 let symbol = symbol.clone();
130 let workspace = self.workspace.clone();
131 cx.spawn_in(window, async move |_, cx| {
132 let buffer = buffer.await?;
133 workspace.update_in(cx, |workspace, window, cx| {
134 let position = buffer
135 .read(cx)
136 .clip_point_utf16(symbol.range.start, Bias::Left);
137 let pane = if secondary {
138 workspace.adjacent_pane(window, cx)
139 } else {
140 workspace.active_pane().clone()
141 };
142
143 let editor = workspace.open_project_item::<Editor>(
144 pane, buffer, true, true, true, true, window, cx,
145 );
146
147 editor.update(cx, |editor, cx| {
148 let multibuffer_snapshot = editor.buffer().read(cx).snapshot(cx);
149 let Some(buffer_snapshot) = multibuffer_snapshot.as_singleton() else {
150 return;
151 };
152 let text_anchor = buffer_snapshot.anchor_before(position);
153 let Some(anchor) = multibuffer_snapshot.anchor_in_buffer(text_anchor)
154 else {
155 return;
156 };
157 editor.change_selections(
158 SelectionEffects::scroll(Autoscroll::center()),
159 window,
160 cx,
161 |s| s.select_ranges([anchor..anchor]),
162 );
163 });
164 })?;
165 anyhow::Ok(())
166 })
167 .detach_and_log_err(cx);
168 cx.emit(DismissEvent);
169 }
170 }
171
172 fn dismissed(&mut self, _window: &mut Window, _cx: &mut Context<Picker<Self>>) {}
173
174 fn match_count(&self) -> usize {
175 self.matches.len()
176 }
177
178 fn selected_index(&self) -> usize {
179 self.selected_match_index
180 }
181
182 fn set_selected_index(
183 &mut self,
184 ix: usize,
185 _window: &mut Window,
186 _cx: &mut Context<Picker<Self>>,
187 ) {
188 self.selected_match_index = ix;
189 }
190
191 fn try_get_preview_data_for_match(&self, _cx: &App) -> Option<PreviewUpdate> {
192 let candidate_id = self.matches.get(self.selected_match_index)?.candidate_id;
193 let symbol = self.symbols.get(candidate_id)?.clone();
194 Some(PreviewUpdate::from_symbol(symbol))
195 }
196
197 fn update_matches(
198 &mut self,
199 query: String,
200 window: &mut Window,
201 cx: &mut Context<Picker<Self>>,
202 ) -> Task<()> {
203 // Try to support rust-analyzer's path based symbols feature which
204 // allows to search by rust path syntax, in that case we only want to
205 // filter names by the last segment
206 // Ideally this was a first class LSP feature (rich queries)
207 let query_filter = query
208 .rsplit_once("::")
209 .map_or(&*query, |(_, suffix)| suffix)
210 .to_owned();
211 self.filter(&query_filter, window, cx);
212 self.show_worktree_root_name = self.project.read(cx).visible_worktrees(cx).count() > 1;
213 let symbols = self
214 .project
215 .update(cx, |project, cx| project.symbols(&query, cx));
216 cx.spawn_in(window, async move |this, cx| {
217 let symbols = symbols.await.log_err();
218 if let Some(symbols) = symbols {
219 this.update_in(cx, |this, window, cx| {
220 let delegate = &mut this.delegate;
221 let project = delegate.project.read(cx);
222 let (visible_match_candidates, external_match_candidates) = symbols
223 .iter()
224 .enumerate()
225 .map(|(id, symbol)| {
226 StringMatchCandidate::new(id, symbol.label.filter_text())
227 })
228 .partition(|candidate| {
229 if let SymbolLocation::InProject(path) = &symbols[candidate.id].path {
230 project
231 .entry_for_path(path, cx)
232 .is_some_and(|e| !e.is_ignored)
233 } else {
234 false
235 }
236 });
237
238 delegate.visible_match_candidates = visible_match_candidates;
239 delegate.external_match_candidates = external_match_candidates;
240 delegate.symbols = symbols;
241 delegate.filter(&query_filter, window, cx);
242 })
243 .log_err();
244 }
245 })
246 }
247
248 fn render_match(
249 &self,
250 ix: usize,
251 selected: bool,
252 _window: &mut Window,
253 cx: &mut Context<Picker<Self>>,
254 ) -> Option<Self::ListItem> {
255 let path_style = self.project.read(cx).path_style(cx);
256 let string_match = &self.matches.get(ix)?;
257 let symbol = &self.symbols.get(string_match.candidate_id)?;
258 let theme = cx.theme();
259 let local_player = theme.players().local();
260 let syntax_runs = styled_runs_for_code_label(&symbol.label, theme.syntax(), &local_player);
261
262 let path = match &symbol.path {
263 SymbolLocation::InProject(project_path) => {
264 let project = self.project.read(cx);
265 let mut path = project_path.path.to_rel_path_buf();
266 if self.show_worktree_root_name
267 && let Some(worktree) = project.worktree_for_id(project_path.worktree_id, cx)
268 {
269 path = worktree.read(cx).root_name().join(&path);
270 }
271 path.display(path_style).into_owned().into()
272 }
273 SymbolLocation::OutsideProject {
274 abs_path,
275 signature: _,
276 } => abs_path.to_string_lossy(),
277 };
278 let label = symbol.label.text.clone();
279 let line_number = symbol.range.start.0.row + 1;
280 let path = path.into_owned();
281
282 let settings = ThemeSettings::get_global(cx);
283
284 let text_style = TextStyle {
285 color: cx.theme().colors().text,
286 font_family: settings.buffer_font.family.clone(),
287 font_features: settings.buffer_font.features.clone(),
288 font_fallbacks: settings.buffer_font.fallbacks.clone(),
289 font_size: settings.buffer_font_size(cx).into(),
290 font_weight: settings.buffer_font.weight,
291 line_height: relative(1.),
292 ..Default::default()
293 };
294
295 let highlight_style = HighlightStyle {
296 background_color: Some(cx.theme().colors().text_accent.alpha(0.3)),
297 ..Default::default()
298 };
299 let custom_highlights = string_match
300 .positions
301 .iter()
302 .map(|pos| (*pos..label.ceil_char_boundary(pos + 1), highlight_style));
303
304 let highlights = gpui::combine_highlights(custom_highlights, syntax_runs);
305
306 Some(
307 ListItem::new(ix)
308 .inset(true)
309 .spacing(ListItemSpacing::Sparse)
310 .toggle_state(selected)
311 .child(
312 v_flex()
313 .child(
314 LabelLike::new().child(
315 StyledText::new(&label)
316 .with_default_highlights(&text_style, highlights),
317 ),
318 )
319 .child(
320 h_flex()
321 .child(Label::new(path).size(LabelSize::Small).color(Color::Muted))
322 .child(
323 Label::new(format!(":{}", line_number))
324 .size(LabelSize::Small)
325 .color(Color::Placeholder),
326 ),
327 ),
328 ),
329 )
330 }
331}
332
333#[cfg(test)]
334mod tests {
335 use super::*;
336 use futures::StreamExt;
337 use gpui::{TestAppContext, VisualContext};
338 use language::{FakeLspAdapter, Language, LanguageConfig, LanguageMatcher};
339 use lsp::OneOf;
340 use project::FakeFs;
341 use serde_json::json;
342 use settings::SettingsStore;
343 use std::{path::Path, sync::Arc};
344 use util::path;
345 use workspace::MultiWorkspace;
346
347 #[gpui::test]
348 async fn test_project_symbols(cx: &mut TestAppContext) {
349 init_test(cx);
350
351 let fs = FakeFs::new(cx.executor());
352 fs.insert_tree(path!("/dir"), json!({ "test.rs": "" }))
353 .await;
354
355 let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
356
357 let language_registry = project.read_with(cx, |project, _| project.languages().clone());
358 language_registry.add(Arc::new(Language::new(
359 LanguageConfig {
360 name: "Rust".into(),
361 matcher: (LanguageMatcher {
362 path_suffixes: vec!["rs".to_string()],
363 ..Default::default()
364 })
365 .into(),
366 ..Default::default()
367 },
368 None,
369 )));
370 let mut fake_servers = language_registry.register_fake_lsp(
371 "Rust",
372 FakeLspAdapter {
373 capabilities: lsp::ServerCapabilities {
374 workspace_symbol_provider: Some(OneOf::Left(true)),
375 ..Default::default()
376 },
377 ..Default::default()
378 },
379 );
380
381 let _buffer = project
382 .update(cx, |project, cx| {
383 project.open_local_buffer_with_lsp(path!("/dir/test.rs"), cx)
384 })
385 .await
386 .unwrap();
387
388 // Set up fake language server to return fuzzy matches against
389 // a fixed set of symbol names.
390 let fake_symbols = [
391 symbol("one", path!("/external")),
392 symbol("ton", path!("/dir/test.rs")),
393 symbol("uno", path!("/dir/test.rs")),
394 ];
395 let fake_server = fake_servers.next().await.unwrap();
396 fake_server.set_request_handler::<lsp::WorkspaceSymbolRequest, _, _>(
397 move |params: lsp::WorkspaceSymbolParams, cx| {
398 let executor = cx.background_executor().clone();
399 let fake_symbols = fake_symbols.clone();
400 async move {
401 let (query, prefixed) = match params.query.strip_prefix("dir::") {
402 Some(query) => (query, true),
403 None => (&*params.query, false),
404 };
405 let candidates = fake_symbols
406 .iter()
407 .enumerate()
408 .filter(|(_, symbol)| {
409 !prefixed || symbol.location.uri.path().contains("dir")
410 })
411 .map(|(id, symbol)| StringMatchCandidate::new(id, &symbol.name))
412 .collect::<Vec<_>>();
413 let matches = if query.is_empty() {
414 Vec::new()
415 } else {
416 fuzzy::match_strings(
417 &candidates,
418 &query,
419 true,
420 true,
421 100,
422 &Default::default(),
423 executor.clone(),
424 )
425 .await
426 };
427
428 Ok(Some(lsp::WorkspaceSymbolResponse::Flat(
429 matches
430 .into_iter()
431 .map(|mat| fake_symbols[mat.candidate_id].clone())
432 .collect(),
433 )))
434 }
435 },
436 );
437
438 let (multi_workspace, cx) =
439 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
440 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
441
442 // Create the project symbols view.
443 let symbols = cx.new_window_entity(|window, cx| {
444 Picker::uniform_list(
445 ProjectSymbolsDelegate::new(workspace.downgrade(), project.clone()),
446 window,
447 cx,
448 )
449 });
450
451 // Spawn multiples updates before the first update completes,
452 // such that in the end, there are no matches. Testing for regression:
453 // https://github.com/zed-industries/zed/issues/861
454 symbols.update_in(cx, |p, window, cx| {
455 p.update_matches("o".to_string(), window, cx);
456 p.update_matches("on".to_string(), window, cx);
457 p.update_matches("onex".to_string(), window, cx);
458 });
459
460 cx.run_until_parked();
461 symbols.read_with(cx, |symbols, _| {
462 assert_eq!(symbols.delegate.matches.len(), 0);
463 });
464
465 // Spawn more updates such that in the end, there are matches.
466 symbols.update_in(cx, |p, window, cx| {
467 p.update_matches("one".to_string(), window, cx);
468 p.update_matches("on".to_string(), window, cx);
469 });
470
471 cx.run_until_parked();
472 symbols.read_with(cx, |symbols, _| {
473 let delegate = &symbols.delegate;
474 assert_eq!(delegate.matches.len(), 2);
475 assert_eq!(delegate.matches[0].string, "ton");
476 assert_eq!(delegate.matches[1].string, "one");
477 });
478
479 // Spawn more updates such that in the end, there are again no matches.
480 symbols.update_in(cx, |p, window, cx| {
481 p.update_matches("o".to_string(), window, cx);
482 p.update_matches("".to_string(), window, cx);
483 });
484
485 cx.run_until_parked();
486 symbols.read_with(cx, |symbols, _| {
487 assert_eq!(symbols.delegate.matches.len(), 0);
488 });
489
490 // Check that rust-analyzer path style symbols work
491 symbols.update_in(cx, |p, window, cx| {
492 p.update_matches("dir::to".to_string(), window, cx);
493 });
494
495 cx.run_until_parked();
496 symbols.read_with(cx, |symbols, _| {
497 assert_eq!(symbols.delegate.matches.len(), 1);
498 });
499 }
500
501 #[gpui::test]
502 async fn test_project_symbols_renders_utf8_match(cx: &mut TestAppContext) {
503 init_test(cx);
504
505 let fs = FakeFs::new(cx.executor());
506 fs.insert_tree(path!("/dir"), json!({ "test.rs": "" }))
507 .await;
508
509 let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
510
511 let language_registry = project.read_with(cx, |project, _| project.languages().clone());
512 language_registry.add(Arc::new(Language::new(
513 LanguageConfig {
514 name: "Rust".into(),
515 matcher: (LanguageMatcher {
516 path_suffixes: vec!["rs".to_string()],
517 ..Default::default()
518 })
519 .into(),
520 ..Default::default()
521 },
522 None,
523 )));
524 let mut fake_servers = language_registry.register_fake_lsp(
525 "Rust",
526 FakeLspAdapter {
527 capabilities: lsp::ServerCapabilities {
528 workspace_symbol_provider: Some(OneOf::Left(true)),
529 ..Default::default()
530 },
531 ..Default::default()
532 },
533 );
534
535 let _buffer = project
536 .update(cx, |project, cx| {
537 project.open_local_buffer_with_lsp(path!("/dir/test.rs"), cx)
538 })
539 .await
540 .unwrap();
541
542 let fake_symbols = [symbol("안녕", path!("/dir/test.rs"))];
543 let fake_server = fake_servers.next().await.unwrap();
544 fake_server.set_request_handler::<lsp::WorkspaceSymbolRequest, _, _>(
545 move |params: lsp::WorkspaceSymbolParams, cx| {
546 let executor = cx.background_executor().clone();
547 let fake_symbols = fake_symbols.clone();
548 async move {
549 let candidates = fake_symbols
550 .iter()
551 .enumerate()
552 .map(|(id, symbol)| StringMatchCandidate::new(id, &symbol.name))
553 .collect::<Vec<_>>();
554 let matches = fuzzy::match_strings(
555 &candidates,
556 ¶ms.query,
557 true,
558 true,
559 100,
560 &Default::default(),
561 executor,
562 )
563 .await;
564
565 Ok(Some(lsp::WorkspaceSymbolResponse::Flat(
566 matches
567 .into_iter()
568 .map(|mat| fake_symbols[mat.candidate_id].clone())
569 .collect(),
570 )))
571 }
572 },
573 );
574
575 let (multi_workspace, cx) =
576 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
577 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
578
579 let symbols = cx.new_window_entity(|window, cx| {
580 Picker::uniform_list(
581 ProjectSymbolsDelegate::new(workspace.downgrade(), project.clone()),
582 window,
583 cx,
584 )
585 });
586
587 symbols.update_in(cx, |p, window, cx| {
588 p.update_matches("안".to_string(), window, cx);
589 });
590
591 cx.run_until_parked();
592 symbols.read_with(cx, |symbols, _| {
593 assert_eq!(symbols.delegate.matches.len(), 1);
594 assert_eq!(symbols.delegate.matches[0].string, "안녕");
595 });
596
597 symbols.update_in(cx, |p, window, cx| {
598 assert!(p.delegate.render_match(0, false, window, cx).is_some());
599 });
600 }
601
602 fn init_test(cx: &mut TestAppContext) {
603 cx.update(|cx| {
604 let store = SettingsStore::test(cx);
605 cx.set_global(store);
606 theme_settings::init(theme::LoadThemes::JustBase, cx);
607 release_channel::init(semver::Version::new(0, 0, 0), cx);
608 editor::init(cx);
609 });
610 }
611
612 fn symbol(name: &str, path: impl AsRef<Path>) -> lsp::SymbolInformation {
613 #[allow(deprecated)]
614 lsp::SymbolInformation {
615 name: name.to_string(),
616 kind: lsp::SymbolKind::FUNCTION,
617 tags: None,
618 deprecated: None,
619 container_name: None,
620 location: lsp::Location::new(
621 lsp::Uri::from_file_path(path.as_ref()).unwrap(),
622 lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 0)),
623 ),
624 }
625 }
626}
627