fix: switch default profile to terminal and fixed some comments

This commit is contained in:
objz committed 2026-04-18 19:44:59 +02:00
1 parent 971375bf1f
commit 52787b57c7
71 files changed
+671 -188

No files matched your search

+13 -12
View File
@@ -1,27 +1,32 @@
// scanning and toggling instance content (mods, resource packs, shaders, worlds).
// minecraft uses a ".disabled" suffix convention for disabled content, so this leans on that heavily.
pub mod mods;
pub mod resource_packs;
pub mod shaders;
pub mod worlds;
pub use mods::{scan_mods, toggle_entry, ContentEntry};
pub use mods::{ContentEntry, scan_mods, toggle_entry};
pub use resource_packs::scan_resource_packs;
pub use shaders::scan_shaders;
pub use worlds::scan_worlds;
use std::io::Read;
/// Determine enabled/disabled state and file stem from a filename.
///
/// Given the file extension (e.g. ".jar", ".zip") and the file name, returns
/// `Some((enabled, file_stem))` or `None` if the file doesn't match.
// figures out if a file is enabled or disabled based on the ".disabled" suffix,
// and strips the extension to get a clean stem name
pub(crate) fn parse_enabled_stem(file_name: &str, ext: &str) -> Option<(bool, String)> {
let disabled_ext = format!("{ext}.disabled");
if let Some(stem) = file_name.strip_suffix(&disabled_ext) {
Some((false, stem.to_string()))
} else { file_name.strip_suffix(ext).map(|stem| (true, stem.to_string())) }
} else {
file_name
.strip_suffix(ext)
.map(|stem| (true, stem.to_string()))
}
}
/// For directories: check if the name ends in `.disabled`.
// same idea but for directories, which don't have a file extension to strip
pub(crate) fn parse_enabled_stem_dir(file_name: &str) -> (bool, String) {
if let Some(stem) = file_name.strip_suffix(".disabled") {
(false, stem.to_string())
@@ -30,17 +35,13 @@ pub(crate) fn parse_enabled_stem_dir(file_name: &str) -> (bool, String) {
}
}
/// Read icon bytes from a zip archive (pack.png).
pub(crate) fn read_icon_from_zip(
archive: &mut zip::ZipArchive<std::fs::File>,
) -> Option<Vec<u8>> {
pub(crate) fn read_icon_from_zip(archive: &mut zip::ZipArchive<std::fs::File>) -> Option<Vec<u8>> {
let mut entry = archive.by_name("pack.png").ok()?;
let mut buf = Vec::new();
entry.read_to_end(&mut buf).ok()?;
Some(buf)
}
/// Open a zip file and return the archive handle.
pub(crate) fn open_zip(path: &std::path::Path) -> Option<zip::ZipArchive<std::fs::File>> {
let file = std::fs::File::open(path).ok()?;
zip::ZipArchive::new(file).ok()
+54 -9
View File
@@ -1,10 +1,14 @@
// mod scanning, metadata extraction, and icon rendering for the content list.
// jar files are just zips, so it cracks them open looking for fabric.mod.json to get
// names, descriptions, and icons. if that fails, just the filename is used. it's fine.
use std::io::Read;
use std::path::{Path, PathBuf};
use serde::Deserialize;
/// A single icon cell representing two vertically stacked pixels using the "▄" half-block.
/// `bg_*` = top pixel (background color), `fg_*` = bottom pixel (foreground color).
// a single "pixel" in the terminal icon. uses the unicode half-block trick
// where each character cell shows two vertical pixels (fg = top, bg = bottom)
#[derive(Debug, Clone, Copy)]
pub struct IconCell {
pub bg_r: u8,
@@ -37,6 +41,8 @@ struct FabricModJson {
}
impl FabricModJson {
// fabric's icon field can be a string path or a map of resolution -> path.
// if it's a map, just grab the first one. good enough.
fn icon_path(&self) -> String {
match &self.icon {
serde_json::Value::String(s) => s.clone(),
@@ -80,7 +86,11 @@ pub fn scan_mods(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry>
.and_then(|bytes| make_icon_pixels(bytes, 6, 3))
.or_else(|| Some(fallback_icon()));
let display_name = if name.is_empty() { file_stem.clone() } else { name };
let display_name = if name.is_empty() {
file_stem.clone()
} else {
name
};
entries.push(ContentEntry {
file_stem,
name: display_name,
@@ -96,6 +106,8 @@ pub fn scan_mods(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry>
entries
}
// tries fabric.mod.json first for rich metadata. if that's missing (forge/other mods),
// still attempts to grab pack.png as a last resort for an icon
fn read_mod_metadata(jar_path: &Path) -> (String, String, Option<Vec<u8>>) {
let file = match std::fs::File::open(jar_path) {
Ok(file) => file,
@@ -126,14 +138,15 @@ fn read_fabric_meta(
let mut entry = archive.by_name("fabric.mod.json").ok()?;
let mut raw = String::new();
entry.read_to_string(&mut raw).ok()?;
// Some mods have literal newlines in JSON strings — sanitize them
let sanitized = sanitize_json_strings(&raw);
let data: FabricModJson = serde_json::from_str(&sanitized).ok()?;
let icon = data.icon_path();
Some((data.name, data.description, icon))
}
/// Replace literal control characters inside JSON string values with escaped versions.
// some mod authors put raw newlines/tabs inside json string values which is
// technically invalid json. walks through character by character, tracking
// whether it's inside a string, and escapes the offending characters.
fn sanitize_json_strings(input: &str) -> String {
let mut result = String::with_capacity(input.len());
let mut in_string = false;
@@ -175,6 +188,8 @@ fn read_zip_bytes(archive: &mut zip::ZipArchive<std::fs::File>, path: &str) -> O
Some(bytes)
}
// downscales an icon to terminal resolution. resizes to height*2 because each
// terminal cell renders two vertical pixels using half-block characters (▀)
pub(crate) fn make_icon_pixels(
bytes: &[u8],
width: u16,
@@ -196,7 +211,14 @@ pub(crate) fn make_icon_pixels(
let bottom_y = (u32::from(row) * 2 + 1).min(rgb.height().saturating_sub(1));
let [tr, tg, tb] = rgb.get_pixel(u32::from(col), top_y).0;
let [br, bg, bb] = rgb.get_pixel(u32::from(col), bottom_y).0;
cols.push(IconCell { bg_r: br, bg_g: bg, bg_b: bb, fg_r: tr, fg_g: tg, fg_b: tb });
cols.push(IconCell {
bg_r: br,
bg_g: bg,
bg_b: bb,
fg_r: tr,
fg_g: tg,
fg_b: tb,
});
}
rows.push(cols);
}
@@ -206,9 +228,30 @@ pub(crate) fn make_icon_pixels(
/// 6x3 fallback icon showing a "?" pattern for mods without icons.
fn fallback_icon() -> Vec<Vec<IconCell>> {
let b = IconCell { bg_r: 50, bg_g: 50, bg_b: 50, fg_r: 50, fg_g: 50, fg_b: 50 };
let tb = IconCell { bg_r: 50, bg_g: 50, bg_b: 50, fg_r: 130, fg_g: 130, fg_b: 130 };
let bt = IconCell { bg_r: 130, bg_g: 130, bg_b: 130, fg_r: 50, fg_g: 50, fg_b: 50 };
let b = IconCell {
bg_r: 50,
bg_g: 50,
bg_b: 50,
fg_r: 50,
fg_g: 50,
fg_b: 50,
};
let tb = IconCell {
bg_r: 50,
bg_g: 50,
bg_b: 50,
fg_r: 130,
fg_g: 130,
fg_b: 130,
};
let bt = IconCell {
bg_r: 130,
bg_g: 130,
bg_b: 130,
fg_r: 50,
fg_g: 50,
fg_b: 50,
};
vec![
vec![b, tb, tb, tb, tb, b],
vec![b, b, b, bt, bt, b],
@@ -216,6 +259,8 @@ fn fallback_icon() -> Vec<Vec<IconCell>> {
]
}
// enable/disable by renaming the file with/without ".disabled" suffix.
// the minecraft way, apparently.
pub fn toggle_entry(entry: &ContentEntry) -> Result<(), std::io::Error> {
let file_name = match entry.path.file_name().and_then(|name| name.to_str()) {
Some(name) => name,
+6
View File
@@ -1,3 +1,7 @@
// resource pack scanning. packs can be either .zip files or plain directories,
// and metadata lives in pack.mcmeta (which mojang decided should have like 3
// different ways to encode a description, because why not)
use std::path::Path;
use serde::Deserialize;
@@ -16,6 +20,8 @@ pub(crate) struct PackInfo {
pub description: serde_json::Value,
}
// description can be a plain string, a chat component object with "text",
// or an array mixing both. thanks mojang, very cool.
pub(crate) fn extract_description(value: &serde_json::Value) -> String {
match value {
serde_json::Value::String(s) => s.clone(),
+3
View File
@@ -1,3 +1,6 @@
// shader pack scanning. structurally almost identical to resource packs
// (zip or dir, pack.mcmeta for metadata, pack.png for icon)
use std::path::Path;
use super::mods::{make_icon_pixels, ContentEntry};
+6
View File
@@ -1,3 +1,7 @@
// world save scanning. worlds are always directories (never zips) and store
// their icon as icon.png. also computes an approximate size from top-level
// files + region data so the user gets some sense of how chonky their world is.
use std::path::Path;
use super::mods::{make_icon_pixels, ContentEntry};
@@ -88,6 +92,8 @@ fn world_description(world_dir: &Path) -> String {
lines.join("\n")
}
// only counts top-level files + region/ contents, not a full recursive walk.
// good enough for a quick size estimate without blocking the UI on huge worlds.
fn dir_size_approx(path: &Path) -> u64 {
let mut total = 0u64;
if let Ok(rd) = std::fs::read_dir(path) {
+5 -1
View File
@@ -1,3 +1,6 @@
// creates OS-native shortcuts for launching instances directly:
// .desktop files on linux, .bat on windows, .command on macos
use std::path::{Path, PathBuf};
use crate::instance::models::InstanceConfig;
@@ -36,6 +39,7 @@ pub fn icon_path() -> Option<PathBuf> {
dirs_next::data_dir().map(|d| d.join("mcl").join("icon.svg"))
}
// lazily writes the bundled svg icon to disk the first time a shortcut needs it
fn ensure_icon() -> Option<PathBuf> {
let path = icon_path()?;
if path.exists() {
@@ -169,6 +173,7 @@ fn build_macos_command(name: &str) -> String {
out
}
// replaces anything that isn't alphanumeric, dash, or underscore with _
fn sanitize(name: &str) -> String {
name.chars()
.map(|c| {
@@ -199,7 +204,6 @@ mod tests {
#[test]
fn desktop_path_returns_some() {
let path = desktop_path("TestPack");
// On CI or minimal environments this may be None, but on most systems it should work
if let Some(p) = path {
let name = p.file_name().unwrap().to_str().unwrap();
assert!(name.contains("TestPack"));
+8
View File
@@ -1,3 +1,6 @@
// importing modrinth .mrpack modpacks: parse the manifest, create the instance,
// download all the mods, and extract config/resource overrides from the zip
use std::path::{Path, PathBuf};
use crate::instance::manager::InstanceManager;
@@ -39,6 +42,7 @@ pub fn build_summary(index: &MrpackIndex, mrpack_path: PathBuf) -> Result<Import
})
}
// peek into the zip to count files under overrides/ and client-overrides/
fn count_overrides(mrpack_path: &Path) -> Result<usize, String> {
let file = std::fs::File::open(mrpack_path).map_err(|e| e.to_string())?;
let archive = zip::ZipArchive::new(file).map_err(|e| e.to_string())?;
@@ -98,6 +102,8 @@ pub async fn execute_import(
Ok(config)
}
// downloads all mod files listed in the mrpack index, capped at 10 concurrent
// downloads to avoid getting rate-limited into oblivion
async fn download_mod_files(
index: &MrpackIndex,
minecraft_dir: &Path,
@@ -111,6 +117,8 @@ async fn download_mod_files(
progress::set_action(format!("Downloading mods... 0/{total}"));
// bounded concurrency via manual JoinSet draining: seed with max_concurrent
// tasks, then spawn a new one each time one finishes
let mut tasks = tokio::task::JoinSet::new();
let max_concurrent = 10;
let mut file_iter = index.files.iter();
+17
View File
@@ -1,3 +1,6 @@
// builds the full java command line and spawns minecraft as a child process.
// handles classpath assembly, auth token injection, and log capture.
use std::path::{Path, PathBuf};
use thiserror::Error;
@@ -18,6 +21,7 @@ pub enum LaunchError {
Auth(String),
}
// subset of mojang's version meta json, only the bits relevant to launching
#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct MetaJson {
@@ -70,6 +74,9 @@ struct LoaderLibrary {
name: String,
}
// 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
// included only if no rule "dominated" (matched at all). yes, it's weird.
fn lib_allowed(lib: &MetaLibrary) -> bool {
let Some(rules) = &lib.rules else {
return true;
@@ -139,6 +146,8 @@ pub async fn launch(
ModLoader::NeoForge => Some(format!("neoforge-{}.json", lv)),
};
// if there's a mod loader, read its profile to get the real main class
// and extra libraries it needs on the classpath
let main_class = if let Some(filename) = profile_filename {
let profile_path = meta_dir.join("loader-profiles").join(&filename);
if !profile_path.exists() {
@@ -149,6 +158,8 @@ pub async fn launch(
let profile: LoaderProfileJson =
serde_json::from_slice(&tokio::fs::read(&profile_path).await?)?;
// forge/neoforge install some libs locally in the instance dir, so
// both locations need to be checked
let has_local_libs = matches!(config.loader, ModLoader::Forge | ModLoader::NeoForge);
let local_lib_dir = minecraft_dir.join("libraries");
@@ -186,6 +197,7 @@ pub async fn launch(
.collect::<Vec<_>>()
.join(sep);
// java resolution: instance override > global setting > auto-detect
let java = config
.java_path
.clone()
@@ -203,6 +215,8 @@ pub async fn launch(
];
jvm.extend(config.jvm_args.clone());
// resolve auth credentials, refreshing the microsoft token if needed.
// falls back to a generic offline player if no account is configured.
let mut account_store = crate::auth::AccountStore::load();
let (mc_username, mc_uuid, mc_token, mc_user_type) = match account_store
.active_account()
@@ -303,6 +317,8 @@ pub async fn launch(
let instances_dir_owned = instances_dir.to_path_buf();
let meta_dir_owned = meta_dir.to_path_buf();
// spawn a background task to babysit the child process: capture stdout/stderr
// into both the TUI log viewer and a timestamped log file on disk
tokio::spawn(async move {
use std::io::Write;
use std::sync::{Arc, Mutex};
@@ -344,6 +360,7 @@ pub async fn launch(
});
}
// wait for either the process to exit naturally or a kill signal from the TUI
let code = tokio::select! {
_ = kill_rx => {
tracing::info!("[{}] Kill requested, terminating process", name_for_task);
+3
View File
@@ -1,3 +1,6 @@
// fabric installation. the nice one: just fetch a profile json and download
// the libraries. no java installer nonsense required.
use std::path::Path;
use async_trait::async_trait;
+7
View File
@@ -1,3 +1,7 @@
// forge installation. unlike fabric/quilt, forge ships a java-based installer
// that has to be downloaded and executed. yes, a jvm is needed just to install
// the thing that runs on a jvm. the installer jar gets cleaned up afterward.
use std::path::Path;
use async_trait::async_trait;
@@ -39,6 +43,7 @@ impl ModLoaderInstaller for ForgeInstaller {
forge_api::download_forge_installer(client, game_version, loader_version, &installer_jar)
.await?;
// use configured java or try to find one on PATH
let java_path = crate::config::SETTINGS
.paths
.effective_java_path()
@@ -47,6 +52,7 @@ impl ModLoaderInstaller for ForgeInstaller {
if let Err(e) =
forge_api::run_forge_installer(&installer_jar, instance_dir, &java_path).await
{
// still clean up even if installation failed
let _ = tokio::fs::remove_file(&installer_jar).await;
return Err(e);
}
@@ -55,6 +61,7 @@ impl ModLoaderInstaller for ForgeInstaller {
tracing::warn!("Failed to remove Forge installer JAR: {}", e);
}
// extract the profile from what the installer just wrote to disk
save_forge_profile(instance_dir, meta_dir, game_version, loader_version)?;
Ok(())
+15 -6
View File
@@ -1,8 +1,13 @@
mod vanilla;
// mod loader installation. each loader (fabric, forge, neoforge, quilt, vanilla)
// implements the same trait so the UI can treat them uniformly: pick game version,
// pick loader version, install. the actual installation strategies differ wildly
// though (fabric/quilt just download jars, forge/neoforge run a whole java installer).
mod fabric;
mod forge;
mod neoforge;
mod quilt;
mod vanilla;
use std::path::Path;
@@ -41,7 +46,6 @@ pub trait ModLoaderInstaller: Send + Sync {
) -> Result<(), NetError>;
}
/// Save a serializable loader profile JSON to `meta_dir/loader-profiles/<filename>`.
pub(crate) fn save_profile_json(
meta_dir: &Path,
filename: &str,
@@ -56,8 +60,9 @@ pub(crate) fn save_profile_json(
Ok(())
}
/// Read a Forge/NeoForge version JSON installed by the Java installer, extract
/// mainClass + libraries, and save a simplified profile to `meta_dir/loader-profiles/`.
// used by forge/neoforge. their java installer drops a version json into
// .minecraft/versions/. parses that to extract the main class and library
// list, then saves a stripped-down profile for use at launch time.
pub(crate) fn save_installer_profile(
instance_dir: &Path,
meta_dir: &Path,
@@ -90,8 +95,12 @@ pub(crate) fn save_installer_profile(
}
let raw = std::fs::read(&ver_json_path)?;
let ver: InstallerVersionJson = serde_json::from_slice(&raw)
.map_err(|e| NetError::Parse(format!("Invalid version JSON at {}: {e}", ver_json_path.display())))?;
let ver: InstallerVersionJson = serde_json::from_slice(&raw).map_err(|e| {
NetError::Parse(format!(
"Invalid version JSON at {}: {e}",
ver_json_path.display()
))
})?;
let libs: Vec<serde_json::Value> = ver
.libraries
+3
View File
@@ -1,3 +1,6 @@
// neoforge installation. same java installer dance as forge (they forked from it,
// after all), just with different URLs and version naming.
use std::path::Path;
use async_trait::async_trait;
+3
View File
@@ -1,3 +1,6 @@
// quilt installation. same clean approach as fabric (profile json + library
// downloads). they're basically fabric's cooler sibling.
use std::path::Path;
use async_trait::async_trait;
+4
View File
@@ -1,3 +1,7 @@
// vanilla "installer". doesn't actually install anything since the launch
// process already handles downloading vanilla assets/libraries. this just
// exists so vanilla fits the same ModLoaderInstaller trait as everyone else.
use std::path::Path;
use async_trait::async_trait;
+4
View File
@@ -1,3 +1,7 @@
// per-launch log files stored under .minecraft/logs/launches/
// each launch gets its own timestamped file so you can go back and see what
// crashed last tuesday at 3am
use std::path::{Path, PathBuf};
#[derive(Debug, Clone)]
+8
View File
@@ -1,3 +1,6 @@
// CRUD for instances: create, delete, rename, load, save.
// creation is the heavy one since it downloads the game, assets, and libraries.
use std::path::PathBuf;
use chrono::Utc;
@@ -23,6 +26,7 @@ pub enum InstanceError {
pub struct InstanceManager {
pub instances_dir: PathBuf,
/// shared across all instances: versions, libraries, assets
pub meta_dir: PathBuf,
client: crate::net::HttpClient,
}
@@ -52,6 +56,7 @@ impl InstanceManager {
return Err(InstanceError::AlreadyExists(name.to_string()));
}
// leftover directory without config = botched previous creation, nuke it
if instance_dir.exists() && !instance_json.exists() {
std::fs::remove_dir_all(&instance_dir)?;
}
@@ -62,6 +67,7 @@ impl InstanceManager {
.create_inner(name, game_version, loader, loader_version, &instance_dir)
.await;
// clean up on failure so there's no half-baked instance left around
if result.is_err() {
let _ = std::fs::remove_dir_all(&instance_dir);
}
@@ -82,6 +88,7 @@ impl InstanceManager {
std::fs::create_dir_all(minecraft_dir.join(subdir))?;
}
// forge insists on this file existing, even if it's empty json. thanks forge.
let launcher_profiles_path = minecraft_dir.join("launcher_profiles.json");
if !launcher_profiles_path.exists() {
std::fs::write(&launcher_profiles_path, "{}")?;
@@ -288,6 +295,7 @@ impl InstanceManager {
}
}
// guard against path traversal and other filesystem shenanigans
fn validate_name(name: &str) -> Result<(), InstanceError> {
if name.is_empty() || name.len() > 64 {
return Err(InstanceError::InvalidName(format!(
+2
View File
@@ -1,3 +1,5 @@
// instance management: creation, launching, importing modpacks, and all the
// bookkeeping that comes with pretending to be a real launcher
pub mod content;
pub mod desktop;
pub mod import;
+3
View File
@@ -1,3 +1,6 @@
// core data types for an instance: what loader it uses, what version, memory
// settings, etc. this is what gets persisted to instance.json
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::fmt;
+4
View File
@@ -1,5 +1,8 @@
use std::path::{Path, PathBuf};
// width/height are read from the actual image file so the TUI can show
// dimensions. falls back to 1920x1080 if the file is corrupt or unreadable
// because honestly, what else are you gonna pick
#[derive(Debug, Clone)]
pub struct ScreenshotEntry {
pub name: String,
@@ -38,6 +41,7 @@ pub fn scan_screenshots(instances_dir: &Path, instance_name: &str) -> Vec<Screen
})
.collect();
// sorted newest-first since minecraft names them with timestamps
entries.sort_by(|a, b| b.name.cmp(&a.name));
entries
}