refactor(core): fold tray, hotkey, autostart updates into effect ensures

This commit is contained in:
Tunglies
2026-10-01 14:34:16 +08:00
committed by GitHub
parent 7aed7be2f1
commit 9d1b400299
14 changed files with 86 additions and 42 deletions
+57
View File
@@ -0,0 +1,57 @@
use crate::{
config::{Config, IVerge},
core::{autostart, hotkey, lightweight, tray},
};
use anyhow::Result;
use futures::future::BoxFuture;
pub(crate) fn ensure_autostart(_patch: &IVerge) -> BoxFuture<'_, Result<()>> {
Box::pin(async move { autostart::update_launch().await })
}
pub(crate) fn ensure_hotkey(patch: &IVerge) -> BoxFuture<'_, Result<()>> {
Box::pin(async move {
if let Some(hotkeys) = &patch.hotkeys {
hotkey::Hotkey::global().update(hotkeys.to_owned()).await?;
}
Ok(())
})
}
pub(crate) fn ensure_tray_menu(_patch: &IVerge) -> BoxFuture<'_, Result<()>> {
Box::pin(async move { tray::Tray::global().update_menu().await })
}
pub(crate) fn ensure_tray_icon(patch: &IVerge) -> BoxFuture<'_, Result<()>> {
Box::pin(async move {
tray::Tray::global()
.update_icon(&Config::verge().await.latest_arc())
.await?;
#[cfg(target_os = "macos")]
if let Some(enabled) = patch.enable_tray_speed {
tray::Tray::global().update_speed_task(enabled);
}
#[cfg(not(target_os = "macos"))]
let _ = patch;
Ok(())
})
}
pub(crate) fn ensure_tray_tooltip(_patch: &IVerge) -> BoxFuture<'_, Result<()>> {
Box::pin(async move { tray::Tray::global().update_tooltip().await })
}
pub(crate) fn ensure_tray_click(_patch: &IVerge) -> BoxFuture<'_, Result<()>> {
Box::pin(async move { tray::Tray::global().update_click_behavior().await })
}
pub(crate) fn ensure_lightweight(patch: &IVerge) -> BoxFuture<'_, Result<()>> {
Box::pin(async move {
if patch.enable_auto_light_weight_mode.unwrap_or(false) {
lightweight::enable_auto_light_weight_mode().await;
} else {
lightweight::disable_auto_light_weight_mode();
}
Ok(())
})
}
+313
View File
@@ -0,0 +1,313 @@
use crate::{
config::{Config, IVerge},
feat::create_local_backup_with_namer,
process::AsyncHandler,
utils::dirs::local_backup_dir,
};
use anyhow::Result;
use chrono::Local;
use clash_verge_logging::{Type, logging};
use once_cell::sync::OnceCell;
use parking_lot::RwLock;
use std::{
path::PathBuf,
sync::{
Arc,
atomic::{AtomicBool, AtomicI64, Ordering},
},
time::{Duration, UNIX_EPOCH},
};
use tokio::{
fs,
sync::{Mutex, watch},
};
const DEFAULT_INTERVAL_HOURS: u64 = 24;
const MIN_INTERVAL_HOURS: u64 = 1;
const MAX_INTERVAL_HOURS: u64 = 168;
const MIN_BACKUP_INTERVAL_SECS: i64 = 60;
const AUTO_BACKUP_KEEP: usize = 20;
const AUTO_MARKER: &str = "-auto-";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AutoBackupTrigger {
Scheduled,
GlobalMerge,
GlobalScript,
}
impl AutoBackupTrigger {
const fn slug(self) -> &'static str {
match self {
Self::Scheduled => "scheduled",
Self::GlobalMerge => "merge",
Self::GlobalScript => "script",
}
}
const fn is_schedule(self) -> bool {
matches!(self, Self::Scheduled)
}
}
#[derive(Clone, Copy, Debug)]
struct AutoBackupSettings {
schedule_enabled: bool,
interval_hours: u64,
change_enabled: bool,
}
impl AutoBackupSettings {
fn from_verge(verge: &IVerge) -> Self {
let interval = verge
.auto_backup_interval_hours
.unwrap_or(DEFAULT_INTERVAL_HOURS)
.clamp(MIN_INTERVAL_HOURS, MAX_INTERVAL_HOURS);
Self {
schedule_enabled: verge.enable_auto_backup_schedule.unwrap_or(false),
interval_hours: interval,
change_enabled: verge.auto_backup_on_change.unwrap_or(true),
}
}
}
impl Default for AutoBackupSettings {
fn default() -> Self {
Self {
schedule_enabled: false,
interval_hours: DEFAULT_INTERVAL_HOURS,
change_enabled: true,
}
}
}
pub struct AutoBackupManager {
settings: Arc<RwLock<AutoBackupSettings>>,
settings_tx: watch::Sender<AutoBackupSettings>,
runner_started: AtomicBool,
exec_lock: Mutex<()>,
last_backup: AtomicI64,
}
impl AutoBackupManager {
pub fn global() -> &'static Self {
static INSTANCE: OnceCell<AutoBackupManager> = OnceCell::new();
INSTANCE.get_or_init(|| {
let (tx, _rx) = watch::channel(AutoBackupSettings::default());
Self {
settings: Arc::new(RwLock::new(AutoBackupSettings::default())),
settings_tx: tx,
runner_started: AtomicBool::new(false),
exec_lock: Mutex::new(()),
last_backup: AtomicI64::new(0),
}
})
}
pub async fn init(&self) -> Result<()> {
let settings = Self::load_settings().await;
{
*self.settings.write() = settings;
}
let _ = self.settings_tx.send(settings);
self.maybe_start_runner(settings);
Ok(())
}
pub async fn refresh_settings(&self) -> Result<()> {
let settings = Self::load_settings().await;
{
*self.settings.write() = settings;
}
let _ = self.settings_tx.send(settings);
self.maybe_start_runner(settings);
Ok(())
}
pub fn trigger_backup(trigger: AutoBackupTrigger) {
AsyncHandler::spawn(move || async move {
if let Err(err) = Self::global().execute_trigger(trigger).await {
logging!(
warn,
Type::Backup,
"Auto backup execution failed ({:?}): {err:#?}",
trigger
);
}
});
}
fn maybe_start_runner(&self, settings: AutoBackupSettings) {
if settings.schedule_enabled {
self.ensure_runner();
}
}
fn ensure_runner(&self) {
if self.runner_started.swap(true, Ordering::SeqCst) {
return;
}
let mut rx = self.settings_tx.subscribe();
AsyncHandler::spawn(move || async move {
Self::run_scheduler(&mut rx).await;
});
}
async fn run_scheduler(rx: &mut watch::Receiver<AutoBackupSettings>) {
let mut current = *rx.borrow();
loop {
if !current.schedule_enabled {
if rx.changed().await.is_err() {
break;
}
current = *rx.borrow();
continue;
}
let duration = Duration::from_secs(current.interval_hours.saturating_mul(3600));
let sleeper = tokio::time::sleep(duration);
tokio::pin!(sleeper);
tokio::select! {
_ = &mut sleeper => {
if let Err(err) = Self::global()
.execute_trigger(AutoBackupTrigger::Scheduled)
.await
{
logging!(
warn,
Type::Backup,
"Scheduled auto backup failed: {err:#?}"
);
}
}
changed = rx.changed() => {
if changed.is_err() {
break;
}
current = *rx.borrow();
}
}
}
}
async fn execute_trigger(&self, trigger: AutoBackupTrigger) -> Result<()> {
let snapshot = *self.settings.read();
if trigger.is_schedule() && !snapshot.schedule_enabled {
return Ok(());
}
if !trigger.is_schedule() && !snapshot.change_enabled {
return Ok(());
}
if !self.should_run_now() {
return Ok(());
}
let _guard = self.exec_lock.lock().await;
if !self.should_run_now() {
return Ok(());
}
let file_name = create_local_backup_with_namer(|name| append_auto_suffix(name, trigger.slug()).into()).await?;
self.last_backup.store(Local::now().timestamp(), Ordering::Release);
if let Err(err) = cleanup_auto_backups().await {
logging!(warn, Type::Backup, "Failed to cleanup old auto backups: {err:#?}");
}
logging!(info, Type::Backup, "Auto backup created ({:?}): {}", trigger, file_name);
Ok(())
}
fn should_run_now(&self) -> bool {
let last = self.last_backup.load(Ordering::Acquire);
if last == 0 {
return true;
}
let now = Local::now().timestamp();
now.saturating_sub(last) >= MIN_BACKUP_INTERVAL_SECS
}
async fn load_settings() -> AutoBackupSettings {
let verge = Config::verge().await;
AutoBackupSettings::from_verge(&verge.latest_arc())
}
}
fn append_auto_suffix(file_name: &str, slug: &str) -> String {
match file_name.rsplit_once('.') {
Some((stem, ext)) => format!("{stem}{AUTO_MARKER}{slug}.{ext}"),
None => format!("{file_name}{AUTO_MARKER}{slug}"),
}
}
async fn cleanup_auto_backups() -> Result<()> {
if AUTO_BACKUP_KEEP == 0 {
return Ok(());
}
let backup_dir = local_backup_dir()?;
if !backup_dir.exists() {
return Ok(());
}
let mut entries = match fs::read_dir(&backup_dir).await {
Ok(dir) => dir,
Err(err) => {
logging!(warn, Type::Backup, "Failed to read backup directory: {err:#?}");
return Ok(());
}
};
let mut files: Vec<(PathBuf, u64)> = Vec::new();
while let Some(entry) = entries.next_entry().await? {
let path = entry.path();
if !path.is_file() {
continue;
}
let file_name = match entry.file_name().into_string() {
Ok(name) => name,
Err(_) => continue,
};
if !file_name.contains(AUTO_MARKER) {
continue;
}
let modified = entry
.metadata()
.await
.and_then(|meta| meta.modified())
.ok()
.and_then(|time| time.duration_since(UNIX_EPOCH).ok())
.map(|dur| dur.as_secs())
.unwrap_or(0);
files.push((path, modified));
}
if files.len() <= AUTO_BACKUP_KEEP {
return Ok(());
}
files.sort_by_key(|(_, ts)| *ts);
let remove_count = files.len() - AUTO_BACKUP_KEEP;
for (path, _) in files.into_iter().take(remove_count) {
if let Err(err) = fs::remove_file(&path).await {
logging!(
warn,
Type::Backup,
"Failed to remove auto backup {}: {err:#?}",
path.display()
);
}
}
Ok(())
}
+1 -1
View File
@@ -3,7 +3,7 @@ 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, feat, module::lightweight::entry_lightweight_mode};
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};
+255
View File
@@ -0,0 +1,255 @@
use crate::{
config::Config,
core::{timer::Timer, tray::Tray},
process::AsyncHandler,
};
use clash_verge_logging::{Type, logging};
use crate::utils::window_manager::WindowManager;
use anyhow::Result;
use parking_lot::Mutex;
use std::sync::atomic::{AtomicU8, AtomicU32, Ordering};
use tauri::Listener as _;
use tokio::sync::oneshot;
use tokio::time::{Duration, sleep};
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LightweightState {
Normal = 0,
In = 1,
Exiting = 2,
}
impl From<u8> for LightweightState {
fn from(v: u8) -> Self {
match v {
1 => Self::In,
2 => Self::Exiting,
_ => Self::Normal,
}
}
}
impl LightweightState {
const fn as_u8(self) -> u8 {
self as u8
}
}
static LIGHTWEIGHT_STATE: AtomicU8 = AtomicU8::new(LightweightState::Normal as u8);
static WINDOW_CLOSE_HANDLER_ID: AtomicU32 = AtomicU32::new(0);
static WEBVIEW_FOCUS_HANDLER_ID: AtomicU32 = AtomicU32::new(0);
static CANCEL_TX: Mutex<Option<oneshot::Sender<()>>> = Mutex::new(None);
#[inline]
fn get_state() -> LightweightState {
LIGHTWEIGHT_STATE.load(Ordering::Acquire).into()
}
#[inline]
fn try_transition(from: LightweightState, to: LightweightState) -> bool {
LIGHTWEIGHT_STATE
.compare_exchange(from.as_u8(), to.as_u8(), Ordering::AcqRel, Ordering::Relaxed)
.is_ok()
}
#[inline]
fn record_state_and_log(state: LightweightState) {
LIGHTWEIGHT_STATE.store(state.as_u8(), Ordering::Release);
match state {
LightweightState::Normal => logging!(info, Type::Lightweight, "轻量模式已关闭"),
LightweightState::In => logging!(info, Type::Lightweight, "轻量模式已开启"),
LightweightState::Exiting => logging!(info, Type::Lightweight, "正在退出轻量模式"),
}
}
#[inline]
pub fn is_in_lightweight_mode() -> bool {
get_state() == LightweightState::In
}
async fn refresh_lightweight_tray_state() {
if let Err(err) = Tray::global().update_menu().await {
logging!(warn, Type::Lightweight, "更新托盘轻量模式状态失败: {err}");
}
}
pub async fn auto_lightweight_boot() -> Result<()> {
let verge_config = Config::verge().await;
let is_enable_auto = verge_config.data_arc().enable_auto_light_weight_mode.unwrap_or(false);
let is_silent_start = verge_config.data_arc().enable_silent_start.unwrap_or(false);
if is_enable_auto {
enable_auto_light_weight_mode().await;
}
if is_silent_start {
entry_lightweight_mode().await;
}
Ok(())
}
pub async fn enable_auto_light_weight_mode() {
if let Err(e) = Timer::global().init().await {
logging!(error, Type::Lightweight, "Failed to initialize timer: {e}");
return;
}
logging!(info, Type::Lightweight, "开启自动轻量模式");
setup_window_close_listener();
setup_webview_focus_listener();
}
pub fn disable_auto_light_weight_mode() {
logging!(info, Type::Lightweight, "关闭自动轻量模式");
cancel_light_weight_timer();
cancel_window_close_listener();
cancel_webview_focus_listener();
}
pub async fn entry_lightweight_mode() -> bool {
if !try_transition(LightweightState::Normal, LightweightState::In) {
logging!(debug, Type::Lightweight, "无需进入轻量模式,跳过调用");
refresh_lightweight_tray_state().await;
return false;
}
record_state_and_log(LightweightState::In);
WindowManager::destroy_main_window();
cancel_light_weight_timer();
refresh_lightweight_tray_state().await;
true
}
pub async fn exit_lightweight_mode() -> bool {
if !try_transition(LightweightState::In, LightweightState::Exiting) {
logging!(
debug,
Type::Lightweight,
"轻量模式不在退出条件(可能已退出或正在退出),跳过调用"
);
refresh_lightweight_tray_state().await;
return false;
}
record_state_and_log(LightweightState::Exiting);
WindowManager::show_main_window().await;
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 {
setup_window_close_listener();
setup_webview_focus_listener();
}
cancel_light_weight_timer();
record_state_and_log(LightweightState::Normal);
refresh_lightweight_tray_state().await;
true
}
#[cfg(target_os = "macos")]
pub async fn add_light_weight_timer() {
setup_light_weight_timer().await;
}
fn setup_window_close_listener() {
if let Some(window) = WindowManager::get_main_window() {
let previous_handler_id = WINDOW_CLOSE_HANDLER_ID.swap(0, Ordering::AcqRel);
if previous_handler_id != 0 {
window.unlisten(previous_handler_id);
logging!(debug, Type::Lightweight, "覆盖旧的窗口关闭监听");
}
let handler_id = window.listen("tauri://close-requested", move |_event| {
std::mem::drop(AsyncHandler::spawn(|| async {
setup_light_weight_timer().await;
}));
logging!(info, Type::Lightweight, "监听到关闭请求,开始轻量模式计时");
});
WINDOW_CLOSE_HANDLER_ID.store(handler_id, Ordering::Release);
}
}
fn cancel_window_close_listener() {
let id = WINDOW_CLOSE_HANDLER_ID.swap(0, Ordering::AcqRel);
if id != 0 {
if let Some(window) = WindowManager::get_main_window() {
window.unlisten(id);
}
logging!(debug, Type::Lightweight, "取消了窗口关闭监听");
}
}
fn setup_webview_focus_listener() {
if let Some(window) = WindowManager::get_main_window() {
let previous_handler_id = WEBVIEW_FOCUS_HANDLER_ID.swap(0, Ordering::AcqRel);
if previous_handler_id != 0 {
window.unlisten(previous_handler_id);
logging!(debug, Type::Lightweight, "覆盖旧的窗口焦点监听");
}
let handler_id = window.listen("tauri://focus", move |_event| {
cancel_light_weight_timer();
logging!(debug, Type::Lightweight, "监听到窗口获得焦点,取消轻量模式计时");
});
WEBVIEW_FOCUS_HANDLER_ID.store(handler_id, Ordering::Release);
}
}
fn cancel_webview_focus_listener() {
let id = WEBVIEW_FOCUS_HANDLER_ID.swap(0, Ordering::AcqRel);
if id != 0 {
if let Some(window) = WindowManager::get_main_window() {
window.unlisten(id);
}
logging!(debug, Type::Lightweight, "取消了窗口焦点监听");
}
}
async fn setup_light_weight_timer() {
let once_by_minutes = Config::verge().await.data_arc().auto_light_weight_minutes.unwrap_or(10);
let mut cancel_tx_guard = CANCEL_TX.lock();
if cancel_tx_guard.is_some() {
logging!(
debug,
Type::Timer,
"Lightweight mode timer already exists, skipping setup"
);
return;
}
let (tx, rx) = oneshot::channel::<()>();
*cancel_tx_guard = Some(tx);
drop(cancel_tx_guard);
AsyncHandler::spawn(move || async move {
tokio::select! {
_ = sleep(Duration::from_secs(once_by_minutes.saturating_mul(60))) => {
logging!(info, Type::Timer, "Lightweight mode timer expired, entering lightweight mode");
{
let mut guard = CANCEL_TX.lock();
*guard = None;
}
entry_lightweight_mode().await;
}
_ = rx => {
logging!(debug, Type::Timer, "Received cancel signal, stopping lightweight mode timer");
}
}
});
logging!(
info,
Type::Timer,
"Lightweight mode timer set, entering lightweight mode in {} minutes",
once_by_minutes
);
}
fn cancel_light_weight_timer() {
let mut cancel_tx_guard = CANCEL_TX.lock();
if let Some(tx) = cancel_tx_guard.take() {
let _ = tx.send(());
logging!(debug, Type::Timer, "Timer cancelled");
}
}
+3
View File
@@ -1,6 +1,9 @@
pub(crate) mod app_effects;
pub mod auto_backup;
pub mod autostart;
pub mod backup;
pub mod hotkey;
pub mod lightweight;
pub mod listener;
pub mod logger;
pub mod manager;
+2 -2
View File
@@ -1,14 +1,14 @@
use crate::config::{IProfilePreview, IVerge};
use crate::core::lightweight;
use crate::core::tray::menu_def::TrayAction;
use crate::module::lightweight;
use crate::process::AsyncHandler;
use crate::singleton;
use crate::utils::window_manager::WindowManager;
use crate::{
Type, cmd,
config::Config,
core::lightweight::is_in_lightweight_mode,
feat, logging,
module::lightweight::is_in_lightweight_mode,
utils::{dirs::find_target_icons, help},
};
use clash_verge_limiter::{Limiter, SystemClock, SystemLimiter};