mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-11-24 13:57:02 +00:00
feat(windows): no background refresh while nobody can see the tray
A locked session or sleeping displays kept the refresh loop spawning a Node process every two minutes for a figure nobody could look at. The mac stops on screensDidSleep and refreshes on didWake; this is the Windows half of that. The notifications need a window to be delivered to, so there is a hidden one on a thread of its own with its own message pump, in the shape of the dock's cursor thread. It registers for session change (lock and unlock), for the console display state, and for suspend and resume. A message-only window would not do here: WM_POWERBROADCAST is not delivered to one. The loop keeps its timer while the machine is unattended and skips the fetch, so the first tick after the screens come back finds fresh numbers even if a notification was never delivered. Waking, unlocking or the screens coming back refreshes at once, in every mode but Manual, as on the mac. An open popover clears a latched flag on its own, since it is proof the screens are on.
This commit is contained in:
parent
8bbdd1c7d2
commit
75b1d14423
6 changed files with 310 additions and 7 deletions
|
|
@ -28,7 +28,7 @@ reqwest = { version = "0.12", default-features = false, features = ["json", "rus
|
|||
fontdue = "0.9"
|
||||
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
windows-sys = { version = "0.59", features = ["Win32_Foundation", "Win32_Graphics_Dwm", "Win32_Security_Cryptography", "Win32_System_Com", "Win32_System_Power", "Win32_UI_Shell", "Win32_UI_Shell_Common", "Win32_System_StationsAndDesktops", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_WindowsAndMessaging"] }
|
||||
windows-sys = { version = "0.59", features = ["Win32_Foundation", "Win32_Graphics_Dwm", "Win32_Security_Cryptography", "Win32_System_Com", "Win32_System_Power", "Win32_System_RemoteDesktop", "Win32_System_SystemServices", "Win32_System_LibraryLoader", "Win32_UI_Shell", "Win32_UI_Shell_Common", "Win32_System_StationsAndDesktops", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_WindowsAndMessaging"] }
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
ksni = "0.3"
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ mod dock;
|
|||
mod fx;
|
||||
mod plan;
|
||||
mod refresh;
|
||||
mod session;
|
||||
mod settings;
|
||||
/// The spend-in-the-tray badge is a second tray icon, which only the Tauri tray backend
|
||||
/// provides; Linux runs its own SNI tray (`tray_linux`) and has no equivalent, so the
|
||||
|
|
@ -79,6 +80,10 @@ pub fn run() {
|
|||
#[cfg(all(debug_assertions, target_os = "windows"))]
|
||||
warn_if_window_station_hidden();
|
||||
|
||||
// Session lock, display sleep and wake, which the background refresh loop reads
|
||||
// before it spends a Node process nobody could see the result of.
|
||||
session::start(app.handle());
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
build_tray_tauri(app.handle())?;
|
||||
|
|
@ -586,6 +591,9 @@ fn show_popover(app: &AppHandle, anchor: Option<(i32, i32)>) {
|
|||
let _ = window.show();
|
||||
let _ = window.unminimize();
|
||||
position_popover(&window, anchor);
|
||||
// A popover on screen is proof the session is unlocked and the displays are on, so a
|
||||
// notification this process never received cannot latch the refresh loop off.
|
||||
session::note_attended();
|
||||
let _ = window.set_focus();
|
||||
let _ = window.emit("codeburn://shown", ());
|
||||
}
|
||||
|
|
|
|||
|
|
@ -89,25 +89,46 @@ pub fn power_state() -> PowerState {
|
|||
PowerState::default()
|
||||
}
|
||||
|
||||
/// What the page's refresh loop is told on every tick: how long to wait for the next one.
|
||||
/// What the page's refresh loop is told on every tick: how long to wait for the next one,
|
||||
/// and whether this one is worth spawning at all.
|
||||
#[derive(Clone, Copy, Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RefreshPlan {
|
||||
/// `null` in Manual mode, which stops the loop until the setting or the popover changes.
|
||||
pub interval_ms: Option<u64>,
|
||||
pub power: PowerState,
|
||||
/// True when this tick should re-arm the timer without fetching anything.
|
||||
pub skip: bool,
|
||||
/// Why, for the log and for nothing else.
|
||||
pub skip_reason: Option<&'static str>,
|
||||
}
|
||||
|
||||
pub fn plan(mode: i64, popover_open: bool) -> RefreshPlan {
|
||||
let power = power_state();
|
||||
// The timer keeps running while the machine is unattended: it costs nothing, and the
|
||||
// first tick after the screens come back then finds fresh numbers without waiting for a
|
||||
// notification that may never have been delivered.
|
||||
let skip_reason = if popover_open {
|
||||
None
|
||||
} else {
|
||||
crate::session::state().reason()
|
||||
};
|
||||
let plan = RefreshPlan {
|
||||
interval_ms: interval_secs(mode, popover_open, power).map(|secs| secs * 1000),
|
||||
power,
|
||||
skip: skip_reason.is_some(),
|
||||
skip_reason,
|
||||
};
|
||||
#[cfg(debug_assertions)]
|
||||
eprintln!(
|
||||
"codeburn: refresh plan mode={mode} popover={popover_open} battery={} saver={} interval={:?}",
|
||||
power.on_battery, power.battery_saver, plan.interval_ms
|
||||
"codeburn: refresh plan mode={mode} popover={popover_open} battery={} saver={} interval={:?} {}",
|
||||
power.on_battery,
|
||||
power.battery_saver,
|
||||
plan.interval_ms,
|
||||
match plan.skip_reason {
|
||||
Some(reason) => format!("skipped ({reason})"),
|
||||
None => "taken".to_string(),
|
||||
}
|
||||
);
|
||||
plan
|
||||
}
|
||||
|
|
|
|||
256
windows/src-tauri/src/session.rs
Normal file
256
windows/src-tauri/src/session.rs
Normal file
|
|
@ -0,0 +1,256 @@
|
|||
//! What the machine is doing to the screen: is the session locked, are the displays off,
|
||||
//! has it just woken. The Windows counterpart of the NSWorkspace observers in
|
||||
//! `mac/.../CodeBurnApp.swift` (`screensDidSleep`, `screensDidWake`, `didWake`).
|
||||
//!
|
||||
//! Nobody can see the tray while the session is locked or the displays are asleep, and a
|
||||
//! refresh there is a full Node process spent on nothing, so the background loop skips one.
|
||||
//! Coming back is the opposite case: the figure on screen is as old as the sleep was long,
|
||||
//! so a wake refreshes at once.
|
||||
//!
|
||||
//! The notifications need a window to be delivered to, so this owns a hidden one on a thread
|
||||
//! of its own with its own message pump, the same shape as the dock's cursor thread. A
|
||||
//! message-only window would not do: `WM_POWERBROADCAST` is not delivered to one.
|
||||
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use serde::Serialize;
|
||||
use tauri::AppHandle;
|
||||
|
||||
static LOCKED: AtomicBool = AtomicBool::new(false);
|
||||
static DISPLAY_OFF: AtomicBool = AtomicBool::new(false);
|
||||
static APP: std::sync::OnceLock<AppHandle> = std::sync::OnceLock::new();
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SystemState {
|
||||
pub locked: bool,
|
||||
pub display_off: bool,
|
||||
}
|
||||
|
||||
impl SystemState {
|
||||
/// True while nobody could see a refreshed figure even if one arrived.
|
||||
pub fn unattended(self) -> bool {
|
||||
self.locked || self.display_off
|
||||
}
|
||||
|
||||
pub fn reason(self) -> Option<&'static str> {
|
||||
if self.locked {
|
||||
Some("locked")
|
||||
} else if self.display_off {
|
||||
Some("displayOff")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn state() -> SystemState {
|
||||
SystemState {
|
||||
locked: LOCKED.load(Ordering::Relaxed),
|
||||
display_off: DISPLAY_OFF.load(Ordering::Relaxed),
|
||||
}
|
||||
}
|
||||
|
||||
/// An open popover proves the screens are on and the session is unlocked, so it clears a
|
||||
/// latched flag the same way the mac's `refreshPayloadForPopoverOpen` does. A missed
|
||||
/// notification must never be able to suppress refreshes forever.
|
||||
pub fn note_attended() {
|
||||
if state().unattended() {
|
||||
LOCKED.store(false, Ordering::Relaxed);
|
||||
DISPLAY_OFF.store(false, Ordering::Relaxed);
|
||||
publish(false);
|
||||
}
|
||||
}
|
||||
|
||||
fn publish(woke: bool) {
|
||||
let current = state();
|
||||
#[cfg(debug_assertions)]
|
||||
eprintln!(
|
||||
"codeburn: system state locked={} display_off={} woke={woke}",
|
||||
current.locked, current.display_off
|
||||
);
|
||||
let Some(app) = APP.get() else { return };
|
||||
use tauri::Emitter;
|
||||
let _ = app.emit("codeburn://system-state", current);
|
||||
if woke {
|
||||
let _ = app.emit("codeburn://wake", current);
|
||||
}
|
||||
}
|
||||
|
||||
fn set_locked(locked: bool) {
|
||||
if LOCKED.swap(locked, Ordering::Relaxed) == locked {
|
||||
return;
|
||||
}
|
||||
publish(!locked);
|
||||
}
|
||||
|
||||
fn set_display_off(off: bool) {
|
||||
if DISPLAY_OFF.swap(off, Ordering::Relaxed) == off {
|
||||
return;
|
||||
}
|
||||
publish(!off);
|
||||
}
|
||||
|
||||
pub fn start(app: &AppHandle) {
|
||||
let _ = APP.set(app.clone());
|
||||
#[cfg(target_os = "windows")]
|
||||
windows_impl::start();
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
mod windows_impl {
|
||||
use std::ptr::{null, null_mut};
|
||||
|
||||
use windows_sys::Win32::Foundation::{HWND, LPARAM, LRESULT, WPARAM};
|
||||
use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW;
|
||||
use windows_sys::Win32::System::Power::{
|
||||
RegisterPowerSettingNotification, RegisterSuspendResumeNotification, POWERBROADCAST_SETTING,
|
||||
};
|
||||
use windows_sys::Win32::System::RemoteDesktop::{
|
||||
WTSRegisterSessionNotification, NOTIFY_FOR_THIS_SESSION,
|
||||
};
|
||||
use windows_sys::Win32::System::SystemServices::GUID_CONSOLE_DISPLAY_STATE;
|
||||
use windows_sys::Win32::UI::WindowsAndMessaging::{
|
||||
CreateWindowExW, DefWindowProcW, DispatchMessageW, GetMessageW, RegisterClassW,
|
||||
TranslateMessage, DEVICE_NOTIFY_WINDOW_HANDLE, MSG, PBT_APMRESUMEAUTOMATIC,
|
||||
PBT_APMRESUMESUSPEND, PBT_POWERSETTINGCHANGE, WM_POWERBROADCAST, WM_WTSSESSION_CHANGE,
|
||||
WNDCLASSW, WS_OVERLAPPED, WTS_SESSION_LOCK, WTS_SESSION_UNLOCK,
|
||||
};
|
||||
|
||||
/// `GUID_CONSOLE_DISPLAY_STATE` payload: 0 off, 1 on, 2 dimmed. Dimmed is still visible.
|
||||
const DISPLAY_OFF: u8 = 0;
|
||||
|
||||
pub fn start() {
|
||||
let _ = std::thread::Builder::new()
|
||||
.name("codeburn-system".into())
|
||||
.spawn(run);
|
||||
}
|
||||
|
||||
fn run() {
|
||||
let class: Vec<u16> = "CodeBurnSystemWatcher\0".encode_utf16().collect();
|
||||
unsafe {
|
||||
let instance = GetModuleHandleW(null());
|
||||
let mut class_def: WNDCLASSW = std::mem::zeroed();
|
||||
class_def.lpfnWndProc = Some(wndproc);
|
||||
class_def.hInstance = instance;
|
||||
class_def.lpszClassName = class.as_ptr();
|
||||
if RegisterClassW(&class_def) == 0 {
|
||||
eprintln!("codeburn: could not register the system watcher window class");
|
||||
return;
|
||||
}
|
||||
// Never shown and never sized: the window exists only as the address the session
|
||||
// and power notifications are delivered to.
|
||||
let hwnd = CreateWindowExW(
|
||||
0,
|
||||
class.as_ptr(),
|
||||
class.as_ptr(),
|
||||
WS_OVERLAPPED,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
null_mut(),
|
||||
null_mut(),
|
||||
instance,
|
||||
null(),
|
||||
);
|
||||
if hwnd.is_null() {
|
||||
eprintln!("codeburn: could not create the system watcher window");
|
||||
return;
|
||||
}
|
||||
if WTSRegisterSessionNotification(hwnd, NOTIFY_FOR_THIS_SESSION) == 0 {
|
||||
eprintln!("codeburn: session lock notifications are unavailable");
|
||||
}
|
||||
// Display state covers the case system sleep does not: the screens go off on
|
||||
// their own timer while the machine keeps running.
|
||||
if RegisterPowerSettingNotification(
|
||||
hwnd,
|
||||
&GUID_CONSOLE_DISPLAY_STATE,
|
||||
DEVICE_NOTIFY_WINDOW_HANDLE,
|
||||
) == 0
|
||||
{
|
||||
eprintln!("codeburn: display state notifications are unavailable");
|
||||
}
|
||||
if RegisterSuspendResumeNotification(hwnd, DEVICE_NOTIFY_WINDOW_HANDLE) == 0 {
|
||||
eprintln!("codeburn: suspend and resume notifications are unavailable");
|
||||
}
|
||||
|
||||
let mut msg: MSG = std::mem::zeroed();
|
||||
while GetMessageW(&mut msg, null_mut(), 0, 0) > 0 {
|
||||
TranslateMessage(&msg);
|
||||
DispatchMessageW(&msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unsafe extern "system" fn wndproc(
|
||||
hwnd: HWND,
|
||||
message: u32,
|
||||
wparam: WPARAM,
|
||||
lparam: LPARAM,
|
||||
) -> LRESULT {
|
||||
match message {
|
||||
WM_WTSSESSION_CHANGE => match wparam as u32 {
|
||||
WTS_SESSION_LOCK => super::set_locked(true),
|
||||
WTS_SESSION_UNLOCK => super::set_locked(false),
|
||||
_ => {}
|
||||
},
|
||||
WM_POWERBROADCAST => {
|
||||
match wparam as u32 {
|
||||
PBT_POWERSETTINGCHANGE => {
|
||||
let setting = lparam as *const POWERBROADCAST_SETTING;
|
||||
if !setting.is_null()
|
||||
&& same_guid(&(*setting).PowerSetting, &GUID_CONSOLE_DISPLAY_STATE)
|
||||
&& (*setting).DataLength >= 1
|
||||
{
|
||||
super::set_display_off((*setting).Data[0] == DISPLAY_OFF);
|
||||
}
|
||||
}
|
||||
// Both resume messages can arrive for one wake; publishing is idempotent
|
||||
// and the page's own refresh is single-flighted.
|
||||
PBT_APMRESUMEAUTOMATIC | PBT_APMRESUMESUSPEND => {
|
||||
super::set_display_off(false);
|
||||
super::publish(true);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
DefWindowProcW(hwnd, message, wparam, lparam)
|
||||
}
|
||||
|
||||
fn same_guid(a: &windows_sys::core::GUID, b: &windows_sys::core::GUID) -> bool {
|
||||
a.data1 == b.data1 && a.data2 == b.data2 && a.data3 == b.data3 && a.data4 == b.data4
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn an_unattended_machine_names_the_reason_that_made_it_so() {
|
||||
let awake = SystemState {
|
||||
locked: false,
|
||||
display_off: false,
|
||||
};
|
||||
assert!(!awake.unattended());
|
||||
assert_eq!(awake.reason(), None);
|
||||
|
||||
let locked = SystemState {
|
||||
locked: true,
|
||||
display_off: false,
|
||||
};
|
||||
assert!(locked.unattended());
|
||||
assert_eq!(locked.reason(), Some("locked"));
|
||||
|
||||
let dark = SystemState {
|
||||
locked: false,
|
||||
display_off: true,
|
||||
};
|
||||
assert!(dark.unattended());
|
||||
assert_eq!(dark.reason(), Some("displayOff"));
|
||||
}
|
||||
}
|
||||
|
|
@ -145,6 +145,10 @@ export function App() {
|
|||
const selection = useRef(current)
|
||||
selection.current = current
|
||||
|
||||
// The wake listener is armed once and must still see the cadence as it stands then.
|
||||
const cadence = useRef(settings.usageRefreshSeconds)
|
||||
cadence.current = settings.usageRefreshSeconds
|
||||
|
||||
const menubarKey = menubarSelection(settings)
|
||||
const menubarRef = useRef(menubarKey)
|
||||
menubarRef.current = menubarKey
|
||||
|
|
@ -240,8 +244,10 @@ export function App() {
|
|||
// The background loop. Rust is asked on every tick how long to wait for the next one,
|
||||
// because the answer follows the machine: Auto is 30 s with the popover open, 120 s hidden,
|
||||
// and backs off on battery and further in battery saver, all of which can change under a
|
||||
// timer that has already been armed. Manual answers null and the loop stops; usage then
|
||||
// refreshes only when the popover opens or Refresh is pressed.
|
||||
// timer that has already been armed. The same answer says whether this tick is worth
|
||||
// spawning at all: a locked session or sleeping displays get the timer back and no CLI
|
||||
// run. Manual answers null and the loop stops; usage then refreshes only when the popover
|
||||
// opens, on wake, or when Refresh is pressed.
|
||||
useEffect(() => {
|
||||
if (!cliReady) return
|
||||
let stopped = false
|
||||
|
|
@ -254,7 +260,7 @@ export function App() {
|
|||
return
|
||||
}
|
||||
if (stopped) return
|
||||
if (refresh) {
|
||||
if (refresh && !plan.skip) {
|
||||
if (popoverVisible) refreshAll({ includeOptimize: true, showOverlay: false })
|
||||
// Hidden, the tray figure is the only thing anyone can see, so only its key is
|
||||
// refreshed and the optimize pass is skipped.
|
||||
|
|
@ -294,6 +300,13 @@ export function App() {
|
|||
}
|
||||
})
|
||||
const unlistenHidden = listen('codeburn://hidden', () => setPopoverVisible(false))
|
||||
// Waking, unlocking or the screens coming back: whatever is on the tray is as old as the
|
||||
// sleep was long. Manual is the one mode that stays silent, as it is on the mac, where
|
||||
// the wake path passes forcePayload only outside Manual.
|
||||
const unlistenWake = listen('codeburn://wake', () => {
|
||||
if (cadence.current === 0) return
|
||||
refreshAll({ includeOptimize: false, showOverlay: false })
|
||||
})
|
||||
const unlistenTheme = listen('codeburn://toggle-theme', () => toggleTheme())
|
||||
const unlistenBudget = listen<Budgets>('codeburn://budget-changed', event => {
|
||||
if (event.payload) setBudgets(event.payload)
|
||||
|
|
@ -305,6 +318,7 @@ export function App() {
|
|||
unlistenRefresh.then(fn => fn())
|
||||
unlistenShown.then(fn => fn())
|
||||
unlistenHidden.then(fn => fn())
|
||||
unlistenWake.then(fn => fn())
|
||||
unlistenTheme.then(fn => fn())
|
||||
unlistenBudget.then(fn => fn())
|
||||
unlistenCurrency.then(fn => fn())
|
||||
|
|
|
|||
|
|
@ -11,6 +11,10 @@ export type RefreshPlan = {
|
|||
/// `null` is Manual: nothing spawns on a timer, so the loop stops until the setting or the
|
||||
/// popover changes.
|
||||
intervalMs: number | null
|
||||
/// True when this tick should re-arm the timer and fetch nothing: the session is locked
|
||||
/// or the displays are off, so nobody could see the answer.
|
||||
skip: boolean
|
||||
skipReason: string | null
|
||||
power: { onBattery: boolean; batterySaver: boolean }
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue