mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-01-29 08:45:41 +08:00
refactor: unify and simplify the call of app_handle
This commit is contained in:
@@ -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,29 +65,24 @@ 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)?
|
||||
.args(["-t", "-d", test_dir, "-f", config_path])
|
||||
.output()
|
||||
.await?;
|
||||
let output = app_handle
|
||||
.shell()
|
||||
.sidecar(clash_core)?
|
||||
.args(["-t", "-d", test_dir, "-f", config_path])
|
||||
.output()
|
||||
.await?;
|
||||
|
||||
if !output.status.success() {
|
||||
let stdout = String::from_utf8(output.stdout).unwrap_or_default();
|
||||
let error = clash_api::parse_check_output(stdout.clone());
|
||||
let error = match !error.is_empty() {
|
||||
true => error,
|
||||
false => stdout.clone(),
|
||||
};
|
||||
Logger::global().set_log(stdout.clone());
|
||||
bail!("{error}");
|
||||
}
|
||||
if !output.status.success() {
|
||||
let stdout = String::from_utf8(output.stdout).unwrap_or_default();
|
||||
let error = clash_api::parse_check_output(stdout.clone());
|
||||
let error = match !error.is_empty() {
|
||||
true => error,
|
||||
false => stdout.clone(),
|
||||
};
|
||||
Logger::global().set_log(stdout.clone());
|
||||
bail!("{error}");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -173,39 +164,37 @@ 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()?;
|
||||
let cmd = app_handle.shell().sidecar(clash_core)?;
|
||||
let (mut rx, _) = cmd.args(args).spawn()?;
|
||||
|
||||
tauri::async_runtime::spawn(async move {
|
||||
while let Some(event) = rx.recv().await {
|
||||
match event {
|
||||
CommandEvent::Stdout(line) => {
|
||||
let line = String::from_utf8(line).unwrap_or_default();
|
||||
log::info!(target: "app", "[mihomo]: {line}");
|
||||
Logger::global().set_log(line);
|
||||
}
|
||||
CommandEvent::Stderr(err) => {
|
||||
let err = String::from_utf8(err).unwrap_or_default();
|
||||
log::error!(target: "app", "[mihomo]: {err}");
|
||||
Logger::global().set_log(err);
|
||||
}
|
||||
CommandEvent::Error(err) => {
|
||||
log::error!(target: "app", "[mihomo]: {err}");
|
||||
Logger::global().set_log(err);
|
||||
}
|
||||
CommandEvent::Terminated(_) => {
|
||||
log::info!(target: "app", "mihomo core terminated");
|
||||
let _ = CoreManager::global().recover_core();
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
tauri::async_runtime::spawn(async move {
|
||||
while let Some(event) = rx.recv().await {
|
||||
match event {
|
||||
CommandEvent::Stdout(line) => {
|
||||
let line = String::from_utf8(line).unwrap_or_default();
|
||||
log::info!(target: "app", "[mihomo]: {line}");
|
||||
Logger::global().set_log(line);
|
||||
}
|
||||
CommandEvent::Stderr(err) => {
|
||||
let err = String::from_utf8(err).unwrap_or_default();
|
||||
log::error!(target: "app", "[mihomo]: {err}");
|
||||
Logger::global().set_log(err);
|
||||
}
|
||||
CommandEvent::Error(err) => {
|
||||
log::error!(target: "app", "[mihomo]: {err}");
|
||||
Logger::global().set_log(err);
|
||||
}
|
||||
CommandEvent::Terminated(_) => {
|
||||
log::info!(target: "app", "mihomo core terminated");
|
||||
let _ = CoreManager::global().recover_core();
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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() {
|
||||
if let Err(e) = app_handle.global_shortcut().unregister_all() {
|
||||
log::error!("Error unregistering all hotkeys: {:?}", e);
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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()),
|
||||
|
||||
Reference in New Issue
Block a user