From 954180beb027e1c87c0df8447e86c248fbc57602 Mon Sep 17 00:00:00 2001 From: audichuang <72485427+audichuang@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:51:27 +0800 Subject: [PATCH] feat(java): Spring bean gutter icons between beans and injection points (#7589) Java files in Spring projects get gutter icons between beans and the places they are injected: an injection point (field, constructor or @Bean method parameter) navigates to the beans it receives, and a bean declaration to its injection points. One target jumps straight there; several open the inheritance chooser, with candidates marked. The editor asks once per file for a server-independent SpringBeanMarker shape, cancels stale requests and asks again after edits, when the server reports changed markers, or when a server settles or stops. java-analyzer is the first source (java-analyzer/springBeanMarkers, declared in its experimental capabilities); without such a server nothing is requested. Icons follow Gutter Icons, excluded folders and the server's features. Refs #7140 Co-authored-by: audichuang <72485427+audichuang@users.noreply.github.com> --- crates/ide-core/src/event.rs | 2 + crates/ide-host/src/ops/lsp.rs | 20 ++ crates/ide-lsp/src/caps.rs | 8 +- crates/ide-lsp/src/handler.rs | 3 + crates/ide-lsp/src/lib.rs | 1 + crates/ide-lsp/src/spring_beans.rs | 97 ++++++ crates/ide-lsp/src/types.rs | 36 ++ crates/ide-lsp/tests/mock_server.rs | 78 +++++ fixtures/README.md | 1 + fixtures/spring-app/pom.xml | 24 ++ .../main/java/com/example/shop/AppConfig.java | 22 ++ .../main/java/com/example/shop/Checkout.java | 38 +++ .../java/com/example/shop/EmailNotifier.java | 11 + .../main/java/com/example/shop/Notifier.java | 6 + .../java/com/example/shop/OrderService.java | 10 + .../java/com/example/shop/SmsNotifier.java | 11 + src-tauri/tests/commands.snap | 1 + src/bindings.ts | 33 +- src/editor/lsp/index.ts | 8 +- src/editor/lsp/navigation.ts | 4 +- src/editor/navigation/implementationGutter.ts | 27 +- src/editor/navigation/index.ts | 1 + .../navigation/springBeanGutter.test.ts | 311 ++++++++++++++++++ src/editor/navigation/springBeanGutter.ts | 295 +++++++++++++++++ src/platform/locales/text/en.json | 6 + src/platform/locales/text/zh.json | 6 + src/ui/icons.tsx | 2 + src/ui/openidea/gutter/springBeanToBean.svg | 6 + .../openidea/gutter/springBeanToBean_dark.svg | 6 + .../gutter/springBeanToInjectionPoint.svg | 6 + .../springBeanToInjectionPoint_dark.svg | 6 + 31 files changed, 1073 insertions(+), 13 deletions(-) create mode 100644 crates/ide-lsp/src/spring_beans.rs create mode 100644 fixtures/spring-app/pom.xml create mode 100644 fixtures/spring-app/src/main/java/com/example/shop/AppConfig.java create mode 100644 fixtures/spring-app/src/main/java/com/example/shop/Checkout.java create mode 100644 fixtures/spring-app/src/main/java/com/example/shop/EmailNotifier.java create mode 100644 fixtures/spring-app/src/main/java/com/example/shop/Notifier.java create mode 100644 fixtures/spring-app/src/main/java/com/example/shop/OrderService.java create mode 100644 fixtures/spring-app/src/main/java/com/example/shop/SmsNotifier.java create mode 100644 src/editor/navigation/springBeanGutter.test.ts create mode 100644 src/editor/navigation/springBeanGutter.ts create mode 100644 src/ui/openidea/gutter/springBeanToBean.svg create mode 100644 src/ui/openidea/gutter/springBeanToBean_dark.svg create mode 100644 src/ui/openidea/gutter/springBeanToInjectionPoint.svg create mode 100644 src/ui/openidea/gutter/springBeanToInjectionPoint_dark.svg diff --git a/crates/ide-core/src/event.rs b/crates/ide-core/src/event.rs index c23f44f81e..d92d7e4845 100644 --- a/crates/ide-core/src/event.rs +++ b/crates/ide-core/src/event.rs @@ -447,6 +447,8 @@ pub enum LspRefreshKind { Inheritance, /// The Dart server published a document's Flutter outline. FlutterOutline, + /// Spring bean markers of open documents may have changed. + SpringBeanMarkers, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] diff --git a/crates/ide-host/src/ops/lsp.rs b/crates/ide-host/src/ops/lsp.rs index 227e5130cc..199bd7c408 100644 --- a/crates/ide-host/src/ops/lsp.rs +++ b/crates/ide-host/src/ops/lsp.rs @@ -675,6 +675,25 @@ pub async fn lsp_switch_source_header( Ok(result?.map(|path| path.to_string_lossy().into_owned())) } +/// The document's Spring bean markers (injection points and bean declarations with their +/// targets); `None` when no server attached to it provides them. Cancel with `cancel_request(request)`. +#[command(trust = trusted)] +pub async fn lsp_spring_bean_markers( + host: &Host, + window: &str, + request: RequestId, + doc: DocId, +) -> IdeResult>> { + let lsp = host.project(window)?.lsp.clone(); + let cancel = host.begin_request(request); + let result = tokio::select! { + result = lsp.spring_bean_markers(doc, cancel.clone()) => result, + _ = cancel.cancelled() => Err(ide_core::IdeError::cancelled()), + }; + host.end_request(request); + result +} + /// Go to Source Definition (vtsls): the JavaScript implementation of the symbol at `pos` /// instead of its `.d.ts`. Cancel with `cancel_request(request)`. #[command(trust = trusted)] @@ -3462,6 +3481,7 @@ ide_command::domain!( lsp_hover, lsp_implementation_locations, lsp_file_references, + lsp_spring_bean_markers, lsp_switch_source_header, lsp_source_definition, lsp_open_typescript_file, diff --git a/crates/ide-lsp/src/caps.rs b/crates/ide-lsp/src/caps.rs index 0baedf7bd4..8faa38b87c 100644 --- a/crates/ide-lsp/src/caps.rs +++ b/crates/ide-lsp/src/caps.rs @@ -168,7 +168,8 @@ pub fn client_capabilities() -> Value { "typeHierarchy": { "dynamicRegistration": false } }, // rust-analyzer: report when the project has loaded (`quiescent`). - "experimental": { "serverStatusNotification": true }, + // java-analyzer: Spring bean markers of open documents may have changed (`spring_beans.rs`). + "experimental": { "serverStatusNotification": true, "java-analyzer/springBeanMarkersChanged": true }, // Jupyter notebooks: code cells are synced with `notebookDocument/*` (see `notebook.rs`). "notebookDocument": { "synchronization": { "dynamicRegistration": false, "executionSummarySupport": false } } }) @@ -361,6 +362,11 @@ impl Restriction { self.keys.as_ref().is_none_or(|k| k.contains(&key)) } + /// Whether the server is used for go-to-implementation navigation (Spring bean markers too). + pub fn implementation(&self) -> bool { + self.allows("implementationProvider") + } + /// Whether the server's `publishDiagnostics` are shown. pub fn diagnostics(&self) -> bool { self.allows("diagnosticProvider") diff --git a/crates/ide-lsp/src/handler.rs b/crates/ide-lsp/src/handler.rs index e92c15e551..5e12df3e6e 100644 --- a/crates/ide-lsp/src/handler.rs +++ b/crates/ide-lsp/src/handler.rs @@ -764,6 +764,9 @@ impl Handler for ClientHandler { "textDocument/publishDiagnostics" => self.publish_diagnostics(&mgr, params), "dart/textDocument/publishFlutterOutline" => self.publish_flutter_outline(&mgr, params), "dart/textDocument/publishClosingLabels" => self.publish_closing_labels(&mgr, params), + crate::spring_beans::CHANGED if self.server.is_live(self.generation) => { + mgr.sink().emit(IdeEvent::LspRefresh { server: self.server.id, kind: LspRefreshKind::SpringBeanMarkers }) + } "window/showMessage" => self.show_message(&mgr, ¶ms), "window/logMessage" => { let text = params.get("message").and_then(Value::as_str).unwrap_or_default(); diff --git a/crates/ide-lsp/src/lib.rs b/crates/ide-lsp/src/lib.rs index ee8e80b901..3e30fc6c10 100644 --- a/crates/ide-lsp/src/lib.rs +++ b/crates/ide-lsp/src/lib.rs @@ -40,6 +40,7 @@ mod roslyn; mod scope; mod server; mod source_actions; +mod spring_beans; mod switch_source_header; mod tcp; mod text; diff --git a/crates/ide-lsp/src/spring_beans.rs b/crates/ide-lsp/src/spring_beans.rs new file mode 100644 index 0000000000..e088547231 --- /dev/null +++ b/crates/ide-lsp/src/spring_beans.rs @@ -0,0 +1,97 @@ +//! Spring bean navigation markers of a Java document. The first source is java-analyzer's +//! `java-analyzer/springBeanMarkers`, one request per document; its answer is turned into the +//! server-independent [`SpringBeanMarker`]s the gutter shows. + +use crate::types::{SpringBeanDirection, SpringBeanMarker, SpringBeanResolution, SpringBeanTarget}; +use crate::{LspManager, Target, lsp}; +use ide_core::{CancellationToken, DocId, IdeError, IdeResult, Range}; +use serde::Deserialize; +use serde_json::json; +use std::time::Duration; + +/// `{ textDocument: { uri } }` → `{ markers: [{ range, name, direction, targets: [{ location, label, resolution }] }] }`. +pub(crate) const METHOD: &str = "java-analyzer/springBeanMarkers"; +/// Sent by the server, to clients that declare it, when markers of open documents may have changed. +pub(crate) const CHANGED: &str = "java-analyzer/springBeanMarkersChanged"; +/// The first answer of a large workspace pairs every injection point with its beans. +const TIMEOUT: Duration = Duration::from_secs(60); + +#[derive(Deserialize)] +struct Answer { + markers: Vec, +} + +#[derive(Deserialize)] +struct WireMarker { + range: lsp::Range, + name: String, + direction: SpringBeanDirection, + targets: Vec, +} + +#[derive(Deserialize)] +struct WireTarget { + location: lsp::Location, + label: String, + resolution: SpringBeanResolution, +} + +impl LspManager { + /// The document's Spring bean markers; `None` when no server attached to it provides them + /// (jdtls, an older java-analyzer, a server not running yet), without asking any server. + pub async fn spring_bean_markers( + &self, + doc: DocId, + cancel: CancellationToken, + ) -> IdeResult>> { + let snap = self.snapshot(doc)?; + // Only an instance the document is open on: waiting for servers to start would hold + // every Java file of a jdtls project for a background feature. + let source = self.docs.lock().get(&doc).and_then(|d| { + d.servers.iter().find_map(|a| { + let run = a.server.running()?; + let provides = { + let caps = run.caps.read(); + // Bean navigation is implementation navigation: `features` without it leave it out. + caps.restriction.implementation() && caps.raw["experimental"][METHOD] == true + }; + (provides && a.opened_gen == Some(run.generation)).then(|| Target::new(a.server.clone(), run)) + }) + }); + let Some(target) = source else { return Ok(None) }; + let answer: Option = + self.call(&target, METHOD, json!({ "textDocument": snap.ident() }), Some(&cancel), TIMEOUT).await?; + // Ranges are read against the text the request was made for. + if self.snapshot(doc)?.version != snap.version { + return Err(IdeError::cancelled()); + } + let enc = target.enc(); + let conv = self.conv(enc); + let pos = |p| snap.text.lsp_to_ide(enc, p); + let markers = answer.map_or_else(Vec::new, |a| a.markers); + Ok(Some( + markers + .into_iter() + .filter_map(|m| { + let targets: Vec<_> = m + .targets + .into_iter() + .filter_map(|t| { + Some(SpringBeanTarget { + location: conv.location(&t.location)?, + label: t.label, + resolution: t.resolution, + }) + }) + .collect(); + (!targets.is_empty()).then(|| SpringBeanMarker { + range: Range::new(pos(m.range.start), pos(m.range.end)), + name: m.name, + direction: m.direction, + targets, + }) + }) + .collect(), + )) + } +} diff --git a/crates/ide-lsp/src/types.rs b/crates/ide-lsp/src/types.rs index cf61037600..d1dc0ed397 100644 --- a/crates/ide-lsp/src/types.rs +++ b/crates/ide-lsp/src/types.rs @@ -716,3 +716,39 @@ pub enum ArgumentValue { Double(f64), Text(String), } + +/// A Spring bean navigation marker on a name in a Java document: an injection point +/// (`ToBean`) or a bean declaration (`ToInjectionPoint`), whichever server found it. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct SpringBeanMarker { + /// The name the marker is on. + pub range: Range, + pub name: String, + pub direction: SpringBeanDirection, + /// Never empty. + pub targets: Vec, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum SpringBeanDirection { + ToBean, + ToInjectionPoint, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct SpringBeanTarget { + pub location: Location, + pub label: String, + pub resolution: SpringBeanResolution, +} + +/// `Candidate`: one of several beans the injection point could receive. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum SpringBeanResolution { + Resolved, + Candidate, +} diff --git a/crates/ide-lsp/tests/mock_server.rs b/crates/ide-lsp/tests/mock_server.rs index b3cecad365..53b5f15e81 100644 --- a/crates/ide-lsp/tests/mock_server.rs +++ b/crates/ide-lsp/tests/mock_server.rs @@ -9964,3 +9964,81 @@ async fn razor_registrations_apply_to_razor_documents_and_not_to_csharp_ones_on_ } h.mgr.shutdown_all().await; } + +#[tokio::test(flavor = "multi_thread")] +async fn spring_bean_markers_come_from_the_server_that_declares_them() { + let mut caps = incremental_caps(); + caps["positionEncoding"] = json!("utf-8"); + caps["experimental"] = json!({ "java-analyzer/springBeanMarkers": true }); + let h = harness(&[("beans", caps), ("plain", incremental_caps())]); + // "é😀" is 3 UTF-16 units and 6 bytes before `clock`. + let (doc, path) = h.open("a.mk", "é😀clock;\nclass App {}\n"); + for name in ["beans", "plain"] { + h.wait_status(name, ServerStatus::Ready).await; + } + let (beans, plain) = (h.launcher.state("beans"), h.launcher.state("plain")); + eventually(|| !beans.notified("textDocument/didOpen").is_empty()).await; + let init = &beans.requested("initialize")[0]; + assert_eq!(init["capabilities"]["experimental"]["java-analyzer/springBeanMarkersChanged"], true); + let at = |l: u32, c0: u32, c1: u32| json!({"start":{"line":l,"character":c0},"end":{"line":l,"character":c1}}); + beans.respond( + "java-analyzer/springBeanMarkers", + json!({ "markers": [ + { "range": at(0, 6, 11), "name": "clock", "direction": "toBean", "targets": [ + { "location": { "uri": uri_of(&path), "range": at(1, 6, 9) }, "label": "App", "resolution": "resolved" }, + { "location": { "uri": uri_of(&path), "range": at(0, 0, 2) }, "label": "é", "resolution": "candidate" }, + ] }, + { "range": at(1, 6, 9), "name": "App", "direction": "toInjectionPoint", "targets": [] }, + ] }), + ); + let markers = h.mgr.spring_bean_markers(doc, Default::default()).await.unwrap().unwrap(); + assert_eq!( + beans.requested("java-analyzer/springBeanMarkers")[0], + json!({ "textDocument": { "uri": uri_of(&path) } }) + ); + assert!(plain.requested("java-analyzer/springBeanMarkers").is_empty()); + // The marker without targets is dropped; positions are UTF-16 in every file. + assert_eq!(markers.len(), 1); + assert_eq!(markers[0].range, rng(0, 3, 0, 8)); + assert_eq!(markers[0].direction, SpringBeanDirection::ToBean); + assert_eq!(markers[0].targets[0].location.range, rng(1, 6, 1, 9)); + assert_eq!(markers[0].targets[1].location.range, rng(0, 0, 0, 1)); + assert_eq!(markers[0].targets[1].resolution, SpringBeanResolution::Candidate); + + let refreshes = || { + h.events + .lock() + .iter() + .filter(|e| matches!(e, IdeEvent::LspRefresh { kind: LspRefreshKind::SpringBeanMarkers, .. })) + .count() + }; + beans.peer().notify("java-analyzer/springBeanMarkersChanged", json!({})).unwrap(); + eventually(|| refreshes() == 1).await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn spring_bean_markers_ask_no_server_without_the_capability() { + let h = harness(&[("plain", incremental_caps())]); + let (doc, _) = h.open("a.mk", "class App {}\n"); + // Not ready yet: no wait for it to start. + assert_eq!(h.mgr.spring_bean_markers(doc, Default::default()).await.unwrap(), None); + h.wait_status("plain", ServerStatus::Ready).await; + let plain = h.launcher.state("plain"); + eventually(|| !plain.notified("textDocument/didOpen").is_empty()).await; + assert_eq!(h.mgr.spring_bean_markers(doc, Default::default()).await.unwrap(), None); + assert!(plain.requested("java-analyzer/springBeanMarkers").is_empty()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn spring_bean_markers_follow_the_servers_features() { + let mut caps = incremental_caps(); + caps["experimental"] = json!({ "java-analyzer/springBeanMarkers": true }); + // Used for diagnostics only: no navigation from it, bean markers included. + let h = harness_configured("mock", "mk", &[("beans", caps)], |cfg| cfg.features = vec!["diagnostics".into()]); + let (doc, _) = h.open("a.mk", "class App {}\n"); + h.wait_status("beans", ServerStatus::Ready).await; + let beans = h.launcher.state("beans"); + eventually(|| !beans.notified("textDocument/didOpen").is_empty()).await; + assert_eq!(h.mgr.spring_bean_markers(doc, Default::default()).await.unwrap(), None); + assert!(beans.requested("java-analyzer/springBeanMarkers").is_empty()); +} diff --git a/fixtures/README.md b/fixtures/README.md index 1bf9197dfe..e408bf5bc4 100644 --- a/fixtures/README.md +++ b/fixtures/README.md @@ -18,6 +18,7 @@ something to show. | `go-app/` | Go 1.22+ | `go run ./cmd/server` | `go test ./...` | `OPENIDEA_FAIL=1 go test ./...` | unused `fmt.Sprintf` result in `internal/store/store.go` | | `kotlin-gradle/` | JDK 21, Gradle 8 (no wrapper) | `gradle run` | `gradle test` | `gradle test -PopenideaFail` | unused variable in `App.kt` | | `java-app/` | JDK 21, Maven 3.9 | `mvn compile exec:java` | `mvn test` | `mvn test -DopenideaFail=true` | unused variable in `App.java` | +| `spring-app/` | JDK 21, Maven 3.9, Spring Framework 6.2 | `mvn compile exec:java -Dexec.mainClass=com.example.shop.AppConfig` | — | — | — | | `c-app/` | gcc / g++ 12+, make, GDB 14+ | `make all` | — | — | — | | `php-app/` | PHP 8.5, Composer | `composer quote` | `vendor/bin/pest` | `OPENIDEA_FAIL=1 vendor/bin/pest` | unused variable in `ThresholdCustoms.php` | | `unittest-app/` | Python 3.10+ (standard library only) | — | `python -m unittest`; doctests in `inventory/stock.py` | `OPENIDEA_FAIL=1 python -m unittest` | unused import in `inventory/stock.py` | diff --git a/fixtures/spring-app/pom.xml b/fixtures/spring-app/pom.xml new file mode 100644 index 0000000000..bb01eb1b64 --- /dev/null +++ b/fixtures/spring-app/pom.xml @@ -0,0 +1,24 @@ + + + 4.0.0 + + com.example + openidea-fixture-spring + 0.1.0 + OpenIDEA QA fixture: Spring beans and their injection points + + + 21 + UTF-8 + + + + + org.springframework + spring-context + 6.2.12 + + + diff --git a/fixtures/spring-app/src/main/java/com/example/shop/AppConfig.java b/fixtures/spring-app/src/main/java/com/example/shop/AppConfig.java new file mode 100644 index 0000000000..b0327ee3ec --- /dev/null +++ b/fixtures/spring-app/src/main/java/com/example/shop/AppConfig.java @@ -0,0 +1,22 @@ +package com.example.shop; + +import java.time.Clock; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan +public class AppConfig { + @Bean + public Clock clock() { + return Clock.systemUTC(); + } + + public static void main(String[] args) { + try (var context = new AnnotationConfigApplicationContext(AppConfig.class)) { + System.out.println(context.getBean(Checkout.class).checkout("book")); + } + } +} diff --git a/fixtures/spring-app/src/main/java/com/example/shop/Checkout.java b/fixtures/spring-app/src/main/java/com/example/shop/Checkout.java new file mode 100644 index 0000000000..713ad83f7f --- /dev/null +++ b/fixtures/spring-app/src/main/java/com/example/shop/Checkout.java @@ -0,0 +1,38 @@ +package com.example.shop; + +import java.time.Clock; +import java.util.List; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Component; + +/** + * Bean navigation: each injection point has a gutter icon to its bean, and each bean one back to + * where it is injected. Remove {@code @Qualifier("sms")} and both notifiers become candidates for + * {@code channel}; remove {@code @Component} from SmsNotifier and its icons go away. + */ +@Component +public class Checkout { + @Autowired + @Qualifier("sms") + private Notifier channel; + + @Autowired + private List everyNotifier; + + private final OrderService service; + private final Clock clock; + + // Two injection points on one line, each with its own icon. + public Checkout(OrderService service, Clock clock) { + this.service = service; + this.clock = clock; + } + + public String checkout(String item) { + String order = service.place(item); + channel.send(order + " at " + clock.instant()); + everyNotifier.forEach(n -> n.send("audit " + order)); + return order; + } +} diff --git a/fixtures/spring-app/src/main/java/com/example/shop/EmailNotifier.java b/fixtures/spring-app/src/main/java/com/example/shop/EmailNotifier.java new file mode 100644 index 0000000000..ee9f85fd21 --- /dev/null +++ b/fixtures/spring-app/src/main/java/com/example/shop/EmailNotifier.java @@ -0,0 +1,11 @@ +package com.example.shop; + +import org.springframework.stereotype.Component; + +@Component("email") +public class EmailNotifier implements Notifier { + @Override + public void send(String message) { + System.out.println("email: " + message); + } +} diff --git a/fixtures/spring-app/src/main/java/com/example/shop/Notifier.java b/fixtures/spring-app/src/main/java/com/example/shop/Notifier.java new file mode 100644 index 0000000000..6451b13442 --- /dev/null +++ b/fixtures/spring-app/src/main/java/com/example/shop/Notifier.java @@ -0,0 +1,6 @@ +package com.example.shop; + +/** Two beans implement it: injection points pick one with {@code @Qualifier}. */ +public interface Notifier { + void send(String message); +} diff --git a/fixtures/spring-app/src/main/java/com/example/shop/OrderService.java b/fixtures/spring-app/src/main/java/com/example/shop/OrderService.java new file mode 100644 index 0000000000..e19b3a97e2 --- /dev/null +++ b/fixtures/spring-app/src/main/java/com/example/shop/OrderService.java @@ -0,0 +1,10 @@ +package com.example.shop; + +import org.springframework.stereotype.Service; + +@Service +public class OrderService { + public String place(String item) { + return "order:" + item; + } +} diff --git a/fixtures/spring-app/src/main/java/com/example/shop/SmsNotifier.java b/fixtures/spring-app/src/main/java/com/example/shop/SmsNotifier.java new file mode 100644 index 0000000000..686e2a6ad7 --- /dev/null +++ b/fixtures/spring-app/src/main/java/com/example/shop/SmsNotifier.java @@ -0,0 +1,11 @@ +package com.example.shop; + +import org.springframework.stereotype.Component; + +@Component("sms") +public class SmsNotifier implements Notifier { + @Override + public void send(String message) { + System.out.println("sms: " + message); + } +} diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 67d8309756..5ddcc7f883 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -495,6 +495,7 @@ lsp_snapshot_completion trusted project_host bin lsp_snapshot_diagnostics trusted project_host bindings async lsp_source_action_text trusted project_host bindings async lsp_source_definition trusted project_host bindings async +lsp_spring_bean_markers trusted project_host bindings async lsp_stop trusted project_host bindings async lsp_switch_source_header trusted project_host bindings async lsp_type_hierarchy trusted project_host bindings async diff --git a/src/bindings.ts b/src/bindings.ts index 1b77c0e4c4..25cfaf26b9 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -1318,6 +1318,11 @@ export const commands = { * instead of its `.d.ts`. Cancel with `cancel_request(request)`. */ lspSourceDefinition: (request: RequestId, doc: DocId, pos: Pos) => typedError(__TAURI_INVOKE("lsp_source_definition", { request, doc, pos })), + /** + * The document's Spring bean markers (injection points and bean declarations with their + * targets); `None` when no server attached to it provides them. Cancel with `cancel_request(request)`. + */ + lspSpringBeanMarkers: (request: RequestId, doc: DocId) => typedError(__TAURI_INVOKE("lsp_spring_bean_markers", { request, doc })), /** Stops a language server; it starts again when a file it serves is opened. */ lspStop: (server: ServerId) => typedError(__TAURI_INVOKE("lsp_stop", { server })), /** @@ -12654,7 +12659,9 @@ export type LspRefreshKind = "inlayHints" | "semanticTokens" | "codeLens" | /** An import or classpath update may have changed inheritance search results. */ "inheritance" | /** The Dart server published a document's Flutter outline. */ -"flutterOutline"; +"flutterOutline" | +/** Spring bean markers of open documents may have changed. */ +"springBeanMarkers"; export type MainToolbarSettings = { left?: string[], @@ -17032,6 +17039,30 @@ export type SpellingSettings = { defaultDictionary?: string | null, }; +export type SpringBeanDirection = "toBean" | "toInjectionPoint"; + +/** + * A Spring bean navigation marker on a name in a Java document: an injection point + * (`ToBean`) or a bean declaration (`ToInjectionPoint`), whichever server found it. + */ +export type SpringBeanMarker = { + /** The name the marker is on. */ + range: Range, + name: string, + direction: SpringBeanDirection, + /** Never empty. */ + targets: SpringBeanTarget[], +}; + +/** `Candidate`: one of several beans the injection point could receive. */ +export type SpringBeanResolution = "resolved" | "candidate"; + +export type SpringBeanTarget = { + location: Location, + label: string, + resolution: SpringBeanResolution, +}; + /** One row of SQL Resolution Scopes. */ export type SqlResolutionScope = { /** Project-relative file or folder, `/`-separated; empty for the whole project. */ diff --git a/src/editor/lsp/index.ts b/src/editor/lsp/index.ts index 68848064d3..44acc5f7ec 100644 --- a/src/editor/lsp/index.ts +++ b/src/editor/lsp/index.ts @@ -47,7 +47,12 @@ import { MemberChooserDialog } from "./MemberChooserDialog"; import { DOCUMENTATION_WINDOW } from "./docs"; import { prefetchMarkdown } from "./markdown"; import { outsideProjectBanner } from "./outsideProject"; -import { implementationGutter, pythonStubGutter, registerNavigationActions } from "@/editor/navigation"; +import { + implementationGutter, + pythonStubGutter, + registerNavigationActions, + springBeanGutter, +} from "@/editor/navigation"; import { ChangeSignatureDialog, ExtractInterfaceDialog, @@ -134,6 +139,7 @@ export function activate(): () => void { // After the run icons (order 55), as their own gutter column. registerEditorContribution({ id: "lsp.lineMarkers", order: 56, extensions: implementationGutter }), registerEditorContribution({ id: "lsp.pythonStubs", order: 57, extensions: pythonStubGutter }), + registerEditorContribution({ id: "lsp.springBeans", order: 58, extensions: springBeanGutter }), // After the templates (order 90): live template / postfix expansion keeps ⇥ first. registerEditorContribution({ id: "lsp.parameterTab", order: 95, extensions: () => parameterTabKeys }), registerOverlay({ id: "editor-lsp.popups", component: LspPopups }), diff --git a/src/editor/lsp/navigation.ts b/src/editor/lsp/navigation.ts index b6a2a4ee7c..2fd40e2aea 100644 --- a/src/editor/lsp/navigation.ts +++ b/src/editor/lsp/navigation.ts @@ -444,10 +444,10 @@ function streamedImplementations(view: EditorView, offset: number, onOpen: () => } /** Pin button of the targets chooser: the targets as a Find tool window tab (code-insight). */ -export function pinToFind(symbol: string, locations: readonly Location[]) { +export function pinToFind(symbol: string, locations: readonly Location[], note?: string) { return { label: "Open in Find Tool Window", - run: () => void executeAction("find.showUsageResults", { symbol, locations }), + run: () => void executeAction("find.showUsageResults", note ? { symbol, locations, note } : { symbol, locations }), }; } diff --git a/src/editor/navigation/implementationGutter.ts b/src/editor/navigation/implementationGutter.ts index 4ee1fa4898..a3341e5f62 100644 --- a/src/editor/navigation/implementationGutter.ts +++ b/src/editor/navigation/implementationGutter.ts @@ -26,7 +26,7 @@ import { featureBackoff, onServerSettled } from "@/editor/lsp/availability"; import { inForeground, onForeground } from "@/editor/lsp/foreground"; import { readManyFileLines, withDocument } from "@/editor/lsp/files"; import { locationItems, navigateTo, pinToFind } from "@/editor/lsp/navigation"; -import { openPopup } from "@/editor/lsp/popupStore"; +import { openPopup, type ListPopupItem } from "@/editor/lsp/popupStore"; import type { DeclarationTarget } from "@/editor/lsp/syntaxFallback"; import { commands, @@ -691,17 +691,28 @@ export async function openMarkerTargets( return true; }); } + await openTargets( + targets, + anchor, + merged ? tx`Choose Inheritance Target (${targets.length} found)` : first.chooserTitle, + [...new Set(markers.map((m) => m.name))].join(", "), + ); +} + +/** A gutter marker's click: one target navigates, several open the chooser titled `title`. */ +export async function openTargets( + targets: readonly DeclarationTarget[], + anchor: { x: number; y: number }, + title: string, + symbol: string, + items: (targets: readonly DeclarationTarget[]) => Promise = locationItems, + note?: string, +) { if (targets.length === 1) { await navigateTo(targets[0]!); return; } - openPopup({ - kind: "list", - anchor, - title: merged ? tx`Choose Inheritance Target (${targets.length} found)` : first.chooserTitle, - items: await locationItems(targets), - pin: pinToFind([...new Set(markers.map((m) => m.name))].join(", "), targets), - }); + openPopup({ kind: "list", anchor, title, items: await items(targets), pin: pinToFind(symbol, targets, note) }); } // --------------------------------------------------------------------------- diff --git a/src/editor/navigation/index.ts b/src/editor/navigation/index.ts index 7b431c8f01..c84396534b 100644 --- a/src/editor/navigation/index.ts +++ b/src/editor/navigation/index.ts @@ -345,4 +345,5 @@ export function registerNavigationActions(): () => void { } export { implementationGutter } from "./implementationGutter"; +export { springBeanGutter } from "./springBeanGutter"; export { pythonStubGutter } from "./pythonStubs"; diff --git a/src/editor/navigation/springBeanGutter.test.ts b/src/editor/navigation/springBeanGutter.test.ts new file mode 100644 index 0000000000..b1a2189b83 --- /dev/null +++ b/src/editor/navigation/springBeanGutter.test.ts @@ -0,0 +1,311 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { fireEvent } from "@testing-library/react"; + +const ipc = vi.hoisted(() => ({ lspSpringBeanMarkers: vi.fn(), cancelRequest: vi.fn(async () => ({ status: "ok" })) })); +const nav = vi.hoisted(() => ({ + navigateTo: vi.fn(), + openPopup: vi.fn(), + pinToFind: vi.fn((symbol: string) => ({ label: "Open in Find Tool Window", run: () => symbol })), +})); +const library = vi.hoisted(() => ({ excluded: false })); +const refresh = vi.hoisted(() => ({ + listeners: [] as (() => void)[], + ide: [] as { event: string; fn: (e: { status?: string }) => void }[], +})); + +vi.mock("@/platform/ipc", async (importOriginal) => ({ + ...(await importOriginal()), + isTauri: () => true, + nextRequestId: () => 7, + onIdeEvent: (event: string, fn: (e: { status?: string }) => void) => { + refresh.ide.push({ event, fn }); + return () => {}; + }, + commands: ipc, +})); +vi.mock("@/editor/api", async (importOriginal) => ({ + ...(await importOriginal()), + whenAllSynced: () => Promise.resolve(), + isLibrarySource: () => library.excluded, +})); +vi.mock("@/editor/lsp/availability", async (importOriginal) => ({ + ...(await importOriginal()), + onLspRefresh: (_: string, fn: () => void) => refresh.listeners.push(fn), + onServerSettled: () => () => {}, +})); +vi.mock("@/editor/lsp/navigation", async (importOriginal) => ({ + ...(await importOriginal()), + navigateTo: nav.navigateTo, + pinToFind: nav.pinToFind, + locationItems: async (locs: { name?: string; path: string }[]) => + locs.map((l, i) => ({ id: `${i}`, label: l.name ?? l.path })), +})); +vi.mock("@/editor/lsp/popupStore", async (importOriginal) => ({ + ...(await importOriginal()), + openPopup: nav.openPopup, +})); + +import { EditorState } from "@codemirror/state"; +import { EditorView } from "@codemirror/view"; +import { iconAreaExtension } from "@/editor/core/cm/iconArea"; +import type { SpringBeanMarker, SpringBeanTarget } from "@/platform/ipc"; +import { foregroundStarted } from "@/editor/lsp/foreground"; +import { useProject } from "@/platform/project"; +import { beanTooltip, springBeanGutter } from "./springBeanGutter"; + +// The acceptance fixture: one interface with two implementations and `@Qualifier`, constructor +// parameters (two on one line), a bean declaration with its injection point. +const SOURCE = [ + "@Component", // 0 + "class Checkout {", // 1 bean, injected into Shop's constructor + ' @Autowired @Qualifier("sms") Notifier channel;', // 2 → SmsNotifier only + " @Autowired Notifier any;", // 3 → EmailNotifier, SmsNotifier (candidates) + " Checkout(OrderService service, Clock clock) {}", // 4 two injection points on one line + "}", +].join("\n"); + +const range = (line: number, col: number, len: number) => ({ + start: { line, col }, + end: { line, col: col + len }, +}); +const target = ( + path: string, + line: number, + label: string, + resolution: SpringBeanTarget["resolution"] = "resolved", +): SpringBeanTarget => ({ location: { path, range: range(line, 6, 4) }, label, resolution }); +const marker = ( + line: number, + col: number, + name: string, + direction: SpringBeanMarker["direction"], + targets: SpringBeanTarget[], +): SpringBeanMarker => ({ range: range(line, col, name.length), name, direction, targets }); + +const SMS = target("/p/SmsNotifier.java", 3, "sms · SmsNotifier"); +const EMAIL = target("/p/EmailNotifier.java", 4, "email · EmailNotifier"); +const MARKERS: SpringBeanMarker[] = [ + // Unsorted on purpose: the gutter orders a line's icons by column. + marker(4, 40, "clock", "toBean", [target("/p/AppConfig.java", 9, "clock · AppConfig.clock()")]), + marker(4, 24, "service", "toBean", [target("/p/OrderService.java", 2, "orderService · OrderService")]), + marker(1, 6, "Checkout", "toInjectionPoint", [target("/p/Shop.java", 5, "Shop.checkout")]), + marker(2, 40, "channel", "toBean", [SMS]), + marker(3, 23, "any", "toBean", [ + { ...EMAIL, resolution: "candidate" }, + { ...SMS, resolution: "candidate" }, + ]), +]; + +const answer = (markers: SpringBeanMarker[] | null) => ({ status: "ok", data: markers }); + +describe("spring bean gutter", () => { + let view: EditorView | null = null; + afterEach(() => { + view?.destroy(); + view = null; + vi.clearAllMocks(); + }); + + function open(language = "java") { + const ctx = { doc: 1, path: "/p/Checkout.java", language, virtual: false } as Parameters< + typeof springBeanGutter + >[0]; + view = new EditorView({ + state: EditorState.create({ doc: SOURCE, extensions: [springBeanGutter(ctx), iconAreaExtension] }), + parent: document.body, + }); + return view; + } + + const buttons = () => [...view!.dom.querySelectorAll("[data-spring-bean]")]; + const button = (name: string) => buttons().find((b) => b.title.includes(` ${name}\n`))!; + + it("puts one icon on each injection point and bean, a line's icons in column order", async () => { + ipc.lspSpringBeanMarkers.mockResolvedValue(answer(MARKERS)); + open(); + await vi.waitFor(() => expect(buttons()).toHaveLength(5), { timeout: 2000 }); + expect(ipc.lspSpringBeanMarkers).toHaveBeenCalledExactlyOnceWith(7, 1); + expect(buttons().map((b) => b.title.split("\n")[0])).toEqual([ + "Navigate to the injection points of Checkout", + "Navigate to the beans injected into channel", + "Navigate to the beans injected into any", + "Navigate to the beans injected into service", + "Navigate to the beans injected into clock", + ]); + expect(buttons().map((b) => b.dataset.springBean)).toEqual([ + "toInjectionPoint", + "toBean", + "toBean", + "toBean", + "toBean", + ]); + // Both parameters of the constructor line keep their own icon. + const line4 = view!.dom.querySelectorAll(".cm-openidea-iconArea .cm-gutterElement")[4]!; + expect(line4.querySelectorAll("[data-spring-bean]")).toHaveLength(2); + }); + + it("navigates to a single target, from either parameter on a shared line", async () => { + ipc.lspSpringBeanMarkers.mockResolvedValue(answer(MARKERS)); + open(); + await vi.waitFor(() => expect(buttons()).toHaveLength(5), { timeout: 2000 }); + fireEvent.click(button("clock")); + await vi.waitFor(() => + expect(nav.navigateTo).toHaveBeenCalledWith({ + ...MARKERS[0]!.targets[0]!.location, + name: "clock · AppConfig.clock()", + }), + ); + fireEvent.click(button("service")); + await vi.waitFor(() => expect(nav.navigateTo).toHaveBeenCalledTimes(2)); + expect(nav.navigateTo.mock.calls[1]![0].path).toBe("/p/OrderService.java"); + fireEvent.click(button("Checkout")); + await vi.waitFor(() => expect(nav.navigateTo).toHaveBeenCalledTimes(3)); + expect(nav.navigateTo.mock.calls[2]![0].path).toBe("/p/Shop.java"); + expect(nav.openPopup).not.toHaveBeenCalled(); + }); + + it("lists several beans in the chooser, each marked when it is only a candidate", async () => { + ipc.lspSpringBeanMarkers.mockResolvedValue(answer(MARKERS)); + open(); + await vi.waitFor(() => expect(buttons()).toHaveLength(5), { timeout: 2000 }); + expect(button("any").title).toBe( + "Navigate to the beans injected into any\nemail · EmailNotifier — candidate\nsms · SmsNotifier — candidate", + ); + fireEvent.click(button("any")); + await vi.waitFor(() => expect(nav.openPopup).toHaveBeenCalledOnce()); + const popup = nav.openPopup.mock.calls[0]![0]; + expect(popup.title).toBe("Choose Bean for any (2 found)"); + expect(popup.items).toEqual([ + { id: "0", label: "email · EmailNotifier", detail: "candidate" }, + { id: "1", label: "sms · SmsNotifier", detail: "candidate" }, + ]); + expect(nav.navigateTo).not.toHaveBeenCalled(); + }); + + it("clears an icon when the server no longer reports its relation", async () => { + ipc.lspSpringBeanMarkers.mockResolvedValue(answer(MARKERS)); + open(); + await vi.waitFor(() => expect(buttons()).toHaveLength(5), { timeout: 2000 }); + // `@Qualifier("sms")` removed in another file: the server says markers changed. + ipc.lspSpringBeanMarkers.mockResolvedValue(answer(MARKERS.filter((m) => m.name !== "channel"))); + refresh.listeners.forEach((l) => l()); + await vi.waitFor(() => expect(buttons()).toHaveLength(4), { timeout: 2000 }); + expect(buttons().some((b) => b.title.includes("channel"))).toBe(false); + // No source any more (another server took over): no icons. + ipc.lspSpringBeanMarkers.mockResolvedValue(answer(null)); + refresh.listeners.forEach((l) => l()); + await vi.waitFor(() => expect(buttons()).toHaveLength(0), { timeout: 2000 }); + }); + + it("keeps a late answer for older text from replacing the current one", async () => { + let first!: (v: unknown) => void; + ipc.lspSpringBeanMarkers.mockReturnValueOnce(new Promise((r) => (first = r))); + open(); + await vi.waitFor(() => expect(ipc.lspSpringBeanMarkers).toHaveBeenCalledOnce(), { timeout: 2000 }); + ipc.lspSpringBeanMarkers.mockResolvedValue(answer([MARKERS[3]!])); + view!.dispatch({ changes: { from: 0, insert: " " } }); + await vi.waitFor(() => expect(buttons()).toHaveLength(1), { timeout: 2000 }); + first(answer(MARKERS)); + await new Promise((r) => setTimeout(r, 50)); + expect(buttons()).toHaveLength(1); + expect(ipc.cancelRequest).toHaveBeenCalled(); + }); + + it("drops an answer already on its way when the server says markers changed", async () => { + ipc.lspSpringBeanMarkers.mockResolvedValue(answer(MARKERS)); + open(); + await vi.waitFor(() => expect(buttons()).toHaveLength(5), { timeout: 2000 }); + let late!: (v: unknown) => void; + ipc.lspSpringBeanMarkers.mockReturnValueOnce(new Promise((r) => (late = r))); + refresh.listeners.forEach((l) => l()); + await vi.waitFor(() => expect(ipc.lspSpringBeanMarkers).toHaveBeenCalledTimes(2), { timeout: 2000 }); + // `@Component` removed from SmsNotifier meanwhile: the answer in flight is stale. + ipc.lspSpringBeanMarkers.mockResolvedValue(answer([MARKERS[0]!])); + refresh.listeners.forEach((l) => l()); + late(answer(MARKERS.slice(0, 2))); + await new Promise((r) => setTimeout(r, 50)); + expect(buttons()).toHaveLength(5); + await vi.waitFor(() => expect(buttons()).toHaveLength(1), { timeout: 2000 }); + }); + + it("asks again when the source server stops, clearing its icons", async () => { + ipc.lspSpringBeanMarkers.mockResolvedValue(answer(MARKERS)); + open(); + await vi.waitFor(() => expect(buttons()).toHaveLength(5), { timeout: 2000 }); + ipc.lspSpringBeanMarkers.mockResolvedValue(answer(null)); + for (const { event, fn } of refresh.ide) if (event === "languageServer") fn({ status: "stopped" }); + await vi.waitFor(() => expect(buttons()).toHaveLength(0), { timeout: 2000 }); + }); + + it("asks again when Gutter Icons are turned back on", async () => { + const settings = useProject.getState().settings; + const withIcons = (on: boolean) => + useProject.setState({ settings: { ...(settings as object), editor: { showGutterIcons: on } } as never }); + try { + withIcons(false); + ipc.lspSpringBeanMarkers.mockResolvedValue(answer(MARKERS)); + open(); + await new Promise((r) => setTimeout(r, 700)); + expect(ipc.lspSpringBeanMarkers).not.toHaveBeenCalled(); + withIcons(true); + await vi.waitFor(() => expect(buttons()).toHaveLength(5), { timeout: 2000 }); + } finally { + useProject.setState({ settings }); + } + }); + + it("waits for a navigation the user started before asking", async () => { + ipc.lspSpringBeanMarkers.mockResolvedValue(answer(MARKERS)); + const done = foregroundStarted(); + open(); + await new Promise((r) => setTimeout(r, 700)); + expect(ipc.lspSpringBeanMarkers).not.toHaveBeenCalled(); + done(); + await vi.waitFor(() => expect(buttons()).toHaveLength(5), { timeout: 2000 }); + }); + + it("marks candidates when the chooser's results are pinned to Find", async () => { + ipc.lspSpringBeanMarkers.mockResolvedValue(answer(MARKERS)); + open(); + await vi.waitFor(() => expect(buttons()).toHaveLength(5), { timeout: 2000 }); + fireEvent.click(button("any")); + await vi.waitFor(() => expect(nav.openPopup).toHaveBeenCalledOnce()); + expect(nav.openPopup.mock.calls[0]![0].pin.label).toBe("Open in Find Tool Window"); + expect(nav.pinToFind).toHaveBeenCalledWith( + "any", + expect.any(Array), + "Candidates, not certain: email · EmailNotifier, sms · SmsNotifier", + ); + }); + + it("follows the folder being excluded and included again without reopening", async () => { + ipc.lspSpringBeanMarkers.mockResolvedValue(answer(MARKERS)); + library.excluded = true; + try { + open(); + await new Promise((r) => setTimeout(r, 700)); + expect(ipc.lspSpringBeanMarkers).not.toHaveBeenCalled(); + // Project Structure › the folder is a source root again: settings change. + library.excluded = false; + useProject.setState({ settings: { ...(useProject.getState().settings as object) } as never }); + await vi.waitFor(() => expect(buttons()).toHaveLength(5), { timeout: 2000 }); + library.excluded = true; + useProject.setState({ settings: { ...(useProject.getState().settings as object) } as never }); + await vi.waitFor(() => expect(buttons()).toHaveLength(0), { timeout: 2000 }); + } finally { + library.excluded = false; + } + }); + + it("asks nothing for other languages", async () => { + open("kotlin"); + await new Promise((r) => setTimeout(r, 700)); + expect(ipc.lspSpringBeanMarkers).not.toHaveBeenCalled(); + }); +}); + +describe("beanTooltip", () => { + it("names the injection points of a bean", () => { + expect(beanTooltip(MARKERS[2]!)).toBe("Navigate to the injection points of Checkout\nShop.checkout"); + }); +}); diff --git a/src/editor/navigation/springBeanGutter.ts b/src/editor/navigation/springBeanGutter.ts new file mode 100644 index 0000000000..c18ced5abe --- /dev/null +++ b/src/editor/navigation/springBeanGutter.ts @@ -0,0 +1,295 @@ +/** + * Spring bean gutter icons on Java documents: an injection point navigates to the beans it + * receives, a bean declaration to the injection points that receive it. One cancellable request + * per document answers both directions (`lspSpringBeanMarkers`); the source is whichever attached + * server provides them, and none means no icons. Asked again after edits, when the server says + * the bean model changed (other files edited, a re-import) and when a server settles. + */ +import { RangeSet, StateEffect, StateField, type Extension, type Text } from "@codemirror/state"; +import { EditorView, GutterMarker, ViewPlugin, type ViewUpdate } from "@codemirror/view"; +import { iconAreaSource, mapLineStart } from "@/editor/core/cm/iconArea"; +import { gutterIconsOn, localAppearanceField } from "@/editor/core/cm/localAppearance"; +import { isLibrarySource, shownAgain, type EditorDocContext } from "@/editor/api"; +import { debounce, lspRequest } from "@/editor/lsp/lsp"; +import { onLspRefresh, onServerSettled } from "@/editor/lsp/availability"; +import { inForeground, onForeground } from "@/editor/lsp/foreground"; +import { locationItems } from "@/editor/lsp/navigation"; +import { + commands, + isCancelled, + nextRequestId, + onIdeEvent, + type RequestId, + type SpringBeanMarker, +} from "@/platform/ipc"; +import { tx } from "@/platform/i18n"; +import { editorPrefs } from "@/platform/editorSettings"; +import { useProject } from "@/platform/project"; +import { gutterIconMarkup } from "@/ui"; +import { openTargets } from "./implementationGutter"; +import styles from "./LineMarkers.module.css"; + +const DEBOUNCE_MS = 500; + +interface PlacedBean { + marker: SpringBeanMarker; + /** Start of the marker's line in the current state. */ + pos: number; +} + +const setBeans = StateEffect.define(); + +const beansField = StateField.define({ + create: () => [], + update(value, tr) { + for (const e of tr.effects) if (e.is(setBeans)) return e.value; + if (!tr.docChanged || !value.length) return value; + return value.map((b) => ({ ...b, pos: mapLineStart(tr, b.pos) })); + }, +}); + +/** Markers on lines of `doc`, left to right within a line. */ +export function placeBeans(doc: Text, markers: readonly SpringBeanMarker[]): PlacedBean[] { + return markers + .filter((m) => m.range.start.line < doc.lines && m.targets.length) + .sort((a, b) => a.range.start.line - b.range.start.line || a.range.start.col - b.range.start.col) + .map((marker) => ({ marker, pos: doc.line(marker.range.start.line + 1).from })); +} + +/** Tooltip and accessible name: what clicking does, then each target. */ +export function beanTooltip(marker: SpringBeanMarker): string { + const head = + marker.direction === "toBean" + ? tx`Navigate to the beans injected into ${marker.name}` + : tx`Navigate to the injection points of ${marker.name}`; + const rows = marker.targets.map((t) => (t.resolution === "candidate" ? `${t.label} — ${tx("candidate")}` : t.label)); + return [head, ...rows].join("\n"); +} + +/** One target navigates; several open the chooser, each row saying whether it is only a candidate. */ +export async function openBeanTargets(marker: SpringBeanMarker, anchor: { x: number; y: number }) { + const targets = marker.targets.map((t) => ({ ...t.location, name: t.label })); + const n = targets.length; + const title = + marker.direction === "toBean" + ? tx`Choose Bean for ${marker.name} (${n} found)` + : tx`Choose Injection Point of ${marker.name} (${n} found)`; + const candidates = marker.targets.filter((t) => t.resolution === "candidate").map((t) => t.label); + // Pinned to Find, candidates must not read as certain usages. + const note = candidates.length ? tx`Candidates, not certain: ${candidates.join(", ")}` : undefined; + await openTargets( + targets, + anchor, + title, + marker.name, + async (locs) => { + const items = await locationItems(locs); + return items.map((item, i) => + marker.targets[i]!.resolution === "candidate" ? { ...item, detail: tx("candidate") } : item, + ); + }, + note, + ); +} + +class BeanMarker extends GutterMarker { + readonly tooltip: string; + readonly icon: string; + + constructor(readonly marker: SpringBeanMarker) { + super(); + this.tooltip = beanTooltip(marker); + this.icon = marker.direction === "toBean" ? "gutter-spring-to-bean" : "gutter-spring-to-injection-point"; + } + + // The DOM holds the marker it navigates with: other targets need a new button. + override eq(other: GutterMarker): boolean { + return other instanceof BeanMarker && other.marker === this.marker; + } + + override toDOM(): Node { + const button = document.createElement("button"); + button.type = "button"; + button.className = styles.stubMarker ?? ""; + button.dataset.springBean = this.marker.direction; + button.title = this.tooltip; + button.setAttribute("aria-label", this.tooltip); + button.innerHTML = gutterIconMarkup(this.icon) ?? ""; + // Keep the caret where it was; the click navigates, so the icon also works from the keyboard. + button.addEventListener("mousedown", (event) => { + event.preventDefault(); + event.stopPropagation(); + }); + button.addEventListener("click", (event) => { + event.preventDefault(); + event.stopPropagation(); + const rect = button.getBoundingClientRect(); + void openBeanTargets(this.marker, { x: rect.left, y: rect.bottom + 2 }); + }); + return button; + } +} + +/** Marker sets by field value: the icon area asks on every view update (caret moves, scrolling). */ +const markerSets = new WeakMap>(); + +function beanSet(placed: readonly PlacedBean[]): RangeSet { + let set = markerSets.get(placed); + if (!set) { + set = RangeSet.of( + placed.map(({ marker, pos }) => new BeanMarker(marker).range(pos)), + true, + ); + markerSets.set(placed, set); + } + return set; +} + +const live = new Set(); +let watching = false; + +function watchChanges() { + if (watching) return; + watching = true; + const refreshAll = () => { + for (const plugin of live) plugin.refreshSoon(); + }; + // The server's own "markers changed" (another file edited, a re-import), or it (re)started. + onLspRefresh("springBeanMarkers", refreshAll); + // Answers given while a server was importing may be incomplete. + onServerSettled(refreshAll); + // A stopped or removed source must not leave icons that navigate to old targets. + onIdeEvent("languageServer", (e) => { + if (e.status === "stopped" || e.status === "crashed") refreshAll(); + }); + onIdeEvent("languageServerRemoved", refreshAll); + // Requests the user waits for go first (Go to Declaration, a refactoring), as for the inheritance icons. + onForeground((foreground) => { + for (const plugin of live) { + if (foreground) plugin.yieldToNavigation(); + else plugin.resumeAfterNavigation(); + } + }); +} + +class BeansPlugin { + private refresh = debounce(() => void this.run(), DEBOUNCE_MS); + private generation = 0; + private skipped = false; + private request: RequestId | null = null; + /** A pass was cancelled or held back by a navigation: run again once it is done. */ + private yielded = false; + private offSettings: () => void; + + constructor( + private view: EditorView, + private ctx: EditorDocContext, + ) { + live.add(this); + watchChanges(); + this.refresh(); + // Turning Gutter Icons back on asks again. + this.offSettings = useProject.subscribe((s, prev) => { + if (s.settings !== prev.settings) this.refresh(); + }); + } + + /** The markers on screen may be stale: an answer already on its way is dropped. */ + refreshSoon() { + this.generation++; + this.cancelRequest(); + this.refresh(); + } + + yieldToNavigation() { + if (this.request === null) return; + this.generation++; + this.cancelRequest(); + this.yielded = true; + } + + resumeAfterNavigation() { + if (!this.yielded) return; + this.yielded = false; + this.refresh(); + } + + update(u: ViewUpdate) { + if (u.docChanged) { + this.generation++; + this.cancelRequest(); + this.refresh(); + } else if (this.skipped && shownAgain(u)) this.refresh(); + // A local Gutter Icons override can turn the icons on. + else if (u.startState.field(localAppearanceField, false) !== u.state.field(localAppearanceField, false)) + this.refresh(); + } + + private cancelRequest() { + if (this.request === null) return; + void commands.cancelRequest(this.request).catch(() => {}); + this.request = null; + } + + private show(placed: PlacedBean[]) { + const current = this.view.state.field(beansField); + if (current.length || placed.length) this.view.dispatch({ effects: setBeans.of(placed) }); + } + + private async run() { + const view = this.view; + this.skipped = !view.dom.isConnected; + if (this.skipped) return; + if (inForeground()) { + this.yielded = true; + return; + } + const gen = ++this.generation; + this.cancelRequest(); + // Checked on every pass, as Code Vision does: excluding or including a folder changes it. + if (isLibrarySource(this.ctx) || !gutterIconsOn(view.state, undefined, editorPrefs())) { + this.show([]); + return; + } + const text = view.state.doc; + const stale = () => gen !== this.generation || view.state.doc !== text; + const request = (this.request = nextRequestId()); + try { + const markers = await lspRequest( + () => commands.lspSpringBeanMarkers(request, this.ctx.doc), + () => !stale(), + ); + if (stale()) return; + this.show(placeBeans(text, markers ?? [])); + } catch (e) { + if (stale()) return; + // A failed answer leaves no icon that could navigate to an old target. + this.show([]); + if (!isCancelled(e)) console.debug("[springBeans]", e); + } finally { + if (this.request === request) this.request = null; + } + } + + destroy() { + this.refresh.cancel(); + this.cancelRequest(); + this.offSettings(); + this.generation++; + live.delete(this); + } +} + +/** Java source documents of the project; library classes and virtual documents have no beans to find. */ +export function springBeanGutter(ctx: EditorDocContext): Extension { + if (ctx.doc < 0 || ctx.language !== "java") return []; + return [ + beansField, + ViewPlugin.define((view) => new BeansPlugin(view, ctx)), + // After the inheritance icons (order 50), in the shared icon area. + iconAreaSource.of({ + order: 51, + markers: (view) => (gutterIconsOn(view.state) ? beanSet(view.state.field(beansField)) : RangeSet.empty), + }), + ]; +} diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 23f57305b0..82bf8eb266 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -3225,6 +3225,12 @@ "Leave empty to enable for all agents, or pick specific coding agents.": "Leave empty to enable for all agents, or pick specific coding agents.", "Related Symbol…": "Related Symbol…", "Choose Inheritance Target ({count} found)": "Choose Inheritance Target ({count} found)", + "Navigate to the beans injected into {name}": "Navigate to the beans injected into {name}", + "Navigate to the injection points of {name}": "Navigate to the injection points of {name}", + "candidate": "candidate", + "Candidates, not certain: {names}": "Candidates, not certain: {names}", + "Choose Bean for {name} ({count} found)": "Choose Bean for {name} ({count} found)", + "Choose Injection Point of {name} ({count} found)": "Choose Injection Point of {name} ({count} found)", "Choose Target": "Choose Target", "No related symbols": "No related symbols", "Switch Header/Source": "Switch Header/Source", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 457561f5e2..8ff0a02d92 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -9973,6 +9973,12 @@ "Leave empty to enable for all agents, or pick specific coding agents.": "留空则对所有智能体启用,也可选择特定的编码智能体。", "Related Symbol…": "相关符号…", "Choose Inheritance Target ({count} found)": "选择继承目标(找到 {count} 个)", + "Navigate to the beans injected into {name}": "转到注入到 {name} 的 Bean", + "Navigate to the injection points of {name}": "转到 {name} 的注入点", + "candidate": "候选", + "Candidates, not certain: {names}": "候选,未确定:{names}", + "Choose Bean for {name} ({count} found)": "选择 {name} 的 Bean(找到 {count} 个)", + "Choose Injection Point of {name} ({count} found)": "选择 {name} 的注入点(找到 {count} 个)", "Choose Target": "选择目标", "No related symbols": "没有相关符号", "Switch Header/Source": "切换头文件/源文件", diff --git a/src/ui/icons.tsx b/src/ui/icons.tsx index 74edc641a7..0d0f798c2f 100644 --- a/src/ui/icons.tsx +++ b/src/ui/icons.tsx @@ -520,6 +520,8 @@ const ICONS = { "gutter-overriding": "gutter/overridingMethod", "gutter-javadoc-read": "gutter/javadocRead", "gutter-javadoc-edit": "gutter/javadocEdit", + "gutter-spring-to-bean": "openidea/gutter/springBeanToBean", + "gutter-spring-to-injection-point": "openidea/gutter/springBeanToInjectionPoint", stop: "run/stop", rerun: "run/rerun", "rerun-automatically": "actions/rerunAutomatically", diff --git a/src/ui/openidea/gutter/springBeanToBean.svg b/src/ui/openidea/gutter/springBeanToBean.svg new file mode 100644 index 0000000000..23a1e21692 --- /dev/null +++ b/src/ui/openidea/gutter/springBeanToBean.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/src/ui/openidea/gutter/springBeanToBean_dark.svg b/src/ui/openidea/gutter/springBeanToBean_dark.svg new file mode 100644 index 0000000000..7dc94661a4 --- /dev/null +++ b/src/ui/openidea/gutter/springBeanToBean_dark.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/src/ui/openidea/gutter/springBeanToInjectionPoint.svg b/src/ui/openidea/gutter/springBeanToInjectionPoint.svg new file mode 100644 index 0000000000..2e64ed0dd3 --- /dev/null +++ b/src/ui/openidea/gutter/springBeanToInjectionPoint.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/src/ui/openidea/gutter/springBeanToInjectionPoint_dark.svg b/src/ui/openidea/gutter/springBeanToInjectionPoint_dark.svg new file mode 100644 index 0000000000..e2da1456f3 --- /dev/null +++ b/src/ui/openidea/gutter/springBeanToInjectionPoint_dark.svg @@ -0,0 +1,6 @@ + + + + + +