use crate::TopBar; use chrono::{Local, Timelike}; use slint::{ComponentHandle, SharedString, Timer, TimerMode}; use std::time::Duration; use super::common::run_cmd; // Format current time as "hh:mm AM" fn format_time() -> SharedString { SharedString::from(Local::now().format("%I:%M %p").to_string()) } // Start a 1-second timer that updates only when the minute changes fn start_clock_updater(ui: &TopBar) { let weak = ui.as_weak(); // Update immediately when the bar first appears 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())); 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 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); }