diff --git a/crates/ide-host/src/plugins/ui_points.rs b/crates/ide-host/src/plugins/ui_points.rs index d6240dcd8d..10c209de3c 100644 --- a/crates/ide-host/src/plugins/ui_points.rs +++ b/crates/ide-host/src/plugins/ui_points.rs @@ -7,10 +7,11 @@ //! [[contributes.menus]] //! menu = "editor.context" # projectView.context, editorTab.context, tools, viewItem.context, commit.message, //! # services.context / services.toolbar (API 1.18: the Services tree's own nodes), -//! # openIn (API 1.19: the Open In › submenu of the editor, its tab and the project view) +//! # openIn (API 1.19: the Open In › submenu of the editor, its tab and the project view), +//! # customEditor.toolbar (API 1.21: strip above a split/preview custom editor's text half) //! command = "check" //! when = "editorLang == java" -//! # view = "" # required for (only allowed on) viewItem.context +//! # view = "" # required for (only allowed on) viewItem.context and customEditor.toolbar //! //! [[contributes.keymaps]] //! command = "check" @@ -138,9 +139,11 @@ const DATABASE_SCHEMA_MENU: &str = "database.schema.context"; const DATABASE_COLUMN_MENU: &str = "database.column.context"; /// Toolbar of the Run and Debug consoles (API 1.21). const RUN_CONSOLE_TOOLBAR_MENU: &str = "runConsole.toolbar"; +/// Toolbar above the text editor of a split/preview custom editor (API 1.21). +const CUSTOM_EDITOR_TOOLBAR_MENU: &str = "customEditor.toolbar"; pub(super) const GIT_BRANCHES_POPUP_MENU: &str = "git.branches.popup"; pub(super) const GIT_BRANCH_CONTEXT_MENU: &str = "git.branch.context"; -const MENU_IDS: [&str; 20] = [ +const MENU_IDS: [&str; 21] = [ "editor.context", "projectView.context", "editorTab.context", @@ -159,6 +162,7 @@ const MENU_IDS: [&str; 20] = [ DATABASE_SCHEMA_MENU, DATABASE_COLUMN_MENU, RUN_CONSOLE_TOOLBAR_MENU, + CUSTOM_EDITOR_TOOLBAR_MENU, GIT_BRANCHES_POPUP_MENU, GIT_BRANCH_CONTEXT_MENU, ]; @@ -179,6 +183,10 @@ fn declared_view(pkg: &Package, id: &str) -> Option { pkg.manifest.declarations(VIEWS).into_iter().find(|d| d.get("id").and_then(|v| v.as_str()) == Some(id)) } +fn declared_custom_editor(pkg: &Package, id: &str) -> Option { + pkg.manifest.declarations(CUSTOM_EDITORS).into_iter().find(|d| d.get("id").and_then(|v| v.as_str()) == Some(id)) +} + fn declared_command(pkg: &Package, point: &str, command: &str) -> Result<(), String> { if commands(pkg).contains(command) { Ok(()) @@ -287,6 +295,9 @@ pub(super) fn menu(pkg: &Package, decl: toml::Value) -> Result { if d.menu == RUN_CONSOLE_TOOLBAR_MENU { pkg.manifest.needs_api(&format!("contributes.menus: {RUN_CONSOLE_TOOLBAR_MENU}"), 21)?; } + if d.menu == CUSTOM_EDITOR_TOOLBAR_MENU { + pkg.manifest.needs_api(&format!("contributes.menus: {CUSTOM_EDITOR_TOOLBAR_MENU}"), 21)?; + } if let Some(w) = &d.when { validate_when(w).map_err(|e| format!("contributes.menus: {e}"))?; } @@ -297,9 +308,9 @@ pub(super) fn menu(pkg: &Package, decl: toml::Value) -> Result { title(MENUS, submenu)?; pkg.manifest.needs_api("contributes.menus: submenu", 3)?; } - let key = match (d.menu == VIEW_ITEM_MENU, &d.view) { - (true, None) => return Err(format!("contributes.menus: {VIEW_ITEM_MENU} needs `view`")), - (true, Some(v)) => { + let key = match (d.menu.as_str(), &d.view) { + (VIEW_ITEM_MENU, None) => return Err(format!("contributes.menus: {VIEW_ITEM_MENU} needs `view`")), + (VIEW_ITEM_MENU, Some(v)) => { pkg.manifest.needs_api(&format!("contributes.menus: {VIEW_ITEM_MENU}"), 2)?; let Some(view) = declared_view(pkg, v) else { return Err(format!("contributes.menus: view {v:?} is not declared under [[contributes.views]]")); @@ -311,8 +322,29 @@ pub(super) fn menu(pkg: &Package, decl: toml::Value) -> Result { } format!("{VIEW_ITEM_MENU}/{v}/{}", d.command) } - (false, Some(_)) => return Err(format!("contributes.menus: `view` is only for {VIEW_ITEM_MENU}")), - (false, None) => format!("{}/{}", d.menu, d.command), + (CUSTOM_EDITOR_TOOLBAR_MENU, None) => { + return Err(format!("contributes.menus: {CUSTOM_EDITOR_TOOLBAR_MENU} needs `view`")); + } + (CUSTOM_EDITOR_TOOLBAR_MENU, Some(v)) => { + let Some(editor) = declared_custom_editor(pkg, v) else { + return Err(format!( + "contributes.menus: view {v:?} is not declared under [[contributes.customEditors]]" + )); + }; + let layout = editor.get("layout").and_then(|l| l.as_str()).unwrap_or("tab"); + if layout != "split" && layout != "preview" { + return Err(format!( + "contributes.menus: custom editor {v:?} has `layout = {layout:?}` ({CUSTOM_EDITOR_TOOLBAR_MENU} requires `layout = \"split\"` or \"preview\")" + )); + } + format!("{CUSTOM_EDITOR_TOOLBAR_MENU}/{v}/{}", d.command) + } + (_, Some(_)) => { + return Err(format!( + "contributes.menus: `view` is only for {VIEW_ITEM_MENU} and {CUSTOM_EDITOR_TOOLBAR_MENU}" + )); + } + (_, None) => format!("{}/{}", d.menu, d.command), }; Ok(UiDecl::new(key, d.command.clone(), json(&d)?)) } @@ -3054,4 +3086,67 @@ title = \"Prepare\"\n" == true ); } + + #[test] + fn custom_editor_toolbar_validates_api_view_layout_and_command() { + let make_pkg = |api: &str, editors: &str| { + let source = format!( + "id = \"p\"\nname = \"P\"\nversion = \"1.0.0\"\nengines.openidea = \"{api}\"\n\ + [[contributes.commands]]\nid = \"run\"\ntitle = \"Run\"\nicon = \"run\"\n\ + [[contributes.views]]\nid = \"panel\"\ntitle = \"Panel\"\nicon = \"plugin\"\nlocation = \"right\"\n\ + {editors}" + ); + Package::new(ide_extension::Manifest::parse(&source).unwrap(), PathBuf::from("/unused")) + }; + let editors = "\ + [[contributes.customEditors]]\nid = \"split-ed\"\ntitle = \"Split\"\npatterns = [\"*.a\"]\nlayout = \"split\"\nweb = \"web/i.html\"\n\ + [[contributes.customEditors]]\nid = \"preview-ed\"\ntitle = \"Preview\"\npatterns = [\"*.b\"]\nlayout = \"preview\"\nweb = \"web/i.html\"\n\ + [[contributes.customEditors]]\nid = \"tab-ed\"\ntitle = \"Tab\"\npatterns = [\"*.c\"]\nlayout = \"tab\"\nweb = \"web/i.html\"\n\ + [[contributes.customEditors]]\nid = \"default-ed\"\ntitle = \"Default\"\npatterns = [\"*.d\"]\nweb = \"web/i.html\"\n"; + + let pkg21 = make_pkg("^1.21", editors); + let pkg20 = make_pkg("^1.20", editors); + + for view in ["split-ed", "preview-ed"] { + let decl = toml::from_str(&format!( + "menu = \"customEditor.toolbar\"\nview = \"{view}\"\ncommand = \"run\"\nwhen = \"editorLang == python\"" + )) + .unwrap(); + let out = menu(&pkg21, decl).unwrap(); + assert_eq!(out.key, format!("customEditor.toolbar/{view}/run")); + assert_eq!(out.json["menu"], "customEditor.toolbar"); + assert_eq!(out.json["view"], view); + assert_eq!(out.json["command"], "run"); + assert_eq!(out.json["when"], "editorLang == python"); + } + + // Gated under API 1.21. + let decl_split = + toml::from_str("menu = \"customEditor.toolbar\"\nview = \"split-ed\"\ncommand = \"run\"").unwrap(); + assert!(menu(&pkg20, decl_split).unwrap_err().contains("1.21")); + + // Invalid declarations rejected with clear errors. + for (raw, needle) in [ + ("menu = \"customEditor.toolbar\"\ncommand = \"run\"", "needs `view`"), + ("menu = \"customEditor.toolbar\"\nview = \"missing\"\ncommand = \"run\"", "[[contributes.customEditors]]"), + ("menu = \"customEditor.toolbar\"\nview = \"panel\"\ncommand = \"run\"", "[[contributes.customEditors]]"), + ("menu = \"customEditor.toolbar\"\nview = \"tab-ed\"\ncommand = \"run\"", "layout = \"tab\""), + ("menu = \"customEditor.toolbar\"\nview = \"default-ed\"\ncommand = \"run\"", "layout = \"tab\""), + ( + "menu = \"customEditor.toolbar\"\nview = \"split-ed\"\ncommand = \"unknown\"", + "not declared under [[contributes.commands]]", + ), + ( + "menu = \"customEditor.toolbar\"\nview = \"split-ed\"\ncommand = \"run\"\nsubmenu = \"Group\"", + "only for context menus", + ), + ( + "menu = \"editor.title\"\nview = \"split-ed\"\ncommand = \"run\"", + "`view` is only for viewItem.context and customEditor.toolbar", + ), + ] { + let err = menu(&pkg21, toml::from_str(raw).unwrap()).unwrap_err(); + assert!(err.contains(needle), "{raw}\n-> {err}"); + } + } } diff --git a/crates/ide-host/tests/plugins.rs b/crates/ide-host/tests/plugins.rs index ac66116ea4..0a1765b731 100644 --- a/crates/ide-host/tests/plugins.rs +++ b/crates/ide-host/tests/plugins.rs @@ -8554,3 +8554,83 @@ web = "clone/index.html" let err = f.host.install_from_dir(&old, &Consent::all()).unwrap_err(); assert!(err.message.contains("new in plugin API 1.21"), "{}", err.message); } + +#[test] +fn custom_editor_toolbar_installs_and_validates_manifest() { + let f = fixture(Limits::default()); + let sample = repo().join("crates/ide-plugin/tests/fixtures/custom-editor-toolbar"); + let info = f.install(&sample); + assert_eq!(info.status, PluginStatus::Inactive, "{:?}", info.error); + + let menus: Vec<_> = + f.host.ui_items("menus").into_iter().filter(|i| i.plugin_id == "custom-editor-toolbar").collect(); + let keys: Vec<_> = menus.iter().map(|i| i.key.as_str()).collect(); + assert_eq!( + keys, + vec![ + "customEditor.toolbar/statement/run", + "customEditor.toolbar/statement/submit", + "customEditor.toolbar/statement/inspect", + ] + ); + assert_eq!(menus[0].decl["view"], "statement"); + assert_eq!(menus[2].decl["when"], "editorLang == python"); + assert!( + f.host + .assets("custom-editor-toolbar", "commandIcon/run") + .unwrap() + .iter() + .any(|(id, svg)| id == "commandIcon/run" && svg.contains("

ok

").unwrap(); + std::fs::write( + pkg.join("plugin.toml"), + format!( + "id = \"toolbar-{name}\"\nname = \"Toolbar\"\nversion = \"1.0.0\"\nengines.openidea = \"{api}\"\n\ + [[contributes.commands]]\nid = \"run\"\ntitle = \"Run\"\n\ + [[contributes.customEditors]]\nid = \"statement\"\ntitle = \"Statement\"\npatterns = [\"*.p\"]\nlayout = \"{layout}\"\nweb = \"web/index.html\"\n\ + [[contributes.menus]]\n{menu_block}\n" + ), + ) + .unwrap(); + f.host.install_from_dir(&pkg, &Consent::all()).unwrap_err().message + }; + + assert!( + invalid("old", "^1.20", "split", "menu = \"customEditor.toolbar\"\nview = \"statement\"\ncommand = \"run\"") + .contains("1.21") + ); + assert!( + invalid("tab", "^1.21", "tab", "menu = \"customEditor.toolbar\"\nview = \"statement\"\ncommand = \"run\"") + .contains("layout = \"tab\"") + ); + assert!( + invalid("no-view", "^1.21", "split", "menu = \"customEditor.toolbar\"\ncommand = \"run\"") + .contains("needs `view`") + ); + assert!( + invalid("bad-view", "^1.21", "split", "menu = \"customEditor.toolbar\"\nview = \"nope\"\ncommand = \"run\"") + .contains("[[contributes.customEditors]]") + ); + assert!( + invalid( + "bad-cmd", + "^1.21", + "split", + "menu = \"customEditor.toolbar\"\nview = \"statement\"\ncommand = \"nope\"" + ) + .contains("[[contributes.commands]]") + ); +} diff --git a/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/Cargo.lock b/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/Cargo.lock new file mode 100644 index 0000000000..98433aaff2 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/Cargo.lock @@ -0,0 +1,336 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anyhow" +version = "1.0.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cb931c189b85683d69a5cfad41d4d418671e1ac413dd209f3f2fc31e3cfd902" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" +dependencies = [ + "foldhash", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "macro-string" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e7b3a5bbb2f63aaa223a671ea1bd0e7bc16bd30ce387324cf63995deaddbbd2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "openidea-plugin" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "wit-bindgen", +] + +[[package]] +name = "openidea-test-custom-editor-toolbar" +version = "0.1.0" +dependencies = [ + "openidea-plugin", +] + +[[package]] +name = "prettyplease" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0" +dependencies = [ + "proc-macro2", + "syn", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "wasm-encoder" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c86ff6668190d9fb70372b306b4f9fe8930f0e2f57ce72e4922bf2f117900949" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b" +dependencies = [ + "bitflags", + "hashbrown", + "indexmap", + "semver", +] + +[[package]] +name = "wit-bindgen" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b85a987ab61d365382d25c7d47e26edd48941b3bf6e3fbf76eff918bc71dab06" +dependencies = [ + "bitflags", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "775e122e390603abfacd548027016cd0113a6e2bf2f8ce6bdd3658b013456ea8" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84e26e13b9d972026778d2ffb7985736de116026fdc8d9464f966e12df2eb240" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a008a0d6b4840677326beb4edbeb210a2f1b7d0183fb7cc33f466b90fd7fb6" +dependencies = [ + "anyhow", + "macro-string", + "prettyplease", + "proc-macro2", + "quote", + "syn", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "078def49fdb49cab405c3006e05793b3fdaf7069126ba6b9c97d01ec8c98fe4c" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00f0dc051466ffe46787721fca3d088536f158ae400be044f1b1c386ba9397ad" +dependencies = [ + "anyhow", + "hashbrown", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-ident", + "wasmparser", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/Cargo.toml b/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/Cargo.toml new file mode 100644 index 0000000000..0cd705c206 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "openidea-test-custom-editor-toolbar" +version = "0.1.0" +edition = "2024" +publish = false + +[workspace] + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +openidea-plugin = { path = "../../../../../sdk/rust/openidea-plugin" } + +[profile.release] +opt-level = "s" +lto = true +strip = true +codegen-units = 1 +panic = "abort" diff --git a/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/dist/plugin.wasm new file mode 100644 index 0000000000..5fafeae946 Binary files /dev/null and b/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/dist/plugin.wasm.sources new file mode 100644 index 0000000000..10b64e0aa4 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/dist/plugin.wasm.sources @@ -0,0 +1 @@ +4a255f1746018ee5e01883f794ecca102909c993a0ee1d7c3679fdd19a131256 diff --git a/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/icons/plugin.svg b/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/icons/plugin.svg new file mode 100644 index 0000000000..3eab7355dc --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/icons/plugin.svg @@ -0,0 +1,4 @@ + + + + diff --git a/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/icons/run.svg b/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/icons/run.svg new file mode 100644 index 0000000000..877b44a6a5 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/icons/run.svg @@ -0,0 +1,3 @@ + + + diff --git a/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/plugin.toml b/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/plugin.toml new file mode 100644 index 0000000000..473ab30771 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/plugin.toml @@ -0,0 +1,48 @@ +id = "custom-editor-toolbar" +name = "Custom Editor Toolbar Sample" +version = "0.1.0" +description = "Sample split custom editor with SVG command buttons in customEditor.toolbar above the text half." +icon = "icons/plugin.svg" +engines.openidea = "^1.21" +wasm = "dist/plugin.wasm" + +[capabilities] +required = ["editor.read"] + +[[contributes.commands]] +id = "run" +title = "Run Solution" +icon = "icons/run.svg" + +[[contributes.commands]] +id = "submit" +title = "Submit Solution" +icon = "check" + +[[contributes.commands]] +id = "inspect" +title = "Inspect Document" + +[[contributes.customEditors]] +id = "statement" +title = "Statement" +patterns = ["*.problem.py"] +priority = "default" +layout = "split" +web = "web/index.html" + +[[contributes.menus]] +menu = "customEditor.toolbar" +view = "statement" +command = "run" + +[[contributes.menus]] +menu = "customEditor.toolbar" +view = "statement" +command = "submit" + +[[contributes.menus]] +menu = "customEditor.toolbar" +view = "statement" +command = "inspect" +when = "editorLang == python" diff --git a/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/src/lib.rs b/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/src/lib.rs new file mode 100644 index 0000000000..066a834de1 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/src/lib.rs @@ -0,0 +1,19 @@ +use openidea_plugin::{Error, Invocation, Plugin, register_plugin}; + +#[derive(Default)] +struct CustomEditorToolbarSample; + +impl Plugin for CustomEditorToolbarSample { + fn run_command(&mut self, id: &str, ctx: &Invocation, _arg: Option<&str>) -> Result, Error> { + let editor = ctx.editor().ok_or("no active editor")?; + let lines = editor.document()?.text.lines().count(); + match id { + "run" => Ok(Some(format!("run:{}:{lines}", editor.path()))), + "submit" => Ok(Some(format!("submit:{}:{lines}", editor.path()))), + "inspect" => Ok(Some(format!("inspect:{}:{lines}", editor.path()))), + _ => Err(Error::NotFound(format!("command {id}"))), + } + } +} + +register_plugin!(CustomEditorToolbarSample); diff --git a/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/web/index.html b/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/web/index.html new file mode 100644 index 0000000000..87d6fadf53 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/custom-editor-toolbar/web/index.html @@ -0,0 +1,57 @@ + + + + + + + +
+

Statement

+

+

+
+ + + diff --git a/docs/en/plugins/versioning.mdx b/docs/en/plugins/versioning.mdx index 1e90669f0d..5ad4f6fd53 100644 --- a/docs/en/plugins/versioning.mdx +++ b/docs/en/plugins/versioning.mdx @@ -12,30 +12,30 @@ The plugin API has one version number: the version of the WIT package in [`wit/` ## Versions -| API | Shipped with | Highlights | -| ------ | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| 1.0.0 | OpenIDEA 0.1.36 | The base API: commands, events, storage, tasks, project and editor access, VCS, diagnostics, network and secrets, processes, declarative views and custom editors, settings, editor providers, syntax provider | -| 1.1.0 | OpenIDEA 0.1.37 | `vcs.remotes`, `ui.copy-to-clipboard`, `ui.open-url`, opening a project file at a line from a view | -| 1.2.0 | OpenIDEA 0.1.38 | Background document indexers, pickers, input boxes and confirmations, plugin context keys for `when` clauses, the files selected in the Project view, a manifest `icon`, the `viewItem.context` menu | -| 1.3.0 | OpenIDEA 0.1.39 | Commit message and before-commit checks, Services detail panes, diagnostics while typing, hover, inlay hints, semantic tokens, file-changing code actions, HTTP endpoints, files outside the project (`fs.read`/`fs.write`, `project.write`, private plugin directory), batched `files-changed` events and path filters, workspace symbols, long-running processes, notifications with buttons, translations, multi-page settings, file template variables, web view PTYs, log tabs and content tabs | -| 1.4.0 | OpenIDEA 0.1.40 | `net.http:`, `ipc:`, `ide.commands` and `database.sources` capabilities; editor and project snapshots, decorations, text search, Problems, Git log/blame/diff; output channels; OAuth loopback; runs, terminal sessions, run configurations, test result parsing and run targets; formatting and other language features; embedded languages; snippets; more menu locations; database sources; MCP tools | -| 1.5.0 | OpenIDEA 0.1.41 | `Project::notify` (a notification in one project's window), the `net:ask` capability, run target validation, per-command run target working-directory arguments | -| 1.6.0 | OpenIDEA 0.1.43 | Bounded, project-bound background WebSockets for event-stream plugins | -| 1.7.0 | OpenIDEA 0.1.44 | `views.open-diff`: two texts in the diff viewer, such as a review's file before and after | -| 1.8.0 | OpenIDEA 0.1.45 | The `problems-changed` workbench event: the host keeps every producer's diagnostics per file, so an annotation follows the file rather than the invoking window | -| 1.9.0 | OpenIDEA 0.1.46 | Run configurations with an environment and a debugger, requests to a running language server (`lsp:`), server commands routed to plugins, editor panels | -| 1.10.0 | OpenIDEA 0.1.47 | `build.dependencies`: the Maven / Gradle dependency graph the IDE resolved (`build.read`) | -| 1.11.0 | OpenIDEA 0.1.48 | `ui.read-clipboard`: the clipboard's text and image in commands the user ran (`clipboard.read`) | -| 1.12.0 | OpenIDEA 0.1.49 | `ui.set-console-rules`: highlight rules (regex, palette colours, styles) for Run and Debug console output | -| 1.13.0 | OpenIDEA 0.1.49 | Optional `search-provider` export and `searchCategories`: custom Search Everywhere tabs with cancellable queries | -| 1.14.0 | OpenIDEA 0.1.50 | Optional `hover-actions` export: left-edge line actions revealed by line-edge hover, with an anchor line and inclusive trigger range; `[[contributes.javaAgents]]` `vmOptions` / `jdk`: JVM flags (optionally JetBrains Runtime–only) before `-javaagent:`; `ui.set-status-item-menu` / `set-window-status-item-menu`: a menu on a status bar item | -| 1.15.0 | OpenIDEA 0.1.51 | `caret-moved` event; declarative `[[contributes.skills]]` (`path = "skills//SKILL.md"`) for bundling agent skills in plugins | -| 1.16.0 | OpenIDEA 0.1.52 | Optional `completion-list-provider` export: completion marked incomplete is asked again while typing on, without re-asking the language server or other plugins; `decorations.set-markdown`: line-end decorations whose hover is a Markdown card | -| 1.17.0 | OpenIDEA 0.1.53 | `decorations.set-styled`: editor decorations with their own `#rrggbb` / `#rrggbbaa` foreground and background, for colors outside the theme palette | -| 1.18.0 | OpenIDEA 0.1.54 | `[[contributes.overlays]]`: a package web page floating over the workbench that never takes the keyboard focus, placed and resized through `openidea.overlay`; `[[contributes.dialogs]]`: a package web page in a modal, resizable IDE dialog opened with `views.reveal`, with a `closed` view event and `openidea.dialog.close()`; `events.subscribe-paths-with-options` (`debounce-ms`), `workspace.project.generation` and `FilesChanged` project/generation fields, stale run target/configuration rejection, and the `project-closed` lifecycle event; `execution-configurations`, `run.start-with-options` and `runDetectors.outputMode`: `pipes` or `pty` console output for plugin run configurations; `[[contributes.runAnything]]` with the `run-anything-provider` export: Run Anything lines starting with the plugin's prefix; `views.open-terminal-session-in`: a keyed terminal in a project directory; `workspace.invoking-project`: the project of the window a call serves, also in `gutter-actions` and `hover-actions`; `events.watch-paths` and the `watched-files-changed` event: files and directories outside the project, within `fs.read` grants; the `run-configuration-completion` export: completion in the Arguments field of the plugin's own run configurations; `services.context` and `services.toolbar` menus on the IDE's own Services nodes, with the selected services as the command argument; `executor` on `[[contributes.javaAgents]]`: "Run/Debug '\' with \" beside Run and Debug, the only launches that get that agent, also startable from the plugin's own commands with a configuration id; grant-scoped `agents.fork-session`: fork a recorded native agent session (`claude`, `codex`, or `copilot`) into a new task in the invoking window's project (`agents` capability), with the host validating the session and building the fork invocation itself | -| 1.19.0 | OpenIDEA 0.1.56 | `[capabilities.reasons]`: the plugin's own sentence on why it asks for a capability, shown below the host's description in the permission dialog and Settings › Plugins; `settings.open` / `settings.open-permissions`: open Settings at one of the plugin's own pages or at its permissions; `net.fetch-stream`: a response whose body is read as it arrives (server-sent events, streamed model replies), with the SDK's `host::fetch_stream` and `sse` parser; `editor.open-as-text`: open a file in the built-in text editor even when a custom editor claims it (the SDK's `host::open_editor_as_text`); the `openIn` menu: the **Open In** submenu of the editor, its tab and the Project view | -| 1.20.0 | OpenIDEA 0.1.57 | Database table context menus and read-only table schema inspection (`database.schema`). Optional `syntax-decorations-provider` export: foreground marks on an open text editor, in the theme tokens `rainbow-1` … `rainbow-5` or its own `#rrggbb` colours for dark and light themes, and a bounded slice of the editor's syntax tree. | -| 1.21.0 | In development | Run lifecycle & Run Config extensions: `run-started` event, `run-exited` for user-launched plugin runs, `run.stop`, `"java"` in `attach-child`, `prepareCommand` `mode` (`"run"` / `"debug"`) and loopback `javaDebug` JDWP attach, `run.upsert-configuration`, `run.open-edit-configurations`, `ownsBeforeLaunch`, transient `logFiles` log-tail tabs (`project.read` / `fs.read`), and the `runConsole.toolbar` menu. Settings controls: `presentation` (`radio`, `segmented`, `slider`, `color`, `checkbox-list`), `enumOptions` labels, hints and icons for `enum` values, `minimum` / `maximum` / `step`, and `when` conditions that hide a setting. `build.sdks` and `build.artifacts` under `build.read`: read installed JDKs/Maven/toolchains (`active` marking the project selection), build-model Maven/Gradle WAR artifacts, and Project Structure › Artifacts definitions (with `id`, `origin`, and `tool`) in trusted projects. `TextEditor::visible_lines` under `editor.read`: the first and last document line on screen when the command or event was invoked. `cloneSources`: plugin pages in the Clone Repository dialog's source list. `popup = true` on `[[contributes.dialogs]]`: a lightweight popup that closes on a click outside it or when the window loses focus. Database discovery and SQL execution in trusted projects: `database.connected-sources`, `database.list-schemas`, and `database.list-tables` under `database.schema`, plus bounded `database.execute-query` under the separate high-risk `database.query` capability. Run devices: `[[contributes.devices]]` lists emulators, simulators and phones in a title bar chooser for the configurations it applies to. Project view panes (`[[contributes.projectViewPanes]]`, the `project-view-provider` export, `project-view.refresh` / `select-in`, `projectViewContext` menu items) under `project.read`; `git.branches.popup` / `git.branch.context` menus with `invocation.git-action-context` and `views.open-revision-comparison` under `vcs.read`. `views.set-badge` (`host::set_view_badge`): per-window stripe badges for a plugin's declared `[[contributes.views]]` (at most 4 characters, `> 99` as `"99+"`, cleared on disable/reload/uninstall). | +| API | Shipped with | Highlights | +| ------ | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 1.0.0 | OpenIDEA 0.1.36 | The base API: commands, events, storage, tasks, project and editor access, VCS, diagnostics, network and secrets, processes, declarative views and custom editors, settings, editor providers, syntax provider | +| 1.1.0 | OpenIDEA 0.1.37 | `vcs.remotes`, `ui.copy-to-clipboard`, `ui.open-url`, opening a project file at a line from a view | +| 1.2.0 | OpenIDEA 0.1.38 | Background document indexers, pickers, input boxes and confirmations, plugin context keys for `when` clauses, the files selected in the Project view, a manifest `icon`, the `viewItem.context` menu | +| 1.3.0 | OpenIDEA 0.1.39 | Commit message and before-commit checks, Services detail panes, diagnostics while typing, hover, inlay hints, semantic tokens, file-changing code actions, HTTP endpoints, files outside the project (`fs.read`/`fs.write`, `project.write`, private plugin directory), batched `files-changed` events and path filters, workspace symbols, long-running processes, notifications with buttons, translations, multi-page settings, file template variables, web view PTYs, log tabs and content tabs | +| 1.4.0 | OpenIDEA 0.1.40 | `net.http:`, `ipc:`, `ide.commands` and `database.sources` capabilities; editor and project snapshots, decorations, text search, Problems, Git log/blame/diff; output channels; OAuth loopback; runs, terminal sessions, run configurations, test result parsing and run targets; formatting and other language features; embedded languages; snippets; more menu locations; database sources; MCP tools | +| 1.5.0 | OpenIDEA 0.1.41 | `Project::notify` (a notification in one project's window), the `net:ask` capability, run target validation, per-command run target working-directory arguments | +| 1.6.0 | OpenIDEA 0.1.43 | Bounded, project-bound background WebSockets for event-stream plugins | +| 1.7.0 | OpenIDEA 0.1.44 | `views.open-diff`: two texts in the diff viewer, such as a review's file before and after | +| 1.8.0 | OpenIDEA 0.1.45 | The `problems-changed` workbench event: the host keeps every producer's diagnostics per file, so an annotation follows the file rather than the invoking window | +| 1.9.0 | OpenIDEA 0.1.46 | Run configurations with an environment and a debugger, requests to a running language server (`lsp:`), server commands routed to plugins, editor panels | +| 1.10.0 | OpenIDEA 0.1.47 | `build.dependencies`: the Maven / Gradle dependency graph the IDE resolved (`build.read`) | +| 1.11.0 | OpenIDEA 0.1.48 | `ui.read-clipboard`: the clipboard's text and image in commands the user ran (`clipboard.read`) | +| 1.12.0 | OpenIDEA 0.1.49 | `ui.set-console-rules`: highlight rules (regex, palette colours, styles) for Run and Debug console output | +| 1.13.0 | OpenIDEA 0.1.49 | Optional `search-provider` export and `searchCategories`: custom Search Everywhere tabs with cancellable queries | +| 1.14.0 | OpenIDEA 0.1.50 | Optional `hover-actions` export: left-edge line actions revealed by line-edge hover, with an anchor line and inclusive trigger range; `[[contributes.javaAgents]]` `vmOptions` / `jdk`: JVM flags (optionally JetBrains Runtime–only) before `-javaagent:`; `ui.set-status-item-menu` / `set-window-status-item-menu`: a menu on a status bar item | +| 1.15.0 | OpenIDEA 0.1.51 | `caret-moved` event; declarative `[[contributes.skills]]` (`path = "skills//SKILL.md"`) for bundling agent skills in plugins | +| 1.16.0 | OpenIDEA 0.1.52 | Optional `completion-list-provider` export: completion marked incomplete is asked again while typing on, without re-asking the language server or other plugins; `decorations.set-markdown`: line-end decorations whose hover is a Markdown card | +| 1.17.0 | OpenIDEA 0.1.53 | `decorations.set-styled`: editor decorations with their own `#rrggbb` / `#rrggbbaa` foreground and background, for colors outside the theme palette | +| 1.18.0 | OpenIDEA 0.1.54 | `[[contributes.overlays]]`: a package web page floating over the workbench that never takes the keyboard focus, placed and resized through `openidea.overlay`; `[[contributes.dialogs]]`: a package web page in a modal, resizable IDE dialog opened with `views.reveal`, with a `closed` view event and `openidea.dialog.close()`; `events.subscribe-paths-with-options` (`debounce-ms`), `workspace.project.generation` and `FilesChanged` project/generation fields, stale run target/configuration rejection, and the `project-closed` lifecycle event; `execution-configurations`, `run.start-with-options` and `runDetectors.outputMode`: `pipes` or `pty` console output for plugin run configurations; `[[contributes.runAnything]]` with the `run-anything-provider` export: Run Anything lines starting with the plugin's prefix; `views.open-terminal-session-in`: a keyed terminal in a project directory; `workspace.invoking-project`: the project of the window a call serves, also in `gutter-actions` and `hover-actions`; `events.watch-paths` and the `watched-files-changed` event: files and directories outside the project, within `fs.read` grants; the `run-configuration-completion` export: completion in the Arguments field of the plugin's own run configurations; `services.context` and `services.toolbar` menus on the IDE's own Services nodes, with the selected services as the command argument; `executor` on `[[contributes.javaAgents]]`: "Run/Debug '\' with \" beside Run and Debug, the only launches that get that agent, also startable from the plugin's own commands with a configuration id; grant-scoped `agents.fork-session`: fork a recorded native agent session (`claude`, `codex`, or `copilot`) into a new task in the invoking window's project (`agents` capability), with the host validating the session and building the fork invocation itself | +| 1.19.0 | OpenIDEA 0.1.56 | `[capabilities.reasons]`: the plugin's own sentence on why it asks for a capability, shown below the host's description in the permission dialog and Settings › Plugins; `settings.open` / `settings.open-permissions`: open Settings at one of the plugin's own pages or at its permissions; `net.fetch-stream`: a response whose body is read as it arrives (server-sent events, streamed model replies), with the SDK's `host::fetch_stream` and `sse` parser; `editor.open-as-text`: open a file in the built-in text editor even when a custom editor claims it (the SDK's `host::open_editor_as_text`); the `openIn` menu: the **Open In** submenu of the editor, its tab and the Project view | +| 1.20.0 | OpenIDEA 0.1.57 | Database table context menus and read-only table schema inspection (`database.schema`). Optional `syntax-decorations-provider` export: foreground marks on an open text editor, in the theme tokens `rainbow-1` … `rainbow-5` or its own `#rrggbb` colours for dark and light themes, and a bounded slice of the editor's syntax tree. | +| 1.21.0 | In development | Run lifecycle & Run Config extensions: `run-started` event, `run-exited` for user-launched plugin runs, `run.stop`, `"java"` in `attach-child`, `prepareCommand` `mode` (`"run"` / `"debug"`) and loopback `javaDebug` JDWP attach, `run.upsert-configuration`, `run.open-edit-configurations`, `ownsBeforeLaunch`, transient `logFiles` log-tail tabs (`project.read` / `fs.read`), and the `runConsole.toolbar` menu. Settings controls: `presentation` (`radio`, `segmented`, `slider`, `color`, `checkbox-list`), `enumOptions` labels, hints and icons for `enum` values, `minimum` / `maximum` / `step`, and `when` conditions that hide a setting. `build.sdks` and `build.artifacts` under `build.read`: read installed JDKs/Maven/toolchains (`active` marking the project selection), build-model Maven/Gradle WAR artifacts, and Project Structure › Artifacts definitions (with `id`, `origin`, and `tool`) in trusted projects. `TextEditor::visible_lines` under `editor.read`: the first and last document line on screen when the command or event was invoked. `cloneSources`: plugin pages in the Clone Repository dialog's source list. `popup = true` on `[[contributes.dialogs]]`: a lightweight popup that closes on a click outside it or when the window loses focus. Database discovery and SQL execution in trusted projects: `database.connected-sources`, `database.list-schemas`, and `database.list-tables` under `database.schema`, plus bounded `database.execute-query` under the separate high-risk `database.query` capability. Run devices: `[[contributes.devices]]` lists emulators, simulators and phones in a title bar chooser for the configurations it applies to. Project view panes (`[[contributes.projectViewPanes]]`, the `project-view-provider` export, `project-view.refresh` / `select-in`, `projectViewContext` menu items) under `project.read`; `git.branches.popup` / `git.branch.context` menus with `invocation.git-action-context` and `views.open-revision-comparison` under `vcs.read`. `views.set-badge` (`host::set_view_badge`): per-window stripe badges for a plugin's declared `[[contributes.views]]` (at most 4 characters, `> 99` as `"99+"`, cleared on disable/reload/uninstall). `customEditor.toolbar` menu: SVG command toolbar strip above the text half of a plugin's split or preview custom editor. | The full list of what each version added is in [`plugins/README.md`](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md). diff --git a/docs/zh/plugins/versioning.mdx b/docs/zh/plugins/versioning.mdx index 31dfedcf5d..c6d78f926b 100644 --- a/docs/zh/plugins/versioning.mdx +++ b/docs/zh/plugins/versioning.mdx @@ -9,30 +9,30 @@ description: "engines.openidea、插件 API 从 1.0 到 1.23 的各个版本, ## 版本历史 -| API | 随哪个版本发布 | 主要内容 | -| ------ | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| 1.0.0 | OpenIDEA 0.1.36 | 基础 API:命令、事件、存储、任务、项目和编辑器访问、VCS、诊断、网络与密钥、进程、声明式视图和自定义编辑器、设置、编辑器 provider、syntax provider | -| 1.1.0 | OpenIDEA 0.1.37 | `vcs.remotes`、`ui.copy-to-clipboard`、`ui.open-url`,从视图中打开项目文件的指定行 | -| 1.2.0 | OpenIDEA 0.1.38 | 后台文档索引器;选择器、输入框和确认框;插件自定义的 `when` 上下文键;项目视图中选中的文件;清单 `icon`;`viewItem.context` 菜单 | -| 1.3.0 | OpenIDEA 0.1.39 | 提交信息和提交前检查、Services 详情面板、输入时诊断、悬停、内嵌提示、语义 token、改动文件的代码操作、HTTP 端点、项目外文件(`fs.read`/`fs.write`、`project.write`、插件私有目录)、批量 `files-changed` 事件和路径过滤、工作区符号、长时间运行的进程、带按钮的通知、翻译、多页设置、文件模板变量、Web 视图 PTY、日志标签页和内容标签页 | -| 1.4.0 | OpenIDEA 0.1.40 | `net.http:`、`ipc:`、`ide.commands` 和 `database.sources` 能力;编辑器与项目快照、装饰、文本搜索、问题视图、Git log/blame/diff;输出通道;OAuth 回环;运行、终端会话、运行配置、测试结果解析和运行目标;格式化等语言功能;嵌入语言;代码片段;更多菜单位置;数据库数据源;MCP 工具 | -| 1.5.0 | OpenIDEA 0.1.41 | `Project::notify`(只在某个项目的窗口中显示通知)、`net:ask` 能力、运行目标启动前校验、运行目标按命令设置工作目录参数 | -| 1.6.0 | OpenIDEA 0.1.43 | 面向事件流插件、受容量限制且绑定项目的后台 WebSocket | -| 1.7.0 | OpenIDEA 0.1.44 | `views.open-diff`:在差异查看器中对比两段文本,例如评审中某个文件的修改前后 | -| 1.8.0 | OpenIDEA 0.1.45 | `problems-changed` 工作台事件:宿主按文件保存每个生产者的诊断,注解跟着文件走,而不是跟着调用它的窗口 | -| 1.9.0 | OpenIDEA 0.1.46 | 带环境变量和调试器的运行配置、向正在运行的语言服务器发送请求(`lsp:`)、交给插件处理的服务器命令、编辑器面板 | -| 1.10.0 | OpenIDEA 0.1.47 | `build.dependencies`:IDE 已解析的 Maven / Gradle 依赖图(`build.read`) | -| 1.11.0 | OpenIDEA 0.1.48 | `ui.read-clipboard`:在用户运行的命令中读取剪贴板的文本和图片(`clipboard.read`) | -| 1.12.0 | OpenIDEA 0.1.49 | `ui.set-console-rules`:Run/Debug 控制台输出的高亮规则(正则、调色板颜色、文本样式) | -| 1.13.0 | OpenIDEA 0.1.49 | 新增 `search-provider` 导出和 `searchCategories` 贡献点:可取消查询的全局搜索自定义分类 | -| 1.14.0 | OpenIDEA 0.1.50 | 可选 `hover-actions` 导出:行内侧 hover 显示的左侧操作,带锚定行和包含式触发行范围; `[[contributes.javaAgents]]` 的 `vmOptions` / `jdk`:在 `-javaagent:` 之前注入 JVM 参数(可选仅 JetBrains Runtime);`ui.set-status-item-menu` / `set-window-status-item-menu`:状态栏项菜单 | -| 1.15.0 | OpenIDEA 0.1.51 | `caret-moved` 事件;声明式 `[[contributes.skills]]`(`path = "skills//SKILL.md"`),在插件包中打包代理技能 | -| 1.16.0 | OpenIDEA 0.1.52 | 可选 `completion-list-provider` 导出:标记为不完整的补全在继续输入时再次询问,不会重新询问语言服务器和其他插件;`decorations.set-markdown`:悬停显示 Markdown 卡片的行尾装饰 | -| 1.17.0 | OpenIDEA 0.1.53 | `decorations.set-styled`:自带 `#rrggbb` / `#rrggbbaa` 前景色和背景色的编辑器装饰,用于主题调色板之外的颜色 | -| 1.18.0 | OpenIDEA 0.1.54 | `[[contributes.overlays]]`:悬浮在工作台上方、从不抢占键盘焦点的插件网页,可通过 `openidea.overlay` 移动和调整大小;`[[contributes.dialogs]]`:插件网页显示在可调整大小的模态对话框中,用 `views.reveal` 打开,关闭时发 `closed` 视图事件,页面可调用 `openidea.dialog.close()`;`events.subscribe-paths-with-options`(`debounce-ms`)、`workspace.project.generation` 与 `FilesChanged` 的 `project`/`generation` 字段、过期运行目标/配置拒绝以及 `project-closed` 生命周期事件;`execution-configurations`、`run.start-with-options` 与 `runDetectors.outputMode`:插件运行配置的控制台输出方式(`pipes` 或 `pty`);`[[contributes.runAnything]]` 与 `run-anything-provider` 导出:以插件前缀开头的 Run Anything 行;`views.open-terminal-session-in`:在项目子目录中打开带 key 的终端;`workspace.invoking-project`:本次调用所服务窗口的项目,`gutter-actions` 和 `hover-actions` 中也可用;`events.watch-paths` 与 `watched-files-changed` 事件:监听项目之外、`fs.read` 授权范围内的文件和目录;`run-configuration-completion` 导出:补全插件自己运行配置的“实参”字段;`services.context` 和 `services.toolbar` 菜单:作用于 IDE 自带的 Services 节点,命令参数是选中的服务;`[[contributes.javaAgents]]` 的 `executor`:运行和调试旁边的“使用 \ 运行/调试 '\'”,只有经它启动时才加载该代理,插件自己的命令也可用配置 id 经它启动;需授权的 `agents.fork-session`:把录制的原生 agent 会话(`claude`、`codex` 或 `copilot`)派生为调用窗口项目中的新任务(`agents` 能力),宿主自行校验会话并构造 fork 调用 | -| 1.19.0 | OpenIDEA 0.1.56 | `[capabilities.reasons]`:插件用一句话说明为什么需要某个能力,显示在授权对话框和 设置 › 插件 中宿主说明的下方;`settings.open` / `settings.open-permissions`:打开设置并定位到插件自己的页面或它的权限;`net.fetch-stream`:边到达边读取响应体(服务器推送事件 SSE、模型的流式回复),SDK 提供 `host::fetch_stream` 和 `sse` 解析器;`editor.open-as-text`:即使文件被自定义编辑器认领,也用内置文本编辑器打开(SDK 的 `host::open_editor_as_text`);菜单点 `openIn`:编辑器、标签页和项目视图的 **打开方式** 子菜单 | -| 1.20.0 | OpenIDEA 0.1.57 | 数据库表的上下文菜单和只读表结构查看(`database.schema`)。可选的 `syntax-decorations-provider` 导出:用主题 token `rainbow-1` … `rainbow-5` 或自带的深色/浅色主题 `#rrggbb` 颜色,给打开的文本编辑器中的范围涂前景色,依据编辑器语法树的有界片段。 | -| 1.21.0 | `main` 上开发中 | 运行配置与运行生命周期扩展:`run-started` 事件与用户启动配置时的 `run-exited`、`run.stop`、`attach-child` 支持 `"java"`、`prepareCommand` 传入 `mode`(`"run"` / `"debug"`)并支持回环 `javaDebug` 附加 JDWP 调试器、`run.upsert-configuration`、`run.open-edit-configurations`、`ownsBeforeLaunch`、控制台日志文件实时标签页 `logFiles`(按 `project.read` / `fs.read` 授权)以及 `runConsole.toolbar` 菜单位置。设置控件:`presentation`(`radio`、`segmented`、`slider`、`color`、`checkbox-list`),为 `enum` 值提供标签、说明和图标的 `enumOptions`,`minimum` / `maximum` / `step`,以及隐藏设置的 `when` 条件。`build.read` 新增 `build.sdks` 与 `build.artifacts`:在受信任项目中读取已安装的 JDK / Maven / 工具链(带项目当前选中的 `active` 标记)以及构建模型 Maven/Gradle WAR 产物和 Project Structure › Artifacts 定义(含 `id`、`origin` 与 `tool`)。`editor.read` 下的 `TextEditor::visible_lines`:命令或事件触发时屏幕上显示的首行和末行。`[[contributes.dialogs]]` 的 `popup = true`:轻量弹出层,点击外部或窗口失去焦点时关闭。`cloneSources`:Clone Repository 对话框来源列表中的插件页面。受信任项目中的数据库发现与 SQL 执行:`database.schema` 新增 `database.connected-sources`、`database.list-schemas`、`database.list-tables`;新增独立高风险能力 `database.query` 与有界的 `database.execute-query`。 运行设备:`[[contributes.devices]]` 在标题栏的设备选择器中列出模拟器和手机,用于其适用的运行配置。Project 视图窗格(`[[contributes.projectViewPanes]]`、`project-view-provider` 导出、`project-view.refresh` / `select-in`、`projectViewContext` 菜单项),需要 `project.read`;`git.branches.popup` / `git.branch.context` 菜单、`invocation.git-action-context` 与 `views.open-revision-comparison`,需要 `vcs.read`。`views.set-badge`(`host::set_view_badge`):按窗口为插件声明的 `[[contributes.views]]` 设置边栏徽章(最多 4 个字符,`> 99` 显示为 `"99+"`,禁用/重载/卸载时自动清除)。 | +| API | 随哪个版本发布 | 主要内容 | +| ------ | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 1.0.0 | OpenIDEA 0.1.36 | 基础 API:命令、事件、存储、任务、项目和编辑器访问、VCS、诊断、网络与密钥、进程、声明式视图和自定义编辑器、设置、编辑器 provider、syntax provider | +| 1.1.0 | OpenIDEA 0.1.37 | `vcs.remotes`、`ui.copy-to-clipboard`、`ui.open-url`,从视图中打开项目文件的指定行 | +| 1.2.0 | OpenIDEA 0.1.38 | 后台文档索引器;选择器、输入框和确认框;插件自定义的 `when` 上下文键;项目视图中选中的文件;清单 `icon`;`viewItem.context` 菜单 | +| 1.3.0 | OpenIDEA 0.1.39 | 提交信息和提交前检查、Services 详情面板、输入时诊断、悬停、内嵌提示、语义 token、改动文件的代码操作、HTTP 端点、项目外文件(`fs.read`/`fs.write`、`project.write`、插件私有目录)、批量 `files-changed` 事件和路径过滤、工作区符号、长时间运行的进程、带按钮的通知、翻译、多页设置、文件模板变量、Web 视图 PTY、日志标签页和内容标签页 | +| 1.4.0 | OpenIDEA 0.1.40 | `net.http:`、`ipc:`、`ide.commands` 和 `database.sources` 能力;编辑器与项目快照、装饰、文本搜索、问题视图、Git log/blame/diff;输出通道;OAuth 回环;运行、终端会话、运行配置、测试结果解析和运行目标;格式化等语言功能;嵌入语言;代码片段;更多菜单位置;数据库数据源;MCP 工具 | +| 1.5.0 | OpenIDEA 0.1.41 | `Project::notify`(只在某个项目的窗口中显示通知)、`net:ask` 能力、运行目标启动前校验、运行目标按命令设置工作目录参数 | +| 1.6.0 | OpenIDEA 0.1.43 | 面向事件流插件、受容量限制且绑定项目的后台 WebSocket | +| 1.7.0 | OpenIDEA 0.1.44 | `views.open-diff`:在差异查看器中对比两段文本,例如评审中某个文件的修改前后 | +| 1.8.0 | OpenIDEA 0.1.45 | `problems-changed` 工作台事件:宿主按文件保存每个生产者的诊断,注解跟着文件走,而不是跟着调用它的窗口 | +| 1.9.0 | OpenIDEA 0.1.46 | 带环境变量和调试器的运行配置、向正在运行的语言服务器发送请求(`lsp:`)、交给插件处理的服务器命令、编辑器面板 | +| 1.10.0 | OpenIDEA 0.1.47 | `build.dependencies`:IDE 已解析的 Maven / Gradle 依赖图(`build.read`) | +| 1.11.0 | OpenIDEA 0.1.48 | `ui.read-clipboard`:在用户运行的命令中读取剪贴板的文本和图片(`clipboard.read`) | +| 1.12.0 | OpenIDEA 0.1.49 | `ui.set-console-rules`:Run/Debug 控制台输出的高亮规则(正则、调色板颜色、文本样式) | +| 1.13.0 | OpenIDEA 0.1.49 | 新增 `search-provider` 导出和 `searchCategories` 贡献点:可取消查询的全局搜索自定义分类 | +| 1.14.0 | OpenIDEA 0.1.50 | 可选 `hover-actions` 导出:行内侧 hover 显示的左侧操作,带锚定行和包含式触发行范围; `[[contributes.javaAgents]]` 的 `vmOptions` / `jdk`:在 `-javaagent:` 之前注入 JVM 参数(可选仅 JetBrains Runtime);`ui.set-status-item-menu` / `set-window-status-item-menu`:状态栏项菜单 | +| 1.15.0 | OpenIDEA 0.1.51 | `caret-moved` 事件;声明式 `[[contributes.skills]]`(`path = "skills//SKILL.md"`),在插件包中打包代理技能 | +| 1.16.0 | OpenIDEA 0.1.52 | 可选 `completion-list-provider` 导出:标记为不完整的补全在继续输入时再次询问,不会重新询问语言服务器和其他插件;`decorations.set-markdown`:悬停显示 Markdown 卡片的行尾装饰 | +| 1.17.0 | OpenIDEA 0.1.53 | `decorations.set-styled`:自带 `#rrggbb` / `#rrggbbaa` 前景色和背景色的编辑器装饰,用于主题调色板之外的颜色 | +| 1.18.0 | OpenIDEA 0.1.54 | `[[contributes.overlays]]`:悬浮在工作台上方、从不抢占键盘焦点的插件网页,可通过 `openidea.overlay` 移动和调整大小;`[[contributes.dialogs]]`:插件网页显示在可调整大小的模态对话框中,用 `views.reveal` 打开,关闭时发 `closed` 视图事件,页面可调用 `openidea.dialog.close()`;`events.subscribe-paths-with-options`(`debounce-ms`)、`workspace.project.generation` 与 `FilesChanged` 的 `project`/`generation` 字段、过期运行目标/配置拒绝以及 `project-closed` 生命周期事件;`execution-configurations`、`run.start-with-options` 与 `runDetectors.outputMode`:插件运行配置的控制台输出方式(`pipes` 或 `pty`);`[[contributes.runAnything]]` 与 `run-anything-provider` 导出:以插件前缀开头的 Run Anything 行;`views.open-terminal-session-in`:在项目子目录中打开带 key 的终端;`workspace.invoking-project`:本次调用所服务窗口的项目,`gutter-actions` 和 `hover-actions` 中也可用;`events.watch-paths` 与 `watched-files-changed` 事件:监听项目之外、`fs.read` 授权范围内的文件和目录;`run-configuration-completion` 导出:补全插件自己运行配置的“实参”字段;`services.context` 和 `services.toolbar` 菜单:作用于 IDE 自带的 Services 节点,命令参数是选中的服务;`[[contributes.javaAgents]]` 的 `executor`:运行和调试旁边的“使用 \ 运行/调试 '\'”,只有经它启动时才加载该代理,插件自己的命令也可用配置 id 经它启动;需授权的 `agents.fork-session`:把录制的原生 agent 会话(`claude`、`codex` 或 `copilot`)派生为调用窗口项目中的新任务(`agents` 能力),宿主自行校验会话并构造 fork 调用 | +| 1.19.0 | OpenIDEA 0.1.56 | `[capabilities.reasons]`:插件用一句话说明为什么需要某个能力,显示在授权对话框和 设置 › 插件 中宿主说明的下方;`settings.open` / `settings.open-permissions`:打开设置并定位到插件自己的页面或它的权限;`net.fetch-stream`:边到达边读取响应体(服务器推送事件 SSE、模型的流式回复),SDK 提供 `host::fetch_stream` 和 `sse` 解析器;`editor.open-as-text`:即使文件被自定义编辑器认领,也用内置文本编辑器打开(SDK 的 `host::open_editor_as_text`);菜单点 `openIn`:编辑器、标签页和项目视图的 **打开方式** 子菜单 | +| 1.20.0 | OpenIDEA 0.1.57 | 数据库表的上下文菜单和只读表结构查看(`database.schema`)。可选的 `syntax-decorations-provider` 导出:用主题 token `rainbow-1` … `rainbow-5` 或自带的深色/浅色主题 `#rrggbb` 颜色,给打开的文本编辑器中的范围涂前景色,依据编辑器语法树的有界片段。 | +| 1.21.0 | `main` 上开发中 | 运行配置与运行生命周期扩展:`run-started` 事件与用户启动配置时的 `run-exited`、`run.stop`、`attach-child` 支持 `"java"`、`prepareCommand` 传入 `mode`(`"run"` / `"debug"`)并支持回环 `javaDebug` 附加 JDWP 调试器、`run.upsert-configuration`、`run.open-edit-configurations`、`ownsBeforeLaunch`、控制台日志文件实时标签页 `logFiles`(按 `project.read` / `fs.read` 授权)以及 `runConsole.toolbar` 菜单位置。设置控件:`presentation`(`radio`、`segmented`、`slider`、`color`、`checkbox-list`),为 `enum` 值提供标签、说明和图标的 `enumOptions`,`minimum` / `maximum` / `step`,以及隐藏设置的 `when` 条件。`build.read` 新增 `build.sdks` 与 `build.artifacts`:在受信任项目中读取已安装的 JDK / Maven / 工具链(带项目当前选中的 `active` 标记)以及构建模型 Maven/Gradle WAR 产物和 Project Structure › Artifacts 定义(含 `id`、`origin` 与 `tool`)。`editor.read` 下的 `TextEditor::visible_lines`:命令或事件触发时屏幕上显示的首行和末行。`[[contributes.dialogs]]` 的 `popup = true`:轻量弹出层,点击外部或窗口失去焦点时关闭。`cloneSources`:Clone Repository 对话框来源列表中的插件页面。受信任项目中的数据库发现与 SQL 执行:`database.schema` 新增 `database.connected-sources`、`database.list-schemas`、`database.list-tables`;新增独立高风险能力 `database.query` 与有界的 `database.execute-query`。 运行设备:`[[contributes.devices]]` 在标题栏的设备选择器中列出模拟器和手机,用于其适用的运行配置。Project 视图窗格(`[[contributes.projectViewPanes]]`、`project-view-provider` 导出、`project-view.refresh` / `select-in`、`projectViewContext` 菜单项),需要 `project.read`;`git.branches.popup` / `git.branch.context` 菜单、`invocation.git-action-context` 与 `views.open-revision-comparison`,需要 `vcs.read`。`views.set-badge`(`host::set_view_badge`):按窗口为插件声明的 `[[contributes.views]]` 设置边栏徽章(最多 4 个字符,`> 99` 显示为 `"99+"`,禁用/重载/卸载时自动清除)。`customEditor.toolbar` 菜单位置:在插件分屏或预览自定义编辑器的文本编辑区上方显示 SVG 命令工具栏。 | 每个版本新增内容的完整列表见 [`plugins/README.md`](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md)。 diff --git a/e2e/customEditorToolbar.spec.ts b/e2e/customEditorToolbar.spec.ts new file mode 100644 index 0000000000..afcd5ca5fd --- /dev/null +++ b/e2e/customEditorToolbar.spec.ts @@ -0,0 +1,279 @@ +import { expect, stubDesktop, test } from "./fixtures"; + +const EVIDENCE = process.env.CUSTOM_EDITOR_TOOLBAR_EVIDENCE; + +test("customEditor.toolbar renders SVG commands above split text half and hides in preview-only", async ({ + workbench: page, +}) => { + await page.setViewportSize({ width: 1200, height: 760 }); + await stubDesktop(page); + + await page.evaluate(async () => { + const backendPath = "/src/editor/core/backend.ts"; + const contributionsPath = "/src/workbench/contributions.ts"; + const pluginsBackendPath = "/src/features/plugins/backend.ts"; + const pluginsStorePath = "/src/features/plugins/store.ts"; + const projectionPath = "/src/features/plugins/projection.ts"; + const bridgeRawPath = "/src/features/plugins/views/frame-bridge.js?raw"; + + const { docBackend } = await import(/* @vite-ignore */ backendPath); + const { editorService } = await import(/* @vite-ignore */ contributionsPath); + const { createMemoryPluginsBackend, setPluginsBackend } = await import(/* @vite-ignore */ pluginsBackendPath); + const { usePlugins } = await import(/* @vite-ignore */ pluginsStorePath); + const { syncUiContributions } = await import(/* @vite-ignore */ projectionPath); + const { default: bridgeSource } = await import(/* @vite-ignore */ bridgeRawPath); + const bridgeFn = bridgeSource.trim().replace(/;\s*$/, ""); + + const source = "/dev/acme-api/two_sum.problem.py"; + const code = [ + "from typing import List", + "", + "", + "class Solution:", + " def twoSum(self, nums: List[int], target: int) -> List[int]:", + " seen: dict[int, int] = {}", + " for index, value in enumerate(nums):", + " complement = target - value", + " if complement in seen:", + " return [seen[complement], index]", + " seen[value] = index", + " return []", + "", + ].join("\n"); + docBackend().files.set(source, code); + window.__ipc.handlers.fs_read_text = (args) => docBackend().files.get(String(args.path)) ?? ""; + window.__ipc.handlers.fs_probe = () => ({ size: code.length, binary: false, tooLarge: false }); + window.__ipc.handlers.window_is_fullscreen = () => false; + + const runSvg = + '' + + '' + + ""; + const pluginSvg = + '' + + '' + + '' + + ""; + + const statementHtml = ` + + + + + + + +
+

1. Two Sum

+ Easy · Array · Hash Table +

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

+
Input:  nums = [2, 7, 11, 15], target = 9
+Output: [0, 1]
+
+ +`; + const pageUrl = URL.createObjectURL(new Blob([statementHtml], { type: "text/html" })); + + const base = createMemoryPluginsBackend(); + const template = (await base.list()).plugins[0]!; + const plugin = { + ...template, + id: "leetcode", + name: "LeetCode Runner", + status: "active" as const, + enabled: true, + icon: { light: pluginSvg, dark: null }, + }; + + const calls: unknown[] = []; + Object.assign(window, { __customToolbarCalls: calls }); + + setPluginsBackend({ + ...base, + webPageUrl: async (pluginId: string) => (pluginId === "leetcode" ? pageUrl : base.webPageUrl(pluginId, "v")), + assets: async (pluginId: string, prefix: string) => + pluginId === "leetcode" && prefix === "commandIcon/run" ? [["commandIcon/run", runSvg]] : [], + runCommand: async (pluginId: string, command: string, arg: string | null, editor: unknown, paths: string[]) => { + calls.push({ pluginId, command, arg, editor, paths }); + return null; + }, + }); + + const baseUi = [ + { + pluginId: "leetcode", + point: "commands", + key: "run", + decl: { id: "run", title: "Run Solution", icon: "icons/run.svg" }, + }, + { + pluginId: "leetcode", + point: "commands", + key: "submit", + decl: { id: "submit", title: "Submit Solution", icon: "check" }, + }, + { + pluginId: "leetcode", + point: "commands", + key: "testcase", + decl: { id: "testcase", title: "Edit Testcases" }, + }, + { + pluginId: "leetcode", + point: "customEditors", + key: "statement", + decl: { + id: "statement", + title: "Statement", + patterns: ["*.problem.py"], + priority: "default", + layout: "split", + web: "web/index.html", + }, + }, + ]; + Object.assign(window, { __customToolbarPlugin: plugin, __customToolbarBaseUi: baseUi }); + usePlugins.setState({ plugins: [plugin], ui: baseUi }); + syncUiContributions(baseUi, [plugin]); + await editorService().openFile(source); + }); + + await expect(page.frameLocator('iframe[data-plugin-webview="leetcode"]').locator("h1")).toHaveText("1. Two Sum"); + await expect(page.getByRole("toolbar", { name: "Statement actions" })).toHaveCount(0); + + if (EVIDENCE) { + await page.screenshot({ path: `${EVIDENCE}/7796-before-light.png`, animations: "disabled" }); + await page.evaluate(async () => { + const themePath = "/src/workbench/theme.ts"; + await (await import(/* @vite-ignore */ themePath)).setTheme("dark"); + }); + await expect(page.locator("html")).toHaveAttribute("data-theme", "dark"); + await page.screenshot({ path: `${EVIDENCE}/7796-before-dark.png`, animations: "disabled" }); + await page.evaluate(async () => { + const themePath = "/src/workbench/theme.ts"; + await (await import(/* @vite-ignore */ themePath)).setTheme("light"); + }); + await expect(page.locator("html")).toHaveAttribute("data-theme", "light"); + } + + // Now contribute `customEditor.toolbar` entries for `statement`. + await page.evaluate(async () => { + const pluginsStorePath = "/src/features/plugins/store.ts"; + const projectionPath = "/src/features/plugins/projection.ts"; + const { usePlugins } = await import(/* @vite-ignore */ pluginsStorePath); + const { syncUiContributions } = await import(/* @vite-ignore */ projectionPath); + const w = window as unknown as { __customToolbarPlugin: unknown; __customToolbarBaseUi: unknown[] }; + const ui = [ + ...w.__customToolbarBaseUi, + { + pluginId: "leetcode", + point: "menus", + key: "customEditor.toolbar/statement/run", + decl: { menu: "customEditor.toolbar", view: "statement", command: "run" }, + }, + { + pluginId: "leetcode", + point: "menus", + key: "customEditor.toolbar/statement/submit", + decl: { menu: "customEditor.toolbar", view: "statement", command: "submit" }, + }, + { + pluginId: "leetcode", + point: "menus", + key: "customEditor.toolbar/statement/testcase", + decl: { menu: "customEditor.toolbar", view: "statement", command: "testcase" }, + }, + ]; + usePlugins.setState({ plugins: [w.__customToolbarPlugin as never], ui: ui as never }); + syncUiContributions(ui as never, [w.__customToolbarPlugin as never]); + }); + + const toolbar = page.getByRole("toolbar", { name: "Statement actions" }); + await expect(toolbar).toBeVisible(); + const runBtn = toolbar.getByRole("button", { name: "Run Solution" }); + const submitBtn = toolbar.getByRole("button", { name: "Submit Solution" }); + const testcaseBtn = toolbar.getByRole("button", { name: "Edit Testcases" }); + await expect(runBtn.locator('[data-run-svg="1"]')).toBeVisible(); + await expect(submitBtn).toBeVisible(); + await expect(testcaseBtn.locator('[data-plugin-svg="1"]')).toBeVisible(); + + // Verify the strip sits directly above the text editor (not in the tab strip). + const geometry = await page.evaluate(() => { + const strip = document.querySelector('[role="toolbar"][aria-label="Statement actions"]')!.getBoundingClientRect(); + const cm = document.querySelector(".cm-editor")!.getBoundingClientRect(); + return { + stripTop: strip.top, + stripBottom: strip.bottom, + stripLeft: strip.left, + stripRight: strip.right, + cmTop: cm.top, + cmLeft: cm.left, + cmRight: cm.right, + }; + }); + expect(geometry.stripBottom).toBeLessThanOrEqual(geometry.cmTop + 1); + expect(Math.abs(geometry.stripLeft - geometry.cmLeft)).toBeLessThanOrEqual(2); + expect(Math.abs(geometry.stripRight - geometry.cmRight)).toBeLessThanOrEqual(2); + + if (EVIDENCE) { + await page.screenshot({ path: `${EVIDENCE}/7796-after-light.png`, animations: "disabled" }); + await page.evaluate(async () => { + const themePath = "/src/workbench/theme.ts"; + await (await import(/* @vite-ignore */ themePath)).setTheme("dark"); + }); + await expect(page.locator("html")).toHaveAttribute("data-theme", "dark"); + await page.screenshot({ path: `${EVIDENCE}/7796-after-dark.png`, animations: "disabled" }); + } + + // Clicking runs the command with the active editor context. + await runBtn.click(); + await expect + .poll(() => + page.evaluate(() => (window as unknown as { __customToolbarCalls: { command: string }[] }).__customToolbarCalls), + ) + .toEqual([ + expect.objectContaining({ + pluginId: "leetcode", + command: "run", + arg: null, + editor: expect.objectContaining({ path: "/dev/acme-api/two_sum.problem.py" }), + paths: [], + }), + ]); + + // Switching to preview-only hides the toolbar strip. + await page.getByRole("button", { name: "Statement Only" }).click(); + await expect(toolbar).toHaveCount(0); + + // Switching back to split restores it. + await page.getByRole("button", { name: "Editor and Statement" }).click(); + await expect(toolbar).toBeVisible(); +}); diff --git a/plugins/README.md b/plugins/README.md index dcfc656ee6..b241478ec0 100644 --- a/plugins/README.md +++ b/plugins/README.md @@ -136,38 +136,38 @@ work), but 0.1 code no longer runs: rebuild it against the 1.0 SDK. ### Contribution points -| Point | Declaration | Code needed | -| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------- | -| `commands` | `id`, `title`, `category?`, `when?` | to run them | -| `themes` | `path` (theme JSON), `editor-scheme?` | no | -| `iconThemes` | `id`, `label`, `path` (icon theme JSON, see §5) | no | -| `languages` | `path` (`languages/.toml` format, see §6) | no | -| `runDetectors` | `id`, `name`, `files`, `command`, `args?`, `test?`, `framework?` (API 1.4; §6.2) | no | -| `runConfigurations` | `files`: marker files for the optional `run-configurations` export (API 1.4) | yes | -| `javaAgents` | `path` (a jar in the package), `args?`, `vmOptions?`, `jdk?`, `executor?` — a Java agent for Java run configurations, behind `java.agent` (API 1.10; `vmOptions`/`jdk` in 1.14; `executor` in 1.18; _Java agents_) | no | -| `devices` | `id`, `name`, `command`, `args?`, `appliesTo`, `runArgs?`, `env?`, `prepare?` — run devices (emulators, simulators, phones) offered in a title bar chooser for the run configurations `appliesTo` matches (API 1.21; _Run devices_) | no | -| `skills` | `path` (`skills//SKILL.md` in the package) — agent skill folder staged into coding-agent sessions (API 1.15) | no | -| `mcpTools` | `name`, `description`, `inputSchema` (package JSON Schema path), `readOnly`, `destructive` (API 1.4; see _Plugin MCP tools_) | yes | -| `snippets` | `language`, `path` (named JSON snippets; API 1.4) | no | -| `providers` | `kinds`, `languages` (editor providers, see _Providers_) | yes | -| `secrets` | `name`, `label`, `description?` (see _Network_) | to use them | -| `menus` | `menu` (`editor.context`, `projectView.context`, `editorTab.context`, `viewItem.context`, `tools`, `commit.message`; API 1.4: `editor.title`, `mainToolbar`, `problems.context`, `searchResults.context`; API 1.18: `services.context`, `services.toolbar`; API 1.19: `openIn`; API 1.21: `git.branches.popup`, `git.branch.context`), `view?`, `command`, `when?` | no | -| `keymaps` | `command`, `key`, `mac?` (`Ctrl+Alt+C`; a chord: `Meta+K Meta+C`); `key = "Escape"` with a required `when` (API 1.10) runs after the editor's own Escape handling | no | -| `statusBar` | `id`, `text?`, `icon?`, `iconDark?` (API 1.21; at least `text` or `icon` is required), `tooltip?`, `command?`, `align?`, `priority?` | no | -| `settings` | `schema` (JSON file) or `pages` (API 1.3), `title?` — see _Settings_ | no | -| `views` | `id`, `title`, `icon?` (an icon name or a package SVG), `location` (`left`, `right`, `bottom`, `services`), `web?` (_Web views_), `frames?` (API 1.16), `group?`, `when?` (API 1.3) | without `web` | -| `projectViewPanes` | `id`, `title`, `weight?` (API 1.21, see [Project view panes](#project-view-panes)) | yes | -| `customEditors` | `id`, `title`, `patterns` (file names), `priority` (`default`, `option`), `layout?`, `web?`, `frames?`, `binary?` (API 1.16) | without `web` | -| `editorPanels` | `id`, `web`, `width` (pixels, 40–400), `when?`, `frames?` (API 1.16) — needs `editor.read` (API 1.9; _Editor panels_) | no | -| `overlays` | `id`, `web`, `width`, `height` (pixels, 40–800), `anchor?`, `when?`, `interactive?` — floats over the workbench, never takes the focus (API 1.18; _Overlays_) | no | -| `runAnything` | `prefix`, `title?` — Run Anything lines starting with `prefix`, answered by the `run-anything-provider` export (API 1.18; _Run Anything entries_) | no | -| `dialogs` | `id`, `title`, `web`, `width` (320–1600), `height` (200–1200) — a modal, resizable dialog opened by `views::reveal(id)` (API 1.18; _Dialogs_) | no | -| `runConfigTypes` | `id`, `label`, `web`, `layout?` (`embedded` / `full`), `height?`, `icon?`, `iconDark?`, `group?`, `command?`, `args?`, `prepareCommand?`, `matchConfigPrefix?`, `defaults?` — a custom Run/Debug Configurations form (`openidea.runConfig`; API 1.20; _Custom run configuration forms_) | no | -| `cloneSources` | `id`, `label`, `icon?` (icon name or package SVG), `web` — an entry of the Clone Repository dialog whose page posts the chosen URL (API 1.21; _Clone sources_) | no | -| `fileIcons` | `id`, `patterns` (file names), `icon` (SVG), `iconDark?` — whatever icon theme is in use | no | -| `fileTemplates` | `id`, `name`, `extension`, `path`; API 1.3: `fileName`, `variables = [{ name, prompt }]` — New menu | no | -| `commitChecks` | `id`, `title` — a before-commit check in Commit Options (see _Commits_) | yes | -| `serverCommands` | `server`, `command`, `run` — a language server's client command run by this plugin's command (API 1.9; see _Commands a server hands to the client_) | +| Point | Declaration | Code needed | +| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------- | +| `commands` | `id`, `title`, `category?`, `when?` | to run them | +| `themes` | `path` (theme JSON), `editor-scheme?` | no | +| `iconThemes` | `id`, `label`, `path` (icon theme JSON, see §5) | no | +| `languages` | `path` (`languages/.toml` format, see §6) | no | +| `runDetectors` | `id`, `name`, `files`, `command`, `args?`, `test?`, `framework?` (API 1.4; §6.2) | no | +| `runConfigurations` | `files`: marker files for the optional `run-configurations` export (API 1.4) | yes | +| `javaAgents` | `path` (a jar in the package), `args?`, `vmOptions?`, `jdk?`, `executor?` — a Java agent for Java run configurations, behind `java.agent` (API 1.10; `vmOptions`/`jdk` in 1.14; `executor` in 1.18; _Java agents_) | no | +| `devices` | `id`, `name`, `command`, `args?`, `appliesTo`, `runArgs?`, `env?`, `prepare?` — run devices (emulators, simulators, phones) offered in a title bar chooser for the run configurations `appliesTo` matches (API 1.21; _Run devices_) | no | +| `skills` | `path` (`skills//SKILL.md` in the package) — agent skill folder staged into coding-agent sessions (API 1.15) | no | +| `mcpTools` | `name`, `description`, `inputSchema` (package JSON Schema path), `readOnly`, `destructive` (API 1.4; see _Plugin MCP tools_) | yes | +| `snippets` | `language`, `path` (named JSON snippets; API 1.4) | no | +| `providers` | `kinds`, `languages` (editor providers, see _Providers_) | yes | +| `secrets` | `name`, `label`, `description?` (see _Network_) | to use them | +| `menus` | `menu` (`editor.context`, `projectView.context`, `editorTab.context`, `viewItem.context`, `tools`, `commit.message`; API 1.4: `editor.title`, `mainToolbar`, `problems.context`, `searchResults.context`; API 1.18: `services.context`, `services.toolbar`; API 1.19: `openIn`; API 1.21: `git.branches.popup`, `git.branch.context`, `customEditor.toolbar`), `view?`, `command`, `when?` | no | +| `keymaps` | `command`, `key`, `mac?` (`Ctrl+Alt+C`; a chord: `Meta+K Meta+C`); `key = "Escape"` with a required `when` (API 1.10) runs after the editor's own Escape handling | no | +| `statusBar` | `id`, `text?`, `icon?`, `iconDark?` (API 1.21; at least `text` or `icon` is required), `tooltip?`, `command?`, `align?`, `priority?` | no | +| `settings` | `schema` (JSON file) or `pages` (API 1.3), `title?` — see _Settings_ | no | +| `views` | `id`, `title`, `icon?` (an icon name or a package SVG), `location` (`left`, `right`, `bottom`, `services`), `web?` (_Web views_), `frames?` (API 1.16), `group?`, `when?` (API 1.3) | without `web` | +| `projectViewPanes` | `id`, `title`, `weight?` (API 1.21, see [Project view panes](#project-view-panes)) | yes | +| `customEditors` | `id`, `title`, `patterns` (file names), `priority` (`default`, `option`), `layout?`, `web?`, `frames?`, `binary?` (API 1.16) | without `web` | +| `editorPanels` | `id`, `web`, `width` (pixels, 40–400), `when?`, `frames?` (API 1.16) — needs `editor.read` (API 1.9; _Editor panels_) | no | +| `overlays` | `id`, `web`, `width`, `height` (pixels, 40–800), `anchor?`, `when?`, `interactive?` — floats over the workbench, never takes the focus (API 1.18; _Overlays_) | no | +| `runAnything` | `prefix`, `title?` — Run Anything lines starting with `prefix`, answered by the `run-anything-provider` export (API 1.18; _Run Anything entries_) | no | +| `dialogs` | `id`, `title`, `web`, `width` (320–1600), `height` (200–1200) — a modal, resizable dialog opened by `views::reveal(id)` (API 1.18; _Dialogs_) | no | +| `runConfigTypes` | `id`, `label`, `web`, `layout?` (`embedded` / `full`), `height?`, `icon?`, `iconDark?`, `group?`, `command?`, `args?`, `prepareCommand?`, `matchConfigPrefix?`, `defaults?` — a custom Run/Debug Configurations form (`openidea.runConfig`; API 1.20; _Custom run configuration forms_) | no | +| `cloneSources` | `id`, `label`, `icon?` (icon name or package SVG), `web` — an entry of the Clone Repository dialog whose page posts the chosen URL (API 1.21; _Clone sources_) | no | +| `fileIcons` | `id`, `patterns` (file names), `icon` (SVG), `iconDark?` — whatever icon theme is in use | no | +| `fileTemplates` | `id`, `name`, `extension`, `path`; API 1.3: `fileName`, `variables = [{ name, prompt }]` — New menu | no | +| `commitChecks` | `id`, `title` — a before-commit check in Commit Options (see _Commits_) | yes | +| `serverCommands` | `server`, `command`, `run` — a language server's client command run by this plugin's command (API 1.9; see _Commands a server hands to the client_) | A `viewItem.context` menu needs `view`, the id of one of the plugin's own views. It adds the commands to the right-click menu of the items in that @@ -2648,6 +2648,42 @@ with your editor next to it (the layout files start in) and the _Editor Only / Editor and … / … Only_ switch in the tab strip, as for Markdown. `"tab"` (the default) is the editor's own tab. +With API 1.21 (`engines.openidea = "^1.21"`), a split or preview custom editor +can add a thin command toolbar strip above its text-editor half using +`menu = "customEditor.toolbar"` in `[[contributes.menus]]`: + +```toml +[[contributes.commands]] +id = "run" +title = "Run Solution" +icon = "icons/run.svg" # built-in icon name or package SVG + +[[contributes.customEditors]] +id = "statement" +title = "Statement" +patterns = ["*.problem.py"] +layout = "split" # split or preview +web = "web/index.html" + +[[contributes.menus]] +menu = "customEditor.toolbar" +view = "statement" # this plugin's split/preview customEditor id +command = "run" +when = "editorLang == python" # optional, as for other menus +``` + +`view` must name one of the plugin's own `[[contributes.customEditors]]` with +`layout = "split"` or `"preview"`, and `command` must name one of its +`[[contributes.commands]]`; `layout = "tab"`, missing/unknown `view`, unknown +`command` and `submenu` are rejected at install time. Buttons render in a strip +above the text editor while the text half is visible (hidden in preview-only +mode), using the command's `icon` (else the plugin icon) and the command title +as tooltip and `aria-label`. Clicking a button runs the command with the same +editor context as `editor.title`. The +`crates/ide-plugin/tests/fixtures/custom-editor-toolbar` sample exercises this +menu with a package SVG icon, a built-in icon, a plugin-icon fallback and a +`when` clause. + `Html` is the escape hatch for content the declarative bodies can't show. It runs in a sandboxed frame — an opaque origin under a CSP that allows only its inline scripts and styles and `data:` images, no network, no IDE API — and diff --git a/src/features/plugins/__tests__/customEditorToolbar.test.tsx b/src/features/plugins/__tests__/customEditorToolbar.test.tsx new file mode 100644 index 0000000000..bec90eb9da --- /dev/null +++ b/src/features/plugins/__tests__/customEditorToolbar.test.tsx @@ -0,0 +1,298 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { act, cleanup, fireEvent, render, screen } from "@testing-library/react"; +import type { PluginEditor, PluginInfo, UiContribution } from "@/bindings"; +import { setContext } from "@/platform/context"; +import { setLocale } from "@/platform/i18n"; +import { textEditorWrapperFor, useMenuSlotItems, useTextEditorWrappers } from "@/workbench/contributions"; +import { createMemoryPluginsBackend, setPluginsBackend } from "../backend"; +import { providePluginEditorContext } from "../editorContext"; +import { defineBuiltinUiPoints } from "../points"; +import { clearUiContributions, syncUiContributions } from "../projection"; +import { usePlugins } from "../store"; + +vi.mock("../views/customEditor", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + CustomEditorPreview: ({ decl, path }: { decl: { title: string }; path: string }) => ( +
{`${decl.title}: ${path}`}
+ ), + }; +}); + +const RUN_SVG = + ''; +const PLUGIN_SVG = + ''; + +let undefinePoints: () => void = () => {}; +let stopEditorCtx: () => void = () => {}; + +const basePlugin = (extra: Partial = {}): PluginInfo => + ({ + id: "leetcode", + name: "LeetCode Runner", + version: "1.0.0", + status: "active", + enabled: true, + icon: { light: PLUGIN_SVG, dark: null }, + capabilities: [], + warnings: [], + ...extra, + }) as PluginInfo; + +beforeEach(() => { + undefinePoints = defineBuiltinUiPoints(); + setContext("editorLang", "python"); + setContext("plugin.leetcode.ready", true); + setContext("toolWindowFocus", false); +}); + +afterEach(async () => { + cleanup(); + stopEditorCtx(); + stopEditorCtx = () => {}; + clearUiContributions(); + undefinePoints(); + setPluginsBackend(null); + usePlugins.setState({ plugins: [], ui: [] }); + setContext("editorLang", undefined); + setContext("plugin.leetcode.ready", undefined); + setContext("toolWindowFocus", false); + await setLocale("en"); +}); + +describe("customEditor.toolbar", () => { + it("renders buttons above the text half, loads SVG/fallback icons, honors when, and runs with editor context", async () => { + const editor: PluginEditor = { + path: "/ws/two_sum.problem.py", + language: "python", + selections: [{ start: { line: 2, col: 4 }, end: { line: 2, col: 4 } }], + visibleLines: [0, 20], + }; + stopEditorCtx = providePluginEditorContext(() => editor); + const runCommand = vi.fn().mockResolvedValue(null); + const assets = vi.fn(async (_pluginId: string, prefix: string) => + prefix === "commandIcon/run" ? ([["commandIcon/run", RUN_SVG]] as [string, string][]) : [], + ); + setPluginsBackend({ ...createMemoryPluginsBackend([]), runCommand, assets }); + + const contributions: UiContribution[] = [ + { + pluginId: "leetcode", + point: "commands", + key: "run", + decl: { id: "run", title: "Run Solution", icon: "icons/run.svg" }, + }, + { + pluginId: "leetcode", + point: "commands", + key: "submit", + decl: { id: "submit", title: "Submit Solution", icon: "check" }, + }, + { + pluginId: "leetcode", + point: "commands", + key: "testcase", + decl: { id: "testcase", title: "Refresh" }, + }, + { + pluginId: "leetcode", + point: "customEditors", + key: "statement", + decl: { + id: "statement", + title: "Statement", + patterns: ["*.problem.py"], + priority: "default", + layout: "split", + web: "web/index.html", + }, + }, + { + pluginId: "leetcode", + point: "customEditors", + key: "other", + decl: { + id: "other", + title: "Other", + patterns: ["*.other.py"], + priority: "default", + layout: "split", + web: "web/index.html", + }, + }, + { + pluginId: "leetcode", + point: "menus", + key: "customEditor.toolbar/statement/run", + decl: { menu: "customEditor.toolbar", view: "statement", command: "run" }, + }, + { + pluginId: "leetcode", + point: "menus", + key: "customEditor.toolbar/statement/submit", + decl: { + menu: "customEditor.toolbar", + view: "statement", + command: "submit", + when: "plugin.leetcode.ready", + }, + }, + { + pluginId: "leetcode", + point: "menus", + key: "customEditor.toolbar/statement/testcase", + decl: { menu: "customEditor.toolbar", view: "statement", command: "testcase" }, + }, + { + pluginId: "leetcode", + point: "menus", + key: "customEditor.toolbar/other/submit", + decl: { menu: "customEditor.toolbar", view: "other", command: "submit" }, + }, + ]; + const plugins = [basePlugin()]; + usePlugins.setState({ plugins, ui: contributions }); + syncUiContributions(contributions, plugins); + + // Must not pollute editor.title. + expect(useMenuSlotItems.getState().slots["editor.title"] ?? []).toEqual([]); + + const wrapper = textEditorWrapperFor(useTextEditorWrappers.getState().wrappers, "/ws/two_sum.problem.py"); + expect(wrapper).toBeDefined(); + const Wrapper = wrapper!.component; + const TabActions = wrapper!.tabActions!; + + // Plugin titles remain verbatim even under a non-English UI locale ("Refresh" stays "Refresh"). + await setLocale("zh"); + + render( + <> + + +