taskbar-focus 0.6.0

A tiny Pomodoro/focus timer that lives in the Windows tray and toggles Do Not Disturb
//! One day's PC lock, and the clocks it is measured on.

use super::settings::{weekday, Day, DayLock, LockSettings, MINUTE};
use serde::{Deserialize, Serialize};

/// The current time, on every clock the rules need.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Moment {
    /// Unix milliseconds, from the wall clock.
    pub wall: i64,
    /// Milliseconds since boot, counting sleep.
    pub tick: i64,
    /// Milliseconds since boot, not counting sleep.
    pub awake: i64,
    /// Identifies the sign-in. `tick` values compare only within one.
    pub sign_in: i64,
}

/// Local time, injected so daylight saving can be tested.
pub trait Zone {
    /// When `minutes` after local midnight of `day` happens, in Unix ms.
    fn instant(&self, day: Day, minutes: u16) -> i64;
    /// The local date at a Unix time in ms.
    fn day_of(&self, wall: i64) -> Day;
}

/// Time left until a moment. It never increases, whatever the clock does.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Countdown {
    end: i64,
    pub remaining: i64,
    tick: i64,
    sign_in: i64,
}

impl Countdown {
    pub fn new(length: i64, now: Moment) -> Self {
        Countdown {
            end: now.wall + length,
            remaining: length,
            tick: now.tick,
            sign_in: now.sign_in,
        }
    }

    /// Ticks within one sign-in, and the smaller of the saved remainder and the
    /// saved end after a new one.
    pub fn update(&mut self, now: Moment) {
        self.remaining = if self.sign_in == now.sign_in && now.tick >= self.tick {
            self.remaining - (now.tick - self.tick)
        } else {
            self.remaining.min(self.end - now.wall)
        };
        self.tick = now.tick;
        self.sign_in = now.sign_in;
    }

    pub fn running(&self) -> bool {
        self.remaining > 0
    }

    /// Give back time during which the countdown was held.
    pub fn extend(&mut self, by: i64) {
        self.remaining += by;
        self.end += by;
    }
}

/// Time left that passes only while the PC is awake, kept across restarts.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AwakeCountdown {
    pub remaining: i64,
    awake: i64,
    sign_in: i64,
}

impl AwakeCountdown {
    pub fn new(length: i64, now: Moment) -> Self {
        AwakeCountdown {
            remaining: length,
            awake: now.awake,
            sign_in: now.sign_in,
        }
    }

    /// Counts awake time within one sign-in. After a new one it carries on
    /// from where it was, without counting the time in between.
    pub fn update(&mut self, now: Moment) {
        if self.sign_in == now.sign_in && now.awake >= self.awake {
            self.remaining -= now.awake - self.awake;
        }
        self.awake = now.awake;
        self.sign_in = now.sign_in;
    }

    pub fn running(&self) -> bool {
        self.remaining > 0
    }
}

/// The moment of a lock, fixed at its cutoff.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Fixed {
    pub instant: i64,
    remaining: i64,
    tick: i64,
    sign_in: i64,
}

impl Fixed {
    pub fn new(instant: i64, now: Moment) -> Self {
        Fixed {
            instant,
            remaining: instant - now.wall,
            tick: now.tick,
            sign_in: now.sign_in,
        }
    }

    /// Bring a saved value up to date after a new sign-in. A wall clock that
    /// claims more time is left than the cutoff allowed was corrected since, and
    /// following it could hold a strict lock open for as long as it was wrong.
    fn reanchor(&mut self, now: Moment) {
        let same = self.sign_in == now.sign_in && now.tick >= self.tick;
        if !same && self.instant - now.wall > self.remaining {
            self.tick = now.tick;
            self.sign_in = now.sign_in;
        }
    }

    /// Ticks within the sign-in that saw the cutoff, so a clock change cannot
    /// move the lock, and the wall clock after that.
    fn remaining(&self, now: Moment) -> i64 {
        if self.sign_in == now.sign_in && now.tick >= self.tick {
            self.remaining - (now.tick - self.tick)
        } else {
            self.instant - now.wall
        }
    }
}

/// Every setting that governs one occurrence.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Rules {
    pub cutoff: i64,
    pub warn_before_cutoff: i64,
    pub warn_before_lock: i64,
    pub postpone: i64,
    pub max_postponements: i64,
    pub locked: i64,
    pub return_window: i64,
    pub relock_delay: i64,
    pub day: DayLock,
}

impl Rules {
    pub fn from(settings: &LockSettings, day: Day) -> Self {
        Rules {
            cutoff: settings.cutoff_minutes * MINUTE,
            warn_before_cutoff: settings.warn_before_cutoff_minutes * MINUTE,
            warn_before_lock: settings.warn_before_lock_minutes * MINUTE,
            postpone: settings.postpone_minutes * MINUTE,
            max_postponements: settings.max_postponements,
            locked: settings.locked_minutes * MINUTE,
            return_window: settings.return_window_minutes * MINUTE,
            relock_delay: settings.relock_delay_seconds * 1000,
            day: *settings.day(weekday(day)),
        }
    }
}

/// The time after a lock during which the PC must stay locked.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Period {
    /// Windows was seen locked since the period began.
    pub confirmed: bool,
    /// Until the period ends or, when its length is zero, until retries stop.
    pub left: Countdown,
    /// The one warning shown when the app starts during this period.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub startup: Option<Countdown>,
}

/// One day's PC lock, named by its original local date.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Occurrence {
    pub day: Day,
    pub postponed: i64,
    pub postponements: i64,
    pub skipped: bool,
    /// Turned off, or turned on too late to apply to this date.
    pub cancelled: bool,
    pub done: bool,
    pub lock_dismissed: bool,
    /// The cutoff instant whose warning was dismissed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cutoff_dismissed: Option<i64>,
    /// The cutoff instant whose warning was shown.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cutoff_shown: Option<i64>,
    pub rules: Rules,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fixed: Option<Fixed>,
    /// The late-return warning.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub late: Option<Countdown>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub period: Option<Period>,
    /// The short countdown of a second late return. It runs only while the PC
    /// is awake, so sleeping through it does not use it up, and it is saved,
    /// so restarting the app does not start it again.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub late_short: Option<AwakeCountdown>,
}

impl Occurrence {
    pub fn new(day: Day, settings: &LockSettings) -> Self {
        Occurrence {
            day,
            postponed: 0,
            postponements: 0,
            skipped: false,
            cancelled: false,
            done: false,
            lock_dismissed: false,
            cutoff_dismissed: None,
            cutoff_shown: None,
            rules: Rules::from(settings, day),
            fixed: None,
            late: None,
            period: None,
            late_short: None,
        }
    }

    /// Bring values from an edited or damaged file into their allowed ranges.
    pub fn sanitize(&mut self, now: Moment) {
        let r = &mut self.rules;
        r.cutoff = r.cutoff.clamp(0, 720 * MINUTE);
        r.warn_before_cutoff = r.warn_before_cutoff.clamp(0, 120 * MINUTE);
        r.warn_before_lock = r.warn_before_lock.clamp(0, 30 * MINUTE);
        r.postpone = r.postpone.clamp(MINUTE, 240 * MINUTE);
        r.max_postponements = r.max_postponements.clamp(0, 10);
        r.locked = r.locked.clamp(0, 120 * MINUTE);
        r.return_window = r.return_window.clamp(0, 240 * MINUTE);
        r.relock_delay = r.relock_delay.clamp(5_000, 300_000);
        self.postponed = self.postponed.clamp(0, 10 * 240 * MINUTE);
        self.postponements = self.postponements.clamp(0, 10);
        let cap = |c: &mut Countdown, most: i64| c.remaining = c.remaining.min(most);
        if let Some(p) = self.period.as_mut() {
            cap(&mut p.left, self.rules.locked.max(MINUTE));
            if let Some(s) = p.startup.as_mut() {
                cap(s, MINUTE);
            }
        }
        if let Some(late) = self.late.as_mut() {
            cap(late, MINUTE);
        }
        if let Some(short) = self.late_short.as_mut() {
            short.remaining = short.remaining.min(self.rules.relock_delay);
        }
        if let Some(f) = self.fixed.as_mut() {
            f.remaining = f.remaining.min(self.rules.cutoff);
            f.reanchor(now);
        }
    }

    fn open(&self) -> bool {
        !self.skipped && !self.cancelled && !self.done
    }

    /// Not yet attempted. A missed occurrence is still pending.
    pub fn pending(&self) -> bool {
        self.open() && self.period.is_none()
    }

    /// In its locked period.
    pub fn active(&self) -> bool {
        self.open() && self.period.is_some()
    }

    pub fn lock_instant(&self, zone: &dyn Zone) -> i64 {
        match self.fixed {
            Some(f) => f.instant,
            None => zone.instant(self.day, self.rules.day.time.0) + self.postponed,
        }
    }

    pub fn cutoff_instant(&self, zone: &dyn Zone) -> i64 {
        self.lock_instant(zone) - self.rules.cutoff
    }

    /// Milliseconds until the lock, negative once it is late.
    pub fn remaining(&self, now: Moment, zone: &dyn Zone) -> i64 {
        match &self.fixed {
            Some(f) => f.remaining(now),
            None => self.lock_instant(zone) - now.wall,
        }
    }

    /// Too late to lock any more. Derived rather than stored, so moving the
    /// clock forward and back does not discard the lock.
    pub fn missed(&self, now: Moment, zone: &dyn Zone) -> bool {
        -self.remaining(now, zone) > self.rules.return_window && !self.warning_of_late_return()
    }

    /// A late-return countdown is running.
    pub fn warning_of_late_return(&self) -> bool {
        self.pending() && (self.late_short.is_some() || self.late.is_some_and(|d| d.running()))
    }

    /// Settings may no longer change this lock.
    pub fn immutable(&self) -> bool {
        self.period.is_some() || (self.fixed.is_some() && self.rules.day.strict)
    }

    pub fn postponements_left(&self) -> i64 {
        (self.rules.max_postponements - self.postponements).max(0)
    }
}