From 5a41bd7d66c7851c52e657a9796427c64214197e Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Thu, 19 Nov 2026 03:02:15 +0800 Subject: [PATCH 1/2] =?UTF-8?q?feat(plugins):=20=E6=8F=92=E4=BB=B6?= =?UTF-8?q?=E8=A7=86=E5=9B=BE=EF=BC=88=E7=95=8C=E9=9D=A2=E6=A0=91=E4=B8=8E?= =?UTF-8?q?=E7=94=BB=E5=B8=83=E8=8A=82=E7=82=B9=EF=BC=89=E5=8F=96=E4=BB=A3?= =?UTF-8?q?=E5=8E=9F=E7=94=9F=20UI=20=E6=96=87=E6=A1=A3=EF=BC=8C=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=E8=AE=BE=E7=BD=AE=E5=8C=BA=E5=9F=9F=E4=B8=8E=E4=B8=89?= =?UTF-8?q?=E4=B8=AA=20SDK=20=E7=9A=84=20view()?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 契约:plugin-ui.schema.json 取代 native-ui.schema.json。工具窗口和设置区域的 view.function 指向后端视图函数,按 open/close/click/change/select/activate/ viewport/settings 事件返回整个视图、补丁或 {}。 - Core:plugin-native-ui 改名为 plugin-ui,新增界面树、画布、补丁和字段检查; 新命令 plugins.ui.applyResult 按清单、界面和上一版视图校验结果,超出预算或违反 界面规则时返回 plugin.ui.invalidView(带 field)。 - 清单新增 settingRegions(最多 16 个):在语言、构建系统、编译器页或插件自己的 设置标签放搜索关键词和插件视图;l10n 可追加其他语言的关键词。 - SDK:Node、Rust、Java 新增 view(id, handler),统一按同一规则读视图事件,不合法时 sdk.view.invalidEvent,处理函数不会运行;null 的可选字段视为缺省。 - 文档:契约 README、ui/settings 领域页、API 总表(API-13、API-19、API-37)、 能力版本页和协议更新记录。 - 顺手修正:toolchain_definitions 测试的 clippy err_expect,settings_view 测试的 rustfmt 格式。 --- rust/Cargo.lock | 22 +- rust/contracts/rust-core-api.md | 73 +- rust/crates/core/Cargo.toml | 2 +- rust/crates/core/src/protocol/command.rs | 10 +- .../core/src/runtime/dispatcher/plugins.rs | 6 +- .../core/src/tests/declarative_plugins.rs | 232 ------ rust/crates/core/src/tests/mod.rs | 1 + .../src/tests/plugin_settings_documents.rs | 74 ++ rust/crates/core/src/tests/plugin_views.rs | 167 ++++ .../core/src/tests/toolchain_definitions.rs | 5 +- rust/crates/plugin-manifest/Cargo.toml | 2 +- rust/crates/plugin-manifest/src/lib.rs | 6 +- rust/crates/plugin-manifest/src/manifest.rs | 13 +- .../crates/plugin-manifest/src/permissions.rs | 8 + rust/crates/plugin-manifest/src/settings.rs | 41 +- .../plugin-manifest/src/settings_surfaces.rs | 64 +- rust/crates/plugin-manifest/src/ui.rs | 58 +- rust/crates/plugin-manifest/src/validation.rs | 26 +- rust/crates/plugin-manifest/src/views.rs | 223 +++++ rust/crates/plugin-model/src/capabilities.rs | 4 +- rust/crates/plugin-model/src/lib.rs | 6 +- rust/crates/plugin-model/src/settings.rs | 28 + .../plugin-model/src/settings/documents.rs | 24 +- .../plugin-model/src/settings/localization.rs | 55 +- .../crates/plugin-model/src/settings/pages.rs | 43 +- .../plugin-model/src/settings/regions.rs | 205 +++++ rust/crates/plugin-model/src/view.rs | 30 + rust/crates/plugin-native-ui/Cargo.toml | 12 - rust/crates/plugin-native-ui/src/lib.rs | 431 ---------- rust/crates/plugin-ui/Cargo.toml | 10 + rust/crates/plugin-ui/src/canvas.rs | 412 +++++++++ rust/crates/plugin-ui/src/fields.rs | 280 +++++++ rust/crates/plugin-ui/src/lib.rs | 613 ++++++++++++++ rust/crates/plugin-ui/src/patch.rs | 183 ++++ rust/crates/plugin-ui/src/tree.rs | 494 +++++++++++ rust/crates/toolchain/src/settings_view.rs | 5 +- shared/plugins/README.md | 4 +- shared/plugins/contract/v1/README.md | 378 ++++++--- .../v1/fixtures/settings/l10n/zh-Hans.json | 8 + .../fixtures/settings/localization-cases.json | 14 + .../v1/fixtures/settings/settings.plugin.json | 12 + .../fixtures/ui/native-controls.plugin.json | 407 --------- .../v1/fixtures/ui/native-form.plugin.json | 157 ---- .../v1/fixtures/ui/native-panel.plugin.json | 137 --- .../v1/fixtures/ui/view-panel.plugin.json | 93 +++ .../contract/v1/fixtures/ui/view-results.json | 140 ++++ .../plugins/contract/v1/native-ui.schema.json | 781 ------------------ .../contract/v1/plugin-l10n.schema.json | 17 + .../contract/v1/plugin-manifest.schema.json | 45 +- .../plugins/contract/v1/plugin-ui.schema.json | 627 ++++++++++++++ shared/plugins/reference/api-catalog.md | 12 +- .../reference/capabilities-and-versions.md | 12 +- shared/plugins/reference/domains/settings.md | 64 +- shared/plugins/reference/domains/ui.md | 50 +- .../plugins/reference/protocol-changelog.md | 5 +- shared/plugins/sdk/java/README.md | 51 +- .../github/litheidea/plugin/sdk/Backend.java | 21 + .../litheidea/plugin/sdk/ViewEvent.java | 254 ++++++ .../litheidea/plugin/sdk/ViewPatch.java | 77 ++ .../litheidea/plugin/sdk/ViewResult.java | 59 ++ .../github/litheidea/plugin/sdk/ViewTest.java | 146 ++++ shared/plugins/sdk/node/README.md | 44 +- shared/plugins/sdk/node/src/backend.mjs | 18 + shared/plugins/sdk/node/src/index.d.ts | 163 ++++ shared/plugins/sdk/node/src/view.mjs | 36 + shared/plugins/sdk/node/test/backend.test.mjs | 66 ++ shared/plugins/sdk/node/test/types/keymap.mts | 3 +- .../plugins/sdk/node/test/types/tsconfig.json | 2 +- shared/plugins/sdk/node/test/types/view.mts | 69 ++ shared/plugins/sdk/rust/README.md | 43 +- .../sdk/rust/plugin-sdk/src/backend.rs | 15 + shared/plugins/sdk/rust/plugin-sdk/src/lib.rs | 12 +- .../plugins/sdk/rust/plugin-sdk/src/view.rs | 363 ++++++++ .../plugins/sdk/rust/plugin-sdk/tests/view.rs | 64 ++ 74 files changed, 5842 insertions(+), 2495 deletions(-) create mode 100644 rust/crates/core/src/tests/plugin_views.rs create mode 100644 rust/crates/plugin-manifest/src/views.rs create mode 100644 rust/crates/plugin-model/src/settings/regions.rs create mode 100644 rust/crates/plugin-model/src/view.rs delete mode 100644 rust/crates/plugin-native-ui/Cargo.toml delete mode 100644 rust/crates/plugin-native-ui/src/lib.rs create mode 100644 rust/crates/plugin-ui/Cargo.toml create mode 100644 rust/crates/plugin-ui/src/canvas.rs create mode 100644 rust/crates/plugin-ui/src/fields.rs create mode 100644 rust/crates/plugin-ui/src/lib.rs create mode 100644 rust/crates/plugin-ui/src/patch.rs create mode 100644 rust/crates/plugin-ui/src/tree.rs delete mode 100644 shared/plugins/contract/v1/fixtures/ui/native-controls.plugin.json delete mode 100644 shared/plugins/contract/v1/fixtures/ui/native-form.plugin.json delete mode 100644 shared/plugins/contract/v1/fixtures/ui/native-panel.plugin.json create mode 100644 shared/plugins/contract/v1/fixtures/ui/view-panel.plugin.json create mode 100644 shared/plugins/contract/v1/fixtures/ui/view-results.json delete mode 100644 shared/plugins/contract/v1/native-ui.schema.json create mode 100644 shared/plugins/contract/v1/plugin-ui.schema.json create mode 100644 shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/ViewEvent.java create mode 100644 shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/ViewPatch.java create mode 100644 shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/ViewResult.java create mode 100644 shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/ViewTest.java create mode 100644 shared/plugins/sdk/node/src/view.mjs create mode 100644 shared/plugins/sdk/node/test/types/view.mts create mode 100644 shared/plugins/sdk/rust/plugin-sdk/src/view.rs create mode 100644 shared/plugins/sdk/rust/plugin-sdk/tests/view.rs diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 19ac0e3e..cf1d8b8f 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -926,9 +926,9 @@ dependencies = [ "lithe-plugin-manifest", "lithe-plugin-marketplace", "lithe-plugin-model", - "lithe-plugin-native-ui", "lithe-plugin-output-links", "lithe-plugin-rpc", + "lithe-plugin-ui", "lithe-plugin-web-content", "lithe-process", "lithe-project", @@ -1301,9 +1301,9 @@ dependencies = [ "lithe-plugin-keymap-import", "lithe-plugin-language-servers", "lithe-plugin-model", - "lithe-plugin-native-ui", "lithe-plugin-output-links", "lithe-plugin-rpc", + "lithe-plugin-ui", "lithe-project-generators", "lithe-protocol", "lithe-toolchain", @@ -1336,16 +1336,6 @@ dependencies = [ "serde_json", ] -[[package]] -name = "lithe-plugin-native-ui" -version = "0.1.0" -dependencies = [ - "lithe-plugin-model", - "lithe-protocol", - "serde", - "serde_json", -] - [[package]] name = "lithe-plugin-output-links" version = "0.1.0" @@ -1384,6 +1374,14 @@ dependencies = [ "serde_json", ] +[[package]] +name = "lithe-plugin-ui" +version = "0.1.0" +dependencies = [ + "lithe-plugin-model", + "serde_json", +] + [[package]] name = "lithe-plugin-web-content" version = "0.1.0" diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 8983559a..ebbfd8d8 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -445,7 +445,7 @@ or removing a command fails until the table changes in the same commit. | `ai.inlineEdit.plan` | Plan a credential-free inline edit request | | `ai.inlineEdit.decode` | Decode the replacement text of an inline edit response | | `plugins.declarative.validate` | Validate and normalize a declarative plugin manifest | -| `plugins.nativeUI.validateData` | Validate native plugin UI data with declaration identity and node budgets | +| `plugins.ui.applyResult` | Check a backend result for a plugin view and return the whole view to draw | | `plugins.web.open` | Register a plugin page for a web tool window | | `plugins.web.close` | Forget a plugin page and lists its calls to cancel | | `plugins.web.resource` | Decide how a plugin page request is served | @@ -4953,6 +4953,12 @@ Success returns `{ status: "ok", state }`. The state contains: the manifest's section title (the empty heading first), so a translation changes only the shown `title`. References are zero-based indices into `rows` and `actions`; declaration order is retained within each section. +- `region`: present when the plugin placed a settings region on its own + Settings tab: `{ id, keywords, view? }`. `keywords` are the manifest + keywords followed by the translated ones that differ, so both languages + find the page. `view` is `{ function }`; the host calls it and draws each + result through `plugins.ui.applyResult`. Each entry of `pages` carries the + region placed on that page in the same shape. - `editors`: `{ global, project }`, each an array in exactly `rows` order. Every entry contains `value`, `resetValue`, `source`, `editable`, `overridden` and `invalidStored`, plus `input`/`resetInput` native-control projections. @@ -6224,21 +6230,33 @@ registered in Core for their lifetime: `build.runChanged` and returns `{ message }`, `null` when the page is closed or the progress is for a call that ended or has no page ID. -### Native plugin UI data - -`plugins.nativeUI.validateData` accepts `{ ui, data }`, where `ui` is the -validated native declaration (`schemaVersion` 0) and `data` is a provider's `{ nodes }` -reply. It returns `{ status: "ok", nodes }` or -`{ status: "rejected", error: { code: "plugin.ui.invalidData", message } }`. -Malformed envelopes remain Core `invalid_request` failures. The operation uses -the same identity, literal label, nesting and node budgets as manifest validation -and rejects data above 1 MiB. Form declarations validate bounded input/select/checkbox -controls (including search/editor/segmented/stepper), typed scalar defaults, choices, -info, button action references/width policies and onCommit references; form source replies -require empty nodes. Hosts inject this typed operation into their -presentation feature; views never call the C ABI. Windows can reuse validation -when it later adds a native renderer; Core support does not make Windows -advertise native plugin content. +### Plugin views + +`plugins.ui.applyResult` accepts `{ manifest, surface, view?, result }`. +`surface` names exactly one declared place that draws a view: +`{ toolWindowID }` for a tool window whose body is `view`, or +`{ settingRegionID }` for a settings region with a `view`. `view` is the +view the host drew last and is absent before the first result. `result` is +what the plugin's view function returned: `{ view }` (a whole view), +`{ patches }` (edits to `view`) or `{}` (nothing changed). + +It returns `{ status: "ok", view: { view, changed } }`, where `view` is the +complete checked view to draw and `changed` tells whether it differs from +the one drawn, or `{ status: "rejected", error: { code: +"plugin.ui.invalidView", message, field } }`, where `field` is the JSON path +of the first problem (`result.view[0].type`, `result.patches[1].id`, or +`view[...]` for a patched view). After a refusal the host keeps drawing the +previous view. Malformed envelopes remain Core `invalid_request` failures. + +Core checks the node vocabulary, the budgets, which nodes each surface +allows, and every reference to the manifest: bound controls and setting rows +name declared settings of a type the control edits, setting-action buttons +name declared setting actions, and tool rows name tools the plugin defines +or requires. Patches apply in order to a copy of `view`; a patch whose target +is missing refuses the whole result. Hosts call this operation for every +result and only render; they keep no second validator or patch engine. The +vocabulary and budgets are in the plugin contract README and +`plugin-ui.schema.json`. ### Workspace indexing policy @@ -7186,16 +7204,23 @@ This is an internal desktop command, not a new public plugin host method. Internal desktop commands reuse the validated settings manifest. They do not add plugin RPCs or admit capabilities. `plugins.settings.catalog` accepts up to -64 `{manifest, owner: {pluginID, version}, enabled}` records. It validates all +64 `{manifest, owner: {pluginID, version}, enabled, localizations?}` records +and an optional `language`. It validates all identities, rejects duplicates and returns deterministic `pages` (up to 512), -with stable `key`, `kind` (`language` or `buildSystem`), opaque `id`, display -`title`, and plugin-ID ordered `contributors` (`pluginID`, `version`, `title`, -`sections`). Sections reference indices in the complete settingsState rows and -actions. Only enabled contributors create pages; action-only pages are valid. +with stable `key`, `kind` (`language`, `buildSystem` or `compiler`), opaque +`id`, display `title`, and plugin-ID ordered `contributors` (`pluginID`, +`version`, `title`, `sections`, `region?`, `localization?`). Sections reference +indices in the complete settingsState rows and actions. Only enabled +contributors create pages; action-only and region-only pages are valid. Names come from enabled language/build declarations, with opaque ID fallback. -`settingsState.pages` supplies the same per-plugin placement projections, with -section titles translated when the state is. Catalog contributor sections keep -the manifest headings. +`settingsState.pages` supplies the same per-plugin placement projections. +`region` is the settings region the contributor placed on the page +(`{ id, keywords, view? }`, as in settingsState); hosts add its keywords to +the page's search terms. With `language`, each record's `localizations` +follows the settingsState rules: section titles are translated, translated +region keywords are appended, and `localization` is that plugin's report. +Without `language`, sections keep the manifest headings and no report is +returned. `plugins.settings.navigation` accepts at most 576 `items` (512 contributed pages plus 64 host entries), up to three levels deep, with stable `id`, `title`, nullable `parent`, `group`, `expanded`, optional `keywords` and optional `limit` diff --git a/rust/crates/core/Cargo.toml b/rust/crates/core/Cargo.toml index 66a6d968..45a9956e 100644 --- a/rust/crates/core/Cargo.toml +++ b/rust/crates/core/Cargo.toml @@ -40,7 +40,7 @@ lithe-plugin-manifest = { path = "../plugin-manifest" } lithe-plugin-lifecycle = { path = "../plugin-lifecycle" } lithe-plugin-marketplace = { path = "../plugin-marketplace" } lithe-plugin-model = { path = "../plugin-model" } -lithe-plugin-native-ui = { path = "../plugin-native-ui" } +lithe-plugin-ui = { path = "../plugin-ui" } lithe-plugin-output-links = { path = "../plugin-output-links" } lithe-plugin-rpc = { path = "../plugin-rpc" } lithe-plugin-web-content = { path = "../plugin-web-content" } diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 299e966e..db549ce8 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -59,7 +59,7 @@ pub enum CoreCommand { SearchActions, /// AI commit, pull request and inline edit planning run by `lithe-ai` (`ai.*`). Ai(AiCommand), - /// Plugin manifests, native UI and web content, plugin settings, installed + /// Plugin manifests, plugin views and web content, plugin settings, installed /// plugins and the marketplace (`plugins.*`). Plugins(PluginsCommand), /// Debug adapters, transports, sessions, breakpoints and inspection (`debug.*`). @@ -206,8 +206,8 @@ pub enum AiCommand { pub enum PluginsCommand { /// Validates and normalizes a declarative plugin manifest (`plugins.declarative.validate`). DeclarativeValidate, - /// Validates native plugin UI data with declaration identity and node budgets. - NativeUIValidateData, + /// Checks what a backend returned for a plugin view and gives the whole view to draw (`plugins.ui.applyResult`). + UIApplyResult, /// Registers a plugin page for a web tool window (`plugins.web.open`). WebOpen, /// Forgets a plugin page and lists its calls to cancel (`plugins.web.close`). @@ -1040,9 +1040,7 @@ impl CoreCommand { "plugins.declarative.validate" => { Some(Self::Plugins(PluginsCommand::DeclarativeValidate)) } - "plugins.nativeUI.validateData" => { - Some(Self::Plugins(PluginsCommand::NativeUIValidateData)) - } + "plugins.ui.applyResult" => Some(Self::Plugins(PluginsCommand::UIApplyResult)), "plugins.web.open" => Some(Self::Plugins(PluginsCommand::WebOpen)), "plugins.web.close" => Some(Self::Plugins(PluginsCommand::WebClose)), "plugins.web.resource" => Some(Self::Plugins(PluginsCommand::WebResource)), diff --git a/rust/crates/core/src/runtime/dispatcher/plugins.rs b/rust/crates/core/src/runtime/dispatcher/plugins.rs index 264308cb..e4b23ecb 100644 --- a/rust/crates/core/src/runtime/dispatcher/plugins.rs +++ b/rust/crates/core/src/runtime/dispatcher/plugins.rs @@ -1,4 +1,4 @@ -//! `plugins.*` commands: plugin manifests, native UI and web content, plugin settings, +//! `plugins.*` commands: plugin manifests, plugin views and web content, plugin settings, //! installed plugins and the marketplace. use super::plugin_response; @@ -12,8 +12,8 @@ pub(super) fn dispatch( payload: Value, ) -> CoreResponse { match command { - PluginsCommand::NativeUIValidateData => { - plugin_response(id, payload, lithe_plugin_native_ui::validate_data_command) + PluginsCommand::UIApplyResult => { + plugin_response(id, payload, lithe_plugin_manifest::apply_result_command) } PluginsCommand::WebOpen => { plugin_response(id, payload, lithe_plugin_web_content::open_command) diff --git a/rust/crates/core/src/tests/declarative_plugins.rs b/rust/crates/core/src/tests/declarative_plugins.rs index 26d9b138..44c879df 100644 --- a/rust/crates/core/src/tests/declarative_plugins.rs +++ b/rust/crates/core/src/tests/declarative_plugins.rs @@ -961,238 +961,6 @@ fn ui_icon_declarations_validate_and_preserve_theme_resources() { } } -/// Native controls are opt-in; a host that does not offer `ui` rejects them -/// before presentation. -#[test] -fn native_ui_validates_version_ownership_actions_and_budgets() { - let manifest: Value = - serde_json::from_str(contract_file!("fixtures/ui/native-panel.plugin.json")).unwrap(); - let result = validate(manifest.clone()); - assert_eq!(result["status"], "ok", "{result}"); - for icon in [json!({"host":"search"}), json!({"host":"reset"})] { - let mut with_icon = manifest.clone(); - with_icon["ui"]["toolWindows"][0]["native"]["actions"][1]["icon"] = icon; - assert_eq!(validate(with_icon)["status"], "ok"); - } - for icon in [ - json!({"host":"unknown"}), - json!({"path":"icons/custom.svg"}), - json!({"host":"reset","mode":"original"}), - ] { - let mut invalid = manifest.clone(); - invalid["ui"]["toolWindows"][0]["native"]["actions"][1]["icon"] = icon; - assert_eq!(validate(invalid)["status"], "rejected"); - } - let without_ui = validate_command(json!({"manifest": manifest, "hostCapabilities": {"buildSystems":[0], "buildProviders":[0]}})).unwrap(); - assert_eq!(without_ui["error"]["code"], "plugin.api.unsupported"); - assert_eq!(without_ui["error"]["field"], "requires.ui"); - let hosted = validate_command(json!({"manifest": manifest, "hostCapabilities": {"ui":[0], "buildSystems":[0], "buildProviders":[0]}})).unwrap(); - assert_eq!(hosted["status"], "ok", "{hosted}"); - for (pointer, value) in [ - ("/ui/toolWindows/0/native/schemaVersion", json!(1)), - ( - "/ui/toolWindows/0/native/source/buildSystemID", - json!("foreign"), - ), - ("/ui/toolWindows/0/native/toolbar", json!(["missing"])), - ( - "/ui/toolWindows/0/native/contextMenu", - json!(["inspect", "inspect"]), - ), - ( - "/ui/toolWindows/0/native/nodes", - json!([{"id":"same","label":"A"},{"id":"same","label":"B"}]), - ), - ( - "/ui/toolWindows/0/native/nodes", - json!(vec![json!({"id":"row","label":"x"}); 2001]), - ), - ("/requires/ui", json!(1)), - ] { - let mut invalid = manifest.clone(); - *invalid.pointer_mut(pointer).unwrap() = value; - assert_eq!(validate(invalid)["status"], "rejected", "{pointer}"); - } - let mut styled = manifest.clone(); - styled["ui"]["toolWindows"][0]["native"]["color"] = json!("red"); - assert_eq!(validate(styled)["status"], "rejected"); - let mut mixed = manifest; - mixed["ui"]["toolWindows"][0]["text"] = json!("cannot mix body types"); - assert_eq!(validate(mixed)["status"], "rejected"); -} - -#[test] -fn native_ui_forms_validate_controls_values_actions_and_budgets() { - let manifest: Value = - serde_json::from_str(contract_file!("fixtures/ui/native-form.plugin.json")).unwrap(); - assert_eq!(validate(manifest.clone())["status"], "ok"); - for (pointer, value) in [ - ("/ui/toolWindows/0/native/kind", json!("list")), - ( - "/ui/toolWindows/0/native/nodes", - json!([{"id":"row","label":"Row"}]), - ), - ("/ui/toolWindows/0/native/controls", json!([])), - ( - "/ui/toolWindows/0/native/controls", - json!(vec![ - json!({"id":"field","kind":"input","label":"Field","value":""}); - 33 - ]), - ), - ("/ui/toolWindows/0/native/controls/0/kind", json!("html")), - ("/ui/toolWindows/0/native/controls/0/id", json!("form")), - ("/ui/toolWindows/0/native/controls/0/value", json!(false)), - ( - "/ui/toolWindows/0/native/controls/0/value", - json!("😀".repeat(257)), - ), - ( - "/ui/toolWindows/0/native/controls/2/value", - json!("missing"), - ), - ("/ui/toolWindows/0/native/controls/2/options", json!([])), - ( - "/ui/toolWindows/0/native/controls/2/options", - json!([{"id":"same","label":"A"},{"id":"same","label":"B"}]), - ), - ( - "/ui/toolWindows/0/native/controls/2/options", - json!(vec![json!({"id":"option","label":"Option"}); 129]), - ), - ("/ui/toolWindows/0/native/controls/3/value", json!("true")), - ] { - let mut invalid = manifest.clone(); - *invalid.pointer_mut(pointer).unwrap() = value; - assert_eq!(validate(invalid)["status"], "rejected", "{pointer}"); - } - for (key, value) in [ - ("onCommit", json!("missing")), - ("options", json!([])), - ("color", json!("red")), - ] { - let mut invalid = manifest.clone(); - invalid["ui"]["toolWindows"][0]["native"]["controls"][0][key] = value; - assert_eq!(validate(invalid)["status"], "rejected", "{key}"); - } - let mut dynamic = manifest; - let native = &mut dynamic["ui"]["toolWindows"][0]["native"]; - native["source"] = json!({"buildSystemID":"sample","function":"form.nodes"}); - native["actions"] = json!([{"id":"changed","title":"Changed","kind":"invoke","function":"form.changed","requiresSelection":false}]); - native["controls"][0]["onCommit"] = json!("changed"); - assert_eq!(validate(dynamic.clone())["status"], "ok"); - dynamic["ui"]["toolWindows"][0]["native"]["actions"][0]["requiresSelection"] = json!(true); - assert_eq!(validate(dynamic)["status"], "rejected"); -} - -#[test] -fn native_ui_form_grid_validates_columns_spans_and_scope() { - let manifest: Value = - serde_json::from_str(contract_file!("fixtures/ui/native-form.plugin.json")).unwrap(); - assert_eq!(validate(manifest.clone())["status"], "ok"); - for (pointer, value) in [ - ("/ui/toolWindows/0/native/layout/columns", json!(0)), - ("/ui/toolWindows/0/native/layout/columns", json!(13)), - ("/ui/toolWindows/0/native/layout/columns", json!(1.5)), - ("/ui/toolWindows/0/native/controls/0/span", json!(0)), - ("/ui/toolWindows/0/native/controls/0/span", json!(13)), - ("/ui/toolWindows/0/native/controls/0/span", json!("6")), - ] { - let mut invalid = manifest.clone(); - *invalid.pointer_mut(pointer).unwrap() = value; - assert_eq!(validate(invalid)["status"], "rejected", "{pointer}"); - } - let mut smaller_grid = manifest.clone(); - smaller_grid["ui"]["toolWindows"][0]["native"]["layout"]["columns"] = json!(4); - assert_eq!(validate(smaller_grid)["status"], "rejected"); - let mut missing_grid = manifest.clone(); - missing_grid["ui"]["toolWindows"][0]["native"] - .as_object_mut() - .unwrap() - .remove("layout"); - assert_eq!(validate(missing_grid.clone())["status"], "rejected"); - for control in missing_grid["ui"]["toolWindows"][0]["native"]["controls"] - .as_array_mut() - .unwrap() - { - control.as_object_mut().unwrap().remove("span"); - } - assert_eq!(validate(missing_grid)["status"], "ok"); - let mut styled = manifest; - styled["ui"]["toolWindows"][0]["native"]["layout"]["gap"] = json!(99); - assert_eq!(validate(styled)["status"], "rejected"); - let mut tree: Value = - serde_json::from_str(contract_file!("fixtures/ui/native-panel.plugin.json")).unwrap(); - tree["ui"]["toolWindows"][0]["native"]["layout"] = json!({"columns":12}); - assert_eq!(validate(tree)["status"], "rejected"); -} - -#[test] -fn native_public_controls_validate_types_ranges_info_and_buttons() { - let manifest: Value = - serde_json::from_str(contract_file!("fixtures/ui/native-controls.plugin.json")).unwrap(); - assert_eq!(validate(manifest.clone())["status"], "ok"); - for (pointer, value) in [ - ("/ui/toolWindows/0/native/controls/0/info", json!(" ")), - ( - "/ui/toolWindows/0/native/controls/0/info", - json!("x".repeat(1025)), - ), - ("/ui/toolWindows/0/native/controls/8/value", json!(true)), - ( - "/ui/toolWindows/0/native/controls/9/value", - json!("😀".repeat(2049)), - ), - ("/ui/toolWindows/0/native/controls/9/rows", json!(13)), - ( - "/ui/toolWindows/0/native/controls/10/value", - json!("unknown"), - ), - ( - "/ui/toolWindows/0/native/controls/10/options", - json!(vec![json!({"id":"option","label":"Option"}); 9]), - ), - ("/ui/toolWindows/0/native/controls/11/value", json!("2")), - ("/ui/toolWindows/0/native/controls/11/value", json!(9)), - ("/ui/toolWindows/0/native/controls/11/minimum", json!(10)), - ("/ui/toolWindows/0/native/controls/11/step", json!(0)), - ("/ui/toolWindows/0/native/buttons/0/id", json!("name")), - ( - "/ui/toolWindows/0/native/buttons/0/action", - json!("unknown"), - ), - ("/ui/toolWindows/0/native/buttons/0/width", json!(200)), - ("/ui/toolWindows/0/native/buttons/0/span", json!(13)), - ( - "/ui/toolWindows/0/native/buttons", - json!(vec![ - json!({"id":"button","label":"Button","action":"changed"}); - 17 - ]), - ), - ] { - let mut invalid = manifest.clone(); - *invalid.pointer_mut(pointer).unwrap() = value; - assert_eq!(validate(invalid)["status"], "rejected", "{pointer}"); - } - for (index, key, value) in [ - (0, "minimum", json!(0)), - (0, "rows", json!(2)), - (9, "onCommit", json!("changed")), - (11, "placeholder", json!("hint")), - ] { - let mut invalid = manifest.clone(); - invalid["ui"]["toolWindows"][0]["native"]["controls"][index][key] = value; - assert_eq!(validate(invalid)["status"], "rejected"); - } - let mut styled = manifest.clone(); - styled["ui"]["toolWindows"][0]["native"]["buttons"][0]["color"] = json!("red"); - assert_eq!(validate(styled)["status"], "rejected"); - let mut button_only = manifest; - button_only["ui"]["toolWindows"][0]["native"]["controls"] = json!([]); - assert_eq!(validate(button_only)["status"], "ok"); -} - /// The shared settings fixture: scoped, page-placed settings with an /// `immediate` one that only the server's `workspaceConfiguration` may read, /// project and immediate settings on a language page, a multi-select on a diff --git a/rust/crates/core/src/tests/mod.rs b/rust/crates/core/src/tests/mod.rs index 5e903742..7bad3c33 100644 --- a/rust/crates/core/src/tests/mod.rs +++ b/rust/crates/core/src/tests/mod.rs @@ -52,6 +52,7 @@ mod plugin_run_debug; mod plugin_run_types; mod plugin_settings_documents; mod plugin_source_settings; +mod plugin_views; mod process_memory; mod project; mod project_generators; diff --git a/rust/crates/core/src/tests/plugin_settings_documents.rs b/rust/crates/core/src/tests/plugin_settings_documents.rs index 916ea1ce..5ef8dd4a 100644 --- a/rust/crates/core/src/tests/plugin_settings_documents.rs +++ b/rust/crates/core/src/tests/plugin_settings_documents.rs @@ -532,6 +532,80 @@ fn settings_state_shows_packaged_translation_and_keeps_manifest_identity() { .find(|page| page["key"] == "language:elixir") .unwrap(); assert_eq!(section_titles(&elixir["sections"]), ["", "服务器"]); + // Translated keywords follow the manifest ones, so either language finds + // the page; a keyword both name appears once. + assert_eq!( + elixir["region"], + json!({"id": "otp", "keywords": ["OTP", "BEAM", "虚拟机"]}) + ); + assert_eq!(state["region"], Value::Null); + let english = english["pages"] + .as_array() + .unwrap() + .iter() + .find(|page| page["key"] == "language:elixir") + .unwrap(); + assert_eq!(english["region"]["keywords"], json!(["OTP", "BEAM"])); +} + +/// The settings catalog shows each contributor's region and, with an +/// interface language, translates headings and keywords the same way the +/// settings state does. +#[test] +fn settings_catalog_carries_regions_and_translates_them() { + let declared = manifest(); + let owner = json!({"pluginID": declared["id"], "version": declared["version"]}); + let contributor = |response: &Value| { + assert_eq!(response["data"]["status"], "ok", "{response}"); + response["data"]["pages"] + .as_array() + .unwrap() + .iter() + .find(|page| page["key"] == "language:elixir") + .unwrap()["contributors"][0] + .clone() + }; + let plain = contributor(&execute( + "plugins.settings.catalog", + json!({"plugins": [{"manifest": declared, "owner": owner, "enabled": true}]}), + )); + assert_eq!(section_titles(&plain["sections"]), ["", "Server"]); + assert_eq!( + plain["region"], + json!({"id": "otp", "keywords": ["OTP", "BEAM"]}) + ); + assert_eq!(plain["localization"], Value::Null); + + let text = contract_settings_file("l10n/zh-Hans.json"); + let translated = contributor(&execute( + "plugins.settings.catalog", + json!({"language": "zh-Hans", "plugins": [{ + "manifest": declared, "owner": owner, "enabled": true, + "localizations": {"l10n/zh-Hans.json": text} + }]}), + )); + assert_eq!(section_titles(&translated["sections"]), ["", "服务器"]); + assert_eq!( + translated["region"]["keywords"], + json!(["OTP", "BEAM", "虚拟机"]) + ); + assert_eq!(translated["localization"]["applied"], "l10n/zh-Hans.json"); + + let unread = contributor(&execute( + "plugins.settings.catalog", + json!({"language": "zh-Hans", "plugins": [{"manifest": declared, "owner": owner, "enabled": true}]}), + )); + assert_eq!(unread["localization"]["readRequired"], true); + + let refused = execute( + "plugins.settings.catalog", + json!({"language": "zh-Hans", "plugins": [{ + "manifest": declared, "owner": owner, "enabled": true, + "localizations": {"l10n/en.json": "{}"} + }]}), + ); + assert_eq!(refused["ok"], false, "{refused}"); + assert_eq!(refused["error"]["code"], "invalid_request"); } #[test] diff --git a/rust/crates/core/src/tests/plugin_views.rs b/rust/crates/core/src/tests/plugin_views.rs new file mode 100644 index 00000000..729025b1 --- /dev/null +++ b/rust/crates/core/src/tests/plugin_views.rs @@ -0,0 +1,167 @@ +//! Plugin views through Core's JSON entry point: the manifest declares where a +//! view is drawn, and `plugins.ui.applyResult` checks each backend result +//! against the shared fixture every host and SDK reads. + +use lithe_plugin_manifest::validate_command; +use serde_json::{json, Value}; + +const MANIFEST: &str = include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../../shared/plugins/contract/v1/fixtures/ui/view-panel.plugin.json" +)); +const RESULTS: &str = include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../../shared/plugins/contract/v1/fixtures/ui/view-results.json" +)); + +fn manifest() -> Value { + serde_json::from_str(MANIFEST).expect("view panel fixture") +} + +fn validate(manifest: Value) -> Value { + validate_command(json!({ "manifest": manifest })).expect("payload is well formed") +} + +fn apply_result(payload: Value) -> Value { + serde_json::from_str(&crate::execute_json( + &json!({"id": "view-test", "command": "plugins.ui.applyResult", "payload": payload}) + .to_string(), + )) + .expect("Core response") +} + +#[test] +fn shared_view_results_match_the_fixture() { + let fixture: Value = serde_json::from_str(RESULTS).expect("view results fixture"); + assert_eq!(fixture["manifest"], "view-panel.plugin.json"); + for case in fixture["cases"].as_array().expect("cases") { + let name = case["name"].as_str().expect("name"); + let mut payload = json!({ + "manifest": manifest(), + "surface": case["surface"], + "result": case["result"], + }); + if let Some(view) = case.get("view") { + payload["view"] = view.clone(); + } + let response = apply_result(payload); + assert_eq!(response["ok"], true, "{name}: {response}"); + let outcome = &response["data"]; + let expected = &case["expected"]; + assert_eq!(outcome["status"], expected["status"], "{name}: {outcome}"); + if expected["status"] == "ok" { + let view = match &expected["view"] { + Value::String(pointer) if pointer == "result.view" => &case["result"]["view"], + view => view, + }; + assert_eq!(&outcome["view"]["view"], view, "{name}"); + assert_eq!(outcome["view"]["changed"], expected["changed"], "{name}"); + } else { + assert_eq!(outcome["error"]["code"], "plugin.ui.invalidView", "{name}"); + assert_eq!( + outcome["error"]["field"], expected["field"], + "{name}: {outcome}" + ); + } + } +} + +#[test] +fn a_malformed_apply_request_is_a_core_failure() { + let response = apply_result(json!({"manifest": manifest(), "result": {}})); + assert_eq!(response["ok"], false, "{response}"); + assert_eq!(response["error"]["code"], "invalid_request"); +} + +/// The manifest side: a view needs a backend, `ui` needs a host that offers +/// it, and a window body is exactly one of text, web and view. +#[test] +fn view_declarations_need_a_backend_and_one_body() { + let manifest = manifest(); + let result = validate(manifest.clone()); + assert_eq!(result["status"], "ok", "{result}"); + assert_eq!( + result["plugin"]["ui"]["toolWindows"][0]["view"], + json!({"function": "explorer.draw"}) + ); + assert_eq!(result["plugin"]["settingRegions"][0]["id"], "overview"); + + let without_ui = validate_command(json!({ + "manifest": manifest, "hostCapabilities": {"backend": [0], "settings": [0]} + })) + .expect("payload is well formed"); + assert_eq!(without_ui["error"]["code"], "plugin.api.unsupported"); + assert_eq!(without_ui["error"]["field"], "requires.ui"); + + let mut mixed = manifest.clone(); + mixed["ui"]["toolWindows"][0]["text"] = json!("cannot mix body types"); + let rejected = validate(mixed); + assert_eq!( + rejected["error"]["field"], "ui.toolWindows[0]", + "{rejected}" + ); + + for (pointer, value) in [ + ("/ui/toolWindows/0/view/function", json!("Explorer Draw")), + ( + "/ui/toolWindows/0/view/source", + json!({"buildSystemID": "sample"}), + ), + ("/settingRegions/0/view/function", json!("")), + ("/settingRegions/0/keywords", json!(["graph", "Graph"])), + ("/settingRegions/0/id", json!("Overview")), + ] { + let mut invalid = manifest.clone(); + let (parent, key) = pointer.rsplit_once('/').expect("pointer"); + invalid + .pointer_mut(parent) + .and_then(Value::as_object_mut) + .expect(parent) + .insert(key.to_owned(), value); + assert_eq!(validate(invalid)["status"], "rejected", "{pointer}"); + } + + let mut without_backend = manifest.clone(); + without_backend + .as_object_mut() + .expect("manifest") + .remove("backend"); + without_backend["permissions"] = json!(["ui.contribute"]); + without_backend["requires"] = json!({"settings": 0, "ui": 0}); + let rejected = validate(without_backend); + assert_eq!(rejected["status"], "rejected", "{rejected}"); +} + +/// A region with only keywords needs no backend, and a region's view counts +/// as UI: it needs `ui.contribute` and the `ui` capability. +#[test] +fn keyword_regions_need_no_backend_and_view_regions_are_ui() { + let keywords_only = json!({ + "schemaVersion": 0, + "id": "dev.lithe.fixture.keywords", + "displayName": "Keywords", + "version": "1.0.0", + "pluginAPIVersion": 0, + "requires": {"languageServers": 0, "languages": 0, "settings": 0}, + "vendor": {"id": "org.example", "displayName": "Example", "signatureRequirement": "publisherPackage"}, + "permissions": ["languageServer.launch"], + "activationEvents": ["onLanguage:fictional"], + "languages": [{"id": "fictional", "displayName": "Fictional", "fileExtensions": ["fictional"]}], + "languageServers": [{"languageID": "fictional", + "launch": {"kind": "systemCommand", "commands": ["fictional-ls"]}}], + "settings": [{"id": "offline", "type": "boolean", "title": "Offline", "default": false}], + "settingRegions": [{"id": "search", "keywords": ["airplane mode"]}] + }); + let result = validate(keywords_only); + assert_eq!(result["status"], "ok", "{result}"); + + let mut region_only = manifest(); + region_only.as_object_mut().expect("manifest").remove("ui"); + region_only["activationEvents"] = json!([]); + assert_eq!(validate(region_only.clone())["status"], "ok"); + region_only["permissions"] = json!(["backend.launch"]); + assert_eq!(validate(region_only.clone())["status"], "rejected"); + region_only["permissions"] = json!(["backend.launch", "ui.contribute"]); + region_only["requires"] = json!({"backend": 0, "settings": 0}); + assert_eq!(validate(region_only)["status"], "rejected"); +} diff --git a/rust/crates/core/src/tests/toolchain_definitions.rs b/rust/crates/core/src/tests/toolchain_definitions.rs index 0dfd7eef..3ac583a9 100644 --- a/rust/crates/core/src/tests/toolchain_definitions.rs +++ b/rust/crates/core/src/tests/toolchain_definitions.rs @@ -69,9 +69,8 @@ fn tool_definitions_declare_settings_category_and_audience() { tagged["audience"] = json!("plugin"); let mut plugin = manifest("dev.lithe.fixture.compiler", tagged); // The fields are toolDefinitions 1, so a host that supports only 0 never installs it. - let rejected = validate_manifest_value(plugin.clone()) - .err() - .expect("version 0 refuses settings categories"); + let rejected = + validate_manifest_value(plugin.clone()).expect_err("version 0 refuses settings categories"); assert_eq!(rejected.field.as_deref(), Some("requires.toolDefinitions")); plugin["requires"]["toolDefinitions"] = json!(1); assert!(validate_manifest_value(plugin.clone()).is_ok()); diff --git a/rust/crates/plugin-manifest/Cargo.toml b/rust/crates/plugin-manifest/Cargo.toml index 8bad6e70..6f1bbf8d 100644 --- a/rust/crates/plugin-manifest/Cargo.toml +++ b/rust/crates/plugin-manifest/Cargo.toml @@ -15,7 +15,7 @@ lithe-plugin-grammar = { path = "../plugin-grammar" } lithe-plugin-keymap-import = { path = "../plugin-keymap-import" } lithe-plugin-language-servers = { path = "../plugin-language-servers" } lithe-plugin-model = { path = "../plugin-model" } -lithe-plugin-native-ui = { path = "../plugin-native-ui" } +lithe-plugin-ui = { path = "../plugin-ui" } lithe-plugin-output-links = { path = "../plugin-output-links" } lithe-plugin-rpc = { path = "../plugin-rpc" } lithe-project-generators = { path = "../project-generators" } diff --git a/rust/crates/plugin-manifest/src/lib.rs b/rust/crates/plugin-manifest/src/lib.rs index 66a287a7..14fe219f 100644 --- a/rust/crates/plugin-manifest/src/lib.rs +++ b/rust/crates/plugin-manifest/src/lib.rs @@ -18,13 +18,13 @@ use lithe_plugin_model::process::{ }; use lithe_plugin_model::settings::{ DeclaredSettings, ResolvedSetting, SettingAction, SettingDeclaration, SettingLayers, - MAX_SETTINGS, MAX_SETTING_ACTIONS, + SettingRegion, SettingsSurface, MAX_SETTINGS, MAX_SETTING_ACTIONS, }; use lithe_plugin_model::{ decode_payload, invalid, invalid_template, is_bare_command, is_environment_name, is_identifier, is_official_namespace, is_plugin_id, is_safe_relative_path, is_semantic_version, outcome, parse_template_with, regex_literal, sorted_unique, validate_minimum_version, PluginRejection, - TemplatePart, UIIcon, Validation, + TemplatePart, UIIcon, Validation, ViewDeclaration, }; use lithe_protocol::{CoreError, ErrorCode}; use serde::{Deserialize, Serialize}; @@ -46,6 +46,7 @@ mod settings_surfaces; mod templates; mod ui; mod validation; +mod views; pub use command_installers::{ command_installer_default_directory_command, command_installer_plan_command, @@ -64,5 +65,6 @@ pub use settings_surfaces::{ }; use templates::*; pub use validation::*; +pub use views::apply_result_command; pub use lithe_plugin_model::capabilities::SUPPORTED_PLUGIN_API_VERSIONS; diff --git a/rust/crates/plugin-manifest/src/manifest.rs b/rust/crates/plugin-manifest/src/manifest.rs index 6977e16e..0918fed7 100644 --- a/rust/crates/plugin-manifest/src/manifest.rs +++ b/rust/crates/plugin-manifest/src/manifest.rs @@ -50,6 +50,10 @@ pub struct DeclarativePluginManifest { /// Buttons on settings pages that invoke the plugin's functions. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub(crate) setting_actions: Vec, + /// Plugin-owned parts of settings pages: search keywords and an optional + /// view; see `lithe_plugin_model::settings::SettingRegion`. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub(crate) setting_regions: Vec, /// Project-level build tools the plugin describes. The shape and its /// validation live in `lithe_build`. #[serde(default, skip_serializing_if = "Vec::is_empty")] @@ -103,7 +107,8 @@ pub struct DeclarativePluginManifest { /// UI supplied by plugins. The host owns every window shell: docking, title, /// activity bar, order, visibility, layout and lifecycle. A window body is /// text, web content that the host loads from the package into a sandboxed -/// web view inside that shell, or host-rendered native content. +/// web view inside that shell, or a plugin view the backend draws and the +/// host renders natively (see `lithe_plugin_ui`). #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(crate) struct UIContributions { @@ -125,15 +130,15 @@ pub(crate) struct UIToolWindow { #[serde(default)] pub(crate) order: i32, /// Plain text shown in the window body; the host never interprets markup. - /// Exactly one of `text` and `web`. + /// Exactly one of `text`, `web` and `view`. #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) text: Option, /// The plugin's own page shown in the window body. #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) web: Option, - /// Host-rendered tree/list content. + /// Backend function that draws the window body as a plugin view. #[serde(default, skip_serializing_if = "Option::is_none")] - pub(crate) native: Option, + pub(crate) view: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) icon: Option, } diff --git a/rust/crates/plugin-manifest/src/permissions.rs b/rust/crates/plugin-manifest/src/permissions.rs index 9f915189..a57aa139 100644 --- a/rust/crates/plugin-manifest/src/permissions.rs +++ b/rust/crates/plugin-manifest/src/permissions.rs @@ -105,6 +105,14 @@ impl DeclarativePluginManifest { required.insert(PERMISSION_UI_WEB); } } + // A settings region that draws a view contributes UI like a window. + if self + .setting_regions + .iter() + .any(|region| region.view.is_some()) + { + required.insert(PERMISSION_UI); + } // A provider process of its own is a server process like a language // server, so it needs the same consent. if !self.language_servers.is_empty() diff --git a/rust/crates/plugin-manifest/src/settings.rs b/rust/crates/plugin-manifest/src/settings.rs index b8f20258..7fa07057 100644 --- a/rust/crates/plugin-manifest/src/settings.rs +++ b/rust/crates/plugin-manifest/src/settings.rs @@ -9,6 +9,7 @@ impl DeclarativePluginManifest { /// launch templates may refer to. pub(crate) fn validate_settings(&mut self) -> Validation { self.validate_setting_actions()?; + self.validate_setting_regions()?; if self.settings.is_empty() { return Ok(DeclaredSettings::default()); } @@ -88,6 +89,36 @@ impl DeclarativePluginManifest { .sort_by(|left, right| left.id.cmp(&right.id)); Ok(()) } + + /// Checks the plugin-owned page regions and sorts them by ID. A region + /// that draws a view needs the backend that draws it. + fn validate_setting_regions(&mut self) -> Validation<()> { + lithe_plugin_model::settings::validate_regions(&self.setting_regions, "settingRegions")?; + if self.backend.is_none() { + if let Some(index) = self + .setting_regions + .iter() + .position(|region| region.view.is_some()) + { + return Err(invalid( + format!("settingRegions[{index}].view"), + "A view is drawn by the plugin backend; declare one.", + )); + } + } + self.setting_regions + .sort_by(|left, right| left.id.cmp(&right.id)); + Ok(()) + } + + /// The plugin's whole settings contribution. + pub(crate) fn settings_surface(&self) -> SettingsSurface<'_> { + SettingsSurface { + settings: &self.settings, + actions: &self.setting_actions, + regions: &self.setting_regions, + } + } } impl DeclarativePluginManifest { @@ -193,13 +224,13 @@ pub fn settings_state_command(payload: Value) -> Result { "The manifest does not match the captured installed package identity.", )); } - let (translation, report) = localization.as_ref().map_or((None, Value::Null), |request| { - request.select(&manifest.settings, &manifest.setting_actions) - }); + let surface = manifest.settings_surface(); + let (translation, report) = localization + .as_ref() + .map_or((None, Value::Null), |request| request.select(surface)); lithe_plugin_model::settings::document_state( &manifest.id, - &manifest.settings, - &manifest.setting_actions, + surface, payload.global_document.as_deref(), payload.project_document.as_deref(), translation.as_ref(), diff --git a/rust/crates/plugin-manifest/src/settings_surfaces.rs b/rust/crates/plugin-manifest/src/settings_surfaces.rs index c8b12e21..c5f21020 100644 --- a/rust/crates/plugin-manifest/src/settings_surfaces.rs +++ b/rust/crates/plugin-manifest/src/settings_surfaces.rs @@ -3,8 +3,9 @@ //! these commands never discover files, subscribe windows or launch plugins. use crate::{validate_manifest_value, SettingsOwner}; +use lithe_plugin_model::settings::LocalizationRequest; use lithe_plugin_model::{decode_payload, outcome, PluginRejection}; -use lithe_protocol::CoreError; +use lithe_protocol::{CoreError, ErrorCode}; use serde::Deserialize; use serde_json::{json, Value}; use std::collections::{BTreeMap, BTreeSet}; @@ -20,12 +21,20 @@ struct Contribution { manifest: Value, owner: SettingsOwner, enabled: bool, + /// Translation files the native adapter found among the candidates for + /// the request's `language`, by package-relative path. + #[serde(default)] + localizations: Option>, } #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct CatalogRequest { plugins: Vec, + /// Interface language whose plugin translations translate section + /// headings and add region keywords, such as `zh-Hans`. + #[serde(default)] + language: Option, } fn rejected(field: &str) -> PluginRejection { @@ -38,15 +47,31 @@ fn rejected(field: &str) -> PluginRejection { /// Builds a deterministic catalog from complete validated installed manifests. /// Disabled packages cannot contribute pages or rename another plugin's page. +/// Each contributor carries its sections and, when it placed one there, its +/// region: search keywords and the view it draws on the page. pub fn settings_catalog_command(payload: Value) -> Result { - let request: CatalogRequest = decode_payload(payload, "plugins.settings.catalog")?; + const COMMAND: &str = "plugins.settings.catalog"; + let request: CatalogRequest = decode_payload(payload, COMMAND)?; + let mut requests = Vec::with_capacity(request.plugins.len()); + for entry in &request.plugins { + requests.push( + LocalizationRequest::new(request.language.as_deref(), entry.localizations.as_ref()) + .map_err(|reason| { + CoreError::new( + ErrorCode::InvalidRequest, + format!("Invalid {COMMAND} payload"), + ) + .with_details(reason) + })?, + ); + } Ok(outcome((|| { if request.plugins.len() > MAX_PLUGINS { return Err(rejected("plugins")); } let mut owners = BTreeSet::new(); let mut manifests = BTreeMap::new(); - for entry in request.plugins { + for (entry, localization) in request.plugins.iter().zip(&requests) { let manifest = validate_manifest_value(entry.manifest.clone())?; if manifest.id != entry.owner.plugin_id || manifest.version != entry.owner.version { return Err(PluginRejection::at( @@ -59,12 +84,20 @@ pub fn settings_catalog_command(payload: Value) -> Result { return Err(rejected("plugins")); } if entry.enabled { - manifests.insert(manifest.id.clone(), (manifest, entry.manifest)); + let (translation, report) = localization + .as_ref() + .map_or((None, Value::Null), |request| { + request.select(manifest.settings_surface()) + }); + manifests.insert( + manifest.id.clone(), + (manifest, &entry.manifest, translation, report), + ); } } let mut titles = BTreeMap::new(); // Plugin ID order resolves competing display names deterministically. - for (_, raw) in manifests.values() { + for (_, raw, _, _) in manifests.values() { for (field, kind) in [("languages", "language"), ("buildSystems", "buildSystem")] { if let Some(entries) = raw[field].as_array() { for entry in entries { @@ -80,20 +113,29 @@ pub fn settings_catalog_command(payload: Value) -> Result { } } let mut pages = BTreeMap::::new(); - for (id, (manifest, _)) in manifests { + for (id, (manifest, _, translation, report)) in manifests { for page in lithe_plugin_model::settings::page_sections( - &manifest.settings, - &manifest.setting_actions, - None, + manifest.settings_surface(), + translation.as_ref(), ) { let key = page["key"].as_str().unwrap_or_default().to_owned(); let target = pages.entry(key.clone()).or_insert_with(|| json!({ "key":key,"kind":page["kind"],"id":page["id"], "title":titles.get(&key).or_else(|| titles.get(&format!("language:{}",page["id"].as_str().unwrap_or_default()))).or_else(|| titles.get(&format!("buildSystem:{}",page["id"].as_str().unwrap_or_default()))).cloned().unwrap_or_else(|| page["id"].as_str().unwrap_or_default().to_owned()),"contributors":[] })); - target["contributors"].as_array_mut().expect("catalog array").push(json!({ + let mut contributor = json!({ "pluginID":id,"version":manifest.version,"title":manifest.display_name,"sections":page["sections"] - })); + }); + if let Some(region) = page.get("region") { + contributor["region"] = region.clone(); + } + if !report.is_null() { + contributor["localization"] = report.clone(); + } + target["contributors"] + .as_array_mut() + .expect("catalog array") + .push(contributor); } } if pages.len() > MAX_PAGES { diff --git a/rust/crates/plugin-manifest/src/ui.rs b/rust/crates/plugin-manifest/src/ui.rs index 8672278e..b5b9fc04 100644 --- a/rust/crates/plugin-manifest/src/ui.rs +++ b/rust/crates/plugin-manifest/src/ui.rs @@ -1,4 +1,5 @@ -//! Validation of UI contributions: tool windows, web content, docks and commands. +//! Validation of UI contributions: tool windows, web content, plugin views, +//! docks and commands. use super::*; @@ -24,23 +25,7 @@ impl DeclarativePluginManifest { if let Some(icon) = &window.icon { icon.validate()?; } - validate_window_body(window, index)?; - if let Some(source) = window - .native - .as_ref() - .and_then(|native| native.source.as_ref()) - { - if !self - .build_systems - .iter() - .any(|system| system.id == source.build_system_id) - { - return Err(invalid( - "ui.toolWindows.native.source", - "The native source must belong to this plugin's build systems.", - )); - } - } + validate_window_body(window, index, self.backend.is_some())?; if !is_plugin_id(&window.id) || !window.id.starts_with(&prefix) || window.title.trim().is_empty() @@ -105,28 +90,27 @@ impl DeclarativePluginManifest { } } -/// A window body is literal text, one package HTML page, or host-rendered -/// native content. -fn validate_window_body(window: &UIToolWindow, index: usize) -> Validation<()> { +/// A window body is literal text, one package HTML page, or a plugin view +/// that the plugin's backend draws. +fn validate_window_body(window: &UIToolWindow, index: usize, has_backend: bool) -> Validation<()> { let field = format!("ui.toolWindows[{index}]"); - if let Some(native) = &window.native { - if window.text.is_some() || window.web.is_some() { - return Err(invalid( - &field, - "Native content cannot coexist with text or web.", - )); - } - return native - .validate() - .map_err(|message| invalid(&field, message)); - } - match (&window.text, &window.web) { - (Some(text), None) if text.len() <= 65536 => Ok(()), - (Some(_), None) => Err(invalid( + match (&window.text, &window.web, &window.view) { + (Some(text), None, None) if text.len() <= 65536 => Ok(()), + (Some(_), None, None) => Err(invalid( format!("{field}.text"), "The window text is too long.", )), - (None, Some(web)) => { + (None, None, Some(view)) => { + view.validate(&format!("{field}.view"))?; + if !has_backend { + return Err(invalid( + format!("{field}.view"), + "A view is drawn by the plugin backend; declare one.", + )); + } + Ok(()) + } + (None, Some(web), None) => { let entry = &web.entry; let valid = is_safe_relative_path(entry) && entry.len() <= 256 @@ -145,7 +129,7 @@ fn validate_window_body(window: &UIToolWindow, index: usize) -> Validation<()> { } _ => Err(invalid( field, - "A tool window shows exactly one of text and web content.", + "A tool window shows exactly one of text, web and view.", )), } } diff --git a/rust/crates/plugin-manifest/src/validation.rs b/rust/crates/plugin-manifest/src/validation.rs index 99f01719..fcd3bddd 100644 --- a/rust/crates/plugin-manifest/src/validation.rs +++ b/rust/crates/plugin-manifest/src/validation.rs @@ -280,10 +280,15 @@ impl DeclarativePluginManifest { if let Some(backend) = &self.backend { backend.validate(&lithe_plugin_backend::DeclarationContext { declared_settings: &declared_settings, - has_web_window: self - .ui - .as_ref() - .is_some_and(|ui| ui.tool_windows.iter().any(|window| window.web.is_some())), + // Web pages and plugin views both call the backend once shown. + has_web_window: self.ui.as_ref().is_some_and(|ui| { + ui.tool_windows + .iter() + .any(|window| window.web.is_some() || window.view.is_some()) + }) || self + .setting_regions + .iter() + .any(|region| region.view.is_some()), has_command: self.ui.as_ref().is_some_and(|ui| !ui.commands.is_empty()), activates_on_workspace_open: self .activation_events @@ -339,7 +344,9 @@ impl DeclarativePluginManifest { ), ( capabilities::SETTINGS, - !self.settings.is_empty() || !self.setting_actions.is_empty(), + !self.settings.is_empty() + || !self.setting_actions.is_empty() + || !self.setting_regions.is_empty(), ), ( capabilities::SOURCE_SETTINGS, @@ -347,7 +354,14 @@ impl DeclarativePluginManifest { .iter() .any(|action| action.source_editor.is_some()), ), - (capabilities::UI, self.ui.is_some()), + ( + capabilities::UI, + self.ui.is_some() + || self + .setting_regions + .iter() + .any(|region| region.view.is_some()), + ), (capabilities::BUILD_SYSTEMS, !self.build_systems.is_empty()), ( capabilities::PROJECT_GENERATORS, diff --git a/rust/crates/plugin-manifest/src/views.rs b/rust/crates/plugin-manifest/src/views.rs new file mode 100644 index 00000000..404c9e3a --- /dev/null +++ b/rust/crates/plugin-manifest/src/views.rs @@ -0,0 +1,223 @@ +//! `plugins.ui.applyResult`: checks what a plugin backend returned for one +//! of its views and gives the host the whole view to draw. +//! +//! A view lives in a tool window body or a settings region the manifest +//! declares. The backend answers each view event with a whole view, patches +//! against the view the host drew last, or nothing. Core checks the result +//! against the surface's vocabulary and the plugin's declared settings, +//! actions and tools, so both products draw the same nodes and refuse the +//! same results; the host only renders. + +use crate::{validate_manifest_value, DeclarativePluginManifest}; +use lithe_plugin_model::{decode_payload, outcome, PluginRejection, Validation}; +use lithe_plugin_ui::{Context, Surface, INVALID_VIEW}; +use lithe_protocol::CoreError; +use serde::Deserialize; +use serde_json::{json, Value}; +use std::collections::BTreeSet; + +/// The declared place a view is drawn in. +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct ViewSurface { + /// A tool window whose body is a view. + #[serde(default, rename = "toolWindowID")] + tool_window_id: Option, + /// A settings region that draws a view. + #[serde(default, rename = "settingRegionID")] + setting_region_id: Option, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct ApplyResultPayload { + manifest: Value, + surface: ViewSurface, + /// The view the host drew last; absent before the first result. + #[serde(default)] + view: Option, + /// What the backend returned: `{view}`, `{patches}` or `{}`. + result: Value, +} + +/// `plugins.ui.applyResult`: the checked whole view the host draws next and +/// whether it differs from the one it drew. A refused result is a rejected +/// outcome with code `plugin.ui.invalidView` and the JSON path of the first +/// problem; the host keeps drawing the previous view. +pub fn apply_result_command(payload: Value) -> Result { + let payload: ApplyResultPayload = decode_payload(payload, "plugins.ui.applyResult")?; + Ok(outcome(validate_manifest_value(payload.manifest).and_then( + |manifest| { + let surface = view_surface(&manifest, &payload.surface)?; + let tools = manifest.view_tools(); + let context = Context { + surface, + settings: &manifest.settings, + actions: &manifest.setting_actions, + tools: &tools, + }; + let (view, changed) = + lithe_plugin_ui::apply(&context, payload.view.as_ref(), &payload.result)?; + Ok(("view", json!({"view": view, "changed": changed}))) + }, + ))) +} + +/// The surface the request names, which must be a declared place that draws +/// a view. +fn view_surface( + manifest: &DeclarativePluginManifest, + surface: &ViewSurface, +) -> Validation { + match (&surface.tool_window_id, &surface.setting_region_id) { + (Some(id), None) => manifest + .ui + .as_ref() + .and_then(|ui| ui.tool_windows.iter().find(|window| &window.id == id)) + .filter(|window| window.view.is_some()) + .map(|_| Surface::ToolWindow) + .ok_or_else(|| { + PluginRejection::at( + INVALID_VIEW, + "surface.toolWindowID", + "The plugin declares no tool window with this ID whose body is a view.", + ) + }), + (None, Some(id)) => manifest + .setting_regions + .iter() + .find(|region| ®ion.id == id) + .filter(|region| region.view.is_some()) + .map(|_| Surface::Settings) + .ok_or_else(|| { + PluginRejection::at( + INVALID_VIEW, + "surface.settingRegionID", + "The plugin declares no settings region with this ID that draws a view.", + ) + }), + _ => Err(PluginRejection::at( + INVALID_VIEW, + "surface", + "Name exactly one of toolWindowID and settingRegionID.", + )), + } +} + +impl DeclarativePluginManifest { + /// Tools a view may show as a tool row: those the plugin defines and + /// those it requires. + fn view_tools(&self) -> BTreeSet { + self.tool_definitions + .iter() + .filter_map(|definition| definition["id"].as_str()) + .map(str::to_owned) + .chain(self.requires_tools.iter().cloned()) + .collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn manifest() -> Value { + json!({ + "schemaVersion": 0, + "id": "io.github.example.views", + "displayName": "Views", + "version": "1.0.0", + "pluginAPIVersion": 0, + "requires": {"backend": 0, "settings": 0, "ui": 0}, + "vendor": {"id": "org.example", "displayName": "Example", "signatureRequirement": "publisherPackage"}, + "permissions": ["backend.launch", "ui.contribute"], + "activationEvents": ["onView:io.github.example.views.panel", "onView:io.github.example.views.text"], + "languages": [], + "requiresTools": ["node"], + "settings": [ + {"id": "mode", "type": "enum", "title": "Mode", "default": "fast", + "options": [{"value": "fast", "title": "Fast"}, {"value": "safe", "title": "Safe"}]} + ], + "settingRegions": [ + {"id": "overview", "keywords": ["overview"], "view": {"function": "settings.overview"}}, + {"id": "search", "page": {"buildSystemID": "example"}, "keywords": ["example"]} + ], + "ui": {"toolWindows": [ + {"id": "io.github.example.views.panel", "title": "Panel", "placement": "right", + "view": {"function": "panel.draw"}}, + {"id": "io.github.example.views.text", "title": "Text", "placement": "bottom", "text": "Hello"} + ]}, + "backend": {"launch": {"kind": "packaged", "path": "bin/backend"}} + }) + } + + fn apply(surface: Value, view: Option, result: Value) -> Value { + let mut payload = json!({"manifest": manifest(), "surface": surface, "result": result}); + if let Some(view) = view { + payload["view"] = view; + } + apply_result_command(payload).expect("outcome") + } + + #[test] + fn a_declared_view_surface_returns_the_checked_view() { + let drawn = json!([{"type": "label", "id": "title", "text": "Hello"}]); + let outcome = apply( + json!({"toolWindowID": "io.github.example.views.panel"}), + None, + json!({"view": drawn}), + ); + assert_eq!(outcome["status"], "ok", "{outcome}"); + assert_eq!(outcome["view"], json!({"view": drawn, "changed": true})); + + let outcome = apply( + json!({"toolWindowID": "io.github.example.views.panel"}), + Some(drawn.clone()), + json!({"patches": [{"op": "set", "id": "title", "fields": {"text": "Bye"}}]}), + ); + assert_eq!(outcome["view"]["view"][0]["text"], "Bye", "{outcome}"); + assert_eq!(outcome["view"]["changed"], true); + } + + #[test] + fn settings_regions_bind_declared_settings() { + let outcome = apply( + json!({"settingRegionID": "overview"}), + None, + json!({"view": [{"type": "segmented", "id": "mode", "setting": "mode"}]}), + ); + assert_eq!(outcome["status"], "ok", "{outcome}"); + let outcome = apply( + json!({"settingRegionID": "overview"}), + None, + json!({"view": [{"type": "toggle", "id": "missing", "setting": "missing"}]}), + ); + assert_eq!(outcome["status"], "rejected", "{outcome}"); + assert_eq!(outcome["error"]["code"], INVALID_VIEW); + } + + #[test] + fn only_declared_view_surfaces_accept_results() { + for surface in [ + json!({"toolWindowID": "io.github.example.views.text"}), + json!({"toolWindowID": "io.github.example.views.unknown"}), + json!({"settingRegionID": "search"}), + json!({}), + json!({"toolWindowID": "io.github.example.views.panel", "settingRegionID": "overview"}), + ] { + let outcome = apply(surface.clone(), None, json!({"view": []})); + assert_eq!(outcome["status"], "rejected", "{surface}: {outcome}"); + assert_eq!(outcome["error"]["code"], INVALID_VIEW, "{surface}"); + } + } + + #[test] + fn a_malformed_envelope_is_an_invalid_request() { + let error = apply_result_command(json!({"manifest": manifest(), "result": {}})) + .expect_err("surface is required"); + assert!(matches!( + error.code, + lithe_protocol::ErrorCode::InvalidRequest + )); + } +} diff --git a/rust/crates/plugin-model/src/capabilities.rs b/rust/crates/plugin-model/src/capabilities.rs index db4ce508..37708b2d 100644 --- a/rust/crates/plugin-model/src/capabilities.rs +++ b/rust/crates/plugin-model/src/capabilities.rs @@ -60,8 +60,8 @@ pub const SETTINGS: &str = "settings"; /// Source-backed workspace editors returned by settings actions, including /// compiler pages and guarded native staging receipts. pub const SOURCE_SETTINGS: &str = "sourceSettings"; -/// `ui`: tool windows with text, web, or host-rendered native content, and -/// commands. +/// `ui`: tool windows with text, web, or plugin view content, plugin views in +/// settings regions, and commands. pub const UI: &str = "ui"; /// Declarative build detection, models, and command plans. pub const BUILD_SYSTEMS: &str = "buildSystems"; diff --git a/rust/crates/plugin-model/src/lib.rs b/rust/crates/plugin-model/src/lib.rs index 059e393e..b8586e7a 100644 --- a/rust/crates/plugin-model/src/lib.rs +++ b/rust/crates/plugin-model/src/lib.rs @@ -5,8 +5,8 @@ //! section, but they refuse content the same way ([`PluginRejection`]), check //! the same identifier alphabets ([`is_plugin_id`], [`is_safe_relative_path`]), //! parse the same `${...}` templates ([`parse_template_with`]), and declare -//! the same [`settings`], [`executables`] and server [`process`]es, and are -//! gated by the same [`capabilities`]. This crate holds that vocabulary so +//! the same [`settings`], [`executables`], server [`process`]es and plugin +//! views ([`ViewDeclaration`]), and are gated by the same [`capabilities`]. This crate holds that vocabulary so //! each domain can live in its own crate; assembling a whole manifest stays //! with the plugin host in `lithe-core`. //! @@ -24,6 +24,7 @@ mod rejection; pub mod settings; mod template; mod version; +mod view; pub use icon::UIIcon; pub use manifest::PluginManifest; @@ -40,3 +41,4 @@ pub use template::{parse_template_with, regex_literal, TemplatePart}; pub use version::{ validate_minimum_version, version_components, PluginVersion, PluginVersionRequirement, }; +pub use view::ViewDeclaration; diff --git a/rust/crates/plugin-model/src/settings.rs b/rust/crates/plugin-model/src/settings.rs index eec36d0a..01c36671 100644 --- a/rust/crates/plugin-model/src/settings.rs +++ b/rust/crates/plugin-model/src/settings.rs @@ -23,6 +23,10 @@ pub use localization::{ }; mod pages; pub use pages::page_sections; +mod regions; +pub use regions::{ + validate_regions, SettingRegion, MAX_KEYWORD_CHARS, MAX_REGION_KEYWORDS, MAX_SETTING_REGIONS, +}; pub mod sources; use crate::rejection::{invalid, PluginRejection, Validation}; @@ -34,6 +38,19 @@ use std::collections::{BTreeMap, BTreeSet}; /// Most settings one plugin may declare, so its pages stay pages. pub const MAX_SETTINGS: usize = 32; +/// Everything one plugin contributes to settings pages: the stored options, +/// the buttons, and the plugin-owned regions. Projections and translations +/// read the three together so a page appears for whichever one names it. +#[derive(Debug, Clone, Copy)] +pub struct SettingsSurface<'a> { + /// Declared options. + pub settings: &'a [SettingDeclaration], + /// Declared buttons. + pub actions: &'a [SettingAction], + /// Declared regions. + pub regions: &'a [SettingRegion], +} + /// A whole number within a declared range. const SETTING_INTEGER: &str = "integer"; /// One of a declared list of values. @@ -517,6 +534,17 @@ impl SettingDeclaration { self.options.iter().any(|option| option.value == value) } + /// The declared kind: `integer`, `enum`, `boolean`, `multiSelect`, + /// `text`, `file` or `directory`. + pub fn kind(&self) -> &str { + &self.kind + } + + /// Option values of an enum or multiSelect setting, in display order. + pub fn option_values(&self) -> impl Iterator { + self.options.iter().map(|option| option.value.as_str()) + } + /// Checks the declaration against the `settings` capability contract. pub fn validate(&self, field: &str) -> Validation<()> { if matches!(self.page, Some(SettingPage::Compiler(_))) { diff --git a/rust/crates/plugin-model/src/settings/documents.rs b/rust/crates/plugin-model/src/settings/documents.rs index 96277019..c55fddf5 100644 --- a/rust/crates/plugin-model/src/settings/documents.rs +++ b/rust/crates/plugin-model/src/settings/documents.rs @@ -5,8 +5,8 @@ use super::localization::shown_section; use super::{ - resolve, SettingAction, SettingDeclaration, SettingEffect, SettingLayers, SettingScope, - SettingsLocalization, + resolve, SettingDeclaration, SettingEffect, SettingLayers, SettingScope, SettingsLocalization, + SettingsSurface, }; use crate::names::is_plugin_id; use crate::rejection::{PluginRejection, Validation}; @@ -69,15 +69,17 @@ fn read_document(content: Option<&str>, field: &str) -> Validation { /// Projects declared rows and raw launch layers from complete native documents. /// Unknown settings remain in storage but are not sent across the UI boundary. /// `localization` translates the text rows, actions and section headings show; -/// IDs, values, grouping and order stay those of the manifest. +/// IDs, values, grouping and order stay those of the manifest. The state also +/// carries the region the plugin placed on its own Settings tab, if any. pub fn document_state( plugin: &str, - declarations: &[SettingDeclaration], - actions: &[SettingAction], + surface: SettingsSurface<'_>, global: Option<&str>, project: Option<&str>, localization: Option<&SettingsLocalization>, ) -> Validation { + let declarations = surface.settings; + let actions = surface.actions; let global = read_document(global, "globalDocument")?; let project = read_document(project, "projectDocument")?; let empty = BTreeMap::new(); @@ -170,13 +172,15 @@ pub fn document_state( ) }) .collect(); - Ok( - json!({"pluginID":plugin, "rows":rows, "actions":shown_actions, "sections":sections, - "pages":super::page_sections(declarations, actions, localization), + let mut state = json!({"pluginID":plugin, "rows":rows, "actions":shown_actions, "sections":sections, + "pages":super::page_sections(surface, localization), "editors":{"global":global_editor,"project":project_editor}, "settings":declared_values(global), "projectSettings":declared_values(project), - "storage":{"globalRelativePath":"plugin-settings.json", "projectRelativePath":".lithe/plugin-settings.json", "maximumBytes":MAX_DOCUMENT_BYTES, "readRequired":!declarations.is_empty()}}), - ) + "storage":{"globalRelativePath":"plugin-settings.json", "projectRelativePath":".lithe/plugin-settings.json", "maximumBytes":MAX_DOCUMENT_BYTES, "readRequired":!declarations.is_empty()}}); + if let Some(region) = super::pages::shown_region(surface, None, localization) { + state["region"] = region; + } + Ok(state) } /// Widget input for an already validated resolved value or reset value. diff --git a/rust/crates/plugin-model/src/settings/localization.rs b/rust/crates/plugin-model/src/settings/localization.rs index 8a6efc5d..dea3ed22 100644 --- a/rust/crates/plugin-model/src/settings/localization.rs +++ b/rust/crates/plugin-model/src/settings/localization.rs @@ -9,9 +9,10 @@ //! //! Note: the decision is recorded in .agents/notes/implemented/architecture/2026-10-21-plugin-settings-surfaces.md +use super::regions::check_keywords; use super::{ - check_label, SettingAction, SettingDeclaration, MAX_SETTING_TEXT, SETTING_ENUM, - SETTING_MULTI_SELECT, + check_label, SettingAction, SettingDeclaration, SettingsSurface, MAX_SETTING_TEXT, + SETTING_ENUM, SETTING_MULTI_SELECT, }; use crate::names::is_language_tag; use crate::rejection::PluginRejection; @@ -41,6 +42,16 @@ struct LocalizationFile { sections: UniqueMap, #[serde(default)] setting_actions: UniqueMap, + #[serde(default)] + setting_regions: UniqueMap, +} + +/// Search keywords a translation adds to one region; the manifest keywords +/// stay, so a page is found in either language. +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RegionText { + keywords: Vec, } /// Translated text of one setting, by the manifest field it replaces. @@ -85,6 +96,7 @@ pub struct SettingsLocalization { settings: BTreeMap, sections: BTreeMap, actions: BTreeMap, Option)>, + regions: BTreeMap>, } #[derive(Debug, Default)] @@ -138,6 +150,11 @@ impl SettingsLocalization { .cloned() .unwrap_or_else(|| title.to_owned()) } + + /// Keywords the translation adds to the region `id`. + pub fn region_keywords(&self, id: &str) -> Option<&Vec> { + self.regions.get(id) + } } /// The heading shown for a section grouped under the manifest heading `title`. @@ -217,12 +234,8 @@ impl<'a> LocalizationRequest<'a> { /// file wins; every invalid file is reported with its rejection and never /// applied in part. Before the adapter has read the candidates the report /// asks it to, and nothing is translated. - pub fn select( - &self, - declarations: &[SettingDeclaration], - actions: &[SettingAction], - ) -> (Option, Value) { - self.select_with(|text| decode(text, declarations, actions)) + pub fn select(&self, surface: SettingsSurface<'_>) -> (Option, Value) { + self.select_with(|text| decode(text, surface)) } /// [`Self::select`] for another surface: `decode` checks one file @@ -297,11 +310,23 @@ pub fn parse_localization_file Deserialize<'de>>( /// translates. fn decode( text: &str, - declarations: &[SettingDeclaration], - actions: &[SettingAction], + surface: SettingsSurface<'_>, ) -> Result { + let declarations = surface.settings; + let actions = surface.actions; let file: LocalizationFile = parse_localization_file(text, INVALID_LOCALIZATION)?; let mut localization = SettingsLocalization::default(); + for (id, text) in file.setting_regions.0 { + let field = format!("settingRegions.{id}.keywords"); + if !surface.regions.iter().any(|region| region.id == id) { + return Err(rejection( + format!("settingRegions.{id}"), + "The plugin declares no region with this ID.", + )); + } + check_keywords(&text.keywords).map_err(|message| rejection(&field, message))?; + localization.regions.insert(id, text.keywords); + } for (id, text) in file.settings.0 { let field = format!("settings.{id}"); let declaration = declarations @@ -467,6 +492,10 @@ mod tests { .expect("actions") } + fn regions() -> Vec { + serde_json::from_value(json!([{"id":"overview","keywords":["PLT"]}])).expect("regions") + } + fn select_text( language: Option<&str>, files: Option<&BTreeMap>, @@ -474,7 +503,11 @@ mod tests { LocalizationRequest::new(language, files) .expect("well-formed request") .map_or((None, Value::Null), |request| { - request.select(&declarations(), &actions()) + request.select(SettingsSurface { + settings: &declarations(), + actions: &actions(), + regions: ®ions(), + }) }) } diff --git a/rust/crates/plugin-model/src/settings/pages.rs b/rust/crates/plugin-model/src/settings/pages.rs index 7be150d7..8877373c 100644 --- a/rust/crates/plugin-model/src/settings/pages.rs +++ b/rust/crates/plugin-model/src/settings/pages.rs @@ -1,23 +1,23 @@ //! Placement projections retain indices into the complete owner-bound editor. -use super::{SettingAction, SettingDeclaration, SettingPage, SettingsLocalization}; +use super::{SettingPage, SettingsLocalization, SettingsSurface}; use serde_json::{json, Value}; use std::collections::BTreeMap; /// Row and action indices placed in one section. type SectionIndices = (Vec, Vec); -/// Groups only explicitly placed rows and actions. Unplaced declarations remain -/// on the plugin's own page; an action alone is sufficient to create a page. -/// Sections are grouped and ordered by their manifest heading; `localization` -/// changes only the heading shown. +/// Groups only explicitly placed rows, actions and regions. Unplaced +/// declarations remain on the plugin's own page; an action or a region alone +/// is sufficient to create a page. Sections are grouped and ordered by their +/// manifest heading; `localization` changes only the heading and adds region +/// keywords. pub fn page_sections( - rows: &[SettingDeclaration], - actions: &[SettingAction], + surface: SettingsSurface<'_>, localization: Option<&SettingsLocalization>, ) -> Vec { let mut pages: BTreeMap> = BTreeMap::new(); - for (index, row) in rows.iter().enumerate() { + for (index, row) in surface.settings.iter().enumerate() { if let Some(page) = &row.page { pages .entry(page.clone()) @@ -28,7 +28,7 @@ pub fn page_sections( .push(index); } } - for (index, action) in actions.iter().enumerate() { + for (index, action) in surface.actions.iter().enumerate() { if let Some(page) = &action.page { pages .entry(page.clone()) @@ -39,6 +39,11 @@ pub fn page_sections( .push(index); } } + for region in surface.regions { + if let Some(page) = ®ion.page { + pages.entry(page.clone()).or_default(); + } + } pages.into_iter().map(|(page, sections)| { let (kind, id) = match &page { SettingPage::Language(id) => ("language", id), @@ -48,6 +53,24 @@ pub fn page_sections( let sections: Vec<_> = sections.into_iter().map(|(title, (rows, actions))| { json!({"title":super::localization::shown_section(localization, title),"rows":rows,"actions":actions}) }).collect(); - json!({"key":format!("{kind}:{id}"),"kind":kind,"id":id,"sections":sections}) + let mut shown = json!({"key":format!("{kind}:{id}"),"kind":kind,"id":id,"sections":sections}); + if let Some(region) = shown_region(surface, Some(&page), localization) { + shown["region"] = region; + } + shown }).collect() } + +/// The region the plugin placed on `page` (`None` is its own Settings tab), +/// with translated keywords appended. +pub(super) fn shown_region( + surface: SettingsSurface<'_>, + page: Option<&SettingPage>, + localization: Option<&SettingsLocalization>, +) -> Option { + surface + .regions + .iter() + .find(|region| region.page.as_ref() == page) + .map(|region| region.shown(localization.and_then(|l| l.region_keywords(®ion.id)))) +} diff --git a/rust/crates/plugin-model/src/settings/regions.rs b/rust/crates/plugin-model/src/settings/regions.rs new file mode 100644 index 00000000..3ba5ab37 --- /dev/null +++ b/rust/crates/plugin-model/src/settings/regions.rs @@ -0,0 +1,205 @@ +//! Plugin-owned regions of a settings page: search keywords for content the +//! host cannot read, and an optional view the plugin draws there. +//! +//! A region sits on one page: the plugin's own Settings tab when it names no +//! page, or the language, build-system or compiler page it names. The host +//! draws the declared rows and actions as before; a region adds the plugin's +//! view between the page header and those rows, and its keywords make the page +//! findable by words that appear only inside the view (canvas text is never +//! indexed). A region never stores values: controls it binds edit the declared +//! settings through the host's ordinary draft and Apply. +//! +//! Note: the decision is recorded in .agents/notes/proposed/architecture/2026-11-12-plugin-authored-settings-content.md + +use super::{check_page, is_setting_identifier, SettingPage}; +use crate::rejection::{invalid, Validation}; +use crate::view::ViewDeclaration; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::collections::BTreeSet; + +/// Most regions one plugin may declare. +pub const MAX_SETTING_REGIONS: usize = 16; +/// Most search keywords one region may declare, and most one translation may add. +pub const MAX_REGION_KEYWORDS: usize = 32; +/// Longest search keyword, in characters. +pub const MAX_KEYWORD_CHARS: usize = 64; + +/// A plugin-owned part of one settings page. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SettingRegion { + /// Identifier, unique among the plugin's regions; view events name it. + pub id: String, + /// Page the region appears on; the plugin's own Settings tab when absent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub page: Option, + /// Words that find the page in settings search, in addition to the page + /// title and the declared rows. Translations may add more. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub keywords: Vec, + /// Function that draws the region; keywords alone need no backend. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub view: Option, +} + +impl SettingRegion { + /// Checks the region as the manifest entry at `field`. + pub fn validate(&self, field: &str) -> Validation<()> { + if !is_setting_identifier(&self.id) { + return Err(invalid( + format!("{field}.id"), + "A region ID starts with a lowercase letter and contains only letters and digits.", + )); + } + if let Some(page) = &self.page { + check_page(page, field)?; + } + if self.keywords.is_empty() && self.view.is_none() { + return Err(invalid( + field, + "A region declares search keywords, a view, or both.", + )); + } + check_keywords(&self.keywords) + .map_err(|message| invalid(format!("{field}.keywords"), message))?; + if let Some(view) = &self.view { + view.validate(&format!("{field}.view"))?; + } + Ok(()) + } + + /// The region as a page projection shows it: manifest keywords followed by + /// the translated ones that differ ignoring case, so both languages find + /// the page. + pub(super) fn shown(&self, translated: Option<&Vec>) -> Value { + let mut keywords = self.keywords.clone(); + let mut seen: BTreeSet = keywords.iter().map(|k| k.to_lowercase()).collect(); + for keyword in translated.into_iter().flatten() { + if seen.insert(keyword.to_lowercase()) { + keywords.push(keyword.clone()); + } + } + let mut shown = json!({"id": self.id, "keywords": keywords}); + if let Some(view) = &self.view { + shown["view"] = json!(view); + } + shown + } +} + +/// Checks the manifest's whole region list: bounded, unique IDs and at most +/// one region per page, so a page has one plugin view slot per plugin. +pub fn validate_regions(regions: &[SettingRegion], field: &str) -> Validation<()> { + if regions.len() > MAX_SETTING_REGIONS { + return Err(invalid( + field, + "A plugin declares at most 16 setting regions.", + )); + } + let mut ids = BTreeSet::new(); + let mut pages = BTreeSet::new(); + for (index, region) in regions.iter().enumerate() { + let entry = format!("{field}[{index}]"); + region.validate(&entry)?; + if !ids.insert(region.id.as_str()) { + return Err(invalid(format!("{entry}.id"), "Region IDs are unique.")); + } + if !pages.insert(region.page.clone()) { + return Err(invalid( + format!("{entry}.page"), + "A plugin declares at most one region per page.", + )); + } + } + Ok(()) +} + +/// Keywords are short, distinct, single-line words a user might type. +pub(super) fn check_keywords(keywords: &[String]) -> Result<(), &'static str> { + if keywords.len() > MAX_REGION_KEYWORDS { + return Err("A region declares at most 32 keywords."); + } + let mut seen = BTreeSet::new(); + for keyword in keywords { + if keyword.trim() != keyword + || keyword.is_empty() + || keyword.chars().count() > MAX_KEYWORD_CHARS + || keyword.chars().any(char::is_control) + { + return Err( + "A keyword is 1 to 64 characters of single-line text without surrounding spaces.", + ); + } + if !seen.insert(keyword.to_lowercase()) { + return Err("Keywords are distinct, ignoring case."); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn regions(value: Value) -> Vec { + serde_json::from_value(value).expect("regions") + } + + #[test] + fn a_region_needs_keywords_or_a_view() { + let empty = regions(json!([{"id":"overview"}])); + assert!(validate_regions(&empty, "settingRegions").is_err()); + let keywords = regions(json!([{"id":"overview","keywords":["jdk","sdk"]}])); + assert!(validate_regions(&keywords, "settingRegions").is_ok()); + let view = regions(json!([{"id":"overview","view":{"function":"settings.overview"}}])); + assert!(validate_regions(&view, "settingRegions").is_ok()); + } + + #[test] + fn one_region_per_page_and_unique_ids() { + let same_page = regions(json!([ + {"id":"a","keywords":["x"]}, + {"id":"b","keywords":["y"]} + ])); + let error = validate_regions(&same_page, "settingRegions").expect_err("same page"); + assert_eq!(error.field.as_deref(), Some("settingRegions[1].page")); + let pages = regions(json!([ + {"id":"a","keywords":["x"]}, + {"id":"b","page":{"buildSystemID":"maven"},"keywords":["y"]} + ])); + assert!(validate_regions(&pages, "settingRegions").is_ok()); + let ids = regions(json!([ + {"id":"a","keywords":["x"]}, + {"id":"a","page":{"buildSystemID":"maven"},"keywords":["y"]} + ])); + assert!(validate_regions(&ids, "settingRegions").is_err()); + } + + #[test] + fn keywords_are_short_distinct_single_line_words() { + for bad in [ + json!([" padded"]), + json!([""]), + json!(["line\nbreak"]), + json!(["Maven", "maven"]), + json!(["x".repeat(65)]), + ] { + let region = regions(json!([{"id":"a","keywords":bad}])); + assert!( + validate_regions(®ion, "settingRegions").is_err(), + "{bad}" + ); + } + } + + #[test] + fn shown_keywords_append_distinct_translations() { + let region = ®ions(json!([{"id":"a","keywords":["JDK","toolchain"]}]))[0]; + let shown = region.shown(Some(&vec!["工具链".to_owned(), "jdk".to_owned()])); + assert_eq!( + shown, + json!({"id":"a","keywords":["JDK","toolchain","工具链"]}) + ); + } +} diff --git a/rust/crates/plugin-model/src/view.rs b/rust/crates/plugin-model/src/view.rs new file mode 100644 index 00000000..a120b68e --- /dev/null +++ b/rust/crates/plugin-model/src/view.rs @@ -0,0 +1,30 @@ +//! The plugin function that draws a plugin view: the body of a tool window or +//! a settings region. The view's tree and canvas vocabulary, and the checks a +//! result passes before a host draws it, live in `lithe-plugin-ui`. + +use crate::names::is_function_id; +use crate::rejection::{invalid, Validation}; +use serde::{Deserialize, Serialize}; + +/// Names the same-plugin function a host calls with a view event (`open`, +/// `click`, `change`, …) and draws from the tree or patches it returns. The +/// host owns layout, controls, input and Apply; the plugin only describes. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct ViewDeclaration { + /// Plugin function served by the plugin's backend process. + pub function: String, +} + +impl ViewDeclaration { + /// Checks the declaration as the manifest entry at `field`. + pub fn validate(&self, field: &str) -> Validation<()> { + if !is_function_id(&self.function) { + return Err(invalid( + format!("{field}.function"), + "A view names a plugin function ID.", + )); + } + Ok(()) + } +} diff --git a/rust/crates/plugin-native-ui/Cargo.toml b/rust/crates/plugin-native-ui/Cargo.toml deleted file mode 100644 index 23c5621f..00000000 --- a/rust/crates/plugin-native-ui/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "lithe-plugin-native-ui" -version = "0.1.0" -edition = "2021" -license = "Apache-2.0" -description = "Versioned native plugin presentation: bounded view data, stable identities and named actions" - -[dependencies] -lithe-plugin-model = { path = "../plugin-model" } -lithe-protocol = { path = "../protocol" } -serde = { version = "1.0", features = ["derive"] } -serde_json = { version = "1.0", features = ["preserve_order"] } diff --git a/rust/crates/plugin-native-ui/src/lib.rs b/rust/crates/plugin-native-ui/src/lib.rs deleted file mode 100644 index 63b35788..00000000 --- a/rust/crates/plugin-native-ui/src/lib.rs +++ /dev/null @@ -1,431 +0,0 @@ -//! Versioned native plugin presentation: bounded data, stable identities and named actions. -//! -//! Note: ownership is recorded in .agents/notes/implemented/feature/2026-10-21-declarative-native-plugin-ui.md - -use serde::{Deserialize, Serialize}; -use std::collections::BTreeSet; - -/// A host-rendered tree, list or form; styling is deliberately absent from the contract. -#[derive(Debug, Clone, Deserialize, Serialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct NativeUI { - schema_version: u32, - id: String, - kind: Kind, - nodes: Vec, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - controls: Vec, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - buttons: Vec, - #[serde(skip_serializing_if = "Option::is_none")] - layout: Option, - /// Plugin function that supplies the rows, when the host fetches them. - #[serde(skip_serializing_if = "Option::is_none")] - pub source: Option, - actions: Vec, - toolbar: Vec, - context_menu: Vec, -} - -/// Tree permits nesting; list requires flat rows; form has controls and no rows. -#[derive(Debug, Clone, Copy, PartialEq, Deserialize, Serialize)] -#[serde(rename_all = "camelCase")] -enum Kind { - Tree, - List, - Form, -} - -/// Stable row identity, literal label and optional children. -#[derive(Debug, Clone, Deserialize, Serialize)] -#[serde(deny_unknown_fields)] -struct Node { - id: String, - label: String, - #[serde(skip_serializing_if = "Option::is_none")] - children: Option>, -} - -/// A bounded scalar owned by the host; no arbitrary JSON or executable content. -#[derive(Debug, Clone, Deserialize, Serialize)] -#[serde(untagged)] -enum ControlValue { - Text(String), - Checked(bool), - Number(f64), -} - -/// The initial form controls reuse native IDE fields, selectors and checkboxes. -#[derive(Debug, Clone, Copy, PartialEq, Deserialize, Serialize)] -#[serde(rename_all = "camelCase")] -enum ControlKind { - Input, - Search, - Editor, - Select, - Segmented, - Checkbox, - Stepper, -} - -/// Stable option value and a literal user-visible label. -#[derive(Debug, Clone, Deserialize, Serialize)] -#[serde(deny_unknown_fields)] -struct SelectOption { - id: String, - label: String, -} - -/// A bounded column grid. The host owns gaps, sizing and the narrow-panel fallback. -#[derive(Debug, Clone, Deserialize, Serialize)] -#[serde(deny_unknown_fields)] -struct GridLayout { - columns: u8, -} - -/// Form semantics only. onCommit names an existing non-selection invoke action. -#[derive(Debug, Clone, Deserialize, Serialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -struct Control { - id: String, - kind: ControlKind, - label: String, - value: ControlValue, - #[serde(skip_serializing_if = "Option::is_none")] - placeholder: Option, - #[serde(skip_serializing_if = "Option::is_none")] - options: Option>, - #[serde(skip_serializing_if = "Option::is_none")] - enabled: Option, - #[serde(skip_serializing_if = "Option::is_none")] - on_commit: Option, - #[serde(skip_serializing_if = "Option::is_none")] - span: Option, - #[serde(skip_serializing_if = "Option::is_none")] - info: Option, - #[serde(skip_serializing_if = "Option::is_none")] - rows: Option, - #[serde(skip_serializing_if = "Option::is_none")] - minimum: Option, - #[serde(skip_serializing_if = "Option::is_none")] - maximum: Option, - #[serde(skip_serializing_if = "Option::is_none")] - step: Option, -} - -/// Button layout policy; all visual metrics stay with the host button owner. -#[derive(Debug, Clone, Deserialize, Serialize)] -#[serde(rename_all = "camelCase")] -enum ButtonWidth { - Content, - Fill, -} - -/// A form action placement, deliberately separate from value-bearing controls. -#[derive(Debug, Clone, Deserialize, Serialize)] -#[serde(deny_unknown_fields)] -struct FormButton { - id: String, - label: String, - action: String, - #[serde(skip_serializing_if = "Option::is_none")] - width: Option, - #[serde(skip_serializing_if = "Option::is_none")] - primary: Option, - #[serde(skip_serializing_if = "Option::is_none")] - enabled: Option, - #[serde(skip_serializing_if = "Option::is_none")] - span: Option, - #[serde(skip_serializing_if = "Option::is_none")] - info: Option, -} - -/// Existing plugin function that returns `{ nodes }` for a detected build instance. -#[derive(Debug, Clone, Deserialize, Serialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct Source { - /// Build system whose detected instances the function serves. - #[serde(rename = "buildSystemID")] - pub build_system_id: String, - function: String, -} - -/// An independent action referenced by toolbar and context-menu placements. -#[derive(Debug, Clone, Deserialize, Serialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -struct Action { - id: String, - title: String, - #[serde(skip_serializing_if = "Option::is_none")] - icon: Option, - kind: ActionKind, - #[serde(skip_serializing_if = "Option::is_none")] - function: Option, - requires_selection: bool, -} - -/// Refresh reloads the source; invoke calls a declared plugin function. -#[derive(Debug, Clone, Copy, PartialEq, Deserialize, Serialize)] -#[serde(rename_all = "camelCase")] -enum ActionKind { - Refresh, - Invoke, -} - -fn identifier(value: &str) -> bool { - !value.is_empty() - && value.len() <= 128 - && value - .bytes() - .all(|byte| byte.is_ascii_alphanumeric() || b"._-".contains(&byte)) -} - -fn valid_info(value: Option<&str>) -> bool { - value.is_none_or(|value| !value.trim().is_empty() && value.len() <= 1024) -} - -impl NativeUI { - /// Checks the bounds and cross-references the contract promises the host. - pub fn validate(&self) -> Result<(), &'static str> { - if self.schema_version != 0 || !identifier(&self.id) || self.actions.len() > 64 { - return Err("Native UI requires schemaVersion 0, a stable ID and at most 64 actions."); - } - if self - .source - .as_ref() - .is_some_and(|source| !identifier(&source.function)) - { - return Err("Invalid native UI source function."); - } - if self.controls.len() > 32 - || self.buttons.len() > 16 - || (self.kind == Kind::Form - && ((self.controls.is_empty() && self.buttons.is_empty()) - || !self.nodes.is_empty() - || !self.context_menu.is_empty())) - || (self.kind != Kind::Form && (!self.controls.is_empty() || !self.buttons.is_empty())) - { - return Err( - "A native form needs controls or buttons, at most 32 controls and 16 buttons, and no rows.", - ); - } - if self - .layout - .as_ref() - .is_some_and(|layout| self.kind != Kind::Form || !(1..=12).contains(&layout.columns)) - || self - .controls - .iter() - .map(|control| control.span) - .chain(self.buttons.iter().map(|button| button.span)) - .any(|span| { - span.is_some_and(|span| { - self.layout - .as_ref() - .is_none_or(|layout| span == 0 || span > layout.columns) - }) - }) - { - return Err("Native form grids need 1–12 columns; each span needs a grid and must fit its columns."); - } - let mut ids = BTreeSet::from([self.id.as_str()]); - let mut pending: Vec<_> = self.nodes.iter().map(|node| (node, 0)).collect(); - let mut count = 0; - while let Some((node, depth)) = pending.pop() { - count += 1; - if count > 2000 - || depth > 16 - || !identifier(&node.id) - || !ids.insert(&node.id) - || node.label.trim().is_empty() - || node.label.len() > 1024 - { - return Err( - "Native rows need unique IDs and labels; limit 2000 nodes and depth 16.", - ); - } - if let Some(children) = &node.children { - if self.kind == Kind::List && !children.is_empty() { - return Err("A native list cannot contain nested rows."); - } - pending.extend(children.iter().map(|child| (child, depth + 1))); - } - } - let mut actions = BTreeSet::new(); - for action in &self.actions { - if !identifier(&action.id) - || !ids.insert(&action.id) - || !actions.insert(&action.id) - || action.title.trim().is_empty() - || action.title.len() > 256 - || action - .icon - .as_ref() - .is_some_and(|icon| !icon.is_valid_host_icon()) - || self.source.is_none() - || match action.kind { - ActionKind::Refresh => action.function.is_some() || action.requires_selection, - ActionKind::Invoke => !action.function.as_deref().is_some_and(identifier), - } - { - return Err( - "Native actions need unique IDs, a source and a valid refresh/invoke handler.", - ); - } - } - for control in &self.controls { - if !identifier(&control.id) - || !ids.insert(&control.id) - || control.label.trim().is_empty() - || control.label.len() > 256 - || control - .placeholder - .as_ref() - .is_some_and(|value| value.len() > 256) - || !valid_info(control.info.as_deref()) - || (control.kind != ControlKind::Editor && control.rows.is_some()) - || (control.kind == ControlKind::Editor && control.on_commit.is_some()) - || (control.kind != ControlKind::Stepper - && (control.minimum.is_some() - || control.maximum.is_some() - || control.step.is_some())) - || control.on_commit.as_ref().is_some_and(|id| { - !self.actions.iter().any(|action| { - &action.id == id - && action.kind == ActionKind::Invoke - && !action.requires_selection - }) - }) - { - return Err("Native controls need unique IDs, bounded labels and a declared non-selection invoke action."); - } - match (&control.kind, &control.value) { - (ControlKind::Input | ControlKind::Search, ControlValue::Text(value)) - if value.len() <= 1024 && control.options.is_none() => {} - (ControlKind::Editor, ControlValue::Text(value)) - if value.len() <= 8192 - && control.options.is_none() - && control.placeholder.is_none() - && control.rows.is_none_or(|rows| (2..=12).contains(&rows)) => {} - (ControlKind::Stepper, ControlValue::Number(value)) - if control.options.is_none() && control.placeholder.is_none() => - { - let (Some(minimum), Some(maximum), Some(step)) = - (control.minimum, control.maximum, control.step) - else { - return Err("A native stepper requires minimum, maximum and step."); - }; - if !minimum.is_finite() - || !maximum.is_finite() - || !step.is_finite() - || minimum.abs() > 1e9 - || maximum.abs() > 1e9 - || minimum > maximum - || step <= 0.0 - || step > 1e9 - || !value.is_finite() - || *value < minimum - || *value > maximum - { - return Err("Native stepper values must fit a finite bounded range and positive step."); - } - } - (ControlKind::Checkbox, ControlValue::Checked(_)) - if control.options.is_none() && control.placeholder.is_none() => {} - (ControlKind::Select | ControlKind::Segmented, ControlValue::Text(value)) - if control.placeholder.is_none() => - { - let Some(options) = &control.options else { - return Err("A native selector needs options."); - }; - let mut option_ids = BTreeSet::new(); - if options.is_empty() - || options.len() - > if control.kind == ControlKind::Segmented { - 8 - } else { - 128 - } - || options.iter().any(|option| { - !identifier(&option.id) - || !option_ids.insert(&option.id) - || option.label.trim().is_empty() - || option.label.len() > 256 - }) - || !options.iter().any(|option| &option.id == value) - { - return Err("Native selectors need 1–128 unique options and an existing selected value."); - } - } - _ => return Err("Native control values and properties must match their kind."), - } - } - for button in &self.buttons { - if !identifier(&button.id) - || !ids.insert(&button.id) - || button.label.trim().is_empty() - || button.label.len() > 256 - || !actions.contains(&button.action) - || !valid_info(button.info.as_deref()) - || self - .actions - .iter() - .any(|action| action.id == button.action && action.requires_selection) - { - return Err("Native form buttons need unique IDs, bounded labels and a non-selection action."); - } - } - for placement in [&self.toolbar, &self.context_menu] { - let mut seen = BTreeSet::new(); - if placement.len() > 64 - || placement - .iter() - .any(|id| !actions.contains(id) || !seen.insert(id)) - { - return Err("Native action placements must reference distinct declared actions."); - } - } - Ok(()) - } -} - -/// Validates a refreshed node set with the same identity and budget rules as -/// the initial declaration. Platform renderers never maintain a second validator. -pub fn validate_data_command( - payload: serde_json::Value, -) -> Result { - use serde_json::{json, Value}; - #[derive(Deserialize)] - #[serde(deny_unknown_fields)] - struct Payload { - ui: NativeUI, - data: Value, - } - #[derive(Deserialize)] - #[serde(deny_unknown_fields)] - struct Data { - nodes: Vec, - } - let mut payload: Payload = serde_json::from_value(payload).map_err(|error| { - lithe_protocol::CoreError::new(lithe_protocol::ErrorCode::InvalidRequest, error.to_string()) - })?; - let validate = || -> Result { - if serde_json::to_vec(&payload.data) - .map_err(|error| error.to_string())? - .len() - > 1024 * 1024 - { - return Err("Native data exceeds 1 MiB.".into()); - } - let data: Data = serde_json::from_value(payload.data).map_err(|error| error.to_string())?; - payload.ui.nodes = data.nodes; - payload.ui.validate().map_err(String::from)?; - Ok(json!({"status":"ok", "nodes": payload.ui.nodes})) - }; - Ok(match validate() { - Ok(nodes) => nodes, - Err(message) => { - json!({"status":"rejected", "error":{"code":"plugin.ui.invalidData", "message":message}}) - } - }) -} diff --git a/rust/crates/plugin-ui/Cargo.toml b/rust/crates/plugin-ui/Cargo.toml new file mode 100644 index 00000000..73b3e289 --- /dev/null +++ b/rust/crates/plugin-ui/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "lithe-plugin-ui" +version = "0.1.0" +edition = "2021" +license = "Apache-2.0" +description = "Plugin views: host-control nodes and canvas scenes checked and patched by Core" + +[dependencies] +lithe-plugin-model = { path = "../plugin-model" } +serde_json = { version = "1.0", features = ["preserve_order"] } diff --git a/rust/crates/plugin-ui/src/canvas.rs b/rust/crates/plugin-ui/src/canvas.rs new file mode 100644 index 00000000..b95e446c --- /dev/null +++ b/rust/crates/plugin-ui/src/canvas.rs @@ -0,0 +1,412 @@ +//! Canvas nodes: a bounded vector scene the host draws natively. A scene is +//! rects, paths, text, package images and groups in view-box coordinates. +//! Groups may react to hover, press and selection without a round trip and +//! report clicks; pan, zoom, hover and tooltips stay local to the host. +//! +//! Colors are `#RRGGBB`, `#RRGGBBAA`, a `$token` the host maps to its theme, +//! a `{light, dark}` pair, or a `{linear, angle}` gradient. Blur, filters, +//! blend modes, radial gradients, custom fonts and animation are not part of +//! the vocabulary. + +use crate::fields::{ + array, at, boolean, choice, events, fail, identifier, integer, line, number, numbers, object, + string, text, Checked, Object, +}; +use crate::tree::Walk; +use crate::{ + MAX_CANVASES, MAX_CANVAS_BYTES, MAX_CANVAS_NODES, MAX_COORDINATE, MAX_INFO_CHARS, + MAX_LABEL_CHARS, MAX_TEXT_CHARS, MAX_TREE_DEPTH, +}; +use lithe_plugin_model::is_safe_relative_path; +use serde_json::Value; +use std::collections::BTreeSet; + +/// Theme colors a canvas may name with `$`. +pub(crate) const COLOR_TOKENS: &[&str] = &[ + "text", + "textSecondary", + "textMuted", + "accent", + "success", + "warning", + "error", + "surface", + "background", + "sidebar", + "line", + "hover", + "selection", + "badge", +]; +/// Text styles of canvas text, mapped to the host type scale. +const TEXT_STYLES: &[&str] = &[ + "title", + "strong", + "body", + "caption", + "display", + "mono", + "monoSmall", +]; +/// Any coordinate. +const COORDINATE: (f64, f64) = (-MAX_COORDINATE, MAX_COORDINATE); +/// Any size, stroke width or radius. +const EXTENT: (f64, f64) = (0.0, MAX_COORDINATE); +/// Opacity. +const UNIT: (f64, f64) = (0.0, 1.0); +/// Group scale. +const SCALE: (f64, f64) = (0.1, 10.0); +/// Shadow elevation steps. +const SHADOW: (u64, u64) = (1, 3); +/// Longest path data, in bytes. +const MAX_PATH_DATA: usize = 8192; +/// Most runs of one text node and most stops of one gradient. +const MAX_RUNS: usize = 64; +const GRADIENT_STOPS: (usize, usize) = (2, 8); +/// Tallest canvas, in points. +const MAX_HEIGHT: u64 = 2000; + +/// Checks the canvas node at `path` and its scene. +pub(crate) fn check(walk: &mut Walk<'_>, value: &Value, path: &str) -> Checked<()> { + let map = object( + value, + path, + &[ + "type", "id", "label", "height", "viewBox", "pan", "zoom", "on", "nodes", + ], + )?; + walk.canvases += 1; + if walk.canvases > MAX_CANVASES { + return Err(fail(path, "A view has at most 8 canvases.")); + } + walk.id(map, path, true)?; + line(map, path, "label", MAX_LABEL_CHARS, true)?; + integer(map, path, "height", (1, MAX_HEIGHT), true)?; + let view_box = numbers(map, path, "viewBox", (4, 4), COORDINATE, true)?.unwrap_or_default(); + if view_box[2] <= 0.0 || view_box[3] <= 0.0 { + return Err(fail( + at(path, "viewBox"), + "A view box is [x, y, width, height] with a positive size.", + )); + } + boolean(map, path, "pan")?; + if let Some(zoom) = numbers(map, path, "zoom", (2, 2), (0.05, 20.0), false)? { + if !(zoom[0] <= 1.0 && 1.0 <= zoom[1]) { + return Err(fail( + at(path, "zoom"), + "Zoom is [minimum, maximum] around 1, from 0.05 to 20.", + )); + } + } + events(map, path, &["viewport"])?; + let nodes = map + .get("nodes") + .ok_or_else(|| fail(at(path, "nodes"), "Required."))?; + if serde_json::to_vec(nodes).map_or(usize::MAX, |bytes| bytes.len()) > MAX_CANVAS_BYTES { + return Err(fail( + at(path, "nodes"), + "A canvas scene is at most 256 KiB of JSON.", + )); + } + Scene::default().shapes(nodes, &at(path, "nodes"), 1) +} + +/// Identifiers and node count of one canvas scene. +#[derive(Default)] +struct Scene { + ids: BTreeSet, + count: usize, +} + +impl Scene { + fn shapes(&mut self, value: &Value, path: &str, depth: usize) -> Checked<()> { + if depth > MAX_TREE_DEPTH { + return Err(fail(path, "Canvas groups nest at most 16 levels deep.")); + } + let shapes = value + .as_array() + .ok_or_else(|| fail(path, "Expected an array of canvas nodes."))?; + for (index, shape) in shapes.iter().enumerate() { + self.shape(shape, &format!("{path}[{index}]"), depth)?; + } + Ok(()) + } + + fn id(&mut self, map: &Object, path: &str, required: bool) -> Checked> { + let id = identifier(map, path, "id", required)?.map(str::to_owned); + if let Some(id) = &id { + if !self.ids.insert(id.clone()) { + return Err(fail( + at(path, "id"), + "Canvas node identifiers are unique within the canvas.", + )); + } + } + Ok(id) + } + + fn shape(&mut self, value: &Value, path: &str, depth: usize) -> Checked<()> { + self.count += 1; + if self.count > MAX_CANVAS_NODES { + return Err(fail(path, "A canvas has at most 2000 nodes.")); + } + let kind = value + .get("type") + .and_then(Value::as_str) + .ok_or_else(|| fail(at(path, "type"), "A canvas node names its type."))?; + match kind { + "rect" => { + let map = object( + value, + path, + &[ + "type", "id", "x", "y", "w", "h", "radius", "fill", "stroke", "width", + "dash", "shadow", "opacity", + ], + )?; + self.id(map, path, false)?; + frame(map, path, true)?; + number(map, path, "radius", EXTENT, false)?; + paint(map, path)?; + integer(map, path, "shadow", SHADOW, false)?; + Ok(()) + } + "path" => { + let map = object( + value, + path, + &[ + "type", "id", "d", "bounds", "fill", "stroke", "width", "dash", "cap", + "rule", "opacity", + ], + )?; + self.id(map, path, false)?; + let data = string(map, path, "d", true)?.unwrap_or_default(); + if data.trim().is_empty() + || data.len() > MAX_PATH_DATA + || !data.chars().all(|character| { + "MmLlHhVvCcSsQqTtAaZz0123456789.,eE+- ".contains(character) + }) + { + return Err(fail( + at(path, "d"), + "Path data is at most 8192 bytes of SVG path commands and numbers.", + )); + } + if let Some(bounds) = numbers(map, path, "bounds", (4, 4), COORDINATE, false)? { + if bounds[2] <= 0.0 || bounds[3] <= 0.0 { + return Err(fail( + at(path, "bounds"), + "Bounds are [x, y, width, height] with a positive size.", + )); + } + } + paint(map, path)?; + choice(map, path, "cap", &["butt", "round", "square"], false)?; + choice(map, path, "rule", &["nonzero", "evenodd"], false)?; + Ok(()) + } + "text" => { + let map = object( + value, + path, + &[ + "type", "id", "x", "y", "text", "runs", "style", "align", "color", + "maxWidth", "opacity", + ], + )?; + self.id(map, path, false)?; + number(map, path, "x", COORDINATE, true)?; + number(map, path, "y", COORDINATE, true)?; + match (map.contains_key("text"), map.contains_key("runs")) { + (true, false) => { + text(map, path, "text", MAX_TEXT_CHARS, true)?; + } + (false, true) => { + let runs = array(map, path, "runs", (1, MAX_RUNS), true)?; + for (index, run) in runs.into_iter().flatten().enumerate() { + let run_path = format!("{path}.runs[{index}]"); + let run = object(run, &run_path, &["text", "color"])?; + text(run, &run_path, "text", MAX_TEXT_CHARS, true)?; + color(run, &run_path, "color")?; + } + } + _ => { + return Err(fail(path, "A text node has either text or runs.")); + } + } + choice(map, path, "style", TEXT_STYLES, false)?; + choice(map, path, "align", &["start", "center", "end"], false)?; + color(map, path, "color")?; + number(map, path, "maxWidth", (1.0, MAX_COORDINATE), false)?; + number(map, path, "opacity", UNIT, false)?; + Ok(()) + } + "image" => { + let map = object( + value, + path, + &["type", "id", "x", "y", "w", "h", "src", "opacity"], + )?; + self.id(map, path, false)?; + frame(map, path, true)?; + let source = string(map, path, "src", true)?.unwrap_or_default(); + if !is_safe_relative_path(source) + || source.len() > 256 + || !source.ends_with(".png") + || source.contains(':') + || source.chars().any(char::is_control) + || source.split('/').any(|part| part.is_empty() || part == ".") + { + return Err(fail( + at(path, "src"), + "An image is a package-relative PNG path of at most 256 bytes.", + )); + } + number(map, path, "opacity", UNIT, false)?; + Ok(()) + } + "group" => self.group(value, path, depth), + other => Err(fail( + at(path, "type"), + format!("Unknown canvas node type {other}."), + )), + } + } + + fn group(&mut self, value: &Value, path: &str, depth: usize) -> Checked<()> { + let map = object( + value, + path, + &[ + "type", "id", "x", "y", "w", "h", "radius", "clip", "scale", "children", "on", + "label", "tooltip", "states", "selected", "opacity", "shadow", "hidden", + ], + )?; + let interactive = events(map, path, &["click"])?.contains(&"click".to_owned()); + let id = self.id(map, path, interactive)?; + frame(map, path, false)?; + if interactive { + if !map.contains_key("w") || !map.contains_key("h") { + return Err(fail( + path, + "A clickable group declares its hit area with w and h.", + )); + } + if map.get("label").is_none() { + return Err(fail( + at(path, "label"), + "A clickable group has an accessible label.", + )); + } + } + debug_assert!(!interactive || id.is_some()); + number(map, path, "radius", EXTENT, false)?; + boolean(map, path, "clip")?; + number(map, path, "scale", SCALE, false)?; + line(map, path, "label", MAX_LABEL_CHARS, false)?; + text(map, path, "tooltip", MAX_INFO_CHARS, false)?; + boolean(map, path, "selected")?; + boolean(map, path, "hidden")?; + number(map, path, "opacity", UNIT, false)?; + integer(map, path, "shadow", SHADOW, false)?; + if let Some(states) = map.get("states") { + let states_path = at(path, "states"); + let states = object(states, &states_path, &["hover", "pressed", "selected"])?; + for (name, state) in states { + let state_path = at(&states_path, name); + let state = object( + state, + &state_path, + &["fill", "stroke", "width", "shadow", "scale", "opacity"], + )?; + color(state, &state_path, "fill")?; + color(state, &state_path, "stroke")?; + number(state, &state_path, "width", EXTENT, false)?; + integer(state, &state_path, "shadow", SHADOW, false)?; + number(state, &state_path, "scale", SCALE, false)?; + number(state, &state_path, "opacity", UNIT, false)?; + } + } + let children = map + .get("children") + .ok_or_else(|| fail(at(path, "children"), "Required."))?; + self.shapes(children, &at(path, "children"), depth + 1) + } +} + +/// `x`, `y`, `w`, `h`: required for rects and images, optional for groups. +fn frame(map: &Object, path: &str, required: bool) -> Checked<()> { + number(map, path, "x", COORDINATE, required)?; + number(map, path, "y", COORDINATE, required)?; + number(map, path, "w", EXTENT, required)?; + number(map, path, "h", EXTENT, required)?; + Ok(()) +} + +/// Fill, stroke, stroke width, dash pattern and opacity of a rect or path. +fn paint(map: &Object, path: &str) -> Checked<()> { + color(map, path, "fill")?; + color(map, path, "stroke")?; + number(map, path, "width", EXTENT, false)?; + numbers(map, path, "dash", (1, 8), EXTENT, false)?; + number(map, path, "opacity", UNIT, false)?; + Ok(()) +} + +/// A color: plain, a light/dark pair, or a linear gradient of plain colors. +fn color(map: &Object, path: &str, key: &str) -> Checked<()> { + let Some(value) = map.get(key) else { + return Ok(()); + }; + let field = at(path, key); + match value { + Value::String(color) => plain(color, &field), + Value::Object(pair) if pair.contains_key("light") || pair.contains_key("dark") => { + let pair = object(value, &field, &["light", "dark"])?; + for side in ["light", "dark"] { + let color = string(pair, &field, side, true)?.unwrap_or_default(); + plain(color, &at(&field, side))?; + } + Ok(()) + } + Value::Object(_) => { + let gradient = object(value, &field, &["linear", "angle"])?; + number(gradient, &field, "angle", (-360.0, 360.0), false)?; + let stops = array(gradient, &field, "linear", GRADIENT_STOPS, true)?; + for (index, stop) in stops.into_iter().flatten().enumerate() { + let stop_path = format!("{field}.linear[{index}]"); + let (Some(offset), Some(color)) = ( + stop.get(0).and_then(Value::as_f64), + stop.get(1).and_then(Value::as_str), + ) else { + return Err(fail(&stop_path, "A stop is [offset, color].")); + }; + if stop.as_array().map_or(0, Vec::len) != 2 || !(0.0..=1.0).contains(&offset) { + return Err(fail(&stop_path, "A stop is [offset from 0 to 1, color].")); + } + plain(color, &format!("{stop_path}[1]"))?; + } + Ok(()) + } + _ => Err(fail(field, "Expected a color.")), + } +} + +fn plain(color: &str, path: &str) -> Checked<()> { + let valid = match color.strip_prefix('#') { + Some(hex) => { + (hex.len() == 6 || hex.len() == 8) && hex.chars().all(|c| c.is_ascii_hexdigit()) + } + None => color + .strip_prefix('$') + .is_some_and(|token| COLOR_TOKENS.contains(&token)), + }; + if !valid { + return Err(fail( + path, + "A color is #RRGGBB, #RRGGBBAA or a $token such as $accent.", + )); + } + Ok(()) +} diff --git a/rust/crates/plugin-ui/src/fields.rs b/rust/crates/plugin-ui/src/fields.rs new file mode 100644 index 00000000..79636f56 --- /dev/null +++ b/rust/crates/plugin-ui/src/fields.rs @@ -0,0 +1,280 @@ +//! Field readers shared by the view, canvas and patch checks. Each reader +//! names the JSON path of the value it refuses, so a plugin author sees +//! `view[2].nodes[14].fill` rather than a bare type error. + +use lithe_plugin_model::PluginRejection; +use serde_json::{Map, Value}; + +/// Error code of every view result Core refuses. +pub const INVALID_VIEW: &str = "plugin.ui.invalidView"; + +/// Result of one check. +pub(crate) type Checked = Result; + +/// A JSON object of view data. +pub(crate) type Object = Map; + +/// The rejection of the value at `path`. +pub(crate) fn fail(path: impl Into, message: impl Into) -> PluginRejection { + PluginRejection::at(INVALID_VIEW, path, message) +} + +/// The path of `key` inside the object at `path`. +pub(crate) fn at(path: &str, key: &str) -> String { + format!("{path}.{key}") +} + +/// The object at `path`, whose keys are all in `allowed`. +pub(crate) fn object<'v>(value: &'v Value, path: &str, allowed: &[&str]) -> Checked<&'v Object> { + let map = value + .as_object() + .ok_or_else(|| fail(path, "Expected an object."))?; + if let Some(key) = map.keys().find(|key| !allowed.contains(&key.as_str())) { + return Err(fail(at(path, key), "Unknown field.")); + } + Ok(map) +} + +/// The value of `key`; `null` is refused rather than read as absent, so a +/// broken serializer cannot pass silently. +fn get<'v>(map: &'v Object, path: &str, key: &str, required: bool) -> Checked> { + match map.get(key) { + Some(Value::Null) => Err(fail( + at(path, key), + "Omit the field instead of sending null.", + )), + Some(value) => Ok(Some(value)), + None if required => Err(fail(at(path, key), "Required.")), + None => Ok(None), + } +} + +/// Single-line, non-blank text of at most `max` characters. +pub(crate) fn line<'v>( + map: &'v Object, + path: &str, + key: &str, + max: usize, + required: bool, +) -> Checked> { + let Some(text) = string(map, path, key, required)? else { + return Ok(None); + }; + if text.trim().is_empty() || text.chars().count() > max || text.chars().any(char::is_control) { + return Err(fail( + at(path, key), + format!("Expected single-line text of 1 to {max} characters."), + )); + } + Ok(Some(text)) +} + +/// Text of at most `max` characters that may break lines. +pub(crate) fn text<'v>( + map: &'v Object, + path: &str, + key: &str, + max: usize, + required: bool, +) -> Checked> { + let Some(text) = string(map, path, key, required)? else { + return Ok(None); + }; + if text.chars().count() > max + || text + .chars() + .any(|character| character.is_control() && character != '\n' && character != '\t') + { + return Err(fail( + at(path, key), + format!("Expected text of at most {max} characters without control characters."), + )); + } + Ok(Some(text)) +} + +/// A string of any content; callers apply their own rule. +pub(crate) fn string<'v>( + map: &'v Object, + path: &str, + key: &str, + required: bool, +) -> Checked> { + get(map, path, key, required)? + .map(|value| { + value + .as_str() + .ok_or_else(|| fail(at(path, key), "Expected a string.")) + }) + .transpose() +} + +/// A finite number within `min..=max`. +pub(crate) fn number( + map: &Object, + path: &str, + key: &str, + (min, max): (f64, f64), + required: bool, +) -> Checked> { + get(map, path, key, required)? + .map(|value| in_range(value, &at(path, key), min, max)) + .transpose() +} + +fn in_range(value: &Value, path: &str, min: f64, max: f64) -> Checked { + value + .as_f64() + .filter(|number| number.is_finite() && (min..=max).contains(number)) + .ok_or_else(|| fail(path, format!("Expected a number from {min} to {max}."))) +} + +/// A whole number within `min..=max`. +pub(crate) fn integer( + map: &Object, + path: &str, + key: &str, + (min, max): (u64, u64), + required: bool, +) -> Checked> { + get(map, path, key, required)? + .map(|value| { + value + .as_u64() + .filter(|number| (min..=max).contains(number)) + .ok_or_else(|| { + fail( + at(path, key), + format!("Expected a whole number from {min} to {max}."), + ) + }) + }) + .transpose() +} + +/// `true` or `false`. +pub(crate) fn boolean(map: &Object, path: &str, key: &str) -> Checked> { + get(map, path, key, false)? + .map(|value| { + value + .as_bool() + .ok_or_else(|| fail(at(path, key), "Expected true or false.")) + }) + .transpose() +} + +/// One of `choices`. +pub(crate) fn choice<'v>( + map: &'v Object, + path: &str, + key: &str, + choices: &[&str], + required: bool, +) -> Checked> { + let Some(text) = string(map, path, key, required)? else { + return Ok(None); + }; + if !choices.contains(&text) { + return Err(fail( + at(path, key), + format!("Expected one of {}.", choices.join(", ")), + )); + } + Ok(Some(text)) +} + +/// An array of `min..=max` items. +pub(crate) fn array<'v>( + map: &'v Object, + path: &str, + key: &str, + (min, max): (usize, usize), + required: bool, +) -> Checked>> { + let Some(value) = get(map, path, key, required)? else { + return Ok(None); + }; + let items = value + .as_array() + .ok_or_else(|| fail(at(path, key), "Expected an array."))?; + if !(min..=max).contains(&items.len()) { + return Err(fail( + at(path, key), + format!("Expected {min} to {max} items."), + )); + } + Ok(Some(items)) +} + +/// `min..=max` numbers, each within `range`. +pub(crate) fn numbers( + map: &Object, + path: &str, + key: &str, + count: (usize, usize), + (min, max): (f64, f64), + required: bool, +) -> Checked>> { + let Some(items) = array(map, path, key, count, required)? else { + return Ok(None); + }; + items + .iter() + .enumerate() + .map(|(index, item)| in_range(item, &format!("{}[{index}]", at(path, key)), min, max)) + .collect::>>() + .map(Some) +} + +/// An event list drawn from `events`, without repeats. +pub(crate) fn events(map: &Object, path: &str, events: &[&str]) -> Checked> { + let Some(items) = array(map, path, "on", (0, events.len()), false)? else { + return Ok(Vec::new()); + }; + let mut seen = Vec::new(); + for (index, item) in items.iter().enumerate() { + let event = item + .as_str() + .filter(|event| events.contains(event) && !seen.iter().any(|seen| seen == event)) + .ok_or_else(|| { + fail( + format!("{path}.on[{index}]"), + format!("Expected distinct events from {}.", events.join(", ")), + ) + })?; + seen.push(event.to_owned()); + } + Ok(seen) +} + +/// A node identifier: 1 to 64 letters, digits, `.`, `_` or `-`, starting +/// with a letter or digit. Events and patches address nodes by it. +pub(crate) fn identifier<'v>( + map: &'v Object, + path: &str, + key: &str, + required: bool, +) -> Checked> { + let Some(id) = string(map, path, key, required)? else { + return Ok(None); + }; + if !is_node_id(id) { + return Err(fail( + at(path, key), + "An identifier is 1 to 64 letters, digits, '.', '_' or '-', starting with a letter or digit.", + )); + } + Ok(Some(id)) +} + +/// Whether `id` may identify a view node, tree item or canvas node. +pub(crate) fn is_node_id(id: &str) -> bool { + id.len() <= 64 + && id + .chars() + .next() + .is_some_and(|first| first.is_ascii_alphanumeric()) + && id + .chars() + .all(|character| character.is_ascii_alphanumeric() || "._-".contains(character)) +} diff --git a/rust/crates/plugin-ui/src/lib.rs b/rust/crates/plugin-ui/src/lib.rs new file mode 100644 index 00000000..e2e42f9d --- /dev/null +++ b/rust/crates/plugin-ui/src/lib.rs @@ -0,0 +1,613 @@ +//! Plugin views: content a plugin draws in a tool window or a settings region +//! through one backend function, checked by Core before any host draws it. +//! +//! A view is an array of nodes. Host-control nodes (rows, sections, labels, +//! inputs, buttons, tables, trees) carry meaning only, and every host draws +//! them with its own native controls. Canvas nodes carry a bounded vector +//! scene the host draws natively, so a plugin can design a distinctive page +//! without a web view. The backend answers each event with a whole view or a +//! batch of patches; [`apply`] turns either into the next checked view, so +//! hosts never keep a second validator or patch engine. +//! +//! Settings regions never store values: a control there names a declared +//! setting and edits the host draft, which the host's Apply commits. +//! +//! Note: the decision is recorded in .agents/notes/proposed/architecture/2026-11-12-plugin-authored-settings-content.md + +mod canvas; +mod fields; +mod patch; +mod tree; + +use fields::{fail, object}; +use lithe_plugin_model::settings::{SettingAction, SettingDeclaration}; +use lithe_plugin_model::Validation; +use serde_json::Value; +use std::collections::BTreeSet; + +pub use fields::INVALID_VIEW; + +/// Largest serialized view, in bytes. +pub const MAX_VIEW_BYTES: usize = 3 * 1024 * 1024; +/// Most host-control nodes of one view; canvas shapes and tree items count separately. +pub const MAX_UI_NODES: usize = 512; +/// Deepest nesting of view nodes, tree items or canvas groups. +pub const MAX_TREE_DEPTH: usize = 16; +/// Most items of one tree. +pub const MAX_TREE_ITEMS: usize = 2000; +/// Most canvases of one view. +pub const MAX_CANVASES: usize = 8; +/// Most nodes of one canvas scene. +pub const MAX_CANVAS_NODES: usize = 2000; +/// Largest serialized canvas scene, in bytes. +pub const MAX_CANVAS_BYTES: usize = 256 * 1024; +/// Most patches of one result. +pub const MAX_PATCHES: usize = 512; +/// Largest absolute canvas coordinate or size. +pub const MAX_COORDINATE: f64 = 1e6; +/// Longest label, title or option text, in characters. +pub const MAX_LABEL_CHARS: usize = 120; +/// Longest body text, value or cell, in characters. +pub const MAX_TEXT_CHARS: usize = 1024; +/// Longest ⓘ explanation or tooltip, in characters. +pub const MAX_INFO_CHARS: usize = 480; + +/// Where a view appears; some nodes belong to one surface only. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Surface { + /// A plugin tool window. Trees appear only here. + ToolWindow, + /// A plugin region of a settings page. Setting rows, tool rows, bound + /// controls and setting-action buttons appear only here. + Settings, +} + +/// What the plugin's manifest lets a view refer to. +#[derive(Debug, Clone, Copy)] +pub struct Context<'a> { + /// Surface the view is drawn on. + pub surface: Surface, + /// Settings the plugin declares; bound controls and setting rows name them. + pub settings: &'a [SettingDeclaration], + /// Setting actions the plugin declares; buttons may run them. + pub actions: &'a [SettingAction], + /// Tools the plugin defines or requires; tool rows name them. + pub tools: &'a BTreeSet, +} + +/// Checks a complete view against the vocabulary, the budgets and the +/// manifest references of `context`. +pub fn check(context: &Context<'_>, view: &Value) -> Validation<()> { + check_at(context, view, "view") +} + +/// Applies a backend result to the host's current view. A result holds a +/// whole `view`, a batch of `patches`, or neither when nothing changed; the +/// returned view is always complete and checked, with whether it differs +/// from `current`. A patch whose target is missing refuses the whole result, +/// so the host keeps drawing `current`. +pub fn apply( + context: &Context<'_>, + current: Option<&Value>, + result: &Value, +) -> Validation<(Option, bool)> { + let map = object(result, "result", &["view", "patches"])?; + let next = match (map.get("view"), map.get("patches")) { + (Some(_), Some(_)) => { + return Err(fail( + "result", + "A result returns either a whole view or patches.", + )); + } + (Some(view), None) => { + check_at(context, view, "result.view")?; + view.clone() + } + (None, Some(patches)) => { + let Some(current) = current else { + return Err(fail( + "result.patches", + "Patches apply to a drawn view; the first result returns a view.", + )); + }; + let mut view = current.clone(); + patch::apply(&mut view, patches, "result.patches")?; + check_at(context, &view, "view")?; + view + } + (None, None) => return Ok((current.cloned(), false)), + }; + let changed = current != Some(&next); + Ok((Some(next), changed)) +} + +fn check_at(context: &Context<'_>, view: &Value, path: &str) -> Validation<()> { + if serde_json::to_vec(view).map_or(usize::MAX, |bytes| bytes.len()) > MAX_VIEW_BYTES { + return Err(fail(path, "A view is at most 3 MiB of JSON.")); + } + tree::Walk::new(context).nodes(view, path, 1) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + struct Fixture { + settings: Vec, + actions: Vec, + tools: BTreeSet, + } + + impl Fixture { + fn new() -> Self { + Self { + settings: serde_json::from_value(json!([ + {"id":"offline","type":"boolean","title":"Offline","default":false}, + {"id":"mode","type":"enum","title":"Mode","default":"fast", + "options":[{"value":"fast","title":"Fast"},{"value":"safe","title":"Safe"}]}, + {"id":"home","type":"directory","title":"Home","default":""} + ])) + .expect("settings"), + actions: serde_json::from_value(json!([ + {"id":"reindex","title":"Reindex","function":"index.rebuild"} + ])) + .expect("actions"), + tools: BTreeSet::from(["maven".to_owned()]), + } + } + + fn context(&self, surface: Surface) -> Context<'_> { + Context { + surface, + settings: &self.settings, + actions: &self.actions, + tools: &self.tools, + } + } + } + + fn field(context: &Context<'_>, view: Value) -> String { + let error = check(context, &view).expect_err("rejected"); + assert_eq!(error.code, INVALID_VIEW); + error.field.expect("field") + } + + fn scene(nodes: Value) -> Value { + json!([{"type":"canvas","id":"map","label":"Dependency map","height":240, + "viewBox":[0,0,400,240],"nodes":nodes}]) + } + + #[test] + fn a_tool_window_view_with_every_tool_window_node_passes() { + let fixture = Fixture::new(); + let view = json!([ + {"type":"section","title":"Summary","info":"What the plugin found.","children":[ + {"type":"row","children":[ + {"type":"label","text":"3 modules","style":"strong","tone":"accent"}, + {"type":"button","id":"refresh","text":"Refresh","icon":"refresh","tone":"primary"} + ]}, + {"type":"keyValue","items":[{"label":"JDK","value":"21","tone":"success"}]}, + {"type":"table","columns":[{"title":"Module"},{"title":"Tests","align":"end"}], + "rows":[["core","120"],["ui","48"]]}, + {"type":"banner","text":"Two modules are stale.","tone":"warning"} + ]}, + {"type":"textField","id":"filter","placeholder":"Filter","width":"fill","value":""}, + {"type":"select","id":"scope","value":"all", + "options":[{"value":"all","label":"All"},{"value":"main","label":"Main"}]}, + {"type":"segmented","id":"layout","value":"tree", + "options":[{"value":"tree","label":"Tree"},{"value":"flat","label":"Flat"}]}, + {"type":"toggle","id":"live","label":"Live","value":true}, + {"type":"tree","id":"modules","items":[ + {"id":"core","label":"core","icon":"plugin","expanded":true,"children":[ + {"id":"core.api","label":"api","detail":"12 classes"} + ]} + ]}, + {"type":"canvas","id":"graph","label":"Module graph","height":200,"viewBox":[0,0,400,200], + "pan":true,"zoom":[0.5,4],"on":["viewport"],"nodes":[ + {"type":"rect","x":0,"y":0,"w":400,"h":200,"radius":8,"fill":{"linear":[[0,"#1E1F22"],[1,"$surface"]],"angle":90}}, + {"type":"path","d":"M 10 10 L 390 190","stroke":{"light":"#3574F0","dark":"#548AF7"},"width":2,"dash":[4,2],"cap":"round"}, + {"type":"group","id":"node.core","x":40,"y":40,"w":120,"h":48,"radius":6,"on":["click"], + "label":"core module","tooltip":"core\n120 tests", + "states":{"hover":{"fill":"$hover"},"selected":{"stroke":"$accent","width":2}},"children":[ + {"type":"text","x":60,"y":24,"runs":[{"text":"core "},{"text":"120","color":"$success"}],"style":"strong","align":"center"}, + {"type":"image","x":4,"y":4,"w":16,"h":16,"src":"assets/module.png"} + ]} + ]} + ]); + check(&fixture.context(Surface::ToolWindow), &view).expect("valid view"); + } + + #[test] + fn nodes_belong_to_their_surface() { + let fixture = Fixture::new(); + let tool_window = fixture.context(Surface::ToolWindow); + let settings = fixture.context(Surface::Settings); + assert_eq!( + field( + &tool_window, + json!([{"type":"setting","setting":"offline"}]) + ), + "view[0]" + ); + assert_eq!( + field( + &tool_window, + json!([{"type":"toggle","id":"o","label":"Offline","setting":"offline"}]) + ), + "view[0].setting" + ); + assert_eq!( + field( + &tool_window, + json!([{"type":"button","id":"r","text":"Reindex","action":"reindex"}]) + ), + "view[0].action" + ); + assert_eq!( + field(&settings, json!([{"type":"tree","id":"t","items":[]}])), + "view[0]" + ); + check( + &settings, + &json!([ + {"type":"setting","setting":"home"}, + {"type":"tool","tool":"maven"}, + {"type":"toggle","id":"o","label":"Offline","setting":"offline"}, + {"type":"segmented","id":"m","setting":"mode"}, + {"type":"textField","id":"h","setting":"home","width":"fill"}, + {"type":"button","id":"r","text":"Reindex","action":"reindex"} + ]), + ) + .expect("settings region view"); + } + + #[test] + fn bound_controls_match_their_declared_setting() { + let fixture = Fixture::new(); + let settings = fixture.context(Surface::Settings); + assert_eq!( + field( + &settings, + json!([{"type":"toggle","id":"m","label":"Mode","setting":"mode"}]) + ), + "view[0].setting" + ); + assert_eq!( + field( + &settings, + json!([{"type":"select","id":"m","setting":"mode", + "options":[{"value":"fast","label":"Fast"}]}]) + ), + "view[0].options" + ); + assert_eq!( + field( + &settings, + json!([{"type":"toggle","id":"o","label":"Offline","setting":"offline","value":true}]) + ), + "view[0].value" + ); + assert_eq!( + field(&settings, json!([{"type":"setting","setting":"missing"}])), + "view[0].setting" + ); + assert_eq!( + field(&settings, json!([{"type":"tool","tool":"gradle"}])), + "view[0].tool" + ); + assert_eq!( + field( + &settings, + json!([{"type":"button","id":"x","text":"Run","action":"missing"}]) + ), + "view[0].action" + ); + } + + #[test] + fn host_control_nodes_refuse_unknown_and_malformed_fields() { + let fixture = Fixture::new(); + let context = fixture.context(Surface::ToolWindow); + assert_eq!( + field( + &context, + json!([{"type":"label","text":"x","color":"#FF0000"}]) + ), + "view[0].color" + ); + assert_eq!( + field(&context, json!([{"type":"label","text":"x","tone":null}])), + "view[0].tone" + ); + assert_eq!(field(&context, json!([{"type":"marquee"}])), "view[0].type"); + assert_eq!( + field( + &context, + json!([{"type":"button","id":"a","text":"A"},{"type":"button","id":"a","text":"B"}]) + ), + "view[1].id" + ); + assert_eq!( + field( + &context, + json!([{"type":"select","id":"s","value":"z", + "options":[{"value":"a","label":"A"}]}]) + ), + "view[0].value" + ); + assert_eq!( + field( + &context, + json!([{"type":"table","columns":[{"title":"A"},{"title":"B"}],"rows":[["only"]]}]) + ), + "view[0].rows[0]" + ); + assert_eq!( + field( + &context, + json!([{"type":"button","id":"b","text":"Go","icon":"not a symbol!"}]) + ), + "view[0].icon" + ); + } + + #[test] + fn canvas_scenes_use_the_bounded_vocabulary() { + let fixture = Fixture::new(); + let context = fixture.context(Surface::ToolWindow); + let cases = [ + ( + json!([{"type":"rect","x":0,"y":0,"w":1,"h":1,"fill":"red"}]), + "view[0].nodes[0].fill", + ), + ( + json!([{"type":"rect","x":0,"y":0,"w":1,"h":1,"fill":"$brand"}]), + "view[0].nodes[0].fill", + ), + ( + json!([{"type":"rect","x":0,"y":0,"w":1,"h":1,"blur":4}]), + "view[0].nodes[0].blur", + ), + ( + json!([{"type":"rect","x":2e6,"y":0,"w":1,"h":1}]), + "view[0].nodes[0].x", + ), + ( + json!([{"type":"path","d":"M0 0 L