Files
clash-proxy/src-tauri/src/core/sysopt.rs

335 lines
11 KiB
Rust
Raw Normal View History

2025-04-21 00:06:37 +08:00
#[cfg(target_os = "windows")]
use crate::utils::autostart as startup_shortcut;
2024-05-26 17:59:39 +08:00
use crate::{
config::{Config, IVerge},
core::{EventDrivenProxyManager, handle::Handle},
refactor: optimize singleton macro usage with Default trait implementations (#4279) * refactor: implement DRY principle improvements across backend Major DRY violations identified and addressed: 1. **IPC Stream Monitor Pattern**: - Created `utils/ipc_monitor.rs` with generic `IpcStreamMonitor` trait - Added `IpcMonitorManager` for common async task management patterns - Eliminates duplication across traffic.rs, memory.rs, and logs.rs 2. **Singleton Pattern Duplication**: - Created `utils/singleton.rs` with `singleton\!` and `singleton_with_logging\!` macros - Replaces 16+ duplicate singleton implementations across codebase - Provides consistent, tested patterns for global instances 3. **macOS Activation Policy Refactoring**: - Consolidated 3 duplicate methods into single parameterized `set_activation_policy()` - Eliminated code duplication while maintaining backward compatibility - Reduced maintenance burden for macOS-specific functionality These improvements enhance maintainability, reduce bug potential, and ensure consistent patterns across the backend codebase. * fix: resolve test failures and clippy warnings - Fix doctest in singleton.rs by using rust,ignore syntax and proper code examples - Remove unused time::Instant import from ipc_monitor.rs - Add #[allow(dead_code)] attributes to future-use utility modules - All 11 unit tests now pass successfully - All clippy checks pass with -D warnings strict mode - Documentation tests properly ignore example code that requires full context * refactor: migrate code to use new utility tools (partial) Progress on systematic migration to use created utility tools: 1. **Reorganized IPC Monitor**: - Moved ipc_monitor.rs to src-tauri/src/ipc/monitor.rs for better organization - Updated module structure to emphasize IPC relationship 2. **IpcManager Singleton Migration**: - Replaced manual OnceLock singleton pattern with singleton_with_logging\! macro - Simplified initialization code and added consistent logging - Removed unused imports (OnceLock, logging::Type) 3. **ProxyRequestCache Singleton Migration**: - Migrated from once_cell::sync::OnceCell to singleton\! macro - Cleaner, more maintainable singleton pattern - Consistent with project-wide singleton approach These migrations demonstrate the utility and effectiveness of the created tools: - Less boilerplate code - Consistent patterns across codebase - Easier maintenance and debugging * feat: complete migration to new utility tools - phase 1 Successfully migrated core components to use the created utility tools: - Moved `ipc_monitor.rs` to `src-tauri/src/ipc/monitor.rs` - Better organization emphasizing IPC relationship - Updated module exports and imports - **IpcManager**: Migrated to `singleton_with_logging\!` macro - **ProxyRequestCache**: Migrated to `singleton\!` macro - Eliminated ~30 lines of boilerplate singleton code - Consistent logging and initialization patterns - Removed unused imports (OnceLock, once_cell, logging::Type) - Cleaner, more maintainable code structure - All 11 unit tests pass successfully - Zero compilation warnings - **Lines of code reduced**: ~50+ lines of boilerplate - **Consistency improved**: Unified singleton patterns - **Maintainability enhanced**: Centralized utility functions - **Test coverage maintained**: 100% test pass rate Remaining complex monitors (traffic, memory, logs) will be migrated to use the shared IPC monitoring patterns in the next phase, which requires careful refactoring of their streaming logic. * refactor: complete singleton pattern migration to utility macros Migrate remaining singleton patterns across the backend to use standardized utility macros, achieving significant code reduction and consistency improvements. - **LogsMonitor** (ipc/logs.rs): `OnceLock` → `singleton_with_logging\!` - **Sysopt** (core/sysopt.rs): `OnceCell` → `singleton_lazy\!` - **Tray** (core/tray/mod.rs): Complex `OnceCell` → `singleton_lazy\!` - **Handle** (core/handle.rs): `OnceCell` → `singleton\!` - **CoreManager** (core/core.rs): `OnceCell` → `singleton_lazy\!` - **TrafficMonitor** (ipc/traffic.rs): `OnceLock` → `singleton_lazy_with_logging\!` - **MemoryMonitor** (ipc/memory.rs): `OnceLock` → `singleton_lazy_with_logging\!` - `singleton_lazy\!` - For complex initialization patterns - `singleton_lazy_with_logging\!` - For complex initialization with logging - **Code Reduction**: -33 lines of boilerplate singleton code - **DRY Compliance**: Eliminated duplicate initialization patterns - **Consistency**: Unified singleton approach across codebase - **Maintainability**: Centralized singleton logic in utility macros - **Zero Breaking Changes**: All existing APIs remain compatible All tests pass and clippy warnings resolved. * refactor: optimize singleton macros using Default trait implementation Simplify singleton macro usage by implementing Default trait for complex initialization patterns, significantly improving code readability and maintainability. - **MemoryMonitor**: Move IPC client initialization to Default impl - **TrafficMonitor**: Move IPC client initialization to Default impl - **Sysopt**: Move Arc<Mutex> initialization to Default impl - **Tray**: Move struct field initialization to Default impl - **CoreManager**: Move Arc<Mutex> initialization to Default impl ```rust singleton_lazy_with_logging\!(MemoryMonitor, INSTANCE, "MemoryMonitor", || { let ipc_path_buf = ipc_path().unwrap(); let ipc_path = ipc_path_buf.to_str().unwrap_or_default(); let client = IpcStreamClient::new(ipc_path).unwrap(); MemoryMonitor::new(client) }); ``` ```rust impl Default for MemoryMonitor { /* initialization logic */ } singleton_lazy_with_logging\!(MemoryMonitor, INSTANCE, "MemoryMonitor", MemoryMonitor::default); ``` - **Code Reduction**: -17 lines of macro closure code (80%+ simplification) - **Separation of Concerns**: Initialization logic moved to proper Default impl - **Readability**: Single-line macro calls vs multi-line closures - **Testability**: Default implementations can be tested independently - **Rust Idioms**: Using standard Default trait pattern - **Performance**: Function calls more efficient than closures All tests pass and clippy warnings resolved. * refactor: implement MonitorData and StreamingParser traits for IPC monitors * refactor: add timeout and retry_interval fields to IpcStreamMonitor; update TrafficMonitorState to derive Default * refactor: migrate AppHandleManager to unified singleton control - Replace manual singleton implementation with singleton_with_logging\! macro - Remove std::sync::Once dependency in favor of OnceLock-based pattern - Improve error handling for macOS activation policy methods - Maintain thread safety with parking_lot::Mutex for AppHandle storage - Add proper initialization check to prevent duplicate handle assignment - Enhance logging consistency across AppHandleManager operations * refactor: improve hotkey management with enum-based operations - Add HotkeyFunction enum for type-safe function selection - Add SystemHotkey enum for predefined system shortcuts - Implement Display and FromStr traits for type conversions - Replace string-based hotkey registration with enum methods - Add register_system_hotkey() and unregister_system_hotkey() methods - Maintain backward compatibility with string-based register() method - Migrate singleton pattern to use singleton_with_logging\! macro - Extract hotkey function execution logic into centralized execute_function() - Update lib.rs to use new enum-based SystemHotkey operations - Improve type safety and reduce string manipulation errors Benefits: - Type safety prevents invalid hotkey function names - Centralized function execution reduces code duplication - Enum-based API provides better IDE autocomplete support - Maintains full backward compatibility with existing configurations * fix: resolve LightWeightState initialization order panic - Modify with_lightweight_status() to safely handle unmanaged state using try_state() - Return Option<R> instead of R to gracefully handle state unavailability - Update is_in_lightweight_mode() to use unwrap_or(false) for safe defaults - Add state availability check in auto_lightweight_mode_init() before access - Maintain singleton check priority while preventing early state access panics - Fix clippy warnings for redundant pattern matching Resolves runtime panic: "state() called before manage() for LightWeightState" * refactor: add unreachable patterns for non-macOS in hotkey handling * refactor: simplify SystemHotkey enum by removing redundant cfg attributes * refactor: add macOS conditional compilation for system hotkey registration methods * refactor: streamline hotkey unregistration and error logging for macOS
2025-07-31 14:35:13 +08:00
logging, logging_error, singleton_lazy,
2025-04-21 00:06:37 +08:00
utils::logging::Type,
2024-05-26 17:59:39 +08:00
};
2024-11-20 03:52:19 +08:00
use anyhow::Result;
use scopeguard::defer;
use smartstring::alias::String;
use std::sync::atomic::{AtomicBool, Ordering};
#[cfg(not(target_os = "windows"))]
2024-05-26 17:59:39 +08:00
use sysproxy::{Autoproxy, Sysproxy};
2024-11-20 03:52:19 +08:00
use tauri_plugin_autostart::ManagerExt;
2022-04-20 01:44:47 +08:00
pub struct Sysopt {
update_sysproxy: AtomicBool,
reset_sysproxy: AtomicBool,
2022-04-20 01:44:47 +08:00
}
2022-09-11 20:58:55 +08:00
#[cfg(target_os = "windows")]
static DEFAULT_BYPASS: &str = "localhost;127.*;192.168.*;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;<local>";
2022-09-11 20:58:55 +08:00
#[cfg(target_os = "linux")]
static DEFAULT_BYPASS: &str =
"localhost,127.0.0.1,192.168.0.0/16,10.0.0.0/8,172.16.0.0/12,172.29.0.0/16,::1";
2022-09-11 20:58:55 +08:00
#[cfg(target_os = "macos")]
static DEFAULT_BYPASS: &str = "127.0.0.1,192.168.0.0/16,10.0.0.0/8,172.16.0.0/12,172.29.0.0/16,localhost,*.local,*.crashlytics.com,<local>";
2022-09-11 20:58:55 +08:00
refactor(async): migrate from sync-blocking async execution to true async with unified AsyncHandler::spawn (#4502) * feat: replace all tokio::spawn with unified AsyncHandler::spawn - 🚀 Core Improvements: * Replace all tokio::spawn calls with AsyncHandler::spawn for unified Tauri async task management * Prioritize converting sync functions to async functions to reduce spawn usage * Use .await directly in async contexts instead of spawn - 🔧 Major Changes: * core/hotkey.rs: Use AsyncHandler::spawn for hotkey callback functions * module/lightweight.rs: Async lightweight mode switching * feat/window.rs: Convert window operation functions to async, use .await internally * feat/proxy.rs, feat/clash.rs: Async proxy and mode switching functions * lib.rs: Window focus handling with AsyncHandler::spawn * core/tray/mod.rs: Complete async tray event handling - ✨ Technical Advantages: * Unified task tracking and debugging capabilities (via tokio-trace feature) * Better error handling and task management * Consistency with Tauri runtime * Reduced async boundaries for better performance - 🧪 Verification: * Compilation successful with 0 errors, 0 warnings * Maintains complete original functionality * Optimized async execution flow * feat: complete tokio fs migration and replace tokio::spawn with AsyncHandler 🚀 Major achievements: - Migrate 8 core modules from std::fs to tokio::fs - Create 6 Send-safe wrapper functions using spawn_blocking pattern - Replace all tokio::spawn calls with AsyncHandler::spawn for unified async task management - Solve all 19 Send trait compilation errors through innovative spawn_blocking architecture 🔧 Core changes: - config/profiles.rs: Add profiles_*_safe functions to handle Send trait constraints - cmd/profile.rs: Update all Tauri commands to use Send-safe operations - config/prfitem.rs: Replace append_item calls with profiles_append_item_safe - utils/help.rs: Convert YAML operations to async (read_yaml, save_yaml) - Multiple modules: Replace tokio::task::spawn_blocking with AsyncHandler::spawn_blocking ✅ Technical innovations: - spawn_blocking wrapper pattern resolves parking_lot RwLock Send trait conflicts - Maintain parking_lot performance while achieving Tauri async command compatibility - Preserve backwards compatibility with gradual migration strategy 🎯 Results: - Zero compilation errors - Zero warnings - All async file operations working correctly - Complete Send trait compliance for Tauri commands * feat: refactor app handle and command functions to use async/await for improved performance * feat: update async handling in profiles and logging functions for improved error handling and performance * fix: update TRACE_MINI_SIZE constant to improve task logging threshold * fix(windows): convert service management functions to async for improved performance * fix: convert service management functions to async for improved responsiveness * fix(ubuntu): convert install and reinstall service functions to async for improved performance * fix(linux): convert uninstall_service function to async for improved performance * fix: convert uninstall_service call to async for improved performance * fix: convert file and directory creation calls to async for improved performance * fix: convert hotkey functions to async for improved responsiveness * chore: update UPDATELOG.md for v2.4.1 with major improvements and performance optimizations
2025-08-26 01:49:51 +08:00
async fn get_bypass() -> String {
let use_default = Config::verge()
refactor(async): migrate from sync-blocking async execution to true async with unified AsyncHandler::spawn (#4502) * feat: replace all tokio::spawn with unified AsyncHandler::spawn - 🚀 Core Improvements: * Replace all tokio::spawn calls with AsyncHandler::spawn for unified Tauri async task management * Prioritize converting sync functions to async functions to reduce spawn usage * Use .await directly in async contexts instead of spawn - 🔧 Major Changes: * core/hotkey.rs: Use AsyncHandler::spawn for hotkey callback functions * module/lightweight.rs: Async lightweight mode switching * feat/window.rs: Convert window operation functions to async, use .await internally * feat/proxy.rs, feat/clash.rs: Async proxy and mode switching functions * lib.rs: Window focus handling with AsyncHandler::spawn * core/tray/mod.rs: Complete async tray event handling - ✨ Technical Advantages: * Unified task tracking and debugging capabilities (via tokio-trace feature) * Better error handling and task management * Consistency with Tauri runtime * Reduced async boundaries for better performance - 🧪 Verification: * Compilation successful with 0 errors, 0 warnings * Maintains complete original functionality * Optimized async execution flow * feat: complete tokio fs migration and replace tokio::spawn with AsyncHandler 🚀 Major achievements: - Migrate 8 core modules from std::fs to tokio::fs - Create 6 Send-safe wrapper functions using spawn_blocking pattern - Replace all tokio::spawn calls with AsyncHandler::spawn for unified async task management - Solve all 19 Send trait compilation errors through innovative spawn_blocking architecture 🔧 Core changes: - config/profiles.rs: Add profiles_*_safe functions to handle Send trait constraints - cmd/profile.rs: Update all Tauri commands to use Send-safe operations - config/prfitem.rs: Replace append_item calls with profiles_append_item_safe - utils/help.rs: Convert YAML operations to async (read_yaml, save_yaml) - Multiple modules: Replace tokio::task::spawn_blocking with AsyncHandler::spawn_blocking ✅ Technical innovations: - spawn_blocking wrapper pattern resolves parking_lot RwLock Send trait conflicts - Maintain parking_lot performance while achieving Tauri async command compatibility - Preserve backwards compatibility with gradual migration strategy 🎯 Results: - Zero compilation errors - Zero warnings - All async file operations working correctly - Complete Send trait compliance for Tauri commands * feat: refactor app handle and command functions to use async/await for improved performance * feat: update async handling in profiles and logging functions for improved error handling and performance * fix: update TRACE_MINI_SIZE constant to improve task logging threshold * fix(windows): convert service management functions to async for improved performance * fix: convert service management functions to async for improved responsiveness * fix(ubuntu): convert install and reinstall service functions to async for improved performance * fix(linux): convert uninstall_service function to async for improved performance * fix: convert uninstall_service call to async for improved performance * fix: convert file and directory creation calls to async for improved performance * fix: convert hotkey functions to async for improved responsiveness * chore: update UPDATELOG.md for v2.4.1 with major improvements and performance optimizations
2025-08-26 01:49:51 +08:00
.await
.latest_ref()
.use_default_bypass
.unwrap_or(true);
2024-06-12 10:00:22 +08:00
let res = {
refactor(async): migrate from sync-blocking async execution to true async with unified AsyncHandler::spawn (#4502) * feat: replace all tokio::spawn with unified AsyncHandler::spawn - 🚀 Core Improvements: * Replace all tokio::spawn calls with AsyncHandler::spawn for unified Tauri async task management * Prioritize converting sync functions to async functions to reduce spawn usage * Use .await directly in async contexts instead of spawn - 🔧 Major Changes: * core/hotkey.rs: Use AsyncHandler::spawn for hotkey callback functions * module/lightweight.rs: Async lightweight mode switching * feat/window.rs: Convert window operation functions to async, use .await internally * feat/proxy.rs, feat/clash.rs: Async proxy and mode switching functions * lib.rs: Window focus handling with AsyncHandler::spawn * core/tray/mod.rs: Complete async tray event handling - ✨ Technical Advantages: * Unified task tracking and debugging capabilities (via tokio-trace feature) * Better error handling and task management * Consistency with Tauri runtime * Reduced async boundaries for better performance - 🧪 Verification: * Compilation successful with 0 errors, 0 warnings * Maintains complete original functionality * Optimized async execution flow * feat: complete tokio fs migration and replace tokio::spawn with AsyncHandler 🚀 Major achievements: - Migrate 8 core modules from std::fs to tokio::fs - Create 6 Send-safe wrapper functions using spawn_blocking pattern - Replace all tokio::spawn calls with AsyncHandler::spawn for unified async task management - Solve all 19 Send trait compilation errors through innovative spawn_blocking architecture 🔧 Core changes: - config/profiles.rs: Add profiles_*_safe functions to handle Send trait constraints - cmd/profile.rs: Update all Tauri commands to use Send-safe operations - config/prfitem.rs: Replace append_item calls with profiles_append_item_safe - utils/help.rs: Convert YAML operations to async (read_yaml, save_yaml) - Multiple modules: Replace tokio::task::spawn_blocking with AsyncHandler::spawn_blocking ✅ Technical innovations: - spawn_blocking wrapper pattern resolves parking_lot RwLock Send trait conflicts - Maintain parking_lot performance while achieving Tauri async command compatibility - Preserve backwards compatibility with gradual migration strategy 🎯 Results: - Zero compilation errors - Zero warnings - All async file operations working correctly - Complete Send trait compliance for Tauri commands * feat: refactor app handle and command functions to use async/await for improved performance * feat: update async handling in profiles and logging functions for improved error handling and performance * fix: update TRACE_MINI_SIZE constant to improve task logging threshold * fix(windows): convert service management functions to async for improved performance * fix: convert service management functions to async for improved responsiveness * fix(ubuntu): convert install and reinstall service functions to async for improved performance * fix(linux): convert uninstall_service function to async for improved performance * fix: convert uninstall_service call to async for improved performance * fix: convert file and directory creation calls to async for improved performance * fix: convert hotkey functions to async for improved responsiveness * chore: update UPDATELOG.md for v2.4.1 with major improvements and performance optimizations
2025-08-26 01:49:51 +08:00
let verge = Config::verge().await;
let verge = verge.latest_ref();
2024-06-09 12:45:57 +08:00
verge.system_proxy_bypass.clone()
2024-06-12 10:00:22 +08:00
};
let custom_bypass = match res {
2024-06-09 12:45:57 +08:00
Some(bypass) => bypass,
None => "".into(),
2024-06-09 12:45:57 +08:00
};
2024-10-05 02:58:41 +08:00
2024-10-10 18:40:39 +08:00
if custom_bypass.is_empty() {
DEFAULT_BYPASS.into()
2024-09-24 20:06:25 +08:00
} else if use_default {
format!("{DEFAULT_BYPASS},{custom_bypass}").into()
2024-06-09 12:45:57 +08:00
} else {
2024-09-24 20:06:25 +08:00
custom_bypass
2024-10-10 18:40:39 +08:00
}
2024-06-09 12:45:57 +08:00
}
// Uses tokio Command with CREATE_NO_WINDOW flag to avoid DLL initialization issues during shutdown
#[cfg(target_os = "windows")]
async fn execute_sysproxy_command(args: Vec<std::string::String>) -> Result<()> {
use crate::utils::dirs;
use anyhow::bail;
#[allow(unused_imports)] // Required for .creation_flags() method
use std::os::windows::process::CommandExt;
use tokio::process::Command;
let binary_path = dirs::service_path()?;
let sysproxy_exe = binary_path.with_file_name("sysproxy.exe");
if !sysproxy_exe.exists() {
bail!("sysproxy.exe not found");
}
let output = Command::new(sysproxy_exe)
.args(args)
.creation_flags(0x08000000) // CREATE_NO_WINDOW - 隐藏窗口
.output()
.await?;
if !output.status.success() {
bail!("sysproxy exe run failed");
}
Ok(())
}
refactor: optimize singleton macro usage with Default trait implementations (#4279) * refactor: implement DRY principle improvements across backend Major DRY violations identified and addressed: 1. **IPC Stream Monitor Pattern**: - Created `utils/ipc_monitor.rs` with generic `IpcStreamMonitor` trait - Added `IpcMonitorManager` for common async task management patterns - Eliminates duplication across traffic.rs, memory.rs, and logs.rs 2. **Singleton Pattern Duplication**: - Created `utils/singleton.rs` with `singleton\!` and `singleton_with_logging\!` macros - Replaces 16+ duplicate singleton implementations across codebase - Provides consistent, tested patterns for global instances 3. **macOS Activation Policy Refactoring**: - Consolidated 3 duplicate methods into single parameterized `set_activation_policy()` - Eliminated code duplication while maintaining backward compatibility - Reduced maintenance burden for macOS-specific functionality These improvements enhance maintainability, reduce bug potential, and ensure consistent patterns across the backend codebase. * fix: resolve test failures and clippy warnings - Fix doctest in singleton.rs by using rust,ignore syntax and proper code examples - Remove unused time::Instant import from ipc_monitor.rs - Add #[allow(dead_code)] attributes to future-use utility modules - All 11 unit tests now pass successfully - All clippy checks pass with -D warnings strict mode - Documentation tests properly ignore example code that requires full context * refactor: migrate code to use new utility tools (partial) Progress on systematic migration to use created utility tools: 1. **Reorganized IPC Monitor**: - Moved ipc_monitor.rs to src-tauri/src/ipc/monitor.rs for better organization - Updated module structure to emphasize IPC relationship 2. **IpcManager Singleton Migration**: - Replaced manual OnceLock singleton pattern with singleton_with_logging\! macro - Simplified initialization code and added consistent logging - Removed unused imports (OnceLock, logging::Type) 3. **ProxyRequestCache Singleton Migration**: - Migrated from once_cell::sync::OnceCell to singleton\! macro - Cleaner, more maintainable singleton pattern - Consistent with project-wide singleton approach These migrations demonstrate the utility and effectiveness of the created tools: - Less boilerplate code - Consistent patterns across codebase - Easier maintenance and debugging * feat: complete migration to new utility tools - phase 1 Successfully migrated core components to use the created utility tools: - Moved `ipc_monitor.rs` to `src-tauri/src/ipc/monitor.rs` - Better organization emphasizing IPC relationship - Updated module exports and imports - **IpcManager**: Migrated to `singleton_with_logging\!` macro - **ProxyRequestCache**: Migrated to `singleton\!` macro - Eliminated ~30 lines of boilerplate singleton code - Consistent logging and initialization patterns - Removed unused imports (OnceLock, once_cell, logging::Type) - Cleaner, more maintainable code structure - All 11 unit tests pass successfully - Zero compilation warnings - **Lines of code reduced**: ~50+ lines of boilerplate - **Consistency improved**: Unified singleton patterns - **Maintainability enhanced**: Centralized utility functions - **Test coverage maintained**: 100% test pass rate Remaining complex monitors (traffic, memory, logs) will be migrated to use the shared IPC monitoring patterns in the next phase, which requires careful refactoring of their streaming logic. * refactor: complete singleton pattern migration to utility macros Migrate remaining singleton patterns across the backend to use standardized utility macros, achieving significant code reduction and consistency improvements. - **LogsMonitor** (ipc/logs.rs): `OnceLock` → `singleton_with_logging\!` - **Sysopt** (core/sysopt.rs): `OnceCell` → `singleton_lazy\!` - **Tray** (core/tray/mod.rs): Complex `OnceCell` → `singleton_lazy\!` - **Handle** (core/handle.rs): `OnceCell` → `singleton\!` - **CoreManager** (core/core.rs): `OnceCell` → `singleton_lazy\!` - **TrafficMonitor** (ipc/traffic.rs): `OnceLock` → `singleton_lazy_with_logging\!` - **MemoryMonitor** (ipc/memory.rs): `OnceLock` → `singleton_lazy_with_logging\!` - `singleton_lazy\!` - For complex initialization patterns - `singleton_lazy_with_logging\!` - For complex initialization with logging - **Code Reduction**: -33 lines of boilerplate singleton code - **DRY Compliance**: Eliminated duplicate initialization patterns - **Consistency**: Unified singleton approach across codebase - **Maintainability**: Centralized singleton logic in utility macros - **Zero Breaking Changes**: All existing APIs remain compatible All tests pass and clippy warnings resolved. * refactor: optimize singleton macros using Default trait implementation Simplify singleton macro usage by implementing Default trait for complex initialization patterns, significantly improving code readability and maintainability. - **MemoryMonitor**: Move IPC client initialization to Default impl - **TrafficMonitor**: Move IPC client initialization to Default impl - **Sysopt**: Move Arc<Mutex> initialization to Default impl - **Tray**: Move struct field initialization to Default impl - **CoreManager**: Move Arc<Mutex> initialization to Default impl ```rust singleton_lazy_with_logging\!(MemoryMonitor, INSTANCE, "MemoryMonitor", || { let ipc_path_buf = ipc_path().unwrap(); let ipc_path = ipc_path_buf.to_str().unwrap_or_default(); let client = IpcStreamClient::new(ipc_path).unwrap(); MemoryMonitor::new(client) }); ``` ```rust impl Default for MemoryMonitor { /* initialization logic */ } singleton_lazy_with_logging\!(MemoryMonitor, INSTANCE, "MemoryMonitor", MemoryMonitor::default); ``` - **Code Reduction**: -17 lines of macro closure code (80%+ simplification) - **Separation of Concerns**: Initialization logic moved to proper Default impl - **Readability**: Single-line macro calls vs multi-line closures - **Testability**: Default implementations can be tested independently - **Rust Idioms**: Using standard Default trait pattern - **Performance**: Function calls more efficient than closures All tests pass and clippy warnings resolved. * refactor: implement MonitorData and StreamingParser traits for IPC monitors * refactor: add timeout and retry_interval fields to IpcStreamMonitor; update TrafficMonitorState to derive Default * refactor: migrate AppHandleManager to unified singleton control - Replace manual singleton implementation with singleton_with_logging\! macro - Remove std::sync::Once dependency in favor of OnceLock-based pattern - Improve error handling for macOS activation policy methods - Maintain thread safety with parking_lot::Mutex for AppHandle storage - Add proper initialization check to prevent duplicate handle assignment - Enhance logging consistency across AppHandleManager operations * refactor: improve hotkey management with enum-based operations - Add HotkeyFunction enum for type-safe function selection - Add SystemHotkey enum for predefined system shortcuts - Implement Display and FromStr traits for type conversions - Replace string-based hotkey registration with enum methods - Add register_system_hotkey() and unregister_system_hotkey() methods - Maintain backward compatibility with string-based register() method - Migrate singleton pattern to use singleton_with_logging\! macro - Extract hotkey function execution logic into centralized execute_function() - Update lib.rs to use new enum-based SystemHotkey operations - Improve type safety and reduce string manipulation errors Benefits: - Type safety prevents invalid hotkey function names - Centralized function execution reduces code duplication - Enum-based API provides better IDE autocomplete support - Maintains full backward compatibility with existing configurations * fix: resolve LightWeightState initialization order panic - Modify with_lightweight_status() to safely handle unmanaged state using try_state() - Return Option<R> instead of R to gracefully handle state unavailability - Update is_in_lightweight_mode() to use unwrap_or(false) for safe defaults - Add state availability check in auto_lightweight_mode_init() before access - Maintain singleton check priority while preventing early state access panics - Fix clippy warnings for redundant pattern matching Resolves runtime panic: "state() called before manage() for LightWeightState" * refactor: add unreachable patterns for non-macOS in hotkey handling * refactor: simplify SystemHotkey enum by removing redundant cfg attributes * refactor: add macOS conditional compilation for system hotkey registration methods * refactor: streamline hotkey unregistration and error logging for macOS
2025-07-31 14:35:13 +08:00
impl Default for Sysopt {
fn default() -> Self {
Sysopt {
update_sysproxy: AtomicBool::new(false),
reset_sysproxy: AtomicBool::new(false),
refactor: optimize singleton macro usage with Default trait implementations (#4279) * refactor: implement DRY principle improvements across backend Major DRY violations identified and addressed: 1. **IPC Stream Monitor Pattern**: - Created `utils/ipc_monitor.rs` with generic `IpcStreamMonitor` trait - Added `IpcMonitorManager` for common async task management patterns - Eliminates duplication across traffic.rs, memory.rs, and logs.rs 2. **Singleton Pattern Duplication**: - Created `utils/singleton.rs` with `singleton\!` and `singleton_with_logging\!` macros - Replaces 16+ duplicate singleton implementations across codebase - Provides consistent, tested patterns for global instances 3. **macOS Activation Policy Refactoring**: - Consolidated 3 duplicate methods into single parameterized `set_activation_policy()` - Eliminated code duplication while maintaining backward compatibility - Reduced maintenance burden for macOS-specific functionality These improvements enhance maintainability, reduce bug potential, and ensure consistent patterns across the backend codebase. * fix: resolve test failures and clippy warnings - Fix doctest in singleton.rs by using rust,ignore syntax and proper code examples - Remove unused time::Instant import from ipc_monitor.rs - Add #[allow(dead_code)] attributes to future-use utility modules - All 11 unit tests now pass successfully - All clippy checks pass with -D warnings strict mode - Documentation tests properly ignore example code that requires full context * refactor: migrate code to use new utility tools (partial) Progress on systematic migration to use created utility tools: 1. **Reorganized IPC Monitor**: - Moved ipc_monitor.rs to src-tauri/src/ipc/monitor.rs for better organization - Updated module structure to emphasize IPC relationship 2. **IpcManager Singleton Migration**: - Replaced manual OnceLock singleton pattern with singleton_with_logging\! macro - Simplified initialization code and added consistent logging - Removed unused imports (OnceLock, logging::Type) 3. **ProxyRequestCache Singleton Migration**: - Migrated from once_cell::sync::OnceCell to singleton\! macro - Cleaner, more maintainable singleton pattern - Consistent with project-wide singleton approach These migrations demonstrate the utility and effectiveness of the created tools: - Less boilerplate code - Consistent patterns across codebase - Easier maintenance and debugging * feat: complete migration to new utility tools - phase 1 Successfully migrated core components to use the created utility tools: - Moved `ipc_monitor.rs` to `src-tauri/src/ipc/monitor.rs` - Better organization emphasizing IPC relationship - Updated module exports and imports - **IpcManager**: Migrated to `singleton_with_logging\!` macro - **ProxyRequestCache**: Migrated to `singleton\!` macro - Eliminated ~30 lines of boilerplate singleton code - Consistent logging and initialization patterns - Removed unused imports (OnceLock, once_cell, logging::Type) - Cleaner, more maintainable code structure - All 11 unit tests pass successfully - Zero compilation warnings - **Lines of code reduced**: ~50+ lines of boilerplate - **Consistency improved**: Unified singleton patterns - **Maintainability enhanced**: Centralized utility functions - **Test coverage maintained**: 100% test pass rate Remaining complex monitors (traffic, memory, logs) will be migrated to use the shared IPC monitoring patterns in the next phase, which requires careful refactoring of their streaming logic. * refactor: complete singleton pattern migration to utility macros Migrate remaining singleton patterns across the backend to use standardized utility macros, achieving significant code reduction and consistency improvements. - **LogsMonitor** (ipc/logs.rs): `OnceLock` → `singleton_with_logging\!` - **Sysopt** (core/sysopt.rs): `OnceCell` → `singleton_lazy\!` - **Tray** (core/tray/mod.rs): Complex `OnceCell` → `singleton_lazy\!` - **Handle** (core/handle.rs): `OnceCell` → `singleton\!` - **CoreManager** (core/core.rs): `OnceCell` → `singleton_lazy\!` - **TrafficMonitor** (ipc/traffic.rs): `OnceLock` → `singleton_lazy_with_logging\!` - **MemoryMonitor** (ipc/memory.rs): `OnceLock` → `singleton_lazy_with_logging\!` - `singleton_lazy\!` - For complex initialization patterns - `singleton_lazy_with_logging\!` - For complex initialization with logging - **Code Reduction**: -33 lines of boilerplate singleton code - **DRY Compliance**: Eliminated duplicate initialization patterns - **Consistency**: Unified singleton approach across codebase - **Maintainability**: Centralized singleton logic in utility macros - **Zero Breaking Changes**: All existing APIs remain compatible All tests pass and clippy warnings resolved. * refactor: optimize singleton macros using Default trait implementation Simplify singleton macro usage by implementing Default trait for complex initialization patterns, significantly improving code readability and maintainability. - **MemoryMonitor**: Move IPC client initialization to Default impl - **TrafficMonitor**: Move IPC client initialization to Default impl - **Sysopt**: Move Arc<Mutex> initialization to Default impl - **Tray**: Move struct field initialization to Default impl - **CoreManager**: Move Arc<Mutex> initialization to Default impl ```rust singleton_lazy_with_logging\!(MemoryMonitor, INSTANCE, "MemoryMonitor", || { let ipc_path_buf = ipc_path().unwrap(); let ipc_path = ipc_path_buf.to_str().unwrap_or_default(); let client = IpcStreamClient::new(ipc_path).unwrap(); MemoryMonitor::new(client) }); ``` ```rust impl Default for MemoryMonitor { /* initialization logic */ } singleton_lazy_with_logging\!(MemoryMonitor, INSTANCE, "MemoryMonitor", MemoryMonitor::default); ``` - **Code Reduction**: -17 lines of macro closure code (80%+ simplification) - **Separation of Concerns**: Initialization logic moved to proper Default impl - **Readability**: Single-line macro calls vs multi-line closures - **Testability**: Default implementations can be tested independently - **Rust Idioms**: Using standard Default trait pattern - **Performance**: Function calls more efficient than closures All tests pass and clippy warnings resolved. * refactor: implement MonitorData and StreamingParser traits for IPC monitors * refactor: add timeout and retry_interval fields to IpcStreamMonitor; update TrafficMonitorState to derive Default * refactor: migrate AppHandleManager to unified singleton control - Replace manual singleton implementation with singleton_with_logging\! macro - Remove std::sync::Once dependency in favor of OnceLock-based pattern - Improve error handling for macOS activation policy methods - Maintain thread safety with parking_lot::Mutex for AppHandle storage - Add proper initialization check to prevent duplicate handle assignment - Enhance logging consistency across AppHandleManager operations * refactor: improve hotkey management with enum-based operations - Add HotkeyFunction enum for type-safe function selection - Add SystemHotkey enum for predefined system shortcuts - Implement Display and FromStr traits for type conversions - Replace string-based hotkey registration with enum methods - Add register_system_hotkey() and unregister_system_hotkey() methods - Maintain backward compatibility with string-based register() method - Migrate singleton pattern to use singleton_with_logging\! macro - Extract hotkey function execution logic into centralized execute_function() - Update lib.rs to use new enum-based SystemHotkey operations - Improve type safety and reduce string manipulation errors Benefits: - Type safety prevents invalid hotkey function names - Centralized function execution reduces code duplication - Enum-based API provides better IDE autocomplete support - Maintains full backward compatibility with existing configurations * fix: resolve LightWeightState initialization order panic - Modify with_lightweight_status() to safely handle unmanaged state using try_state() - Return Option<R> instead of R to gracefully handle state unavailability - Update is_in_lightweight_mode() to use unwrap_or(false) for safe defaults - Add state availability check in auto_lightweight_mode_init() before access - Maintain singleton check priority while preventing early state access panics - Fix clippy warnings for redundant pattern matching Resolves runtime panic: "state() called before manage() for LightWeightState" * refactor: add unreachable patterns for non-macOS in hotkey handling * refactor: simplify SystemHotkey enum by removing redundant cfg attributes * refactor: add macOS conditional compilation for system hotkey registration methods * refactor: streamline hotkey unregistration and error logging for macOS
2025-07-31 14:35:13 +08:00
}
2022-04-20 01:44:47 +08:00
}
refactor: optimize singleton macro usage with Default trait implementations (#4279) * refactor: implement DRY principle improvements across backend Major DRY violations identified and addressed: 1. **IPC Stream Monitor Pattern**: - Created `utils/ipc_monitor.rs` with generic `IpcStreamMonitor` trait - Added `IpcMonitorManager` for common async task management patterns - Eliminates duplication across traffic.rs, memory.rs, and logs.rs 2. **Singleton Pattern Duplication**: - Created `utils/singleton.rs` with `singleton\!` and `singleton_with_logging\!` macros - Replaces 16+ duplicate singleton implementations across codebase - Provides consistent, tested patterns for global instances 3. **macOS Activation Policy Refactoring**: - Consolidated 3 duplicate methods into single parameterized `set_activation_policy()` - Eliminated code duplication while maintaining backward compatibility - Reduced maintenance burden for macOS-specific functionality These improvements enhance maintainability, reduce bug potential, and ensure consistent patterns across the backend codebase. * fix: resolve test failures and clippy warnings - Fix doctest in singleton.rs by using rust,ignore syntax and proper code examples - Remove unused time::Instant import from ipc_monitor.rs - Add #[allow(dead_code)] attributes to future-use utility modules - All 11 unit tests now pass successfully - All clippy checks pass with -D warnings strict mode - Documentation tests properly ignore example code that requires full context * refactor: migrate code to use new utility tools (partial) Progress on systematic migration to use created utility tools: 1. **Reorganized IPC Monitor**: - Moved ipc_monitor.rs to src-tauri/src/ipc/monitor.rs for better organization - Updated module structure to emphasize IPC relationship 2. **IpcManager Singleton Migration**: - Replaced manual OnceLock singleton pattern with singleton_with_logging\! macro - Simplified initialization code and added consistent logging - Removed unused imports (OnceLock, logging::Type) 3. **ProxyRequestCache Singleton Migration**: - Migrated from once_cell::sync::OnceCell to singleton\! macro - Cleaner, more maintainable singleton pattern - Consistent with project-wide singleton approach These migrations demonstrate the utility and effectiveness of the created tools: - Less boilerplate code - Consistent patterns across codebase - Easier maintenance and debugging * feat: complete migration to new utility tools - phase 1 Successfully migrated core components to use the created utility tools: - Moved `ipc_monitor.rs` to `src-tauri/src/ipc/monitor.rs` - Better organization emphasizing IPC relationship - Updated module exports and imports - **IpcManager**: Migrated to `singleton_with_logging\!` macro - **ProxyRequestCache**: Migrated to `singleton\!` macro - Eliminated ~30 lines of boilerplate singleton code - Consistent logging and initialization patterns - Removed unused imports (OnceLock, once_cell, logging::Type) - Cleaner, more maintainable code structure - All 11 unit tests pass successfully - Zero compilation warnings - **Lines of code reduced**: ~50+ lines of boilerplate - **Consistency improved**: Unified singleton patterns - **Maintainability enhanced**: Centralized utility functions - **Test coverage maintained**: 100% test pass rate Remaining complex monitors (traffic, memory, logs) will be migrated to use the shared IPC monitoring patterns in the next phase, which requires careful refactoring of their streaming logic. * refactor: complete singleton pattern migration to utility macros Migrate remaining singleton patterns across the backend to use standardized utility macros, achieving significant code reduction and consistency improvements. - **LogsMonitor** (ipc/logs.rs): `OnceLock` → `singleton_with_logging\!` - **Sysopt** (core/sysopt.rs): `OnceCell` → `singleton_lazy\!` - **Tray** (core/tray/mod.rs): Complex `OnceCell` → `singleton_lazy\!` - **Handle** (core/handle.rs): `OnceCell` → `singleton\!` - **CoreManager** (core/core.rs): `OnceCell` → `singleton_lazy\!` - **TrafficMonitor** (ipc/traffic.rs): `OnceLock` → `singleton_lazy_with_logging\!` - **MemoryMonitor** (ipc/memory.rs): `OnceLock` → `singleton_lazy_with_logging\!` - `singleton_lazy\!` - For complex initialization patterns - `singleton_lazy_with_logging\!` - For complex initialization with logging - **Code Reduction**: -33 lines of boilerplate singleton code - **DRY Compliance**: Eliminated duplicate initialization patterns - **Consistency**: Unified singleton approach across codebase - **Maintainability**: Centralized singleton logic in utility macros - **Zero Breaking Changes**: All existing APIs remain compatible All tests pass and clippy warnings resolved. * refactor: optimize singleton macros using Default trait implementation Simplify singleton macro usage by implementing Default trait for complex initialization patterns, significantly improving code readability and maintainability. - **MemoryMonitor**: Move IPC client initialization to Default impl - **TrafficMonitor**: Move IPC client initialization to Default impl - **Sysopt**: Move Arc<Mutex> initialization to Default impl - **Tray**: Move struct field initialization to Default impl - **CoreManager**: Move Arc<Mutex> initialization to Default impl ```rust singleton_lazy_with_logging\!(MemoryMonitor, INSTANCE, "MemoryMonitor", || { let ipc_path_buf = ipc_path().unwrap(); let ipc_path = ipc_path_buf.to_str().unwrap_or_default(); let client = IpcStreamClient::new(ipc_path).unwrap(); MemoryMonitor::new(client) }); ``` ```rust impl Default for MemoryMonitor { /* initialization logic */ } singleton_lazy_with_logging\!(MemoryMonitor, INSTANCE, "MemoryMonitor", MemoryMonitor::default); ``` - **Code Reduction**: -17 lines of macro closure code (80%+ simplification) - **Separation of Concerns**: Initialization logic moved to proper Default impl - **Readability**: Single-line macro calls vs multi-line closures - **Testability**: Default implementations can be tested independently - **Rust Idioms**: Using standard Default trait pattern - **Performance**: Function calls more efficient than closures All tests pass and clippy warnings resolved. * refactor: implement MonitorData and StreamingParser traits for IPC monitors * refactor: add timeout and retry_interval fields to IpcStreamMonitor; update TrafficMonitorState to derive Default * refactor: migrate AppHandleManager to unified singleton control - Replace manual singleton implementation with singleton_with_logging\! macro - Remove std::sync::Once dependency in favor of OnceLock-based pattern - Improve error handling for macOS activation policy methods - Maintain thread safety with parking_lot::Mutex for AppHandle storage - Add proper initialization check to prevent duplicate handle assignment - Enhance logging consistency across AppHandleManager operations * refactor: improve hotkey management with enum-based operations - Add HotkeyFunction enum for type-safe function selection - Add SystemHotkey enum for predefined system shortcuts - Implement Display and FromStr traits for type conversions - Replace string-based hotkey registration with enum methods - Add register_system_hotkey() and unregister_system_hotkey() methods - Maintain backward compatibility with string-based register() method - Migrate singleton pattern to use singleton_with_logging\! macro - Extract hotkey function execution logic into centralized execute_function() - Update lib.rs to use new enum-based SystemHotkey operations - Improve type safety and reduce string manipulation errors Benefits: - Type safety prevents invalid hotkey function names - Centralized function execution reduces code duplication - Enum-based API provides better IDE autocomplete support - Maintains full backward compatibility with existing configurations * fix: resolve LightWeightState initialization order panic - Modify with_lightweight_status() to safely handle unmanaged state using try_state() - Return Option<R> instead of R to gracefully handle state unavailability - Update is_in_lightweight_mode() to use unwrap_or(false) for safe defaults - Add state availability check in auto_lightweight_mode_init() before access - Maintain singleton check priority while preventing early state access panics - Fix clippy warnings for redundant pattern matching Resolves runtime panic: "state() called before manage() for LightWeightState" * refactor: add unreachable patterns for non-macOS in hotkey handling * refactor: simplify SystemHotkey enum by removing redundant cfg attributes * refactor: add macOS conditional compilation for system hotkey registration methods * refactor: streamline hotkey unregistration and error logging for macOS
2025-07-31 14:35:13 +08:00
}
2022-04-20 01:44:47 +08:00
refactor: optimize singleton macro usage with Default trait implementations (#4279) * refactor: implement DRY principle improvements across backend Major DRY violations identified and addressed: 1. **IPC Stream Monitor Pattern**: - Created `utils/ipc_monitor.rs` with generic `IpcStreamMonitor` trait - Added `IpcMonitorManager` for common async task management patterns - Eliminates duplication across traffic.rs, memory.rs, and logs.rs 2. **Singleton Pattern Duplication**: - Created `utils/singleton.rs` with `singleton\!` and `singleton_with_logging\!` macros - Replaces 16+ duplicate singleton implementations across codebase - Provides consistent, tested patterns for global instances 3. **macOS Activation Policy Refactoring**: - Consolidated 3 duplicate methods into single parameterized `set_activation_policy()` - Eliminated code duplication while maintaining backward compatibility - Reduced maintenance burden for macOS-specific functionality These improvements enhance maintainability, reduce bug potential, and ensure consistent patterns across the backend codebase. * fix: resolve test failures and clippy warnings - Fix doctest in singleton.rs by using rust,ignore syntax and proper code examples - Remove unused time::Instant import from ipc_monitor.rs - Add #[allow(dead_code)] attributes to future-use utility modules - All 11 unit tests now pass successfully - All clippy checks pass with -D warnings strict mode - Documentation tests properly ignore example code that requires full context * refactor: migrate code to use new utility tools (partial) Progress on systematic migration to use created utility tools: 1. **Reorganized IPC Monitor**: - Moved ipc_monitor.rs to src-tauri/src/ipc/monitor.rs for better organization - Updated module structure to emphasize IPC relationship 2. **IpcManager Singleton Migration**: - Replaced manual OnceLock singleton pattern with singleton_with_logging\! macro - Simplified initialization code and added consistent logging - Removed unused imports (OnceLock, logging::Type) 3. **ProxyRequestCache Singleton Migration**: - Migrated from once_cell::sync::OnceCell to singleton\! macro - Cleaner, more maintainable singleton pattern - Consistent with project-wide singleton approach These migrations demonstrate the utility and effectiveness of the created tools: - Less boilerplate code - Consistent patterns across codebase - Easier maintenance and debugging * feat: complete migration to new utility tools - phase 1 Successfully migrated core components to use the created utility tools: - Moved `ipc_monitor.rs` to `src-tauri/src/ipc/monitor.rs` - Better organization emphasizing IPC relationship - Updated module exports and imports - **IpcManager**: Migrated to `singleton_with_logging\!` macro - **ProxyRequestCache**: Migrated to `singleton\!` macro - Eliminated ~30 lines of boilerplate singleton code - Consistent logging and initialization patterns - Removed unused imports (OnceLock, once_cell, logging::Type) - Cleaner, more maintainable code structure - All 11 unit tests pass successfully - Zero compilation warnings - **Lines of code reduced**: ~50+ lines of boilerplate - **Consistency improved**: Unified singleton patterns - **Maintainability enhanced**: Centralized utility functions - **Test coverage maintained**: 100% test pass rate Remaining complex monitors (traffic, memory, logs) will be migrated to use the shared IPC monitoring patterns in the next phase, which requires careful refactoring of their streaming logic. * refactor: complete singleton pattern migration to utility macros Migrate remaining singleton patterns across the backend to use standardized utility macros, achieving significant code reduction and consistency improvements. - **LogsMonitor** (ipc/logs.rs): `OnceLock` → `singleton_with_logging\!` - **Sysopt** (core/sysopt.rs): `OnceCell` → `singleton_lazy\!` - **Tray** (core/tray/mod.rs): Complex `OnceCell` → `singleton_lazy\!` - **Handle** (core/handle.rs): `OnceCell` → `singleton\!` - **CoreManager** (core/core.rs): `OnceCell` → `singleton_lazy\!` - **TrafficMonitor** (ipc/traffic.rs): `OnceLock` → `singleton_lazy_with_logging\!` - **MemoryMonitor** (ipc/memory.rs): `OnceLock` → `singleton_lazy_with_logging\!` - `singleton_lazy\!` - For complex initialization patterns - `singleton_lazy_with_logging\!` - For complex initialization with logging - **Code Reduction**: -33 lines of boilerplate singleton code - **DRY Compliance**: Eliminated duplicate initialization patterns - **Consistency**: Unified singleton approach across codebase - **Maintainability**: Centralized singleton logic in utility macros - **Zero Breaking Changes**: All existing APIs remain compatible All tests pass and clippy warnings resolved. * refactor: optimize singleton macros using Default trait implementation Simplify singleton macro usage by implementing Default trait for complex initialization patterns, significantly improving code readability and maintainability. - **MemoryMonitor**: Move IPC client initialization to Default impl - **TrafficMonitor**: Move IPC client initialization to Default impl - **Sysopt**: Move Arc<Mutex> initialization to Default impl - **Tray**: Move struct field initialization to Default impl - **CoreManager**: Move Arc<Mutex> initialization to Default impl ```rust singleton_lazy_with_logging\!(MemoryMonitor, INSTANCE, "MemoryMonitor", || { let ipc_path_buf = ipc_path().unwrap(); let ipc_path = ipc_path_buf.to_str().unwrap_or_default(); let client = IpcStreamClient::new(ipc_path).unwrap(); MemoryMonitor::new(client) }); ``` ```rust impl Default for MemoryMonitor { /* initialization logic */ } singleton_lazy_with_logging\!(MemoryMonitor, INSTANCE, "MemoryMonitor", MemoryMonitor::default); ``` - **Code Reduction**: -17 lines of macro closure code (80%+ simplification) - **Separation of Concerns**: Initialization logic moved to proper Default impl - **Readability**: Single-line macro calls vs multi-line closures - **Testability**: Default implementations can be tested independently - **Rust Idioms**: Using standard Default trait pattern - **Performance**: Function calls more efficient than closures All tests pass and clippy warnings resolved. * refactor: implement MonitorData and StreamingParser traits for IPC monitors * refactor: add timeout and retry_interval fields to IpcStreamMonitor; update TrafficMonitorState to derive Default * refactor: migrate AppHandleManager to unified singleton control - Replace manual singleton implementation with singleton_with_logging\! macro - Remove std::sync::Once dependency in favor of OnceLock-based pattern - Improve error handling for macOS activation policy methods - Maintain thread safety with parking_lot::Mutex for AppHandle storage - Add proper initialization check to prevent duplicate handle assignment - Enhance logging consistency across AppHandleManager operations * refactor: improve hotkey management with enum-based operations - Add HotkeyFunction enum for type-safe function selection - Add SystemHotkey enum for predefined system shortcuts - Implement Display and FromStr traits for type conversions - Replace string-based hotkey registration with enum methods - Add register_system_hotkey() and unregister_system_hotkey() methods - Maintain backward compatibility with string-based register() method - Migrate singleton pattern to use singleton_with_logging\! macro - Extract hotkey function execution logic into centralized execute_function() - Update lib.rs to use new enum-based SystemHotkey operations - Improve type safety and reduce string manipulation errors Benefits: - Type safety prevents invalid hotkey function names - Centralized function execution reduces code duplication - Enum-based API provides better IDE autocomplete support - Maintains full backward compatibility with existing configurations * fix: resolve LightWeightState initialization order panic - Modify with_lightweight_status() to safely handle unmanaged state using try_state() - Return Option<R> instead of R to gracefully handle state unavailability - Update is_in_lightweight_mode() to use unwrap_or(false) for safe defaults - Add state availability check in auto_lightweight_mode_init() before access - Maintain singleton check priority while preventing early state access panics - Fix clippy warnings for redundant pattern matching Resolves runtime panic: "state() called before manage() for LightWeightState" * refactor: add unreachable patterns for non-macOS in hotkey handling * refactor: simplify SystemHotkey enum by removing redundant cfg attributes * refactor: add macOS conditional compilation for system hotkey registration methods * refactor: streamline hotkey unregistration and error logging for macOS
2025-07-31 14:35:13 +08:00
// Use simplified singleton_lazy macro
singleton_lazy!(Sysopt, SYSOPT, Sysopt::default);
impl Sysopt {
pub fn init_guard_sysproxy(&self) -> Result<()> {
// 使用事件驱动代理管理器
let proxy_manager = EventDrivenProxyManager::global();
proxy_manager.notify_app_started();
log::info!(target: "app", "已启用事件驱动代理守卫");
Ok(())
}
2022-11-12 11:37:23 +08:00
/// init the sysproxy
2024-10-04 05:27:59 +08:00
pub async fn update_sysproxy(&self) -> Result<()> {
if self
.update_sysproxy
.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
.is_err()
{
return Ok(());
}
defer! {
self.update_sysproxy.store(false, Ordering::SeqCst);
}
refactor(async): migrate from sync-blocking async execution to true async with unified AsyncHandler::spawn (#4502) * feat: replace all tokio::spawn with unified AsyncHandler::spawn - 🚀 Core Improvements: * Replace all tokio::spawn calls with AsyncHandler::spawn for unified Tauri async task management * Prioritize converting sync functions to async functions to reduce spawn usage * Use .await directly in async contexts instead of spawn - 🔧 Major Changes: * core/hotkey.rs: Use AsyncHandler::spawn for hotkey callback functions * module/lightweight.rs: Async lightweight mode switching * feat/window.rs: Convert window operation functions to async, use .await internally * feat/proxy.rs, feat/clash.rs: Async proxy and mode switching functions * lib.rs: Window focus handling with AsyncHandler::spawn * core/tray/mod.rs: Complete async tray event handling - ✨ Technical Advantages: * Unified task tracking and debugging capabilities (via tokio-trace feature) * Better error handling and task management * Consistency with Tauri runtime * Reduced async boundaries for better performance - 🧪 Verification: * Compilation successful with 0 errors, 0 warnings * Maintains complete original functionality * Optimized async execution flow * feat: complete tokio fs migration and replace tokio::spawn with AsyncHandler 🚀 Major achievements: - Migrate 8 core modules from std::fs to tokio::fs - Create 6 Send-safe wrapper functions using spawn_blocking pattern - Replace all tokio::spawn calls with AsyncHandler::spawn for unified async task management - Solve all 19 Send trait compilation errors through innovative spawn_blocking architecture 🔧 Core changes: - config/profiles.rs: Add profiles_*_safe functions to handle Send trait constraints - cmd/profile.rs: Update all Tauri commands to use Send-safe operations - config/prfitem.rs: Replace append_item calls with profiles_append_item_safe - utils/help.rs: Convert YAML operations to async (read_yaml, save_yaml) - Multiple modules: Replace tokio::task::spawn_blocking with AsyncHandler::spawn_blocking ✅ Technical innovations: - spawn_blocking wrapper pattern resolves parking_lot RwLock Send trait conflicts - Maintain parking_lot performance while achieving Tauri async command compatibility - Preserve backwards compatibility with gradual migration strategy 🎯 Results: - Zero compilation errors - Zero warnings - All async file operations working correctly - Complete Send trait compliance for Tauri commands * feat: refactor app handle and command functions to use async/await for improved performance * feat: update async handling in profiles and logging functions for improved error handling and performance * fix: update TRACE_MINI_SIZE constant to improve task logging threshold * fix(windows): convert service management functions to async for improved performance * fix: convert service management functions to async for improved responsiveness * fix(ubuntu): convert install and reinstall service functions to async for improved performance * fix(linux): convert uninstall_service function to async for improved performance * fix: convert uninstall_service call to async for improved performance * fix: convert file and directory creation calls to async for improved performance * fix: convert hotkey functions to async for improved responsiveness * chore: update UPDATELOG.md for v2.4.1 with major improvements and performance optimizations
2025-08-26 01:49:51 +08:00
let port = {
let verge_port = Config::verge().await.latest_ref().verge_mixed_port;
match verge_port {
Some(port) => port,
None => Config::clash().await.latest_ref().get_mixed_port(),
}
};
2024-05-26 17:59:39 +08:00
let pac_port = IVerge::get_singleton_port();
2022-09-11 20:58:55 +08:00
let (sys_enable, pac_enable, proxy_host) = {
refactor(async): migrate from sync-blocking async execution to true async with unified AsyncHandler::spawn (#4502) * feat: replace all tokio::spawn with unified AsyncHandler::spawn - 🚀 Core Improvements: * Replace all tokio::spawn calls with AsyncHandler::spawn for unified Tauri async task management * Prioritize converting sync functions to async functions to reduce spawn usage * Use .await directly in async contexts instead of spawn - 🔧 Major Changes: * core/hotkey.rs: Use AsyncHandler::spawn for hotkey callback functions * module/lightweight.rs: Async lightweight mode switching * feat/window.rs: Convert window operation functions to async, use .await internally * feat/proxy.rs, feat/clash.rs: Async proxy and mode switching functions * lib.rs: Window focus handling with AsyncHandler::spawn * core/tray/mod.rs: Complete async tray event handling - ✨ Technical Advantages: * Unified task tracking and debugging capabilities (via tokio-trace feature) * Better error handling and task management * Consistency with Tauri runtime * Reduced async boundaries for better performance - 🧪 Verification: * Compilation successful with 0 errors, 0 warnings * Maintains complete original functionality * Optimized async execution flow * feat: complete tokio fs migration and replace tokio::spawn with AsyncHandler 🚀 Major achievements: - Migrate 8 core modules from std::fs to tokio::fs - Create 6 Send-safe wrapper functions using spawn_blocking pattern - Replace all tokio::spawn calls with AsyncHandler::spawn for unified async task management - Solve all 19 Send trait compilation errors through innovative spawn_blocking architecture 🔧 Core changes: - config/profiles.rs: Add profiles_*_safe functions to handle Send trait constraints - cmd/profile.rs: Update all Tauri commands to use Send-safe operations - config/prfitem.rs: Replace append_item calls with profiles_append_item_safe - utils/help.rs: Convert YAML operations to async (read_yaml, save_yaml) - Multiple modules: Replace tokio::task::spawn_blocking with AsyncHandler::spawn_blocking ✅ Technical innovations: - spawn_blocking wrapper pattern resolves parking_lot RwLock Send trait conflicts - Maintain parking_lot performance while achieving Tauri async command compatibility - Preserve backwards compatibility with gradual migration strategy 🎯 Results: - Zero compilation errors - Zero warnings - All async file operations working correctly - Complete Send trait compliance for Tauri commands * feat: refactor app handle and command functions to use async/await for improved performance * feat: update async handling in profiles and logging functions for improved error handling and performance * fix: update TRACE_MINI_SIZE constant to improve task logging threshold * fix(windows): convert service management functions to async for improved performance * fix: convert service management functions to async for improved responsiveness * fix(ubuntu): convert install and reinstall service functions to async for improved performance * fix(linux): convert uninstall_service function to async for improved performance * fix: convert uninstall_service call to async for improved performance * fix: convert file and directory creation calls to async for improved performance * fix: convert hotkey functions to async for improved responsiveness * chore: update UPDATELOG.md for v2.4.1 with major improvements and performance optimizations
2025-08-26 01:49:51 +08:00
let verge = Config::verge().await;
let verge = verge.latest_ref();
2022-11-16 01:26:41 +08:00
(
2024-01-10 17:36:35 +08:00
verge.enable_system_proxy.unwrap_or(false),
2024-05-26 17:59:39 +08:00
verge.proxy_auto_config.unwrap_or(false),
2025-04-17 15:20:12 +08:00
verge
.proxy_host
.clone()
.unwrap_or_else(|| String::from("127.0.0.1")),
2022-11-16 01:26:41 +08:00
)
};
#[cfg(not(target_os = "windows"))]
{
let mut sys = Sysproxy {
enable: false,
host: proxy_host.clone().into(),
port,
bypass: get_bypass().await.into(),
};
let mut auto = Autoproxy {
enable: false,
url: format!("http://{proxy_host}:{pac_port}/commands/pac"),
};
2024-10-16 02:55:23 +08:00
if !sys_enable {
sys.set_system_proxy()?;
auto.set_auto_proxy()?;
let proxy_manager = EventDrivenProxyManager::global();
proxy_manager.notify_config_changed();
return Ok(());
}
if pac_enable {
sys.enable = false;
auto.enable = true;
sys.set_system_proxy()?;
auto.set_auto_proxy()?;
let proxy_manager = EventDrivenProxyManager::global();
proxy_manager.notify_config_changed();
return Ok(());
}
if sys_enable {
auto.enable = false;
sys.enable = true;
auto.set_auto_proxy()?;
sys.set_system_proxy()?;
let proxy_manager = EventDrivenProxyManager::global();
proxy_manager.notify_config_changed();
return Ok(());
}
}
#[cfg(target_os = "windows")]
{
2024-10-16 02:55:23 +08:00
if !sys_enable {
let result = self.reset_sysproxy().await;
let proxy_manager = EventDrivenProxyManager::global();
proxy_manager.notify_config_changed();
return result;
}
let args: Vec<std::string::String> = if pac_enable {
let address = format!("http://{proxy_host}:{pac_port}/commands/pac");
vec!["pac".into(), address]
} else {
let address = format!("{proxy_host}:{port}");
refactor(async): migrate from sync-blocking async execution to true async with unified AsyncHandler::spawn (#4502) * feat: replace all tokio::spawn with unified AsyncHandler::spawn - 🚀 Core Improvements: * Replace all tokio::spawn calls with AsyncHandler::spawn for unified Tauri async task management * Prioritize converting sync functions to async functions to reduce spawn usage * Use .await directly in async contexts instead of spawn - 🔧 Major Changes: * core/hotkey.rs: Use AsyncHandler::spawn for hotkey callback functions * module/lightweight.rs: Async lightweight mode switching * feat/window.rs: Convert window operation functions to async, use .await internally * feat/proxy.rs, feat/clash.rs: Async proxy and mode switching functions * lib.rs: Window focus handling with AsyncHandler::spawn * core/tray/mod.rs: Complete async tray event handling - ✨ Technical Advantages: * Unified task tracking and debugging capabilities (via tokio-trace feature) * Better error handling and task management * Consistency with Tauri runtime * Reduced async boundaries for better performance - 🧪 Verification: * Compilation successful with 0 errors, 0 warnings * Maintains complete original functionality * Optimized async execution flow * feat: complete tokio fs migration and replace tokio::spawn with AsyncHandler 🚀 Major achievements: - Migrate 8 core modules from std::fs to tokio::fs - Create 6 Send-safe wrapper functions using spawn_blocking pattern - Replace all tokio::spawn calls with AsyncHandler::spawn for unified async task management - Solve all 19 Send trait compilation errors through innovative spawn_blocking architecture 🔧 Core changes: - config/profiles.rs: Add profiles_*_safe functions to handle Send trait constraints - cmd/profile.rs: Update all Tauri commands to use Send-safe operations - config/prfitem.rs: Replace append_item calls with profiles_append_item_safe - utils/help.rs: Convert YAML operations to async (read_yaml, save_yaml) - Multiple modules: Replace tokio::task::spawn_blocking with AsyncHandler::spawn_blocking ✅ Technical innovations: - spawn_blocking wrapper pattern resolves parking_lot RwLock Send trait conflicts - Maintain parking_lot performance while achieving Tauri async command compatibility - Preserve backwards compatibility with gradual migration strategy 🎯 Results: - Zero compilation errors - Zero warnings - All async file operations working correctly - Complete Send trait compliance for Tauri commands * feat: refactor app handle and command functions to use async/await for improved performance * feat: update async handling in profiles and logging functions for improved error handling and performance * fix: update TRACE_MINI_SIZE constant to improve task logging threshold * fix(windows): convert service management functions to async for improved performance * fix: convert service management functions to async for improved responsiveness * fix(ubuntu): convert install and reinstall service functions to async for improved performance * fix(linux): convert uninstall_service function to async for improved performance * fix: convert uninstall_service call to async for improved performance * fix: convert file and directory creation calls to async for improved performance * fix: convert hotkey functions to async for improved responsiveness * chore: update UPDATELOG.md for v2.4.1 with major improvements and performance optimizations
2025-08-26 01:49:51 +08:00
let bypass = get_bypass().await;
vec!["global".into(), address, bypass.into()]
};
execute_sysproxy_command(args).await?;
2022-11-12 11:37:23 +08:00
}
let proxy_manager = EventDrivenProxyManager::global();
proxy_manager.notify_config_changed();
2022-11-12 11:37:23 +08:00
Ok(())
}
2022-11-12 11:37:23 +08:00
/// reset the sysproxy
#[allow(clippy::unused_async)]
2024-10-04 05:27:59 +08:00
pub async fn reset_sysproxy(&self) -> Result<()> {
if self
.reset_sysproxy
.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
.is_err()
{
return Ok(());
}
defer! {
self.reset_sysproxy.store(false, Ordering::SeqCst);
}
//直接关闭所有代理
#[cfg(not(target_os = "windows"))]
{
2025-10-20 23:09:13 +08:00
let mut sysproxy: Sysproxy = match Sysproxy::get_system_proxy() {
Ok(sp) => sp,
Err(e) => {
log::warn!(target: "app", "重置代理时获取系统代理配置失败: {e}, 使用默认配置");
Sysproxy::default()
}
};
let mut autoproxy = match Autoproxy::get_auto_proxy() {
Ok(ap) => ap,
Err(e) => {
log::warn!(target: "app", "重置代理时获取自动代理配置失败: {e}, 使用默认配置");
2025-10-20 23:09:13 +08:00
Autoproxy::default()
}
};
sysproxy.enable = false;
autoproxy.enable = false;
autoproxy.set_auto_proxy()?;
sysproxy.set_system_proxy()?;
}
2022-11-12 11:37:23 +08:00
#[cfg(target_os = "windows")]
{
execute_sysproxy_command(vec!["set".into(), "1".into()]).await?;
}
2024-05-26 19:07:14 +08:00
2022-11-12 11:37:23 +08:00
Ok(())
2022-04-20 01:44:47 +08:00
}
2022-11-12 11:37:23 +08:00
/// update the startup
refactor(async): migrate from sync-blocking async execution to true async with unified AsyncHandler::spawn (#4502) * feat: replace all tokio::spawn with unified AsyncHandler::spawn - 🚀 Core Improvements: * Replace all tokio::spawn calls with AsyncHandler::spawn for unified Tauri async task management * Prioritize converting sync functions to async functions to reduce spawn usage * Use .await directly in async contexts instead of spawn - 🔧 Major Changes: * core/hotkey.rs: Use AsyncHandler::spawn for hotkey callback functions * module/lightweight.rs: Async lightweight mode switching * feat/window.rs: Convert window operation functions to async, use .await internally * feat/proxy.rs, feat/clash.rs: Async proxy and mode switching functions * lib.rs: Window focus handling with AsyncHandler::spawn * core/tray/mod.rs: Complete async tray event handling - ✨ Technical Advantages: * Unified task tracking and debugging capabilities (via tokio-trace feature) * Better error handling and task management * Consistency with Tauri runtime * Reduced async boundaries for better performance - 🧪 Verification: * Compilation successful with 0 errors, 0 warnings * Maintains complete original functionality * Optimized async execution flow * feat: complete tokio fs migration and replace tokio::spawn with AsyncHandler 🚀 Major achievements: - Migrate 8 core modules from std::fs to tokio::fs - Create 6 Send-safe wrapper functions using spawn_blocking pattern - Replace all tokio::spawn calls with AsyncHandler::spawn for unified async task management - Solve all 19 Send trait compilation errors through innovative spawn_blocking architecture 🔧 Core changes: - config/profiles.rs: Add profiles_*_safe functions to handle Send trait constraints - cmd/profile.rs: Update all Tauri commands to use Send-safe operations - config/prfitem.rs: Replace append_item calls with profiles_append_item_safe - utils/help.rs: Convert YAML operations to async (read_yaml, save_yaml) - Multiple modules: Replace tokio::task::spawn_blocking with AsyncHandler::spawn_blocking ✅ Technical innovations: - spawn_blocking wrapper pattern resolves parking_lot RwLock Send trait conflicts - Maintain parking_lot performance while achieving Tauri async command compatibility - Preserve backwards compatibility with gradual migration strategy 🎯 Results: - Zero compilation errors - Zero warnings - All async file operations working correctly - Complete Send trait compliance for Tauri commands * feat: refactor app handle and command functions to use async/await for improved performance * feat: update async handling in profiles and logging functions for improved error handling and performance * fix: update TRACE_MINI_SIZE constant to improve task logging threshold * fix(windows): convert service management functions to async for improved performance * fix: convert service management functions to async for improved responsiveness * fix(ubuntu): convert install and reinstall service functions to async for improved performance * fix(linux): convert uninstall_service function to async for improved performance * fix: convert uninstall_service call to async for improved performance * fix: convert file and directory creation calls to async for improved performance * fix: convert hotkey functions to async for improved responsiveness * chore: update UPDATELOG.md for v2.4.1 with major improvements and performance optimizations
2025-08-26 01:49:51 +08:00
pub async fn update_launch(&self) -> Result<()> {
let enable_auto_launch = { Config::verge().await.latest_ref().enable_auto_launch };
let is_enable = enable_auto_launch.unwrap_or(false);
logging!(
info,
Type::System,
"Setting auto-launch state to: {:?}",
is_enable
);
// 首先尝试使用快捷方式方法
#[cfg(target_os = "windows")]
{
if is_enable {
if let Err(e) = startup_shortcut::create_shortcut().await {
log::error!(target: "app", "创建启动快捷方式失败: {e}");
// 如果快捷方式创建失败,回退到原来的方法
self.try_original_autostart_method(is_enable);
} else {
return Ok(());
}
} else if let Err(e) = startup_shortcut::remove_shortcut().await {
log::error!(target: "app", "删除启动快捷方式失败: {e}");
self.try_original_autostart_method(is_enable);
} else {
return Ok(());
}
}
#[cfg(not(target_os = "windows"))]
{
// 非Windows平台使用原来的方法
self.try_original_autostart_method(is_enable);
}
Ok(())
}
/// 尝试使用原来的自启动方法
fn try_original_autostart_method(&self, is_enable: bool) {
let app_handle = Handle::app_handle();
2024-11-20 03:52:19 +08:00
let autostart_manager = app_handle.autolaunch();
if is_enable {
logging_error!(Type::System, "{:?}", autostart_manager.enable());
} else {
logging_error!(Type::System, "{:?}", autostart_manager.disable());
}
2022-11-12 11:37:23 +08:00
}
2025-03-17 09:48:44 +08:00
/// 获取当前自启动的实际状态
pub fn get_launch_status(&self) -> Result<bool> {
// 首先尝试检查快捷方式是否存在
#[cfg(target_os = "windows")]
{
match startup_shortcut::is_shortcut_enabled() {
Ok(enabled) => {
log::info!(target: "app", "快捷方式自启动状态: {enabled}");
return Ok(enabled);
}
Err(e) => {
log::error!(target: "app", "检查快捷方式失败,尝试原来的方法: {e}");
}
}
}
// 回退到原来的方法
let app_handle = Handle::app_handle();
2025-03-17 09:48:44 +08:00
let autostart_manager = app_handle.autolaunch();
2025-03-17 13:51:52 +08:00
match autostart_manager.is_enabled() {
Ok(status) => {
log::info!(target: "app", "Auto launch status: {status}");
2025-03-17 13:51:52 +08:00
Ok(status)
}
2025-03-17 13:51:52 +08:00
Err(e) => {
log::error!(target: "app", "Failed to get auto launch status: {e}");
2025-03-17 13:51:52 +08:00
Err(anyhow::anyhow!("Failed to get auto launch status: {}", e))
}
}
2025-03-17 09:48:44 +08:00
}
2022-04-20 01:44:47 +08:00
}