Skip to main content

compose_rust/
time.rs

1//! Today's date and the time of day, in the user's time zone.
2//!
3//! The Host reads them itself, so nothing about them crosses the boundary. On desktop, iOS
4//! and Android the C library converts an instant with the time zone the operating system
5//! is set to; a `TZ` in the environment wins, as it does for every program on those
6//! systems. In a browser the page's `Date` answers, which is the browser's time zone.
7//!
8//! [`subscribe_date_change`] wakes a reader once when the date changes: at local midnight,
9//! or when the user moves to a time zone where it is already another day.
10
11use std::sync::Arc;
12use std::time::{Duration, SystemTime, UNIX_EPOCH};
13
14/// A day of the week.
15#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
16pub enum Weekday {
17    Monday,
18    Tuesday,
19    Wednesday,
20    Thursday,
21    Friday,
22    Saturday,
23    Sunday,
24}
25
26impl Weekday {
27    /// The day `days` days after 1970-01-01, which was a Thursday. Negative goes back.
28    fn from_days_since_epoch(days: i64) -> Self {
29        // Monday is 0 here, so the epoch's Thursday is 3.
30        match (days + 3).rem_euclid(7) {
31            0 => Weekday::Monday,
32            1 => Weekday::Tuesday,
33            2 => Weekday::Wednesday,
34            3 => Weekday::Thursday,
35            4 => Weekday::Friday,
36            5 => Weekday::Saturday,
37            _ => Weekday::Sunday,
38        }
39    }
40
41    /// One for Monday up to seven for Sunday, as ISO 8601 numbers them.
42    pub fn number_from_monday(self) -> u8 {
43        self as u8 + 1
44    }
45}
46
47/// A date on the calendar of the user's time zone.
48#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
49pub struct LocalDate {
50    pub year: i32,
51    /// One for January up to twelve.
52    pub month: u8,
53    /// One up to the last day of the month.
54    pub day: u8,
55    pub weekday: Weekday,
56}
57
58impl LocalDate {
59    /// The date of the day `days` days after 1970-01-01.
60    fn from_days_since_epoch(days: i64) -> Self {
61        // Howard Hinnant's civil_from_days: the proleptic Gregorian calendar, with years
62        // counted from March so that the leap day is the last day of a year.
63        let z = days + 719_468;
64        let era = z.div_euclid(146_097);
65        let day_of_era = z.rem_euclid(146_097);
66        let year_of_era =
67            (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
68        let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
69        let shifted_month = (5 * day_of_year + 2) / 153;
70        let day = day_of_year - (153 * shifted_month + 2) / 5 + 1;
71        let month = if shifted_month < 10 {
72            shifted_month + 3
73        } else {
74            shifted_month - 9
75        };
76        let year = year_of_era + era * 400 + i64::from(month <= 2);
77        LocalDate {
78            year: year as i32,
79            month: month as u8,
80            day: day as u8,
81            weekday: Weekday::from_days_since_epoch(days),
82        }
83    }
84
85    /// How many days after 1970-01-01 this date is. Negative for a date before it.
86    pub fn days_since_epoch(&self) -> i64 {
87        let month = i64::from(self.month);
88        let year = i64::from(self.year) - i64::from(month <= 2);
89        let era = year.div_euclid(400);
90        let year_of_era = year.rem_euclid(400);
91        let shifted_month = if month > 2 { month - 3 } else { month + 9 };
92        let day_of_year = (153 * shifted_month + 2) / 5 + i64::from(self.day) - 1;
93        let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
94        era * 146_097 + day_of_era - 719_468
95    }
96}
97
98/// A moment as the clock on the user's wall shows it.
99#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
100pub struct LocalDateTime {
101    pub date: LocalDate,
102    /// Zero up to 23.
103    pub hour: u8,
104    pub minute: u8,
105    /// Zero up to 59, or 60 in a leap second where the platform reports one.
106    pub second: u8,
107    pub nanosecond: u32,
108    /// How far ahead of UTC the user's time zone is at this moment, daylight saving
109    /// included. Negative west of Greenwich.
110    pub utc_offset_seconds: i32,
111}
112
113/// Today's date in the user's time zone.
114pub fn today() -> LocalDate {
115    now_local().date
116}
117
118/// The current date and time of day in the user's time zone.
119pub fn now_local() -> LocalDateTime {
120    local_at(platform::now())
121}
122
123/// What the wall clock in the user's time zone showed, or will show, at `instant`.
124pub fn local_at(instant: SystemTime) -> LocalDateTime {
125    let (seconds, nanosecond) = match instant.duration_since(UNIX_EPOCH) {
126        Ok(after) => (after.as_secs() as i64, after.subsec_nanos()),
127        Err(before) => {
128            let before = before.duration();
129            let whole = before.as_secs() as i64;
130            match before.subsec_nanos() {
131                0 => (-whole, 0),
132                part => (-whole - 1, 1_000_000_000 - part),
133            }
134        }
135    };
136    let offset = platform::utc_offset_seconds(seconds);
137    let local = seconds + i64::from(offset);
138    let days = local.div_euclid(86_400);
139    let second_of_day = local.rem_euclid(86_400);
140    LocalDateTime {
141        date: LocalDate::from_days_since_epoch(days),
142        hour: (second_of_day / 3600) as u8,
143        minute: (second_of_day / 60 % 60) as u8,
144        second: (second_of_day % 60) as u8,
145        nanosecond,
146        utc_offset_seconds: offset,
147    }
148}
149
150/// How long from `now` until the next local midnight, as `now`'s offset counts it.
151fn until_midnight(now: &LocalDateTime) -> Duration {
152    let into_day = u64::from(now.hour) * 3600 + u64::from(now.minute) * 60 + u64::from(now.second);
153    let left = 86_400u64.saturating_sub(into_day).max(1);
154    Duration::from_secs(left).saturating_sub(Duration::from_nanos(u64::from(now.nanosecond)))
155}
156
157/// The longest the date goes unchecked. A time zone the user changes, or a daylight saving
158/// change that moves midnight, is noticed within this.
159const LONGEST_WAIT: Duration = Duration::from_secs(60);
160
161/// A little past midnight, so the check that follows it is on the new date.
162const PAST_MIDNIGHT: Duration = Duration::from_millis(20);
163
164/// A registration for date changes. Dropping it ends the registration.
165pub struct DateChangeSubscription {
166    id: u64,
167}
168
169impl Drop for DateChangeSubscription {
170    fn drop(&mut self) {
171        watch::remove(self.id);
172    }
173}
174
175/// Registers `notify` to be called once each time the date in the user's time zone
176/// changes: when local midnight passes, or when the user moves to a time zone where it is
177/// another day. Called on a Host worker thread, or in a browser at the start of a frame,
178/// so it does what any worker does with a change: update a signal, which asks for a frame.
179pub fn subscribe_date_change(notify: Arc<dyn Fn() + Send + Sync>) -> DateChangeSubscription {
180    DateChangeSubscription {
181        id: watch::add(notify),
182    }
183}
184
185/// The subscribers and the date they last heard of, shared by every platform.
186mod watch {
187    use super::{LocalDate, today};
188    use std::sync::{Arc, Mutex, MutexGuard};
189
190    pub(super) type Notify = Arc<dyn Fn() + Send + Sync>;
191
192    pub(super) struct Watch {
193        pub(super) subscribers: Vec<(u64, Notify)>,
194        pub(super) next_id: u64,
195        /// The date the subscribers were last told of, or found on subscribing.
196        pub(super) seen: Option<LocalDate>,
197        /// Whether something is already waiting to check the date again.
198        pub(super) armed: bool,
199    }
200
201    pub(super) static WATCH: Mutex<Watch> = Mutex::new(Watch {
202        subscribers: Vec::new(),
203        next_id: 1,
204        seen: None,
205        armed: false,
206    });
207
208    pub(super) fn lock() -> MutexGuard<'static, Watch> {
209        WATCH.lock().unwrap_or_else(|poison| poison.into_inner())
210    }
211
212    pub(super) fn add(notify: Notify) -> u64 {
213        let mut watch = lock();
214        let id = watch.next_id;
215        watch.next_id += 1;
216        // The date the first subscriber starts from is read now, on the caller's thread,
217        // so a midnight that passes before anything waits is still a change.
218        if watch.subscribers.is_empty() {
219            watch.seen = Some(today());
220        }
221        watch.subscribers.push((id, notify));
222        if !watch.armed {
223            watch.armed = true;
224            super::platform::arm();
225        }
226        drop(watch);
227        super::platform::changed();
228        id
229    }
230
231    pub(super) fn remove(id: u64) {
232        let mut watch = lock();
233        watch
234            .subscribers
235            .retain(|(subscriber, _)| *subscriber != id);
236        drop(watch);
237        super::platform::changed();
238    }
239
240    /// Reads the date, and calls every subscriber once if it is not the one they last
241    /// heard of. The calls are made with nothing held, so a subscriber may subscribe or
242    /// drop a subscription from inside one.
243    pub(super) fn check() {
244        let now = today();
245        let woken: Vec<Notify> = {
246            let mut watch = lock();
247            if watch.seen == Some(now) {
248                return;
249            }
250            watch.seen = Some(now);
251            watch
252                .subscribers
253                .iter()
254                .map(|(_, notify)| notify.clone())
255                .collect()
256        };
257        for notify in woken {
258            notify();
259        }
260    }
261}
262
263#[cfg(not(target_family = "wasm"))]
264mod platform {
265    use super::{LONGEST_WAIT, PAST_MIDNIGHT, now_local, until_midnight, watch};
266    use std::sync::Condvar;
267    use std::time::SystemTime;
268
269    pub(super) fn now() -> SystemTime {
270        SystemTime::now()
271    }
272
273    /// Wakes the watching thread early: a subscriber came or went.
274    static CHANGED: Condvar = Condvar::new();
275
276    pub(super) fn changed() {
277        CHANGED.notify_all();
278    }
279
280    /// Starts the thread that checks the date at each local midnight, and at least once a
281    /// minute between them. It ends when the last subscriber has gone.
282    pub(super) fn arm() {
283        let started = std::thread::Builder::new()
284            .name("compose-rust-date".to_owned())
285            .spawn(run);
286        if started.is_err() {
287            // Without a thread there is nothing to wake anyone; the next subscriber tries
288            // again rather than finding it armed.
289            watch::lock().armed = false;
290        }
291    }
292
293    fn run() {
294        loop {
295            let wait = until_midnight(&now_local()).min(LONGEST_WAIT) + PAST_MIDNIGHT;
296            let mut watch = watch::lock();
297            if !watch.subscribers.is_empty() {
298                watch = CHANGED
299                    .wait_timeout(watch, wait)
300                    .unwrap_or_else(|poison| poison.into_inner())
301                    .0;
302            }
303            if watch.subscribers.is_empty() {
304                watch.armed = false;
305                return;
306            }
307            drop(watch);
308            watch::check();
309        }
310    }
311
312    #[cfg(unix)]
313    pub(super) fn utc_offset_seconds(seconds: i64) -> i32 {
314        use std::ffi::{c_char, c_int, c_long};
315
316        // `struct tm` as glibc, musl, bionic and Apple's libc lay it out: nine ints, then
317        // the offset from UTC and the zone's abbreviation, which all four have.
318        #[repr(C)]
319        struct Tm {
320            tm_sec: c_int,
321            tm_min: c_int,
322            tm_hour: c_int,
323            tm_mday: c_int,
324            tm_mon: c_int,
325            tm_year: c_int,
326            tm_wday: c_int,
327            tm_yday: c_int,
328            tm_isdst: c_int,
329            tm_gmtoff: c_long,
330            tm_zone: *const c_char,
331        }
332
333        unsafe extern "C" {
334            fn tzset();
335            fn localtime_r(time: *const c_long, result: *mut Tm) -> *mut Tm;
336        }
337
338        let Some(time) = c_long::try_from(seconds).ok() else {
339            return 0;
340        };
341        let mut tm = Tm {
342            tm_sec: 0,
343            tm_min: 0,
344            tm_hour: 0,
345            tm_mday: 0,
346            tm_mon: 0,
347            tm_year: 0,
348            tm_wday: 0,
349            tm_yday: 0,
350            tm_isdst: 0,
351            tm_gmtoff: 0,
352            tm_zone: std::ptr::null(),
353        };
354        // `localtime_r` need not look at the time zone again, and a user who changed it
355        // expects the next read to show it, so it is read again every time.
356        // SAFETY: both pointers are to locals that outlive the call, and `tm` has the
357        // layout this platform's libc writes.
358        let converted = unsafe {
359            tzset();
360            localtime_r(&time, &mut tm)
361        };
362        if converted.is_null() {
363            return 0;
364        }
365        tm.tm_gmtoff as i32
366    }
367
368    #[cfg(windows)]
369    pub(super) fn utc_offset_seconds(seconds: i64) -> i32 {
370        use std::ffi::{CString, c_char, c_int};
371        use std::sync::Mutex;
372
373        // The C runtime's `struct tm`: nine ints and nothing after them.
374        #[repr(C)]
375        #[derive(Default)]
376        struct Tm {
377            tm_sec: c_int,
378            tm_min: c_int,
379            tm_hour: c_int,
380            tm_mday: c_int,
381            tm_mon: c_int,
382            tm_year: c_int,
383            tm_wday: c_int,
384            tm_yday: c_int,
385            tm_isdst: c_int,
386        }
387
388        unsafe extern "C" {
389            fn _tzset();
390            fn _putenv_s(name: *const c_char, value: *const c_char) -> c_int;
391            fn _localtime64_s(result: *mut Tm, time: *const i64) -> c_int;
392        }
393
394        // The C runtime keeps its own copy of the environment, which a `TZ` set through
395        // the process's environment does not reach. It is copied across when it changed,
396        // so `TZ` wins here as it does on every other desktop.
397        static SYNCED: Mutex<Option<String>> = Mutex::new(None);
398        let wanted = std::env::var("TZ").ok();
399        {
400            let mut synced = SYNCED.lock().unwrap_or_else(|poison| poison.into_inner());
401            if *synced != wanted {
402                if let Ok(value) = CString::new(wanted.clone().unwrap_or_default()) {
403                    // SAFETY: both are NUL-terminated strings that outlive the call.
404                    unsafe { _putenv_s(c"TZ".as_ptr(), value.as_ptr()) };
405                }
406                *synced = wanted;
407            }
408        }
409        let mut tm = Tm::default();
410        // SAFETY: both pointers are to locals that outlive the call.
411        let failed = unsafe {
412            _tzset();
413            _localtime64_s(&mut tm, &seconds)
414        };
415        if failed != 0 {
416            return 0;
417        }
418        // The runtime reports the fields and not the offset, so the offset is how far the
419        // wall clock it reports is from the instant read as UTC.
420        let date = super::LocalDate {
421            year: tm.tm_year + 1900,
422            month: (tm.tm_mon + 1) as u8,
423            day: tm.tm_mday as u8,
424            weekday: super::Weekday::Monday,
425        };
426        let wall = date.days_since_epoch() * 86_400
427            + i64::from(tm.tm_hour) * 3600
428            + i64::from(tm.tm_min) * 60
429            + i64::from(tm.tm_sec);
430        (wall - seconds) as i32
431    }
432}
433
434#[cfg(target_family = "wasm")]
435mod platform {
436    use super::{PAST_MIDNIGHT, now_local, until_midnight, watch};
437    use std::cell::Cell;
438    use std::time::{Duration, SystemTime, UNIX_EPOCH};
439
440    // The page answers these from `Date`; the generated instantiation of the Host supplies
441    // them. They are not boundary calls: nothing goes to the Renderer through them.
442    #[link(wasm_import_module = "compose_rust_time")]
443    unsafe extern "C" {
444        /// `Date.now()`: milliseconds since 1970 in UTC.
445        fn now_millis() -> f64;
446        /// How many minutes the browser's time zone is ahead of UTC at that instant.
447        fn utc_offset_minutes(millis: f64) -> i32;
448        /// Asks the Renderer for a frame after `millis`, from a browser timer, so the date
449        /// is checked then without a frame drawn in every moment between.
450        fn wake_after(millis: f64);
451    }
452
453    pub(super) fn now() -> SystemTime {
454        // SAFETY: an import the page supplies with no arguments.
455        let millis = unsafe { now_millis() };
456        UNIX_EPOCH + Duration::from_millis(millis.max(0.0) as u64)
457    }
458
459    pub(super) fn utc_offset_seconds(seconds: i64) -> i32 {
460        // SAFETY: an import the page supplies, given a number.
461        unsafe { utc_offset_minutes(seconds as f64 * 1000.0) * 60 }
462    }
463
464    pub(super) fn changed() {}
465
466    thread_local! {
467        /// When the next check is due, in `Date.now()` milliseconds. A frame before then,
468        /// and an animation draws many, checks nothing and sets no timer.
469        static DUE: Cell<f64> = const { Cell::new(0.0) };
470    }
471
472    pub(super) fn arm() {
473        schedule();
474    }
475
476    fn schedule() {
477        // A browser has no thread to wait on, so the timer is the browser's, and what it
478        // wakes is a frame, at whose start the date is checked.
479        let wait = (until_midnight(&now_local()).min(super::LONGEST_WAIT) + PAST_MIDNIGHT)
480            .as_millis() as f64;
481        // SAFETY: imports the page supplies, given a number or nothing.
482        unsafe {
483            DUE.with(|due| due.set(now_millis() + wait));
484            wake_after(wait);
485        }
486    }
487
488    /// Checks the date at the start of a frame once the timer is due, and waits for the
489    /// next check.
490    pub(crate) fn frame() {
491        let armed = {
492            let mut watch = watch::lock();
493            if watch.subscribers.is_empty() {
494                watch.armed = false;
495            }
496            watch.armed
497        };
498        // SAFETY: an import the page supplies with no arguments.
499        if !armed || unsafe { now_millis() } < DUE.with(Cell::get) {
500            return;
501        }
502        watch::check();
503        schedule();
504    }
505}
506
507/// What a browser's frame does for the date: checks it, at the start of the frame, if
508/// anyone listens. Nothing anywhere else, where a thread waits for midnight instead.
509#[cfg(target_family = "wasm")]
510pub(crate) fn on_frame() {
511    platform::frame();
512}