From 3f0f13f867bc845ed1403ec9cc6497b816693d7b Mon Sep 17 00:00:00 2001 From: qiqi Date: Wed, 25 Nov 2026 18:44:24 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20v3.26.73=20=E5=9E=83=E5=9C=BE=E6=A1=B6?= =?UTF-8?q?=E6=82=AC=E5=81=9C=E6=89=8D=E6=98=BE=E5=BD=A2=20/=20=E6=9B=B4?= =?UTF-8?q?=E5=A4=9A=E8=8F=9C=E5=8D=95=E5=B1=95=E5=BC=80=E4=B8=8D=E5=8F=8D?= =?UTF-8?q?=E8=89=B2=20/=20=E6=A1=8C=E9=9D=A2=E7=AB=AF=E5=8F=AF=E7=B2=98?= =?UTF-8?q?=E8=B4=B4=E8=AE=BF=E8=BE=BE=E5=A4=8D=E5=88=B6=E7=9A=84=E5=9B=BE?= =?UTF-8?q?=E7=89=87=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 14 + CONTRIBUTING.md | 2 +- app.js | 6 +- docs/standards/architecture-current-state.md | 2 +- package.json | 4 +- src-tauri/Cargo.lock | 4 +- src-tauri/Cargo.toml | 7 +- src-tauri/src/lib.rs | 283 ++++++++++++++++++- src-tauri/tauri.conf.json | 2 +- src/clipboard-native.js | 56 +++- src/clipboard-paste.js | 117 ++++++-- style.css | 16 +- tests/clipboard-native-test.js | 66 +++++ tests/clipboard-paste-test.js | 10 +- 14 files changed, 536 insertions(+), 53 deletions(-) create mode 100644 tests/clipboard-native-test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index f2cfea5..959f26d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,20 @@ > 3. 核验正式地址版本 → 之后才移动 `stable` / `stable-verified-<日期>` 标签、更新本 CHANGELOG、写 GitHub Release(`gh release create`)。 > 测试发现问题 → 改 → 再 `deploy:test`,正式环境不受影响。回滚点 `git reset --hard stable`。 +## v3.26.73(2026-11-25)垃圾桶按钮收口 / 「更多」不再黑圈 / 桌面端粘贴补全 + +**宿主** +- **模型行垃圾桶**:默认不显示,且显隐改成「透明度 90ms + visibility 延迟 90ms」—— 旧写法 visibility 立即切换、只有透明度在动,鼠标进出那一帧会跳一下,观感像卡顿。默认色由 `--iwb-err` 改为中性灰 `--iwb-text-dim`,只有指针真正移到图标上才转红 + 淡红底(先显形、再确认危险色)。尺寸 26px 硬编码改 `--iwb-control-h`(30px),与同一行的厂商下拉等高;补 `padding:0`(原为浏览器默认 1px 6px);行横向内距 8→12px —— 行是 999px 胶囊(半径 18px),8px 内距会让图标压到弧线上,看上去像被一个歪框套住。 +- **左下「更多」展开时不再反色**:触发器带着 `on` 类,命中了 `.iwb-nav-item.on` 的「页面选中」反色(底=文字色、字=页面底色)⇒ 三个点后面多出一个黑圆圈,和真正的页面选中态撞语义。现在 `.iwb-nav-more-btn.on` 只铺 hover 同级浅底。 + +**桌面端** +- **可粘贴「访达里复制的图片文件」**:剪贴板里那种只有路径、没有位图的复制,此前一律读不到。`clipboard_read_image` 改为先读位图,读不到再读 NSPasteboard 的 `public.file-url`(多选兜底 `NSFilenamesPboardType`),百分号编码按 UTF-8 解(带空格/中文名的文件也能读对)。Rust 侧**不解码**(`image` 只编了 png feature):文件分支把原始字节 + 原 MIME + 原名交回前端,走已有的 canvas 解码与「压到长边 ≤1600」收口,格式不支持时还有准入判据给「怎么转」;超过 48MB 直接回可读原因。 +- **粘贴过程有反馈**:按下即出「正在粘贴图片…」,完成后替换成「已粘贴 N 张」;失败提示带具体原因(解码超时 / 字节为空 / 文件过大),不再一律「处理失败」。实测一张 6.3MB 截图到节点出现约 1.8s,这段空窗就是「有时候像没粘进去」的来源。 +- 焦点停在提示词输入框里粘图片,改为**接管**:blur 焦点 → 直接贴到画布(图片本来就放不进输入框)。 +- 单张导入加 16s 兜底(内层压缩本身上限 12s),worker 卡死时不再无限静默。 + +**验证**:`verify:ci` 全绿;新增 `tests/clipboard-native-test.js`(16 项,覆盖位图/文件/空载荷/读取报错四路);Rust `cargo test clip_tests` 3 项通过,含端到端(用 osascript 把剪贴板设成一张带空格的 PNG 文件 → 命令回文件载荷、MIME/文件名/字节数一致)。 + ## v3.26.72(2026-11-25)修 v3.26.71 三处「改了但看不到」 **宿主** diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7221d0e..86b15f9 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -40,7 +40,7 @@ build esbuild 打包到 dist/(单 dist/app.js = src/ 模块按序 node --check app.js 与 dist/app.js 语法 check-dist.js 产物体检 lint ESLint(src/ + app.js,正确性规则) -test:unit 128 个单测文件(jsdom 契约测试;2026-11-07 新增 sync-facts-guard(事实一致性)/ _helpers/source(统一源文本);2026-11-12 新增 provider-ping(测速 no-cors 兜底)) +test:unit 129 个单测文件(jsdom 契约测试;2026-11-07 新增 sync-facts-guard(事实一致性)/ _helpers/source(统一源文本);2026-11-12 新增 provider-ping(测速 no-cors 兜底)) test relay-task-graph-fixture + iwb-v32-web-test test:facts 事实基线守门(见 §5) typecheck 渐进类型检查(tsc --noEmit;范围 = src/*.js,不含 app.js) diff --git a/app.js b/app.js index c48c563..6298349 100644 --- a/app.js +++ b/app.js @@ -7444,7 +7444,7 @@ const tbCenterSeed = (type, refs) => { refs, ui: { settingOpen, drawerOpen, helpOpen, wsMoreOpen, ctxMenu, connMenu }, readClipboardGraph, pasteCopiedNodes, pasteGraph, 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, + pushHistory, commitCanvas, setSel, setNotice, showToast, importImage: wImportImage, readNativeImage: (typeof window !== 'undefined' && window.IWBDesktop && window.IWBDesktop.clipboardReadImage) ? () => window.IWBDesktop.clipboardReadImage() : null, closeLibrary: () => { setDrawerOpen(false) }, }) @@ -7532,9 +7532,9 @@ 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) + // pasteStamp 只在**真正被消费**时自增(桌面端 keydown 兜底靠它判断);无条件自增会让被忽略的 paste 也挡住兜底。 + if (mod && mod.handle(e, pasteCtx(), editable)) refs.pasteStamp = (refs.pasteStamp || 0) + 1 } window.addEventListener('keydown', onKey) window.addEventListener('keyup', onKeyUp) diff --git a/docs/standards/architecture-current-state.md b/docs/standards/architecture-current-state.md index 8533b70..ab9ca1c 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 **9,172 行**(**双层预算**:绝对上限 9,173 / 占总源码 ≤ 40%,现 **30.1%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **3,040 行**(上限 **3,046**,余量 6;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **111** 个模块 / 21,282 行,`sourceModules` 111 项;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 **9,172 行**(**双层预算**:绝对上限 9,173 / 占总源码 ≤ 40%,现 **30.0%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **3,040 行**(上限 **3,046**,余量 6;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **111** 个模块 / 21,395 行,`sourceModules` 111 项;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. 门禁与环境现状 diff --git a/package.json b/package.json index 892e152..baee7c1 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "image-workbench-web", "private": true, - "version": "3.26.72", + "version": "3.26.73", "description": "Browser-based node canvas image workbench", "scripts": { "build": "node scripts/build.js && node scripts/copy-plugins.js", @@ -10,7 +10,7 @@ "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", - "test:unit": "node tests/plugin-files-policy-test.js && node tests/theme-plugin-tokens-test.js && node tests/design-tokens-component-doc-test.js && node tests/theme-static-snapshot-test.js && node tests/overlay-layer-test.js && node tests/settings-scope-test.js && node tests/node-scope-test.js && node tests/appearance-v2-test.js && node tests/image-prompt-cover-test.js && 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/album-task-graph-test.js && node tests/generation-endpoint-test.js && node tests/storage-config-shape-test.js && node tests/generation-default-model-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-gc-canvas-refs-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/gallery-sync-test.js && node tests/image-blob-store-test.js && node tests/image-format-test.js && node tests/clipboard-graph-test.js && node tests/clipboard-graph-fallback-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/desktop-csp-loopback-test.js && node tests/architecture-boundary-guard-test.js && node tests/plugin-host-test.js && node tests/plugin-data-test.js && node tests/plugin-loader-test.js && node tests/plugin-bundle-test.js && node tests/plugin-install-test.js && node tests/plugin-gallery-render-test.js && node tests/plugin-gallery-recovery-test.js && node tests/plugin-gallery-ux-test.js && node tests/plugin-grouplib-render-test.js && node tests/plugin-promptlib-render-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/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/plugin-theme-contract-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/native-overlay-park-test.js && node tests/ui-dock-sanitize-test.js && node tests/ui-minimap-fit-test.js && node tests/ui-workbench-hooks-test.js && node tests/plugin-scale-contract-test.js && node tests/design-token-ratchet-test.js && node tests/theme-contrast-test.js && node tests/image-file-ref-preview-test.js", + "test:unit": "node tests/plugin-files-policy-test.js && node tests/theme-plugin-tokens-test.js && node tests/design-tokens-component-doc-test.js && node tests/theme-static-snapshot-test.js && node tests/overlay-layer-test.js && node tests/settings-scope-test.js && node tests/node-scope-test.js && node tests/appearance-v2-test.js && node tests/image-prompt-cover-test.js && 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/album-task-graph-test.js && node tests/generation-endpoint-test.js && node tests/storage-config-shape-test.js && node tests/generation-default-model-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-gc-canvas-refs-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/gallery-sync-test.js && node tests/image-blob-store-test.js && node tests/image-format-test.js && node tests/clipboard-graph-test.js && node tests/clipboard-graph-fallback-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/clipboard-native-test.js && node tests/paste-once-test.js && node tests/list-e2e-specs-test.js && node tests/desktop-csp-loopback-test.js && node tests/architecture-boundary-guard-test.js && node tests/plugin-host-test.js && node tests/plugin-data-test.js && node tests/plugin-loader-test.js && node tests/plugin-bundle-test.js && node tests/plugin-install-test.js && node tests/plugin-gallery-render-test.js && node tests/plugin-gallery-recovery-test.js && node tests/plugin-gallery-ux-test.js && node tests/plugin-grouplib-render-test.js && node tests/plugin-promptlib-render-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/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/plugin-theme-contract-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/native-overlay-park-test.js && node tests/ui-dock-sanitize-test.js && node tests/ui-minimap-fit-test.js && node tests/ui-workbench-hooks-test.js && node tests/plugin-scale-contract-test.js && node tests/design-token-ratchet-test.js && node tests/theme-contrast-test.js && node tests/image-file-ref-preview-test.js", "test:diagnostics": "node tests/runtime-diagnostics-hotpath-test.js", "test:facts": "node tests/architecture-facts-guard-test.js && node tests/release-records-test.js", "plugins:gc": "node scripts/plugins-publish.mjs --gc", diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index ddf70b2..7fc0864 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -1983,13 +1983,15 @@ dependencies = [ [[package]] name = "image-workbench" -version = "3.26.72" +version = "3.26.73" dependencies = [ "arboard", "base64 0.22.1", "image", "log", "objc2", + "objc2-app-kit", + "objc2-foundation", "serde", "serde_json", "tauri", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 24b421c..6d0ec8d 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "image-workbench" -version = "3.26.72" +version = "3.26.73" description = "无限画布 · 生图工作台桌面版" authors = ["malongan"] license = "" @@ -44,6 +44,11 @@ base64 = "0.22" # (Cargo.lock 里是同一个 0.6.x),这里显式依赖不会多编译一份。 [target.'cfg(target_os = "macos")'.dependencies] objc2 = "0.6" +# 剪贴板「复制的是文件」:Finder 复制文件时 NSPasteboard 里只有 public.file-url / NSFilenamesPboardType, +# 没有位图,arboard 的 get_image 读不到。这里直接问 NSPasteboard 要路径。 +# 这两个 crate 本来就是 tauri/wry 在 macOS 上的依赖(Cargo.lock 已锁 0.3.x),显式依赖不会多编译一份。 +objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSPasteboard"] } +objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSString", "NSArray", "NSURL"] } # Windows:直接读进程工作集(GetProcessMemoryInfo),不再启动 PowerShell 子进程 [target.'cfg(windows)'.dependencies] diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 9c3666e..f739963 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -387,12 +387,37 @@ struct ClipImagePayload { png_base64: String, } -/// 读系统剪贴板图片 → PNG(base64) +/// 「复制的是文件」(在 Finder 里选中图片文件按 ⌘C)时,剪贴板里**没有位图**,只有路径, +/// arboard 的 get_image 读到的是 None —— 这就是「明明复制了一张图却粘不进来」。 /// -/// 为什么返回 PNG 而不是裸 RGBA:12MP 照片的 RGBA 是 46MB,base64 后 62MB, -/// 穿过 IPC 会卡住前端好几秒;PNG 通常只有几 MB。 -#[tauri::command] -fn clipboard_read_image() -> Result, String> { +/// 这里刻意**不在 Rust 解码**,而把原始字节交回前端: +/// · image 依赖只开了 png feature,JPEG / HEIC / TIFF 解不了; +/// · 前端本来就有唯一导入收口(app.js wImportImage:canvas 解码 → 压到长边 ≤1600 → 落盘), +/// 格式不支持时还有准入判据(src/image-admit.js)给「怎么转」的具体指引。 +#[derive(serde::Serialize)] +#[serde(rename_all = "camelCase")] +struct ClipFilePayload { + name: String, + mime: String, + size: u64, + bytes_base64: String, +} + +/// 两种来源共用一个命令:位图带 pngBase64、文件带 bytesBase64。 +/// serde(untagged) ⇒ 序列化后就是扁平对象,前端按字段判断即可,不用改 IPC 形状。 +#[derive(serde::Serialize)] +#[serde(untagged)] +enum ClipPayload { + Bitmap(ClipImagePayload), + File(ClipFilePayload), +} + +/// 文件粘贴上限:48MB 的 base64 是 64MB,再大穿 IPC 会把前端卡住好几秒, +/// 不如明确告诉用户「压缩或拖入」(拖入走 File 对象,不经过这条 base64 通道)。 +const CLIP_FILE_MAX: u64 = 48 * 1024 * 1024; + +/// 剪贴板位图 → PNG payload;剪贴板里没有位图时返回 None(不再当作错误) +fn clip_bitmap() -> Result, String> { let mut cb = Clipboard::new().map_err(|e| e.to_string())?; let img = match cb.get_image() { Ok(v) => v, @@ -420,6 +445,191 @@ fn clipboard_read_image() -> Result, String> { })) } +/// 按文件头判 MIME(扩展名会说谎:微信导出的 .png 实际是 JPEG 的情况不少) +fn sniff_image_mime(b: &[u8]) -> Option<&'static str> { + if b.len() < 12 { + return None; + } + if b.starts_with(&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]) { + return Some("image/png"); + } + if b.starts_with(&[0xff, 0xd8, 0xff]) { + return Some("image/jpeg"); + } + if b.starts_with(b"GIF87a") || b.starts_with(b"GIF89a") { + return Some("image/gif"); + } + if b.starts_with(b"RIFF") && &b[8..12] == b"WEBP" { + return Some("image/webp"); + } + if b.starts_with(b"BM") { + return Some("image/bmp"); + } + if b.starts_with(&[0x49, 0x49, 0x2a, 0x00]) || b.starts_with(&[0x4d, 0x4d, 0x00, 0x2a]) { + return Some("image/tiff"); + } + if &b[4..8] == b"ftyp" { + let brand = &b[8..12]; + // HEIC / HEIF 家族与 AVIF 都是 ISO-BMFF,靠 brand 区分 + if brand == b"avif" || brand == b"avis" { + return Some("image/avif"); + } + return Some("image/heic"); + } + None +} + +fn ext_image_mime(path: &std::path::Path) -> Option<&'static str> { + let ext = path + .extension() + .map(|e| e.to_string_lossy().to_ascii_lowercase()) + .unwrap_or_default(); + Some(match ext.as_str() { + "png" => "image/png", + "jpg" | "jpeg" | "jpe" => "image/jpeg", + "gif" => "image/gif", + "webp" => "image/webp", + "bmp" => "image/bmp", + "tif" | "tiff" => "image/tiff", + "heic" | "heif" => "image/heic", + "avif" => "image/avif", + "svg" => "image/svg+xml", + _ => return None, + }) +} + +/// 系统剪贴板里的「文件路径」:macOS 走 NSPasteboard,其它平台暂不接(Windows 复制图片文件 +/// 通常同时带 CF_DIB,arboard 的位图分支已经能拿到;纯 CF_HDROP 场景等有 Windows 需求再加)。 +fn pasteboard_file_paths() -> Vec { + #[cfg(target_os = "macos")] + { + macos::pasteboard_file_paths() + } + #[cfg(not(target_os = "macos"))] + { + Vec::new() + } +} + +#[cfg(target_os = "macos")] +mod macos { + use std::path::PathBuf; + + /// Finder 复制文件时 NSPasteboard 上的两种写法,都要看: + /// · public.file-url:单个文件(最常用),值是 file:// 字符串; + /// · NSFilenamesPboardType:多选/老应用,值是路径字符串数组。 + pub fn pasteboard_file_paths() -> Vec { + use objc2_app_kit::NSPasteboard; + use objc2_foundation::{NSArray, NSString}; + + let mut out: Vec = Vec::new(); + let pb = NSPasteboard::generalPasteboard(); + let ty_url = NSString::from_str("public.file-url"); + if let Some(s) = pb.stringForType(&ty_url) { + if let Some(p) = file_url_to_path(&s.to_string()) { + out.push(p); + } + } + if out.is_empty() { + let ty_names = NSString::from_str("NSFilenamesPboardType"); + if let Some(plist) = pb.propertyListForType(&ty_names) { + if let Ok(arr) = plist.downcast::() { + for item in arr.iter() { + // 元素理论上是 NSString(路径),但 plist 是弱类型的,逐个降级判断 + if let Some(s) = item.downcast_ref::() { + if let Some(p) = file_url_to_path(&s.to_string()) { + out.push(p); + } + } + } + } + } + } + out + } + + /// file:///Users/x/a%20b.png → PathBuf(百分号编码必须解,否则带空格的文件名会读不到) + pub(super) fn file_url_to_path(s: &str) -> Option { + let s = s.trim(); + if s.is_empty() { + return None; + } + if let Ok(u) = url::Url::parse(s) { + if let Ok(p) = u.to_file_path() { + return Some(p); + } + } + // NSFilenamesPboardType 给的本来就是裸路径 + let p = PathBuf::from(s); + if p.is_absolute() { Some(p) } else { None } + } +} + +/// 从剪贴板里的文件路径造 payload:只取第一张「像图片」的文件 +fn clip_file() -> Result, String> { + for path in pasteboard_file_paths() { + if !path.is_file() { + continue; + } + let size = match std::fs::metadata(&path) { + Ok(m) => m.len(), + Err(_) => continue, + }; + if size == 0 { + continue; + } + // 扩展名 + 文件头任一命中就算图片(拖进来/复制过来的临时文件可能没有扩展名) + let head = { + use std::io::Read; + let mut buf = [0u8; 16]; + let mut f = match std::fs::File::open(&path) { + Ok(f) => f, + Err(_) => continue, + }; + let n = f.read(&mut buf).unwrap_or(0); + buf[..n].to_vec() + }; + let mime = match sniff_image_mime(&head).or_else(|| ext_image_mime(&path)) { + Some(m) => m, + None => continue, + }; + if size > CLIP_FILE_MAX { + return Err(format!( + "图片文件太大({:.0} MB,上限 {} MB):请先压缩,或直接把它拖进画布", + size as f64 / 1048576.0, + CLIP_FILE_MAX / 1048576 + )); + } + let bytes = std::fs::read(&path).map_err(|e| format!("读取图片文件失败:{}", e))?; + let name = path + .file_name() + .map(|s| s.to_string_lossy().to_string()) + .unwrap_or_else(|| "clipboard.png".to_string()); + return Ok(Some(ClipFilePayload { + name, + mime: mime.to_string(), + size, + bytes_base64: b64_encode(&bytes), + })); + } + Ok(None) +} + +/// 读系统剪贴板图片 → PNG(base64)或原始文件字节(base64) +/// +/// 为什么位图返回 PNG 而不是裸 RGBA:12MP 照片的 RGBA 是 46MB,base64 后 62MB, +/// 穿过 IPC 会卡住前端好几秒;PNG 通常只有几 MB。 +#[tauri::command] +fn clipboard_read_image() -> Result, String> { + if let Some(p) = clip_bitmap()? { + return Ok(Some(ClipPayload::Bitmap(p))); + } + if let Some(f) = clip_file()? { + return Ok(Some(ClipPayload::File(f))); + } + Ok(None) +} + /// 把 PNG(base64)写进系统剪贴板 #[tauri::command] fn clipboard_write_image(png_base64: String) -> Result { @@ -1035,3 +1245,66 @@ pub fn run() { } }); } + +/* ── 剪贴板读图的真实链路测试(只在 macOS 手动跑:cd src-tauri && cargo test)── + * 为什么不进门禁:会改写开发机的系统剪贴板,且依赖 osascript —— CI 里跑没有意义。 + * 覆盖的是这次新增的分支:Finder 复制「图片文件」时剪贴板里没有位图,只有 public.file-url。 */ +#[cfg(all(test, target_os = "macos"))] +mod clip_tests { + use super::*; + + #[test] + fn sniff_recognises_common_headers() { + assert_eq!(sniff_image_mime(&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0]), Some("image/png")); + assert_eq!(sniff_image_mime(&[0xff, 0xd8, 0xff, 0xe0, 0, 0, 0, 0, 0, 0, 0, 0]), Some("image/jpeg")); + assert_eq!(sniff_image_mime(b"\0\0\0\x18ftypheic\0\0\0\0"), Some("image/heic")); + assert_eq!(sniff_image_mime(b"definitely-not-an-image"), None); + } + + /// 纯函数层:public.file-url 里的中文/空格是百分号编码,解不干净就读不到文件 + #[test] + fn file_url_decodes_percent_encoding() { + let p = macos::file_url_to_path("file:///Users/x/%E6%88%AA%E5%9B%BE%20two.png").unwrap(); + assert_eq!(p.file_name().unwrap().to_string_lossy(), "截图 two.png"); + } + + /// 端到端:把一张带空格与中文名的 PNG 放进剪贴板当作「复制文件」,命令必须回文件载荷 + #[test] + fn pasteboard_file_copy_returns_bytes() { + let dir = std::env::temp_dir().join("iwb-clip-test"); + std::fs::create_dir_all(&dir).expect("建临时目录"); + // 文件名留空格:走 public.file-url 时是 %20,能验证百分号解码(中文名会被 + // AppleScript 源码编码弄坏,脚本侧不测,解码逻辑靠 url::Url 保证) + let path = dir.join("iwb clip copy two.png"); + // 2x2 红绿蓝白,用 image 编码一份真实 PNG + let px: Vec = vec![255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255]; + let mut png: Vec = Vec::new(); + { + use image::ImageEncoder; + image::codecs::png::PngEncoder::new(&mut png) + .write_image(&px, 2, 2, image::ExtendedColorType::Rgba8) + .expect("编码 PNG"); + } + std::fs::write(&path, &png).expect("写临时 PNG"); + + let script = format!("set the clipboard to (POSIX file \"{}\")", path.display()); + let status = std::process::Command::new("osascript") + .arg("-e") + .arg(&script) + .status() + .expect("调用 osascript"); + assert!(status.success(), "把剪贴板设成文件失败"); + + match clipboard_read_image().expect("命令不应报错") { + Some(ClipPayload::File(f)) => { + assert_eq!(f.mime, "image/png"); + // 百分号编码解对了才会带带空格的原名(public.file-url 里是 %20) + assert_eq!(f.name, "iwb clip copy two.png"); + assert_eq!(f.size, png.len() as u64); + assert!(!f.bytes_base64.is_empty()); + } + Some(ClipPayload::Bitmap(_)) => panic!("这份剪贴板里没有位图,不该走位图分支"), + None => panic!("没读到任何图片:文件分支没生效"), + } + } +} diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 556d375..b15810d 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "image-workbench", - "version": "3.26.72", + "version": "3.26.73", "identifier": "com.malongan.imageworkbench", "build": { "frontendDist": "../dist", diff --git a/src/clipboard-native.js b/src/clipboard-native.js index 6e3853f..29544ff 100644 --- a/src/clipboard-native.js +++ b/src/clipboard-native.js @@ -39,23 +39,50 @@ return Promise.resolve(blobOrFile) } - /** 读系统剪贴板里的图片 → PNG File(读不到返回 null) */ + /** 最后一次读失败的原因(给上层拼提示文案用;成功时清空) */ + let lastReason = '' + + function makeFile(u8, mime, name) { + const blob = new global.Blob([u8], { type: mime }) + try { return new global.File([blob], name, { type: mime }) } catch (e) { + const named = /** @type {any} */ (blob) + named.name = name + return named + } + } + + /** 读系统剪贴板里的图片 → File(读不到返回 null) + * + * 两种来源(Rust 侧 clipboard_read_image 已经分流): + * · pngBase64 —— 位图:截图、⌘C 复制的图片内容 + * · bytesBase64 —— 文件:在访达里选中图片文件按 ⌘C(剪贴板里只有路径,没有位图) + * 文件分支**保留原始格式**(jpg/heic 不在这里转),交给画布导入链路自己解: + * 那边有 canvas 解码与「转成什么格式」的准入判据,比在 Rust 里瞎转更准。 + */ async function readImage() { const T = tauri() if (!T) return null + lastReason = '' try { const r = await T.core.invoke('clipboard_read_image') - const b64 = r && (r.pngBase64 || r.png_base64) - if (!b64) return null - const u8 = u8FromB64(b64) - const blob = new global.Blob([u8], { type: 'image/png' }) - const name = 'clipboard-' + Date.now() + '.png' - try { return new global.File([blob], name, { type: 'image/png' }) } catch (e) { - const named = /** @type {any} */ (blob) - named.name = name - return named + if (!r) return null + const png = r.pngBase64 || r.png_base64 + if (png) return makeFile(u8FromB64(png), 'image/png', 'clipboard-' + Date.now() + '.png') + const raw = r.bytesBase64 || r.bytes_base64 + if (raw) { + const p2 = String(r.name || '') + const dot = p2.lastIndexOf('.') + const stem = dot > 0 ? p2.slice(0, dot) : p2 + return makeFile(u8FromB64(raw), String(r.mime || 'application/octet-stream'), (stem || 'clipboard-' + Date.now()) + (dot > 0 ? p2.slice(dot) : '.png')) } - } catch (e) { return null } + return null + } catch (e) { + // 2026-11-25:原来的 catch 直接 return null,权限/编码失败/超时全被压成「剪贴板里没有图」, + // 用户与我们都无法定位。这里留一条可查的日志 + 把原因交给上层拼文案。 + lastReason = String((e && e.message) || e || '') + try { console.warn('[iwb] 读取剪贴板图片失败:' + lastReason) } catch (err) { /* ignore */ } + return null + } } /** 把图片写进系统剪贴板(Blob/File 均可) */ @@ -70,5 +97,10 @@ } catch (e) { return false } } - global.IWBNativeClipboard = Object.freeze({ readImage, writeImage, available: () => !!tauri() }) + global.IWBNativeClipboard = Object.freeze({ + readImage, + writeImage, + available: () => !!tauri(), + lastReason: () => lastReason, + }) })(typeof window !== 'undefined' ? window : globalThis) diff --git a/src/clipboard-paste.js b/src/clipboard-paste.js index 89328a1..d9eaae5 100644 --- a/src/clipboard-paste.js +++ b/src/clipboard-paste.js @@ -44,6 +44,16 @@ const nameOf = (f, i) => str(f && f.name) || ('pasted-' + (i + 1) + '.png') + /* 原生剪贴板读取失败的具体原因(文件过大 / 无权限 / 编码失败…)。 + * 没有它的时候,所有失败都被压成「剪贴板里没有可粘贴的内容」——用户刚复制了一张图, + * 看到这句话只会觉得是坏的。 */ + function nativeReason() { + try { + const N = g.IWBNativeClipboard + return (N && typeof N.lastReason === 'function') ? str(N.lastReason()) : '' + } catch (e) { return '' } + } + /* ── 粘贴落点跟随指针(v3.24.69,用户裁定)─────────────────────────────── * 原本落点固定是「视口中心 + 自动避让」,用户实测后要求改成跟鼠标 —— 指哪贴哪, * 连贴几张时也不必每张都去视口中心找回来。 @@ -107,11 +117,21 @@ } /* 单张导入:wImportImage(dataUrl, opts, cb) 是回调式,这里包成 Promise。 - * 它内部可能同时触发 onError 与 cb,用 done 保证只结算一次。 */ + * 它内部可能同时触发 onError 与 cb,用 done 保证只结算一次。 + * 超时兜底(2026-11-25):wImportImage 内部压缩最长要等 12s,worker 卡死时回调仍可能不触发, + * 那时 Promise.all 永不结算 ⇒ 用户按了 Ctrl+V 之后**什么都不发生也不报错**。给一个略大于 + * 内部超时的上限,至少让提示说清是哪一张、卡在哪一步。 */ function importOne(file, ctx) { return new Promise((resolve) => { let done = false - const finish = (v) => { if (!done) { done = true; resolve(v) } } + let timer = null + const finish = (v) => { + if (done) return + done = true + try { if (timer) clearTimeout(timer) } catch (e) { /* ignore */ } + resolve(v) + } + timer = setTimeout(() => finish({ err: (nameOf(file, 0) + ' 解码超时') }), 16000) // FileReader 缺失(无 DOM 宿主 / 极端环境)不能让整个 Promise **reject**: // 调用方是 Promise.all,一次 reject 就把同批其它图片的结果全丢,还会变成未处理拒绝。 let rd = null @@ -195,16 +215,38 @@ ctx.setNotice({ type: 'ok', text: label }) } - /* 多图:并行导入、**一次落盘** —— 撤销一次就回到粘之前(旧实现分 N 次 commit 要按 N 次) */ + /* 多图:并行导入、**一次落盘** —— 撤销一次就回到粘之前(旧实现分 N 次 commit 要按 N 次) + * 2026-11-25(用户反馈「有时候粘贴不进来」):开始就发一条 info 进度提示。 + * 实测一张 6.3MB / 3024×1964 的截图要 ~1.8s(桌面端还要多一次原生 PNG 重编码), + * 旧实现全程静默 ⇒ 用户以为按键没生效,再按一次就贴出两份。 */ function pasteImages(files, ctx) { + if (!files || !files.length) return + // 状态栏那行 11px 文字在底部,粘贴时用户的视线在指针处 —— 必须同时给顶部 toast, + // 否则「正在处理」等于没提示(这就是「有时候粘贴不进来」的观感来源)。 + const tip = files.length > 1 ? ('正在粘贴 ' + files.length + ' 张图片…') : '正在粘贴图片…' + ctx.setNotice({ type: 'info', text: tip }) + try { if (typeof ctx.showToast === 'function') ctx.showToast(tip, 'ok') } catch (e) { /* ignore */ } const jobs = [] for (let i = 0; i < files.length; i++) jobs.push(importOne(files[i], ctx)) Promise.all(jobs).then((results) => { const ok = [] - results.forEach((r, i) => { if (r && r.data) ok.push({ data: r.data, name: nameOf(files[i], i) }) }) - if (!ok.length) { ctx.setNotice({ type: 'err', text: '粘贴图片处理失败,未新建参考图' }); return } + const why = [] + results.forEach((r, i) => { + if (r && r.data) ok.push({ data: r.data, name: nameOf(files[i], i) }) + else if (r && r.err) why.push(r.err) + }) + if (!ok.length) { + // 失败必须能看出原因(前两条就够定位:解码超时 / 字节为空 / 接口拒绝) + const head = why.slice(0, 2).join(';') + const msg = '粘贴图片失败:' + (head || '未读到图片数据') + ctx.setNotice({ type: 'err', text: msg }) + try { if (typeof ctx.showToast === 'function') ctx.showToast(msg, 'err') } catch (e) { /* ignore */ } + return + } const fail = results.length - ok.length - addRefs(ok, ctx, '已粘贴 ' + ok.length + ' 张图片为参考图节点' + (fail ? '(' + fail + ' 张处理失败)' : '')) + const done = '已粘贴 ' + ok.length + ' 张图片为参考图节点' + (fail ? '(' + fail + ' 张处理失败)' : '') + addRefs(ok, ctx, done) + try { if (typeof ctx.showToast === 'function') ctx.showToast(done, fail ? 'err' : 'ok') } catch (e) { /* ignore */ } // 不下载:粘贴 ≠ 另存到下载目录(用户 2026-11-11 裁定) }) } @@ -256,12 +298,23 @@ const c = K.classify(e.clipboardData) if (editable) { // 输入框里:文本 / 链接照样走浏览器原生粘贴(这里**不**接管、不 preventDefault), - // 但图片、非图片文件、复制的节点组原来会被**静默吞掉** —— 用户以为粘上了,其实什么都没发生。 - // 节点组尤其不能静默:剪贴板里同时带着 text/plain 摘要,用户很容易以为会贴出提示词。 + // 但节点组、非图片文件原来会被**静默吞掉** —— 用户以为粘上了,其实什么都没发生。 if (c.kind === 'graph') { ctx.setNotice({ type: 'err', text: '输入框里不能粘贴节点;先点一下画布空白处再按 Ctrl+V' }) - } else if (c.kind === 'image' || c.kind === 'files') { - ctx.setNotice({ type: 'err', text: '图片不能粘进输入框;先点一下画布空白处再粘贴会成为参考图节点' }) + return false + } + if (c.kind === 'image') { + // 2026-11-25(用户反馈「有时候报错贴不进去」):焦点还留在提示词节点的 textarea / + // 搜索框里时,粘图片旧实现只弹一条 err("图片不能粘进输入框")就结束 —— 用户看到的 + // 就是「粘贴报错」。图片本来也放不进输入框,直接接管:blur 掉焦点、贴到画布,并说明一句。 + e.preventDefault() + try { const a = /** @type {any} */ (document.activeElement); if (a && typeof a.blur === 'function') a.blur() } catch (err) { /* ignore */ } + pasteImages(c.images, ctx) + return true + } + if (c.kind === 'files') { + ctx.setNotice({ type: 'err', text: '暂不支持把文件粘进输入框;先点一下画布空白处再粘贴' }) + return false } return false } @@ -283,14 +336,31 @@ // 复制只进了内部那份;用户从旧版本带过来的复制内容也靠它。 // 每个 paste 事件独立处理 → 连按 N 次贴 N 份,不会像旧的定时器方案那样只贴一份。 e.preventDefault() - // 桌面端:Finder/预览复制的图片在 WKWebView 的 paste 事件里读不到,先问原生剪贴板 + // 桌面端:Finder/预览复制的图片在 WKWebView 的 paste 事件里读不到,先问原生剪贴板。 + // 2026-11-25:读不到时**重试一次**(arboard 偶发首次取不到),并且文案要能指路 —— + // "剪贴板里没有可粘贴的内容"会让刚复制了一张图的用户莫名其妙。 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 分钟),请重新复制节点' : '剪贴板里没有可粘贴的内容' }) - }) + const tryRead = (retry) => { + let p = null + try { p = ctx.readNativeImage() } catch (e) { p = null } + Promise.resolve(p).then((f) => { + if (f) { pasteImages([f], ctx); return } + if (retry) { setTimeout(() => tryRead(false), 140); return } + if (ctx.pasteCopiedNodes()) { ctx.setNotice(null); return } + ctx.setNotice({ + type: 'err', + text: ctx.refs.clipExpired + ? '内部剪贴板已过期(10 分钟),请重新复制节点' + : (nativeReason() || '剪贴板里没有可粘贴的图片:复制图片内容,或把图片文件直接拖进画布'), + }) + }, () => { + if (retry) { setTimeout(() => tryRead(false), 140); return } + if (ctx.pasteCopiedNodes()) { ctx.setNotice(null); return } + ctx.setNotice({ type: 'err', text: '读取剪贴板图片失败,请重试或直接把图片拖进画布' }) + }) + } + tryRead(true) return true } if (ctx.pasteCopiedNodes()) return true @@ -307,8 +377,19 @@ // 用户没法照着做(他粘的可能本来就是 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) } }) + const isImg = (f) => (A && typeof A.of === 'function') ? (A.of(f) === 'image') : /^image\//i.test(str(f && f.type)) + // 2026-11-25:只有「全是浏览器解不了的图片格式」(HEIC/TIFF…)才值得问原生剪贴板; + // 旧写法不看类型就去读,粘一份 PDF 时会把剪贴板里**上一条**的图贴出来。 + const allImages = list.length > 0 && list.every(isImg) + if (allImages && typeof ctx.readNativeImage === 'function') { + ctx.setNotice({ type: 'info', text: '正在转换为可用的图片…' }) + let p = null + try { p = ctx.readNativeImage() } catch (e) { p = null } + Promise.resolve(p).then((f) => { + if (f) { pasteImages([f], ctx); return } + const why = (A && typeof A.why === 'function' && list[0]) ? A.why(list[0]) : ('暂不支持粘贴该图片格式(' + ((list[0] && list[0].name) || '未知文件') + ')') + ctx.setNotice({ type: 'err', text: (why || '暂不支持粘贴该图片格式') }) + }, () => ctx.setNotice({ type: 'err', text: '读取剪贴板图片失败,请重试或直接把图片拖进画布' })) return true } const why = (A && typeof A.why === 'function' && list[0]) ? A.why(list[0]) diff --git a/style.css b/style.css index f466383..9859c9d 100644 --- a/style.css +++ b/style.css @@ -1993,7 +1993,7 @@ html { scrollbar-width: thin; scrollbar-color: var(--iwb-border2) color-mix(in s .iwb-settings-modal .iwb-llm-card .iwb-row { margin: var(--iwb-space-4) 0; gap: var(--iwb-space-8); } .iwb-settings-modal .iwb-llm-card .iwb-input { height: auto; padding: var(--iwb-space-6) var(--iwb-space-10); font-size: var(--iwb-font-md); } .iwb-settings-modal .iwb-modellist { display: flex; flex-wrap: wrap; gap: var(--iwb-space-6); margin: var(--iwb-space-2) 0 var(--iwb-space-4); } -.iwb-settings-modal .iwb-modelrow { padding: var(--iwb-space-2) var(--iwb-space-8); border-radius: var(--iwb-radius-full); background: var(--iwb-layer2); border: 1px solid transparent; margin: 0; font-size: var(--iwb-font-sm); } +.iwb-settings-modal .iwb-modelrow { padding: var(--iwb-space-2) var(--iwb-space-12); border-radius: var(--iwb-radius-full); background: var(--iwb-layer2); border: 1px solid transparent; margin: 0; font-size: var(--iwb-font-sm); } .iwb-settings-modal .iwb-modelrow-active { border-color: var(--iwb-brand); background: color-mix(in srgb, var(--iwb-brand) 8%, transparent); } .iwb-settings-modal .iwb-llm-card .iwb-btn-xs { opacity: .5; } .iwb-settings-modal .iwb-llm-card .iwb-btn-xs:hover { opacity: 1; } @@ -2163,6 +2163,10 @@ html { scrollbar-width: thin; scrollbar-color: var(--iwb-border2) color-mix(in s 旧暗色是 #e0e0e0 底 + var(--iwb-text) 字,实测 1.3:1(白底白字)。 */ .iwb-nav-item.on { background: var(--iwb-text); color: var(--iwb-bg); } .iwb-nav-item.on:hover { background: color-mix(in srgb, var(--iwb-text) 88%, var(--iwb-bg)); } +/* 底部「更多」是**菜单开关**,不是页面选中项:展开时不做反色(黑底白点看着像"这一页被选中了", + 和左边真正的页面选中态撞语义),只铺一层和 hover 同级的浅底。 */ +.iwb-nav-more-btn.on { background: var(--iwb-hover); color: var(--iwb-text); } +.iwb-nav-more-btn.on:hover { background: var(--iwb-hover); } /* 底部「更多」:有新版本时 ⋯ → 圆形上箭头,强调色提示可升级 */ .iwb-nav-more-btn.has-update { color: var(--iwb-brand-text); } .iwb-nav-more-btn.has-update .iwb-ic { color: var(--iwb-brand-text); } @@ -2395,9 +2399,13 @@ html { scrollbar-width: thin; scrollbar-color: var(--iwb-border2) color-mix(in s .iwb-modelrow .iwb-modelrow-name{flex:1 1 auto;min-width:0} .iwb-modelrow-defmark{flex:0 0 auto;font-size:var(--iwb-font-xs);color:var(--iwb-text-dim);border-radius:var(--iwb-radius-full);padding:var(--iwb-space-2) var(--iwb-space-8);background:var(--iwb-layer2)} .iwb-settings-modal .iwb-modelrow-default{border-color:var(--iwb-brand);background:color-mix(in srgb,var(--iwb-brand) 8%,transparent)} -.iwb-model-del{flex:0 0 auto;width:26px;height:26px;display:inline-flex;align-items:center;justify-content:center;border:0;background:transparent;border-radius:var(--iwb-radius-control);color:var(--iwb-err);cursor:pointer;opacity:0;visibility:hidden;pointer-events:none;transition:opacity .15s ease} -.iwb-modelrow:hover .iwb-model-del,.iwb-modelrow:focus-within .iwb-model-del{opacity:1;visibility:visible;pointer-events:auto} -.iwb-model-del:hover:not(:disabled){background:var(--iwb-err-bg)} +/* 2026-11-25(用户反馈二改):默认中性灰不用红(红=危险色,常驻会抢注意力), + 只在 hover 时才转红 + 红底;尺寸走 --iwb-control-h,与同一行的厂商下拉等高对齐。 + 显隐用「透明度过渡 + visibility 延迟」而不是两个属性都过渡: + 旧写法 visibility 立即切换 → 鼠标进出的那一帧只有透明度在动,视觉上像卡了一下。 */ +.iwb-model-del{flex:0 0 auto;width:var(--iwb-control-h);height:var(--iwb-control-h);padding:0;display:inline-flex;align-items:center;justify-content:center;border:0;background:transparent;border-radius:var(--iwb-radius-control);color:var(--iwb-text-dim);cursor:pointer;opacity:0;visibility:hidden;pointer-events:none;transition:opacity .09s linear,background-color .09s linear,color .09s linear,visibility 0s linear .09s} +.iwb-modelrow:hover .iwb-model-del,.iwb-modelrow:focus-within .iwb-model-del{opacity:1;visibility:visible;pointer-events:auto;transition:opacity .09s linear,background-color .09s linear,color .09s linear,visibility 0s linear 0s} +.iwb-model-del:hover:not(:disabled){color:var(--iwb-err);background:var(--iwb-err-bg)} .iwb-model-del .iwb-ic{width:var(--iwb-icon-sm);height:var(--iwb-icon-sm)} .iwb-model-del:disabled{cursor:default;opacity:0!important;pointer-events:none} diff --git a/tests/clipboard-native-test.js b/tests/clipboard-native-test.js new file mode 100644 index 0000000..1a72d4e --- /dev/null +++ b/tests/clipboard-native-test.js @@ -0,0 +1,66 @@ +'use strict' +// 桌面端剪贴板读图(src/clipboard-native.js)载荷解析测试 +// 背景(2026-11-25 用户反馈「有时候粘贴不进来」):Rust 侧 clipboard_read_image 有两条来源 —— +// · 位图:截图 / ⌘C 复制图片内容 → pngBase64 +// · 文件:访达里选中图片文件按 ⌘C → bytesBase64 + mime + name(剪贴板里没有位图) +// 前端必须两种都认,且失败时**留下原因**(旧实现把权限/编码/超时全压成 null → 用户只看到一句 +// 「剪贴板里没有可粘贴的内容」)。真实字节链路在桌面端实测,这里测映射与降级。 +const fs = require('fs') +const path = require('path') +const root = path.join(__dirname, '..') +let pass = 0, fail = 0 +const ok = (name, cond) => { if (cond) { pass++; console.log(' ✅ ' + name) } else { fail++; console.log(' ❌ ' + name) } } +const eq = (name, got, want) => ok(name + '(' + JSON.stringify(got) + ' === ' + JSON.stringify(want) + ')', got === want) + +let replies = [] +const win = { + btoa: (s) => Buffer.from(s, 'binary').toString('base64'), + atob: (s) => Buffer.from(s, 'base64').toString('binary'), + Blob: global.Blob, + File: global.File, + __TAURI__: { core: { invoke: async () => { const r = replies.shift(); if (r instanceof Error) throw r; return r } } }, +} +new Function('window', 'globalThis', fs.readFileSync(path.join(root, 'src/clipboard-native.js'), 'utf8'))(win, win) +const N = win.IWBNativeClipboard +ok('模块加载并导出 IWBNativeClipboard', !!N && typeof N.readImage === 'function') +eq('桌面端 available()', N.available(), true) + +const pngB64 = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).toString('base64') + +;(async () => { + // 1) 位图:pngBase64 → PNG File + replies = [{ width: 2, height: 2, pngBase64: pngB64 }] + const a = await N.readImage() + ok('位图 → 返回 File', !!a && typeof a.arrayBuffer === 'function') + eq('位图 → mime 固定为 image/png', a && a.type, 'image/png') + ok('位图 → 文件名以 .png 结尾', /\.png$/.test(String(a && a.name))) + eq('位图 → 字节长度', a ? (await a.arrayBuffer()).byteLength : -1, 8) + + // 2) 文件:bytesBase64 + mime + name → 保留原始格式(不在这一层转码) + const jpg = Buffer.from([0xff, 0xd8, 0xff, 0xe0]).toString('base64') + replies = [{ name: 'IMG_0001.JPG', mime: 'image/jpeg', size: 4, bytesBase64: jpg }] + const b = await N.readImage() + eq('文件 → 保留原 mime', b && b.type, 'image/jpeg') + eq('文件 → 保留原文件名', b && b.name, 'IMG_0001.JPG') + eq('文件 → 字节长度', b ? (await b.arrayBuffer()).byteLength : -1, 4) + + // 3) 两种字段都没有 → null(剪贴板里确实没图) + replies = [{}] + eq('空载荷 → null', await N.readImage(), null) + eq('成功读取后原因清空', N.lastReason(), '') + + // 4) Rust 报错(文件过大 / 无权限)→ null + 留下原因,供上层拼文案 + replies = [new Error('图片文件太大(88 MB,上限 48 MB):请先压缩,或直接把它拖进画布')] + eq('读取失败 → null', await N.readImage(), null) + ok('读取失败 → lastReason 带上具体原因', N.lastReason().indexOf('太大') > 0) + eq('下一次成功读取 → 原因清空', (replies = [{ pngBase64: pngB64 }], await N.readImage(), N.lastReason()), '') + + // 5) 非桌面端(没有 __TAURI__)→ null,不抛 + const win2 = { btoa: win.btoa, atob: win.atob, Blob: global.Blob, File: global.File } + new Function('window', 'globalThis', fs.readFileSync(path.join(root, 'src/clipboard-native.js'), 'utf8'))(win2, win2) + eq('非桌面端 available()', win2.IWBNativeClipboard.available(), false) + eq('非桌面端 readImage() → null', await win2.IWBNativeClipboard.readImage(), null) + + console.log(fail ? ('\n❌ ' + fail + ' 项失败') : '\n✅ clipboard-native 全部通过(' + pass + ')') + process.exit(fail ? 1 : 0) +})() diff --git a/tests/clipboard-paste-test.js b/tests/clipboard-paste-test.js index 8d5fd37..85dd754 100644 --- a/tests/clipboard-paste-test.js +++ b/tests/clipboard-paste-test.js @@ -230,12 +230,14 @@ function makeCtx(over) { eq('输入框内 → 文本不弹提示(原生粘贴本来就正常)', ctx.log.length, 0) } { + // 2026-11-25(用户反馈「有时候报错贴不进去」):焦点留在输入框里粘图片,旧行为只弹一条 + // err「图片不能粘进输入框」就结束 —— 用户看到的就是「粘贴报错」。图片本来就放不进输入框, + // 现在直接接管:blur 焦点 → 贴到画布(这里只断言接管与即时反馈,真落节点要 FileReader,走 e2e)。 const ctx = makeCtx() const ev = pasteEv({ files: [{ name: 'a.png', type: 'image/png', size: 10 }] }) - eq('输入框内粘图片 → 不接管', P.handle(ev, ctx, true), false) - eq('输入框内粘图片 → 不 preventDefault', ev.defaultPrevented, false) - ok('输入框内粘图片 → 明确提示「不能粘进输入框」', ctx.log.some((x) => x.indexOf('notice:err') === 0 && x.indexOf('输入框') > 0)) - eq('输入框内粘图片 → 不落节点', ctx.log.filter((x) => x.startsWith('commit')).length, 0) + eq('输入框内粘图片 → 直接接管(不再只弹报错)', P.handle(ev, ctx, true), true) + eq('输入框内粘图片 → preventDefault', ev.defaultPrevented, true) + ok('输入框内粘图片 → 立即给「正在粘贴」反馈', ctx.log.some((x) => x.indexOf('notice:info') === 0)) } { const ctx = makeCtx()