taskbar-focus 0.6.0

A tiny Pomodoro/focus timer that lives in the Windows tray and toggles Do Not Disturb
//! What the user configures about PC locks, and the calendar types the
//! engine works with.

use serde::{Deserialize, Deserializer, Serialize, Serializer};

/// Milliseconds in a minute.
pub const MINUTE: i64 = 60_000;

/// A local calendar date, as days since 1970-01-01.
pub type Day = i64;

/// Weekday of a [`Day`], with Monday as 0.
pub fn weekday(day: Day) -> usize {
    (day + 3).rem_euclid(7) as usize
}

/// Minutes after local midnight.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ClockTime(pub u16);

impl ClockTime {
    /// Read the `17:45` form used in the settings file.
    fn from_file(text: &str) -> Option<ClockTime> {
        let (h, m) = text.trim().split_once(':')?;
        let (h, m): (u16, u16) = (h.parse().ok()?, m.parse().ok()?);
        (h < 24 && m < 60).then(|| ClockTime(h * 60 + m))
    }
}

impl Default for ClockTime {
    fn default() -> Self {
        ClockTime(17 * 60 + 45)
    }
}

impl Serialize for ClockTime {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str(&format!("{:02}:{:02}", self.0 / 60, self.0 % 60))
    }
}

impl<'de> Deserialize<'de> for DayLock {
    /// A day whose time cannot be read is turned off: failing would make the
    /// whole settings file unreadable, and guessing could lock at a wrong time.
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        struct Raw {
            #[serde(default)]
            enabled: bool,
            #[serde(default)]
            time: Option<toml::Value>,
            #[serde(default)]
            strict: bool,
        }
        let raw = Raw::deserialize(d)?;
        let time = match &raw.time {
            None => Some(ClockTime::default()),
            Some(value) => value.as_str().and_then(ClockTime::from_file),
        };
        Ok(DayLock {
            enabled: raw.enabled && time.is_some(),
            time: time.unwrap_or_default(),
            strict: raw.strict,
        })
    }
}

/// One weekday's PC lock.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
pub struct DayLock {
    pub enabled: bool,
    pub time: ClockTime,
    pub strict: bool,
}

/// The `[lock]` section of the settings file.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct LockSettings {
    pub cutoff_minutes: i64,
    pub warn_before_cutoff_minutes: i64,
    pub warn_before_lock_minutes: i64,
    pub postpone_minutes: i64,
    pub max_postponements: i64,
    pub locked_minutes: i64,
    pub return_window_minutes: i64,
    pub relock_delay_seconds: i64,
    pub monday: DayLock,
    pub tuesday: DayLock,
    pub wednesday: DayLock,
    pub thursday: DayLock,
    pub friday: DayLock,
    pub saturday: DayLock,
    pub sunday: DayLock,
}

impl Default for LockSettings {
    fn default() -> Self {
        Self {
            cutoff_minutes: 30,
            warn_before_cutoff_minutes: 10,
            warn_before_lock_minutes: 1,
            postpone_minutes: 30,
            max_postponements: 2,
            locked_minutes: 15,
            return_window_minutes: 30,
            relock_delay_seconds: 10,
            monday: DayLock::default(),
            tuesday: DayLock::default(),
            wednesday: DayLock::default(),
            thursday: DayLock::default(),
            friday: DayLock::default(),
            saturday: DayLock::default(),
            sunday: DayLock::default(),
        }
    }
}

impl LockSettings {
    pub fn day(&self, weekday: usize) -> &DayLock {
        match weekday {
            0 => &self.monday,
            1 => &self.tuesday,
            2 => &self.wednesday,
            3 => &self.thursday,
            4 => &self.friday,
            5 => &self.saturday,
            _ => &self.sunday,
        }
    }

    pub fn day_mut(&mut self, weekday: usize) -> &mut DayLock {
        match weekday {
            0 => &mut self.monday,
            1 => &mut self.tuesday,
            2 => &mut self.wednesday,
            3 => &mut self.thursday,
            4 => &mut self.friday,
            5 => &mut self.saturday,
            _ => &mut self.sunday,
        }
    }

    /// The largest allowed warning before the lock: it may not start before the
    /// cutoff, unless there is no cutoff.
    pub fn max_warn_before_lock(&self) -> i64 {
        match self.cutoff_minutes {
            0 => 30,
            cutoff => cutoff.min(30),
        }
    }

    /// Bring every value into its allowed range.
    pub fn clamp(&mut self) {
        self.cutoff_minutes = self.cutoff_minutes.clamp(0, 720);
        self.warn_before_cutoff_minutes = self.warn_before_cutoff_minutes.clamp(0, 120);
        self.warn_before_lock_minutes = self
            .warn_before_lock_minutes
            .clamp(0, self.max_warn_before_lock());
        self.postpone_minutes = self.postpone_minutes.clamp(1, 240);
        self.max_postponements = self.max_postponements.clamp(0, 10);
        self.locked_minutes = self.locked_minutes.clamp(0, 120);
        self.return_window_minutes = self.return_window_minutes.clamp(0, 240);
        self.relock_delay_seconds = self.relock_delay_seconds.clamp(5, 300);
    }
}