fix(plugins): ask line markers again after a save of a file their plugin covers (#8272)

A plugin's gutter markers can be built from another file (MyBatis arrows in Mapper.xml come from the Java mapper), but the editor asked line-markers only after its own document changed. A save now asks again, debounced, in the visible editors of the same project root whose language a plugin declares along with the saved file's ("*" covers all); hidden kept tabs ask once shown. plugin_line_marker_languages(path) returns those languages from the usable plugins' declarations without loading plugin code.

Co-authored-by: audichuang <[email protected]>
Цей коміт міститься в:
audichuang authored and GitHub committed 2026-12-06 03:45:10 +08:00
1 джерело 8e8a3f397b
коміт 4021bdd0d1
8 files changed
+341 -14

No files matched your search

+18
Переглянути файл
@@ -715,6 +715,23 @@ pub async fn plugin_line_markers(host: &Host, window: &str, doc: DocId) -> IdeRe
Ok(crate::plugins::LineMarkers { markers, late })
}
/// The languages whose plugin line markers a save of `path` can change: those a plugin declares for
/// `line-markers` along with the file's language (`"*"` for every language). Does not load plugin
/// code. By path, not document: closing a tab saves it and then closes its document.
#[command(trust = trusted)]
pub async fn plugin_line_marker_languages(
host: &Host,
window: &str,
path: std::path::PathBuf,
) -> IdeResult<Vec<String>> {
let Some(plugins) = editor_providers(ProviderKind::LineMarkers) else {
return Ok(Vec::new());
};
let project = host.project(window)?;
let language = blocking(move || Ok(project.documents.language_of(&path, None).language.0)).await?;
Ok(plugins.line_marker_languages_with(&language))
}
/// Where other files import the document's file (Find Usages on a file, a Vue component's
/// usages). Cancel with `cancel_request(request)`.
#[command(trust = trusted)]
@@ -3832,6 +3849,7 @@ ide_command::domain!(
plugin_color_presentations,
plugin_formatters,
plugin_language_visuals,
plugin_line_marker_languages,
plugin_line_markers,
prepare_workspace_edit,
redo_workspace_edit,
+48 -4
Переглянути файл
@@ -128,6 +128,29 @@ impl Providers {
out
}
/// Each plugin's languages declared for `kind`, in declaration order.
fn languages_by_plugin(&self, kind: ProviderKind) -> Vec<(String, Vec<String>)> {
let mut out: Vec<(String, Vec<String>)> = Vec::new();
for (_, plugin, kinds, languages) in self.items.read().iter() {
if !kinds.contains(&kind) {
continue;
}
let at = match out.iter().position(|(id, _)| id == plugin) {
Some(at) => at,
None => {
out.push((plugin.clone(), Vec::new()));
out.len() - 1
}
};
for language in languages {
if !out[at].1.contains(language) {
out[at].1.push(language.clone());
}
}
}
out
}
/// One coherent declaration snapshot, preserving the first match per plugin.
fn matching<T: FromIterator<(String, u64)>>(&self, kind: ProviderKind, language: &str) -> T {
let items = self.items.read();
@@ -301,6 +324,11 @@ use std::collections::BTreeSet;
use std::sync::Weak;
use std::time::{Duration, Instant};
fn usable_provider(p: &LoadedPlugin) -> bool {
let m = p.meta.lock();
matches!(m.status, PluginStatus::Active | PluginStatus::Inactive) && m.pending.is_empty()
}
/// What the plugins answered for completion in the editor.
#[derive(Debug, Default)]
pub(crate) struct EditorCompletion {
@@ -342,13 +370,29 @@ impl PluginHost {
.plugins_for(kind, language)
.into_iter()
.filter_map(|id| self.get(&id).ok())
.filter(|p| {
let m = p.meta.lock();
matches!(m.status, PluginStatus::Active | PluginStatus::Inactive) && m.pending.is_empty()
})
.filter(|p| usable_provider(p))
.collect()
}
/// The languages a usable plugin declares for `line-markers` along with `language` (`"*"` for
/// every language), without loading any plugin: a saved file of `language` can change the
/// markers of the files of these languages.
pub fn line_marker_languages_with(&self, language: &str) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for (id, languages) in self.providers.languages_by_plugin(ProviderKind::LineMarkers) {
let covers = languages.iter().any(|l| l == "*" || l == language);
if !covers || !self.get(&id).is_ok_and(|p| usable_provider(&p)) {
continue;
}
for l in languages {
if !out.contains(&l) {
out.push(l);
}
}
}
out
}
/// Edit-path calls (soft / hard deadline) to every usable plugin that
/// declares `kind` for `language`, in plugin order, leaving out those that
/// failed or were late. Each plugin runs on its own thread, so the calls
+49
Переглянути файл
@@ -3465,7 +3465,13 @@ fn official_license_header_reports_fixes_and_scans() {
#[test]
fn official_mybatis_navigates_between_interface_and_xml() {
let f = fixture(Limits::default());
assert!(f.host.line_marker_languages_with("java").is_empty());
f.install(&official("mybatis"));
// One plugin's two declarations: a saved Kotlin file can change the XML's markers too.
let mut languages = f.host.line_marker_languages_with("kotlin");
languages.sort();
assert_eq!(languages, ["java", "kotlin", "xml"]);
assert!(f.host.line_marker_languages_with("markdown").is_empty());
let java_path = f.project.join("src/main/java/com/acme/UserMapper.java");
let xml_path = f.project.join("src/main/resources/mapper/UserMapper.xml");
std::fs::create_dir_all(java_path.parent().unwrap()).unwrap();
@@ -8903,3 +8909,46 @@ fn line_markers_too_late_from_one_provider_keep_the_others() {
assert!(markers.iter().all(|(id, _)| id == "on-time"));
});
}
/// A disabled plugin's languages don't make a save ask for line markers again.
#[test]
fn line_marker_languages_leave_out_disabled_plugins() {
let f = fixture(Limits::default());
f.install(&official("mybatis"));
assert_eq!(f.host.line_marker_languages_with("xml").len(), 3);
f.host.set_enabled("openidea.mybatis", false).unwrap();
assert!(f.host.line_marker_languages_with("xml").is_empty());
}
/// Another plugin's languages don't count: only one plugin declaring both links two files.
#[test]
fn line_marker_languages_come_from_the_plugins_covering_the_saved_language() {
let f = fixture(Limits::default());
let tmp = tempfile::tempdir().unwrap();
let install = |id: &str, languages: &str| {
let pkg = tmp.path().join(id);
copy_dir(&misbehave_pkg(), &pkg);
std::fs::write(
pkg.join("plugin.toml"),
format!(
"id = \"{id}\"\nname = \"{id}\"\nversion = \"0.0.1\"\nengines.openidea = \"^1.0\"\n\
wasm = \"dist/plugin.wasm\"\nactivation = [\"on-language:text\"]\n\
[[contributes.providers]]\nkinds = [\"line-markers\"]\nlanguages = {languages}\n"
),
)
.unwrap();
f.install(&pkg);
};
install("text-markers", r#"["text"]"#);
install("md-markers", r#"["markdown"]"#);
// Another plugin's languages don't come along.
assert_eq!(f.host.line_marker_languages_with("text"), ["text"]);
assert_eq!(f.host.line_marker_languages_with("markdown"), ["markdown"]);
assert!(f.host.line_marker_languages_with("java").is_empty());
install("any-markers", r#"["*"]"#);
// `any-markers` covers every language, so every save reaches its editors.
let mut languages = f.host.line_marker_languages_with("text");
languages.sort();
assert_eq!(languages, ["*", "text"]);
assert_eq!(f.host.line_marker_languages_with("java"), ["*"]);
}
+5 -1
Переглянути файл
@@ -1936,7 +1936,11 @@ Editor providers run under the edit-path budget: 50 ms, after which the
result is dropped, and an interruption at 500 ms. Every plugin providing a
kind is asked at the same time, so each has the whole budget. When a
plugin's `line-markers` call is dropped, the editor keeps the markers it
shows from that plugin until the next edit or plugin event asks it again.
shows from that plugin until the next edit or plugin event asks it again. Saving
a file also asks `line-markers` again in the visible editors of the same
project root whose language a plugin declares along with the saved file's
(hidden tabs ask once shown), so markers built from other files follow their
saved changes.
Providers run in the plugin's one instance, with its commands, events and
views: they see the same memory (Checkstyle answers quick fixes from the
+1
Переглянути файл
@@ -589,6 +589,7 @@ plugin_grant outside_restricted desktop bin
plugin_install_dir outside_restricted desktop bindings async
plugin_installed_intellij_themes always desktop bindings async
plugin_language_visuals trusted project_host bindings async
plugin_line_marker_languages trusted project_host bindings async
plugin_line_markers trusted project_host bindings async
plugin_link trusted desktop bindings async
plugin_list always desktop bindings async
+6
Переглянути файл
@@ -1653,6 +1653,12 @@ export const commands = {
/** Theme plugins installed in the JetBrains IDEs of this user, the ones in use first. */
pluginInstalledIntellijThemes: () => typedError<InstalledIntellijTheme[], IdeError>(__TAURI_INVOKE("plugin_installed_intellij_themes")),
pluginLanguageVisuals: (doc: DocId) => typedError<PluginLanguageVisuals, IdeError>(__TAURI_INVOKE("plugin_language_visuals", { doc })),
/**
* The languages whose plugin line markers a save of `path` can change: those a plugin declares for
* `line-markers` along with the file's language (`"*"` for every language). Does not load plugin
* code. By path, not document: closing a tab saves it and then closes its document.
*/
pluginLineMarkerLanguages: (path: string) => typedError<string[], IdeError>(__TAURI_INVOKE("plugin_line_marker_languages", { path })),
/** Gutter markers of plugin `line-markers` providers for an open document. */
pluginLineMarkers: (doc: DocId) => typedError<LineMarkers, IdeError>(__TAURI_INVOKE("plugin_line_markers", { doc })),
/** Links a development plugin folder (`openidea-plugin link` does the same from a terminal). */
+155 -3
Переглянути файл
@@ -1,7 +1,8 @@
import { afterEach, expect, it, vi } from "vitest";
import { afterEach, expect, it, onTestFinished, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { viewShown, type EditorDocContext } from "@/editor/api";
import { _emitEditorEvent, viewShown, type EditorDocContext } from "@/editor/api";
import { useProject } from "@/platform/project";
import type { LineMarkerInfo, PluginEvent } from "@/bindings";
import { iconAreaExtension } from "@/editor/core/cm/iconArea";
import { pluginLineMarkerGutter } from "./lineMarkerGutter";
@@ -9,13 +10,17 @@ import { pluginIconName } from "./pluginIcon";
import { projectMarkerIcon } from "./markerIcons";
const mock = vi.hoisted(() => ({
markers: vi.fn(),
languages: vi.fn(),
assets: vi.fn(),
event: undefined as ((event: PluginEvent) => void) | undefined,
off: vi.fn(),
}));
vi.mock(import("@/platform/ipc"), async (original) => {
const actual = await original();
return { ...actual, commands: { ...actual.commands, pluginLineMarkers: mock.markers } };
return {
...actual,
commands: { ...actual.commands, pluginLineMarkers: mock.markers, pluginLineMarkerLanguages: mock.languages },
};
});
vi.mock("./backend", () => ({
pluginsBackend: () => ({
@@ -298,3 +303,150 @@ it("does not show an older answer over a newer one asked while the tab was hidde
await vi.advanceTimersByTimeAsync(0);
expect(labels(view)).toEqual([]);
});
// MyBatis: a statement's markers in the XML come from the Java mapper's methods.
const covered = (languages: string[]) => mock.languages.mockResolvedValue({ status: "ok", data: languages });
const save = async (path = "/w/a/Mapper.java") => {
_emitEditorEvent({ type: "docSaved", doc: 1, path });
await vi.advanceTimersByTimeAsync(450);
};
function xmlEditor(path = "/w/a/Mapper.xml", doc = 2) {
return new EditorView({
parent: document.body,
state: EditorState.create({
doc: "<select/>",
extensions: [iconAreaExtension, pluginLineMarkerGutter({ doc, path, language: "xml" } as EditorDocContext)],
}),
});
}
async function xmlShowing(path?: string, doc?: number) {
covered(["java", "xml"]);
mock.markers.mockResolvedValue(answer([marker("mybatis", "old")]));
const created = xmlEditor(path, doc);
await vi.advanceTimersByTimeAsync(450);
expect(labels(created)).toEqual(["old"]);
return created;
}
function inProject(project: object) {
const before = useProject.getState().project;
useProject.setState({ project: project as never });
onTestFinished(() => useProject.setState({ project: before }));
}
it("asks again in the editor beside the one saved, keeping its markers until the answer", async () => {
vi.useFakeTimers();
inProject({ root: "/w/a" });
view = await xmlShowing();
const java = new EditorView({
parent: document.body,
state: EditorState.create({
doc: "interface Mapper {}",
extensions: [
iconAreaExtension,
pluginLineMarkerGutter({ doc: 1, path: "/w/a/Mapper.java", language: "java" } as EditorDocContext),
],
}),
});
await vi.advanceTimersByTimeAsync(450);
onTestFinished(() => java.destroy());
mock.markers.mockClear();
let reply!: (value: unknown) => void;
mock.markers.mockReturnValueOnce(new Promise((resolve) => (reply = resolve)));
// The icon area is as wide as its spacer's icons.
const width = () => view!.dom.querySelectorAll(".cm-openidea-iconSpacer").length;
expect(width()).toBe(1);
await save();
// The languages are those of the saved file's plugins; both editors ask.
expect(mock.languages).toHaveBeenCalledWith("/w/a/Mapper.java");
expect(mock.markers.mock.calls).toEqual([[2], [1]]);
// Pending: the old markers hold the icon area open.
expect(labels(view)).toEqual(["old"]);
expect(width()).toBe(1);
reply(answer([marker("mybatis", "new")]));
await vi.advanceTimersByTimeAsync(0);
expect(labels(view)).toEqual(["new"]);
});
it("asks a kept tab hidden during the save once it is shown again", async () => {
vi.useFakeTimers();
inProject({ root: "/w/a" });
view = await xmlShowing();
view.dom.remove();
mock.markers.mockResolvedValue(answer([marker("mybatis", "new")]));
await save();
await save();
expect(mock.markers).toHaveBeenCalledTimes(1);
await showAgain(view);
expect(mock.markers).toHaveBeenCalledTimes(2);
expect(labels(view)).toEqual(["new"]);
});
it("does not ask again for a save no plugin of the editor's language covers", async () => {
vi.useFakeTimers();
inProject({ root: "/w/a" });
view = await xmlShowing();
covered(["markdown"]);
await save("/w/a/README.md");
covered([]);
await save("/w/a/notes.txt");
expect(mock.markers).toHaveBeenCalledTimes(1);
});
it("asks again for a save a plugin of every language covers", async () => {
vi.useFakeTimers();
inProject({ root: "/w/a" });
view = await xmlShowing();
covered(["*"]);
await save("/w/a/README.md");
expect(mock.markers).toHaveBeenCalledTimes(2);
});
it("does not ask again for a save in another project root of the workspace", async () => {
vi.useFakeTimers();
inProject({ root: "/w", workspace: { projects: ["/w/a", "/w/b"] } });
view = await xmlShowing();
await save("/w/b/Mapper.java");
// Outside every member: no root to share.
await save("/w/other/Mapper.java");
expect(mock.markers).toHaveBeenCalledTimes(1);
await save("/w/a/Mapper.java");
expect(mock.markers).toHaveBeenCalledTimes(2);
});
it("does not ask again for a save outside a single-folder project", async () => {
vi.useFakeTimers();
inProject({ root: "/repo/app" });
view = await xmlShowing("/repo/app/Mapper.xml");
await save("/repo/shared/Other.java");
expect(mock.markers).toHaveBeenCalledTimes(1);
});
it("does not reject when the languages can't be asked", async () => {
vi.useFakeTimers();
inProject({ root: "/w/a" });
view = await xmlShowing();
mock.languages.mockRejectedValue(new Error("no backend"));
await save();
expect(mock.markers).toHaveBeenCalledTimes(1);
});
it("asks again in the editor of the saved document", async () => {
vi.useFakeTimers();
inProject({ root: "/w/a" });
view = await xmlShowing("/w/a/Mapper.xml", 1);
await save("/w/a/Mapper.xml");
expect(mock.markers).toHaveBeenCalledTimes(2);
});
it("does not ask a tab hidden before the save's request goes out until it is shown again", async () => {
vi.useFakeTimers();
inProject({ root: "/w/a" });
view = await xmlShowing();
_emitEditorEvent({ type: "docSaved", doc: 1, path: "/w/a/Mapper.java" });
await vi.advanceTimersByTimeAsync(100);
view.dom.remove();
await vi.advanceTimersByTimeAsync(450);
expect(mock.markers).toHaveBeenCalledTimes(1);
await showAgain(view);
expect(mock.markers).toHaveBeenCalledTimes(2);
});
+59 -6
Переглянути файл
@@ -1,16 +1,19 @@
/**
* Gutter icons from plugins' `line-markers` providers. Asked once per document version
* (debounced); markers follow their lines in between; a click opens the
* (debounced) and after a save of a file one of its plugins covers; markers follow their
* lines in between; a click opens the
* marker's target. They sit in the shared icon area, which takes no width
* while no source has icons.
*/
import { RangeSet, StateEffect, StateField, type Extension, type Text } from "@codemirror/state";
import { EditorView, GutterMarker, ViewPlugin, type ViewUpdate } from "@codemirror/view";
import { iconAreaSource, mapLineStart, shownAgain, type EditorDocContext } from "@/editor/api";
import { iconAreaSource, mapLineStart, onEditorEvent, shownAgain, type EditorDocContext } from "@/editor/api";
import { CoalescedRefresh } from "@/editor/coalescedRefresh";
import { navigationButton } from "./navigationButton";
import { tx } from "@/platform/i18n";
import { pluginsBackend } from "./backend";
import { isSameOrInside } from "@/platform/paths";
import { projectFolder, useProject } from "@/platform/project";
import { commands, type LineMarkerInfo } from "@/platform/ipc";
import { gutterIconMarkup, isIconName } from "@/ui/icons";
import { onMarkerIconsChanged, resolveMarkerIcon } from "./markerIcons";
@@ -129,6 +132,42 @@ class PluginMarker extends GutterMarker {
}
}
const live = new Set<MarkersPlugin>();
let unwatch: (() => void) | null = null;
/** The folder of the project `path` is in, if any. */
function rootOf(path: string): string | null {
const folder = projectFolder(useProject.getState().project, path);
return folder && isSameOrInside(path, folder.root) ? folder.root : null;
}
/**
* Providers read other files too (a MyBatis statement's Java method, #8145): a saved file asks again
* in the editors of its project root whose language a plugin declares along with the saved one's.
*/
function watchSaves(plugin: MarkersPlugin): () => void {
live.add(plugin);
unwatch ??= onEditorEvent((e) => {
if (e.type !== "docSaved") return;
const root = rootOf(e.path);
if (root === null) return;
// Asked of the host running the plugins, at the save: no list to keep current.
void commands
.pluginLineMarkerLanguages(e.path)
.then((languages) => {
if (languages.status !== "ok" || !languages.data.length) return;
for (const each of live) each.saved(root, languages.data);
})
.catch((err) => console.debug("[plugin line markers]", err));
});
return () => {
live.delete(plugin);
if (live.size || !unwatch) return;
unwatch();
unwatch = null;
};
}
class MarkersPlugin {
private refresh = new CoalescedRefresh((ticket) => void this.run(ticket), DEBOUNCE_MS);
private skipped = false;
@@ -136,7 +175,7 @@ class MarkersPlugin {
constructor(
private view: EditorView,
private doc: number,
private ctx: EditorDocContext,
) {
const offBackend = pluginsBackend().onEvent((event) => {
if (event.type !== "documentIndexesChanged") return;
@@ -145,21 +184,36 @@ class MarkersPlugin {
this.refresh.schedule();
});
const offIcons = onMarkerIconsChanged(() => this.refresh.schedule());
const offSaves = watchSaves(this);
this.off = () => {
offBackend();
offIcons();
offSaves();
};
this.refresh.schedule();
}
saved(root: string, languages: readonly string[]) {
if (rootOf(this.ctx.path) !== root) return;
if (!languages.includes("*") && !languages.includes(this.ctx.language)) return;
// A hidden tab asks once shown again.
if (this.view.dom.isConnected) this.refresh.schedule();
else this.skipped = true;
}
update(u: ViewUpdate) {
if (u.docChanged || (this.skipped && shownAgain(u))) this.refresh.schedule();
}
private async run(ticket: number) {
const text = this.view.state.doc;
// Hidden since it was scheduled: ask once shown again.
if (!this.view.dom.isConnected) {
this.skipped = true;
return;
}
try {
const answer = await commands.pluginLineMarkers(this.doc);
const answer = await commands.pluginLineMarkers(this.ctx.doc);
if (!this.refresh.current(ticket) || this.view.state.doc !== text) return;
// Hidden meanwhile: ask again once shown (`shownAgain`), not when the next edit comes.
if (!this.view.dom.isConnected) {
@@ -207,6 +261,5 @@ const markerSource = iconAreaSource.of({
export function pluginLineMarkerGutter(ctx: EditorDocContext): Extension {
if (ctx.doc < 0) return [];
const doc = ctx.doc;
return [markersField, markerSource, ViewPlugin.define((view) => new MarkersPlugin(view, doc))];
return [markersField, markerSource, ViewPlugin.define((view) => new MarkersPlugin(view, ctx))];
}