fix: v3.26.73 垃圾桶悬停才显形 / 更多菜单展开不反色 / 桌面端可粘贴访达复制的图片文件
This commit is contained in:
1 parent
98fd50ad91
commit
3f0f13f867
14 files changed
+536
-53
No files matched your search
+278
-5
@@ -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<Option<ClipImagePayload>, 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<Option<ClipImagePayload>, 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<Option<ClipImagePayload>, 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<std::path::PathBuf> {
|
||||
#[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<PathBuf> {
|
||||
use objc2_app_kit::NSPasteboard;
|
||||
use objc2_foundation::{NSArray, NSString};
|
||||
|
||||
let mut out: Vec<PathBuf> = 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::<NSArray>() {
|
||||
for item in arr.iter() {
|
||||
// 元素理论上是 NSString(路径),但 plist 是弱类型的,逐个降级判断
|
||||
if let Some(s) = item.downcast_ref::<NSString>() {
|
||||
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<PathBuf> {
|
||||
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<Option<ClipFilePayload>, 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<Option<ClipPayload>, 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<bool, String> {
|
||||
@@ -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<u8> = vec![255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255];
|
||||
let mut png: Vec<u8> = 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!("没读到任何图片:文件分支没生效"),
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user