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

+1 -1
View File
@@ -5,7 +5,7 @@
# custom themes:
# theme = "my-theme" (loads ~/.config/mcl/theme/my-theme.toml)
# theme = "/path/to/file" (loads from absolute path)
theme = "catppuccin"
theme = "terminal"
# rounded, plain, double, thick
border_style = "rounded"
+12 -5
View File
@@ -1,3 +1,5 @@
// account management: persistence, switching active accounts, and offline uuid generation
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
@@ -41,10 +43,11 @@ impl AccountStore {
pub fn save(&self) {
if let Some(parent) = self.path.parent()
&& let Err(e) = std::fs::create_dir_all(parent) {
tracing::error!("Failed to create accounts directory: {}", e);
return;
}
&& let Err(e) = std::fs::create_dir_all(parent)
{
tracing::error!("Failed to create accounts directory: {}", e);
return;
}
match serde_json::to_string_pretty(&self.accounts) {
Ok(json) => {
if let Err(e) = std::fs::write(&self.path, json) {
@@ -66,6 +69,8 @@ impl AccountStore {
self.save();
}
// if an account with the same uuid already exists, replace it.
// first account added auto-becomes active so there's always a selection.
pub fn add(&mut self, account: Account) {
let uuid = &account.uuid;
self.accounts.retain(|a| a.uuid != *uuid);
@@ -93,7 +98,9 @@ pub fn account_store_path() -> PathBuf {
crate::config::get_config_path().join("accounts.json")
}
/// Generate a deterministic offline-mode UUID for a username.
// deterministic fake uuid from a username, formatted as uuid v3 with the proper
// version and variant bits set. not cryptographically meaningful, just needs to
// be consistent so the same offline name always maps to the same uuid.
pub fn offline_uuid(username: &str) -> String {
use std::hash::{DefaultHasher, Hash, Hasher};
let mut hasher = DefaultHasher::new();
+1
View File
@@ -1,3 +1,4 @@
// auth module: account storage (offline + microsoft) and the oauth device code flow
mod accounts;
mod oauth;
+10
View File
@@ -1,3 +1,7 @@
// microsoft oauth device code flow for minecraft authentication.
// the flow goes: MSA device code -> MSA token -> xbox/mc token exchange -> mc profile fetch.
// device code auth is used because it works without a redirect URI, which is nice for a TUI.
use std::sync::{Arc, LazyLock, Mutex};
use minecraft_msa_auth::MinecraftAuthorizationFlow;
@@ -28,6 +32,7 @@ struct McProfile {
name: String,
}
// shared slot so the TUI can poll for the device code to show the user
pub static DEVICE_CODE_DISPLAY: LazyLock<Arc<Mutex<Option<DeviceCodeInfo>>>> =
LazyLock::new(|| Arc::new(Mutex::new(None)));
@@ -68,6 +73,8 @@ async fn run_full_oauth_flow() -> Result<(String, Option<String>), String> {
Ok((ms_access_token, ms_refresh_token))
}
// kicks off auth on a background task, returns a mutex the caller can poll for the result.
// the TUI checks DEVICE_CODE_DISPLAY for the code to show, and this mutex for completion.
pub fn start_microsoft_auth() -> Arc<Mutex<Option<AuthResult>>> {
let result: Arc<Mutex<Option<AuthResult>>> = Arc::new(Mutex::new(None));
let result_clone = result.clone();
@@ -124,6 +131,7 @@ async fn exchange_and_build_account(
Err(e) => return AuthResult::Error(format!("Profile parse failed: {e}")),
};
// mojang returns uuids without dashes because of course they do
let uuid = if profile.id.len() == 32 {
format!(
"{}-{}-{}-{}-{}",
@@ -146,6 +154,8 @@ async fn exchange_and_build_account(
})
}
// returns (mc_access_token, new_refresh_token). for offline accounts it just
// hands back a dummy token since the server doesn't care.
pub async fn refresh_and_get_token(account: &Account) -> Result<(String, Option<String>), String> {
match account.account_type {
AccountType::Offline => Ok(("0".to_owned(), None)),
+8
View File
@@ -1,3 +1,4 @@
// cli handlers for account management (microsoft oauth + offline accounts)
use std::io;
use std::time::Duration;
@@ -18,6 +19,7 @@ pub async fn handle_account(matches: &ArgMatches) -> CliResult {
}
}
// trait indirection so a mock store can be swapped in for tests
trait AccountStoreLike {
fn accounts(&self) -> &[Account];
fn add_account(&mut self, account: Account);
@@ -65,6 +67,10 @@ async fn add_account(matches: &ArgMatches) -> CliResult {
Ok(())
}
// microsoft auth runs on a background thread via device code flow.
// polls two shared slots: one for the device code to display,
// then one for the final auth result. not the prettiest pattern
// but it keeps the oauth complexity out of the CLI layer.
async fn add_microsoft_account() -> CliResult {
if let Ok(mut slot) = crate::auth::DEVICE_CODE_DISPLAY.lock() {
*slot = None;
@@ -72,6 +78,7 @@ async fn add_microsoft_account() -> CliResult {
let result_arc = crate::auth::start_microsoft_auth();
// wait for the device code to become available before showing it
loop {
if let Ok(slot) = crate::auth::DEVICE_CODE_DISPLAY.lock()
&& let Some(info) = slot.as_ref() {
@@ -82,6 +89,7 @@ async fn add_microsoft_account() -> CliResult {
tokio::time::sleep(Duration::from_millis(200)).await;
}
// now wait for the user to complete auth in their browser
loop {
if let Ok(slot) = result_arc.lock()
&& let Some(result) = slot.as_ref() {
+4
View File
@@ -1,3 +1,6 @@
// unified content management for mods, resource packs, and shaders.
// all three content types share the same list/enable/disable workflow,
// just with different scanner functions plugged in.
use std::io;
use std::path::Path;
@@ -51,6 +54,7 @@ fn handle_content(matches: &ArgMatches, kind: &str, scan: Scanner) -> CliResult
}
}
// match by filename stem (no extension) so users don't have to type ".jar"
pub(crate) fn find_entry_by_stem<'a>(
entries: &'a [ContentEntry],
target: &str,
+3
View File
@@ -1,3 +1,5 @@
// modpack importing from modrinth (remote slug/url) or local .mrpack files.
// resolves the input, downloads if needed, then hands off to the import engine.
use clap::ArgMatches;
use crate::instance::InstanceManager;
@@ -15,6 +17,7 @@ pub async fn handle_import(matches: &ArgMatches) -> CliResult {
let manager = InstanceManager::new(instances_dir, meta_dir);
let client = crate::net::HttpClient::new();
// figure out what the user gave us: a local file, a project slug, or a versioned URL
let parsed = modrinth::parse_input(input);
let mrpack_path = match parsed {
+5
View File
@@ -1,3 +1,5 @@
// instance lifecycle: create, delete, rename, launch, config, desktop shortcuts.
// the heaviest handler in the CLI since instances are the core concept.
use std::io;
use std::time::Duration;
@@ -137,6 +139,8 @@ async fn launch_instance(matches: &ArgMatches) -> CliResult {
.await
.map_err(|error| io::Error::other(format!("Launch failed: {}", error)))?;
// poll until the game process exits. in CLI mode this blocks here
// so the user gets a proper exit code at the end.
loop {
match crate::running::get(name) {
Some(RunState::Crashed(Some(code))) => {
@@ -237,6 +241,7 @@ fn config_instance(matches: &ArgMatches) -> CliResult {
Ok(())
}
// maps --set key=value pairs to config fields. empty value = clear the field.
fn apply_config_update(
config: &mut crate::instance::InstanceConfig,
key: &str,
+4
View File
@@ -1,3 +1,4 @@
// viewing minecraft log files from the CLI, with optional `--follow` for tailing
use std::io;
use std::path::{Path, PathBuf};
use std::time::Duration;
@@ -46,6 +47,8 @@ async fn show_log(matches: &ArgMatches) -> CliResult {
println!("{}", line);
}
// ghetto tail -f: re-read the whole file and print new lines.
// not efficient, but log files are small and this is simple.
if follow {
let mut last_len = lines.len();
loop {
@@ -61,6 +64,7 @@ async fn show_log(matches: &ArgMatches) -> CliResult {
Ok(())
}
// if no file is specified, grab the most recent log (first from the sorted scan)
pub(crate) fn resolve_log_path(
instances_dir: &Path,
instance: &str,
+5
View File
@@ -1,3 +1,5 @@
// cli entry point and clap command definitions.
// no subcommand = launch TUI, otherwise dispatch to the appropriate handler.
mod account;
mod content;
mod import;
@@ -12,7 +14,9 @@ use clap::{Arg, ArgAction, ArgGroup, Command};
pub async fn init() {
let matches = build_command().get_matches();
// no subcommand means the user just ran `mcl` bare, so fall through to TUI mode
if matches.subcommand().is_none() {
// force-init the theme so it's ready before the TUI renders
let _ = &*crate::config::theme::THEME;
if let Err(e) = crate::tui::show().await {
tracing::error!("TUI error: {}", e);
@@ -206,6 +210,7 @@ fn build_command() -> Command {
)
}
// mods, resource packs, and shaders all share the same list/enable/disable shape
fn build_content_command(name: &'static str, about: &'static str) -> Command {
Command::new(name)
.about(format!("Manage {}", about))
+3
View File
@@ -1,3 +1,5 @@
// plain-text table rendering for CLI output. no fancy box-drawing,
// just left-aligned columns with two-space gaps. keeps it pipeable.
use chrono::{DateTime, Utc};
pub fn print_table(headers: &[&str], rows: &[Vec<String>]) {
@@ -39,6 +41,7 @@ pub fn active_marker(active: bool) -> &'static str {
}
}
// find the widest value in each column to pad everything evenly
fn column_widths(headers: &[&str], rows: &[Vec<String>]) -> Vec<usize> {
let mut widths: Vec<usize> = headers.iter().map(|header| header.len()).collect();
+3
View File
@@ -1,3 +1,4 @@
// shared CLI helpers: confirmation prompts, arg extraction, instance validation
use std::io::{self, Write};
use clap::ArgMatches;
@@ -17,6 +18,8 @@ pub fn required_arg<'a>(matches: &'a ArgMatches, name: &str) -> Result<&'a str,
.ok_or_else(|| io::Error::other(format!("missing required argument '{name}'")))
}
// checks for instance.json rather than just the directory, since a folder
// without config is just a sad empty directory pretending to be an instance
pub fn require_instance(instances_dir: &std::path::Path, name: &str) -> Result<(), io::Error> {
if !instances_dir.join(name).join("instance.json").exists() {
return Err(io::Error::other(format!("Instance '{name}' not found")));
+5
View File
@@ -1,3 +1,6 @@
// lists available game versions, optionally filtered by mod loader support.
// fetches the mojang manifest and cross-references with loader APIs
// to show only versions that actually work with a given loader.
use std::collections::HashSet;
use std::io;
@@ -27,6 +30,8 @@ async fn list_versions(matches: &ArgMatches) -> CliResult {
.map(|value| parse_loader(value).map_err(io::Error::other))
.transpose()?;
// vanilla supports everything by definition, so only fetch loader-specific
// version lists when the user actually asked for a modded loader
let supported = match loader {
Some(ModLoader::Vanilla) | None => None,
Some(loader) => Some(fetch_supported_versions(&client, loader).await?),
+4
View File
@@ -1,3 +1,6 @@
// config loading: reads config.toml from the platform config dir, creates defaults if missing.
// everything lands in the SETTINGS static so the rest of the app can just grab it.
use config::{Config as ConfigLoader, ConfigError, File};
use std::fs;
use std::path::PathBuf;
@@ -15,6 +18,7 @@ pub fn get_config_path() -> PathBuf {
.join("mcl")
}
// seeds the config file from the bundled default on first run
fn ensure_config_exists() -> PathBuf {
let config_path = get_config_path().join("config.toml");
if !config_path.exists() {
+6
View File
@@ -1,3 +1,6 @@
// all the config structs that map to sections in config.toml.
// everything has sane defaults so a blank file (or no file) still works.
use std::path::PathBuf;
use serde::Deserialize;
@@ -43,6 +46,7 @@ impl Default for Paths {
}
}
// expand ~ in paths since toml doesn't do that for us
pub fn resolve_path(raw: &str) -> PathBuf {
if let Some(stripped) = raw.strip_prefix("~/") {
if let Some(home) = dirs_next::home_dir() {
@@ -94,6 +98,8 @@ impl Default for Defaults {
}
#[derive(Debug, Deserialize)]
// timing knobs for the error toast animation: show for 5s, start sliding at 3.5s,
// fly off screen over 300ms. tweak these if the toasts feel too fast or slow.
pub struct Ui {
#[serde(default = "default_error_auto_dismiss_ms")]
pub error_auto_dismiss_ms: u64,
+19 -13
View File
@@ -1,3 +1,7 @@
// theme resolution: loads theme.toml, picks a base theme (builtin or custom file),
// then layers user color overrides on top. supports loading .toml themes from the
// config/theme/ directory or by absolute path.
use std::path::Path;
use std::sync::LazyLock;
@@ -92,6 +96,7 @@ fn ensure_theme_exists(path: &Path) {
let _ = std::fs::write(path, include_str!("../../assets/theme.toml"));
}
// start from a base theme, then override individual colors if the user specified any
fn resolve_app_theme(config: &ThemeConfig) -> Box<dyn Theme> {
let base = load_base_theme(&config.theme);
@@ -112,21 +117,23 @@ fn resolve_app_theme(config: &ThemeConfig) -> Box<dyn Theme> {
warning: overrides.warning.unwrap_or_else(|| base.warning()),
info: overrides.info.unwrap_or_else(|| base.info()),
diff_added: overrides.diff_added.unwrap_or_else(|| base.diff_added()),
diff_removed: overrides.diff_removed.unwrap_or_else(|| base.diff_removed()),
diff_context: overrides.diff_context.unwrap_or_else(|| base.diff_context()),
diff_removed: overrides
.diff_removed
.unwrap_or_else(|| base.diff_removed()),
diff_context: overrides
.diff_context
.unwrap_or_else(|| base.diff_context()),
border: overrides.border.unwrap_or_else(|| base.border()),
surface: overrides.surface.unwrap_or_else(|| base.surface()),
background: overrides.background.unwrap_or_else(|| base.background()),
})
}
/// Load a base theme by built-in name or file path.
// tries to find the theme: absolute path > config/theme/<name> > config/theme/<name>.toml > builtin
fn load_base_theme(name: &str) -> Box<dyn Theme> {
// Try as a file path first (absolute or relative to config dir)
let path = if Path::new(name).is_absolute() {
Some(std::path::PathBuf::from(name))
} else {
// Check in the mcl config theme directory
let theme_dir = super::get_config_path().join("theme");
let candidate = theme_dir.join(name);
if candidate.exists() {
@@ -142,15 +149,15 @@ fn load_base_theme(name: &str) -> Box<dyn Theme> {
};
if let Some(path) = path
&& let Ok(content) = std::fs::read_to_string(&path) {
if let Ok(custom) = toml::from_str::<CustomTheme>(&content) {
return Box::new(custom);
} else {
tracing::warn!("Failed to parse theme file: {}", path.display());
}
&& let Ok(content) = std::fs::read_to_string(&path)
{
if let Ok(custom) = toml::from_str::<CustomTheme>(&content) {
return Box::new(custom);
} else {
tracing::warn!("Failed to parse theme file: {}", path.display());
}
}
// Fall back to built-in theme by name
resolve_theme(name)
}
@@ -218,7 +225,6 @@ accent = "Red"
};
let theme = resolve_app_theme(&config);
assert_eq!(theme.accent(), Color::Red);
// Other colors should come from dracula base
let base = resolve_theme("dracula");
assert_eq!(theme.text(), base.text());
assert_eq!(theme.error(), base.error());
+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
}
+4
View File
@@ -1,3 +1,7 @@
// in-memory ring buffer for stdout/stderr from running mc instances.
// capped at 2000 lines per instance so it doesn't eat all the RAM
// if someone leaves a server running for a week. you're welcome.
use std::collections::{HashMap, VecDeque};
use std::sync::LazyLock;
use std::sync::{Arc, Mutex};
+5
View File
@@ -1,3 +1,6 @@
// fabric mod loader: fetches loader metadata and downloads libraries
// from fabric's maven. structurally very similar to quilt (they forked).
use std::path::Path;
use serde::{Deserialize, Serialize};
@@ -74,6 +77,8 @@ pub async fn fetch_fabric_profile(
client.get_json(&url).await
}
// each fabric library entry has a maven coordinate and a base url.
// the coordinate gets resolved to a path and combined with the url to download.
pub async fn download_fabric_libraries(
client: &HttpClient,
profile: &FabricProfile,
+9 -12
View File
@@ -1,10 +1,14 @@
// forge mod loader: version discovery via promotions API, then download
// and run the installer jar. forge doesn't have a nice metadata API like
// fabric/quilt, so it shells out to java to run their installer.
use std::collections::HashMap;
use std::path::Path;
use serde::Deserialize;
use crate::instance::loader::GameVersion;
use crate::net::{download_file, HttpClient, NetError};
use crate::net::{HttpClient, NetError, download_file};
use crate::tui::progress::set_action;
const FORGE_PROMOTIONS_URL: &str =
@@ -16,10 +20,8 @@ struct ForgePromotions {
promos: HashMap<String, String>,
}
/// Fetch available Forge loader versions for a given Minecraft game version.
///
/// Queries the Forge promotions JSON and returns unique Forge version strings
/// matching the requested game version (e.g. `"47.2.20"` for game version `"1.20.1"`).
// forge promotions use keys like "1.20.1-recommended", "1.20.1-latest"
// so this filters by game version prefix and extracts the forge version values
pub async fn fetch_forge_versions(
client: &HttpClient,
game_version: &str,
@@ -39,6 +41,8 @@ pub async fn fetch_forge_versions(
Ok(versions)
}
// extracts unique game versions from the promotion keys by splitting off
// the "-recommended"/"-latest" suffix
pub async fn fetch_forge_game_versions(client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
let promos: ForgePromotions = client.get_json(FORGE_PROMOTIONS_URL).await?;
@@ -60,9 +64,6 @@ pub async fn fetch_forge_game_versions(client: &HttpClient) -> Result<Vec<GameVe
.collect())
}
/// Download the Forge installer JAR for the given game + forge version combo.
///
/// The installer JAR is saved to `dest`. Progress is reported via the TUI progress system.
pub async fn download_forge_installer(
client: &HttpClient,
game_version: &str,
@@ -87,10 +88,6 @@ pub async fn download_forge_installer(
.await
}
/// Run the Forge installer JAR to install Forge into the instance directory.
///
/// Requires a Java runtime. The installer is invoked with `--installClient` from
/// the instance directory.
pub async fn run_forge_installer(
installer_path: &Path,
instance_dir: &Path,
+15 -4
View File
@@ -1,8 +1,11 @@
// networking layer: http client, file downloads, and shared utilities
// for fetching game assets from mojang, mod loaders, and modrinth.
pub mod fabric;
pub mod forge;
pub mod modrinth;
pub mod mojang;
pub mod neoforge;
pub mod modrinth;
pub mod quilt;
use reqwest::Client;
@@ -40,7 +43,10 @@ impl Default for HttpClient {
impl HttpClient {
pub fn new() -> Self {
let client = Client::builder()
.user_agent(format!("mcl/{} (Minecraft Launcher)", env!("CARGO_PKG_VERSION")))
.user_agent(format!(
"mcl/{} (Minecraft Launcher)",
env!("CARGO_PKG_VERSION")
))
.timeout(std::time::Duration::from_secs(30))
.build()
.unwrap_or_else(|_| Client::new());
@@ -67,8 +73,9 @@ impl HttpClient {
}
}
/// Download a file from `url` to `dest`, calling `progress_cb(bytes_downloaded, total_bytes)` as chunks arrive.
/// `total_bytes` is 0 if Content-Length is unknown.
// streams a file to disk in chunks, calling progress_cb(downloaded, total) along the way.
// total will be 0 if the server doesn't send content-length, so callers
// should handle that gracefully.
pub async fn download_file(
client: &HttpClient,
url: &str,
@@ -97,6 +104,7 @@ pub async fn download_file(
Ok(())
}
// tries JAVA_HOME first, then PATH, then just yolos "java" and hopes for the best
#[must_use]
pub fn detect_java_path() -> String {
if let Ok(java_home) = std::env::var("JAVA_HOME") {
@@ -111,6 +119,9 @@ pub fn detect_java_path() -> String {
.unwrap_or_else(|_| "java".to_string())
}
// converts maven coordinates like "org.example:artifact:1.0" into a
// filesystem path like "org/example/artifact/1.0/artifact-1.0.jar".
// supports optional classifier as a 4th component.
#[must_use]
pub fn maven_coord_to_path(coord: &str) -> Option<String> {
let parts: Vec<&str> = coord.split(':').collect();
+13
View File
@@ -1,3 +1,6 @@
// modrinth modpack support: parses URLs/slugs, fetches project metadata,
// downloads .mrpack files, and extracts loader info from pack manifests.
use serde::Deserialize;
use std::collections::HashMap;
@@ -55,6 +58,9 @@ pub enum ModrinthInput {
LocalFile(String),
}
// figures out what the user gave us: a modrinth URL, a local .mrpack file,
// or just a project slug. accepts a pretty wide range of inputs so users
// don't have to think about it.
pub fn parse_input(input: &str) -> ModrinthInput {
let input = input.trim();
@@ -85,6 +91,8 @@ pub fn parse_input(input: &str) -> ModrinthInput {
use crate::instance::models::ModLoader;
// mrpack dependencies use keys like "fabric-loader", "forge", etc.
// checks in priority order and returns the first match.
pub fn loader_from_dependencies(deps: &HashMap<String, String>) -> (Option<ModLoader>, Option<String>) {
let loaders = [
("fabric-loader", ModLoader::Fabric),
@@ -106,6 +114,8 @@ pub fn game_version_from_dependencies(deps: &HashMap<String, String>) -> Option<
const API_BASE: &str = "https://api.modrinth.com/v2";
// hand-rolled percent encoding because pulling in a crate for RFC 3986
// unreserved chars felt like overkill
fn url_encode(s: &str) -> String {
use std::fmt::Write;
let mut encoded = String::with_capacity(s.len());
@@ -149,6 +159,8 @@ pub async fn fetch_version(
client.get_json(&url).await
}
// grabs the primary file from a version, falling back to the first file
// if none is marked primary (some projects are sloppy about that)
pub async fn download_mrpack(
client: &crate::net::HttpClient,
version: &VersionInfo,
@@ -166,6 +178,7 @@ pub async fn download_mrpack(
Ok(mrpack_path)
}
// .mrpack is just a zip with modrinth.index.json at the root
pub fn parse_mrpack(path: &std::path::Path) -> Result<MrpackIndex, String> {
let file = std::fs::File::open(path).map_err(|e| format!("Cannot open .mrpack: {e}"))?;
let mut archive = zip::ZipArchive::new(file).map_err(|e| format!("Invalid ZIP: {e}"))?;
+19 -3
View File
@@ -1,16 +1,20 @@
// handles all downloads from mojang's servers: version manifests,
// client jars, libraries, and asset objects. this is the core of
// getting vanilla minecraft onto disk.
use std::{
collections::HashMap,
path::{Path, PathBuf},
sync::{
atomic::{AtomicU64, Ordering},
Arc,
atomic::{AtomicU64, Ordering},
},
};
use serde::{Deserialize, Serialize};
use tokio::task::JoinSet;
use super::{download_file, HttpClient, NetError};
use super::{HttpClient, NetError, download_file};
use crate::tui::progress::{clear, set_action, set_progress, set_sub_action};
const MANIFEST_URL: &str = "https://piston-meta.mojang.com/mc/game/version_manifest_v2.json";
@@ -239,11 +243,16 @@ pub async fn download_assets(
}
}
// assets are stored by hash with the first 2 chars as a directory prefix,
// e.g. "ab/ab1234..." - same layout mojang uses on their CDN
let mut downloads = Vec::new();
for object in asset_index.objects.values() {
if object.hash.len() < 2 {
clear();
return Err(NetError::Parse(format!("Invalid asset hash: {}", object.hash)));
return Err(NetError::Parse(format!(
"Invalid asset hash: {}",
object.hash
)));
}
let prefix = &object.hash[..2];
@@ -272,6 +281,9 @@ pub async fn download_assets(
result
}
// mojang's rule system is a bit quirky: no rules means "allow everywhere",
// and rules are evaluated in order where the last matching rule wins.
// a "disallow" for the current OS is an immediate reject though.
fn library_allowed_for_current_os(library: &Library) -> bool {
let rules = match &library.rules {
Some(rules) => rules,
@@ -306,6 +318,7 @@ fn library_allowed_for_current_os(library: &Library) -> bool {
allowed
}
// mojang calls macOS "osx" because apparently it's still 2012
fn mojang_os_name() -> &'static str {
match std::env::consts::OS {
"macos" => "osx",
@@ -313,6 +326,9 @@ fn mojang_os_name() -> &'static str {
}
}
// bounded parallel downloader. spawns up to MAX_CONCURRENT_DOWNLOADS tasks
// and feeds new ones in as each completes. collects errors but keeps going
// so it downloads as much as possible before reporting the first failure.
async fn run_parallel_downloads(
client: &HttpClient,
downloads: Vec<(String, PathBuf, String)>,
+20 -14
View File
@@ -1,9 +1,14 @@
// neoforge: the forge fork that broke away after 1.20.1.
// uses a different versioning scheme where neoforge versions map to
// minecraft versions by dropping the "1." prefix (e.g. MC 1.21 = NF 21.x).
// like forge, installation requires running their installer jar.
use std::path::Path;
use serde::Deserialize;
use crate::instance::loader::GameVersion;
use crate::net::{download_file, HttpClient, NetError};
use crate::net::{HttpClient, NetError, download_file};
use crate::tui::progress::set_action;
const NEOFORGE_MAVEN_BASE: &str = "https://maven.neoforged.net/releases/net/neoforged/neoforge";
@@ -15,10 +20,8 @@ struct NeoForgeMavenVersions {
versions: Vec<String>,
}
/// Map a Minecraft game version like "1.21" or "1.20.4" to the NeoForge version
/// prefix (e.g. "21.0." or "20.4."). NeoForge versions encode the MC version as
/// `MAJOR.MINOR.` where MAJOR is the MC major-minor (20 for 1.20.x, 21 for 1.21.x)
/// and MINOR is the MC patch (0 if absent, e.g. "1.21" → "21.0.").
// neoforge dropped the "1." from minecraft versions in their scheme,
// so "1.20.4" becomes prefix "20.4." and "1.21" becomes "21.0."
fn game_version_to_neoforge_prefix(game_version: &str) -> Option<String> {
let parts: Vec<&str> = game_version.split('.').collect();
match parts.as_slice() {
@@ -55,6 +58,8 @@ pub async fn fetch_neoforge_versions(
Ok(versions)
}
// reverse-engineers minecraft versions from neoforge version numbers.
// e.g. neoforge "21.0.x" means MC 1.21, "20.4.x" means MC 1.20.4
pub async fn fetch_neoforge_game_versions(
client: &HttpClient,
) -> Result<Vec<GameVersion>, NetError> {
@@ -64,17 +69,18 @@ pub async fn fetch_neoforge_game_versions(
for version in &maven.versions {
let parts: Vec<&str> = version.split('.').collect();
if parts.len() >= 2
&& let (Ok(major), Ok(minor)) = (parts[0].parse::<u32>(), parts[1].parse::<u32>()) {
let mc_version = if minor == 0 {
format!("1.{}", major)
} else {
format!("1.{}.{}", major, minor)
};
&& let (Ok(major), Ok(minor)) = (parts[0].parse::<u32>(), parts[1].parse::<u32>())
{
let mc_version = if minor == 0 {
format!("1.{}", major)
} else {
format!("1.{}.{}", major, minor)
};
if !game_versions.contains(&mc_version) {
game_versions.push(mc_version);
}
if !game_versions.contains(&mc_version) {
game_versions.push(mc_version);
}
}
}
game_versions.reverse();
+4 -2
View File
@@ -1,9 +1,12 @@
// quilt mod loader: fabric fork with a nearly identical metadata API.
// if you're getting deja vu reading this after fabric.rs, that's why.
use std::path::Path;
use serde::{Deserialize, Serialize};
use crate::instance::loader::GameVersion;
use crate::net::{download_file, HttpClient, NetError};
use crate::net::{HttpClient, NetError, download_file};
use crate::tui::progress::set_sub_action;
const QUILT_META_BASE: &str = "https://meta.quiltmc.org/v3";
@@ -140,5 +143,4 @@ mod tests {
Err(e) => panic!("fetch_quilt_game_versions failed: {}", e),
}
}
}
+8
View File
@@ -1,3 +1,7 @@
// global tracking for running minecraft instances. everything is behind
// Arc<Mutex<>> because the launch/monitor tasks live on separate tokio threads
// and the TUI render loop needs to read state every frame.
use chrono::{DateTime, Utc};
use std::collections::HashMap;
use std::sync::LazyLock;
@@ -14,10 +18,14 @@ pub enum RunState {
pub static RUNNING: LazyLock<Arc<Mutex<HashMap<String, RunState>>>> =
LazyLock::new(|| Arc::new(Mutex::new(HashMap::new())));
// queued up so the TUI event loop can flush these to disk in batch,
// the child process monitor shouldn't be writing config files directly
type PendingLastPlayed = Arc<Mutex<Vec<(String, DateTime<Utc>)>>>;
pub static PENDING_LAST_PLAYED: LazyLock<PendingLastPlayed> =
LazyLock::new(|| Arc::new(Mutex::new(Vec::new())));
// oneshot channels to signal a running instance to stop.
// send_kill fires the channel, the launch task receives it and kills the child process.
type KillSenders = Arc<Mutex<HashMap<String, tokio::sync::oneshot::Sender<()>>>>;
pub static KILL_SENDERS: LazyLock<KillSenders> =
LazyLock::new(|| Arc::new(Mutex::new(HashMap::new())));
+8
View File
@@ -1,3 +1,8 @@
// app state: holds everything the TUI needs between frames.
// this is basically the "god struct" of the UI. not ideal, but ratatui
// kinda pushes you into this pattern since you need mutable access
// to all the widget states during rendering.
use std::collections::HashMap;
use std::sync::{Arc, LazyLock, Mutex};
@@ -6,6 +11,8 @@ use tachyonfx::Effect;
use super::widgets::{self, instances};
use crate::instance::{InstanceConfig, InstanceManager};
// background tasks (instance creation, import) push completed configs here
// so the main loop can pick them up without blocking
pub(super) static PENDING_INSTANCES: LazyLock<Arc<Mutex<Vec<InstanceConfig>>>> =
LazyLock::new(|| Arc::new(Mutex::new(Vec::new())));
@@ -34,6 +41,7 @@ pub struct App {
pub(super) pending_editor: Option<std::path::PathBuf>,
}
// lifecycle of an error toast animation: slide in -> sit there -> fade out
pub(super) enum ErrorEffectState {
SlidingIn(Effect, std::time::Instant),
Idle,
+8 -1
View File
@@ -1,3 +1,10 @@
// thread-safe FIFO queue for error/warning toasts displayed in the UI.
// also (ab)used for INFO toasts like "desktop shortcut created" because
// why build a separate notification system when this one works fine.
//
// callers pass id: 0 and push_error assigns a real unique id. the id is
// used by the render layer to track per-toast animation state.
use std::collections::VecDeque;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
@@ -60,8 +67,8 @@ pub fn peek_error() -> Option<ErrorEvent> {
}
}
/// Returns all queued error events, newest first (for top-to-bottom stacking).
#[must_use]
// returned in reverse order (newest first) so they stack top-down in the UI
pub fn peek_all_errors() -> Vec<ErrorEvent> {
match ERROR_EVENTS.lock() {
Ok(events) => events.iter().rev().cloned().collect(),
+13
View File
@@ -11,8 +11,10 @@ use crate::tui::error_buffer;
use crate::tui::progress;
impl App {
/// main loop: drain async results, render, handle input, repeat at ~60fps
pub async fn run(&mut self, terminal: &mut Tui) -> color_eyre::Result<()> {
while !self.exit {
// check if any popup wizard finished and wants to create/import
if let Some(params) = new_instance::take_result() {
self.spawn_create(params);
}
@@ -23,6 +25,9 @@ impl App {
self.dismiss_expired_errors();
// drain all the channels from background tasks.
// every content type has its own pending queue because they each
// get scanned/loaded on separate tokio tasks
self.drain_pending_instances();
self.drain_pending_last_played();
self.mods_state.drain_pending();
@@ -40,6 +45,7 @@ impl App {
self.screenshots_state.drain_pending_entries();
self.screenshots_state.request_visible_loads();
self.create_screenshot_protocols();
// only advance the spinner every 8 ticks to keep it readable
self.throbber_tick = self.throbber_tick.wrapping_add(1);
if self.throbber_tick.is_multiple_of(8) {
self.throbber_state.calc_next();
@@ -55,6 +61,8 @@ impl App {
Ok(())
}
// polls for input with a 16ms timeout (~60fps). only key presses are handled,
// releases and repeats are ignored thanks to the enhanced keyboard protocol
fn handle_events(&mut self) -> color_eyre::Result<()> {
match crossterm::event::poll(Duration::from_millis(16)) {
Ok(true) => match event::read() {
@@ -138,6 +146,9 @@ impl App {
});
}
// spawns $EDITOR/$VISUAL to edit a file. for terminal editors (vim, nano, etc)
// gotta leave the alternate screen and restore it after, otherwise the
// editor fights with ratatui for the terminal. GUI editors just get spawned detached.
fn run_editor(terminal: &mut ratatui::DefaultTerminal, path: &std::path::Path) {
use ratatui::crossterm::{
terminal::{
@@ -215,6 +226,8 @@ impl App {
});
}
// pops errors from the front of the queue once they've been visible long enough.
// loops because multiple errors could expire in the same frame
fn dismiss_expired_errors(&self) {
use crate::config::SETTINGS;
loop {
+14
View File
@@ -1,3 +1,8 @@
// keybindings and input dispatch.
// the general pattern: check which area is focused, give it first crack at the
// keypress, and fall through to global bindings if nobody claimed it.
// vim-style navigation (j/k/g/G) where it makes sense.
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use super::app::{App, FocusedArea};
@@ -6,6 +11,7 @@ use crate::tui::error_buffer;
impl App {
pub(super) fn handle_key_event(&mut self, key_event: KeyEvent) -> color_eyre::Result<()> {
// log overlay eats all input when open, including its own search sub-mode
if self.focused == FocusedArea::OverviewExpanded {
if self.log_overlay_search.active {
match key_event.code {
@@ -85,6 +91,8 @@ impl App {
}
}
// content area delegates to whichever tab is active.
// worlds get handle_key_no_toggle because you can't "disable" a world like you can a mod
if self.focused == FocusedArea::Content {
if self.content_tab == widgets::content::ContentTab::Logs {
if widgets::logs_viewer::handle_key(&key_event, &mut self.logs_state) {
@@ -216,6 +224,7 @@ impl App {
return Ok(());
}
// global keybindings (uppercase = area switch, lowercase = action)
match key_event.code {
KeyCode::Char('q') => self.exit = true,
KeyCode::Char('I') => self.focused = FocusedArea::Instances,
@@ -246,6 +255,7 @@ impl App {
self.focused = FocusedArea::ConfirmDelete;
}
}
// shift+enter = open .minecraft folder in file manager
KeyCode::Enter
if self.focused == FocusedArea::Instances
&& !self.instances_state.search.active
@@ -262,12 +272,15 @@ impl App {
}
}
}
// plain enter = focus the content area for the selected instance
KeyCode::Enter
if self.focused == FocusedArea::Instances
&& !self.instances_state.search.active =>
{
self.focused = FocusedArea::Content;
}
// only allow launching if instance isn't already running.
// crashed instances can be relaunched (clears old state first)
KeyCode::Char('l')
if self.focused == FocusedArea::Instances
&& !self.instances_state.search.active =>
@@ -292,6 +305,7 @@ impl App {
self.instances_state.renaming = Some(inst.name.clone());
}
}
// esc = kill running instance. brutal but effective
KeyCode::Esc
if self.focused == FocusedArea::Instances
&& !self.instances_state.search.active =>
+14
View File
@@ -1,3 +1,7 @@
// sets up the tracing subscriber stack: file logging, tui-logger widget, and
// our custom StatusLayer that feeds WARN/ERROR events into the error toast system.
// also keeps an in-memory ring buffer of log lines for the log overlay viewer.
use std::fmt;
use std::sync::{Arc, Mutex};
@@ -12,6 +16,7 @@ use std::sync::LazyLock;
use crate::tui::error_buffer::{self, ErrorEvent};
// capped at 5000 lines so it doesn't eat all the ram if something goes haywire
static APP_LOG_LINES: LazyLock<Arc<Mutex<Vec<String>>>> =
LazyLock::new(|| Arc::new(Mutex::new(Vec::new())));
@@ -29,6 +34,10 @@ fn push_app_log(line: String) {
}
}
// returns a WorkerGuard that must be held alive for the duration of the
// program, otherwise the file logging thread gets dropped immediately.
// yes, you will spend 30 minutes debugging "why aren't my logs writing"
// before you remember this. ask me how i know.
pub fn init() -> WorkerGuard {
let log_dir = match dirs_next::cache_dir() {
Some(d) => d.join("mcl"),
@@ -81,6 +90,9 @@ pub fn init() -> WorkerGuard {
guard
}
// custom tracing layer that intercepts all log events:
// - everything gets appended to the in-memory log buffer for the overlay viewer
// - WARN and ERROR additionally get pushed as error toasts
struct StatusLayer;
impl StatusLayer {
@@ -132,6 +144,8 @@ impl Visit for MessageVisitor {
fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
if field.name() == "message" {
// Debug format wraps strings in quotes, strip them so the toast
// doesn't show "\"something went wrong\""
let formatted = format!("{:?}", value);
self.message = formatted
.strip_prefix('"')
+5
View File
@@ -1,3 +1,5 @@
// tui entrypoint: sets up the terminal, runs the app, cleans up on exit.
pub mod app;
pub mod error_buffer;
mod event;
@@ -12,6 +14,7 @@ pub type Tui = ratatui::DefaultTerminal;
pub async fn show() -> color_eyre::Result<()> {
let mut terminal = ratatui::init();
// opt into enhanced keyboard protocol to distinguish key press vs release
let _ = crossterm::execute!(
std::io::stdout(),
crossterm::event::PushKeyboardEnhancementFlags(
@@ -20,6 +23,8 @@ pub async fn show() -> color_eyre::Result<()> {
)
);
// figure out the terminal's font cell size for rendering images.
// falls back to halfblock characters if the terminal doesn't respond
let picker = ratatui_image::picker::Picker::from_query_stdio()
.unwrap_or_else(|_| ratatui_image::picker::Picker::halfblocks());
+3 -3
View File
@@ -1,13 +1,13 @@
// global progress state shared between background tasks and the status bar widget.
// background tasks set the action/progress, the render loop reads it every frame.
use std::sync::LazyLock;
use std::sync::{Arc, Mutex};
#[derive(Debug, Default, Clone)]
pub struct ProgressState {
/// Current main action text, e.g. "Downloading 1.20.1..."
pub current_action: Option<String>,
/// (bytes_downloaded, total_bytes). total = 0 means unknown size.
pub progress: Option<(u64, u64)>,
/// Detail text shown below main action, e.g. "libraries/net/minecraft/client.jar"
pub sub_action: Option<String>,
}
+12
View File
@@ -1,3 +1,8 @@
// layout and rendering. the main frame is split into:
// left 20%: instance sidebar
// right 80%: title bar + content area + bottom bar (account / details / status)
// popups and error toasts render on top of everything.
use ratatui::{
layout::{Constraint, Direction, Layout},
Frame,
@@ -96,6 +101,7 @@ impl App {
self.render_log_overlay(frame);
}
// error toasts stack from the top, each one below the previous
let all_errors = error_buffer::peek_all_errors();
self.sync_error_effects(&all_errors);
let mut next_y: u16 = 1;
@@ -127,6 +133,8 @@ impl App {
}
}
// full-screen log viewer with search highlighting and auto-scroll.
// auto-sticks to the bottom unless the user scrolled up manually
fn render_log_overlay(&mut self, frame: &mut Frame) {
use crate::config::theme::{THEME, BORDER_STYLE};
use crate::tui::logging::get_app_logs;
@@ -226,6 +234,8 @@ impl App {
);
}
// keeps the effect map in sync with current errors: removes effects for
// dismissed errors and creates slide-in effects for new ones
fn sync_error_effects(&mut self, events: &[error_buffer::ErrorEvent]) {
use crate::config::theme::THEME;
let theme = THEME.as_ref();
@@ -244,6 +254,8 @@ impl App {
}
}
// drives the slide-in / idle / slide-out state machine for each error toast.
// transitions to FadingOut once it's within fly_out_ms of auto-dismiss time
fn render_error_effect(
&mut self,
frame: &mut Frame,
+9
View File
@@ -1,3 +1,7 @@
// account management panel: list, add (microsoft/offline), delete
// microsoft auth uses the device code flow, so it polls a shared mutex
// for the result while showing the user a code to enter in their browser
use std::sync::{Arc, Mutex};
use crossterm::event::{KeyCode, KeyEvent};
@@ -51,6 +55,8 @@ impl Default for AccountState {
}
impl AccountState {
// called every tick to check if the background auth thread finished.
// can't block on it because the TUI needs to keep rendering
pub fn drain_auth_result(&mut self) {
if let AddMode::DeviceCodeWaiting { pending, .. } = &self.add_mode {
let result = match pending.lock() { Ok(mut slot) => {
@@ -199,6 +205,8 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut AccountState) -> bool {
}
}
// the device code arrives asynchronously from the auth thread,
// so it gets pulled out of a global mutex once it's ready
pub fn drain_device_code(state: &mut AccountState) {
if let AddMode::DeviceCodeWaiting { info, .. } = &mut state.add_mode
&& info.user_code.is_empty()
@@ -322,6 +330,7 @@ fn render_account_list(
frame.render_stateful_widget(list, area, &mut state.list_state);
}
// center a popup of given size within the terminal. nothing fancy
fn popup_area(frame: &Frame, width: u16, height: u16) -> Rect {
let area = frame.area();
let x = area.x + (area.width.saturating_sub(width)) / 2;
+107 -87
View File
@@ -1,19 +1,25 @@
// generic scrollable list for content items (mods, resource packs, shaders, worlds).
// supports toggling items on/off by renaming files with .disabled suffix,
// search filtering, per-instance caching, and directory change detection.
// also handles minecraft's formatting codes for colored mod names/descriptions
// because apparently mojang thought terminal UIs would need that. thanks guys
use std::collections::HashMap;
use std::path::Path;
use std::sync::{Arc, Mutex};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::{
Frame,
layout::Rect,
style::{Color, Modifier, Style},
text::{Line, Span, Text},
widgets::{Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState},
Frame,
};
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
use crate::instance::content::mods::{ContentEntry, IconCell};
use crate::config::theme::THEME;
use crate::instance::content::mods::{ContentEntry, IconCell};
type PendingContent = Arc<Mutex<Option<(String, Vec<ContentEntry>)>>>;
type SnapshotRow = (String, String, bool, Option<Vec<Vec<IconCell>>>);
@@ -56,11 +62,11 @@ impl Default for ContentListState {
}
impl ContentListState {
/// Check if the content directory changed (files added/removed).
/// Only triggers a rescan when the directory's modification time differs.
// poll the content directory for changes every ~120 ticks.
// if the dir's mtime changed, invalidate the cache to pick up
// mods/packs the user dropped in from outside the launcher
pub fn try_rescan(&mut self) {
self.check_counter = self.check_counter.wrapping_add(1);
// Check every ~2 seconds (120 ticks at 16ms)
if !self.check_counter.is_multiple_of(120) {
return;
}
@@ -69,13 +75,10 @@ impl ContentListState {
return;
};
let current_mtime = std::fs::metadata(dir)
.ok()
.and_then(|m| m.modified().ok());
let current_mtime = std::fs::metadata(dir).ok().and_then(|m| m.modified().ok());
if current_mtime != self.last_dir_mtime {
self.last_dir_mtime = current_mtime;
// Directory changed — invalidate so next render triggers start_load
if let Some(name) = &self.loaded_for {
self.cache.remove(name);
self.loaded_for = None;
@@ -83,7 +86,6 @@ impl ContentListState {
}
}
/// Set the directory to watch for changes. Call after start_load.
pub fn watch_dir(&mut self, dir: std::path::PathBuf) {
self.last_dir_mtime = std::fs::metadata(&dir).ok().and_then(|m| m.modified().ok());
self.watched_dir = Some(dir);
@@ -100,20 +102,23 @@ impl ContentListState {
}
impl ContentListState {
// saves current entries to cache before loading new ones, and restores
// from cache if this instance was seen before (avoids re-scanning)
pub fn start_load<F>(&mut self, instances_dir: &Path, instance_name: &str, scan_fn: F)
where
F: FnOnce(&Path, &str) -> Vec<ContentEntry> + Send + 'static,
{
if let Some(prev) = self.loaded_for.take()
&& !self.entries.is_empty() {
self.cache.insert(
prev,
CachedList {
entries: std::mem::take(&mut self.entries),
selected: self.list_state.selected,
},
);
}
&& !self.entries.is_empty()
{
self.cache.insert(
prev,
CachedList {
entries: std::mem::take(&mut self.entries),
selected: self.list_state.selected,
},
);
}
if let Some(cached) = self.cache.remove(instance_name) {
self.entries = cached.entries;
@@ -146,35 +151,35 @@ impl ContentListState {
}
pub fn drain_pending(&mut self) {
let taken = match self.pending.lock() { Ok(mut slot) => {
slot.take()
} _ => {
None
}};
let taken = match self.pending.lock() {
Ok(mut slot) => slot.take(),
_ => None,
};
if let Some((instance_name, entries)) = taken
&& (self.loaded_for.as_deref() == Some(&instance_name) || instance_name.is_empty()) {
let selected_name = self
.list_state
.selected
.and_then(|i| self.entries.get(i))
.map(|e| e.name.clone());
&& (self.loaded_for.as_deref() == Some(&instance_name) || instance_name.is_empty())
{
let selected_name = self
.list_state
.selected
.and_then(|i| self.entries.get(i))
.map(|e| e.name.clone());
self.entries = entries;
self.loading = false;
self.entries = entries;
self.loading = false;
if !self.entries.is_empty() {
let new_index = selected_name
.and_then(|name| self.entries.iter().position(|e| e.name == name))
.or(self.list_state.selected)
.map(|i| i.min(self.entries.len().saturating_sub(1)))
.unwrap_or(0);
self.list_state.selected = Some(new_index);
} else {
self.list_state.selected = None;
}
self.update_scrollbar();
if !self.entries.is_empty() {
let new_index = selected_name
.and_then(|name| self.entries.iter().position(|e| e.name == name))
.or(self.list_state.selected)
.map(|i| i.min(self.entries.len().saturating_sub(1)))
.unwrap_or(0);
self.list_state.selected = Some(new_index);
} else {
self.list_state.selected = None;
}
self.update_scrollbar();
}
}
fn update_scrollbar(&mut self) {
@@ -184,6 +189,8 @@ impl ContentListState {
self.scrollbar_state = ScrollbarState::new(max).position(pos);
}
// enable/disable by renaming the file with/without .disabled extension.
// this is how most minecraft launchers handle it
pub fn toggle_selected(&mut self) {
let Some(index) = self.list_state.selected else {
return;
@@ -279,16 +286,16 @@ pub fn handle_key_no_toggle(key_event: &KeyEvent, state: &mut ContentListState)
KeyCode::Enter if key_event.modifiers.contains(KeyModifiers::SHIFT) => {
if let Some(&real_idx) = state.list_state.selected.and_then(|i| filtered.get(i))
&& let Some(dir) = state.entries[real_idx].path.parent()
&& let Err(e) = open::that(dir) {
tracing::error!("Failed to open directory: {}", e);
}
&& let Err(e) = open::that(dir)
{
tracing::error!("Failed to open directory: {}", e);
}
true
}
_ => false,
}
}
/// Returns `true` if the key was consumed.
pub fn handle_key(key_event: &KeyEvent, state: &mut ContentListState) -> bool {
if handle_search_keys(key_event, state) {
return true;
@@ -314,9 +321,10 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut ContentListState) -> bool {
KeyCode::Enter if key_event.modifiers.contains(KeyModifiers::SHIFT) => {
if let Some(&real_idx) = state.list_state.selected.and_then(|i| filtered.get(i))
&& let Some(dir) = state.entries[real_idx].path.parent()
&& let Err(e) = open::that(dir) {
tracing::error!("Failed to open directory: {}", e);
}
&& let Err(e) = open::that(dir)
{
tracing::error!("Failed to open directory: {}", e);
}
true
}
KeyCode::Enter => {
@@ -343,8 +351,7 @@ pub fn render(
let theme = THEME.as_ref();
if state.loading {
frame.render_widget(
Paragraph::new(loading_text)
.style(Style::default().fg(theme.text_dim())),
Paragraph::new(loading_text).style(Style::default().fg(theme.text_dim())),
area,
);
return;
@@ -354,8 +361,7 @@ pub fn render(
if filtered.is_empty() {
frame.render_widget(
Paragraph::new(empty_text)
.style(Style::default().fg(theme.text_dim())),
Paragraph::new(empty_text).style(Style::default().fg(theme.text_dim())),
area,
);
return;
@@ -390,7 +396,9 @@ pub fn render(
let (name_style, description_style, background) = match (*enabled, show_selected) {
(true, true) => (
Style::default().fg(theme.accent()).add_modifier(Modifier::BOLD),
Style::default()
.fg(theme.accent())
.add_modifier(Modifier::BOLD),
Style::default().fg(theme.text_dim()),
stripe_bg,
),
@@ -402,12 +410,16 @@ pub fn render(
stripe_bg,
),
(false, true) => (
Style::default().fg(theme.accent()).add_modifier(Modifier::CROSSED_OUT),
Style::default()
.fg(theme.accent())
.add_modifier(Modifier::CROSSED_OUT),
Style::default().fg(theme.text_dim()),
stripe_bg,
),
(false, false) => (
Style::default().fg(theme.text_dim()).add_modifier(Modifier::CROSSED_OUT),
Style::default()
.fg(theme.text_dim())
.add_modifier(Modifier::CROSSED_OUT),
Style::default().fg(theme.text_dim()),
stripe_bg,
),
@@ -530,6 +542,8 @@ pub fn render(
);
}
// minecraft's 16-color palette, keyed by the formatting code character.
// these exact RGB values come from the minecraft wiki
fn mc_color(code: char) -> Option<Color> {
match code {
'0' => Some(Color::Rgb(0x00, 0x00, 0x00)),
@@ -552,6 +566,8 @@ fn mc_color(code: char) -> Option<Color> {
}
}
// parses minecraft's section-sign (U+00A7) formatting codes into styled spans.
// handles colors (0-f), bold (l), strikethrough (m), underline (n), italic (o), reset (r)
fn parse_mc_text(text: &str, base_style: Style) -> Vec<Span<'static>> {
let mut spans = Vec::new();
let mut current_style = base_style;
@@ -560,37 +576,38 @@ fn parse_mc_text(text: &str, base_style: Style) -> Vec<Span<'static>> {
while let Some(ch) = chars.next() {
if ch == '\u{00A7}'
&& let Some(&code) = chars.peek() {
if !current_text.is_empty() {
spans.push(Span::styled(current_text.clone(), current_style));
current_text.clear();
}
chars.next();
if let Some(color) = mc_color(code) {
current_style = base_style.fg(color);
} else {
match code {
'l' | 'L' => {
current_style = current_style.add_modifier(Modifier::BOLD);
}
'm' | 'M' => {
current_style = current_style.add_modifier(Modifier::CROSSED_OUT);
}
'n' | 'N' => {
current_style = current_style.add_modifier(Modifier::UNDERLINED);
}
'o' | 'O' => {
current_style = current_style.add_modifier(Modifier::ITALIC);
}
'r' | 'R' => {
current_style = base_style;
}
_ => {}
}
}
continue;
&& let Some(&code) = chars.peek()
{
if !current_text.is_empty() {
spans.push(Span::styled(current_text.clone(), current_style));
current_text.clear();
}
chars.next();
if let Some(color) = mc_color(code) {
current_style = base_style.fg(color);
} else {
match code {
'l' | 'L' => {
current_style = current_style.add_modifier(Modifier::BOLD);
}
'm' | 'M' => {
current_style = current_style.add_modifier(Modifier::CROSSED_OUT);
}
'n' | 'N' => {
current_style = current_style.add_modifier(Modifier::UNDERLINED);
}
'o' | 'O' => {
current_style = current_style.add_modifier(Modifier::ITALIC);
}
'r' | 'R' => {
current_style = base_style;
}
_ => {}
}
}
continue;
}
current_text.push(ch);
}
@@ -614,6 +631,9 @@ fn strip_mc_codes(text: &str) -> String {
result
}
// renders one row of a mod icon using half-block characters (U+2584).
// each cell packs two vertical pixels via fg/bg colors, giving
// double the vertical resolution out of the terminal
fn icon_spans(icon_pixels: Option<&Vec<Vec<IconCell>>>, row: usize) -> Vec<Span<'static>> {
match icon_pixels.and_then(|rows| rows.get(row)) {
Some(cols) => cols
+2
View File
@@ -1,3 +1,5 @@
// the tabbed content area: mods, resource packs, shaders, screenshots, worlds, logs
pub mod list;
pub mod tabs;
+9
View File
@@ -1,3 +1,7 @@
// the outer frame for the content area: tab bar, keybind footer,
// and dispatching render calls to the active tab's widget.
// also renders the instance name/version header with run state indicators.
use ratatui::{
layout::{Alignment, Constraint, Layout, Rect},
style::{Modifier, Style},
@@ -137,6 +141,8 @@ pub fn render(
block = block.title_top(sl);
}
// keybinds change depending on which tab is active and whether
// the content panel or instances panel has focus
let kb: Option<&[(&str, &str)]> = if is_focused {
Some(match tab {
ContentTab::Mods | ContentTab::ResourcePacks | ContentTab::Shaders => &[
@@ -203,6 +209,7 @@ pub fn render(
let content_area = block.inner(area);
frame.render_widget(block, area);
// lazy-load: only scan when switching to an instance that hasn't been loaded yet
match tab {
ContentTab::Mods => {
if let Some(instance) = instance {
@@ -339,6 +346,8 @@ pub fn render(
}
}
// the header bar above the content tabs, showing instance name, loader info,
// and a spinner/error indicator when the instance is running or crashed
pub fn title(
frame: &mut Frame,
area: Rect,
+3
View File
@@ -1,3 +1,6 @@
// settings panel: shows instance config (memory, java, jvm args, resolution)
// and provides keybinds to open config files in $EDITOR
use ratatui::{
layout::Rect,
style::{Modifier, Style},
+6
View File
@@ -1,3 +1,7 @@
// the instance list on the left side of the UI.
// handles search/filter, scrollbar sync, and inline renaming.
// each row shows instance name + "last played" or current run state.
use crate::config::theme::{THEME, BORDER_STYLE};
use crossterm::event::KeyCode;
use ratatui::{
@@ -15,6 +19,8 @@ use crate::tui::app::FocusedArea;
use super::{search::SearchState, styled_title, WidgetKey};
// rough human-friendly time delta. not trying to be precise here,
// "2 months ago" is close enough when months are ~30 days
fn format_last_played(last_played: Option<chrono::DateTime<chrono::Utc>>) -> String {
let Some(dt) = last_played else {
return "Never played".to_string();
+12
View File
@@ -1,3 +1,8 @@
// split-pane log viewer: file list on the left, log content on the right.
// supports live log tailing when the instance is running, plus search
// filtering in both the file list and the viewer pane.
// log scanning runs on a background thread to avoid blocking the UI.
use std::path::Path;
use std::sync::{Arc, Mutex};
@@ -114,6 +119,8 @@ impl LogsState {
}
}
// periodically re-scan log files in case new ones appeared while playing.
// only triggers every 120 ticks to avoid hammering the filesystem
pub fn try_rescan(&mut self) {
self.rescan_counter = self.rescan_counter.wrapping_add(1);
if !self.rescan_counter.is_multiple_of(120) {
@@ -142,6 +149,7 @@ impl LogsState {
});
}
// when an instance is running, a synthetic "Live" entry is injected at index 0
fn has_live(&self) -> bool {
let name = self.loaded_for.as_deref().unwrap_or("");
matches!(
@@ -487,6 +495,8 @@ fn render_viewer(
.collect();
let visible_height = area.height as usize;
// auto-scroll: if the user was already at the bottom, keep following
// new lines as they come in (like `tail -f` behavior)
let was_at_bottom = state.viewer_scroll >= state.viewer_max_scroll.saturating_sub(1);
state.update_viewer_scrollbar(visible_height, lines.len());
@@ -533,6 +543,8 @@ fn render_viewer(
);
}
// color-code log lines by severity so errors actually stand out
// instead of drowning in a wall of white text
fn line_level_style(line: &str) -> Style {
let theme = THEME.as_ref();
let upper = line.to_uppercase();
+4
View File
@@ -1,3 +1,5 @@
// shared widget utilities and the trait all key-handling widgets implement
use crate::config::theme::THEME;
use crossterm::event::KeyEvent;
use ratatui::{
@@ -15,6 +17,8 @@ pub mod screenshots_grid;
pub mod search;
pub mod status;
// highlight the first character of a title with the accent color,
// gives the UI that "keyboard shortcut hint" look
pub fn styled_title(title: &str, highlight: bool) -> Line<'_> {
let theme = THEME.as_ref();
if !highlight || title.is_empty() {
+5
View File
@@ -1,3 +1,7 @@
// base frame that all popups render inside. handles the border, title bar,
// keybind footer, and optional search indicator. content is injected via closure
// so each popup type only worries about its inner area.
use ratatui::{
buffer::Buffer,
layout::{Alignment, Rect},
@@ -21,6 +25,7 @@ pub struct PopupFrame<'a> {
impl<'a> Widget for PopupFrame<'a> {
fn render(self, area: Rect, buf: &mut Buffer) {
// clear first so the popup doesn't layer on top of whatever was underneath
Clear.render(area, buf);
if let Some(bg) = self.bg {
+3
View File
@@ -1,3 +1,6 @@
// "are you sure?" popup for instance deletion. uses global state so the
// confirmation target persists across render frames.
use std::sync::LazyLock;
use std::sync::Mutex;
+5
View File
@@ -1,3 +1,6 @@
// toast-style error/warning popup that auto-dismisses after a timeout.
// stacks in the top-right corner; border color changes based on severity.
use ratatui::{
buffer::Buffer,
layout::Rect,
@@ -60,6 +63,8 @@ impl Widget for ErrorPopup {
}
}
// returns None when the toast has lived past its expiry, which is
// what triggers removal from the render loop
pub fn popup_area(frame_area: Rect, message: &str, base_y: u16, elapsed_ms: u128) -> Option<Rect> {
use super::word_wrap_size;
@@ -1,3 +1,6 @@
// rendering for the modpack import wizard. same pattern as new_instance:
// snapshot the state, pick the right step renderer, done.
use super::super::base::PopupFrame;
use super::super::new_instance::LoadState;
use super::state::{ImportStep, ImportWizardState, IMPORT_STATE};
@@ -1,3 +1,8 @@
// state machine for the modpack import wizard.
// accepts modrinth URLs, project slugs, version IDs, or local .mrpack paths.
// for remote packs, it fetches project info then lets the user pick a version.
// local files skip straight to the confirm step.
use super::super::new_instance::LoadState;
use crate::instance::import::ImportSummary;
use crate::net::modrinth::{self, ModrinthInput, VersionInfo};
@@ -189,6 +194,7 @@ fn handle_confirm_key(
) {
match key_event.code {
KeyCode::Esc => close_popup(state, instances_state),
// if it came from a local file, there's no version list to go back to
KeyCode::Left | KeyCode::Char('h') => {
if matches!(state.versions, LoadState::Loaded(_)) {
state.step = ImportStep::Version;
@@ -217,6 +223,7 @@ fn handle_confirm_key(
}
}
// pushes an error toast and rewinds the wizard to a previous step
fn set_error_and_back(state_arc: &Arc<Mutex<ImportWizardState>>, msg: String, step: ImportStep) {
push_import_error(msg);
if let Ok(mut s) = state_arc.lock() {
@@ -224,6 +231,8 @@ fn set_error_and_back(state_arc: &Arc<Mutex<ImportWizardState>>, msg: String, st
}
}
// parses user input to figure out what they gave us, then dispatches
// to the appropriate resolve path (slug lookup, direct version, or local file)
fn start_resolve(state: &mut ImportWizardState) {
let input_text = state.input.clone();
state.step = ImportStep::Fetching;
@@ -364,6 +373,8 @@ fn resolve_local_file(state_arc: Arc<Mutex<ImportWizardState>>, path: &str) {
}
}
// user picked a version from the list. download the .mrpack, parse it,
// build a summary, and move to confirm.
fn start_version_download(state: &mut ImportWizardState) {
let version = match selected_version(state) {
Some(v) => v.clone(),
+13 -10
View File
@@ -1,3 +1,6 @@
// shared utilities for popup widgets: layout helpers, word wrapping, keybind rendering.
// individual popup types live in their own submodules.
pub mod base;
pub mod confirm;
pub mod error;
@@ -6,14 +9,8 @@ pub mod new_instance;
use ratatui::layout::Rect;
/// Calculates the minimum inner dimensions needed to display `text` with word-boundary wrapping
/// inside a box of `max_inner_width` columns.
///
/// Returns `(actual_inner_width, line_count)` where:
/// - `actual_inner_width` is the width of the widest wrapped line (never exceeds `max_inner_width`)
/// - `line_count` is how many lines are needed
///
/// Add 2 to each dimension for borders: popup_w = actual_inner_width + 2, popup_h = line_count + 2.
// figures out the (width, height) a text block will need after word wrapping.
// used to size popups before rendering so they fit their content snugly.
pub fn word_wrap_size(text: &str, max_inner_width: usize) -> (usize, usize) {
if text.is_empty() || max_inner_width == 0 {
return (0, 1);
@@ -62,7 +59,9 @@ pub fn keybind_line(binds: &[(&str, &str)]) -> ratatui::text::Line<'static> {
text::{Line, Span},
};
let theme = THEME.as_ref();
let key_style = Style::default().fg(theme.accent()).add_modifier(Modifier::BOLD);
let key_style = Style::default()
.fg(theme.accent())
.add_modifier(Modifier::BOLD);
let label_style = Style::default().fg(theme.text());
let mut spans: Vec<Span<'static>> = Vec::new();
@@ -78,6 +77,8 @@ pub fn keybind_line(binds: &[(&str, &str)]) -> ratatui::text::Line<'static> {
Line::from(spans)
}
// same as keybind_line but wraps to multiple rows when the popup is too narrow
// to fit everything on one line
pub fn keybind_lines_wrapped(
binds: &[(&str, &str)],
max_width: u16,
@@ -88,7 +89,9 @@ pub fn keybind_lines_wrapped(
text::{Line, Span},
};
let theme = THEME.as_ref();
let key_style = Style::default().fg(theme.accent()).add_modifier(Modifier::BOLD);
let key_style = Style::default()
.fg(theme.accent())
.add_modifier(Modifier::BOLD);
let label_style = Style::default().fg(theme.text());
let mut rows: Vec<Line<'static>> = Vec::new();
@@ -1,3 +1,6 @@
// rendering for the new instance wizard. each step gets its own render fn
// and the popup resizes itself based on which step is active.
use super::state::{
clamp_loader_version_index, clamp_version_index, ensure_loader_versions_loaded,
ensure_versions_loaded, visible_versions, LoadState, WizardState, WizardStep, WIZARD_STATE,
@@ -16,6 +19,9 @@ use ratatui::{
};
pub fn render(frame: &mut Frame, area: Rect, _focused: FocusedArea) {
// grab the lock, kick off any lazy-loading, then clone and release.
// data fetching happens here (in render) because the wizard is purely
// reactive: version lists only load when you navigate to that step.
let snapshot = match WIZARD_STATE.lock() {
Ok(mut state) => {
if state.step == WizardStep::Version {
@@ -23,6 +29,7 @@ pub fn render(frame: &mut Frame, area: Rect, _focused: FocusedArea) {
clamp_version_index(&mut state);
}
// vanilla has no loader version, so skip straight to confirm
if state.step == WizardStep::LoaderVersion {
if state.selected_loader() == ModLoader::Vanilla {
state.step = WizardStep::Confirm;
@@ -130,6 +137,7 @@ fn step_keybinds(state: &WizardState) -> ratatui::text::Line<'static> {
fn render_name_step(state: &WizardState, area: Rect, buf: &mut ratatui::buffer::Buffer) {
let theme = THEME.as_ref();
let value = state.name_state.value();
// \u{2588} is the full block char used as a fake blinking cursor
let line = if value.is_empty() {
Line::from(vec![
Span::styled(
+16 -5
View File
@@ -1,5 +1,9 @@
// state machine and input handling for the new instance wizard.
// flow: Name -> Loader -> Version -> LoaderVersion -> Confirm
// version lists are fetched lazily from the network when you reach that step.
use crate::instance::{
loader::{get_installer, GameVersion},
loader::{GameVersion, get_installer},
models::ModLoader,
};
use crate::tui::widgets::instances;
@@ -10,6 +14,7 @@ use tui_prompts::{FocusState, State as PromptState, TextState};
pub(crate) static WIZARD_STATE: LazyLock<Arc<Mutex<WizardState>>> =
LazyLock::new(|| Arc::new(Mutex::new(WizardState::default())));
// populated on confirm, consumed by the main event loop to actually create the instance
pub(crate) static WIZARD_RESULT: LazyLock<Arc<Mutex<Option<WizardParams>>>> =
LazyLock::new(|| Arc::new(Mutex::new(None)));
@@ -31,8 +36,7 @@ pub enum WizardStep {
Confirm,
}
#[derive(Debug, Clone)]
#[derive(Default)]
#[derive(Debug, Clone, Default)]
pub enum LoadState<T> {
#[default]
Idle,
@@ -386,6 +390,8 @@ pub(crate) fn clamp_loader_version_index(state: &mut WizardState) {
}
}
// only fires on the Idle -> Loading transition to avoid spamming requests.
// the spawned task writes results back into WIZARD_STATE when done.
pub(crate) fn ensure_versions_loaded(state: &mut WizardState) {
if !matches!(state.versions, LoadState::Idle) {
return;
@@ -420,7 +426,11 @@ pub(crate) fn ensure_versions_loaded(state: &mut WizardState) {
});
}
pub(crate) fn ensure_loader_versions_loaded(state: &mut WizardState, loader: ModLoader, game_version: String) {
pub(crate) fn ensure_loader_versions_loaded(
state: &mut WizardState,
loader: ModLoader,
game_version: String,
) {
if !matches!(state.loader_versions, LoadState::Idle) {
return;
}
@@ -452,6 +462,8 @@ pub(crate) fn ensure_loader_versions_loaded(state: &mut WizardState, loader: Mod
});
}
// quick and dirty semver compare. doesn't handle pre-release tags or anything
// fancy, just splits on dots and compares numerically. good enough for mc versions.
fn compare_semver(a: &str, b: &str) -> std::cmp::Ordering {
let parse_parts = |s: &str| -> Vec<u64> {
s.split('.')
@@ -470,6 +482,5 @@ fn compare_semver(a: &str, b: &str) -> std::cmp::Ordering {
}
fn sort_versions_semver(versions: &mut [GameVersion]) {
// Sort newest first (descending), so compare b vs a
versions.sort_by(|a, b| compare_semver(&b.id, &a.id));
}
+11
View File
@@ -1,3 +1,7 @@
// responsive grid of screenshot thumbnails rendered directly in the terminal.
// images load lazily on background threads as they scroll into view,
// and get converted to terminal graphics via ratatui-image protocols.
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::sync::{Arc, Mutex};
@@ -15,6 +19,8 @@ use ratatui_image::{protocol::StatefulProtocol, Resize, StatefulImage};
use crate::instance::screenshots::ScreenshotEntry;
use crate::config::theme::THEME;
// grid cell sizing constraints in terminal columns.
// the grid auto-fits columns within these bounds depending on terminal width
const TARGET_CELL_WIDTH: u16 = 34;
const MIN_CELL_WIDTH: u16 = 24;
const MAX_CELL_WIDTH: u16 = 52;
@@ -118,6 +124,8 @@ impl ScreenshotsState {
self.protocols.insert(idx, proto);
}
// only load images that are currently visible (or about to be).
// no point decoding a 4K screenshot the user can't even see yet
pub fn request_visible_loads(&mut self) {
if self.entries.is_empty() {
return;
@@ -286,6 +294,9 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut ScreenshotsState, is_fo
let cols = target_cols.clamp(min_cols, max_cols);
let cell_width = area.width / cols as u16;
// figure out how tall each thumbnail should be in terminal rows.
// need the font's pixel aspect ratio to keep screenshots from
// looking stretched since terminal cells aren't square
let (img_w, img_h) = state
.entries
.first()
+6
View File
@@ -1,3 +1,6 @@
// reusable incremental search state used across multiple widgets.
// handles case-insensitive filtering and inline match highlighting.
use ratatui::{
style::{Modifier, Style},
text::{Line, Span},
@@ -40,6 +43,8 @@ impl SearchState {
text.to_lowercase().contains(&self.query.to_lowercase())
}
// splits a line into spans, bolding+underlining the parts that match
// the query so they pop out visually
pub fn highlight_line<'a>(&self, text: &'a str, base_style: Style) -> Line<'a> {
if self.query.is_empty() {
return Line::from(Span::styled(text, base_style));
@@ -72,6 +77,7 @@ impl SearchState {
}
}
// renders the "/ query█" indicator in the block title bar
pub fn title_line(&self) -> Option<Line<'static>> {
if !self.active && self.query.is_empty() {
return None;
+3
View File
@@ -1,3 +1,6 @@
// the "overview" panel showing download/install progress.
// shows a gauge when the total is known, or a spinner when it's not.
use ratatui::{
layout::{Constraint, Layout, Rect},
style::{Modifier, Style},