refactor: unify and simplify the call of app_handle

This commit is contained in:
huzibaca 2024-09-23 16:31:58 +08:00
parent 3d6faecaed
commit 1c894f3cfa
10 changed files with 135 additions and 158 deletions

View File

@ -14,8 +14,8 @@ type CmdResult<T = ()> = Result<T, String>;
use tauri::Manager;
#[tauri::command]
pub fn copy_clash_env(app_handle: tauri::AppHandle) -> CmdResult {
feat::copy_clash_env(&app_handle);
pub fn copy_clash_env() -> CmdResult {
feat::copy_clash_env();
Ok(())
}

View File

@ -8,7 +8,6 @@ use parking_lot::Mutex;
use serde_yaml::Mapping;
use std::{sync::Arc, time::Duration};
use sysinfo::{ProcessRefreshKind, RefreshKind, System};
use tauri::AppHandle;
use tauri_plugin_shell::process::{CommandChild, CommandEvent};
use tauri_plugin_shell::ShellExt;
@ -16,7 +15,6 @@ use tokio::time::sleep;
#[derive(Debug)]
pub struct CoreManager {
app_handle: Arc<Mutex<Option<AppHandle>>>,
sidecar: Arc<Mutex<Option<CommandChild>>>,
#[allow(unused)]
use_service_mode: Arc<Mutex<bool>>,
@ -27,14 +25,12 @@ impl CoreManager {
static CORE_MANAGER: OnceCell<CoreManager> = OnceCell::new();
CORE_MANAGER.get_or_init(|| CoreManager {
app_handle: Arc::new(Mutex::new(None)),
sidecar: Arc::new(Mutex::new(None)),
use_service_mode: Arc::new(Mutex::new(false)),
})
}
pub fn init(&self, app_handle: &AppHandle) -> Result<()> {
*self.app_handle.lock() = Some(app_handle.clone());
pub fn init(&self) -> Result<()> {
tauri::async_runtime::spawn(async {
log::trace!("run core start");
// 启动clash
@ -69,12 +65,8 @@ impl CoreManager {
let test_dir = dirs::app_home_dir()?.join("test");
let test_dir = dirs::path_to_str(&test_dir)?;
let app_handle_option = {
let lock = self.app_handle.lock();
lock.as_ref().cloned()
};
let app_handle = handle::Handle::global().app_handle().unwrap();
if let Some(app_handle) = app_handle_option {
let output = app_handle
.shell()
.sidecar(clash_core)?
@ -92,7 +84,6 @@ impl CoreManager {
Logger::global().set_log(stdout.clone());
bail!("{error}");
}
}
Ok(())
}
@ -173,9 +164,8 @@ impl CoreManager {
let args = vec!["-d", app_dir, "-f", config_path];
let app_handle = self.app_handle.lock();
let app_handle = handle::Handle::global().app_handle().unwrap();
if let Some(app_handle) = app_handle.as_ref() {
let cmd = app_handle.shell().sidecar(clash_core)?;
let (mut rx, _) = cmd.args(args).spawn()?;
@ -205,7 +195,6 @@ impl CoreManager {
}
}
});
}
Ok(())
}

View File

@ -1,6 +1,6 @@
use super::tray::Tray;
use crate::log_err;
use anyhow::{bail, Result};
use anyhow::Result;
use once_cell::sync::OnceCell;
use parking_lot::Mutex;
use std::sync::Arc;
@ -24,10 +24,12 @@ impl Handle {
*self.app_handle.lock() = Some(app_handle.clone());
}
pub fn app_handle(&self) -> Option<AppHandle> {
self.app_handle.lock().clone()
}
pub fn get_window(&self) -> Option<WebviewWindow> {
self.app_handle
.lock()
.clone()
self.app_handle()
.as_ref()
.and_then(|a| a.get_webview_window("main"))
}
@ -59,11 +61,7 @@ impl Handle {
/// update the system tray state
pub fn update_systray_part() -> Result<()> {
let app_handle = Self::global().app_handle.lock().clone();
if app_handle.is_none() {
bail!("update_systray unhandled error");
}
Tray::update_part(app_handle.as_ref().unwrap())?;
Tray::update_part()?;
Ok(())
}
}

View File

@ -1,3 +1,4 @@
use crate::core::handle;
use crate::{config::Config, feat, log_err};
use anyhow::{bail, Result};
use once_cell::sync::OnceCell;
@ -7,7 +8,6 @@ use tauri::{AppHandle, Manager};
use tauri_plugin_global_shortcut::{Code, GlobalShortcutExt, ShortcutState};
pub struct Hotkey {
current: Arc<Mutex<Vec<String>>>, // 保存当前的热键设置
app_handle: Arc<Mutex<Option<AppHandle>>>,
}
impl Hotkey {
@ -16,12 +16,10 @@ impl Hotkey {
HOTKEY.get_or_init(|| Hotkey {
current: Arc::new(Mutex::new(Vec::new())),
app_handle: Arc::new(Mutex::new(None)),
})
}
pub fn init(&self, app_handle: &AppHandle) -> Result<()> {
*self.app_handle.lock() = Some(app_handle.clone());
pub fn init(&self) -> Result<()> {
let verge = Config::verge();
if let Some(hotkeys) = verge.latest().hotkeys.as_ref() {
@ -48,11 +46,8 @@ impl Hotkey {
}
pub fn register(&self, hotkey: &str, func: &str) -> Result<()> {
let app_handle = self.app_handle.lock();
if app_handle.is_none() {
bail!("failed to get the hotkey manager");
}
let manager = app_handle.as_ref().unwrap().global_shortcut();
let app_handle: AppHandle = handle::Handle::global().app_handle().unwrap();
let manager = app_handle.global_shortcut();
if manager.is_registered(hotkey) {
manager.unregister(hotkey)?;
@ -88,11 +83,8 @@ impl Hotkey {
}
pub fn unregister(&self, hotkey: &str) -> Result<()> {
let app_handle = self.app_handle.lock();
if app_handle.is_none() {
bail!("failed to get the hotkey manager");
}
let manager = app_handle.as_ref().unwrap().global_shortcut();
let app_handle: AppHandle = handle::Handle::global().app_handle().unwrap();
let manager = app_handle.global_shortcut();
manager.unregister(hotkey)?;
log::info!(target: "app", "unregister hotkey {hotkey}");
@ -166,10 +158,9 @@ impl Hotkey {
impl Drop for Hotkey {
fn drop(&mut self) {
if let Some(app_handle) = self.app_handle.lock().as_ref() {
let app_handle: AppHandle = 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

@ -17,14 +17,17 @@ use tauri::{
Wry,
};
use tauri::{AppHandle, Manager};
use super::handle;
pub struct Tray {}
impl Tray {
pub fn create_systray(app_handle: &AppHandle) -> Result<()> {
pub fn create_systray() -> Result<()> {
let app_handle: AppHandle = handle::Handle::global().app_handle().unwrap();
let tray_incon_id = TrayIconId::new("main");
let tray = app_handle.tray_by_id(&tray_incon_id).unwrap();
tray.on_tray_icon_event(|tray, event| {
tray.on_tray_icon_event(|_, event| {
let tray_event = { Config::verge().latest().tray_event.clone() };
let tray_event: String = tray_event.unwrap_or("main_window".into());
@ -35,11 +38,10 @@ impl Tray {
..
} = event
{
let app = tray.app_handle();
match tray_event.as_str() {
"system_proxy" => feat::toggle_system_proxy(),
"tun_mode" => feat::toggle_tun_mode(),
"main_window" => resolve::create_window(app),
"main_window" => resolve::create_window(),
_ => {}
}
}
@ -67,7 +69,8 @@ impl Tray {
Ok(())
}
pub fn update_part(app_handle: &AppHandle) -> Result<()> {
pub fn update_part() -> Result<()> {
let app_handle: AppHandle = handle::Handle::global().app_handle().unwrap();
let use_zh = { Config::verge().latest().language == Some("zh".into()) };
let version = VERSION.get().unwrap();
let mode = {
@ -91,7 +94,7 @@ impl Tray {
let tray = app_handle.tray_by_id("main").unwrap();
let _ = tray.set_menu(Some(create_tray_menu(
app_handle,
&app_handle,
Some(mode.as_str()),
*system_proxy,
*tun_mode,
@ -421,10 +424,10 @@ fn on_menu_event(app_handle: &AppHandle, event: MenuEvent) {
println!("change mode to: {}", mode);
feat::change_clash_mode(mode.into());
}
"open_window" => resolve::create_window(app_handle),
"open_window" => resolve::create_window(),
"system_proxy" => feat::toggle_system_proxy(),
"tun_mode" => feat::toggle_tun_mode(),
"copy_env" => feat::copy_clash_env(app_handle),
"copy_env" => feat::copy_clash_env(),
"open_app_dir" => crate::log_err!(cmds::open_app_dir()),
"open_core_dir" => crate::log_err!(cmds::open_core_dir()),
"open_logs_dir" => crate::log_err!(cmds::open_logs_dir()),

View File

@ -10,22 +10,18 @@ use crate::log_err;
use crate::utils::resolve;
use anyhow::{bail, Result};
use serde_yaml::{Mapping, Value};
use tauri::{AppHandle, Manager};
use tauri::AppHandle;
use tauri_plugin_clipboard_manager::ClipboardExt;
// 打开面板
pub fn open_or_close_dashboard() {
let handle = handle::Handle::global();
let app_handle = handle.app_handle.lock().clone();
if let Some(app_handle) = app_handle.as_ref() {
if let Some(window) = app_handle.get_webview_window("main") {
if let Some(window) = handle::Handle::global().get_window() {
if let Ok(true) = window.is_focused() {
let _ = window.close();
return;
}
}
resolve::create_window(app_handle);
}
resolve::create_window();
}
// 重启clash
@ -104,15 +100,12 @@ pub fn toggle_tun_mode() {
}
pub fn quit() {
let handle = handle::Handle::global();
let app_handle = handle.app_handle.lock().clone();
if let Some(app_handle) = app_handle.as_ref() {
let _ = resolve::save_window_size_position(&app_handle, true);
let app_handle: AppHandle = handle::Handle::global().app_handle().unwrap();
let _ = resolve::save_window_size_position(true);
resolve::resolve_reset();
app_handle.exit(0);
std::process::exit(0);
}
}
/// 修改clash的订阅
pub async fn patch_clash(patch: Mapping) -> Result<()> {
@ -319,7 +312,8 @@ async fn update_core_config() -> Result<()> {
}
/// copy env variable
pub fn copy_clash_env(app_handle: &AppHandle) {
pub fn copy_clash_env() {
let app_handle = handle::Handle::global().app_handle().unwrap();
let port = { Config::verge().latest().verge_mixed_port.unwrap_or(7897) };
let http_proxy = format!("http://127.0.0.1:{}", port);
let socks5_proxy = format!("socks5://127.0.0.1:{}", port);

View File

@ -133,7 +133,7 @@ pub fn run() {
.build(tauri::generate_context!())
.expect("error while running tauri application");
app.run(|app_handle, e| match e {
app.run(|_, e| match e {
tauri::RunEvent::ExitRequested { api, .. } => {
api.prevent_exit();
}
@ -141,13 +141,13 @@ pub fn run() {
if label == "main" {
match event {
tauri::WindowEvent::Destroyed => {
let _ = resolve::save_window_size_position(app_handle, true);
let _ = resolve::save_window_size_position(true);
}
tauri::WindowEvent::CloseRequested { .. } => {
let _ = resolve::save_window_size_position(app_handle, true);
let _ = resolve::save_window_size_position(true);
}
tauri::WindowEvent::Moved(_) | tauri::WindowEvent::Resized(_) => {
let _ = resolve::save_window_size_position(app_handle, false);
let _ = resolve::save_window_size_position(false);
}
tauri::WindowEvent::Focused(true) => {
#[cfg(target_os = "macos")]

View File

@ -1,4 +1,5 @@
use crate::config::*;
use crate::core::handle;
use crate::utils::{dirs, help};
use anyhow::Result;
use chrono::{Local, TimeZone};
@ -297,7 +298,9 @@ pub fn init_scheme() -> Result<()> {
Ok(())
}
pub async fn startup_script(app_handle: &AppHandle) -> Result<()> {
pub async fn startup_script() -> Result<()> {
let app_handle: AppHandle = handle::Handle::global().app_handle().unwrap();
let script_path = {
let verge = Config::verge();
let verge = verge.latest();

View File

@ -44,7 +44,7 @@ pub async fn resolve_setup(app: &mut App) {
log_err!(init::init_config());
log_err!(init::init_resources());
log_err!(init::init_scheme());
log_err!(init::startup_script(app.app_handle()).await);
log_err!(init::startup_script().await);
// 处理随机端口
let enable_random_port = Config::verge().latest().enable_random_port.unwrap_or(false);
@ -78,25 +78,25 @@ pub async fn resolve_setup(app: &mut App) {
log_err!(Config::init_config().await);
log::trace!("launch core");
log_err!(CoreManager::global().init(app.app_handle()));
log_err!(CoreManager::global().init());
// setup a simple http server for singleton
log::trace!("launch embed server");
server::embed_server(app.app_handle());
server::embed_server();
log::trace!("init system tray");
log_err!(tray::Tray::create_systray(&app.app_handle()));
log_err!(tray::Tray::create_systray());
let silent_start = { Config::verge().data().enable_silent_start };
if !silent_start.unwrap_or(false) {
create_window(&app.app_handle());
create_window();
}
log_err!(sysopt::Sysopt::global().init_launch());
log_err!(sysopt::Sysopt::global().init_sysproxy());
log_err!(handle::Handle::update_systray_part());
log_err!(hotkey::Hotkey::global().init(app.app_handle()));
log_err!(hotkey::Hotkey::global().init());
log_err!(timer::Timer::global().init());
}
@ -110,8 +110,10 @@ pub fn resolve_reset() {
}
/// create main window
pub fn create_window(app_handle: &AppHandle) {
if let Some(window) = app_handle.get_webview_window("main") {
pub fn create_window() {
let app_handle: AppHandle = handle::Handle::global().app_handle().unwrap();
if let Some(window) = handle::Handle::global().get_window() {
trace_err!(window.unminimize(), "set win unminimize");
trace_err!(window.show(), "set win visible");
trace_err!(window.set_focus(), "set win focus");
@ -119,7 +121,7 @@ pub fn create_window(app_handle: &AppHandle) {
}
let mut builder = tauri::WebviewWindowBuilder::new(
app_handle,
&app_handle,
"main".to_string(),
tauri::WebviewUrl::App("index.html".into()),
)
@ -208,7 +210,8 @@ pub fn create_window(app_handle: &AppHandle) {
}
/// save window size and position
pub fn save_window_size_position(app_handle: &AppHandle, save_to_file: bool) -> Result<()> {
pub fn save_window_size_position(save_to_file: bool) -> Result<()> {
let app_handle: AppHandle = handle::Handle::global().app_handle().unwrap();
let verge = Config::verge();
let mut verge = verge.latest();
@ -236,6 +239,8 @@ pub fn save_window_size_position(app_handle: &AppHandle, save_to_file: bool) ->
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 param_str = if param.starts_with("[") && param.len() > 4 {
param
.get(2..param.len() - 2)
@ -269,10 +274,7 @@ pub async fn resolve_scheme(param: String) -> Result<()> {
.decode_utf8_lossy()
.to_string();
let handle = handle::Handle::global();
let app_handle = handle.app_handle.lock().clone();
if let Some(app_handle) = app_handle.as_ref() {
create_window(app_handle);
create_window();
match PrfItem::from_url(url.as_ref(), name, None, None).await {
Ok(item) => {
let uid = item.uid.clone().unwrap();
@ -300,7 +302,6 @@ pub async fn resolve_scheme(param: String) -> Result<()> {
}
}
}
}
None => bail!("failed to get profile url"),
}
}

View File

@ -6,7 +6,6 @@ use crate::log_err;
use anyhow::{bail, Result};
use port_scanner::local_port_available;
use std::convert::Infallible;
use tauri::AppHandle;
use warp::Filter;
#[derive(serde::Deserialize, Debug)]
@ -42,13 +41,12 @@ pub async fn check_singleton() -> Result<()> {
/// The embed server only be used to implement singleton process
/// maybe it can be used as pac server later
pub fn embed_server(app_handle: &AppHandle) {
pub fn embed_server() {
let port = IVerge::get_singleton_port();
let handle = app_handle.clone();
tauri::async_runtime::spawn(async move {
let visible = warp::path!("commands" / "visible").map(move || {
resolve::create_window(&handle);
resolve::create_window();
"ok"
});