1use std::cell::RefCell;
4use std::collections::HashMap;
5use std::future::poll_fn;
6use std::path::Path;
7use std::pin::Pin;
8use std::rc::Rc;
9use std::sync::Once;
10use std::task::Poll;
11use std::time::{Duration, Instant};
12
13use calloop::RegistrationToken;
14use calloop::timer::TimeoutAction;
15use crabshell_reactive::{ReadSignal, Signal};
16use crabshell_ui::Cx;
17use jiff::tz::TimeZone;
18use jiff::{SignedDuration, Timestamp, Zoned};
19use zbus::export::futures_core::Stream;
20use zbus::{MatchRule, Message, MessageStream};
21
22use crate::Shared;
23
24#[cfg(test)]
25mod tests;
26
27#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
29pub enum Precision {
30 Second,
32 Minute,
34 Day,
37}
38
39const WATCH_AFTER: Duration = if cfg!(test) {
43 Duration::from_millis(200)
44} else {
45 Duration::from_secs(1)
46};
47
48const EARLY: SignedDuration = SignedDuration::from_millis(50);
50
51pub(crate) struct Clocks {
53 shared: Rc<Shared>,
54 started: RefCell<Vec<Clock>>,
55}
56
57struct Clock {
58 precision: Precision,
59 signal: Signal<Zoned>,
60 timer: Option<RegistrationToken>,
62}
63
64pub(crate) fn clock(cx: &Cx, precision: Precision) -> ReadSignal<Zoned> {
66 if let Some(clocks) = cx.service::<Clocks>() {
67 return clocks.get(precision);
68 }
69 static LOGGED: Once = Once::new();
70 LOGGED.call_once(|| {
71 tracing::warn!("cx.clock() needs the services the shell provides; this clock stands still");
72 });
73 let zone = TimeZone::system();
74 let (shown, _) = boundaries(Timestamp::now(), precision, &zone);
75 cx.signal(shown.to_zoned(zone)).read_only()
76}
77
78impl Clocks {
79 pub(crate) fn new(shared: Rc<Shared>) -> Clocks {
80 Clocks {
81 shared,
82 started: RefCell::new(Vec::new()),
83 }
84 }
85
86 fn get(self: &Rc<Self>, precision: Precision) -> ReadSignal<Zoned> {
88 let started = self.started.borrow();
89 if let Some(clock) = started.iter().find(|clock| clock.precision == precision) {
90 return clock.signal.read_only();
91 }
92 let first = started.is_empty();
93 drop(started);
94 if first
95 && let Some(bus) = self.shared.config.system_bus.clone()
96 && let Some(event_loop) = self.shared.event_loop()
97 {
98 let clocks = Rc::clone(self);
99 let mut bus = Some(bus);
100 let later = Box::new(move || {
101 if let Some(bus) = bus.take() {
102 clocks.shared.spawn(watch(Rc::clone(&clocks), bus));
103 }
104 TimeoutAction::Drop
105 });
106 event_loop.insert_timer(Instant::now() + WATCH_AFTER, later);
107 }
108 let (shown, deadline) = current(precision, &self.zone());
109 let signal = self.shared.root.signal(shown);
110 let timer = self.timer(precision, deadline);
111 self.started.borrow_mut().push(Clock {
112 precision,
113 signal,
114 timer,
115 });
116 signal.read_only()
117 }
118
119 fn resync(self: &Rc<Self>) {
122 let zone = self.zone();
123 let Some(event_loop) = self.shared.event_loop() else {
124 return;
125 };
126 for clock in self.started.borrow_mut().iter_mut() {
127 let (shown, deadline) = current(clock.precision, &zone);
128 clock.signal.try_set(shown);
129 if let Some(old) = clock.timer.take() {
130 event_loop.remove(old);
131 }
132 clock.timer = self.timer(clock.precision, deadline);
133 }
134 }
135
136 fn on_message(self: &Rc<Self>, message: &Message) {
138 let body = message.body();
139 match message.header().member().map(|member| member.as_str()) {
140 Some("PrepareForSleep") => match body.deserialize::<bool>() {
141 Ok(true) => {}
142 Ok(false) => self.resync(),
143 Err(error) => tracing::warn!(%error, "a bad PrepareForSleep from logind"),
144 },
145 Some("PropertiesChanged") => {
146 match body.deserialize::<(&str, HashMap<&str, zbus::Variant<'_>>, Vec<&str>)>() {
147 Ok((_, changed, invalidated))
148 if changed.contains_key("Timezone") || invalidated.contains(&"Timezone") =>
149 {
150 tracing::info!(zone = self.zone().iana_name(), "the time zone changed");
151 self.resync();
152 }
153 Ok(_) => {}
154 Err(error) => tracing::warn!(%error, "a bad PropertiesChanged from timedated"),
155 }
156 }
157 _ => {}
158 }
159 }
160
161 fn timer(self: &Rc<Self>, precision: Precision, deadline: Instant) -> Option<RegistrationToken> {
164 let clocks = Rc::clone(self);
165 self
166 .shared
167 .event_loop()?
168 .insert_timer(deadline, Box::new(move || clocks.tick(precision)))
169 }
170
171 fn tick(&self, precision: Precision) -> TimeoutAction {
174 let (shown, deadline) = current(precision, &self.zone());
175 let started = self.started.borrow();
176 let clock = started.iter().find(|clock| clock.precision == precision);
177 match clock {
178 Some(clock) if clock.signal.try_set(shown) => TimeoutAction::ToInstant(deadline),
179 _ => TimeoutAction::Drop,
180 }
181 }
182
183 fn zone(&self) -> TimeZone {
186 system_zone(self.shared.config.localtime.as_deref())
187 }
188}
189
190async fn watch(clocks: Rc<Clocks>, bus: zbus::Address) {
193 let (mut sleep, mut zone) = match subscribe(bus).await {
194 Ok(streams) => streams,
195 Err(error) => {
196 tracing::info!(
197 %error,
198 "no system bus: the clock won't re-sync after a suspend or a time zone change"
199 );
200 return;
201 }
202 };
203 clocks.resync();
205 loop {
206 let next = poll_fn(|cx| match Pin::new(&mut sleep).poll_next(cx) {
207 Poll::Pending => Pin::new(&mut zone).poll_next(cx),
208 ready => ready,
209 });
210 match next.await {
211 Some(Ok(message)) => clocks.on_message(&message),
212 Some(Err(error)) => tracing::warn!(%error, "a bad message on the system bus"),
213 None => {
214 tracing::info!("the system bus closed: the clock no longer re-syncs");
215 return;
216 }
217 }
218 }
219}
220
221async fn subscribe(bus: zbus::Address) -> zbus::Result<(MessageStream, MessageStream)> {
226 let connection = zbus::connection::Builder::address(bus).build().await?;
227 let signal = || MatchRule::builder().msg_type(zbus::message::Type::Signal);
228 let sleep = signal()
229 .sender("org.freedesktop.login1")
230 .path("/org/freedesktop/login1")
231 .interface("org.freedesktop.login1.Manager")
232 .member("PrepareForSleep")
233 .build()?;
234 let zone = signal()
235 .sender("org.freedesktop.timedate1")
236 .path("/org/freedesktop/timedate1")
237 .interface("org.freedesktop.DBus.Properties")
238 .member("PropertiesChanged")
239 .arg(0, "org.freedesktop.timedate1")
240 .build()?;
241 Ok((
242 MessageStream::for_match_rule(sleep, &connection, None).await?,
243 MessageStream::for_match_rule(zone, &connection, None).await?,
244 ))
245}
246
247fn current(precision: Precision, zone: &TimeZone) -> (Zoned, Instant) {
250 let now = Timestamp::now();
251 let (shown, next) = boundaries(now, precision, zone);
252 let wait = Duration::try_from(next.duration_since(now)).unwrap_or_default();
253 (shown.to_zoned(zone.clone()), Instant::now() + wait)
255}
256
257fn boundaries(now: Timestamp, precision: Precision, zone: &TimeZone) -> (Timestamp, Timestamp) {
262 const RANGE: &str = "the system clock is within jiff's years -9999 to 9999";
263 let step = match precision {
264 Precision::Second => 1,
265 Precision::Minute => 60,
266 Precision::Day => {
267 let today = (now + EARLY).to_zoned(zone.clone());
268 let midnight = |day: &Zoned| day.start_of_day().expect(RANGE).timestamp();
269 return (midnight(&today), midnight(&today.tomorrow().expect(RANGE)));
270 }
271 };
272 let shown = (now + EARLY).as_second().div_euclid(step) * step;
273 let at = |second| Timestamp::from_second(second).expect(RANGE);
274 (at(shown), at(shown + step))
275}
276
277fn system_zone(localtime: Option<&Path>) -> TimeZone {
282 let target = localtime.and_then(|path| std::fs::read_link(path).ok());
283 let name = target
284 .as_deref()
285 .and_then(Path::to_str)
286 .and_then(|target| target.rsplit_once("zoneinfo/"))
287 .map(|(_, name)| name);
288 match name.map(|name| jiff::tz::db().get(name)) {
289 Some(Ok(zone)) => zone,
290 _ => TimeZone::system(),
291 }
292}