254 lines
9.9 KiB
Rust
254 lines
9.9 KiB
Rust
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 };
|
||
if g.w < 800 || g.h < 500 {
|
||
return;
|
||
}
|
||
let _ = win.set_size(PhysicalSize::new(g.w, g.h));
|
||
let cx = g.x + (g.w as i32) / 2;
|
||
let cy = g.y + (g.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)
|
||
}
|
||
|
||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||
pub fn run() {
|
||
let app = tauri::Builder::default()
|
||
.plugin(tauri_plugin_http::init())
|
||
.plugin(tauri_plugin_fs::init())
|
||
.plugin(tauri_plugin_dialog::init())
|
||
.invoke_handler(tauri::generate_handler![open_app_data_dir, grant_dir, copy_tree])
|
||
.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())?;
|
||
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);
|
||
}
|
||
}
|
||
});
|
||
}
|