From 497288c58539d3c3e0db52c52d6feb24f7003df8 Mon Sep 17 00:00:00 2001 From: Candifloss Date: Thu, 20 Nov 2025 19:00:25 +0530 Subject: [PATCH] Update timer - Change time-updater from 1-minute timer to 1-second timer - More accuracy --- src/widgets/timewidget.rs | 37 +++++++++++++++---------------------- 1 file changed, 15 insertions(+), 22 deletions(-) diff --git a/src/widgets/timewidget.rs b/src/widgets/timewidget.rs index 141e5a2..27270e3 100644 --- a/src/widgets/timewidget.rs +++ b/src/widgets/timewidget.rs @@ -10,49 +10,42 @@ fn format_time() -> SharedString { SharedString::from(Local::now().format("%I:%M %p").to_string()) } -// Time until the next minute starts -fn time_until_next_minute() -> Duration { - let now = Local::now(); - let secs = now.second(); - let nanos = now.nanosecond(); - - Duration::from_secs(60 - u64::from(secs)) - Duration::from_nanos(u64::from(nanos)) -} - -// Create timers that update the time_text property every minute +// Start a 1-second timer that updates only when the minute changes fn start_clock_updater(ui: &TopBar) { let weak = ui.as_weak(); - let initial_timer = Box::leak(Box::new(Timer::default())); - let repeating_timer = Box::leak(Box::new(Timer::default())); - + // Update immediately when the bar first appears if let Some(ui) = weak.upgrade() { ui.set_time_text(format_time()); } - initial_timer.start(TimerMode::SingleShot, time_until_next_minute(), move || { - if let Some(ui) = weak.upgrade() { - ui.set_time_text(format_time()); - } + // Timer that ticks every second + let timer = Box::leak(Box::new(Timer::default())); - let weak_clone = weak.clone(); - repeating_timer.start(TimerMode::Repeated, Duration::from_secs(60), move || { - if let Some(ui) = weak_clone.upgrade() { + timer.start(TimerMode::Repeated, Duration::from_secs(1), move || { + // Access UI safely through the weak pointer + if let Some(ui) = weak.upgrade() { + let now = Local::now(); + + // Only update when the minute has rolled over + if now.second() == 0 { ui.set_time_text(format_time()); } - }); + } }); } -// Public entry for this widget +// Public entry point: connect widget events + start clock pub fn install(ui: &TopBar) { let weak = ui.as_weak(); + // When the widget emits show_clock(), run the program ui.on_show_clock(move || { if weak.upgrade().is_some() { run_cmd("xclock"); } }); + // Start the clock updater start_clock_updater(ui); }