use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use tauri::menu::{IsMenuItem, Menu, MenuItem, PredefinedMenuItem, Submenu}; use tauri::tray::TrayIconBuilder; use tauri::webview::NewWindowResponse; use tauri::{AppHandle, Emitter, Manager, PhysicalPosition, PhysicalSize, WebviewUrl, WebviewWindowBuilder, WindowEvent}; use tauri_plugin_fs::FsExt; // 提供 fs_scope():运行时给「资料目录」授权 // 「是否正在真正退出」:托盘菜单的「退出」或 Cmd+Q 才会置位, // 其余情况点窗口关闭按钮只是收进托盘,进程继续跑(后台生图不中断)。 static QUITTING: AtomicBool = AtomicBool::new(false); #[derive(serde::Serialize, serde::Deserialize, Clone, Default)] struct WindowGeom { x: i32, y: i32, w: u32, h: u32, } fn geom_file(app: &AppHandle, label: &str) -> Option { app.path().app_config_dir().ok().map(|d| { // 主窗口沿用历史文件名,避免升级后把已记住的位置丢掉一次 if label == "main" { d.join("window-geom.json") } else { d.join(format!("{}-geom.json", label)) } }) } // 只在窗口处于普通状态时记录:最大化/全屏时的尺寸不是用户想恢复的那个尺寸。 // 按 label 取窗口,主窗口与浏览器窗口共用同一套机制,各自存各自的文件。 fn save_geom(app: &AppHandle, label: &str) { let Some(win) = app.get_window(label) else { return }; if win.is_maximized().unwrap_or(false) || win.is_fullscreen().unwrap_or(false) { return; } let (Ok(size), Ok(pos)) = (win.inner_size(), win.outer_position()) else { return; }; let g = WindowGeom { x: pos.x, y: pos.y, w: size.width, h: size.height }; if let Some(p) = geom_file(app, label) { if let Some(dir) = p.parent() { let _ = std::fs::create_dir_all(dir); } if let Ok(txt) = serde_json::to_string(&g) { let _ = std::fs::write(p, txt); } } } // 恢复上次窗口大小与位置;中心点不在任何显示器内就只恢复尺寸(换过显示器不至于把窗口丢到屏幕外) fn restore_geom(app: &AppHandle, label: &str, min_w: u32, min_h: u32) { let Some(win) = app.get_window(label) else { return }; let Some(p) = geom_file(app, label) else { return }; let Ok(txt) = std::fs::read_to_string(p) else { return }; let Ok(g) = serde_json::from_str::(&txt) else { return }; // 最小尺寸与窗口下限对齐:否则会恢复出一个比下限还小的窗口 // (曾实测 1051x488 时画布渲染成空白) let w = g.w.max(min_w); let h = g.h.max(min_h); let _ = win.set_size(PhysicalSize::new(w, h)); let cx = g.x + (w as i32) / 2; let cy = g.y + (h as i32) / 2; let visible = win .available_monitors() .map(|ms| { ms.iter().any(|m| { let mp = m.position(); let ms = m.size(); cx >= mp.x && cx <= mp.x + ms.width as i32 && cy >= mp.y && cy <= mp.y + ms.height as i32 }) }) .unwrap_or(false); if visible { let _ = win.set_position(PhysicalPosition::new(g.x, g.y)); } } fn show_main(app: &AppHandle) { if let Some(w) = app.get_window("main") { let _ = w.show(); let _ = w.unminimize(); let _ = w.set_focus(); } } // 系统托盘:左键(macOS:点图标出菜单)+ 菜单「显示主窗口 / 隐藏到托盘 / 退出」 fn build_tray(app: &AppHandle) -> tauri::Result<()> { let show = MenuItem::with_id(app, "show", "显示主窗口", true, None::<&str>)?; let hide = MenuItem::with_id(app, "hide", "隐藏到托盘", true, None::<&str>)?; let quit = MenuItem::with_id(app, "quit", "退出", true, None::<&str>)?; let menu = Menu::with_items(app, &[&show, &hide, &quit])?; let mut builder = TrayIconBuilder::with_id("main") .tooltip("无限画布") .menu(&menu) // 左键 = 直接唤出主窗口(不用再点一次菜单);右键才出菜单(显示/隐藏/退出) .show_menu_on_left_click(false) .on_menu_event(|app, e| match e.id().as_ref() { "show" => show_main(app), "hide" => { if let Some(w) = app.get_window("main") { let _ = w.hide(); } } "quit" => { QUITTING.store(true, Ordering::SeqCst); app.exit(0); } _ => {} }); // 所有平台统一:左键点图标 = 显示/聚焦主窗口(macOS 也照做,菜单改到右键) builder = builder.on_tray_icon_event(|tray, event| { if let tauri::tray::TrayIconEvent::Click { button: tauri::tray::MouseButton::Left, button_state: tauri::tray::MouseButtonState::Up, .. } = event { show_main(tray.app_handle()); } }); // 托盘图标按平台分(icon_as_template 只在 macOS 生效,Windows 是 no-op): // - macOS:单色模板图标 + icon_as_template(true),随菜单栏深浅自动反色。 // - Windows/Linux:template 不反色、直接渲染像素。tray-template.png 是「黑底 + IW 镂空」, // 深色任务栏上黑底融入背景、镂空透出背景 ⇒ 图标「看不见」。所以这里用实心主图标 // default_window_icon(黑底白 IW),深色靠白 IW、浅色靠黑底方块,两种背景都清晰;不加描边。 #[cfg(target_os = "macos")] { match tauri::image::Image::from_bytes(include_bytes!("../icons/tray-template.png")) { Ok(ic) => builder = builder.icon(ic).icon_as_template(true), Err(_) => { if let Some(icon) = app.default_window_icon().cloned() { builder = builder.icon(icon); } } } } #[cfg(not(target_os = "macos"))] { if let Some(icon) = app.default_window_icon().cloned() { builder = builder.icon(icon); } else if let Ok(ic) = tauri::image::Image::from_bytes(include_bytes!("../icons/tray-template.png")) { // 兜底:极端情况拿不到主图标,仍给一张,避免空托盘 builder = builder.icon(ic); } } builder.build(app)?; Ok(()) } // 把「资料目录」加进本次运行的 fs scope。 // 为什么需要它:tauri-plugin-fs 的路径白名单是**运行时**的,重启就没了;而资料目录是用户 // 在设置里选的、存在应用配置里 ⇒ 启动时由这里重新授权一次,之后 fs 插件的读写才允许。 /// 当前进程的常驻内存(MB)。用于状态栏显示,方便对比性能改动前后的内存占用。 /// macOS/Linux 用 ps 读 RSS;Windows 用 PowerShell 读 WorkingSet64(作为兜底,轮询间隔 4s 可接受)。 #[tauri::command] fn app_memory_mb() -> u64 { let pid = std::process::id(); #[cfg(unix)] { let out = std::process::Command::new("ps") .args(["-o", "rss=", "-p", &pid.to_string()]) .output(); if let Ok(o) = out { if o.status.success() { let txt = String::from_utf8_lossy(&o.stdout); if let Ok(kb) = txt.trim().parse::() { return kb / 1024; } } } 0 } #[cfg(windows)] { use windows_sys::Win32::System::ProcessStatus::{GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS}; use windows_sys::Win32::System::Threading::GetCurrentProcess; let mut pmc: PROCESS_MEMORY_COUNTERS = unsafe { std::mem::zeroed() }; pmc.cb = std::mem::size_of::() as u32; let ok = unsafe { GetProcessMemoryInfo(GetCurrentProcess(), &mut pmc, pmc.cb) }; if ok != 0 { return (pmc.WorkingSetSize as u64) / (1024 * 1024); } 0 } #[cfg(not(any(unix, windows)))] { 0 } } // 把用户**显式选择**的路径加进本次运行的 fs scope(2026-11-26,相册「只引用本地文件」用)。 // 为什么单独一条命令:dialog 选中的外部图片不在「资料目录」里,fs 插件默认拒绝读写; // 这里只授权调用方传进来的具体路径,不扩大 $HOME 之类的面。 // 用户显式选择过的外部路径:tauri fs scope 是**运行时**的,重启就失效。 // 相册的 {__file} 只存路径,若不持久化授权,第二天打开就只剩缩略图缓存、组合/参考图全空。 const FILE_GRANTS_FILE: &str = "file-grants.json"; fn file_grants_path(app: &AppHandle) -> Option { app.path().app_config_dir().ok().map(|c| c.join(FILE_GRANTS_FILE)) } fn persist_file_grants(app: &AppHandle, paths: &[String]) { let Some(p) = file_grants_path(app) else { return }; let mut list: Vec = std::fs::read_to_string(&p) .ok() .and_then(|s| serde_json::from_str::>(&s).ok()) .unwrap_or_default(); for x in paths { if !x.is_empty() && !list.iter().any(|y| y == x) { list.push(x.clone()) } } if let Some(dir) = p.parent() { let _ = std::fs::create_dir_all(dir); } if let Ok(txt) = serde_json::to_vec(&list) { let _ = std::fs::write(&p, txt); } } fn restore_file_grants(app: &AppHandle) { let Some(p) = file_grants_path(app) else { return }; let list: Vec = std::fs::read_to_string(&p) .ok() .and_then(|s| serde_json::from_str::>(&s).ok()) .unwrap_or_default(); for raw in list { let p = std::path::PathBuf::from(&raw); if !p.is_absolute() || !p.exists() { continue } if p.is_dir() { let _ = app.fs_scope().allow_directory(&p, true); } else { let _ = app.fs_scope().allow_file(&p); } } } #[tauri::command] fn grant_paths(app: AppHandle, paths: Vec) -> Result, String> { let mut ok: Vec = Vec::new(); for raw in paths { let p = std::path::PathBuf::from(&raw); if !p.is_absolute() { continue; } let granted = if p.is_dir() { app.fs_scope().allow_directory(&p, true).is_ok() } else { app.fs_scope().allow_file(&p).is_ok() }; if granted { ok.push(p.to_string_lossy().to_string()); } } if !ok.is_empty() { persist_file_grants(&app, &ok); } Ok(ok) } #[tauri::command] fn grant_dir(app: AppHandle, dir: String, record: Option) -> Result { let p = std::path::PathBuf::from(&dir); if !p.is_absolute() { return Err("资料目录必须是绝对路径".into()); } std::fs::create_dir_all(&p).map_err(|e| e.to_string())?; app.fs_scope() .allow_directory(&p, true) .map_err(|e| e.to_string())?; // 只有「资料目录」才记进配置(record 默认 true);下载目录等传 record=false, // 否则会把 data-dir.txt 覆盖成别的目录,导致「打开」跳到错误位置。 if record.unwrap_or(true) { if let Ok(cfg) = app.path().app_config_dir() { let _ = std::fs::create_dir_all(&cfg); let _ = std::fs::write(cfg.join("data-dir.txt"), p.to_string_lossy().as_bytes()); } } Ok(p.to_string_lossy().to_string()) } // 递归复制整个资料目录(「转移」用:整库搬到新位置,成功后再切换指针) #[tauri::command] fn copy_tree(src: String, dst: String) -> Result { fn walk(from: &std::path::Path, to: &std::path::Path, n: &mut u64) -> std::io::Result<()> { std::fs::create_dir_all(to)?; for e in std::fs::read_dir(from)? { let e = e?; let name = e.file_name(); if name.to_string_lossy() == "trash" { continue } // 回收站不搬 let f = e.path(); let t = to.join(&name); if e.file_type()?.is_dir() { walk(&f, &t, n)? } else { std::fs::copy(&f, &t)?; *n += 1 } } Ok(()) } let s = std::path::PathBuf::from(&src); let d = std::path::PathBuf::from(&dst); if !s.is_dir() { return Err("源目录不存在".into()) } if d.starts_with(&s) { return Err("目标不能放在源目录里面".into()) } if d.exists() && std::fs::read_dir(&d).map(|mut i| i.next().is_some()).unwrap_or(false) { return Err("目标目录不是空目录".into()) } std::fs::create_dir_all(&d).map_err(|e| e.to_string())?; let mut n = 0u64; walk(&s, &d, &mut n).map_err(|e| e.to_string())?; Ok(n) } // 打开应用数据目录(设置里的「打开数据目录」按钮用;macOS 访达 / Windows 资源管理器 / Linux xdg-open) #[tauri::command] fn open_data_subpath(app: AppHandle, rel: String) -> Result { // 只允许打开「资料目录」下的子路径:rel 由宿主/插件传入,必须做规范化 + 前缀校验, // 否则等于给插件一个任意路径的打开权限。 let recorded = app .path() .app_config_dir() .ok() .and_then(|c| std::fs::read_to_string(c.join("data-dir.txt")).ok()) .map(|s| s.trim().to_string()) .filter(|s| !s.is_empty()); let base = match recorded { Some(p) => std::path::PathBuf::from(p), None => app.path().app_data_dir().map_err(|e| e.to_string())?, }; let base = base.canonicalize().map_err(|e| e.to_string())?; let target = base.join(rel.trim_start_matches('/')).canonicalize().map_err(|e| e.to_string())?; if !target.starts_with(&base) { return Err("路径不在资料目录内".into()); } std::fs::create_dir_all(&target).map_err(|e| e.to_string())?; let path = target.to_string_lossy().to_string(); #[cfg(target_os = "macos")] let cmd = "open"; #[cfg(target_os = "windows")] let cmd = "explorer"; #[cfg(target_os = "linux")] let cmd = "xdg-open"; std::process::Command::new(cmd) .arg(&path) .spawn() .map_err(|e| e.to_string())?; Ok(path) } #[tauri::command] fn open_app_data_dir(app: AppHandle) -> Result { // 资料目录(用户选的那个)优先;没设置过才退回应用私有目录 let recorded = app .path() .app_config_dir() .ok() .and_then(|c| std::fs::read_to_string(c.join("data-dir.txt")).ok()) .map(|s| s.trim().to_string()) .filter(|s| !s.is_empty() && std::path::Path::new(s).exists()); let dir = match recorded { Some(p) => std::path::PathBuf::from(p), None => app.path().app_data_dir().map_err(|e| e.to_string())?, }; std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; let path = dir.to_string_lossy().to_string(); #[cfg(target_os = "macos")] let cmd = "open"; #[cfg(target_os = "windows")] let cmd = "explorer"; #[cfg(target_os = "linux")] let cmd = "xdg-open"; std::process::Command::new(cmd) .arg(&dir) .spawn() .map_err(|e| e.to_string())?; Ok(path) } use tauri_plugin_updater::UpdaterExt; #[tauri::command] fn clipboard_write_text(text: String) -> Result { let mut cb = Clipboard::new().map_err(|e| e.to_string())?; cb.set_text(text).map_err(|e| e.to_string())?; Ok(true) } #[tauri::command] fn clipboard_read_text() -> Result { let mut cb = Clipboard::new().map_err(|e| e.to_string())?; Ok(cb.get_text().unwrap_or_default()) } #[tauri::command] async fn check_update(app: tauri::AppHandle) -> Result, String> { let updater = app.updater().map_err(|e| e.to_string())?; match updater.check().await { Ok(Some(update)) => Ok(Some(serde_json::json!({ "version": update.version, "currentVersion": update.current_version, "notes": update.body.unwrap_or_default(), "date": update.date.map(|d| d.to_string()).unwrap_or_default() }))), Ok(None) => Ok(None), Err(e) => Err(e.to_string()), } } #[tauri::command] async fn install_update(app: tauri::AppHandle) -> Result { use tauri::Emitter; let updater = app.updater().map_err(|e| e.to_string())?; let found = updater.check().await.map_err(|e| e.to_string())?; let Some(update) = found else { return Ok(false) }; // 真实下载进度(v3.26.95):updater 的 on_chunk 能拿到累计字节与总大小, // 通过事件窗口送回前端画外圈进度环。80ms 节流,避免每个 chunk 都跨进程投递。 let emit_app = app.clone(); let done_app = app.clone(); let mut downloaded: u64 = 0; let mut last_emit = std::time::Instant::now(); update .download_and_install( move |chunk, total| { downloaded += chunk as u64; let done = total.map(|t| downloaded >= t).unwrap_or(false); if last_emit.elapsed().as_millis() >= 80 || done { last_emit = std::time::Instant::now(); let _ = emit_app.emit("iwb-update-progress", serde_json::json!({ "phase": "downloading", "downloaded": downloaded, "total": total })); } }, move || { // 下载完成 → 进入安装(签名校验/替换文件),这一段没有字节级进度 let _ = done_app.emit("iwb-update-progress", serde_json::json!({ "phase": "installing" })); }, ) .await .map_err(|e| e.to_string())?; app.restart(); } // 浏览器收藏夹的原生弹出菜单(2026-11-26,方案 B) // 为什么必须原生:网页是子 webview,DOM 菜单永远会被它盖住;系统菜单在 OS 层, // 不会遮挡页面,也不会让网页消失。菜单项点击通过 iwb-bookmark-open / iwb-bookmark-add // 事件回给前端插件,由插件更新 settings 或导航。 #[tauri::command] async fn browser_bookmarks_menu( app: AppHandle, mode: String, groups: Vec, current_url: String, ) -> Result { let win = app.get_window("main").ok_or_else(|| "主窗口不存在".to_string())?; // 收藏目标组:单组菜单 → 该组;「所有书签」→ 空(插件落第一个组)。 // 用户点「海报」里的收藏,应该进「海报」,而不是永远进第一个组「常用」。 let single = !mode.is_empty(); let add_group = if single { mode.clone() } else { String::new() }; let add_id = format!("bm-add:{}:{}", b64_encode(add_group.as_bytes()), b64_encode(current_url.as_bytes())); let add_item = MenuItem::with_id( &app, add_id, "收藏当前页", !current_url.trim().is_empty(), None::<&str>, ) .map_err(|e| e.to_string())?; let sep = PredefinedMenuItem::separator(&app).map_err(|e| e.to_string())?; let mut owned_items: Vec> = Vec::new(); let mut owned_subs: Vec> = Vec::new(); let mut refs: Vec<&dyn IsMenuItem> = vec![&add_item, &sep]; let mut counter = 0usize; for g in groups.iter() { let gname = g.get("name").and_then(|v| v.as_str()).unwrap_or("收藏夹"); let gid = g.get("id").and_then(|v| v.as_str()).unwrap_or(""); if single && gid != mode.as_str() { continue; } let items = g.get("items").and_then(|v| v.as_array()).cloned().unwrap_or_default(); if single { // 单组模式:不再重复显示分组名(用户指出那一层是多余的) if items.is_empty() { let empty = MenuItem::with_id( &app, format!("bm-empty:{counter}"), "这个分组还没有书签", false, None::<&str>, ).map_err(|e| e.to_string())?; owned_items.push(empty); } for it in items.iter() { let title = it.get("title").and_then(|v| v.as_str()).unwrap_or("书签"); let url = it.get("url").and_then(|v| v.as_str()).unwrap_or(""); if url.is_empty() { continue; } counter += 1; let id = format!("bm-open:{}:{}", counter, b64_encode(url.as_bytes())); let mi = MenuItem::with_id(&app, id, title, true, None::<&str>) .map_err(|e| e.to_string())?; owned_items.push(mi); } } else { // 全部分组:每个分组一个子菜单(原生「文件夹」) let mut g_items: Vec> = Vec::new(); for it in items.iter() { let title = it.get("title").and_then(|v| v.as_str()).unwrap_or("书签"); let url = it.get("url").and_then(|v| v.as_str()).unwrap_or(""); if url.is_empty() { continue; } counter += 1; let id = format!("bm-open:{}:{}", counter, b64_encode(url.as_bytes())); let mi = MenuItem::with_id(&app, id, title, true, None::<&str>) .map_err(|e| e.to_string())?; g_items.push(mi); } if g_items.is_empty() { let empty = MenuItem::with_id( &app, format!("bm-empty:{}", counter), "(空)", false, None::<&str>, ).map_err(|e| e.to_string())?; g_items.push(empty); } let mut grefs: Vec<&dyn IsMenuItem> = Vec::new(); for mi in g_items.iter() { grefs.push(mi); } let sub = Submenu::with_items(&app, gname, true, &grefs) .map_err(|e| e.to_string())?; owned_subs.push(sub); } } if single { for mi in owned_items.iter() { refs.push(mi); } } else { for sub in owned_subs.iter() { refs.push(sub); } } let menu = Menu::with_items(&app, &refs).map_err(|e| e.to_string())?; win.popup_menu(&menu).map_err(|e| e.to_string())?; Ok(true) } use arboard::Clipboard; fn b64_encode(bytes: &[u8]) -> String { use base64::Engine; base64::engine::general_purpose::STANDARD.encode(bytes) } fn b64_decode(s: &str) -> Result, String> { use base64::Engine; base64::engine::general_purpose::STANDARD .decode(s.as_bytes()) .map_err(|e| e.to_string()) } #[derive(serde::Serialize)] #[serde(rename_all = "camelCase")] struct ClipImagePayload { width: u32, height: u32, png_base64: String, } /// 「复制的是文件」(在 Finder 里选中图片文件按 ⌘C)时,剪贴板里**没有位图**,只有路径, /// arboard 的 get_image 读到的是 None —— 这就是「明明复制了一张图却粘不进来」。 /// /// 这里刻意**不在 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, Err(_) => return Ok(None), }; let w = img.width as u32; let h = img.height as u32; if w == 0 || h == 0 { return Ok(None); } let raw = img.bytes.into_owned(); let buf = image::RgbaImage::from_raw(w, h, raw) .ok_or_else(|| "剪贴板图片像素数据不完整".to_string())?; let mut png: Vec = Vec::new(); { use image::ImageEncoder; let enc = image::codecs::png::PngEncoder::new(&mut png); enc.write_image(buf.as_raw(), w, h, image::ExtendedColorType::Rgba8) .map_err(|e| e.to_string())?; } Ok(Some(ClipImagePayload { width: w, height: h, png_base64: b64_encode(&png), })) } /// 按文件头判 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 { let bytes = b64_decode(&png_base64)?; let img = image::load_from_memory(&bytes).map_err(|e| e.to_string())?.to_rgba8(); let (w, h) = (img.width() as usize, img.height() as usize); let mut cb = Clipboard::new().map_err(|e| e.to_string())?; cb.set_image(arboard::ImageData { width: w, height: h, bytes: std::borrow::Cow::Owned(img.into_raw()), }) .map_err(|e| e.to_string())?; Ok(true) } fn open_external(url: &str) -> Result<(), String> { #[cfg(target_os = "macos")] { std::process::Command::new("open").arg(url).spawn().map(|_| ()).map_err(|e| e.to_string()) } #[cfg(target_os = "windows")] { std::process::Command::new("cmd") .args(["/C", "start", "", url]) .spawn() .map(|_| ()) .map_err(|e| e.to_string()) } #[cfg(all(unix, not(target_os = "macos")))] { std::process::Command::new("xdg-open").arg(url).spawn().map(|_| ()).map_err(|e| e.to_string()) } } #[tauri::command] fn open_external_url(url: String) -> Result { if !(url.starts_with("http://") || url.starts_with("https://")) { return Err("只允许 http/https".into()); } open_external(&url)?; Ok(true) } // 应用内打开网页:固定 label `browser` 复用同一个窗口,重复打开就聚焦并导航到新地址。 // 加载的是外部网站自己的页面,不受主窗口 CSP 约束(Tauri 的 CSP 只注入自身的 HTML 页面), // 这也是官方推荐的「加载不可信远程内容」方式,避免 iframe 被对方 X-Frame-Options 拒绝。 // 浏览器窗口不在 capabilities 里 ⇒ 无 IPC 权限,正好不该让它碰到宿主 API。 // // 保留 async(内部无 await):让命令跑在 Tauri 的异步运行时里,不占 IPC 主线程; // 建窗/导航都是同步 API,不需要 await 也不需要额外 yield。 #[tauri::command] async fn open_browser_window(app: AppHandle, url: String) -> Result { let parsed = url::Url::parse(&url).map_err(|_| "网址格式不合法".to_string())?; if parsed.scheme() != "http" && parsed.scheme() != "https" { return Err("只允许 http/https".into()); } let label = "browser"; // 窗口标题跟着目标站点走,复用窗口时也要更新,否则标题永远是第一次打开的那个站。 let title = parsed .host_str() .filter(|h| !h.is_empty()) .unwrap_or("浏览器") .to_string(); if let Some(win) = app.get_webview_window(label) { // 已存在:显示、取消最小化、聚焦,再导航到新地址。 let _ = win.show(); let _ = win.unminimize(); let _ = win.set_focus(); let _ = win.set_title(&title); // 用原生命令导航,不在外部页面的 JS 上下文里执行字符串。 win.navigate(parsed).map_err(|e| e.to_string())?; return Ok(true); } let app_for_new_window = app.clone(); WebviewWindowBuilder::new(&app, label, WebviewUrl::External(parsed)) .title(&title) .inner_size(1200.0, 820.0) .min_inner_size(800.0, 600.0) .center() .on_new_window(move |url, _features| { // 独立浏览器窗口里点画板等 target="_blank" 链接:原地导航,不弹新窗口。 if let Some(url) = new_window_url(url) { if let Some(win) = app_for_new_window.get_webview_window("browser") { let _ = win.navigate(url.clone()); if let Some(host) = url.host_str().filter(|h| !h.is_empty()) { let _ = win.set_title(host); } } } NewWindowResponse::Deny }) .build() .map_err(|e| e.to_string())?; // 恢复上次浏览器窗口的位置/大小;没有记录时保持上面的居中默认值。 restore_geom(&app, label, 800, 600); Ok(true) } // 浏览器窗口控制:由主窗口(有 IPC 权限)驱动,browser 窗口自身仍然无 IPC 权限。 // back/forward 用固定字符串且不拼接任何外部输入,不构成注入面。 #[tauri::command] async fn browser_control(app: AppHandle, action: String) -> Result { let win = app .get_webview_window("browser") .ok_or_else(|| "浏览器窗口未打开".to_string())?; match action.as_str() { "back" => win.eval("history.back()").map_err(|e| e.to_string())?, "forward" => win.eval("history.forward()").map_err(|e| e.to_string())?, "reload" => win.reload().map_err(|e| e.to_string())?, // 关闭走正常 CloseRequested 路径;主窗口以外不再 prevent_close,会真正销毁。 "close" => win.close().map_err(|e| e.to_string())?, _ => return Err("未知操作".into()), } Ok(true) } // 面板用来显示「当前打开的是哪个站」以及窗口是否还活着。 #[tauri::command] async fn browser_state(app: AppHandle) -> Result { match app.get_webview_window("browser") { Some(win) => Ok(serde_json::json!({ "open": true, "url": win.url().map(|u| u.to_string()).unwrap_or_default() })), None => Ok(serde_json::json!({ "open": false, "url": "" })), } } // ── 画布内嵌浏览器(主窗口的**子 webview**)──────────────────────────────────── // 与上面「独立窗口」是两条完全不同的路:这里用 `Window::add_child` 把 webview 作为 // 主窗口的子视图挂在画布节点上,网页真正长在画布里面(跟着平移、缩放)。 // // 为什么不用 iframe:GitHub / 站酷 / Figma / Pinterest 这些站用 X-Frame-Options 或 // CSP frame-ancestors 明确拒绝被嵌,且主窗口 CSP 没有 frame-src。 // // 三条硬约束(2026-11-19 重做时定下,都是踩坑换来的): // 1) **永不调 show()/hide()**。macOS 上对子 webview `hide()` 之后再 `show()`, // 两个调用都返回 Ok、网页却永久不再绘制(v3.25.24 用户实测:一动画布就白)。 // 需要隐藏时用 set_bounds 把视图停到窗口外(CWV_PARK)——NSView 在父视图外 // 既不绘制也不收事件,效果等价且可以移回来。 // 2) 位置与尺寸**用一次 set_bounds 推**(一条消息),不要 set_size + set_position // 两条消息:两条消息之间视图会短暂处于「新尺寸 + 旧位置」的中间态。 // 3) 尺寸只在渲染层判定「静止」时推;位置可以随时跟。实测连续 60 帧改尺寸、 // 1×1 极值、连续移动都不会白(最小工程逐帧截图验证),但静止推送能把 WebKit // 的重排次数压到最少,拖动/缩放过程更稳。 // // `add_child` 与 `Manager::get_window` 都需要 tauri 的 `unstable` feature(见 Cargo.toml)。 // 子 webview 不在 capabilities 里 ⇒ 被它加载的外部页面拿不到宿主 IPC。 const CWV_PREFIX: &str = "cwv-"; const CWV_PARK: f64 = -20000.0; // 热路径采样计数器:bounds 每秒可能推几十次,不能每次都写盘。 static CWV_BOUNDS_CALLS: AtomicU64 = AtomicU64::new(0); // 圆角设置次数(只用于日志节流) static CWV_ROUND_CALLS: AtomicU64 = AtomicU64::new(0); // 画布网页的运行时诊断日志(_cwv.log,落在 app_config_dir)。 // 子 webview 建不起来时,渲染层只拿到一个 Err 字符串,落盘日志能还原「哪一步断的」。 fn cwv_log(app: &AppHandle, msg: &str) { let Ok(dir) = app.path().app_config_dir() else { return }; let p = dir.join("_cwv.log"); // 超过 256KB 只留尾部 32KB:长跑时不能无上限增长 if let Ok(meta) = std::fs::metadata(&p) { if meta.len() > 256 * 1024 { if let Ok(bytes) = std::fs::read(&p) { let keep = bytes.len().saturating_sub(32 * 1024); let _ = std::fs::write(&p, &bytes[keep..]); } } } let ts = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_millis()) .unwrap_or(0); use std::io::Write; if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&p) { let _ = f.write_all(format!("[{}] {}\n", ts, msg).as_bytes()); } } // 节点 id → 子 webview label。只保留安全字符:label 会进系统标识符,不能被节点 id 里的 // 任意字符污染(旧存档里可能有空格/中文)。 fn cwv_label(id: &str) -> String { let cleaned: String = id .chars() .filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_') .take(40) .collect(); format!("{}{}", CWV_PREFIX, if cleaned.is_empty() { "x".into() } else { cleaned }) } fn cwv_parse(url: &str) -> Result { let raw = url.trim(); if raw.is_empty() { return Err("没有网址".into()); } let with_scheme = if raw.contains("://") { raw.to_string() } else { format!("https://{}", raw) }; let parsed = url::Url::parse(&with_scheme).map_err(|_| "网址格式不合法".to_string())?; if parsed.scheme() != "http" && parsed.scheme() != "https" { return Err("只允许 http/https".into()); } Ok(parsed) } // 新窗口请求(target="_blank" / window.open)在原生 webview 里默认被静默丢弃: // wry 的 macOS delegate 没拿到 handler 时直接返回 None,所以用户看到的是「点了没反应」。 // 统一策略:只放行 http/https,并拒绝弹窗,由调用方把 URL 导航到当前页面。 fn new_window_url(url: url::Url) -> Option { if matches!(url.scheme(), "http" | "https") { Some(url) } else { None } } // 位置 + 尺寸打包成一次 set_bounds 的入参。 // // ox/oy 是「原生层坐标原点到 DOM 坐标原点」的差值(见 canvas_webview_metrics 的注释)。 // 渲染层量到的是内容视图坐标,而 add_child/set_bounds 用的是**窗口边框**坐标, // 两者相差一个标题栏高度 —— 不补这一下,网页会整体上浮盖住地址栏。 fn cwv_rect(x: f64, y: f64, w: f64, h: f64, ox: f64, oy: f64) -> tauri::Rect { tauri::Rect { position: tauri::Position::Logical(tauri::LogicalPosition::new(x + ox, y + oy)), // 下限 2px:wry/WebKit 对 0 尺寸视图的处理不稳定,1px 也没有任何显示价值 size: tauri::Size::Logical(tauri::LogicalSize::new(w.max(2.0), h.max(2.0))), } } // ── 圆角(2026-11-19 用户要求)────────────────────────────────────────────── // 原生子 webview 本身是矩形,盖在节点卡片上时四角会从卡片的圆角(--iwb-node-radius, // 默认 14px)里「顶」出来——看起来像网页没有跟着节点外形走。 // 做法:直接给 WKWebView 的 backing layer 设 cornerRadius + masksToBounds。 // WebKit 把渲染内容放在它的 sublayer 里,父 layer 的 masksToBounds 会把四角裁掉。 // 半径按画布缩放同比缩放(zoom 即「画布缩放 × 节点自身缩放」),否则缩到 25% 时 // 14px 圆角相对节点会显得巨大、缩放到 300% 又几乎看不见。 // // 2026-11-19 二次:半径不再写死,由渲染层把「外观设置 → 节点圆角」的当前值 // (CSS 变量 --iwb-node-radius,6~20px)随 bounds 一起送进来,用户改设置即时生效; // 传 null 时才退回默认 14。 const CWV_RADIUS: f64 = 14.0; #[cfg(target_os = "macos")] fn cwv_round(app: &AppHandle, wv: &tauri::webview::Webview, zoom: f64, base: Option) { let base = match base { Some(b) if b.is_finite() && b > 0.0 => b.clamp(2.0, 40.0), _ => CWV_RADIUS, }; // 上限 60:圆角设置 20px × 300% 缩放;下限 0.5:缩到 20% 时不至于变成直角。 let r = (base * zoom).clamp(0.5, 60.0); let app2 = app.clone(); // 失败不致命(视图可能正在销毁):忽略即可,不要中断 bounds 推送 let _ = wv.with_webview(move |p| { let view = p.inner(); if view.is_null() { return; } unsafe { use objc2::msg_send; use objc2::runtime::{AnyObject, Bool}; let v = view as *mut AnyObject; // 子 webview 通常已经是 layer-backed,这一句幂等,只是为了拿到非空 layer let _: () = msg_send![v, setWantsLayer: Bool::YES]; let layer: *mut AnyObject = msg_send![v, layer]; if layer.is_null() { cwv_log(&app2, &format!("round:no-layer r={:.1}", r)); return; } let _: () = msg_send![layer, setCornerRadius: r]; let _: () = msg_send![layer, setMasksToBounds: Bool::YES]; // 只记前几次:确认「圆角到底有没有落到 layer 上」,避免日志刷屏 let n = CWV_ROUND_CALLS.fetch_add(1, Ordering::Relaxed); if n < 4 { cwv_log(&app2, &format!("round:ok n={} r={:.1}", n, r)); } } }); } #[cfg(not(target_os = "macos"))] fn cwv_round(_app: &AppHandle, _wv: &tauri::webview::Webview, _zoom: f64, _base: Option) {} // 窗口边框尺寸 vs 内容视图尺寸。 // // **为什么需要它(v3.25.29 实测)**:`add_child` / `set_bounds` 的 LogicalPosition // 以**窗口边框左上角**为原点,而 `getBoundingClientRect()` 以**内容视图左上角**为原点。 // macOS 标准标题栏下两者差 32pt,于是每个画布网页都整体上移 32px —— 正好把地址栏、 // 前进/后退/刷新按钮全部盖住(用户看到的就是「按钮被遮住了」)。 // 最小工程实测:窗口 frame=1000x760,DOM innerHeight=728,子视图 y 传 200 实际落在 168。 // // 这里只回报「窗口边框」尺寸,差值由渲染层用 window.innerHeight 算 —— 全屏时标题栏消失, // 差值自然回到 0,不需要额外分支。 #[tauri::command] async fn canvas_webview_metrics(app: AppHandle) -> Result { let win = app.get_window("main").ok_or_else(|| "主窗口不存在".to_string())?; let size = win.inner_size().map_err(|e| e.to_string())?; let scale = win.scale_factor().unwrap_or(1.0); Ok(serde_json::json!({ "frameW": size.width as f64 / scale, "frameH": size.height as f64 / scale, "scale": scale, })) } // 确保某节点对应的子 webview 存在。返回 true = 这次真的新建了。 #[tauri::command] async fn canvas_webview_ensure( app: AppHandle, id: String, url: String, x: f64, y: f64, w: f64, h: f64, ox: f64, oy: f64, zoom: Option, radius: Option, ) -> Result { let parsed = cwv_parse(&url)?; let label = cwv_label(&id); if let Some(wv) = app.get_webview(&label) { // 已存在:只校正 bounds(不 show/hide —— 见文件头约束 1) if let Err(e) = wv.set_bounds(cwv_rect(x, y, w, h, ox, oy)) { cwv_log(&app, &format!("ensure:bounds-err label={} err={}", label, e)); } if let Some(z) = zoom { let _ = wv.set_zoom(z); } // 圆角:视图可能刚被重建(画布切换/暂停恢复),每次 ensure 都补一次,幂等 cwv_round(&app, &wv, zoom.unwrap_or(1.0), radius); return Ok(false); } // 必须用 get_window 而不是 get_webview_window:后者要求 `is_webview_window()`, // 即该窗口下所有 webview 的 label 都等于窗口 label。一旦 add_child 建出 cwv-xxx, // 这个条件永久为假,get_webview_window("main") 从此永远返回 None(v3.25.26 实测)。 let Some(window) = app.get_window("main") else { cwv_log(&app, "ensure:fail 取不到 main 窗口的 Window 句柄"); return Err("主窗口不存在".into()); }; let app_for_new_window = app.clone(); let label_for_new_window = label.clone(); let built = window.add_child( tauri::webview::WebviewBuilder::new(&label, WebviewUrl::External(parsed.clone())) .on_page_load(|wv, payload| { use tauri::webview::PageLoadEvent; use tauri::Emitter; let kind = match payload.event() { PageLoadEvent::Started => "started", PageLoadEvent::Finished => "finished", }; let label = wv.label().to_string(); let id = label.strip_prefix(CWV_PREFIX).unwrap_or(&label).to_string(); // 子 webview 没有 IPC 权限,只能由它自己的 app_handle 往主窗口广播 let _ = wv.app_handle().emit( "cwv-page", serde_json::json!({ "id": id, "kind": kind, "url": payload.url().to_string() }), ); }) .on_new_window(move |url, _features| { // 左侧栏面板 / 画布网页节点共用这个 builder:画板详情等新开标签链接 // 统一在当前 webview 原地打开,地址栏由 cwv-page 事件自动回填。 if let Some(url) = new_window_url(url) { if let Some(wv) = app_for_new_window.get_webview(&label_for_new_window) { if let Err(e) = wv.navigate(url) { cwv_log( &app_for_new_window, &format!( "new-window:navigate-err label={} err={}", label_for_new_window, e ), ); } } } NewWindowResponse::Deny }), tauri::LogicalPosition::new(x + ox, y + oy), tauri::LogicalSize::new(w.max(2.0), h.max(2.0)), ); match built { Ok(wv) => { // add_child 传入的 bounds 在部分 macOS 版本上不立刻生效,用 set_bounds 再摆一次 if let Err(e) = wv.set_bounds(cwv_rect(x, y, w, h, ox, oy)) { cwv_log(&app, &format!("ensure:post-bounds-err label={} err={}", label, e)); } // 缩放:页面 CSS 像素按 zoom 放大/缩小,配合「矩形随画布缩放」就能让网页 // 像图片一样跟着画布一起缩放,而不是一直按原宽度重排。 if let Some(z) = zoom { if let Err(e) = wv.set_zoom(z) { cwv_log(&app, &format!("ensure:zoom-err label={} zoom={} err={}", label, z, e)); } } // 新建后立刻上一次圆角(zoom 缺省按 1 倍)。放 here 而不是等首帧 bounds: // 首帧前视图已经贴到卡片上,直角会闪一下;先设好就不会看到方角。 cwv_round(&app, &wv, zoom.unwrap_or(1.0), radius); cwv_log( &app, &format!( "ensure:ok label={} url={} rect=({:.0},{:.0} {:.0}x{:.0}) off=({:.0},{:.0}) zoom={:?}", label, parsed, x, y, w, h, ox, oy, zoom ), ); Ok(true) } Err(e) => { cwv_log(&app, &format!("ensure:err label={} err={}", label, e)); Err(e.to_string()) } } } // 渲染层推送位置/尺寸/可见性。 // 返回 false = Rust 侧没有这个 webview(被 close / 进程重启),前端应回滚并重建。 #[tauri::command] async fn canvas_webview_bounds( app: AppHandle, id: String, x: f64, y: f64, w: f64, h: f64, visible: bool, zoom: Option, ox: f64, oy: f64, radius: Option, ) -> Result { let label = cwv_label(&id); let Some(wv) = app.get_webview(&label) else { return Ok(false); }; // 隐藏 = 停到窗口外,尺寸保持不变(别裁到 1px:那会触发 WebKit 重排) let rect = if visible { cwv_rect(x, y, w, h, ox, oy) } else { cwv_rect(CWV_PARK, CWV_PARK, w, h, 0.0, 0.0) }; if let Err(e) = wv.set_bounds(rect) { cwv_log(&app, &format!("bounds:err label={} err={}", label, e)); return Err(e.to_string()); } // 页面缩放:只在渲染层判定「该改了」时才带过来,避免每条消息都重排一次 if let Some(z) = zoom { if let Err(e) = wv.set_zoom(z) { cwv_log(&app, &format!("bounds:zoom-err label={} zoom={} err={}", label, z, e)); } } // 圆角:缩放变了(半径要同比缩放)或用户改了「外观设置 → 节点圆角」时重设。 // 两个条件都由渲染层判定,正常拖动时这里是 None,不会每帧跨线程投递。 if zoom.is_some() || radius.is_some() { cwv_round(&app, &wv, zoom.unwrap_or(1.0), radius); } let n = CWV_BOUNDS_CALLS.fetch_add(1, Ordering::Relaxed); if n < 8 || n % 400 == 0 { cwv_log( &app, &format!( "bounds label={} n={} rect=({:.0},{:.0} {:.0}x{:.0}) visible={} zoom={:?} off=({:.0},{:.0})", label, n, x, y, w, h, visible, zoom, ox, oy ), ); } Ok(true) } #[tauri::command] async fn canvas_webview_navigate(app: AppHandle, id: String, url: String) -> Result { let parsed = cwv_parse(&url)?; let label = cwv_label(&id); let Some(wv) = app.get_webview(&label) else { return Err("该节点还没有浏览器".into()); }; cwv_log(&app, &format!("navigate label={} url={}", label, parsed)); wv.navigate(parsed).map_err(|e| e.to_string())?; Ok(true) } #[tauri::command] async fn canvas_webview_action(app: AppHandle, id: String, action: String) -> Result { let label = cwv_label(&id); let Some(wv) = app.get_webview(&label) else { return Err("该节点还没有浏览器".into()); }; // 用 eval 而不是注入脚本到页面:这些是宿主发起的历史操作,外部页面无需配合 match action.as_str() { "back" => wv.eval("history.back()").map_err(|e| e.to_string())?, "forward" => wv.eval("history.forward()").map_err(|e| e.to_string())?, "reload" => wv.eval("location.reload()").map_err(|e| e.to_string())?, // 加载中把 ⟳ 变成「停止」:只中断当前请求,不销毁视图(销毁会丢滚动位置) "stop" => wv.eval("window.stop()").map_err(|e| e.to_string())?, "close" => { let _ = wv.close(); } other => return Err(format!("未知操作:{}", other)), } Ok(true) } #[tauri::command] fn canvas_webview_state(app: AppHandle, id: String) -> Result { match app.get_webview(&cwv_label(&id)) { Some(wv) => Ok(serde_json::json!({ "open": true, "url": wv.url().map(|u| u.to_string()).unwrap_or_default() })), None => Ok(serde_json::json!({ "open": false, "url": "" })), } } // 退出 / 切工作区时回收所有子 webview(label 前缀 cwv-)。 #[tauri::command] async fn canvas_webview_close_all(app: AppHandle) -> Result { let labels: Vec = app .webviews() .keys() .filter(|k| k.starts_with(CWV_PREFIX)) .cloned() .collect(); let mut n = 0u32; for label in labels { if let Some(wv) = app.get_webview(&label) { if wv.close().is_ok() { n += 1; } } } if n > 0 { cwv_log(&app, &format!("close_all closed={}", n)); } Ok(n) } #[tauri::command] fn notify_desktop(app: tauri::AppHandle, title: String, body: String) -> Result { use tauri_plugin_notification::NotificationExt; match app.notification().builder().title(title).body(body).show() { Ok(_) => Ok(true), Err(e) => Err(e.to_string()), } } #[cfg_attr(mobile, tauri::mobile_entry_point)] pub fn run() { let app = tauri::Builder::default() .plugin(tauri_plugin_single_instance::init(|app, _argv, _cwd| { // 第二次启动:聚焦已有窗口(多实例同时写同一个资料目录会把 data.json 写坏) if let Some(w) = app.get_window("main") { let _ = w.show(); let _ = w.unminimize(); let _ = w.set_focus(); } })) .plugin(tauri_plugin_notification::init()) .plugin(tauri_plugin_http::init()) .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, open_data_subpath, grant_paths, grant_dir, copy_tree, check_update, install_update, clipboard_read_image, clipboard_write_image, clipboard_write_text, clipboard_read_text, open_external_url, open_browser_window, browser_control, browser_state, canvas_webview_ensure, canvas_webview_bounds, canvas_webview_navigate, canvas_webview_action, canvas_webview_state, canvas_webview_close_all, canvas_webview_metrics, browser_bookmarks_menu, notify_desktop, app_memory_mb]) .setup(|app| { if cfg!(debug_assertions) { app.handle().plugin( tauri_plugin_log::Builder::default() .level(log::LevelFilter::Info) .build(), )?; } // 重启后恢复用户选择过的外部图片路径(相册 {__file} 依赖;fs scope 不持久) restore_file_grants(app.handle()); // 恢复上次窗口大小/位置(主窗口下限与 tauri.conf 的 minWidth/minHeight 对齐) restore_geom(app.handle(), "main", 1024, 640); 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(()) }) // 原生收藏夹菜单:菜单项点击统一从这里回给前端插件。 // ID 形如 bm-open:<序号>: / bm-add::;序号只为避免同 URL 重复 ID。 .on_menu_event(|app, e| { let id = e.id().as_ref(); let emit = |kind: &str, url: String| { let _ = app.emit(kind, serde_json::json!({ "url": url })); }; if let Some(rest) = id.strip_prefix("bm-open:") { if let Some((_n, enc)) = rest.split_once(':') { if let Ok(bytes) = b64_decode(enc) { emit("iwb-bookmark-open", String::from_utf8_lossy(&bytes).to_string()); } } } else if let Some(rest) = id.strip_prefix("bm-add:") { if let Some((g, enc)) = rest.split_once(':') { if let (Ok(gb), Ok(bytes)) = (b64_decode(g), b64_decode(enc)) { let url = String::from_utf8_lossy(&bytes).to_string(); let group = String::from_utf8_lossy(&gb).to_string(); let _ = app.emit("iwb-bookmark-add", serde_json::json!({ "url": url, "groupId": group })); } } } }) // 点关闭按钮 ⇒ 记住窗口尺寸后收进托盘(不退出,后台任务继续) .on_window_event(|window, event| { if let WindowEvent::CloseRequested { api, .. } = event { let label = window.label(); // 主窗口之外(browser 等)正常关闭:先记几何,再放行销毁。 // 这一步不能省 —— 否则外部网页会「点 ✕ 只是隐藏」,在后台继续跑, // 用户再也关不掉,只能 Cmd+Q 退整个应用。 if label != "main" { save_geom(window.app_handle(), label); return; } save_geom(window.app_handle(), "main"); if !QUITTING.load(Ordering::SeqCst) { api.prevent_close(); let _ = window.hide(); } } }) .build(tauri::generate_context!()) .expect("error while building tauri application"); app.run(|app_handle, event| { // Cmd+Q / 系统退出时也把当前窗口尺寸落盘 if let tauri::RunEvent::ExitRequested { .. } = event { save_geom(app_handle, "main"); } }); } /* ── 剪贴板读图的真实链路测试(只在 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!("没读到任何图片:文件分支没生效"), } } }