From e861e52d43e93478690c3a20903639f7773b8ce8 Mon Sep 17 00:00:00 2001 From: HsiangNianian Date: Wed, 14 Jan 2026 16:37:23 +0800 Subject: feat: add Fabric and Forge loader support modules with version fetching and installation functionality --- src-tauri/src/core/fabric.rs | 269 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 269 insertions(+) create mode 100644 src-tauri/src/core/fabric.rs (limited to 'src-tauri/src/core/fabric.rs') diff --git a/src-tauri/src/core/fabric.rs b/src-tauri/src/core/fabric.rs new file mode 100644 index 0000000..8fc960f --- /dev/null +++ b/src-tauri/src/core/fabric.rs @@ -0,0 +1,269 @@ +//! Fabric Loader support module. +//! +//! This module provides functionality to: +//! - Fetch available Fabric loader versions from the Fabric Meta API +//! - Generate version JSON files for Fabric-enabled Minecraft versions +//! - Install Fabric loader for a specific Minecraft version + +use serde::{Deserialize, Serialize}; +use std::error::Error; +use std::path::PathBuf; + +const FABRIC_META_URL: &str = "https://meta.fabricmc.net/v2"; + +/// Represents a Fabric loader version from the Meta API. +#[derive(Debug, Deserialize, Serialize, Clone)] +pub struct FabricLoaderVersion { + pub separator: String, + pub build: i32, + pub maven: String, + pub version: String, + pub stable: bool, +} + +/// Represents a Fabric intermediary mapping version. +#[derive(Debug, Deserialize, Serialize, Clone)] +pub struct FabricIntermediaryVersion { + pub maven: String, + pub version: String, + pub stable: bool, +} + +/// Represents a combined loader + intermediary version entry. +#[derive(Debug, Deserialize, Serialize, Clone)] +pub struct FabricLoaderEntry { + pub loader: FabricLoaderVersion, + pub intermediary: FabricIntermediaryVersion, + #[serde(rename = "launcherMeta")] + pub launcher_meta: FabricLauncherMeta, +} + +/// Launcher metadata from Fabric Meta API. +#[derive(Debug, Deserialize, Serialize, Clone)] +pub struct FabricLauncherMeta { + pub version: i32, + pub libraries: FabricLibraries, + #[serde(rename = "mainClass")] + pub main_class: FabricMainClass, +} + +/// Libraries required by Fabric loader. +#[derive(Debug, Deserialize, Serialize, Clone)] +pub struct FabricLibraries { + pub client: Vec, + pub common: Vec, + pub server: Vec, +} + +/// A single Fabric library dependency. +#[derive(Debug, Deserialize, Serialize, Clone)] +pub struct FabricLibrary { + pub name: String, + pub url: Option, +} + +/// Main class configuration for Fabric. +#[derive(Debug, Deserialize, Serialize, Clone)] +pub struct FabricMainClass { + pub client: String, + pub server: String, +} + +/// Represents a Minecraft version supported by Fabric. +#[derive(Debug, Deserialize, Serialize, Clone)] +pub struct FabricGameVersion { + pub version: String, + pub stable: bool, +} + +/// Information about an installed Fabric version. +#[derive(Debug, Serialize, Clone)] +pub struct InstalledFabricVersion { + pub id: String, + pub minecraft_version: String, + pub loader_version: String, + pub path: PathBuf, +} + +/// Fetch all Minecraft versions supported by Fabric. +/// +/// # Returns +/// A list of game versions that have Fabric intermediary mappings available. +pub async fn fetch_supported_game_versions() -> Result, Box> { + let url = format!("{}/versions/game", FABRIC_META_URL); + let resp = reqwest::get(&url) + .await? + .json::>() + .await?; + Ok(resp) +} + +/// Fetch all available Fabric loader versions. +/// +/// # Returns +/// A list of all Fabric loader versions, ordered by build number (newest first). +pub async fn fetch_loader_versions() -> Result, Box> { + let url = format!("{}/versions/loader", FABRIC_META_URL); + let resp = reqwest::get(&url) + .await? + .json::>() + .await?; + Ok(resp) +} + +/// Fetch Fabric loader versions available for a specific Minecraft version. +/// +/// # Arguments +/// * `game_version` - The Minecraft version (e.g., "1.20.4") +/// +/// # Returns +/// A list of loader entries with full metadata for the specified game version. +pub async fn fetch_loaders_for_game_version( + game_version: &str, +) -> Result, Box> { + let url = format!("{}/versions/loader/{}", FABRIC_META_URL, game_version); + let resp = reqwest::get(&url) + .await? + .json::>() + .await?; + Ok(resp) +} + +/// Fetch the version JSON profile for a specific Fabric loader + game version combination. +/// +/// # Arguments +/// * `game_version` - The Minecraft version (e.g., "1.20.4") +/// * `loader_version` - The Fabric loader version (e.g., "0.15.6") +/// +/// # Returns +/// The raw version JSON as a `serde_json::Value` that can be saved to the versions directory. +pub async fn fetch_version_profile( + game_version: &str, + loader_version: &str, +) -> Result> { + let url = format!( + "{}/versions/loader/{}/{}/profile/json", + FABRIC_META_URL, game_version, loader_version + ); + let resp = reqwest::get(&url).await?.json::().await?; + Ok(resp) +} + +/// Generate the version ID for a Fabric installation. +/// +/// # Arguments +/// * `game_version` - The Minecraft version +/// * `loader_version` - The Fabric loader version +/// +/// # Returns +/// The version ID string (e.g., "fabric-loader-0.15.6-1.20.4") +pub fn generate_version_id(game_version: &str, loader_version: &str) -> String { + format!("fabric-loader-{}-{}", loader_version, game_version) +} + +/// Install Fabric loader for a specific Minecraft version. +/// +/// This creates the version JSON file in the versions directory. +/// The actual library downloads happen during game launch. +/// +/// # Arguments +/// * `game_dir` - The .minecraft directory path +/// * `game_version` - The Minecraft version (e.g., "1.20.4") +/// * `loader_version` - The Fabric loader version (e.g., "0.15.6") +/// +/// # Returns +/// Information about the installed version. +pub async fn install_fabric( + game_dir: &PathBuf, + game_version: &str, + loader_version: &str, +) -> Result> { + // Fetch the version profile from Fabric Meta + let profile = fetch_version_profile(game_version, loader_version).await?; + + // Get the version ID from the profile or generate it + let version_id = profile + .get("id") + .and_then(|v| v.as_str()) + .map(|s| s.to_string()) + .unwrap_or_else(|| generate_version_id(game_version, loader_version)); + + // Create the version directory + let version_dir = game_dir.join("versions").join(&version_id); + tokio::fs::create_dir_all(&version_dir).await?; + + // Write the version JSON + let json_path = version_dir.join(format!("{}.json", version_id)); + let json_content = serde_json::to_string_pretty(&profile)?; + tokio::fs::write(&json_path, json_content).await?; + + Ok(InstalledFabricVersion { + id: version_id, + minecraft_version: game_version.to_string(), + loader_version: loader_version.to_string(), + path: json_path, + }) +} + +/// Check if Fabric is installed for a specific version combination. +/// +/// # Arguments +/// * `game_dir` - The .minecraft directory path +/// * `game_version` - The Minecraft version +/// * `loader_version` - The Fabric loader version +/// +/// # Returns +/// `true` if the version JSON exists, `false` otherwise. +pub fn is_fabric_installed(game_dir: &PathBuf, game_version: &str, loader_version: &str) -> bool { + let version_id = generate_version_id(game_version, loader_version); + let json_path = game_dir + .join("versions") + .join(&version_id) + .join(format!("{}.json", version_id)); + json_path.exists() +} + +/// List all installed Fabric versions in the game directory. +/// +/// # Arguments +/// * `game_dir` - The .minecraft directory path +/// +/// # Returns +/// A list of installed Fabric version IDs. +pub async fn list_installed_fabric_versions( + game_dir: &PathBuf, +) -> Result, Box> { + let versions_dir = game_dir.join("versions"); + let mut installed = Vec::new(); + + if !versions_dir.exists() { + return Ok(installed); + } + + let mut entries = tokio::fs::read_dir(&versions_dir).await?; + while let Some(entry) = entries.next_entry().await? { + let name = entry.file_name().to_string_lossy().to_string(); + if name.starts_with("fabric-loader-") { + // Verify the JSON file exists + let json_path = entry.path().join(format!("{}.json", name)); + if json_path.exists() { + installed.push(name); + } + } + } + + Ok(installed) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_generate_version_id() { + assert_eq!( + generate_version_id("1.20.4", "0.15.6"), + "fabric-loader-0.15.6-1.20.4" + ); + } +} -- cgit v1.2.3-70-g09d2 From 9193112aca842dbe4d723aa865a7a30f3bcdb691 Mon Sep 17 00:00:00 2001 From: HsiangNianian Date: Wed, 14 Jan 2026 16:44:56 +0800 Subject: refactor: clean up formatting and improve readability in core modules --- src-tauri/src/core/fabric.rs | 11 ++++++++--- src-tauri/src/core/forge.rs | 13 ++++++++----- src-tauri/src/core/manifest.rs | 6 +++--- src-tauri/src/core/maven.rs | 15 ++++++++++++--- src-tauri/src/main.rs | 35 ++++++++++++++++------------------- 5 files changed, 47 insertions(+), 33 deletions(-) (limited to 'src-tauri/src/core/fabric.rs') diff --git a/src-tauri/src/core/fabric.rs b/src-tauri/src/core/fabric.rs index 8fc960f..fd38f41 100644 --- a/src-tauri/src/core/fabric.rs +++ b/src-tauri/src/core/fabric.rs @@ -89,7 +89,8 @@ pub struct InstalledFabricVersion { /// /// # Returns /// A list of game versions that have Fabric intermediary mappings available. -pub async fn fetch_supported_game_versions() -> Result, Box> { +pub async fn fetch_supported_game_versions( +) -> Result, Box> { let url = format!("{}/versions/game", FABRIC_META_URL); let resp = reqwest::get(&url) .await? @@ -102,7 +103,8 @@ pub async fn fetch_supported_game_versions() -> Result, B /// /// # Returns /// A list of all Fabric loader versions, ordered by build number (newest first). -pub async fn fetch_loader_versions() -> Result, Box> { +pub async fn fetch_loader_versions( +) -> Result, Box> { let url = format!("{}/versions/loader", FABRIC_META_URL); let resp = reqwest::get(&url) .await? @@ -145,7 +147,10 @@ pub async fn fetch_version_profile( "{}/versions/loader/{}/{}/profile/json", FABRIC_META_URL, game_version, loader_version ); - let resp = reqwest::get(&url).await?.json::().await?; + let resp = reqwest::get(&url) + .await? + .json::() + .await?; Ok(resp) } diff --git a/src-tauri/src/core/forge.rs b/src-tauri/src/core/forge.rs index 7b951ff..0f17bcc 100644 --- a/src-tauri/src/core/forge.rs +++ b/src-tauri/src/core/forge.rs @@ -48,7 +48,7 @@ pub struct InstalledForgeVersion { /// A list of Minecraft version strings that have Forge available. pub async fn fetch_supported_game_versions() -> Result, Box> { let promos = fetch_promotions().await?; - + let mut versions: Vec = promos .promos .keys() @@ -62,12 +62,12 @@ pub async fn fetch_supported_game_versions() -> Result, Box Result> { let version_id = generate_version_id(game_version, forge_version); - + // Create basic version JSON structure // Note: This is a simplified version. Full Forge installation requires // downloading the installer and running processors. @@ -206,7 +206,10 @@ fn create_forge_version_json( vec![ create_library_entry(&forge_maven_coord, Some(FORGE_MAVEN_URL)), create_library_entry( - &format!("net.minecraftforge:forge:{}-{}:universal", game_version, forge_version), + &format!( + "net.minecraftforge:forge:{}-{}:universal", + game_version, forge_version + ), Some(FORGE_MAVEN_URL), ), ], diff --git a/src-tauri/src/core/manifest.rs b/src-tauri/src/core/manifest.rs index 2fea811..bae87c9 100644 --- a/src-tauri/src/core/manifest.rs +++ b/src-tauri/src/core/manifest.rs @@ -74,7 +74,7 @@ pub async fn fetch_vanilla_version( ) -> Result> { // First, get the manifest to find the version URL let manifest = fetch_version_manifest().await?; - + let version_entry = manifest .versions .iter() @@ -86,7 +86,7 @@ pub async fn fetch_vanilla_version( .await? .json::() .await?; - + Ok(resp) } @@ -121,7 +121,7 @@ pub async fn load_version( Ok(v) => v, Err(_) => fetch_vanilla_version(&parent_id).await?, }; - + // Merge child into parent version = crate::core::version_merge::merge_versions(version, parent); } diff --git a/src-tauri/src/core/maven.rs b/src-tauri/src/core/maven.rs index a930e05..8c89768 100644 --- a/src-tauri/src/core/maven.rs +++ b/src-tauri/src/core/maven.rs @@ -101,7 +101,10 @@ impl MavenCoordinate { } }; - format!("{}/{}/{}/{}", group_path, self.artifact, self.version, filename) + format!( + "{}/{}/{}/{}", + group_path, self.artifact, self.version, filename + ) } /// Get the local file path for storing this artifact. @@ -142,7 +145,11 @@ impl MavenCoordinate { /// /// # Returns /// The resolved download URL -pub fn resolve_library_url(name: &str, explicit_url: Option<&str>, maven_url: Option<&str>) -> Option { +pub fn resolve_library_url( + name: &str, + explicit_url: Option<&str>, + maven_url: Option<&str>, +) -> Option { // If there's an explicit URL, use it if let Some(url) = explicit_url { return Some(url.to_string()); @@ -156,7 +163,9 @@ pub fn resolve_library_url(name: &str, explicit_url: Option<&str>, maven_url: Op // Guess the repository based on group if coord.group.starts_with("net.fabricmc") { FABRIC_MAVEN - } else if coord.group.starts_with("net.minecraftforge") || coord.group.starts_with("cpw.mods") { + } else if coord.group.starts_with("net.minecraftforge") + || coord.group.starts_with("cpw.mods") + { FORGE_MAVEN } else { MOJANG_LIBRARIES diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index 2261273..ba16f7a 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -41,7 +41,7 @@ impl MsRefreshTokenState { } /// Check if a string contains unresolved placeholders in the form ${...} -/// +/// /// After the replacement phase, if a string still contains ${...}, it means /// that placeholder variable was not found in the replacements map and is /// therefore unresolved. We should skip adding such arguments to avoid @@ -119,11 +119,11 @@ async fn start_game( window, format!("Loading version details for {}...", version_id) ); - + let version_details = core::manifest::load_version(&game_dir, &version_id) .await .map_err(|e| e.to_string())?; - + emit_log!( window, format!( @@ -145,7 +145,9 @@ async fn start_game( // --- Client Jar --- // Get downloads from version_details (may be inherited) - let downloads = version_details.downloads.as_ref() + let downloads = version_details + .downloads + .as_ref() .ok_or("Version has no downloads information")?; let client_jar = &downloads.client; let mut client_path = game_dir.join("versions"); @@ -222,12 +224,11 @@ async fn start_game( } else { // 3. Library without explicit downloads (mod loader libraries) // Use Maven coordinate resolution - if let Some(url) = core::maven::resolve_library_url( - &lib.name, - None, - lib.url.as_deref(), - ) { - if let Some(lib_path) = core::maven::get_library_path(&lib.name, &libraries_dir) { + if let Some(url) = + core::maven::resolve_library_url(&lib.name, None, lib.url.as_deref()) + { + if let Some(lib_path) = core::maven::get_library_path(&lib.name, &libraries_dir) + { download_tasks.push(core::downloader::DownloadTask { url, path: lib_path, @@ -246,7 +247,9 @@ async fn start_game( let indexes_dir = assets_dir.join("indexes"); // Get asset index (may be inherited from parent) - let asset_index = version_details.asset_index.as_ref() + let asset_index = version_details + .asset_index + .as_ref() .ok_or("Version has no asset index information")?; // Download Asset Index JSON @@ -262,10 +265,7 @@ async fn start_game( .await .map_err(|e| e.to_string())? } else { - println!( - "Downloading asset index from {}", - asset_index.url - ); + println!("Downloading asset index from {}", asset_index.url); let content = reqwest::get(&asset_index.url) .await .map_err(|e| e.to_string())? @@ -426,10 +426,7 @@ async fn start_game( replacements.insert("${version_name}", version_id.clone()); replacements.insert("${game_directory}", game_dir.to_string_lossy().to_string()); replacements.insert("${assets_root}", assets_dir.to_string_lossy().to_string()); - replacements.insert( - "${assets_index_name}", - asset_index.id.clone(), - ); + replacements.insert("${assets_index_name}", asset_index.id.clone()); replacements.insert("${auth_uuid}", account.uuid()); replacements.insert("${auth_access_token}", account.access_token()); replacements.insert("${user_type}", "mojang".to_string()); -- cgit v1.2.3-70-g09d2