Skip to main content

tilo_notify/
calendar.rs

1//! Local wall-clock alarms, shared by apps and the host that delivers them.
2use jiff::Zoned;
3use jiff::civil::{Date, Time};
4use jiff::tz::AmbiguousOffset;
5
6/// An alarm in this device's local time. Monday is bit zero; no weekdays
7/// means a single occurrence. A repeating alarm needs no network connection.
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9pub struct CalendarAlarm {
10    pub hour: u8,
11    pub minute: u8,
12    pub weekdays: u8,
13}
14
15impl CalendarAlarm {
16    pub fn valid(self) -> bool {
17        self.hour < 24 && self.minute < 60 && self.weekdays < 128
18    }
19
20    pub fn next_in(self, last_rung: Option<Date>, after: &Zoned) -> Option<Zoned> {
21        if !self.valid() {
22            return None;
23        }
24        let time = Time::new(
25            i8::try_from(self.hour).ok()?,
26            i8::try_from(self.minute).ok()?,
27            0,
28            0,
29        )
30        .ok()?;
31        for day in 0..=8_i32 {
32            let date = after.date().checked_add(jiff::Span::new().days(day)).ok()?;
33            let weekday =
34                1u8.checked_shl(date.weekday().to_monday_zero_offset().unsigned_abs().into())?;
35            if last_rung == Some(date) || (self.weekdays != 0 && self.weekdays & weekday == 0) {
36                continue;
37            }
38            let mut naive = date.to_datetime(time);
39            for _ in 0..180 {
40                let local = after.time_zone().to_ambiguous_zoned(naive);
41                if !matches!(local.offset(), AmbiguousOffset::Gap { .. }) {
42                    let candidate = local.earlier().ok()?;
43                    if candidate > *after {
44                        return Some(candidate);
45                    }
46                    break;
47                }
48                naive = naive.checked_add(jiff::SignedDuration::from_mins(1)).ok()?;
49            }
50        }
51        None
52    }
53}
54
55#[derive(Clone, Copy, Debug, PartialEq, Eq)]
56pub struct AlarmSchedule {
57    pub alarm: CalendarAlarm,
58    pub enabled_at_ms: i64,
59    pub last_rung: Option<Date>,
60}