taskbar-focus 0.6.0

A tiny Pomodoro/focus timer that lives in the Windows tray and toggles Do Not Disturb
//! Local time: turning a date and time into an instant, and showing and reading
//! times the way Windows is set to.

use windows::core::PCWSTR;
use windows::Win32::Foundation::{FILETIME, SYSTEMTIME};
use windows::Win32::Globalization::{
    GetLocaleInfoEx, GetTimeFormatEx, LOCALE_S1159, LOCALE_S2359, LOCALE_SSHORTTIME,
    TIME_FORMAT_FLAGS,
};
use windows::Win32::System::Time::{
    FileTimeToSystemTime, SystemTimeToFileTime, SystemTimeToTzSpecificLocalTime,
    TzSpecificLocalTimeToSystemTime,
};

use crate::lock::settings::{weekday, ClockTime, Day, MINUTE};
use crate::lock::Zone;

const DAY_MS: i64 = 24 * 60 * MINUTE;
/// 1970-01-01 as a `FILETIME`, in milliseconds.
const UNIX_EPOCH_MS: i64 = 11_644_473_600_000;

/// Weekday names, Monday first, matching [`weekday`].
pub const DAY_NAMES: [&str; 7] = [
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
    "Sunday",
];

/// The time zone Windows is set to.
pub struct Local;

impl Zone for Local {
    /// A time skipped by daylight saving moves forward by the gap, and a
    /// repeated one uses the first.
    ///
    /// Windows resolves a skipped time to an instant before the gap, so the
    /// result is converted back and any shortfall is added.
    fn instant(&self, day: Day, minutes: u16) -> i64 {
        let wanted = day * DAY_MS + i64::from(minutes) * MINUTE;
        let utc = local_to_utc(wanted).unwrap_or(wanted);
        let shown = utc_to_local(utc).unwrap_or(wanted);
        utc + (wanted - shown).max(0)
    }

    fn day_of(&self, wall: i64) -> Day {
        utc_to_local(wall).unwrap_or(wall).div_euclid(DAY_MS)
    }
}

fn to_system(ms: i64) -> Option<SYSTEMTIME> {
    let ticks = ((ms + UNIX_EPOCH_MS) * 10_000) as u64;
    let file = FILETIME {
        dwLowDateTime: ticks as u32,
        dwHighDateTime: (ticks >> 32) as u32,
    };
    let mut out = SYSTEMTIME::default();
    unsafe { FileTimeToSystemTime(&file, &mut out) }.ok()?;
    Some(out)
}

fn from_system(time: &SYSTEMTIME) -> Option<i64> {
    let mut file = FILETIME::default();
    unsafe { SystemTimeToFileTime(time, &mut file) }.ok()?;
    let ticks = (u64::from(file.dwHighDateTime) << 32) | u64::from(file.dwLowDateTime);
    Some((ticks / 10_000) as i64 - UNIX_EPOCH_MS)
}

fn local_to_utc(local: i64) -> Option<i64> {
    let mut utc = SYSTEMTIME::default();
    unsafe { TzSpecificLocalTimeToSystemTime(None, &to_system(local)?, &mut utc) }.ok()?;
    from_system(&utc)
}

fn utc_to_local(utc: i64) -> Option<i64> {
    let mut local = SYSTEMTIME::default();
    unsafe { SystemTimeToTzSpecificLocalTime(None, &to_system(utc)?, &mut local) }.ok()?;
    from_system(&local)
}

fn locale(what: u32) -> String {
    let mut buffer = [0u16; 80];
    let n = unsafe { GetLocaleInfoEx(PCWSTR::null(), what, Some(&mut buffer)) };
    String::from_utf16_lossy(&buffer[..(n as usize).saturating_sub(1)])
}

/// The time of day at an instant, in the Windows short format.
pub fn format_instant(wall: i64) -> String {
    let local = utc_to_local(wall).unwrap_or(wall).rem_euclid(DAY_MS);
    format_time(ClockTime((local / MINUTE) as u16))
}

/// The time at an instant, with the weekday unless it is today.
pub fn format_when(wall: i64, now: i64) -> String {
    let day = Local.day_of(wall);
    let time = format_instant(wall);
    let name = DAY_NAMES[weekday(day)];
    match day - Local.day_of(now) {
        0 => time,
        7.. => format!("next {name} {time}"),
        _ => format!("{name} {time}"),
    }
}

/// A time of day in the Windows short format.
pub fn format_time(time: ClockTime) -> String {
    let (h, m) = (time.0 / 60, time.0 % 60);
    let system = SYSTEMTIME {
        wYear: 2000,
        wMonth: 1,
        wDay: 1,
        wHour: h,
        wMinute: m,
        ..Default::default()
    };
    let pattern: Vec<u16> = locale(LOCALE_SSHORTTIME)
        .encode_utf16()
        .chain([0])
        .collect();
    let mut buffer = [0u16; 80];
    let n = unsafe {
        GetTimeFormatEx(
            PCWSTR::null(),
            TIME_FORMAT_FLAGS(0),
            Some(&system),
            PCWSTR(pattern.as_ptr()),
            Some(&mut buffer),
        )
    };
    match n {
        n if n > 1 => String::from_utf16_lossy(&buffer[..n as usize - 1]),
        _ => format!("{h}:{m:02}"),
    }
}

/// The words Windows uses for morning and afternoon when it is set to a
/// 12-hour clock, or `None` for a 24-hour clock.
///
/// The clock is 12-hour when the short time pattern has an `h` outside quoted
/// text, so a pattern such as `HH 'h' mm` counts as 24-hour.
pub fn day_halves() -> Option<[String; 2]> {
    let pattern = locale(LOCALE_SSHORTTIME);
    let twelve_hour = pattern
        .split('\'')
        .step_by(2)
        .any(|unquoted| unquoted.contains('h'));
    if !twelve_hour {
        return None;
    }
    let or = |text: String, fallback: &str| match text.trim() {
        "" => fallback.to_string(),
        word => word.to_string(),
    };
    Some([
        or(locale(LOCALE_S1159), "AM"),
        or(locale(LOCALE_S2359), "PM"),
    ])
}