feat: implement auto lightweight mode timer functionality

This commit implements the automatic lightweight mode feature with timer functionality:

- Rename configuration properties from auto_enter_lite_mode to enable_auto_light_weight_mode and auto_enter_lite_mode_delay to auto_light_weight_minutes for better clarity
- Add window event listeners to detect when window is closed or gets focus
- Implement timer system to automatically enter lightweight mode after configured time
- Remove exit_lightweight_mode function as it's no longer needed with the new implementation
- Update UI components to reflect the new property names
- Add logging for lightweight mode operations
- Initialize lightweight mode based on user configuration at startup

The feature now allows users to set a timer that will automatically enter lightweight mode
after closing the main window, which can be cancelled by focusing the window again.
This commit is contained in:
Tunglies 2025-03-20 06:01:38 +08:00
parent 33d54b27f4
commit 7fa1767645
9 changed files with 172 additions and 48 deletions

View File

@ -7,9 +7,3 @@ pub async fn entry_lightweight_mode() -> CmdResult {
lightweight::entry_lightweight_mode(); lightweight::entry_lightweight_mode();
Ok(()) Ok(())
} }
#[tauri::command]
pub async fn exit_lightweight_mode() -> CmdResult {
lightweight::exit_lightweight_mode();
Ok(())
}

View File

@ -190,10 +190,10 @@ pub struct IVerge {
pub enable_tray_speed: Option<bool>, pub enable_tray_speed: Option<bool>,
/// 自动进入轻量模式 /// 自动进入轻量模式
pub auto_enter_lite_mode: Option<bool>, pub enable_auto_light_weight_mode: Option<bool>,
/// 自动进入轻量模式的延迟(分钟) /// 自动进入轻量模式的延迟(分钟)
pub auto_enter_lite_mode_delay: Option<u16>, pub auto_light_weight_minutes: Option<u64>,
} }
#[derive(Default, Debug, Clone, Deserialize, Serialize)] #[derive(Default, Debug, Clone, Deserialize, Serialize)]
@ -296,8 +296,8 @@ impl IVerge {
webdav_password: None, webdav_password: None,
enable_tray_speed: Some(true), enable_tray_speed: Some(true),
enable_global_hotkey: Some(true), enable_global_hotkey: Some(true),
auto_enter_lite_mode: Some(false), enable_auto_light_weight_mode: Some(false),
auto_enter_lite_mode_delay: Some(10), auto_light_weight_minutes: Some(10),
enable_dns_settings: Some(true), enable_dns_settings: Some(true),
home_cards: None, home_cards: None,
..Self::default() ..Self::default()
@ -381,8 +381,8 @@ impl IVerge {
patch!(webdav_username); patch!(webdav_username);
patch!(webdav_password); patch!(webdav_password);
patch!(enable_tray_speed); patch!(enable_tray_speed);
patch!(auto_enter_lite_mode); patch!(enable_auto_light_weight_mode);
patch!(auto_enter_lite_mode_delay); patch!(auto_light_weight_minutes);
patch!(enable_dns_settings); patch!(enable_dns_settings);
patch!(home_cards); patch!(home_cards);
} }
@ -473,8 +473,8 @@ pub struct IVergeResponse {
pub webdav_username: Option<String>, pub webdav_username: Option<String>,
pub webdav_password: Option<String>, pub webdav_password: Option<String>,
pub enable_tray_speed: Option<bool>, pub enable_tray_speed: Option<bool>,
pub auto_enter_lite_mode: Option<bool>, pub enable_auto_light_weight_mode: Option<bool>,
pub auto_enter_lite_mode_delay: Option<u16>, pub auto_light_weight_minutes: Option<u64>,
pub enable_dns_settings: Option<bool>, pub enable_dns_settings: Option<bool>,
pub home_cards: Option<serde_json::Value>, pub home_cards: Option<serde_json::Value>,
} }
@ -539,8 +539,8 @@ impl From<IVerge> for IVergeResponse {
webdav_username: verge.webdav_username, webdav_username: verge.webdav_username,
webdav_password: verge.webdav_password, webdav_password: verge.webdav_password,
enable_tray_speed: verge.enable_tray_speed, enable_tray_speed: verge.enable_tray_speed,
auto_enter_lite_mode: verge.auto_enter_lite_mode, enable_auto_light_weight_mode: verge.enable_auto_light_weight_mode,
auto_enter_lite_mode_delay: verge.auto_enter_lite_mode_delay, auto_light_weight_minutes: verge.auto_light_weight_minutes,
enable_dns_settings: verge.enable_dns_settings, enable_dns_settings: verge.enable_dns_settings,
home_cards: verge.home_cards, home_cards: verge.home_cards,
} }

View File

@ -8,24 +8,25 @@ use std::{collections::HashMap, sync::Arc};
type TaskID = u64; type TaskID = u64;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
struct TimerTask { pub struct TimerTask {
task_id: TaskID, pub task_id: TaskID,
interval_minutes: u64, pub interval_minutes: u64,
__last_run: i64, // Timestamp of last execution #[allow(unused)]
pub last_run: i64, // Timestamp of last execution
} }
pub struct Timer { pub struct Timer {
/// cron manager /// cron manager
delay_timer: Arc<RwLock<DelayTimer>>, pub delay_timer: Arc<RwLock<DelayTimer>>,
/// save the current state - using RwLock for better read concurrency /// save the current state - using RwLock for better read concurrency
timer_map: Arc<RwLock<HashMap<String, TimerTask>>>, pub timer_map: Arc<RwLock<HashMap<String, TimerTask>>>,
/// increment id - kept as mutex since it's just a counter /// increment id - kept as mutex since it's just a counter
timer_count: Arc<Mutex<TaskID>>, pub timer_count: Arc<Mutex<TaskID>>,
/// Flag to mark if timer is initialized - atomic for better performance /// Flag to mark if timer is initialized - atomic for better performance
initialized: Arc<std::sync::atomic::AtomicBool>, pub initialized: Arc<std::sync::atomic::AtomicBool>,
} }
impl Timer { impl Timer {
@ -139,7 +140,7 @@ impl Timer {
let task = TimerTask { let task = TimerTask {
task_id: tid, task_id: tid,
interval_minutes: interval, interval_minutes: interval,
__last_run: chrono::Local::now().timestamp(), last_run: chrono::Local::now().timestamp(),
}; };
timer_map.insert(uid.clone(), task); timer_map.insert(uid.clone(), task);
@ -161,7 +162,7 @@ impl Timer {
let task = TimerTask { let task = TimerTask {
task_id: tid, task_id: tid,
interval_minutes: interval, interval_minutes: interval,
__last_run: chrono::Local::now().timestamp(), last_run: chrono::Local::now().timestamp(),
}; };
timer_map.insert(uid.clone(), task); timer_map.insert(uid.clone(), task);

View File

@ -2,6 +2,7 @@ use crate::{
config::{Config, IVerge}, config::{Config, IVerge},
core::{handle, hotkey, sysopt, tray, CoreManager}, core::{handle, hotkey, sysopt, tray, CoreManager},
log_err, log_err,
module::lightweight,
}; };
use anyhow::Result; use anyhow::Result;
use serde_yaml::Mapping; use serde_yaml::Mapping;
@ -53,6 +54,7 @@ enum UpdateFlags {
SystrayMenu = 1 << 7, SystrayMenu = 1 << 7,
SystrayTooltip = 1 << 8, SystrayTooltip = 1 << 8,
SystrayClickBehavior = 1 << 9, SystrayClickBehavior = 1 << 9,
LighteWeight = 1 << 10,
} }
/// Patch Verge configuration /// Patch Verge configuration
@ -90,7 +92,7 @@ pub async fn patch_verge(patch: IVerge, not_save_file: bool) -> Result<()> {
let enable_global_hotkey = patch.enable_global_hotkey; let enable_global_hotkey = patch.enable_global_hotkey;
let tray_event = patch.tray_event; let tray_event = patch.tray_event;
let home_cards = patch.home_cards.clone(); let home_cards = patch.home_cards.clone();
let enable_auto_light_weight = patch.enable_auto_light_weight_mode;
let res: std::result::Result<(), anyhow::Error> = { let res: std::result::Result<(), anyhow::Error> = {
// Initialize with no flags set // Initialize with no flags set
let mut update_flags: i32 = UpdateFlags::None as i32; let mut update_flags: i32 = UpdateFlags::None as i32;
@ -156,6 +158,10 @@ pub async fn patch_verge(patch: IVerge, not_save_file: bool) -> Result<()> {
update_flags |= UpdateFlags::SystrayClickBehavior as i32; update_flags |= UpdateFlags::SystrayClickBehavior as i32;
} }
if enable_auto_light_weight.is_some() {
update_flags |= UpdateFlags::LighteWeight as i32;
}
// Process updates based on flags // Process updates based on flags
if (update_flags & (UpdateFlags::RestartCore as i32)) != 0 { if (update_flags & (UpdateFlags::RestartCore as i32)) != 0 {
CoreManager::global().restart_core().await?; CoreManager::global().restart_core().await?;
@ -189,6 +195,13 @@ pub async fn patch_verge(patch: IVerge, not_save_file: bool) -> Result<()> {
if (update_flags & (UpdateFlags::SystrayClickBehavior as i32)) != 0 { if (update_flags & (UpdateFlags::SystrayClickBehavior as i32)) != 0 {
tray::Tray::global().update_click_behavior()?; tray::Tray::global().update_click_behavior()?;
} }
if (update_flags & (UpdateFlags::LighteWeight as i32)) != 0 {
if enable_auto_light_weight.unwrap() {
lightweight::enable_auto_light_weight_mode();
} else {
lightweight::disable_auto_light_weight_mode();
}
}
<Result<()>>::Ok(()) <Result<()>>::Ok(())
}; };

View File

@ -217,7 +217,6 @@ pub fn run() {
cmd::check_media_unlock, cmd::check_media_unlock,
// light-weight model // light-weight model
cmd::entry_lightweight_mode, cmd::entry_lightweight_mode,
cmd::exit_lightweight_mode,
]); ]);
#[cfg(debug_assertions)] #[cfg(debug_assertions)]

View File

@ -1,12 +1,31 @@
use tauri::Manager; use anyhow::{Context, Result};
use delay_timer::prelude::TaskBuilder;
use tauri::{Listener, Manager};
use crate::{core::handle, log_err, utils::resolve}; use crate::{
config::Config,
core::{handle, timer::Timer},
log_err,
};
const LIGHT_WEIGHT_TASK_UID: &str = "light_weight_task";
pub fn enable_auto_light_weight_mode() {
println!("[lightweight_mode] 开启自动轻量模式");
log::info!(target: "app", "[lightweight_mode] 开启自动轻量模式");
setup_window_close_listener();
setup_webview_focus_listener();
}
pub fn disable_auto_light_weight_mode() {
println!("[lightweight_mode] 关闭自动轻量模式");
log::info!(target: "app", "[lightweight_mode] 关闭自动轻量模式");
let _ = cancel_light_weight_timer();
cancel_window_close_listener();
}
pub fn entry_lightweight_mode() { pub fn entry_lightweight_mode() {
println!("entry_lightweight_mode"); println!("尝试进入轻量模式。motherfucker");
log::debug!(target: "app", "entry_lightweight_mode");
if let Some(window) = handle::Handle::global().get_window() { if let Some(window) = handle::Handle::global().get_window() {
log_err!(window.close()); log_err!(window.close());
} }
@ -14,12 +33,109 @@ pub fn entry_lightweight_mode() {
if let Some(window) = handle::Handle::global().get_window() { if let Some(window) = handle::Handle::global().get_window() {
if let Some(webview) = window.get_webview_window("main") { if let Some(webview) = window.get_webview_window("main") {
log_err!(webview.destroy()); log_err!(webview.destroy());
println!("[lightweight_mode] 轻量模式已开启");
log::info!(target: "app", "[lightweight_mode] 轻量模式已开启");
} }
} }
} }
pub fn exit_lightweight_mode() { fn setup_window_close_listener() -> u32 {
println!("exit_lightweight_mode"); if let Some(window) = handle::Handle::global().get_window() {
log::debug!(target: "app", "exit_lightweight_mode"); let handler = window.listen("tauri://close-requested", move |_event| {
resolve::create_window(); let _ = setup_light_weight_timer();
println!("[lightweight_mode] 监听到关闭请求,开始轻量模式计时");
log::info!(target: "app", "[lightweight_mode] 监听到关闭请求,开始轻量模式计时");
});
return handler;
}
0
}
fn setup_webview_focus_listener() -> u32 {
if let Some(window) = handle::Handle::global().get_window() {
let handler = window.listen("tauri://focus", move |_event| {
log_err!(cancel_light_weight_timer());
println!("[lightweight_mode] 监听到窗口获得焦点,取消轻量模式计时");
log::info!(target: "app", "[lightweight_mode] 监听到窗口获得焦点,取消轻量模式计时");
});
return handler;
}
0
}
fn cancel_window_close_listener() {
if let Some(window) = handle::Handle::global().get_window() {
window.unlisten(setup_window_close_listener());
println!("[lightweight_mode] 取消了窗口关闭监听");
log::info!(target: "app", "[lightweight_mode] 取消了窗口关闭监听");
}
}
fn setup_light_weight_timer() -> Result<()> {
Timer::global().init()?;
let mut timer_map = Timer::global().timer_map.write();
let delay_timer = Timer::global().delay_timer.write();
let mut timer_count = Timer::global().timer_count.lock();
let task_id = *timer_count;
*timer_count += 1;
let once_by_minutes = Config::verge()
.latest()
.auto_light_weight_minutes
.clone()
.unwrap_or(10);
let task = TaskBuilder::default()
.set_task_id(task_id)
.set_maximum_parallel_runnable_num(1)
.set_frequency_once_by_minutes(once_by_minutes)
.spawn_async_routine(move || async move {
println!("[lightweight_mode] 计时器到期,开始进入轻量模式");
log::info!(target: "app",
"[lightweight_mode] 计时器到期,开始进入轻量模式"
);
entry_lightweight_mode();
})
.context("failed to create light weight timer task")?;
delay_timer
.add_task(task)
.context("failed to add light weight timer task")?;
let timer_task = crate::core::timer::TimerTask {
task_id,
interval_minutes: once_by_minutes,
last_run: chrono::Local::now().timestamp(),
};
timer_map.insert(LIGHT_WEIGHT_TASK_UID.to_string(), timer_task);
println!(
"[lightweight_mode] 轻量模式计时器已设置,{} 分钟后将自动进入轻量模式",
once_by_minutes
);
log::info!(target: "app",
"[lightweight_mode] 轻量模式计时器已设置,{} 分钟后将自动进入轻量模式",
once_by_minutes
);
Ok(())
}
fn cancel_light_weight_timer() -> Result<()> {
let mut timer_map = Timer::global().timer_map.write();
let delay_timer = Timer::global().delay_timer.write();
if let Some(task) = timer_map.remove(LIGHT_WEIGHT_TASK_UID) {
delay_timer
.remove_task(task.task_id)
.context("failed to remove light weight timer task")?;
}
println!("[lightweight_mode] 轻量模式计时器已取消");
log::info!(target: "app", "[lightweight_mode] 轻量模式计时器已取消");
Ok(())
} }

View File

@ -1,11 +1,7 @@
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
use crate::AppHandleManager; use crate::AppHandleManager;
use crate::{ use crate::{
config::{Config, IVerge, PrfItem}, config::{Config, IVerge, PrfItem}, core::*, log_err, module::lightweight, utils::{error, init, server}, wrap_err
core::*,
log_err,
utils::{error, init, server},
wrap_err,
}; };
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use once_cell::sync::OnceCell; use once_cell::sync::OnceCell;
@ -115,6 +111,11 @@ pub async fn resolve_setup(app: &mut App) {
log_err!(tray::Tray::global().update_part()); log_err!(tray::Tray::global().update_part());
log_err!(timer::Timer::global().init()); log_err!(timer::Timer::global().init());
let enable_auto_light_weight_mode = { Config::verge().data().enable_auto_light_weight_mode };
if enable_auto_light_weight_mode.unwrap_or(false) {
lightweight::enable_auto_light_weight_mode();
}
} }
/// reset system proxy /// reset system proxy

View File

@ -28,8 +28,8 @@ export const LiteModeViewer = forwardRef<DialogRef>((props, ref) => {
open: () => { open: () => {
setOpen(true); setOpen(true);
setValues({ setValues({
autoEnterLiteMode: verge?.auto_enter_lite_mode ?? false, autoEnterLiteMode: verge?.enable_auto_light_weight_mode ?? false,
autoEnterLiteModeDelay: verge?.auto_enter_lite_mode_delay ?? 10, autoEnterLiteModeDelay: verge?.auto_light_weight_minutes ?? 10,
}); });
}, },
close: () => setOpen(false), close: () => setOpen(false),
@ -38,8 +38,8 @@ export const LiteModeViewer = forwardRef<DialogRef>((props, ref) => {
const onSave = useLockFn(async () => { const onSave = useLockFn(async () => {
try { try {
await patchVerge({ await patchVerge({
auto_enter_lite_mode: values.autoEnterLiteMode, enable_auto_light_weight_mode: values.autoEnterLiteMode,
auto_enter_lite_mode_delay: values.autoEnterLiteModeDelay, auto_light_weight_minutes: values.autoEnterLiteModeDelay,
}); });
setOpen(false); setOpen(false);
} catch (err: any) { } catch (err: any) {

View File

@ -739,8 +739,8 @@ interface IVergeConfig {
tun_tray_icon?: boolean; tun_tray_icon?: boolean;
enable_tray_speed?: boolean; enable_tray_speed?: boolean;
enable_tun_mode?: boolean; enable_tun_mode?: boolean;
auto_enter_lite_mode?: boolean; enable_auto_light_weight_mode?: boolean;
auto_enter_lite_mode_delay?: number; auto_light_weight_minutes?: number;
enable_auto_launch?: boolean; enable_auto_launch?: boolean;
enable_silent_start?: boolean; enable_silent_start?: boolean;
enable_system_proxy?: boolean; enable_system_proxy?: boolean;