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]
+8 -3
View File
@@ -9,15 +9,19 @@
// used by the render layer to track per-toast animation state.
use std::collections::VecDeque;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Instant;
use std::sync::LazyLock;
use tracing::Level;
const MAX_ERROR_EVENTS: usize = 50;
static NEXT_ERROR_ID: AtomicU64 = AtomicU64::new(1);
static MAX_ERROR_EVENTS: AtomicUsize = AtomicUsize::new(50);
pub(crate) fn set_max_error_events(max_events: usize) {
MAX_ERROR_EVENTS.store(max_events.max(1), Ordering::Relaxed);
}
#[derive(Debug, Clone)]
pub struct ErrorEvent {
@@ -38,7 +42,8 @@ pub fn push_error(event: ErrorEvent) {
events.push_back(event);
while events.len() > MAX_ERROR_EVENTS {
let max_events = MAX_ERROR_EVENTS.load(Ordering::Relaxed);
while events.len() > max_events {
events.pop_front();
}
super::request_redraw();
+4 -2
View File
@@ -72,13 +72,15 @@ fn overflow_drops_oldest() {
let _guard = TEST_LOCK.lock().unwrap();
clear_errors_for_test();
for i in 0..(MAX_ERROR_EVENTS + 10) {
let max_error_events = 50;
set_max_error_events(max_error_events);
for i in 0..(max_error_events + 10) {
push_error(make_event(&format!("overflow_{i}")));
}
let all = peek_all_errors();
assert_eq!(all.len(), MAX_ERROR_EVENTS);
assert_eq!(all.len(), max_error_events);
assert!(!all.iter().any(|e| e.message == "overflow_0"));
assert!(!all.iter().any(|e| e.message == "overflow_9"));
+20 -7
View File
@@ -386,6 +386,13 @@ pub async fn build_launch_invocation(
) -> Result<LaunchInvocation, LaunchError> {
let instance_dir = instances_dir.join(&config.name);
let minecraft_dir = instance_dir.join(crate::storage::MINECRAFT_DIR_NAME);
let (window_mode, resolution) = {
let defaults = &crate::config::SETTINGS.read().defaults;
(
config.effective_window_mode(defaults.window_mode),
config.effective_resolution(defaults.resolution),
)
};
let metadata_paths = crate::storage::MetadataPaths::new(meta_dir);
let meta_path = metadata_paths
@@ -407,7 +414,7 @@ pub async fn build_launch_invocation(
let current_features = FeatureSet {
is_quick_play_singleplayer: quick_play_world.map(|_| true),
has_custom_resolution: config.resolution.map(|_| true),
has_custom_resolution: resolution.map(|_| true),
..Default::default()
};
let host_os_version = system::mojang_os_version();
@@ -585,8 +592,8 @@ pub async fn build_launch_invocation(
.join(&config.game_version)
.join("natives");
let version_type = merged_profile.type_.as_deref().unwrap_or("release");
let resolution_width = config.resolution.map(|(width, _)| width.to_string());
let resolution_height = config.resolution.map(|(_, height)| height.to_string());
let resolution_width = resolution.map(|(width, _)| width.to_string());
let resolution_height = resolution.map(|(_, height)| height.to_string());
let template_ctx = TemplateContext {
library_directory,
classpath_separator: sep,
@@ -615,10 +622,10 @@ pub async fn build_launch_invocation(
build_game_args(&merged_profile, &rule_ctx, &template_ctx)?;
// Modern Mojang profiles include feature-gated resolution arguments.
// Older and third-party profiles may not, so add them when absent.
apply_custom_resolution(&mut game_args, config.resolution);
apply_window_mode(&mut game_args, config.window_mode);
apply_custom_resolution(&mut game_args, resolution);
apply_window_mode(&mut game_args, window_mode);
let (memory_min, memory_max) = {
let (memory_min, memory_max, global_jvm_args, global_environment) = {
let settings = crate::config::SETTINGS.read();
(
config
@@ -629,16 +636,22 @@ pub async fn build_launch_invocation(
.memory_max
.clone()
.unwrap_or_else(|| settings.defaults.memory_max.clone()),
settings.defaults.jvm_args.clone(),
settings.defaults.environment.clone(),
)
};
let mut jvm_args: Vec<String> = vec![format!("-Xms{memory_min}"), format!("-Xmx{memory_max}")];
jvm_args.extend(patch_jvm_args);
jvm_args.extend(upstream_jvm_args);
jvm_args.extend(global_jvm_args);
jvm_args.extend(config.jvm_args.clone());
if let Some(glfw_path) = config.glfw_path.as_deref() {
jvm_args.push(format!("-Dorg.lwjgl.glfw.libname={glfw_path}"));
}
let mut environment = global_environment;
environment.extend(config.environment.clone());
Ok(LaunchInvocation {
java,
jvm_args,
@@ -647,7 +660,7 @@ pub async fn build_launch_invocation(
main_class,
extra_args,
game_args,
environment: config.environment.clone(),
environment,
working_dir: minecraft_dir,
})
}
+5 -2
View File
@@ -262,6 +262,7 @@ impl InstanceManager {
}
})?;
let defaults = crate::config::SETTINGS.read().defaults.clone();
let config = InstanceConfig {
name: name.to_string(),
game_version: game_version.to_string(),
@@ -274,8 +275,10 @@ impl InstanceManager {
memory_min: None,
jvm_args: vec![],
environment: Default::default(),
window_mode: Default::default(),
resolution: None,
window_mode: defaults.window_mode,
inherit_window_mode: true,
resolution: defaults.resolution,
inherit_resolution: true,
preferred_account: None,
pre_launch_command: Default::default(),
post_exit_command: Default::default(),
+3 -1
View File
@@ -27,4 +27,6 @@ pub use content::{
pub use launch::LaunchError;
pub use loader::{GameVersion, ModLoaderInstaller, VanillaInstaller, get_installer};
pub use manager::{InstanceError, InstanceManager};
pub use models::{InstanceConfig, LaunchCommand, ModLoader, WindowMode, normalize_memory_value};
pub use models::{
InstanceConfig, LaunchCommand, ModLoader, WindowMode, memory_kib, normalize_memory_value,
};
+38
View File
@@ -89,8 +89,12 @@ pub struct InstanceConfig {
pub environment: BTreeMap<String, String>,
#[serde(default, skip_serializing_if = "WindowMode::is_windowed")]
pub window_mode: WindowMode,
#[serde(default, skip_serializing_if = "is_false")]
pub inherit_window_mode: bool,
#[serde(default)]
pub resolution: Option<(u32, u32)>,
#[serde(default, skip_serializing_if = "is_false")]
pub inherit_resolution: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub preferred_account: Option<String>,
#[serde(default, skip_serializing_if = "LaunchCommand::is_default")]
@@ -105,6 +109,28 @@ pub struct InstanceConfig {
pub modpack_source: Option<crate::instance::ProviderProject>,
}
impl InstanceConfig {
pub fn effective_window_mode(&self, global: WindowMode) -> WindowMode {
if self.inherit_window_mode {
global
} else {
self.window_mode
}
}
pub fn effective_resolution(&self, global: Option<(u32, u32)>) -> Option<(u32, u32)> {
if self.inherit_resolution {
global
} else {
self.resolution
}
}
}
fn is_false(value: &bool) -> bool {
!value
}
pub fn parse_resolution(input: &str) -> Result<(u32, u32), String> {
let (width, height) = input
.trim()
@@ -152,6 +178,18 @@ pub fn normalize_memory_value(raw: &str) -> Option<String> {
}
}
pub fn memory_kib(value: &str) -> Option<u64> {
let normalized = normalize_memory_value(value)?;
let (number, suffix) = normalized.split_at(normalized.len().saturating_sub(1));
let number = number.parse::<u64>().ok()?;
match suffix {
"K" => Some(number),
"M" => number.checked_mul(1024),
"G" => number.checked_mul(1024 * 1024),
_ => None,
}
}
fn deserialize_optional_memory<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
where
D: serde::Deserializer<'de>,
@@ -246,7 +246,9 @@ fn instance() -> InstanceConfig {
jvm_args: Vec::new(),
environment: Default::default(),
window_mode: Default::default(),
inherit_window_mode: false,
resolution: None,
inherit_resolution: false,
preferred_account: None,
pre_launch_command: Default::default(),
post_exit_command: Default::default(),
+2
View File
@@ -51,7 +51,9 @@ fn job(name: &str) -> ReconcileJob {
jvm_args: Vec::new(),
environment: Default::default(),
window_mode: Default::default(),
inherit_window_mode: false,
resolution: None,
inherit_resolution: false,
preferred_account: None,
pre_launch_command: Default::default(),
post_exit_command: Default::default(),
+6
View File
@@ -191,7 +191,9 @@ async fn launch_commands_receive_instance_environment() {
jvm_args: Vec::new(),
environment: Default::default(),
window_mode: Default::default(),
inherit_window_mode: false,
resolution: None,
inherit_resolution: false,
preferred_account: None,
pre_launch_command: Default::default(),
post_exit_command: Default::default(),
@@ -321,7 +323,9 @@ async fn migrate_legacy_loader_profile_skips_modern_with_inherits_from() {
jvm_args: Vec::new(),
environment: Default::default(),
window_mode: Default::default(),
inherit_window_mode: false,
resolution: None,
inherit_resolution: false,
preferred_account: None,
pre_launch_command: Default::default(),
post_exit_command: Default::default(),
@@ -376,7 +380,9 @@ async fn migrate_legacy_loader_profile_skips_fabric() {
jvm_args: Vec::new(),
environment: Default::default(),
window_mode: Default::default(),
inherit_window_mode: false,
resolution: None,
inherit_resolution: false,
preferred_account: None,
pre_launch_command: Default::default(),
post_exit_command: Default::default(),
+2
View File
@@ -29,7 +29,9 @@ fn dummy_config(name: &str) -> InstanceConfig {
jvm_args: vec![],
environment: Default::default(),
window_mode: Default::default(),
inherit_window_mode: false,
resolution: None,
inherit_resolution: false,
preferred_account: None,
pre_launch_command: Default::default(),
post_exit_command: Default::default(),
+47
View File
@@ -18,7 +18,9 @@ fn instance_config_roundtrips_through_json() {
jvm_args: vec![],
environment: Default::default(),
window_mode: Default::default(),
inherit_window_mode: false,
resolution: Some((1920, 1080)),
inherit_resolution: false,
preferred_account: None,
pre_launch_command: Default::default(),
post_exit_command: Default::default(),
@@ -55,12 +57,57 @@ fn instance_config_accepts_numeric_memory() {
assert_eq!(parsed.memory_min.as_deref(), Some("512M"));
assert!(parsed.environment.is_empty());
assert_eq!(parsed.window_mode, WindowMode::Windowed);
assert!(!parsed.inherit_window_mode);
assert!(!parsed.inherit_resolution);
assert_eq!(parsed.preferred_account, None);
assert_eq!(parsed.pre_launch_command, LaunchCommand::default());
assert_eq!(parsed.post_exit_command, LaunchCommand::default());
assert_eq!(parsed.glfw_path, None);
}
#[test]
fn window_defaults_are_inherited_only_when_explicitly_enabled() {
let mut config = InstanceConfig {
name: "test".to_owned(),
game_version: "1.21.1".to_owned(),
loader: ModLoader::Vanilla,
loader_version: None,
created: Utc::now(),
last_played: None,
java_path: None,
memory_max: None,
memory_min: None,
jvm_args: Vec::new(),
environment: Default::default(),
window_mode: WindowMode::Windowed,
inherit_window_mode: false,
resolution: None,
inherit_resolution: false,
preferred_account: None,
pre_launch_command: Default::default(),
post_exit_command: Default::default(),
glfw_path: None,
config_sync_profile: None,
modpack_source: None,
};
assert_eq!(
config.effective_window_mode(WindowMode::Fullscreen),
WindowMode::Windowed
);
assert_eq!(config.effective_resolution(Some((1920, 1080))), None);
config.inherit_window_mode = true;
config.inherit_resolution = true;
assert_eq!(
config.effective_window_mode(WindowMode::Fullscreen),
WindowMode::Fullscreen
);
assert_eq!(
config.effective_resolution(Some((1920, 1080))),
Some((1920, 1080))
);
}
#[test]
fn normalize_memory_value_handles_bare_numbers() {
assert_eq!(normalize_memory_value("8").as_deref(), Some("8G"));
+12
View File
@@ -141,6 +141,18 @@ impl MetadataPaths {
}
}
pub fn clear_disposable_caches(meta_dir: &Path) -> io::Result<()> {
let paths = MetadataPaths::new(meta_dir);
for path in [paths.cache().join("providers"), paths.cache().join("java")] {
match std::fs::remove_dir_all(&path) {
Ok(()) => {}
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(error) => return Err(error),
}
}
Ok(())
}
pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
let parent = path
.parent()
+18
View File
@@ -42,6 +42,24 @@ fn metadata_paths_separate_state_and_cache() {
);
}
#[test]
fn disposable_cache_cleanup_preserves_runtime_metadata() {
let temp = tempfile::tempdir().unwrap();
let paths = MetadataPaths::new(temp.path());
std::fs::create_dir_all(paths.provider_icons("modrinth")).unwrap();
std::fs::create_dir_all(paths.java_installations().parent().unwrap()).unwrap();
std::fs::create_dir_all(paths.temporary()).unwrap();
std::fs::create_dir_all(paths.versions()).unwrap();
std::fs::write(paths.java_installations(), "[]").unwrap();
clear_disposable_caches(temp.path()).unwrap();
assert!(!paths.cache().join("providers").exists());
assert!(!paths.cache().join("java").exists());
assert!(paths.temporary().exists());
assert!(paths.versions().exists());
}
#[test]
fn atomic_write_replaces_existing_file() {
let temp = tempfile::tempdir().unwrap();
+23 -8
View File
@@ -418,7 +418,7 @@ impl App {
cached.map(|snapshot| (result.instance_name.clone(), snapshot));
self.content_manifest = Some((result.instance_name.clone(), result.manifest.clone()));
self.apply_content_update_snapshot();
if stale {
if stale && crate::config::SETTINGS.read().general.check_content_updates {
crate::instance::content::updates::spawn(
selected,
result.manifest,
@@ -756,13 +756,28 @@ impl App {
match path.file_name().and_then(|name| name.to_str()) {
Some("config.toml") => {
match crate::config::SETTINGS.reload() {
Ok(true) => error_buffer::push_error(error_buffer::ErrorEvent {
id: 0,
level: tracing::Level::INFO,
message: "Path and image protocol changes apply after restart".to_owned(),
pushed_at: std::time::Instant::now(),
}),
Ok(false) => {}
Ok(outcome) => {
if outcome.provider_changed {
self.reset_discovery_states();
}
if outcome.modpack_updates_enabled {
widgets::instances::spawn_modpack_update_checks(
&self.instances_state.instances,
);
}
if outcome.content_updates_enabled {
self.spawn_selected_content_update_check();
}
if outcome.restart_required {
error_buffer::push_error(error_buffer::ErrorEvent {
id: 0,
level: tracing::Level::INFO,
message: "Path and image protocol changes apply after restart"
.to_owned(),
pushed_at: std::time::Instant::now(),
});
}
}
Err(error) => error_buffer::push_error(error_buffer::ErrorEvent {
id: 0,
level: tracing::Level::ERROR,
+77 -4
View File
@@ -296,6 +296,23 @@ impl App {
}
self.focused
}
Some(confirm_popup::ConfirmTarget::LauncherCache) => {
let meta_dir = crate::config::SETTINGS.read().paths.resolve_meta_dir();
match crate::storage::clear_disposable_caches(&meta_dir) {
Ok(()) => {
self.reset_discovery_states();
error_buffer::push_message(
tracing::Level::INFO,
"Cleared launcher caches",
);
}
Err(error) => error_buffer::push_message(
tracing::Level::ERROR,
format!("Failed to clear launcher caches: {error}"),
),
}
FocusedArea::GlobalSettings
}
Some(confirm_popup::ConfirmTarget::AutomaticSelection {
setting,
instance,
@@ -363,6 +380,9 @@ impl App {
}
FocusedArea::InstanceSettings
}
Some(confirm_popup::ConfirmTarget::LauncherCache) => {
FocusedArea::GlobalSettings
}
Some(confirm_popup::ConfirmTarget::AutomaticSelection {
instance, ..
}) => {
@@ -747,6 +767,10 @@ impl App {
});
self.focused = FocusedArea::ConfirmDelete;
}
widgets::popups::global_settings::Action::ClearCache => {
confirm_popup::set_pending(confirm_popup::ConfirmTarget::LauncherCache);
self.focused = FocusedArea::ConfirmDelete;
}
widgets::popups::global_settings::Action::Close => {
self.global_settings = None;
self.focused = self.pre_overlay_focused;
@@ -2137,11 +2161,32 @@ impl App {
theme: String,
border: crate::config::theme::BorderStyle,
) {
let result = crate::config::SETTINGS
.save_launcher_settings(config)
.and_then(|()| crate::config::theme::apply_theme(theme, border));
let result = crate::config::SETTINGS.save_launcher_settings(config);
match result {
Ok(()) => crate::feedback::request_redraw(),
Ok(outcome) => {
if let Err(error) = crate::config::theme::apply_theme(theme, border) {
error_buffer::push_message(tracing::Level::ERROR, error.to_string());
return;
}
if outcome.provider_changed {
self.reset_discovery_states();
}
if outcome.modpack_updates_enabled {
widgets::instances::spawn_modpack_update_checks(
&self.instances_state.instances,
);
}
if outcome.content_updates_enabled {
self.spawn_selected_content_update_check();
}
if outcome.restart_required && outcome.restart_changed {
error_buffer::push_message(
tracing::Level::INFO,
"Restart rmcl to apply storage and image changes",
);
}
crate::feedback::request_redraw();
}
Err(error) => error_buffer::push_message(tracing::Level::ERROR, error.to_string()),
}
}
@@ -2212,6 +2257,34 @@ impl App {
}),
}
}
pub(super) fn reset_discovery_states(&mut self) {
self.mods_discovery_state =
widgets::content::DiscoveryState::new(crate::instance::ContentKind::Mod);
self.resource_packs_discovery_state =
widgets::content::DiscoveryState::new(crate::instance::ContentKind::ResourcePack);
self.shaders_discovery_state =
widgets::content::DiscoveryState::new(crate::instance::ContentKind::Shader);
self.datapacks_discovery_state =
widgets::content::DiscoveryState::new(crate::instance::ContentKind::DataPack);
}
pub(super) fn spawn_selected_content_update_check(&self) {
let Some(instance) = self.instances_state.selected_instance().cloned() else {
return;
};
let Some((name, manifest)) = self.content_manifest.as_ref() else {
return;
};
if name != &instance.name {
return;
}
let path = crate::storage::InstancePaths::new(
self.instance_manager.instances_dir.join(&instance.name),
)
.content_updates();
crate::instance::content::updates::spawn(instance, manifest.clone(), path);
}
}
fn delete_content_path(path: &std::path::Path) -> std::io::Result<()> {
+1
View File
@@ -50,6 +50,7 @@ pub async fn show() -> color_eyre::Result<()> {
.unwrap_or_else(|_| ratatui_image::picker::Picker::halfblocks());
let detected_protocol = picker.protocol_type();
let requested_protocol = match crate::config::SETTINGS.read().ui.image_protocol {
crate::config::settings::ImageProtocol::Auto => detected_protocol,
crate::config::settings::ImageProtocol::Halfblocks
| crate::config::settings::ImageProtocol::Quadrants => {
ratatui_image::picker::ProtocolType::Halfblocks
+4
View File
@@ -168,7 +168,9 @@ fn structural_settings_update_repairs_runtime_before_persisting() {
jvm_args: Vec::new(),
environment: Default::default(),
window_mode: Default::default(),
inherit_window_mode: false,
resolution: None,
inherit_resolution: false,
preferred_account: None,
pre_launch_command: Default::default(),
post_exit_command: Default::default(),
@@ -267,7 +269,9 @@ fn failed_structural_settings_update_keeps_previous_config() {
jvm_args: Vec::new(),
environment: Default::default(),
window_mode: Default::default(),
inherit_window_mode: false,
resolution: None,
inherit_resolution: false,
preferred_account: None,
pre_launch_command: Default::default(),
post_exit_command: Default::default(),
+32 -1
View File
@@ -641,6 +641,8 @@ fn settings_panel_routes_legacy_edit_keys_to_tui_popups() {
assert_eq!(ui.app.focused, FocusedArea::GlobalSettings);
ui.draw();
assert!(ui.screen().contains("Launcher Settings"));
assert!(ui.screen().contains("Appearance"));
assert!(ui.screen().contains("Image rendering"));
assert!(ui.screen().contains("Memory max"));
assert!(ui.screen().contains('◆'));
assert!(!ui.screen().contains('█'));
@@ -653,6 +655,35 @@ fn settings_panel_routes_legacy_edit_keys_to_tui_popups() {
assert_eq!(ui.app.focused, FocusedArea::Settings);
}
#[test]
fn launcher_settings_scroll_to_storage_and_confirm_cache_cleanup() {
let mut ui = UiHarness::new();
ui.add_instance("global-settings-test");
ui.key(KeyCode::Char('G'));
for _ in 0..18 {
ui.key(KeyCode::Char('j'));
}
ui.draw();
assert!(ui.screen().contains("Storage"));
assert!(ui.screen().contains("Instances"));
assert!(ui.screen().contains("Metadata"));
for _ in 18..23 {
ui.key(KeyCode::Char('j'));
}
ui.key(KeyCode::Enter);
assert_eq!(ui.app.focused, FocusedArea::ConfirmDelete);
assert!(matches!(
confirm::pending_target(),
Some(confirm::ConfirmTarget::LauncherCache)
));
ui.draw();
assert!(ui.screen().contains("Clear caches"));
ui.key(KeyCode::Esc);
assert_eq!(ui.app.focused, FocusedArea::GlobalSettings);
}
#[test]
fn runtime_settings_use_the_shared_confirmation_popup() {
let mut ui = UiHarness::new();
@@ -953,7 +984,7 @@ fn settings_use_java_memory_and_resolution_controls() {
ui.key(KeyCode::Esc);
ui.key(KeyCode::Char('G'));
for _ in 0..4 {
for _ in 0..5 {
ui.key(KeyCode::Char('j'));
}
ui.key(KeyCode::Enter);
+2
View File
@@ -136,7 +136,9 @@ impl UiHarness {
jvm_args: Vec::new(),
environment: Default::default(),
window_mode: Default::default(),
inherit_window_mode: false,
resolution: None,
inherit_resolution: false,
preferred_account: None,
pre_launch_command: Default::default(),
post_exit_command: Default::default(),
@@ -45,7 +45,9 @@ fn instance(name: &str, version: &str) -> InstanceConfig {
jvm_args: Vec::new(),
environment: Default::default(),
window_mode: Default::default(),
inherit_window_mode: false,
resolution: None,
inherit_resolution: false,
preferred_account: None,
pre_launch_command: Default::default(),
post_exit_command: Default::default(),
+2
View File
@@ -49,7 +49,9 @@ fn synthetic_instance(name: &str) -> InstanceConfig {
jvm_args: vec![],
environment: Default::default(),
window_mode: Default::default(),
inherit_window_mode: false,
resolution: None,
inherit_resolution: false,
preferred_account: None,
pre_launch_command: Default::default(),
post_exit_command: Default::default(),
+6
View File
@@ -36,12 +36,18 @@ static MODPACK_UPDATE_SLOTS: LazyLock<Arc<tokio::sync::Semaphore>> =
LazyLock::new(|| Arc::new(tokio::sync::Semaphore::new(4)));
pub fn spawn_modpack_update_checks(instances: &[InstanceConfig]) {
if !crate::config::SETTINGS.read().general.check_modpack_updates {
return;
}
for instance in instances {
spawn_modpack_update_check(instance);
}
}
pub fn spawn_modpack_update_check(instance: &InstanceConfig) {
if !crate::config::SETTINGS.read().general.check_modpack_updates {
return;
}
let Some(source) = instance.modpack_source.clone() else {
return;
};
+7
View File
@@ -48,6 +48,7 @@ pub enum ConfirmTarget {
InstanceRuntime {
name: String,
},
LauncherCache,
AutomaticSelection {
setting: AutomaticSetting,
instance: Option<String>,
@@ -81,6 +82,7 @@ impl ConfirmTarget {
match self {
Self::OrphanDependencies { .. } => " Remove unused dependencies ".to_owned(),
Self::InstanceRuntime { .. } => " Change runtime ".to_owned(),
Self::LauncherCache => " Clear caches ".to_owned(),
Self::AutomaticSelection { setting, .. } => setting.title().to_owned(),
_ => format!(" Delete '{}' ", self.name()),
}
@@ -123,6 +125,9 @@ impl ConfirmTarget {
ConfirmTarget::InstanceRuntime { .. } => {
"Some installed mods may be incompatible".to_owned()
}
ConfirmTarget::LauncherCache => {
"Provider metadata and Java detection will be rebuilt".to_owned()
}
ConfirmTarget::AutomaticSelection { setting, .. } => setting.description().to_owned(),
}
}
@@ -135,6 +140,7 @@ impl ConfirmTarget {
ConfirmTarget::Content { name, .. } => name,
ConfirmTarget::OrphanDependencies { .. } => "unused dependencies",
ConfirmTarget::InstanceRuntime { name, .. } => name,
ConfirmTarget::LauncherCache => "launcher caches",
ConfirmTarget::AutomaticSelection { instance, .. } => {
instance.as_deref().unwrap_or("launcher")
}
@@ -146,6 +152,7 @@ impl ConfirmTarget {
Self::Content { dependents, .. } if !dependents.is_empty() => " delete anyway",
Self::OrphanDependencies { .. } => " remove all",
Self::InstanceRuntime { .. } => " change",
Self::LauncherCache => " clear",
Self::AutomaticSelection { .. } => " enable",
_ => " confirm",
}
+607 -69
View File
@@ -16,16 +16,29 @@ use ratatui_textarea::TextArea;
use crate::{
config::{
Config,
settings::{ContentProvider, ImageProtocol},
theme::{BORDER_STYLE, BorderStyle, THEME, ThemeConfig},
},
instance::models::normalize_memory_value,
instance::models::{WindowMode, normalize_memory_value, parse_resolution},
tui::widgets::popups::settings_controls::{
JavaChoice, JavaPicker, SettingsPickerAction, adjust_memory, auto_label,
handle_text_area_input, memory_kib, render_memory_gauge, render_settings_picker,
settings_text_area,
JavaChoice, JavaPicker, SettingsPicker, SettingsPickerAction, SettingsPickerOption,
adjust_memory, auto_label, display_resolutions, environment_labels, handle_text_area_input,
memory_kib, parse_environment, render_memory_gauge, render_settings_picker,
settings_text_area, tagged_value_lines,
},
tui::widgets::status_badge,
};
const FIELD_COUNT: usize = 24;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ChoicePicker {
ImageProtocol,
WindowMode,
Resolution,
Provider,
}
pub struct State {
pub config: Config,
pub theme: ThemeConfig,
@@ -38,6 +51,9 @@ pub struct State {
theme_index: usize,
java_picker_open: bool,
java_picker: JavaPicker,
choice_picker: Option<ChoicePicker>,
settings_picker: SettingsPicker,
resolutions: Vec<(u32, u32)>,
}
pub enum Action {
@@ -45,6 +61,7 @@ pub enum Action {
Save(Box<Config>, String, BorderStyle),
Error(String),
ConfirmJavaAuto,
ClearCache,
OpenRaw(std::path::PathBuf),
Close,
}
@@ -57,12 +74,34 @@ impl State {
.iter()
.position(|candidate| candidate == &theme.theme)
.unwrap_or(0);
let config = crate::config::SETTINGS.read().clone();
let java_cache = crate::storage::MetadataPaths::new(config.paths.resolve_meta_dir())
.java_installations();
let runtime_config = crate::config::SETTINGS.read().clone();
let config_path = crate::config::get_config_path().join("config.toml");
let config = crate::config::load_config(&config_path).unwrap_or_else(|error| {
tracing::warn!("Failed to load persisted launcher settings: {error}");
runtime_config.clone()
});
let java_cache =
crate::storage::MetadataPaths::new(runtime_config.paths.resolve_meta_dir())
.java_installations();
let mut java_picker =
JavaPicker::with_cache(crate::instance::java::detect_java_path(), Some(java_cache));
java_picker.open(config.paths.java_path.as_deref());
let mut resolutions = display_resolutions()
.into_iter()
.map(|display| (display.width, display.height))
.collect::<Vec<_>>();
resolutions.extend([
(854, 480),
(1280, 720),
(1920, 1080),
(2560, 1440),
(3840, 2160),
]);
if let Some(resolution) = config.defaults.resolution {
resolutions.push(resolution);
}
resolutions.sort_unstable();
resolutions.dedup();
Self {
config,
theme,
@@ -75,6 +114,9 @@ impl State {
theme_index,
java_picker_open: false,
java_picker,
choice_picker: None,
settings_picker: SettingsPicker::default(),
resolutions,
}
}
@@ -82,17 +124,39 @@ impl State {
match field {
0 => self.theme.theme.clone(),
1 => format!("{:?}", self.theme.border_style).to_lowercase(),
2 => self.config.defaults.memory_min.clone(),
3 => self.config.defaults.memory_max.clone(),
4 => self.config.paths.java_path.clone().unwrap_or_default(),
2 => self.config.ui.image_protocol.to_string(),
3 => self.config.defaults.memory_min.clone(),
4 => self.config.defaults.memory_max.clone(),
5 => self.config.paths.java_path.clone().unwrap_or_default(),
6 => self.config.defaults.window_mode.to_string(),
7 => self
.config
.defaults
.resolution
.map(|(width, height)| format!("{width}x{height}"))
.unwrap_or_default(),
8 => self.config.defaults.jvm_args.join(" "),
9 => environment_labels(&self.config.defaults.environment).join(" "),
10 => self.config.content.preferred_provider.to_string(),
11 => status(self.config.content.preferred_provider_only),
12 => status(self.config.content.ask_on_provider_conflict),
13 => status(self.config.general.check_modpack_updates),
14 => status(self.config.general.check_content_updates),
15 => self.config.content.unmatched_retry_hours.to_string(),
16 => self.config.content.max_fingerprint_size_mib.to_string(),
17 => self.config.paths.instances_dir.clone(),
18 => self.config.paths.meta_dir.clone(),
19 => self.config.ui.error_auto_dismiss_ms.to_string(),
20 => self.config.ui.error_slide_start_ms.to_string(),
21 => self.config.ui.error_fly_out_ms.to_string(),
22 => self.config.ui.max_error_events.to_string(),
_ => String::new(),
}
}
fn display_value(&self, field: usize) -> String {
match field {
1 => format!("{:?}", self.theme.border_style).to_lowercase(),
4 => self.java_picker.display_label(
5 => self.java_picker.display_label(
self.config
.paths
.java_path
@@ -100,6 +164,9 @@ impl State {
.filter(|path| !path.is_empty())
.unwrap_or_else(|| self.java_picker.detected_path()),
),
7 if self.config.defaults.resolution.is_none() => "game default".to_owned(),
16 if self.config.content.max_fingerprint_size_mib == 0 => "unlimited".to_owned(),
23 => "provider and Java metadata".to_owned(),
_ => self.value(field),
}
}
@@ -116,11 +183,11 @@ impl State {
state.editing = Some(settings_text_area(editor.lines().to_vec()));
};
match self.selected {
2 | 3 if normalize_memory_value(value).is_none() => invalid(
3 | 4 if normalize_memory_value(value).is_none() => invalid(
self,
"Use a positive memory value ending in K, M, or G.".to_owned(),
),
2 => {
3 => {
let value = normalize_memory_value(value).unwrap();
self.config.defaults.memory_min = value.clone();
if memory_kib(&value) > memory_kib(&self.config.defaults.memory_max) {
@@ -128,7 +195,7 @@ impl State {
}
self.save_pending = true;
}
3 => {
4 => {
let value = normalize_memory_value(value).unwrap();
self.config.defaults.memory_max = value.clone();
if memory_kib(&value) < memory_kib(&self.config.defaults.memory_min) {
@@ -136,10 +203,77 @@ impl State {
}
self.save_pending = true;
}
4 => {
5 => {
self.config.paths.java_path = (!value.is_empty()).then(|| value.to_owned());
self.save_pending = true;
}
7 if value.is_empty() => {
self.config.defaults.resolution = None;
self.save_pending = true;
}
7 => match parse_resolution(value) {
Ok(resolution) => {
self.config.defaults.resolution = Some(resolution);
self.save_pending = true;
}
Err(error) => invalid(self, error),
},
8 => {
self.config.defaults.jvm_args =
value.split_whitespace().map(str::to_owned).collect();
self.save_pending = true;
}
9 => match parse_environment(value) {
Ok(environment) => {
self.config.defaults.environment = environment;
self.save_pending = true;
}
Err(error) => invalid(self, error),
},
15 => match value.parse::<u64>() {
Ok(hours) => {
self.config.content.unmatched_retry_hours = hours;
self.save_pending = true;
}
Err(_) => invalid(self, "Use a non-negative number of hours.".to_owned()),
},
16 => match value.parse::<u64>() {
Ok(size) => {
self.config.content.max_fingerprint_size_mib = size;
self.save_pending = true;
}
Err(_) => invalid(self, "Use a non-negative size in MiB.".to_owned()),
},
17 | 18 if value.is_empty() => {
invalid(self, "Storage paths cannot be empty.".to_owned());
}
17 => {
self.config.paths.instances_dir = value.to_owned();
self.save_pending = true;
}
18 => {
self.config.paths.meta_dir = value.to_owned();
self.save_pending = true;
}
19..=21 => match value.parse::<u64>() {
Ok(milliseconds) if milliseconds > 0 => {
match self.selected {
19 => self.config.ui.error_auto_dismiss_ms = milliseconds,
20 => self.config.ui.error_slide_start_ms = milliseconds,
21 => self.config.ui.error_fly_out_ms = milliseconds,
_ => {}
}
self.save_pending = true;
}
_ => invalid(self, "Use a positive duration in milliseconds.".to_owned()),
},
22 => match value.parse::<usize>() {
Ok(count) if count > 0 => {
self.config.ui.max_error_events = count;
self.save_pending = true;
}
_ => invalid(self, "Keep at least one notification.".to_owned()),
},
_ => {}
}
}
@@ -198,6 +332,143 @@ impl State {
}
}
fn choice_options(&self, picker: ChoicePicker) -> Vec<SettingsPickerOption> {
let option = |key: &str, title: &str, description: &str| SettingsPickerOption {
key: key.to_owned(),
title: title.to_owned(),
detail: Some(description.to_owned()),
leading: None,
badge: None,
active: false,
};
match picker {
ChoicePicker::ImageProtocol => [
(
"auto",
"Auto",
"Use the protocol detected for this terminal",
),
("kitty", "Kitty", "Use Kitty graphics when supported"),
(
"iterm2",
"iTerm2",
"Use the iTerm2 image protocol when supported",
),
(
"quadrants",
"Quadrants",
"Render images with quadrant characters",
),
(
"halfblocks",
"Halfblocks",
"Render images with half-block characters",
),
]
.into_iter()
.map(|(key, title, description)| option(key, title, description))
.collect(),
ChoicePicker::WindowMode => [
("windowed", "windowed", "Launch new instances in a window"),
(
"fullscreen",
"fullscreen",
"Launch new instances in fullscreen",
),
]
.into_iter()
.map(|(key, title, description)| option(key, title, description))
.collect(),
ChoicePicker::Resolution => std::iter::once(option(
"default",
"Game default",
"Let Minecraft choose the initial window size",
))
.chain(self.resolutions.iter().map(|(width, height)| {
let value = format!("{width}x{height}");
option(&value, &value, "Use this size for newly created instances")
}))
.collect(),
ChoicePicker::Provider => {
let mut options = vec![option(
"modrinth",
"Modrinth",
"Prefer Modrinth when projects exist on multiple providers",
)];
if crate::net::curseforge::api_key().is_some() {
options.push(option(
"curseforge",
"CurseForge",
"Prefer CurseForge when projects exist on multiple providers",
));
}
options
}
}
}
fn open_choice_picker(&mut self, picker: ChoicePicker) {
let preferred = match picker {
ChoicePicker::ImageProtocol => self.config.ui.image_protocol.to_string(),
ChoicePicker::WindowMode => self.config.defaults.window_mode.to_string(),
ChoicePicker::Resolution => self.value(7),
ChoicePicker::Provider => self.config.content.preferred_provider.as_str().to_owned(),
};
self.settings_picker.reset();
self.settings_picker
.sync(self.choice_options(picker), Some(&preferred));
self.choice_picker = Some(picker);
}
fn handle_choice_picker_key(&mut self, key: &KeyEvent) {
match self.settings_picker.handle_key(key) {
SettingsPickerAction::Back => self.choice_picker = None,
SettingsPickerAction::Select => {
let Some(picker) = self.choice_picker else {
return;
};
let Some(value) = self.settings_picker.selected_key().map(str::to_owned) else {
return;
};
match picker {
ChoicePicker::ImageProtocol => {
self.config.ui.image_protocol = match value.as_str() {
"kitty" => ImageProtocol::Kitty,
"iterm2" => ImageProtocol::Iterm2,
"quadrants" => ImageProtocol::Quadrants,
"halfblocks" => ImageProtocol::Halfblocks,
_ => ImageProtocol::Auto,
};
}
ChoicePicker::WindowMode => {
self.config.defaults.window_mode = if value == "fullscreen" {
WindowMode::Fullscreen
} else {
WindowMode::Windowed
};
}
ChoicePicker::Resolution => {
self.config.defaults.resolution = if value == "default" {
None
} else {
parse_resolution(&value).ok()
};
}
ChoicePicker::Provider => {
self.config.content.preferred_provider = if value == "curseforge" {
ContentProvider::CurseForge
} else {
ContentProvider::Modrinth
};
}
}
self.save_pending = true;
self.choice_picker = None;
}
SettingsPickerAction::None => {}
}
}
fn open_java_picker(&mut self) {
self.java_picker
.open(self.config.paths.java_path.as_deref());
@@ -255,13 +526,13 @@ impl State {
}
fn adjust_selected_memory(&mut self, forward: bool) {
let value = if self.selected == 2 {
let value = if self.selected == 3 {
&self.config.defaults.memory_min
} else {
&self.config.defaults.memory_max
};
let value = adjust_memory(value, forward);
if self.selected == 2 {
if self.selected == 3 {
self.config.defaults.memory_min = value.clone();
if memory_kib(&value) > memory_kib(&self.config.defaults.memory_max) {
self.config.defaults.memory_max = value;
@@ -276,6 +547,30 @@ impl State {
self.error = None;
}
fn toggle_selected(&mut self) {
match self.selected {
11 => {
self.config.content.preferred_provider_only =
!self.config.content.preferred_provider_only;
}
12 => {
self.config.content.ask_on_provider_conflict =
!self.config.content.ask_on_provider_conflict;
}
13 => {
self.config.general.check_modpack_updates =
!self.config.general.check_modpack_updates;
}
14 => {
self.config.general.check_content_updates =
!self.config.general.check_content_updates;
}
_ => return,
}
self.save_pending = true;
self.error = None;
}
pub fn handle_key(&mut self, key: &KeyEvent) -> Action {
let action = self.handle_key_inner(key);
if !matches!(action, Action::None) {
@@ -286,6 +581,7 @@ impl State {
}
if self.save_pending && self.editing.is_none() {
self.save_pending = false;
self.config = self.config.clone().normalize();
return Action::Save(
Box::new(self.config.clone()),
self.theme.theme.clone(),
@@ -296,6 +592,10 @@ impl State {
}
fn handle_key_inner(&mut self, key: &KeyEvent) -> Action {
if self.choice_picker.is_some() {
self.handle_choice_picker_key(key);
return Action::None;
}
if self.java_picker_open {
self.handle_java_picker_key(key);
return Action::None;
@@ -313,28 +613,43 @@ impl State {
return Action::None;
}
match key.code {
KeyCode::Char('j') | KeyCode::Down => self.selected = (self.selected + 1).min(4),
KeyCode::Char('j') | KeyCode::Down => {
self.selected = (self.selected + 1).min(FIELD_COUNT - 1);
}
KeyCode::Char('k') | KeyCode::Up => self.selected = self.selected.saturating_sub(1),
KeyCode::Char('h') | KeyCode::Left if self.selected == 1 => self.cycle_border(false),
KeyCode::Char('l') | KeyCode::Right if self.selected == 1 => self.cycle_border(true),
KeyCode::Char('h') | KeyCode::Left if matches!(self.selected, 2 | 3) => {
KeyCode::Char('h') | KeyCode::Left if matches!(self.selected, 3 | 4) => {
self.adjust_selected_memory(false);
}
KeyCode::Char('l') | KeyCode::Right if matches!(self.selected, 2 | 3) => {
KeyCode::Char('l') | KeyCode::Right if matches!(self.selected, 3 | 4) => {
self.adjust_selected_memory(true);
}
KeyCode::Enter => match self.selected {
0 => self.theme_picker = true,
1 => self.cycle_border(true),
2 | 3 => {
2 => self.open_choice_picker(ChoicePicker::ImageProtocol),
3 | 4 => {
self.editing = Some(settings_text_area(vec![self.value(self.selected)]));
}
4 => self.open_java_picker(),
5 => self.open_java_picker(),
6 => self.open_choice_picker(ChoicePicker::WindowMode),
7 => self.open_choice_picker(ChoicePicker::Resolution),
10 => self.open_choice_picker(ChoicePicker::Provider),
11..=14 => self.toggle_selected(),
23 => return Action::ClearCache,
field => self.editing = Some(settings_text_area(vec![self.value(field)])),
},
KeyCode::Char('a') if self.selected == 4 => return self.toggle_auto_java(),
KeyCode::Char('c') if self.selected == 4 => {
self.editing = Some(settings_text_area(vec![self.value(4)]));
KeyCode::Char('a') if self.selected == 5 => return self.toggle_auto_java(),
KeyCode::Char('c') if self.selected == 5 => {
self.editing = Some(settings_text_area(vec![self.value(5)]));
}
KeyCode::Char('c') if self.selected == 7 => {
self.editing = Some(settings_text_area(vec![self.value(7)]));
}
KeyCode::Char('d') if self.selected == 7 => {
self.config.defaults.resolution = None;
self.save_pending = true;
}
KeyCode::Char('E') => {
let file = if self.selected <= 1 {
@@ -382,12 +697,16 @@ fn available_themes() -> Vec<String> {
}
pub fn popup_rect(area: Rect, state: &State) -> Rect {
let height = if state.theme_picker || state.java_picker_open {
let height = if state.theme_picker || state.java_picker_open || state.choice_picker.is_some() {
(area.height * 2 / 3).max(10)
} else {
7
26
};
let width = if state.java_picker_open || state.choice_picker.is_some() {
72
} else {
68
};
let width = if state.java_picker_open { 72 } else { 52 };
area.centered(
ratatui::layout::Constraint::Percentage(width),
ratatui::layout::Constraint::Length(height.min(area.height.saturating_sub(4))),
@@ -402,17 +721,30 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut State) {
frame.render_widget(Clear, area);
let keybinds = if state.editing.is_some() {
super::keybind_line(&[("Enter", " apply"), ("Esc", " cancel")])
} else if state.java_picker_open || state.theme_picker {
} else if state.java_picker_open || state.theme_picker || state.choice_picker.is_some() {
super::keybind_line(&[("h", " back"), ("Enter", " select")])
} else if matches!(state.selected, 2 | 3) {
} else if matches!(state.selected, 3 | 4) {
super::keybind_line(&[("h/l", " adjust"), ("Enter", " exact"), ("Esc", " back")])
} else if state.selected == 4 {
} else if state.selected == 5 {
super::keybind_line(&[
("Enter", " runtimes"),
("a", " auto"),
("c", " custom"),
("Esc", " back"),
])
} else if matches!(state.selected, 2 | 6 | 10) {
super::keybind_line(&[("Enter", " select"), ("E", " raw"), ("Esc", " back")])
} else if state.selected == 7 {
super::keybind_line(&[
("Enter", " presets"),
("c", " custom"),
("d", " default"),
("Esc", " back"),
])
} else if matches!(state.selected, 11..=14) {
super::keybind_line(&[("Enter", " toggle"), ("E", " raw"), ("Esc", " back")])
} else if state.selected == 23 {
super::keybind_line(&[("Enter", " clear"), ("Esc", " back")])
} else if state.selected == 0 {
super::keybind_line(&[
("j/k", ""),
@@ -439,6 +771,13 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut State) {
" Theme "
} else if state.java_picker_open {
" Java Runtime "
} else if let Some(picker) = state.choice_picker {
match picker {
ChoicePicker::ImageProtocol => " Image Rendering ",
ChoicePicker::WindowMode => " Default Window Mode ",
ChoicePicker::Resolution => " Default Resolution ",
ChoicePicker::Provider => " Preferred Provider ",
}
} else {
" Launcher Settings "
};
@@ -459,6 +798,10 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut State) {
render_java_picker(frame, inner, state);
return;
}
if state.choice_picker.is_some() {
render_settings_picker(&state.settings_picker, inner, frame.buffer_mut());
return;
}
render_settings_list(frame, inner, state);
}
@@ -496,38 +839,162 @@ fn render_java_picker(frame: &mut Frame, area: Rect, state: &mut State) {
}
fn render_settings_list(frame: &mut Frame, area: Rect, state: &State) {
let labels = ["Theme", "Border style", "Memory min", "Memory max", "Java"];
let lines = labels
.iter()
.enumerate()
.map(|(index, label)| global_field_line(state, index, label))
.collect::<Vec<_>>();
frame.render_widget(Paragraph::new(lines), area);
for field in [2, 3] {
let value = state.value(field);
render_memory_gauge(
frame,
Rect {
x: area.x.saturating_add(20),
y: area.y.saturating_add(field as u16),
width: area.width.saturating_sub(21),
height: 1,
},
&value,
value.clone(),
state.selected == field,
);
let theme = THEME.as_ref();
let sections: [(&str, &[usize]); 6] = [
("Appearance", &[0, 1, 2]),
("Launch Defaults", &[3, 4, 5, 6, 7, 8, 9]),
("Content", &[10, 11, 12, 13, 14, 15, 16]),
("Storage", &[17, 18]),
("Notifications", &[19, 20, 21, 22]),
("Maintenance", &[23]),
];
let jvm_args = &state.config.defaults.jvm_args;
let environment = environment_labels(&state.config.defaults.environment);
let mut rows: Vec<(Option<usize>, Vec<Line<'static>>)> = Vec::new();
for (section_index, (title, fields)) in sections.iter().enumerate() {
if section_index > 0 {
rows.push((None, vec![Line::default()]));
}
rows.push((None, vec![section_line(title)]));
for index in *fields {
let label = field_label(*index);
let lines = match index {
8 => tagged_value_lines(
global_field_line(state, *index, label).spans,
state.selected == *index,
state.editing.is_some(),
jvm_args,
"no arguments",
area.width,
),
9 => tagged_value_lines(
global_field_line(state, *index, label).spans,
state.selected == *index,
state.editing.is_some(),
&environment,
"no variables",
area.width,
),
_ => vec![global_field_line(state, *index, label)],
};
rows.push((Some(*index), lines));
}
}
if let Some(editor) = state.editing.as_ref() {
let edit_area = Rect {
x: area.x.saturating_add(20),
y: area.y.saturating_add(state.selected as u16),
width: area.width.saturating_sub(20),
height: 1,
};
frame.render_widget(editor, edit_area);
let mut selected_end = 0u16;
let mut cursor = 0u16;
for (field, lines) in &rows {
let height = lines.len() as u16;
if *field == Some(state.selected) {
selected_end = cursor.saturating_add(height);
}
cursor = cursor.saturating_add(height);
}
let scroll = selected_end.saturating_sub(area.height);
let mut row_start = 0u16;
for (field, lines) in rows {
let height = lines.len() as u16;
let row_end = row_start.saturating_add(height);
if row_end <= scroll || row_start >= scroll.saturating_add(area.height) {
row_start = row_end;
continue;
}
let skip = scroll.saturating_sub(row_start) as usize;
let y = area.y.saturating_add(row_start.saturating_sub(scroll));
let visible_height = height
.saturating_sub(skip as u16)
.min(area.y.saturating_add(area.height).saturating_sub(y));
let selected = field == Some(state.selected);
frame.render_widget(
Paragraph::new(
lines
.into_iter()
.skip(skip)
.take(visible_height as usize)
.collect::<Vec<_>>(),
)
.style(Style::default().bg(if selected {
theme.stripe()
} else {
theme.surface()
})),
Rect {
y,
height: visible_height,
..area
},
);
if let Some(field @ (3 | 4)) = field
&& row_start >= scroll
{
let value = state.value(field);
render_memory_gauge(
frame,
Rect {
x: area.x.saturating_add(20),
y: area.y.saturating_add(row_start.saturating_sub(scroll)),
width: area.width.saturating_sub(21),
height: 1,
},
&value,
value.clone(),
state.selected == field,
);
}
if field == Some(state.selected)
&& row_start >= scroll
&& let Some(editor) = state.editing.as_ref()
{
frame.render_widget(
editor,
Rect {
x: area.x.saturating_add(20),
y: area.y.saturating_add(row_start.saturating_sub(scroll)),
width: area.width.saturating_sub(20),
height: 1,
},
);
}
row_start = row_end;
}
}
fn section_line(title: &str) -> Line<'static> {
Line::from(Span::styled(
format!(" {title}"),
Style::default()
.fg(THEME.as_ref().text())
.add_modifier(Modifier::BOLD),
))
}
fn field_label(index: usize) -> &'static str {
match index {
0 => "Theme",
1 => "Border style",
2 => "Image rendering",
3 => "Memory min",
4 => "Memory max",
5 => "Java",
6 => "Window mode",
7 => "Resolution",
8 => "JVM arguments",
9 => "Environment",
10 => "Provider",
11 => "Provider only",
12 => "Ask on conflict",
13 => "Modpack updates",
14 => "Content updates",
15 => "Retry hours",
16 => "Fingerprint MiB",
17 => "Instances",
18 => "Metadata",
19 => "Dismiss ms",
20 => "Slide start ms",
21 => "Fly-out ms",
22 => "Max notifications",
23 => "Clear caches",
_ => "",
}
}
@@ -545,7 +1012,7 @@ fn global_field_line(state: &State, index: usize, label: &str) -> Line<'static>
Style::default().fg(theme.text_dim()),
),
Span::styled(
if editing || matches!(index, 2 | 3) {
if editing || matches!(index, 3 | 4) {
String::new()
} else {
state.display_value(index)
@@ -563,9 +1030,15 @@ fn global_field_line(state: &State, index: usize, label: &str) -> Line<'static>
}),
),
];
if index == 4 && state.config.paths.java_path.is_none() && !editing {
if index == 5 && state.config.paths.java_path.is_none() && !editing {
spans.extend([Span::raw(" "), auto_label()]);
}
if restart_required_for(state, index) {
spans.extend([
Span::raw(" "),
status_badge("Restart", THEME.as_ref().warning()),
]);
}
Line::from(spans).style(Style::default().bg(if selected {
theme.stripe()
} else {
@@ -573,6 +1046,20 @@ fn global_field_line(state: &State, index: usize, label: &str) -> Line<'static>
}))
}
fn restart_required_for(state: &State, index: usize) -> bool {
let current = crate::config::SETTINGS.read();
match index {
2 => state.config.ui.image_protocol != current.ui.image_protocol,
17 => state.config.paths.instances_dir != current.paths.instances_dir,
18 => state.config.paths.meta_dir != current.paths.meta_dir,
_ => false,
}
}
fn status(enabled: bool) -> String {
if enabled { "enabled" } else { "disabled" }.to_owned()
}
#[cfg(test)]
mod tests {
use super::*;
@@ -580,7 +1067,7 @@ mod tests {
#[test]
fn launcher_memory_uses_slider_and_java_uses_picker() {
let mut state = State::new();
state.selected = 2;
state.selected = 3;
let original = state.config.defaults.memory_min.clone();
assert!(matches!(
state.handle_key(&KeyEvent::from(KeyCode::Char('l'))),
@@ -593,7 +1080,7 @@ mod tests {
assert!(state.editing.is_some());
state.editing = None;
state.selected = 4;
state.selected = 5;
state.handle_key(&KeyEvent::from(KeyCode::Enter));
assert!(state.java_picker_open);
}
@@ -601,7 +1088,7 @@ mod tests {
#[test]
fn java_auto_mode_toggles_to_and_from_the_detected_path() {
let mut state = State::new();
state.selected = 4;
state.selected = 5;
state.config.paths.java_path = None;
assert!(matches!(
@@ -623,7 +1110,7 @@ mod tests {
#[test]
fn java_picker_does_not_toggle_auto_mode() {
let mut state = State::new();
state.selected = 4;
state.selected = 5;
state.config.paths.java_path = Some("/custom/java".to_owned());
state.open_java_picker();
@@ -641,7 +1128,7 @@ mod tests {
#[test]
fn changing_runtime_to_auto_requests_confirmation() {
let mut state = State::new();
state.selected = 4;
state.selected = 5;
state.config.paths.java_path = Some("/custom/java".to_owned());
assert!(matches!(
@@ -653,4 +1140,55 @@ mod tests {
Some("/custom/java")
);
}
#[test]
fn launcher_choices_toggles_and_maintenance_are_interactive() {
let mut state = State::new();
state.selected = 2;
state.handle_key(&KeyEvent::from(KeyCode::Enter));
assert_eq!(state.choice_picker, Some(ChoicePicker::ImageProtocol));
state.handle_key(&KeyEvent::from(KeyCode::Char('j')));
assert!(matches!(
state.handle_key(&KeyEvent::from(KeyCode::Enter)),
Action::Save(..)
));
assert_eq!(state.config.ui.image_protocol, ImageProtocol::Kitty);
state.selected = 11;
let previous = state.config.content.preferred_provider_only;
assert!(matches!(
state.handle_key(&KeyEvent::from(KeyCode::Enter)),
Action::Save(..)
));
assert_eq!(state.config.content.preferred_provider_only, !previous);
state.selected = 23;
assert!(matches!(
state.handle_key(&KeyEvent::from(KeyCode::Enter)),
Action::ClearCache
));
}
#[test]
fn launcher_jvm_and_environment_defaults_share_tag_editing() {
let mut state = State::new();
state.selected = 8;
state.editing = Some(settings_text_area(vec!["-Xfoo -Xbar".to_owned()]));
assert!(matches!(
state.handle_key(&KeyEvent::from(KeyCode::Enter)),
Action::Save(..)
));
assert_eq!(state.config.defaults.jvm_args, ["-Xfoo", "-Xbar"]);
state.selected = 9;
state.editing = Some(settings_text_area(vec!["FOO=bar BAZ=qux".to_owned()]));
assert!(matches!(
state.handle_key(&KeyEvent::from(KeyCode::Enter)),
Action::Save(..)
));
assert_eq!(
state.config.defaults.environment.get("FOO"),
Some(&"bar".to_owned())
);
}
}
+106 -109
View File
@@ -12,10 +12,7 @@ use ratatui::{
widgets::{Block, Borders, Clear, ListItem, Paragraph},
};
use ratatui_textarea::TextArea;
use std::{
collections::BTreeMap,
sync::{Arc, Mutex},
};
use std::sync::{Arc, Mutex};
use crate::{
auth::{Account, AccountType},
@@ -35,11 +32,13 @@ use crate::{
DisplayResolution, GlfwChoice, GlfwPicker, JavaChoice, JavaPicker, SettingsPicker,
SettingsPickerAction, SettingsPickerBadge, SettingsPickerOption, adjust_memory,
auto_label, bundled_glfw_version, bundled_label as bundled_badge,
display_resolutions, handle_text_area_input, memory_kib, render_memory_gauge,
render_settings_picker, settings_text_area,
display_resolutions, environment_labels, handle_text_area_input, memory_kib,
parse_environment, render_memory_gauge, render_settings_picker, settings_text_area,
tagged_row_count, tagged_value_lines,
},
},
search::SearchState,
status_badge,
},
};
@@ -252,10 +251,13 @@ impl State {
.map(|(key, value)| format!("{key}={value}"))
.collect::<Vec<_>>()
.join(" "),
8 => self.draft.window_mode.to_string(),
8 => self
.draft
.effective_window_mode(SETTINGS.read().defaults.window_mode)
.to_string(),
9 => self
.draft
.resolution
.effective_resolution(SETTINGS.read().defaults.resolution)
.map(|(w, h)| format!("{w}x{h}"))
.unwrap_or_default(),
10 => self.draft.preferred_account.clone().unwrap_or_default(),
@@ -282,10 +284,11 @@ impl State {
6 => self.draft.jvm_args.join(" "),
7 if self.draft.environment.is_empty() => "no variables".to_owned(),
7 => self.value(7),
9 if self.draft.resolution.is_none() => self.default_resolution().map_or_else(
|| "not detected".to_owned(),
9 if self.draft.inherit_resolution => SETTINGS.read().defaults.resolution.map_or_else(
|| "game default".to_owned(),
|(width, height)| format!("{width}x{height}"),
),
9 if self.draft.resolution.is_none() => "game default".to_owned(),
10 => self.preferred_account_label(),
11 if self.desktop => "enabled".to_owned(),
11 => "disabled".to_owned(),
@@ -400,7 +403,11 @@ impl State {
6 => self.editing = Some(settings_text_area(vec![self.value(self.selected)])),
7 => self.editing = Some(settings_text_area(vec![self.value(7)])),
8 => {
self.draft.window_mode = match self.draft.window_mode {
let current = self
.draft
.effective_window_mode(SETTINGS.read().defaults.window_mode);
self.draft.inherit_window_mode = false;
self.draft.window_mode = match current {
WindowMode::Windowed => WindowMode::Fullscreen,
WindowMode::Fullscreen => WindowMode::Windowed,
};
@@ -430,10 +437,13 @@ impl State {
self.java_picker.initialize();
}
ChoicePicker::Resolution => {
let resolution = self
.draft
.effective_resolution(SETTINGS.read().defaults.resolution);
self.choice_index = self
.resolution_choices()
.iter()
.position(|choice| choice.resolution() == self.draft.resolution)
.position(|choice| choice.resolution() == resolution)
.unwrap_or(0);
}
ChoicePicker::Account => {
@@ -536,6 +546,7 @@ impl State {
.and_then(|choice| choice.resolution());
if let Some(resolution) = selected {
self.draft.resolution = Some(resolution);
self.draft.inherit_resolution = false;
}
}
Some(ChoicePicker::Account) => {
@@ -736,7 +747,11 @@ impl State {
}
fn resolution_choices(&self) -> Vec<ResolutionChoice> {
resolution_choices(self.draft.resolution, &self.display_resolutions)
resolution_choices(
self.draft
.effective_resolution(SETTINGS.read().defaults.resolution),
&self.display_resolutions,
)
}
fn default_resolution(&self) -> Option<(u32, u32)> {
@@ -758,12 +773,28 @@ impl State {
fn apply_default_resolution(&mut self) {
if let Some(resolution) = self.default_resolution() {
self.draft.resolution = Some(resolution);
self.draft.inherit_resolution = false;
self.error = None;
} else {
self.error = Some("Display resolution could not be detected.".to_owned());
}
}
fn toggle_global_window_default(&mut self) {
if self.selected == 8 {
if self.draft.inherit_window_mode {
self.draft.window_mode = SETTINGS.read().defaults.window_mode;
}
self.draft.inherit_window_mode = !self.draft.inherit_window_mode;
} else if self.selected == 9 {
if self.draft.inherit_resolution {
self.draft.resolution = SETTINGS.read().defaults.resolution;
}
self.draft.inherit_resolution = !self.draft.inherit_resolution;
}
self.error = None;
}
fn toggle_auto_java(&mut self) -> Action {
let Some(current) = self.draft.java_path.as_deref() else {
self.draft.java_path = Some(self.java_picker.detected_path().to_owned());
@@ -934,9 +965,15 @@ impl State {
Ok(environment) => self.draft.environment = environment,
Err(error) => invalid(self, error),
},
9 if value.is_empty() => self.draft.resolution = None,
9 if value.is_empty() => {
self.draft.resolution = None;
self.draft.inherit_resolution = false;
}
9 => match parse_resolution(value) {
Ok(resolution) => self.draft.resolution = Some(resolution),
Ok(resolution) => {
self.draft.resolution = Some(resolution);
self.draft.inherit_resolution = false;
}
Err(error) => invalid(self, error),
},
12 | 13 => {
@@ -1036,6 +1073,9 @@ impl State {
self.apply_default_memory();
}
KeyCode::Char('d') if self.selected == 9 => self.apply_default_resolution(),
KeyCode::Char('i') if matches!(self.selected, 8 | 9) => {
self.toggle_global_window_default();
}
KeyCode::Char('c') if self.selected == 9 => {
self.editing = Some(settings_text_area(vec![self.value(9)]));
}
@@ -1124,27 +1164,6 @@ fn resolution_choices(
choices
}
fn parse_environment(value: &str) -> Result<BTreeMap<String, String>, String> {
let mut environment = BTreeMap::new();
for assignment in value.split_whitespace() {
let Some((key, value)) = assignment.split_once('=') else {
return Err(format!(
"Environment variable '{assignment}' must use KEY=value."
));
};
if key.is_empty() || key.contains('\0') || value.contains('\0') {
return Err("Environment variable names cannot be empty.".to_owned());
}
if environment
.insert(key.to_owned(), value.to_owned())
.is_some()
{
return Err(format!("Environment variable '{key}' is repeated."));
}
}
Ok(environment)
}
pub fn popup_rect(area: Rect, state: &State) -> Rect {
let height = if state.picker.is_some()
|| matches!(
@@ -1232,6 +1251,7 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut State) {
("Enter", " presets"),
("c", " custom"),
("d", " default"),
("i", " global"),
("Esc", " back"),
])
} else if state.selected == 10 {
@@ -1248,7 +1268,15 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut State) {
("E", " raw"),
("Esc", " back"),
])
} else if matches!(state.selected, 8 | 11) {
} else if state.selected == 8 {
super::keybind_line(&[
("j/k", ""),
("Enter", " toggle"),
("i", " global"),
("E", " raw"),
("Esc", " back"),
])
} else if state.selected == 11 {
super::keybind_line(&[
("j/k", ""),
("Enter", " toggle"),
@@ -1517,6 +1545,11 @@ fn field_line(state: &State, index: usize, label: &str) -> Line<'static> {
if index == 14 && state.draft.glfw_path.is_none() && !editing {
spans.extend([Span::raw(" "), bundled_badge()]);
}
if (index == 8 && state.draft.inherit_window_mode)
|| (index == 9 && state.draft.inherit_resolution)
{
spans.extend([Span::raw(" "), status_badge("Global", theme.accent())]);
}
Line::from(spans)
}
@@ -1587,77 +1620,15 @@ fn tagged_field_lines(
empty: &str,
width: u16,
) -> Vec<Line<'static>> {
let theme = THEME.as_ref();
let selected = state.selected == index;
let mut prefix = field_line(state, index, label).spans;
if selected && state.editing.is_some() {
return vec![Line::from(prefix)];
}
if values.is_empty() {
prefix.push(Span::styled(
empty.to_owned(),
Style::default().fg(theme.text_dim()),
));
return vec![Line::from(prefix)];
}
let available = width.saturating_sub(20) as usize;
let mut lines = Vec::new();
let mut spans = prefix;
let mut used = 0usize;
for argument in values {
let badge_width = argument.chars().count() + 2;
let separator = usize::from(used > 0);
if used > 0 && used + separator + badge_width > available {
lines.push(Line::from(spans));
spans = vec![Span::raw(" ".repeat(20))];
used = 0;
}
if used > 0 {
spans.push(Span::raw(" "));
used += 1;
}
spans.push(Span::styled(
format!(" {argument} "),
Style::default()
.fg(if selected {
theme.accent()
} else {
theme.text()
})
.bg(theme.background())
.add_modifier(Modifier::BOLD),
));
used += badge_width;
}
lines.push(Line::from(spans));
lines
}
fn tagged_row_count(values: &[String], width: u16) -> usize {
if values.is_empty() {
return 1;
}
let available = width.saturating_sub(20) as usize;
let mut rows = 1;
let mut used = 0usize;
for argument in values {
let badge_width = argument.chars().count() + 2;
let separator = usize::from(used > 0);
if used > 0 && used + separator + badge_width > available {
rows += 1;
used = 0;
}
used += usize::from(used > 0) + badge_width;
}
rows
}
fn environment_labels(environment: &BTreeMap<String, String>) -> Vec<String> {
environment
.iter()
.map(|(key, value)| format!("{key}={value}"))
.collect()
tagged_value_lines(
field_line(state, index, label).spans,
selected,
state.editing.is_some(),
values,
empty,
width,
)
}
fn render_choice_picker(frame: &mut Frame, area: Rect, state: &mut State) {
@@ -1861,7 +1832,9 @@ mod tests {
jvm_args: Vec::new(),
environment: Default::default(),
window_mode: Default::default(),
inherit_window_mode: false,
resolution: None,
inherit_resolution: false,
preferred_account: None,
pre_launch_command: Default::default(),
post_exit_command: Default::default(),
@@ -2186,7 +2159,7 @@ mod tests {
}
#[test]
fn inherited_resolution_displays_the_detected_primary_size() {
fn explicit_game_default_resolution_is_labeled_clearly() {
let temp = tempfile::tempdir().unwrap();
let mut state = State::new(&instance(), temp.path());
state.display_resolutions = vec![DisplayResolution {
@@ -2196,7 +2169,31 @@ mod tests {
primary: true,
}];
assert_eq!(state.display_value(9), "2560x1440");
assert_eq!(state.display_value(9), "game default");
}
#[test]
fn window_settings_can_explicitly_inherit_launcher_defaults() {
let temp = tempfile::tempdir().unwrap();
let mut state = State::new(&instance(), temp.path());
state.selected = 8;
state.handle_key(&KeyEvent::from(KeyCode::Char('i')));
assert!(state.draft.inherit_window_mode);
assert_eq!(
state.display_value(8),
SETTINGS.read().defaults.window_mode.to_string()
);
state.selected = 9;
state.handle_key(&KeyEvent::from(KeyCode::Char('i')));
assert!(state.draft.inherit_resolution);
assert_eq!(
state
.draft
.effective_resolution(SETTINGS.read().defaults.resolution),
SETTINGS.read().defaults.resolution
);
}
#[test]
+102 -10
View File
@@ -4,7 +4,7 @@
// Reusable interactive controls shared by instance and launcher settings.
use std::{
collections::BTreeSet,
collections::{BTreeMap, BTreeSet},
path::{Path, PathBuf},
sync::{Arc, Mutex},
};
@@ -763,15 +763,7 @@ fn java_title(version: &str) -> String {
}
pub(crate) fn memory_kib(value: &str) -> Option<u64> {
let normalized = crate::instance::models::normalize_memory_value(value)?;
let (number, suffix) = normalized.split_at(normalized.len().saturating_sub(1));
let number = number.parse::<u64>().ok()?;
match suffix {
"K" => Some(number),
"M" => number.checked_mul(1024),
"G" => number.checked_mul(1024 * 1024),
_ => None,
}
crate::instance::models::memory_kib(value)
}
pub(crate) fn adjust_memory(value: &str, forward: bool) -> String {
@@ -887,6 +879,106 @@ pub(crate) fn settings_text_area(lines: Vec<String>) -> TextArea<'static> {
editor
}
pub(crate) fn parse_environment(value: &str) -> Result<BTreeMap<String, String>, String> {
let mut environment = BTreeMap::new();
for assignment in value.split_whitespace() {
let Some((key, value)) = assignment.split_once('=') else {
return Err(format!(
"Environment variable '{assignment}' must use KEY=value."
));
};
if key.is_empty() || key.contains('\0') || value.contains('\0') {
return Err("Environment variable names cannot be empty.".to_owned());
}
if environment
.insert(key.to_owned(), value.to_owned())
.is_some()
{
return Err(format!("Environment variable '{key}' is repeated."));
}
}
Ok(environment)
}
pub(crate) fn environment_labels(environment: &BTreeMap<String, String>) -> Vec<String> {
environment
.iter()
.map(|(key, value)| format!("{key}={value}"))
.collect()
}
pub(crate) fn tagged_value_lines(
mut prefix: Vec<Span<'static>>,
selected: bool,
editing: bool,
values: &[String],
empty: &str,
width: u16,
) -> Vec<Line<'static>> {
let theme = THEME.as_ref();
if selected && editing {
return vec![Line::from(prefix)];
}
if values.is_empty() {
prefix.push(Span::styled(
empty.to_owned(),
Style::default().fg(theme.text_dim()),
));
return vec![Line::from(prefix)];
}
let available = width.saturating_sub(20) as usize;
let mut lines = Vec::new();
let mut spans = prefix;
let mut used = 0usize;
for value in values {
let badge_width = value.chars().count() + 2;
let separator = usize::from(used > 0);
if used > 0 && used + separator + badge_width > available {
lines.push(Line::from(spans));
spans = vec![Span::raw(" ".repeat(20))];
used = 0;
}
if used > 0 {
spans.push(Span::raw(" "));
used += 1;
}
spans.push(Span::styled(
format!(" {value} "),
Style::default()
.fg(if selected {
theme.accent()
} else {
theme.text()
})
.bg(theme.background())
.add_modifier(Modifier::BOLD),
));
used += badge_width;
}
lines.push(Line::from(spans));
lines
}
pub(crate) fn tagged_row_count(values: &[String], width: u16) -> usize {
if values.is_empty() {
return 1;
}
let available = width.saturating_sub(20) as usize;
let mut rows = 1;
let mut used = 0usize;
for value in values {
let badge_width = value.chars().count() + 2;
let separator = usize::from(used > 0);
if used > 0 && used + separator + badge_width > available {
rows += 1;
used = 0;
}
used += usize::from(used > 0) + badge_width;
}
rows
}
pub(crate) fn auto_label() -> Span<'static> {
status_badge("Auto", THEME.as_ref().success())
}