Files
image-workbench-desktop/src-tauri/src/lib.rs
T

970 lines
40 KiB
Rust
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.
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use tauri::menu::{Menu, MenuItem};
use tauri::tray::TrayIconBuilder;
use tauri::{AppHandle, 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<std::path::PathBuf> {
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::<WindowGeom>(&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::<u64>() {
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::<PROCESS_MEMORY_COUNTERS>() 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
}
}
#[tauri::command]
fn grant_dir(app: AppHandle, dir: String, record: Option<bool>) -> Result<String, String> {
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<u64, String> {
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<String, String> {
// 只允许打开「资料目录」下的子路径: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<String, String> {
// 资料目录(用户选的那个)优先;没设置过才退回应用私有目录
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<bool, String> {
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<String, String> {
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<Option<serde_json::Value>, 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<bool, String> {
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) };
update
.download_and_install(|_chunk, _total| {}, || {})
.await
.map_err(|e| e.to_string())?;
app.restart();
}
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<Vec<u8>, 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,
}
/// 读系统剪贴板图片 → PNG(base64)
///
/// 为什么返回 PNG 而不是裸 RGBA:12MP 照片的 RGBA 是 46MB,base64 后 62MB,
/// 穿过 IPC 会卡住前端好几秒;PNG 通常只有几 MB。
#[tauri::command]
fn clipboard_read_image() -> Result<Option<ClipImagePayload>, 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<u8> = 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),
}))
}
/// 把 PNG(base64)写进系统剪贴板
#[tauri::command]
fn clipboard_write_image(png_base64: String) -> Result<bool, String> {
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<bool, String> {
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<bool, String> {
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);
}
WebviewWindowBuilder::new(&app, label, WebviewUrl::External(parsed))
.title(&title)
.inner_size(1200.0, 820.0)
.min_inner_size(800.0, 600.0)
.center()
.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<bool, String> {
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<serde_json::Value, String> {
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<url::Url, String> {
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)
}
// 位置 + 尺寸打包成一次 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<tauri::Wry>, zoom: f64, base: Option<f64>) {
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<tauri::Wry>, _zoom: f64, _base: Option<f64>) {}
// 窗口边框尺寸 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<serde_json::Value, String> {
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<f64>,
radius: Option<f64>,
) -> Result<bool, String> {
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 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() }),
);
}),
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<f64>,
ox: f64,
oy: f64,
radius: Option<f64>,
) -> Result<bool, String> {
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<bool, String> {
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<bool, String> {
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<serde_json::Value, String> {
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<u32, String> {
let labels: Vec<String> = 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<bool, String> {
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_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, notify_desktop,
app_memory_mb])
.setup(|app| {
if cfg!(debug_assertions) {
app.handle().plugin(
tauri_plugin_log::Builder::default()
.level(log::LevelFilter::Info)
.build(),
)?;
}
// 恢复上次窗口大小/位置(主窗口下限与 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(())
})
// 点关闭按钮 ⇒ 记住窗口尺寸后收进托盘(不退出,后台任务继续)
.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");
}
});
}