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]