diff --git a/app.js b/app.js index e43cbc9..7ea2d84 100644 --- a/app.js +++ b/app.js @@ -132,6 +132,8 @@ marketInstalled: wMarketInstalled, marketInstall: wMarketInstall, marketUninstall: wMarketUninstall, + clipboardReadImage: (window.IWBNativeClipboard || {}).readImage, + clipboardWriteImage: (window.IWBNativeClipboard || {}).writeImage, }) } @@ -4083,6 +4085,12 @@ async function copyImageToClipboard(srcOrBlob) { if (!srcOrBlob) throw wCopyError('format', W_COPY_HINT.format) if (!navigator.clipboard || typeof navigator.clipboard.write !== 'function' || typeof ClipboardItem === 'undefined') { + // 桌面端兜底:WKWebView 里 ClipboardItem 常不可用,改走原生 arboard 写图片 + const D = (typeof window !== 'undefined') ? window.IWBDesktop : null + if (D && D.clipboardWriteImage) { + const okNative = await D.clipboardWriteImage(srcOrBlob) + if (okNative) return srcOrBlob + } throw wCopyError('unsupported', W_COPY_HINT.unsupported) } // 先转 PNG 再写剪贴板(任何输入都产出 image/png) @@ -4090,6 +4098,11 @@ try { await navigator.clipboard.write([new ClipboardItem({ 'image/png': png })]) } catch (err) { + const D = (typeof window !== 'undefined') ? window.IWBDesktop : null + if (D && D.clipboardWriteImage) { + const okNative = await D.clipboardWriteImage(png) + if (okNative) return png + } const msg = String((err && err.message) || err) // 没有写权限(页面失焦/未授权)也归为「浏览器不支持剪贴板图片」一类,附浏览器原文便于排查 throw wCopyError('unsupported', W_COPY_HINT.unsupported + '(' + msg + ')') @@ -7188,6 +7201,7 @@ const tbCenterSeed = (type, refs) => { wsId: activeWsId, activeWsId: () => activeWsIdRef.current || activeWsId, nodes: () => refs.nodes, uid, findSpot, nodeW: (ty) => nodeWidth({ type: ty }), nodeH: (ty) => nodeTypeH(ty), pushHistory, commitCanvas, setSel, setNotice, importImage: wImportImage, + readNativeImage: (typeof window !== 'undefined' && window.IWBDesktop && window.IWBDesktop.clipboardReadImage) ? () => window.IWBDesktop.clipboardReadImage() : null, }) const onKey = (e) => { const t = e.target, C = window.IWBClipboardCopy, hasTxt = C && C.hasTextSelection @@ -7280,11 +7294,14 @@ const tbCenterSeed = (type, refs) => { const onPaste = (e) => { const t = e.target, editable = !!(t && t.tagName && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.tagName === 'SELECT' || t.isContentEditable)) refs.pasteProbe = 0 // 收到真实 paste → 取消「系统剪贴板为空」的提示 + refs.pasteStamp = (refs.pasteStamp || 0) + 1 const mod = (typeof window !== 'undefined' && window.IWBClipboardPaste) || null if (mod) mod.handle(e, pasteCtx(), editable) } window.addEventListener('keydown', onKey) window.addEventListener('keyup', onKeyUp) + const pasteModEarly = (typeof window !== 'undefined' && window.IWBClipboardPaste) || null + if (pasteModEarly && pasteModEarly.bindHotkeyFallback) pasteModEarly.bindHotkeyFallback(pasteCtx) window.addEventListener('paste', onPaste) window.addEventListener('blur', onBlur) return () => { diff --git a/docs/standards/architecture-current-state.md b/docs/standards/architecture-current-state.md index 5bd91a4..a035879 100644 --- a/docs/standards/architecture-current-state.md +++ b/docs/standards/architecture-current-state.md @@ -22,7 +22,7 @@ - 图片**新写入主通道 = IndexedDB Blob `{__blob}` / key `imgblob__`** (A) `app.js:2143`;`{__cache}`(Cache Storage)为兜底;\`ref_\`(`app.js` 内定义的 `IDB_REF_PREFIX = 'ref_'`)为 legacy 形态 (A)。 - 大图判定:`isBigDataUrl` = `data:` 且 `length > 3000` (A) `app.js:2018`;**画布保存保留阈值** `< 16384` 才原样保留 (A) `app.js:2182`。**两处阈值并存,含义不同**。 - 单测是**源码契约测试**:`tests/` 目录共 **493** 处源码文本钉点(`source.includes` / `source.indexOf` / `/re/.test(source)`),分布在 **20** 个文件(其中 `iwb-v32-web-test.js` 一个就占 **407**)→ **结构性重构会先打红测试**。**该数字已由 `tests/source-text-ratchet-test.js` 的「只减不增」棘轮守门**(2026-10-20 起守卫范围从 1 个文件扩到全目录:新增任何一处源码文本钉点都会打红)。**2026-11-12 复算**(`npm run audit:pins`,v3.24.76):二分 STRUCT **417** / NAME **76**;形态 **POS 403 / NEG 87 / COUNT 3**;难度 **易 62 / 中 316 / 难 115**。钉点减法第一批(v3.24.72)把 **537 → 505**:8 条探针钉点改为「门禁内 spec 是否真的读该计数器」、5 条改为运行时断言(生产态 `window` 上无探针)、10 条改为 DOM 断言(质量档位禁用 / 传输页无三模式按钮 / 模型项 title)、4 条改为运行时对象断言(健康检查两域、策略对象冻结)、其余 9 条有同文件 DOM 等价断言或仅剩 NEG。第二批(v3.24.76)把 **505 → 493**:94-5~7 三条「多标签释放语义」(10 处正则)换成 `tests/iwb-tabs-release.spec.js` 的 3 条真 e2e,剩 1 条「消费方契约」(断言该 spec 在门禁内且 spec 源码真的读两个探针);另 2 条 `wPurgeIntent.add` 钉点改为读 `src/workspace-purge.js`。**这一批一换就查出 3 个真缺陷**(objectURL 从未释放 / 彻底删除留孤儿标签 · session / 刷新后误回收打开标签的图)—— 见 CHANGELOG v3.24.76。 -- `app.js` = 单 IIFE **8,508 行**(**双层预算**:绝对上限 8,700 / 占总源码 ≤ 40%,现 **36.8%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **2,998 行**(上限 **3,030**,余量 32;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **84** 个模块 / 14,607 行,`sourceModules` 84 项;v3.24.68 新增 `clipboard-graph.js`,v3.24.74 新增 `image-admit.js`,v3.24.75 新增 `image-dedupe.js`,v3.24.76 新增 `workspace-purge.js`,v3.24.79 新增 `generation-provider-ping.js`,v3.24.80 删除无调用的 `createWBFlushViewport` 17 行)。 +- `app.js` = 单 IIFE **8,508 行**(**双层预算**:绝对上限 8,700 / 占总源码 ≤ 40%,现 **36.8%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **2,998 行**(上限 **3,030**,余量 32;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **85** 个模块 / 14,607 行,`sourceModules` 85 项;v3.24.68 新增 `clipboard-graph.js`,v3.24.74 新增 `image-admit.js`,v3.24.75 新增 `image-dedupe.js`,v3.24.76 新增 `workspace-purge.js`,v3.24.79 新增 `generation-provider-ping.js`,v3.24.80 删除无调用的 `createWBFlushViewport` 17 行)。 - 门禁:`npm run verify` = `verify:ci`(`build` → `node --check app.js` → `node --check dist/app.js` → `check-dist.js` → `lint`(ESLint 正确性规则,`src/` + `app.js`,P4-16a)→ `test:unit` → `test` → `test:facts`)+ `test:e2e` (A) `package.json`。 ## 2. 门禁与环境现状 @@ -167,7 +167,7 @@ - 同一张图被 3 个节点引用、hydrate 成 3 个不同 objectURL 时,preview/display 缓存各自 miss → 重复解码(与 F2 相邻)。 - **F10|`refs.genScheduler` 是桩** (A) → 未接线,暂无运行时影响(P3)。 - **F11|已建但未接线的模块层(2026-10-17 接线审计;2026-10-18 复核更正)** (A) - - **判定法**:`global.X =` / `root.X =` 判「导出」;跨文件裸引用判「读」;排除自合并(`src/runtime-constants.js:9`)。`app.js` 是**唯一生产消费者**(无 HTML 入口;`sw.js` 不引用模块全局)。**84 个模块中 59 个导出**被 `app.js` 读取;其余为未接线 / 仅测试 / 零引用(见下)。 + - **判定法**:`global.X =` / `root.X =` 判「导出」;跨文件裸引用判「读」;排除自合并(`src/runtime-constants.js:9`)。`app.js` 是**唯一生产消费者**(无 HTML 入口;`sw.js` 不引用模块全局)。**85 个模块中 59 个导出**被 `app.js` 读取;其余为未接线 / 仅测试 / 零引用(见下)。 - **仅被测试引用(9 模块 + 2 导出)**:`canvas-domain`、`generation-retry`、`generation-service`、`runtime-recovery-runner`、`runtime-state-bridge`、`runtime-store`、`storage-reconcile`、`storage-result`、`workspace-service`;导出 `IWBStorageHealthFactory`、`IWBPluginHostFactory`。(`storage-result` 是**存储层共享结果类型**,被 6 个存储模块读取,**非死代码**;`runtime-store` 为状态模型 epic 地基。) - **app.js 零引用(1 模块 + 3 导出)**:模块 `generation-controller`;导出 `IWBRuntimeMetricsFactory`、`IWBStorageRuntimeFactory`、`IWBUIComponents`。`canvas-relations` 已随 `06cf211` 删除(本文档早前把它列为"唯一可删者",实际已删)。零引用证据 = `grep -rn "<名字>" .`(排除 `node_modules|dist|vendor|test-results`)**只命中其自身赋值行**。 - **半接线 / 未接线**:`IWBRuntimeStateBridge` **无 app.js 引用(仅测试)**;`IWBRuntimeRunContext` **已接线**(`runNode` 读取运行上下文);`IWBGenerationController` 是完整但**从未被调用**的工厂;`ModularWorkspaceStore`(`app.js` 内)是 `storage-workspace` 的**预留接线 seam**(当前无下游使用,保留);`window.IWBImageFolder` 自注册后读回(装载路径)。 @@ -183,7 +183,7 @@ | `storage-reconcile` | 存储对账(`createReconciler`/`check`) | 内联对账 | 存储层收口 | | `runtime-recovery-runner` | 执行恢复候选(`candidate`/`valid`/`run`) | 内联恢复 | 断点恢复 | | `canvas-domain` | 画布域模型(`commit`/`updateNode`/`deleteNodes`…) | `CanvasStore` 那一套 | Workbench 解耦(P2-9) | - - **耦合面已冻结**:`tests/architecture-boundary-guard-test.js`(进 `npm run test:unit` 末环)冻结 app.js↔src 耦合面(**73** 项)与 `sourceModules` 顺序(**84** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。 + - **耦合面已冻结**:`tests/architecture-boundary-guard-test.js`(进 `npm run test:unit` 末环)冻结 app.js↔src 耦合面(**74** 项)与 `sourceModules` 顺序(**85** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。 ## 12. 易踩的坑 @@ -254,7 +254,7 @@ **信任模型(必须明示)**:形态 A 的插件是**可信代码**(与核心同权限、无沙箱);启停与设置是 UX 与可维护性手段,**不是安全边界**(同 §13.27 教训:前端开关一定可被绕过)。 -**守门与快照**:`tests/architecture-boundary-guard-test.js` 冻结「app.js ↔ src 耦合面」(**73** 项)与 `sourceModules` 顺序(**84** 项);新增模块、新增耦合、新增 dev 探针都**必须有意重生成对应快照**(`IWB_WRITE_BOUNDARY_SNAPSHOT=1`)。契约与行为的可执行验证在 `tests/plugin-host-test.js`(宿主单测)与 `tests/_plugin-host-probe.spec.js`(真实浏览器探针,`_` 前缀 + `iwb-dev-probe`,不进 34 门禁)。 +**守门与快照**:`tests/architecture-boundary-guard-test.js` 冻结「app.js ↔ src 耦合面」(**74** 项)与 `sourceModules` 顺序(**85** 项);新增模块、新增耦合、新增 dev 探针都**必须有意重生成对应快照**(`IWB_WRITE_BOUNDARY_SNAPSHOT=1`)。契约与行为的可执行验证在 `tests/plugin-host-test.js`(宿主单测)与 `tests/_plugin-host-probe.spec.js`(真实浏览器探针,`_` 前缀 + `iwb-dev-probe`,不进 34 门禁)。 **关键陷阱**:`normalizeNodes`(现位于 `src/canvas-normalize.js`)会**静默丢弃**不在 `NODE_H` 里的节点类型 ⇒ 新增节点类型必须先登记 `NODE_H`,否则节点一刷新就消失(§13.27 规则三的同一失败模式)。 diff --git a/scripts/build.js b/scripts/build.js index 53db50c..0622adf 100644 --- a/scripts/build.js +++ b/scripts/build.js @@ -36,6 +36,7 @@ const sourceModules = [ 'clipboard-paste.js', 'clipboard-copy.js', 'clipboard-paste-once.js', + 'clipboard-native.js', 'generation-size-policy.js', 'generation-request-shape.js', 'image-preview-derive.js', diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index f4556bf..04588a8 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -64,6 +64,26 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "arboard" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeb9553e62312c8756a5979254fc6d7da8bbeb5986a1e17037fab932f7037917" +dependencies = [ + "clipboard-win", + "image", + "log", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation", + "parking_lot", + "percent-encoding", + "windows-sys 0.61.2", + "x11rb", +] + [[package]] name = "atk" version = "0.18.2" @@ -383,6 +403,15 @@ dependencies = [ "windows-link", ] +[[package]] +name = "clipboard-win" +version = "5.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a" +dependencies = [ + "error-code", +] + [[package]] name = "combine" version = "4.6.9" @@ -529,6 +558,12 @@ version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + [[package]] name = "crypto-common" version = "0.1.7" @@ -888,12 +923,24 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "error-code" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7" + [[package]] name = "fastrand" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "fax" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a" + [[package]] name = "fdeflate" version = "0.3.7" @@ -1177,6 +1224,16 @@ dependencies = [ "version_check", ] +[[package]] +name = "gethostname" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" +dependencies = [ + "rustix", + "windows-link", +] + [[package]] name = "getrandom" version = "0.2.17" @@ -1383,6 +1440,17 @@ dependencies = [ "tracing", ] +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "zerocopy", +] + [[package]] name = "hashbrown" version = "0.12.3" @@ -1691,12 +1759,15 @@ dependencies = [ "moxcms", "num-traits", "png", + "tiff", ] [[package]] name = "image-workbench" version = "3.25.2" dependencies = [ + "arboard", + "base64 0.22.1", "log", "serde", "serde_json", @@ -2279,6 +2350,7 @@ dependencies = [ "block2", "objc2", "objc2-core-foundation", + "objc2-core-graphics", "objc2-foundation", "objc2-quartz-core", ] @@ -2818,6 +2890,12 @@ version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + [[package]] name = "quick-xml" version = "0.42.0" @@ -4331,6 +4409,20 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "tiff" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52" +dependencies = [ + "fax", + "flate2", + "half", + "quick-error", + "weezl", + "zune-jpeg", +] + [[package]] name = "time" version = "0.3.55" @@ -4979,6 +5071,12 @@ dependencies = [ "windows-core", ] +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + [[package]] name = "winapi" version = "0.3.9" @@ -5408,6 +5506,23 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "x11rb" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414" +dependencies = [ + "gethostname", + "rustix", + "x11rb-protocol", +] + +[[package]] +name = "x11rb-protocol" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" + [[package]] name = "xattr" version = "1.7.0" @@ -5441,6 +5556,26 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "zerofrom" version = "0.1.8" @@ -5544,3 +5679,18 @@ name = "zmij" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zune-core" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index ed5d6c8..0939748 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -29,3 +29,5 @@ tauri-plugin-dialog = "2" tauri-plugin-fs = "2" tauri-plugin-http = "2" tauri-plugin-updater = "2" +arboard = "3" +base64 = "0.22" diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index d7bb8d1..64bce30 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -234,6 +234,54 @@ async fn install_update(app: tauri::AppHandle) -> Result { app.restart(); } +use arboard::Clipboard; + +#[derive(serde::Serialize)] +struct ClipImagePayload { + width: u32, + height: u32, + rgba_base64: String, +} + +fn b64_encode(bytes: &[u8]) -> String { + use base64::Engine; + base64::engine::general_purpose::STANDARD.encode(bytes) +} + +#[tauri::command] +fn clipboard_read_image() -> Result, String> { + let mut cb = Clipboard::new().map_err(|e| e.to_string())?; + let img = match cb.get_image() { + Ok(v) => v, + Err(_) => return Ok(None), + }; + Ok(Some(ClipImagePayload { + width: img.width as u32, + height: img.height as u32, + rgba_base64: b64_encode(&img.bytes), + })) +} + +#[tauri::command] +fn clipboard_write_image(width: u32, height: u32, rgba_base64: String) -> Result { + use base64::Engine; + let bytes = base64::engine::general_purpose::STANDARD + .decode(rgba_base64.as_bytes()) + .map_err(|e| e.to_string())?; + let expect = (width as usize) * (height as usize) * 4; + if width == 0 || height == 0 || bytes.len() < expect { + return Err("图片像素数据不完整".into()); + } + let mut cb = Clipboard::new().map_err(|e| e.to_string())?; + cb.set_image(arboard::ImageData { + width: width as usize, + height: height as usize, + bytes: std::borrow::Cow::Owned(bytes), + }) + .map_err(|e| e.to_string())?; + Ok(true) +} + #[cfg_attr(mobile, tauri::mobile_entry_point)] pub fn run() { let app = tauri::Builder::default() @@ -241,7 +289,7 @@ pub fn run() { .plugin(tauri_plugin_fs::init()) .plugin(tauri_plugin_dialog::init()) .plugin(tauri_plugin_updater::Builder::new().build()) - .invoke_handler(tauri::generate_handler![open_app_data_dir, grant_dir, copy_tree, check_update, install_update]) + .invoke_handler(tauri::generate_handler![open_app_data_dir, grant_dir, copy_tree, check_update, install_update, clipboard_read_image, clipboard_write_image]) .setup(|app| { if cfg!(debug_assertions) { app.handle().plugin( @@ -255,6 +303,12 @@ pub fn run() { restore_geom(&win, app.handle()); } build_tray(app.handle())?; + // macOS 必须有应用菜单,否则 Cmd+C / Cmd+V / Cmd+X 根本不会进 WebView(Tauri 已知问题) + #[cfg(target_os = "macos")] + { + let menu = tauri::menu::Menu::default(app.handle())?; + app.set_menu(menu)?; + } Ok(()) }) // 点关闭按钮 ⇒ 记住窗口尺寸后收进托盘(不退出,后台任务继续) diff --git a/src/clipboard-native.js b/src/clipboard-native.js new file mode 100644 index 0000000..56081ab --- /dev/null +++ b/src/clipboard-native.js @@ -0,0 +1,82 @@ +/* native-clipboard.js —— 桌面端原生剪贴板图片(2026-11-17) + * + * 为什么单独一个模块: + * WKWebView 的 paste 事件拿不到「从 Finder/预览复制的图片」, + * navigator.clipboard.write([ClipboardItem]) 在部分 macOS 版本也不可用。 + * 图片读写统一走 Rust 侧 arboard(命令 clipboard_read_image / clipboard_write_image), + * 这里只做 RGBA ⇄ PNG Blob 的转换与调用封装。 + * + * 网页版:IWBDesktop 不会把这两个函数注入进来,模块静默不可用,行为与原来一致。 + */ +;(function (global) { + 'use strict' + + function tauri() { + const T = global && global.__TAURI__ + return (T && T.core && typeof T.core.invoke === 'function') ? T : null + } + + function b64FromU8(u8) { + let s = '' + const CH = 0x8000 + for (let i = 0; i < u8.length; i += CH) s += String.fromCharCode.apply(null, u8.subarray(i, i + CH)) + return global.btoa(s) + } + + function u8FromB64(b64) { + const s = global.atob(b64) + const u8 = new Uint8Array(s.length) + for (let i = 0; i < s.length; i++) u8[i] = s.charCodeAt(i) + return u8 + } + + /** 读系统剪贴板里的图片 → PNG File(读不到返回 null) */ + async function readImage() { + const T = tauri() + if (!T) return null + try { + const r = await T.core.invoke('clipboard_read_image') + if (!r || !r.width || !r.height || !r.rgbaBase64) return null + const u8 = u8FromB64(r.rgbaBase64) + const canvas = global.document.createElement('canvas') + canvas.width = r.width + canvas.height = r.height + const ctx = canvas.getContext('2d') + const imgData = ctx.createImageData(r.width, r.height) + imgData.data.set(u8.subarray(0, r.width * r.height * 4)) + ctx.putImageData(imgData, 0, 0) + const blob = await new Promise((resolve) => canvas.toBlob((b) => resolve(b), 'image/png')) + if (!blob) return null + const name = 'clipboard-' + Date.now() + '.png' + try { return new File([blob], name, { type: 'image/png' }) } catch (e) { + blob.name = name + return blob + } + } catch (e) { return null } + } + + /** 把图片写进系统剪贴板(Blob/File 均可) */ + async function writeImage(blobOrFile) { + const T = tauri() + if (!T || !blobOrFile) return false + try { + const C = global.IWBImageBlob + const png = (C && typeof C.toPng === 'function') ? await C.toPng(blobOrFile) : blobOrFile + const bmp = await global.createImageBitmap(png) + const canvas = global.document.createElement('canvas') + canvas.width = bmp.width + canvas.height = bmp.height + const ctx = canvas.getContext('2d') + ctx.drawImage(bmp, 0, 0) + const data = ctx.getImageData(0, 0, canvas.width, canvas.height).data + await T.core.invoke('clipboard_write_image', { + width: canvas.width, + height: canvas.height, + rgbaBase64: b64FromU8(new Uint8Array(data.buffer, data.byteOffset, data.byteLength)), + }) + return true + } catch (e) { return false } + } + + global.IWBNativeClipboard = Object.freeze({ readImage, writeImage, available: () => !!tauri() }) +})(typeof window !== 'undefined' ? window : globalThis) diff --git a/src/clipboard-paste.js b/src/clipboard-paste.js index 7aa12da..c288cd4 100644 --- a/src/clipboard-paste.js +++ b/src/clipboard-paste.js @@ -266,6 +266,16 @@ // 复制只进了内部那份;用户从旧版本带过来的复制内容也靠它。 // 每个 paste 事件独立处理 → 连按 N 次贴 N 份,不会像旧的定时器方案那样只贴一份。 e.preventDefault() + // 桌面端:Finder/预览复制的图片在 WKWebView 的 paste 事件里读不到,先问原生剪贴板 + if (typeof ctx.readNativeImage === 'function') { + ctx.setNotice({ type: 'info', text: '正在读取剪贴板图片…' }) + ctx.readNativeImage().then((f) => { + if (f) { pasteImages([f], ctx); ctx.setNotice(null) } + else if (ctx.pasteCopiedNodes()) { ctx.setNotice(null) } + else ctx.setNotice({ type: 'err', text: ctx.refs.clipExpired ? '内部剪贴板已过期(10 分钟),请重新复制节点' : '剪贴板里没有可粘贴的内容' }) + }) + return true + } if (ctx.pasteCopiedNodes()) return true ctx.setNotice({ type: 'err', @@ -280,6 +290,10 @@ // 用户没法照着做(他粘的可能本来就是 PNG,只是 MIME 没填)。 const A = g.IWBImageAdmit const list = c.files || [] + if (typeof ctx.readNativeImage === 'function') { + ctx.readNativeImage().then((f) => { if (f) { pasteImages([f], ctx); ctx.setNotice(null) } }) + return true + } const why = (A && typeof A.why === 'function' && list[0]) ? A.why(list[0]) : ('暂不支持粘贴文件(' + ((list[0] && list[0].name) || '该文件') + ')') ctx.setNotice({ type: 'err', text: (why || '暂不支持粘贴该文件') + (list.length > 1 ? '(另有 ' + (list.length - 1) + ' 个文件未处理)' : '') }) @@ -325,5 +339,28 @@ function probe(ctx) { }, 420) } - g.IWBClipboardPaste = Object.freeze({ handle, probe, overlayOpen, anchor }) + /* Cmd/Ctrl+V 兜底(桌面端):菜单缺失或 WebView 不派发 paste 时,160ms 内没收到 + * 真实 paste 事件就主动读一次原生剪贴板图片。getCtx 由 app.js 注入(懒取,避免闭包过期)。 */ + let hotkeyBound = false + function bindHotkeyFallback(getCtx) { + if (hotkeyBound || typeof window === 'undefined') return + hotkeyBound = true + window.addEventListener('keydown', (e) => { + if (!(e.metaKey || e.ctrlKey) || e.shiftKey || e.altKey) return + if (String(e.key || '').toLowerCase() !== 'v') return + const t = /** @type {any} */ (e.target) + if (t && t.tagName && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return + const D = g.IWBDesktop + if (!D || !D.clipboardReadImage) return + const ctx = (typeof getCtx === 'function') ? getCtx() : null + const stamp = ctx && ctx.refs ? (ctx.refs.pasteStamp || 0) : 0 + setTimeout(() => { + const now = ctx && ctx.refs ? (ctx.refs.pasteStamp || 0) : 0 + if (now !== stamp) return + D.clipboardReadImage().then((f) => { if (f) pasteImages([f], ctx) }) + }, 160) + }) + } + + g.IWBClipboardPaste = Object.freeze({ handle, probe, overlayOpen, anchor, bindHotkeyFallback, pasteFiles: (files, ctx) => pasteImages(files || [], ctx) }) })(typeof window !== 'undefined' ? window : globalThis) diff --git a/src/runtime-desktop-bridge.js b/src/runtime-desktop-bridge.js index e6fc298..1ab9600 100644 --- a/src/runtime-desktop-bridge.js +++ b/src/runtime-desktop-bridge.js @@ -23,6 +23,10 @@ getSilentSave() { return !!(state.impl && state.impl.getSilentSave()) }, setSilentSave(on) { if (state.impl) state.impl.setSilentSave(on) }, openDataDir() { return state.impl ? state.impl.openDataDir() : Promise.reject(new Error('仅桌面端可用')) }, + // 原生剪贴板图片(v3.26):WKWebView 里 paste 事件拿不到 Finder 复制的图片, + // navigator.clipboard.write 也常不可用,统一走 Rust 侧 arboard。 + clipboardReadImage() { return state.impl && state.impl.clipboardReadImage ? state.impl.clipboardReadImage() : Promise.resolve(null) }, + clipboardWriteImage(blob) { return state.impl && state.impl.clipboardWriteImage ? state.impl.clipboardWriteImage(blob) : Promise.resolve(false) }, market: { list() { return state.impl && state.impl.marketList ? state.impl.marketList() : Promise.resolve([]) }, installed() { return state.impl && state.impl.marketInstalled ? state.impl.marketInstalled() : Promise.resolve([]) }, diff --git a/tests/fixtures/iwb-app-global-reads.json b/tests/fixtures/iwb-app-global-reads.json index 6ca5f74..5c92cdd 100644 --- a/tests/fixtures/iwb-app-global-reads.json +++ b/tests/fixtures/iwb-app-global-reads.json @@ -20,6 +20,7 @@ "IWBImageCompress", "IWBImagePreviewDerive", "IWBMetricsSwallow", + "IWBNativeClipboard", "IWBNodeBodies", "IWBPluginHost", "IWBProviderPing", diff --git a/tests/fixtures/iwb-source-modules-order.json b/tests/fixtures/iwb-source-modules-order.json index 60ad834..5aea946 100644 --- a/tests/fixtures/iwb-source-modules-order.json +++ b/tests/fixtures/iwb-source-modules-order.json @@ -8,6 +8,7 @@ "clipboard-paste.js", "clipboard-copy.js", "clipboard-paste-once.js", + "clipboard-native.js", "generation-size-policy.js", "generation-request-shape.js", "image-preview-derive.js",