taskbar-focus 0.6.0

A tiny Pomodoro/focus timer that lives in the Windows tray and toggles Do Not Disturb
//! Saving the lock engine's state as `lock.toml`, next to the settings.

use super::Saved;
use std::io::Write as _;
use std::path::PathBuf;

const FILE: &str = "lock.toml";
const READ_RETRIES: u32 = 10;
/// `ERROR_SHARING_VIOLATION`.
const SHARING_VIOLATION: i32 = 32;

fn is_sharing(e: &std::io::Error) -> bool {
    e.raw_os_error() == Some(SHARING_VIOLATION)
}

fn path() -> Option<PathBuf> {
    crate::config::app_dir().map(|d| d.join(FILE))
}

/// The saved state, or why there is none.
pub enum Loaded {
    Ready(Saved),
    /// The file made no sense and was set aside.
    Damaged,
    /// The file is there but could not be read, so it must not be replaced.
    Inaccessible,
}

/// Load the saved state. Another program may hold the file for a moment, so a
/// failed read is repeated.
pub fn load() -> Loaded {
    let Some(path) = path() else {
        return Loaded::Ready(Saved::default());
    };
    let mut read = std::fs::read_to_string(&path);
    for _ in 0..READ_RETRIES {
        match &read {
            Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied || is_sharing(e) => {
                std::thread::sleep(std::time::Duration::from_millis(100));
                read = std::fs::read_to_string(&path);
            }
            _ => break,
        }
    }
    let problem = match read {
        Ok(text) => match toml::from_str(&text) {
            Ok(saved) => return Loaded::Ready(saved),
            Err(e) => e.to_string(),
        },
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            return Loaded::Ready(Saved::default())
        }
        Err(e) if e.kind() == std::io::ErrorKind::InvalidData => e.to_string(),
        Err(e) => {
            crate::audit::log(&format!("lock: lock.toml could not be read: {e}"));
            return Loaded::Inaccessible;
        }
    };
    if let Err(e) = std::fs::rename(&path, path.with_extension("toml.bad")) {
        crate::audit::log(&format!("lock: lock.toml could not be set aside: {e}"));
    }
    crate::audit::log(&format!("lock: lock.toml was unreadable: {problem}"));
    Loaded::Damaged
}

/// Replace the file. It is flushed before the replacement, so neither a crash
/// nor a power cut leaves a truncated file behind.
pub fn save(saved: &Saved) -> std::io::Result<()> {
    let path = path().ok_or(std::io::ErrorKind::NotFound)?;
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir)?;
    }
    let text = toml::to_string_pretty(saved).map_err(std::io::Error::other)?;
    let tmp = path.with_extension("toml.tmp");
    let mut file = std::fs::File::create(&tmp)?;
    file.write_all(text.as_bytes())?;
    file.sync_all()?;
    drop(file);
    std::fs::rename(&tmp, &path)
}