feat(tui): instance launching, tabs, profiles overhaul
This commit is contained in:
1 parent
09d548272b
commit
46087c47a8
15 files changed
+813
-71
No files matched your search
@@ -0,0 +1,331 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::instance::models::{InstanceConfig, ModLoader};
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum LaunchError {
|
||||
#[error("Version metadata not found: {0}. Re-create the instance to fix this.")]
|
||||
MetaNotFound(String),
|
||||
#[error("IO error: {0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
#[error("JSON error: {0}")]
|
||||
Json(#[from] serde_json::Error),
|
||||
#[error("{0} launch is not yet supported")]
|
||||
NotSupported(String),
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct MetaJson {
|
||||
main_class: String,
|
||||
asset_index: MetaAssetIndex,
|
||||
libraries: Vec<MetaLibrary>,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct MetaAssetIndex {
|
||||
id: String,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct MetaLibrary {
|
||||
downloads: Option<MetaLibraryDownloads>,
|
||||
rules: Option<Vec<MetaRule>>,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct MetaLibraryDownloads {
|
||||
artifact: Option<MetaArtifact>,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct MetaArtifact {
|
||||
path: String,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct MetaRule {
|
||||
action: String,
|
||||
os: Option<MetaOsRule>,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct MetaOsRule {
|
||||
name: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct LoaderProfileJson {
|
||||
main_class: String,
|
||||
libraries: Vec<LoaderLibrary>,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct LoaderLibrary {
|
||||
name: String,
|
||||
}
|
||||
|
||||
fn lib_allowed(lib: &MetaLibrary) -> bool {
|
||||
let rules = match &lib.rules {
|
||||
Some(r) => r,
|
||||
None => return true,
|
||||
};
|
||||
let current_os = match std::env::consts::OS {
|
||||
"macos" => "osx",
|
||||
other => other,
|
||||
};
|
||||
let mut allowed = false;
|
||||
for rule in rules {
|
||||
let matches = match &rule.os {
|
||||
Some(os) => os.name.as_deref().map(|n| n == current_os).unwrap_or(true),
|
||||
None => true,
|
||||
};
|
||||
if !matches {
|
||||
continue;
|
||||
}
|
||||
if rule.action == "disallow" {
|
||||
return false;
|
||||
}
|
||||
if rule.action == "allow" {
|
||||
allowed = true;
|
||||
}
|
||||
}
|
||||
allowed
|
||||
}
|
||||
|
||||
pub async fn launch(
|
||||
config: &InstanceConfig,
|
||||
instances_dir: &Path,
|
||||
meta_dir: &Path,
|
||||
) -> Result<(), LaunchError> {
|
||||
let name = config.name.clone();
|
||||
let instance_dir = instances_dir.join(&name);
|
||||
let minecraft_dir = instance_dir.join(".minecraft");
|
||||
|
||||
let meta_path = meta_dir
|
||||
.join("versions")
|
||||
.join(&config.game_version)
|
||||
.join("meta.json");
|
||||
if !meta_path.exists() {
|
||||
return Err(LaunchError::MetaNotFound(meta_path.display().to_string()));
|
||||
}
|
||||
let meta: MetaJson = serde_json::from_slice(&std::fs::read(&meta_path)?)?;
|
||||
|
||||
let lib_dir = meta_dir.join("libraries");
|
||||
let mut classpath: Vec<PathBuf> = meta
|
||||
.libraries
|
||||
.iter()
|
||||
.filter(|l| lib_allowed(l))
|
||||
.filter_map(|l| l.downloads.as_ref()?.artifact.as_ref().map(|a| lib_dir.join(&a.path)))
|
||||
.collect();
|
||||
|
||||
let main_class = match config.loader {
|
||||
ModLoader::Vanilla => meta.main_class.clone(),
|
||||
ModLoader::Fabric => {
|
||||
let lv = config.loader_version.as_deref().unwrap_or("unknown");
|
||||
let profile_path = meta_dir
|
||||
.join("loader-profiles")
|
||||
.join(format!("fabric-{}-{}.json", config.game_version, lv));
|
||||
if !profile_path.exists() {
|
||||
return Err(LaunchError::MetaNotFound(profile_path.display().to_string()));
|
||||
}
|
||||
let profile: LoaderProfileJson =
|
||||
serde_json::from_slice(&std::fs::read(&profile_path)?)?;
|
||||
for lib in &profile.libraries {
|
||||
if let Some(p) = crate::net::maven_coord_to_path(&lib.name) {
|
||||
classpath.push(lib_dir.join(p));
|
||||
}
|
||||
}
|
||||
profile.main_class
|
||||
}
|
||||
ModLoader::Quilt => {
|
||||
let lv = config.loader_version.as_deref().unwrap_or("unknown");
|
||||
let profile_path = meta_dir
|
||||
.join("loader-profiles")
|
||||
.join(format!("quilt-{}-{}.json", config.game_version, lv));
|
||||
if !profile_path.exists() {
|
||||
return Err(LaunchError::MetaNotFound(profile_path.display().to_string()));
|
||||
}
|
||||
let profile: LoaderProfileJson =
|
||||
serde_json::from_slice(&std::fs::read(&profile_path)?)?;
|
||||
for lib in &profile.libraries {
|
||||
if let Some(p) = crate::net::maven_coord_to_path(&lib.name) {
|
||||
classpath.push(lib_dir.join(p));
|
||||
}
|
||||
}
|
||||
profile.main_class
|
||||
}
|
||||
ModLoader::Forge => {
|
||||
let lv = config.loader_version.as_deref().unwrap_or("unknown");
|
||||
let profile_path = meta_dir
|
||||
.join("loader-profiles")
|
||||
.join(format!("forge-{}-{}.json", config.game_version, lv));
|
||||
if !profile_path.exists() {
|
||||
return Err(LaunchError::MetaNotFound(profile_path.display().to_string()));
|
||||
}
|
||||
let profile: LoaderProfileJson =
|
||||
serde_json::from_slice(&std::fs::read(&profile_path)?)?;
|
||||
let forge_lib_dir = minecraft_dir.join("libraries");
|
||||
for lib in &profile.libraries {
|
||||
if let Some(p) = crate::net::maven_coord_to_path(&lib.name) {
|
||||
let in_meta = lib_dir.join(&p);
|
||||
let in_forge = forge_lib_dir.join(&p);
|
||||
if in_meta.exists() {
|
||||
classpath.push(in_meta);
|
||||
} else if in_forge.exists() {
|
||||
classpath.push(in_forge);
|
||||
}
|
||||
}
|
||||
}
|
||||
profile.main_class
|
||||
}
|
||||
ModLoader::NeoForge => {
|
||||
let lv = config.loader_version.as_deref().unwrap_or("unknown");
|
||||
let profile_path = meta_dir
|
||||
.join("loader-profiles")
|
||||
.join(format!("neoforge-{}.json", lv));
|
||||
if !profile_path.exists() {
|
||||
return Err(LaunchError::MetaNotFound(profile_path.display().to_string()));
|
||||
}
|
||||
let profile: LoaderProfileJson =
|
||||
serde_json::from_slice(&std::fs::read(&profile_path)?)?;
|
||||
let neo_lib_dir = minecraft_dir.join("libraries");
|
||||
for lib in &profile.libraries {
|
||||
if let Some(p) = crate::net::maven_coord_to_path(&lib.name) {
|
||||
let in_meta = lib_dir.join(&p);
|
||||
let in_neo = neo_lib_dir.join(&p);
|
||||
if in_meta.exists() {
|
||||
classpath.push(in_meta);
|
||||
} else if in_neo.exists() {
|
||||
classpath.push(in_neo);
|
||||
}
|
||||
}
|
||||
}
|
||||
profile.main_class
|
||||
}
|
||||
};
|
||||
|
||||
classpath.push(
|
||||
meta_dir
|
||||
.join("versions")
|
||||
.join(&config.game_version)
|
||||
.join(format!("{}.jar", config.game_version)),
|
||||
);
|
||||
|
||||
let sep = if cfg!(windows) { ";" } else { ":" };
|
||||
let cp_str = classpath
|
||||
.iter()
|
||||
.map(|p| p.to_string_lossy().into_owned())
|
||||
.collect::<Vec<_>>()
|
||||
.join(sep);
|
||||
|
||||
let java = config
|
||||
.java_path
|
||||
.clone()
|
||||
.unwrap_or_else(crate::net::detect_java_path);
|
||||
|
||||
let mut jvm: Vec<String> = vec![
|
||||
format!("-Xms{}", config.memory_min.as_deref().unwrap_or("512M")),
|
||||
format!("-Xmx{}", config.memory_max.as_deref().unwrap_or("2G")),
|
||||
];
|
||||
jvm.extend(config.jvm_args.clone());
|
||||
|
||||
let game_args = vec![
|
||||
"--username".to_string(),
|
||||
"Player".to_string(),
|
||||
"--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(),
|
||||
meta.asset_index.id.clone(),
|
||||
"--uuid".to_string(),
|
||||
"00000000-0000-0000-0000-000000000000".to_string(),
|
||||
"--accessToken".to_string(),
|
||||
"0".to_string(),
|
||||
"--userType".to_string(),
|
||||
"legacy".to_string(),
|
||||
];
|
||||
|
||||
crate::running::set_state(&name, crate::running::RunState::Starting);
|
||||
tracing::info!(
|
||||
"[{}] Starting Minecraft ({} {})",
|
||||
name,
|
||||
config.game_version,
|
||||
config.loader
|
||||
);
|
||||
|
||||
let mut cmd = tokio::process::Command::new(&java);
|
||||
cmd.args(&jvm);
|
||||
cmd.arg("-cp").arg(&cp_str);
|
||||
cmd.arg(&main_class);
|
||||
cmd.args(&game_args);
|
||||
cmd.current_dir(&minecraft_dir);
|
||||
cmd.stdout(std::process::Stdio::piped());
|
||||
cmd.stderr(std::process::Stdio::piped());
|
||||
|
||||
let mut child = match cmd.spawn() {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
crate::running::remove(&name);
|
||||
return Err(LaunchError::Io(e));
|
||||
}
|
||||
};
|
||||
|
||||
crate::running::set_state(&name, crate::running::RunState::Running);
|
||||
|
||||
let name_for_task = name.clone();
|
||||
let instances_dir_owned = instances_dir.to_path_buf();
|
||||
let meta_dir_owned = meta_dir.to_path_buf();
|
||||
|
||||
tokio::spawn(async move {
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
|
||||
if let Some(stdout) = child.stdout.take() {
|
||||
let n = name_for_task.clone();
|
||||
let mut lines = tokio::io::BufReader::new(stdout).lines();
|
||||
tokio::spawn(async move {
|
||||
while let Ok(Some(line)) = lines.next_line().await {
|
||||
tracing::info!(target: "mc_instance", "[{}] {}", n, line);
|
||||
crate::instance_logs::push(&n, &line);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(stderr) = child.stderr.take() {
|
||||
let n = name_for_task.clone();
|
||||
let mut lines = tokio::io::BufReader::new(stderr).lines();
|
||||
tokio::spawn(async move {
|
||||
while let Ok(Some(line)) = lines.next_line().await {
|
||||
tracing::warn!(target: "mc_instance", "[{}] {}", n, line);
|
||||
crate::instance_logs::push(&n, &line);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let code = child.wait().await.ok().and_then(|s| s.code());
|
||||
tracing::info!("[{}] Exited with code {:?}", name_for_task, code);
|
||||
|
||||
if code == Some(0) {
|
||||
crate::running::remove(&name_for_task);
|
||||
} else {
|
||||
crate::running::set_state(
|
||||
&name_for_task,
|
||||
crate::running::RunState::Crashed(code),
|
||||
);
|
||||
}
|
||||
|
||||
let manager = crate::instance::InstanceManager::new(instances_dir_owned, meta_dir_owned);
|
||||
if let Err(e) = manager.touch_last_played(&name_for_task) {
|
||||
tracing::warn!("Failed to update last_played for '{}': {}", name_for_task, e);
|
||||
}
|
||||
crate::running::push_last_played(&name_for_task, chrono::Utc::now());
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
+161
-2
@@ -145,6 +145,23 @@ impl ModLoaderInstaller for FabricInstaller {
|
||||
}
|
||||
}
|
||||
|
||||
let profiles_dir = meta_dir.join("loader-profiles");
|
||||
match std::fs::create_dir_all(&profiles_dir) {
|
||||
Ok(_) => {
|
||||
let profile_path =
|
||||
profiles_dir.join(format!("fabric-{}-{}.json", game_version, loader_version));
|
||||
match serde_json::to_string_pretty(&profile) {
|
||||
Ok(json) => {
|
||||
if let Err(e) = std::fs::write(&profile_path, &json) {
|
||||
tracing::warn!("Failed to save Fabric profile: {}", e);
|
||||
}
|
||||
}
|
||||
Err(e) => tracing::warn!("Failed to serialize Fabric profile: {}", e),
|
||||
}
|
||||
}
|
||||
Err(e) => tracing::warn!("Failed to create loader-profiles dir: {}", e),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -183,7 +200,7 @@ impl ModLoaderInstaller for ForgeInstaller {
|
||||
game_version: &str,
|
||||
loader_version: &str,
|
||||
instance_dir: &Path,
|
||||
_meta_dir: &Path,
|
||||
meta_dir: &Path,
|
||||
) -> Result<(), NetError> {
|
||||
let installer_jar = instance_dir.join(".minecraft").join("forge-installer.jar");
|
||||
|
||||
@@ -213,6 +230,68 @@ impl ModLoaderInstaller for ForgeInstaller {
|
||||
);
|
||||
}
|
||||
|
||||
let forge_ver_json = instance_dir
|
||||
.join(".minecraft")
|
||||
.join("versions")
|
||||
.join(format!("{}-forge-{}", game_version, loader_version))
|
||||
.join(format!("{}-forge-{}.json", game_version, loader_version));
|
||||
if forge_ver_json.exists() {
|
||||
#[derive(serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ForgeVersionJson {
|
||||
main_class: String,
|
||||
#[serde(default)]
|
||||
libraries: Vec<ForgeVersionLib>,
|
||||
}
|
||||
#[derive(serde::Deserialize)]
|
||||
struct ForgeVersionLib {
|
||||
name: String,
|
||||
}
|
||||
match std::fs::read(&forge_ver_json)
|
||||
.ok()
|
||||
.and_then(|b| serde_json::from_slice::<ForgeVersionJson>(&b).ok())
|
||||
{
|
||||
Some(forge_ver) => {
|
||||
let profile_dir = meta_dir.join("loader-profiles");
|
||||
match std::fs::create_dir_all(&profile_dir) {
|
||||
Ok(_) => {
|
||||
let profile_path = profile_dir
|
||||
.join(format!("forge-{}-{}.json", game_version, loader_version));
|
||||
let libs: Vec<serde_json::Value> = forge_ver
|
||||
.libraries
|
||||
.iter()
|
||||
.map(|l| serde_json::json!({"name": l.name}))
|
||||
.collect();
|
||||
let json_val = serde_json::json!({
|
||||
"mainClass": forge_ver.main_class,
|
||||
"libraries": libs
|
||||
});
|
||||
match serde_json::to_string_pretty(&json_val) {
|
||||
Ok(json) => {
|
||||
if let Err(e) = std::fs::write(&profile_path, &json) {
|
||||
tracing::warn!("Failed to save Forge profile: {}", e);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to serialize Forge profile: {}", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => tracing::warn!("Failed to create loader-profiles dir: {}", e),
|
||||
}
|
||||
}
|
||||
None => tracing::warn!(
|
||||
"Could not read Forge version JSON at {}",
|
||||
forge_ver_json.display()
|
||||
),
|
||||
}
|
||||
} else {
|
||||
tracing::warn!(
|
||||
"Forge version JSON not found at {} — profile not saved",
|
||||
forge_ver_json.display()
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -272,6 +351,23 @@ impl ModLoaderInstaller for QuiltInstaller {
|
||||
}
|
||||
}
|
||||
|
||||
let profiles_dir = meta_dir.join("loader-profiles");
|
||||
match std::fs::create_dir_all(&profiles_dir) {
|
||||
Ok(_) => {
|
||||
let profile_path =
|
||||
profiles_dir.join(format!("quilt-{}-{}.json", game_version, loader_version));
|
||||
match serde_json::to_string_pretty(&profile) {
|
||||
Ok(json) => {
|
||||
if let Err(e) = std::fs::write(&profile_path, &json) {
|
||||
tracing::warn!("Failed to save Quilt profile: {}", e);
|
||||
}
|
||||
}
|
||||
Err(e) => tracing::warn!("Failed to serialize Quilt profile: {}", e),
|
||||
}
|
||||
}
|
||||
Err(e) => tracing::warn!("Failed to create loader-profiles dir: {}", e),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -310,7 +406,7 @@ impl ModLoaderInstaller for NeoForgeInstaller {
|
||||
_game_version: &str,
|
||||
loader_version: &str,
|
||||
instance_dir: &Path,
|
||||
_meta_dir: &Path,
|
||||
meta_dir: &Path,
|
||||
) -> Result<(), NetError> {
|
||||
let installer_jar = instance_dir
|
||||
.join(".minecraft")
|
||||
@@ -340,6 +436,69 @@ impl ModLoaderInstaller for NeoForgeInstaller {
|
||||
);
|
||||
}
|
||||
|
||||
let neo_ver_json = instance_dir
|
||||
.join(".minecraft")
|
||||
.join("versions")
|
||||
.join(format!("neoforge-{}", loader_version))
|
||||
.join(format!("neoforge-{}.json", loader_version));
|
||||
if neo_ver_json.exists() {
|
||||
#[derive(serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ForgeVersionJson {
|
||||
main_class: String,
|
||||
#[serde(default)]
|
||||
libraries: Vec<ForgeVersionLib>,
|
||||
}
|
||||
#[derive(serde::Deserialize)]
|
||||
struct ForgeVersionLib {
|
||||
name: String,
|
||||
}
|
||||
match std::fs::read(&neo_ver_json)
|
||||
.ok()
|
||||
.and_then(|b| serde_json::from_slice::<ForgeVersionJson>(&b).ok())
|
||||
{
|
||||
Some(neo_ver) => {
|
||||
let profile_dir = meta_dir.join("loader-profiles");
|
||||
match std::fs::create_dir_all(&profile_dir) {
|
||||
Ok(_) => {
|
||||
let profile_path =
|
||||
profile_dir.join(format!("neoforge-{}.json", loader_version));
|
||||
let libs: Vec<serde_json::Value> = neo_ver
|
||||
.libraries
|
||||
.iter()
|
||||
.map(|l| serde_json::json!({"name": l.name}))
|
||||
.collect();
|
||||
let json_val = serde_json::json!({
|
||||
"mainClass": neo_ver.main_class,
|
||||
"libraries": libs
|
||||
});
|
||||
match serde_json::to_string_pretty(&json_val) {
|
||||
Ok(json) => {
|
||||
if let Err(e) = std::fs::write(&profile_path, &json) {
|
||||
tracing::warn!("Failed to save NeoForge profile: {}", e);
|
||||
}
|
||||
}
|
||||
Err(e) => tracing::warn!(
|
||||
"Failed to serialize NeoForge profile: {}",
|
||||
e
|
||||
),
|
||||
}
|
||||
}
|
||||
Err(e) => tracing::warn!("Failed to create loader-profiles dir: {}", e),
|
||||
}
|
||||
}
|
||||
None => tracing::warn!(
|
||||
"Could not read NeoForge version JSON at {}",
|
||||
neo_ver_json.display()
|
||||
),
|
||||
}
|
||||
} else {
|
||||
tracing::warn!(
|
||||
"NeoForge version JSON not found at {} — profile not saved",
|
||||
neo_ver_json.display()
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,6 +177,18 @@ impl InstanceManager {
|
||||
}
|
||||
}
|
||||
|
||||
let meta_json_path = self.meta_dir.join("versions").join(game_version).join("meta.json");
|
||||
match serde_json::to_string_pretty(&version_meta) {
|
||||
Ok(json) => {
|
||||
if let Err(e) = std::fs::write(&meta_json_path, &json) {
|
||||
tracing::warn!("Failed to save version meta: {}", e);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to serialize version meta: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
match crate::net::mojang::download_libraries(&self.client, &version_meta, &self.meta_dir).await {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
pub mod launch;
|
||||
pub mod manager;
|
||||
pub mod loader;
|
||||
pub mod models;
|
||||
|
||||
pub use launch::LaunchError;
|
||||
pub use manager::{InstanceError, InstanceManager};
|
||||
pub use loader::{get_installer, GameVersion, ModLoaderInstaller, VanillaInstaller};
|
||||
pub use models::{InstanceConfig, ModLoader};
|
||||
Reference in new issue
Block a user