Files
clash-verge-rev/src-tauri/src/core/sysopt.rs
Tunglies b1e2940db6 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

324 lines
11 KiB
Rust

#[cfg(target_os = "windows")]
use crate::utils::autostart as startup_shortcut;
use crate::{
config::{Config, IVerge},
core::{handle::Handle, EventDrivenProxyManager},
logging, logging_error, singleton_lazy,
utils::logging::Type,
};
use anyhow::Result;
use std::sync::Arc;
#[cfg(not(target_os = "windows"))]
use sysproxy::{Autoproxy, Sysproxy};
use tauri::async_runtime::Mutex as TokioMutex;
use tauri_plugin_autostart::ManagerExt;
pub struct Sysopt {
update_sysproxy: Arc<TokioMutex<bool>>,
reset_sysproxy: Arc<TokioMutex<bool>>,
}
#[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>";
#[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";
#[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>";
fn get_bypass() -> String {
let use_default = Config::verge()
.latest_ref()
.use_default_bypass
.unwrap_or(true);
let res = {
let verge = Config::verge();
let verge = verge.latest_ref();
verge.system_proxy_bypass.clone()
};
let custom_bypass = match res {
Some(bypass) => bypass,
None => "".to_string(),
};
if custom_bypass.is_empty() {
DEFAULT_BYPASS.to_string()
} else if use_default {
format!("{DEFAULT_BYPASS},{custom_bypass}")
} else {
custom_bypass
}
}
impl Default for Sysopt {
fn default() -> Self {
Sysopt {
update_sysproxy: Arc::new(TokioMutex::new(false)),
reset_sysproxy: Arc::new(TokioMutex::new(false)),
}
}
}
// 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(())
}
/// init the sysproxy
pub async fn update_sysproxy(&self) -> Result<()> {
let _lock = self.update_sysproxy.lock().await;
let port = Config::verge()
.latest_ref()
.verge_mixed_port
.unwrap_or(Config::clash().latest_ref().get_mixed_port());
let pac_port = IVerge::get_singleton_port();
let (sys_enable, pac_enable, proxy_host) = {
let verge = Config::verge();
let verge = verge.latest_ref();
(
verge.enable_system_proxy.unwrap_or(false),
verge.proxy_auto_config.unwrap_or(false),
verge
.proxy_host
.clone()
.unwrap_or_else(|| String::from("127.0.0.1")),
)
};
#[cfg(not(target_os = "windows"))]
{
let mut sys = Sysproxy {
enable: false,
host: proxy_host.clone(),
port,
bypass: get_bypass(),
};
let mut auto = Autoproxy {
enable: false,
url: format!("http://{proxy_host}:{pac_port}/commands/pac"),
};
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")]
{
if !sys_enable {
let result = self.reset_sysproxy().await;
let proxy_manager = EventDrivenProxyManager::global();
proxy_manager.notify_config_changed();
return result;
}
use crate::{core::handle::Handle, utils::dirs};
use anyhow::bail;
use tauri_plugin_shell::ShellExt;
let app_handle = Handle::global().app_handle().unwrap();
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 shell = app_handle.shell();
let output = if pac_enable {
let address = format!("http://{proxy_host}:{pac_port}/commands/pac");
let output = shell
.command(sysproxy_exe.as_path().to_str().unwrap())
.args(["pac", address.as_str()])
.output()
.await
.unwrap();
output
} else {
let address = format!("{proxy_host}:{port}");
let bypass = get_bypass();
let output = shell
.command(sysproxy_exe.as_path().to_str().unwrap())
.args(["global", address.as_str(), bypass.as_ref()])
.output()
.await
.unwrap();
output
};
if !output.status.success() {
bail!("sysproxy exe run failed");
}
}
let proxy_manager = EventDrivenProxyManager::global();
proxy_manager.notify_config_changed();
Ok(())
}
/// reset the sysproxy
pub async fn reset_sysproxy(&self) -> Result<()> {
let _lock = self.reset_sysproxy.lock().await;
//直接关闭所有代理
#[cfg(not(target_os = "windows"))]
{
let mut sysproxy: Sysproxy = Sysproxy::get_system_proxy()?;
let mut autoproxy = match Autoproxy::get_auto_proxy() {
Ok(ap) => ap,
Err(e) => {
log::warn!(target: "app", "重置代理时获取自动代理配置失败: {e}, 使用默认配置");
Autoproxy {
enable: false,
url: "".to_string(),
}
}
};
sysproxy.enable = false;
autoproxy.enable = false;
autoproxy.set_auto_proxy()?;
sysproxy.set_system_proxy()?;
}
#[cfg(target_os = "windows")]
{
use crate::{core::handle::Handle, utils::dirs};
use anyhow::bail;
use tauri_plugin_shell::ShellExt;
let app_handle = Handle::global().app_handle().unwrap();
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 shell = app_handle.shell();
let output = shell
.command(sysproxy_exe.as_path().to_str().unwrap())
.args(["set", "1"])
.output()
.await
.unwrap();
if !output.status.success() {
bail!("sysproxy exe run failed");
}
}
Ok(())
}
/// update the startup
pub fn update_launch(&self) -> Result<()> {
let enable_auto_launch = { Config::verge().latest_ref().enable_auto_launch };
let is_enable = enable_auto_launch.unwrap_or(false);
logging!(info, true, "Setting auto-launch state to: {:?}", is_enable);
// 首先尝试使用快捷方式方法
#[cfg(target_os = "windows")]
{
if is_enable {
if let Err(e) = startup_shortcut::create_shortcut() {
log::error!(target: "app", "创建启动快捷方式失败: {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}");
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::global().app_handle().unwrap();
let autostart_manager = app_handle.autolaunch();
if is_enable {
logging_error!(Type::System, true, "{:?}", autostart_manager.enable());
} else {
logging_error!(Type::System, true, "{:?}", autostart_manager.disable());
}
}
/// 获取当前自启动的实际状态
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::global().app_handle().unwrap();
let autostart_manager = app_handle.autolaunch();
match autostart_manager.is_enabled() {
Ok(status) => {
log::info!(target: "app", "Auto launch status: {status}");
Ok(status)
}
Err(e) => {
log::error!(target: "app", "Failed to get auto launch status: {e}");
Err(anyhow::anyhow!("Failed to get auto launch status: {}", e))
}
}
}
}