refactor: improve code formatting and enhance logging consistency across core and event handling modules

This commit is contained in:
xmk23333
2025-10-20 16:47:26 +08:00
parent b9dd62e2e6
commit 98778fe6a3
3 changed files with 129 additions and 67 deletions

View File

@@ -257,7 +257,11 @@ impl CoreManager {
async fn cleanup_orphaned_mihomo_processes(&self) -> Result<()> { async fn cleanup_orphaned_mihomo_processes(&self) -> Result<()> {
logging!(info, Type::Core, "开始清理多余的 mihomo 进程"); logging!(info, Type::Core, "开始清理多余的 mihomo 进程");
let current_pid = self.child_sidecar.lock().as_ref().and_then(|child| child.pid()); let current_pid = self
.child_sidecar
.lock()
.as_ref()
.and_then(|child| child.pid());
let target_processes = ["verge-mihomo", "verge-mihomo-alpha"]; let target_processes = ["verge-mihomo", "verge-mihomo-alpha"];
let process_futures = target_processes.iter().map(|&target| { let process_futures = target_processes.iter().map(|&target| {
@@ -286,7 +290,8 @@ impl CoreManager {
return Ok(()); return Ok(());
} }
let kill_futures = pids_to_kill.iter() let kill_futures = pids_to_kill
.iter()
.map(|(pid, name)| self.kill_process_with_verification(*pid, name.clone())); .map(|(pid, name)| self.kill_process_with_verification(*pid, name.clone()));
let killed_count = futures::future::join_all(kill_futures) let killed_count = futures::future::join_all(kill_futures)
@@ -338,16 +343,19 @@ impl CoreManager {
if Process32FirstW(snapshot, &mut pe32) != 0 { if Process32FirstW(snapshot, &mut pe32) != 0 {
loop { loop {
let end_pos = pe32.szExeFile.iter().position(|&x| x == 0) let end_pos = pe32
.szExeFile
.iter()
.position(|&x| x == 0)
.unwrap_or(pe32.szExeFile.len()); .unwrap_or(pe32.szExeFile.len());
if end_pos > 0 { if end_pos > 0 {
let exe_file = String::from_utf16_lossy(&pe32.szExeFile[..end_pos]); let exe_file = String::from_utf16_lossy(&pe32.szExeFile[..end_pos]);
if exe_file.eq_ignore_ascii_case(&process_name_clone) { if exe_file.eq_ignore_ascii_case(&process_name_clone) {
pids.push(pe32.th32ProcessID); pids.push(pe32.th32ProcessID);
} }
} }
if Process32NextW(snapshot, &mut pe32) == 0 { if Process32NextW(snapshot, &mut pe32) == 0 {
break; break;
} }
@@ -393,7 +401,13 @@ impl CoreManager {
} }
async fn kill_process_with_verification(&self, pid: u32, process_name: String) -> bool { async fn kill_process_with_verification(&self, pid: u32, process_name: String) -> bool {
logging!(info, Type::Core, "尝试终止进程: {} (PID: {})", process_name, pid); logging!(
info,
Type::Core,
"尝试终止进程: {} (PID: {})",
process_name,
pid
);
#[cfg(windows)] #[cfg(windows)]
let success = { let success = {
@@ -423,17 +437,35 @@ impl CoreManager {
.unwrap_or(false); .unwrap_or(false);
if !success { if !success {
logging!(warn, Type::Core, "无法终止进程: {} (PID: {})", process_name, pid); logging!(
warn,
Type::Core,
"无法终止进程: {} (PID: {})",
process_name,
pid
);
return false; return false;
} }
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await; tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
if self.is_process_running(pid).await.unwrap_or(false) { if self.is_process_running(pid).await.unwrap_or(false) {
logging!(warn, Type::Core, "进程 {} (PID: {}) 终止命令成功但进程仍在运行", process_name, pid); logging!(
warn,
Type::Core,
"进程 {} (PID: {}) 终止命令成功但进程仍在运行",
process_name,
pid
);
false false
} else { } else {
logging!(info, Type::Core, "成功终止进程: {} (PID: {})", process_name, pid); logging!(
info,
Type::Core,
"成功终止进程: {} (PID: {})",
process_name,
pid
);
true true
} }
} }
@@ -500,7 +532,7 @@ impl CoreManager {
AsyncHandler::spawn(|| async move { AsyncHandler::spawn(|| async move {
while let Some(event) = rx.recv().await { while let Some(event) = rx.recv().await {
match event { match event {
tauri_plugin_shell::process::CommandEvent::Stdout(line) tauri_plugin_shell::process::CommandEvent::Stdout(line)
| tauri_plugin_shell::process::CommandEvent::Stderr(line) => { | tauri_plugin_shell::process::CommandEvent::Stderr(line) => {
let mut now = DeferredNow::default(); let mut now = DeferredNow::default();
let message = CompactString::from(String::from_utf8_lossy(&line).as_ref()); let message = CompactString::from(String::from_utf8_lossy(&line).as_ref());

View File

@@ -254,8 +254,8 @@ pub fn run() {
.invoke_handler(app_init::generate_handlers()); .invoke_handler(app_init::generate_handlers());
mod event_handlers { mod event_handlers {
use crate::core::handle;
use super::*; use super::*;
use crate::core::handle;
pub fn handle_ready_resumed(_app_handle: &AppHandle) { pub fn handle_ready_resumed(_app_handle: &AppHandle) {
if handle::Handle::global().is_exiting() { if handle::Handle::global().is_exiting() {
@@ -310,8 +310,12 @@ pub fn run() {
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
{ {
use crate::core::hotkey::SystemHotkey; use crate::core::hotkey::SystemHotkey;
let _ = hotkey::Hotkey::global().register_system_hotkey(SystemHotkey::CmdQ).await; let _ = hotkey::Hotkey::global()
let _ = hotkey::Hotkey::global().register_system_hotkey(SystemHotkey::CmdW).await; .register_system_hotkey(SystemHotkey::CmdQ)
.await;
let _ = hotkey::Hotkey::global()
.register_system_hotkey(SystemHotkey::CmdW)
.await;
} }
if !is_enable_global_hotkey { if !is_enable_global_hotkey {
@@ -354,69 +358,83 @@ pub fn run() {
let context = tauri::test::mock_context(tauri::test::noop_assets()); let context = tauri::test::mock_context(tauri::test::noop_assets());
#[cfg(feature = "clippy")] #[cfg(feature = "clippy")]
let app = builder.build(context).unwrap_or_else(|e| { let app = builder.build(context).unwrap_or_else(|e| {
logging!(error, Type::Setup, "Failed to build Tauri application: {}", e); logging!(
error,
Type::Setup,
"Failed to build Tauri application: {}",
e
);
std::process::exit(1); std::process::exit(1);
}); });
#[cfg(not(feature = "clippy"))] #[cfg(not(feature = "clippy"))]
let app = builder.build(tauri::generate_context!()).unwrap_or_else(|e| { let app = builder
logging!(error, Type::Setup, "Failed to build Tauri application: {}", e); .build(tauri::generate_context!())
std::process::exit(1); .unwrap_or_else(|e| {
}); logging!(
error,
Type::Setup,
"Failed to build Tauri application: {}",
e
);
std::process::exit(1);
});
app.run(|app_handle, e| { app.run(|app_handle, e| match e {
match e { tauri::RunEvent::Ready | tauri::RunEvent::Resumed => {
tauri::RunEvent::Ready | tauri::RunEvent::Resumed => { if core::handle::Handle::global().is_exiting() {
if core::handle::Handle::global().is_exiting() { return;
return;
}
event_handlers::handle_ready_resumed(app_handle);
} }
#[cfg(target_os = "macos")] event_handlers::handle_ready_resumed(app_handle);
tauri::RunEvent::Reopen { has_visible_windows, .. } => { }
if core::handle::Handle::global().is_exiting() { #[cfg(target_os = "macos")]
return; tauri::RunEvent::Reopen {
} has_visible_windows,
let _ = AsyncHandler::spawn(move || async move { ..
event_handlers::handle_reopen(has_visible_windows).await; } => {
}); if core::handle::Handle::global().is_exiting() {
return;
} }
tauri::RunEvent::ExitRequested { api, code, .. } => { let _ = AsyncHandler::spawn(move || async move {
tauri::async_runtime::block_on(async { event_handlers::handle_reopen(has_visible_windows).await;
let _ = handle::Handle::mihomo().await.clear_all_ws_connections().await; });
}); }
tauri::RunEvent::ExitRequested { api, code, .. } => {
tauri::async_runtime::block_on(async {
let _ = handle::Handle::mihomo()
.await
.clear_all_ws_connections()
.await;
});
if core::handle::Handle::global().is_exiting() { if core::handle::Handle::global().is_exiting() {
return; return;
} }
if code.is_none() { if code.is_none() {
api.prevent_exit(); api.prevent_exit();
}
} }
tauri::RunEvent::Exit => { }
let handle = core::handle::Handle::global(); tauri::RunEvent::Exit => {
if !handle.is_exiting() { let handle = core::handle::Handle::global();
handle.set_is_exiting(); if !handle.is_exiting() {
EventDrivenProxyManager::global().notify_app_stopping(); handle.set_is_exiting();
feat::clean(); EventDrivenProxyManager::global().notify_app_stopping();
} feat::clean();
} }
tauri::RunEvent::WindowEvent { label, event, .. } if label == "main" => { }
match event { tauri::RunEvent::WindowEvent { label, event, .. } if label == "main" => match event {
tauri::WindowEvent::CloseRequested { .. } => { tauri::WindowEvent::CloseRequested { .. } => {
event_handlers::handle_window_close(&event); event_handlers::handle_window_close(&event);
} }
tauri::WindowEvent::Focused(focused) => { tauri::WindowEvent::Focused(focused) => {
event_handlers::handle_window_focus(focused); event_handlers::handle_window_focus(focused);
} }
tauri::WindowEvent::Destroyed => { tauri::WindowEvent::Destroyed => {
event_handlers::handle_window_destroyed(); event_handlers::handle_window_destroyed();
}
_ => {}
}
} }
_ => {} _ => {}
} },
_ => {}
}); });
} }

View File

@@ -36,7 +36,12 @@ pub fn resolve_setup_async() {
let _ = AsyncHandler::spawn(|| async { let _ = AsyncHandler::spawn(|| async {
#[cfg(not(feature = "tauri-dev"))] #[cfg(not(feature = "tauri-dev"))]
resolve_setup_logger().await; resolve_setup_logger().await;
logging!(info, Type::ClashVergeRev, "Version: {}", env!("CARGO_PKG_VERSION")); logging!(
info,
Type::ClashVergeRev,
"Version: {}",
env!("CARGO_PKG_VERSION")
);
futures::join!(init_work_config(), init_resources(), init_startup_script()); futures::join!(init_work_config(), init_resources(), init_startup_script());
@@ -156,7 +161,10 @@ pub(super) async fn init_core_manager() {
} }
pub(super) async fn init_system_proxy() { pub(super) async fn init_system_proxy() {
logging_error!(Type::Setup, sysopt::Sysopt::global().update_sysproxy().await); logging_error!(
Type::Setup,
sysopt::Sysopt::global().update_sysproxy().await
);
} }
pub(super) fn init_system_proxy_guard() { pub(super) fn init_system_proxy_guard() {
@@ -168,7 +176,11 @@ pub(super) async fn refresh_tray_menu() {
} }
pub(super) async fn init_window() { pub(super) async fn init_window() {
let is_silent_start = Config::verge().await.latest_ref().enable_silent_start.unwrap_or(false); let is_silent_start = Config::verge()
.await
.latest_ref()
.enable_silent_start
.unwrap_or(false);
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
if is_silent_start { if is_silent_start {
use crate::core::handle::Handle; use crate::core::handle::Handle;