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]>
Цей коміт міститься в:
aLiEz authored and GitHub committed 2026-12-06 08:00:23 +08:00
1 джерело fe04de3862
коміт 2d11fd484f
35 files changed
+1274 -202

No files matched your search

+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";
/**
+2
Переглянути файл
@@ -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 }),
+1
Переглянути файл
@@ -348,5 +348,6 @@ export function registerNavigationActions(): () => void {
}
export { implementationGutter } from "./implementationGutter";
export { springAopGutter } from "./springAopGutter";
export { springBeanGutter } from "./springBeanGutter";
export { pythonStubGutter } from "./pythonStubs";
+235
Переглянути файл
@@ -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),
}),
];
}
+348
Переглянути файл
@@ -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",
);
});
});
+116
Переглянути файл
@@ -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,
});
}
+13 -197
Переглянути файл
@@ -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,
});
}
+8
Переглянути файл
@@ -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",
+8
Переглянути файл
@@ -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": "切换头文件/源文件",
+2
Переглянути файл
@@ -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",
+7
Переглянути файл
@@ -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

+7
Переглянути файл
@@ -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

+7
Переглянути файл
@@ -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

+7
Переглянути файл
@@ -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