Files
image-workbench-desktop/src-tauri/src/lib.rs
T
2026-11-18 13:09:42 +08:00

422 lines
16 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, WebviewWindow, 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) -> Option<std::path::PathBuf> {
app.path()
.app_config_dir()
.ok()
.map(|d| d.join("window-geom.json"))
}
// 只在窗口处于普通状态时记录:最大化/全屏时的尺寸不是用户想恢复的那个尺寸
fn save_geom(win: &WebviewWindow) {
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 };
let app = win.app_handle();
if let Some(p) = geom_file(app) {
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(win: &WebviewWindow, app: &AppHandle) {
let Some(p) = geom_file(app) else { return };
let Ok(txt) = std::fs::read_to_string(p) else { return };
let Ok(g) = serde_json::from_str::<WindowGeom>(&txt) else { return };
// 最小尺寸与 tauri.conf.json 的 minWidth/minHeight 对齐:否则会恢复出一个
// 比窗口下限还小的窗口(实测 1051x488 时画布渲染成空白)
let w = g.w.max(1024);
let h = g.h.max(640);
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)
}
#[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, notify_desktop])
.setup(|app| {
if cfg!(debug_assertions) {
app.handle().plugin(
tauri_plugin_log::Builder::default()
.level(log::LevelFilter::Info)
.build(),
)?;
}
// 恢复上次窗口大小/位置
if let Some(win) = app.get_webview_window("main") {
restore_geom(&win, app.handle());
}
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 {
if !QUITTING.load(Ordering::SeqCst) {
if let Some(w) = window.app_handle().get_webview_window("main") {
save_geom(&w);
}
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 {
if let Some(w) = app_handle.get_webview_window("main") {
save_geom(&w);
}
}
});
}