diff --git a/src/instance/java.rs b/src/instance/java.rs index db6b4e5..8b139d1 100644 --- a/src/instance/java.rs +++ b/src/instance/java.rs @@ -9,7 +9,9 @@ use std::{ process::Command, }; -#[derive(Debug, Clone, PartialEq, Eq)] +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct JavaInstallation { pub path: PathBuf, pub version: Option, @@ -91,10 +93,9 @@ pub fn discover_installations() -> Vec { .filter(|path| path.is_file()) .filter_map(|path| { let identity = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone()); - seen.insert(identity).then(|| JavaInstallation { - version: java_version(&path), - path, - }) + seen.insert(identity) + .then(|| inspect_installation(&path)) + .flatten() }) .collect::>(); installations.sort_by(|a, b| { @@ -105,6 +106,31 @@ pub fn discover_installations() -> Vec { installations } +/// Reads the version reported by one Java executable. +#[must_use] +pub fn inspect_installation(path: &Path) -> Option { + path.is_file().then(|| JavaInstallation { + version: java_version(path), + path: path.to_path_buf(), + }) +} + +#[must_use] +pub fn load_installation_cache(path: &Path) -> Option> { + let mut installations = + serde_json::from_slice::>(&std::fs::read(path).ok()?).ok()?; + installations.retain(|installation| installation.path.is_file()); + (!installations.is_empty()).then_some(installations) +} + +pub fn save_installation_cache( + path: &Path, + installations: &[JavaInstallation], +) -> std::io::Result<()> { + let bytes = serde_json::to_vec_pretty(installations).map_err(std::io::Error::other)?; + crate::storage::write_atomic(path, &bytes) +} + fn java_roots() -> Vec { let mut roots = Vec::new(); if cfg!(target_os = "windows") { @@ -237,4 +263,22 @@ mod tests { assert_eq!(java_major(Some("21.0.4")), 21); assert_eq!(java_major(Some("1.8.0_412")), 8); } + + #[test] + fn installation_cache_round_trips_existing_paths() { + let temp = tempfile::tempdir().unwrap(); + let executable = temp.path().join("java"); + std::fs::write(&executable, b"java").unwrap(); + let cache = temp.path().join("cache/java/installations.json"); + let installations = vec![JavaInstallation { + path: executable.clone(), + version: Some("25.0.1".to_owned()), + }]; + + save_installation_cache(&cache, &installations).unwrap(); + assert_eq!(load_installation_cache(&cache), Some(installations)); + + std::fs::remove_file(executable).unwrap(); + assert_eq!(load_installation_cache(&cache), None); + } } diff --git a/src/instance/launch/mod.rs b/src/instance/launch/mod.rs index 54dcf34..69187c0 100644 --- a/src/instance/launch/mod.rs +++ b/src/instance/launch/mod.rs @@ -13,7 +13,7 @@ use std::path::{Path, PathBuf}; use thiserror::Error; use crate::auth::AccountType; -use crate::instance::models::{InstanceConfig, ModLoader}; +use crate::instance::models::{InstanceConfig, LaunchCommand, ModLoader, WindowMode}; use crate::launch_profile::model::{Argument, LaunchProfile}; use crate::launch_profile::rules::{self, FeatureSet, RuleAction, RuleContext}; use crate::launch_profile::templates::TemplateContext; @@ -45,6 +45,8 @@ pub enum LaunchError { }, #[error("{0}")] Auth(String), + #[error("{phase} command failed: {reason}")] + Command { phase: &'static str, reason: String }, #[error("Config sync error: {0}")] ConfigSync(#[from] crate::instance::config_sync::ConfigSyncError), } @@ -71,6 +73,14 @@ fn apply_custom_resolution(game_args: &mut Vec, resolution: Option<(u32, } } +fn apply_window_mode(game_args: &mut Vec, window_mode: WindowMode) { + if window_mode == WindowMode::Windowed { + game_args.retain(|argument| argument != "--fullscreen"); + } else if !game_args.iter().any(|arg| arg == "--fullscreen") { + game_args.push("--fullscreen".to_owned()); + } +} + fn parse_java_major_version(text: &str) -> Option { let quoted = text .split_once('"') @@ -318,6 +328,7 @@ pub struct LaunchInvocation { pub main_class: String, pub extra_args: Vec, pub game_args: Vec, + pub environment: std::collections::BTreeMap, pub working_dir: PathBuf, } @@ -605,6 +616,7 @@ pub async fn build_launch_invocation( // Modern Mojang profiles include feature-gated resolution arguments. // Older and third-party profiles may not, so add them when absent. apply_custom_resolution(&mut game_args, config.resolution); + apply_window_mode(&mut game_args, config.window_mode); let (memory_min, memory_max) = { let settings = crate::config::SETTINGS.read(); @@ -623,6 +635,9 @@ pub async fn build_launch_invocation( jvm_args.extend(patch_jvm_args); jvm_args.extend(upstream_jvm_args); jvm_args.extend(config.jvm_args.clone()); + if let Some(glfw_path) = config.glfw_path.as_deref() { + jvm_args.push(format!("-Dorg.lwjgl.glfw.libname={glfw_path}")); + } Ok(LaunchInvocation { java, @@ -632,10 +647,94 @@ pub async fn build_launch_invocation( main_class, extra_args, game_args, + environment: config.environment.clone(), working_dir: minecraft_dir, }) } +fn command_process(command: &str) -> tokio::process::Command { + #[cfg(windows)] + { + let mut process = tokio::process::Command::new("cmd"); + process.args(["/C", command]); + process + } + #[cfg(not(windows))] + { + let mut process = tokio::process::Command::new("/bin/sh"); + process.args(["-c", command]); + process + } +} + +fn select_launch_account<'a>( + accounts: &'a [crate::auth::Account], + preferred: Option<&str>, +) -> Option<&'a crate::auth::Account> { + preferred + .and_then(|uuid| accounts.iter().find(|account| account.uuid == uuid)) + .or_else(|| accounts.iter().find(|account| account.active)) +} + +async fn run_launch_command( + phase: &'static str, + command: &LaunchCommand, + config: &InstanceConfig, + invocation: &LaunchInvocation, + instance_dir: &Path, +) -> Result<(), LaunchError> { + if !command.enabled || command.command.trim().is_empty() { + return Ok(()); + } + + tracing::info!("[{}] Running {} command", config.name, phase.to_lowercase()); + let mut process = command_process(&command.command); + process + .current_dir(&invocation.working_dir) + .envs(&invocation.environment) + .env("INST_NAME", &config.name) + .env("INST_ID", &config.name) + .env("INST_DIR", instance_dir) + .env("INST_MC_DIR", &invocation.working_dir) + .env("INST_JAVA", &invocation.java) + .env("INST_JAVA_ARGS", invocation.jvm_args.join(" ")); + let output = process + .output() + .await + .map_err(|error| LaunchError::Command { + phase, + reason: error.to_string(), + })?; + for line in String::from_utf8_lossy(&output.stdout).lines() { + tracing::info!("[{}] [{}] {}", config.name, phase, line); + } + for line in String::from_utf8_lossy(&output.stderr).lines() { + tracing::warn!("[{}] [{}] {}", config.name, phase, line); + } + if output.status.success() { + Ok(()) + } else { + Err(LaunchError::Command { + phase, + reason: output.status.to_string(), + }) + } +} + +fn finish_config_sync( + active: bool, + profile: Option<&str>, + meta_dir: &Path, + minecraft_dir: &Path, + instance: &str, +) { + if active + && let Err(error) = crate::instance::config_sync::finish(profile, meta_dir, minecraft_dir) + { + tracing::warn!("Failed to sync config for '{}': {}", instance, error); + } +} + // resolves auth credentials, then builds the launch invocation and spawns // the java process. only thin wrapper logic lives here: token refresh, // process spawn, child supervision. all the heavy lifting (profile loading, @@ -650,7 +749,9 @@ pub async fn launch( // resolve auth credentials, refreshing the microsoft token if needed. let mut account_store = crate::auth::AccountStore::load(); - let Some(acc) = account_store.active_account().cloned() else { + let account = + select_launch_account(&account_store.accounts, config.preferred_account.as_deref()); + let Some(acc) = account.cloned() else { return Err(LaunchError::Auth("No account selected".to_owned())); }; @@ -704,6 +805,7 @@ pub async fn launch( let invocation = build_launch_invocation(config, instances_dir, meta_dir, &auth, quick_play_world).await?; + let instance_dir = instances_dir.join(&config.name); tracing::debug!( "[{}] Prepared launch invocation: working_dir={} classpath_entries={} jvm_args={} extra_args={} game_args={} main_class={}", name, @@ -720,6 +822,24 @@ pub async fn launch( meta_dir, &invocation.working_dir, )?; + if let Err(error) = run_launch_command( + "Pre-launch", + &config.pre_launch_command, + config, + &invocation, + &instance_dir, + ) + .await + { + finish_config_sync( + config_sync_active, + config_sync_profile.as_deref(), + meta_dir, + &invocation.working_dir, + &name, + ); + return Err(error); + } let (kill_tx, kill_rx) = tokio::sync::oneshot::channel::<()>(); crate::instance::runtime::register_kill(&name, kill_tx); @@ -752,6 +872,7 @@ pub async fn launch( cmd.args(&invocation.extra_args); cmd.args(&invocation.game_args); cmd.current_dir(&invocation.working_dir); + cmd.envs(&invocation.environment); cmd.stdout(std::process::Stdio::piped()); cmd.stderr(std::process::Stdio::piped()); @@ -760,6 +881,13 @@ pub async fn launch( Err(e) => { crate::instance::runtime::cleanup_kill_sender(&name); crate::instance::runtime::remove(&name); + finish_config_sync( + config_sync_active, + config_sync_profile.as_deref(), + meta_dir, + &invocation.working_dir, + &name, + ); tracing::error!("[{}] Failed to spawn Minecraft process: {}", name, e); return Err(LaunchError::Io(e)); } @@ -782,6 +910,10 @@ pub async fn launch( let instances_dir_owned = instances_dir.to_path_buf(); let meta_dir_owned = meta_dir.to_path_buf(); let minecraft_dir_owned = invocation.working_dir.clone(); + let instance_dir_owned = instances_dir.join(&config.name); + let post_exit_command = config.post_exit_command.clone(); + let config_for_post_exit = config.clone(); + let invocation_for_post_exit = invocation.clone(); // spawn a background task to babysit the child process: capture stdout/stderr // into both the TUI log viewer and a timestamped log file on disk @@ -883,15 +1015,26 @@ pub async fn launch( let _ = parser_task.await; tracing::info!("[{}] Exited with code {:?}", name_for_task, code); - if config_sync_active - && let Err(e) = crate::instance::config_sync::finish( - config_sync_profile.as_deref(), - &meta_dir_owned, - &minecraft_dir_owned, - ) + if let Err(error) = run_launch_command( + "Post-exit", + &post_exit_command, + &config_for_post_exit, + &invocation_for_post_exit, + &instance_dir_owned, + ) + .await { - tracing::warn!("Failed to sync config for '{}': {}", name_for_task, e); + tracing::warn!("[{}] {}", name_for_task, error); + crate::feedback::errors::push_message(tracing::Level::WARN, error.to_string()); } + + finish_config_sync( + config_sync_active, + config_sync_profile.as_deref(), + &meta_dir_owned, + &minecraft_dir_owned, + &name_for_task, + ); if code == Some(0) || killed_by_user { crate::instance::runtime::remove(&name_for_task); tracing::debug!( diff --git a/src/instance/manager.rs b/src/instance/manager.rs index 9968033..0e91ded 100644 --- a/src/instance/manager.rs +++ b/src/instance/manager.rs @@ -273,7 +273,13 @@ impl InstanceManager { memory_max: None, memory_min: None, jvm_args: vec![], + environment: Default::default(), + window_mode: Default::default(), resolution: None, + preferred_account: None, + pre_launch_command: Default::default(), + post_exit_command: Default::default(), + glfw_path: None, config_sync_profile: None, modpack_source: None, }; diff --git a/src/instance/mod.rs b/src/instance/mod.rs index 7aa53c4..e47bd0a 100644 --- a/src/instance/mod.rs +++ b/src/instance/mod.rs @@ -27,4 +27,4 @@ pub use content::{ pub use launch::LaunchError; pub use loader::{GameVersion, ModLoaderInstaller, VanillaInstaller, get_installer}; pub use manager::{InstanceError, InstanceManager}; -pub use models::{InstanceConfig, ModLoader, normalize_memory_value}; +pub use models::{InstanceConfig, LaunchCommand, ModLoader, WindowMode, normalize_memory_value}; diff --git a/src/instance/models.rs b/src/instance/models.rs index baa8051..de294f8 100644 --- a/src/instance/models.rs +++ b/src/instance/models.rs @@ -7,7 +7,7 @@ use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use serde_json::Value; -use std::fmt; +use std::{collections::BTreeMap, fmt}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] @@ -31,6 +31,43 @@ impl fmt::Display for ModLoader { } } +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum WindowMode { + #[default] + Windowed, + Fullscreen, +} + +impl WindowMode { + fn is_windowed(&self) -> bool { + *self == Self::Windowed + } +} + +impl fmt::Display for WindowMode { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Windowed => write!(f, "windowed"), + Self::Fullscreen => write!(f, "fullscreen"), + } + } +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct LaunchCommand { + #[serde(default)] + pub enabled: bool, + #[serde(default)] + pub command: String, +} + +impl LaunchCommand { + fn is_default(&self) -> bool { + !self.enabled && self.command.is_empty() + } +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct InstanceConfig { pub name: String, @@ -48,8 +85,20 @@ pub struct InstanceConfig { pub memory_min: Option, #[serde(default)] pub jvm_args: Vec, + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub environment: BTreeMap, + #[serde(default, skip_serializing_if = "WindowMode::is_windowed")] + pub window_mode: WindowMode, #[serde(default)] pub resolution: Option<(u32, u32)>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub preferred_account: Option, + #[serde(default, skip_serializing_if = "LaunchCommand::is_default")] + pub pre_launch_command: LaunchCommand, + #[serde(default, skip_serializing_if = "LaunchCommand::is_default")] + pub post_exit_command: LaunchCommand, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub glfw_path: Option, #[serde(default)] pub config_sync_profile: Option, #[serde(default)] diff --git a/src/instance/tests/content/dependencies.rs b/src/instance/tests/content/dependencies.rs index c6b0bf5..18d9aee 100644 --- a/src/instance/tests/content/dependencies.rs +++ b/src/instance/tests/content/dependencies.rs @@ -244,7 +244,13 @@ fn instance() -> InstanceConfig { memory_max: None, memory_min: None, jvm_args: Vec::new(), + environment: Default::default(), + window_mode: Default::default(), resolution: None, + preferred_account: None, + pre_launch_command: Default::default(), + post_exit_command: Default::default(), + glfw_path: None, config_sync_profile: None, modpack_source: None, } diff --git a/src/instance/tests/content/reconcile.rs b/src/instance/tests/content/reconcile.rs index 5efc68c..a69aeff 100644 --- a/src/instance/tests/content/reconcile.rs +++ b/src/instance/tests/content/reconcile.rs @@ -49,7 +49,13 @@ fn job(name: &str) -> ReconcileJob { memory_max: None, memory_min: None, jvm_args: Vec::new(), + environment: Default::default(), + window_mode: Default::default(), resolution: None, + preferred_account: None, + pre_launch_command: Default::default(), + post_exit_command: Default::default(), + glfw_path: None, config_sync_profile: None, modpack_source: None, }, diff --git a/src/instance/tests/launch/pipeline.rs b/src/instance/tests/launch/pipeline.rs index a4aa5b0..bd86deb 100644 --- a/src/instance/tests/launch/pipeline.rs +++ b/src/instance/tests/launch/pipeline.rs @@ -112,6 +112,122 @@ fn custom_resolution_is_added_once() { assert_eq!(args.iter().filter(|arg| *arg == "--height").count(), 1); } +#[test] +fn fullscreen_is_added_once() { + let mut args = vec!["--username".to_owned(), "Player".to_owned()]; + apply_window_mode(&mut args, WindowMode::Fullscreen); + apply_window_mode(&mut args, WindowMode::Fullscreen); + assert_eq!( + args.iter() + .filter(|argument| *argument == "--fullscreen") + .count(), + 1 + ); + + let mut windowed = vec![ + "--username".to_owned(), + "Player".to_owned(), + "--fullscreen".to_owned(), + ]; + apply_window_mode(&mut windowed, WindowMode::Windowed); + assert_eq!(windowed, ["--username", "Player"]); +} + +#[test] +fn preferred_account_falls_back_to_the_active_account() { + let accounts = vec![ + crate::auth::Account { + uuid: "active".to_owned(), + username: "Active".to_owned(), + account_type: AccountType::Microsoft, + active: true, + refresh_token: None, + cached_mc_token: None, + cached_mc_token_expires_at: None, + }, + crate::auth::Account { + uuid: "preferred".to_owned(), + username: "Preferred".to_owned(), + account_type: AccountType::Offline, + active: false, + refresh_token: None, + cached_mc_token: None, + cached_mc_token_expires_at: None, + }, + ]; + + assert_eq!( + select_launch_account(&accounts, Some("preferred")).map(|account| account.uuid.as_str()), + Some("preferred") + ); + assert_eq!( + select_launch_account(&accounts, Some("removed")).map(|account| account.uuid.as_str()), + Some("active") + ); + assert_eq!( + select_launch_account(&accounts, None).map(|account| account.uuid.as_str()), + Some("active") + ); +} + +#[cfg(unix)] +#[tokio::test] +async fn launch_commands_receive_instance_environment() { + use chrono::Utc; + + let temp = tempfile::tempdir().unwrap(); + let minecraft = temp.path().join("minecraft"); + std::fs::create_dir_all(&minecraft).unwrap(); + let mut config = InstanceConfig { + name: "Hook Test".to_owned(), + game_version: "1.21.1".to_owned(), + loader: ModLoader::Vanilla, + loader_version: None, + created: Utc::now(), + last_played: None, + java_path: None, + memory_max: None, + memory_min: None, + jvm_args: Vec::new(), + environment: Default::default(), + window_mode: Default::default(), + resolution: None, + preferred_account: None, + pre_launch_command: Default::default(), + post_exit_command: Default::default(), + glfw_path: None, + config_sync_profile: None, + modpack_source: None, + }; + config + .environment + .insert("CUSTOM_VALUE".to_owned(), "available".to_owned()); + let invocation = LaunchInvocation { + java: "/usr/bin/java".to_owned(), + jvm_args: vec!["-Xmx2G".to_owned()], + classpath: Vec::new(), + classpath_string: String::new(), + main_class: String::new(), + extra_args: Vec::new(), + game_args: Vec::new(), + environment: config.environment.clone(), + working_dir: minecraft.clone(), + }; + let command = LaunchCommand { + enabled: true, + command: "printf '%s|%s' \"$CUSTOM_VALUE\" \"$INST_NAME\" > hook-result".to_owned(), + }; + + run_launch_command("Pre-launch", &command, &config, &invocation, temp.path()) + .await + .unwrap(); + + assert_eq!( + std::fs::read_to_string(minecraft.join("hook-result")).unwrap(), + "available|Hook Test" + ); +} + // 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 @@ -203,7 +319,13 @@ async fn migrate_legacy_loader_profile_skips_modern_with_inherits_from() { memory_max: None, memory_min: None, jvm_args: Vec::new(), + environment: Default::default(), + window_mode: Default::default(), resolution: None, + preferred_account: None, + pre_launch_command: Default::default(), + post_exit_command: Default::default(), + glfw_path: None, config_sync_profile: None, modpack_source: None, }; @@ -252,7 +374,13 @@ async fn migrate_legacy_loader_profile_skips_fabric() { memory_max: None, memory_min: None, jvm_args: Vec::new(), + environment: Default::default(), + window_mode: Default::default(), resolution: None, + preferred_account: None, + pre_launch_command: Default::default(), + post_exit_command: Default::default(), + glfw_path: None, config_sync_profile: None, modpack_source: None, }; diff --git a/src/instance/tests/manager.rs b/src/instance/tests/manager.rs index c33ab4e..3c786f8 100644 --- a/src/instance/tests/manager.rs +++ b/src/instance/tests/manager.rs @@ -27,7 +27,13 @@ fn dummy_config(name: &str) -> InstanceConfig { memory_max: None, memory_min: None, jvm_args: vec![], + environment: Default::default(), + window_mode: Default::default(), resolution: None, + preferred_account: None, + pre_launch_command: Default::default(), + post_exit_command: Default::default(), + glfw_path: None, config_sync_profile: None, modpack_source: None, } diff --git a/src/instance/tests/models.rs b/src/instance/tests/models.rs index 88eb681..ff5f47f 100644 --- a/src/instance/tests/models.rs +++ b/src/instance/tests/models.rs @@ -16,7 +16,13 @@ fn instance_config_roundtrips_through_json() { memory_max: Some("4G".to_string()), memory_min: Some("512M".to_string()), jvm_args: vec![], + environment: Default::default(), + window_mode: Default::default(), resolution: Some((1920, 1080)), + preferred_account: None, + pre_launch_command: Default::default(), + post_exit_command: Default::default(), + glfw_path: None, config_sync_profile: None, modpack_source: Some(crate::instance::ProviderProject { provider: "modrinth".to_owned(), @@ -47,6 +53,12 @@ fn instance_config_accepts_numeric_memory() { let parsed: InstanceConfig = serde_json::from_str(json).expect("deserialize"); assert_eq!(parsed.memory_max.as_deref(), Some("8G")); assert_eq!(parsed.memory_min.as_deref(), Some("512M")); + assert!(parsed.environment.is_empty()); + assert_eq!(parsed.window_mode, WindowMode::Windowed); + assert_eq!(parsed.preferred_account, None); + assert_eq!(parsed.pre_launch_command, LaunchCommand::default()); + assert_eq!(parsed.post_exit_command, LaunchCommand::default()); + assert_eq!(parsed.glfw_path, None); } #[test] diff --git a/src/storage.rs b/src/storage.rs index 81b42d3..21a398b 100644 --- a/src/storage.rs +++ b/src/storage.rs @@ -104,6 +104,10 @@ impl MetadataPaths { self.cache().join("loaders").join("profiles") } + pub fn java_installations(&self) -> PathBuf { + self.cache().join("java").join("installations.json") + } + pub fn provider_cache(&self, provider: &str) -> PathBuf { self.cache().join("providers").join(provider) } diff --git a/src/tests/storage.rs b/src/tests/storage.rs index ae50dc3..1ae54f3 100644 --- a/src/tests/storage.rs +++ b/src/tests/storage.rs @@ -32,6 +32,10 @@ fn metadata_paths_separate_state_and_cache() { paths.versions(), PathBuf::from("/meta/cache/minecraft/versions") ); + assert_eq!( + paths.java_installations(), + PathBuf::from("/meta/cache/java/installations.json") + ); assert_eq!( paths.migration_journal(), PathBuf::from("/meta/state/migration.json") diff --git a/src/tui/app.rs b/src/tui/app.rs index 3c00e89..20c31b4 100644 --- a/src/tui/app.rs +++ b/src/tui/app.rs @@ -19,6 +19,8 @@ use crate::instance::{InstanceConfig, InstanceManager}; // so the main loop can pick them up without blocking pub(super) static PENDING_INSTANCES: LazyLock>>> = LazyLock::new(|| Arc::new(Mutex::new(Vec::new()))); +pub(super) static FAILED_INSTANCE_SETTINGS_UPDATES: LazyLock>>> = + LazyLock::new(|| Arc::new(Mutex::new(Vec::new()))); pub struct App { pub(super) exit: bool, @@ -43,6 +45,7 @@ pub struct App { pub(super) account_state: widgets::account::AccountState, pub(super) settings_state: widgets::settings::SettingsState, pub(super) instance_settings: Option, + pub(super) pending_instance_settings_updates: HashSet, pub(super) global_settings: Option, pub(super) picker: ratatui_image::picker::Picker, pub(super) instance_manager: InstanceManager, @@ -176,6 +179,7 @@ impl App { account_state: widgets::account::AccountState::default(), settings_state, instance_settings: None, + pending_instance_settings_updates: HashSet::new(), global_settings: None, screenshots_state: { let mut s = widgets::screenshots_grid::ScreenshotsState::default(); diff --git a/src/tui/event.rs b/src/tui/event.rs index 28293f1..ece7018 100644 --- a/src/tui/event.rs +++ b/src/tui/event.rs @@ -10,7 +10,7 @@ use ratatui::{ use std::time::Duration; use super::Tui; -use super::app::{App, FocusedArea, PENDING_INSTANCES}; +use super::app::{App, FAILED_INSTANCE_SETTINGS_UPDATES, FocusedArea, PENDING_INSTANCES}; use super::widgets::{self, popups::import_modpack, popups::new_instance}; use crate::feedback::errors as error_buffer; use crate::feedback::progress; @@ -43,6 +43,7 @@ impl App { // every content type has its own pending queue because they each // get scanned/loaded on separate tokio tasks self.drain_pending_instances(); + self.drain_failed_instance_settings_updates(); self.instances_state.drain_modpack_updates(); self.drain_pending_last_played(); if let Some(state) = self.modpack_versions_state.as_mut() { @@ -628,6 +629,9 @@ impl App { Ok(updated) => updated, Err(error) => { progress::clear(); + if let Ok(mut failed) = FAILED_INSTANCE_SETTINGS_UPDATES.lock() { + failed.push(previous.name.clone()); + } error_buffer::push_error(error_buffer::ErrorEvent { id: 0, level: tracing::Level::ERROR, @@ -878,6 +882,14 @@ impl App { fn drain_pending_instances(&mut self) { if let Ok(mut pending) = PENDING_INSTANCES.lock() { for config in pending.drain(..) { + let settings_update = self.pending_instance_settings_updates.remove(&config.name); + if settings_update + && let Some(state) = self.instance_settings.as_mut() + && state.runtime_update_pending_for(&config.name) + { + let desktop = crate::instance::desktop::exists(&config.name); + state.mark_saved(&config, desktop); + } self.forget_instance_content(&config.name); widgets::instances::spawn_modpack_update_check(&config); if self @@ -895,6 +907,19 @@ impl App { } } + fn drain_failed_instance_settings_updates(&mut self) { + if let Ok(mut failed) = FAILED_INSTANCE_SETTINGS_UPDATES.lock() { + for name in failed.drain(..) { + self.pending_instance_settings_updates.remove(&name); + if let Some(state) = self.instance_settings.as_mut() + && state.runtime_update_pending_for(&name) + { + state.cancel_runtime_change(); + } + } + } + } + pub(super) fn forget_instance_content(&mut self, instance_name: &str) { for state in [ &mut self.mods_state, diff --git a/src/tui/input.rs b/src/tui/input.rs index 027adf3..c1bcca7 100644 --- a/src/tui/input.rs +++ b/src/tui/input.rs @@ -205,7 +205,31 @@ impl App { } Some(confirm_popup::ConfirmTarget::Account { index, .. }) => { let count = self.account_state.store.accounts.len(); + let removed_uuid = self + .account_state + .store + .accounts + .get(index) + .map(|account| account.uuid.clone()); self.account_state.store.remove(index); + if let Some(removed_uuid) = removed_uuid { + for instance in &mut self.instances_state.instances { + if instance.preferred_account.as_deref() + == Some(removed_uuid.as_str()) + { + instance.preferred_account = None; + if let Err(error) = self.instance_manager.save(instance) { + error_buffer::push_message( + tracing::Level::ERROR, + format!( + "Failed to reset preferred account for '{}': {error}", + instance.name + ), + ); + } + } + } + } if count > 1 { self.account_state.list_state.selected = Some(index.min( self.account_state.store.accounts.len().saturating_sub(1), @@ -268,43 +292,51 @@ impl App { .as_mut() .and_then(|state| state.confirmed_save()); if let Some((updated, desktop)) = confirmed { - self.apply_instance_settings(*updated, desktop, true); + self.apply_instance_settings(*updated, desktop); } self.focused } - Some(confirm_popup::ConfirmTarget::JvmArguments { .. }) => { - self.focused = FocusedArea::InstanceSettings; - let confirmed = self.instance_settings.as_mut().and_then(|state| { - state.clear_jvm_args(); - state.confirmed_save() - }); - if let Some((updated, desktop)) = confirmed { - self.apply_instance_settings(*updated, desktop, false); - } - self.focused - } - Some(confirm_popup::ConfirmTarget::JavaAuto { instance, .. }) => { - if instance.is_some() { - self.focused = FocusedArea::InstanceSettings; - let confirmed = self.instance_settings.as_mut().and_then(|state| { - state.enable_auto_java(); - state.confirmed_save() - }); - if let Some((updated, desktop)) = confirmed { - self.apply_instance_settings(*updated, desktop, false); + Some(confirm_popup::ConfirmTarget::AutomaticSelection { + setting, + instance, + .. + }) => { + match setting { + confirm_popup::AutomaticSetting::Java if instance.is_some() => { + self.focused = FocusedArea::InstanceSettings; + let confirmed = + self.instance_settings.as_mut().and_then(|state| { + state.enable_auto_java(); + state.confirmed_save() + }); + if let Some((updated, desktop)) = confirmed { + self.apply_instance_settings(*updated, desktop); + } } - } else { - self.focused = FocusedArea::GlobalSettings; - let action = self.global_settings.as_mut().map( - widgets::popups::global_settings::State::confirm_auto_java, - ); - if let Some(widgets::popups::global_settings::Action::Save( - config, - theme, - border, - )) = action - { - self.apply_global_settings(*config, theme, border); + confirm_popup::AutomaticSetting::Account => { + self.focused = FocusedArea::InstanceSettings; + let confirmed = + self.instance_settings.as_mut().and_then(|state| { + state.enable_auto_account(); + state.confirmed_save() + }); + if let Some((updated, desktop)) = confirmed { + self.apply_instance_settings(*updated, desktop); + } + } + confirm_popup::AutomaticSetting::Java => { + self.focused = FocusedArea::GlobalSettings; + let action = self.global_settings.as_mut().map( + widgets::popups::global_settings::State::confirm_auto_java, + ); + if let Some(widgets::popups::global_settings::Action::Save( + config, + theme, + border, + )) = action + { + self.apply_global_settings(*config, theme, border); + } } } self.focused @@ -331,10 +363,9 @@ impl App { } FocusedArea::InstanceSettings } - Some(confirm_popup::ConfirmTarget::JvmArguments { .. }) => { - FocusedArea::InstanceSettings - } - Some(confirm_popup::ConfirmTarget::JavaAuto { instance, .. }) => { + Some(confirm_popup::ConfirmTarget::AutomaticSelection { + instance, .. + }) => { if instance.is_some() { FocusedArea::InstanceSettings } else { @@ -629,15 +660,7 @@ impl App { self.instances_state.selected_instance(), ) { widgets::settings::SettingsAction::OpenInstance => { - if let Some(instance) = self.instances_state.selected_instance() { - self.pre_overlay_focused = FocusedArea::Settings; - self.instance_settings = - Some(widgets::popups::instance_settings::State::new( - instance, - &self.instance_manager.meta_dir, - )); - self.focused = FocusedArea::InstanceSettings; - } + self.open_instance_settings(FocusedArea::Settings); return Ok(()); } widgets::settings::SettingsAction::OpenGlobal => { @@ -717,11 +740,10 @@ impl App { pushed_at: std::time::Instant::now(), }); } - widgets::popups::global_settings::Action::ConfirmJavaAuto { from, to } => { - confirm_popup::set_pending(confirm_popup::ConfirmTarget::JavaAuto { + widgets::popups::global_settings::Action::ConfirmJavaAuto => { + confirm_popup::set_pending(confirm_popup::ConfirmTarget::AutomaticSelection { + setting: confirm_popup::AutomaticSetting::Java, instance: None, - from, - to, }); self.focused = FocusedArea::ConfirmDelete; } @@ -757,6 +779,9 @@ impl App { pushed_at: std::time::Instant::now(), }); } + widgets::popups::instance_settings::Action::Warning(message) => { + error_buffer::push_message(tracing::Level::WARN, message); + } widgets::popups::instance_settings::Action::Close => { self.instance_settings = None; self.focused = self.pre_overlay_focused; @@ -774,7 +799,7 @@ impl App { self.focused = self.pre_overlay_focused; } widgets::popups::instance_settings::Action::Save(updated, desktop) => { - self.apply_instance_settings(*updated, desktop, false); + self.apply_instance_settings(*updated, desktop); } widgets::popups::instance_settings::Action::ConfirmRuntime { name } => { error_buffer::push_message( @@ -786,15 +811,17 @@ impl App { }); self.focused = FocusedArea::ConfirmDelete; } - widgets::popups::instance_settings::Action::ConfirmClearJvmArgs { name } => { - confirm_popup::set_pending(confirm_popup::ConfirmTarget::JvmArguments { name }); + widgets::popups::instance_settings::Action::ConfirmJavaAuto { name } => { + confirm_popup::set_pending(confirm_popup::ConfirmTarget::AutomaticSelection { + setting: confirm_popup::AutomaticSetting::Java, + instance: Some(name), + }); self.focused = FocusedArea::ConfirmDelete; } - widgets::popups::instance_settings::Action::ConfirmJavaAuto { name, from, to } => { - confirm_popup::set_pending(confirm_popup::ConfirmTarget::JavaAuto { + widgets::popups::instance_settings::Action::ConfirmAccountAuto { name } => { + confirm_popup::set_pending(confirm_popup::ConfirmTarget::AutomaticSelection { + setting: confirm_popup::AutomaticSetting::Account, instance: Some(name), - from, - to, }); self.focused = FocusedArea::ConfirmDelete; } @@ -886,15 +913,7 @@ impl App { 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; - } + self.open_instance_settings(self.focused); } KeyCode::Char('G') => { self.pre_overlay_focused = self.focused; @@ -2096,6 +2115,26 @@ impl App { } } + fn open_instance_settings(&mut self, return_focus: FocusedArea) { + let Some(instance) = self.instances_state.selected_instance().cloned() else { + return; + }; + let mut state = widgets::popups::instance_settings::State::with_accounts( + &instance, + &self.instance_manager.meta_dir, + self.account_state.store.accounts.clone(), + ); + if self + .pending_instance_settings_updates + .contains(&instance.name) + { + state.mark_runtime_update_pending(); + } + self.pre_overlay_focused = return_focus; + self.instance_settings = Some(state); + self.focused = FocusedArea::InstanceSettings; + } + fn apply_global_settings( &mut self, config: crate::config::Config, @@ -2115,7 +2154,6 @@ impl App { &mut self, updated: crate::instance::models::InstanceConfig, desktop: bool, - close: bool, ) { let Some(previous) = self.instances_state.selected_instance().cloned() else { return; @@ -2131,12 +2169,16 @@ impl App { message: "Stop the instance before changing its runtime".to_owned(), pushed_at: std::time::Instant::now(), }); + if let Some(state) = self.instance_settings.as_mut() { + state.cancel_runtime_change(); + } return; } + self.pending_instance_settings_updates + .insert(previous.name.clone()); self.spawn_instance_settings_update(previous, updated, desktop); - if close { - self.instance_settings = None; - self.focused = self.pre_overlay_focused; + if let Some(state) = self.instance_settings.as_mut() { + state.mark_runtime_update_pending(); } return; } @@ -2148,22 +2190,22 @@ impl App { } 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(), - }); - } + let saved_desktop = match shortcut_result { + Ok(()) => desktop, + Err(error) => { + 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(), + }); + crate::instance::desktop::exists(&updated.name) + } + }; self.instances_state .replace_instance(&previous.name, updated.clone()); if let Some(state) = self.instance_settings.as_mut() { - state.mark_saved(&updated, desktop); - } - if close { - self.instance_settings = None; - self.focused = self.pre_overlay_focused; + state.mark_saved(&updated, saved_desktop); } } Err(error) => error_buffer::push_error(error_buffer::ErrorEvent { diff --git a/src/tui/tests/event.rs b/src/tui/tests/event.rs index 12ffa58..de048dd 100644 --- a/src/tui/tests/event.rs +++ b/src/tui/tests/event.rs @@ -57,6 +57,57 @@ fn completed_background_instance_is_drained_into_the_ui() { assert_eq!(ui.app.mods_state.loaded_for.as_deref(), Some("Pending")); } +#[test] +fn runtime_settings_update_keeps_the_editor_open_and_handles_results() { + let mut ui = UiHarness::new(); + ui.add_instance("Runtime Settings"); + ui.key(crossterm::event::KeyCode::Char('E')); + let state = ui.app.instance_settings.as_mut().unwrap(); + state.draft.game_version = "1.21.2".to_owned(); + state.mark_runtime_update_pending(); + ui.app + .pending_instance_settings_updates + .insert("Runtime Settings".to_owned()); + + ui.key(crossterm::event::KeyCode::Esc); + assert!(ui.app.instance_settings.is_none()); + ui.key(crossterm::event::KeyCode::Char('E')); + assert!( + ui.app + .instance_settings + .as_ref() + .unwrap() + .runtime_update_pending_for("Runtime Settings") + ); + + let mut updated = ui.app.instances_state.selected_instance().unwrap().clone(); + updated.game_version = "1.21.2".to_owned(); + PENDING_INSTANCES.lock().unwrap().push(updated); + ui.app.drain_pending_instances(); + + let state = ui.app.instance_settings.as_ref().unwrap(); + assert_eq!(state.draft.game_version, "1.21.2"); + assert!(!state.runtime_update_pending_for("Runtime Settings")); + assert!(ui.app.pending_instance_settings_updates.is_empty()); + + let state = ui.app.instance_settings.as_mut().unwrap(); + state.draft.game_version = "1.21.3".to_owned(); + state.mark_runtime_update_pending(); + ui.app + .pending_instance_settings_updates + .insert("Runtime Settings".to_owned()); + FAILED_INSTANCE_SETTINGS_UPDATES + .lock() + .unwrap() + .push("Runtime Settings".to_owned()); + ui.app.drain_failed_instance_settings_updates(); + + let state = ui.app.instance_settings.as_ref().unwrap(); + assert_eq!(state.draft.game_version, "1.21.2"); + assert!(!state.runtime_update_pending_for("Runtime Settings")); + assert!(ui.app.pending_instance_settings_updates.is_empty()); +} + #[test] fn structural_settings_update_repairs_runtime_before_persisting() { use sha1::{Digest, Sha1}; @@ -115,7 +166,13 @@ fn structural_settings_update_repairs_runtime_before_persisting() { memory_max: None, memory_min: None, jvm_args: Vec::new(), + environment: Default::default(), + window_mode: Default::default(), resolution: None, + preferred_account: None, + pre_launch_command: Default::default(), + post_exit_command: Default::default(), + glfw_path: None, config_sync_profile: None, modpack_source: None, }; @@ -208,7 +265,13 @@ fn failed_structural_settings_update_keeps_previous_config() { memory_max: None, memory_min: None, jvm_args: Vec::new(), + environment: Default::default(), + window_mode: Default::default(), resolution: None, + preferred_account: None, + pre_launch_command: Default::default(), + post_exit_command: Default::default(), + glfw_path: None, config_sync_profile: None, modpack_source: None, }; diff --git a/src/tui/tests/flows.rs b/src/tui/tests/flows.rs index e7704f1..a65c8ea 100644 --- a/src/tui/tests/flows.rs +++ b/src/tui/tests/flows.rs @@ -559,7 +559,13 @@ fn deleting_a_required_library_warns_but_can_continue() { #[test] fn confirmed_account_delete_updates_the_account_panel() { let mut ui = UiHarness::new(); + ui.add_instance("preferred-account-test"); ui.add_account("Player"); + ui.app.instances_state.instances[0].preferred_account = Some("Player".to_owned()); + ui.app + .instance_manager + .save(&ui.app.instances_state.instances[0]) + .unwrap(); ui.app.focused = FocusedArea::Account; ui.key(KeyCode::Char('d')); @@ -568,6 +574,22 @@ fn confirmed_account_delete_updates_the_account_panel() { assert_eq!(ui.app.focused, FocusedArea::Account); assert!(ui.app.account_state.store.accounts.is_empty()); assert_eq!(ui.app.account_state.list_state.selected, None); + assert_eq!( + ui.app + .instances_state + .selected_instance() + .unwrap() + .preferred_account, + None + ); + assert_eq!( + ui.app + .instance_manager + .load_one("preferred-account-test") + .unwrap() + .preferred_account, + None + ); } #[test] @@ -597,7 +619,7 @@ fn settings_panel_routes_legacy_edit_keys_to_tui_popups() { assert!(ui.screen().contains("Fabric")); assert!(ui.screen().contains("Forge")); ui.key(KeyCode::Esc); - for _ in 0..5 { + for _ in 0..6 { ui.key(KeyCode::Down); } ui.key(KeyCode::Enter); @@ -645,7 +667,7 @@ fn runtime_settings_use_the_shared_confirmation_popup() { .draft .game_version = "1.21.2".to_owned(); - for _ in 0..4 { + for _ in 0..5 { ui.key(KeyCode::Char('j')); } ui.key(KeyCode::Char('l')); @@ -682,23 +704,19 @@ fn runtime_settings_use_the_shared_confirmation_popup() { } #[test] -fn clearing_jvm_arguments_requires_confirmation_and_autosaves() { +fn jvm_arguments_use_the_same_editor_controls_as_environment() { let mut ui = UiHarness::new(); ui.add_instance("jvm-clear-test"); ui.key(KeyCode::Char('E')); ui.app.instance_settings.as_mut().unwrap().draft.jvm_args = vec!["-XX:+UseG1GC".to_owned(), "-Xss1M".to_owned()]; - for _ in 0..6 { + for _ in 0..7 { ui.key(KeyCode::Char('j')); } ui.key(KeyCode::Char('d')); - assert_eq!(ui.app.focused, FocusedArea::ConfirmDelete); - assert!(matches!( - confirm::pending_target(), - Some(confirm::ConfirmTarget::JvmArguments { name }) if name == "jvm-clear-test" - )); + assert_eq!(ui.app.focused, FocusedArea::InstanceSettings); assert_eq!( ui.app .instance_settings @@ -709,18 +727,8 @@ fn clearing_jvm_arguments_requires_confirmation_and_autosaves() { .len(), 2 ); - - ui.key(KeyCode::Enter); - - assert_eq!(ui.app.focused, FocusedArea::InstanceSettings); - assert!( - ui.app - .instances_state - .selected_instance() - .unwrap() - .jvm_args - .is_empty() - ); + ui.draw(); + assert!(!ui.screen().contains("[d] clear")); } #[test] @@ -730,7 +738,7 @@ fn enabling_a_different_automatic_java_requires_confirmation() { ui.key(KeyCode::Char('E')); ui.app.instance_settings.as_mut().unwrap().draft.java_path = Some("/custom/java".to_owned()); - for _ in 0..3 { + for _ in 0..4 { ui.key(KeyCode::Char('j')); } ui.key(KeyCode::Char('a')); @@ -738,14 +746,19 @@ fn enabling_a_different_automatic_java_requires_confirmation() { assert_eq!(ui.app.focused, FocusedArea::ConfirmDelete); assert!(matches!( confirm::pending_target(), - Some(confirm::ConfirmTarget::JavaAuto { + Some(confirm::ConfirmTarget::AutomaticSelection { + setting: confirm::AutomaticSetting::Java, instance: Some(name), .. }) if name == "java-auto-test" )); ui.draw(); assert!(ui.screen().contains("Enable automatic Java")); - assert!(ui.screen().contains("Java runtime will change")); + assert!( + ui.screen() + .contains("Use the automatically selected Java runtime") + ); + assert!(!ui.screen().contains("/custom/java")); ui.key(KeyCode::Esc); assert_eq!(ui.app.focused, FocusedArea::InstanceSettings); @@ -774,6 +787,72 @@ fn enabling_a_different_automatic_java_requires_confirmation() { ); } +#[test] +fn enabling_a_different_automatic_account_requires_confirmation() { + let mut ui = UiHarness::new(); + ui.add_instance("account-auto-test"); + ui.add_account("Active"); + ui.app + .account_state + .store + .accounts + .push(crate::auth::Account { + uuid: "preferred".to_owned(), + username: "Preferred".to_owned(), + account_type: crate::auth::AccountType::Microsoft, + active: false, + refresh_token: Some("refresh".to_owned()), + cached_mc_token: None, + cached_mc_token_expires_at: None, + }); + ui.app.instances_state.instances[0].preferred_account = Some("preferred".to_owned()); + ui.app + .instance_manager + .save(&ui.app.instances_state.instances[0]) + .unwrap(); + ui.key(KeyCode::Char('E')); + for _ in 0..3 { + ui.key(KeyCode::Char('j')); + } + + ui.key(KeyCode::Char('a')); + + assert_eq!(ui.app.focused, FocusedArea::ConfirmDelete); + assert!(matches!( + confirm::pending_target(), + Some(confirm::ConfirmTarget::AutomaticSelection { + setting: confirm::AutomaticSetting::Account, + instance: Some(name), + }) if name == "account-auto-test" + )); + ui.draw(); + assert!(ui.screen().contains("Enable automatic account")); + assert!(ui.screen().contains("Use the currently active account")); + assert!(!ui.screen().contains("Preferred → Active")); + + ui.key(KeyCode::Esc); + assert_eq!( + ui.app + .instance_settings + .as_ref() + .unwrap() + .draft + .preferred_account + .as_deref(), + Some("preferred") + ); + ui.key(KeyCode::Char('a')); + ui.key(KeyCode::Enter); + assert_eq!( + ui.app + .instances_state + .selected_instance() + .unwrap() + .preferred_account, + None + ); +} + #[test] fn instance_settings_validation_errors_use_the_toast_buffer() { let mut ui = UiHarness::new(); @@ -796,13 +875,36 @@ fn instance_settings_validation_errors_use_the_toast_buffer() { ); } +#[test] +fn enabling_an_empty_launch_hook_uses_a_warning_toast() { + let mut ui = UiHarness::new(); + ui.add_instance("empty-hook-test"); + ui.key(KeyCode::Char('E')); + for _ in 0..13 { + ui.key(KeyCode::Char('j')); + } + + ui.key(KeyCode::Char(' ')); + + assert!( + crate::feedback::errors::ERROR_EVENTS + .lock() + .unwrap() + .iter() + .any(|event| { + event.level == tracing::Level::WARN + && event.message == "Enter a pre-launch command before enabling it" + }) + ); +} + #[test] fn settings_use_java_memory_and_resolution_controls() { let mut ui = UiHarness::new(); ui.add_instance("controls-test"); ui.key(KeyCode::Char('E')); - for _ in 0..3 { + for _ in 0..4 { ui.key(KeyCode::Char('j')); } ui.key(KeyCode::Enter); @@ -815,6 +917,7 @@ fn settings_use_java_memory_and_resolution_controls() { assert!(!ui.screen().contains("Manual")); ui.key(KeyCode::Esc); + ui.app.instance_settings.as_mut().unwrap().draft.memory_min = Some("512M".to_owned()); ui.key(KeyCode::Char('j')); ui.key(KeyCode::Char('l')); assert_eq!( @@ -837,7 +940,7 @@ fn settings_use_java_memory_and_resolution_controls() { Some("1G") ); - for _ in 0..3 { + for _ in 0..6 { ui.key(KeyCode::Char('j')); } ui.key(KeyCode::Enter); @@ -863,6 +966,58 @@ fn settings_use_java_memory_and_resolution_controls() { ui.key(KeyCode::Esc); } +#[test] +fn instance_launch_options_autosave_through_the_editor() { + let mut ui = UiHarness::new(); + ui.add_instance("launch-options-test"); + ui.add_account("Player"); + ui.key(KeyCode::Char('E')); + + for _ in 0..3 { + ui.key(KeyCode::Char('j')); + } + ui.key(KeyCode::Enter); + ui.key(KeyCode::Enter); + + for _ in 0..5 { + ui.key(KeyCode::Char('j')); + } + ui.key(KeyCode::Enter); + for character in "MESA_LOADER_DRIVER_OVERRIDE=zink".chars() { + ui.key(KeyCode::Char(character)); + } + ui.key(KeyCode::Enter); + + ui.key(KeyCode::Char('j')); + ui.key(KeyCode::Char('j')); + ui.key(KeyCode::Enter); + + ui.key(KeyCode::Char('k')); + ui.draw(); + assert!(ui.screen().contains("Java")); + ui.key(KeyCode::Char('c')); + for character in "/opt/lib/libglfw.so.3".chars() { + ui.key(KeyCode::Char(character)); + } + ui.key(KeyCode::Enter); + + let saved = ui + .app + .instance_manager + .load_one("launch-options-test") + .unwrap(); + assert_eq!( + saved + .environment + .get("MESA_LOADER_DRIVER_OVERRIDE") + .map(String::as_str), + Some("zink") + ); + assert_eq!(saved.window_mode, crate::instance::WindowMode::Fullscreen); + assert_eq!(saved.preferred_account.as_deref(), Some("Player")); + assert_eq!(saved.glfw_path.as_deref(), Some("/opt/lib/libglfw.so.3")); +} + #[test] fn settings_panel_keeps_direct_profile_management() { let mut ui = UiHarness::new(); diff --git a/src/tui/tests/harness.rs b/src/tui/tests/harness.rs index 695cf5a..88f28bd 100644 --- a/src/tui/tests/harness.rs +++ b/src/tui/tests/harness.rs @@ -26,6 +26,10 @@ impl UiHarness { pub fn new() -> Self { let guard = TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner()); widgets::popups::confirm::clear_pending(); + crate::tui::app::FAILED_INSTANCE_SETTINGS_UPDATES + .lock() + .unwrap_or_else(|error| error.into_inner()) + .clear(); widgets::popups::new_instance::reset_for_test(); widgets::popups::import_modpack::reset_for_test(); crate::feedback::errors::ERROR_EVENTS @@ -84,6 +88,7 @@ impl UiHarness { account_state, settings_state: widgets::settings::SettingsState::new(meta_dir), instance_settings: None, + pending_instance_settings_updates: Default::default(), global_settings: None, picker, instance_manager, @@ -129,7 +134,13 @@ impl UiHarness { memory_max: None, memory_min: None, jvm_args: Vec::new(), + environment: Default::default(), + window_mode: Default::default(), resolution: None, + preferred_account: None, + pre_launch_command: Default::default(), + post_exit_command: Default::default(), + glfw_path: None, config_sync_profile: None, modpack_source: None, }; diff --git a/src/tui/tests/widgets/content/discovery.rs b/src/tui/tests/widgets/content/discovery.rs index 3869577..9a8ecb1 100644 --- a/src/tui/tests/widgets/content/discovery.rs +++ b/src/tui/tests/widgets/content/discovery.rs @@ -43,7 +43,13 @@ fn instance(name: &str, version: &str) -> InstanceConfig { memory_max: None, memory_min: None, jvm_args: Vec::new(), + environment: Default::default(), + window_mode: Default::default(), resolution: None, + preferred_account: None, + pre_launch_command: Default::default(), + post_exit_command: Default::default(), + glfw_path: None, config_sync_profile: None, modpack_source: None, } diff --git a/src/tui/tests/widgets/instances.rs b/src/tui/tests/widgets/instances.rs index f680f4d..1f26344 100644 --- a/src/tui/tests/widgets/instances.rs +++ b/src/tui/tests/widgets/instances.rs @@ -47,7 +47,13 @@ fn synthetic_instance(name: &str) -> InstanceConfig { memory_max: None, memory_min: None, jvm_args: vec![], + environment: Default::default(), + window_mode: Default::default(), resolution: None, + preferred_account: None, + pre_launch_command: Default::default(), + post_exit_command: Default::default(), + glfw_path: None, config_sync_profile: None, modpack_source: None, } diff --git a/src/tui/widgets/popups/confirm.rs b/src/tui/widgets/popups/confirm.rs index 68dfc47..854d5f3 100644 --- a/src/tui/widgets/popups/confirm.rs +++ b/src/tui/widgets/popups/confirm.rs @@ -48,23 +48,40 @@ pub enum ConfirmTarget { InstanceRuntime { name: String, }, - JvmArguments { - name: String, - }, - JavaAuto { + AutomaticSelection { + setting: AutomaticSetting, instance: Option, - from: String, - to: String, }, } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AutomaticSetting { + Java, + Account, +} + +impl AutomaticSetting { + fn title(self) -> &'static str { + match self { + Self::Java => " Enable automatic Java ", + Self::Account => " Enable automatic account ", + } + } + + fn description(self) -> &'static str { + match self { + Self::Java => "Use the automatically selected Java runtime", + Self::Account => "Use the currently active account", + } + } +} + impl ConfirmTarget { fn title(&self) -> String { match self { Self::OrphanDependencies { .. } => " Remove unused dependencies ".to_owned(), Self::InstanceRuntime { .. } => " Change runtime ".to_owned(), - Self::JvmArguments { .. } => " Clear JVM arguments ".to_owned(), - Self::JavaAuto { .. } => " Enable automatic Java ".to_owned(), + Self::AutomaticSelection { setting, .. } => setting.title().to_owned(), _ => format!(" Delete '{}' ", self.name()), } } @@ -104,10 +121,7 @@ impl ConfirmTarget { .collect::>() .join("\n"), ConfirmTarget::InstanceRuntime { .. } => "Apply this runtime change".to_owned(), - ConfirmTarget::JvmArguments { .. } => "Remove all JVM arguments".to_owned(), - ConfirmTarget::JavaAuto { from, to, .. } => { - format!("Java runtime will change:\n{from} → {to}") - } + ConfirmTarget::AutomaticSelection { setting, .. } => setting.description().to_owned(), } } @@ -119,8 +133,9 @@ impl ConfirmTarget { ConfirmTarget::Content { name, .. } => name, ConfirmTarget::OrphanDependencies { .. } => "unused dependencies", ConfirmTarget::InstanceRuntime { name, .. } => name, - ConfirmTarget::JvmArguments { name, .. } => name, - ConfirmTarget::JavaAuto { instance, .. } => instance.as_deref().unwrap_or("launcher"), + ConfirmTarget::AutomaticSelection { instance, .. } => { + instance.as_deref().unwrap_or("launcher") + } } } @@ -129,8 +144,7 @@ impl ConfirmTarget { Self::Content { dependents, .. } if !dependents.is_empty() => " delete anyway", Self::OrphanDependencies { .. } => " remove all", Self::InstanceRuntime { .. } => " change", - Self::JvmArguments { .. } => " clear", - Self::JavaAuto { .. } => " enable", + Self::AutomaticSelection { .. } => " enable", _ => " confirm", } } diff --git a/src/tui/widgets/popups/global_settings.rs b/src/tui/widgets/popups/global_settings.rs index f116176..0a16297 100644 --- a/src/tui/widgets/popups/global_settings.rs +++ b/src/tui/widgets/popups/global_settings.rs @@ -11,7 +11,7 @@ use ratatui::{ text::{Line, Span}, widgets::{Block, Borders, Clear, ListItem, Paragraph}, }; -use ratatui_textarea::{CursorMove, TextArea}; +use ratatui_textarea::TextArea; use crate::{ config::{ @@ -20,8 +20,9 @@ use crate::{ }, instance::models::normalize_memory_value, tui::widgets::popups::settings_controls::{ - JavaChoice, JavaPicker, adjust_memory, auto_label, handle_text_area_input, memory_kib, - render_memory_gauge, + JavaChoice, JavaPicker, SettingsPickerAction, adjust_memory, auto_label, + handle_text_area_input, memory_kib, render_memory_gauge, render_settings_picker, + settings_text_area, }, }; @@ -43,7 +44,7 @@ pub enum Action { None, Save(Box, String, BorderStyle), Error(String), - ConfirmJavaAuto { from: String, to: String }, + ConfirmJavaAuto, OpenRaw(std::path::PathBuf), Close, } @@ -56,8 +57,14 @@ impl State { .iter() .position(|candidate| candidate == &theme.theme) .unwrap_or(0); + let config = crate::config::SETTINGS.read().clone(); + let java_cache = crate::storage::MetadataPaths::new(config.paths.resolve_meta_dir()) + .java_installations(); + let mut java_picker = + JavaPicker::with_cache(crate::instance::java::detect_java_path(), Some(java_cache)); + java_picker.open(config.paths.java_path.as_deref()); Self { - config: crate::config::SETTINGS.read().clone(), + config, theme, selected: 0, editing: None, @@ -67,7 +74,7 @@ impl State { theme_picker: false, theme_index, java_picker_open: false, - java_picker: JavaPicker::new(), + java_picker, } } @@ -85,15 +92,14 @@ impl State { fn display_value(&self, field: usize) -> String { match field { 1 => format!("{:?}", self.theme.border_style).to_lowercase(), - 4 if self - .config - .paths - .java_path - .as_deref() - .is_none_or(str::is_empty) => - { - self.java_picker.detected_path().to_owned() - } + 4 => self.java_picker.display_label( + self.config + .paths + .java_path + .as_deref() + .filter(|path| !path.is_empty()) + .unwrap_or_else(|| self.java_picker.detected_path()), + ), _ => self.value(field), } } @@ -107,7 +113,7 @@ impl State { self.error = None; let invalid = |state: &mut Self, message: String| { state.error = Some(message); - state.editing = Some(new_text_area(editor.lines().to_vec())); + state.editing = Some(settings_text_area(editor.lines().to_vec())); }; match self.selected { 2 | 3 if normalize_memory_value(value).is_none() => invalid( @@ -206,8 +212,8 @@ impl State { self.error = None; return Action::None; }; - if let Some((from, to)) = self.java_picker.automatic_change(current) { - return Action::ConfirmJavaAuto { from, to }; + if self.java_picker.automatic_change(current) { + return Action::ConfirmJavaAuto; } self.enable_auto_java(); Action::None @@ -231,16 +237,9 @@ impl State { fn handle_java_picker_key(&mut self, key: &KeyEvent) { self.java_picker.initialize(); - let count = self.java_picker.labels().len(); - match key.code { - KeyCode::Esc | KeyCode::Char('h') | KeyCode::Left => self.java_picker_open = false, - KeyCode::Char('j') | KeyCode::Down if count > 0 => { - self.java_picker.selected = (self.java_picker.selected + 1).min(count - 1); - } - KeyCode::Char('k') | KeyCode::Up => { - self.java_picker.selected = self.java_picker.selected.saturating_sub(1); - } - KeyCode::Enter | KeyCode::Char('l') | KeyCode::Right => { + match self.java_picker.selection_mut().handle_key(key) { + SettingsPickerAction::Back => self.java_picker_open = false, + SettingsPickerAction::Select => { match self.java_picker.selected_choice() { JavaChoice::Installation(path) => { if self.config.paths.java_path.as_deref() != Some(&path) { @@ -251,7 +250,7 @@ impl State { } self.java_picker_open = false; } - _ => {} + SettingsPickerAction::None => {} } } @@ -328,14 +327,14 @@ impl State { 0 => self.theme_picker = true, 1 => self.cycle_border(true), 2 | 3 => { - self.editing = Some(new_text_area(vec![self.value(self.selected)])); + self.editing = Some(settings_text_area(vec![self.value(self.selected)])); } 4 => self.open_java_picker(), - field => self.editing = Some(new_text_area(vec![self.value(field)])), + field => self.editing = Some(settings_text_area(vec![self.value(field)])), }, KeyCode::Char('a') if self.selected == 4 => return self.toggle_auto_java(), KeyCode::Char('c') if self.selected == 4 => { - self.editing = Some(new_text_area(vec![self.value(4)])); + self.editing = Some(settings_text_area(vec![self.value(4)])); } KeyCode::Char('E') => { let file = if self.selected <= 1 { @@ -382,21 +381,6 @@ fn available_themes() -> Vec { 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 popup_rect(area: Rect, state: &State) -> Rect { let height = if state.theme_picker || state.java_picker_open { (area.height * 2 / 3).max(10) @@ -508,12 +492,7 @@ fn render_java_picker(frame: &mut Frame, area: Rect, state: &mut State) { Err(error) => crate::feedback::errors::push_message(tracing::Level::ERROR, error), } } - super::select_list::render_styled( - state.java_picker.items(), - state.java_picker.selected, - list_area, - frame.buffer_mut(), - ); + render_settings_picker(state.java_picker.selection(), list_area, frame.buffer_mut()); } fn render_settings_list(frame: &mut Frame, area: Rect, state: &State) { @@ -667,7 +646,7 @@ mod tests { assert!(matches!( state.handle_key(&KeyEvent::from(KeyCode::Char('a'))), - Action::ConfirmJavaAuto { .. } + Action::ConfirmJavaAuto )); assert_eq!( state.config.paths.java_path.as_deref(), diff --git a/src/tui/widgets/popups/instance_settings.rs b/src/tui/widgets/popups/instance_settings.rs index 2f70925..9b0ab84 100644 --- a/src/tui/widgets/popups/instance_settings.rs +++ b/src/tui/widgets/popups/instance_settings.rs @@ -11,29 +11,40 @@ use ratatui::{ text::{Line, Span}, widgets::{Block, Borders, Clear, ListItem, Paragraph}, }; -use ratatui_textarea::{CursorMove, TextArea}; -use std::sync::{Arc, Mutex}; +use ratatui_textarea::TextArea; +use std::{ + collections::BTreeMap, + sync::{Arc, Mutex}, +}; use crate::{ + auth::{Account, AccountType}, config::{ SETTINGS, theme::{BORDER_STYLE, THEME}, }, instance::loader::GameVersion, - instance::models::{InstanceConfig, ModLoader, normalize_memory_value, parse_resolution}, + instance::models::{ + InstanceConfig, LaunchCommand, ModLoader, WindowMode, normalize_memory_value, + parse_resolution, + }, tui::widgets::{ popups::{ LoadState, settings_controls::{ - DisplayResolution, JavaChoice, JavaPicker, adjust_memory, auto_label, + DisplayResolution, GlfwChoice, GlfwPicker, JavaChoice, JavaPicker, SettingsPicker, + SettingsPickerAction, SettingsPickerBadge, SettingsPickerOption, adjust_memory, + auto_label, bundled_glfw_version, bundled_label as bundled_badge, display_resolutions, handle_text_area_input, memory_kib, render_memory_gauge, + render_settings_picker, settings_text_area, }, }, search::SearchState, }, }; -const FIELD_COUNT: usize = 9; +const FIELD_COUNT: usize = 15; +const FIELD_ORDER: [usize; FIELD_COUNT] = [0, 1, 2, 10, 3, 4, 5, 6, 7, 14, 8, 9, 11, 12, 13]; type SharedLoad = Arc>>; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -47,6 +58,8 @@ enum ChoicePicker { Loader, Java, Resolution, + Account, + Glfw, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -99,36 +112,49 @@ pub struct State { choice_picker: Option, choice_index: usize, java_picker: JavaPicker, + glfw_picker: GlfwPicker, + account_picker: SettingsPicker, + accounts: Vec, + meta_dir: std::path::PathBuf, display_resolutions: Vec, + runtime_update_pending: bool, } pub enum Action { None, Save(Box, bool), Error(String), - ConfirmRuntime { - name: String, - }, - ConfirmClearJvmArgs { - name: String, - }, - ConfirmJavaAuto { - name: String, - from: String, - to: String, - }, + Warning(String), + ConfirmRuntime { name: String }, + ConfirmJavaAuto { name: String }, + ConfirmAccountAuto { name: String }, OpenRaw, Close, } impl State { - pub fn new(instance: &InstanceConfig, _meta_dir: &std::path::Path) -> Self { + pub fn new(instance: &InstanceConfig, meta_dir: &std::path::Path) -> Self { + Self::with_accounts( + instance, + meta_dir, + crate::auth::AccountStore::load().accounts, + ) + } + + pub fn with_accounts( + instance: &InstanceConfig, + meta_dir: &std::path::Path, + accounts: Vec, + ) -> Self { let auto_java_path = SETTINGS .read() .paths .effective_java_path() .map(str::to_owned) .unwrap_or_else(crate::instance::java::detect_java_path); + let java_cache = crate::storage::MetadataPaths::new(meta_dir).java_installations(); + let mut java_picker = JavaPicker::with_cache(auto_java_path, Some(java_cache)); + java_picker.open(instance.java_path.as_deref()); Self { original: instance.clone(), draft: instance.clone(), @@ -146,8 +172,16 @@ impl State { loader_versions: Arc::new(Mutex::new(LoadState::Idle)), choice_picker: None, choice_index: 0, - java_picker: JavaPicker::with_auto_path(auto_java_path), + java_picker, + glfw_picker: GlfwPicker::with_bundled_version(bundled_glfw_version( + meta_dir, + &instance.game_version, + )), + account_picker: SettingsPicker::default(), + accounts, + meta_dir: meta_dir.to_path_buf(), display_resolutions: display_resolutions(), + runtime_update_pending: false, } } @@ -190,6 +224,14 @@ impl State { ) && min > max { self.error = Some("Minimum memory cannot exceed maximum memory.".to_owned()); + } else if self.draft.pre_launch_command.enabled + && self.draft.pre_launch_command.command.trim().is_empty() + { + self.error = Some("Enter a pre-launch command before enabling it.".to_owned()); + } else if self.draft.post_exit_command.enabled + && self.draft.post_exit_command.command.trim().is_empty() + { + self.error = Some("Enter a post-exit command before enabling it.".to_owned()); } self.error.is_none() } @@ -204,11 +246,23 @@ impl State { 5 => self.draft.memory_max.clone().unwrap_or_default(), 6 => self.draft.jvm_args.join(" "), 7 => self + .draft + .environment + .iter() + .map(|(key, value)| format!("{key}={value}")) + .collect::>() + .join(" "), + 8 => self.draft.window_mode.to_string(), + 9 => self .draft .resolution .map(|(w, h)| format!("{w}x{h}")) .unwrap_or_default(), - 8 => if self.desktop { "yes" } else { "no" }.to_owned(), + 10 => self.draft.preferred_account.clone().unwrap_or_default(), + 11 => if self.desktop { "yes" } else { "no" }.to_owned(), + 12 => self.draft.pre_launch_command.command.clone(), + 13 => self.draft.post_exit_command.command.clone(), + 14 => self.draft.glfw_path.clone().unwrap_or_default(), _ => String::new(), } } @@ -216,21 +270,119 @@ impl State { 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() => self.java_picker.detected_path().to_owned(), + 3 => self.java_picker.display_label( + self.draft + .java_path + .as_deref() + .unwrap_or_else(|| self.java_picker.detected_path()), + ), 4 if self.draft.memory_min.is_none() => SETTINGS.read().defaults.memory_min.clone(), 5 if self.draft.memory_max.is_none() => SETTINGS.read().defaults.memory_max.clone(), 6 if self.draft.jvm_args.is_empty() => "no arguments".to_owned(), 6 => self.draft.jvm_args.join(" "), - 7 if self.draft.resolution.is_none() => self.default_resolution().map_or_else( + 7 if self.draft.environment.is_empty() => "no variables".to_owned(), + 7 => self.value(7), + 9 if self.draft.resolution.is_none() => self.default_resolution().map_or_else( || "not detected".to_owned(), |(width, height)| format!("{width}x{height}"), ), - 8 if self.desktop => "enabled".to_owned(), - 8 => "disabled".to_owned(), + 10 => self.preferred_account_label(), + 11 if self.desktop => "enabled".to_owned(), + 11 => "disabled".to_owned(), + 12 if self.draft.pre_launch_command.command.is_empty() => "no command".to_owned(), + 13 if self.draft.post_exit_command.command.is_empty() => "no command".to_owned(), + 14 => self + .glfw_picker + .display_label(self.draft.glfw_path.as_deref()), _ => self.value(field).replace('\n', " ↵ "), } } + fn preferred_account_label(&self) -> String { + if let Some(username) = self + .draft + .preferred_account + .as_deref() + .and_then(|uuid| self.accounts.iter().find(|account| account.uuid == uuid)) + .map(|account| account.username.clone()) + { + return username; + } + self.accounts + .iter() + .find(|account| account.active) + .map(|account| account.username.clone()) + .unwrap_or_else(|| "no active account".to_owned()) + } + + fn account_is_auto(&self) -> bool { + self.draft + .preferred_account + .as_deref() + .is_none_or(|uuid| !self.accounts.iter().any(|account| account.uuid == uuid)) + } + + fn launch_command(&self, field: usize) -> Option<&LaunchCommand> { + match field { + 12 => Some(&self.draft.pre_launch_command), + 13 => Some(&self.draft.post_exit_command), + _ => None, + } + } + + fn launch_command_mut(&mut self, field: usize) -> Option<&mut LaunchCommand> { + match field { + 12 => Some(&mut self.draft.pre_launch_command), + 13 => Some(&mut self.draft.post_exit_command), + _ => None, + } + } + + fn toggle_selected_command(&mut self) -> Action { + let phase = if self.selected == 12 { + "pre-launch" + } else { + "post-exit" + }; + let Some(command) = self.launch_command_mut(self.selected) else { + return Action::None; + }; + if !command.enabled && command.command.trim().is_empty() { + return Action::Warning(format!("Enter a {phase} command before enabling it")); + } + command.enabled = !command.enabled; + Action::None + } + + fn sync_account_picker(&mut self) { + let preferred = self + .draft + .preferred_account + .as_deref() + .filter(|uuid| self.accounts.iter().any(|account| account.uuid == *uuid)) + .or_else(|| { + self.accounts + .iter() + .find(|account| account.active) + .map(|account| account.uuid.as_str()) + }); + let automatic = self.account_is_auto(); + let options = self + .accounts + .iter() + .map(|account| SettingsPickerOption { + key: account.uuid.clone(), + title: account.username.clone(), + detail: (account.account_type == AccountType::Offline) + .then(|| "(Offline)".to_owned()), + leading: Some(if account.active { "▸ " } else { " " }.to_owned()), + active: account.active, + badge: (automatic && account.active).then_some(SettingsPickerBadge::Auto), + }) + .collect(); + self.account_picker.sync(options, preferred); + } + fn begin_edit(&mut self) { match self.selected { 0 => self.open_game_picker(), @@ -241,33 +393,58 @@ impl State { 2 => self.open_loader_picker(), 3 => self.open_choice_picker(ChoicePicker::Java), 4 | 5 => { - self.editing = Some(new_text_area(vec![self.effective_memory(self.selected)])); + self.editing = Some(settings_text_area(vec![ + self.effective_memory(self.selected), + ])); } - 6 => self.editing = Some(new_text_area(vec![self.value(self.selected)])), - 7 => self.open_choice_picker(ChoicePicker::Resolution), - 8 => self.desktop = !self.desktop, - field => self.editing = Some(new_text_area(vec![self.value(field)])), + 6 => self.editing = Some(settings_text_area(vec![self.value(self.selected)])), + 7 => self.editing = Some(settings_text_area(vec![self.value(7)])), + 8 => { + self.draft.window_mode = match self.draft.window_mode { + WindowMode::Windowed => WindowMode::Fullscreen, + WindowMode::Fullscreen => WindowMode::Windowed, + }; + } + 9 => self.open_choice_picker(ChoicePicker::Resolution), + 10 => self.open_choice_picker(ChoicePicker::Account), + 11 => self.desktop = !self.desktop, + 12 | 13 => { + self.editing = Some(settings_text_area(vec![self.value(self.selected)])); + } + 14 => self.open_choice_picker(ChoicePicker::Glfw), + field => self.editing = Some(settings_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 => super::select_list::MOD_LOADERS - .iter() - .position(|loader| *loader == self.draft.loader) - .unwrap_or(0), + match picker { + ChoicePicker::Loader => { + self.choice_index = super::select_list::MOD_LOADERS + .iter() + .position(|loader| *loader == self.draft.loader) + .unwrap_or(0); + } ChoicePicker::Java => { self.java_picker.open(self.draft.java_path.as_deref()); self.java_picker.initialize(); - self.java_picker.selected } - ChoicePicker::Resolution => self - .resolution_choices() - .iter() - .position(|choice| choice.resolution() == self.draft.resolution) - .unwrap_or(0), - }; + ChoicePicker::Resolution => { + self.choice_index = self + .resolution_choices() + .iter() + .position(|choice| choice.resolution() == self.draft.resolution) + .unwrap_or(0); + } + ChoicePicker::Account => { + self.account_picker.reset(); + self.sync_account_picker(); + } + ChoicePicker::Glfw => { + self.glfw_picker.open(self.draft.glfw_path.as_deref()); + self.glfw_picker.initialize(); + } + } } fn choice_values(&self) -> Vec { @@ -287,13 +464,34 @@ impl State { .iter() .map(ResolutionChoice::label) .collect(), + ChoicePicker::Account => self.account_picker.labels(), + ChoicePicker::Glfw => self.glfw_picker.labels(), } } fn handle_choice_key(&mut self, key: &KeyEvent) { - if self.choice_picker == Some(ChoicePicker::Java) { - self.java_picker.initialize(); - self.choice_index = self.java_picker.selected; + let picker_action = match self.choice_picker { + Some(ChoicePicker::Java) => { + self.java_picker.initialize(); + Some(self.java_picker.selection_mut().handle_key(key)) + } + Some(ChoicePicker::Account) => { + self.sync_account_picker(); + Some(self.account_picker.handle_key(key)) + } + Some(ChoicePicker::Glfw) => { + self.glfw_picker.initialize(); + Some(self.glfw_picker.selection_mut().handle_key(key)) + } + _ => None, + }; + if let Some(action) = picker_action { + match action { + SettingsPickerAction::Back => self.choice_picker = None, + SettingsPickerAction::Select => self.apply_choice(), + SettingsPickerAction::None => {} + } + return; } let count = self.choice_values().len(); match key.code { @@ -311,9 +509,6 @@ impl State { KeyCode::Enter | KeyCode::Char('l') | KeyCode::Right => self.apply_choice(), _ => {} } - if self.choice_picker == Some(ChoicePicker::Java) { - self.java_picker.selected = self.choice_index; - } } fn apply_choice(&mut self) { @@ -330,12 +525,9 @@ impl State { open_loader_versions = loader != ModLoader::Vanilla; } } - Some(ChoicePicker::Java) => { - self.java_picker.selected = self.choice_index; - match self.java_picker.selected_choice() { - JavaChoice::Installation(path) => self.draft.java_path = Some(path), - } - } + Some(ChoicePicker::Java) => match self.java_picker.selected_choice() { + JavaChoice::Installation(path) => self.draft.java_path = Some(path), + }, Some(ChoicePicker::Resolution) => { let selected = self .resolution_choices() @@ -346,6 +538,16 @@ impl State { self.draft.resolution = Some(resolution); } } + Some(ChoicePicker::Account) => { + self.draft.preferred_account = + self.account_picker.selected_key().map(str::to_owned); + } + Some(ChoicePicker::Glfw) => { + self.draft.glfw_path = match self.glfw_picker.selected_choice() { + GlfwChoice::Bundled => None, + GlfwChoice::System(path) => Some(path), + }; + } None => {} } self.choice_picker = None; @@ -520,6 +722,19 @@ impl State { self.error = None; } + fn move_selection(&mut self, forward: bool) { + let position = FIELD_ORDER + .iter() + .position(|field| *field == self.selected) + .unwrap_or(0); + let position = if forward { + (position + 1).min(FIELD_ORDER.len() - 1) + } else { + position.saturating_sub(1) + }; + self.selected = FIELD_ORDER[position]; + } + fn resolution_choices(&self) -> Vec { resolution_choices(self.draft.resolution, &self.display_resolutions) } @@ -555,11 +770,9 @@ impl State { self.error = None; return Action::None; }; - if let Some((from, to)) = self.java_picker.automatic_change(current) { + if self.java_picker.automatic_change(current) { return Action::ConfirmJavaAuto { name: self.draft.name.clone(), - from, - to, }; } self.enable_auto_java(); @@ -571,6 +784,40 @@ impl State { self.error = None; } + fn toggle_auto_account(&mut self) -> Action { + if self.account_is_auto() { + if let Some(account) = self.accounts.iter().find(|account| account.active) { + self.draft.preferred_account = Some(account.uuid.clone()); + self.error = None; + } else { + self.error = Some("No active account is available.".to_owned()); + } + return Action::None; + } + let Some(preferred_uuid) = self.draft.preferred_account.as_deref() else { + return Action::None; + }; + let preferred = self + .accounts + .iter() + .find(|account| account.uuid == preferred_uuid); + let active = self.accounts.iter().find(|account| account.active); + if let (Some(preferred), Some(active)) = (preferred, active) + && preferred.uuid != active.uuid + { + return Action::ConfirmAccountAuto { + name: self.draft.name.clone(), + }; + } + self.enable_auto_account(); + Action::None + } + + pub fn enable_auto_account(&mut self) { + self.draft.preferred_account = None; + self.error = None; + } + fn close_version_picker(&mut self) { let cancel_runtime_change = self.picker == Some(VersionPicker::Loader) && self.runtime_changed() @@ -667,7 +914,7 @@ impl State { self.error = None; let invalid = |state: &mut Self, message: String| { state.error = Some(message); - state.editing = Some(new_text_area(editor.lines().to_vec())); + state.editing = Some(settings_text_area(editor.lines().to_vec())); }; match self.selected { 0 if value.is_empty() => invalid(self, "Game version is required.".to_owned()), @@ -683,16 +930,36 @@ impl State { 6 => { self.draft.jvm_args = value.split_whitespace().map(str::to_owned).collect(); } - 7 if value.is_empty() => self.draft.resolution = None, - 7 => match parse_resolution(value) { + 7 => match parse_environment(value) { + Ok(environment) => self.draft.environment = environment, + Err(error) => invalid(self, error), + }, + 9 if value.is_empty() => self.draft.resolution = None, + 9 => match parse_resolution(value) { Ok(resolution) => self.draft.resolution = Some(resolution), Err(error) => invalid(self, error), }, + 12 | 13 => { + if let Some(command) = self.launch_command_mut(self.selected) { + command.command = value.to_owned(); + if value.is_empty() { + command.enabled = false; + } + } + } + 14 => self.draft.glfw_path = (!value.is_empty()).then(|| value.to_owned()), _ => {} } } pub fn handle_key(&mut self, key: &KeyEvent) -> Action { + if self.runtime_update_pending { + return if key.code == KeyCode::Esc { + Action::Close + } else { + Action::None + }; + } let before = self.draft.clone(); let desktop_before = self.desktop; let action = self.handle_key_inner(key); @@ -756,10 +1023,8 @@ impl State { } 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::Char('j') | KeyCode::Down => self.move_selection(true), + KeyCode::Char('k') | KeyCode::Up => self.move_selection(false), KeyCode::Char('h') | KeyCode::Left if matches!(self.selected, 4 | 5) => { self.adjust_selected_memory(false); } @@ -770,18 +1035,20 @@ impl State { KeyCode::Char('d') if matches!(self.selected, 4 | 5) => { self.apply_default_memory(); } - KeyCode::Char('d') if self.selected == 7 => self.apply_default_resolution(), - KeyCode::Char('d') if self.selected == 6 && !self.draft.jvm_args.is_empty() => { - return Action::ConfirmClearJvmArgs { - name: self.draft.name.clone(), - }; - } - KeyCode::Char('c') if self.selected == 7 => { - self.editing = Some(new_text_area(vec![self.value(7)])); + KeyCode::Char('d') if self.selected == 9 => self.apply_default_resolution(), + KeyCode::Char('c') if self.selected == 9 => { + self.editing = Some(settings_text_area(vec![self.value(9)])); } KeyCode::Char('a') if self.selected == 3 => return self.toggle_auto_java(), KeyCode::Char('c') if self.selected == 3 => { - self.editing = Some(new_text_area(vec![self.value(3)])); + self.editing = Some(settings_text_area(vec![self.value(3)])); + } + KeyCode::Char('a') if self.selected == 10 => return self.toggle_auto_account(), + KeyCode::Char(' ') if matches!(self.selected, 12 | 13) => { + return self.toggle_selected_command(); + } + KeyCode::Char('c') if self.selected == 14 => { + self.editing = Some(settings_text_area(vec![self.value(14)])); } KeyCode::Char('E') => return Action::OpenRaw, KeyCode::Esc => return Action::Close, @@ -795,9 +1062,12 @@ impl State { .then(|| (Box::new(self.draft.clone()), self.desktop)) } - pub fn clear_jvm_args(&mut self) { - self.draft.jvm_args.clear(); - self.error = None; + pub fn mark_runtime_update_pending(&mut self) { + self.runtime_update_pending = true; + } + + pub fn runtime_update_pending_for(&self, name: &str) -> bool { + self.runtime_update_pending && self.draft.name == name } pub fn mark_saved(&mut self, saved: &InstanceConfig, desktop: bool) { @@ -805,6 +1075,9 @@ impl State { self.draft = saved.clone(); self.original_desktop = desktop; self.desktop = desktop; + self.glfw_picker + .set_bundled_version(bundled_glfw_version(&self.meta_dir, &saved.game_version)); + self.runtime_update_pending = false; self.error = None; } @@ -815,6 +1088,7 @@ impl State { self.game_versions = Arc::new(Mutex::new(LoadState::Idle)); self.loader_versions = Arc::new(Mutex::new(LoadState::Idle)); self.picker_initialized = false; + self.runtime_update_pending = false; self.error = None; } } @@ -850,34 +1124,46 @@ fn resolution_choices( choices } -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 +fn parse_environment(value: &str) -> Result, String> { + let mut environment = BTreeMap::new(); + for assignment in value.split_whitespace() { + let Some((key, value)) = assignment.split_once('=') else { + return Err(format!( + "Environment variable '{assignment}' must use KEY=value." + )); + }; + if key.is_empty() || key.contains('\0') || value.contains('\0') { + return Err("Environment variable names cannot be empty.".to_owned()); + } + if environment + .insert(key.to_owned(), value.to_owned()) + .is_some() + { + return Err(format!("Environment variable '{key}' is repeated.")); + } + } + Ok(environment) } pub fn popup_rect(area: Rect, state: &State) -> Rect { - let height = if state.picker.is_some() || state.choice_picker == Some(ChoicePicker::Java) { + let height = if state.picker.is_some() + || matches!( + state.choice_picker, + Some(ChoicePicker::Java | ChoicePicker::Glfw) + ) { (area.height * 2 / 3).max(10) } else if state.choice_picker.is_some() { 10 } else { - let form_width = (area.width * 58 / 100).saturating_sub(2); - 11 + jvm_row_count(state, form_width).saturating_sub(1) as u16 + let form_width = (area.width * 68 / 100).saturating_sub(2); + 24 + tagged_row_count(&state.draft.jvm_args, form_width).saturating_sub(1) as u16 + + tagged_row_count(&environment_labels(&state.draft.environment), form_width) + .saturating_sub(1) as u16 }; let width = match state.choice_picker { - Some(ChoicePicker::Java) => 72, + Some(ChoicePicker::Java | ChoicePicker::Glfw) => 72, Some(ChoicePicker::Resolution) => 64, - _ => 58, + _ => 68, }; area.centered( Constraint::Percentage(width), @@ -888,7 +1174,12 @@ pub fn popup_rect(area: Rect, state: &State) -> Rect { pub fn render(frame: &mut Frame, area: Rect, state: &mut State) { if state.choice_picker == Some(ChoicePicker::Java) { state.java_picker.initialize(); - state.choice_index = state.java_picker.selected; + } + if state.choice_picker == Some(ChoicePicker::Account) { + state.sync_account_picker(); + } + if state.choice_picker == Some(ChoicePicker::Glfw) { + state.glfw_picker.initialize(); } let theme = THEME.as_ref(); frame.render_widget(Clear, area); @@ -898,6 +1189,8 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut State) { (_, Some(ChoicePicker::Loader)) => " Mod Loader ", (_, Some(ChoicePicker::Java)) => " Java Runtime ", (_, Some(ChoicePicker::Resolution)) => " Resolution ", + (_, Some(ChoicePicker::Account)) => " Preferred Account ", + (_, Some(ChoicePicker::Glfw)) => " GLFW Library ", _ => " Instance Settings ", }; let keybinds = if state.editing.is_some() { @@ -911,7 +1204,10 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut State) { ]) } else if state.picker.is_some() { super::keybind_line(&[("/", " search"), ("h", " back"), ("Enter", " select")]) - } else if state.choice_picker == Some(ChoicePicker::Java) { + } else if matches!( + state.choice_picker, + Some(ChoicePicker::Java | ChoicePicker::Account | ChoicePicker::Glfw) + ) { super::keybind_line(&[("h", " back"), ("Enter", " select")]) } else if state.choice_picker == Some(ChoicePicker::Resolution) { super::keybind_line(&[("d", " default"), ("h", " back"), ("Enter", " select")]) @@ -931,18 +1227,18 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut State) { ("c", " custom"), ("Esc", " back"), ]) - } else if state.selected == 7 { + } else if state.selected == 9 { super::keybind_line(&[ ("Enter", " presets"), ("c", " custom"), ("d", " default"), ("Esc", " back"), ]) - } else if state.selected == 6 { + } else if state.selected == 10 { super::keybind_line(&[ - ("j/k", ""), - ("Enter", " edit"), - ("d", " clear"), + ("Enter", " accounts"), + ("a", " auto"), + ("E", " raw"), ("Esc", " back"), ]) } else if matches!(state.selected, 0..=2) { @@ -952,13 +1248,30 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut State) { ("E", " raw"), ("Esc", " back"), ]) - } else if state.selected == 8 { + } else if matches!(state.selected, 8 | 11) { super::keybind_line(&[ ("j/k", ""), ("Enter", " toggle"), ("E", " raw"), ("Esc", " back"), ]) + } else if matches!(state.selected, 12 | 13) { + let enabled = state + .launch_command(state.selected) + .is_some_and(|command| command.enabled); + super::keybind_line(&[ + ("Enter", " command"), + ("Space", if enabled { " disable" } else { " enable" }), + ("E", " raw"), + ("Esc", " back"), + ]) + } else if state.selected == 14 { + super::keybind_line(&[ + ("Enter", " libraries"), + ("c", " custom"), + ("E", " raw"), + ("Esc", " back"), + ]) } else { super::keybind_line(&[ ("j/k", ""), @@ -996,28 +1309,86 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut State) { fn render_settings_list(frame: &mut Frame, area: Rect, state: &State) { let theme = THEME.as_ref(); - let labels = [ - "Game version", - "Loader", - "Loader version", - "Java", - "Memory min", - "Memory max", - "JVM args", - "Resolution", - "Desktop shortcut", + let sections: [(&str, &[usize]); 4] = [ + ("Game", &[0, 1, 2, 10]), + ("Java", &[3, 4, 5, 6, 7, 14]), + ("Window", &[8, 9, 11]), + ("Commands", &[12, 13]), ]; - let mut y = area.y; - for (index, label) in labels.iter().enumerate() { - let lines = if index == 6 { - jvm_field_lines(state, area.width) - } else { - vec![field_line(state, index, label)] - }; + let mut rows: Vec<(Option, Vec>)> = Vec::new(); + for (section_index, (title, fields)) in sections.iter().enumerate() { + if section_index > 0 { + rows.push((None, vec![Line::default()])); + } + rows.push((None, vec![section_line(title)])); + for index in *fields { + let label = field_label(*index); + let lines = match index { + 6 => tagged_field_lines( + state, + 6, + label, + &state.draft.jvm_args, + "no arguments", + area.width, + ), + 7 => tagged_field_lines( + state, + 7, + label, + &environment_labels(&state.draft.environment), + "no variables", + area.width, + ), + 12 | 13 => command_field_lines(state, *index, label), + _ => vec![field_line(state, *index, label)], + }; + rows.push((Some(*index), lines)); + } + } + + let mut selected_end = 0u16; + let mut cursor = 0u16; + for (field, lines) in &rows { let height = lines.len() as u16; - let row_area = Rect { y, height, ..area }; + if *field == Some(state.selected) { + selected_end = cursor.saturating_add(height); + } + cursor = cursor.saturating_add(height); + } + let scroll = if selected_end > area.height { + selected_end.saturating_sub(area.height) + } else { + 0 + }; + + let mut row_start = 0u16; + for (field, lines) in rows { + let height = lines.len() as u16; + let row_end = row_start.saturating_add(height); + if row_end <= scroll || row_start >= scroll.saturating_add(area.height) { + row_start = row_end; + continue; + } + let skip = scroll.saturating_sub(row_start) as usize; + let y = area.y.saturating_add(row_start.saturating_sub(scroll)); + let visible_height = (height.saturating_sub(skip as u16)) + .min(area.y.saturating_add(area.height).saturating_sub(y)); + let row_area = Rect { + y, + height: visible_height, + ..area + }; + let selected = field == Some(state.selected); frame.render_widget( - Paragraph::new(lines).style(Style::default().bg(if state.selected == index { + Paragraph::new( + lines + .into_iter() + .skip(skip) + .take(visible_height as usize) + .collect::>(), + ) + .style(Style::default().bg(if selected { theme.stripe() } else { theme.surface() @@ -1025,13 +1396,15 @@ fn render_settings_list(frame: &mut Frame, area: Rect, state: &State) { row_area, ); - if matches!(index, 4 | 5) { + if let Some(index @ (4 | 5)) = field + && row_start >= scroll + { let value = state.effective_memory(index); render_memory_gauge( frame, Rect { x: area.x.saturating_add(20), - y, + y: area.y.saturating_add(row_start.saturating_sub(scroll)), width: area.width.saturating_sub(21), height: 1, }, @@ -1040,28 +1413,67 @@ fn render_settings_list(frame: &mut Frame, area: Rect, state: &State) { state.selected == index, ); } - if state.selected == index + if field == Some(state.selected) + && row_start >= scroll && let Some(editor) = state.editing.as_ref() { + let (edit_x, edit_offset) = if matches!(field, Some(12 | 13)) { + (22, 0) + } else { + (20, 0) + }; frame.render_widget( editor, Rect { - x: area.x.saturating_add(20), - y, - width: area.width.saturating_sub(20), + x: area.x.saturating_add(edit_x), + y: area + .y + .saturating_add(row_start.saturating_sub(scroll)) + .saturating_add(edit_offset), + width: area.width.saturating_sub(edit_x), height: 1, }, ); } - y = y.saturating_add(height); + row_start = row_end; } } +fn field_label(index: usize) -> &'static str { + match index { + 0 => "Game version", + 1 => "Loader", + 2 => "Loader version", + 3 => "Java runtime", + 4 => "Memory min", + 5 => "Memory max", + 6 => "JVM args", + 7 => "Environment", + 8 => "Window mode", + 9 => "Resolution", + 10 => "Preferred account", + 11 => "Desktop shortcut", + 12 => "Pre-launch", + 13 => "Post-exit", + 14 => "GLFW", + _ => "", + } +} + +fn section_line(title: &str) -> Line<'static> { + Line::from(Span::styled( + format!(" {title}"), + Style::default() + .fg(THEME.as_ref().text()) + .add_modifier(Modifier::BOLD), + )) +} + fn field_line(state: &State, index: usize, label: &str) -> Line<'static> { let theme = THEME.as_ref(); let selected = index == state.selected; let editing = selected && state.editing.is_some(); - let value = if editing || matches!(index, 4..=6) { + let value = if editing || matches!(index, 4..=7) { String::new() } else { state.display_value(index) @@ -1078,7 +1490,7 @@ fn field_line(state: &State, index: usize, label: &str) -> Line<'static> { Span::styled( value, Style::default() - .fg(if index == 8 { + .fg(if index == 11 { if state.desktop { theme.text() } else { @@ -1099,19 +1511,91 @@ fn field_line(state: &State, index: usize, label: &str) -> Line<'static> { if index == 3 && state.draft.java_path.is_none() && !editing { spans.extend([Span::raw(" "), auto_label()]); } + if index == 10 && state.account_is_auto() { + spans.extend([Span::raw(" "), auto_label()]); + } + if index == 14 && state.draft.glfw_path.is_none() && !editing { + spans.extend([Span::raw(" "), bundled_badge()]); + } Line::from(spans) } -fn jvm_field_lines(state: &State, width: u16) -> Vec> { +fn command_field_lines(state: &State, index: usize, label: &str) -> Vec> { let theme = THEME.as_ref(); - let selected = state.selected == 6; - let mut prefix = field_line(state, 6, "JVM args").spans; + let selected = state.selected == index; + let enabled = state + .launch_command(index) + .is_some_and(|command| command.enabled); + let label_style = Style::default() + .fg(if selected { + theme.accent() + } else { + theme.text() + }) + .add_modifier(if selected { + Modifier::BOLD + } else { + Modifier::empty() + }); + let checkbox_style = Style::default() + .fg(if enabled { + theme.success() + } else { + theme.text_dim() + }) + .add_modifier(if enabled { + Modifier::BOLD + } else { + Modifier::empty() + }); + let mut spans = vec![ + Span::styled( + if selected { "▌ " } else { " " }, + Style::default().fg(theme.accent()), + ), + Span::styled(if enabled { "[✓] " } else { "[ ] " }, checkbox_style), + Span::styled(format!("{label:<16}"), label_style), + ]; + if selected && state.editing.is_some() { + return vec![Line::from(spans)]; + } + let command = state.display_value(index); + spans.push(Span::styled( + command, + Style::default() + .fg(if !enabled || state.value(index).is_empty() { + theme.text_dim() + } else if selected { + theme.accent() + } else { + theme.text() + }) + .add_modifier(if selected && !state.value(index).is_empty() { + Modifier::BOLD + } else { + Modifier::empty() + }), + )); + vec![Line::from(spans)] +} + +fn tagged_field_lines( + state: &State, + index: usize, + label: &str, + values: &[String], + empty: &str, + width: u16, +) -> Vec> { + let theme = THEME.as_ref(); + let selected = state.selected == index; + let mut prefix = field_line(state, index, label).spans; if selected && state.editing.is_some() { return vec![Line::from(prefix)]; } - if state.draft.jvm_args.is_empty() { + if values.is_empty() { prefix.push(Span::styled( - "no arguments", + empty.to_owned(), Style::default().fg(theme.text_dim()), )); return vec![Line::from(prefix)]; @@ -1121,7 +1605,7 @@ fn jvm_field_lines(state: &State, width: u16) -> Vec> { let mut lines = Vec::new(); let mut spans = prefix; let mut used = 0usize; - for argument in &state.draft.jvm_args { + for argument in values { let badge_width = argument.chars().count() + 2; let separator = usize::from(used > 0); if used > 0 && used + separator + badge_width > available { @@ -1150,14 +1634,14 @@ fn jvm_field_lines(state: &State, width: u16) -> Vec> { lines } -fn jvm_row_count(state: &State, width: u16) -> usize { - if state.draft.jvm_args.is_empty() || state.selected == 6 && state.editing.is_some() { +fn tagged_row_count(values: &[String], width: u16) -> usize { + if values.is_empty() { return 1; } let available = width.saturating_sub(20) as usize; let mut rows = 1; let mut used = 0usize; - for argument in &state.draft.jvm_args { + for argument in values { let badge_width = argument.chars().count() + 2; let separator = usize::from(used > 0); if used > 0 && used + separator + badge_width > available { @@ -1169,6 +1653,13 @@ fn jvm_row_count(state: &State, width: u16) -> usize { rows } +fn environment_labels(environment: &BTreeMap) -> Vec { + environment + .iter() + .map(|(key, value)| format!("{key}={value}")) + .collect() +} + fn render_choice_picker(frame: &mut Frame, area: Rect, state: &mut State) { let theme = THEME.as_ref(); let mut list_area = area; @@ -1187,11 +1678,28 @@ fn render_choice_picker(frame: &mut Frame, area: Rect, state: &mut State) { Err(error) => crate::feedback::errors::push_message(tracing::Level::ERROR, error), } } + if state.choice_picker == Some(ChoicePicker::Glfw) + && let Some(status) = state.glfw_picker.take_status() + { + frame.render_widget( + Paragraph::new(status).style(Style::default().fg(theme.text_dim())), + Rect { height: 1, ..area }, + ); + list_area.y = list_area.y.saturating_add(1); + list_area.height = list_area.height.saturating_sub(1); + } + if state.choice_picker == Some(ChoicePicker::Account) && state.accounts.is_empty() { + frame.render_widget( + Paragraph::new("No accounts.").style(Style::default().fg(theme.text_dim())), + list_area, + ); + return; + } let items = match state.choice_picker { - Some(ChoicePicker::Java) => state.java_picker.items(), Some(ChoicePicker::Resolution) => { resolution_items(&state.resolution_choices(), state.choice_index) } + Some(ChoicePicker::Java | ChoicePicker::Account | ChoicePicker::Glfw) => Vec::new(), _ => state .choice_values() .iter() @@ -1203,10 +1711,15 @@ fn render_choice_picker(frame: &mut Frame, area: Rect, state: &mut State) { }) .collect(), }; - if matches!( - state.choice_picker, - Some(ChoicePicker::Java | ChoicePicker::Resolution) - ) { + let settings_picker = match state.choice_picker { + Some(ChoicePicker::Java) => Some(state.java_picker.selection()), + Some(ChoicePicker::Account) => Some(&state.account_picker), + Some(ChoicePicker::Glfw) => Some(state.glfw_picker.selection()), + _ => None, + }; + if let Some(picker) = settings_picker { + render_settings_picker(picker, list_area, frame.buffer_mut()); + } else if state.choice_picker == Some(ChoicePicker::Resolution) { super::select_list::render_styled(items, state.choice_index, list_area, frame.buffer_mut()); } else { super::select_list::render(items, state.choice_index, list_area, frame.buffer_mut()); @@ -1346,7 +1859,13 @@ mod tests { memory_max: None, memory_min: None, jvm_args: Vec::new(), + environment: Default::default(), + window_mode: Default::default(), resolution: None, + preferred_account: None, + pre_launch_command: Default::default(), + post_exit_command: Default::default(), + glfw_path: None, config_sync_profile: None, modpack_source: None, } @@ -1357,12 +1876,12 @@ mod tests { 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.editing = Some(settings_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.selected = 9; + state.editing = Some(settings_text_area(vec!["1920X1080".to_owned()])); state.commit_edit(); assert_eq!(state.draft.resolution, Some((1920, 1080))); } @@ -1435,7 +1954,7 @@ mod tests { let mut config = instance(); config.config_sync_profile = Some("shared".to_owned()); let mut state = State::new(&config, temp.path()); - state.selected = 8; + state.selected = 11; let Action::Save(config, _) = state.handle_key(&KeyEvent::from(KeyCode::Enter)) else { panic!("expected settings save"); @@ -1509,7 +2028,7 @@ mod tests { assert_eq!(state.picker, Some(VersionPicker::Loader)); state.picker = None; - state.selected = 8; + state.selected = 11; let desktop = state.desktop; state.handle_key(&KeyEvent::from(KeyCode::Enter)); assert_ne!(state.desktop, desktop); @@ -1539,7 +2058,7 @@ mod tests { let temp = tempfile::tempdir().unwrap(); let mut state = State::new(&instance(), temp.path()); - state.selected = 7; + state.selected = 9; state.begin_edit(); assert!(state.editing.is_none()); assert_eq!(state.choice_picker, Some(ChoicePicker::Resolution)); @@ -1593,7 +2112,7 @@ mod tests { )); assert_eq!(state.draft.java_path, None); - state.selected = 7; + state.selected = 9; state.display_resolutions = vec![DisplayResolution { width: 2560, height: 1440, @@ -1640,7 +2159,7 @@ mod tests { assert_eq!(state.draft.memory_min.as_deref(), Some("6G")); assert_eq!(state.draft.memory_max.as_deref(), Some("6G")); - let desktop = state.display_value(8); + let desktop = state.display_value(11); assert!(matches!(desktop.as_str(), "enabled" | "disabled")); assert!(!desktop.contains('●') && !desktop.contains('○')); } @@ -1677,7 +2196,7 @@ mod tests { primary: true, }]; - assert_eq!(state.display_value(7), "2560x1440"); + assert_eq!(state.display_value(9), "2560x1440"); } #[test] @@ -1736,10 +2255,152 @@ mod tests { .collect(); let state = State::new(&config, temp.path()); - let lines = jvm_field_lines(&state, 48); + let lines = tagged_field_lines( + &state, + 6, + "JVM args", + &state.draft.jvm_args, + "no arguments", + 48, + ); assert!(lines.len() > 1); - assert_eq!(jvm_row_count(&state, 48), lines.len()); + assert_eq!(tagged_row_count(&state.draft.jvm_args, 48), lines.len()); assert!(lines.iter().any(|line| line.to_string().contains("second"))); } + + #[test] + fn environment_variables_are_parsed_and_validated() { + assert_eq!( + parse_environment("MESA_LOADER_DRIVER_OVERRIDE=zink FOO=bar=baz") + .unwrap() + .get("FOO") + .map(String::as_str), + Some("bar=baz") + ); + assert!(parse_environment("MISSING_VALUE").is_err()); + assert!(parse_environment("FOO=one FOO=two").is_err()); + } + + #[test] + fn window_mode_and_commands_autosave() { + let temp = tempfile::tempdir().unwrap(); + let mut state = State::new(&instance(), temp.path()); + state.selected = 8; + assert!(matches!( + state.handle_key(&KeyEvent::from(KeyCode::Enter)), + Action::Save(..) + )); + assert_eq!(state.draft.window_mode, WindowMode::Fullscreen); + + let saved = state.draft.clone(); + state.mark_saved(&saved, state.desktop); + state.selected = 12; + state.editing = Some(settings_text_area(vec!["echo ready".to_owned()])); + assert!(matches!( + state.handle_key(&KeyEvent::from(KeyCode::Enter)), + Action::Save(..) + )); + let saved = state.draft.clone(); + state.mark_saved(&saved, state.desktop); + assert!(matches!( + state.handle_key(&KeyEvent::from(KeyCode::Char(' '))), + Action::Save(..) + )); + assert!(state.draft.pre_launch_command.enabled); + + let saved = state.draft.clone(); + state.mark_saved(&saved, state.desktop); + state.editing = Some(settings_text_area(vec![String::new()])); + assert!(matches!( + state.handle_key(&KeyEvent::from(KeyCode::Enter)), + Action::Save(..) + )); + assert!(state.draft.pre_launch_command.command.is_empty()); + assert!(!state.draft.pre_launch_command.enabled); + } + + #[test] + fn preferred_account_picker_uses_accounts_and_main_row_auto() { + let temp = tempfile::tempdir().unwrap(); + let accounts = vec![Account { + uuid: "account-id".to_owned(), + username: "Player".to_owned(), + account_type: AccountType::Microsoft, + active: true, + refresh_token: None, + cached_mc_token: None, + cached_mc_token_expires_at: None, + }]; + let mut state = State::with_accounts(&instance(), temp.path(), accounts); + state.selected = 10; + state.begin_edit(); + assert_eq!(state.choice_index, 0); + assert!( + !state + .choice_values() + .iter() + .any(|value| value == "Current active account") + ); + state.handle_choice_key(&KeyEvent::from(KeyCode::Enter)); + assert_eq!(state.draft.preferred_account.as_deref(), Some("account-id")); + + state.toggle_auto_account(); + assert_eq!(state.draft.preferred_account, None); + + state.draft.preferred_account = Some("removed-account".to_owned()); + state.toggle_auto_account(); + assert_eq!(state.draft.preferred_account.as_deref(), Some("account-id")); + } + + #[test] + fn command_control_uses_one_compact_checkbox_row() { + assert_eq!(section_line("Commands").to_string(), " Commands"); + let temp = tempfile::tempdir().unwrap(); + let mut state = State::new(&instance(), temp.path()); + state.selected = 12; + + let lines = command_field_lines(&state, 12, "Pre-launch"); + assert_eq!(lines.len(), 1); + assert_eq!( + lines[0].to_string().trim(), + "▌ [ ] Pre-launch no command" + ); + assert!(!lines[0].to_string().contains("disabled")); + + state.draft.pre_launch_command.command = "echo ready".to_owned(); + state.draft.pre_launch_command.enabled = true; + let enabled = command_field_lines(&state, 12, "Pre-launch"); + assert!(enabled[0].to_string().contains("[✓] Pre-launch")); + assert!(enabled[0].to_string().ends_with("echo ready")); + } + + #[test] + fn java_and_custom_glfw_values_include_their_titles() { + let temp = tempfile::tempdir().unwrap(); + let mut state = State::new(&instance(), temp.path()); + state.draft.java_path = Some("/custom/java".to_owned()); + state.draft.glfw_path = Some("/usr/lib/libglfw.so.3.5".to_owned()); + + assert_eq!(state.display_value(3), "Java /custom/java"); + assert_eq!(state.display_value(14), "GLFW 3.5 /usr/lib/libglfw.so.3.5"); + } + + #[test] + fn glfw_picker_offers_bundled_and_custom_modes() { + let temp = tempfile::tempdir().unwrap(); + let mut state = State::new(&instance(), temp.path()); + state.selected = 14; + state.begin_edit(); + assert_eq!(state.choice_picker, Some(ChoicePicker::Glfw)); + assert!( + state + .choice_values() + .iter() + .any(|value| value.contains("GLFW")) + ); + state.handle_choice_key(&KeyEvent::from(KeyCode::Esc)); + state.handle_key(&KeyEvent::from(KeyCode::Char('c'))); + assert!(state.editing.is_some()); + } } diff --git a/src/tui/widgets/popups/settings_controls.rs b/src/tui/widgets/popups/settings_controls.rs index 37e291b..5450517 100644 --- a/src/tui/widgets/popups/settings_controls.rs +++ b/src/tui/widgets/popups/settings_controls.rs @@ -3,7 +3,11 @@ // Reusable interactive controls shared by instance and launcher settings. -use std::sync::{Arc, Mutex}; +use std::{ + collections::BTreeSet, + path::{Path, PathBuf}, + sync::{Arc, Mutex}, +}; use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; use ratatui::{ @@ -13,7 +17,7 @@ use ratatui::{ text::{Line, Span}, widgets::{LineGauge, ListItem, Paragraph}, }; -use ratatui_textarea::TextArea; +use ratatui_textarea::{CursorMove, TextArea}; use crate::{ config::theme::THEME, @@ -25,13 +29,162 @@ const MEMORY_STEPS: [&str; 12] = [ "512M", "1G", "2G", "3G", "4G", "6G", "8G", "12G", "16G", "24G", "32G", "64G", ]; +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum SettingsPickerBadge { + Auto, + Bundled, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct SettingsPickerOption { + pub key: String, + pub title: String, + pub detail: Option, + pub leading: Option, + pub active: bool, + pub badge: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum SettingsPickerAction { + None, + Back, + Select, +} + +#[derive(Debug, Clone, Default)] +pub(crate) struct SettingsPicker { + options: Vec, + selected: usize, +} + +impl SettingsPicker { + pub(crate) fn reset(&mut self) { + self.options.clear(); + self.selected = 0; + } + + pub(crate) fn sync(&mut self, options: Vec, preferred: Option<&str>) { + let selected_key = self + .options + .get(self.selected) + .map(|option| option.key.clone()) + .or_else(|| preferred.map(str::to_owned)); + self.options = options; + self.selected = selected_key + .as_deref() + .and_then(|key| self.options.iter().position(|option| option.key == key)) + .unwrap_or(0); + } + + pub(crate) fn handle_key(&mut self, key: &KeyEvent) -> SettingsPickerAction { + match key.code { + KeyCode::Esc | KeyCode::Char('h') | KeyCode::Left => SettingsPickerAction::Back, + KeyCode::Char('j') | KeyCode::Down if !self.options.is_empty() => { + self.selected = (self.selected + 1).min(self.options.len() - 1); + SettingsPickerAction::None + } + KeyCode::Char('k') | KeyCode::Up => { + self.selected = self.selected.saturating_sub(1); + SettingsPickerAction::None + } + KeyCode::Enter | KeyCode::Char('l') | KeyCode::Right if !self.options.is_empty() => { + SettingsPickerAction::Select + } + _ => SettingsPickerAction::None, + } + } + + pub(crate) fn selected(&self) -> usize { + self.selected + } + + pub(crate) fn selected_key(&self) -> Option<&str> { + self.options + .get(self.selected) + .map(|option| option.key.as_str()) + } + + pub(crate) fn labels(&self) -> Vec { + self.options + .iter() + .map(|option| { + option.detail.as_ref().map_or_else( + || option.title.clone(), + |detail| format!("{} {detail}", option.title), + ) + }) + .collect() + } + + pub(crate) fn items(&self) -> Vec> { + let theme = THEME.as_ref(); + self.options + .iter() + .enumerate() + .map(|(index, option)| { + let selected = index == self.selected; + let title_style = if selected { + Style::default() + .fg(theme.accent()) + .add_modifier(Modifier::BOLD) + } else if option.active { + Style::default() + .fg(theme.text()) + .add_modifier(Modifier::BOLD) + } else { + Style::default().fg(theme.text()) + }; + let mut spans = Vec::new(); + if let Some(leading) = &option.leading { + spans.push(Span::styled( + leading.clone(), + Style::default().fg(theme.success()), + )); + } + spans.push(Span::styled(option.title.clone(), title_style)); + if let Some(detail) = &option.detail { + spans.push(Span::styled( + format!(" {detail}"), + Style::default() + .fg(if selected { + theme.accent() + } else { + theme.text_dim() + }) + .add_modifier(if selected { + Modifier::BOLD + } else { + Modifier::empty() + }), + )); + } + if let Some(badge) = option.badge { + spans.extend([ + Span::raw(" "), + status_badge( + match badge { + SettingsPickerBadge::Auto => "Auto", + SettingsPickerBadge::Bundled => "Bundled", + }, + theme.success(), + ), + ]); + } + ListItem::new(Line::from(spans)) + }) + .collect() + } +} + #[derive(Debug, Clone)] pub(crate) struct JavaPicker { load: Arc>>>, current: Option, detected: String, - pub selected: usize, - previous_choices: Vec, + picker: SettingsPicker, + cache_path: Option, + refresh_started: bool, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -39,6 +192,26 @@ pub(crate) enum JavaChoice { Installation(String), } +#[derive(Debug, Clone)] +pub(crate) struct GlfwPicker { + load: Arc>>>, + current: Option, + bundled_version: Option, + picker: SettingsPicker, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum GlfwChoice { + Bundled, + System(String), +} + +#[derive(Debug, Clone)] +struct GlfwInstallation { + path: PathBuf, + version: Option, +} + #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct DisplayResolution { pub width: u32, @@ -53,30 +226,63 @@ impl JavaPicker { } pub(crate) fn with_auto_path(detected: String) -> Self { + Self::with_cache(detected, None) + } + + pub(crate) fn with_cache(detected: String, cache_path: Option) -> Self { + let cached = cache_path + .as_deref() + .and_then(crate::instance::java::load_installation_cache); Self { - load: Arc::new(Mutex::new(LoadState::Idle)), + load: Arc::new(Mutex::new( + cached.map_or(LoadState::Idle, LoadState::Loaded), + )), current: None, detected, - selected: 0, - previous_choices: Vec::new(), + picker: SettingsPicker::default(), + cache_path, + refresh_started: false, } } pub(crate) fn open(&mut self, current: Option<&str>) { self.current = current.map(str::to_owned); - self.previous_choices.clear(); + self.picker.reset(); + if self.refresh_started { + return; + } + self.refresh_started = true; let mut load = self .load .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); - if !matches!(*load, LoadState::Idle | LoadState::Error(_)) { - return; + if matches!(*load, LoadState::Idle | LoadState::Error(_)) { + *load = LoadState::Loading; } - *load = LoadState::Loading; drop(load); let target = self.load.clone(); + let cache_path = self.cache_path.clone(); + let selected_paths = [Some(self.detected.clone()), self.current.clone()]; let discover = move || { - let installations = crate::instance::java::discover_installations(); + let mut installations = crate::instance::java::discover_installations(); + for path in selected_paths.into_iter().flatten() { + if installations.iter().any(|installation| { + same_executable(&installation.path.to_string_lossy(), &path) + }) { + continue; + } + if let Some(installation) = + crate::instance::java::inspect_installation(Path::new(&path)) + { + installations.push(installation); + } + } + if let Some(cache_path) = cache_path + && let Err(error) = + crate::instance::java::save_installation_cache(&cache_path, &installations) + { + tracing::debug!("Could not cache Java installations: {error}"); + } *target .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) = @@ -86,10 +292,7 @@ impl JavaPicker { if let Ok(runtime) = tokio::runtime::Handle::try_current() { runtime.spawn_blocking(discover); } else { - *self - .load - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) = LoadState::Loaded(Vec::new()); + self.refresh_started = false; } } @@ -106,18 +309,29 @@ impl JavaPicker { .map(|installation| installation.path.to_string_lossy().into_owned()), ); } - if !paths.contains(&self.detected) { + if let Some(index) = paths + .iter() + .position(|path| same_executable(path, &self.detected)) + { + paths[index].clone_from(&self.detected); + } else { paths.insert(0, self.detected.clone()); } - if let Some(current) = &self.current - && !paths.contains(current) - { - paths.push(current.clone()); + if let Some(current) = &self.current { + if let Some(index) = paths.iter().position(|path| same_executable(path, current)) { + paths[index].clone_from(current); + } else { + paths.push(current.clone()); + } } paths.into_iter().map(JavaChoice::Installation).collect() } pub(crate) fn labels(&self) -> Vec { + self.picker.labels() + } + + fn options(&self) -> Vec { let installations = match &*self .load .lock() @@ -129,62 +343,24 @@ impl JavaPicker { self.choices() .into_iter() .map(|choice| match choice { - JavaChoice::Installation(path) => installations - .as_ref() - .and_then(|items| { + JavaChoice::Installation(path) => { + let installation = installations.as_ref().and_then(|items| { items .iter() - .find(|item| item.path.to_string_lossy() == path) - }) - .map_or_else(|| format!("Java {path}"), JavaInstallation::label), - }) - .collect() - } - - pub(crate) fn items(&self) -> Vec> { - let theme = THEME.as_ref(); - let installations = match &*self - .load - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - { - LoadState::Loaded(installations) => installations.clone(), - _ => Vec::new(), - }; - self.choices() - .into_iter() - .enumerate() - .map(|(index, choice)| match choice { - JavaChoice::Installation(path) => { - let installation = installations - .iter() - .find(|installation| installation.path.to_string_lossy() == path); - let version = installation + .find(|item| same_executable(&item.path.to_string_lossy(), &path)) + }); + let title = installation .and_then(|installation| installation.version.as_deref()) - .map_or_else(|| "Java".to_owned(), |version| format!("Java {version}")); - let selected = index == self.selected; - let mut spans = vec![ - Span::styled( - version, - Style::default().fg(if selected { - theme.accent() - } else { - theme.text() - }), - ), - Span::styled( - format!(" {path}"), - Style::default().fg(if selected { - theme.accent() - } else { - theme.text_dim() - }), - ), - ]; - if self.current.is_none() && path == self.detected { - spans.extend([Span::raw(" "), auto_label()]); + .map_or_else(|| "Java".to_owned(), java_title); + SettingsPickerOption { + key: path.clone(), + title, + detail: Some(path.clone()), + leading: None, + active: false, + badge: (self.current.is_none() && path == self.detected) + .then_some(SettingsPickerBadge::Auto), } - ListItem::new(Line::from(spans)) } }) .collect() @@ -211,65 +387,51 @@ impl JavaPicker { } pub(crate) fn initialize(&mut self) { - let choices = self.choices(); - if choices == self.previous_choices { - return; - } - let selected = self - .previous_choices - .get(self.selected) - .cloned() - .or_else(|| { - Some(JavaChoice::Installation( - self.current - .clone() - .unwrap_or_else(|| self.detected.clone()), - )) - }) - .unwrap_or_else(|| JavaChoice::Installation(self.detected.clone())); - self.selected = choices - .iter() - .position(|choice| choice == &selected) - .unwrap_or(0); - self.previous_choices = choices; + let preferred = self + .current + .clone() + .unwrap_or_else(|| self.detected.clone()); + self.picker.sync(self.options(), Some(&preferred)); } pub(crate) fn selected_choice(&self) -> JavaChoice { - self.choices() - .get(self.selected) - .cloned() - .unwrap_or_else(|| JavaChoice::Installation(self.detected.clone())) + JavaChoice::Installation( + self.picker + .selected_key() + .unwrap_or(&self.detected) + .to_owned(), + ) + } + + pub(crate) fn selection(&self) -> &SettingsPicker { + &self.picker + } + + pub(crate) fn selection_mut(&mut self) -> &mut SettingsPicker { + &mut self.picker } pub(crate) fn detected_path(&self) -> &str { &self.detected } - pub(crate) fn automatic_change(&self, current: &str) -> Option<(String, String)> { - if same_executable(current, &self.detected) { - return None; - } - - let load = self + pub(crate) fn display_label(&self, path: &str) -> String { + let version = match &*self .load .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let installations = match &*load { - LoadState::Loaded(installations) => installations, - _ => return Some((current.to_owned(), self.detected.clone())), - }; - let version_for = |path: &str| { - installations + .unwrap_or_else(std::sync::PoisonError::into_inner) + { + LoadState::Loaded(installations) => installations .iter() .find(|installation| same_executable(&installation.path.to_string_lossy(), path)) - .and_then(|installation| installation.version.clone()) + .and_then(|installation| installation.version.clone()), + _ => None, }; - let current_version = version_for(current); - let detected_version = version_for(&self.detected); - Some(( - java_runtime_label(current, current_version.as_deref()), - java_runtime_label(&self.detected, detected_version.as_deref()), - )) + java_runtime_label(path, version.as_deref()) + } + + pub(crate) fn automatic_change(&self, current: &str) -> bool { + !same_executable(current, &self.detected) } } @@ -279,6 +441,299 @@ impl Default for JavaPicker { } } +impl GlfwPicker { + pub(crate) fn new() -> Self { + Self::with_bundled_version(None) + } + + pub(crate) fn with_bundled_version(bundled_version: Option) -> Self { + Self { + load: Arc::new(Mutex::new(LoadState::Idle)), + current: None, + bundled_version, + picker: SettingsPicker::default(), + } + } + + pub(crate) fn open(&mut self, current: Option<&str>) { + self.current = current.map(str::to_owned); + self.picker.reset(); + let mut load = self + .load + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if !matches!(*load, LoadState::Idle | LoadState::Error(_)) { + return; + } + *load = LoadState::Loading; + drop(load); + let target = self.load.clone(); + let discover = move || { + let installations = discover_glfw_installations(); + *target + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = + LoadState::Loaded(installations); + crate::feedback::request_redraw(); + }; + if let Ok(runtime) = tokio::runtime::Handle::try_current() { + runtime.spawn_blocking(discover); + } else { + *self + .load + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = LoadState::Loaded(Vec::new()); + } + } + + pub(crate) fn set_bundled_version(&mut self, version: Option) { + self.bundled_version = version; + } + + pub(crate) fn choices(&self) -> Vec { + let mut choices = vec![GlfwChoice::Bundled]; + if let LoadState::Loaded(installations) = &*self + .load + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + { + choices.extend(installations.iter().map(|installation| { + GlfwChoice::System(installation.path.to_string_lossy().into_owned()) + })); + } + if let Some(current) = &self.current { + if let Some(choice) = choices.iter_mut().find(|choice| { + matches!(choice, GlfwChoice::System(path) if same_executable(path, current)) + }) { + *choice = GlfwChoice::System(current.clone()); + } else { + choices.push(GlfwChoice::System(current.clone())); + } + } + choices + } + + pub(crate) fn initialize(&mut self) { + let preferred = self.current.as_deref().unwrap_or(BUNDLED_GLFW_KEY); + self.picker.sync(self.options(), Some(preferred)); + } + + pub(crate) fn selected_choice(&self) -> GlfwChoice { + match self.picker.selected_key() { + Some(BUNDLED_GLFW_KEY) | None => GlfwChoice::Bundled, + Some(path) => GlfwChoice::System(path.to_owned()), + } + } + + pub(crate) fn labels(&self) -> Vec { + self.picker.labels() + } + + pub(crate) fn bundled_label(&self) -> String { + self.bundled_version.as_ref().map_or_else( + || "Minecraft GLFW".to_owned(), + |version| format!("LWJGL GLFW {version}"), + ) + } + + pub(crate) fn display_label(&self, path: Option<&str>) -> String { + let Some(path) = path else { + return self.bundled_label(); + }; + let detected_version = match &*self + .load + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + { + LoadState::Loaded(installations) => installations + .iter() + .find(|installation| installation.path.to_string_lossy() == path) + .and_then(|installation| installation.version.clone()), + _ => None, + }; + detected_version + .or_else(|| glfw_version_from_path(Path::new(path))) + .map_or_else( + || format!("System GLFW {path}"), + |version| format!("GLFW {version} {path}"), + ) + } + + fn options(&self) -> Vec { + let installations = match &*self + .load + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + { + LoadState::Loaded(installations) => installations.clone(), + _ => Vec::new(), + }; + self.choices() + .into_iter() + .map(|choice| match choice { + GlfwChoice::Bundled => SettingsPickerOption { + key: BUNDLED_GLFW_KEY.to_owned(), + title: self.bundled_label(), + detail: None, + leading: None, + active: false, + badge: Some(SettingsPickerBadge::Bundled), + }, + GlfwChoice::System(path) => { + let version = installations + .iter() + .find(|installation| { + same_executable(&installation.path.to_string_lossy(), &path) + }) + .and_then(|installation| installation.version.as_deref()); + SettingsPickerOption { + key: path.clone(), + title: version.map_or_else( + || "System GLFW".to_owned(), + |version| format!("GLFW {version}"), + ), + detail: Some(path), + leading: None, + active: false, + badge: None, + } + } + }) + .collect() + } + + pub(crate) fn selection(&self) -> &SettingsPicker { + &self.picker + } + + pub(crate) fn selection_mut(&mut self) -> &mut SettingsPicker { + &mut self.picker + } + + pub(crate) fn take_status(&mut self) -> Option<&'static str> { + match &*self + .load + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + { + LoadState::Loading => Some("Detecting installed GLFW libraries…"), + LoadState::Loaded(installations) if installations.is_empty() => { + Some("No system GLFW libraries found; bundled remains available.") + } + _ => None, + } + } +} + +const BUNDLED_GLFW_KEY: &str = "\0bundled-glfw"; + +impl Default for GlfwPicker { + fn default() -> Self { + Self::new() + } +} + +pub(crate) fn bundled_glfw_version(meta_dir: &Path, game_version: &str) -> Option { + let path = crate::storage::MetadataPaths::new(meta_dir) + .versions() + .join(game_version) + .join("meta.json"); + let profile: serde_json::Value = serde_json::from_slice(&std::fs::read(path).ok()?).ok()?; + profile + .get("libraries")? + .as_array()? + .iter() + .filter_map(|library| library.get("name")?.as_str()) + .find_map(|coordinate| { + let mut parts = coordinate.split(':'); + match (parts.next(), parts.next(), parts.next()) { + (Some("org.lwjgl"), Some("lwjgl-glfw"), Some(version)) => Some(version.to_owned()), + _ => None, + } + }) +} + +fn discover_glfw_installations() -> Vec { + let mut directories = Vec::::new(); + for variable in ["LD_LIBRARY_PATH", "DYLD_LIBRARY_PATH", "PATH"] { + if let Some(value) = std::env::var_os(variable) { + directories.extend(std::env::split_paths(&value)); + } + } + directories.extend( + [ + "/usr/lib", + "/usr/lib64", + "/usr/local/lib", + "/lib", + "/lib64", + "/opt/homebrew/lib", + "/opt/local/lib", + ] + .into_iter() + .map(PathBuf::from), + ); + + let mut nested = Vec::new(); + for directory in &directories { + if let Ok(entries) = std::fs::read_dir(directory) { + nested.extend( + entries + .flatten() + .map(|entry| entry.path()) + .filter(|path| path.is_dir()), + ); + } + } + directories.extend(nested); + + let mut seen = BTreeSet::new(); + let mut installations = Vec::new(); + for directory in directories { + let Ok(entries) = std::fs::read_dir(directory) else { + continue; + }; + for path in entries.flatten().map(|entry| entry.path()) { + if !is_glfw_library(&path) { + continue; + } + let canonical = std::fs::canonicalize(&path).unwrap_or(path); + if seen.insert(canonical.clone()) { + installations.push(GlfwInstallation { + version: glfw_version_from_path(&canonical), + path: canonical, + }); + } + } + } + installations.sort_by(|left, right| left.path.cmp(&right.path)); + installations +} + +fn is_glfw_library(path: &Path) -> bool { + let Some(name) = path.file_name().and_then(|name| name.to_str()) else { + return false; + }; + let name = name.to_ascii_lowercase(); + name.starts_with("libglfw") && (name.contains(".so") || name.ends_with(".dylib")) + || name.starts_with("glfw") && name.ends_with(".dll") +} + +fn glfw_version_from_path(path: &Path) -> Option { + let name = path.file_name()?.to_str()?.to_ascii_lowercase(); + if let Some((_, suffix)) = name.rsplit_once(".so.") { + return (!suffix.is_empty()).then(|| suffix.to_owned()); + } + let stem = name + .strip_prefix("libglfw.") + .and_then(|name| name.strip_suffix(".dylib")) + .or_else(|| { + name.strip_prefix("glfw") + .and_then(|name| name.strip_suffix(".dll")) + })?; + (!stem.is_empty()).then(|| stem.trim_start_matches(['-', '.']).to_owned()) +} + fn same_executable(left: &str, right: &str) -> bool { if left == right { return true; @@ -291,11 +746,22 @@ fn same_executable(left: &str, right: &str) -> bool { fn java_runtime_label(path: &str, version: Option<&str>) -> String { version.map_or_else( - || path.to_owned(), - |version| format!("Java {version} {path}"), + || format!("Java {path}"), + |version| format!("{} {path}", java_title(version)), ) } +fn java_title(version: &str) -> String { + let mut parts = version.split(['.', '_']); + let first = parts.next().unwrap_or(version); + let major = if first == "1" { + parts.next().unwrap_or(first) + } else { + first + }; + format!("Java {major}") +} + pub(crate) fn memory_kib(value: &str) -> Option { let normalized = crate::instance::models::normalize_memory_value(value)?; let (number, suffix) = normalized.split_at(normalized.len().saturating_sub(1)); @@ -406,10 +872,37 @@ pub(crate) fn handle_text_area_input(input: &mut TextArea<'_>, key: &KeyEvent) { } } +pub(crate) fn settings_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(crate) fn auto_label() -> Span<'static> { status_badge("Auto", THEME.as_ref().success()) } +pub(crate) fn bundled_label() -> Span<'static> { + status_badge("Bundled", THEME.as_ref().success()) +} + +pub(crate) fn render_settings_picker( + picker: &SettingsPicker, + area: Rect, + buffer: &mut ratatui::buffer::Buffer, +) { + super::select_list::render_styled(picker.items(), picker.selected(), area, buffer); +} + pub(crate) fn display_resolutions() -> Vec { let Ok(displays) = display_info::DisplayInfo::all() else { return Vec::new(); @@ -463,25 +956,101 @@ mod tests { picker.selected_choice(), JavaChoice::Installation("/opt/jdk/bin/java".to_owned()) ); + assert_eq!( + picker.display_label("/opt/jdk/bin/java"), + "Java 21 /opt/jdk/bin/java" + ); + } + + #[test] + fn java_title_is_minimal_and_uses_the_major_version() { + let picker = JavaPicker::with_auto_path("/opt/jdk-25/bin/java".to_owned()); + assert_eq!( + picker.display_label("/opt/jdk-25/bin/java"), + "Java /opt/jdk-25/bin/java" + ); + *picker.load.lock().unwrap() = LoadState::Loaded(vec![JavaInstallation { + path: "/opt/jdk-25/bin/java".into(), + version: Some("25.0.1".to_owned()), + }]); + assert_eq!( + picker.display_label("/opt/jdk-25/bin/java"), + "Java 25 /opt/jdk-25/bin/java" + ); + assert_eq!(java_title("1.8.0_412"), "Java 8"); } #[test] fn automatic_java_compares_selected_executables() { let picker = JavaPicker::with_auto_path("/auto/java".to_owned()); - *picker.load.lock().unwrap() = LoadState::Loaded(vec![ - JavaInstallation { - path: "/current/java".into(), - version: Some("21.0.8".to_owned()), - }, - JavaInstallation { - path: "/auto/java".into(), - version: Some("21.0.8".to_owned()), - }, - ]); + assert!(!picker.automatic_change("/auto/java")); + assert!(picker.automatic_change("/current/java")); + assert!(picker.automatic_change("/other/java")); + } - assert!(picker.automatic_change("/auto/java").is_none()); - assert!(picker.automatic_change("/current/java").is_some()); - assert!(picker.automatic_change("/other/java").is_some()); + #[test] + fn settings_picker_shares_navigation_and_preserves_selection() { + let option = |key: &str| SettingsPickerOption { + key: key.to_owned(), + title: key.to_owned(), + detail: None, + leading: None, + active: false, + badge: None, + }; + let mut picker = SettingsPicker::default(); + picker.sync(vec![option("one"), option("two")], Some("one")); + assert_eq!( + picker.handle_key(&KeyEvent::from(KeyCode::Char('j'))), + SettingsPickerAction::None + ); + assert_eq!(picker.selected_key(), Some("two")); + + picker.sync( + vec![option("zero"), option("one"), option("two")], + Some("one"), + ); + assert_eq!(picker.selected_key(), Some("two")); + assert_eq!( + picker.handle_key(&KeyEvent::from(KeyCode::Enter)), + SettingsPickerAction::Select + ); + } + + #[test] + fn bundled_glfw_version_comes_from_minecraft_metadata() { + let temp = tempfile::tempdir().unwrap(); + let versions = crate::storage::MetadataPaths::new(temp.path()).versions(); + std::fs::create_dir_all(versions.join("1.21.1")).unwrap(); + std::fs::write( + versions.join("1.21.1/meta.json"), + r#"{"libraries":[{"name":"org.lwjgl:lwjgl-glfw:3.3.3"}]}"#, + ) + .unwrap(); + + assert_eq!( + bundled_glfw_version(temp.path(), "1.21.1").as_deref(), + Some("3.3.3") + ); + let mut picker = GlfwPicker::with_bundled_version(Some("3.3.3".to_owned())); + picker.initialize(); + assert_eq!(picker.labels()[0], "LWJGL GLFW 3.3.3"); + assert_eq!( + picker.selection().options[0].badge, + Some(SettingsPickerBadge::Bundled) + ); + } + + #[test] + fn glfw_library_names_are_recognized() { + assert!(is_glfw_library(Path::new("/usr/lib/libglfw.so.3"))); + assert!(is_glfw_library(Path::new("/usr/lib/libglfw.3.dylib"))); + assert!(is_glfw_library(Path::new("C:/bin/glfw3.dll"))); + assert!(!is_glfw_library(Path::new("/usr/lib/libGL.so"))); + assert_eq!( + glfw_version_from_path(Path::new("/usr/lib/libglfw.so.3.4")).as_deref(), + Some("3.4") + ); } #[test] diff --git a/tests/launch_pipeline.rs b/tests/launch_pipeline.rs index 0414522..285c5dd 100644 --- a/tests/launch_pipeline.rs +++ b/tests/launch_pipeline.rs @@ -56,7 +56,13 @@ fn make_config_with( memory_max: None, memory_min: None, jvm_args: Vec::new(), + environment: Default::default(), + window_mode: Default::default(), resolution: None, + preferred_account: None, + pre_launch_command: Default::default(), + post_exit_command: Default::default(), + glfw_path: None, config_sync_profile: None, modpack_source: None, } @@ -663,6 +669,38 @@ async fn xms_xmx_use_config_memory() { assert!(inv.jvm_args.iter().any(|a| a == "-Xmx4G")); } +#[tokio::test] +async fn instance_launch_options_are_injected() { + let fx = Fixture::new("options", "1.20.1", modern_vanilla_meta("1.20.1")); + let mut config = make_config("options", "1.20.1", ModLoader::Vanilla); + config.window_mode = rmcl::instance::WindowMode::Fullscreen; + config.glfw_path = Some("/usr/lib/libglfw.so.3".to_owned()); + config + .environment + .insert("MESA_LOADER_DRIVER_OVERRIDE".to_owned(), "zink".to_owned()); + + let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth(), None) + .await + .unwrap(); + + assert!( + inv.game_args + .iter() + .any(|argument| argument == "--fullscreen") + ); + assert!( + inv.jvm_args + .iter() + .any(|argument| argument == "-Dorg.lwjgl.glfw.libname=/usr/lib/libglfw.so.3") + ); + assert_eq!( + inv.environment + .get("MESA_LOADER_DRIVER_OVERRIDE") + .map(String::as_str), + Some("zink") + ); +} + #[tokio::test] async fn default_memory_used_when_unset() { let fx = Fixture::new("memdef", "1.20.1", modern_vanilla_meta("1.20.1"));