feat: add instance launch settings

This commit is contained in:
objz committed 2026-09-04 20:06:22 +02:00
1 parent 59407ee01d
commit 8de0cbaa09
25 files changed
+2463 -482

No files matched your search

+49 -5
View File
@@ -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<String>,
@@ -91,10 +93,9 @@ pub fn discover_installations() -> Vec<JavaInstallation> {
.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::<Vec<_>>();
installations.sort_by(|a, b| {
@@ -105,6 +106,31 @@ pub fn discover_installations() -> Vec<JavaInstallation> {
installations
}
/// Reads the version reported by one Java executable.
#[must_use]
pub fn inspect_installation(path: &Path) -> Option<JavaInstallation> {
path.is_file().then(|| JavaInstallation {
version: java_version(path),
path: path.to_path_buf(),
})
}
#[must_use]
pub fn load_installation_cache(path: &Path) -> Option<Vec<JavaInstallation>> {
let mut installations =
serde_json::from_slice::<Vec<JavaInstallation>>(&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<PathBuf> {
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);
}
}
+152 -9
View File
@@ -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<String>, resolution: Option<(u32,
}
}
fn apply_window_mode(game_args: &mut Vec<String>, 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<u32> {
let quoted = text
.split_once('"')
@@ -318,6 +328,7 @@ pub struct LaunchInvocation {
pub main_class: String,
pub extra_args: Vec<String>,
pub game_args: Vec<String>,
pub environment: std::collections::BTreeMap<String, String>,
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!(
+6
View File
@@ -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,
};
+1 -1
View File
@@ -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};
+50 -1
View File
@@ -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<String>,
#[serde(default)]
pub jvm_args: Vec<String>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub environment: BTreeMap<String, String>,
#[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<String>,
#[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<String>,
#[serde(default)]
pub config_sync_profile: Option<String>,
#[serde(default)]
@@ -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,
}
+6
View File
@@ -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,
},
+128
View File
@@ -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,
};
+6
View File
@@ -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,
}
+12
View File
@@ -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]
+4
View File
@@ -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)
}
+4
View File
@@ -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")
+4
View File
@@ -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<Arc<Mutex<Vec<InstanceConfig>>>> =
LazyLock::new(|| Arc::new(Mutex::new(Vec::new())));
pub(super) static FAILED_INSTANCE_SETTINGS_UPDATES: LazyLock<Arc<Mutex<Vec<String>>>> =
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<widgets::popups::instance_settings::State>,
pub(super) pending_instance_settings_updates: HashSet<String>,
pub(super) global_settings: Option<widgets::popups::global_settings::State>,
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();
+26 -1
View File
@@ -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,
+125 -83
View File
@@ -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 {
+63
View File
@@ -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,
};
+181 -26
View File
@@ -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();
+11
View File
@@ -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,
};
@@ -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,
}
+6
View File
@@ -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,
}
+30 -16
View File
@@ -48,23 +48,40 @@ pub enum ConfirmTarget {
InstanceRuntime {
name: String,
},
JvmArguments {
name: String,
},
JavaAuto {
AutomaticSelection {
setting: AutomaticSetting,
instance: Option<String>,
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::<Vec<_>>()
.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",
}
}
+33 -54
View File
@@ -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<Config>, 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<String> {
themes
}
fn new_text_area(lines: Vec<String>) -> 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(),
File diff suppressed because it is too large. Load diff
+702 -133
View File
@@ -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<String>,
pub leading: Option<String>,
pub active: bool,
pub badge: Option<SettingsPickerBadge>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum SettingsPickerAction {
None,
Back,
Select,
}
#[derive(Debug, Clone, Default)]
pub(crate) struct SettingsPicker {
options: Vec<SettingsPickerOption>,
selected: usize,
}
impl SettingsPicker {
pub(crate) fn reset(&mut self) {
self.options.clear();
self.selected = 0;
}
pub(crate) fn sync(&mut self, options: Vec<SettingsPickerOption>, 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<String> {
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<ListItem<'static>> {
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<Mutex<LoadState<Vec<JavaInstallation>>>>,
current: Option<String>,
detected: String,
pub selected: usize,
previous_choices: Vec<JavaChoice>,
picker: SettingsPicker,
cache_path: Option<PathBuf>,
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<Mutex<LoadState<Vec<GlfwInstallation>>>>,
current: Option<String>,
bundled_version: Option<String>,
picker: SettingsPicker,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum GlfwChoice {
Bundled,
System(String),
}
#[derive(Debug, Clone)]
struct GlfwInstallation {
path: PathBuf,
version: Option<String>,
}
#[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<PathBuf>) -> 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<String> {
self.picker.labels()
}
fn options(&self) -> Vec<SettingsPickerOption> {
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<ListItem<'static>> {
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<String>) -> 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<String>) {
self.bundled_version = version;
}
pub(crate) fn choices(&self) -> Vec<GlfwChoice> {
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<String> {
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<SettingsPickerOption> {
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<String> {
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<GlfwInstallation> {
let mut directories = Vec::<PathBuf>::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<String> {
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<u64> {
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<String>) -> 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<DisplayResolution> {
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]
+38
View File
@@ -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"));