From c82f4e50d29e42ab3fdf6962e40b9acccdd7c6a3 Mon Sep 17 00:00:00 2001 From: vffuunnyy Date: Sat, 16 Aug 2025 01:56:56 +0700 Subject: [PATCH 1/5] feat: add compression support and fix tun config overwrite issue --- src-tauri/Cargo.lock | 17 +++++++++++++++++ src-tauri/Cargo.toml | 2 +- src-tauri/src/enhance/mod.rs | 4 +++- 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 9c8ecb9d..d7a504be 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -256,6 +256,22 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "async-compression" +version = "0.4.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddb939d66e4ae03cee6091612804ba446b12878410cfa17f785f4dd67d4014e8" +dependencies = [ + "brotli", + "flate2", + "futures-core", + "memchr", + "pin-project-lite", + "tokio", + "zstd", + "zstd-safe", +] + [[package]] name = "async-executor" version = "1.13.2" @@ -5853,6 +5869,7 @@ version = "0.12.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eabf4c97d9130e2bf606614eb937e86edac8292eaa6f422f995d7e8de1eb1813" dependencies = [ + "async-compression", "base64 0.22.1", "bytes", "cookie", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 43910d84..c1dbbd37 100755 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -45,7 +45,7 @@ tokio = { version = "1.45.1", features = [ "sync", ] } serde = { version = "1.0.219", features = ["derive"] } -reqwest = { version = "0.12.20", features = ["json", "rustls-tls", "cookies"] } +reqwest = { version = "0.12.20", features = ["json", "rustls-tls", "cookies", "brotli", "gzip", "zstd"] } regex = "1.11.1" sysproxy = { git = "https://github.com/clash-verge-rev/sysproxy-rs" } image = "0.25.6" diff --git a/src-tauri/src/enhance/mod.rs b/src-tauri/src/enhance/mod.rs index 000440c1..196f8f9d 100644 --- a/src-tauri/src/enhance/mod.rs +++ b/src-tauri/src/enhance/mod.rs @@ -202,7 +202,9 @@ pub async fn enhance() -> (Mapping, Vec, HashMap) { }); let patch_tun = value.as_mapping().cloned().unwrap_or(Mapping::new()); for (key, value) in patch_tun.into_iter() { - tun.insert(key, value); + if !tun.contains_key(&key) { + tun.insert(key, value); + } } config.insert("tun".into(), tun.into()); } else { From 902256d4611e15cec874479f7bdac1f02871d3bc Mon Sep 17 00:00:00 2001 From: vffuunnyy Date: Sat, 16 Aug 2025 04:00:00 +0700 Subject: [PATCH 2/5] refactor: translate Chinese log messages to English in core modules --- src-tauri/src/cmd/app.rs | 12 +- src-tauri/src/cmd/network.rs | 8 +- src-tauri/src/cmd/proxy.rs | 8 +- src-tauri/src/cmd/save_profile.rs | 8 +- src-tauri/src/config/profiles.rs | 10 +- src-tauri/src/core/async_proxy_query.rs | 26 ++-- src-tauri/src/core/backup.rs | 2 +- src-tauri/src/core/core.rs | 127 +++++++++--------- src-tauri/src/core/event_driven_proxy.rs | 70 +++++----- src-tauri/src/core/handle.rs | 4 +- src-tauri/src/core/service.rs | 162 ++++++++++++----------- src-tauri/src/core/service_ipc.rs | 40 +++--- src-tauri/src/core/sysopt.rs | 12 +- src-tauri/src/core/timer.rs | 39 +++--- src-tauri/src/core/tray/mod.rs | 42 +++--- src-tauri/src/feat/profile.rs | 28 ++-- src-tauri/src/feat/window.rs | 40 +++--- src-tauri/src/lib.rs | 34 ++--- src-tauri/src/state/lightweight.rs | 4 +- src-tauri/src/utils/autostart.rs | 24 ++-- src-tauri/src/utils/window_manager.rs | 8 +- 21 files changed, 356 insertions(+), 352 deletions(-) diff --git a/src-tauri/src/cmd/app.rs b/src-tauri/src/cmd/app.rs index f862dbe7..4a8a4637 100644 --- a/src-tauri/src/cmd/app.rs +++ b/src-tauri/src/cmd/app.rs @@ -147,7 +147,7 @@ pub async fn download_icon_cache(url: String, name: String) -> CmdResult Ok(icon_path.to_string_lossy().to_string()) } else { let _ = std::fs::remove_file(&temp_path); - Err(format!("下载的内容不是有效图片: {url}")) + Err(format!("Downloaded content is not a valid image: {url}")) } } @@ -209,7 +209,7 @@ pub fn copy_icon_file(path: String, icon_info: IconInfo) -> CmdResult { /// 通知UI已准备就绪 #[tauri::command] pub fn notify_ui_ready() -> CmdResult<()> { - log::info!(target: "app", "前端UI已准备就绪"); + log::info!(target: "app", "Frontend UI is ready"); crate::utils::resolve::mark_ui_ready(); Ok(()) } @@ -217,7 +217,7 @@ pub fn notify_ui_ready() -> CmdResult<()> { /// UI加载阶段 #[tauri::command] pub fn update_ui_stage(stage: String) -> CmdResult<()> { - log::info!(target: "app", "UI加载阶段更新: {stage}"); + log::info!(target: "app", "UI loading stage updated: {stage}"); use crate::utils::resolve::UiReadyStage; @@ -228,8 +228,8 @@ pub fn update_ui_stage(stage: String) -> CmdResult<()> { "ResourcesLoaded" => UiReadyStage::ResourcesLoaded, "Ready" => UiReadyStage::Ready, _ => { - log::warn!(target: "app", "未知的UI加载阶段: {stage}"); - return Err(format!("未知的UI加载阶段: {stage}")); + log::warn!(target: "app", "Unknown UI loading stage: {stage}"); + return Err(format!("Unknown UI loading stage: {stage}")); } }; @@ -240,7 +240,7 @@ pub fn update_ui_stage(stage: String) -> CmdResult<()> { /// 重置UI就绪状态 #[tauri::command] pub fn reset_ui_ready_state() -> CmdResult<()> { - log::info!(target: "app", "重置UI就绪状态"); + log::info!(target: "app", "Reset UI ready state"); crate::utils::resolve::reset_ui_ready(); Ok(()) } diff --git a/src-tauri/src/cmd/network.rs b/src-tauri/src/cmd/network.rs index 52f88eff..5888dd1c 100644 --- a/src-tauri/src/cmd/network.rs +++ b/src-tauri/src/cmd/network.rs @@ -7,7 +7,7 @@ use serde_yaml::Mapping; /// get the system proxy #[tauri::command] pub async fn get_sys_proxy() -> CmdResult { - log::debug!(target: "app", "异步获取系统代理配置"); + log::debug!(target: "app", "Asynchronously getting system proxy configuration"); let current = AsyncProxyQuery::get_system_proxy().await; @@ -19,14 +19,14 @@ pub async fn get_sys_proxy() -> CmdResult { ); map.insert("bypass".into(), current.bypass.into()); - log::debug!(target: "app", "返回系统代理配置: enable={}, {}:{}", current.enable, current.host, current.port); + log::debug!(target: "app", "Return system proxy configuration: enable={}, {}:{}", current.enable, current.host, current.port); Ok(map) } /// 获取自动代理配置 #[tauri::command] pub async fn get_auto_proxy() -> CmdResult { - log::debug!(target: "app", "开始获取自动代理配置(事件驱动)"); + log::debug!(target: "app", "Start retrieving auto proxy configuration (event-driven)"); let proxy_manager = EventDrivenProxyManager::global(); @@ -40,7 +40,7 @@ pub async fn get_auto_proxy() -> CmdResult { map.insert("enable".into(), current.enable.into()); map.insert("url".into(), current.url.clone().into()); - log::debug!(target: "app", "返回自动代理配置(缓存): enable={}, url={}", current.enable, current.url); + log::debug!(target: "app", "Return auto proxy configuration (cached): enable={}, url={}", current.enable, current.url); Ok(map) } diff --git a/src-tauri/src/cmd/proxy.rs b/src-tauri/src/cmd/proxy.rs index 48be7c2c..46548c0b 100644 --- a/src-tauri/src/cmd/proxy.rs +++ b/src-tauri/src/cmd/proxy.rs @@ -33,7 +33,7 @@ pub async fn get_proxies() -> CmdResult { state.proxies = Box::new(proxies); state.need_refresh = false; } - log::debug!(target: "app", "proxies刷新成功"); + log::debug!(target: "app", "Proxies refreshed successfully"); } let proxies = { @@ -50,7 +50,7 @@ pub async fn force_refresh_proxies() -> CmdResult { let app_handle = handle::Handle::global().app_handle().unwrap(); let cmd_proxy_state = app_handle.state::>(); - log::debug!(target: "app", "强制刷新代理缓存"); + log::debug!(target: "app", "Force refresh proxy cache"); let proxies = manager.get_refresh_proxies().await?; @@ -61,7 +61,7 @@ pub async fn force_refresh_proxies() -> CmdResult { state.last_refresh_time = Instant::now(); } - log::debug!(target: "app", "强制刷新代理缓存完成"); + log::debug!(target: "app", "Force refresh proxy cache completed"); Ok(proxies) } @@ -88,7 +88,7 @@ pub async fn get_providers_proxies() -> CmdResult { state.providers_proxies = Box::new(providers); state.need_refresh = false; } - log::debug!(target: "app", "providers_proxies刷新成功"); + log::debug!(target: "app", "providers_proxies refreshed successfully"); } let providers_proxies = { diff --git a/src-tauri/src/cmd/save_profile.rs b/src-tauri/src/cmd/save_profile.rs index 5e2b7bc1..5e85f18f 100644 --- a/src-tauri/src/cmd/save_profile.rs +++ b/src-tauri/src/cmd/save_profile.rs @@ -133,17 +133,17 @@ pub async fn save_profile_file(index: String, file_data: Option) -> CmdR || (!file_path_str.ends_with(".js") && !is_script_error) { // 普通YAML错误使用YAML通知处理 - log::info!(target: "app", "[cmd配置save] YAML配置文件验证失败,发送通知"); + log::info!(target: "app", "[cmd config save] YAML config file validation failed, sending notification"); let result = (false, error_msg.clone()); crate::cmd::validate::handle_yaml_validation_notice(&result, "YAML配置文件"); } else if is_script_error { // 脚本错误使用专门的通知处理 - log::info!(target: "app", "[cmd配置save] 脚本文件验证失败,发送通知"); + log::info!(target: "app", "[cmd config save] Script file validation failed, sending notification"); let result = (false, error_msg.clone()); crate::cmd::validate::handle_script_validation_notice(&result, "脚本文件"); } else { // 普通配置错误使用一般通知 - log::info!(target: "app", "[cmd配置save] 其他类型验证失败,发送一般通知"); + log::info!(target: "app", "[cmd config save] Other validation failure type, sending general notification"); handle::Handle::notice_message("config_validate::error", &error_msg); } @@ -154,7 +154,7 @@ pub async fn save_profile_file(index: String, file_data: Option) -> CmdR error, Type::Config, true, - "[cmd配置save] 验证过程发生错误: {}", + "[cmd config save] Error occurred during validation: {}", e ); // 恢复原始配置文件 diff --git a/src-tauri/src/config/profiles.rs b/src-tauri/src/config/profiles.rs index 17fb255c..348ab98c 100644 --- a/src-tauri/src/config/profiles.rs +++ b/src-tauri/src/config/profiles.rs @@ -536,7 +536,7 @@ impl IProfiles { if Self::is_profile_file(file_name) { // 检查是否为全局扩展文件 if protected_files.contains(file_name) { - log::debug!(target: "app", "保护全局扩展配置文件: {file_name}"); + log::debug!(target: "app", "Protect global extension config file: {file_name}"); continue; } @@ -545,11 +545,11 @@ impl IProfiles { match std::fs::remove_file(&path) { Ok(_) => { deleted_files.push(file_name.to_string()); - log::info!(target: "app", "已清理冗余文件: {file_name}"); + log::info!(target: "app", "Cleaned up redundant file: {file_name}"); } Err(e) => { failed_deletions.push(format!("{file_name}: {e}")); - log::warn!(target: "app", "清理文件失败: {file_name} - {e}"); + log::warn!(target: "app", "Failed to clean file: {file_name} - {e}"); } } } @@ -679,14 +679,14 @@ impl IProfiles { if !result.deleted_files.is_empty() { log::info!( target: "app", - "自动清理完成,删除了 {} 个冗余文件", + "Auto cleanup completed, deleted {} redundant files", result.deleted_files.len() ); } Ok(()) } Err(e) => { - log::warn!(target: "app", "自动清理失败: {e}"); + log::warn!(target: "app", "Auto cleanup failed: {e}"); Ok(()) } } diff --git a/src-tauri/src/core/async_proxy_query.rs b/src-tauri/src/core/async_proxy_query.rs index 788a6d26..485bec56 100644 --- a/src-tauri/src/core/async_proxy_query.rs +++ b/src-tauri/src/core/async_proxy_query.rs @@ -39,15 +39,15 @@ impl AsyncProxyQuery { pub async fn get_auto_proxy() -> AsyncAutoproxy { match timeout(Duration::from_secs(3), Self::get_auto_proxy_impl()).await { Ok(Ok(proxy)) => { - log::debug!(target: "app", "异步获取自动代理成功: enable={}, url={}", proxy.enable, proxy.url); + log::debug!(target: "app", "Async auto proxy fetch succeeded: enable={}, url={}", proxy.enable, proxy.url); proxy } Ok(Err(e)) => { - log::warn!(target: "app", "异步获取自动代理失败: {e}"); + log::warn!(target: "app", "Async auto proxy fetch failed: {e}"); AsyncAutoproxy::default() } Err(_) => { - log::warn!(target: "app", "异步获取自动代理超时"); + log::warn!(target: "app", "Async auto proxy fetch timed out"); AsyncAutoproxy::default() } } @@ -57,15 +57,15 @@ impl AsyncProxyQuery { pub async fn get_system_proxy() -> AsyncSysproxy { match timeout(Duration::from_secs(3), Self::get_system_proxy_impl()).await { Ok(Ok(proxy)) => { - log::debug!(target: "app", "异步获取系统代理成功: enable={}, {}:{}", proxy.enable, proxy.host, proxy.port); + log::debug!(target: "app", "Async system proxy fetch succeeded: enable={}, {}:{}", proxy.enable, proxy.host, proxy.port); proxy } Ok(Err(e)) => { - log::warn!(target: "app", "异步获取系统代理失败: {e}"); + log::warn!(target: "app", "Async system proxy fetch failed: {e}"); AsyncSysproxy::default() } Err(_) => { - log::warn!(target: "app", "异步获取系统代理超时"); + log::warn!(target: "app", "Async system proxy fetch timed out"); AsyncSysproxy::default() } } @@ -97,7 +97,7 @@ impl AsyncProxyQuery { RegOpenKeyExW(HKEY_CURRENT_USER, key_path.as_ptr(), 0, KEY_READ, &mut hkey); if result != 0 { - log::debug!(target: "app", "无法打开注册表项"); + log::debug!(target: "app", "Unable to open registry key"); return Ok(AsyncAutoproxy::default()); } @@ -123,7 +123,7 @@ impl AsyncProxyQuery { .position(|&x| x == 0) .unwrap_or(url_buffer.len()); pac_url = String::from_utf16_lossy(&url_buffer[..end_pos]); - log::debug!(target: "app", "从注册表读取到PAC URL: {}", pac_url); + log::debug!(target: "app", "Read PAC URL from registry: {}", pac_url); } // 2. 检查自动检测设置是否启用 @@ -148,7 +148,7 @@ impl AsyncProxyQuery { || (detect_query_result == 0 && detect_value_type == REG_DWORD && auto_detect != 0); if pac_enabled { - log::debug!(target: "app", "PAC配置启用: URL={}, AutoDetect={}", pac_url, auto_detect); + log::debug!(target: "app", "PAC configuration enabled: URL={}, AutoDetect={}", pac_url, auto_detect); if pac_url.is_empty() && auto_detect != 0 { pac_url = "auto-detect".to_string(); @@ -159,7 +159,7 @@ impl AsyncProxyQuery { url: pac_url, }) } else { - log::debug!(target: "app", "PAC配置未启用"); + log::debug!(target: "app", "PAC configuration not enabled"); Ok(AsyncAutoproxy::default()) } } @@ -194,7 +194,7 @@ impl AsyncProxyQuery { } } - log::debug!(target: "app", "解析结果: pac_enabled={pac_enabled}, pac_url={pac_url}"); + log::debug!(target: "app", "Parse result: pac_enabled={pac_enabled}, pac_url={pac_url}"); Ok(AsyncAutoproxy { enable: pac_enabled && !pac_url.is_empty(), @@ -361,7 +361,7 @@ impl AsyncProxyQuery { (proxy_server, 8080) }; - log::debug!(target: "app", "从注册表读取到代理设置: {}:{}, bypass: {}", host, port, bypass_list); + log::debug!(target: "app", "Read proxy settings from registry: {}:{}, bypass: {}", host, port, bypass_list); Ok(AsyncSysproxy { enable: true, @@ -518,7 +518,7 @@ impl AsyncProxyQuery { }; if host.is_empty() { - return Err(anyhow!("无效的代理URL")); + return Err(anyhow!("Invalid proxy URL")); } Ok(AsyncSysproxy { diff --git a/src-tauri/src/core/backup.rs b/src-tauri/src/core/backup.rs index da892fa4..4470f7c6 100644 --- a/src-tauri/src/core/backup.rs +++ b/src-tauri/src/core/backup.rs @@ -112,7 +112,7 @@ impl WebDavClient { .redirect(reqwest::redirect::Policy::custom(|attempt| { // 允许所有请求类型的重定向,包括PUT if attempt.previous().len() >= 5 { - attempt.error("重定向次数过多") + attempt.error("Too many redirects") } else { attempt.follow() } diff --git a/src-tauri/src/core/core.rs b/src-tauri/src/core/core.rs index 79e37af6..3ce526ce 100644 --- a/src-tauri/src/core/core.rs +++ b/src-tauri/src/core/core.rs @@ -72,7 +72,7 @@ impl CoreManager { warn, Type::Config, true, - "无法读取文件以检测类型: {}, 错误: {}", + "Failed to read file to detect type: {}, error: {}", path, err ); @@ -130,7 +130,7 @@ impl CoreManager { debug, Type::Config, true, - "无法确定文件类型,默认当作YAML处理: {}", + "Unable to determine file type, defaulting to YAML handling: {}", path ); Ok(false) @@ -153,7 +153,7 @@ impl CoreManager { } /// 验证运行时配置 pub async fn validate_config(&self) -> Result<(bool, String)> { - logging!(info, Type::Config, true, "生成临时配置文件用于验证"); + logging!(info, Type::Config, true, "Generate temporary config file for validation"); let config_path = Config::generate_file(ConfigType::Check)?; let config_path = dirs::path_to_str(&config_path)?; self.validate_config_internal(config_path).await @@ -166,7 +166,7 @@ impl CoreManager { ) -> Result<(bool, String)> { // 检查程序是否正在退出,如果是则跳过验证 if handle::Handle::global().is_exiting() { - logging!(info, Type::Core, true, "应用正在退出,跳过验证"); + logging!(info, Type::Core, true, "App is exiting, skipping validation"); return Ok((true, String::new())); } @@ -183,7 +183,7 @@ impl CoreManager { info, Type::Config, true, - "检测到Merge文件,仅进行语法检查: {}", + "Detected merge file, performing syntax check only: {}", config_path ); return self.validate_file_syntax(config_path).await; @@ -201,7 +201,7 @@ impl CoreManager { warn, Type::Config, true, - "无法确定文件类型: {}, 错误: {}", + "Unable to determine file type: {}, error: {}", config_path, err ); @@ -215,7 +215,7 @@ impl CoreManager { info, Type::Config, true, - "检测到脚本文件,使用JavaScript验证: {}", + "Detected script file, validating with JavaScript: {}", config_path ); return self.validate_script_file(config_path).await; @@ -226,7 +226,7 @@ impl CoreManager { info, Type::Config, true, - "使用Clash内核验证配置文件: {}", + "Validating config file with Clash core: {}", config_path ); self.validate_config_internal(config_path).await @@ -235,7 +235,7 @@ impl CoreManager { async fn validate_config_internal(&self, config_path: &str) -> Result<(bool, String)> { // 检查程序是否正在退出,如果是则跳过验证 if handle::Handle::global().is_exiting() { - logging!(info, Type::Core, true, "应用正在退出,跳过验证"); + logging!(info, Type::Core, true, "App is exiting, skipping validation"); return Ok((true, String::new())); } @@ -243,17 +243,17 @@ impl CoreManager { info, Type::Config, true, - "开始验证配置文件: {}", + "Starting validation for config file: {}", config_path ); let clash_core = Config::verge().latest().get_valid_clash_core(); - logging!(info, Type::Config, true, "使用内核: {}", clash_core); + logging!(info, Type::Config, true, "Using core: {}", clash_core); let app_handle = handle::Handle::global().app_handle().unwrap(); let app_dir = dirs::app_home_dir()?; let app_dir_str = dirs::path_to_str(&app_dir)?; - logging!(info, Type::Config, true, "验证目录: {}", app_dir_str); + logging!(info, Type::Config, true, "Validation directory: {}", app_dir_str); // 使用子进程运行clash验证配置 let output = app_handle @@ -271,56 +271,56 @@ impl CoreManager { let has_error = !output.status.success() || error_keywords.iter().any(|&kw| stderr.contains(kw)); - logging!(info, Type::Config, true, "-------- 验证结果 --------"); + logging!(info, Type::Config, true, "-------- Validation Result --------"); if !stderr.is_empty() { - logging!(info, Type::Config, true, "stderr输出:\n{}", stderr); + logging!(info, Type::Config, true, "stderr output:\n{}", stderr); } if has_error { - logging!(info, Type::Config, true, "发现错误,开始处理错误信息"); + logging!(info, Type::Config, true, "Errors found, processing error details"); let error_msg = if !stdout.is_empty() { stdout.to_string() } else if !stderr.is_empty() { stderr.to_string() } else if let Some(code) = output.status.code() { - format!("验证进程异常退出,退出码: {code}") + format!("Validation process exited abnormally, exit code: {code}") } else { - "验证进程被终止".to_string() + "Validation process was terminated".to_string() }; - logging!(info, Type::Config, true, "-------- 验证结束 --------"); + logging!(info, Type::Config, true, "-------- Validation End --------"); Ok((false, error_msg)) // 返回错误消息给调用者处理 } else { - logging!(info, Type::Config, true, "验证成功"); - logging!(info, Type::Config, true, "-------- 验证结束 --------"); + logging!(info, Type::Config, true, "Validation succeeded"); + logging!(info, Type::Config, true, "-------- Validation End --------"); Ok((true, String::new())) } } /// 只进行文件语法检查,不进行完整验证 async fn validate_file_syntax(&self, config_path: &str) -> Result<(bool, String)> { - logging!(info, Type::Config, true, "开始检查文件: {}", config_path); + logging!(info, Type::Config, true, "Starting file check: {}", config_path); // 读取文件内容 let content = match std::fs::read_to_string(config_path) { Ok(content) => content, Err(err) => { let error_msg = format!("Failed to read file: {err}"); - logging!(error, Type::Config, true, "无法读取文件: {}", error_msg); + logging!(error, Type::Config, true, "Failed to read file: {}", error_msg); return Ok((false, error_msg)); } }; // 对YAML文件尝试解析,只检查语法正确性 - logging!(info, Type::Config, true, "进行YAML语法检查"); + logging!(info, Type::Config, true, "Performing YAML syntax check"); match serde_yaml::from_str::(&content) { Ok(_) => { - logging!(info, Type::Config, true, "YAML语法检查通过"); + logging!(info, Type::Config, true, "YAML syntax check passed"); Ok((true, String::new())) } Err(err) => { // 使用标准化的前缀,以便错误处理函数能正确识别 let error_msg = format!("YAML syntax error: {err}"); - logging!(error, Type::Config, true, "YAML语法错误: {}", error_msg); + logging!(error, Type::Config, true, "YAML syntax error: {}", error_msg); Ok((false, error_msg)) } } @@ -332,13 +332,13 @@ impl CoreManager { Ok(content) => content, Err(err) => { let error_msg = format!("Failed to read script file: {err}"); - logging!(warn, Type::Config, true, "脚本语法错误: {}", err); + logging!(warn, Type::Config, true, "Script syntax error: {}", err); //handle::Handle::notice_message("config_validate::script_syntax_error", &error_msg); return Ok((false, error_msg)); } }; - logging!(debug, Type::Config, true, "验证脚本文件: {}", path); + logging!(debug, Type::Config, true, "Validating script file: {}", path); // 使用boa引擎进行基本语法检查 use boa_engine::{Context, Source}; @@ -348,7 +348,7 @@ impl CoreManager { match result { Ok(_) => { - logging!(debug, Type::Config, true, "脚本语法验证通过: {}", path); + logging!(debug, Type::Config, true, "Script syntax validation passed: {}", path); // 检查脚本是否包含main函数 if !content.contains("function main") @@ -356,7 +356,7 @@ impl CoreManager { && !content.contains("let main") { let error_msg = "Script must contain a main function"; - logging!(warn, Type::Config, true, "脚本缺少main函数: {}", path); + logging!(warn, Type::Config, true, "Script missing main function: {}", path); //handle::Handle::notice_message("config_validate::script_missing_main", error_msg); return Ok((false, error_msg.to_string())); } @@ -365,7 +365,7 @@ impl CoreManager { } Err(err) => { let error_msg = format!("Script syntax error: {err}"); - logging!(warn, Type::Config, true, "脚本语法错误: {}", err); + logging!(warn, Type::Config, true, "Script syntax error: {}", err); //handle::Handle::notice_message("config_validate::script_syntax_error", &error_msg); Ok((false, error_msg)) } @@ -375,33 +375,33 @@ impl CoreManager { pub async fn update_config(&self) -> Result<(bool, String)> { // 检查程序是否正在退出,如果是则跳过完整验证流程 if handle::Handle::global().is_exiting() { - logging!(info, Type::Config, true, "应用正在退出,跳过验证"); + logging!(info, Type::Config, true, "App is exiting, skipping validation"); return Ok((true, String::new())); } - logging!(info, Type::Config, true, "开始更新配置"); + logging!(info, Type::Config, true, "Starting config update"); // 1. 先生成新的配置内容 - logging!(info, Type::Config, true, "生成新的配置内容"); + logging!(info, Type::Config, true, "Generating new configuration content"); Config::generate().await?; // 2. 验证配置 match self.validate_config().await { Ok((true, _)) => { - logging!(info, Type::Config, true, "配置验证通过"); + logging!(info, Type::Config, true, "Configuration validation passed"); // 4. 验证通过后,生成正式的运行时配置 - logging!(info, Type::Config, true, "生成运行时配置"); + logging!(info, Type::Config, true, "Generating runtime configuration"); let run_path = Config::generate_file(ConfigType::Run)?; logging_error!(Type::Config, true, self.put_configs_force(run_path).await); Ok((true, "something".into())) } Ok((false, error_msg)) => { - logging!(warn, Type::Config, true, "配置验证失败: {}", error_msg); + logging!(warn, Type::Config, true, "Configuration validation failed: {}", error_msg); Config::runtime().discard(); Ok((false, error_msg)) } Err(e) => { - logging!(warn, Type::Config, true, "验证过程发生错误: {}", e); + logging!(warn, Type::Config, true, "Error occurred during validation: {}", e); Config::runtime().discard(); Err(e) } @@ -435,7 +435,7 @@ impl CoreManager { impl CoreManager { /// 清理多余的 mihomo 进程 async fn cleanup_orphaned_mihomo_processes(&self) -> Result<()> { - logging!(info, Type::Core, true, "开始清理多余的 mihomo 进程"); + logging!(info, Type::Core, true, "Starting cleanup of orphaned mihomo processes"); // 获取当前管理的进程 PID let current_pid = { @@ -471,7 +471,7 @@ impl CoreManager { debug, Type::Core, true, - "跳过当前管理的进程: {} (PID: {})", + "Skipping currently managed process: {} (PID: {})", process_name, pid ); @@ -482,13 +482,13 @@ impl CoreManager { } } Err(e) => { - logging!(debug, Type::Core, true, "查找进程时发生错误: {}", e); + logging!(debug, Type::Core, true, "Error occurred while finding processes: {}", e); } } } if pids_to_kill.is_empty() { - logging!(debug, Type::Core, true, "未发现多余的 mihomo 进程"); + logging!(debug, Type::Core, true, "No orphaned mihomo processes found"); return Ok(()); } @@ -837,7 +837,7 @@ impl CoreManager { // 当服务安装失败时的回退逻辑 async fn attempt_service_init(&self) -> Result<()> { if service::check_service_needs_reinstall().await { - logging!(info, Type::Core, true, "服务版本不匹配或状态异常,执行重装"); + logging!(info, Type::Core, true, "Service version mismatch or abnormal status, performing reinstallation"); if let Err(e) = service::reinstall_service().await { logging!( warn, @@ -849,7 +849,7 @@ impl CoreManager { return Err(e); } // 如果重装成功,还需要尝试启动服务 - logging!(info, Type::Core, true, "服务重装成功,尝试启动服务"); + logging!(info, Type::Core, true, "Service reinstalled successfully, attempting to start"); } if let Err(e) = self.start_core_by_service().await { @@ -857,14 +857,14 @@ impl CoreManager { warn, Type::Core, true, - "通过服务启动核心失败 during attempt_service_init: {}", + "Failed to start core via service during attempt_service_init: {}", e ); // 确保 prefer_sidecar 在 start_core_by_service 失败时也被设置 let mut state = service::ServiceState::get(); if !state.prefer_sidecar { state.prefer_sidecar = true; - state.last_error = Some(format!("通过服务启动核心失败: {e}")); + state.last_error = Some(format!("Failed to start core via service: {e}")); if let Err(save_err) = state.save() { logging!( error, @@ -901,11 +901,11 @@ impl CoreManager { info, Type::Core, true, - "服务当前可用或看似可用,尝试通过服务模式启动/重装" + "Service currently available or appears available; attempting to start/reinstall via service mode" ); match self.attempt_service_init().await { Ok(_) => { - logging!(info, Type::Core, true, "服务模式成功启动核心"); + logging!(info, Type::Core, true, "Service mode successfully started core"); core_started_successfully = true; } Err(_err) => { @@ -913,7 +913,7 @@ impl CoreManager { warn, Type::Core, true, - "服务模式启动或重装失败。将尝试Sidecar模式回退。" + "Service mode start or reinstall failed. Will attempt Sidecar fallback." ); } } @@ -922,7 +922,7 @@ impl CoreManager { info, Type::Core, true, - "服务初始不可用 (is_service_available 调用失败)" + "Service initially unavailable (is_service_available call failed)" ); } @@ -931,7 +931,7 @@ impl CoreManager { info, Type::Core, true, - "核心未通过服务模式启动,执行Sidecar回退或首次安装逻辑" + "Core not started via service mode; performing Sidecar fallback or first-time install logic" ); let service_state = service::ServiceState::get(); @@ -941,7 +941,7 @@ impl CoreManager { info, Type::Core, true, - "用户偏好Sidecar模式或先前服务启动失败,使用Sidecar模式启动" + "User prefers Sidecar mode or previous service start failed; starting with Sidecar mode" ); self.start_core_by_sidecar().await?; // 如果 sidecar 启动成功,我们可以认为核心初始化流程到此结束 @@ -953,31 +953,32 @@ impl CoreManager { info, Type::Core, true, - "无服务安装记录 (首次运行或状态重置),尝试安装服务" + "No service installation record (first run or state reset); attempting to install service" ); match service::install_service().await { Ok(_) => { - logging!(info, Type::Core, true, "服务安装成功(首次尝试)"); + logging!(info, Type::Core, true, "Service installed successfully (first attempt)"); let mut new_state = service::ServiceState::default(); new_state.record_install(); new_state.prefer_sidecar = false; new_state.save()?; if service::is_service_available().await.is_ok() { - logging!(info, Type::Core, true, "新安装的服务可用,尝试启动"); + logging!(info, Type::Core, true, "Newly installed service available; attempting to start"); if self.start_core_by_service().await.is_ok() { - logging!(info, Type::Core, true, "新安装的服务启动成功"); + logging!(info, Type::Core, true, "Newly installed service started successfully"); } else { logging!( warn, Type::Core, true, - "新安装的服务启动失败,回退到Sidecar模式" + "Newly installed service failed to start; falling back to Sidecar mode" ); let mut final_state = service::ServiceState::get(); final_state.prefer_sidecar = true; - final_state.last_error = - Some("Newly installed service failed to start".to_string()); + final_state.last_error = Some( + "Newly installed service failed to start".to_string(), + ); final_state.save()?; self.start_core_by_sidecar().await?; } @@ -986,7 +987,7 @@ impl CoreManager { warn, Type::Core, true, - "服务安装成功但未能连接/立即可用,回退到Sidecar模式" + "Service installed successfully but not connectable/immediately available; falling back to Sidecar mode" ); let mut final_state = service::ServiceState::get(); final_state.prefer_sidecar = true; @@ -999,7 +1000,7 @@ impl CoreManager { } } Err(err) => { - logging!(warn, Type::Core, true, "服务首次安装失败: {}", err); + logging!(warn, Type::Core, true, "Service first-time installation failed: {}", err); let new_state = service::ServiceState { last_error: Some(err.to_string()), prefer_sidecar: true, @@ -1062,7 +1063,7 @@ impl CoreManager { if service::check_service_needs_reinstall().await { service::reinstall_service().await?; } - logging!(info, Type::Core, true, "服务可用,使用服务模式启动"); + logging!(info, Type::Core, true, "Service available; starting in service mode"); self.start_core_by_service().await?; } else { // 服务不可用,检查用户偏好 @@ -1072,11 +1073,11 @@ impl CoreManager { info, Type::Core, true, - "服务不可用,根据用户偏好使用Sidecar模式" + "Service unavailable; starting in Sidecar mode per user preference" ); self.start_core_by_sidecar().await?; } else { - logging!(info, Type::Core, true, "服务不可用,使用Sidecar模式"); + logging!(info, Type::Core, true, "Service unavailable; starting in Sidecar mode"); self.start_core_by_sidecar().await?; } } diff --git a/src-tauri/src/core/event_driven_proxy.rs b/src-tauri/src/core/event_driven_proxy.rs index 6937e43a..240e9a73 100644 --- a/src-tauri/src/core/event_driven_proxy.rs +++ b/src-tauri/src/core/event_driven_proxy.rs @@ -78,7 +78,7 @@ struct QueryRequest { response_tx: oneshot::Sender, } -// 配置结构体移到外部 +// Configuration structure moved to external struct ProxyConfig { sys_enabled: bool, pac_enabled: bool, @@ -106,59 +106,59 @@ impl EventDrivenProxyManager { } } - /// 获取自动代理配置(缓存) + /// Get automatic proxy configuration (cached) pub fn get_auto_proxy_cached(&self) -> Autoproxy { self.state.read().auto_proxy.clone() } - /// 异步获取最新的自动代理配置 + /// Asynchronously get the latest automatic proxy configuration pub async fn get_auto_proxy_async(&self) -> Autoproxy { let (tx, rx) = oneshot::channel(); let query = QueryRequest { response_tx: tx }; if self.query_sender.send(query).is_err() { - log::error!(target: "app", "发送查询请求失败,返回缓存数据"); + log::error!(target: "app", "Failed to send query request, returning cached data"); return self.get_auto_proxy_cached(); } match timeout(Duration::from_secs(5), rx).await { Ok(Ok(result)) => result, _ => { - log::warn!(target: "app", "查询超时,返回缓存数据"); + log::warn!(target: "app", "Query timed out, returning cached data"); self.get_auto_proxy_cached() } } } - /// 通知配置变更 + /// Notify configuration changed pub fn notify_config_changed(&self) { self.send_event(ProxyEvent::ConfigChanged); } - /// 通知应用启动 + /// Notify application started pub fn notify_app_started(&self) { self.send_event(ProxyEvent::AppStarted); } - /// 通知应用即将关闭 + /// Notify application stopping #[allow(dead_code)] pub fn notify_app_stopping(&self) { self.send_event(ProxyEvent::AppStopping); } - /// 启用系统代理 + /// Enable system proxy #[allow(dead_code)] pub fn enable_proxy(&self) { self.send_event(ProxyEvent::EnableProxy); } - /// 禁用系统代理 + /// Disable system proxy #[allow(dead_code)] pub fn disable_proxy(&self) { self.send_event(ProxyEvent::DisableProxy); } - /// 强制检查代理状态 + /// Force check proxy status #[allow(dead_code)] pub fn force_check(&self) { self.send_event(ProxyEvent::ForceCheck); @@ -166,7 +166,7 @@ impl EventDrivenProxyManager { fn send_event(&self, event: ProxyEvent) { if let Err(e) = self.event_sender.send(event) { - log::error!(target: "app", "发送代理事件失败: {e}"); + log::error!(target: "app", "Failed to send proxy event: {e}"); } } @@ -176,18 +176,18 @@ impl EventDrivenProxyManager { mut query_rx: mpsc::UnboundedReceiver, ) { tokio::spawn(async move { - log::info!(target: "app", "事件驱动代理管理器启动"); + log::info!(target: "app", "Event-driven proxy manager started"); loop { tokio::select! { event = event_rx.recv() => { match event { Some(event) => { - log::debug!(target: "app", "处理代理事件: {event:?}"); + log::debug!(target: "app", "Handling proxy event: {event:?}"); Self::handle_event(&state, event).await; } None => { - log::info!(target: "app", "事件通道关闭,代理管理器停止"); + log::info!(target: "app", "Event channel closed, proxy manager stopped"); break; } } @@ -199,7 +199,7 @@ impl EventDrivenProxyManager { let _ = query.response_tx.send(result); } None => { - log::info!(target: "app", "查询通道关闭"); + log::info!(target: "app", "Query channel closed"); break; } } @@ -230,7 +230,7 @@ impl EventDrivenProxyManager { Self::initialize_proxy_state(state).await; } ProxyEvent::AppStopping => { - log::info!(target: "app", "清理代理状态"); + log::info!(target: "app", "Cleaning up proxy state"); } } } @@ -246,7 +246,7 @@ impl EventDrivenProxyManager { } async fn initialize_proxy_state(state: &Arc>) { - log::info!(target: "app", "初始化代理状态"); + log::info!(target: "app", "Initializing proxy state"); let config = Self::get_proxy_config(); let auto_proxy = Self::get_auto_proxy_with_timeout().await; @@ -260,11 +260,11 @@ impl EventDrivenProxyManager { s.is_healthy = true; }); - log::info!(target: "app", "代理状态初始化完成: sys={}, pac={}", config.sys_enabled, config.pac_enabled); + log::info!(target: "app", "Proxy state initialized: sys={}, pac={}", config.sys_enabled, config.pac_enabled); } async fn update_proxy_config(state: &Arc>) { - log::debug!(target: "app", "更新代理配置"); + log::debug!(target: "app", "Updating proxy configuration"); let config = Self::get_proxy_config(); @@ -288,7 +288,7 @@ impl EventDrivenProxyManager { return; } - log::debug!(target: "app", "检查代理状态"); + log::debug!(target: "app", "Checking proxy status"); if pac_enabled { Self::check_and_restore_pac_proxy(state).await; @@ -306,7 +306,7 @@ impl EventDrivenProxyManager { }); if !current.enable || current.url != expected.url { - log::info!(target: "app", "PAC代理设置异常,正在恢复..."); + log::info!(target: "app", "PAC proxy setting abnormal, recovering..."); Self::restore_pac_proxy(&expected.url).await; sleep(Duration::from_millis(500)).await; @@ -328,7 +328,7 @@ impl EventDrivenProxyManager { }); if !current.enable || current.host != expected.host || current.port != expected.port { - log::info!(target: "app", "系统代理设置异常,正在恢复..."); + log::info!(target: "app", "System proxy setting abnormal, recovering..."); Self::restore_sys_proxy(&expected).await; sleep(Duration::from_millis(500)).await; @@ -344,7 +344,7 @@ impl EventDrivenProxyManager { } async fn enable_system_proxy(state: &Arc>) { - log::info!(target: "app", "启用系统代理"); + log::info!(target: "app", "Enabling system proxy"); let pac_enabled = state.read().pac_enabled; @@ -360,7 +360,7 @@ impl EventDrivenProxyManager { } async fn disable_system_proxy(_state: &Arc>) { - log::info!(target: "app", "禁用系统代理"); + log::info!(target: "app", "Disabling system proxy"); #[cfg(not(target_os = "windows"))] { @@ -373,7 +373,7 @@ impl EventDrivenProxyManager { } async fn switch_proxy_mode(state: &Arc>, to_pac: bool) { - log::info!(target: "app", "切换到{}模式", if to_pac { "PAC" } else { "HTTP代理" }); + log::info!(target: "app", "Switching to {} mode", if to_pac { "PAC" } else { "HTTP Proxy" }); if to_pac { let disabled_sys = Sysproxy::default(); @@ -396,7 +396,7 @@ impl EventDrivenProxyManager { async fn get_auto_proxy_with_timeout() -> Autoproxy { let async_proxy = AsyncProxyQuery::get_auto_proxy().await; - // 转换为兼容的结构 + // Convert to compatible structure Autoproxy { enable: async_proxy.enable, url: async_proxy.url, @@ -406,7 +406,7 @@ impl EventDrivenProxyManager { async fn get_sys_proxy_with_timeout() -> Sysproxy { let async_proxy = AsyncProxyQuery::get_system_proxy().await; - // 转换为兼容的结构 + // Convert to compatible structure Sysproxy { enable: async_proxy.enable, host: async_proxy.host, @@ -415,7 +415,7 @@ impl EventDrivenProxyManager { } } - // 统一的状态更新方法 + // Unified state update method fn update_state_timestamp(state: &Arc>, update_fn: F) where F: FnOnce(&mut ProxyState), @@ -534,14 +534,14 @@ impl EventDrivenProxyManager { let binary_path = match dirs::service_path() { Ok(path) => path, Err(e) => { - log::error!(target: "app", "获取服务路径失败: {}", e); + log::error!(target: "app", "Failed to get service path: {}", e); return; } }; let sysproxy_exe = binary_path.with_file_name("sysproxy.exe"); if !sysproxy_exe.exists() { - log::error!(target: "app", "sysproxy.exe 不存在"); + log::error!(target: "app", "sysproxy.exe does not exist"); return; } @@ -554,17 +554,17 @@ impl EventDrivenProxyManager { match output { Ok(output) => { if !output.status.success() { - log::error!(target: "app", "执行sysproxy命令失败: {:?}", args); + log::error!(target: "app", "Failed to execute sysproxy command: {:?}", args); let stderr = String::from_utf8_lossy(&output.stderr); if !stderr.is_empty() { - log::error!(target: "app", "sysproxy错误输出: {}", stderr); + log::error!(target: "app", "sysproxy stderr: {}", stderr); } } else { - log::debug!(target: "app", "成功执行sysproxy命令: {:?}", args); + log::debug!(target: "app", "Successfully executed sysproxy command: {:?}", args); } } Err(e) => { - log::error!(target: "app", "执行sysproxy命令出错: {}", e); + log::error!(target: "app", "Error executing sysproxy command: {}", e); } } } diff --git a/src-tauri/src/core/handle.rs b/src-tauri/src/core/handle.rs index d7e15187..c2f51445 100644 --- a/src-tauri/src/core/handle.rs +++ b/src-tauri/src/core/handle.rs @@ -416,7 +416,7 @@ impl Handle { info, Type::Frontend, true, - "启动过程中发现错误,加入消息队列: {} - {}", + "Error found during startup; queued: {} - {}", status_str, msg_str ); @@ -466,7 +466,7 @@ impl Handle { info, Type::Frontend, true, - "发送{}条启动时累积的错误消息", + "Sending {} accumulated startup error messages", errors.len() ); diff --git a/src-tauri/src/core/service.rs b/src-tauri/src/core/service.rs index c16d9ecf..10dc2138 100644 --- a/src-tauri/src/core/service.rs +++ b/src-tauri/src/core/service.rs @@ -477,7 +477,7 @@ pub async fn reinstall_service() -> Result<()> { /// 检查服务状态 - 使用IPC通信 pub async fn check_ipc_service_status() -> Result { - logging!(info, Type::Service, true, "开始检查服务状态 (IPC)"); + logging!(info, Type::Service, true, "Starting service status check (IPC)"); // 使用IPC通信 let payload = serde_json::json!({}); @@ -495,8 +495,10 @@ pub async fn check_ipc_service_status() -> Result { ); */ if !response.success { - let err_msg = response.error.unwrap_or_else(|| "未知服务错误".to_string()); - logging!(error, Type::Service, true, "服务响应错误: {}", err_msg); + let err_msg = response + .error + .unwrap_or_else(|| "Unknown service error".to_string()); + logging!(error, Type::Service, true, "Service response error: {}", err_msg); bail!(err_msg); } @@ -516,7 +518,7 @@ pub async fn check_ipc_service_status() -> Result { warn, Type::Service, true, - "解析嵌套的ResponseBody失败: {}; 尝试其他方式", + "Failed to parse nested ResponseBody: {}; trying alternative", e ); None @@ -536,7 +538,7 @@ pub async fn check_ipc_service_status() -> Result { info, Type::Service, true, - "服务检测成功: code={}, msg={}, data存在={}", + "Service check succeeded: code={}, msg={}, data_present={}", json_response.code, json_response.msg, json_response.data.is_some() @@ -550,7 +552,7 @@ pub async fn check_ipc_service_status() -> Result { info, Type::Service, true, - "服务检测成功: code={}, msg={}", + "Service check succeeded: code={}, msg={}", json_response.code, json_response.msg ); @@ -561,31 +563,31 @@ pub async fn check_ipc_service_status() -> Result { error, Type::Service, true, - "解析服务响应失败: {}; 原始数据: {:?}", + "Failed to parse service response: {}; raw data: {:?}", e, data ); - bail!("无法解析服务响应数据: {}", e) + bail!("Unable to parse service response data: {}", e) } } } } None => { - logging!(error, Type::Service, true, "服务响应中没有数据"); - bail!("服务响应中没有数据") + logging!(error, Type::Service, true, "No data in service response"); + bail!("No data in service response") } } } Err(e) => { - logging!(error, Type::Service, true, "IPC通信失败: {}", e); - bail!("无法连接到Koala Clash Service: {}", e) + logging!(error, Type::Service, true, "IPC communication failed: {}", e); + bail!("Unable to connect to Koala Clash Service: {}", e) } } } /// 检查服务版本 - 使用IPC通信 pub async fn check_service_version() -> Result { - logging!(info, Type::Service, true, "开始检查服务版本 (IPC)"); + logging!(info, Type::Service, true, "Starting service version check (IPC)"); let payload = serde_json::json!({}); // logging!(debug, Type::Service, true, "发送GetVersion请求"); @@ -604,8 +606,8 @@ pub async fn check_service_version() -> Result { if !response.success { let err_msg = response .error - .unwrap_or_else(|| "获取服务版本失败".to_string()); - logging!(error, Type::Service, true, "获取版本错误: {}", err_msg); + .unwrap_or_else(|| "Failed to get service version".to_string()); + logging!(error, Type::Service, true, "Failed to get service version: {}", err_msg); bail!(err_msg); } @@ -618,7 +620,7 @@ pub async fn check_service_version() -> Result { info, Type::Service, true, - "获取到服务版本: {}", + "Service version: {}", version_str ); return Ok(version_str.to_string()); @@ -628,7 +630,7 @@ pub async fn check_service_version() -> Result { error, Type::Service, true, - "嵌套数据中没有version字段: {:?}", + "Nested data does not contain version field: {:?}", nested_data ); } else { @@ -639,7 +641,7 @@ pub async fn check_service_version() -> Result { info, Type::Service, true, - "获取到服务版本: {}", + "Received service version: {}", version_response.version ); return Ok(version_response.version); @@ -649,44 +651,44 @@ pub async fn check_service_version() -> Result { error, Type::Service, true, - "解析版本响应失败: {}; 原始数据: {:?}", + "Failed to parse version response: {}; raw data: {:?}", e, data ); - bail!("无法解析服务版本数据: {}", e) + bail!("Unable to parse service version data: {}", e) } } } - bail!("响应中未找到有效的版本信息") + bail!("No valid version information found in response") } None => { - logging!(error, Type::Service, true, "版本响应中没有数据"); - bail!("服务版本响应中没有数据") + logging!(error, Type::Service, true, "No data in version response"); + bail!("No data in service version response") } } } Err(e) => { - logging!(error, Type::Service, true, "IPC通信失败: {}", e); - bail!("无法连接到Koala Clash Service: {}", e) + logging!(error, Type::Service, true, "IPC communication failed: {}", e); + bail!("Unable to connect to Koala Clash Service: {}", e) } } } /// 检查服务是否需要重装 pub async fn check_service_needs_reinstall() -> bool { - logging!(info, Type::Service, true, "开始检查服务是否需要重装"); + logging!(info, Type::Service, true, "Checking whether service needs reinstallation"); let service_state = ServiceState::get(); if !service_state.can_reinstall() { - log::info!(target: "app", "服务重装检查: 处于冷却期或已达最大尝试次数"); + log::info!(target: "app", "Service reinstall check: in cooldown period or max attempts reached"); return false; } // 检查版本和可用性 match check_service_version().await { Ok(version) => { - log::info!(target: "app", "服务版本检测:当前={version}, 要求={REQUIRED_SERVICE_VERSION}"); + log::info!(target: "app", "Service version check: current={version}, required={REQUIRED_SERVICE_VERSION}"); /* logging!( info, Type::Service, @@ -698,25 +700,25 @@ pub async fn check_service_needs_reinstall() -> bool { let needs_reinstall = version != REQUIRED_SERVICE_VERSION; if needs_reinstall { - log::warn!(target: "app", "发现服务版本不匹配,需要重装! 当前={version}, 要求={REQUIRED_SERVICE_VERSION}"); - logging!(warn, Type::Service, true, "服务版本不匹配,需要重装"); + log::warn!(target: "app", "Service version mismatch detected, reinstallation required! current={version}, required={REQUIRED_SERVICE_VERSION}"); + logging!(warn, Type::Service, true, "Service version mismatch, reinstallation required"); // log::debug!(target: "app", "当前版本字节: {:?}", version.as_bytes()); // log::debug!(target: "app", "要求版本字节: {:?}", REQUIRED_SERVICE_VERSION.as_bytes()); } else { - log::info!(target: "app", "服务版本匹配,无需重装"); + log::info!(target: "app", "Service version matches, no reinstallation needed"); // logging!(info, Type::Service, true, "服务版本匹配,无需重装"); } needs_reinstall } Err(err) => { - logging!(error, Type::Service, true, "检查服务版本失败: {}", err); + logging!(error, Type::Service, true, "Failed to check service version: {}", err); // 检查服务是否可用 match is_service_available().await { Ok(()) => { - log::info!(target: "app", "服务正在运行但版本检查失败: {err}"); + log::info!(target: "app", "Service is running but version check failed: {err}"); /* logging!( info, Type::Service, @@ -727,7 +729,7 @@ pub async fn check_service_needs_reinstall() -> bool { false } _ => { - log::info!(target: "app", "服务不可用或未运行,需要重装"); + log::info!(target: "app", "Service unavailable or not running, reinstallation needed"); // logging!(info, Type::Service, true, "服务不可用或未运行,需要重装"); true } @@ -738,7 +740,7 @@ pub async fn check_service_needs_reinstall() -> bool { /// 尝试使用服务启动core pub(super) async fn start_with_existing_service(config_file: &PathBuf) -> Result<()> { - log::info!(target:"app", "尝试使用现有服务启动核心 (IPC)"); + log::info!(target:"app", "Attempting to start core with existing service (IPC)"); // logging!(info, Type::Service, true, "尝试使用现有服务启动核心"); let clash_core = Config::verge().latest().get_valid_clash_core(); @@ -781,8 +783,8 @@ pub(super) async fn start_with_existing_service(config_file: &PathBuf) -> Result ); */ if !response.success { - let err_msg = response.error.unwrap_or_else(|| "启动核心失败".to_string()); - logging!(error, Type::Service, true, "启动核心失败: {}", err_msg); + let err_msg = response.error.unwrap_or_else(|| "Failed to start core".to_string()); + logging!(error, Type::Service, true, "Failed to start core: {}", err_msg); bail!(err_msg); } @@ -793,127 +795,127 @@ pub(super) async fn start_with_existing_service(config_file: &PathBuf) -> Result let msg = data .get("msg") .and_then(|m| m.as_str()) - .unwrap_or("未知错误"); + .unwrap_or("Unknown error"); if code_value != 0 { logging!( error, Type::Service, true, - "启动核心返回错误: code={}, msg={}", + "Start core returned error: code={}, msg={}", code_value, msg ); - bail!("启动核心失败: {}", msg); + bail!("Failed to start core: {}", msg); } } } - logging!(info, Type::Service, true, "服务成功启动核心"); + logging!(info, Type::Service, true, "Service successfully started core"); Ok(()) } Err(e) => { - logging!(error, Type::Service, true, "启动核心IPC通信失败: {}", e); - bail!("无法连接到Koala Clash Service: {}", e) + logging!(error, Type::Service, true, "Failed to start core via IPC: {}", e); + bail!("Unable to connect to Koala Clash Service: {}", e) } } } // 以服务启动core pub(super) async fn run_core_by_service(config_file: &PathBuf) -> Result<()> { - log::info!(target: "app", "正在尝试通过服务启动核心"); + log::info!(target: "app", "Attempting to start core via service"); // 先检查服务版本,不受冷却期限制 let version_check = match check_service_version().await { Ok(version) => { - log::info!(target: "app", "检测到服务版本: {version}, 要求版本: {REQUIRED_SERVICE_VERSION}"); + log::info!(target: "app", "Detected service version: {version}, required: {REQUIRED_SERVICE_VERSION}"); if version.as_bytes() != REQUIRED_SERVICE_VERSION.as_bytes() { - log::warn!(target: "app", "服务版本不匹配,需要重装"); + log::warn!(target: "app", "Service version mismatch, reinstallation required"); false } else { - log::info!(target: "app", "服务版本匹配"); + log::info!(target: "app", "Service version matches"); true } } Err(err) => { - log::warn!(target: "app", "无法获取服务版本: {err}"); + log::warn!(target: "app", "Failed to get service version: {err}"); false } }; if version_check && is_service_available().await.is_ok() { - log::info!(target: "app", "服务已在运行且版本匹配,尝试使用"); + log::info!(target: "app", "Service is running and version matches, attempting to use it"); return start_with_existing_service(config_file).await; } if !version_check { - log::info!(target: "app", "服务版本不匹配,尝试重装"); + log::info!(target: "app", "Service version mismatch, attempting reinstallation"); let service_state = ServiceState::get(); if !service_state.can_reinstall() { - log::warn!(target: "app", "由于限制无法重装服务"); + log::warn!(target: "app", "Cannot reinstall service due to limitations"); if let Ok(()) = start_with_existing_service(config_file).await { - log::info!(target: "app", "尽管版本不匹配,但成功启动了服务"); + log::info!(target: "app", "Service started successfully despite version mismatch"); return Ok(()); } else { - bail!("服务版本不匹配且无法重装,启动失败"); + bail!("Service version mismatch and cannot reinstall; startup failed"); } } - log::info!(target: "app", "开始重装服务"); + log::info!(target: "app", "Starting service reinstallation"); if let Err(err) = reinstall_service().await { - log::warn!(target: "app", "服务重装失败: {err}"); + log::warn!(target: "app", "Service reinstallation failed: {err}"); - log::info!(target: "app", "尝试使用现有服务"); + log::info!(target: "app", "Attempting to use existing service"); return start_with_existing_service(config_file).await; } - log::info!(target: "app", "服务重装成功,尝试启动"); + log::info!(target: "app", "Service reinstalled successfully, attempting to start"); return start_with_existing_service(config_file).await; } - // 检查服务状态 + // Check service status match check_ipc_service_status().await { Ok(_) => { - log::info!(target: "app", "服务可用但未运行核心,尝试启动"); + log::info!(target: "app", "Service available but core not running, attempting to start"); if let Ok(()) = start_with_existing_service(config_file).await { return Ok(()); } } Err(err) => { - log::warn!(target: "app", "服务检查失败: {err}"); + log::warn!(target: "app", "Service check failed: {err}"); } } - // 服务不可用或启动失败,检查是否需要重装 + // Service unavailable or startup failed, check if reinstallation is needed if check_service_needs_reinstall().await { - log::info!(target: "app", "服务需要重装"); + log::info!(target: "app", "Service needs reinstallation"); if let Err(err) = reinstall_service().await { - log::warn!(target: "app", "服务重装失败: {err}"); + log::warn!(target: "app", "Service reinstallation failed: {err}"); bail!("Failed to reinstall service: {}", err); } - log::info!(target: "app", "服务重装完成,尝试启动核心"); + log::info!(target: "app", "Service reinstallation completed, attempting to start core"); start_with_existing_service(config_file).await } else { - log::warn!(target: "app", "服务不可用且无法重装"); + log::warn!(target: "app", "Service unavailable and cannot be reinstalled"); bail!("Service is not available and cannot be reinstalled at this time") } } /// 通过服务停止core pub(super) async fn stop_core_by_service() -> Result<()> { - logging!(info, Type::Service, true, "通过服务停止核心 (IPC)"); + logging!(info, Type::Service, true, "Stopping core via service (IPC)"); let payload = serde_json::json!({}); let response = send_ipc_request(IpcCommand::StopClash, payload) .await - .context("无法连接到Koala Clash Service")?; + .context("Unable to connect to Koala Clash Service")?; if !response.success { - bail!(response.error.unwrap_or_else(|| "停止核心失败".to_string())); + bail!(response.error.unwrap_or_else(|| "Failed to stop core".to_string())); } if let Some(data) = &response.data { @@ -922,18 +924,18 @@ pub(super) async fn stop_core_by_service() -> Result<()> { let msg = data .get("msg") .and_then(|m| m.as_str()) - .unwrap_or("未知错误"); + .unwrap_or("Unknown error"); if code_value != 0 { logging!( error, Type::Service, true, - "停止核心返回错误: code={}, msg={}", + "Stop core returned error: code={}, msg={}", code_value, msg ); - bail!("停止核心失败: {}", msg); + bail!("Failed to stop core: {}", msg); } } } @@ -943,19 +945,19 @@ pub(super) async fn stop_core_by_service() -> Result<()> { /// 检查服务是否正在运行 pub async fn is_service_available() -> Result<()> { - logging!(info, Type::Service, true, "开始检查服务是否正在运行"); + logging!(info, Type::Service, true, "Checking whether service is running"); match check_ipc_service_status().await { Ok(resp) => { if resp.code == 0 && resp.msg == "ok" && resp.data.is_some() { - logging!(info, Type::Service, true, "服务正在运行"); + logging!(info, Type::Service, true, "Service is running"); Ok(()) } else { logging!( warn, Type::Service, true, - "服务未正常运行: code={}, msg={}", + "Service not running normally: code={}, msg={}", resp.code, resp.msg ); @@ -963,7 +965,7 @@ pub async fn is_service_available() -> Result<()> { } } Err(err) => { - logging!(error, Type::Service, true, "检查服务运行状态失败: {}", err); + logging!(error, Type::Service, true, "Failed to check service running status: {}", err); Err(err) } } @@ -971,21 +973,21 @@ pub async fn is_service_available() -> Result<()> { /// 强制重装服务(UI修复按钮) pub async fn force_reinstall_service() -> Result<()> { - log::info!(target: "app", "用户请求强制重装服务"); + log::info!(target: "app", "User requested forced service reinstallation"); let service_state = ServiceState::default(); service_state.save()?; - log::info!(target: "app", "已重置服务状态,开始执行重装"); + log::info!(target: "app", "Service state reset, starting reinstallation"); match reinstall_service().await { Ok(()) => { - log::info!(target: "app", "服务重装成功"); + log::info!(target: "app", "Service reinstalled successfully"); Ok(()) } Err(err) => { - log::error!(target: "app", "强制重装服务失败: {err}"); - bail!("强制重装服务失败: {}", err) + log::error!(target: "app", "Forced service reinstallation failed: {err}"); + bail!("Forced service reinstallation failed: {}", err) } } } diff --git a/src-tauri/src/core/service_ipc.rs b/src-tauri/src/core/service_ipc.rs index 9ffb6695..bab502d1 100644 --- a/src-tauri/src/core/service_ipc.rs +++ b/src-tauri/src/core/service_ipc.rs @@ -129,14 +129,14 @@ pub async fn send_ipc_request( winnt::{FILE_SHARE_READ, FILE_SHARE_WRITE, GENERIC_READ, GENERIC_WRITE}, }; - logging!(info, Type::Service, true, "正在连接服务 (Windows)..."); + logging!(info, Type::Service, true, "Connecting to service (Windows)..."); let command_type = format!("{:?}", command); let request = match create_signed_request(command, payload) { Ok(req) => req, Err(e) => { - logging!(error, Type::Service, true, "创建签名请求失败: {}", e); + logging!(error, Type::Service, true, "Failed to create signed request: {}", e); return Err(e); } }; @@ -147,8 +147,8 @@ pub async fn send_ipc_request( let c_pipe_name = match CString::new(IPC_SOCKET_NAME) { Ok(name) => name, Err(e) => { - logging!(error, Type::Service, true, "创建CString失败: {}", e); - return Err(anyhow::anyhow!("创建CString失败: {}", e)); + logging!(error, Type::Service, true, "Failed to create CString: {}", e); + return Err(anyhow::anyhow!("Failed to create CString: {}", e)); } }; @@ -177,29 +177,29 @@ pub async fn send_ipc_request( } let mut pipe = unsafe { File::from_raw_handle(handle as RawHandle) }; - logging!(info, Type::Service, true, "服务连接成功 (Windows)"); + logging!(info, Type::Service, true, "Service connection successful (Windows)"); let request_bytes = request_json.as_bytes(); let len_bytes = (request_bytes.len() as u32).to_be_bytes(); if let Err(e) = pipe.write_all(&len_bytes) { - logging!(error, Type::Service, true, "写入请求长度失败: {}", e); + logging!(error, Type::Service, true, "Failed to write request length: {}", e); return Err(anyhow::anyhow!("写入请求长度失败: {}", e)); } if let Err(e) = pipe.write_all(request_bytes) { - logging!(error, Type::Service, true, "写入请求内容失败: {}", e); + logging!(error, Type::Service, true, "Failed to write request body: {}", e); return Err(anyhow::anyhow!("写入请求内容失败: {}", e)); } if let Err(e) = pipe.flush() { - logging!(error, Type::Service, true, "刷新管道失败: {}", e); + logging!(error, Type::Service, true, "Failed to flush pipe: {}", e); return Err(anyhow::anyhow!("刷新管道失败: {}", e)); } let mut response_len_bytes = [0u8; 4]; if let Err(e) = pipe.read_exact(&mut response_len_bytes) { - logging!(error, Type::Service, true, "读取响应长度失败: {}", e); + logging!(error, Type::Service, true, "Failed to read response length: {}", e); return Err(anyhow::anyhow!("读取响应长度失败: {}", e)); } @@ -207,14 +207,14 @@ pub async fn send_ipc_request( let mut response_bytes = vec![0u8; response_len]; if let Err(e) = pipe.read_exact(&mut response_bytes) { - logging!(error, Type::Service, true, "读取响应内容失败: {}", e); + logging!(error, Type::Service, true, "Failed to read response body: {}", e); return Err(anyhow::anyhow!("读取响应内容失败: {}", e)); } let response: IpcResponse = match serde_json::from_slice::(&response_bytes) { Ok(r) => r, Err(e) => { - logging!(error, Type::Service, true, "服务响应解析失败: {}", e); + logging!(error, Type::Service, true, "Failed to parse service response: {}", e); return Err(anyhow::anyhow!("解析响应失败: {}", e)); } }; @@ -222,12 +222,12 @@ pub async fn send_ipc_request( match verify_response_signature(&response) { Ok(valid) => { if !valid { - logging!(error, Type::Service, true, "服务响应签名验证失败"); + logging!(error, Type::Service, true, "Service response signature verification failed"); bail!("服务响应签名验证失败"); } } Err(e) => { - logging!(error, Type::Service, true, "验证响应签名时出错: {}", e); + logging!(error, Type::Service, true, "Error verifying response signature: {}", e); return Err(e); } } @@ -236,7 +236,7 @@ pub async fn send_ipc_request( info, Type::Service, true, - "IPC请求完成: 命令={}, 成功={}", + "IPC request completed: command={}, success={}", command_type, response.success ); @@ -255,7 +255,7 @@ pub async fn send_ipc_request( ) -> Result { use std::os::unix::net::UnixStream; - logging!(info, Type::Service, true, "正在连接服务 (Unix)..."); + logging!(info, Type::Service, true, "Connecting to service (Unix)..."); let command_type = format!("{command:?}"); @@ -271,11 +271,11 @@ pub async fn send_ipc_request( let mut stream = match UnixStream::connect(IPC_SOCKET_NAME) { Ok(s) => { - logging!(info, Type::Service, true, "服务连接成功 (Unix)"); + logging!(info, Type::Service, true, "Service connection successful (Unix)"); s } Err(e) => { - logging!(error, Type::Service, true, "连接到Unix套接字失败: {}", e); + logging!(error, Type::Service, true, "Failed to connect to Unix socket: {}", e); return Err(anyhow::anyhow!("无法连接到服务Unix套接字: {}", e)); } }; @@ -310,7 +310,7 @@ pub async fn send_ipc_request( let response: IpcResponse = match serde_json::from_slice::(&response_bytes) { Ok(r) => r, Err(e) => { - logging!(error, Type::Service, true, "服务响应解析失败: {}", e,); + logging!(error, Type::Service, true, "Failed to parse service response: {}", e,); return Err(anyhow::anyhow!("解析响应失败: {}", e)); } }; @@ -323,7 +323,7 @@ pub async fn send_ipc_request( } } Err(e) => { - logging!(error, Type::Service, true, "验证响应签名时出错: {}", e); + logging!(error, Type::Service, true, "Error verifying response signature: {}", e); return Err(e); } } @@ -332,7 +332,7 @@ pub async fn send_ipc_request( info, Type::Service, true, - "IPC请求完成: 命令={}, 成功={}", + "IPC request completed: command={}, success={}", command_type, response.success ); diff --git a/src-tauri/src/core/sysopt.rs b/src-tauri/src/core/sysopt.rs index e7c4b4c5..350570d8 100644 --- a/src-tauri/src/core/sysopt.rs +++ b/src-tauri/src/core/sysopt.rs @@ -63,7 +63,7 @@ impl Sysopt { let proxy_manager = EventDrivenProxyManager::global(); proxy_manager.notify_app_started(); - log::info!(target: "app", "已启用事件驱动代理守卫"); + log::info!(target: "app", "Event-driven proxy guard enabled"); Ok(()) } @@ -193,7 +193,7 @@ impl Sysopt { let mut autoproxy = match Autoproxy::get_auto_proxy() { Ok(ap) => ap, Err(e) => { - log::warn!(target: "app", "重置代理时获取自动代理配置失败: {e}, 使用默认配置"); + log::warn!(target: "app", "Failed to get auto proxy config while resetting: {e}, using default config"); Autoproxy { enable: false, url: "".to_string(), @@ -248,14 +248,14 @@ impl Sysopt { { if is_enable { if let Err(e) = startup_shortcut::create_shortcut() { - log::error!(target: "app", "创建启动快捷方式失败: {}", e); + log::error!(target: "app", "Failed to create startup shortcut: {}", e); // 如果快捷方式创建失败,回退到原来的方法 self.try_original_autostart_method(is_enable); } else { return Ok(()); } } else if let Err(e) = startup_shortcut::remove_shortcut() { - log::error!(target: "app", "删除启动快捷方式失败: {}", e); + log::error!(target: "app", "Failed to remove startup shortcut: {}", e); self.try_original_autostart_method(is_enable); } else { return Ok(()); @@ -290,11 +290,11 @@ impl Sysopt { { match startup_shortcut::is_shortcut_enabled() { Ok(enabled) => { - log::info!(target: "app", "快捷方式自启动状态: {}", enabled); + log::info!(target: "app", "Shortcut auto-launch state: {}", enabled); return Ok(enabled); } Err(e) => { - log::error!(target: "app", "检查快捷方式失败,尝试原来的方法: {}", e); + log::error!(target: "app", "Failed to check shortcut, falling back to original method: {}", e); } } } diff --git a/src-tauri/src/core/timer.rs b/src-tauri/src/core/timer.rs index 8f38275d..206566fb 100644 --- a/src-tauri/src/core/timer.rs +++ b/src-tauri/src/core/timer.rs @@ -73,7 +73,7 @@ impl Timer { logging!( info, Type::Timer, - "已注册的定时任务数量: {}", + "Registered timer task count: {}", timer_map.len() ); @@ -81,7 +81,7 @@ impl Timer { logging!( info, Type::Timer, - "注册了定时任务 - uid={}, interval={}min, task_id={}", + "Registered timer task - uid={}, interval={}min, task_id={}", uid, task.interval_minutes, task.task_id @@ -100,7 +100,7 @@ impl Timer { let uid = item.uid.as_ref()?; if interval > 0 && cur_timestamp - updated >= interval * 60 { - logging!(info, Type::Timer, "需要立即更新的配置: uid={}", uid); + logging!(info, Type::Timer, "Profile requires immediate update: uid={}", uid); Some(uid.clone()) } else { None @@ -116,7 +116,7 @@ impl Timer { logging!( info, Type::Timer, - "需要立即更新的配置数量: {}", + "Number of profiles requiring immediate update: {}", profiles_to_update.len() ); let timer_map = self.timer_map.read(); @@ -124,7 +124,7 @@ impl Timer { for uid in profiles_to_update { if let Some(task) = timer_map.get(&uid) { - logging!(info, Type::Timer, "立即执行任务: uid={}", uid); + logging!(info, Type::Timer, "Executing task immediately: uid={}", uid); if let Err(e) = delay_timer.advance_task(task.task_id) { logging!(warn, Type::Timer, "Failed to advance task {}: {}", uid, e); } @@ -237,7 +237,7 @@ impl Timer { logging!( debug, Type::Timer, - "找到定时更新配置: uid={}, interval={}min", + "Found scheduled update config: uid={}, interval={}min", uid, interval ); @@ -251,7 +251,7 @@ impl Timer { logging!( debug, Type::Timer, - "生成的定时更新配置数量: {}", + "Generated scheduled update config count: {}", new_map.len() ); new_map @@ -267,7 +267,7 @@ impl Timer { logging!( debug, Type::Timer, - "当前 timer_map 大小: {}", + "Current timer_map size: {}", timer_map.len() ); @@ -279,7 +279,7 @@ impl Timer { logging!( debug, Type::Timer, - "定时任务间隔变更: uid={}, 旧={}, 新={}", + "Timer task interval changed: uid={}, old={}, new={}", uid, task.interval_minutes, interval @@ -288,12 +288,12 @@ impl Timer { } None => { // Task no longer needed - logging!(debug, Type::Timer, "定时任务已删除: uid={}", uid); + logging!(debug, Type::Timer, "Timer task removed: uid={}", uid); diff_map.insert(uid.clone(), DiffFlag::Del(task.task_id)); } _ => { // Task exists with same interval, no change needed - logging!(debug, Type::Timer, "定时任务保持不变: uid={}", uid); + logging!(debug, Type::Timer, "Timer task unchanged: uid={}", uid); } } } @@ -306,7 +306,7 @@ impl Timer { logging!( debug, Type::Timer, - "新增定时任务: uid={}, interval={}min", + "Added timer task: uid={}, interval={}min", uid, interval ); @@ -321,6 +321,7 @@ impl Timer { } logging!(debug, Type::Timer, "定时任务变更数量: {}", diff_map.len()); + logging!(debug, Type::Timer, "Number of timer task changes: {}", diff_map.len()); diff_map } @@ -363,13 +364,13 @@ impl Timer { /// Get next update time for a profile pub fn get_next_update_time(&self, uid: &str) -> Option { - logging!(info, Type::Timer, "获取下次更新时间,uid={}", uid); + logging!(info, Type::Timer, "Getting next update time, uid={}", uid); let timer_map = self.timer_map.read(); let task = match timer_map.get(uid) { Some(t) => t, None => { - logging!(warn, Type::Timer, "找不到对应的定时任务,uid={}", uid); + logging!(warn, Type::Timer, "Corresponding timer task not found, uid={}", uid); return None; } }; @@ -380,7 +381,7 @@ impl Timer { let items = match profiles.get_items() { Some(i) => i, None => { - logging!(warn, Type::Timer, "获取配置列表失败"); + logging!(warn, Type::Timer, "Failed to get profile list"); return None; } }; @@ -388,7 +389,7 @@ impl Timer { let profile = match items.iter().find(|item| item.uid.as_deref() == Some(uid)) { Some(p) => p, None => { - logging!(warn, Type::Timer, "找不到对应的配置,uid={}", uid); + logging!(warn, Type::Timer, "Corresponding profile not found, uid={}", uid); return None; } }; @@ -401,7 +402,7 @@ impl Timer { logging!( info, Type::Timer, - "计算得到下次更新时间: {}, uid={}", + "Calculated next update time: {}, uid={}", next_time, uid ); @@ -410,7 +411,7 @@ impl Timer { logging!( warn, Type::Timer, - "更新时间或间隔无效,updated={}, interval={}", + "Invalid update time or interval, updated={}, interval={}", updated, task.interval_minutes ); @@ -442,7 +443,7 @@ impl Timer { logging!( info, Type::Timer, - "配置 {} 是否为当前激活配置: {}", + "Is profile {} currently active: {}", uid, is_current ); diff --git a/src-tauri/src/core/tray/mod.rs b/src-tauri/src/core/tray/mod.rs index cd3a3f39..914fe5fb 100644 --- a/src-tauri/src/core/tray/mod.rs +++ b/src-tauri/src/core/tray/mod.rs @@ -46,7 +46,7 @@ fn should_handle_tray_click() -> bool { *last_click = now; true } else { - log::debug!(target: "app", "托盘点击被防抖机制忽略,距离上次点击 {:?}ms", + log::debug!(target: "app", "Tray click ignored by debounce; time since last click: {:?}ms", now.duration_since(*last_click).as_millis()); false } @@ -231,7 +231,7 @@ impl Tray { let app_handle = match handle::Handle::global().app_handle() { Some(handle) => handle, None => { - log::warn!(target: "app", "更新托盘菜单失败: app_handle不存在"); + log::warn!(target: "app", "Failed to update tray menu: app_handle not found"); return Ok(()); } }; @@ -279,11 +279,11 @@ impl Tray { profile_uid_and_name, is_lightweight_mode, )?)); - log::debug!(target: "app", "托盘菜单更新成功"); + log::debug!(target: "app", "Tray menu updated successfully"); Ok(()) } None => { - log::warn!(target: "app", "更新托盘菜单失败: 托盘不存在"); + log::warn!(target: "app", "Failed to update tray menu: tray not found"); Ok(()) } } @@ -295,7 +295,7 @@ impl Tray { let app_handle = match handle::Handle::global().app_handle() { Some(handle) => handle, None => { - log::warn!(target: "app", "更新托盘图标失败: app_handle不存在"); + log::warn!(target: "app", "Failed to update tray icon: app_handle not found"); return Ok(()); } }; @@ -303,7 +303,7 @@ impl Tray { let tray = match app_handle.tray_by_id("main") { Some(tray) => tray, None => { - log::warn!(target: "app", "更新托盘图标失败: 托盘不存在"); + log::warn!(target: "app", "Failed to update tray icon: tray not found"); return Ok(()); } }; @@ -332,7 +332,7 @@ impl Tray { let app_handle = match handle::Handle::global().app_handle() { Some(handle) => handle, None => { - log::warn!(target: "app", "更新托盘图标失败: app_handle不存在"); + log::warn!(target: "app", "Failed to update tray icon: app_handle not found"); return Ok(()); } }; @@ -340,7 +340,7 @@ impl Tray { let tray = match app_handle.tray_by_id("main") { Some(tray) => tray, None => { - log::warn!(target: "app", "更新托盘图标失败: 托盘不存在"); + log::warn!(target: "app", "Failed to update tray icon: tray not found"); return Ok(()); } }; @@ -376,7 +376,7 @@ impl Tray { let app_handle = match handle::Handle::global().app_handle() { Some(handle) => handle, None => { - log::warn!(target: "app", "更新托盘提示失败: app_handle不存在"); + log::warn!(target: "app", "Failed to update tray tooltip: app_handle not found"); return Ok(()); } }; @@ -384,7 +384,7 @@ impl Tray { let version = match VERSION.get() { Some(v) => v, None => { - log::warn!(target: "app", "更新托盘提示失败: 版本信息不存在"); + log::warn!(target: "app", "Failed to update tray tooltip: version info not found"); return Ok(()); } }; @@ -423,7 +423,7 @@ impl Tray { current_profile_name ))); } else { - log::warn!(target: "app", "更新托盘提示失败: 托盘不存在"); + log::warn!(target: "app", "Failed to update tray tooltip: tray not found"); } Ok(()) @@ -443,7 +443,7 @@ impl Tray { pub fn unsubscribe_traffic(&self) {} pub fn create_tray_from_handle(&self, app_handle: &AppHandle) -> Result<()> { - log::info!(target: "app", "正在从AppHandle创建系统托盘"); + log::info!(target: "app", "Creating system tray from AppHandle"); // 获取图标 let icon_bytes = TrayState::get_common_tray_icon().1; @@ -491,20 +491,20 @@ impl Tray { "tun_mode" => feat::toggle_tun_mode(None), "main_window" => { use crate::utils::window_manager::WindowManager; - log::info!(target: "app", "Tray点击事件: 显示主窗口"); + log::info!(target: "app", "Tray click: show main window"); if crate::module::lightweight::is_in_lightweight_mode() { - log::info!(target: "app", "当前在轻量模式,正在退出轻量模式"); + log::info!(target: "app", "Currently in lightweight mode, exiting lightweight mode"); crate::module::lightweight::exit_lightweight_mode(); } let result = WindowManager::show_main_window(); - log::info!(target: "app", "窗口显示结果: {result:?}"); + log::info!(target: "app", "Window show result: {result:?}"); } _ => {} } } }); tray.on_menu_event(on_menu_event); - log::info!(target: "app", "系统托盘创建成功"); + log::info!(target: "app", "System tray created successfully"); Ok(()) } @@ -718,18 +718,18 @@ fn on_menu_event(_: &AppHandle, event: MenuEvent) { } "open_window" => { use crate::utils::window_manager::WindowManager; - log::info!(target: "app", "托盘菜单点击: 打开窗口"); + log::info!(target: "app", "Tray menu click: open window"); if !should_handle_tray_click() { return; } if crate::module::lightweight::is_in_lightweight_mode() { - log::info!(target: "app", "当前在轻量模式,正在退出"); + log::info!(target: "app", "Currently in lightweight mode, exiting"); crate::module::lightweight::exit_lightweight_mode(); } let result = WindowManager::show_main_window(); - log::info!(target: "app", "窗口显示结果: {result:?}"); + log::info!(target: "app", "Window show result: {result:?}"); } "system_proxy" => { feat::toggle_system_proxy(); @@ -754,7 +754,7 @@ fn on_menu_event(_: &AppHandle, event: MenuEvent) { if was_lightweight { use crate::utils::window_manager::WindowManager; let result = WindowManager::show_main_window(); - log::info!(target: "app", "退出轻量模式后显示主窗口: {result:?}"); + log::info!(target: "app", "Show main window after exiting lightweight mode: {result:?}"); } } "quit" => { @@ -768,6 +768,6 @@ fn on_menu_event(_: &AppHandle, event: MenuEvent) { } if let Err(e) = Tray::global().update_all_states() { - log::warn!(target: "app", "更新托盘状态失败: {e}"); + log::warn!(target: "app", "Failed to update tray state: {e}"); } } diff --git a/src-tauri/src/feat/profile.rs b/src-tauri/src/feat/profile.rs index 83b840a6..c3819bca 100644 --- a/src-tauri/src/feat/profile.rs +++ b/src-tauri/src/feat/profile.rs @@ -31,7 +31,7 @@ pub async fn update_profile( option: Option, auto_refresh: Option, ) -> Result<()> { - logging!(info, Type::Config, true, "[订阅更新] 开始更新订阅 {}", uid); + logging!(info, Type::Config, true, "[Subscription Update] Start updating subscription {}", uid); let auto_refresh = auto_refresh.unwrap_or(true); // 默认为true,保持兼容性 let url_opt = { @@ -41,14 +41,14 @@ pub async fn update_profile( let is_remote = item.itype.as_ref().is_some_and(|s| s == "remote"); if !is_remote { - log::info!(target: "app", "[订阅更新] {uid} 不是远程订阅,跳过更新"); + log::info!(target: "app", "[Subscription Update] {uid} is not a remote subscription, skipping update"); None // 非远程订阅直接更新 } else if item.url.is_none() { - log::warn!(target: "app", "[订阅更新] {uid} 缺少URL,无法更新"); + log::warn!(target: "app", "[Subscription Update] {uid} is missing URL, cannot update"); bail!("failed to get the profile item url"); } else { log::info!(target: "app", - "[订阅更新] {} 是远程订阅,URL: {}", + "[Subscription Update] {} is a remote subscription, URL: {}", uid, item.url.clone().unwrap() ); @@ -58,24 +58,24 @@ pub async fn update_profile( let should_update = match url_opt { Some((url, opt)) => { - log::info!(target: "app", "[订阅更新] 开始下载新的订阅内容"); + log::info!(target: "app", "[Subscription Update] Start downloading new subscription content"); let merged_opt = PrfOption::merge(opt.clone(), option.clone()); // 尝试使用正常设置更新 match PrfItem::from_url(&url, None, None, merged_opt.clone()).await { Ok(item) => { - log::info!(target: "app", "[订阅更新] 更新订阅配置成功"); + log::info!(target: "app", "[Subscription Update] Subscription config updated successfully"); let profiles = Config::profiles(); let mut profiles = profiles.latest(); profiles.update_item(uid.clone(), item)?; let is_current = Some(uid.clone()) == profiles.get_current(); - log::info!(target: "app", "[订阅更新] 是否为当前使用的订阅: {is_current}"); + log::info!(target: "app", "[Subscription Update] Is current active subscription: {is_current}"); is_current && auto_refresh } Err(err) => { // 首次更新失败,尝试使用Clash代理 - log::warn!(target: "app", "[订阅更新] 正常更新失败: {err},尝试使用Clash代理更新"); + log::warn!(target: "app", "[Subscription Update] Normal update failed: {err}, trying to update via Clash proxy"); // 发送通知 handle::Handle::notice_message("update_retry_with_clash", uid.clone()); @@ -92,7 +92,7 @@ pub async fn update_profile( // 使用Clash代理重试 match PrfItem::from_url(&url, None, None, Some(fallback_opt)).await { Ok(mut item) => { - log::info!(target: "app", "[订阅更新] 使用Clash代理更新成功"); + log::info!(target: "app", "[Subscription Update] Update via Clash proxy succeeded"); // 恢复原始代理设置到item if let Some(option) = item.option.as_mut() { @@ -112,11 +112,11 @@ pub async fn update_profile( handle::Handle::notice_message("update_with_clash_proxy", profile_name); let is_current = Some(uid.clone()) == profiles.get_current(); - log::info!(target: "app", "[订阅更新] 是否为当前使用的订阅: {is_current}"); + log::info!(target: "app", "[Subscription Update] Is current active subscription: {is_current}"); is_current && auto_refresh } Err(retry_err) => { - log::error!(target: "app", "[订阅更新] 使用Clash代理更新仍然失败: {retry_err}"); + log::error!(target: "app", "[Subscription Update] Update via Clash proxy still failed: {retry_err}"); handle::Handle::notice_message( "update_failed_even_with_clash", format!("{retry_err}"), @@ -131,14 +131,14 @@ pub async fn update_profile( }; if should_update { - logging!(info, Type::Config, true, "[订阅更新] 更新内核配置"); + logging!(info, Type::Config, true, "[Subscription Update] Update core configuration"); match CoreManager::global().update_config().await { Ok(_) => { - logging!(info, Type::Config, true, "[订阅更新] 更新成功"); + logging!(info, Type::Config, true, "[Subscription Update] Update succeeded"); handle::Handle::refresh_clash(); } Err(err) => { - logging!(error, Type::Config, true, "[订阅更新] 更新失败: {}", err); + logging!(error, Type::Config, true, "[Subscription Update] Update failed: {}", err); handle::Handle::notice_message("update_failed", format!("{err}")); log::error!(target: "app", "{err}"); } diff --git a/src-tauri/src/feat/window.rs b/src-tauri/src/feat/window.rs index ba61640b..c1fd92c7 100644 --- a/src-tauri/src/feat/window.rs +++ b/src-tauri/src/feat/window.rs @@ -25,14 +25,14 @@ fn open_or_close_dashboard_internal(bypass_debounce: bool) { use crate::process::AsyncHandler; use crate::utils::window_manager::WindowManager; - log::info!(target: "app", "Attempting to open/close dashboard (绕过防抖: {bypass_debounce})"); + log::info!(target: "app", "Attempting to open/close dashboard (bypass debounce: {bypass_debounce})"); // 热键调用调度到主线程执行,避免 WebView 创建死锁 if bypass_debounce { - log::info!(target: "app", "热键调用,调度到主线程执行窗口操作"); + log::info!(target: "app", "Hotkey invoked, dispatching window operation to main thread"); AsyncHandler::spawn(move || async move { - log::info!(target: "app", "主线程中执行热键窗口操作"); + log::info!(target: "app", "Executing hotkey window operation on main thread"); if crate::module::lightweight::is_in_lightweight_mode() { log::info!(target: "app", "Currently in lightweight mode, exiting lightweight mode"); @@ -64,7 +64,7 @@ fn open_or_close_dashboard_internal(bypass_debounce: bool) { /// 异步优化的应用退出函数 pub fn quit() { use crate::process::AsyncHandler; - logging!(debug, Type::System, true, "启动退出流程"); + logging!(debug, Type::System, true, "Start exit process"); // 获取应用句柄并设置退出标志 let app_handle = handle::Handle::global().app_handle().unwrap(); @@ -73,19 +73,19 @@ pub fn quit() { // 优先关闭窗口,提供立即反馈 if let Some(window) = handle::Handle::global().get_window() { let _ = window.hide(); - log::info!(target: "app", "窗口已隐藏"); + log::info!(target: "app", "Window hidden"); } // 使用异步任务处理资源清理,避免阻塞 AsyncHandler::spawn(move || async move { - logging!(info, Type::System, true, "开始异步清理资源"); + logging!(info, Type::System, true, "Start asynchronous resource cleanup"); let cleanup_result = clean_async().await; logging!( info, Type::System, true, - "资源清理完成,退出代码: {}", + "Resource cleanup completed, exit code: {}", if cleanup_result { 0 } else { 1 } ); app_handle.exit(if cleanup_result { 0 } else { 1 }); @@ -95,7 +95,7 @@ pub fn quit() { async fn clean_async() -> bool { use tokio::time::{timeout, Duration}; - logging!(info, Type::System, true, "开始执行异步清理操作..."); + logging!(info, Type::System, true, "Start executing asynchronous cleanup..."); // 1. 处理TUN模式 let tun_task = async { @@ -112,11 +112,11 @@ async fn clean_async() -> bool { .await { Ok(_) => { - log::info!(target: "app", "TUN模式已禁用"); + log::info!(target: "app", "TUN mode disabled"); true } Err(_) => { - log::warn!(target: "app", "禁用TUN模式超时"); + log::warn!(target: "app", "Timeout disabling TUN mode"); false } } @@ -134,11 +134,11 @@ async fn clean_async() -> bool { .await { Ok(_) => { - log::info!(target: "app", "系统代理已重置"); + log::info!(target: "app", "System proxy reset"); true } Err(_) => { - log::warn!(target: "app", "重置系统代理超时"); + log::warn!(target: "app", "Timeout resetting system proxy"); false } } @@ -148,11 +148,11 @@ async fn clean_async() -> bool { let core_task = async { match timeout(Duration::from_secs(3), CoreManager::global().stop_core()).await { Ok(_) => { - log::info!(target: "app", "核心服务已停止"); + log::info!(target: "app", "Core service stopped"); true } Err(_) => { - log::warn!(target: "app", "停止核心服务超时"); + log::warn!(target: "app", "Timeout stopping core service"); false } } @@ -168,11 +168,11 @@ async fn clean_async() -> bool { .await { Ok(_) => { - log::info!(target: "app", "DNS设置已恢复"); + log::info!(target: "app", "DNS settings restored"); true } Err(_) => { - log::warn!(target: "app", "恢复DNS设置超时"); + log::warn!(target: "app", "Timeout restoring DNS settings"); false } } @@ -192,7 +192,7 @@ async fn clean_async() -> bool { info, Type::System, true, - "异步清理操作完成 - TUN: {}, 代理: {}, 核心: {}, DNS: {}, 总体: {}", + "Asynchronous cleanup completed - TUN: {}, Proxy: {}, Core: {}, DNS: {}, Overall: {}", tun_success, proxy_success, core_success, @@ -209,7 +209,7 @@ pub fn clean() -> bool { let (tx, rx) = std::sync::mpsc::channel(); AsyncHandler::spawn(move || async move { - logging!(info, Type::System, true, "开始执行清理操作..."); + logging!(info, Type::System, true, "Start executing cleanup..."); // 使用已有的异步清理函数 let cleanup_result = clean_async().await; @@ -220,7 +220,7 @@ pub fn clean() -> bool { match rx.recv_timeout(std::time::Duration::from_secs(8)) { Ok(result) => { - logging!(info, Type::System, true, "清理操作完成,结果: {}", result); + logging!(info, Type::System, true, "Cleanup completed, result: {}", result); result } Err(_) => { @@ -228,7 +228,7 @@ pub fn clean() -> bool { warn, Type::System, true, - "清理操作超时,返回成功状态避免阻塞" + "Cleanup timed out, returning success to avoid blocking" ); true } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 626606ed..5a246779 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -115,7 +115,7 @@ pub fn run() { .plugin(tauri_plugin_shell::init()) .plugin(tauri_plugin_deep_link::init()) .setup(|app| { - logging!(info, Type::Setup, true, "开始应用初始化..."); + logging!(info, Type::Setup, true, "Starting app initialization..."); let mut auto_start_plugin_builder = tauri_plugin_autostart::Builder::new(); #[cfg(target_os = "macos")] { @@ -128,7 +128,7 @@ pub fn run() { #[cfg(any(target_os = "linux", all(debug_assertions, windows)))] { use tauri_plugin_deep_link::DeepLinkExt; - logging!(info, Type::Setup, true, "注册深层链接..."); + logging!(info, Type::Setup, true, "Registering deep links..."); logging_error!(Type::System, true, app.deep_link().register_all()); } @@ -144,7 +144,7 @@ pub fn run() { }); // 窗口管理 - logging!(info, Type::Setup, true, "初始化窗口状态管理..."); + logging!(info, Type::Setup, true, "Initializing window state management..."); let window_state_plugin = tauri_plugin_window_state::Builder::new() .with_filename("window_state.json") .with_state_flags(tauri_plugin_window_state::StateFlags::default()) @@ -154,7 +154,7 @@ pub fn run() { // 异步处理 let app_handle = app.handle().clone(); AsyncHandler::spawn(move || async move { - logging!(info, Type::Setup, true, "异步执行应用设置..."); + logging!(info, Type::Setup, true, "Executing app setup asynchronously..."); match timeout( Duration::from_secs(30), resolve::resolve_setup_async(&app_handle), @@ -162,35 +162,35 @@ pub fn run() { .await { Ok(_) => { - logging!(info, Type::Setup, true, "应用设置成功完成"); + logging!(info, Type::Setup, true, "App setup completed successfully"); } Err(_) => { logging!( error, Type::Setup, true, - "应用设置超时(30秒),继续执行后续流程" + "App setup timed out (30s), continuing with subsequent steps" ); } } }); - logging!(info, Type::Setup, true, "执行主要设置操作..."); + logging!(info, Type::Setup, true, "Executing main setup operations..."); - logging!(info, Type::Setup, true, "初始化AppHandleManager..."); + logging!(info, Type::Setup, true, "Initializing AppHandleManager..."); AppHandleManager::global().init(app.handle().clone()); - logging!(info, Type::Setup, true, "初始化核心句柄..."); + logging!(info, Type::Setup, true, "Initializing core handle..."); core::handle::Handle::global().init(app.handle()); - logging!(info, Type::Setup, true, "初始化配置..."); + logging!(info, Type::Setup, true, "Initializing config..."); if let Err(e) = utils::init::init_config() { - logging!(error, Type::Setup, true, "初始化配置失败: {}", e); + logging!(error, Type::Setup, true, "Failed to initialize config: {}", e); } - logging!(info, Type::Setup, true, "初始化资源..."); + logging!(info, Type::Setup, true, "Initializing resources..."); if let Err(e) = utils::init::init_resources() { - logging!(error, Type::Setup, true, "初始化资源失败: {}", e); + logging!(error, Type::Setup, true, "Failed to initialize resources: {}", e); } app.manage(Mutex::new(state::proxy::CmdProxyState::default())); @@ -204,7 +204,7 @@ pub fn run() { } }); - logging!(info, Type::Setup, true, "初始化完成,继续执行"); + logging!(info, Type::Setup, true, "Initialization completed, continuing"); Ok(()) }) .invoke_handler(tauri::generate_handler![ @@ -324,7 +324,7 @@ pub fn run() { app.run(|app_handle, e| match e { tauri::RunEvent::Ready | tauri::RunEvent::Resumed => { - logging!(info, Type::System, true, "应用就绪或恢复"); + logging!(info, Type::System, true, "App ready or resumed"); AppHandleManager::global().init(app_handle.clone()); #[cfg(target_os = "macos")] { @@ -332,7 +332,7 @@ pub fn run() { .get_handle() .get_webview_window("main") { - logging!(info, Type::Window, true, "设置macOS窗口标题"); + logging!(info, Type::Window, true, "Setting macOS window title"); let _ = window.set_title("Koala Clash"); } } @@ -376,7 +376,7 @@ pub fn run() { if let Some(window) = core::handle::Handle::global().get_window() { let _ = window.hide(); } else { - logging!(warn, Type::Window, true, "尝试隐藏窗口但窗口不存在"); + logging!(warn, Type::Window, true, "Tried to hide window but it does not exist"); } } tauri::WindowEvent::Focused(true) => { diff --git a/src-tauri/src/state/lightweight.rs b/src-tauri/src/state/lightweight.rs index da960984..29994f6a 100644 --- a/src-tauri/src/state/lightweight.rs +++ b/src-tauri/src/state/lightweight.rs @@ -28,9 +28,9 @@ impl LightWeightState { pub fn set_lightweight_mode(&mut self, value: bool) -> &Self { self.is_lightweight = value; if value { - logging!(info, Type::Lightweight, true, "轻量模式已开启"); + logging!(info, Type::Lightweight, true, "Lightweight mode enabled"); } else { - logging!(info, Type::Lightweight, true, "轻量模式已关闭"); + logging!(info, Type::Lightweight, true, "Lightweight mode disabled"); } self } diff --git a/src-tauri/src/utils/autostart.rs b/src-tauri/src/utils/autostart.rs index 4c7faf06..add94d3d 100644 --- a/src-tauri/src/utils/autostart.rs +++ b/src-tauri/src/utils/autostart.rs @@ -41,9 +41,9 @@ pub fn create_shortcut() -> Result<()> { let startup_dir = get_startup_dir()?; let shortcut_path = startup_dir.join("Koala-Clash.lnk"); - // 如果快捷方式已存在,直接返回成功 + // If the shortcut already exists, return success directly if shortcut_path.exists() { - info!(target: "app", "启动快捷方式已存在"); + info!(target: "app", "Startup shortcut already exists"); return Ok(()); } @@ -59,36 +59,36 @@ pub fn create_shortcut() -> Result<()> { let output = std::process::Command::new("powershell") .args(["-Command", &powershell_command]) - // 隐藏 PowerShell 窗口 + // Hide the PowerShell window .creation_flags(0x08000000) // CREATE_NO_WINDOW .output() - .map_err(|e| anyhow!("执行 PowerShell 命令失败: {}", e))?; + .map_err(|e| anyhow!("Failed to execute PowerShell command: {}", e))?; if !output.status.success() { let error_msg = String::from_utf8_lossy(&output.stderr); - return Err(anyhow!("创建快捷方式失败: {}", error_msg)); + return Err(anyhow!("Failed to create shortcut: {}", error_msg)); } - info!(target: "app", "成功创建启动快捷方式"); + info!(target: "app", "Successfully created startup shortcut"); Ok(()) } -/// 删除快捷方式 +/// Remove the shortcut #[cfg(target_os = "windows")] pub fn remove_shortcut() -> Result<()> { let startup_dir = get_startup_dir()?; let shortcut_path = startup_dir.join("Koala-Clash.lnk"); - // 如果快捷方式不存在,直接返回成功 + // If the shortcut does not exist, return success directly if !shortcut_path.exists() { - info!(target: "app", "启动快捷方式不存在,无需删除"); + info!(target: "app", "Startup shortcut does not exist, nothing to remove"); return Ok(()); } - // 删除快捷方式 - fs::remove_file(&shortcut_path).map_err(|e| anyhow!("删除快捷方式失败: {}", e))?; + // Delete the shortcut + fs::remove_file(&shortcut_path).map_err(|e| anyhow!("Failed to delete shortcut: {}", e))?; - info!(target: "app", "成功删除启动快捷方式"); + info!(target: "app", "Successfully removed startup shortcut"); Ok(()) } diff --git a/src-tauri/src/utils/window_manager.rs b/src-tauri/src/utils/window_manager.rs index eea075c9..0f538a38 100644 --- a/src-tauri/src/utils/window_manager.rs +++ b/src-tauri/src/utils/window_manager.rs @@ -53,7 +53,7 @@ fn get_window_operation_debounce() -> &'static Mutex { fn should_handle_window_operation() -> bool { if WINDOW_OPERATION_IN_PROGRESS.load(Ordering::Acquire) { - log::warn!(target: "app", "[防抖] 窗口操作已在进行中,跳过重复调用"); + log::warn!(target: "app", "[debounce] Window operation already in progress, skipping duplicate call"); return false; } @@ -62,16 +62,16 @@ fn should_handle_window_operation() -> bool { let now = Instant::now(); let elapsed = now.duration_since(*last_operation); - log::debug!(target: "app", "[防抖] 检查窗口操作间隔: {}ms (需要>={}ms)", + log::debug!(target: "app", "[debounce] Checking window operation interval: {}ms (need >={}ms)", elapsed.as_millis(), WINDOW_OPERATION_DEBOUNCE_MS); if elapsed >= Duration::from_millis(WINDOW_OPERATION_DEBOUNCE_MS) { *last_operation = now; WINDOW_OPERATION_IN_PROGRESS.store(true, Ordering::Release); - log::info!(target: "app", "[防抖] 窗口操作被允许执行"); + log::info!(target: "app", "[debounce] Window operation allowed to execute"); true } else { - log::warn!(target: "app", "[防抖] 窗口操作被防抖机制忽略,距离上次操作 {}ms < {}ms", + log::warn!(target: "app", "[debounce] Window operation ignored by debounce: {}ms since last < {}ms", elapsed.as_millis(), WINDOW_OPERATION_DEBOUNCE_MS); false } From 9c33f007a13eb987b54252345bf1aaadb1130dd5 Mon Sep 17 00:00:00 2001 From: vffuunnyy Date: Sat, 16 Aug 2025 15:22:38 +0700 Subject: [PATCH 3/5] refactor: fix formating in rust --- src-tauri/src/cmd/profile.rs | 193 +++++++++++++++++++-------- src-tauri/src/config/prfitem.rs | 2 +- src-tauri/src/config/verge.rs | 10 +- src-tauri/src/core/core.rs | 212 +++++++++++++++++++++++++----- src-tauri/src/core/service.rs | 116 +++++++++++++--- src-tauri/src/core/service_ipc.rs | 116 +++++++++++++--- src-tauri/src/core/timer.rs | 28 +++- src-tauri/src/core/tray/mod.rs | 1 - src-tauri/src/enhance/mod.rs | 2 +- src-tauri/src/enhance/script.rs | 4 +- src-tauri/src/feat/profile.rs | 30 ++++- src-tauri/src/feat/window.rs | 22 +++- src-tauri/src/lib.rs | 60 +++++++-- src-tauri/src/utils/resolve.rs | 5 +- 14 files changed, 654 insertions(+), 147 deletions(-) diff --git a/src-tauri/src/cmd/profile.rs b/src-tauri/src/cmd/profile.rs index 5c72968b..3836cfdc 100644 --- a/src-tauri/src/cmd/profile.rs +++ b/src-tauri/src/cmd/profile.rs @@ -6,14 +6,14 @@ use crate::{ utils::{dirs, help, logging::Type}, wrap_err, }; +use base64::{engine::general_purpose::STANDARD, Engine as _}; +use percent_encoding::percent_decode_str; +use serde_yaml::Value; +use std::collections::BTreeMap; use std::sync::atomic::{AtomicU64, Ordering}; use std::time::Duration; use tokio::sync::{Mutex, RwLock}; -use std::collections::BTreeMap; use url::Url; -use serde_yaml::Value; -use base64::{engine::general_purpose::STANDARD, Engine as _}; -use percent_encoding::percent_decode_str; // 全局互斥锁防止并发配置更新 static PROFILE_UPDATE_MUTEX: Mutex<()> = Mutex::const_new(()); @@ -138,20 +138,34 @@ pub async fn import_profile(url: String, option: Option) -> CmdResult let profiles = Config::profiles(); let profiles = profiles.latest(); - profiles.items.as_ref() + profiles + .items + .as_ref() .and_then(|items| items.iter().find(|item| item.url.as_deref() == Some(&url))) .and_then(|item| item.uid.clone()) }; if let Some(uid) = existing_uid { - logging!(info, Type::Cmd, true, "The profile with URL {} already exists (UID: {}). Running the update...", url, uid); + logging!( + info, + Type::Cmd, + true, + "The profile with URL {} already exists (UID: {}). Running the update...", + url, + uid + ); update_profile(uid, option).await } else { - logging!(info, Type::Cmd, true, "Profile with URL {} not found. Create a new one...", url); + logging!( + info, + Type::Cmd, + true, + "Profile with URL {} not found. Create a new one...", + url + ); let item = wrap_err!(PrfItem::from_url(&url, None, None, option).await)?; wrap_err!(Config::profiles().data().append_item(item)) } - } /// 重新排序配置文件 @@ -181,20 +195,29 @@ pub async fn delete_profile(index: String) -> CmdResult { { let profiles_config = Config::profiles(); let mut profiles_data = profiles_config.data(); - should_update = profiles_data.delete_item(index.clone()).map_err(|e| e.to_string())?; + should_update = profiles_data + .delete_item(index.clone()) + .map_err(|e| e.to_string())?; - let was_last_profile = profiles_data.items.as_ref().map_or(true, |items| { - !items.iter().any(|item| - item.itype == Some("remote".to_string()) || item.itype == Some("local".to_string()) - ) + let was_last_profile = profiles_data.items.as_ref().is_none_or(|items| { + !items + .iter() + .any(|item| matches!(item.itype.as_deref(), Some("remote") | Some("local"))) }); if was_last_profile { - logging!(info, Type::Cmd, true, "The last profile has been deleted. Disabling proxy modes..."); + logging!( + info, + Type::Cmd, + true, + "The last profile has been deleted. Disabling proxy modes..." + ); let verge_config = Config::verge(); let mut verge_data = verge_config.data(); - if verge_data.enable_tun_mode == Some(true) || verge_data.enable_system_proxy == Some(true) { + if verge_data.enable_tun_mode == Some(true) + || verge_data.enable_system_proxy == Some(true) + { verge_data.enable_tun_mode = Some(false); verge_data.enable_system_proxy = Some(false); verge_data.save_file().map_err(|e| e.to_string())?; @@ -696,23 +719,30 @@ pub fn get_next_update_time(uid: String) -> CmdResult> { Ok(next_time) } - #[tauri::command] pub async fn update_profiles_on_startup() -> CmdResult { - logging!(info, Type::Cmd, true, "Checking profiles for updates at startup..."); + logging!( + info, + Type::Cmd, + true, + "Checking profiles for updates at startup..." + ); let profiles_to_update = { let profiles = Config::profiles(); let profiles = profiles.latest(); - profiles.items.as_ref() - .map_or_else( - Vec::new, - |items| items.iter() - .filter(|item| item.option.as_ref().is_some_and(|opt| opt.update_always == Some(true))) - .filter_map(|item| item.uid.clone()) - .collect() - ) + profiles.items.as_ref().map_or_else(Vec::new, |items| { + items + .iter() + .filter(|item| { + item.option + .as_ref() + .is_some_and(|opt| opt.update_always == Some(true)) + }) + .filter_map(|item| item.uid.clone()) + .collect() + }) }; if profiles_to_update.is_empty() { @@ -720,7 +750,13 @@ pub async fn update_profiles_on_startup() -> CmdResult { return Ok(()); } - logging!(info, Type::Cmd, true, "Found profiles to update: {:?}", profiles_to_update); + logging!( + info, + Type::Cmd, + true, + "Found profiles to update: {:?}", + profiles_to_update + ); let mut update_futures = Vec::new(); for uid in profiles_to_update { @@ -729,13 +765,25 @@ pub async fn update_profiles_on_startup() -> CmdResult { let results = futures::future::join_all(update_futures).await; - if results.iter().any(|res| res.is_ok()) { - logging!(info, Type::Cmd, true, "The startup update is complete, restart the kernel..."); - CoreManager::global().update_config().await.map_err(|e| e.to_string())?; + logging!( + info, + Type::Cmd, + true, + "The startup update is complete, restart the kernel..." + ); + CoreManager::global() + .update_config() + .await + .map_err(|e| e.to_string())?; handle::Handle::refresh_clash(); } else { - logging!(warn, Type::Cmd, true, "All updates completed with errors on startup."); + logging!( + warn, + Type::Cmd, + true, + "All updates completed with errors on startup." + ); } Ok(()) @@ -743,7 +791,6 @@ pub async fn update_profiles_on_startup() -> CmdResult { #[tauri::command] pub async fn create_profile_from_share_link(link: String, template_name: String) -> CmdResult { - const DEFAULT_TEMPLATE: &str = r#" mixed-port: 2080 allow-lan: true @@ -1107,14 +1154,18 @@ pub async fn create_profile_from_share_link(link: String, template_name: String) let parsed_url = Url::parse(&link).map_err(|e| e.to_string())?; let scheme = parsed_url.scheme(); - let proxy_name = parsed_url.fragment() + let proxy_name = parsed_url + .fragment() .map(|f| percent_decode_str(f).decode_utf8_lossy().to_string()) .unwrap_or_else(|| "Proxy from Link".to_string()); let mut proxy_map: BTreeMap = BTreeMap::new(); proxy_map.insert("name".into(), proxy_name.clone().into()); proxy_map.insert("type".into(), scheme.into()); - proxy_map.insert("server".into(), parsed_url.host_str().unwrap_or_default().into()); + proxy_map.insert( + "server".into(), + parsed_url.host_str().unwrap_or_default().into(), + ); proxy_map.insert("port".into(), parsed_url.port().unwrap_or(443).into()); proxy_map.insert("udp".into(), true.into()); @@ -1130,16 +1181,29 @@ pub async fn create_profile_from_share_link(link: String, template_name: String) "security" if value == "tls" => { proxy_map.insert("tls".into(), true.into()); } - "flow" => { proxy_map.insert("flow".into(), value.to_string().into()); } - "sni" => { proxy_map.insert("servername".into(), value.to_string().into()); } - "fp" => { proxy_map.insert("client-fingerprint".into(), value.to_string().into()); } - "pbk" => { reality_opts.insert("public-key".into(), value.to_string().into()); } - "sid" => { reality_opts.insert("short-id".into(), value.to_string().into()); } + "flow" => { + proxy_map.insert("flow".into(), value.to_string().into()); + } + "sni" => { + proxy_map.insert("servername".into(), value.to_string().into()); + } + "fp" => { + proxy_map.insert("client-fingerprint".into(), value.to_string().into()); + } + "pbk" => { + reality_opts.insert("public-key".into(), value.to_string().into()); + } + "sid" => { + reality_opts.insert("short-id".into(), value.to_string().into()); + } _ => {} } } if !reality_opts.is_empty() { - proxy_map.insert("reality-opts".into(), serde_yaml::to_value(reality_opts).map_err(|e| e.to_string())?); + proxy_map.insert( + "reality-opts".into(), + serde_yaml::to_value(reality_opts).map_err(|e| e.to_string())?, + ); } } "ss" => { @@ -1155,19 +1219,32 @@ pub async fn create_profile_from_share_link(link: String, template_name: String) "vmess" => { if let Ok(decoded_bytes) = STANDARD.decode(parsed_url.host_str().unwrap_or_default()) { if let Ok(json_str) = String::from_utf8(decoded_bytes) { - if let Ok(vmess_params) = serde_json::from_str::>(&json_str) { - if let Some(add) = vmess_params.get("add") { proxy_map.insert("server".into(), add.clone()); } - if let Some(port) = vmess_params.get("port") { proxy_map.insert("port".into(), port.clone()); } - if let Some(id) = vmess_params.get("id") { proxy_map.insert("uuid".into(), id.clone()); } - if let Some(aid) = vmess_params.get("aid") { proxy_map.insert("alterId".into(), aid.clone()); } - if let Some(net) = vmess_params.get("net") { proxy_map.insert("network".into(), net.clone()); } - if let Some(ps) = vmess_params.get("ps") { proxy_map.insert("name".into(), ps.clone()); } + if let Ok(vmess_params) = + serde_json::from_str::>(&json_str) + { + if let Some(add) = vmess_params.get("add") { + proxy_map.insert("server".into(), add.clone()); + } + if let Some(port) = vmess_params.get("port") { + proxy_map.insert("port".into(), port.clone()); + } + if let Some(id) = vmess_params.get("id") { + proxy_map.insert("uuid".into(), id.clone()); + } + if let Some(aid) = vmess_params.get("aid") { + proxy_map.insert("alterId".into(), aid.clone()); + } + if let Some(net) = vmess_params.get("net") { + proxy_map.insert("network".into(), net.clone()); + } + if let Some(ps) = vmess_params.get("ps") { + proxy_map.insert("name".into(), ps.clone()); + } } } } } - _ => { - } + _ => {} } let mut config: Value = serde_yaml::from_str(template_yaml).map_err(|e| e.to_string())?; @@ -1177,10 +1254,15 @@ pub async fn create_profile_from_share_link(link: String, template_name: String) proxies.push(serde_yaml::to_value(proxy_map).map_err(|e| e.to_string())?); } - if let Some(groups) = config.get_mut("proxy-groups").and_then(|v| v.as_sequence_mut()) { + if let Some(groups) = config + .get_mut("proxy-groups") + .and_then(|v| v.as_sequence_mut()) + { for group in groups.iter_mut() { if let Some(mapping) = group.as_mapping_mut() { - if let Some(proxies_list) = mapping.get_mut("proxies").and_then(|p| p.as_sequence_mut()) { + if let Some(proxies_list) = + mapping.get_mut("proxies").and_then(|p| p.as_sequence_mut()) + { let new_proxies_list: Vec = proxies_list .iter() .map(|p| { @@ -1199,8 +1281,13 @@ pub async fn create_profile_from_share_link(link: String, template_name: String) let new_yaml_content = serde_yaml::to_string(&config).map_err(|e| e.to_string())?; - let item = PrfItem::from_local(proxy_name, "Created from share link".into(), Some(new_yaml_content), None) - .map_err(|e| e.to_string())?; + let item = PrfItem::from_local( + proxy_name, + "Created from share link".into(), + Some(new_yaml_content), + None, + ) + .map_err(|e| e.to_string())?; wrap_err!(Config::profiles().data().append_item(item)) -} \ No newline at end of file +} diff --git a/src-tauri/src/config/prfitem.rs b/src-tauri/src/config/prfitem.rs index 3fd74323..0a47d911 100644 --- a/src-tauri/src/config/prfitem.rs +++ b/src-tauri/src/config/prfitem.rs @@ -326,7 +326,7 @@ impl PrfItem { if let Ok(mut parsed_url) = Url::parse(url) { if parsed_url.set_host(Some(new_domain)).is_ok() { final_url = parsed_url.to_string(); - log::info!(target: "app", "URL host updated to -> {}", final_url); + log::info!(target: "app", "URL host updated to -> {final_url}"); } } } diff --git a/src-tauri/src/config/verge.rs b/src-tauri/src/config/verge.rs index 833a4fce..7b53878c 100644 --- a/src-tauri/src/config/verge.rs +++ b/src-tauri/src/config/verge.rs @@ -340,10 +340,12 @@ impl IVerge { } pub fn new() -> Self { - dirs::verge_path().and_then(|path| help::read_yaml::(&path)).unwrap_or_else(|err| { - log::error!(target: "app", "{err}"); - Self::template() - }) + dirs::verge_path() + .and_then(|path| help::read_yaml::(&path)) + .unwrap_or_else(|err| { + log::error!(target: "app", "{err}"); + Self::template() + }) } pub fn template() -> Self { diff --git a/src-tauri/src/core/core.rs b/src-tauri/src/core/core.rs index 3ce526ce..68ef4488 100644 --- a/src-tauri/src/core/core.rs +++ b/src-tauri/src/core/core.rs @@ -153,7 +153,12 @@ impl CoreManager { } /// 验证运行时配置 pub async fn validate_config(&self) -> Result<(bool, String)> { - logging!(info, Type::Config, true, "Generate temporary config file for validation"); + logging!( + info, + Type::Config, + true, + "Generate temporary config file for validation" + ); let config_path = Config::generate_file(ConfigType::Check)?; let config_path = dirs::path_to_str(&config_path)?; self.validate_config_internal(config_path).await @@ -166,7 +171,12 @@ impl CoreManager { ) -> Result<(bool, String)> { // 检查程序是否正在退出,如果是则跳过验证 if handle::Handle::global().is_exiting() { - logging!(info, Type::Core, true, "App is exiting, skipping validation"); + logging!( + info, + Type::Core, + true, + "App is exiting, skipping validation" + ); return Ok((true, String::new())); } @@ -235,7 +245,12 @@ impl CoreManager { async fn validate_config_internal(&self, config_path: &str) -> Result<(bool, String)> { // 检查程序是否正在退出,如果是则跳过验证 if handle::Handle::global().is_exiting() { - logging!(info, Type::Core, true, "App is exiting, skipping validation"); + logging!( + info, + Type::Core, + true, + "App is exiting, skipping validation" + ); return Ok((true, String::new())); } @@ -253,7 +268,13 @@ impl CoreManager { let app_handle = handle::Handle::global().app_handle().unwrap(); let app_dir = dirs::app_home_dir()?; let app_dir_str = dirs::path_to_str(&app_dir)?; - logging!(info, Type::Config, true, "Validation directory: {}", app_dir_str); + logging!( + info, + Type::Config, + true, + "Validation directory: {}", + app_dir_str + ); // 使用子进程运行clash验证配置 let output = app_handle @@ -271,14 +292,24 @@ impl CoreManager { let has_error = !output.status.success() || error_keywords.iter().any(|&kw| stderr.contains(kw)); - logging!(info, Type::Config, true, "-------- Validation Result --------"); + logging!( + info, + Type::Config, + true, + "-------- Validation Result --------" + ); if !stderr.is_empty() { logging!(info, Type::Config, true, "stderr output:\n{}", stderr); } if has_error { - logging!(info, Type::Config, true, "Errors found, processing error details"); + logging!( + info, + Type::Config, + true, + "Errors found, processing error details" + ); let error_msg = if !stdout.is_empty() { stdout.to_string() } else if !stderr.is_empty() { @@ -299,14 +330,26 @@ impl CoreManager { } /// 只进行文件语法检查,不进行完整验证 async fn validate_file_syntax(&self, config_path: &str) -> Result<(bool, String)> { - logging!(info, Type::Config, true, "Starting file check: {}", config_path); + logging!( + info, + Type::Config, + true, + "Starting file check: {}", + config_path + ); // 读取文件内容 let content = match std::fs::read_to_string(config_path) { Ok(content) => content, Err(err) => { let error_msg = format!("Failed to read file: {err}"); - logging!(error, Type::Config, true, "Failed to read file: {}", error_msg); + logging!( + error, + Type::Config, + true, + "Failed to read file: {}", + error_msg + ); return Ok((false, error_msg)); } }; @@ -320,7 +363,13 @@ impl CoreManager { Err(err) => { // 使用标准化的前缀,以便错误处理函数能正确识别 let error_msg = format!("YAML syntax error: {err}"); - logging!(error, Type::Config, true, "YAML syntax error: {}", error_msg); + logging!( + error, + Type::Config, + true, + "YAML syntax error: {}", + error_msg + ); Ok((false, error_msg)) } } @@ -338,7 +387,13 @@ impl CoreManager { } }; - logging!(debug, Type::Config, true, "Validating script file: {}", path); + logging!( + debug, + Type::Config, + true, + "Validating script file: {}", + path + ); // 使用boa引擎进行基本语法检查 use boa_engine::{Context, Source}; @@ -348,7 +403,13 @@ impl CoreManager { match result { Ok(_) => { - logging!(debug, Type::Config, true, "Script syntax validation passed: {}", path); + logging!( + debug, + Type::Config, + true, + "Script syntax validation passed: {}", + path + ); // 检查脚本是否包含main函数 if !content.contains("function main") @@ -356,7 +417,13 @@ impl CoreManager { && !content.contains("let main") { let error_msg = "Script must contain a main function"; - logging!(warn, Type::Config, true, "Script missing main function: {}", path); + logging!( + warn, + Type::Config, + true, + "Script missing main function: {}", + path + ); //handle::Handle::notice_message("config_validate::script_missing_main", error_msg); return Ok((false, error_msg.to_string())); } @@ -375,14 +442,24 @@ impl CoreManager { pub async fn update_config(&self) -> Result<(bool, String)> { // 检查程序是否正在退出,如果是则跳过完整验证流程 if handle::Handle::global().is_exiting() { - logging!(info, Type::Config, true, "App is exiting, skipping validation"); + logging!( + info, + Type::Config, + true, + "App is exiting, skipping validation" + ); return Ok((true, String::new())); } logging!(info, Type::Config, true, "Starting config update"); // 1. 先生成新的配置内容 - logging!(info, Type::Config, true, "Generating new configuration content"); + logging!( + info, + Type::Config, + true, + "Generating new configuration content" + ); Config::generate().await?; // 2. 验证配置 @@ -396,12 +473,24 @@ impl CoreManager { Ok((true, "something".into())) } Ok((false, error_msg)) => { - logging!(warn, Type::Config, true, "Configuration validation failed: {}", error_msg); + logging!( + warn, + Type::Config, + true, + "Configuration validation failed: {}", + error_msg + ); Config::runtime().discard(); Ok((false, error_msg)) } Err(e) => { - logging!(warn, Type::Config, true, "Error occurred during validation: {}", e); + logging!( + warn, + Type::Config, + true, + "Error occurred during validation: {}", + e + ); Config::runtime().discard(); Err(e) } @@ -435,7 +524,12 @@ impl CoreManager { impl CoreManager { /// 清理多余的 mihomo 进程 async fn cleanup_orphaned_mihomo_processes(&self) -> Result<()> { - logging!(info, Type::Core, true, "Starting cleanup of orphaned mihomo processes"); + logging!( + info, + Type::Core, + true, + "Starting cleanup of orphaned mihomo processes" + ); // 获取当前管理的进程 PID let current_pid = { @@ -482,13 +576,24 @@ impl CoreManager { } } Err(e) => { - logging!(debug, Type::Core, true, "Error occurred while finding processes: {}", e); + logging!( + debug, + Type::Core, + true, + "Error occurred while finding processes: {}", + e + ); } } } if pids_to_kill.is_empty() { - logging!(debug, Type::Core, true, "No orphaned mihomo processes found"); + logging!( + debug, + Type::Core, + true, + "No orphaned mihomo processes found" + ); return Ok(()); } @@ -837,7 +942,12 @@ impl CoreManager { // 当服务安装失败时的回退逻辑 async fn attempt_service_init(&self) -> Result<()> { if service::check_service_needs_reinstall().await { - logging!(info, Type::Core, true, "Service version mismatch or abnormal status, performing reinstallation"); + logging!( + info, + Type::Core, + true, + "Service version mismatch or abnormal status, performing reinstallation" + ); if let Err(e) = service::reinstall_service().await { logging!( warn, @@ -849,7 +959,12 @@ impl CoreManager { return Err(e); } // 如果重装成功,还需要尝试启动服务 - logging!(info, Type::Core, true, "Service reinstalled successfully, attempting to start"); + logging!( + info, + Type::Core, + true, + "Service reinstalled successfully, attempting to start" + ); } if let Err(e) = self.start_core_by_service().await { @@ -905,7 +1020,12 @@ impl CoreManager { ); match self.attempt_service_init().await { Ok(_) => { - logging!(info, Type::Core, true, "Service mode successfully started core"); + logging!( + info, + Type::Core, + true, + "Service mode successfully started core" + ); core_started_successfully = true; } Err(_err) => { @@ -957,16 +1077,31 @@ impl CoreManager { ); match service::install_service().await { Ok(_) => { - logging!(info, Type::Core, true, "Service installed successfully (first attempt)"); + logging!( + info, + Type::Core, + true, + "Service installed successfully (first attempt)" + ); let mut new_state = service::ServiceState::default(); new_state.record_install(); new_state.prefer_sidecar = false; new_state.save()?; if service::is_service_available().await.is_ok() { - logging!(info, Type::Core, true, "Newly installed service available; attempting to start"); + logging!( + info, + Type::Core, + true, + "Newly installed service available; attempting to start" + ); if self.start_core_by_service().await.is_ok() { - logging!(info, Type::Core, true, "Newly installed service started successfully"); + logging!( + info, + Type::Core, + true, + "Newly installed service started successfully" + ); } else { logging!( warn, @@ -976,9 +1111,8 @@ impl CoreManager { ); let mut final_state = service::ServiceState::get(); final_state.prefer_sidecar = true; - final_state.last_error = Some( - "Newly installed service failed to start".to_string(), - ); + final_state.last_error = + Some("Newly installed service failed to start".to_string()); final_state.save()?; self.start_core_by_sidecar().await?; } @@ -1000,7 +1134,13 @@ impl CoreManager { } } Err(err) => { - logging!(warn, Type::Core, true, "Service first-time installation failed: {}", err); + logging!( + warn, + Type::Core, + true, + "Service first-time installation failed: {}", + err + ); let new_state = service::ServiceState { last_error: Some(err.to_string()), prefer_sidecar: true, @@ -1063,7 +1203,12 @@ impl CoreManager { if service::check_service_needs_reinstall().await { service::reinstall_service().await?; } - logging!(info, Type::Core, true, "Service available; starting in service mode"); + logging!( + info, + Type::Core, + true, + "Service available; starting in service mode" + ); self.start_core_by_service().await?; } else { // 服务不可用,检查用户偏好 @@ -1077,7 +1222,12 @@ impl CoreManager { ); self.start_core_by_sidecar().await?; } else { - logging!(info, Type::Core, true, "Service unavailable; starting in Sidecar mode"); + logging!( + info, + Type::Core, + true, + "Service unavailable; starting in Sidecar mode" + ); self.start_core_by_sidecar().await?; } } diff --git a/src-tauri/src/core/service.rs b/src-tauri/src/core/service.rs index 10dc2138..a30501e5 100644 --- a/src-tauri/src/core/service.rs +++ b/src-tauri/src/core/service.rs @@ -346,7 +346,7 @@ pub async fn reinstall_service() -> Result<()> { Ok(()) } Err(err) => { - let error = format!("failed to install service: {}", err); + let error = format!("failed to install service: {err}"); service_state.last_error = Some(error.clone()); service_state.prefer_sidecar = true; service_state.save()?; @@ -477,7 +477,12 @@ pub async fn reinstall_service() -> Result<()> { /// 检查服务状态 - 使用IPC通信 pub async fn check_ipc_service_status() -> Result { - logging!(info, Type::Service, true, "Starting service status check (IPC)"); + logging!( + info, + Type::Service, + true, + "Starting service status check (IPC)" + ); // 使用IPC通信 let payload = serde_json::json!({}); @@ -498,7 +503,13 @@ pub async fn check_ipc_service_status() -> Result { let err_msg = response .error .unwrap_or_else(|| "Unknown service error".to_string()); - logging!(error, Type::Service, true, "Service response error: {}", err_msg); + logging!( + error, + Type::Service, + true, + "Service response error: {}", + err_msg + ); bail!(err_msg); } @@ -579,7 +590,13 @@ pub async fn check_ipc_service_status() -> Result { } } Err(e) => { - logging!(error, Type::Service, true, "IPC communication failed: {}", e); + logging!( + error, + Type::Service, + true, + "IPC communication failed: {}", + e + ); bail!("Unable to connect to Koala Clash Service: {}", e) } } @@ -587,7 +604,12 @@ pub async fn check_ipc_service_status() -> Result { /// 检查服务版本 - 使用IPC通信 pub async fn check_service_version() -> Result { - logging!(info, Type::Service, true, "Starting service version check (IPC)"); + logging!( + info, + Type::Service, + true, + "Starting service version check (IPC)" + ); let payload = serde_json::json!({}); // logging!(debug, Type::Service, true, "发送GetVersion请求"); @@ -607,7 +629,13 @@ pub async fn check_service_version() -> Result { let err_msg = response .error .unwrap_or_else(|| "Failed to get service version".to_string()); - logging!(error, Type::Service, true, "Failed to get service version: {}", err_msg); + logging!( + error, + Type::Service, + true, + "Failed to get service version: {}", + err_msg + ); bail!(err_msg); } @@ -668,7 +696,13 @@ pub async fn check_service_version() -> Result { } } Err(e) => { - logging!(error, Type::Service, true, "IPC communication failed: {}", e); + logging!( + error, + Type::Service, + true, + "IPC communication failed: {}", + e + ); bail!("Unable to connect to Koala Clash Service: {}", e) } } @@ -676,7 +710,12 @@ pub async fn check_service_version() -> Result { /// 检查服务是否需要重装 pub async fn check_service_needs_reinstall() -> bool { - logging!(info, Type::Service, true, "Checking whether service needs reinstallation"); + logging!( + info, + Type::Service, + true, + "Checking whether service needs reinstallation" + ); let service_state = ServiceState::get(); @@ -701,7 +740,12 @@ pub async fn check_service_needs_reinstall() -> bool { let needs_reinstall = version != REQUIRED_SERVICE_VERSION; if needs_reinstall { log::warn!(target: "app", "Service version mismatch detected, reinstallation required! current={version}, required={REQUIRED_SERVICE_VERSION}"); - logging!(warn, Type::Service, true, "Service version mismatch, reinstallation required"); + logging!( + warn, + Type::Service, + true, + "Service version mismatch, reinstallation required" + ); // log::debug!(target: "app", "当前版本字节: {:?}", version.as_bytes()); // log::debug!(target: "app", "要求版本字节: {:?}", REQUIRED_SERVICE_VERSION.as_bytes()); @@ -713,7 +757,13 @@ pub async fn check_service_needs_reinstall() -> bool { needs_reinstall } Err(err) => { - logging!(error, Type::Service, true, "Failed to check service version: {}", err); + logging!( + error, + Type::Service, + true, + "Failed to check service version: {}", + err + ); // 检查服务是否可用 match is_service_available().await { @@ -783,8 +833,16 @@ pub(super) async fn start_with_existing_service(config_file: &PathBuf) -> Result ); */ if !response.success { - let err_msg = response.error.unwrap_or_else(|| "Failed to start core".to_string()); - logging!(error, Type::Service, true, "Failed to start core: {}", err_msg); + let err_msg = response + .error + .unwrap_or_else(|| "Failed to start core".to_string()); + logging!( + error, + Type::Service, + true, + "Failed to start core: {}", + err_msg + ); bail!(err_msg); } @@ -811,11 +869,22 @@ pub(super) async fn start_with_existing_service(config_file: &PathBuf) -> Result } } - logging!(info, Type::Service, true, "Service successfully started core"); + logging!( + info, + Type::Service, + true, + "Service successfully started core" + ); Ok(()) } Err(e) => { - logging!(error, Type::Service, true, "Failed to start core via IPC: {}", e); + logging!( + error, + Type::Service, + true, + "Failed to start core via IPC: {}", + e + ); bail!("Unable to connect to Koala Clash Service: {}", e) } } @@ -915,7 +984,9 @@ pub(super) async fn stop_core_by_service() -> Result<()> { .context("Unable to connect to Koala Clash Service")?; if !response.success { - bail!(response.error.unwrap_or_else(|| "Failed to stop core".to_string())); + bail!(response + .error + .unwrap_or_else(|| "Failed to stop core".to_string())); } if let Some(data) = &response.data { @@ -945,7 +1016,12 @@ pub(super) async fn stop_core_by_service() -> Result<()> { /// 检查服务是否正在运行 pub async fn is_service_available() -> Result<()> { - logging!(info, Type::Service, true, "Checking whether service is running"); + logging!( + info, + Type::Service, + true, + "Checking whether service is running" + ); match check_ipc_service_status().await { Ok(resp) => { @@ -965,7 +1041,13 @@ pub async fn is_service_available() -> Result<()> { } } Err(err) => { - logging!(error, Type::Service, true, "Failed to check service running status: {}", err); + logging!( + error, + Type::Service, + true, + "Failed to check service running status: {}", + err + ); Err(err) } } diff --git a/src-tauri/src/core/service_ipc.rs b/src-tauri/src/core/service_ipc.rs index bab502d1..39b85865 100644 --- a/src-tauri/src/core/service_ipc.rs +++ b/src-tauri/src/core/service_ipc.rs @@ -129,14 +129,25 @@ pub async fn send_ipc_request( winnt::{FILE_SHARE_READ, FILE_SHARE_WRITE, GENERIC_READ, GENERIC_WRITE}, }; - logging!(info, Type::Service, true, "Connecting to service (Windows)..."); + logging!( + info, + Type::Service, + true, + "Connecting to service (Windows)..." + ); let command_type = format!("{:?}", command); let request = match create_signed_request(command, payload) { Ok(req) => req, Err(e) => { - logging!(error, Type::Service, true, "Failed to create signed request: {}", e); + logging!( + error, + Type::Service, + true, + "Failed to create signed request: {}", + e + ); return Err(e); } }; @@ -147,7 +158,13 @@ pub async fn send_ipc_request( let c_pipe_name = match CString::new(IPC_SOCKET_NAME) { Ok(name) => name, Err(e) => { - logging!(error, Type::Service, true, "Failed to create CString: {}", e); + logging!( + error, + Type::Service, + true, + "Failed to create CString: {}", + e + ); return Err(anyhow::anyhow!("Failed to create CString: {}", e)); } }; @@ -177,18 +194,35 @@ pub async fn send_ipc_request( } let mut pipe = unsafe { File::from_raw_handle(handle as RawHandle) }; - logging!(info, Type::Service, true, "Service connection successful (Windows)"); + logging!( + info, + Type::Service, + true, + "Service connection successful (Windows)" + ); let request_bytes = request_json.as_bytes(); let len_bytes = (request_bytes.len() as u32).to_be_bytes(); if let Err(e) = pipe.write_all(&len_bytes) { - logging!(error, Type::Service, true, "Failed to write request length: {}", e); + logging!( + error, + Type::Service, + true, + "Failed to write request length: {}", + e + ); return Err(anyhow::anyhow!("写入请求长度失败: {}", e)); } if let Err(e) = pipe.write_all(request_bytes) { - logging!(error, Type::Service, true, "Failed to write request body: {}", e); + logging!( + error, + Type::Service, + true, + "Failed to write request body: {}", + e + ); return Err(anyhow::anyhow!("写入请求内容失败: {}", e)); } @@ -199,7 +233,13 @@ pub async fn send_ipc_request( let mut response_len_bytes = [0u8; 4]; if let Err(e) = pipe.read_exact(&mut response_len_bytes) { - logging!(error, Type::Service, true, "Failed to read response length: {}", e); + logging!( + error, + Type::Service, + true, + "Failed to read response length: {}", + e + ); return Err(anyhow::anyhow!("读取响应长度失败: {}", e)); } @@ -207,14 +247,26 @@ pub async fn send_ipc_request( let mut response_bytes = vec![0u8; response_len]; if let Err(e) = pipe.read_exact(&mut response_bytes) { - logging!(error, Type::Service, true, "Failed to read response body: {}", e); + logging!( + error, + Type::Service, + true, + "Failed to read response body: {}", + e + ); return Err(anyhow::anyhow!("读取响应内容失败: {}", e)); } let response: IpcResponse = match serde_json::from_slice::(&response_bytes) { Ok(r) => r, Err(e) => { - logging!(error, Type::Service, true, "Failed to parse service response: {}", e); + logging!( + error, + Type::Service, + true, + "Failed to parse service response: {}", + e + ); return Err(anyhow::anyhow!("解析响应失败: {}", e)); } }; @@ -222,12 +274,23 @@ pub async fn send_ipc_request( match verify_response_signature(&response) { Ok(valid) => { if !valid { - logging!(error, Type::Service, true, "Service response signature verification failed"); + logging!( + error, + Type::Service, + true, + "Service response signature verification failed" + ); bail!("服务响应签名验证失败"); } } Err(e) => { - logging!(error, Type::Service, true, "Error verifying response signature: {}", e); + logging!( + error, + Type::Service, + true, + "Error verifying response signature: {}", + e + ); return Err(e); } } @@ -271,11 +334,22 @@ pub async fn send_ipc_request( let mut stream = match UnixStream::connect(IPC_SOCKET_NAME) { Ok(s) => { - logging!(info, Type::Service, true, "Service connection successful (Unix)"); + logging!( + info, + Type::Service, + true, + "Service connection successful (Unix)" + ); s } Err(e) => { - logging!(error, Type::Service, true, "Failed to connect to Unix socket: {}", e); + logging!( + error, + Type::Service, + true, + "Failed to connect to Unix socket: {}", + e + ); return Err(anyhow::anyhow!("无法连接到服务Unix套接字: {}", e)); } }; @@ -310,7 +384,13 @@ pub async fn send_ipc_request( let response: IpcResponse = match serde_json::from_slice::(&response_bytes) { Ok(r) => r, Err(e) => { - logging!(error, Type::Service, true, "Failed to parse service response: {}", e,); + logging!( + error, + Type::Service, + true, + "Failed to parse service response: {}", + e, + ); return Err(anyhow::anyhow!("解析响应失败: {}", e)); } }; @@ -323,7 +403,13 @@ pub async fn send_ipc_request( } } Err(e) => { - logging!(error, Type::Service, true, "Error verifying response signature: {}", e); + logging!( + error, + Type::Service, + true, + "Error verifying response signature: {}", + e + ); return Err(e); } } diff --git a/src-tauri/src/core/timer.rs b/src-tauri/src/core/timer.rs index 206566fb..a301305b 100644 --- a/src-tauri/src/core/timer.rs +++ b/src-tauri/src/core/timer.rs @@ -100,7 +100,12 @@ impl Timer { let uid = item.uid.as_ref()?; if interval > 0 && cur_timestamp - updated >= interval * 60 { - logging!(info, Type::Timer, "Profile requires immediate update: uid={}", uid); + logging!( + info, + Type::Timer, + "Profile requires immediate update: uid={}", + uid + ); Some(uid.clone()) } else { None @@ -321,7 +326,12 @@ impl Timer { } logging!(debug, Type::Timer, "定时任务变更数量: {}", diff_map.len()); - logging!(debug, Type::Timer, "Number of timer task changes: {}", diff_map.len()); + logging!( + debug, + Type::Timer, + "Number of timer task changes: {}", + diff_map.len() + ); diff_map } @@ -370,7 +380,12 @@ impl Timer { let task = match timer_map.get(uid) { Some(t) => t, None => { - logging!(warn, Type::Timer, "Corresponding timer task not found, uid={}", uid); + logging!( + warn, + Type::Timer, + "Corresponding timer task not found, uid={}", + uid + ); return None; } }; @@ -389,7 +404,12 @@ impl Timer { let profile = match items.iter().find(|item| item.uid.as_deref() == Some(uid)) { Some(p) => p, None => { - logging!(warn, Type::Timer, "Corresponding profile not found, uid={}", uid); + logging!( + warn, + Type::Timer, + "Corresponding profile not found, uid={}", + uid + ); return None; } }; diff --git a/src-tauri/src/core/tray/mod.rs b/src-tauri/src/core/tray/mod.rs index 914fe5fb..c4e19970 100644 --- a/src-tauri/src/core/tray/mod.rs +++ b/src-tauri/src/core/tray/mod.rs @@ -3,7 +3,6 @@ use tauri::tray::TrayIconBuilder; #[cfg(target_os = "macos")] pub mod speed_rate; use crate::{ - cmd, config::Config, feat, logging, module::{lightweight::is_in_lightweight_mode, mihomo::Rate}, diff --git a/src-tauri/src/enhance/mod.rs b/src-tauri/src/enhance/mod.rs index 196f8f9d..6e0de239 100644 --- a/src-tauri/src/enhance/mod.rs +++ b/src-tauri/src/enhance/mod.rs @@ -241,7 +241,7 @@ pub async fn enhance() -> (Mapping, Vec, HashMap) { .filter(|(s, _)| s.is_support(clash_core.as_ref())) .map(|(_, c)| c) .for_each(|item| { - log::debug!(target: "app", "run builtin script {}", item.uid); + log::debug!(target: "app", "run builtin script {0}", item.uid); if let ChainType::Script(script) = item.data { match use_script(script, config.to_owned(), "".to_string()) { Ok((res_config, _)) => { diff --git a/src-tauri/src/enhance/script.rs b/src-tauri/src/enhance/script.rs index d1ced5ed..09ef378d 100644 --- a/src-tauri/src/enhance/script.rs +++ b/src-tauri/src/enhance/script.rs @@ -141,8 +141,8 @@ fn test_script() { fn test_escape_unescape() { let test_string = r#"Hello "World"!\nThis is a test with \u00A9 copyright symbol."#; let escaped = escape_js_string_for_single_quote(test_string); - println!("Original: {}", test_string); - println!("Escaped: {}", escaped); + println!("Original: {test_string}"); + println!("Escaped: {escaped}"); let json_str = r#"{"key":"value","nested":{"key":"value"}}"#; let parsed = parse_json_safely(json_str).unwrap(); diff --git a/src-tauri/src/feat/profile.rs b/src-tauri/src/feat/profile.rs index c3819bca..b3d07251 100644 --- a/src-tauri/src/feat/profile.rs +++ b/src-tauri/src/feat/profile.rs @@ -31,7 +31,13 @@ pub async fn update_profile( option: Option, auto_refresh: Option, ) -> Result<()> { - logging!(info, Type::Config, true, "[Subscription Update] Start updating subscription {}", uid); + logging!( + info, + Type::Config, + true, + "[Subscription Update] Start updating subscription {}", + uid + ); let auto_refresh = auto_refresh.unwrap_or(true); // 默认为true,保持兼容性 let url_opt = { @@ -131,14 +137,30 @@ pub async fn update_profile( }; if should_update { - logging!(info, Type::Config, true, "[Subscription Update] Update core configuration"); + logging!( + info, + Type::Config, + true, + "[Subscription Update] Update core configuration" + ); match CoreManager::global().update_config().await { Ok(_) => { - logging!(info, Type::Config, true, "[Subscription Update] Update succeeded"); + logging!( + info, + Type::Config, + true, + "[Subscription Update] Update succeeded" + ); handle::Handle::refresh_clash(); } Err(err) => { - logging!(error, Type::Config, true, "[Subscription Update] Update failed: {}", err); + logging!( + error, + Type::Config, + true, + "[Subscription Update] Update failed: {}", + err + ); handle::Handle::notice_message("update_failed", format!("{err}")); log::error!(target: "app", "{err}"); } diff --git a/src-tauri/src/feat/window.rs b/src-tauri/src/feat/window.rs index c1fd92c7..f3f735e7 100644 --- a/src-tauri/src/feat/window.rs +++ b/src-tauri/src/feat/window.rs @@ -78,7 +78,12 @@ pub fn quit() { // 使用异步任务处理资源清理,避免阻塞 AsyncHandler::spawn(move || async move { - logging!(info, Type::System, true, "Start asynchronous resource cleanup"); + logging!( + info, + Type::System, + true, + "Start asynchronous resource cleanup" + ); let cleanup_result = clean_async().await; logging!( @@ -95,7 +100,12 @@ pub fn quit() { async fn clean_async() -> bool { use tokio::time::{timeout, Duration}; - logging!(info, Type::System, true, "Start executing asynchronous cleanup..."); + logging!( + info, + Type::System, + true, + "Start executing asynchronous cleanup..." + ); // 1. 处理TUN模式 let tun_task = async { @@ -220,7 +230,13 @@ pub fn clean() -> bool { match rx.recv_timeout(std::time::Duration::from_secs(8)) { Ok(result) => { - logging!(info, Type::System, true, "Cleanup completed, result: {}", result); + logging!( + info, + Type::System, + true, + "Cleanup completed, result: {}", + result + ); result } Err(_) => { diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 5a246779..6ba9e2c5 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -144,7 +144,12 @@ pub fn run() { }); // 窗口管理 - logging!(info, Type::Setup, true, "Initializing window state management..."); + logging!( + info, + Type::Setup, + true, + "Initializing window state management..." + ); let window_state_plugin = tauri_plugin_window_state::Builder::new() .with_filename("window_state.json") .with_state_flags(tauri_plugin_window_state::StateFlags::default()) @@ -154,7 +159,12 @@ pub fn run() { // 异步处理 let app_handle = app.handle().clone(); AsyncHandler::spawn(move || async move { - logging!(info, Type::Setup, true, "Executing app setup asynchronously..."); + logging!( + info, + Type::Setup, + true, + "Executing app setup asynchronously..." + ); match timeout( Duration::from_secs(30), resolve::resolve_setup_async(&app_handle), @@ -175,7 +185,12 @@ pub fn run() { } }); - logging!(info, Type::Setup, true, "Executing main setup operations..."); + logging!( + info, + Type::Setup, + true, + "Executing main setup operations..." + ); logging!(info, Type::Setup, true, "Initializing AppHandleManager..."); AppHandleManager::global().init(app.handle().clone()); @@ -185,12 +200,24 @@ pub fn run() { logging!(info, Type::Setup, true, "Initializing config..."); if let Err(e) = utils::init::init_config() { - logging!(error, Type::Setup, true, "Failed to initialize config: {}", e); + logging!( + error, + Type::Setup, + true, + "Failed to initialize config: {}", + e + ); } logging!(info, Type::Setup, true, "Initializing resources..."); if let Err(e) = utils::init::init_resources() { - logging!(error, Type::Setup, true, "Failed to initialize resources: {}", e); + logging!( + error, + Type::Setup, + true, + "Failed to initialize resources: {}", + e + ); } app.manage(Mutex::new(state::proxy::CmdProxyState::default())); @@ -198,13 +225,23 @@ pub fn run() { tauri::async_runtime::spawn(async { tokio::time::sleep(Duration::from_secs(5)).await; - logging!(info, Type::Cmd, true, "Running profile updates at startup..."); + logging!( + info, + Type::Cmd, + true, + "Running profile updates at startup..." + ); if let Err(e) = crate::cmd::update_profiles_on_startup().await { - log::error!("Failed to update profiles on startup: {}", e); + log::error!("Failed to update profiles on startup: {e}"); } }); - logging!(info, Type::Setup, true, "Initialization completed, continuing"); + logging!( + info, + Type::Setup, + true, + "Initialization completed, continuing" + ); Ok(()) }) .invoke_handler(tauri::generate_handler![ @@ -376,7 +413,12 @@ pub fn run() { if let Some(window) = core::handle::Handle::global().get_window() { let _ = window.hide(); } else { - logging!(warn, Type::Window, true, "Tried to hide window but it does not exist"); + logging!( + warn, + Type::Window, + true, + "Tried to hide window but it does not exist" + ); } } tauri::WindowEvent::Focused(true) => { diff --git a/src-tauri/src/utils/resolve.rs b/src-tauri/src/utils/resolve.rs index 9150811f..b8f86126 100644 --- a/src-tauri/src/utils/resolve.rs +++ b/src-tauri/src/utils/resolve.rs @@ -23,7 +23,6 @@ use tauri::{AppHandle, Manager}; use tokio::net::TcpListener; use tauri::Url; -use crate::config::PrfOption; //#[cfg(not(target_os = "linux"))] // use window_shadows::set_shadow; @@ -556,7 +555,9 @@ pub async fn resolve_scheme(param: String) -> Result<()> { for (key, value) in link_parsed.query_pairs() { match key.as_ref() { "name" => name = Some(value.into_owned()), - "url" => url_param = Some(percent_decode_str(&value).decode_utf8_lossy().to_string()), + "url" => { + url_param = Some(percent_decode_str(&value).decode_utf8_lossy().to_string()) + } _ => {} } } From e26f500ad0da6bac64d4a06f054edf3b01a46f24 Mon Sep 17 00:00:00 2001 From: vffuunnyy Date: Sat, 16 Aug 2025 15:23:43 +0700 Subject: [PATCH 4/5] refactor: format code with prettier and fix quotation marks --- .github/FUNDING.yml | 6 +- .github/workflows/release.yml | 25 +- UPDATELOG.md | 3 +- hooks/use-mobile.ts | 24 +- src-tauri/webview2.arm64.json | 1 - src/App.tsx | 6 +- .../connection/connection-table.tsx | 412 +++++------ src/components/home/power-button.tsx | 122 ++-- src/components/layout/sidebar.tsx | 79 ++- src/components/layout/update-button.tsx | 6 +- src/components/layout/use-custom-theme.ts | 22 +- src/components/profile/hwid-error-dialog.tsx | 10 +- src/components/profile/profile-item.tsx | 32 +- src/components/profile/profile-viewer.tsx | 94 ++- src/components/proxy/proxy-groups.tsx | 3 - src/components/setting/mods/layout-viewer.tsx | 176 +++-- src/components/setting/setting-system.tsx | 13 +- .../setting/setting-verge-basic.tsx | 24 +- src/components/ui/dropdown-menu.tsx | 358 +++++----- src/components/ui/select.tsx | 300 ++++---- src/components/ui/sidebar.tsx | 246 +++---- src/components/ui/skeleton.tsx | 6 +- src/hooks/useZoomControls.ts | 56 +- src/index.css | 3 +- src/pages/_layout.tsx | 109 ++- src/pages/connections.tsx | 287 ++++---- src/pages/home.tsx | 662 +++++++++--------- src/pages/logs.tsx | 2 +- src/pages/profiles.tsx | 8 +- src/pages/rules.tsx | 8 +- src/services/cmds.ts | 5 +- src/services/noticeService.ts | 18 +- 32 files changed, 1636 insertions(+), 1490 deletions(-) diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index ee5d6934..aa8053b6 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -1 +1,5 @@ -custom: ['https://t.me/tribute/app?startapp=dtfk','https://t.me/tribute/app?startapp=dtLE'] +custom: + [ + "https://t.me/tribute/app?startapp=dtfk", + "https://t.me/tribute/app?startapp=dtLE", + ] diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a6dd9f14..954d6eef 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -91,17 +91,17 @@ jobs: > :warning: **Warning** If you get a notification that the application is corrupted when you run it on macOS, run this command:
sudo xattr -r -c /Applications/Koala\ Clash.app - + ### Linux
- +
- +
- + ### Windows (Win7 is no longer supported) #### Normal version (recommended)
@@ -217,11 +217,11 @@ jobs: shell: bash run: | TARGET_DIR="src-tauri/target/${{ matrix.target }}/release/bundle" - + if [ ! -d "$TARGET_DIR" ]; then exit 1 fi - + find "$TARGET_DIR" -type f \( -name "*.dmg" -o -name "*.deb" -o -name "*.rpm" \) -print0 | while IFS= read -r -d '' old_path; do dir_path=$(dirname "$old_path") old_filename=$(basename "$old_path") @@ -365,11 +365,11 @@ jobs: shell: bash run: | TARGET_DIR="src-tauri/target/${{ matrix.target }}/release/bundle" - + if [ ! -d "$TARGET_DIR" ]; then exit 1 fi - + find "$TARGET_DIR" -type f \( -name "*.dmg" -o -name "*.deb" -o -name "*.rpm" \) -print0 | while IFS= read -r -d '' old_path; do dir_path=$(dirname "$old_path") old_filename=$(basename "$old_path") @@ -578,14 +578,14 @@ jobs: echo "Using found update logs" UPDATE_LOGS=$(echo "$UPDATE_LOGS" | sed 's/^## \(v.*\)/\*\1\*/') fi - + cat > release.txt << EOF Вышло обновление! - + $UPDATE_LOGS - + [Ссылка на релиз](https://github.com/coolcoala/clash-verge-rev-lite/releases/latest) - + EOF - name: notify to channel @@ -603,4 +603,3 @@ jobs: token: ${{ secrets.TELEGRAM_TOKEN }} message_file: release.txt format: markdown - diff --git a/UPDATELOG.md b/UPDATELOG.md index c0f61405..df0d7fe9 100644 --- a/UPDATELOG.md +++ b/UPDATELOG.md @@ -1,7 +1,7 @@ ## v0.2.5 - new main page -- fixed issue with opening via shortcut +- fixed issue with opening via shortcut - fixed logo in sidebar - fixed issue with changing tray settings - name changed to koala clash @@ -27,7 +27,6 @@ - corrected side menu in compressed window - added check at the main toggle switch, now it cannot be enabled if there are no profiles. - ## v0.2.1 - added headers "announce-url", "update-always" diff --git a/hooks/use-mobile.ts b/hooks/use-mobile.ts index 2b0fe1df..a93d5839 100644 --- a/hooks/use-mobile.ts +++ b/hooks/use-mobile.ts @@ -1,19 +1,21 @@ -import * as React from "react" +import * as React from "react"; -const MOBILE_BREAKPOINT = 768 +const MOBILE_BREAKPOINT = 768; export function useIsMobile() { - const [isMobile, setIsMobile] = React.useState(undefined) + const [isMobile, setIsMobile] = React.useState( + undefined, + ); React.useEffect(() => { - const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`) + const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`); const onChange = () => { - setIsMobile(window.innerWidth < MOBILE_BREAKPOINT) - } - mql.addEventListener("change", onChange) - setIsMobile(window.innerWidth < MOBILE_BREAKPOINT) - return () => mql.removeEventListener("change", onChange) - }, []) + setIsMobile(window.innerWidth < MOBILE_BREAKPOINT); + }; + mql.addEventListener("change", onChange); + setIsMobile(window.innerWidth < MOBILE_BREAKPOINT); + return () => mql.removeEventListener("change", onChange); + }, []); - return !!isMobile + return !!isMobile; } diff --git a/src-tauri/webview2.arm64.json b/src-tauri/webview2.arm64.json index 18f87dcb..296703b5 100644 --- a/src-tauri/webview2.arm64.json +++ b/src-tauri/webview2.arm64.json @@ -31,4 +31,3 @@ } } } - diff --git a/src/App.tsx b/src/App.tsx index fec46f19..2d2f0663 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -3,9 +3,9 @@ import Layout from "./pages/_layout"; function App() { return ( - - - + + + ); } export default App; diff --git a/src/components/connection/connection-table.tsx b/src/components/connection/connection-table.tsx index 2cf1d2e1..3a906fbc 100644 --- a/src/components/connection/connection-table.tsx +++ b/src/components/connection/connection-table.tsx @@ -73,21 +73,25 @@ interface Props { scrollerRef: (element: HTMLElement | Window | null) => void; } -const ColumnResizer = ({ header }: { header: Header }) => { +const ColumnResizer = ({ + header, +}: { + header: Header; +}) => { return ( -
+
); }; @@ -105,8 +109,8 @@ export const ConnectionTable = (props: Props) => { try { const saved = localStorage.getItem("connection-table-widths"); return saved - ? JSON.parse(saved) - : { + ? JSON.parse(saved) + : { host: 220, download: 88, upload: 88, @@ -140,8 +144,8 @@ export const ConnectionTable = (props: Props) => { useEffect(() => { localStorage.setItem( - "connection-table-widths", - JSON.stringify(columnSizing) + "connection-table-widths", + JSON.stringify(columnSizing), ); }, [columnSizing]); @@ -151,13 +155,13 @@ export const ConnectionTable = (props: Props) => { const chains = [...each.chains].reverse().join(" / "); const rule = rulePayload ? `${each.rule}(${rulePayload})` : each.rule; const Destination = metadata.destinationIP - ? `${metadata.destinationIP}:${metadata.destinationPort}` - : `${metadata.remoteDestination}:${metadata.destinationPort}`; + ? `${metadata.destinationIP}:${metadata.destinationPort}` + : `${metadata.remoteDestination}:${metadata.destinationPort}`; return { id: each.id, host: metadata.host - ? `${metadata.host}:${metadata.destinationPort}` - : `${metadata.remoteDestination}:${metadata.destinationPort}`, + ? `${metadata.host}:${metadata.destinationPort}` + : `${metadata.remoteDestination}:${metadata.destinationPort}`, download: each.download, upload: each.upload, dlSpeed: each.curDownload ?? 0, @@ -175,118 +179,118 @@ export const ConnectionTable = (props: Props) => { }, [connections]); const columns = useMemo[]>( - () => [ - { - accessorKey: "host", - header: () => t("Host"), - size: columnSizing?.host || 220, - minSize: 180, - maxSize: 400, - }, - { - accessorKey: "download", - header: () => t("Downloaded"), - size: columnSizing?.download || 88, - minSize: 80, - maxSize: 150, - cell: ({ getValue }) => ( -
- {parseTraffic(getValue()).join(" ")} -
- ), - }, - { - accessorKey: "upload", - header: () => t("Uploaded"), - size: columnSizing?.upload || 88, - minSize: 80, - maxSize: 150, - cell: ({ getValue }) => ( -
- {parseTraffic(getValue()).join(" ")} -
- ), - }, - { - accessorKey: "dlSpeed", - header: () => t("DL Speed"), - size: columnSizing?.dlSpeed || 88, - minSize: 80, - maxSize: 150, - cell: ({ getValue }) => ( -
- {parseTraffic(getValue()).join(" ")}/s -
- ), - }, - { - accessorKey: "ulSpeed", - header: () => t("UL Speed"), - size: columnSizing?.ulSpeed || 88, - minSize: 80, - maxSize: 150, - cell: ({ getValue }) => ( -
- {parseTraffic(getValue()).join(" ")}/s -
- ), - }, - { - accessorKey: "chains", - header: () => t("Chains"), - size: columnSizing?.chains || 340, - minSize: 180, - maxSize: 500, - }, - { - accessorKey: "rule", - header: () => t("Rule"), - size: columnSizing?.rule || 280, - minSize: 180, - maxSize: 400, - }, - { - accessorKey: "process", - header: () => t("Process"), - size: columnSizing?.process || 220, - minSize: 180, - maxSize: 350, - }, - { - accessorKey: "time", - header: () => t("Time"), - size: columnSizing?.time || 120, - minSize: 100, - maxSize: 180, - cell: ({ getValue }) => ( -
- {dayjs(getValue()).fromNow()} -
- ), - }, - { - accessorKey: "source", - header: () => t("Source"), - size: columnSizing?.source || 200, - minSize: 130, - maxSize: 300, - }, - { - accessorKey: "remoteDestination", - header: () => t("Destination"), - size: columnSizing?.remoteDestination || 200, - minSize: 130, - maxSize: 300, - }, - { - accessorKey: "type", - header: () => t("Type"), - size: columnSizing?.type || 160, - minSize: 100, - maxSize: 220, - }, - ], - [columnSizing] + () => [ + { + accessorKey: "host", + header: () => t("Host"), + size: columnSizing?.host || 220, + minSize: 180, + maxSize: 400, + }, + { + accessorKey: "download", + header: () => t("Downloaded"), + size: columnSizing?.download || 88, + minSize: 80, + maxSize: 150, + cell: ({ getValue }) => ( +
+ {parseTraffic(getValue()).join(" ")} +
+ ), + }, + { + accessorKey: "upload", + header: () => t("Uploaded"), + size: columnSizing?.upload || 88, + minSize: 80, + maxSize: 150, + cell: ({ getValue }) => ( +
+ {parseTraffic(getValue()).join(" ")} +
+ ), + }, + { + accessorKey: "dlSpeed", + header: () => t("DL Speed"), + size: columnSizing?.dlSpeed || 88, + minSize: 80, + maxSize: 150, + cell: ({ getValue }) => ( +
+ {parseTraffic(getValue()).join(" ")}/s +
+ ), + }, + { + accessorKey: "ulSpeed", + header: () => t("UL Speed"), + size: columnSizing?.ulSpeed || 88, + minSize: 80, + maxSize: 150, + cell: ({ getValue }) => ( +
+ {parseTraffic(getValue()).join(" ")}/s +
+ ), + }, + { + accessorKey: "chains", + header: () => t("Chains"), + size: columnSizing?.chains || 340, + minSize: 180, + maxSize: 500, + }, + { + accessorKey: "rule", + header: () => t("Rule"), + size: columnSizing?.rule || 280, + minSize: 180, + maxSize: 400, + }, + { + accessorKey: "process", + header: () => t("Process"), + size: columnSizing?.process || 220, + minSize: 180, + maxSize: 350, + }, + { + accessorKey: "time", + header: () => t("Time"), + size: columnSizing?.time || 120, + minSize: 100, + maxSize: 180, + cell: ({ getValue }) => ( +
+ {dayjs(getValue()).fromNow()} +
+ ), + }, + { + accessorKey: "source", + header: () => t("Source"), + size: columnSizing?.source || 200, + minSize: 130, + maxSize: 300, + }, + { + accessorKey: "remoteDestination", + header: () => t("Destination"), + size: columnSizing?.remoteDestination || 200, + minSize: 130, + maxSize: 300, + }, + { + accessorKey: "type", + header: () => t("Type"), + size: columnSizing?.type || 160, + minSize: 100, + maxSize: 220, + }, + ], + [columnSizing], ); const table = useReactTable({ @@ -305,82 +309,82 @@ export const ConnectionTable = (props: Props) => { if (connRows.length === 0) { return ( -
-

{t("No connections")}

-
+
+

{t("No connections")}

+
); } return ( -
- - - {table.getHeaderGroups().map((headerGroup) => ( - +
+ + {table.getHeaderGroups().map((headerGroup) => ( + + {headerGroup.headers.map((header) => ( + - {headerGroup.headers.map((header) => ( - -
- {header.isPlaceholder - ? null - : flexRender( - header.column.columnDef.header, - header.getContext() - )} -
- {header.column.getCanResize() && ( - +
+ {header.isPlaceholder + ? null + : flexRender( + header.column.columnDef.header, + header.getContext(), )} - - ))} - - ))} - +
+ {header.column.getCanResize() && ( + + )} +
+ ))} +
+ ))} +
- - {table.getRowModel().rows.map((row) => ( - onShowDetail(row.original.connectionData)} + + {table.getRowModel().rows.map((row) => ( + onShowDetail(row.original.connectionData)} + > + {row.getVisibleCells().map((cell) => ( + - {row.getVisibleCells().map((cell) => ( - - {flexRender(cell.column.columnDef.cell, cell.getContext())} - - ))} - - ))} - -
-
+ {flexRender(cell.column.columnDef.cell, cell.getContext())} + + ))} + + ))} + + +
); -}; \ No newline at end of file +}; diff --git a/src/components/home/power-button.tsx b/src/components/home/power-button.tsx index eedd5823..456f7f90 100644 --- a/src/components/home/power-button.tsx +++ b/src/components/home/power-button.tsx @@ -1,64 +1,72 @@ -import React from 'react'; -import { cn } from '@root/lib/utils'; -import { Power } from 'lucide-react'; +import React from "react"; +import { cn } from "@root/lib/utils"; +import { Power } from "lucide-react"; -export interface PowerButtonProps extends React.ButtonHTMLAttributes { - checked?: boolean; - loading?: boolean; +export interface PowerButtonProps + extends React.ButtonHTMLAttributes { + checked?: boolean; + loading?: boolean; } -export const PowerButton = React.forwardRef( - ({ className, checked = false, loading = false, ...props }, ref) => { - const state = checked ? 'on' : 'off'; +export const PowerButton = React.forwardRef< + HTMLButtonElement, + PowerButtonProps +>(({ className, checked = false, loading = false, ...props }, ref) => { + const state = checked ? "on" : "off"; - return ( -
+ return ( +
+
-
+ - // Стили ТОЛЬКО для отключенного состояния (но не для загрузки) - (props.disabled && !loading) && 'grayscale opacity-50 shadow-none bg-slate-100/70 border-slate-300/80', - className - )} - {...props} - > - - - - {loading && ( -
-
-
- )} -
- ); - } -); \ No newline at end of file + {loading && ( +
+
+
+ )} +
+ ); +}); diff --git a/src/components/layout/sidebar.tsx b/src/components/layout/sidebar.tsx index b64a262a..77117206 100644 --- a/src/components/layout/sidebar.tsx +++ b/src/components/layout/sidebar.tsx @@ -1,16 +1,18 @@ -import { Link } from 'react-router-dom'; +import { Link } from "react-router-dom"; import { Sidebar, - SidebarContent, SidebarFooter, + SidebarContent, + SidebarFooter, SidebarGroup, SidebarGroupContent, SidebarHeader, SidebarMenu, SidebarMenuButton, - SidebarMenuItem, useSidebar, -} from "@/components/ui/sidebar" -import { t } from 'i18next'; -import { cn } from '@root/lib/utils'; + SidebarMenuItem, + useSidebar, +} from "@/components/ui/sidebar"; +import { t } from "i18next"; +import { cn } from "@root/lib/utils"; import { Home, @@ -19,21 +21,22 @@ import { Cable, ListChecks, FileText, - Settings, EarthLock, -} from 'lucide-react'; + Settings, + EarthLock, +} from "lucide-react"; import { UpdateButton } from "@/components/layout/update-button"; import React from "react"; -import { SheetClose } from '@/components/ui/sheet'; -import logo from "@/assets/image/logo.png" +import { SheetClose } from "@/components/ui/sheet"; +import logo from "@/assets/image/logo.png"; const menuItems = [ - { title: 'Home', url: '/home', icon: Home }, - { title: 'Profiles', url: '/profile', icon: Users }, - { title: 'Proxies', url: '/proxies', icon: Server }, - { title: 'Connections', url: '/connections', icon: Cable }, - { title: 'Rules', url: '/rules', icon: ListChecks }, - { title: 'Logs', url: '/logs', icon: FileText }, - { title: 'Settings', url: '/settings', icon: Settings }, + { title: "Home", url: "/home", icon: Home }, + { title: "Profiles", url: "/profile", icon: Users }, + { title: "Proxies", url: "/proxies", icon: Server }, + { title: "Connections", url: "/connections", icon: Cable }, + { title: "Rules", url: "/rules", icon: ListChecks }, + { title: "Logs", url: "/logs", icon: FileText }, + { title: "Settings", url: "/settings", icon: Settings }, ]; export function AppSidebar() { @@ -41,18 +44,15 @@ export function AppSidebar() { return ( - - logo + logo Koala Clash @@ -69,30 +69,29 @@ export function AppSidebar() { key={item.title} to={item.url} className={cn( - 'flex items-center gap-3 rounded-lg px-3 py-2 text-muted-foreground transition-all hover:text-primary', - 'data-[active=true]:font-semibold data-[active=true]:border' + "flex items-center gap-3 rounded-lg px-3 py-2 text-muted-foreground transition-all hover:text-primary", + "data-[active=true]:font-semibold data-[active=true]:border", )} > {t(item.title)} - ) + ); return ( - - - {isMobile ? ( - - {linkElement} - + + + {isMobile ? ( + {linkElement} ) : ( linkElement )} - - - ) + + + ); })} @@ -104,5 +103,5 @@ export function AppSidebar() {
- ) + ); } diff --git a/src/components/layout/update-button.tsx b/src/components/layout/update-button.tsx index 414e75c3..f1d043e0 100644 --- a/src/components/layout/update-button.tsx +++ b/src/components/layout/update-button.tsx @@ -6,7 +6,7 @@ import { DialogRef } from "../base"; import { useVerge } from "@/hooks/use-verge"; import { Button } from "@/components/ui/button"; import { t } from "i18next"; -import {Download, RefreshCw} from "lucide-react"; +import { Download, RefreshCw } from "lucide-react"; import { useSidebar } from "../ui/sidebar"; interface Props { @@ -17,7 +17,7 @@ export const UpdateButton = (props: Props) => { const { className } = props; const { verge } = useVerge(); const { auto_check_update } = verge || {}; - const { state: sidebarState } = useSidebar(); + const { state: sidebarState } = useSidebar(); const viewerRef = useRef(null); @@ -36,7 +36,7 @@ export const UpdateButton = (props: Props) => { return ( <> - {sidebarState === 'collapsed' ? ( + {sidebarState === "collapsed" ? (
- + {type}
@@ -389,14 +388,13 @@ export const ProfileItem = (props: Props) => {
- - {parseTraffic(download)} - + {parseTraffic(download)} {total > 0 ? ( - {parseTraffic(total)} - ) : } - + {parseTraffic(total)} + ) : ( + + )}
@@ -510,11 +508,11 @@ export const ProfileItem = (props: Props) => { )}
); diff --git a/src/components/profile/profile-viewer.tsx b/src/components/profile/profile-viewer.tsx index c35c2d83..3c4ed007 100644 --- a/src/components/profile/profile-viewer.tsx +++ b/src/components/profile/profile-viewer.tsx @@ -12,7 +12,8 @@ import { createProfile, patchProfile, importProfile, - enhanceProfiles, createProfileFromShareLink, + enhanceProfiles, + createProfileFromShareLink, } from "@/services/cmds"; import { useProfiles } from "@/hooks/use-profiles"; import { showNotice } from "@/services/noticeService"; @@ -138,7 +139,9 @@ export const ProfileViewer = forwardRef( setIsCheckingUrl(true); const handler = setTimeout(() => { - const isValid = /^(https?|vmess|vless|ss|socks|trojan):\/\//.test(importUrl); + const isValid = /^(https?|vmess|vless|ss|socks|trojan):\/\//.test( + importUrl, + ); setIsUrlValid(isValid); setIsCheckingUrl(false); }, 500); @@ -165,23 +168,35 @@ export const ProfileViewer = forwardRef( await enhanceProfiles(); setOpen(false); } catch (err: any) { - const errorMessage = typeof err === 'string' ? err : (err.message || String(err)); + const errorMessage = + typeof err === "string" ? err : err.message || String(err); const lowerErrorMessage = errorMessage.toLowerCase(); - if (lowerErrorMessage.includes('device') || lowerErrorMessage.includes('устройств')) { - window.dispatchEvent(new CustomEvent('show-hwid-error', { detail: errorMessage })); + if ( + lowerErrorMessage.includes("device") || + lowerErrorMessage.includes("устройств") + ) { + window.dispatchEvent( + new CustomEvent("show-hwid-error", { detail: errorMessage }), + ); } else if (!isShareLink && errorMessage.includes("failed to fetch")) { - showNotice("info", t("Import failed, retrying with Clash proxy...")); - try { - await importProfile(importUrl, { with_proxy: false, self_proxy: true }); - showNotice("success", t("Profile Imported with Clash proxy")); - props.onChange(); - await enhanceProfiles(); - setOpen(false); - } catch (retryErr: any) { - showNotice("error", `${t("Import failed even with Clash proxy")}: ${retryErr?.message || retryErr.toString()}`); - } + showNotice("info", t("Import failed, retrying with Clash proxy...")); + try { + await importProfile(importUrl, { + with_proxy: false, + self_proxy: true, + }); + showNotice("success", t("Profile Imported with Clash proxy")); + props.onChange(); + await enhanceProfiles(); + setOpen(false); + } catch (retryErr: any) { + showNotice( + "error", + `${t("Import failed even with Clash proxy")}: ${retryErr?.message || retryErr.toString()}`, + ); + } } else { - showNotice("error", errorMessage); + showNotice("error", errorMessage); } } finally { setIsImporting(false); @@ -302,19 +317,26 @@ export const ProfileViewer = forwardRef(
{/^(vmess|vless|ss|socks|trojan):\/\//.test(importUrl) && ( -
+
- + + + + + + {t("Default Template")} + + + {t("Template without RU Rules")} + + -
- )} +
+ )} - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + ); -}); \ No newline at end of file +}); diff --git a/src/components/setting/setting-system.tsx b/src/components/setting/setting-system.tsx index 1cf0a678..a5516166 100644 --- a/src/components/setting/setting-system.tsx +++ b/src/components/setting/setting-system.tsx @@ -1,4 +1,4 @@ -import {useMemo, useRef, useState} from "react"; +import { useMemo, useRef, useState } from "react"; import { useTranslation } from "react-i18next"; import { useLockFn } from "ahooks"; import { mutate } from "swr"; @@ -43,7 +43,7 @@ import { Power, BellOff, Repeat, - Fingerprint + Fingerprint, } from "lucide-react"; // Модальные окна @@ -56,7 +56,7 @@ import { SelectTrigger, SelectValue, } from "@/components/ui/select"; -import {useProfiles} from "@/hooks/use-profiles"; +import { useProfiles } from "@/hooks/use-profiles"; const isWIN = getSystem() === "windows"; interface Props { @@ -110,7 +110,7 @@ const SettingSystem = ({ onError }: Props) => { const { profiles } = useProfiles(); const hasProfiles = useMemo(() => { const items = profiles?.items ?? []; - return items.some(p => p.type === 'local' || p.type === 'remote'); + return items.some((p) => p.type === "local" || p.type === "remote"); }, [profiles]); const { @@ -261,7 +261,10 @@ const SettingSystem = ({ onError }: Props) => { ); } if (e) { - return patchVerge({ enable_tun_mode: true, enable_system_proxy: false }); + return patchVerge({ + enable_tun_mode: true, + enable_system_proxy: false, + }); } else { return patchVerge({ enable_tun_mode: false }); } diff --git a/src/components/setting/setting-verge-basic.tsx b/src/components/setting/setting-verge-basic.tsx index 3c08ea5c..bcc84bf9 100644 --- a/src/components/setting/setting-verge-basic.tsx +++ b/src/components/setting/setting-verge-basic.tsx @@ -188,20 +188,20 @@ const SettingVergeBasic = ({ onError }: Props) => { {OS !== "linux" && ( - } + label={ + + } > v} - onChange={(e) => onChangeData({ tray_event: e })} - onGuard={(e) => patchVerge({ tray_event: e })} - onChangeProps="onValueChange" + value={tray_event ?? "main_window"} + onCatch={onError} + onFormat={(v) => v} + onChange={(e) => onChangeData({ tray_event: e })} + onGuard={(e) => patchVerge({ tray_event: e })} + onChangeProps="onValueChange" > setOrderOpt(value)} - > - - - - - {Object.keys(orderOpts).map((opt) => ( - - {t(opt)} - - ))} - - - )} -
- + + + + + + +

{isTableLayout ? t("List View") : t("Table View")}

+
+
+ + + + + +

{isPaused ? t("Resume") : t("Pause")}

+
+
+
- + - -
- {filterConn.length === 0 ? ( - - ) : isTableLayout ? ( -
- detailRef.current?.open(detail)} - scrollerRef={scrollerRefCallback} - /> -
- ) : ( - ( - detailRef.current?.open(item)} - /> - )} - /> +
+ {!isTableLayout && ( + )} - +
+ +
+ +
+ {filterConn.length === 0 ? ( + + ) : isTableLayout ? ( +
+ detailRef.current?.open(detail)} + scrollerRef={scrollerRefCallback} + /> +
+ ) : ( + ( + detailRef.current?.open(item)} + /> + )} + /> + )} + +
+ ); }; -export default ConnectionsPage; \ No newline at end of file +export default ConnectionsPage; diff --git a/src/pages/home.tsx b/src/pages/home.tsx index 991757b9..fe0baad3 100644 --- a/src/pages/home.tsx +++ b/src/pages/home.tsx @@ -1,4 +1,10 @@ -import React, {useRef, useMemo, useCallback, useState, useEffect} from "react"; +import React, { + useRef, + useMemo, + useCallback, + useState, + useEffect, +} from "react"; import { useLockFn } from "ahooks"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; @@ -25,7 +31,11 @@ import { AlertTriangle, Loader2, Globe, - Send, ExternalLink, RefreshCw, ArrowDown, ArrowUp, + Send, + ExternalLink, + RefreshCw, + ArrowDown, + ArrowUp, } from "lucide-react"; import { useVerge } from "@/hooks/use-verge"; import { useSystemState } from "@/hooks/use-system-state"; @@ -34,7 +44,12 @@ import { Switch } from "@/components/ui/switch"; import { ProxySelectors } from "@/components/home/proxy-selectors"; import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; import { closeAllConnections } from "@/services/api"; -import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"; +import { + Tooltip, + TooltipContent, + TooltipProvider, + TooltipTrigger, +} from "@/components/ui/tooltip"; import { updateProfile } from "@/services/cmds"; import { SidebarTrigger } from "@/components/ui/sidebar"; import parseTraffic from "@/utils/parse-traffic"; @@ -48,45 +63,45 @@ const MinimalHomePage: React.FC = () => { const [isToggling, setIsToggling] = useState(false); const [isUpdating, setIsUpdating] = useState(false); const { profiles, patchProfiles, activateSelected, mutateProfiles } = - useProfiles(); + useProfiles(); const viewerRef = useRef(null); const [uidToActivate, setUidToActivate] = useState(null); const { connections } = useAppData(); const profileItems = useMemo(() => { const items = - profiles && Array.isArray(profiles.items) ? profiles.items : []; + profiles && Array.isArray(profiles.items) ? profiles.items : []; const allowedTypes = ["local", "remote"]; return items.filter((i: any) => i && allowedTypes.includes(i.type!)); }, [profiles]); const currentProfile = useMemo(() => { - return profileItems.find(p => p.uid === profiles?.current); + return profileItems.find((p) => p.uid === profiles?.current); }, [profileItems, profiles?.current]); const currentProfileName = currentProfile?.name || profiles?.current; const activateProfile = useCallback( - async (uid: string, notifySuccess: boolean) => { - try { - await patchProfiles({ current: uid }); - await closeAllConnections(); - await activateSelected(); - if (notifySuccess) { - toast.success(t("Profile Switched")); - } - } catch (err: any) { - toast.error(err.message || err.toString()); - mutateProfiles(); + async (uid: string, notifySuccess: boolean) => { + try { + await patchProfiles({ current: uid }); + await closeAllConnections(); + await activateSelected(); + if (notifySuccess) { + toast.success(t("Profile Switched")); } - }, - [patchProfiles, activateSelected, mutateProfiles, t], + } catch (err: any) { + toast.error(err.message || err.toString()); + mutateProfiles(); + } + }, + [patchProfiles, activateSelected, mutateProfiles, t], ); useEffect(() => { - const uidToActivate = sessionStorage.getItem('activateProfile'); - if (uidToActivate && profileItems.some(p => p.uid === uidToActivate)) { + const uidToActivate = sessionStorage.getItem("activateProfile"); + if (uidToActivate && profileItems.some((p) => p.uid === uidToActivate)) { activateProfile(uidToActivate, false); - sessionStorage.removeItem('activateProfile'); + sessionStorage.removeItem("activateProfile"); } }, [profileItems, activateProfile]); @@ -101,7 +116,7 @@ const MinimalHomePage: React.FC = () => { const isTunAvailable = isServiceMode || isAdminMode; const isProxyEnabled = verge?.enable_system_proxy || verge?.enable_tun_mode; const showTunAlert = - (verge?.primary_action ?? "tun-mode") === "tun-mode" && !isTunAvailable; + (verge?.primary_action ?? "tun-mode") === "tun-mode" && !isTunAvailable; const handleToggleProxy = useLockFn(async () => { const turningOn = !isProxyEnabled; @@ -143,7 +158,7 @@ const MinimalHomePage: React.FC = () => { }); const handleUpdateProfile = useLockFn(async () => { - if (!currentProfile?.uid || currentProfile.type !== 'remote') return; + if (!currentProfile?.uid || currentProfile.type !== "remote") return; setIsUpdating(true); try { await updateProfile(currentProfile.uid); @@ -159,316 +174,325 @@ const MinimalHomePage: React.FC = () => { const statusInfo = useMemo(() => { if (isToggling) { return { - text: isProxyEnabled ? t('Disconnecting...') : t('Connecting...'), - color: isProxyEnabled ? '#f59e0b' : '#84cc16', + text: isProxyEnabled ? t("Disconnecting...") : t("Connecting..."), + color: isProxyEnabled ? "#f59e0b" : "#84cc16", isAnimating: true, }; } if (isProxyEnabled) { return { - text: t('Connected'), - color: '#22c55e', + text: t("Connected"), + color: "#22c55e", isAnimating: false, }; } return { - text: t('Disconnected'), - color: '#ef4444', + text: t("Disconnected"), + color: "#ef4444", isAnimating: false, }; }, [isToggling, isProxyEnabled, t]); return ( -
-
- World map -
- - {isProxyEnabled && ( -
- )} - -
-
- -
-
-
- {profileItems.length > 0 ? ( - <> -
- - - - - - -

{t("Add Profile")}

-
-
-
-
- - - - - - {t("Profiles")} - - {profileItems.map((p) => ( - handleProfileChange(p.uid)} - > - {p.name} - {profiles?.current === p.uid && ( - - )} - - ))} - - - {currentProfile?.type === 'remote' && ( -
- - - - - -

{t("Update Profile")}

-
-
-
- )} - - ) : ( - <> -
- - - - - - -

{t("Add Profile")}

-
-
-
-
- - - )} -
-
-
-
-
- -
-
- {currentProfile?.announce && ( -
- {currentProfile.announce_url ? ( - - {currentProfile.announce.replace(/\\n/g, '\n')} - - - ) : ( -

- {currentProfile.announce} -

- )} -
- )} -
-

- {statusInfo.text} -

- {isProxyEnabled && ( -
-
- - {parseTraffic(connections.downloadTotal)} -
-
- - {parseTraffic(connections.uploadTotal)} -
-
- )} -
- -
- -
- - {showTunAlert && ( -
- - - {t("Attention Required")} - - {t("TUN requires Service Mode or Admin Mode")} - - {!isServiceMode && !isAdminMode && ( - - )} - -
- )} - -
- {profileItems.length > 0 ? ( - - ) : ( - - - {t("Get Started")} - - {t( - "You don't have any profiles yet. Add your first one to begin.", - )} - - - - )} -
-
-
- - mutateProfiles()} /> +
+
+ World map
+ + {isProxyEnabled && ( +
+ )} + +
+
+ +
+
+
+ {profileItems.length > 0 ? ( + <> +
+ + + + + + +

{t("Add Profile")}

+
+
+
+
+ + + + + + {t("Profiles")} + + {profileItems.map((p) => ( + handleProfileChange(p.uid)} + > + {p.name} + {profiles?.current === p.uid && ( + + )} + + ))} + + + {currentProfile?.type === "remote" && ( +
+ + + + + + +

{t("Update Profile")}

+
+
+
+
+ )} + + ) : ( + <> +
+ + + + + + +

{t("Add Profile")}

+
+
+
+
+ + + )} +
+
+
+
+ +
+
+ {currentProfile?.announce && ( +
+ {currentProfile.announce_url ? ( + + {currentProfile.announce.replace(/\\n/g, "\n")} + + + ) : ( +

+ {currentProfile.announce} +

+ )} +
+ )} +
+

+ {statusInfo.text} +

+ {isProxyEnabled && ( +
+
+ + {parseTraffic(connections.downloadTotal)} +
+
+ + {parseTraffic(connections.uploadTotal)} +
+
+ )} +
+ +
+ +
+ + {showTunAlert && ( +
+ + + {t("Attention Required")} + + {t("TUN requires Service Mode or Admin Mode")} + + {!isServiceMode && !isAdminMode && ( + + )} + +
+ )} + +
+ {profileItems.length > 0 ? ( + + ) : ( + + + {t("Get Started")} + + {t( + "You don't have any profiles yet. Add your first one to begin.", + )} + + + + )} +
+
+
+ + mutateProfiles()} /> +
); }; -export default MinimalHomePage; \ No newline at end of file +export default MinimalHomePage; diff --git a/src/pages/logs.tsx b/src/pages/logs.tsx index 2a3d1bbe..24e6154c 100644 --- a/src/pages/logs.tsx +++ b/src/pages/logs.tsx @@ -31,7 +31,7 @@ import { SelectTrigger, SelectValue, } from "@/components/ui/select"; -import {SidebarTrigger} from "@/components/ui/sidebar"; +import { SidebarTrigger } from "@/components/ui/sidebar"; const LogPage = () => { const { t } = useTranslation(); diff --git a/src/pages/profiles.tsx b/src/pages/profiles.tsx index 1c1a30c2..eff08f41 100644 --- a/src/pages/profiles.tsx +++ b/src/pages/profiles.tsx @@ -55,13 +55,7 @@ import { TooltipTrigger, } from "@/components/ui/tooltip"; -import { - PlusCircle, - RefreshCw, - Zap, - FileText, - Loader2, -} from "lucide-react"; +import { PlusCircle, RefreshCw, Zap, FileText, Loader2 } from "lucide-react"; import { SidebarTrigger } from "@/components/ui/sidebar"; const ProfilePage = () => { diff --git a/src/pages/rules.tsx b/src/pages/rules.tsx index 7df67cf5..e6e44c15 100644 --- a/src/pages/rules.tsx +++ b/src/pages/rules.tsx @@ -1,4 +1,10 @@ -import React, { useState, useMemo, useRef, useEffect, useCallback } from "react"; +import React, { + useState, + useMemo, + useRef, + useEffect, + useCallback, +} from "react"; import { useTranslation } from "react-i18next"; import { Virtuoso, VirtuosoHandle } from "react-virtuoso"; import { useAppData } from "@/providers/app-data-provider"; diff --git a/src/services/cmds.ts b/src/services/cmds.ts index 4b7ccb80..788557f4 100644 --- a/src/services/cmds.ts +++ b/src/services/cmds.ts @@ -401,6 +401,9 @@ export async function getNextUpdateTime(uid: string) { return invoke("get_next_update_time", { uid }); } -export async function createProfileFromShareLink(link: string, templateName: string) { +export async function createProfileFromShareLink( + link: string, + templateName: string, +) { return invoke("create_profile_from_share_link", { link, templateName }); } diff --git a/src/services/noticeService.ts b/src/services/noticeService.ts index 2e19d7bb..3f482a76 100644 --- a/src/services/noticeService.ts +++ b/src/services/noticeService.ts @@ -1,25 +1,29 @@ import { toast } from "sonner"; -type NoticeType = 'success' | 'error' | 'info' | 'warning'; +type NoticeType = "success" | "error" | "info" | "warning"; -export const showNotice = (type: NoticeType, message: string, duration?: number) => { +export const showNotice = ( + type: NoticeType, + message: string, + duration?: number, +) => { const options = duration ? { duration } : {}; switch (type) { - case 'success': + case "success": toast.success(message, options); break; - case 'error': + case "error": toast.error(message, options); break; - case 'info': + case "info": toast.info(message, options); break; - case 'warning': + case "warning": toast.warning(message, options); break; default: toast(message, options); break; } -}; \ No newline at end of file +}; From bec1b95ad324186a9843e03ca538244da5bdfbf9 Mon Sep 17 00:00:00 2001 From: vffuunnyy Date: Sat, 16 Aug 2025 15:31:30 +0700 Subject: [PATCH 5/5] refactor: fix lifetime annotations in draft.rs ci: add cargo retry settings --- .github/workflows/autobuild.yml | 3 +++ .github/workflows/clippy.yml | 3 +++ .github/workflows/dev.yml | 3 +++ .github/workflows/fmt.yml | 3 +++ .gitignore | 1 + src-tauri/src/config/draft.rs | 6 +++--- 6 files changed, 16 insertions(+), 3 deletions(-) diff --git a/.github/workflows/autobuild.yml b/.github/workflows/autobuild.yml index f6c7c81e..da5f780b 100644 --- a/.github/workflows/autobuild.yml +++ b/.github/workflows/autobuild.yml @@ -193,6 +193,9 @@ jobs: - os: ubuntu-22.04 target: x86_64-unknown-linux-gnu runs-on: ${{ matrix.os }} + env: + CARGO_NET_RETRY: "5" + CARGO_HTTP_CHECK_REVOKE: "false" steps: - name: Checkout Repository uses: actions/checkout@v4 diff --git a/.github/workflows/clippy.yml b/.github/workflows/clippy.yml index 64392ab3..270080bf 100644 --- a/.github/workflows/clippy.yml +++ b/.github/workflows/clippy.yml @@ -17,6 +17,9 @@ jobs: target: x86_64-unknown-linux-gnu runs-on: ${{ matrix.os }} + env: + CARGO_NET_RETRY: "5" + CARGO_HTTP_CHECK_REVOKE: "false" steps: - name: Checkout Repository uses: actions/checkout@v4 diff --git a/.github/workflows/dev.yml b/.github/workflows/dev.yml index 53b771cc..634a9d35 100644 --- a/.github/workflows/dev.yml +++ b/.github/workflows/dev.yml @@ -28,6 +28,9 @@ jobs: bundle: dmg runs-on: ${{ matrix.os }} + env: + CARGO_NET_RETRY: "5" + CARGO_HTTP_CHECK_REVOKE: "false" steps: - name: Checkout Repository uses: actions/checkout@v4 diff --git a/.github/workflows/fmt.yml b/.github/workflows/fmt.yml index 3320cba1..335b6165 100644 --- a/.github/workflows/fmt.yml +++ b/.github/workflows/fmt.yml @@ -10,6 +10,9 @@ on: jobs: rustfmt: runs-on: ubuntu-latest + env: + CARGO_NET_RETRY: "5" + CARGO_HTTP_CHECK_REVOKE: "false" steps: - uses: actions/checkout@v4 diff --git a/.gitignore b/.gitignore index aa25c632..558caa4f 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,4 @@ scripts/_env.sh .tool-versions .idea .old +bun.lock \ No newline at end of file diff --git a/src-tauri/src/config/draft.rs b/src-tauri/src/config/draft.rs index 97ef7412..4f3b5a56 100644 --- a/src-tauri/src/config/draft.rs +++ b/src-tauri/src/config/draft.rs @@ -19,11 +19,11 @@ macro_rules! draft_define { impl Draft> { #[allow(unused)] - pub fn data(&self) -> MappedMutexGuard> { + pub fn data(&self) -> MappedMutexGuard<'_, Box<$id>> { MutexGuard::map(self.inner.lock(), |guard| &mut guard.0) } - pub fn latest(&self) -> MappedMutexGuard> { + pub fn latest(&self) -> MappedMutexGuard<'_, Box<$id>> { MutexGuard::map(self.inner.lock(), |inner| { if inner.1.is_none() { &mut inner.0 @@ -33,7 +33,7 @@ macro_rules! draft_define { }) } - pub fn draft(&self) -> MappedMutexGuard> { + pub fn draft(&self) -> MappedMutexGuard<'_, Box<$id>> { MutexGuard::map(self.inner.lock(), |inner| { if inner.1.is_none() { inner.1 = Some(inner.0.clone());