From c95f2d17ff64fd43cec74d25e74e46efa9209b77 Mon Sep 17 00:00:00 2001 From: objz Date: Thu, 3 Sep 2026 20:44:44 +0200 Subject: [PATCH] feat: add in-TUI settings editors --- src/cli/content.rs | 4 +- src/cli/import.rs | 4 +- src/cli/instance.rs | 28 +- src/cli/log.rs | 4 +- src/cli/mod.rs | 4 +- src/config/mod.rs | 83 +- src/config/settings.rs | 16 +- src/config/theme.rs | 134 +- src/instance/config_sync.rs | 2 +- src/instance/content/reconcile.rs | 20 +- src/instance/launch/mod.rs | 41 +- src/instance/loader/forge.rs | 1 + src/instance/loader/neoforge.rs | 1 + src/instance/models.rs | 19 + src/instance/runtime.rs | 8 + src/instance/tests/launch/pipeline.rs | 23 + src/instance/tests/models.rs | 13 + src/instance/tests/runtime.rs | 8 + src/launch_profile/templates.rs | 4 + src/launch_profile/tests/render.rs | 2 + src/launch_profile/tests/templates.rs | 14 + src/tui/app.rs | 12 +- src/tui/event.rs | 154 ++- src/tui/input.rs | 270 ++-- src/tui/mod.rs | 6 +- src/tui/render.rs | 22 +- src/tui/tests/event.rs | 174 +++ src/tui/tests/flows.rs | 37 +- src/tui/tests/harness.rs | 3 +- ..._empty_app_renders_the_complete_frame.snap | 2 +- ...nfirmation_renders_the_complete_frame.snap | 6 +- ...r_conflict_renders_the_complete_frame.snap | 2 +- src/tui/tests/widgets/popups/error/area.rs | 2 +- src/tui/tests/widgets/settings.rs | 19 - src/tui/widgets/content/discovery.rs | 10 +- src/tui/widgets/content/list.rs | 2 +- src/tui/widgets/content/tabs.rs | 10 +- src/tui/widgets/logs_viewer.rs | 23 +- src/tui/widgets/markdown.rs | 2 +- src/tui/widgets/popups/error.rs | 2 +- src/tui/widgets/popups/global_settings.rs | 435 +++++++ .../widgets/popups/import_modpack/state.rs | 13 +- src/tui/widgets/popups/instance_settings.rs | 1090 +++++++++++++++++ src/tui/widgets/popups/mod.rs | 3 + src/tui/widgets/popups/new_instance/state.rs | 20 +- src/tui/widgets/popups/version_lists.rs | 27 + src/tui/widgets/settings.rs | 536 +------- 47 files changed, 2574 insertions(+), 741 deletions(-) delete mode 100644 src/tui/tests/widgets/settings.rs create mode 100644 src/tui/widgets/popups/global_settings.rs create mode 100644 src/tui/widgets/popups/instance_settings.rs create mode 100644 src/tui/widgets/popups/version_lists.rs diff --git a/src/cli/content.rs b/src/cli/content.rs index efdd4e9..38b3d55 100644 --- a/src/cli/content.rs +++ b/src/cli/content.rs @@ -68,7 +68,7 @@ pub(crate) fn find_entry_by_stem<'a>( } fn list_entries(instance: &str, scan: Scanner) -> CliResult { - let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir(); + let instances_dir = crate::config::SETTINGS.read().paths.resolve_instances_dir(); require_instance(&instances_dir, instance)?; let rows = scan(&instances_dir, instance) .into_iter() @@ -95,7 +95,7 @@ fn toggle_entry( kind: &str, scan: Scanner, ) -> CliResult { - let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir(); + let instances_dir = crate::config::SETTINGS.read().paths.resolve_instances_dir(); require_instance(&instances_dir, instance)?; let entries = scan(&instances_dir, instance); let entry = find_entry_by_stem(&entries, target) diff --git a/src/cli/import.rs b/src/cli/import.rs index 086ef15..790ece1 100644 --- a/src/cli/import.rs +++ b/src/cli/import.rs @@ -16,8 +16,8 @@ pub async fn handle_import(matches: &ArgMatches) -> CliResult { let override_name = matches.get_one::("name"); let override_version = matches.get_one::("version"); - let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir(); - let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir(); + let instances_dir = crate::config::SETTINGS.read().paths.resolve_instances_dir(); + let meta_dir = crate::config::SETTINGS.read().paths.resolve_meta_dir(); let manager = InstanceManager::new(instances_dir, meta_dir); let client = crate::net::HttpClient::new(); diff --git a/src/cli/instance.rs b/src/cli/instance.rs index bbed75d..d6d8603 100644 --- a/src/cli/instance.rs +++ b/src/cli/instance.rs @@ -11,7 +11,7 @@ use clap::ArgMatches; use super::utils::{confirm, required_arg}; use crate::cli::output::{format_datetime, print_table}; use crate::instance::runtime::RunState; -use crate::instance::{InstanceManager, ModLoader}; +use crate::instance::{InstanceManager, ModLoader, models::parse_resolution}; type CliResult = Result<(), Box>; const LOCAL_CONFIG_PROFILE: &str = "instance default"; @@ -44,27 +44,9 @@ pub(crate) fn parse_loader(input: &str) -> Result { } } -pub(crate) fn parse_resolution(input: &str) -> Result<(u32, u32), String> { - let (width, height) = input - .split_once('x') - .ok_or_else(|| "resolution must be in WxH format".to_string())?; - let width = width - .parse::() - .map_err(|_| "resolution width must be a positive integer".to_string())?; - let height = height - .parse::() - .map_err(|_| "resolution height must be a positive integer".to_string())?; - - if width == 0 || height == 0 { - return Err("resolution values must be greater than zero".to_string()); - } - - Ok((width, height)) -} - fn manager() -> InstanceManager { - let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir(); - let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir(); + let instances_dir = crate::config::SETTINGS.read().paths.resolve_instances_dir(); + let meta_dir = crate::config::SETTINGS.read().paths.resolve_meta_dir(); InstanceManager::new(instances_dir, meta_dir) } @@ -135,8 +117,8 @@ fn rename_instance(matches: &ArgMatches) -> CliResult { async fn launch_instance(matches: &ArgMatches) -> CliResult { let name = required_arg(matches, "name")?; let manager = manager(); - let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir(); - let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir(); + let instances_dir = crate::config::SETTINGS.read().paths.resolve_instances_dir(); + let meta_dir = crate::config::SETTINGS.read().paths.resolve_meta_dir(); let config = manager.load_one(name)?; crate::instance::launch::launch(&config, &instances_dir, &meta_dir, None) diff --git a/src/cli/log.rs b/src/cli/log.rs index c492b89..09599b5 100644 --- a/src/cli/log.rs +++ b/src/cli/log.rs @@ -21,7 +21,7 @@ pub async fn handle_log(matches: &ArgMatches) -> CliResult { } fn list_logs(instance: &str) -> CliResult { - let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir(); + let instances_dir = crate::config::SETTINGS.read().paths.resolve_instances_dir(); require_instance(&instances_dir, instance)?; let rows = crate::instance::logs::files::scan_log_files(&instances_dir, instance) .into_iter() @@ -41,7 +41,7 @@ async fn show_log(matches: &ArgMatches) -> CliResult { let instance = required_arg(matches, "instance")?; let file = matches.get_one::("file").map(String::as_str); let follow = matches.get_flag("follow"); - let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir(); + let instances_dir = crate::config::SETTINGS.read().paths.resolve_instances_dir(); require_instance(&instances_dir, instance)?; let path = resolve_log_path(&instances_dir, instance, file)?; diff --git a/src/cli/mod.rs b/src/cli/mod.rs index 493e114..f32af79 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -27,8 +27,8 @@ pub async fn init() { return; } - let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir(); - let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir(); + let instances_dir = crate::config::SETTINGS.read().paths.resolve_instances_dir(); + let meta_dir = crate::config::SETTINGS.read().paths.resolve_meta_dir(); if crate::layout_migration::is_needed(&instances_dir, &meta_dir) { let config = crate::config::get_config_path().join("config.toml"); if let Err(error) = diff --git a/src/config/mod.rs b/src/config/mod.rs index caaaad4..e2e0ff9 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -7,7 +7,7 @@ use config::{Config as ConfigLoader, ConfigError, File}; use std::fs; use std::path::PathBuf; -use std::sync::LazyLock; +use std::sync::{LazyLock, RwLock, RwLockReadGuard}; pub mod settings; pub mod theme; @@ -56,18 +56,75 @@ pub fn load_config(config_path: &std::path::Path) -> Result .try_deserialize() } -pub static SETTINGS: LazyLock = LazyLock::new(|| { - 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(), - } - }) +pub struct ConfigStore(RwLock); + +impl ConfigStore { + pub fn read(&self) -> RwLockReadGuard<'_, Config> { + self.0 + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + + pub fn save_launcher_settings(&self, edited: Config) -> std::io::Result<()> { + 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; + *self + .0 + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) = runtime; + Ok(()) + } + + pub fn reload(&self) -> Result { + let mut config = load_config(&get_config_path().join("config.toml"))?; + let restart_required = { + let current = self.read(); + let changed = current.paths.instances_dir != config.paths.instances_dir + || current.paths.meta_dir != config.paths.meta_dir + || current.ui.image_protocol != config.ui.image_protocol; + // App owns a manager and several watchers rooted at these paths. + // Keep them stable for this process; persisted path edits apply on restart. + config + .paths + .instances_dir + .clone_from(¤t.paths.instances_dir); + config.paths.meta_dir.clone_from(¤t.paths.meta_dir); + config.ui.image_protocol = current.ui.image_protocol; + changed + }; + *self + .0 + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) = config; + Ok(restart_required) + } +} + +pub static SETTINGS: LazyLock = LazyLock::new(|| { + ConfigStore(RwLock::new({ + 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(), + } + }) + })) }); #[cfg(test)] diff --git a/src/config/settings.rs b/src/config/settings.rs index b38d932..807523a 100644 --- a/src/config/settings.rs +++ b/src/config/settings.rs @@ -6,9 +6,9 @@ use std::path::PathBuf; -use serde::Deserialize; +use serde::{Deserialize, Serialize}; -#[derive(Debug, Deserialize, Default, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Serialize, Deserialize, Default, Clone, Copy, PartialEq, Eq)] #[serde(rename_all = "lowercase")] pub enum ImageProtocol { Halfblocks, @@ -18,10 +18,10 @@ pub enum ImageProtocol { Iterm2, } -#[derive(Debug, Deserialize, Default)] +#[derive(Debug, Clone, Serialize, Deserialize, Default)] pub struct General {} -#[derive(Debug, Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct Content { #[serde(default = "default_true")] pub ask_on_provider_conflict: bool, @@ -119,7 +119,7 @@ impl Content { } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct Paths { #[serde(default = "default_instances_dir")] pub instances_dir: String, @@ -185,7 +185,7 @@ impl Paths { } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct Defaults { #[serde(default = "default_memory_min")] pub memory_min: String, @@ -209,7 +209,7 @@ impl Default for Defaults { } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] // timing knobs for the error toast animation: show for 5s, start sliding at 3.5s, // fly off screen over 300ms. tweak these if the toasts feel too fast or slow. pub struct Ui { @@ -250,7 +250,7 @@ impl Default for Ui { } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct Config { #[serde(default)] pub general: General, diff --git a/src/config/theme.rs b/src/config/theme.rs index 27fea15..3629844 100644 --- a/src/config/theme.rs +++ b/src/config/theme.rs @@ -6,7 +6,7 @@ // config/theme/ directory or by absolute path. use std::path::Path; -use std::sync::LazyLock; +use std::sync::{Arc, LazyLock, RwLock}; use ratatui::style::Color; use ratatui::widgets::BorderType; @@ -34,7 +34,7 @@ impl BorderStyle { } } -#[derive(Debug, Deserialize, Default)] +#[derive(Debug, Clone, Serialize, Deserialize, Default)] pub struct ThemeOverrides { pub accent: Option, pub accent_dim: Option, @@ -53,7 +53,7 @@ pub struct ThemeOverrides { pub background: Option, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct ThemeConfig { #[serde(default)] pub border_style: BorderStyle, @@ -167,12 +167,132 @@ fn load_base_theme(name: &str) -> Box { resolve_theme(name) } -static THEME_CONFIG: LazyLock = LazyLock::new(load_theme_config); +pub struct ThemeStore(RwLock>); -pub static THEME: LazyLock> = LazyLock::new(|| resolve_app_theme(&THEME_CONFIG)); +impl ThemeStore { + pub fn as_ref(&self) -> Arc { + self.0 + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + } -pub static BORDER_STYLE: LazyLock = - LazyLock::new(|| THEME_CONFIG.border_style.clone()); + fn set(&self, theme: Box) { + *self + .0 + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) = Arc::from(theme); + } +} + +pub struct BorderStyleStore(RwLock); + +impl BorderStyleStore { + pub fn to_border_type(&self) -> BorderType { + self.current().to_border_type() + } + + pub fn current(&self) -> BorderStyle { + self.0 + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + } + + fn set(&self, style: BorderStyle) { + *self + .0 + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) = style; + } +} + +static THEME_CONFIG: LazyLock> = + LazyLock::new(|| RwLock::new(load_theme_config())); + +pub static THEME: LazyLock = LazyLock::new(|| { + let config = THEME_CONFIG + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner); + ThemeStore(RwLock::new(Arc::from(resolve_app_theme(&config)))) +}); + +pub static BORDER_STYLE: LazyLock = LazyLock::new(|| { + let config = THEME_CONFIG + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner); + BorderStyleStore(RwLock::new(config.border_style.clone())) +}); + +pub fn current_theme_config() -> ThemeConfig { + THEME_CONFIG + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() +} + +pub fn apply_theme(theme: String, border_style: BorderStyle) -> std::io::Result<()> { + validate_theme_name(&theme)?; + let mut config = current_theme_config(); + config.theme = theme; + config.border_style = border_style.clone(); + let serialized = toml::to_string_pretty(&config).map_err(std::io::Error::other)?; + crate::storage::write_atomic( + &super::get_config_path().join("theme.toml"), + serialized.as_bytes(), + )?; + THEME.set(resolve_app_theme(&config)); + BORDER_STYLE.set(border_style); + *THEME_CONFIG + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) = config; + crate::feedback::request_redraw(); + Ok(()) +} + +fn validate_theme_name(name: &str) -> std::io::Result<()> { + if ratatui_themekit::available_theme_ids().contains(&name) { + return Ok(()); + } + let path = if Path::new(name).is_absolute() { + std::path::PathBuf::from(name) + } else { + let directory = super::get_config_path().join("theme"); + let direct = directory.join(name); + if direct.exists() { + direct + } else { + directory.join(format!("{name}.toml")) + } + }; + let content = std::fs::read_to_string(&path).map_err(|error| { + std::io::Error::new( + error.kind(), + format!("failed to load theme {}: {error}", path.display()), + ) + })?; + toml::from_str::(&content).map_err(|error| { + std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!("invalid theme {}: {error}", path.display()), + ) + })?; + Ok(()) +} + +pub fn reload_theme() -> std::io::Result<()> { + let path = super::get_config_path().join("theme.toml"); + let content = std::fs::read_to_string(path)?; + let config: ThemeConfig = toml::from_str(&content) + .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?; + THEME.set(resolve_app_theme(&config)); + BORDER_STYLE.set(config.border_style.clone()); + *THEME_CONFIG + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) = config; + crate::feedback::request_redraw(); + Ok(()) +} #[cfg(test)] #[path = "tests/theme.rs"] diff --git a/src/instance/config_sync.rs b/src/instance/config_sync.rs index 3ae13b3..21b0cd7 100644 --- a/src/instance/config_sync.rs +++ b/src/instance/config_sync.rs @@ -113,7 +113,7 @@ pub fn switch_profile( meta_dir: &Path, instance_dir: &Path, ) -> Result, ConfigSyncError> { - if crate::instance::runtime::get(instance_name).is_some() { + if crate::instance::runtime::is_active(instance_name) { return Err(ConfigSyncError::InstanceRunning { instance: instance_name.to_string(), }); diff --git a/src/instance/content/reconcile.rs b/src/instance/content/reconcile.rs index 033ed74..8406e97 100644 --- a/src/instance/content/reconcile.rs +++ b/src/instance/content/reconcile.rs @@ -151,8 +151,11 @@ async fn reconcile(job: ReconcileJob, task: &ProgressTask) -> ReconcileResult { let paths = InstancePaths::new(instances_dir.join(&instance_name)); let manifest_path = paths.content_manifest(); let minecraft_dir = paths.minecraft(); - let retry_hours = crate::config::SETTINGS.content.unmatched_retry_hours; - let max_fingerprint_size_mib = crate::config::SETTINGS.content.max_fingerprint_size_mib; + let retry_hours = crate::config::SETTINGS.read().content.unmatched_retry_hours; + let max_fingerprint_size_mib = crate::config::SETTINGS + .read() + .content + .max_fingerprint_size_mib; let inventory_progress = task.handle(); let inventory_minecraft_dir = minecraft_dir.clone(); let inventory = tokio::task::spawn_blocking(move || { @@ -400,6 +403,7 @@ fn reconcile_inventory( } let provider_unchecked = ["modrinth", "curseforge"].into_iter().any(|provider| { crate::config::SETTINGS + .read() .content .discovery_provider_enabled(provider) && provider_was_not_checked(&record, provider) @@ -553,8 +557,16 @@ async fn resolve_queries( }, Vec::new(), ), - _ if !crate::config::SETTINGS.content.ask_on_provider_conflict => { - let preferred = crate::config::SETTINGS.content.preferred_provider(); + _ if !crate::config::SETTINGS + .read() + .content + .ask_on_provider_conflict => + { + let preferred = crate::config::SETTINGS + .read() + .content + .preferred_provider() + .to_owned(); if let Some(project) = candidates .iter() .find(|project| project.provider == preferred) diff --git a/src/instance/launch/mod.rs b/src/instance/launch/mod.rs index dc676e4..54dcf34 100644 --- a/src/instance/launch/mod.rs +++ b/src/instance/launch/mod.rs @@ -59,6 +59,18 @@ fn build_game_args( Ok((rendered.jvm, rendered.game)) } +fn apply_custom_resolution(game_args: &mut Vec, resolution: Option<(u32, u32)>) { + let Some((width, height)) = resolution else { + return; + }; + if !game_args.iter().any(|arg| arg == "--width") { + game_args.extend(["--width".to_owned(), width.to_string()]); + } + if !game_args.iter().any(|arg| arg == "--height") { + game_args.extend(["--height".to_owned(), height.to_string()]); + } +} + fn parse_java_major_version(text: &str) -> Option { let quoted = text .split_once('"') @@ -384,6 +396,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), ..Default::default() }; let host_os_version = system::mojang_os_version(); @@ -539,6 +552,7 @@ pub async fn build_launch_invocation( .clone() .or_else(|| { crate::config::SETTINGS + .read() .paths .effective_java_path() .map(str::to_owned) @@ -560,6 +574,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 template_ctx = TemplateContext { library_directory, classpath_separator: sep, @@ -580,15 +596,30 @@ pub async fn build_launch_invocation( launcher_version: env!("CARGO_PKG_VERSION"), clientid: "0", quick_play_singleplayer: quick_play_world, + resolution_width: resolution_width.as_deref(), + resolution_height: resolution_height.as_deref(), }; - let (upstream_jvm_args, game_args) = + let (upstream_jvm_args, mut game_args) = 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); - let mut jvm_args: Vec = vec![ - format!("-Xms{}", config.memory_min.as_deref().unwrap_or("512M")), - format!("-Xmx{}", config.memory_max.as_deref().unwrap_or("2G")), - ]; + let (memory_min, memory_max) = { + let settings = crate::config::SETTINGS.read(); + ( + config + .memory_min + .clone() + .unwrap_or_else(|| settings.defaults.memory_min.clone()), + config + .memory_max + .clone() + .unwrap_or_else(|| settings.defaults.memory_max.clone()), + ) + }; + let mut jvm_args: Vec = vec![format!("-Xms{memory_min}"), format!("-Xmx{memory_max}")]; jvm_args.extend(patch_jvm_args); jvm_args.extend(upstream_jvm_args); jvm_args.extend(config.jvm_args.clone()); diff --git a/src/instance/loader/forge.rs b/src/instance/loader/forge.rs index 0959912..d72a436 100644 --- a/src/instance/loader/forge.rs +++ b/src/instance/loader/forge.rs @@ -77,6 +77,7 @@ impl ModLoaderInstaller for ForgeInstaller { } else { // modern forge: run the java installer let java_path = crate::config::SETTINGS + .read() .paths .effective_java_path() .map(str::to_owned) diff --git a/src/instance/loader/neoforge.rs b/src/instance/loader/neoforge.rs index 7be7494..221128a 100644 --- a/src/instance/loader/neoforge.rs +++ b/src/instance/loader/neoforge.rs @@ -57,6 +57,7 @@ impl ModLoaderInstaller for NeoForgeInstaller { neoforge_api::download_neoforge_installer(client, loader_version, &installer_jar).await?; let java_path = crate::config::SETTINGS + .read() .paths .effective_java_path() .map(str::to_owned) diff --git a/src/instance/models.rs b/src/instance/models.rs index 5bd456b..baa8051 100644 --- a/src/instance/models.rs +++ b/src/instance/models.rs @@ -56,6 +56,25 @@ pub struct InstanceConfig { pub modpack_source: Option, } +pub fn parse_resolution(input: &str) -> Result<(u32, u32), String> { + let (width, height) = input + .trim() + .split_once(['x', 'X']) + .ok_or_else(|| "resolution must be in WxH format".to_string())?; + let width = width + .parse::() + .map_err(|_| "resolution width must be a positive integer".to_string())?; + let height = height + .parse::() + .map_err(|_| "resolution height must be a positive integer".to_string())?; + + if width == 0 || height == 0 { + return Err("resolution values must be greater than zero".to_string()); + } + + Ok((width, height)) +} + pub fn normalize_memory_value(raw: &str) -> Option { let trimmed = raw.trim(); if trimmed.is_empty() { diff --git a/src/instance/runtime.rs b/src/instance/runtime.rs index 5cb2a8b..e358f26 100644 --- a/src/instance/runtime.rs +++ b/src/instance/runtime.rs @@ -52,6 +52,14 @@ pub fn get(name: &str) -> Option { RUNNING.lock().ok().and_then(|map| map.get(name).cloned()) } +#[must_use] +pub fn is_active(name: &str) -> bool { + matches!( + get(name), + Some(RunState::Authenticating | RunState::Starting | RunState::Running) + ) +} + #[must_use] pub fn all() -> Vec<(String, RunState)> { RUNNING diff --git a/src/instance/tests/launch/pipeline.rs b/src/instance/tests/launch/pipeline.rs index dc7c75f..a4aa5b0 100644 --- a/src/instance/tests/launch/pipeline.rs +++ b/src/instance/tests/launch/pipeline.rs @@ -57,6 +57,8 @@ fn build_game_args_renders_upstream_arguments() { launcher_version: "test", clientid: "0", quick_play_singleplayer: None, + resolution_width: None, + resolution_height: None, version_type: "release", }; let features = FeatureSet::default(); @@ -89,6 +91,27 @@ fn build_game_args_renders_upstream_arguments() { assert_eq!(game_args, vec!["--username", "Player"]); } +#[test] +fn custom_resolution_is_added_once() { + let mut args = vec!["--username".to_owned(), "Player".to_owned()]; + apply_custom_resolution(&mut args, Some((1920, 1080))); + assert_eq!( + args, + [ + "--username", + "Player", + "--width", + "1920", + "--height", + "1080" + ] + ); + + apply_custom_resolution(&mut args, Some((1280, 720))); + assert_eq!(args.iter().filter(|arg| *arg == "--width").count(), 1); + assert_eq!(args.iter().filter(|arg| *arg == "--height").count(), 1); +} + // exercises the early-return branch of migrate_legacy_meta_if_needed. // a profile with either arguments or minecraftArguments is not legacy // and must produce Ok(None) without touching the network. covers both diff --git a/src/instance/tests/models.rs b/src/instance/tests/models.rs index 62a41c8..88eb681 100644 --- a/src/instance/tests/models.rs +++ b/src/instance/tests/models.rs @@ -84,3 +84,16 @@ fn normalize_memory_value_rejects_invalid_values() { assert_eq!(normalize_memory_value("8GB"), None); assert_eq!(normalize_memory_value("banana"), None); } + +#[test] +fn parse_resolution_accepts_common_separators() { + assert_eq!(parse_resolution("1920x1080"), Ok((1920, 1080))); + assert_eq!(parse_resolution(" 1280X720 "), Ok((1280, 720))); +} + +#[test] +fn parse_resolution_rejects_invalid_values() { + assert!(parse_resolution("1920").is_err()); + assert!(parse_resolution("0x1080").is_err()); + assert!(parse_resolution("wide x tall").is_err()); +} diff --git a/src/instance/tests/runtime.rs b/src/instance/tests/runtime.rs index 24b9ec5..fc191db 100644 --- a/src/instance/tests/runtime.rs +++ b/src/instance/tests/runtime.rs @@ -41,6 +41,14 @@ fn crashed_state_stores_exit_code() { assert_eq!(get("run_test_crash"), Some(RunState::Crashed(Some(1)))); } +#[test] +fn crashed_instances_are_not_active() { + set_state("run_test_inactive_crash", RunState::Crashed(Some(1))); + assert!(!is_active("run_test_inactive_crash")); + set_state("run_test_active_start", RunState::Starting); + assert!(is_active("run_test_active_start")); +} + #[test] fn push_and_drain_last_played() { let time = Utc::now(); diff --git a/src/launch_profile/templates.rs b/src/launch_profile/templates.rs index d3353c2..25e9fd6 100644 --- a/src/launch_profile/templates.rs +++ b/src/launch_profile/templates.rs @@ -33,6 +33,8 @@ pub struct TemplateContext<'a> { pub launcher_version: &'a str, pub clientid: &'a str, pub quick_play_singleplayer: Option<&'a str>, + pub resolution_width: Option<&'a str>, + pub resolution_height: Option<&'a str>, } pub fn substitute(input: &str, ctx: &TemplateContext) -> String { @@ -88,6 +90,8 @@ fn lookup(name: &str, ctx: &TemplateContext) -> Option { "launcher_version" => ctx.launcher_version.to_string(), "clientid" => ctx.clientid.to_string(), "quickPlaySingleplayer" => ctx.quick_play_singleplayer?.to_owned(), + "resolution_width" => ctx.resolution_width?.to_owned(), + "resolution_height" => ctx.resolution_height?.to_owned(), _ => return None, }) } diff --git a/src/launch_profile/tests/render.rs b/src/launch_profile/tests/render.rs index 3a24e52..1bb3dec 100644 --- a/src/launch_profile/tests/render.rs +++ b/src/launch_profile/tests/render.rs @@ -50,6 +50,8 @@ impl Fixture { launcher_version: "0.3.0", clientid: "0", quick_play_singleplayer: None, + resolution_width: None, + resolution_height: None, } } diff --git a/src/launch_profile/tests/templates.rs b/src/launch_profile/tests/templates.rs index ae80610..db84c30 100644 --- a/src/launch_profile/tests/templates.rs +++ b/src/launch_profile/tests/templates.rs @@ -58,6 +58,8 @@ impl Fixture { launcher_version: "0.3.0", clientid: "0", quick_play_singleplayer: None, + resolution_width: None, + resolution_height: None, } } } @@ -115,3 +117,15 @@ fn quick_play_world_is_substituted_when_present() { "New World" ); } + +#[test] +fn custom_resolution_is_substituted_when_present() { + let fx = Fixture::unix(); + let mut context = fx.ctx(); + context.resolution_width = Some("1920"); + context.resolution_height = Some("1080"); + assert_eq!( + substitute("${resolution_width}x${resolution_height}", &context), + "1920x1080" + ); +} diff --git a/src/tui/app.rs b/src/tui/app.rs index f25793b..ae2d527 100644 --- a/src/tui/app.rs +++ b/src/tui/app.rs @@ -41,7 +41,8 @@ pub struct App { pub(super) screenshots_state: widgets::screenshots_grid::ScreenshotsState, pub(super) logs_state: widgets::logs_viewer::LogsState, pub(super) account_state: widgets::account::AccountState, - pub(super) settings_state: widgets::settings::SettingsState, + pub(super) instance_settings: Option, + pub(super) global_settings: Option, pub(super) picker: ratatui_image::picker::Picker, pub(super) instance_manager: InstanceManager, pub(super) log_overlay_scroll: usize, @@ -89,6 +90,8 @@ pub enum FocusedArea { ImportPopup, ErrorPopup, ConfirmDelete, + InstanceSettings, + GlobalSettings, } impl App { @@ -115,8 +118,8 @@ impl App { } pub fn new(picker: ratatui_image::picker::Picker) -> Self { - let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir(); - let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir(); + let instances_dir = crate::config::SETTINGS.read().paths.resolve_instances_dir(); + let meta_dir = crate::config::SETTINGS.read().paths.resolve_meta_dir(); let _ = std::fs::create_dir_all(&instances_dir); let _ = std::fs::create_dir_all(&meta_dir); @@ -169,7 +172,8 @@ impl App { world_quick_play_support: None, logs_state: widgets::logs_viewer::LogsState::default(), account_state: widgets::account::AccountState::default(), - settings_state: widgets::settings::SettingsState::new(manager.meta_dir.clone()), + instance_settings: None, + global_settings: None, screenshots_state: { let mut s = widgets::screenshots_grid::ScreenshotsState::default(); let font_size = picker.font_size(); diff --git a/src/tui/event.rs b/src/tui/event.rs index b1d06f9..e04ac89 100644 --- a/src/tui/event.rs +++ b/src/tui/event.rs @@ -209,6 +209,8 @@ impl App { + usize::from(self.instances_state.show_import_popup) + usize::from(self.focused == super::app::FocusedArea::OverviewExpanded) + usize::from(self.focused == super::app::FocusedArea::ConfirmDelete) + + usize::from(self.focused == super::app::FocusedArea::InstanceSettings) + + usize::from(self.focused == super::app::FocusedArea::GlobalSettings) + usize::from(self.provider_conflict.is_some()) + usize::from( self.content_update_popup @@ -221,10 +223,6 @@ impl App { &self.account_state.add_mode, widgets::account::AddMode::None )) - + usize::from(!matches!( - &self.settings_state.add_mode, - widgets::settings::AddMode::None - )) + [ &self.mods_discovery_state, &self.resource_packs_discovery_state, @@ -505,7 +503,10 @@ impl App { } fn ensure_provider_conflict_popup(&mut self) { - if !crate::config::SETTINGS.content.ask_on_provider_conflict + if !crate::config::SETTINGS + .read() + .content + .ask_on_provider_conflict || self.focused != super::app::FocusedArea::Content || self.provider_conflict.is_some() { @@ -569,7 +570,7 @@ impl App { fn spawn_create(&self, params: new_instance::WizardParams) { let instances_dir = self.instance_manager.instances_dir.clone(); - let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir(); + let meta_dir = crate::config::SETTINGS.read().paths.resolve_meta_dir(); let pending_instances = PENDING_INSTANCES.clone(); tokio::spawn(async move { @@ -605,9 +606,64 @@ impl App { }); } + pub(super) fn spawn_instance_settings_update( + &self, + previous: crate::instance::InstanceConfig, + mut updated: crate::instance::InstanceConfig, + desktop: bool, + ) { + let instances_dir = self.instance_manager.instances_dir.clone(); + let meta_dir = self.instance_manager.meta_dir.clone(); + let pending_instances = PENDING_INSTANCES.clone(); + + tokio::spawn(async move { + progress::set_action(format!("Updating instance '{}'...", updated.name)); + progress::set_sub_action(format!("{} {}", updated.game_version, updated.loader)); + let manager = InstanceManager::new(&instances_dir, &meta_dir); + updated = match apply_instance_settings_update(&manager, &previous, updated).await { + Ok(updated) => updated, + Err(error) => { + progress::clear(); + error_buffer::push_error(error_buffer::ErrorEvent { + id: 0, + level: tracing::Level::ERROR, + message: format!("Failed to update instance '{}': {error}", previous.name), + pushed_at: std::time::Instant::now(), + }); + return; + } + }; + + let shortcut_result = if desktop { + crate::instance::desktop::create(&updated).map(|_| ()) + } else { + crate::instance::desktop::remove(&updated.name) + }; + if let Err(error) = shortcut_result { + error_buffer::push_error(error_buffer::ErrorEvent { + id: 0, + level: tracing::Level::ERROR, + message: format!("Instance saved, but shortcut update failed: {error}"), + pushed_at: std::time::Instant::now(), + }); + } + if let Ok(mut pending) = pending_instances.lock() { + pending.push(updated); + } + progress::clear(); + error_buffer::push_error(error_buffer::ErrorEvent { + id: 0, + level: tracing::Level::INFO, + message: format!("Updated instance '{}'", previous.name), + pushed_at: std::time::Instant::now(), + }); + crate::feedback::request_redraw(); + }); + } + fn spawn_import(&self, result: import_modpack::ImportResult) { let instances_dir = self.instance_manager.instances_dir.clone(); - let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir(); + let meta_dir = crate::config::SETTINGS.read().paths.resolve_meta_dir(); let pending_instances = PENDING_INSTANCES.clone(); tokio::spawn(async move { @@ -689,8 +745,38 @@ impl App { } fn reload_edited_config(&mut self, path: &std::path::Path) { - if path.file_name().and_then(|n| n.to_str()) != Some("instance.json") { - return; + 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) => {} + Err(error) => error_buffer::push_error(error_buffer::ErrorEvent { + id: 0, + level: tracing::Level::ERROR, + message: format!("Failed to reload config.toml: {error}"), + pushed_at: std::time::Instant::now(), + }), + } + return; + } + Some("theme.toml") => { + if let Err(error) = crate::config::theme::reload_theme() { + error_buffer::push_error(error_buffer::ErrorEvent { + id: 0, + level: tracing::Level::ERROR, + message: format!("Failed to reload theme.toml: {error}"), + pushed_at: std::time::Instant::now(), + }); + } + return; + } + Some("instance.json") => {} + _ => return, } let Some(name) = path @@ -776,7 +862,7 @@ impl App { match error_buffer::peek_error() { Some(event) if event.pushed_at.elapsed().as_millis() - >= SETTINGS.ui.error_auto_dismiss_ms as u128 => + >= SETTINGS.read().ui.error_auto_dismiss_ms as u128 => { let _ = error_buffer::pop_error(); } @@ -790,7 +876,17 @@ impl App { for config in pending.drain(..) { self.forget_instance_content(&config.name); widgets::instances::spawn_modpack_update_check(&config); - self.instances_state.add_instance(config); + if self + .instances_state + .instances + .iter() + .any(|instance| instance.name == config.name) + { + let name = config.name.clone(); + self.instances_state.replace_instance(&name, config); + } else { + self.instances_state.add_instance(config); + } } } } @@ -840,6 +936,42 @@ impl App { } } +async fn apply_instance_settings_update( + manager: &InstanceManager, + previous: &crate::instance::InstanceConfig, + mut updated: crate::instance::InstanceConfig, +) -> color_eyre::Result { + manager.repair_runtime_cache(&updated).await?; + + let profile_changed = previous.config_sync_profile != updated.config_sync_profile; + if profile_changed { + updated.config_sync_profile = crate::instance::config_sync::switch_profile( + &previous.name, + previous.config_sync_profile.as_deref(), + updated.config_sync_profile.as_deref(), + &manager.meta_dir, + &manager.instances_dir.join(&previous.name), + )?; + } + + if let Err(error) = manager.save(&updated) { + if profile_changed + && let Err(rollback_error) = crate::instance::config_sync::switch_profile( + &previous.name, + updated.config_sync_profile.as_deref(), + previous.config_sync_profile.as_deref(), + &manager.meta_dir, + &manager.instances_dir.join(&previous.name), + ) + { + tracing::error!("Failed to roll back config profile: {rollback_error}"); + } + return Err(error.into()); + } + + Ok(updated) +} + fn mark_terminal_images(buffer: &mut Buffer, alternate: bool) { // toggling an invisible suffix lets the normal cell diff redraw exposed // images before later popup cells, without clearing or repainting the screen diff --git a/src/tui/input.rs b/src/tui/input.rs index f3be45b..a8fd94b 100644 --- a/src/tui/input.rs +++ b/src/tui/input.rs @@ -552,101 +552,185 @@ impl App { return Ok(()); } - if self.focused == FocusedArea::Settings { - let editing_profile = matches!( - &self.settings_state.add_mode, - widgets::settings::AddMode::ProfileName(_) - ); - match widgets::settings::handle_key( - &key_event, - &mut self.settings_state, - self.instances_state.selected_instance(), - &self.instance_manager.instances_dir, - ) { - widgets::settings::SettingsAction::EditInstance(path) - | widgets::settings::SettingsAction::EditGlobal(path) => { - self.pending_editor = Some(path); - return Ok(()); + if self.focused == FocusedArea::GlobalSettings { + let action = self + .global_settings + .as_mut() + .map(|state| state.handle_key(&key_event)) + .unwrap_or(widgets::popups::global_settings::Action::Close); + match action { + widgets::popups::global_settings::Action::None => {} + widgets::popups::global_settings::Action::Close => { + self.global_settings = None; + self.focused = self.pre_overlay_focused; } - widgets::settings::SettingsAction::ToggleDesktop => { - if let Some(inst) = self.instances_state.selected_instance() { - let name = inst.name.clone(); - match crate::instance::desktop::toggle(inst) { - Ok(true) => { - error_buffer::push_error(error_buffer::ErrorEvent { - id: 0, - level: tracing::Level::INFO, - message: format!("Desktop shortcut created for '{name}'"), - pushed_at: std::time::Instant::now(), - }); - } - Ok(false) => { - error_buffer::push_error(error_buffer::ErrorEvent { - id: 0, - level: tracing::Level::INFO, - message: format!("Desktop shortcut removed for '{name}'"), - pushed_at: std::time::Instant::now(), - }); - } - Err(e) => { - tracing::error!("Failed to toggle desktop shortcut: {}", e); + widgets::popups::global_settings::Action::OpenRaw(path) => { + self.pending_editor = Some(path); + self.global_settings = None; + self.focused = self.pre_overlay_focused; + } + widgets::popups::global_settings::Action::Save(config, theme, border) => { + let result = crate::config::SETTINGS + .save_launcher_settings(*config) + .and_then(|()| crate::config::theme::apply_theme(theme, border)); + match result { + Ok(()) => { + self.global_settings = None; + self.focused = self.pre_overlay_focused; + } + Err(error) => error_buffer::push_error(error_buffer::ErrorEvent { + id: 0, + level: tracing::Level::ERROR, + message: error.to_string(), + pushed_at: std::time::Instant::now(), + }), + } + } + } + return Ok(()); + } + + if self.focused == FocusedArea::InstanceSettings { + let action = self + .instance_settings + .as_mut() + .map(|state| state.handle_key(&key_event)) + .unwrap_or(widgets::popups::instance_settings::Action::Close); + match action { + widgets::popups::instance_settings::Action::None => {} + widgets::popups::instance_settings::Action::Close => { + self.instance_settings = None; + self.focused = self.pre_overlay_focused; + } + widgets::popups::instance_settings::Action::OpenRaw => { + if let Some(instance) = self.instances_state.selected_instance() { + self.pending_editor = Some( + self.instance_manager + .instances_dir + .join(&instance.name) + .join("instance.json"), + ); + } + self.instance_settings = None; + self.focused = self.pre_overlay_focused; + } + widgets::popups::instance_settings::Action::DeleteProfile(profile) => { + match self.delete_config_profile(&profile) { + Ok(()) => { + if let Some(state) = self.instance_settings.as_mut() { + state.profile_deleted(&profile); } } + Err(error) => error_buffer::push_error(error_buffer::ErrorEvent { + id: 0, + level: tracing::Level::ERROR, + message: error.to_string(), + pushed_at: std::time::Instant::now(), + }), } - return Ok(()); } - widgets::settings::SettingsAction::SelectProfile(profile) => { - if let Some(inst) = self.instances_state.selected_instance().cloned() { - let instance_dir = self.instance_manager.instances_dir.join(&inst.name); - match crate::instance::config_sync::switch_profile( - &inst.name, - inst.config_sync_profile.as_deref(), - profile.as_deref(), - &self.instance_manager.meta_dir, - &instance_dir, - ) { - Ok(selected) => { - let mut updated = inst.clone(); - updated.config_sync_profile = selected; - if let Err(e) = self.instance_manager.save(&updated) { - tracing::error!("Failed to save config profile: {}", e); - } else { - self.instances_state.replace_instance(&inst.name, updated); - } - } - Err(e) => { + widgets::popups::instance_settings::Action::Save(updated, desktop) => { + let mut updated = *updated; + if let Some(previous) = self.instances_state.selected_instance().cloned() { + let structural_change = previous.game_version != updated.game_version + || previous.loader != updated.loader + || previous.loader_version != updated.loader_version; + if structural_change { + if crate::instance::runtime::is_active(&previous.name) { error_buffer::push_error(error_buffer::ErrorEvent { id: 0, level: tracing::Level::ERROR, - message: e.to_string(), + message: "Stop the instance before changing its runtime" + .to_owned(), + pushed_at: std::time::Instant::now(), + }); + return Ok(()); + } + self.spawn_instance_settings_update(previous, updated, desktop); + self.instance_settings = None; + self.focused = self.pre_overlay_focused; + return Ok(()); + } + if previous.config_sync_profile != updated.config_sync_profile { + let instance_dir = + self.instance_manager.instances_dir.join(&previous.name); + match crate::instance::config_sync::switch_profile( + &previous.name, + previous.config_sync_profile.as_deref(), + updated.config_sync_profile.as_deref(), + &self.instance_manager.meta_dir, + &instance_dir, + ) { + Ok(profile) => updated.config_sync_profile = profile, + Err(error) => { + error_buffer::push_error(error_buffer::ErrorEvent { + id: 0, + level: tracing::Level::ERROR, + message: error.to_string(), + pushed_at: std::time::Instant::now(), + }); + return Ok(()); + } + } + } + match self.instance_manager.save(&updated) { + Ok(()) => { + let shortcut_result = if desktop { + crate::instance::desktop::create(&updated).map(|_| ()) + } else { + crate::instance::desktop::remove(&updated.name) + }; + if let Err(error) = shortcut_result { + error_buffer::push_error(error_buffer::ErrorEvent { + id: 0, + level: tracing::Level::ERROR, + message: format!( + "Instance saved, but shortcut update failed: {error}" + ), + pushed_at: std::time::Instant::now(), + }); + } + self.instances_state + .replace_instance(&previous.name, updated); + error_buffer::push_error(error_buffer::ErrorEvent { + id: 0, + level: tracing::Level::INFO, + message: format!("Updated instance '{}'", previous.name), + pushed_at: std::time::Instant::now(), + }); + self.instance_settings = None; + self.focused = self.pre_overlay_focused; + } + Err(error) => { + if previous.config_sync_profile != updated.config_sync_profile { + let instance_dir = + self.instance_manager.instances_dir.join(&previous.name); + if let Err(rollback_error) = + crate::instance::config_sync::switch_profile( + &previous.name, + updated.config_sync_profile.as_deref(), + previous.config_sync_profile.as_deref(), + &self.instance_manager.meta_dir, + &instance_dir, + ) + { + tracing::error!( + "Failed to roll back config profile: {rollback_error}" + ); + } + } + error_buffer::push_error(error_buffer::ErrorEvent { + id: 0, + level: tracing::Level::ERROR, + message: error.to_string(), pushed_at: std::time::Instant::now(), }); } } } - return Ok(()); } - widgets::settings::SettingsAction::ConfirmDeleteProfile(profile) => { - confirm_popup::set_pending(confirm_popup::ConfirmTarget::ConfigProfile { - profile, - }); - self.focused = FocusedArea::ConfirmDelete; - return Ok(()); - } - widgets::settings::SettingsAction::Error(message) => { - error_buffer::push_error(error_buffer::ErrorEvent { - id: 0, - level: tracing::Level::ERROR, - message, - pushed_at: std::time::Instant::now(), - }); - return Ok(()); - } - widgets::settings::SettingsAction::None => {} - } - if editing_profile { - return Ok(()); } + return Ok(()); } match self.focused { @@ -732,6 +816,22 @@ impl App { KeyCode::Char('C') => self.focused = FocusedArea::Content, KeyCode::Char('A') => self.focused = FocusedArea::Account, KeyCode::Char('S') => self.focused = FocusedArea::Settings, + KeyCode::Char('E') => { + if let Some(instance) = self.instances_state.selected_instance() { + self.pre_overlay_focused = self.focused; + self.instance_settings = + Some(widgets::popups::instance_settings::State::new( + instance, + &self.instance_manager.meta_dir, + )); + self.focused = FocusedArea::InstanceSettings; + } + } + KeyCode::Char('G') => { + self.pre_overlay_focused = self.focused; + self.global_settings = Some(widgets::popups::global_settings::State::new()); + self.focused = FocusedArea::GlobalSettings; + } KeyCode::Char('O') => { self.pre_overlay_focused = self.focused; self.focused = FocusedArea::OverviewExpanded; @@ -1783,6 +1883,15 @@ impl App { fn delete_config_profile(&mut self, profile: &str) -> color_eyre::Result<()> { let instances = self.instance_manager.load_all(); + if let Some(instance) = instances.iter().find(|instance| { + instance.config_sync_profile.as_deref() == Some(profile) + && crate::instance::runtime::is_active(&instance.name) + }) { + return Err(color_eyre::eyre::eyre!( + "Stop '{}' before deleting its active config profile", + instance.name + )); + } for instance in instances .into_iter() .filter(|instance| instance.config_sync_profile.as_deref() == Some(profile)) @@ -1802,7 +1911,6 @@ impl App { } crate::instance::config_sync::delete_profile(&self.instance_manager.meta_dir, profile)?; - self.settings_state.remove_profile(profile); Ok(()) } diff --git a/src/tui/mod.rs b/src/tui/mod.rs index ac1bb29..7907b7a 100644 --- a/src/tui/mod.rs +++ b/src/tui/mod.rs @@ -49,7 +49,7 @@ pub async fn show() -> color_eyre::Result<()> { let mut picker = ratatui_image::picker::Picker::from_query_stdio() .unwrap_or_else(|_| ratatui_image::picker::Picker::halfblocks()); let detected_protocol = picker.protocol_type(); - let requested_protocol = match crate::config::SETTINGS.ui.image_protocol { + let requested_protocol = match crate::config::SETTINGS.read().ui.image_protocol { crate::config::settings::ImageProtocol::Halfblocks | crate::config::settings::ImageProtocol::Quadrants => { ratatui_image::picker::ProtocolType::Halfblocks @@ -106,8 +106,8 @@ async fn run_layout_migration_screen( use std::sync::{Arc, Mutex}; use std::time::Duration; - let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir(); - let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir(); + let instances_dir = crate::config::SETTINGS.read().paths.resolve_instances_dir(); + let meta_dir = crate::config::SETTINGS.read().paths.resolve_meta_dir(); if !crate::layout_migration::is_needed(&instances_dir, &meta_dir) { crate::layout_migration::initialize_new_layout(&meta_dir)?; return Ok(MigrationScreenOutcome::NotNeeded); diff --git a/src/tui/render.rs b/src/tui/render.rs index 44db0a8..e0f213e 100644 --- a/src/tui/render.rs +++ b/src/tui/render.rs @@ -135,9 +135,7 @@ impl App { frame, bottom_chunks[1], self.focused, - &mut self.settings_state, self.instances_state.selected_instance(), - &self.instance_manager.instances_dir, ); widgets::status::render( frame, @@ -150,6 +148,20 @@ impl App { self.render_log_overlay(frame); } + if self.focused == FocusedArea::InstanceSettings + && let Some(state) = self.instance_settings.as_ref() + { + let area = widgets::popups::instance_settings::popup_rect(frame.area()); + widgets::popups::instance_settings::render(frame, area, state); + } + + if self.focused == FocusedArea::GlobalSettings + && let Some(state) = self.global_settings.as_ref() + { + let area = widgets::popups::instance_settings::popup_rect(frame.area()); + widgets::popups::global_settings::render(frame, area, state); + } + // error toasts stack from the top, each one below the previous let all_errors = error_buffer::peek_all_errors(); self.sync_error_effects(&all_errors); @@ -343,9 +355,9 @@ impl App { use crate::config::theme::THEME; let theme = THEME.as_ref(); let bg = theme.background(); - let fly_out_ms = SETTINGS.ui.error_fly_out_ms as u128; - let fly_start_ms = SETTINGS.ui.error_auto_dismiss_ms as u128 - - fly_out_ms.min(SETTINGS.ui.error_auto_dismiss_ms as u128); + let fly_out_ms = SETTINGS.read().ui.error_fly_out_ms as u128; + let fly_start_ms = SETTINGS.read().ui.error_auto_dismiss_ms as u128 + - fly_out_ms.min(SETTINGS.read().ui.error_auto_dismiss_ms as u128); if elapsed_ms >= fly_start_ms { let entry = self diff --git a/src/tui/tests/event.rs b/src/tui/tests/event.rs index 377157c..12ffa58 100644 --- a/src/tui/tests/event.rs +++ b/src/tui/tests/event.rs @@ -57,6 +57,180 @@ fn completed_background_instance_is_drained_into_the_ui() { assert_eq!(ui.app.mods_state.loaded_for.as_deref(), Some("Pending")); } +#[test] +fn structural_settings_update_repairs_runtime_before_persisting() { + use sha1::{Digest, Sha1}; + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + fn sha1(bytes: &[u8]) -> String { + format!("{:x}", Sha1::digest(bytes)) + } + + let _guard = crate::tests::TEST_LOCK + .lock() + .unwrap_or_else(|error| error.into_inner()); + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + runtime.block_on(async { + let server = MockServer::start().await; + let client_jar = b"client"; + let library_jar = b"library"; + for (endpoint, body) in [ + ("/client.jar", client_jar.as_slice()), + ("/library.jar", library_jar.as_slice()), + ] { + Mock::given(method("GET")) + .and(path(endpoint)) + .respond_with(ResponseTemplate::new(200).set_body_bytes(body.to_vec())) + .expect(1) + .mount(&server) + .await; + } + Mock::given(method("GET")) + .and(path("/assets.json")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "objects": {} + }))) + .expect(1) + .mount(&server) + .await; + + let temp = tempfile::tempdir().unwrap(); + let instances_dir = temp.path().join("instances"); + let meta_dir = temp.path().join("meta"); + let instance_dir = instances_dir.join("Migrating"); + std::fs::create_dir_all(&instance_dir).unwrap(); + let manager = InstanceManager::new(&instances_dir, &meta_dir); + let mut previous = crate::instance::InstanceConfig { + name: "Migrating".to_owned(), + game_version: "1.20.1".to_owned(), + loader: crate::instance::ModLoader::Vanilla, + loader_version: None, + created: chrono::Utc::now(), + last_played: None, + java_path: None, + memory_max: None, + memory_min: None, + jvm_args: Vec::new(), + resolution: None, + config_sync_profile: None, + modpack_source: None, + }; + manager.save(&previous).unwrap(); + + let metadata = crate::storage::MetadataPaths::new(&meta_dir); + let version_dir = metadata.versions().join("1.21.2"); + std::fs::create_dir_all(&version_dir).unwrap(); + std::fs::write( + version_dir.join("meta.json"), + serde_json::to_vec(&serde_json::json!({ + "id": "1.21.2", + "mainClass": "net.minecraft.client.main.Main", + "assetIndex": { + "id": "1.21.2", + "url": format!("{}/assets.json", server.uri()), + "sha1": "unused" + }, + "downloads": { + "client": { + "url": format!("{}/client.jar", server.uri()), + "sha1": sha1(client_jar), + "size": client_jar.len() + } + }, + "libraries": [{ + "name": "example:test:1", + "downloads": { + "artifact": { + "url": format!("{}/library.jar", server.uri()), + "path": "example/test/1/test-1.jar", + "sha1": sha1(library_jar), + "size": library_jar.len() + } + } + }], + "javaVersion": { "majorVersion": 21 } + })) + .unwrap(), + ) + .unwrap(); + + let mut updated = previous.clone(); + updated.game_version = "1.21.2".to_owned(); + updated.memory_max = Some("4G".to_owned()); + let applied = apply_instance_settings_update(&manager, &previous, updated) + .await + .unwrap(); + + assert_eq!(applied.game_version, "1.21.2"); + previous = manager.load_one("Migrating").unwrap(); + assert_eq!(previous.game_version, "1.21.2"); + assert_eq!(previous.memory_max.as_deref(), Some("4G")); + assert_eq!( + std::fs::read(version_dir.join("1.21.2.jar")).unwrap(), + client_jar + ); + assert_eq!( + std::fs::read(metadata.libraries().join("example/test/1/test-1.jar")).unwrap(), + library_jar + ); + assert!(metadata.assets().join("indexes/1.21.2.json").exists()); + crate::feedback::progress::clear(); + }); +} + +#[test] +fn failed_structural_settings_update_keeps_previous_config() { + let _guard = crate::tests::TEST_LOCK + .lock() + .unwrap_or_else(|error| error.into_inner()); + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + runtime.block_on(async { + let temp = tempfile::tempdir().unwrap(); + let instances_dir = temp.path().join("instances"); + let meta_dir = temp.path().join("meta"); + std::fs::create_dir_all(instances_dir.join("Stable")).unwrap(); + let manager = InstanceManager::new(&instances_dir, &meta_dir); + let previous = crate::instance::InstanceConfig { + name: "Stable".to_owned(), + game_version: "1.20.1".to_owned(), + loader: crate::instance::ModLoader::Vanilla, + loader_version: None, + created: chrono::Utc::now(), + last_played: None, + java_path: None, + memory_max: None, + memory_min: None, + jvm_args: Vec::new(), + resolution: None, + config_sync_profile: None, + modpack_source: None, + }; + manager.save(&previous).unwrap(); + + let metadata = crate::storage::MetadataPaths::new(&meta_dir); + let version_dir = metadata.versions().join("missing-runtime"); + std::fs::create_dir_all(&version_dir).unwrap(); + std::fs::write(version_dir.join("meta.json"), b"not json").unwrap(); + let mut updated = previous.clone(); + updated.game_version = "missing-runtime".to_owned(); + + assert!( + apply_instance_settings_update(&manager, &previous, updated) + .await + .is_err() + ); + assert_eq!(manager.load_one("Stable").unwrap().game_version, "1.20.1"); + crate::feedback::progress::clear(); + }); +} + #[test] fn editor_kind_is_detected_from_the_executable_name() { assert!(editor_runs_in_terminal("/usr/bin/nvim")); diff --git a/src/tui/tests/flows.rs b/src/tui/tests/flows.rs index d9d82d4..524a7ef 100644 --- a/src/tui/tests/flows.rs +++ b/src/tui/tests/flows.rs @@ -54,9 +54,6 @@ fn escape_returns_through_nested_sections() { assert_eq!(ui.app.focused, FocusedArea::Instances); ui.app.focused = FocusedArea::Settings; - ui.key(KeyCode::Char('a')); - ui.key(KeyCode::Esc); - assert_eq!(ui.app.focused, FocusedArea::Settings); ui.key(KeyCode::Esc); assert_eq!(ui.app.focused, FocusedArea::Instances); @@ -574,19 +571,37 @@ fn confirmed_account_delete_updates_the_account_panel() { } #[test] -fn settings_profile_can_be_created_from_key_events() { +fn settings_popups_open_from_global_key_events() { let mut ui = UiHarness::new(); + ui.add_instance("settings-test"); ui.app.focused = FocusedArea::Settings; - ui.key(KeyCode::Char('a')); - for character in "qConfig".chars() { - ui.key(KeyCode::Char(character)); - } + ui.key(KeyCode::Char('E')); + assert_eq!(ui.app.focused, FocusedArea::InstanceSettings); + ui.draw(); + assert!(ui.screen().contains("Instance settings: settings-test")); + assert!(ui.screen().contains("Game version")); + assert!(ui.screen().contains("Desktop shortcut")); + ui.key(KeyCode::Down); ui.key(KeyCode::Enter); - - assert!(!ui.app.exit); + ui.draw(); + assert!(ui.screen().contains("Select loader")); + assert!(ui.screen().contains("Fabric")); + ui.key(KeyCode::Esc); + ui.key(KeyCode::Esc); + assert_eq!(ui.app.focused, FocusedArea::Settings); + + ui.key(KeyCode::Char('G')); + assert_eq!(ui.app.focused, FocusedArea::GlobalSettings); + ui.draw(); + assert!(ui.screen().contains("Launcher settings")); + assert!(ui.screen().contains("Default memory max")); + ui.key(KeyCode::Enter); + ui.draw(); + assert!(ui.screen().contains("Select theme")); + ui.key(KeyCode::Esc); + ui.key(KeyCode::Esc); assert_eq!(ui.app.focused, FocusedArea::Settings); - assert_eq!(ui.app.settings_state.profiles, ["qConfig"]); } #[test] diff --git a/src/tui/tests/harness.rs b/src/tui/tests/harness.rs index 227914c..587dfad 100644 --- a/src/tui/tests/harness.rs +++ b/src/tui/tests/harness.rs @@ -82,7 +82,8 @@ impl UiHarness { }, logs_state: widgets::logs_viewer::LogsState::default(), account_state, - settings_state: widgets::settings::SettingsState::new(meta_dir), + instance_settings: None, + global_settings: None, picker, instance_manager, log_overlay_scroll: 0, diff --git a/src/tui/tests/snapshots/rmcl__tui__tests__snapshots__empty_app_renders_the_complete_frame.snap b/src/tui/tests/snapshots/rmcl__tui__tests__snapshots__empty_app_renders_the_complete_frame.snap index cc90885..c30f562 100644 --- a/src/tui/tests/snapshots/rmcl__tui__tests__snapshots__empty_app_renders_the_complete_frame.snap +++ b/src/tui/tests/snapshots/rmcl__tui__tests__snapshots__empty_app_renders_the_complete_frame.snap @@ -28,7 +28,7 @@ expression: ui.screen() "│ ││ │" "│ │╰[l] launch [⏎] content [Shift+⏎] open dir [Esc] kill [a] add [m] modpacks╯" "│ │╭Accounts─────────╮╭Settings───────────────────────────╮╭Overview──────────────╮" -"│ ││No accounts. ││▸ instance default ││Ready │" +"│ ││No accounts. ││No instance selected. ││Ready │" "│ ││ ││ ││ │" "│ ││ ││ ││ │" "╰──────────────────╯╰─────────────────╯╰───────────────────────────────────╯╰──────────────────────╯" diff --git a/src/tui/tests/snapshots/rmcl__tui__tests__snapshots__instance_delete_confirmation_renders_the_complete_frame.snap b/src/tui/tests/snapshots/rmcl__tui__tests__snapshots__instance_delete_confirmation_renders_the_complete_frame.snap index bf31793..454390f 100644 --- a/src/tui/tests/snapshots/rmcl__tui__tests__snapshots__instance_delete_confirmation_renders_the_complete_frame.snap +++ b/src/tui/tests/snapshots/rmcl__tui__tests__snapshots__instance_delete_confirmation_renders_the_complete_frame.snap @@ -28,7 +28,7 @@ expression: ui.screen() "│ ││ │" "│ │╰──────────────────────────────────────────────────────────────────────────────╯" "│ │╭Accounts─────────╮╭Settings───────────────────────────╮╭Overview──────────────╮" -"│ ││No accounts. ││▸ instance default ││Ready │" -"│ ││ ││ ││ │" -"│ ││ ││ ││ │" +"│ ││No accounts. ││Version 1.21.1 / Fabric ││Ready │" +"│ ││ ││Runtime 512M-2G, auto java ││ │" +"│ ││ ││Profile instance default / desk no││ │" "╰──────────────────╯╰─────────────────╯╰───────────────────────────────────╯╰──────────────────────╯" diff --git a/src/tui/tests/snapshots/rmcl__tui__tests__snapshots__provider_conflict_renders_the_complete_frame.snap b/src/tui/tests/snapshots/rmcl__tui__tests__snapshots__provider_conflict_renders_the_complete_frame.snap index 02a964c..313e4de 100644 --- a/src/tui/tests/snapshots/rmcl__tui__tests__snapshots__provider_conflict_renders_the_complete_frame.snap +++ b/src/tui/tests/snapshots/rmcl__tui__tests__snapshots__provider_conflict_renders_the_complete_frame.snap @@ -28,7 +28,7 @@ expression: ui.screen() "│ ││ │" "│ │╰[l] launch [⏎] content [Shift+⏎] open dir [Esc] kill [a] add [m] modpacks╯" "│ │╭Accounts─────────╮╭Settings───────────────────────────╮╭Overview──────────────╮" -"│ ││No accounts. ││▸ instance default ││Ready │" +"│ ││No accounts. ││No instance selected. ││Ready │" "│ ││ ││ ││ │" "│ ││ ││ ││ │" "╰──────────────────╯╰─────────────────╯╰───────────────────────────────────╯╰──────────────────────╯" diff --git a/src/tui/tests/widgets/popups/error/area.rs b/src/tui/tests/widgets/popups/error/area.rs index dd40919..494b31c 100644 --- a/src/tui/tests/widgets/popups/error/area.rs +++ b/src/tui/tests/widgets/popups/error/area.rs @@ -11,7 +11,7 @@ fn frame() -> Rect { #[test] fn returns_none_after_dismiss_timeout() { - let past_dismiss = SETTINGS.ui.error_auto_dismiss_ms as u128 + 1; + let past_dismiss = SETTINGS.read().ui.error_auto_dismiss_ms as u128 + 1; assert!(popup_area(frame(), "msg", 0, past_dismiss).is_none()); } diff --git a/src/tui/tests/widgets/settings.rs b/src/tui/tests/widgets/settings.rs deleted file mode 100644 index 4bac7f5..0000000 --- a/src/tui/tests/widgets/settings.rs +++ /dev/null @@ -1,19 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Constantin Bauer -// SPDX-License-Identifier: GPL-3.0-only - -use super::*; - -#[test] -fn removing_selected_last_profile_clamps_selection() { - let tmp = tempfile::tempdir().unwrap(); - let mut state = SettingsState::new(tmp.path().to_path_buf()); - state.profiles = vec!["first".to_string(), "second".to_string()]; - state.active_profile = Some("second".to_string()); - state.list_state.selected = Some(2); - - state.remove_profile("second"); - - assert_eq!(state.profiles, vec!["first"]); - assert_eq!(state.active_profile, None); - assert_eq!(state.list_state.selected, Some(1)); -} diff --git a/src/tui/widgets/content/discovery.rs b/src/tui/widgets/content/discovery.rs index 86f7fd4..e34c9c2 100644 --- a/src/tui/widgets/content/discovery.rs +++ b/src/tui/widgets/content/discovery.rs @@ -138,6 +138,7 @@ pub(crate) fn spawn_provider_search( search_provider( registry.get("modrinth"), crate::config::SETTINGS + .read() .content .discovery_provider_enabled("modrinth"), &target, @@ -148,6 +149,7 @@ pub(crate) fn spawn_provider_search( search_provider( registry.get("curseforge"), crate::config::SETTINGS + .read() .content .discovery_provider_enabled("curseforge"), &target, @@ -177,7 +179,7 @@ pub(crate) fn spawn_provider_search( } let mut merged = merge_provider_results( pages, - crate::config::SETTINGS.content.preferred_provider(), + crate::config::SETTINGS.read().content.preferred_provider(), known_projects, ); refresh_source_installed_versions(&mut merged.sources, &target); @@ -795,7 +797,11 @@ impl DiscoveryState { installed_path: Option, target_world: Option<(String, PathBuf)>, ) -> Option { - let preferred = crate::config::SETTINGS.content.preferred_provider(); + let preferred = crate::config::SETTINGS + .read() + .content + .preferred_provider() + .to_owned(); sources.sort_by_key(|source| source.provider != preferred); let source = sources.first()?.clone(); self.next_action_request_id = self.next_action_request_id.wrapping_add(1); diff --git a/src/tui/widgets/content/list.rs b/src/tui/widgets/content/list.rs index c9b6e70..7659277 100644 --- a/src/tui/widgets/content/list.rs +++ b/src/tui/widgets/content/list.rs @@ -542,7 +542,7 @@ impl ContentListState { let use_image_protocol = picker.protocol_type() != ratatui_image::picker::ProtocolType::Halfblocks; - let use_quadrants = crate::config::SETTINGS.ui.image_protocol + let use_quadrants = crate::config::SETTINGS.read().ui.image_protocol == crate::config::settings::ImageProtocol::Quadrants; if !use_image_protocol { self.image_protocols.clear(); diff --git a/src/tui/widgets/content/tabs.rs b/src/tui/widgets/content/tabs.rs index 87ba426..8082434 100644 --- a/src/tui/widgets/content/tabs.rs +++ b/src/tui/widgets/content/tabs.rs @@ -504,7 +504,10 @@ pub fn render( } let loading_text = format!( "Searching {}...", - crate::config::SETTINGS.content.discovery_provider_label() + crate::config::SETTINGS + .read() + .content + .discovery_provider_label() ); render_discovery( frame, @@ -671,7 +674,10 @@ fn render_downloadable( if mode == ContentMode::Discover { let loading_text = format!( "Searching {}...", - crate::config::SETTINGS.content.discovery_provider_label() + crate::config::SETTINGS + .read() + .content + .discovery_provider_label() ); render_discovery( frame, diff --git a/src/tui/widgets/logs_viewer.rs b/src/tui/widgets/logs_viewer.rs index ab64426..229b8a1 100644 --- a/src/tui/widgets/logs_viewer.rs +++ b/src/tui/widgets/logs_viewer.rs @@ -509,33 +509,34 @@ fn render_list(frame: &mut Frame, area: Rect, state: &mut LogsState, is_focused: }) .collect(); let search = &state.search; + let success = theme.success(); + let accent = theme.accent(); + let text = theme.text(); + let background = theme.background(); + let stripe = theme.stripe(); let builder = ListBuilder::new(move |context| { let (name, is_live) = &entries_snapshot[context.index]; let show_selected = list_focused && context.is_selected; let style = if *is_live && show_selected { - Style::default() - .fg(theme.success()) - .add_modifier(Modifier::BOLD) + Style::default().fg(success).add_modifier(Modifier::BOLD) } else if *is_live { - Style::default().fg(theme.success()) + Style::default().fg(success) } else if show_selected { - Style::default() - .fg(theme.accent()) - .add_modifier(Modifier::BOLD) + Style::default().fg(accent).add_modifier(Modifier::BOLD) } else { - Style::default().fg(theme.text()) + Style::default().fg(text) }; let bg = if context.index % 2 == 0 { - theme.background() + background } else { - theme.stripe() + stripe }; let selector = if show_selected { - Span::styled("\u{258c} ", Style::default().fg(theme.accent())) + Span::styled("\u{258c} ", Style::default().fg(accent)) } else { Span::raw(" ") }; diff --git a/src/tui/widgets/markdown.rs b/src/tui/widgets/markdown.rs index 47f043a..001c08a 100644 --- a/src/tui/widgets/markdown.rs +++ b/src/tui/widgets/markdown.rs @@ -1651,7 +1651,7 @@ fn render_image( width: area.width, height: full_height, protocol: picker.protocol_type(), - mode: crate::config::SETTINGS.ui.image_protocol, + mode: crate::config::SETTINGS.read().ui.image_protocol, }; if image .prepared diff --git a/src/tui/widgets/popups/error.rs b/src/tui/widgets/popups/error.rs index 33e0283..b6e1a32 100644 --- a/src/tui/widgets/popups/error.rs +++ b/src/tui/widgets/popups/error.rs @@ -74,7 +74,7 @@ pub fn popup_area(frame_area: Rect, message: &str, base_y: u16, elapsed_ms: u128 const MAX_W: usize = 58; const MIN_W: usize = 22; - if elapsed_ms >= SETTINGS.ui.error_auto_dismiss_ms as u128 { + if elapsed_ms >= SETTINGS.read().ui.error_auto_dismiss_ms as u128 { return None; } diff --git a/src/tui/widgets/popups/global_settings.rs b/src/tui/widgets/popups/global_settings.rs new file mode 100644 index 0000000..0566196 --- /dev/null +++ b/src/tui/widgets/popups/global_settings.rs @@ -0,0 +1,435 @@ +// SPDX-FileCopyrightText: 2026 Constantin Bauer +// SPDX-License-Identifier: GPL-3.0-only + +// modal editor for launcher-wide settings. + +use crossterm::event::{KeyCode, KeyEvent}; +use ratatui::{ + Frame, + layout::Rect, + style::{Modifier, Style}, + text::{Line, Span}, + widgets::{Block, Borders, Clear, Paragraph}, +}; +use ratatui_textarea::{CursorMove, TextArea}; + +use crate::{ + config::{ + Config, + theme::{BORDER_STYLE, BorderStyle, THEME, ThemeConfig}, + }, + instance::models::normalize_memory_value, +}; + +pub struct State { + pub config: Config, + pub theme: ThemeConfig, + selected: usize, + editing: Option>, + error: Option, + config_dirty: bool, + confirm_close: bool, + themes: Vec, + theme_picker: bool, + theme_index: usize, +} + +pub enum Action { + None, + Save(Box, String, BorderStyle), + OpenRaw(std::path::PathBuf), + Close, +} + +impl State { + pub fn new() -> Self { + let theme = crate::config::theme::current_theme_config(); + let themes = available_themes(); + let theme_index = themes + .iter() + .position(|candidate| candidate == &theme.theme) + .unwrap_or(0); + Self { + config: crate::config::SETTINGS.read().clone(), + theme, + selected: 0, + editing: None, + error: None, + config_dirty: false, + confirm_close: false, + themes, + theme_picker: false, + theme_index, + } + } + + fn value(&self, field: usize) -> String { + 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(), + _ => String::new(), + } + } + + fn display_value(&self, field: usize) -> String { + if field == 4 && self.config.paths.java_path.is_none() { + "auto-detect".to_owned() + } else { + self.value(field) + } + } + + fn commit_edit(&mut self) { + let Some(editor) = self.editing.take() else { + return; + }; + let raw = editor.lines().join(""); + let value = raw.trim(); + self.error = None; + let invalid = |state: &mut Self, message: String| { + state.error = Some(message); + state.editing = Some(new_text_area(editor.lines().to_vec())); + }; + match self.selected { + 2 | 3 if normalize_memory_value(value).is_none() => invalid( + self, + "memory must be a positive number with K, M, or G".to_owned(), + ), + 2 => { + self.config.defaults.memory_min = normalize_memory_value(value).unwrap(); + self.config_dirty = true; + } + 3 => { + self.config.defaults.memory_max = normalize_memory_value(value).unwrap(); + self.config_dirty = true; + } + 4 => { + self.config.paths.java_path = (!value.is_empty()).then(|| value.to_owned()); + self.config_dirty = true; + } + _ => {} + } + } + + fn select_theme(&mut self) { + let previous = self.theme.theme.clone(); + self.theme.theme = self.themes[self.theme_index].clone(); + self.error = None; + if let Err(error) = crate::config::theme::apply_theme( + self.theme.theme.clone(), + self.theme.border_style.clone(), + ) { + self.error = Some(error.to_string()); + self.theme.theme = previous; + } + } + + fn handle_theme_picker_key(&mut self, key: &KeyEvent) { + match key.code { + KeyCode::Esc => self.theme_picker = false, + KeyCode::Char('j') | KeyCode::Down => { + self.theme_index = (self.theme_index + 1).min(self.themes.len() - 1); + } + KeyCode::Char('k') | KeyCode::Up => { + self.theme_index = self.theme_index.saturating_sub(1); + } + KeyCode::Enter => { + self.select_theme(); + if self.error.is_none() { + self.theme_picker = false; + } + } + _ => {} + } + } + + fn cycle_border(&mut self) { + let previous = self.theme.border_style.clone(); + self.theme.border_style = match self.theme.border_style { + BorderStyle::Rounded => BorderStyle::Plain, + BorderStyle::Plain => BorderStyle::Double, + BorderStyle::Double => BorderStyle::Thick, + BorderStyle::Thick => BorderStyle::Rounded, + }; + self.error = None; + if let Err(error) = crate::config::theme::apply_theme( + self.theme.theme.clone(), + self.theme.border_style.clone(), + ) { + self.error = Some(error.to_string()); + self.theme.border_style = previous; + } + } + + fn validate_before_save(&mut self) -> bool { + self.error = None; + let min = memory_kib(&self.config.defaults.memory_min); + let max = memory_kib(&self.config.defaults.memory_max); + if min.zip(max).is_some_and(|(min, max)| min > max) { + self.error = Some("minimum memory cannot exceed maximum memory".to_owned()); + } + self.error.is_none() + } + + pub fn handle_key(&mut self, key: &KeyEvent) -> Action { + if self.theme_picker { + self.handle_theme_picker_key(key); + return Action::None; + } + if self.confirm_close { + match key.code { + KeyCode::Char('y') | KeyCode::Enter => return Action::Close, + KeyCode::Char('n') | KeyCode::Esc => self.confirm_close = false, + _ => {} + } + return Action::None; + } + if let Some(input) = &mut self.editing { + match key.code { + KeyCode::Enter => self.commit_edit(), + KeyCode::Esc => self.editing = None, + _ => { + input.input(*key); + } + } + return Action::None; + } + match key.code { + KeyCode::Char('j') | KeyCode::Down => self.selected = (self.selected + 1).min(4), + KeyCode::Char('k') | KeyCode::Up => self.selected = self.selected.saturating_sub(1), + KeyCode::Enter => match self.selected { + 0 => self.theme_picker = true, + 1 => self.cycle_border(), + field => self.editing = Some(new_text_area(vec![self.value(field)])), + }, + KeyCode::Char('s') => { + if self.validate_before_save() { + return Action::Save( + Box::new(self.config.clone()), + self.theme.theme.clone(), + self.theme.border_style.clone(), + ); + } + } + KeyCode::Char('E') if self.config_dirty => { + self.error = Some( + "save or discard launcher defaults before opening the raw file".to_owned(), + ); + } + KeyCode::Char('E') => { + let file = if self.selected <= 1 { + "theme.toml" + } else { + "config.toml" + }; + return Action::OpenRaw(crate::config::get_config_path().join(file)); + } + KeyCode::Esc if self.config_dirty => self.confirm_close = true, + KeyCode::Esc => return Action::Close, + _ => {} + } + Action::None + } +} + +impl Default for State { + fn default() -> Self { + Self::new() + } +} + +fn memory_kib(value: &str) -> Option { + let normalized = normalize_memory_value(value)?; + let (number, suffix) = normalized.split_at(normalized.len().saturating_sub(1)); + let number = number.parse::().ok()?; + match suffix { + "K" => Some(number), + "M" => number.checked_mul(1024), + "G" => number.checked_mul(1024 * 1024), + _ => None, + } +} + +fn available_themes() -> Vec { + let mut themes: Vec = ratatui_themekit::available_theme_ids() + .into_iter() + .map(str::to_owned) + .collect(); + let theme_dir = crate::config::get_config_path().join("theme"); + if let Ok(entries) = std::fs::read_dir(theme_dir) { + themes.extend(entries.flatten().filter_map(|entry| { + let path = entry.path(); + (path.extension().and_then(|ext| ext.to_str()) == Some("toml")) + .then(|| path.file_stem()?.to_str().map(str::to_owned)) + .flatten() + })); + } + themes.sort(); + themes.dedup(); + let current = crate::config::theme::current_theme_config().theme; + if !themes.contains(¤t) { + themes.push(current); + themes.sort(); + } + themes +} + +fn new_text_area(lines: Vec) -> TextArea<'static> { + let theme = THEME.as_ref(); + let mut editor = TextArea::new(if lines.is_empty() { + vec![String::new()] + } else { + lines + }); + editor.set_style(Style::default().fg(theme.text()).bg(theme.surface())); + editor.set_cursor_line_style(Style::default()); + editor.set_cursor_style(Style::default().fg(theme.background()).bg(theme.accent())); + editor.move_cursor(CursorMove::Bottom); + editor.move_cursor(CursorMove::End); + editor +} + +pub fn render(frame: &mut Frame, area: Rect, state: &State) { + let theme = THEME.as_ref(); + frame.render_widget(Clear, area); + let keybinds = if state.theme_picker { + super::keybind_line(&[("j/k", " move"), ("Enter", " apply"), ("Esc", " back")]) + } else { + super::keybind_line(&[ + ("j/k", " field"), + ("Enter", " edit"), + ("s", " save"), + ("E", " raw"), + ("Esc", " back"), + ]) + }; + let block = Block::default() + .title(if state.config_dirty { + " Launcher settings * " + } else { + " Launcher settings " + }) + .borders(Borders::ALL) + .border_type(BORDER_STYLE.to_border_type()) + .border_style(Style::default().fg(theme.accent())) + .style(Style::default().bg(theme.background())) + .title_bottom(keybinds); + let inner = block.inner(area); + frame.render_widget(block, area); + if state.theme_picker { + let mut lines = vec![Line::from(Span::styled( + "Select theme", + Style::default() + .fg(theme.text()) + .add_modifier(Modifier::BOLD), + ))]; + let visible_rows = inner.height.saturating_sub(1) as usize; + let start = state + .theme_index + .saturating_sub(visible_rows.saturating_sub(1)); + for (index, name) in state + .themes + .iter() + .enumerate() + .skip(start) + .take(visible_rows) + { + let selected = index == state.theme_index; + lines.push(Line::from(vec![ + Span::styled( + if selected { "▸ " } else { " " }, + Style::default().fg(theme.accent()), + ), + Span::styled( + name.clone(), + Style::default() + .fg(if selected { + theme.accent() + } else { + theme.text() + }) + .add_modifier(if selected { + Modifier::BOLD + } else { + Modifier::empty() + }), + ), + ])); + } + frame.render_widget(Paragraph::new(lines), inner); + return; + } + let labels = [ + "Theme", + "Border style", + "Default memory min", + "Default memory max", + "Java path", + ]; + let mut lines = Vec::new(); + for (index, label) in labels.iter().enumerate() { + let selected = index == state.selected; + let displayed = if selected { + state.editing.as_ref().map_or_else( + || state.display_value(index), + |_| "editing below".to_owned(), + ) + } else { + state.display_value(index) + }; + lines.push(Line::from(vec![ + Span::styled( + if selected { "▸ " } else { " " }, + Style::default().fg(theme.accent()), + ), + Span::styled( + format!("{label:<20}"), + Style::default().fg(theme.text_dim()), + ), + Span::styled( + displayed, + Style::default() + .fg(if selected { + theme.accent() + } else { + theme.text() + }) + .add_modifier(if selected { + Modifier::BOLD + } else { + Modifier::empty() + }), + ), + ])); + } + if let Some(error) = &state.error { + lines.push(Line::from(Span::styled( + error, + Style::default().fg(theme.error()), + ))); + } else if state.confirm_close { + lines.push(Line::from(Span::styled( + "Discard unsaved launcher defaults? [y] yes [n] no", + Style::default().fg(theme.warning()), + ))); + } + frame.render_widget(Paragraph::new(lines), inner); + if let Some(editor) = state.editing.as_ref() { + let editor_area = Rect { + x: inner.x, + y: inner.y.saturating_add(7), + width: inner.width, + height: 3.min(inner.height.saturating_sub(7)).max(1), + }; + let editor_block = Block::default() + .title(" Value — Enter applies ") + .borders(Borders::ALL) + .border_style(Style::default().fg(theme.accent())); + let editor_inner = editor_block.inner(editor_area); + frame.render_widget(editor_block, editor_area); + frame.render_widget(editor, editor_inner); + } +} diff --git a/src/tui/widgets/popups/import_modpack/state.rs b/src/tui/widgets/popups/import_modpack/state.rs index 72b00c3..351250a 100644 --- a/src/tui/widgets/popups/import_modpack/state.rs +++ b/src/tui/widgets/popups/import_modpack/state.rs @@ -480,7 +480,7 @@ async fn resolve_version_id( ) { match modrinth::fetch_version(client, version_id).await { Ok(version) => { - let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir(); + let meta_dir = crate::config::SETTINGS.read().paths.resolve_meta_dir(); let tmp_dir = crate::storage::MetadataPaths::new(&meta_dir).temporary(); if let Err(e) = tokio::fs::create_dir_all(&tmp_dir).await { set_error_and_back( @@ -558,7 +558,7 @@ fn start_version_download(state: &mut ImportWizardState) { tokio::spawn(async move { let client = crate::net::HttpClient::new(); - let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir(); + let meta_dir = crate::config::SETTINGS.read().paths.resolve_meta_dir(); let tmp_dir = crate::storage::MetadataPaths::new(&meta_dir).temporary(); if let Err(e) = tokio::fs::create_dir_all(&tmp_dir).await { set_error_and_back( @@ -618,7 +618,7 @@ fn spawn_discovery_request_with_query( crate::tui::widgets::content::discovery::spawn_provider_search( query, crate::tui::widgets::content::discovery::DiscoveryTarget::Modpacks, - crate::config::SETTINGS.paths.resolve_meta_dir(), + crate::config::SETTINGS.read().paths.resolve_meta_dir(), request, ); } @@ -667,9 +667,10 @@ fn start_discovered_download(request: crate::tui::widgets::content::discovery::I tokio::spawn(async move { let client = crate::net::HttpClient::new(); let registry = crate::instance::content::provider::ProviderRegistry::configured(client); - let tmp_dir = - crate::storage::MetadataPaths::new(crate::config::SETTINGS.paths.resolve_meta_dir()) - .temporary(); + let tmp_dir = crate::storage::MetadataPaths::new( + crate::config::SETTINGS.read().paths.resolve_meta_dir(), + ) + .temporary(); let result: Result = async { let source = crate::instance::ProviderProject { provider: request.provider.clone(), diff --git a/src/tui/widgets/popups/instance_settings.rs b/src/tui/widgets/popups/instance_settings.rs new file mode 100644 index 0000000..d1205ee --- /dev/null +++ b/src/tui/widgets/popups/instance_settings.rs @@ -0,0 +1,1090 @@ +// SPDX-FileCopyrightText: 2026 Constantin Bauer +// SPDX-License-Identifier: GPL-3.0-only + +// modal editor for settings belonging to the selected Minecraft instance. + +use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; +use ratatui::{ + Frame, + layout::{Constraint, Direction, Layout, Rect}, + style::{Modifier, Style}, + text::{Line, Span}, + widgets::{Block, Borders, Clear, Paragraph}, +}; +use ratatui_textarea::{CursorMove, TextArea}; +use std::sync::{Arc, Mutex}; + +use crate::{ + config::{ + SETTINGS, + theme::{BORDER_STYLE, THEME}, + }, + instance::loader::GameVersion, + instance::models::{InstanceConfig, ModLoader, normalize_memory_value, parse_resolution}, + tui::widgets::popups::LoadState, +}; + +const FIELD_COUNT: usize = 10; +type SharedLoad = Arc>>; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum VersionPicker { + Game, + Loader, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum ChoicePicker { + Loader, + Profile, +} + +enum PickerLoad { + Idle, + Loading, + Loaded, + Error(String), +} + +#[derive(Debug, Clone)] +pub struct State { + original: InstanceConfig, + pub draft: InstanceConfig, + selected: usize, + editing: Option>, + profiles: Vec, + profile_input: Option>, + confirm_profile_delete: bool, + pub desktop: bool, + original_desktop: bool, + error: Option, + confirm_close: bool, + confirm_runtime_change: bool, + picker: Option, + picker_index: usize, + picker_initialized: bool, + picker_query: String, + picker_search: bool, + show_snapshots: bool, + game_versions: SharedLoad>, + loader_versions: SharedLoad>, + choice_picker: Option, + choice_index: usize, +} + +pub enum Action { + None, + Save(Box, bool), + DeleteProfile(String), + OpenRaw, + Close, +} + +impl State { + pub fn new(instance: &InstanceConfig, meta_dir: &std::path::Path) -> Self { + Self { + original: instance.clone(), + draft: instance.clone(), + selected: 0, + editing: None, + profiles: crate::instance::config_sync::list_profiles(meta_dir).unwrap_or_default(), + profile_input: None, + confirm_profile_delete: false, + desktop: crate::instance::desktop::exists(&instance.name), + original_desktop: crate::instance::desktop::exists(&instance.name), + error: None, + confirm_close: false, + confirm_runtime_change: false, + picker: None, + picker_index: 0, + picker_initialized: false, + picker_query: String::new(), + picker_search: false, + show_snapshots: false, + game_versions: Arc::new(Mutex::new(LoadState::Idle)), + loader_versions: Arc::new(Mutex::new(LoadState::Idle)), + choice_picker: None, + choice_index: 0, + } + } + + fn dirty(&self) -> bool { + self.draft != self.original || self.desktop != self.original_desktop + } + + fn runtime_changed(&self) -> bool { + self.draft.game_version != self.original.game_version + || self.draft.loader != self.original.loader + || self.draft.loader_version != self.original.loader_version + } + + fn validate_before_save(&mut self) -> bool { + self.error = None; + if self.draft.game_version.trim().is_empty() { + self.error = Some("game version cannot be empty".to_owned()); + } else if self.draft.loader != ModLoader::Vanilla + && self + .draft + .loader_version + .as_deref() + .is_none_or(str::is_empty) + { + self.error = Some("the selected loader requires a loader version".to_owned()); + } else if let (Some(min), Some(max)) = ( + self.draft.memory_min.as_deref().and_then(memory_kib), + self.draft.memory_max.as_deref().and_then(memory_kib), + ) && min > max + { + self.error = Some("minimum memory cannot exceed maximum memory".to_owned()); + } + self.error.is_none() + } + + fn value(&self, field: usize) -> String { + match field { + 0 => self.draft.game_version.clone(), + 1 => self.draft.loader.to_string(), + 2 => self.draft.loader_version.clone().unwrap_or_default(), + 3 => self.draft.java_path.clone().unwrap_or_default(), + 4 => self.draft.memory_min.clone().unwrap_or_default(), + 5 => self.draft.memory_max.clone().unwrap_or_default(), + 6 => self.draft.jvm_args.join("\n"), + 7 => self + .draft + .resolution + .map(|(w, h)| format!("{w}x{h}")) + .unwrap_or_default(), + 8 => self + .draft + .config_sync_profile + .clone() + .unwrap_or_else(|| "instance default".to_owned()), + 9 => if self.desktop { "yes" } else { "no" }.to_owned(), + _ => String::new(), + } + } + + fn display_value(&self, field: usize) -> String { + match field { + 2 if self.draft.loader == ModLoader::Vanilla => "not applicable".to_owned(), + 3 if self.draft.java_path.is_none() => "auto-detect".to_owned(), + 4 if self.draft.memory_min.is_none() => { + format!("default ({})", SETTINGS.read().defaults.memory_min) + } + 5 if self.draft.memory_max.is_none() => { + format!("default ({})", SETTINGS.read().defaults.memory_max) + } + 6 if self.draft.jvm_args.is_empty() => "none".to_owned(), + 7 if self.draft.resolution.is_none() => "default".to_owned(), + _ => self.value(field).replace('\n', " ↵ "), + } + } + + fn begin_edit(&mut self) { + match self.selected { + 0 => self.open_game_picker(), + 1 => self.open_choice_picker(ChoicePicker::Loader), + 2 if self.draft.loader == ModLoader::Vanilla => { + self.error = Some("Vanilla does not use a loader version".to_owned()); + } + 2 => self.open_loader_picker(), + 8 => self.open_choice_picker(ChoicePicker::Profile), + 9 => self.desktop = !self.desktop, + 6 => self.editing = Some(new_text_area(self.draft.jvm_args.clone())), + field => self.editing = Some(new_text_area(vec![self.value(field)])), + } + } + + fn open_choice_picker(&mut self, picker: ChoicePicker) { + self.choice_picker = Some(picker); + self.choice_index = match picker { + ChoicePicker::Loader => loaders() + .iter() + .position(|loader| *loader == self.draft.loader) + .unwrap_or(0), + ChoicePicker::Profile => self + .draft + .config_sync_profile + .as_deref() + .and_then(|selected| self.profiles.iter().position(|profile| profile == selected)) + .map_or(0, |index| index + 1), + }; + } + + fn choice_values(&self) -> Vec { + match self.choice_picker { + Some(ChoicePicker::Loader) => loaders().iter().map(ToString::to_string).collect(), + Some(ChoicePicker::Profile) => std::iter::once("instance default".to_owned()) + .chain(self.profiles.iter().cloned()) + .collect(), + None => Vec::new(), + } + } + + fn handle_choice_key(&mut self, key: &KeyEvent) { + let count = self.choice_values().len(); + match key.code { + KeyCode::Esc => self.choice_picker = None, + KeyCode::Char('j') | KeyCode::Down if count > 0 => { + self.choice_index = (self.choice_index + 1).min(count - 1); + } + KeyCode::Char('k') | KeyCode::Up => { + self.choice_index = self.choice_index.saturating_sub(1); + } + KeyCode::Enter => { + match self.choice_picker { + Some(ChoicePicker::Loader) => { + let available = loaders(); + let loader = available[self.choice_index.min(available.len() - 1)]; + if self.draft.loader != loader { + self.draft.loader = loader; + self.draft.loader_version = None; + self.loader_versions = Arc::new(Mutex::new(LoadState::Idle)); + self.game_versions = Arc::new(Mutex::new(LoadState::Idle)); + } + } + Some(ChoicePicker::Profile) => { + self.draft.config_sync_profile = self + .choice_index + .checked_sub(1) + .and_then(|index| self.profiles.get(index).cloned()); + } + None => {} + } + self.choice_picker = None; + } + _ => {} + } + } + + fn open_game_picker(&mut self) { + self.picker = Some(VersionPicker::Game); + self.picker_index = 0; + self.picker_initialized = false; + self.picker_query.clear(); + self.picker_search = false; + let mut load = self + .game_versions + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if matches!(*load, LoadState::Idle | LoadState::Error(_)) { + *load = LoadState::Loading; + let target = self.game_versions.clone(); + let loader = self.draft.loader; + tokio::spawn(async move { + let result = super::version_lists::game_versions(loader).await; + *target + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = match result { + Ok(versions) => LoadState::Loaded(versions), + Err(error) => LoadState::Error(error), + }; + crate::feedback::request_redraw(); + }); + } + } + + fn open_loader_picker(&mut self) { + self.picker = Some(VersionPicker::Loader); + self.picker_index = 0; + self.picker_initialized = false; + self.picker_query.clear(); + self.picker_search = false; + let mut load = self + .loader_versions + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if matches!(*load, LoadState::Idle | LoadState::Error(_)) { + *load = LoadState::Loading; + let target = self.loader_versions.clone(); + let loader = self.draft.loader; + let game_version = self.draft.game_version.clone(); + tokio::spawn(async move { + let result = super::version_lists::loader_versions(loader, &game_version).await; + *target + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = match result { + Ok(versions) => LoadState::Loaded(versions), + Err(error) => LoadState::Error(error), + }; + crate::feedback::request_redraw(); + }); + } + } + + fn visible_game_versions(&self) -> Vec { + let query = self.picker_query.to_lowercase(); + match &*self + .game_versions + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + { + LoadState::Loaded(versions) => versions + .iter() + .filter(|version| self.show_snapshots || version.stable) + .filter(|version| query.is_empty() || version.id.to_lowercase().contains(&query)) + .cloned() + .collect(), + _ => Vec::new(), + } + } + + fn visible_loader_versions(&self) -> Vec { + let query = self.picker_query.to_lowercase(); + match &*self + .loader_versions + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + { + LoadState::Loaded(versions) => versions + .iter() + .filter(|version| query.is_empty() || version.to_lowercase().contains(&query)) + .cloned() + .collect(), + _ => Vec::new(), + } + } + + fn initialize_picker_index(&mut self) { + if self.picker_initialized { + return; + } + let index = match self.picker { + Some(VersionPicker::Game) => self + .visible_game_versions() + .iter() + .position(|version| version.id == self.draft.game_version), + Some(VersionPicker::Loader) => { + self.draft.loader_version.as_deref().and_then(|selected| { + self.visible_loader_versions() + .iter() + .position(|version| version == selected) + }) + } + None => None, + }; + if let Some(index) = index { + self.picker_index = index; + self.picker_initialized = true; + } + } + + fn handle_picker_key(&mut self, key: &KeyEvent) { + self.initialize_picker_index(); + if self.picker_search { + match key.code { + KeyCode::Esc => { + self.picker_search = false; + return; + } + KeyCode::Backspace => { + self.picker_query.pop(); + self.picker_index = 0; + return; + } + KeyCode::Char('j') | KeyCode::Down | KeyCode::Char('k') | KeyCode::Up => {} + KeyCode::Char(character) => { + self.picker_query.push(character); + self.picker_index = 0; + return; + } + _ => {} + } + } + let count = match self.picker { + Some(VersionPicker::Game) => self.visible_game_versions().len(), + Some(VersionPicker::Loader) => self.visible_loader_versions().len(), + None => 0, + }; + match key.code { + KeyCode::Esc => self.picker = None, + KeyCode::Char('/') => self.picker_search = true, + KeyCode::Char('s') if self.picker == Some(VersionPicker::Game) => { + self.show_snapshots = !self.show_snapshots; + self.picker_index = 0; + self.picker_initialized = false; + } + KeyCode::Char('j') | KeyCode::Down if count > 0 => { + self.picker_index = (self.picker_index + 1).min(count - 1); + } + KeyCode::Char('k') | KeyCode::Up => { + self.picker_index = self.picker_index.saturating_sub(1); + } + KeyCode::Enter => match self.picker { + Some(VersionPicker::Game) => { + if let Some(version) = self.visible_game_versions().get(self.picker_index) { + if self.draft.game_version != version.id { + self.draft.game_version = version.id.clone(); + self.draft.loader_version = None; + self.loader_versions = Arc::new(Mutex::new(LoadState::Idle)); + } + self.picker = None; + } + } + Some(VersionPicker::Loader) => { + if let Some(version) = self.visible_loader_versions().get(self.picker_index) { + self.draft.loader_version = Some(version.clone()); + self.picker = None; + } + } + None => {} + }, + _ => {} + } + } + + fn commit_edit(&mut self) { + let Some(editor) = self.editing.take() else { + return; + }; + let raw = editor.lines().join("\n"); + let value = raw.trim(); + self.error = None; + let invalid = |state: &mut Self, message: String| { + state.error = Some(message); + state.editing = Some(new_text_area(editor.lines().to_vec())); + }; + match self.selected { + 0 if value.is_empty() => invalid(self, "game version cannot be empty".to_owned()), + 0 => self.draft.game_version = value.to_owned(), + 2 => self.draft.loader_version = (!value.is_empty()).then(|| value.to_owned()), + 3 => self.draft.java_path = (!value.is_empty()).then(|| value.to_owned()), + 4 | 5 if !value.is_empty() && normalize_memory_value(value).is_none() => invalid( + self, + "memory must be a positive number with K, M, or G".to_owned(), + ), + 4 => self.draft.memory_min = normalize_memory_value(value), + 5 => self.draft.memory_max = normalize_memory_value(value), + 6 => { + self.draft.jvm_args = value + .lines() + .map(str::trim) + .filter(|argument| !argument.is_empty()) + .map(str::to_owned) + .collect(); + } + 7 if value.is_empty() => self.draft.resolution = None, + 7 => match parse_resolution(value) { + Ok(resolution) => self.draft.resolution = Some(resolution), + Err(error) => invalid(self, error), + }, + _ => {} + } + } + + pub fn handle_key(&mut self, key: &KeyEvent) -> Action { + if self.choice_picker.is_some() { + self.handle_choice_key(key); + return Action::None; + } + if self.picker.is_some() { + self.handle_picker_key(key); + return Action::None; + } + if let Some(input) = &mut self.profile_input { + match key.code { + KeyCode::Enter => { + let name = input.lines().join("").trim().to_owned(); + self.profile_input = None; + if !name.is_empty() { + match crate::instance::config_sync::validate_profile(&name) { + Ok(()) => { + if !self.profiles.contains(&name) { + self.profiles.push(name.clone()); + self.profiles.sort_unstable(); + } + self.draft.config_sync_profile = Some(name); + } + Err(error) => self.error = Some(error.to_string()), + } + } + } + KeyCode::Esc => self.profile_input = None, + _ => { + input.input(*key); + } + } + return Action::None; + } + if self.confirm_profile_delete { + match key.code { + KeyCode::Char('y') | KeyCode::Enter => { + self.confirm_profile_delete = false; + if let Some(profile) = self.draft.config_sync_profile.clone() + && (self.original.config_sync_profile.as_deref() == Some(&profile) + || self.profiles.iter().any(|candidate| candidate == &profile)) + { + return Action::DeleteProfile(profile); + } + } + KeyCode::Char('n') | KeyCode::Esc => self.confirm_profile_delete = false, + _ => {} + } + return Action::None; + } + if self.confirm_close { + match key.code { + KeyCode::Char('y') | KeyCode::Enter => return Action::Close, + KeyCode::Char('n') | KeyCode::Esc => self.confirm_close = false, + _ => {} + } + return Action::None; + } + if self.confirm_runtime_change { + match key.code { + KeyCode::Char('y') | KeyCode::Enter => { + if self.validate_before_save() { + return Action::Save(Box::new(self.draft.clone()), self.desktop); + } + self.confirm_runtime_change = false; + } + KeyCode::Char('n') | KeyCode::Esc => self.confirm_runtime_change = false, + _ => {} + } + return Action::None; + } + if let Some(input) = &mut self.editing { + match key.code { + KeyCode::Enter + if self.selected == 6 && !key.modifiers.contains(KeyModifiers::CONTROL) => + { + input.input(*key); + } + KeyCode::Enter => self.commit_edit(), + KeyCode::Esc => self.editing = None, + _ => { + input.input(*key); + } + } + return Action::None; + } + + match key.code { + 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::Enter => self.begin_edit(), + KeyCode::Char('a') if self.selected == 8 => { + self.profile_input = Some(new_text_area(vec![String::new()])); + } + KeyCode::Char('d') + if self.selected == 8 && self.draft.config_sync_profile.is_some() => + { + self.confirm_profile_delete = true; + } + KeyCode::Char('s') if self.dirty() => { + if self.validate_before_save() { + if self.runtime_changed() { + self.confirm_runtime_change = true; + } else { + return Action::Save(Box::new(self.draft.clone()), self.desktop); + } + } + } + KeyCode::Char('E') if self.dirty() => { + self.error = + Some("save or discard draft changes before opening the raw file".to_owned()); + } + KeyCode::Char('E') => return Action::OpenRaw, + KeyCode::Esc if self.dirty() => self.confirm_close = true, + KeyCode::Esc => return Action::Close, + _ => {} + } + Action::None + } + + pub fn profile_deleted(&mut self, profile: &str) { + self.profiles.retain(|candidate| candidate != profile); + if self.draft.config_sync_profile.as_deref() == Some(profile) { + self.draft.config_sync_profile = None; + } + if self.original.config_sync_profile.as_deref() == Some(profile) { + self.original.config_sync_profile = None; + } + } +} + +fn memory_kib(value: &str) -> Option { + let normalized = normalize_memory_value(value)?; + let (number, suffix) = normalized.split_at(normalized.len().saturating_sub(1)); + let number = number.parse::().ok()?; + match suffix { + "K" => Some(number), + "M" => number.checked_mul(1024), + "G" => number.checked_mul(1024 * 1024), + _ => None, + } +} + +fn loaders() -> [ModLoader; 5] { + [ + ModLoader::Vanilla, + ModLoader::Fabric, + ModLoader::Forge, + ModLoader::NeoForge, + ModLoader::Quilt, + ] +} + +fn new_text_area(lines: Vec) -> TextArea<'static> { + let theme = THEME.as_ref(); + let mut editor = TextArea::new(if lines.is_empty() { + vec![String::new()] + } else { + lines + }); + editor.set_style(Style::default().fg(theme.text()).bg(theme.surface())); + editor.set_cursor_line_style(Style::default()); + editor.set_cursor_style(Style::default().fg(theme.background()).bg(theme.accent())); + editor.move_cursor(CursorMove::Bottom); + editor.move_cursor(CursorMove::End); + editor +} + +pub fn popup_rect(area: Rect) -> Rect { + let vertical = Layout::default() + .direction(Direction::Vertical) + .constraints([ + Constraint::Percentage(8), + Constraint::Percentage(84), + Constraint::Percentage(8), + ]) + .split(area); + Layout::default() + .direction(Direction::Horizontal) + .constraints([ + Constraint::Percentage(12), + Constraint::Percentage(76), + Constraint::Percentage(12), + ]) + .split(vertical[1])[1] +} + +pub fn render(frame: &mut Frame, area: Rect, state: &State) { + let theme = THEME.as_ref(); + frame.render_widget(Clear, area); + let title = format!( + " Instance settings: {} {}", + state.draft.name, + if state.dirty() { "*" } else { "" } + ); + let keybinds = if state.picker.is_some() { + super::keybind_line(&[ + ("j/k", " move"), + ("Enter", " select"), + ("/", " search"), + ("s", " snapshots"), + ("Esc", " back"), + ]) + } else if state.choice_picker.is_some() { + super::keybind_line(&[("j/k", " move"), ("Enter", " select"), ("Esc", " back")]) + } else { + super::keybind_line(&[ + ("j/k", " field"), + ("Enter", " edit"), + ("s", " save"), + ("E", " raw"), + ("Esc", " back"), + ]) + }; + let block = Block::default() + .title(title) + .borders(Borders::ALL) + .border_type(BORDER_STYLE.to_border_type()) + .border_style(Style::default().fg(theme.accent())) + .style(Style::default().bg(theme.background())) + .title_bottom(keybinds); + let inner = block.inner(area); + frame.render_widget(block, area); + + if state.picker.is_some() { + render_version_picker(frame, inner, state); + return; + } + if state.choice_picker.is_some() { + render_choice_picker(frame, inner, state); + return; + } + + let labels = [ + "Game version", + "Loader", + "Loader version", + "Java", + "Memory min", + "Memory max", + "JVM args", + "Resolution", + "Config profile", + "Desktop shortcut", + ]; + let mut lines = Vec::with_capacity(FIELD_COUNT + 2); + for (index, label) in labels.iter().enumerate() { + let selected = index == state.selected; + let marker = if selected { "▸ " } else { " " }; + let displayed = if selected && state.profile_input.is_some() { + "new profile (editing below)".to_owned() + } else if selected && state.editing.is_some() { + "editing below".to_owned() + } else { + state.display_value(index) + }; + lines.push(Line::from(vec![ + Span::styled(marker, Style::default().fg(theme.accent())), + Span::styled( + format!("{label:<18}"), + Style::default().fg(theme.text_dim()), + ), + Span::styled( + displayed, + Style::default() + .fg(if selected { + theme.accent() + } else { + theme.text() + }) + .add_modifier(if selected { + Modifier::BOLD + } else { + Modifier::empty() + }), + ), + ])); + } + if state.confirm_profile_delete { + lines.push(Line::from(Span::styled( + "Delete the selected shared profile? [y/n]", + Style::default().fg(theme.warning()), + ))); + } else if let Some(error) = &state.error { + lines.push(Line::from(Span::styled( + error, + Style::default().fg(theme.error()), + ))); + } else if state.confirm_runtime_change { + lines.push(Line::from(Span::styled( + "Changing the runtime downloads files and may break mods. Continue? [y/n]", + Style::default().fg(theme.warning()), + ))); + } else if state.confirm_close { + lines.push(Line::from(Span::styled( + "Discard unsaved changes? [y] yes [n] no", + Style::default().fg(theme.warning()), + ))); + } else { + let settings = SETTINGS.read(); + let defaults = &settings.defaults; + lines.push(Line::from(Span::styled( + format!( + "Empty Java/memory values use launcher defaults ({}-{}).", + defaults.memory_min, defaults.memory_max + ), + Style::default().fg(theme.text_dim()), + ))); + } + frame.render_widget(Paragraph::new(lines), inner); + if let Some(editor) = state.editing.as_ref().or(state.profile_input.as_ref()) { + let editor_area = Rect { + x: inner.x, + y: inner.y.saturating_add(12), + width: inner.width, + height: inner.height.saturating_sub(12).max(1), + }; + let editor_block = Block::default() + .title(if state.selected == 6 { + " JVM arguments — one argument per line; Ctrl+Enter applies " + } else { + " Value — Enter applies " + }) + .borders(Borders::ALL) + .border_style(Style::default().fg(theme.accent())); + let editor_inner = editor_block.inner(editor_area); + frame.render_widget(editor_block, editor_area); + frame.render_widget(editor, editor_inner); + } +} + +fn render_choice_picker(frame: &mut Frame, area: Rect, state: &State) { + let theme = THEME.as_ref(); + let title = match state.choice_picker { + Some(ChoicePicker::Loader) => "Select loader", + Some(ChoicePicker::Profile) => "Select config profile", + None => return, + }; + let mut lines = vec![Line::from(Span::styled( + title, + Style::default() + .fg(theme.text()) + .add_modifier(Modifier::BOLD), + ))]; + let values = state.choice_values(); + let visible_rows = area.height.saturating_sub(1) as usize; + let start = state + .choice_index + .saturating_sub(visible_rows.saturating_sub(1)); + for (index, value) in values.iter().enumerate().skip(start).take(visible_rows) { + let selected = index == state.choice_index; + lines.push(Line::from(vec![ + Span::styled( + if selected { "▸ " } else { " " }, + Style::default().fg(theme.accent()), + ), + Span::styled( + value.clone(), + Style::default() + .fg(if selected { + theme.accent() + } else { + theme.text() + }) + .add_modifier(if selected { + Modifier::BOLD + } else { + Modifier::empty() + }), + ), + ])); + } + frame.render_widget(Paragraph::new(lines), area); +} + +fn render_version_picker(frame: &mut Frame, area: Rect, state: &State) { + let theme = THEME.as_ref(); + let title = match state.picker { + Some(VersionPicker::Game) => "Minecraft version", + Some(VersionPicker::Loader) => "Loader version", + None => return, + }; + let status = match state.picker { + Some(VersionPicker::Game) => match &*state + .game_versions + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + { + LoadState::Idle => PickerLoad::Idle, + LoadState::Loading => PickerLoad::Loading, + LoadState::Loaded(_) => PickerLoad::Loaded, + LoadState::Error(error) => PickerLoad::Error(error.clone()), + }, + Some(VersionPicker::Loader) => match &*state + .loader_versions + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + { + LoadState::Idle => PickerLoad::Idle, + LoadState::Loading => PickerLoad::Loading, + LoadState::Loaded(_) => PickerLoad::Loaded, + LoadState::Error(error) => PickerLoad::Error(error.clone()), + }, + None => return, + }; + let mut lines = vec![Line::from(vec![ + Span::styled(format!("{title}: "), Style::default().fg(theme.text_dim())), + Span::styled( + if state.picker_search { + format!("/{}█", state.picker_query) + } else if state.picker_query.is_empty() { + "press / to search".to_owned() + } else { + format!("/{}", state.picker_query) + }, + Style::default().fg(theme.accent()), + ), + ])]; + match status { + PickerLoad::Idle | PickerLoad::Loading => lines.push(Line::from("Loading versions...")), + PickerLoad::Error(error) => lines.push(Line::from(Span::styled( + format!("Failed to load versions: {error}. Reopen to retry."), + Style::default().fg(theme.error()), + ))), + PickerLoad::Loaded => { + let versions: Vec = match state.picker { + Some(VersionPicker::Game) => state + .visible_game_versions() + .into_iter() + .map(|version| { + if version.stable { + version.id + } else { + format!("{} (snapshot)", version.id) + } + }) + .collect(), + Some(VersionPicker::Loader) => state.visible_loader_versions(), + None => Vec::new(), + }; + if versions.is_empty() { + lines.push(Line::from("No matching versions.")); + } else { + let visible_rows = area.height.saturating_sub(2) as usize; + let start = state + .picker_index + .saturating_sub(visible_rows.saturating_sub(1)); + for (index, version) in versions.iter().enumerate().skip(start).take(visible_rows) { + let selected = index == state.picker_index; + lines.push(Line::from(vec![ + Span::styled( + if selected { "▸ " } else { " " }, + Style::default().fg(theme.accent()), + ), + Span::styled( + version.clone(), + Style::default() + .fg(if selected { + theme.accent() + } else { + theme.text() + }) + .add_modifier(if selected { + Modifier::BOLD + } else { + Modifier::empty() + }), + ), + ])); + } + } + } + } + frame.render_widget(Paragraph::new(lines), area); +} + +#[cfg(test)] +mod tests { + use super::*; + use chrono::Utc; + + fn instance() -> InstanceConfig { + InstanceConfig { + name: "test".to_owned(), + game_version: "1.21.1".to_owned(), + loader: ModLoader::Fabric, + loader_version: Some("0.16.0".to_owned()), + created: Utc::now(), + last_played: None, + java_path: None, + memory_max: None, + memory_min: None, + jvm_args: Vec::new(), + resolution: None, + config_sync_profile: None, + modpack_source: None, + } + } + + #[test] + fn memory_and_resolution_inputs_are_normalized() { + let temp = tempfile::tempdir().unwrap(); + let mut state = State::new(&instance(), temp.path()); + state.selected = 4; + state.editing = Some(new_text_area(vec!["2048m".to_owned()])); + state.commit_edit(); + assert_eq!(state.draft.memory_min.as_deref(), Some("2048M")); + + state.selected = 7; + state.editing = Some(new_text_area(vec!["1920X1080".to_owned()])); + state.commit_edit(); + assert_eq!(state.draft.resolution, Some((1920, 1080))); + } + + #[test] + fn text_editor_supports_cursor_movement_and_multiline_jvm_arguments() { + let temp = tempfile::tempdir().unwrap(); + let mut config = instance(); + config.memory_min = Some("512M".to_owned()); + let mut state = State::new(&config, temp.path()); + state.selected = 4; + state.begin_edit(); + state.handle_key(&KeyEvent::from(KeyCode::Left)); + state.handle_key(&KeyEvent::from(KeyCode::Char('0'))); + state.handle_key(&KeyEvent::from(KeyCode::Enter)); + assert_eq!(state.draft.memory_min.as_deref(), Some("5120M")); + + state.selected = 6; + state.begin_edit(); + for character in "-Xfoo".chars() { + state.handle_key(&KeyEvent::from(KeyCode::Char(character))); + } + state.handle_key(&KeyEvent::from(KeyCode::Enter)); + for character in "-Xbar".chars() { + state.handle_key(&KeyEvent::from(KeyCode::Char(character))); + } + state.handle_key(&KeyEvent::new(KeyCode::Enter, KeyModifiers::CONTROL)); + assert_eq!(state.draft.jvm_args, ["-Xfoo", "-Xbar"]); + } + + #[test] + fn runtime_changes_require_confirmation_before_save() { + let temp = tempfile::tempdir().unwrap(); + let mut state = State::new(&instance(), temp.path()); + state.draft.game_version = "1.21.2".to_owned(); + + assert!(matches!( + state.handle_key(&KeyEvent::from(KeyCode::Char('s'))), + Action::None + )); + assert!(state.confirm_runtime_change); + assert!(matches!( + state.handle_key(&KeyEvent::from(KeyCode::Char('y'))), + Action::Save(_, _) + )); + } + + #[test] + fn version_picker_selects_loaded_version_and_clears_loader_version() { + let temp = tempfile::tempdir().unwrap(); + let mut state = State::new(&instance(), temp.path()); + *state.game_versions.lock().unwrap() = LoadState::Loaded(vec![ + GameVersion { + id: "1.21.2".to_owned(), + stable: true, + }, + GameVersion { + id: "1.21.1".to_owned(), + stable: true, + }, + ]); + state.picker = Some(VersionPicker::Game); + state.picker_initialized = true; + state.picker_index = 0; + + state.handle_picker_key(&KeyEvent::from(KeyCode::Enter)); + + assert_eq!(state.draft.game_version, "1.21.2"); + assert_eq!(state.draft.loader_version, None); + } + + #[test] + fn adding_profile_is_staged_until_settings_are_saved() { + let temp = tempfile::tempdir().unwrap(); + let mut state = State::new(&instance(), temp.path()); + state.profile_input = Some(new_text_area(vec!["new-profile".to_owned()])); + + state.handle_key(&KeyEvent::from(KeyCode::Enter)); + + assert_eq!( + state.draft.config_sync_profile.as_deref(), + Some("new-profile") + ); + assert!( + crate::instance::config_sync::list_profiles(temp.path()) + .unwrap() + .is_empty() + ); + } + + #[test] + fn selecting_loader_clears_the_previous_loaders_version() { + let temp = tempfile::tempdir().unwrap(); + let mut state = State::new(&instance(), temp.path()); + + state.open_choice_picker(ChoicePicker::Loader); + state.handle_choice_key(&KeyEvent::from(KeyCode::Char('j'))); + state.handle_choice_key(&KeyEvent::from(KeyCode::Enter)); + + assert_eq!(state.draft.loader, ModLoader::Forge); + assert_eq!(state.draft.loader_version, None); + assert!(!state.validate_before_save()); + } +} diff --git a/src/tui/widgets/popups/mod.rs b/src/tui/widgets/popups/mod.rs index 10f2794..42f8403 100644 --- a/src/tui/widgets/popups/mod.rs +++ b/src/tui/widgets/popups/mod.rs @@ -7,10 +7,13 @@ pub mod base; pub mod confirm; pub mod error; +pub mod global_settings; pub mod import_modpack; +pub mod instance_settings; mod load_state; pub mod modpack_update; pub mod new_instance; +pub mod version_lists; pub use load_state::LoadState; diff --git a/src/tui/widgets/popups/new_instance/state.rs b/src/tui/widgets/popups/new_instance/state.rs index 098a558..5c49505 100644 --- a/src/tui/widgets/popups/new_instance/state.rs +++ b/src/tui/widgets/popups/new_instance/state.rs @@ -5,10 +5,7 @@ // flow: Name -> Loader -> Version -> LoaderVersion -> Confirm // version lists are fetched lazily from the network when you reach that step. -use crate::instance::{ - loader::{GameVersion, get_installer}, - models::ModLoader, -}; +use crate::instance::{loader::GameVersion, models::ModLoader}; use crate::tui::widgets::instances; use crossterm::event::{KeyCode, KeyEvent}; use std::sync::LazyLock; @@ -405,12 +402,9 @@ pub(crate) fn ensure_versions_loaded(state: &mut WizardState) { let versions_arc = WIZARD_STATE.clone(); let loader = state.selected_loader(); tokio::spawn(async move { - let client = crate::net::HttpClient::new(); - let installer = get_installer(loader); - match installer.get_game_versions(&client).await { - Ok(mut versions) => match versions_arc.lock() { + match super::super::version_lists::game_versions(loader).await { + Ok(versions) => match versions_arc.lock() { Ok(mut s) => { - sort_versions_semver(&mut versions); s.versions = LoadState::Loaded(versions); clamp_version_index(&mut s); } @@ -442,9 +436,7 @@ pub(crate) fn ensure_loader_versions_loaded( state.loader_versions = LoadState::Loading; let versions_arc = WIZARD_STATE.clone(); tokio::spawn(async move { - let client = crate::net::HttpClient::new(); - let installer = get_installer(loader); - match installer.get_versions(&client, &game_version).await { + match super::super::version_lists::loader_versions(loader, &game_version).await { Ok(versions) => match versions_arc.lock() { Ok(mut s) => { s.loader_versions = LoadState::Loaded(versions); @@ -466,10 +458,6 @@ pub(crate) fn ensure_loader_versions_loaded( }); } -fn sort_versions_semver(versions: &mut [GameVersion]) { - versions.sort_by(|a, b| super::super::compare_game_versions(&b.id, &a.id)); -} - #[cfg(test)] #[path = "../../../tests/widgets/popups/new_instance/state.rs"] mod tests; diff --git a/src/tui/widgets/popups/version_lists.rs b/src/tui/widgets/popups/version_lists.rs new file mode 100644 index 0000000..fdafbb5 --- /dev/null +++ b/src/tui/widgets/popups/version_lists.rs @@ -0,0 +1,27 @@ +// SPDX-FileCopyrightText: 2026 Constantin Bauer +// SPDX-License-Identifier: GPL-3.0-only + +// shared network loading for Minecraft and mod-loader version pickers. + +use crate::instance::{ + loader::{GameVersion, get_installer}, + models::ModLoader, +}; + +pub async fn game_versions(loader: ModLoader) -> Result, String> { + let client = crate::net::HttpClient::new(); + let mut versions = get_installer(loader) + .get_game_versions(&client) + .await + .map_err(|error| error.to_string())?; + versions.sort_by(|a, b| super::compare_game_versions(&b.id, &a.id)); + Ok(versions) +} + +pub async fn loader_versions(loader: ModLoader, game_version: &str) -> Result, String> { + let client = crate::net::HttpClient::new(); + get_installer(loader) + .get_versions(&client, game_version) + .await + .map_err(|error| error.to_string()) +} diff --git a/src/tui/widgets/settings.rs b/src/tui/widgets/settings.rs index a477330..26bb397 100644 --- a/src/tui/widgets/settings.rs +++ b/src/tui/widgets/settings.rs @@ -1,23 +1,8 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// settings panel: manages config profiles and shows compact instance info. -// also provides keybinds to open config files in $EDITOR. - -use std::{ - path::{Path, PathBuf}, - process::Command, -}; - -use crossterm::event::{KeyCode, KeyEvent}; -use ratatui::{ - Frame, - layout::{Constraint, Direction, Layout, Rect}, - style::{Modifier, Style}, - text::{Line, Span}, - widgets::{Block, Borders, Paragraph, Widget}, -}; -use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView}; +// compact, read-only summary of the selected instance. editing lives in the +// instance and launcher settings popups. use crate::config::{ SETTINGS, @@ -25,181 +10,24 @@ use crate::config::{ }; use crate::instance::models::InstanceConfig; use crate::tui::app::FocusedArea; +use ratatui::{ + Frame, + layout::Rect, + style::{Modifier, Style}, + text::{Line, Span}, + widgets::{Block, Borders, Paragraph}, +}; use super::styled_title; const LOCAL_PROFILE_LABEL: &str = "instance default"; -#[derive(Default)] -pub enum AddMode { - #[default] - None, - ProfileName(String), -} - -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub enum SettingsPane { - #[default] - Profile, - Info, -} - -pub struct SettingsState { - pub list_state: TuiListState, - pub profiles: Vec, - pub add_mode: AddMode, - pub pane: SettingsPane, - meta_dir: PathBuf, - active_profile: Option, - instance_name: Option, - java_key: Option, - java_source: Option, - java_label: String, -} - -impl SettingsState { - pub fn new(meta_dir: PathBuf) -> Self { - let profiles = crate::instance::config_sync::list_profiles(&meta_dir).unwrap_or_else(|e| { - tracing::warn!("Failed to load config sync profiles: {}", e); - Vec::new() - }); - let mut state = Self { - list_state: TuiListState::default(), - profiles, - add_mode: AddMode::None, - pane: SettingsPane::Profile, - meta_dir, - active_profile: None, - instance_name: None, - java_key: None, - java_source: None, - java_label: "unknown".to_string(), - }; - state.select_active(); - state - } - - fn reload_profiles(&mut self) { - match crate::instance::config_sync::list_profiles(&self.meta_dir) { - Ok(mut profiles) => { - add_active_profile(&mut profiles, self.active_profile.as_deref()); - self.profiles = profiles; - } - Err(e) => tracing::warn!("Failed to reload config sync profiles: {}", e), - } - } - - fn select_active(&mut self) { - self.list_state.selected = Some( - self.active_profile - .as_deref() - .and_then(|active| self.profiles.iter().position(|profile| profile == active)) - .map(|idx| idx + 1) - .unwrap_or(0), - ); - } - - fn count(&self) -> usize { - self.profiles.len() + 1 - } - - pub fn remove_profile(&mut self, profile: &str) { - self.profiles.retain(|candidate| candidate != profile); - if self.active_profile.as_deref() == Some(profile) { - self.active_profile = None; - } - let last = self.count().saturating_sub(1); - self.list_state.selected = Some(self.list_state.selected.unwrap_or(0).min(last)); - } - - fn update_for_instance(&mut self, instance: Option<&InstanceConfig>) { - let instance_name = instance.map(|inst| inst.name.clone()); - let active_profile = instance.and_then(|inst| inst.config_sync_profile.clone()); - let active_profile = active_profile - .filter(|profile| self.profiles.iter().any(|candidate| candidate == profile)); - if self.instance_name != instance_name || self.active_profile != active_profile { - self.instance_name = instance_name; - self.active_profile = active_profile; - add_active_profile(&mut self.profiles, self.active_profile.as_deref()); - self.select_active(); - } - - let java_key = instance.map(java_path_key); - if self.java_key != java_key { - let java_source = instance.map(effective_java_path); - self.java_label = java_source - .as_deref() - .map(java_version_label) - .unwrap_or_else(|| "unknown".to_string()); - self.java_key = java_key; - self.java_source = java_source; - } - } -} - -fn add_active_profile(profiles: &mut Vec, active_profile: Option<&str>) { - if let Some(active) = active_profile - && !profiles.iter().any(|profile| profile == active) - { - profiles.push(active.to_string()); - profiles.sort_unstable(); - } -} - -fn java_path_key(instance: &InstanceConfig) -> String { - instance - .java_path - .as_deref() - .filter(|path| !path.is_empty()) - .or_else(|| SETTINGS.paths.effective_java_path()) - .unwrap_or("") - .to_string() -} - -fn effective_java_path(instance: &InstanceConfig) -> String { - instance - .java_path - .clone() - .or_else(|| SETTINGS.paths.effective_java_path().map(str::to_string)) - .unwrap_or_else(crate::instance::java::detect_java_path) -} - -fn java_version_label(java_path: &str) -> String { - let output = Command::new(java_path).arg("-version").output(); - let Ok(output) = output else { - return "unknown".to_string(); - }; - let raw = String::from_utf8_lossy(if output.stderr.is_empty() { - &output.stdout - } else { - &output.stderr - }); - let first_line = raw.lines().next().unwrap_or_default(); - let Some(version) = first_line.split('"').nth(1) else { - return "unknown".to_string(); - }; - let major = if let Some(stripped) = version.strip_prefix("1.") { - stripped.split('.').next().unwrap_or(stripped) - } else { - version.split('.').next().unwrap_or(version) - }; - if major.is_empty() { - "unknown".to_string() - } else { - format!("jdk{major}") - } -} - pub fn render( frame: &mut Frame, area: Rect, focused: FocusedArea, - state: &mut SettingsState, instance: Option<&InstanceConfig>, - _instances_dir: &Path, ) { - state.update_for_instance(instance); - let theme = THEME.as_ref(); let color = if focused == FocusedArea::Settings { theme.accent() @@ -214,23 +42,7 @@ pub fn render( .border_style(Style::default().fg(color)); let keybind_line = if focused == FocusedArea::Settings { - let keybinds: &[(&str, &str)] = match state.pane { - SettingsPane::Profile => &[ - ("⏎", " select"), - ("a", " add"), - ("d", " del"), - ("j/k", " move"), - ("h/l", " tab"), - ("Esc", " back"), - ], - SettingsPane::Info => &[ - ("e", " inst"), - ("g", " global"), - ("d", " desk"), - ("h/l", " tab"), - ("Esc", " back"), - ], - }; + let keybinds: &[(&str, &str)] = &[("E", " instance"), ("G", " launcher"), ("Esc", " back")]; Some(super::popups::keybind_line_fitted( keybinds, area.width.saturating_sub(2), @@ -245,49 +57,10 @@ pub fn render( let inner = block.inner(area); frame.render_widget(block, area); - if inner.width >= 42 { - let chunks = Layout::default() - .direction(Direction::Horizontal) - .constraints([ - Constraint::Percentage(50), - Constraint::Length(3), - Constraint::Percentage(50), - ]) - .split(inner); - render_profile_list(frame, chunks[0], focused, state); - render_separator(frame, chunks[1], focused, state.pane); - render_instance_info(frame, chunks[2], focused, state, instance); - } else { - render_profile_list(frame, inner, focused, state); - } - - if let AddMode::ProfileName(name) = &state.add_mode { - render_add_profile_popup(frame, name); - } + render_instance_info(frame, inner, instance); } -fn render_separator(frame: &mut Frame, area: Rect, focused: FocusedArea, pane: SettingsPane) { - let theme = THEME.as_ref(); - let color = if focused == FocusedArea::Settings && pane == SettingsPane::Info { - theme.accent() - } else { - theme.border() - }; - let line = if area.width >= 3 { - " │ \n".repeat(area.height as usize) - } else { - "│\n".repeat(area.height as usize) - }; - frame.render_widget(Paragraph::new(line).style(Style::default().fg(color)), area); -} - -fn render_instance_info( - frame: &mut Frame, - area: Rect, - focused: FocusedArea, - state: &SettingsState, - instance: Option<&InstanceConfig>, -) { +fn render_instance_info(frame: &mut Frame, area: Rect, instance: Option<&InstanceConfig>) { let theme = THEME.as_ref(); let label_style = Style::default().fg(theme.text_dim()); let value_style = Style::default() @@ -302,278 +75,59 @@ fn render_instance_info( return; }; + let settings = SETTINGS.read(); let memory_min = inst .memory_min .as_deref() - .unwrap_or(&SETTINGS.defaults.memory_min); + .unwrap_or(&settings.defaults.memory_min); let memory_max = inst .memory_max .as_deref() - .unwrap_or(&SETTINGS.defaults.memory_max); - let active_style = if focused == FocusedArea::Settings && state.pane == SettingsPane::Info { - value_style.fg(theme.accent()) - } else { - value_style - }; + .unwrap_or(&settings.defaults.memory_max); + let active_style = value_style; let desktop = if crate::instance::desktop::exists(&inst.name) { "yes" } else { "no" }; + let java_source = if inst + .java_path + .as_deref() + .is_some_and(|path| !path.is_empty()) + { + "instance java" + } else if settings.paths.effective_java_path().is_some() { + "global java" + } else { + "auto java" + }; let lines = vec![ Line::from(vec![ - Span::styled("Memory ", label_style), - Span::styled(format!("{memory_min} - {memory_max}"), active_style), + Span::styled("Version ", label_style), + Span::styled( + format!("{} / {}", inst.game_version, inst.loader), + active_style, + ), ]), Line::from(vec![ - Span::styled("Java ", label_style), - Span::styled(state.java_label.as_str(), active_style), + Span::styled("Runtime ", label_style), + Span::styled( + format!("{memory_min}-{memory_max}, {java_source}"), + active_style, + ), ]), Line::from(vec![ - Span::styled("Desktop ", label_style), + Span::styled("Profile ", label_style), + Span::styled( + inst.config_sync_profile + .as_deref() + .unwrap_or(LOCAL_PROFILE_LABEL), + active_style, + ), + Span::styled(" / desk ", label_style), Span::styled(desktop, active_style), ]), ]; frame.render_widget(Paragraph::new(lines), area); } - -fn render_profile_list( - frame: &mut Frame, - area: Rect, - focused: FocusedArea, - state: &mut SettingsState, -) { - let is_focused = focused == FocusedArea::Settings; - let pane = state.pane; - let active_profile = state.active_profile.clone(); - let profiles = state.profiles.clone(); - let count = profiles.len() + 1; - let last = count.saturating_sub(1); - state.list_state.selected = Some(state.list_state.selected.unwrap_or(0).min(last)); - - let builder = ListBuilder::new(move |context| { - let theme = THEME.as_ref(); - let name = if context.index == 0 { - LOCAL_PROFILE_LABEL.to_string() - } else { - profiles.get(context.index - 1).cloned().unwrap_or_default() - }; - let is_active = if context.index == 0 { - active_profile.is_none() - } else { - active_profile.as_deref() == Some(name.as_str()) - }; - let show_selected = is_focused && pane == SettingsPane::Profile && context.is_selected; - let marker = if is_active { "\u{25b8} " } else { " " }; - let background = if show_selected { - theme.stripe() - } else { - theme.background() - }; - let style = if show_selected { - Style::default() - .fg(theme.accent()) - .add_modifier(Modifier::BOLD) - } else if is_active { - Style::default() - .fg(theme.text()) - .add_modifier(Modifier::BOLD) - } else { - Style::default().fg(theme.text()) - }; - let line = Line::from(vec![ - Span::styled(marker, Style::default().fg(theme.success())), - Span::styled(name, style), - ]); - ( - ratatui::text::Text::from(line).style(Style::default().bg(background)), - 1, - ) - }); - - frame.render_stateful_widget(ListView::new(builder, count), area, &mut state.list_state); -} - -fn render_add_profile_popup(frame: &mut Frame, name: &str) { - use super::popups::{base::PopupFrame, keybind_line}; - let theme = THEME.as_ref(); - let area = popup_area(frame, 42, 5); - let name = name.to_string(); - - let border_color = theme.text_dim(); - let bg_color = theme.surface(); - let dim_color = theme.text_dim(); - let text_color = theme.text(); - - PopupFrame { - title: Line::from(Span::styled( - " Config Profile ", - Style::default() - .fg(border_color) - .add_modifier(Modifier::BOLD), - )) - .centered(), - border_color, - bg: Some(bg_color), - keybinds: Some(keybind_line(&[("Enter", " create"), ("Esc", " cancel")])), - search_line: None, - content: Box::new(move |inner, buf| { - let line = if name.is_empty() { - Line::from(vec![ - Span::styled("Profile name...", Style::default().fg(dim_color)), - Span::styled( - "\u{2588}", - Style::default() - .fg(border_color) - .add_modifier(Modifier::SLOW_BLINK), - ), - ]) - } else { - Line::from(vec![ - Span::styled(name.as_str(), Style::default().fg(text_color)), - Span::styled( - "\u{2588}", - Style::default() - .fg(border_color) - .add_modifier(Modifier::SLOW_BLINK), - ), - ]) - }; - Paragraph::new(line).render(inner, buf); - }), - } - .render(area, frame.buffer_mut()); -} - -fn popup_area(frame: &Frame, width: u16, height: u16) -> Rect { - let area = frame.area(); - let x = area.x + (area.width.saturating_sub(width)) / 2; - let y = area.y + (area.height.saturating_sub(height)) / 2; - Rect { - x, - y, - width: width.min(area.width), - height: height.min(area.height), - } -} - -pub enum SettingsAction { - None, - EditInstance(PathBuf), - EditGlobal(PathBuf), - ToggleDesktop, - SelectProfile(Option), - ConfirmDeleteProfile(String), - Error(String), -} - -pub fn handle_key( - key_event: &KeyEvent, - state: &mut SettingsState, - instance: Option<&InstanceConfig>, - instances_dir: &Path, -) -> SettingsAction { - if let AddMode::ProfileName(name) = &state.add_mode { - match key_event.code { - KeyCode::Enter => { - let name = name.trim().to_string(); - state.add_mode = AddMode::None; - if name.is_empty() { - return SettingsAction::None; - } - return match crate::instance::config_sync::create_profile(&state.meta_dir, &name) { - Ok(profile) => { - state.reload_profiles(); - state.active_profile = Some(profile); - state.select_active(); - SettingsAction::SelectProfile(state.active_profile.clone()) - } - Err(e) => SettingsAction::Error(e.to_string()), - }; - } - KeyCode::Esc => { - state.add_mode = AddMode::None; - return SettingsAction::None; - } - KeyCode::Backspace => { - let mut new_name = name.clone(); - super::search::backspace(&mut new_name, key_event.modifiers); - state.add_mode = AddMode::ProfileName(new_name); - return SettingsAction::None; - } - KeyCode::Char(c) => { - let mut new_name = name.clone(); - new_name.push(c); - state.add_mode = AddMode::ProfileName(new_name); - return SettingsAction::None; - } - _ => return SettingsAction::None, - } - } - - match key_event.code { - KeyCode::Char('h') | KeyCode::Left => { - state.pane = SettingsPane::Profile; - SettingsAction::None - } - KeyCode::Char('l') | KeyCode::Right => { - state.pane = SettingsPane::Info; - SettingsAction::None - } - KeyCode::Enter if state.pane == SettingsPane::Profile => { - let selected = state.list_state.selected.unwrap_or(0); - let profile = if selected == 0 { - None - } else { - state.profiles.get(selected - 1).cloned() - }; - SettingsAction::SelectProfile(profile) - } - KeyCode::Char('a') if state.pane == SettingsPane::Profile => { - state.add_mode = AddMode::ProfileName(String::new()); - SettingsAction::None - } - KeyCode::Char('d') if state.pane == SettingsPane::Profile => { - let selected = state.list_state.selected.unwrap_or(0); - if selected == 0 { - SettingsAction::None - } else if let Some(profile) = state.profiles.get(selected - 1) { - SettingsAction::ConfirmDeleteProfile(profile.clone()) - } else { - SettingsAction::None - } - } - KeyCode::Char('j') | KeyCode::Down if state.pane == SettingsPane::Profile => { - let count = state.count(); - if count > 0 { - let cur = state.list_state.selected.unwrap_or(0); - state.list_state.selected = Some((cur + 1).min(count - 1)); - } - SettingsAction::None - } - KeyCode::Char('k') | KeyCode::Up if state.pane == SettingsPane::Profile => { - let cur = state.list_state.selected.unwrap_or(0); - state.list_state.selected = Some(cur.saturating_sub(1)); - SettingsAction::None - } - KeyCode::Char('e') if state.pane == SettingsPane::Info => { - if let Some(inst) = instance { - let path = instances_dir.join(&inst.name).join("instance.json"); - SettingsAction::EditInstance(path) - } else { - SettingsAction::None - } - } - KeyCode::Char('g') if state.pane == SettingsPane::Info => { - let path = crate::config::get_config_path().join("config.toml"); - SettingsAction::EditGlobal(path) - } - KeyCode::Char('d') if state.pane == SettingsPane::Info => SettingsAction::ToggleDesktop, - _ => SettingsAction::None, - } -} - -#[cfg(test)] -#[path = "../tests/widgets/settings.rs"] -mod tests;