From 2d11fd484f6d656794b02df0c8ec2db015d8fa73 Mon Sep 17 00:00:00 2001 From: aLiEz <38580409+aLIEz1@users.noreply.github.com> Date: Sun, 6 Dec 2026 08:00:23 +0800 Subject: [PATCH] feat(java): Spring AOP advice gutter icons (#8308) Java documents show Spring AOP gutter icons: on an advised method, to the advices applied to it; on an advice method, to the methods it advises. One target navigates directly; several open the chooser (Navigate to AOP Advices / Advised Methods), advice rows showing the advice kind and its order when statically known. The backend adds server-independent SpringAopMarker types and lsp_spring_aop_markers, asking only a server attached to the document that declares experimental java-analyzer/springAopMarkers (java-analyzer first; jdtls and older builds are not asked), refreshing on java-analyzer/springAopMarkersChanged. The Spring bean gutter's request/refresh logic moves into a shared lspMarkerGutter driver used by both. fixtures/spring-app gains aspects covering both directions, all advice kinds, named pointcuts, &&/||/! and order. Co-authored-by: aLIEz1 <38580409+aLIEz1@users.noreply.github.com> --- crates/ide-core/src/event.rs | 2 + crates/ide-host/src/ops/lsp.rs | 21 ++ crates/ide-lsp/src/caps.rs | 9 +- crates/ide-lsp/src/handler.rs | 3 + crates/ide-lsp/src/lib.rs | 1 + crates/ide-lsp/src/spring_aop.rs | 103 ++++++ crates/ide-lsp/src/types.rs | 43 +++ .../ide-lsp/tests/integration/mock_server.rs | 84 +++++ fixtures/README.md | 2 +- fixtures/spring-app/pom.xml | 7 +- .../java/com/example/shop/AuditAspect.java | 37 ++ .../main/java/com/example/shop/Audited.java | 15 + .../main/java/com/example/shop/Checkout.java | 3 + .../main/java/com/example/shop/Inventory.java | 17 + .../java/com/example/shop/LoggingAspect.java | 39 ++ .../java/com/example/shop/NegationAspect.java | 22 ++ .../com/example/shop/NotificationAspect.java | 20 + .../java/com/example/shop/OrderService.java | 2 + .../java/com/example/shop/TimingAspect.java | 27 ++ .../com/example/shop/UnsupportedAspect.java | 20 + src-tauri/tests/commands.snap | 1 + src/bindings.ts | 40 +- src/editor/lsp/index.ts | 2 + src/editor/navigation/index.ts | 1 + src/editor/navigation/lspMarkerGutter.ts | 235 ++++++++++++ src/editor/navigation/springAopGutter.test.ts | 348 ++++++++++++++++++ src/editor/navigation/springAopGutter.ts | 116 ++++++ src/editor/navigation/springBeanGutter.ts | 210 +---------- src/platform/locales/text/en.json | 8 + src/platform/locales/text/zh.json | 8 + src/ui/icons.tsx | 2 + src/ui/openidea/gutter/springAopToAdvice.svg | 7 + .../gutter/springAopToAdvice_dark.svg | 7 + src/ui/openidea/gutter/springAopToAdvised.svg | 7 + .../gutter/springAopToAdvised_dark.svg | 7 + 35 files changed, 1274 insertions(+), 202 deletions(-) create mode 100644 crates/ide-lsp/src/spring_aop.rs create mode 100644 fixtures/spring-app/src/main/java/com/example/shop/AuditAspect.java create mode 100644 fixtures/spring-app/src/main/java/com/example/shop/Audited.java create mode 100644 fixtures/spring-app/src/main/java/com/example/shop/Inventory.java create mode 100644 fixtures/spring-app/src/main/java/com/example/shop/LoggingAspect.java create mode 100644 fixtures/spring-app/src/main/java/com/example/shop/NegationAspect.java create mode 100644 fixtures/spring-app/src/main/java/com/example/shop/NotificationAspect.java create mode 100644 fixtures/spring-app/src/main/java/com/example/shop/TimingAspect.java create mode 100644 fixtures/spring-app/src/main/java/com/example/shop/UnsupportedAspect.java create mode 100644 src/editor/navigation/lspMarkerGutter.ts create mode 100644 src/editor/navigation/springAopGutter.test.ts create mode 100644 src/editor/navigation/springAopGutter.ts create mode 100644 src/ui/openidea/gutter/springAopToAdvice.svg create mode 100644 src/ui/openidea/gutter/springAopToAdvice_dark.svg create mode 100644 src/ui/openidea/gutter/springAopToAdvised.svg create mode 100644 src/ui/openidea/gutter/springAopToAdvised_dark.svg diff --git a/crates/ide-core/src/event.rs b/crates/ide-core/src/event.rs index f803904d69..1210434a0f 100644 --- a/crates/ide-core/src/event.rs +++ b/crates/ide-core/src/event.rs @@ -467,6 +467,8 @@ pub enum LspRefreshKind { FlutterOutline, /// Spring bean markers of open documents may have changed. SpringBeanMarkers, + /// Spring AOP markers of open documents may have changed. + SpringAopMarkers, } #[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 9d548e363f..66f4c825d3 100644 --- a/crates/ide-host/src/ops/lsp.rs +++ b/crates/ide-host/src/ops/lsp.rs @@ -790,6 +790,26 @@ pub async fn lsp_spring_bean_markers( result } +/// The document's Spring AOP markers (advised methods with their advices, advice methods with +/// the methods they advise); `None` when no server attached to it provides them. Cancel with +/// `cancel_request(request)`. +#[command(trust = trusted)] +pub async fn lsp_spring_aop_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_aop_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)] @@ -3814,6 +3834,7 @@ ide_command::domain!( lsp_implementation_locations, lsp_file_references, lsp_spring_bean_markers, + lsp_spring_aop_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 8faa38b87c..4b05c7bc31 100644 --- a/crates/ide-lsp/src/caps.rs +++ b/crates/ide-lsp/src/caps.rs @@ -168,8 +168,13 @@ pub fn client_capabilities() -> Value { "typeHierarchy": { "dynamicRegistration": false } }, // rust-analyzer: report when the project has loaded (`quiescent`). - // java-analyzer: Spring bean markers of open documents may have changed (`spring_beans.rs`). - "experimental": { "serverStatusNotification": true, "java-analyzer/springBeanMarkersChanged": true }, + // java-analyzer: Spring bean and AOP markers of open documents may have changed + // (`spring_beans.rs`, `spring_aop.rs`). + "experimental": { + "serverStatusNotification": true, + "java-analyzer/springBeanMarkersChanged": true, + "java-analyzer/springAopMarkersChanged": true + }, // Jupyter notebooks: code cells are synced with `notebookDocument/*` (see `notebook.rs`). "notebookDocument": { "synchronization": { "dynamicRegistration": false, "executionSummarySupport": false } } }) diff --git a/crates/ide-lsp/src/handler.rs b/crates/ide-lsp/src/handler.rs index 3f79eb78df..29e6198d47 100644 --- a/crates/ide-lsp/src/handler.rs +++ b/crates/ide-lsp/src/handler.rs @@ -783,6 +783,9 @@ impl Handler for ClientHandler { crate::spring_beans::CHANGED if self.server.is_live(self.generation) => { mgr.sink().emit(IdeEvent::LspRefresh { server: self.server.id, kind: LspRefreshKind::SpringBeanMarkers }) } + crate::spring_aop::CHANGED if self.server.is_live(self.generation) => { + mgr.sink().emit(IdeEvent::LspRefresh { server: self.server.id, kind: LspRefreshKind::SpringAopMarkers }) + } "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 5c4a8f90ac..8c32586f20 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_aop; mod spring_beans; mod switch_source_header; mod tcp; diff --git a/crates/ide-lsp/src/spring_aop.rs b/crates/ide-lsp/src/spring_aop.rs new file mode 100644 index 0000000000..57c5bdd271 --- /dev/null +++ b/crates/ide-lsp/src/spring_aop.rs @@ -0,0 +1,103 @@ +//! Spring AOP markers of a Java document: advised methods with the advices applied to them, and +//! advice methods with the methods they advise. The first source is java-analyzer's +//! `java-analyzer/springAopMarkers`, one request per document; its answer is turned into the +//! server-independent [`SpringAopMarker`]s the gutter shows. + +use crate::types::{SpringAopAdviceKind, SpringAopDirection, SpringAopMarker, SpringAopTarget}; +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, adviceKind, order }] }] }`. +pub(crate) const METHOD: &str = "java-analyzer/springAopMarkers"; +/// Sent by the server, to clients that declare it, when markers of open documents may have changed. +pub(crate) const CHANGED: &str = "java-analyzer/springAopMarkersChanged"; +/// The first answer of a large workspace pairs every advised method with its advices. +const TIMEOUT: Duration = Duration::from_secs(60); + +#[derive(Deserialize)] +struct Answer { + markers: Vec, +} + +#[derive(Deserialize)] +struct WireMarker { + range: lsp::Range, + name: String, + direction: SpringAopDirection, + targets: Vec, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct WireTarget { + location: lsp::Location, + label: String, + #[serde(default)] + advice_kind: Option, + #[serde(default)] + order: Option, +} + +impl LspManager { + /// The document's Spring AOP 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_aop_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(); + // AOP markers are 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(SpringAopTarget { + location: conv.location(&t.location)?, + label: t.label, + advice_kind: t.advice_kind, + order: t.order, + }) + }) + .collect(); + (!targets.is_empty()).then(|| SpringAopMarker { + 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 1d88c880ff..c6529c75d4 100644 --- a/crates/ide-lsp/src/types.rs +++ b/crates/ide-lsp/src/types.rs @@ -840,3 +840,46 @@ pub enum SpringBeanResolution { Resolved, Candidate, } + +/// A Spring AOP marker on a Java method: an advised method (`ToAdvice`) or an advice +/// method (`ToAdvised`), whichever server found it. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct SpringAopMarker { + /// The method's name range. + pub range: Range, + pub name: String, + pub direction: SpringAopDirection, + /// Never empty. + pub targets: Vec, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum SpringAopDirection { + /// On an advised method: its targets are the advices applied to it. + ToAdvice, + /// On an advice method: its targets are the methods it advises. + ToAdvised, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct SpringAopTarget { + pub location: Location, + pub label: String, + /// Set on an advice target; `None` on an advised method. + pub advice_kind: Option, + /// The advice's Spring `order`; `None` when it has none. + pub order: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum SpringAopAdviceKind { + Before, + After, + AfterReturning, + AfterThrowing, + Around, +} diff --git a/crates/ide-lsp/tests/integration/mock_server.rs b/crates/ide-lsp/tests/integration/mock_server.rs index 2957c8c8e5..ac62cb06c5 100644 --- a/crates/ide-lsp/tests/integration/mock_server.rs +++ b/crates/ide-lsp/tests/integration/mock_server.rs @@ -11014,3 +11014,87 @@ async fn move_without_the_pair_on_java_analyzer_says_so() { assert!(err.message.starts_with("java-analyzer doesn't support Move"), "{}", err.message); h.mgr.shutdown_all().await; } + +#[tokio::test(flavor = "multi_thread")] +async fn spring_aop_markers_come_from_the_server_that_declares_them() { + let mut caps = incremental_caps(); + caps["positionEncoding"] = json!("utf-8"); + caps["experimental"] = json!({ "java-analyzer/springAopMarkers": true }); + let h = harness(&[("aop", 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 ["aop", "plain"] { + h.wait_status(name, ServerStatus::Ready).await; + } + let (aop, plain) = (h.launcher.state("aop"), h.launcher.state("plain")); + eventually(|| !aop.notified("textDocument/didOpen").is_empty()).await; + let init = &aop.requested("initialize")[0]; + assert_eq!(init["capabilities"]["experimental"]["java-analyzer/springAopMarkersChanged"], true); + let at = |l: u32, c0: u32, c1: u32| json!({"start":{"line":l,"character":c0},"end":{"line":l,"character":c1}}); + aop.respond( + "java-analyzer/springAopMarkers", + json!({ "markers": [ + { "range": at(0, 6, 11), "name": "clock", "direction": "toAdvice", "targets": [ + { "location": { "uri": uri_of(&path), "range": at(1, 6, 9) }, "label": "logBefore", "adviceKind": "before", "order": 1 }, + { "location": { "uri": uri_of(&path), "range": at(0, 0, 2) }, "label": "é", "adviceKind": "around", "order": null }, + ] }, + { "range": at(1, 6, 9), "name": "App", "direction": "toAdvised", "targets": [ + { "location": { "uri": uri_of(&path), "range": at(0, 3, 8) }, "label": "clock", "adviceKind": null, "order": null }, + ] }, + { "range": at(1, 0, 3), "name": "App", "direction": "toAdvised", "targets": [] }, + ] }), + ); + let markers = h.mgr.spring_aop_markers(doc, Default::default()).await.unwrap().unwrap(); + assert_eq!(aop.requested("java-analyzer/springAopMarkers")[0], json!({ "textDocument": { "uri": uri_of(&path) } })); + assert!(plain.requested("java-analyzer/springAopMarkers").is_empty()); + // The marker without targets is dropped; positions are UTF-16 in every file. + assert_eq!(markers.len(), 2); + assert_eq!(markers[0].range, rng(0, 3, 0, 8)); + assert_eq!(markers[0].direction, SpringAopDirection::ToAdvice); + assert_eq!(markers[0].targets[0].location.range, rng(1, 6, 1, 9)); + assert_eq!(markers[0].targets[0].advice_kind, Some(SpringAopAdviceKind::Before)); + assert_eq!(markers[0].targets[0].order, Some(1)); + assert_eq!(markers[0].targets[1].location.range, rng(0, 0, 0, 1)); + assert_eq!(markers[0].targets[1].advice_kind, Some(SpringAopAdviceKind::Around)); + assert_eq!(markers[0].targets[1].order, None); + assert_eq!(markers[1].direction, SpringAopDirection::ToAdvised); + assert_eq!(markers[1].targets[0].advice_kind, None); + assert_eq!(markers[1].targets[0].order, None); + + let refreshes = || { + h.events + .lock() + .iter() + .filter(|e| matches!(e, IdeEvent::LspRefresh { kind: LspRefreshKind::SpringAopMarkers, .. })) + .count() + }; + aop.peer().notify("java-analyzer/springAopMarkersChanged", json!({})).unwrap(); + eventually(|| refreshes() == 1).await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn spring_aop_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_aop_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_aop_markers(doc, Default::default()).await.unwrap(), None); + assert!(plain.requested("java-analyzer/springAopMarkers").is_empty()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn spring_aop_markers_follow_the_servers_features() { + let mut caps = incremental_caps(); + caps["experimental"] = json!({ "java-analyzer/springAopMarkers": true }); + // Used for diagnostics only: no navigation from it, AOP markers included. + let h = harness_configured("mock", "mk", &[("aop", caps)], |cfg| cfg.features = vec!["diagnostics".into()]); + let (doc, _) = h.open("a.mk", "class App {}\n"); + h.wait_status("aop", ServerStatus::Ready).await; + let aop = h.launcher.state("aop"); + eventually(|| !aop.notified("textDocument/didOpen").is_empty()).await; + assert_eq!(h.mgr.spring_aop_markers(doc, Default::default()).await.unwrap(), None); + assert!(aop.requested("java-analyzer/springAopMarkers").is_empty()); +} diff --git a/fixtures/README.md b/fixtures/README.md index cc85c22a14..98f6769477 100644 --- a/fixtures/README.md +++ b/fixtures/README.md @@ -20,7 +20,7 @@ something to show. | `java-app/` | JDK 21, Maven 3.9 | `mvn compile exec:java` | `mvn test` | `mvn test -DopenideaFail=true` | unused variable in `App.java` | | `java-multimodule/` | JDK 21, Maven 3.9 | `mvn -q compile` | — | — | — | | `kotlin-gradle-multi/` | JDK 21, Gradle 8 (no wrapper) | `gradle :app:run` | — | — | — | -| `spring-app/` | JDK 21, Maven 3.9, Spring Framework 6.2 | `mvn compile exec:java -Dexec.mainClass=com.example.shop.AppConfig` | — | — | — | +| `spring-app/` | JDK 21, Maven 3.9, Spring Framework 6.2, AspectJ 1.9 | `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 index bb01eb1b64..b011f25faf 100644 --- a/fixtures/spring-app/pom.xml +++ b/fixtures/spring-app/pom.xml @@ -7,7 +7,7 @@ com.example openidea-fixture-spring 0.1.0 - OpenIDEA QA fixture: Spring beans and their injection points + OpenIDEA QA fixture: Spring beans, injection points and Spring AOP advice navigation 21 @@ -20,5 +20,10 @@ spring-context 6.2.12 + + org.aspectj + aspectjweaver + 1.9.24 + diff --git a/fixtures/spring-app/src/main/java/com/example/shop/AuditAspect.java b/fixtures/spring-app/src/main/java/com/example/shop/AuditAspect.java new file mode 100644 index 0000000000..af3200982b --- /dev/null +++ b/fixtures/spring-app/src/main/java/com/example/shop/AuditAspect.java @@ -0,0 +1,37 @@ +package com.example.shop; + +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.After; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.aspectj.lang.annotation.Pointcut; +import org.springframework.core.Ordered; +import org.springframework.stereotype.Component; + +/** + * Order from {@link Ordered#getOrder()}, so {@code audit} is second in {@code place}'s chooser. + * {@code trace} matches {@code @annotation} on the method and {@code @within} on the class, and + * references {@link LoggingAspect}'s pointcut by its qualified name. + */ +@Aspect +@Component +public class AuditAspect implements Ordered { + + @Pointcut("execution(* com.example.shop.OrderService.place(..))") + public void orderPlacement() {} + + @Override + public int getOrder() { + return 2; + } + + @After("orderPlacement()") + public void audit(JoinPoint joinPoint) { + System.out.println("audit " + joinPoint.getSignature().toShortString()); + } + + @Before("com.example.shop.LoggingAspect.serviceLayer() && (@annotation(com.example.shop.Audited) || @within(com.example.shop.Audited))") + public void trace(JoinPoint joinPoint) { + System.out.println("traced " + joinPoint.getSignature().toShortString()); + } +} diff --git a/fixtures/spring-app/src/main/java/com/example/shop/Audited.java b/fixtures/spring-app/src/main/java/com/example/shop/Audited.java new file mode 100644 index 0000000000..be766afb38 --- /dev/null +++ b/fixtures/spring-app/src/main/java/com/example/shop/Audited.java @@ -0,0 +1,15 @@ +package com.example.shop; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Method-level {@code @annotation} and type-level {@code @within} target for AOP navigation: + * {@link OrderService#place(String)} and {@link Inventory#reconcile()} carry it on the method, + * {@link Checkout} on the class. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.METHOD, ElementType.TYPE}) +public @interface Audited {} 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 index 713ad83f7f..0cc49e8cc5 100644 --- a/fixtures/spring-app/src/main/java/com/example/shop/Checkout.java +++ b/fixtures/spring-app/src/main/java/com/example/shop/Checkout.java @@ -10,7 +10,10 @@ 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. + * AOP navigation: the class-level {@code @Audited} makes {@code checkout} an {@code @within} + * target of AuditAspect.trace. */ +@Audited @Component public class Checkout { @Autowired diff --git a/fixtures/spring-app/src/main/java/com/example/shop/Inventory.java b/fixtures/spring-app/src/main/java/com/example/shop/Inventory.java new file mode 100644 index 0000000000..fc1222ccaf --- /dev/null +++ b/fixtures/spring-app/src/main/java/com/example/shop/Inventory.java @@ -0,0 +1,17 @@ +package com.example.shop; + +import org.springframework.stereotype.Component; + +/** + * Negation demo with {@link NegationAspect}: {@code stock} carries no {@code @Audited}, so that + * aspect's advice matches it; {@code reconcile} is annotated, so {@code !@annotation} excludes it. + */ +@Component +public class Inventory { + public String stock(String item) { + return "stock:" + item; + } + + @Audited + public void reconcile() {} +} diff --git a/fixtures/spring-app/src/main/java/com/example/shop/LoggingAspect.java b/fixtures/spring-app/src/main/java/com/example/shop/LoggingAspect.java new file mode 100644 index 0000000000..d7d226002f --- /dev/null +++ b/fixtures/spring-app/src/main/java/com/example/shop/LoggingAspect.java @@ -0,0 +1,39 @@ +package com.example.shop; + +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.AfterReturning; +import org.aspectj.lang.annotation.AfterThrowing; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.aspectj.lang.annotation.Pointcut; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; + +/** + * AOP navigation: {@code place} is advised by four advices (the chooser), {@code checkout} by + * two, {@code SmsNotifier.send} by one (a direct jump). {@code serviceLayer} is the named + * pointcut another aspect references; the after advices use Spring's {@code pointcut} alias. + */ +@Aspect +@Component +@Order(1) +public class LoggingAspect { + + @Pointcut("within(com.example.shop..*)") + public void serviceLayer() {} + + @Before("serviceLayer() && execution(* com.example.shop.OrderService.*(..))") + public void beforeOrder(JoinPoint joinPoint) { + System.out.println("before " + joinPoint.getSignature().toShortString()); + } + + @AfterReturning(pointcut = "execution(* com.example.shop.Checkout.checkout(..))", returning = "order") + public void afterCheckout(Object order) { + System.out.println("checkout returned " + order); + } + + @AfterThrowing(pointcut = "execution(* com.example.shop.EmailNotifier.send(..))", throwing = "error") + public void afterSendFailure(Throwable error) { + System.out.println("email failed: " + error); + } +} diff --git a/fixtures/spring-app/src/main/java/com/example/shop/NegationAspect.java b/fixtures/spring-app/src/main/java/com/example/shop/NegationAspect.java new file mode 100644 index 0000000000..72530ad738 --- /dev/null +++ b/fixtures/spring-app/src/main/java/com/example/shop/NegationAspect.java @@ -0,0 +1,22 @@ +package com.example.shop; + +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.springframework.stereotype.Component; + +/** + * Negation: {@code !@annotation(com.example.shop.Audited)} excludes {@link Inventory#reconcile()} + * from this advice, while {@link Inventory#stock(String)} carries no annotation and is matched: + * the advice method's icon navigates to {@code stock} only, and {@code reconcile} shows just + * {@link AuditAspect#trace}, the {@code @annotation} advice it still matches. + */ +@Aspect +@Component +public class NegationAspect { + + @Before("execution(* com.example.shop.Inventory.*(..)) && !@annotation(com.example.shop.Audited)") + public void beforeUnannotated(JoinPoint joinPoint) { + System.out.println("unannotated " + joinPoint.getSignature().toShortString()); + } +} diff --git a/fixtures/spring-app/src/main/java/com/example/shop/NotificationAspect.java b/fixtures/spring-app/src/main/java/com/example/shop/NotificationAspect.java new file mode 100644 index 0000000000..cb12fcd736 --- /dev/null +++ b/fixtures/spring-app/src/main/java/com/example/shop/NotificationAspect.java @@ -0,0 +1,20 @@ +package com.example.shop; + +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.After; +import org.aspectj.lang.annotation.Aspect; +import org.springframework.stereotype.Component; + +/** + * No order, so its rows show the advice kind only. {@code Notifier+} matches both + * implementations: the advice's chooser has two targets, and each notifier has this one advice. + */ +@Aspect +@Component +public class NotificationAspect { + + @After("execution(* com.example.shop.Notifier+.send(..))") + public void afterEverySend(JoinPoint joinPoint) { + System.out.println("sent " + joinPoint.getSignature().toShortString()); + } +} 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 index e19b3a97e2..1e28dce289 100644 --- a/fixtures/spring-app/src/main/java/com/example/shop/OrderService.java +++ b/fixtures/spring-app/src/main/java/com/example/shop/OrderService.java @@ -4,6 +4,8 @@ import org.springframework.stereotype.Service; @Service public class OrderService { + /** {@code @annotation(Audited)} in AuditAspect.trace matches this method. */ + @Audited public String place(String item) { return "order:" + item; } diff --git a/fixtures/spring-app/src/main/java/com/example/shop/TimingAspect.java b/fixtures/spring-app/src/main/java/com/example/shop/TimingAspect.java new file mode 100644 index 0000000000..da53367483 --- /dev/null +++ b/fixtures/spring-app/src/main/java/com/example/shop/TimingAspect.java @@ -0,0 +1,27 @@ +package com.example.shop; + +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; + +/** + * {@code execution} with {@code *} (return type and method) and {@code ..} (package and + * arguments), and {@code @Order(3)}: its advice is last in {@code place}'s chooser. + */ +@Aspect +@Component +@Order(3) +public class TimingAspect { + + @Around("execution(* com.example.shop..*Service.*(..))") + public Object timed(ProceedingJoinPoint joinPoint) throws Throwable { + long start = System.nanoTime(); + try { + return joinPoint.proceed(); + } finally { + System.out.println(joinPoint.getSignature().toShortString() + " took " + (System.nanoTime() - start) + " ns"); + } + } +} diff --git a/fixtures/spring-app/src/main/java/com/example/shop/UnsupportedAspect.java b/fixtures/spring-app/src/main/java/com/example/shop/UnsupportedAspect.java new file mode 100644 index 0000000000..51be25af6c --- /dev/null +++ b/fixtures/spring-app/src/main/java/com/example/shop/UnsupportedAspect.java @@ -0,0 +1,20 @@ +package com.example.shop; + +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.springframework.stereotype.Component; + +/** + * {@code args(...)} is outside the first slice: this advice contributes no AOP marker, and its + * advice method shows no icon. + */ +@Aspect +@Component +public class UnsupportedAspect { + + @Before("execution(* com.example.shop..*.*(..)) && args(java.lang.String)") + public void logArgument(JoinPoint joinPoint) { + System.out.println("argument " + joinPoint.getArgs()[0]); + } +} diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 307eaefc55..662a6b033a 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -501,6 +501,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_aop_markers 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 diff --git a/src/bindings.ts b/src/bindings.ts index 884b56b757..f2164f8ac2 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -1349,6 +1349,12 @@ 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 AOP markers (advised methods with their advices, advice methods with + * the methods they advise); `None` when no server attached to it provides them. Cancel with + * `cancel_request(request)`. + */ + lspSpringAopMarkers: (request: RequestId, doc: DocId) => typedError(__TAURI_INVOKE("lsp_spring_aop_markers", { request, doc })), /** * 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)`. @@ -13023,7 +13029,9 @@ export type LspRefreshKind = "inlayHints" | "semanticTokens" | "codeLens" | /** The Dart server published a document's Flutter outline. */ "flutterOutline" | /** Spring bean markers of open documents may have changed. */ -"springBeanMarkers"; +"springBeanMarkers" | +/** Spring AOP markers of open documents may have changed. */ +"springAopMarkers"; export type MainToolbarSettings = { left?: string[], @@ -17566,6 +17574,36 @@ export type SpellingSettings = { defaultDictionary?: string | null, }; +export type SpringAopAdviceKind = "before" | "after" | "afterReturning" | "afterThrowing" | "around"; + +export type SpringAopDirection = +/** On an advised method: its targets are the advices applied to it. */ +"toAdvice" | +/** On an advice method: its targets are the methods it advises. */ +"toAdvised"; + +/** + * A Spring AOP marker on a Java method: an advised method (`ToAdvice`) or an advice + * method (`ToAdvised`), whichever server found it. + */ +export type SpringAopMarker = { + /** The method's name range. */ + range: Range, + name: string, + direction: SpringAopDirection, + /** Never empty. */ + targets: SpringAopTarget[], +}; + +export type SpringAopTarget = { + location: Location, + label: string, + /** Set on an advice target; `None` on an advised method. */ + adviceKind: SpringAopAdviceKind | null, + /** The advice's Spring `order`; `None` when it has none. */ + order: number | null, +}; + export type SpringBeanDirection = "toBean" | "toInjectionPoint"; /** diff --git a/src/editor/lsp/index.ts b/src/editor/lsp/index.ts index df4a08ded5..87892ffdf1 100644 --- a/src/editor/lsp/index.ts +++ b/src/editor/lsp/index.ts @@ -51,6 +51,7 @@ import { implementationGutter, pythonStubGutter, registerNavigationActions, + springAopGutter, springBeanGutter, } from "@/editor/navigation"; import { @@ -140,6 +141,7 @@ export function activate(): () => void { registerEditorContribution({ id: "lsp.lineMarkers", order: 56, extensions: implementationGutter }), registerEditorContribution({ id: "lsp.pythonStubs", order: 57, extensions: pythonStubGutter }), registerEditorContribution({ id: "lsp.springBeans", order: 58, extensions: springBeanGutter }), + registerEditorContribution({ id: "lsp.springAop", order: 59, extensions: springAopGutter }), // 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/navigation/index.ts b/src/editor/navigation/index.ts index e54fe2a938..46eb830520 100644 --- a/src/editor/navigation/index.ts +++ b/src/editor/navigation/index.ts @@ -348,5 +348,6 @@ export function registerNavigationActions(): () => void { } export { implementationGutter } from "./implementationGutter"; +export { springAopGutter } from "./springAopGutter"; export { springBeanGutter } from "./springBeanGutter"; export { pythonStubGutter } from "./pythonStubs"; diff --git a/src/editor/navigation/lspMarkerGutter.ts b/src/editor/navigation/lspMarkerGutter.ts new file mode 100644 index 0000000000..5dba69cf96 --- /dev/null +++ b/src/editor/navigation/lspMarkerGutter.ts @@ -0,0 +1,235 @@ +/** + * Per-document gutter markers answered by one language-server request: Spring bean and Spring + * AOP navigation (`lspSpringBeanMarkers`, `lspSpringAopMarkers`). One cancellable request per + * document and 500 ms debounce; late answers are dropped. The markers follow their lines through + * edits, and are asked again when the server says they changed, when it settles, and when a + * source server stops or is removed. Library sources and documents without Gutter Icons ask + * nothing; a navigation the user waits for is served first. + */ +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 { + commands, + isCancelled, + nextRequestId, + onIdeEvent, + type IdeError, + type LspRefreshKind, + type RequestId, +} from "@/platform/ipc"; +import { editorPrefs } from "@/platform/editorSettings"; +import { useProject } from "@/platform/project"; + +const DEBOUNCE_MS = 500; + +export interface PlacedMarker { + marker: M; + /** Start of the marker's line in the current state. */ + pos: number; +} + +export interface MarkerGutterOptions { + /** Ask the server for this document's markers; `null` when no attached server provides them. */ + request: ( + request: RequestId, + doc: number, + ) => Promise<{ status: "ok"; data: M[] | null } | { status: "error"; error: IdeError }>; + /** The refresh kind the server sends when these markers may have changed. */ + refreshKind: LspRefreshKind; + /** Markers to show, left to right within a line. */ + place: (doc: Text, markers: readonly M[]) => PlacedMarker[]; + /** The gutter icon (a button) for one placed marker. */ + marker: (value: M) => GutterMarker; + /** Position in the shared icon area, after the inheritance icons (50). */ + order: number; +} + +interface LivePlugin { + readonly refreshKind: LspRefreshKind; + refreshSoon(): void; + yieldToNavigation(): void; + resumeAfterNavigation(): void; +} + +const live = new Set(); +const watchedKinds = new Set(); +let watching = false; + +function refreshAll(kind?: LspRefreshKind) { + for (const plugin of live) if (kind === undefined || plugin.refreshKind === kind) plugin.refreshSoon(); +} + +function watchChanges(kind: LspRefreshKind) { + if (!watchedKinds.has(kind)) { + watchedKinds.add(kind); + // The server's own "markers changed" (another file edited, a re-import). + onLspRefresh(kind, () => refreshAll(kind)); + } + if (watching) return; + watching = true; + // 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(); + } + }); +} + +/** Gutter markers of `ctx`'s document, placed as `options` says and drawn by its `marker` factory. */ +export function lspMarkerGutter(ctx: EditorDocContext, options: MarkerGutterOptions): Extension { + const setPlaced = StateEffect.define[]>(); + + const field = StateField.define[]>({ + create: () => [], + update(value, tr) { + for (const e of tr.effects) if (e.is(setPlaced)) return e.value; + if (!tr.docChanged || !value.length) return value; + return value.map((p) => ({ ...p, pos: mapLineStart(tr, p.pos) })); + }, + }); + + /** Marker sets by field value: the icon area asks on every view update (caret moves, scrolling). */ + const markerSets = new WeakMap[], RangeSet>(); + + function placedSet(placed: readonly PlacedMarker[]): RangeSet { + let set = markerSets.get(placed); + if (!set) { + set = RangeSet.of( + placed.map(({ marker, pos }) => options.marker(marker).range(pos)), + true, + ); + markerSets.set(placed, set); + } + return set; + } + + class MarkerPlugin implements LivePlugin { + readonly refreshKind = options.refreshKind; + 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) { + live.add(this); + watchChanges(options.refreshKind); + 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: PlacedMarker[]) { + const current = this.view.state.field(field); + if (current.length || placed.length) this.view.dispatch({ effects: setPlaced.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(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( + () => options.request(request, ctx.doc), + () => !stale(), + ); + if (stale()) return; + this.show(options.place(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("[lspMarkers]", e); + } finally { + if (this.request === request) this.request = null; + } + } + + destroy() { + this.refresh.cancel(); + this.cancelRequest(); + this.offSettings(); + this.generation++; + live.delete(this); + } + } + + return [ + field, + ViewPlugin.define((view) => new MarkerPlugin(view)), + // In the shared icon area, beside the inheritance icons and the other language markers. + iconAreaSource.of({ + order: options.order, + markers: (view) => (gutterIconsOn(view.state) ? placedSet(view.state.field(field)) : RangeSet.empty), + }), + ]; +} diff --git a/src/editor/navigation/springAopGutter.test.ts b/src/editor/navigation/springAopGutter.test.ts new file mode 100644 index 0000000000..7f0ee403f4 --- /dev/null +++ b/src/editor/navigation/springAopGutter.test.ts @@ -0,0 +1,348 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { fireEvent } from "@testing-library/react"; + +const ipc = vi.hoisted(() => ({ lspSpringAopMarkers: 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 { SpringAopMarker, SpringAopTarget } from "@/platform/ipc"; +import { foregroundStarted } from "@/editor/lsp/foreground"; +import { useI18n } from "@/platform/i18n"; +import { useProject } from "@/platform/project"; +import { aopTooltip, springAopGutter } from "./springAopGutter"; + +// An aspect with one advice, a service whose `place` has two advices (the toAdvice chooser) and +// whose `cancel` has one (a direct jump). +const SOURCE = [ + "@Aspect", // 0 + "class AuditAspect {", // 1 + ' @Before("execution(* Service.place(..))")', // 2 + " void before() {}", // 3 advice, advises two methods + "}", // 4 + "class Service {", // 5 + " void place() {}", // 6 advised by two advices + " void cancel() {}", // 7 advised by one advice + "}", // 8 +].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, + adviceKind: SpringAopTarget["adviceKind"], + order: number | null, +): SpringAopTarget => ({ location: { path, range: range(line, 6, 4) }, label, adviceKind, order }); +const marker = ( + line: number, + col: number, + name: string, + direction: SpringAopMarker["direction"], + targets: SpringAopTarget[], +): SpringAopMarker => ({ range: range(line, col, name.length), name, direction, targets }); + +const BEFORE = target("/p/AuditAspect.java", 3, "before · AuditAspect.before()", "before", 1); +const AROUND = target("/p/TimingAspect.java", 4, "timed · TimingAspect.timed()", "around", null); +const AFTER = target("/p/NotificationAspect.java", 3, "sent · NotificationAspect.sent()", "after", 2); +const PLACE = target("/p/Service.java", 6, "place · Service.place()", null, null); +const CANCEL = target("/p/Service.java", 7, "cancel · Service.cancel()", null, null); + +const MARKERS: SpringAopMarker[] = [ + // Unsorted on purpose: the gutter orders icons by line. + marker(6, 7, "place", "toAdvice", [AROUND, BEFORE]), + marker(7, 7, "cancel", "toAdvice", [AFTER]), + marker(3, 7, "before", "toAdvised", [PLACE, CANCEL]), + // No target and a line past the end of the text: no icon. + marker(2, 20, "unmatched", "toAdvice", []), + marker(99, 0, "gone", "toAdvised", [PLACE]), +]; + +const answer = (markers: SpringAopMarker[] | null) => ({ status: "ok", data: markers }); + +describe("spring AOP gutter", () => { + let view: EditorView | null = null; + afterEach(() => { + view?.destroy(); + view = null; + vi.clearAllMocks(); + }); + + function open(language = "java", doc = 1) { + const ctx = { doc, path: "/p/AuditAspect.java", language, virtual: false } as Parameters[0]; + view = new EditorView({ + state: EditorState.create({ doc: SOURCE, extensions: [springAopGutter(ctx), iconAreaExtension] }), + parent: document.body, + }); + return view; + } + + const buttons = () => [...view!.dom.querySelectorAll("[data-spring-aop]")]; + const button = (row: string) => + buttons().find((b) => + b.title + .split("\n") + .slice(1) + .some((r) => r.startsWith(row)), + )!; + + it("puts an icon on each advised method and advice, in line order", async () => { + ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS)); + open(); + await vi.waitFor(() => expect(buttons()).toHaveLength(3), { timeout: 2000 }); + expect(ipc.lspSpringAopMarkers).toHaveBeenCalledExactlyOnceWith(7, 1); + expect(buttons().map((b) => b.dataset.springAop)).toEqual(["toAdvised", "toAdvice", "toAdvice"]); + expect(buttons().map((b) => b.title.split("\n")[0])).toEqual([ + "Navigate to Advised Methods", + "Navigate to AOP Advices", + "Navigate to AOP Advices", + ]); + }); + + it("navigates to a single advice or advised method directly", async () => { + ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS)); + open(); + await vi.waitFor(() => expect(buttons()).toHaveLength(3), { timeout: 2000 }); + fireEvent.click(button("sent · NotificationAspect.sent()")); + await vi.waitFor(() => + expect(nav.navigateTo).toHaveBeenCalledWith({ ...AFTER.location, name: "sent · NotificationAspect.sent()" }), + ); + // An advice with one advised method navigates there too. + ipc.lspSpringAopMarkers.mockResolvedValue( + answer([marker(3, 7, "cancel", "toAdvised", [CANCEL]), marker(7, 7, "cancel", "toAdvice", [AFTER])]), + ); + refresh.listeners.forEach((l) => l()); + await vi.waitFor(() => expect(buttons()).toHaveLength(2), { timeout: 2000 }); + fireEvent.click(buttons()[0]!); + await vi.waitFor(() => expect(nav.navigateTo).toHaveBeenCalledTimes(2)); + expect(nav.navigateTo.mock.calls[1]![0].path).toBe("/p/Service.java"); + expect(nav.openPopup).not.toHaveBeenCalled(); + }); + + it("opens the chooser with the exact titles, advice rows saying kind and order", async () => { + ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS)); + open(); + await vi.waitFor(() => expect(buttons()).toHaveLength(3), { timeout: 2000 }); + fireEvent.click(button("timed · TimingAspect.timed()")); + await vi.waitFor(() => expect(nav.openPopup).toHaveBeenCalledOnce()); + const chooser = nav.openPopup.mock.calls[0]![0]; + expect(chooser.title).toBe("Navigate to AOP Advices"); + expect(chooser.items).toEqual([ + { id: "0", label: "timed · TimingAspect.timed()", detail: "Around advice" }, + { id: "1", label: "before · AuditAspect.before()", detail: "Before advice · order 1" }, + ]); + expect(nav.pinToFind).toHaveBeenCalledWith("place", expect.any(Array), undefined); + expect(nav.navigateTo).not.toHaveBeenCalled(); + }); + + it("lists advised methods by their label only", async () => { + ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS)); + open(); + await vi.waitFor(() => expect(buttons()).toHaveLength(3), { timeout: 2000 }); + fireEvent.click(button("place · Service.place()")); + await vi.waitFor(() => expect(nav.openPopup).toHaveBeenCalledOnce()); + const chooser = nav.openPopup.mock.calls[0]![0]; + expect(chooser.title).toBe("Navigate to Advised Methods"); + expect(chooser.items).toEqual([ + { id: "0", label: "place · Service.place()" }, + { id: "1", label: "cancel · Service.cancel()" }, + ]); + }); + + it("writes each tooltip row like the chooser, kind and order included", async () => { + ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS)); + open(); + await vi.waitFor(() => expect(buttons()).toHaveLength(3), { timeout: 2000 }); + expect(button("timed · TimingAspect.timed()").title).toBe( + "Navigate to AOP Advices\ntimed · TimingAspect.timed() — Around advice\nbefore · AuditAspect.before() — Before advice · order 1", + ); + expect(button("sent · NotificationAspect.sent()").title).toBe( + "Navigate to AOP Advices\nsent · NotificationAspect.sent() — After advice · order 2", + ); + expect(buttons()[0]!.title).toBe("Navigate to Advised Methods\nplace · Service.place()\ncancel · Service.cancel()"); + // The accessible name is the tooltip, so the icon works from the keyboard. + expect(button("timed · TimingAspect.timed()").getAttribute("aria-label")).toBe( + button("timed · TimingAspect.timed()").title, + ); + }); + + it("names advice kinds and orders in the current locale", async () => { + const texts = { "Before advice": "前置通知", "order {n}": "顺序 {n}" }; + useI18n.setState({ locale: "zh", texts }); + try { + ipc.lspSpringAopMarkers.mockResolvedValue(answer([MARKERS[0]!])); + open(); + await vi.waitFor(() => expect(buttons()).toHaveLength(1), { timeout: 2000 }); + expect(buttons()[0]!.title).toBe( + "Navigate to AOP Advices\ntimed · TimingAspect.timed() — Around advice\nbefore · AuditAspect.before() — 前置通知 · 顺序 1", + ); + fireEvent.click(buttons()[0]!); + await vi.waitFor(() => expect(nav.openPopup).toHaveBeenCalledOnce()); + expect(nav.openPopup.mock.calls[0]![0].items[1]).toEqual({ + id: "1", + label: "before · AuditAspect.before()", + detail: "前置通知 · 顺序 1", + }); + } finally { + useI18n.setState({ locale: "en", texts: {} }); + } + }); + + it("keeps a late answer for older text from replacing the current one", async () => { + let first!: (v: unknown) => void; + ipc.lspSpringAopMarkers.mockReturnValueOnce(new Promise((r) => (first = r))); + open(); + await vi.waitFor(() => expect(ipc.lspSpringAopMarkers).toHaveBeenCalledOnce(), { timeout: 2000 }); + ipc.lspSpringAopMarkers.mockResolvedValue(answer([MARKERS[1]!])); + 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("asks again when the server says the markers changed, clearing stale icons", async () => { + ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS)); + open(); + await vi.waitFor(() => expect(buttons()).toHaveLength(3), { timeout: 2000 }); + // The advice's pointcut was narrowed in another file. + ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS.filter((m) => m.name !== "place"))); + refresh.listeners.forEach((l) => l()); + await vi.waitFor(() => expect(buttons()).toHaveLength(2), { timeout: 2000 }); + // No source any more (another server took over): no icons. + ipc.lspSpringAopMarkers.mockResolvedValue(answer(null)); + refresh.listeners.forEach((l) => l()); + await vi.waitFor(() => expect(buttons()).toHaveLength(0), { timeout: 2000 }); + }); + + it("drops an answer already on its way when the markers changed", async () => { + ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS)); + open(); + await vi.waitFor(() => expect(buttons()).toHaveLength(3), { timeout: 2000 }); + let late!: (v: unknown) => void; + ipc.lspSpringAopMarkers.mockReturnValueOnce(new Promise((r) => (late = r))); + refresh.listeners.forEach((l) => l()); + await vi.waitFor(() => expect(ipc.lspSpringAopMarkers).toHaveBeenCalledTimes(2), { timeout: 2000 }); + ipc.lspSpringAopMarkers.mockResolvedValue(answer([MARKERS[1]!])); + refresh.listeners.forEach((l) => l()); + late(answer(MARKERS.slice(0, 2))); + await new Promise((r) => setTimeout(r, 50)); + expect(buttons()).toHaveLength(3); + await vi.waitFor(() => expect(buttons()).toHaveLength(1), { timeout: 2000 }); + }); + + it("asks again when the source server stops, clearing its icons", async () => { + ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS)); + open(); + await vi.waitFor(() => expect(buttons()).toHaveLength(3), { timeout: 2000 }); + ipc.lspSpringAopMarkers.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 nothing and shows nothing while Gutter Icons are off, then asks when turned 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.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS)); + open(); + await new Promise((r) => setTimeout(r, 700)); + expect(ipc.lspSpringAopMarkers).not.toHaveBeenCalled(); + expect(buttons()).toHaveLength(0); + withIcons(true); + await vi.waitFor(() => expect(buttons()).toHaveLength(3), { timeout: 2000 }); + } finally { + useProject.setState({ settings }); + } + }); + + it("asks nothing for a document in an excluded folder", async () => { + ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS)); + library.excluded = true; + try { + open(); + await new Promise((r) => setTimeout(r, 700)); + expect(ipc.lspSpringAopMarkers).not.toHaveBeenCalled(); + } finally { + library.excluded = false; + } + }); + + it("waits for a navigation the user started before asking", async () => { + ipc.lspSpringAopMarkers.mockResolvedValue(answer(MARKERS)); + const done = foregroundStarted(); + open(); + await new Promise((r) => setTimeout(r, 700)); + expect(ipc.lspSpringAopMarkers).not.toHaveBeenCalled(); + done(); + await vi.waitFor(() => expect(buttons()).toHaveLength(3), { timeout: 2000 }); + }); + + it("registers nothing for other languages or virtual documents", async () => { + open("kotlin"); + view!.destroy(); + open("java", -1); + await new Promise((r) => setTimeout(r, 700)); + expect(ipc.lspSpringAopMarkers).not.toHaveBeenCalled(); + expect(buttons()).toHaveLength(0); + }); +}); + +describe("aopTooltip", () => { + it("names each advice's kind and order, and each advised method by its label", () => { + expect(aopTooltip(MARKERS[2]!)).toBe( + "Navigate to Advised Methods\nplace · Service.place()\ncancel · Service.cancel()", + ); + expect(aopTooltip(MARKERS[1]!)).toBe( + "Navigate to AOP Advices\nsent · NotificationAspect.sent() — After advice · order 2", + ); + }); +}); diff --git a/src/editor/navigation/springAopGutter.ts b/src/editor/navigation/springAopGutter.ts new file mode 100644 index 0000000000..42b8ad546a --- /dev/null +++ b/src/editor/navigation/springAopGutter.ts @@ -0,0 +1,116 @@ +/** + * Spring AOP gutter icons on Java documents: an advised method navigates to the advices applied + * to it, an advice method to the methods it advises. One cancellable request per document answers + * both directions (`lspSpringAopMarkers`); a server without them means no icons. Advice rows say + * their kind and, when statically known, their order. + */ +import type { Extension, Text } from "@codemirror/state"; +import { GutterMarker } from "@codemirror/view"; +import type { EditorDocContext } from "@/editor/api"; +import { locationItems } from "@/editor/lsp/navigation"; +import { commands, type SpringAopAdviceKind, type SpringAopMarker, type SpringAopTarget } from "@/platform/ipc"; +import { tx } from "@/platform/i18n"; +import { gutterIconMarkup } from "@/ui"; +import { openTargets } from "./implementationGutter"; +import { lspMarkerGutter, type PlacedMarker } from "./lspMarkerGutter"; +import styles from "./LineMarkers.module.css"; + +/** The advice kinds as the tooltip and chooser name them. */ +const KIND_LABELS: Record = { + before: "Before advice", + after: "After advice", + afterReturning: "After returning advice", + afterThrowing: "After throwing advice", + around: "Around advice", +}; + +/** Markers on lines of `doc`, left to right within a line. */ +export function placeAopMarkers(doc: Text, markers: readonly SpringAopMarker[]): PlacedMarker[] { + 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 })); +} + +/** An advice row's detail: its kind and, when known, the Spring order. */ +export function adviceDetail(target: SpringAopTarget): string | null { + const parts: string[] = []; + if (target.adviceKind) parts.push(tx(KIND_LABELS[target.adviceKind])); + if (target.order !== null) parts.push(tx`order ${target.order}`); + return parts.length ? parts.join(" · ") : null; +} + +/** Tooltip and accessible name: what clicking does, then each target, an advice with its kind and order. */ +export function aopTooltip(marker: SpringAopMarker): string { + const head = marker.direction === "toAdvice" ? tx("Navigate to AOP Advices") : tx("Navigate to Advised Methods"); + const rows = marker.targets.map((target) => { + if (marker.direction !== "toAdvice") return target.label; + const detail = adviceDetail(target); + return detail ? `${target.label} — ${detail}` : target.label; + }); + return [head, ...rows].join("\n"); +} + +/** One target navigates; several open the chooser, advice rows saying their kind and order. */ +export async function openAopTargets(marker: SpringAopMarker, anchor: { x: number; y: number }) { + const targets = marker.targets.map((t) => ({ ...t.location, name: t.label })); + const title = marker.direction === "toAdvice" ? tx("Navigate to AOP Advices") : tx("Navigate to Advised Methods"); + await openTargets(targets, anchor, title, marker.name, async (locs) => { + const items = await locationItems(locs); + if (marker.direction !== "toAdvice") return items; + return items.map((item, i) => { + const detail = adviceDetail(marker.targets[i]!); + return detail ? { ...item, detail } : item; + }); + }); +} + +class AopMarker extends GutterMarker { + readonly tooltip: string; + readonly icon: string; + + constructor(readonly marker: SpringAopMarker) { + super(); + this.tooltip = aopTooltip(marker); + this.icon = marker.direction === "toAdvice" ? "gutter-spring-aop-to-advice" : "gutter-spring-aop-to-advised"; + } + + // The DOM holds the marker it navigates with: other targets need a new button. + override eq(other: GutterMarker): boolean { + return other instanceof AopMarker && other.marker === this.marker; + } + + override toDOM(): Node { + const button = document.createElement("button"); + button.type = "button"; + button.className = styles.stubMarker ?? ""; + button.dataset.springAop = 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 openAopTargets(this.marker, { x: rect.left, y: rect.bottom + 2 }); + }); + return button; + } +} + +/** Java source documents of the project; library classes and virtual documents have no aspects to find. */ +export function springAopGutter(ctx: EditorDocContext): Extension { + if (ctx.doc < 0 || ctx.language !== "java") return []; + return lspMarkerGutter(ctx, { + request: (request, doc) => commands.lspSpringAopMarkers(request, doc), + refreshKind: "springAopMarkers", + place: placeAopMarkers, + marker: (marker) => new AopMarker(marker), + order: 52, + }); +} diff --git a/src/editor/navigation/springBeanGutter.ts b/src/editor/navigation/springBeanGutter.ts index c18ced5abe..608413e8a8 100644 --- a/src/editor/navigation/springBeanGutter.ts +++ b/src/editor/navigation/springBeanGutter.ts @@ -5,51 +5,19 @@ * 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 type { Extension, Text } from "@codemirror/state"; +import { GutterMarker } from "@codemirror/view"; +import type { EditorDocContext } from "@/editor/api"; import { locationItems } from "@/editor/lsp/navigation"; -import { - commands, - isCancelled, - nextRequestId, - onIdeEvent, - type RequestId, - type SpringBeanMarker, -} from "@/platform/ipc"; +import { commands, 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 { lspMarkerGutter, type PlacedMarker } from "./lspMarkerGutter"; 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[] { +export function placeBeans(doc: Text, markers: readonly SpringBeanMarker[]): PlacedMarker[] { 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) @@ -130,166 +98,14 @@ class BeanMarker extends GutterMarker { } } -/** 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), - }), - ]; + return lspMarkerGutter(ctx, { + request: (request, doc) => commands.lspSpringBeanMarkers(request, doc), + refreshKind: "springBeanMarkers", + place: placeBeans, + marker: (marker) => new BeanMarker(marker), + order: 51, + }); } diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index a3e90dfe2e..37454ce295 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -3288,6 +3288,14 @@ "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)", + "Navigate to AOP Advices": "Navigate to AOP Advices", + "Navigate to Advised Methods": "Navigate to Advised Methods", + "Before advice": "Before advice", + "After advice": "After advice", + "After returning advice": "After returning advice", + "After throwing advice": "After throwing advice", + "Around advice": "Around advice", + "order {n}": "order {n}", "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 92ba1d5789..e46aa94ad8 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -10053,6 +10053,14 @@ "Candidates, not certain: {names}": "候选,未确定:{names}", "Choose Bean for {name} ({count} found)": "选择 {name} 的 Bean(找到 {count} 个)", "Choose Injection Point of {name} ({count} found)": "选择 {name} 的注入点(找到 {count} 个)", + "Navigate to AOP Advices": "导航到 AOP 通知", + "Navigate to Advised Methods": "导航到被通知的方法", + "Before advice": "前置通知", + "After advice": "后置通知", + "After returning advice": "返回通知", + "After throwing advice": "异常通知", + "Around advice": "环绕通知", + "order {n}": "顺序 {n}", "Choose Target": "选择目标", "No related symbols": "没有相关符号", "Switch Header/Source": "切换头文件/源文件", diff --git a/src/ui/icons.tsx b/src/ui/icons.tsx index b42e8897c0..d1ac11d97a 100644 --- a/src/ui/icons.tsx +++ b/src/ui/icons.tsx @@ -539,6 +539,8 @@ const ICONS = { "gutter-javadoc-edit": "gutter/javadocEdit", "gutter-spring-to-bean": "openidea/gutter/springBeanToBean", "gutter-spring-to-injection-point": "openidea/gutter/springBeanToInjectionPoint", + "gutter-spring-aop-to-advice": "openidea/gutter/springAopToAdvice", + "gutter-spring-aop-to-advised": "openidea/gutter/springAopToAdvised", stop: "run/stop", rerun: "run/rerun", "rerun-automatically": "actions/rerunAutomatically", diff --git a/src/ui/openidea/gutter/springAopToAdvice.svg b/src/ui/openidea/gutter/springAopToAdvice.svg new file mode 100644 index 0000000000..5de980708b --- /dev/null +++ b/src/ui/openidea/gutter/springAopToAdvice.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/src/ui/openidea/gutter/springAopToAdvice_dark.svg b/src/ui/openidea/gutter/springAopToAdvice_dark.svg new file mode 100644 index 0000000000..63fea8d917 --- /dev/null +++ b/src/ui/openidea/gutter/springAopToAdvice_dark.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/src/ui/openidea/gutter/springAopToAdvised.svg b/src/ui/openidea/gutter/springAopToAdvised.svg new file mode 100644 index 0000000000..087abe7f38 --- /dev/null +++ b/src/ui/openidea/gutter/springAopToAdvised.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/src/ui/openidea/gutter/springAopToAdvised_dark.svg b/src/ui/openidea/gutter/springAopToAdvised_dark.svg new file mode 100644 index 0000000000..038c0256ec --- /dev/null +++ b/src/ui/openidea/gutter/springAopToAdvised_dark.svg @@ -0,0 +1,7 @@ + + + + + + +