feat: expand launcher settings

This commit is contained in:
objz committed 2026-09-04 20:57:07 +02:00
1 parent e8d67322b0
commit 53191bc23b
35 files changed
+1540 -266

No files matched your search

+140 -28
View File
@@ -6,6 +6,7 @@
use config::{Config as ConfigLoader, ConfigError, File};
use std::fs;
use std::io;
use std::path::PathBuf;
use std::sync::{LazyLock, RwLock, RwLockReadGuard};
@@ -53,7 +54,17 @@ pub fn load_config(config_path: &std::path::Path) -> Result<Config, ConfigError>
ConfigLoader::builder()
.add_source(File::from(config_path).required(false))
.build()?
.try_deserialize()
.try_deserialize::<Config>()
.map(Config::normalize)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LauncherSettingsSave {
pub restart_required: bool,
pub restart_changed: bool,
pub provider_changed: bool,
pub modpack_updates_enabled: bool,
pub content_updates_enabled: bool,
}
pub struct ConfigStore(RwLock<Config>);
@@ -65,34 +76,62 @@ impl ConfigStore {
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
pub fn save_launcher_settings(&self, edited: Config) -> std::io::Result<()> {
pub fn save_launcher_settings(&self, edited: Config) -> io::Result<LauncherSettingsSave> {
let path = get_config_path().join("config.toml");
let current = self.read().clone();
let mut persisted = load_config(&path).unwrap_or_else(|error| {
tracing::warn!("Failed to merge config.toml while saving settings: {error}");
current.clone()
});
persisted.defaults = edited.defaults.clone();
persisted.paths.java_path = edited.paths.java_path.clone();
let serialized = toml::to_string_pretty(&persisted).map_err(std::io::Error::other)?;
crate::storage::write_atomic(&path, serialized.as_bytes())?;
let mut runtime = current;
runtime.defaults = edited.defaults;
runtime.paths.java_path = edited.paths.java_path;
let edited = edited.normalize();
let persisted = load_config(&path).unwrap_or_else(|_| current.clone());
let restart_required = current.paths.instances_dir != edited.paths.instances_dir
|| current.paths.meta_dir != edited.paths.meta_dir
|| current.ui.image_protocol != edited.ui.image_protocol;
let restart_changed = persisted.paths.instances_dir != edited.paths.instances_dir
|| persisted.paths.meta_dir != edited.paths.meta_dir
|| persisted.ui.image_protocol != edited.ui.image_protocol;
let provider_changed = current.content.preferred_provider
!= edited.content.preferred_provider
|| current.content.preferred_provider_only != edited.content.preferred_provider_only;
let modpack_updates_enabled =
!current.general.check_modpack_updates && edited.general.check_modpack_updates;
let content_updates_enabled =
!current.general.check_content_updates && edited.general.check_content_updates;
write_config_document(&path, &edited)?;
let mut runtime = edited;
runtime
.paths
.instances_dir
.clone_from(&current.paths.instances_dir);
runtime.paths.meta_dir.clone_from(&current.paths.meta_dir);
runtime.ui.image_protocol = current.ui.image_protocol;
*self
.0
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner) = runtime;
Ok(())
crate::feedback::errors::set_max_error_events(self.read().ui.max_error_events);
Ok(LauncherSettingsSave {
restart_required,
restart_changed,
provider_changed,
modpack_updates_enabled,
content_updates_enabled,
})
}
pub fn reload(&self) -> Result<bool, ConfigError> {
pub fn reload(&self) -> Result<LauncherSettingsSave, ConfigError> {
let mut config = load_config(&get_config_path().join("config.toml"))?;
let restart_required = {
let outcome = {
let current = self.read();
let changed = current.paths.instances_dir != config.paths.instances_dir
let restart_required = current.paths.instances_dir != config.paths.instances_dir
|| current.paths.meta_dir != config.paths.meta_dir
|| current.ui.image_protocol != config.ui.image_protocol;
let provider_changed = current.content.preferred_provider
!= config.content.preferred_provider
|| current.content.preferred_provider_only
!= config.content.preferred_provider_only;
let modpack_updates_enabled =
!current.general.check_modpack_updates && config.general.check_modpack_updates;
let content_updates_enabled =
!current.general.check_content_updates && config.general.check_content_updates;
// App owns a manager and several watchers rooted at these paths.
// Keep them stable for this process; persisted path edits apply on restart.
config
@@ -101,32 +140,105 @@ impl ConfigStore {
.clone_from(&current.paths.instances_dir);
config.paths.meta_dir.clone_from(&current.paths.meta_dir);
config.ui.image_protocol = current.ui.image_protocol;
changed
LauncherSettingsSave {
restart_required,
restart_changed: restart_required,
provider_changed,
modpack_updates_enabled,
content_updates_enabled,
}
};
*self
.0
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner) = config;
Ok(restart_required)
crate::feedback::errors::set_max_error_events(self.read().ui.max_error_events);
Ok(outcome)
}
}
pub static SETTINGS: LazyLock<ConfigStore> = LazyLock::new(|| {
ConfigStore(RwLock::new({
let config = {
let path = ensure_config_exists();
load_config(&path).unwrap_or_else(|e| {
tracing::error!("Config load failed, using defaults: {}", e);
Config {
general: settings::General::default(),
paths: settings::Paths::default(),
defaults: settings::Defaults::default(),
ui: settings::Ui::default(),
content: settings::Content::default(),
}
Config::default()
})
}))
};
crate::feedback::errors::set_max_error_events(config.ui.max_error_events);
ConfigStore(RwLock::new(config))
});
fn write_config_document(path: &std::path::Path, config: &Config) -> io::Result<()> {
let source = match fs::read_to_string(path) {
Ok(source) => source,
Err(error) if error.kind() == io::ErrorKind::NotFound => String::new(),
Err(error) => return Err(error),
};
let mut document = source.parse::<toml_edit::DocumentMut>().map_err(|error| {
io::Error::new(
io::ErrorKind::InvalidData,
format!("cannot update {}: {error}", path.display()),
)
})?;
let generated = toml::to_string_pretty(config)
.map_err(io::Error::other)?
.parse::<toml_edit::DocumentMut>()
.map_err(io::Error::other)?;
merge_table(document.as_table_mut(), generated.as_table());
if config.paths.java_path.is_none()
&& let Some(paths) = document
.get_mut("paths")
.and_then(|item| item.as_table_mut())
{
paths.remove("java_path");
}
let default_paths = settings::Paths::default();
if let Some(paths) = document
.get_mut("paths")
.and_then(|item| item.as_table_mut())
{
if config.paths.instances_dir == default_paths.instances_dir {
paths.remove("instances_dir");
}
if config.paths.meta_dir == default_paths.meta_dir {
paths.remove("meta_dir");
}
}
if config.defaults.resolution.is_none()
&& let Some(defaults) = document
.get_mut("defaults")
.and_then(|item| item.as_table_mut())
{
defaults.remove("resolution");
}
crate::storage::write_atomic(path, document.to_string().as_bytes())
}
fn merge_table(target: &mut toml_edit::Table, source: &toml_edit::Table) {
for (key, source_item) in source {
if let Some(target_item) = target.get_mut(key) {
if let (Some(target_table), Some(source_table)) =
(target_item.as_table_mut(), source_item.as_table())
{
merge_table(target_table, source_table);
continue;
}
if let (Some(target_value), Some(source_value)) =
(target_item.as_value_mut(), source_item.as_value())
{
let decor = target_value.decor().clone();
*target_value = source_value.clone();
*target_value.decor_mut() = decor;
continue;
}
*target_item = source_item.clone();
} else {
target.insert(key, source_item.clone());
}
}
}
#[cfg(test)]
#[path = "tests/loading.rs"]
mod tests;
+131 -11
View File
@@ -4,29 +4,84 @@
// all the config structs that map to sections in config.toml.
// everything has sane defaults so a blank file (or no file) still works.
use std::path::PathBuf;
use std::{collections::BTreeMap, fmt, path::PathBuf};
use serde::{Deserialize, Serialize};
use crate::instance::models::{WindowMode, memory_kib, normalize_memory_value};
#[derive(Debug, Serialize, Deserialize, Default, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ImageProtocol {
#[default]
Auto,
Halfblocks,
Quadrants,
#[default]
Kitty,
Iterm2,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct General {}
impl fmt::Display for ImageProtocol {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Auto => formatter.write_str("auto"),
Self::Halfblocks => formatter.write_str("halfblocks"),
Self::Quadrants => formatter.write_str("quadrants"),
Self::Kitty => formatter.write_str("kitty"),
Self::Iterm2 => formatter.write_str("iterm2"),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct General {
#[serde(default = "default_true")]
pub check_modpack_updates: bool,
#[serde(default = "default_true")]
pub check_content_updates: bool,
}
impl Default for General {
fn default() -> Self {
Self {
check_modpack_updates: true,
check_content_updates: true,
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ContentProvider {
#[default]
Modrinth,
CurseForge,
}
impl ContentProvider {
pub fn as_str(self) -> &'static str {
match self {
Self::Modrinth => "modrinth",
Self::CurseForge => "curseforge",
}
}
}
impl fmt::Display for ContentProvider {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Modrinth => formatter.write_str("Modrinth"),
Self::CurseForge => formatter.write_str("CurseForge"),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Content {
#[serde(default = "default_true")]
pub ask_on_provider_conflict: bool,
#[serde(default = "default_provider")]
pub preferred_provider: String,
#[serde(default, deserialize_with = "deserialize_content_provider")]
pub preferred_provider: ContentProvider,
#[serde(default)]
pub preferred_provider_only: bool,
#[serde(default = "default_unmatched_retry_hours")]
@@ -39,8 +94,16 @@ fn default_true() -> bool {
true
}
fn default_provider() -> String {
"modrinth".to_owned()
fn deserialize_content_provider<'de, D>(deserializer: D) -> Result<ContentProvider, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
Ok(if value.eq_ignore_ascii_case("curseforge") {
ContentProvider::CurseForge
} else {
ContentProvider::Modrinth
})
}
fn default_unmatched_retry_hours() -> u64 {
@@ -55,7 +118,7 @@ impl Default for Content {
fn default() -> Self {
Self {
ask_on_provider_conflict: true,
preferred_provider: default_provider(),
preferred_provider: ContentProvider::default(),
preferred_provider_only: false,
unmatched_retry_hours: default_unmatched_retry_hours(),
max_fingerprint_size_mib: default_max_fingerprint_size_mib(),
@@ -80,7 +143,7 @@ impl Content {
}
fn preferred_provider_with_curseforge(&self, curseforge_available: bool) -> &'static str {
if self.preferred_provider.eq_ignore_ascii_case("curseforge") && curseforge_available {
if self.preferred_provider == ContentProvider::CurseForge && curseforge_available {
"curseforge"
} else {
"modrinth"
@@ -122,10 +185,13 @@ impl Content {
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Paths {
#[serde(default = "default_instances_dir")]
#[serde(skip_serializing_if = "is_default_instances_dir")]
pub instances_dir: String,
#[serde(default = "default_meta_dir")]
#[serde(skip_serializing_if = "is_default_meta_dir")]
pub meta_dir: String,
#[serde(default)]
#[serde(skip_serializing_if = "Option::is_none")]
pub java_path: Option<String>,
}
@@ -138,6 +204,10 @@ fn default_instances_dir() -> String {
.into_owned()
}
fn is_default_instances_dir(path: &str) -> bool {
path == default_instances_dir()
}
fn default_meta_dir() -> String {
dirs_next::data_dir()
.unwrap_or_else(|| PathBuf::from("."))
@@ -147,6 +217,10 @@ fn default_meta_dir() -> String {
.into_owned()
}
fn is_default_meta_dir(path: &str) -> bool {
path == default_meta_dir()
}
impl Default for Paths {
fn default() -> Self {
Self {
@@ -191,6 +265,15 @@ pub struct Defaults {
pub memory_min: String,
#[serde(default = "default_memory_max")]
pub memory_max: String,
#[serde(default)]
pub jvm_args: Vec<String>,
#[serde(default)]
pub environment: BTreeMap<String, String>,
#[serde(default)]
pub window_mode: WindowMode,
#[serde(default)]
#[serde(skip_serializing_if = "Option::is_none")]
pub resolution: Option<(u32, u32)>,
}
fn default_memory_min() -> String {
@@ -205,6 +288,10 @@ impl Default for Defaults {
Self {
memory_min: default_memory_min(),
memory_max: default_memory_max(),
jvm_args: Vec::new(),
environment: BTreeMap::new(),
window_mode: WindowMode::default(),
resolution: None,
}
}
}
@@ -250,7 +337,7 @@ impl Default for Ui {
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Config {
#[serde(default)]
pub general: General,
@@ -264,6 +351,39 @@ pub struct Config {
pub content: Content,
}
impl Config {
pub fn normalize(mut self) -> Self {
if self.paths.instances_dir.trim().is_empty() {
self.paths.instances_dir = default_instances_dir();
}
if self.paths.meta_dir.trim().is_empty() {
self.paths.meta_dir = default_meta_dir();
}
self.paths.java_path = self
.paths
.java_path
.take()
.and_then(|path| (!path.trim().is_empty()).then(|| path.trim().to_owned()));
self.defaults.memory_min =
normalize_memory_value(&self.defaults.memory_min).unwrap_or_else(default_memory_min);
self.defaults.memory_max =
normalize_memory_value(&self.defaults.memory_max).unwrap_or_else(default_memory_max);
if memory_kib(&self.defaults.memory_min) > memory_kib(&self.defaults.memory_max) {
self.defaults
.memory_max
.clone_from(&self.defaults.memory_min);
}
self.ui.error_auto_dismiss_ms = self.ui.error_auto_dismiss_ms.max(1);
self.ui.error_slide_start_ms = self
.ui
.error_slide_start_ms
.min(self.ui.error_auto_dismiss_ms);
self.ui.error_fly_out_ms = self.ui.error_fly_out_ms.min(self.ui.error_auto_dismiss_ms);
self.ui.max_error_events = self.ui.max_error_events.max(1);
self
}
}
#[cfg(test)]
#[path = "tests/settings.rs"]
mod tests;
+73
View File
@@ -54,3 +54,76 @@ fn load_config_partial_sections() {
assert_eq!(config.paths.instances_dir, "/custom/path");
assert!(config.paths.java_path.is_none());
}
#[test]
fn bundled_config_uses_platform_paths_and_automatic_java() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("config.toml");
std::fs::write(&path, include_str!("../../../assets/config.toml")).unwrap();
let config = load_config(&path).unwrap();
assert_eq!(
config.paths.instances_dir,
settings::Paths::default().instances_dir
);
assert_eq!(config.paths.meta_dir, settings::Paths::default().meta_dir);
assert!(config.paths.java_path.is_none());
assert_eq!(config.ui.image_protocol, settings::ImageProtocol::Auto);
}
#[test]
fn config_normalizes_memory_java_and_notification_bounds() {
let config = Config {
paths: settings::Paths {
instances_dir: String::new(),
meta_dir: " ".to_owned(),
java_path: Some(" ".to_owned()),
},
defaults: settings::Defaults {
memory_min: "invalid".to_owned(),
memory_max: "1G".to_owned(),
..Default::default()
},
ui: settings::Ui {
error_auto_dismiss_ms: 100,
error_slide_start_ms: 200,
error_fly_out_ms: 300,
max_error_events: 0,
..Default::default()
},
..Default::default()
}
.normalize();
assert_eq!(
config.paths.instances_dir,
settings::Paths::default().instances_dir
);
assert_eq!(config.paths.meta_dir, settings::Paths::default().meta_dir);
assert!(config.paths.java_path.is_none());
assert_eq!(config.defaults.memory_min, "512M");
assert_eq!(config.defaults.memory_max, "1G");
assert_eq!(config.ui.error_slide_start_ms, 100);
assert_eq!(config.ui.error_fly_out_ms, 100);
assert_eq!(config.ui.max_error_events, 1);
}
#[test]
fn settings_writer_preserves_comments_and_unknown_keys() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("config.toml");
std::fs::write(
&path,
"# keep this comment\n[defaults]\n# heap comment\nmemory_max = \"2G\"\n\n[future]\nvalue = 42\n",
)
.unwrap();
let mut config = Config::default();
config.defaults.memory_max = "8G".to_owned();
write_config_document(&path, &config).unwrap();
let saved = std::fs::read_to_string(path).unwrap();
assert!(saved.contains("# keep this comment"), "{saved}");
assert!(saved.contains("# heap comment"), "{saved}");
assert!(saved.contains("memory_max = \"8G\""));
assert!(saved.contains("[future]"));
assert!(saved.contains("value = 42"));
assert!(!saved.contains("instances_dir"));
assert!(!saved.contains("meta_dir"));
}
+5
View File
@@ -66,6 +66,11 @@ fn content_provider_settings_are_normalized() {
merged.discovery_provider_label_with_curseforge(true),
"providers"
);
let legacy: Content = toml::from_str("preferred_provider = \"CurseForge\"").unwrap();
assert_eq!(legacy.preferred_provider, ContentProvider::CurseForge);
let unknown: Content = toml::from_str("preferred_provider = \"unknown\"").unwrap();
assert_eq!(unknown.preferred_provider, ContentProvider::Modrinth);
}
#[test]