Files
image-workbench-desktop/src/clipboard-native.js
T

83 lines
3.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* 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)