tilo-settings-model 0.5.5

The settings' typed schema, the theme names and the shared sections as resource models, buildable for WebAssembly
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
//! When the day ends: the one schedule automatic light/dark and night light share.
//!
//! The `appearance` section holds the choice: follow the sun (`schedule: "sun"`, the default)
//! or fixed times (`schedule: "custom"` with `sunrise`/`sunset` as `HH:MM`). Following the sun
//! computes sunrise and sunset for today at the location the system time zone names in tzdata's
//! `zone1970.tab`; without a usable location (no zone, a zone missing from the table, polar day
//! or night) it uses the fixed times, which default to 07:00 and 19:00.
//!
//! Everything here is pure except [`timezone_location`], so callers pass the local moment in
//! and tests pin it.

use std::path::Path;

use serde_json::{Map, Value};

pub const SECTION: &str = "appearance";
pub const SCHEDULE_KEY: &str = "schedule";
pub const SUNRISE_KEY: &str = "sunrise";
pub const SUNSET_KEY: &str = "sunset";
pub const MODE_KEY: &str = "mode";
pub const AUTOMATIC_MODE: &str = "automatic";

const MINUTES_PER_DAY: i32 = 24 * 60;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DaySchedule {
    pub sunrise: u16,
    pub sunset: u16,
}

impl DaySchedule {
    pub const FIXED: Self = Self {
        sunrise: 7 * 60,
        sunset: 19 * 60,
    };

    pub fn is_night(self, minute_of_day: u16) -> bool {
        if self.sunrise <= self.sunset {
            minute_of_day < self.sunrise || minute_of_day >= self.sunset
        } else {
            minute_of_day >= self.sunset && minute_of_day < self.sunrise
        }
    }
}

impl Default for DaySchedule {
    fn default() -> Self {
        Self::FIXED
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LocalMoment {
    /// 1 for 1 January.
    pub day_of_year: u16,
    pub minute_of_day: u16,
    pub utc_offset_minutes: i32,
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Location {
    pub latitude: f64,
    pub longitude: f64,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ScheduleConfig {
    pub follow_sun: bool,
    pub fixed: DaySchedule,
}

impl Default for ScheduleConfig {
    fn default() -> Self {
        Self {
            follow_sun: true,
            fixed: DaySchedule::FIXED,
        }
    }
}

impl ScheduleConfig {
    pub fn from_section(section: &Map<String, Value>) -> Self {
        let time = |key: &str, fallback: u16| {
            section
                .get(key)
                .and_then(Value::as_str)
                .and_then(parse_hhmm)
                .unwrap_or(fallback)
        };
        Self {
            follow_sun: section.get(SCHEDULE_KEY).and_then(Value::as_str) != Some("custom"),
            fixed: DaySchedule {
                sunrise: time(SUNRISE_KEY, DaySchedule::FIXED.sunrise),
                sunset: time(SUNSET_KEY, DaySchedule::FIXED.sunset),
            },
        }
    }

    pub fn resolve(self, location: Option<Location>, moment: LocalMoment) -> DaySchedule {
        if self.follow_sun
            && let Some(location) = location
            && let Some(sun) = sun_times(location, moment.day_of_year, moment.utc_offset_minutes)
        {
            return sun;
        }
        self.fixed
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Scheduled {
    pub config: ScheduleConfig,
    pub location: Option<Location>,
}

impl Scheduled {
    pub fn from_settings(settings: &Map<String, Value>) -> Self {
        let section = settings
            .get(SECTION)
            .and_then(Value::as_object)
            .cloned()
            .unwrap_or_default();
        Self {
            config: ScheduleConfig::from_section(&section),
            location: timezone_location(),
        }
    }

    pub fn is_night(&self, moment: LocalMoment) -> bool {
        self.config
            .resolve(self.location, moment)
            .is_night(moment.minute_of_day)
    }
}

pub fn is_automatic(mode: &str) -> bool {
    mode == AUTOMATIC_MODE
}

/// Parse `HH:MM` (24-hour) to minutes after midnight.
pub fn parse_hhmm(value: &str) -> Option<u16> {
    let (hours, minutes) = value.trim().split_once(':')?;
    if minutes.len() != 2 {
        return None;
    }
    let hours: u16 = hours.parse().ok()?;
    let minutes: u16 = minutes.parse().ok()?;
    (hours < 24 && minutes < 60).then(|| hours.saturating_mul(60).saturating_add(minutes))
}

/// Format minutes after midnight as `HH:MM`.
pub fn format_hhmm(minute_of_day: u16) -> String {
    let minute_of_day = minute_of_day % (24 * 60);
    tilo_formats::machine!(
        "a clock time the settings document stores for a person's schedule, read back by parse_hhmm",
        format!("{:02}:{:02}", minute_of_day / 60, minute_of_day % 60)
    )
}

/// Sunrise and sunset at `location` on `day_of_year`, in local minutes for `utc_offset_minutes`.
/// `None` during polar day or night, when the sun does not cross the horizon.
///
/// NOAA's low-precision solar position (equation of time and declination from the fractional
/// year), with the standard −0.833° horizon for refraction and the solar disc: within a few
/// minutes of the precise value, which is all a theme switch needs.
pub fn sun_times(
    location: Location,
    day_of_year: u16,
    utc_offset_minutes: i32,
) -> Option<DaySchedule> {
    use std::f64::consts::PI;
    let gamma = 2.0 * PI / 365.0 * (f64::from(day_of_year) - 1.0);
    let equation_of_time = 229.18
        * (0.000_075 + 0.001_868 * gamma.cos()
            - 0.032_077 * gamma.sin()
            - 0.014_615 * (2.0 * gamma).cos()
            - 0.040_849 * (2.0 * gamma).sin());
    let declination = 0.006_918 - 0.399_912 * gamma.cos() + 0.070_257 * gamma.sin()
        - 0.006_758 * (2.0 * gamma).cos()
        + 0.000_907 * (2.0 * gamma).sin()
        - 0.002_697 * (3.0 * gamma).cos()
        + 0.001_48 * (3.0 * gamma).sin();
    let latitude = location.latitude.to_radians();
    let cos_hour_angle = 90.833_f64.to_radians().cos() / (latitude.cos() * declination.cos())
        - latitude.tan() * declination.tan();
    if !(-1.0..=1.0).contains(&cos_hour_angle) {
        return None;
    }
    let hour_angle = cos_hour_angle.acos().to_degrees();
    let local = |utc_minutes: f64| -> Option<u16> {
        if !utc_minutes.is_finite() {
            return None;
        }
        #[allow(
            clippy::cast_possible_truncation,
            reason = "a finite sunrise/sunset is within a day or two of noon, far inside i32"
        )]
        let minutes = (utc_minutes.round() as i32)
            .saturating_add(utc_offset_minutes)
            .rem_euclid(MINUTES_PER_DAY);
        u16::try_from(minutes).ok()
    };
    Some(DaySchedule {
        sunrise: local(720.0 - 4.0 * (location.longitude + hour_angle) - equation_of_time)?,
        sunset: local(720.0 - 4.0 * (location.longitude - hour_angle) - equation_of_time)?,
    })
}

pub fn timezone_location() -> Option<Location> {
    let zone = system_timezone()?;
    [
        "/usr/share/zoneinfo/zone1970.tab",
        "/usr/share/zoneinfo/zone.tab",
    ]
    .iter()
    .find_map(|table| std::fs::read_to_string(table).ok())
    .and_then(|table| timezone_location_in(&zone, &table))
}

fn system_timezone() -> Option<String> {
    if let Some(tz) = std::env::var_os("TZ").and_then(|v| v.into_string().ok()) {
        let tz = tz.trim_start_matches(':');
        if tz.contains('/') && !tz.starts_with('/') {
            return Some(tz.to_string());
        }
    }
    zone_from_link(&std::fs::read_link(Path::new("/etc/localtime")).ok()?)
}

fn zone_from_link(target: &Path) -> Option<String> {
    let text = target.to_str()?;
    let (_, zone) = text.split_once("zoneinfo/")?;
    (!zone.is_empty()).then(|| zone.to_string())
}

pub fn timezone_location_in(zone: &str, table: &str) -> Option<Location> {
    table
        .lines()
        .filter(|line| !line.starts_with('#'))
        .find_map(|line| {
            let mut columns = line.split('\t');
            let _countries = columns.next()?;
            let coordinate = columns.next()?;
            (columns.next()? == zone).then_some(coordinate)
        })
        .and_then(parse_iso6709)
}

/// Parse the compact ISO 6709 latitude+longitude form tzdata uses: `+DDMM+DDDMM` or
/// `+DDMMSS+DDDMMSS` (and negative equivalents).
pub fn parse_iso6709(value: &str) -> Option<Location> {
    let split = value
        .char_indices()
        .skip(1)
        .find_map(|(i, c)| matches!(c, '+' | '-').then_some(i))?;
    Some(Location {
        latitude: parse_coordinate_part(value.get(..split)?, true)?,
        longitude: parse_coordinate_part(value.get(split..)?, false)?,
    })
}

fn parse_coordinate_part(value: &str, latitude: bool) -> Option<f64> {
    let sign = match value.as_bytes().first().copied()? {
        b'+' => 1.0,
        b'-' => -1.0,
        _ => return None,
    };
    let digits = value.get(1..)?;
    let (degrees_end, minutes_end, with_seconds) = match (latitude, digits.len()) {
        (true, 4) => (2, 4, false),
        (true, 6) => (2, 4, true),
        (false, 5) => (3, 5, false),
        (false, 7) => (3, 5, true),
        _ => return None,
    };
    let degrees: f64 = digits.get(..degrees_end)?.parse().ok()?;
    let minutes: f64 = digits.get(degrees_end..minutes_end)?.parse().ok()?;
    let seconds: f64 = if with_seconds {
        digits.get(minutes_end..)?.parse().ok()?
    } else {
        0.0
    };
    let limit = if latitude { 90.0 } else { 180.0 };
    if degrees > limit || minutes >= 60.0 || seconds >= 60.0 {
        return None;
    }
    Some(sign * (degrees + minutes / 60.0 + seconds / 3600.0))
}

#[cfg(test)]
mod tests {
    use super::*;

    const BERLIN: Location = Location {
        latitude: 52.5,
        longitude: 13.366_666,
    };

    fn at(day_of_year: u16, hhmm: &str, utc_offset_minutes: i32) -> LocalMoment {
        LocalMoment {
            day_of_year,
            minute_of_day: parse_hhmm(hhmm).unwrap(),
            utc_offset_minutes,
        }
    }

    fn near(actual: u16, expected: &str) {
        let expected = parse_hhmm(expected).unwrap();
        assert!(
            actual.abs_diff(expected) <= 5,
            "{} is not within five minutes of {}",
            format_hhmm(actual),
            format_hhmm(expected)
        );
    }

    tilo_test_env::scenario! {
        fn a_schedule_resolves_fixed_custom_and_malformed_settings;

        phase without_a_location_the_fixed_seven_to_seven_applies;
        {
            let config = ScheduleConfig::default();
            let schedule = config.resolve(None, at(100, "12:00", 0));
            assert_eq!(format_hhmm(schedule.sunrise), "07:00");
            assert_eq!(format_hhmm(schedule.sunset), "19:00");
            assert!(schedule.is_night(parse_hhmm("06:59").unwrap()));
            assert!(!schedule.is_night(parse_hhmm("07:00").unwrap()));
            assert!(!schedule.is_night(parse_hhmm("18:59").unwrap()));
            assert!(schedule.is_night(parse_hhmm("19:00").unwrap()));
        }

        phase custom_times_win_over_the_sun_and_may_wrap_midnight;
        {
            let mut section = Map::new();
            section.insert(SCHEDULE_KEY.into(), "custom".into());
            section.insert(SUNRISE_KEY.into(), "08:30".into());
            section.insert(SUNSET_KEY.into(), "21:15".into());
            let config = ScheduleConfig::from_section(&section);
            let schedule = config.resolve(Some(BERLIN), at(172, "12:00", 120));
            assert_eq!(schedule.sunrise, parse_hhmm("08:30").unwrap());
            assert_eq!(schedule.sunset, parse_hhmm("21:15").unwrap());

            let inverted = DaySchedule {
                sunrise: parse_hhmm("22:00").unwrap(),
                sunset: parse_hhmm("06:00").unwrap(),
            };
            assert!(!inverted.is_night(parse_hhmm("23:00").unwrap()));
            assert!(inverted.is_night(parse_hhmm("12:00").unwrap()));
        }

        phase malformed_settings_take_the_defaults;
        {
            let mut section = Map::new();
            section.insert(SUNRISE_KEY.into(), "7am".into());
            section.insert(SUNSET_KEY.into(), Value::from(19));
            assert_eq!(
                ScheduleConfig::from_section(&section),
                ScheduleConfig::default()
            );
            assert_eq!(parse_hhmm("24:00"), None);
            assert_eq!(parse_hhmm("07:60"), None);
            assert_eq!(format_hhmm(parse_hhmm("7:05").unwrap()), "07:05");
        }
    }

    tilo_test_env::scenario! {
        fn sun_times_come_from_the_location_and_the_time_zone;

        phase berlin_sunrise_and_sunset_match_the_almanac;
        {
            let summer = sun_times(BERLIN, 172, 120).unwrap();
            near(summer.sunrise, "04:43");
            near(summer.sunset, "21:33");
        }

        phase polar_day_has_no_sunset_and_falls_back_to_fixed_times;
        {
            let tromso = Location {
                latitude: 69.65,
                longitude: 18.96,
            };
            assert_eq!(sun_times(tromso, 172, 120), None);
            let schedule = ScheduleConfig::default().resolve(Some(tromso), at(172, "12:00", 120));
            assert_eq!(schedule, DaySchedule::FIXED);
        }

        phase the_time_zone_names_a_location_in_tzdata;
        {
            let table = "# comment\nDE,DK,NO,SE,SJ\t+5230+01322\tEurope/Berlin\n\
                     AU\t-3352+15113\tAustralia/Sydney\tNew South Wales\n";
            let berlin = timezone_location_in("Europe/Berlin", table).unwrap();
            assert!((berlin.latitude - 52.5).abs() < 1e-9);
            assert!((berlin.longitude - 13.366_666).abs() < 1e-3);
            let sydney = timezone_location_in("Australia/Sydney", table).unwrap();
            assert!(sydney.latitude < 0.0);
            assert_eq!(timezone_location_in("Mars/Olympus", table), None);
            assert_eq!(
                zone_from_link(Path::new("../usr/share/zoneinfo/Europe/Berlin")).as_deref(),
                Some("Europe/Berlin")
            );
        }
    }

    #[test]
    fn automatic_theme_follows_the_schedule() {
        let scheduled = Scheduled {
            config: ScheduleConfig::default(),
            location: Some(BERLIN),
        };
        assert!(!scheduled.is_night(at(172, "12:00", 120)));
        assert!(scheduled.is_night(at(172, "23:00", 120)));
        assert!(
            scheduled.is_night(at(355, "17:00", 60)),
            "dark before five in winter"
        );
        assert!(is_automatic("automatic"));
        assert!(!is_automatic("dark"));
    }
}