5 Commits
17 changed files with 885 additions and 181 deletions

No files matched your search

+2 -2
View File
@@ -34,7 +34,7 @@ the codebase is split roughly like this:
- `src/cli/` handles command line interface - `src/cli/` handles command line interface
- `src/config/` has settings, paths, theme config - `src/config/` has settings, paths, theme config
- `src/instance/` is the core. `content/` scans mods, resource packs, shaders, worlds. `import/` handles modpack importing with `mod.rs` dispatching to format-specific modules like `mrpack.rs` and `mmc.rs`. `loader/` installs mod loaders (fabric, forge, neoforge, quilt). `launch.rs` builds the java command and spawns minecraft. `manager.rs` does instance CRUD - `src/instance/` is the core. `content/` scans mods, resource packs, shaders, worlds. `import/` handles modpack importing with `mod.rs` dispatching to format-specific modules like `mrpack.rs` and `mmc.rs`. `loader/` installs mod loaders (fabric, forge, neoforge, quilt). `launch/` builds the java command and spawns minecraft, with `patches.rs` handling lwjgl3ify classpath patches. `manager.rs` does instance CRUD
- `src/net/` is the networking layer. http client, file downloads, and API clients per service - `src/net/` is the networking layer. http client, file downloads, and API clients per service
- `src/tui/` is the terminal UI built with ratatui - `src/tui/` is the terminal UI built with ratatui
@@ -52,4 +52,4 @@ start with what you did: `added`, `fixed`, `refactored`, etc. lowercase. separat
## before submitting ## before submitting
make sure `cargo build`, `cargo clippy`, and `cargo test` all pass. make sure `cargo build`, `cargo clippy`, and `cargo test` all pass. you'll need a JDK (`javac` and `jar` on PATH) for the build script that compiles the java shim.
Generated
+1 -1
View File
@@ -1830,7 +1830,7 @@ dependencies = [
[[package]] [[package]]
name = "mcl-launcher" name = "mcl-launcher"
version = "0.1.0" version = "0.2.1"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"chrono", "chrono",
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "mcl-launcher" name = "mcl-launcher"
version = "0.2.0" version = "0.2.1"
authors = ["objz"] authors = ["objz"]
edition = "2024" edition = "2024"
description = "A fully featured Minecraft launcher TUI" description = "A fully featured Minecraft launcher TUI"
+18 -7
View File
@@ -85,16 +85,27 @@ mcl can be compiled for Linux, macOS, and Windows. right now it's only packaged
## where things live ## where things live
| path | what | ### config & data
|---|---|
| `~/.config/mcl/config.toml` | general config (paths, memory defaults, UI settings) | settings, accounts, instances, and cached game metadata.
| `~/.config/mcl/theme.toml` | theme, border style, color overrides |
| `~/.config/mcl/accounts.json` | accounts | | what | Linux | macOS | Windows |
| `~/.local/share/mcl/instances/` | instances, each in its own directory | |---|---|---|---|
| `~/.local/share/mcl/meta/` | cached game metadata, libraries, assets, loader profiles | | config (`config.toml`, `theme.toml`, `accounts.json`) | `~/.config/mcl/` | `~/Library/Application Support/mcl/` | `%APPDATA%\mcl\` |
| instances | `~/.local/share/mcl/instances/` | `~/Library/Application Support/mcl/instances/` | `%LOCALAPPDATA%\mcl\instances\` |
| metadata (versions, libraries, assets, loader profiles) | `~/.local/share/mcl/meta/` | `~/Library/Application Support/mcl/meta/` | `%LOCALAPPDATA%\mcl\meta\` |
each instance has an `instance.json` for its config and a `.minecraft/` directory with the actual game files. standard layout, nothing weird. each instance has an `instance.json` for its config and a `.minecraft/` directory with the actual game files. standard layout, nothing weird.
### logs
launcher logs are per-session and contain mcl's own output. instance launch logs capture game stdout/stderr per launch.
| what | Linux | macOS | Windows |
|---|---|---|---|
| launcher logs | `~/.cache/mcl/` | `~/Library/Caches/mcl/` | `%LOCALAPPDATA%\mcl\` |
| instance launch logs | `<instances>/<name>/.minecraft/logs/launches/` | same | same |
--- ---
## configuration ## configuration
+38
View File
@@ -0,0 +1,38 @@
use std::env;
use std::path::Path;
use std::process::Command;
fn main() {
println!("cargo:rerun-if-changed=java/MclShim.java");
let out_dir = env::var("OUT_DIR").unwrap();
let out = Path::new(&out_dir);
// compile MclShim.java into a jar that gets embedded via include_bytes!
let status = Command::new("javac")
.arg("-source")
.arg("8")
.arg("-target")
.arg("8")
.arg("-d")
.arg(out.to_str().unwrap())
.arg("java/MclShim.java")
.status()
.expect("Failed to run javac - is a JDK installed?");
assert!(status.success(), "javac failed to compile MclShim.java");
// package into a jar
let jar_path = out.join("mcl-shim.jar");
let status = Command::new("jar")
.arg("cfe")
.arg(jar_path.to_str().unwrap())
.arg("MclShim")
.arg("-C")
.arg(out.to_str().unwrap())
.arg("MclShim.class")
.status()
.expect("Failed to run jar - is a JDK installed?");
assert!(status.success(), "jar failed to create mcl-shim.jar");
}
+19
View File
@@ -0,0 +1,19 @@
import java.lang.reflect.Method;
public class MclShim {
public static void main(String[] args) throws Exception {
if (args.length == 0) {
System.err.println("Usage: MclShim <mainClass> [args...]");
System.exit(1);
}
String mainClass = args[0];
String[] remaining = new String[args.length - 1];
System.arraycopy(args, 1, remaining, 0, remaining.length);
ClassLoader loader = ClassLoader.getSystemClassLoader();
Class<?> clazz = loader.loadClass(mainClass);
Method main = clazz.getMethod("main", String[].class);
main.invoke(null, (Object) remaining);
}
}
+7 -7
View File
@@ -12,6 +12,10 @@ pub struct Account {
pub active: bool, pub active: bool,
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub refresh_token: Option<String>, pub refresh_token: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cached_mc_token: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cached_mc_token_expires_at: Option<i64>,
} }
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
@@ -123,6 +127,8 @@ pub fn create_offline_account(username: &str) -> Account {
account_type: AccountType::Offline, account_type: AccountType::Offline,
active: false, active: false,
refresh_token: None, refresh_token: None,
cached_mc_token: None,
cached_mc_token_expires_at: None,
} }
} }
@@ -185,13 +191,7 @@ mod tests {
} }
fn dummy_account(name: &str) -> Account { fn dummy_account(name: &str) -> Account {
Account { create_offline_account(name)
uuid: offline_uuid(name),
username: name.to_owned(),
account_type: AccountType::Offline,
active: false,
refresh_token: None,
}
} }
#[test] #[test]
+83 -6
View File
@@ -19,6 +19,8 @@ const DEVICE_CODE_URL: &str = "https://login.microsoftonline.com/consumers/oauth
const MSA_AUTHORIZE_URL: &str = "https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize"; const MSA_AUTHORIZE_URL: &str = "https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize";
const MSA_TOKEN_URL: &str = "https://login.microsoftonline.com/consumers/oauth2/v2.0/token"; const MSA_TOKEN_URL: &str = "https://login.microsoftonline.com/consumers/oauth2/v2.0/token";
const MC_PROFILE_URL: &str = "https://api.minecraftservices.com/minecraft/profile"; const MC_PROFILE_URL: &str = "https://api.minecraftservices.com/minecraft/profile";
const MC_TOKEN_CACHE_TTL_SECS: i64 = 20 * 60 * 60;
const MC_TOKEN_CACHE_REFRESH_MARGIN_SECS: i64 = 5 * 60;
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub struct DeviceCodeInfo { pub struct DeviceCodeInfo {
@@ -131,7 +133,7 @@ async fn exchange_and_build_account(
Err(e) => return AuthResult::Error(format!("Profile parse failed: {e}")), Err(e) => return AuthResult::Error(format!("Profile parse failed: {e}")),
}; };
// mojang returns uuids without dashes because of course they do // mojang returns uuids without dashes
let uuid = if profile.id.len() == 32 { let uuid = if profile.id.len() == 32 {
format!( format!(
"{}-{}-{}-{}-{}", "{}-{}-{}-{}-{}",
@@ -151,15 +153,42 @@ async fn exchange_and_build_account(
account_type: AccountType::Microsoft, account_type: AccountType::Microsoft,
active: false, active: false,
refresh_token: ms_refresh_token.map(|s| s.to_owned()), refresh_token: ms_refresh_token.map(|s| s.to_owned()),
cached_mc_token: None,
cached_mc_token_expires_at: None,
}) })
} }
// returns (mc_access_token, new_refresh_token). for offline accounts it just fn valid_cached_mc_token(account: &Account, now: i64) -> Option<&str> {
// hands back a dummy token since the server doesn't care. let (Some(cached), Some(expires_at)) = (
pub async fn refresh_and_get_token(account: &Account) -> Result<(String, Option<String>), String> { account.cached_mc_token.as_deref(),
account.cached_mc_token_expires_at,
) else {
return None;
};
if now < expires_at - MC_TOKEN_CACHE_REFRESH_MARGIN_SECS {
Some(cached)
} else {
None
}
}
// returns (mc_access_token, new_refresh_token, new_mc_token_expires_at).
// cached tokens return no expiry so callers don't rewrite the account store.
pub async fn refresh_and_get_token(
account: &Account,
) -> Result<(String, Option<String>, Option<i64>), String> {
match account.account_type { match account.account_type {
AccountType::Offline => Ok(("0".to_owned(), None)), AccountType::Offline => Ok(("0".to_owned(), None, None)),
AccountType::Microsoft => { AccountType::Microsoft => {
let now = chrono::Utc::now().timestamp();
if let Some(cached) = valid_cached_mc_token(account, now) {
tracing::info!("Using cached Minecraft token for '{}'", account.username);
return Ok((cached.to_owned(), None, None));
}
tracing::info!("Refreshing Minecraft token for '{}'", account.username);
let refresh = account.refresh_token.as_deref().ok_or_else(|| { let refresh = account.refresh_token.as_deref().ok_or_else(|| {
format!( format!(
"No saved credentials for '{}'. Please remove and re-add the account.", "No saved credentials for '{}'. Please remove and re-add the account.",
@@ -192,7 +221,55 @@ pub async fn refresh_and_get_token(account: &Account) -> Result<(String, Option<
.await .await
.map_err(|e| format!("Minecraft auth failed: {e}"))?; .map_err(|e| format!("Minecraft auth failed: {e}"))?;
Ok((mc_token.access_token().as_ref().to_owned(), new_refresh)) // minecraft-msa-auth does not expose this expiry here, so cache
// conservatively and refresh before the token gets close.
let expires_at = chrono::Utc::now().timestamp() + MC_TOKEN_CACHE_TTL_SECS;
Ok((
mc_token.access_token().as_ref().to_owned(),
new_refresh,
Some(expires_at),
))
} }
} }
} }
#[cfg(test)]
mod tests {
use super::*;
fn microsoft_account(cached_mc_token_expires_at: Option<i64>) -> Account {
Account {
uuid: "00000000-0000-0000-0000-000000000000".to_owned(),
username: "TestPlayer".to_owned(),
account_type: AccountType::Microsoft,
active: true,
refresh_token: Some("refresh".to_owned()),
cached_mc_token: Some("cached".to_owned()),
cached_mc_token_expires_at,
}
}
#[test]
fn cached_mc_token_is_valid_before_refresh_margin() {
let now = 1_000;
let account = microsoft_account(Some(now + MC_TOKEN_CACHE_REFRESH_MARGIN_SECS + 1));
assert_eq!(valid_cached_mc_token(&account, now), Some("cached"));
}
#[test]
fn cached_mc_token_expires_inside_refresh_margin() {
let now = 1_000;
let account = microsoft_account(Some(now + MC_TOKEN_CACHE_REFRESH_MARGIN_SECS));
assert!(valid_cached_mc_token(&account, now).is_none());
}
#[test]
fn cached_mc_token_requires_expiry() {
let account = microsoft_account(None);
assert!(valid_cached_mc_token(&account, 1_000).is_none());
}
}
+2 -10
View File
@@ -249,18 +249,10 @@ fn apply_config_update(
) -> CliResult { ) -> CliResult {
match key { match key {
"memory-max" => { "memory-max" => {
config.memory_max = if value.is_empty() { config.memory_max = crate::instance::normalize_memory_value(value);
None
} else {
Some(value.to_string())
}
} }
"memory-min" => { "memory-min" => {
config.memory_min = if value.is_empty() { config.memory_min = crate::instance::normalize_memory_value(value);
None
} else {
Some(value.to_string())
}
} }
"java-path" => { "java-path" => {
config.java_path = if value.is_empty() { config.java_path = if value.is_empty() {
@@ -1,5 +1,8 @@
// builds the full java command line and spawns minecraft as a child process. // builds the full java command line and spawns minecraft as a child process.
// handles classpath assembly, auth token injection, and log capture. // handles classpath assembly, auth token injection, and log capture.
// loader-specific patches live in submodules (e.g. patches.rs for lwjgl3ify).
mod patches;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@@ -76,6 +79,13 @@ struct LoaderLibrary {
name: String, name: String,
} }
struct GameAuth {
username: String,
uuid: String,
token: String,
user_type: String,
}
// mojang's library rules are a fun little state machine: each rule can allow // mojang's library rules are a fun little state machine: each rule can allow
// or disallow based on OS. if no rule matches the current OS, the library is // or disallow based on OS. if no rule matches the current OS, the library is
// included only if no rule "dominated" (matched at all). yes, it's weird. // included only if no rule "dominated" (matched at all). yes, it's weird.
@@ -107,6 +117,38 @@ fn lib_allowed(lib: &MetaLibrary) -> bool {
!dominated !dominated
} }
fn build_game_args(
config: &InstanceConfig,
minecraft_dir: &Path,
meta_dir: &Path,
asset_index_id: &str,
auth: GameAuth,
loader_game_args: Vec<String>,
) -> Vec<String> {
let mut game_args = vec![
"--username".to_string(),
auth.username,
"--version".to_string(),
config.game_version.clone(),
"--gameDir".to_string(),
minecraft_dir.to_string_lossy().into_owned(),
"--assetsDir".to_string(),
meta_dir.join("assets").to_string_lossy().into_owned(),
"--assetIndex".to_string(),
asset_index_id.to_string(),
"--uuid".to_string(),
auth.uuid,
"--accessToken".to_string(),
auth.token,
"--userProperties".to_string(),
"{}".to_string(),
"--userType".to_string(),
auth.user_type,
];
game_args.extend(loader_game_args);
game_args
}
pub async fn launch( pub async fn launch(
config: &InstanceConfig, config: &InstanceConfig,
instances_dir: &Path, instances_dir: &Path,
@@ -193,15 +235,14 @@ pub async fn launch(
.join(format!("{}.jar", config.game_version)), .join(format!("{}.jar", config.game_version)),
); );
// lwjgl3ify ships a patched launchwrapper and retrofuturabootstrap for // apply loader-specific patches (lwjgl3ify for old forge on java 9+)
// java 9+ compat. if present, prepend its patches to the classpath, let (patch_jvm_args, main_class, extra_args) = if matches!(config.loader, ModLoader::Forge) {
// override the main class to use RFB's bootstrap, and add the required match patches::apply(&minecraft_dir, &lib_dir, &mut classpath).await {
// --add-opens and system classloader flags. Some(p) => (p.jvm_args, p.main_class, p.extra_args),
let (lwjgl3ify_jvm_args, main_class) = if matches!(config.loader, ModLoader::Forge) { None => (Vec::new(), main_class, Vec::new()),
let (jvm_args, override_main) = apply_lwjgl3ify_patches(&minecraft_dir, &mut classpath); }
(jvm_args, override_main.unwrap_or(main_class))
} else { } else {
(Vec::new(), main_class) (Vec::new(), main_class, Vec::new())
}; };
let sep = if cfg!(windows) { ";" } else { ":" }; let sep = if cfg!(windows) { ";" } else { ":" };
@@ -227,7 +268,7 @@ pub async fn launch(
format!("-Xms{}", config.memory_min.as_deref().unwrap_or("512M")), format!("-Xms{}", config.memory_min.as_deref().unwrap_or("512M")),
format!("-Xmx{}", config.memory_max.as_deref().unwrap_or("2G")), format!("-Xmx{}", config.memory_max.as_deref().unwrap_or("2G")),
]; ];
jvm.extend(lwjgl3ify_jvm_args); jvm.extend(patch_jvm_args);
jvm.extend(config.jvm_args.clone()); jvm.extend(config.jvm_args.clone());
// resolve auth credentials, refreshing the microsoft token if needed. // resolve auth credentials, refreshing the microsoft token if needed.
@@ -238,26 +279,36 @@ pub async fn launch(
.cloned() .cloned()
{ {
Some(acc) => { Some(acc) => {
let (token, new_refresh) = match acc.account_type { let (token, new_refresh, new_expires) = match acc.account_type {
crate::auth::AccountType::Microsoft => { crate::auth::AccountType::Microsoft => {
match crate::auth::refresh_and_get_token(&acc).await { match crate::auth::refresh_and_get_token(&acc).await {
Ok(pair) => pair, Ok(triple) => triple,
Err(e) => { Err(e) => {
return Err(LaunchError::Auth(format!("Authentication failed: {e}"))); return Err(LaunchError::Auth(format!("Authentication failed: {e}")));
} }
} }
} }
crate::auth::AccountType::Offline => ("0".to_string(), None), crate::auth::AccountType::Offline => ("0".to_string(), None, None),
}; };
if let Some(new_rt) = new_refresh if let Some(stored) = account_store
&& let Some(stored) = account_store .accounts
.accounts .iter_mut()
.iter_mut() .find(|a| a.uuid == acc.uuid)
.find(|a| a.uuid == acc.uuid) {
{ let mut changed = false;
if let Some(new_rt) = new_refresh {
stored.refresh_token = Some(new_rt); stored.refresh_token = Some(new_rt);
changed = true;
}
if let Some(expires) = new_expires {
stored.cached_mc_token = Some(token.clone());
stored.cached_mc_token_expires_at = Some(expires);
changed = true;
}
if changed {
account_store.save(); account_store.save();
} }
}
let user_type = match acc.account_type { let user_type = match acc.account_type {
crate::auth::AccountType::Microsoft => "msa", crate::auth::AccountType::Microsoft => "msa",
crate::auth::AccountType::Offline => "legacy", crate::auth::AccountType::Offline => "legacy",
@@ -277,25 +328,19 @@ pub async fn launch(
), ),
}; };
let mut game_args = vec![ let game_args = build_game_args(
"--username".to_string(), config,
mc_username, &minecraft_dir,
"--version".to_string(), meta_dir,
config.game_version.clone(), &meta.asset_index.id,
"--gameDir".to_string(), GameAuth {
minecraft_dir.to_string_lossy().into_owned(), username: mc_username,
"--assetsDir".to_string(), uuid: mc_uuid,
meta_dir.join("assets").to_string_lossy().into_owned(), token: mc_token,
"--assetIndex".to_string(), user_type: mc_user_type,
meta.asset_index.id.clone(), },
"--uuid".to_string(), loader_game_args,
mc_uuid, );
"--accessToken".to_string(),
mc_token,
"--userType".to_string(),
mc_user_type,
];
game_args.extend(loader_game_args);
let (kill_tx, kill_rx) = tokio::sync::oneshot::channel::<()>(); let (kill_tx, kill_rx) = tokio::sync::oneshot::channel::<()>();
crate::running::register_kill(&name, kill_tx); crate::running::register_kill(&name, kill_tx);
@@ -307,10 +352,24 @@ pub async fn launch(
config.loader config.loader
); );
tracing::info!("[{}] Java: {}", name, java);
tracing::info!("[{}] JVM args: {:?}", name, jvm);
tracing::info!(
"[{}] Classpath:\n{}",
name,
classpath
.iter()
.map(|p| p.display().to_string())
.collect::<Vec<_>>()
.join("\n")
);
tracing::info!("[{}] Main class: {}", name, main_class);
let mut cmd = tokio::process::Command::new(&java); let mut cmd = tokio::process::Command::new(&java);
cmd.args(&jvm); cmd.args(&jvm);
cmd.arg("-cp").arg(&cp_str); cmd.arg("-cp").arg(&cp_str);
cmd.arg(&main_class); cmd.arg(&main_class);
cmd.args(&extra_args);
cmd.args(&game_args); cmd.args(&game_args);
cmd.current_dir(&minecraft_dir); cmd.current_dir(&minecraft_dir);
cmd.stdout(std::process::Stdio::piped()); cmd.stdout(std::process::Stdio::piped());
@@ -353,9 +412,10 @@ pub async fn launch(
tracing::info!(target: "mc_instance", "[{}] {}", n, line); tracing::info!(target: "mc_instance", "[{}] {}", n, line);
crate::instance_logs::push(&n, &line); crate::instance_logs::push(&n, &line);
if let Ok(mut f) = w.lock() if let Ok(mut f) = w.lock()
&& let Some(f) = f.as_mut() { && let Some(f) = f.as_mut()
let _ = writeln!(f, "{}", line); {
} let _ = writeln!(f, "{}", line);
}
} }
}); });
} }
@@ -369,9 +429,10 @@ pub async fn launch(
tracing::warn!(target: "mc_instance", "[{}] {}", n, line); tracing::warn!(target: "mc_instance", "[{}] {}", n, line);
crate::instance_logs::push(&n, &line); crate::instance_logs::push(&n, &line);
if let Ok(mut f) = w.lock() if let Ok(mut f) = w.lock()
&& let Some(f) = f.as_mut() { && let Some(f) = f.as_mut()
let _ = writeln!(f, "[STDERR] {}", line); {
} let _ = writeln!(f, "[STDERR] {}", line);
}
} }
}); });
} }
@@ -411,99 +472,54 @@ pub async fn launch(
Ok(()) Ok(())
} }
// lwjgl3ify (used by GTNH and other old forge modpacks) bundles a #[cfg(test)]
// forgePatches.zip with patched launchwrapper classes that fix the mod tests {
// URLClassLoader cast on java 9+. if we find it, extract the patches use super::*;
// and prepend them to the classpath so they shadow the vanilla classes. use chrono::Utc;
// also parses Add-Opens from the zip's manifest for the required
// --add-opens flags.
fn apply_lwjgl3ify_patches(
minecraft_dir: &Path,
classpath: &mut Vec<PathBuf>,
) -> (Vec<String>, Option<String>) {
let mods_dir = minecraft_dir.join("mods");
let lwjgl3ify_jar = match find_lwjgl3ify_jar(&mods_dir) {
Some(p) => p,
None => return (Vec::new(), None),
};
let patches_dest = minecraft_dir.join(".forge-patches.zip"); fn test_config() -> InstanceConfig {
InstanceConfig {
if let Err(e) = extract_forge_patches(&lwjgl3ify_jar, &patches_dest) { name: "test".to_owned(),
tracing::warn!("Failed to extract lwjgl3ify forge patches: {e}"); game_version: "1.7.10".to_owned(),
return (Vec::new(), None); loader: ModLoader::Forge,
} loader_version: Some("10.13.4.1614".to_owned()),
created: Utc::now(),
// prepend so patched classes shadow vanilla launchwrapper last_played: None,
classpath.insert(0, patches_dest.clone()); java_path: None,
memory_max: None,
let mut jvm_args = parse_add_opens(&patches_dest).unwrap_or_default(); memory_min: None,
jvm_args: Vec::new(),
// RFB requires its own classloader to be the system classloader, and resolution: None,
// its Main class handles bootstrapping into launchwrapper.
// the other flags match lwjgl3ify's java9args.txt.
jvm_args.extend([
"-Djava.system.class.loader=com.gtnewhorizons.retrofuturabootstrap.RfbSystemClassLoader".to_string(),
"-Dfile.encoding=UTF-8".to_string(),
"--enable-native-access".to_string(),
"ALL-UNNAMED".to_string(),
]);
// also prepend the lwjgl3ify jar itself so RFB can find its plugin classes
classpath.insert(1, lwjgl3ify_jar);
let main_class = "com.gtnewhorizons.retrofuturabootstrap.Main".to_string();
(jvm_args, Some(main_class))
}
fn find_lwjgl3ify_jar(mods_dir: &Path) -> Option<PathBuf> {
let entries = std::fs::read_dir(mods_dir).ok()?;
for entry in entries.flatten() {
let name = entry.file_name();
let name = name.to_string_lossy();
if name.starts_with("lwjgl3ify") && name.ends_with(".jar") {
return Some(entry.path());
}
}
None
}
fn extract_forge_patches(lwjgl3ify_jar: &Path, dest: &Path) -> Result<(), std::io::Error> {
use std::io::Read;
let file = std::fs::File::open(lwjgl3ify_jar)?;
let mut archive = zip::ZipArchive::new(file)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
let mut entry = archive
.by_name("me/eigenraven/lwjgl3ify/relauncher/forgePatches.zip")
.map_err(|e| std::io::Error::new(std::io::ErrorKind::NotFound, e))?;
let mut buf = Vec::new();
entry.read_to_end(&mut buf)?;
std::fs::write(dest, &buf)
}
fn parse_add_opens(patches_zip: &Path) -> Option<Vec<String>> {
use std::io::Read;
let file = std::fs::File::open(patches_zip).ok()?;
let mut archive = zip::ZipArchive::new(file).ok()?;
let mut entry = archive.by_name("META-INF/MANIFEST.MF").ok()?;
let mut manifest = String::new();
entry.read_to_string(&mut manifest).ok()?;
// manifest continuation lines start with a single space
let manifest = manifest.replace("\r\n ", "").replace("\n ", "");
let mut args = Vec::new();
for line in manifest.lines() {
if let Some(value) = line.strip_prefix("Add-Opens: ") {
for module_package in value.split_whitespace() {
args.push("--add-opens".to_string());
args.push(format!("{module_package}=ALL-UNNAMED"));
}
} }
} }
Some(args) #[test]
fn game_args_include_empty_user_properties() {
let args = build_game_args(
&test_config(),
Path::new("/instances/test/.minecraft"),
Path::new("/meta"),
"legacy",
GameAuth {
username: "TestPlayer".to_owned(),
uuid: "00000000-0000-0000-0000-000000000000".to_owned(),
token: "token".to_owned(),
user_type: "msa".to_owned(),
},
vec![
"--tweakClass".to_owned(),
"cpw.mods.fml.common.launcher.FMLTweaker".to_owned(),
],
);
let position = args
.iter()
.position(|arg| arg == "--userProperties")
.expect("game args should include --userProperties");
assert_eq!(args.get(position + 1).map(String::as_str), Some("{}"));
assert!(
args.windows(2)
.any(|pair| pair == ["--tweakClass", "cpw.mods.fml.common.launcher.FMLTweaker"])
);
}
} }
+324
View File
@@ -0,0 +1,324 @@
// classpath and jvm patches for legacy forge on java 9+.
// lwjgl3ify ships a patched launchwrapper and retrofuturabootstrap that
// replace the old URLClassLoader-based launcher with one that works on
// modern java. this module handles extracting those patches, building
// the right --add-opens flags, and swapping out the broken log4j jars.
use std::path::{Path, PathBuf};
const LOG4J_FIXED_BASE: &str = "https://files.prismlauncher.org/maven/org/apache/logging/log4j";
pub struct LwjglifyPatches {
pub jvm_args: Vec<String>,
pub main_class: String,
// extra args inserted before game args (used by the shim to pass
// the real main class name)
pub extra_args: Vec<String>,
}
// checks if lwjgl3ify is present in the mods folder, and if so:
// 1. extracts forge patches from the lwjgl3ify jar
// 2. prepends them to the classpath so they shadow vanilla launchwrapper
// 3. parses --add-opens from the patches manifest
// 4. replaces log4j 2.0-beta9 with prism's patched builds
// 5. returns the jvm args and overridden main class
pub async fn apply(
minecraft_dir: &Path,
lib_dir: &Path,
classpath: &mut Vec<PathBuf>,
) -> Option<LwjglifyPatches> {
let mods_dir = minecraft_dir.join("mods");
let lwjgl3ify_jar = find_lwjgl3ify_jar(&mods_dir)?;
// rfb only scans jars for plugin metadata. keeping the extracted
// forgePatches payload as a zip makes it skip rfb-asm-safety and
// rfb-modern-java, which GTNH needs on modern Java.
let patches_dest = minecraft_dir.join(".forge-patches.jar");
if let Err(e) = extract_forge_patches(&lwjgl3ify_jar, &patches_dest) {
tracing::warn!("Failed to extract lwjgl3ify forge patches: {e}");
return None;
}
// prepend so patched classes shadow vanilla launchwrapper
classpath.insert(0, patches_dest.clone());
let mut jvm_args = parse_add_opens(&patches_dest).unwrap_or_default();
// RFB requires its own classloader to be the system classloader, and
// its Main class handles bootstrapping into launchwrapper.
// the other flags match lwjgl3ify's java9args.txt.
jvm_args.extend([
"-Djava.system.class.loader=com.gtnewhorizons.retrofuturabootstrap.RfbSystemClassLoader"
.to_string(),
"-Dfile.encoding=UTF-8".to_string(),
]);
// forge patches replace launchwrapper, asm, and old lwjgl2.
// lwjgl3ify redirects lwjgl2 calls to lwjgl3 at runtime, so lwjgl3
// must be on the classpath (matching what prism does).
strip_replaced_libs(classpath);
add_lwjgl3(lib_dir, classpath);
replace_log4j_fixed(lib_dir, classpath).await;
// on java 24+, SecurityManager.getClassContext() was reimplemented to use
// StackWalker. log4j 2.0-beta9's ThrowableProxy calls getClassContext() to
// resolve stack frames, but StackWalker triggers class loading through
// LaunchClassLoader, which debug-logs failures, which creates another
// ThrowableProxy... infinite recursion. we break the loop by providing a
// log4j config that sets the root level to INFO, so the debug() call in
// LaunchClassLoader is a no-op and never creates a ThrowableProxy.
write_log4j_config(minecraft_dir, &mut jvm_args);
// RfbSystemClassLoader discovers plugins differently depending on whether
// the main class is loaded by the JVM directly or through the system
// classloader's loadClass(). direct invocation misses the rfb-asm-safety
// and rfb-modern-java plugins from forgePatches, causing
// ClassCircularityErrors. we use a tiny shim jar that loads the real main
// class through ClassLoader.getSystemClassLoader().loadClass(), matching
// how prism's EntryPoint does it.
let shim_path = deploy_shim(minecraft_dir);
classpath.insert(0, shim_path);
Some(LwjglifyPatches {
jvm_args,
main_class: "MclShim".to_string(),
extra_args: vec!["com.gtnewhorizons.retrofuturabootstrap.Main".to_string()],
})
}
const SHIM_JAR: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/mcl-shim.jar"));
fn deploy_shim(minecraft_dir: &Path) -> PathBuf {
let dest = minecraft_dir.join(".mcl-shim.jar");
if let Err(e) = std::fs::write(&dest, SHIM_JAR) {
tracing::warn!("Failed to write mcl-shim.jar: {e}");
}
dest
}
fn find_lwjgl3ify_jar(mods_dir: &Path) -> Option<PathBuf> {
let entries = std::fs::read_dir(mods_dir).ok()?;
for entry in entries.flatten() {
let name = entry.file_name();
let name = name.to_string_lossy();
if name.starts_with("lwjgl3ify") && name.ends_with(".jar") {
return Some(entry.path());
}
}
None
}
fn extract_forge_patches(lwjgl3ify_jar: &Path, dest: &Path) -> Result<(), std::io::Error> {
use std::io::Read;
let file = std::fs::File::open(lwjgl3ify_jar)?;
let mut archive = zip::ZipArchive::new(file)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
let mut entry = archive
.by_name("me/eigenraven/lwjgl3ify/relauncher/forgePatches.zip")
.map_err(|e| std::io::Error::new(std::io::ErrorKind::NotFound, e))?;
let mut buf = Vec::new();
entry.read_to_end(&mut buf)?;
std::fs::write(dest, &buf)
}
fn parse_add_opens(patches_archive: &Path) -> Option<Vec<String>> {
use std::io::Read;
let file = std::fs::File::open(patches_archive).ok()?;
let mut archive = zip::ZipArchive::new(file).ok()?;
let mut entry = archive.by_name("META-INF/MANIFEST.MF").ok()?;
let mut manifest = String::new();
entry.read_to_string(&mut manifest).ok()?;
// manifest continuation lines start with a single space
let manifest = manifest.replace("\r\n ", "").replace("\n ", "");
let mut args = Vec::new();
for line in manifest.lines() {
if let Some(value) = line.strip_prefix("Add-Opens: ") {
for module_package in value.split_whitespace() {
args.push("--add-opens".to_string());
args.push(format!("{module_package}=ALL-UNNAMED"));
}
}
}
Some(args)
}
// strips libraries from the classpath that are replaced by forge patches
// or not needed with lwjgl3ify. matches what prism's component system does:
// no old lwjgl2, no vanilla launchwrapper/asm, no extra vanilla-only libs.
fn strip_replaced_libs(classpath: &mut Vec<PathBuf>) {
let replaced = [
"launchwrapper-",
"asm-all-",
"lwjgl-2.",
"lwjgl_util-",
"commons-compress-",
"commons-io-",
"guava-15.",
];
classpath.retain(|entry| {
let name = entry
.file_name()
.map(|n| n.to_string_lossy())
.unwrap_or_default();
let dominated = replaced.iter().any(|prefix| name.starts_with(prefix));
if dominated {
tracing::info!("Stripping {name} from classpath (replaced by forge-patches)");
}
!dominated
});
}
// adds lwjgl 3.3.3 to the classpath. lwjgl3ify redirects old lwjgl2 calls
// to lwjgl3 at runtime, but the lwjgl3 jars need to be on the system
// classpath for this to work. prism includes these via its org.lwjgl3
// component; we add them from the meta library cache.
fn add_lwjgl3(lib_dir: &Path, classpath: &mut Vec<PathBuf>) {
let lwjgl3_modules = [
"lwjgl",
"lwjgl-freetype",
"lwjgl-glfw",
"lwjgl-jemalloc",
"lwjgl-openal",
"lwjgl-opengl",
"lwjgl-stb",
"lwjgl-tinyfd",
];
let os_classifier = match std::env::consts::OS {
"macos" => "natives-macos",
"windows" => "natives-windows",
_ => "natives-linux",
};
// insert lwjgl3 jars right after forge patches (position 1+)
let mut insert_pos = 1.min(classpath.len());
for module in &lwjgl3_modules {
let base = if *module == "lwjgl" {
lib_dir.join("org/lwjgl/lwjgl/3.3.3/lwjgl-3.3.3.jar")
} else {
lib_dir.join(format!("org/lwjgl/{0}/3.3.3/{0}-3.3.3.jar", module))
};
if base.exists() {
classpath.insert(insert_pos, base);
insert_pos += 1;
}
// natives
let natives = if *module == "lwjgl" {
lib_dir.join(format!(
"org/lwjgl/lwjgl/3.3.3/lwjgl-3.3.3-{os_classifier}.jar"
))
} else {
lib_dir.join(format!(
"org/lwjgl/{0}/3.3.3/{0}-3.3.3-{1}.jar",
module, os_classifier
))
};
if natives.exists() {
classpath.insert(insert_pos, natives);
insert_pos += 1;
}
}
tracing::info!("Added {} LWJGL 3.3.3 jars to classpath", insert_pos - 1);
}
// writes a log4j2.xml config that sets the root logger to INFO. this
// prevents LaunchClassLoader's debug() call from ever firing, which
// avoids the ThrowableProxy -> SecurityManager -> StackWalker infinite
// recursion on java 24+. the config is written to .minecraft/ and
// pointed to via -Dlog4j.configurationFile.
fn write_log4j_config(minecraft_dir: &Path, jvm_args: &mut Vec<String>) {
let config_path = minecraft_dir.join(".mcl-log4j2.xml");
let config = r#"<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="SysOut" target="SYSTEM_OUT">
<PatternLayout pattern="[%d{HH:mm:ss}] [%t/%level] [%logger]: %msg%n"/>
</Console>
<Queue name="ServerGuiConsole">
<PatternLayout pattern="[%d{HH:mm:ss} %level]: %msg%n"/>
</Queue>
<RollingRandomAccessFile name="File" fileName="logs/latest.log"
filePattern="logs/%d{yyyy-MM-dd}-%i.log.gz">
<PatternLayout pattern="[%d{HH:mm:ss}] [%t/%level]: %msg%n"/>
<Policies>
<TimeBasedTriggeringPolicy/>
<OnStartupTriggeringPolicy/>
</Policies>
</RollingRandomAccessFile>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="SysOut"/>
<AppenderRef ref="File"/>
</Root>
</Loggers>
</Configuration>
"#;
if let Err(e) = std::fs::write(&config_path, config) {
tracing::warn!("Failed to write log4j2 config: {e}");
return;
}
jvm_args.push(format!(
"-Dlog4j.configurationFile={}",
config_path.display()
));
}
// replaces log4j-api and log4j-core 2.0-beta9 in the classpath with
// prism's patched "-fixed" builds. the vanilla 2.0-beta9 has a bug
// where ThrowableProxy calls SecurityManager.getClassContext() which
// on java 24+ uses StackWalker internally, triggering class loading
// through LaunchClassLoader, which triggers more logging, infinite
// recursion, stack overflow. the fixed builds patch this out.
async fn replace_log4j_fixed(lib_dir: &Path, classpath: &mut [PathBuf]) {
let replacements = [
(
"log4j-api-2.0-beta9.jar",
"org/apache/logging/log4j/log4j-api/2.0-beta9-fixed/log4j-api-2.0-beta9-fixed.jar",
format!("{LOG4J_FIXED_BASE}/log4j-api/2.0-beta9-fixed/log4j-api-2.0-beta9-fixed.jar"),
),
(
"log4j-core-2.0-beta9.jar",
"org/apache/logging/log4j/log4j-core/2.0-beta9-fixed/log4j-core-2.0-beta9-fixed.jar",
format!("{LOG4J_FIXED_BASE}/log4j-core/2.0-beta9-fixed/log4j-core-2.0-beta9-fixed.jar"),
),
];
for (old_name, fixed_rel, url) in &replacements {
let fixed_path = lib_dir.join(fixed_rel);
if !fixed_path.exists() {
tracing::info!("Downloading patched {old_name}...");
if let Some(parent) = fixed_path.parent() {
let _ = tokio::fs::create_dir_all(parent).await;
}
let client = crate::net::HttpClient::new();
if let Err(e) = crate::net::download_file(&client, url, &fixed_path, |_, _| {}).await {
tracing::error!("Failed to download patched {old_name}: {e}, continuing with unpatched version");
continue;
}
}
for entry in classpath.iter_mut() {
if entry
.file_name()
.is_some_and(|n| n.to_string_lossy() == *old_name)
{
tracing::info!("Replacing {old_name} with patched version");
*entry = fixed_path.clone();
}
}
}
}
+27
View File
@@ -387,6 +387,33 @@ mod tests {
std::fs::remove_dir_all(&tmp).ok(); std::fs::remove_dir_all(&tmp).ok();
} }
#[test]
fn test_load_all_accepts_numeric_memory() {
let (manager, tmp) = test_manager();
let instance_dir = tmp.join("test-memory");
std::fs::create_dir_all(&instance_dir).ok();
std::fs::write(
instance_dir.join("instance.json"),
r#"{
"name": "test-memory",
"game_version": "1.7.10",
"loader": "forge",
"loader_version": "10.13.4.1614",
"created": "2026-04-20T18:04:25.567993893Z",
"memory_max": 8,
"memory_min": 512
}"#,
)
.expect("write config");
let all = manager.load_all();
assert_eq!(all.len(), 1);
assert_eq!(all[0].memory_max.as_deref(), Some("8G"));
assert_eq!(all[0].memory_min.as_deref(), Some("512M"));
std::fs::remove_dir_all(&tmp).ok();
}
#[test] #[test]
fn test_load_one_not_found() { fn test_load_one_not_found() {
let (manager, tmp) = test_manager(); let (manager, tmp) = test_manager();
+1 -1
View File
@@ -14,4 +14,4 @@ pub use content::{scan_mods, toggle_entry, ContentEntry, scan_resource_packs, sc
pub use launch::LaunchError; pub use launch::LaunchError;
pub use loader::{get_installer, GameVersion, ModLoaderInstaller, VanillaInstaller}; pub use loader::{get_installer, GameVersion, ModLoaderInstaller, VanillaInstaller};
pub use manager::{InstanceError, InstanceManager}; pub use manager::{InstanceError, InstanceManager};
pub use models::{InstanceConfig, ModLoader}; pub use models::{normalize_memory_value, InstanceConfig, ModLoader};
+133
View File
@@ -3,6 +3,7 @@
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::fmt; use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
@@ -34,14 +35,92 @@ pub struct InstanceConfig {
pub loader: ModLoader, pub loader: ModLoader,
pub loader_version: Option<String>, pub loader_version: Option<String>,
pub created: DateTime<Utc>, pub created: DateTime<Utc>,
#[serde(default)]
pub last_played: Option<DateTime<Utc>>, pub last_played: Option<DateTime<Utc>>,
#[serde(default)]
pub java_path: Option<String>, pub java_path: Option<String>,
#[serde(default, deserialize_with = "deserialize_optional_memory")]
pub memory_max: Option<String>, pub memory_max: Option<String>,
#[serde(default, deserialize_with = "deserialize_optional_memory")]
pub memory_min: Option<String>, pub memory_min: Option<String>,
#[serde(default)]
pub jvm_args: Vec<String>, pub jvm_args: Vec<String>,
#[serde(default)]
pub resolution: Option<(u32, u32)>, pub resolution: Option<(u32, u32)>,
} }
pub fn normalize_memory_value(raw: &str) -> Option<String> {
let trimmed = raw.trim();
if trimmed.is_empty() {
return None;
}
let (digits, suffix) = match trimmed.chars().last() {
Some(c) if c.is_ascii_alphabetic() => {
(&trimmed[..trimmed.len() - c.len_utf8()], Some(c))
}
Some(_) => (trimmed, None),
None => return None,
};
if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_digit()) {
return None;
}
let value = digits.parse::<u64>().ok()?;
if value == 0 {
return None;
}
match suffix.map(|c| c.to_ascii_uppercase()) {
Some(unit @ ('K' | 'M' | 'G')) => Some(format!("{value}{unit}")),
Some(_) => None,
None => memory_number_to_string(value),
}
}
fn deserialize_optional_memory<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = Option::<Value>::deserialize(deserializer)?;
match value {
None | Some(Value::Null) => Ok(None),
Some(Value::String(raw)) => Ok(normalize_memory_value(&raw)),
Some(Value::Number(number)) => {
let number = if let Some(value) = number.as_u64() {
value
} else if let Some(value) = number.as_i64() {
let Ok(value) = u64::try_from(value) else {
return Ok(None);
};
value
} else {
let Some(value) = number.as_f64() else {
return Ok(None);
};
if !value.is_finite() || value.fract() != 0.0 || value < 0.0 {
return Ok(None);
}
value as u64
};
Ok(memory_number_to_string(number))
}
Some(_) => Ok(None),
}
}
fn memory_number_to_string(value: u64) -> Option<String> {
if value == 0 {
return None;
}
if value < 128 {
Some(format!("{value}G"))
} else {
Some(format!("{value}M"))
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -68,4 +147,58 @@ mod tests {
assert_eq!(parsed.loader, config.loader); assert_eq!(parsed.loader, config.loader);
assert_eq!(parsed.resolution, config.resolution); assert_eq!(parsed.resolution, config.resolution);
} }
#[test]
fn instance_config_accepts_numeric_memory() {
let json = r#"
{
"name": "test",
"game_version": "1.7.10",
"loader": "forge",
"loader_version": "10.13.4.1614",
"created": "2026-04-20T18:04:25.567993893Z",
"memory_max": 8,
"memory_min": 512
}
"#;
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"));
}
#[test]
fn normalize_memory_value_handles_bare_numbers() {
assert_eq!(normalize_memory_value("8").as_deref(), Some("8G"));
assert_eq!(normalize_memory_value("4096").as_deref(), Some("4096M"));
assert_eq!(normalize_memory_value("8G").as_deref(), Some("8G"));
assert_eq!(normalize_memory_value("2048m").as_deref(), Some("2048M"));
assert_eq!(normalize_memory_value(""), None);
}
#[test]
fn instance_config_ignores_invalid_memory_values() {
let json = r#"
{
"name": "test",
"game_version": "1.7.10",
"loader": "forge",
"loader_version": "10.13.4.1614",
"created": "2026-04-20T18:04:25.567993893Z",
"memory_max": ["8G"],
"memory_min": "8GB"
}
"#;
let parsed: InstanceConfig = serde_json::from_str(json).expect("deserialize");
assert_eq!(parsed.memory_max, None);
assert_eq!(parsed.memory_min, None);
}
#[test]
fn normalize_memory_value_rejects_invalid_values() {
assert_eq!(normalize_memory_value("0"), None);
assert_eq!(normalize_memory_value("-1"), None);
assert_eq!(normalize_memory_value("1.5G"), None);
assert_eq!(normalize_memory_value("8GB"), None);
assert_eq!(normalize_memory_value("banana"), None);
}
} }
+62 -10
View File
@@ -54,8 +54,10 @@ impl App {
terminal.draw(|frame| self.render_frame(frame))?; terminal.draw(|frame| self.render_frame(frame))?;
self.handle_events().wrap_err("handle events failed")?; self.handle_events().wrap_err("handle events failed")?;
if let Some(path) = self.pending_editor.take() { if let Some(path) = self.pending_editor.take()
Self::run_editor(terminal, &path); && Self::run_editor(terminal, &path)
{
self.reload_edited_config(&path);
} }
} }
Ok(()) Ok(())
@@ -149,7 +151,7 @@ impl App {
// spawns $EDITOR/$VISUAL to edit a file. for terminal editors (vim, nano, etc) // spawns $EDITOR/$VISUAL to edit a file. for terminal editors (vim, nano, etc)
// gotta leave the alternate screen and restore it after, otherwise the // gotta leave the alternate screen and restore it after, otherwise the
// editor fights with ratatui for the terminal. GUI editors just get spawned detached. // editor fights with ratatui for the terminal. GUI editors just get spawned detached.
fn run_editor(terminal: &mut ratatui::DefaultTerminal, path: &std::path::Path) { fn run_editor(terminal: &mut ratatui::DefaultTerminal, path: &std::path::Path) -> bool {
use ratatui::crossterm::{ use ratatui::crossterm::{
terminal::{ terminal::{
disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
@@ -199,20 +201,70 @@ impl App {
if let Err(e) = result { if let Err(e) = result {
tracing::error!("Failed to open editor: {}", e); tracing::error!("Failed to open editor: {}", e);
return false;
} }
} else { if let Err(e) = std::process::Command::new(&editor) true
.arg(path) } else {
.stdout(std::process::Stdio::null()) if let Err(e) = std::process::Command::new(&editor)
.stderr(std::process::Stdio::null()) .arg(path)
.spawn() { .stdout(std::process::Stdio::null())
tracing::error!("Failed to open editor: {}", e); .stderr(std::process::Stdio::null())
}} .spawn()
{
tracing::error!("Failed to open editor: {}", e);
return false;
}
false
}
}
fn reload_edited_config(&mut self, path: &std::path::Path) {
if path.file_name().and_then(|n| n.to_str()) != Some("instance.json") {
return;
}
let Some(name) = path
.parent()
.and_then(|p| p.file_name())
.and_then(|n| n.to_str())
else {
return;
};
match self.instance_manager.load_one(name) {
Ok(config) => {
self.instances_state.replace_instance(name, config);
}
Err(e) => {
tracing::error!("Failed to reload edited instance '{}': {}", name, e);
error_buffer::push_error(error_buffer::ErrorEvent {
id: 0,
level: tracing::Level::ERROR,
message: format!("Failed to reload edited instance '{name}': {e}"),
pushed_at: std::time::Instant::now(),
});
}
}
} }
pub(super) fn spawn_launch(&self, instance: crate::instance::InstanceConfig) { pub(super) fn spawn_launch(&self, instance: crate::instance::InstanceConfig) {
use crate::instance::launch; use crate::instance::launch;
use crate::running; use crate::running;
let instance = match self.instance_manager.load_one(&instance.name) {
Ok(config) => config,
Err(e) => {
tracing::error!("Failed to load instance '{}': {}", instance.name, e);
error_buffer::push_error(error_buffer::ErrorEvent {
id: 0,
level: tracing::Level::ERROR,
message: format!("Failed to load instance '{}': {e}", instance.name),
pushed_at: std::time::Instant::now(),
});
return;
}
};
running::set_state(&instance.name, running::RunState::Authenticating); running::set_state(&instance.name, running::RunState::Authenticating);
let instances_dir = self.instance_manager.instances_dir.clone(); let instances_dir = self.instance_manager.instances_dir.clone();
+4 -2
View File
@@ -54,12 +54,14 @@ pub fn init() -> WorkerGuard {
} }
} }
let file_appender = tracing_appender::rolling::daily(&log_dir, "mcl.log"); let now = chrono::Local::now().format("%Y-%m-%d_%H-%M-%S");
let file_appender = tracing_appender::rolling::never(&log_dir, format!("mcl_{now}.log"));
let (non_blocking, guard) = tracing_appender::non_blocking(file_appender); let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);
let env_filter = EnvFilter::builder() let env_filter = EnvFilter::builder()
.with_default_directive(Level::INFO.into()) .with_default_directive(Level::INFO.into())
.from_env_lossy(); .from_env_lossy()
.add_directive("mc_instance=off".parse().unwrap());
let rust_log = std::env::var("RUST_LOG").unwrap_or_default().to_lowercase(); let rust_log = std::env::var("RUST_LOG").unwrap_or_default().to_lowercase();
let tui_level = if rust_log.contains("debug") || rust_log.contains("trace") { let tui_level = if rust_log.contains("debug") || rust_log.contains("trace") {
+13
View File
@@ -149,6 +149,19 @@ impl State {
self.instances.push(instance); self.instances.push(instance);
self.update_scrollbar(); self.update_scrollbar();
} }
pub fn replace_instance(&mut self, old_name: &str, instance: InstanceConfig) {
if let Some(existing) = self
.instances
.iter_mut()
.find(|i| i.name == old_name || i.name == instance.name)
{
*existing = instance;
} else {
self.instances.push(instance);
}
self.update_scrollbar();
}
} }
impl WidgetKey for State { impl WidgetKey for State {