Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: 手动实现了 window-state 插件 #677

Merged
merged 1 commit into from
Oct 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 11 additions & 16 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ members = [
[workspace.dependencies]
tauri = "2.0.2"
serde = "1.0"
serde_json = "1"
fs_extra = "1.3.0"
log = "0.4.22"
cocoa = "0.25.0"
Expand All @@ -20,4 +21,5 @@ tauri-plugin-eco-backup = { path = "./src-tauri/src/plugins/backup" }
tauri-plugin-eco-locale = { path = "./src-tauri/src/plugins/locale" }
tauri-plugin-eco-clipboard = { path = "./src-tauri/src/plugins/clipboard" }
tauri-plugin-eco-ocr = { path = "./src-tauri/src/plugins/ocr" }
tauri-plugin-eco-paste = { path = "./src-tauri/src/plugins/paste" }
tauri-plugin-eco-paste = { path = "./src-tauri/src/plugins/paste" }
tauri-plugin-eco-window-state = { path = "./src-tauri/src/plugins/window-state" }
4 changes: 2 additions & 2 deletions src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,12 @@ tauri-build = { version = "2.0.1", features = [] }
[dependencies]
tauri = { workspace = true, features = [ "tray-icon", "protocol-asset", "macos-private-api", "image-png" ] }
serde = { workspace = true, features = ["derive"] }
serde_json = "1"
serde_json.workspace = true
tauri-plugin-shell.workspace = true
tauri-plugin-single-instance = "2.0.1"
tauri-plugin-autostart = "2.0.1"
tauri-plugin-sql = { version = "2.0.1", features = ["sqlite"] }
tauri-plugin-log = "2.0.1"
tauri-plugin-window-state = "2.0.1"
tauri-plugin-global-shortcut = "2.0.1"
tauri-plugin-os = "2.0.1"
tauri-plugin-dialog = "2.0.1"
Expand All @@ -42,6 +41,7 @@ tauri-plugin-eco-locale.workspace = true
tauri-plugin-eco-clipboard.workspace = true
tauri-plugin-eco-ocr.workspace = true
tauri-plugin-eco-paste.workspace = true
tauri-plugin-eco-window-state.workspace = true

[target."cfg(target_os = \"macos\")".dependencies]
cocoa.workspace = true
1 change: 0 additions & 1 deletion src-tauri/capabilities/default.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@
"log:default",
"sql:default",
"sql:allow-execute",
"window-state:default",
"global-shortcut:allow-is-registered",
"global-shortcut:allow-register",
"global-shortcut:allow-unregister",
Expand Down
20 changes: 2 additions & 18 deletions src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use tauri::{generate_context, Builder, Manager, WindowEvent};
use tauri_plugin_autostart::MacosLauncher;
use tauri_plugin_eco_window::{show_main_window, MAIN_WINDOW_LABEL, PREFERENCE_WINDOW_LABEL};
use tauri_plugin_log::{Target, TargetKind};
// use tauri_plugin_window_state::{AppHandleExt, StateFlags};

pub const AUTO_LAUNCH_ARG: &str = "--auto-launch";

Expand Down Expand Up @@ -46,13 +45,6 @@ pub fn run() {
])
.build(),
)
// TODO: 窗口状态插件
// 记住窗口状态的插件:https://github.com/tauri-apps/plugins-workspace/tree/v2/plugins/window-state
// .plugin(
// tauri_plugin_window_state::Builder::default()
// .with_state_flags(StateFlags::all() & !StateFlags::VISIBLE)
// .build(),
// )
// 快捷键插件: https://github.com/tauri-apps/tauri-plugin-global-shortcut
.plugin(tauri_plugin_global_shortcut::Builder::new().build())
// 操作系统相关信息插件:https://github.com/tauri-apps/tauri-plugin-os
Expand Down Expand Up @@ -83,23 +75,15 @@ pub fn run() {
.plugin(tauri_plugin_eco_paste::init())
// 自定义 macos 权限查询的插件
.plugin(tauri_plugin_eco_macos_permissions::init())
// 自定义保存和恢复窗口状态的插件
.plugin(tauri_plugin_eco_window_state::init())
.on_window_event(|window, event| match event {
// 让 app 保持在后台运行:https://tauri.app/v1/guides/features/system-tray/#preventing-the-app-from-closing
WindowEvent::CloseRequested { api, .. } => {
window.hide().unwrap();

api.prevent_close();
}
// 窗口失焦保存窗口的状态信息
// WindowEvent::Focused(focused) => {
// if *focused {
// return;
// }

// let app_handle = window.app_handle();

// let _ = app_handle.save_window_state(StateFlags::all());
// }
_ => {}
})
.invoke_handler(tauri::generate_handler![])
Expand Down
4 changes: 2 additions & 2 deletions src-tauri/src/plugins/backup/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,12 +90,12 @@ pub async fn move_data(from: PathBuf, to: PathBuf) -> Result<PathBuf, String> {
let is_file = path.is_file();
let file_name = get_file_name(path.clone());

// 忽略窗口状态插件生成的的文件,无法修改存储路径
// 忽略窗口状态插件生成的的文件
if is_file && file_name.starts_with(".window-state") {
continue;
}

// 忽略日志插件生成的目录,无法修改存储路径
// 忽略日志插件生成的目录
if is_dir && file_name == "logs" {
continue;
}
Expand Down
16 changes: 16 additions & 0 deletions src-tauri/src/plugins/window-state/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
[package]
name = "tauri-plugin-eco-window-state"
version = "0.1.0"
authors = []
description = ""
edition = "2021"
rust-version = "1.77.2"
links = "tauri-plugin-eco-window-state"

[dependencies]
tauri.workspace = true
serde.workspace = true
serde_json.workspace = true

[build-dependencies]
tauri-plugin.workspace = true
5 changes: 5 additions & 0 deletions src-tauri/src/plugins/window-state/build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const COMMANDS: &[&str] = &["save_state", "restore_state"];

fn main() {
tauri_plugin::Builder::new(COMMANDS).build();
}
5 changes: 5 additions & 0 deletions src-tauri/src/plugins/window-state/permissions/default.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
"$schema" = "schemas/schema.json"

[default]
description = "Default permissions for the plugin"
permissions = ["allow-save-state", "allow-restore-state"]
60 changes: 60 additions & 0 deletions src-tauri/src/plugins/window-state/src/commands.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, fs::File, path::PathBuf};
use tauri::{command, AppHandle, Manager, PhysicalPosition, PhysicalSize, Runtime, Window};

#[derive(Debug, Serialize, Deserialize)]
pub struct WindowState {
width: u32,
height: u32,
x: i32,
y: i32,
}

// 保存窗口状态
#[command]
pub fn save_state<R: Runtime>(app_handle: AppHandle<R>, save_path: PathBuf) {
let windows = app_handle.webview_windows();

let mut data: HashMap<String, WindowState> = HashMap::new();

for (label, window) in windows {
if let (Ok(size), Ok(position)) = (window.inner_size(), window.outer_position()) {
let window_state = WindowState {
width: size.width,
height: size.height,
x: position.x,
y: position.y,
};

data.insert(label, window_state);
}
}

let file = File::create(save_path).unwrap();
serde_json::to_writer_pretty(file, &data).unwrap();
}

// 恢复窗口状态
#[command]
pub fn restore_state<R: Runtime>(window: Window<R>, save_path: PathBuf) {
let exists = save_path.exists();

if !exists {
return;
}

let file = File::open(save_path).unwrap();
let data: HashMap<String, WindowState> = serde_json::from_reader(file).unwrap();

if let Some(window_state) = data.get(window.label()) {
let _ = window.set_size(PhysicalSize {
width: window_state.width,
height: window_state.height,
});

let _ = window.set_position(PhysicalPosition {
x: window_state.x,
y: window_state.y,
});
}
}
38 changes: 38 additions & 0 deletions src-tauri/src/plugins/window-state/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
use tauri::{
generate_handler,
plugin::{Builder, TauriPlugin},
Manager, Runtime, WindowEvent,
};

mod commands;

pub use commands::*;

pub fn init<R: Runtime>() -> TauriPlugin<R> {
Builder::new("eco-window-state")
.invoke_handler(generate_handler![
commands::save_state,
commands::restore_state
])
.on_window_ready(|window| {
let app_handle = window.app_handle().clone();

if let Ok(app_data_dir) = app_handle.path().app_data_dir() {
let save_path = app_data_dir.join(".window-state.json");

restore_state(window.clone(), save_path.clone());

window.on_window_event(move |e| match e {
WindowEvent::Focused(focused) => {
if *focused {
return;
}

save_state(app_handle.clone(), save_path.clone());
}
_ => {}
});
}
})
.build()
}
6 changes: 4 additions & 2 deletions src-tauri/tauri.conf.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@
"transparent": true,
"alwaysOnTop": true,
"acceptFirstMouse": true,
"skipTaskbar": true
"skipTaskbar": true,
"dragDropEnabled": false
},
{
"label": "preference",
Expand All @@ -46,7 +47,8 @@
"windowEffects": {
"effects": ["sidebar"],
"state": "active"
}
},
"dragDropEnabled": false
}
],
"security": {
Expand Down