Files
clash-proxy/src-tauri/src/lib.rs

599 lines
21 KiB
Rust
Raw Normal View History

refactor: enhance async initialization and streamline setup process (#4560) * feat: Implement DNS management for macOS - Added `set_public_dns` and `restore_public_dns` functions in `dns.rs` to manage system DNS settings. - Introduced `resolve` module to encapsulate DNS and scheme resolution functionalities. - Implemented `resolve_scheme` function in `scheme.rs` to handle deep links and profile imports. - Created UI readiness management in `ui.rs` to track and update UI loading states. - Developed window management logic in `window.rs` to handle window creation and visibility. - Added initial loading overlay script in `window_script.rs` for better user experience during startup. - Updated server handling in `server.rs` to integrate new resolve functionalities. - Refactored window creation calls in `window_manager.rs` to use the new window management logic. * refactor: streamline asynchronous handling in config and resolve setup * Revert "refactor: streamline asynchronous handling in config and resolve setup" This reverts commit 23d7dc86d5b87a3a34df2ae69c2caacef803ef81. * fix: optimize asynchronous memory handling * fix: enhance task logging by adding size check for special cases * refactor: enhance async initialization and streamline setup process * refactor: optimize async setup by consolidating initialization tasks * chore: update changelog for Mihomo(Meta) kernel upgrade to v1.19.13 * fix: improve startup phase initialization performance * refactor: optimize file read/write performance to reduce application wait time * refactor: simplify app instance exit logic and adjust system proxy guard initialization * refactor: change resolve_setup_async to synchronous execution for improved performance * refactor: update resolve_setup_async to accept AppHandle for improved initialization flow * refactor: remove unnecessary initialization of portable flag in run function * refactor: consolidate async initialization tasks into a single blocking call for improved execution flow * refactor: optimize resolve_setup_async by restructuring async tasks for improved concurrency * refactor: streamline resolve_setup_async and embed_server for improved async handling * refactor: separate synchronous and asynchronous setup functions for improved clarity * refactor: simplify async notification handling and remove redundant network manager initialization * refactor: enhance async handling in proxy request cache and window creation logic * refactor: improve code formatting and readability in ProxyRequestCache * refactor: adjust singleton check timeout and optimize trace size conditions * refactor: update TRACE_SPECIAL_SIZE to include additional size condition * refactor: update kode-bridge dependency to version 0.2.1-rc2 * refactor: replace RwLock with AtomicBool for UI readiness and implement event-driven monitoring * refactor: convert async functions to synchronous for window management * Update src-tauri/src/utils/resolve/window.rs * fix: handle missing app_handle in create_window function * Update src-tauri/src/module/lightweight.rs
2025-08-29 23:51:09 +08:00
#![allow(non_snake_case)]
#![recursion_limit = "512"]
mod cache;
mod cmd;
pub mod config;
mod core;
mod enhance;
mod feat;
// mod ipc;
mod module;
mod process;
mod utils;
#[cfg(target_os = "macos")]
use crate::utils::window_manager::WindowManager;
use crate::{
2025-10-01 12:14:07 +08:00
core::{handle, hotkey},
process::AsyncHandler,
utils::{resolve, server},
};
use config::Config;
use once_cell::sync::OnceCell;
#[cfg(target_os = "macos")]
2025-03-03 02:27:45 +08:00
use tauri::Manager;
use tauri::{AppHandle, Manager};
#[cfg(target_os = "macos")]
use tauri_plugin_autostart::MacosLauncher;
use tauri_plugin_deep_link::DeepLinkExt;
use tokio::time::{Duration, timeout};
use utils::logging::Type;
pub static APP_HANDLE: OnceCell<AppHandle> = OnceCell::new();
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
/// Application initialization helper functions
mod app_init {
use super::*;
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
/// Initialize singleton monitoring for other instances
pub fn init_singleton_check() {
AsyncHandler::spawn_blocking(move || async move {
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!(info, Type::Setup, true, "开始检查单例实例...");
refactor: enhance async initialization and streamline setup process (#4560) * feat: Implement DNS management for macOS - Added `set_public_dns` and `restore_public_dns` functions in `dns.rs` to manage system DNS settings. - Introduced `resolve` module to encapsulate DNS and scheme resolution functionalities. - Implemented `resolve_scheme` function in `scheme.rs` to handle deep links and profile imports. - Created UI readiness management in `ui.rs` to track and update UI loading states. - Developed window management logic in `window.rs` to handle window creation and visibility. - Added initial loading overlay script in `window_script.rs` for better user experience during startup. - Updated server handling in `server.rs` to integrate new resolve functionalities. - Refactored window creation calls in `window_manager.rs` to use the new window management logic. * refactor: streamline asynchronous handling in config and resolve setup * Revert "refactor: streamline asynchronous handling in config and resolve setup" This reverts commit 23d7dc86d5b87a3a34df2ae69c2caacef803ef81. * fix: optimize asynchronous memory handling * fix: enhance task logging by adding size check for special cases * refactor: enhance async initialization and streamline setup process * refactor: optimize async setup by consolidating initialization tasks * chore: update changelog for Mihomo(Meta) kernel upgrade to v1.19.13 * fix: improve startup phase initialization performance * refactor: optimize file read/write performance to reduce application wait time * refactor: simplify app instance exit logic and adjust system proxy guard initialization * refactor: change resolve_setup_async to synchronous execution for improved performance * refactor: update resolve_setup_async to accept AppHandle for improved initialization flow * refactor: remove unnecessary initialization of portable flag in run function * refactor: consolidate async initialization tasks into a single blocking call for improved execution flow * refactor: optimize resolve_setup_async by restructuring async tasks for improved concurrency * refactor: streamline resolve_setup_async and embed_server for improved async handling * refactor: separate synchronous and asynchronous setup functions for improved clarity * refactor: simplify async notification handling and remove redundant network manager initialization * refactor: enhance async handling in proxy request cache and window creation logic * refactor: improve code formatting and readability in ProxyRequestCache * refactor: adjust singleton check timeout and optimize trace size conditions * refactor: update TRACE_SPECIAL_SIZE to include additional size condition * refactor: update kode-bridge dependency to version 0.2.1-rc2 * refactor: replace RwLock with AtomicBool for UI readiness and implement event-driven monitoring * refactor: convert async functions to synchronous for window management * Update src-tauri/src/utils/resolve/window.rs * fix: handle missing app_handle in create_window function * Update src-tauri/src/module/lightweight.rs
2025-08-29 23:51:09 +08:00
match timeout(Duration::from_millis(500), server::check_singleton()).await {
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
Ok(result) => {
if result.is_err() {
logging!(info, Type::Setup, true, "检测到已有应用实例运行");
if let Some(app_handle) = APP_HANDLE.get() {
app_handle.exit(0);
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
} else {
std::process::exit(0);
}
} else {
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!(info, Type::Setup, true, "未检测到其他应用实例");
}
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
}
Err(_) => {
logging!(
warn,
Type::Setup,
true,
"单例检查超时,假定没有其他实例运行"
);
}
}
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
});
}
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
/// Setup plugins for the Tauri builder
pub fn setup_plugins(builder: tauri::Builder<tauri::Wry>) -> tauri::Builder<tauri::Wry> {
#[allow(unused_mut)]
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
let mut builder = builder
.plugin(tauri_plugin_notification::init())
.plugin(tauri_plugin_updater::Builder::new().build())
.plugin(tauri_plugin_clipboard_manager::init())
.plugin(tauri_plugin_process::init())
.plugin(tauri_plugin_global_shortcut::Builder::new().build())
.plugin(tauri_plugin_fs::init())
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_shell::init())
.plugin(tauri_plugin_deep_link::init())
.plugin(tauri_plugin_http::init())
.plugin(
tauri_plugin_mihomo::Builder::new()
.protocol(tauri_plugin_mihomo::models::Protocol::LocalSocket)
.socket_path(crate::config::IClashTemp::guard_external_controller_ipc())
.build(),
);
// Devtools plugin only in debug mode with feature tauri-dev
// to avoid duplicated registering of logger since the devtools plugin also registers a logger
#[cfg(all(debug_assertions, not(feature = "tokio-trace"), feature = "tauri-dev"))]
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
{
builder = builder.plugin(tauri_plugin_devtools::init());
}
builder
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
}
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
/// Setup deep link handling
pub fn setup_deep_links(app: &tauri::App) -> Result<(), Box<dyn std::error::Error>> {
#[cfg(any(target_os = "linux", all(debug_assertions, windows)))]
{
logging!(info, Type::Setup, true, "注册深层链接...");
app.deep_link().register_all()?;
}
2024-12-08 15:54:46 +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
app.deep_link().on_open_url(|event| {
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 url = event.urls().first().map(|u| u.to_string());
if let Some(url) = url {
AsyncHandler::spawn(|| async {
if let Err(e) = resolve::resolve_scheme(url).await {
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
logging!(error, Type::Setup, true, "Failed to resolve scheme: {}", e);
}
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
});
}
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
});
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
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
/// Setup autostart plugin
pub fn setup_autostart(app: &tauri::App) -> Result<(), Box<dyn std::error::Error>> {
#[cfg(target_os = "macos")]
let mut auto_start_plugin_builder = tauri_plugin_autostart::Builder::new();
#[cfg(not(target_os = "macos"))]
let auto_start_plugin_builder = tauri_plugin_autostart::Builder::new();
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
#[cfg(target_os = "macos")]
{
auto_start_plugin_builder = auto_start_plugin_builder
.macos_launcher(MacosLauncher::LaunchAgent)
.app_name(app.config().identifier.clone());
}
app.handle().plugin(auto_start_plugin_builder.build())?;
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
/// Setup window state management
pub fn setup_window_state(app: &tauri::App) -> Result<(), Box<dyn std::error::Error>> {
logging!(info, Type::Setup, true, "初始化窗口状态管理...");
let window_state_plugin = tauri_plugin_window_state::Builder::new()
.with_filename("window_state.json")
.with_state_flags(tauri_plugin_window_state::StateFlags::default())
.build();
app.handle().plugin(window_state_plugin)?;
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
/// Generate all command handlers for the application
pub fn generate_handlers()
-> impl Fn(tauri::ipc::Invoke<tauri::Wry>) -> bool + Send + Sync + 'static {
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
tauri::generate_handler![
// Common commands
cmd::get_sys_proxy,
cmd::get_auto_proxy,
cmd::open_app_dir,
cmd::open_logs_dir,
cmd::open_web_url,
cmd::open_core_dir,
cmd::get_portable_flag,
cmd::get_network_interfaces,
cmd::get_system_hostname,
cmd::restart_app,
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
// Core management
cmd::start_core,
cmd::stop_core,
cmd::restart_core,
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
// Application lifecycle
cmd::notify_ui_ready,
cmd::update_ui_stage,
cmd::get_running_mode,
2025-03-14 13:31:34 +08:00
cmd::get_app_uptime,
2025-03-17 09:48:44 +08:00
cmd::get_auto_launch_status,
cmd::is_admin,
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
// Lightweight mode
cmd::entry_lightweight_mode,
cmd::exit_lightweight_mode,
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
// Service management
cmd::install_service,
cmd::uninstall_service,
cmd::reinstall_service,
cmd::repair_service,
cmd::is_service_available,
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
// Clash core commands
cmd::get_clash_info,
cmd::patch_clash_config,
cmd::patch_clash_mode,
cmd::change_clash_core,
cmd::get_runtime_config,
cmd::get_runtime_yaml,
cmd::get_runtime_exists,
cmd::get_runtime_logs,
cmd::get_runtime_proxy_chain_config,
cmd::update_proxy_chain_config_in_runtime,
cmd::invoke_uwp_tool,
cmd::copy_clash_env,
// cmd::get_proxies,
// cmd::force_refresh_proxies,
// cmd::get_providers_proxies,
Win 下添加代理节点的系统托盘 (#4562) * add proxy memu in tray * 添加win下系统托盘 节点 代理->代理组->nodes 同时添加了对应gui同步 * 添加win 系统托盘显示代理节点 且gui和托盘刷新机制 * rust format * 添加 win下系统托盘节点延迟 * Squashed commit of the following: commit 44caaa62c54be198718ad93638c97f2b56560149 Merge: 1916e539 3939741a Author: Junkai W. <129588175+Be-Forever223@users.noreply.github.com> Date: Sat Aug 30 02:37:07 2025 +0800 Merge branch 'dev' into dev commit 3939741a06b40d449c59a22351edac154e02fdbf Author: Tunglies <tunglies.dev@outlook.com> Date: Sat Aug 30 02:24:47 2025 +0800 refactor: migrate from serde_yaml to serde_yaml_ng for improved YAML handling (#4568) * refactor: migrate from serde_yaml to serde_yaml_ng for improved YAML handling * refactor: format code for better readability in DNS configuration commit f86a1816e06e92f637e7ea317fd0819f952dc0e7 Author: Tunglies <tunglies.dev@outlook.com> Date: Sat Aug 30 02:15:34 2025 +0800 chore(deps): update sysinfo to 0.37.0 and zip to 4.5.0 in Cargo.toml (#4564) * chore(deps): update sysinfo to 0.37.0 and zip to 4.5.0 in Cargo.toml * chore(deps): remove libnghttp2-sys dependency and update isahc features in Cargo.toml * chore(deps): remove sysinfo and zip from ignoreDeps in renovate.json commit 9cbd8b45293d3de62abdb72359295f87fa2f0b7f Author: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Sat Aug 30 01:30:48 2025 +0800 feat: add x86 OpenSSL installation step for macOS in workflows commit 5dea73fc2a3bdd5646665a508830ac30c524604a Author: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Date: Sat Aug 30 01:21:53 2025 +0800 chore(deps): update npm dependencies (#4542) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> commit 01af1bea23dded6a9056c4987fe4f38680c4781e Author: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Date: Sat Aug 30 01:21:46 2025 +0800 chore(deps): update rust crate reqwest_dav to 0.2.2 (#4554) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> commit 1227e86134c998c6cd71dfbc8539a1a1b8b80a0f Author: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Sat Aug 30 01:12:03 2025 +0800 Remove unnecessary "rustls-tls" feature from reqwest dependency in Cargo.toml commit c6a6ea48dd23297deb8439f9e414059755330c65 Author: Tunglies <tunglies.dev@outlook.com> Date: Fri Aug 29 23:51:09 2025 +0800 refactor: enhance async initialization and streamline setup process (#4560) * feat: Implement DNS management for macOS - Added `set_public_dns` and `restore_public_dns` functions in `dns.rs` to manage system DNS settings. - Introduced `resolve` module to encapsulate DNS and scheme resolution functionalities. - Implemented `resolve_scheme` function in `scheme.rs` to handle deep links and profile imports. - Created UI readiness management in `ui.rs` to track and update UI loading states. - Developed window management logic in `window.rs` to handle window creation and visibility. - Added initial loading overlay script in `window_script.rs` for better user experience during startup. - Updated server handling in `server.rs` to integrate new resolve functionalities. - Refactored window creation calls in `window_manager.rs` to use the new window management logic. * refactor: streamline asynchronous handling in config and resolve setup * Revert "refactor: streamline asynchronous handling in config and resolve setup" This reverts commit 23d7dc86d5b87a3a34df2ae69c2caacef803ef81. * fix: optimize asynchronous memory handling * fix: enhance task logging by adding size check for special cases * refactor: enhance async initialization and streamline setup process * refactor: optimize async setup by consolidating initialization tasks * chore: update changelog for Mihomo(Meta) kernel upgrade to v1.19.13 * fix: improve startup phase initialization performance * refactor: optimize file read/write performance to reduce application wait time * refactor: simplify app instance exit logic and adjust system proxy guard initialization * refactor: change resolve_setup_async to synchronous execution for improved performance * refactor: update resolve_setup_async to accept AppHandle for improved initialization flow * refactor: remove unnecessary initialization of portable flag in run function * refactor: consolidate async initialization tasks into a single blocking call for improved execution flow * refactor: optimize resolve_setup_async by restructuring async tasks for improved concurrency * refactor: streamline resolve_setup_async and embed_server for improved async handling * refactor: separate synchronous and asynchronous setup functions for improved clarity * refactor: simplify async notification handling and remove redundant network manager initialization * refactor: enhance async handling in proxy request cache and window creation logic * refactor: improve code formatting and readability in ProxyRequestCache * refactor: adjust singleton check timeout and optimize trace size conditions * refactor: update TRACE_SPECIAL_SIZE to include additional size condition * refactor: update kode-bridge dependency to version 0.2.1-rc2 * refactor: replace RwLock with AtomicBool for UI readiness and implement event-driven monitoring * refactor: convert async functions to synchronous for window management * Update src-tauri/src/utils/resolve/window.rs * fix: handle missing app_handle in create_window function * Update src-tauri/src/module/lightweight.rs * format
2025-08-31 14:20:57 +08:00
cmd::sync_tray_proxy_selection,
cmd::update_proxy_and_sync,
cmd::save_dns_config,
cmd::apply_dns_config,
cmd::check_dns_config_exists,
cmd::get_dns_config_content,
cmd::validate_dns_config,
// cmd::get_clash_version,
// cmd::get_clash_config,
// cmd::force_refresh_clash_config,
// cmd::update_geo_data,
// cmd::upgrade_clash_core,
// cmd::get_clash_rules,
// cmd::update_proxy_choice,
// cmd::get_proxy_providers,
// cmd::get_rule_providers,
// cmd::proxy_provider_health_check,
// cmd::update_proxy_provider,
// cmd::update_rule_provider,
// cmd::get_clash_connections,
// cmd::delete_clash_connection,
// cmd::close_all_clash_connections,
// cmd::get_group_proxy_delays,
// cmd::is_clash_debug_enabled,
// cmd::clash_gc,
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 and monitoring
cmd::get_clash_logs,
// cmd::start_logs_monitoring,
// cmd::stop_logs_monitoring,
// cmd::clear_logs,
// cmd::get_traffic_data,
// cmd::get_memory_data,
// cmd::get_formatted_traffic_data,
// cmd::get_formatted_memory_data,
// cmd::get_system_monitor_overview,
// cmd::start_traffic_service,
// cmd::stop_traffic_service,
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
// Verge configuration
cmd::get_verge_config,
cmd::patch_verge_config,
cmd::test_delay,
cmd::get_app_dir,
cmd::copy_icon_file,
cmd::download_icon_cache,
cmd::open_devtools,
cmd::exit_app,
cmd::get_network_interfaces_info,
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
// Profile management
cmd::get_profiles,
cmd::enhance_profiles,
cmd::patch_profiles_config,
cmd::view_profile,
cmd::patch_profile,
cmd::create_profile,
cmd::import_profile,
cmd::reorder_profile,
cmd::update_profile,
cmd::delete_profile,
cmd::read_profile_file,
cmd::save_profile_file,
cmd::get_next_update_time,
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
// Script validation
cmd::script_validate_notice,
cmd::validate_script_file,
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
// Clash API
// cmd::clash_api_get_proxy_delay,
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
// Backup and WebDAV
cmd::create_webdav_backup,
cmd::save_webdav_config,
cmd::list_webdav_backup,
cmd::delete_webdav_backup,
cmd::restore_webdav_backup,
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
// Diagnostics and system info
cmd::export_diagnostic_info,
2025-03-14 13:31:34 +08:00
cmd::get_system_info,
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
// Media unlock checker
2025-03-16 12:15:35 +08:00
cmd::get_unlock_items,
cmd::check_media_unlock,
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
]
}
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
}
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
pub fn run() {
// Setup singleton check
app_init::init_singleton_check();
let _ = utils::dirs::init_portable_flag();
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
// Set Linux environment variable
#[cfg(target_os = "linux")]
{
unsafe {
std::env::set_var("WEBKIT_DISABLE_DMABUF_RENDERER", "1");
}
let desktop_env = std::env::var("XDG_CURRENT_DESKTOP")
.unwrap_or_default()
.to_uppercase();
let is_kde_desktop = desktop_env.contains("KDE");
let is_plasma_desktop = desktop_env.contains("PLASMA");
if is_kde_desktop || is_plasma_desktop {
unsafe {
std::env::set_var("GTK_CSD", "0");
}
logging!(
info,
Type::Setup,
true,
"KDE detected: Disabled GTK CSD for better titlebar stability."
);
}
}
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
// Create and configure the Tauri builder
let builder = app_init::setup_plugins(tauri::Builder::default())
.setup(|app| {
logging!(info, Type::Setup, true, "开始应用初始化...");
2025-10-01 10:17:08 +08:00
#[allow(clippy::expect_used)]
APP_HANDLE
.set(app.app_handle().clone())
.expect("failed to set global app 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
// Setup autostart plugin
if let Err(e) = app_init::setup_autostart(app) {
logging!(error, Type::Setup, true, "Failed to setup autostart: {}", e);
}
// Setup deep links
if let Err(e) = app_init::setup_deep_links(app) {
logging!(
error,
Type::Setup,
true,
"Failed to setup deep links: {}",
e
);
}
// Setup window state management
if let Err(e) = app_init::setup_window_state(app) {
logging!(
error,
Type::Setup,
true,
"Failed to setup window state: {}",
e
);
}
logging!(info, Type::Setup, true, "执行主要设置操作...");
resolve::resolve_setup_handle();
refactor: enhance async initialization and streamline setup process (#4560) * feat: Implement DNS management for macOS - Added `set_public_dns` and `restore_public_dns` functions in `dns.rs` to manage system DNS settings. - Introduced `resolve` module to encapsulate DNS and scheme resolution functionalities. - Implemented `resolve_scheme` function in `scheme.rs` to handle deep links and profile imports. - Created UI readiness management in `ui.rs` to track and update UI loading states. - Developed window management logic in `window.rs` to handle window creation and visibility. - Added initial loading overlay script in `window_script.rs` for better user experience during startup. - Updated server handling in `server.rs` to integrate new resolve functionalities. - Refactored window creation calls in `window_manager.rs` to use the new window management logic. * refactor: streamline asynchronous handling in config and resolve setup * Revert "refactor: streamline asynchronous handling in config and resolve setup" This reverts commit 23d7dc86d5b87a3a34df2ae69c2caacef803ef81. * fix: optimize asynchronous memory handling * fix: enhance task logging by adding size check for special cases * refactor: enhance async initialization and streamline setup process * refactor: optimize async setup by consolidating initialization tasks * chore: update changelog for Mihomo(Meta) kernel upgrade to v1.19.13 * fix: improve startup phase initialization performance * refactor: optimize file read/write performance to reduce application wait time * refactor: simplify app instance exit logic and adjust system proxy guard initialization * refactor: change resolve_setup_async to synchronous execution for improved performance * refactor: update resolve_setup_async to accept AppHandle for improved initialization flow * refactor: remove unnecessary initialization of portable flag in run function * refactor: consolidate async initialization tasks into a single blocking call for improved execution flow * refactor: optimize resolve_setup_async by restructuring async tasks for improved concurrency * refactor: streamline resolve_setup_async and embed_server for improved async handling * refactor: separate synchronous and asynchronous setup functions for improved clarity * refactor: simplify async notification handling and remove redundant network manager initialization * refactor: enhance async handling in proxy request cache and window creation logic * refactor: improve code formatting and readability in ProxyRequestCache * refactor: adjust singleton check timeout and optimize trace size conditions * refactor: update TRACE_SPECIAL_SIZE to include additional size condition * refactor: update kode-bridge dependency to version 0.2.1-rc2 * refactor: replace RwLock with AtomicBool for UI readiness and implement event-driven monitoring * refactor: convert async functions to synchronous for window management * Update src-tauri/src/utils/resolve/window.rs * fix: handle missing app_handle in create_window function * Update src-tauri/src/module/lightweight.rs
2025-08-29 23:51:09 +08:00
resolve::resolve_setup_async();
resolve::resolve_setup_sync();
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!(info, Type::Setup, true, "初始化完成,继续执行");
Ok(())
})
.invoke_handler(app_init::generate_handlers());
/// Event handling helper functions
mod event_handlers {
use crate::core::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
use super::*;
/// Handle application ready/resumed events
pub fn handle_ready_resumed(_app_handle: &AppHandle) {
logging!(info, Type::System, true, "应用就绪或恢复");
handle::Handle::global().init();
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
2025-03-03 02:27:45 +08:00
#[cfg(target_os = "macos")]
{
if let Some(window) = _app_handle.get_webview_window("main") {
logging!(info, Type::Window, true, "设置macOS窗口标题");
let _ = window.set_title("Clash Verge");
}
2025-03-03 02:27:45 +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
/// Handle application reopen events (macOS)
2025-03-01 19:52:42 +08:00
#[cfg(target_os = "macos")]
pub async fn handle_reopen(app_handle: &AppHandle, has_visible_windows: bool) {
logging!(
info,
Type::System,
true,
"处理 macOS 应用重新打开事件: has_visible_windows={}",
has_visible_windows
);
handle::Handle::global().init(app_handle.clone());
if !has_visible_windows {
// 当没有可见窗口时,设置为 regular 模式并显示主窗口
handle::Handle::global().set_activation_policy_regular();
logging!(info, Type::System, true, "没有可见窗口,尝试显示主窗口");
let result = WindowManager::show_main_window().await;
logging!(
info,
Type::System,
true,
"窗口显示操作完成,结果: {:?}",
result
);
} else {
logging!(info, Type::System, true, "已有可见窗口,无需额外操作");
}
}
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
/// Handle window close requests
pub fn handle_window_close(api: &tauri::WindowEvent) {
#[cfg(target_os = "macos")]
handle::Handle::global().set_activation_policy_accessory();
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
if core::handle::Handle::global().is_exiting() {
return;
}
log::info!(target: "app", "closing window...");
if let tauri::WindowEvent::CloseRequested { api, .. } = api {
api.prevent_close();
if let Some(window) = core::handle::Handle::get_window() {
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
let _ = window.hide();
} else {
logging!(warn, Type::Window, true, "尝试隐藏窗口但窗口不存在");
}
}
}
/// Handle window focus events
pub fn handle_window_focus(focused: bool) {
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
AsyncHandler::spawn(move || async move {
let is_enable_global_hotkey = Config::verge()
.await
.latest_ref()
.enable_global_hotkey
.unwrap_or(true);
if focused {
#[cfg(target_os = "macos")]
{
use crate::core::hotkey::SystemHotkey;
if let Err(e) = hotkey::Hotkey::global()
.register_system_hotkey(SystemHotkey::CmdQ)
.await
{
logging!(error, Type::Hotkey, true, "Failed to register CMD+Q: {}", e);
}
if let Err(e) = hotkey::Hotkey::global()
.register_system_hotkey(SystemHotkey::CmdW)
.await
{
logging!(error, Type::Hotkey, true, "Failed to register CMD+W: {}", e);
}
}
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
if !is_enable_global_hotkey
&& let Err(e) = hotkey::Hotkey::global().init().await
{
logging!(error, Type::Hotkey, true, "Failed to init hotkeys: {}", e);
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
}
return;
}
// Handle unfocused state
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
#[cfg(target_os = "macos")]
{
use crate::core::hotkey::SystemHotkey;
if let Err(e) =
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
hotkey::Hotkey::global().unregister_system_hotkey(SystemHotkey::CmdQ)
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
{
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
logging!(
error,
Type::Hotkey,
true,
"Failed to unregister CMD+Q: {}",
e
);
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
}
if let Err(e) =
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
hotkey::Hotkey::global().unregister_system_hotkey(SystemHotkey::CmdW)
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
{
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
logging!(
error,
Type::Hotkey,
true,
"Failed to unregister CMD+W: {}",
e
);
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
}
}
if !is_enable_global_hotkey && let Err(e) = hotkey::Hotkey::global().reset() {
logging!(error, Type::Hotkey, true, "Failed to reset hotkeys: {}", e);
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
}
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
});
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
}
/// Handle window destroyed events
pub fn handle_window_destroyed() {
#[cfg(target_os = "macos")]
{
use crate::core::hotkey::SystemHotkey;
if let Err(e) =
hotkey::Hotkey::global().unregister_system_hotkey(SystemHotkey::CmdQ)
{
logging!(
error,
Type::Hotkey,
true,
"Failed to unregister CMD+Q on destroy: {}",
e
);
}
if let Err(e) =
hotkey::Hotkey::global().unregister_system_hotkey(SystemHotkey::CmdW)
{
logging!(
error,
Type::Hotkey,
true,
"Failed to unregister CMD+W on destroy: {}",
e
);
}
}
}
}
// Build the application
let app = builder
.build(tauri::generate_context!())
fix: clippy errors with new config (#4428) * refactor: improve code quality with clippy fixes and standardized logging - Replace dangerous unwrap()/expect() calls with proper error handling - Standardize logging from log:: to logging\! macro with Type:: classifications - Fix app handle panics with graceful fallback patterns - Improve error resilience across 35+ modules without breaking functionality - Reduce clippy warnings from 300+ to 0 in main library code * chore: update Cargo.toml configuration * refactor: resolve all clippy warnings - Fix Arc clone warnings using explicit Arc::clone syntax across 9 files - Add #[allow(clippy::expect_used)] to test functions for appropriate expect usage - Remove no-effect statements from debug code cleanup - Apply clippy auto-fixes for dbg\! macro removals and path statements - Achieve zero clippy warnings on all targets with -D warnings flag * chore: update Cargo.toml clippy configuration * refactor: simplify macOS job configuration and improve caching * refactor: remove unnecessary async/await from service and proxy functions * refactor: streamline pnpm installation in CI configuration * refactor: simplify error handling and remove unnecessary else statements * refactor: replace async/await with synchronous locks for core management * refactor: add workflow_dispatch trigger to clippy job * refactor: convert async functions to synchronous for service management * refactor: convert async functions to synchronous for UWP tool invocation * fix: change wrong logging * refactor: convert proxy restoration functions to async * Revert "refactor: convert proxy restoration functions to async" This reverts commit b82f5d250b2af7151e4dfd7dd411630b34ed2c18. * refactor: update proxy restoration functions to return Result types * fix: handle errors during proxy restoration and update async function signatures * fix: handle errors during proxy restoration and update async function signatures * refactor: update restore_pac_proxy and restore_sys_proxy functions to async * fix: convert restore_pac_proxy and restore_sys_proxy functions to async * fix: await restore_sys_proxy calls in proxy restoration logic * fix: suppress clippy warnings for unused async functions in proxy restoration * fix: suppress clippy warnings for unused async functions in proxy restoration
2025-08-18 02:02:25 +08:00
.unwrap_or_else(|e| {
logging!(
error,
Type::Setup,
true,
"Failed to build Tauri application: {}",
e
);
std::process::exit(1);
});
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
app.run(|app_handle, e| {
match e {
tauri::RunEvent::Ready | tauri::RunEvent::Resumed => {
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
event_handlers::handle_ready_resumed(app_handle);
2024-09-25 11:47:01 +08:00
}
#[cfg(target_os = "macos")]
tauri::RunEvent::Reopen {
has_visible_windows,
..
} => {
let app_handle = app_handle.clone();
AsyncHandler::spawn(move || async move {
event_handlers::handle_reopen(&app_handle, has_visible_windows).await;
});
}
tauri::RunEvent::ExitRequested { api, code, .. } => {
2025-10-01 12:14:07 +08:00
tauri::async_runtime::block_on(async {
let _ = handle::Handle::mihomo()
.await
.clear_all_ws_connections()
.await;
});
if code.is_none() {
api.prevent_exit();
}
}
tauri::RunEvent::Exit => {
// Avoid duplicate cleanup
if core::handle::Handle::global().is_exiting() {
return;
}
feat::clean();
}
tauri::RunEvent::WindowEvent { label, event, .. } => {
if label == "main" {
match event {
tauri::WindowEvent::CloseRequested { .. } => {
event_handlers::handle_window_close(&event);
}
tauri::WindowEvent::Focused(focused) => {
event_handlers::handle_window_focus(focused);
}
tauri::WindowEvent::Destroyed => {
event_handlers::handle_window_destroyed();
}
_ => {}
2024-09-18 15:16:43 +08:00
}
}
}
_ => {}
}
});
}