From 46087c47a8657ce74108eff7caf7f136ae005650 Mon Sep 17 00:00:00 2001 From: objz Date: Sat, 1 Nov 2025 14:22:18 +0100 Subject: [PATCH] feat(tui): instance launching, tabs, profiles overhaul --- src/instance/launch.rs | 331 ++++++++++++++++++++++++++++++++++++ src/instance/loader.rs | 163 +++++++++++++++++- src/instance/manager.rs | 12 ++ src/instance/mod.rs | 2 + src/instance_logs.rs | 31 ++++ src/main.rs | 2 + src/net/fabric.rs | 6 +- src/net/mod.rs | 7 + src/net/mojang.rs | 26 +-- src/net/quilt.rs | 6 +- src/running.rs | 55 ++++++ src/tui/layout.rs | 60 ++++++- src/tui/widgets/content.rs | 110 +++++++++--- src/tui/widgets/profiles.rs | 34 +++- src/tui/widgets/status.rs | 39 ++--- 15 files changed, 813 insertions(+), 71 deletions(-) create mode 100644 src/instance/launch.rs create mode 100644 src/instance_logs.rs create mode 100644 src/running.rs diff --git a/src/instance/launch.rs b/src/instance/launch.rs new file mode 100644 index 0000000..8d6fb9c --- /dev/null +++ b/src/instance/launch.rs @@ -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, +} + +#[derive(serde::Deserialize)] +struct MetaAssetIndex { + id: String, +} + +#[derive(serde::Deserialize)] +struct MetaLibrary { + downloads: Option, + rules: Option>, +} + +#[derive(serde::Deserialize)] +struct MetaLibraryDownloads { + artifact: Option, +} + +#[derive(serde::Deserialize)] +struct MetaArtifact { + path: String, +} + +#[derive(serde::Deserialize)] +struct MetaRule { + action: String, + os: Option, +} + +#[derive(serde::Deserialize)] +struct MetaOsRule { + name: Option, +} + +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase")] +struct LoaderProfileJson { + main_class: String, + libraries: Vec, +} + +#[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 = 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::>() + .join(sep); + + let java = config + .java_path + .clone() + .unwrap_or_else(crate::net::detect_java_path); + + let mut jvm: Vec = 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(()) +} diff --git a/src/instance/loader.rs b/src/instance/loader.rs index cc18788..0ce8396 100644 --- a/src/instance/loader.rs +++ b/src/instance/loader.rs @@ -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, + } + #[derive(serde::Deserialize)] + struct ForgeVersionLib { + name: String, + } + match std::fs::read(&forge_ver_json) + .ok() + .and_then(|b| serde_json::from_slice::(&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 = 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, + } + #[derive(serde::Deserialize)] + struct ForgeVersionLib { + name: String, + } + match std::fs::read(&neo_ver_json) + .ok() + .and_then(|b| serde_json::from_slice::(&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 = 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(()) } } diff --git a/src/instance/manager.rs b/src/instance/manager.rs index a718abf..899a598 100644 --- a/src/instance/manager.rs +++ b/src/instance/manager.rs @@ -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) => { diff --git a/src/instance/mod.rs b/src/instance/mod.rs index b62f903..9cf717d 100644 --- a/src/instance/mod.rs +++ b/src/instance/mod.rs @@ -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}; diff --git a/src/instance_logs.rs b/src/instance_logs.rs new file mode 100644 index 0000000..6406bb7 --- /dev/null +++ b/src/instance_logs.rs @@ -0,0 +1,31 @@ +use once_cell::sync::Lazy; +use std::collections::{HashMap, VecDeque}; +use std::sync::{Arc, Mutex}; + +const MAX_LINES: usize = 2000; + +pub static LOGS: Lazy>>>> = + Lazy::new(|| Arc::new(Mutex::new(HashMap::new()))); + +pub fn push(name: &str, line: impl Into) { + if let Ok(mut logs) = LOGS.lock() { + let buf = logs.entry(name.to_string()).or_insert_with(VecDeque::new); + buf.push_back(line.into()); + while buf.len() > MAX_LINES { + buf.pop_front(); + } + } +} + +pub fn get_all(name: &str) -> Vec { + LOGS.lock() + .ok() + .and_then(|logs| logs.get(name).map(|buf| buf.iter().cloned().collect())) + .unwrap_or_default() +} + +pub fn clear(name: &str) { + if let Ok(mut logs) = LOGS.lock() { + logs.remove(name); + } +} diff --git a/src/main.rs b/src/main.rs index c23e010..17030a0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,6 +2,8 @@ mod cli; pub mod config; pub mod instance; pub mod net; +pub mod instance_logs; +pub mod running; pub mod tui; #[tokio::main] diff --git a/src/net/fabric.rs b/src/net/fabric.rs index 052810a..44c9f17 100644 --- a/src/net/fabric.rs +++ b/src/net/fabric.rs @@ -1,6 +1,6 @@ use std::path::Path; -use serde::Deserialize; +use serde::{Deserialize, Serialize}; use crate::instance::loader::GameVersion; use crate::net::{download_file, HttpClient, NetError}; @@ -27,7 +27,7 @@ pub struct FabricGameVersion { pub stable: bool, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct FabricProfile { pub id: String, @@ -35,7 +35,7 @@ pub struct FabricProfile { pub libraries: Vec, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct FabricLibrary { pub name: String, pub url: String, diff --git a/src/net/mod.rs b/src/net/mod.rs index 3b196e4..c93a527 100644 --- a/src/net/mod.rs +++ b/src/net/mod.rs @@ -136,6 +136,13 @@ pub fn maven_coord_to_path(coord: &str) -> Option { group_path, artifact, version, artifact, version )) } + [group, artifact, version, classifier] => { + let group_path = group.replace('.', "/"); + Some(format!( + "{}/{}/{}/{}-{}-{}.jar", + group_path, artifact, version, artifact, version, classifier + )) + } _ => None, } } diff --git a/src/net/mojang.rs b/src/net/mojang.rs index ef5794e..8d8b600 100644 --- a/src/net/mojang.rs +++ b/src/net/mojang.rs @@ -17,19 +17,19 @@ const MANIFEST_URL: &str = "https://piston-meta.mojang.com/mc/game/version_manif const ASSETS_BASE_URL: &str = "https://resources.download.minecraft.net"; const MAX_CONCURRENT_DOWNLOADS: usize = 10; -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct VersionManifest { pub latest: LatestVersions, pub versions: Vec, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct LatestVersions { pub release: String, pub snapshot: String, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct VersionEntry { pub id: String, #[serde(rename = "type")] @@ -38,7 +38,7 @@ pub struct VersionEntry { pub sha1: String, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct VersionMeta { pub id: String, @@ -49,38 +49,38 @@ pub struct VersionMeta { pub java_version: Option, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct AssetIndex { pub id: String, pub url: String, pub sha1: String, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct VersionDownloads { pub client: Download, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct Download { pub url: String, pub sha1: String, pub size: u64, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct Library { pub name: String, pub downloads: LibraryDownloads, pub rules: Option>, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct LibraryDownloads { pub artifact: Option, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct Artifact { pub url: String, pub path: String, @@ -88,18 +88,18 @@ pub struct Artifact { pub size: u64, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct Rule { pub action: String, pub os: Option, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct OsRule { pub name: Option, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct JavaVersion { pub major_version: u32, diff --git a/src/net/quilt.rs b/src/net/quilt.rs index c431b23..80ce4ba 100644 --- a/src/net/quilt.rs +++ b/src/net/quilt.rs @@ -1,6 +1,6 @@ use std::path::Path; -use serde::Deserialize; +use serde::{Deserialize, Serialize}; use crate::instance::loader::GameVersion; use crate::net::{download_file, HttpClient, NetError}; @@ -24,7 +24,7 @@ pub struct QuiltGameVersion { pub stable: bool, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct QuiltProfile { pub id: String, @@ -32,7 +32,7 @@ pub struct QuiltProfile { pub libraries: Vec, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct QuiltLibrary { pub name: String, pub url: String, diff --git a/src/running.rs b/src/running.rs new file mode 100644 index 0000000..b2d876f --- /dev/null +++ b/src/running.rs @@ -0,0 +1,55 @@ +use chrono::{DateTime, Utc}; +use once_cell::sync::Lazy; +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +#[derive(Debug, Clone, PartialEq)] +pub enum RunState { + Starting, + Running, + Crashed(Option), +} + +pub static RUNNING: Lazy>>> = + Lazy::new(|| Arc::new(Mutex::new(HashMap::new()))); + +pub static PENDING_LAST_PLAYED: Lazy)>>>> = + Lazy::new(|| Arc::new(Mutex::new(Vec::new()))); + +pub fn set_state(name: &str, state: RunState) { + if let Ok(mut map) = RUNNING.lock() { + map.insert(name.to_string(), state); + } +} + +pub fn remove(name: &str) { + if let Ok(mut map) = RUNNING.lock() { + map.remove(name); + } +} + +pub fn get(name: &str) -> Option { + RUNNING.lock().ok().and_then(|map| map.get(name).cloned()) +} + +pub fn all() -> Vec<(String, RunState)> { + RUNNING + .lock() + .ok() + .map(|map| map.iter().map(|(k, v)| (k.clone(), v.clone())).collect()) + .unwrap_or_default() +} + +pub fn push_last_played(name: &str, time: DateTime) { + if let Ok(mut q) = PENDING_LAST_PLAYED.lock() { + q.push((name.to_string(), time)); + } +} + +pub fn drain_last_played() -> Vec<(String, DateTime)> { + PENDING_LAST_PLAYED + .lock() + .ok() + .map(|mut q| q.drain(..).collect()) + .unwrap_or_default() +} diff --git a/src/tui/layout.rs b/src/tui/layout.rs index eb2ca18..06e74fd 100644 --- a/src/tui/layout.rs +++ b/src/tui/layout.rs @@ -105,6 +105,7 @@ impl App { self.dismiss_expired_errors(); self.drain_pending_instances(); + self.drain_pending_last_played(); self.throbber_state.calc_next(); tui_logger::move_events(); terminal.draw(|frame| self.render_frame(frame))?; @@ -139,7 +140,13 @@ impl App { self.focused, self.profiles_state.selected_instance(), ); - widgets::content::render(frame, main_chunks[1], self.focused, self.content_tab); + widgets::content::render( + frame, + main_chunks[1], + self.focused, + self.content_tab, + self.profiles_state.selected_instance(), + ); let bottom_chunks = Layout::default() .direction(Direction::Horizontal) @@ -293,6 +300,22 @@ impl App { self.focused = FocusedArea::ConfirmDelete; } } + KeyCode::Enter + if self.focused == FocusedArea::Profiles + && !self.profiles_state.search.active => + { + if let Some(instance) = self.profiles_state.selected_instance().cloned() { + let can_launch = matches!( + crate::running::get(&instance.name), + None | Some(crate::running::RunState::Crashed(_)) + ); + if can_launch { + crate::running::remove(&instance.name); + crate::instance_logs::clear(&instance.name); + self.spawn_launch(instance); + } + } + } _ => {} } @@ -345,6 +368,30 @@ impl App { }); } + fn spawn_launch(&self, instance: crate::instance::InstanceConfig) { + use crate::instance::launch; + use crate::{running, tui::error_buffer}; + + let instances_dir = self.instance_manager.instances_dir.clone(); + let meta_dir = self.instance_manager.meta_dir.clone(); + + tokio::spawn(async move { + match launch::launch(&instance, &instances_dir, &meta_dir).await { + Ok(()) => {} + Err(e) => { + tracing::error!("Launch failed for '{}': {}", instance.name, e); + running::remove(&instance.name); + error_buffer::push_error(error_buffer::ErrorEvent { + id: 0, + level: tracing::Level::ERROR, + message: format!("Failed to launch '{}': {}", instance.name, e), + pushed_at: std::time::Instant::now(), + }); + } + } + }); + } + fn dismiss_expired_errors(&self) { loop { match error_buffer::peek_error() { @@ -369,6 +416,17 @@ impl App { } } + fn drain_pending_last_played(&mut self) { + for (name, time) in crate::running::drain_last_played() { + for inst in &mut self.profiles_state.instances { + if inst.name == name { + inst.last_played = Some(time); + break; + } + } + } + } + fn render_log_overlay(frame: &mut Frame, log_state: &mut tui_logger::TuiWidgetState) { use crate::tui::theme::THEME; use ratatui::{ diff --git a/src/tui/widgets/content.rs b/src/tui/widgets/content.rs index bbc97b8..3940bcb 100644 --- a/src/tui/widgets/content.rs +++ b/src/tui/widgets/content.rs @@ -1,7 +1,7 @@ use ratatui::{ layout::{Alignment, Constraint, Layout, Rect}, style::{Modifier, Style}, - text::Span, + text::{Line, Span}, widgets::{Block, BorderType, Borders, Paragraph, Tabs}, Frame, }; @@ -9,8 +9,6 @@ use ratatui::{ use crate::tui::layout::FocusedArea; use crate::tui::theme::THEME; -use super::styled_title; - #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] pub enum ContentTab { #[default] @@ -61,7 +59,22 @@ impl ContentTab { } } -pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, tab: ContentTab) { +fn spinner_char() -> char { + const FRAMES: &[char] = &['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']; + let ms = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_millis(); + FRAMES[(ms / 100) as usize % FRAMES.len()] +} + +pub fn render( + frame: &mut Frame, + area: Rect, + focused: FocusedArea, + tab: ContentTab, + instance: Option<&crate::instance::InstanceConfig>, +) { let border_color = if focused == FocusedArea::Content { THEME.colors.border_focused } else { @@ -94,19 +107,42 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, tab: ContentT frame.render_widget(tabs, tabs_area); - let body = match tab { - ContentTab::Mods => "No mods installed.", - ContentTab::ResourcePacks => "No resource packs installed.", - ContentTab::Shaders => "No shaders installed.", - ContentTab::Screenshots => "No screenshots.", - ContentTab::Worlds => "No worlds saved.", - ContentTab::Logs => "No logs yet.", - }; + match tab { + ContentTab::Logs => { + let lines = instance + .map(|i| crate::instance_logs::get_all(&i.name)) + .unwrap_or_default(); + if lines.is_empty() { + frame.render_widget( + Paragraph::new("No logs yet.") + .style(Style::default().fg(THEME.colors.text_idle)), + content_area, + ); + } else { + frame.render_widget( + Paragraph::new(lines.join("\n")) + .style(Style::default().fg(THEME.colors.text_idle)) + .wrap(ratatui::widgets::Wrap { trim: false }), + content_area, + ); + } + } + _ => { + let body = match tab { + ContentTab::Mods => "No mods installed.", + ContentTab::ResourcePacks => "No resource packs installed.", + ContentTab::Shaders => "No shaders installed.", + ContentTab::Screenshots => "No screenshots.", + ContentTab::Worlds => "No worlds saved.", + ContentTab::Logs => unreachable!(), + }; - frame.render_widget( - Paragraph::new(body).style(Style::default().fg(THEME.colors.text_idle)), - content_area, - ); + frame.render_widget( + Paragraph::new(body).style(Style::default().fg(THEME.colors.text_idle)), + content_area, + ); + } + } } pub fn title( @@ -122,7 +158,6 @@ pub fn title( }; let block = Block::default() - .title(styled_title("Content", true)) .borders(Borders::ALL) .border_type(BorderType::Rounded) .border_style(Style::default().fg(color)); @@ -142,14 +177,45 @@ pub fn title( let [left_area, right_area] = Layout::horizontal([Constraint::Min(0), Constraint::Length(32)]).areas(inner); - frame.render_widget( - Paragraph::new(inst.name.as_str()).style( + use crate::running::RunState; + + let run_state = crate::running::get(&inst.name); + let (prefix, prefix_style) = match run_state { + Some(RunState::Running) | Some(RunState::Starting) => ( + format!("{} ", spinner_char()), + Style::default() + .fg(THEME.colors.success) + .add_modifier(Modifier::BOLD), + ), + Some(RunState::Crashed(_)) => ( + String::from("\u{2717} "), + Style::default() + .fg(THEME.colors.error) + .add_modifier(Modifier::BOLD), + ), + None => (String::new(), Style::default()), + }; + + let name_line = if prefix.is_empty() { + Line::from(Span::styled( + inst.name.as_str(), Style::default() .fg(THEME.colors.foreground) .add_modifier(Modifier::BOLD), - ), - left_area, - ); + )) + } else { + Line::from(vec![ + Span::styled(prefix, prefix_style), + Span::styled( + inst.name.as_str(), + Style::default() + .fg(THEME.colors.foreground) + .add_modifier(Modifier::BOLD), + ), + ]) + }; + + frame.render_widget(Paragraph::new(name_line), left_area); let loader_str = match &inst.loader_version { Some(lv) => format!("{} \u{00b7} {} {}", inst.game_version, inst.loader, lv), diff --git a/src/tui/widgets/profiles.rs b/src/tui/widgets/profiles.rs index 43f5064..eadec63 100644 --- a/src/tui/widgets/profiles.rs +++ b/src/tui/widgets/profiles.rs @@ -9,6 +9,7 @@ use ratatui::{ use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView}; use crate::instance::models::InstanceConfig; +use crate::running::{get as get_run_state, RunState}; use crate::tui::{layout::FocusedArea, theme::THEME}; use super::{popups, search::SearchState, styled_title, WidgetKey}; @@ -225,7 +226,7 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut S Style::default() .fg(THEME.colors.row_highlight) .add_modifier(Modifier::BOLD), - Style::default().fg(THEME.colors.foreground), + Style::default().fg(THEME.colors.row_highlight), THEME.colors.row_alternate_bg, ) } else { @@ -238,16 +239,37 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut S ) }; - let indicator = Span::styled( - "\u{258c} ", - Style::default().fg(loader_color(instance.loader)), - ); + let run_state = get_run_state(&instance.name); + let indicator = match &run_state { + Some(RunState::Running) | Some(RunState::Starting) => { + Span::styled("\u{25c9} ", Style::default().fg(THEME.colors.success)) + } + Some(RunState::Crashed(_)) => { + Span::styled("\u{2717} ", Style::default().fg(THEME.colors.error)) + } + None => Span::styled( + "\u{258c} ", + Style::default().fg(loader_color(instance.loader)), + ), + }; let name_line = Line::from(vec![ indicator, Span::styled(instance.name.as_str(), name_style), ]); + let meta_indicator = match &run_state { + Some(RunState::Running) | Some(RunState::Starting) => { + Span::styled("\u{258c} ", Style::default().fg(THEME.colors.success)) + } + Some(RunState::Crashed(_)) => { + Span::styled("\u{258c} ", Style::default().fg(THEME.colors.error)) + } + None => Span::styled( + "\u{258c} ", + Style::default().fg(loader_color(instance.loader)), + ), + }; let meta_line = Line::from(vec![ - Span::raw(" "), + meta_indicator, Span::styled(format_last_played(instance.last_played), meta_style), ]); diff --git a/src/tui/widgets/status.rs b/src/tui/widgets/status.rs index 9a4f049..c31fa2a 100644 --- a/src/tui/widgets/status.rs +++ b/src/tui/widgets/status.rs @@ -34,21 +34,27 @@ pub fn render( let state = match PROGRESS.lock() { Ok(s) => s.clone(), Err(_) => { - let idle = Paragraph::new(Span::styled( - "Ready", - Style::default().fg(THEME.colors.text_idle), - )); - frame.render_widget(idle.block(block), area); + frame.render_widget( + Paragraph::new(Span::styled( + "Ready", + Style::default().fg(THEME.colors.text_idle), + )) + .block(block), + area, + ); return; } }; if state.current_action.is_none() { - let idle = Paragraph::new(Span::styled( - "Ready", - Style::default().fg(THEME.colors.text_idle), - )); - frame.render_widget(idle.block(block), area); + frame.render_widget( + Paragraph::new(Span::styled( + "Ready", + Style::default().fg(THEME.colors.text_idle), + )) + .block(block), + area, + ); return; } @@ -67,12 +73,7 @@ pub fn render( ]) .split(inner); - let ratio = if total > 0 { - (current as f64 / total as f64).min(1.0) - } else { - 0.0 - }; - let pct = (ratio * 100.0) as u16; + let ratio = (current as f64 / total as f64).min(1.0); let gauge = Gauge::default() .gauge_style( Style::default() @@ -80,14 +81,12 @@ pub fn render( .bg(THEME.colors.progress_track) .add_modifier(Modifier::BOLD), ) - .percent(pct); + .percent((ratio * 100.0) as u16); frame.render_widget(gauge, chunks[0]); - frame.render_widget( Paragraph::new(action_text).style(Style::default().fg(THEME.colors.foreground)), chunks[1], ); - if !sub_text.is_empty() { frame.render_widget( Paragraph::new(sub_text) @@ -99,7 +98,6 @@ pub fn render( _ => { let chunks = Layout::vertical([Constraint::Length(1), Constraint::Length(1)]).split(inner); - let throbber = Throbber::default() .label(action_text) .style(Style::default().fg(THEME.colors.foreground)) @@ -109,7 +107,6 @@ pub fn render( .add_modifier(Modifier::BOLD), ); frame.render_stateful_widget(throbber, chunks[0], throbber_state); - if !sub_text.is_empty() { frame.render_widget( Paragraph::new(sub_text)