refactor: upgrade crates and restructure project

This commit is contained in:
objz committed 2026-04-18 16:59:27 +02:00
1 parent ea093c044f
commit 47dad69321
80 files changed
+6094 -6125

No files matched your search

+21 -204
View File
@@ -1,21 +1,7 @@
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use minecraft_msa_auth::MinecraftAuthorizationFlow;
use oauth2::basic::BasicClient;
use oauth2::{
AuthUrl, ClientId, DeviceAuthorizationUrl, RefreshToken, Scope,
StandardDeviceAuthorizationResponse, TokenResponse, TokenUrl,
};
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
const CLIENT_ID: &str = "708e91b5-99f8-4a1d-80ec-e746cbb24771";
const DEVICE_CODE_URL: &str = "https://login.microsoftonline.com/consumers/oauth2/v2.0/devicecode";
const MSA_AUTHORIZE_URL: &str = "https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize";
const MSA_TOKEN_URL: &str = "https://login.microsoftonline.com/consumers/oauth2/v2.0/token";
const MC_PROFILE_URL: &str = "https://api.minecraftservices.com/minecraft/profile";
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Account {
pub uuid: String,
@@ -32,24 +18,12 @@ pub enum AccountType {
Offline,
}
#[derive(Debug, Clone, PartialEq)]
pub struct DeviceCodeInfo {
pub user_code: String,
pub verification_uri: String,
}
#[derive(Debug)]
pub enum AuthResult {
Success(Account),
Error(String),
}
#[derive(Deserialize)]
struct McProfile {
id: String,
name: String,
}
pub struct AccountStore {
pub accounts: Vec<Account>,
path: PathBuf,
@@ -67,10 +41,18 @@ impl AccountStore {
pub fn save(&self) {
if let Some(parent) = self.path.parent() {
let _ = std::fs::create_dir_all(parent);
if let Err(e) = std::fs::create_dir_all(parent) {
tracing::error!("Failed to create accounts directory: {}", e);
return;
}
}
if let Ok(json) = serde_json::to_string_pretty(&self.accounts) {
let _ = std::fs::write(&self.path, json);
match serde_json::to_string_pretty(&self.accounts) {
Ok(json) => {
if let Err(e) = std::fs::write(&self.path, json) {
tracing::error!("Failed to write accounts file: {}", e);
}
}
Err(e) => tracing::error!("Failed to serialize accounts: {}", e),
}
}
@@ -86,11 +68,10 @@ impl AccountStore {
}
pub fn add(&mut self, account: Account) {
let is_first = self.accounts.is_empty();
let uuid = account.uuid.clone();
self.accounts.retain(|a| a.uuid != uuid);
let uuid = &account.uuid;
self.accounts.retain(|a| a.uuid != *uuid);
let mut account = account;
if is_first {
if self.accounts.is_empty() {
account.active = true;
}
self.accounts.push(account);
@@ -109,16 +90,13 @@ impl AccountStore {
}
}
fn account_store_path() -> PathBuf {
dirs_next::config_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join("mcl")
.join("accounts.json")
pub fn account_store_path() -> PathBuf {
crate::config::get_config_path().join("accounts.json")
}
/// Generate a deterministic offline-mode UUID for a username.
pub fn offline_uuid(username: &str) -> String {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::hash::{DefaultHasher, Hash, Hasher};
let mut hasher = DefaultHasher::new();
format!("OfflinePlayer:{username}").hash(&mut hasher);
let h = hasher.finish();
@@ -135,174 +113,13 @@ pub fn offline_uuid(username: &str) -> String {
pub fn create_offline_account(username: &str) -> Account {
Account {
uuid: offline_uuid(username),
username: username.to_string(),
username: username.to_owned(),
account_type: AccountType::Offline,
active: false,
refresh_token: None,
}
}
pub static DEVICE_CODE_DISPLAY: Lazy<Arc<Mutex<Option<DeviceCodeInfo>>>> =
Lazy::new(|| Arc::new(Mutex::new(None)));
async fn run_full_oauth_flow() -> Result<(String, Option<String>), String> {
let oauth_client = BasicClient::new(ClientId::new(CLIENT_ID.to_string()))
.set_auth_uri(AuthUrl::new(MSA_AUTHORIZE_URL.to_string()).map_err(|e| e.to_string())?)
.set_token_uri(TokenUrl::new(MSA_TOKEN_URL.to_string()).map_err(|e| e.to_string())?)
.set_device_authorization_url(
DeviceAuthorizationUrl::new(DEVICE_CODE_URL.to_string()).map_err(|e| e.to_string())?,
);
let http_client = reqwest::Client::new();
let details: StandardDeviceAuthorizationResponse = oauth_client
.exchange_device_code()
.add_scope(Scope::new("XboxLive.signin".to_string()))
.add_scope(Scope::new("offline_access".to_string()))
.request_async(&http_client)
.await
.map_err(|e| format!("Device code request failed: {e}"))?;
if let Ok(mut slot) = DEVICE_CODE_DISPLAY.lock() {
*slot = Some(DeviceCodeInfo {
user_code: details.user_code().secret().to_string(),
verification_uri: details.verification_uri().to_string(),
});
}
let token = oauth_client
.exchange_device_access_token(&details)
.request_async(&http_client, tokio::time::sleep, None)
.await
.map_err(|e| format!("Authentication failed: {e}"))?;
let ms_access_token = token.access_token().secret().to_string();
let ms_refresh_token = token.refresh_token().map(|r| r.secret().to_string());
Ok((ms_access_token, ms_refresh_token))
}
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();
tokio::spawn(async move {
let outcome = run_full_auth_flow().await;
if let Ok(mut slot) = result_clone.lock() {
*slot = Some(outcome);
}
});
result
}
async fn run_full_auth_flow() -> AuthResult {
let (ms_access_token, ms_refresh_token) = match run_full_oauth_flow().await {
Ok(pair) => pair,
Err(e) => return AuthResult::Error(e),
};
exchange_and_build_account(&ms_access_token, ms_refresh_token.as_deref()).await
}
async fn exchange_and_build_account(
ms_access_token: &str,
ms_refresh_token: Option<&str>,
) -> AuthResult {
let mc_flow = MinecraftAuthorizationFlow::new(reqwest::Client::new());
let mc_token = match mc_flow.exchange_microsoft_token(ms_access_token).await {
Ok(t) => t,
Err(e) => return AuthResult::Error(format!("Minecraft auth failed: {e}")),
};
let client = reqwest::Client::new();
let profile_resp = match client
.get(MC_PROFILE_URL)
.header(
"Authorization",
format!("Bearer {}", mc_token.access_token().as_ref()),
)
.send()
.await
{
Ok(r) => r,
Err(e) => return AuthResult::Error(format!("Profile fetch failed: {e}")),
};
if !profile_resp.status().is_success() {
return AuthResult::Error("Account does not own Minecraft".to_string());
}
let profile: McProfile = match profile_resp.json().await {
Ok(p) => p,
Err(e) => return AuthResult::Error(format!("Profile parse failed: {e}")),
};
let uuid = if profile.id.len() == 32 {
format!(
"{}-{}-{}-{}-{}",
&profile.id[..8],
&profile.id[8..12],
&profile.id[12..16],
&profile.id[16..20],
&profile.id[20..32],
)
} else {
profile.id.clone()
};
AuthResult::Success(Account {
uuid,
username: profile.name,
account_type: AccountType::Microsoft,
active: false,
refresh_token: ms_refresh_token.map(|s| s.to_string()),
})
}
pub async fn refresh_and_get_token(account: &Account) -> Result<(String, Option<String>), String> {
match account.account_type {
AccountType::Offline => Ok(("0".to_string(), None)),
AccountType::Microsoft => {
let refresh = account.refresh_token.as_deref().ok_or_else(|| {
format!(
"No saved credentials for '{}'. Please remove and re-add the account.",
account.username
)
})?;
let oauth_client = BasicClient::new(ClientId::new(CLIENT_ID.to_string()))
.set_auth_uri(
AuthUrl::new(MSA_AUTHORIZE_URL.to_string()).map_err(|e| e.to_string())?,
)
.set_token_uri(
TokenUrl::new(MSA_TOKEN_URL.to_string()).map_err(|e| e.to_string())?,
);
let http_client = reqwest::Client::new();
let token = oauth_client
.exchange_refresh_token(&RefreshToken::new(refresh.to_string()))
.add_scope(Scope::new("XboxLive.signin".to_string()))
.add_scope(Scope::new("offline_access".to_string()))
.request_async(&http_client)
.await
.map_err(|e| format!("Token refresh failed: {e}"))?;
let ms_access_token = token.access_token().secret().to_string();
let new_refresh = token.refresh_token().map(|r| r.secret().to_string());
let mc_flow = MinecraftAuthorizationFlow::new(reqwest::Client::new());
let mc_token = mc_flow
.exchange_microsoft_token(&ms_access_token)
.await
.map_err(|e| format!("Minecraft auth failed: {e}"))?;
Ok((mc_token.access_token().as_ref().to_string(), new_refresh))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -364,7 +181,7 @@ mod tests {
fn dummy_account(name: &str) -> Account {
Account {
uuid: offline_uuid(name),
username: name.to_string(),
username: name.to_owned(),
account_type: AccountType::Offline,
active: false,
refresh_token: None,
@@ -397,7 +214,7 @@ mod tests {
let mut store = make_store(tmp.path());
store.add(dummy_account("Alice"));
let mut dup = dummy_account("Alice");
dup.username = "AliceRenamed".to_string();
dup.username = "AliceRenamed".to_owned();
dup.uuid = store.accounts[0].uuid.clone();
store.add(dup);
assert_eq!(store.accounts.len(), 1);
+8
View File
@@ -0,0 +1,8 @@
mod accounts;
mod oauth;
pub use accounts::{
account_store_path, create_offline_account, offline_uuid, Account, AccountStore, AccountType,
AuthResult,
};
pub use oauth::{refresh_and_get_token, start_microsoft_auth, DeviceCodeInfo, DEVICE_CODE_DISPLAY};
+188
View File
@@ -0,0 +1,188 @@
use std::sync::{Arc, LazyLock, Mutex};
use minecraft_msa_auth::MinecraftAuthorizationFlow;
use oauth2::basic::BasicClient;
use oauth2::{
AuthUrl, ClientId, DeviceAuthorizationUrl, RefreshToken, Scope,
StandardDeviceAuthorizationResponse, TokenResponse, TokenUrl,
};
use serde::Deserialize;
use super::accounts::{Account, AccountType, AuthResult};
const CLIENT_ID: &str = "708e91b5-99f8-4a1d-80ec-e746cbb24771";
const DEVICE_CODE_URL: &str = "https://login.microsoftonline.com/consumers/oauth2/v2.0/devicecode";
const MSA_AUTHORIZE_URL: &str = "https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize";
const MSA_TOKEN_URL: &str = "https://login.microsoftonline.com/consumers/oauth2/v2.0/token";
const MC_PROFILE_URL: &str = "https://api.minecraftservices.com/minecraft/profile";
#[derive(Debug, Clone, PartialEq)]
pub struct DeviceCodeInfo {
pub user_code: String,
pub verification_uri: String,
}
#[derive(Deserialize)]
struct McProfile {
id: String,
name: String,
}
pub static DEVICE_CODE_DISPLAY: LazyLock<Arc<Mutex<Option<DeviceCodeInfo>>>> =
LazyLock::new(|| Arc::new(Mutex::new(None)));
async fn run_full_oauth_flow() -> Result<(String, Option<String>), String> {
let oauth_client = BasicClient::new(ClientId::new(CLIENT_ID.to_owned()))
.set_auth_uri(AuthUrl::new(MSA_AUTHORIZE_URL.to_owned()).map_err(|e| e.to_string())?)
.set_token_uri(TokenUrl::new(MSA_TOKEN_URL.to_owned()).map_err(|e| e.to_string())?)
.set_device_authorization_url(
DeviceAuthorizationUrl::new(DEVICE_CODE_URL.to_owned()).map_err(|e| e.to_string())?,
);
let http_client = reqwest::Client::new();
let details: StandardDeviceAuthorizationResponse = oauth_client
.exchange_device_code()
.add_scope(Scope::new("XboxLive.signin".to_owned()))
.add_scope(Scope::new("offline_access".to_owned()))
.request_async(&http_client)
.await
.map_err(|e| format!("Device code request failed: {e}"))?;
if let Ok(mut slot) = DEVICE_CODE_DISPLAY.lock() {
*slot = Some(DeviceCodeInfo {
user_code: details.user_code().secret().to_owned(),
verification_uri: details.verification_uri().to_string(),
});
}
let token = oauth_client
.exchange_device_access_token(&details)
.request_async(&http_client, tokio::time::sleep, None)
.await
.map_err(|e| format!("Authentication failed: {e}"))?;
let ms_access_token = token.access_token().secret().to_owned();
let ms_refresh_token = token.refresh_token().map(|r| r.secret().to_owned());
Ok((ms_access_token, ms_refresh_token))
}
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();
tokio::spawn(async move {
let outcome = run_full_auth_flow().await;
if let Ok(mut slot) = result_clone.lock() {
*slot = Some(outcome);
}
});
result
}
async fn run_full_auth_flow() -> AuthResult {
let (ms_access_token, ms_refresh_token) = match run_full_oauth_flow().await {
Ok(pair) => pair,
Err(e) => return AuthResult::Error(e),
};
exchange_and_build_account(&ms_access_token, ms_refresh_token.as_deref()).await
}
async fn exchange_and_build_account(
ms_access_token: &str,
ms_refresh_token: Option<&str>,
) -> AuthResult {
let mc_flow = MinecraftAuthorizationFlow::new(reqwest::Client::new());
let mc_token = match mc_flow.exchange_microsoft_token(ms_access_token).await {
Ok(t) => t,
Err(e) => return AuthResult::Error(format!("Minecraft auth failed: {e}")),
};
let client = reqwest::Client::new();
let profile_resp = match client
.get(MC_PROFILE_URL)
.header(
"Authorization",
format!("Bearer {}", mc_token.access_token().as_ref()),
)
.send()
.await
{
Ok(r) => r,
Err(e) => return AuthResult::Error(format!("Profile fetch failed: {e}")),
};
if !profile_resp.status().is_success() {
return AuthResult::Error("Account does not own Minecraft".to_owned());
}
let profile: McProfile = match profile_resp.json().await {
Ok(p) => p,
Err(e) => return AuthResult::Error(format!("Profile parse failed: {e}")),
};
let uuid = if profile.id.len() == 32 {
format!(
"{}-{}-{}-{}-{}",
&profile.id[..8],
&profile.id[8..12],
&profile.id[12..16],
&profile.id[16..20],
&profile.id[20..32],
)
} else {
profile.id.clone()
};
AuthResult::Success(Account {
uuid,
username: profile.name,
account_type: AccountType::Microsoft,
active: false,
refresh_token: ms_refresh_token.map(|s| s.to_owned()),
})
}
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)),
AccountType::Microsoft => {
let refresh = account.refresh_token.as_deref().ok_or_else(|| {
format!(
"No saved credentials for '{}'. Please remove and re-add the account.",
account.username
)
})?;
let oauth_client = BasicClient::new(ClientId::new(CLIENT_ID.to_owned()))
.set_auth_uri(
AuthUrl::new(MSA_AUTHORIZE_URL.to_owned()).map_err(|e| e.to_string())?,
)
.set_token_uri(TokenUrl::new(MSA_TOKEN_URL.to_owned()).map_err(|e| e.to_string())?);
let http_client = reqwest::Client::new();
let token = oauth_client
.exchange_refresh_token(&RefreshToken::new(refresh.to_owned()))
.add_scope(Scope::new("XboxLive.signin".to_owned()))
.add_scope(Scope::new("offline_access".to_owned()))
.request_async(&http_client)
.await
.map_err(|e| format!("Token refresh failed: {e}"))?;
let ms_access_token = token.access_token().secret().to_owned();
let new_refresh = token.refresh_token().map(|r| r.secret().to_owned());
let mc_flow = MinecraftAuthorizationFlow::new(reqwest::Client::new());
let mc_token = mc_flow
.exchange_microsoft_token(&ms_access_token)
.await
.map_err(|e| format!("Minecraft auth failed: {e}"))?;
Ok((mc_token.access_token().as_ref().to_owned(), new_refresh))
}
}
}
+2 -15
View File
@@ -1,4 +1,4 @@
use std::io::{self, Write};
use std::io;
use std::time::Duration;
use clap::ArgMatches;
@@ -143,20 +143,7 @@ fn find_account_index(accounts: &[Account], username: &str) -> Option<usize> {
.position(|account| account.username.eq_ignore_ascii_case(username))
}
fn confirm(message: &str) -> Result<bool, io::Error> {
print!("{}? [y/N] ", message);
io::stdout().flush()?;
let mut input = String::new();
io::stdin().read_line(&mut input)?;
Ok(input.trim().eq_ignore_ascii_case("y"))
}
fn required_arg<'a>(matches: &'a ArgMatches, name: &str) -> Result<&'a str, io::Error> {
matches
.get_one::<String>(name)
.map(String::as_str)
.ok_or_else(|| io::Error::other(format!("missing required argument '{}'", name)))
}
use super::utils::{confirm, required_arg};
#[cfg(test)]
mod tests {
+27 -30
View File
@@ -3,22 +3,31 @@ use std::path::Path;
use clap::ArgMatches;
use super::utils::{require_instance, required_arg};
use crate::cli::output::print_table;
use crate::instance::ModEntry;
use crate::instance::ContentEntry;
type CliResult = Result<(), Box<dyn std::error::Error>>;
type Scanner = fn(&Path, &str) -> Vec<ModEntry>;
type Scanner = fn(&Path, &str) -> Vec<ContentEntry>;
pub async fn handle_mod(matches: &ArgMatches) -> CliResult {
handle_content(matches, "mod", crate::instance::mods::scan_mods)
pub fn handle_mod(matches: &ArgMatches) -> CliResult {
handle_content(matches, "mod", crate::instance::content::mods::scan_mods)
}
pub async fn handle_pack(matches: &ArgMatches) -> CliResult {
handle_content(matches, "pack", crate::instance::resource_packs::scan_resource_packs)
pub fn handle_pack(matches: &ArgMatches) -> CliResult {
handle_content(
matches,
"pack",
crate::instance::content::resource_packs::scan_resource_packs,
)
}
pub async fn handle_shader(matches: &ArgMatches) -> CliResult {
handle_content(matches, "shader", crate::instance::shaders::scan_shaders)
pub fn handle_shader(matches: &ArgMatches) -> CliResult {
handle_content(
matches,
"shader",
crate::instance::content::shaders::scan_shaders,
)
}
fn handle_content(matches: &ArgMatches, kind: &str, scan: Scanner) -> CliResult {
@@ -42,19 +51,15 @@ fn handle_content(matches: &ArgMatches, kind: &str, scan: Scanner) -> CliResult
}
}
pub(crate) fn find_entry_by_stem<'a>(entries: &'a [ModEntry], target: &str) -> Option<&'a ModEntry> {
pub(crate) fn find_entry_by_stem<'a>(
entries: &'a [ContentEntry],
target: &str,
) -> Option<&'a ContentEntry> {
entries
.iter()
.find(|entry| entry.file_stem.eq_ignore_ascii_case(target))
}
fn require_instance(instances_dir: &Path, name: &str) -> Result<(), io::Error> {
if !instances_dir.join(name).join("instance.json").exists() {
return Err(io::Error::other(format!("Instance '{}' not found", name)));
}
Ok(())
}
fn list_entries(instance: &str, scan: Scanner) -> CliResult {
let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir();
require_instance(&instances_dir, instance)?;
@@ -86,9 +91,8 @@ fn toggle_entry(
let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir();
require_instance(&instances_dir, instance)?;
let entries = scan(&instances_dir, instance);
let entry = find_entry_by_stem(&entries, target).ok_or_else(|| {
io::Error::other(format!("{} '{}' not found", kind, target))
})?;
let entry = find_entry_by_stem(&entries, target)
.ok_or_else(|| io::Error::other(format!("{} '{}' not found", kind, target)))?;
if entry.enabled == should_enable {
println!(
@@ -98,7 +102,7 @@ fn toggle_entry(
return Ok(());
}
crate::instance::mods::toggle_mod(entry)?;
crate::instance::content::mods::toggle_entry(entry)?;
println!(
"{}d '{}'.",
if should_enable { "Enable" } else { "Disable" },
@@ -107,21 +111,14 @@ fn toggle_entry(
Ok(())
}
fn required_arg<'a>(matches: &'a ArgMatches, name: &str) -> Result<&'a str, io::Error> {
matches
.get_one::<String>(name)
.map(String::as_str)
.ok_or_else(|| io::Error::other(format!("missing required argument '{}'", name)))
}
#[cfg(test)]
mod tests {
use super::find_entry_by_stem;
use crate::instance::ModEntry;
use crate::instance::ContentEntry;
use std::path::PathBuf;
fn entry(file_stem: &str) -> ModEntry {
ModEntry {
fn entry(file_stem: &str) -> ContentEntry {
ContentEntry {
file_stem: file_stem.to_string(),
name: file_stem.to_string(),
description: String::new(),
+17 -15
View File
@@ -19,13 +19,7 @@ pub async fn handle_import(matches: &ArgMatches) -> CliResult {
let mrpack_path = match parsed {
modrinth::ModrinthInput::LocalFile(ref path) => {
let resolved = if let Some(stripped) = path.strip_prefix("~/") {
dirs_next::home_dir()
.map(|h| h.join(stripped))
.unwrap_or_else(|| std::path::PathBuf::from(path))
} else {
std::path::PathBuf::from(path)
};
let resolved = crate::config::settings::resolve_path(path);
if !resolved.exists() {
return Err(format!("File not found: {}", resolved.display()).into());
}
@@ -33,11 +27,13 @@ pub async fn handle_import(matches: &ArgMatches) -> CliResult {
}
modrinth::ModrinthInput::ProjectSlug(ref slug) => {
println!("Fetching project '{slug}'...");
let project = modrinth::fetch_project(&client, slug).await
let project = modrinth::fetch_project(&client, slug)
.await
.map_err(|e| format!("Failed to fetch project: {e}"))?;
println!("Found: {}", project.title);
let versions = modrinth::fetch_versions(&client, slug).await
let versions = modrinth::fetch_versions(&client, slug)
.await
.map_err(|e| format!("Failed to fetch versions: {e}"))?;
if versions.is_empty() {
@@ -61,13 +57,17 @@ pub async fn handle_import(matches: &ArgMatches) -> CliResult {
let tmp_dir = manager.meta_dir.join("tmp");
std::fs::create_dir_all(&tmp_dir)?;
modrinth::download_mrpack(&client, version, &tmp_dir).await
modrinth::download_mrpack(&client, version, &tmp_dir)
.await
.map_err(|e| format!("Failed to download .mrpack: {e}"))?
}
modrinth::ModrinthInput::VersionId { ref slug, ref version_id } => {
modrinth::ModrinthInput::VersionId {
slug: _,
ref version_id,
} => {
println!("Fetching version '{version_id}'...");
let _slug = slug;
let version = modrinth::fetch_version(&client, version_id).await
let version = modrinth::fetch_version(&client, version_id)
.await
.map_err(|e| format!("Failed to fetch version: {e}"))?;
println!(
@@ -78,7 +78,8 @@ pub async fn handle_import(matches: &ArgMatches) -> CliResult {
let tmp_dir = manager.meta_dir.join("tmp");
std::fs::create_dir_all(&tmp_dir)?;
modrinth::download_mrpack(&client, &version, &tmp_dir).await
modrinth::download_mrpack(&client, &version, &tmp_dir)
.await
.map_err(|e| format!("Failed to download .mrpack: {e}"))?
}
};
@@ -102,7 +103,8 @@ pub async fn handle_import(matches: &ArgMatches) -> CliResult {
summary.override_count
);
let config = crate::instance::import::execute_import(&summary, &manager).await
let config = crate::instance::import::execute_import(&summary, &manager)
.await
.map_err(|e| format!("Import failed: {e}"))?;
println!("Instance '{}' created successfully.", config.name);
+14 -22
View File
@@ -1,8 +1,9 @@
use std::io::{self, Write};
use std::io;
use std::time::Duration;
use clap::ArgMatches;
use super::utils::{confirm, required_arg};
use crate::cli::output::{format_datetime, print_table};
use crate::instance::{InstanceManager, ModLoader};
use crate::running::RunState;
@@ -87,13 +88,16 @@ fn list_instances() -> CliResult {
async fn create_instance(matches: &ArgMatches) -> CliResult {
let name = required_arg(matches, "name")?;
let version = required_arg(matches, "version")?;
let loader = parse_loader(required_arg(matches, "loader")?)
.map_err(io::Error::other)?;
let loader_version = matches.get_one::<String>("loader-version").map(String::as_str);
let loader = parse_loader(required_arg(matches, "loader")?).map_err(io::Error::other)?;
let loader_version = matches
.get_one::<String>("loader-version")
.map(String::as_str);
let manager = manager();
println!("Creating instance '{}'...", name);
let config = manager.create(name, version, loader, loader_version).await?;
let config = manager
.create(name, version, loader, loader_version)
.await?;
println!(
"Created '{}' ({} {})",
config.name, config.game_version, config.loader
@@ -140,7 +144,7 @@ async fn launch_instance(matches: &ArgMatches) -> CliResult {
break;
}
Some(RunState::Crashed(None)) => {
println!("Game exited with status terminated.");
println!("Game was terminated.");
break;
}
Some(_) => tokio::time::sleep(Duration::from_millis(500)).await,
@@ -278,28 +282,16 @@ fn apply_config_update(
Ok(())
}
fn confirm(message: &str) -> Result<bool, io::Error> {
print!("{}? [y/N] ", message);
io::stdout().flush()?;
let mut input = String::new();
io::stdin().read_line(&mut input)?;
Ok(input.trim().eq_ignore_ascii_case("y"))
}
fn required_arg<'a>(matches: &'a ArgMatches, name: &str) -> Result<&'a str, io::Error> {
matches
.get_one::<String>(name)
.map(String::as_str)
.ok_or_else(|| io::Error::other(format!("missing required argument '{}'", name)))
}
#[cfg(test)]
mod tests {
use super::parse_resolution;
#[test]
fn parses_valid_resolution() {
assert_eq!(parse_resolution("1920x1080").expect("should parse"), (1920, 1080));
assert_eq!(
parse_resolution("1920x1080").expect("should parse"),
(1920, 1080)
);
}
#[test]
+10 -17
View File
@@ -16,20 +16,15 @@ pub async fn handle_log(matches: &ArgMatches) -> CliResult {
}
}
fn require_instance(instances_dir: &Path, name: &str) -> Result<(), io::Error> {
if !instances_dir.join(name).join("instance.json").exists() {
return Err(io::Error::other(format!("Instance '{}' not found", name)));
}
Ok(())
}
fn list_logs(instance: &str) -> CliResult {
let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir();
require_instance(&instances_dir, instance)?;
let rows = crate::instance::log_files::scan_log_files(&instances_dir, instance)
.into_iter()
.map(|entry| {
let size = std::fs::metadata(&entry.path).map(|meta| meta.len()).unwrap_or(0);
let size = std::fs::metadata(&entry.path)
.map(|meta| meta.len())
.unwrap_or(0);
vec![entry.name, size.to_string()]
})
.collect::<Vec<_>>();
@@ -86,12 +81,7 @@ pub(crate) fn resolve_log_path(
.ok_or_else(|| io::Error::other(format!("no log files found for '{}'", instance)))
}
fn required_arg<'a>(matches: &'a ArgMatches, name: &str) -> Result<&'a str, io::Error> {
matches
.get_one::<String>(name)
.map(String::as_str)
.ok_or_else(|| io::Error::other(format!("missing required argument '{}'", name)))
}
use super::utils::{require_instance, required_arg};
#[cfg(test)]
mod tests {
@@ -131,9 +121,12 @@ mod tests {
std::fs::create_dir_all(&dir).expect("log directory should exist");
std::fs::write(dir.join("latest.log"), "hello").expect("write named log");
let path = resolve_log_path(&root, "demo", Some("latest.log"))
.expect("named log should resolve");
assert_eq!(path.file_name().and_then(|name| name.to_str()), Some("latest.log"));
let path =
resolve_log_path(&root, "demo", Some("latest.log")).expect("named log should resolve");
assert_eq!(
path.file_name().and_then(|name| name.to_str()),
Some("latest.log")
);
let _ = std::fs::remove_dir_all(&root);
}
+25 -12
View File
@@ -1,9 +1,10 @@
mod account;
mod content;
mod import;
mod instance;
mod log;
mod output;
mod import;
mod utils;
mod version;
use clap::{Arg, ArgAction, ArgGroup, Command};
@@ -12,7 +13,7 @@ pub async fn init() {
let matches = build_command().get_matches();
if matches.subcommand().is_none() {
let _ = &*crate::tui::theme::THEME;
let _ = &*crate::config::theme::THEME;
if let Err(e) = crate::tui::show().await {
tracing::error!("TUI error: {}", e);
}
@@ -21,9 +22,9 @@ pub async fn init() {
let result = match matches.subcommand() {
Some(("instance", sub_matches)) => instance::handle_instance(sub_matches).await,
Some(("mod", sub_matches)) => content::handle_mod(sub_matches).await,
Some(("pack", sub_matches)) => content::handle_pack(sub_matches).await,
Some(("shader", sub_matches)) => content::handle_shader(sub_matches).await,
Some(("mod", sub_matches)) => content::handle_mod(sub_matches),
Some(("pack", sub_matches)) => content::handle_pack(sub_matches),
Some(("shader", sub_matches)) => content::handle_shader(sub_matches),
Some(("account", sub_matches)) => account::handle_account(sub_matches).await,
Some(("log", sub_matches)) => log::handle_log(sub_matches).await,
Some(("version", sub_matches)) => version::handle_version(sub_matches).await,
@@ -40,7 +41,7 @@ pub async fn init() {
fn build_command() -> Command {
Command::new("mcl")
.about("Minecraft CLI Launcher")
.version("1.0.0")
.version(env!("CARGO_PKG_VERSION"))
.subcommand_required(false)
.arg_required_else_help(false)
.subcommand(
@@ -184,12 +185,24 @@ fn build_command() -> Command {
Command::new("import")
.about("Import a modpack")
.arg_required_else_help(true)
.arg(Arg::new("source").required(true).action(ArgAction::Set)
.help("Modrinth URL, project slug, or local .mrpack file path"))
.arg(Arg::new("version").long("version").action(ArgAction::Set)
.help("Modpack version to import (default: latest)"))
.arg(Arg::new("name").long("name").action(ArgAction::Set)
.help("Override instance name")),
.arg(
Arg::new("source")
.required(true)
.action(ArgAction::Set)
.help("Modrinth URL, project slug, or local .mrpack file path"),
)
.arg(
Arg::new("version")
.long("version")
.action(ArgAction::Set)
.help("Modpack version to import (default: latest)"),
)
.arg(
Arg::new("name")
.long("name")
.action(ArgAction::Set)
.help("Override instance name"),
),
)
}
+25
View File
@@ -0,0 +1,25 @@
use std::io::{self, Write};
use clap::ArgMatches;
pub fn confirm(message: &str) -> Result<bool, io::Error> {
print!("{}? [y/N] ", message);
io::stdout().flush()?;
let mut input = String::new();
io::stdin().read_line(&mut input)?;
Ok(input.trim().eq_ignore_ascii_case("y"))
}
pub fn required_arg<'a>(matches: &'a ArgMatches, name: &str) -> Result<&'a str, io::Error> {
matches
.get_one::<String>(name)
.map(String::as_str)
.ok_or_else(|| io::Error::other(format!("missing required argument '{name}'")))
}
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")));
}
Ok(())
}
+1 -1
View File
@@ -6,8 +6,8 @@ use clap::ArgMatches;
use crate::cli::instance::parse_loader;
use crate::cli::output::print_table;
use crate::instance::ModLoader;
use crate::net::HttpClient;
use crate::net::mojang::{VersionEntry, VersionManifest};
use crate::net::HttpClient;
type CliResult = Result<(), Box<dyn std::error::Error>>;
+33 -89
View File
@@ -1,99 +1,49 @@
use config::{Config as ConfigLoader, ConfigError, File};
use dirs_next::config_dir;
use once_cell::sync::Lazy;
use std::fs;
use std::path::PathBuf;
use types::Config;
use std::sync::LazyLock;
pub mod types;
pub mod settings;
pub mod theme;
pub use settings::Config;
#[must_use]
pub fn get_config_path() -> PathBuf {
match config_dir() {
Some(base_dir) => base_dir.join("mcl/"),
None => {
tracing::error!("Could not determine config directory, falling back to ./config/");
PathBuf::from("./config/")
}
}
dirs_next::config_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join("mcl")
}
fn ensure_config_exists(default_path: &str) -> PathBuf {
fn ensure_config_exists() -> PathBuf {
let config_path = get_config_path().join("config.toml");
if !config_path.exists() {
if let Some(parent_dir) = config_path.parent() {
match fs::create_dir_all(parent_dir) {
Ok(_) => {}
Err(e) => {
tracing::error!("Failed to create configuration directory: {}", e);
}
}
}
match fs::copy(default_path, &config_path) {
Ok(_) => {
tracing::debug!(
"Default configuration copied to '{}'",
config_path.display()
);
}
Err(e) => {
tracing::error!(
"Failed to copy default config from '{}' to '{}': {}",
default_path,
config_path.display(),
e
);
}
if let Some(parent) = config_path.parent() {
let _ = fs::create_dir_all(parent);
}
let _ = fs::write(&config_path, include_str!("../../assets/config.toml"));
}
config_path
}
pub fn load_config(config_path: &std::path::Path) -> Result<Config, ConfigError> {
let built = match ConfigLoader::builder()
ConfigLoader::builder()
.add_source(File::from(config_path).required(false))
.build()
{
Ok(c) => c,
Err(e) => {
tracing::error!(
"Failed to build config from '{}': {}",
config_path.display(),
e
);
return Err(e);
}
};
match built.try_deserialize() {
Ok(config) => Ok(config),
Err(e) => {
tracing::error!(
"Failed to deserialize config from '{}': {}",
config_path.display(),
e
);
Err(e)
}
}
.build()?
.try_deserialize()
}
pub static SETTINGS: Lazy<Config> = Lazy::new(|| {
let path: PathBuf = ensure_config_exists("assets/config.toml");
match load_config(&path) {
Ok(config) => config,
Err(e) => {
tracing::error!("Config load failed, using defaults: {}", e);
Config {
general: types::General::default(),
paths: types::Paths::default(),
defaults: types::Defaults::default(),
ui: types::Ui::default(),
}
pub static SETTINGS: LazyLock<Config> = LazyLock::new(|| {
let path = ensure_config_exists();
load_config(&path).unwrap_or_else(|e| {
tracing::error!("Config load failed, using defaults: {}", e);
Config {
general: settings::General::default(),
paths: settings::Paths::default(),
defaults: settings::Defaults::default(),
ui: settings::Ui::default(),
}
}
})
});
#[cfg(test)]
@@ -107,16 +57,12 @@ mod tests {
std::fs::write(
&path,
r#"
[general]
debug = true
[defaults]
memory_max = "4G"
"#,
[defaults]
memory_max = "4G"
"#,
)
.unwrap();
let config = load_config(&path).unwrap();
assert!(config.general.debug);
assert_eq!(config.defaults.memory_max, "4G");
assert_eq!(config.defaults.memory_min, "512M");
}
@@ -127,7 +73,6 @@ memory_max = "4G"
let path = tmp.path().join("config.toml");
std::fs::write(&path, "").unwrap();
let config = load_config(&path).unwrap();
assert!(!config.general.debug);
assert_eq!(config.defaults.memory_max, "2G");
}
@@ -135,8 +80,7 @@ memory_max = "4G"
fn load_config_missing_file_uses_defaults() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("nonexistent.toml");
let config = load_config(&path).unwrap();
assert!(!config.general.debug);
load_config(&path).unwrap();
}
#[test]
@@ -146,9 +90,9 @@ memory_max = "4G"
std::fs::write(
&path,
r#"
[paths]
instances_dir = "/custom/path"
"#,
[paths]
instances_dir = "/custom/path"
"#,
)
.unwrap();
let config = load_config(&path).unwrap();
+51 -79
View File
@@ -1,11 +1,9 @@
use dirs_next;
use std::path::PathBuf;
use serde::Deserialize;
#[derive(Debug, Deserialize, Default)]
pub struct General {
#[serde(default)]
pub debug: bool,
}
pub struct General {}
#[derive(Debug, Deserialize)]
pub struct Paths {
@@ -18,16 +16,26 @@ pub struct Paths {
}
fn default_instances_dir() -> String {
"~/.local/share/mcl/instances".to_string()
dirs_next::data_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join("mcl")
.join("instances")
.to_string_lossy()
.into_owned()
}
fn default_meta_dir() -> String {
"~/.local/share/mcl/meta".to_string()
dirs_next::data_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join("mcl")
.join("meta")
.to_string_lossy()
.into_owned()
}
impl Default for Paths {
fn default() -> Self {
Paths {
Self {
instances_dir: default_instances_dir(),
meta_dir: default_meta_dir(),
java_path: None,
@@ -35,43 +43,30 @@ impl Default for Paths {
}
}
pub fn resolve_path(raw: &str) -> PathBuf {
if let Some(stripped) = raw.strip_prefix("~/") {
if let Some(home) = dirs_next::home_dir() {
return home.join(stripped);
}
} else if raw == "~" {
if let Some(home) = dirs_next::home_dir() {
return home;
}
}
PathBuf::from(raw)
}
impl Paths {
pub fn effective_java_path(&self) -> Option<&str> {
self.java_path.as_deref().filter(|s| !s.is_empty())
}
pub fn resolve_instances_dir(&self) -> std::path::PathBuf {
let raw = &self.instances_dir;
if let Some(stripped) = raw.strip_prefix("~/") {
return match dirs_next::home_dir() {
Some(home) => home.join(stripped),
None => std::path::PathBuf::from(raw),
};
}
if raw == "~" {
return match dirs_next::home_dir() {
Some(home) => home,
None => std::path::PathBuf::from(raw),
};
}
std::path::PathBuf::from(raw)
pub fn resolve_instances_dir(&self) -> PathBuf {
resolve_path(&self.instances_dir)
}
pub fn resolve_meta_dir(&self) -> std::path::PathBuf {
let raw = &self.meta_dir;
if let Some(stripped) = raw.strip_prefix("~/") {
return match dirs_next::home_dir() {
Some(home) => home.join(stripped),
None => std::path::PathBuf::from(raw),
};
}
if raw == "~" {
return match dirs_next::home_dir() {
Some(home) => home,
None => std::path::PathBuf::from(raw),
};
}
std::path::PathBuf::from(raw)
pub fn resolve_meta_dir(&self) -> PathBuf {
resolve_path(&self.meta_dir)
}
}
@@ -84,16 +79,15 @@ pub struct Defaults {
}
fn default_memory_min() -> String {
"512M".to_string()
"512M".to_owned()
}
fn default_memory_max() -> String {
"2G".to_string()
"2G".to_owned()
}
impl Default for Defaults {
fn default() -> Self {
Defaults {
Self {
memory_min: default_memory_min(),
memory_max: default_memory_max(),
}
@@ -115,22 +109,19 @@ pub struct Ui {
fn default_error_auto_dismiss_ms() -> u64 {
5000
}
fn default_error_slide_start_ms() -> u64 {
3500
}
fn default_error_fly_out_ms() -> u64 {
300
}
fn default_max_error_events() -> usize {
50
}
impl Default for Ui {
fn default() -> Self {
Ui {
Self {
error_auto_dismiss_ms: default_error_auto_dismiss_ms(),
error_slide_start_ms: default_error_slide_start_ms(),
error_fly_out_ms: default_error_fly_out_ms(),
@@ -176,66 +167,49 @@ mod tests {
#[test]
fn effective_java_path_some_when_set() {
let paths = Paths {
java_path: Some("/usr/bin/java".to_string()),
java_path: Some("/usr/bin/java".to_owned()),
..Paths::default()
};
assert_eq!(paths.effective_java_path(), Some("/usr/bin/java"));
}
#[test]
fn resolve_instances_dir_absolute_path() {
let paths = Paths {
instances_dir: "/opt/mcl/instances".to_string(),
..Paths::default()
};
assert_eq!(
paths.resolve_instances_dir(),
std::path::PathBuf::from("/opt/mcl/instances")
);
fn resolve_path_absolute() {
assert_eq!(resolve_path("/opt/mcl"), PathBuf::from("/opt/mcl"));
}
#[test]
fn resolve_instances_dir_tilde_prefix() {
let paths = Paths {
instances_dir: "~/games/mcl".to_string(),
..Paths::default()
};
let resolved = paths.resolve_instances_dir();
fn resolve_path_tilde_prefix() {
let resolved = resolve_path("~/games/mcl");
assert!(!resolved.to_string_lossy().starts_with('~'));
assert!(resolved.to_string_lossy().ends_with("games/mcl"));
}
#[test]
fn resolve_instances_dir_bare_tilde() {
let paths = Paths {
instances_dir: "~".to_string(),
..Paths::default()
};
let resolved = paths.resolve_instances_dir();
fn resolve_path_bare_tilde() {
let resolved = resolve_path("~");
assert!(!resolved.to_string_lossy().starts_with('~'));
}
#[test]
fn resolve_meta_dir_absolute_path() {
fn resolve_instances_dir_absolute() {
let paths = Paths {
meta_dir: "/opt/mcl/meta".to_string(),
instances_dir: "/opt/mcl/instances".to_owned(),
..Paths::default()
};
assert_eq!(
paths.resolve_meta_dir(),
std::path::PathBuf::from("/opt/mcl/meta")
paths.resolve_instances_dir(),
PathBuf::from("/opt/mcl/instances")
);
}
#[test]
fn resolve_meta_dir_tilde_prefix() {
fn resolve_meta_dir_absolute() {
let paths = Paths {
meta_dir: "~/mcl/meta".to_string(),
meta_dir: "/opt/mcl/meta".to_owned(),
..Paths::default()
};
let resolved = paths.resolve_meta_dir();
assert!(!resolved.to_string_lossy().starts_with('~'));
assert!(resolved.to_string_lossy().ends_with("mcl/meta"));
assert_eq!(paths.resolve_meta_dir(), PathBuf::from("/opt/mcl/meta"));
}
#[test]
@@ -257,7 +231,6 @@ mod tests {
#[test]
fn config_deserializes_from_empty_toml() {
let config: Config = toml::from_str("").unwrap();
assert!(!config.general.debug);
assert_eq!(config.defaults.memory_max, "2G");
}
@@ -271,7 +244,6 @@ debug = true
memory_max = "8G"
"#;
let config: Config = toml::from_str(toml_str).unwrap();
assert!(config.general.debug);
assert_eq!(config.defaults.memory_max, "8G");
assert_eq!(config.defaults.memory_min, "512M");
}
+244
View File
@@ -0,0 +1,244 @@
use std::path::Path;
use std::sync::LazyLock;
use ratatui::style::Color;
use ratatui::widgets::BorderType;
use ratatui_themekit::{CustomTheme, Theme, resolve_theme};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum BorderStyle {
#[default]
Rounded,
Plain,
Double,
Thick,
}
impl BorderStyle {
pub fn to_border_type(&self) -> BorderType {
match self {
Self::Rounded => BorderType::Rounded,
Self::Plain => BorderType::Plain,
Self::Double => BorderType::Double,
Self::Thick => BorderType::Thick,
}
}
}
#[derive(Debug, Deserialize, Default)]
pub struct ThemeOverrides {
pub accent: Option<Color>,
pub accent_dim: Option<Color>,
pub text: Option<Color>,
pub text_dim: Option<Color>,
pub text_bright: Option<Color>,
pub success: Option<Color>,
pub error: Option<Color>,
pub warning: Option<Color>,
pub info: Option<Color>,
pub diff_added: Option<Color>,
pub diff_removed: Option<Color>,
pub diff_context: Option<Color>,
pub border: Option<Color>,
pub surface: Option<Color>,
pub background: Option<Color>,
}
#[derive(Debug, Deserialize)]
pub struct ThemeConfig {
#[serde(default)]
pub border_style: BorderStyle,
#[serde(default = "default_theme_name")]
pub theme: String,
#[serde(default)]
pub custom: Option<ThemeOverrides>,
}
fn default_theme_name() -> String {
"catppuccin".to_owned()
}
impl Default for ThemeConfig {
fn default() -> Self {
Self {
border_style: BorderStyle::default(),
theme: default_theme_name(),
custom: None,
}
}
}
fn load_theme_config() -> ThemeConfig {
let path = super::get_config_path().join("theme.toml");
ensure_theme_exists(&path);
match std::fs::read_to_string(&path) {
Ok(content) => toml::from_str(&content).unwrap_or_else(|e| {
tracing::warn!("Failed to parse theme.toml: {}. Using defaults.", e);
ThemeConfig::default()
}),
Err(_) => ThemeConfig::default(),
}
}
fn ensure_theme_exists(path: &Path) {
if path.exists() {
return;
}
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
let _ = std::fs::write(path, include_str!("../../assets/theme.toml"));
}
fn resolve_app_theme(config: &ThemeConfig) -> Box<dyn Theme> {
let base = load_base_theme(&config.theme);
let Some(overrides) = &config.custom else {
return base;
};
Box::new(CustomTheme {
name: format!("{} (customized)", base.name()),
id: base.id().to_owned(),
accent: overrides.accent.unwrap_or_else(|| base.accent()),
accent_dim: overrides.accent_dim.unwrap_or_else(|| base.accent_dim()),
text: overrides.text.unwrap_or_else(|| base.text()),
text_dim: overrides.text_dim.unwrap_or_else(|| base.text_dim()),
text_bright: overrides.text_bright.unwrap_or_else(|| base.text_bright()),
success: overrides.success.unwrap_or_else(|| base.success()),
error: overrides.error.unwrap_or_else(|| base.error()),
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()),
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.
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() {
Some(candidate)
} else {
let with_ext = theme_dir.join(format!("{name}.toml"));
if with_ext.exists() {
Some(with_ext)
} else {
None
}
}
};
if let Some(path) = path {
if 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)
}
static THEME_CONFIG: LazyLock<ThemeConfig> = LazyLock::new(load_theme_config);
pub static THEME: LazyLock<Box<dyn Theme>> = LazyLock::new(|| resolve_app_theme(&THEME_CONFIG));
pub static BORDER_STYLE: LazyLock<BorderStyle> =
LazyLock::new(|| THEME_CONFIG.border_style.clone());
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_theme_config() {
let config = ThemeConfig::default();
assert_eq!(config.theme, "catppuccin");
assert_eq!(config.border_style, BorderStyle::Rounded);
assert!(config.custom.is_none());
}
#[test]
fn border_style_roundtrip() {
let style = BorderStyle::Double;
assert_eq!(style.to_border_type(), BorderType::Double);
}
#[test]
fn theme_config_deserialize_builtin() {
let toml_str = r#"
theme = "dracula"
border_style = "plain"
"#;
let config: ThemeConfig = toml::from_str(toml_str).unwrap();
assert_eq!(config.theme, "dracula");
assert_eq!(config.border_style, BorderStyle::Plain);
assert!(config.custom.is_none());
}
#[test]
fn theme_config_with_partial_overrides() {
let toml_str = r#"
theme = "dracula"
[custom]
accent = "Red"
"#;
let config: ThemeConfig = toml::from_str(toml_str).unwrap();
assert_eq!(config.theme, "dracula");
let overrides = config.custom.unwrap();
assert_eq!(overrides.accent, Some(Color::Red));
assert!(overrides.text.is_none());
}
#[test]
fn resolve_with_overrides_keeps_base() {
let config = ThemeConfig {
theme: "dracula".to_owned(),
custom: Some(ThemeOverrides {
accent: Some(Color::Red),
..ThemeOverrides::default()
}),
..ThemeConfig::default()
};
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());
}
#[test]
fn resolve_builtin_theme() {
let config = ThemeConfig {
theme: "dracula".to_owned(),
..ThemeConfig::default()
};
let theme = resolve_app_theme(&config);
assert_eq!(theme.id(), "dracula");
}
#[test]
fn theme_config_empty_toml_uses_defaults() {
let config: ThemeConfig = toml::from_str("").unwrap();
assert_eq!(config.theme, "catppuccin");
assert_eq!(config.border_style, BorderStyle::Rounded);
}
}
+51
View File
@@ -0,0 +1,51 @@
pub mod mods;
pub mod resource_packs;
pub mod shaders;
pub mod worlds;
pub use mods::{scan_mods, toggle_entry, ContentEntry};
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.
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 if let Some(stem) = file_name.strip_suffix(ext) {
Some((true, stem.to_string()))
} else {
None
}
}
/// For directories: check if the name ends in `.disabled`.
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())
} else {
(true, file_name.to_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>> {
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()
}
@@ -3,10 +3,20 @@ use std::path::{Path, PathBuf};
use serde::Deserialize;
type IconCell = (u8, u8, u8, u8, u8, u8);
/// A single icon cell representing two vertically stacked pixels using the "▄" half-block.
/// `bg_*` = top pixel (background color), `fg_*` = bottom pixel (foreground color).
#[derive(Debug, Clone, Copy)]
pub struct IconCell {
pub bg_r: u8,
pub bg_g: u8,
pub bg_b: u8,
pub fg_r: u8,
pub fg_g: u8,
pub fg_b: u8,
}
#[derive(Debug, Clone)]
pub struct ModEntry {
pub struct ContentEntry {
pub file_stem: String,
pub name: String,
pub description: String,
@@ -19,14 +29,28 @@ pub struct ModEntry {
#[derive(Deserialize, Default)]
struct FabricModJson {
#[serde(default)]
pub name: String,
name: String,
#[serde(default)]
pub description: String,
description: String,
#[serde(default)]
pub icon: String,
icon: serde_json::Value,
}
pub fn scan_mods(instances_dir: &Path, instance_name: &str) -> Vec<ModEntry> {
impl FabricModJson {
fn icon_path(&self) -> String {
match &self.icon {
serde_json::Value::String(s) => s.clone(),
serde_json::Value::Object(map) => map
.values()
.find_map(|v| v.as_str())
.unwrap_or("")
.to_owned(),
_ => String::new(),
}
}
}
pub fn scan_mods(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
let mods_dir = instances_dir
.join(instance_name)
.join(".minecraft")
@@ -46,25 +70,20 @@ pub fn scan_mods(instances_dir: &Path, instance_name: &str) -> Vec<ModEntry> {
None => continue,
};
let (enabled, file_stem) = if file_name.ends_with(".jar") {
(true, file_name.trim_end_matches(".jar").to_string())
} else if file_name.ends_with(".jar.disabled") {
(
false,
file_name.trim_end_matches(".jar.disabled").to_string(),
)
} else {
let Some((enabled, file_stem)) = super::parse_enabled_stem(&file_name, ".jar") else {
continue;
};
let (name, description, icon_bytes) = read_mod_metadata(&path);
let icon_lines = icon_bytes
.as_ref()
.and_then(|bytes| make_icon_pixels(bytes, 6, 3));
.and_then(|bytes| make_icon_pixels(bytes, 6, 3))
.or_else(|| Some(fallback_icon()));
entries.push(ModEntry {
file_stem: file_stem.clone(),
name: if name.is_empty() { file_stem } else { name },
let display_name = if name.is_empty() { file_stem.clone() } else { name };
entries.push(ContentEntry {
file_stem,
name: display_name,
description,
enabled,
icon_bytes,
@@ -73,7 +92,7 @@ pub fn scan_mods(instances_dir: &Path, instance_name: &str) -> Vec<ModEntry> {
});
}
entries.sort_by(|left, right| left.name.to_lowercase().cmp(&right.name.to_lowercase()));
entries.sort_by_cached_key(|e| e.name.to_lowercase());
entries
}
@@ -104,9 +123,49 @@ fn read_mod_metadata(jar_path: &Path) -> (String, String, Option<Vec<u8>>) {
fn read_fabric_meta(
archive: &mut zip::ZipArchive<std::fs::File>,
) -> Option<(String, String, String)> {
let entry = archive.by_name("fabric.mod.json").ok()?;
let data: FabricModJson = serde_json::from_reader(entry).ok()?;
Some((data.name, data.description, data.icon))
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.
fn sanitize_json_strings(input: &str) -> String {
let mut result = String::with_capacity(input.len());
let mut in_string = false;
let mut escape_next = false;
for ch in input.chars() {
if escape_next {
result.push(ch);
escape_next = false;
continue;
}
if ch == '\\' && in_string {
result.push(ch);
escape_next = true;
continue;
}
if ch == '"' {
in_string = !in_string;
result.push(ch);
continue;
}
if in_string && ch == '\n' {
result.push_str("\\n");
} else if in_string && ch == '\r' {
result.push_str("\\r");
} else if in_string && ch == '\t' {
result.push_str("\\t");
} else {
result.push(ch);
}
}
result
}
fn read_zip_bytes(archive: &mut zip::ZipArchive<std::fs::File>, path: &str) -> Option<Vec<u8>> {
@@ -137,7 +196,7 @@ 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((br, bg, bb, tr, tg, 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);
}
@@ -145,7 +204,19 @@ pub(crate) fn make_icon_pixels(
Some(rows)
}
pub fn toggle_mod(entry: &ModEntry) -> Result<(), std::io::Error> {
/// 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 };
vec![
vec![b, tb, tb, tb, tb, b],
vec![b, b, b, bt, bt, b],
vec![b, b, bt, bt, b, b],
]
}
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,
None => return Ok(()),
@@ -234,13 +305,13 @@ mod tests {
}
#[test]
fn toggle_mod_enable() {
fn toggle_entry_enable() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_mods_dir(tmp.path(), "inst");
let disabled_path = dir.join("mymod.jar.disabled");
std::fs::write(&disabled_path, b"PK\x03\x04").unwrap();
let entry = ModEntry {
let entry = ContentEntry {
file_stem: "mymod".to_string(),
name: "mymod".to_string(),
description: String::new(),
@@ -250,19 +321,19 @@ mod tests {
icon_lines: None,
};
toggle_mod(&entry).unwrap();
toggle_entry(&entry).unwrap();
assert!(!disabled_path.exists());
assert!(dir.join("mymod.jar").exists());
}
#[test]
fn toggle_mod_disable() {
fn toggle_entry_disable() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_mods_dir(tmp.path(), "inst");
let enabled_path = dir.join("mymod.jar");
std::fs::write(&enabled_path, b"PK\x03\x04").unwrap();
let entry = ModEntry {
let entry = ContentEntry {
file_stem: "mymod".to_string(),
name: "mymod".to_string(),
description: String::new(),
@@ -272,7 +343,7 @@ mod tests {
icon_lines: None,
};
toggle_mod(&entry).unwrap();
toggle_entry(&entry).unwrap();
assert!(!enabled_path.exists());
assert!(dir.join("mymod.jar.disabled").exists());
}
@@ -1,9 +1,8 @@
use std::io::Read;
use std::path::Path;
use serde::Deserialize;
use super::mods::{make_icon_pixels, ModEntry};
use super::mods::{make_icon_pixels, ContentEntry};
#[derive(Deserialize, Default)]
pub(crate) struct PackMcMeta {
@@ -38,7 +37,7 @@ pub(crate) fn extract_description(value: &serde_json::Value) -> String {
}
}
pub fn scan_resource_packs(instances_dir: &Path, instance_name: &str) -> Vec<ModEntry> {
pub fn scan_resource_packs(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
let packs_dir = instances_dir
.join(instance_name)
.join(".minecraft")
@@ -60,18 +59,9 @@ pub fn scan_resource_packs(instances_dir: &Path, instance_name: &str) -> Vec<Mod
let is_dir = path.is_dir();
let (enabled, file_stem) = if is_dir {
if file_name.ends_with(".disabled") {
(false, file_name.trim_end_matches(".disabled").to_string())
} else {
(true, file_name.clone())
}
} else if file_name.ends_with(".zip") {
(true, file_name.trim_end_matches(".zip").to_string())
} else if file_name.ends_with(".zip.disabled") {
(
false,
file_name.trim_end_matches(".zip.disabled").to_string(),
)
super::parse_enabled_stem_dir(&file_name)
} else if let Some(pair) = super::parse_enabled_stem(&file_name, ".zip") {
pair
} else {
continue;
};
@@ -86,9 +76,10 @@ pub fn scan_resource_packs(instances_dir: &Path, instance_name: &str) -> Vec<Mod
.as_ref()
.and_then(|bytes| make_icon_pixels(bytes, 6, 3));
entries.push(ModEntry {
file_stem: file_stem.clone(),
name: if name.is_empty() { file_stem } else { name },
let display_name = if name.is_empty() { file_stem.clone() } else { name };
entries.push(ContentEntry {
file_stem,
name: display_name,
description,
enabled,
icon_bytes,
@@ -97,72 +88,36 @@ pub fn scan_resource_packs(instances_dir: &Path, instance_name: &str) -> Vec<Mod
});
}
entries.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
entries.sort_by_cached_key(|e| e.name.to_lowercase());
entries
}
fn read_pack_metadata_from_zip(zip_path: &Path) -> (String, String, Option<Vec<u8>>) {
let file = match std::fs::File::open(zip_path) {
Ok(f) => f,
Err(_) => return (String::new(), String::new(), None),
let Some(mut archive) = super::open_zip(zip_path) else {
return (String::new(), String::new(), None);
};
let mut archive = match zip::ZipArchive::new(file) {
Ok(a) => a,
Err(_) => return (String::new(), String::new(), None),
};
let description = read_pack_description(&mut archive);
let icon_bytes = {
let mut buf = Vec::new();
match archive.by_name("pack.png") {
Ok(mut entry) => {
if entry.read_to_end(&mut buf).is_ok() {
Some(buf)
} else {
None
}
}
Err(_) => None,
}
};
let icon_bytes = super::read_icon_from_zip(&mut archive);
(String::new(), description, icon_bytes)
}
fn read_pack_description(archive: &mut zip::ZipArchive<std::fs::File>) -> String {
let entry = match archive.by_name("pack.mcmeta") {
Ok(e) => e,
Err(_) => return String::new(),
};
let meta: PackMcMeta = match serde_json::from_reader(entry) {
Ok(m) => m,
Err(_) => return String::new(),
};
extract_description(&meta.pack.description)
archive
.by_name("pack.mcmeta")
.ok()
.and_then(|entry| serde_json::from_reader::<_, PackMcMeta>(entry).ok())
.map(|meta| extract_description(&meta.pack.description))
.unwrap_or_default()
}
fn read_pack_metadata_from_dir(dir: &Path) -> (String, String, Option<Vec<u8>>) {
let actual_dir = dir.to_path_buf();
let description = std::fs::read_to_string(dir.join("pack.mcmeta"))
.ok()
.and_then(|content| serde_json::from_str::<PackMcMeta>(&content).ok())
.map(|meta| extract_description(&meta.pack.description))
.unwrap_or_default();
let description = {
let mcmeta_path = actual_dir.join("pack.mcmeta");
match std::fs::read_to_string(&mcmeta_path) {
Ok(content) => match serde_json::from_str::<PackMcMeta>(&content) {
Ok(meta) => extract_description(&meta.pack.description),
Err(_) => String::new(),
},
Err(_) => String::new(),
}
};
let icon_bytes = {
let icon_path = actual_dir.join("pack.png");
std::fs::read(&icon_path).ok()
};
let icon_bytes = std::fs::read(dir.join("pack.png")).ok();
(String::new(), description, icon_bytes)
}
@@ -1,10 +1,9 @@
use std::io::Read;
use std::path::Path;
use super::mods::{make_icon_pixels, ModEntry};
use super::mods::{make_icon_pixels, ContentEntry};
use super::resource_packs::{extract_description, PackMcMeta};
pub fn scan_shaders(instances_dir: &Path, instance_name: &str) -> Vec<ModEntry> {
pub fn scan_shaders(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
let shaders_dir = instances_dir
.join(instance_name)
.join(".minecraft")
@@ -26,18 +25,9 @@ pub fn scan_shaders(instances_dir: &Path, instance_name: &str) -> Vec<ModEntry>
let is_dir = path.is_dir();
let (enabled, file_stem) = if is_dir {
if file_name.ends_with(".disabled") {
(false, file_name.trim_end_matches(".disabled").to_string())
} else {
(true, file_name.clone())
}
} else if file_name.ends_with(".zip") {
(true, file_name.trim_end_matches(".zip").to_string())
} else if file_name.ends_with(".zip.disabled") {
(
false,
file_name.trim_end_matches(".zip.disabled").to_string(),
)
super::parse_enabled_stem_dir(&file_name)
} else if let Some(pair) = super::parse_enabled_stem(&file_name, ".zip") {
pair
} else {
continue;
};
@@ -52,9 +42,9 @@ pub fn scan_shaders(instances_dir: &Path, instance_name: &str) -> Vec<ModEntry>
.as_ref()
.and_then(|bytes| make_icon_pixels(bytes, 6, 3));
entries.push(ModEntry {
file_stem: file_stem.clone(),
name: file_stem,
entries.push(ContentEntry {
name: file_stem.clone(),
file_stem,
description,
enabled,
icon_bytes,
@@ -63,54 +53,30 @@ pub fn scan_shaders(instances_dir: &Path, instance_name: &str) -> Vec<ModEntry>
});
}
entries.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
entries.sort_by_cached_key(|e| e.name.to_lowercase());
entries
}
fn read_shader_metadata_from_zip(zip_path: &Path) -> (String, Option<Vec<u8>>) {
let file = match std::fs::File::open(zip_path) {
Ok(f) => f,
Err(_) => return (String::new(), None),
let Some(mut archive) = super::open_zip(zip_path) else {
return (String::new(), None);
};
let mut archive = match zip::ZipArchive::new(file) {
Ok(a) => a,
Err(_) => return (String::new(), None),
};
let description = match archive.by_name("pack.mcmeta") {
Ok(entry) => match serde_json::from_reader::<_, PackMcMeta>(entry) {
Ok(meta) => extract_description(&meta.pack.description),
Err(_) => String::new(),
},
Err(_) => String::new(),
};
let icon_bytes = {
let mut buf = Vec::new();
match archive.by_name("pack.png") {
Ok(mut entry) => {
if entry.read_to_end(&mut buf).is_ok() {
Some(buf)
} else {
None
}
}
Err(_) => None,
}
};
let description = archive
.by_name("pack.mcmeta")
.ok()
.and_then(|entry| serde_json::from_reader::<_, PackMcMeta>(entry).ok())
.map(|meta| extract_description(&meta.pack.description))
.unwrap_or_default();
let icon_bytes = super::read_icon_from_zip(&mut archive);
(description, icon_bytes)
}
fn read_shader_metadata_from_dir(dir: &Path) -> (String, Option<Vec<u8>>) {
let description = match std::fs::read_to_string(dir.join("pack.mcmeta")) {
Ok(content) => match serde_json::from_str::<PackMcMeta>(&content) {
Ok(meta) => extract_description(&meta.pack.description),
Err(_) => String::new(),
},
Err(_) => String::new(),
};
let description = std::fs::read_to_string(dir.join("pack.mcmeta"))
.ok()
.and_then(|content| serde_json::from_str::<PackMcMeta>(&content).ok())
.map(|meta| extract_description(&meta.pack.description))
.unwrap_or_default();
let icon_bytes = std::fs::read(dir.join("pack.png")).ok();
@@ -1,8 +1,8 @@
use std::path::Path;
use super::mods::{make_icon_pixels, ModEntry};
use super::mods::{make_icon_pixels, ContentEntry};
pub fn scan_worlds(instances_dir: &Path, instance_name: &str) -> Vec<ModEntry> {
pub fn scan_worlds(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
let saves_dir = instances_dir
.join(instance_name)
.join(".minecraft")
@@ -26,21 +26,19 @@ pub fn scan_worlds(instances_dir: &Path, instance_name: &str) -> Vec<ModEntry> {
None => continue,
};
let (enabled, file_stem) = if file_name.ends_with(".disabled") {
(false, file_name.trim_end_matches(".disabled").to_string())
} else {
(true, file_name.clone())
};
let (enabled, file_stem) = super::parse_enabled_stem_dir(&file_name);
let icon_bytes = std::fs::read(path.join("icon.png")).ok();
let icon_lines = icon_bytes
.as_ref()
.and_then(|bytes| make_icon_pixels(bytes, 12, 6));
entries.push(ModEntry {
file_stem: file_stem.clone(),
name: file_stem,
description: String::new(),
let description = world_description(&path);
entries.push(ContentEntry {
name: file_stem.clone(),
file_stem,
description,
enabled,
icon_bytes,
path,
@@ -48,10 +46,85 @@ pub fn scan_worlds(instances_dir: &Path, instance_name: &str) -> Vec<ModEntry> {
});
}
entries.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
entries.sort_by_cached_key(|e| e.name.to_lowercase());
entries
}
fn world_description(world_dir: &Path) -> String {
let level_dat = world_dir.join("level.dat");
let created = world_dir
.metadata()
.ok()
.and_then(|m| m.created().ok().or_else(|| m.modified().ok()))
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_secs());
let modified = level_dat
.metadata()
.ok()
.and_then(|m| m.modified().ok())
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_secs());
let dir_size = dir_size_approx(world_dir);
let mut lines = Vec::new();
if let Some(secs) = created {
if let Some(dt) = chrono::DateTime::from_timestamp(secs as i64, 0) {
lines.push(format!("Created: {}", dt.format("%Y-%m-%d %H:%M")));
}
}
if let Some(secs) = modified {
if let Some(dt) = chrono::DateTime::from_timestamp(secs as i64, 0) {
lines.push(format!("Played: {}", dt.format("%Y-%m-%d %H:%M")));
}
}
if dir_size > 0 {
lines.push(format!("Size: {}", format_size(dir_size)));
}
lines.join("\n")
}
fn dir_size_approx(path: &Path) -> u64 {
let mut total = 0u64;
if let Ok(rd) = std::fs::read_dir(path) {
for entry in rd.flatten() {
if let Ok(meta) = entry.metadata() {
if meta.is_file() {
total += meta.len();
}
}
}
}
// Check region folder too (main chunk data)
let region = path.join("region");
if let Ok(rd) = std::fs::read_dir(region) {
for entry in rd.flatten() {
if let Ok(meta) = entry.metadata() {
total += meta.len();
}
}
}
total
}
fn format_size(bytes: u64) -> String {
if bytes < 1024 {
format!("{} B", bytes)
} else if bytes < 1024 * 1024 {
format!("{:.1} KB", bytes as f64 / 1024.0)
} else if bytes < 1024 * 1024 * 1024 {
format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0))
} else {
format!("{:.2} GB", bytes as f64 / (1024.0 * 1024.0 * 1024.0))
}
}
#[cfg(test)]
mod tests {
use super::*;
+99 -15
View File
@@ -2,17 +2,38 @@ use std::path::{Path, PathBuf};
use crate::instance::models::InstanceConfig;
const ICON_BYTES: &[u8] = include_bytes!("../../assets/icon.png");
const ICON_BYTES: &[u8] = include_bytes!("../../assets/icon.svg");
pub fn desktop_path(name: &str) -> Option<PathBuf> {
dirs_next::data_dir().map(|d| {
d.join("applications")
.join(format!("mcl-{}.desktop", sanitize(name)))
})
let sanitized = sanitize(name);
#[cfg(target_os = "linux")]
{
dirs_next::data_dir().map(|d| {
d.join("applications")
.join(format!("mcl-{sanitized}.desktop"))
})
}
#[cfg(target_os = "windows")]
{
dirs::desktop_dir().map(|d| d.join(format!("Minecraft - {sanitized}.bat")))
}
#[cfg(target_os = "macos")]
{
dirs::desktop_dir().map(|d| d.join(format!("Minecraft - {sanitized}.command")))
}
#[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
{
let _ = sanitized;
None
}
}
pub fn icon_path() -> Option<PathBuf> {
dirs_next::data_dir().map(|d| d.join("mcl").join("icon.png"))
dirs_next::data_dir().map(|d| d.join("mcl").join("icon.svg"))
}
fn ensure_icon() -> Option<PathBuf> {
@@ -38,7 +59,7 @@ pub fn exists(name: &str) -> bool {
pub fn create(config: &InstanceConfig) -> std::io::Result<PathBuf> {
let path = desktop_path(&config.name)
.ok_or_else(|| std::io::Error::other("cannot resolve data directory"))?;
.ok_or_else(|| std::io::Error::other("cannot resolve shortcut directory"))?;
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
@@ -47,6 +68,14 @@ pub fn create(config: &InstanceConfig) -> std::io::Result<PathBuf> {
let icon = ensure_icon();
let content = build_content(&config.name, icon.as_deref());
std::fs::write(&path, content)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let perms = std::fs::Permissions::from_mode(0o755);
std::fs::set_permissions(&path, perms)?;
}
Ok(path)
}
@@ -80,6 +109,32 @@ pub fn rename(old_name: &str, new_config: &InstanceConfig) -> std::io::Result<()
}
fn build_content(name: &str, icon: Option<&Path>) -> String {
#[cfg(target_os = "linux")]
{
build_linux_desktop(name, icon)
}
#[cfg(target_os = "windows")]
{
let _ = icon;
build_windows_shortcut(name)
}
#[cfg(target_os = "macos")]
{
let _ = icon;
build_macos_command(name)
}
#[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
{
let _ = (name, icon);
String::new()
}
}
#[cfg(target_os = "linux")]
fn build_linux_desktop(name: &str, icon: Option<&Path>) -> String {
let mut out = String::new();
out.push_str("[Desktop Entry]\n");
out.push_str("Version=1.0\n");
@@ -95,6 +150,25 @@ fn build_content(name: &str, icon: Option<&Path>) -> String {
out
}
#[cfg(target_os = "windows")]
fn build_windows_shortcut(name: &str) -> String {
let mut out = String::new();
out.push_str("@echo off\r\n");
out.push_str(&format!("title Minecraft - {name}\r\n"));
out.push_str(&format!("mcl instance launch \"{name}\"\r\n"));
out.push_str("pause\r\n");
out
}
#[cfg(target_os = "macos")]
fn build_macos_command(name: &str) -> String {
let mut out = String::new();
out.push_str("#!/bin/bash\n");
out.push_str(&format!("# Launch Minecraft instance: {name}\n"));
out.push_str(&format!("mcl instance launch \"{name}\"\n"));
out
}
fn sanitize(name: &str) -> String {
name.chars()
.map(|c| {
@@ -123,20 +197,30 @@ mod tests {
}
#[test]
fn build_content_with_icon() {
let icon = PathBuf::from("/home/user/icon.png");
let content = build_content("TestPack", Some(&icon));
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"));
}
}
#[test]
#[cfg(target_os = "linux")]
fn build_content_linux() {
let content = build_content("TestPack", None);
assert!(content.contains("Name=Minecraft - TestPack"));
assert!(content.contains("Exec=mcl instance launch \"TestPack\""));
assert!(content.contains("Icon=/home/user/icon.png"));
assert!(content.contains("Terminal=true"));
assert!(content.contains("Categories=Game;"));
}
#[test]
fn build_content_without_icon() {
let content = build_content("TestPack", None);
assert!(content.contains("Name=Minecraft - TestPack"));
assert!(!content.contains("Icon="));
#[cfg(target_os = "linux")]
fn build_content_linux_with_icon() {
let icon = PathBuf::from("/tmp/icon.png");
let content = build_content("TestPack", Some(&icon));
assert!(content.contains("Icon=/tmp/icon.png"));
}
}
+52 -104
View File
@@ -71,31 +71,31 @@ struct LoaderLibrary {
}
fn lib_allowed(lib: &MetaLibrary) -> bool {
let rules = match &lib.rules {
Some(r) => r,
None => return true,
let Some(rules) = &lib.rules else {
return true;
};
let current_os = match std::env::consts::OS {
"macos" => "osx",
other => other,
};
let mut allowed = false;
let mut dominated = false;
for rule in rules {
let matches = match &rule.os {
Some(os) => os.name.as_deref().map(|n| n == current_os).unwrap_or(true),
None => true,
};
if !matches {
let matches_os = rule
.os
.as_ref()
.and_then(|os| os.name.as_deref())
.is_none_or(|n| n == current_os);
if !matches_os {
continue;
}
if rule.action == "disallow" {
return false;
}
if rule.action == "allow" {
allowed = true;
dominated = true;
match rule.action.as_str() {
"disallow" => return false,
"allow" => return true,
_ => {}
}
}
allowed
!dominated
}
pub async fn launch(
@@ -114,7 +114,7 @@ pub async fn launch(
if !meta_path.exists() {
return Err(LaunchError::MetaNotFound(meta_path.display().to_string()));
}
let meta: MetaJson = serde_json::from_slice(&std::fs::read(&meta_path)?)?;
let meta: MetaJson = serde_json::from_slice(&tokio::fs::read(&meta_path).await?)?;
let lib_dir = meta_dir.join("libraries");
let mut classpath: Vec<PathBuf> = meta
@@ -130,98 +130,46 @@ pub async fn launch(
})
.collect();
let main_class = match config.loader {
ModLoader::Vanilla => meta.main_class.clone(),
ModLoader::Fabric => {
let lv = config.loader_version.as_deref().unwrap_or("unknown");
let profile_path = meta_dir
.join("loader-profiles")
.join(format!("fabric-{}-{}.json", config.game_version, lv));
if !profile_path.exists() {
return Err(LaunchError::MetaNotFound(
profile_path.display().to_string(),
));
}
let profile: LoaderProfileJson =
serde_json::from_slice(&std::fs::read(&profile_path)?)?;
for lib in &profile.libraries {
if let Some(p) = crate::net::maven_coord_to_path(&lib.name) {
let lv = config.loader_version.as_deref().unwrap_or("unknown");
let profile_filename = match config.loader {
ModLoader::Vanilla => None,
ModLoader::Fabric => Some(format!("fabric-{}-{}.json", config.game_version, lv)),
ModLoader::Quilt => Some(format!("quilt-{}-{}.json", config.game_version, lv)),
ModLoader::Forge => Some(format!("forge-{}-{}.json", config.game_version, lv)),
ModLoader::NeoForge => Some(format!("neoforge-{}.json", lv)),
};
let main_class = if let Some(filename) = profile_filename {
let profile_path = meta_dir.join("loader-profiles").join(&filename);
if !profile_path.exists() {
return Err(LaunchError::MetaNotFound(
profile_path.display().to_string(),
));
}
let profile: LoaderProfileJson =
serde_json::from_slice(&tokio::fs::read(&profile_path).await?)?;
let has_local_libs = matches!(config.loader, ModLoader::Forge | ModLoader::NeoForge);
let local_lib_dir = minecraft_dir.join("libraries");
for lib in &profile.libraries {
if let Some(p) = crate::net::maven_coord_to_path(&lib.name) {
if has_local_libs {
let in_meta = lib_dir.join(&p);
let in_local = local_lib_dir.join(&p);
if in_meta.exists() {
classpath.push(in_meta);
} else if in_local.exists() {
classpath.push(in_local);
}
} else {
classpath.push(lib_dir.join(p));
}
}
profile.main_class
}
ModLoader::Quilt => {
let lv = config.loader_version.as_deref().unwrap_or("unknown");
let profile_path = meta_dir
.join("loader-profiles")
.join(format!("quilt-{}-{}.json", config.game_version, lv));
if !profile_path.exists() {
return Err(LaunchError::MetaNotFound(
profile_path.display().to_string(),
));
}
let profile: LoaderProfileJson =
serde_json::from_slice(&std::fs::read(&profile_path)?)?;
for lib in &profile.libraries {
if let Some(p) = crate::net::maven_coord_to_path(&lib.name) {
classpath.push(lib_dir.join(p));
}
}
profile.main_class
}
ModLoader::Forge => {
let lv = config.loader_version.as_deref().unwrap_or("unknown");
let profile_path = meta_dir
.join("loader-profiles")
.join(format!("forge-{}-{}.json", config.game_version, lv));
if !profile_path.exists() {
return Err(LaunchError::MetaNotFound(
profile_path.display().to_string(),
));
}
let profile: LoaderProfileJson =
serde_json::from_slice(&std::fs::read(&profile_path)?)?;
let forge_lib_dir = minecraft_dir.join("libraries");
for lib in &profile.libraries {
if let Some(p) = crate::net::maven_coord_to_path(&lib.name) {
let in_meta = lib_dir.join(&p);
let in_forge = forge_lib_dir.join(&p);
if in_meta.exists() {
classpath.push(in_meta);
} else if in_forge.exists() {
classpath.push(in_forge);
}
}
}
profile.main_class
}
ModLoader::NeoForge => {
let lv = config.loader_version.as_deref().unwrap_or("unknown");
let profile_path = meta_dir
.join("loader-profiles")
.join(format!("neoforge-{}.json", lv));
if !profile_path.exists() {
return Err(LaunchError::MetaNotFound(
profile_path.display().to_string(),
));
}
let profile: LoaderProfileJson =
serde_json::from_slice(&std::fs::read(&profile_path)?)?;
let neo_lib_dir = minecraft_dir.join("libraries");
for lib in &profile.libraries {
if let Some(p) = crate::net::maven_coord_to_path(&lib.name) {
let in_meta = lib_dir.join(&p);
let in_neo = neo_lib_dir.join(&p);
if in_meta.exists() {
classpath.push(in_meta);
} else if in_neo.exists() {
classpath.push(in_neo);
}
}
}
profile.main_class
}
profile.main_class
} else {
meta.main_class.clone()
};
classpath.push(
-542
View File
@@ -1,542 +0,0 @@
use std::path::Path;
use async_trait::async_trait;
use crate::instance::models::ModLoader;
use crate::net::fabric;
use crate::net::forge;
use crate::net::mojang;
use crate::net::neoforge;
use crate::net::quilt;
use crate::net::{HttpClient, NetError};
#[derive(Debug, Clone)]
pub struct GameVersion {
pub id: String,
pub stable: bool,
}
#[async_trait]
pub trait ModLoaderInstaller: Send + Sync {
/// Returns the ModLoader variant this installer handles.
fn loader_type(&self) -> ModLoader;
async fn get_game_versions(&self, client: &HttpClient) -> Result<Vec<GameVersion>, NetError>;
/// Returns available loader versions for the given Minecraft version.
/// For Vanilla, returns a single placeholder entry.
async fn get_versions(
&self,
client: &HttpClient,
game_version: &str,
) -> Result<Vec<String>, NetError>;
/// Downloads and installs the loader into the given instance directory.
/// For Vanilla, this is a no-op since Minecraft files are downloaded separately.
async fn install(
&self,
client: &HttpClient,
game_version: &str,
loader_version: &str,
instance_dir: &Path,
meta_dir: &Path,
) -> Result<(), NetError>;
}
pub struct VanillaInstaller;
#[async_trait]
impl ModLoaderInstaller for VanillaInstaller {
fn loader_type(&self) -> ModLoader {
ModLoader::Vanilla
}
async fn get_game_versions(&self, client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
let manifest = match mojang::fetch_version_manifest(client).await {
Ok(m) => m,
Err(e) => {
return Err(e);
}
};
Ok(manifest
.versions
.into_iter()
.map(|version| GameVersion {
id: version.id,
stable: version.version_type == "release",
})
.collect())
}
async fn get_versions(
&self,
_client: &HttpClient,
_game_version: &str,
) -> Result<Vec<String>, NetError> {
Ok(vec!["vanilla".to_string()])
}
async fn install(
&self,
_client: &HttpClient,
_game_version: &str,
_loader_version: &str,
_instance_dir: &Path,
_meta_dir: &Path,
) -> Result<(), NetError> {
// Vanilla: no loader to install; Minecraft files downloaded by Mojang API separately
Ok(())
}
}
pub struct FabricInstaller;
#[async_trait]
impl ModLoaderInstaller for FabricInstaller {
fn loader_type(&self) -> ModLoader {
ModLoader::Fabric
}
async fn get_game_versions(&self, client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
fabric::fetch_fabric_game_versions(client).await
}
async fn get_versions(
&self,
client: &HttpClient,
game_version: &str,
) -> Result<Vec<String>, NetError> {
let loader_versions = match fabric::fetch_fabric_versions(client, game_version).await {
Ok(v) => v,
Err(e) => {
return Err(e);
}
};
Ok(loader_versions
.into_iter()
.map(|lv| lv.loader.version)
.collect())
}
async fn install(
&self,
client: &HttpClient,
game_version: &str,
loader_version: &str,
_instance_dir: &Path,
meta_dir: &Path,
) -> Result<(), NetError> {
let profile = match fabric::fetch_fabric_profile(client, game_version, loader_version).await
{
Ok(p) => p,
Err(e) => {
return Err(e);
}
};
match fabric::download_fabric_libraries(client, &profile, meta_dir).await {
Ok(()) => {}
Err(e) => {
return Err(e);
}
}
let profiles_dir = meta_dir.join("loader-profiles");
match std::fs::create_dir_all(&profiles_dir) {
Ok(_) => {
let profile_path =
profiles_dir.join(format!("fabric-{}-{}.json", game_version, loader_version));
match serde_json::to_string_pretty(&profile) {
Ok(json) => {
if let Err(e) = std::fs::write(&profile_path, &json) {
tracing::warn!("Failed to save Fabric profile: {}", e);
}
}
Err(e) => tracing::warn!("Failed to serialize Fabric profile: {}", e),
}
}
Err(e) => tracing::warn!("Failed to create loader-profiles dir: {}", e),
}
Ok(())
}
}
pub struct ForgeInstaller;
#[async_trait]
impl ModLoaderInstaller for ForgeInstaller {
fn loader_type(&self) -> ModLoader {
ModLoader::Forge
}
async fn get_game_versions(&self, client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
forge::fetch_forge_game_versions(client).await
}
async fn get_versions(
&self,
client: &HttpClient,
game_version: &str,
) -> Result<Vec<String>, NetError> {
forge::fetch_forge_versions(client, game_version).await
}
async fn install(
&self,
client: &HttpClient,
game_version: &str,
loader_version: &str,
instance_dir: &Path,
meta_dir: &Path,
) -> Result<(), NetError> {
let installer_jar = instance_dir.join(".minecraft").join("forge-installer.jar");
match forge::download_forge_installer(client, game_version, loader_version, &installer_jar)
.await
{
Ok(()) => {}
Err(e) => {
return Err(e);
}
}
let java_path = crate::net::detect_java_path();
match forge::run_forge_installer(&installer_jar, instance_dir, &java_path).await {
Ok(()) => {}
Err(e) => {
let _ = tokio::fs::remove_file(&installer_jar).await;
return Err(e);
}
}
if let Err(e) = tokio::fs::remove_file(&installer_jar).await {
tracing::error!(
"Failed to remove Forge installer JAR {}: {}",
installer_jar.display(),
e
);
}
let forge_ver_json = instance_dir
.join(".minecraft")
.join("versions")
.join(format!("{}-forge-{}", game_version, loader_version))
.join(format!("{}-forge-{}.json", game_version, loader_version));
if forge_ver_json.exists() {
#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct ForgeVersionJson {
main_class: String,
#[serde(default)]
libraries: Vec<ForgeVersionLib>,
}
#[derive(serde::Deserialize)]
struct ForgeVersionLib {
name: String,
}
match std::fs::read(&forge_ver_json)
.ok()
.and_then(|b| serde_json::from_slice::<ForgeVersionJson>(&b).ok())
{
Some(forge_ver) => {
let profile_dir = meta_dir.join("loader-profiles");
match std::fs::create_dir_all(&profile_dir) {
Ok(_) => {
let profile_path = profile_dir
.join(format!("forge-{}-{}.json", game_version, loader_version));
let libs: Vec<serde_json::Value> = forge_ver
.libraries
.iter()
.map(|l| serde_json::json!({"name": l.name}))
.collect();
let json_val = serde_json::json!({
"mainClass": forge_ver.main_class,
"libraries": libs
});
match serde_json::to_string_pretty(&json_val) {
Ok(json) => {
if let Err(e) = std::fs::write(&profile_path, &json) {
tracing::warn!("Failed to save Forge profile: {}", e);
}
}
Err(e) => {
tracing::warn!("Failed to serialize Forge profile: {}", e)
}
}
}
Err(e) => tracing::warn!("Failed to create loader-profiles dir: {}", e),
}
}
None => tracing::warn!(
"Could not read Forge version JSON at {}",
forge_ver_json.display()
),
}
} else {
tracing::warn!(
"Forge version JSON not found at {} — profile not saved",
forge_ver_json.display()
);
}
Ok(())
}
}
pub struct QuiltInstaller;
#[async_trait]
impl ModLoaderInstaller for QuiltInstaller {
fn loader_type(&self) -> ModLoader {
ModLoader::Quilt
}
async fn get_game_versions(&self, client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
quilt::fetch_quilt_game_versions(client).await
}
async fn get_versions(
&self,
client: &HttpClient,
game_version: &str,
) -> Result<Vec<String>, NetError> {
let loader_versions = match quilt::fetch_quilt_versions(client, game_version).await {
Ok(v) => v,
Err(e) => {
return Err(e);
}
};
Ok(loader_versions
.into_iter()
.map(|lv| lv.loader.version)
.collect())
}
async fn install(
&self,
client: &HttpClient,
game_version: &str,
loader_version: &str,
_instance_dir: &Path,
meta_dir: &Path,
) -> Result<(), NetError> {
let profile = match quilt::fetch_quilt_profile(client, game_version, loader_version).await {
Ok(p) => p,
Err(e) => {
return Err(e);
}
};
match quilt::download_quilt_libraries(client, &profile, meta_dir).await {
Ok(()) => {}
Err(e) => {
return Err(e);
}
}
let profiles_dir = meta_dir.join("loader-profiles");
match std::fs::create_dir_all(&profiles_dir) {
Ok(_) => {
let profile_path =
profiles_dir.join(format!("quilt-{}-{}.json", game_version, loader_version));
match serde_json::to_string_pretty(&profile) {
Ok(json) => {
if let Err(e) = std::fs::write(&profile_path, &json) {
tracing::warn!("Failed to save Quilt profile: {}", e);
}
}
Err(e) => tracing::warn!("Failed to serialize Quilt profile: {}", e),
}
}
Err(e) => tracing::warn!("Failed to create loader-profiles dir: {}", e),
}
Ok(())
}
}
pub struct NeoForgeInstaller;
#[async_trait]
impl ModLoaderInstaller for NeoForgeInstaller {
fn loader_type(&self) -> ModLoader {
ModLoader::NeoForge
}
async fn get_game_versions(&self, client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
neoforge::fetch_neoforge_game_versions(client).await
}
async fn get_versions(
&self,
client: &HttpClient,
game_version: &str,
) -> Result<Vec<String>, NetError> {
neoforge::fetch_neoforge_versions(client, game_version).await
}
async fn install(
&self,
client: &HttpClient,
_game_version: &str,
loader_version: &str,
instance_dir: &Path,
meta_dir: &Path,
) -> Result<(), NetError> {
let installer_jar = instance_dir
.join(".minecraft")
.join("neoforge-installer.jar");
match neoforge::download_neoforge_installer(client, loader_version, &installer_jar).await {
Ok(()) => {}
Err(e) => {
return Err(e);
}
}
let java_path = crate::net::detect_java_path();
match neoforge::run_neoforge_installer(&installer_jar, instance_dir, &java_path).await {
Ok(()) => {}
Err(e) => {
let _ = tokio::fs::remove_file(&installer_jar).await;
return Err(e);
}
}
if let Err(e) = tokio::fs::remove_file(&installer_jar).await {
tracing::error!(
"Failed to remove NeoForge installer JAR {}: {}",
installer_jar.display(),
e
);
}
let neo_ver_json = instance_dir
.join(".minecraft")
.join("versions")
.join(format!("neoforge-{}", loader_version))
.join(format!("neoforge-{}.json", loader_version));
if neo_ver_json.exists() {
#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct ForgeVersionJson {
main_class: String,
#[serde(default)]
libraries: Vec<ForgeVersionLib>,
}
#[derive(serde::Deserialize)]
struct ForgeVersionLib {
name: String,
}
match std::fs::read(&neo_ver_json)
.ok()
.and_then(|b| serde_json::from_slice::<ForgeVersionJson>(&b).ok())
{
Some(neo_ver) => {
let profile_dir = meta_dir.join("loader-profiles");
match std::fs::create_dir_all(&profile_dir) {
Ok(_) => {
let profile_path =
profile_dir.join(format!("neoforge-{}.json", loader_version));
let libs: Vec<serde_json::Value> = neo_ver
.libraries
.iter()
.map(|l| serde_json::json!({"name": l.name}))
.collect();
let json_val = serde_json::json!({
"mainClass": neo_ver.main_class,
"libraries": libs
});
match serde_json::to_string_pretty(&json_val) {
Ok(json) => {
if let Err(e) = std::fs::write(&profile_path, &json) {
tracing::warn!("Failed to save NeoForge profile: {}", e);
}
}
Err(e) => {
tracing::warn!("Failed to serialize NeoForge profile: {}", e)
}
}
}
Err(e) => tracing::warn!("Failed to create loader-profiles dir: {}", e),
}
}
None => tracing::warn!(
"Could not read NeoForge version JSON at {}",
neo_ver_json.display()
),
}
} else {
tracing::warn!(
"NeoForge version JSON not found at {} — profile not saved",
neo_ver_json.display()
);
}
Ok(())
}
}
pub fn get_installer(loader: ModLoader) -> Box<dyn ModLoaderInstaller + Send + Sync> {
match loader {
ModLoader::Vanilla => Box::new(VanillaInstaller),
ModLoader::Fabric => Box::new(FabricInstaller),
ModLoader::Forge => Box::new(ForgeInstaller),
ModLoader::NeoForge => Box::new(NeoForgeInstaller),
ModLoader::Quilt => Box::new(QuiltInstaller),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_vanilla_factory() {
let installer = get_installer(ModLoader::Vanilla);
assert_eq!(installer.loader_type(), ModLoader::Vanilla);
}
#[tokio::test]
async fn test_vanilla_get_versions() {
let client = HttpClient::new();
let installer = VanillaInstaller;
match installer.get_versions(&client, "1.20.1").await {
Ok(versions) => {
assert!(!versions.is_empty());
assert_eq!(versions[0], "vanilla");
}
Err(e) => panic!("get_versions failed: {}", e),
}
}
#[tokio::test]
async fn test_vanilla_install_noop() {
let client = HttpClient::new();
let installer = VanillaInstaller;
let tmp = std::env::temp_dir().join("mcl_test_vanilla_install");
let meta = std::env::temp_dir().join("mcl_test_meta");
match installer
.install(&client, "1.20.1", "vanilla", &tmp, &meta)
.await
{
Ok(()) => {}
Err(e) => panic!("install failed: {}", e),
}
}
#[tokio::test]
async fn test_vanilla_get_game_versions() {
let client = HttpClient::new();
let installer = VanillaInstaller;
match installer.get_game_versions(&client).await {
Ok(versions) => {
assert!(!versions.is_empty());
assert!(versions.iter().any(|version| version.id == "1.20.1"));
}
Err(e) => panic!("get_game_versions failed: {}", e),
}
}
}
+53
View File
@@ -0,0 +1,53 @@
use std::path::Path;
use async_trait::async_trait;
use super::{GameVersion, ModLoaderInstaller};
use crate::instance::models::ModLoader;
use crate::net::{fabric as fabric_api, HttpClient, NetError};
pub struct FabricInstaller;
#[async_trait]
impl ModLoaderInstaller for FabricInstaller {
fn loader_type(&self) -> ModLoader {
ModLoader::Fabric
}
async fn get_game_versions(&self, client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
fabric_api::fetch_fabric_game_versions(client).await
}
async fn get_versions(
&self,
client: &HttpClient,
game_version: &str,
) -> Result<Vec<String>, NetError> {
let loader_versions = fabric_api::fetch_fabric_versions(client, game_version).await?;
Ok(loader_versions
.into_iter()
.map(|lv| lv.loader.version)
.collect())
}
async fn install(
&self,
client: &HttpClient,
game_version: &str,
loader_version: &str,
_instance_dir: &Path,
meta_dir: &Path,
) -> Result<(), NetError> {
let profile =
fabric_api::fetch_fabric_profile(client, game_version, loader_version).await?;
fabric_api::download_fabric_libraries(client, &profile, meta_dir).await?;
super::save_profile_json(
meta_dir,
&format!("fabric-{game_version}-{loader_version}.json"),
&profile,
)?;
Ok(())
}
}
+73
View File
@@ -0,0 +1,73 @@
use std::path::Path;
use async_trait::async_trait;
use super::{GameVersion, ModLoaderInstaller};
use crate::instance::models::ModLoader;
use crate::net::{forge as forge_api, HttpClient, NetError};
pub struct ForgeInstaller;
#[async_trait]
impl ModLoaderInstaller for ForgeInstaller {
fn loader_type(&self) -> ModLoader {
ModLoader::Forge
}
async fn get_game_versions(&self, client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
forge_api::fetch_forge_game_versions(client).await
}
async fn get_versions(
&self,
client: &HttpClient,
game_version: &str,
) -> Result<Vec<String>, NetError> {
forge_api::fetch_forge_versions(client, game_version).await
}
async fn install(
&self,
client: &HttpClient,
game_version: &str,
loader_version: &str,
instance_dir: &Path,
meta_dir: &Path,
) -> Result<(), NetError> {
let installer_jar = instance_dir.join(".minecraft").join("forge-installer.jar");
forge_api::download_forge_installer(client, game_version, loader_version, &installer_jar)
.await?;
let java_path = crate::config::SETTINGS
.paths
.effective_java_path()
.map(str::to_owned)
.unwrap_or_else(crate::net::detect_java_path);
if let Err(e) =
forge_api::run_forge_installer(&installer_jar, instance_dir, &java_path).await
{
let _ = tokio::fs::remove_file(&installer_jar).await;
return Err(e);
}
if let Err(e) = tokio::fs::remove_file(&installer_jar).await {
tracing::warn!("Failed to remove Forge installer JAR: {}", e);
}
save_forge_profile(instance_dir, meta_dir, game_version, loader_version)?;
Ok(())
}
}
fn save_forge_profile(
instance_dir: &Path,
meta_dir: &Path,
game_version: &str,
loader_version: &str,
) -> Result<(), NetError> {
let version_dir_name = format!("{game_version}-forge-{loader_version}");
let profile_filename = format!("forge-{game_version}-{loader_version}.json");
super::save_installer_profile(instance_dir, meta_dir, &version_dir_name, &profile_filename)
}
+159
View File
@@ -0,0 +1,159 @@
mod vanilla;
mod fabric;
mod forge;
mod neoforge;
mod quilt;
use std::path::Path;
use async_trait::async_trait;
use crate::instance::models::ModLoader;
use crate::net::{HttpClient, NetError};
pub use vanilla::VanillaInstaller;
#[derive(Debug, Clone)]
pub struct GameVersion {
pub id: String,
pub stable: bool,
}
#[async_trait]
pub trait ModLoaderInstaller: Send + Sync {
fn loader_type(&self) -> ModLoader;
async fn get_game_versions(&self, client: &HttpClient) -> Result<Vec<GameVersion>, NetError>;
async fn get_versions(
&self,
client: &HttpClient,
game_version: &str,
) -> Result<Vec<String>, NetError>;
async fn install(
&self,
client: &HttpClient,
game_version: &str,
loader_version: &str,
instance_dir: &Path,
meta_dir: &Path,
) -> 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,
profile: &impl serde::Serialize,
) -> Result<(), NetError> {
let profiles_dir = meta_dir.join("loader-profiles");
std::fs::create_dir_all(&profiles_dir)?;
let profile_path = profiles_dir.join(filename);
let json = serde_json::to_string_pretty(profile)
.map_err(|e| NetError::Parse(format!("Failed to serialize profile {filename}: {e}")))?;
std::fs::write(&profile_path, &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/`.
pub(crate) fn save_installer_profile(
instance_dir: &Path,
meta_dir: &Path,
version_dir_name: &str,
profile_filename: &str,
) -> Result<(), NetError> {
let ver_json_path = instance_dir
.join(".minecraft")
.join("versions")
.join(version_dir_name)
.join(format!("{version_dir_name}.json"));
if !ver_json_path.exists() {
return Err(NetError::Parse(format!(
"Version JSON not found at {}",
ver_json_path.display()
)));
}
#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct InstallerVersionJson {
main_class: String,
#[serde(default)]
libraries: Vec<InstallerLib>,
}
#[derive(serde::Deserialize)]
struct InstallerLib {
name: String,
}
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 libs: Vec<serde_json::Value> = ver
.libraries
.iter()
.map(|l| serde_json::json!({"name": l.name}))
.collect();
let json_val = serde_json::json!({
"mainClass": ver.main_class,
"libraries": libs
});
save_profile_json(meta_dir, profile_filename, &json_val)
}
pub fn get_installer(loader: ModLoader) -> Box<dyn ModLoaderInstaller + Send + Sync> {
match loader {
ModLoader::Vanilla => Box::new(vanilla::VanillaInstaller),
ModLoader::Fabric => Box::new(fabric::FabricInstaller),
ModLoader::Forge => Box::new(forge::ForgeInstaller),
ModLoader::NeoForge => Box::new(neoforge::NeoForgeInstaller),
ModLoader::Quilt => Box::new(quilt::QuiltInstaller),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_vanilla_factory() {
let installer = get_installer(ModLoader::Vanilla);
assert_eq!(installer.loader_type(), ModLoader::Vanilla);
}
#[tokio::test]
async fn test_vanilla_get_versions() {
let client = HttpClient::new();
let installer = VanillaInstaller;
let versions = installer.get_versions(&client, "1.20.1").await.unwrap();
assert!(!versions.is_empty());
assert_eq!(versions[0], "vanilla");
}
#[tokio::test]
async fn test_vanilla_install_noop() {
let client = HttpClient::new();
let installer = VanillaInstaller;
let tmp = std::env::temp_dir().join("mcl_test_vanilla_install");
let meta = std::env::temp_dir().join("mcl_test_meta");
installer
.install(&client, "1.20.1", "vanilla", &tmp, &meta)
.await
.unwrap();
}
#[tokio::test]
#[ignore = "hits live Mojang API"]
async fn test_vanilla_get_game_versions() {
let client = HttpClient::new();
let installer = VanillaInstaller;
let versions = installer.get_game_versions(&client).await.unwrap();
assert!(!versions.is_empty());
assert!(versions.iter().any(|v| v.id == "1.20.1"));
}
}
+69
View File
@@ -0,0 +1,69 @@
use std::path::Path;
use async_trait::async_trait;
use super::{GameVersion, ModLoaderInstaller};
use crate::instance::models::ModLoader;
use crate::net::{neoforge as neoforge_api, HttpClient, NetError};
pub struct NeoForgeInstaller;
#[async_trait]
impl ModLoaderInstaller for NeoForgeInstaller {
fn loader_type(&self) -> ModLoader {
ModLoader::NeoForge
}
async fn get_game_versions(&self, client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
neoforge_api::fetch_neoforge_game_versions(client).await
}
async fn get_versions(
&self,
client: &HttpClient,
game_version: &str,
) -> Result<Vec<String>, NetError> {
neoforge_api::fetch_neoforge_versions(client, game_version).await
}
async fn install(
&self,
client: &HttpClient,
_game_version: &str,
loader_version: &str,
instance_dir: &Path,
meta_dir: &Path,
) -> Result<(), NetError> {
let installer_jar = instance_dir
.join(".minecraft")
.join("neoforge-installer.jar");
neoforge_api::download_neoforge_installer(client, loader_version, &installer_jar).await?;
let java_path = crate::config::SETTINGS
.paths
.effective_java_path()
.map(str::to_owned)
.unwrap_or_else(crate::net::detect_java_path);
if let Err(e) =
neoforge_api::run_neoforge_installer(&installer_jar, instance_dir, &java_path).await
{
let _ = tokio::fs::remove_file(&installer_jar).await;
return Err(e);
}
if let Err(e) = tokio::fs::remove_file(&installer_jar).await {
tracing::warn!("Failed to remove NeoForge installer JAR: {}", e);
}
save_neoforge_profile(instance_dir, meta_dir, loader_version)?;
Ok(())
}
}
fn save_neoforge_profile(instance_dir: &Path, meta_dir: &Path, loader_version: &str) -> Result<(), NetError> {
let version_dir_name = format!("neoforge-{loader_version}");
let profile_filename = format!("neoforge-{loader_version}.json");
super::save_installer_profile(instance_dir, meta_dir, &version_dir_name, &profile_filename)
}
+53
View File
@@ -0,0 +1,53 @@
use std::path::Path;
use async_trait::async_trait;
use super::{GameVersion, ModLoaderInstaller};
use crate::instance::models::ModLoader;
use crate::net::{quilt as quilt_api, HttpClient, NetError};
pub struct QuiltInstaller;
#[async_trait]
impl ModLoaderInstaller for QuiltInstaller {
fn loader_type(&self) -> ModLoader {
ModLoader::Quilt
}
async fn get_game_versions(&self, client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
quilt_api::fetch_quilt_game_versions(client).await
}
async fn get_versions(
&self,
client: &HttpClient,
game_version: &str,
) -> Result<Vec<String>, NetError> {
let loader_versions = quilt_api::fetch_quilt_versions(client, game_version).await?;
Ok(loader_versions
.into_iter()
.map(|lv| lv.loader.version)
.collect())
}
async fn install(
&self,
client: &HttpClient,
game_version: &str,
loader_version: &str,
_instance_dir: &Path,
meta_dir: &Path,
) -> Result<(), NetError> {
let profile =
quilt_api::fetch_quilt_profile(client, game_version, loader_version).await?;
quilt_api::download_quilt_libraries(client, &profile, meta_dir).await?;
super::save_profile_json(
meta_dir,
&format!("quilt-{game_version}-{loader_version}.json"),
&profile,
)?;
Ok(())
}
}
+47
View File
@@ -0,0 +1,47 @@
use std::path::Path;
use async_trait::async_trait;
use super::{GameVersion, ModLoaderInstaller};
use crate::instance::models::ModLoader;
use crate::net::{mojang, HttpClient, NetError};
pub struct VanillaInstaller;
#[async_trait]
impl ModLoaderInstaller for VanillaInstaller {
fn loader_type(&self) -> ModLoader {
ModLoader::Vanilla
}
async fn get_game_versions(&self, client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
let manifest = mojang::fetch_version_manifest(client).await?;
Ok(manifest
.versions
.into_iter()
.map(|v| GameVersion {
id: v.id,
stable: v.version_type == "release",
})
.collect())
}
async fn get_versions(
&self,
_client: &HttpClient,
_game_version: &str,
) -> Result<Vec<String>, NetError> {
Ok(vec!["vanilla".to_owned()])
}
async fn install(
&self,
_client: &HttpClient,
_game_version: &str,
_loader_version: &str,
_instance_dir: &Path,
_meta_dir: &Path,
) -> Result<(), NetError> {
Ok(())
}
}
+33 -168
View File
@@ -43,59 +43,27 @@ impl InstanceManager {
loader: ModLoader,
loader_version: Option<&str>,
) -> Result<InstanceConfig, InstanceError> {
match validate_name(name) {
Ok(_) => {}
Err(e) => {
tracing::error!("Invalid instance name '{}': {}", name, e);
return Err(e);
}
}
validate_name(name)?;
let instance_dir = self.instances_dir.join(name);
let instance_json = instance_dir.join("instance.json");
if instance_json.exists() {
tracing::error!("Instance '{}' already exists", name);
return Err(InstanceError::AlreadyExists(name.to_string()));
}
if instance_dir.exists() && !instance_json.exists() {
match std::fs::remove_dir_all(&instance_dir) {
Ok(_) => {}
Err(e) => {
tracing::error!(
"Failed to remove partial instance directory '{}': {}",
instance_dir.display(),
e
);
return Err(InstanceError::Io(e));
}
}
std::fs::remove_dir_all(&instance_dir)?;
}
match std::fs::create_dir_all(&instance_dir) {
Ok(_) => {}
Err(e) => {
tracing::error!("Failed to create instance directory: {}", e);
return Err(InstanceError::Io(e));
}
}
std::fs::create_dir_all(&instance_dir)?;
let result = self
.create_inner(name, game_version, loader, loader_version, &instance_dir)
.await;
if result.is_err() {
match std::fs::remove_dir_all(&instance_dir) {
Ok(_) => {}
Err(e) => {
tracing::warn!(
"Failed to clean up partial instance directory '{}': {}",
instance_dir.display(),
e
);
}
}
let _ = std::fs::remove_dir_all(&instance_dir);
}
result
@@ -111,24 +79,12 @@ impl InstanceManager {
) -> Result<InstanceConfig, InstanceError> {
let minecraft_dir = instance_dir.join(".minecraft");
for subdir in &["mods", "config", "resourcepacks", "shaderpacks", "saves"] {
match std::fs::create_dir_all(minecraft_dir.join(subdir)) {
Ok(_) => {}
Err(e) => {
tracing::error!("Failed to create directory: {}", e);
return Err(InstanceError::Io(e));
}
}
std::fs::create_dir_all(minecraft_dir.join(subdir))?;
}
let launcher_profiles_path = minecraft_dir.join("launcher_profiles.json");
if !launcher_profiles_path.exists() {
match std::fs::write(&launcher_profiles_path, "{}") {
Ok(_) => {}
Err(e) => {
tracing::error!("Failed to create launcher_profiles.json: {}", e);
return Err(InstanceError::Io(e));
}
}
std::fs::write(&launcher_profiles_path, "{}")?;
}
for meta_subdir in &[
@@ -137,47 +93,26 @@ impl InstanceManager {
self.meta_dir.join("assets").join("objects"),
self.meta_dir.join("assets").join("indexes"),
] {
match std::fs::create_dir_all(meta_subdir) {
Ok(_) => {}
Err(e) => {
tracing::error!("Failed to create meta directory: {}", e);
return Err(InstanceError::Io(e));
}
}
std::fs::create_dir_all(meta_subdir)?;
}
let manifest = match crate::net::mojang::fetch_version_manifest(&self.client).await {
Ok(m) => m,
Err(e) => {
return Err(InstanceError::Download(e));
}
};
let manifest = crate::net::mojang::fetch_version_manifest(&self.client).await?;
let version_entry = match manifest.versions.iter().find(|v| v.id == game_version) {
Some(v) => v,
None => {
let msg = format!("Minecraft version '{}' not found in manifest", game_version);
tracing::error!("{}", msg);
return Err(InstanceError::InvalidName(msg));
return Err(InstanceError::InvalidName(format!(
"Minecraft version '{}' not found in manifest",
game_version
)));
}
};
let version_meta =
match crate::net::mojang::fetch_version_meta(&self.client, version_entry).await {
Ok(m) => m,
Err(e) => {
return Err(InstanceError::Download(e));
}
};
crate::net::mojang::fetch_version_meta(&self.client, version_entry).await?;
match crate::net::mojang::download_client_jar(&self.client, &version_meta, &self.meta_dir)
.await
{
Ok(_) => {}
Err(e) => {
return Err(InstanceError::Download(e));
}
}
crate::net::mojang::download_client_jar(&self.client, &version_meta, &self.meta_dir)
.await?;
let meta_json_path = self
.meta_dir
@@ -195,36 +130,23 @@ impl InstanceManager {
}
}
match crate::net::mojang::download_libraries(&self.client, &version_meta, &self.meta_dir)
.await
{
Ok(_) => {}
Err(e) => {
return Err(InstanceError::Download(e));
}
}
crate::net::mojang::download_libraries(&self.client, &version_meta, &self.meta_dir)
.await?;
match crate::net::mojang::download_assets(&self.client, &version_meta, &self.meta_dir).await
{
Ok(_) => {}
Err(e) => {
return Err(InstanceError::Download(e));
}
}
crate::net::mojang::download_assets(&self.client, &version_meta, &self.meta_dir).await?;
let installer = crate::instance::loader::get_installer(loader);
let effective_loader_version = match loader_version {
Some(v) => v,
None if loader == ModLoader::Vanilla => "vanilla",
None => {
tracing::error!("No loader version provided for {} loader", loader);
return Err(InstanceError::InvalidName(format!(
"A loader version is required for {}",
loader
)));
}
};
match installer
installer
.install(
&self.client,
game_version,
@@ -232,13 +154,7 @@ impl InstanceManager {
instance_dir,
&self.meta_dir,
)
.await
{
Ok(_) => {}
Err(e) => {
return Err(InstanceError::Download(e));
}
}
.await?;
let config = InstanceConfig {
name: name.to_string(),
@@ -254,13 +170,7 @@ impl InstanceManager {
resolution: None,
};
match self.save(&config) {
Ok(_) => {}
Err(e) => {
tracing::error!("Failed to save instance config: {}", e);
return Err(e);
}
}
self.save(&config)?;
crate::tui::progress::clear();
Ok(config)
@@ -271,18 +181,11 @@ impl InstanceManager {
if !instance_dir.exists() {
return Err(InstanceError::NotFound(name.to_string()));
}
match std::fs::remove_dir_all(&instance_dir) {
Ok(_) => {
if let Err(e) = crate::instance::desktop::remove(name) {
tracing::warn!("Failed to remove desktop shortcut for '{}': {}", name, e);
}
Ok(())
}
Err(e) => {
tracing::error!("Failed to delete instance '{}': {}", name, e);
Err(InstanceError::Io(e))
}
std::fs::remove_dir_all(&instance_dir)?;
if let Err(e) = crate::instance::desktop::remove(name) {
tracing::warn!("Failed to remove desktop shortcut for '{}': {}", name, e);
}
Ok(())
}
pub fn rename(&self, old_name: &str, new_name: &str) -> Result<(), InstanceError> {
@@ -360,58 +263,23 @@ impl InstanceManager {
}
pub fn load_one(&self, name: &str) -> Result<InstanceConfig, InstanceError> {
match validate_name(name) {
Ok(_) => {}
Err(e) => {
tracing::error!("Invalid instance name '{}': {}", name, e);
return Err(e);
}
}
validate_name(name)?;
let config_path = self.instances_dir.join(name).join("instance.json");
if !config_path.exists() {
tracing::error!("Instance '{}' not found", name);
return Err(InstanceError::NotFound(name.to_string()));
}
let contents = match std::fs::read_to_string(&config_path) {
Ok(c) => c,
Err(e) => {
tracing::error!("Failed to read {}: {}", config_path.display(), e);
return Err(InstanceError::Io(e));
}
};
match serde_json::from_str::<InstanceConfig>(&contents) {
Ok(config) => Ok(config),
Err(e) => {
tracing::error!("Failed to parse {}: {}", config_path.display(), e);
Err(InstanceError::Json(e))
}
}
let contents = std::fs::read_to_string(&config_path)?;
Ok(serde_json::from_str::<InstanceConfig>(&contents)?)
}
pub fn save(&self, instance: &InstanceConfig) -> Result<(), InstanceError> {
let instance_dir = self.instances_dir.join(&instance.name);
let config_path = instance_dir.join("instance.json");
let json = match serde_json::to_string_pretty(instance) {
Ok(j) => j,
Err(e) => {
tracing::error!("Failed to serialize instance config: {}", e);
return Err(InstanceError::Json(e));
}
};
match std::fs::write(&config_path, &json) {
Ok(_) => Ok(()),
Err(e) => {
tracing::error!(
"Failed to write instance config to {}: {}",
config_path.display(),
e
);
Err(InstanceError::Io(e))
}
}
let json = serde_json::to_string_pretty(instance)?;
std::fs::write(&config_path, &json)?;
Ok(())
}
pub fn touch_last_played(&self, name: &str) -> Result<(), InstanceError> {
@@ -428,7 +296,7 @@ fn validate_name(name: &str) -> Result<(), InstanceError> {
name
)));
}
if name.contains('/') || name.contains('\\') || name.contains('.') {
if name.contains('/') || name.contains('\\') || name.starts_with('.') {
return Err(InstanceError::InvalidName(format!(
"Name contains invalid characters: {:?}",
name
@@ -502,10 +370,7 @@ mod tests {
resolution: None,
};
match manager.save(&config) {
Ok(_) => {}
Err(e) => panic!("save failed: {}", e),
}
manager.save(&config).expect("save failed");
let all = manager.load_all();
assert_eq!(all.len(), 1);
+4 -10
View File
@@ -1,21 +1,15 @@
pub mod content;
pub mod desktop;
pub mod import;
pub mod launch;
pub mod loader;
pub mod desktop;
pub mod log_files;
pub mod manager;
pub mod models;
pub mod mods;
pub mod resource_packs;
pub mod screenshots;
pub mod shaders;
pub mod worlds;
pub mod import;
pub use content::{scan_mods, toggle_entry, ContentEntry, scan_resource_packs, scan_shaders, scan_worlds};
pub use launch::LaunchError;
pub use loader::{get_installer, GameVersion, ModLoaderInstaller, VanillaInstaller};
pub use manager::{InstanceError, InstanceManager};
pub use models::{InstanceConfig, ModLoader};
pub use mods::{scan_mods, toggle_mod, ModEntry};
pub use resource_packs::scan_resource_packs;
pub use shaders::scan_shaders;
pub use worlds::scan_worlds;
+7 -22
View File
@@ -2,7 +2,7 @@ use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ModLoader {
Vanilla,
@@ -43,15 +43,6 @@ pub struct InstanceConfig {
mod tests {
use super::*;
#[test]
fn test_modloader_display() {
assert_eq!(ModLoader::Vanilla.to_string(), "Vanilla");
assert_eq!(ModLoader::Fabric.to_string(), "Fabric");
assert_eq!(ModLoader::Forge.to_string(), "Forge");
assert_eq!(ModLoader::NeoForge.to_string(), "NeoForge");
assert_eq!(ModLoader::Quilt.to_string(), "Quilt");
}
#[test]
fn test_instance_config_roundtrip() {
let config = InstanceConfig {
@@ -67,17 +58,11 @@ mod tests {
jvm_args: vec![],
resolution: Some((1920, 1080)),
};
match serde_json::to_string_pretty(&config) {
Ok(json) => match serde_json::from_str::<InstanceConfig>(&json) {
Ok(parsed) => {
assert_eq!(parsed.name, config.name);
assert_eq!(parsed.game_version, config.game_version);
assert_eq!(parsed.loader, config.loader);
assert_eq!(parsed.resolution, config.resolution);
}
Err(e) => panic!("Deserialization failed: {}", e),
},
Err(e) => panic!("Serialization failed: {}", e),
}
let json = serde_json::to_string_pretty(&config).expect("serialize");
let parsed: InstanceConfig = serde_json::from_str(&json).expect("deserialize");
assert_eq!(parsed.name, config.name);
assert_eq!(parsed.game_version, config.game_version);
assert_eq!(parsed.loader, config.loader);
assert_eq!(parsed.resolution, config.resolution);
}
}
+6 -3
View File
@@ -1,11 +1,11 @@
use once_cell::sync::Lazy;
use std::collections::{HashMap, VecDeque};
use std::sync::LazyLock;
use std::sync::{Arc, Mutex};
const MAX_LINES: usize = 2000;
type LogsMap = Arc<Mutex<HashMap<String, VecDeque<String>>>>;
pub static LOGS: Lazy<LogsMap> = Lazy::new(|| Arc::new(Mutex::new(HashMap::new())));
pub static LOGS: LazyLock<LogsMap> = LazyLock::new(|| Arc::new(Mutex::new(HashMap::new())));
pub fn push(name: &str, line: impl Into<String>) {
if let Ok(mut logs) = LOGS.lock() {
@@ -72,6 +72,9 @@ mod tests {
}
let lines = get_all(name);
assert_eq!(lines.len(), MAX_LINES);
assert!(lines.last().unwrap().contains(&format!("{}", MAX_LINES + 99)));
assert!(lines
.last()
.unwrap()
.contains(&format!("{}", MAX_LINES + 99)));
}
}
+1
View File
@@ -9,6 +9,7 @@ pub mod tui;
#[tokio::main]
async fn main() {
// Guard must stay in scope to keep the log file writer alive
let _guard = tui::logging::init();
if let Err(e) = color_eyre::install() {
eprintln!("Failed to install color-eyre: {}", e);
+6 -96
View File
@@ -43,27 +43,7 @@ pub struct FabricLibrary {
pub async fn fetch_fabric_game_versions(client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
let url = format!("{}/versions/game", FABRIC_META_BASE);
let response = match client.inner().get(&url).send().await {
Ok(r) => r,
Err(e) => {
tracing::error!("Fabric game versions GET {} failed: {}", url, e);
return Err(NetError::Http(e));
}
};
if !response.status().is_success() {
let status = response.status().as_u16();
tracing::error!("HTTP {} for {}", status, url);
return Err(NetError::StatusError { status, url });
}
let versions: Vec<FabricGameVersion> = match response.json().await {
Ok(v) => v,
Err(e) => {
tracing::error!("Failed to parse Fabric game versions: {}", e);
return Err(NetError::Http(e));
}
};
let versions: Vec<FabricGameVersion> = client.get_json(&url).await?;
Ok(versions
.into_iter()
@@ -79,33 +59,7 @@ pub async fn fetch_fabric_versions(
game_version: &str,
) -> Result<Vec<FabricLoaderVersion>, NetError> {
let url = format!("{}/versions/loader/{}", FABRIC_META_BASE, game_version);
let response = match client.inner().get(&url).send().await {
Ok(r) => r,
Err(e) => {
tracing::error!("Fabric meta GET {} failed: {}", url, e);
return Err(NetError::Http(e));
}
};
if !response.status().is_success() {
let status = response.status().as_u16();
tracing::error!("Fabric meta HTTP {} for {}", status, url);
return Err(NetError::StatusError {
status,
url: url.clone(),
});
}
let versions: Vec<FabricLoaderVersion> = match response.json().await {
Ok(v) => v,
Err(e) => {
tracing::error!("Failed to parse Fabric loader versions: {}", e);
return Err(NetError::Http(e));
}
};
Ok(versions)
client.get_json(&url).await
}
pub async fn fetch_fabric_profile(
@@ -117,33 +71,7 @@ pub async fn fetch_fabric_profile(
"{}/versions/loader/{}/{}/profile/json",
FABRIC_META_BASE, game_version, loader_version
);
let response = match client.inner().get(&url).send().await {
Ok(r) => r,
Err(e) => {
tracing::error!("Fabric profile GET {} failed: {}", url, e);
return Err(NetError::Http(e));
}
};
if !response.status().is_success() {
let status = response.status().as_u16();
tracing::error!("Fabric profile HTTP {} for {}", status, url);
return Err(NetError::StatusError {
status,
url: url.clone(),
});
}
let profile: FabricProfile = match response.json().await {
Ok(p) => p,
Err(e) => {
tracing::error!("Failed to parse Fabric profile: {}", e);
return Err(NetError::Http(e));
}
};
Ok(profile)
client.get_json(&url).await
}
pub async fn download_fabric_libraries(
@@ -157,7 +85,6 @@ pub async fn download_fabric_libraries(
let maven_path = match crate::net::maven_coord_to_path(&lib.name) {
Some(p) => p,
None => {
tracing::error!("Invalid Maven coordinate in Fabric profile: {}", lib.name);
return Err(NetError::Parse(format!(
"Invalid Maven coordinate: {}",
lib.name
@@ -178,13 +105,7 @@ pub async fn download_fabric_libraries(
set_sub_action(&lib.name);
tracing::info!("Downloading Fabric library: {}", lib.name);
match download_file(client, &download_url, &dest, |_, _| {}).await {
Ok(()) => {}
Err(e) => {
tracing::error!("Failed to download Fabric library {}: {}", lib.name, e);
return Err(e);
}
}
download_file(client, &download_url, &dest, |_, _| {}).await?;
}
Ok(())
@@ -196,6 +117,7 @@ mod tests {
use crate::net::HttpClient;
#[tokio::test]
#[ignore = "hits live Fabric API"]
async fn test_fetch_versions() {
let client = HttpClient::new();
match fetch_fabric_versions(&client, "1.20.1").await {
@@ -214,6 +136,7 @@ mod tests {
}
#[tokio::test]
#[ignore = "hits live Fabric API"]
async fn test_fetch_game_versions() {
let client = HttpClient::new();
match fetch_fabric_game_versions(&client).await {
@@ -225,17 +148,4 @@ mod tests {
}
}
#[test]
fn test_maven_coord_to_path() {
assert_eq!(
crate::net::maven_coord_to_path("net.fabricmc:fabric-loader:0.16.0"),
Some("net/fabricmc/fabric-loader/0.16.0/fabric-loader-0.16.0.jar".to_string())
);
assert_eq!(
crate::net::maven_coord_to_path("org.ow2.asm:asm:9.6"),
Some("org/ow2/asm/asm/9.6/asm-9.6.jar".to_string())
);
assert_eq!(crate::net::maven_coord_to_path("invalid"), None);
assert_eq!(crate::net::maven_coord_to_path("only:two"), None);
}
}
+6 -66
View File
@@ -24,30 +24,7 @@ pub async fn fetch_forge_versions(
client: &HttpClient,
game_version: &str,
) -> Result<Vec<String>, NetError> {
let response = match client.inner().get(FORGE_PROMOTIONS_URL).send().await {
Ok(r) => r,
Err(e) => {
tracing::error!("GET {} failed: {}", FORGE_PROMOTIONS_URL, e);
return Err(NetError::Http(e));
}
};
if !response.status().is_success() {
let status = response.status().as_u16();
tracing::error!("HTTP {} for {}", status, FORGE_PROMOTIONS_URL);
return Err(NetError::StatusError {
status,
url: FORGE_PROMOTIONS_URL.to_string(),
});
}
let promotions: ForgePromotions = match response.json().await {
Ok(p) => p,
Err(e) => {
tracing::error!("Failed to parse Forge promotions JSON: {}", e);
return Err(NetError::Http(e));
}
};
let promotions: ForgePromotions = client.get_json(FORGE_PROMOTIONS_URL).await?;
let prefix = format!("{}-", game_version);
let mut versions: Vec<String> = promotions
@@ -63,30 +40,7 @@ pub async fn fetch_forge_versions(
}
pub async fn fetch_forge_game_versions(client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
let response = match client.inner().get(FORGE_PROMOTIONS_URL).send().await {
Ok(r) => r,
Err(e) => {
tracing::error!("GET {} failed: {}", FORGE_PROMOTIONS_URL, e);
return Err(NetError::Http(e));
}
};
if !response.status().is_success() {
let status = response.status().as_u16();
tracing::error!("HTTP {} for {}", status, FORGE_PROMOTIONS_URL);
return Err(NetError::StatusError {
status,
url: FORGE_PROMOTIONS_URL.to_string(),
});
}
let promos: ForgePromotions = match response.json().await {
Ok(p) => p,
Err(e) => {
tracing::error!("Failed to parse Forge promotions: {}", e);
return Err(NetError::Http(e));
}
};
let promos: ForgePromotions = client.get_json(FORGE_PROMOTIONS_URL).await?;
let mut game_versions: Vec<String> = promos
.promos
@@ -127,17 +81,10 @@ pub async fn download_forge_installer(
game_version, forge_version
));
match download_file(client, &url, dest, |downloaded, total| {
download_file(client, &url, dest, |downloaded, total| {
crate::tui::progress::set_progress(downloaded, total);
})
.await
{
Ok(()) => Ok(()),
Err(e) => {
tracing::error!("Failed to download Forge installer from {}: {}", url, e);
Err(e)
}
}
}
/// Run the Forge installer JAR to install Forge into the instance directory.
@@ -163,21 +110,12 @@ pub async fn run_forge_installer(
{
Ok(o) => o,
Err(e) => {
tracing::error!("Failed to launch Forge installer: {}", e);
return Err(NetError::Io(e));
}
};
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
tracing::error!(
"Forge installer failed (exit {:?}): {} {}",
output.status.code(),
stderr,
stdout
);
return Err(NetError::Parse(format!(
return Err(NetError::InstallerFailed(format!(
"Forge installer exited with {:?}",
output.status.code()
)));
@@ -192,6 +130,7 @@ mod tests {
use crate::net::HttpClient;
#[tokio::test]
#[ignore = "hits live Forge API"]
async fn test_fetch_versions() {
let client = HttpClient::new();
match fetch_forge_versions(&client, "1.20.1").await {
@@ -206,6 +145,7 @@ mod tests {
}
#[tokio::test]
#[ignore = "hits live Forge API"]
async fn test_fetch_game_versions() {
let client = HttpClient::new();
match fetch_forge_game_versions(&client).await {
+40 -66
View File
@@ -6,6 +6,7 @@ pub mod modrinth;
pub mod quilt;
use reqwest::Client;
use serde::de::DeserializeOwned;
use std::path::Path;
use thiserror::Error;
@@ -19,6 +20,10 @@ pub enum NetError {
Parse(String),
#[error("Server returned error status {status}: {url}")]
StatusError { status: u16, url: String },
#[error("Installer process failed: {0}")]
InstallerFailed(String),
#[error("Task failed: {0}")]
TaskFailed(String),
}
#[derive(Clone)]
@@ -34,24 +39,32 @@ impl Default for HttpClient {
impl HttpClient {
pub fn new() -> Self {
match Client::builder()
.user_agent("mcl/0.1.0 (Minecraft Launcher)")
let client = Client::builder()
.user_agent(format!("mcl/{} (Minecraft Launcher)", env!("CARGO_PKG_VERSION")))
.timeout(std::time::Duration::from_secs(30))
.build()
{
Ok(client) => HttpClient { inner: client },
Err(e) => {
tracing::error!("Failed to build HTTP client: {}", e);
HttpClient {
inner: Client::new(),
}
}
}
.unwrap_or_else(|_| Client::new());
Self { inner: client }
}
pub fn inner(&self) -> &Client {
&self.inner
}
pub async fn get(&self, url: &str) -> Result<reqwest::Response, NetError> {
let response = self.inner.get(url).send().await?;
if !response.status().is_success() {
return Err(NetError::StatusError {
status: response.status().as_u16(),
url: url.to_string(),
});
}
Ok(response)
}
pub async fn get_json<T: DeserializeOwned>(&self, url: &str) -> Result<T, NetError> {
Ok(self.get(url).await?.json().await?)
}
}
/// Download a file from `url` to `dest`, calling `progress_cb(bytes_downloaded, total_bytes)` as chunks arrive.
@@ -64,80 +77,41 @@ pub async fn download_file(
) -> Result<(), NetError> {
use tokio::io::AsyncWriteExt;
let response = match client.inner().get(url).send().await {
Ok(r) => r,
Err(e) => {
tracing::error!("GET {} failed: {}", url, e);
return Err(NetError::Http(e));
}
};
if !response.status().is_success() {
let status = response.status().as_u16();
tracing::error!("HTTP {} for {}", status, url);
return Err(NetError::StatusError {
status,
url: url.to_string(),
});
}
let response = client.get(url).await?;
let total = response.content_length().unwrap_or(0);
if let Some(parent) = dest.parent() {
match tokio::fs::create_dir_all(parent).await {
Ok(_) => {}
Err(e) => {
tracing::error!("Failed to create directory {}: {}", parent.display(), e);
return Err(NetError::Io(e));
}
}
tokio::fs::create_dir_all(parent).await?;
}
let mut file = match tokio::fs::File::create(dest).await {
Ok(f) => f,
Err(e) => {
tracing::error!("Failed to create file {}: {}", dest.display(), e);
return Err(NetError::Io(e));
}
};
let mut file = tokio::fs::File::create(dest).await?;
let mut downloaded: u64 = 0;
let mut stream = response;
loop {
match stream.chunk().await {
Ok(Some(chunk)) => {
match file.write_all(&chunk).await {
Ok(_) => {}
Err(e) => {
tracing::error!("Failed to write chunk to {}: {}", dest.display(), e);
return Err(NetError::Io(e));
}
}
downloaded += chunk.len() as u64;
progress_cb(downloaded, total);
}
Ok(None) => break,
Err(e) => {
tracing::error!("Failed to read response chunk from {}: {}", url, e);
return Err(NetError::Http(e));
}
}
while let Some(chunk) = stream.chunk().await? {
file.write_all(&chunk).await?;
downloaded += chunk.len() as u64;
progress_cb(downloaded, total);
}
Ok(())
}
#[must_use]
pub fn detect_java_path() -> String {
if let Ok(java_home) = std::env::var("JAVA_HOME") {
let path = std::path::Path::new(&java_home).join("bin").join("java");
if path.exists() {
return path.to_string_lossy().to_string();
let java_name = if cfg!(windows) { "java.exe" } else { "java" };
let bin = std::path::Path::new(&java_home).join("bin").join(java_name);
if bin.exists() {
return bin.to_string_lossy().to_string();
}
}
"java".to_string()
which::which("java")
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_else(|_| "java".to_string())
}
#[must_use]
pub fn maven_coord_to_path(coord: &str) -> Option<String> {
let parts: Vec<&str> = coord.split(':').collect();
match parts.as_slice() {
+24 -39
View File
@@ -106,23 +106,28 @@ pub fn game_version_from_dependencies(deps: &HashMap<String, String>) -> Option<
const API_BASE: &str = "https://api.modrinth.com/v2";
fn url_encode(s: &str) -> String {
use std::fmt::Write;
let mut encoded = String::with_capacity(s.len());
for byte in s.bytes() {
match byte {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
encoded.push(byte as char);
}
_ => {
write!(encoded, "%{byte:02X}").unwrap();
}
}
}
encoded
}
pub async fn fetch_project(
client: &crate::net::HttpClient,
slug_or_id: &str,
) -> Result<ProjectInfo, crate::net::NetError> {
let url = format!("{}/project/{}", API_BASE, slug_or_id);
let resp = client
.inner()
.get(&url)
.send()
.await?;
if !resp.status().is_success() {
return Err(crate::net::NetError::StatusError {
status: resp.status().as_u16(),
url,
});
}
resp.json().await.map_err(crate::net::NetError::Http)
let url = format!("{}/project/{}", API_BASE, url_encode(slug_or_id));
client.get_json(&url).await
}
pub async fn fetch_versions(
@@ -131,39 +136,17 @@ pub async fn fetch_versions(
) -> Result<Vec<VersionInfo>, crate::net::NetError> {
let url = format!(
"{}/project/{}/version?loaders=[\"fabric\",\"forge\",\"neoforge\",\"quilt\"]",
API_BASE, slug_or_id
API_BASE, url_encode(slug_or_id)
);
let resp = client
.inner()
.get(&url)
.send()
.await?;
if !resp.status().is_success() {
return Err(crate::net::NetError::StatusError {
status: resp.status().as_u16(),
url,
});
}
resp.json().await.map_err(crate::net::NetError::Http)
client.get_json(&url).await
}
pub async fn fetch_version(
client: &crate::net::HttpClient,
version_id: &str,
) -> Result<VersionInfo, crate::net::NetError> {
let url = format!("{}/version/{}", API_BASE, version_id);
let resp = client
.inner()
.get(&url)
.send()
.await?;
if !resp.status().is_success() {
return Err(crate::net::NetError::StatusError {
status: resp.status().as_u16(),
url,
});
}
resp.json().await.map_err(crate::net::NetError::Http)
let url = format!("{}/version/{}", API_BASE, url_encode(version_id));
client.get_json(&url).await
}
pub async fn download_mrpack(
@@ -315,6 +298,7 @@ mod tests {
}
#[tokio::test]
#[ignore = "hits live Modrinth API"]
async fn test_fetch_project() {
let client = crate::net::HttpClient::new();
let project = fetch_project(&client, "fabulously-optimized").await;
@@ -328,6 +312,7 @@ mod tests {
}
#[tokio::test]
#[ignore = "hits live Modrinth API"]
async fn test_fetch_versions() {
let client = crate::net::HttpClient::new();
let versions = fetch_versions(&client, "fabulously-optimized").await;
+8 -46
View File
@@ -117,14 +117,14 @@ pub struct AssetObject {
}
pub async fn fetch_version_manifest(client: &HttpClient) -> Result<VersionManifest, NetError> {
fetch_json(client, MANIFEST_URL).await
client.get_json(MANIFEST_URL).await
}
pub async fn fetch_version_meta(
client: &HttpClient,
entry: &VersionEntry,
) -> Result<VersionMeta, NetError> {
fetch_json(client, &entry.url).await
client.get_json(&entry.url).await
}
pub async fn download_client_jar(
@@ -203,7 +203,7 @@ pub async fn download_assets(
) -> Result<(), NetError> {
set_action("Downloading assets...");
let asset_index = match fetch_json::<AssetIndexContent>(client, &meta.asset_index.url).await {
let asset_index: AssetIndexContent = match client.get_json(&meta.asset_index.url).await {
Ok(index) => index,
Err(e) => {
clear();
@@ -242,10 +242,8 @@ pub async fn download_assets(
let mut downloads = Vec::new();
for object in asset_index.objects.values() {
if object.hash.len() < 2 {
let message = format!("Invalid asset hash: {}", object.hash);
tracing::error!("{}", message);
clear();
return Err(NetError::Parse(message));
return Err(NetError::Parse(format!("Invalid asset hash: {}", object.hash)));
}
let prefix = &object.hash[..2];
@@ -274,36 +272,6 @@ pub async fn download_assets(
result
}
async fn fetch_json<T>(client: &HttpClient, url: &str) -> Result<T, NetError>
where
T: for<'de> Deserialize<'de>,
{
let response = match client.inner().get(url).send().await {
Ok(response) => response,
Err(e) => {
tracing::error!("Failed to fetch {}: {}", url, e);
return Err(NetError::Http(e));
}
};
if !response.status().is_success() {
let status = response.status().as_u16();
tracing::error!("HTTP {} from {}", status, url);
return Err(NetError::StatusError {
status,
url: url.to_string(),
});
}
match response.json::<T>().await {
Ok(data) => Ok(data),
Err(e) => {
tracing::error!("Failed to parse JSON from {}: {}", url, e);
Err(NetError::Http(e))
}
}
}
fn library_allowed_for_current_os(library: &Library) -> bool {
let rules = match &library.rules {
Some(rules) => rules,
@@ -384,7 +352,7 @@ async fn run_parallel_downloads(
Err(e) => {
tracing::error!("Task panicked: {}", e);
if first_error.is_none() {
first_error = Some(NetError::Parse(format!("Join error: {}", e)));
first_error = Some(NetError::TaskFailed(format!("Join error: {}", e)));
}
}
}
@@ -409,18 +377,11 @@ fn spawn_download_task(
job: (String, PathBuf, String),
) {
let (url, destination, label) = job;
let task_client = HttpClient {
inner: client.inner().clone(),
};
let task_client = client.clone();
set.spawn(async move {
let label_for_progress = label.clone();
let result = download_file(&task_client, &url, &destination, |_current, _total| {}).await;
match result {
Ok(()) => Ok(label_for_progress),
Err(e) => Err(e),
}
result.map(|()| label)
});
}
@@ -430,6 +391,7 @@ mod tests {
use crate::net::HttpClient;
#[tokio::test]
#[ignore = "hits live Mojang API"]
async fn test_fetch_manifest_contains_1_20_1() {
let client = HttpClient::new();
match fetch_version_manifest(&client).await {
+6 -72
View File
@@ -26,8 +26,6 @@ fn game_version_to_neoforge_prefix(game_version: &str) -> Option<String> {
["1", minor] => Some(format!("{}.0.", minor)),
// "1.20.4" → prefix "20.4."
["1", minor, patch] => Some(format!("{}.{}.", minor, patch)),
[major, minor] => Some(format!("{}.{}.", major, minor)),
[major, minor, _patch] => Some(format!("{}.{}.", major, minor)),
_ => None,
}
}
@@ -39,10 +37,6 @@ pub async fn fetch_neoforge_versions(
let prefix = match game_version_to_neoforge_prefix(game_version) {
Some(p) => p,
None => {
tracing::error!(
"Cannot map game version '{}' to NeoForge version prefix",
game_version
);
return Err(NetError::Parse(format!(
"Invalid game version for NeoForge: {}",
game_version
@@ -50,30 +44,7 @@ pub async fn fetch_neoforge_versions(
}
};
let response = match client.inner().get(NEOFORGE_API_BASE).send().await {
Ok(r) => r,
Err(e) => {
tracing::error!("GET {} failed: {}", NEOFORGE_API_BASE, e);
return Err(NetError::Http(e));
}
};
if !response.status().is_success() {
let status = response.status().as_u16();
tracing::error!("HTTP {} for {}", status, NEOFORGE_API_BASE);
return Err(NetError::StatusError {
status,
url: NEOFORGE_API_BASE.to_string(),
});
}
let maven_versions: NeoForgeMavenVersions = match response.json().await {
Ok(v) => v,
Err(e) => {
tracing::error!("Failed to parse NeoForge maven versions: {}", e);
return Err(NetError::Http(e));
}
};
let maven_versions: NeoForgeMavenVersions = client.get_json(NEOFORGE_API_BASE).await?;
let versions: Vec<String> = maven_versions
.versions
@@ -87,30 +58,7 @@ pub async fn fetch_neoforge_versions(
pub async fn fetch_neoforge_game_versions(
client: &HttpClient,
) -> Result<Vec<GameVersion>, NetError> {
let response = match client.inner().get(NEOFORGE_API_BASE).send().await {
Ok(r) => r,
Err(e) => {
tracing::error!("GET {} failed: {}", NEOFORGE_API_BASE, e);
return Err(NetError::Http(e));
}
};
if !response.status().is_success() {
let status = response.status().as_u16();
tracing::error!("HTTP {} for {}", status, NEOFORGE_API_BASE);
return Err(NetError::StatusError {
status,
url: NEOFORGE_API_BASE.to_string(),
});
}
let maven: NeoForgeMavenVersions = match response.json().await {
Ok(m) => m,
Err(e) => {
tracing::error!("Failed to parse NeoForge versions: {}", e);
return Err(NetError::Http(e));
}
};
let maven: NeoForgeMavenVersions = client.get_json(NEOFORGE_API_BASE).await?;
let mut game_versions: Vec<String> = Vec::new();
for version in &maven.versions {
@@ -152,17 +100,10 @@ pub async fn download_neoforge_installer(
set_action(format!("Downloading NeoForge {}...", neoforge_version));
match download_file(client, &url, dest, |downloaded, total| {
download_file(client, &url, dest, |downloaded, total| {
crate::tui::progress::set_progress(downloaded, total);
})
.await
{
Ok(()) => Ok(()),
Err(e) => {
tracing::error!("Failed to download NeoForge installer from {}: {}", url, e);
Err(e)
}
}
}
pub async fn run_neoforge_installer(
@@ -184,21 +125,12 @@ pub async fn run_neoforge_installer(
{
Ok(o) => o,
Err(e) => {
tracing::error!("Failed to launch NeoForge installer: {}", e);
return Err(NetError::Io(e));
}
};
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
tracing::error!(
"NeoForge installer failed (exit {:?}): {} {}",
output.status.code(),
stderr,
stdout
);
return Err(NetError::Parse(format!(
return Err(NetError::InstallerFailed(format!(
"NeoForge installer exited with {:?}",
output.status.code()
)));
@@ -213,6 +145,7 @@ mod tests {
use crate::net::HttpClient;
#[tokio::test]
#[ignore = "hits live NeoForge API"]
async fn test_fetch_versions() {
let client = HttpClient::new();
match fetch_neoforge_versions(&client, "1.21").await {
@@ -227,6 +160,7 @@ mod tests {
}
#[tokio::test]
#[ignore = "hits live NeoForge API"]
async fn test_fetch_game_versions() {
let client = HttpClient::new();
match fetch_neoforge_game_versions(&client).await {
+6 -93
View File
@@ -40,28 +40,7 @@ pub struct QuiltLibrary {
pub async fn fetch_quilt_game_versions(client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
let url = format!("{}/versions/game", QUILT_META_BASE);
let response = match client.inner().get(&url).send().await {
Ok(r) => r,
Err(e) => {
tracing::error!("Quilt game versions GET {} failed: {}", url, e);
return Err(NetError::Http(e));
}
};
if !response.status().is_success() {
let status = response.status().as_u16();
tracing::error!("HTTP {} for {}", status, url);
return Err(NetError::StatusError { status, url });
}
let versions: Vec<QuiltGameVersion> = match response.json().await {
Ok(v) => v,
Err(e) => {
tracing::error!("Failed to parse Quilt game versions: {}", e);
return Err(NetError::Http(e));
}
};
let versions: Vec<QuiltGameVersion> = client.get_json(&url).await?;
Ok(versions
.into_iter()
@@ -77,33 +56,7 @@ pub async fn fetch_quilt_versions(
game_version: &str,
) -> Result<Vec<QuiltLoaderVersion>, NetError> {
let url = format!("{}/versions/loader/{}", QUILT_META_BASE, game_version);
let response = match client.inner().get(&url).send().await {
Ok(r) => r,
Err(e) => {
tracing::error!("Quilt meta GET {} failed: {}", url, e);
return Err(NetError::Http(e));
}
};
if !response.status().is_success() {
let status = response.status().as_u16();
tracing::error!("Quilt meta HTTP {} for {}", status, url);
return Err(NetError::StatusError {
status,
url: url.clone(),
});
}
let versions: Vec<QuiltLoaderVersion> = match response.json().await {
Ok(v) => v,
Err(e) => {
tracing::error!("Failed to parse Quilt loader versions: {}", e);
return Err(NetError::Http(e));
}
};
Ok(versions)
client.get_json(&url).await
}
pub async fn fetch_quilt_profile(
@@ -115,33 +68,7 @@ pub async fn fetch_quilt_profile(
"{}/versions/loader/{}/{}/profile/json",
QUILT_META_BASE, game_version, loader_version
);
let response = match client.inner().get(&url).send().await {
Ok(r) => r,
Err(e) => {
tracing::error!("Quilt profile GET {} failed: {}", url, e);
return Err(NetError::Http(e));
}
};
if !response.status().is_success() {
let status = response.status().as_u16();
tracing::error!("Quilt profile HTTP {} for {}", status, url);
return Err(NetError::StatusError {
status,
url: url.clone(),
});
}
let profile: QuiltProfile = match response.json().await {
Ok(p) => p,
Err(e) => {
tracing::error!("Failed to parse Quilt profile: {}", e);
return Err(NetError::Http(e));
}
};
Ok(profile)
client.get_json(&url).await
}
pub async fn download_quilt_libraries(
@@ -155,7 +82,6 @@ pub async fn download_quilt_libraries(
let maven_path = match crate::net::maven_coord_to_path(&lib.name) {
Some(p) => p,
None => {
tracing::error!("Invalid Maven coordinate in Quilt profile: {}", lib.name);
return Err(NetError::Parse(format!(
"Invalid Maven coordinate: {}",
lib.name
@@ -176,13 +102,7 @@ pub async fn download_quilt_libraries(
set_sub_action(&lib.name);
tracing::info!("Downloading Quilt library: {}", lib.name);
match download_file(client, &download_url, &dest, |_, _| {}).await {
Ok(()) => {}
Err(e) => {
tracing::error!("Failed to download Quilt library {}: {}", lib.name, e);
return Err(e);
}
}
download_file(client, &download_url, &dest, |_, _| {}).await?;
}
Ok(())
@@ -194,6 +114,7 @@ mod tests {
use crate::net::HttpClient;
#[tokio::test]
#[ignore = "hits live Quilt API"]
async fn test_fetch_versions() {
let client = HttpClient::new();
match fetch_quilt_versions(&client, "1.20.1").await {
@@ -208,6 +129,7 @@ mod tests {
}
#[tokio::test]
#[ignore = "hits live Quilt API"]
async fn test_fetch_game_versions() {
let client = HttpClient::new();
match fetch_quilt_game_versions(&client).await {
@@ -219,13 +141,4 @@ mod tests {
}
}
#[test]
fn test_maven_coord_to_path() {
assert_eq!(
crate::net::maven_coord_to_path("org.quiltmc:quilt-loader:0.20.0"),
Some("org/quiltmc/quilt-loader/0.20.0/quilt-loader-0.20.0.jar".to_string())
);
assert_eq!(crate::net::maven_coord_to_path("invalid"), None);
assert_eq!(crate::net::maven_coord_to_path("only:two"), None);
}
}
+10 -7
View File
@@ -1,6 +1,6 @@
use chrono::{DateTime, Utc};
use once_cell::sync::Lazy;
use std::collections::HashMap;
use std::sync::LazyLock;
use std::sync::{Arc, Mutex};
#[derive(Debug, Clone, PartialEq)]
@@ -11,15 +11,16 @@ pub enum RunState {
Crashed(Option<i32>),
}
pub static RUNNING: Lazy<Arc<Mutex<HashMap<String, RunState>>>> =
Lazy::new(|| Arc::new(Mutex::new(HashMap::new())));
pub static RUNNING: LazyLock<Arc<Mutex<HashMap<String, RunState>>>> =
LazyLock::new(|| Arc::new(Mutex::new(HashMap::new())));
type PendingLastPlayed = Arc<Mutex<Vec<(String, DateTime<Utc>)>>>;
pub static PENDING_LAST_PLAYED: Lazy<PendingLastPlayed> =
Lazy::new(|| Arc::new(Mutex::new(Vec::new())));
pub static PENDING_LAST_PLAYED: LazyLock<PendingLastPlayed> =
LazyLock::new(|| Arc::new(Mutex::new(Vec::new())));
type KillSenders = Arc<Mutex<HashMap<String, tokio::sync::oneshot::Sender<()>>>>;
pub static KILL_SENDERS: Lazy<KillSenders> = Lazy::new(|| Arc::new(Mutex::new(HashMap::new())));
pub static KILL_SENDERS: LazyLock<KillSenders> =
LazyLock::new(|| Arc::new(Mutex::new(HashMap::new())));
pub fn set_state(name: &str, state: RunState) {
if let Ok(mut map) = RUNNING.lock() {
@@ -33,10 +34,12 @@ pub fn remove(name: &str) {
}
}
#[must_use]
pub fn get(name: &str) -> Option<RunState> {
RUNNING.lock().ok().and_then(|map| map.get(name).cloned())
}
#[must_use]
pub fn all() -> Vec<(String, RunState)> {
RUNNING
.lock()
@@ -135,7 +138,7 @@ mod tests {
fn drain_empty_returns_empty() {
let _ = drain_last_played();
let drained = drain_last_played();
assert!(drained.len() <= drained.len());
assert!(drained.is_empty());
}
#[test]
+99
View File
@@ -0,0 +1,99 @@
use std::collections::HashMap;
use std::sync::{Arc, LazyLock, Mutex};
use tachyonfx::Effect;
use super::widgets::{self, instances};
use crate::instance::{InstanceConfig, InstanceManager};
pub(super) static PENDING_INSTANCES: LazyLock<Arc<Mutex<Vec<InstanceConfig>>>> =
LazyLock::new(|| Arc::new(Mutex::new(Vec::new())));
pub struct App {
pub(super) exit: bool,
pub(super) focused: FocusedArea,
pub(super) pre_overlay_focused: FocusedArea,
pub(super) content_tab: widgets::content::ContentTab,
pub(super) instances_state: instances::State,
pub(super) mods_state: widgets::content::list::ContentListState,
pub(super) resource_packs_state: widgets::content::list::ContentListState,
pub(super) shaders_state: widgets::content::list::ContentListState,
pub(super) worlds_state: widgets::content::list::ContentListState,
pub(super) screenshots_state: widgets::screenshots_grid::ScreenshotsState,
pub(super) logs_state: widgets::logs_viewer::LogsState,
pub(super) account_state: widgets::account::AccountState,
pub(super) picker: ratatui_image::picker::Picker,
pub(super) instance_manager: InstanceManager,
pub(super) log_overlay_scroll: usize,
pub(super) log_overlay_max_scroll: usize,
pub(super) log_overlay_search: widgets::search::SearchState,
pub(super) log_overlay_scrollbar: ratatui::widgets::ScrollbarState,
pub(super) throbber_state: throbber_widgets_tui::ThrobberState,
pub(super) throbber_tick: u8,
pub(super) error_effects: HashMap<u64, ErrorEffectState>,
pub(super) pending_editor: Option<std::path::PathBuf>,
}
pub(super) enum ErrorEffectState {
SlidingIn(Effect, std::time::Instant),
Idle,
FadingOut(Effect, std::time::Instant),
}
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub enum FocusedArea {
#[default]
Instances,
Content,
Account,
Settings,
Overview,
OverviewExpanded,
Popup,
ImportPopup,
ErrorPopup,
ConfirmDelete,
}
impl App {
pub fn new(picker: ratatui_image::picker::Picker) -> Self {
let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir();
let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir();
let _ = std::fs::create_dir_all(&instances_dir);
let _ = std::fs::create_dir_all(&meta_dir);
let manager = InstanceManager::new(instances_dir, meta_dir);
let instances = manager.load_all();
let instances_state = instances::State::with_instances(instances);
App {
exit: false,
focused: FocusedArea::default(),
pre_overlay_focused: FocusedArea::default(),
content_tab: widgets::content::ContentTab::default(),
instances_state,
mods_state: widgets::content::list::ContentListState::default(),
resource_packs_state: widgets::content::list::ContentListState::default(),
shaders_state: widgets::content::list::ContentListState::default(),
worlds_state: widgets::content::list::ContentListState::default(),
logs_state: widgets::logs_viewer::LogsState::default(),
account_state: widgets::account::AccountState::default(),
screenshots_state: {
let mut s = widgets::screenshots_grid::ScreenshotsState::default();
s.font_size = picker.font_size();
s
},
picker,
instance_manager: manager,
log_overlay_scroll: 0,
log_overlay_max_scroll: 0,
log_overlay_search: widgets::search::SearchState::default(),
log_overlay_scrollbar: ratatui::widgets::ScrollbarState::default(),
throbber_state: throbber_widgets_tui::ThrobberState::default(),
throbber_tick: 0,
error_effects: HashMap::new(),
pending_editor: None,
}
}
}
+7 -3
View File
@@ -3,7 +3,7 @@ use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Instant;
use once_cell::sync::Lazy;
use std::sync::LazyLock;
use tracing::Level;
const MAX_ERROR_EVENTS: usize = 50;
@@ -17,8 +17,8 @@ pub struct ErrorEvent {
pub pushed_at: Instant,
}
pub static ERROR_EVENTS: Lazy<Arc<Mutex<VecDeque<ErrorEvent>>>> =
Lazy::new(|| Arc::new(Mutex::new(VecDeque::new())));
pub static ERROR_EVENTS: LazyLock<Arc<Mutex<VecDeque<ErrorEvent>>>> =
LazyLock::new(|| Arc::new(Mutex::new(VecDeque::new())));
pub fn push_error(event: ErrorEvent) {
match ERROR_EVENTS.lock() {
@@ -36,6 +36,7 @@ pub fn push_error(event: ErrorEvent) {
}
}
#[must_use]
pub fn has_errors() -> bool {
match ERROR_EVENTS.lock() {
Ok(events) => !events.is_empty(),
@@ -43,6 +44,7 @@ pub fn has_errors() -> bool {
}
}
#[must_use]
pub fn pop_error() -> Option<ErrorEvent> {
match ERROR_EVENTS.lock() {
Ok(mut events) => events.pop_front(),
@@ -50,6 +52,7 @@ pub fn pop_error() -> Option<ErrorEvent> {
}
}
#[must_use]
pub fn peek_error() -> Option<ErrorEvent> {
match ERROR_EVENTS.lock() {
Ok(events) => events.front().cloned(),
@@ -58,6 +61,7 @@ pub fn peek_error() -> Option<ErrorEvent> {
}
/// Returns all queued error events, newest first (for top-to-bottom stacking).
#[must_use]
pub fn peek_all_errors() -> Vec<ErrorEvent> {
match ERROR_EVENTS.lock() {
Ok(events) => events.iter().rev().cloned().collect(),
+260
View File
@@ -0,0 +1,260 @@
use color_eyre::eyre::Context;
use crossterm::event::{self, Event};
use ratatui::crossterm::event::KeyEventKind;
use std::time::Duration;
use super::app::{App, PENDING_INSTANCES};
use super::widgets::{self, popups::import_modpack, popups::new_instance};
use super::Tui;
use crate::instance::InstanceManager;
use crate::tui::error_buffer;
use crate::tui::progress;
impl App {
pub async fn run(&mut self, terminal: &mut Tui) -> color_eyre::Result<()> {
while !self.exit {
if let Some(params) = new_instance::take_result() {
self.spawn_create(params);
}
if let Some(result) = import_modpack::take_result() {
self.spawn_import(result);
}
self.dismiss_expired_errors();
self.drain_pending_instances();
self.drain_pending_last_played();
self.mods_state.drain_pending();
self.mods_state.try_rescan();
self.resource_packs_state.drain_pending();
self.resource_packs_state.try_rescan();
self.shaders_state.drain_pending();
self.shaders_state.try_rescan();
self.worlds_state.drain_pending();
self.worlds_state.try_rescan();
self.logs_state.drain_pending();
self.logs_state.try_rescan();
self.account_state.drain_auth_result();
widgets::account::drain_device_code(&mut self.account_state);
self.screenshots_state.drain_pending_entries();
self.screenshots_state.request_visible_loads();
self.create_screenshot_protocols();
self.throbber_tick = self.throbber_tick.wrapping_add(1);
if self.throbber_tick.is_multiple_of(8) {
self.throbber_state.calc_next();
}
terminal.draw(|frame| self.render_frame(frame))?;
self.handle_events().wrap_err("handle events failed")?;
if let Some(path) = self.pending_editor.take() {
Self::run_editor(terminal, &path);
}
}
Ok(())
}
fn handle_events(&mut self) -> color_eyre::Result<()> {
match crossterm::event::poll(Duration::from_millis(16)) {
Ok(true) => match event::read() {
Ok(Event::Key(key_event)) if key_event.kind == KeyEventKind::Press => self
.handle_key_event(key_event)
.wrap_err_with(|| format!("handling key event failed:\n{key_event:#?}")),
Ok(_) => Ok(()),
Err(e) => {
tracing::error!("Event read error: {}", e);
Ok(())
}
},
Ok(false) => Ok(()),
Err(e) => {
tracing::error!("Event poll error: {}", e);
Ok(())
}
}
}
fn spawn_create(&self, params: new_instance::WizardParams) {
let instances_dir = self.instance_manager.instances_dir.clone();
let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir();
let pending_instances = PENDING_INSTANCES.clone();
tokio::spawn(async move {
progress::set_action(format!("Creating instance '{}'...", params.name));
progress::set_sub_action(format!("{} {}", params.game_version, params.loader));
let manager = InstanceManager::new(instances_dir, meta_dir);
match manager
.create(
&params.name,
&params.game_version,
params.loader,
params.loader_version.as_deref(),
)
.await
{
Ok(config) => {
if let Ok(mut pending) = pending_instances.lock() {
pending.push(config);
}
}
Err(e) => {
progress::clear();
error_buffer::push_error(error_buffer::ErrorEvent {
id: 0,
level: tracing::Level::ERROR,
message: format!("Failed to create instance '{}': {e}", params.name),
pushed_at: std::time::Instant::now(),
});
}
}
});
}
fn spawn_import(&self, result: import_modpack::ImportResult) {
let instances_dir = self.instance_manager.instances_dir.clone();
let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir();
let pending_instances = PENDING_INSTANCES.clone();
tokio::spawn(async move {
let manager = InstanceManager::new(instances_dir, meta_dir);
match crate::instance::import::execute_import(&result.summary, &manager).await {
Ok(config) => {
if let Ok(mut pending) = pending_instances.lock() {
pending.push(config);
}
}
Err(e) => {
crate::tui::progress::clear();
error_buffer::push_error(error_buffer::ErrorEvent {
id: 0,
level: tracing::Level::ERROR,
message: format!("Import failed: {e}"),
pushed_at: std::time::Instant::now(),
});
}
}
});
}
fn run_editor(terminal: &mut ratatui::DefaultTerminal, path: &std::path::Path) {
use ratatui::crossterm::{
terminal::{
disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
},
ExecutableCommand,
};
use std::io::stdout;
let default_editor = if cfg!(windows) { "notepad" } else { "vi" };
let editor = std::env::var("EDITOR")
.or_else(|_| std::env::var("VISUAL"))
.unwrap_or_else(|_| default_editor.to_owned());
let editor_name = std::path::Path::new(&editor)
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or(&editor);
let is_tui_editor = matches!(
editor_name,
"vi" | "vim"
| "nvim"
| "neovim"
| "nano"
| "micro"
| "helix"
| "hx"
| "emacs"
| "ne"
| "joe"
| "mcedit"
);
if is_tui_editor {
let _ = stdout().execute(LeaveAlternateScreen);
let _ = disable_raw_mode();
let result = std::process::Command::new(&editor)
.arg(path)
.stdin(std::process::Stdio::inherit())
.stdout(std::process::Stdio::inherit())
.stderr(std::process::Stdio::inherit())
.status();
let _ = stdout().execute(EnterAlternateScreen);
let _ = enable_raw_mode();
let _ = terminal.clear();
if let Err(e) = result {
tracing::error!("Failed to open editor: {}", e);
}
} else if let Err(e) = std::process::Command::new(&editor)
.arg(path)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
{
tracing::error!("Failed to open editor: {}", e);
}
}
pub(super) fn spawn_launch(&self, instance: crate::instance::InstanceConfig) {
use crate::instance::launch;
use crate::running;
running::set_state(&instance.name, running::RunState::Authenticating);
let instances_dir = self.instance_manager.instances_dir.clone();
let meta_dir = self.instance_manager.meta_dir.clone();
tokio::spawn(async move {
if let Err(e) = launch::launch(&instance, &instances_dir, &meta_dir).await {
tracing::error!("Failed to launch '{}': {}", instance.name, e);
running::remove(&instance.name);
}
});
}
fn dismiss_expired_errors(&self) {
use crate::config::SETTINGS;
loop {
match error_buffer::peek_error() {
Some(event)
if event.pushed_at.elapsed().as_millis()
>= SETTINGS.ui.error_auto_dismiss_ms as u128 =>
{
let _ = error_buffer::pop_error();
}
_ => break,
}
}
}
fn drain_pending_instances(&mut self) {
if let Ok(mut pending) = PENDING_INSTANCES.lock() {
for config in pending.drain(..) {
self.instances_state.add_instance(config);
}
}
}
fn drain_pending_last_played(&mut self) {
for (name, time) in crate::running::drain_last_played() {
for inst in &mut self.instances_state.instances {
if inst.name == name {
inst.last_played = Some(time);
break;
}
}
}
}
pub(super) fn create_screenshot_protocols(&mut self) {
let pending = self.screenshots_state.take_pending_images();
for (idx, img) in pending {
let proto = self.picker.new_resize_protocol(img);
self.screenshots_state.set_protocol(idx, proto);
}
}
}
+327
View File
@@ -0,0 +1,327 @@
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use super::app::{App, FocusedArea};
use super::widgets::{self, popups::confirm as confirm_popup, popups::import_modpack, popups::new_instance, WidgetKey};
use crate::tui::error_buffer;
impl App {
pub(super) fn handle_key_event(&mut self, key_event: KeyEvent) -> color_eyre::Result<()> {
if self.focused == FocusedArea::OverviewExpanded {
if self.log_overlay_search.active {
match key_event.code {
KeyCode::Esc => {
self.log_overlay_search.deactivate();
}
KeyCode::Backspace => {
self.log_overlay_search.pop();
}
KeyCode::Char(c) => {
self.log_overlay_search.push(c);
}
_ => {}
}
return Ok(());
}
match key_event.code {
KeyCode::Char('O') | KeyCode::Esc => {
self.focused = self.pre_overlay_focused;
self.log_overlay_search.deactivate();
return Ok(());
}
KeyCode::Char('j') | KeyCode::Down => {
if self.log_overlay_scroll < self.log_overlay_max_scroll {
self.log_overlay_scroll += 1;
}
return Ok(());
}
KeyCode::Char('k') | KeyCode::Up => {
self.log_overlay_scroll = self.log_overlay_scroll.saturating_sub(1);
return Ok(());
}
KeyCode::Char('G') => {
self.log_overlay_scroll = self.log_overlay_max_scroll;
return Ok(());
}
KeyCode::Char('g') => {
self.log_overlay_scroll = 0;
return Ok(());
}
KeyCode::Char('/') => {
self.log_overlay_search.activate();
return Ok(());
}
_ => {
return Ok(());
}
}
}
if self.focused == FocusedArea::ConfirmDelete {
match key_event.code {
KeyCode::Enter | KeyCode::Char('y') | KeyCode::Char('Y') => {
let name = confirm_popup::pending_delete_name();
if !name.is_empty() {
match self.instance_manager.delete(&name) {
Ok(_) => {
self.instances_state.remove_instance(&name);
}
Err(e) => {
tracing::error!("Failed to delete instance '{}': {}", name, e);
}
}
}
confirm_popup::clear_pending();
self.focused = FocusedArea::Instances;
return Ok(());
}
KeyCode::Esc | KeyCode::Char('n') | KeyCode::Char('N') => {
confirm_popup::clear_pending();
self.focused = FocusedArea::Instances;
return Ok(());
}
_ => {
return Ok(());
}
}
}
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) {
return Ok(());
}
} else if self.content_tab == widgets::content::ContentTab::Screenshots {
if widgets::screenshots_grid::handle_key(&key_event, &mut self.screenshots_state) {
return Ok(());
}
} else if self.content_tab == widgets::content::ContentTab::Worlds {
if widgets::content::list::handle_key_no_toggle(&key_event, &mut self.worlds_state) {
return Ok(());
}
} else {
let state = match self.content_tab {
widgets::content::ContentTab::Mods => Some(&mut self.mods_state),
widgets::content::ContentTab::ResourcePacks => {
Some(&mut self.resource_packs_state)
}
widgets::content::ContentTab::Shaders => Some(&mut self.shaders_state),
_ => None,
};
if let Some(state) = state {
if widgets::content::list::handle_key(&key_event, state) {
return Ok(());
}
}
}
}
if self.focused == FocusedArea::Account
&& widgets::account::handle_key(&key_event, &mut self.account_state)
{
return Ok(());
}
if self.focused == FocusedArea::Settings {
match widgets::details::handle_key(
&key_event,
self.instances_state.selected_instance(),
&self.instance_manager.instances_dir,
) {
widgets::details::SettingsAction::EditInstance(path)
| widgets::details::SettingsAction::EditGlobal(path) => {
self.pending_editor = Some(path);
return Ok(());
}
widgets::details::SettingsAction::ToggleDesktop => {
if let Some(inst) = self.instances_state.selected_instance() {
let name = inst.name.clone();
match crate::instance::desktop::toggle(inst) {
Ok(true) => {
error_buffer::push_error(error_buffer::ErrorEvent {
id: 0,
level: tracing::Level::INFO,
message: format!("Desktop shortcut created for '{name}'"),
pushed_at: std::time::Instant::now(),
});
}
Ok(false) => {
error_buffer::push_error(error_buffer::ErrorEvent {
id: 0,
level: tracing::Level::INFO,
message: format!("Desktop shortcut removed for '{name}'"),
pushed_at: std::time::Instant::now(),
});
}
Err(e) => {
tracing::error!("Failed to toggle desktop shortcut: {}", e);
}
}
}
return Ok(());
}
widgets::details::SettingsAction::None => {}
}
}
match self.focused {
FocusedArea::Popup => {
new_instance::handle_key(&key_event, &mut self.instances_state);
}
FocusedArea::ImportPopup => {
import_modpack::handle_key(&key_event, &mut self.instances_state);
}
_ => {
if self.focused == FocusedArea::Instances && self.instances_state.renaming.is_some() {
match key_event.code {
KeyCode::Enter => {
let new_name = self.instances_state.renaming.take().unwrap_or_default();
if let Some(inst) = self.instances_state.selected_instance() {
let old_name = inst.name.clone();
match self.instance_manager.rename(&old_name, &new_name) {
Ok(()) => {
if let Some(inst) = self
.instances_state
.instances
.iter_mut()
.find(|i| i.name == old_name)
{
inst.name = new_name.trim().to_owned();
}
}
Err(e) => {
tracing::error!("Rename failed: {}", e);
}
}
}
}
KeyCode::Esc => {
self.instances_state.renaming = None;
}
KeyCode::Backspace => {
if let Some(ref mut name) = self.instances_state.renaming {
name.pop();
}
}
KeyCode::Char(c) => {
if let Some(ref mut name) = self.instances_state.renaming {
name.push(c);
}
}
_ => {}
}
return Ok(());
}
if self.focused == FocusedArea::Instances && self.instances_state.search.active {
self.instances_state.handle_key(&key_event);
return Ok(());
}
match key_event.code {
KeyCode::Char('q') => self.exit = true,
KeyCode::Char('I') => self.focused = FocusedArea::Instances,
KeyCode::Char('C') => self.focused = FocusedArea::Content,
KeyCode::Char('A') => self.focused = FocusedArea::Account,
KeyCode::Char('S') => self.focused = FocusedArea::Settings,
KeyCode::Char('O') => {
self.pre_overlay_focused = self.focused;
self.focused = FocusedArea::OverviewExpanded;
}
KeyCode::Tab | KeyCode::Char('l') | KeyCode::Right
if self.focused == FocusedArea::Content =>
{
self.content_tab = self.content_tab.next();
}
KeyCode::BackTab | KeyCode::Char('h') | KeyCode::Left
if self.focused == FocusedArea::Content =>
{
self.content_tab = self.content_tab.previous();
}
KeyCode::Char('d')
if self.focused == FocusedArea::Instances
&& !self.instances_state.search.active =>
{
if let Some(instance) = self.instances_state.selected_instance() {
let name = instance.name.clone();
confirm_popup::set_pending_delete(&name);
self.focused = FocusedArea::ConfirmDelete;
}
}
KeyCode::Enter
if self.focused == FocusedArea::Instances
&& !self.instances_state.search.active
&& key_event.modifiers.contains(KeyModifiers::SHIFT) =>
{
if let Some(instance) = self.instances_state.selected_instance() {
let dir = self
.instance_manager
.instances_dir
.join(&instance.name)
.join(".minecraft");
if let Err(e) = open::that(&dir) {
tracing::error!("Failed to open instance directory: {}", e);
}
}
}
KeyCode::Enter
if self.focused == FocusedArea::Instances
&& !self.instances_state.search.active =>
{
self.focused = FocusedArea::Content;
}
KeyCode::Char('l')
if self.focused == FocusedArea::Instances
&& !self.instances_state.search.active =>
{
if let Some(instance) = self.instances_state.selected_instance().cloned() {
let can_launch = matches!(
crate::running::get(&instance.name),
None | Some(crate::running::RunState::Crashed(_))
);
if can_launch {
crate::running::remove(&instance.name);
crate::instance_logs::clear(&instance.name);
self.spawn_launch(instance);
}
}
}
KeyCode::Char('r')
if self.focused == FocusedArea::Instances
&& !self.instances_state.search.active =>
{
if let Some(inst) = self.instances_state.selected_instance() {
self.instances_state.renaming = Some(inst.name.clone());
}
}
KeyCode::Esc
if self.focused == FocusedArea::Instances
&& !self.instances_state.search.active =>
{
if let Some(instance) = self.instances_state.selected_instance() {
crate::running::send_kill(&instance.name);
}
}
_ => {}
}
if self.focused == FocusedArea::Instances {
self.instances_state.handle_key(&key_event)
}
}
}
if self.instances_state.wants_popup() {
self.focused = FocusedArea::Popup;
} else if self.focused == FocusedArea::Popup {
self.focused = FocusedArea::Instances;
}
if self.instances_state.wants_import_popup() {
self.focused = FocusedArea::ImportPopup;
} else if self.focused == FocusedArea::ImportPopup {
self.focused = FocusedArea::Instances;
}
Ok(())
}
}
-967
View File
@@ -1,967 +0,0 @@
use super::widgets::popups::import_modpack;
use super::widgets::popups::new_instance;
use super::{
widgets::{self, profiles, WidgetKey},
Tui,
};
use crate::instance::{InstanceConfig, InstanceManager};
use crate::tui::error_buffer;
use crate::tui::progress;
use crate::tui::widgets::popups::confirm as confirm_popup;
use crate::tui::widgets::popups::confirm::{confirm_popup_area, ConfirmPopup};
use crate::tui::widgets::popups::error::{popup_area, ErrorPopup};
use color_eyre::eyre::Context;
use crossterm::event::{self, Event};
use once_cell::sync::Lazy;
use ratatui::{
crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers},
layout::{Constraint, Direction, Layout},
Frame,
};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tachyonfx::{fx, Effect, EffectRenderer, Interpolation, Motion};
static PENDING_INSTANCES: Lazy<Arc<Mutex<Vec<InstanceConfig>>>> =
Lazy::new(|| Arc::new(Mutex::new(Vec::new())));
pub struct App {
exit: bool,
focused: FocusedArea,
pre_overlay_focused: FocusedArea,
content_tab: widgets::content::ContentTab,
profiles_state: profiles::State,
mods_state: widgets::content_list::ContentListState,
resource_packs_state: widgets::content_list::ContentListState,
shaders_state: widgets::content_list::ContentListState,
worlds_state: widgets::content_list::ContentListState,
screenshots_state: widgets::screenshots_grid::ScreenshotsState,
logs_state: widgets::logs_viewer::LogsState,
account_state: widgets::account::AccountState,
picker: ratatui_image::picker::Picker,
instance_manager: InstanceManager,
log_overlay_scroll: usize,
log_overlay_max_scroll: usize,
log_overlay_search: widgets::search::SearchState,
log_overlay_scrollbar: ratatui::widgets::ScrollbarState,
throbber_state: throbber_widgets_tui::ThrobberState,
throbber_tick: u8,
error_effects: HashMap<u64, ErrorEffectState>,
pending_editor: Option<std::path::PathBuf>,
}
enum ErrorEffectState {
SlidingIn(Effect),
Idle,
FadingOut(Effect),
}
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub enum FocusedArea {
#[default]
Profiles,
Content,
Account,
Settings,
Overview,
OverviewExpanded,
Popup,
ImportPopup,
ErrorPopup,
ConfirmDelete,
}
impl App {
pub fn new(picker: ratatui_image::picker::Picker) -> Self {
let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir();
let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir();
match std::fs::create_dir_all(&instances_dir) {
Ok(_) => {}
Err(e) => {
tracing::error!("Failed to create instances dir: {}", e);
}
}
match std::fs::create_dir_all(&meta_dir) {
Ok(_) => {}
Err(e) => {
tracing::error!("Failed to create meta dir: {}", e);
}
}
let manager = InstanceManager::new(instances_dir, meta_dir);
let instances = manager.load_all();
let profiles_state = profiles::State::with_instances(instances);
App {
exit: false,
focused: FocusedArea::default(),
pre_overlay_focused: FocusedArea::default(),
content_tab: widgets::content::ContentTab::default(),
profiles_state,
mods_state: widgets::content_list::ContentListState::default(),
resource_packs_state: widgets::content_list::ContentListState::default(),
shaders_state: widgets::content_list::ContentListState::default(),
worlds_state: widgets::content_list::ContentListState::default(),
logs_state: widgets::logs_viewer::LogsState::default(),
account_state: widgets::account::AccountState::default(),
screenshots_state: {
let mut s = widgets::screenshots_grid::ScreenshotsState::default();
s.font_size = picker.font_size();
s
},
picker,
instance_manager: manager,
log_overlay_scroll: 0,
log_overlay_max_scroll: 0,
log_overlay_search: widgets::search::SearchState::default(),
log_overlay_scrollbar: ratatui::widgets::ScrollbarState::default(),
throbber_state: throbber_widgets_tui::ThrobberState::default(),
throbber_tick: 0,
error_effects: HashMap::new(),
pending_editor: None,
}
}
}
impl App {
pub async fn run(&mut self, terminal: &mut Tui) -> color_eyre::Result<()> {
while !self.exit {
if let Some(params) = new_instance::take_result() {
self.spawn_create(params);
}
if let Some(result) = import_modpack::take_result() {
self.spawn_import(result);
}
self.dismiss_expired_errors();
self.drain_pending_instances();
self.drain_pending_last_played();
self.mods_state.drain_pending();
self.resource_packs_state.drain_pending();
self.shaders_state.drain_pending();
self.worlds_state.drain_pending();
self.logs_state.drain_pending();
self.logs_state.try_rescan();
self.account_state.drain_auth_result();
widgets::account::drain_device_code(&mut self.account_state);
self.screenshots_state.drain_pending_entries();
self.screenshots_state.request_visible_loads();
self.create_screenshot_protocols();
self.throbber_tick = self.throbber_tick.wrapping_add(1);
if self.throbber_tick.is_multiple_of(8) {
self.throbber_state.calc_next();
}
terminal.draw(|frame| self.render_frame(frame))?;
self.handle_events().wrap_err("handle events failed")?;
if let Some(path) = self.pending_editor.take() {
Self::run_editor(terminal, &path);
}
}
Ok(())
}
fn render_frame(&mut self, frame: &mut Frame) {
let chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage(20), // Instances
Constraint::Percentage(80), // Main content
])
.split(frame.area());
widgets::profiles::render(frame, chunks[0], self.focused, &mut self.profiles_state);
let main_chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(3), // Title
Constraint::Min(10), // Main Content
Constraint::Length(5), // Bottom panel
])
.split(chunks[1]);
widgets::content::title(
frame,
main_chunks[0],
self.focused,
self.profiles_state.selected_instance(),
&mut self.throbber_state,
);
widgets::content::render(
frame,
main_chunks[1],
self.focused,
self.content_tab,
self.profiles_state.selected_instance(),
&mut self.mods_state,
&mut self.resource_packs_state,
&mut self.shaders_state,
&mut self.worlds_state,
&mut self.screenshots_state,
&mut self.logs_state,
&self.instance_manager.instances_dir,
);
let bottom_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage(30),
Constraint::Percentage(40),
Constraint::Percentage(30),
])
.split(main_chunks[2]);
widgets::account::render(
frame,
bottom_chunks[0],
self.focused,
&mut self.account_state,
);
widgets::details::render(
frame,
bottom_chunks[1],
self.focused,
self.profiles_state.selected_instance(),
&self.instance_manager.instances_dir,
);
widgets::status::render(
frame,
bottom_chunks[2],
self.focused,
&mut self.throbber_state,
);
if self.focused == FocusedArea::OverviewExpanded {
self.render_log_overlay(frame);
}
let all_errors = error_buffer::peek_all_errors();
self.sync_error_effects(&all_errors);
let mut next_y: u16 = 1;
for event in all_errors {
let elapsed_ms = event.pushed_at.elapsed().as_millis();
if let Some(area) = popup_area(frame.area(), &event.message, next_y, elapsed_ms) {
next_y = next_y.saturating_add(area.height + 1);
frame.render_widget(ErrorPopup::new(event.clone()), area);
self.render_error_effect(frame, area, &event, elapsed_ms);
}
}
if self.profiles_state.show_popup {
let area = new_instance::popup_rect(frame.area());
new_instance::render(frame, area, self.focused);
}
if self.profiles_state.show_import_popup {
let area = import_modpack::popup_rect(frame.area());
import_modpack::render(frame, area, self.focused);
}
if self.focused == FocusedArea::ConfirmDelete {
let name = confirm_popup::pending_delete_name();
if !name.is_empty() {
let area = confirm_popup_area(frame.area(), &name);
frame.render_widget(ConfirmPopup::new(&name), area);
}
}
}
fn handle_events(&mut self) -> color_eyre::Result<()> {
match crossterm::event::poll(Duration::from_millis(16)) {
Ok(true) => match event::read() {
Ok(Event::Key(key_event)) if key_event.kind == KeyEventKind::Press => self
.handle_key_event(key_event)
.wrap_err_with(|| format!("handling key event failed:\n{key_event:#?}")),
Ok(_) => Ok(()),
Err(e) => {
tracing::error!("Event read error: {}", e);
Ok(())
}
},
Ok(false) => Ok(()),
Err(e) => {
tracing::error!("Event poll error: {}", e);
Ok(())
}
}
}
fn handle_key_event(&mut self, key_event: KeyEvent) -> color_eyre::Result<()> {
if self.focused == FocusedArea::OverviewExpanded {
if self.log_overlay_search.active {
match key_event.code {
KeyCode::Esc => {
self.log_overlay_search.deactivate();
}
KeyCode::Backspace => {
self.log_overlay_search.pop();
}
KeyCode::Char(c) => {
self.log_overlay_search.push(c);
}
_ => {}
}
return Ok(());
}
match key_event.code {
KeyCode::Char('O') | KeyCode::Esc => {
self.focused = self.pre_overlay_focused;
self.log_overlay_search.deactivate();
return Ok(());
}
KeyCode::Char('j') | KeyCode::Down => {
if self.log_overlay_scroll < self.log_overlay_max_scroll {
self.log_overlay_scroll += 1;
}
return Ok(());
}
KeyCode::Char('k') | KeyCode::Up => {
self.log_overlay_scroll = self.log_overlay_scroll.saturating_sub(1);
return Ok(());
}
KeyCode::Char('G') => {
self.log_overlay_scroll = self.log_overlay_max_scroll;
return Ok(());
}
KeyCode::Char('g') => {
self.log_overlay_scroll = 0;
return Ok(());
}
KeyCode::Char('/') => {
self.log_overlay_search.activate();
return Ok(());
}
_ => {
return Ok(());
}
}
}
if self.focused == FocusedArea::ConfirmDelete {
match key_event.code {
KeyCode::Enter | KeyCode::Char('y') | KeyCode::Char('Y') => {
let name = confirm_popup::pending_delete_name();
if !name.is_empty() {
match self.instance_manager.delete(&name) {
Ok(_) => {
self.profiles_state.remove_instance(&name);
}
Err(e) => {
tracing::error!("Failed to delete instance '{}': {}", name, e);
}
}
}
confirm_popup::clear_pending();
self.focused = FocusedArea::Profiles;
return Ok(());
}
KeyCode::Esc | KeyCode::Char('n') | KeyCode::Char('N') => {
confirm_popup::clear_pending();
self.focused = FocusedArea::Profiles;
return Ok(());
}
_ => {
return Ok(());
}
}
}
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) {
return Ok(());
}
} else if self.content_tab == widgets::content::ContentTab::Screenshots {
if widgets::screenshots_grid::handle_key(&key_event, &mut self.screenshots_state) {
return Ok(());
}
} else if self.content_tab == widgets::content::ContentTab::Worlds {
if widgets::content_list::handle_key_no_toggle(&key_event, &mut self.worlds_state) {
return Ok(());
}
} else {
let state = match self.content_tab {
widgets::content::ContentTab::Mods => Some(&mut self.mods_state),
widgets::content::ContentTab::ResourcePacks => {
Some(&mut self.resource_packs_state)
}
widgets::content::ContentTab::Shaders => Some(&mut self.shaders_state),
_ => None,
};
if let Some(state) = state {
if widgets::content_list::handle_key(&key_event, state) {
return Ok(());
}
}
}
}
if self.focused == FocusedArea::Account
&& widgets::account::handle_key(&key_event, &mut self.account_state) {
return Ok(());
}
if self.focused == FocusedArea::Settings {
match widgets::details::handle_key(
&key_event,
self.profiles_state.selected_instance(),
&self.instance_manager.instances_dir,
) {
widgets::details::SettingsAction::EditInstance(path)
| widgets::details::SettingsAction::EditGlobal(path) => {
self.pending_editor = Some(path);
return Ok(());
}
widgets::details::SettingsAction::ToggleDesktop => {
if let Some(inst) = self.profiles_state.selected_instance() {
let name = inst.name.clone();
match crate::instance::desktop::toggle(inst) {
Ok(true) => {
error_buffer::push_error(error_buffer::ErrorEvent {
id: 0,
level: tracing::Level::INFO,
message: format!("Desktop shortcut created for '{name}'"),
pushed_at: std::time::Instant::now(),
});
}
Ok(false) => {
error_buffer::push_error(error_buffer::ErrorEvent {
id: 0,
level: tracing::Level::INFO,
message: format!("Desktop shortcut removed for '{name}'"),
pushed_at: std::time::Instant::now(),
});
}
Err(e) => {
tracing::error!("Failed to toggle desktop shortcut: {}", e);
}
}
}
return Ok(());
}
widgets::details::SettingsAction::None => {}
}
}
match self.focused {
FocusedArea::Popup => {
new_instance::handle_key(&key_event, &mut self.profiles_state);
}
FocusedArea::ImportPopup => {
import_modpack::handle_key(&key_event, &mut self.profiles_state);
}
_ => {
if self.focused == FocusedArea::Profiles && self.profiles_state.renaming.is_some() {
match key_event.code {
KeyCode::Enter => {
let new_name = self.profiles_state.renaming.take().unwrap_or_default();
if let Some(inst) = self.profiles_state.selected_instance() {
let old_name = inst.name.clone();
match self.instance_manager.rename(&old_name, &new_name) {
Ok(()) => {
if let Some(inst) = self
.profiles_state
.instances
.iter_mut()
.find(|i| i.name == old_name)
{
inst.name = new_name.trim().to_string();
}
}
Err(e) => {
tracing::error!("Rename failed: {}", e);
}
}
}
}
KeyCode::Esc => {
self.profiles_state.renaming = None;
}
KeyCode::Backspace => {
if let Some(ref mut name) = self.profiles_state.renaming {
name.pop();
}
}
KeyCode::Char(c) => {
if let Some(ref mut name) = self.profiles_state.renaming {
name.push(c);
}
}
_ => {}
}
return Ok(());
}
if self.focused == FocusedArea::Profiles && self.profiles_state.search.active {
self.profiles_state.handle_key(&key_event);
return Ok(());
}
match key_event.code {
KeyCode::Char('q') => self.exit = true,
KeyCode::Char('P') => self.focused = FocusedArea::Profiles,
KeyCode::Char('C') => self.focused = FocusedArea::Content,
KeyCode::Char('A') => self.focused = FocusedArea::Account,
KeyCode::Char('S') => self.focused = FocusedArea::Settings,
KeyCode::Char('O') => {
self.pre_overlay_focused = self.focused;
self.focused = FocusedArea::OverviewExpanded;
}
KeyCode::Tab | KeyCode::Char('l') | KeyCode::Right
if self.focused == FocusedArea::Content =>
{
self.content_tab = self.content_tab.next();
}
KeyCode::BackTab | KeyCode::Char('h') | KeyCode::Left
if self.focused == FocusedArea::Content =>
{
self.content_tab = self.content_tab.previous();
}
KeyCode::Char('d')
if self.focused == FocusedArea::Profiles
&& !self.profiles_state.search.active =>
{
if let Some(instance) = self.profiles_state.selected_instance() {
let name = instance.name.clone();
confirm_popup::set_pending_delete(&name);
self.focused = FocusedArea::ConfirmDelete;
}
}
KeyCode::Enter
if self.focused == FocusedArea::Profiles
&& !self.profiles_state.search.active
&& key_event.modifiers.contains(KeyModifiers::SHIFT) =>
{
if let Some(instance) = self.profiles_state.selected_instance() {
let dir = self
.instance_manager
.instances_dir
.join(&instance.name)
.join(".minecraft");
if let Err(e) = std::process::Command::new("xdg-open")
.arg(&dir)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
{
tracing::error!("Failed to open instance directory: {}", e);
}
}
}
KeyCode::Enter
if self.focused == FocusedArea::Profiles
&& !self.profiles_state.search.active =>
{
self.focused = FocusedArea::Content;
}
KeyCode::Char('l')
if self.focused == FocusedArea::Profiles
&& !self.profiles_state.search.active =>
{
if let Some(instance) = self.profiles_state.selected_instance().cloned() {
let can_launch = matches!(
crate::running::get(&instance.name),
None | Some(crate::running::RunState::Crashed(_))
);
if can_launch {
crate::running::remove(&instance.name);
crate::instance_logs::clear(&instance.name);
self.spawn_launch(instance);
}
}
}
KeyCode::Char('r')
if self.focused == FocusedArea::Profiles
&& !self.profiles_state.search.active =>
{
if let Some(inst) = self.profiles_state.selected_instance() {
self.profiles_state.renaming = Some(inst.name.clone());
}
}
KeyCode::Esc
if self.focused == FocusedArea::Profiles
&& !self.profiles_state.search.active =>
{
if let Some(instance) = self.profiles_state.selected_instance() {
crate::running::send_kill(&instance.name);
}
}
_ => {}
}
if self.focused == FocusedArea::Profiles {
self.profiles_state.handle_key(&key_event)
}
}
}
if self.profiles_state.wants_popup() {
self.focused = FocusedArea::Popup;
} else if self.focused == FocusedArea::Popup {
self.focused = FocusedArea::Profiles;
}
if self.profiles_state.wants_import_popup() {
self.focused = FocusedArea::ImportPopup;
} else if self.focused == FocusedArea::ImportPopup {
self.focused = FocusedArea::Profiles;
}
Ok(())
}
fn spawn_create(&self, params: new_instance::WizardParams) {
let instances_dir = self.instance_manager.instances_dir.clone();
let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir();
let pending_instances = PENDING_INSTANCES.clone();
tokio::spawn(async move {
progress::set_action(format!("Creating instance '{}'...", params.name));
progress::set_sub_action(format!("{} {}", params.game_version, params.loader));
let manager = InstanceManager::new(instances_dir, meta_dir);
match manager
.create(
&params.name,
&params.game_version,
params.loader,
params.loader_version.as_deref(),
)
.await
{
Ok(config) => match pending_instances.lock() {
Ok(mut pending) => {
pending.push(config);
}
Err(e) => {
tracing::error!("Pending instance queue lock poisoned: {}", e);
}
},
Err(_e) => {
progress::clear();
}
}
});
}
fn spawn_import(&self, result: import_modpack::ImportResult) {
let instances_dir = self.instance_manager.instances_dir.clone();
let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir();
let pending_instances = PENDING_INSTANCES.clone();
tokio::spawn(async move {
let manager = InstanceManager::new(instances_dir, meta_dir);
match crate::instance::import::execute_import(&result.summary, &manager).await {
Ok(config) => match pending_instances.lock() {
Ok(mut pending) => {
pending.push(config);
}
Err(e) => {
tracing::error!("Pending instance queue lock poisoned: {}", e);
}
},
Err(e) => {
tracing::error!("Import failed: {}", e);
crate::tui::progress::clear();
}
}
});
}
fn run_editor(terminal: &mut ratatui::DefaultTerminal, path: &std::path::Path) {
use ratatui::crossterm::{
terminal::{
disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
},
ExecutableCommand,
};
use std::io::stdout;
let editor = std::env::var("EDITOR")
.or_else(|_| std::env::var("VISUAL"))
.unwrap_or_else(|_| "vi".to_string());
let is_tui_editor = matches!(
editor.rsplit('/').next().unwrap_or(&editor),
"vi" | "vim"
| "nvim"
| "neovim"
| "nano"
| "micro"
| "helix"
| "hx"
| "emacs"
| "ne"
| "joe"
| "mcedit"
);
if is_tui_editor {
let _ = stdout().execute(LeaveAlternateScreen);
let _ = disable_raw_mode();
let result = std::process::Command::new(&editor)
.arg(path)
.stdin(std::process::Stdio::inherit())
.stdout(std::process::Stdio::inherit())
.stderr(std::process::Stdio::inherit())
.status();
let _ = stdout().execute(EnterAlternateScreen);
let _ = enable_raw_mode();
let _ = terminal.clear();
if let Err(e) = result {
tracing::error!("Failed to open editor: {}", e);
}
} else {
if let Err(e) = std::process::Command::new(&editor)
.arg(path)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
{
tracing::error!("Failed to open editor: {}", e);
}
}
}
fn spawn_launch(&self, instance: crate::instance::InstanceConfig) {
use crate::instance::launch;
use crate::running;
running::set_state(&instance.name, running::RunState::Authenticating);
let instances_dir = self.instance_manager.instances_dir.clone();
let meta_dir = self.instance_manager.meta_dir.clone();
tokio::spawn(async move {
match launch::launch(&instance, &instances_dir, &meta_dir).await {
Ok(()) => {}
Err(e) => {
tracing::error!("Failed to launch '{}': {}", instance.name, e);
running::remove(&instance.name);
}
}
});
}
fn dismiss_expired_errors(&self) {
use crate::config::SETTINGS;
loop {
match error_buffer::peek_error() {
Some(event)
if event.pushed_at.elapsed().as_millis()
>= SETTINGS.ui.error_auto_dismiss_ms as u128 =>
{
error_buffer::pop_error();
}
_ => break,
}
}
}
fn drain_pending_instances(&mut self) {
match PENDING_INSTANCES.lock() {
Ok(mut pending) => {
for config in pending.drain(..) {
self.profiles_state.add_instance(config);
}
}
Err(e) => {
tracing::error!("Pending instance queue lock poisoned: {}", e);
}
}
}
fn drain_pending_last_played(&mut self) {
for (name, time) in crate::running::drain_last_played() {
for inst in &mut self.profiles_state.instances {
if inst.name == name {
inst.last_played = Some(time);
break;
}
}
}
}
fn create_screenshot_protocols(&mut self) {
let pending = self.screenshots_state.take_pending_images();
for (idx, img) in pending {
let proto = self.picker.new_resize_protocol(img);
self.screenshots_state.set_protocol(idx, proto);
}
}
fn render_log_overlay(&mut self, frame: &mut Frame) {
use crate::tui::logging::get_app_logs;
use crate::tui::theme::THEME;
use ratatui::{
layout::{Alignment, Margin},
style::{Modifier, Style},
text::Line,
widgets::{Block, Clear, Paragraph, Scrollbar, ScrollbarOrientation},
};
let area = frame.area();
let overlay = area.inner(Margin::new(1, 1));
frame.render_widget(Clear, overlay);
let all_lines = get_app_logs();
let filtered: Vec<&String> = all_lines
.iter()
.filter(|l| self.log_overlay_search.matches(l))
.collect();
let visible_height = overlay.height.saturating_sub(2) as usize;
let was_at_bottom =
self.log_overlay_scroll >= self.log_overlay_max_scroll.saturating_sub(1);
self.log_overlay_max_scroll = filtered.len().saturating_sub(visible_height);
if was_at_bottom || self.log_overlay_scroll > self.log_overlay_max_scroll {
self.log_overlay_scroll = self.log_overlay_max_scroll;
}
self.log_overlay_scrollbar =
ratatui::widgets::ScrollbarState::new(self.log_overlay_max_scroll)
.position(self.log_overlay_scroll);
let mut block = Block::bordered()
.title_top(
Line::from(" Logs ").style(
Style::default()
.fg(THEME.log_overlay.text_fg)
.add_modifier(Modifier::BOLD),
),
)
.title_bottom(
crate::tui::widgets::popups::keybind_line(&[("O", " close"), ("/", " search")])
.alignment(Alignment::Right),
)
.border_type(THEME.general.border_type.to_border_type())
.border_style(Style::default().fg(THEME.log_overlay.border_fg));
if let Some(sl) = self.log_overlay_search.title_line() {
block = block.title_top(sl);
}
let inner = block.inner(overlay);
frame.render_widget(block, overlay);
let search = &self.log_overlay_search;
let styled: Vec<Line> = filtered
.iter()
.skip(self.log_overlay_scroll)
.take(visible_height)
.map(|line| {
let style = if line.contains("ERROR") || line.contains("FATAL") {
Style::default().fg(THEME.log_overlay.error_fg)
} else if line.contains("WARN") {
Style::default().fg(THEME.log_overlay.warn_fg)
} else if line.contains("DEBUG") || line.contains("TRACE") {
Style::default().fg(THEME.log_overlay.debug_fg)
} else {
Style::default().fg(THEME.log_overlay.text_fg)
};
search.highlight_line(line, style)
})
.collect();
frame.render_widget(Paragraph::new(styled), inner);
let scrollbar_area = ratatui::layout::Rect {
x: inner.x + inner.width.saturating_sub(1),
y: inner.y + 1,
width: 1,
height: inner.height.saturating_sub(2),
};
frame.render_stateful_widget(
Scrollbar::default()
.orientation(ScrollbarOrientation::VerticalRight)
.begin_symbol(Some("\u{25b2}"))
.style(
Style::default()
.fg(THEME.log_overlay.border_fg)
.add_modifier(Modifier::BOLD),
)
.thumb_symbol("\u{2503}")
.track_symbol(Some(""))
.end_symbol(Some("\u{25bc}")),
scrollbar_area,
&mut self.log_overlay_scrollbar,
);
}
fn sync_error_effects(&mut self, events: &[error_buffer::ErrorEvent]) {
use crate::tui::theme::THEME;
let active_ids: std::collections::HashSet<u64> =
events.iter().map(|event| event.id).collect();
self.error_effects.retain(|id, _| active_ids.contains(id));
for event in events {
self.error_effects.entry(event.id).or_insert_with(|| {
ErrorEffectState::SlidingIn(fx::slide_in(
Motion::RightToLeft,
8,
0,
THEME.log_overlay.bg,
(300, Interpolation::SineOut),
))
});
}
}
fn render_error_effect(
&mut self,
frame: &mut Frame,
area: ratatui::layout::Rect,
event: &error_buffer::ErrorEvent,
elapsed_ms: u128,
) {
use crate::config::SETTINGS;
use crate::tui::theme::THEME;
let fly_out_ms = SETTINGS.ui.error_fly_out_ms as u128;
let fly_start_ms = SETTINGS.ui.error_auto_dismiss_ms as u128
- fly_out_ms.min(SETTINGS.ui.error_auto_dismiss_ms as u128);
if elapsed_ms >= fly_start_ms {
let entry = self
.error_effects
.entry(event.id)
.or_insert(ErrorEffectState::Idle);
if !matches!(entry, ErrorEffectState::FadingOut(_)) {
*entry = ErrorEffectState::FadingOut(fx::slide_out(
Motion::LeftToRight,
8,
0,
THEME.log_overlay.bg,
(fly_out_ms as u32, Interpolation::SineIn),
));
}
}
if let Some(effect_state) = self.error_effects.get_mut(&event.id) {
match effect_state {
ErrorEffectState::SlidingIn(effect) => {
if effect.running() {
frame.render_effect(effect, area, tachyonfx::Duration::from_millis(16));
} else {
*effect_state = ErrorEffectState::Idle;
}
}
ErrorEffectState::Idle => {}
ErrorEffectState::FadingOut(effect) => {
if effect.running() {
frame.render_effect(effect, area, tachyonfx::Duration::from_millis(16));
}
}
}
}
}
}
+3 -3
View File
@@ -8,12 +8,12 @@ use tracing_subscriber::layer::Context;
use tracing_subscriber::prelude::*;
use tracing_subscriber::{EnvFilter, Layer};
use once_cell::sync::Lazy;
use std::sync::LazyLock;
use crate::tui::error_buffer::{self, ErrorEvent};
static APP_LOG_LINES: Lazy<Arc<Mutex<Vec<String>>>> =
Lazy::new(|| Arc::new(Mutex::new(Vec::new())));
static APP_LOG_LINES: LazyLock<Arc<Mutex<Vec<String>>>> =
LazyLock::new(|| Arc::new(Mutex::new(Vec::new())));
pub fn get_app_logs() -> Vec<String> {
APP_LOG_LINES.lock().map(|l| l.clone()).unwrap_or_default()
+5 -3
View File
@@ -1,8 +1,10 @@
pub mod app;
pub mod error_buffer;
pub mod layout;
mod event;
mod input;
pub mod logging;
pub mod progress;
pub mod theme;
mod render;
pub mod widgets;
pub type Tui = ratatui::DefaultTerminal;
@@ -21,7 +23,7 @@ pub async fn show() -> color_eyre::Result<()> {
let picker = ratatui_image::picker::Picker::from_query_stdio()
.unwrap_or_else(|_| ratatui_image::picker::Picker::halfblocks());
let result = layout::App::new(picker).run(&mut terminal).await;
let result = app::App::new(picker).run(&mut terminal).await;
let _ = crossterm::execute!(
std::io::stdout(),
+3 -3
View File
@@ -1,4 +1,4 @@
use once_cell::sync::Lazy;
use std::sync::LazyLock;
use std::sync::{Arc, Mutex};
#[derive(Debug, Default, Clone)]
@@ -11,8 +11,8 @@ pub struct ProgressState {
pub sub_action: Option<String>,
}
pub static PROGRESS: Lazy<Arc<Mutex<ProgressState>>> =
Lazy::new(|| Arc::new(Mutex::new(ProgressState::default())));
pub static PROGRESS: LazyLock<Arc<Mutex<ProgressState>>> =
LazyLock::new(|| Arc::new(Mutex::new(ProgressState::default())));
pub fn set_action(text: impl Into<String>) {
let text = text.into();
+297
View File
@@ -0,0 +1,297 @@
use ratatui::{
layout::{Constraint, Direction, Layout},
Frame,
};
use tachyonfx::{fx, EffectRenderer, Interpolation, Motion};
use super::app::{App, ErrorEffectState, FocusedArea};
use super::widgets::{self, popups::confirm as confirm_popup, popups::import_modpack, popups::new_instance};
use crate::tui::error_buffer;
use crate::tui::widgets::popups::confirm::{confirm_popup_area, ConfirmPopup};
use crate::tui::widgets::popups::error::{popup_area, ErrorPopup};
impl App {
pub(super) fn render_frame(&mut self, frame: &mut Frame) {
use crate::config::theme::THEME;
use ratatui::widgets::Block;
use ratatui::style::Style;
let theme = THEME.as_ref();
frame.render_widget(
Block::default().style(Style::default().bg(theme.background())),
frame.area(),
);
let chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage(20),
Constraint::Percentage(80),
])
.split(frame.area());
widgets::instances::render(frame, chunks[0], self.focused, &mut self.instances_state);
let main_chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(3),
Constraint::Min(10),
Constraint::Length(5),
])
.split(chunks[1]);
widgets::content::title(
frame,
main_chunks[0],
self.focused,
self.instances_state.selected_instance(),
&mut self.throbber_state,
);
widgets::content::render(
frame,
main_chunks[1],
self.focused,
self.content_tab,
self.instances_state.selected_instance(),
&mut self.mods_state,
&mut self.resource_packs_state,
&mut self.shaders_state,
&mut self.worlds_state,
&mut self.screenshots_state,
&mut self.logs_state,
&self.instance_manager.instances_dir,
);
let bottom_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage(30),
Constraint::Percentage(40),
Constraint::Percentage(30),
])
.split(main_chunks[2]);
widgets::account::render(
frame,
bottom_chunks[0],
self.focused,
&mut self.account_state,
);
widgets::details::render(
frame,
bottom_chunks[1],
self.focused,
self.instances_state.selected_instance(),
&self.instance_manager.instances_dir,
);
widgets::status::render(
frame,
bottom_chunks[2],
self.focused,
&mut self.throbber_state,
);
if self.focused == FocusedArea::OverviewExpanded {
self.render_log_overlay(frame);
}
let all_errors = error_buffer::peek_all_errors();
self.sync_error_effects(&all_errors);
let mut next_y: u16 = 1;
for event in all_errors {
let elapsed_ms = event.pushed_at.elapsed().as_millis();
if let Some(area) = popup_area(frame.area(), &event.message, next_y, elapsed_ms) {
next_y = next_y.saturating_add(area.height + 1);
frame.render_widget(ErrorPopup::new(event.clone()), area);
self.render_error_effect(frame, area, &event, elapsed_ms);
}
}
if self.instances_state.show_popup {
let area = new_instance::popup_rect(frame.area());
new_instance::render(frame, area, self.focused);
}
if self.instances_state.show_import_popup {
let area = import_modpack::popup_rect(frame.area());
import_modpack::render(frame, area, self.focused);
}
if self.focused == FocusedArea::ConfirmDelete {
let name = confirm_popup::pending_delete_name();
if !name.is_empty() {
let area = confirm_popup_area(frame.area(), &name);
frame.render_widget(ConfirmPopup::new(&name), area);
}
}
}
fn render_log_overlay(&mut self, frame: &mut Frame) {
use crate::config::theme::{THEME, BORDER_STYLE};
use crate::tui::logging::get_app_logs;
use ratatui::{
layout::{Alignment, Margin},
style::{Modifier, Style},
text::Line,
widgets::{Block, Clear, Paragraph, Scrollbar, ScrollbarOrientation},
};
let theme = THEME.as_ref();
let area = frame.area();
let overlay = area.inner(Margin::new(1, 1));
frame.render_widget(Clear, overlay);
let all_lines = get_app_logs();
let filtered: Vec<&String> = all_lines
.iter()
.filter(|l| self.log_overlay_search.matches(l))
.collect();
let visible_height = overlay.height.saturating_sub(2) as usize;
let was_at_bottom =
self.log_overlay_scroll >= self.log_overlay_max_scroll.saturating_sub(1);
self.log_overlay_max_scroll = filtered.len().saturating_sub(visible_height);
if was_at_bottom || self.log_overlay_scroll > self.log_overlay_max_scroll {
self.log_overlay_scroll = self.log_overlay_max_scroll;
}
self.log_overlay_scrollbar =
ratatui::widgets::ScrollbarState::new(self.log_overlay_max_scroll)
.position(self.log_overlay_scroll);
let mut block = Block::bordered()
.title_top(
Line::from(" Logs ").style(
Style::default()
.fg(theme.text())
.add_modifier(Modifier::BOLD),
),
)
.title_bottom(
crate::tui::widgets::popups::keybind_line(&[("O", " close"), ("/", " search")])
.alignment(Alignment::Right),
)
.border_type(BORDER_STYLE.to_border_type())
.border_style(Style::default().fg(theme.accent()));
if let Some(sl) = self.log_overlay_search.title_line() {
block = block.title_top(sl);
}
let inner = block.inner(overlay);
frame.render_widget(block, overlay);
let search = &self.log_overlay_search;
let styled: Vec<Line> = filtered
.iter()
.skip(self.log_overlay_scroll)
.take(visible_height)
.map(|line| {
let style = if line.contains("ERROR") || line.contains("FATAL") {
Style::default().fg(theme.error())
} else if line.contains("WARN") {
Style::default().fg(theme.warning())
} else if line.contains("DEBUG") || line.contains("TRACE") {
Style::default().fg(theme.text_dim())
} else {
Style::default().fg(theme.text())
};
search.highlight_line(line, style)
})
.collect();
frame.render_widget(Paragraph::new(styled), inner);
let scrollbar_area = ratatui::layout::Rect {
x: overlay.x + overlay.width.saturating_sub(1),
y: overlay.y + 1,
width: 1,
height: overlay.height.saturating_sub(2),
};
frame.render_stateful_widget(
Scrollbar::default()
.orientation(ScrollbarOrientation::VerticalRight)
.begin_symbol(Some("\u{25b2}"))
.style(
Style::default()
.fg(theme.text_dim())
.add_modifier(Modifier::BOLD),
)
.thumb_symbol("\u{2551}")
.track_symbol(Some(""))
.end_symbol(Some("\u{25bc}")),
scrollbar_area,
&mut self.log_overlay_scrollbar,
);
}
fn sync_error_effects(&mut self, events: &[error_buffer::ErrorEvent]) {
use crate::config::theme::THEME;
let theme = THEME.as_ref();
let bg = theme.background();
let active_ids: std::collections::HashSet<u64> =
events.iter().map(|event| event.id).collect();
self.error_effects.retain(|id, _| active_ids.contains(id));
for event in events {
self.error_effects.entry(event.id).or_insert_with(|| {
ErrorEffectState::SlidingIn(
fx::slide_in(Motion::RightToLeft, 4, 0, bg, (250, Interpolation::CubicOut)),
std::time::Instant::now(),
)
});
}
}
fn render_error_effect(
&mut self,
frame: &mut Frame,
area: ratatui::layout::Rect,
event: &error_buffer::ErrorEvent,
elapsed_ms: u128,
) {
use crate::config::SETTINGS;
use crate::config::theme::THEME;
let theme = THEME.as_ref();
let bg = theme.background();
let fly_out_ms = SETTINGS.ui.error_fly_out_ms as u128;
let fly_start_ms = SETTINGS.ui.error_auto_dismiss_ms as u128
- fly_out_ms.min(SETTINGS.ui.error_auto_dismiss_ms as u128);
if elapsed_ms >= fly_start_ms {
let entry = self
.error_effects
.entry(event.id)
.or_insert(ErrorEffectState::Idle);
if !matches!(entry, ErrorEffectState::FadingOut(..)) {
*entry = ErrorEffectState::FadingOut(
fx::slide_out(Motion::LeftToRight, 4, 0, bg, (fly_out_ms as u32, Interpolation::CubicIn)),
std::time::Instant::now(),
);
}
}
if let Some(effect_state) = self.error_effects.get_mut(&event.id) {
match effect_state {
ErrorEffectState::SlidingIn(effect, started) => {
let dt = started.elapsed().as_millis() as u32;
if effect.running() {
frame.render_effect(effect, area, tachyonfx::Duration::from_millis(dt.min(32)));
*started = std::time::Instant::now();
} else {
*effect_state = ErrorEffectState::Idle;
}
}
ErrorEffectState::Idle => {}
ErrorEffectState::FadingOut(effect, started) => {
let dt = started.elapsed().as_millis() as u32;
if effect.running() {
frame.render_effect(effect, area, tachyonfx::Duration::from_millis(dt.min(32)));
*started = std::time::Instant::now();
}
}
}
}
}
}
-1611
View File
File diff suppressed because it is too large. Load diff
+68 -55
View File
@@ -3,7 +3,7 @@ use std::sync::{Arc, Mutex};
use crossterm::event::{KeyCode, KeyEvent};
use ratatui::{
layout::Rect,
style::{Color, Modifier, Style},
style::{Modifier, Style},
text::{Line, Span},
widgets::{Block, Borders, Paragraph, Widget},
Frame,
@@ -11,8 +11,8 @@ use ratatui::{
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
use crate::auth::{self, AccountStore, AccountType, AuthResult, DeviceCodeInfo};
use crate::tui::layout::FocusedArea;
use crate::tui::theme::THEME;
use crate::tui::app::FocusedArea;
use crate::config::theme::{THEME, BORDER_STYLE};
use super::styled_title;
@@ -213,16 +213,17 @@ pub fn drain_device_code(state: &mut AccountState) {
}
pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut AccountState) {
let theme = THEME.as_ref();
let color = if focused == FocusedArea::Account {
THEME.account.border_focused_fg
theme.accent()
} else {
THEME.account.border_unfocused_fg
theme.border()
};
let mut block = Block::default()
.title(styled_title("Accounts", true))
.borders(Borders::ALL)
.border_type(THEME.general.border_type.to_border_type())
.border_type(BORDER_STYLE.to_border_type())
.border_style(Style::default().fg(color));
if focused == FocusedArea::Account {
@@ -241,7 +242,7 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut A
if state.store.accounts.is_empty() {
frame.render_widget(
Paragraph::new("No accounts.")
.style(Style::default().fg(THEME.account.text_secondary_fg)),
.style(Style::default().fg(theme.text_dim())),
inner,
);
} else {
@@ -282,47 +283,36 @@ fn render_account_list(
let count = accounts.len();
let builder = ListBuilder::new(move |context| {
let theme = THEME.as_ref();
let (username, acc_type, is_active) = &accounts[context.index];
let show_selected = is_focused && context.is_selected;
let stripe_bg = Color::Reset;
let stripe_bg = theme.background();
let bg = if show_selected {
THEME.account.selected_bg
} else {
stripe_bg
};
let bg = stripe_bg;
let active_marker = if *is_active { "\u{25b8} " } else { " " };
let style = if show_selected {
let mut s = Style::default().fg(THEME.account.selected_fg);
if THEME.account.selected_bold {
s = s.add_modifier(Modifier::BOLD);
}
s
Style::default().fg(theme.accent()).add_modifier(Modifier::BOLD)
} else if *is_active {
Style::default()
.fg(THEME.account.text_fg)
.fg(theme.text())
.add_modifier(Modifier::BOLD)
} else {
Style::default().fg(THEME.account.text_fg)
Style::default().fg(theme.text())
};
let mut spans = vec![
Span::styled(active_marker, Style::default().fg(THEME.account.active_fg)),
Span::styled(active_marker, Style::default().fg(theme.success())),
Span::styled(username.clone(), style),
];
if *acc_type == AccountType::Offline {
let offline_style = if show_selected {
let mut s = Style::default().fg(THEME.account.selected_fg);
if THEME.account.selected_bold {
s = s.add_modifier(Modifier::BOLD);
}
s
Style::default().fg(theme.accent()).add_modifier(Modifier::BOLD)
} else {
Style::default().fg(THEME.account.text_secondary_fg)
Style::default().fg(theme.text_dim())
};
spans.push(Span::styled(" (Offline)", offline_style));
}
@@ -349,42 +339,48 @@ fn popup_area(frame: &Frame, width: u16, height: u16) -> Rect {
fn render_choose_popup(frame: &mut Frame) {
use super::popups::base::PopupFrame;
let theme = THEME.as_ref();
let area = popup_area(frame, 40, 7);
let border_color = theme.text_dim();
let dim_color = theme.text_dim();
let accent_color = theme.success();
let text_color = theme.text();
PopupFrame {
title: Line::from(" Add Account ").centered(),
border_color: THEME.account.border_focused_fg,
border_color,
bg: None,
keybinds: Some(Line::from(Span::styled(
" Esc: cancel ",
Style::default().fg(THEME.account.text_secondary_fg),
Style::default().fg(dim_color),
))),
search_line: None,
content: Box::new(|inner, buf| {
content: Box::new(move |inner, buf| {
let text = vec![
Line::from(""),
Line::from(vec![
Span::styled(
" [m] ",
Style::default()
.fg(THEME.account.active_fg)
.fg(accent_color)
.add_modifier(Modifier::BOLD),
),
Span::styled(
"Microsoft Account",
Style::default().fg(THEME.account.text_fg),
Style::default().fg(text_color),
),
]),
Line::from(vec![
Span::styled(
" [o] ",
Style::default()
.fg(THEME.account.active_fg)
.fg(accent_color)
.add_modifier(Modifier::BOLD),
),
Span::styled(
"Offline Account",
Style::default().fg(THEME.account.text_fg),
Style::default().fg(text_color),
),
]),
];
@@ -396,19 +392,25 @@ fn render_choose_popup(frame: &mut Frame) {
fn render_offline_popup(frame: &mut Frame, name: &str) {
use super::popups::{base::PopupFrame, keybind_line};
let theme = THEME.as_ref();
let area = popup_area(frame, 40, 5);
let name = name.to_string();
let border_color = theme.text_dim();
let bg_color = theme.surface();
let dim_color = theme.text_dim();
let text_color = theme.text();
PopupFrame {
title: Line::from(Span::styled(
" Offline Account ",
Style::default()
.fg(THEME.account.border_focused_fg)
.fg(border_color)
.add_modifier(Modifier::BOLD),
))
.centered(),
border_color: THEME.account.border_focused_fg,
bg: Some(THEME.account.popup_bg),
border_color,
bg: Some(bg_color),
keybinds: Some(keybind_line(&[("Enter", " confirm"), ("Esc", " cancel")])),
search_line: None,
content: Box::new(move |inner, buf| {
@@ -416,22 +418,22 @@ fn render_offline_popup(frame: &mut Frame, name: &str) {
Line::from(vec![
Span::styled(
"Username...",
Style::default().fg(THEME.account.border_unfocused_fg),
Style::default().fg(dim_color),
),
Span::styled(
"\u{2588}",
Style::default()
.fg(THEME.account.border_focused_fg)
.fg(border_color)
.add_modifier(Modifier::SLOW_BLINK),
),
])
} else {
Line::from(vec![
Span::styled(name.as_str(), Style::default().fg(THEME.account.text_fg)),
Span::styled(name.as_str(), Style::default().fg(text_color)),
Span::styled(
"\u{2588}",
Style::default()
.fg(THEME.account.border_focused_fg)
.fg(border_color)
.add_modifier(Modifier::SLOW_BLINK),
),
])
@@ -444,6 +446,7 @@ fn render_offline_popup(frame: &mut Frame, name: &str) {
fn render_confirm_delete(frame: &mut Frame, state: &AccountState, idx: usize) {
use super::popups::{base::PopupFrame, keybind_line};
let theme = THEME.as_ref();
let username = state
.store
.accounts
@@ -451,10 +454,11 @@ fn render_confirm_delete(frame: &mut Frame, state: &AccountState, idx: usize) {
.map(|a| a.username.as_str())
.unwrap_or("?");
let border_color = theme.text_dim();
let title = Line::from(Span::styled(
format!(" Delete '{}' ", username),
Style::default()
.fg(THEME.account.border_focused_fg)
.fg(border_color)
.add_modifier(Modifier::BOLD),
));
@@ -462,15 +466,18 @@ fn render_confirm_delete(frame: &mut Frame, state: &AccountState, idx: usize) {
let popup_w = (username.len() + 14).max(body.len() + 2).min(48) as u16 + 2;
let area = popup_area(frame, popup_w, 3);
let bg_color = theme.surface();
let text_color = theme.text();
PopupFrame {
title,
border_color: THEME.account.border_focused_fg,
bg: Some(THEME.account.popup_bg),
border_color,
bg: Some(bg_color),
keybinds: Some(keybind_line(&[("Enter", " confirm")])),
search_line: None,
content: Box::new(|inner, buf| {
content: Box::new(move |inner, buf| {
Paragraph::new("This will permanently remove this account")
.style(Style::default().fg(THEME.account.text_fg))
.style(Style::default().fg(text_color))
.render(inner, buf);
}),
}
@@ -479,57 +486,63 @@ fn render_confirm_delete(frame: &mut Frame, state: &AccountState, idx: usize) {
fn render_device_code_popup(frame: &mut Frame, info: &DeviceCodeInfo) {
use super::popups::{base::PopupFrame, keybind_line};
let theme = THEME.as_ref();
let area = popup_area(frame, 50, 8);
let uri = info.verification_uri.clone();
let code = info.user_code.clone();
let border_color = theme.text_dim();
let bg_color = theme.surface();
let dim_color = theme.text_dim();
let accent_color = theme.success();
PopupFrame {
title: Line::from(Span::styled(
" Microsoft Login ",
Style::default()
.fg(THEME.account.border_focused_fg)
.fg(border_color)
.add_modifier(Modifier::BOLD),
))
.centered(),
border_color: THEME.account.border_focused_fg,
bg: Some(THEME.account.popup_bg),
border_color,
bg: Some(bg_color),
keybinds: Some(keybind_line(&[("Esc", " cancel")])),
search_line: None,
content: Box::new(move |inner, buf| {
let text = if code.is_empty() {
vec![Line::from(Span::styled(
"Connecting to Microsoft...",
Style::default().fg(THEME.account.text_secondary_fg),
Style::default().fg(dim_color),
))]
} else {
vec![
Line::from(Span::styled(
"Open this URL in your browser:",
Style::default().fg(THEME.account.text_secondary_fg),
Style::default().fg(dim_color),
)),
Line::from(Span::styled(
uri.as_str(),
Style::default()
.fg(THEME.account.active_fg)
.fg(accent_color)
.add_modifier(Modifier::BOLD),
)),
Line::from(""),
Line::from(vec![
Span::styled(
"Enter code: ",
Style::default().fg(THEME.account.text_secondary_fg),
Style::default().fg(dim_color),
),
Span::styled(
code.as_str(),
Style::default()
.fg(THEME.account.active_fg)
.fg(accent_color)
.add_modifier(Modifier::BOLD),
),
]),
Line::from(""),
Line::from(Span::styled(
"Waiting for authentication...",
Style::default().fg(THEME.account.text_secondary_fg),
Style::default().fg(dim_color),
)),
]
};
@@ -12,27 +12,29 @@ use ratatui::{
};
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
use crate::instance::mods::ModEntry;
use crate::tui::theme::THEME;
use crate::instance::content::mods::{ContentEntry, IconCell};
use crate::config::theme::THEME;
type IconCell = (u8, u8, u8, u8, u8, u8);
type PendingContent = Arc<Mutex<Option<(String, Vec<ModEntry>)>>>;
type PendingContent = Arc<Mutex<Option<(String, Vec<ContentEntry>)>>>;
type SnapshotRow = (String, String, bool, Option<Vec<Vec<IconCell>>>);
struct CachedList {
entries: Vec<ModEntry>,
entries: Vec<ContentEntry>,
selected: Option<usize>,
}
pub struct ContentListState {
pub entries: Vec<ModEntry>,
pub entries: Vec<ContentEntry>,
pub list_state: TuiListState,
pub scrollbar_state: ScrollbarState,
pub loaded_for: Option<String>,
pub loading: bool,
pub search: super::search::SearchState,
pub search: crate::tui::widgets::search::SearchState,
cache: HashMap<String, CachedList>,
pending: PendingContent,
check_counter: u16,
watched_dir: Option<std::path::PathBuf>,
last_dir_mtime: Option<std::time::SystemTime>,
}
impl Default for ContentListState {
@@ -43,14 +45,50 @@ impl Default for ContentListState {
scrollbar_state: ScrollbarState::default(),
loaded_for: None,
loading: false,
search: super::search::SearchState::default(),
search: crate::tui::widgets::search::SearchState::default(),
cache: HashMap::new(),
pending: Arc::new(Mutex::new(None)),
check_counter: 0,
watched_dir: None,
last_dir_mtime: None,
}
}
}
impl ContentListState {
/// Check if the content directory changed (files added/removed).
/// Only triggers a rescan when the directory's modification time differs.
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;
}
let Some(dir) = &self.watched_dir else {
return;
};
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;
}
}
}
/// 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);
}
pub fn filtered_indices(&self) -> Vec<usize> {
self.entries
.iter()
@@ -64,7 +102,7 @@ impl ContentListState {
impl ContentListState {
pub fn start_load<F>(&mut self, instances_dir: &Path, instance_name: &str, scan_fn: F)
where
F: FnOnce(&Path, &str) -> Vec<ModEntry> + Send + 'static,
F: FnOnce(&Path, &str) -> Vec<ContentEntry> + Send + 'static,
{
if let Some(prev) = self.loaded_for.take() {
if !self.entries.is_empty() {
@@ -243,12 +281,7 @@ 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)) {
if let Some(dir) = state.entries[real_idx].path.parent() {
if let Err(e) = std::process::Command::new("xdg-open")
.arg(dir)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
{
if let Err(e) = open::that(dir) {
tracing::error!("Failed to open directory: {}", e);
}
}
@@ -285,12 +318,7 @@ 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)) {
if let Some(dir) = state.entries[real_idx].path.parent() {
if let Err(e) = std::process::Command::new("xdg-open")
.arg(dir)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
{
if let Err(e) = open::that(dir) {
tracing::error!("Failed to open directory: {}", e);
}
}
@@ -318,10 +346,11 @@ pub fn render(
loading_text: &str,
empty_text: &str,
) {
let theme = THEME.as_ref();
if state.loading {
frame.render_widget(
Paragraph::new(loading_text)
.style(Style::default().fg(THEME.content_list.text_secondary_fg)),
.style(Style::default().fg(theme.text_dim())),
area,
);
return;
@@ -332,7 +361,7 @@ pub fn render(
if filtered.is_empty() {
frame.render_widget(
Paragraph::new(empty_text)
.style(Style::default().fg(THEME.content_list.text_secondary_fg)),
.style(Style::default().fg(theme.text_dim())),
area,
);
return;
@@ -354,67 +383,57 @@ pub fn render(
.collect();
let builder = ListBuilder::new(move |context| {
let theme = THEME.as_ref();
let (name, description, enabled, icon_pixels) = &snapshot[context.index];
let show_selected = is_focused && context.is_selected;
let use_mc_colors = *enabled && !show_selected;
let use_mc_colors = *enabled;
let stripe_bg = if context.index % 2 == 0 {
Color::Reset
theme.background()
} else {
THEME.content_list.row_alt_bg
theme.stripe()
};
let (name_style, description_style, background) = match (*enabled, show_selected) {
(true, true) => {
let mut ns = Style::default().fg(THEME.content_list.selected_fg);
if THEME.content_list.selected_bold {
ns = ns.add_modifier(Modifier::BOLD);
}
(
ns,
Style::default().fg(THEME.content_list.selected_fg),
THEME.content_list.selected_bg,
)
}
(true, false) => (
Style::default()
.fg(THEME.content_list.text_fg)
.add_modifier(Modifier::BOLD),
Style::default().fg(THEME.content_list.text_secondary_fg),
(true, true) => (
Style::default().fg(theme.accent()).add_modifier(Modifier::BOLD),
Style::default().fg(theme.text_dim()),
stripe_bg,
),
(true, false) => (
Style::default()
.fg(theme.text())
.add_modifier(Modifier::BOLD),
Style::default().fg(theme.text_dim()),
stripe_bg,
),
(false, true) => (
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()),
stripe_bg,
),
(false, true) => {
let mut ns = Style::default().fg(THEME.content_list.selected_fg);
if THEME.content_list.disabled_crossed_out {
ns = ns.add_modifier(Modifier::CROSSED_OUT);
}
(
ns,
Style::default().fg(THEME.content_list.selected_fg),
THEME.content_list.selected_bg,
)
}
(false, false) => {
let mut ns = Style::default().fg(THEME.content_list.text_secondary_fg);
if THEME.content_list.disabled_crossed_out {
ns = ns.add_modifier(Modifier::CROSSED_OUT);
}
(
ns,
Style::default().fg(THEME.content_list.text_secondary_fg),
stripe_bg,
)
}
};
let has_icon = icon_pixels.is_some();
let stripped_desc = strip_mc_codes(description);
let has_description = !stripped_desc.trim().is_empty();
let full_desc = strip_mc_codes(description);
let stripped_desc = full_desc.lines().next().unwrap_or("").trim().to_string();
let has_description = !stripped_desc.is_empty();
let compact = !has_icon && !has_description;
let selector = if show_selected {
Span::styled("\u{258c}", Style::default().fg(theme.accent()))
} else {
Span::raw(" ")
};
if compact {
let mut line = Vec::new();
line.push(Span::raw(" "));
line.push(selector.clone());
if use_mc_colors {
line.extend(parse_mc_text(name, name_style));
} else {
@@ -425,9 +444,17 @@ pub fn render(
(item, 1)
} else if has_icon {
let icon_row_count = icon_pixels.as_ref().map(|r| r.len()).unwrap_or(0);
let height = icon_row_count.max(2) as u16;
let text_rows = if has_description { 2 } else { 1 }; // name + optional description
let height = icon_row_count.max(text_rows) as u16;
let mut line_0 = icon_spans(icon_pixels.as_ref(), 0);
let pad = if show_selected {
Span::styled("\u{258c}", Style::default().fg(theme.accent()))
} else {
Span::raw(" ")
};
let mut line_0 = vec![selector.clone()];
line_0.extend(icon_spans(icon_pixels.as_ref(), 0));
line_0.push(Span::raw(" "));
if use_mc_colors {
line_0.extend(parse_mc_text(name, name_style));
@@ -435,41 +462,51 @@ pub fn render(
line_0.push(Span::styled(strip_mc_codes(name), name_style));
}
let mut line_1 = icon_spans(icon_pixels.as_ref(), 1);
line_1.push(Span::raw(" "));
if use_mc_colors {
line_1.extend(parse_mc_text(description, description_style));
} else {
line_1.push(Span::styled(stripped_desc, description_style));
let mut lines = vec![Line::from(line_0)];
if has_description {
let mut row = vec![pad.clone()];
row.extend(icon_spans(icon_pixels.as_ref(), 1));
row.push(Span::raw(" "));
row.push(Span::styled(stripped_desc.clone(), description_style));
lines.push(Line::from(row));
}
let mut lines = vec![Line::from(line_0), Line::from(line_1)];
for r in 2..icon_row_count {
lines.push(Line::from(icon_spans(icon_pixels.as_ref(), r)));
let desc_rows = if has_description { 1 } else { 0 };
for r in (1 + desc_rows)..icon_row_count {
let mut row = vec![pad.clone()];
row.extend(icon_spans(icon_pixels.as_ref(), r));
lines.push(Line::from(row));
}
let item = Text::from(lines).style(Style::default().bg(background));
(item, height)
} else {
let mut line_0 = Vec::new();
line_0.push(Span::raw(" "));
line_0.push(selector.clone());
if use_mc_colors {
line_0.extend(parse_mc_text(name, name_style));
} else {
line_0.push(Span::styled(strip_mc_codes(name), name_style));
}
let mut line_1 = Vec::new();
line_1.push(Span::raw(" "));
if use_mc_colors {
line_1.extend(parse_mc_text(description, description_style));
} else {
line_1.push(Span::styled(stripped_desc, description_style));
let mut lines = vec![Line::from(line_0)];
if has_description {
let pad = if show_selected {
Span::styled("\u{258c}", Style::default().fg(theme.accent()))
} else {
Span::raw(" ")
};
lines.push(Line::from(vec![
pad,
Span::styled(stripped_desc.clone(), description_style),
]));
}
let item = Text::from(vec![Line::from(line_0), Line::from(line_1)])
.style(Style::default().bg(background));
(item, 2)
let height = lines.len() as u16;
let item = Text::from(lines).style(Style::default().bg(background));
(item, height)
}
});
@@ -488,7 +525,7 @@ pub fn render(
.begin_symbol(Some("\u{25b2}"))
.style(
Style::default()
.fg(THEME.content_list.border_focused_fg)
.fg(theme.text_dim())
.add_modifier(Modifier::BOLD),
)
.thumb_symbol("\u{2551}")
@@ -588,18 +625,21 @@ fn icon_spans(icon_pixels: Option<&Vec<Vec<IconCell>>>, row: usize) -> Vec<Span<
match icon_pixels.and_then(|rows| rows.get(row)) {
Some(cols) => cols
.iter()
.map(|&(fg_r, fg_g, fg_b, bg_r, bg_g, bg_b)| {
.map(|cell| {
Span::styled(
"\u{2584}",
Style::default()
.fg(Color::Rgb(fg_r, fg_g, fg_b))
.bg(Color::Rgb(bg_r, bg_g, bg_b)),
.fg(Color::Rgb(cell.fg_r, cell.fg_g, cell.fg_b))
.bg(Color::Rgb(cell.bg_r, cell.bg_g, cell.bg_b)),
)
})
.collect(),
None => vec![Span::styled(
" ",
Style::default().fg(THEME.content_list.text_secondary_fg),
)],
None => {
let theme = THEME.as_ref();
vec![Span::styled(
" ",
Style::default().fg(theme.text_dim()),
)]
}
}
}
+5
View File
@@ -0,0 +1,5 @@
pub mod list;
pub mod tabs;
pub use tabs::{ContentTab, render, title};
pub use list::{ContentListState, handle_key, handle_key_no_toggle};
@@ -7,10 +7,10 @@ use ratatui::{
};
use throbber_widgets_tui::{Throbber, ThrobberState};
use crate::tui::layout::FocusedArea;
use crate::tui::theme::THEME;
use crate::tui::app::FocusedArea;
use crate::config::theme::{THEME, BORDER_STYLE};
use super::styled_title;
use crate::tui::widgets::styled_title;
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum ContentTab {
@@ -69,20 +69,21 @@ pub fn render(
focused: FocusedArea,
tab: ContentTab,
instance: Option<&crate::instance::InstanceConfig>,
mods_state: &mut super::content_list::ContentListState,
resource_packs_state: &mut super::content_list::ContentListState,
shaders_state: &mut super::content_list::ContentListState,
worlds_state: &mut super::content_list::ContentListState,
screenshots_state: &mut super::screenshots_grid::ScreenshotsState,
logs_state: &mut super::logs_viewer::LogsState,
mods_state: &mut super::list::ContentListState,
resource_packs_state: &mut super::list::ContentListState,
shaders_state: &mut super::list::ContentListState,
worlds_state: &mut super::list::ContentListState,
screenshots_state: &mut crate::tui::widgets::screenshots_grid::ScreenshotsState,
logs_state: &mut crate::tui::widgets::logs_viewer::LogsState,
instances_dir: &std::path::Path,
) {
let theme = THEME.as_ref();
let is_focused = focused == FocusedArea::Content;
let border_color = if is_focused {
THEME.content.border_focused_fg
theme.accent()
} else {
THEME.content.border_unfocused_fg
theme.border()
};
let tab_titles: Vec<Span> = ContentTab::ALL
@@ -93,21 +94,18 @@ pub fn render(
if i > 0 {
spans.push(Span::styled(
"\u{2022}",
Style::default().fg(THEME.content.border_unfocused_fg),
Style::default().fg(theme.text_dim()),
));
}
if i == tab.index() {
let mut style = Style::default()
.fg(THEME.content.tab_active_fg)
.bg(THEME.content.selected_bg);
if THEME.content.tab_active_bold {
style = style.add_modifier(Modifier::BOLD);
}
let style = Style::default()
.fg(theme.accent())
.add_modifier(Modifier::BOLD);
spans.push(Span::styled(format!(" {} ", t.label()), style));
} else {
spans.push(Span::styled(
format!(" {} ", t.label()),
Style::default().fg(THEME.content.text_fg),
Style::default().fg(theme.text()),
));
}
spans
@@ -132,7 +130,7 @@ pub fn render(
let mut block = Block::default()
.title_top(Line::from(tab_titles))
.borders(Borders::ALL)
.border_type(THEME.general.border_type.to_border_type())
.border_type(BORDER_STYLE.to_border_type())
.border_style(Style::default().fg(border_color));
if let Some(sl) = search_line {
@@ -179,7 +177,7 @@ pub fn render(
}
}
})
} else if focused == FocusedArea::Profiles {
} else if focused == FocusedArea::Instances {
Some(&[
("l", " launch"),
("⏎", " content"),
@@ -196,7 +194,7 @@ pub fn render(
};
if let Some(kb) = kb {
let lines = super::popups::keybind_lines_wrapped(kb, area.width.saturating_sub(2));
let lines = crate::tui::widgets::popups::keybind_lines_wrapped(kb, area.width.saturating_sub(2));
for line in lines {
block = block.title_bottom(line);
}
@@ -214,8 +212,9 @@ pub fn render(
&instance.name,
crate::instance::scan_mods,
);
mods_state.watch_dir(instances_dir.join(&instance.name).join(".minecraft").join("mods"));
}
super::content_list::render(
super::list::render(
frame,
content_area,
mods_state,
@@ -226,7 +225,7 @@ pub fn render(
} else {
frame.render_widget(
Paragraph::new("No instance selected.")
.style(Style::default().fg(THEME.content.tab_inactive_fg)),
.style(Style::default().fg(theme.text_dim())),
content_area,
);
}
@@ -239,8 +238,9 @@ pub fn render(
&instance.name,
crate::instance::scan_resource_packs,
);
resource_packs_state.watch_dir(instances_dir.join(&instance.name).join(".minecraft").join("resourcepacks"));
}
super::content_list::render(
super::list::render(
frame,
content_area,
resource_packs_state,
@@ -251,7 +251,7 @@ pub fn render(
} else {
frame.render_widget(
Paragraph::new("No instance selected.")
.style(Style::default().fg(THEME.content.tab_inactive_fg)),
.style(Style::default().fg(theme.text_dim())),
content_area,
);
}
@@ -264,8 +264,9 @@ pub fn render(
&instance.name,
crate::instance::scan_shaders,
);
shaders_state.watch_dir(instances_dir.join(&instance.name).join(".minecraft").join("shaderpacks"));
}
super::content_list::render(
super::list::render(
frame,
content_area,
shaders_state,
@@ -276,7 +277,7 @@ pub fn render(
} else {
frame.render_widget(
Paragraph::new("No instance selected.")
.style(Style::default().fg(THEME.content.tab_inactive_fg)),
.style(Style::default().fg(theme.text_dim())),
content_area,
);
}
@@ -286,11 +287,11 @@ pub fn render(
if logs_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
logs_state.start_load(instances_dir, &instance.name);
}
super::logs_viewer::render(frame, content_area, logs_state, is_focused);
crate::tui::widgets::logs_viewer::render(frame, content_area, logs_state, is_focused);
} else {
frame.render_widget(
Paragraph::new("No instance selected.")
.style(Style::default().fg(THEME.content.tab_inactive_fg)),
.style(Style::default().fg(theme.text_dim())),
content_area,
);
}
@@ -300,11 +301,11 @@ pub fn render(
if screenshots_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
screenshots_state.start_load(instances_dir, &instance.name);
}
super::screenshots_grid::render(frame, content_area, screenshots_state, is_focused);
crate::tui::widgets::screenshots_grid::render(frame, content_area, screenshots_state, is_focused);
} else {
frame.render_widget(
Paragraph::new("No instance selected.")
.style(Style::default().fg(THEME.content.tab_inactive_fg)),
.style(Style::default().fg(theme.text_dim())),
content_area,
);
}
@@ -317,8 +318,9 @@ pub fn render(
&instance.name,
crate::instance::scan_worlds,
);
worlds_state.watch_dir(instances_dir.join(&instance.name).join(".minecraft").join("saves"));
}
super::content_list::render(
super::list::render(
frame,
content_area,
worlds_state,
@@ -329,7 +331,7 @@ pub fn render(
} else {
frame.render_widget(
Paragraph::new("No instance selected.")
.style(Style::default().fg(THEME.content.tab_inactive_fg)),
.style(Style::default().fg(theme.text_dim())),
content_area,
);
}
@@ -344,16 +346,17 @@ pub fn title(
instance: Option<&crate::instance::InstanceConfig>,
throbber_state: &mut ThrobberState,
) {
let theme = THEME.as_ref();
let color = if focused == FocusedArea::Content {
THEME.content.border_focused_fg
theme.accent()
} else {
THEME.content.border_unfocused_fg
theme.border()
};
let block = Block::default()
.title(styled_title("Content", true))
.borders(Borders::ALL)
.border_type(THEME.general.border_type.to_border_type())
.border_type(BORDER_STYLE.to_border_type())
.border_style(Style::default().fg(color));
let inner = block.inner(area);
@@ -363,7 +366,7 @@ pub fn title(
None => {
frame.render_widget(
Paragraph::new("No instance selected")
.style(Style::default().fg(THEME.content.tab_inactive_fg)),
.style(Style::default().fg(theme.text_dim())),
inner,
);
}
@@ -382,12 +385,12 @@ pub fn title(
.label(inst.name.as_str())
.style(
Style::default()
.fg(THEME.content.text_fg)
.fg(theme.text())
.add_modifier(Modifier::BOLD),
)
.throbber_style(
Style::default()
.fg(THEME.general.success)
.fg(theme.success())
.add_modifier(Modifier::BOLD),
)
.throbber_set(throbber_widgets_tui::BRAILLE_EIGHT_DOUBLE)
@@ -400,13 +403,13 @@ pub fn title(
Span::styled(
"\u{2717} ",
Style::default()
.fg(THEME.general.error)
.fg(theme.error())
.add_modifier(Modifier::BOLD),
),
Span::styled(
inst.name.as_str(),
Style::default()
.fg(THEME.content.text_fg)
.fg(theme.text())
.add_modifier(Modifier::BOLD),
),
])),
@@ -418,7 +421,7 @@ pub fn title(
Paragraph::new(Span::styled(
inst.name.as_str(),
Style::default()
.fg(THEME.content.text_fg)
.fg(theme.text())
.add_modifier(Modifier::BOLD),
)),
left_area,
@@ -432,7 +435,7 @@ pub fn title(
};
frame.render_widget(
Paragraph::new(loader_str)
.style(Style::default().fg(THEME.content.border_focused_fg))
.style(Style::default().fg(theme.text_dim()))
.alignment(Alignment::Right),
right_area,
);
+10 -9
View File
@@ -7,8 +7,8 @@ use ratatui::{
};
use crate::instance::models::InstanceConfig;
use crate::tui::layout::FocusedArea;
use crate::tui::theme::THEME;
use crate::tui::app::FocusedArea;
use crate::config::theme::{THEME, BORDER_STYLE};
use super::styled_title;
@@ -19,16 +19,17 @@ pub fn render(
instance: Option<&InstanceConfig>,
_instances_dir: &std::path::Path,
) {
let theme = THEME.as_ref();
let color = if focused == FocusedArea::Settings {
THEME.details.border_focused_fg
theme.accent()
} else {
THEME.details.border_unfocused_fg
theme.border()
};
let mut block = Block::default()
.title(styled_title("Settings", true))
.borders(Borders::ALL)
.border_type(THEME.general.border_type.to_border_type())
.border_type(BORDER_STYLE.to_border_type())
.border_style(Style::default().fg(color));
if focused == FocusedArea::Settings {
@@ -51,17 +52,17 @@ pub fn render(
let Some(inst) = instance else {
frame.render_widget(
Paragraph::new("No instance selected.")
.style(Style::default().fg(THEME.details.label_fg)),
.style(Style::default().fg(theme.text_dim())),
inner,
);
return;
};
let label_style = Style::default().fg(THEME.details.label_fg);
let label_style = Style::default().fg(theme.text_dim());
let value_style = Style::default()
.fg(THEME.details.value_fg)
.fg(theme.text())
.add_modifier(Modifier::BOLD);
let dim_style = Style::default().fg(THEME.details.border_unfocused_fg);
let dim_style = Style::default().fg(theme.text_dim());
let memory_min = inst.memory_min.as_deref().unwrap_or("512M");
let memory_max = inst.memory_max.as_deref().unwrap_or("2G");
@@ -1,4 +1,4 @@
use crate::tui::theme::THEME;
use crate::config::theme::{THEME, BORDER_STYLE};
use crossterm::event::KeyCode;
use ratatui::{
layout::Rect,
@@ -11,7 +11,7 @@ use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
use crate::instance::models::InstanceConfig;
use crate::running::{get as get_run_state, RunState};
use crate::tui::layout::FocusedArea;
use crate::tui::app::FocusedArea;
use super::{search::SearchState, styled_title, WidgetKey};
@@ -33,17 +33,6 @@ fn format_last_played(last_played: Option<chrono::DateTime<chrono::Utc>>) -> Str
}
}
fn loader_color(loader: crate::instance::models::ModLoader) -> ratatui::style::Color {
use crate::instance::models::ModLoader;
match loader {
ModLoader::Vanilla => THEME.profiles.loader_vanilla,
ModLoader::Fabric => THEME.profiles.loader_fabric,
ModLoader::Forge => THEME.profiles.loader_forge,
ModLoader::NeoForge => THEME.profiles.loader_neoforge,
ModLoader::Quilt => THEME.profiles.loader_quilt,
}
}
#[derive(Debug, Default)]
pub struct State {
pub instances: Vec<InstanceConfig>,
@@ -202,16 +191,17 @@ impl WidgetKey for State {
}
pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut State) {
let color = if focused == FocusedArea::Profiles {
THEME.profiles.border_focused_fg
let theme = THEME.as_ref();
let color = if focused == FocusedArea::Instances {
theme.accent()
} else {
THEME.profiles.border_unfocused_fg
theme.border()
};
let mut block = Block::default()
.title(styled_title("Profiles", true))
.title(styled_title("Instances", true))
.borders(Borders::ALL)
.border_type(THEME.general.border_type.to_border_type())
.border_type(BORDER_STYLE.to_border_type())
.border_style(Style::default().fg(color));
if let Some(search_line) = state.search.title_line() {
@@ -229,56 +219,54 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut S
let count = filtered.len();
let builder = ListBuilder::new(|context| {
let theme = THEME.as_ref();
let idx = filtered[context.index];
let instance = &state.instances[idx];
let stripe_bg = if context.index % 2 == 0 {
THEME.general.bg
theme.background()
} else {
THEME.profiles.row_alt_bg
theme.stripe()
};
let (name_style, meta_style, bg) = if context.is_selected {
let mut style = Style::default().fg(THEME.profiles.selected_fg);
if THEME.profiles.selected_bold {
style = style.add_modifier(Modifier::BOLD);
}
(
style,
Style::default().fg(THEME.profiles.selected_fg),
THEME.profiles.selected_bg,
Style::default().fg(theme.accent()).add_modifier(Modifier::BOLD),
Style::default().fg(theme.text_dim()),
stripe_bg,
)
} else {
(
Style::default()
.fg(THEME.profiles.border_focused_fg)
.fg(theme.text())
.add_modifier(Modifier::BOLD),
Style::default().fg(THEME.profiles.border_unfocused_fg),
Style::default().fg(theme.text_dim()),
stripe_bg,
)
};
let stripe = Span::styled(
"\u{258c} ",
Style::default().fg(loader_color(instance.loader)),
);
let selector = if context.is_selected {
Span::styled("\u{258c} ", Style::default().fg(theme.accent()))
} else {
Span::raw(" ")
};
let is_renaming = context.is_selected && state.renaming.is_some();
let name_line = if is_renaming {
let rename_val = state.renaming.as_deref().unwrap_or("");
Line::from(vec![
stripe.clone(),
Span::styled(rename_val, Style::default().fg(THEME.profiles.text_fg)),
selector.clone(),
Span::styled(rename_val, Style::default().fg(theme.text())),
Span::styled(
"\u{2588}",
Style::default()
.fg(THEME.profiles.border_focused_fg)
.fg(theme.text_dim())
.add_modifier(Modifier::SLOW_BLINK),
),
])
} else {
Line::from(vec![
stripe.clone(),
selector.clone(),
Span::styled(instance.name.as_str(), name_style),
])
};
@@ -286,16 +274,16 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut S
let (meta_text, meta_text_style) = match get_run_state(&instance.name) {
Some(RunState::Authenticating) => (
"Authenticating".to_string(),
Style::default().fg(THEME.profiles.running_fg),
Style::default().fg(theme.success()),
),
Some(RunState::Running) | Some(RunState::Starting) => (
"Playing".to_string(),
Style::default().fg(THEME.profiles.running_fg),
Style::default().fg(theme.success()),
),
_ => (format_last_played(instance.last_played), meta_style),
};
let meta_line = Line::from(vec![stripe, Span::styled(meta_text, meta_text_style)]);
let meta_line = Line::from(vec![selector.clone(), Span::styled(meta_text, meta_text_style)]);
let item = Text::from(vec![name_line, meta_line]).style(Style::default().bg(bg));
(item, 2)
@@ -311,7 +299,7 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut S
.begin_symbol(Some("\u{25b2}"))
.style(
Style::default()
.fg(THEME.profiles.border_focused_fg)
.fg(theme.text_dim())
.add_modifier(Modifier::BOLD),
)
.thumb_symbol("\u{2551}")
+31 -36
View File
@@ -4,7 +4,7 @@ use std::sync::{Arc, Mutex};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::{
layout::{Constraint, Layout, Rect},
style::{Color, Modifier, Style},
style::{Modifier, Style},
text::{Line, Span},
widgets::{Block, Borders, Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState},
Frame,
@@ -12,7 +12,7 @@ use ratatui::{
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
use crate::instance::log_files::{read_log_file, scan_log_files, LogFileEntry};
use crate::tui::theme::THEME;
use crate::config::theme::{THEME, BORDER_STYLE};
type PendingLogs = Arc<Mutex<Option<(String, Vec<LogFileEntry>)>>>;
@@ -342,9 +342,10 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool {
}
pub fn render(frame: &mut Frame, area: Rect, state: &mut LogsState, is_focused: bool) {
let theme = THEME.as_ref();
if state.loading {
frame.render_widget(
Paragraph::new("Loading logs...").style(Style::default().fg(THEME.logs.text_fg)),
Paragraph::new("Loading logs...").style(Style::default().fg(theme.text_dim())),
area,
);
return;
@@ -355,7 +356,7 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut LogsState, is_focused:
if display_count == 0 {
frame.render_widget(
Paragraph::new("No logs yet.").style(Style::default().fg(THEME.logs.text_fg)),
Paragraph::new("No logs yet.").style(Style::default().fg(theme.text_dim())),
area,
);
return;
@@ -380,16 +381,17 @@ fn render_list(
is_focused: bool,
has_live: bool,
) {
let theme = THEME.as_ref();
let list_focused = is_focused && !state.viewer_focused;
let border_color = if list_focused {
THEME.logs.border_focused_fg
theme.accent()
} else {
THEME.logs.border_unfocused_fg
theme.border()
};
let block = Block::default()
.borders(Borders::RIGHT)
.border_type(THEME.general.border_type.to_border_type())
.border_type(BORDER_STYLE.to_border_type())
.border_style(Style::default().fg(border_color));
let inner = block.inner(area);
@@ -413,34 +415,27 @@ fn render_list(
let show_selected = list_focused && context.is_selected;
let style = if *is_live && show_selected {
let s = Style::default().fg(THEME.logs.running_fg);
if THEME.logs.selected_bold {
s.add_modifier(Modifier::BOLD)
} else {
s
}
Style::default().fg(theme.success()).add_modifier(Modifier::BOLD)
} else if *is_live {
Style::default().fg(THEME.logs.running_fg)
Style::default().fg(theme.success())
} else if show_selected {
let s = Style::default().fg(THEME.logs.selected_fg);
if THEME.logs.selected_bold {
s.add_modifier(Modifier::BOLD)
} else {
s
}
Style::default().fg(theme.accent()).add_modifier(Modifier::BOLD)
} else {
Style::default().fg(THEME.logs.text_fg)
Style::default().fg(theme.text())
};
let bg = if show_selected {
THEME.logs.selected_bg
} else if context.index % 2 == 0 {
Color::Reset
let bg = if context.index % 2 == 0 {
theme.background()
} else {
THEME.logs.row_alt_bg
theme.stripe()
};
let item = ratatui::text::Text::from(Line::from(Span::styled(name.clone(), style)))
let selector = if show_selected {
Span::styled("\u{258c} ", Style::default().fg(theme.accent()))
} else {
Span::raw(" ")
};
let item = ratatui::text::Text::from(Line::from(vec![selector, Span::styled(name.clone(), style)]))
.style(Style::default().bg(bg));
(item, 1)
});
@@ -460,7 +455,7 @@ fn render_list(
.begin_symbol(Some("\u{25b2}"))
.style(
Style::default()
.fg(THEME.logs.border_focused_fg)
.fg(theme.accent())
.add_modifier(Modifier::BOLD),
)
.thumb_symbol("\u{2551}")
@@ -478,6 +473,7 @@ fn render_viewer(
_is_focused: bool,
has_live: bool,
) {
let theme = THEME.as_ref();
let is_live = has_live && state.list_state.selected == Some(0);
let all_lines: Vec<String> = if is_live {
@@ -528,7 +524,7 @@ fn render_viewer(
.begin_symbol(Some("\u{25b2}"))
.style(
Style::default()
.fg(THEME.logs.border_focused_fg)
.fg(theme.accent())
.add_modifier(Modifier::BOLD),
)
.thumb_symbol("\u{2551}")
@@ -540,16 +536,15 @@ fn render_viewer(
}
fn line_level_style(line: &str) -> Style {
let theme = THEME.as_ref();
let upper = line.to_uppercase();
if upper.contains("ERROR") || upper.contains("FATAL") || upper.contains("[STDERR]") {
Style::default().fg(THEME.logs.error_fg)
Style::default().fg(theme.error())
} else if upper.contains("WARN") {
Style::default().fg(THEME.logs.warn_fg)
} else if upper.contains("DEBUG") {
Style::default().fg(THEME.logs.debug_fg)
} else if upper.contains("TRACE") {
Style::default().fg(THEME.logs.trace_fg)
Style::default().fg(theme.warning())
} else if upper.contains("DEBUG") || upper.contains("TRACE") {
Style::default().fg(theme.text_dim())
} else {
Style::default().fg(THEME.logs.text_fg)
Style::default().fg(theme.text())
}
}
+5 -5
View File
@@ -1,4 +1,4 @@
use crate::tui::theme::THEME;
use crate::config::theme::THEME;
use crossterm::event::KeyEvent;
use ratatui::{
style::Style,
@@ -7,16 +7,16 @@ use ratatui::{
pub mod account;
pub mod content;
pub mod content_list;
pub mod details;
pub mod logs_viewer;
pub mod popups;
pub mod profiles;
pub mod instances;
pub mod screenshots_grid;
pub mod search;
pub mod status;
pub fn styled_title(title: &str, highlight: bool) -> Line<'_> {
let theme = THEME.as_ref();
if !highlight || title.is_empty() {
Line::from(Span::raw(title))
} else {
@@ -24,8 +24,8 @@ pub fn styled_title(title: &str, highlight: bool) -> Line<'_> {
let first = chars.next().unwrap_or_default().to_string();
let rest: String = chars.collect();
Line::from(vec![
Span::styled(first, Style::default().fg(THEME.general.accent)),
Span::raw(rest),
Span::styled(first, Style::default().fg(theme.accent())),
Span::styled(rest, Style::default().fg(theme.text())),
])
}
}
+2 -2
View File
@@ -6,7 +6,7 @@ use ratatui::{
widgets::{Block, Clear, Widget},
};
use crate::tui::theme::THEME;
use crate::config::theme::BORDER_STYLE;
type ContentFn<'a> = Box<dyn Fn(Rect, &mut Buffer) + 'a>;
@@ -29,7 +29,7 @@ impl<'a> Widget for PopupFrame<'a> {
let mut block = Block::bordered()
.title_top(self.title)
.border_type(THEME.general.border_type.to_border_type())
.border_type(BORDER_STYLE.to_border_type())
.border_style(Style::default().fg(self.border_color));
if let Some(sl) = self.search_line {
+12 -8
View File
@@ -1,4 +1,4 @@
use once_cell::sync::Lazy;
use std::sync::LazyLock;
use std::sync::Mutex;
use ratatui::{
@@ -9,9 +9,9 @@ use ratatui::{
widgets::{Paragraph, Widget},
};
use crate::tui::theme::THEME;
use crate::config::theme::THEME;
static CONFIRM_STATE: Lazy<Mutex<ConfirmState>> = Lazy::new(|| Mutex::new(ConfirmState::default()));
static CONFIRM_STATE: LazyLock<Mutex<ConfirmState>> = LazyLock::new(|| Mutex::new(ConfirmState::default()));
#[derive(Debug, Default)]
struct ConfirmState {
@@ -63,23 +63,27 @@ impl Widget for ConfirmPopup {
fn render(self, area: Rect, buf: &mut Buffer) {
use super::{base::PopupFrame, keybind_line};
let theme = THEME.as_ref();
let title = Line::from(vec![Span::styled(
format!(" Delete '{}' ", self.instance_name),
Style::default()
.fg(THEME.popup_confirm.border_fg)
.fg(theme.text_dim())
.add_modifier(Modifier::BOLD),
)]);
let kb = keybind_line(&[("Enter", " confirm")]);
let border_color = theme.text_dim();
let bg_color = theme.surface();
let text_color = theme.text();
let popup = PopupFrame {
title,
border_color: THEME.popup_confirm.border_fg,
bg: Some(THEME.popup_confirm.highlight_bg),
border_color,
bg: Some(bg_color),
keybinds: Some(kb),
search_line: None,
content: Box::new(|inner, buf| {
content: Box::new(move |inner, buf| {
Paragraph::new("This will permanently remove the instance")
.style(Style::default().fg(THEME.popup_confirm.text_fg))
.style(Style::default().fg(text_color))
.render(inner, buf);
}),
};
+10 -7
View File
@@ -10,7 +10,7 @@ use tracing::Level;
use super::base::PopupFrame;
use crate::config::SETTINGS;
use crate::tui::error_buffer::ErrorEvent;
use crate::tui::theme::THEME;
use crate::config::theme::THEME;
pub struct ErrorPopup {
pub event: ErrorEvent,
@@ -24,31 +24,34 @@ impl ErrorPopup {
impl Widget for ErrorPopup {
fn render(self, area: Rect, buf: &mut Buffer) {
let theme = THEME.as_ref();
let (border_color, label) = match self.event.level {
Level::ERROR => (THEME.popup_error.error_fg, "ERROR"),
Level::WARN => (THEME.popup_error.warn_fg, "WARN"),
_ => (THEME.popup_error.border_fg, "INFO"),
Level::ERROR => (theme.error(), "ERROR"),
Level::WARN => (theme.warning(), "WARN"),
_ => (theme.text_dim(), "INFO"),
};
let title = Line::from(vec![Span::styled(
format!(" {} ", label),
Style::default()
.fg(THEME.popup_error.badge_text_fg)
.fg(theme.text_bright())
.bg(border_color)
.add_modifier(Modifier::BOLD),
)]);
let message = self.event.message.clone();
let text_color = theme.text();
let bg_color = theme.surface();
let popup = PopupFrame {
title,
border_color,
bg: Some(THEME.popup_error.bg),
bg: Some(bg_color),
keybinds: None,
search_line: None,
content: Box::new(move |inner, buf| {
Paragraph::new(message.as_str())
.wrap(Wrap { trim: true })
.style(Style::default().fg(THEME.popup_error.text_fg))
.style(Style::default().fg(text_color))
.render(inner, buf);
}),
};
@@ -0,0 +1,5 @@
mod render;
mod state;
pub use render::{popup_rect, render};
pub use state::{handle_key, take_result, ImportResult, ImportStep, ImportWizardState};
@@ -0,0 +1,254 @@
use super::super::base::PopupFrame;
use super::super::new_instance::LoadState;
use super::state::{ImportStep, ImportWizardState, IMPORT_STATE};
use crate::tui::app::FocusedArea;
use crate::config::theme::THEME;
use ratatui::{
layout::{Constraint, Direction, Layout, Rect},
style::{Modifier, Style},
text::{Line, Span},
widgets::{List, ListItem, ListState, Paragraph, StatefulWidget, Widget, Wrap},
Frame,
};
pub fn render(frame: &mut Frame, area: Rect, _focused: FocusedArea) {
let snapshot = match IMPORT_STATE.lock() {
Ok(state) => state.clone(),
Err(e) => {
tracing::error!("Import state lock poisoned: {}", e);
ImportWizardState::default()
}
};
let keybinds = step_keybinds(&snapshot);
let search_line = if snapshot.step == ImportStep::Version {
snapshot.version_search.title_line()
} else {
None
};
let theme = THEME.as_ref();
let popup = PopupFrame {
title: wizard_title(&snapshot),
border_color: theme.text_dim(),
bg: Some(theme.surface()),
keybinds: Some(keybinds),
search_line,
content: Box::new(move |popup_area, buf| {
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Min(1)])
.split(popup_area);
match snapshot.step {
ImportStep::Input => render_input_step(&snapshot, chunks[0], buf),
ImportStep::Fetching => render_fetching_step(chunks[0], buf),
ImportStep::Version => render_version_step(&snapshot, chunks[0], buf),
ImportStep::Confirm => render_confirm_step(&snapshot, chunks[0], buf),
}
}),
};
frame.render_widget(popup, area);
}
pub fn popup_rect(frame_area: Rect) -> Rect {
let w = Constraint::Percentage(50);
let step = match IMPORT_STATE.lock() {
Ok(s) => s.step.clone(),
Err(_) => ImportStep::Input,
};
match step {
ImportStep::Input => {
let h = 8u16.min(frame_area.height.saturating_sub(4));
frame_area.centered(w, Constraint::Length(h))
}
ImportStep::Fetching => {
let h = 5u16.min(frame_area.height.saturating_sub(4));
frame_area.centered(w, Constraint::Length(h))
}
ImportStep::Version => {
let h = (frame_area.height * 2 / 3)
.max(10)
.min(frame_area.height.saturating_sub(4));
frame_area.centered(w, Constraint::Length(h))
}
ImportStep::Confirm => {
let h = 10u16.min(frame_area.height.saturating_sub(4));
frame_area.centered(w, Constraint::Length(h))
}
}
}
fn render_input_step(
state: &ImportWizardState,
area: Rect,
buf: &mut ratatui::buffer::Buffer,
) {
let theme = THEME.as_ref();
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(1),
Constraint::Length(1),
Constraint::Min(0),
])
.split(area);
let input_line = if state.input.is_empty() {
Line::from(vec![
Span::styled(
"URL, slug, or .mrpack path...",
Style::default().fg(theme.text_dim()),
),
Span::styled(
"\u{2588}",
Style::default()
.fg(theme.text_dim())
.add_modifier(Modifier::SLOW_BLINK),
),
])
} else {
Line::from(vec![
Span::styled(
state.input.clone(),
Style::default().fg(theme.text()),
),
Span::styled(
"\u{2588}",
Style::default()
.fg(theme.text_dim())
.add_modifier(Modifier::SLOW_BLINK),
),
])
};
Paragraph::new(input_line).render(chunks[0], buf);
}
fn render_fetching_step(area: Rect, buf: &mut ratatui::buffer::Buffer) {
let theme = THEME.as_ref();
Paragraph::new("Fetching modpack info...")
.style(Style::default().fg(theme.text_dim()))
.render(area, buf);
}
fn render_version_step(
state: &ImportWizardState,
area: Rect,
buf: &mut ratatui::buffer::Buffer,
) {
let theme = THEME.as_ref();
match &state.versions {
LoadState::Idle | LoadState::Loading => {
Paragraph::new("Loading versions...")
.style(Style::default().fg(theme.text_dim()))
.render(area, buf);
}
LoadState::Error(message) => {
Paragraph::new(message.as_str())
.wrap(Wrap { trim: true })
.style(Style::default().fg(theme.error()))
.render(area, buf);
}
LoadState::Loaded(_) => {
let items: Vec<ListItem> = super::state::visible_versions(state)
.into_iter()
.map(|version| {
let game_ver = version.game_versions.first().cloned().unwrap_or_default();
let loader = version.loaders.first().cloned().unwrap_or_default();
ListItem::new(Line::from(Span::styled(
format!("{} {} {}", version.version_number, game_ver, loader),
Style::default().fg(theme.text()),
)))
})
.collect();
let list = List::new(items)
.highlight_style(
Style::default()
.fg(theme.accent())
.add_modifier(Modifier::BOLD),
)
.highlight_symbol("\u{25b6} ");
let mut list_state = ListState::default().with_selected(Some(state.version_idx));
StatefulWidget::render(list, area, buf, &mut list_state);
}
}
}
fn render_confirm_step(
state: &ImportWizardState,
area: Rect,
buf: &mut ratatui::buffer::Buffer,
) {
let theme = THEME.as_ref();
let summary = match &state.summary {
Some(s) => s,
None => {
Paragraph::new("No summary available")
.style(Style::default().fg(theme.text_dim()))
.render(area, buf);
return;
}
};
let label_style = Style::default().fg(theme.text_dim());
let loader_display = if let Some(ref lv) = summary.loader_version {
format!("{} {}", summary.loader, lv)
} else {
summary.loader.to_string()
};
Paragraph::new(vec![
Line::from(vec![
Span::styled("Name: ", label_style),
Span::raw(summary.name.clone()),
]),
Line::from(vec![
Span::styled("Pack Version: ", label_style),
Span::raw(summary.pack_version.clone()),
]),
Line::from(vec![
Span::styled("MC Version: ", label_style),
Span::raw(summary.game_version.clone()),
]),
Line::from(vec![
Span::styled("Loader: ", label_style),
Span::raw(loader_display),
]),
Line::from(vec![
Span::styled("Mods: ", label_style),
Span::raw(format!("{} files", summary.mod_count)),
]),
Line::from(vec![
Span::styled("Overrides: ", label_style),
Span::raw(format!("{} files", summary.override_count)),
]),
])
.style(Style::default().fg(theme.text()))
.wrap(Wrap { trim: true })
.render(area, buf);
}
fn wizard_title(_state: &ImportWizardState) -> Line<'static> {
use crate::tui::widgets::styled_title;
styled_title("Import Modpack", false)
}
fn step_keybinds(state: &ImportWizardState) -> Line<'static> {
use super::super::keybind_line;
match state.step {
ImportStep::Input => keybind_line(&[("Enter", " fetch")]),
ImportStep::Fetching => keybind_line(&[("Esc", " cancel")]),
ImportStep::Version => keybind_line(&[
("/", " search"),
("h", " back"),
("Enter", " select"),
]),
ImportStep::Confirm => keybind_line(&[("h", " back"), ("Enter", " import")]),
}
}
@@ -1,28 +1,18 @@
use super::base::PopupFrame;
use super::new_instance::LoadState;
use super::super::new_instance::LoadState;
use crate::instance::import::ImportSummary;
use crate::net::modrinth::{self, ModrinthInput, VersionInfo};
use crate::tui::layout::FocusedArea;
use crate::tui::theme::THEME;
use crate::tui::widgets::profiles;
use crate::tui::widgets::instances;
use crate::tui::widgets::search::SearchState;
use crossterm::event::{KeyCode, KeyEvent};
use once_cell::sync::Lazy;
use ratatui::{
layout::{Constraint, Direction, Layout, Rect},
style::{Modifier, Style},
text::{Line, Span},
widgets::{List, ListItem, ListState, Paragraph, StatefulWidget, Widget, Wrap},
Frame,
};
use std::sync::LazyLock;
use std::sync::{Arc, Mutex};
use std::time::Instant;
use tracing::Level;
static IMPORT_STATE: Lazy<Arc<Mutex<ImportWizardState>>> =
Lazy::new(|| Arc::new(Mutex::new(ImportWizardState::default())));
static IMPORT_RESULT: Lazy<Arc<Mutex<Option<ImportResult>>>> =
Lazy::new(|| Arc::new(Mutex::new(None)));
pub(super) static IMPORT_STATE: LazyLock<Arc<Mutex<ImportWizardState>>> =
LazyLock::new(|| Arc::new(Mutex::new(ImportWizardState::default())));
pub(super) static IMPORT_RESULT: LazyLock<Arc<Mutex<Option<ImportResult>>>> =
LazyLock::new(|| Arc::new(Mutex::new(None)));
#[derive(Debug, Clone)]
pub struct ImportResult {
@@ -69,91 +59,21 @@ impl ImportWizardState {
}
}
pub fn render(frame: &mut Frame, area: Rect, _focused: FocusedArea) {
let snapshot = match IMPORT_STATE.lock() {
Ok(state) => state.clone(),
Err(e) => {
tracing::error!("Import state lock poisoned: {}", e);
ImportWizardState::default()
}
};
let keybinds = step_keybinds(&snapshot);
let search_line = if snapshot.step == ImportStep::Version {
snapshot.version_search.title_line()
} else {
None
};
let popup = PopupFrame {
title: wizard_title(&snapshot),
border_color: THEME.popup_import.border_fg,
bg: Some(THEME.popup_import.bg),
keybinds: Some(keybinds),
search_line,
content: Box::new(move |popup_area, buf| {
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Min(1)])
.split(popup_area);
match snapshot.step {
ImportStep::Input => render_input_step(&snapshot, chunks[0], buf),
ImportStep::Fetching => render_fetching_step(chunks[0], buf),
ImportStep::Version => render_version_step(&snapshot, chunks[0], buf),
ImportStep::Confirm => render_confirm_step(&snapshot, chunks[0], buf),
}
}),
};
frame.render_widget(popup, area);
}
pub fn popup_rect(frame_area: Rect) -> Rect {
let w = Constraint::Percentage(50);
let step = match IMPORT_STATE.lock() {
Ok(s) => s.step.clone(),
Err(_) => ImportStep::Input,
};
match step {
ImportStep::Input => {
let h = 8u16.min(frame_area.height.saturating_sub(4));
frame_area.centered(w, Constraint::Length(h))
}
ImportStep::Fetching => {
let h = 5u16.min(frame_area.height.saturating_sub(4));
frame_area.centered(w, Constraint::Length(h))
}
ImportStep::Version => {
let h = (frame_area.height * 2 / 3)
.max(10)
.min(frame_area.height.saturating_sub(4));
frame_area.centered(w, Constraint::Length(h))
}
ImportStep::Confirm => {
let h = 10u16.min(frame_area.height.saturating_sub(4));
frame_area.centered(w, Constraint::Length(h))
}
}
}
pub fn handle_key(key_event: &KeyEvent, profiles_state: &mut profiles::State) {
pub fn handle_key(key_event: &KeyEvent, instances_state: &mut instances::State) {
let mut state = match IMPORT_STATE.lock() {
Ok(state) => state,
Err(e) => {
tracing::error!("Import state lock poisoned: {}", e);
profiles_state.show_import_popup = false;
instances_state.show_import_popup = false;
return;
}
};
match state.step {
ImportStep::Input => handle_input_key(&mut state, key_event, profiles_state),
ImportStep::Fetching => handle_fetching_key(&mut state, key_event, profiles_state),
ImportStep::Version => handle_version_key(&mut state, key_event, profiles_state),
ImportStep::Confirm => handle_confirm_key(&mut state, key_event, profiles_state),
ImportStep::Input => handle_input_key(&mut state, key_event, instances_state),
ImportStep::Fetching => handle_fetching_key(&mut state, key_event, instances_state),
ImportStep::Version => handle_version_key(&mut state, key_event, instances_state),
ImportStep::Confirm => handle_confirm_key(&mut state, key_event, instances_state),
}
}
@@ -167,10 +87,10 @@ pub fn take_result() -> Option<ImportResult> {
fn handle_input_key(
state: &mut ImportWizardState,
key_event: &KeyEvent,
profiles_state: &mut profiles::State,
instances_state: &mut instances::State,
) {
match key_event.code {
KeyCode::Esc => close_popup(state, profiles_state),
KeyCode::Esc => close_popup(state, instances_state),
KeyCode::Backspace => {
state.input.pop();
}
@@ -190,17 +110,17 @@ fn handle_input_key(
fn handle_fetching_key(
state: &mut ImportWizardState,
key_event: &KeyEvent,
profiles_state: &mut profiles::State,
instances_state: &mut instances::State,
) {
if key_event.code == KeyCode::Esc {
close_popup(state, profiles_state);
close_popup(state, instances_state);
}
}
fn handle_version_key(
state: &mut ImportWizardState,
key_event: &KeyEvent,
profiles_state: &mut profiles::State,
instances_state: &mut instances::State,
) {
if state.version_search.active {
match key_event.code {
@@ -232,7 +152,7 @@ fn handle_version_key(
let visible_count = visible_versions(state).len();
match key_event.code {
KeyCode::Esc => close_popup(state, profiles_state),
KeyCode::Esc => close_popup(state, instances_state),
KeyCode::Left | KeyCode::Char('h') if !state.version_search.active => {
state.step = ImportStep::Input;
state.versions = LoadState::Idle;
@@ -265,10 +185,10 @@ fn handle_version_key(
fn handle_confirm_key(
state: &mut ImportWizardState,
key_event: &KeyEvent,
profiles_state: &mut profiles::State,
instances_state: &mut instances::State,
) {
match key_event.code {
KeyCode::Esc => close_popup(state, profiles_state),
KeyCode::Esc => close_popup(state, instances_state),
KeyCode::Left | KeyCode::Char('h') => {
if matches!(state.versions, LoadState::Loaded(_)) {
state.step = ImportStep::Version;
@@ -291,7 +211,7 @@ fn handle_confirm_key(
}
}
close_popup(state, profiles_state);
close_popup(state, instances_state);
}
_ => {}
}
@@ -418,14 +338,7 @@ async fn resolve_version_id(
}
fn resolve_local_file(state_arc: Arc<Mutex<ImportWizardState>>, path: &str) {
let resolved = if let Some(stripped) = path.strip_prefix("~/") {
match dirs_next::home_dir() {
Some(home) => home.join(stripped),
None => std::path::PathBuf::from(path),
}
} else {
std::path::PathBuf::from(path)
};
let resolved = crate::config::settings::resolve_path(path);
match modrinth::parse_mrpack(&resolved) {
Ok(index) => {
@@ -506,157 +419,9 @@ fn start_version_download(state: &mut ImportWizardState) {
});
}
fn render_input_step(
state: &ImportWizardState,
area: Rect,
buf: &mut ratatui::buffer::Buffer,
) {
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(1),
Constraint::Length(1),
Constraint::Min(0),
])
.split(area);
let input_line = if state.input.is_empty() {
Line::from(vec![
Span::styled(
"URL, slug, or .mrpack path...",
Style::default().fg(THEME.popup_import.field_inactive_border_fg),
),
Span::styled(
"\u{2588}",
Style::default()
.fg(THEME.popup_import.border_fg)
.add_modifier(Modifier::SLOW_BLINK),
),
])
} else {
Line::from(vec![
Span::styled(
state.input.clone(),
Style::default().fg(THEME.popup_import.text_fg),
),
Span::styled(
"\u{2588}",
Style::default()
.fg(THEME.popup_import.border_fg)
.add_modifier(Modifier::SLOW_BLINK),
),
])
};
Paragraph::new(input_line).render(chunks[0], buf);
}
fn render_fetching_step(area: Rect, buf: &mut ratatui::buffer::Buffer) {
Paragraph::new("Fetching modpack info...")
.style(Style::default().fg(THEME.popup_import.field_inactive_border_fg))
.render(area, buf);
}
fn render_version_step(
state: &ImportWizardState,
area: Rect,
buf: &mut ratatui::buffer::Buffer,
) {
match &state.versions {
LoadState::Idle | LoadState::Loading => {
Paragraph::new("Loading versions...")
.style(Style::default().fg(THEME.popup_import.field_inactive_border_fg))
.render(area, buf);
}
LoadState::Error(message) => {
Paragraph::new(message.as_str())
.wrap(Wrap { trim: true })
.style(Style::default().fg(THEME.general.error))
.render(area, buf);
}
LoadState::Loaded(_) => {
let items: Vec<ListItem> = visible_versions(state)
.into_iter()
.map(|version| {
let game_ver = version.game_versions.first().cloned().unwrap_or_default();
let loader = version.loaders.first().cloned().unwrap_or_default();
ListItem::new(Line::from(Span::styled(
format!("{} {} {}", version.version_number, game_ver, loader),
Style::default().fg(THEME.popup_import.text_fg),
)))
})
.collect();
let list = List::new(items)
.highlight_style(
Style::default()
.fg(THEME.popup_import.accent_fg)
.add_modifier(Modifier::BOLD),
)
.highlight_symbol("\u{25b6} ");
let mut list_state = ListState::default().with_selected(Some(state.version_idx));
StatefulWidget::render(list, area, buf, &mut list_state);
}
}
}
fn render_confirm_step(
state: &ImportWizardState,
area: Rect,
buf: &mut ratatui::buffer::Buffer,
) {
let summary = match &state.summary {
Some(s) => s,
None => {
Paragraph::new("No summary available")
.style(Style::default().fg(THEME.popup_import.field_inactive_border_fg))
.render(area, buf);
return;
}
};
let label_style = Style::default().fg(THEME.popup_import.border_fg);
let loader_display = if let Some(ref lv) = summary.loader_version {
format!("{} {}", summary.loader, lv)
} else {
summary.loader.to_string()
};
Paragraph::new(vec![
Line::from(vec![
Span::styled("Name: ", label_style),
Span::raw(summary.name.clone()),
]),
Line::from(vec![
Span::styled("Pack Version: ", label_style),
Span::raw(summary.pack_version.clone()),
]),
Line::from(vec![
Span::styled("MC Version: ", label_style),
Span::raw(summary.game_version.clone()),
]),
Line::from(vec![
Span::styled("Loader: ", label_style),
Span::raw(loader_display),
]),
Line::from(vec![
Span::styled("Mods: ", label_style),
Span::raw(format!("{} files", summary.mod_count)),
]),
Line::from(vec![
Span::styled("Overrides: ", label_style),
Span::raw(format!("{} files", summary.override_count)),
]),
])
.style(Style::default().fg(THEME.popup_import.text_fg))
.wrap(Wrap { trim: true })
.render(area, buf);
}
fn close_popup(state: &mut ImportWizardState, profiles_state: &mut profiles::State) {
fn close_popup(state: &mut ImportWizardState, instances_state: &mut instances::State) {
state.reset();
profiles_state.show_import_popup = false;
instances_state.show_import_popup = false;
}
fn push_import_error(msg: String) {
@@ -668,35 +433,7 @@ fn push_import_error(msg: String) {
});
}
fn wizard_title(_state: &ImportWizardState) -> Line<'static> {
use crate::tui::widgets::styled_title;
styled_title("Import Modpack", false)
}
fn step_keybinds(state: &ImportWizardState) -> Line<'static> {
use super::keybind_line;
match state.step {
ImportStep::Input => keybind_line(&[("Enter", " fetch")]),
ImportStep::Fetching => keybind_line(&[("Esc", " cancel")]),
ImportStep::Version => keybind_line(&[
("/", " search"),
("h", " back"),
("Enter", " select"),
]),
ImportStep::Confirm => keybind_line(&[("h", " back"), ("Enter", " import")]),
}
}
fn selected_version(state: &ImportWizardState) -> Option<&VersionInfo> {
if let LoadState::Loaded(ref versions) = state.versions {
let visible: Vec<_> = visible_versions_ref(versions, &state.version_search);
visible.get(state.version_idx).copied()
} else {
None
}
}
fn visible_versions(state: &ImportWizardState) -> Vec<VersionInfo> {
pub(super) fn visible_versions(state: &ImportWizardState) -> Vec<VersionInfo> {
match &state.versions {
LoadState::Loaded(versions) => {
let q = state.version_search.query.to_lowercase();
@@ -729,6 +466,15 @@ fn visible_versions_ref<'a>(
.collect()
}
fn selected_version(state: &ImportWizardState) -> Option<&VersionInfo> {
if let LoadState::Loaded(ref versions) = state.versions {
let visible: Vec<_> = visible_versions_ref(versions, &state.version_search);
visible.get(state.version_idx).copied()
} else {
None
}
}
fn clamp_version_index(state: &mut ImportWizardState) {
let count = visible_versions(state).len();
if count == 0 {
+12 -18
View File
@@ -56,26 +56,23 @@ pub fn top_right_rect(frame: Rect, inner_w: usize, inner_h: usize) -> Rect {
}
pub fn keybind_line(binds: &[(&str, &str)]) -> ratatui::text::Line<'static> {
use crate::tui::theme::THEME;
use crate::config::theme::THEME;
use ratatui::{
style::{Modifier, Style},
text::{Line, Span},
};
let mut key_style = Style::default().fg(THEME.popup.keybind_active_fg);
if THEME.popup.keybind_active_bold {
key_style = key_style.add_modifier(Modifier::BOLD);
}
let dim_style = Style::default().fg(THEME.popup.keybind_inactive_fg);
let theme = THEME.as_ref();
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();
for (i, (key, label)) in binds.iter().enumerate() {
if i > 0 {
spans.push(Span::styled(" ", dim_style));
spans.push(Span::styled(" ", label_style));
}
spans.push(Span::styled(format!("[{}]", key), key_style));
if !label.is_empty() {
spans.push(Span::styled(label.to_string(), dim_style));
spans.push(Span::styled(label.to_string(), label_style));
}
}
Line::from(spans)
@@ -85,17 +82,14 @@ pub fn keybind_lines_wrapped(
binds: &[(&str, &str)],
max_width: u16,
) -> Vec<ratatui::text::Line<'static>> {
use crate::tui::theme::THEME;
use crate::config::theme::THEME;
use ratatui::{
style::{Modifier, Style},
text::{Line, Span},
};
let mut key_style = Style::default().fg(THEME.popup.keybind_active_fg);
if THEME.popup.keybind_active_bold {
key_style = key_style.add_modifier(Modifier::BOLD);
}
let dim_style = Style::default().fg(THEME.popup.keybind_inactive_fg);
let theme = THEME.as_ref();
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();
let mut current_spans: Vec<Span<'static>> = Vec::new();
@@ -117,13 +111,13 @@ pub fn keybind_lines_wrapped(
}
if !current_spans.is_empty() {
current_spans.push(Span::styled(" ", dim_style));
current_spans.push(Span::styled(" ", label_style));
current_width += 2;
}
current_spans.push(Span::styled(format!("[{}]", key), key_style));
if !label.is_empty() {
current_spans.push(Span::styled(label.to_string(), dim_style));
current_spans.push(Span::styled(label.to_string(), label_style));
}
current_width += item_w;
}
@@ -0,0 +1,5 @@
mod render;
mod state;
pub use render::{popup_rect, render};
pub use state::{handle_key, take_result, LoadState, WizardParams, WizardStep, WizardState};
@@ -0,0 +1,321 @@
use super::state::{
clamp_loader_version_index, clamp_version_index, ensure_loader_versions_loaded,
ensure_versions_loaded, visible_versions, LoadState, WizardState, WizardStep, WIZARD_STATE,
};
use crate::instance::models::ModLoader;
use crate::tui::app::FocusedArea;
use crate::config::theme::THEME;
use crate::tui::widgets::popups::base::PopupFrame;
use tui_prompts::State as PromptState;
use ratatui::{
layout::{Constraint, Direction, Layout, Rect},
style::{Modifier, Style},
text::{Line, Span},
widgets::{List, ListItem, ListState, Paragraph, StatefulWidget, Widget, Wrap},
Frame,
};
pub fn render(frame: &mut Frame, area: Rect, _focused: FocusedArea) {
let snapshot = match WIZARD_STATE.lock() {
Ok(mut state) => {
if state.step == WizardStep::Version {
ensure_versions_loaded(&mut state);
clamp_version_index(&mut state);
}
if state.step == WizardStep::LoaderVersion {
if state.selected_loader() == ModLoader::Vanilla {
state.step = WizardStep::Confirm;
} else {
clamp_loader_version_index(&mut state);
let game_version = state.selected_version().map(|v| v.id.clone());
let loader = state.selected_loader();
if let Some(game_version) = game_version {
ensure_loader_versions_loaded(&mut state, loader, game_version);
}
}
}
state.clone()
}
Err(e) => {
tracing::error!("Wizard state lock poisoned: {}", e);
WizardState::default()
}
};
let keybinds = step_keybinds(&snapshot);
let search_line = snapshot.version_search.title_line();
let theme = THEME.as_ref();
let popup = PopupFrame {
title: wizard_title(&snapshot),
border_color: theme.text_dim(),
bg: Some(theme.surface()),
keybinds: Some(keybinds),
search_line,
content: Box::new(move |popup_area, buf| {
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Min(1)])
.split(popup_area);
match snapshot.step {
WizardStep::Name => render_name_step(&snapshot, chunks[0], buf),
WizardStep::Version => render_version_step(&snapshot, chunks[0], buf),
WizardStep::Loader => render_loader_step(&snapshot, chunks[0], buf),
WizardStep::LoaderVersion => render_loader_version_step(&snapshot, chunks[0], buf),
WizardStep::Confirm => render_confirm_step(&snapshot, chunks[0], buf),
}
}),
};
frame.render_widget(popup, area);
}
pub fn popup_rect(frame_area: Rect) -> Rect {
use ratatui::layout::Constraint;
let step = match WIZARD_STATE.lock() {
Ok(s) => s.step.clone(),
Err(_) => WizardStep::Name,
};
let w = Constraint::Percentage(50);
match step {
WizardStep::Name => {
let h = 6u16.min(frame_area.height.saturating_sub(4));
frame_area.centered(w, Constraint::Length(h))
}
WizardStep::Version | WizardStep::LoaderVersion => {
let h = (frame_area.height * 2 / 3)
.max(10)
.min(frame_area.height.saturating_sub(4));
frame_area.centered(w, Constraint::Length(h))
}
WizardStep::Loader => {
let h = 9u16.min(frame_area.height.saturating_sub(4));
frame_area.centered(w, Constraint::Length(h))
}
WizardStep::Confirm => {
let h = 8u16.min(frame_area.height.saturating_sub(4));
frame_area.centered(w, Constraint::Length(h))
}
}
}
fn wizard_title(_state: &WizardState) -> Line<'static> {
use crate::tui::widgets::styled_title;
styled_title("New Instance", false)
}
fn step_keybinds(state: &WizardState) -> ratatui::text::Line<'static> {
use crate::tui::widgets::popups::keybind_line;
match state.step {
WizardStep::Name => keybind_line(&[("Enter", " continue")]),
WizardStep::Loader => keybind_line(&[("h", " back"), ("Enter", " select")]),
WizardStep::Version => keybind_line(&[
("/", " search"),
("s", " snap"),
("h", " back"),
("Enter", " select"),
]),
WizardStep::LoaderVersion => keybind_line(&[("h", " back"), ("Enter", " select")]),
WizardStep::Confirm => keybind_line(&[("h", " back"), ("Enter", " create")]),
}
}
fn render_name_step(state: &WizardState, area: Rect, buf: &mut ratatui::buffer::Buffer) {
let theme = THEME.as_ref();
let value = state.name_state.value();
let line = if value.is_empty() {
Line::from(vec![
Span::styled(
"Instance name...",
Style::default().fg(theme.text_dim()),
),
Span::styled(
"\u{2588}",
Style::default()
.fg(theme.text_dim())
.add_modifier(Modifier::SLOW_BLINK),
),
])
} else {
Line::from(vec![
Span::styled(value, Style::default().fg(theme.text())),
Span::styled(
"\u{2588}",
Style::default()
.fg(theme.text_dim())
.add_modifier(Modifier::SLOW_BLINK),
),
])
};
Paragraph::new(line).render(area, buf);
}
fn render_version_step(state: &WizardState, area: Rect, buf: &mut ratatui::buffer::Buffer) {
let theme = THEME.as_ref();
match &state.versions {
LoadState::Idle | LoadState::Loading => {
Paragraph::new("Loading versions...")
.style(Style::default().fg(theme.text_dim()))
.render(area, buf);
}
LoadState::Error(message) => {
Paragraph::new(message.as_str())
.wrap(Wrap { trim: true })
.style(Style::default().fg(theme.error()))
.render(area, buf);
}
LoadState::Loaded(_) => {
let items: Vec<ListItem> = visible_versions(state)
.into_iter()
.map(|version| {
let suffix = if version.stable {
String::new()
} else {
" (snapshot)".to_string()
};
ListItem::new(Line::from(Span::styled(
format!("{}{}", version.id, suffix),
Style::default().fg(theme.text()),
)))
})
.collect();
let list = List::new(items)
.highlight_style(
Style::default()
.fg(theme.accent())
.add_modifier(Modifier::BOLD),
)
.highlight_symbol("▶ ");
let mut list_state = ListState::default().with_selected(Some(state.version_idx));
StatefulWidget::render(list, area, buf, &mut list_state);
}
}
}
fn render_loader_step(state: &WizardState, area: Rect, buf: &mut ratatui::buffer::Buffer) {
let theme = THEME.as_ref();
let loaders = [
ModLoader::Vanilla,
ModLoader::Fabric,
ModLoader::Forge,
ModLoader::NeoForge,
ModLoader::Quilt,
];
let items: Vec<ListItem> = loaders
.into_iter()
.map(|loader| {
ListItem::new(Line::from(Span::styled(
loader.to_string(),
Style::default().fg(theme.text()),
)))
})
.collect();
let list = List::new(items)
.highlight_style(
Style::default()
.fg(theme.accent())
.add_modifier(Modifier::BOLD),
)
.highlight_symbol("▶ ");
let mut list_state = ListState::default().with_selected(Some(state.loader_idx));
StatefulWidget::render(list, area, buf, &mut list_state);
}
fn render_loader_version_step(state: &WizardState, area: Rect, buf: &mut ratatui::buffer::Buffer) {
let theme = THEME.as_ref();
if state.selected_loader() == ModLoader::Vanilla {
Paragraph::new("Vanilla has no loader version.")
.style(Style::default().fg(theme.text_dim()))
.render(area, buf);
return;
}
match &state.loader_versions {
LoadState::Idle | LoadState::Loading => {
Paragraph::new(format!("Loading {} versions...", state.selected_loader()))
.style(Style::default().fg(theme.text_dim()))
.render(area, buf);
}
LoadState::Error(message) => {
Paragraph::new(message.as_str())
.wrap(Wrap { trim: true })
.style(Style::default().fg(theme.error()))
.render(area, buf);
}
LoadState::Loaded(versions) => {
let items: Vec<ListItem> = versions
.iter()
.map(|version| {
ListItem::new(Line::from(Span::styled(
version.clone(),
Style::default().fg(theme.text()),
)))
})
.collect();
let list = List::new(items)
.highlight_style(
Style::default()
.fg(theme.accent())
.add_modifier(Modifier::BOLD),
)
.highlight_symbol("▶ ");
let mut list_state = ListState::default().with_selected(Some(state.loader_version_idx));
StatefulWidget::render(list, area, buf, &mut list_state);
}
}
}
fn render_confirm_step(state: &WizardState, area: Rect, buf: &mut ratatui::buffer::Buffer) {
let theme = THEME.as_ref();
let game_version = state
.selected_version()
.map(|version| version.id.as_str())
.unwrap_or("<not selected>");
let loader = state.selected_loader();
let loader_version = if loader == ModLoader::Vanilla {
"n/a".to_string()
} else {
state
.selected_loader_version()
.unwrap_or_else(|| "<not selected>".to_string())
};
let label_style = Style::default().fg(theme.text_dim());
Paragraph::new(vec![
Line::from(vec![
Span::styled("Name: ", label_style),
Span::raw(state.name_state.value()),
]),
Line::from(vec![
Span::styled("MC: ", label_style),
Span::raw(game_version),
]),
Line::from(vec![
Span::styled("Loader: ", label_style),
Span::raw(loader.to_string()),
]),
Line::from(vec![
Span::styled("Loader version: ", label_style),
Span::raw(loader_version),
]),
])
.style(Style::default().fg(theme.text()))
.wrap(Wrap { trim: true })
.render(area, buf);
}
@@ -1,27 +1,17 @@
use super::base::PopupFrame;
use crate::instance::{
loader::{get_installer, GameVersion},
models::ModLoader,
};
use crate::tui::layout::FocusedArea;
use crate::tui::theme::THEME;
use crate::tui::widgets::profiles;
use crate::tui::widgets::instances;
use crossterm::event::{KeyCode, KeyEvent};
use once_cell::sync::Lazy;
use ratatui::{
layout::{Constraint, Direction, Layout, Rect},
style::{Modifier, Style},
text::{Line, Span},
widgets::{List, ListItem, ListState, Paragraph, StatefulWidget, Widget, Wrap},
Frame,
};
use std::sync::LazyLock;
use std::sync::{Arc, Mutex};
use tui_prompts::{FocusState, State as PromptState, TextState};
static WIZARD_STATE: Lazy<Arc<Mutex<WizardState>>> =
Lazy::new(|| Arc::new(Mutex::new(WizardState::default())));
static WIZARD_RESULT: Lazy<Arc<Mutex<Option<WizardParams>>>> =
Lazy::new(|| Arc::new(Mutex::new(None)));
pub(crate) static WIZARD_STATE: LazyLock<Arc<Mutex<WizardState>>> =
LazyLock::new(|| Arc::new(Mutex::new(WizardState::default())));
pub(crate) static WIZARD_RESULT: LazyLock<Arc<Mutex<Option<WizardParams>>>> =
LazyLock::new(|| Arc::new(Mutex::new(None)));
#[derive(Debug, Clone)]
pub struct WizardParams {
@@ -51,7 +41,6 @@ pub enum LoadState<T> {
Error(String),
}
#[derive(Debug, Clone)]
pub struct WizardState {
pub step: WizardStep,
@@ -118,82 +107,24 @@ impl WizardState {
}
}
pub fn render(frame: &mut Frame, area: Rect, _focused: FocusedArea) {
let snapshot = match WIZARD_STATE.lock() {
Ok(mut state) => {
if state.step == WizardStep::Version {
ensure_versions_loaded(&mut state);
clamp_version_index(&mut state);
}
if state.step == WizardStep::LoaderVersion {
if state.selected_loader() == ModLoader::Vanilla {
state.step = WizardStep::Confirm;
} else {
clamp_loader_version_index(&mut state);
let game_version = state.selected_version().map(|v| v.id.clone());
let loader = state.selected_loader();
if let Some(game_version) = game_version {
ensure_loader_versions_loaded(&mut state, loader, game_version);
}
}
}
state.clone()
}
Err(e) => {
tracing::error!("Wizard state lock poisoned: {}", e);
WizardState::default()
}
};
let keybinds = step_keybinds(&snapshot);
let search_line = snapshot.version_search.title_line();
let popup = PopupFrame {
title: wizard_title(&snapshot),
border_color: THEME.popup_new_instance.border_fg,
bg: Some(THEME.popup_new_instance.bg),
keybinds: Some(keybinds),
search_line,
content: Box::new(move |popup_area, buf| {
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Min(1)])
.split(popup_area);
match snapshot.step {
WizardStep::Name => render_name_step(&snapshot, chunks[0], buf),
WizardStep::Version => render_version_step(&snapshot, chunks[0], buf),
WizardStep::Loader => render_loader_step(&snapshot, chunks[0], buf),
WizardStep::LoaderVersion => render_loader_version_step(&snapshot, chunks[0], buf),
WizardStep::Confirm => render_confirm_step(&snapshot, chunks[0], buf),
}
}),
};
frame.render_widget(popup, area);
}
pub fn handle_key(key_event: &KeyEvent, profiles_state: &mut profiles::State) {
pub fn handle_key(key_event: &KeyEvent, instances_state: &mut instances::State) {
let mut state = match WIZARD_STATE.lock() {
Ok(state) => state,
Err(e) => {
tracing::error!("Wizard state lock poisoned: {}", e);
profiles_state.show_popup = false;
instances_state.show_popup = false;
return;
}
};
match state.step {
WizardStep::Name => handle_name_key(&mut state, key_event, profiles_state),
WizardStep::Version => handle_version_key(&mut state, key_event, profiles_state),
WizardStep::Loader => handle_loader_key(&mut state, key_event, profiles_state),
WizardStep::Name => handle_name_key(&mut state, key_event, instances_state),
WizardStep::Version => handle_version_key(&mut state, key_event, instances_state),
WizardStep::Loader => handle_loader_key(&mut state, key_event, instances_state),
WizardStep::LoaderVersion => {
handle_loader_version_key(&mut state, key_event, profiles_state)
handle_loader_version_key(&mut state, key_event, instances_state)
}
WizardStep::Confirm => handle_confirm_key(&mut state, key_event, profiles_state),
WizardStep::Confirm => handle_confirm_key(&mut state, key_event, instances_state),
}
}
@@ -204,46 +135,14 @@ pub fn take_result() -> Option<WizardParams> {
}
}
pub fn popup_rect(frame_area: Rect) -> Rect {
use ratatui::layout::Constraint;
let step = match WIZARD_STATE.lock() {
Ok(s) => s.step.clone(),
Err(_) => WizardStep::Name,
};
let w = Constraint::Percentage(50);
match step {
WizardStep::Name => {
let h = 6u16.min(frame_area.height.saturating_sub(4));
frame_area.centered(w, Constraint::Length(h))
}
WizardStep::Version | WizardStep::LoaderVersion => {
let h = (frame_area.height * 2 / 3)
.max(10)
.min(frame_area.height.saturating_sub(4));
frame_area.centered(w, Constraint::Length(h))
}
WizardStep::Loader => {
let h = 9u16.min(frame_area.height.saturating_sub(4));
frame_area.centered(w, Constraint::Length(h))
}
WizardStep::Confirm => {
let h = 8u16.min(frame_area.height.saturating_sub(4));
frame_area.centered(w, Constraint::Length(h))
}
}
}
fn handle_name_key(
state: &mut WizardState,
key_event: &KeyEvent,
profiles_state: &mut profiles::State,
instances_state: &mut instances::State,
) {
match key_event.code {
KeyCode::Esc => {
close_popup(state, profiles_state);
close_popup(state, instances_state);
}
KeyCode::Enter => {
if state.name_state.value().trim().is_empty() {
@@ -260,7 +159,7 @@ fn handle_name_key(
fn handle_version_key(
state: &mut WizardState,
key_event: &KeyEvent,
profiles_state: &mut profiles::State,
instances_state: &mut instances::State,
) {
// Search mode: route char input to search query
if state.version_search.active {
@@ -294,7 +193,7 @@ fn handle_version_key(
match key_event.code {
KeyCode::Esc => {
close_popup(state, profiles_state);
close_popup(state, instances_state);
}
KeyCode::Left | KeyCode::Char('h') if !state.version_search.active => {
state.step = WizardStep::Loader;
@@ -342,10 +241,10 @@ fn handle_version_key(
fn handle_loader_key(
state: &mut WizardState,
key_event: &KeyEvent,
profiles_state: &mut profiles::State,
instances_state: &mut instances::State,
) {
match key_event.code {
KeyCode::Esc => close_popup(state, profiles_state),
KeyCode::Esc => close_popup(state, instances_state),
KeyCode::Left | KeyCode::Char('h') => state.step = WizardStep::Name,
KeyCode::Char('j') | KeyCode::Down => {
state.loader_idx = (state.loader_idx + 1).min(4);
@@ -368,7 +267,7 @@ fn handle_loader_key(
fn handle_loader_version_key(
state: &mut WizardState,
key_event: &KeyEvent,
profiles_state: &mut profiles::State,
instances_state: &mut instances::State,
) {
if state.selected_loader() == ModLoader::Vanilla {
state.step = WizardStep::Confirm;
@@ -381,7 +280,7 @@ fn handle_loader_version_key(
};
match key_event.code {
KeyCode::Esc => close_popup(state, profiles_state),
KeyCode::Esc => close_popup(state, instances_state),
KeyCode::Left | KeyCode::Char('h') => state.step = WizardStep::Version,
KeyCode::Char('j') | KeyCode::Down => {
if version_count > 0 {
@@ -405,10 +304,10 @@ fn handle_loader_version_key(
fn handle_confirm_key(
state: &mut WizardState,
key_event: &KeyEvent,
profiles_state: &mut profiles::State,
instances_state: &mut instances::State,
) {
match key_event.code {
KeyCode::Esc => close_popup(state, profiles_state),
KeyCode::Esc => close_popup(state, instances_state),
KeyCode::Left | KeyCode::Char('h') => {
if state.selected_loader() == ModLoader::Vanilla {
state.step = WizardStep::Version;
@@ -442,230 +341,18 @@ fn handle_confirm_key(
}
}
close_popup(state, profiles_state);
close_popup(state, instances_state);
}
_ => {}
}
}
fn close_popup(state: &mut WizardState, profiles_state: &mut profiles::State) {
fn close_popup(state: &mut WizardState, instances_state: &mut instances::State) {
state.reset();
profiles_state.show_popup = false;
instances_state.show_popup = false;
}
fn wizard_title(_state: &WizardState) -> Line<'static> {
use crate::tui::widgets::styled_title;
styled_title("New Instance", false)
}
fn step_keybinds(state: &WizardState) -> ratatui::text::Line<'static> {
use super::keybind_line;
match state.step {
WizardStep::Name => keybind_line(&[("Enter", " continue")]),
WizardStep::Loader => keybind_line(&[("h", " back"), ("Enter", " select")]),
WizardStep::Version => keybind_line(&[
("/", " search"),
("s", " snap"),
("h", " back"),
("Enter", " select"),
]),
WizardStep::LoaderVersion => keybind_line(&[("h", " back"), ("Enter", " select")]),
WizardStep::Confirm => keybind_line(&[("h", " back"), ("Enter", " create")]),
}
}
fn render_name_step(state: &WizardState, area: Rect, buf: &mut ratatui::buffer::Buffer) {
use ratatui::style::Modifier;
use ratatui::text::{Line, Span};
let value = state.name_state.value();
let line = if value.is_empty() {
Line::from(vec![
Span::styled(
"Instance name...",
Style::default().fg(THEME.popup_new_instance.field_inactive_border_fg),
),
Span::styled(
"\u{2588}",
Style::default()
.fg(THEME.popup_new_instance.border_fg)
.add_modifier(Modifier::SLOW_BLINK),
),
])
} else {
Line::from(vec![
Span::styled(value, Style::default().fg(THEME.popup_new_instance.text_fg)),
Span::styled(
"\u{2588}",
Style::default()
.fg(THEME.popup_new_instance.border_fg)
.add_modifier(Modifier::SLOW_BLINK),
),
])
};
Paragraph::new(line).render(area, buf);
}
fn render_version_step(state: &WizardState, area: Rect, buf: &mut ratatui::buffer::Buffer) {
match &state.versions {
LoadState::Idle | LoadState::Loading => {
Paragraph::new("Loading versions...")
.style(Style::default().fg(THEME.popup_new_instance.field_inactive_border_fg))
.render(area, buf);
}
LoadState::Error(message) => {
Paragraph::new(message.as_str())
.wrap(Wrap { trim: true })
.style(Style::default().fg(THEME.popup_new_instance.error_fg))
.render(area, buf);
}
LoadState::Loaded(_) => {
let items: Vec<ListItem> = visible_versions(state)
.into_iter()
.map(|version| {
let suffix = if version.stable {
String::new()
} else {
" (snapshot)".to_string()
};
ListItem::new(Line::from(Span::styled(
format!("{}{}", version.id, suffix),
Style::default().fg(THEME.popup_new_instance.text_fg),
)))
})
.collect();
let list = List::new(items)
.highlight_style(
Style::default()
.fg(THEME.popup_new_instance.accent_fg)
.add_modifier(Modifier::BOLD),
)
.highlight_symbol("▶ ");
let mut list_state = ListState::default().with_selected(Some(state.version_idx));
StatefulWidget::render(list, area, buf, &mut list_state);
}
}
}
fn render_loader_step(state: &WizardState, area: Rect, buf: &mut ratatui::buffer::Buffer) {
let loaders = [
ModLoader::Vanilla,
ModLoader::Fabric,
ModLoader::Forge,
ModLoader::NeoForge,
ModLoader::Quilt,
];
let items: Vec<ListItem> = loaders
.into_iter()
.map(|loader| {
ListItem::new(Line::from(Span::styled(
loader.to_string(),
Style::default().fg(THEME.popup_new_instance.text_fg),
)))
})
.collect();
let list = List::new(items)
.highlight_style(
Style::default()
.fg(THEME.popup_new_instance.accent_fg)
.add_modifier(Modifier::BOLD),
)
.highlight_symbol("▶ ");
let mut list_state = ListState::default().with_selected(Some(state.loader_idx));
StatefulWidget::render(list, area, buf, &mut list_state);
}
fn render_loader_version_step(state: &WizardState, area: Rect, buf: &mut ratatui::buffer::Buffer) {
if state.selected_loader() == ModLoader::Vanilla {
Paragraph::new("Vanilla has no loader version.")
.style(Style::default().fg(THEME.popup_new_instance.field_inactive_border_fg))
.render(area, buf);
return;
}
match &state.loader_versions {
LoadState::Idle | LoadState::Loading => {
Paragraph::new(format!("Loading {} versions...", state.selected_loader()))
.style(Style::default().fg(THEME.popup_new_instance.field_inactive_border_fg))
.render(area, buf);
}
LoadState::Error(message) => {
Paragraph::new(message.as_str())
.wrap(Wrap { trim: true })
.style(Style::default().fg(THEME.popup_new_instance.error_fg))
.render(area, buf);
}
LoadState::Loaded(versions) => {
let items: Vec<ListItem> = versions
.iter()
.map(|version| {
ListItem::new(Line::from(Span::styled(
version.clone(),
Style::default().fg(THEME.popup_new_instance.text_fg),
)))
})
.collect();
let list = List::new(items)
.highlight_style(
Style::default()
.fg(THEME.popup_new_instance.accent_fg)
.add_modifier(Modifier::BOLD),
)
.highlight_symbol("▶ ");
let mut list_state = ListState::default().with_selected(Some(state.loader_version_idx));
StatefulWidget::render(list, area, buf, &mut list_state);
}
}
}
fn render_confirm_step(state: &WizardState, area: Rect, buf: &mut ratatui::buffer::Buffer) {
let game_version = state
.selected_version()
.map(|version| version.id.as_str())
.unwrap_or("<not selected>");
let loader = state.selected_loader();
let loader_version = if loader == ModLoader::Vanilla {
"n/a".to_string()
} else {
state
.selected_loader_version()
.unwrap_or_else(|| "<not selected>".to_string())
};
let label_style = Style::default().fg(THEME.popup_new_instance.border_fg);
Paragraph::new(vec![
Line::from(vec![
Span::styled("Name: ", label_style),
Span::raw(state.name_state.value()),
]),
Line::from(vec![
Span::styled("MC: ", label_style),
Span::raw(game_version),
]),
Line::from(vec![
Span::styled("Loader: ", label_style),
Span::raw(loader.to_string()),
]),
Line::from(vec![
Span::styled("Loader version: ", label_style),
Span::raw(loader_version),
]),
])
.style(Style::default().fg(THEME.popup_new_instance.text_fg))
.wrap(Wrap { trim: true })
.render(area, buf);
}
fn visible_versions(state: &WizardState) -> Vec<GameVersion> {
pub(crate) fn visible_versions(state: &WizardState) -> Vec<GameVersion> {
let q = state.version_search.query.to_lowercase();
match &state.versions {
LoadState::Loaded(versions) => versions
@@ -678,7 +365,7 @@ fn visible_versions(state: &WizardState) -> Vec<GameVersion> {
}
}
fn clamp_version_index(state: &mut WizardState) {
pub(crate) fn clamp_version_index(state: &mut WizardState) {
let count = visible_versions(state).len();
if count == 0 {
state.version_idx = 0;
@@ -687,7 +374,7 @@ fn clamp_version_index(state: &mut WizardState) {
}
}
fn clamp_loader_version_index(state: &mut WizardState) {
pub(crate) fn clamp_loader_version_index(state: &mut WizardState) {
if let LoadState::Loaded(versions) = &state.loader_versions {
if versions.is_empty() {
state.loader_version_idx = 0;
@@ -699,7 +386,7 @@ fn clamp_loader_version_index(state: &mut WizardState) {
}
}
fn ensure_versions_loaded(state: &mut WizardState) {
pub(crate) fn ensure_versions_loaded(state: &mut WizardState) {
if !matches!(state.versions, LoadState::Idle) {
return;
}
@@ -733,7 +420,7 @@ fn ensure_versions_loaded(state: &mut WizardState) {
});
}
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;
}
+13 -19
View File
@@ -13,7 +13,7 @@ use ratatui::{
use ratatui_image::{protocol::StatefulProtocol, Resize, StatefulImage};
use crate::instance::screenshots::ScreenshotEntry;
use crate::tui::theme::THEME;
use crate::config::theme::THEME;
const TARGET_CELL_WIDTH: u16 = 34;
const MIN_CELL_WIDTH: u16 = 24;
@@ -219,14 +219,18 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut ScreenshotsState) -> bool {
KeyCode::Enter if key_event.modifiers.contains(KeyModifiers::SHIFT) => {
if let Some(entry) = state.entries.get(state.selected) {
if let Some(dir) = entry.path.parent() {
xdg_open(dir);
if let Err(e) = open::that(dir) {
tracing::error!("Failed to open directory: {}", e);
}
}
}
true
}
KeyCode::Enter => {
if let Some(entry) = state.entries.get(state.selected) {
xdg_open(&entry.path);
if let Err(e) = open::that(&entry.path) {
tracing::error!("Failed to open file: {}", e);
}
}
true
}
@@ -261,22 +265,12 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut ScreenshotsState) -> bool {
}
}
fn xdg_open(path: &std::path::Path) {
if let Err(e) = std::process::Command::new("xdg-open")
.arg(path)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
{
tracing::error!("Failed to open: {}", e);
}
}
pub fn render(frame: &mut Frame, area: Rect, state: &mut ScreenshotsState, is_focused: bool) {
let theme = THEME.as_ref();
if state.loading {
frame.render_widget(
Paragraph::new("Loading screenshots...")
.style(Style::default().fg(THEME.screenshots.label_fg)),
.style(Style::default().fg(theme.text_dim())),
area,
);
return;
@@ -285,7 +279,7 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut ScreenshotsState, is_fo
if state.entries.is_empty() {
frame.render_widget(
Paragraph::new("No screenshots.")
.style(Style::default().fg(THEME.screenshots.label_fg)),
.style(Style::default().fg(theme.text_dim())),
area,
);
return;
@@ -352,10 +346,10 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut ScreenshotsState, is_fo
let name = &state.entries[idx].name;
let name_style = if is_selected {
Style::default()
.fg(THEME.screenshots.selected_border_fg)
.fg(theme.accent())
.add_modifier(Modifier::BOLD)
} else {
Style::default().fg(THEME.screenshots.label_fg)
Style::default().fg(theme.text_dim())
};
let truncated = if name.len() > cell_width as usize {
@@ -382,7 +376,7 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut ScreenshotsState, is_fo
.begin_symbol(Some("\u{25b2}"))
.style(
Style::default()
.fg(THEME.screenshots.border_focused_fg)
.fg(theme.text_dim())
.add_modifier(Modifier::BOLD),
)
.thumb_symbol("\u{2551}")
+4 -3
View File
@@ -3,7 +3,7 @@ use ratatui::{
text::{Line, Span},
};
use crate::tui::theme::THEME;
use crate::config::theme::THEME;
#[derive(Debug, Default, Clone)]
pub struct SearchState {
@@ -77,9 +77,10 @@ impl SearchState {
return None;
}
let dim = Style::default().fg(THEME.search.border_unfocused_fg);
let theme = THEME.as_ref();
let dim = Style::default().fg(theme.text_dim());
let accent = Style::default()
.fg(THEME.search.border_focused_fg)
.fg(theme.text_dim())
.add_modifier(Modifier::BOLD);
let mut spans = vec![
+15 -14
View File
@@ -7,9 +7,9 @@ use ratatui::{
};
use throbber_widgets_tui::{Throbber, ThrobberState};
use crate::tui::layout::FocusedArea;
use crate::tui::app::FocusedArea;
use crate::tui::progress::PROGRESS;
use crate::tui::theme::THEME;
use crate::config::theme::{THEME, BORDER_STYLE};
use super::styled_title;
@@ -19,16 +19,17 @@ pub fn render(
focused: FocusedArea,
throbber_state: &mut ThrobberState,
) {
let theme = THEME.as_ref();
let border_color = if focused == FocusedArea::Overview {
THEME.status.border_focused_fg
theme.accent()
} else {
THEME.status.border_unfocused_fg
theme.border()
};
let block = Block::default()
.title(styled_title("Overview", true))
.borders(Borders::ALL)
.border_type(THEME.general.border_type.to_border_type())
.border_type(BORDER_STYLE.to_border_type())
.border_style(Style::default().fg(border_color));
let state = match PROGRESS.lock() {
@@ -37,7 +38,7 @@ pub fn render(
frame.render_widget(
Paragraph::new(Span::styled(
"Ready",
Style::default().fg(THEME.status.label_fg),
Style::default().fg(theme.text_dim()),
))
.block(block),
area,
@@ -50,7 +51,7 @@ pub fn render(
frame.render_widget(
Paragraph::new(Span::styled(
"Ready",
Style::default().fg(THEME.status.label_fg),
Style::default().fg(theme.text_dim()),
))
.block(block),
area,
@@ -77,19 +78,19 @@ pub fn render(
let gauge = Gauge::default()
.gauge_style(
Style::default()
.fg(THEME.status.progress_fill_fg)
.bg(THEME.status.progress_track_fg)
.fg(theme.success())
.bg(theme.surface())
.add_modifier(Modifier::BOLD),
)
.percent((ratio * 100.0) as u16);
frame.render_widget(gauge, chunks[0]);
frame.render_widget(
Paragraph::new(action_text).style(Style::default().fg(THEME.status.text_fg)),
Paragraph::new(action_text).style(Style::default().fg(theme.text())),
chunks[1],
);
if !sub_text.is_empty() {
frame.render_widget(
Paragraph::new(sub_text).style(Style::default().fg(THEME.status.label_fg)),
Paragraph::new(sub_text).style(Style::default().fg(theme.text_dim())),
chunks[2],
);
}
@@ -99,16 +100,16 @@ pub fn render(
Layout::vertical([Constraint::Length(1), Constraint::Length(1)]).split(inner);
let throbber = Throbber::default()
.label(action_text)
.style(Style::default().fg(THEME.status.text_fg))
.style(Style::default().fg(theme.text()))
.throbber_style(
Style::default()
.fg(THEME.status.border_focused_fg)
.fg(theme.text_dim())
.add_modifier(Modifier::BOLD),
);
frame.render_stateful_widget(throbber, chunks[0], throbber_state);
if !sub_text.is_empty() {
frame.render_widget(
Paragraph::new(sub_text).style(Style::default().fg(THEME.status.label_fg)),
Paragraph::new(sub_text).style(Style::default().fg(theme.text_dim())),
chunks[1],
);
}