feat(tauri): 完成桌面端迁移(原生另存为 + plugin-http 取图 + 插件静态化 + 中文注释)

This commit is contained in:
qiqi committed 2026-11-16 18:52:30 +08:00
1 parent 4709ec05f2
commit cddbd1f8eb
72 files changed
+16317 -56

No files matched your search

+5
View File
@@ -14,3 +14,8 @@ coverage/
# 其他 agent 的本地记忆目录(不入库)
.workbuddy/
# 桌面版本地构建缓存(sandbox 内 npm cache 只能落在仓库里)
.npm-cache/
.cargo-home/
release/
+79
View File
@@ -0,0 +1,79 @@
# 构建与打包(桌面版)
## 一、依赖
| 项 | 版本 | 说明 |
|---|---|---|
| Node.js | ≥ 20 | 前端构建(esbuild 逐文件压缩 + 拼接) |
| Rust | ≥ 1.90 | Tauri 后端;macOS 用默认 toolchain,Windows 必须 **MSVC** |
| Xcode CLT | — | 仅 macOS:`xcode-select --install` |
| VS Build Tools | 2019/2022 + 「使用 C++ 的桌面开发」 | 仅 Windows |
| WebView2 Runtime | — | Windows 10 需安装;Win11 自带 |
## 二、日常命令
```bash
npm ci # 首次
npm run build # 只出前端 dist/(含运行时插件)
npm run app:dev # 开发(启动前自动 build,改完源码需手动再 build)
npm run app:build # 打包当前平台(mac:.app + .dmg;Win:.exe + .msi)
```
首次 `app:build` 要编译 ~250 个 Rust crate,约 2–5 分钟;之后增量很快。
> 本机(沙箱)里 cargo/npm 的缓存目录被限制在仓库内,所以 build 时用
> `CARGO_HOME=$PWD/.cargo-home npm_config_cache=$PWD/.npm-cache`;
> 在你自己的机器上不需要,直接用默认缓存即可。
## 三、产物位置
| 平台 | 路径 |
|---|---|
| macOS | `src-tauri/target/release/bundle/macos/image-workbench.app` |
| macOS dmg | `src-tauri/target/release/bundle/dmg/image-workbench_3.24.85_*.dmg` |
| Windows msi | `src-tauri/target/release/bundle/msi/*.msi` |
| Windows exe(setup) | `src-tauri/target/release/bundle/nsis/*-setup.exe` |
## 四、Windows 打包(只能在 Windows 上做)
Tauri 不支持从 macOS 交叉编译 Windows 产物,必须在 Windows 机器上跑:
```powershell
# 1) 一次性环境(有 winget 的话)
winget install OpenJS.NodeJS.LTS
winget install Rustlang.Rustup
winget install Microsoft.VisualStudio.2022.BuildTools --override "--quiet --add Microsoft.VisualStudio.Workload.VCTools"
winget install Microsoft.EdgeWebView2Runtime
# 2) 确认 Rust 走的是 MSVC
rustup default stable-msvc
rustc -V
# 3) 构建
git clone <本仓库地址> image-workbench-desktop
cd image-workbench-desktop
npm ci
npm run app:build
```
产物在 `src-tauri\target\release\bundle\` 下的 `msi\` 与 `nsis` 目录。
常见坑:
- `link.exe not found` → VS Build Tools 没装「使用 C++ 的桌面开发」工作负载
- 中文路径 / 空格路径可能让 NSIS 失败 → 仓库放在 `C:\work\` 这类纯英文路径
- 没签名 → SmartScreen 会提示「未知发布者」,点「更多信息 → 仍要运行」
## 五、签名与分发(本次不做)
macOS 未签名:首次打开要 **右键 → 打开**(或在「系统设置 → 隐私与安全性」里放行)。
Windows 未签名:SmartScreen 提示,仅影响首次运行体验。
要正式分发再考虑 Apple Developer ID / Windows 代码签名证书,与本次迁移无关。
## 六、插件资源的来路
网页版插件由 Cloudflare KV 在 `/plugins/*` 提供;桌面版没有服务端,所以把
**发布产物**(`plugins/runtime/*.js`,文件名带内容哈希)随仓库带走,构建后由
`scripts/copy-plugins.js` 拷进 `dist/plugins/`。每个文件的 SHA-256 与
`plugins/index.json` 里的 `integrity` 一致(已校验)。
升级插件时:换掉 `plugins/runtime/` 里的文件 + 同步 `plugins/index.json` 即可,代码不用动。
+23 -7
View File
@@ -19,13 +19,29 @@
除 `src-tauri/`(纯新增,不会冲突)外,业务代码只改了这些地方:
| 文件 | 位置 | 改了什么 |
|---|---|---|
| `app.js` | 保存图片入口 `downloadUrl` / `downloadBlob` / `clickDownload` | Tauri 下改走「原生另存为 + fs 写二进制」 |
| `app.js` | `wDownloadBlob`(备份/导出) | 同上 |
| `app.js` | `/api/img` 代理处(3 处) | Tauri 下改走 `plugin-http` 直取字节 |
| `package.json` | 依赖与脚本 | 加 `@tauri-apps/*` 与 `tauri` 脚本 |
| `.upstream-base` / `scripts/sync-upstream.sh` | 新增 | 同步机制本身 |
| # | 文件 | 位置 | 改了什么 |
|---|---|---|---|
| P1 | `app.js` | 文件顶部 | 新增「桌面端适配层」:`wIsTauri()` / `wSaveBlobNative()` / `window.__IWB_SAVE_BLOB__` |
| P2 | `app.js` | 输出缩略图归档 | 桌面端用 `plugin-http` 取字节,替代 `/api/img` 代理 |
| P3 | `app.js` | `downloadUrl` 内 `downloadBlob` | 桌面端弹系统「另存为」,`fs.writeFile` 写 Uint8Array |
| P4 | `app.js` | `downloadUrl` 的 `data:`/`blob:` 分支 | 桌面端先取 Blob 再走原生保存(`<a download>` 在桌面无效) |
| P5 | `app.js` | `downloadUrl` 第③段代理兜底 | 桌面端换 `plugin-http` 直连 |
| P6 | `app.js` | 预览派生 `viaUrl` | 桌面端不拼代理地址,直连(失败则负缓存回退原图) |
| P7 | `app.js` | 显示缩略图 `img.src` | 桌面端直接用原地址 |
| P8 | `app.js` | `wDownloadBlob`(备份 zip 等) | 统一走 `__IWB_SAVE_BLOB__` |
| P9 | `app.js` | 运行诊断导出 | 同上 |
| P10 | `app.js` | 节点组导出 | 同上 |
| P11 | `src/runtime-workbench-logic.js` | 画布导出 `.iwb.json` | 同上 |
新增的配套文件(都不碰业务逻辑):
| 路径 | 作用 |
|---|---|
| `src-tauri/` | 壳层:conf / capabilities / lib.rs(只注册 dialog、fs、http 三个官方插件,零自定义命令) |
| `plugins/runtime/*.js` | 7 个运行时插件的发布产物(从线上抓取,SHA-256 与 `plugins/index.json` 逐一校验通过) |
| `scripts/copy-plugins.js` | 构建后把插件拷进 `dist/plugins/`(网页版由 KV 提供,桌面端只能随包) |
| `scripts/sync-upstream.sh` + `.upstream-base` | 同步机制 |
| `package.json` | 加 `@tauri-apps/*` 依赖、`tauri`/`app:dev`/`app:build` 脚本,`build` 链上 copy-plugins |
**红线:除上表外不要再改业务代码。** 差异每多一处,以后同步冲突的概率就高一分。
+71 -8
View File
@@ -10,6 +10,38 @@
// 页面加载时就会跑一次保存,声明若在后面会命中 TDZ(异常被 catch 吞掉 ⇒ 落盘退回未精简的 result)。
const GenerationResults = (typeof window !== 'undefined' && window.IWBGenerationResults) || null
// ========== 桌面端(Tauri v2)适配层 ==========
// 仅在 Tauri 内生效:网页版没有 window.__TAURI__ ⇒ 所有分支都走原逻辑,行为零变化。
// 用 withGlobalTauri 注入的官方 API(无需打包器),权限仍由 src-tauri/capabilities 约束。
const wTauri = (typeof window !== 'undefined' && window.__TAURI__) ? window.__TAURI__ : null
const wIsTauri = () => !!(wTauri && wTauri.core)
// 桌面端保存二进制:弹系统「另存为」→ fs 直接写 Uint8Array。
// 刻意不经 base64:Blob → arrayBuffer → Uint8Array,省掉一次全量编码/解码。
const wSaveBlobNative = async (blob, name, title) => {
const save = wTauri && wTauri.dialog && wTauri.dialog.save
const writeFile = wTauri && wTauri.fs && wTauri.fs.writeFile
if (!save || !writeFile) throw new Error('Tauri 保存接口不可用(检查 dialog/fs 插件是否初始化)')
const fileName = String(name || 'image.png')
const ext = (fileName.split('.').pop() || 'png').toLowerCase()
// 路径来自 save() 的返回值:tauri-plugin-dialog 会把该路径动态加入 fs scope,
// 因此 capabilities 里不需要静态放开任何目录(不放开 $HOME 这类宽权限)。
const path = await save({ title: title || '保存', defaultPath: fileName, filters: [{ name: ext.toUpperCase() + ' 文件', extensions: [ext] }] })
if (!path) return false
await writeFile(path, new Uint8Array(await blob.arrayBuffer()))
return true
}
// 统一保存出口:桌面端交系统另存为,网页端沿用 <a download>。
// 挂到 window 供 IIFE 深处的导出/诊断/备份复用,避免到处写分支。
const wSaveBlob = (blob, name) => {
if (wIsTauri()) return wSaveBlobNative(blob, name).catch((e) => { console.error('[iwb][tauri] 保存失败', e) })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url; a.download = name
document.body.appendChild(a); a.click(); a.remove()
setTimeout(() => URL.revokeObjectURL(url), 5000)
}
if (typeof window !== 'undefined') window.__IWB_SAVE_BLOB__ = wSaveBlob
// ========== 浏览器本地模式(Cloudflare Pages 免费版)==========
// 数据层:localStorage + IndexedDB;网络层:直连兼容 API(CORS 已验证允许)
function storageRuntime() { return typeof window !== 'undefined' && window.IWBStorageRuntime }
@@ -1655,7 +1687,10 @@
if (fkEarly && /^https:/i.test(fkEarly) && !wThumbProxyTried.has(fkEarly)) {
wThumbProxyTried.add(fkEarly)
try {
const pr = await fetch('/api/img?url=' + encodeURIComponent(fkEarly), { mode: 'cors' })
// 桌面端没有 /api/img 代理(无服务端)⇒ 用 plugin-http 直取字节(Rust 侧请求,不受 CORS 限制)
const pr = wIsTauri()
? await wTauri.http.fetch(fkEarly)
: await fetch('/api/img?url=' + encodeURIComponent(fkEarly), { mode: 'cors' })
// v3.87.52(丙方案 C5):交给 wRegisterBlobUrl(入参是 Blob,内部创建并登记 objectURL),
// 避免此前的"创建了 blob URL 却不登记、不回收"✗
if (pr.ok) return storeOutputThumb(Object.assign({}, item, { url: wRegisterBlobUrl(await pr.blob()) }))
@@ -4092,13 +4127,24 @@
}
const downloadBlob = (blob) => {
if (blob && blob.type) outName = nameOf(blob.type)
// 桌面端:替换原来的 <a download>,弹系统「另存为」后 fs 写二进制
if (wIsTauri()) {
wSaveBlobNative(blob, outName, '保存图片')
.then((ok) => { if (ok) wDownloadToast('已保存:' + outName) })
.catch((e) => wDownloadToast('保存失败:' + ((e && e.message) || e)))
return
}
const obj = URL.createObjectURL(blob)
clickDownload(obj)
setTimeout(() => URL.revokeObjectURL(obj), 5000)
}
// data URL / blob: URL(同源,已被浏览器解析过):直接用 <a download>。
// 注意 blob: 也必须走这条路:线上 CSP connect-src 'self' https: 会拦掉 fetch(blob:...)。
if (su.indexOf('data:') === 0 || su.indexOf('blob:') === 0) { clickDownload(url); return }
if (su.indexOf('data:') === 0 || su.indexOf('blob:') === 0) {
// 桌面端没有「浏览器下载目录」这回事 ⇒ 先取回字节,再走原生另存为
if (wIsTauri()) { try { downloadBlob(await (await fetch(url)).blob()); return } catch (e) { /* 落到后面的兜底 */ } }
else { clickDownload(url); return }
}
// ① 直连(图床允许跨域时最快、最保真)
try {
const resp = await fetch(url, { mode: 'cors' })
@@ -4124,8 +4170,11 @@
} catch (e) { /* 继续兜底 */ }
// ③ **本站同源代理**兜底(functions/api/img.js;跨域图床专用。不经任何第三方)
try {
const r2 = await fetch('/api/img?url=' + encodeURIComponent(su), { mode: 'cors' })
if (r2.ok) { downloadBlob(await r2.blob()); wDownloadToast('该图床不支持直连下载,已通过本站代理保存'); return }
// 桌面端没有同源代理:改用 plugin-http 直连(Rust 侧请求,不受 CORS 限制)
const r2 = wIsTauri()
? await wTauri.http.fetch(su)
: await fetch('/api/img?url=' + encodeURIComponent(su), { mode: 'cors' })
if (r2.ok) { downloadBlob(await r2.blob()); wDownloadToast(wIsTauri() ? '已通过原生 HTTP 取图保存' : '该图床不支持直连下载,已通过本站代理保存'); return }
} catch (e) { /* 继续兜底 */ }
// ④ 最后兜底:新标签打开(右键/长按另存)——绝不静默失败
try {
@@ -4437,7 +4486,8 @@ const tbCenterSeed = (type, refs) => {
if (!Derive || typeof Derive.create !== 'function' || typeof document === 'undefined') return v
previewPending.add(key)
// 跨域图必须走同源代理(否则 fetch 必失败 ⇒ 负缓存后等于没做 ✗,见 §8.3 坑 2)
const viaUrl = (/^https?:\/\//i.test(v) && (typeof location === 'undefined' || v.indexOf(location.origin + '/') !== 0))
// 桌面端没有 /api/img 代理:不给 viaUrl,让派生器直连(失败即负缓存并回退原图,不影响显示)
const viaUrl = (/^https?:\/\//i.test(v) && (typeof location === 'undefined' || v.indexOf(location.origin + '/') !== 0) && !wIsTauri())
? (location.origin + '/api/img?url=' + encodeURIComponent(v)) : undefined
let inst = null
try { inst = Derive.create({ maxEdge: PREVIEW_MAX_EDGE, quality: 0.82 }) } catch (e) { inst = null }
@@ -4478,7 +4528,9 @@ const tbCenterSeed = (type, refs) => {
displayThumbs.set(key, val)
}
const isRemoteHttp = /^https?:\/\//i.test(v) && (typeof location === 'undefined' || v.indexOf(location.origin + '/') !== 0)
img.src = isRemoteHttp ? (location.origin + '/api/img?url=' + encodeURIComponent(v)) : v
// 桌面端没有代理:直接给原地址(<img> 不受 CORS 限制,能正常显示;canvas 降采样失败会回退原图)
img.src = (isRemoteHttp && wIsTauri()) ? v
: (isRemoteHttp ? (location.origin + '/api/img?url=' + encodeURIComponent(v)) : v)
img.onload = () => {
try {
const iw = img.naturalWidth || 0, ih = img.naturalHeight || 0
@@ -5074,6 +5126,8 @@ const tbCenterSeed = (type, refs) => {
const wOpenZipBlob = (blob) => _zipFn('wOpenZipBlob')(blob)
const wCreateStoreZip = () => _zipFn('wCreateStoreZip')()
function wDownloadBlob(blob, name) {
// 备份/导出统一走同一个出口:桌面端弹系统另存为,网页端仍用 <a download>
if (typeof window !== 'undefined' && window.__IWB_SAVE_BLOB__) { window.__IWB_SAVE_BLOB__(blob, name); return }
const a = document.createElement('a')
a.href = URL.createObjectURL(blob)
a.download = name
@@ -5770,7 +5824,10 @@ const tbCenterSeed = (type, refs) => {
})
const meta = (typeof window !== 'undefined' && window.__IWB_BUILD_META__) || {}
const text = buildRuntimeDiagnosticsText(tasks, meta)
const blob = new Blob([text], { type: 'application/json' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'image-workbench-diagnostics-' + new Date().toISOString().slice(0, 10) + '.json'; document.body.appendChild(a); a.click(); document.body.removeChild(a); setTimeout(() => URL.revokeObjectURL(url), 5000)
const blob = new Blob([text], { type: 'application/json' })
const fileName = 'image-workbench-diagnostics-' + new Date().toISOString().slice(0, 10) + '.json'
// 统一出口:桌面端原生另存为,网页端 <a download>
window.__IWB_SAVE_BLOB__(blob, fileName)
showToast('已导出运行诊断(不含 Key、提示词和图片)')
} catch (e) { setNotice({ type: 'err', text: '诊断导出失败:' + String((e && e.message) || e) }) }
}
@@ -7213,7 +7270,13 @@ const tbCenterSeed = (type, refs) => {
// C3 第2步:节点组导出同样要自带字节(按需解析,不写回画布)
const nodesForExport = await wResolveImagesForExport(withoutGenerationResults({ nodes: selectedNodes }).nodes)
const data = { app: 'image-workbench', version: 2, schemaVersion: SchemaVersions.canvas, exportType: 'group', exportedAt: new Date().toISOString(), exportSummary: { nodes: selectedNodes.length, edges: selectedEdges.length, groups: completeGroups.length }, group: Object.assign({ id: uid('g'), name: safeName, memberIds: sel.slice() }, exportedGroupPad ? { pad: exportedGroupPad } : null), groups: completeGroups, nodes: nodesForExport, edges: selectedEdges }
try { const blob = new Blob([JSON.stringify(data, null, 1)], { type: 'application/json' }); const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = safeName.replace(/\\.iwb\\.json$/i, '') + '.iwb.json'; document.body.appendChild(a); a.click(); document.body.removeChild(a); setTimeout(() => URL.revokeObjectURL(a.href), 5000); setNotice({ type: 'ok', text: '已导出节点组:' + a.download }) } catch (e) { setNotice({ type: 'err', text: '导出节点组失败:' + String((e && e.message) || e) }) }
try {
const blob = new Blob([JSON.stringify(data, null, 1)], { type: 'application/json' })
const outName = safeName.replace(/\\.iwb\\.json$/i, '') + '.iwb.json'
// 统一出口:桌面端弹系统另存为,网页端仍走 <a download>
window.__IWB_SAVE_BLOB__(blob, outName)
setNotice({ type: 'ok', text: '已导出节点组:' + outName })
} catch (e) { setNotice({ type: 'err', text: '导出节点组失败:' + String((e && e.message) || e) }) }
} })
}
// importCanvasFile 已搬到 src/runtime-workbench-logic.js(2026-10-29)
+4 -1
View File
@@ -4,7 +4,10 @@
"version": "3.24.85",
"description": "Browser-based node canvas image workbench",
"scripts": {
"build": "node scripts/build.js",
"build": "node scripts/build.js && node scripts/copy-plugins.js",
"tauri": "tauri",
"app:dev": "tauri dev",
"app:build": "tauri build",
"lint": "eslint src app.js",
"test": "node tests/relay-task-graph-fixture-test.js && node tests/plugin-style-node-test.js && node tests/inherit-text-test.js && node tests/iwb-v32-web-test.js",
"test:unit": "node tests/unit-test.js && node tests/canvas-actions-test.js && node tests/canvas-performance-test.js && node tests/canvas-drag-performance-test.js && node tests/resize-observer-performance-test.js && node tests/node-drag-jank-test.js && node tests/edge-graph-performance-test.js && node tests/persistence-export-images-test.js && node tests/settings-hotkeys-size-presets-test.js && node tests/custom-size-validation-test.js && node tests/image-node-performance-test.js && node tests/drag-frame-performance-test.js && node tests/canvas-edge-memo-test.js && node tests/canvas-node-transform-test.js && node tests/canvas-dot-zoom-test.js && node tests/duplicate-ws-fresh-source-test.js && node tests/single-canvas-shell-test.js && node tests/navigation-layout-test.js && node tests/home-canvas-library-test.js && node tests/left-resource-layout-test.js && node tests/interface-hierarchy-test.js && node tests/three-page-layout-test.js && node tests/page-chrome-regression-test.js && node tests/task-cache-test.js && node tests/storage-config-shape-test.js && node tests/storage-zip-test.js && node tests/canvas-node-factory-test.js && node tests/runtime-error-test.js && node tests/runtime-lifecycle-test.js && node tests/runtime-fetch-test.js && node tests/runtime-channel-test.js && node tests/runtime-boundary-test.js && node tests/runtime-record-test.js && node tests/runtime-recovery-test.js && node tests/runtime-diagnostic-record-test.js && node tests/runtime-metrics-test.js && node tests/runtime-run-context-test.js && node tests/runtime-execution-context-test.js && node tests/storage-health-test.js && node tests/generation-state-test.js && node tests/canvas-store-test.js && node tests/storage-result-test.js && node tests/storage-local-test.js && node tests/storage-domain-test.js && node tests/storage-runtime-test.js && node tests/storage-indexeddb-test.js && node tests/generation-scheduler-test.js && node tests/gallery-query-test.js && node tests/gallery-hydration-test.js && node tests/image-blob-store-test.js && node tests/image-preview-derive-test.js && node tests/image-format-test.js && node tests/clipboard-graph-test.js && node tests/image-admit-test.js && node tests/image-dedupe-test.js && node tests/clipboard-kind-test.js && node tests/clipboard-paste-test.js && node tests/clipboard-copy-test.js && node tests/paste-once-test.js && node tests/list-e2e-specs-test.js && node tests/architecture-boundary-guard-test.js && node tests/plugin-host-test.js && node tests/image-compress-test.js && node tests/storage-fallback-indexeddb-test.js && node tests/canvas-normalize-test.js && node tests/canvas-geometry-test.js && node tests/canvas-history-test.js && node tests/canvas-ops-test.js && node tests/canvas-text-test.js && node tests/history-store-test.js && node tests/plugin-integrity-test.js && node tests/workspace-sessions-store-test.js && node tests/workspace-list-test.js && node tests/workspace-purge-test.js && node tests/provider-ping-test.js && node tests/ui-groups-sidebar-test.js && node tests/ui-lib-sidebar-test.js && node tests/runtime-diagnostics-hotpath-test.js && node tests/storage-log-failure-test.js && node tests/storage-convergence-test.js && node tests/swallow-wiring-test.js && node tests/workbench-logic-test.js && node tests/storage-autobackup-test.js && node tests/storage-outputs-mutate-test.js && node tests/sync-facts-guard-test.js && node tests/e2e-fixed-waits-ratchet-test.js && node tests/shell-render-behavior-test.js && node tests/canvas-meta-notice-behavior-test.js && node tests/source-text-ratchet-test.js && node tests/functions-api-test.js && node tests/prompt-md-roundtrip-test.js && node tests/generation-results-store-test.js && node tests/out-groups-order-test.js && node tests/ui-workbench-hooks-test.js",
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,137 @@
// iwb-plugin: 空白画布 —— 给「空白的参考图节点」填入指定尺寸(1K)的纯白图片,作为插图/标注的起点。
// 移植自 iwb-plaus 仓库 iwb-cutout-extension:src/content.js 的 BLANK_RATIOS / performBlankCanvas / showBlankMenu。
// 有意差异:只保留 1K 档(上游菜单实际也只用 1K);只填当前节点(不新建);不联动编辑器。
;(function (global) {
'use strict'
// 与宿主 app.js 的 RATIOS 表 1K 档逐字一致。插件不能 import 宿主内部,故照抄数值;
// 上游扩展也是这么做的(BLANK_RATIOS 抄自宿主)。
var SIZES = [
{ label: '1:1 方形', w: 1024, h: 1024 },
{ label: '2:3 竖版', w: 832, h: 1248 },
{ label: '3:2 横版', w: 1248, h: 832 },
{ label: '3:4 竖版', w: 880, h: 1168 },
{ label: '4:3 横版', w: 1184, h: 880 },
{ label: '4:5 竖版', w: 912, h: 1136 },
{ label: '5:4 横版', w: 1136, h: 896 },
{ label: '9:16 竖版', w: 768, h: 1360 },
{ label: '16:9 横版', w: 1360, h: 752 },
{ label: '21:9 超宽', w: 1552, h: 656 },
{ label: '9:21 超宽竖版', w: 656, h: 1520 },
]
var CSS = [
'.iwb-blankcanvas-menu{position:fixed;left:50%;top:64px;transform:translateX(-50%);z-index:2147483000;',
'width:312px;padding:10px;border-radius:10px;box-sizing:border-box;',
'background:var(--iwb-panel,#fff);color:var(--iwb-text,#1c2333);',
'border:1px solid var(--iwb-border,#d5d9e0);box-shadow:0 12px 32px rgba(0,0,0,.28);',
'font:12px/1.4 system-ui,-apple-system,"PingFang SC",sans-serif}',
'.iwb-blankcanvas-title{font-weight:600;margin:2px 2px 8px}',
'.iwb-blankcanvas-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:6px}',
'.iwb-blankcanvas-item{display:flex;flex-direction:column;align-items:center;gap:2px;padding:8px 4px;',
'border-radius:8px;border:1px solid var(--iwb-border,#d5d9e0);background:var(--iwb-layer,#f0f1f4);',
'color:inherit;font:inherit;cursor:pointer}',
'.iwb-blankcanvas-item:hover{background:var(--iwb-layer2,#fff)}',
'.iwb-blankcanvas-item b{font-weight:600}',
'.iwb-blankcanvas-item i{font-style:normal;font-size:11px;color:var(--iwb-text2,#4d5668)}',
].join('')
global.IWBPluginHost.register({
id: 'blank-canvas',
name: '空白画布',
version: '1.0.0',
apiVersion: 1,
capabilities: ['nodeActions', 'canvas', 'canvasWrite'],
}, function (ctx) {
var STYLE_ID = 'iwb-blankcanvas-style'
var menuEl = null
var outsideHandler = null
function injectStyle() {
if (document.getElementById(STYLE_ID)) return
var style = document.createElement('style')
style.id = STYLE_ID
style.textContent = CSS
;(document.head || document.documentElement).appendChild(style)
}
// 与上游 isEmptyRefNode 等价:ref 节点且既无本地数据也无 URL({__blob}/{__cache} 引用是对象,天然为真)
function isEmptyImageNode(node) {
if (!node || node.type !== 'ref') return false
var d = node.data || {}
return !d.data && !d.url
}
function whitePng(w, h) {
var canvas = document.createElement('canvas')
canvas.width = w
canvas.height = h
var ctx2d = canvas.getContext('2d')
ctx2d.fillStyle = '#ffffff'
ctx2d.fillRect(0, 0, w, h)
return canvas.toDataURL('image/png')
}
function closeMenu() {
if (menuEl && menuEl.parentNode) menuEl.parentNode.removeChild(menuEl)
menuEl = null
if (outsideHandler) { document.removeEventListener('pointerdown', outsideHandler, true); outsideHandler = null }
document.removeEventListener('keydown', onKeyDown, true)
}
function onKeyDown(e) { if (e.key === 'Escape') closeMenu() }
function apply(nodeId, w, h) {
var nodes = (ctx.canvas && typeof ctx.canvas.getNodes === 'function') ? ctx.canvas.getNodes() : []
var target = null
for (var i = 0; i < nodes.length; i++) if (nodes[i] && nodes[i].id === nodeId) target = nodes[i]
if (!target || !isEmptyImageNode(target)) throw new Error('该节点不是空白的图片节点')
// 宿主把 canvasWrite 的 API 合并进 ctx.canvas(plugin-host.js 的 CAPABILITY_API_KEYS)⇒ 写接口在 ctx.canvas 上
if (!ctx.canvas.setNodeImage(nodeId, whitePng(w, h))) throw new Error('写入节点失败')
}
function openMenu(nodeId) {
injectStyle()
closeMenu()
var menu = document.createElement('div')
menu.className = 'iwb-blankcanvas-menu'
var title = document.createElement('div')
title.className = 'iwb-blankcanvas-title'
title.textContent = '创建空白画布(1K)'
menu.appendChild(title)
var grid = document.createElement('div')
grid.className = 'iwb-blankcanvas-grid'
SIZES.forEach(function (size) {
var btn = document.createElement('button')
btn.type = 'button'
btn.className = 'iwb-blankcanvas-item'
btn.setAttribute('data-size', size.w + 'x' + size.h)
btn.innerHTML = '<b>' + size.label + '</b><i>' + size.w + '×' + size.h + '</i>'
btn.addEventListener('pointerdown', function (e) { e.stopPropagation() })
btn.addEventListener('click', function (e) {
e.stopPropagation()
e.preventDefault()
closeMenu()
apply(nodeId, size.w, size.h)
})
grid.appendChild(btn)
})
menu.appendChild(grid)
document.body.appendChild(menu)
menuEl = menu
outsideHandler = function (e) { if (!menuEl || !menuEl.contains(e.target)) closeMenu() }
document.addEventListener('pointerdown', outsideHandler, true)
document.addEventListener('keydown', onKeyDown, true)
}
ctx.nodeActions.register({
id: 'blank-canvas-open',
title: '空白画布',
icon: 'plus',
appliesTo: function (node) { return isEmptyImageNode(node) },
run: function (node) { openMenu(node.id); return true },
})
return { dispose: closeMenu }
})
})(typeof window !== 'undefined' ? window : globalThis)
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,313 @@
// iwb-plugin: 白底图 —— 把选中节点的图等比缩放、居中合成到正方形画布,按设置的格式/质量/体积上限编码,
// 输出 <name>_<size>x<size>.<ext>(默认 800×800 白底 jpeg,≤500KB;可开双版本一次出透明 PNG + 白底 JPG)。
// 移植自 iwb-plaus 仓库 iwb-cutout-extension:src/shared/image-math.js 的 fitRect + src/content.js 的 makeWhiteBgImage / performWhiteBg;
// 几何与合成算法逐字对齐上游,只有宿主胶水(IWBPluginHost 注册 / ctx 调用)与导出编码是新写的。
;(function (global) {
'use strict'
// 上游 shared/image-math.js 的 clamp
function clamp(v, min, max) {
return Math.max(min, Math.min(max, v))
}
// 上游 shared/image-math.js 的 fitRect:内容最长边 = min(boxW, boxH) * ratio,等比缩放并居中(不裁剪)
function fitRect(srcW, srcH, boxW, boxH, ratio) {
if (!(srcW > 0) || !(srcH > 0) || !(boxW > 0) || !(boxH > 0)) {
return { x: 0, y: 0, w: 0, h: 0, scale: 0 }
}
var r = Math.max(0.01, Math.min(1, ratio))
var maxLen = Math.min(boxW, boxH) * r
var scale = Math.min(maxLen / srcW, maxLen / srcH)
var w = srcW * scale
var h = srcH * scale
return { x: (boxW - w) / 2, y: (boxH - h) / 2, w: w, h: h, scale: scale }
}
function loadImage(src) {
return new Promise(function (resolve, reject) {
var img = new Image()
img.onload = function () { resolve(img) }
img.onerror = function () { reject(new Error('图片解码失败')) }
img.src = src
})
}
// ---------- 编码 ----------
// png 无损(无质量参数);jpeg/webp 有损且有质量参数;webp 另外保留 alpha。
var FORMATS = {
png: { mime: 'image/png', ext: 'png', lossy: false, alpha: true },
jpeg: { mime: 'image/jpeg', ext: 'jpg', lossy: true, alpha: false },
webp: { mime: 'image/webp', ext: 'webp', lossy: true, alpha: true },
}
// toBlob 的 blob.type 才是真实产出格式(浏览器不支持 webp 时会静默回退 png),命名按它走。
var TYPE_EXT = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp' }
// 双版本固定产出:透明 PNG(无损、保 alpha)+ 白底 JPG(有损、体积可控)—— 电商平台两种图都要。
// png 那种允许超上限(透明图是必需产物,PNG 无压缩参数,压不下去只能照常输出并记日志)。
var DUAL_TARGETS = [
{ format: 'png', transparent: true, allowOversize: true },
{ format: 'jpeg', transparent: false, allowOversize: false },
]
// 导出格式设置是 text 输入框(宿主设置面板只有 text/number/boolean),这里做容错归一化。
function normalizeFormat(raw) {
var s = String(raw === undefined || raw === null ? '' : raw).trim().toLowerCase().replace(/^\./, '')
if (s === 'jpg' || s === 'jpeg' || s === 'jpe') return 'jpeg'
if (s === 'png' || s === 'webp') return s
return ''
}
// dataURL 的字节数(仅在 canvas.toBlob 缺失时的退路;正常路径用 blob.size,精确且无 base64 开销)
function dataUrlBytes(url) {
var s = String(url || '')
var comma = s.indexOf(',')
if (comma < 0) return 0
var body = s.length - comma - 1
var pad = s.charAt(s.length - 1) === '=' ? (s.charAt(s.length - 2) === '=' ? 2 : 1) : 0
return Math.max(0, Math.floor(body * 3 / 4) - pad)
}
function blobToDataUrl(blob) {
return new Promise(function (resolve, reject) {
var reader = new FileReader()
reader.onload = function () { resolve(String(reader.result || '')) }
reader.onerror = function () { reject(reader.error || new Error('读取编码结果失败')) }
reader.readAsDataURL(blob)
})
}
// 编码一次,产出 { dataUrl, size, type }
function encodeOnce(canvas, mime, quality) {
return new Promise(function (resolve, reject) {
if (typeof canvas.toBlob !== 'function') {
var url = canvas.toDataURL(mime, quality)
resolve({ dataUrl: url, size: dataUrlBytes(url), type: mime })
return
}
try {
canvas.toBlob(function (blob) {
if (!blob) { reject(new Error('图片编码失败')); return }
blobToDataUrl(blob).then(function (dataUrl) {
resolve({ dataUrl: dataUrl, size: blob.size, type: String(blob.type || mime) })
}, reject)
}, mime, quality)
} catch (error) {
reject(error)
}
})
}
function kb(bytes) {
return (Math.round(bytes / 1024 * 10) / 10) + 'KB'
}
// 体积上限:先按用户质量编码;超限就有损格式向下二分找「能进上限的最高质量」。
// 有损质量下限固定 0.2:再低画质不可用,此时报错而不是偷偷改边长(800×800 是硬规范)。
var MIN_QUALITY = 0.2
async function encodeWithLimit(canvas, format, quality, maxBytes) {
var spec = FORMATS[format]
var first = await encodeOnce(canvas, spec.mime, quality)
if (!maxBytes || first.size <= maxBytes) return first
if (!spec.lossy) {
throw new Error(
'PNG 体积 ' + kb(first.size) + ' 超过上限 ' + kb(maxBytes) +
':浏览器导出 PNG 无法调压缩级别 —— 请把「导出格式」改成 jpeg / webp,或调大「体积上限」'
)
}
var floor = await encodeOnce(canvas, spec.mime, MIN_QUALITY)
if (floor.size > maxBytes) {
throw new Error(
'已压到质量 20 仍有 ' + kb(floor.size) + ',超过上限 ' + kb(maxBytes) +
':请调小「大图边长」或调大「体积上限」'
)
}
var lo = MIN_QUALITY
var hi = quality
var pick = floor
for (var i = 0; i < 6 && hi - lo > 0.01; i++) {
var mid = (lo + hi) / 2
var cur = await encodeOnce(canvas, spec.mime, mid)
if (cur.size <= maxBytes) {
pick = cur
lo = mid
} else {
hi = mid
}
}
return pick
}
global.IWBPluginHost.register({
id: 'white-bg-800',
name: '白底图',
version: '1.2.1',
apiVersion: 1,
capabilities: ['commands', 'canvas', 'canvasWrite', 'nodeActions'],
settings: {
bgSize: { type: 'number', label: '大图边长(像素)', desc: '默认 800;允许 64–4096,越界自动夹取。', default: 800 },
ratioPct: { type: 'number', label: '内容占比(%)', desc: '内容等比缩放后占边长的百分比,默认 80(=640/800,电商主图规范);允许 10–100。', default: 80 },
dual: { type: 'boolean', label: '双版本(透明 PNG + 白底 JPG)', desc: '开启=一次生成两个节点:透明底 PNG + 白底 JPG,各一份。此时「导出格式」「透明底」不生效,「覆盖原节点」被忽略(双版本总是新建)。', default: false },
format: { type: 'text', label: '导出格式(单版本)', desc: '填 png / jpeg / webp(jpg 也认),默认 jpeg。png 无损但无压缩参数,体积可能超限。双版本开启时此项不生效。', default: 'jpeg' },
quality: { type: 'number', label: '压缩质量(1–100)', desc: '仅 jpeg / webp 生效,默认 82;超过体积上限时自动向下调(最低 20)。', default: 82 },
maxKB: { type: 'number', label: '体积上限(KB)', desc: '默认 500;填 0 或负数=不限制。按编码后的文件字节数判定。', default: 500 },
transparent: { type: 'boolean', label: '透明底(单版本)', desc: '关闭(默认)=填白底;开启=保留透明通道(jpeg 不支持,会自动改填白底)。双版本开启时此项不生效。', default: false },
replace: { type: 'boolean', label: '覆盖原节点', desc: '关闭(默认)=新建参考图节点;开启=覆盖当前节点。双版本开启时忽略此项。', default: false },
},
}, function (ctx) {
const NO_IMAGE = '该节点没有可编码的图片(请选中带图的参考图或输出节点)'
const REMOTE_FAIL = '远程图片无法读取(可能被跨域限制):请先转存为本地位图'
// 取图:dataUrl 直接赋给 img.src(img-src 放行 data:,不污染画布);
// 绝不对 data: URL 发网络请求 —— 宿主 CSP connect-src 不含 data:,必被拦(姊妹插件 image-annotate 踩过并修掉的坑)。
// 远程 url 才走 fetch,转成 blob: URL 再解码(blob: 同样不污染画布)。
async function resolveImage(nodeId) {
const image = await ctx.canvas.getNodeImage(nodeId)
if (!image) throw new Error(NO_IMAGE)
if (image.dataUrl) return loadImage(image.dataUrl)
if (!image.url) throw new Error(NO_IMAGE)
let resp
try {
resp = await global.fetch(image.url)
} catch (e) {
throw new Error(REMOTE_FAIL)
}
if (!resp.ok) throw new Error(REMOTE_FAIL)
const objUrl = URL.createObjectURL(await resp.blob())
try {
return await loadImage(objUrl)
} catch (e) {
throw new Error(REMOTE_FAIL)
} finally {
URL.revokeObjectURL(objUrl)
}
}
// 合成(对齐上游 makeWhiteBgImage):正方形画布,白底或透明底,fitRect 等比缩放居中、不裁剪
function composeCanvas(img, size, ratio, transparent) {
const canvas = document.createElement('canvas')
canvas.width = size
canvas.height = size
const ctx2d = canvas.getContext('2d')
if (!transparent) {
ctx2d.fillStyle = '#ffffff'
ctx2d.fillRect(0, 0, size, size)
}
const rect = fitRect(img.naturalWidth || img.width, img.naturalHeight || img.height, size, size, ratio)
ctx2d.drawImage(img, rect.x, rect.y, rect.w, rect.h)
return canvas
}
// allowOversize 只给双版本的透明 PNG 用:透明图是必需产物,PNG 又无压缩参数,
// 超限也只能照常输出(记日志),不能因为一个版本超限就让另一个版本也出不来。
async function encodeTarget(canvas, format, quality, maxBytes, allowOversize) {
if (allowOversize && !FORMATS[format].lossy) {
const res = await encodeOnce(canvas, FORMATS[format].mime, 1)
if (maxBytes && res.size > maxBytes) {
ctx.log('white-bg: 透明 PNG 为 ' + kb(res.size) + ',超过上限 ' + kb(maxBytes) + '(PNG 无压缩参数,已照常输出)')
}
return res
}
return encodeWithLimit(canvas, format, quality, maxBytes)
}
// 命名用真实边长与真实编码格式(上游 autoWhiteBg 分支硬编码 _800x800 是 bug,这里按夹取后的实际边长命名;
// 扩展名同理取 blob.type —— 浏览器不支持 webp 时会回退 png,不能照抄设置值)
function outName(base, size, encoded, format) {
const ext = TYPE_EXT[encoded.type] || FORMATS[format].ext
return base + '_' + size + 'x' + size + '.' + ext
}
function readNumeric(key, fallback, min, max) {
return clamp(Number(ctx.settings.get(key)) || fallback, min, max)
}
async function runOne(nodeId, nodeName) {
const img = await resolveImage(nodeId)
// 宿主可能把数值设置存成字符串,统一强转再夹取
const size = Math.round(readNumeric('bgSize', 800, 64, 4096))
const ratio = readNumeric('ratioPct', 80, 10, 100) / 100
const quality = readNumeric('quality', 82, 1, 100) / 100
const maxKB = Number(ctx.settings.get('maxKB'))
const maxBytes = Number.isFinite(maxKB) && maxKB > 0 ? Math.round(maxKB * 1024) : 0
const dual = Boolean(ctx.settings.get('dual'))
const replace = Boolean(ctx.settings.get('replace'))
const base = String(nodeName || 'image').replace(/\.[^.]+$/, '') || 'image'
let targets
if (dual) {
// 双版本下「覆盖原节点」没意义(两个版本只能覆盖一个位置),按文档忽略并留痕
if (replace) ctx.log('white-bg: 双版本模式总是新建节点,「覆盖原节点」已忽略')
targets = DUAL_TARGETS
} else {
const rawFormat = ctx.settings.get('format')
let format = normalizeFormat(rawFormat)
if (!format) {
ctx.log('white-bg: 未知导出格式 ' + JSON.stringify(String(rawFormat)) + ',回退 jpeg(可选 png / jpeg / webp)')
format = 'jpeg'
}
// 透明底与不支持的格式冲突:jpeg 没有 alpha 通道,用它画透明底会变成黑块 —— 强制填白并留痕。
const wantsTransparent = Boolean(ctx.settings.get('transparent'))
const transparent = wantsTransparent && FORMATS[format].alpha
if (wantsTransparent && !FORMATS[format].alpha) {
ctx.log('white-bg: ' + format + ' 不支持透明通道,已自动改填白底')
}
targets = [{ format: format, transparent: transparent, allowOversize: false }]
}
const made = []
const errors = []
for (const target of targets) {
try {
const canvas = composeCanvas(img, size, ratio, target.transparent)
const encoded = await encodeTarget(canvas, target.format, quality, maxBytes, target.allowOversize)
const name = outName(base, size, encoded, target.format)
if (replace && !dual) {
if (!ctx.canvas.setNodeImage(nodeId, encoded.dataUrl)) throw new Error('写回画布失败')
made.push('覆盖当前节点')
} else {
const created = ctx.canvas.createImageNode({ dataUrl: encoded.dataUrl, name: name })
if (!created) throw new Error('写回画布失败')
made.push(name)
}
ctx.log('white-bg: ' + name + ' ' + kb(encoded.size))
} catch (error) {
errors.push(error && error.message ? error.message : String(error))
}
}
if (!made.length && errors.length) throw new Error(errors[0])
// 部分成功:节点已经建好了,但要把失败原因说清楚(宿主只把 throw 显示成红色提示,这是唯一通道)
if (errors.length) throw new Error(errors.join(';') + '(已生成:' + made.join('、') + ')')
return dual ? made : (replace ? true : made[0])
}
ctx.nodeActions.register({
id: 'white-bg-node',
title: '白底图',
icon: 'vector-square',
appliesTo: function (node) { return Boolean(node) && node.type === 'ref' },
run: function (node) { return runOne(node.id, node.name) },
})
ctx.commands.register({
id: 'white-bg-selected',
title: '白底图:选中节点',
icon: 'vector-square',
run: function () {
const selected = ctx.canvas.getSelectedNode()
if (!selected) return Promise.reject(new Error('请先选中一个带图的节点'))
return runOne(selected.id, selected.name)
},
})
return {}
})
})(typeof window !== 'undefined' ? window : globalThis)
@@ -0,0 +1,107 @@
// iwb-plugin: 鲜艺抠图 —— 调用本机抠图服务(POST {apiUrl}/rmbg?crop=)把选中节点的图抠成透明底,写回为新的参考图节点。
// 契约来源:iwb-plaus v3.1.3 的 background.js(二进制进、PNG 字节出,无 token/无 JSON)。
;(function (global) {
'use strict'
var DEFAULT_API = 'http://localhost:30092'
var DEFAULT_TIMEOUT = 120000
function toPositive(v, fallback) {
var n = Number(v)
return Number.isFinite(n) && n > 0 ? n : fallback
}
function trimUrl(v) {
return String(v || DEFAULT_API).trim().replace(/\/+$/, '') || DEFAULT_API
}
function base64ToBytes(dataUrl) {
var s = String(dataUrl || '')
var comma = s.indexOf(',')
var bin = global.atob(comma >= 0 ? s.slice(comma + 1) : s)
var out = new Uint8Array(bin.length)
for (var i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)
return out
}
function bytesToDataUrl(buffer) {
var bytes = new Uint8Array(buffer)
var chunk = 0x8000
var text = ''
for (var i = 0; i < bytes.length; i += chunk) {
text += String.fromCharCode.apply(null, bytes.subarray(i, i + chunk))
}
return 'data:image/png;base64,' + global.btoa(text)
}
global.IWBPluginHost.register({
id: 'xianyi-cutout',
name: '鲜艺抠图',
version: '1.0.3',
apiVersion: 1,
capabilities: ['commands', 'canvas', 'canvasWrite', 'nodeActions'],
settings: {
apiUrl: { type: 'text', label: '本地服务地址', desc: 'CSP 仅放行 127.0.0.1 / localhost 的 30092 端口;改到别的 host 或端口会被拦。', default: DEFAULT_API },
crop: { type: 'boolean', label: '抠图后裁掉多余透明像素', desc: '对应接口的 crop 参数,默认开启。', default: true },
timeoutMs: { type: 'number', label: '超时(毫秒)', desc: '原扩展没有超时;这里补上,避免服务无响应时永久挂起。', default: DEFAULT_TIMEOUT },
},
}, function (ctx) {
async function cutoutOne(nodeId) {
const image = await ctx.canvas.getNodeImage(nodeId)
if (!image || !image.dataUrl) throw new Error('该节点没有可编码的图片(请选中带图的参考图或输出节点)')
const apiUrl = trimUrl(ctx.settings.get('apiUrl'))
const crop = ctx.settings.get('crop') ? 'true' : 'false'
const timeoutMs = toPositive(ctx.settings.get('timeoutMs'), DEFAULT_TIMEOUT)
const controller = typeof global.AbortController === 'function' ? new global.AbortController() : null
const timer = controller ? global.setTimeout(function () { try { controller.abort() } catch (e) { /* ignore */ } }, timeoutMs) : null
let response
try {
response = await global.fetch(apiUrl + '/rmbg?crop=' + crop, {
method: 'POST',
headers: { 'Content-Type': 'application/octet-stream' },
body: base64ToBytes(image.dataUrl),
signal: controller ? controller.signal : undefined,
})
} catch (e) {
throw new Error('连不上本地抠图服务(' + apiUrl + '):' + String((e && e.message) || e))
} finally {
if (timer) global.clearTimeout(timer)
}
if (!response.ok) {
const detail = await response.text().catch(function () { return '' })
throw new Error('抠图服务返回 ' + response.status + (detail ? ':' + String(detail).slice(0, 120) : ''))
}
const dataUrl = bytesToDataUrl(await response.arrayBuffer())
const selected = ctx.canvas.getSelectedNode()
const base = String((selected && selected.name) || 'image').replace(/\.[^.]+$/, '') || 'image'
const created = ctx.canvas.createImageNode({ dataUrl: dataUrl, name: base + '_cutout.png' })
if (!created) throw new Error('写回画布失败')
return created
}
ctx.commands.register({
id: 'cutout-selected',
title: '抠图:选中节点',
icon: 'scissors',
run: function () {
const selected = ctx.canvas.getSelectedNode()
if (!selected) return Promise.reject(new Error('请先选中一个带图的节点'))
return cutoutOne(selected.id)
},
})
ctx.nodeActions.register({
id: 'cutout-node',
title: '抠图',
icon: 'scissors',
appliesTo: function (node) { return Boolean(node) && node.type === 'ref' },
run: function (node) { return cutoutOne(node.id) },
})
return {}
})
})(typeof window !== 'undefined' ? window : globalThis)
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env node
'use strict'
// 桌面版专用:把 plugins/runtime/ 下的运行时插件拷进 dist/plugins/。
// 网页版插件由 Cloudflare KV 在 /plugins/* 提供;桌面端没有服务端,只能随包发布。
// 刻意不改 scripts/build.js(上游文件),单独一步执行,保持桌面侧差异最小。
const fs = require('fs')
const path = require('path')
const root = path.resolve(__dirname, '..')
const src = path.join(root, 'plugins', 'runtime')
const dst = path.join(root, 'dist', 'plugins')
if (!fs.existsSync(src)) {
console.error('[copy-plugins] 缺少 plugins/runtime,无法打包运行时插件')
process.exit(1)
}
fs.mkdirSync(dst, { recursive: true })
let count = 0
for (const name of fs.readdirSync(src)) {
fs.copyFileSync(path.join(src, name), path.join(dst, name))
count++
}
// 索引与插件文件必须同源同包:应用按 index.json 里的 filename 去 /plugins/ 取
fs.copyFileSync(path.join(root, 'plugins', 'index.json'), path.join(dst, 'index.json'))
console.log('[copy-plugins] 已拷入 ' + count + ' 个插件 → dist/plugins/')
+38
View File
@@ -0,0 +1,38 @@
<#
一次性环境检查(Windows)。不自动安装任何东西,只报告缺什么。
用法:右键「使用 PowerShell 运行」,或 powershell -ExecutionPolicy Bypass -File scripts\windows-check.ps1
#>
$ErrorActionPreference = 'Continue'
function Show($name, $ok, $hint) {
if ($ok) { Write-Host ("[OK] " + $name) -ForegroundColor Green }
else { Write-Host ("[缺失] " + $name + " -> " + $hint) -ForegroundColor Yellow }
}
# Node
$node = (Get-Command node -ErrorAction SilentlyContinue)
Show "Node.js" ($null -ne $node) "winget install OpenJS.NodeJS.LTS"
# Rust
$rustc = (Get-Command rustc -ErrorAction SilentlyContinue)
Show "Rust (rustc)" ($null -ne $rustc) "winget install Rustlang.Rustup"
if ($rustc) {
$v = (& rustc -V) -join ' '
Write-Host (" " + $v)
if ($v -notmatch 'msvc') {
Write-Host " [!] 当前工具链不是 MSVC,请执行: rustup default stable-msvc" -ForegroundColor Yellow
}
}
# MSVC 链接器
$link = Get-ChildItem "C:\Program Files (x86)\Microsoft Visual Studio" -Recurse -Filter link.exe -ErrorAction SilentlyContinue | Select-Object -First 1
Show "MSVC Build Tools (link.exe)" ($null -ne $link) "安装 VS 2022 Build Tools 并勾选「使用 C++ 的桌面开发」"
# WebView2
$wv = Get-ItemProperty "HKLM:\SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}" -ErrorAction SilentlyContinue
Show "WebView2 Runtime" ($null -ne $wv) "winget install Microsoft.EdgeWebView2Runtime(Win11 一般自带)"
Write-Host ""
Write-Host "全部 OK 后执行:" -ForegroundColor Cyan
Write-Host " npm ci"
Write-Host " npm run app:build"
+15 -15
View File
@@ -64,21 +64,6 @@ version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
[[package]]
name = "app"
version = "0.1.0"
dependencies = [
"log",
"serde",
"serde_json",
"tauri",
"tauri-build",
"tauri-plugin-dialog",
"tauri-plugin-fs",
"tauri-plugin-http",
"tauri-plugin-log",
]
[[package]]
name = "atk"
version = "0.18.2"
@@ -1660,6 +1645,21 @@ dependencies = [
"icu_properties",
]
[[package]]
name = "image-workbench"
version = "3.24.85"
dependencies = [
"log",
"serde",
"serde_json",
"tauri",
"tauri-build",
"tauri-plugin-dialog",
"tauri-plugin-fs",
"tauri-plugin-http",
"tauri-plugin-log",
]
[[package]]
name = "indexmap"
version = "1.9.3"
+7 -7
View File
@@ -1,8 +1,8 @@
[package]
name = "app"
version = "0.1.0"
description = "A Tauri App"
authors = ["you"]
name = "image-workbench"
version = "3.24.85"
description = "无限画布 · 生图工作台桌面版"
authors = ["malongan"]
license = ""
repository = ""
edition = "2024"
@@ -11,17 +11,17 @@ rust-version = "1.90"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
name = "app_lib"
name = "image_workbench_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2.7.4" }
tauri-build = { version = "2.7.4", features = [] }
[dependencies]
serde_json = "1.0"
serde = { version = "1.0", features = ["derive"] }
log = "0.4"
tauri = { version = "2.12.5" }
tauri = { version = "2.12.5", features = [] }
tauri-plugin-log = "2"
tauri-plugin-dialog = "2"
tauri-plugin-fs = "2"
+35 -4
View File
@@ -1,14 +1,45 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "enables the default permissions",
"description": "主窗口最小能力集:原生另存为 + 写文件 + 白名单取图",
"windows": [
"main"
],
"permissions": [
"core:default",
"dialog:default",
"fs:default",
"http:default"
"fs:allow-write-file",
{
"identifier": "http:default",
"allow": [
{
"url": "https://*.volces.com/**"
},
{
"url": "https://*.aliyuncs.com/**"
},
{
"url": "https://*.myqcloud.com/**"
},
{
"url": "https://*.qiniucdn.com/**"
},
{
"url": "https://*.cloudfront.net/**"
},
{
"url": "https://*.googleusercontent.com/**"
},
{
"url": "https://*.openai.org/**"
},
{
"url": "https://*.oaistatic.com/**"
},
{
"url": "https://*.blob.core.windows.net/**"
}
]
}
]
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

After

Width:  |  Height:  |  Size: 8.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.0 KiB

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

After

Width:  |  Height:  |  Size: 9.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 1006 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.3 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.9 KiB

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.4 KiB

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.9 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
<background android:drawable="@color/ic_launcher_background"/>
</adaptive-icon>
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#FFFFFF</color>
</resources>
Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 37 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 49 KiB

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 680 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 992 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 KiB

+1 -1
View File
@@ -2,5 +2,5 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
app_lib::run();
image_workbench_lib::run();
}
+16 -10
View File
@@ -1,39 +1,45 @@
{
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
"productName": "image-workbench",
"version": "0.1.0",
"identifier": "com.tauri.dev",
"version": "3.24.85",
"identifier": "com.malongan.imageworkbench",
"build": {
"frontendDist": "../dist",
"beforeDevCommand": "npm run build",
"beforeBuildCommand": "npm run build"
},
"app": {
"withGlobalTauri": true,
"windows": [
{
"label": "main",
"title": "无限画布",
"width": 800,
"height": 600,
"width": 1440,
"height": 900,
"minWidth": 1024,
"minHeight": 640,
"resizable": true,
"fullscreen": false
"fullscreen": false,
"center": true,
"dragDropEnabled": false
}
],
"security": {
"csp": null
"csp": "default-src 'self'; script-src 'self'; worker-src 'self' blob:; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data:; connect-src 'self' ipc: http://ipc.localhost https: blob: data: http://127.0.0.1:30092 http://localhost:30092 http://127.0.0.1:3425 http://localhost:3425; object-src 'none'; base-uri 'none'; frame-ancestors 'none'"
}
},
"bundle": {
"active": true,
"targets": "all",
"category": "GraphicsAndDesign",
"shortDescription": "无限画布 · 生图工作台",
"longDescription": "节点式无限画布,本地编排与生成图片,支持系统原生另存为。",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/[email protected]",
"icons/icon.icns",
"icons/icon.ico"
],
"android": {
"debugApplicationIdSuffix": ".debug"
}
]
}
}
+10 -3
View File
@@ -2165,9 +2165,16 @@
edges: refs.edges.slice(), groups: refs.groups.map((g) => ({ ...g, memberIds: g.memberIds.slice() })),
}
try {
const blob = new Blob([JSON.stringify(data, null, 1)], { type: 'application/json' }); const a = document.createElement('a')
a.href = URL.createObjectURL(blob); a.download = safeName.replace(/\.iwb\.json$/i, '') + '.iwb.json'; document.body.appendChild(a); a.click(); document.body.removeChild(a)
setTimeout(() => URL.revokeObjectURL(a.href), 5000); setNotice({ type: 'ok', text: '已导出画布:' + a.download })
const blob = new Blob([JSON.stringify(data, null, 1)], { type: 'application/json' })
const outName = safeName.replace(/\.iwb\.json$/i, '') + '.iwb.json'
// 统一出口:桌面端弹系统另存为(原生),网页端仍走 <a download>
if (typeof window !== 'undefined' && window.__IWB_SAVE_BLOB__) window.__IWB_SAVE_BLOB__(blob, outName)
else {
const a = document.createElement('a')
a.href = URL.createObjectURL(blob); a.download = outName; document.body.appendChild(a); a.click(); document.body.removeChild(a)
setTimeout(() => URL.revokeObjectURL(a.href), 5000)
}
setNotice({ type: 'ok', text: '已导出画布:' + outName })
} catch (e) { setNotice({ type: 'err', text: '导出失败:' + String((e && e.message) || e) }) }
} })
return { exportCanvas } // 包装方按对象取用