refactor: unify and simplify the call of app_handle(2)

This commit is contained in:
huzibaca 2024-09-23 23:15:51 +08:00
parent 8a3a094414
commit a3465d292c
No known key found for this signature in database
GPG Key ID: D4364EE4851DC302
12 changed files with 39 additions and 62 deletions

View File

@ -3,8 +3,8 @@
"version": "2.0.0",
"license": "GPL-3.0-only",
"scripts": {
"dev": "tauri dev",
"dev:diff": "tauri dev -f verge-dev",
"dev": "RUST_BACKTRACE=1 tauri dev",
"dev:diff": "RUST_BACKTRACE=1 tauri dev -f verge-dev",
"build": "tauri build",
"tauri": "tauri",
"web:dev": "vite",

View File

@ -7,9 +7,6 @@ use serde::{Deserialize, Serialize};
/// ### `verge.yaml` schema
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct IVerge {
/// app listening port for app singleton
pub app_singleton_port: Option<u16>,
/// app log level
/// silent | error | warn | info | debug | trace
pub app_log_level: Option<String>,
@ -330,11 +327,7 @@ impl IVerge {
const SERVER_PORT: u16 = 33331;
#[cfg(feature = "verge-dev")]
const SERVER_PORT: u16 = 11233;
match dirs::verge_path().and_then(|path| help::read_yaml::<IVerge>(&path)) {
Ok(config) => config.app_singleton_port.unwrap_or(SERVER_PORT),
Err(_) => SERVER_PORT, // 这里就不log错误了
}
SERVER_PORT
}
/// 获取日志等级

View File

@ -138,9 +138,5 @@ fn test_parse_check_output() {
let res2 = parse_check_output(str2.into());
let res3 = parse_check_output(str3.into());
println!("res1: {res1}");
println!("res2: {res2}");
println!("res3: {res3}");
assert_eq!(res1, res3);
}

View File

@ -2,13 +2,13 @@ use super::tray::Tray;
use crate::log_err;
use anyhow::Result;
use once_cell::sync::OnceCell;
use parking_lot::Mutex;
use parking_lot::RwLock;
use std::sync::Arc;
use tauri::{AppHandle, Emitter, Manager, WebviewWindow};
#[derive(Debug, Default, Clone)]
pub struct Handle {
pub app_handle: Arc<Mutex<Option<AppHandle>>>,
pub app_handle: Arc<RwLock<Option<AppHandle>>>,
}
impl Handle {
@ -16,16 +16,17 @@ impl Handle {
static HANDLE: OnceCell<Handle> = OnceCell::new();
HANDLE.get_or_init(|| Handle {
app_handle: Arc::new(Mutex::new(None)),
app_handle: Arc::new(RwLock::new(None)),
})
}
pub fn init(&self, app_handle: &AppHandle) {
*self.app_handle.lock() = Some(app_handle.clone());
let mut handle = self.app_handle.write();
*handle = Some(app_handle.clone());
}
pub fn app_handle(&self) -> Option<AppHandle> {
self.app_handle.lock().clone()
self.app_handle.read().clone()
}
pub fn get_window(&self) -> Option<WebviewWindow> {

View File

@ -4,7 +4,7 @@ use anyhow::{bail, Result};
use once_cell::sync::OnceCell;
use parking_lot::Mutex;
use std::{collections::HashMap, sync::Arc};
use tauri::{AppHandle, Manager};
use tauri::Manager;
use tauri_plugin_global_shortcut::{Code, GlobalShortcutExt, ShortcutState};
pub struct Hotkey {
current: Arc<Mutex<Vec<String>>>, // 保存当前的热键设置
@ -46,7 +46,7 @@ impl Hotkey {
}
pub fn register(&self, hotkey: &str, func: &str) -> Result<()> {
let app_handle: AppHandle = handle::Handle::global().app_handle().unwrap();
let app_handle = handle::Handle::global().app_handle().unwrap();
let manager = app_handle.global_shortcut();
if manager.is_registered(hotkey) {
@ -83,7 +83,7 @@ impl Hotkey {
}
pub fn unregister(&self, hotkey: &str) -> Result<()> {
let app_handle: AppHandle = handle::Handle::global().app_handle().unwrap();
let app_handle = handle::Handle::global().app_handle().unwrap();
let manager = app_handle.global_shortcut();
manager.unregister(hotkey)?;
@ -158,7 +158,7 @@ impl Hotkey {
impl Drop for Hotkey {
fn drop(&mut self) {
let app_handle: AppHandle = handle::Handle::global().app_handle().unwrap();
let app_handle = handle::Handle::global().app_handle().unwrap();
if let Err(e) = app_handle.global_shortcut().unregister_all() {
log::error!("Error unregistering all hotkeys: {:?}", e);
}

View File

@ -23,7 +23,7 @@ pub struct Tray {}
impl Tray {
pub fn create_systray() -> Result<()> {
let app_handle: AppHandle = handle::Handle::global().app_handle().unwrap();
let app_handle = handle::Handle::global().app_handle().unwrap();
let tray_incon_id = TrayIconId::new("main");
let tray = app_handle.tray_by_id(&tray_incon_id).unwrap();
@ -66,7 +66,7 @@ impl Tray {
}
pub fn update_part() -> Result<()> {
let app_handle: AppHandle = handle::Handle::global().app_handle().unwrap();
let app_handle = handle::Handle::global().app_handle().unwrap();
let use_zh = { Config::verge().latest().language == Some("zh".into()) };
let version = VERSION.get().unwrap();
let mode = {

View File

@ -56,7 +56,5 @@ fn test_merge() -> anyhow::Result<()> {
let result = serde_yaml::to_string(&use_merge(merge, config))?;
println!("{result}");
Ok(())
}

View File

@ -105,7 +105,5 @@ fn test_script() {
let config_str = serde_yaml::to_string(&config).unwrap();
println!("{config_str}");
dbg!(results);
}

View File

@ -10,7 +10,6 @@ use crate::log_err;
use crate::utils::resolve;
use anyhow::{bail, Result};
use serde_yaml::{Mapping, Value};
use tauri::AppHandle;
use tauri_plugin_clipboard_manager::ClipboardExt;
// 打开面板
@ -100,7 +99,7 @@ pub fn toggle_tun_mode() {
}
pub fn quit() {
let app_handle: AppHandle = handle::Handle::global().app_handle().unwrap();
let app_handle = handle::Handle::global().app_handle().unwrap();
let _ = resolve::save_window_size_position(true);
resolve::resolve_reset();
app_handle.exit(0);

View File

@ -44,39 +44,31 @@ pub fn app_home_dir() -> Result<PathBuf> {
.ok_or(anyhow::anyhow!("failed to get the portable app dir"))?;
return Ok(PathBuf::from(app_dir).join(".config").join(APP_ID));
}
let handle = handle::Handle::global();
let app_handle = handle.app_handle.lock().clone();
let app_handle = handle::Handle::global().app_handle().unwrap();
if let Some(app_handle) = app_handle.as_ref() {
match app_handle.path().data_dir() {
Ok(dir) => {
return Ok(dir.join(APP_ID));
}
Err(e) => {
log::error!("Failed to get the app home directory: {}", e);
return Err(anyhow::anyhow!("Failed to get the app homedirectory"));
}
match app_handle.path().data_dir() {
Ok(dir) => {
return Ok(dir.join(APP_ID));
}
Err(e) => {
log::error!("Failed to get the app home directory: {}", e);
return Err(anyhow::anyhow!("Failed to get the app homedirectory"));
}
}
Err(anyhow::anyhow!("failed to get the app home dir"))
}
/// get the resources dir
pub fn app_resources_dir() -> Result<PathBuf> {
let handle = handle::Handle::global();
let app_handle = handle.app_handle.lock().clone();
if let Some(app_handle) = app_handle.as_ref() {
match app_handle.path().resource_dir() {
Ok(dir) => {
return Ok(dir.join("resources"));
}
Err(e) => {
log::error!("Failed to get the resource directory: {}", e);
return Err(anyhow::anyhow!("Failed to get the resource directory"));
}
};
let app_handle = handle::Handle::global().app_handle().unwrap();
match app_handle.path().resource_dir() {
Ok(dir) => {
return Ok(dir.join("resources"));
}
Err(e) => {
log::error!("Failed to get the resource directory: {}", e);
return Err(anyhow::anyhow!("Failed to get the resource directory"));
}
};
Err(anyhow::anyhow!("failed to get the resource dir"))
}
/// profiles dir

View File

@ -11,7 +11,6 @@ use log4rs::encode::pattern::PatternEncoder;
use std::fs::{self, DirEntry};
use std::path::PathBuf;
use std::str::FromStr;
use tauri::AppHandle;
use tauri_plugin_shell::ShellExt;
/// initialize this instance's log file
@ -299,7 +298,7 @@ pub fn init_scheme() -> Result<()> {
}
pub async fn startup_script() -> Result<()> {
let app_handle: AppHandle = handle::Handle::global().app_handle().unwrap();
let app_handle = handle::Handle::global().app_handle().unwrap();
let script_path = {
let verge = Config::verge();

View File

@ -7,7 +7,7 @@ use once_cell::sync::OnceCell;
use percent_encoding::percent_decode_str;
use serde_yaml::Mapping;
use std::net::TcpListener;
use tauri::{App, AppHandle, Manager};
use tauri::{App, Manager};
use url::Url;
//#[cfg(not(target_os = "linux"))]
@ -39,6 +39,7 @@ pub async fn resolve_setup(app: &mut App) {
#[cfg(target_os = "macos")]
app.set_activation_policy(tauri::ActivationPolicy::Accessory);
let version = app.package_info().version.to_string();
handle::Handle::global().init(app.app_handle());
VERSION.get_or_init(|| version.clone());
log_err!(init::init_config());
@ -111,7 +112,7 @@ pub fn resolve_reset() {
/// create main window
pub fn create_window() {
let app_handle: AppHandle = handle::Handle::global().app_handle().unwrap();
let app_handle = handle::Handle::global().app_handle().unwrap();
if let Some(window) = handle::Handle::global().get_window() {
trace_err!(window.unminimize(), "set win unminimize");
@ -211,7 +212,7 @@ pub fn create_window() {
/// save window size and position
pub fn save_window_size_position(save_to_file: bool) -> Result<()> {
let app_handle: AppHandle = handle::Handle::global().app_handle().unwrap();
let app_handle = handle::Handle::global().app_handle().unwrap();
let verge = Config::verge();
let mut verge = verge.latest();
@ -239,7 +240,7 @@ pub fn save_window_size_position(save_to_file: bool) -> Result<()> {
pub async fn resolve_scheme(param: String) -> Result<()> {
log::info!("received deep link: {}", param);
let app_handle: AppHandle = handle::Handle::global().app_handle().unwrap();
let app_handle = handle::Handle::global().app_handle().unwrap();
let param_str = if param.starts_with("[") && param.len() > 4 {
param