Refactor logging macros to remove print control parameter

- Updated logging macros to eliminate the boolean parameter for print control, simplifying the logging calls throughout the codebase.
- Adjusted all logging calls in various modules (lib.rs, lightweight.rs, help.rs, init.rs, logging.rs, resolve/mod.rs, resolve/scheme.rs, resolve/ui.rs, resolve/window.rs, server.rs, singleton.rs, window_manager.rs) to reflect the new macro structure.
- Ensured consistent logging behavior across the application by standardizing the logging format.
This commit is contained in:
Tunglies
2025-10-10 13:05:01 +08:00
parent a4d94c8bc9
commit 8c0af66ca9
33 changed files with 292 additions and 706 deletions

View File

@@ -191,7 +191,6 @@ pub fn copy_icon_file(path: String, icon_info: IconInfo) -> CmdResult<String> {
logging!( logging!(
info, info,
Type::Cmd, Type::Cmd,
true,
"Copying icon file path: {:?} -> file dist: {:?}", "Copying icon file path: {:?} -> file dist: {:?}",
path, path,
dest_path dest_path

View File

@@ -38,11 +38,11 @@ pub async fn get_profiles() -> CmdResult<IProfiles> {
match latest_result { match latest_result {
Ok(profiles) => { Ok(profiles) => {
logging!(info, Type::Cmd, false, "快速获取配置列表成功"); logging!(info, Type::Cmd, "快速获取配置列表成功");
return Ok(profiles); return Ok(profiles);
} }
Err(_) => { Err(_) => {
logging!(warn, Type::Cmd, true, "快速获取配置超时(500ms)"); logging!(warn, Type::Cmd, "快速获取配置超时(500ms)");
} }
} }
@@ -59,14 +59,13 @@ pub async fn get_profiles() -> CmdResult<IProfiles> {
match data_result { match data_result {
Ok(profiles) => { Ok(profiles) => {
logging!(info, Type::Cmd, false, "获取draft配置列表成功"); logging!(info, Type::Cmd, "获取draft配置列表成功");
return Ok(profiles); return Ok(profiles);
} }
Err(join_err) => { Err(join_err) => {
logging!( logging!(
error, error,
Type::Cmd, Type::Cmd,
true,
"获取draft配置任务失败或超时: {}", "获取draft配置任务失败或超时: {}",
join_err join_err
); );
@@ -74,12 +73,7 @@ pub async fn get_profiles() -> CmdResult<IProfiles> {
} }
// 策略3: fallback尝试重新创建配置 // 策略3: fallback尝试重新创建配置
logging!( logging!(warn, Type::Cmd, "所有获取配置策略都失败尝试fallback");
warn,
Type::Cmd,
true,
"所有获取配置策略都失败尝试fallback"
);
Ok(IProfiles::new().await) Ok(IProfiles::new().await)
} }
@@ -101,11 +95,11 @@ pub async fn enhance_profiles() -> CmdResult {
/// 导入配置文件 /// 导入配置文件
#[tauri::command] #[tauri::command]
pub async fn import_profile(url: String, option: Option<PrfOption>) -> CmdResult { pub async fn import_profile(url: String, option: Option<PrfOption>) -> CmdResult {
logging!(info, Type::Cmd, true, "[导入订阅] 开始导入: {}", url); logging!(info, Type::Cmd, "[导入订阅] 开始导入: {}", url);
let import_result = tokio::time::timeout(Duration::from_secs(60), async { let import_result = tokio::time::timeout(Duration::from_secs(60), async {
let item = PrfItem::from_url(&url, None, None, option).await?; let item = PrfItem::from_url(&url, None, None, option).await?;
logging!(info, Type::Cmd, true, "[导入订阅] 下载完成,开始保存配置"); logging!(info, Type::Cmd, "[导入订阅] 下载完成,开始保存配置");
let profiles = Config::profiles().await; let profiles = Config::profiles().await;
let pre_count = profiles let pre_count = profiles
@@ -123,19 +117,13 @@ pub async fn import_profile(url: String, option: Option<PrfOption>) -> CmdResult
.as_ref() .as_ref()
.map_or(0, |items| items.len()); .map_or(0, |items| items.len());
if post_count <= pre_count { if post_count <= pre_count {
logging!( logging!(error, Type::Cmd, "[导入订阅] 配置未增加,导入可能失败");
error,
Type::Cmd,
true,
"[导入订阅] 配置未增加,导入可能失败"
);
return Err(anyhow::anyhow!("配置导入后数量未增加")); return Err(anyhow::anyhow!("配置导入后数量未增加"));
} }
logging!( logging!(
info, info,
Type::Cmd, Type::Cmd,
true,
"[导入订阅] 配置保存成功,数量: {} -> {}", "[导入订阅] 配置保存成功,数量: {} -> {}",
pre_count, pre_count,
post_count post_count
@@ -143,13 +131,7 @@ pub async fn import_profile(url: String, option: Option<PrfOption>) -> CmdResult
// 立即发送配置变更通知 // 立即发送配置变更通知
if let Some(uid) = &item.uid { if let Some(uid) = &item.uid {
logging!( logging!(info, Type::Cmd, "[导入订阅] 发送配置变更通知: {}", uid);
info,
Type::Cmd,
true,
"[导入订阅] 发送配置变更通知: {}",
uid
);
handle::Handle::notify_profile_changed(uid.clone()); handle::Handle::notify_profile_changed(uid.clone());
} }
@@ -158,9 +140,9 @@ pub async fn import_profile(url: String, option: Option<PrfOption>) -> CmdResult
crate::process::AsyncHandler::spawn(move || async move { crate::process::AsyncHandler::spawn(move || async move {
// 使用Send-safe helper函数 // 使用Send-safe helper函数
if let Err(e) = profiles_save_file_safe().await { if let Err(e) = profiles_save_file_safe().await {
logging!(error, Type::Cmd, true, "[导入订阅] 保存配置文件失败: {}", e); logging!(error, Type::Cmd, "[导入订阅] 保存配置文件失败: {}", e);
} else { } else {
logging!(info, Type::Cmd, true, "[导入订阅] 配置文件保存成功"); logging!(info, Type::Cmd, "[导入订阅] 配置文件保存成功");
// 发送全局配置更新通知 // 发送全局配置更新通知
if let Some(uid) = uid_clone { if let Some(uid) = uid_clone {
@@ -177,15 +159,15 @@ pub async fn import_profile(url: String, option: Option<PrfOption>) -> CmdResult
match import_result { match import_result {
Ok(Ok(())) => { Ok(Ok(())) => {
logging!(info, Type::Cmd, true, "[导入订阅] 导入完成: {}", url); logging!(info, Type::Cmd, "[导入订阅] 导入完成: {}", url);
Ok(()) Ok(())
} }
Ok(Err(e)) => { Ok(Err(e)) => {
logging!(error, Type::Cmd, true, "[导入订阅] 导入失败: {}", e); logging!(error, Type::Cmd, "[导入订阅] 导入失败: {}", e);
Err(format!("导入订阅失败: {e}")) Err(format!("导入订阅失败: {e}"))
} }
Err(_) => { Err(_) => {
logging!(error, Type::Cmd, true, "[导入订阅] 导入超时(60秒): {}", url); logging!(error, Type::Cmd, "[导入订阅] 导入超时(60秒): {}", url);
Err("导入订阅超时,请检查网络连接".into()) Err("导入订阅超时,请检查网络连接".into())
} }
} }
@@ -214,13 +196,7 @@ pub async fn create_profile(item: PrfItem, file_data: Option<String>) -> CmdResu
Ok(_) => { Ok(_) => {
// 发送配置变更通知 // 发送配置变更通知
if let Some(uid) = &item.uid { if let Some(uid) = &item.uid {
logging!( logging!(info, Type::Cmd, "[创建订阅] 发送配置变更通知: {}", uid);
info,
Type::Cmd,
true,
"[创建订阅] 发送配置变更通知: {}",
uid
);
handle::Handle::notify_profile_changed(uid.clone()); handle::Handle::notify_profile_changed(uid.clone());
} }
Ok(()) Ok(())
@@ -255,13 +231,7 @@ pub async fn delete_profile(index: String) -> CmdResult {
Ok(_) => { Ok(_) => {
handle::Handle::refresh_clash(); handle::Handle::refresh_clash();
// 发送配置变更通知 // 发送配置变更通知
logging!( logging!(info, Type::Cmd, "[删除订阅] 发送配置变更通知: {}", index);
info,
Type::Cmd,
true,
"[删除订阅] 发送配置变更通知: {}",
index
);
handle::Handle::notify_profile_changed(index); handle::Handle::notify_profile_changed(index);
} }
Err(e) => { Err(e) => {
@@ -277,7 +247,7 @@ pub async fn delete_profile(index: String) -> CmdResult {
#[tauri::command] #[tauri::command]
pub async fn patch_profiles_config(profiles: IProfiles) -> CmdResult<bool> { pub async fn patch_profiles_config(profiles: IProfiles) -> CmdResult<bool> {
if CURRENT_SWITCHING_PROFILE.load(Ordering::SeqCst) { if CURRENT_SWITCHING_PROFILE.load(Ordering::SeqCst) {
logging!(info, Type::Cmd, true, "当前正在切换配置,放弃请求"); logging!(info, Type::Cmd, "当前正在切换配置,放弃请求");
return Ok(false); return Ok(false);
} }
CURRENT_SWITCHING_PROFILE.store(true, Ordering::SeqCst); CURRENT_SWITCHING_PROFILE.store(true, Ordering::SeqCst);
@@ -289,7 +259,6 @@ pub async fn patch_profiles_config(profiles: IProfiles) -> CmdResult<bool> {
logging!( logging!(
info, info,
Type::Cmd, Type::Cmd,
true,
"开始修改配置文件,请求序列号: {}, 目标profile: {:?}", "开始修改配置文件,请求序列号: {}, 目标profile: {:?}",
current_sequence, current_sequence,
target_profile target_profile
@@ -300,7 +269,6 @@ pub async fn patch_profiles_config(profiles: IProfiles) -> CmdResult<bool> {
logging!( logging!(
info, info,
Type::Cmd, Type::Cmd,
true,
"获取锁后发现更新的请求 (序列号: {} < {}),放弃当前请求", "获取锁后发现更新的请求 (序列号: {} < {}),放弃当前请求",
current_sequence, current_sequence,
latest_sequence latest_sequence
@@ -310,13 +278,13 @@ pub async fn patch_profiles_config(profiles: IProfiles) -> CmdResult<bool> {
// 保存当前配置,以便在验证失败时恢复 // 保存当前配置,以便在验证失败时恢复
let current_profile = Config::profiles().await.latest_ref().current.clone(); let current_profile = Config::profiles().await.latest_ref().current.clone();
logging!(info, Type::Cmd, true, "当前配置: {:?}", current_profile); logging!(info, Type::Cmd, "当前配置: {:?}", current_profile);
// 如果要切换配置,先检查目标配置文件是否有语法错误 // 如果要切换配置,先检查目标配置文件是否有语法错误
if let Some(new_profile) = profiles.current.as_ref() if let Some(new_profile) = profiles.current.as_ref()
&& current_profile.as_ref() != Some(new_profile) && current_profile.as_ref() != Some(new_profile)
{ {
logging!(info, Type::Cmd, true, "正在切换到新配置: {}", new_profile); logging!(info, Type::Cmd, "正在切换到新配置: {}", new_profile);
// 获取目标配置文件路径 // 获取目标配置文件路径
let config_file_result = { let config_file_result = {
@@ -332,7 +300,7 @@ pub async fn patch_profiles_config(profiles: IProfiles) -> CmdResult<bool> {
} }
} }
Err(e) => { Err(e) => {
logging!(error, Type::Cmd, true, "获取目标配置信息失败: {}", e); logging!(error, Type::Cmd, "获取目标配置信息失败: {}", e);
None None
} }
} }
@@ -344,7 +312,6 @@ pub async fn patch_profiles_config(profiles: IProfiles) -> CmdResult<bool> {
logging!( logging!(
error, error,
Type::Cmd, Type::Cmd,
true,
"目标配置文件不存在: {}", "目标配置文件不存在: {}",
file_path.display() file_path.display()
); );
@@ -371,14 +338,13 @@ pub async fn patch_profiles_config(profiles: IProfiles) -> CmdResult<bool> {
match yaml_parse_result { match yaml_parse_result {
Ok(Ok(_)) => { Ok(Ok(_)) => {
logging!(info, Type::Cmd, true, "目标配置文件语法正确"); logging!(info, Type::Cmd, "目标配置文件语法正确");
} }
Ok(Err(err)) => { Ok(Err(err)) => {
let error_msg = format!(" {err}"); let error_msg = format!(" {err}");
logging!( logging!(
error, error,
Type::Cmd, Type::Cmd,
true,
"目标配置文件存在YAML语法错误:{}", "目标配置文件存在YAML语法错误:{}",
error_msg error_msg
); );
@@ -390,7 +356,7 @@ pub async fn patch_profiles_config(profiles: IProfiles) -> CmdResult<bool> {
} }
Err(join_err) => { Err(join_err) => {
let error_msg = format!("YAML解析任务失败: {join_err}"); let error_msg = format!("YAML解析任务失败: {join_err}");
logging!(error, Type::Cmd, true, "{}", error_msg); logging!(error, Type::Cmd, "{}", error_msg);
handle::Handle::notice_message( handle::Handle::notice_message(
"config_validate::yaml_parse_error", "config_validate::yaml_parse_error",
&error_msg, &error_msg,
@@ -401,13 +367,13 @@ pub async fn patch_profiles_config(profiles: IProfiles) -> CmdResult<bool> {
} }
Ok(Err(err)) => { Ok(Err(err)) => {
let error_msg = format!("无法读取目标配置文件: {err}"); let error_msg = format!("无法读取目标配置文件: {err}");
logging!(error, Type::Cmd, true, "{}", error_msg); logging!(error, Type::Cmd, "{}", error_msg);
handle::Handle::notice_message("config_validate::file_read_error", &error_msg); handle::Handle::notice_message("config_validate::file_read_error", &error_msg);
return Ok(false); return Ok(false);
} }
Err(_) => { Err(_) => {
let error_msg = "读取配置文件超时(5秒)".to_string(); let error_msg = "读取配置文件超时(5秒)".to_string();
logging!(error, Type::Cmd, true, "{}", error_msg); logging!(error, Type::Cmd, "{}", error_msg);
handle::Handle::notice_message( handle::Handle::notice_message(
"config_validate::file_read_timeout", "config_validate::file_read_timeout",
&error_msg, &error_msg,
@@ -424,7 +390,6 @@ pub async fn patch_profiles_config(profiles: IProfiles) -> CmdResult<bool> {
logging!( logging!(
info, info,
Type::Cmd, Type::Cmd,
true,
"在核心操作前发现更新的请求 (序列号: {} < {}),放弃当前请求", "在核心操作前发现更新的请求 (序列号: {} < {}),放弃当前请求",
current_sequence, current_sequence,
latest_sequence latest_sequence
@@ -436,7 +401,6 @@ pub async fn patch_profiles_config(profiles: IProfiles) -> CmdResult<bool> {
logging!( logging!(
info, info,
Type::Cmd, Type::Cmd,
true,
"正在更新配置草稿,序列号: {}", "正在更新配置草稿,序列号: {}",
current_sequence current_sequence
); );
@@ -451,7 +415,6 @@ pub async fn patch_profiles_config(profiles: IProfiles) -> CmdResult<bool> {
logging!( logging!(
info, info,
Type::Cmd, Type::Cmd,
true,
"在内核交互前发现更新的请求 (序列号: {} < {}),放弃当前请求", "在内核交互前发现更新的请求 (序列号: {} < {}),放弃当前请求",
current_sequence, current_sequence,
latest_sequence latest_sequence
@@ -464,7 +427,6 @@ pub async fn patch_profiles_config(profiles: IProfiles) -> CmdResult<bool> {
logging!( logging!(
info, info,
Type::Cmd, Type::Cmd,
true,
"开始内核配置更新,序列号: {}", "开始内核配置更新,序列号: {}",
current_sequence current_sequence
); );
@@ -483,7 +445,6 @@ pub async fn patch_profiles_config(profiles: IProfiles) -> CmdResult<bool> {
logging!( logging!(
info, info,
Type::Cmd, Type::Cmd,
true,
"内核操作后发现更新的请求 (序列号: {} < {}),忽略当前结果", "内核操作后发现更新的请求 (序列号: {} < {}),忽略当前结果",
current_sequence, current_sequence,
latest_sequence latest_sequence
@@ -495,7 +456,6 @@ pub async fn patch_profiles_config(profiles: IProfiles) -> CmdResult<bool> {
logging!( logging!(
info, info,
Type::Cmd, Type::Cmd,
true,
"配置更新成功,序列号: {}", "配置更新成功,序列号: {}",
current_sequence current_sequence
); );
@@ -527,7 +487,6 @@ pub async fn patch_profiles_config(profiles: IProfiles) -> CmdResult<bool> {
logging!( logging!(
info, info,
Type::Cmd, Type::Cmd,
true,
"向前端发送配置变更事件: {}, 序列号: {}", "向前端发送配置变更事件: {}, 序列号: {}",
current, current,
current_sequence current_sequence
@@ -539,17 +498,11 @@ pub async fn patch_profiles_config(profiles: IProfiles) -> CmdResult<bool> {
Ok(true) Ok(true)
} }
Ok(Ok((false, error_msg))) => { Ok(Ok((false, error_msg))) => {
logging!(warn, Type::Cmd, true, "配置验证失败: {}", error_msg); logging!(warn, Type::Cmd, "配置验证失败: {}", error_msg);
Config::profiles().await.discard(); Config::profiles().await.discard();
// 如果验证失败,恢复到之前的配置 // 如果验证失败,恢复到之前的配置
if let Some(prev_profile) = current_profile { if let Some(prev_profile) = current_profile {
logging!( logging!(info, Type::Cmd, "尝试恢复到之前的配置: {}", prev_profile);
info,
Type::Cmd,
true,
"尝试恢复到之前的配置: {}",
prev_profile
);
let restore_profiles = IProfiles { let restore_profiles = IProfiles {
current: Some(prev_profile), current: Some(prev_profile),
items: None, items: None,
@@ -569,7 +522,7 @@ pub async fn patch_profiles_config(profiles: IProfiles) -> CmdResult<bool> {
} }
}); });
logging!(info, Type::Cmd, true, "成功恢复到之前的配置"); logging!(info, Type::Cmd, "成功恢复到之前的配置");
} }
// 发送验证错误通知 // 发送验证错误通知
@@ -581,7 +534,6 @@ pub async fn patch_profiles_config(profiles: IProfiles) -> CmdResult<bool> {
logging!( logging!(
warn, warn,
Type::Cmd, Type::Cmd,
true,
"更新过程发生错误: {}, 序列号: {}", "更新过程发生错误: {}, 序列号: {}",
e, e,
current_sequence current_sequence
@@ -598,7 +550,6 @@ pub async fn patch_profiles_config(profiles: IProfiles) -> CmdResult<bool> {
logging!( logging!(
error, error,
Type::Cmd, Type::Cmd,
true,
"{}, 序列号: {}", "{}, 序列号: {}",
timeout_msg, timeout_msg,
current_sequence current_sequence
@@ -609,7 +560,6 @@ pub async fn patch_profiles_config(profiles: IProfiles) -> CmdResult<bool> {
logging!( logging!(
info, info,
Type::Cmd, Type::Cmd,
true,
"超时后尝试恢复到之前的配置: {}, 序列号: {}", "超时后尝试恢复到之前的配置: {}, 序列号: {}",
prev_profile, prev_profile,
current_sequence current_sequence
@@ -637,7 +587,7 @@ pub async fn patch_profiles_config(profiles: IProfiles) -> CmdResult<bool> {
/// 根据profile name修改profiles /// 根据profile name修改profiles
#[tauri::command] #[tauri::command]
pub async fn patch_profiles_config_by_profile_index(profile_index: String) -> CmdResult<bool> { pub async fn patch_profiles_config_by_profile_index(profile_index: String) -> CmdResult<bool> {
logging!(info, Type::Cmd, true, "切换配置到: {}", profile_index); logging!(info, Type::Cmd, "切换配置到: {}", profile_index);
let profiles = IProfiles { let profiles = IProfiles {
current: Some(profile_index), current: Some(profile_index),

View File

@@ -36,7 +36,6 @@ pub async fn save_profile_file(index: String, file_data: Option<String>) -> CmdR
logging!( logging!(
info, info,
Type::Config, Type::Config,
true,
"[cmd配置save] 开始验证配置文件: {}, 是否为merge文件: {}", "[cmd配置save] 开始验证配置文件: {}, 是否为merge文件: {}",
file_path_str, file_path_str,
is_merge_file is_merge_file
@@ -47,7 +46,6 @@ pub async fn save_profile_file(index: String, file_data: Option<String>) -> CmdR
logging!( logging!(
info, info,
Type::Config, Type::Config,
true,
"[cmd配置save] 检测到merge文件只进行语法验证" "[cmd配置save] 检测到merge文件只进行语法验证"
); );
match CoreManager::global() match CoreManager::global()
@@ -55,12 +53,7 @@ pub async fn save_profile_file(index: String, file_data: Option<String>) -> CmdR
.await .await
{ {
Ok((true, _)) => { Ok((true, _)) => {
logging!( logging!(info, Type::Config, "[cmd配置save] merge文件语法验证通过");
info,
Type::Config,
true,
"[cmd配置save] merge文件语法验证通过"
);
// 成功后尝试更新整体配置 // 成功后尝试更新整体配置
match CoreManager::global().update_config().await { match CoreManager::global().update_config().await {
Ok(_) => { Ok(_) => {
@@ -71,7 +64,6 @@ pub async fn save_profile_file(index: String, file_data: Option<String>) -> CmdR
logging!( logging!(
warn, warn,
Type::Config, Type::Config,
true,
"[cmd配置save] 更新整体配置时发生错误: {}", "[cmd配置save] 更新整体配置时发生错误: {}",
e e
); );
@@ -83,7 +75,6 @@ pub async fn save_profile_file(index: String, file_data: Option<String>) -> CmdR
logging!( logging!(
warn, warn,
Type::Config, Type::Config,
true,
"[cmd配置save] merge文件语法验证失败: {}", "[cmd配置save] merge文件语法验证失败: {}",
error_msg error_msg
); );
@@ -95,13 +86,7 @@ pub async fn save_profile_file(index: String, file_data: Option<String>) -> CmdR
return Ok(()); return Ok(());
} }
Err(e) => { Err(e) => {
logging!( logging!(error, Type::Config, "[cmd配置save] 验证过程发生错误: {}", e);
error,
Type::Config,
true,
"[cmd配置save] 验证过程发生错误: {}",
e
);
// 恢复原始配置文件 // 恢复原始配置文件
wrap_err!(fs::write(&file_path, original_content).await)?; wrap_err!(fs::write(&file_path, original_content).await)?;
return Err(e.to_string()); return Err(e.to_string());
@@ -115,17 +100,11 @@ pub async fn save_profile_file(index: String, file_data: Option<String>) -> CmdR
.await .await
{ {
Ok((true, _)) => { Ok((true, _)) => {
logging!(info, Type::Config, true, "[cmd配置save] 验证成功"); logging!(info, Type::Config, "[cmd配置save] 验证成功");
Ok(()) Ok(())
} }
Ok((false, error_msg)) => { Ok((false, error_msg)) => {
logging!( logging!(warn, Type::Config, "[cmd配置save] 验证失败: {}", error_msg);
warn,
Type::Config,
true,
"[cmd配置save] 验证失败: {}",
error_msg
);
// 恢复原始配置文件 // 恢复原始配置文件
wrap_err!(fs::write(&file_path, original_content).await)?; wrap_err!(fs::write(&file_path, original_content).await)?;
@@ -169,13 +148,7 @@ pub async fn save_profile_file(index: String, file_data: Option<String>) -> CmdR
Ok(()) Ok(())
} }
Err(e) => { Err(e) => {
logging!( logging!(error, Type::Config, "[cmd配置save] 验证过程发生错误: {}", e);
error,
Type::Config,
true,
"[cmd配置save] 验证过程发生错误: {}",
e
);
// 恢复原始配置文件 // 恢复原始配置文件
wrap_err!(fs::write(&file_path, original_content).await)?; wrap_err!(fs::write(&file_path, original_content).await)?;
Err(e.to_string()) Err(e.to_string())

View File

@@ -28,14 +28,7 @@ pub fn handle_script_validation_notice(result: &(bool, String), file_type: &str)
"config_validate::script_error" "config_validate::script_error"
}; };
logging!( logging!(warn, Type::Config, "{} 验证失败: {}", file_type, error_msg);
warn,
Type::Config,
true,
"{} 验证失败: {}",
file_type,
error_msg
);
handle::Handle::notice_message(status, error_msg); handle::Handle::notice_message(status, error_msg);
} }
} }
@@ -43,7 +36,7 @@ pub fn handle_script_validation_notice(result: &(bool, String), file_type: &str)
/// 验证指定脚本文件 /// 验证指定脚本文件
#[tauri::command] #[tauri::command]
pub async fn validate_script_file(file_path: String) -> CmdResult<bool> { pub async fn validate_script_file(file_path: String) -> CmdResult<bool> {
logging!(info, Type::Config, true, "验证脚本文件: {}", file_path); logging!(info, Type::Config, "验证脚本文件: {}", file_path);
match CoreManager::global() match CoreManager::global()
.validate_config_file(&file_path, None) .validate_config_file(&file_path, None)
@@ -58,7 +51,6 @@ pub async fn validate_script_file(file_path: String) -> CmdResult<bool> {
logging!( logging!(
error, error,
Type::Config, Type::Config,
true,
"验证脚本文件过程发生错误: {}", "验证脚本文件过程发生错误: {}",
error_msg error_msg
); );
@@ -76,7 +68,6 @@ pub fn handle_yaml_validation_notice(result: &(bool, String), file_type: &str) {
logging!( logging!(
info, info,
Type::Config, Type::Config,
true,
"[通知] 处理{}验证错误: {}", "[通知] 处理{}验证错误: {}",
file_type, file_type,
error_msg error_msg
@@ -117,18 +108,10 @@ pub fn handle_yaml_validation_notice(result: &(bool, String), file_type: &str) {
} }
}; };
logging!( logging!(warn, Type::Config, "{} 验证失败: {}", file_type, error_msg);
warn,
Type::Config,
true,
"{} 验证失败: {}",
file_type,
error_msg
);
logging!( logging!(
info, info,
Type::Config, Type::Config,
true,
"[通知] 发送通知: status={}, msg={}", "[通知] 发送通知: status={}, msg={}",
status, status,
error_msg error_msg

View File

@@ -75,9 +75,9 @@ impl Config {
} }
// 生成运行时配置 // 生成运行时配置
if let Err(err) = Self::generate().await { if let Err(err) = Self::generate().await {
logging!(error, Type::Config, true, "生成运行时配置失败: {}", err); logging!(error, Type::Config, "生成运行时配置失败: {}", err);
} else { } else {
logging!(info, Type::Config, true, "生成运行时配置成功"); logging!(info, Type::Config, "生成运行时配置成功");
} }
// 生成运行时配置文件并验证 // 生成运行时配置文件并验证
@@ -85,7 +85,7 @@ impl Config {
let validation_result = if config_result.is_ok() { let validation_result = if config_result.is_ok() {
// 验证配置文件 // 验证配置文件
logging!(info, Type::Config, true, "开始验证配置"); logging!(info, Type::Config, "开始验证配置");
match CoreManager::global().validate_config().await { match CoreManager::global().validate_config().await {
Ok((is_valid, error_msg)) => { Ok((is_valid, error_msg)) => {
@@ -93,7 +93,6 @@ impl Config {
logging!( logging!(
warn, warn,
Type::Config, Type::Config,
true,
"[首次启动] 配置验证失败,使用默认最小配置启动: {}", "[首次启动] 配置验证失败,使用默认最小配置启动: {}",
error_msg error_msg
); );
@@ -102,14 +101,14 @@ impl Config {
.await?; .await?;
Some(("config_validate::boot_error", error_msg)) Some(("config_validate::boot_error", error_msg))
} else { } else {
logging!(info, Type::Config, true, "配置验证成功"); logging!(info, Type::Config, "配置验证成功");
// 前端没有必要知道验证成功的消息,也没有事件驱动 // 前端没有必要知道验证成功的消息,也没有事件驱动
// Some(("config_validate::success", String::new())) // Some(("config_validate::success", String::new()))
None None
} }
} }
Err(err) => { Err(err) => {
logging!(warn, Type::Config, true, "验证程执行失败: {}", err); logging!(warn, Type::Config, "验证程执行失败: {}", err);
CoreManager::global() CoreManager::global()
.use_default_config("config_validate::process_terminated", "") .use_default_config("config_validate::process_terminated", "")
.await?; .await?;
@@ -117,7 +116,7 @@ impl Config {
} }
} }
} else { } else {
logging!(warn, Type::Config, true, "生成配置文件失败,使用默认配置"); logging!(warn, Type::Config, "生成配置文件失败,使用默认配置");
CoreManager::global() CoreManager::global()
.use_default_config("config_validate::error", "") .use_default_config("config_validate::error", "")
.await?; .await?;
@@ -167,12 +166,7 @@ impl Config {
} }
pub async fn verify_config_initialization() { pub async fn verify_config_initialization() {
logging!( logging!(info, Type::Setup, "Verifying config initialization...");
info,
Type::Setup,
true,
"Verifying config initialization..."
);
let backoff_strategy = ExponentialBackoff { let backoff_strategy = ExponentialBackoff {
initial_interval: std::time::Duration::from_millis(100), initial_interval: std::time::Duration::from_millis(100),
@@ -187,7 +181,6 @@ impl Config {
logging!( logging!(
info, info,
Type::Setup, Type::Setup,
true,
"Config initialization verified successfully" "Config initialization verified successfully"
); );
return Ok::<(), BackoffError<anyhow::Error>>(()); return Ok::<(), BackoffError<anyhow::Error>>(());
@@ -196,17 +189,16 @@ impl Config {
logging!( logging!(
warn, warn,
Type::Setup, Type::Setup,
true,
"Runtime config not found, attempting to regenerate..." "Runtime config not found, attempting to regenerate..."
); );
match Config::generate().await { match Config::generate().await {
Ok(_) => { Ok(_) => {
logging!(info, Type::Setup, true, "Config successfully regenerated"); logging!(info, Type::Setup, "Config successfully regenerated");
Ok(()) Ok(())
} }
Err(e) => { Err(e) => {
logging!(warn, Type::Setup, true, "Failed to generate config: {}", e); logging!(warn, Type::Setup, "Failed to generate config: {}", e);
Err(BackoffError::transient(e)) Err(BackoffError::transient(e))
} }
} }
@@ -217,7 +209,6 @@ impl Config {
logging!( logging!(
info, info,
Type::Setup, Type::Setup,
true,
"Config initialization verified with backoff retry" "Config initialization verified with backoff retry"
); );
} }
@@ -225,7 +216,6 @@ impl Config {
logging!( logging!(
error, error,
Type::Setup, Type::Setup,
true,
"Failed to verify config initialization after retries: {}", "Failed to verify config initialization after retries: {}",
e e
); );

View File

@@ -297,7 +297,6 @@ impl IProfiles {
if let Err(err) = result { if let Err(err) = result {
logging_error!( logging_error!(
Type::Config, Type::Config,
false,
"[配置文件删除] 删除文件 {} 失败: {}", "[配置文件删除] 删除文件 {} 失败: {}",
path.display(), path.display(),
err err
@@ -323,7 +322,6 @@ impl IProfiles {
if let Err(err) = result { if let Err(err) = result {
logging_error!( logging_error!(
Type::Config, Type::Config,
false,
"[配置文件删除] 删除文件 {} 失败: {}", "[配置文件删除] 删除文件 {} 失败: {}",
path.display(), path.display(),
err err
@@ -349,7 +347,6 @@ impl IProfiles {
if let Err(err) = result { if let Err(err) = result {
logging_error!( logging_error!(
Type::Config, Type::Config,
false,
"[配置文件删除] 删除文件 {} 失败: {}", "[配置文件删除] 删除文件 {} 失败: {}",
path.display(), path.display(),
err err
@@ -375,7 +372,6 @@ impl IProfiles {
if let Err(err) = result { if let Err(err) = result {
logging_error!( logging_error!(
Type::Config, Type::Config,
false,
"[配置文件删除] 删除文件 {} 失败: {}", "[配置文件删除] 删除文件 {} 失败: {}",
path.display(), path.display(),
err err
@@ -401,7 +397,6 @@ impl IProfiles {
if let Err(err) = result { if let Err(err) = result {
logging_error!( logging_error!(
Type::Config, Type::Config,
false,
"[配置文件删除] 删除文件 {} 失败: {}", "[配置文件删除] 删除文件 {} 失败: {}",
path.display(), path.display(),
err err
@@ -427,7 +422,6 @@ impl IProfiles {
if let Err(err) = result { if let Err(err) = result {
logging_error!( logging_error!(
Type::Config, Type::Config,
false,
"[配置文件删除] 删除文件 {} 失败: {}", "[配置文件删除] 删除文件 {} 失败: {}",
path.display(), path.display(),
err err

View File

@@ -255,7 +255,6 @@ impl IVerge {
logging!( logging!(
warn, warn,
Type::Config, Type::Config,
true,
"启动时发现无效的clash_core配置: '{}', 将自动修正为 'verge-mihomo'", "启动时发现无效的clash_core配置: '{}', 将自动修正为 'verge-mihomo'",
core core
); );
@@ -266,7 +265,6 @@ impl IVerge {
logging!( logging!(
info, info,
Type::Config, Type::Config,
true,
"启动时发现未配置clash_core, 将设置为默认值 'verge-mihomo'" "启动时发现未配置clash_core, 将设置为默认值 'verge-mihomo'"
); );
config.clash_core = Some("verge-mihomo".to_string()); config.clash_core = Some("verge-mihomo".to_string());
@@ -275,21 +273,15 @@ impl IVerge {
// 修正后保存配置 // 修正后保存配置
if needs_fix { if needs_fix {
logging!(info, Type::Config, true, "正在保存修正后的配置文件..."); logging!(info, Type::Config, "正在保存修正后的配置文件...");
help::save_yaml(&config_path, &config, Some("# Clash Verge Config")).await?; help::save_yaml(&config_path, &config, Some("# Clash Verge Config")).await?;
logging!( logging!(info, Type::Config, "配置文件修正完成,需要重新加载配置");
info,
Type::Config,
true,
"配置文件修正完成,需要重新加载配置"
);
Self::reload_config_after_fix(config).await?; Self::reload_config_after_fix(config).await?;
} else { } else {
logging!( logging!(
info, info,
Type::Config, Type::Config,
true,
"clash_core配置验证通过: {:?}", "clash_core配置验证通过: {:?}",
config.clash_core config.clash_core
); );
@@ -309,7 +301,6 @@ impl IVerge {
logging!( logging!(
info, info,
Type::Config, Type::Config,
true,
"内存配置已强制更新新的clash_core: {:?}", "内存配置已强制更新新的clash_core: {:?}",
updated_config.clash_core updated_config.clash_core
); );

View File

@@ -97,7 +97,6 @@ impl CoreManager {
logging!( logging!(
warn, warn,
Type::Config, Type::Config,
true,
"无法读取文件以检测类型: {}, 错误: {}", "无法读取文件以检测类型: {}, 错误: {}",
path, path,
err err
@@ -155,7 +154,6 @@ impl CoreManager {
logging!( logging!(
debug, debug,
Type::Config, Type::Config,
true,
"无法确定文件类型默认当作YAML处理: {}", "无法确定文件类型默认当作YAML处理: {}",
path path
); );
@@ -179,7 +177,7 @@ impl CoreManager {
} }
/// 验证运行时配置 /// 验证运行时配置
pub async fn validate_config(&self) -> Result<(bool, String)> { pub async fn validate_config(&self) -> Result<(bool, String)> {
logging!(info, Type::Config, true, "生成临时配置文件用于验证"); logging!(info, Type::Config, "生成临时配置文件用于验证");
let config_path = Config::generate_file(ConfigType::Check).await?; let config_path = Config::generate_file(ConfigType::Check).await?;
let config_path = dirs::path_to_str(&config_path)?; let config_path = dirs::path_to_str(&config_path)?;
self.validate_config_internal(config_path).await self.validate_config_internal(config_path).await
@@ -192,7 +190,7 @@ impl CoreManager {
) -> Result<(bool, String)> { ) -> Result<(bool, String)> {
// 检查程序是否正在退出,如果是则跳过验证 // 检查程序是否正在退出,如果是则跳过验证
if handle::Handle::global().is_exiting() { if handle::Handle::global().is_exiting() {
logging!(info, Type::Core, true, "应用正在退出,跳过验证"); logging!(info, Type::Core, "应用正在退出,跳过验证");
return Ok((true, String::new())); return Ok((true, String::new()));
} }
@@ -208,7 +206,6 @@ impl CoreManager {
logging!( logging!(
info, info,
Type::Config, Type::Config,
true,
"检测到Merge文件仅进行语法检查: {}", "检测到Merge文件仅进行语法检查: {}",
config_path config_path
); );
@@ -226,7 +223,6 @@ impl CoreManager {
logging!( logging!(
warn, warn,
Type::Config, Type::Config,
true,
"无法确定文件类型: {}, 错误: {}", "无法确定文件类型: {}, 错误: {}",
config_path, config_path,
err err
@@ -240,7 +236,6 @@ impl CoreManager {
logging!( logging!(
info, info,
Type::Config, Type::Config,
true,
"检测到脚本文件使用JavaScript验证: {}", "检测到脚本文件使用JavaScript验证: {}",
config_path config_path
); );
@@ -251,7 +246,6 @@ impl CoreManager {
logging!( logging!(
info, info,
Type::Config, Type::Config,
true,
"使用Clash内核验证配置文件: {}", "使用Clash内核验证配置文件: {}",
config_path config_path
); );
@@ -261,25 +255,19 @@ impl CoreManager {
async fn validate_config_internal(&self, config_path: &str) -> Result<(bool, String)> { async fn validate_config_internal(&self, config_path: &str) -> Result<(bool, String)> {
// 检查程序是否正在退出,如果是则跳过验证 // 检查程序是否正在退出,如果是则跳过验证
if handle::Handle::global().is_exiting() { if handle::Handle::global().is_exiting() {
logging!(info, Type::Core, true, "应用正在退出,跳过验证"); logging!(info, Type::Core, "应用正在退出,跳过验证");
return Ok((true, String::new())); return Ok((true, String::new()));
} }
logging!( logging!(info, Type::Config, "开始验证配置文件: {}", config_path);
info,
Type::Config,
true,
"开始验证配置文件: {}",
config_path
);
let clash_core = Config::verge().await.latest_ref().get_valid_clash_core(); let clash_core = Config::verge().await.latest_ref().get_valid_clash_core();
logging!(info, Type::Config, true, "使用内核: {}", clash_core); logging!(info, Type::Config, "使用内核: {}", clash_core);
let app_handle = handle::Handle::app_handle(); let app_handle = handle::Handle::app_handle();
let app_dir = dirs::app_home_dir()?; let app_dir = dirs::app_home_dir()?;
let app_dir_str = dirs::path_to_str(&app_dir)?; let app_dir_str = dirs::path_to_str(&app_dir)?;
logging!(info, Type::Config, true, "验证目录: {}", app_dir_str); logging!(info, Type::Config, "验证目录: {}", app_dir_str);
// 使用子进程运行clash验证配置 // 使用子进程运行clash验证配置
let output = app_handle let output = app_handle
@@ -297,14 +285,14 @@ impl CoreManager {
let has_error = let has_error =
!output.status.success() || error_keywords.iter().any(|&kw| stderr.contains(kw)); !output.status.success() || error_keywords.iter().any(|&kw| stderr.contains(kw));
logging!(info, Type::Config, true, "-------- 验证结果 --------"); logging!(info, Type::Config, "-------- 验证结果 --------");
if !stderr.is_empty() { if !stderr.is_empty() {
logging!(info, Type::Config, true, "stderr输出:\n{}", stderr); logging!(info, Type::Config, "stderr输出:\n{}", stderr);
} }
if has_error { if has_error {
logging!(info, Type::Config, true, "发现错误,开始处理错误信息"); logging!(info, Type::Config, "发现错误,开始处理错误信息");
let error_msg = if !stdout.is_empty() { let error_msg = if !stdout.is_empty() {
stdout.to_string() stdout.to_string()
} else if !stderr.is_empty() { } else if !stderr.is_empty() {
@@ -315,38 +303,38 @@ impl CoreManager {
"验证进程被终止".to_string() "验证进程被终止".to_string()
}; };
logging!(info, Type::Config, true, "-------- 验证结束 --------"); logging!(info, Type::Config, "-------- 验证结束 --------");
Ok((false, error_msg)) // 返回错误消息给调用者处理 Ok((false, error_msg)) // 返回错误消息给调用者处理
} else { } else {
logging!(info, Type::Config, true, "验证成功"); logging!(info, Type::Config, "验证成功");
logging!(info, Type::Config, true, "-------- 验证结束 --------"); logging!(info, Type::Config, "-------- 验证结束 --------");
Ok((true, String::new())) Ok((true, String::new()))
} }
} }
/// 只进行文件语法检查,不进行完整验证 /// 只进行文件语法检查,不进行完整验证
fn validate_file_syntax(&self, config_path: &str) -> Result<(bool, String)> { fn validate_file_syntax(&self, config_path: &str) -> Result<(bool, String)> {
logging!(info, Type::Config, true, "开始检查文件: {}", config_path); logging!(info, Type::Config, "开始检查文件: {}", config_path);
// 读取文件内容 // 读取文件内容
let content = match std::fs::read_to_string(config_path) { let content = match std::fs::read_to_string(config_path) {
Ok(content) => content, Ok(content) => content,
Err(err) => { Err(err) => {
let error_msg = format!("Failed to read file: {err}"); let error_msg = format!("Failed to read file: {err}");
logging!(error, Type::Config, true, "无法读取文件: {}", error_msg); logging!(error, Type::Config, "无法读取文件: {}", error_msg);
return Ok((false, error_msg)); return Ok((false, error_msg));
} }
}; };
// 对YAML文件尝试解析只检查语法正确性 // 对YAML文件尝试解析只检查语法正确性
logging!(info, Type::Config, true, "进行YAML语法检查"); logging!(info, Type::Config, "进行YAML语法检查");
match serde_yaml_ng::from_str::<serde_yaml_ng::Value>(&content) { match serde_yaml_ng::from_str::<serde_yaml_ng::Value>(&content) {
Ok(_) => { Ok(_) => {
logging!(info, Type::Config, true, "YAML语法检查通过"); logging!(info, Type::Config, "YAML语法检查通过");
Ok((true, String::new())) Ok((true, String::new()))
} }
Err(err) => { Err(err) => {
// 使用标准化的前缀,以便错误处理函数能正确识别 // 使用标准化的前缀,以便错误处理函数能正确识别
let error_msg = format!("YAML syntax error: {err}"); let error_msg = format!("YAML syntax error: {err}");
logging!(error, Type::Config, true, "YAML语法错误: {}", error_msg); logging!(error, Type::Config, "YAML语法错误: {}", error_msg);
Ok((false, error_msg)) Ok((false, error_msg))
} }
} }
@@ -358,13 +346,13 @@ impl CoreManager {
Ok(content) => content, Ok(content) => content,
Err(err) => { Err(err) => {
let error_msg = format!("Failed to read script file: {err}"); let error_msg = format!("Failed to read script file: {err}");
logging!(warn, Type::Config, true, "脚本语法错误: {}", err); logging!(warn, Type::Config, "脚本语法错误: {}", err);
//handle::Handle::notice_message("config_validate::script_syntax_error", &error_msg); //handle::Handle::notice_message("config_validate::script_syntax_error", &error_msg);
return Ok((false, error_msg)); return Ok((false, error_msg));
} }
}; };
logging!(debug, Type::Config, true, "验证脚本文件: {}", path); logging!(debug, Type::Config, "验证脚本文件: {}", path);
// 使用boa引擎进行基本语法检查 // 使用boa引擎进行基本语法检查
use boa_engine::{Context, Source}; use boa_engine::{Context, Source};
@@ -374,7 +362,7 @@ impl CoreManager {
match result { match result {
Ok(_) => { Ok(_) => {
logging!(debug, Type::Config, true, "脚本语法验证通过: {}", path); logging!(debug, Type::Config, "脚本语法验证通过: {}", path);
// 检查脚本是否包含main函数 // 检查脚本是否包含main函数
if !content.contains("function main") if !content.contains("function main")
@@ -382,7 +370,7 @@ impl CoreManager {
&& !content.contains("let main") && !content.contains("let main")
{ {
let error_msg = "Script must contain a main function"; let error_msg = "Script must contain a main function";
logging!(warn, Type::Config, true, "脚本缺少main函数: {}", path); logging!(warn, Type::Config, "脚本缺少main函数: {}", path);
//handle::Handle::notice_message("config_validate::script_missing_main", error_msg); //handle::Handle::notice_message("config_validate::script_missing_main", error_msg);
return Ok((false, error_msg.to_string())); return Ok((false, error_msg.to_string()));
} }
@@ -391,7 +379,7 @@ impl CoreManager {
} }
Err(err) => { Err(err) => {
let error_msg = format!("Script syntax error: {err}"); let error_msg = format!("Script syntax error: {err}");
logging!(warn, Type::Config, true, "脚本语法错误: {}", err); logging!(warn, Type::Config, "脚本语法错误: {}", err);
//handle::Handle::notice_message("config_validate::script_syntax_error", &error_msg); //handle::Handle::notice_message("config_validate::script_syntax_error", &error_msg);
Ok((false, error_msg)) Ok((false, error_msg))
} }
@@ -401,30 +389,30 @@ impl CoreManager {
pub async fn update_config(&self) -> Result<(bool, String)> { pub async fn update_config(&self) -> Result<(bool, String)> {
// 检查程序是否正在退出,如果是则跳过完整验证流程 // 检查程序是否正在退出,如果是则跳过完整验证流程
if handle::Handle::global().is_exiting() { if handle::Handle::global().is_exiting() {
logging!(info, Type::Config, true, "应用正在退出,跳过验证"); logging!(info, Type::Config, "应用正在退出,跳过验证");
return Ok((true, String::new())); return Ok((true, String::new()));
} }
// 1. 先生成新的配置内容 // 1. 先生成新的配置内容
logging!(info, Type::Config, true, "生成新的配置内容"); logging!(info, Type::Config, "生成新的配置内容");
Config::generate().await?; Config::generate().await?;
// 2. 验证配置 // 2. 验证配置
match self.validate_config().await { match self.validate_config().await {
Ok((true, _)) => { Ok((true, _)) => {
// 4. 验证通过后,生成正式的运行时配置 // 4. 验证通过后,生成正式的运行时配置
logging!(info, Type::Config, true, "配置验证通过, 生成运行时配置"); logging!(info, Type::Config, "配置验证通过, 生成运行时配置");
let run_path = Config::generate_file(ConfigType::Run).await?; let run_path = Config::generate_file(ConfigType::Run).await?;
logging_error!(Type::Config, true, self.put_configs_force(run_path).await); logging_error!(Type::Config, self.put_configs_force(run_path).await);
Ok((true, "something".into())) Ok((true, "something".into()))
} }
Ok((false, error_msg)) => { Ok((false, error_msg)) => {
logging!(warn, Type::Config, true, "配置验证失败: {}", error_msg); logging!(warn, Type::Config, "配置验证失败: {}", error_msg);
Config::runtime().await.discard(); Config::runtime().await.discard();
Ok((false, error_msg)) Ok((false, error_msg))
} }
Err(e) => { Err(e) => {
logging!(warn, Type::Config, true, "验证过程发生错误: {}", e); logging!(warn, Type::Config, "验证过程发生错误: {}", e);
Config::runtime().await.discard(); Config::runtime().await.discard();
Err(e) Err(e)
} }
@@ -433,7 +421,7 @@ impl CoreManager {
pub async fn put_configs_force(&self, path_buf: PathBuf) -> Result<(), String> { pub async fn put_configs_force(&self, path_buf: PathBuf) -> Result<(), String> {
let run_path_str = dirs::path_to_str(&path_buf).map_err(|e| { let run_path_str = dirs::path_to_str(&path_buf).map_err(|e| {
let msg = e.to_string(); let msg = e.to_string();
logging_error!(Type::Core, true, "{}", msg); logging_error!(Type::Core, "{}", msg);
msg msg
}); });
match handle::Handle::mihomo() match handle::Handle::mihomo()
@@ -443,13 +431,13 @@ impl CoreManager {
{ {
Ok(_) => { Ok(_) => {
Config::runtime().await.apply(); Config::runtime().await.apply();
logging!(info, Type::Core, true, "Configuration updated successfully"); logging!(info, Type::Core, "Configuration updated successfully");
Ok(()) Ok(())
} }
Err(e) => { Err(e) => {
let msg = e.to_string(); let msg = e.to_string();
Config::runtime().await.discard(); Config::runtime().await.discard();
logging_error!(Type::Core, true, "Failed to update configuration: {}", msg); logging_error!(Type::Core, "Failed to update configuration: {}", msg);
Err(msg) Err(msg)
} }
} }
@@ -459,7 +447,7 @@ impl CoreManager {
impl CoreManager { impl CoreManager {
/// 清理多余的 mihomo 进程 /// 清理多余的 mihomo 进程
async fn cleanup_orphaned_mihomo_processes(&self) -> Result<()> { async fn cleanup_orphaned_mihomo_processes(&self) -> Result<()> {
logging!(info, Type::Core, true, "开始清理多余的 mihomo 进程"); logging!(info, Type::Core, "开始清理多余的 mihomo 进程");
// 获取当前管理的进程 PID // 获取当前管理的进程 PID
let current_pid = { let current_pid = {
@@ -495,7 +483,6 @@ impl CoreManager {
logging!( logging!(
debug, debug,
Type::Core, Type::Core,
true,
"跳过当前管理的进程: {} (PID: {})", "跳过当前管理的进程: {} (PID: {})",
process_name, process_name,
pid pid
@@ -506,13 +493,13 @@ impl CoreManager {
} }
} }
Err(e) => { Err(e) => {
logging!(debug, Type::Core, true, "查找进程时发生错误: {}", e); logging!(debug, Type::Core, "查找进程时发生错误: {}", e);
} }
} }
} }
if pids_to_kill.is_empty() { if pids_to_kill.is_empty() {
logging!(debug, Type::Core, true, "未发现多余的 mihomo 进程"); logging!(debug, Type::Core, "未发现多余的 mihomo 进程");
return Ok(()); return Ok(());
} }
@@ -529,7 +516,6 @@ impl CoreManager {
logging!( logging!(
info, info,
Type::Core, Type::Core,
true,
"清理完成,共终止了 {} 个多余的 mihomo 进程", "清理完成,共终止了 {} 个多余的 mihomo 进程",
killed_count killed_count
); );
@@ -638,7 +624,6 @@ impl CoreManager {
logging!( logging!(
info, info,
Type::Core, Type::Core,
true,
"尝试终止进程: {} (PID: {})", "尝试终止进程: {} (PID: {})",
process_name, process_name,
pid pid
@@ -685,7 +670,6 @@ impl CoreManager {
logging!( logging!(
warn, warn,
Type::Core, Type::Core,
true,
"进程 {} (PID: {}) 终止命令成功但进程仍在运行", "进程 {} (PID: {}) 终止命令成功但进程仍在运行",
process_name, process_name,
pid pid
@@ -695,7 +679,6 @@ impl CoreManager {
logging!( logging!(
info, info,
Type::Core, Type::Core,
true,
"成功终止进程: {} (PID: {})", "成功终止进程: {} (PID: {})",
process_name, process_name,
pid pid
@@ -706,7 +689,6 @@ impl CoreManager {
logging!( logging!(
warn, warn,
Type::Core, Type::Core,
true,
"无法终止进程: {} (PID: {})", "无法终止进程: {} (PID: {})",
process_name, process_name,
pid pid
@@ -756,7 +738,7 @@ impl CoreManager {
} }
async fn start_core_by_sidecar(&self) -> Result<()> { async fn start_core_by_sidecar(&self) -> Result<()> {
logging!(info, Type::Core, true, "Running core by sidecar"); logging!(info, Type::Core, "Running core by sidecar");
let config_file = &Config::generate_file(ConfigType::Run).await?; let config_file = &Config::generate_file(ConfigType::Run).await?;
let app_handle = handle::Handle::app_handle(); let app_handle = handle::Handle::app_handle();
@@ -775,13 +757,7 @@ impl CoreManager {
.spawn()?; .spawn()?;
let pid = child.pid(); let pid = child.pid();
logging!( logging!(trace, Type::Core, "Started core by sidecar pid: {}", pid);
trace,
Type::Core,
true,
"Started core by sidecar pid: {}",
pid
);
*self.child_sidecar.lock() = Some(CommandChildGuard::new(child)); *self.child_sidecar.lock() = Some(CommandChildGuard::new(child));
self.set_running_mode(RunningMode::Sidecar); self.set_running_mode(RunningMode::Sidecar);
@@ -824,18 +800,12 @@ impl CoreManager {
Ok(()) Ok(())
} }
fn stop_core_by_sidecar(&self) -> Result<()> { fn stop_core_by_sidecar(&self) -> Result<()> {
logging!(info, Type::Core, true, "Stopping core by sidecar"); logging!(info, Type::Core, "Stopping core by sidecar");
if let Some(child) = self.child_sidecar.lock().take() { if let Some(child) = self.child_sidecar.lock().take() {
let pid = child.pid(); let pid = child.pid();
drop(child); drop(child);
logging!( logging!(trace, Type::Core, "Stopped core by sidecar pid: {:?}", pid);
trace,
Type::Core,
true,
"Stopped core by sidecar pid: {:?}",
pid
);
} }
self.set_running_mode(RunningMode::NotRunning); self.set_running_mode(RunningMode::NotRunning);
Ok(()) Ok(())
@@ -844,14 +814,14 @@ impl CoreManager {
impl CoreManager { impl CoreManager {
async fn start_core_by_service(&self) -> Result<()> { async fn start_core_by_service(&self) -> Result<()> {
logging!(info, Type::Core, true, "Running core by service"); logging!(info, Type::Core, "Running core by service");
let config_file = &Config::generate_file(ConfigType::Run).await?; let config_file = &Config::generate_file(ConfigType::Run).await?;
service::run_core_by_service(config_file).await?; service::run_core_by_service(config_file).await?;
self.set_running_mode(RunningMode::Service); self.set_running_mode(RunningMode::Service);
Ok(()) Ok(())
} }
async fn stop_core_by_service(&self) -> Result<()> { async fn stop_core_by_service(&self) -> Result<()> {
logging!(info, Type::Core, true, "Stopping core by service"); logging!(info, Type::Core, "Stopping core by service");
service::stop_core_by_service().await?; service::stop_core_by_service().await?;
self.set_running_mode(RunningMode::NotRunning); self.set_running_mode(RunningMode::NotRunning);
Ok(()) Ok(())
@@ -876,17 +846,16 @@ impl CoreManager {
logging!( logging!(
warn, warn,
Type::Core, Type::Core,
true,
"应用初始化时清理多余 mihomo 进程失败: {}", "应用初始化时清理多余 mihomo 进程失败: {}",
e e
); );
} }
// 使用简化的启动流程 // 使用简化的启动流程
logging!(info, Type::Core, true, "开始核心初始化"); logging!(info, Type::Core, "开始核心初始化");
self.start_core().await?; self.start_core().await?;
logging!(info, Type::Core, true, "核心初始化完成"); logging!(info, Type::Core, "核心初始化完成");
Ok(()) Ok(())
} }
@@ -919,10 +888,10 @@ impl CoreManager {
match self.get_running_mode() { match self.get_running_mode() {
RunningMode::Service => { RunningMode::Service => {
logging_error!(Type::Core, true, self.start_core_by_service().await); logging_error!(Type::Core, self.start_core_by_service().await);
} }
RunningMode::NotRunning | RunningMode::Sidecar => { RunningMode::NotRunning | RunningMode::Sidecar => {
logging_error!(Type::Core, true, self.start_core_by_sidecar().await); logging_error!(Type::Core, self.start_core_by_sidecar().await);
} }
}; };
@@ -941,7 +910,7 @@ impl CoreManager {
/// 重启内核 /// 重启内核
pub async fn restart_core(&self) -> Result<()> { pub async fn restart_core(&self) -> Result<()> {
logging!(info, Type::Core, true, "Restarting core"); logging!(info, Type::Core, "Restarting core");
self.stop_core().await?; self.stop_core().await?;
self.start_core().await?; self.start_core().await?;
Ok(()) Ok(())
@@ -951,17 +920,17 @@ impl CoreManager {
pub async fn change_core(&self, clash_core: Option<String>) -> Result<(), String> { pub async fn change_core(&self, clash_core: Option<String>) -> Result<(), String> {
if clash_core.is_none() { if clash_core.is_none() {
let error_message = "Clash core should not be Null"; let error_message = "Clash core should not be Null";
logging!(error, Type::Core, true, "{}", error_message); logging!(error, Type::Core, "{}", error_message);
return Err(error_message.to_string()); return Err(error_message.to_string());
} }
let core = clash_core.as_ref().ok_or_else(|| { let core = clash_core.as_ref().ok_or_else(|| {
let msg = "Clash core should not be None"; let msg = "Clash core should not be None";
logging!(error, Type::Core, true, "{}", msg); logging!(error, Type::Core, "{}", msg);
msg.to_string() msg.to_string()
})?; })?;
if !IVerge::VALID_CLASH_CORES.contains(&core.as_str()) { if !IVerge::VALID_CLASH_CORES.contains(&core.as_str()) {
let error_message = format!("Clash core invalid name: {core}"); let error_message = format!("Clash core invalid name: {core}");
logging!(error, Type::Core, true, "{}", error_message); logging!(error, Type::Core, "{}", error_message);
return Err(error_message); return Err(error_message);
} }
@@ -970,11 +939,11 @@ impl CoreManager {
// 分离数据获取和异步调用避免Send问题 // 分离数据获取和异步调用避免Send问题
let verge_data = Config::verge().await.latest_ref().clone(); let verge_data = Config::verge().await.latest_ref().clone();
logging_error!(Type::Core, true, verge_data.save_file().await); logging_error!(Type::Core, verge_data.save_file().await);
let run_path = Config::generate_file(ConfigType::Run).await.map_err(|e| { let run_path = Config::generate_file(ConfigType::Run).await.map_err(|e| {
let msg = e.to_string(); let msg = e.to_string();
logging_error!(Type::Core, true, "{}", msg); logging_error!(Type::Core, "{}", msg);
msg msg
})?; })?;

View File

@@ -401,8 +401,8 @@ impl EventDrivenProxyManager {
let disabled_sys = Sysproxy::default(); let disabled_sys = Sysproxy::default();
let disabled_auto = Autoproxy::default(); let disabled_auto = Autoproxy::default();
logging_error!(Type::System, true, disabled_auto.set_auto_proxy()); logging_error!(Type::System, disabled_auto.set_auto_proxy());
logging_error!(Type::System, true, disabled_sys.set_system_proxy()); logging_error!(Type::System, disabled_sys.set_system_proxy());
} }
} }
@@ -411,7 +411,7 @@ impl EventDrivenProxyManager {
if to_pac { if to_pac {
let disabled_sys = Sysproxy::default(); let disabled_sys = Sysproxy::default();
logging_error!(Type::System, true, disabled_sys.set_system_proxy()); logging_error!(Type::System, disabled_sys.set_system_proxy());
let expected = Self::get_expected_pac_config().await; let expected = Self::get_expected_pac_config().await;
if let Err(e) = Self::restore_pac_proxy(&expected.url).await { if let Err(e) = Self::restore_pac_proxy(&expected.url).await {
@@ -419,7 +419,7 @@ impl EventDrivenProxyManager {
} }
} else { } else {
let disabled_auto = Autoproxy::default(); let disabled_auto = Autoproxy::default();
logging_error!(Type::System, true, disabled_auto.set_auto_proxy()); logging_error!(Type::System, disabled_auto.set_auto_proxy());
let expected = Self::get_expected_sys_proxy().await; let expected = Self::get_expected_sys_proxy().await;
if let Err(e) = Self::restore_sys_proxy(&expected).await { if let Err(e) = Self::restore_sys_proxy(&expected).await {

View File

@@ -418,7 +418,6 @@ impl Handle {
logging!( logging!(
info, info,
Type::Frontend, Type::Frontend,
true,
"启动过程中发现错误,加入消息队列: {} - {}", "启动过程中发现错误,加入消息队列: {} - {}",
status_str, status_str,
msg_str msg_str
@@ -468,7 +467,6 @@ impl Handle {
logging!( logging!(
info, info,
Type::Frontend, Type::Frontend,
true,
"发送{}条启动时累积的错误消息: {:?}", "发送{}条启动时累积的错误消息: {:?}",
errors.len(), errors.len(),
errors errors
@@ -536,7 +534,6 @@ impl Handle {
logging!( logging!(
warn, warn,
Type::Setup, Type::Setup,
true,
"Failed to set regular activation policy: {}", "Failed to set regular activation policy: {}",
e e
); );
@@ -548,7 +545,6 @@ impl Handle {
logging!( logging!(
warn, warn,
Type::Setup, Type::Setup,
true,
"Failed to set accessory activation policy: {}", "Failed to set accessory activation policy: {}",
e e
); );
@@ -561,7 +557,6 @@ impl Handle {
logging!( logging!(
warn, warn,
Type::Setup, Type::Setup,
true,
"Failed to set prohibited activation policy: {}", "Failed to set prohibited activation policy: {}",
e e
); );

View File

@@ -294,7 +294,6 @@ impl Hotkey {
logging!( logging!(
debug, debug,
Type::Hotkey, Type::Hotkey,
true,
"Initializing global hotkeys: {}", "Initializing global hotkeys: {}",
enable_global_hotkey enable_global_hotkey
); );
@@ -310,7 +309,6 @@ impl Hotkey {
logging!( logging!(
debug, debug,
Type::Hotkey, Type::Hotkey,
true,
"Has {} hotkeys need to register", "Has {} hotkeys need to register",
hotkeys.len() hotkeys.len()
); );
@@ -325,7 +323,6 @@ impl Hotkey {
logging!( logging!(
debug, debug,
Type::Hotkey, Type::Hotkey,
true,
"Registering hotkey: {} -> {}", "Registering hotkey: {} -> {}",
key, key,
func func
@@ -334,7 +331,6 @@ impl Hotkey {
logging!( logging!(
error, error,
Type::Hotkey, Type::Hotkey,
true,
"Failed to register hotkey {} -> {}: {:?}", "Failed to register hotkey {} -> {}: {:?}",
key, key,
func, func,
@@ -356,7 +352,6 @@ impl Hotkey {
logging!( logging!(
error, error,
Type::Hotkey, Type::Hotkey,
true,
"Invalid hotkey configuration: `{}`:`{}`", "Invalid hotkey configuration: `{}`:`{}`",
key, key,
func func
@@ -467,7 +462,6 @@ impl Drop for Hotkey {
logging!( logging!(
error, error,
Type::Hotkey, Type::Hotkey,
true,
"Error unregistering all hotkeys: {:?}", "Error unregistering all hotkeys: {:?}",
e e
); );

View File

@@ -28,7 +28,7 @@ pub struct ServiceManager(ServiceStatus);
#[allow(clippy::unused_async)] #[allow(clippy::unused_async)]
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
async fn uninstall_service() -> Result<()> { async fn uninstall_service() -> Result<()> {
logging!(info, Type::Service, true, "uninstall service"); logging!(info, Type::Service, "uninstall service");
use deelevate::{PrivilegeLevel, Token}; use deelevate::{PrivilegeLevel, Token};
use runas::Command as RunasCommand; use runas::Command as RunasCommand;
@@ -63,7 +63,7 @@ async fn uninstall_service() -> Result<()> {
#[allow(clippy::unused_async)] #[allow(clippy::unused_async)]
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
async fn install_service() -> Result<()> { async fn install_service() -> Result<()> {
logging!(info, Type::Service, true, "install service"); logging!(info, Type::Service, "install service");
use deelevate::{PrivilegeLevel, Token}; use deelevate::{PrivilegeLevel, Token};
use runas::Command as RunasCommand; use runas::Command as RunasCommand;
@@ -97,17 +97,11 @@ async fn install_service() -> Result<()> {
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
async fn reinstall_service() -> Result<()> { async fn reinstall_service() -> Result<()> {
logging!(info, Type::Service, true, "reinstall service"); logging!(info, Type::Service, "reinstall service");
// 先卸载服务 // 先卸载服务
if let Err(err) = uninstall_service().await { if let Err(err) = uninstall_service().await {
logging!( logging!(warn, Type::Service, "failed to uninstall service: {}", err);
warn,
Type::Service,
true,
"failed to uninstall service: {}",
err
);
} }
// 再安装服务 // 再安装服务
@@ -122,7 +116,7 @@ async fn reinstall_service() -> Result<()> {
#[allow(clippy::unused_async)] #[allow(clippy::unused_async)]
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
async fn uninstall_service() -> Result<()> { async fn uninstall_service() -> Result<()> {
logging!(info, Type::Service, true, "uninstall service"); logging!(info, Type::Service, "uninstall service");
use users::get_effective_uid; use users::get_effective_uid;
let uninstall_path = tauri::utils::platform::current_exe()?.with_file_name("uninstall-service"); let uninstall_path = tauri::utils::platform::current_exe()?.with_file_name("uninstall-service");
@@ -145,7 +139,6 @@ async fn uninstall_service() -> Result<()> {
logging!( logging!(
info, info,
Type::Service, Type::Service,
true,
"uninstall status code:{}", "uninstall status code:{}",
status.code().unwrap_or(-1) status.code().unwrap_or(-1)
); );
@@ -163,7 +156,7 @@ async fn uninstall_service() -> Result<()> {
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
#[allow(clippy::unused_async)] #[allow(clippy::unused_async)]
async fn install_service() -> Result<()> { async fn install_service() -> Result<()> {
logging!(info, Type::Service, true, "install service"); logging!(info, Type::Service, "install service");
use users::get_effective_uid; use users::get_effective_uid;
let install_path = tauri::utils::platform::current_exe()?.with_file_name("install-service"); let install_path = tauri::utils::platform::current_exe()?.with_file_name("install-service");
@@ -186,7 +179,6 @@ async fn install_service() -> Result<()> {
logging!( logging!(
info, info,
Type::Service, Type::Service,
true,
"install status code:{}", "install status code:{}",
status.code().unwrap_or(-1) status.code().unwrap_or(-1)
); );
@@ -203,7 +195,7 @@ async fn install_service() -> Result<()> {
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
async fn reinstall_service() -> Result<()> { async fn reinstall_service() -> Result<()> {
logging!(info, Type::Service, true, "reinstall service"); logging!(info, Type::Service, "reinstall service");
// 先卸载服务 // 先卸载服务
if let Err(err) = uninstall_service().await { if let Err(err) = uninstall_service().await {
@@ -229,7 +221,7 @@ async fn reinstall_service() -> Result<()> {
async fn uninstall_service() -> Result<()> { async fn uninstall_service() -> Result<()> {
use crate::utils::i18n::t; use crate::utils::i18n::t;
logging!(info, Type::Service, true, "uninstall service"); logging!(info, Type::Service, "uninstall service");
let binary_path = dirs::service_path()?; let binary_path = dirs::service_path()?;
let uninstall_path = binary_path.with_file_name("uninstall-service"); let uninstall_path = binary_path.with_file_name("uninstall-service");
@@ -245,7 +237,7 @@ async fn uninstall_service() -> Result<()> {
r#"do shell script "sudo '{uninstall_shell}'" with administrator privileges with prompt "{prompt}""# r#"do shell script "sudo '{uninstall_shell}'" with administrator privileges with prompt "{prompt}""#
); );
// logging!(debug, Type::Service, true, "uninstall command: {}", command); // logging!(debug, Type::Service, "uninstall command: {}", command);
let status = StdCommand::new("osascript") let status = StdCommand::new("osascript")
.args(vec!["-e", &command]) .args(vec!["-e", &command])
@@ -265,7 +257,7 @@ async fn uninstall_service() -> Result<()> {
async fn install_service() -> Result<()> { async fn install_service() -> Result<()> {
use crate::utils::i18n::t; use crate::utils::i18n::t;
logging!(info, Type::Service, true, "install service"); logging!(info, Type::Service, "install service");
let binary_path = dirs::service_path()?; let binary_path = dirs::service_path()?;
let install_path = binary_path.with_file_name("install-service"); let install_path = binary_path.with_file_name("install-service");
@@ -281,7 +273,7 @@ async fn install_service() -> Result<()> {
r#"do shell script "sudo '{install_shell}'" with administrator privileges with prompt "{prompt}""# r#"do shell script "sudo '{install_shell}'" with administrator privileges with prompt "{prompt}""#
); );
// logging!(debug, Type::Service, true, "install command: {}", command); // logging!(debug, Type::Service, "install command: {}", command);
let status = StdCommand::new("osascript") let status = StdCommand::new("osascript")
.args(vec!["-e", &command]) .args(vec!["-e", &command])
@@ -299,17 +291,11 @@ async fn install_service() -> Result<()> {
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
async fn reinstall_service() -> Result<()> { async fn reinstall_service() -> Result<()> {
logging!(info, Type::Service, true, "reinstall service"); logging!(info, Type::Service, "reinstall service");
// 先卸载服务 // 先卸载服务
if let Err(err) = uninstall_service().await { if let Err(err) = uninstall_service().await {
logging!( logging!(warn, Type::Service, "failed to uninstall service: {}", err);
warn,
Type::Service,
true,
"failed to uninstall service: {}",
err
);
} }
// 再安装服务 // 再安装服务
@@ -323,9 +309,9 @@ async fn reinstall_service() -> Result<()> {
/// 强制重装服务UI修复按钮 /// 强制重装服务UI修复按钮
pub async fn force_reinstall_service() -> Result<()> { pub async fn force_reinstall_service() -> Result<()> {
logging!(info, Type::Service, true, "用户请求强制重装服务"); logging!(info, Type::Service, "用户请求强制重装服务");
reinstall_service().await.map_err(|err| { reinstall_service().await.map_err(|err| {
logging!(error, Type::Service, true, "强制重装服务失败: {}", err); logging!(error, Type::Service, "强制重装服务失败: {}", err);
err err
}) })
} }
@@ -333,7 +319,7 @@ pub async fn force_reinstall_service() -> Result<()> {
/// 检查服务版本 - 使用IPC通信 /// 检查服务版本 - 使用IPC通信
async fn check_service_version() -> Result<String> { async fn check_service_version() -> Result<String> {
let version_arc: Result<String> = { let version_arc: Result<String> = {
logging!(info, Type::Service, true, "开始检查服务版本 (IPC)"); logging!(info, Type::Service, "开始检查服务版本 (IPC)");
let payload = serde_json::json!({}); let payload = serde_json::json!({});
let response = send_ipc_request(IpcCommand::GetVersion, payload).await?; let response = send_ipc_request(IpcCommand::GetVersion, payload).await?;
@@ -367,7 +353,7 @@ pub async fn check_service_needs_reinstall() -> bool {
/// 尝试使用服务启动core /// 尝试使用服务启动core
pub(super) async fn start_with_existing_service(config_file: &PathBuf) -> Result<()> { pub(super) async fn start_with_existing_service(config_file: &PathBuf) -> Result<()> {
logging!(info, Type::Service, true, "尝试使用现有服务启动核心"); logging!(info, Type::Service, "尝试使用现有服务启动核心");
let verge_config = Config::verge().await; let verge_config = Config::verge().await;
let clash_core = verge_config.latest_ref().get_valid_clash_core(); let clash_core = verge_config.latest_ref().get_valid_clash_core();
@@ -405,25 +391,25 @@ pub(super) async fn start_with_existing_service(config_file: &PathBuf) -> Result
bail!("启动核心失败: {}", msg); bail!("启动核心失败: {}", msg);
} }
logging!(info, Type::Service, true, "服务成功启动核心"); logging!(info, Type::Service, "服务成功启动核心");
Ok(()) Ok(())
} }
// 以服务启动core // 以服务启动core
pub(super) async fn run_core_by_service(config_file: &PathBuf) -> Result<()> { pub(super) async fn run_core_by_service(config_file: &PathBuf) -> Result<()> {
logging!(info, Type::Service, true, "正在尝试通过服务启动核心"); logging!(info, Type::Service, "正在尝试通过服务启动核心");
if check_service_needs_reinstall().await { if check_service_needs_reinstall().await {
reinstall_service().await?; reinstall_service().await?;
} }
logging!(info, Type::Service, true, "服务已运行且版本匹配,直接使用"); logging!(info, Type::Service, "服务已运行且版本匹配,直接使用");
start_with_existing_service(config_file).await start_with_existing_service(config_file).await
} }
/// 通过服务停止core /// 通过服务停止core
pub(super) async fn stop_core_by_service() -> Result<()> { pub(super) async fn stop_core_by_service() -> Result<()> {
logging!(info, Type::Service, true, "通过服务停止核心 (IPC)"); logging!(info, Type::Service, "通过服务停止核心 (IPC)");
let payload = serde_json::json!({}); let payload = serde_json::json!({});
let response = send_ipc_request(IpcCommand::StopClash, payload) let response = send_ipc_request(IpcCommand::StopClash, payload)
@@ -432,7 +418,7 @@ pub(super) async fn stop_core_by_service() -> Result<()> {
if !response.success { if !response.success {
let err_msg = response.error.unwrap_or_else(|| "停止核心失败".to_string()); let err_msg = response.error.unwrap_or_else(|| "停止核心失败".to_string());
logging!(error, Type::Service, true, "停止核心失败: {}", err_msg); logging!(error, Type::Service, "停止核心失败: {}", err_msg);
bail!(err_msg); bail!(err_msg);
} }
@@ -449,7 +435,6 @@ pub(super) async fn stop_core_by_service() -> Result<()> {
logging!( logging!(
error, error,
Type::Service, Type::Service,
true,
"停止核心返回错误: code={}, msg={}", "停止核心返回错误: code={}, msg={}",
code_value, code_value,
msg msg
@@ -458,7 +443,7 @@ pub(super) async fn stop_core_by_service() -> Result<()> {
} }
} }
logging!(info, Type::Service, true, "服务成功停止核心"); logging!(info, Type::Service, "服务成功停止核心");
Ok(()) Ok(())
} }
@@ -479,11 +464,7 @@ impl ServiceManager {
pub async fn refresh(&mut self) -> Result<()> { pub async fn refresh(&mut self) -> Result<()> {
let status = self.check_service_comprehensive().await; let status = self.check_service_comprehensive().await;
logging_error!( logging_error!(Type::Service, self.handle_service_status(&status).await);
Type::Service,
true,
self.handle_service_status(&status).await
);
self.0 = status; self.0 = status;
Ok(()) Ok(())
} }
@@ -492,16 +473,16 @@ impl ServiceManager {
pub async fn check_service_comprehensive(&self) -> ServiceStatus { pub async fn check_service_comprehensive(&self) -> ServiceStatus {
match is_service_available().await { match is_service_available().await {
Ok(_) => { Ok(_) => {
logging!(info, Type::Service, true, "服务当前可用,检查是否需要重装"); logging!(info, Type::Service, "服务当前可用,检查是否需要重装");
if check_service_needs_reinstall().await { if check_service_needs_reinstall().await {
logging!(info, Type::Service, true, "服务需要重装且允许重装"); logging!(info, Type::Service, "服务需要重装且允许重装");
ServiceStatus::NeedsReinstall ServiceStatus::NeedsReinstall
} else { } else {
ServiceStatus::Ready ServiceStatus::Ready
} }
} }
Err(err) => { Err(err) => {
logging!(warn, Type::Service, true, "服务不可用,检查安装状态"); logging!(warn, Type::Service, "服务不可用,检查安装状态");
ServiceStatus::Unavailable(err.to_string()) ServiceStatus::Unavailable(err.to_string())
} }
} }
@@ -511,34 +492,29 @@ impl ServiceManager {
pub async fn handle_service_status(&mut self, status: &ServiceStatus) -> Result<()> { pub async fn handle_service_status(&mut self, status: &ServiceStatus) -> Result<()> {
match status { match status {
ServiceStatus::Ready => { ServiceStatus::Ready => {
logging!(info, Type::Service, true, "服务就绪,直接启动"); logging!(info, Type::Service, "服务就绪,直接启动");
Ok(()) Ok(())
} }
ServiceStatus::NeedsReinstall | ServiceStatus::ReinstallRequired => { ServiceStatus::NeedsReinstall | ServiceStatus::ReinstallRequired => {
logging!(info, Type::Service, true, "服务需要重装,执行重装流程"); logging!(info, Type::Service, "服务需要重装,执行重装流程");
reinstall_service().await?; reinstall_service().await?;
self.0 = ServiceStatus::Ready; self.0 = ServiceStatus::Ready;
Ok(()) Ok(())
} }
ServiceStatus::ForceReinstallRequired => { ServiceStatus::ForceReinstallRequired => {
logging!( logging!(info, Type::Service, "服务需要强制重装,执行强制重装流程");
info,
Type::Service,
true,
"服务需要强制重装,执行强制重装流程"
);
force_reinstall_service().await?; force_reinstall_service().await?;
self.0 = ServiceStatus::Ready; self.0 = ServiceStatus::Ready;
Ok(()) Ok(())
} }
ServiceStatus::InstallRequired => { ServiceStatus::InstallRequired => {
logging!(info, Type::Service, true, "需要安装服务,执行安装流程"); logging!(info, Type::Service, "需要安装服务,执行安装流程");
install_service().await?; install_service().await?;
self.0 = ServiceStatus::Ready; self.0 = ServiceStatus::Ready;
Ok(()) Ok(())
} }
ServiceStatus::UninstallRequired => { ServiceStatus::UninstallRequired => {
logging!(info, Type::Service, true, "服务需要卸载,执行卸载流程"); logging!(info, Type::Service, "服务需要卸载,执行卸载流程");
uninstall_service().await?; uninstall_service().await?;
self.0 = ServiceStatus::Unavailable("Service Uninstalled".into()); self.0 = ServiceStatus::Unavailable("Service Uninstalled".into());
Ok(()) Ok(())
@@ -547,7 +523,6 @@ impl ServiceManager {
logging!( logging!(
info, info,
Type::Service, Type::Service,
true,
"服务不可用: {}将使用Sidecar模式", "服务不可用: {}将使用Sidecar模式",
reason reason
); );

View File

@@ -139,7 +139,6 @@ pub async fn send_ipc_request(
logging!( logging!(
warn, warn,
Type::Service, Type::Service,
true,
"IPC请求失败准备重试: 命令={}, 错误={}", "IPC请求失败准备重试: 命令={}, 错误={}",
command_type, command_type,
e e
@@ -165,7 +164,6 @@ pub async fn send_ipc_request(
logging!( logging!(
error, error,
Type::Service, Type::Service,
true,
"IPC请求最终失败重试已耗尽: 命令={}, 错误={}", "IPC请求最终失败重试已耗尽: 命令={}, 错误={}",
command_type, command_type,
e e
@@ -204,12 +202,12 @@ async fn send_ipc_request_windows(
let mut pipe = match ClientOptions::new().open(IPC_SOCKET_NAME) { let mut pipe = match ClientOptions::new().open(IPC_SOCKET_NAME) {
Ok(p) => p, Ok(p) => p,
Err(e) => { Err(e) => {
logging!(error, Type::Service, true, "连接到服务命名管道失败: {}", e); logging!(error, Type::Service, "连接到服务命名管道失败: {}", e);
return Err(anyhow::anyhow!("无法连接到服务命名管道: {}", e)); return Err(anyhow::anyhow!("无法连接到服务命名管道: {}", e));
} }
}; };
logging!(info, Type::Service, true, "服务连接成功 (Windows)"); logging!(info, Type::Service, "服务连接成功 (Windows)");
pipe.write_all(&len_bytes).await?; pipe.write_all(&len_bytes).await?;
pipe.write_all(request_bytes).await?; pipe.write_all(request_bytes).await?;
@@ -226,7 +224,7 @@ async fn send_ipc_request_windows(
.map_err(|e| anyhow::anyhow!("解析响应失败: {}", e))?; .map_err(|e| anyhow::anyhow!("解析响应失败: {}", e))?;
if !verify_response_signature(&response)? { if !verify_response_signature(&response)? {
logging!(error, Type::Service, true, "服务响应签名验证失败"); logging!(error, Type::Service, "服务响应签名验证失败");
bail!("服务响应签名验证失败"); bail!("服务响应签名验证失败");
} }
@@ -245,7 +243,7 @@ async fn send_ipc_request_unix(
let mut stream = match UnixStream::connect(IPC_SOCKET_NAME).await { let mut stream = match UnixStream::connect(IPC_SOCKET_NAME).await {
Ok(s) => s, Ok(s) => s,
Err(e) => { Err(e) => {
logging!(error, Type::Service, true, "连接到Unix套接字失败: {}", e); logging!(error, Type::Service, "连接到Unix套接字失败: {}", e);
return Err(anyhow::anyhow!("无法连接到服务Unix套接字: {}", e)); return Err(anyhow::anyhow!("无法连接到服务Unix套接字: {}", e));
} }
}; };
@@ -269,7 +267,7 @@ async fn send_ipc_request_unix(
.map_err(|e| anyhow::anyhow!("解析响应失败: {}", e))?; .map_err(|e| anyhow::anyhow!("解析响应失败: {}", e))?;
if !verify_response_signature(&response)? { if !verify_response_signature(&response)? {
logging!(error, Type::Service, true, "服务响应签名验证失败"); logging!(error, Type::Service, "服务响应签名验证失败");
bail!("服务响应签名验证失败"); bail!("服务响应签名验证失败");
} }

View File

@@ -230,7 +230,12 @@ impl Sysopt {
pub async fn update_launch(&self) -> Result<()> { pub async fn update_launch(&self) -> Result<()> {
let enable_auto_launch = { Config::verge().await.latest_ref().enable_auto_launch }; let enable_auto_launch = { Config::verge().await.latest_ref().enable_auto_launch };
let is_enable = enable_auto_launch.unwrap_or(false); let is_enable = enable_auto_launch.unwrap_or(false);
logging!(info, true, "Setting auto-launch state to: {:?}", is_enable); logging!(
info,
Type::System,
"Setting auto-launch state to: {:?}",
is_enable
);
// 首先尝试使用快捷方式方法 // 首先尝试使用快捷方式方法
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
@@ -266,9 +271,9 @@ impl Sysopt {
let autostart_manager = app_handle.autolaunch(); let autostart_manager = app_handle.autolaunch();
if is_enable { if is_enable {
logging_error!(Type::System, true, "{:?}", autostart_manager.enable()); logging_error!(Type::System, "{:?}", autostart_manager.enable());
} else { } else {
logging_error!(Type::System, true, "{:?}", autostart_manager.disable()); logging_error!(Type::System, "{:?}", autostart_manager.disable());
} }
} }

View File

@@ -64,7 +64,7 @@ impl Timer {
if let Err(e) = self.refresh().await { if let Err(e) = self.refresh().await {
// Reset initialization flag on error // Reset initialization flag on error
self.initialized.store(false, Ordering::SeqCst); self.initialized.store(false, Ordering::SeqCst);
logging_error!(Type::Timer, false, "Failed to initialize timer: {}", e); logging_error!(Type::Timer, "Failed to initialize timer: {}", e);
return Err(e); return Err(e);
} }
@@ -501,7 +501,7 @@ impl Timer {
} }
}, },
Err(_) => { Err(_) => {
logging_error!(Type::Timer, false, "Timer task timed out for uid: {}", uid); logging_error!(Type::Timer, "Timer task timed out for uid: {}", uid);
} }
} }

View File

@@ -971,13 +971,7 @@ fn on_menu_event(_: &AppHandle, event: MenuEvent) {
match event.id.as_ref() { match event.id.as_ref() {
mode @ ("rule_mode" | "global_mode" | "direct_mode") => { mode @ ("rule_mode" | "global_mode" | "direct_mode") => {
let mode = &mode[0..mode.len() - 5]; // Removing the "_mode" suffix let mode = &mode[0..mode.len() - 5]; // Removing the "_mode" suffix
logging!( logging!(info, Type::ProxyMode, "Switch Proxy Mode To: {}", mode);
info,
Type::ProxyMode,
true,
"Switch Proxy Mode To: {}",
mode
);
feat::change_clash_mode(mode.into()).await; feat::change_clash_mode(mode.into()).await;
} }
"open_window" => { "open_window" => {

View File

@@ -75,7 +75,6 @@ pub async fn restore_webdav_backup(filename: String) -> Result<()> {
zip.extract(app_home_dir()?)?; zip.extract(app_home_dir()?)?;
logging_error!( logging_error!(
Type::Backup, Type::Backup,
true,
super::patch_verge( super::patch_verge(
IVerge { IVerge {
webdav_url, webdav_url,

View File

@@ -77,8 +77,8 @@ pub async fn change_clash_mode(mode: String) {
let clash_data = Config::clash().await.data_mut().clone(); let clash_data = Config::clash().await.data_mut().clone();
if clash_data.save_config().await.is_ok() { if clash_data.save_config().await.is_ok() {
handle::Handle::refresh_clash(); handle::Handle::refresh_clash();
logging_error!(Type::Tray, true, tray::Tray::global().update_menu().await); logging_error!(Type::Tray, tray::Tray::global().update_menu().await);
logging_error!(Type::Tray, true, tray::Tray::global().update_icon().await); logging_error!(Type::Tray, tray::Tray::global().update_icon().await);
} }
let is_auto_close_connection = Config::verge() let is_auto_close_connection = Config::verge()

View File

@@ -22,8 +22,8 @@ pub async fn patch_clash(patch: Mapping) -> Result<()> {
CoreManager::global().restart_core().await?; CoreManager::global().restart_core().await?;
} else { } else {
if patch.get("mode").is_some() { if patch.get("mode").is_some() {
logging_error!(Type::Tray, true, tray::Tray::global().update_menu().await); logging_error!(Type::Tray, tray::Tray::global().update_menu().await);
logging_error!(Type::Tray, true, tray::Tray::global().update_icon().await); logging_error!(Type::Tray, tray::Tray::global().update_icon().await);
} }
Config::runtime().await.draft_mut().patch_config(patch); Config::runtime().await.draft_mut().patch_config(patch);
CoreManager::global().update_config().await?; CoreManager::global().update_config().await?;

View File

@@ -13,7 +13,7 @@ pub async fn toggle_proxy_profile(profile_index: String) {
Ok(_) => { Ok(_) => {
let result = tray::Tray::global().update_menu().await; let result = tray::Tray::global().update_menu().await;
if let Err(err) = result { if let Err(err) = result {
logging!(error, Type::Tray, true, "更新菜单失败: {}", err); logging!(error, Type::Tray, "更新菜单失败: {}", err);
} }
} }
Err(err) => { Err(err) => {
@@ -30,7 +30,7 @@ pub async fn update_profile(
option: Option<PrfOption>, option: Option<PrfOption>,
auto_refresh: Option<bool>, auto_refresh: Option<bool>,
) -> Result<()> { ) -> Result<()> {
logging!(info, Type::Config, true, "[订阅更新] 开始更新订阅 {}", uid); logging!(info, Type::Config, "[订阅更新] 开始更新订阅 {}", uid);
let auto_refresh = auto_refresh.unwrap_or(true); // 默认为true保持兼容性 let auto_refresh = auto_refresh.unwrap_or(true); // 默认为true保持兼容性
let url_opt = { let url_opt = {
@@ -138,10 +138,10 @@ pub async fn update_profile(
}; };
if should_update { if should_update {
logging!(info, Type::Config, true, "[订阅更新] 更新内核配置"); logging!(info, Type::Config, "[订阅更新] 更新内核配置");
match CoreManager::global().update_config().await { match CoreManager::global().update_config().await {
Ok(_) => { Ok(_) => {
logging!(info, Type::Config, true, "[订阅更新] 更新成功"); logging!(info, Type::Config, "[订阅更新] 更新成功");
handle::Handle::refresh_clash(); handle::Handle::refresh_clash();
// if let Err(err) = cmd::proxy::force_refresh_proxies().await { // if let Err(err) = cmd::proxy::force_refresh_proxies().await {
// logging!( // logging!(
@@ -154,7 +154,7 @@ pub async fn update_profile(
// } // }
} }
Err(err) => { Err(err) => {
logging!(error, Type::Config, true, "[订阅更新] 更新失败: {}", err); logging!(error, Type::Config, "[订阅更新] 更新失败: {}", err);
handle::Handle::notice_message("update_failed", format!("{err}")); handle::Handle::notice_message("update_failed", format!("{err}"));
log::error!(target: "app", "{err}"); log::error!(target: "app", "{err}");
} }

View File

@@ -8,7 +8,7 @@ use crate::{
utils::logging::Type, utils::logging::Type,
}; };
/// Open or close the dashboard window /// Public API: open or close the dashboard
pub async fn open_or_close_dashboard() { pub async fn open_or_close_dashboard() {
open_or_close_dashboard_internal().await open_or_close_dashboard_internal().await
} }
@@ -21,7 +21,7 @@ async fn open_or_close_dashboard_internal() {
} }
pub async fn quit() { pub async fn quit() {
logging!(debug, Type::System, true, "启动退出流程"); logging!(debug, Type::System, "启动退出流程");
utils::server::shutdown_embedded_server(); utils::server::shutdown_embedded_server();
// 获取应用句柄并设置退出标志 // 获取应用句柄并设置退出标志
@@ -34,13 +34,12 @@ pub async fn quit() {
log::info!(target: "app", "窗口已隐藏"); log::info!(target: "app", "窗口已隐藏");
} }
logging!(info, Type::System, true, "开始异步清理资源"); logging!(info, Type::System, "开始异步清理资源");
let cleanup_result = clean_async().await; let cleanup_result = clean_async().await;
logging!( logging!(
info, info,
Type::System, Type::System,
true,
"资源清理完成,退出代码: {}", "资源清理完成,退出代码: {}",
if cleanup_result { 0 } else { 1 } if cleanup_result { 0 } else { 1 }
); );
@@ -50,7 +49,7 @@ pub async fn quit() {
async fn clean_async() -> bool { async fn clean_async() -> bool {
use tokio::time::{Duration, timeout}; use tokio::time::{Duration, timeout};
logging!(info, Type::System, true, "开始执行异步清理操作..."); logging!(info, Type::System, "开始执行异步清理操作...");
// 1. 处理TUN模式 // 1. 处理TUN模式
let tun_success = if Config::verge() let tun_success = if Config::verge()
@@ -255,7 +254,6 @@ async fn clean_async() -> bool {
logging!( logging!(
info, info,
Type::System, Type::System,
true,
"异步关闭操作完成 - TUN: {}, 代理: {}, 核心: {}, DNS: {}, 总体: {}", "异步关闭操作完成 - TUN: {}, 代理: {}, 核心: {}, DNS: {}, 总体: {}",
tun_success, tun_success,
proxy_success, proxy_success,
@@ -273,7 +271,7 @@ pub fn clean() -> bool {
let (tx, rx) = std::sync::mpsc::channel(); let (tx, rx) = std::sync::mpsc::channel();
AsyncHandler::spawn(move || async move { AsyncHandler::spawn(move || async move {
logging!(info, Type::System, true, "开始执行关闭操作..."); logging!(info, Type::System, "开始执行关闭操作...");
// 使用已有的异步清理函数 // 使用已有的异步清理函数
let cleanup_result = clean_async().await; let cleanup_result = clean_async().await;
@@ -288,14 +286,13 @@ pub fn clean() -> bool {
match rx.recv_timeout(total_timeout) { match rx.recv_timeout(total_timeout) {
Ok(result) => { Ok(result) => {
logging!(info, Type::System, true, "关闭操作完成,结果: {}", result); logging!(info, Type::System, "关闭操作完成,结果: {}", result);
result result
} }
Err(_) => { Err(_) => {
logging!( logging!(
warn, warn,
Type::System, Type::System,
true,
"清理操作超时(可能正在关机),返回成功避免阻塞" "清理操作超时(可能正在关机),返回成功避免阻塞"
); );
true true

View File

@@ -34,27 +34,22 @@ mod app_init {
/// Initialize singleton monitoring for other instances /// Initialize singleton monitoring for other instances
pub fn init_singleton_check() { pub fn init_singleton_check() {
AsyncHandler::spawn_blocking(move || async move { AsyncHandler::spawn_blocking(move || async move {
logging!(info, Type::Setup, true, "开始检查单例实例..."); logging!(info, Type::Setup, "开始检查单例实例...");
match timeout(Duration::from_millis(500), server::check_singleton()).await { match timeout(Duration::from_millis(500), server::check_singleton()).await {
Ok(result) => { Ok(result) => {
if result.is_err() { if result.is_err() {
logging!(info, Type::Setup, true, "检测到已有应用实例运行"); logging!(info, Type::Setup, "检测到已有应用实例运行");
if let Some(app_handle) = APP_HANDLE.get() { if let Some(app_handle) = APP_HANDLE.get() {
app_handle.exit(0); app_handle.exit(0);
} else { } else {
std::process::exit(0); std::process::exit(0);
} }
} else { } else {
logging!(info, Type::Setup, true, "未检测到其他应用实例"); logging!(info, Type::Setup, "未检测到其他应用实例");
} }
} }
Err(_) => { Err(_) => {
logging!( logging!(warn, Type::Setup, "单例检查超时,假定没有其他实例运行");
warn,
Type::Setup,
true,
"单例检查超时,假定没有其他实例运行"
);
} }
} }
}); });
@@ -94,7 +89,7 @@ mod app_init {
pub fn setup_deep_links(app: &tauri::App) -> Result<(), Box<dyn std::error::Error>> { pub fn setup_deep_links(app: &tauri::App) -> Result<(), Box<dyn std::error::Error>> {
#[cfg(any(target_os = "linux", all(debug_assertions, windows)))] #[cfg(any(target_os = "linux", all(debug_assertions, windows)))]
{ {
logging!(info, Type::Setup, true, "注册深层链接..."); logging!(info, Type::Setup, "注册深层链接...");
app.deep_link().register_all()?; app.deep_link().register_all()?;
} }
@@ -103,7 +98,7 @@ mod app_init {
if let Some(url) = url { if let Some(url) = url {
AsyncHandler::spawn(|| async { AsyncHandler::spawn(|| async {
if let Err(e) = resolve::resolve_scheme(url).await { if let Err(e) = resolve::resolve_scheme(url).await {
logging!(error, Type::Setup, true, "Failed to resolve scheme: {}", e); logging!(error, Type::Setup, "Failed to resolve scheme: {}", e);
} }
}); });
} }
@@ -131,7 +126,7 @@ mod app_init {
/// Setup window state management /// Setup window state management
pub fn setup_window_state(app: &tauri::App) -> Result<(), Box<dyn std::error::Error>> { pub fn setup_window_state(app: &tauri::App) -> Result<(), Box<dyn std::error::Error>> {
logging!(info, Type::Setup, true, "初始化窗口状态管理..."); logging!(info, Type::Setup, "初始化窗口状态管理...");
let window_state_plugin = tauri_plugin_window_state::Builder::new() let window_state_plugin = tauri_plugin_window_state::Builder::new()
.with_filename("window_state.json") .with_filename("window_state.json")
.with_state_flags(tauri_plugin_window_state::StateFlags::default()) .with_state_flags(tauri_plugin_window_state::StateFlags::default())
@@ -337,7 +332,7 @@ pub fn run() {
// Create and configure the Tauri builder // Create and configure the Tauri builder
let builder = app_init::setup_plugins(tauri::Builder::default()) let builder = app_init::setup_plugins(tauri::Builder::default())
.setup(|app| { .setup(|app| {
logging!(info, Type::Setup, true, "开始应用初始化..."); logging!(info, Type::Setup, "开始应用初始化...");
#[allow(clippy::expect_used)] #[allow(clippy::expect_used)]
APP_HANDLE APP_HANDLE
@@ -346,38 +341,26 @@ pub fn run() {
// Setup autostart plugin // Setup autostart plugin
if let Err(e) = app_init::setup_autostart(app) { if let Err(e) = app_init::setup_autostart(app) {
logging!(error, Type::Setup, true, "Failed to setup autostart: {}", e); logging!(error, Type::Setup, "Failed to setup autostart: {}", e);
} }
// Setup deep links // Setup deep links
if let Err(e) = app_init::setup_deep_links(app) { if let Err(e) = app_init::setup_deep_links(app) {
logging!( logging!(error, Type::Setup, "Failed to setup deep links: {}", e);
error,
Type::Setup,
true,
"Failed to setup deep links: {}",
e
);
} }
// Setup window state management // Setup window state management
if let Err(e) = app_init::setup_window_state(app) { if let Err(e) = app_init::setup_window_state(app) {
logging!( logging!(error, Type::Setup, "Failed to setup window state: {}", e);
error,
Type::Setup,
true,
"Failed to setup window state: {}",
e
);
} }
logging!(info, Type::Setup, true, "执行主要设置操作..."); logging!(info, Type::Setup, "执行主要设置操作...");
resolve::resolve_setup_handle(); resolve::resolve_setup_handle();
resolve::resolve_setup_async(); resolve::resolve_setup_async();
resolve::resolve_setup_sync(); resolve::resolve_setup_sync();
logging!(info, Type::Setup, true, "初始化完成,继续执行"); logging!(info, Type::Setup, "初始化完成,继续执行");
Ok(()) Ok(())
}) })
.invoke_handler(app_init::generate_handlers()); .invoke_handler(app_init::generate_handlers());
@@ -395,19 +378,18 @@ pub fn run() {
logging!( logging!(
debug, debug,
Type::System, Type::System,
true,
"handle_ready_resumed: 应用正在退出,跳过处理" "handle_ready_resumed: 应用正在退出,跳过处理"
); );
return; return;
} }
logging!(info, Type::System, true, "应用就绪或恢复"); logging!(info, Type::System, "应用就绪或恢复");
handle::Handle::global().init(); handle::Handle::global().init();
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
{ {
if let Some(window) = _app_handle.get_webview_window("main") { if let Some(window) = _app_handle.get_webview_window("main") {
logging!(info, Type::Window, true, "设置macOS窗口标题"); logging!(info, Type::Window, "设置macOS窗口标题");
let _ = window.set_title("Clash Verge"); let _ = window.set_title("Clash Verge");
} }
} }
@@ -419,7 +401,6 @@ pub fn run() {
logging!( logging!(
info, info,
Type::System, Type::System,
true,
"处理 macOS 应用重新打开事件: has_visible_windows={}", "处理 macOS 应用重新打开事件: has_visible_windows={}",
has_visible_windows has_visible_windows
); );
@@ -430,18 +411,12 @@ pub fn run() {
// 当没有可见窗口时,设置为 regular 模式并显示主窗口 // 当没有可见窗口时,设置为 regular 模式并显示主窗口
handle::Handle::global().set_activation_policy_regular(); handle::Handle::global().set_activation_policy_regular();
logging!(info, Type::System, true, "没有可见窗口,尝试显示主窗口"); logging!(info, Type::System, "没有可见窗口,尝试显示主窗口");
let result = WindowManager::show_main_window().await; let result = WindowManager::show_main_window().await;
logging!( logging!(info, Type::System, "窗口显示操作完成,结果: {:?}", result);
info,
Type::System,
true,
"窗口显示操作完成,结果: {:?}",
result
);
} else { } else {
logging!(info, Type::System, true, "已有可见窗口,无需额外操作"); logging!(info, Type::System, "已有可见窗口,无需额外操作");
} }
} }
@@ -460,7 +435,7 @@ pub fn run() {
if let Some(window) = core::handle::Handle::get_window() { if let Some(window) = core::handle::Handle::get_window() {
let _ = window.hide(); let _ = window.hide();
} else { } else {
logging!(warn, Type::Window, true, "尝试隐藏窗口但窗口不存在"); logging!(warn, Type::Window, "尝试隐藏窗口但窗口不存在");
} }
} }
} }
@@ -482,20 +457,20 @@ pub fn run() {
.register_system_hotkey(SystemHotkey::CmdQ) .register_system_hotkey(SystemHotkey::CmdQ)
.await .await
{ {
logging!(error, Type::Hotkey, true, "Failed to register CMD+Q: {}", e); logging!(error, Type::Hotkey, "Failed to register CMD+Q: {}", e);
} }
if let Err(e) = hotkey::Hotkey::global() if let Err(e) = hotkey::Hotkey::global()
.register_system_hotkey(SystemHotkey::CmdW) .register_system_hotkey(SystemHotkey::CmdW)
.await .await
{ {
logging!(error, Type::Hotkey, true, "Failed to register CMD+W: {}", e); logging!(error, Type::Hotkey, "Failed to register CMD+W: {}", e);
} }
} }
if !is_enable_global_hotkey if !is_enable_global_hotkey
&& let Err(e) = hotkey::Hotkey::global().init().await && let Err(e) = hotkey::Hotkey::global().init().await
{ {
logging!(error, Type::Hotkey, true, "Failed to init hotkeys: {}", e); logging!(error, Type::Hotkey, "Failed to init hotkeys: {}", e);
} }
return; return;
} }
@@ -507,29 +482,17 @@ pub fn run() {
if let Err(e) = if let Err(e) =
hotkey::Hotkey::global().unregister_system_hotkey(SystemHotkey::CmdQ) hotkey::Hotkey::global().unregister_system_hotkey(SystemHotkey::CmdQ)
{ {
logging!( logging!(error, Type::Hotkey, "Failed to unregister CMD+Q: {}", e);
error,
Type::Hotkey,
true,
"Failed to unregister CMD+Q: {}",
e
);
} }
if let Err(e) = if let Err(e) =
hotkey::Hotkey::global().unregister_system_hotkey(SystemHotkey::CmdW) hotkey::Hotkey::global().unregister_system_hotkey(SystemHotkey::CmdW)
{ {
logging!( logging!(error, Type::Hotkey, "Failed to unregister CMD+W: {}", e);
error,
Type::Hotkey,
true,
"Failed to unregister CMD+W: {}",
e
);
} }
} }
if !is_enable_global_hotkey && let Err(e) = hotkey::Hotkey::global().reset() { if !is_enable_global_hotkey && let Err(e) = hotkey::Hotkey::global().reset() {
logging!(error, Type::Hotkey, true, "Failed to reset hotkeys: {}", e); logging!(error, Type::Hotkey, "Failed to reset hotkeys: {}", e);
} }
}); });
} }
@@ -545,7 +508,6 @@ pub fn run() {
logging!( logging!(
error, error,
Type::Hotkey, Type::Hotkey,
true,
"Failed to unregister CMD+Q on destroy: {}", "Failed to unregister CMD+Q on destroy: {}",
e e
); );
@@ -556,7 +518,6 @@ pub fn run() {
logging!( logging!(
error, error,
Type::Hotkey, Type::Hotkey,
true,
"Failed to unregister CMD+W on destroy: {}", "Failed to unregister CMD+W on destroy: {}",
e e
); );
@@ -572,7 +533,6 @@ pub fn run() {
logging!( logging!(
error, error,
Type::Setup, Type::Setup,
true,
"Failed to build Tauri application: {}", "Failed to build Tauri application: {}",
e e
); );
@@ -584,12 +544,7 @@ pub fn run() {
tauri::RunEvent::Ready | tauri::RunEvent::Resumed => { tauri::RunEvent::Ready | tauri::RunEvent::Resumed => {
// 如果正在退出,忽略 Ready/Resumed 事件 // 如果正在退出,忽略 Ready/Resumed 事件
if core::handle::Handle::global().is_exiting() { if core::handle::Handle::global().is_exiting() {
logging!( logging!(debug, Type::System, "忽略 Ready/Resumed 事件,应用正在退出");
debug,
Type::System,
true,
"忽略 Ready/Resumed 事件,应用正在退出"
);
return; return;
} }
event_handlers::handle_ready_resumed(app_handle); event_handlers::handle_ready_resumed(app_handle);
@@ -601,7 +556,7 @@ pub fn run() {
} => { } => {
// 如果正在退出,忽略 Reopen 事件 // 如果正在退出,忽略 Reopen 事件
if core::handle::Handle::global().is_exiting() { if core::handle::Handle::global().is_exiting() {
logging!(debug, Type::System, true, "忽略 Reopen 事件,应用正在退出"); logging!(debug, Type::System, "忽略 Reopen 事件,应用正在退出");
return; return;
} }
AsyncHandler::spawn(move || async move { AsyncHandler::spawn(move || async move {
@@ -620,7 +575,6 @@ pub fn run() {
logging!( logging!(
info, info,
Type::System, Type::System,
true,
"应用正在退出,允许 ExitRequested (code: {:?})", "应用正在退出,允许 ExitRequested (code: {:?})",
code code
); );
@@ -629,7 +583,7 @@ pub fn run() {
// 只阻止外部的无退出码请求(如用户取消系统关机) // 只阻止外部的无退出码请求(如用户取消系统关机)
if code.is_none() { if code.is_none() {
logging!(debug, Type::System, true, "阻止外部退出请求"); logging!(debug, Type::System, "阻止外部退出请求");
api.prevent_exit(); api.prevent_exit();
} }
} }

View File

@@ -50,13 +50,13 @@ fn set_state(new: LightweightState) {
LIGHTWEIGHT_STATE.store(new.as_u8(), Ordering::Release); LIGHTWEIGHT_STATE.store(new.as_u8(), Ordering::Release);
match new { match new {
LightweightState::Normal => { LightweightState::Normal => {
logging!(info, Type::Lightweight, true, "轻量模式已关闭"); logging!(info, Type::Lightweight, "轻量模式已关闭");
} }
LightweightState::In => { LightweightState::In => {
logging!(info, Type::Lightweight, true, "轻量模式已开启"); logging!(info, Type::Lightweight, "轻量模式已开启");
} }
LightweightState::Exiting => { LightweightState::Exiting => {
logging!(info, Type::Lightweight, true, "正在退出轻量模式"); logging!(info, Type::Lightweight, "正在退出轻量模式");
} }
} }
} }
@@ -100,7 +100,6 @@ pub async fn run_once_auto_lightweight() {
logging!( logging!(
info, info,
Type::Lightweight, Type::Lightweight,
true,
"不满足静默启动且自动进入轻量模式的条件,跳过自动进入轻量模式" "不满足静默启动且自动进入轻量模式的条件,跳过自动进入轻量模式"
); );
return; return;
@@ -125,7 +124,6 @@ pub async fn auto_lightweight_mode_init() -> Result<()> {
logging!( logging!(
info, info,
Type::Lightweight, Type::Lightweight,
true,
"非静默启动直接挂载自动进入轻量模式监听器!" "非静默启动直接挂载自动进入轻量模式监听器!"
); );
set_state(LightweightState::Normal); set_state(LightweightState::Normal);
@@ -140,13 +138,13 @@ pub async fn enable_auto_light_weight_mode() {
logging!(error, Type::Lightweight, "Failed to initialize timer: {e}"); logging!(error, Type::Lightweight, "Failed to initialize timer: {e}");
return; return;
} }
logging!(info, Type::Lightweight, true, "开启自动轻量模式"); logging!(info, Type::Lightweight, "开启自动轻量模式");
setup_window_close_listener(); setup_window_close_listener();
setup_webview_focus_listener(); setup_webview_focus_listener();
} }
pub fn disable_auto_light_weight_mode() { pub fn disable_auto_light_weight_mode() {
logging!(info, Type::Lightweight, true, "关闭自动轻量模式"); logging!(info, Type::Lightweight, "关闭自动轻量模式");
let _ = cancel_light_weight_timer(); let _ = cancel_light_weight_timer();
cancel_window_close_listener(); cancel_window_close_listener();
cancel_webview_focus_listener(); cancel_webview_focus_listener();
@@ -163,7 +161,7 @@ pub async fn entry_lightweight_mode() -> bool {
) )
.is_err() .is_err()
{ {
logging!(info, Type::Lightweight, true, "无需进入轻量模式,跳过调用"); logging!(info, Type::Lightweight, "无需进入轻量模式,跳过调用");
return false; return false;
} }
@@ -193,7 +191,6 @@ pub async fn exit_lightweight_mode() -> bool {
logging!( logging!(
info, info,
Type::Lightweight, Type::Lightweight,
true,
"轻量模式不在退出条件(可能已退出或正在退出),跳过调用" "轻量模式不在退出条件(可能已退出或正在退出),跳过调用"
); );
return false; return false;
@@ -207,7 +204,7 @@ pub async fn exit_lightweight_mode() -> bool {
// 回到 Normal // 回到 Normal
set_state(LightweightState::Normal); set_state(LightweightState::Normal);
logging!(info, Type::Lightweight, true, "轻量模式退出完成"); logging!(info, Type::Lightweight, "轻量模式退出完成");
true true
} }
@@ -224,12 +221,7 @@ fn setup_window_close_listener() {
log::warn!("Failed to setup light weight timer: {e}"); log::warn!("Failed to setup light weight timer: {e}");
} }
})); }));
logging!( logging!(info, Type::Lightweight, "监听到关闭请求,开始轻量模式计时");
info,
Type::Lightweight,
true,
"监听到关闭请求,开始轻量模式计时"
);
}); });
WINDOW_CLOSE_HANDLER.store(handler, Ordering::Release); WINDOW_CLOSE_HANDLER.store(handler, Ordering::Release);
@@ -241,7 +233,7 @@ fn cancel_window_close_listener() {
let handler = WINDOW_CLOSE_HANDLER.swap(0, Ordering::AcqRel); let handler = WINDOW_CLOSE_HANDLER.swap(0, Ordering::AcqRel);
if handler != 0 { if handler != 0 {
window.unlisten(handler); window.unlisten(handler);
logging!(info, Type::Lightweight, true, "取消了窗口关闭监听"); logging!(info, Type::Lightweight, "取消了窗口关闭监听");
} }
} }
} }
@@ -266,7 +258,7 @@ fn cancel_webview_focus_listener() {
let handler = WEBVIEW_FOCUS_HANDLER.swap(0, Ordering::AcqRel); let handler = WEBVIEW_FOCUS_HANDLER.swap(0, Ordering::AcqRel);
if handler != 0 { if handler != 0 {
window.unlisten(handler); window.unlisten(handler);
logging!(info, Type::Lightweight, true, "取消了窗口焦点监听"); logging!(info, Type::Lightweight, "取消了窗口焦点监听");
} }
} }
} }
@@ -292,7 +284,7 @@ async fn setup_light_weight_timer() -> Result<()> {
.set_maximum_parallel_runnable_num(1) .set_maximum_parallel_runnable_num(1)
.set_frequency_once_by_minutes(once_by_minutes) .set_frequency_once_by_minutes(once_by_minutes)
.spawn_async_routine(move || async move { .spawn_async_routine(move || async move {
logging!(info, Type::Timer, true, "计时器到期,开始进入轻量模式"); logging!(info, Type::Timer, "计时器到期,开始进入轻量模式");
entry_lightweight_mode().await; entry_lightweight_mode().await;
}) })
.context("failed to create timer task")?; .context("failed to create timer task")?;
@@ -319,7 +311,6 @@ async fn setup_light_weight_timer() -> Result<()> {
logging!( logging!(
info, info,
Type::Timer, Type::Timer,
true,
"计时器已设置,{} 分钟后将自动进入轻量模式", "计时器已设置,{} 分钟后将自动进入轻量模式",
once_by_minutes once_by_minutes
); );
@@ -335,7 +326,7 @@ fn cancel_light_weight_timer() -> Result<()> {
delay_timer delay_timer
.remove_task(task.task_id) .remove_task(task.task_id)
.context("failed to remove timer task")?; .context("failed to remove timer task")?;
logging!(info, Type::Timer, true, "计时器已取消"); logging!(info, Type::Timer, "计时器已取消");
} }
Ok(()) Ok(())

View File

@@ -42,7 +42,7 @@ pub async fn read_mapping(path: &PathBuf) -> Result<Mapping> {
} }
Err(err) => { Err(err) => {
let error_msg = format!("YAML syntax error in {}: {}", path.display(), err); let error_msg = format!("YAML syntax error in {}: {}", path.display(), err);
logging!(error, Type::Config, true, "{}", error_msg); logging!(error, Type::Config, "{}", error_msg);
crate::core::handle::Handle::notice_message( crate::core::handle::Handle::notice_message(
"config_validate::yaml_syntax_error", "config_validate::yaml_syntax_error",

View File

@@ -136,13 +136,7 @@ pub async fn delete_log() -> Result<()> {
_ => return Ok(()), _ => return Ok(()),
}; };
logging!( logging!(info, Type::Setup, "try to delete log files, day: {}", day);
info,
Type::Setup,
true,
"try to delete log files, day: {}",
day
);
// %Y-%m-%d to NaiveDateTime // %Y-%m-%d to NaiveDateTime
let parse_time_str = |s: &str| { let parse_time_str = |s: &str| {
@@ -177,7 +171,7 @@ pub async fn delete_log() -> Result<()> {
if duration.num_days() > day { if duration.num_days() > day {
let file_path = file.path(); let file_path = file.path();
let _ = fs::remove_file(file_path).await; let _ = fs::remove_file(file_path).await;
logging!(info, Type::Setup, true, "delete log file: {}", file_name); logging!(info, Type::Setup, "delete log file: {}", file_name);
} }
} }
Ok(()) Ok(())
@@ -304,7 +298,7 @@ async fn init_dns_config() -> Result<()> {
let dns_path = app_dir.join("dns_config.yaml"); let dns_path = app_dir.join("dns_config.yaml");
if !dns_path.exists() { if !dns_path.exists() {
logging!(info, Type::Setup, true, "Creating default DNS config file"); logging!(info, Type::Setup, "Creating default DNS config file");
help::save_yaml( help::save_yaml(
&dns_path, &dns_path,
&default_dns_config, &default_dns_config,
@@ -329,14 +323,7 @@ async fn ensure_directories() -> Result<()> {
fs::create_dir_all(&dir).await.map_err(|e| { fs::create_dir_all(&dir).await.map_err(|e| {
anyhow::anyhow!("Failed to create {} directory {:?}: {}", name, dir, e) anyhow::anyhow!("Failed to create {} directory {:?}: {}", name, dir, e)
})?; })?;
logging!( logging!(info, Type::Setup, "Created {} directory: {:?}", name, dir);
info,
Type::Setup,
true,
"Created {} directory: {:?}",
name,
dir
);
} }
} }
@@ -352,13 +339,7 @@ async fn initialize_config_files() -> Result<()> {
help::save_yaml(&path, &template, Some("# Clash Verge")) help::save_yaml(&path, &template, Some("# Clash Verge"))
.await .await
.map_err(|e| anyhow::anyhow!("Failed to create clash config: {}", e))?; .map_err(|e| anyhow::anyhow!("Failed to create clash config: {}", e))?;
logging!( logging!(info, Type::Setup, "Created clash config at {:?}", path);
info,
Type::Setup,
true,
"Created clash config at {:?}",
path
);
} }
if let Ok(path) = dirs::verge_path() if let Ok(path) = dirs::verge_path()
@@ -368,13 +349,7 @@ async fn initialize_config_files() -> Result<()> {
help::save_yaml(&path, &template, Some("# Clash Verge")) help::save_yaml(&path, &template, Some("# Clash Verge"))
.await .await
.map_err(|e| anyhow::anyhow!("Failed to create verge config: {}", e))?; .map_err(|e| anyhow::anyhow!("Failed to create verge config: {}", e))?;
logging!( logging!(info, Type::Setup, "Created verge config at {:?}", path);
info,
Type::Setup,
true,
"Created verge config at {:?}",
path
);
} }
if let Ok(path) = dirs::profiles_path() if let Ok(path) = dirs::profiles_path()
@@ -384,13 +359,7 @@ async fn initialize_config_files() -> Result<()> {
help::save_yaml(&path, &template, Some("# Clash Verge")) help::save_yaml(&path, &template, Some("# Clash Verge"))
.await .await
.map_err(|e| anyhow::anyhow!("Failed to create profiles config: {}", e))?; .map_err(|e| anyhow::anyhow!("Failed to create profiles config: {}", e))?;
logging!( logging!(info, Type::Setup, "Created profiles config at {:?}", path);
info,
Type::Setup,
true,
"Created profiles config at {:?}",
path
);
} }
// 验证并修正verge配置 // 验证并修正verge配置
@@ -418,19 +387,13 @@ pub async fn init_config() -> Result<()> {
AsyncHandler::spawn(|| async { AsyncHandler::spawn(|| async {
if let Err(e) = delete_log().await { if let Err(e) = delete_log().await {
logging!(warn, Type::Setup, true, "Failed to clean old logs: {}", e); logging!(warn, Type::Setup, "Failed to clean old logs: {}", e);
} }
logging!(info, Type::Setup, true, "后台日志清理任务完成"); logging!(info, Type::Setup, "后台日志清理任务完成");
}); });
if let Err(e) = init_dns_config().await { if let Err(e) = init_dns_config().await {
logging!( logging!(warn, Type::Setup, "DNS config initialization failed: {}", e);
warn,
Type::Setup,
true,
"DNS config initialization failed: {}",
e
);
} }
Ok(()) Ok(())
@@ -460,13 +423,12 @@ pub async fn init_resources() -> Result<()> {
let handle_copy = |src: PathBuf, dest: PathBuf, file: String| async move { let handle_copy = |src: PathBuf, dest: PathBuf, file: String| async move {
match fs::copy(&src, &dest).await { match fs::copy(&src, &dest).await {
Ok(_) => { Ok(_) => {
logging!(debug, Type::Setup, true, "resources copied '{}'", file); logging!(debug, Type::Setup, "resources copied '{}'", file);
} }
Err(err) => { Err(err) => {
logging!( logging!(
error, error,
Type::Setup, Type::Setup,
true,
"failed to copy resources '{}' to '{:?}', {}", "failed to copy resources '{}' to '{:?}', {}",
file, file,
dest, dest,
@@ -491,13 +453,7 @@ pub async fn init_resources() -> Result<()> {
} }
} }
_ => { _ => {
logging!( logging!(debug, Type::Setup, "failed to get modified '{}'", file);
debug,
Type::Setup,
true,
"failed to get modified '{}'",
file
);
handle_copy(src_path.clone(), dest_path.clone(), file.to_string()).await; handle_copy(src_path.clone(), dest_path.clone(), file.to_string()).await;
} }
}; };

View File

@@ -113,18 +113,6 @@ macro_rules! wrap_err {
#[macro_export] #[macro_export]
macro_rules! logging { macro_rules! logging {
// 带 println 的版本(支持格式化参数)
($level:ident, $type:expr, true, $($arg:tt)*) => {
// We dont need println here anymore
// println!("{} {}", $type, format_args!($($arg)*));
log::$level!(target: "app", "{} {}", $type, format_args!($($arg)*));
};
// 带 println 的版本(使用 false 明确不打印)
($level:ident, $type:expr, false, $($arg:tt)*) => {
log::$level!(target: "app", "{} {}", $type, format_args!($($arg)*));
};
// 不带 print 参数的版本(默认不打印) // 不带 print 参数的版本(默认不打印)
($level:ident, $type:expr, $($arg:tt)*) => { ($level:ident, $type:expr, $($arg:tt)*) => {
log::$level!(target: "app", "{} {}", $type, format_args!($($arg)*)); log::$level!(target: "app", "{} {}", $type, format_args!($($arg)*));
@@ -133,37 +121,16 @@ macro_rules! logging {
#[macro_export] #[macro_export]
macro_rules! logging_error { macro_rules! logging_error {
// 1. 处理 Result<T, E>,带打印控制 // Handle Result<T, E>
($type:expr, $print:expr, $expr:expr) => {
match $expr {
Ok(_) => {},
Err(err) => {
if $print {
println!("[{}] Error: {}", $type, err);
}
log::error!(target: "app", "[{}] {}", $type, err);
}
}
};
// 2. 处理 Result<T, E>,默认不打印
($type:expr, $expr:expr) => { ($type:expr, $expr:expr) => {
if let Err(err) = $expr { if let Err(err) = $expr {
log::error!(target: "app", "[{}] {}", $type, err); log::error!(target: "app", "[{}] {}", $type, err);
} }
}; };
// 3. 处理格式化字符串,带打印控制 // Handle formatted message: always print to stdout and log as error
($type:expr, $print:expr, $fmt:literal $(, $arg:expr)*) => {
if $print {
println!("[{}] {}", $type, format_args!($fmt $(, $arg)*));
}
log::error!(target: "app", "[{}] {}", $type, format_args!($fmt $(, $arg)*));
};
// 4. 处理格式化字符串,不带 bool 时,默认 `false`
($type:expr, $fmt:literal $(, $arg:expr)*) => { ($type:expr, $fmt:literal $(, $arg:expr)*) => {
logging_error!($type, false, $fmt $(, $arg)*); log::error!(target: "app", "[{}] {}", $type, format_args!($fmt $(, $arg)*));
}; };
} }

View File

@@ -33,7 +33,6 @@ pub fn resolve_setup_async() {
logging!( logging!(
info, info,
Type::Setup, Type::Setup,
true,
"开始执行异步设置任务... 线程ID: {:?}", "开始执行异步设置任务... 线程ID: {:?}",
std::thread::current().id() std::thread::current().id()
); );
@@ -44,7 +43,6 @@ pub fn resolve_setup_async() {
logging!( logging!(
info, info,
Type::ClashVergeRev, Type::ClashVergeRev,
true,
"Version: {}", "Version: {}",
env!("CARGO_PKG_VERSION") env!("CARGO_PKG_VERSION")
); );
@@ -82,38 +80,26 @@ pub fn resolve_setup_async() {
}); });
let elapsed = start_time.elapsed(); let elapsed = start_time.elapsed();
logging!( logging!(info, Type::Setup, "异步设置任务完成,耗时: {:?}", elapsed);
info,
Type::Setup,
true,
"异步设置任务完成,耗时: {:?}",
elapsed
);
if elapsed.as_secs() > 10 { if elapsed.as_secs() > 10 {
logging!( logging!(warn, Type::Setup, "异步设置任务耗时较长({:?})", elapsed);
warn,
Type::Setup,
true,
"异步设置任务耗时较长({:?})",
elapsed
);
} }
} }
// 其它辅助函数不变 // 其它辅助函数不变
pub async fn resolve_reset_async() -> Result<(), anyhow::Error> { pub async fn resolve_reset_async() -> Result<(), anyhow::Error> {
logging!(info, Type::Tray, true, "Resetting system proxy"); logging!(info, Type::Tray, "Resetting system proxy");
sysopt::Sysopt::global().reset_sysproxy().await?; sysopt::Sysopt::global().reset_sysproxy().await?;
logging!(info, Type::Core, true, "Stopping core service"); logging!(info, Type::Core, "Stopping core service");
CoreManager::global().stop_core().await?; CoreManager::global().stop_core().await?;
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
{ {
use dns::restore_public_dns; use dns::restore_public_dns;
logging!(info, Type::System, true, "Restoring system DNS settings"); logging!(info, Type::System, "Restoring system DNS settings");
restore_public_dns().await; restore_public_dns().await;
} }
@@ -121,157 +107,116 @@ pub async fn resolve_reset_async() -> Result<(), anyhow::Error> {
} }
pub fn init_handle() { pub fn init_handle() {
logging!(info, Type::Setup, true, "Initializing app handle..."); logging!(info, Type::Setup, "Initializing app handle...");
handle::Handle::global().init(); handle::Handle::global().init();
} }
pub(super) fn init_scheme() { pub(super) fn init_scheme() {
logging!(info, Type::Setup, true, "Initializing custom URL scheme"); logging!(info, Type::Setup, "Initializing custom URL scheme");
logging_error!(Type::Setup, true, init::init_scheme()); logging_error!(Type::Setup, init::init_scheme());
} }
#[cfg(not(feature = "tauri-dev"))] #[cfg(not(feature = "tauri-dev"))]
pub(super) async fn resolve_setup_logger() { pub(super) async fn resolve_setup_logger() {
logging!(info, Type::Setup, true, "Initializing global logger..."); logging!(info, Type::Setup, "Initializing global logger...");
logging_error!(Type::Setup, true, init::init_logger().await); logging_error!(Type::Setup, init::init_logger().await);
} }
pub async fn resolve_scheme(param: String) -> Result<()> { pub async fn resolve_scheme(param: String) -> Result<()> {
logging!( logging!(info, Type::Setup, "Resolving scheme for param: {}", param);
info, logging_error!(Type::Setup, scheme::resolve_scheme(param).await);
Type::Setup,
true,
"Resolving scheme for param: {}",
param
);
logging_error!(Type::Setup, true, scheme::resolve_scheme(param).await);
Ok(()) Ok(())
} }
pub(super) fn init_embed_server() { pub(super) fn init_embed_server() {
logging!(info, Type::Setup, true, "Initializing embedded server..."); logging!(info, Type::Setup, "Initializing embedded server...");
server::embed_server(); server::embed_server();
} }
pub(super) async fn init_resources() { pub(super) async fn init_resources() {
logging!(info, Type::Setup, true, "Initializing resources..."); logging!(info, Type::Setup, "Initializing resources...");
logging_error!(Type::Setup, true, init::init_resources().await); logging_error!(Type::Setup, init::init_resources().await);
} }
pub(super) async fn init_startup_script() { pub(super) async fn init_startup_script() {
logging!(info, Type::Setup, true, "Initializing startup script"); logging!(info, Type::Setup, "Initializing startup script");
logging_error!(Type::Setup, true, init::startup_script().await); logging_error!(Type::Setup, init::startup_script().await);
} }
pub(super) async fn init_timer() { pub(super) async fn init_timer() {
logging!(info, Type::Setup, true, "Initializing timer..."); logging!(info, Type::Setup, "Initializing timer...");
logging_error!(Type::Setup, true, Timer::global().init().await); logging_error!(Type::Setup, Timer::global().init().await);
} }
pub(super) async fn init_hotkey() { pub(super) async fn init_hotkey() {
logging!(info, Type::Setup, true, "Initializing hotkey..."); logging!(info, Type::Setup, "Initializing hotkey...");
logging_error!(Type::Setup, true, Hotkey::global().init().await); logging_error!(Type::Setup, Hotkey::global().init().await);
} }
pub(super) async fn init_once_auto_lightweight() { pub(super) async fn init_once_auto_lightweight() {
logging!( logging!(
info, info,
Type::Lightweight, Type::Lightweight,
true,
"Running auto lightweight mode check..." "Running auto lightweight mode check..."
); );
run_once_auto_lightweight().await; run_once_auto_lightweight().await;
} }
pub(super) async fn init_auto_lightweight_mode() { pub(super) async fn init_auto_lightweight_mode() {
logging!( logging!(info, Type::Setup, "Initializing auto lightweight mode...");
info, logging_error!(Type::Setup, auto_lightweight_mode_init().await);
Type::Setup,
true,
"Initializing auto lightweight mode..."
);
logging_error!(Type::Setup, true, auto_lightweight_mode_init().await);
} }
pub async fn init_work_config() { pub async fn init_work_config() {
logging!( logging!(info, Type::Setup, "Initializing work configuration...");
info, logging_error!(Type::Setup, init::init_config().await);
Type::Setup,
true,
"Initializing work configuration..."
);
logging_error!(Type::Setup, true, init::init_config().await);
} }
pub(super) async fn init_tray() { pub(super) async fn init_tray() {
// Check if tray should be disabled via environment variable // Check if tray should be disabled via environment variable
if std::env::var("CLASH_VERGE_DISABLE_TRAY").unwrap_or_default() == "1" { if std::env::var("CLASH_VERGE_DISABLE_TRAY").unwrap_or_default() == "1" {
logging!( logging!(info, Type::Setup, "System tray disabled via --no-tray flag");
info,
Type::Setup,
true,
"System tray disabled via --no-tray flag"
);
return; return;
} }
logging!(info, Type::Setup, true, "Initializing system tray..."); logging!(info, Type::Setup, "Initializing system tray...");
logging_error!(Type::Setup, true, Tray::global().init().await); logging_error!(Type::Setup, Tray::global().init().await);
} }
pub(super) async fn init_verge_config() { pub(super) async fn init_verge_config() {
logging!( logging!(info, Type::Setup, "Initializing verge configuration...");
info, logging_error!(Type::Setup, Config::init_config().await);
Type::Setup,
true,
"Initializing verge configuration..."
);
logging_error!(Type::Setup, true, Config::init_config().await);
} }
pub(super) async fn init_service_manager() { pub(super) async fn init_service_manager() {
logging!(info, Type::Setup, true, "Initializing service manager..."); logging!(info, Type::Setup, "Initializing service manager...");
logging_error!( logging_error!(Type::Setup, SERVICE_MANAGER.lock().await.refresh().await);
Type::Setup,
true,
SERVICE_MANAGER.lock().await.refresh().await
);
} }
pub(super) async fn init_core_manager() { pub(super) async fn init_core_manager() {
logging!(info, Type::Setup, true, "Initializing core manager..."); logging!(info, Type::Setup, "Initializing core manager...");
logging_error!(Type::Setup, true, CoreManager::global().init().await); logging_error!(Type::Setup, CoreManager::global().init().await);
} }
pub(super) async fn init_system_proxy() { pub(super) async fn init_system_proxy() {
logging!(info, Type::Setup, true, "Initializing system proxy..."); logging!(info, Type::Setup, "Initializing system proxy...");
logging_error!( logging_error!(
Type::Setup, Type::Setup,
true,
sysopt::Sysopt::global().update_sysproxy().await sysopt::Sysopt::global().update_sysproxy().await
); );
} }
pub(super) fn init_system_proxy_guard() { pub(super) fn init_system_proxy_guard() {
logging!( logging!(info, Type::Setup, "Initializing system proxy guard...");
info, logging_error!(Type::Setup, sysopt::Sysopt::global().init_guard_sysproxy());
Type::Setup,
true,
"Initializing system proxy guard..."
);
logging_error!(
Type::Setup,
true,
sysopt::Sysopt::global().init_guard_sysproxy()
);
} }
pub(super) async fn refresh_tray_menu() { pub(super) async fn refresh_tray_menu() {
logging!(info, Type::Setup, true, "Refreshing tray menu..."); logging!(info, Type::Setup, "Refreshing tray menu...");
logging_error!(Type::Setup, true, Tray::global().update_part().await); logging_error!(Type::Setup, Tray::global().update_part().await);
} }
pub(super) async fn init_window() { pub(super) async fn init_window() {
logging!(info, Type::Setup, true, "Initializing main window..."); logging!(info, Type::Setup, "Initializing main window...");
let is_silent_start = let is_silent_start =
{ Config::verge().await.latest_ref().enable_silent_start }.unwrap_or(false); { Config::verge().await.latest_ref().enable_silent_start }.unwrap_or(false);
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]

View File

@@ -49,7 +49,7 @@ pub(super) async fn resolve_scheme(param: String) -> Result<()> {
let uid = match item.uid.clone() { let uid = match item.uid.clone() {
Some(uid) => uid, Some(uid) => uid,
None => { None => {
logging!(error, Type::Config, true, "Profile item missing UID"); logging!(error, Type::Config, "Profile item missing UID");
handle::Handle::notice_message( handle::Handle::notice_message(
"import_sub_url::error", "import_sub_url::error",
"Profile item missing UID".to_string(), "Profile item missing UID".to_string(),

View File

@@ -66,7 +66,7 @@ pub fn update_ui_ready_stage(stage: UiReadyStage) {
// 标记UI已准备就绪 // 标记UI已准备就绪
pub fn mark_ui_ready() { pub fn mark_ui_ready() {
get_ui_ready().store(true, Ordering::Release); get_ui_ready().store(true, Ordering::Release);
logging!(info, Type::Window, true, "UI已标记为完全就绪"); logging!(info, Type::Window, "UI已标记为完全就绪");
// 通知所有等待的任务 // 通知所有等待的任务
get_ui_ready_notify().notify_waiters(); get_ui_ready_notify().notify_waiters();

View File

@@ -37,7 +37,7 @@ pub fn build_new_window() -> Result<WebviewWindow, String> {
.build() .build()
{ {
Ok(window) => { Ok(window) => {
logging_error!(Type::Window, true, window.eval(INITIAL_LOADING_OVERLAY)); logging_error!(Type::Window, window.eval(INITIAL_LOADING_OVERLAY));
Ok(window) Ok(window)
} }
Err(e) => Err(e.to_string()), Err(e) => Err(e.to_string()),

View File

@@ -95,7 +95,7 @@ pub fn embed_server() {
// Spawn async work in a fire-and-forget manner // Spawn async work in a fire-and-forget manner
let param = query.param.clone(); let param = query.param.clone();
tokio::task::spawn_local(async move { tokio::task::spawn_local(async move {
logging_error!(Type::Setup, true, resolve::resolve_scheme(param).await); logging_error!(Type::Setup, resolve::resolve_scheme(param).await);
}); });
warp::reply::with_status("ok".to_string(), warp::http::StatusCode::OK) warp::reply::with_status("ok".to_string(), warp::http::StatusCode::OK)
}); });

View File

@@ -50,7 +50,6 @@ macro_rules! singleton_with_logging {
$crate::logging!( $crate::logging!(
info, info,
$crate::utils::logging::Type::Setup, $crate::utils::logging::Type::Setup,
true,
concat!($struct_name_str, " initialized") concat!($struct_name_str, " initialized")
); );
instance instance
@@ -88,7 +87,6 @@ macro_rules! singleton_lazy_with_logging {
$crate::logging!( $crate::logging!(
info, info,
$crate::utils::logging::Type::Setup, $crate::utils::logging::Type::Setup,
true,
concat!($struct_name_str, " initialized") concat!($struct_name_str, " initialized")
); );
instance instance

View File

@@ -131,43 +131,32 @@ impl WindowManager {
finish_window_operation(); finish_window_operation();
}); });
logging!(info, Type::Window, true, "开始智能显示主窗口"); logging!(info, Type::Window, "开始智能显示主窗口");
logging!( logging!(debug, Type::Window, "{}", Self::get_window_status_info());
debug,
Type::Window,
true,
"{}",
Self::get_window_status_info()
);
let current_state = Self::get_main_window_state(); let current_state = Self::get_main_window_state();
match current_state { match current_state {
WindowState::NotExist => { WindowState::NotExist => {
logging!(info, Type::Window, true, "窗口不存在,创建新窗口"); logging!(info, Type::Window, "窗口不存在,创建新窗口");
if Self::create_window(true).await { if Self::create_window(true).await {
logging!(info, Type::Window, true, "窗口创建成功"); logging!(info, Type::Window, "窗口创建成功");
std::thread::sleep(std::time::Duration::from_millis(100)); std::thread::sleep(std::time::Duration::from_millis(100));
WindowOperationResult::Created WindowOperationResult::Created
} else { } else {
logging!(warn, Type::Window, true, "窗口创建失败"); logging!(warn, Type::Window, "窗口创建失败");
WindowOperationResult::Failed WindowOperationResult::Failed
} }
} }
WindowState::VisibleFocused => { WindowState::VisibleFocused => {
logging!(info, Type::Window, true, "窗口已经可见且有焦点,无需操作"); logging!(info, Type::Window, "窗口已经可见且有焦点,无需操作");
WindowOperationResult::NoAction WindowOperationResult::NoAction
} }
WindowState::VisibleUnfocused | WindowState::Minimized | WindowState::Hidden => { WindowState::VisibleUnfocused | WindowState::Minimized | WindowState::Hidden => {
if let Some(window) = Self::get_main_window() { if let Some(window) = Self::get_main_window() {
let state_after_check = Self::get_main_window_state(); let state_after_check = Self::get_main_window_state();
if state_after_check == WindowState::VisibleFocused { if state_after_check == WindowState::VisibleFocused {
logging!( logging!(info, Type::Window, "窗口在检查期间已变为可见和有焦点状态");
info,
Type::Window,
true,
"窗口在检查期间已变为可见和有焦点状态"
);
return WindowOperationResult::NoAction; return WindowOperationResult::NoAction;
} }
Self::activate_window(&window) Self::activate_window(&window)
@@ -188,13 +177,12 @@ impl WindowManager {
finish_window_operation(); finish_window_operation();
}); });
logging!(info, Type::Window, true, "开始切换主窗口显示状态"); logging!(info, Type::Window, "开始切换主窗口显示状态");
let current_state = Self::get_main_window_state(); let current_state = Self::get_main_window_state();
logging!( logging!(
info, info,
Type::Window, Type::Window,
true,
"当前窗口状态: {:?} | 详细状态: {}", "当前窗口状态: {:?} | 详细状态: {}",
current_state, current_state,
Self::get_window_status_info() Self::get_window_status_info()
@@ -203,7 +191,7 @@ impl WindowManager {
match current_state { match current_state {
WindowState::NotExist => { WindowState::NotExist => {
// 窗口不存在,创建新窗口 // 窗口不存在,创建新窗口
logging!(info, Type::Window, true, "窗口不存在,将创建新窗口"); logging!(info, Type::Window, "窗口不存在,将创建新窗口");
// 由于已经有防抖保护,直接调用内部方法 // 由于已经有防抖保护,直接调用内部方法
if Self::create_window(true).await { if Self::create_window(true).await {
WindowOperationResult::Created WindowOperationResult::Created
@@ -215,7 +203,6 @@ impl WindowManager {
logging!( logging!(
info, info,
Type::Window, Type::Window,
true,
"窗口可见(焦点状态: {}),将隐藏窗口", "窗口可见(焦点状态: {}),将隐藏窗口",
if current_state == WindowState::VisibleFocused { if current_state == WindowState::VisibleFocused {
"有焦点" "有焦点"
@@ -226,30 +213,25 @@ impl WindowManager {
if let Some(window) = Self::get_main_window() { if let Some(window) = Self::get_main_window() {
match window.hide() { match window.hide() {
Ok(_) => { Ok(_) => {
logging!(info, Type::Window, true, "窗口已成功隐藏"); logging!(info, Type::Window, "窗口已成功隐藏");
WindowOperationResult::Hidden WindowOperationResult::Hidden
} }
Err(e) => { Err(e) => {
logging!(warn, Type::Window, true, "隐藏窗口失败: {}", e); logging!(warn, Type::Window, "隐藏窗口失败: {}", e);
WindowOperationResult::Failed WindowOperationResult::Failed
} }
} }
} else { } else {
logging!(warn, Type::Window, true, "无法获取窗口实例"); logging!(warn, Type::Window, "无法获取窗口实例");
WindowOperationResult::Failed WindowOperationResult::Failed
} }
} }
WindowState::Minimized | WindowState::Hidden => { WindowState::Minimized | WindowState::Hidden => {
logging!( logging!(info, Type::Window, "窗口存在但被隐藏或最小化,将激活窗口");
info,
Type::Window,
true,
"窗口存在但被隐藏或最小化,将激活窗口"
);
if let Some(window) = Self::get_main_window() { if let Some(window) = Self::get_main_window() {
Self::activate_window(&window) Self::activate_window(&window)
} else { } else {
logging!(warn, Type::Window, true, "无法获取窗口实例"); logging!(warn, Type::Window, "无法获取窗口实例");
WindowOperationResult::Failed WindowOperationResult::Failed
} }
} }
@@ -258,35 +240,35 @@ impl WindowManager {
/// 激活窗口(取消最小化、显示、设置焦点) /// 激活窗口(取消最小化、显示、设置焦点)
fn activate_window(window: &WebviewWindow<Wry>) -> WindowOperationResult { fn activate_window(window: &WebviewWindow<Wry>) -> WindowOperationResult {
logging!(info, Type::Window, true, "开始激活窗口"); logging!(info, Type::Window, "开始激活窗口");
let mut operations_successful = true; let mut operations_successful = true;
// 1. 如果窗口最小化,先取消最小化 // 1. 如果窗口最小化,先取消最小化
if window.is_minimized().unwrap_or(false) { if window.is_minimized().unwrap_or(false) {
logging!(info, Type::Window, true, "窗口已最小化,正在取消最小化"); logging!(info, Type::Window, "窗口已最小化,正在取消最小化");
if let Err(e) = window.unminimize() { if let Err(e) = window.unminimize() {
logging!(warn, Type::Window, true, "取消最小化失败: {}", e); logging!(warn, Type::Window, "取消最小化失败: {}", e);
operations_successful = false; operations_successful = false;
} }
} }
// 2. 显示窗口 // 2. 显示窗口
if let Err(e) = window.show() { if let Err(e) = window.show() {
logging!(warn, Type::Window, true, "显示窗口失败: {}", e); logging!(warn, Type::Window, "显示窗口失败: {}", e);
operations_successful = false; operations_successful = false;
} }
// 3. 设置焦点 // 3. 设置焦点
if let Err(e) = window.set_focus() { if let Err(e) = window.set_focus() {
logging!(warn, Type::Window, true, "设置窗口焦点失败: {}", e); logging!(warn, Type::Window, "设置窗口焦点失败: {}", e);
operations_successful = false; operations_successful = false;
} }
// 4. 平台特定的激活策略 // 4. 平台特定的激活策略
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
{ {
logging!(info, Type::Window, true, "应用 macOS 特定的激活策略"); logging!(info, Type::Window, "应用 macOS 特定的激活策略");
handle::Handle::global().set_activation_policy_regular(); handle::Handle::global().set_activation_policy_regular();
} }
@@ -294,31 +276,19 @@ impl WindowManager {
{ {
// Windows 尝试额外的激活方法 // Windows 尝试额外的激活方法
if let Err(e) = window.set_always_on_top(true) { if let Err(e) = window.set_always_on_top(true) {
logging!( logging!(debug, Type::Window, "设置置顶失败(非关键错误): {}", e);
debug,
Type::Window,
true,
"设置置顶失败(非关键错误): {}",
e
);
} }
// 立即取消置顶 // 立即取消置顶
if let Err(e) = window.set_always_on_top(false) { if let Err(e) = window.set_always_on_top(false) {
logging!( logging!(debug, Type::Window, "取消置顶失败(非关键错误): {}", e);
debug,
Type::Window,
true,
"取消置顶失败(非关键错误): {}",
e
);
} }
} }
if operations_successful { if operations_successful {
logging!(info, Type::Window, true, "窗口激活成功"); logging!(info, Type::Window, "窗口激活成功");
WindowOperationResult::Shown WindowOperationResult::Shown
} else { } else {
logging!(warn, Type::Window, true, "窗口激活部分失败"); logging!(warn, Type::Window, "窗口激活部分失败");
WindowOperationResult::Failed WindowOperationResult::Failed
} }
} }
@@ -350,7 +320,6 @@ impl WindowManager {
logging!( logging!(
info, info,
Type::Window, Type::Window,
true,
"开始创建/显示主窗口, is_show={}", "开始创建/显示主窗口, is_show={}",
is_show is_show
); );
@@ -361,10 +330,10 @@ impl WindowManager {
match build_new_window() { match build_new_window() {
Ok(_) => { Ok(_) => {
logging!(info, Type::Window, true, "新窗口创建成功"); logging!(info, Type::Window, "新窗口创建成功");
} }
Err(e) => { Err(e) => {
logging!(error, Type::Window, true, "新窗口创建失败: {}", e); logging!(error, Type::Window, "新窗口创建失败: {}", e);
return false; return false;
} }
} }
@@ -383,15 +352,15 @@ impl WindowManager {
pub fn destroy_main_window() -> WindowOperationResult { pub fn destroy_main_window() -> WindowOperationResult {
if let Some(window) = Self::get_main_window() { if let Some(window) = Self::get_main_window() {
let _ = window.destroy(); let _ = window.destroy();
logging!(info, Type::Window, true, "窗口已摧毁"); logging!(info, Type::Window, "窗口已摧毁");
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
{ {
logging!(info, Type::Window, true, "应用 macOS 特定的激活策略"); logging!(info, Type::Window, "应用 macOS 特定的激活策略");
handle::Handle::global().set_activation_policy_accessory(); handle::Handle::global().set_activation_policy_accessory();
} }
return WindowOperationResult::Destroyed; return WindowOperationResult::Destroyed;
} }
logging!(warn, Type::Window, true, "窗口摧毁失败"); logging!(warn, Type::Window, "窗口摧毁失败");
WindowOperationResult::Failed WindowOperationResult::Failed
} }