Skip to main content

settings_model/
day_schedule.rs

1//! When the day ends: the one schedule automatic light/dark and night light share.
2//!
3//! The `appearance` section holds the choice: follow the sun (`schedule: "sun"`, the default)
4//! or fixed times (`schedule: "custom"` with `sunrise`/`sunset` as `HH:MM`). Following the sun
5//! computes sunrise and sunset for today at the location the system time zone names in tzdata's
6//! `zone1970.tab`; without a usable location (no zone, a zone missing from the table, polar day
7//! or night) it uses the fixed times, which default to 07:00 and 19:00.
8//!
9//! Everything here is pure except [`timezone_location`], so callers pass the local moment in
10//! and tests pin it.
11
12use std::path::Path;
13
14use serde_json::{Map, Value};
15
16pub const SECTION: &str = "appearance";
17pub const SCHEDULE_KEY: &str = "schedule";
18pub const SUNRISE_KEY: &str = "sunrise";
19pub const SUNSET_KEY: &str = "sunset";
20pub const MODE_KEY: &str = "mode";
21pub const AUTOMATIC_MODE: &str = "automatic";
22
23const MINUTES_PER_DAY: i32 = 24 * 60;
24
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub struct DaySchedule {
27    pub sunrise: u16,
28    pub sunset: u16,
29}
30
31impl DaySchedule {
32    pub const FIXED: Self = Self {
33        sunrise: 7 * 60,
34        sunset: 19 * 60,
35    };
36
37    pub fn is_night(self, minute_of_day: u16) -> bool {
38        if self.sunrise <= self.sunset {
39            minute_of_day < self.sunrise || minute_of_day >= self.sunset
40        } else {
41            minute_of_day >= self.sunset && minute_of_day < self.sunrise
42        }
43    }
44}
45
46impl Default for DaySchedule {
47    fn default() -> Self {
48        Self::FIXED
49    }
50}
51
52#[derive(Clone, Copy, Debug, PartialEq, Eq)]
53pub struct LocalMoment {
54    /// 1 for 1 January.
55    pub day_of_year: u16,
56    pub minute_of_day: u16,
57    pub utc_offset_minutes: i32,
58}
59
60#[derive(Clone, Copy, Debug, PartialEq)]
61pub struct Location {
62    pub latitude: f64,
63    pub longitude: f64,
64}
65
66#[derive(Clone, Copy, Debug, PartialEq, Eq)]
67pub struct ScheduleConfig {
68    pub follow_sun: bool,
69    pub fixed: DaySchedule,
70}
71
72impl Default for ScheduleConfig {
73    fn default() -> Self {
74        Self {
75            follow_sun: true,
76            fixed: DaySchedule::FIXED,
77        }
78    }
79}
80
81impl ScheduleConfig {
82    pub fn from_section(section: &Map<String, Value>) -> Self {
83        let time = |key: &str, fallback: u16| {
84            section
85                .get(key)
86                .and_then(Value::as_str)
87                .and_then(parse_hhmm)
88                .unwrap_or(fallback)
89        };
90        Self {
91            follow_sun: section.get(SCHEDULE_KEY).and_then(Value::as_str) != Some("custom"),
92            fixed: DaySchedule {
93                sunrise: time(SUNRISE_KEY, DaySchedule::FIXED.sunrise),
94                sunset: time(SUNSET_KEY, DaySchedule::FIXED.sunset),
95            },
96        }
97    }
98
99    pub fn resolve(self, location: Option<Location>, moment: LocalMoment) -> DaySchedule {
100        if self.follow_sun
101            && let Some(location) = location
102            && let Some(sun) = sun_times(location, moment.day_of_year, moment.utc_offset_minutes)
103        {
104            return sun;
105        }
106        self.fixed
107    }
108}
109
110#[derive(Clone, Copy, Debug, PartialEq)]
111pub struct Scheduled {
112    pub config: ScheduleConfig,
113    pub location: Option<Location>,
114}
115
116impl Scheduled {
117    pub fn from_settings(settings: &Map<String, Value>) -> Self {
118        let section = settings
119            .get(SECTION)
120            .and_then(Value::as_object)
121            .cloned()
122            .unwrap_or_default();
123        Self {
124            config: ScheduleConfig::from_section(&section),
125            location: timezone_location(),
126        }
127    }
128
129    pub fn is_night(&self, moment: LocalMoment) -> bool {
130        self.config
131            .resolve(self.location, moment)
132            .is_night(moment.minute_of_day)
133    }
134}
135
136pub fn is_automatic(mode: &str) -> bool {
137    mode == AUTOMATIC_MODE
138}
139
140/// Parse `HH:MM` (24-hour) to minutes after midnight.
141pub fn parse_hhmm(value: &str) -> Option<u16> {
142    let (hours, minutes) = value.trim().split_once(':')?;
143    if minutes.len() != 2 {
144        return None;
145    }
146    let hours: u16 = hours.parse().ok()?;
147    let minutes: u16 = minutes.parse().ok()?;
148    (hours < 24 && minutes < 60).then(|| hours.saturating_mul(60).saturating_add(minutes))
149}
150
151/// Format minutes after midnight as `HH:MM`.
152pub fn format_hhmm(minute_of_day: u16) -> String {
153    let minute_of_day = minute_of_day % (24 * 60);
154    tilo_formats::machine!(
155        "a clock time the settings document stores for a person's schedule, read back by parse_hhmm",
156        format!("{:02}:{:02}", minute_of_day / 60, minute_of_day % 60)
157    )
158}
159
160/// Sunrise and sunset at `location` on `day_of_year`, in local minutes for `utc_offset_minutes`.
161/// `None` during polar day or night, when the sun does not cross the horizon.
162///
163/// NOAA's low-precision solar position (equation of time and declination from the fractional
164/// year), with the standard −0.833° horizon for refraction and the solar disc: within a few
165/// minutes of the precise value, which is all a theme switch needs.
166pub fn sun_times(
167    location: Location,
168    day_of_year: u16,
169    utc_offset_minutes: i32,
170) -> Option<DaySchedule> {
171    use std::f64::consts::PI;
172    let gamma = 2.0 * PI / 365.0 * (f64::from(day_of_year) - 1.0);
173    let equation_of_time = 229.18
174        * (0.000_075 + 0.001_868 * gamma.cos()
175            - 0.032_077 * gamma.sin()
176            - 0.014_615 * (2.0 * gamma).cos()
177            - 0.040_849 * (2.0 * gamma).sin());
178    let declination = 0.006_918 - 0.399_912 * gamma.cos() + 0.070_257 * gamma.sin()
179        - 0.006_758 * (2.0 * gamma).cos()
180        + 0.000_907 * (2.0 * gamma).sin()
181        - 0.002_697 * (3.0 * gamma).cos()
182        + 0.001_48 * (3.0 * gamma).sin();
183    let latitude = location.latitude.to_radians();
184    let cos_hour_angle = 90.833_f64.to_radians().cos() / (latitude.cos() * declination.cos())
185        - latitude.tan() * declination.tan();
186    if !(-1.0..=1.0).contains(&cos_hour_angle) {
187        return None;
188    }
189    let hour_angle = cos_hour_angle.acos().to_degrees();
190    let local = |utc_minutes: f64| -> Option<u16> {
191        if !utc_minutes.is_finite() {
192            return None;
193        }
194        #[allow(
195            clippy::cast_possible_truncation,
196            reason = "a finite sunrise/sunset is within a day or two of noon, far inside i32"
197        )]
198        let minutes = (utc_minutes.round() as i32)
199            .saturating_add(utc_offset_minutes)
200            .rem_euclid(MINUTES_PER_DAY);
201        u16::try_from(minutes).ok()
202    };
203    Some(DaySchedule {
204        sunrise: local(720.0 - 4.0 * (location.longitude + hour_angle) - equation_of_time)?,
205        sunset: local(720.0 - 4.0 * (location.longitude - hour_angle) - equation_of_time)?,
206    })
207}
208
209pub fn timezone_location() -> Option<Location> {
210    let zone = system_timezone()?;
211    [
212        "/usr/share/zoneinfo/zone1970.tab",
213        "/usr/share/zoneinfo/zone.tab",
214    ]
215    .iter()
216    .find_map(|table| std::fs::read_to_string(table).ok())
217    .and_then(|table| timezone_location_in(&zone, &table))
218}
219
220fn system_timezone() -> Option<String> {
221    if let Some(tz) = std::env::var_os("TZ").and_then(|v| v.into_string().ok()) {
222        let tz = tz.trim_start_matches(':');
223        if tz.contains('/') && !tz.starts_with('/') {
224            return Some(tz.to_string());
225        }
226    }
227    zone_from_link(&std::fs::read_link(Path::new("/etc/localtime")).ok()?)
228}
229
230fn zone_from_link(target: &Path) -> Option<String> {
231    let text = target.to_str()?;
232    let (_, zone) = text.split_once("zoneinfo/")?;
233    (!zone.is_empty()).then(|| zone.to_string())
234}
235
236pub fn timezone_location_in(zone: &str, table: &str) -> Option<Location> {
237    table
238        .lines()
239        .filter(|line| !line.starts_with('#'))
240        .find_map(|line| {
241            let mut columns = line.split('\t');
242            let _countries = columns.next()?;
243            let coordinate = columns.next()?;
244            (columns.next()? == zone).then_some(coordinate)
245        })
246        .and_then(parse_iso6709)
247}
248
249/// Parse the compact ISO 6709 latitude+longitude form tzdata uses: `+DDMM+DDDMM` or
250/// `+DDMMSS+DDDMMSS` (and negative equivalents).
251pub fn parse_iso6709(value: &str) -> Option<Location> {
252    let split = value
253        .char_indices()
254        .skip(1)
255        .find_map(|(i, c)| matches!(c, '+' | '-').then_some(i))?;
256    Some(Location {
257        latitude: parse_coordinate_part(value.get(..split)?, true)?,
258        longitude: parse_coordinate_part(value.get(split..)?, false)?,
259    })
260}
261
262fn parse_coordinate_part(value: &str, latitude: bool) -> Option<f64> {
263    let sign = match value.as_bytes().first().copied()? {
264        b'+' => 1.0,
265        b'-' => -1.0,
266        _ => return None,
267    };
268    let digits = value.get(1..)?;
269    let (degrees_end, minutes_end, with_seconds) = match (latitude, digits.len()) {
270        (true, 4) => (2, 4, false),
271        (true, 6) => (2, 4, true),
272        (false, 5) => (3, 5, false),
273        (false, 7) => (3, 5, true),
274        _ => return None,
275    };
276    let degrees: f64 = digits.get(..degrees_end)?.parse().ok()?;
277    let minutes: f64 = digits.get(degrees_end..minutes_end)?.parse().ok()?;
278    let seconds: f64 = if with_seconds {
279        digits.get(minutes_end..)?.parse().ok()?
280    } else {
281        0.0
282    };
283    let limit = if latitude { 90.0 } else { 180.0 };
284    if degrees > limit || minutes >= 60.0 || seconds >= 60.0 {
285        return None;
286    }
287    Some(sign * (degrees + minutes / 60.0 + seconds / 3600.0))
288}
289
290#[cfg(test)]
291mod tests {
292    use super::*;
293
294    const BERLIN: Location = Location {
295        latitude: 52.5,
296        longitude: 13.366_666,
297    };
298
299    fn at(day_of_year: u16, hhmm: &str, utc_offset_minutes: i32) -> LocalMoment {
300        LocalMoment {
301            day_of_year,
302            minute_of_day: parse_hhmm(hhmm).unwrap(),
303            utc_offset_minutes,
304        }
305    }
306
307    fn near(actual: u16, expected: &str) {
308        let expected = parse_hhmm(expected).unwrap();
309        assert!(
310            actual.abs_diff(expected) <= 5,
311            "{} is not within five minutes of {}",
312            format_hhmm(actual),
313            format_hhmm(expected)
314        );
315    }
316
317    tilo_test_env::scenario! {
318        fn a_schedule_resolves_fixed_custom_and_malformed_settings;
319
320        phase without_a_location_the_fixed_seven_to_seven_applies;
321        {
322            let config = ScheduleConfig::default();
323            let schedule = config.resolve(None, at(100, "12:00", 0));
324            assert_eq!(format_hhmm(schedule.sunrise), "07:00");
325            assert_eq!(format_hhmm(schedule.sunset), "19:00");
326            assert!(schedule.is_night(parse_hhmm("06:59").unwrap()));
327            assert!(!schedule.is_night(parse_hhmm("07:00").unwrap()));
328            assert!(!schedule.is_night(parse_hhmm("18:59").unwrap()));
329            assert!(schedule.is_night(parse_hhmm("19:00").unwrap()));
330        }
331
332        phase custom_times_win_over_the_sun_and_may_wrap_midnight;
333        {
334            let mut section = Map::new();
335            section.insert(SCHEDULE_KEY.into(), "custom".into());
336            section.insert(SUNRISE_KEY.into(), "08:30".into());
337            section.insert(SUNSET_KEY.into(), "21:15".into());
338            let config = ScheduleConfig::from_section(&section);
339            let schedule = config.resolve(Some(BERLIN), at(172, "12:00", 120));
340            assert_eq!(schedule.sunrise, parse_hhmm("08:30").unwrap());
341            assert_eq!(schedule.sunset, parse_hhmm("21:15").unwrap());
342
343            let inverted = DaySchedule {
344                sunrise: parse_hhmm("22:00").unwrap(),
345                sunset: parse_hhmm("06:00").unwrap(),
346            };
347            assert!(!inverted.is_night(parse_hhmm("23:00").unwrap()));
348            assert!(inverted.is_night(parse_hhmm("12:00").unwrap()));
349        }
350
351        phase malformed_settings_take_the_defaults;
352        {
353            let mut section = Map::new();
354            section.insert(SUNRISE_KEY.into(), "7am".into());
355            section.insert(SUNSET_KEY.into(), Value::from(19));
356            assert_eq!(
357                ScheduleConfig::from_section(&section),
358                ScheduleConfig::default()
359            );
360            assert_eq!(parse_hhmm("24:00"), None);
361            assert_eq!(parse_hhmm("07:60"), None);
362            assert_eq!(format_hhmm(parse_hhmm("7:05").unwrap()), "07:05");
363        }
364    }
365
366    tilo_test_env::scenario! {
367        fn sun_times_come_from_the_location_and_the_time_zone;
368
369        phase berlin_sunrise_and_sunset_match_the_almanac;
370        {
371            let summer = sun_times(BERLIN, 172, 120).unwrap();
372            near(summer.sunrise, "04:43");
373            near(summer.sunset, "21:33");
374        }
375
376        phase polar_day_has_no_sunset_and_falls_back_to_fixed_times;
377        {
378            let tromso = Location {
379                latitude: 69.65,
380                longitude: 18.96,
381            };
382            assert_eq!(sun_times(tromso, 172, 120), None);
383            let schedule = ScheduleConfig::default().resolve(Some(tromso), at(172, "12:00", 120));
384            assert_eq!(schedule, DaySchedule::FIXED);
385        }
386
387        phase the_time_zone_names_a_location_in_tzdata;
388        {
389            let table = "# comment\nDE,DK,NO,SE,SJ\t+5230+01322\tEurope/Berlin\n\
390                     AU\t-3352+15113\tAustralia/Sydney\tNew South Wales\n";
391            let berlin = timezone_location_in("Europe/Berlin", table).unwrap();
392            assert!((berlin.latitude - 52.5).abs() < 1e-9);
393            assert!((berlin.longitude - 13.366_666).abs() < 1e-3);
394            let sydney = timezone_location_in("Australia/Sydney", table).unwrap();
395            assert!(sydney.latitude < 0.0);
396            assert_eq!(timezone_location_in("Mars/Olympus", table), None);
397            assert_eq!(
398                zone_from_link(Path::new("../usr/share/zoneinfo/Europe/Berlin")).as_deref(),
399                Some("Europe/Berlin")
400            );
401        }
402    }
403
404    #[test]
405    fn automatic_theme_follows_the_schedule() {
406        let scheduled = Scheduled {
407            config: ScheduleConfig::default(),
408            location: Some(BERLIN),
409        };
410        assert!(!scheduled.is_night(at(172, "12:00", 120)));
411        assert!(scheduled.is_night(at(172, "23:00", 120)));
412        assert!(
413            scheduled.is_night(at(355, "17:00", 60)),
414            "dark before five in winter"
415        );
416        assert!(is_automatic("automatic"));
417        assert!(!is_automatic("dark"));
418    }
419}