дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 10:07:11 +02:00
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 <[email protected]>
Цей коміт міститься в:
1 джерело
fe04de3862
коміт
2d11fd484f
35 files changed
+1274
-202
No files matched your search
@@ -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)]
|
||||
|
||||
@@ -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<Option<Vec<SpringAopMarker>>> {
|
||||
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,
|
||||
|
||||
@@ -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 } }
|
||||
})
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<WireMarker>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct WireMarker {
|
||||
range: lsp::Range,
|
||||
name: String,
|
||||
direction: SpringAopDirection,
|
||||
targets: Vec<WireTarget>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct WireTarget {
|
||||
location: lsp::Location,
|
||||
label: String,
|
||||
#[serde(default)]
|
||||
advice_kind: Option<SpringAopAdviceKind>,
|
||||
#[serde(default)]
|
||||
order: Option<i32>,
|
||||
}
|
||||
|
||||
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<Option<Vec<SpringAopMarker>>> {
|
||||
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<Answer> =
|
||||
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(),
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -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<SpringAopTarget>,
|
||||
}
|
||||
|
||||
#[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<SpringAopAdviceKind>,
|
||||
/// The advice's Spring `order`; `None` when it has none.
|
||||
pub order: Option<i32>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum SpringAopAdviceKind {
|
||||
Before,
|
||||
After,
|
||||
AfterReturning,
|
||||
AfterThrowing,
|
||||
Around,
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
@@ -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` |
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>openidea-fixture-spring</artifactId>
|
||||
<version>0.1.0</version>
|
||||
<description>OpenIDEA QA fixture: Spring beans and their injection points</description>
|
||||
<description>OpenIDEA QA fixture: Spring beans, injection points and Spring AOP advice navigation</description>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.release>21</maven.compiler.release>
|
||||
@@ -20,5 +20,10 @@
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>6.2.12</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.aspectj</groupId>
|
||||
<artifactId>aspectjweaver</artifactId>
|
||||
<version>1.9.24</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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 {}
|
||||
@@ -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
|
||||
|
||||
@@ -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() {}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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]);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
+39
-1
@@ -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<Location[], IdeError>(__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<SpringAopMarker[] | null, IdeError>(__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";
|
||||
|
||||
/**
|
||||
|
||||
@@ -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 }),
|
||||
|
||||
@@ -348,5 +348,6 @@ export function registerNavigationActions(): () => void {
|
||||
}
|
||||
|
||||
export { implementationGutter } from "./implementationGutter";
|
||||
export { springAopGutter } from "./springAopGutter";
|
||||
export { springBeanGutter } from "./springBeanGutter";
|
||||
export { pythonStubGutter } from "./pythonStubs";
|
||||
@@ -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<M> {
|
||||
marker: M;
|
||||
/** Start of the marker's line in the current state. */
|
||||
pos: number;
|
||||
}
|
||||
|
||||
export interface MarkerGutterOptions<M> {
|
||||
/** 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<M>[];
|
||||
/** 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<LivePlugin>();
|
||||
const watchedKinds = new Set<LspRefreshKind>();
|
||||
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<M>(ctx: EditorDocContext, options: MarkerGutterOptions<M>): Extension {
|
||||
const setPlaced = StateEffect.define<PlacedMarker<M>[]>();
|
||||
|
||||
const field = StateField.define<PlacedMarker<M>[]>({
|
||||
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<readonly PlacedMarker<M>[], RangeSet<GutterMarker>>();
|
||||
|
||||
function placedSet(placed: readonly PlacedMarker<M>[]): RangeSet<GutterMarker> {
|
||||
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<M>[]) {
|
||||
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),
|
||||
}),
|
||||
];
|
||||
}
|
||||
@@ -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<typeof import("@/platform/ipc")>()),
|
||||
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<typeof import("@/editor/api")>()),
|
||||
whenAllSynced: () => Promise.resolve(),
|
||||
isLibrarySource: () => library.excluded,
|
||||
}));
|
||||
vi.mock("@/editor/lsp/availability", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/editor/lsp/availability")>()),
|
||||
onLspRefresh: (_: string, fn: () => void) => refresh.listeners.push(fn),
|
||||
onServerSettled: () => () => {},
|
||||
}));
|
||||
vi.mock("@/editor/lsp/navigation", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/editor/lsp/navigation")>()),
|
||||
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<typeof import("@/editor/lsp/popupStore")>()),
|
||||
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<typeof springAopGutter>[0];
|
||||
view = new EditorView({
|
||||
state: EditorState.create({ doc: SOURCE, extensions: [springAopGutter(ctx), iconAreaExtension] }),
|
||||
parent: document.body,
|
||||
});
|
||||
return view;
|
||||
}
|
||||
|
||||
const buttons = () => [...view!.dom.querySelectorAll<HTMLButtonElement>("[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",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -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<SpringAopAdviceKind, string> = {
|
||||
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<SpringAopMarker>[] {
|
||||
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,
|
||||
});
|
||||
}
|
||||
@@ -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<PlacedBean[]>();
|
||||
|
||||
const beansField = StateField.define<PlacedBean[]>({
|
||||
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<SpringBeanMarker>[] {
|
||||
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<readonly PlacedBean[], RangeSet<BeanMarker>>();
|
||||
|
||||
function beanSet(placed: readonly PlacedBean[]): RangeSet<BeanMarker> {
|
||||
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<BeansPlugin>();
|
||||
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,
|
||||
});
|
||||
}
|
||||
@@ -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",
|
||||
|
||||
@@ -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": "切换头文件/源文件",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
<!-- OpenIDEA: Spring AOP marker on an advised method: navigate to its advices (arrow up), in the expui gutter style. -->
|
||||
<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<ellipse cx="5" cy="7" rx="3.4" ry="1.9" transform="rotate(45 5 7)" stroke="#208A3C" stroke-width="1.2"/>
|
||||
<ellipse cx="5" cy="7" rx="3.4" ry="1.9" transform="rotate(-45 5 7)" stroke="#208A3C" stroke-width="1.2"/>
|
||||
<circle cx="5" cy="7" r="0.9" fill="#208A3C"/>
|
||||
<path d="M11.5 7.5V1.5M9.5 3.5L11.5 1.5L13.5 3.5" stroke="#6C707E" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
Після Ширина: | Висота: | Розмір: 601 B |
@@ -0,0 +1,7 @@
|
||||
<!-- OpenIDEA: Spring AOP marker on an advised method: navigate to its advices (arrow up), in the expui gutter style. -->
|
||||
<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<ellipse cx="5" cy="7" rx="3.4" ry="1.9" transform="rotate(45 5 7)" stroke="#57965C" stroke-width="1.2"/>
|
||||
<ellipse cx="5" cy="7" rx="3.4" ry="1.9" transform="rotate(-45 5 7)" stroke="#57965C" stroke-width="1.2"/>
|
||||
<circle cx="5" cy="7" r="0.9" fill="#57965C"/>
|
||||
<path d="M11.5 7.5V1.5M9.5 3.5L11.5 1.5L13.5 3.5" stroke="#CED0D6" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
Після Ширина: | Висота: | Розмір: 601 B |
@@ -0,0 +1,7 @@
|
||||
<!-- OpenIDEA: Spring AOP marker on an advice method: navigate to the methods it advises (arrow down), in the expui gutter style. -->
|
||||
<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<ellipse cx="5" cy="7" rx="3.4" ry="1.9" transform="rotate(45 5 7)" stroke="#208A3C" stroke-width="1.2"/>
|
||||
<ellipse cx="5" cy="7" rx="3.4" ry="1.9" transform="rotate(-45 5 7)" stroke="#208A3C" stroke-width="1.2"/>
|
||||
<circle cx="5" cy="7" r="0.9" fill="#208A3C"/>
|
||||
<path d="M11.5 6.5V12.5M9.5 10.5L11.5 12.5L13.5 10.5" stroke="#6C707E" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
Після Ширина: | Висота: | Розмір: 617 B |
@@ -0,0 +1,7 @@
|
||||
<!-- OpenIDEA: Spring AOP marker on an advice method: navigate to the methods it advises (arrow down), in the expui gutter style. -->
|
||||
<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<ellipse cx="5" cy="7" rx="3.4" ry="1.9" transform="rotate(45 5 7)" stroke="#57965C" stroke-width="1.2"/>
|
||||
<ellipse cx="5" cy="7" rx="3.4" ry="1.9" transform="rotate(-45 5 7)" stroke="#57965C" stroke-width="1.2"/>
|
||||
<circle cx="5" cy="7" r="0.9" fill="#57965C"/>
|
||||
<path d="M11.5 6.5V12.5M9.5 10.5L11.5 12.5L13.5 10.5" stroke="#CED0D6" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
Після Ширина: | Висота: | Розмір: 617 B |
Reference in new issue
Заблокувати користувача