//! Durable preferences, separate from the disposable cache. Reads never create files.
use crate::{Result, cache::atomic_write, paths::read_game_version};
use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
fs,
path::{Path, PathBuf},
time::Duration,
};
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Settings {
pub data_dir: Option<PathBuf>,
pub install_dir: Option<PathBuf>,
pub verify_downloads: bool,
pub ui_sounds_enabled: bool,
#[serde(deserialize_with = "sound_volume")]
pub ui_sound_volume: u8,
}
fn sound_volume<'de, D: serde::Deserializer<'de>>(
deserializer: D,
) -> std::result::Result<u8, D::Error> {
Ok(i64::deserialize(deserializer)?.clamp(0, 100) as u8)
}
impl Default for Settings {
fn default() -> Self {
Self {
data_dir: None,
install_dir: None,
verify_downloads: true,
ui_sounds_enabled: true,
ui_sound_volume: 50,
}
}
}
impl Settings {
pub fn catalogue_ttl(&self) -> Duration {
crate::portal_data::CATALOGUE_TTL
}
pub fn effective_install_dir(&self, env: &HashMap<String, String>) -> Option<PathBuf> {
env.get("FACTORIO_DIR")
.filter(|v| !v.is_empty())
.map(PathBuf::from)
.or_else(|| self.install_dir.clone())
}
pub fn effective_data_dir(&self, env: &HashMap<String, String>) -> PathBuf {
self.data_dir.clone().unwrap_or_else(|| {
let install = self.effective_install_dir(env);
crate::paths::find_factorio_with_env(install.as_deref(), env)
.ok()
.flatten()
.map(|p| p.user_dir)
.unwrap_or_else(|| crate::paths::default_user_dir(env))
})
}
pub fn from_inputs(data: &str, install: &str) -> Result<Self> {
let settings = Self {
data_dir: (!data.trim().is_empty()).then(|| PathBuf::from(data.trim())),
install_dir: (!install.trim().is_empty())
.then(|| crate::paths::game_dir(Path::new(install.trim()))),
..Default::default()
};
if settings.data_dir.is_none() {
return Err("Enter the Factorio data folder.".into());
}
settings.validate()?;
Ok(settings)
}
fn validate(&self) -> Result<()> {
if let Some(path) = &self.data_dir {
validate_data_dir(path)?;
}
if let Some(path) = &self.install_dir {
if !path.is_absolute() {
return Err("The install folder must be an absolute path.".into());
}
read_game_version(path).map_err(|e| {
format!("Cannot read data/base/info.json in that install folder: {e}")
})?;
}
Ok(())
}
}
pub fn validate_data_dir(path: &Path) -> Result<()> {
if !path.is_absolute() {
return Err("The data folder must be an absolute path.".into());
}
if !path.join("mods").is_dir() {
return Err("The data folder must contain a mods folder.".into());
}
crate::mod_list::read_mod_list(&path.join("mods/mod-list.json"))
.map_err(|e| format!("Cannot read mods/mod-list.json in that data folder: {e}"))?;
if !path.join("mods/mod-list.json").is_file() {
return Err("The data folder must contain mods/mod-list.json.".into());
}
Ok(())
}
pub fn settings_dir_with_env(env: &HashMap<String, String>) -> Result<PathBuf> {
crate::app_dirs::directory(env, crate::app_dirs::Kind::Settings)
}
pub fn settings_dir() -> Result<PathBuf> {
settings_dir_with_env(&std::env::vars().collect())
}
pub fn load(dir: &Path) -> Result<Settings> {
let bytes = match fs::read(dir.join("settings.json")) {
Ok(bytes) => bytes,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Settings::default()),
Err(e) => return Err(e.into()),
};
// Unknown fields (including the former catalogueRefreshHours) remain readable.
let mut settings: Settings = serde_json::from_slice(&bytes)?;
for path in [&mut settings.install_dir, &mut settings.data_dir] {
if path.as_ref().is_some_and(|p| p.as_os_str().is_empty()) {
*path = None;
}
}
Ok(settings)
}
pub fn save(dir: &Path, settings: &Settings) -> Result<()> {
settings.validate()?;
let mut bytes = serde_json::to_vec_pretty(settings)?;
bytes.push(b'\n');
atomic_write(&dir.join("settings.json"), &bytes)
}