Commit Graph

82 Commits

Author SHA1 Message Date
Tunglies
b1e2940db6 refactor: optimize singleton macro usage with Default trait implementations (#4279)
* refactor: implement DRY principle improvements across backend

Major DRY violations identified and addressed:

1. **IPC Stream Monitor Pattern**:
   - Created `utils/ipc_monitor.rs` with generic `IpcStreamMonitor` trait
   - Added `IpcMonitorManager` for common async task management patterns
   - Eliminates duplication across traffic.rs, memory.rs, and logs.rs

2. **Singleton Pattern Duplication**:
   - Created `utils/singleton.rs` with `singleton\!` and `singleton_with_logging\!` macros
   - Replaces 16+ duplicate singleton implementations across codebase
   - Provides consistent, tested patterns for global instances

3. **macOS Activation Policy Refactoring**:
   - Consolidated 3 duplicate methods into single parameterized `set_activation_policy()`
   - Eliminated code duplication while maintaining backward compatibility
   - Reduced maintenance burden for macOS-specific functionality

These improvements enhance maintainability, reduce bug potential, and ensure consistent patterns across the backend codebase.

* fix: resolve test failures and clippy warnings

- Fix doctest in singleton.rs by using rust,ignore syntax and proper code examples
- Remove unused time::Instant import from ipc_monitor.rs
- Add #[allow(dead_code)] attributes to future-use utility modules
- All 11 unit tests now pass successfully
- All clippy checks pass with -D warnings strict mode
- Documentation tests properly ignore example code that requires full context

* refactor: migrate code to use new utility tools (partial)

Progress on systematic migration to use created utility tools:

1. **Reorganized IPC Monitor**:
   - Moved ipc_monitor.rs to src-tauri/src/ipc/monitor.rs for better organization
   - Updated module structure to emphasize IPC relationship

2. **IpcManager Singleton Migration**:
   - Replaced manual OnceLock singleton pattern with singleton_with_logging\! macro
   - Simplified initialization code and added consistent logging
   - Removed unused imports (OnceLock, logging::Type)

3. **ProxyRequestCache Singleton Migration**:
   - Migrated from once_cell::sync::OnceCell to singleton\! macro
   - Cleaner, more maintainable singleton pattern
   - Consistent with project-wide singleton approach

These migrations demonstrate the utility and effectiveness of the created tools:
- Less boilerplate code
- Consistent patterns across codebase
- Easier maintenance and debugging

* feat: complete migration to new utility tools - phase 1

Successfully migrated core components to use the created utility tools:

- Moved `ipc_monitor.rs` to `src-tauri/src/ipc/monitor.rs`
- Better organization emphasizing IPC relationship
- Updated module exports and imports

- **IpcManager**: Migrated to `singleton_with_logging\!` macro
- **ProxyRequestCache**: Migrated to `singleton\!` macro
- Eliminated ~30 lines of boilerplate singleton code
- Consistent logging and initialization patterns

- Removed unused imports (OnceLock, once_cell, logging::Type)
- Cleaner, more maintainable code structure
- All 11 unit tests pass successfully
- Zero compilation warnings

- **Lines of code reduced**: ~50+ lines of boilerplate
- **Consistency improved**: Unified singleton patterns
- **Maintainability enhanced**: Centralized utility functions
- **Test coverage maintained**: 100% test pass rate

Remaining complex monitors (traffic, memory, logs) will be migrated to use the shared IPC monitoring patterns in the next phase, which requires careful refactoring of their streaming logic.

* refactor: complete singleton pattern migration to utility macros

Migrate remaining singleton patterns across the backend to use standardized
utility macros, achieving significant code reduction and consistency improvements.

- **LogsMonitor** (ipc/logs.rs): `OnceLock` → `singleton_with_logging\!`
- **Sysopt** (core/sysopt.rs): `OnceCell` → `singleton_lazy\!`
- **Tray** (core/tray/mod.rs): Complex `OnceCell` → `singleton_lazy\!`
- **Handle** (core/handle.rs): `OnceCell` → `singleton\!`
- **CoreManager** (core/core.rs): `OnceCell` → `singleton_lazy\!`
- **TrafficMonitor** (ipc/traffic.rs): `OnceLock` → `singleton_lazy_with_logging\!`
- **MemoryMonitor** (ipc/memory.rs): `OnceLock` → `singleton_lazy_with_logging\!`

- `singleton_lazy\!` - For complex initialization patterns
- `singleton_lazy_with_logging\!` - For complex initialization with logging

- **Code Reduction**: -33 lines of boilerplate singleton code
- **DRY Compliance**: Eliminated duplicate initialization patterns
- **Consistency**: Unified singleton approach across codebase
- **Maintainability**: Centralized singleton logic in utility macros
- **Zero Breaking Changes**: All existing APIs remain compatible

All tests pass and clippy warnings resolved.

* refactor: optimize singleton macros using Default trait implementation

Simplify singleton macro usage by implementing Default trait for complex
initialization patterns, significantly improving code readability and maintainability.

- **MemoryMonitor**: Move IPC client initialization to Default impl
- **TrafficMonitor**: Move IPC client initialization to Default impl
- **Sysopt**: Move Arc<Mutex> initialization to Default impl
- **Tray**: Move struct field initialization to Default impl
- **CoreManager**: Move Arc<Mutex> initialization to Default impl

```rust
singleton_lazy_with_logging\!(MemoryMonitor, INSTANCE, "MemoryMonitor", || {
    let ipc_path_buf = ipc_path().unwrap();
    let ipc_path = ipc_path_buf.to_str().unwrap_or_default();
    let client = IpcStreamClient::new(ipc_path).unwrap();
    MemoryMonitor::new(client)
});
```

```rust
impl Default for MemoryMonitor { /* initialization logic */ }
singleton_lazy_with_logging\!(MemoryMonitor, INSTANCE, "MemoryMonitor", MemoryMonitor::default);
```

- **Code Reduction**: -17 lines of macro closure code (80%+ simplification)
- **Separation of Concerns**: Initialization logic moved to proper Default impl
- **Readability**: Single-line macro calls vs multi-line closures
- **Testability**: Default implementations can be tested independently
- **Rust Idioms**: Using standard Default trait pattern
- **Performance**: Function calls more efficient than closures

All tests pass and clippy warnings resolved.

* refactor: implement MonitorData and StreamingParser traits for IPC monitors

* refactor: add timeout and retry_interval fields to IpcStreamMonitor; update TrafficMonitorState to derive Default

* refactor: migrate AppHandleManager to unified singleton control

- Replace manual singleton implementation with singleton_with_logging\! macro
- Remove std::sync::Once dependency in favor of OnceLock-based pattern
- Improve error handling for macOS activation policy methods
- Maintain thread safety with parking_lot::Mutex for AppHandle storage
- Add proper initialization check to prevent duplicate handle assignment
- Enhance logging consistency across AppHandleManager operations

* refactor: improve hotkey management with enum-based operations

- Add HotkeyFunction enum for type-safe function selection
- Add SystemHotkey enum for predefined system shortcuts
- Implement Display and FromStr traits for type conversions
- Replace string-based hotkey registration with enum methods
- Add register_system_hotkey() and unregister_system_hotkey() methods
- Maintain backward compatibility with string-based register() method
- Migrate singleton pattern to use singleton_with_logging\! macro
- Extract hotkey function execution logic into centralized execute_function()
- Update lib.rs to use new enum-based SystemHotkey operations
- Improve type safety and reduce string manipulation errors

Benefits:
- Type safety prevents invalid hotkey function names
- Centralized function execution reduces code duplication
- Enum-based API provides better IDE autocomplete support
- Maintains full backward compatibility with existing configurations

* fix: resolve LightWeightState initialization order panic

- Modify with_lightweight_status() to safely handle unmanaged state using try_state()
- Return Option<R> instead of R to gracefully handle state unavailability
- Update is_in_lightweight_mode() to use unwrap_or(false) for safe defaults
- Add state availability check in auto_lightweight_mode_init() before access
- Maintain singleton check priority while preventing early state access panics
- Fix clippy warnings for redundant pattern matching

Resolves runtime panic: "state() called before manage() for LightWeightState"

* refactor: add unreachable patterns for non-macOS in hotkey handling

* refactor: simplify SystemHotkey enum by removing redundant cfg attributes

* refactor: add macOS conditional compilation for system hotkey registration methods

* refactor: streamline hotkey unregistration and error logging for macOS
2025-07-31 14:35:13 +08:00
Tunglies
764ef48fd1 refactor(Draft): Replace latest() with latest_ref() and data() with data_mut() in multiple files for improved mutability handling and consistency across the codebase (#3987)
* feat: add benchmarking for draft operations and new draft management structure

* Refactor Config Access: Replace `latest()` with `latest_ref()` and `data()` with `data_mut()` in multiple files for improved mutability handling and consistency across the codebase.

* refactor: remove DraftNew implementation and related benchmarks for cleaner codebase
2025-07-04 22:43:23 +08:00
Dyna
7b5afb7afe Add cors (#3909)
* add external `cors` control panel

* optimize format

* fix-script.rs

* fix-service.rs

* fix-rs

async_proxy_query.rs

event_driven_proxy.rs

service_ipc.rs

service.rs

sysopt.rs

* lower the prettier version number to 3.5.3

* Revert "lower the prettier version number to 3.5.3"

This reverts commit 0f1c3dfa8a.

* fix: prttier erros

* add developer environment detection and controlled the display of development environment URL

* submit required

* fix-external-controller-cors

* use the custom component ToggleButton to ensure a uniform button style

* fix-tsx

hotkey-viewer.tsx

external-controller-cors.tsx

* fix-bug_report.yml

* remove the annoying title

* fix-write overload problem

* Individual button settings

* fix-setting-clash.tsx

---------

Co-authored-by: Tunglies <77394545+Tunglies@users.noreply.github.com>
Co-authored-by: Tunglies <tunglies.dev@outlook.com>
2025-06-30 20:48:20 +08:00
Tunglies
a574ced428 Refactor logging statements to use the new formatting syntax for improved readability and consistency across the codebase. This includes updating error, warning, and info logs in various modules such as system commands, configuration, core functionalities, and utilities. Additionally, minor adjustments were made to string formatting in backup and proxy features to enhance clarity. 2025-06-27 23:30:59 +08:00
Tunglies
3d8b2cf35f fix: improve error handling for application handle retrieval (#3860)
* fix: improve error handling for application handle retrieval

* fix: correct argument passing for command execution and improve URL stripping logic
2025-06-22 01:16:57 +08:00
wonfen
034885d810 feat: introduce event-driven proxy manager and optimize proxy config updates 2025-06-21 21:56:15 +08:00
Tunglies
5cf3e1a817 refactor: streamline macOS-specific code by consolidating conditional imports and logic in sysopt, tray, lightweight, and mihomo modules 2025-06-11 00:19:06 +08:00
wonfen
0bb042e085 feat: sysproxy guard can detect and recover from unexpected changes 2025-04-24 09:09:23 +08:00
Tunglies
07b424cb09 fix: cargo clippy errors 2025-04-21 00:06:37 +08:00
Tunglies
c7494de0a7 chore: update UPDATELOG 2025-04-20 23:51:05 +08:00
wonfen
41629df189 feat: autolaunch via Startup folder on windows 2025-04-19 13:51:11 +08:00
Tunglies
1df9fff0a7 2.2.4-alpha.0 2025-04-17 16:47:21 +08:00
逐雁南飛
b70cad537c 添加代理主机的设置,允许代理设置为其他IP(非127.0.0.1) (#2963)
允许下拉选择ip地址(支持IPv6)、localhost、以及当前系统的主机名,同时兼容手工输入
2025-04-17 16:47:21 +08:00
Tunglies
b6a6f5f434 Add AsyncHandler for wrapping task spawning 2025-04-11 17:30:30 +08:00
Tunglies
25d66a4eee Update autostart capability permissions
Enable more precise control over autostart functionality and clean up
logging code by removing unnecessary boolean parameters.
2025-04-10 15:43:45 +08:00
Tunglies
e8e16f7d57 refactor(logging): replace log_err! with structured logging_error! calls
refactor(cm-service): better error handling from Backend to Frontend
2025-03-28 03:39:34 +08:00
Tunglies
42db9ea0bb chore: enable pre-commit for Rust formatting, pre-push for Rust linter check 2025-03-26 18:59:31 +08:00
wonfen
530669d288 fix: auto launch 2025-03-17 13:51:52 +08:00
wonfen
6239f81f36 feat: sync auto-start status 2025-03-17 09:48:44 +08:00
Tunglies
b57c6e408a chore: git hooks for linter and formatter 2025-03-13 12:51:20 +08:00
huzibaca
a51191c661 chore: update default_bypass
1. add 172.29.0.0/16
2024-12-23 06:06:46 +08:00
huzibaca
bb44fc51bd fix: auto launch does not worki 2024-11-20 03:52:19 +08:00
huzibaca
c2843f3c4b fix: pac url error ,fixes #1889 2024-10-21 22:52:10 +08:00
huzibaca
9742fb296c fix: failed to start system proxy with PAC mode 2024-10-20 23:13:23 +08:00
huzibaca
2bbb5ea23b chore: update 2024-10-16 02:55:23 +08:00
huzibaca
4f9c1533c1 fix: system proxy cannot be closed on mac 2024-10-16 02:52:48 +08:00
huzibaca
f52089a674 chore:update 2024-10-10 18:52:20 +08:00
huzibaca
82543de95e chore: update 2024-10-10 18:40:39 +08:00
huzibaca
e0d96c0ce1 refactor: get_bypass func 2024-10-05 02:58:41 +08:00
huzibaca
591c1cb454 chore: update 2024-10-04 05:37:53 +08:00
huzibaca
0ca90ed082 chore: update 2024-10-04 05:27:59 +08:00
huzibaca
4c963b3978 chore: update 2024-10-03 14:31:40 +08:00
huzibaca
071665f0c3 chore: update 2024-10-03 12:01:06 +08:00
huzibaca
9a7826752f feat: windows uses sysproxy.exe for system proxy 2024-10-03 02:09:22 +08:00
huzibaca
44b4187365 refactor: simplify sysproxy logic
1. close all proxies directly when reset_proxy
2. init_sysproxy and update_sysproxy combined into one
3. optimize lock usage
4 ptimize the thread loop of guard_sysproxy,
2024-10-03 01:31:37 +08:00
huzibaca
10211d1d03 chore: optimize lock 2024-10-01 00:27:08 +08:00
huzibaca
46811f33ad chore: remove the manual release lock 2024-09-30 23:07:46 +08:00
huzibaca
57f1c005e6 fix: code lint 2024-09-24 20:06:25 +08:00
huzibaca
3154b8ce55 chore: update 2024-09-23 23:57:08 +08:00
MystiPanda
d81ef1d67c feat: allow set bypass without using default value 2024-07-01 22:53:32 +08:00
MystiPanda
c698b24e01 chore: update & fmt & clippy 2024-06-12 10:00:22 +08:00
MystiPanda
019293a034 feat: keep default bypass 2024-06-09 12:45:57 +08:00
MystiPanda
a88d149dad fix: auto proxy changed by guard 2024-05-26 19:07:14 +08:00
MystiPanda
b9ec94d835 feat: Support PAC Mode 2024-05-26 17:59:39 +08:00
Remember
952d7494ac Update 172.16.0.0/12 on Windows (#1013) 2024-05-13 18:28:41 +08:00
MystiPanda
9aeba20086 fix: use default bypass when empty 2024-05-13 18:27:19 +08:00
MystiPanda
e5b82dca4d fix: SymbolicLink
#750
2024-04-13 15:46:11 +08:00
MystiPanda
6136f1206b feat: add reset button 2024-02-22 00:19:45 +08:00
MystiPanda
36a3c5b501 fix: Do not set autolaunch at init
#423 #424
2024-02-21 23:50:50 +08:00
MystiPanda
ef9bbaca19 revert: Support both registry and api for windows sysproxy 2024-01-20 12:16:46 +08:00