wallswitch 0.63.1

randomly selects wallpapers for multiple monitors
Documentation
use crate::{Dimension, WallSwitchError, WallSwitchResult, get_config_path};
use serde::{Deserialize, Serialize};
use std::{
    collections::HashMap,
    fs,
    io::{BufWriter, Write},
    path::PathBuf,
};

const MAX_ITENS: usize = 10_000;

/// Represents cached metadata of an image file to prevent redundant hashing and dimension probing.
#[derive(Debug, Serialize, Deserialize, Default, Clone)]
pub struct CacheEntry {
    pub size: u64,
    pub mtime: u64,
    pub hash: String,
    #[serde(default)]
    pub dimension: Option<Dimension>,
}

/// Manages the persistence of the wallpaper history loop and the smart file cache.
#[derive(Debug, Serialize, Deserialize, Default)]
pub struct State {
    pub history: Vec<PathBuf>,
    pub hashes: HashMap<PathBuf, CacheEntry>,
}

impl State {
    /// Loads the saved application state from the JSON file on disk.
    ///
    /// If the file does not exist or fails to parse, a default initialized state is returned.
    pub fn load() -> Self {
        if let Ok(path) = Self::get_path()
            && let Ok(content) = fs::read_to_string(&path)
            && let Ok(state) = serde_json::from_str(&content)
        {
            return state;
        }
        State::default()
    }

    /// Persists the current wallpaper history and file hash cache atomically to disk.
    ///
    /// To ensure filesystem consistency and prevent file corruption during sudden
    /// process terminations, the state is written to a temporary file in the same
    /// directory and then atomically moved to the destination path.
    ///
    /// # Errors
    ///
    /// Returns a [`WallSwitchError::IOError`] if the creation of the temporary file,
    /// serialization, flushing, or renaming operation fails.
    pub fn save(&mut self) -> WallSwitchResult<()> {
        // Enforce maximum history capacity constraints
        if self.history.len() > MAX_ITENS {
            let start = self.history.len() - MAX_ITENS;
            self.history = self.history[start..].to_vec();
        }

        let path = Self::get_path()?;
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }

        // Generate temporary path in the same parent folder to guarantee atomic swapping
        let temp_ext = format!("tmp-{}", std::process::id());
        let temp_path = path.with_extension(temp_ext);

        {
            let file =
                fs::File::create(&temp_path).map_err(|io_error| WallSwitchError::IOError {
                    path: temp_path.clone(),
                    io_error,
                })?;
            let mut writer = BufWriter::new(file);
            serde_json::to_writer_pretty(&mut writer, self)?;
            writer.flush()?;
        }

        // Perform atomic rename swap
        fs::rename(&temp_path, &path).map_err(|io_error| WallSwitchError::IOError {
            path: path.clone(),
            io_error,
        })?;

        Ok(())
    }

    /// Removes untracked paths that no longer exist on the current filesystem from the cache.
    pub fn garbage_collect(&mut self) {
        self.hashes.retain(|path, _| path.exists());
        self.hashes.shrink_to_fit();
    }

    /// Resolves the absolute path to the application state JSON file.
    fn get_path() -> WallSwitchResult<PathBuf> {
        let mut path = get_config_path()?;
        path.set_file_name("wallswitch-state.json");
        Ok(path)
    }
}