Files
image-workbench-desktop/src-tauri/src/lib.rs
T
qiqi 05dd343155 feat(canvas-webview): 画布内嵌网页节点(原生子 webview)
- lib.rs:新增 canvas_webview_ensure/bounds/navigate/action/state/close_all,
  用 Window::add_child 建 label=cwv-<节点id> 的子 webview(tauri 启用 unstable feature)。
  子 webview 不在 capabilities ⇒ 外部页面拿不到宿主 IPC。
- 新增 src/canvas-webview.js:锚点扫描 + 每帧位置同步。自启动、对 app.js 零侵入
  (app.js 总行数棘轮只剩 1 行余量)。快速平移缩放拖拽时先隐藏避免拖影;
  节点必须完整落在画布内才显示(原生层不受 overflow:hidden 约束,溢出会盖住侧边栏);
  选中时内缩 12px 露出缩放手柄;锚点消失 900ms 后才回收(LOD 降级不重载页面)。
- 插件节点可声明初始宽度:nodes.register 的 width 经 addPluginNode 生效。
- browser 插件 1.1.0:新增「网页」节点(地址栏 + 后退/前进/刷新/关闭)。
- 同步模块顺序快照与架构文档计数(89 个模块)。
2026-11-18 23:29:17 +08:00

631 lines
26 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, 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_webview_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_webview_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_webview_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_webview_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());
}
});
// 菜单栏用单色模板图标(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);
}
}
}
builder.build(app)?;
Ok(())
}
// 把「资料目录」加进本次运行的 fs scope。
// 为什么需要它:tauri-plugin-fs 的路径白名单是**运行时**的,重启就没了;而资料目录是用户
// 在设置里选的、存在应用配置里 ⇒ 启动时由这里重新授权一次,之后 fs 插件的读写才允许。
#[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_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]
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]
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 明确拒绝被嵌,iframe 里只会白屏,且主窗口 CSP 也没有 frame-src。
// 子 webview 是真实浏览器实例,不受这些响应头约束。
//
// 代价(已知且不可消除):子 webview 是原生层,永远浮在 HTML 之上 —— 它无法被画布节点
// 遮挡,也无法被 CSS 裁剪。所以可见性由渲染层每帧算:节点离开画布可视区、被折叠、
// 或画布正在拖拽/缩放时主动 hide,避免它盖住菜单与侧边栏。
//
// `add_child` 需要 tauri 的 `unstable` feature(见 Cargo.toml)。
// 子 webview 不在 capabilities 里 ⇒ 被它加载的外部页面拿不到宿主 IPC。
const CWV_PREFIX: &str = "cwv-";
// label 只允许 [a-zA-Z0-9-_:/]:节点 id 本身是 uid() 生成的安全串,这里仍过一遍白名单兜底。
fn cwv_label(id: &str) -> String {
let cleaned: String = id
.chars()
.filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_')
.collect();
format!("{}{}", CWV_PREFIX, cleaned)
}
fn cwv_parse(url: &str) -> Result<url::Url, String> {
let parsed = url::Url::parse(url).map_err(|_| "网址格式不合法".to_string())?;
if parsed.scheme() != "http" && parsed.scheme() != "https" {
return Err("只允许 http/https".into());
}
Ok(parsed)
}
// 确保某节点对应的子 webview 存在。返回 true 表示这次真的新建了。
#[tauri::command]
fn canvas_webview_ensure(app: AppHandle, id: String, url: String, x: f64, y: f64, w: f64, h: f64) -> Result<bool, String> {
let parsed = cwv_parse(&url)?;
let label = cwv_label(&id);
if app.get_webview(&label).is_some() {
return Ok(false);
}
let main = app.get_webview_window("main").ok_or_else(|| "主窗口不存在".to_string())?;
// WebviewWindow → &Webview → Window(Window 才是 add_child 的宿主)
let window = AsRef::<tauri::Webview<_>>::as_ref(&main).window();
window
.add_child(
tauri::webview::WebviewBuilder::new(&label, WebviewUrl::External(parsed)),
tauri::LogicalPosition::new(x, y),
tauri::LogicalSize::new(w.max(1.0), h.max(1.0)),
)
.map_err(|e| e.to_string())?;
Ok(true)
}
// 热路径:渲染层每帧(rect 有变化时)调一次。位置/尺寸/可见性一把推过来。
#[tauri::command]
fn canvas_webview_bounds(app: AppHandle, id: String, x: f64, y: f64, w: f64, h: f64, visible: bool) -> Result<bool, String> {
let Some(wv) = app.get_webview(&cwv_label(&id)) else { return Ok(false) };
// 单参数失败不整体报错:节点可能正被拖到画布外,set_size(0) 之类会返回 Err,
// 但下一次调用就会恢复正常,没必要把前端的 rAF 打断。
let _ = wv.set_position(tauri::LogicalPosition::new(x, y));
let _ = wv.set_size(tauri::LogicalSize::new(w.max(1.0), h.max(1.0)));
if visible {
let _ = wv.show();
} else {
let _ = wv.hide();
}
Ok(true)
}
#[tauri::command]
fn canvas_webview_navigate(app: AppHandle, id: String, url: String) -> Result<bool, String> {
let parsed = cwv_parse(&url)?;
let wv = app.get_webview(&cwv_label(&id)).ok_or_else(|| "该节点还没有浏览器".to_string())?;
wv.navigate(parsed).map_err(|e| e.to_string())?;
Ok(true)
}
// back/forward 用固定字符串且不拼接外部输入,不构成注入面。
#[tauri::command]
fn canvas_webview_action(app: AppHandle, id: String, action: String) -> Result<bool, String> {
let wv = app.get_webview(&cwv_label(&id)).ok_or_else(|| "该节点还没有浏览器".to_string())?;
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.reload().map_err(|e| e.to_string())?,
// 关掉的是子 webview 本身,节点还在;节点下次可见时 ensure 会重建。
"close" => wv.close().map_err(|e| e.to_string())?,
_ => return Err("未知操作".into()),
}
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 不随 DOM 消失,
// 漏掉就会在窗口上留一块「无主网页」,而且它永远盖在最上面。
#[tauri::command]
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;
}
}
}
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_webview_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, 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, notify_desktop])
.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");
}
});
}