taskbar-focus 0.6.0

A tiny Pomodoro/focus timer that lives in the Windows tray and toggles Do Not Disturb
//! What the user should currently see: the card on screen and the tray line.

use super::occurrence::{Countdown, Occurrence};
use super::settings::{weekday, Day, MINUTE};
use super::{Enforcer, Engine, Moment, Session, Zone};

/// What a button on a card does.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Action {
    Postpone,
    SkipLate,
    EndPeriod,
    Dismiss,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CardKind {
    /// The cutoff is near, or has passed with its warning still open.
    Cutoff { passed: bool },
    /// The lock is near.
    Upcoming,
    /// Returned after the lock time.
    Late,
    /// The app started during a locked period.
    Startup,
    /// Unlocked during a locked period.
    Relock,
    /// Windows did not lock.
    Failed,
}

/// A card that should be on screen.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Card {
    pub kind: CardKind,
    pub day: Day,
    /// The lock time, or the end of the locked period, in Unix ms.
    pub at: i64,
    pub cutoff: i64,
    /// Seconds until the PC locks, for countdown cards.
    pub seconds: Option<i64>,
    pub postpone_minutes: i64,
    pub actions: Vec<Action>,
}

/// What the tray menu shows.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Status {
    Hidden,
    /// A lock can still be postponed or skipped.
    Open {
        day: Day,
        lock: i64,
        cutoff: i64,
        left: i64,
        strict: bool,
        today: bool,
        postpone_minutes: i64,
    },
    CutoffPassed {
        lock: i64,
    },
    Next {
        lock: i64,
    },
    Skipped {
        next: Option<i64>,
    },
    Late {
        can_skip: bool,
    },
    LockedUntil {
        end: i64,
        can_end: bool,
    },
}

impl Engine {
    /// The card that should be on screen, the most urgent first.
    pub fn card(&mut self, now: Moment, session: Session, zone: &dyn Zone) -> Option<Card> {
        if !session.present() || self.held.is_some() {
            return None;
        }
        self.period_card(now)
            .or_else(|| self.late_card(zone))
            .or_else(|| self.upcoming_card(now, zone))
            .or_else(|| self.cutoff_card(now, zone))
    }

    /// Close a card without changing the lock.
    pub fn dismiss(&mut self, card: &Card) {
        let cutoff = card.cutoff;
        match card.kind {
            CardKind::Failed => self.failure_dismissed = true,
            CardKind::Late | CardKind::Startup | CardKind::Relock => {
                self.countdown_dismissed = true
            }
            CardKind::Cutoff { .. } => {
                self.change_day(card.day, |o| o.cutoff_dismissed = Some(cutoff))
            }
            CardKind::Upcoming => self.change_day(card.day, |o| o.lock_dismissed = true),
        }
    }

    fn change_day(&mut self, day: Day, change: impl Fn(&mut Occurrence)) {
        self.saved
            .occurrences
            .iter_mut()
            .filter(|o| o.day == day)
            .for_each(change);
        self.dirty = true;
    }

    fn period_card(&self, now: Moment) -> Option<Card> {
        let (day, period) = self
            .saved
            .occurrences
            .iter()
            .filter(|o| o.active())
            .filter_map(|o| o.period.as_ref().map(|p| (o.day, p)))
            .max_by_key(|(_, p)| p.left.remaining)?;
        let (kind, ms) = match self.enforcer {
            Enforcer::Relock { until } => (CardKind::Relock, Some(until - now.awake)),
            Enforcer::Startup => {
                let warning = period.startup.filter(Countdown::running)?;
                (CardKind::Startup, Some(warning.remaining))
            }
            Enforcer::Retry { .. } | Enforcer::Attempting { .. } if self.failure_reported => {
                (CardKind::Failed, None)
            }
            _ => return None,
        };
        let dismissed = match kind {
            CardKind::Failed => self.failure_dismissed,
            _ => self.countdown_dismissed,
        };
        if dismissed {
            return None;
        }
        let end = self.can_end().then_some(Action::EndPeriod);
        Some(Card {
            kind,
            day,
            at: now.wall + period.left.remaining,
            cutoff: 0,
            seconds: ms.map(whole_seconds),
            postpone_minutes: 0,
            actions: with_dismiss(end),
        })
    }

    fn late_card(&self, zone: &dyn Zone) -> Option<Card> {
        if self.countdown_dismissed {
            return None;
        }
        let o = self
            .saved
            .occurrences
            .iter()
            .find(|o| o.warning_of_late_return())?;
        let left = match o.late_short {
            Some(short) => short.remaining,
            None => o.late?.remaining,
        };
        let skip = (!o.rules.day.strict).then_some(Action::SkipLate);
        Some(Card {
            kind: CardKind::Late,
            day: o.day,
            at: o.lock_instant(zone),
            cutoff: 0,
            seconds: Some(whole_seconds(left)),
            postpone_minutes: 0,
            actions: with_dismiss(skip),
        })
    }

    fn upcoming_card(&self, now: Moment, zone: &dyn Zone) -> Option<Card> {
        let o = self.saved.occurrences.iter().find(|o| {
            let left = o.remaining(now, zone);
            o.pending() && !o.lock_dismissed && left > 0 && left <= o.rules.warn_before_lock
        })?;
        Some(Card {
            kind: CardKind::Upcoming,
            day: o.day,
            at: now.wall + o.remaining(now, zone),
            cutoff: 0,
            seconds: None,
            postpone_minutes: 0,
            actions: with_dismiss(None),
        })
    }

    /// Shown from before the cutoff until dismissed. It repeats before a moved
    /// cutoff only while another postponement remains.
    fn cutoff_card(&mut self, now: Moment, zone: &dyn Zone) -> Option<Card> {
        let o = self.saved.occurrences.iter_mut().find(|o| {
            let cutoff = o.cutoff_instant(zone);
            let shown = o.cutoff_shown == Some(cutoff);
            let may_show = o.postponements == 0 || o.postponements_left() > 0;
            o.pending()
                && o.rules.warn_before_cutoff > 0
                && o.cutoff_dismissed != Some(cutoff)
                && o.remaining(now, zone) > 0
                && cutoff - now.wall <= o.rules.warn_before_cutoff
                && (shown || (may_show && o.fixed.is_none()))
        })?;
        let cutoff = o.cutoff_instant(zone);
        self.dirty |= o.cutoff_shown != Some(cutoff);
        o.cutoff_shown = Some(cutoff);
        let passed = o.fixed.is_some();
        let postpone = (!passed && o.postponements_left() > 0).then_some(Action::Postpone);
        Some(Card {
            kind: CardKind::Cutoff { passed },
            day: o.day,
            at: now.wall + o.remaining(now, zone),
            cutoff,
            seconds: None,
            postpone_minutes: o.rules.postpone / MINUTE,
            actions: with_dismiss(postpone),
        })
    }

    pub fn status(&self, now: Moment, zone: &dyn Zone) -> Status {
        let all = &self.saved.occurrences;
        let active = all.iter().filter(|o| o.active());
        if let Some(left) = active
            .filter_map(|o| o.period.as_ref())
            .map(|p| p.left.remaining)
            .max()
        {
            return Status::LockedUntil {
                end: now.wall + left,
                can_end: self.can_end(),
            };
        }
        if let Some(o) = all.iter().find(|o| o.warning_of_late_return()) {
            return Status::Late {
                can_skip: !o.rules.day.strict,
            };
        }
        if let Some(left) = all
            .iter()
            .filter(|o| o.pending() && o.fixed.is_some() && !o.missed(now, zone))
            .map(|o| o.remaining(now, zone))
            .min()
        {
            return Status::CutoffPassed {
                lock: now.wall + left,
            };
        }
        let today = zone.day_of(now.wall);
        if let Some(i) = self.adjustable(now, zone) {
            let o = &all[i];
            return Status::Open {
                day: o.day,
                lock: o.lock_instant(zone),
                cutoff: o.cutoff_instant(zone),
                left: o.postponements_left(),
                strict: o.rules.day.strict,
                today: o.day == today,
                postpone_minutes: o.rules.postpone / MINUTE,
            };
        }
        let next = self.next_lock(now, zone);
        if all.iter().any(|o| o.skipped && o.day == today) {
            return Status::Skipped { next };
        }
        next.map_or(Status::Hidden, |lock| Status::Next { lock })
    }

    fn next_lock(&self, now: Moment, zone: &dyn Zone) -> Option<i64> {
        let today = zone.day_of(now.wall);
        (today..=today + 7)
            .filter_map(|day| match self.find(day) {
                Some(o) => o.pending().then(|| o.lock_instant(zone)),
                None => {
                    let d = self.saved.accepted.day(weekday(day));
                    d.enabled.then(|| zone.instant(day, d.time.0))
                }
            })
            .filter(|&at| at > now.wall)
            .min()
    }
}

fn with_dismiss(first: Option<Action>) -> Vec<Action> {
    first.into_iter().chain([Action::Dismiss]).collect()
}

fn whole_seconds(ms: i64) -> i64 {
    (ms.max(0) + 999) / 1000
}