diff --git a/plugins/ztools-dock/AGENTS.md b/plugins/ztools-dock/AGENTS.md new file mode 100644 index 000000000..325091226 --- /dev/null +++ b/plugins/ztools-dock/AGENTS.md @@ -0,0 +1,7 @@ +# 程序坞开发约定 + +- 用中文沟通。 +- 默认只做最小回归:构建/打包检查,以及本次变更直接影响的测试和1条实际宿主操作链路。 +- 只有用户明确要求“完整回归”时,才运行全量单元、`scripts/test-host.mjs` 和完整升级测试;不要每个版本自动运行全套。 +- 新增功能验证取消、保存及必要的失败分支;文案和普通样式调整以构建与页面查看为主,不扩展成全量功能回归。 +- 市场 CI 的构建与打包属于发布检查。提交说明只填写本次实际执行的检查范围,不沿用旧版通过数量。 diff --git a/plugins/ztools-dock/CHANGELOG.md b/plugins/ztools-dock/CHANGELOG.md index 7da861d54..05030a224 100644 --- a/plugins/ztools-dock/CHANGELOG.md +++ b/plugins/ztools-dock/CHANGELOG.md @@ -1,5 +1,49 @@ +## 0.1.21 + +- 统一入口编辑与外观设置的下拉样式,加入搜索、选中标记、键盘选择和自动避让。 +- 插件与分类的当前值、下拉选项都显示图标,支持分类自定义图片。 +- 插件图标按可见范围加载,缩略图缓存最多128项、最长64px、最多3项并发,避免重复读取插件清单。 + +## 0.1.20 + +- 添加插件前先确认两项读取权限,默认不勾选,全部勾选后才能继续。 +- 新增授权管理入口,可查看状态、停止读取,并打开ZTools设置移除宿主授权。 +- 精简设置说明;默认采用定向回归,仅用户明确要求时执行完整回归。 + +## 0.1.19 + +- 移除外层背景材质选项,替换为背景图片上传、预览、更换和移除。 +- 支持PNG、JPG和WebP(5MB以内),自动压缩存入配置,在导航条和弹窗中居中裁剪铺满。 +- 原生云母和亚克力背景停用;菜单和入口玻璃样式保持独立,背景图片支持不透明度及备份迁移。 + +## 0.1.18 + +- 新增冰蓝厚玻璃、柔光磨砂、液态玻璃、清透描边、虹彩玻璃,直接应用于每个分类菜单和入口卡片。 +- 材质强度 0~100% 可调,增加效果预览;卡片质感与外层云母/亚克力背景分别设置。 +- 旧配置沿用经典纯色,原分类、入口与尺寸保留。 + +## 0.1.17 + +- 修复悬浮反复展开时卡片布局和裁剪区域重算导致的闪跳,收起时保留弹窗尺寸。 +- 原生材质背景先于内容窗口显示;钉住收起保持布局并禁止隐藏卡片获得焦点。 + +## 0.1.16 + +- 插件入口改为选择已安装插件及其指令,自动带入插件图标。 +- 插件列表按需授权读取;旧入口保留,停用或同名插件标明原因。 + # 更新记录 +## 0.1.15 - 2026-11-14 + +- 设置按停靠位置、边缘触发区、菜单导航、卡片弹窗、材质与颜色、展开与收起分组,增加快速跳转与尺寸恢复自动按钮;入口管理和备份帮助同步调整。 +- 商店详情精简为快速使用、常用功能和运行要求,移除重复说明、开发测试记录和重复截图。 + +- 材质下拉框改为直接点击的纯色、云母、亚克力按钮,保存期间防止重复点击;原生材质之间切换立即恢复已有背景布局。 +- 关闭钉住功能时同时移除图钉占用的宽度或高度;手动固定导航尺寸时,分类区域接管按钮位置。 +- 新增导航条宽度、高度和卡片弹窗宽度、高度四项独立设置,0 为自动;固定弹窗按可用宽度减少列数,超出高度时滚动,所有尺寸限制在屏幕可用区域内。 +- 四项尺寸支持备份、升级恢复和外观重置;旧配置默认自动,保留原有分类与入口。 + ## 0.1.14 - 2026-11-13 - “图标大小”改为50%~150%的“卡片缩放”滑块,默认100%,同步缩放入口卡片宽高、图片/图标、间距和文字,顶部分类导航大小保持不变。 diff --git a/plugins/ztools-dock/MARKET.md b/plugins/ztools-dock/MARKET.md index 1f66d0f49..809a2522c 100644 --- a/plugins/ztools-dock/MARKET.md +++ b/plugins/ztools-dock/MARKET.md @@ -1,77 +1,32 @@ # 程序坞 -Windows 屏幕边缘的分类启动器。悬停边缘触发条展开程序坞,按分类打开应用、文件、文件夹、网址和已安装的 ZTools 插件。 +把常用应用、文件、文件夹、网址和 ZTools 插件放到屏幕边缘。鼠标移过去展开,点击即可打开。 -## 使用 +![程序坞](screenshots/dock-adaptive-width.png) -- “卡片缩放”范围50%~150%,默认100%,调整整张入口卡片、图标和间距;弹窗同步自适应,空间不足时减少列数,导航保持原大小。旧高度和图标大小作为基准保留。 +## 开始使用 -- “外观与行为 → 启用钉住功能”控制导航栏图钉,默认开启。关闭后隐藏按钮并取消已有钉住,恢复整体自动收起。 -- “每行最多列数”为上限:入口不足时按实际数量自动收窄弹窗,卡片大小保持不变;搜索结果也同步自适应。 +1. 安装后,在 ZTools 输入 **程序坞设置**,添加分类和入口。也可以把应用、快捷方式、文件或文件夹拖进设置页。 +2. 复制网址或本地文件后唤起 ZTools,选择 **添加到程序坞**。没有自动匹配时,粘贴到搜索框或直接输入这条指令。 +3. 悬停屏幕边缘的触发条展开;也可以搜索 **程序坞** 或 **dock**。右键程序坞打开设置。 -- “外观与行为”中的“显示菜单栏名称”“显示入口名称”可以分别关闭分类导航和入口卡片文字,默认都开启。关闭后悬停提示、搜索和管理页面名称仍保留。 +在插件管理中关闭本插件的“退出即结束”,让程序坞留在后台。需要随 ZTools 启动时,可开启宿主提供的“跟随启动”。 -- 在“外观与行为”选择上/下/左/右停靠;支持比例定位(0% 起点、50% 居中、100% 终点),也可选择距左/右边的距离,侧边停靠对应距上/下边。距离为逻辑像素,超出工作区时自动限制。默认顶部居中,侧边分类纵向滚动。 +## 按习惯调整 -- 在 ZTools 搜索“程序坞设置”管理分类和入口,搜索“程序坞”或“dock”展开面板。 -- 分类栏右侧图钉可钉住导航条。鼠标离开后卡片区收起,移回导航条再次展开;取消钉住后整个程序坞自动收起。 -- 右键顶部细条、导航栏或卡片面板打开设置。分类和入口可拖拽排序,空分类在设置中管理。 -- 复制网址、应用、文件或文件夹后唤起 ZTools,选择“添加到程序坞”;也可粘贴到搜索框。宿主关闭复制内容自动匹配时,可手动粘贴或输入“添加到程序坞”。单项打开预填表单,批量添加先确认。 -- 默认分类:网址 → 网址;应用 → 常用工具;文件 → 文件处理;文件夹 → 文件夹。可在表单中修改分类。 -- 网址编辑页“获取图标”读取网站 favicon,并随配置保存;失败时可选择本地 PNG/JPG/WebP 图片。 -- “外观与行为”可选择经典细条、虫仔、蜗牛触发主题,以及50%~150%的入口卡片缩放。卡通主题为静态矢量图案,触发区高度为 32 px。 -- 触发图案底边始终朝向所选屏幕边缘。“底部距屏幕边缘”默认为0,正数向内、负数藏到边缘外,至少保留1px供悬停唤出。可上传2MB以内PNG,自动裁掉透明留白、按比例显示,图案高度最多160px;图片随JSON备份保存。 -- 面板支持纯色、原生云母、原生亚克力。原生材质需要 Windows 11 22H2+;不支持的系统使用纯色。背景不透明度只调整表面着色,不改变文字和图标的不透明度,系统模糊强度由 Windows 控制。 -- 搜索默认关闭,可在“外观与行为”开启。开启后 Ctrl+F 聚焦搜索,Enter 打开首项。 -- “外观与行为”页底部的重置仅恢复该页设置,保留分类、入口、图标、顺序和启用/暂停状态。 -- 备份页可导出、导入 JSON 配置。退出 ZTools 会同时结束程序坞。 +- **整理入口**:分类和入口可拖动排序,空分类自动隐藏。插件与分类选择支持图标,长列表可搜索。网址支持获取网站图标,也可选择本地图片。 +- **停靠位置**:上、下、左、右任选,按比例或距离定位。触发区可用细条、虫仔、蜗牛,或上传 PNG(不超过 2 MB)。 +- **尺寸与外观**:菜单条、卡片弹窗分别设置宽高;点击“自动”恢复内容适配。卡片支持 50%~150% 整体缩放,菜单名称和入口名称可分别隐藏。 +- **卡片材质**:经典纯色、冰蓝厚玻璃、柔光磨砂、液态玻璃、清透描边、虹彩玻璃,作用于每个菜单和入口,强度支持 0~100%。 +- **钉住与搜索**:图钉只固定菜单条,卡片仍随鼠标离开收起。图钉和搜索框都可在设置中开关,搜索默认关闭。 +- **备份**:导出、导入 JSON,保存分类、入口、图片和外观。重置外观不会删除分类和入口;换电脑后,本地路径可能需要重新选择。 -## 界面 +![分组设置](screenshots/settings-overview.png) -![50%卡片](screenshots/dock-card-scale-50.png) +## 运行要求 -![150%卡片](screenshots/dock-card-scale-150.png) +仅支持 Windows,依赖 ZTools 运行。可在一个选定显示屏的工作区四边停靠,副屏断开后回到主屏。 -![钉住功能开关](screenshots/pin-setting.png) +菜单与入口的玻璃样式使用高光、渐变和内阴影呈现。导航条和弹窗支持上传背景图片(PNG、JPG、WebP,最大5MB),可更换、移除并调整不透明度;图片随配置备份保存。 -![两入口自适应弹窗](screenshots/dock-adaptive-width.png) - -![悬浮分类栏和入口卡片](screenshots/dock.png) - -上图为隔离配置中的示例入口,展示自定义分类、图标与卡片布局,不表示内置截图、录屏等工具。 - -![重置外观与行为](screenshots/appearance.png) - -![PNG和边缘距离设置](screenshots/trigger-art-settings.png) - -![卡片整体缩放设置](screenshots/card-scale-settings.png) - -![停靠方向和位置设置](screenshots/position-settings.png) - -![左侧停靠](screenshots/dock-position-left.png) - -![名称显示设置](screenshots/name-visibility-settings.png) - -![仅显示图标](screenshots/names-hidden-top.png) - -## 范围 - -仅支持 Windows,在一个选定显示屏的工作区四边停靠。副屏断开后回退主屏。依赖 ZTools 后台运行,可按宿主提供的“退出即结束”“跟随启动”选项设置。 - -不包含全屏自动避让、多屏同时停靠、应用参数或自定义脚本。管理员窗口、UAC 安全桌面及独占全屏场景未保证兼容。插件跳转使用唯一插件标题和指令,同名插件无法区分。 - -## 构建与验证 - -```sh -npm ci -npm test -npm run build -``` - -正式安装目录为 `dist/`。源码 manifest 位于 `public/plugin.json`。`npm run pack` 可生成根布局的安装 ZIP,并排除旧哈希资源和 Vite 内部清单。 - -0.1.14已通过43项单元、46项生产ZIP隔离宿主检查。另1项最终桌面合成像素检查因Windows锁屏暂不可执行,没有计为通过;原生Mica/Acrylic属性、四向背景窗组件边界和生命周期检查通过。5项0.1.13→0.1.14升级/恢复检查通过。宿主验证环境为ZTools3.3.0-beta.2安装版app.asar + 独立Electron41.4.0,不能等同日常EXE完整人工验收。文件粘贴匹配及原生选择框使用受控适配器,本地PNG解码、文件读写和程序启动执行真实API。 - -宿主回归需设置 `ZTOOLS_EXECUTABLE`,另用 `ZTOOLS_APP` 指向 app.asar(若适用),执行 `npm run test:host`。测试使用独占临时 profile,不修改日常用户配置。 - -MIT 许可。Vue 与 Lucide 的许可随构建产物提供。 +暂不支持全屏自动避让、多屏同时停靠、启动参数和自定义脚本;管理员窗口、UAC 安全桌面及独占全屏场景未保证兼容。添加插件入口时,从已安装插件中选择名称和指令,自动带入图标。首次使用需勾选两项读取权限并在 ZTools 确认;“备份与帮助 → 插件授权”可管理读取和宿主授权。同名插件暂无法区分。 diff --git a/plugins/ztools-dock/README.md b/plugins/ztools-dock/README.md index 1f66d0f49..809a2522c 100644 --- a/plugins/ztools-dock/README.md +++ b/plugins/ztools-dock/README.md @@ -1,77 +1,32 @@ # 程序坞 -Windows 屏幕边缘的分类启动器。悬停边缘触发条展开程序坞,按分类打开应用、文件、文件夹、网址和已安装的 ZTools 插件。 +把常用应用、文件、文件夹、网址和 ZTools 插件放到屏幕边缘。鼠标移过去展开,点击即可打开。 -## 使用 +![程序坞](screenshots/dock-adaptive-width.png) -- “卡片缩放”范围50%~150%,默认100%,调整整张入口卡片、图标和间距;弹窗同步自适应,空间不足时减少列数,导航保持原大小。旧高度和图标大小作为基准保留。 +## 开始使用 -- “外观与行为 → 启用钉住功能”控制导航栏图钉,默认开启。关闭后隐藏按钮并取消已有钉住,恢复整体自动收起。 -- “每行最多列数”为上限:入口不足时按实际数量自动收窄弹窗,卡片大小保持不变;搜索结果也同步自适应。 +1. 安装后,在 ZTools 输入 **程序坞设置**,添加分类和入口。也可以把应用、快捷方式、文件或文件夹拖进设置页。 +2. 复制网址或本地文件后唤起 ZTools,选择 **添加到程序坞**。没有自动匹配时,粘贴到搜索框或直接输入这条指令。 +3. 悬停屏幕边缘的触发条展开;也可以搜索 **程序坞** 或 **dock**。右键程序坞打开设置。 -- “外观与行为”中的“显示菜单栏名称”“显示入口名称”可以分别关闭分类导航和入口卡片文字,默认都开启。关闭后悬停提示、搜索和管理页面名称仍保留。 +在插件管理中关闭本插件的“退出即结束”,让程序坞留在后台。需要随 ZTools 启动时,可开启宿主提供的“跟随启动”。 -- 在“外观与行为”选择上/下/左/右停靠;支持比例定位(0% 起点、50% 居中、100% 终点),也可选择距左/右边的距离,侧边停靠对应距上/下边。距离为逻辑像素,超出工作区时自动限制。默认顶部居中,侧边分类纵向滚动。 +## 按习惯调整 -- 在 ZTools 搜索“程序坞设置”管理分类和入口,搜索“程序坞”或“dock”展开面板。 -- 分类栏右侧图钉可钉住导航条。鼠标离开后卡片区收起,移回导航条再次展开;取消钉住后整个程序坞自动收起。 -- 右键顶部细条、导航栏或卡片面板打开设置。分类和入口可拖拽排序,空分类在设置中管理。 -- 复制网址、应用、文件或文件夹后唤起 ZTools,选择“添加到程序坞”;也可粘贴到搜索框。宿主关闭复制内容自动匹配时,可手动粘贴或输入“添加到程序坞”。单项打开预填表单,批量添加先确认。 -- 默认分类:网址 → 网址;应用 → 常用工具;文件 → 文件处理;文件夹 → 文件夹。可在表单中修改分类。 -- 网址编辑页“获取图标”读取网站 favicon,并随配置保存;失败时可选择本地 PNG/JPG/WebP 图片。 -- “外观与行为”可选择经典细条、虫仔、蜗牛触发主题,以及50%~150%的入口卡片缩放。卡通主题为静态矢量图案,触发区高度为 32 px。 -- 触发图案底边始终朝向所选屏幕边缘。“底部距屏幕边缘”默认为0,正数向内、负数藏到边缘外,至少保留1px供悬停唤出。可上传2MB以内PNG,自动裁掉透明留白、按比例显示,图案高度最多160px;图片随JSON备份保存。 -- 面板支持纯色、原生云母、原生亚克力。原生材质需要 Windows 11 22H2+;不支持的系统使用纯色。背景不透明度只调整表面着色,不改变文字和图标的不透明度,系统模糊强度由 Windows 控制。 -- 搜索默认关闭,可在“外观与行为”开启。开启后 Ctrl+F 聚焦搜索,Enter 打开首项。 -- “外观与行为”页底部的重置仅恢复该页设置,保留分类、入口、图标、顺序和启用/暂停状态。 -- 备份页可导出、导入 JSON 配置。退出 ZTools 会同时结束程序坞。 +- **整理入口**:分类和入口可拖动排序,空分类自动隐藏。插件与分类选择支持图标,长列表可搜索。网址支持获取网站图标,也可选择本地图片。 +- **停靠位置**:上、下、左、右任选,按比例或距离定位。触发区可用细条、虫仔、蜗牛,或上传 PNG(不超过 2 MB)。 +- **尺寸与外观**:菜单条、卡片弹窗分别设置宽高;点击“自动”恢复内容适配。卡片支持 50%~150% 整体缩放,菜单名称和入口名称可分别隐藏。 +- **卡片材质**:经典纯色、冰蓝厚玻璃、柔光磨砂、液态玻璃、清透描边、虹彩玻璃,作用于每个菜单和入口,强度支持 0~100%。 +- **钉住与搜索**:图钉只固定菜单条,卡片仍随鼠标离开收起。图钉和搜索框都可在设置中开关,搜索默认关闭。 +- **备份**:导出、导入 JSON,保存分类、入口、图片和外观。重置外观不会删除分类和入口;换电脑后,本地路径可能需要重新选择。 -## 界面 +![分组设置](screenshots/settings-overview.png) -![50%卡片](screenshots/dock-card-scale-50.png) +## 运行要求 -![150%卡片](screenshots/dock-card-scale-150.png) +仅支持 Windows,依赖 ZTools 运行。可在一个选定显示屏的工作区四边停靠,副屏断开后回到主屏。 -![钉住功能开关](screenshots/pin-setting.png) +菜单与入口的玻璃样式使用高光、渐变和内阴影呈现。导航条和弹窗支持上传背景图片(PNG、JPG、WebP,最大5MB),可更换、移除并调整不透明度;图片随配置备份保存。 -![两入口自适应弹窗](screenshots/dock-adaptive-width.png) - -![悬浮分类栏和入口卡片](screenshots/dock.png) - -上图为隔离配置中的示例入口,展示自定义分类、图标与卡片布局,不表示内置截图、录屏等工具。 - -![重置外观与行为](screenshots/appearance.png) - -![PNG和边缘距离设置](screenshots/trigger-art-settings.png) - -![卡片整体缩放设置](screenshots/card-scale-settings.png) - -![停靠方向和位置设置](screenshots/position-settings.png) - -![左侧停靠](screenshots/dock-position-left.png) - -![名称显示设置](screenshots/name-visibility-settings.png) - -![仅显示图标](screenshots/names-hidden-top.png) - -## 范围 - -仅支持 Windows,在一个选定显示屏的工作区四边停靠。副屏断开后回退主屏。依赖 ZTools 后台运行,可按宿主提供的“退出即结束”“跟随启动”选项设置。 - -不包含全屏自动避让、多屏同时停靠、应用参数或自定义脚本。管理员窗口、UAC 安全桌面及独占全屏场景未保证兼容。插件跳转使用唯一插件标题和指令,同名插件无法区分。 - -## 构建与验证 - -```sh -npm ci -npm test -npm run build -``` - -正式安装目录为 `dist/`。源码 manifest 位于 `public/plugin.json`。`npm run pack` 可生成根布局的安装 ZIP,并排除旧哈希资源和 Vite 内部清单。 - -0.1.14已通过43项单元、46项生产ZIP隔离宿主检查。另1项最终桌面合成像素检查因Windows锁屏暂不可执行,没有计为通过;原生Mica/Acrylic属性、四向背景窗组件边界和生命周期检查通过。5项0.1.13→0.1.14升级/恢复检查通过。宿主验证环境为ZTools3.3.0-beta.2安装版app.asar + 独立Electron41.4.0,不能等同日常EXE完整人工验收。文件粘贴匹配及原生选择框使用受控适配器,本地PNG解码、文件读写和程序启动执行真实API。 - -宿主回归需设置 `ZTOOLS_EXECUTABLE`,另用 `ZTOOLS_APP` 指向 app.asar(若适用),执行 `npm run test:host`。测试使用独占临时 profile,不修改日常用户配置。 - -MIT 许可。Vue 与 Lucide 的许可随构建产物提供。 +暂不支持全屏自动避让、多屏同时停靠、启动参数和自定义脚本;管理员窗口、UAC 安全桌面及独占全屏场景未保证兼容。添加插件入口时,从已安装插件中选择名称和指令,自动带入图标。首次使用需勾选两项读取权限并在 ZTools 确认;“备份与帮助 → 插件授权”可管理读取和宿主授权。同名插件暂无法区分。 diff --git a/plugins/ztools-dock/package-lock.json b/plugins/ztools-dock/package-lock.json index 457693472..68bf27333 100644 --- a/plugins/ztools-dock/package-lock.json +++ b/plugins/ztools-dock/package-lock.json @@ -1,12 +1,12 @@ { "name": "ztools-dock", - "version": "0.1.14", + "version": "0.1.21", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ztools-dock", - "version": "0.1.14", + "version": "0.1.21", "license": "MIT", "dependencies": { "lucide-vue-next": "0.468.0", diff --git a/plugins/ztools-dock/package.json b/plugins/ztools-dock/package.json index 6063e428e..b942fde09 100644 --- a/plugins/ztools-dock/package.json +++ b/plugins/ztools-dock/package.json @@ -1,6 +1,6 @@ { "name": "ztools-dock", - "version": "0.1.14", + "version": "0.1.21", "private": true, "description": "程序坞 · Windows 桌面分类启动器", "type": "module", @@ -12,7 +12,8 @@ "test:host": "node scripts/test-host.mjs", "bench:host": "node scripts/benchmark-host.mjs", "pack": "npm run build && node scripts/package.mjs", - "market:prepare": "node scripts/prepare-market.mjs" + "market:prepare": "node scripts/prepare-market.mjs", + "test:smoke": "node scripts/test-smoke.mjs" }, "dependencies": { "lucide-vue-next": "0.468.0", diff --git a/plugins/ztools-dock/public/plugin.json b/plugins/ztools-dock/public/plugin.json index d46d172bd..d62a66fc9 100644 --- a/plugins/ztools-dock/public/plugin.json +++ b/plugins/ztools-dock/public/plugin.json @@ -2,7 +2,7 @@ "name": "ztools-dock", "title": "程序坞", "description": "屏幕边缘的分类启动器,快速打开应用、文件夹、网址和 ZTools 插件", - "version": "0.1.14", + "version": "0.1.21", "platform": [ "win32" ], diff --git a/plugins/ztools-dock/public/preload.cjs b/plugins/ztools-dock/public/preload.cjs index eb87ebf00..8167b8297 100644 --- a/plugins/ztools-dock/public/preload.cjs +++ b/plugins/ztools-dock/public/preload.cjs @@ -1,6 +1,7 @@ 'use strict'; const { ipcRenderer, clipboard } = require('electron'); const { prepareAddition } = require('./runtime/addition.cjs'); +const { pluginCatalog, requestCatalog, pluginIcon, catalogPermissions, stopCatalog } = require('./runtime/plugin-catalog.cjs'); const { FILE_ACTIONS, fileAction } = require('./runtime/file-actions.cjs'); const { createController } = require('./runtime/controller.cjs'); const { mergeState } = require('./runtime/state.cjs'); @@ -16,6 +17,16 @@ async function dispatch(op, payload) { switch (op) { case 'snapshot': return controller.snapshot(); case 'take-addition': return controller.takeAddition(); + case 'plugin-catalog': return pluginCatalog(api); + case 'plugin-authorize': return requestCatalog(api, payload); + case 'plugin-permissions': return catalogPermissions(api); + case 'plugin-stop-reading': return stopCatalog(api); + case 'plugin-permissions-settings': { + if(api.redirect(['设置','通用设置'])===false)throw new Error('无法打开 ZTools 设置,请在 ZTools 搜索“通用设置”'); + controller.windows().find(win=>controller.isSettingsSender(win.webContents.id))?.hide(); + await api.showMainWindow();return true; + } + case 'plugin-icon': return pluginIcon(api, payload); case 'panel-layout': return controller.panelLayout(payload); case 'save': return controller.save(payload); case 'expand': return controller.expand(); @@ -48,7 +59,7 @@ function initialize() { if (!window.ztools) { setTimeout(initialize, 30); return; } controller = createController(window.ztools, { onChange: emit }); const childOps = new Set(['snapshot', 'expand', 'collapse', 'pin', 'focus', 'hover', 'select', 'run', 'settings']); - const editorOps = new Set(['save', 'pause', 'test', 'reset', 'take-addition']); + const editorOps = new Set(['save', 'pause', 'test', 'reset', 'take-addition', 'plugin-catalog', 'plugin-authorize', 'plugin-icon', 'plugin-permissions', 'plugin-stop-reading', 'plugin-permissions-settings']); ipcRenderer.on('dock:request', async (event, request) => { if (!request) return; const child = controller.windows().find(w => w.webContents.id === request.sender && event.senderId === request.sender); diff --git a/plugins/ztools-dock/public/runtime/background-image.cjs b/plugins/ztools-dock/public/runtime/background-image.cjs new file mode 100644 index 000000000..87c5608fa --- /dev/null +++ b/plugins/ztools-dock/public/runtime/background-image.cjs @@ -0,0 +1,28 @@ +'use strict'; +const fs=require('node:fs'),path=require('node:path'); +function normalizeBackground(filename) { + const stat=fs.statSync(filename); + if(!stat.isFile()||stat.size>5*1024*1024||!['.png','.jpg','.jpeg','.webp'].includes(path.extname(filename).toLowerCase()))throw new Error('请选择5MB以内的PNG、JPG或WebP图片'); + const {nativeImage}=require('electron'); + let image=nativeImage.createFromBuffer(fs.readFileSync(filename)); + if(image.isEmpty())throw new Error('背景图片无法解码'); + const size=image.getSize(); + if(size.width>8192||size.height>8192)throw new Error('图片尺寸不能超过8192px'); + const ratio=Math.min(1,1600/Math.max(size.width,size.height)); + if(ratio<1)image=image.resize({width:Math.max(1,Math.round(size.width*ratio)),height:Math.max(1,Math.round(size.height*ratio)),quality:'best'}); + const pixels=image.toBitmap();let visible=false; + for(let i=3;i1024*1024){const s=image.getSize();if(Math.max(s.width,s.height)<256)throw new Error('背景图片过大,请选择更小的图片');image=image.resize({width:Math.max(1,Math.round(s.width*.75)),height:Math.max(1,Math.round(s.height*.75)),quality:'best'});png=image.toPNG();} + return `data:image/png;base64,${png.toString('base64')}`; +} +function validateBackgroundImage(settings){ + if(!settings.backgroundImage)return; + const image=require('electron').nativeImage.createFromDataURL(settings.backgroundImage); + if(image.isEmpty())throw new Error('背景图片无法解码'); + const pixels=image.toBitmap(); + for(let i=3;i materialsSupported ? config.settings.material : 'solid'; @@ -22,7 +22,7 @@ function createController(api, options = {}) { let addition = null, additionId = ''; let monitorSignature = '', displayCache = [], primaryDisplay, displayInfo = [], maintenanceTicks = 0; let dark = Boolean(api.isDarkColors()); - try { const stored = api.dbStorage.getItem('dock-config-v1'); if (stored) { const valid = validateConfig(stored); validateTriggerImage(valid.settings); config = valid; } } + try { const stored = api.dbStorage.getItem('dock-config-v1'); if (stored) { const valid = validateConfig(stored); validateTriggerImage(valid.settings); validateBackgroundImage(valid.settings); config = valid; } } catch (e) { error = `配置读取失败:${e.message}。可从设置导入备份或恢复默认。`; config.settings.enabled = false; } function live(win) { return win && !win.isDestroyed(); } @@ -109,12 +109,21 @@ function createController(api, options = {}) { trigger.showInactive(); maintainTopmost(); } const material = effectiveMaterial(); + const previousMaterial = panelMaterial; panelMaterial = material; if (!live(panel)) { panel = api.createBrowserWindow('index.html?surface=panel', { ...common, ...bounds.panel, transparent: true, backgroundColor: '#00000000', hasShadow: false }); resetPanelShape(); } - if (materialSurfaces.setMaterial(material,common)) { panelRegions=[];lastPanelShape=''; } + if (materialSurfaces.setMaterial(material,common)) { + // Native-to-native switches have identical geometry. Restore backgrounds now, + // even when the renderer is hidden/throttled and cannot report a new layout yet. + if (previousMaterial !== 'solid' && material !== 'solid') { + materialSurfaces.layout(panelRegions, bounds.panel, expanded, trayVisible); + maintainTopmost(); + } else panelRegions=[]; + lastPanelShape=''; + } if (topmostTimer === null) topmostTimer = timers.setInterval(() => { try { maintainTopmost(); @@ -129,6 +138,7 @@ function createController(api, options = {}) { function save(next) { const valid = validateConfig(next); if (valid.settings.triggerImage !== config.settings.triggerImage) validateTriggerImage(valid.settings); + if (valid.settings.backgroundImage !== config.settings.backgroundImage) validateBackgroundImage(valid.settings); persist(valid); config = valid; error = ''; if (config.settings.enabled) ensureWindows(); else stopWindows(); @@ -172,8 +182,8 @@ function createController(api, options = {}) { } if (!config.settings.enabled || disposed) start(); else ensureWindows(); expanded = true; trayVisible = true; - panel.showInactive(); materialSurfaces.layout(panelRegions,bounds.panel,true,true); + panel.showInactive(); maintainTopmost(); startCursorPolling(); notify('runtime'); return true; diff --git a/plugins/ztools-dock/public/runtime/core.cjs b/plugins/ztools-dock/public/runtime/core.cjs index f78a4607b..f6815f282 100644 --- a/plugins/ztools-dock/public/runtime/core.cjs +++ b/plugins/ztools-dock/public/runtime/core.cjs @@ -16,21 +16,26 @@ function defaults() { ['home', '用户目录', 'House'], ['desktop', '桌面', 'Monitor'], ['downloads', '下载', 'Download'], ['documents', '文档', 'FileText'], ['pictures', '图片', 'Image'], ['music', '音乐', 'Music'], ['videos', '视频', 'Video'] ].map(([target, name, icon], i) => ({ id: `system-${target}`, categoryId: 'folders', name, type: 'system', target, icon, color: ['#087fe7', '#0c9c83', '#08a7cd'][i % 3] })); - return { version: 1, settings: { enabled: true, pinEnabled: true, searchEnabled: false, showCategoryNames: true, showEntryNames: true, dockEdge: 'top', positionMode: 'ratio', positionRatio: 50, positionDistance: 0, positionAnchor: 'start', triggerTheme: 'bar', triggerImage: '', triggerEdgeDistance: 0, iconSize: 'medium', material: 'solid', panelOpacity: 1, displayId: 'primary', openDelay: 180, closeDelay: 450, triggerWidth: 80, triggerHeight: 5, triggerOpacity: 0.75, accent: '#087fe7', columns: 3, cardSize: 100, cardScale: 100, theme: 'system', lastCategoryId: 'folders' }, categories, entries }; + return { version: 1, settings: { enabled: true, dockWidth: 0, dockHeight: 0, popupWidth: 0, popupHeight: 0, pinEnabled: true, searchEnabled: false, showCategoryNames: true, showEntryNames: true, dockEdge: 'top', positionMode: 'ratio', positionRatio: 50, positionDistance: 0, positionAnchor: 'start', triggerTheme: 'bar', triggerImage: '', triggerEdgeDistance: 0, iconSize: 'medium', backgroundImage: '', tileMaterial: 'plain', tileStrength: 70, material: 'solid', panelOpacity: 1, displayId: 'primary', openDelay: 180, closeDelay: 450, triggerWidth: 80, triggerHeight: 5, triggerOpacity: 0.75, accent: '#087fe7', columns: 3, cardSize: 100, cardScale: 100, theme: 'system', lastCategoryId: 'folders' }, categories, entries }; } /** Validate an entire import before any state is mutated; retain only known fields. */ function validateConfig(input) { if (!input || input.version !== 1) throw new Error('不支持此配置版本,请使用程序坞导出的 JSON 文件'); - const s = input.settings && { ...input.settings, cardScale: input.settings.cardScale === undefined ? 100 : input.settings.cardScale, pinEnabled: input.settings.pinEnabled === undefined ? true : input.settings.pinEnabled, searchEnabled: input.settings.searchEnabled ?? false, showCategoryNames: input.settings.showCategoryNames === undefined ? true : input.settings.showCategoryNames, showEntryNames: input.settings.showEntryNames === undefined ? true : input.settings.showEntryNames, triggerTheme: input.settings.triggerTheme ?? 'bar', triggerImage: input.settings.triggerImage ?? '', triggerEdgeDistance: input.settings.triggerEdgeDistance ?? 0, iconSize: input.settings.iconSize ?? 'medium', material: input.settings.material ?? 'solid', panelOpacity: input.settings.panelOpacity ?? 1, dockEdge: input.settings.dockEdge ?? 'top', positionMode: input.settings.positionMode ?? 'ratio', positionRatio: input.settings.positionRatio ?? 50, positionDistance: input.settings.positionDistance ?? 0, positionAnchor: input.settings.positionAnchor ?? 'start' }; + const s = input.settings && { ...input.settings, popupWidth: input.settings.popupWidth === undefined ? 0 : input.settings.popupWidth, popupHeight: input.settings.popupHeight === undefined ? 0 : input.settings.popupHeight, dockWidth: input.settings.dockWidth === undefined ? 0 : input.settings.dockWidth, dockHeight: input.settings.dockHeight === undefined ? 0 : input.settings.dockHeight, cardScale: input.settings.cardScale === undefined ? 100 : input.settings.cardScale, pinEnabled: input.settings.pinEnabled === undefined ? true : input.settings.pinEnabled, searchEnabled: input.settings.searchEnabled ?? false, showCategoryNames: input.settings.showCategoryNames === undefined ? true : input.settings.showCategoryNames, showEntryNames: input.settings.showEntryNames === undefined ? true : input.settings.showEntryNames, triggerTheme: input.settings.triggerTheme ?? 'bar', triggerImage: input.settings.triggerImage ?? '', triggerEdgeDistance: input.settings.triggerEdgeDistance ?? 0, iconSize: input.settings.iconSize ?? 'medium', backgroundImage: input.settings.backgroundImage === undefined ? '' : input.settings.backgroundImage, tileMaterial: input.settings.tileMaterial === undefined ? 'plain' : input.settings.tileMaterial, tileStrength: input.settings.tileStrength === undefined ? 70 : input.settings.tileStrength, material: input.settings.material ?? 'solid', panelOpacity: input.settings.panelOpacity ?? 1, dockEdge: input.settings.dockEdge ?? 'top', positionMode: input.settings.positionMode ?? 'ratio', positionRatio: input.settings.positionRatio ?? 50, positionDistance: input.settings.positionDistance ?? 0, positionAnchor: input.settings.positionAnchor ?? 'start' }; if (!s || typeof s.enabled !== 'boolean' || !cleanText(s.displayId, 80)) throw new Error('基本设置不完整'); if (!['bar', 'worm', 'snail', 'custom'].includes(s.triggerTheme) || !['small', 'medium', 'large'].includes(s.iconSize) || !['solid', 'mica', 'acrylic'].includes(s.material)) throw new Error('外观主题或材质无效'); if (!Number.isInteger(s.triggerEdgeDistance) || s.triggerEdgeDistance < -400 || s.triggerEdgeDistance > 400) throw new Error('底部距离超出允许范围'); if (typeof s.triggerImage !== 'string' || (s.triggerImage && !pngSize(s.triggerImage)) || (s.triggerTheme === 'custom' && !s.triggerImage)) throw new Error('请上传有效的PNG触发图案'); + if (typeof s.backgroundImage !== 'string' || (s.backgroundImage && !pngSize(s.backgroundImage,1600))) throw new Error('背景图片无效'); + if (!['plain','ice','frosted','liquid','clear','iridescent'].includes(s.tileMaterial) || !Number.isInteger(s.tileStrength) || s.tileStrength < 0 || s.tileStrength > 100) throw new Error('卡片材质或强度无效'); if (typeof s.panelOpacity !== 'number' || !Number.isFinite(s.panelOpacity) || s.panelOpacity < 0.1 || s.panelOpacity > 1) throw new Error('面板不透明度超出允许范围'); if (!['top','bottom','left','right'].includes(s.dockEdge) || !['ratio','distance'].includes(s.positionMode) || !['start','end'].includes(s.positionAnchor)) throw new Error('停靠位置设置无效'); if (!Number.isFinite(s.positionRatio) || s.positionRatio < 0 || s.positionRatio > 100 || !Number.isInteger(s.positionDistance) || s.positionDistance < 0 || s.positionDistance > 20000) throw new Error('位置距离或比例超出允许范围'); if (typeof s.showCategoryNames !== 'boolean' || typeof s.showEntryNames !== 'boolean') throw new Error('名称显示设置无效'); + for (const [key, minimum, maximum] of [['dockWidth', 80, 2000], ['dockHeight', 40, 1200], ['popupWidth', 160, 2000], ['popupHeight', 100, 1200]]) { + if (!Number.isInteger(s[key]) || (s[key] !== 0 && (s[key] < minimum || s[key] > maximum))) throw new Error('尺寸无效:请输入控件提示范围内的整数,0 为自动'); + } if (!Number.isInteger(s.cardScale) || s.cardScale < 50 || s.cardScale > 150) throw new Error('卡片缩放应在50%~150%之间'); if (typeof s.pinEnabled !== 'boolean') throw new Error('钉住功能设置无效'); if (typeof s.searchEnabled !== 'boolean') throw new Error('搜索设置无效'); @@ -95,12 +100,12 @@ function resolveEntry(entry, paths) { } /** Normalized PNG data only; filesystem decoder verifies selected images before saving. */ -function pngSize(value) { +function pngSize(value, maxDimension = 512) { if (typeof value !== 'string' || value.length > 1400000 || !/^data:image\/png;base64,[a-zA-Z0-9+/=]+$/.test(value)) return null; const bytes=Buffer.from(value.slice(22),'base64'); if(bytes.length<33 || bytes.subarray(0,8).toString('hex')!=='89504e470d0a1a0a' || bytes.toString('ascii',12,16)!=='IHDR')return null; const width=bytes.readUInt32BE(16),height=bytes.readUInt32BE(20); - return width>0&&height>0&&width<=512&&height<=512?{width,height}:null; + return width>0&&height>0&&width<=maxDimension&&height<=maxDimension?{width,height}:null; } /** Lay out windows in Electron DIP coordinates, including negative monitor origins. */ @@ -128,11 +133,12 @@ function geometry(settings, displays, primary, categoryCount = 7) { // otherwise push a thin right/bottom trigger onto a neighbour with a different DPI. const backingWidth = Math.min(area.width, Math.max(128, trigger.width)), backingHeight = Math.min(area.height, Math.max(64, trigger.height)); const triggerWindow = { x: Math.round(clamp(trigger.x - (backingWidth - trigger.width) / 2, area.x, area.x + area.width - backingWidth)), y: Math.round(clamp(trigger.y - (backingHeight - trigger.height) / 2, area.y, area.y + area.height - backingHeight)), width: backingWidth, height: backingHeight }; - const trayWidth = Math.ceil((settings.columns * 128 + 6) * (settings.cardScale ?? 100) / 100 + 2) + 6; - const barWidth = Math.max(160, categoryCount * 100 + 32); + const ratio = (settings.cardScale ?? 100) / 100; + const trayWidth = Math.ceil(settings.popupWidth ? Math.max(settings.popupWidth, 134 * ratio + 2) : (settings.columns * 128 + 6) * ratio + 2) + 6; + const barWidth = settings.dockWidth || (vertical ? 100 : categoryCount ? categoryCount * 100 + 6 + (settings.pinEnabled === false ? 0 : 26) : 160); const inward = edge==='left'?area.x+area.width-trigger.x-trigger.width:edge==='right'?trigger.x-area.x:edge==='top'?area.y+area.height-trigger.y-trigger.height:trigger.y-area.y; - const width = vertical ? Math.min(100 + trayWidth + 32, Math.max(1, inward - 12)) : Math.min(Math.max(trayWidth, barWidth + Math.max(0, trayWidth - 100)) + 32, Math.max(1, area.width - 24)); - const height = Math.min(820, Math.max(1, vertical ? area.height - 24 : inward - 12)); + const width = vertical ? Math.min(barWidth + trayWidth + 32, Math.max(1, inward - 12)) : Math.min(Math.max(trayWidth, barWidth + Math.max(0, trayWidth - 100)) + 32, Math.max(1, area.width - 24)); + const height = Math.min(Math.max(820, (settings.dockHeight || 66) + (settings.popupHeight || 220) + 32), Math.max(1, vertical ? area.height - 24 : inward - 12)); const centre = { x: trigger.x + trigger.width / 2, y: trigger.y + trigger.height / 2 }; const panel = { x: vertical ? (edge === 'left' ? trigger.x + trigger.width : trigger.x - width) : Math.round(clamp(centre.x - width / 2, area.x, area.x + area.width - width)), diff --git a/plugins/ztools-dock/public/runtime/file-actions.cjs b/plugins/ztools-dock/public/runtime/file-actions.cjs index fc563a6ef..1c97c3f4f 100644 --- a/plugins/ztools-dock/public/runtime/file-actions.cjs +++ b/plugins/ztools-dock/public/runtime/file-actions.cjs @@ -3,7 +3,8 @@ const fs = require('node:fs'); const path = require('node:path'); const { validateConfig, MAX_CONFIG_BYTES } = require('./core.cjs'); const { websiteIcon } = require('./website-icon.cjs'); -const FILE_ACTIONS = new Set(['describe', 'pick', 'icon', 'import', 'export', 'website-icon', 'trigger-image']); +const {normalizeBackground,validateBackgroundImage}=require('./background-image.cjs'); +const FILE_ACTIONS = new Set(['describe', 'pick', 'icon', 'import', 'export', 'website-icon', 'trigger-image', 'background-image']); function validateTriggerImage(settings) { if (!settings.triggerImage) return; @@ -28,6 +29,10 @@ function describeFile(filename, api) { /** Dialogs belong to the visible settings window, including focus restoration. */ async function fileAction(op, payload, api, getConfig) { switch (op) { + case 'background-image': { + const selected=api.showOpenDialog({title:'上传背景图片',properties:['openFile'],filters:[{name:'背景图片',extensions:['png','jpg','jpeg','webp']}]}); + return selected?.[0]?normalizeBackground(selected[0]):null; + } case 'website-icon': return websiteIcon(payload); case 'describe': if (!Array.isArray(payload) || payload.length > 100) throw new Error('一次最多添加 100 个文件'); @@ -69,6 +74,7 @@ async function fileAction(op, payload, api, getConfig) { if (fs.statSync(selected[0]).size > MAX_CONFIG_BYTES) throw new Error('配置文件过大,最大支持 8 MB'); const config = validateConfig(JSON.parse(fs.readFileSync(selected[0], 'utf8').replace(/^\uFEFF/, ''))); validateTriggerImage(config.settings); + validateBackgroundImage(config.settings); return config; } case 'export': { @@ -79,4 +85,4 @@ async function fileAction(op, payload, api, getConfig) { default: throw new Error('不支持的文件操作'); } } -module.exports = { FILE_ACTIONS, fileAction, describeFile, validateTriggerImage }; +module.exports = { FILE_ACTIONS, fileAction, describeFile, validateTriggerImage, validateBackgroundImage }; diff --git a/plugins/ztools-dock/public/runtime/plugin-catalog.cjs b/plugins/ztools-dock/public/runtime/plugin-catalog.cjs new file mode 100644 index 000000000..3ce30210e --- /dev/null +++ b/plugins/ztools-dock/public/runtime/plugin-catalog.cjs @@ -0,0 +1,87 @@ +'use strict'; +const fs = require('node:fs/promises'); +const path = require('node:path'); +const {createHash}=require('node:crypto'); +const descriptors=new Map(); +const PERMISSIONS = ['internal:get-plugins', 'internal:get-disabled-plugins']; +const CONSENT_KEY = 'dock-plugin-consent-v1'; +function hasConsent(api) { return api.dbStorage?.getItem(CONSENT_KEY) === true; } +function setConsent(api, value) { + api.dbStorage.setItem(CONSENT_KEY, value); + if(api.dbStorage.getItem(CONSENT_KEY)!==value)throw new Error('授权选择未能保存'); +} +async function catalogPermissions(api) { + if(!api.getInternalApiPermissions)throw new Error('请升级 ZTools 后使用插件授权'); + const state=await api.getInternalApiPermissions(); + return { reading:hasConsent(api), fullAccess:!!state.fullAccess, permissions:PERMISSIONS.map(id=>({id,granted:!!state.fullAccess||!!state.granted?.includes(id),pending:!!state.pending?.includes(id)})) }; +} +function stopCatalog(api) { setConsent(api,false); descriptors.clear(); return true; } + +// Electron's isolated preload can reject Node's cross-realm fileURLToPath +// implementation. Decode the Windows file URL without crossing VM realms. +function windowsIconPath(value) { + const url = new URL(value); + if (url.protocol !== 'file:' || /%2f|%5c/i.test(url.pathname)) throw new Error('插件图标路径无效'); + const pathname = decodeURIComponent(url.pathname).replaceAll('/', '\\'); + if (url.hostname && url.hostname !== 'localhost') return `\\\\${url.hostname}${pathname}`; + if (!/^\\[a-z]:\\/i.test(pathname)) throw new Error('插件图标路径无效'); + return pathname.slice(1); +} + +async function permission(api) { + if (!api.getInternalApiPermissions || !api.internal?.getPlugins || !api.internal?.getDisabledPlugins) throw new Error('当前 ZTools 不支持插件选择,请升级宿主'); + if (!hasConsent(api)) return false; + const state = await api.getInternalApiPermissions(); + return state.fullAccess || PERMISSIONS.every(key => state.granted?.includes(key)); +} +function normalizePlugins(plugins, disabled = []) { + const rows = plugins.filter(p => p && typeof p.title === 'string' && p.title.trim() && typeof p.name === 'string' && p.name !== 'ztools-dock'); + const counts = new Map(); + rows.forEach(p => counts.set(p.title, (counts.get(p.title) || 0) + 1)); + return rows.map(p => ({ + id: p.name, title: p.title, + iconVersion: createHash('sha256').update(`${p.version || ''}:${p.path || ''}:${p.logo || ''}`).digest('hex').slice(0,16), + commands: [...new Set((p.features || []).flatMap(f => Array.isArray(f.cmds) ? f.cmds.filter(c => typeof c === 'string' && c.trim()) : []))], + unavailable: disabled.includes(p.path) || disabled.includes(p.name) ? '已停用' : counts.get(p.title) > 1 ? '同名插件无法区分' : '' + })).sort((a, b) => a.title.localeCompare(b.title, 'zh-CN')); +} +async function pluginCatalog(api) { + if (!await permission(api)) return { authorized: false, plugins: [] }; + const [plugins, disabled] = await Promise.all([api.internal.getPlugins(), api.internal.getDisabledPlugins()]); + descriptors.clear();plugins.forEach(p=>descriptors.set(p.name,p)); + return { authorized: true, plugins: normalizePlugins(plugins, disabled) }; +} +async function requestCatalog(api, accepted) { + if(!Array.isArray(accepted)||accepted.length!==PERMISSIONS.length||!PERMISSIONS.every(id=>accepted.includes(id)))throw new Error('请勾选两项读取权限'); + const current=await api.getInternalApiPermissions(); + if(current.fullAccess||PERMISSIONS.every(id=>current.granted?.includes(id))){setConsent(api,true);return true;} + if (await permission(api)) return true; + const result = await api.requestInternalApiPermissions(PERMISSIONS, '选择已安装插件及其指令,并读取所选插件的图标,用于添加程序坞入口。'); + if (!result?.success) throw new Error(result?.error || '无法申请插件列表权限'); + setConsent(api,true); + return result.status === 'granted'; +} +async function pluginIcon(api, id) { + if (typeof id !== 'string' || !await permission(api)) throw new Error('请先授权读取插件列表'); + let plugin=descriptors.get(id); + if(!plugin){const plugins=await api.internal.getPlugins();plugin=plugins.find(p=>p.name===id);if(plugin)descriptors.set(id,plugin);} + if (!plugin) throw new Error('插件已卸载,请刷新列表'); + const logo = plugin.logo; + if (typeof logo !== 'string') return null; + if (/^data:image\/(png|jpeg|webp|gif|svg\+xml|x-icon);base64,/.test(logo)) return logo.length <= 2800000 ? logo : null; + if (/^https?:\/\//.test(logo)) { + const { download } = require('./website-icon.cjs'); + const image = await download(logo, AbortSignal.timeout(8000), 2 * 1024 * 1024); + if (!/^image\/(png|jpeg|webp|gif|svg\+xml|x-icon|vnd.microsoft.icon)$/.test(image.mime)) return null; + return `data:${image.mime};base64,${image.bytes.toString('base64')}`; + } + if (!logo.startsWith('file:') || !plugin.path) return null; + const filename = await fs.realpath(windowsIconPath(logo)); + const root = await fs.realpath(plugin.path); + const relative = path.relative(root, filename); + if (relative.startsWith('..') || path.isAbsolute(relative)) return null; + const mime = { '.png': 'png', '.jpg': 'jpeg', '.jpeg': 'jpeg', '.webp': 'webp', '.gif': 'gif', '.svg': 'svg+xml', '.ico': 'x-icon' }[path.extname(filename).toLowerCase()]; + if (!mime || (await fs.stat(filename)).size > 2 * 1024 * 1024) return null; + return `data:image/${mime};base64,${(await fs.readFile(filename)).toString('base64')}`; +} +module.exports = { PERMISSIONS, CONSENT_KEY, catalogPermissions, stopCatalog, windowsIconPath, normalizePlugins, pluginCatalog, requestCatalog, pluginIcon }; diff --git a/plugins/ztools-dock/public/runtime/website-icon.cjs b/plugins/ztools-dock/public/runtime/website-icon.cjs index bce93e017..aacd964ef 100644 --- a/plugins/ztools-dock/public/runtime/website-icon.cjs +++ b/plugins/ztools-dock/public/runtime/website-icon.cjs @@ -44,4 +44,4 @@ async function websiteIcon(target) { throw new Error('未获取到网站图标,可重试或选择本地图片'); }finally {clearTimeout(timer);} } -module.exports={websiteIcon,iconLinks}; +module.exports={websiteIcon,iconLinks,download}; diff --git a/plugins/ztools-dock/screenshots/background-image-settings.png b/plugins/ztools-dock/screenshots/background-image-settings.png new file mode 100644 index 000000000..12458ec17 Binary files /dev/null and b/plugins/ztools-dock/screenshots/background-image-settings.png differ diff --git a/plugins/ztools-dock/screenshots/category-dropdown.png b/plugins/ztools-dock/screenshots/category-dropdown.png new file mode 100644 index 000000000..0e7f27b35 Binary files /dev/null and b/plugins/ztools-dock/screenshots/category-dropdown.png differ diff --git a/plugins/ztools-dock/screenshots/dock-background-image.png b/plugins/ztools-dock/screenshots/dock-background-image.png new file mode 100644 index 000000000..bcab86d6c Binary files /dev/null and b/plugins/ztools-dock/screenshots/dock-background-image.png differ diff --git a/plugins/ztools-dock/screenshots/dock-dimension-settings.png b/plugins/ztools-dock/screenshots/dock-dimension-settings.png new file mode 100644 index 000000000..9ebcce116 Binary files /dev/null and b/plugins/ztools-dock/screenshots/dock-dimension-settings.png differ diff --git a/plugins/ztools-dock/screenshots/dock-manual-dimensions.png b/plugins/ztools-dock/screenshots/dock-manual-dimensions.png new file mode 100644 index 000000000..adc53aaea Binary files /dev/null and b/plugins/ztools-dock/screenshots/dock-manual-dimensions.png differ diff --git a/plugins/ztools-dock/screenshots/plugin-icon-dropdown.png b/plugins/ztools-dock/screenshots/plugin-icon-dropdown.png new file mode 100644 index 000000000..4cd1178fc Binary files /dev/null and b/plugins/ztools-dock/screenshots/plugin-icon-dropdown.png differ diff --git a/plugins/ztools-dock/screenshots/plugin-permissions.png b/plugins/ztools-dock/screenshots/plugin-permissions.png new file mode 100644 index 000000000..4a9f35d2b Binary files /dev/null and b/plugins/ztools-dock/screenshots/plugin-permissions.png differ diff --git a/plugins/ztools-dock/screenshots/plugin-selector.png b/plugins/ztools-dock/screenshots/plugin-selector.png new file mode 100644 index 000000000..53050028a Binary files /dev/null and b/plugins/ztools-dock/screenshots/plugin-selector.png differ diff --git a/plugins/ztools-dock/screenshots/settings-backup.png b/plugins/ztools-dock/screenshots/settings-backup.png new file mode 100644 index 000000000..fe6dbd49a Binary files /dev/null and b/plugins/ztools-dock/screenshots/settings-backup.png differ diff --git a/plugins/ztools-dock/screenshots/settings-card-controls.png b/plugins/ztools-dock/screenshots/settings-card-controls.png new file mode 100644 index 000000000..58d39b172 Binary files /dev/null and b/plugins/ztools-dock/screenshots/settings-card-controls.png differ diff --git a/plugins/ztools-dock/screenshots/settings-entries.png b/plugins/ztools-dock/screenshots/settings-entries.png new file mode 100644 index 000000000..2ba3e1661 Binary files /dev/null and b/plugins/ztools-dock/screenshots/settings-entries.png differ diff --git a/plugins/ztools-dock/screenshots/settings-overview.png b/plugins/ztools-dock/screenshots/settings-overview.png new file mode 100644 index 000000000..1313e59d5 Binary files /dev/null and b/plugins/ztools-dock/screenshots/settings-overview.png differ diff --git a/plugins/ztools-dock/screenshots/tile-ice.png b/plugins/ztools-dock/screenshots/tile-ice.png new file mode 100644 index 000000000..3d69048fe Binary files /dev/null and b/plugins/ztools-dock/screenshots/tile-ice.png differ diff --git a/plugins/ztools-dock/screenshots/tile-iridescent-dark.png b/plugins/ztools-dock/screenshots/tile-iridescent-dark.png new file mode 100644 index 000000000..8f28d25de Binary files /dev/null and b/plugins/ztools-dock/screenshots/tile-iridescent-dark.png differ diff --git a/plugins/ztools-dock/scripts/check-appearance.mjs b/plugins/ztools-dock/scripts/check-appearance.mjs index 9d32ac0f4..663eb4a3d 100644 --- a/plugins/ztools-dock/scripts/check-appearance.mjs +++ b/plugins/ztools-dock/scripts/check-appearance.mjs @@ -28,8 +28,9 @@ export async function checkAppearance({app,evaluate,screenshot,native,check}) { await expect.poll(()=>evaluate('(()=>{const c=document.querySelector(".launch-card").getBoundingClientRect(),i=document.querySelector(".launch-icon").getBoundingClientRect(),n=document.querySelector(".launch-name").getBoundingClientRect();return i.top>=c.top && n.bottom<=c.bottom})()','panel')).toBe(true); check('real 50/100/150 percent slider scales whole card width/height and tray together; text remains inside minimum-height cards'); if((await evaluate('window.dock.call("snapshot")')).materialsSupported) { - for(const [material,code] of [['mica',2],['acrylic',3]]) { - await evaluate(`(()=>{const s=document.querySelector('[aria-label="面板材质"]');s.value='${material}';s.dispatchEvent(new Event('change',{bubbles:true}))})()`); + for(const [material,code] of [['mica',2],['acrylic',3],['mica',2],['acrylic',3]]) { + const settingsPage=app.windows().find(page=>page.url().includes('surface=settings')); + await settingsPage.locator(`[data-material="${material}"]`).click(); await expect.poll(()=>evaluate('window.dock.call("snapshot").then(s=>s.material)')).toBe(material); await expect.poll(()=>evaluate('Boolean(document.querySelector(".dock-panel.material-native"))','panel').catch(()=>false)).toBe(true); await evaluate('window.dock.call("expand")'); @@ -48,7 +49,7 @@ export async function checkAppearance({app,evaluate,screenshot,native,check}) { await expect.poll(()=>evaluate('window.dock.call("snapshot").then(s=>s.config.settings.panelOpacity)')).toBe(0.35); const opacity=await evaluate('(()=>{const p=getComputedStyle(document.querySelector(".dock-panel")),t=getComputedStyle(document.querySelector(".launch-name"));return {opacity:p.opacity,text:t.opacity,bg:getComputedStyle(document.querySelector(".dock-tray")).backgroundColor}})()','panel'); assert.equal(opacity.opacity,'1');assert.equal(opacity.text,'1');assert.match(opacity.bg, /0\.35/); - await evaluate('document.querySelector("[aria-label=面板材质]").scrollIntoView({block:"center"})'); + await evaluate('document.querySelector("[aria-label=上传背景图片]").scrollIntoView({block:"center"})'); await screenshot('appearance-options.png');await screenshot('dock-large-icons.png','panel',true); check('background opacity control affects surface tint only; panel and text stay fully opaque'); } finally { diff --git a/plugins/ztools-dock/scripts/check-background-image.mjs b/plugins/ztools-dock/scripts/check-background-image.mjs new file mode 100644 index 000000000..fb1110c10 --- /dev/null +++ b/plugins/ztools-dock/scripts/check-background-image.mjs @@ -0,0 +1,50 @@ +import {expect} from '@playwright/test'; +import assert from 'node:assert/strict'; +import {writeFileSync} from 'node:fs'; +import {join} from 'node:path'; +export async function checkBackgroundImage({app,evaluate,screenshot,temp,check}) { + const before=await evaluate('window.dock.call("snapshot")'); + const page=app.windows().find(w=>w.url().includes('surface=settings')); + const setDialog=file=>app.evaluate(({dialog},file)=>{dialog.showOpenDialog=async()=>({canceled:!file,filePaths:file?[file]:[]})},file); + const appearance=()=>evaluate('document.querySelectorAll(".settings-tabs button")[1].click()'); + try { + await appearance(); + assert.equal(await page.locator('[data-material]').count(),0); + await setDialog(null);await page.getByLabel('上传背景图片',{exact:true}).click(); + await expect(page.getByLabel('上传背景图片',{exact:true})).toBeEnabled(); + assert.equal((await evaluate('window.dock.call("snapshot")')).config.settings.backgroundImage,''); + await assert.rejects(evaluate('window.dock.call("background-image")','panel'),/此窗口不支持/); + const invalid=join(temp,'bad-background.png');writeFileSync(invalid,'invalid');await setDialog(invalid); + await assert.rejects(evaluate('window.dock.call("background-image")'),/解码/); + const transparent=join(temp,'transparent-background.png'); + const blank=await evaluate('(()=>{const c=document.createElement("canvas");c.width=8;c.height=8;return c.toDataURL()})()'); + writeFileSync(transparent,Buffer.from(blank.split(',')[1],'base64'));await setDialog(transparent); + await assert.rejects(evaluate('window.dock.call("background-image")'),/透明/); + for(const ext of ['png','jpeg','webp']){ + const data=await evaluate(`(()=>{const c=document.createElement('canvas');c.width=2000;c.height=800;const x=c.getContext('2d');const g=x.createLinearGradient(0,0,2000,800);g.addColorStop(0,'#4c8d92');g.addColorStop(.5,'#a7cbd9');g.addColorStop(1,'#d59f80');x.fillStyle=g;x.fillRect(0,0,2000,800);x.fillStyle='#fff4';for(let i=0;i<10;i++)x.fillRect(i*220,0,6,800);return c.toDataURL('image/${ext}')})()`); + const file=join(temp,`background.${ext}`);writeFileSync(file,Buffer.from(data.split(',')[1],'base64'));await setDialog(file); + await page.getByLabel('上传背景图片',{exact:true}).click(); + await expect(page.locator('.background-image-preview')).toBeVisible(); + await expect(page.getByLabel('上传背景图片',{exact:true})).toBeEnabled(); + const stored=(await evaluate('window.dock.call("snapshot")')).config.settings.backgroundImage; + assert.match(stored,/^data:image\/png;base64,/);const bytes=Buffer.from(stored.split(',')[1],'base64');assert.equal(bytes.readUInt32BE(16),1600);assert.ok(bytes.length<=1024*1024); + await evaluate('window.dock.call("expand")'); + await expect.poll(()=>evaluate('getComputedStyle(document.querySelector(".dock-bar"),"::before").backgroundImage','panel')).toContain(stored); + assert.equal(await evaluate('getComputedStyle(document.querySelector(".dock-tray"),"::before").backgroundSize','panel'),'cover'); + assert.equal(await evaluate('getComputedStyle(document.querySelector(".launch-name")).opacity','panel'),'1'); + assert.equal(await app.evaluate(({BrowserWindow})=>BrowserWindow.getAllWindows().filter(w=>w.webContents.getURL().includes('material.html')).length),0); + } + await evaluate(`(async()=>{const s=await window.dock.call('snapshot');Object.assign(s.config.settings,{tileMaterial:'clear',theme:'light'});await window.dock.call('save',s.config)})()`); + await screenshot('dock-background-image.png','panel',true); + await expect(page.locator('.toast')).toHaveCount(0,{timeout:9000}); + await page.getByLabel('上传背景图片',{exact:true}).scrollIntoViewIfNeeded();await screenshot('background-image-settings.png'); + const withImage=(await evaluate('window.dock.call("snapshot")')).config; + const exported=join(temp,'background-backup.json'); + await app.evaluate(({dialog},file)=>{dialog.showSaveDialog=async()=>({canceled:false,filePath:file})},exported); + await evaluate('window.dock.call("export")');await setDialog(exported);const imported=await evaluate('window.dock.call("import")');assert.equal(imported.settings.backgroundImage,withImage.settings.backgroundImage); + await appearance();await page.getByRole('button',{name:'移除背景',exact:true}).click(); + await expect(page.locator('.background-image-preview')).toHaveCount(0); + await expect.poll(()=>evaluate('getComputedStyle(document.querySelector(".dock-bar"),"::before").backgroundImage','panel')).toBe('none'); + check('background upload UI replaces native materials; PNG/JPEG/WebP normalize to bounded PNG, cancel/invalid preserve config, bar/tray show cover image, removal clears both; backup includes image and no native backdrop windows remain'); + } finally {await setDialog(null);await evaluate(`window.dock.call('save',${JSON.stringify(before.config)})`);await evaluate(`(async()=>{if((await window.dock.call('snapshot')).pinned!==${before.pinned})await window.dock.call('pin');await window.dock.call('${before.expanded?'expand':'collapse'}')})()`);await evaluate('document.querySelectorAll(".settings-tabs button")[0].click()');} +} diff --git a/plugins/ztools-dock/scripts/check-card-scale.mjs b/plugins/ztools-dock/scripts/check-card-scale.mjs index f32bb25ff..538f40c63 100644 --- a/plugins/ztools-dock/scripts/check-card-scale.mjs +++ b/plugins/ztools-dock/scripts/check-card-scale.mjs @@ -25,7 +25,7 @@ export async function checkCardScale({app,evaluate,screenshot,check}){ await expect.poll(async()=>{const m=await read(`(()=>{const g=document.querySelector('.dock-grid'),t=document.querySelector('.dock-tray').getBoundingClientRect(),c=document.querySelector('.launch-card').getBoundingClientRect();return {width:innerWidth,tray:{x:t.x,right:t.right,width:t.width},card:c.width,columns:getComputedStyle(g).gridTemplateColumns,scroll:g.offsetWidth-g.clientWidth,scrollHeight:g.scrollHeight,clientHeight:g.clientHeight}})()`);writeFileSync('artifacts/card-scale-narrow.json',JSON.stringify(m,null,2));return m.columns.split(' ').length===columns&&Math.abs(m.card-180)<1&&m.tray.x>=0&&m.tray.right<=m.width+1}).toBe(true); if(original.materialsSupported)await expect.poll(async()=>{const actual=await app.evaluate(({BrowserWindow})=>BrowserWindow.getAllWindows().find(w=>w.webContents.getURL().includes('surface=material-tray'))?.getBounds().width);const width=await read('document.querySelector(".dock-tray").getBoundingClientRect().width');return Number.isFinite(actual)&&Math.abs(actual-Math.ceil(width))<=1}).toBe(true); }}finally{await app.evaluate(({BrowserWindow},bounds)=>BrowserWindow.getAllWindows().find(w=>w.webContents.getURL().includes('surface=panel')).setBounds(bounds),actual)} - check('150 percent cards retain width by reducing columns at 360/620-DIP window widths; native Acrylic tray follows resized dimensions'); + check('150 percent cards retain width by reducing columns at 360/620-DIP window widths; tray follows resized dimensions'); await evaluate('document.querySelector("[aria-label=卡片缩放]").scrollIntoView({block:"center"})');await screenshot('card-scale-settings.png'); }finally{ await evaluate(`window.dock.call('save',${JSON.stringify(original.config)})`);await evaluate(`(async()=>{if((await window.dock.call('snapshot')).pinned!==${original.pinned})await window.dock.call('pin');await window.dock.call('${original.expanded?'expand':'collapse'}')})()`); diff --git a/plugins/ztools-dock/scripts/check-compositor.mjs b/plugins/ztools-dock/scripts/check-compositor.mjs index 9d234fe63..815772fa6 100644 --- a/plugins/ztools-dock/scripts/check-compositor.mjs +++ b/plugins/ztools-dock/scripts/check-compositor.mjs @@ -23,7 +23,7 @@ export async function checkCompositor({app,evaluate,native,check}) { await app.evaluate((_,point)=>{globalThis.compositorPoint=point},{x:state.bounds.trigger.x+1,y:state.bounds.trigger.y+1}); await new Promise(r=>setTimeout(r,350)); await expect.poll(()=>app.evaluate(({BrowserWindow})=>BrowserWindow.getAllWindows().filter(w=>w.webContents.getURL().includes('material.html')&&w.isVisible()).length)).toBe(2); - let stable=0; + let stable=0, baselineSeen=false; const card=await evaluate('(()=>{const r=document.querySelector(".launch-card").getBoundingClientRect();return {x:r.x+8,y:r.y+8}})()','panel'); for(let attempt=0;attempt<6;attempt++){ const sample=await app.evaluate(({BrowserWindow,screen},{panel,card})=>{ @@ -37,12 +37,15 @@ export async function checkCompositor({app,evaluate,native,check}) { },{panel:state.bounds.panel,card}); await new Promise(r=>setTimeout(r,120)); [sample.baseline,sample.inside,sample.blank]=native.pixels(sample.points);sample.flags=native.flags(sample.plateHandle); - const good=sample.baseline.every((v,i)=>Math.abs(v-[137,90,49][i])<=4)&&sample.inside.some((v,i)=>Math.abs(v-sample.baseline[i])>10)&&sample.blank.every((v,i)=>Math.abs(v-sample.baseline[i])<=4); + const baselineValid=sample.baseline.every((v,i)=>Math.abs(v-[137,90,49][i])<=4); + baselineSeen ||= baselineValid; + const good=baselineValid&&sample.inside.some((v,i)=>Math.abs(v-sample.baseline[i])>10)&&sample.blank.every((v,i)=>Math.abs(v-sample.baseline[i])<=4); stable=good?stable+1:0; results.push({material,attempt,good,...sample});writeFileSync('artifacts/compositor-result.json',JSON.stringify(results,null,2)); if(stable>=2)break; await new Promise(r=>setTimeout(r,200)); } + if(!baselineSeen){writeFileSync('artifacts/compositor-result.json',JSON.stringify({blocked:true,reason:'Desktop capture never saw the known test backplate color; material pixels are inconclusive',attempts:results},null,2));console.warn('BLOCKED: desktop capture baseline unavailable');return false;} assert.ok(stable>=2,`${material} desktop backdrop did not remain clear outside surfaces; see compositor-result.json`); } check('real desktop compositor keeps test background unchanged outside Mica/Acrylic dock surfaces');return true; diff --git a/plugins/ztools-dock/scripts/check-dock-dimensions.mjs b/plugins/ztools-dock/scripts/check-dock-dimensions.mjs new file mode 100644 index 000000000..a59872aba --- /dev/null +++ b/plugins/ztools-dock/scripts/check-dock-dimensions.mjs @@ -0,0 +1,60 @@ +import assert from 'node:assert/strict'; +import {expect} from '@playwright/test'; + +export async function checkDockDimensions({app,evaluate,screenshot,check}) { + const original=await evaluate('window.dock.call("snapshot")'); + const read=s=>evaluate(s,'panel'); + await app.evaluate(({screen})=>{globalThis.dimensionsCursor=screen.getCursorScreenPoint;screen.getCursorScreenPoint=()=>globalThis.dimensionsPoint||{x:0,y:0};}); + const apply=async config=>{await evaluate(`window.dock.call('save',${JSON.stringify(config)})`);await evaluate('window.dock.call("expand")');const s=await evaluate('window.dock.call("snapshot")');await app.evaluate((_,p)=>{globalThis.dimensionsPoint=p},{x:s.bounds.trigger.x+1,y:s.bounds.trigger.y+1});}; + const rects=()=>read(`(()=>{const r=s=>{const t=document.querySelector(s).getBoundingClientRect();return {x:t.x,y:t.y,width:t.width,height:t.height,right:t.right,bottom:t.bottom}};return {bar:r('.dock-bar'),tray:r('.dock-tray'),width:innerWidth,height:innerHeight}})()`); + try{ + const c=structuredClone(original.config);Object.assign(c.settings,{dockWidth:0,dockHeight:0,popupWidth:0,popupHeight:0,pinEnabled:true,cardScale:100,material:'solid'}); + for(const edge of ['top','bottom','left','right']){ + c.settings.dockEdge=edge;c.settings.pinEnabled=true;await apply(c); + await expect.poll(()=>read('document.querySelector(".dock-panel").dataset.edge')).toBe(edge); + await expect.poll(()=>read('document.querySelectorAll(".dock-menu-toggle").length')).toBe(1); + const before=await rects();c.settings.pinEnabled=false;await apply(c); + const axis=['top','bottom'].includes(edge)?'width':'height'; + await expect.poll(async()=>Math.round(before.bar[axis]-(await rects()).bar[axis])).toBe(26); + } + check('hiding pin removes its full 26-DIP slot in horizontal and vertical navigation bars'); + await evaluate('document.querySelectorAll(".settings-tabs button")[1].click()'); + for(const edge of ['top','bottom','left','right']){ + c.settings.dockEdge=edge;await apply(c); + for(const [label,key,value] of [['导航条宽度','dockWidth',320],['导航条高度','dockHeight',160],['卡片弹窗宽度','popupWidth',420],['卡片弹窗高度','popupHeight',230]]){ + await evaluate(`(()=>{const i=document.querySelector('[aria-label="${label}"]');i.value='${value}';i.dispatchEvent(new Event('change',{bubbles:true}))})()`); + await expect.poll(()=>evaluate(`window.dock.call('snapshot').then(s=>s.config.settings.${key})`)).toBe(value); + } + await expect.poll(async()=>{const r=await rects();return Math.abs(r.bar.width-320)<1&&Math.abs(r.bar.height-160)<1&&Math.abs(r.tray.width-420)<1&&Math.abs(r.tray.height-230)<1&&r.tray.x>=0&&r.tray.y>=0&&r.tray.right<=r.width+1&&r.tray.bottom<=r.height+1}).toBe(true); + } + check('four independent dimension inputs set 320x160 navigation and 420x230 popup on all edges; cards scroll within fixed popup'); + Object.assign(c.settings,{dockEdge:'top',dockWidth:240,dockHeight:40,popupWidth:0,popupHeight:0});await apply(c); + await expect.poll(()=>read(`(()=>{const b=document.querySelector('.dock-bar').getBoundingClientRect();return b.height===40&&[...document.querySelectorAll('.dock-category svg,.dock-category-name')].every(el=>{const r=el.getBoundingClientRect();return r.top>=b.top&&r.bottom<=b.bottom})})()`)).toBe(true); + c.settings.dockEdge='top';Object.assign(c.settings,{dockWidth:2000,dockHeight:1200,popupWidth:2000,popupHeight:1200}); + for(const edge of ['top','bottom','left','right']){ + c.settings.dockEdge=edge;await apply(c); + await expect.poll(async()=>{const r=await rects();return ['bar','tray'].every(k=>r[k].x>=0&&r[k].y>=0&&r[k].right<=r.width+1&&r[k].bottom<=r.height+1)}).toBe(true); + } + check('oversized manual dimensions are clamped to available space on all four docking edges'); + Object.assign(c.settings,{dockEdge:'top',dockWidth:400,dockHeight:80,popupWidth:420,popupHeight:230});await apply(c); + await screenshot('dock-manual-dimensions.png','panel',true); + await evaluate('document.querySelector("[aria-label=导航条宽度]").scrollIntoView({block:"center"})');await screenshot('dock-dimension-settings.png'); + // Switching while collapsed must survive the hidden renderer and then restore both backgrounds. + if(original.materialsSupported){ + const page=app.windows().find(p=>p.url().includes('surface=settings')); + for(const m of ['mica','acrylic','solid','acrylic','mica','solid']){ + await evaluate('window.dock.call("collapse")'); + await page.locator(`[data-material="${m}"]`).click(); + await expect.poll(()=>evaluate('window.dock.call("snapshot").then(s=>s.material)')).toBe(m); + await page.locator(`[data-material="${m}"]`).getAttribute('aria-pressed').then(value=>assert.equal(value,'true')); + await evaluate('window.dock.call("expand")'); + await expect.poll(()=>app.evaluate(({BrowserWindow})=>BrowserWindow.getAllWindows().filter(w=>w.webContents.getURL().includes('material.html')&&w.isVisible()).length)).toBe(m==='solid'?0:2); + } + check('actual material buttons survive repeated collapsed solid/Mica/Acrylic switches and restore native backgrounds on expand'); + } + }finally{ + await evaluate(`window.dock.call('save',${JSON.stringify(original.config)})`); + await evaluate(`(async()=>{if((await window.dock.call('snapshot')).pinned!==${original.pinned})await window.dock.call('pin');await window.dock.call('${original.expanded?'expand':'collapse'}')})()`); + await app.evaluate(({screen})=>{screen.getCursorScreenPoint=globalThis.dimensionsCursor}); + } +} diff --git a/plugins/ztools-dock/scripts/check-dropdowns.mjs b/plugins/ztools-dock/scripts/check-dropdowns.mjs new file mode 100644 index 000000000..831a6c445 --- /dev/null +++ b/plugins/ztools-dock/scripts/check-dropdowns.mjs @@ -0,0 +1,52 @@ +import {expect} from '@playwright/test'; +import assert from 'node:assert/strict'; +import {writeFileSync} from 'node:fs'; +export async function checkDropdowns({app,evaluate,screenshot,check,page}) { + const before=(await evaluate('window.dock.call("snapshot")')).config; + const box=name=>page.getByRole('combobox',{name,exact:true}); + const list=name=>page.getByRole('listbox',{name:name+'选项',exact:true}); + const working=structuredClone(before); + working.categories.push(...Array.from({length:20},(_,i)=>({id:'dropdown-category-'+i,name:'自定义分类'+i,icon:'Folder',color:'#087fe7',...(i===0?{image:before.entries.at(-1).image}:{})}))); + await evaluate(`window.dock.call('save',${JSON.stringify(working)})`); + try { + await page.getByTitle('编辑工具设置',{exact:true}).click(); + await box('所属分类').click();await expect(list('所属分类').getByRole('option',{name:'开发工具',exact:true}).locator('svg')).toBeVisible(); + const categoryBounds=await page.locator('.rich-select-popup').boundingBox();assert.ok(categoryBounds.height<=320.1); + assert.ok(await list('所属分类').evaluate(el=>el.scrollHeight>el.clientHeight),'long category menu scrolls'); + await screenshot('category-dropdown.png'); + await list('所属分类').getByRole('option',{name:'开发工具',exact:true}).click(); + await expect(box('所属分类')).toHaveText('开发工具');await expect(box('所属分类').locator('svg').first()).toBeVisible(); + await box('所属分类').click();await page.getByLabel('搜索所属分类',{exact:true}).fill('自定义分类0'); + await expect(list('所属分类').getByRole('option',{name:'自定义分类0',exact:true}).locator('img')).toBeVisible(); + await list('所属分类').getByRole('option',{name:'自定义分类0',exact:true}).click();await expect(box('所属分类').locator('img')).toBeVisible(); + await box('类型').click();await expect(list('类型').getByRole('option',{name:'网址',exact:true}).locator('svg')).toBeVisible(); + await box('类型').press('Escape');assert.equal(await page.locator('.editor-modal').count(),1); + await box('插件名称').scrollIntoViewIfNeeded();await box('插件名称').click(); + await expect(list('插件名称').getByRole('option',{name:'图标验收工具',exact:true}).locator('img')).toBeVisible(); + await expect(list('插件名称').getByRole('option',{name:'程序坞验收工具',exact:true}).locator('img')).toBeVisible(); + await expect(box('插件名称').locator('img')).toBeVisible(); + await screenshot('plugin-icon-dropdown.png'); + const rect=await page.locator('.rich-select-popup').boundingBox();assert.ok(rect.height<=320.1);assert.ok(rect.y>=0&&rect.y+rect.height<=await page.evaluate(()=>innerHeight)); + await page.getByLabel('搜索插件名称',{exact:true}).fill('图标');assert.equal(await list('插件名称').getByRole('option').count(),1); + await page.getByLabel('搜索插件名称',{exact:true}).fill('不存在的插件');await expect(page.getByText('没有匹配项',{exact:true})).toBeVisible(); + await page.getByLabel('搜索插件名称',{exact:true}).press('Escape'); + await evaluate('window.originalIconCall=window.dock.call;window.iconReadCount=0;window.dock.call=(op,...args)=>{if(op==="plugin-icon")window.iconReadCount++;return window.originalIconCall(op,...args)};true'); + for(let i=0;i<3;i++){await box('插件名称').click();await expect(list('插件名称').getByRole('option').first()).toBeVisible();await page.getByLabel('搜索插件名称',{exact:true}).press('Escape');} + const reads=await evaluate('window.iconReadCount');assert.equal(reads,0,'cached visible icons require no new preload reads during repeated opening'); + writeFileSync('artifacts/dropdown-performance.json',JSON.stringify({fixturePlugins:2,reopens:3,additionalIconReads:reads,thumbnailMaximum:64,concurrentLoads:3,cacheLimit:128},null,2)); + await box('插件名称').click();await list('插件名称').getByRole('option',{name:'程序坞验收工具',exact:true}).click(); + await expect(box('插件名称')).toHaveText('程序坞验收工具');await expect(box('插件名称').locator('img')).toBeVisible(); + await expect(box('插件指令')).toHaveText('验证跳转'); + await page.getByTitle('关闭编辑',{exact:true}).click();assert.deepEqual((await evaluate('window.dock.call("snapshot")')).config,working); + check('custom type/category/plugin/command dropdowns show icons and bound search lists; three reopenings of two cached plugin icons cause zero additional icon reads; cancel preserves entry'); + await page.locator('.settings-tabs button').nth(1).click();await box('颜色模式').scrollIntoViewIfNeeded();await box('颜色模式').click();await list('颜色模式').getByRole('option',{name:'深色',exact:true}).click(); + await expect.poll(()=>evaluate('window.dock.call("snapshot").then(s=>s.config.settings.theme)')).toBe('dark'); + await box('每行最多列数').scrollIntoViewIfNeeded();await box('每行最多列数').click();await screenshot('dropdown-dark.png');await box('每行最多列数').press('Escape'); + await box('颜色模式').focus();await box('颜色模式').press('ArrowDown');await page.locator('.rich-select-popup').press('Home');await page.locator('.rich-select-popup').press('ArrowDown');await page.locator('.rich-select-popup').press('Enter'); + await expect.poll(()=>evaluate('window.dock.call("snapshot").then(s=>s.config.settings.theme)')).toBe('light'); + check('appearance selectors use matching popup style in dark mode; Home/Arrow/Enter choose and persist the expected value'); + } finally { + await evaluate('if(window.originalIconCall){window.dock.call=window.originalIconCall;delete window.originalIconCall}document.querySelector("button[title=关闭编辑]")?.click()').catch(()=>{}); + await evaluate(`window.dock.call('save',${JSON.stringify(before)})`);await page.locator('.settings-tabs button').nth(0).click(); + } +} diff --git a/plugins/ztools-dock/scripts/check-hover-stability.mjs b/plugins/ztools-dock/scripts/check-hover-stability.mjs new file mode 100644 index 000000000..6b485c663 --- /dev/null +++ b/plugins/ztools-dock/scripts/check-hover-stability.mjs @@ -0,0 +1,43 @@ +import assert from 'node:assert/strict'; +import { expect } from '@playwright/test'; + +export async function checkHoverStability({app,evaluate,native,check}) { + const original=await evaluate('window.dock.call("snapshot")'); + const measure=()=>evaluate(`(()=>{const el=document.querySelector('.dock-tray'),r=el.getBoundingClientRect();return {x:r.x,y:r.y,width:r.width,height:r.height,display:getComputedStyle(el).display,visibility:getComputedStyle(el).visibility}})()`,'panel'); + const handle=await app.evaluate(({BrowserWindow})=>BrowserWindow.getAllWindows().find(w=>w.webContents.getURL().includes('surface=panel')).getNativeWindowHandle().readBigUInt64LE().toString()); + const scale=native.probe(handle).dpi/96; + try { + for(const edge of ['top','bottom','left','right']) { + await evaluate(`(async()=>{const s=await window.dock.call('snapshot');Object.assign(s.config.settings,{dockEdge:'${edge}',material:'solid',openDelay:0,closeDelay:1500});await window.dock.call('save',s.config);await window.dock.call('expand')})()`); + await expect.poll(async()=> (await measure()).height).toBeGreaterThan(0); + await expect.poll(async()=> (await measure()).visibility).toBe('visible'); + // Let resize observers finish positioning before comparing subsequent shows. + await evaluate('new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r)))','panel'); + const shown=await measure(); + for(let i=0;i<3;i++) { + await evaluate('(async()=>{if((await window.dock.call("snapshot")).pinned)await window.dock.call("pin");await window.dock.call("collapse")})()'); + await new Promise(r=>setTimeout(r,100)); + const hidden=await measure(); + assert.equal(hidden.display,'flex',`${edge}: collapsed tray retains measurable layout`); + assert.deepEqual({x:hidden.x,y:hidden.y,width:hidden.width,height:hidden.height},{x:shown.x,y:shown.y,width:shown.width,height:shown.height},`${edge}: collapse must not reposition or resize tray`); + assert.equal(native.probe(handle,undefined,{x:Math.round((shown.x+shown.width/2)*scale),y:Math.round((shown.y+shown.height/2)*scale)}).contains,true,edge+': hidden native window retains card region before show'); + await evaluate('window.dock.call("hover",true)','panel'); + await expect.poll(()=>evaluate('window.dock.call("snapshot").then(s=>s.expanded)')).toBe(true); + await expect.poll(async()=> (await measure()).visibility).toBe('visible'); + const again=await measure(); + assert.deepEqual(again,shown,`${edge}: hover reopening uses the prepared layout`); + } + await evaluate('window.dock.call("pin")');await evaluate('window.dock.call("collapse",false)'); + await expect.poll(async()=>(await measure()).visibility).toBe('hidden'); + const pinned=await measure();assert.equal(pinned.width,shown.width);assert.equal(pinned.height,shown.height); + assert.equal(await evaluate('document.querySelector(".dock-tray").inert','panel'),true); + await evaluate('window.dock.call("expand")'); + await expect.poll(async()=>(await measure()).visibility).toBe('visible'); + await evaluate('(async()=>{if((await window.dock.call("snapshot")).pinned)await window.dock.call("pin");await window.dock.call("collapse")})()'); + } + check('12 hover reopenings across all edges retain tray dimensions, position and complete native regions before show; pinned hidden tray retains size and is inert'); + } finally { + await evaluate(`window.dock.call('save',${JSON.stringify(original.config)})`); + await evaluate(`(async()=>{await window.dock.call('${original.expanded?'expand':'collapse'}');if((await window.dock.call('snapshot')).pinned!==${original.pinned})await window.dock.call('pin')})()`); + } +} diff --git a/plugins/ztools-dock/scripts/check-pin-adaptive.mjs b/plugins/ztools-dock/scripts/check-pin-adaptive.mjs index c09d5075f..83ae9a9eb 100644 --- a/plugins/ztools-dock/scripts/check-pin-adaptive.mjs +++ b/plugins/ztools-dock/scripts/check-pin-adaptive.mjs @@ -44,7 +44,7 @@ export async function checkPinAdaptive({app,evaluate,screenshot,check}){ await expect.poll(()=>read('document.querySelector(".dock-tray").getBoundingClientRect().width')).toBe(264); await screenshot('dock-adaptive-width.png','panel',true); await evaluate('document.querySelector("[aria-label=启用钉住功能]").scrollIntoView({block:"center"})');await screenshot('pin-setting.png'); - check('search result counts resize tray and native Acrylic backdrop together; empty search remains usable; two-entry preview has no empty columns'); + check('search result counts resize tray together; empty search remains usable; two-entry preview has no empty columns'); }finally{ await evaluate(`window.dock.call('save',${JSON.stringify(original.config)})`); await evaluate(`(async()=>{if((await window.dock.call('snapshot')).pinned!==${original.pinned})await window.dock.call('pin');await window.dock.call('${original.expanded?'expand':'collapse'}')})()`); diff --git a/plugins/ztools-dock/scripts/check-plugin-selection.mjs b/plugins/ztools-dock/scripts/check-plugin-selection.mjs new file mode 100644 index 000000000..20713fd65 --- /dev/null +++ b/plugins/ztools-dock/scripts/check-plugin-selection.mjs @@ -0,0 +1,122 @@ +import assert from 'node:assert/strict'; +import { expect } from '@playwright/test'; +import { writeFileSync, readFileSync, readdirSync } from 'node:fs'; +import { join, dirname } from 'node:path'; +import { zipSync, strToU8 } from 'fflate'; +import {checkDropdowns} from './check-dropdowns.mjs'; + +export async function checkPluginSelection({app,evaluate,screenshot,temp,check}) { + const before=(await evaluate('window.dock.call("snapshot")')).config; + // The isolated Electron runtime has no bundled settings folder of its own. + // Install the unchanged official settings UI from the tested host resources. + const settingPresent=await app.evaluate(async({ipcMain,BrowserWindow})=>(await ipcMain._invokeHandlers.get('get-all-plugins')({sender:BrowserWindow.getAllWindows()[0].webContents})).some(p=>p.name==='setting')); + if(!settingPresent){ + const folder=join(dirname(process.env.ZTOOLS_APP),'app.asar.unpacked/internal-plugins/setting'),files={}; + function collect(dir,prefix=''){for(const e of readdirSync(dir,{withFileTypes:true})){if(e.isDirectory())collect(join(dir,e.name),prefix+e.name+'/');else files[prefix+e.name]=new Uint8Array(readFileSync(join(dir,e.name)));}} + collect(folder);const manifest=JSON.parse(Buffer.from(files['plugin.json']).toString());delete manifest.development;files['plugin.json']=strToU8(JSON.stringify(manifest)); + const zip=join(temp,'official-host-settings.zip');writeFileSync(zip,zipSync(files)); + const result=await app.evaluate(async({ipcMain,BrowserWindow},zip)=>ipcMain._invokeHandlers.get('install-plugin-from-path')({sender:BrowserWindow.getAllWindows().find(w=>w.getTitle()==='ZTools').webContents},zip),zip);assert.equal(result.success,true); + } + + const page=app.windows().find(w=>w.url().includes('surface=settings')); + const fixture=join(temp,'selector-fixture.zip'); + writeFileSync(fixture,zipSync({ + 'plugin.json':strToU8(JSON.stringify({name:'dock-select-fixture',title:'图标验收工具',version:'1.0.0',main:'index.html',logo:'logo.svg',features:[{code:'first',cmds:['打开工具','工具设置',{type:'over',label:'需要文本'}]}]})), + 'index.html':strToU8('图标验收工具'), + 'logo.svg':strToU8('') + })); + await app.evaluate(async({ipcMain,BrowserWindow},zip)=>ipcMain._invokeHandlers.get('install-plugin-from-path')({sender:BrowserWindow.getAllWindows().find(w=>w.getTitle()==='ZTools').webContents},zip),fixture); + try { + await page.getByRole('button',{name:'添加入口',exact:true}).first().click(); + await page.locator('.field-pair select').first().selectOption('plugin'); + const proceed=page.getByRole('button',{name:'继续授权',exact:true}); + await expect(proceed).toBeDisabled(); + const boxes=page.locator('.plugin-consent input[type=checkbox]'); + assert.equal(await boxes.count(),2);await expect(boxes.nth(0)).not.toBeChecked();await expect(boxes.nth(1)).not.toBeChecked(); + await boxes.nth(0).check();await expect(proceed).toBeDisabled(); + await boxes.nth(1).check();await expect(proceed).toBeEnabled(); + await boxes.nth(0).uncheck();await expect(proceed).toBeDisabled();await boxes.nth(0).check(); + assert.deepEqual(await evaluate('window.dock.call("plugin-catalog")'),{authorized:false,plugins:[]}); + await assert.rejects(evaluate('window.dock.call("plugin-catalog")','panel'),/此窗口不支持/); + await proceed.click(); + await expect.poll(()=>evaluate('window.ztools.getInternalApiPermissions().then(s=>s.pending.includes("internal:get-plugins"))','host')).toBe(true); + const approval=await app.evaluate(async({ipcMain,BrowserWindow})=>ipcMain._invokeHandlers.get('internal:resolve-internal-api-request')({sender:BrowserWindow.getAllWindows().find(w=>w.getTitle()==='ZTools').webContents},'ztools-dock',['internal:get-plugins','internal:get-disabled-plugins'])); + assert.equal(approval.success,true); + await page.getByRole('button',{name:'刷新列表',exact:true}).click(); + await expect(page.locator('#dock-plugin-select')).toBeEnabled(); + check('plugin list respects host permission, narrow request approved through isolated host management handler; panel denied'); + await page.locator('#dock-plugin-select').selectOption('dock-launch-fixture'); + await page.locator('.field-pair select').first().selectOption('url'); + await page.locator('.field-pair select').first().selectOption('plugin'); + await expect(page.locator('#dock-plugin-select')).toHaveValue(''); + await expect(page.locator('#dock-plugin-select')).toBeEnabled(); + await page.locator('.editor-modal input').first().fill(''); + await page.locator('#dock-plugin-select').selectOption('dock-select-fixture'); + const commands=page.locator('.rich-select').filter({has:page.getByRole('combobox',{name:'插件指令',exact:true})}).locator('select'); + await expect(commands).toHaveValue('打开工具'); + assert.deepEqual(await commands.locator('option').allTextContents(),['打开工具','工具设置']); + try { await expect(page.locator('.custom-icon-preview img')).toBeVisible(); } + catch(e) { console.log('icon diagnostic',await page.locator('.toast').allTextContents(),await evaluate('window.dock.call("plugin-icon","dock-select-fixture").then(x=>({length:x?.length,prefix:x?.slice(0,45)})).catch(e=>({error:e.stack}))','host'));throw e; } + const svgIcon=await page.locator('.custom-icon-preview img').getAttribute('src'); + assert.match(svgIcon,/^data:image\/png;base64,/); + await commands.selectOption('工具设置'); + assert.equal(await page.locator('.editor-modal input').first().inputValue(),'工具设置'); + await expect(page.locator('.toast')).toHaveCount(0,{timeout:9000}); + await screenshot('plugin-selector.png'); + await page.locator('.editor-modal button[type=submit]').click(); + await expect(page.locator('.editor-modal')).toHaveCount(0); + const saved=(await evaluate('window.dock.call("snapshot")')).config.entries.at(-1); + assert.equal(saved.plugin,'图标验收工具');assert.equal(saved.target,'工具设置');assert.equal(saved.image,svgIcon); + check('real installed plugin and text commands selectable; SVG plugin logo converted to PNG and persisted with selected command'); + await page.getByTitle('编辑工具设置',{exact:true}).click(); + await expect(page.locator('#dock-plugin-select')).toHaveValue('dock-select-fixture'); + assert.equal(await page.locator('.custom-icon-preview img').getAttribute('src'),svgIcon); + await page.locator('#dock-plugin-select').selectOption('dock-launch-fixture'); + await expect(commands).toHaveValue('验证跳转'); + await expect(page.locator('.custom-icon-preview img')).toBeVisible(); + assert.notEqual(await page.locator('.custom-icon-preview img').getAttribute('src'),svgIcon); + assert.equal(await commands.locator('option').count(),1); + await page.getByTitle('关闭编辑',{exact:true}).click(); + assert.equal((await evaluate('window.dock.call("snapshot")')).config.entries.at(-1).image,svgIcon); + check('editing preserves saved icon; switching plugin replaces commands and icon; cancelling preserves saved entry'); + await checkDropdowns({app,evaluate,screenshot,check,page}); + const legacy={...saved,id:'legacy-plugin',name:'旧插件入口',plugin:'已卸载的旧插件',target:'旧指令'}; + await evaluate(`(async()=>{const s=await window.dock.call('snapshot');s.config.entries.push(${JSON.stringify(legacy)});await window.dock.call('save',s.config)})()`); + await page.getByTitle('编辑旧插件入口',{exact:true}).click(); + await expect(page.locator('#dock-plugin-select')).toHaveValue('__legacy'); + await page.locator('.editor-modal input').first().fill('旧插件重命名'); + await page.locator('.editor-modal button[type=submit]').click(); + await expect(page.locator('.editor-modal')).toHaveCount(0); + const old=(await evaluate('window.dock.call("snapshot")')).config.entries.at(-1); + assert.equal(old.plugin,legacy.plugin);assert.equal(old.target,legacy.target);assert.equal(old.image,svgIcon); + check('unavailable legacy plugin remains editable without losing command or saved icon'); + await page.locator('.settings-tabs button').nth(2).click(); + await page.locator('.permission-settings-entry button').click(); + await expect(page.getByRole('dialog',{name:'插件授权',exact:true})).toBeVisible(); + await expect(page.locator('.permission-status strong').first()).toHaveText('宿主已授权'); + await page.getByRole('button',{name:'停止读取',exact:true}).click(); + await expect(page.locator('.permission-summary')).toHaveText('程序坞已停止读取'); + assert.equal((await evaluate('window.dock.call("plugin-catalog")')).authorized,false); + await assert.rejects(evaluate('window.dock.call("plugin-icon","dock-select-fixture")'),/授权/); + await expect(page.locator('.permission-status strong').first()).toHaveText('宿主已授权'); + await expect(page.locator('.permission-status').first()).toBeVisible(); + await expect(page.locator('.permission-status').nth(1)).toBeVisible(); + await screenshot('plugin-permissions.png'); + await page.getByRole('button',{name:'打开 ZTools 设置',exact:true}).click(); + await expect.poll(()=>app.evaluate(({webContents})=>webContents.getAllWebContents().some(w=>w.getURL().includes('/setting/index.html')))).toBe(true).catch(async e=>{console.log('host settings diagnostic',await app.evaluate(async({webContents,ipcMain,BrowserWindow})=>({urls:webContents.getAllWebContents().map(w=>w.getURL()),setting:(await ipcMain._invokeHandlers.get('get-all-plugins')({sender:BrowserWindow.getAllWindows()[0].webContents})).filter(p=>p.name==='setting').map(p=>({title:p.title,name:p.name}))})));throw e}); + const hostSettings=app.windows().find(w=>w.url().includes('/setting/index.html')); + await hostSettings.getByText('高级权限',{exact:true}).click(); + await hostSettings.locator('[data-testid=permission-tab-granted]').click(); + const grant=hostSettings.locator('[data-testid="permission-grant-card"]').filter({hasText:'ztools-dock'}); + await grant.locator('.plugin-head').click(); + await grant.locator('[data-testid="grant-remove-all"]').click(); + await hostSettings.getByRole('button',{name:'移除',exact:true}).click(); + await expect.poll(()=>evaluate('window.dock.call("plugin-permissions").then(s=>s.permissions.every(p=>!p.granted))')).toBe(true); + check('authorization manager reports host grants; local stop blocks list/icon reads; real host settings removal revokes both grants'); + await evaluate('window.dock.call("settings")','panel'); + } finally { + await evaluate('document.querySelector("button[title=关闭授权管理]")?.click()').catch(()=>{}); + if (await page.getByTitle('关闭编辑',{exact:true}).count()) await page.getByTitle('关闭编辑',{exact:true}).click(); + await evaluate(`window.dock.call('save',${JSON.stringify(before)})`); + } +} diff --git a/plugins/ztools-dock/scripts/check-position.mjs b/plugins/ztools-dock/scripts/check-position.mjs index d49212418..190a53cff 100644 --- a/plugins/ztools-dock/scripts/check-position.mjs +++ b/plugins/ztools-dock/scripts/check-position.mjs @@ -14,6 +14,9 @@ export async function checkPosition({app,evaluate,screenshot,native,check}) { await expect.poll(()=>evaluate(`window.dock.call('snapshot').then(s=>s.config.settings.${key})`)).toBe(value); }; const read=script=>evaluate(script,'panel'); + // Layout checks control selection explicitly. Window movement beneath the real + // desktop pointer must not synthesize unrelated category hover selections. + await read(`(()=>{const s=document.createElement('style');s.id='position-input-guard';s.textContent='.dock-category{pointer-events:none!important}';document.head.append(s)})()`); const layout=()=>read(`(()=>{const rect=s=>{const r=document.querySelector(s).getBoundingClientRect();return {x:r.x,y:r.y,width:r.width,height:r.height,right:r.right,bottom:r.bottom}};return {bar:rect('.dock-bar'),tray:rect('.dock-tray'),width:innerWidth,height:innerHeight,edge:document.querySelector('.dock-panel').dataset.edge}})()`); try { await evaluate('document.querySelectorAll(".settings-tabs button")[1].click()'); @@ -91,6 +94,7 @@ export async function checkPosition({app,evaluate,screenshot,native,check}) { } }finally{ + await read('document.getElementById("position-input-guard")?.remove()'); await evaluate(`window.dock.call('save',${JSON.stringify(before)})`); await evaluate(`(async()=>{if((await window.dock.call('snapshot')).pinned!==${original.pinned})await window.dock.call('pin');await window.dock.call('${original.expanded?'expand':'collapse'}')})()`); await expect.poll(()=>read('document.querySelector(".dock-panel")?.dataset.edge').catch(()=>false)).toBe(before.settings.dockEdge); diff --git a/plugins/ztools-dock/scripts/check-settings-layout.mjs b/plugins/ztools-dock/scripts/check-settings-layout.mjs new file mode 100644 index 000000000..ba776582b --- /dev/null +++ b/plugins/ztools-dock/scripts/check-settings-layout.mjs @@ -0,0 +1,46 @@ +import assert from 'node:assert/strict'; +import {expect} from '@playwright/test'; +export async function checkSettingsLayout({app,evaluate,screenshot,check}) { + const original=(await evaluate('window.dock.call("snapshot")')).config; + const bounds=await app.evaluate(({BrowserWindow})=>BrowserWindow.getAllWindows().find(w=>w.webContents.getURL().includes('surface=settings')).getBounds()); + const page=app.windows().find(p=>p.url().includes('surface=settings')); + try{ + await evaluate('document.querySelectorAll(".settings-tabs button")[1].click()'); + for(const [title,id] of [['停靠位置','position'],['边缘触发区','trigger'],['菜单导航','navigation'],['卡片弹窗','cards'],['材质与颜色','material'],['展开与收起','behavior']]){ + await page.getByRole('navigation',{name:'外观设置分组'}).getByRole('button',{name:title,exact:true}).click(); + await expect.poll(()=>evaluate(`(()=>{const r=document.querySelector('#heading-${id}').getBoundingClientRect(),n=document.querySelector('.preference-jumps').getBoundingClientRect();return r.top>=n.bottom-1&&r.bottomevaluate('window.dock.call("snapshot").then(s=>s.config.settings.dockWidth)')).toBe(0); + const input=page.getByRole('spinbutton',{name:'导航条宽度',exact:true}); + await input.fill('380');await input.press('Tab'); + await expect.poll(()=>evaluate('window.dock.call("snapshot").then(s=>s.config.settings.dockWidth)')).toBe(380); + await input.fill('9999');await input.press('Tab'); + await expect(input).toHaveValue('380');assert.equal((await evaluate('window.dock.call("snapshot")')).config.settings.dockWidth,380); + await page.getByRole('button',{name:'导航条宽度恢复自动',exact:true}).click(); + await expect.poll(()=>evaluate('window.dock.call("snapshot").then(s=>s.config.settings.dockWidth)')).toBe(0); + check('six section links reveal unobscured headings; dimension field saves manual size, rejects invalid input and restores auto via its button'); + await expect(page.locator('.toast')).toHaveCount(0,{timeout:9000}); + for(const theme of ['light','dark']){ + await evaluate(`(async()=>{const s=await window.dock.call('snapshot');s.config.settings.theme='${theme}';await window.dock.call('save',s.config)})()`); + await expect.poll(()=>evaluate('document.documentElement.dataset.theme')).toBe(theme); + await evaluate('document.querySelector(".preferences").scrollTop=0');await screenshot(`settings-${theme}.png`); + } + await app.evaluate(({BrowserWindow})=>BrowserWindow.getAllWindows().find(w=>w.webContents.getURL().includes('surface=settings')).setSize(620,720)); + await expect.poll(()=>evaluate('innerWidth')).toBeLessThan(625); + await evaluate('document.querySelector(".preferences").scrollTop=0'); + assert.equal(await evaluate('document.querySelector(".preferences").scrollWidth<=document.querySelector(".preferences").clientWidth'),true); + await screenshot('settings-narrow.png'); + await app.evaluate(({BrowserWindow},b)=>BrowserWindow.getAllWindows().find(w=>w.webContents.getURL().includes('surface=settings')).setBounds(b),bounds); + await evaluate(`(async()=>{const s=await window.dock.call('snapshot');s.config.settings.theme='light';await window.dock.call('save',s.config)})()`); + await evaluate('document.querySelector(".preferences").scrollTop=0');await screenshot('settings-overview.png'); + await page.getByRole('navigation',{name:'外观设置分组'}).getByRole('button',{name:'菜单导航',exact:true}).click();await screenshot('settings-card-controls.png'); + await evaluate('document.querySelectorAll(".settings-tabs button")[0].click()');await screenshot('settings-entries.png'); + await evaluate('document.querySelectorAll(".settings-tabs button")[2].click()');await screenshot('settings-backup.png'); + check('grouped settings render in light/dark and 620-DIP narrow window; entry and backup pages captured from production ZIP'); + }finally{ + await app.evaluate(({BrowserWindow},b)=>BrowserWindow.getAllWindows().find(w=>w.webContents.getURL().includes('surface=settings')).setBounds(b),bounds); + await evaluate(`window.dock.call('save',${JSON.stringify(original)})`); + await evaluate('document.querySelectorAll(".settings-tabs button")[0].click()'); + } +} diff --git a/plugins/ztools-dock/scripts/check-style.mjs b/plugins/ztools-dock/scripts/check-style.mjs index 9601be987..caac3fdcd 100644 --- a/plugins/ztools-dock/scripts/check-style.mjs +++ b/plugins/ztools-dock/scripts/check-style.mjs @@ -87,7 +87,7 @@ export async function checkStyle({ app, evaluate, screenshot, native, check }) { await app.evaluate(({screen})=>{screen.getCursorScreenPoint=()=>({x:-100000,y:-100000})}); await expect.poll(()=>read('window.dock.call("snapshot").then(s=>s.trayVisible)'),{timeout:4000}).toBe(false); assert.equal((await read('window.dock.call("snapshot")')).expanded,true); - assert.equal(await read('getComputedStyle(document.querySelector(".dock-tray")).display'),'none'); + assert.equal(await read('getComputedStyle(document.querySelector(".dock-tray")).visibility'),'hidden'); await read('document.querySelector(".dock-bar").dispatchEvent(new MouseEvent("mouseenter"))'); await expect.poll(()=>read('window.dock.call("snapshot").then(s=>s.trayVisible)')).toBe(true); await read('document.querySelector(".dock-menu-toggle").click()'); diff --git a/plugins/ztools-dock/scripts/check-tile-materials.mjs b/plugins/ztools-dock/scripts/check-tile-materials.mjs new file mode 100644 index 000000000..c44eb5a3b --- /dev/null +++ b/plugins/ztools-dock/scripts/check-tile-materials.mjs @@ -0,0 +1,49 @@ +import assert from 'node:assert/strict'; +import {expect} from '@playwright/test'; +import {writeFileSync} from 'node:fs'; +export async function checkTileMaterials({app,evaluate,screenshot,check}) { + const original=await evaluate('window.dock.call("snapshot")'); + const appearance=()=>evaluate('document.querySelectorAll(".settings-tabs button")[1].click()'); + const styles=()=>evaluate(`(()=>{const read=sel=>{const e=document.querySelector(sel),s=getComputedStyle(e),p=getComputedStyle(e,'::before'),r=e.getBoundingClientRect();return{background:s.backgroundImage,shadow:s.boxShadow,border:s.borderColor,before:p.backgroundImage,width:r.width,height:r.height,opacity:s.opacity,ink:s.color}};return{menu:read('.dock-category'),card:read('.launch-card'),tray:read('.dock-tray'),strength:getComputedStyle(document.querySelector('.dock-panel')).getPropertyValue('--glass-strength')}})()`,'panel'); + const results=[]; + try { + await evaluate(`(async()=>{const s=await window.dock.call('snapshot');Object.assign(s.config.settings,{dockEdge:'top',material:'solid',theme:'light',tileStrength:85});s.config.entries.push({...s.config.entries[0],id:'material-tools',categoryId:'tools',name:'常用工具'},{...s.config.entries[1],id:'material-ai',categoryId:'ai',name:'AI工具'});await window.dock.call('save',s.config);await window.dock.call('expand');if(!(await window.dock.call('snapshot')).pinned)await window.dock.call('pin')})()`); + await appearance(); + for(const kind of ['plain','ice','frosted','liquid','clear','iridescent']){ + await evaluate(`document.querySelector('[data-tile-choice="${kind}"]').click()`); + await expect.poll(()=>evaluate('window.dock.call("snapshot").then(s=>s.config.settings.tileMaterial)')).toBe(kind); + await expect.poll(()=>evaluate('document.querySelector(".dock-panel").dataset.tileMaterial','panel')).toBe(kind); + await evaluate('new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r)))','panel'); + const info=await styles();results.push({kind,...info}); + assert.equal(info.card.opacity,'1');assert.equal(info.menu.opacity,'1'); + if(kind!=='plain') {assert.notEqual(info.card.shadow,'none');assert.notEqual(info.menu.shadow,'none');} + await screenshot(`tile-${kind}-light.png`,'panel',true); + } + assert.equal(new Set(results.map(r=>JSON.stringify([r.card.background,r.card.shadow,r.card.before]))).size,6,'six distinct card surfaces'); + assert.equal(new Set(results.map(r=>r.tray.background)).size,1,'tile choices do not replace outer background'); + for(const value of [0,40,100]) { + await evaluate(`(()=>{const el=document.querySelector('[aria-label="材质强度"]');el.value='${value}';el.dispatchEvent(new Event('input',{bubbles:true}));el.dispatchEvent(new Event('change',{bubbles:true}))})()`); + await expect.poll(()=>evaluate('window.dock.call("snapshot").then(s=>s.config.settings.tileStrength)')).toBe(value); + await expect.poll(()=>evaluate('getComputedStyle(document.querySelector(".dock-panel")).getPropertyValue("--glass-strength")','panel')).toBe(String(value/100)); + results.push({strength:value,...await styles()}); + } + assert.notEqual(results.at(-1).card.shadow,results.at(-3).card.shadow); + assert.equal(results.at(-1).card.width,results.at(-3).card.width);assert.equal(results.at(-1).card.height,results.at(-3).card.height); + await evaluate(`(async()=>{const s=await window.dock.call('snapshot');Object.assign(s.config.settings,{tileStrength:85,theme:'dark'});await window.dock.call('save',s.config)})()`); + for(const kind of ['ice','frosted','liquid','clear','iridescent']){ + await evaluate(`document.querySelector('[data-tile-choice="${kind}"]').click()`); + await expect.poll(()=>evaluate('document.querySelector(".dock-panel").dataset.tileMaterial','panel')).toBe(kind); + await screenshot(`tile-${kind}-dark.png`,'panel',true); + } + await evaluate('document.querySelector(".tile-material-picker").scrollIntoView({block:"center"})'); + await screenshot('tile-material-picker-dark.png'); + await evaluate(`(async()=>{const s=await window.dock.call('snapshot');s.config.settings.theme='light';await window.dock.call('save',s.config)})()`); + await screenshot('tile-material-picker.png'); + writeFileSync('artifacts/tile-material-styles.json',JSON.stringify(results,null,2)); + check('six distinct menu/entry surfaces selected through real controls; intensity 0/40/100 persists and changes rim/shadow without resizing or fading content; light/dark screenshots captured'); + } finally { + await evaluate(`window.dock.call('save',${JSON.stringify(original.config)})`); + await evaluate(`(async()=>{if((await window.dock.call('snapshot')).pinned!==${original.pinned})await window.dock.call('pin');await window.dock.call('${original.expanded?'expand':'collapse'}')})()`); + await evaluate('document.querySelectorAll(".settings-tabs button")[0].click()'); + } +} diff --git a/plugins/ztools-dock/scripts/test-host.mjs b/plugins/ztools-dock/scripts/test-host.mjs index ab42f0eae..459fd2135 100644 --- a/plugins/ztools-dock/scripts/test-host.mjs +++ b/plugins/ztools-dock/scripts/test-host.mjs @@ -14,8 +14,14 @@ import { checkCardScale } from './check-card-scale.mjs'; import { checkPinAdaptive } from './check-pin-adaptive.mjs'; import { checkNames } from './check-names.mjs'; import { checkPosition } from './check-position.mjs'; +import { checkDockDimensions } from './check-dock-dimensions.mjs'; +import { checkSettingsLayout } from './check-settings-layout.mjs'; import { checkAppearance } from './check-appearance.mjs'; import { checkReset } from './check-reset.mjs'; +import { checkPluginSelection } from './check-plugin-selection.mjs'; +import { checkHoverStability } from './check-hover-stability.mjs'; +import { checkTileMaterials } from './check-tile-materials.mjs'; +import { checkBackgroundImage } from './check-background-image.mjs'; const executablePath = process.env.ZTOOLS_EXECUTABLE; if (!executablePath) throw new Error('Set ZTOOLS_EXECUTABLE to an Electron-compatible test executable; set ZTOOLS_APP when loading an installed app.asar.'); @@ -94,6 +100,7 @@ try { })); await app.evaluate(async ({ ipcMain, BrowserWindow }, zip) => { const sender = BrowserWindow.getAllWindows().find(w => w.getTitle() === 'ZTools').webContents; return ipcMain._invokeHandlers.get('install-plugin-from-path')({ sender }, zip); }, fixtureZip); await openSettings(main); + await checkPluginSelection({app,evaluate,screenshot,temp,check}); const state = await evaluate('window.dock.call("snapshot")'); assert.equal(state.config.entries.length, 7); await screenshot('settings.png'); @@ -109,6 +116,9 @@ try { screen.getCursorScreenPoint=()=>{const w=BrowserWindow.getAllWindows().find(w=>w.webContents.getURL().includes('surface=panel'));const b=w.getBounds();return {x:b.x+b.width/2,y:b.y+20}}; }); await evaluate('window.dock.call("expand")'); + await checkHoverStability({app,evaluate,native,check}); + await checkTileMaterials({app,evaluate,screenshot,check}); + await checkBackgroundImage({app,evaluate,screenshot,temp,check}); await evaluate('window.dock.call("pin")'); await expect.poll(() => evaluate('document.querySelectorAll(".launch-card").length', 'panel'), { timeout: 15000 }).toBe(7); await screenshot('dock.png', 'panel'); @@ -122,11 +132,15 @@ try { check('native trigger region clipped; hover panel does not steal focus'); await checkTriggerArt({app,evaluate,screenshot,native,temp,check}); await checkAppearance({app,evaluate,screenshot,native,check}); + await checkDockDimensions({app,evaluate,screenshot,check}); + await checkSettingsLayout({app,evaluate,screenshot,check}); await checkPosition({app,evaluate,screenshot,native,check}); - if(!await checkCompositor({app,evaluate,native,check}))evidence.blockedChecks=['Windows locked or material unsupported: compositor check unavailable']; + // Native background materials have been replaced by uploaded pictures. await checkCardScale({app,evaluate,screenshot,check}); await checkPinAdaptive({app,evaluate,screenshot,check}); await checkNames({app,evaluate,screenshot,check}); + await evaluate('window.dock.call("settings")','panel'); + await waitDock(); await checkFixes({app,evaluate,screenshot,native,triggerHandle,check}); await checkStyle({app,evaluate,screenshot,native,check}); await checkAddition({app,main,evaluate,screenshot,native,temp,check}); diff --git a/plugins/ztools-dock/scripts/test-smoke.mjs b/plugins/ztools-dock/scripts/test-smoke.mjs new file mode 100644 index 000000000..64bb48d83 --- /dev/null +++ b/plugins/ztools-dock/scripts/test-smoke.mjs @@ -0,0 +1,94 @@ +import { _electron as electron, expect } from '@playwright/test'; +import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, existsSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve, sep } from 'node:path'; +import assert from 'node:assert/strict'; +import { zipSync, strToU8 } from 'fflate'; +import { checkPluginSelection } from './check-plugin-selection.mjs'; + +const executablePath = process.env.ZTOOLS_EXECUTABLE; +if (!executablePath) throw new Error('Set ZTOOLS_EXECUTABLE to an Electron-compatible test executable; set ZTOOLS_APP when loading an installed app.asar.'); +const temp = mkdtempSync(join(tmpdir(), 'ztools-dock-test-')); +mkdirSync(join(temp, 'legacy')); +mkdirSync('artifacts', { recursive: true }); +const version = JSON.parse(readFileSync('package.json', 'utf8')).version; +const evidence = { host: null, checks: [], temp, zip: resolve(`release/程序坞-${version}-windows.zip`) }; +let app, failed = false; + +const logs = []; +function check(text) { evidence.checks.push(text); console.log(text); writeFileSync("artifacts/host-progress.json", JSON.stringify(evidence, null, 2)); } +async function bounded(promise, ms = 15000) { let timer; try { return await Promise.race([promise, new Promise((_, reject) => timer = setTimeout(() => reject(new Error("Host operation timed out")), ms))]); } finally { clearTimeout(timer); } } +const hostArgs = process.env.ZTOOLS_APP ? [process.env.ZTOOLS_APP] : []; +async function start() { + app = await electron.launch({ executablePath, args: hostArgs, env: { ...process.env, ZTOOLS_DATA_ROOT: temp, ZTOOLS_LEGACY_USER_DATA_PATH: join(temp, 'legacy'), ZTOOLS_E2E: '1' }, timeout: 35000 }); + app.process()?.stdout?.on('data', data => { logs.push(String(data)); if (logs.length > 120) logs.shift(); }); + app.process()?.stderr?.on('data', data => { logs.push(String(data)); if (logs.length > 120) logs.shift(); }); + evidence.host = await app.evaluate(({ app }) => ({ appVersion: app.getVersion(), versions: process.versions, executable: process.execPath, userData: app.getPath('userData') })); + await app.evaluate(({ app, webContents }) => { + globalThis.dockTestConsole = []; + const attach = wc => wc.on('console-message', (event, details, message) => globalThis.dockTestConsole.push({ url: wc.getURL(), message: event.message || details?.message || message })); + webContents.getAllWebContents().forEach(attach); app.on('web-contents-created', (_e, wc) => attach(wc)); + }); + const main = await app.firstWindow(); + await main.locator('.search-input').waitFor({ timeout: 25000 }); + return main; +} +async function evaluate(script, surface = 'settings') { + return bounded(app.evaluate(({ webContents }, { script, surface }) => { + const wc = webContents.getAllWebContents().find(w => w.getURL().includes('/plugins/ztools-dock/') && (surface === 'host' ? !w.getURL().includes('surface=') : w.getURL().includes(`surface=${surface}`))); + if (!wc) throw new Error(`Missing ${surface} WebContents`); + return wc.executeJavaScript(script); + }, { script, surface })); +} +async function waitDock() { await expect.poll(() => evaluate('Boolean(window.dock && document.querySelector(".settings-shell"))').catch(() => false), { timeout: 18000 }).toBe(true); } +async function openSettings(main) { + const input = main.locator('.search-input'); + await expect.poll(async () => { const count = await main.locator('.app-item').filter({ hasText: '程序坞设置' }).count(); if (!count) { await input.fill(''); await input.fill('程序坞设置'); } return count; }, { timeout: 15000, intervals: [300, 600, 1000] }).toBeGreaterThan(0); + await main.locator('.app-item').filter({ hasText: '程序坞设置' }).first().click(); await waitDock(); +} +async function screenshot(filename, surface = 'settings', preview = false) { + const bytes = await app.evaluate(async ({ webContents }, {surface,preview}) => { + const wc = webContents.getAllWebContents().find(w => w.getURL().includes('/plugins/ztools-dock/') && (surface === 'host' ? !w.getURL().includes('surface=') : w.getURL().includes(`surface=${surface}`))); + // Capture an explicitly neutral backdrop for shareable style previews; no image post-processing. + if (preview) await wc.executeJavaScript('document.documentElement.style.setProperty("background","#f4f4f4","important")'); + try { + await wc.executeJavaScript('new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve(true))))'); + await wc.executeJavaScript('Promise.all(document.getAnimations().map(a=>a.finished.catch(()=>{}))).then(()=>new Promise(resolve=>requestAnimationFrame(()=>resolve(true))))'); + const crop = preview ? await wc.executeJavaScript(`(()=>{const rs=['.dock-bar','.dock-tray'].map(s=>document.querySelector(s).getBoundingClientRect());const x=Math.max(0,Math.floor(Math.min(...rs.map(r=>r.x))-16)),y=Math.max(0,Math.floor(Math.min(...rs.map(r=>r.y))-16));return {x,y,width:Math.min(innerWidth-x,Math.ceil(Math.max(...rs.map(r=>r.right))+16-x)),height:Math.min(innerHeight-y,Math.ceil(Math.max(...rs.map(r=>r.bottom))+18-y))}})()`) : undefined; + return Array.from((await wc.capturePage(crop)).toPNG()); + } finally { if (preview) await wc.executeJavaScript('document.documentElement.style.removeProperty("background")'); } + }, {surface,preview}); + writeFileSync(`artifacts/${filename}`, Buffer.from(bytes)); +} +async function close() { + if (!app) return; + const timer = setTimeout(() => app.process()?.kill(), 5000); + try { await app.close(); } finally { clearTimeout(timer); app = null; } +} + +try { + const main = await start(); + const installed = await app.evaluate(async ({ ipcMain, BrowserWindow }, zip) => { + const sender = BrowserWindow.getAllWindows().find(w => w.getTitle() === 'ZTools').webContents; + const handler = ipcMain._invokeHandlers.get('install-plugin-from-path'); + if (!handler) throw new Error('Host install handler not available'); + return handler({ sender }, zip); + }, evidence.zip); + assert.equal(installed.success, true, JSON.stringify(installed)); check('production ZIP installed'); + const fixtureZip = join(temp, 'target-plugin.zip'); + writeFileSync(fixtureZip, zipSync({ + 'plugin.json': strToU8(JSON.stringify({ name: 'dock-launch-fixture', title: '程序坞验收工具', version: '1.0.0', main: 'index.html', logo: 'logo.png', preload: 'preload.js', features: [{ code: 'target', explain: '验证跳转', cmds: ['验证跳转'] }] })), + 'index.html': strToU8('

目标插件已打开

'), + 'preload.js': strToU8('window.ztools.onPluginEnter(()=>{});'), 'logo.png': new Uint8Array(readFileSync('dist/logo.png')) + })); + await app.evaluate(async ({ ipcMain, BrowserWindow }, zip) => { const sender = BrowserWindow.getAllWindows().find(w => w.getTitle() === 'ZTools').webContents; return ipcMain._invokeHandlers.get('install-plugin-from-path')({ sender }, zip); }, fixtureZip); + await openSettings(main); + await checkPluginSelection({app,evaluate,screenshot,temp,check}); + await evaluate('document.querySelectorAll(".settings-tabs button")[1].click()'); + assert.equal(await evaluate('document.querySelectorAll(".preference-group").length'),6); + assert.equal(await evaluate('document.querySelectorAll(".preference-heading p").length'),0); + assert.equal(await evaluate('Boolean(document.querySelector("[aria-label=上传背景图片]"))'),true); + await screenshot('settings-copy-smoke.png');check('three settings tabs retain key controls; redundant section descriptions removed'); +} catch(error) {failed=true;evidence.error=String(error.stack||error);console.error(evidence.error);} +finally {await close();writeFileSync('artifacts/smoke-result.json',JSON.stringify(evidence,null,2));const safe=resolve(temp).startsWith(resolve(tmpdir())+sep)&&/^ztools-dock-test-/.test(temp.split(sep).at(-1));if(safe)rmSync(temp,{recursive:true,force:true,maxRetries:3,retryDelay:200});} +if(failed)process.exitCode=1; diff --git a/plugins/ztools-dock/scripts/test-upgrade.mjs b/plugins/ztools-dock/scripts/test-upgrade.mjs index 1993ed551..35e6cc510 100644 --- a/plugins/ztools-dock/scripts/test-upgrade.mjs +++ b/plugins/ztools-dock/scripts/test-upgrade.mjs @@ -9,7 +9,7 @@ if (!process.env.ZTOOLS_EXECUTABLE) throw new Error('Set ZTOOLS_EXECUTABLE and o const temp = mkdtempSync(join(tmpdir(), 'ztools-dock-upgrade-')); mkdirSync(join(temp, 'legacy')); mkdirSync('artifacts', { recursive: true }); const version = JSON.parse(readFileSync('package.json', 'utf8')).version; -const previousZip = process.env.ZTOOLS_PREVIOUS_ZIP || 'release/程序坞-0.1.13-windows.zip'; +const previousZip = process.env.ZTOOLS_PREVIOUS_ZIP || 'release/程序坞-0.1.18-windows.zip'; const previousVersion = JSON.parse(strFromU8(unzipSync(readFileSync(previousZip))['plugin.json'])).version; const previousSurface = previousVersion === '0.1.0' ? 'host' : 'settings'; const evidence = { checks: [] }; @@ -48,6 +48,9 @@ try { const expected = await evaluate('(async()=>{const s=await window.dock.call("snapshot");s.config.categories[0].name="升级保留分类";s.config.entries.reverse();s.config.settings.triggerOpacity=0.66;if(s.config.settings.dockEdge!==undefined)Object.assign(s.config.settings,{dockEdge:"left",positionMode:"distance",positionDistance:120,positionAnchor:"end",positionRatio:70});await window.dock.call("save",s.config);return s.config})()',previousSurface); stage("old config customized");expected.settings.pinEnabled ??= true; expected.settings.cardScale ??= 100; + expected.settings.backgroundImage ??= ''; + expected.settings.tileMaterial ??= 'plain'; expected.settings.tileStrength ??= 70; + for(const key of ["dockWidth","dockHeight","popupWidth","popupHeight"])expected.settings[key] ??= 0; expected.settings.searchEnabled ??= false; expected.settings.triggerTheme ??= 'bar';expected.settings.iconSize ??= 'medium';expected.settings.material ??= 'solid';expected.settings.panelOpacity ??= 1; expected.settings.dockEdge ??= 'top';expected.settings.positionMode ??= 'ratio';expected.settings.positionRatio ??= 50;expected.settings.positionDistance ??= 0;expected.settings.positionAnchor ??= 'start'; @@ -63,9 +66,9 @@ try { await expect.poll(() => evaluate('Boolean(document.querySelector(".settings-shell"))', 'settings').catch(() => false)).toBe(true); assert.deepEqual((await evaluate('window.dock.call("snapshot")', 'settings')).config, expected); evidence.checks.push(`${previousVersion} → ${version} retains custom category, entry order and appearance`); - stage("upgraded config retained");let appearance=await evaluate('(async()=>{const s=await window.dock.call("snapshot");Object.assign(s.config.settings,{cardScale:125,pinEnabled:false,triggerEdgeDistance:-6,showCategoryNames:false,showEntryNames:false,dockEdge:"right",positionMode:"distance",positionDistance:140,positionAnchor:"end",positionRatio:25,triggerTheme:"snail",iconSize:"large",material:s.materialsSupported?"acrylic":"solid",panelOpacity:0.35});await window.dock.call("save",s.config);return s.config})()','settings'); + stage("upgraded config retained");let appearance=await evaluate('(async()=>{const s=await window.dock.call("snapshot");Object.assign(s.config.settings,{tileMaterial:"iridescent",tileStrength:82,dockWidth:180,dockHeight:320,popupWidth:460,popupHeight:260,cardScale:125,pinEnabled:false,triggerEdgeDistance:-6,showCategoryNames:false,showEntryNames:false,dockEdge:"right",positionMode:"distance",positionDistance:140,positionAnchor:"end",positionRatio:25,triggerTheme:"snail",iconSize:"large",material:s.materialsSupported?"acrylic":"solid",panelOpacity:0.35});await window.dock.call("save",s.config);return s.config})()','settings'); const customTrigger=await app.evaluate(({nativeImage})=>nativeImage.createFromBitmap(Buffer.from([220,90,35,255]),{width:1,height:1}).toDataURL()); - appearance=await evaluate(`(async()=>{const s=await window.dock.call('snapshot');s.config.settings.triggerTheme='custom';s.config.settings.triggerImage=${JSON.stringify(customTrigger)};await window.dock.call('save',s.config);return s.config})()`,'settings'); + appearance=await evaluate(`(async()=>{const s=await window.dock.call('snapshot');s.config.settings.triggerTheme='custom';s.config.settings.triggerImage=${JSON.stringify(customTrigger)};s.config.settings.backgroundImage=${JSON.stringify(customTrigger)};await window.dock.call('save',s.config);return s.config})()`,'settings'); await evaluate('window.ztools.outPlugin(true)'); await expect.poll(()=>app.evaluate(({webContents})=>webContents.getAllWebContents().filter(w=>w.getURL().includes('/plugins/ztools-dock/')).length)).toBe(0); await search(main,'程序坞设置'); diff --git a/plugins/ztools-dock/src/AppearanceSettings.vue b/plugins/ztools-dock/src/AppearanceSettings.vue new file mode 100644 index 000000000..798366854 --- /dev/null +++ b/plugins/ztools-dock/src/AppearanceSettings.vue @@ -0,0 +1,80 @@ + + diff --git a/plugins/ztools-dock/src/DimensionField.vue b/plugins/ztools-dock/src/DimensionField.vue new file mode 100644 index 000000000..8edd52895 --- /dev/null +++ b/plugins/ztools-dock/src/DimensionField.vue @@ -0,0 +1,19 @@ + + diff --git a/plugins/ztools-dock/src/Dock.vue b/plugins/ztools-dock/src/Dock.vue index 0b62b1041..6a7332bef 100644 --- a/plugins/ztools-dock/src/Dock.vue +++ b/plugins/ztools-dock/src/Dock.vue @@ -3,6 +3,7 @@ import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue' import type { State } from './types'; import Icon from './Icon.vue'; import { command } from './bridge'; +import './tile-materials.css'; const props = defineProps<{ state: State }>(); const query = ref(''); const selected = ref(props.state.config.settings.lastCategoryId); @@ -17,8 +18,16 @@ const entries = computed(() => { }); const current = computed(() => categories.value.find(c => c.id === selected.value)); const vertical = computed(() => ['left','right'].includes(props.state.config.settings.dockEdge)); +// A fully collapsed native window is already hidden. Keep its last complete +// layout ready for the next show; only pinned navigation hides the tray itself. +const trayPrepared = computed(() => !props.state.expanded || props.state.trayVisible); const iconPixels = computed(() => ({ small: 24, medium: 29, large: 36 })[props.state.config.settings.iconSize]); const viewportWidth = ref(0), scrollbarWidth = ref(0); +const navWidth = computed(() => props.state.config.settings.dockWidth || (vertical.value ? 100 : categories.value.length ? categories.value.length * 100 + 6 + (props.state.config.settings.pinEnabled ? 26 : 0) : 160)); +const navHeight = computed(() => props.state.config.settings.dockHeight || (vertical.value ? Math.max(76, categories.value.length * 66 + 10 + (props.state.config.settings.pinEnabled ? 26 : 0)) : 66)); +const actualNavWidth = ref(100), actualNavHeight = ref(66); +const categoryIconPixels = computed(() => Math.min(Math.round(iconPixels.value * 25 / 29), vertical.value ? 36 : Math.max(12, actualNavHeight.value - (props.state.config.settings.showCategoryNames ? 25 : 8)))); + const cardRatio = computed(() => props.state.config.settings.cardScale / 100); const cardIconPixels = computed(() => Math.round(iconPixels.value * cardRatio.value)); const cardFont = computed(() => Math.max(10, 12 * cardRatio.value)); @@ -26,11 +35,13 @@ const cardHeight = computed(() => Math.ceil(Math.max(props.state.config.settings cardIconPixels.value + 12 * cardRatio.value + 2 + (props.state.config.settings.showEntryNames ? cardFont.value * 1.5 + 6 * cardRatio.value : 0)))); const gridColumns = computed(() => { const width = viewportWidth.value || props.state.bounds?.panel.width || 1000; - const available = width - (vertical.value ? 100 : 32) - scrollbarWidth.value; + const room = width - (vertical.value ? actualNavWidth.value : 32); + const requested = props.state.config.settings.popupWidth; + const available = Math.min(room, requested ? Math.max(requested, 134 * cardRatio.value + 2) : room) - scrollbarWidth.value; const fitting = Math.max(1, Math.floor(((available - 2) / cardRatio.value - 6) / 128)); return Math.min(props.state.config.settings.columns, entries.value.length || 2, fitting); }); -const dimensions = computed(() => ({ '--panel-opacity': `${props.state.config.settings.panelOpacity * 100}%`, '--card-opacity': `${(0.2 + props.state.config.settings.panelOpacity * 0.8) * 100}%`, '--bar-width': `${Math.max(160, categories.value.length * 100 + 32)}px`, '--tray-width': `${(gridColumns.value * 128 + 6) * cardRatio.value + 2 + scrollbarWidth.value}px`, '--card-height': `${cardHeight.value}px`, '--card-padding': `${6 * cardRatio.value}px`, '--card-gap': `${6 * cardRatio.value}px`, '--card-font': `${cardFont.value}px`, '--grid-gap': `${8 * cardRatio.value}px`, '--tray-padding': `${7 * cardRatio.value}px`, '--card-radius': `${Math.max(4, 7 * cardRatio.value)}px` })); +const dimensions = computed(() => ({ '--background-image': props.state.config.settings.backgroundImage ? `url("${props.state.config.settings.backgroundImage}")` : 'none', '--glass-strength': props.state.config.settings.tileStrength / 100, '--panel-opacity': `${props.state.config.settings.panelOpacity * 100}%`, '--card-opacity': `${(0.2 + props.state.config.settings.panelOpacity * 0.8) * 100}%`, '--bar-width': `${navWidth.value}px`, '--nav-width': `${actualNavWidth.value}px`, '--nav-height': `${actualNavHeight.value}px`, '--category-padding': !vertical.value && actualNavHeight.value < 60 ? '2px 8px' : '6px 8px', '--category-gap': !vertical.value && actualNavHeight.value < 60 ? '2px' : '4px', '--category-basis': props.state.config.settings.dockWidth ? '60px' : '92px', '--tray-width': `${props.state.config.settings.popupWidth ? Math.max(props.state.config.settings.popupWidth, 134 * cardRatio.value + 2 + scrollbarWidth.value) : (gridColumns.value * 128 + 6) * cardRatio.value + 2 + scrollbarWidth.value}px`, '--tray-height': props.state.config.settings.popupHeight ? `${props.state.config.settings.popupHeight}px` : 'auto', '--card-height': `${cardHeight.value}px`, '--card-padding': `${6 * cardRatio.value}px`, '--card-gap': `${6 * cardRatio.value}px`, '--card-font': `${cardFont.value}px`, '--grid-gap': `${8 * cardRatio.value}px`, '--tray-padding': `${7 * cardRatio.value}px`, '--card-radius': `${Math.max(4, 7 * cardRatio.value)}px` })); let observer: ResizeObserver | undefined, frame = 0, lastShape = ''; function scheduleLayout() { @@ -45,8 +56,9 @@ function updateLayout() { const edge = props.state.config.settings.dockEdge; const anchor = props.state.bounds?.anchor || { x: width / 2, y: height / 2 }; const clamp = (value: number, min: number, max: number) => Math.max(min, Math.min(Math.max(min, max), value)); - const barWidth = vertical.value ? Math.min(100, width) : Math.min(Math.max(160, categories.value.length * 100 + 32), Math.max(1, width - 32)); - const barHeight = vertical.value ? Math.min(Math.max(92, categories.value.length * 66 + 26), Math.max(66, height - 32)) : 66; + const barWidth = Math.min(navWidth.value, Math.max(1, width - (vertical.value ? Math.min(width - 1, 100) : 32))); + const barHeight = Math.min(navHeight.value, Math.max(1, height - (vertical.value ? 32 : 100))); + actualNavWidth.value = barWidth; actualNavHeight.value = barHeight; const barX = vertical.value ? (edge === 'left' ? 0 : width - barWidth) : clamp(anchor.x - barWidth / 2, 16, width - barWidth - 16); const barY = vertical.value ? clamp(anchor.y - barHeight / 2, 16, height - barHeight - 16) : edge === 'bottom' ? height - barHeight : 0; Object.assign(bar.value.style, { left: `${Math.round(barX)}px`, top: `${Math.round(barY)}px`, width: `${barWidth}px`, height: `${barHeight}px` }); @@ -58,7 +70,7 @@ function updateLayout() { const trayY = vertical.value ? clamp(centreY - trayHeight / 2, 16, height - trayHeight - 16) : edge === 'bottom' ? barY - trayHeight : barY + barHeight; // Drawing and native hit regions use the same final placement. Object.assign(tray.value.style, { left: `${Math.round(trayX)}px`, top: `${Math.round(trayY)}px` }); - const regions = [bar.value, ...(props.state.trayVisible ? [tray.value] : [])].map(el => { + const regions = [bar.value, ...(trayPrepared.value ? [tray.value] : [])].map(el => { const rect = el.getBoundingClientRect(), shadow = props.state.material && props.state.material !== 'solid' ? 0 : 14; const x = Math.max(0, Math.floor(rect.x - shadow)), y = Math.max(0, Math.floor(rect.y - shadow)); return { x, y, width: Math.min(width, Math.ceil(rect.right + shadow)) - x, height: Math.min(height, Math.ceil(rect.bottom + shadow)) - y }; @@ -80,7 +92,7 @@ watch([categories, () => props.state.config.settings.lastCategoryId], ([list, id watch(selected, revealSelected); watch(() => props.state.material, () => { lastShape = ''; scheduleLayout(); }); watch(() => props.state.config.settings.dockEdge, async () => { await nextTick(); updateLayout(); await revealSelected(); }); -watch([() => props.state.expanded, () => props.state.trayVisible, dimensions, () => props.state.config.settings.dockEdge, () => props.state.bounds?.anchor.x, () => props.state.bounds?.anchor.y, () => props.state.material, () => entries.value.length, () => props.state.config.settings.searchEnabled, query], async () => { await nextTick(); scheduleLayout(); }); +watch([() => props.state.expanded, () => props.state.trayVisible, dimensions, navHeight, () => props.state.config.settings.dockEdge, () => props.state.bounds?.anchor.x, () => props.state.bounds?.anchor.y, () => props.state.material, () => entries.value.length, () => props.state.config.settings.searchEnabled, query], async () => { await nextTick(); scheduleLayout(); }); function select(id: string) { if (!props.state.trayVisible) command('expand'); query.value = ''; @@ -117,24 +129,24 @@ onMounted(() => { onBeforeUnmount(() => { observer?.disconnect(); cancelAnimationFrame(frame); document.removeEventListener('visibilitychange', visibility); });