wallswitch 0.55.0

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

const MAX_ITENS: usize = 10_000;

/// Representa as informações cacheadas de um arquivo para evitar re-hashing
#[derive(Debug, Serialize, Deserialize, Default, Clone)]
pub struct CacheEntry {
    pub size: u64,
    pub mtime: u64,
    pub hash: String,
}

/// Gerencia o Histórico de Papéis de Parede e o Cache Inteligente de Hashes
#[derive(Debug, Serialize, Deserialize, Default)]
pub struct State {
    pub history: Vec<PathBuf>,
    pub hashes: HashMap<PathBuf, CacheEntry>,
}

impl State {
    /// Carrega o estado do arquivo JSON. Se não existir ou for inválido, retorna o padrão.
    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()
    }

    /// Salva o estado atual no arquivo JSON
    pub fn save(&mut self) -> WallSwitchResult<()> {
        // Limita o histórico aos últimos MAX_ITENS itens para não crescer infinitamente
        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)?;
        }

        let file = fs::File::create(path)?;
        serde_json::to_writer_pretty(file, self)?;
        Ok(())
    }

    /// Limpa caminhos de cache que não existem mais (Garbage Collection)
    pub fn garbage_collect(&mut self) {
        self.hashes.retain(|path, _| path.exists());
    }

    /// Retorna o caminho do arquivo state (~/.config/wallswitch/wallswitch-state.json)
    fn get_path() -> WallSwitchResult<PathBuf> {
        let mut path = get_config_path()?;
        path.set_file_name("wallswitch-state.json");
        Ok(path)
    }
}