Files
clash-verge-rev/src-tauri/src/feat/window.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

522 lines
17 KiB
Rust

use crate::config::Config;
use crate::core::lightweight;
use crate::core::notify::NoticeStatus;
use crate::core::{CoreManager, handle};
use crate::utils;
use crate::utils::window_manager::WindowManager;
use anyhow::{Context as _, anyhow};
use clash_verge_logging::{Type, logging};
use parking_lot::Mutex;
use std::sync::mpsc::RecvTimeoutError;
use tokio::time::Duration;
#[cfg(target_os = "macos")]
use tokio::time::timeout;
#[cfg(target_os = "windows")]
const SESSION_ENDING_STOP_TIMEOUT: Duration = Duration::from_secs(2);
// TODO(macOS): a DNS script already running can outlast this and write after exit.
#[cfg(not(target_os = "windows"))]
const SESSION_ENDING_STOP_TIMEOUT: Duration = Duration::from_secs(3);
// Outlasts the script's own kill deadline.
#[cfg(target_os = "macos")]
const DNS_RESTORE_TIMEOUT: Duration =
crate::utils::resolve::dns::DNS_SCRIPT_TIMEOUT.saturating_add(Duration::from_secs(1));
#[cfg(not(target_os = "macos"))]
const DNS_RESTORE_TIMEOUT: Duration = Duration::ZERO;
// Backstop for when the cleanup's own deadlines cannot fire.
const SESSION_ENDING_HARD_DEADLINE: Duration = SESSION_ENDING_STOP_TIMEOUT
.saturating_add(DNS_RESTORE_TIMEOUT)
.saturating_add(Duration::from_secs(1));
#[derive(Debug, Clone, Default)]
pub struct CleanupResult {
pub all_success: bool,
pub core_stopped: bool,
/// Why the stop failed, for the cancelled-exit notice.
pub stop_error: Option<String>,
}
const fn should_abort_exit_after_cleanup(core_stopped: bool) -> bool {
!core_stopped
}
async fn run_exit_cleanup_transition<Stop, StopFuture, Ancillary, AncillaryFuture>(
stop_core: Stop,
ancillary_cleanup: Ancillary,
) -> CleanupResult
where
Stop: FnOnce() -> StopFuture,
StopFuture: std::future::Future<Output = bool>,
Ancillary: FnOnce() -> AncillaryFuture,
AncillaryFuture: std::future::Future<Output = bool>,
{
if !stop_core().await {
return CleanupResult::default();
}
CleanupResult {
all_success: ancillary_cleanup().await,
core_stopped: true,
stop_error: None,
}
}
async fn run_interactive_cleanup_transition<Stop, StopFuture, Ancillary, AncillaryFuture>(
stop_core: Stop,
ancillary_cleanup: Ancillary,
) -> CleanupResult
where
Stop: FnOnce() -> StopFuture,
StopFuture: std::future::Future<Output = bool>,
Ancillary: FnOnce() -> AncillaryFuture,
AncillaryFuture: std::future::Future<Output = bool>,
{
run_exit_cleanup_transition(stop_core, ancillary_cleanup).await
}
async fn run_session_ending_cleanup_transition<Stop, StopFuture, DeadlineFuture, Ancillary, AncillaryFuture>(
stop_core: Stop,
stop_deadline: DeadlineFuture,
ancillary_cleanup: Ancillary,
) -> CleanupResult
where
Stop: FnOnce() -> StopFuture,
StopFuture: std::future::Future<Output = bool>,
DeadlineFuture: std::future::Future<Output = ()>,
Ancillary: FnOnce() -> AncillaryFuture,
AncillaryFuture: std::future::Future<Output = bool>,
{
run_exit_cleanup_transition(
|| async {
tokio::select! {
biased;
stopped = stop_core() => stopped,
() = stop_deadline => false,
}
},
ancillary_cleanup,
)
.await
}
async fn restore_dns_after_core_stop() -> bool {
#[cfg(target_os = "macos")]
match timeout(DNS_RESTORE_TIMEOUT, crate::utils::resolve::dns::restore_public_dns()).await {
Ok(Ok(())) => {
logging!(debug, Type::Window, "DNS设置已恢复");
true
}
Ok(Err(err)) => {
logging!(warn, Type::Window, "恢复DNS设置失败: {err:#}");
false
}
Err(_) => {
logging!(warn, Type::Window, "恢复DNS设置超时");
false
}
}
#[cfg(not(target_os = "macos"))]
true
}
pub async fn open_or_close_dashboard() {
if lightweight::is_in_lightweight_mode() {
let _ = lightweight::exit_lightweight_mode().await;
return;
}
let result = WindowManager::toggle_main_window().await;
logging!(info, Type::Window, "Window toggle result: {result:?}");
}
pub(crate) async fn run_exit_cleanup_flow(stop_failed_notice: NoticeStatus) -> CleanupResult {
handle::Handle::global().set_is_exiting();
Config::apply_all_and_save_file().await;
let cleanup_result = clean_async().await;
logging!(
info,
Type::System,
"资源清理完成,退出代码: {}",
if cleanup_result.all_success { 0 } else { 1 }
);
if should_abort_exit_after_cleanup(cleanup_result.core_stopped) {
handle::Handle::global().clear_is_exiting();
// A failed stop may still have marked the core stopped, and exit cleanup skipped the DNS restore.
// A core that kept running keeps its DNS, whatever an unapplied config draft says.
#[cfg(target_os = "macos")]
{
let manager = CoreManager::global();
let _lifecycle = manager.lifecycle_lock.lock().await;
if matches!(
*manager.get_running_mode(),
crate::core::manager::RunningMode::NotRunning
) {
crate::utils::resolve::dns::sync_public_dns().await;
}
}
handle::Handle::notice(
stop_failed_notice,
cleanup_result.stop_error.clone().unwrap_or_default(),
);
}
cleanup_result
}
pub async fn quit() {
logging!(debug, Type::System, "启动退出流程");
let cleanup_result = run_exit_cleanup_flow(NoticeStatus::AppQuitCoreStopFailed).await;
utils::server::shutdown_embedded_server();
let app_handle = handle::Handle::app_handle();
app_handle.exit(if cleanup_result.all_success { 0 } else { 1 });
}
pub async fn clean_async() -> CleanupResult {
let stop_error = Mutex::new(None);
let mut result = run_interactive_cleanup_transition(
|| async {
logging!(debug, Type::System, "Stopping core for interactive quit or restart");
match CoreManager::global().stop_core().await {
Ok(()) => true,
Err(error) => {
logging!(
warn,
Type::Window,
"Controlled core stop failed; interactive quit or restart must remain cancelled: {error:#}"
);
*stop_error.lock() = Some(format!("{error:#}"));
false
}
}
},
restore_dns_after_core_stop,
)
.await;
result.stop_error = stop_error.into_inner();
logging!(
info,
Type::System,
"Interactive cleanup complete - core stopped: {}, all cleanup successful: {}",
result.core_stopped,
result.all_success
);
result
}
pub fn clean_session_ending_with_hard_deadline() -> Option<CleanupResult> {
match run_with_hard_deadline(clean_session_ending_best_effort, SESSION_ENDING_HARD_DEADLINE) {
Ok(result) => Some(result),
Err(error) => {
logging!(
warn,
Type::System,
"Session-ending cleanup abandoned; exiting without it: {error:#}"
);
None
}
}
}
/// Avoids the app runtime, whose workers may wait on the blocked main thread.
fn run_with_hard_deadline<F, Fut, T>(cleanup: F, deadline: Duration) -> anyhow::Result<T>
where
F: FnOnce() -> Fut + Send + 'static,
Fut: std::future::Future<Output = T>,
T: Send + 'static,
{
let (sender, receiver) = std::sync::mpsc::sync_channel(1);
std::thread::Builder::new()
.name("clash-verge-session-ending".into())
.spawn(move || {
let runtime = match tokio::runtime::Builder::new_current_thread().enable_all().build() {
Ok(runtime) => runtime,
Err(error) => {
let _ = sender.send(Err(error));
return;
}
};
// Send first: dropping the runtime waits for blocking tasks.
let _ = sender.send(Ok(runtime.block_on(cleanup())));
})
.context("failed to spawn the cleanup thread")?;
match receiver.recv_timeout(deadline) {
Ok(result) => result.context("failed to build the cleanup runtime"),
Err(RecvTimeoutError::Timeout) => Err(anyhow!("still running after {} ms", deadline.as_millis())),
Err(RecvTimeoutError::Disconnected) => Err(anyhow!("cleanup thread ended without a result")),
}
}
async fn clean_session_ending_best_effort() -> CleanupResult {
logging!(
info,
Type::System,
"Starting bounded session-ending best-effort cleanup"
);
let result = run_session_ending_cleanup_transition(
|| async {
let _ = handle::Handle::mihomo().clear_all_ws_connections();
match CoreManager::global().stop_core().await {
Ok(()) => {
true
}
Err(error) => {
logging!(
warn,
Type::Window,
"Session-ending best-effort core stop failed; OS or session exit is already in progress: {error:#}"
);
false
}
}
},
async move {
tokio::time::sleep(SESSION_ENDING_STOP_TIMEOUT).await;
logging!(
warn,
Type::Window,
"Session-ending best-effort core stop timed out after {} seconds; OS or session exit is already in progress",
SESSION_ENDING_STOP_TIMEOUT.as_secs()
);
},
restore_dns_after_core_stop,
)
.await;
logging!(
info,
Type::System,
"Session-ending best-effort cleanup finished - core stopped: {}, all cleanup successful: {}",
result.core_stopped,
result.all_success
);
result
}
#[cfg(target_os = "macos")]
pub async fn hide() {
use crate::core::lightweight::add_light_weight_timer;
let enable_auto_light_weight_mode = Config::verge()
.await
.data_arc()
.enable_auto_light_weight_mode
.unwrap_or(false);
if enable_auto_light_weight_mode {
add_light_weight_timer().await;
}
if let Some(window) = WindowManager::get_main_window()
&& window.is_visible().unwrap_or(false)
{
let _ = window.hide();
}
handle::Handle::global().set_activation_policy_accessory();
}
#[cfg(test)]
mod tests {
use super::{
run_interactive_cleanup_transition, run_session_ending_cleanup_transition, run_with_hard_deadline,
should_abort_exit_after_cleanup,
};
use parking_lot::Mutex;
use std::{
future::pending,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
mpsc,
},
task::Poll,
time::Duration,
};
use tokio::sync::Barrier;
struct CancellationProbe {
cancelled: Arc<AtomicBool>,
completed: Arc<AtomicBool>,
}
impl Drop for CancellationProbe {
fn drop(&mut self) {
if !self.completed.load(Ordering::Acquire) {
self.cancelled.store(true, Ordering::Release);
}
}
}
#[test]
fn exit_aborts_when_controlled_core_stop_fails() {
assert!(should_abort_exit_after_cleanup(false));
assert!(!should_abort_exit_after_cleanup(true));
}
#[test]
fn hard_deadline_returns_while_cleanup_blocks_its_thread() {
let (release, blocked) = mpsc::channel::<()>();
let result = run_with_hard_deadline(
move || async move {
let _ = blocked.recv();
},
Duration::from_millis(50),
);
assert!(matches!(result, Err(error) if error.to_string().starts_with("still running")));
drop(release);
}
#[test]
fn hard_deadline_cleanup_runs_its_own_timers() {
let result = run_with_hard_deadline(
|| async {
tokio::time::sleep(Duration::from_millis(10)).await;
true
},
Duration::from_secs(5),
);
assert!(result.is_ok_and(|done| done));
}
#[tokio::test]
async fn interactive_cleanup_awaits_barrier_controlled_stop_without_cancellation() {
let calls = Arc::new(Mutex::new(Vec::new()));
let stop_started = Arc::new(Barrier::new(2));
let release_stop = Arc::new(Barrier::new(2));
let stop_cancelled = Arc::new(AtomicBool::new(false));
let stop_completed = Arc::new(AtomicBool::new(false));
let mut cleanup = Box::pin(run_interactive_cleanup_transition(
{
let calls = Arc::clone(&calls);
let stop_started = Arc::clone(&stop_started);
let release_stop = Arc::clone(&release_stop);
let stop_cancelled = Arc::clone(&stop_cancelled);
let stop_completed = Arc::clone(&stop_completed);
move || async move {
let _probe = CancellationProbe {
cancelled: stop_cancelled,
completed: Arc::clone(&stop_completed),
};
calls.lock().push("core_stop");
stop_started.wait().await;
release_stop.wait().await;
stop_completed.store(true, Ordering::Release);
true
}
},
{
let calls = Arc::clone(&calls);
move || async move {
calls.lock().push("ancillary_cleanup");
true
}
},
));
assert!(matches!(futures::poll!(cleanup.as_mut()), Poll::Pending));
stop_started.wait().await;
assert!(matches!(futures::poll!(cleanup.as_mut()), Poll::Pending));
assert!(!stop_cancelled.load(Ordering::Acquire));
assert_eq!(&*calls.lock(), &["core_stop"]);
release_stop.wait().await;
let result = cleanup.await;
assert!(result.core_stopped);
assert!(result.all_success);
assert!(!stop_cancelled.load(Ordering::Acquire));
assert_eq!(&*calls.lock(), &["core_stop", "ancillary_cleanup"]);
}
#[tokio::test]
async fn interactive_cleanup_does_not_run_ancillary_cleanup_after_stop_failure() {
let calls = Mutex::new(Vec::new());
let result = run_interactive_cleanup_transition(
|| async {
calls.lock().push("core_stop");
false
},
|| async {
calls.lock().push("ancillary_cleanup");
true
},
)
.await;
assert!(!result.core_stopped);
assert!(!result.all_success);
assert_eq!(&*calls.lock(), &["core_stop"]);
}
#[tokio::test]
async fn session_ending_cleanup_may_cancel_stop_and_skips_ancillary_after_timeout() {
let calls = Arc::new(Mutex::new(Vec::new()));
let stop_started = Arc::new(Barrier::new(2));
let deadline_started = Arc::new(Barrier::new(2));
let release_deadline = Arc::new(Barrier::new(2));
let stop_cancelled = Arc::new(AtomicBool::new(false));
let stop_completed = Arc::new(AtomicBool::new(false));
let mut cleanup = Box::pin(run_session_ending_cleanup_transition(
{
let calls = Arc::clone(&calls);
let stop_started = Arc::clone(&stop_started);
let stop_cancelled = Arc::clone(&stop_cancelled);
let stop_completed = Arc::clone(&stop_completed);
move || async move {
let _probe = CancellationProbe {
cancelled: stop_cancelled,
completed: stop_completed,
};
calls.lock().push("core_stop");
stop_started.wait().await;
pending::<bool>().await
}
},
{
let deadline_started = Arc::clone(&deadline_started);
let release_deadline = Arc::clone(&release_deadline);
async move {
deadline_started.wait().await;
release_deadline.wait().await;
}
},
{
let calls = Arc::clone(&calls);
move || async move {
calls.lock().push("ancillary_cleanup");
true
}
},
));
assert!(matches!(futures::poll!(cleanup.as_mut()), Poll::Pending));
stop_started.wait().await;
deadline_started.wait().await;
assert!(matches!(futures::poll!(cleanup.as_mut()), Poll::Pending));
assert!(!stop_cancelled.load(Ordering::Acquire));
release_deadline.wait().await;
let result = cleanup.await;
assert!(!result.core_stopped);
assert!(!result.all_success);
assert!(stop_cancelled.load(Ordering::Acquire));
assert_eq!(&*calls.lock(), &["core_stop"]);
}
}