diff --git a/.agents/notes/implemented/feature/2026-10-21-declarative-native-plugin-ui.md b/.agents/notes/archived/feature/2026-10-21-declarative-native-plugin-ui.md similarity index 88% rename from .agents/notes/implemented/feature/2026-10-21-declarative-native-plugin-ui.md rename to .agents/notes/archived/feature/2026-10-21-declarative-native-plugin-ui.md index 4d2361491e..48a56f4ab6 100644 --- a/.agents/notes/implemented/feature/2026-10-21-declarative-native-plugin-ui.md +++ b/.agents/notes/archived/feature/2026-10-21-declarative-native-plugin-ui.md @@ -2,6 +2,10 @@ 状态:已实现 +归档日期:2026-11-19 + +> 契约在 v0 里删掉了 `native-ui`,换成插件视图:工具窗口和设置区域都由插件返回节点树,Core 的 `plugins.ui.applyResult` 校验,宿主用 Viva 原生绘制。本文的 `desktop/internal/core/plugin_native.go` 已删除,当前决策见[插件视图——插件描述界面,宿主用 Viva 原生绘制](../../implemented/architecture/2026-11-12-plugin-authored-settings-content.md)。本文只保留历史取舍。 + ## 先说结论 插件可以声明树、列表、表单和面板工具栏动作,由宿主用共享控件呈现,开发者只提供数据与函数,不编写样式。声明本身不能携带颜色、字体或脚本。结构、所有权和预算的校验由 Rust Core 完成,宿主的呈现层不复制这些规则。当前 Viva 桌面端只有 Core 侧的校验入口(`desktop/internal/core/plugin_native.go`),还没有渲染原生插件界面。 diff --git a/.agents/notes/implemented/architecture/2026-11-12-plugin-authored-settings-content.md b/.agents/notes/implemented/architecture/2026-11-12-plugin-authored-settings-content.md new file mode 100644 index 0000000000..672a1115f7 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-12-plugin-authored-settings-content.md @@ -0,0 +1,153 @@ +# Agent 笔记:插件视图——插件描述界面,宿主用 Viva 原生绘制 + +状态:已实现 + +## 先说结论 + +插件自己设计界面的地方有两处:工具窗口的正文,以及设置页里的设置区域(`settingRegions`)。两处都叫插件视图。插件后端的视图函数返回一棵 JSON 节点树,宿主把它交给 Core 的 `plugins.ui.applyResult` 校验,再用自己的 Viva 控件原生绘制。插件后端不接触界面库,也不需要网页。 + +节点分两类: + +- **宿主控件**:行、分组、文字、输入框、选择、开关、按钮、表格、树等。只表达含义,样式全部来自宿主主题。 +- **画布**(`canvas`):插件描述一个有界的矢量场景(矩形、路径、文字、位图、分组),宿主保存场景并每帧自己画。悬停、按下、焦点、平移、缩放、悬停提示都在宿主本地处理,只有点击、修改这类语义事件才发给插件。 + +设置窗口里不嵌网页,网页只用于工具窗口。框外的一切归宿主;绑定设置的控件只改设置窗口的草稿,由宿主的「应用」经 Core 提交。 + +可以操作的原型: + +- [`docs/design/plugin-canvas-scene.html`](../../../../docs/design/plugin-canvas-scene.html):画布的交互、预算、故障回退和消息计数。 +- [`docs/design/build-execution-settings.html`](../../../../docs/design/build-execution-settings.html):大量插件注入时「构建、执行、部署」页的布局,见[构建、执行、部署设置页在大量插件注入时的结构](../feature/2026-11-18-build-execution-settings-at-scale.md)。 + +## 问题 + +设置页原来只能显示 Core 按清单生成的声明式设置行(`settings[]`)。插件作者做不了字段联动、「测试连接」按钮、依赖冲突图、配色预览这类界面。 + +旧的原生声明 `native-ui.schema.json` 只支持工具窗口里的树、列表和表单,还引用了 macOS 共享控件名(如 `LitheSettingsSelect`),换到 Viva 桌面端后已经不适用。 + +如果不划边界,插件会去改别的设置页、弹自己的对话框、改窗口底部按钮,宿主就没法统一管理设置窗口,也保证不了 `${setting:}`(把设置值代入启动参数的模板)的安全。 + +2026-11-12 的方案让插件在设置区域里用网页自绘。在 macOS 上实测,一个最简网页就额外带来三个系统进程,约 60 到 70 MB(见备选方案)。设置窗口一页可能有好几个插件区域,用户还会来回切页,这个开销太大。 + +## 决策 + +### 两处位置 + +| 位置 | 入口由谁决定 | 内容 | +| --- | --- | --- | +| 工具窗口正文 | 插件在 `ui.toolWindows` 里声明,带 `view: {function}` | 插件视图;树只在这里可用 | +| 设置区域 | 插件在 `settingRegions` 里声明 `page`;不写 `page` 时放在插件详情的「设置」标签。分组和位置由宿主按[设置页分类](../feature/2026-10-15-macos-settings-hierarchy.md)决定 | 插件视图画在页眉和本插件的声明式设置行之间,设置行照常显示;`setting`/`tool` 行、绑定设置的控件、带 `action` 的按钮只在这里可用 | + +区域还可以声明 `keywords`:设置搜索除了页面标题和声明的设置行,也按这些词定位页面,并打开到这个插件的那一块。画布里的文字不进搜索。 + +### 事件与答案 + +- 宿主按契约发送 `open`、`close`、`click`、`change`、`select`、`activate`、`viewport`、`settings` 事件,每个事件调用一次视图函数,参数里带 `instance`、`surface`、`language` 和 `settings{effective, draft}`。 +- 每个视图同一时间只发一个调用,按顺序发送。`viewport` 和 `settings` 停止变化 400 ms 后才发,等待中的同类事件合并成最新一个。输入框只在回车、失焦或提交时发一次 `change`,不按键调用。 +- 函数返回整棵视图 `{view}`、补丁 `{patches}`(`set`、`replace`、`remove`、`insert`,最多 512 个)或 `{}`。宿主把答案连同清单、位置和上一次画的视图交给 Core 的 `plugins.ui.applyResult`,Core 校验并应用补丁后返回完整的下一棵视图,宿主只画这棵。宿主不保留自己的校验器或补丁引擎。 +- 本版没有插件主动推送:视图只在回答事件时变化。 + +### 画布 + +- 节点是 `rect`、`path`、`text`、`image`、`group`,按 `viewBox` 坐标缩放到视图宽度。 +- 颜色可以是固定值、主题令牌(`$accent`、`$text` 等)、深浅两套值,或线性渐变;令牌和深浅两套值跟随主题。宿主控件不接受颜色、字体、尺寸和坐标。 +- 可点击的分组必须有 `id`、`w`、`h` 和 `label`。悬停、按下、选中的样式写在 `states`(`hover`、`pressed`、`selected`)里,由宿主本地切换。 +- 普通滚轮滚动页面;⌘ 或 Ctrl 加滚轮缩放,拖动空白处平移,缩放按钮由宿主画。悬停提示停留 500 ms 后显示。 +- 画布里没有文本框,需要输入时用旁边的宿主控件。 +- 图片只能是插件包里的 PNG,宿主只读加载,单个文件不超过 256 KiB,每边不超过 1024 像素。 + +### 预算与失败 + +预算以 Core 契约为准:一棵视图 3 MiB、宿主控件节点 512 个、嵌套 16 层、一棵树 2000 项、一棵视图 8 个画布、每个画布 2000 个节点、每个画布场景 256 KiB。超出时 Core 拒绝整个答案。 + +每次调用 2 秒超时。调用失败、超时或被 Core 拒绝时,保留上一次画好的视图,在视图自己的框里显示宿主文案加插件原文,并提供「重试」;窗口其他部分照常可用。设置区域还没画出视图时,只显示声明式设置行,这些设置行照样能改。 + +### 生命周期 + +视图显示时发 `open`,消失时发 `close`。关闭、停用、更新或卸载插件、关闭项目、切换界面语言时,宿主取消未完成的调用并丢弃晚到的答案;切换语言后用新的 `instance` 重新打开。视图状态只存在后端和宿主内存里,不写进插件包或应用包。 + +### Viva 尚不支持的画布能力 + +宿主按以下方式降级绘制,缺口在 Lithe-IDEA/viva fork 补齐后再接上([#2182](https://github.com/1lck/Lithe-IDEA/issues/2182)),不在 Lithe 里绕过: + +- `dash` 只区分实线和虚线,用 Viva 固定的虚线样式,不按插件给的长短。 +- 路径的渐变填充只取第一个和最后一个色标;矩形支持全部色标。 +- 分组透明度按每个子节点的颜色分别相乘,不是整层合成,重叠的子节点会互相透出;位图不跟随透明度。 +- 分组裁剪只做矩形裁剪,不带圆角。 +- 不支持双指捏合缩放。 + +### 正确做法 + +- 数据库插件在「设置」标签放一个区域,用宿主控件画连接表单,输入框绑定它声明的 `host`、`port`,「测试连接」按钮发 `click` 给后端。用户点宿主的「应用」后,Core 校验并写入设置。 +- 依赖分析插件在构建系统页放一个区域,用画布画依赖图。悬停、平移、缩放都在宿主本地完成;用户点了冲突节点,插件回 `set` 或 `insert` 补丁,在旁边放一个带 `action` 的「排除」按钮,写构建文件仍走插件的设置动作,遵守[设置反映工具真实配置](2026-10-25-settings-native-configuration-editing.md)。 +- 主题插件用画布画配色预览,预览里用固定颜色;「变体」分段控件绑定设置,切换只改草稿,插件收到 `settings` 事件后按草稿重画,点「取消」后预览恢复。 +- 新增宿主控件或画布能力时,先改 Core 契约和 `plugins.ui.applyResult`,再在 `desktop/internal/pluginview` 里绘制。 + +### 不要这样做 + +- 不要在宿主里校验或应用补丁,也不要在 Core 拒绝答案后画出一部分。 +- 不要让插件在框外画任何东西,也不要在宿主里按插件名加专用页面分支。插件需要新页面时只能用 `page` 声明。 +- 不要绕过 Core 直接写偏好目录或 `.lithe/plugin-settings.json`,否则 `${setting:}` 可能把未校验的值带进启动命令。 +- 不要把悬停、拖动、每帧重画发给插件处理。 +- 不要在画布里自己做文本框或键盘输入。 +- 不要在设置窗口的插件区域里嵌网页。 +- 不要为 Viva 缺少的画布能力在 Lithe 里写绕过代码,按上面的方式降级并在 fork 里补。 + +### 已确认 + +- 2026-11-12:渲染归 API-13,读写设置归 API-19,插件文字本地化归 API-37,都是现有编号的扩展,不新增编号。契约在 v0 里直接删掉 `native-ui`,换成插件视图,不升版本号(版本已于 2026-11-11 全部归 0)。 +- 2026-11-18:设置区域只用插件视图,需要自由绘制时用画布(保留场景),不嵌网页;网页只用于工具窗口,沿用[插件自带网页界面](2026-10-18-plugin-web-content-in-host-windows.md)。顺序是先合设计和原型,再做 Core 契约加 SDK,最后做桌面端 Viva 渲染。 + +## 考虑过的备选方案 + +### 只保留声明式设置行,不允许自由绘制 + +宿主最好管:样式统一、没有网页引擎、无障碍有保证。用户在 2026-11-12 否定了这一点:图形预览、可视化编辑这类插件确实需要自己绘制,只给设置行会把它们挡在外面。画布满足了这个需求。 + +### 设置区域用自绘网页(2026-11-12 提议,2026-11-18 放弃) + +插件提供包内 HTML,Viva 用 `canvas.NativeView(id, rect)` 在区域里放系统网页引擎(macOS 是 WKWebView,Windows 是 WebView2,Linux 是 WebKitGTK)。插件作者能直接用 Canvas、WebGL、SVG。 + +放弃的原因: + +- 内存。在 macOS 上实测一个最简页面,额外带来三个系统进程。两次测量分别是 WebContent 41、42 MB,GPU 22、12 MB,Networking 6、5 MB,合计约 69、59 MB。画布只在宿主进程里多存一份场景,通常几 KB 到几十 KB,没有额外进程。Windows 的 WebView2 没测。 +- 一页可能有多个插件区域,用户频繁切页,每次都要启动和销毁网页进程。 +- 原生视图挖洞后,宿主的下拉弹层必须画在更高一层,否则会被网页盖住;三端网页引擎的行为也不一致。 + +### 即时绘制的远程画布 + +插件后端每一帧都发绘图指令,宿主把所有鼠标和键盘事件转发回去。每次交互都要跨进程往返,拖动会卡;文字输入和输入法要宿主重做;插件作者还要学一套新接口。2026-11-12 用户决定不采用。保留场景的画布只让语义事件跨进程,输入仍用宿主控件,场景词汇和 SVG 接近。 + +### 把插件进程的原生窗口嵌进框里 + +各平台嵌入方式完全不同,插件进程也能借此操作宿主窗口,安全边界守不住。不采用。 + +### 在宿主进程里运行 WASM 绘制 + +省掉跨进程往返,但插件代码跑进宿主进程,资源和崩溃难隔离,还要维护一套 WASM 运行时和接口版本。不采用。 + +## 后果 + +- 旧的原生树、列表、表单已删除(`core/plugin_native.go`、`pluginservice/hostnative.go`、`workbench/plugin_native.go`),声明 `native-ui` 的插件要改用插件视图。旧决策「声明式原生插件界面契约」(2026-10-21)已归档,不再作为依据。 +- 工具窗口和设置区域共用 `desktop/internal/pluginview` 这一个渲染器:`session.go` 管事件队列、去抖、取消和重试,`render.go` 画宿主控件和树,`canvas.go` 画画布。新增节点只改这一处。 +- 视图只在回答事件时变化,构建进度这类实时内容要等以后的版本加推送。 +- 画布图片的大小上限(256 KiB、1024 像素)目前只在宿主实现里,需要写进 Core 契约。 +- 降级项在 Viva fork 补齐之前,插件不能依赖自定义虚线、多色路径渐变、整层透明度、位图透明度、圆角裁剪和捏合缩放。 +- 画布可点击分组的无障碍名称用 Viva 的命中区域(`HitWithOptions` 的 `Role` 和 `label`)提供,读屏的实际效果需要在原生整机上验收。 + +## 验证 + +- `scripts/desktop/desktop-go.sh test ./internal/pluginview/ ./internal/pluginservice/ ./internal/workbench/ ./internal/settingswindow/ ./internal/core/ -count=1`:覆盖事件顺序与去抖、晚到答案丢弃、失败重试、节点解析、画布路径与颜色、图片限制、嵌套树高度、视图事件参数(Core 契约 fixture)、区域绑定设置与搜索关键词。 +- `scripts/desktop/desktop-go.sh test -count=1 -tags 'vivahead lithevisual' -run 'TestVisualPluginView' ./internal/pluginview/` 和 `scripts/desktop/desktop-go.sh test -count=1 -tags 'vivahead lithevisual' -run 'TestVisualPluginRegion' ./internal/settingswindow/`:设置 `LITHE_VISUAL_OUTPUT_DIR` 后输出工具窗口视图和设置区域的深浅主题截图。 +- `scripts/desktop/verify/verify-runtime-bundle-immutability.sh`:确认插件包和应用包在运行中不被写入。 +- 原生整机验收:安装一个声明了视图工具窗口和设置区域的测试插件,检查点击、编辑、树选择与激活、画布平移缩放、绑定设置的应用与取消、后端报错后的重试、停用插件后视图关闭;macOS 上打开插件区域时不出现新的 `com.apple.WebKit` 进程。Windows 在虚拟机上重复。 + +## 适用范围 + +- `desktop/internal/pluginview/` +- `desktop/internal/pluginservice/hostview.go` +- `desktop/internal/core/plugin_view.go` +- `desktop/internal/workbench/plugin_view.go` +- `desktop/internal/settingswindow/plugin_region_view.go` +- `desktop/internal/settingswindow/settings_surfaces.go` +- `docs/design/plugin-canvas-scene.html` +- Lithe-core-rust 的 `shared/plugins/contract/v1/`(插件视图、设置区域的契约、schema 与 fixture) diff --git a/.agents/notes/proposed/architecture/2026-10-13-public-extension-contract-and-provider-api.md b/.agents/notes/proposed/architecture/2026-10-13-public-extension-contract-and-provider-api.md index 3872d3f4f0..bb6d6a83bb 100644 --- a/.agents/notes/proposed/architecture/2026-10-13-public-extension-contract-and-provider-api.md +++ b/.agents/notes/proposed/architecture/2026-10-13-public-extension-contract-and-provider-api.md @@ -6,25 +6,25 @@ ## 先说结论 -PR #37 建立了第一阶段 UI Contribution(插件声明的界面入口);到 2026-10-30,Mac 已有原生 Tree/List/Form、包内网页和独立后端,不再只是静态文本窗口。下一步先在 Viva 桌面端(`desktop/`,macOS 与 Windows 共用)把已有编辑器、文件和命令功能开放成有授权、版本与生命周期的公共 API,再接续领域 Provider(提供业务数据、行为或进程的实现)。不开放任意第三方原生二进制动态加载,也不把 WASM 运行时作为补齐 API 的前置条件;任务与公开文档待办见 [macOS 插件 API 实施计划](../../../../docs/development/macos-plugin-api-plan.md)。 +PR #37 建立了第一阶段 UI Contribution(插件声明的界面入口);到 2026-11-19,桌面端已有插件视图(宿主控件、树、画布)、包内网页和独立后端,不再只是静态文本窗口。下一步先在 Viva 桌面端(`desktop/`,macOS 与 Windows 共用)把已有编辑器、文件和命令功能开放成有授权、版本与生命周期的公共 API,再接续领域 Provider(提供业务数据、行为或进程的实现)。不开放任意第三方原生二进制动态加载,也不把 WASM 运行时作为补齐 API 的前置条件;任务与公开文档待办见 [macOS 插件 API 实施计划](../../../../docs/development/macos-plugin-api-plan.md)。 ## 问题 -最初的 API level 2 要求窗口使用 `text`,命令只能打开自身窗口,插件校验依赖语言或 UI。这是第一阶段的历史背景,不是今天的完整能力表:当前 Core 已允许纯 Build/VCS/Debug/项目生成器插件,桌面端的 `ui:3` 也已经支持原生树、列表和表单。 +最初的 API level 2 要求窗口使用 `text`,命令只能打开自身窗口,插件校验依赖语言或 UI。这是第一阶段的历史背景,不是今天的完整能力表:当前 Core 已允许纯 Build/VCS/Debug/项目生成器插件,桌面端也已经支持插件视图(ui 0)。 -当前缺口在于通用接入:`ui.commands` 仍绑定自身窗口;原生动态数据源绑定自身构建系统和唯一实例;`backend:1` 是每插件一个应用级本机进程,只由自身网页调用,不识别远程工作区。函数协议 v2 已有本插件凭据服务,但尚不是通用工作区/编辑器 SDK。开发者不能因为宿主内部模块能操作文件或编辑器,就直接从第三方后端调用它。领域能力的进一步迁移也不能与通用宿主 API 混为一谈。 +当前缺口在于通用接入:`ui.commands` 仍绑定自身窗口;插件视图只在回答事件时变化,还没有主动推送和树的懒加载;`backend:1` 是每插件一个应用级本机进程,只由自身网页调用,不识别远程工作区。函数协议 v2 已有本插件凭据服务,但尚不是通用工作区/编辑器 SDK。开发者不能因为宿主内部模块能操作文件或编辑器,就直接从第三方后端调用它。领域能力的进一步迁移也不能与通用宿主 API 混为一谈。 ## 提案 ### 原生 UI 与窗口管理分离 -第三方插件可声明版本化 JSON UI 组件树,包含 Tree/List/Form/Input/Button、数据源和事件,由各平台的原生适配器渲染。窗口外壳继续由宿主管理停靠、标题、活动栏、顺序、显隐、布局和生命周期;组件事件通过宿主授权的动作或 Provider 调用。 +第三方插件可声明版本化 JSON UI 组件树,包含宿主控件(输入、选择、按钮、表格、树等)、画布和事件,由各平台的原生适配器渲染(已落地为插件视图)。窗口外壳继续由宿主管理停靠、标题、活动栏、顺序、显隐、布局和生命周期;组件事件通过宿主授权的动作或 Provider 调用。 2026-10-18 起,插件也可以在宿主管理的窗口里放自己的包内网页(`ui` 能力版本 2),这是可选项,不替代组件树。外壳规则不变,加载与桥接边界见[插件自带网页界面](../../implemented/architecture/2026-10-18-plugin-web-content-in-host-windows.md)。 内置或受信任的原生模块可通过 Native View/Renderer Factory(宿主登记的原生视图构造器)接入复杂原生内容,并共用同一套窗口管理。这个路径不等于开放任意第三方原生动态库加载;二进制接口(ABI)、签名、分发与隔离仍需单独设计。数据契约不含任何平台 UI 类型,各平台适配器的完成度以跨平台功能矩阵为准。 -截至 2026-10-28,原生 Tree/List/Form 及面板动作已落地,见[声明式原生插件树与动作](../../implemented/feature/2026-10-21-declarative-native-plugin-ui.md)。后续应扩展通用数据源与分页,而不是重新实现一套控件;面板内动作不等于已支持独立全局命令。 +2026-10-28 落地的原生 Tree/List/Form 已于 2026-11-19 由插件视图取代:工具窗口和设置区域的内容由插件后端返回节点树(宿主控件、树、画布),Core 校验,宿主原生绘制,见[插件视图——插件描述界面,宿主用 Viva 原生绘制](../../implemented/architecture/2026-11-12-plugin-authored-settings-content.md)。后续应在插件视图上扩展主动推送、懒加载与分页,而不是再实现一套控件;视图里的按钮不等于已支持独立全局命令。 ### 动作独立于窗口 @@ -136,4 +136,4 @@ Agent 的 Skills、Hooks、MCP 是用户管理的 Codex/Claude 原生配置, - [通用 ServiceProvider 与资源归属 #42](https://github.com/Lithe-IDEA/Lithe-IDEA/issues/42)。 - [四个纵向端到端样例 #14](https://github.com/Lithe-IDEA/Lithe-IDEA/issues/14)。 -本 Note 保留公共扩展的未完成方向;已落地部分以[第一阶段工作台 UI 贡献](../../implemented/architecture/2026-10-12-workbench-ui-contributions.md)、[原生插件 UI](../../implemented/feature/2026-10-21-declarative-native-plugin-ui.md)及[插件契约](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/shared/plugins/contract/v1/README.md)为准,不能再把第一阶段限制当成全部当前能力。 +本 Note 保留公共扩展的未完成方向;已落地部分以[第一阶段工作台 UI 贡献](../../implemented/architecture/2026-10-12-workbench-ui-contributions.md)、[插件视图](../../implemented/architecture/2026-11-12-plugin-authored-settings-content.md)及[插件契约](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/shared/plugins/contract/v1/README.md)为准,不能再把第一阶段限制当成全部当前能力。 diff --git a/.agents/notes/proposed/architecture/2026-11-12-plugin-authored-settings-content.md b/.agents/notes/proposed/architecture/2026-11-12-plugin-authored-settings-content.md deleted file mode 100644 index faceb1a3ce..0000000000 --- a/.agents/notes/proposed/architecture/2026-11-12-plugin-authored-settings-content.md +++ /dev/null @@ -1,226 +0,0 @@ -# Agent 笔记:插件在设置的两块区域里自己做界面 - -状态:提议中 - -## 先说结论 - -设置窗口里有两块区域交给插件自由创作:插件详情「设置」标签的正文,以及插件用 `page` 声明的侧栏页的正文。侧栏入口本身(名称、所属分组、位置)仍然只能声明。 - -区域里的内容只用**描述模式**:插件后端返回一棵与界面框架无关的 JSON 界面树,宿主用 Viva 控件画。需要自由绘制时(依赖图、配色预览、构建看板),在树里放一个**画布节点**。插件一次发来整个场景(矩形、路径、文字、位图、分组),宿主保存下来,每帧自己画。悬停、按下、键盘焦点、平移、缩放、悬停提示都由宿主在本地处理,只有点击、控件修改这类语义事件才发回插件。 - -设置窗口里不再嵌网页,网页只留给工具窗口。不管内容是什么,框外的一切都归宿主管;写入设置必须经过 Core 校验,而且只能写本插件声明过的设置。 - -可以操作的原型: - -- [`docs/design/plugin-canvas-scene.html`](../../../../docs/design/plugin-canvas-scene.html):画布节点的交互、预算、故障回退和消息计数。 -- [`docs/design/build-execution-settings.html`](../../../../docs/design/build-execution-settings.html):「构建、执行、部署」页在大量插件注入时的布局,见[构建、执行、部署设置页在大量插件注入时的结构](../../implemented/feature/2026-11-18-build-execution-settings-at-scale.md)。 - -## 问题 - -现在这两块区域只能显示 Core 按清单生成的声明式设置行(`settings[]`)。插件作者做不了字段联动、「测试连接」按钮、图形预览这类界面,例如数据库连接向导、依赖冲突图或配色预览。 - -现有的原生声明 `native-ui.schema.json` 引用了 macOS 共享控件名(如 `LitheSettingsSelect`),切换到 Viva 后已经不适用,而且它只用于工具窗口。 - -如果不先划边界,插件会想改别的设置页、弹自己的对话框、改窗口底部按钮。那样宿主就没法统一管理设置窗口,也无法保证 `${setting:}`(把设置值代入启动参数的模板)的安全。 - -2026-11-12 的版本让插件在这两块区域里用自绘网页。实测一个最简网页在 macOS 上额外带来三个系统进程,约 60 到 70 MB(数字见备选方案)。设置窗口一页可能有好几个插件区域,用户还会来回切页,这个开销太大。 - -## 提案 - -### 两块区域 - -| 区域 | 入口由谁决定 | 内容由谁画 | -| --- | --- | --- | -| 插件详情「设置」标签 | 宿主固定 | 插件,用描述模式,可以含画布节点;没有自定义内容时显示声明式设置行 | -| 侧栏插件页(「语言与框架 › <语言>」「构建、执行、部署 › <构建系统>」) | 插件在清单里声明 `page`,分组和位置由宿主按[设置页分类](../../implemented/feature/2026-10-15-macos-settings-hierarchy.md)决定 | 同上;同一页有多个插件声明时,用已有的贡献者切换(`settings_surfaces.go` 的 contributorIDs),每个插件只画自己那一块 | - -### 描述模式(界面树) - -插件后端(用现有的 Node 或 Rust SDK)返回一棵 JSON 界面树。宿主用 Viva 控件把它画出来,再把点击、提交等事件发回后端,后端返回补丁或新的树。 - -- 词汇与界面框架无关:布局(列、行、网格、分组、分隔线)、内容(文本、标题、宿主图标、徽标、链接)、控件(按钮、开关、文本框、数字框、单选、多选、文件或目录选择、列表、树、表格)、画布节点。 -- 树里画布以外的部分,样式只开放主题 token(宿主主题里命名好的颜色、字号、间距档位):语气色(普通、弱化、强调、警告、危险、成功)、字号档、粗细、间距档、宽度(填满或按字符数)。不开放任意颜色、字体和绝对坐标,这样深浅色、缩放、无障碍和输入法由宿主统一保证。 -- 这套 schema 替换 `native-ui.schema.json`。工具窗口的 Tree/List/Form 也改用同一套词汇,桌面端在 `plugin_native.go` 现有的渲染代码上改造。 -- 输入框不会每按一次键都调用后端,只在回车、失焦或提交时发一次 change 事件。 - -### 画布节点 - -画布节点是界面树里的一种节点,内容是一个**保留场景**:插件描述“画面里有哪些东西”,宿主保存这份描述并负责每一帧的绘制。与之相对的是即时绘制,也就是每一帧都由插件发绘图指令,这种方式不采用(见备选方案)。 - -下面的字段名都是示意,和原型一致,正式名字在 Core 契约 PR 里定。 - -```json -{ - "type": "canvas", "id": "deps", "label": "依赖图", "height": 360, - "viewBox": [0, 0, 1200, 640], "pan": true, "zoom": [0.4, 3], "on": ["viewport"], - "nodes": [ - { "type": "path", "id": "e:liba", "d": "M190 20C234 20 216 80 260 80", "stroke": "$line", "width": 1.5 }, - { "type": "group", "id": "guava31", "x": 260, "y": 60, "w": 190, "h": 40, - "on": ["click"], "label": "com.google.guava:guava 31.1,因冲突未使用", - "tooltip": "范围:compile\n未使用:被 33.0 取代", - "hover": { "fill": "$hover" }, "pressed": { "scale": 0.97 }, "sel": { "stroke": "$accent", "width": 2 }, - "children": [ - { "type": "rect", "w": 190, "h": 40, "radius": 8, "fill": { "light": "#fdf0ef", "dark": "#3a2726" }, "stroke": "$err", "dash": [4, 3] }, - { "type": "text", "x": 12, "y": 28, "style": "strong", "maxWidth": 168, - "runs": [{ "text": "guava", "color": "$text" }, { "text": " 31.1", "color": "$err" }] } - ] } - ] -} -``` - -**节点种类** - -| 节点 | 内容 | 说明 | -| --- | --- | --- | -| `rect` | 位置、大小、圆角、填充、描边、虚线、阴影档位 | 填充可以是线性渐变 | -| `path` | SVG 的 `d` 字符串、填充、描边 | 圆弧(`A` 命令)由宿主转换成三次贝塞尔,再交给 Viva 的 PathBuilder | -| `text` | 锚点、对齐、字号档、文字片段 `runs`(每段可以有自己的颜色)、`maxWidth` | 宿主用自己的界面字体和等宽字体测量和排版,超过 `maxWidth` 显示 …;插件不能指定字体 | -| `image` | 插件包里的位图路径 | 只读,只能来自插件包 | -| `group` | 变换、裁剪、命中区域 `w`/`h`、子节点 | 可点击、悬停样式、提示都挂在分组上 | - -每个节点有稳定的 `id`,补丁按 `id` 定位。 - -**颜色**有三种写法: - -- 主题 token(`$text`、`$accent`),跟随深浅色。依赖图这类普通界面用这种。 -- 深浅两套值(`{ "light": …, "dark": … }`),宿主按当前主题挑一个。构建看板的系列色用这种。 -- 固定颜色,不跟随主题。只在画布里允许,用于配色预览这类要展示颜色本身的内容。 - -**交互分工** - -| 由宿主在本地处理,不跨进程 | 发回插件 | -| --- | --- | -| 悬停、按下、选中的样式(插件预先声明 `hover`、`pressed`、`sel`) | `click`:点了哪个节点 | -| 键盘焦点和焦点框 | 界面树控件的 `change` | -| 平移、缩放、缩放按钮 | `viewport`:平移或缩放停下 400 ms 后发一次,场景用 `on` 声明了才发 | -| 悬停提示(节点的 `tooltip` 字段) | | - -插件收到事件后按节点 `id` 回补丁:`set` 改属性,`replace` 换一棵子树,`scene` 换整个画布,`ui` 换界面树里的一个节点(例如点了冲突节点后,在右侧详情里放一个「排除」按钮)。插件也可以主动推送补丁,例如进行中构建的实时进度。 - -**输入和滚动** - -- 画布里没有文本框。需要输入时用界面树里的控件;输入法、选择、复制粘贴都由宿主控件负责。 -- 滚轮归设置页滚动,避免画布“吞掉”滚动。⌘/Ctrl + 滚轮或双指捏合缩放画布,拖动空白处平移。缩放按钮由宿主画,插件只声明 `pan` 和 `zoom` 范围。 - -**无障碍** - -可点击的节点必须有 `label`(读屏软件读出的名字),否则整个场景被拒绝。Tab 键进入画布后在可点击节点之间移动,Enter 或空格触发 click,焦点框由宿主画。 - -**预算** - -| 项 | 上限 | 超出时 | -| --- | --- | --- | -| 每个画布的节点数 | 2,000 | 拒绝场景,回退 | -| 每个画布的场景大小 | 256 KB | 拒绝场景,回退 | -| 插件推送的应用频率 | 每秒 30 次 | 多出的按节点合并,只保留最新值 | -| 每次调用 | 2 秒超时 | 回退 | - -回退是指框里显示错误,改为显示插件在清单里声明的设置行;窗口其他部分照常可用,这些设置行照样能改,用户可以点「重试」。 - -**搜索** - -画布里的文字不进设置搜索:宿主不理解它的含义,也不应该为了搜索去渲染每个插件。插件在清单里给页面声明 `keywords`(API-19,文字按 API-37 本地化),侧栏搜索命中关键词后打开对应页和对应贡献者。 - -**首版不做**:模糊、滤镜、混合模式、径向渐变、自定义字体、动画。以后需要时可以加声明式过渡。 - -**编号**:画布节点是界面树的一种节点,和界面树一起算 API-13 的扩展;页面关键词算 API-19,插件文字本地化用 API-37。不新增编号。 - -### 宿主强制的边界 - -- **只画在框里。** 裁剪和滚动归宿主。弹出层只能由宿主控件打开(下拉、文件选择),并且锚在框内。插件不能弹对话框、发通知,也不能改标题、标签页、底部按钮、别的设置页或别的插件。 -- **只写自己的东西。** 写入走 Core:Core 按清单校验 id、类型、范围和作用域(API-19 `settings.update`)。插件没法写宿主偏好或别的插件的设置。修改工具的真实配置(例如在 `pom.xml` 里加排除项、改 Maven 的 `settings.xml`)走本插件自己的函数,并遵守[设置反映工具真实配置](../../implemented/architecture/2026-10-25-settings-native-configuration-editing.md):显式 Apply、冲突保护、写后重读。 -- **保存归宿主。** 控件绑定到设置 id,改动只生成草稿,由宿主保存,窗口底部写明写入目标(设置文件或 `app/pom.xml` 这类工具文件)。点宿主的「应用」时,设置由 Core 提交,工具配置由插件函数写入并重新读取;点「取消」时宿主丢弃草稿,把已保存的值发回插件让它重画。提交结果的生效方式(restart、immediate、reload、nextRun)照旧由宿主分发。 -- **生命周期跟着区域走。** 区域显示时才发 open 调用后端;切走、换贡献者、关闭窗口、停用或卸载插件时,取消未完成的调用并关闭区域,插件的推送也随之停止。每次调用都有超时。 -- **失败只影响这一块。** 后端出错、超时、崩溃或场景超出预算时,按上面的方式回退,窗口其他部分照常可用。 -- **文案分两种。** 宿主自己的文案(应用、取消、错误、回退提示、缩放按钮的提示)走 `shared/i18n`;插件画出来的文字属于插件内容,由插件自己做本地化(API-37 包内语言文件)。 - -### 正确做法 - -- 数据库插件在「设置」标签用界面树画一个连接表单,「测试连接」按钮调用本插件函数。用户点宿主的「应用」后,Core 校验并写入插件声明的 `host`、`port`。 -- Maven 依赖分析插件在「构建、执行、部署 › Maven」页用画布节点画依赖图。悬停、平移、缩放都在宿主本地完成。用户点了冲突的 guava 31.1,插件回一个 `ui` 补丁,在详情里放「排除」按钮。点「排除」生成一条写入 `app/pom.xml` 的草稿,底部显示写入目标。点「应用」后插件写入文件、重新读取,宿主显示新的依赖图。 -- 主题插件在「设置」标签用画布节点画配色预览,预览里用固定颜色。“变体”分段控件绑定设置 `dusk.variant`:切换只生成草稿,插件按草稿重画预览;点「取消」后预览恢复。 - -### 不要这样做 - -- 不要让插件在框外画任何东西,也不要在宿主里按插件名加专用页面分支。插件需要新页面时只能用 `page` 声明。 -- 不要绕过 Core 直接写偏好目录或 `.lithe/plugin-settings.json`。那样会跳过校验,`${setting:}` 就可能把未校验的值带进启动命令。 -- 不要在画布以外的界面树里开放任意颜色或像素坐标。需要像素级控制的内容放进画布节点。 -- 不要把悬停、拖动、每帧重画发给插件处理。悬停和按下的样式由插件预先声明,宿主本地切换。 -- 不要在画布里自己做文本框或键盘输入,用界面树的控件。 -- 不要在设置窗口的插件区域里嵌网页。 - -### 已确认(2026-11-12) - -1. API 编号:界面树渲染归入 API-13,读写设置归入 API-19,都算现有编号的扩展,不新增编号。当时自绘页面归入 API-14;2026-11-18 起设置区域不再用网页,API-14 只用于工具窗口。 -2. 契约版本:在 v0 里直接删掉 `native-ui`,换成新 schema,不升版本号(版本已于 2026-11-11 全部归 0)。 -3. 时间:现在做,包括一个 Core 契约加 SDK 的 PR,以及 #1799 的桌面端渲染。#1799 已于 2026-11-12 合入,桌面端渲染改为从最新 main 新开 PR。 - -### 已确认(2026-11-18) - -1. 设置窗口里的插件区域只用描述模式,需要自由绘制时用画布节点(保留场景),不嵌网页。网页只用于工具窗口,沿用[插件自带网页界面](../../implemented/architecture/2026-10-18-plugin-web-content-in-host-windows.md)的实现。 -2. 顺序:先合入这份设计和两个原型;再做 Core 契约加 SDK 的 PR(界面树、画布节点、页面关键词、预算);最后做桌面端的 Viva 渲染。 - -## 考虑过的备选方案 - -### 只保留声明式设置行,不允许自由绘制 - -吸引力在于宿主最好管:样式统一、没有网页引擎、无障碍有保证。用户在 2026-11-12 否定了这一点:有些插件确实需要自己绘制(图形预览、可视化编辑),只给设置行会把它们挡在外面。画布节点在描述模式里满足了这个需求。 - -### 设置区域用自绘网页(2026-11-12 提议,2026-11-18 放弃) - -插件提供包内的 HTML 页面,Viva 用 `canvas.NativeView(id, rect)` 在区域里挖一个洞,放进系统网页引擎(macOS 是 WKWebView,Windows 是 WebView2,Linux 是 WebKitGTK)。加载规则、内容安全策略和 bridge 沿用工具窗口的实现。吸引力在于插件作者能直接用 Canvas、WebGL、SVG,什么都能画。 - -放弃的原因: - -- 内存。在 macOS 上实测一个最简页面,额外带来三个系统进程。两次测量分别是 WebContent 41、42 MB,GPU 22、12 MB,Networking 6、5 MB,合计约 69、59 MB。画布节点只在宿主进程里多存一份场景,通常几 KB 到几十 KB,没有额外进程。Windows 的 WebView2 还没测。 -- 设置窗口一页可能有多个插件区域,用户会频繁切页;每次都要启动和销毁网页进程。 -- 原生视图挖洞后,宿主的下拉弹层必须画在更高一层,否则会被网页盖住;三端网页引擎的行为也不一致,Linux 差异最大。 - -工具窗口不受影响:那里的网页已经实现,只在窗口显示时存活。 - -### 即时绘制的远程画布(不采用) - -插件后端每一帧都发绘图指令,宿主画出来,再把所有鼠标和键盘事件转发回去。2026-11-12 用户决定不考虑,原因是每次交互都要跨进程往返(拖动会卡)、文字输入和输入法要宿主重做、插件作者还得学一套新接口。 - -保留场景的画布节点和它的区别: - -- 悬停、拖动、缩放在宿主本地处理,只有语义事件跨进程,没有每帧往返。 -- 输入仍然用界面树的控件,宿主不用重做输入法。 -- 场景词汇和 SVG 接近(矩形、路径的 `d`、文字、分组变换),插件作者不需要学新东西。 - -### 把插件进程的原生窗口嵌进框里 - -插件自己开一个原生视图,由宿主重新挂到设置窗口里。看起来最自由,但各平台嵌入方式完全不同,插件进程也能借此操作宿主窗口,安全边界守不住。不采用。 - -### 在宿主进程里运行 WASM 绘制 - -插件提供 WASM 模块,在宿主进程里调用 Viva 的绘图接口。省掉了跨进程往返,但插件代码会跑进宿主进程,资源和崩溃都难隔离,还要再维护一套 WASM 运行时和接口版本。不采用。 - -## 验收标准 - -- 同一个插件在「设置」标签和侧栏页里分别显示界面树和画布节点,并能通过宿主的「应用」写入它声明的设置;Core 拒绝未声明 id、越界值和错误作用域。 -- 画布节点的五种节点、三种颜色写法在浅色和深色下都正确显示;圆弧正确转换;文字超过 `maxWidth` 时截断。滚动设置页、打开下拉弹层、切换标签页时,画布的位置和裁剪都正确。 -- 悬停、按下、平移、缩放、悬停提示不产生跨进程消息;平移停下后只发一次 `viewport`;点击只发一条 `click`。 -- 节点数或场景大小超出预算、可点击节点缺少 `label`、调用超时、后端崩溃时,框里显示错误并回退到声明式设置行,这些设置行照样能改,窗口其他区域可以继续操作。插件推送超过每秒 30 次时按节点合并。 -- 键盘能用 Tab 在可点击节点间移动,用 Enter 或空格触发;读屏软件读出 `label`。 -- 打开任意插件区域时都不启动网页进程(macOS 上没有新的 `com.apple.WebKit` 进程)。 -- 停用、更新、卸载插件或关闭设置窗口后,没有残留的后端调用和推送。 -- 运行 `scripts/desktop/verify/verify-runtime-bundle-immutability.sh`,确认插件包和应用包在整个流程中没有被写入。 -- `native-ui.schema.json` 不再出现在 Core 契约里,工具窗口改用新 schema 后行为不变。 - -## 风险 - -- Viva 画布的绘制性能。2,000 个节点在平移和缩放时每帧重画,需要先在 Viva 里测帧时间,必要时按分组缓存。平移和缩放属于高频交互,遵守[可调整界面的性能边界](../../implemented/architecture/2026-09-13-resizable-ui-performance-boundaries.md)。 -- 文字度量在三端不同,插件不能依赖文字的精确宽度。用锚点、对齐和 `maxWidth` 截断减少影响,插件文档要写明这一点。 -- 画布节点要映射到各平台的无障碍树。需要先确认 Viva 能不能为自绘区域提供自定义无障碍元素;不能时先在 Viva fork 补上,不在 Lithe 里绕过。 -- 圆弧转三次贝塞尔有精度误差。大半径、接近整圆时要拆成多段。 -- 替换 `native-ui.schema.json` 会让现有声明原生工具窗口的插件失效。需要在契约更新记录里写清楚,并同步更新官方插件。 - -## 适用范围 - -- `desktop/internal/settingswindow/plugin_settings_view.go` -- `desktop/internal/settingswindow/settings_surfaces.go` -- `desktop/internal/workbench/plugin_native.go` -- `desktop/internal/workbench/pluginpages.go` -- Lithe-core-rust 的 `shared/plugins/contract/v1/`(界面树、画布节点、页面关键词的 schema 与 fixture) -- `docs/design/plugin-canvas-scene.html` diff --git a/desktop/internal/bgra/bgra.go b/desktop/internal/bgra/bgra.go new file mode 100644 index 0000000000..baf5829b02 --- /dev/null +++ b/desktop/internal/bgra/bgra.go @@ -0,0 +1,23 @@ +// Package bgra converts decoded images to the bitmaps Viva's canvas draws. +package bgra + +import ( + "image" + "image/draw" + + "github.com/vivaui/viva/gfx" +) + +// Bitmap converts an image to the canvas's premultiplied BGRA. id names the bitmap to the +// canvas, which keeps one texture per id and version. +func Bitmap(decoded image.Image, id uint64) gfx.Bitmap { + bounds := decoded.Bounds() + rgba := image.NewRGBA(image.Rect(0, 0, bounds.Dx(), bounds.Dy())) + draw.Draw(rgba, rgba.Bounds(), decoded, bounds.Min, draw.Src) + // image.RGBA is premultiplied RGBA; the canvas takes premultiplied BGRA. + pix := rgba.Pix + for i := 0; i+3 < len(pix); i += 4 { + pix[i], pix[i+2] = pix[i+2], pix[i] + } + return gfx.Bitmap{Pix: pix, Width: rgba.Rect.Dx(), Height: rgba.Rect.Dy(), Stride: rgba.Stride, ID: id, Version: 1} +} diff --git a/desktop/internal/bgra/bgra_test.go b/desktop/internal/bgra/bgra_test.go new file mode 100644 index 0000000000..640389c0ad --- /dev/null +++ b/desktop/internal/bgra/bgra_test.go @@ -0,0 +1,24 @@ +package bgra + +import ( + "bytes" + "image" + "image/color" + "testing" +) + +func TestBitmapIsPremultipliedBGRAFromTheImageOrigin(t *testing.T) { + whole := image.NewNRGBA(image.Rect(0, 0, 3, 2)) + whole.SetNRGBA(1, 1, color.NRGBA{R: 255, G: 64, A: 128}) + whole.SetNRGBA(2, 1, color.NRGBA{B: 200, A: 255}) + // A part of an image whose bounds do not start at the origin. + part := whole.SubImage(image.Rect(1, 1, 3, 2)) + bitmap := Bitmap(part, 42) + if bitmap.Width != 2 || bitmap.Height != 1 || bitmap.Stride != 8 || bitmap.ID != 42 || bitmap.Version != 1 { + t.Fatalf("bitmap = %dx%d stride %d id %d version %d", bitmap.Width, bitmap.Height, bitmap.Stride, bitmap.ID, bitmap.Version) + } + want := []byte{0, 32, 128, 128, 200, 0, 0, 255} + if !bytes.Equal(bitmap.Pix, want) { + t.Fatalf("pixels = %v, want %v", bitmap.Pix, want) + } +} diff --git a/desktop/internal/core/plugin_native.go b/desktop/internal/core/plugin_native.go deleted file mode 100644 index 6fc4a2e54e..0000000000 --- a/desktop/internal/core/plugin_native.go +++ /dev/null @@ -1,33 +0,0 @@ -package core - -import ( - "context" - "encoding/json" -) - -// ValidatePluginNativeData asks Core to check a native panel's data reply against the panel's -// declaration (ui 3). declaration is the validated native schema-1 object of the window, and data is -// the provider's {nodes} reply. Core applies the identity, label, nesting and node budgets of manifest -// validation and returns the checked nodes; a rejection is a *MarketplaceRejection carrying -// plugin.ui.invalidData. The host renders the returned nodes and never validates them itself. -func (c *Client) ValidatePluginNativeData(ctx context.Context, declaration, data json.RawMessage) (json.RawMessage, error) { - const command = "plugins.nativeUI.validateData" - var result struct { - Status string `json:"status"` - Nodes json.RawMessage `json:"nodes"` - Error *MarketplaceRejection `json:"error"` - } - if err := c.Execute(ctx, command, struct { - UI json.RawMessage `json:"ui"` - Data json.RawMessage `json:"data"` - }{declaration, data}, &result); err != nil { - return nil, err - } - if result.Status == "rejected" && result.Error != nil { - return nil, result.Error - } - if result.Status != "ok" || len(result.Nodes) == 0 || string(result.Nodes) == "null" { - return nil, newParseError(command, "native data validation returned an invalid outcome", "") - } - return result.Nodes, nil -} diff --git a/desktop/internal/core/plugin_settings.go b/desktop/internal/core/plugin_settings.go index c2af1bb79e..60958d5c4a 100644 --- a/desktop/internal/core/plugin_settings.go +++ b/desktop/internal/core/plugin_settings.go @@ -137,6 +137,29 @@ type PluginSettingsState struct { Storage PluginSettingsStorage `json:"storage"` // Localization is present whenever the request named a language. Localization *PluginSettingsLocalization `json:"localization,omitempty"` + // Region is the settings region the plugin placed on its own Settings tab, nil when it + // placed none there. + Region *PluginSettingsRegion `json:"region,omitempty"` +} + +// PluginSettingsRegion is a plugin-owned part of one settings page (settingRegions, API-19): +// search keywords that find the page and, when View is set, the plugin view (API-13) the +// host draws between the page's header and its declared rows, which stay. Keywords are the +// manifest's followed by those of the request's language. +type PluginSettingsRegion struct { + ID string `json:"id"` + Keywords []string `json:"keywords"` + View *struct { + Function string `json:"function"` + } `json:"view,omitempty"` +} + +// ViewFunction is the region's view function, empty when the region only adds keywords. +func (r *PluginSettingsRegion) ViewFunction() string { + if r == nil || r.View == nil { + return "" + } + return r.View.Function } // PluginSettingsLocalizationRequest names the interface language and, on the diff --git a/desktop/internal/core/plugin_view.go b/desktop/internal/core/plugin_view.go new file mode 100644 index 0000000000..ac0932535f --- /dev/null +++ b/desktop/internal/core/plugin_view.go @@ -0,0 +1,52 @@ +package core + +import ( + "context" + "encoding/json" +) + +// PluginViewSurface names the declared place a plugin view is drawn in: exactly one of a tool +// window whose body is a view, or a settings region with a view. +type PluginViewSurface struct { + ToolWindowID string `json:"toolWindowID,omitempty"` + SettingRegionID string `json:"settingRegionID,omitempty"` +} + +// ApplyPluginViewResult asks Core to check what a plugin's view function returned for one view +// event (plugins.ui.applyResult). manifest is the installed manifest, surface the place the view is +// drawn in, view the whole view the host drew last (nil before the first result) and result the +// function's answer: {view}, {patches} or {}. Core checks the node vocabulary, the budgets, the +// surface's rules and every reference to the manifest, applies patches to a copy of view, and +// returns the whole view to draw and whether it differs from view. A refused result is a +// *MarketplaceRejection carrying plugin.ui.invalidView and the JSON path of the first problem; the +// host then keeps drawing view. The host renders the returned nodes and never validates them itself. +func (c *Client) ApplyPluginViewResult(ctx context.Context, manifest json.RawMessage, surface PluginViewSurface, view, result json.RawMessage) (json.RawMessage, bool, error) { + const command = "plugins.ui.applyResult" + request := struct { + Manifest json.RawMessage `json:"manifest"` + Surface PluginViewSurface `json:"surface"` + View json.RawMessage `json:"view,omitempty"` + Result json.RawMessage `json:"result"` + }{Manifest: manifest, Surface: surface, Result: result} + if len(view) > 0 && string(view) != "null" { + request.View = view + } + var answer struct { + Status string `json:"status"` + View *struct { + View json.RawMessage `json:"view"` + Changed bool `json:"changed"` + } `json:"view"` + Error *MarketplaceRejection `json:"error"` + } + if err := c.Execute(ctx, command, request, &answer); err != nil { + return nil, false, err + } + if answer.Status == "rejected" && answer.Error != nil { + return nil, false, answer.Error + } + if answer.Status != "ok" || answer.View == nil || len(answer.View.View) == 0 || string(answer.View.View) == "null" { + return nil, false, newParseError(command, "plugin view check returned an invalid outcome", "") + } + return answer.View.View, answer.View.Changed, nil +} diff --git a/desktop/internal/core/settings_surfaces.go b/desktop/internal/core/settings_surfaces.go index 286624f2c8..e964c3d7c9 100644 --- a/desktop/internal/core/settings_surfaces.go +++ b/desktop/internal/core/settings_surfaces.go @@ -10,6 +10,9 @@ type SettingsContribution struct { Manifest json.RawMessage `json:"manifest"` Owner PluginSettingsOwner `json:"owner"` Enabled bool `json:"enabled"` + // Localizations are the translation files read for the request's language, by + // package-relative path: nil before the host read them, empty when it found none. + Localizations map[string]string `json:"localizations"` } // SettingsPageContribution references the complete editor of one installed owner. @@ -18,6 +21,11 @@ type SettingsPageContribution struct { Version string `json:"version"` Title string `json:"title"` Sections []PluginSettingsSection `json:"sections"` + // Region is the settings region the contributor placed on the page, nil when none. + Region *PluginSettingsRegion `json:"region,omitempty"` + // Localization reports the translation the catalog applied, present when the request + // named a language; ReadRequired asks the host to read Candidates and ask again. + Localization *PluginSettingsLocalization `json:"localization,omitempty"` } type SettingsPage struct { @@ -91,13 +99,17 @@ func settingsSurfaceResult[T any](ctx context.Context, c *Client, command, field return value, nil } -func (c *Client) SettingsPages(ctx context.Context, plugins []SettingsContribution) ([]SettingsPage, error) { +// SettingsPages asks Core for the settings page catalog of plugins. language, when not empty, +// translates section headings and adds region keywords from each plugin's translation files, +// which the host supplies as SettingsContribution.Localizations. +func (c *Client) SettingsPages(ctx context.Context, plugins []SettingsContribution, language string) ([]SettingsPage, error) { if plugins == nil { plugins = []SettingsContribution{} } return settingsSurfaceResult[[]SettingsPage](ctx, c, "plugins.settings.catalog", "pages", struct { - Plugins []SettingsContribution `json:"plugins"` - }{plugins}) + Plugins []SettingsContribution `json:"plugins"` + Language string `json:"language,omitempty"` + }{plugins, language}) } func (c *Client) SettingsNavigation(ctx context.Context, items []SettingsNavigationItem, query string) ([]SettingsNavigationRow, error) { diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index e67aeda7ed..6574e25b45 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -1219,11 +1219,6 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.memory.tooltip": "Memory: {total} in total, {lithe} of it in the Lithe main process.", "desktop.memory.unavailable": "Process memory could not be read.", "desktop.menu.open": "Menu", - "desktop.nativePanel.empty": "Nothing to show.", - "desktop.nativePanel.failed": "The plugin could not run this action.", - "desktop.nativePanel.multipleInstances": "This workspace has several build system instances; the panel cannot choose one.", - "desktop.nativePanel.noInstance": "This workspace has no build system instance for this panel.", - "desktop.nativePanel.sourceFailed": "The plugin could not load this panel.", "desktop.navigation.historyUnavailable": "That location no longer exists.", "desktop.navigation.label": "[Line] [:column]:", "desktop.navigation.title": "Go to Line:Column", @@ -1345,6 +1340,12 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.pluginSettings.scopeHelp": "Global settings apply to every project. Project settings apply to this project only, and each value stored there overrides the global one. Save or reload your draft before switching scope.", "desktop.pluginSettings.sourceChanged": "Settings changed in another window. Your draft is kept; reload before saving.", "desktop.pluginSettings.title": "Plugin settings", + "desktop.pluginView.failed": "The plugin could not update this view.", + "desktop.pluginView.invalid": "The plugin returned a view Lithe cannot show.", + "desktop.pluginView.resetZoom": "Reset zoom to 100%", + "desktop.pluginView.resetZoomHint": "Reset zoom", + "desktop.pluginView.timedOut": "The plugin took too long to update this view.", + "desktop.pluginView.zoom": "Canvas zoom", "desktop.pluginWeb.dialogTitle": "{plugin}: {title}", "desktop.pluginWeb.fileFilter": "Files ({extensions})", "desktop.pluginWeb.loading": "Opening…", @@ -4348,11 +4349,6 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.memory.tooltip": "内存:共 {total},其中 Lithe 主进程 {lithe}。", "desktop.memory.unavailable": "无法读取进程内存。", "desktop.menu.open": "菜单", - "desktop.nativePanel.empty": "没有可显示的内容。", - "desktop.nativePanel.failed": "插件无法执行此操作。", - "desktop.nativePanel.multipleInstances": "此工作区有多个构建系统实例,面板无法选择。", - "desktop.nativePanel.noInstance": "此工作区没有该面板需要的构建系统实例。", - "desktop.nativePanel.sourceFailed": "插件无法加载此面板。", "desktop.navigation.historyUnavailable": "该位置已不存在。", "desktop.navigation.label": "[行] [:列]:", "desktop.navigation.title": "跳转到行:列", @@ -4474,6 +4470,12 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.pluginSettings.scopeHelp": "全局设置对所有项目生效;项目设置只对当前项目生效,存了值的项会覆盖全局值。切换范围前,请保存或重新加载草稿。", "desktop.pluginSettings.sourceChanged": "设置已在其他窗口更改。草稿已保留;请重新加载后再保存。", "desktop.pluginSettings.title": "插件设置", + "desktop.pluginView.failed": "插件无法更新此视图。", + "desktop.pluginView.invalid": "插件返回的视图无法显示。", + "desktop.pluginView.resetZoom": "缩放重置为 100%", + "desktop.pluginView.resetZoomHint": "重置缩放", + "desktop.pluginView.timedOut": "插件更新此视图超时。", + "desktop.pluginView.zoom": "画布缩放", "desktop.pluginWeb.dialogTitle": "{plugin}:{title}", "desktop.pluginWeb.fileFilter": "文件({extensions})", "desktop.pluginWeb.loading": "正在打开…", diff --git a/desktop/internal/pluginhost/pluginhost.go b/desktop/internal/pluginhost/pluginhost.go index 94ed2d9d63..fd37e80d4e 100644 --- a/desktop/internal/pluginhost/pluginhost.go +++ b/desktop/internal/pluginhost/pluginhost.go @@ -124,15 +124,17 @@ type Capabilities map[string][]int // their forms through Core, discovers tools with the shared toolchain and // runs the plan in a staging directory. // - settings: pages per language and build system, sections, every control -// type, the project layer, setting effects and page buttons. +// type, the project layer, setting effects, page buttons and settingRegions +// (search keywords and plugin views on a page or the plugin's own Settings tab). // - debugAdapters: stdio adapters, adapter processes that print the loopback // TCP endpoint they listen on (tcpAnnounced) and adapters inside the // plugin's language server over loopback TCP, launch and attach (a remote host after the user // confirms it), argument and environment bindings, features and defaults. // - outputLinkMatchers: Build, Run and Test console lines become links at the // ranges Core finds; a matcher with resolve asks the backend on click. -// - ui: text, web (window.lithe bridge) and native tree, list or form tool -// windows docked in the tool stripes. +// - ui: text, web (window.lithe bridge) and plugin view tool windows docked +// in the tool stripes; a plugin view (pluginview) draws the host controls, +// trees and canvases a backend view function returns. // - vcsProviders: each provider's roots get a version control tool window // with status, check-in, rollback, Diff and whatever else the provider // negotiated; its session starts when the window first needs it. diff --git a/desktop/internal/pluginservice/hostnative.go b/desktop/internal/pluginservice/hostnative.go deleted file mode 100644 index 6bf37f09a4..0000000000 --- a/desktop/internal/pluginservice/hostnative.go +++ /dev/null @@ -1,95 +0,0 @@ -package pluginservice - -import ( - "context" - "encoding/json" - "errors" - "time" -) - -// nativeActionTimeout bounds one invoke action of a native panel. -const nativeActionTimeout = 60 * time.Second - -// InvokeToolWindowAction calls the function of a native panel's invoke action in the workspace at root, -// with the selected node's ID (or null). The answer may carry a message the panel shows; the rest of it -// belongs to the plugin. The plugin must be running: its panel does not start a backend. -func (s *Service) InvokeToolWindowAction(ctx context.Context, root, pluginID, function, selectedID string, values map[string]any) (string, error) { - if s == nil { - return "", ErrBackendUnavailable - } - workspace, ok := s.Contexts.ByPath(root) - if !ok { - return "", errors.New("the workspace is not open") - } - session := s.Host.Running(pluginID) - if session == nil { - return "", ErrBackendUnavailable - } - if !session.hasFunction(function) { - return "", errors.New("the action's function is not registered") - } - var selected any - if selectedID != "" { - selected = selectedID - } - argument := map[string]any{"selectedID": selected} - if values != nil { - argument["values"] = values - } - answer, err := session.Call(ctx, function, mustMarshal(argument), mustMarshal(workspace.ContextRef), nativeActionTimeout) - if err != nil { - return "", err - } - var result struct { - Message string `json:"message"` - } - if len(answer) > 0 && string(answer) != "null" { - if err := json.Unmarshal(answer, &result); err != nil { - return "", err - } - } - return result.Message, nil -} - -// InvokeNativeSource calls a source panel's function for the instance it reads and returns the nodes it -// answers with. Core checks the reply against the panel's declaration (declaration is the window's native -// object), so the host applies no rule of its own. The function receives the build system ID and the -// instance's root, and a form's current values when values is not nil. -func (s *Service) InvokeNativeSource(ctx context.Context, root, pluginID string, declaration json.RawMessage, function, buildSystemID, instanceRoot string, values map[string]any) ([]NativeNode, error) { - if s == nil { - return nil, ErrBackendUnavailable - } - workspace, ok := s.Contexts.ByPath(root) - if !ok { - return nil, errors.New("the workspace is not open") - } - session := s.Host.Running(pluginID) - if session == nil { - return nil, ErrBackendUnavailable - } - if !session.hasFunction(function) { - return nil, errors.New("the source's function is not registered") - } - argument := map[string]any{"buildSystemID": buildSystemID, "root": instanceRoot} - if values != nil { - argument["values"] = values - } - answer, err := session.Call(ctx, function, mustMarshal(argument), mustMarshal(workspace.ContextRef), nativeActionTimeout) - if err != nil { - return nil, err - } - if s.kernel == nil { - return nil, ErrBackendUnavailable - } - checked, err := s.kernel.ValidatePluginNativeData(ctx, declaration, answer) - if err != nil { - return nil, err - } - var result struct { - Nodes []NativeNode `json:"nodes"` - } - if err := json.Unmarshal(checked, &result); err != nil { - return nil, err - } - return result.Nodes, nil -} diff --git a/desktop/internal/pluginservice/hostview.go b/desktop/internal/pluginservice/hostview.go new file mode 100644 index 0000000000..1ca0c01da2 --- /dev/null +++ b/desktop/internal/pluginservice/hostview.go @@ -0,0 +1,153 @@ +package pluginservice + +import ( + "context" + "encoding/json" + "errors" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// viewCallTimeout bounds one call of a view function. The contract gives every view event +// 2 seconds; a slower answer fails the event, and the host keeps drawing the last view. +const viewCallTimeout = 2 * time.Second + +// ErrViewNotActivating is a view event for a stopped backend whose manifest does not start it +// for the view: a tool window without onView:. +var ErrViewNotActivating = errors.New("the plugin's view does not start its backend") + +// ViewCall is one event of a plugin view (API-13) for its backend view function. +type ViewCall struct { + PluginID string + // Manifest is the installed manifest, which Core checks the result against. + Manifest json.RawMessage + // Function is the declared view function: a tool window's view.function or a settings + // region's view.function. + Function string + Surface core.PluginViewSurface + // Activation starts a stopped backend when its manifest declares it; empty starts the + // backend unconditionally, as a settings region's page does. + Activation string + // Workspace is the root of the workspace the view is shown for; empty outside one. + Workspace string + // Event is the view event's params as the contract names them, without surface, which + // CallView adds. A settings page puts its own settings in, the saved values with its + // draft; without them CallView reads the saved values for Workspace, with an empty + // draft, as a tool window sends them. + Event json.RawMessage + // View is the whole view the host drew last; nil before the first result. + View json.RawMessage + // Close is a close event: it reaches a running backend only, and its result is ignored. + Close bool +} + +// CallView sends one view event to the plugin's backend and has Core check the answer +// (plugins.ui.applyResult). It returns the whole view to draw and whether it differs from +// call.View; a close event returns neither. A refused answer is a *core.MarketplaceRejection +// with plugin.ui.invalidView, which leaves the caller drawing call.View. ctx cancels the call: +// the host cancels a pending event when the view closes, so its late answer is dropped. +func (s *Service) CallView(ctx context.Context, call ViewCall) (json.RawMessage, bool, error) { + if s == nil || s.Host == nil || s.kernel == nil { + return nil, false, ErrBackendUnavailable + } + if !validFunctionID(call.Function) { + return nil, false, errors.New("invalid view function") + } + session := s.Host.Running(call.PluginID) + if session == nil { + if call.Close { + return nil, false, nil + } + if !declaresBackend(call.Manifest) || (call.Activation != "" && !declaredActivation(call.Manifest, call.Activation)) { + return nil, false, ErrViewNotActivating + } + var err error + if session, err = s.Host.EnsureBackend(ctx, call.PluginID); err != nil { + return nil, false, err + } + } + var reference json.RawMessage + if workspace, ok := s.Contexts.ByPath(call.Workspace); ok && call.Workspace != "" { + reference = mustMarshal(workspace.ContextRef) + } + event, err := s.viewEvent(ctx, call) + if err != nil { + return nil, false, err + } + answer, err := session.Call(ctx, call.Function, event, reference, viewCallTimeout) + if err != nil || call.Close { + return nil, false, err + } + if len(answer) == 0 || string(answer) == "null" { + answer = json.RawMessage(`{}`) + } + return s.kernel.ApplyPluginViewResult(ctx, call.Manifest, call.Surface, call.View, answer) +} + +// ViewSettings are the plugin's setting values by ID that a view event carries: Effective is +// what is saved and in force, Draft what the open settings window changed and did not apply. +type ViewSettings struct { + Effective map[string]json.RawMessage `json:"effective"` + Draft map[string]json.RawMessage `json:"draft"` +} + +// viewEvent is the event's params with the surface added, and the saved settings when the +// event carries none. A close event, which must reach the backend even when the settings +// cannot be read, goes without them then. +func (s *Service) viewEvent(ctx context.Context, call ViewCall) (json.RawMessage, error) { + params := map[string]json.RawMessage{} + if len(call.Event) > 0 { + if err := json.Unmarshal(call.Event, ¶ms); err != nil { + return nil, err + } + } + params["surface"] = mustMarshal(call.Surface) + if _, ok := params["settings"]; !ok { + effective, err := s.effectiveSettings(ctx, call.Manifest, call.Workspace) + if err != nil && !call.Close { + return nil, err + } + if effective != nil { + params["settings"] = mustMarshal(ViewSettings{Effective: effective, Draft: map[string]json.RawMessage{}}) + } + } + return json.Marshal(params) +} + +// effectiveSettings are the plugin's saved values in force in workspace, by setting ID, as +// Core projects them; a plugin without settings has none. +func (s *Service) effectiveSettings(ctx context.Context, manifest json.RawMessage, workspace string) (map[string]json.RawMessage, error) { + effective := map[string]json.RawMessage{} + if s.Settings == nil { + return effective, nil + } + snapshot, err := s.Settings.Load(ctx, manifest, workspace) + if err != nil { + return nil, err + } + for _, row := range snapshot.State.Rows { + effective[row.Declaration.ID] = row.Effective.Value + } + return effective, nil +} + +// ToolWindowViewCall is the call of a tool window's view for one event: the window's backend +// starts for it when its manifest declares onView:. +func ToolWindowViewCall(window ToolWindow, workspace string, event, view json.RawMessage, closing bool) ViewCall { + return ViewCall{ + PluginID: window.PluginID, Manifest: window.Manifest, Function: window.View, + Surface: core.PluginViewSurface{ToolWindowID: window.ID}, + Activation: "onView:" + window.ID, Workspace: workspace, Event: event, View: view, Close: closing, + } +} + +// SettingsViewCall is the call of a settings region's view for one event. The region's page +// opening starts the backend, so no activation event is needed. +func SettingsViewCall(editor SettingsEditor, regionID, function, workspace string, event, view json.RawMessage, closing bool) ViewCall { + return ViewCall{ + PluginID: editor.entry.Installed.ID, Manifest: editor.manifest, Function: function, + Surface: core.PluginViewSurface{SettingRegionID: regionID}, + Workspace: workspace, Event: event, View: view, Close: closing, + } +} diff --git a/desktop/internal/pluginservice/hostview_test.go b/desktop/internal/pluginservice/hostview_test.go new file mode 100644 index 0000000000..5a031e49e6 --- /dev/null +++ b/desktop/internal/pluginservice/hostview_test.go @@ -0,0 +1,118 @@ +package pluginservice + +import ( + "context" + "encoding/json" + "os" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginsettings" +) + +// viewParams is what viewEvent sends for call, by key. +func viewParams(t *testing.T, s *Service, call ViewCall) map[string]json.RawMessage { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + data, err := s.viewEvent(ctx, call) + if err != nil { + t.Fatal(err) + } + var params map[string]json.RawMessage + if err := json.Unmarshal(data, ¶ms); err != nil { + t.Fatal(err) + } + return params +} + +// viewSettingsOf is the settings params carried. +func viewSettingsOf(t *testing.T, params map[string]json.RawMessage) ViewSettings { + t.Helper() + var settings ViewSettings + if err := json.Unmarshal(params["settings"], &settings); err != nil { + t.Fatalf("settings %s: %v", params["settings"], err) + } + return settings +} + +// A settings page's event keeps the settings it carries, the draft with them, and gains the +// surface it is shown on. +func TestViewEventKeepsTheSettingsThePageSent(t *testing.T) { + s := &Service{Settings: pluginsettings.New(core.NewClient(), t.TempDir())} + params := viewParams(t, s, ViewCall{ + Manifest: json.RawMessage(`{}`), + Surface: core.PluginViewSurface{SettingRegionID: "overview"}, + Event: json.RawMessage(`{"event":"click","node":"probe","settings":{"effective":{"threads":4},"draft":{"threads":8}}}`), + }) + if string(params["event"]) != `"click"` || string(params["node"]) != `"probe"` { + t.Fatalf("the event's own params changed: %v", params) + } + var surface core.PluginViewSurface + if err := json.Unmarshal(params["surface"], &surface); err != nil || surface.SettingRegionID != "overview" { + t.Fatalf("surface %s, %v", params["surface"], err) + } + settings := viewSettingsOf(t, params) + if string(settings.Effective["threads"]) != `4` || string(settings.Draft["threads"]) != `8` { + t.Fatalf("the page's settings were replaced: %+v", settings) + } +} + +// A tool window's event carries the saved values in force with an empty draft: none for a +// host without a settings store, and Core's projection of the manifest's settings otherwise. +func TestViewEventAddsTheSavedSettingsForAToolWindow(t *testing.T) { + bare := viewSettingsOf(t, viewParams(t, &Service{}, ViewCall{Event: json.RawMessage(`{"event":"open"}`)})) + if bare.Effective == nil || len(bare.Effective) != 0 || bare.Draft == nil || len(bare.Draft) != 0 { + t.Fatalf("a host without a settings store sent %+v", bare) + } + + manifest, err := os.ReadFile(contractfixture.Path("fixtures/settings/settings.plugin.json")) + if err != nil { + t.Fatal(err) + } + s := &Service{Settings: pluginsettings.New(core.NewClient(), t.TempDir())} + params := viewParams(t, s, ViewCall{ + Manifest: manifest, Workspace: t.TempDir(), + Surface: core.PluginViewSurface{ToolWindowID: "fixture.tool"}, + Event: json.RawMessage(`{"event":"open"}`), + }) + settings := viewSettingsOf(t, params) + for _, id := range []string{"dialyzer", "checks"} { + if len(settings.Effective[id]) == 0 { + t.Errorf("the saved value of %s is not carried: %v", id, settings.Effective) + } + } + if settings.Draft == nil || len(settings.Draft) != 0 { + t.Fatalf("a tool window carried the drafts %v", settings.Draft) + } +} + +// Settings that cannot be read fail the event, except a close, which still reaches the +// backend so the view's state ends. +func TestViewEventFailsWithoutTheSettingsUnlessItCloses(t *testing.T) { + s := &Service{Settings: pluginsettings.New(core.NewClient(), t.TempDir())} + call := ViewCall{Manifest: json.RawMessage(`{"not":"a manifest"}`), Event: json.RawMessage(`{"event":"open"}`)} + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + if _, err := s.viewEvent(ctx, call); err == nil { + t.Fatal("an event went out without the settings it could not read") + } + call.Event, call.Close = json.RawMessage(`{"event":"close"}`), true + params := viewParams(t, s, call) + if string(params["event"]) != `"close"` { + t.Fatalf("the close event = %v", params) + } + if settings, ok := params["settings"]; ok { + t.Fatalf("a close carried settings it could not read: %s", settings) + } +} + +func TestViewEventRefusesParamsThatAreNotAnObject(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + if _, err := (&Service{}).viewEvent(ctx, ViewCall{Event: json.RawMessage(`["open"]`)}); err == nil { + t.Fatal("a list was sent as an event's params") + } +} diff --git a/desktop/internal/pluginservice/pluginservice.go b/desktop/internal/pluginservice/pluginservice.go index 76c8f5cbe0..f5c7f40818 100644 --- a/desktop/internal/pluginservice/pluginservice.go +++ b/desktop/internal/pluginservice/pluginservice.go @@ -44,7 +44,7 @@ type Kernel interface { pluginbackend.Kernel pluginsettings.Kernel ReadInstalledPluginSettingsState(context.Context, json.RawMessage, string, string) (core.PluginSettingsState, error) - ValidatePluginNativeData(ctx context.Context, declaration, data json.RawMessage) (json.RawMessage, error) + ApplyPluginViewResult(ctx context.Context, manifest json.RawMessage, surface core.PluginViewSurface, view, result json.RawMessage) (json.RawMessage, bool, error) SelectInstalledPluginVersions(context.Context, []core.InstalledPluginFact, bool) (core.InstalledPluginSelection, error) pluginmanager.Kernel ExpandPluginWorkspaceConfiguration(context.Context, json.RawMessage, string, map[string]json.RawMessage, map[string]json.RawMessage) (json.RawMessage, error) diff --git a/desktop/internal/pluginservice/pluginservice_test.go b/desktop/internal/pluginservice/pluginservice_test.go index e7d2547a49..d3b10fe849 100644 --- a/desktop/internal/pluginservice/pluginservice_test.go +++ b/desktop/internal/pluginservice/pluginservice_test.go @@ -446,8 +446,8 @@ func (k *fakeKernel) ReadInstalledPluginSettingsState(ctx context.Context, manif return core.NewClient().ReadInstalledPluginSettingsState(ctx, manifest, id, version) } -func (k *fakeKernel) ValidatePluginNativeData(ctx context.Context, declaration, data json.RawMessage) (json.RawMessage, error) { - return core.NewClient().ValidatePluginNativeData(ctx, declaration, data) +func (k *fakeKernel) ApplyPluginViewResult(ctx context.Context, manifest json.RawMessage, surface core.PluginViewSurface, view, result json.RawMessage) (json.RawMessage, bool, error) { + return core.NewClient().ApplyPluginViewResult(ctx, manifest, surface, view, result) } func (k *fakeKernel) InvokePluginFunction(context.Context, string, string, string, string, json.RawMessage) (string, error) { diff --git a/desktop/internal/pluginservice/settings_editor.go b/desktop/internal/pluginservice/settings_editor.go index d28ebfe91f..2776730425 100644 --- a/desktop/internal/pluginservice/settings_editor.go +++ b/desktop/internal/pluginservice/settings_editor.go @@ -222,11 +222,20 @@ func (e SettingsEditor) SettingsOwner() core.PluginSettingsOwner { return core.PluginSettingsOwner{PluginID: e.entry.Installed.ID, Version: e.entry.Installed.Version} } +// Package is the installed package directory the editor was read from, which a region's +// canvas reads its images from. It is read only. +func (e SettingsEditor) Package() string { + return e.entry.Installed.Path +} + // SettingsPages captures a bounded catalog off the window thread. Core owns // enabled filtering, placement, grouping, ordering and display-name resolution. -func (s *Service) SettingsPages(ctx context.Context) ([]core.SettingsPage, error) { +// language (a code such as zh-Hans; empty for none) translates section headings and +// adds each region's translated keywords: when Core reports a translation to read, +// the package's candidates are read once and the catalog is asked again with them. +func (s *Service) SettingsPages(ctx context.Context, language string) ([]core.SettingsPage, error) { kernel, ok := s.kernel.(interface { - SettingsPages(context.Context, []core.SettingsContribution) ([]core.SettingsPage, error) + SettingsPages(context.Context, []core.SettingsContribution, string) ([]core.SettingsPage, error) }) if !ok { return nil, ErrAssembly @@ -239,6 +248,7 @@ func (s *Service) SettingsPages(ctx context.Context) ([]core.SettingsPage, error return nil, errors.New("settings catalog exceeds package read budget") } contributions := make([]core.SettingsContribution, 0, len(entries)) + directories := make(map[string]string, len(entries)) var failures []error for _, entry := range entries { manifest, err := configfile.Capture(ctx, entry.Installed.Path, pluginpkg.ManifestFile, MaxManifestBytes) @@ -251,8 +261,40 @@ func (s *Service) SettingsPages(ctx context.Context) ([]core.SettingsPage, error continue } contributions = append(contributions, core.SettingsContribution{Manifest: manifest.Bytes(), Owner: core.PluginSettingsOwner{PluginID: entry.Installed.ID, Version: entry.Installed.Version}, Enabled: entry.Enabled}) + directories[entry.Installed.ID] = entry.Installed.Path + } + pages, err := kernel.SettingsPages(ctx, contributions, language) + if err != nil || language == "" { + return pages, errors.Join(append(failures, err)...) + } + // A plugin contributes to several pages with one translation, so its report is read once. + plans := make(map[string]core.PluginSettingsLocalization) + for _, page := range pages { + for _, contributor := range page.Contributors { + if contributor.Localization != nil && contributor.Localization.ReadRequired { + plans[contributor.PluginID] = *contributor.Localization + } + } + } + if len(plans) == 0 { + return pages, errors.Join(failures...) + } + for index := range contributions { + id := contributions[index].Owner.PluginID + plan, ok := plans[id] + if !ok { + continue + } + // An unreadable translation leaves the manifest's headings and keywords; the plugin's + // settings form reads the same files and reports them when it loads. + files, _, readErr := pluginsettings.ReadTranslations(ctx, directories[id], plan) + if readErr != nil { + return pages, errors.Join(append(failures, readErr)...) + } + // A read that found no file is an empty map, so Core does not ask for it again. + contributions[index].Localizations = files } - pages, err := kernel.SettingsPages(ctx, contributions) + pages, err = kernel.SettingsPages(ctx, contributions, language) return pages, errors.Join(append(failures, err)...) } diff --git a/desktop/internal/pluginservice/toolwindows.go b/desktop/internal/pluginservice/toolwindows.go index b0155f65be..01dac1ef3e 100644 --- a/desktop/internal/pluginservice/toolwindows.go +++ b/desktop/internal/pluginservice/toolwindows.go @@ -6,9 +6,7 @@ import ( "errors" "fmt" "path/filepath" - "slices" "sort" - "strings" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginmanager" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginpkg" @@ -35,273 +33,14 @@ type ToolWindow struct { Text string // Web is the package-relative entry document of a web window. Web string - // Native is the host-rendered content of a native window; nil for the other kinds. - Native *NativePanel + // View is the backend view function that draws the window's body for each view event + // (pluginview); empty for the other kinds. + View string // IconHost is the declared host icon ID ("database", "git", ...), empty when the window // declares none. Package resources are not read as icons. IconHost string } -// NativePanel is a host-rendered tree or list of literal nodes, with actions that call plugin -// functions. The host draws every control; the plugin supplies only the data and the handlers. -type NativePanel struct { - // Kind is "tree" or "list". - Kind string - Nodes []NativeNode - // Form is the declared form of a form panel; nil for tree and list panels. - Form *NativeForm - // Source, when set, supplies the nodes: a function of the plugin, called for the one detected instance - // of a build system, instead of the literal Nodes. - Source *NativeSource - // Actions are the handlers the toolbar and context menu reference, by ID. - Actions []NativeAction - Toolbar []string - ContextMenu []string - // Declaration is the window's native object as the manifest declares it. Core checks source replies - // against it, so the host never validates node data itself. - Declaration json.RawMessage -} - -// NativeForm is a form panel's controls and buttons. Layout is the column count when the form declares -// one, else 1; the host lays the controls out in order. -type NativeForm struct { - Controls []NativeControl - Buttons []NativeFormButton - Columns int -} - -// NativeControl is one field of a form. Value is a string, a boolean or a number, by kind. -type NativeControl struct { - ID string - Label string - Kind string - Value any - Placeholder string - Enabled bool - Info string - Options []NativeOption - Rows int - Minimum float64 - Maximum float64 - Step float64 - // OnCommit names the action a change of the field calls with every field's value; empty keeps the field local. - OnCommit string - // Span is how many of the form's columns the field takes; 1 when the form declares no layout. - Span int -} - -// NativeOption is one choice of a select or segmented control. -type NativeOption struct { - ID string - Label string -} - -// NativeFormButton is a button of a form that runs a declared action with the form's values. Info is the -// text of the information icon beside it, empty when the button declares none. -type NativeFormButton struct { - ID string - Label string - Action string - Primary bool - Enabled bool - Info string -} - -// NativeSource names the build system whose single instance a source panel reads, and the function that -// returns its nodes. -type NativeSource struct { - BuildSystemID string - Function string -} - -// NativeNode is one row of a native panel. -type NativeNode struct { - ID string `json:"id"` - Label string `json:"label"` - Children []NativeNode `json:"children,omitempty"` -} - -// NativeAction is one handler of a native panel. Refresh redraws the panel; invoke calls Function with -// the selected node's ID. -type NativeAction struct { - ID string - Title string - Kind string - RequiresSelection bool - Function string - // Icon is the declared host icon ID ("refresh", "reset", ...); empty when the action declares none. - Icon string -} - -// nativeActionIcons maps the action IDs of a native declaration to their declared host icon IDs. The -// declaration was checked by Core, so only the icon field is read here. -func nativeActionIcons(raw json.RawMessage) map[string]string { - var declared struct { - Actions []struct { - ID string `json:"id"` - Icon *struct { - Host string `json:"host"` - } `json:"icon"` - } `json:"actions"` - } - icons := map[string]string{} - if json.Unmarshal(raw, &declared) != nil { - return icons - } - for _, action := range declared.Actions { - if action.Icon != nil { - icons[action.ID] = action.Icon.Host - } - } - return icons -} - -// Native schema limits, from the contract's native schema 1. -const ( - maxNativeNodes = 2000 - maxNativeDepth = 16 - maxNativeAction = 64 -) - -// nativeIDPattern reports whether an ID is ASCII letters, digits or "._-" within 128 bytes. -func validNativeID(id string) bool { - if id == "" || len(id) > 128 { - return false - } - for i := 0; i < len(id); i++ { - c := id[i] - switch { - case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c >= '0' && c <= '9', c == '.', c == '_', c == '-': - default: - return false - } - } - return true -} - -// decodeNativePanel validates a native declaration against the schema limits. A declaration that -// breaks them is refused as a whole; the other windows of the plugin still load. -func decodeNativePanel(raw json.RawMessage) (*NativePanel, error) { - var declared struct { - Kind string `json:"kind"` - Nodes []json.RawMessage `json:"nodes"` - Actions []struct { - ID string `json:"id"` - Title string `json:"title"` - Kind string `json:"kind"` - RequiresSelection bool `json:"requiresSelection"` - Function string `json:"function"` - } `json:"actions"` - Toolbar []struct { - Action string `json:"action"` - } `json:"toolbar"` - ContextMenu []string `json:"contextMenu"` - Source *struct { - BuildSystemID string `json:"buildSystemID"` - Function string `json:"function"` - } `json:"source"` - } - if err := json.Unmarshal(raw, &declared); err != nil { - return nil, err - } - var source *NativeSource - if declared.Source != nil { - if strings.TrimSpace(declared.Source.BuildSystemID) == "" || !validFunctionID(declared.Source.Function) { - return nil, errors.New("a native source names a build system and a function ID") - } - source = &NativeSource{BuildSystemID: declared.Source.BuildSystemID, Function: declared.Source.Function} - } - if declared.Kind == "form" { - return decodeNativeForm(raw, declared.Actions, source) - } - if declared.Kind != "tree" && declared.Kind != "list" { - return nil, fmt.Errorf("native kind %q is not supported", declared.Kind) - } - if len(declared.Actions) > maxNativeAction { - return nil, errors.New("a native panel declares too many actions") - } - panel := &NativePanel{Kind: declared.Kind} - icons := nativeActionIcons(raw) - count := 0 - nodes, err := decodeNativeNodes(declared.Nodes, 0, &count, declared.Kind == "list") - if err != nil { - return nil, err - } - panel.Nodes = nodes - panel.Source = source - actions := map[string]bool{} - for _, action := range declared.Actions { - if !validNativeID(action.ID) || action.Title == "" { - return nil, errors.New("a native action needs a valid ID and a title") - } - if actions[action.ID] { - return nil, fmt.Errorf("native action %q is declared twice", action.ID) - } - actions[action.ID] = true - switch action.Kind { - case "refresh": - if action.RequiresSelection || action.Function != "" { - return nil, errors.New("a refresh action selects nothing and names no function") - } - case "invoke": - if !validFunctionID(action.Function) { - return nil, errors.New("an invoke action names a function ID") - } - default: - return nil, fmt.Errorf("native action kind %q is not supported", action.Kind) - } - panel.Actions = append(panel.Actions, NativeAction{ID: action.ID, Title: action.Title, Kind: action.Kind, RequiresSelection: action.RequiresSelection, Function: action.Function, Icon: icons[action.ID]}) - } - for _, entry := range declared.Toolbar { - if !actions[entry.Action] { - return nil, fmt.Errorf("the toolbar names the undeclared action %q", entry.Action) - } - panel.Toolbar = append(panel.Toolbar, entry.Action) - } - for _, id := range declared.ContextMenu { - if !actions[id] { - return nil, fmt.Errorf("the context menu names the undeclared action %q", id) - } - panel.ContextMenu = append(panel.ContextMenu, id) - } - return panel, nil -} - -// decodeNativeNodes reads a node list. Nodes need a valid ID and a non-blank label of at most 1024 bytes. -// A list takes no children; the whole tree stays within the node and depth limits. -func decodeNativeNodes(raw []json.RawMessage, depth int, count *int, flat bool) ([]NativeNode, error) { - if depth > maxNativeDepth { - return nil, errors.New("a native panel nests deeper than the limit") - } - var nodes []NativeNode - for _, item := range raw { - var declared struct { - ID string `json:"id"` - Label string `json:"label"` - Children []json.RawMessage `json:"children"` - } - if err := json.Unmarshal(item, &declared); err != nil { - return nil, err - } - *count++ - if *count > maxNativeNodes { - return nil, errors.New("a native panel has too many nodes") - } - if !validNativeID(declared.ID) || strings.TrimSpace(declared.Label) == "" || len(declared.Label) > 1024 { - return nil, errors.New("a native node needs a valid ID and a label") - } - if flat && len(declared.Children) > 0 { - return nil, errors.New("a native list takes no children") - } - children, err := decodeNativeNodes(declared.Children, depth+1, count, flat) - if err != nil { - return nil, err - } - nodes = append(nodes, NativeNode{ID: declared.ID, Label: declared.Label, Children: children}) - } - return nodes, nil -} - // ToolWindows reads the tool windows of every enabled plugin, ordered by // plugin ID, then by the declared order and ID. A broken manifest is // reported without hiding the others. @@ -323,13 +62,15 @@ func (s *Service) ToolWindows(ctx context.Context, entries []pluginmanager.Entry DisplayName string `json:"displayName"` UI struct { ToolWindows []struct { - ID string `json:"id"` - Title string `json:"title"` - Placement string `json:"placement"` - Order int `json:"order"` - Text string `json:"text"` - Native json.RawMessage `json:"native"` - Web *struct { + ID string `json:"id"` + Title string `json:"title"` + Placement string `json:"placement"` + Order int `json:"order"` + Text string `json:"text"` + View *struct { + Function string `json:"function"` + } `json:"view"` + Web *struct { Entry string `json:"entry"` } `json:"web"` Icon *struct { @@ -358,14 +99,8 @@ func (s *Service) ToolWindows(ctx context.Context, entries []pluginmanager.Entry if window.Icon != nil { declaredWindow.IconHost = window.Icon.Host } - if len(window.Native) > 0 { - panel, err := decodeNativePanel(window.Native) - if err != nil { - failures = append(failures, fmt.Errorf("%s: %w", entry.Installed.ID, err)) - continue - } - panel.Declaration = window.Native - declaredWindow.Native = panel + if window.View != nil { + declaredWindow.View = window.View.Function } windows = append(windows, declaredWindow) } @@ -379,171 +114,3 @@ func (s *Service) ToolWindows(ctx context.Context, entries []pluginmanager.Entry } return windows, errors.Join(failures...) } - -// decodeNativeForm reads a form declaration against the schema: at most 32 controls and 16 buttons, unique -// IDs, a literal label, a known kind, options for the choice kinds, and bounds for the stepper. A button -// names a declared action that selects nothing. A form declares no nodes; its optional source is called -// with the form's values and answers {nodes: []}, which the host never shows. -func decodeNativeForm(raw json.RawMessage, actions []struct { - ID string `json:"id"` - Title string `json:"title"` - Kind string `json:"kind"` - RequiresSelection bool `json:"requiresSelection"` - Function string `json:"function"` -}, source *NativeSource) (*NativePanel, error) { - var declared struct { - Nodes []json.RawMessage `json:"nodes"` - Layout *struct { - Columns int `json:"columns"` - } `json:"layout"` - Controls []struct { - ID string `json:"id"` - Label string `json:"label"` - Kind string `json:"kind"` - Value any `json:"value"` - Placeholder string `json:"placeholder"` - Enabled *bool `json:"enabled"` - Info string `json:"info"` - Options []struct { - ID string `json:"id"` - Label string `json:"label"` - } `json:"options"` - Rows int `json:"rows"` - Minimum *float64 `json:"minimum"` - Maximum *float64 `json:"maximum"` - Step *float64 `json:"step"` - OnCommit string `json:"onCommit"` - Span int `json:"span"` - } `json:"controls"` - Buttons []struct { - ID string `json:"id"` - Label string `json:"label"` - Action string `json:"action"` - Primary bool `json:"primary"` - Enabled *bool `json:"enabled"` - Info string `json:"info"` - } `json:"buttons"` - } - if err := json.Unmarshal(raw, &declared); err != nil { - return nil, err - } - if len(declared.Nodes) != 0 { - return nil, errors.New("a form declares no nodes") - } - if len(declared.Controls) > 32 || len(declared.Buttons) > 16 || len(declared.Controls)+len(declared.Buttons) == 0 { - return nil, errors.New("a form needs one to 32 controls and at most 16 buttons") - } - columns := 1 - if declared.Layout != nil { - if declared.Layout.Columns < 1 || declared.Layout.Columns > 12 { - return nil, errors.New("a form layout has one to 12 columns") - } - columns = declared.Layout.Columns - } - form := &NativeForm{Columns: columns} - ids := map[string]bool{} - for _, control := range declared.Controls { - if !validNativeID(control.ID) || ids[control.ID] || strings.TrimSpace(control.Label) == "" || len(control.Label) > 256 { - return nil, errors.New("a form control needs a unique valid ID and a label") - } - ids[control.ID] = true - item := NativeControl{ID: control.ID, Label: control.Label, Kind: control.Kind, Value: control.Value, Placeholder: control.Placeholder, Enabled: control.Enabled == nil || *control.Enabled, Info: control.Info, OnCommit: control.OnCommit, Span: 1} - if control.Kind == "editor" && control.OnCommit != "" { - return nil, errors.New("an editor control takes no onCommit") - } - if declared.Layout == nil && control.Span != 0 { - return nil, errors.New("a span needs the form's layout") - } - if declared.Layout != nil { - if control.Span == 0 { - item.Span = columns - } else if control.Span < 1 || control.Span > columns { - return nil, errors.New("a control's span is outside the form's columns") - } else { - item.Span = control.Span - } - } - switch control.Kind { - case "input", "search", "editor": - if _, ok := control.Value.(string); !ok && control.Value != nil { - return nil, fmt.Errorf("the %s control %q takes a string", control.Kind, control.ID) - } - if control.Kind == "editor" { - item.Rows = control.Rows - if item.Rows == 0 { - item.Rows = 4 - } - if item.Rows < 2 || item.Rows > 12 { - return nil, errors.New("an editor control has two to 12 rows") - } - } - case "select", "segmented": - if len(control.Options) == 0 || (control.Kind == "segmented" && len(control.Options) > 8) || len(control.Options) > 128 { - return nil, fmt.Errorf("the %s control %q needs options within the limits", control.Kind, control.ID) - } - for _, option := range control.Options { - if !validNativeID(option.ID) || strings.TrimSpace(option.Label) == "" { - return nil, errors.New("a form option needs a valid ID and a label") - } - item.Options = append(item.Options, NativeOption{ID: option.ID, Label: option.Label}) - } - if text, ok := control.Value.(string); !ok || !slices.ContainsFunc(item.Options, func(o NativeOption) bool { return o.ID == text }) { - return nil, fmt.Errorf("the %s control %q takes one of its options", control.Kind, control.ID) - } - case "checkbox": - if _, ok := control.Value.(bool); !ok { - return nil, fmt.Errorf("the checkbox control %q takes a boolean", control.ID) - } - case "stepper": - number, ok := control.Value.(float64) - if !ok || control.Minimum == nil || control.Maximum == nil || control.Step == nil || *control.Step <= 0 { - return nil, fmt.Errorf("the stepper control %q needs a number, bounds and a positive step", control.ID) - } - if number < *control.Minimum || number > *control.Maximum { - return nil, fmt.Errorf("the stepper control %q is outside its bounds", control.ID) - } - item.Minimum, item.Maximum, item.Step = *control.Minimum, *control.Maximum, *control.Step - default: - return nil, fmt.Errorf("the form control kind %q is not supported", control.Kind) - } - form.Controls = append(form.Controls, item) - } - declaredActions := map[string]struct { - kind string - selects bool - function string - }{} - for _, action := range actions { - declaredActions[action.ID] = struct { - kind string - selects bool - function string - }{action.Kind, action.RequiresSelection, action.Function} - } - for index := range form.Controls { - commit := form.Controls[index].OnCommit - if commit == "" { - continue - } - target, ok := declaredActions[commit] - if !ok || target.selects || target.kind != "invoke" { - return nil, fmt.Errorf("the onCommit of %q names no declared invoke action that selects nothing", form.Controls[index].ID) - } - } - for _, button := range declared.Buttons { - if !validNativeID(button.ID) || ids[button.ID] || strings.TrimSpace(button.Label) == "" { - return nil, errors.New("a form button needs a unique valid ID and a label") - } - ids[button.ID] = true - target, ok := declaredActions[button.Action] - if !ok || target.selects { - return nil, fmt.Errorf("the button %q names no declared action that selects nothing", button.ID) - } - form.Buttons = append(form.Buttons, NativeFormButton{ID: button.ID, Label: button.Label, Action: button.Action, Primary: button.Primary, Enabled: button.Enabled == nil || *button.Enabled, Info: button.Info}) - } - panel := &NativePanel{Kind: "form", Form: form, Source: source} - for _, action := range actions { - panel.Actions = append(panel.Actions, NativeAction{ID: action.ID, Title: action.Title, Kind: action.Kind, RequiresSelection: action.RequiresSelection, Function: action.Function}) - } - return panel, nil -} diff --git a/desktop/internal/pluginview/canvas.go b/desktop/internal/pluginview/canvas.go new file mode 100644 index 0000000000..816adaf4ce --- /dev/null +++ b/desktop/internal/pluginview/canvas.go @@ -0,0 +1,696 @@ +package pluginview + +import ( + "math" + "slices" + "strconv" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/icons" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// A canvas draws its scene in view-box coordinates scaled to the width of the view: at zoom +// 1 the view box's width fills the canvas, and its top edge is at the canvas's top. The user +// drags the empty area to pan (pan) and zooms with ⌘ or Control and the wheel, about the +// pointer, or with the host's zoom buttons, about the middle (zoom). The plain wheel scrolls +// the page. A scene narrower than the canvas is centered; one shorter starts at the top. +// There is no pinch to zoom: Viva reports no trackpad magnify yet (#2182). +const ( + // canvasZoomStep is how far a zoom button zooms. + canvasZoomStep = 1.25 + // canvasWheelZoom is how far a point of the wheel zooms: by exp(-delta*canvasWheelZoom). + canvasWheelZoom = 0.01 + // canvasTooltipDelay is how long the pointer rests on a group before its tooltip shows. + canvasTooltipDelay = 500 * time.Millisecond + // canvasMinTextSize is the smallest text in pixels the canvas draws; smaller text, + // zoomed far out, cannot be read and is left out. + canvasMinTextSize = 4 +) + +// canvasState is the host's state of one canvas: where the user panned and zoomed it, the +// drag under way, and the groups the pointer rests on. It lives in memory and ends with the +// showing. +type canvasState struct { + // zoom is the user's zoom, 1 at the view's width; x and y are the view-box point at the + // canvas's top-left corner. placed reports that x and y were set. + zoom, x, y float64 + placed bool + + dragging bool + from gfx.Point + fromX, fromY float64 + + // rect is where the canvas was drawn last. + rect gfx.Rect + // node, host and session are those of the last paint, for the handlers that run between + // paints. + node *Node + host *Host + session *Session + + input ui.Handlers + draw func(*ui.DrawContext) + made bool + + // keys number the clickable groups' IDs in the order they were first drawn, so a group + // keeps its part, and its focus, as the scene changes around it; ids are the reverse. + keys map[string]int + ids []string + + // pointer is the part the pointer is over, -1 for none; hover is the part whose tooltip + // is timed, and since when. + pointer, hover int + since time.Duration + // tip is the tooltip of the hovered group and anchor its rectangle, found in each draw. + tip string + anchor gfx.Rect + lines []string +} + +// make gives the state its handlers and draw function, once. +func (s *canvasState) make() { + s.made, s.pointer, s.hover = true, -1, -1 + s.keys = map[string]int{} + s.input = ui.Handlers{Scroll: s.scroll, Pointer: s.pointerEvent} + s.draw = s.paint +} + +// key is the stable part number of a clickable group, given on first sight. +func (s *canvasState) key(id string) int { + key, ok := s.keys[id] + if !ok { + key = len(s.ids) + s.keys[id] = key + s.ids = append(s.ids, id) + } + return key +} + +// zoomRange is the zoom range of n, [1, 1] for a canvas without zoom. +func zoomRange(n *Node) (low, high float64) { + if n.Zoom == nil { + return 1, 1 + } + return n.Zoom[0], n.Zoom[1] +} + +// scale is how many pixels one view-box unit takes in rect at the state's zoom; 0 for a +// view box without area, which draws nothing. +func (s *canvasState) scale(rect gfx.Rect, n *Node) float64 { + if n.ViewBox[2] <= 0 || n.ViewBox[3] <= 0 || rect.Width <= 0 { + return 0 + } + return float64(rect.Width) / n.ViewBox[2] * s.zoom +} + +// clamp keeps the visible part inside the view box: a view box narrower than the canvas +// is centered across it, one shorter than the canvas starts at its top. +func (s *canvasState) clamp(rect gfx.Rect, n *Node) { + k := s.scale(rect, n) + if k <= 0 { + return + } + box := n.ViewBox + if !s.placed { + s.x, s.y, s.placed = box[0], box[1], true + } + width, height := float64(rect.Width)/k, float64(rect.Height)/k + if width >= box[2] { + s.x = box[0] - (width-box[2])/2 + } else { + s.x = math.Min(math.Max(s.x, box[0]), box[0]+box[2]-width) + } + if height >= box[3] { + s.y = box[1] + } else { + s.y = math.Min(math.Max(s.y, box[1]), box[1]+box[3]-height) + } +} + +// zoomAt zooms to zoom, within the canvas's range, keeping the view-box point under the +// pixel (px, py) where it is. It reports whether the zoom changed. +func (s *canvasState) zoomAt(rect gfx.Rect, n *Node, zoom float64, px, py float32) bool { + low, high := zoomRange(n) + zoom = math.Min(math.Max(zoom, low), high) + before := s.scale(rect, n) + if zoom == s.zoom || before <= 0 { + return false + } + s.clamp(rect, n) + dx, dy := float64(px-rect.X), float64(py-rect.Y) + vx, vy := s.x+dx/before, s.y+dy/before + s.zoom = zoom + after := s.scale(rect, n) + s.x, s.y = vx-dx/after, vy-dy/after + s.clamp(rect, n) + return true +} + +// viewport is the visible part of the canvas in view-box coordinates. +func (s *canvasState) viewport(rect gfx.Rect, n *Node) Viewport { + k := s.scale(rect, n) + if k <= 0 { + return Viewport{} + } + return Viewport{X: s.x, Y: s.y, Width: float64(rect.Width) / k, Height: float64(rect.Height) / k} +} + +// moved tells the plugin where the canvas now lies, once it stops moving, when it asked. +func (s *canvasState) moved() { + if s.node != nil && slices.Contains(s.node.On, "viewport") { + s.session.ViewportMoved(s.node.ID, s.viewport(s.rect, s.node)) + } +} + +// scroll zooms about the pointer for ⌘ or Control and the wheel, and leaves the plain +// wheel to the page around the canvas. +func (s *canvasState) scroll(event gfx.ScrollEvent) gfx.EventResult { + n := s.node + if n == nil || n.Zoom == nil || event.Modifiers&(gfx.ModifierControl|gfx.ModifierMeta) == 0 { + return gfx.EventResult{} + } + if s.zoomAt(s.rect, n, s.zoom*math.Exp(-float64(event.DeltaY)*canvasWheelZoom), event.X, event.Y) { + s.moved() + } + return gfx.EventResult{Handled: true, Repaint: true} +} + +// pointerEvent drags the empty area to pan and notes the group the pointer is over. An +// event aimed at a group stays unhandled, so the page presses, clicks and focuses it. +func (s *canvasState) pointerEvent(event gfx.PointerEvent) gfx.EventResult { + n := s.node + if n == nil { + return gfx.EventResult{} + } + part, onPart := event.Target.In(s.input.Parts()) + switch event.Kind { + case gfx.PointerDown: + if !n.Pan || onPart || event.Button != gfx.PointerButtonPrimary { + return gfx.EventResult{} + } + s.dragging, s.from, s.fromX, s.fromY = true, gfx.Point{X: event.X, Y: event.Y}, s.x, s.y + return gfx.EventResult{Handled: true} + case gfx.PointerMove: + if s.dragging { + if k := s.scale(s.rect, n); k > 0 { + s.x = s.fromX - float64(event.X-s.from.X)/k + s.y = s.fromY - float64(event.Y-s.from.Y)/k + s.clamp(s.rect, n) + s.moved() + } + return gfx.EventResult{Handled: true, Repaint: true} + } + over := -1 + if onPart { + over = part + } + if over != s.pointer { + s.pointer = over + return gfx.EventResult{Repaint: true} + } + case gfx.PointerUp: + if s.dragging { + s.dragging = false + return gfx.EventResult{Handled: true, Repaint: true} + } + case gfx.PointerExit: + if s.dragging && !event.Captured { + s.dragging = false + } + if !s.dragging && s.pointer >= 0 { + s.pointer = -1 + return gfx.EventResult{Repaint: true} + } + } + return gfx.EventResult{} +} + +// canvas declares a canvas: the zoom buttons above it when it zooms, then the scene, and +// sends click for a group clicked or activated with Enter or Space. +func (r *renderer) canvas(c ui.C, n *Node) { + state := r.s.canvas(n.ID) + if !state.made { + state.make() + } + state.node, state.host, state.session = n, r.host, r.s + ui.Column(c).FillWidth().Gap(4).Children(func() { + if n.Zoom != nil { + r.zoomButtons(c, state) + } + ui.Control(c.Part("canvas"), n.Label, &state.input).FillWidth().Height(float32(n.Height)).Clip().Draw(state.draw) + }) + canvas := c.Canvas() + if canvas == nil { + return + } + if i, ok := canvas.ClickedIn(state.input.Parts()); ok && i < len(state.ids) { + r.s.Send(Event{Name: "click", Canvas: n.ID, Node: state.ids[i]}) + } + // The tooltip shows once the pointer has rested on a group for canvasTooltipDelay. + now := canvas.Now() + if state.pointer != state.hover { + state.hover, state.since = state.pointer, now + } + if state.hover >= 0 { + if left := canvasTooltipDelay - (now - state.since); left > 0 { + canvas.RequestFrameIn(left) + } + } +} + +// zoomButtons declares the zoom buttons over the canvas's trailing edge: zoom out, the +// percentage, which resets the zoom to 100%, and zoom in. They zoom about the middle. +func (r *renderer) zoomButtons(c ui.C, state *canvasState) { + p := &r.host.Palette + language := r.host.Language + zoomTo := func(zoom float64) { + c.After(func() { + rect := state.rect + if state.zoomAt(rect, state.node, zoom, rect.X+rect.Width/2, rect.Y+rect.Height/2) { + state.moved() + } + }) + } + ui.Row(c.Part("zoom")).FillWidth().Items(ui.Center).Justify(ui.End).Gap(2).Children(func() { + if zoomButton(c.Part("zoom-out"), i18n.Shared(language, "desktop.viewer.zoomOut"), icons.ZoomOut) { + zoomTo(state.zoom / canvasZoomStep) + } + k := c.Part("zoom-reset") + percent := strconv.Itoa(int(math.Round(state.zoom*100))) + "%" + button := ui.Row(k).Size(44, 26).Shrink(0).Center().Radius(6). + HitWith(ui.ID(k), i18n.Shared(language, "desktop.pluginView.zoom"), gfx.HitOptions{ + Role: gfx.RoleButton, Value: percent, Hint: i18n.Shared(language, "desktop.pluginView.resetZoomHint"), Cursor: gfx.PointerCursorHand, + }). + Hover(ui.Look{}.Background(p.Hover)).Pressed(ui.Look{}.Background(p.Selection)). + Tooltip(i18n.Shared(language, "desktop.pluginView.resetZoom")) + button.Children(func() { + ui.Text(k, percent).FontSize(11).Weight(gfx.WeightMedium).Mono().Color(p.Text) + }) + if button.Clicked() { + zoomTo(1) + } + if zoomButton(c.Part("zoom-in"), i18n.Shared(language, "desktop.viewer.zoomIn"), icons.ZoomIn) { + zoomTo(state.zoom * canvasZoomStep) + } + }) +} + +// zoomButton declares one icon button of the zoom buttons and reports a click. +func zoomButton(c ui.C, label string, icon gfx.Icon) bool { + return ui.Button(c, label).Icon(icon).IconOnly().Ghost().Size(26, 26).Shrink(0).Tooltip(label).Clicked() +} + +// place maps view-box coordinates to pixels: pixel = origin + point × k. +type place struct { + ox, oy, k float64 +} + +func (t place) point(x, y float64) (float32, float32) { + return float32(t.ox + x*t.k), float32(t.oy + y*t.k) +} + +func (t place) rect(x, y, w, h float64) gfx.Rect { + left, top := t.point(x, y) + return gfx.Rect{X: left, Y: top, Width: float32(w * t.k), Height: float32(h * t.k)} +} + +// inner is the place of a group's children: they start at (x, y) and are scale times as large. +func (t place) inner(x, y, scale float64) place { + return place{ox: t.ox + x*t.k, oy: t.oy + y*t.k, k: t.k * scale} +} + +// scaled is t scaled by scale about the middle of the w × h area at its origin. +func (t place) scaled(w, h, scale float64) place { + if scale == 1 { + return t + } + return place{ox: t.ox + t.k*(w/2)*(1-scale), oy: t.oy + t.k*(h/2)*(1-scale), k: t.k * scale} +} + +// painter draws one canvas scene in one draw. +type painter struct { + d *ui.DrawContext + state *canvasState + p *Palette + parts gfx.Scope +} + +// paint draws the scene, the hovered group's tooltip over it, and nothing for a view box +// without area. It only paints: Viva may call it more than once a frame. +func (s *canvasState) paint(d *ui.DrawContext) { + n := s.node + if n == nil || s.host == nil { + return + } + s.rect = d.Rect + s.clamp(d.Rect, n) + k := s.scale(d.Rect, n) + if k <= 0 { + return + } + s.tip = "" + pt := &painter{d: d, state: s, p: &s.host.Palette, parts: s.input.Parts()} + at := place{ox: float64(d.Rect.X) - s.x*k, oy: float64(d.Rect.Y) - s.y*k, k: k} + pt.shapes(n.Nodes, at, d.Opacity) + if s.tip != "" && s.hover >= 0 && d.Canvas.Now()-s.since >= canvasTooltipDelay { + pt.tooltip(s.tip, s.anchor) + } +} + +// shapes draws shapes in order. +func (pt *painter) shapes(shapes []Shape, at place, opacity float32) { + for i := range shapes { + pt.shape(&shapes[i], at, opacity) + } +} + +// shape draws one shape. +func (pt *painter) shape(sh *Shape, at place, opacity float32) { + opacity *= sh.opacity() + if opacity <= 0 { + return + } + switch sh.Type { + case "rect": + bounds := at.rect(sh.X, sh.Y, sh.W, sh.H) + pt.area(bounds, float32(sh.Radius*at.k), sh.Fill, sh.Stroke, float32(sh.strokeWidth()*at.k), len(sh.Dash) > 0, sh.Shadow, opacity) + case "path": + pt.path(sh, at, opacity) + case "text": + pt.text(sh, at, opacity) + case "image": + // DrawBitmap takes no opacity, so an image is drawn opaque until Viva has one (#2182). + if bitmap, ok := pt.state.host.Images.bitmap(sh.Src); ok { + pt.d.Canvas.DrawBitmap(bitmap, at.rect(sh.X, sh.Y, sh.W, sh.H)) + } + case "group": + pt.group(sh, at, opacity) + } +} + +// area paints a rounded rectangle: its shadow, its fill (a color or a gradient), then its +// stroke, dashed or solid. +func (pt *painter) area(bounds gfx.Rect, radius float32, fill, stroke *Color, width float32, dashed bool, shadow int, opacity float32) { + canvas := pt.d.Canvas + if level, ok := shadowLevel(shadow); ok { + canvas.ElevateFaded(bounds, radius, level, opacity) + } + if stops := pt.p.Stops(fill, opacity); stops != nil { + canvas.FillGradient(bounds, radius, float32(fill.Angle), stops) + } else if color, ok := pt.p.Solid(fill); ok { + canvas.Rounded(bounds, radius, fade(color, opacity)) + } + if color, ok := pt.p.Solid(stroke); ok && width > 0 { + if dashed { + canvas.DashedRoundedOutline(bounds, radius, width, fade(color, opacity)) + } else { + canvas.RoundedOutline(bounds, radius, width, fade(color, opacity)) + } + } +} + +// shadowLevel is the host shadow of an elevation step 1–3; ok is false for none. +func shadowLevel(step int) (gfx.ShadowLevel, bool) { + switch step { + case 1: + return gfx.ShadowSM, true + case 2: + return gfx.ShadowMD, true + case 3: + return gfx.ShadowLG, true + } + return gfx.ShadowNone, false +} + +// path draws path data: its fill, a color or a gradient over its bounds, then its stroke. +func (pt *painter) path(sh *Shape, at place, opacity float32) { + geometry := sh.geometryOf() + if geometry.empty { + return + } + style := gfx.PathStyle{Join: gfx.JoinRound} + switch sh.Rule { + case "evenodd": + style.FillRule = gfx.PathFillEvenOdd + default: + style.FillRule = gfx.PathFillNonZero + } + switch sh.Cap { + case "round": + style.Cap = gfx.CapRound + case "square": + style.Cap = gfx.CapSquare + default: + style.Cap = gfx.CapButt + } + if stops := pt.p.Stops(sh.Fill, opacity); stops != nil { + box := [4]float64{geometry.x + 1, geometry.y + 1, geometry.w - 2, geometry.h - 2} + if sh.Bounds != nil { + box = *sh.Bounds + } + style.FillGradient = pathGradient(stops, sh.Fill.Angle, box, geometry) + } else if color, ok := pt.p.Solid(sh.Fill); ok { + style.Fill = fade(color, opacity) + } + if color, ok := pt.p.Solid(sh.Stroke); ok { + style.Stroke = fade(color, opacity) + style.StrokeWidth = float32(sh.strokeWidth() * at.k) + // Viva dashes are all one length: the lengths in dash wait for Viva (#2182). + style.Dashed = len(sh.Dash) > 0 + } + pt.d.Canvas.DrawPath(geometry.path, at.rect(geometry.x, geometry.y, geometry.w, geometry.h), style) +} + +// pathGradient is the gradient of a path's fill over box, in the path's own units: the CSS +// gradient line through the middle of box at angle, between the first and the last stop. +// A Viva path gradient takes two colors, so stops between them are left out until it takes +// more (#2182). +func pathGradient(stops []gfx.GradientStop, angle float64, box [4]float64, geometry *pathGeometry) *gfx.LinearGradient { + first, last := stops[0], stops[len(stops)-1] + sin, cos := math.Sincos(angle * math.Pi / 180) + dx, dy := sin, -cos + length := math.Abs(box[2]*sin) + math.Abs(box[3]*cos) + cx, cy := box[0]+box[2]/2-geometry.x, box[1]+box[3]/2-geometry.y + sx, sy := cx-dx*length/2, cy-dy*length/2 + from, to := float64(first.At)*length, float64(last.At)*length + return &gfx.LinearGradient{ + Start: gfx.Point{X: float32(sx + dx*from), Y: float32(sy + dy*from)}, + End: gfx.Point{X: float32(sx + dx*to), Y: float32(sy + dy*to)}, + From: first.Color, + To: last.Color, + } +} + +// canvasTextStyle is the font of a canvas text style at zoom 1. +func canvasTextStyle(style string) (size float32, weight float32, mono bool) { + switch style { + case "title": + return 15, gfx.WeightSemibold, false + case "strong": + return 13, gfx.WeightSemibold, false + case "caption": + return 11, gfx.WeightRegular, false + case "display": + return 22, gfx.WeightSemibold, false + case "mono": + return 12, gfx.WeightRegular, true + case "monoSmall": + return 11, gfx.WeightRegular, true + } + return 13, gfx.WeightRegular, false +} + +// text draws one line with its baseline at y: the text, or its runs one after another, each +// in its own color. align places the line's start, middle or end at x, and a line wider than +// maxWidth is cut and ends with an ellipsis. +func (pt *painter) text(sh *Shape, at place, opacity float32) { + canvas := pt.d.Canvas + size, weight, mono := canvasTextStyle(sh.Style) + size *= float32(at.k) + if size < canvasMinTextSize { + return + } + style := gfx.TextStyle{Size: size, Weight: weight, Mono: mono} + runs := sh.Runs + if len(runs) == 0 { + runs = []Run{{Text: sh.Text, Color: sh.Color}} + } + var total float32 + for _, run := range runs { + total += canvas.TextWidthStyle(run.Text, style) + } + room := total + if sh.MaxWidth > 0 { + room = min(total, float32(sh.MaxWidth*at.k)) + } + x, baseline := at.point(sh.X, sh.Y) + switch sh.Align { + case "center": + x -= room / 2 + case "end": + x -= room + } + height := float32(math.Ceil(float64(size) * 1.5)) + left := room + for _, run := range runs { + if left <= 0 { + break + } + color := pt.p.Text + if own, ok := pt.p.Solid(run.Color); ok { + color = own + } else if own, ok := pt.p.Solid(sh.Color); ok { + color = own + } + style.Color = fade(color, opacity) + value, width := run.Text, canvas.TextWidthStyle(run.Text, style) + if width > left { + value = pt.fit(value, style, left) + width = left + } + canvas.LabelAlignedOnBaseline(value, gfx.Rect{X: x, Width: width + 1, Height: height}, baseline, style, gfx.AlignLeft) + x += width + left -= width + } +} + +// fit is value cut to width with an ellipsis, in the font of style. +func (pt *painter) fit(value string, style gfx.TextStyle, width float32) string { + if !style.Mono { + return pt.d.Canvas.FitLine(value, style.Size, style.Weight, width) + } + lines := pt.d.Canvas.WrapLinesStyle(pt.state.lines[:0], value, style, width, 1, nil) + pt.state.lines = lines + if len(lines) == 0 { + return "" + } + return lines[0] +} + +// group draws a group: a clickable one takes its w × h area as its hit, and the states +// the pointer, the focus and selected give it paint that area behind the children and +// scale and fade the whole group. +func (pt *painter) group(sh *Shape, at place, opacity float32) { + if sh.Hidden { + return + } + canvas := pt.d.Canvas + inner := at.inner(sh.X, sh.Y, sh.scale()) + look := State{Shadow: sh.Shadow} + var id gfx.ID + var state gfx.State + clickable := sh.clickable() && sh.ID != "" + if clickable { + key := pt.state.key(sh.ID) + id = pt.parts.At(key) + state = canvas.StateOf(id) + canvas.HitWithOptions(id, inner.rect(0, 0, sh.W, sh.H), sh.Label, gfx.HitOptions{ + Role: gfx.RoleButton, Cursor: gfx.PointerCursorHand, Selected: sh.Selected, + }) + if sh.States != nil { + if sh.Selected { + look.merge(sh.States.Selected) + } + if state.Hovered { + look.merge(sh.States.Hover) + } + if state.Pressed { + look.merge(sh.States.Pressed) + } + } + if key == pt.state.hover && sh.Tooltip != "" { + pt.state.tip, pt.state.anchor = sh.Tooltip, inner.rect(0, 0, sh.W, sh.H) + } + } + if look.Opacity != nil { + opacity *= float32(*look.Opacity) + } + scale := 1.0 + if look.Scale != nil { + scale = *look.Scale + } + inner = inner.scaled(sh.W, sh.H, scale) + bounds := inner.rect(0, 0, sh.W, sh.H) + radius := float32(sh.Radius * inner.k) + width := float32(1 * inner.k) + if look.Width != nil { + width = float32(*look.Width * inner.k) + } + pt.area(bounds, radius, look.Fill, look.Stroke, width, false, look.Shadow, opacity) + // Viva clips to a rectangle, so a rounded group clips square, and opacity fades each child + // rather than the group as one layer, until Viva has both (#2182). + if sh.Clip { + canvas.Clip(bounds) + } + pt.shapes(sh.Children, inner, opacity) + if sh.Clip { + canvas.Unclip() + } + if clickable && state.FocusVisible { + ring := gfx.Rect{X: bounds.X - 2, Y: bounds.Y - 2, Width: bounds.Width + 4, Height: bounds.Height + 4} + canvas.RoundedOutline(ring, radius+2, 2, pt.p.Accent) + } +} + +// merge lays state over l: what state sets replaces what l had. +func (l *State) merge(state *State) { + if state == nil { + return + } + if state.Fill != nil { + l.Fill = state.Fill + } + if state.Stroke != nil { + l.Stroke = state.Stroke + } + if state.Width != nil { + l.Width = state.Width + } + if state.Shadow != 0 { + l.Shadow = state.Shadow + } + if state.Scale != nil { + l.Scale = state.Scale + } + if state.Opacity != nil { + l.Opacity = state.Opacity + } +} + +// tooltip draws the host's tooltip bubble for text under anchor, or over it where the +// canvas has no room below, kept inside the canvas. +func (pt *painter) tooltip(text string, anchor gfx.Rect) { + canvas, rect := pt.d.Canvas, pt.d.Rect + style := gfx.TextStyle{Size: 12, Color: pt.p.PopoverText} + const padX, padY, line = 8, 5, 16 + room := min(float32(320), rect.Width-16) - 2*padX + if room <= 0 { + return + } + lines := canvas.WrapLinesStyle(pt.state.lines[:0], text, style, room, 4, nil) + pt.state.lines = lines + if len(lines) == 0 { + return + } + var widest float32 + for _, value := range lines { + widest = max(widest, canvas.TextWidthStyle(value, style)) + } + width, height := widest+2*padX, float32(len(lines))*line+2*padY + x := anchor.X + anchor.Width/2 - width/2 + x = max(rect.X+4, min(x, rect.X+rect.Width-width-4)) + y := anchor.Y + anchor.Height + 6 + if y+height > rect.Y+rect.Height-4 { + y = anchor.Y - height - 6 + } + y = max(y, rect.Y+4) + bubble := gfx.Rect{X: x, Y: y, Width: width, Height: height} + canvas.ElevateFaded(bubble, 6, gfx.ShadowMD, 1) + canvas.Rounded(bubble, 6, pt.p.Popover) + for i, value := range lines { + canvas.Label(value, gfx.Rect{X: x + padX, Y: y + padY + float32(i)*line, Width: widest + 1, Height: line}, style) + } +} diff --git a/desktop/internal/pluginview/canvas_test.go b/desktop/internal/pluginview/canvas_test.go new file mode 100644 index 0000000000..9e84ca0ba7 --- /dev/null +++ b/desktop/internal/pluginview/canvas_test.go @@ -0,0 +1,172 @@ +package pluginview + +import ( + "math" + "testing" + + "github.com/vivaui/viva/gfx" +) + +// testCanvas is a canvas node of a 400 × 400 view box that pans, zooms from half to four +// times and tells the plugin where it lies. +func testCanvas() *Node { + return &Node{ + Type: "canvas", ID: "graph", ViewBox: [4]float64{0, 0, 400, 400}, + Pan: true, Zoom: &[2]float64{0.5, 4}, On: []string{"viewport"}, + } +} + +func TestCanvasScaleFollowsTheWidthAndTheZoom(t *testing.T) { + n := testCanvas() + state := &canvasState{zoom: 1} + rect := gfx.Rect{Width: 200, Height: 100} + if got := state.scale(rect, n); got != 0.5 { + t.Fatalf("scale at zoom 1 = %v, want the view box's width across the canvas", got) + } + state.zoom = 3 + if got := state.scale(rect, n); got != 1.5 { + t.Fatalf("scale at zoom 3 = %v", got) + } + flat := &Node{Type: "canvas", ViewBox: [4]float64{0, 0, 100, 0}} + if got := state.scale(rect, flat); got != 0 { + t.Fatalf("scale of a view box without area = %v, want 0", got) + } + if got := state.viewport(rect, flat); got != (Viewport{}) { + t.Fatalf("viewport of a view box without area = %+v", got) + } +} + +func TestCanvasClampKeepsTheViewInsideTheViewBox(t *testing.T) { + n := testCanvas() + n.ViewBox = [4]float64{100, 50, 400, 200} + rect := gfx.Rect{Width: 200, Height: 200} + + // Zoomed out the view box is narrower and shorter than the canvas: centered across it, + // at its top. + state := &canvasState{zoom: 0.5, x: 999, y: 999, placed: true} + state.clamp(rect, n) + if state.x != 100-(800-400)/2.0 || state.y != 50 { + t.Fatalf("zoomed out at (%v, %v), want centered across and at the top", state.x, state.y) + } + + // Zoomed in it is larger: the visible part stays inside it. + state = &canvasState{zoom: 4, x: 999, y: -999, placed: true} + state.clamp(rect, n) + if state.x != 100+400-100 || state.y != 50 { + t.Fatalf("zoomed in at (%v, %v), want the edges of the view box", state.x, state.y) + } + + // A canvas not yet placed starts at the view box's top-left corner. + state = &canvasState{zoom: 4} + state.clamp(rect, n) + if !state.placed || state.x != 100 || state.y != 50 { + t.Fatalf("first placement at (%v, %v)", state.x, state.y) + } +} + +func TestCanvasZoomAtKeepsThePointUnderThePointer(t *testing.T) { + n := testCanvas() + rect := gfx.Rect{X: 10, Y: 20, Width: 400, Height: 400} + state := &canvasState{zoom: 1} + px, py := rect.X+200, rect.Y+100 + if !state.zoomAt(rect, n, 2, px, py) { + t.Fatal("zooming in did not change the zoom") + } + if state.zoom != 2 { + t.Fatalf("zoom = %v, want 2", state.zoom) + } + k := state.scale(rect, n) + if x, y := state.x+200/k, state.y+100/k; x != 200 || y != 100 { + t.Fatalf("the pointer is over (%v, %v) after zooming, want (200, 100) as before", x, y) + } + if got := state.viewport(rect, n); got != (Viewport{X: 100, Y: 50, Width: 200, Height: 200}) { + t.Fatalf("viewport = %+v", got) + } + if !state.zoomAt(rect, n, 100, px, py) || state.zoom != 4 { + t.Fatalf("zoom past the range = %v, want its top", state.zoom) + } + if state.zoomAt(rect, n, 100, px, py) { + t.Fatal("zooming at the top of the range reported a change") + } + fixed := &Node{Type: "canvas", ViewBox: [4]float64{0, 0, 400, 400}} + if (&canvasState{zoom: 1}).zoomAt(rect, fixed, 2, px, py) { + t.Fatal("a canvas without zoom zoomed") + } +} + +// openCanvas is a canvas state drawn at 200 × 200 in an open session at zoom 2, where one +// view-box unit is one pixel. +func openCanvas(t *testing.T) (*backend, *Session, *canvasState) { + b := newBackend(t) + s := b.session() + s.Open() + b.answered(s) + state := &canvasState{zoom: 2} + state.make() + state.node, state.session, state.rect = testCanvas(), s, gfx.Rect{Width: 200, Height: 200} + state.clamp(state.rect, state.node) + return b, s, state +} + +func TestCanvasDragPansAndSendsTheViewportOnceSettled(t *testing.T) { + b, s, state := openCanvas(t) + down := gfx.PointerEvent{Kind: gfx.PointerDown, Button: gfx.PointerButtonPrimary, X: 100, Y: 100} + if !state.pointerEvent(down).Handled { + t.Fatal("a press on the empty area did not start a drag") + } + state.pointerEvent(gfx.PointerEvent{Kind: gfx.PointerMove, X: 40, Y: 70}) + if state.x != 60 || state.y != 30 { + t.Fatalf("dragged to (%v, %v), want (60, 30)", state.x, state.y) + } + state.pointerEvent(gfx.PointerEvent{Kind: gfx.PointerMove, X: -1000, Y: 100}) + if state.x != 200 || state.y != 0 { + t.Fatalf("dragged past the edge to (%v, %v), want the edge", state.x, state.y) + } + if !state.pointerEvent(gfx.PointerEvent{Kind: gfx.PointerUp, X: -1000, Y: 100}).Handled || state.dragging { + t.Fatal("releasing did not end the drag") + } + if wait := s.Take(); wait != settleDelay || len(b.pending) != 0 { + t.Fatalf("while settling: wait %v, %d calls", wait, len(b.pending)) + } + b.now = b.now.Add(settleDelay) + s.Take() + b.run() + viewport, _ := b.last()["viewport"].(map[string]any) + if b.last()["event"] != "viewport" || b.last()["canvas"] != "graph" || viewport["x"] != 200.0 || viewport["width"] != 200.0 { + t.Fatalf("viewport event = %v", b.last()) + } +} + +func TestCanvasDragNeedsPanAndThePrimaryButton(t *testing.T) { + _, _, state := openCanvas(t) + secondary := gfx.PointerEvent{Kind: gfx.PointerDown, Button: gfx.PointerButtonSecondary, X: 100, Y: 100} + if state.pointerEvent(secondary).Handled || state.dragging { + t.Fatal("the secondary button started a drag") + } + state.node.Pan = false + primary := gfx.PointerEvent{Kind: gfx.PointerDown, Button: gfx.PointerButtonPrimary, X: 100, Y: 100} + if state.pointerEvent(primary).Handled || state.dragging { + t.Fatal("a canvas without pan started a drag") + } +} + +func TestCanvasWheelZoomsOnlyWithCommandOrControl(t *testing.T) { + b, s, state := openCanvas(t) + state.node.On = nil + plain := gfx.ScrollEvent{X: 100, Y: 100, DeltaY: -50} + if state.scroll(plain).Handled || state.zoom != 2 { + t.Fatal("the plain wheel zoomed instead of scrolling the page") + } + in := gfx.ScrollEvent{X: 100, Y: 100, DeltaY: -float32(math.Log(2) / canvasWheelZoom), Modifiers: gfx.ModifierMeta} + if !state.scroll(in).Handled || math.Abs(state.zoom-4) > 1e-4 { + t.Fatalf("⌘ and the wheel zoomed to %v, want 4", state.zoom) + } + out := gfx.ScrollEvent{X: 100, Y: 100, DeltaY: 1000, Modifiers: gfx.ModifierControl} + if !state.scroll(out).Handled || state.zoom != 0.5 { + t.Fatalf("Control and the wheel zoomed to %v, want the bottom of the range", state.zoom) + } + b.now = b.now.Add(settleDelay) + if s.Take(); len(b.pending) != 0 { + t.Fatal("a canvas that does not ask for viewport sent one") + } +} diff --git a/desktop/internal/pluginview/color.go b/desktop/internal/pluginview/color.go new file mode 100644 index 0000000000..9d36cf7f37 --- /dev/null +++ b/desktop/internal/pluginview/color.go @@ -0,0 +1,150 @@ +package pluginview + +import ( + "strconv" + + "github.com/vivaui/viva/gfx" +) + +// Palette is the host theme a view is drawn in. Every $token of +// plugin-ui.schema.json#/$defs/color resolves to one of these colors, so a view +// follows the host's light and dark themes without knowing either. +type Palette struct { + // Dark picks the dark side of a {light, dark} color pair. + Dark bool + Text gfx.Color + TextSecondary gfx.Color + TextMuted gfx.Color + Accent gfx.Color + Success gfx.Color + Warning gfx.Color + Error gfx.Color + Surface gfx.Color + Background gfx.Color + Sidebar gfx.Color + Line gfx.Color + Hover gfx.Color + Selection gfx.Color + Badge gfx.Color + // Popover and PopoverText draw the host's own canvas tooltip bubble. + Popover gfx.Color + PopoverText gfx.Color +} + +// token is the palette color a $token names; ok is false for a name the schema does not list. +func (p *Palette) token(name string) (gfx.Color, bool) { + switch name { + case "text": + return p.Text, true + case "textSecondary": + return p.TextSecondary, true + case "textMuted": + return p.TextMuted, true + case "accent": + return p.Accent, true + case "success": + return p.Success, true + case "warning": + return p.Warning, true + case "error": + return p.Error, true + case "surface": + return p.Surface, true + case "background": + return p.Background, true + case "sidebar": + return p.Sidebar, true + case "line": + return p.Line, true + case "hover": + return p.Hover, true + case "selection": + return p.Selection, true + case "badge": + return p.Badge, true + } + return gfx.Color{}, false +} + +// Tone is the text color of a host-control tone ("secondary", "muted", "accent", +// "success", "warning", "error"); fallback is used for no tone. +func (p *Palette) Tone(tone string, fallback gfx.Color) gfx.Color { + switch tone { + case "secondary": + return p.TextSecondary + case "muted": + return p.TextMuted + case "accent": + return p.Accent + case "success": + return p.Success + case "warning": + return p.Warning + case "error": + return p.Error + } + return fallback +} + +// plain resolves #RRGGBB, #RRGGBBAA or a $token. ok is false for anything else, +// which Core refuses, so the caller draws nothing rather than a guessed color. +func (p *Palette) plain(value string) (gfx.Color, bool) { + if len(value) > 1 && value[0] == '$' { + return p.token(value[1:]) + } + if len(value) != 7 && len(value) != 9 || value[0] != '#' { + return gfx.Color{}, false + } + channels, err := strconv.ParseUint(value[1:], 16, 32) + if err != nil { + return gfx.Color{}, false + } + alpha := uint64(255) + if len(value) == 9 { + alpha = channels & 0xff + channels >>= 8 + } + return gfx.RGBA(uint8(channels>>16), uint8(channels>>8), uint8(channels), float32(alpha)/255), true +} + +// Solid is the single color of c: a plain color, the side of a pair that matches +// the theme, or the first stop of a gradient where only one color can be drawn +// (a stroke, text). ok is false for a missing or unreadable color. +func (p *Palette) Solid(c *Color) (gfx.Color, bool) { + switch { + case c == nil: + return gfx.Color{}, false + case len(c.Stops) > 0: + return p.plain(c.Stops[0].Color) + case c.Light != "" || c.Dark != "": + if p.Dark { + return p.plain(c.Dark) + } + return p.plain(c.Light) + } + return p.plain(c.Plain) +} + +// Stops are the resolved stops of a gradient color, nil when c is not one. +func (p *Palette) Stops(c *Color, opacity float32) []gfx.GradientStop { + if c == nil || len(c.Stops) < 2 { + return nil + } + stops := make([]gfx.GradientStop, 0, len(c.Stops)) + for _, stop := range c.Stops { + color, ok := p.plain(stop.Color) + if !ok { + return nil + } + stops = append(stops, gfx.Stop(float32(stop.At), fade(color, opacity))) + } + return stops +} + +// fade multiplies a color's alpha by opacity. +func fade(color gfx.Color, opacity float32) gfx.Color { + if opacity >= 1 { + return color + } + return color.WithAlpha(color.Alpha * max(opacity, 0)) +} diff --git a/desktop/internal/pluginview/color_test.go b/desktop/internal/pluginview/color_test.go new file mode 100644 index 0000000000..720ffc3b0e --- /dev/null +++ b/desktop/internal/pluginview/color_test.go @@ -0,0 +1,154 @@ +package pluginview + +import ( + "encoding/json" + "testing" + + "github.com/vivaui/viva/gfx" +) + +// testPalette has one distinct color per token, so a test can tell which token resolved. +func testPalette(dark bool) Palette { + return Palette{ + Dark: dark, Text: gfx.RGBA(1, 0, 0, 1), TextSecondary: gfx.RGBA(2, 0, 0, 1), TextMuted: gfx.RGBA(3, 0, 0, 1), + Accent: gfx.RGBA(4, 0, 0, 1), Success: gfx.RGBA(5, 0, 0, 1), Warning: gfx.RGBA(6, 0, 0, 1), Error: gfx.RGBA(7, 0, 0, 1), + Surface: gfx.RGBA(8, 0, 0, 1), Background: gfx.RGBA(9, 0, 0, 1), Sidebar: gfx.RGBA(10, 0, 0, 1), Line: gfx.RGBA(11, 0, 0, 1), + Hover: gfx.RGBA(12, 0, 0, 1), Selection: gfx.RGBA(13, 0, 0, 1), Badge: gfx.RGBA(14, 0, 0, 1), + } +} + +func TestPalettePlainReadsHexAndTokens(t *testing.T) { + p := testPalette(false) + for _, tc := range []struct { + value string + want gfx.Color + ok bool + }{ + {"#112233", gfx.RGBA(0x11, 0x22, 0x33, 1), true}, + {"#11223380", gfx.RGBA(0x11, 0x22, 0x33, float32(0x80)/255), true}, + {"#ABCDEF", gfx.RGBA(0xab, 0xcd, 0xef, 1), true}, + {"$accent", p.Accent, true}, + {"$badge", p.Badge, true}, + {"$popover", gfx.Color{}, false}, + {"$", gfx.Color{}, false}, + {"#12345", gfx.Color{}, false}, + {"#GG2233", gfx.Color{}, false}, + {"112233", gfx.Color{}, false}, + {"red", gfx.Color{}, false}, + {"", gfx.Color{}, false}, + } { + got, ok := p.plain(tc.value) + if ok != tc.ok || got != tc.want { + t.Errorf("plain(%q) = %v, %v; want %v, %v", tc.value, got, ok, tc.want, tc.ok) + } + } +} + +func TestPaletteSolidPicksTheThemeSideAndTheFirstStop(t *testing.T) { + pair := &Color{Light: "#ffffff", Dark: "$surface"} + light, dark := testPalette(false), testPalette(true) + if got, ok := light.Solid(pair); !ok || got != gfx.RGBA(255, 255, 255, 1) { + t.Errorf("light side = %v, %v", got, ok) + } + if got, ok := dark.Solid(pair); !ok || got != dark.Surface { + t.Errorf("dark side = %v, %v", got, ok) + } + gradient := &Color{Stops: []Stop{{At: 0, Color: "$success"}, {At: 1, Color: "#000000"}}} + if got, ok := light.Solid(gradient); !ok || got != light.Success { + t.Errorf("gradient's solid = %v, %v, want its first stop", got, ok) + } + if got, ok := light.Solid(&Color{Plain: "$line"}); !ok || got != light.Line { + t.Errorf("plain = %v, %v", got, ok) + } + if _, ok := light.Solid(nil); ok { + t.Error("a missing color resolved") + } + if _, ok := light.Solid(&Color{Dark: "#000000"}); ok { + t.Error("a pair without a light side resolved in the light theme") + } +} + +func TestPaletteStopsFadeAndRefuseAnUnreadableStop(t *testing.T) { + p := testPalette(false) + gradient := &Color{Stops: []Stop{{At: 0, Color: "#ff0000"}, {At: 0.5, Color: "#00ff0080"}, {At: 1, Color: "$accent"}}} + stops := p.Stops(gradient, 0.5) + if len(stops) != 3 { + t.Fatalf("stops = %v", stops) + } + want := []gfx.GradientStop{ + gfx.Stop(0, gfx.RGBA(255, 0, 0, 0.5)), + gfx.Stop(0.5, gfx.RGBA(0, 255, 0, float32(0x80)/255*0.5)), + gfx.Stop(1, p.Accent.WithAlpha(0.5)), + } + for i := range want { + if stops[i] != want[i] { + t.Errorf("stop %d = %v, want %v", i, stops[i], want[i]) + } + } + if p.Stops(&Color{Stops: []Stop{{At: 0, Color: "#ff0000"}}}, 1) != nil { + t.Error("one stop made a gradient") + } + if p.Stops(&Color{Stops: []Stop{{At: 0, Color: "#ff0000"}, {At: 1, Color: "blue"}}}, 1) != nil { + t.Error("a gradient with an unreadable stop was drawn") + } + if p.Stops(&Color{Plain: "#ff0000"}, 1) != nil { + t.Error("a plain color made a gradient") + } +} + +func TestPaletteToneFallsBackForNoTone(t *testing.T) { + p := testPalette(false) + if got := p.Tone("warning", p.Text); got != p.Warning { + t.Errorf("warning tone = %v", got) + } + if got := p.Tone("", p.Line); got != p.Line { + t.Errorf("no tone = %v, want the fallback", got) + } + if got := p.Tone("primary", p.Text); got != p.Text { + t.Errorf("a control-only tone = %v, want the fallback", got) + } +} + +func TestFadeKeepsOpaqueAndClampsBelowZero(t *testing.T) { + color := gfx.RGBA(10, 20, 30, 0.8) + if fade(color, 1) != color || fade(color, 2) != color { + t.Error("an opacity of 1 or more changed the color") + } + if got := fade(color, -1); got.Alpha != 0 { + t.Errorf("a negative opacity left alpha %v", got.Alpha) + } +} + +func TestColorUnmarshalReadsTheThreeForms(t *testing.T) { + var colors struct { + Plain Color `json:"plain"` + Pair Color `json:"pair"` + Down Color `json:"down"` + Sideways Color `json:"sideways"` + } + data := `{ + "plain": "$accent", + "pair": {"light": "#ffffff", "dark": "#000000"}, + "down": {"linear": [[0, "#ff0000"], [1, "$accent"]]}, + "sideways": {"linear": [[0, "#ff0000"], [0.4, "#00ff00"], [1, "#0000ff"]], "angle": 90} + }` + if err := json.Unmarshal([]byte(data), &colors); err != nil { + t.Fatal(err) + } + if colors.Plain.Plain != "$accent" { + t.Errorf("plain = %+v", colors.Plain) + } + if colors.Pair.Light != "#ffffff" || colors.Pair.Dark != "#000000" { + t.Errorf("pair = %+v", colors.Pair) + } + if colors.Down.Angle != 180 || len(colors.Down.Stops) != 2 || colors.Down.Stops[1] != (Stop{At: 1, Color: "$accent"}) { + t.Errorf("gradient without an angle = %+v, want top to bottom", colors.Down) + } + if colors.Sideways.Angle != 90 || len(colors.Sideways.Stops) != 3 || colors.Sideways.Stops[1].At != 0.4 { + t.Errorf("gradient with an angle = %+v", colors.Sideways) + } + var bad Color + if err := json.Unmarshal([]byte(`{"linear": [["start", "#ff0000"]]}`), &bad); err == nil { + t.Error("a stop offset that is not a number was read") + } +} diff --git a/desktop/internal/pluginview/hosticons.go b/desktop/internal/pluginview/hosticons.go new file mode 100644 index 0000000000..44d2c6a645 --- /dev/null +++ b/desktop/internal/pluginview/hosticons.go @@ -0,0 +1,45 @@ +package pluginview + +import ( + "github.com/1lck/Lithe-IDEA/desktop/internal/icons" + "github.com/1lck/Lithe-IDEA/desktop/internal/toolicons" + "github.com/vivaui/viva/gfx" +) + +// HostIcon is the host icon a plugin names (plugin-manifest.schema.json#/$defs/uiIcon host): +// the IntelliJ New UI icon of a tool window where the workbench has one, a Lucide icon +// otherwise. ok is false for a name the host does not draw. A tool window's stripe button and +// a node of a view draw the same vocabulary, so the names mean the same in both. +func HostIcon(name string) (gfx.Icon, bool) { + switch name { + case "database", "services": + return toolicons.Services, true + case "terminal": + return toolicons.Terminal, true + case "search": + return toolicons.Find, true + case "refresh": + return icons.RefreshCw, true + case "reset": + return icons.Undo2, true + case "run": + return toolicons.Run, true + case "debug": + return toolicons.Debug, true + case "settings": + return icons.Settings, true + case "add": + return icons.Plus, true + case "remove": + return icons.Minus, true + case "git": + return toolicons.Vcs, true + case "problems": + return toolicons.Problems, true + case "plugin": + return icons.Sparkles, true + case "tool-window": + return icons.LayoutGrid, true + } + return gfx.Icon{}, false +} diff --git a/desktop/internal/pluginview/images.go b/desktop/internal/pluginview/images.go new file mode 100644 index 0000000000..301eac2ca5 --- /dev/null +++ b/desktop/internal/pluginview/images.go @@ -0,0 +1,140 @@ +package pluginview + +import ( + "bytes" + "errors" + "fmt" + "hash/fnv" + "image/png" + "io" + "os" + "sync" + + "github.com/1lck/Lithe-IDEA/desktop/internal/bgra" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" + "github.com/vivaui/viva/gfx" +) + +// A canvas image is a PNG file of the plugin's installed package, named by a package-relative +// path. The host reads it read-only, under the same rules as the package's icons: the path +// must stay inside the package, through real directories, to a regular file. Images are +// loaded off the window thread the first time a scene draws them and kept until the view +// closes; the view draws without an image until it arrives, and without one that cannot be +// read, whose failure the host logs once. +const ( + // imageBytes bounds the size of one image file. + imageBytes = 256 << 10 + // imageSide bounds the width and the height of one image. + imageSide = 1024 +) + +// Images loads and keeps the canvas images of one plugin view. +type Images struct { + dir string + wake func() + failed func(error) + + mu sync.Mutex + images map[string]*picture + closed bool +} + +// picture is one image: loading until its load ends, then its bitmap or failed. +type picture struct { + bitmap gfx.Bitmap + ready bool +} + +// NewImages keeps the images of the package installed in packageDir. wake asks for a frame +// when an image arrives; failed logs an image that cannot be read, naming its path. Both run +// on the loading goroutine, so they must be safe to call from any goroutine. +func NewImages(packageDir string, wake func(), failed func(error)) *Images { + return &Images{dir: packageDir, wake: wake, failed: failed, images: map[string]*picture{}} +} + +// Close drops the kept images; loads still under way end without effect. +func (i *Images) Close() { + if i == nil { + return + } + i.mu.Lock() + defer i.mu.Unlock() + i.images, i.closed = map[string]*picture{}, true +} + +// bitmap is the image at src once it is loaded; the first ask starts loading it. +func (i *Images) bitmap(src string) (gfx.Bitmap, bool) { + if i == nil || src == "" { + return gfx.Bitmap{}, false + } + i.mu.Lock() + defer i.mu.Unlock() + if p := i.images[src]; p != nil { + return p.bitmap, p.ready + } + if i.closed { + return gfx.Bitmap{}, false + } + p := &picture{} + i.images[src] = p + go i.load(src, p) + return gfx.Bitmap{}, false +} + +// load reads one image and hands it to the view. An image that cannot be read stays loading, +// so it is read and logged once while the view shows; the view draws without it. +func (i *Images) load(src string, p *picture) { + bitmap, err := loadImage(i.dir, src) + i.mu.Lock() + kept := i.images[src] == p + if kept && err == nil { + p.bitmap, p.ready = bitmap, true + } + i.mu.Unlock() + switch { + case err != nil && i.failed != nil: + i.failed(fmt.Errorf("pluginview: canvas image %q: %w", src, err)) + case kept && err == nil && i.wake != nil: + i.wake() + } +} + +// loadImage reads and decodes the PNG at the package-relative path src, refusing a file +// or an image over the limits before decoding it. +func loadImage(dir, src string) (gfx.Bitmap, error) { + path, err := pluginhost.ResolvePackagePath(dir, src) + if err != nil { + return gfx.Bitmap{}, err + } + file, err := os.Open(path) + if err != nil { + return gfx.Bitmap{}, err + } + defer file.Close() + data, err := io.ReadAll(io.LimitReader(file, imageBytes+1)) + if err != nil { + return gfx.Bitmap{}, err + } + if len(data) > imageBytes { + return gfx.Bitmap{}, errors.New("pluginview: image file is too large") + } + config, err := png.DecodeConfig(bytes.NewReader(data)) + if err != nil { + return gfx.Bitmap{}, err + } + if config.Width <= 0 || config.Height <= 0 || config.Width > imageSide || config.Height > imageSide { + return gfx.Bitmap{}, errors.New("pluginview: image is too large") + } + decoded, err := png.Decode(bytes.NewReader(data)) + if err != nil { + return gfx.Bitmap{}, err + } + return bgra.Bitmap(decoded, imageID(dir, src)), nil +} + +// imageID names an image to the canvas, apart from the other bitmaps the window draws. +func imageID(dir, src string) uint64 { + hash := fnv.New64a() + _, _ = hash.Write([]byte(dir + "\x00" + src)) + return hash.Sum64()&0x00ffffffffffffff | 0x50<<56 +} diff --git a/desktop/internal/pluginview/images_test.go b/desktop/internal/pluginview/images_test.go new file mode 100644 index 0000000000..8f334e9925 --- /dev/null +++ b/desktop/internal/pluginview/images_test.go @@ -0,0 +1,175 @@ +package pluginview + +import ( + "bytes" + "errors" + "image" + "image/color" + "image/png" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" +) + +// imageWait bounds how long a test waits for an image to load; a load reads one small file. +const imageWait = 10 * time.Second + +// writePNG writes a width × height PNG of one color at rel inside dir. +func writePNG(t *testing.T, dir, rel string, width, height int, fill color.NRGBA) { + t.Helper() + picture := image.NewNRGBA(image.Rect(0, 0, width, height)) + for y := 0; y < height; y++ { + for x := 0; x < width; x++ { + picture.SetNRGBA(x, y, fill) + } + } + var data bytes.Buffer + if err := png.Encode(&data, picture); err != nil { + t.Fatal(err) + } + writeFile(t, dir, rel, data.Bytes()) +} + +func writeFile(t *testing.T, dir, rel string, data []byte) { + t.Helper() + path := filepath.Join(dir, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, data, 0o644); err != nil { + t.Fatal(err) + } +} + +// loader is a package's images with the wake and failure they report, which arrive on the +// loading goroutine. +type loader struct { + t *testing.T + images *Images + woken chan struct{} + failed chan error +} + +func newLoader(t *testing.T, dir string) *loader { + l := &loader{t: t, woken: make(chan struct{}, 4), failed: make(chan error, 4)} + l.images = NewImages(dir, func() { l.woken <- struct{}{} }, func(err error) { l.failed <- err }) + t.Cleanup(l.images.Close) + return l +} + +// loaded asks for src and waits until it arrives. +func (l *loader) loaded(src string) { + l.t.Helper() + if _, ready := l.images.bitmap(src); ready { + l.t.Fatalf("%s was ready before it loaded", src) + } + select { + case <-l.woken: + case err := <-l.failed: + l.t.Fatalf("loading %s failed: %v", src, err) + case <-time.After(imageWait): + l.t.Fatalf("%s did not load within %v", src, imageWait) + } +} + +// refused asks for src and waits for the failure it reports. +func (l *loader) refused(src string) error { + l.t.Helper() + l.images.bitmap(src) + select { + case err := <-l.failed: + if !strings.Contains(err.Error(), src) { + l.t.Errorf("failure %q does not name the image", err) + } + return err + case <-l.woken: + l.t.Fatalf("%s loaded, want it refused", src) + case <-time.After(imageWait): + l.t.Fatalf("%s reported nothing within %v", src, imageWait) + } + return nil +} + +func TestImagesLoadAPackagePNGOnce(t *testing.T) { + dir := t.TempDir() + writePNG(t, dir, "media/dot.png", 2, 1, color.NRGBA{R: 255, A: 255}) + l := newLoader(t, dir) + l.loaded("media/dot.png") + bitmap, ready := l.images.bitmap("media/dot.png") + if !ready || bitmap.Width != 2 || bitmap.Height != 1 { + t.Fatalf("bitmap = %dx%d, ready %v", bitmap.Width, bitmap.Height, ready) + } + if got := bitmap.Pix[:4]; !bytes.Equal(got, []byte{0, 0, 255, 255}) { + t.Fatalf("red pixel = %v, want BGRA", got) + } + if bitmap.ID>>56 != 0x50 || bitmap.ID != imageID(dir, "media/dot.png") { + t.Fatalf("bitmap ID = %#x", bitmap.ID) + } + if len(l.woken) != 0 { + t.Fatal("asking for a loaded image loaded it again") + } +} + +func TestImagesRefuseWhatThePackageRulesOrTheLimitsExclude(t *testing.T) { + dir := t.TempDir() + writePNG(t, dir, "wide.png", imageSide+1, 1, color.NRGBA{A: 255}) + writeFile(t, dir, "huge.png", make([]byte, imageBytes+1)) + writeFile(t, dir, "notes.png", []byte("not a picture")) + writePNG(t, filepath.Dir(dir), "outside.png", 1, 1, color.NRGBA{A: 255}) + l := newLoader(t, dir) + for _, tc := range []struct { + src string + want string + }{ + {"wide.png", "image is too large"}, + {"huge.png", "image file is too large"}, + {"notes.png", "png"}, + {"missing.png", "does not exist"}, + } { + if err := l.refused(tc.src); err != nil && !strings.Contains(err.Error(), tc.want) { + t.Errorf("%s: %v, want %q", tc.src, err, tc.want) + } + } + if err := l.refused("../outside.png"); err != nil && !errors.Is(err, pluginhost.ErrPackagePath) { + t.Errorf("a path out of the package: %v, want a package path error", err) + } + if err := os.Symlink(filepath.Join(filepath.Dir(dir), "outside.png"), filepath.Join(dir, "link.png")); err != nil { + t.Fatal(err) + } + if err := l.refused("link.png"); err != nil && !errors.Is(err, pluginhost.ErrPackageSymlink) { + t.Errorf("a link out of the package: %v, want a symbolic link error", err) + } + if _, ready := l.images.bitmap("wide.png"); ready { + t.Fatal("a refused image was drawn") + } +} + +func TestImagesCloseDropsTheLoadedImages(t *testing.T) { + dir := t.TempDir() + writePNG(t, dir, "dot.png", 1, 1, color.NRGBA{G: 255, A: 255}) + l := newLoader(t, dir) + l.loaded("dot.png") + l.images.Close() + if _, ready := l.images.bitmap("dot.png"); ready { + t.Fatal("a closed view still draws its image") + } + var none *Images + none.Close() + if _, ready := none.bitmap("dot.png"); ready { + t.Fatal("no images drew an image") + } + if _, ready := l.images.bitmap(""); ready { + t.Fatal("an image without a path was drawn") + } +} + +func TestImageIDsDifferByPackageAndPath(t *testing.T) { + a, b, c := imageID("/p", "a.png"), imageID("/p", "b.png"), imageID("/q", "a.png") + if a == b || a == c || b == c { + t.Fatalf("image IDs collide: %#x %#x %#x", a, b, c) + } +} diff --git a/desktop/internal/pluginview/node.go b/desktop/internal/pluginview/node.go new file mode 100644 index 0000000000..13cd33156a --- /dev/null +++ b/desktop/internal/pluginview/node.go @@ -0,0 +1,277 @@ +// Package pluginview draws plugin views (API-13): the host controls, trees and canvas +// scenes that a plugin's view function returns for a tool window body or a settings +// region (settingRegions, API-19). +// +// Core checks every result and applies its patches (plugins.ui.applyResult) before +// the host sees it, so this package keeps no validator or patch engine of its own. It +// decodes the checked view, draws it with Viva each frame, and turns user input into +// view events. Hovering, pressing, focus, tooltips, tree expansion, scrolling, +// panning and zooming stay in the host and never reach the plugin. +// +// View state (text being typed, open tree items, a canvas's pan and zoom) lives in +// memory only. Nothing is written to disk, to the installed package or to the +// application bundle. +package pluginview + +import ( + "encoding/json" + "errors" +) + +// Node is one view node of any type; Type selects which fields apply. Core checked +// the node against plugin-ui.schema.json and the README rules, so fields that belong +// to other types are absent. +type Node struct { + Type string `json:"type"` + ID string `json:"id,omitempty"` + Children []Node `json:"children,omitempty"` + Title string `json:"title,omitempty"` + Info string `json:"info,omitempty"` + Text string `json:"text,omitempty"` + Tone string `json:"tone,omitempty"` + Style string `json:"style,omitempty"` + // Width is a label's reserved character count, or a text field's "fill" or count. + Width json.RawMessage `json:"width,omitempty"` + Label string `json:"label,omitempty"` + // Value is a control's own value: a string, or a boolean for a toggle. + Value json.RawMessage `json:"value,omitempty"` + Setting string `json:"setting,omitempty"` + Placeholder string `json:"placeholder,omitempty"` + Mono bool `json:"mono,omitempty"` + Enabled *bool `json:"enabled,omitempty"` + Options []Option `json:"options,omitempty"` + Icon string `json:"icon,omitempty"` + Action string `json:"action,omitempty"` + // Items are a keyValue's pairs or a tree's top-level items. + Items []Item `json:"items,omitempty"` + Columns []Column `json:"columns,omitempty"` + Rows [][]string `json:"rows,omitempty"` + Tool string `json:"tool,omitempty"` + // Height, ViewBox, Pan, Zoom, On and Nodes describe a canvas. + Height float64 `json:"height,omitempty"` + ViewBox [4]float64 `json:"viewBox,omitempty"` + Pan bool `json:"pan,omitempty"` + Zoom *[2]float64 `json:"zoom,omitempty"` + On []string `json:"on,omitempty"` + Nodes []Shape `json:"nodes,omitempty"` +} + +// Option is one choice of a select or segmented control. +type Option struct { + Value string `json:"value"` + Label string `json:"label"` +} + +// Item is a keyValue pair (Label, Value, Tone) or a tree item (ID, Label, Icon, +// Detail, Expanded, Children). +type Item struct { + ID string `json:"id,omitempty"` + Label string `json:"label"` + Value string `json:"value,omitempty"` + Tone string `json:"tone,omitempty"` + Icon string `json:"icon,omitempty"` + Detail string `json:"detail,omitempty"` + Expanded bool `json:"expanded,omitempty"` + Children []Item `json:"children,omitempty"` +} + +// Column is one column of a table. +type Column struct { + Title string `json:"title"` + Align string `json:"align,omitempty"` +} + +// Shape is one canvas node of any type; Type selects which fields apply. +type Shape struct { + Type string `json:"type"` + ID string `json:"id,omitempty"` + X float64 `json:"x,omitempty"` + Y float64 `json:"y,omitempty"` + W float64 `json:"w,omitempty"` + H float64 `json:"h,omitempty"` + Radius float64 `json:"radius,omitempty"` + Fill *Color `json:"fill,omitempty"` + Stroke *Color `json:"stroke,omitempty"` + // Width is the stroke width in view-box units, 1 when absent. + Width *float64 `json:"width,omitempty"` + Dash []float64 `json:"dash,omitempty"` + Shadow int `json:"shadow,omitempty"` + Opacity *float64 `json:"opacity,omitempty"` + // D, Bounds, Cap and Rule describe a path. + D string `json:"d,omitempty"` + Bounds *[4]float64 `json:"bounds,omitempty"` + Cap string `json:"cap,omitempty"` + Rule string `json:"rule,omitempty"` + // Text, Runs, Style, Align, Color and MaxWidth describe text. + Text string `json:"text,omitempty"` + Runs []Run `json:"runs,omitempty"` + Style string `json:"style,omitempty"` + Align string `json:"align,omitempty"` + Color *Color `json:"color,omitempty"` + MaxWidth float64 `json:"maxWidth,omitempty"` + // Src is an image's package-relative PNG path. + Src string `json:"src,omitempty"` + // Scale, Clip, Children, On, Label, Tooltip, States, Selected and Hidden describe a group. + Scale *float64 `json:"scale,omitempty"` + Clip bool `json:"clip,omitempty"` + Children []Shape `json:"children,omitempty"` + On []string `json:"on,omitempty"` + Label string `json:"label,omitempty"` + Tooltip string `json:"tooltip,omitempty"` + States *States `json:"states,omitempty"` + Selected bool `json:"selected,omitempty"` + Hidden bool `json:"hidden,omitempty"` + + // geometry is the parsed path, made on first draw and kept with the decoded view. + geometry *pathGeometry +} + +// Run is one differently colored part of a text node. +type Run struct { + Text string `json:"text"` + Color *Color `json:"color,omitempty"` +} + +// States are what the host draws while a clickable group is hovered, pressed or selected. +type States struct { + Hover *State `json:"hover,omitempty"` + Pressed *State `json:"pressed,omitempty"` + Selected *State `json:"selected,omitempty"` +} + +// State paints the group's w × h area behind its children (Fill, Stroke, Width, +// Shadow) and changes the whole group (Scale, Opacity). +type State struct { + Fill *Color `json:"fill,omitempty"` + Stroke *Color `json:"stroke,omitempty"` + Width *float64 `json:"width,omitempty"` + Shadow int `json:"shadow,omitempty"` + Scale *float64 `json:"scale,omitempty"` + Opacity *float64 `json:"opacity,omitempty"` +} + +// Color is a plain color (#RRGGBB, #RRGGBBAA or a $token), a light and dark pair, or +// a linear gradient of stops. Angle follows CSS: 0 runs upward, 90 to the right, and +// an absent angle is 180, top to bottom. +type Color struct { + Plain string + Light string + Dark string + Stops []Stop + Angle float64 +} + +// Stop is one gradient stop: a plain color at an offset from 0 to 1. +type Stop struct { + At float64 + Color string +} + +// UnmarshalJSON reads the three color forms of plugin-ui.schema.json#/$defs/color. +func (c *Color) UnmarshalJSON(data []byte) error { + if len(data) > 0 && data[0] == '"' { + return json.Unmarshal(data, &c.Plain) + } + var object struct { + Light string `json:"light"` + Dark string `json:"dark"` + Linear [][2]json.RawMessage `json:"linear"` + Angle *float64 `json:"angle"` + } + if err := json.Unmarshal(data, &object); err != nil { + return err + } + c.Light, c.Dark, c.Angle = object.Light, object.Dark, 180 + if object.Angle != nil { + c.Angle = *object.Angle + } + for _, pair := range object.Linear { + var stop Stop + if err := json.Unmarshal(pair[0], &stop.At); err != nil { + return err + } + if err := json.Unmarshal(pair[1], &stop.Color); err != nil { + return err + } + c.Stops = append(c.Stops, stop) + } + return nil +} + +// Decode reads a view Core returned. A view that is not an array of nodes is an +// error; Core never returns one, so it means the host and Core disagree. +func Decode(view json.RawMessage) ([]Node, error) { + if len(view) == 0 { + return nil, errors.New("pluginview: empty view") + } + var nodes []Node + if err := json.Unmarshal(view, &nodes); err != nil { + return nil, err + } + return nodes, nil +} + +// enabled reports whether a control accepts input; a control is enabled unless it says otherwise. +func (n *Node) enabled() bool { + return n.Enabled == nil || *n.Enabled +} + +// stringValue is a control's own string value, empty when it has none. +func (n *Node) stringValue() string { + var value string + if len(n.Value) > 0 { + _ = json.Unmarshal(n.Value, &value) + } + return value +} + +// boolValue is a toggle's own value, false when it has none. +func (n *Node) boolValue() bool { + var value bool + if len(n.Value) > 0 { + _ = json.Unmarshal(n.Value, &value) + } + return value +} + +// characters is a label's or text field's reserved character count, 0 for none. +// fill reports a text field that takes the row's free width. +func (n *Node) characters() (count int, fill bool) { + if len(n.Width) == 0 { + return 0, false + } + if string(n.Width) == `"fill"` { + return 0, true + } + _ = json.Unmarshal(n.Width, &count) + return count, false +} + +// clickable reports whether a group is a control. +func (s *Shape) clickable() bool { + return s.Type == "group" && len(s.On) > 0 +} + +// opacity is the shape's opacity, 1 when absent. +func (s *Shape) opacity() float32 { + if s.Opacity == nil { + return 1 + } + return float32(*s.Opacity) +} + +// strokeWidth is the shape's stroke width in view-box units, 1 when absent. +func (s *Shape) strokeWidth() float64 { + if s.Width == nil { + return 1 + } + return *s.Width +} + +// scale is a group's scale, 1 when absent. +func (s *Shape) scale() float64 { + if s.Scale == nil { + return 1 + } + return *s.Scale +} diff --git a/desktop/internal/pluginview/node_test.go b/desktop/internal/pluginview/node_test.go new file mode 100644 index 0000000000..0f845d757c --- /dev/null +++ b/desktop/internal/pluginview/node_test.go @@ -0,0 +1,177 @@ +package pluginview + +import ( + "bytes" + "encoding/json" + "os" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture" +) + +// viewCase is one case of the contract's view-results fixture. +type viewCase struct { + Name string `json:"name"` + View json.RawMessage `json:"view"` + Result struct { + View json.RawMessage `json:"view"` + } `json:"result"` + Expected struct { + Status string `json:"status"` + View json.RawMessage `json:"view"` + } `json:"expected"` +} + +// strictNodes decodes a view refusing any field Node does not read, so a field the contract +// adds is a failing test here rather than a view the host draws without it. +func strictNodes(t *testing.T, view json.RawMessage) []Node { + t.Helper() + decoder := json.NewDecoder(bytes.NewReader(view)) + decoder.DisallowUnknownFields() + var nodes []Node + if err := decoder.Decode(&nodes); err != nil { + t.Fatalf("decode %s: %v", view, err) + } + return nodes +} + +func TestDecodeReadsEveryFieldOfTheContractViews(t *testing.T) { + data, err := os.ReadFile(contractfixture.Path("fixtures/ui/view-results.json")) + if err != nil { + t.Fatal(err) + } + var fixture struct { + Cases []viewCase `json:"cases"` + } + if err := json.Unmarshal(data, &fixture); err != nil { + t.Fatal(err) + } + types := map[string]bool{} + var walk func([]Node) + walk = func(nodes []Node) { + for _, n := range nodes { + types[n.Type] = true + walk(n.Children) + } + } + checked := 0 + for _, c := range fixture.Cases { + if c.Expected.Status != "ok" { + continue + } + views := []json.RawMessage{c.View} + if string(c.Expected.View) == `"result.view"` { + views = append(views, c.Result.View) + } else { + views = append(views, c.Expected.View) + } + for _, view := range views { + if len(view) == 0 { + continue + } + strict := strictNodes(t, view) + decoded, err := Decode(view) + if err != nil || len(decoded) != len(strict) { + t.Fatalf("%s: Decode = %d nodes, %v; want %d", c.Name, len(decoded), err, len(strict)) + } + walk(strict) + checked++ + } + } + if checked == 0 { + t.Fatal("the fixture has no view the host can draw") + } + for _, want := range []string{"section", "row", "label", "button", "tree", "toggle", "tool", "canvas"} { + if !types[want] { + t.Errorf("the fixture views have no %s node", want) + } + } +} + +func TestDecodeRefusesWhatIsNotANodeList(t *testing.T) { + for _, view := range []string{"", `{"type":"label"}`, `"label"`, `[{"type":1}]`} { + if _, err := Decode(json.RawMessage(view)); err == nil { + t.Errorf("Decode(%q) read a view", view) + } + } + if nodes, err := Decode(json.RawMessage(`[]`)); err != nil || len(nodes) != 0 { + t.Errorf("an empty view = %v, %v", nodes, err) + } +} + +func TestNodeValuesDefaultWhenAbsent(t *testing.T) { + nodes := strictNodes(t, json.RawMessage(`[ + {"type":"textField","value":"main","width":"fill"}, + {"type":"toggle","value":true,"enabled":false}, + {"type":"label","width":12}, + {"type":"textField","value":true}, + {"type":"label"} + ]`)) + field, toggle, label, mistyped, bare := nodes[0], nodes[1], nodes[2], nodes[3], nodes[4] + if field.stringValue() != "main" || !field.enabled() { + t.Errorf("text field value %q, enabled %v", field.stringValue(), field.enabled()) + } + if count, fill := field.characters(); count != 0 || !fill { + t.Errorf("fill width = %d, %v", count, fill) + } + if !toggle.boolValue() || toggle.enabled() { + t.Errorf("toggle value %v, enabled %v", toggle.boolValue(), toggle.enabled()) + } + if count, fill := label.characters(); count != 12 || fill { + t.Errorf("label width = %d, %v", count, fill) + } + if mistyped.stringValue() != "" || bare.boolValue() || bare.stringValue() != "" { + t.Error("a missing or mistyped value was read") + } + if count, fill := bare.characters(); count != 0 || fill { + t.Errorf("no width = %d, %v", count, fill) + } +} + +func TestShapeDefaults(t *testing.T) { + half, two, three := 0.5, 2.0, 3.0 + var bare Shape + if bare.opacity() != 1 || bare.strokeWidth() != 1 || bare.scale() != 1 || bare.clickable() { + t.Errorf("bare shape: opacity %v, stroke %v, scale %v, clickable %v", bare.opacity(), bare.strokeWidth(), bare.scale(), bare.clickable()) + } + set := Shape{Type: "group", Opacity: &half, Width: &two, Scale: &three, On: []string{"click"}} + if set.opacity() != 0.5 || set.strokeWidth() != 2 || set.scale() != 3 || !set.clickable() { + t.Errorf("set shape: opacity %v, stroke %v, scale %v, clickable %v", set.opacity(), set.strokeWidth(), set.scale(), set.clickable()) + } + if (&Shape{Type: "rect", On: []string{"click"}}).clickable() { + t.Error("a rect with events is a control; only groups are") + } +} + +func TestHostIconDrawsEveryNameTheContractLists(t *testing.T) { + data, err := os.ReadFile(contractfixture.Path("plugin-manifest.schema.json")) + if err != nil { + t.Fatal(err) + } + var schema struct { + Defs struct { + UIIcon struct { + Properties struct { + Host struct { + Enum []string `json:"enum"` + } `json:"host"` + } `json:"properties"` + } `json:"uiIcon"` + } `json:"$defs"` + } + if err := json.Unmarshal(data, &schema); err != nil { + t.Fatal(err) + } + names := schema.Defs.UIIcon.Properties.Host.Enum + if len(names) == 0 { + t.Fatal("the manifest schema lists no host icon") + } + for _, name := range names { + if icon, ok := HostIcon(name); !ok || len(icon.Commands) == 0 { + t.Errorf("host icon %q is not drawn", name) + } + } + if _, ok := HostIcon("not-an-icon"); ok { + t.Error("an unknown icon name resolved") + } +} diff --git a/desktop/internal/pluginview/path.go b/desktop/internal/pluginview/path.go new file mode 100644 index 0000000000..cb1df67e09 --- /dev/null +++ b/desktop/internal/pluginview/path.go @@ -0,0 +1,388 @@ +package pluginview + +import ( + "math" + "strconv" + + "github.com/vivaui/viva/gfx" +) + +// pathGeometry is a canvas path parsed once: the Viva path in its own view box, which +// starts at (X, Y) of the canvas's view box and is W × H units large. +type pathGeometry struct { + path gfx.Path + x, y, w, h float64 + empty bool +} + +// segment is one absolute path command: op is 'M', 'L', 'Q', 'C' or 'Z', with up +// to three points. +type segment struct { + op byte + points [6]float64 +} + +// geometryOf parses the shape's path data on first use and keeps the result with +// the decoded view, so a frame draws a path without parsing it again. +func (s *Shape) geometryOf() *pathGeometry { + if s.geometry != nil { + return s.geometry + } + segments := parsePathData(s.D) + geometry := &pathGeometry{empty: len(segments) == 0} + if !geometry.empty { + left, top, right, bottom := math.Inf(1), math.Inf(1), math.Inf(-1), math.Inf(-1) + for _, segment := range segments { + for index := 0; index < segment.count(); index++ { + x, y := segment.points[2*index], segment.points[2*index+1] + left, top = math.Min(left, x), math.Min(top, y) + right, bottom = math.Max(right, x), math.Max(bottom, y) + } + } + // One unit around the points keeps a horizontal or vertical line, which has + // no height or width, a valid view box. The mapping to the canvas stays exact. + geometry.x, geometry.y = left-1, top-1 + geometry.w, geometry.h = right-left+2, bottom-top+2 + commands := make([]gfx.PathCommand, 0, len(segments)) + at := func(index int, segment segment) (float32, float32) { + return float32(segment.points[2*index] - geometry.x), float32(segment.points[2*index+1] - geometry.y) + } + for _, segment := range segments { + switch segment.op { + case 'M': + x, y := at(0, segment) + commands = append(commands, gfx.MoveTo(x, y)) + case 'L': + x, y := at(0, segment) + commands = append(commands, gfx.LineTo(x, y)) + case 'Q': + cx, cy := at(0, segment) + x, y := at(1, segment) + commands = append(commands, gfx.QuadTo(cx, cy, x, y)) + case 'C': + c1x, c1y := at(0, segment) + c2x, c2y := at(1, segment) + x, y := at(2, segment) + commands = append(commands, gfx.CubicTo(c1x, c1y, c2x, c2y, x, y)) + case 'Z': + commands = append(commands, gfx.ClosePath()) + } + } + geometry.path = gfx.NewPath(float32(geometry.w), float32(geometry.h), commands...) + } + s.geometry = geometry + return geometry +} + +// count is the number of points the segment carries. +func (s segment) count() int { + switch s.op { + case 'M', 'L': + return 1 + case 'Q': + return 2 + case 'C': + return 3 + } + return 0 +} + +// parsePathData reads SVG path data (MmLlHhVvCcSsQqTtAaZz) into absolute moves, +// lines, quadratic and cubic curves. Arcs become cubic curves. Core checked the +// letters and the length; data that stops making sense ends the path where it +// does, as an SVG renderer draws an erroneous path up to the error. +func parsePathData(data string) []segment { + var ( + scan = scanner{text: data} + out []segment + x, y float64 + startX, startY float64 + controlX float64 + controlY float64 + previous byte + command byte + haveCurrentPoint bool + ) + for { + scan.skipSeparators() + if scan.done() { + return out + } + if letter := scan.peek(); isPathLetter(letter) { + command = letter + scan.pos++ + } else if command == 0 || command == 'Z' || command == 'z' { + return out + } + relative := command >= 'a' + upper := command &^ 0x20 + if upper != 'M' && !haveCurrentPoint { + return out + } + offset := func(px, py float64) (float64, float64) { + if relative { + return px + x, py + y + } + return px, py + } + switch upper { + case 'Z': + out = append(out, segment{op: 'Z'}) + x, y = startX, startY + case 'M': + px, py, ok := scan.pair() + if !ok { + return out + } + x, y = offset(px, py) + startX, startY = x, y + haveCurrentPoint = true + out = append(out, segment{op: 'M', points: [6]float64{x, y}}) + // Further pairs after a move are lines, relative when the move was. + command = 'L' | command&0x20 + case 'L': + px, py, ok := scan.pair() + if !ok { + return out + } + x, y = offset(px, py) + out = append(out, segment{op: 'L', points: [6]float64{x, y}}) + case 'H': + value, ok := scan.number() + if !ok { + return out + } + if relative { + value += x + } + x = value + out = append(out, segment{op: 'L', points: [6]float64{x, y}}) + case 'V': + value, ok := scan.number() + if !ok { + return out + } + if relative { + value += y + } + y = value + out = append(out, segment{op: 'L', points: [6]float64{x, y}}) + case 'C', 'S': + c1x, c1y := x, y + if upper == 'C' { + px, py, ok := scan.pair() + if !ok { + return out + } + c1x, c1y = offset(px, py) + } else if previous == 'C' || previous == 'S' { + c1x, c1y = 2*x-controlX, 2*y-controlY + } + p2x, p2y, ok := scan.pair() + if !ok { + return out + } + p3x, p3y, ok := scan.pair() + if !ok { + return out + } + c2x, c2y := offset(p2x, p2y) + ex, ey := offset(p3x, p3y) + out = append(out, segment{op: 'C', points: [6]float64{c1x, c1y, c2x, c2y, ex, ey}}) + controlX, controlY = c2x, c2y + x, y = ex, ey + case 'Q', 'T': + cx, cy := x, y + if upper == 'Q' { + px, py, ok := scan.pair() + if !ok { + return out + } + cx, cy = offset(px, py) + } else if previous == 'Q' || previous == 'T' { + cx, cy = 2*x-controlX, 2*y-controlY + } + px, py, ok := scan.pair() + if !ok { + return out + } + ex, ey := offset(px, py) + out = append(out, segment{op: 'Q', points: [6]float64{cx, cy, ex, ey}}) + controlX, controlY = cx, cy + x, y = ex, ey + case 'A': + rx, okRX := scan.number() + ry, okRY := scan.number() + rotation, okRotation := scan.number() + large, okLarge := scan.flag() + sweep, okSweep := scan.flag() + px, py, okEnd := scan.pair() + if !okRX || !okRY || !okRotation || !okLarge || !okSweep || !okEnd { + return out + } + ex, ey := offset(px, py) + out = appendArc(out, x, y, rx, ry, rotation, large, sweep, ex, ey) + x, y = ex, ey + } + previous = upper + } +} + +// appendArc appends the elliptical arc from (x1, y1) to (x2, y2) as cubic curves of +// at most a quarter turn each, following the endpoint-to-center conversion of SVG 1.1 +// appendix F.6.5 and F.6.6. +func appendArc(out []segment, x1, y1, rx, ry, rotation float64, large, sweep bool, x2, y2 float64) []segment { + if x1 == x2 && y1 == y2 { + return out + } + rx, ry = math.Abs(rx), math.Abs(ry) + if rx == 0 || ry == 0 { + return append(out, segment{op: 'L', points: [6]float64{x2, y2}}) + } + phi := rotation * math.Pi / 180 + cos, sin := math.Cos(phi), math.Sin(phi) + dx, dy := (x1-x2)/2, (y1-y2)/2 + x1p, y1p := cos*dx+sin*dy, -sin*dx+cos*dy + if lambda := x1p*x1p/(rx*rx) + y1p*y1p/(ry*ry); lambda > 1 { + root := math.Sqrt(lambda) + rx, ry = rx*root, ry*root + } + numerator := rx*rx*ry*ry - rx*rx*y1p*y1p - ry*ry*x1p*x1p + denominator := rx*rx*y1p*y1p + ry*ry*x1p*x1p + coefficient := 0.0 + if numerator > 0 && denominator > 0 { + coefficient = math.Sqrt(numerator / denominator) + } + if large == sweep { + coefficient = -coefficient + } + cxp, cyp := coefficient*rx*y1p/ry, -coefficient*ry*x1p/rx + cx := cos*cxp - sin*cyp + (x1+x2)/2 + cy := sin*cxp + cos*cyp + (y1+y2)/2 + ux, uy := (x1p-cxp)/rx, (y1p-cyp)/ry + vx, vy := (-x1p-cxp)/rx, (-y1p-cyp)/ry + start := math.Atan2(uy, ux) + delta := math.Atan2(ux*vy-uy*vx, ux*vx+uy*vy) + if !sweep && delta > 0 { + delta -= 2 * math.Pi + } else if sweep && delta < 0 { + delta += 2 * math.Pi + } + pieces := int(math.Ceil(math.Abs(delta)/(math.Pi/2) - 1e-9)) + pieces = max(pieces, 1) + step := delta / float64(pieces) + handle := 4.0 / 3.0 * math.Tan(step/4) + point := func(px, py float64) (float64, float64) { + return cx + rx*px*cos - ry*py*sin, cy + rx*px*sin + ry*py*cos + } + for piece := 0; piece < pieces; piece++ { + from := start + float64(piece)*step + to := from + step + c1x, c1y := point(math.Cos(from)-handle*math.Sin(from), math.Sin(from)+handle*math.Cos(from)) + c2x, c2y := point(math.Cos(to)+handle*math.Sin(to), math.Sin(to)-handle*math.Cos(to)) + ex, ey := point(math.Cos(to), math.Sin(to)) + if piece == pieces-1 { + ex, ey = x2, y2 + } + out = append(out, segment{op: 'C', points: [6]float64{c1x, c1y, c2x, c2y, ex, ey}}) + } + return out +} + +// isPathLetter reports whether b is one of the SVG path commands. +func isPathLetter(b byte) bool { + switch b | 0x20 { + case 'm', 'l', 'h', 'v', 'c', 's', 'q', 't', 'a', 'z': + return true + } + return false +} + +// scanner reads the numbers of SVG path data. +type scanner struct { + text string + pos int +} + +func (s *scanner) done() bool { return s.pos >= len(s.text) } + +func (s *scanner) peek() byte { return s.text[s.pos] } + +// skipSeparators skips white space and at most the commas between numbers. +func (s *scanner) skipSeparators() { + for !s.done() { + switch s.peek() { + case ' ', '\t', '\n', '\r', '\f', ',': + s.pos++ + default: + return + } + } +} + +// number reads one SVG number: an optional sign, digits with an optional fraction, +// and an optional exponent. "1.5.5" is two numbers and "1-2" is two, as in SVG. +func (s *scanner) number() (float64, bool) { + s.skipSeparators() + begin := s.pos + if !s.done() && (s.peek() == '+' || s.peek() == '-') { + s.pos++ + } + digits := s.digits() + if !s.done() && s.peek() == '.' { + s.pos++ + digits += s.digits() + } + if digits == 0 { + s.pos = begin + return 0, false + } + if !s.done() && (s.peek() == 'e' || s.peek() == 'E') { + mark := s.pos + s.pos++ + if !s.done() && (s.peek() == '+' || s.peek() == '-') { + s.pos++ + } + if s.digits() == 0 { + s.pos = mark + } + } + value, err := strconv.ParseFloat(s.text[begin:s.pos], 64) + return value, err == nil +} + +// digits skips a run of decimal digits and returns its length. +func (s *scanner) digits() int { + begin := s.pos + for !s.done() && s.peek() >= '0' && s.peek() <= '9' { + s.pos++ + } + return s.pos - begin +} + +// pair reads an x and y. +func (s *scanner) pair() (float64, float64, bool) { + x, ok := s.number() + if !ok { + return 0, 0, false + } + y, ok := s.number() + return x, y, ok +} + +// flag reads an arc flag, a single 0 or 1 that may touch the next number. +func (s *scanner) flag() (bool, bool) { + s.skipSeparators() + if s.done() { + return false, false + } + switch s.peek() { + case '0': + s.pos++ + return false, true + case '1': + s.pos++ + return true, true + } + return false, false +} diff --git a/desktop/internal/pluginview/path_test.go b/desktop/internal/pluginview/path_test.go new file mode 100644 index 0000000000..143e13f731 --- /dev/null +++ b/desktop/internal/pluginview/path_test.go @@ -0,0 +1,136 @@ +package pluginview + +import ( + "math" + "testing" +) + +// seg is a segment written briefly: op and its points. +func seg(op byte, points ...float64) segment { + s := segment{op: op} + copy(s.points[:], points) + return s +} + +// sameSegments compares two segment lists to a tolerance that absorbs arc arithmetic. +func sameSegments(got, want []segment) bool { + if len(got) != len(want) { + return false + } + for i := range got { + if got[i].op != want[i].op { + return false + } + for j := range got[i].points { + if math.Abs(got[i].points[j]-want[i].points[j]) > 1e-9 { + return false + } + } + } + return true +} + +func TestParsePathDataReadsEveryCommand(t *testing.T) { + for _, tc := range []struct { + name string + data string + want []segment + }{ + {"absolute lines", "M10 20 L30 40", []segment{seg('M', 10, 20), seg('L', 30, 40)}}, + {"relative lines, H, V and Z", "m10 20 l5 5 h10 v-5 z", + []segment{seg('M', 10, 20), seg('L', 15, 25), seg('L', 25, 25), seg('L', 25, 20), seg('Z')}}, + {"absolute H and V", "M1 2 H8 V9", []segment{seg('M', 1, 2), seg('L', 8, 2), seg('L', 8, 9)}}, + {"pairs after a move are lines", "M0 0 10 10 20 0", []segment{seg('M', 0, 0), seg('L', 10, 10), seg('L', 20, 0)}}, + {"pairs after a relative move are relative lines", "m1 1 2 2", []segment{seg('M', 1, 1), seg('L', 3, 3)}}, + {"a move after Z starts from the subpath's start", "M5 5 L9 5 Z m1 1 l1 0", + []segment{seg('M', 5, 5), seg('L', 9, 5), seg('Z'), seg('M', 6, 6), seg('L', 7, 6)}}, + {"S reflects the previous control", "M0 0 C10 0 20 10 30 10 S50 20 60 20", + []segment{seg('M', 0, 0), seg('C', 10, 0, 20, 10, 30, 10), seg('C', 40, 10, 50, 20, 60, 20)}}, + {"S after a line starts at the current point", "M0 0 L5 5 S10 10 20 0", + []segment{seg('M', 0, 0), seg('L', 5, 5), seg('C', 5, 5, 10, 10, 20, 0)}}, + {"relative C and S", "M10 10 c0 -10 10 -10 10 0 s10 10 10 0", + []segment{seg('M', 10, 10), seg('C', 10, 0, 20, 0, 20, 10), seg('C', 20, 20, 30, 20, 30, 10)}}, + {"T reflects the previous quadratic control", "M0 0 Q10 10 20 0 T40 0", + []segment{seg('M', 0, 0), seg('Q', 10, 10, 20, 0), seg('Q', 30, -10, 40, 0)}}, + {"T after a move uses the current point", "M3 4 T10 4", []segment{seg('M', 3, 4), seg('Q', 3, 4, 10, 4)}}, + {"SVG number forms", "M1.5.5L1-2M1e1 2E-1", []segment{seg('M', 1.5, 0.5), seg('L', 1, -2), seg('M', 10, 0.2)}}, + {"commas and line breaks separate numbers", "M1,2\nL3,4", []segment{seg('M', 1, 2), seg('L', 3, 4)}}, + {"a zero radius arc is a line", "M0 0 A0 5 0 0 1 10 0", []segment{seg('M', 0, 0), seg('L', 10, 0)}}, + {"an arc to its own start draws nothing", "M4 4 A5 5 0 0 1 4 4", []segment{seg('M', 4, 4)}}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := parsePathData(tc.data); !sameSegments(got, tc.want) { + t.Fatalf("parsePathData(%q) = %v, want %v", tc.data, got, tc.want) + } + }) + } +} + +func TestParsePathDataStopsAtTheFirstError(t *testing.T) { + for _, tc := range []struct { + name string + data string + want []segment + }{ + {"a line missing its y", "M0 0 L10", []segment{seg('M', 0, 0)}}, + {"a command before any move", "L10 10", nil}, + {"numbers after Z", "M0 0 L1 1 Z 5 5", []segment{seg('M', 0, 0), seg('L', 1, 1), seg('Z')}}, + {"a letter that is no command", "M0 0 X1 1", []segment{seg('M', 0, 0)}}, + {"an arc flag that is not 0 or 1", "M0 0 A5 5 0 2 1 10 0", []segment{seg('M', 0, 0)}}, + {"no data", "", nil}, + {"only separators", " ,\n", nil}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := parsePathData(tc.data); !sameSegments(got, tc.want) { + t.Fatalf("parsePathData(%q) = %v, want %v", tc.data, got, tc.want) + } + }) + } +} + +func TestParsePathDataTurnsArcsIntoQuarterCurves(t *testing.T) { + // A half circle of radius 10 about (10, 0), drawn as two quarter turns. + got := parsePathData("M0 0 A10 10 0 0 1 20 0") + if len(got) != 3 || got[1].op != 'C' || got[2].op != 'C' { + t.Fatalf("half circle = %v, want a move and two curves", got) + } + middle := got[1].points + if radius := math.Hypot(middle[4]-10, middle[5]); math.Abs(radius-10) > 1e-9 { + t.Errorf("the quarter point %v is %v from the center, want 10", middle[4:6], radius) + } + if end := got[2].points; end[4] != 20 || end[5] != 0 { + t.Errorf("the arc ends at %v, want exactly (20, 0)", end[4:6]) + } + // Flags that touch the next number, and a radius too small for the distance, which + // SVG scales up until the arc reaches its end. + touching := parsePathData("M0 0a5 5 0 1120 0") + if len(touching) < 2 { + t.Fatalf("arc with touching flags = %v", touching) + } + if end := touching[len(touching)-1].points; end[4] != 20 || end[5] != 0 { + t.Errorf("the scaled arc ends at %v, want (20, 0)", end[4:6]) + } + // The other sweep runs through the other side of the center. + other := parsePathData("M0 0 A10 10 0 0 0 20 0") + if len(other) != 3 || math.Signbit(other[1].points[5]) == math.Signbit(middle[5]) { + t.Errorf("sweep 0 = %v, want the half circle on the other side", other) + } +} + +func TestGeometryOfBoundsThePathAndKeepsIt(t *testing.T) { + line := &Shape{Type: "path", D: "M10 20 H30"} + geometry := line.geometryOf() + if geometry.empty || geometry.x != 9 || geometry.y != 19 || geometry.w != 22 || geometry.h != 2 { + t.Fatalf("horizontal line geometry = %+v, want one unit around the points", geometry) + } + if line.geometryOf() != geometry { + t.Fatal("the parsed path was not kept with the shape") + } + curve := &Shape{Type: "path", D: "M0 0 C-5 10 25 10 20 0"} + if g := curve.geometryOf(); g.x != -6 || g.y != -1 || g.w != 32 || g.h != 12 { + t.Fatalf("curve geometry = %+v, want its control points inside", g) + } + if empty := (&Shape{Type: "path", D: "L1 1"}).geometryOf(); !empty.empty { + t.Fatal("a path with no segment is drawn") + } +} diff --git a/desktop/internal/pluginview/render.go b/desktop/internal/pluginview/render.go new file mode 100644 index 0000000000..71390a1c9f --- /dev/null +++ b/desktop/internal/pluginview/render.go @@ -0,0 +1,638 @@ +package pluginview + +import ( + "context" + "errors" + "strconv" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// Host is what a surface lends the views it draws: its theme, its words, its icons and +// the settings page a region sits on. +type Host struct { + Palette Palette + Language i18n.Language + // Icon is the host icon a node names; ok is false for a name the host does not draw. + Icon func(name string) (gfx.Icon, bool) + // Images reads the PNGs of the plugin's package a canvas draws; nil draws none. + Images *Images + // Info draws the host's ⓘ for an info text. + Info func(c ui.C, text string) + // Settings is the settings page of a region; nil in a tool window. + Settings SettingsHost +} + +// SettingsHost is the settings page a region is drawn on. Its rows, tools, drafts and +// action flow stay the page's own: a region shows them, and never stores a value. +type SettingsHost interface { + // Row draws the page's own row for a declared setting, exactly as the page draws it. + // It reports false when the page has no such row. + Row(c ui.C, setting string) bool + // Tool draws the toolchain pages' row for a tool the plugin defines or requires. + // It reports false when the host has no row for it. + Tool(c ui.C, tool string) bool + // Binding is the draft of a declared setting for a control bound to it. + Binding(setting string) (Binding, bool) + // Action runs a setting action through the page's confirmation flow. It runs + // after the paint, as a native dialog must. + Action(action string) + // ActionEnabled reports whether the action can run now. + ActionEnabled(action string) bool +} + +// Binding is a declared setting's draft, which a control bound to it edits. Exactly +// one of Text, On and Selected is set, by the setting's kind. +type Binding struct { + Title string + Text *string + On *bool + Selected *int + // Options are the choices of an enum setting, and OptionLabel their words. + Options []int + OptionLabel func(int) string + // Editable is false while the draft cannot change: the page is saving, the setting + // is not editable in the scope shown, or there is no file to write. + Editable bool + // Value is the draft value typed as the setting stores it: a number for an integer. + Value func() any + // Edited tells the page the control changed the draft. + Edited func() +} + +// Draw declares a view in the space its parent gives it. In a tool window the view fills +// the body (fill), and a tree among its top-level nodes takes the height the others leave; +// a tree in a row or a section takes the height of its rows, up to treeRows. In a settings +// region the view takes the width and the height of its content. +func Draw(c ui.C, s *Session, host *Host, fill bool) { + if s == nil || host == nil { + return + } + // The answer that arrived is drawn in this paint, and a waiting viewport or settings + // event asks for the paint that sends it. + if wait := s.Take(); wait > 0 { + if canvas := c.Canvas(); canvas != nil { + canvas.RequestFrameIn(wait) + } + } + r := &renderer{c: c, s: s, host: host} + root := ui.Column(c).FillWidth().Gap(10) + if fill { + root = root.Fill() + } + root.Children(func() { + r.frame(c) + if !s.Drawn() { + return + } + nodes := s.View() + if fill && !hasTree(nodes) { + ui.Scroll(c).FillWidth().Grow(1).Children(func() { + ui.Column(c).FillWidth().Gap(10).PadX(10).PadY(10).Children(func() { r.nodes(c, nodes) }) + }) + return + } + body := ui.Column(c).FillWidth().Gap(10) + if fill { + body = body.Grow(1).PadX(10).PadY(10) + } + r.fillTree = fill + body.Children(func() { r.nodes(c, nodes) }) + }) +} + +// hasTree reports a tree among the top-level nodes: it scrolls by itself, so the body does not. +func hasTree(nodes []Node) bool { + for i := range nodes { + if nodes[i].Type == "tree" { + return true + } + } + return false +} + +// renderer declares the nodes of one view in one paint. +type renderer struct { + c ui.C + s *Session + host *Host + // fillTree says a tree declared now is a top-level node of a view that fills its + // window, so it takes the height the other nodes leave; a tree in a row or a section + // sits in the scrolling body and takes the height of its rows. + fillTree bool +} + +// treeRows is the most rows a tree in the scrolling body shows before it scrolls itself. +const treeRows = 12 + +// frame is the view's own frame: what is loading, and the failure of the last call with +// Retry. The rest of the window stays usable, and a drawn view stays under it. +func (r *renderer) frame(c ui.C) { + p := &r.host.Palette + err := r.s.Err() + if err == nil { + if r.s.Busy() && !r.s.Drawn() { + ui.Text(c, i18n.Shared(r.host.Language, "native.loading")).FontSize(12).Color(p.TextMuted) + } + return + } + message, detail := r.failure(err) + ui.Row(c.Key("failure")).FillWidth().Gap(8).Items(ui.Center).PadX(10).PadY(6).Radius(6). + Background(p.Warning.WithAlpha(0.10)).Border(1, p.Warning.WithAlpha(0.35)).Children(func() { + ui.Column(c).Grow(1).Shrink(1).MinWidth(0).Gap(2).Children(func() { + ui.Wrap(c, message).FontSize(12).Color(p.Text) + if detail != "" { + ui.Wrap(c, detail).FontSize(11).Color(p.TextMuted) + } + }) + if ui.Button(c, i18n.Shared(r.host.Language, "desktop.everywhere.retry")).Outline().Small().Shrink(0).Clicked() { + r.s.Retry() + } + }) +} + +// failure is the host's words for a failed call, and the diagnostic under them: Core's +// refusal with the JSON path it names, or the plugin's own error, which is not translated. +func (r *renderer) failure(err error) (message, detail string) { + language := r.host.Language + var rejection *core.MarketplaceRejection + switch { + case errors.As(err, &rejection): + detail = rejection.Message + if rejection.Field != "" { + detail = rejection.Field + ": " + rejection.Message + } + return i18n.Shared(language, "desktop.pluginView.invalid"), detail + case errors.Is(err, context.DeadlineExceeded): + return i18n.Shared(language, "desktop.pluginView.timedOut"), "" + } + return i18n.Shared(language, "desktop.pluginView.failed"), err.Error() +} + +// nodes declares nodes in order, each keyed by its ID or its place. +func (r *renderer) nodes(c ui.C, nodes []Node) { + for i := range nodes { + n := &nodes[i] + key := c.KeyInt(i) + if n.ID != "" { + key = c.Key("#" + n.ID) + } + r.node(key, n) + } +} + +// node declares one node. +func (r *renderer) node(c ui.C, n *Node) { + p := &r.host.Palette + switch n.Type { + case "row", "section": + // A tree among the children does not fill the window: rows and sections take the + // height of their content. + fillTree := r.fillTree + r.fillTree = false + defer func() { r.fillTree = fillTree }() + } + switch n.Type { + case "row": + ui.Flow(c).FillWidth().Items(ui.Center).Gap(8).LineGap(6).Children(func() { r.nodes(c, n.Children) }) + case "section": + ui.Column(c).FillWidth().Gap(6).Children(func() { + if n.Title != "" { + ui.Row(c).FillWidth().MinHeight(28).Items(ui.Center).Gap(8).Children(func() { + ui.Text(c, n.Title).FontSize(13).Weight(gfx.WeightSemibold).Color(p.Text).Shrink(1).MinWidth(0).Ellipsis() + r.info(c, n.Info) + }) + } + ui.Column(c).FillWidth().Gap(8).Children(func() { r.nodes(c, n.Children) }) + }) + case "label": + r.label(c, n) + case "textField": + r.textField(c, n) + case "select", "segmented": + r.choice(c, n) + case "toggle": + r.toggle(c, n) + case "button": + r.button(c, n) + case "keyValue": + r.keyValue(c, n) + case "table": + r.table(c, n) + case "banner": + tone := p.Tone(n.Tone, p.Accent) + ui.Row(c).FillWidth().PadX(10).PadY(8).Radius(6).Background(tone.WithAlpha(0.10)).Border(1, tone.WithAlpha(0.35)).Children(func() { + ui.Wrap(c, n.Text).FontSize(12).Color(p.Text).Grow(1).MinWidth(0) + }) + case "setting": + if r.host.Settings != nil { + r.host.Settings.Row(c, n.Setting) + } + case "tool": + if r.host.Settings != nil { + r.host.Settings.Tool(c, n.Tool) + } + case "tree": + r.tree(c, n) + case "canvas": + r.canvas(c, n) + } +} + +// info draws the host's ⓘ for text, nothing for none. +func (r *renderer) info(c ui.C, text string) { + if text != "" && r.host.Info != nil { + r.host.Info(c, text) + } +} + +// textStyle is the font of a label style: its size, weight and whether it is monospaced. +func textStyle(style string) (size float32, weight float32, mono bool) { + switch style { + case "title": + return 15, gfx.WeightSemibold, false + case "strong": + return 13, gfx.WeightSemibold, false + case "caption": + return 11, gfx.WeightRegular, false + case "mono": + return 12, gfx.WeightRegular, true + } + return 13, gfx.WeightRegular, false +} + +// characterWidth is the width a reserved character takes at size: an average glyph of +// the interface font, or the monospace advance. +func characterWidth(size float32, mono bool) float32 { + if mono { + return size * 0.62 + } + return size * 0.56 +} + +// label declares a label: body and caption wrap, the other styles are one line. +func (r *renderer) label(c ui.C, n *Node) { + p := &r.host.Palette + size, weight, mono := textStyle(n.Style) + fallback := p.Text + if n.Style == "caption" { + fallback = p.TextSecondary + } + color := p.Tone(n.Tone, fallback) + var box ui.Box + if n.Style == "" || n.Style == "body" || n.Style == "caption" { + box = ui.Wrap(c, n.Text) + } else { + box = ui.Text(c, n.Text).Ellipsis() + } + box = box.FontSize(size).Weight(weight).Color(color).MinWidth(0) + if mono { + box = box.Mono() + } + if count, _ := n.characters(); count > 0 { + box.Width(float32(count) * characterWidth(size, mono)).Shrink(0) + } else { + box.Shrink(1) + } +} + +// caption declares a control's label and ⓘ on its leading side; nothing for no label. +func (r *renderer) caption(c ui.C, label, info string) { + if label == "" && info == "" { + return + } + ui.Row(c.Part("caption")).Shrink(1).MinWidth(0).Items(ui.Center).Gap(6).Children(func() { + if label != "" { + ui.Text(c, label).FontSize(12).Weight(gfx.WeightSemibold).Color(r.host.Palette.Text).Shrink(1).MinWidth(0).Ellipsis() + } + r.info(c, info) + }) +} + +// binding is the bound draft of n, ok false for a control with its own value or a +// setting the page does not have. +func (r *renderer) binding(n *Node) (Binding, bool) { + if n.Setting == "" || r.host.Settings == nil { + return Binding{}, false + } + return r.host.Settings.Binding(n.Setting) +} + +// changed sends change for n: the bound setting's typed draft, or the control's own value. +func (r *renderer) changed(n *Node, binding Binding, bound bool, value any) { + event := Event{Name: "change", Node: n.ID, Value: value} + if bound { + event.Setting = n.Setting + if binding.Value != nil { + event.Value = binding.Value() + } + } + r.s.Send(event) +} + +// textField declares a text field. It commits on Enter or when it loses the focus with +// text that differs from what it last sent, never per keystroke. +func (r *renderer) textField(c ui.C, n *Node) { + binding, bound := r.binding(n) + if n.Setting != "" && (!bound || binding.Text == nil) { + return + } + label := n.Label + if bound && label == "" { + label = binding.Title + } + own := n.stringValue() + state := r.s.field(n.ID, own) + text := &state.text + if bound { + text = binding.Text + } else if state.last != own && !state.focused { + state.text, state.last, state.sent = own, own, own + } + if !state.started { + state.sent, state.started = *text, true + } + enabled := n.enabled() && (!bound || binding.Editable) + count, fillWidth := n.characters() + row := ui.Row(c).Items(ui.Center).Gap(8).MinWidth(0) + if fillWidth || count == 0 { + row = row.Grow(1).Basis(0) + } + row.Children(func() { + r.caption(c, n.Label, n.Info) + if !enabled { + r.readOnly(c, label, *text, count, fillWidth, n.Mono) + state.focused = false + return + } + field := ui.TextField(c, text, label, n.Placeholder).Height(30).MinWidth(0) + if n.Mono { + field = field.Mono() + } + if count > 0 && !fillWidth { + field = field.Width(float32(count)*characterWidth(13, n.Mono) + 20).Shrink(0) + } else { + field = field.Grow(1) + } + if field.Changed() && bound && binding.Edited != nil { + binding.Edited() + } + focused := field.State().Focused + if (field.Submitted() || (state.focused && !focused)) && *text != state.sent { + state.sent = *text + r.changed(n, binding, bound, *text) + } + state.focused = focused + }) +} + +// readOnly is a field that takes no input: its text in a frame, which assistive +// technology reads as a read-only text field, as the settings pages draw one. +func (r *renderer) readOnly(c ui.C, label, value string, count int, fillWidth, mono bool) { + p := &r.host.Palette + frame := ui.Row(c).MinWidth(0).Height(30).PadX(10).Border(1, p.Line).Radius(6).Items(ui.Center). + HitWith(ui.ID(c), label, gfx.HitOptions{Role: gfx.RoleTextField, Value: value, ReadOnly: true, Disabled: true}) + if count > 0 && !fillWidth { + frame = frame.Width(float32(count)*characterWidth(13, mono) + 20).Shrink(0) + } else { + frame = frame.Grow(1) + } + frame.Children(func() { + text := ui.Text(c, value).FontSize(13).Color(p.TextMuted).Ellipsis() + if mono { + text.Mono() + } + }) +} + +// choice declares a select or segmented control, over its own options or a bound enum's. +// A control that takes no input is the read-only frame the settings pages draw, since +// Disabled does not reach a Select or Choice in pinned Viva. +func (r *renderer) choice(c ui.C, n *Node) { + binding, bound := r.binding(n) + if n.Setting != "" && (!bound || binding.Selected == nil) { + return + } + enabled := n.enabled() && (!bound || binding.Editable) + label := n.Label + if bound && label == "" { + label = binding.Title + } + ui.Row(c).Items(ui.Center).Gap(8).MinWidth(0).Children(func() { + r.caption(c, n.Label, n.Info) + if bound { + if !enabled { + r.readOnly(c, label, binding.OptionLabel(*binding.Selected), 0, false, false) + return + } + if choose(c, n, label, binding.Selected, binding.Options, binding.OptionLabel) { + if binding.Edited != nil { + binding.Edited() + } + r.changed(n, binding, true, nil) + } + return + } + state := r.s.selection(n.ID, n.stringValue()) + values, words := optionsOf(n.Options) + name := func(value string) string { return words[value] } + if !enabled { + r.readOnly(c, label, name(state.value), 0, false, false) + return + } + if choose(c, n, label, &state.value, values, name) { + r.changed(n, binding, false, state.value) + } + }) +} + +// choose declares the select or segmented control of n over value and reports a choice +// the user made in this paint. +func choose[T comparable](c ui.C, n *Node, label string, value *T, values []T, name func(T) string) bool { + if n.Type == "segmented" { + return ui.Choice(c, value, values, name).Label(label).Changed() + } + return ui.Select(c, value, values, name).MinWidth(120).MaxWidth(230).Label(label).Changed() +} + +// optionsOf splits options into their values and the words of each. +func optionsOf(options []Option) ([]string, map[string]string) { + values := make([]string, len(options)) + words := make(map[string]string, len(options)) + for i, option := range options { + values[i] = option.Value + words[option.Value] = option.Label + } + return values, words +} + +// toggle declares a switch with its label on the leading side. +func (r *renderer) toggle(c ui.C, n *Node) { + binding, bound := r.binding(n) + if n.Setting != "" && (!bound || binding.On == nil) { + return + } + enabled := n.enabled() && (!bound || binding.Editable) + label := n.Label + if bound && label == "" { + label = binding.Title + } + ui.Row(c).Items(ui.Center).Gap(8).MinWidth(0).Children(func() { + r.caption(c, n.Label, n.Info) + on := binding.On + if !bound { + on = &r.s.toggle(n.ID, n.boolValue()).on + } + if ui.Switch(c, on, "").Label(label).Disabled(!enabled).Changed() { + if bound && binding.Edited != nil { + binding.Edited() + } + r.changed(n, binding, bound, *on) + } + }) +} + +// button declares a button: the primary tone is filled, the others outlined. With an +// action it runs that setting action through the page's flow instead of sending click. +func (r *renderer) button(c ui.C, n *Node) { + enabled := n.enabled() + if n.Action != "" { + enabled = enabled && r.host.Settings != nil && r.host.Settings.ActionEnabled(n.Action) + } + button := ui.Button(c, n.Text) + if n.Tone != "primary" { + button = button.Outline() + } + if icon, ok := r.icon(n.Icon); ok { + button = button.Icon(icon) + } + if !button.Shrink(0).Disabled(!enabled).Clicked() { + return + } + if n.Action != "" { + action, settings := n.Action, r.host.Settings + c.After(func() { settings.Action(action) }) + return + } + r.s.Send(Event{Name: "click", Node: n.ID}) +} + +// icon is the host icon name names, ok false for none or one the host does not draw. +func (r *renderer) icon(name string) (gfx.Icon, bool) { + if name == "" || r.host.Icon == nil { + return gfx.Icon{}, false + } + return r.host.Icon(name) +} + +// tree declares a tree: the host opens and closes items without the plugin, a click or +// Return on an item selects it (select), and a double click or Return activates it +// (activate). Activating a branch also opens or closes it, as an IDE's tree does. +func (r *renderer) tree(c ui.C, n *Node) { + p := &r.host.Palette + state := r.s.tree(n.ID) + state.flatten(n.Items) + content := func(i int) { + item := state.rows[i].item + if icon, ok := r.icon(item.Icon); ok { + ui.Icon(c, icon).Size(14, 14).Shrink(0) + } + ui.Text(c, item.Label).FontSize(12.5).Color(p.Text).Shrink(1).MinWidth(0).Ellipsis().LabelFor(state.tree.RowID(i)) + if item.Detail != "" { + ui.Text(c, item.Detail).FontSize(11.5).Color(p.TextMuted).Shrink(2).MinWidth(0).Ellipsis() + } + } + box := ui.Tree(c, &state.tree, len(state.rows), state.tree.Label, content).Scrollbars().Label(n.Label).FillWidth() + if r.fillTree { + box.Grow(1).MinHeight(80) + } else { + box.Height(state.tree.RowHeight * float32(max(1, min(len(state.rows), treeRows)))) + } + toggled := -1 + if i, ok := state.tree.Toggled(); ok { + toggled = i + item := state.rows[i].item + open := !state.expanded(item) + c.After(func() { state.open[item.ID] = open }) + } + i, ok := state.tree.Chosen() + if !ok { + return + } + canvas := c.Canvas() + byKey := canvas.ClickedByKey(state.tree.RowID(i)) + info, _ := canvas.ClickInfo() + item, tree, session := state.rows[i].item, n.ID, r.s + activate := byKey || info.Clicks >= 2 + branch := len(item.Children) > 0 && toggled != i + open := !state.expanded(item) + c.After(func() { + if item.ID != state.selected { + state.selected = item.ID + session.Send(Event{Name: "select", Node: tree, Item: item.ID}) + } + if !activate { + return + } + if branch { + state.open[item.ID] = open + } + session.Send(Event{Name: "activate", Node: tree, Item: item.ID}) + }) +} + +// keyValue declares label and value pairs, the labels in one column. +func (r *renderer) keyValue(c ui.C, n *Node) { + p := &r.host.Palette + ui.Column(c).FillWidth().Gap(4).Children(func() { + for i, item := range n.Items { + ui.Row(c.KeyInt(i)).FillWidth().Items(ui.Start).Gap(12).Children(func() { + ui.Text(c, item.Label).FontSize(12).Color(p.TextSecondary).Basis(0).Grow(1).MinWidth(80).Ellipsis() + ui.Wrap(c, item.Value).FontSize(12).Color(p.Tone(item.Tone, p.Text)).Basis(0).Grow(2).MinWidth(0) + }) + } + }) +} + +// table declares a read-only table: a header row, then one single-line cell per column. +func (r *renderer) table(c ui.C, n *Node) { + p := &r.host.Palette + cell := func(c ui.C, text string, column int, header bool) { + box := ui.Text(c, text).FontSize(12).Basis(0).Grow(1).MinWidth(0).Ellipsis() + if header { + box = box.Weight(gfx.WeightSemibold).Color(p.TextSecondary) + } else { + box = box.Color(p.Text) + } + if column < len(n.Columns) { + switch n.Columns[column].Align { + case "end": + box.TextEnd() + case "center": + box.TextCenter() + } + } + } + ui.Column(c).FillWidth().Border(1, p.Line).Radius(6).Clip().Children(func() { + ui.Row(c.Key("header")).FillWidth().Height(26).PadX(10).Gap(12).Items(ui.Center).Background(p.Sidebar).Children(func() { + for i, column := range n.Columns { + cell(c.KeyInt(i), column.Title, i, true) + } + }) + for i, cells := range n.Rows { + ui.Row(c.Key("line-" + strconv.Itoa(i))).FillWidth().Height(1).Background(p.Line) + ui.Row(c.KeyInt(i)).FillWidth().Height(26).PadX(10).Gap(12).Items(ui.Center).Children(func() { + for column := range n.Columns { + text := "" + if column < len(cells) { + text = cells[column] + } + cell(c.KeyInt(column), text, column, false) + } + }) + } + }) +} diff --git a/desktop/internal/pluginview/render_test.go b/desktop/internal/pluginview/render_test.go new file mode 100644 index 0000000000..555213afd7 --- /dev/null +++ b/desktop/internal/pluginview/render_test.go @@ -0,0 +1,242 @@ +package pluginview + +import ( + "encoding/json" + "errors" + "strconv" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// viewDriver draws a session's view as a tool window body in a headless window and +// addresses its controls by their accessible names, as a user would. +type viewDriver struct { + t *testing.T + b *backend + s *Session + driver *app.Driver + invalidator *app.Invalidator +} + +// drawView opens a session whose plugin answers every event with view, takes the open +// answer and draws it. +func drawView(t *testing.T, view string) *viewDriver { + t.Helper() + b := newBackend(t) + b.answer = func(map[string]any) (json.RawMessage, bool, error) { return json.RawMessage(view), true, nil } + s := b.session() + s.Open() + b.answered(s) + if !s.Drawn() { + t.Fatalf("the open answer was not drawn: %v", s.Err()) + } + theme := ui.LightTheme() + background := theme.Background + invalidator := &app.Invalidator{} + host := &Host{Palette: testPalette(false), Language: i18n.English, Icon: HostIcon} + page := ui.NewPage(ui.PageConfig{ + View: func(c ui.C) { Draw(c, s, host, true) }, + Theme: &theme, + Background: &background, + Invalidator: invalidator, + }) + driver, err := app.NewDriver(page.Config(app.Config{Width: 480, Height: 400, Invalidator: invalidator}), nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(driver.Close) + return &viewDriver{t: t, b: b, s: s, driver: driver, invalidator: invalidator} +} + +// repaint paints the frame again after the session changed outside a paint, as the wake +// the window gets for an answer does. +func (d *viewDriver) repaint() { + d.t.Helper() + d.invalidator.Invalidate() + if err := d.driver.Pump(); err != nil { + d.t.Fatal(err) + } +} + +// click clicks the middle of the front-most control labeled label and paints again, so +// the work the click left for after the paint runs. +func (d *viewDriver) click(label string) { + d.t.Helper() + d.clickCount(label, 1) +} + +func (d *viewDriver) clickCount(label string, clicks int) { + d.t.Helper() + hits := d.driver.Snapshot().Hits + for i := len(hits) - 1; i >= 0; i-- { + hit := hits[i] + if hit.Label != label || hit.IsLabel || hit.Backdrop || hit.ID.IsZero() { + continue + } + if err := d.driver.ClickCount(hit.Bounds.X+hit.Bounds.Width/2, hit.Bounds.Y+hit.Bounds.Height/2, clicks); err != nil { + d.t.Fatal(err) + } + if err := d.driver.Pump(); err != nil { + d.t.Fatal(err) + } + return + } + d.t.Fatalf("no control labeled %q", label) +} + +// shows reports whether a label of the frame reads exactly text. +func (d *viewDriver) shows(text string) bool { + for _, label := range d.driver.Snapshot().Labels { + if label.Value == text { + return true + } + } + return false +} + +// sent runs the one call the clicks queued and is the event it carried. +func (d *viewDriver) sent() map[string]any { + d.t.Helper() + if len(d.b.pending) != 1 { + d.t.Fatalf("%d calls waiting, want one", len(d.b.pending)) + } + d.b.answered(d.s) + return d.b.last() +} + +func TestDrawSendsClickForAButtonAndDrawsItsText(t *testing.T) { + d := drawView(t, `[ + {"type": "label", "id": "count", "text": "3 modules"}, + {"type": "row", "children": [ + {"type": "button", "id": "sync", "text": "Sync", "tone": "primary", "icon": "refresh"}, + {"type": "button", "id": "later", "text": "Later", "enabled": false} + ]} + ]`) + if !d.shows("3 modules") { + t.Fatal("the label is not drawn") + } + d.click("Later") + if len(d.b.pending) != 0 { + t.Fatal("a disabled button sent an event") + } + d.click("Sync") + if event := d.sent(); event["event"] != "click" || event["node"] != "sync" { + t.Fatalf("event = %v, want click on sync", event) + } +} + +func TestDrawSendsChangeForAToggleWithItsValue(t *testing.T) { + d := drawView(t, `[{"type": "toggle", "id": "watch", "label": "Watch files", "value": false}]`) + d.click("Watch files") + if event := d.sent(); event["event"] != "change" || event["node"] != "watch" || event["value"] != true { + t.Fatalf("event = %v, want change of watch to true", event) + } +} + +func TestDrawSendsSelectOnceAndActivateForATreeItem(t *testing.T) { + d := drawView(t, `[{"type": "tree", "id": "modules", "label": "Modules", "items": [ + {"id": "core", "label": "core", "detail": "3 files", "icon": "plugin"}, + {"id": "app", "label": "app"} + ]}]`) + if !d.shows("3 files") { + t.Fatal("the item's detail is not drawn") + } + d.click("core") + if event := d.sent(); event["event"] != "select" || event["node"] != "modules" || event["item"] != "core" { + t.Fatalf("event = %v, want select of core", event) + } + d.repaint() + d.click("core") + if len(d.b.pending) != 0 { + t.Fatal("selecting the selected item sent select again") + } + d.repaint() + d.clickCount("app", 2) + if event := d.sent(); event["event"] != "select" || event["item"] != "app" { + t.Fatalf("a double click first sent %v, want select of app", event) + } + if event := d.sent(); event["event"] != "activate" || event["node"] != "modules" || event["item"] != "app" { + t.Fatalf("a double click then sent %v, want activate of app", event) + } +} + +// hitOf is the front-most control labeled label, ok false for none drawn. +func (d *viewDriver) hitOf(label string) (gfx.Rect, bool) { + hits := d.driver.Snapshot().Hits + for i := len(hits) - 1; i >= 0; i-- { + if hit := hits[i]; hit.Label == label && !hit.IsLabel && !hit.Backdrop && !hit.ID.IsZero() { + return hit.Bounds, true + } + } + return gfx.Rect{}, false +} + +// nestedTreeView is a section holding a tree of count items and a toggle under it. +func nestedTreeView(count int) string { + items := make([]map[string]any, count) + for i := range items { + items[i] = map[string]any{"id": "m" + strconv.Itoa(i), "label": "module " + strconv.Itoa(i)} + } + view, _ := json.Marshal([]map[string]any{{"type": "section", "title": "Modules", "children": []map[string]any{ + {"type": "tree", "id": "modules", "label": "Modules", "items": items}, + {"type": "toggle", "id": "watch", "label": "Watch", "value": true}, + }}}) + return string(view) +} + +// A tree in a section sits in the scrolling body: it takes the height of its rows, so every +// row shows and what follows it sits right under it, up to treeRows rows, past which it +// scrolls by itself. +func TestDrawGivesANestedTreeTheHeightOfItsRows(t *testing.T) { + d := drawView(t, nestedTreeView(4)) + last, ok := d.hitOf("module 3") + if !ok { + t.Fatal("the last row of a short nested tree is not shown") + } + toggle, ok := d.hitOf("Watch") + if !ok { + t.Fatal("the toggle under the tree is not shown") + } + if gap := toggle.Y - (last.Y + last.Height); gap < 0 || gap > 20 { + t.Fatalf("the toggle is %v under the last row, want right under it", gap) + } + + d = drawView(t, nestedTreeView(treeRows+8)) + if _, ok := d.hitOf("module " + strconv.Itoa(treeRows-1)); !ok { + t.Fatalf("a long nested tree does not show %d rows", treeRows) + } + if _, ok := d.hitOf("module " + strconv.Itoa(treeRows+1)); ok { + t.Fatalf("a long nested tree shows more than %d rows instead of scrolling", treeRows) + } + if _, ok := d.hitOf("Watch"); !ok { + t.Fatal("the toggle under a long tree is not shown") + } +} + +func TestDrawShowsTheFailureWithRetry(t *testing.T) { + d := drawView(t, `[{"type": "button", "id": "sync", "text": "Sync"}]`) + d.b.answer = func(map[string]any) (json.RawMessage, bool, error) { + return nil, false, errPluginFailed + } + d.click("Sync") + d.sent() + d.repaint() + if !d.shows(i18n.Shared(i18n.English, "desktop.pluginView.failed")) || !d.shows(errPluginFailed.Error()) { + t.Fatal("the failure and the plugin's own message are not drawn") + } + if !d.shows("Sync") { + t.Fatal("the drawn view went away under the failure") + } + d.b.answer = nil + d.click(i18n.Shared(i18n.English, "desktop.everywhere.retry")) + if event := d.sent(); event["event"] != "click" || event["node"] != "sync" { + t.Fatalf("retry sent %v, want the failed click again", event) + } +} + +// errPluginFailed is a backend's own failure, shown untranslated under the host's words. +var errPluginFailed = errors.New("the index is locked") diff --git a/desktop/internal/pluginview/session.go b/desktop/internal/pluginview/session.go new file mode 100644 index 0000000000..4730890ef7 --- /dev/null +++ b/desktop/internal/pluginview/session.go @@ -0,0 +1,544 @@ +package pluginview + +import ( + "context" + "encoding/json" + "errors" + "strconv" + "sync" + "sync/atomic" + "time" + + "github.com/vivaui/viva/ui" +) + +// settleDelay is how long a canvas stays still, or the settings stay unchanged, before +// the host sends the viewport or settings event: the contract's 400 ms for viewport, +// which settings follow so typing in a declared row does not call the backend per key. +const settleDelay = 400 * time.Millisecond + +// Call sends one view event to the plugin's backend and has Core check the answer. It +// runs on a goroutine of its own and returns the whole view to draw and whether it +// differs from view, the view the host drew last. ctx ends when the view closes, so the +// caller drops a late answer. A close event (closing) returns nothing. +type Call func(ctx context.Context, event, view json.RawMessage, closing bool) (json.RawMessage, bool, error) + +// Options connect a Session to its host. +type Options struct { + // Call sends events; nil leaves the view empty. + Call Call + // Params are the params every event of the surface carries, such as surface, + // language and settings. It runs on the window thread when an event is sent, so an + // event carries the values in force at that moment. + Params func() map[string]any + // Wake asks the window for a frame. It is called from the call's goroutine once an + // answer arrives, and must be safe to call from any goroutine. + Wake func() + // Failed logs, on the window thread, a view the session cannot read although Core + // accepted it, which the view then shows as a failure. A call's own failure is logged + // by Call, which knows the call. + Failed func(error) + // Now is the clock that settles viewport and settings events; nil is time.Now. + // Tests inject a fixed clock so a debounce never depends on real time. + Now func() time.Time + // Context bounds every call: the host's context for the place the view is shown in, + // such as the open project. nil is context.Background(). + Context context.Context + // Go runs one call off the window thread; nil starts a goroutine. It is called on the + // window thread, so a host that waits for its background work when it ends can count + // the call before it starts. + Go func(work func()) +} + +// Event is one view event the host sends. Name is the contract's event name; the other +// fields apply to the events the contract lists them for. +type Event struct { + Name string + Node string + Canvas string + Value any + Setting string + Item string + Viewport *Viewport +} + +// Viewport is the visible part of a canvas in view-box coordinates. +type Viewport struct { + X float64 `json:"x"` + Y float64 `json:"y"` + Width float64 `json:"width"` + Height float64 `json:"height"` +} + +// outcome is the answer of one call, handed from its goroutine to the window thread. +type outcome struct { + generation uint64 + event Event + view json.RawMessage + changed bool + err error +} + +// settling is a viewport or settings event waiting for the input to stop. +type settling struct { + event Event + due time.Time +} + +// instances numbers the showings of every view in this process, so each open gets a +// new instance string. +var instances atomic.Uint64 + +// Session is one showing of one plugin view: a tool window's body in one workspace, or +// one settings region on an open page. All methods except the call's own goroutine run +// on the window thread. +type Session struct { + options Options + + mu sync.Mutex + done *outcome + + open bool + instance string + raw json.RawMessage + nodes []Node + err error + // failed is the event whose call failed last; Retry sends it again. + failed *Event + busy bool + generation uint64 + cancel context.CancelFunc + queue []Event + settings *settling + viewports map[string]*settling + + // fields, selects, toggles, trees and canvases are the host's own state of the + // drawn nodes, by node ID. They live in memory and end with the showing. + fields map[string]*fieldState + selects map[string]*selectState + toggles map[string]*toggleState + trees map[string]*treeState + canvases map[string]*canvasState +} + +// NewSession returns a closed session; Open shows it. +func NewSession(options Options) *Session { + if options.Now == nil { + options.Now = time.Now + } + if options.Context == nil { + options.Context = context.Background() + } + if options.Go == nil { + options.Go = func(work func()) { go work() } + } + return &Session{options: options} +} + +// Open shows the view: it sends open with a new instance. A session already open is +// left as it is. +func (s *Session) Open() { + if s == nil || s.open { + return + } + s.open = true + s.instance = "view-" + strconv.FormatUint(instances.Add(1), 10) + s.queue = append(s.queue[:0], Event{Name: "open"}) + s.pump() +} + +// Close hides the view: it cancels the pending call, drops its late answer and every +// waiting event, sends close, and forgets the view and the host's state of it. +func (s *Session) Close() { + if s == nil || !s.open { + return + } + if s.cancel != nil { + s.cancel() + } + if s.options.Call != nil { + event := s.encode(Event{Name: "close"}) + view, call := s.raw, s.options.Call + // The close event outlives the showing, so it is not cancelled with it. + ctx := context.WithoutCancel(s.options.Context) + s.options.Go(func() { _, _, _ = call(ctx, event, view, true) }) + } + // The generation moves on so a late answer is dropped; mu stays, since the cancelled + // call's goroutine may still be about to hand its answer over. + s.generation++ + s.open, s.instance, s.raw, s.nodes, s.err, s.failed = false, "", nil, nil, nil, nil + s.busy, s.cancel, s.queue, s.settings, s.viewports = false, nil, nil, nil, nil + s.fields, s.selects, s.toggles, s.trees, s.canvases = nil, nil, nil, nil, nil +} + +// Opened reports whether the view is showing. +func (s *Session) Opened() bool { return s != nil && s.open } + +// Instance is the instance string of the current showing, empty when closed. +func (s *Session) Instance() string { + if s == nil { + return "" + } + return s.instance +} + +// Send queues one event and sends it once the events before it have their answers. +func (s *Session) Send(event Event) { + if s == nil || !s.open { + return + } + s.queue = append(s.queue, event) + s.pump() +} + +// SettingsChanged sends settings once the values stop changing for settleDelay. A +// change while one waits restarts the wait; the event carries the values at sending. +func (s *Session) SettingsChanged() { + if s == nil || !s.open { + return + } + s.settings = &settling{event: Event{Name: "settings"}, due: s.options.Now().Add(settleDelay)} +} + +// ViewportMoved sends viewport for the canvas once it stops moving for settleDelay. +func (s *Session) ViewportMoved(canvas string, viewport Viewport) { + if s == nil || !s.open { + return + } + if s.viewports == nil { + s.viewports = map[string]*settling{} + } + s.viewports[canvas] = &settling{ + event: Event{Name: "viewport", Canvas: canvas, Viewport: &viewport}, + due: s.options.Now().Add(settleDelay), + } +} + +// Take applies an answer that arrived and sends the events that are due. The host calls +// it at the start of each frame that draws the view. wait is how long until the next +// waiting event is due, 0 when none waits, so the host asks for a frame then. +func (s *Session) Take() (wait time.Duration) { + if s == nil || !s.open { + return 0 + } + s.mu.Lock() + done := s.done + s.done = nil + s.mu.Unlock() + if done != nil && done.generation == s.generation { + s.busy, s.cancel = false, nil + s.apply(done) + } + now := s.options.Now() + if s.settings != nil { + if !now.Before(s.settings.due) { + s.enqueue(s.settings.event) + s.settings = nil + } else { + wait = s.settings.due.Sub(now) + } + } + for canvas, waiting := range s.viewports { + if !now.Before(waiting.due) { + s.enqueue(waiting.event) + delete(s.viewports, canvas) + continue + } + if left := waiting.due.Sub(now); wait == 0 || left < wait { + wait = left + } + } + s.pump() + return wait +} + +// apply takes in the answer of the call that just finished. +func (s *Session) apply(done *outcome) { + if done.err != nil { + if errors.Is(done.err, context.Canceled) { + return + } + s.err = done.err + event := done.event + s.failed = &event + return + } + if len(done.view) == 0 { + return + } + if s.raw == nil || done.changed { + nodes, err := Decode(done.view) + if err != nil { + if s.options.Failed != nil { + s.options.Failed(err) + } + s.err = err + event := done.event + s.failed = &event + return + } + s.raw, s.nodes = done.view, nodes + } + s.err, s.failed = nil, nil +} + +// enqueue queues a settled event, merging it into a waiting one of the same kind: the +// latest settings, or the latest viewport of the same canvas, is all the plugin needs. +func (s *Session) enqueue(event Event) { + for i, waiting := range s.queue { + if waiting.Name == event.Name && (event.Name == "settings" || waiting.Canvas == event.Canvas) { + s.queue = append(s.queue[:i], s.queue[i+1:]...) + break + } + } + s.queue = append(s.queue, event) +} + +// pump starts the next waiting event when no call is pending. +func (s *Session) pump() { + if s.busy || len(s.queue) == 0 || s.options.Call == nil { + return + } + event := s.queue[0] + s.queue = s.queue[1:] + encoded := s.encode(event) + s.busy = true + s.generation++ + generation, view, call, wake := s.generation, s.raw, s.options.Call, s.options.Wake + ctx, cancel := context.WithCancel(s.options.Context) + s.cancel = cancel + s.options.Go(func() { + defer cancel() + answer, changed, err := call(ctx, encoded, view, false) + s.mu.Lock() + // A call of a showing that closed can answer after the call of the next showing, so + // an older generation never replaces a newer answer that waits to be taken. + if s.done == nil || s.done.generation < generation { + s.done = &outcome{generation: generation, event: event, view: answer, changed: changed, err: err} + } + s.mu.Unlock() + if wake != nil { + wake() + } + }) +} + +// encode is the event's params: the surface's own params, then the event's fields. +func (s *Session) encode(event Event) json.RawMessage { + params := map[string]any{} + if s.options.Params != nil { + for key, value := range s.options.Params() { + params[key] = value + } + } + params["event"], params["instance"] = event.Name, s.instance + if event.Node != "" { + params["node"] = event.Node + } + if event.Canvas != "" { + params["canvas"] = event.Canvas + } + if event.Value != nil { + params["value"] = event.Value + } + if event.Setting != "" { + params["setting"] = event.Setting + } + if event.Item != "" { + params["item"] = event.Item + } + if event.Viewport != nil { + params["viewport"] = event.Viewport + } + encoded, err := json.Marshal(params) + if err != nil { + encoded, _ = json.Marshal(map[string]any{"event": event.Name, "instance": s.instance}) + } + return encoded +} + +// View is the decoded view to draw, nil before the first answer. +func (s *Session) View() []Node { + if s == nil { + return nil + } + return s.nodes +} + +// Drawn reports whether the view has an answer to draw. +func (s *Session) Drawn() bool { return s != nil && s.raw != nil } + +// Err is the failure of the last call, nil after one succeeds. +func (s *Session) Err() error { + if s == nil { + return nil + } + return s.err +} + +// Busy reports a call waiting for its answer. +func (s *Session) Busy() bool { return s != nil && s.busy } + +// Retry sends the event that failed again and clears the error it left. +func (s *Session) Retry() { + if s == nil || !s.open || s.failed == nil { + return + } + event := *s.failed + s.err, s.failed = nil, nil + s.queue = append([]Event{event}, s.queue...) + s.pump() +} + +// fieldState is a text field's text while the user types. last is the value the view +// gave it, so a new value from the plugin replaces the text unless the field is focused; +// sent is the text the field last committed, so Enter or leaving the field sends change +// only for text that differs from it. started reports that sent holds the first text. +type fieldState struct { + text string + last string + sent string + started bool + focused bool +} + +// selectState is a select's or segmented control's chosen value, kept by the host so +// the choice shows at once while the change event is on its way. +type selectState struct { + value string + last string +} + +// toggleState is a toggle's state, kept as selectState is. +type toggleState struct { + on bool + last bool +} + +// treeState is a tree's selection and its open items, which the host keeps: opening an +// item never reaches the plugin, and selecting one sends select. +type treeState struct { + tree ui.TreeState + // open holds the items the user opened or closed, by item ID; an item not in it is + // open as the plugin's expanded says. + open map[string]bool + // keys number the item IDs in the order they were first shown, so a row keeps its + // focus as rows open and close above it. + keys map[string]int + // rows are the visible items, flattened in order, as the last paint showed them. + rows []treeRow + selected string +} + +// treeRow is one visible tree item and its depth. +type treeRow struct { + item *Item + depth int +} + +// flatten lists the visible items of items: each, then its children when it is open. +func (t *treeState) flatten(items []Item) { + t.rows = t.rows[:0] + var walk func(items []Item, depth int) + walk = func(items []Item, depth int) { + for i := range items { + item := &items[i] + t.rows = append(t.rows, treeRow{item: item, depth: depth}) + if len(item.Children) > 0 && t.expanded(item) { + walk(item.Children, depth+1) + } + } + } + walk(items, 0) +} + +// expanded reports whether item shows its children: as the user left it, else as the +// plugin's expanded says. +func (t *treeState) expanded(item *Item) bool { + if open, ok := t.open[item.ID]; ok { + return open + } + return item.Expanded +} + +// key is the stable number of an item ID, given on first sight. +func (t *treeState) key(id string) int { + key, ok := t.keys[id] + if !ok { + key = len(t.keys) + t.keys[id] = key + } + return key +} + +func (s *Session) field(id, value string) *fieldState { + if s.fields == nil { + s.fields = map[string]*fieldState{} + } + state := s.fields[id] + if state == nil { + state = &fieldState{text: value, last: value, sent: value} + s.fields[id] = state + } + return state +} + +func (s *Session) selection(id, value string) *selectState { + if s.selects == nil { + s.selects = map[string]*selectState{} + } + state := s.selects[id] + if state == nil || state.last != value { + state = &selectState{value: value, last: value} + s.selects[id] = state + } + return state +} + +func (s *Session) toggle(id string, value bool) *toggleState { + if s.toggles == nil { + s.toggles = map[string]*toggleState{} + } + state := s.toggles[id] + if state == nil || state.last != value { + state = &toggleState{on: value, last: value} + s.toggles[id] = state + } + return state +} + +func (s *Session) tree(id string) *treeState { + if s.trees == nil { + s.trees = map[string]*treeState{} + } + state := s.trees[id] + if state == nil { + state = &treeState{open: map[string]bool{}, keys: map[string]int{}} + state.tree.RowHeight = 24 + state.tree.Key = func(i int) int { return state.key(state.rows[i].item.ID) } + state.tree.Label = func(i int) string { return state.rows[i].item.Label } + state.tree.Node = func(i int) ui.TreeNode { + row := state.rows[i] + return ui.TreeNode{ + Depth: row.depth, + Branch: len(row.item.Children) > 0, + Expanded: state.expanded(row.item), + Selected: row.item.ID == state.selected, + } + } + s.trees[id] = state + } + return state +} + +func (s *Session) canvas(id string) *canvasState { + if s.canvases == nil { + s.canvases = map[string]*canvasState{} + } + state := s.canvases[id] + if state == nil { + state = &canvasState{zoom: 1} + s.canvases[id] = state + } + return state +} diff --git a/desktop/internal/pluginview/session_test.go b/desktop/internal/pluginview/session_test.go new file mode 100644 index 0000000000..36e76870e3 --- /dev/null +++ b/desktop/internal/pluginview/session_test.go @@ -0,0 +1,487 @@ +package pluginview + +import ( + "context" + "encoding/json" + "errors" + "slices" + "strings" + "testing" + "time" +) + +// received is one view event the test backend was sent. +type received struct { + ctx context.Context + params map[string]any + view json.RawMessage + closing bool +} + +// backend is a plugin backend under the test's control. Go only queues a call, and the test +// runs the queued calls in the order it chooses, so no assertion depends on a goroutine's +// timing; the clock moves only when the test moves it. +type backend struct { + t *testing.T + now time.Time + params map[string]any + calls []received + pending []func() + wakes int + failed []error + // answer is the answer to one event; nil answers a view of one label that names the event. + answer func(params map[string]any) (json.RawMessage, bool, error) +} + +func newBackend(t *testing.T) *backend { + return &backend{ + t: t, + now: time.Date(2026, 11, 19, 9, 0, 0, 0, time.UTC), + params: map[string]any{"surface": map[string]any{"toolWindowID": "panel"}}, + } +} + +// session is a closed session wired to the backend; it closes with the test. +func (b *backend) session(adjust ...func(*Options)) *Session { + options := Options{ + Call: b.call, + Params: func() map[string]any { + params := map[string]any{} + for key, value := range b.params { + params[key] = value + } + return params + }, + Wake: func() { b.wakes++ }, + Failed: func(err error) { b.failed = append(b.failed, err) }, + Now: func() time.Time { return b.now }, + Go: func(work func()) { b.pending = append(b.pending, work) }, + } + for _, fn := range adjust { + fn(&options) + } + s := NewSession(options) + b.t.Cleanup(s.Close) + return s +} + +func (b *backend) call(ctx context.Context, event, view json.RawMessage, closing bool) (json.RawMessage, bool, error) { + var params map[string]any + if err := json.Unmarshal(event, ¶ms); err != nil { + b.t.Errorf("event %s is not a JSON object: %v", event, err) + } + b.calls = append(b.calls, received{ctx: ctx, params: params, view: view, closing: closing}) + if closing { + return nil, false, nil + } + if b.answer != nil { + return b.answer(params) + } + name, _ := params["event"].(string) + return labelView(name), true, nil +} + +// labelView is a view of one label with text. +func labelView(text string) json.RawMessage { + view, _ := json.Marshal([]map[string]any{{"type": "label", "id": "status", "text": text}}) + return view +} + +// run runs the oldest queued call. +func (b *backend) run() { + b.t.Helper() + if len(b.pending) == 0 { + b.t.Fatal("no call is waiting to run") + } + work := b.pending[0] + b.pending = b.pending[1:] + work() +} + +// answered runs the oldest queued call and has the session take its answer. +func (b *backend) answered(s *Session) { + b.t.Helper() + b.run() + s.Take() +} + +// events are the names of the events the backend was sent, in order. +func (b *backend) events() []string { + names := make([]string, 0, len(b.calls)) + for _, call := range b.calls { + name, _ := call.params["event"].(string) + names = append(names, name) + } + return names +} + +// last is the params of the last event the backend was sent. +func (b *backend) last() map[string]any { + b.t.Helper() + if len(b.calls) == 0 { + b.t.Fatal("the backend was sent no event") + } + return b.calls[len(b.calls)-1].params +} + +// shown is the text of the session's label, which names the event that drew it. +func shown(t *testing.T, s *Session) string { + t.Helper() + nodes := s.View() + if len(nodes) != 1 { + t.Fatalf("view = %+v, want one label", nodes) + } + return nodes[0].Text +} + +func TestSessionOpenSendsOpenAndDrawsTheAnswer(t *testing.T) { + b := newBackend(t) + s := b.session() + s.Open() + if !s.Opened() || !s.Busy() || len(b.pending) != 1 { + t.Fatalf("after Open: opened %v, busy %v, %d calls queued", s.Opened(), s.Busy(), len(b.pending)) + } + if s.Drawn() { + t.Fatal("a view is drawn before the backend answered") + } + b.run() + if b.wakes != 1 { + t.Fatalf("wakes = %d, want 1 once the answer arrived", b.wakes) + } + if wait := s.Take(); wait != 0 { + t.Fatalf("Take waits %v with nothing settling", wait) + } + if s.Busy() || !s.Drawn() || s.Err() != nil || shown(t, s) != "open" { + t.Fatalf("after the answer: busy %v, drawn %v, err %v", s.Busy(), s.Drawn(), s.Err()) + } + call := b.calls[0] + if call.params["event"] != "open" || call.view != nil || call.closing { + t.Fatalf("open call = %+v, want open with no drawn view", call) + } + if instance := s.Instance(); !strings.HasPrefix(instance, "view-") || call.params["instance"] != instance { + t.Fatalf("instance = %q, sent %v", instance, call.params["instance"]) + } + if _, ok := call.params["surface"]; !ok { + t.Fatalf("open params %v lost the surface's own params", call.params) + } + s.Open() + if len(b.pending) != 0 { + t.Fatal("Open on a showing view sent another open") + } +} + +func TestSessionSendsOneEventAtATimeWithTheDrawnView(t *testing.T) { + b := newBackend(t) + s := b.session() + s.Open() + b.answered(s) + s.Send(Event{Name: "click", Node: "refresh"}) + s.Send(Event{Name: "change", Node: "filter", Value: "core"}) + if len(b.pending) != 1 { + t.Fatalf("%d calls run at once, want one at a time", len(b.pending)) + } + b.answered(s) + if string(b.calls[1].view) != string(labelView("open")) { + t.Fatalf("click carried view %s, want the view drawn last", b.calls[1].view) + } + if len(b.pending) != 1 { + t.Fatalf("the change did not follow the click's answer: %d calls queued", len(b.pending)) + } + b.answered(s) + if got := b.events(); !slices.Equal(got, []string{"open", "click", "change"}) { + t.Fatalf("events = %v", got) + } + if last := b.last(); last["node"] != "filter" || last["value"] != "core" { + t.Fatalf("change params = %v", last) + } + if shown(t, s) != "change" { + t.Fatalf("view shows %q, want the last answer", shown(t, s)) + } +} + +func TestSessionSettlesSettingsAndSendsTheValuesAtSending(t *testing.T) { + b := newBackend(t) + s := b.session() + s.Open() + b.answered(s) + s.SettingsChanged() + b.now = b.now.Add(100 * time.Millisecond) + if wait := s.Take(); wait != 300*time.Millisecond || len(b.pending) != 0 { + t.Fatalf("100 ms after a change: wait %v, %d calls", wait, len(b.pending)) + } + b.now = b.now.Add(200 * time.Millisecond) + s.SettingsChanged() + b.params["settings"] = map[string]any{"jdk": "21"} + b.now = b.now.Add(300 * time.Millisecond) + if wait := s.Take(); wait != 100*time.Millisecond || len(b.pending) != 0 { + t.Fatalf("a second change did not restart the wait: wait %v, %d calls", wait, len(b.pending)) + } + b.now = b.now.Add(100 * time.Millisecond) + if wait := s.Take(); wait != 0 || len(b.pending) != 1 { + t.Fatalf("once settled: wait %v, %d calls", wait, len(b.pending)) + } + b.answered(s) + if got := b.events(); !slices.Equal(got, []string{"open", "settings"}) { + t.Fatalf("events = %v, want one settings event", got) + } + settings, _ := b.last()["settings"].(map[string]any) + if settings["jdk"] != "21" { + t.Fatalf("settings params = %v, want the values at sending", b.last()) + } +} + +func TestSessionMergesWaitingViewportsPerCanvas(t *testing.T) { + b := newBackend(t) + s := b.session() + s.Open() + s.ViewportMoved("graph", Viewport{X: 1, Width: 10, Height: 10}) + s.ViewportMoved("minimap", Viewport{X: 2, Width: 5, Height: 5}) + b.now = b.now.Add(settleDelay) + s.Take() + s.ViewportMoved("graph", Viewport{X: 3, Width: 10, Height: 10}) + b.now = b.now.Add(settleDelay) + s.Take() + for len(b.pending) > 0 { + b.answered(s) + } + if got := b.events(); !slices.Equal(got, []string{"open", "viewport", "viewport"}) { + t.Fatalf("events = %v, want open and one viewport per canvas", got) + } + minimap, graph := b.calls[1].params, b.calls[2].params + if minimap["canvas"] != "minimap" || graph["canvas"] != "graph" { + t.Fatalf("viewport canvases = %v, %v", minimap["canvas"], graph["canvas"]) + } + if viewport, _ := graph["viewport"].(map[string]any); viewport["x"] != 3.0 { + t.Fatalf("graph viewport = %v, want the latest one", graph["viewport"]) + } +} + +func TestSessionCloseDropsTheLateAnswerAndSendsClose(t *testing.T) { + b := newBackend(t) + s := b.session() + s.Open() + first := s.Instance() + s.Close() + if s.Opened() || s.Instance() != "" || len(b.pending) != 2 { + t.Fatalf("after Close: opened %v, instance %q, %d calls queued", s.Opened(), s.Instance(), len(b.pending)) + } + b.run() + if err := b.calls[0].ctx.Err(); !errors.Is(err, context.Canceled) { + t.Fatalf("the pending call's context = %v, want cancelled by Close", err) + } + b.run() + closing := b.calls[1] + if !closing.closing || closing.params["event"] != "close" || closing.params["instance"] != first { + t.Fatalf("close call = %+v", closing) + } + if err := closing.ctx.Err(); err != nil { + t.Fatalf("the close call's context = %v, want it to outlive the showing", err) + } + if s.Take() != 0 || s.Drawn() { + t.Fatal("a closed session took the late answer") + } + s.Open() + if s.Instance() == first || s.Instance() == "" { + t.Fatalf("reopening kept instance %q", s.Instance()) + } + b.answered(s) + if !s.Drawn() || s.Busy() || shown(t, s) != "open" { + t.Fatalf("the reopened view: drawn %v, busy %v", s.Drawn(), s.Busy()) + } +} + +func TestSessionKeepsTheNewerAnswerWhenAClosedShowingAnswersLate(t *testing.T) { + b := newBackend(t) + b.answer = func(params map[string]any) (json.RawMessage, bool, error) { + instance, _ := params["instance"].(string) + return labelView(instance), true, nil + } + s := b.session() + s.Open() + s.Close() + s.Open() + if len(b.pending) != 3 { + t.Fatalf("%d calls queued, want the first open, close and the second open", len(b.pending)) + } + stale, closing, reopened := b.pending[0], b.pending[1], b.pending[2] + b.pending = nil + reopened() + stale() + closing() + s.Take() + if s.Busy() || !s.Drawn() || shown(t, s) != s.Instance() { + t.Fatalf("after a late answer of the closed showing: busy %v, drawn %v", s.Busy(), s.Drawn()) + } +} + +func TestSessionRetrySendsTheFailedEventAgain(t *testing.T) { + b := newBackend(t) + failures := 1 + b.answer = func(params map[string]any) (json.RawMessage, bool, error) { + if params["event"] == "click" && failures > 0 { + failures-- + return nil, false, errors.New("backend stopped") + } + name, _ := params["event"].(string) + return labelView(name), true, nil + } + s := b.session() + s.Open() + b.answered(s) + s.Send(Event{Name: "click", Node: "refresh"}) + b.answered(s) + if s.Err() == nil || !s.Drawn() || shown(t, s) != "open" { + t.Fatalf("after a failed call: err %v, drawn %v, want the error over the last view", s.Err(), s.Drawn()) + } + if len(b.failed) != 0 { + t.Fatalf("Failed logged %v; a call's own failure is the caller's to log", b.failed) + } + s.Retry() + if s.Err() != nil || len(b.pending) != 1 { + t.Fatalf("after Retry: err %v, %d calls queued", s.Err(), len(b.pending)) + } + b.answered(s) + if got := b.events(); !slices.Equal(got, []string{"open", "click", "click"}) || b.last()["node"] != "refresh" { + t.Fatalf("events = %v, last %v", got, b.last()) + } + if s.Err() != nil || shown(t, s) != "click" { + t.Fatalf("after the retried call: err %v", s.Err()) + } +} + +func TestSessionLogsAViewItCannotRead(t *testing.T) { + b := newBackend(t) + b.answer = func(params map[string]any) (json.RawMessage, bool, error) { + if params["event"] == "click" { + return json.RawMessage(`{"type":"label"}`), true, nil + } + return labelView("open"), true, nil + } + s := b.session() + s.Open() + b.answered(s) + s.Send(Event{Name: "click", Node: "refresh"}) + b.answered(s) + if len(b.failed) != 1 || s.Err() == nil { + t.Fatalf("failed %v, err %v, want the unreadable view logged and shown", b.failed, s.Err()) + } + if shown(t, s) != "open" { + t.Fatal("an unreadable view replaced the last one") + } + s.Retry() + if len(b.pending) != 1 { + t.Fatal("Retry did not send the event whose view could not be read") + } +} + +func TestSessionIgnoresACancelledCall(t *testing.T) { + b := newBackend(t) + b.answer = func(params map[string]any) (json.RawMessage, bool, error) { + if params["event"] == "click" { + return nil, false, context.Canceled + } + return labelView("open"), true, nil + } + s := b.session() + s.Open() + b.answered(s) + s.Send(Event{Name: "click"}) + b.answered(s) + if s.Err() != nil || s.Busy() { + t.Fatalf("a cancelled call left err %v, busy %v", s.Err(), s.Busy()) + } + s.Retry() + if len(b.pending) != 0 { + t.Fatal("Retry resent a cancelled call") + } +} + +func TestSessionKeepsTheViewForAnEmptyOrUnchangedAnswer(t *testing.T) { + b := newBackend(t) + b.answer = func(params map[string]any) (json.RawMessage, bool, error) { + switch params["event"] { + case "click": + return nil, false, nil + case "change": + // Core reports the view unchanged, so the host does not read it again. + return json.RawMessage(`not a view`), false, nil + } + return labelView("open"), true, nil + } + s := b.session() + s.Open() + b.answered(s) + s.Send(Event{Name: "click"}) + b.answered(s) + s.Send(Event{Name: "change", Value: "x"}) + b.answered(s) + if s.Err() != nil || len(b.failed) != 0 || shown(t, s) != "open" { + t.Fatalf("err %v, failed %v, want the drawn view kept", s.Err(), b.failed) + } +} + +func TestSessionEncodesTheEventOverTheSurfaceParams(t *testing.T) { + b := newBackend(t) + b.params["event"], b.params["instance"] = "spoofed", "spoofed" + s := b.session() + s.Open() + b.answered(s) + if _, ok := b.calls[0].params["node"]; ok { + t.Fatalf("open params %v carry a node", b.calls[0].params) + } + s.Send(Event{ + Name: "activate", Node: "modules", Item: "core", Setting: "jdk", Value: 3, Canvas: "graph", + Viewport: &Viewport{X: 1, Y: 2, Width: 30, Height: 40}, + }) + b.run() + params := b.last() + want := map[string]any{ + "event": "activate", "instance": s.Instance(), "node": "modules", "item": "core", + "setting": "jdk", "value": 3.0, "canvas": "graph", + } + for key, value := range want { + if params[key] != value { + t.Errorf("params[%q] = %v, want %v", key, params[key], value) + } + } + viewport, _ := params["viewport"].(map[string]any) + if viewport["y"] != 2.0 || viewport["height"] != 40.0 { + t.Errorf("viewport = %v", params["viewport"]) + } + if _, ok := params["surface"]; !ok { + t.Errorf("params %v lost the surface's own params", params) + } +} + +func TestSessionCallsEndWithTheHostContext(t *testing.T) { + b := newBackend(t) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + s := b.session(func(options *Options) { options.Context = ctx }) + s.Open() + cancel() + b.run() + if err := b.calls[0].ctx.Err(); !errors.Is(err, context.Canceled) { + t.Fatalf("call context = %v, want it to end with the host's", err) + } +} + +func TestSessionTakesNoInputWhileClosed(t *testing.T) { + b := newBackend(t) + s := b.session() + s.Send(Event{Name: "click"}) + s.SettingsChanged() + s.ViewportMoved("graph", Viewport{Width: 1, Height: 1}) + s.Retry() + b.now = b.now.Add(settleDelay) + if s.Take() != 0 || len(b.pending) != 0 || len(b.calls) != 0 { + t.Fatalf("a closed session sent %d events", len(b.pending)+len(b.calls)) + } + var none *Session + none.Open() + none.Send(Event{Name: "click"}) + none.Close() + if none.Opened() || none.Drawn() || none.Busy() || none.Err() != nil || none.View() != nil || none.Instance() != "" { + t.Fatal("a nil session reports a view") + } +} diff --git a/desktop/internal/pluginview/view_visual_test.go b/desktop/internal/pluginview/view_visual_test.go new file mode 100644 index 0000000000..c4c12a02b5 --- /dev/null +++ b/desktop/internal/pluginview/view_visual_test.go @@ -0,0 +1,128 @@ +//go:build vivahead && lithevisual + +package pluginview + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/headless" + "github.com/vivaui/viva/ui" +) + +// visualView is a tool window view that uses every host control and a canvas with clickable, +// selected and dashed shapes, as a module explorer plugin might draw it. +const visualView = `[ + {"type":"section","title":"Modules","info":"Modules the backend found in the workspace.","children":[ + {"type":"row","children":[ + {"type":"label","id":"count","text":"3 modules · 41 classes","style":"strong"}, + {"type":"button","id":"refresh","text":"Refresh","icon":"refresh"}, + {"type":"button","id":"build","text":"Build all","icon":"run","tone":"primary"}]}, + {"type":"textField","id":"filter","placeholder":"Filter modules","width":"fill"}, + {"type":"tree","id":"modules","items":[ + {"id":"core","label":"core","icon":"plugin","detail":"18 classes","expanded":true,"children":[ + {"id":"core.api","label":"api","detail":"7 classes"}, + {"id":"core.impl","label":"impl","detail":"11 classes"}]}, + {"id":"app","label":"app","icon":"run","detail":"15 classes"}, + {"id":"tools","label":"tools","icon":"terminal","detail":"8 classes"}]}, + {"type":"toggle","id":"watch","label":"Rebuild on save","value":true}]}, + {"type":"section","title":"Last build","children":[ + {"type":"keyValue","items":[ + {"label":"Finished","value":"09:41"}, + {"label":"Duration","value":"12.4 s"}, + {"label":"Result","value":"Passed","tone":"success"}]}, + {"type":"banner","tone":"warning","text":"core.impl has 2 warnings."}, + {"type":"table","id":"slow","columns":[{"title":"Module"},{"title":"Time","align":"end"}], + "rows":[["core","6.1 s"],["app","4.8 s"],["tools","1.5 s"]]}]}, + {"type":"canvas","id":"graph","label":"Module graph","height":170,"viewBox":[0,0,440,160],"nodes":[ + {"type":"rect","x":0,"y":0,"w":440,"h":160,"radius":8,"fill":"$surface","stroke":"$line"}, + {"type":"path","d":"M 140 75 L 180 75","stroke":"$accent","width":2}, + {"type":"path","d":"M 300 75 L 260 75","stroke":"$textMuted","width":1.5,"dash":[4,3]}, + {"type":"group","id":"node.app","x":20,"y":55,"w":120,"h":40,"radius":6,"on":["click"],"label":"app module", + "states":{"hover":{"fill":"$hover"}},"children":[ + {"type":"rect","x":0,"y":0,"w":120,"h":40,"radius":6,"stroke":"$line"}, + {"type":"text","x":60,"y":25,"text":"app","style":"strong","align":"center"}]}, + {"type":"group","id":"node.core","x":180,"y":55,"w":80,"h":40,"radius":6,"on":["click"],"label":"core module","selected":true, + "states":{"hover":{"fill":"$hover"},"selected":{"fill":"$selection","stroke":"$accent","width":1.5}},"children":[ + {"type":"text","x":40,"y":25,"text":"core","style":"strong","align":"center"}]}, + {"type":"group","id":"node.tools","x":300,"y":55,"w":120,"h":40,"radius":6,"on":["click"],"label":"tools module", + "states":{"hover":{"fill":"$hover"}},"children":[ + {"type":"rect","x":0,"y":0,"w":120,"h":40,"radius":6,"stroke":"$line","dash":[4,3]}, + {"type":"text","x":60,"y":25,"text":"tools","style":"strong","align":"center"}]}, + {"type":"text","x":220,"y":140,"text":"2 edges · 1 optional","style":"caption","align":"center","color":"$textSecondary"}]} +]` + +// visualPalette maps a Viva theme onto the view tokens as the workbench maps its own. +func visualPalette(theme gfx.Theme, dark bool) Palette { + warning := gfx.RGBA(178, 107, 0, 1) + if dark { + warning = gfx.RGBA(229, 160, 58, 1) + } + return Palette{ + Dark: dark, Text: theme.Foreground, TextSecondary: theme.MutedForeground, TextMuted: theme.MutedForeground, + Accent: theme.Primary, Success: theme.Success, Warning: warning, Error: theme.Danger, + Surface: theme.Card, Background: theme.Background, Sidebar: theme.Muted, Line: theme.Border, + Hover: theme.Hover, Selection: theme.Selection, Badge: theme.Secondary, + Popover: theme.Popover, PopoverText: theme.PopoverForeground, + } +} + +// TestVisualPluginView renders a tool window view in the dark and the light theme. Opt in +// with -tags 'vivahead lithevisual' and LITHE_VISUAL_OUTPUT_DIR. +func TestVisualPluginView(t *testing.T) { + out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") + if out == "" { + t.Skip("set LITHE_VISUAL_OUTPUT_DIR to capture a plugin view") + } + if err := os.MkdirAll(out, 0755); err != nil { + t.Fatal(err) + } + for _, dark := range []bool{true, false} { + name := "plugin-view-toolwindow-light" + theme := ui.LightTheme() + if dark { + name, theme = "plugin-view-toolwindow-dark", ui.DarkTheme() + } + t.Run(name, func(t *testing.T) { + b := newBackend(t) + b.answer = func(map[string]any) (json.RawMessage, bool, error) { return json.RawMessage(visualView), true, nil } + s := b.session() + s.Open() + b.answered(s) + if !s.Drawn() { + t.Fatalf("the view was not drawn: %v", s.Err()) + } + background := theme.Background + invalidator := &app.Invalidator{} + host := &Host{Palette: visualPalette(theme, dark), Language: i18n.English, Icon: HostIcon} + page := ui.NewPage(ui.PageConfig{ + View: func(c ui.C) { + ui.Column(c.Key("body")).Fill().Background(theme.Background).Children(func() { Draw(c, s, host, true) }) + }, + Theme: &theme, Background: &background, Invalidator: invalidator, + }) + session, err := headless.Open(page.Config(app.Config{Width: 480, Height: 860, Invalidator: invalidator}), nil, headless.Options{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + labels := map[string]bool{} + for _, label := range session.Snapshot().Labels { + labels[label.Value] = true + } + for _, text := range []string{"3 modules · 41 classes", "Rebuild on save", "core.impl has 2 warnings.", "2 edges · 1 optional"} { + if !labels[text] { + t.Errorf("the view does not show %q", text) + } + } + if err := session.Screenshot(filepath.Join(out, name+".png")); err != nil { + t.Fatal(err) + } + }) + } +} diff --git a/desktop/internal/settingswindow/build_aggregation_test.go b/desktop/internal/settingswindow/build_aggregation_test.go index fa7917c8b2..b385878483 100644 --- a/desktop/internal/settingswindow/build_aggregation_test.go +++ b/desktop/internal/settingswindow/build_aggregation_test.go @@ -51,8 +51,8 @@ func TestBuildPageGathersSettingsThePluginKeepsInItsOwnTab(t *testing.T) { return []PluginFacts{{ID: pluginID, Name: "Settings", Version: "1.0.0", Settings: 2}} }, SettingsNavigation: client.SettingsNavigation, - SettingsPages: func(ctx context.Context) ([]core.SettingsPage, error) { - return client.SettingsPages(ctx, contributions) + SettingsPages: func(ctx context.Context, _ i18n.Language) ([]core.SettingsPage, error) { + return client.SettingsPages(ctx, contributions, "") }, }), Values{}) w.sess.page = pagePlugins diff --git a/desktop/internal/settingswindow/build_directory_view_test.go b/desktop/internal/settingswindow/build_directory_view_test.go index 8d2cbf4d31..572dd11ddb 100644 --- a/desktop/internal/settingswindow/build_directory_view_test.go +++ b/desktop/internal/settingswindow/build_directory_view_test.go @@ -86,8 +86,8 @@ func buildPagesWindow(t *testing.T, count int) (*window, *windowDriver) { Text: func() *i18n.Messages { return i18n.For(i18n.English) }, Language: func() i18n.Language { return i18n.English }, PluginSettings: newBuildFormSource(t, client, contributions), SettingsNavigation: client.SettingsNavigation, - SettingsPages: func(ctx context.Context) ([]core.SettingsPage, error) { - return client.SettingsPages(ctx, contributions) + SettingsPages: func(ctx context.Context, _ i18n.Language) ([]core.SettingsPage, error) { + return client.SettingsPages(ctx, contributions, "") }, }), Values{Theme: "dark"}) w.sess.page = pageBuild diff --git a/desktop/internal/settingswindow/controller.go b/desktop/internal/settingswindow/controller.go index c5d81afce7..f1e08d5068 100644 --- a/desktop/internal/settingswindow/controller.go +++ b/desktop/internal/settingswindow/controller.go @@ -9,6 +9,7 @@ package settingswindow import ( "context" + "encoding/json" "github.com/1lck/Lithe-IDEA/desktop/internal/shortcuts" "sync" "time" @@ -243,6 +244,15 @@ type PluginSettingsActionLoader interface { Action(context.Context, pluginservice.SettingsEditor, string, bool) (pluginservice.SettingsActionResult, error) } +// PluginViewLoader sends one event of a settings region's view (API-13, API-19) to the +// plugin's backend, off the window thread, and returns the whole view Core checked and +// whether it differs from view, the view drawn last. event carries the page's settings, +// the saved values with the draft. ctx ends when the region closes; a close event (closing) +// returns nothing. +type PluginViewLoader interface { + View(ctx context.Context, editor pluginservice.SettingsEditor, region, function string, event, view json.RawMessage, closing bool) (json.RawMessage, bool, error) +} + // PluginSourceSettingsLoader publishes only explicitly saved native-source drafts. type PluginSourceSettingsLoader interface { SaveSources(context.Context, pluginservice.SettingsEditor, string, pluginsettings.SourceEditor, []core.SourceSettingsEdits) (pluginsettings.SourceEditor, error) @@ -318,7 +328,7 @@ type Options struct { // SettingsError logs a failure of the window, with the operation that failed as the log // names it (plugin_settings_surface, keymap_schemes, settings_about_copy, ...). SettingsError func(operation string, err error) - SettingsPages func(context.Context) ([]core.SettingsPage, error) + SettingsPages func(context.Context, i18n.Language) ([]core.SettingsPage, error) SettingsNavigation func(context.Context, []core.SettingsNavigationItem, string) ([]core.SettingsNavigationRow, error) // Marketplace fetches the enabled source only while the plugin page is open. Marketplace func(context.Context) (marketplace.Snapshot, error) diff --git a/desktop/internal/settingswindow/plugin_region_view.go b/desktop/internal/settingswindow/plugin_region_view.go new file mode 100644 index 0000000000..9d6f084287 --- /dev/null +++ b/desktop/internal/settingswindow/plugin_region_view.go @@ -0,0 +1,377 @@ +package settingswindow + +import ( + "context" + "encoding/json" + "fmt" + "strconv" + "strings" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginview" + "github.com/vivaui/viva/ui" +) + +// A settings region (settingRegions, API-19) with a view function shows a plugin view +// (API-13) between the page's header and the plugin's declared rows, which stay. The +// plugin's backend answers each view event with the nodes to draw, Core checks the answer, +// and the window draws it with its own controls (pluginview). Its bound controls, setting +// rows and action buttons are the page's own: they edit the page's draft and run the page's +// actions, and the view never stores a value. The window shows one region at a time, the +// one of the page on screen: the first paint that declares it opens it, and the first that +// does not, because the page, the plugin, its version or the language changed or the window +// closed, closes it. What the view shows lives in memory only and ends with the showing. + +// The operations a region's failures are logged under: a view the window cannot read, and a +// canvas image it cannot read. A failed call is logged where the call is made. +const ( + pluginRegionViewOperation = "plugin_settings_view" + pluginRegionImageOperation = "plugin_settings_view_image" +) + +// regionKey names one showing of a region: a change of any part opens the view anew. +type regionKey struct { + plugin, version, page, region, function, pkg string + language i18n.Language +} + +// regionView is the region the window shows. +type regionView struct { + key regionKey + session *pluginview.Session + images *pluginview.Images + host pluginview.Host + // shown says this paint declared the region. + shown bool + // sent is the settings, encoded, that the paint before found, so a paint that finds + // them changed tells the view. + sent string +} + +// pluginRegionOf is the region the form's plugin placed on the page on screen: on a page +// under Build or a contributed page the contributor's, on the plugin's own Settings tab the +// editor's. It is nil when the plugin placed none there. +func (w *window) pluginRegionOf(p *pluginSettingsForm) *core.PluginSettingsRegion { + if w.dynamicPage == "" { + return p.editor.Snapshot.State.Region + } + page := w.dynamic.selected(w.dynamicPage) + if page == nil { + return nil + } + for index := range page.Contributors { + if page.Contributors[index].PluginID == p.id { + return page.Contributors[index].Region + } + } + return nil +} + +// pluginRegion declares the form's region view, when the plugin placed one with a view on +// the page on screen and the host can call it. hasSource says the scope shown has a file +// to write, which bound controls need as the page's rows do. +func (w *window) pluginRegion(c ui.C, p *pluginSettingsForm, hasSource bool) { + region := w.pluginRegionOf(p) + function := region.ViewFunction() + loader, ok := w.ctrl.opts.PluginSettings.(PluginViewLoader) + if function == "" || !ok || !p.loaded { + return + } + language := w.marketLanguage() + key := regionKey{ + plugin: p.id, version: p.editor.Snapshot.State.Metadata.Version, page: w.dynamicPage, + region: region.ID, function: function, pkg: p.editor.Package(), language: language, + } + if w.region != nil && w.region.key != key { + w.closeRegion() + } + if w.region == nil { + w.region = w.openRegion(key, loader, p) + } + v := w.region + v.shown = true + if sent := p.viewSettingsText(); sent != v.sent { + v.sent = sent + v.session.SettingsChanged() + } + v.host.Palette, v.host.Language = w.regionPalette(), language + v.host.Settings = regionSettings{w: w, p: p, hasSource: hasSource} + pluginview.Draw(c.Key("plugin-region:"+region.ID), v.session, &v.host, false) +} + +// openRegion makes and opens the view of key. Its calls carry the editor the form holds now, +// whose plugin, version and package the key names, and each event carries the settings the +// form holds when it is sent. +func (w *window) openRegion(key regionKey, loader PluginViewLoader, p *pluginSettingsForm) *regionView { + // The window's invalidator is installed before the first paint and is safe to call from + // the call's goroutine. + inv := &w.inv + wake := func() { inv.Invalidate() } + editor, opts := p.editor, w.ctrl.opts + failed := func(operation string) func(error) { + return func(err error) { reportSettingsError(opts, operation, err) } + } + v := ®ionView{key: key, images: pluginview.NewImages(key.pkg, wake, failed(pluginRegionImageOperation)), sent: p.viewSettingsText()} + v.session = pluginview.NewSession(pluginview.Options{ + Call: func(ctx context.Context, event, view json.RawMessage, closing bool) (json.RawMessage, bool, error) { + return loader.View(ctx, editor, key.region, key.function, event, view, closing) + }, + Params: func() map[string]any { + return map[string]any{"language": key.language.Code(), "settings": p.viewSettings()} + }, + Wake: wake, + Failed: failed(pluginRegionViewOperation), + }) + v.host = pluginview.Host{Icon: pluginview.HostIcon, Images: v.images, Info: w.infoButton} + v.session.Open() + return v +} + +// closeRegion ends the region's showing and drops the images it read. +func (w *window) closeRegion() { + if v := w.region; v != nil { + v.session.Close() + v.images.Close() + w.region = nil + } +} + +// endRegion runs at the end of each paint: a region the paint did not declare closes, and +// the one it did is marked as not declared until the next paint declares it. +func (w *window) endRegion() { + if v := w.region; v != nil { + if !v.shown { + w.closeRegion() + return + } + v.shown = false + } +} + +// regionPalette maps the window's look onto the tokens a view names, so a region reads as +// part of the page in the light and the dark theme. +func (w *window) regionPalette() pluginview.Palette { + p := &w.pal + return pluginview.Palette{ + Dark: w.dark, Text: p.text, TextSecondary: p.muted, TextMuted: p.subtle, + Accent: p.accent, Success: p.success, Warning: p.warning, Error: p.danger, + Surface: p.card, Background: p.window, Sidebar: p.sidebar, Line: p.line, + Hover: p.hover, Selection: p.selection, Badge: w.theme.Secondary, + Popover: w.theme.Popover, PopoverText: w.theme.PopoverForeground, + } +} + +// regionSettings is the page a region is drawn on: the form's rows, drafts and actions, and +// the toolchain pages' rows. +type regionSettings struct { + w *window + p *pluginSettingsForm + hasSource bool +} + +// row is the index of the declared setting in the form, or -1. +func (s regionSettings) row(setting string) int { + rows := s.p.editor.Snapshot.State.Rows + for index := range rows { + if rows[index].Declaration.ID == setting { + if index < len(s.p.controls[s.p.scope]) { + return index + } + break + } + } + return -1 +} + +func (s regionSettings) Row(c ui.C, setting string) bool { + index := s.row(setting) + if index < 0 { + return false + } + s.w.pluginSettingRow(c, index, s.hasSource) + return true +} + +// Tool draws the toolchains list's row for the tool, in the scope the toolchain pages show. +// Choosing it opens the Toolchains page with the tool chosen, where it is configured. +func (s regionSettings) Tool(c ui.C, tool string) bool { + w := s.w + t := w.toolchains + if t == nil || !t.available() { + return false + } + t.ensureLoaded() + scope := t.current() + if scope == nil || !scope.loaded { + return false + } + entry := t.toolchainEntryFor(scope, tool) + if entry == nil { + return false + } + b := &w.bp + language := w.marketLanguage() + row := ui.ButtonBase(c, entry.tool.DisplayName).FillWidth().Height(toolchainToolRow).PadSides(0, 12, 0, 14). + Gap(9).Items(ui.Center).Radius(6).Border(1, b.line).Hover(ui.Look{}.Background(b.hover)) + if row.Clicked() { + t.reveal(tool, t.view.group(tool)) + w.openBuildChild(pageToolchains) + } + row.Children(func() { w.toolchainToolContent(c, language, scope, entry, "") }) + return true +} + +// Binding is the draft of a declared setting a control can edit: a text, file, directory or +// integer setting's text, a boolean's switch and an enum's choice. +func (s regionSettings) Binding(setting string) (pluginview.Binding, bool) { + p := s.p + index := s.row(setting) + if index < 0 { + return pluginview.Binding{}, false + } + declaration := &p.editor.Snapshot.State.Rows[index].Declaration + control := &p.controls[p.scope][index] + binding := pluginview.Binding{ + Title: declaration.Title, + Editable: !p.running && p.loaded && p.scopeEditor(index).Editable && s.hasSource, + Value: func() any { + value, _ := p.draftValue(index) + return value + }, + Edited: func() { + control.reset = false + p.saved = false + }, + } + switch declaration.Kind { + case "boolean": + binding.On = &control.input.On + case "enum": + binding.Selected, binding.Options = &control.input.Selected, control.options + binding.OptionLabel = func(option int) string { + if option >= 0 && option < len(declaration.Options) { + return declaration.Options[option].Title + } + return "" + } + case "text", "file", "directory", "integer": + binding.Text = &control.text + default: + return pluginview.Binding{}, false + } + return binding, true +} + +func (s regionSettings) Action(action string) { + s.p.act(action, false) +} + +func (s regionSettings) ActionEnabled(action string) bool { + _, ok := s.p.loader.(PluginSettingsActionLoader) + return ok && !s.p.running && s.p.loaded +} + +// scopeEditor is Core's projection of the setting in the scope shown. +func (p *pluginSettingsForm) scopeEditor(index int) core.PluginSettingEditorValue { + if p.scope == 1 { + return p.editor.Snapshot.State.Editors.Project[index] + } + return p.editor.Snapshot.State.Editors.Global[index] +} + +// draftValue is the draft of a setting in the scope shown, typed as the setting stores it, +// as a view event carries it: a number for an integer and the nonblank lines of a list. +// ok is false for a draft that has no such value, an integer the text does not spell. +func (p *pluginSettingsForm) draftValue(index int) (any, bool) { + control := &p.controls[p.scope][index] + declaration := &p.editor.Snapshot.State.Rows[index].Declaration + switch declaration.Kind { + case "boolean": + return control.input.On, true + case "enum": + if selected := control.input.Selected; selected >= 0 && selected < len(declaration.Options) { + return declaration.Options[selected].Value, true + } + return nil, false + case "multiSelect": + values := []string{} + for option, checked := range control.input.Checks { + if checked && option < len(declaration.Options) { + values = append(values, declaration.Options[option].Value) + } + } + return values, true + case "integer": + value, err := strconv.ParseInt(strings.TrimSpace(control.text), 10, 64) + return value, err == nil + case "stringList", "fileList": + // A list is edited one item per line, and keeps its spaces and path spelling. + values := []string{} + for _, line := range strings.Split(control.text, "\n") { + if strings.TrimSpace(line) != "" { + values = append(values, line) + } + } + return values, true + case "text", "file", "directory": + return control.text, true + } + return nil, false +} + +// viewSettings are the plugin's values a region's event carries: what is in force in the +// workspace, and the drafts of the scope shown that differ from it, by setting ID. A reset +// row's draft is the value the reset leaves; a draft that has no typed value is left out. +func (p *pluginSettingsForm) viewSettings() pluginservice.ViewSettings { + settings := pluginservice.ViewSettings{Effective: map[string]json.RawMessage{}, Draft: map[string]json.RawMessage{}} + rows := p.editor.Snapshot.State.Rows + for index := range rows { + if value := rows[index].Effective.Value; len(value) > 0 { + settings.Effective[rows[index].Declaration.ID] = value + } + } + for index := range p.controls[p.scope] { + if index >= len(rows) || !p.changed(index) { + continue + } + id := rows[index].Declaration.ID + if p.controls[p.scope][index].reset { + if value := p.scopeEditor(index).ResetValue; len(value) > 0 { + settings.Draft[id] = value + } + continue + } + value, ok := p.draftValue(index) + if !ok { + continue + } + data, err := json.Marshal(value) + if err != nil { + p.reportViewSettings(err) + continue + } + settings.Draft[id] = data + } + return settings +} + +// reportViewSettings logs settings a view event cannot carry. The drafts are booleans, text, +// numbers and lists of text, and the values in force Core's JSON, so this means a bug. +func (p *pluginSettingsForm) reportViewSettings(err error) { + if p.report != nil { + p.report(fmt.Errorf("settingswindow: encode the settings of a view event: %w", err)) + } +} + +// viewSettingsText is viewSettings encoded, which a paint compares with the last one; JSON +// sorts the IDs, so the same values encode the same. +func (p *pluginSettingsForm) viewSettingsText() string { + data, err := json.Marshal(p.viewSettings()) + if err != nil { + p.reportViewSettings(err) + return "" + } + return string(data) +} diff --git a/desktop/internal/settingswindow/plugin_region_view_test.go b/desktop/internal/settingswindow/plugin_region_view_test.go new file mode 100644 index 0000000000..ed2745de3d --- /dev/null +++ b/desktop/internal/settingswindow/plugin_region_view_test.go @@ -0,0 +1,405 @@ +package settingswindow + +import ( + "context" + "encoding/json" + "errors" + "os" + "reflect" + "slices" + "sync/atomic" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/marketplace" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginsettings" +) + +// regionPlugin is the synthetic plugin whose settings page carries a region view. +const regionPlugin = "dev.lithe.test.region" + +// viewPanelPlugin is the contract fixture that declares a settings region with a view. +const viewPanelPlugin = "dev.lithe.fixture.view-panel" + +// The rows of regionEditor, by index. +const ( + regionWatch = iota + regionMode + regionChecks + regionThreads + regionName + regionPaths +) + +// regionEditor is Core's projection of the synthetic plugin's settings: one row of each kind +// a region binds or carries, editable in the global scope and not in the project's, and a +// region with a view on the plugin's own Settings tab. +func regionEditor() pluginservice.SettingsEditor { + options := func(values ...string) []core.PluginSettingOption { + var list []core.PluginSettingOption + for _, value := range values { + list = append(list, core.PluginSettingOption{Value: value, Title: "Option " + value}) + } + return list + } + rows := []core.PluginSettingRow{ + {Declaration: core.PluginSettingDeclaration{ID: "watch", Kind: "boolean", Title: "Watch files"}, Effective: core.PluginSettingValue{Value: json.RawMessage(`true`)}}, + {Declaration: core.PluginSettingDeclaration{ID: "mode", Kind: "enum", Title: "Mode", Options: options("fast", "full")}, Effective: core.PluginSettingValue{Value: json.RawMessage(`"fast"`)}}, + {Declaration: core.PluginSettingDeclaration{ID: "checks", Kind: "multiSelect", Title: "Checks", Options: options("a", "b")}, Effective: core.PluginSettingValue{Value: json.RawMessage(`["a"]`)}}, + {Declaration: core.PluginSettingDeclaration{ID: "threads", Kind: "integer", Title: "Threads"}, Effective: core.PluginSettingValue{Value: json.RawMessage(`4`)}}, + {Declaration: core.PluginSettingDeclaration{ID: "name", Kind: "text", Title: "Name"}, Effective: core.PluginSettingValue{Value: json.RawMessage(`"core"`)}}, + {Declaration: core.PluginSettingDeclaration{ID: "paths", Kind: "stringList", Title: "Paths"}, Effective: core.PluginSettingValue{Value: json.RawMessage(`["src"]`)}}, + } + inputs := []core.PluginSettingInput{ + {On: true}, {Selected: 0}, {Checks: []bool{true, false}}, {Text: "4"}, {Text: "core"}, {Text: "src"}, + } + var global, project []core.PluginSettingEditorValue + for index, input := range inputs { + value := core.PluginSettingEditorValue{Value: rows[index].Effective.Value, Input: input, Editable: true} + if index == regionThreads { + value.ResetValue = json.RawMessage(`2`) + } + global = append(global, value) + value.Editable = false + project = append(project, value) + } + state := core.PluginSettingsState{ + PluginID: regionPlugin, + Metadata: core.PluginSettingsMetadata{Version: "1.0.0"}, + Rows: rows, + Editors: core.PluginSettingsEditors{Global: global, Project: project}, + Region: &core.PluginSettingsRegion{ID: "overview"}, + } + state.Region.View = &struct { + Function string `json:"function"` + }{Function: "settingsView"} + return pluginservice.SettingsEditor{Snapshot: pluginsettings.Snapshot{State: state}} +} + +// regionForm is a loaded form of the synthetic plugin, its drafts the values in force. +func regionForm() *pluginSettingsForm { + p := newPluginSettingsForm(nil) + p.applyLoad(regionEditor(), nil) + return p +} + +func TestRegionDraftValuesAreTypedAsTheSettingsStoreThem(t *testing.T) { + p := regionForm() + controls := p.controls[0] + controls[regionWatch].input.On = false + controls[regionMode].input.Selected = 1 + controls[regionChecks].input.Checks = []bool{false, true} + controls[regionThreads].text = " 8 " + controls[regionName].text = "app" + controls[regionPaths].text = "src\n \n lib " + for _, tc := range []struct { + row int + want any + }{ + {regionWatch, false}, + {regionMode, "full"}, + {regionChecks, []string{"b"}}, + {regionThreads, int64(8)}, + {regionName, "app"}, + {regionPaths, []string{"src", " lib "}}, + } { + got, ok := p.draftValue(tc.row) + if !ok || !reflect.DeepEqual(got, tc.want) { + t.Errorf("row %d: draft %#v, %v; want %#v", tc.row, got, ok, tc.want) + } + } + controls[regionThreads].text = "eight" + if got, ok := p.draftValue(regionThreads); ok { + t.Errorf("an integer the text does not spell has the value %#v", got) + } + controls[regionMode].input.Selected = 5 + if got, ok := p.draftValue(regionMode); ok { + t.Errorf("a choice outside the options has the value %#v", got) + } +} + +func TestRegionEventSettingsCarryWhatIsInForceAndTheChangedDrafts(t *testing.T) { + p := regionForm() + clean := p.viewSettings() + want := map[string]string{"watch": `true`, "mode": `"fast"`, "checks": `["a"]`, "threads": `4`, "name": `"core"`, "paths": `["src"]`} + if len(clean.Effective) != len(want) || len(clean.Draft) != 0 { + t.Fatalf("a clean form carries %v and the drafts %v", clean.Effective, clean.Draft) + } + for id, value := range want { + if string(clean.Effective[id]) != value { + t.Errorf("%s in force = %s, want %s", id, clean.Effective[id], value) + } + } + before := p.viewSettingsText() + if again := p.viewSettingsText(); again != before { + t.Fatalf("the same settings encode differently: %s and %s", before, again) + } + + controls := p.controls[0] + controls[regionWatch].input.On = false + controls[regionName].text = "app" + controls[regionThreads].reset = true + drafts := p.viewSettings().Draft + if len(drafts) != 3 || string(drafts["watch"]) != `false` || string(drafts["name"]) != `"app"` || string(drafts["threads"]) != `2` { + t.Fatalf("drafts = %v, want watch off, the name app and the threads the reset leaves", drafts) + } + if p.viewSettingsText() == before { + t.Fatal("changed drafts encode as the clean form") + } + + controls[regionThreads].reset = false + controls[regionThreads].text = "eight" + if value, ok := p.viewSettings().Draft["threads"]; ok { + t.Fatalf("an integer the text does not spell was carried as %s", value) + } +} + +func TestRegionBindingsEditTheFormDrafts(t *testing.T) { + p := regionForm() + s := regionSettings{p: p, hasSource: true} + controls := p.controls[0] + + watch, ok := s.Binding("watch") + if !ok || watch.On != &controls[regionWatch].input.On || watch.Title != "Watch files" || !watch.Editable { + t.Fatalf("watch binding = %+v, %v", watch, ok) + } + *watch.On = false + controls[regionWatch].reset, p.saved = true, true + watch.Edited() + if watch.Value() != false || controls[regionWatch].reset || p.saved { + t.Fatalf("an edit left value %v, reset %v, saved %v", watch.Value(), controls[regionWatch].reset, p.saved) + } + + mode, ok := s.Binding("mode") + if !ok || mode.Selected != &controls[regionMode].input.Selected || !reflect.DeepEqual(mode.Options, []int{0, 1}) { + t.Fatalf("mode binding = %+v, %v", mode, ok) + } + if mode.OptionLabel(1) != "Option full" || mode.OptionLabel(5) != "" { + t.Fatalf("option labels %q and %q", mode.OptionLabel(1), mode.OptionLabel(5)) + } + for _, tc := range []struct { + id string + row int + }{{"threads", regionThreads}, {"name", regionName}} { + if binding, ok := s.Binding(tc.id); !ok || binding.Text != &controls[tc.row].text { + t.Errorf("%s binds %+v, %v; want its text", tc.id, binding, ok) + } + } + for _, id := range []string{"checks", "paths", "missing"} { + if _, ok := s.Binding(id); ok { + t.Errorf("%s has a control binding", id) + } + } + + if binding, _ := (regionSettings{p: p}).Binding("watch"); binding.Editable { + t.Error("a scope without a file to write is editable") + } + p.running = true + if binding, _ := s.Binding("watch"); binding.Editable { + t.Error("a form saving is editable") + } + p.running, p.scope = false, 1 + if binding, _ := s.Binding("watch"); binding.Editable { + t.Error("a setting Core does not let the scope edit is editable") + } + + p.scope = 0 + p.controls[0] = p.controls[0][:regionThreads] + if s.row("threads") != -1 || s.row("missing") != -1 || s.row("mode") != regionMode { + t.Fatalf("rows threads %d, missing %d, mode %d", s.row("threads"), s.row("missing"), s.row("mode")) + } +} + +// regionCall is one event a region's view sent its plugin. +type regionCall struct { + region, function string + params map[string]any + closing bool +} + +// regionSource serves the synthetic plugin's form and answers every event of its region +// view with view, or one button without, recording the events in the order the window +// sends them. +type regionSource struct { + calls chan regionCall + view json.RawMessage +} + +func (s *regionSource) Load(context.Context, string, i18n.Language) (pluginservice.SettingsEditor, error) { + return regionEditor(), nil +} + +func (s *regionSource) Save(context.Context, pluginservice.SettingsEditor, string, []core.PluginSettingEdit) (pluginsettings.SaveResult, error) { + return pluginsettings.SaveResult{}, errors.New("unexpected save") +} + +func (s *regionSource) View(_ context.Context, _ pluginservice.SettingsEditor, region, function string, event, _ json.RawMessage, closing bool) (json.RawMessage, bool, error) { + var params map[string]any + if err := json.Unmarshal(event, ¶ms); err != nil { + return nil, false, err + } + s.calls <- regionCall{region: region, function: function, params: params, closing: closing} + if closing { + return nil, false, nil + } + if s.view != nil { + return s.view, true, nil + } + return json.RawMessage(`[{"type":"button","id":"probe","text":"Probe"}]`), true, nil +} + +// next is the next event the view sent other than a settings event, which a draft change +// sends once the values settle. +func (s *regionSource) next(t *testing.T) regionCall { + t.Helper() + deadline := time.After(5 * time.Second) + for { + select { + case call := <-s.calls: + if call.params["event"] == "settings" { + continue + } + return call + case <-deadline: + t.Fatal("the view sent nothing within 5s") + return regionCall{} + } + } +} + +// regionSettingsParam is the settings an event carried, by kind and setting ID. +func regionSettingsParam(t *testing.T, call regionCall) (effective, draft map[string]any) { + t.Helper() + settings, ok := call.params["settings"].(map[string]any) + if !ok { + t.Fatalf("%v carries no settings", call.params) + } + effective, _ = settings["effective"].(map[string]any) + draft, _ = settings["draft"].(map[string]any) + return effective, draft +} + +// A region opens with the plugin's own Settings tab and carries the page's settings, a +// changed draft rides on the next event, and the view closes when the tab is left or the +// language changes, opening anew when it shows again. +func TestRegionViewOpensWithThePageAndClosesWhenThePageChanges(t *testing.T) { + source := ®ionSource{calls: make(chan regionCall, 32)} + var language atomic.Int32 + current := func() i18n.Language { return i18n.Language(language.Load()) } + fetch := func(context.Context) (marketplace.Snapshot, error) { + return marketplace.Snapshot{Index: core.MarketplaceIndex{Plugins: []core.MarketplacePlugin{{ID: regionPlugin, Name: "Region Fixture", LatestVersion: "1.0.0"}}}}, nil + } + w := newWindow(NewController(Options{ + Text: func() *i18n.Messages { return i18n.For(current()) }, Language: current, + Marketplace: fetch, MarketplaceInstalled: fetch, PluginSettings: source, + PluginState: func(string) PluginState { return PluginState{Installed: true, Enabled: true, Version: "1.0.0"} }, + InstalledPlugins: func() []PluginFacts { + return []PluginFacts{{ID: regionPlugin, Name: "Region Fixture", Version: "1.0.0", Settings: len(regionEditor().Snapshot.State.Rows)}} + }, + }), Values{Theme: "dark"}) + w.sess.page = pagePlugins + w.installed.tab = installedSettings + d := openWindow(t, w) + d.until("the region's view", func() bool { return d.has("Probe") }) + + opened := source.next(t) + if opened.params["event"] != "open" || opened.region != "overview" || opened.function != "settingsView" || opened.closing { + t.Fatalf("the first call = %+v, want open of the overview region", opened) + } + if opened.params["language"] != i18n.English.Code() { + t.Fatalf("the view opened in %v", opened.params["language"]) + } + effective, draft := regionSettingsParam(t, opened) + if effective["threads"] != float64(4) || effective["name"] != "core" || len(draft) != 0 { + t.Fatalf("open carried %v in force and the drafts %v", effective, draft) + } + + form := w.pluginSettings + form.controls[0][regionName].text = "app" + d.click("Probe") + clicked := source.next(t) + if _, draft := regionSettingsParam(t, clicked); clicked.params["event"] != "click" || clicked.params["node"] != "probe" || draft["name"] != "app" { + t.Fatalf("the click = %v, want it on probe with the name draft", clicked.params) + } + form.controls[0][regionName].text = "core" + + w.installed.tab = installedFeatures + w.inv.Invalidate() + d.pump() + if closed := source.next(t); !closed.closing || closed.params["event"] != "close" || closed.params["instance"] != opened.params["instance"] { + t.Fatalf("leaving the tab sent %+v, want the view closed", closed) + } + if w.region != nil { + t.Fatal("the window still holds the region of a tab not shown") + } + + w.installed.tab = installedSettings + d.until("the region's view again", func() bool { return d.has("Probe") }) + reopened := source.next(t) + if reopened.params["event"] != "open" || reopened.params["instance"] == opened.params["instance"] { + t.Fatalf("showing the tab again sent %v, want a new open", reopened.params) + } + + language.Store(int32(i18n.Chinese)) + d.until("the view in Chinese", func() bool { + return w.region != nil && w.region.key.language == i18n.Chinese && d.has("Probe") + }) + if closed := source.next(t); !closed.closing || closed.params["instance"] != reopened.params["instance"] { + t.Fatalf("a language change sent %+v, want the view closed", closed) + } + if chinese := source.next(t); chinese.params["event"] != "open" || chinese.params["language"] != i18n.Chinese.Code() { + t.Fatalf("a language change then sent %v, want the view opened in Chinese", chinese.params) + } +} + +// A region's keywords find its page: the view-panel fixture's region, placed on a language +// page, makes the page a hit for words only the region declares, through Core's search. +func TestSearchFindsAPluginPageByItsRegionKeywords(t *testing.T) { + data, err := os.ReadFile(contractfixture.Path("fixtures/ui/view-panel.plugin.json")) + if err != nil { + t.Fatal(err) + } + var manifest map[string]any + if err := json.Unmarshal(data, &manifest); err != nil { + t.Fatal(err) + } + regions, _ := manifest["settingRegions"].([]any) + region, _ := regions[0].(map[string]any) + if region == nil { + t.Fatal("the view-panel fixture declares no settings region") + } + region["page"] = map[string]string{"languageID": "elixir"} + placed, err := json.Marshal(manifest) + if err != nil { + t.Fatal(err) + } + client := core.NewClient() + w := newWindow(NewController(Options{ + Text: func() *i18n.Messages { return i18n.For(i18n.English) }, SettingsNavigation: client.SettingsNavigation, + SettingsPages: func(ctx context.Context, _ i18n.Language) ([]core.SettingsPage, error) { + return client.SettingsPages(ctx, []core.SettingsContribution{{Manifest: placed, Owner: core.PluginSettingsOwner{PluginID: viewPanelPlugin, Version: "1.0.0"}, Enabled: true}}, "") + }, + }), Values{Theme: "dark"}) + d := openWindow(t, w) + d.until("the region's page", func() bool { return len(w.dynamic.pages) == 1 }) + page := w.dynamic.pages[0] + if len(page.Contributors) != 1 || page.Contributors[0].Region == nil || !slices.Contains(page.Contributors[0].Region.Keywords, "module graph") { + t.Fatalf("Core placed %+v on the page, want the fixture's region with its keywords", page.Contributors) + } + listed := func() bool { + for _, r := range w.rows { + if r.dynamic == page.Key { + return true + } + } + return false + } + w.searchField.SetText("module graph") + d.until("the page the region's keyword finds", listed) + w.searchField.SetText("no such words") + d.until("a search no region matches", func() bool { return w.query == foldQuery("no such words") && !listed() }) +} diff --git a/desktop/internal/settingswindow/plugin_region_visual_test.go b/desktop/internal/settingswindow/plugin_region_visual_test.go new file mode 100644 index 0000000000..06b7352ba3 --- /dev/null +++ b/desktop/internal/settingswindow/plugin_region_visual_test.go @@ -0,0 +1,138 @@ +//go:build vivahead && lithevisual + +package settingswindow + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/marketplace" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginsettings" + "github.com/vivaui/viva/headless" +) + +// viewPanelManifest is the contract's view-panel fixture with settings a region binds: one of +// each kind the view's controls edit and one the host draws as its own row. +func viewPanelManifest(t *testing.T) json.RawMessage { + t.Helper() + data, err := os.ReadFile(contractfixture.Path("fixtures/ui/view-panel.plugin.json")) + if err != nil { + t.Fatal(err) + } + var manifest map[string]json.RawMessage + if err := json.Unmarshal(data, &manifest); err != nil { + t.Fatal(err) + } + manifest["settings"] = json.RawMessage(`[ + {"id":"mode","type":"enum","title":"Mode","default":"fast","options":[{"value":"fast","title":"Fast"},{"value":"full","title":"Full"}]}, + {"id":"watch","type":"boolean","title":"Watch files","default":true}, + {"id":"name","type":"text","title":"Name","default":"core","pattern":"[a-z][a-z0-9-]*","maxLength":32}, + {"id":"threads","type":"integer","title":"Threads","default":4,"minimum":1,"maximum":64}]`) + data, err = json.Marshal(manifest) + if err != nil { + t.Fatal(err) + } + return data +} + +// regionViewSource is the settings store over the view-panel fixture, its region drawn from view. +type regionViewSource struct { + settingsFormSource + view json.RawMessage +} + +func (s regionViewSource) View(context.Context, pluginservice.SettingsEditor, string, string, json.RawMessage, json.RawMessage, bool) (json.RawMessage, bool, error) { + return s.view, true, nil +} + +// visualRegionView is a settings region that binds declared settings, shows the host's row +// for one setting and one tool, and draws a summary on a canvas. +func visualRegionView() json.RawMessage { + view, _ := json.Marshal([]map[string]any{ + {"type": "banner", "tone": "accent", "text": "These settings apply to every project the plugin indexes."}, + {"type": "segmented", "id": "mode", "label": "Mode", "setting": "mode"}, + {"type": "toggle", "id": "watch", "label": "Watch files", "setting": "watch"}, + {"type": "textField", "id": "name", "label": "Name", "setting": "name", "width": 24}, + {"type": "setting", "setting": "threads"}, + {"type": "tool", "tool": fixtureTool}, + {"type": "keyValue", "items": []map[string]any{ + {"label": "Indexed", "value": "1,284 files"}, + {"label": "Last check", "value": "Passed", "tone": "success"}, + }}, + {"type": "canvas", "id": "coverage", "label": "Index coverage", "height": 56, "viewBox": []int{0, 0, 560, 56}, "nodes": []map[string]any{ + {"type": "rect", "x": 0, "y": 0, "w": 560, "h": 56, "radius": 8, "fill": "$surface", "stroke": "$line"}, + {"type": "text", "x": 14, "y": 22, "text": "Index coverage", "style": "caption", "color": "$textSecondary"}, + {"type": "rect", "x": 14, "y": 32, "w": 532, "h": 10, "radius": 5, "fill": "$badge"}, + {"type": "rect", "x": 14, "y": 32, "w": 420, "h": 10, "radius": 5, "fill": "$accent"}, + {"type": "text", "x": 546, "y": 22, "text": "79%", "style": "strong", "align": "end"}, + }}, + }) + return view +} + +// TestVisualPluginRegion renders the view-panel fixture's Settings tab with its region, in the +// dark and the light theme. Opt in with -tags 'vivahead lithevisual' and +// LITHE_VISUAL_OUTPUT_DIR. +func TestVisualPluginRegion(t *testing.T) { + out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") + if out == "" { + t.Skip("set LITHE_VISUAL_OUTPUT_DIR to capture a plugin settings region") + } + if err := os.MkdirAll(out, 0755); err != nil { + t.Fatal(err) + } + language := i18n.English + manifest := viewPanelManifest(t) + fetch := func(context.Context) (marketplace.Snapshot, error) { + return marketplace.Snapshot{Index: core.MarketplaceIndex{Plugins: []core.MarketplacePlugin{{ID: viewPanelPlugin, Name: "View Panel", LatestVersion: "1.0.0"}}}}, nil + } + for _, theme := range []string{"dark", "light"} { + t.Run(theme, func(t *testing.T) { + // The preference directory does not exist, so the page reads the defaults and shows + // a fixed path rather than the machine's temporary directory; nothing here saves. + source := regionViewSource{ + settingsFormSource: settingsFormSource{store: pluginsettings.New(core.NewClient(), "/fixture/preferences"), manifest: manifest, workspace: t.TempDir()}, + view: visualRegionView(), + } + // Core validates the manifest; a rule it adds would otherwise show only as a window + // that never draws the region. + if _, err := source.Load(context.Background(), viewPanelPlugin, language); err != nil { + t.Fatalf("Core did not load the view-panel fixture's settings: %v", err) + } + w := newWindow(NewController(Options{ + Text: func() *i18n.Messages { return i18n.For(language) }, Language: func() i18n.Language { return language }, + SystemDark: func() bool { return theme == "dark" }, + Marketplace: fetch, MarketplaceInstalled: fetch, PluginSettings: source, + Toolchains: &fakeToolchainLoader{snapshot: globalVisualToolchains()}, + PluginState: func(string) PluginState { return PluginState{Installed: true, Enabled: true, Version: "1.0.0"} }, + InstalledPlugins: func() []PluginFacts { + return []PluginFacts{{ID: viewPanelPlugin, Name: "View Panel", Vendor: "Example", Version: "1.0.0", Settings: 4}} + }, + }), Values{Theme: theme, Language: language.Code()}) + w.sess.page = pagePlugins + w.installed.tab = installedSettings + config := w.config() + config.Height = 1180 + session, err := headless.Open(config, nil, headless.Options{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + d := &windowDriver{t: t, w: w, driver: session.Driver()} + d.until("the region's view and the tool row", func() bool { + return d.text("Indexed") && d.has("Compiler") && d.has("Fast") + }) + d.pump() + if err := session.Screenshot(filepath.Join(out, "plugin-settings-region-"+theme+".png")); err != nil { + t.Fatal(err) + } + }) + } +} diff --git a/desktop/internal/settingswindow/plugin_settings_language_test.go b/desktop/internal/settingswindow/plugin_settings_language_test.go index 652462ea0b..192c48015b 100644 --- a/desktop/internal/settingswindow/plugin_settings_language_test.go +++ b/desktop/internal/settingswindow/plugin_settings_language_test.go @@ -67,8 +67,8 @@ func TestPluginSettingsTextFollowsTheWindowLanguageWithoutDiscardingDrafts(t *te Language: current, Text: func() *i18n.Messages { return i18n.For(current()) }, SettingsNavigation: client.SettingsNavigation, - SettingsPages: func(ctx context.Context) ([]core.SettingsPage, error) { - return client.SettingsPages(ctx, []core.SettingsContribution{{Manifest: manifest, Owner: core.PluginSettingsOwner{PluginID: "dev.lithe.fixture.settings", Version: "0.1.0"}, Enabled: true}}) + SettingsPages: func(ctx context.Context, _ i18n.Language) ([]core.SettingsPage, error) { + return client.SettingsPages(ctx, []core.SettingsContribution{{Manifest: manifest, Owner: core.PluginSettingsOwner{PluginID: "dev.lithe.fixture.settings", Version: "0.1.0"}, Enabled: true}}, "") }, }), Values{Theme: "dark"}) d := openWindow(t, w, func(config *app.Config) { config.Height = 1100 }) diff --git a/desktop/internal/settingswindow/plugin_settings_view.go b/desktop/internal/settingswindow/plugin_settings_view.go index 1319da6a54..90ba3597b9 100644 --- a/desktop/internal/settingswindow/plugin_settings_view.go +++ b/desktop/internal/settingswindow/plugin_settings_view.go @@ -134,6 +134,7 @@ func (w *window) pluginSettingsPanel(c ui.C, id string) { } if compiler { w.pluginSettingActions(c) + w.pluginRegion(c, p, true) for _, item := range p.layout { if item.action { w.pluginSettingActionRow(c, item.row) @@ -162,8 +163,12 @@ func (w *window) pluginSettingsPanel(c ui.C, id string) { ui.Wrap(c, source).FontSize(11).Color(w.pal.muted) } w.pluginSettingActions(c) + // The plugin's region sits between the header and its declared rows, which stay. + w.pluginRegion(c, p, source != "") if len(p.layout) == 0 { - ui.Text(c, i18n.Shared(language, "desktop.pluginSettings.empty")).FontSize(12).Color(w.pal.muted) + if w.region == nil { + ui.Text(c, i18n.Shared(language, "desktop.pluginSettings.empty")).FontSize(12).Color(w.pal.muted) + } return } // Core's section references are walked in Core's order, without sorting or diff --git a/desktop/internal/settingswindow/plugin_settings_visual_test.go b/desktop/internal/settingswindow/plugin_settings_visual_test.go index 3f01bf6419..651a1ab034 100644 --- a/desktop/internal/settingswindow/plugin_settings_visual_test.go +++ b/desktop/internal/settingswindow/plugin_settings_visual_test.go @@ -129,8 +129,8 @@ func TestVisualPluginSettingsPage(t *testing.T) { Text: func() *i18n.Messages { return i18n.For(look.language) }, Language: func() i18n.Language { return look.language }, SystemLanguage: look.language, SystemDark: func() bool { return look.theme == "dark" }, PluginSettings: source, SettingsNavigation: client.SettingsNavigation, - SettingsPages: func(ctx context.Context) ([]core.SettingsPage, error) { - return client.SettingsPages(ctx, []core.SettingsContribution{{Manifest: manifest, Owner: core.PluginSettingsOwner{PluginID: "dev.example.settings", Version: "1.0.0"}, Enabled: true}}) + SettingsPages: func(ctx context.Context, _ i18n.Language) ([]core.SettingsPage, error) { + return client.SettingsPages(ctx, []core.SettingsContribution{{Manifest: manifest, Owner: core.PluginSettingsOwner{PluginID: "dev.example.settings", Version: "1.0.0"}, Enabled: true}}, "") }, }), Values{Theme: look.theme, Language: look.language.Code()}) config := w.config() diff --git a/desktop/internal/settingswindow/settings_surfaces.go b/desktop/internal/settingswindow/settings_surfaces.go index ff2ba62891..2de5b49c09 100644 --- a/desktop/internal/settingswindow/settings_surfaces.go +++ b/desktop/internal/settingswindow/settings_surfaces.go @@ -104,7 +104,7 @@ func (s *settingsSurfaces) run(parent context.Context) (surfacesResult, error) { result := surfacesResult{pages: job.pages} if !job.loaded && opts.SettingsPages != nil { var err error - result.pages, err = opts.SettingsPages(ctx) + result.pages, err = opts.SettingsPages(ctx, job.language) for index := range result.pages { page := &result.pages[index] if page.Kind == "compiler" { @@ -175,7 +175,7 @@ func (s *settingsSurfaces) run(parent context.Context) (surfacesResult, error) { parentID = "kind:" + page.Kind } name := "page:" + page.Key - items = append(items, core.SettingsNavigationItem{ID: name, Title: page.Title, Parent: &parentID}) + items = append(items, core.SettingsNavigationItem{ID: name, Title: page.Title, Parent: &parentID, Keywords: regionKeywords(page)}) lookup[name] = row{page: parent, dynamic: page.Key, title: page.Title, hit: int(pageCount) + index} } projected, err := opts.SettingsNavigation(ctx, items, key.query) @@ -203,6 +203,19 @@ func (s *settingsSurfaces) run(parent context.Context) (surfacesResult, error) { return result, nil } +// regionKeywords are the words the settings regions of a plugin page's contributors add to +// its search (settingRegions, API-19): Core lists each region's keywords, the manifest's and +// those of the interface language. +func regionKeywords(page core.SettingsPage) string { + var words []string + for _, contributor := range page.Contributors { + if contributor.Region != nil { + words = append(words, contributor.Region.Keywords...) + } + } + return strings.Join(words, " ") +} + // searchRows lists a search's hits flat, as the prototype does: every page the search matched // or that is under a match, with the titles of its ancestors as its path. A group without a // page of its own is only a path, since its pages are listed. A plugin's page under a kind is diff --git a/desktop/internal/settingswindow/settings_surfaces_test.go b/desktop/internal/settingswindow/settings_surfaces_test.go index c0a826f402..b3e1b2f2be 100644 --- a/desktop/internal/settingswindow/settings_surfaces_test.go +++ b/desktop/internal/settingswindow/settings_surfaces_test.go @@ -49,8 +49,8 @@ func TestSettingsDynamicPagesShareDraftsFilterActionsAndRefreshCleanForms(t *tes secondEnabled := true enabled := true var warnings atomic.Int32 - w := newWindow(NewController(Options{SettingsError: func(string, error) { warnings.Add(1) }, PluginSettings: source, Text: func() *i18n.Messages { return i18n.For(i18n.English) }, SettingsNavigation: client.SettingsNavigation, SettingsPages: func(ctx context.Context) ([]core.SettingsPage, error) { - return client.SettingsPages(ctx, []core.SettingsContribution{{Manifest: manifest, Owner: core.PluginSettingsOwner{PluginID: "dev.example.settings", Version: "1.0.0"}, Enabled: enabled}, {Manifest: otherManifest, Owner: core.PluginSettingsOwner{PluginID: "dev.example.settings-other", Version: "1.0.0"}, Enabled: secondEnabled}}) + w := newWindow(NewController(Options{SettingsError: func(string, error) { warnings.Add(1) }, PluginSettings: source, Text: func() *i18n.Messages { return i18n.For(i18n.English) }, SettingsNavigation: client.SettingsNavigation, SettingsPages: func(ctx context.Context, _ i18n.Language) ([]core.SettingsPage, error) { + return client.SettingsPages(ctx, []core.SettingsContribution{{Manifest: manifest, Owner: core.PluginSettingsOwner{PluginID: "dev.example.settings", Version: "1.0.0"}, Enabled: enabled}, {Manifest: otherManifest, Owner: core.PluginSettingsOwner{PluginID: "dev.example.settings-other", Version: "1.0.0"}, Enabled: secondEnabled}}, "") }}), Values{Theme: "dark"}) d := openWindow(t, w, func(config *app.Config) { config.Height = 1100 }) pump := func() { @@ -298,8 +298,8 @@ func TestSettingsDynamicPageListFillsThePageAndShowsItsLastRowWhole(t *testing.T for _, height := range settingsListHeights { client := core.NewClient() source := settingsFormSource{store: pluginsettings.New(client, t.TempDir()), manifest: manifest, workspace: t.TempDir()} - w := newWindow(NewController(Options{PluginSettings: source, Text: func() *i18n.Messages { return i18n.For(i18n.English) }, SettingsNavigation: client.SettingsNavigation, SettingsPages: func(ctx context.Context) ([]core.SettingsPage, error) { - return client.SettingsPages(ctx, []core.SettingsContribution{{Manifest: manifest, Owner: core.PluginSettingsOwner{PluginID: "dev.example.settings", Version: "1.0.0"}, Enabled: true}}) + w := newWindow(NewController(Options{PluginSettings: source, Text: func() *i18n.Messages { return i18n.For(i18n.English) }, SettingsNavigation: client.SettingsNavigation, SettingsPages: func(ctx context.Context, _ i18n.Language) ([]core.SettingsPage, error) { + return client.SettingsPages(ctx, []core.SettingsContribution{{Manifest: manifest, Owner: core.PluginSettingsOwner{PluginID: "dev.example.settings", Version: "1.0.0"}, Enabled: true}}, "") }}), Values{Theme: "dark"}) d := openWindow(t, w, func(config *app.Config) { config.Height = height }) d.until("the language page", func() bool { return len(w.dynamic.pages) == 1 }) diff --git a/desktop/internal/settingswindow/source_settings_view_test.go b/desktop/internal/settingswindow/source_settings_view_test.go index 1dd9118f17..d31b0c9b42 100644 --- a/desktop/internal/settingswindow/source_settings_view_test.go +++ b/desktop/internal/settingswindow/source_settings_view_test.go @@ -107,8 +107,8 @@ func nativeFormWindow(t *testing.T, source *nativeFormFixture, language i18n.Lan } w := newWindow(NewController(Options{Text: func() *i18n.Messages { return i18n.For(language) }, Language: func() i18n.Language { return language }, SystemLanguage: language, SystemDark: func() bool { return theme == "dark" }, PluginSettings: source, SettingsNavigation: core.NewClient().SettingsNavigation, - SettingsPages: func(ctx context.Context) ([]core.SettingsPage, error) { - return core.NewClient().SettingsPages(ctx, []core.SettingsContribution{{Manifest: source.manifest, Owner: core.PluginSettingsOwner{PluginID: "dev.lithe.test.source-settings", Version: "1.0.0"}, Enabled: true}}) + SettingsPages: func(ctx context.Context, _ i18n.Language) ([]core.SettingsPage, error) { + return core.NewClient().SettingsPages(ctx, []core.SettingsContribution{{Manifest: source.manifest, Owner: core.PluginSettingsOwner{PluginID: "dev.lithe.test.source-settings", Version: "1.0.0"}, Enabled: true}}, "") }, Marketplace: fetch, MarketplaceInstalled: fetch, PluginState: func(string) PluginState { return PluginState{Installed: true, Enabled: true, Version: "1.0.0"} }, InstalledPlugins: func() []PluginFacts { return []PluginFacts{{ID: "dev.lithe.test.source-settings", Name: "Fictional Compiler", Version: "1.0.0", Settings: 1}} }}), Values{Theme: theme, Language: language.Code()}) diff --git a/desktop/internal/settingswindow/toolchains_state.go b/desktop/internal/settingswindow/toolchains_state.go index 252f1a453f..ba9ff9f869 100644 --- a/desktop/internal/settingswindow/toolchains_state.go +++ b/desktop/internal/settingswindow/toolchains_state.go @@ -724,13 +724,19 @@ func (t *toolchainState) searchReady(text string) bool { // searchGroup is the key of the group the sidebar's search lists the tool under, empty when // the page does not group. func (t *toolchainState) searchGroup(id string) string { + return t.search.group(id) +} + +// group is the key of the group the projection lists the tool under, empty when it does not +// group or does not list the tool. +func (p *toolchainProjection) group(id string) string { group := "" - for _, row := range t.search.view.Rows { + for _, row := range p.view.Rows { if row.Kind != "tool" { group = row.Key continue } - if entry := t.search.entry(row); entry != nil && entry.tool.ID == id { + if entry := p.entry(row); entry != nil && entry.tool.ID == id { return group } } diff --git a/desktop/internal/settingswindow/toolchains_view.go b/desktop/internal/settingswindow/toolchains_view.go index 818a5d5f27..ee564d1d95 100644 --- a/desktop/internal/settingswindow/toolchains_view.go +++ b/desktop/internal/settingswindow/toolchains_view.go @@ -476,7 +476,17 @@ func (w *window) toolchainGroupRow(r ui.ListRow, language i18n.Language, row cor // draft changes it to and its layer, then the plugin and the home or the reason. func (w *window) toolchainToolRow(r ui.ListRow, language i18n.Language, scope *toolchainScope, entry *toolchainEntry, status string) { b := &w.bp - c := r.C + r.Element.Height(toolchainToolRow).PadSides(0, 12, 0, 14).Gap(9).Items(ui.Center).Hover(ui.Look{}.Background(b.hover)) + if r.Selected() { + r.Element.Background(b.sel) + } + r.Element.Children(func() { w.toolchainToolContent(r.C, language, scope, entry, status) }) +} + +// toolchainToolContent is what a tool's row holds, inside the row the caller lays out: the +// toolchains list's row, or a plugin region's tool node, which draws the same row. +func (w *window) toolchainToolContent(c ui.C, language i18n.Language, scope *toolchainScope, entry *toolchainEntry, status string) { + b := &w.bp tool := &entry.tool if fresh := scope.tool(tool.ID); fresh != nil { tool = fresh @@ -486,47 +496,41 @@ func (w *window) toolchainToolRow(r ui.ListRow, language i18n.Language, scope *t status = toolchainStatus(current) } changed := scope.changed(tool.ID) - r.Element.Height(toolchainToolRow).PadSides(0, 12, 0, 14).Gap(9).Items(ui.Center).Hover(ui.Look{}.Background(b.hover)) - if r.Selected() { - r.Element.Background(b.sel) + if changed { + ui.Row(c).Absolute().Left(4).Top(20).Size(6, 6).Radius(3).Background(b.accent) } - r.Element.Children(func() { - if changed { - ui.Row(c).Absolute().Left(4).Top(20).Size(6, 6).Radius(3).Background(b.accent) - } - dot(c, 8, b.statusColor(status)) - ui.Column(c).Grow(1).Shrink(1).MinWidth(0).Children(func() { - ui.Row(c).FillWidth().Gap(6).Items(ui.Center).Children(func() { - ui.Text(c, toolchainName(tool)).FontSize(buildFont).Weight(gfx.WeightSemibold).Color(b.text).Shrink(1).Ellipsis() - if current.ok { - ui.Text(c, current.version).FontSize(11).Mono().Color(b.sub).Shrink(0) - } - if changed { - next := toolchainNext(scope, tool) - version := "?" - if next.ok { - version = next.version - } - ui.Text(c, "→ "+version).FontSize(11).Mono().Color(b.accent).Shrink(0) - } - ui.Spacer(c) - w.layerTag(c, language, current, status) - }) - ui.Row(c).FillWidth().Height(2).Shrink(0) - ui.Row(c).FillWidth().MinWidth(0).Items(ui.Center).Children(func() { - plugin := toolchainPluginName(scope, tool.PluginID, tool.PluginName) - if current.ok { - ui.Text(c, plugin+" · "+midTrim(current.home, 44)).FontSize(11).Color(b.faint).Shrink(1).Ellipsis() - return - } - detail := w.toolchainReasonDetail(language, scope, entry, tool) - if detail == "" { - ui.Text(c, plugin).FontSize(11).Color(b.faint).Shrink(1).Ellipsis() - return + dot(c, 8, b.statusColor(status)) + ui.Column(c).Grow(1).Shrink(1).MinWidth(0).Children(func() { + ui.Row(c).FillWidth().Gap(6).Items(ui.Center).Children(func() { + ui.Text(c, toolchainName(tool)).FontSize(buildFont).Weight(gfx.WeightSemibold).Color(b.text).Shrink(1).Ellipsis() + if current.ok { + ui.Text(c, current.version).FontSize(11).Mono().Color(b.sub).Shrink(0) + } + if changed { + next := toolchainNext(scope, tool) + version := "?" + if next.ok { + version = next.version } - ui.Text(c, plugin+" · ").FontSize(11).Color(b.faint).Shrink(0) - ui.Text(c, detail).FontSize(11).Color(b.statusColor(status)).Shrink(1).Ellipsis() - }) + ui.Text(c, "→ "+version).FontSize(11).Mono().Color(b.accent).Shrink(0) + } + ui.Spacer(c) + w.layerTag(c, language, current, status) + }) + ui.Row(c).FillWidth().Height(2).Shrink(0) + ui.Row(c).FillWidth().MinWidth(0).Items(ui.Center).Children(func() { + plugin := toolchainPluginName(scope, tool.PluginID, tool.PluginName) + if current.ok { + ui.Text(c, plugin+" · "+midTrim(current.home, 44)).FontSize(11).Color(b.faint).Shrink(1).Ellipsis() + return + } + detail := w.toolchainReasonDetail(language, scope, entry, tool) + if detail == "" { + ui.Text(c, plugin).FontSize(11).Color(b.faint).Shrink(1).Ellipsis() + return + } + ui.Text(c, plugin+" · ").FontSize(11).Color(b.faint).Shrink(0) + ui.Text(c, detail).FontSize(11).Color(b.statusColor(status)).Shrink(1).Ellipsis() }) }) } diff --git a/desktop/internal/settingswindow/visual_capture_test.go b/desktop/internal/settingswindow/visual_capture_test.go index 12a4e386e9..8b82bd257b 100644 --- a/desktop/internal/settingswindow/visual_capture_test.go +++ b/desktop/internal/settingswindow/visual_capture_test.go @@ -107,8 +107,8 @@ func TestVisualSettings(t *testing.T) { client := core.NewClient() opts.PluginSettings = newBuildFormSource(t, client, contributions) opts.SettingsNavigation = client.SettingsNavigation - opts.SettingsPages = func(ctx context.Context) ([]core.SettingsPage, error) { - return client.SettingsPages(ctx, contributions) + opts.SettingsPages = func(ctx context.Context, _ i18n.Language) ([]core.SettingsPage, error) { + return client.SettingsPages(ctx, contributions, "") } } w := newWindow(NewController(opts), values) diff --git a/desktop/internal/settingswindow/window.go b/desktop/internal/settingswindow/window.go index abe0d809d2..0a65d858e3 100644 --- a/desktop/internal/settingswindow/window.go +++ b/desktop/internal/settingswindow/window.go @@ -126,9 +126,11 @@ type window struct { apply buildApply // kinds is the list of each kind of plugin pages under Build, by the kind's place in // buildKinds: its filter, its rows and the page it last showed. - kinds [len(buildKinds)]kindState - pluginSettings *pluginSettingsForm - pluginForms map[string]*pluginSettingsForm + kinds [len(buildKinds)]kindState + pluginSettings *pluginSettingsForm + pluginForms map[string]*pluginSettingsForm + // region is the plugin view of the settings region on screen (plugin_region_view.go). + region *regionView formLimitReported bool dynamic settingsSurfaces dynamicPage string @@ -397,6 +399,7 @@ func (w *window) native() *app.Window { // the system look is no longer watched and the controller forgets the window, so the next // Open makes a new one. The Page has cancelled its effects by then. func (w *window) closed() { + w.closeRegion() w.dismissPluginInstall() if w.ctrl.opts.PluginInstallsClosed != nil { w.ctrl.opts.PluginInstallsClosed() diff --git a/desktop/internal/settingswindow/window_view.go b/desktop/internal/settingswindow/window_view.go index f3c85323c6..940741899f 100644 --- a/desktop/internal/settingswindow/window_view.go +++ b/desktop/internal/settingswindow/window_view.go @@ -37,6 +37,7 @@ func (w *window) view(c ui.C) { w.pluginInstallModal(c.Part("plugin-install")) w.commandInstallModal(c.Part("command-install")) w.declareWork(c) + w.endRegion() } // keys gives Escape its meaning of Cancel, or of emptying the search while the search has diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 8b557431c9..ee310784a2 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -470,10 +470,8 @@ type project struct { everywhereSymbols everywhereSymbolState // tree is the Project tool window's tree of the project folder. tree fileTree - // nativePanels is the view state of each native plugin panel the project shows, by window, and - // nativeSaved what the project kept for them when it last closed (plugin_native.go, plugin_native_state.go). - nativePanels map[string]*nativePanelState - nativeSaved map[string]savedNativePanel + // pluginViews are the plugin views the project's tool windows show, by window (plugin_view.go). + pluginViews map[string]*pluginViewState // build is the Run tool window's provider-backed instances and output. build buildState // buildSessions are the build provider sessions the project started. They live beside build @@ -1522,7 +1520,6 @@ func (a *App) openProjectHere(path string) { a.activatePluginWorkspace(p) a.restoreEditorSession(p) a.restoreCheckpoints(p) - a.restoreNativePanels(p) a.openPendingFiles(p) }) } @@ -1565,7 +1562,7 @@ func (a *App) finishCloseProject(p *project, after func()) { } { a.saveEditorSession(p) - a.saveNativePanels(p) + a.closePluginViews(p) a.releaseIndexing(p) a.closeEverywhere(p) a.recentFiles.open = false diff --git a/desktop/internal/workbench/markdown_images.go b/desktop/internal/workbench/markdown_images.go index 494672d601..f2e830dda6 100644 --- a/desktop/internal/workbench/markdown_images.go +++ b/desktop/internal/workbench/markdown_images.go @@ -6,12 +6,12 @@ import ( "errors" "hash/fnv" "image" - "image/draw" "io" "net/http" "strings" "time" + "github.com/1lck/Lithe-IDEA/desktop/internal/bgra" "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/webpreview" "github.com/vivaui/viva/gfx" @@ -139,18 +139,5 @@ func decodeImageData(data []byte, id uint64) (gfx.Bitmap, error) { if err != nil { return gfx.Bitmap{}, err } - return bitmapOf(decoded, id), nil -} - -// bitmapOf converts an image to the canvas's premultiplied BGRA. -func bitmapOf(decoded image.Image, id uint64) gfx.Bitmap { - bounds := decoded.Bounds() - rgba := image.NewRGBA(image.Rect(0, 0, bounds.Dx(), bounds.Dy())) - draw.Draw(rgba, rgba.Bounds(), decoded, bounds.Min, draw.Src) - // image.RGBA is premultiplied RGBA; the canvas takes premultiplied BGRA. - pix := rgba.Pix - for i := 0; i+3 < len(pix); i += 4 { - pix[i], pix[i+2] = pix[i+2], pix[i] - } - return gfx.Bitmap{Pix: pix, Width: rgba.Rect.Dx(), Height: rgba.Rect.Dy(), Stride: rgba.Stride, ID: id, Version: 1} + return bgra.Bitmap(decoded, id), nil } diff --git a/desktop/internal/workbench/plugin_native.go b/desktop/internal/workbench/plugin_native.go deleted file mode 100644 index b5276b17db..0000000000 --- a/desktop/internal/workbench/plugin_native.go +++ /dev/null @@ -1,704 +0,0 @@ -package workbench - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "strconv" - "time" - - "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" - "github.com/1lck/Lithe-IDEA/desktop/internal/icons" - "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" - "github.com/vivaui/viva/gfx" - "github.com/vivaui/viva/ui" -) - -// Native plugin panels: a tool window the plugin declares as a tree, a list or a form. The host draws the -// rows, fields, toolbar and context menu with its own controls. A click or an arrow key selects a node, Left -// and Right close and open a tree branch, and an action calls the plugin function with the selected ID. A -// form's values and a panel's selection and open branches are kept per project (plugin_native_state.go). - -// nativePanelState is one panel's view state: what is selected, which tree nodes are open, the list's -// scroll, whether an action is running and the message the last action answered. -type nativePanelState struct { - // declaration is the window's native object the state was made for; a changed package starts afresh. - declaration json.RawMessage - form *pluginservice.NativeForm - selected string - expanded map[string]bool - list ui.ListState - tree ui.TreeState - // rows are the visible rows of a tree or list this paint, which the tree's Node reads. - rows []nativeRow - busy bool - message string - // revealed says the toolbar shows: the pointer is over the panel, or the keyboard or assistive focus is on - // one of its buttons. It is read from the previous paint, so the toolbar keeps its place either way. - revealed bool - toolbarFocused bool - // shown says the paint in progress declared this panel. A panel a paint leaves out is hidden: its - // pending calls end (endNativePanels). - shown bool - // nodes are the rows of a source panel, read from its function; sourceLoaded says they are current, - // sourceBusy that a read is out, and sourceFailure names why the last read failed, if it did. - nodes []pluginservice.NativeNode - sourceLoaded bool - sourceBusy bool - sourceFailure string - source nativeCall - action nativeCall - // form holds a form panel's fields: text for the string and number kinds, flags for checkboxes. - // They are created once from the declaration and kept across repaints and reopening. savedForm holds - // the values the project kept until the fields are created. - formReady bool - text map[string]*string - flags map[string]*bool - savedForm map[string]any -} - -// nativeCall is the background call of a panel: its cancel ends it, and its generation tells the answer -// that the panel still wants it. A call that was stopped or superseded has an old generation and is dropped. -type nativeCall struct { - cancel context.CancelFunc - gen uint64 -} - -// nativeRow is one visible row of a panel: a node and how deep it sits. -type nativeRow struct { - node pluginservice.NativeNode - depth int -} - -// nativeWindowKey names a native window within its project. -func nativeWindowKey(tool *pluginservice.ToolWindow) string { - return tool.PluginID + "\x00" + tool.ID -} - -// nativeState returns the state of a window in project p, creating it on first use. A window whose -// declaration changed (its package was replaced) starts from nothing but what the project kept for it. -func (a *App) nativeState(p *project, tool *pluginservice.ToolWindow) *nativePanelState { - if p.nativePanels == nil { - p.nativePanels = map[string]*nativePanelState{} - } - key := nativeWindowKey(tool) - state := p.nativePanels[key] - if state != nil && !bytes.Equal(state.declaration, tool.Native.Declaration) { - state.hide() - state = nil - } - if state == nil { - state = newNativePanelState(p, key, tool) - p.nativePanels[key] = state - } - return state -} - -// newNativePanelState makes the state of a window, applying what the project kept for it: the selection, -// the open branches and the form values. A tree's Node describes its rows from this state. -func newNativePanelState(p *project, key string, tool *pluginservice.ToolWindow) *nativePanelState { - state := &nativePanelState{declaration: tool.Native.Declaration, form: tool.Native.Form, expanded: map[string]bool{}} - state.tree.RowHeight = debugRowHeight - state.tree.Node = func(i int) ui.TreeNode { - row := state.rows[i] - return ui.TreeNode{ - Depth: row.depth, - Branch: len(row.node.Children) > 0, - Expanded: state.expanded[row.node.ID], - Selected: row.node.ID == state.selected, - } - } - if saved, ok := p.nativeSaved[key]; ok { - state.selected = saved.Selected - for _, id := range saved.Expanded { - state.expanded[id] = true - } - state.savedForm = saved.Form - } - return state -} - -// hide ends the calls of a panel that is no longer shown, so their answers are dropped. A reopened panel -// reads its source again and its action buttons are enabled. -func (s *nativePanelState) hide() { - if s.source.cancel == nil && s.action.cancel == nil { - return - } - s.source.stop() - s.action.stop() - s.sourceBusy, s.sourceLoaded, s.busy = false, false, false -} - -// stop ends the call if one is out and makes its answer stale. -func (c *nativeCall) stop() { - if c.cancel != nil { - c.cancel() - c.cancel = nil - } - c.gen++ -} - -// flattenNativeRows lists the rows a panel shows: every node, with the children of the open nodes. -func flattenNativeRows(nodes []pluginservice.NativeNode, expanded map[string]bool, depth int, rows []nativeRow) []nativeRow { - for _, node := range nodes { - rows = append(rows, nativeRow{node: node, depth: depth}) - if expanded[node.ID] && len(node.Children) > 0 { - rows = flattenNativeRows(node.Children, expanded, depth+1, rows) - } - } - return rows -} - -// endNativePanels runs at the end of each paint: a native panel of the open project that the paint did not -// declare is hidden, and every panel is marked as not declared until the next paint declares it. -func (a *App) endNativePanels() { - p := a.project - if p == nil { - return - } - for _, state := range p.nativePanels { - if !state.shown { - state.hide() - } - state.shown = false - } -} - -// startCall runs work for a panel in the background, with the project's context. Starting a call ends the -// previous one of the same kind. The answer is applied only while the call is still wanted and the project -// is open; the call ends with the project, when the panel is hidden, or at its timeout. -func (a *App) startCall(p *project, call *nativeCall, timeout time.Duration, work func(ctx context.Context) func(*App)) { - call.stop() - ctx, cancel := context.WithTimeout(p.ctx, timeout) - call.cancel = cancel - gen := call.gen - a.tasks.running.Add(1) - go func() { - defer a.tasks.running.Done() - apply := work(ctx) - a.post(func(a *App) { - if call.gen != gen || a.project != p { - return - } - call.cancel = nil - cancel() - if apply != nil { - apply(a) - } - }) - }() -} - -// pluginNativeBody declares a native panel: its toolbar, its rows and the actions of its context menu. -func (a *App) pluginNativeBody(c ui.C, p *project, tool *pluginservice.ToolWindow) { - panel := tool.Native - state := a.nativeState(p, tool) - state.shown = true - if panel.Form != nil { - a.pluginFormBody(c, p, tool, state) - return - } - nodes := panel.Nodes - if panel.Source != nil { - nodes = state.nodes - if !state.sourceLoaded && !state.sourceBusy { - a.loadNativeSource(p, tool, state) - } - } - state.rows = flattenNativeRows(nodes, state.expanded, 0, nil) - rows := state.rows - state.toolbarFocused = false - root := ui.Column(c).Fill().Background(a.colors.Editor).Hit(ui.ID(c.Key("native-panel")), tool.Title) - root.Children(func() { - a.nativeFailure(c, state) - if len(panel.Toolbar) > 0 { - // Icon-only actions. They keep their place and stay focusable while hidden; the opacity is - // what the pointer or the keyboard reveals. - opacity := float32(0) - if state.revealed { - opacity = 1 - } - ui.Row(c).FillWidth().Height(panelHeaderHeight).Shrink(0).Items(ui.Center).Gap(2).PadX(8).Children(func() { - for _, id := range panel.Toolbar { - action := nativeAction(panel, id) - if action == nil { - continue - } - button := ui.Button(c.Key("native-"+id), action.Title).Icon(*nativeActionIcon(action)).IconOnly().Ghost(). - Size(shellHideSize, shellHideSize).Shrink(0).Tooltip(action.Title).Opacity(opacity) - button = button.Disabled(state.busy || (action.RequiresSelection && state.selected == "")) - if button.State().Focused { - state.toolbarFocused = true - } - if button.Clicked() { - c.After(func() { a.runNativeAction(p, tool, state, *action, nil) }) - } - } - }) - } - switch { - case len(rows) == 0: - a.panelMessage(c, i18n.Shared(a.language(), "desktop.nativePanel.empty"), a.colors.Subtle) - case panel.Kind == "tree": - a.nativeTree(c, p, tool, state) - default: - a.nativeList(c, p, tool, state) - } - a.nativeMessage(c, state) - }) - state.revealed = root.State().Hovered || state.toolbarFocused -} - -// nativeFailure shows why the last source read failed, above the rows. -func (a *App) nativeFailure(c ui.C, state *nativePanelState) { - if state.sourceFailure == "" { - return - } - ui.Row(c).FillWidth().Height(28).Shrink(0).Items(ui.Center).PadX(8).Children(func() { - ui.Text(c, state.sourceFailure).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Warning).Ellipsis() - }) -} - -// nativeMessage shows the message the last action answered, under the rows. -func (a *App) nativeMessage(c ui.C, state *nativePanelState) { - if state.message == "" { - return - } - ui.Divider(c) - ui.Row(c).FillWidth().Height(28).Shrink(0).Items(ui.Center).PadX(8).Children(func() { - ui.Text(c, state.message).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Ellipsis() - }) -} - -// nativeTree declares a tree panel. The Tree answers the arrows: Right opens a closed branch and Left -// closes an open one (Toggled), a click or Enter chooses a row (Chosen), and a branch chosen that way -// opens or closes as well. -func (a *App) nativeTree(c ui.C, p *project, tool *pluginservice.ToolWindow, state *nativePanelState) { - rows := state.rows - ui.Tree(c, &state.tree, len(rows), func(i int) string { return rows[i].node.Label }, func(i int) { - a.nativeRowContent(c.KeyInt(i), p, tool, state, state.tree.RowID(i), rows[i]) - }).Scrollbars().Label(tool.Title).Grow(1).FillWidth() - toggled, didToggle := state.tree.Toggled() - if didToggle && toggled < len(rows) { - id := rows[toggled].node.ID - c.After(func() { state.expanded[id] = !state.expanded[id] }) - } - if i, ok := state.tree.Chosen(); ok && i < len(rows) { - row := rows[i] - opens := len(row.node.Children) > 0 && !(didToggle && toggled == i) - c.After(func() { - state.selected = row.node.ID - if opens { - state.expanded[row.node.ID] = !state.expanded[row.node.ID] - } - }) - } -} - -// nativeRowContent declares what tree row shows after its chevron. The label names the row, so -// the panel's context menu it carries opens from anywhere on the row. -func (a *App) nativeRowContent(c ui.C, p *project, tool *pluginservice.ToolWindow, state *nativePanelState, row gfx.ID, item nativeRow) { - ui.Row(c).Grow(1).Shrink(1).Items(ui.Center).Gap(6).Children(func() { - label := ui.Text(c, item.node.Label).Grow(1).Shrink(1).FontSize(12.5).Color(a.colors.Text).Ellipsis().LabelFor(row) - a.nativeContextMenu(c, label, p, tool, state, item.node.ID) - }) -} - -// nativeList declares a list panel: one row per node, a click selects it. -func (a *App) nativeList(c ui.C, p *project, tool *pluginservice.ToolWindow, state *nativePanelState) { - rows := state.rows - ui.List(c, &state.list, len(rows), func(row ui.ListRow) { - item := rows[row.Index] - row.Element.Height(debugRowHeight).PadX(10).Items(ui.Center).Gap(6).Hover(ui.Look{}.Background(a.colors.Hover)) - if item.node.ID == state.selected { - row.Element.Background(a.colors.Selection) - } - row.Element.Children(func() { - ui.Text(row.C, item.node.Label).Grow(1).Shrink(1).FontSize(12.5).Color(a.colors.Text).Ellipsis() - }) - if row.Element.Clicked() { - state.selected = item.node.ID - } - a.nativeContextMenu(row.C, row.Element, p, tool, state, item.node.ID) - }).Scrollbars().Label(tool.Title).Grow(1).FillWidth() -} - -// nativeContextMenu attaches the panel's context menu to a list row or to the label of a tree row. -func (a *App) nativeContextMenu(c ui.C, target ui.Box, p *project, tool *pluginservice.ToolWindow, state *nativePanelState, id string) { - if len(tool.Native.ContextMenu) == 0 { - return - } - ui.ContextMenu(c, target, func(menu *ui.MenuItems) { - a.nativeMenuItems(c, menu, p, tool, state, id) - }) -} - -// nativeMenuItems declares the actions of the panel's context menu for the node id. An action -// selects the row it was opened on and then runs. -func (a *App) nativeMenuItems(c ui.C, menu *ui.MenuItems, p *project, tool *pluginservice.ToolWindow, state *nativePanelState, id string) { - panel := tool.Native - menu.WidthRange(160, 240) - for _, actionID := range panel.ContextMenu { - action := nativeAction(panel, actionID) - if action == nil { - continue - } - if menu.Item(action.Title).Disabled(state.busy).Clicked() { - c.After(func() { - state.selected = id - a.runNativeAction(p, tool, state, *action, nil) - }) - } - } -} - -// nativeActionIcon is the host icon an action shows in the toolbar: its declared icon, else the refresh icon -// for a refresh and the generic run icon for an invoke. -func nativeActionIcon(action *pluginservice.NativeAction) *gfx.Icon { - if action.Icon != "" { - return pluginToolIcon(action.Icon) - } - if action.Kind == "refresh" { - return &icons.RefreshCw - } - return &icons.Play -} - -// nativeAction finds a declared action by ID. -func nativeAction(panel *pluginservice.NativePanel, id string) *pluginservice.NativeAction { - for index := range panel.Actions { - if panel.Actions[index].ID == id { - return &panel.Actions[index] - } - } - return nil -} - -// initForm creates the fields of a form from its declaration, once. A value the project kept is used when -// its field still exists with the same kind and, for a choice, one of its options, and within the bounds of -// a stepper; anything else falls back to the declared value. -func initForm(state *nativePanelState, form *pluginservice.NativeForm) { - if state.formReady { - return - } - state.text, state.flags = map[string]*string{}, map[string]*bool{} - for _, control := range form.Controls { - saved, kept := state.savedForm[control.ID] - switch control.Kind { - case "checkbox": - value, _ := control.Value.(bool) - if flag, ok := saved.(bool); kept && ok { - value = flag - } - state.flags[control.ID] = &value - case "stepper": - number, _ := control.Value.(float64) - if kept { - if value, ok := saved.(float64); ok && value >= control.Minimum && value <= control.Maximum { - number = value - } - } - text := strconv.FormatFloat(number, 'f', -1, 64) - state.text[control.ID] = &text - default: - text, _ := control.Value.(string) - if value, ok := saved.(string); kept && ok && savedTextFits(control, value) { - text = value - } - state.text[control.ID] = &text - } - } - state.savedForm = nil - state.formReady = true -} - -// savedTextFits reports whether a kept text value is still a value of its field: a choice must still have -// the option, and a text field keeps any text. -func savedTextFits(control pluginservice.NativeControl, value string) bool { - if control.Kind != "select" && control.Kind != "segmented" { - return true - } - for _, option := range control.Options { - if option.ID == value { - return true - } - } - return false -} - -// formValues collects the current fields keyed by control ID, as the contract passes them to a button. -// A stepper's text is read as a number when it parses, and kept as text otherwise. -func formValues(state *nativePanelState, form *pluginservice.NativeForm) map[string]any { - values := make(map[string]any, len(form.Controls)) - for _, control := range form.Controls { - if flag, ok := state.flags[control.ID]; ok { - values[control.ID] = *flag - continue - } - text := *state.text[control.ID] - if control.Kind == "stepper" { - if number, err := strconv.ParseFloat(text, 64); err == nil { - values[control.ID] = number - continue - } - } - values[control.ID] = text - } - return values -} - -// pluginFormBody declares a form panel: its controls packed into the form's columns by their spans, then -// its buttons. Every field is disabled while a call is out, and a field the declaration disabled stays -// disabled. A change of a field with onCommit calls that action with every field's value. A form with a -// source reads it when it is shown, and again after each action with the current values. -func (a *App) pluginFormBody(c ui.C, p *project, tool *pluginservice.ToolWindow, state *nativePanelState) { - form := tool.Native.Form - initForm(state, form) - if tool.Native.Source != nil && !state.sourceLoaded && !state.sourceBusy { - a.loadNativeSource(p, tool, state) - } - ui.Column(c).Fill().Background(a.colors.Editor).Children(func() { - a.nativeFailure(c, state) - ui.Column(c).FillWidth().Grow(1).Gap(10).PadX(10).PadY(10).Children(func() { - for _, row := range packFormRows(form) { - row := row - ui.Row(c.Key(fmt.Sprintf("row-%d", row[0].index))).FillWidth().Gap(10).Items(ui.Start).Children(func() { - for _, placed := range row { - a.drawFormControl(c, p, tool, state, placed.control, placed.index, float32(placed.control.Span)) - } - }) - } - if len(form.Buttons) > 0 { - ui.Row(c).FillWidth().Items(ui.Center).Gap(8).Children(func() { - for _, button := range form.Buttons { - button := button - action := nativeAction(tool.Native, button.Action) - if action == nil { - continue - } - styled := ui.Button(c.Key("button-"+button.ID), button.Label) - if !button.Primary { - styled = styled.Outline() - } - if styled.Disabled(state.busy || state.sourceBusy || !button.Enabled).Clicked() { - values := formValues(state, form) - c.After(func() { a.runNativeAction(p, tool, state, *action, values) }) - } - if button.Info != "" { - // The information icon is inert, so its tip stays readable while the button is disabled. - ui.Button(c.Key("info-"+button.ID), button.Label).Icon(icons.Info).IconOnly().Ghost(). - Size(shellHideSize, shellHideSize).Shrink(0).Tooltip(button.Info) - } - } - }) - } - }) - a.nativeMessage(c, state) - }) -} - -// placedControl is a control with its place in the declaration. -type placedControl struct { - control pluginservice.NativeControl - index int -} - -// packFormRows packs the controls in declaration order into rows of the form's columns: a control wraps to -// the next row before its span would exceed the columns. Without a layout every control spans the one column. -func packFormRows(form *pluginservice.NativeForm) [][]placedControl { - var rows [][]placedControl - var current []placedControl - used := 0 - for index, control := range form.Controls { - if used+control.Span > form.Columns && len(current) > 0 { - rows = append(rows, current) - current, used = nil, 0 - } - current = append(current, placedControl{control: control, index: index}) - used += control.Span - } - if len(current) > 0 { - rows = append(rows, current) - } - return rows -} - -// drawFormControl declares one field, filling its share of the row, and commits its change when it has an -// onCommit. The first paint after a change compares with the last committed values, so a commit is never -// repeated for the same value. -func (a *App) drawFormControl(c ui.C, p *project, tool *pluginservice.ToolWindow, state *nativePanelState, control pluginservice.NativeControl, index int, span float32) { - disabled := state.busy || state.sourceBusy || !control.Enabled - key := c.Key("field-" + control.ID) - commit := func() { - if control.OnCommit == "" { - return - } - action := nativeAction(tool.Native, control.OnCommit) - if action == nil { - return - } - values := formValues(state, tool.Native.Form) - c.After(func() { a.runNativeAction(p, tool, state, *action, values) }) - } - ui.Column(c.Key(fmt.Sprintf("cell-%d", index))).Grow(span).Basis(0).MinWidth(0).Gap(4).Children(func() { - switch control.Kind { - case "checkbox": - if ui.Checkbox(key, state.flags[control.ID], control.Label).Disabled(disabled).Changed() { - commit() - } - case "select": - ids, labels := optionIDs(control.Options) - before := *state.text[control.ID] - ui.Select(key, state.text[control.ID], ids, func(id string) string { return labels[id] }).Label(control.Label).FillWidth().Disabled(disabled) - if *state.text[control.ID] != before { - commit() - } - case "segmented": - ui.Text(c, control.Label).FontSize(12).Color(a.colors.Subtle) - ui.Row(c.Key("seg-" + control.ID)).FillWidth().Gap(4).Children(func() { - for _, option := range control.Options { - option := option - button := ui.Button(c.Key("seg-"+control.ID+"-"+option.ID), option.Label).Small() - if *state.text[control.ID] != option.ID { - button = button.Outline() - } - if button.Disabled(disabled).Clicked() && *state.text[control.ID] != option.ID { - *state.text[control.ID] = option.ID - commit() - } - } - }) - case "stepper": - ui.Row(c.Key("step-" + control.ID)).FillWidth().Gap(4).Items(ui.Center).Children(func() { - ui.Text(c, control.Label).Grow(1).FontSize(12).Color(a.colors.Subtle).Ellipsis() - if ui.Button(c.Key("step-down-"+control.ID), "−").Small().Outline().Disabled(disabled).Clicked() { - *state.text[control.ID] = stepValue(*state.text[control.ID], -control.Step, control.Minimum, control.Maximum) - commit() - } - ui.TextField(key, state.text[control.ID], "", control.Placeholder).Width(96).Disabled(disabled) - if ui.Button(c.Key("step-up-"+control.ID), "+").Small().Outline().Disabled(disabled).Clicked() { - *state.text[control.ID] = stepValue(*state.text[control.ID], control.Step, control.Minimum, control.Maximum) - commit() - } - }) - case "editor": - ui.TextArea(key, state.text[control.ID], control.Label, control.Placeholder).FillWidth().Height(float32(control.Rows) * 20).Disabled(disabled) - case "input", "search": - if ui.TextField(key, state.text[control.ID], control.Label, control.Placeholder).FillWidth().Disabled(disabled).Submitted() { - commit() - } - default: - ui.TextField(key, state.text[control.ID], control.Label, control.Placeholder).FillWidth().Disabled(disabled) - } - // The information icon sits under its field, and its tip stays readable while the field is disabled: - // only the field itself is inert. - if control.Info != "" { - ui.Button(c.Key("info-"+control.ID), control.Label).Icon(icons.Info).IconOnly().Ghost(). - Size(shellHideSize, shellHideSize).Shrink(0).Tooltip(control.Info) - } - }) -} - -// optionIDs splits options into their IDs and a label lookup for a select. -func optionIDs(options []pluginservice.NativeOption) ([]string, map[string]string) { - ids := make([]string, len(options)) - labels := make(map[string]string, len(options)) - for index, option := range options { - ids[index], labels[option.ID] = option.ID, option.Label - } - return ids, labels -} - -// stepValue moves a stepper's number by delta and keeps it inside its bounds. Text that is not a number -// starts from the minimum. -func stepValue(text string, delta, minimum, maximum float64) string { - value, err := strconv.ParseFloat(text, 64) - if err != nil { - value = minimum - } - value = min(max(value+delta, minimum), maximum) - return strconv.FormatFloat(value, 'f', -1, 64) -} - -// runNativeAction runs an action. A refresh reads the source again, and a static panel has nothing to -// read, so it changes nothing; an invoke calls its function in the background and shows the message the -// answer carries. Only one action runs at a time. -func (a *App) runNativeAction(p *project, tool *pluginservice.ToolWindow, state *nativePanelState, action pluginservice.NativeAction, values map[string]any) { - if p == nil || a.plugins == nil || state.busy { - return - } - if action.Kind == "refresh" { - if tool.Native.Source != nil { - state.sourceLoaded = false - a.loadNativeSource(p, tool, state) - } - return - } - if action.Kind != "invoke" { - return - } - state.busy, state.message = true, "" - selected, root, plugins, pluginID, function := state.selected, p.root, a.plugins, tool.PluginID, action.Function - reload := tool.Native.Source != nil - a.startCall(p, &state.action, 70*time.Second, func(ctx context.Context) func(*App) { - message, err := plugins.InvokeToolWindowAction(ctx, root, pluginID, function, selected, values) - return func(a *App) { - state.busy = false - if err != nil { - a.operationFailed("plugin_native_action", err) - a.notifyError(i18n.Shared(a.language(), "desktop.nativePanel.failed")) - return - } - state.message = message - // The contract reloads a source after an invocation, since the invocation may have changed it. - if reload { - state.sourceLoaded = false - } - } - }) -} - -// loadNativeSource reads a source panel's nodes for the one detected instance of its build system. Zero -// or several instances fail the read instead of guessing a root, as the contract requires. A form's source -// receives the form's values; its answer has no nodes, so only the failure is shown. -func (a *App) loadNativeSource(p *project, tool *pluginservice.ToolWindow, state *nativePanelState) { - source := tool.Native.Source - var instances []buildInstance - for _, instance := range p.build.instances { - if instance.PluginID == tool.PluginID && instance.BuildSystemID == source.BuildSystemID { - instances = append(instances, instance) - } - } - language := a.language() - switch { - case len(instances) == 0: - state.nodes, state.sourceLoaded = nil, true - state.sourceFailure = i18n.Shared(language, "desktop.nativePanel.noInstance") - return - case len(instances) > 1: - state.nodes, state.sourceLoaded = nil, true - state.sourceFailure = i18n.Shared(language, "desktop.nativePanel.multipleInstances") - return - } - var values map[string]any - if tool.Native.Form != nil { - values = formValues(state, tool.Native.Form) - } - state.sourceBusy = true - plugins, root, pluginID, declaration, function, buildSystemID, instanceRoot := a.plugins, p.root, tool.PluginID, tool.Native.Declaration, source.Function, source.BuildSystemID, instances[0].Root - a.startCall(p, &state.source, 30*time.Second, func(ctx context.Context) func(*App) { - nodes, err := plugins.InvokeNativeSource(ctx, root, pluginID, declaration, function, buildSystemID, instanceRoot, values) - return func(a *App) { - state.sourceBusy = false - state.sourceLoaded = true - if err != nil { - a.operationFailed("plugin_native_source", err) - state.nodes = nil - state.sourceFailure = i18n.Shared(a.language(), "desktop.nativePanel.sourceFailed") - return - } - state.nodes, state.sourceFailure = nodes, "" - } - }) -} diff --git a/desktop/internal/workbench/plugin_native_state.go b/desktop/internal/workbench/plugin_native_state.go deleted file mode 100644 index e39a6b070d..0000000000 --- a/desktop/internal/workbench/plugin_native_state.go +++ /dev/null @@ -1,108 +0,0 @@ -package workbench - -import ( - "encoding/json" - "slices" - "sort" - "time" -) - -// A project reopens with its native plugin panels as they were left: the selected row, the open tree -// branches and a form's values. The state is written when the project closes and read when it opens -// again, by project root, in the same store as the editor session. Each window keeps at most 64 KiB, and -// a window that would keep more keeps nothing. Values of a field that no longer exists, or that no longer -// fits the field, are dropped when the form is built (initForm), so an old state never breaks a new form. - -// nativePanelsFile holds the native panel state of the most recently closed projects, by root. -const nativePanelsFile = "plugin-native-panels.json" - -// nativePanelStateLimit is the most a window may keep, as the contract's per-window state store allows. -const nativePanelStateLimit = 64 << 10 - -// savedNativePanel is one window's state: its selected row ID, the open branches (sorted) and a form's -// values keyed by control ID. -type savedNativePanel struct { - Selected string `json:"selected,omitempty"` - Expanded []string `json:"expanded,omitempty"` - Form map[string]any `json:"form,omitempty"` -} - -// savedNativeProject is the native panel state of one project when it closed. -type savedNativeProject struct { - SavedAt time.Time `json:"savedAt"` - Panels map[string]savedNativePanel `json:"panels"` -} - -// restoreNativePanels reads what p kept for its native panels. Each window applies it when it first opens. -func (a *App) restoreNativePanels(p *project) { - all := map[string]savedNativeProject{} - if found, err := a.store.Load(nativePanelsFile, &all); err != nil { - a.backgroundFailed("plugin_native_state_load", documentLogError(err)) - return - } else if !found { - return - } - if saved, ok := all[p.root]; ok { - p.nativeSaved = saved.Panels - } -} - -// saveNativePanels records the native panels of p for the next time the project opens. A window that was -// never opened this session keeps what it had. A project with no state forgets it. -func (a *App) saveNativePanels(p *project) { - all := map[string]savedNativeProject{} - if _, err := a.store.Load(nativePanelsFile, &all); err != nil { - a.backgroundFailed("plugin_native_state_load", documentLogError(err)) - all = map[string]savedNativeProject{} - } - panels := map[string]savedNativePanel{} - for key, saved := range p.nativeSaved { - panels[key] = saved - } - for key, state := range p.nativePanels { - saved := state.capture() - if encoded, err := json.Marshal(saved); err != nil || len(encoded) > nativePanelStateLimit { - delete(panels, key) - continue - } - panels[key] = saved - } - if len(panels) == 0 { - delete(all, p.root) - } else { - all[p.root] = savedNativeProject{SavedAt: a.now(), Panels: panels} - } - if len(all) > editorSessionLimit { - roots := make([]string, 0, len(all)) - for root := range all { - roots = append(roots, root) - } - slices.SortFunc(roots, func(x, y string) int { return all[y].SavedAt.Compare(all[x].SavedAt) }) - for _, root := range roots[editorSessionLimit:] { - delete(all, root) - } - } - if err := a.store.Save(nativePanelsFile, all); err != nil { - a.backgroundFailed("plugin_native_state_save", documentLogError(err)) - } -} - -// capture reads what a window keeps: its selection, its open branches and, for a form whose fields exist, -// their values. -func (s *nativePanelState) capture() savedNativePanel { - saved := savedNativePanel{Selected: s.selected} - for id, open := range s.expanded { - if open { - saved.Expanded = append(saved.Expanded, id) - } - } - sort.Strings(saved.Expanded) - if s.form != nil { - if s.formReady { - saved.Form = formValues(s, s.form) - } else { - saved.Form = s.savedForm - } - } - return saved -} diff --git a/desktop/internal/workbench/plugin_view.go b/desktop/internal/workbench/plugin_view.go new file mode 100644 index 0000000000..9c0d26a549 --- /dev/null +++ b/desktop/internal/workbench/plugin_view.go @@ -0,0 +1,162 @@ +package workbench + +import ( + "bytes" + "context" + "encoding/json" + "errors" + + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/icons" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginview" + "github.com/vivaui/viva/ui" +) + +// A plugin tool window with a view function (API-13) shows a plugin view: the plugin's +// backend answers each view event with the nodes to draw, Core checks the answer, and the +// workbench draws it with its own controls (pluginview). The view shows while the window's +// body is declared: the first paint that declares it opens it, and the first paint that does +// not, because the window closed, the project closed or the plugin changed, closes it. What the +// view shows lives in memory only and ends with the showing; nothing is saved for it. + +// pluginViewState is one tool window's view in the open project. +type pluginViewState struct { + window pluginservice.ToolWindow + // language is the interface language the view was opened in: the plugin returns its + // text in it, so a language change opens the view anew. + language i18n.Language + session *pluginview.Session + images *pluginview.Images + host pluginview.Host + // shown says this paint declared the window's body. + shown bool +} + +// pluginViewOperation is the operation a tool window view's failures are logged under: a call +// that failed and a view the window cannot read, both drawn in the view with a retry. A canvas +// image it cannot read is drawn without and logged as background work. +const pluginViewOperation = "plugin_view" + +// viewCallFailed logs a view call that failed, from the call's goroutine, under operation: the +// view draws the failure. A call the view's closing or the project's cancelled is not one. +func (a *App) viewCallFailed(ctx context.Context, operation string, err error) { + // log-exempt: 用户取消:视图关闭或项目关闭时取消的调用不是失败。 + if err == nil || errors.Is(err, context.Canceled) { + return + } + a.operationFailedIn(ctx, operation, err) +} + +// pluginViewKey names a tool window's view among the project's. +func pluginViewKey(window *pluginservice.ToolWindow) string { + return window.PluginID + "\x00" + window.ID +} + +// close ends the showing and drops the images it read. +func (v *pluginViewState) close() { + v.session.Close() + v.images.Close() +} + +// pluginView is the view of window in p, made the first time the window shows and made anew +// when the plugin's installed manifest, package or view function, or the interface language, +// changed under it. +func (a *App) pluginView(p *project, window *pluginservice.ToolWindow) *pluginViewState { + key := pluginViewKey(window) + if v := p.pluginViews[key]; v != nil { + if v.window.View == window.View && v.window.Package == window.Package && bytes.Equal(v.window.Manifest, window.Manifest) && v.language == a.language() { + return v + } + v.close() + } + if p.pluginViews == nil { + p.pluginViews = map[string]*pluginViewState{} + } + // The wake is taken now: the window's invalidator is installed before the first paint and + // is safe to call from the call's goroutine. + wake := a.invalidator.Invalidate + plugins, root, current, language, ctx := a.plugins, p.root, *window, a.language(), p.ctx + imageFailed := func(err error) { a.backgroundFailedIn(ctx, "plugin_view_image", err) } + v := &pluginViewState{window: current, language: language, images: pluginview.NewImages(current.Package, wake, imageFailed)} + v.session = pluginview.NewSession(pluginview.Options{ + Call: func(ctx context.Context, event, view json.RawMessage, closing bool) (json.RawMessage, bool, error) { + drawn, changed, err := plugins.CallView(ctx, pluginservice.ToolWindowViewCall(current, root, event, view, closing)) + a.viewCallFailed(ctx, pluginViewOperation, err) + return drawn, changed, err + }, + Params: func() map[string]any { return map[string]any{"language": language.Code()} }, + Wake: wake, + Failed: func(err error) { a.operationFailed(pluginViewOperation, err) }, + Context: ctx, + Go: func(work func()) { + a.tasks.running.Add(1) + go func() { + defer a.tasks.running.Done() + work() + }() + }, + }) + v.host = pluginview.Host{ + Icon: pluginview.HostIcon, + Images: v.images, + Info: a.pluginViewInfo, + } + p.pluginViews[key] = v + return v +} + +// pluginViewBody declares a plugin tool window's body: its view, opened the first time. +func (a *App) pluginViewBody(c ui.C, p *project, window *pluginservice.ToolWindow) { + v := a.pluginView(p, window) + v.shown = true + v.session.Open() + v.host.Palette, v.host.Language = a.pluginViewPalette(), a.language() + ui.Column(c.Key("plugin-view")).Fill().Background(a.colors.Editor).Children(func() { + pluginview.Draw(c, v.session, &v.host, true) + }) +} + +// pluginViewInfo is the workbench's ⓘ for a view's info text, a hover tip as elsewhere. +func (a *App) pluginViewInfo(c ui.C, text string) { + ui.Button(c, i18n.Shared(a.language(), "native.moreInformation")).Icon(icons.Info).IconOnly().Ghost(). + Size(18, 18).Shrink(0).Tooltip(text) +} + +// pluginViewPalette maps the workbench's look onto the tokens a view names, so a view reads +// as part of the window in the light and the dark theme. +func (a *App) pluginViewPalette() pluginview.Palette { + t, k := a.theme, a.colors + return pluginview.Palette{ + Dark: k.Dark, Text: k.Text, TextSecondary: t.MutedForeground, TextMuted: k.Subtle, + Accent: k.Accent, Success: k.Success, Warning: k.Warning, Error: t.Danger, + Surface: t.Card, Background: k.Ground, Sidebar: k.Chrome, Line: k.Line, + Hover: k.Hover, Selection: k.Selection, Badge: t.Secondary, + Popover: t.Popover, PopoverText: t.PopoverForeground, + } +} + +// endPluginViews runs at the end of each paint: a view of the open project that the paint did +// not declare closes, and every view is marked as not declared until the next paint declares it. +func (a *App) endPluginViews() { + p := a.project + if p == nil { + return + } + for key, v := range p.pluginViews { + if !v.shown { + v.close() + delete(p.pluginViews, key) + continue + } + v.shown = false + } +} + +// closePluginViews closes every view of p, as the project closes. +func (a *App) closePluginViews(p *project) { + for _, v := range p.pluginViews { + v.close() + } + p.pluginViews = nil +} diff --git a/desktop/internal/workbench/plugin_view_test.go b/desktop/internal/workbench/plugin_view_test.go new file mode 100644 index 0000000000..d79f69ab08 --- /dev/null +++ b/desktop/internal/workbench/plugin_view_test.go @@ -0,0 +1,30 @@ +package workbench + +import ( + "context" + "errors" + "fmt" + "testing" +) + +// A failed view call, a deadline among them, is logged as a failure the user sees; a call +// the view's closing cancelled is not a failure and writes nothing. +func TestViewCallFailedLogsAFailureButNotACancelledCall(t *testing.T) { + log := &opRecordingLog{} + a := &App{logSink: log} + ctx := context.Background() + a.viewCallFailed(ctx, pluginViewOperation, nil) + a.viewCallFailed(ctx, pluginViewOperation, context.Canceled) + a.viewCallFailed(ctx, pluginViewOperation, fmt.Errorf("plugin view: %w", context.Canceled)) + if len(log.records) != 0 { + t.Fatalf("a call that did not fail was logged: %v", log.records) + } + a.viewCallFailed(ctx, pluginViewOperation, errors.New("the backend exited")) + a.viewCallFailed(ctx, pluginViewOperation, context.DeadlineExceeded) + if got := log.ops(operationFailedEvent); len(got) != 2 { + t.Fatalf("failed calls wrote %d %s records, want two: %v", len(got), operationFailedEvent, log.records) + } + if got := log.ops(backgroundFailedEvent); len(got) != 0 { + t.Fatalf("a failure the view draws was logged as background work: %v", got) + } +} diff --git a/desktop/internal/workbench/plugintools.go b/desktop/internal/workbench/plugintools.go index 10173e9d7c..06c0788057 100644 --- a/desktop/internal/workbench/plugintools.go +++ b/desktop/internal/workbench/plugintools.go @@ -11,6 +11,7 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/icons" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginview" "github.com/1lck/Lithe-IDEA/desktop/internal/toolicons" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" @@ -39,40 +40,18 @@ func placementZone(placement string) zone { return zoneBottomLeft } -// pluginToolIcon is the host icon a window declared by ID, or the generic tool window icon for -// an ID the host does not map. The IDs are the public ones the manifest contract lists. As for -// the built-in windows, an ID IntelliJ has a tool window icon for shows that icon, and the -// others a Lucide icon at its weight. +// pluginToolIcon is the host icon a window declared by ID (pluginview.HostIcon), or the generic +// tool window icon for an ID the host does not map. As for the built-in windows, an ID IntelliJ +// has a tool window icon for shows that icon, and the others a Lucide icon at its weight. func pluginToolIcon(host string) *gfx.Icon { - switch host { - case "database", "services": - return &toolicons.Services - case "terminal": - return &toolicons.Terminal - case "search": - return &toolicons.Find - case "refresh": - return stripeLucide(icons.RefreshCw) - case "reset": - return stripeLucide(icons.Undo2) - case "run": - return &toolicons.Run - case "debug": - return &toolicons.Debug - case "settings": - return stripeLucide(icons.Settings) - case "add": - return stripeLucide(icons.Plus) - case "remove": - return stripeLucide(icons.Minus) - case "git": - return &toolicons.Vcs - case "problems": - return &toolicons.Problems - case "plugin": - return stripeLucide(icons.Sparkles) + icon, ok := pluginview.HostIcon(host) + if !ok { + icon = icons.LayoutGrid } - return stripeLucide(icons.LayoutGrid) + if icon.Stroke > 0 { + return stripeLucide(icon) + } + return &icon } // pluginItems is the built-in catalog followed by an item for each plugin tool window, then diff --git a/desktop/internal/workbench/root.go b/desktop/internal/workbench/root.go index 82fc1e6bc3..0c6ed69b08 100644 --- a/desktop/internal/workbench/root.go +++ b/desktop/internal/workbench/root.go @@ -135,7 +135,7 @@ func (a *App) endPaint() { a.treeApps.endFrame() a.endPluginPageFrame() a.endPreviewFrame() - a.endNativePanels() + a.endPluginViews() } // page declares the window: one stack, so what is declared after the workbench lies over it diff --git a/desktop/internal/workbench/settings.go b/desktop/internal/workbench/settings.go index a6e75b4f8f..669b7c5db6 100644 --- a/desktop/internal/workbench/settings.go +++ b/desktop/internal/workbench/settings.go @@ -40,11 +40,11 @@ func (a *App) newSettingsWindow() *settingswindow.Controller { (settingsToolchains{app: a}).recordFailure(context.Background(), operation, err) }, SettingsNavigation: navigation, - SettingsPages: func(ctx context.Context) ([]core.SettingsPage, error) { + SettingsPages: func(ctx context.Context, language i18n.Language) ([]core.SettingsPage, error) { if a.plugins == nil { return nil, nil } - return a.plugins.SettingsPages(ctx) + return a.plugins.SettingsPages(ctx, language.Code()) }, MarketplaceRank: a.kernel.RankNames, PluginRuntime: a.pluginSettingsRuntime, diff --git a/desktop/internal/workbench/settings_plugins.go b/desktop/internal/workbench/settings_plugins.go index f03aa084a9..a3ad47c604 100644 --- a/desktop/internal/workbench/settings_plugins.go +++ b/desktop/internal/workbench/settings_plugins.go @@ -2,6 +2,7 @@ package workbench import ( "context" + "encoding/json" "errors" "os" @@ -78,3 +79,13 @@ func (s pluginSettingsSources) Save(ctx context.Context, editor pluginservice.Se } return result, err } + +// View sends one event of a settings region's view to the plugin's backend (API-13, API-19). +// The event already carries the page's settings, so nothing is read for it here; the +// workspace is the one the editor was read for. Every failure is logged, that of a close +// event too, whose answer the view ignores; a call the closing page cancelled is not. +func (s pluginSettingsSources) View(ctx context.Context, editor pluginservice.SettingsEditor, region, function string, event, view json.RawMessage, closing bool) (json.RawMessage, bool, error) { + drawn, changed, err := s.app.plugins.CallView(ctx, pluginservice.SettingsViewCall(editor, region, function, editor.Snapshot.Workspace(), event, view, closing)) + s.app.viewCallFailed(ctx, "plugin_settings_view", err) + return drawn, changed, err +} diff --git a/desktop/internal/workbench/shell_view.go b/desktop/internal/workbench/shell_view.go index c2ae097712..d90555860e 100644 --- a/desktop/internal/workbench/shell_view.go +++ b/desktop/internal/workbench/shell_view.go @@ -213,8 +213,8 @@ func (a *App) toolBody(c ui.C, tool item, p *project) { a.notificationsToolBody(c.Part("notificationHistory")) default: switch { - case tool.tool != nil && tool.tool.Native != nil: - a.pluginNativeBody(c, p, tool.tool) + case tool.tool != nil && tool.tool.View != "": + a.pluginViewBody(c, p, tool.tool) case tool.tool != nil && tool.tool.Web != "": a.pluginWebBody(c, tool, p) case tool.tool != nil: diff --git a/desktop/internal/workbench/viewer.go b/desktop/internal/workbench/viewer.go index 94d1a6aefe..88d41b7e1c 100644 --- a/desktop/internal/workbench/viewer.go +++ b/desktop/internal/workbench/viewer.go @@ -14,6 +14,7 @@ import ( "strconv" "strings" + "github.com/1lck/Lithe-IDEA/desktop/internal/bgra" "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/vivaui/viva/gfx" ) @@ -265,7 +266,7 @@ func decodeViewerImage(path string, id uint64) (gfx.Bitmap, error) { if err != nil { return gfx.Bitmap{}, err } - return bitmapOf(decoded, 0x5669657700000000|id), nil + return bgra.Bitmap(decoded, 0x5669657700000000|id), nil } // readViewerHex is the hex view of the leading bytes of a file: offset, sixteen bytes diff --git a/desktop/internal/workbench/viewer_image.go b/desktop/internal/workbench/viewer_image.go index fe45e3ada0..fd738b27a5 100644 --- a/desktop/internal/workbench/viewer_image.go +++ b/desktop/internal/workbench/viewer_image.go @@ -6,6 +6,7 @@ import ( "math" "strconv" + "github.com/1lck/Lithe-IDEA/desktop/internal/bgra" "github.com/1lck/Lithe-IDEA/desktop/internal/fileicons" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/icons" @@ -393,7 +394,7 @@ func checkerBitmap(surface gfx.Color, scale float32, version uint32) gfx.Bitmap } } } - bitmap := bitmapOf(picture, checkerBitmapID) + bitmap := bgra.Bitmap(picture, checkerBitmapID) bitmap.Version = version return bitmap } diff --git a/docs/assets/plugin-views/plugin-settings-region-dark.png b/docs/assets/plugin-views/plugin-settings-region-dark.png new file mode 100644 index 0000000000..1d2c3e927d Binary files /dev/null and b/docs/assets/plugin-views/plugin-settings-region-dark.png differ diff --git a/docs/assets/plugin-views/plugin-settings-region-light.png b/docs/assets/plugin-views/plugin-settings-region-light.png new file mode 100644 index 0000000000..8372a01c44 Binary files /dev/null and b/docs/assets/plugin-views/plugin-settings-region-light.png differ diff --git a/docs/assets/plugin-views/plugin-view-toolwindow-dark.png b/docs/assets/plugin-views/plugin-view-toolwindow-dark.png new file mode 100644 index 0000000000..e3190e8849 Binary files /dev/null and b/docs/assets/plugin-views/plugin-view-toolwindow-dark.png differ diff --git a/docs/assets/plugin-views/plugin-view-toolwindow-light.png b/docs/assets/plugin-views/plugin-view-toolwindow-light.png new file mode 100644 index 0000000000..f1f53eca38 Binary files /dev/null and b/docs/assets/plugin-views/plugin-view-toolwindow-light.png differ diff --git a/docs/development/macos-plugin-api-plan.md b/docs/development/macos-plugin-api-plan.md index 9019e614f6..b85e480309 100644 --- a/docs/development/macos-plugin-api-plan.md +++ b/docs/development/macos-plugin-api-plan.md @@ -35,13 +35,13 @@ Windows 不在本轮,平台矩阵的 partial/pending 保持真实。 | API-10 | 已公开 | applyEdits/replaceSelections/insertText;版本校验、IME/只读拒绝、一次 Undo | | API-11 | 未做 | 公共 save/saveAs/close 与工作区文件变更接口未接入 | | API-12 | 部分完成 | 已公开 `documents/registerContentProvider`(只读内容,≤1 MiB,每窗口每 scheme 一个,仅 macOS);公共多文件 edit、showDiff 未接入 | -| API-13 | 部分完成 | 既有 ui:3 原生 Tree/List/Form;通用独立后端数据源/懒加载未做 | +| API-13 | 部分完成 | 插件视图(ui 0):工具窗口和设置区域的内容由插件后端返回节点树(宿主控件、树、画布),Core `plugins.ui.applyResult` 校验,桌面端用 Viva 原生绘制;旧的 Tree/List/Form 已删除;插件主动推送、树懒加载/分页、`views.reveal` 未做 | | API-14 | 部分完成 | 既有包内网页 bridge、状态/生命周期;通用双向页面消息未做 | | API-15 | 部分完成 | editor/open/reveal 返回 documentID/version;range 只起点光标,替换预览标签未做 | | API-16 | 已公开 | preview/openHTML 支持 split/previewOnly;browser/openExternal 支持 HTTP(S)/已保存 HTML | | API-17 | 部分完成 | 三类窗口消息和按钮/取消;通用 QuickPick/InputBox/授权文件句柄未做 | | API-18 | 未做 | 通用剪贴板与 revealInFinder API 未开放 | -| API-19 | 部分完成 | 已有声明式设置 1/2;通用 settings.get/inspect/update/events 未做;Java 拆分计划(M1、D1):Maven 插件按真实配置读取、回显、写回 settings | +| API-19 | 部分完成 | 已有声明式设置(settings 0)和设置区域 `settingRegions`(搜索关键词、绑定声明设置的插件视图);通用 settings.get/inspect/update/events 未做;Java 拆分计划(M1、D1):Maven 插件按真实配置读取、回显、写回 settings | | API-20 | 部分完成 | global/backend/workspace 可写目录与网页状态;语言服务器的按工作区状态目录按 `state.retention` 后台回收(Core 决定,仅 macOS,无用户可见重置入口);统一 KV/配额/session API 未做 | | API-21 | 既有能力 | 协议 2 credentials/get/set/delete;权限与插件隔离不变 | | API-22 | 部分完成 | 既有函数进度与取消;语言服务器准备状态 `languageServer/setStatus`(仅百分比,无 actions,仅 macOS);新增 `outputLinkMatchers:1`,插件声明的匹配器让 Run 与测试控制台出现链接(macOS);独立 output channel、通用 log/progress API 未做 | @@ -145,7 +145,7 @@ Windows 不在本轮,平台矩阵的 partial/pending 保持真实。 | 表面 | 当前事实 | 仍需补齐 | | --- | --- | --- | | 清单与能力协商 | Mac 支持声明式 API level 1–4;`PluginManifest.hostCapabilities` 是宿主实际声明的版本表 [S1] | 每个新 API 同步完成 Core 校验、Mac 执行、权限、文档、旧版拒绝路径 | -| 原生插件界面 | `ui:3` 已有 Tree/List/Form、工具栏、右键和本地动作,不只是静态文本 [S3] | 动态数据源目前绑定自身 `buildSystemID` 和唯一匹配实例;需通用后端来源、懒加载和分页 | +| 原生插件界面 | 插件视图(ui 0):插件后端的视图函数回答 open/close/click/change/select/activate/viewport/settings 事件,返回宿主控件、树和画布节点,宿主原生绘制 [S3] | 视图只在回答事件时变化,需插件主动推送;树需懒加载和分页 | | 命令 | `ui.commands` 打开自己的工具窗口;面板内动作可以调用函数 [S1/S3] | 不依赖窗口/构建系统的命令处理器,以及语义事件、上下文菜单、快捷键接入 | | 自有网页 | 包内页面可走白名单 Web bridge [S4] | 不是完整文件/编辑器 API;新能力必须分别授权,不能开放 AppModel、DOM 或任意脚本入口 | | 独立后端 | `backend:1` 是每插件一个应用级本机外部进程,只服务自己的网页;`${stateDir}` 可用,`${workspaceStateDir}` 被拒绝;后端会话未接入远程工作区注册表 [S2/S20] | 没有窗口的命令/事件插件不能直接复用该声明;需新版本上下文和激活模型,不能悄悄改 v1 的作用域 | @@ -211,7 +211,7 @@ Mac 当前声明的能力版本为:`backend:1`、`buildModelInputs:1`、`build | ID / 方向 | 候选能力与现状/所有者 | 权限、作用域与验收 | 阶段 | | --- | --- | --- | --- | -| API-13 C/P/E | Tree/List/Form 通用数据源、`views.refresh/getChildren/reveal`、选择/激活/提交;已有 `ui:3` [S3] | UI 贡献权限;数据源不再被迫声明假构建系统。稳定节点 ID、懒加载、分页、错误保留旧数据;选中不等于执行,表单不逐按键调用后端 | M3 | +| API-13 C/P/E | 插件主动推送、树的 `getChildren` 懒加载与分页、`views.reveal`;已有 ui 0 插件视图(节点树、画布、选择/激活/提交事件,视图函数属于插件自己的后端)[S3] | UI 贡献权限;稳定节点 ID、懒加载、分页、错误保留旧数据;选中不等于执行,表单不逐按键调用后端 | M3 | | API-14 C/H/E | 自有 Webview 的 `postMessage/onMessage`、显隐/销毁/状态;已有包内网页与 bridge [S4] | 只面向自己的页面;origin/主框架/页面 generation 验证、内容安全策略、消息/队列限额;关闭页面取消所属请求。不能控制编辑器 Webview 或别的插件页面 | M3 | | API-15 H | `editor.open/reveal`;复用 `workspace.openFile` 与文档 owner [S4/S5] | 文件打开/编辑器访问权限,明确窗口、预览标签与定位范围;已打开 dirty 文档不被磁盘内容替换,后台窗口不抢焦点 | M1:已有打开入口接续;M3:统一选项 | | API-16 H | `preview.openHTML`、`browser.openExternal`;已有内嵌 HTML 浏览器与系统打开 adapter [S9] | 分开授权本地预览和外部链接;内嵌可用当前缓冲区,外部本地文件读取磁盘,未保存时明确告知/请求保存。远程 URL 仅 http(s),本地文件只接授权资源句柄,禁止任意 scheme/脚本注入 | M3 | @@ -224,7 +224,7 @@ Mac 当前声明的能力版本为:`backend:1`、`buildModelInputs:1`、`build | ID / 方向 | 候选能力与现状/所有者 | 权限、作用域与验收 | 阶段 | | --- | --- | --- | --- | -| API-19 H/C/E | `settings.get/inspect/update/onDidChange`;已有 settings 1/2 和注册表 [S10] | 只读/写入分权;区分 Lithe 偏好与工具真实配置,显示来源/作用域/有效值。工具配置显式 Apply、冲突保护、写后重读,不建立无效影子设置 | M3;Java 拆分(M1、D1):Maven 插件内实现 | +| API-19 H/C/E | `settings.get/inspect/update/onDidChange`;已有 settings 0、`settingRegions` 和注册表 [S10] | 只读/写入分权;区分 Lithe 偏好与工具真实配置,显示来源/作用域/有效值。工具配置显式 Apply、冲突保护、写后重读,不建立无效影子设置 | M3;Java 拆分(M1、D1):Maven 插件内实现 | | API-20 H | `storage.global/workspace/session`、包内只读资源;已有平台 state store [S2/S4] | 插件命名空间和配额;状态放平台可写位置,迁移/卸载策略明确。工作区状态不是 v1 应用级 `${stateDir}` 的别名,不写插件包/bundle | M0:作用域;M3:扩展接口;Java 拆分(C-LS):仅新增 temporaryDirectory | | API-21 H | `secrets.get/set/delete`;已有函数协议 v2 credentials 服务 [S2] | 保持本插件隔离和现有凭据授权;不得读取 IDE/Agent/其他插件密钥,不将 secret 放日志、普通配置或状态。先补 SDK/文档一致性,不另造密码库 | M1 | | API-22 H/E | `output.createChannel/append/dispose`、`log`、`progress.withCancellation`;已有函数进度与输出生命周期 [S2/S11] | 插件/操作归属、日志脱敏与字节预算;取消/超时后不再更新 UI。只复用已有进度状态机,不把 stdout 协议流与业务日志混用。输出链接由 Core 匹配、宿主只上样式和转发点击,`resolve` 函数在点击时才调用 | M1:命令结果/进度;M3:独立输出;Java 拆分(C-LS):setStatus | @@ -325,7 +325,7 @@ Mac 当前声明的能力版本为:`backend:1`、`buildModelInputs:1`、`build | DOC-05 | `reference/commands-and-events.md` | handler/贡献/事件区别;菜单、快捷键、上下文键;事件过滤、初始快照和背压 | API-02–04,M1/M3 | | DOC-06 | `reference/workspace-and-files.md` | 目录分页/懒加载、读取/编码、watch、搜索、授权资源句柄、文件修改 | API-05–08/11,M3 | | DOC-07 | `reference/documents-and-editor.md` | dirty 与磁盘、版本/范围/UTF-16、选区、单次 undo、安全保存、保存前事件与超时、diff/只读/多文件限制 | API-09–12/15/43,M1–M3 | -| DOC-08 | `guides/native-ui-and-webviews.md` | 原生 Tree/List/Form 与包内网页的选择;数据源、动作、页面消息、恢复/释放、限制 | API-13/14,M3 | +| DOC-08 | `guides/native-ui-and-webviews.md` | 插件视图(宿主控件、树、画布)与包内网页的选择;事件、补丁、预算、失败与生命周期、页面消息、限制 | API-13/14,M3 | | DOC-09 | `guides/browser-and-preview.md` | 编辑器/内嵌 HTML/自有网页/外部浏览器四分法;未保存内容、网络及 bridge 隔离 | API-15/16,M3 | | DOC-10 | `reference/settings-storage-and-secrets.md` | 真实工具配置与偏好区别、scope、Apply/冲突、状态迁移/卸载、凭据授权 | API-19–21,M1/M3 | | DOC-11 | `reference/window-output-and-execution.md` | 通知/选择/进度/输出、剪贴板、toolchain/process/terminal 权限和所有权 | API-17/18/22–24,随对应阶段 | @@ -393,7 +393,7 @@ Mac 当前声明的能力版本为:`backend:1`、`buildModelInputs:1`、`build | --- | --- | | S1 | [插件契约](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/shared/plugins/contract/v1/README.md)、[Core 能力](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/crates/plugin-model/src/capabilities.rs)、[清单校验与激活事件](https://github.com/Lithe-IDEA/Lithe-core-rust/tree/main/rust/crates/plugin-manifest/src)、[清单 schema](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/shared/plugins/contract/v1/plugin-manifest.schema.json)、Mac 能力表 | | S2 | [backend 1](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/crates/plugin-backend/src/lib.rs)、[函数协议](https://github.com/Lithe-IDEA/Lithe-core-rust/tree/main/rust/crates/plugin-rpc/src)、Mac 后端会话、宿主凭据服务 | -| S3 | 原生 UI 功能、[Core UI 校验](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/crates/plugin-native-ui/src/lib.rs)、[已实现原生 UI Note](../../.agents/notes/implemented/feature/2026-10-21-declarative-native-plugin-ui.md) | +| S3 | 插件视图渲染(`desktop/internal/pluginview/`)、[Core 视图校验](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/crates/plugin-ui/src/lib.rs)、[插件视图 Note](../../.agents/notes/implemented/architecture/2026-11-12-plugin-authored-settings-content.md) | | S4 | Web bridge、包内内容、页面生命周期、状态存储 | | S5 | 文档功能、LSP 编辑入口、Monaco model、diff review | | S6 | 文件端口、Mac 文件适配、目录变更、工程功能 | diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index 6c93bf0090..5055047385 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -27,7 +27,15 @@ native_path() { fi } -# Lithe-core-rust main at 8d3c16b: #102, squash-merged into main on top of fa33446: +# Lithe-core-rust main at 545ca11: #104, squash-merged into main: plugin views replace the native +# UI document. A tool window's view.function and a manifest's settingRegions[].view name a backend +# view function the host calls once per event, and plugins.ui.applyResult checks each result (a +# whole view, patches or nothing) against the manifest, the surface and the view drawn last and +# returns the view to draw; settingsState and plugins.settings.catalog carry each settings region +# with its translated keywords. It is on top of #103 (a76f7d1), squash-merged into main: +# plugins.settings.navigation no longer takes limit or returns overflow rows, which the desktop +# never sent or read. +# Below them, Lithe-core-rust main at 8d3c16b: #102, squash-merged into main on top of fa33446: # toolchains.settingsView issues carry the key of the group their tool is listed under, so the # Toolchains page opens that group with the tool. Main below it has #99 (2ddfae7): # toolDefinitions 1 adds a definition's category and audience; toolchains.settingsView filters, @@ -258,7 +266,7 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # the contract, plugin guides, reference and SDKs live only in shared/plugins; on top of #16 (reported Git queries folded in the console), # #15 (git.write cherryPick, revert and reset fields), #14 (word-level changed ranges of diff # rows), #13, #8, #7, #6 and #4. -PINNED_CORE_REVISION="8d3c16bb75424b7c23aecc890573f0a6d0c74ca8" +PINNED_CORE_REVISION="545ca11fb971795a9937f0f60bcc29afebe3b8be" PROFILE="debug" while [[ $# -gt 0 ]]; do case "$1" in diff --git a/shared/i18n/features/plugin-views.json b/shared/i18n/features/plugin-views.json new file mode 100644 index 0000000000..787faac8ce --- /dev/null +++ b/shared/i18n/features/plugin-views.json @@ -0,0 +1,65 @@ +{ + "schemaVersion": 1, + "messages": [ + { + "id": "desktop.pluginView.failed", + "description": "Plugin view (tool window or settings region): the plugin's backend could not answer the last view event; the last drawn view stays and Retry sends it again", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.pluginView.timedOut", + "description": "Plugin view: the plugin's backend did not answer a view event within the contract's time limit", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.pluginView.invalid", + "description": "Plugin view: Core refused the view the plugin returned, so the host keeps drawing the last valid one", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.pluginView.zoom", + "description": "Plugin view canvas: accessibility label of the zoom percentage button", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.pluginView.resetZoom", + "description": "Plugin view canvas: tooltip of the zoom percentage button, which resets the zoom", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.pluginView.resetZoomHint", + "description": "Plugin view canvas: accessibility hint of the zoom percentage button", + "platforms": [ + "desktop" + ] + } + ], + "locales": { + "en-US": { + "desktop.pluginView.failed": "The plugin could not update this view.", + "desktop.pluginView.timedOut": "The plugin took too long to update this view.", + "desktop.pluginView.invalid": "The plugin returned a view Lithe cannot show.", + "desktop.pluginView.zoom": "Canvas zoom", + "desktop.pluginView.resetZoom": "Reset zoom to 100%", + "desktop.pluginView.resetZoomHint": "Reset zoom" + }, + "zh-CN": { + "desktop.pluginView.failed": "插件无法更新此视图。", + "desktop.pluginView.timedOut": "插件更新此视图超时。", + "desktop.pluginView.invalid": "插件返回的视图无法显示。", + "desktop.pluginView.zoom": "画布缩放", + "desktop.pluginView.resetZoom": "缩放重置为 100%", + "desktop.pluginView.resetZoomHint": "重置缩放" + } + } +} diff --git a/shared/i18n/locales/en-US.json b/shared/i18n/locales/en-US.json index 58d0a045f6..6532848a9b 100644 --- a/shared/i18n/locales/en-US.json +++ b/shared/i18n/locales/en-US.json @@ -10876,8 +10876,6 @@ "desktop.command.groupEditor": "Editor", "desktop.marketplace.sourceUnavailable": "Source unavailable: {source}", "desktop.marketplace.sourceInvalid": "Enter an HTTPS address for the index.", - "desktop.nativePanel.empty": "Nothing to show.", - "desktop.nativePanel.failed": "The plugin could not run this action.", "desktop.run.performance.cpu": "CPU {percent}%", "desktop.run.performance.memory": "Memory {megabytes} MB", "desktop.run.startedAt": ": at {time}", @@ -10885,9 +10883,6 @@ "desktop.run.statusRunning": "Running", "desktop.run.statusStopped": "Stopped", "desktop.run.statusSucceeded": "Succeeded", - "desktop.nativePanel.noInstance": "This workspace has no build system instance for this panel.", - "desktop.nativePanel.multipleInstances": "This workspace has several build system instances; the panel cannot choose one.", - "desktop.nativePanel.sourceFailed": "The plugin could not load this panel.", "desktop.debug.exceptionInfo": "Exception info", "desktop.problems.showPreview": "Show Editor Preview", "desktop.problems.previewEmpty": "Select a problem to preview its source.", diff --git a/shared/i18n/locales/zh-CN.json b/shared/i18n/locales/zh-CN.json index 0097bc597b..8fc485ff15 100644 --- a/shared/i18n/locales/zh-CN.json +++ b/shared/i18n/locales/zh-CN.json @@ -10876,8 +10876,6 @@ "desktop.command.groupEditor": "编辑器", "desktop.marketplace.sourceUnavailable": "来源不可用:{source}", "desktop.marketplace.sourceInvalid": "请输入 HTTPS 格式的索引地址。", - "desktop.nativePanel.empty": "没有可显示的内容。", - "desktop.nativePanel.failed": "插件无法执行此操作。", "desktop.run.performance.cpu": "CPU {percent}%", "desktop.run.performance.memory": "内存 {megabytes} MB", "desktop.run.startedAt": ": 在 {time}", @@ -10885,9 +10883,6 @@ "desktop.run.statusRunning": "正在运行", "desktop.run.statusStopped": "已停止", "desktop.run.statusSucceeded": "成功", - "desktop.nativePanel.noInstance": "此工作区没有该面板需要的构建系统实例。", - "desktop.nativePanel.multipleInstances": "此工作区有多个构建系统实例,面板无法选择。", - "desktop.nativePanel.sourceFailed": "插件无法加载此面板。", "desktop.debug.exceptionInfo": "异常信息", "desktop.problems.showPreview": "显示编辑器预览", "desktop.problems.previewEmpty": "选择一个问题以预览源码。", diff --git a/shared/i18n/messages.json b/shared/i18n/messages.json index dc2c2f22f7..70e8b14ccd 100644 --- a/shared/i18n/messages.json +++ b/shared/i18n/messages.json @@ -13460,41 +13460,6 @@ "desktop" ] }, - { - "id": "desktop.nativePanel.empty", - "description": "Shown in a plugin native panel that declares no node", - "platforms": [ - "desktop" - ] - }, - { - "id": "desktop.nativePanel.failed", - "description": "Notice when a plugin native panel action failed", - "platforms": [ - "desktop" - ] - }, - { - "id": "desktop.nativePanel.multipleInstances", - "description": "Shown in a source-backed plugin panel when the workspace has several instances, so the root is ambiguous", - "platforms": [ - "desktop" - ] - }, - { - "id": "desktop.nativePanel.noInstance", - "description": "Shown in a source-backed plugin panel when the workspace has no instance of the build system it reads", - "platforms": [ - "desktop" - ] - }, - { - "id": "desktop.nativePanel.sourceFailed", - "description": "Shown when a source-backed plugin panel could not read its nodes", - "platforms": [ - "desktop" - ] - }, { "id": "desktop.navigation.historyUnavailable", "description": "Banner shown when the location a back/forward step leads to no longer exists", diff --git a/shared/platform-feature-matrix/features/declarative-native-plugin-ui.json b/shared/platform-feature-matrix/features/declarative-native-plugin-ui.json index 26eeb8c45d..ba805abad5 100644 --- a/shared/platform-feature-matrix/features/declarative-native-plugin-ui.json +++ b/shared/platform-feature-matrix/features/declarative-native-plugin-ui.json @@ -2,15 +2,28 @@ "id": "declarative-native-plugin-ui", "area": "插件", "group": "插件界面", - "capability": "插件声明原生树/列表、工具栏按钮及右键菜单,由宿主统一样式;数据与动作复用已有插件函数入口,保存稳定选择及展开状态,关闭/停用/替换时取消并拒绝晚到结果;ui 3 原生 schema 1;树/列表复用共享外侧留白与焦点外观,选中及悬停背景不贴面板边缘,保留键盘导航;同一停靠槽切换面板按贡献 ID 隔离会话,公共标题栏使用41pt高度、13pt Bold,纯文字且无标题图标、边框和底线;工具栏动作仅图标按钮,复用宿主图标、公共工具栏颜色及原生16pt动作资源,面板悬停或键盘/无障碍聚焦时显露;表单通过 input/select/checkbox 直接复用 IDE 公共输入框、下拉选择与复选框,支持初始值、禁用、提交和工作区内恢复,输入框悬停在未聚焦时即显示I形光标,按钮外观继续复用公共控件;表单支持1–12列栅格与控件span,宿主管理间距及窄面板单列回退;接入字段info、搜索、多行输入、分段选择、数字步进器及普通/主要按钮,文字动作使用#1422公共自然宽度与6pt间距;搜索统一完整入口,单行/密码及多行输入使用完整公共组件,MCP命令输入通过公共垂直输入保持1–3行自适应且Agent指令编辑保留外部焦点,禁用字段/动作的说明仍可用鼠标和键盘查看", + "capability": "插件视图(ui 0 的 view 工具窗口):插件后端的视图函数返回节点树(JSON 场景),宿主用自己的 Viva 控件原生绘制,后端不接触界面库;节点包括 row/section 布局、label、textField、select/segmented、toggle、button、keyValue、table、banner、可折叠树(选择、双击激活、超过 12 行自身滚动)和画布(rect/path/text/image/group,主题色令牌 $accent 等、viewBox 缩放、平移缩放视口);宿主按契约发送 open/close/click/change/select/activate/viewport/settings 事件,同一时间只发一个调用、viewport 与 settings 事件 400 ms 去抖合并,答案由 Core 校验后才绘制;失败显示宿主文案加插件原文并可重试,关闭、停用或替换时取消并丢弃晚到答案;工具窗口标题栏图标与停靠位置沿用已有工具窗口;设置区域(settingRegions)复用同一渲染器,见 plugin-registered-settings-pages", "macos": { "implementationStatus": "partial", "verificationStatus": "pending", "evidence": [ "docs/viva-migration.md", - "desktop/internal/workbench/plugin_native.go", - "desktop/internal/pluginservice/hostnative.go", - "desktop/internal/pluginhost/pluginhost.go" + "desktop/internal/pluginhost/pluginhost.go", + "desktop/internal/core/plugin_view.go", + "desktop/internal/pluginservice/hostview.go", + "desktop/internal/pluginservice/hostview_test.go", + "desktop/internal/pluginservice/toolwindows.go", + "desktop/internal/pluginview/session.go", + "desktop/internal/pluginview/session_test.go", + "desktop/internal/pluginview/render.go", + "desktop/internal/pluginview/render_test.go", + "desktop/internal/pluginview/canvas.go", + "desktop/internal/pluginview/canvas_test.go", + "desktop/internal/pluginview/node.go", + "desktop/internal/pluginview/node_test.go", + "desktop/internal/pluginview/view_visual_test.go", + "desktop/internal/workbench/plugin_view.go", + "desktop/internal/workbench/plugin_view_test.go" ] }, "windows": { @@ -18,13 +31,26 @@ "verificationStatus": "pending", "evidence": [ "docs/viva-migration.md", - "desktop/internal/workbench/plugin_native.go", - "desktop/internal/pluginservice/hostnative.go", - "desktop/internal/pluginhost/pluginhost.go" + "desktop/internal/pluginhost/pluginhost.go", + "desktop/internal/core/plugin_view.go", + "desktop/internal/pluginservice/hostview.go", + "desktop/internal/pluginservice/hostview_test.go", + "desktop/internal/pluginservice/toolwindows.go", + "desktop/internal/pluginview/session.go", + "desktop/internal/pluginview/session_test.go", + "desktop/internal/pluginview/render.go", + "desktop/internal/pluginview/render_test.go", + "desktop/internal/pluginview/canvas.go", + "desktop/internal/pluginview/canvas_test.go", + "desktop/internal/pluginview/node.go", + "desktop/internal/pluginview/node_test.go", + "desktop/internal/pluginview/view_visual_test.go", + "desktop/internal/workbench/plugin_view.go", + "desktop/internal/workbench/plugin_view_test.go" ] }, "owner": "Plugin Platform", - "verification": "运行 PluginNativeUITests、PluginWebBridgeTests、WorkbenchContributionHostTests 和 UI Lab 验收测试(从 Lithe-core-rust 的 shared/plugins/sdk 取得 SDK);macOS 加载 sample-build 示例,刷新、选择、展开及右键 Inspect,验证键盘、浅深色、失焦、隐藏重开、停靠布局恢复以及停用/关闭过程取消;Windows 必须拒绝 ui 3,后续独立适配并验收。原生产品视觉验收 pending。 已在真实 DEBUG 预览中使用磁盘安装示例验证节点加载、展开、Inspect、右键动作、方向键及隐藏重开恢复;修复原生入口初始为空时未出现内容的问题,增加完整父容器挂载回归。完整浅深色、停靠及停用中取消验收仍 pending。 独立 native-ui-lab 验收插件覆盖静态/动态树与列表、左右及底部位置、空数据、600 项长数据、增删改序、动作/数据错误、重复 ID 拒绝和可取消慢动作;运行 Node 验收测试并从打包后的 vendored SDK 再跑一次。完整人工验收由配套 README 指引,仍为 pending。 同一停靠槽在动态树、静态树、列表与空面板间往返切换,确认正确释放窗口会话,不能出现 disabled or already registered;检查标题栏高度、文字、无图标/边框/底线和隐藏动作。 三面板同时挂载,分别隐藏/重开,再全部移除并重建;确认会话所有者销毁后登记清空,旧句柄的释放不影响后续会话。 分隔布局新面板先挂载、旧面板后释放时,同一窗口原子移交会话;旧释放不关闭新句柄,不允许跨插件覆盖登记。 检查原生动作 host 图标的深浅主题工具栏色、原生16pt动作资源和描边,刷新/通用执行兼容回退、面板内悬停显露与面板外隐藏,标题仅用于 tooltip/辅助功能名称。 表单验收:输入中文/Emoji、占位提示与回车提交,选择器键盘/鼠标与 Escape,复选框文字/键盘切换,三类禁用、执行中禁用、所有当前值传入既有函数、隐藏重开及工作区隔离、窄面板滚动和深浅主题;按钮声明复用公共样式。 栅格验收:宽面板每行两个字段,跨列布局能力正确对齐,窄于640pt内容宽度回到单列,变宽恢复;不丢字段值/焦点、不水平溢出,旧无layout表单保持单列。 0.3.0验收:提示悬停/固定/键盘、搜索输入/清空/回车、多行编辑与按钮提交、分段选择与数值边界、主次按钮正常/禁用和content/fill宽度、参数类型/恢复/忙碌/取消/错误;运行公共按钮深浅外框像素回归。 0.3.1验收:现有设置/市场/Git/数据库搜索和插件的完整公共入口一致,清空及外部焦点不回归,禁用输入/按钮和忙碌状态下i提示可悬停/点击/键盘打开,值和动作仍保持禁用。 0.3.2:主次文字按钮复用preview统一样式,实际28pt高度、无外圈留白、短/长文案自然增长和6pt动作间距;窄面板纵向排列;旧fill声明仍可加载但不能拉伸按钮。", + "verification": "自动化:scripts/desktop/desktop-go.sh test ./internal/pluginview/ ./internal/pluginservice/ ./internal/workbench/ ./internal/core/,覆盖事件顺序与去抖、晚到答案丢弃、失败重试、节点解析、画布路径与颜色、图片限制、嵌套树高度,宿主视图事件参数(Core 契约 fixture settings.plugin.json)和工作台视图调用失败的日志;无头截图:LITHE_VISUAL_OUTPUT_DIR=<目录> scripts/desktop/desktop-go.sh test -tags 'vivahead lithevisual' -run TestVisualPluginView ./internal/pluginview/,检查深浅主题。原生整机验收 pending:安装一个声明 view 工具窗口的测试插件,打开、点击、编辑、选择树项、双击激活、拖动与缩放画布,确认事件到达后端并重绘;停用插件、关闭项目时视图关闭且无晚到重绘;后端报错时显示失败与重试。Windows 使用同一 Go Viva 桌面端,需在 Windows 虚拟机上重复上述原生验收。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { @@ -61,5 +87,5 @@ ] } }, - "notes": "Viva:插件声明的原生树、列表与表单工具窗口由宿主控件绘制(plugin_native.go):工具栏在悬停或键盘/无障碍焦点时显露,右键菜单,点击或方向键选择,左右键收起展开,动作带所选 ID 调用插件函数(hostnative.go);表单值、选择和展开状态按项目保存。规格中的 1–12 列栅格、字段 info、搜索与多行输入等尚未逐项核对;没有专门的自动化测试。" + "notes": "Viva:pluginview 包是通用渲染器(session.go 管事件队列与去抖,render.go 绘制控件与树,canvas.go 绘制画布),pluginservice/hostview.go 经 Core 调用后端视图函数并校验答案,workbench/plugin_view.go 把视图挂进工具窗口;旧的 ui 原生树/列表/表单(plugin_native.go、hostnative.go)已删除,由插件视图取代。Viva 尚不支持的画布能力(自定义虚线、多色路径渐变、位图与图层透明度、捏合缩放、圆角裁剪)按契约降级绘制,在 Viva fork 跟进(#2182)。" } diff --git a/shared/platform-feature-matrix/features/declarative-plugin-contract.json b/shared/platform-feature-matrix/features/declarative-plugin-contract.json index 036450857b..76bb8d986d 100644 --- a/shared/platform-feature-matrix/features/declarative-plugin-contract.json +++ b/shared/platform-feature-matrix/features/declarative-plugin-contract.json @@ -38,7 +38,7 @@ ] }, "owner": "Extensions", - "notes": "Viva 的生产启动入口现通过 DesktopOptions 装配同一个原有 Core client,插件发现、Build/Debug/LSP 计划和会话生命周期不再只存在于注入测试选项中。安装目录的版本选择复用 Core 既有数字版本规则,选择最新版本后再检查启用状态,不能回退启用旧版;清单设置投影绑定安装注册的 ID/版本,保存另校验原生目录身份和清单字节。固定 Core 支持 languages 3 TextMate 并撤回 languages 2;settings 2、完整宿主 UI、可信市场安装和全部真实插件生命周期仍未验收,不声明完整支持。公开插件文档须在本 PR 合并后按规则同步。2026-11-11 起 Viva 声明 ui 1、2:ui.toolWindows 的文本窗口与包内网页窗口停靠到工具栏,由 Core 统一排列,停用期间保留位置;ui 3 原生树/列表与 ui.commands 入口尚未接入。", + "notes": "Viva 的生产启动入口现通过 DesktopOptions 装配同一个原有 Core client,插件发现、Build/Debug/LSP 计划和会话生命周期不再只存在于注入测试选项中。安装目录的版本选择复用 Core 既有数字版本规则,选择最新版本后再检查启用状态,不能回退启用旧版;清单设置投影绑定安装注册的 ID/版本,保存另校验原生目录身份和清单字节。固定 Core 支持 languages 3 TextMate 并撤回 languages 2;settings 2、完整宿主 UI、可信市场安装和全部真实插件生命周期仍未验收,不声明完整支持。公开插件文档须在本 PR 合并后按规则同步。2026-11-11 起契约版本归 0,Viva 声明 ui 0:ui.toolWindows 的文本窗口、包内网页窗口和插件视图停靠到工具栏,由 Core 统一排列,停用期间保留位置;旧的原生树/列表已由插件视图取代(见 declarative-native-plugin-ui),ui.commands 入口尚未接入。", "verification": "macOS Core 桥接测试覆盖能力拒绝、启动计划、受控后端进程和会话清理,并验证 TextMate 声明与编辑器解析;旧 Core 固定版本的 Windows 桥接测试已运行,更新后的 Core 尚待 Windows 重跑。完整验收需在两平台安装、启停真实插件,验证权限、路径、安全、进程清理及发行目录不变。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", diff --git a/shared/platform-feature-matrix/features/plugin-functions.json b/shared/platform-feature-matrix/features/plugin-functions.json index 0cbee25463..ea2f9c3bed 100644 --- a/shared/platform-feature-matrix/features/plugin-functions.json +++ b/shared/platform-feature-matrix/features/plugin-functions.json @@ -13,7 +13,7 @@ "desktop/internal/pluginservice/pluginservice.go", "desktop/internal/pluginservice/activation.go", "desktop/internal/pluginservice/pages.go", - "desktop/internal/pluginservice/hostnative.go" + "desktop/internal/pluginservice/hostview.go" ] }, "windows": { @@ -26,12 +26,12 @@ "desktop/internal/pluginservice/pluginservice.go", "desktop/internal/pluginservice/activation.go", "desktop/internal/pluginservice/pages.go", - "desktop/internal/pluginservice/hostnative.go" + "desktop/internal/pluginservice/hostview.go" ] }, "owner": "Extensions", "verification": "macOS Core 桥接测试覆盖声明校验、启动计划、进程协商、函数结果、插件归属拒绝、取消及迟到结果隔离、停止销毁;需接通可信插件宿主后在 macOS 与 Windows 验收完整工作流和进程清理。", - "notes": "Viva:pluginFunctions 已声明;宿主按插件归属调用后端函数(原生面板动作、编辑器动作、设置页按钮、插件页面),调用带上下文以支持取消与超时,页面调用可接收进度;跨插件调用经 Core 的函数中转(lsp.configureFunctionRelay)。尚未用三个官方 SDK 的真实插件在 Viva 上验收。", + "notes": "Viva:pluginFunctions 已声明;宿主按插件归属调用后端函数(插件视图事件、编辑器动作、设置页按钮、插件页面),调用带上下文以支持取消与超时,页面调用可接收进度;跨插件调用经 Core 的函数中转(lsp.configureFunctionRelay)。尚未用三个官方 SDK 的真实插件在 Viva 上验收。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { diff --git a/shared/platform-feature-matrix/features/plugin-registered-settings-pages.json b/shared/platform-feature-matrix/features/plugin-registered-settings-pages.json index 6fcf80f48a..6b401c955f 100644 --- a/shared/platform-feature-matrix/features/plugin-registered-settings-pages.json +++ b/shared/platform-feature-matrix/features/plugin-registered-settings-pages.json @@ -2,7 +2,7 @@ "id": "plugin-registered-settings-pages", "area": "插件", "group": "插件管理", - "capability": "插件通过 settings 2 在 plugin.json 里把设置项和按钮注册到“语言与框架 › <语言>”或“构建、执行、部署 › <构建系统>”页,按 section 分组;设置可声明项目级覆盖(写入项目 .lithe/plugin-settings.json)和生效方式(重启、立即、重新加载、下次运行),“立即生效”的值经 workspace/configuration 推给正在运行的语言服务器;按钮调用插件自己的插件函数。宿主只提供通用页面、控件和语言服务状态卡,不内置任何语言或构建工具的页面;路径选择按钮保持完整可见,窄面板由输入框和标题列缩短以容纳状态标签", + "capability": "插件通过 settings(当前契约版本 0)在 plugin.json 里把设置项和按钮注册到“语言与框架 › <语言>”或“构建、执行、部署 › <构建系统>”页,按 section 分组;设置可声明项目级覆盖(写入项目 .lithe/plugin-settings.json)和生效方式(重启、立即、重新加载、下次运行),“立即生效”的值经 workspace/configuration 推给正在运行的语言服务器;按钮调用插件自己的插件函数。宿主只提供通用页面、控件和语言服务状态卡,不内置任何语言或构建工具的页面;路径选择按钮保持完整可见,窄面板由输入框和标题列缩短以容纳状态标签;settingRegions 让插件在设置页或插件详情的“设置”页签声明区域:区域带搜索关键词,内容由插件视图绘制,控件可绑定已声明的设置(宿主读写真实来源)、嵌入宿主自己的设置行(setting)和工具链工具行(tool),值变化后去抖发送 settings 事件让插件重画", "macos": { "implementationStatus": "partial", "verificationStatus": "pending", @@ -10,7 +10,15 @@ "desktop/internal/settingswindow/settings_surfaces.go", "desktop/internal/settingswindow/plugin_settings_view.go", "desktop/internal/pluginsettings/store.go", - "desktop/internal/pluginservice/settings.go" + "desktop/internal/pluginservice/settings.go", + "desktop/internal/settingswindow/plugin_region_view.go", + "desktop/internal/settingswindow/plugin_region_view_test.go", + "desktop/internal/settingswindow/plugin_region_visual_test.go", + "desktop/internal/pluginservice/settings_editor.go", + "desktop/internal/core/plugin_settings.go", + "desktop/internal/settingswindow/settings_surfaces_test.go", + "desktop/internal/pluginsettings/store_test.go", + "desktop/internal/pluginservice/settings_editor_test.go" ] }, "windows": { @@ -20,11 +28,19 @@ "desktop/internal/settingswindow/settings_surfaces.go", "desktop/internal/settingswindow/plugin_settings_view.go", "desktop/internal/pluginsettings/store.go", - "desktop/internal/pluginservice/settings.go" + "desktop/internal/pluginservice/settings.go", + "desktop/internal/settingswindow/plugin_region_view.go", + "desktop/internal/settingswindow/plugin_region_view_test.go", + "desktop/internal/settingswindow/plugin_region_visual_test.go", + "desktop/internal/pluginservice/settings_editor.go", + "desktop/internal/core/plugin_settings.go", + "desktop/internal/settingswindow/settings_surfaces_test.go", + "desktop/internal/pluginsettings/store_test.go", + "desktop/internal/pluginservice/settings_editor_test.go" ] }, "owner": "Plugin Platform", - "verification": "macOS:先使用 Swift 6.3.3 构建 Release,确认插件页选择回调不触发编译器崩溃;在 Release 应用中选择插件设置页,确认其侧栏分组自动展开。macOS:安装一个声明了 settings 2 页面(page/section/scope/effect/settingActions)的插件并启用,确认设置侧栏的对应分组下出现该语言或构建系统页,页内按插件和 section 分组显示设置与按钮;搜索设置标题能定位到该页。打开项目后把 scope 为 project 的设置切到“此项目”并修改,确认项目下生成 .lithe/plugin-settings.json 且显示“已在此项目覆盖”,恢复默认后文件被删除。修改 effect 为 immediate 的设置,确认语言服务器不重启而配置生效;修改 restart 设置时出现重启提示。点击带 confirm 的按钮先弹确认,再调用插件函数并给出结果通知。停用插件后页面消失。macOS 布局回归:运行 PluginSettingsLayoutTests,检查 480/640/900 点宽、深浅主题的路径控件与选择按钮不重叠且留在容器内,点击选择按钮写入所选路径;在插件详情的窄设置页确认“选择…”文字完整。Windows:宿主仍只声明 settings/languageServers 1,需要 v2 的插件在市场中隐藏。契约 Schema:用 draft 2020-12 校验器(先加载 native-ui.schema.json)校验 settings.plugin.json,确认通过;把 requires.settings 改为 1 或去掉 requires.languageServers 2 后应被拒,确认 Schema 与 Core 对 settings 2 的结构规则一致。", + "verification": "自动化:scripts/desktop/desktop-go.sh test ./internal/settingswindow/ ./internal/pluginsettings/ ./internal/pluginservice/,覆盖 Core 投影的动态插件页(Core 契约 fixture 与 rust/fixtures 的设置清单)共享草稿、按页过滤按钮、刷新干净表单、项目层存储和编辑器投影。设置区域:scripts/desktop/desktop-go.sh test -run 'Region' ./internal/settingswindow/,覆盖绑定设置的草稿类型、可编辑与只读、settings 事件携带的生效值与草稿、随页面打开关闭及切换语言重开,以及按 Core 契约 fixture view-panel 的区域关键词搜索定位页面;无头截图 LITHE_VISUAL_OUTPUT_DIR=<目录> scripts/desktop/desktop-go.sh test -tags 'vivahead lithevisual' -run TestVisualPluginRegion ./internal/settingswindow/(Core 契约 fixture view-panel,深浅主题),检查区域控件、setting 行与 tool 行。原生整机验收 pending:安装一个声明了设置页面(page/section/scope/effect/settingActions/settingRegions)的测试插件并启用,确认设置侧栏的对应分组下出现该语言或构建系统页,页内按插件和 section 分组显示设置、按钮与区域;搜索设置标题或区域关键词能定位到该页。打开项目后把 scope 为 project 的设置切到“此项目”并修改,确认项目下生成 .lithe/plugin-settings.json 且显示“已在此项目覆盖”,恢复默认后文件被删除。修改 effect 为 immediate 的设置,确认语言服务器不重启而配置生效;修改 restart 设置时出现重启提示。点击带 confirm 的按钮先弹确认,再调用插件函数并给出结果通知。在区域里修改绑定值,确认写回来源、插件重画。停用插件后页面与区域消失。Windows 使用同一 Go Viva 桌面端,需在 Windows 虚拟机上重复原生验收。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { @@ -54,5 +70,5 @@ "verificationStatus": "not-applicable" } }, - "notes": "Viva:settings_surfaces.go 按 core.SettingsPage(Key、Kind、Contributors、Sections)动态生成插件设置页,带确认的页面按钮在 plugin_settings_actions_view.go;pluginsettings/store.go 提供项目层存储,pluginservice/settings.go 的 ApplyLanguageSettings 把配置推给运行中的语言服务器;pluginhost 声明 settings 1–2。" + "notes": "Viva:settings_surfaces.go 按 core.SettingsPage(Key、Kind、Contributors、Sections)动态生成插件设置页,带确认的页面按钮在 plugin_settings_actions_view.go;pluginsettings/store.go 提供项目层存储,pluginservice/settings.go 的 ApplyLanguageSettings 把配置推给运行中的语言服务器;pluginhost 声明 settings 0(契约 2026-11-11 版本归 0)。 设置区域:settingswindow/plugin_region_view.go 用 pluginview 渲染器绘制插件区域,绑定设置走与声明设置行相同的编辑器(可编辑条件:已加载、作用域可写且设置有真实来源)。" }