Files
clash-verge-rev/src-tauri/src/core/hotkey.rs
T
Tunglies 9a904af3aa refactor: backend cleanup (#8436)
* refactor(utils): drop dead reset helper and tidy init_resources

- remove resolve_reset_async, which had no callers
- drop the duplicated time.*.com entry from the default fake-ip-filter
- init_resources no longer recreates app_home (ensure_directories during
  init_config already created it) and now propagates res_dir creation errors

* refactor(profile): remove identical blind retry when switching node

The second select_node_for_group call in switch_proxy_node was a
zero-interval retry with identical arguments. Its success path was a
degraded copy of the first (missing the Refresh::Proxies announcement
ever since the old force-refresh emit was removed), and its distinct
"回退/最终失败" log wording misled maintainers. Keep a single call,
the primary success aftermath, and one error log.

* refactor(enhance): simplify tun mode check and lowercase helpers

- Drop the always-true second clause in use_tun's enhanced-mode check:
  the key is absent only when the unwrap_or default already makes
  current_mode == "fake-ip" true.
- Collapse use_lowercase into a delegation to use_lowercase_owned.

* refactor(core): drop unreachable hotkey dtor and dedupe tray predicate

Remove impl Drop for Hotkey: the instance lives in a OnceLock static via
the singleton! macro and is never dropped; exit-time unregistration is
already handled by Hotkey::reset().

Spell the include_proxy_groups/display-mode predicate identically at
both evaluation sites in tray menu building; behavior is unchanged
(Option != Some("disable") is equivalent to unwrap_or("default") != "disable").

* refactor(config): fold port guards into single helper

The five IClashTemp port guards duplicated the same read/parse/default
logic with drifting defaults: some hardcoded 7895/7898/7899 while others
referenced network::ports constants. Route them all through one
guard_port_value helper and use the constants everywhere, keeping each
guard's name, key and cfg attributes.

* refactor(config): dedupe prfitem factories and companion seeding

from_rules/from_proxies/from_groups differed only in uid prefix, type
string and template, so they now delegate to a shared from_seq_item.
The five current_* accessors collapse into a local macro. The identical
five-block companion seeding in from_local and from_url moves into
ensure_companion_items, preserving seeding order and error propagation.

* refactor(config): share patch macro and profiles helpers

IVerge::patch_config, IProfiles::patch_item and PrfOption::merge each
hand-rolled the same copy-Some-overwrite pattern; they now share one
patch_opt_field macro (the or-else merge form is field-for-field
equivalent for Option fields). The four profiles *_safe wrappers that
inlined Config::profiles().with_data_modify boilerplate delegate to a
with_profiles_edit helper, and record/forget_selected_node share the
current-item lookup prelude via current_item_mut.

* refactor(enhance): merge chain processing and drop unused builtin js payload

- collapse the identical process_global_items/process_profile_items into
  one parameterized process_override_items (entry uid sources unchanged)
- fold the identical rules/proxies/groups arms of ChainItem::from_async
  into a single arm with an inner dispatch
- stop embedding builtin JS payloads never executed by any path: the
  enhance loop dispatches builtin items by uid to native implementations,
  so ChainItem::builtin now carries empty script data (uids unchanged)
- source ProfileItems fallback literals from Default instead of a second
  hand-written copy in collect_profile_items

* refactor(net): reuse webpki tls config and fallback

Extract build_webpki_rooted_tls_config so the delay-test TLS connector
and the reqwest clients share one static-webpki-roots builder; ALPN
stays caller-specific (only reqwest offers h2).

Collapse the duplicated platform-verifier -> static-webpki-roots retry
in get/get_bytes into request_with_static_webpki_fallback, gated by the
caller's certificate-verification setting.

* refactor(app): extract common exit cleanup

restart_app and quit duplicate the whole exit preparation: set the
exiting flag, persist configs, run interactive cleanup, and on a failed
core stop clear the flag, restore public DNS under the lifecycle lock
on macOS, and send the stop-failed notice.

Move that flow into run_exit_cleanup_flow next to clean_async, taking
the notice variant as a parameter and returning the CleanupResult so
each caller keeps its own tail: restart aborts before shutdown, quit
always shuts down and exits with the cleanup code.

* refactor(backup): share restore finalize path

restore_webdav_backup and restore_local_backup duplicated the
credential extraction (backup creation strips the WebDAV credentials,
so both re-inject the live ones), the archive extraction and the
finalize tail. Move that tail into a private restore_backup_archive
helper so the two entries keep only their download/locate logic; the
config-write lock scope and the off-runtime extraction land in one
place. The webdav entry keeps its downloaded-file cleanup.

* refactor(sysopt): drop redundant lock and busy-wait

The proxy target pair sat behind an Arc<RwLock> with no readers and an
Arc that was never cloned; both writers already serialize on
update_lock, so store the pair inside that mutex and delete the RwLock.

refresh_guard waited for the guard to become ready with a yield_now spin
at full CPU while holding guard_operation_lock; a 10 ms sleep keeps the
same wait condition and lock scope without the spin.

* refactor(sysopt): share macos bypass formatting

The macOS default bypass list and its three-way composition (empty ->
default, default + custom, custom only) were maintained twice: in
sysopt's format_bypass and inline in proxy_control's service_bypass.
Keep the literal once in constants and compose both paths through
format_bypass; service_bypass keeps its NUL check and UTF-8 truncation.

* refactor(core): dedupe window listeners, elevated runners, backup settings

- Collapse the close/focus window listener pairs in lightweight.rs onto a shared WindowListener with per-listener event and log label.
- Extract the windows runas-or-direct execution into service::run_maybe_elevated, shared by win_uwp and the service uninstaller, and factor the common uninstaller path resolution and status check shared across platforms.
- Make the auto-backup watch channel the single settings source, replacing the duplicate Arc<RwLock> copy with a stored receiver.

* refactor(enhance): fold lowercase helpers into single owned function

use_lowercase_owned disappears; the surviving use_lowercase takes the
owned Mapping and borrowed callers clone at the call site.

* refactor(enhance): rename ChainSupport variants to Mihomo names

Clash is a legacy name; the variants match the verge-mihomo and
verge-mihomo-alpha cores they gate.

* refactor(enhance): lowercase takes a reference and chain support is copy

use_lowercase borrows the mapping and clones only the values; call
sites no longer clone whole configs. ChainSupport is a fieldless enum
and now Copy; builtin() registers each support pair without clones.

* refactor(config): name prfitem constructor for what it builds

new_seq_item states that a fresh item is built from a template; the
from_ prefix wrongly implied an existing source. append_companion_item
returns the uid directly: append_item bails on a missing uid, so the
Option was always Some on the Ok path.

* refactor(sysopt): name the proxy state lock for its full role

The lock now owns the (Sysproxy, Autoproxy) state, so proxy_state_lock
says what it guards; the guard locals follow. constants::proxy held a
single sysproxy constant and is renamed sysproxy.

* refactor: replace remaining clash meta naming with mihomo

Doc comment, generated bindings and the prebuild sidecar helpers stop
referring to the legacy Clash Meta name; installer legacy-process
cleanup keeps the old executable names on purpose.

* refactor(enhance): drop builtin core filtering that never discriminates

Both valid cores matched a different ChainSupport variant, yet each
variant registered the same uid pair, so the filtered builtin list was
identical for stable and alpha. Invalid cores are coerced at startup
(validate_and_fix_config / get_valid_clash_core) and the None arm of
is_support was unreachable. builtin() now returns the items directly
and the clash_core threading through ConfigValues goes away; re-add
core discrimination when a builtin actually differs per core.

* refactor(enhance): drop unreachable mode script guard

merge_default_config overwrites the profile's mode with the verge-owned
clash config, whose mode is always present (template seeds rule and
patch semantics never clear it) and restricted to rule/global/direct;
change_clash_mode is rejected by the core before persisting anything
else. mode:script can therefore only arrive through a hand-crafted
patch_clash call, and for that path an explicit invalid-mode validation
error is more honest than silently rewriting to rule. mihomo rejects
mode:script outright (invalid mode), and user merge/script chains run
after the builtins, so the guard never covered them anyway.

* refactor(enhance): call the hysteria alpn builtin directly

builtin() existed to feed the uid-dispatch loop; with a single
builtin the vec and match are ceremony. apply_builtin_scripts calls
builtin_hy_alpn directly and to_script goes away; tests construct
ChainItem literals the way the merge items already did.
2026-11-03 10:48:44 +00:00

469 lines
16 KiB
Rust
Executable File

use crate::core::notify::NoticeStatus;
use crate::process::AsyncHandler;
use crate::singleton;
use crate::utils::notification::{NotificationEvent, notify_event};
use crate::utils::window_manager::WindowManager;
use crate::{config::Config, core::handle, core::lightweight::entry_lightweight_mode, feat};
use anyhow::{Result, bail};
use arc_swap::ArcSwap;
use clash_verge_logging::{Type, logging};
use smartstring::alias::String;
use std::{
collections::HashMap,
fmt,
str::FromStr,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
};
use tauri_plugin_global_shortcut::{Code, GlobalShortcutExt as _, ShortcutState};
/// Enum representing all available hotkey functions
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum HotkeyFunction {
OpenOrCloseDashboard,
ClashModeRule,
ClashModeGlobal,
ClashModeDirect,
ToggleSystemProxy,
ToggleTunMode,
EntryLightweightMode,
ReactivateProfiles,
Quit,
#[cfg(target_os = "macos")]
Hide,
}
impl fmt::Display for HotkeyFunction {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match self {
Self::OpenOrCloseDashboard => "open_or_close_dashboard",
Self::ClashModeRule => "clash_mode_rule",
Self::ClashModeGlobal => "clash_mode_global",
Self::ClashModeDirect => "clash_mode_direct",
Self::ToggleSystemProxy => "toggle_system_proxy",
Self::ToggleTunMode => "toggle_tun_mode",
Self::EntryLightweightMode => "entry_lightweight_mode",
Self::ReactivateProfiles => "reactivate_profiles",
Self::Quit => "quit",
#[cfg(target_os = "macos")]
Self::Hide => "hide",
};
write!(f, "{s}")
}
}
impl FromStr for HotkeyFunction {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.trim() {
"open_or_close_dashboard" => Ok(Self::OpenOrCloseDashboard),
"clash_mode_rule" => Ok(Self::ClashModeRule),
"clash_mode_global" => Ok(Self::ClashModeGlobal),
"clash_mode_direct" => Ok(Self::ClashModeDirect),
"toggle_system_proxy" => Ok(Self::ToggleSystemProxy),
"toggle_tun_mode" => Ok(Self::ToggleTunMode),
"entry_lightweight_mode" => Ok(Self::EntryLightweightMode),
"reactivate_profiles" => Ok(Self::ReactivateProfiles),
"quit" => Ok(Self::Quit),
#[cfg(target_os = "macos")]
"hide" => Ok(Self::Hide),
_ => bail!("invalid hotkey function: {}", s),
}
}
}
#[cfg(target_os = "macos")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
/// Enum representing predefined system hotkeys
pub enum SystemHotkey {
CmdQ,
CmdW,
}
#[cfg(target_os = "macos")]
impl fmt::Display for SystemHotkey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match self {
Self::CmdQ => "CMD+Q",
Self::CmdW => "CMD+W",
};
write!(f, "{s}")
}
}
#[cfg(target_os = "macos")]
impl SystemHotkey {
pub const fn function(self) -> HotkeyFunction {
match self {
Self::CmdQ => HotkeyFunction::Quit,
Self::CmdW => HotkeyFunction::Hide,
}
}
}
pub struct Hotkey {
current: ArcSwap<Vec<String>>,
}
impl Hotkey {
fn new() -> Self {
Self {
current: ArcSwap::new(Arc::new(Vec::new())),
}
}
/// Execute the function associated with a hotkey function enum
fn execute_function(function: HotkeyFunction) {
match function {
HotkeyFunction::OpenOrCloseDashboard => {
AsyncHandler::spawn(async move || {
crate::feat::open_or_close_dashboard().await;
notify_event(NotificationEvent::DashboardToggled).await;
});
}
HotkeyFunction::ClashModeRule => {
AsyncHandler::spawn(async move || {
// 错误已在 change_clash_mode 内部记录,此处显式忽略返回值
let _ = feat::change_clash_mode("rule".into()).await;
notify_event(NotificationEvent::ClashModeChanged { mode: "Rule" }).await;
});
}
HotkeyFunction::ClashModeGlobal => {
AsyncHandler::spawn(async move || {
// 错误已在 change_clash_mode 内部记录,此处显式忽略返回值
let _ = feat::change_clash_mode("global".into()).await;
notify_event(NotificationEvent::ClashModeChanged { mode: "Global" }).await;
});
}
HotkeyFunction::ClashModeDirect => {
AsyncHandler::spawn(async move || {
// 错误已在 change_clash_mode 内部记录,此处显式忽略返回值
let _ = feat::change_clash_mode("direct".into()).await;
notify_event(NotificationEvent::ClashModeChanged { mode: "Direct" }).await;
});
}
HotkeyFunction::ToggleSystemProxy => {
AsyncHandler::spawn(async move || {
if let Some(is_proxy_enabled) = feat::toggle_system_proxy().await {
notify_event(NotificationEvent::SystemProxyToggled(is_proxy_enabled)).await;
}
});
}
HotkeyFunction::ToggleTunMode => {
AsyncHandler::spawn(async move || {
let is_tun_enable = feat::toggle_tun_mode(None).await;
notify_event(NotificationEvent::TunModeToggled(is_tun_enable)).await;
});
}
HotkeyFunction::EntryLightweightMode => {
AsyncHandler::spawn(async move || {
entry_lightweight_mode().await;
notify_event(NotificationEvent::LightweightModeEntered).await;
});
}
HotkeyFunction::ReactivateProfiles => {
AsyncHandler::spawn(async move || match feat::enhance_profiles().await {
Ok(outcome) if outcome.is_valid() => {
handle::Handle::refresh_clash();
notify_event(NotificationEvent::ProfilesReactivated).await;
}
Ok(outcome) => {
let message = outcome.to_string();
logging!(
warn,
Type::Hotkey,
"Hotkey profile reactivation failed validation: {}",
message.as_str()
);
handle::Handle::notice(NoticeStatus::ReactivateProfilesError, message);
}
Err(err) => {
logging!(
error,
Type::Hotkey,
"Failed to reactivate subscriptions via hotkey: {}",
err
);
handle::Handle::notice(NoticeStatus::ReactivateProfilesError, err.to_string());
}
});
}
HotkeyFunction::Quit => {
AsyncHandler::spawn(async move || {
notify_event(NotificationEvent::AppQuit).await;
feat::quit().await;
});
}
#[cfg(target_os = "macos")]
HotkeyFunction::Hide => {
AsyncHandler::spawn(async move || {
feat::hide().await;
});
}
}
}
#[cfg(target_os = "macos")]
/// Register a system hotkey using enum
pub async fn register_system_hotkey(&self, hotkey: SystemHotkey) -> Result<()> {
let hotkey_str = hotkey.to_string();
let function = hotkey.function();
self.register_hotkey_with_function(&hotkey_str, function).await
}
#[cfg(target_os = "macos")]
/// Unregister a system hotkey using enum
pub fn unregister_system_hotkey(&self, hotkey: SystemHotkey) -> Result<()> {
let hotkey_str = hotkey.to_string();
self.unregister(&hotkey_str)
}
/// Register a hotkey with function enum
#[allow(clippy::unused_async)]
pub async fn register_hotkey_with_function(&self, hotkey: &str, function: HotkeyFunction) -> Result<()> {
let app_handle = handle::Handle::app_handle();
let manager = app_handle.global_shortcut();
logging!(
debug,
Type::Hotkey,
"Attempting to register hotkey: {} for function: {}",
hotkey,
function
);
if manager.is_registered(hotkey) {
logging!(
debug,
Type::Hotkey,
"Hotkey {} was already registered, unregistering first",
hotkey
);
manager.unregister(hotkey)?;
}
let is_quit = matches!(function, HotkeyFunction::Quit);
let pressed = AtomicBool::new(false);
manager.on_shortcut(hotkey, move |_app_handle, hotkey_event, event| match event.state {
ShortcutState::Released => {
pressed.store(false, Ordering::Relaxed);
}
ShortcutState::Pressed => {
if pressed.swap(true, Ordering::Relaxed) {
logging!(
debug,
Type::Hotkey,
"Ignoring repeated hotkey press: {:?}",
hotkey_event
);
return;
}
logging!(debug, Type::Hotkey, "Hotkey pressed: {:?}", hotkey_event);
let hotkey = hotkey_event.key;
if hotkey == Code::KeyQ && is_quit {
if let Some(window) = WindowManager::get_main_window()
&& window.is_focused().unwrap_or(false)
{
logging!(debug, Type::Hotkey, "Executing quit function");
Self::execute_function(function);
}
} else {
AsyncHandler::spawn(move || async move {
logging!(debug, Type::Hotkey, "Executing function directly");
let is_enable_global_hotkey =
Config::verge().await.data_arc().enable_global_hotkey.unwrap_or(true);
if is_enable_global_hotkey {
Self::execute_function(function);
} else {
use crate::utils::window_manager::WindowManager;
let window = WindowManager::get_main_window();
let is_visible = WindowManager::is_main_window_visible(window.as_ref());
let is_focused = WindowManager::is_main_window_focused(window.as_ref());
if is_focused && is_visible {
Self::execute_function(function);
}
}
});
}
}
})?;
logging!(
debug,
Type::Hotkey,
"Successfully registered hotkey {} for {}",
hotkey,
function
);
Ok(())
}
}
singleton!(Hotkey, INSTANCE);
impl Hotkey {
pub async fn init(&self, skip: bool) -> Result<()> {
if skip {
logging!(debug, Type::Hotkey, "skip register all hotkeys");
return Ok(());
}
let verge = Config::verge().await;
let enable_global_hotkey = verge.latest_arc().enable_global_hotkey.unwrap_or(true);
logging!(
debug,
Type::Hotkey,
"Initializing global hotkeys: {}",
enable_global_hotkey
);
// Extract hotkeys data before async operations
let hotkeys = verge.latest_arc().hotkeys.clone();
if let Some(hotkeys) = hotkeys {
logging!(debug, Type::Hotkey, "Has {} hotkeys need to register", hotkeys.len());
for hotkey in hotkeys.iter() {
let mut iter = hotkey.split(',');
let func = iter.next();
let key = iter.next();
match (key, func) {
(Some(key), Some(func)) => {
logging!(debug, Type::Hotkey, "Registering hotkey: {} -> {}", key, func);
if let Err(e) = self.register(key, func).await {
logging!(
error,
Type::Hotkey,
"Failed to register hotkey {} -> {}: {:?}",
key,
func,
e
);
} else {
logging!(
debug,
Type::Hotkey,
"Successfully registered hotkey {} -> {}",
key,
func
);
}
}
_ => {
let key = key.unwrap_or("None");
let func = func.unwrap_or("None");
logging!(
error,
Type::Hotkey,
"Invalid hotkey configuration: `{}`:`{}`",
key,
func
);
}
}
}
self.current.store(Arc::new(hotkeys));
} else {
logging!(debug, Type::Hotkey, "No hotkeys configured");
}
Ok(())
}
pub fn reset(&self) -> Result<()> {
let app_handle = handle::Handle::app_handle();
let manager = app_handle.global_shortcut();
manager.unregister_all()?;
Ok(())
}
/// Register a hotkey with string-based function (backward compatibility)
pub async fn register(&self, hotkey: &str, func: &str) -> Result<()> {
let function = HotkeyFunction::from_str(func)?;
self.register_hotkey_with_function(hotkey, function).await
}
pub fn unregister(&self, hotkey: &str) -> Result<()> {
let app_handle = handle::Handle::app_handle();
let manager = app_handle.global_shortcut();
manager.unregister(hotkey)?;
logging!(debug, Type::Hotkey, "Unregister hotkey {}", hotkey);
Ok(())
}
pub async fn update(&self, new_hotkeys: Vec<String>) -> Result<()> {
// Extract current hotkeys before async operations
let current_hotkeys = &*self.current.load();
let old_map = Self::get_map_from_vec(current_hotkeys);
let new_map = Self::get_map_from_vec(&new_hotkeys);
let (del, add) = Self::get_diff(old_map, new_map);
del.iter().for_each(|key| {
let _ = self.unregister(key);
});
for (key, func) in add.iter() {
self.register(key, func).await?;
}
// Update the current hotkeys after all async operations
self.current.store(Arc::new(new_hotkeys));
Ok(())
}
fn get_map_from_vec(hotkeys: &[String]) -> HashMap<&str, &str> {
let mut map = HashMap::new();
hotkeys.iter().for_each(|hotkey| {
let mut iter = hotkey.split(',');
let func = iter.next();
let key = iter.next();
if let (Some(func), Some(key)) = (func, key) {
let func = func.trim();
let key = key.trim();
map.insert(key, func);
}
});
map
}
fn get_diff<'a>(
old_map: HashMap<&'a str, &'a str>,
new_map: HashMap<&'a str, &'a str>,
) -> (Vec<&'a str>, Vec<(&'a str, &'a str)>) {
let mut del_list = vec![];
let mut add_list = vec![];
old_map.iter().for_each(|(&key, func)| {
match new_map.get(key) {
Some(new_func) => {
if new_func != func {
del_list.push(key);
add_list.push((key, *new_func));
}
}
None => del_list.push(key),
};
});
new_map.iter().for_each(|(&key, &func)| {
if !old_map.contains_key(key) {
add_list.push((key, func));
}
});
(del_list, add_list)
}
}