37 Commits
Author SHA1 Message Date
objz 6dda8dc410 chore: updated readme and updated to 0.3.3 release 2026-07-11 17:49:35 +02:00
objz b4d03e7212 perf(content): use stable keys for icon caches 2026-07-11 17:16:30 +02:00
objz c792e1cc11 perf(tui): avoid redundant idle rendering 2026-07-11 17:13:02 +02:00
objz d10be1676e Merge pull request #25 from objz/feature/image-render-options
Feature/image render options
2026-07-11 16:04:25 +02:00
objz b94957a952 fix: formatting 2026-07-11 15:46:15 +02:00
objz 6f5722aa02 feat(tui): render streamed content icons 2026-07-11 15:41:51 +02:00
objz 4bf43a438b feat(content): add quadrant icon rasterization 2026-07-11 15:41:36 +02:00
objz b372571648 feat(config): add terminal image mode setting 2026-07-11 15:41:21 +02:00
objz b5d98e5e8a fix: polling noice on log and cache for scanning java version 2026-07-10 17:06:59 +02:00
objz 7e5ff7f75f fix(ci): choco validation file was remove and fixed icon paths 2026-07-10 16:56:11 +02:00
objz 099d96bcca Merge pull request #23 from objz/feature/delete-mods
feat(tui): add delete actions for instance content
2026-07-10 16:46:34 +02:00
objz 4ba9c65f73 fix(tui): route account deletes through shared confirmation 2026-07-10 16:39:43 +02:00
objz be01370ab2 feature(tui): added delete button to every content type 2026-07-10 16:35:55 +02:00
objz 4ddb8f49bb Merge pull request #24 from objz/feature/config-sync
feat(config-sync): add shared config profiles
2026-07-10 16:30:00 +02:00
objz 4576da4551 fix(config-sync): satisfy clippy warnings 2026-07-10 16:20:03 +02:00
objz 269814945d feat(tui): manage config profiles from settings 2026-07-10 16:12:48 +02:00
objz 69549b7152 feat(config-sync): add per-instance config profiles 2026-07-10 16:09:47 +02:00
objz 8f16931502 chore: v0.3.2 2026-06-16 15:17:55 +02:00
objz a95250cf9a Merge pull request #21 from objz/fix/adding-neoforge-instance-fails
Fix/adding neoforge instance fails
2026-06-16 15:13:30 +02:00
objz 2adfd0afbd Merge pull request #20 from objz/fix/sun-misc-unsafe-memory-accessallow
Fix/sun misc unsafe memory accessallow
2026-06-16 15:13:15 +02:00
objz 3ab6adf700 Merge pull request #22 from objz/fix/aur-failed-to-install
fix(pkg): isolate cargo target and config for AUR builds
2026-06-16 15:12:31 +02:00
objz 7c59758f5f fix(pkg): isolate cargo target and config for AUR builds 2026-06-16 15:08:14 +02:00
objz 63d7ef0fa1 fix: lib directory should point to the local libs preffered, only shared libs as backup to prevent corruption neoforge installation 2026-06-16 14:13:57 +02:00
objz 68d2f45236 fix: point -Duser to the right directory to prevent crashes 2026-06-16 14:13:57 +02:00
objz 3dd384c5c6 fixed clippy fail on windows caused by dead code that is only needed on unix 2026-06-16 14:01:32 +02:00
objz c5da2c7c99 fixed duplicate error messages on installer failure and added new error type 2026-06-16 13:25:28 +02:00
objz 1fd1b4e09d fix(launch): validate required Java version before launch 2026-06-16 12:32:37 +02:00
objz 0d9cd9c6b8 fixed duplicate logs 2026-06-16 12:26:18 +02:00
objz 09f403aa07 fixed noisy log 2026-06-16 12:07:31 +02:00
objz 3d7f233e27 fixed clippy issues 2026-06-16 10:35:34 +02:00
objz db23b86dca fix: flush downloaded files before returning 2026-06-16 10:27:21 +02:00
objz 09bc8f26fb chore: improve rmcl diagnostic logging 2026-06-16 10:22:51 +02:00
objz a58e6fb76d style: apply rustfmt 2026-06-16 09:58:34 +02:00
objz 7723716e18 Merge pull request #12 from objz/stout/sterr-parse-tui
added minecraft log parser
2026-06-13 16:53:21 +02:00
objz 29280e9f8d added minecraft log parser 2026-06-13 16:27:05 +02:00
objz e7e033715e fixed shocase gif 2026-06-12 11:36:19 +02:00
objz 4c22381675 added showcase.gif to the readme 2026-06-12 09:58:18 +02:00
71 changed files with 4463 additions and 598 deletions

No files matched your search

-1
View File
@@ -46,7 +46,6 @@ jobs:
checksum="$(awk '{print $1}' "$package_dir/$checksum_file")"
sed -i "s|__TAG__|$tag|g; s|__CHECKSUM64__|$checksum|g" "$package_dir/tools/chocolateyInstall.ps1"
sed -i "s|__TAG__|$tag|g; s|__CHECKSUM64__|$checksum|g" "$package_dir/tools/VERIFICATION.txt"
echo "version=$version" >> "$GITHUB_OUTPUT"
echo "package_dir=$package_dir" >> "$GITHUB_OUTPUT"
Generated
+61 -1
View File
@@ -1053,6 +1053,15 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd2e7510819d6fbf51a5545c8f922716ecfb14df168a3242f7d33e0239efe6a1"
[[package]]
name = "fast-strip-ansi"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3086ffd0a7160f58f988c74173a002e255da505a114e2f5425acb1eaab2b8ac"
dependencies = [
"vt-push-parser",
]
[[package]]
name = "fastrand"
version = "2.4.1"
@@ -1244,6 +1253,16 @@ dependencies = [
"slab",
]
[[package]]
name = "gdb-command"
version = "0.7.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73b2762e2f2c0768e1137b33e9f7cf31599994e96496f4e020cc16e0d4e66319"
dependencies = [
"regex",
"wait-timeout",
]
[[package]]
name = "generic-array"
version = "0.14.7"
@@ -1927,6 +1946,12 @@ dependencies = [
"syn 2.0.117",
]
[[package]]
name = "kodama"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f868feceed4703c842925c14232667c5f29c8059d0354154b2d06ec3bf9daf82"
[[package]]
name = "kqueue"
version = "1.1.1"
@@ -1977,6 +2002,19 @@ version = "0.2.186"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
[[package]]
name = "libcasr"
version = "2.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "159cff1fadbb464709c30306774c57171e98cc1ea41e7767df5c63819743a453"
dependencies = [
"chrono",
"gdb-command",
"kodama",
"regex",
"thiserror 2.0.18",
]
[[package]]
name = "libm"
version = "0.2.16"
@@ -3157,7 +3195,7 @@ dependencies = [
[[package]]
name = "rmcl"
version = "0.3.1"
version = "0.3.3"
dependencies = [
"async-trait",
"chrono",
@@ -3167,8 +3205,10 @@ dependencies = [
"crossterm 0.29.0",
"dirs",
"dirs-next",
"fast-strip-ansi",
"image",
"insta",
"libcasr",
"log",
"minecraft-msa-auth",
"notify",
@@ -3178,6 +3218,7 @@ dependencies = [
"ratatui-image",
"ratatui-textarea",
"ratatui-themekit",
"regex",
"reqwest",
"rstest",
"serde",
@@ -4331,6 +4372,16 @@ version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64"
[[package]]
name = "vt-push-parser"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdbf39d53c5a50cad8119d9cde929ecd208764e8d8d1626486b8929cbcd5f0e7"
dependencies = [
"hex",
"smallvec",
]
[[package]]
name = "vtparse"
version = "0.6.2"
@@ -4340,6 +4391,15 @@ dependencies = [
"utf8parse",
]
[[package]]
name = "wait-timeout"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11"
dependencies = [
"libc",
]
[[package]]
name = "walkdir"
version = "2.5.0"
+4 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "rmcl"
version = "0.3.1"
version = "0.3.3"
authors = ["objz"]
edition = "2024"
description = "A fully featured Minecraft TUI launcher"
@@ -58,6 +58,9 @@ open = "5"
which = "8.0.2"
dirs = "6.0.0"
notify = "8"
regex = "1"
fast-strip-ansi = "0.13"
libcasr = "2.13"
[profile.release]
+47 -36
View File
@@ -20,23 +20,27 @@
## about
we all love TUIs. and we all know the official Minecraft launcher is not exactly a joy to use (performance wise; no hatespeech here). so here's rmcl, a fully featured Minecraft launcher that lives in your terminal. written in Rust because if you're replacing something bloated you might as well go all the way.
we all love TUIs. and we all know the official Minecraft launcher is not exactly a joy to use (performance wise; no hatespeech here). so here's rmcl, a fully featured Minecraft launcher that lives in your terminal. written in Rust.
it does everything you'd expect from a launcher. multiple instances, mod loaders, modpack imports, Microsoft auth, content management, launching. all from a TUI or from the command line. the TUI is the main thing though, the CLI is there for scripting and automation.
it does everything you'd expect from a launcher.
![showcase](assets/showcase.gif)
## features
| Mod Loader | Supported |
|------------|-----------|
| Vanilla | ✅ |
| Fabric | ✅ |
| Forge | ✅ |
| NeoForge | ✅ |
| Quilt | ✅ |
| LiteLoader | ❌ |
| Rift | ❌ |
| | |
|---|---|
| **instances** | create and manage multiple instances, each with their own version, loader, mods, and settings |
| **mod loaders** | vanilla, Fabric, Quilt, Forge, NeoForge. more might show up later |
| **content** | browse and toggle mods, shaders, resource packs. view worlds, screenshots, and logs |
| **modpack import** | import from Modrinth via `.mrpack` file, URL, or slug |
| **accounts** | multiple Microsoft accounts and offline players, switch between them |
| **launching** | launch directly from the TUI or generate a desktop shortcut for any instance |
| **desktop shortcuts** | click it and Minecraft starts, no need to open rmcl or type anything |
| **CLI** | every feature the TUI has is also available as a subcommand |
| **theming** | 10 built-in themes, custom themes, color overrides |
### modpacks and accounts
`Modrinth`, `MultiMC`, and `GTNH` modpacks format is supported. Import it from a file, URL, or just the slug. Able to use multiple Microsoft accounts and offline accounts aswell.
---
@@ -48,10 +52,14 @@ Authentication is performed through Microsoft’s official services.
## installation
[![GitHub release](https://img.shields.io/github/v/release/objz/rmcl?style=for-the-badge&logo=github)](https://github.com/objz/rmcl/releases)
### macOS / Linux
prebuilt archives are attached to each GitHub release.
[![Homebrew tap](https://img.shields.io/badge/homebrew-objz%2Ftap-FBB040?style=for-the-badge&logo=homebrew)](https://github.com/objz/homebrew-tap)
```sh
# Homebrew
brew install objz/tap/rmcl
@@ -62,6 +70,9 @@ brew install objz/tap/rmcl
release builds include a `.zip` archive and an `.msi`. WinGet and Chocolatey
packages are submitted from release CI and become available after review.
[![WinGet](https://img.shields.io/badge/winget-Objz.Rmcl-0078D4?style=for-the-badge&logo=windows11)](https://winstall.app/apps/Objz.Rmcl)
[![Chocolatey](https://img.shields.io/chocolatey/v/rmcl?style=for-the-badge&logo=chocolatey)](https://community.chocolatey.org/packages/rmcl)
```powershell
# WinGet
winget install Objz.Rmcl
@@ -72,6 +83,10 @@ choco install rmcl
### Arch Linux
[![AUR rmcl](https://img.shields.io/aur/version/rmcl?style=for-the-badge&logo=archlinux)](https://aur.archlinux.org/packages/rmcl)
[![AUR rmcl-bin](https://img.shields.io/aur/version/rmcl-bin?style=for-the-badge&logo=archlinux)](https://aur.archlinux.org/packages/rmcl-bin)
[![AUR rmcl-git](https://img.shields.io/aur/version/rmcl-git?style=for-the-badge&logo=archlinux)](https://aur.archlinux.org/packages/rmcl-git)
```sh
# from source (release tarball)
paru -S rmcl
@@ -85,29 +100,11 @@ paru -S rmcl-git
### Cargo
[![crates.io](https://img.shields.io/crates/v/rmcl?style=for-the-badge&logo=rust)](https://crates.io/crates/rmcl)
```sh
cargo install rmcl
```
### package status
release:
[![GitHub release](https://img.shields.io/github/v/release/objz/rmcl?style=for-the-badge&logo=github)](https://github.com/objz/rmcl/releases)
[![crates.io](https://img.shields.io/crates/v/rmcl?style=for-the-badge&logo=rust)](https://crates.io/crates/rmcl)
package managers:
[![Homebrew tap](https://img.shields.io/badge/homebrew-objz%2Ftap-FBB040?style=for-the-badge&logo=homebrew)](https://github.com/objz/homebrew-tap)
[![WinGet](https://img.shields.io/badge/winget-Objz.Rmcl-0078D4?style=for-the-badge&logo=windows11)](https://winstall.app/apps/Objz.Rmcl)
[![Chocolatey](https://img.shields.io/chocolatey/v/rmcl?style=for-the-badge&logo=chocolatey)](https://community.chocolatey.org/packages/rmcl)
aur:
[![AUR rmcl](https://img.shields.io/aur/version/rmcl?style=for-the-badge&logo=archlinux)](https://aur.archlinux.org/packages/rmcl)
[![AUR rmcl-bin](https://img.shields.io/aur/version/rmcl-bin?style=for-the-badge&logo=archlinux)](https://aur.archlinux.org/packages/rmcl-bin)
[![AUR rmcl-git](https://img.shields.io/aur/version/rmcl-git?style=for-the-badge&logo=archlinux)](https://aur.archlinux.org/packages/rmcl-git)
### from source
requires a Rust toolchain and a JDK (`javac` and `jar` on `PATH`).
@@ -132,7 +129,7 @@ settings, accounts, instances, and cached game metadata.
| instances | `~/.local/share/rmcl/instances/` | `~/Library/Application Support/rmcl/instances/` | `%LOCALAPPDATA%\rmcl\instances\` |
| metadata (versions, libraries, assets, loader profiles) | `~/.local/share/rmcl/meta/` | `~/Library/Application Support/rmcl/meta/` | `%LOCALAPPDATA%\rmcl\meta\` |
each instance has an `instance.json` for its config and a `.minecraft/` directory with the actual game files. standard layout, nothing weird.
each instance has an `instance.json` for its config and a `.minecraft/` directory with the actual game files.
### logs
@@ -145,9 +142,23 @@ launcher logs are per-session and contain rmcl's own output. instance launch log
---
## configuration
## performance
everything is configured through TOML files. `config.toml` for paths, default memory allocation, and UI behavior. `theme.toml` for theme selection and border style. you can also override individual colors without making a full custom theme.
the following measurements were taken from a release build on a Linux development system. they are intended as a practical reference, since terminal, window size, content count, and hardware all affect the result.
### idle instance list
over a `60` second sample, the instance list used `497.81 ms` of CPU time. that is about `0.83%` of one CPU core. resident memory was `15.1 MiB`.
### idle mods list
with a populated mods list and its icons loaded, a `60` second sample used `664.77 ms` of CPU time. that is about `1.11%` of one CPU core. resident memory was `67.2 MiB`, with a peak of `69.9 MiB`.
### scrolling mods list
continuously scrolling through the populated mods list used `1000.02 ms` of CPU time over 30 seconds. that is about `3.33%` of one CPU core.
In comparison, the Modrinth AppImage used approximately `14-30%` of a CPU core and about `327 Mib` of memory while browsing the mod list.
---
@@ -163,7 +174,7 @@ you can create your own by dropping a TOML file in `~/.config/rmcl/theme/` and r
## contributing
contributions are welcome. fork it, branch it, PR it. see [CONTRIBUTING.md](CONTRIBUTING.md) for code style and project structure.
contributions are welcome. fork it, branch it, PR it. see [CONTRIBUTING.md](CONTRIBUTING.md)
---
+2
View File
@@ -14,6 +14,8 @@ memory_min = "512M"
memory_max = "2G"
[ui]
# image protocol for content icons and screenshots: halfblocks, quadrants, kitty, or iterm2
image_protocol = "kitty"
# error popup timing (in ms)
error_auto_dismiss_ms = 5000
error_slide_start_ms = 3500
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 MiB

+2 -1
View File
@@ -5,7 +5,7 @@
<version>0.0.0</version>
<packageSourceUrl>https://github.com/objz/rmcl</packageSourceUrl>
<owners>objz</owners>
<title>rmcl</title>
<title>rmcl Minecraft Launcher</title>
<authors>objz</authors>
<projectUrl>https://github.com/objz/rmcl</projectUrl>
<licenseUrl>https://github.com/objz/rmcl/blob/master/LICENSE</licenseUrl>
@@ -13,6 +13,7 @@
<projectSourceUrl>https://github.com/objz/rmcl</projectSourceUrl>
<docsUrl>https://github.com/objz/rmcl#readme</docsUrl>
<bugTrackerUrl>https://github.com/objz/rmcl/issues</bugTrackerUrl>
<releaseNotes>https://github.com/objz/rmcl/releases</releaseNotes>
<tags>minecraft launcher cli tui rust</tags>
<summary>Minecraft launcher TUI</summary>
<description>A fully featured Minecraft launcher TUI with Microsoft account authentication, instance management, mod loaders, imports, content management, and launch support.</description>
-12
View File
@@ -1,12 +0,0 @@
VERIFICATION
This package downloads the official MSI from the GitHub release:
https://github.com/objz/rmcl/releases/download/__TAG__/rmcl-x86_64-pc-windows-msvc.msi
The SHA256 checksum is generated by cargo-dist and published next to the release asset:
https://github.com/objz/rmcl/releases/download/__TAG__/rmcl-x86_64-pc-windows-msvc.msi.sha256
Expected SHA256:
__CHECKSUM64__
+5
View File
@@ -20,11 +20,16 @@ pkgver() {
}
build() {
export CARGO_TARGET_DIR="$srcdir/target"
rm -rf "$CARGO_TARGET_DIR"
cd "$srcdir/rmcl"
cargo build --release --locked
}
check() {
export CARGO_TARGET_DIR="$srcdir/target"
export XDG_CONFIG_HOME="$srcdir/xdg-config"
mkdir -p "$XDG_CONFIG_HOME"
cd "$srcdir/rmcl"
cargo test --release --locked
}
+5
View File
@@ -15,11 +15,16 @@ source=("${url}/archive/v${pkgver}.tar.gz")
sha256sums=('SKIP')
build() {
export CARGO_TARGET_DIR="$srcdir/target"
rm -rf "$CARGO_TARGET_DIR"
cd "$srcdir/rmcl-${pkgver}"
cargo build --release --locked
}
check() {
export CARGO_TARGET_DIR="$srcdir/target"
export XDG_CONFIG_HOME="$srcdir/xdg-config"
mkdir -p "$XDG_CONFIG_HOME"
cd "$srcdir/rmcl-${pkgver}"
cargo test --release --locked
}
+56 -3
View File
@@ -39,9 +39,27 @@ impl AccountStore {
pub fn load() -> Self {
let path = account_store_path();
let accounts = match std::fs::read_to_string(&path) {
Ok(content) => serde_json::from_str(&content).unwrap_or_default(),
Err(_) => Vec::new(),
Ok(content) => match serde_json::from_str(&content) {
Ok(accounts) => accounts,
Err(e) => {
tracing::warn!("Failed to parse accounts file {}: {}", path.display(), e);
Vec::new()
}
},
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
tracing::debug!("No accounts file at {}", path.display());
Vec::new()
}
Err(e) => {
tracing::warn!("Failed to read accounts file {}: {}", path.display(), e);
Vec::new()
}
};
tracing::debug!(
"Loaded {} account(s) from {}",
accounts.len(),
path.display()
);
Self { accounts, path }
}
@@ -55,7 +73,17 @@ impl AccountStore {
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);
tracing::error!(
"Failed to write accounts file {}: {}",
self.path.display(),
e
);
} else {
tracing::debug!(
"Saved {} account(s) to {}",
self.accounts.len(),
self.path.display()
);
}
}
Err(e) => tracing::error!("Failed to serialize accounts: {}", e),
@@ -73,9 +101,18 @@ impl AccountStore {
}
pub fn set_active(&mut self, index: usize) {
let username = self
.accounts
.get(index)
.map(|account| account.username.clone());
for (i, acc) in self.accounts.iter_mut().enumerate() {
acc.active = i == index;
}
if let Some(username) = username {
tracing::info!("Selected account '{}'", username);
} else {
tracing::warn!("Tried to select missing account index {}", index);
}
self.save();
}
@@ -83,22 +120,38 @@ impl AccountStore {
// first account added auto-becomes active so there's always a selection.
pub fn add(&mut self, account: Account) {
let uuid = &account.uuid;
let replaced = self.accounts.iter().any(|a| a.uuid == *uuid);
let account_type = account.account_type.clone();
let username = account.username.clone();
self.accounts.retain(|a| a.uuid != *uuid);
let mut account = account;
if self.accounts.is_empty() {
account.active = true;
}
self.accounts.push(account);
tracing::info!(
"{} {:?} account '{}'",
if replaced { "Updated" } else { "Added" },
account_type,
username
);
self.save();
}
pub fn remove(&mut self, index: usize) {
if index >= self.accounts.len() {
tracing::warn!("Tried to remove missing account index {}", index);
return;
}
let account = self.accounts.remove(index);
tracing::info!(
"Removed {:?} account '{}'",
account.account_type,
account.username
);
if account.active && !self.accounts.is_empty() {
self.accounts[0].active = true;
tracing::debug!("Activated fallback account '{}'", self.accounts[0].username);
}
self.save();
}
+2
View File
@@ -61,6 +61,7 @@ async fn run_full_oauth_flow() -> Result<(String, Option<String>), String> {
user_code: details.user_code().secret().to_owned(),
verification_uri: details.verification_uri().to_string(),
});
crate::tui::request_redraw();
}
let token = oauth_client
@@ -85,6 +86,7 @@ pub fn start_microsoft_auth() -> Arc<Mutex<Option<AuthResult>>> {
let outcome = run_full_auth_flow().await;
if let Ok(mut slot) = result_clone.lock() {
*slot = Some(outcome);
crate::tui::request_redraw();
}
});
+76
View File
@@ -11,6 +11,7 @@ use crate::instance::{InstanceManager, ModLoader};
use crate::running::RunState;
type CliResult = Result<(), Box<dyn std::error::Error>>;
const LOCAL_CONFIG_PROFILE: &str = "instance default";
pub async fn handle_instance(matches: &ArgMatches) -> CliResult {
match matches.subcommand() {
@@ -20,6 +21,7 @@ pub async fn handle_instance(matches: &ArgMatches) -> CliResult {
Some(("rename", sub_matches)) => rename_instance(sub_matches),
Some(("launch", sub_matches)) => launch_instance(sub_matches).await,
Some(("config", sub_matches)) => config_instance(sub_matches),
Some(("profile", sub_matches)) => profile_instance(sub_matches),
Some(("desktop", sub_matches)) => desktop_instance(sub_matches),
_ => Ok(()),
}
@@ -233,12 +235,86 @@ fn config_instance(matches: &ArgMatches) -> CliResult {
.map(|(width, height)| format!("{}x{}", width, height))
.unwrap_or_else(|| "-".to_string()),
],
vec![
"config-sync-profile".to_string(),
display_config_profile(config.config_sync_profile.as_deref()).to_string(),
],
];
print_table(&["Field", "Value"], &rows);
Ok(())
}
fn profile_instance(matches: &ArgMatches) -> CliResult {
let name = required_arg(matches, "name")?;
let manager = manager();
let mut config = manager.load_one(name)?;
let profiles = crate::instance::config_sync::list_profiles(&manager.meta_dir)?;
if config
.config_sync_profile
.as_ref()
.is_some_and(|profile| !profiles.iter().any(|candidate| candidate == profile))
{
config.config_sync_profile = None;
manager.save(&config)?;
}
let Some(profile) = matches.get_one::<String>("profile") else {
let rows = vec![
vec![
"current".to_string(),
display_config_profile(config.config_sync_profile.as_deref()).to_string(),
],
vec![
"available".to_string(),
if profiles.is_empty() {
LOCAL_CONFIG_PROFILE.to_string()
} else {
format!("{}, {}", LOCAL_CONFIG_PROFILE, profiles.join(", "))
},
],
];
print_table(&["Field", "Value"], &rows);
return Ok(());
};
let target = if is_local_profile_alias(profile) {
None
} else {
Some(profile.as_str())
};
let instance_dir = manager.instances_dir.join(&config.name);
let selected = crate::instance::config_sync::switch_profile(
&config.name,
config.config_sync_profile.as_deref(),
target,
&manager.meta_dir,
&instance_dir,
)?;
config.config_sync_profile = selected;
manager.save(&config)?;
println!(
"Updated '{}' config profile to {}.",
name,
display_config_profile(config.config_sync_profile.as_deref())
);
Ok(())
}
fn display_config_profile(profile: Option<&str>) -> &str {
profile.unwrap_or(LOCAL_CONFIG_PROFILE)
}
fn is_local_profile_alias(profile: &str) -> bool {
let profile = profile.trim();
profile.eq_ignore_ascii_case("none")
|| profile.eq_ignore_ascii_case("default")
|| profile.eq_ignore_ascii_case("local")
|| profile.eq_ignore_ascii_case("instance-default")
|| profile.eq_ignore_ascii_case("instance default")
}
// maps --set key=value pairs to config fields. empty value = clear the field.
fn apply_config_update(
config: &mut crate::instance::InstanceConfig,
+7
View File
@@ -104,6 +104,13 @@ fn build_command() -> Command {
.arg(Arg::new("name").required(true).action(ArgAction::Set))
.arg(Arg::new("set").long("set").action(ArgAction::Set)),
)
.subcommand(
Command::new("profile")
.about("Show or set an instance config-sync profile")
.arg_required_else_help(true)
.arg(Arg::new("name").required(true).action(ArgAction::Set))
.arg(Arg::new("profile").action(ArgAction::Set)),
)
.subcommand(
Command::new("desktop")
.about("Toggle desktop shortcut for an instance")
+19 -3
View File
@@ -22,15 +22,31 @@ pub fn get_config_path() -> PathBuf {
fn ensure_config_exists() -> PathBuf {
let config_path = get_config_path().join("config.toml");
if !config_path.exists() {
if let Some(parent) = config_path.parent() {
let _ = fs::create_dir_all(parent);
if let Some(parent) = config_path.parent()
&& let Err(e) = fs::create_dir_all(parent)
{
tracing::warn!(
"Failed to create config directory {}: {}",
parent.display(),
e
);
}
let _ = fs::write(&config_path, include_str!("../../assets/config.toml"));
match fs::write(&config_path, include_str!("../../assets/config.toml")) {
Ok(()) => tracing::debug!("Wrote default config to {}", config_path.display()),
Err(e) => tracing::warn!(
"Failed to write default config to {}: {}",
config_path.display(),
e
),
}
} else {
tracing::trace!("Using existing config at {}", config_path.display());
}
config_path
}
pub fn load_config(config_path: &std::path::Path) -> Result<Config, ConfigError> {
tracing::debug!("Loading config from {}", config_path.display());
ConfigLoader::builder()
.add_source(File::from(config_path).required(false))
.build()?
+13
View File
@@ -5,6 +5,16 @@ use std::path::PathBuf;
use serde::Deserialize;
#[derive(Debug, Deserialize, Default, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ImageProtocol {
Halfblocks,
Quadrants,
#[default]
Kitty,
Iterm2,
}
#[derive(Debug, Deserialize, Default)]
pub struct General {}
@@ -102,6 +112,8 @@ impl Default for Defaults {
// timing knobs for the error toast animation: show for 5s, start sliding at 3.5s,
// fly off screen over 300ms. tweak these if the toasts feel too fast or slow.
pub struct Ui {
#[serde(default)]
pub image_protocol: ImageProtocol,
#[serde(default = "default_error_auto_dismiss_ms")]
pub error_auto_dismiss_ms: u64,
#[serde(default = "default_error_slide_start_ms")]
@@ -128,6 +140,7 @@ fn default_max_error_events() -> usize {
impl Default for Ui {
fn default() -> Self {
Self {
image_protocol: ImageProtocol::default(),
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(),
+677
View File
@@ -0,0 +1,677 @@
use std::path::{Path, PathBuf};
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ConfigSyncError {
#[error("Invalid config sync profile: {0}")]
InvalidProfile(String),
#[error("Config sync profile '{profile}' is already in use")]
AlreadyLocked { profile: String },
#[error("Cannot switch config profiles while '{instance}' is running")]
InstanceRunning { instance: String },
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
}
#[derive(Debug)]
pub struct ConfigSyncLock {
path: PathBuf,
}
impl Drop for ConfigSyncLock {
fn drop(&mut self) {
if let Err(e) = std::fs::remove_file(&self.path)
&& e.kind() != std::io::ErrorKind::NotFound
{
tracing::warn!("Failed to release config sync lock: {}", e);
}
}
}
pub fn prepare(
profile: Option<&str>,
meta_dir: &Path,
minecraft_dir: &Path,
) -> Result<Option<ConfigSyncLock>, ConfigSyncError> {
let Some(profile) = profile.and_then(normalize_profile) else {
return Ok(None);
};
validate_profile(profile)?;
let profile_dir = profile_dir(meta_dir, profile);
if !profile_dir.exists() {
return Ok(None);
}
let lock = acquire_lock(&profile_dir, profile)?;
if !profile_payload_exists(&profile_dir)? {
sync_to_profile(minecraft_dir, &profile_dir)?;
} else {
sync_from_profile(&profile_dir, minecraft_dir)?;
}
Ok(Some(lock))
}
pub fn finish(
profile: Option<&str>,
meta_dir: &Path,
minecraft_dir: &Path,
) -> Result<(), ConfigSyncError> {
let Some(profile) = profile.and_then(normalize_profile) else {
return Ok(());
};
validate_profile(profile)?;
sync_to_profile(minecraft_dir, &profile_dir(meta_dir, profile))
}
pub fn list_profiles(meta_dir: &Path) -> Result<Vec<String>, ConfigSyncError> {
let root = profiles_dir(meta_dir);
let mut profiles = Vec::new();
if !root.exists() {
return Ok(profiles);
}
for entry in std::fs::read_dir(root)? {
let entry = entry?;
if entry.file_type()?.is_dir() {
let name = entry.file_name().to_string_lossy().to_string();
if validate_profile(&name).is_ok() {
profiles.push(name);
}
}
}
profiles.sort_unstable();
Ok(profiles)
}
pub fn create_profile(meta_dir: &Path, profile: &str) -> Result<String, ConfigSyncError> {
let Some(profile) = normalize_profile(profile) else {
return Err(ConfigSyncError::InvalidProfile(profile.to_string()));
};
validate_profile(profile)?;
std::fs::create_dir_all(profile_dir(meta_dir, profile))?;
Ok(profile.to_string())
}
pub fn delete_profile(meta_dir: &Path, profile: &str) -> Result<(), ConfigSyncError> {
validate_profile(profile)?;
let dir = profile_dir(meta_dir, profile);
if dir.exists() {
remove_path(&dir)?;
}
Ok(())
}
pub fn switch_profile(
instance_name: &str,
current_profile: Option<&str>,
target_profile: Option<&str>,
meta_dir: &Path,
instance_dir: &Path,
) -> Result<Option<String>, ConfigSyncError> {
if crate::running::get(instance_name).is_some() {
return Err(ConfigSyncError::InstanceRunning {
instance: instance_name.to_string(),
});
}
let current_profile = current_profile.and_then(normalize_profile);
let target_profile = target_profile.and_then(normalize_profile);
if let Some(profile) = current_profile {
validate_profile(profile)?;
}
if let Some(profile) = target_profile {
validate_profile(profile)?;
}
if current_profile == target_profile {
return Ok(current_profile.map(str::to_string));
}
if let Some(profile) = current_profile {
let profile_dir = profile_dir(meta_dir, profile);
if profile_dir.exists() {
let _lock = acquire_lock(&profile_dir, profile)?;
finish(Some(profile), meta_dir, &minecraft_dir(instance_dir))?;
}
}
match (current_profile, target_profile) {
(None, Some(_)) => {
sync_to_profile(
&minecraft_dir(instance_dir),
&local_backup_dir(instance_dir),
)?;
}
(Some(_), None) => {
let backup = local_backup_dir(instance_dir);
if backup.exists() {
sync_from_profile(&backup, &minecraft_dir(instance_dir))?;
}
return Ok(None);
}
_ => {}
}
let Some(profile) = target_profile else {
return Ok(None);
};
let profile_dir = profile_dir(meta_dir, profile);
let _lock = acquire_lock(&profile_dir, profile)?;
if !profile_payload_exists(&profile_dir)? {
sync_to_profile(&minecraft_dir(instance_dir), &profile_dir)?;
}
sync_from_profile(&profile_dir, &minecraft_dir(instance_dir))?;
Ok(Some(profile.to_string()))
}
fn normalize_profile(profile: &str) -> Option<&str> {
let trimmed = profile.trim();
if trimmed.is_empty() {
None
} else {
Some(trimmed)
}
}
pub fn validate_profile(profile: &str) -> Result<(), ConfigSyncError> {
if profile.is_empty()
|| profile.len() > 64
|| profile.starts_with('.')
|| profile.contains('/')
|| profile.contains('\\')
|| profile.eq_ignore_ascii_case("default")
|| profile.eq_ignore_ascii_case("none")
|| profile.eq_ignore_ascii_case("local")
|| profile.eq_ignore_ascii_case("instance default")
|| profile.eq_ignore_ascii_case("local default")
|| profile
.chars()
.any(|c| c.is_control() || matches!(c, '<' | '>' | ':' | '"' | '|' | '?' | '*'))
{
return Err(ConfigSyncError::InvalidProfile(profile.to_string()));
}
Ok(())
}
fn profile_dir(meta_dir: &Path, profile: &str) -> PathBuf {
profiles_dir(meta_dir).join(profile)
}
fn profiles_dir(meta_dir: &Path) -> PathBuf {
meta_dir.join("config-sync").join("profiles")
}
fn minecraft_dir(instance_dir: &Path) -> PathBuf {
instance_dir.join(".minecraft")
}
fn local_backup_dir(instance_dir: &Path) -> PathBuf {
instance_dir
.join(".rmcl")
.join("config-sync")
.join("local-config")
}
fn acquire_lock(profile_dir: &Path, profile: &str) -> Result<ConfigSyncLock, ConfigSyncError> {
std::fs::create_dir_all(profile_dir)?;
let path = profile_dir.join(".lock");
match std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&path)
{
Ok(_) => Ok(ConfigSyncLock { path }),
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
Err(ConfigSyncError::AlreadyLocked {
profile: profile.to_string(),
})
}
Err(e) => Err(e.into()),
}
}
fn mirror_dir(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> {
if dst.exists() {
remove_path(dst)?;
}
std::fs::create_dir_all(dst)?;
if !src.exists() {
return Ok(());
}
copy_dir_contents(src, dst)
}
fn sync_to_profile(minecraft_dir: &Path, profile_dir: &Path) -> Result<(), ConfigSyncError> {
mirror_dir(&minecraft_dir.join("config"), &profile_dir.join("config"))?;
mirror_options(minecraft_dir, profile_dir)
}
fn sync_from_profile(profile_dir: &Path, minecraft_dir: &Path) -> Result<(), ConfigSyncError> {
mirror_dir(&profile_dir.join("config"), &minecraft_dir.join("config"))?;
mirror_options(profile_dir, minecraft_dir)
}
fn profile_payload_exists(profile_dir: &Path) -> Result<bool, ConfigSyncError> {
if profile_dir.join("config").exists() {
return Ok(true);
}
if !profile_dir.exists() {
return Ok(false);
}
for entry in std::fs::read_dir(profile_dir)? {
let entry = entry?;
if entry.file_type()?.is_file() && is_options_file(&entry.file_name().to_string_lossy()) {
return Ok(true);
}
}
Ok(false)
}
fn mirror_options(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> {
remove_options(dst)?;
std::fs::create_dir_all(dst)?;
if !src.exists() {
return Ok(());
}
for entry in std::fs::read_dir(src)? {
let entry = entry?;
let name = entry.file_name();
if entry.file_type()?.is_file() && is_options_file(&name.to_string_lossy()) {
std::fs::copy(entry.path(), dst.join(name))?;
}
}
Ok(())
}
fn remove_options(dir: &Path) -> Result<(), ConfigSyncError> {
if !dir.exists() {
return Ok(());
}
for entry in std::fs::read_dir(dir)? {
let entry = entry?;
if is_options_file(&entry.file_name().to_string_lossy()) {
remove_path(&entry.path())?;
}
}
Ok(())
}
fn is_options_file(name: &str) -> bool {
name == "options.txt" || name.starts_with("options") && name.ends_with(".txt")
}
fn remove_path(path: &Path) -> Result<(), ConfigSyncError> {
let meta = std::fs::symlink_metadata(path)?;
if meta.is_dir() {
std::fs::remove_dir_all(path)?;
} else {
std::fs::remove_file(path)?;
}
Ok(())
}
fn copy_dir_contents(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> {
for entry in std::fs::read_dir(src)? {
let entry = entry?;
let source = entry.path();
let target = dst.join(entry.file_name());
let file_type = entry.file_type()?;
if file_type.is_dir() {
std::fs::create_dir_all(&target)?;
copy_dir_contents(&source, &target)?;
} else if file_type.is_file() {
std::fs::copy(&source, &target)?;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn first_prepare_seeds_shared_config() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let minecraft = tmp.path().join("instance/.minecraft");
create_profile(&meta, "main").unwrap();
std::fs::create_dir_all(minecraft.join("config/nested")).unwrap();
std::fs::write(minecraft.join("options.txt"), "local-options").unwrap();
std::fs::write(minecraft.join("optionsshaders.txt"), "shader-options").unwrap();
std::fs::write(minecraft.join("config/options.txt"), "local-config").unwrap();
std::fs::write(minecraft.join("config/nested/mod.toml"), "nested").unwrap();
let _lock = prepare(Some("main"), &meta, &minecraft).unwrap();
assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/main/options.txt")).unwrap(),
"local-options"
);
assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/main/optionsshaders.txt"))
.unwrap(),
"shader-options"
);
assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/main/config/options.txt"))
.unwrap(),
"local-config"
);
assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/main/config/nested/mod.toml"))
.unwrap(),
"nested"
);
}
#[test]
fn prepare_mirrors_shared_config_into_instance() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let minecraft = tmp.path().join("instance/.minecraft");
std::fs::create_dir_all(meta.join("config-sync/profiles/main/config")).unwrap();
std::fs::create_dir_all(minecraft.join("config")).unwrap();
std::fs::write(
meta.join("config-sync/profiles/main/options.txt"),
"shared-options",
)
.unwrap();
std::fs::write(
meta.join("config-sync/profiles/main/config/shared.toml"),
"shared",
)
.unwrap();
std::fs::write(minecraft.join("options.txt"), "stale-options").unwrap();
std::fs::write(minecraft.join("config/local.toml"), "stale").unwrap();
let _lock = prepare(Some("main"), &meta, &minecraft).unwrap();
assert_eq!(
std::fs::read_to_string(minecraft.join("options.txt")).unwrap(),
"shared-options"
);
assert_eq!(
std::fs::read_to_string(minecraft.join("config/shared.toml")).unwrap(),
"shared"
);
assert!(!minecraft.join("config/local.toml").exists());
}
#[test]
fn finish_mirrors_instance_config_back_to_shared() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let minecraft = tmp.path().join("instance/.minecraft");
std::fs::create_dir_all(meta.join("config-sync/profiles/main/config")).unwrap();
std::fs::write(
meta.join("config-sync/profiles/main/config/old.toml"),
"old",
)
.unwrap();
std::fs::create_dir_all(minecraft.join("config")).unwrap();
std::fs::write(minecraft.join("options.txt"), "new-options").unwrap();
std::fs::write(minecraft.join("config/new.toml"), "new").unwrap();
finish(Some("main"), &meta, &minecraft).unwrap();
assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/main/options.txt")).unwrap(),
"new-options"
);
assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/main/config/new.toml"))
.unwrap(),
"new"
);
assert!(
!meta
.join("config-sync/profiles/main/config/old.toml")
.exists()
);
}
#[test]
fn lock_blocks_second_prepare() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let minecraft = tmp.path().join("instance/.minecraft");
create_profile(&meta, "main").unwrap();
std::fs::create_dir_all(minecraft.join("config")).unwrap();
let _lock = prepare(Some("main"), &meta, &minecraft).unwrap();
let err = prepare(Some("main"), &meta, &minecraft).unwrap_err();
assert!(matches!(err, ConfigSyncError::AlreadyLocked { .. }));
}
#[test]
fn profile_rejects_path_traversal() {
let tmp = tempfile::tempdir().unwrap();
let err = prepare(Some("../bad"), tmp.path(), tmp.path()).unwrap_err();
assert!(matches!(err, ConfigSyncError::InvalidProfile(_)));
}
#[test]
fn profile_rejects_builtin_names() {
for profile in [
"none",
"default",
"local",
"instance default",
"local default",
] {
let err = validate_profile(profile).unwrap_err();
assert!(matches!(err, ConfigSyncError::InvalidProfile(_)));
}
}
#[test]
fn prepare_ignores_deleted_profile() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let minecraft = tmp.path().join("instance/.minecraft");
std::fs::create_dir_all(minecraft.join("config")).unwrap();
let lock = prepare(Some("deleted"), &meta, &minecraft).unwrap();
assert!(lock.is_none());
assert!(!meta.join("config-sync/profiles/deleted").exists());
}
#[test]
fn create_profile_trims_and_lists_profiles() {
let tmp = tempfile::tempdir().unwrap();
let profile = create_profile(tmp.path(), " main ").unwrap();
let profiles = list_profiles(tmp.path()).unwrap();
assert_eq!(profile, "main");
assert_eq!(profiles, vec!["main"]);
}
#[test]
fn delete_profile_removes_profile_dir() {
let tmp = tempfile::tempdir().unwrap();
create_profile(tmp.path(), "main").unwrap();
delete_profile(tmp.path(), "main").unwrap();
assert!(list_profiles(tmp.path()).unwrap().is_empty());
}
#[test]
fn switch_to_profile_backs_up_local_config_and_restores_none() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let instance = tmp.path().join("instance");
let minecraft = instance.join(".minecraft");
std::fs::create_dir_all(minecraft.join("config")).unwrap();
std::fs::write(minecraft.join("options.txt"), "local-options").unwrap();
std::fs::write(minecraft.join("config/local.txt"), "local").unwrap();
let selected = switch_profile("inst", None, Some("main"), &meta, &instance).unwrap();
assert_eq!(selected.as_deref(), Some("main"));
assert_eq!(
std::fs::read_to_string(instance.join(".rmcl/config-sync/local-config/options.txt"))
.unwrap(),
"local-options"
);
assert_eq!(
std::fs::read_to_string(
instance.join(".rmcl/config-sync/local-config/config/local.txt")
)
.unwrap(),
"local"
);
std::fs::write(minecraft.join("options.txt"), "shared-options").unwrap();
std::fs::write(minecraft.join("config/shared.txt"), "shared").unwrap();
let selected = switch_profile("inst", Some("main"), None, &meta, &instance).unwrap();
assert_eq!(selected, None);
assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/main/options.txt")).unwrap(),
"shared-options"
);
assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/main/config/shared.txt"))
.unwrap(),
"shared"
);
assert_eq!(
std::fs::read_to_string(minecraft.join("options.txt")).unwrap(),
"local-options"
);
assert_eq!(
std::fs::read_to_string(minecraft.join("config/local.txt")).unwrap(),
"local"
);
assert!(!minecraft.join("config/shared.txt").exists());
}
#[test]
fn switch_from_deleted_profile_restores_local_without_recreating_profile() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let instance = tmp.path().join("instance");
let minecraft = instance.join(".minecraft");
std::fs::create_dir_all(minecraft.join("config")).unwrap();
std::fs::create_dir_all(instance.join(".rmcl/config-sync/local-config/config")).unwrap();
std::fs::write(minecraft.join("options.txt"), "deleted-profile-options").unwrap();
std::fs::write(
instance.join(".rmcl/config-sync/local-config/options.txt"),
"local-options",
)
.unwrap();
std::fs::write(
instance.join(".rmcl/config-sync/local-config/config/local.txt"),
"local",
)
.unwrap();
let selected = switch_profile("inst", Some("deleted"), None, &meta, &instance).unwrap();
assert_eq!(selected, None);
assert_eq!(
std::fs::read_to_string(minecraft.join("options.txt")).unwrap(),
"local-options"
);
assert_eq!(
std::fs::read_to_string(minecraft.join("config/local.txt")).unwrap(),
"local"
);
assert!(!meta.join("config-sync/profiles/deleted").exists());
}
#[test]
fn switch_between_profiles_saves_old_and_loads_new() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let instance = tmp.path().join("instance");
let minecraft = instance.join(".minecraft");
std::fs::create_dir_all(minecraft.join("config")).unwrap();
std::fs::write(minecraft.join("options.txt"), "changed-a-options").unwrap();
std::fs::write(minecraft.join("config/a.txt"), "changed-a").unwrap();
create_profile(&meta, "a").unwrap();
std::fs::create_dir_all(meta.join("config-sync/profiles/b/config")).unwrap();
std::fs::write(
meta.join("config-sync/profiles/b/options.txt"),
"profile-b-options",
)
.unwrap();
std::fs::write(
meta.join("config-sync/profiles/b/config/b.txt"),
"profile-b",
)
.unwrap();
let selected = switch_profile("inst", Some("a"), Some("b"), &meta, &instance).unwrap();
assert_eq!(selected.as_deref(), Some("b"));
assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/a/options.txt")).unwrap(),
"changed-a-options"
);
assert_eq!(
std::fs::read_to_string(meta.join("config-sync/profiles/a/config/a.txt")).unwrap(),
"changed-a"
);
assert_eq!(
std::fs::read_to_string(minecraft.join("options.txt")).unwrap(),
"profile-b-options"
);
assert_eq!(
std::fs::read_to_string(minecraft.join("config/b.txt")).unwrap(),
"profile-b"
);
assert!(!minecraft.join("config/a.txt").exists());
}
#[test]
fn second_instance_uses_profile_options_saved_by_first_instance() {
let tmp = tempfile::tempdir().unwrap();
let meta = tmp.path().join("meta");
let first = tmp.path().join("first/.minecraft");
let second_instance = tmp.path().join("second");
let second = second_instance.join(".minecraft");
std::fs::create_dir_all(first.join("config")).unwrap();
std::fs::create_dir_all(second.join("config")).unwrap();
std::fs::write(first.join("options.txt"), "first-default").unwrap();
std::fs::write(second.join("options.txt"), "second-local").unwrap();
create_profile(&meta, "main").unwrap();
let _lock = prepare(Some("main"), &meta, &first).unwrap();
std::fs::write(first.join("options.txt"), "changed-in-main").unwrap();
finish(Some("main"), &meta, &first).unwrap();
drop(_lock);
switch_profile("second", None, Some("main"), &meta, &second_instance).unwrap();
assert_eq!(
std::fs::read_to_string(second.join("options.txt")).unwrap(),
"changed-in-main"
);
assert_eq!(
std::fs::read_to_string(
second_instance.join(".rmcl/config-sync/local-config/options.txt")
)
.unwrap(),
"second-local"
);
}
}
+4 -4
View File
@@ -6,11 +6,11 @@ pub mod resource_packs;
pub mod shaders;
pub mod worlds;
pub use mods::{ContentEntry, scan_mods, toggle_entry};
pub use mods::scan_one_mod;
pub use resource_packs::{scan_resource_packs, scan_one_resource_pack};
pub use shaders::{scan_shaders, scan_one_shader};
pub use worlds::{scan_worlds, scan_one_world};
pub use mods::{ContentEntry, scan_mods, toggle_entry};
pub use resource_packs::{scan_one_resource_pack, scan_resource_packs};
pub use shaders::{scan_one_shader, scan_shaders};
pub use worlds::{scan_one_world, scan_worlds};
use std::io::Read;
+153 -4
View File
@@ -13,6 +13,7 @@ use serde::Deserialize;
// where each character cell shows two vertical pixels (fg = top, bg = bottom)
#[derive(Debug, Clone, Copy)]
pub struct IconCell {
pub symbol: char,
pub bg_r: u8,
pub bg_g: u8,
pub bg_b: u8,
@@ -153,12 +154,22 @@ pub fn scan_mods(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry>
fn read_mod_metadata(jar_path: &Path) -> (String, String, Option<Vec<u8>>) {
let file = match std::fs::File::open(jar_path) {
Ok(file) => file,
Err(_) => return (String::new(), String::new(), None),
Err(e) => {
tracing::trace!("Failed to open mod JAR {}: {}", jar_path.display(), e);
return (String::new(), String::new(), None);
}
};
let mut archive = match zip::ZipArchive::new(file) {
Ok(archive) => archive,
Err(_) => return (String::new(), String::new(), None),
Err(e) => {
tracing::trace!(
"Failed to read mod JAR as ZIP {}: {}",
jar_path.display(),
e
);
return (String::new(), String::new(), None);
}
};
// try each loader's metadata in order. if we get metadata but the
@@ -180,12 +191,23 @@ fn read_mod_metadata(jar_path: &Path) -> (String, String, Option<Vec<u8>>) {
read_zip_bytes(&mut archive, icon_path)
}
.or_else(|| try_fallback_icons(&mut archive));
tracing::trace!(
"Read mod metadata from {}: name='{}' icon_declared={}",
jar_path.display(),
name,
!icon_path.is_empty()
);
return (name, description, icon);
}
}
// no recognized metadata at all, try common icon paths
let icon_bytes = try_fallback_icons(&mut archive);
tracing::trace!(
"No recognized mod metadata in {}; fallback_icon={}",
jar_path.display(),
icon_bytes.is_some()
);
(String::new(), String::new(), icon_bytes)
}
@@ -354,6 +376,14 @@ pub(crate) fn make_icon_pixels(
height: u16,
) -> Option<Vec<Vec<IconCell>>> {
let img = image::load_from_memory(bytes).ok()?;
Some(make_icon_pixels_from_image(&img, width, height))
}
pub(crate) fn make_icon_pixels_from_image(
img: &image::DynamicImage,
width: u16,
height: u16,
) -> Vec<Vec<IconCell>> {
let resized = img.resize_exact(
u32::from(width),
u32::from(height) * 2,
@@ -370,6 +400,7 @@ pub(crate) fn make_icon_pixels(
let [tr, tg, tb] = rgb.get_pixel(u32::from(col), top_y).0;
let [br, bg, bb] = rgb.get_pixel(u32::from(col), bottom_y).0;
cols.push(IconCell {
symbol: '\u{2584}',
bg_r: br,
bg_g: bg,
bg_b: bb,
@@ -381,12 +412,110 @@ pub(crate) fn make_icon_pixels(
rows.push(cols);
}
Some(rows)
rows
}
pub(crate) fn make_icon_quadrants_from_image(
img: &image::DynamicImage,
width: u16,
height: u16,
) -> Vec<Vec<IconCell>> {
let resized = img
.resize_exact(
u32::from(width) * 2,
u32::from(height) * 2,
image::imageops::FilterType::Lanczos3,
)
.to_rgb8();
(0..height)
.map(|row| {
(0..width)
.map(|col| {
let x = u32::from(col) * 2;
let y = u32::from(row) * 2;
let pixels = [
resized.get_pixel(x, y).0,
resized.get_pixel(x + 1, y).0,
resized.get_pixel(x, y + 1).0,
resized.get_pixel(x + 1, y + 1).0,
];
quadrant_cell(pixels)
})
.collect()
})
.collect()
}
fn quadrant_cell(pixels: [[u8; 3]; 4]) -> IconCell {
let mut pair = (0, 0);
let mut max_distance = 0;
for left in 0..pixels.len() {
for right in (left + 1)..pixels.len() {
let distance = color_distance(pixels[left], pixels[right]);
if distance > max_distance {
max_distance = distance;
pair = (left, right);
}
}
}
let bg = pixels[pair.0];
let fg = pixels[pair.1];
let mask = pixels
.iter()
.enumerate()
.fold(0_u8, |mask, (index, pixel)| {
if color_distance(*pixel, fg) <= color_distance(*pixel, bg) {
mask | (1 << index)
} else {
mask
}
});
let symbol = match mask {
0 => ' ',
1 => '\u{2598}',
2 => '\u{259d}',
3 => '\u{2580}',
4 => '\u{2596}',
5 => '\u{258c}',
6 => '\u{259e}',
7 => '\u{259b}',
8 => '\u{2597}',
9 => '\u{259a}',
10 => '\u{2590}',
11 => '\u{259c}',
12 => '\u{2584}',
13 => '\u{2599}',
14 => '\u{259f}',
_ => '\u{2588}',
};
IconCell {
symbol,
bg_r: bg[0],
bg_g: bg[1],
bg_b: bg[2],
fg_r: fg[0],
fg_g: fg[1],
fg_b: fg[2],
}
}
fn color_distance(left: [u8; 3], right: [u8; 3]) -> u32 {
left.into_iter()
.zip(right)
.map(|(left, right)| {
let delta = i32::from(left) - i32::from(right);
(delta * delta) as u32
})
.sum()
}
// 6x3 fallback icon showing a "?" pattern for mods without icons.
pub(super) fn fallback_icon() -> Vec<Vec<IconCell>> {
let b = IconCell {
symbol: '\u{2584}',
bg_r: 50,
bg_g: 50,
bg_b: 50,
@@ -395,6 +524,7 @@ pub(super) fn fallback_icon() -> Vec<Vec<IconCell>> {
fg_b: 50,
};
let tb = IconCell {
symbol: '\u{2584}',
bg_r: 50,
bg_g: 50,
bg_b: 50,
@@ -403,6 +533,7 @@ pub(super) fn fallback_icon() -> Vec<Vec<IconCell>> {
fg_b: 130,
};
let bt = IconCell {
symbol: '\u{2584}',
bg_r: 130,
bg_g: 130,
bg_b: 130,
@@ -420,6 +551,7 @@ pub(super) fn fallback_icon() -> Vec<Vec<IconCell>> {
// 12x6 fallback icon showing a "?" pattern for worlds without icons.
pub(super) fn fallback_icon_large() -> Vec<Vec<IconCell>> {
let b = IconCell {
symbol: '\u{2584}',
bg_r: 50,
bg_g: 50,
bg_b: 50,
@@ -428,6 +560,7 @@ pub(super) fn fallback_icon_large() -> Vec<Vec<IconCell>> {
fg_b: 50,
};
let tb = IconCell {
symbol: '\u{2584}',
bg_r: 50,
bg_g: 50,
bg_b: 50,
@@ -436,6 +569,7 @@ pub(super) fn fallback_icon_large() -> Vec<Vec<IconCell>> {
fg_b: 130,
};
let bt = IconCell {
symbol: '\u{2584}',
bg_r: 130,
bg_g: 130,
bg_b: 130,
@@ -476,6 +610,20 @@ pub fn toggle_entry(entry: &ContentEntry) -> Result<(), std::io::Error> {
mod tests {
use super::*;
#[test]
fn quadrant_raster_has_requested_dimensions() {
let image = image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(
2,
2,
image::Rgb([12, 34, 56]),
));
let rows = make_icon_quadrants_from_image(&image, 7, 3);
assert_eq!(rows.len(), 3);
assert!(rows.iter().all(|row| row.len() == 7));
assert!(rows.iter().flatten().all(|cell| cell.symbol == '\u{2588}'));
}
fn setup_mods_dir(tmp: &Path, instance: &str) -> PathBuf {
let dir = tmp.join(instance).join(".minecraft").join("mods");
std::fs::create_dir_all(&dir).unwrap();
@@ -742,7 +890,8 @@ description = "A neoforge mod"
fn scan_mods_prefers_neoforge_toml_over_forge_toml() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_mods_dir(tmp.path(), "inst");
let neoforge = "[[mods]]\ndisplayName = \"NeoForge Name\"\ndescription = \"neoforge desc\"\n";
let neoforge =
"[[mods]]\ndisplayName = \"NeoForge Name\"\ndescription = \"neoforge desc\"\n";
let forge = "[[mods]]\ndisplayName = \"Forge Name\"\ndescription = \"forge desc\"\n";
make_jar(
&dir,
-1
View File
@@ -89,4 +89,3 @@ fn read_shader_metadata_from_dir(dir: &Path) -> (String, Option<Vec<u8>>) {
(description, icon_bytes)
}
-1
View File
@@ -134,4 +134,3 @@ fn format_size(bytes: u64) -> String {
format!("{:.2} GB", bytes as f64 / (1024.0 * 1024.0 * 1024.0))
}
}
+48
View File
@@ -51,6 +51,11 @@ impl MmcPack {
pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
let pack = parse_mmc_pack(path)?;
tracing::debug!(
"Parsed MultiMC pack {} with {} component(s)",
path.display(),
pack.components.len()
);
let game_version = pack
.game_version()
@@ -62,6 +67,15 @@ pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
let name = instance_name_from_cfg(path).unwrap_or_else(|| "Imported Pack".to_string());
let (mod_count, override_count) = count_content_files(path)?;
tracing::trace!(
"MultiMC summary: name='{}' game_version={} loader={:?} loader_version={:?} mods={} overrides={}",
name,
game_version,
loader,
loader_version,
mod_count,
override_count
);
Ok(ImportSummary {
name,
@@ -81,6 +95,11 @@ pub async fn execute_import(
manager: &InstanceManager,
) -> Result<crate::instance::InstanceConfig, Box<dyn std::error::Error + Send + Sync>> {
let name = super::unique_instance_name(&summary.name, &manager.instances_dir);
tracing::info!(
"Importing MultiMC/Prism pack '{}' as instance '{}'",
summary.name,
name
);
progress::set_action(format!("Importing '{name}'..."));
progress::set_sub_action(format!("{} {}", summary.game_version, summary.loader));
@@ -99,6 +118,11 @@ pub async fn execute_import(
extract_mmc_archive(&summary.archive_path, &minecraft_dir)?;
progress::clear();
tracing::info!(
"Imported MultiMC/Prism pack '{}' as '{}'",
summary.name,
name
);
Ok(config)
}
@@ -117,8 +141,16 @@ fn extract_mmc_archive(
let prefix = find_archive_prefix(&archive);
let minecraft_prefix = format!("{prefix}.minecraft/");
tracing::debug!(
"Extracting MultiMC archive {} with prefix '{}' into {}",
archive_path.display(),
prefix,
minecraft_dir.display()
);
let total = archive.len();
let mut extracted = 0usize;
let mut dirs = 0usize;
for i in 0..total {
let mut entry = archive.by_index(i)?;
let entry_name = entry.name().to_string();
@@ -129,6 +161,7 @@ fn extract_mmc_archive(
if relative.is_empty() || entry_name.ends_with('/') {
std::fs::create_dir_all(minecraft_dir.join(relative))?;
dirs += 1;
continue;
}
@@ -142,9 +175,22 @@ fn extract_mmc_archive(
let mut buf = Vec::new();
entry.read_to_end(&mut buf)?;
tracing::trace!(
"Extracting MultiMC entry {} to {} ({} bytes)",
entry_name,
dest.display(),
buf.len()
);
std::fs::write(&dest, &buf)?;
extracted += 1;
}
tracing::debug!(
"Extracted {} files and {} directories from MultiMC archive {}",
extracted,
dirs,
archive_path.display()
);
Ok(())
}
@@ -167,6 +213,7 @@ fn instance_name_from_cfg(path: &Path) -> Option<String> {
let mut archive = zip::ZipArchive::new(file).ok()?;
let entry_name = find_entry(&archive, "instance.cfg")?;
tracing::trace!("Reading instance name from {}", entry_name);
let entry = archive.by_name(&entry_name).ok()?;
let reader = std::io::BufRead::lines(std::io::BufReader::new(entry));
@@ -174,6 +221,7 @@ fn instance_name_from_cfg(path: &Path) -> Option<String> {
if let Some(value) = line.strip_prefix("name=") {
let name = value.trim().to_string();
if !name.is_empty() {
tracing::debug!("Read MultiMC instance name '{}' from instance.cfg", name);
return Some(name);
}
}
+43 -17
View File
@@ -33,6 +33,7 @@ pub fn parse_import_input(input: &str) -> ImportInput {
|| input.starts_with('/')
|| input.starts_with("~/")
{
tracing::debug!("Import input resolved as local file: {}", input);
return ImportInput::LocalFile(input.to_string());
}
@@ -41,7 +42,7 @@ pub fn parse_import_input(input: &str) -> ImportInput {
.or_else(|| input.strip_prefix("http://modrinth.com/modpack/"))
{
let parts: Vec<&str> = rest.split('/').filter(|s| !s.is_empty()).collect();
return match parts.as_slice() {
let parsed = match parts.as_slice() {
[slug, "version", version_id, ..] => ImportInput::VersionId {
slug: slug.to_string(),
version_id: version_id.to_string(),
@@ -49,8 +50,11 @@ pub fn parse_import_input(input: &str) -> ImportInput {
[slug, ..] => ImportInput::ProjectSlug(slug.to_string()),
[] => ImportInput::ProjectSlug(String::new()),
};
tracing::debug!("Import input resolved as Modrinth URL: {:?}", parsed);
return parsed;
}
tracing::debug!("Import input resolved as Modrinth project slug: {}", input);
ImportInput::ProjectSlug(input.to_string())
}
@@ -70,12 +74,14 @@ pub struct ImportSummary {
// peeks inside a zip to figure out what format it is.
// checks for modrinth.index.json first, then mmc-pack.json.
pub fn detect_format(path: &Path) -> Result<PackFormat, String> {
tracing::debug!("Detecting modpack format for {}", path.display());
let file =
std::fs::File::open(path).map_err(|e| format!("Cannot open '{}': {e}", path.display()))?;
let archive =
zip::ZipArchive::new(file).map_err(|e| format!("Invalid ZIP '{}': {e}", path.display()))?;
if archive.file_names().any(|n| n == "modrinth.index.json") {
tracing::debug!("Detected Modrinth .mrpack archive: {}", path.display());
return Ok(PackFormat::Mrpack);
}
@@ -84,21 +90,36 @@ pub fn detect_format(path: &Path) -> Result<PackFormat, String> {
.file_names()
.any(|n| n == "mmc-pack.json" || n.ends_with("/mmc-pack.json"))
{
tracing::debug!("Detected MultiMC/Prism archive: {}", path.display());
return Ok(PackFormat::Mmc);
}
tracing::warn!("Unknown modpack archive format: {}", path.display());
Err("Unknown pack format: no modrinth.index.json or mmc-pack.json found".to_string())
}
pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
if !path.exists() {
tracing::warn!("Cannot import missing file {}", path.display());
return Err(format!("File not found: {}", path.display()));
}
let format = detect_format(path)?;
match format {
let summary = match format {
PackFormat::Mrpack => mrpack::build_summary(path),
PackFormat::Mmc => mmc::build_summary(path),
}
}?;
tracing::debug!(
"Built import summary for {}: name='{}' format={:?} mc={} loader={} loader_version={:?} mods={} overrides={}",
path.display(),
summary.name,
summary.format,
summary.game_version,
summary.loader,
summary.loader_version,
summary.mod_count,
summary.override_count
);
Ok(summary)
}
pub fn unique_instance_name(base: &str, instances_dir: &Path) -> String {
@@ -108,6 +129,7 @@ pub fn unique_instance_name(base: &str, instances_dir: &Path) -> String {
.join("instance.json")
.exists()
{
tracing::trace!("Import instance name '{}' is available", candidate);
return candidate;
}
for n in 2..100 {
@@ -117,9 +139,18 @@ pub fn unique_instance_name(base: &str, instances_dir: &Path) -> String {
.join("instance.json")
.exists()
{
tracing::debug!(
"Import instance name '{}' collided; using '{}'",
base,
candidate
);
return candidate;
}
}
tracing::warn!(
"Import instance name '{}' had many collisions; using fallback suffix",
base
);
format!("{base} (import)")
}
@@ -127,6 +158,12 @@ pub async fn execute_import(
summary: &ImportSummary,
manager: &InstanceManager,
) -> Result<crate::instance::InstanceConfig, Box<dyn std::error::Error + Send + Sync>> {
tracing::info!(
"Executing {:?} import '{}' from {}",
summary.format,
summary.name,
summary.archive_path.display()
);
match summary.format {
PackFormat::Mrpack => mrpack::execute_import(summary, manager).await,
PackFormat::Mmc => mmc::execute_import(summary, manager).await,
@@ -154,11 +191,7 @@ mod tests {
#[test]
fn detect_format_recognises_mrpack() {
let tmp = tempfile::tempdir().unwrap();
let path = make_pack_zip(
tmp.path(),
"pack.mrpack",
&[("modrinth.index.json", b"{}")],
);
let path = make_pack_zip(tmp.path(), "pack.mrpack", &[("modrinth.index.json", b"{}")]);
assert_eq!(detect_format(&path), Ok(PackFormat::Mrpack));
}
@@ -176,11 +209,7 @@ mod tests {
// mmc-pack.json one directory deep - the more common layout where
// the archive wraps everything in a named directory.
let tmp = tempfile::tempdir().unwrap();
let path = make_pack_zip(
tmp.path(),
"pack.zip",
&[("MyPack/mmc-pack.json", b"{}")],
);
let path = make_pack_zip(tmp.path(), "pack.zip", &[("MyPack/mmc-pack.json", b"{}")]);
assert_eq!(detect_format(&path), Ok(PackFormat::Mmc));
}
@@ -192,10 +221,7 @@ mod tests {
let path = make_pack_zip(
tmp.path(),
"weird.zip",
&[
("modrinth.index.json", b"{}"),
("mmc-pack.json", b"{}"),
],
&[("modrinth.index.json", b"{}"), ("mmc-pack.json", b"{}")],
);
assert_eq!(detect_format(&path), Ok(PackFormat::Mrpack));
}
+66 -4
View File
@@ -12,6 +12,13 @@ use super::{ImportSummary, PackFormat};
pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
let index = crate::net::modrinth::parse_mrpack(path)?;
tracing::debug!(
"Parsed .mrpack '{}' version_id={} files={} deps={}",
index.name,
index.version_id,
index.files.len(),
index.dependencies.len()
);
let game_version = crate::net::modrinth::game_version_from_dependencies(&index.dependencies)
.ok_or_else(|| "Manifest missing minecraft dependency".to_string())?;
@@ -21,6 +28,13 @@ pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
let loader = loader_opt.unwrap_or(ModLoader::Vanilla);
let override_count = count_overrides(path).unwrap_or(0);
tracing::trace!(
".mrpack summary: game_version={} loader={:?} loader_version={:?} overrides={}",
game_version,
loader,
loader_version,
override_count
);
Ok(ImportSummary {
name: index.name.clone(),
@@ -54,6 +68,11 @@ pub async fn execute_import(
manager: &InstanceManager,
) -> Result<crate::instance::InstanceConfig, Box<dyn std::error::Error + Send + Sync>> {
let name = super::unique_instance_name(&summary.name, &manager.instances_dir);
tracing::info!(
"Importing Modrinth pack '{}' as instance '{}'",
summary.name,
name
);
progress::set_action(format!("Importing '{name}'..."));
progress::set_sub_action(format!("{} {}", summary.game_version, summary.loader));
@@ -78,6 +97,7 @@ pub async fn execute_import(
extract_overrides(&summary.archive_path, &minecraft_dir)?;
progress::clear();
tracing::info!("Imported Modrinth pack '{}' as '{}'", summary.name, name);
Ok(config)
}
@@ -93,6 +113,12 @@ async fn download_mod_files(
let client = crate::net::HttpClient::new();
let total = index.files.len();
let completed = Arc::new(AtomicUsize::new(0));
tracing::debug!(
"Downloading {} file(s) from .mrpack '{}' into {}",
total,
index.name,
minecraft_dir.display()
);
progress::set_action(format!("Downloading mods... 0/{total}"));
@@ -107,6 +133,9 @@ async fn download_mod_files(
let client = client.clone();
let dest = minecraft_dir.join(&file.path);
let url = file.downloads.first().cloned().unwrap_or_default();
if url.is_empty() {
tracing::warn!(".mrpack file '{}' has no download URL", file.path);
}
let filename = file
.path
.rsplit('/')
@@ -115,10 +144,17 @@ async fn download_mod_files(
.to_string();
let completed = completed.clone();
tasks.spawn(async move {
if let Some(parent) = dest.parent() {
let _ = tokio::fs::create_dir_all(parent).await;
if let Some(parent) = dest.parent()
&& let Err(e) = tokio::fs::create_dir_all(parent).await
{
tracing::warn!(
"Failed to create mod download directory {}: {}",
parent.display(),
e
);
}
progress::set_sub_action(filename);
tracing::trace!("Downloading .mrpack file to {}", dest.display());
crate::net::download_file(&client, &url, &dest, |_, _| {}).await?;
let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
progress::set_action(format!("Downloading mods... {done}/{total}"));
@@ -136,6 +172,9 @@ async fn download_mod_files(
let client = client.clone();
let dest = minecraft_dir.join(&file.path);
let url = file.downloads.first().cloned().unwrap_or_default();
if url.is_empty() {
tracing::warn!(".mrpack file '{}' has no download URL", file.path);
}
let filename = file
.path
.rsplit('/')
@@ -144,10 +183,17 @@ async fn download_mod_files(
.to_string();
let completed = completed.clone();
tasks.spawn(async move {
if let Some(parent) = dest.parent() {
let _ = tokio::fs::create_dir_all(parent).await;
if let Some(parent) = dest.parent()
&& let Err(e) = tokio::fs::create_dir_all(parent).await
{
tracing::warn!(
"Failed to create mod download directory {}: {}",
parent.display(),
e
);
}
progress::set_sub_action(filename);
tracing::trace!("Downloading .mrpack file to {}", dest.display());
crate::net::download_file(&client, &url, &dest, |_, _| {}).await?;
let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
progress::set_action(format!("Downloading mods... {done}/{total}"));
@@ -175,6 +221,8 @@ fn extract_overrides(
let file = std::fs::File::open(mrpack_path)?;
let mut archive = zip::ZipArchive::new(file)?;
let mut extracted = 0usize;
let mut dirs = 0usize;
for i in 0..archive.len() {
let mut entry = archive.by_index(i)?;
@@ -191,6 +239,7 @@ fn extract_overrides(
if relative.is_empty() || entry_name.ends_with('/') {
let dir = minecraft_dir.join(relative);
std::fs::create_dir_all(dir)?;
dirs += 1;
continue;
}
@@ -201,8 +250,21 @@ fn extract_overrides(
let mut buf = Vec::new();
entry.read_to_end(&mut buf)?;
tracing::trace!(
"Extracting .mrpack override {} to {} ({} bytes)",
entry_name,
dest.display(),
buf.len()
);
std::fs::write(&dest, &buf)?;
extracted += 1;
}
tracing::debug!(
"Extracted {} override files and {} directories from {}",
extracted,
dirs,
mrpack_path.display()
);
Ok(())
}
+242 -13
View File
@@ -2,6 +2,7 @@
// handles classpath assembly, auth token injection, and log capture.
// loader-specific patches live in submodules (e.g. patches.rs for lwjgl3ify).
pub(crate) mod parser;
mod patches;
use std::path::{Path, PathBuf};
@@ -27,8 +28,22 @@ pub enum LaunchError {
Json(#[from] serde_json::Error),
#[error("{0} launch is not yet supported")]
NotSupported(String),
#[error("This instance requires Java {required}, but rmcl is using Java {detected}: {java}")]
JavaTooOld {
java: String,
required: u32,
detected: u32,
},
#[error("This instance requires Java {required}, but rmcl could not check {java}: {reason}")]
JavaCheckFailed {
java: String,
required: u32,
reason: String,
},
#[error("{0}")]
Auth(String),
#[error("Config sync error: {0}")]
ConfigSync(#[from] crate::instance::config_sync::ConfigSyncError),
}
fn build_game_args(
@@ -41,6 +56,68 @@ fn build_game_args(
Ok((rendered.jvm, rendered.game))
}
fn parse_java_major_version(text: &str) -> Option<u32> {
let quoted = text
.split_once('"')
.and_then(|(_, rest)| rest.split_once('"').map(|(version, _)| version));
let token = quoted.or_else(|| {
let start = text.find(|c: char| c.is_ascii_digit())?;
Some(&text[start..])
})?;
let parts: Vec<u32> = token
.split(|c: char| !c.is_ascii_digit())
.filter(|part| !part.is_empty())
.filter_map(|part| part.parse::<u32>().ok())
.collect();
match parts.as_slice() {
[1, legacy_major, ..] => Some(*legacy_major),
[major, ..] => Some(*major),
[] => None,
}
}
async fn check_java_version(java: &str, required: Option<u32>) -> Result<(), LaunchError> {
let Some(required) = required.filter(|major| *major > 0) else {
return Ok(());
};
let output = tokio::process::Command::new(java)
.arg("-version")
.output()
.await
.map_err(|e| LaunchError::JavaCheckFailed {
java: java.to_owned(),
required,
reason: e.to_string(),
})?;
let version_text = format!(
"{}{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
let detected =
parse_java_major_version(&version_text).ok_or_else(|| LaunchError::JavaCheckFailed {
java: java.to_owned(),
required,
reason: format!("could not parse `java -version` output: {version_text:?}"),
})?;
if detected < required {
return Err(LaunchError::JavaTooOld {
java: java.to_owned(),
required,
detected,
});
}
Ok(())
}
// existing installs from rmcl <= 0.3.0 have meta.json files in the
// stripped legacy format (no `arguments`, no `minecraftArguments`). every
// real upstream profile has at least one of those fields. on detecting the
@@ -333,6 +410,11 @@ pub async fn build_launch_invocation(
// so we check there first.
let has_local_libs = matches!(config.loader, ModLoader::Forge | ModLoader::NeoForge);
let local_lib_dir = minecraft_dir.join("libraries");
let library_directory = if has_local_libs {
&local_lib_dir
} else {
&lib_dir
};
let mut classpath: Vec<PathBuf> = Vec::new();
for lib in &merged_profile.libraries {
@@ -406,6 +488,15 @@ pub async fn build_launch_invocation(
})
.unwrap_or_else(crate::net::detect_java_path);
check_java_version(
&java,
merged_profile
.java_version
.as_ref()
.map(|version| version.major_version),
)
.await?;
let assets_root = meta_dir.join("assets");
let natives_dir = meta_dir
.join("versions")
@@ -413,7 +504,7 @@ pub async fn build_launch_invocation(
.join("natives");
let version_type = merged_profile.type_.as_deref().unwrap_or("release");
let template_ctx = TemplateContext {
library_directory: &lib_dir,
library_directory,
classpath_separator: sep,
version_name: &config.game_version,
version_type,
@@ -522,6 +613,23 @@ pub async fn launch(
};
let invocation = build_launch_invocation(config, instances_dir, meta_dir, &auth).await?;
tracing::debug!(
"[{}] Prepared launch invocation: working_dir={} classpath_entries={} jvm_args={} extra_args={} game_args={} main_class={}",
name,
invocation.working_dir.display(),
invocation.classpath.len(),
invocation.jvm_args.len(),
invocation.extra_args.len(),
invocation.game_args.len(),
invocation.main_class
);
let config_sync_profile = config.config_sync_profile.clone();
let config_sync_lock = crate::instance::config_sync::prepare(
config_sync_profile.as_deref(),
meta_dir,
&invocation.working_dir,
)?;
let config_sync_active = config_sync_lock.is_some();
let (kill_tx, kill_rx) = tokio::sync::oneshot::channel::<()>();
crate::running::register_kill(&name, kill_tx);
@@ -562,17 +670,28 @@ pub async fn launch(
Err(e) => {
crate::running::cleanup_kill_sender(&name);
crate::running::remove(&name);
tracing::error!("[{}] Failed to spawn Minecraft process: {}", name, e);
return Err(LaunchError::Io(e));
}
};
tracing::debug!("[{}] Spawned Minecraft process", name);
crate::running::set_state(&name, crate::running::RunState::Running);
let log_file_path = crate::instance::log_files::create_log_file(instances_dir, &name);
match &log_file_path {
Some(path) => tracing::debug!(
"[{}] Writing Minecraft process log to {}",
name,
path.display()
),
None => tracing::warn!("[{}] Could not create Minecraft process log file", name),
}
let name_for_task = name.clone();
let instances_dir_owned = instances_dir.to_path_buf();
let meta_dir_owned = meta_dir.to_path_buf();
let minecraft_dir_owned = invocation.working_dir.clone();
// spawn a background task to babysit the child process: capture stdout/stderr
// into both the TUI log viewer and a timestamped log file on disk
@@ -580,63 +699,131 @@ pub async fn launch(
use std::io::Write;
use std::sync::{Arc, Mutex};
use tokio::io::AsyncBufReadExt;
use tokio::sync::mpsc;
use tokio::time::{Duration, sleep};
use crate::instance::launch::parser::{LogStream, MinecraftLogParser};
let log_writer: Arc<Mutex<Option<std::fs::File>>> = Arc::new(Mutex::new(
log_file_path.and_then(|p| std::fs::File::create(p).ok()),
));
let (log_tx, mut log_rx) = mpsc::channel::<(LogStream, String)>(1024);
let parser_name = name_for_task.clone();
let parser_task = tokio::spawn(async move {
let mut parser = MinecraftLogParser::new();
let idle_flush = Duration::from_millis(150);
loop {
tokio::select! {
maybe_line = log_rx.recv() => {
match maybe_line {
Some((stream, line)) => {
for event in parser.push_line(stream, line) {
emit_parsed_instance_log(&parser_name, event);
}
}
None => break,
}
}
_ = sleep(idle_flush), if parser.has_pending() => {
if let Some(event) = parser.flush() {
emit_parsed_instance_log(&parser_name, event);
}
}
}
}
if let Some(event) = parser.flush() {
emit_parsed_instance_log(&parser_name, event);
}
});
if let Some(stdout) = child.stdout.take() {
let n = name_for_task.clone();
let w = log_writer.clone();
let tx = log_tx.clone();
let mut lines = tokio::io::BufReader::new(stdout).lines();
tokio::spawn(async move {
while let Ok(Some(line)) = lines.next_line().await {
tracing::info!(target: "mc_instance", "[{}] {}", n, line);
crate::instance_logs::push(&n, &line);
if let Ok(mut f) = w.lock()
&& let Some(f) = f.as_mut()
{
let _ = writeln!(f, "{}", line);
}
if tx.send((LogStream::Stdout, line)).await.is_err() {
break;
}
}
tracing::trace!("Minecraft stdout capture task ended");
});
}
if let Some(stderr) = child.stderr.take() {
let n = name_for_task.clone();
let w = log_writer.clone();
let tx = log_tx.clone();
let mut lines = tokio::io::BufReader::new(stderr).lines();
tokio::spawn(async move {
while let Ok(Some(line)) = lines.next_line().await {
tracing::warn!(target: "mc_instance", "[{}] {}", n, line);
crate::instance_logs::push(&n, &line);
if let Ok(mut f) = w.lock()
&& let Some(f) = f.as_mut()
{
let _ = writeln!(f, "[STDERR] {}", line);
let _ = writeln!(f, "{}", line);
}
if tx.send((LogStream::Stderr, line)).await.is_err() {
break;
}
}
tracing::trace!("Minecraft stderr capture task ended");
});
}
drop(log_tx);
// wait for either the process to exit naturally or a kill signal from the TUI
let code = tokio::select! {
let (code, killed_by_user) = tokio::select! {
_ = kill_rx => {
tracing::info!("[{}] Kill requested, terminating process", name_for_task);
let _ = child.kill().await;
let _ = child.wait().await;
None
(None, true)
}
result = child.wait() => {
result.ok().and_then(|s| s.code())
(result.ok().and_then(|s| s.code()), false)
}
};
let _ = parser_task.await;
tracing::info!("[{}] Exited with code {:?}", name_for_task, code);
if code == Some(0) {
if config_sync_active
&& let Err(e) = crate::instance::config_sync::finish(
config_sync_profile.as_deref(),
&meta_dir_owned,
&minecraft_dir_owned,
)
{
tracing::warn!("Failed to sync config for '{}': {}", name_for_task, e);
}
drop(config_sync_lock);
if code == Some(0) || killed_by_user {
crate::running::remove(&name_for_task);
tracing::debug!(
"[{}] Cleared running state after normal exit (killed_by_user={})",
name_for_task,
killed_by_user
);
} else {
crate::running::set_state(&name_for_task, crate::running::RunState::Crashed(code));
crate::tui::error_buffer::push_error(crate::tui::error_buffer::ErrorEvent {
id: 0,
level: tracing::Level::ERROR,
message: match code {
Some(code) => {
format!("Minecraft '{name_for_task}' crashed with exit code {code}")
}
None => format!("Minecraft '{name_for_task}' crashed without an exit code"),
},
pushed_at: std::time::Instant::now(),
});
}
let manager = crate::instance::InstanceManager::new(instances_dir_owned, meta_dir_owned);
@@ -654,10 +841,47 @@ pub async fn launch(
Ok(())
}
fn emit_parsed_instance_log(
instance_name: &str,
event: crate::instance::launch::parser::ParsedLogEvent,
) {
let text = event.lines.join("\n");
match event.level {
crate::instance::launch::parser::LogLevel::Error => {
tracing::error!(target: "mc_instance", "[{}] {}", instance_name, text);
}
crate::instance::launch::parser::LogLevel::Warn => {
tracing::warn!(target: "mc_instance", "[{}] {}", instance_name, text);
}
crate::instance::launch::parser::LogLevel::Info => {
tracing::info!(target: "mc_instance", "[{}] {}", instance_name, text);
}
crate::instance::launch::parser::LogLevel::Debug => {
tracing::debug!(target: "mc_instance", "[{}] {}", instance_name, text);
}
crate::instance::launch::parser::LogLevel::Trace => {
tracing::trace!(target: "mc_instance", "[{}] {}", instance_name, text);
}
}
crate::instance_logs::push_event(instance_name, event);
}
#[cfg(test)]
mod tests {
use super::*;
#[rstest::rstest]
#[case("openjdk version \"25.0.3\" 2026-04-21", Some(25))]
#[case("openjdk version \"21.0.11\" 2026-04-21", Some(21))]
#[case("java version \"1.8.0_402\"", Some(8))]
#[case("garbage", None)]
fn parse_java_major_version_handles_common_outputs(
#[case] output: &str,
#[case] expected: Option<u32>,
) {
assert_eq!(parse_java_major_version(output), expected);
}
#[test]
fn build_game_args_renders_upstream_arguments() {
use crate::launch_profile::model::{Argument, Arguments, LaunchProfile};
@@ -812,12 +1036,16 @@ mod tests {
memory_min: None,
jvm_args: Vec::new(),
resolution: None,
config_sync_profile: None,
};
let result =
migrate_legacy_loader_profile_if_needed(&profile_path, &modern, &config, &instance_dir)
.await;
assert!(matches!(result, Ok(None)), "expected Ok(None), got {result:?}");
assert!(
matches!(result, Ok(None)),
"expected Ok(None), got {result:?}"
);
}
#[tokio::test]
@@ -856,6 +1084,7 @@ mod tests {
memory_min: None,
jvm_args: Vec::new(),
resolution: None,
config_sync_profile: None,
};
let result = migrate_legacy_loader_profile_if_needed(
+425
View File
@@ -0,0 +1,425 @@
// live minecraft process log parser.
//
// disk launch logs stay raw, but the tui needs enough structure to color and
// group output sanely. this parser keeps stdout/stderr as a hint, frames
// multiline java/jvm/native bursts into events, then assigns a semantic level.
use libcasr::exception::Exception;
use libcasr::java::{JavaException, JavaStacktrace};
use libcasr::stacktrace::ParseStacktrace;
use regex::Regex;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogStream {
Stdout,
Stderr,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogLevel {
Trace,
Debug,
Info,
Warn,
Error,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct JavaParse {
pub has_exception: bool,
pub has_stacktrace: bool,
pub stacktrace_frames: usize,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedLogEvent {
pub level: LogLevel,
pub primary_stream: LogStream,
pub lines: Vec<String>,
pub java: Option<JavaParse>,
}
#[derive(Debug, Clone)]
struct PendingEvent {
level: LogLevel,
primary_stream: LogStream,
lines: Vec<String>,
normalized_lines: Vec<String>,
kind: EventKind,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum EventKind {
Header,
Java,
JvmBurst,
Native,
Plain,
}
#[derive(Debug)]
pub struct MinecraftLogParser {
current: Option<PendingEvent>,
minecraft_header_re: Regex,
plain_level_re: Regex,
java_exception_re: Regex,
java_continuation_re: Regex,
jvm_burst_re: Regex,
native_header_re: Regex,
}
impl Default for MinecraftLogParser {
fn default() -> Self {
Self::new()
}
}
impl MinecraftLogParser {
pub fn new() -> Self {
Self {
// header matching stays local because this parser is in the live
// path; pulling in heavier pattern machinery would not help with
// the multiline framing problem.
minecraft_header_re: Regex::new(
r"(?i)^\s*(?:\[[^\]]+\]\s*)*\[[^/\]]+/(?P<level>TRACE|DEBUG|INFO|WARN|ERROR|FATAL)\]\s*:",
)
.expect("valid minecraft header regex"),
plain_level_re: Regex::new(
r"(?i)^\s*(?:\[[^\]]+\]\s*)*(?P<level>TRACE|DEBUG|INFO|WARN|ERROR|FATAL)\b\s*(?:[:\]\-])?",
)
.expect("valid plain level regex"),
java_exception_re: Regex::new(
r"(?i)^\s*(?:Exception in thread .+|Caused by: |Suppressed: )?(?:[a-z_$][\w$]*\.)+(?:[A-Z][\w$]*(?:Exception|Error)|Throwable)(?::|\b)",
)
.expect("valid java exception regex"),
java_continuation_re: Regex::new(
r"^(?:\s+at\s+.+|\s*\.\.\.\s+\d+\s+more|Caused by:\s+.+|Suppressed:\s+.+)$",
)
.expect("valid java continuation regex"),
jvm_burst_re: Regex::new(
r"(?i)^\s*(?:Error:\s+.+|Unrecognized option:\s+.+|Could not create the Java Virtual Machine\.|A fatal exception has occurred\. Program will exit\.|Invalid maximum heap size:.+)$",
)
.expect("valid jvm burst regex"),
native_header_re: Regex::new(r"^\[[A-Z]\]\s+\[[0-9:.]+\]\s+[^:]+:")
.expect("valid native header regex"),
current: None,
}
}
pub fn push_line(&mut self, stream: LogStream, line: impl Into<String>) -> Vec<ParsedLogEvent> {
let line = line.into();
// classify against ansi-stripped text, but keep the original line for
// display so the live log remains faithful to the child process.
let normalized = fast_strip_ansi::strip_ansi_string(&line).into_owned();
let analysis = self.analyze_line(stream, &normalized);
let Some(current) = &mut self.current else {
self.current = Some(PendingEvent::new(stream, line, normalized, analysis));
return Vec::new();
};
// only hard starts split events. this keeps stacktraces and native
// loader bursts together even when they arrive one line at a time.
if should_split(current.kind, analysis.kind) {
let finished = self.current.take().map(finish_event);
self.current = Some(PendingEvent::new(stream, line, normalized, analysis));
finished.into_iter().collect()
} else {
if analysis.level_priority() > current.level_priority() {
current.level = analysis.level;
}
if matches!(current.kind, EventKind::Plain)
&& !matches!(analysis.kind, EventKind::Plain)
{
current.kind = analysis.kind;
}
current.lines.push(line);
current.normalized_lines.push(normalized);
Vec::new()
}
}
pub fn flush(&mut self) -> Option<ParsedLogEvent> {
self.current.take().map(finish_event)
}
pub fn has_pending(&self) -> bool {
self.current.is_some()
}
fn analyze_line(&self, stream: LogStream, normalized: &str) -> LineAnalysis {
if let Some(level) = self.header_level(normalized) {
return LineAnalysis {
level,
kind: EventKind::Header,
};
}
if self.java_exception_re.is_match(normalized) {
return LineAnalysis {
level: LogLevel::Error,
kind: EventKind::Java,
};
}
if self.java_continuation_re.is_match(normalized) {
return LineAnalysis {
level: LogLevel::Error,
kind: EventKind::Java,
};
}
if self.jvm_burst_re.is_match(normalized) {
return LineAnalysis {
level: LogLevel::Error,
kind: EventKind::JvmBurst,
};
}
if self.native_header_re.is_match(normalized) {
return LineAnalysis {
level: native_level(normalized).unwrap_or(LogLevel::Warn),
kind: EventKind::Native,
};
}
LineAnalysis {
level: match stream {
LogStream::Stdout => LogLevel::Info,
LogStream::Stderr => LogLevel::Error,
},
kind: EventKind::Plain,
}
}
fn header_level(&self, normalized: &str) -> Option<LogLevel> {
self.minecraft_header_re
.captures(normalized)
.and_then(|caps| caps.name("level"))
.or_else(|| {
self.plain_level_re
.captures(normalized)
.and_then(|caps| caps.name("level"))
})
.and_then(|m| parse_level(m.as_str()))
}
}
#[derive(Debug, Clone, Copy)]
struct LineAnalysis {
level: LogLevel,
kind: EventKind,
}
impl LineAnalysis {
fn level_priority(self) -> u8 {
level_priority(self.level)
}
}
impl PendingEvent {
fn new(stream: LogStream, line: String, normalized: String, analysis: LineAnalysis) -> Self {
Self {
level: analysis.level,
primary_stream: stream,
lines: vec![line],
normalized_lines: vec![normalized],
kind: analysis.kind,
}
}
fn level_priority(&self) -> u8 {
level_priority(self.level)
}
}
fn should_split(current: EventKind, next: EventKind) -> bool {
match next {
EventKind::Header => true,
EventKind::Native => !matches!(current, EventKind::Native),
EventKind::JvmBurst => !matches!(current, EventKind::JvmBurst),
EventKind::Java => !matches!(current, EventKind::Java | EventKind::Header),
EventKind::Plain => false,
}
}
fn finish_event(mut event: PendingEvent) -> ParsedLogEvent {
let normalized_body = event.normalized_lines.join("\n");
// libcasr is intentionally second-stage here: first frame the multiline
// event ourselves, then ask libcasr whether the block is a java failure.
let java = parse_java(&normalized_body);
if java
.as_ref()
.is_some_and(|java| java.has_exception || java.has_stacktrace)
{
event.level = LogLevel::Error;
}
ParsedLogEvent {
level: event.level,
primary_stream: event.primary_stream,
lines: event.lines,
java,
}
}
fn parse_java(body: &str) -> Option<JavaParse> {
let stacktrace_entries = JavaStacktrace::extract_stacktrace(body).unwrap_or_default();
let parsed_stacktrace = if stacktrace_entries.is_empty() {
None
} else {
JavaStacktrace::parse_stacktrace(&stacktrace_entries).ok()
};
let has_exception = JavaException::parse_exception(body).is_some();
let has_stacktrace = parsed_stacktrace
.as_ref()
.is_some_and(|stacktrace| !stacktrace.is_empty());
if has_exception || has_stacktrace {
Some(JavaParse {
has_exception,
has_stacktrace,
stacktrace_frames: parsed_stacktrace.map_or(0, |stacktrace| stacktrace.len()),
})
} else {
None
}
}
fn parse_level(level: &str) -> Option<LogLevel> {
match level.to_ascii_uppercase().as_str() {
"TRACE" => Some(LogLevel::Trace),
"DEBUG" => Some(LogLevel::Debug),
"INFO" => Some(LogLevel::Info),
"WARN" => Some(LogLevel::Warn),
"ERROR" | "FATAL" => Some(LogLevel::Error),
_ => None,
}
}
fn native_level(line: &str) -> Option<LogLevel> {
match line.chars().nth(1)? {
'E' | 'F' => Some(LogLevel::Error),
'W' => Some(LogLevel::Warn),
'I' => Some(LogLevel::Info),
'D' => Some(LogLevel::Debug),
_ => None,
}
}
fn level_priority(level: LogLevel) -> u8 {
match level {
LogLevel::Trace => 0,
LogLevel::Debug => 1,
LogLevel::Info => 2,
LogLevel::Warn => 3,
LogLevel::Error => 4,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn parse_all(lines: &[(LogStream, &str)]) -> Vec<ParsedLogEvent> {
let mut parser = MinecraftLogParser::new();
let mut events = Vec::new();
for (stream, line) in lines {
events.extend(parser.push_line(*stream, *line));
}
events.extend(parser.flush());
events
}
#[test]
fn classifies_minecraft_headers() {
let events = parse_all(&[
(LogStream::Stdout, "[Render thread/INFO]: hello"),
(LogStream::Stdout, "[Render thread/WARN]: careful"),
(LogStream::Stdout, "[Render thread/ERROR]: broken"),
(LogStream::Stdout, "[Render thread/DEBUG]: noisy"),
(LogStream::Stdout, "[Render thread/TRACE]: tiny"),
]);
assert_eq!(events.len(), 5);
assert_eq!(events[0].level, LogLevel::Info);
assert_eq!(events[1].level, LogLevel::Warn);
assert_eq!(events[2].level, LogLevel::Error);
assert_eq!(events[3].level, LogLevel::Debug);
assert_eq!(events[4].level, LogLevel::Trace);
}
#[test]
fn explicit_stderr_info_stays_info() {
let events = parse_all(&[(LogStream::Stderr, "[Render thread/INFO]: hello")]);
assert_eq!(events[0].level, LogLevel::Info);
}
#[test]
fn unstructured_stderr_falls_back_to_error() {
let events = parse_all(&[(LogStream::Stderr, "native library failed")]);
assert_eq!(events[0].level, LogLevel::Error);
}
#[test]
fn groups_java_stacktrace() {
let events = parse_all(&[
(
LogStream::Stderr,
"Exception in thread \"main\" java.lang.RuntimeException: boom",
),
(
LogStream::Stderr,
"\tat net.minecraft.client.Main.main(Main.java:42)",
),
(
LogStream::Stderr,
"Caused by: java.lang.IllegalStateException: bad",
),
(LogStream::Stderr, "\tat example.Mod.load(Mod.java:7)"),
(LogStream::Stdout, "[Render thread/INFO]: after"),
]);
assert_eq!(events.len(), 2);
assert_eq!(events[0].level, LogLevel::Error);
assert_eq!(events[0].lines.len(), 4);
assert!(
events[0]
.java
.as_ref()
.is_some_and(|java| java.has_stacktrace)
);
assert_eq!(events[1].level, LogLevel::Info);
}
#[test]
fn groups_jvm_startup_failure_burst() {
let events = parse_all(&[
(LogStream::Stderr, "Unrecognized option: --bad"),
(
LogStream::Stderr,
"Could not create the Java Virtual Machine.",
),
(
LogStream::Stderr,
"A fatal exception has occurred. Program will exit.",
),
]);
assert_eq!(events.len(), 1);
assert_eq!(events[0].level, LogLevel::Error);
assert_eq!(events[0].lines.len(), 3);
}
#[test]
fn colored_header_classifies_but_keeps_original_text() {
let line = "\u{1b}[31m[Render thread/ERROR]: red\u{1b}[0m";
let events = parse_all(&[(LogStream::Stdout, line)]);
assert_eq!(events[0].level, LogLevel::Error);
assert_eq!(events[0].lines[0], line);
}
}
+7 -2
View File
@@ -383,8 +383,13 @@ mod tests {
#[test]
fn parse_add_opens_extracts_module_args() {
let tmp = tempfile::tempdir().unwrap();
let manifest = b"Manifest-Version: 1.0\nAdd-Opens: java.base/java.lang java.base/java.util\n";
let zip_path = make_zip(tmp.path(), "patches.zip", &[("META-INF/MANIFEST.MF", manifest)]);
let manifest =
b"Manifest-Version: 1.0\nAdd-Opens: java.base/java.lang java.base/java.util\n";
let zip_path = make_zip(
tmp.path(),
"patches.zip",
&[("META-INF/MANIFEST.MF", manifest)],
);
let args = parse_add_opens(&zip_path).expect("parsed");
assert_eq!(
args,
+28 -3
View File
@@ -5,7 +5,7 @@ use std::path::Path;
use async_trait::async_trait;
use super::{GameVersion, ModLoaderInstaller};
use super::{GameVersion, InstallError, InstallerError, ModLoaderInstaller};
use crate::instance::models::ModLoader;
use crate::net::{HttpClient, NetError, fabric as fabric_api};
@@ -26,7 +26,16 @@ impl ModLoaderInstaller for FabricInstaller {
client: &HttpClient,
game_version: &str,
) -> Result<Vec<String>, NetError> {
tracing::debug!(
"Fetching Fabric loader versions for Minecraft {}",
game_version
);
let loader_versions = fabric_api::fetch_fabric_versions(client, game_version).await?;
tracing::debug!(
"Fetched {} Fabric loader version(s) for Minecraft {}",
loader_versions.len(),
game_version
);
Ok(loader_versions
.into_iter()
.map(|lv| lv.loader.version)
@@ -40,15 +49,31 @@ impl ModLoaderInstaller for FabricInstaller {
loader_version: &str,
_instance_dir: &Path,
meta_dir: &Path,
) -> Result<(), NetError> {
) -> Result<(), InstallError> {
tracing::info!(
"Installing Fabric {} for Minecraft {}",
loader_version,
game_version
);
let (profile, raw_bytes) =
fabric_api::fetch_fabric_profile_with_raw(client, game_version, loader_version).await?;
tracing::debug!(
"Fetched Fabric profile {} with {} libraries",
profile.id,
profile.libraries.len()
);
fabric_api::download_fabric_libraries(client, &profile, meta_dir).await?;
super::save_profile_bytes(
meta_dir,
&format!("fabric-{game_version}-{loader_version}.json"),
&raw_bytes,
)?;
)
.map_err(InstallerError::from)?;
tracing::debug!(
"Saved Fabric profile for Minecraft {} loader {}",
game_version,
loader_version
);
Ok(())
}
}
+27 -6
View File
@@ -6,7 +6,7 @@ use std::path::Path;
use async_trait::async_trait;
use super::{GameVersion, ModLoaderInstaller};
use super::{GameVersion, InstallError, ModLoaderInstaller};
use crate::instance::models::ModLoader;
use crate::net::{HttpClient, NetError, forge as forge_api};
@@ -27,7 +27,14 @@ impl ModLoaderInstaller for ForgeInstaller {
client: &HttpClient,
game_version: &str,
) -> Result<Vec<String>, NetError> {
forge_api::fetch_forge_versions(client, game_version).await
tracing::debug!("Fetching Forge versions for Minecraft {}", game_version);
let versions = forge_api::fetch_forge_versions(client, game_version).await?;
tracing::debug!(
"Fetched {} Forge version(s) for Minecraft {}",
versions.len(),
game_version
);
Ok(versions)
}
async fn install(
@@ -37,8 +44,14 @@ impl ModLoaderInstaller for ForgeInstaller {
loader_version: &str,
instance_dir: &Path,
meta_dir: &Path,
) -> Result<(), NetError> {
) -> Result<(), InstallError> {
let installer_jar = instance_dir.join(".minecraft").join("forge-installer.jar");
tracing::info!(
"Installing Forge {} for Minecraft {}",
loader_version,
game_version
);
tracing::debug!("Forge installer path: {}", installer_jar.display());
forge_api::download_forge_installer(client, game_version, loader_version, &installer_jar)
.await?;
@@ -47,6 +60,7 @@ impl ModLoaderInstaller for ForgeInstaller {
if forge_api::has_legacy_install_profile(&installer_jar) {
// old forge: no --installClient support, extract directly from jar
tracing::debug!("Forge installer uses legacy install_profile.json path");
if let Err(e) = forge_api::install_forge_from_profile(
client,
&installer_jar,
@@ -65,21 +79,28 @@ impl ModLoaderInstaller for ForgeInstaller {
.effective_java_path()
.map(str::to_owned)
.unwrap_or_else(crate::net::detect_java_path);
tracing::debug!("Running Forge installer with Java {}", 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);
return Err(InstallError::Installer(e));
}
// extract the profile from what the installer just wrote to disk
save_forge_profile(instance_dir, meta_dir, game_version, loader_version)?;
save_forge_profile(instance_dir, meta_dir, game_version, loader_version)
.map_err(InstallError::Installer)?;
}
if let Err(e) = tokio::fs::remove_file(&installer_jar).await {
tracing::warn!("Failed to remove Forge installer JAR: {}", e);
}
tracing::debug!(
"Installed Forge {} for Minecraft {}",
loader_version,
game_version
);
Ok(())
}
}
@@ -89,7 +110,7 @@ fn save_forge_profile(
meta_dir: &Path,
game_version: &str,
loader_version: &str,
) -> Result<(), NetError> {
) -> Result<(), super::InstallerError> {
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)
+36 -3
View File
@@ -12,10 +12,29 @@ mod vanilla;
use std::path::Path;
use async_trait::async_trait;
use thiserror::Error;
use crate::instance::models::ModLoader;
use crate::net::{HttpClient, NetError};
#[derive(Debug, Error)]
pub enum InstallerError {
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
#[error("Process failed: {0}")]
ProcessFailed(String),
#[error("Profile error: {0}")]
Profile(String),
}
#[derive(Debug, Error)]
pub enum InstallError {
#[error("Download error: {0}")]
Download(#[from] NetError),
#[error("Installer error: {0}")]
Installer(#[from] InstallerError),
}
pub use vanilla::VanillaInstaller;
#[derive(Debug, Clone)]
@@ -43,7 +62,7 @@ pub trait ModLoaderInstaller: Send + Sync {
loader_version: &str,
instance_dir: &Path,
meta_dir: &Path,
) -> Result<(), NetError>;
) -> Result<(), InstallError>;
}
// writes raw profile JSON bytes to meta_dir/loader-profiles/<filename>.
@@ -71,7 +90,7 @@ pub(crate) fn save_installer_profile(
meta_dir: &Path,
version_dir_name: &str,
profile_filename: &str,
) -> Result<(), NetError> {
) -> Result<(), InstallerError> {
let ver_json_path = instance_dir
.join(".minecraft")
.join("versions")
@@ -79,18 +98,32 @@ pub(crate) fn save_installer_profile(
.join(format!("{version_dir_name}.json"));
if !ver_json_path.exists() {
return Err(NetError::Parse(format!(
tracing::debug!(
"Installer profile JSON missing: {}",
ver_json_path.display()
);
return Err(InstallerError::Profile(format!(
"Version JSON not found at {}",
ver_json_path.display()
)));
}
tracing::debug!(
"Saving installer profile {} from {}",
profile_filename,
ver_json_path.display()
);
let raw = std::fs::read(&ver_json_path)?;
let profiles_dir = meta_dir.join("loader-profiles");
std::fs::create_dir_all(&profiles_dir)?;
let profile_path = profiles_dir.join(profile_filename);
std::fs::write(&profile_path, &raw)?;
tracing::debug!(
"Saved installer profile to {} ({} bytes)",
profile_path.display(),
raw.len()
);
Ok(())
}
+18 -6
View File
@@ -5,7 +5,7 @@ use std::path::Path;
use async_trait::async_trait;
use super::{GameVersion, ModLoaderInstaller};
use super::{GameVersion, InstallError, ModLoaderInstaller};
use crate::instance::models::ModLoader;
use crate::net::{HttpClient, NetError, neoforge as neoforge_api};
@@ -26,7 +26,14 @@ impl ModLoaderInstaller for NeoForgeInstaller {
client: &HttpClient,
game_version: &str,
) -> Result<Vec<String>, NetError> {
neoforge_api::fetch_neoforge_versions(client, game_version).await
tracing::debug!("Fetching NeoForge versions for Minecraft {}", game_version);
let versions = neoforge_api::fetch_neoforge_versions(client, game_version).await?;
tracing::debug!(
"Fetched {} NeoForge version(s) for Minecraft {}",
versions.len(),
game_version
);
Ok(versions)
}
async fn install(
@@ -36,10 +43,12 @@ impl ModLoaderInstaller for NeoForgeInstaller {
loader_version: &str,
instance_dir: &Path,
meta_dir: &Path,
) -> Result<(), NetError> {
) -> Result<(), InstallError> {
let installer_jar = instance_dir
.join(".minecraft")
.join("neoforge-installer.jar");
tracing::info!("Installing NeoForge {}", loader_version);
tracing::debug!("NeoForge installer path: {}", installer_jar.display());
neoforge_api::download_neoforge_installer(client, loader_version, &installer_jar).await?;
@@ -48,19 +57,22 @@ impl ModLoaderInstaller for NeoForgeInstaller {
.effective_java_path()
.map(str::to_owned)
.unwrap_or_else(crate::net::detect_java_path);
tracing::debug!("Running NeoForge installer with Java {}", 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);
return Err(InstallError::Installer(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)?;
save_neoforge_profile(instance_dir, meta_dir, loader_version)
.map_err(InstallError::Installer)?;
tracing::debug!("Installed NeoForge {}", loader_version);
Ok(())
}
}
@@ -69,7 +81,7 @@ fn save_neoforge_profile(
instance_dir: &Path,
meta_dir: &Path,
loader_version: &str,
) -> Result<(), NetError> {
) -> Result<(), super::InstallerError> {
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)
+28 -3
View File
@@ -5,7 +5,7 @@ use std::path::Path;
use async_trait::async_trait;
use super::{GameVersion, ModLoaderInstaller};
use super::{GameVersion, InstallError, InstallerError, ModLoaderInstaller};
use crate::instance::models::ModLoader;
use crate::net::{HttpClient, NetError, quilt as quilt_api};
@@ -26,7 +26,16 @@ impl ModLoaderInstaller for QuiltInstaller {
client: &HttpClient,
game_version: &str,
) -> Result<Vec<String>, NetError> {
tracing::debug!(
"Fetching Quilt loader versions for Minecraft {}",
game_version
);
let loader_versions = quilt_api::fetch_quilt_versions(client, game_version).await?;
tracing::debug!(
"Fetched {} Quilt loader version(s) for Minecraft {}",
loader_versions.len(),
game_version
);
Ok(loader_versions
.into_iter()
.map(|lv| lv.loader.version)
@@ -40,15 +49,31 @@ impl ModLoaderInstaller for QuiltInstaller {
loader_version: &str,
_instance_dir: &Path,
meta_dir: &Path,
) -> Result<(), NetError> {
) -> Result<(), InstallError> {
tracing::info!(
"Installing Quilt {} for Minecraft {}",
loader_version,
game_version
);
let (profile, raw_bytes) =
quilt_api::fetch_quilt_profile_with_raw(client, game_version, loader_version).await?;
tracing::debug!(
"Fetched Quilt profile {} with {} libraries",
profile.id,
profile.libraries.len()
);
quilt_api::download_quilt_libraries(client, &profile, meta_dir).await?;
super::save_profile_bytes(
meta_dir,
&format!("quilt-{game_version}-{loader_version}.json"),
&raw_bytes,
)?;
)
.map_err(InstallerError::from)?;
tracing::debug!(
"Saved Quilt profile for Minecraft {} loader {}",
game_version,
loader_version
);
Ok(())
}
}
+2 -2
View File
@@ -6,7 +6,7 @@ use std::path::Path;
use async_trait::async_trait;
use super::{GameVersion, ModLoaderInstaller};
use super::{GameVersion, InstallError, ModLoaderInstaller};
use crate::instance::models::ModLoader;
use crate::net::{HttpClient, NetError, mojang};
@@ -45,7 +45,7 @@ impl ModLoaderInstaller for VanillaInstaller {
_loader_version: &str,
_instance_dir: &Path,
_meta_dir: &Path,
) -> Result<(), NetError> {
) -> Result<(), InstallError> {
Ok(())
}
}
+201 -16
View File
@@ -6,6 +6,8 @@ use std::path::PathBuf;
use chrono::Utc;
use thiserror::Error;
use crate::instance::loader::InstallError;
use crate::instance::loader::InstallerError;
use crate::instance::models::{InstanceConfig, ModLoader};
#[derive(Debug, Error)]
@@ -20,6 +22,8 @@ pub enum InstanceError {
Json(#[from] serde_json::Error),
#[error("Download error: {0}")]
Download(#[from] crate::net::NetError),
#[error("Installer error: {0}")]
InstallerError(#[from] InstallerError),
#[error("Invalid instance name: {0}")]
InvalidName(String),
}
@@ -33,11 +37,17 @@ pub struct InstanceManager {
impl InstanceManager {
pub fn new(instances_dir: impl Into<PathBuf>, meta_dir: impl Into<PathBuf>) -> Self {
InstanceManager {
let manager = InstanceManager {
instances_dir: instances_dir.into(),
meta_dir: meta_dir.into(),
client: crate::net::HttpClient::new(),
}
};
tracing::trace!(
"Created InstanceManager with instances_dir={} meta_dir={}",
manager.instances_dir.display(),
manager.meta_dir.display()
);
manager
}
pub async fn create(
@@ -51,13 +61,31 @@ impl InstanceManager {
let instance_dir = self.instances_dir.join(name);
let instance_json = instance_dir.join("instance.json");
tracing::info!(
"Creating instance '{}' (Minecraft {}, loader {}, loader_version={})",
name,
game_version,
loader,
loader_version.unwrap_or("<none>")
);
tracing::debug!("Instance directory: {}", instance_dir.display());
if instance_json.exists() {
tracing::warn!(
"Cannot create instance '{}': {} already exists",
name,
instance_json.display()
);
return Err(InstanceError::AlreadyExists(name.to_string()));
}
// leftover directory without config = botched previous creation, nuke it
if instance_dir.exists() && !instance_json.exists() {
tracing::warn!(
"Removing incomplete instance directory before recreating '{}': {}",
name,
instance_dir.display()
);
std::fs::remove_dir_all(&instance_dir)?;
}
@@ -69,7 +97,22 @@ impl InstanceManager {
// clean up on failure so there's no half-baked instance left around
if result.is_err() {
let _ = std::fs::remove_dir_all(&instance_dir);
tracing::debug!(
"Cleaning up incomplete instance '{}' after creation failed",
name
);
if let Err(cleanup_error) = std::fs::remove_dir_all(&instance_dir) {
tracing::warn!(
"Failed to clean up incomplete instance directory {}: {}",
instance_dir.display(),
cleanup_error
);
} else {
tracing::debug!(
"Cleaned up incomplete instance directory {}",
instance_dir.display()
);
}
}
result
@@ -84,14 +127,26 @@ impl InstanceManager {
instance_dir: &std::path::Path,
) -> Result<InstanceConfig, InstanceError> {
let minecraft_dir = instance_dir.join(".minecraft");
tracing::debug!(
"Preparing Minecraft directory for '{}': {}",
name,
minecraft_dir.display()
);
for subdir in &["mods", "config", "resourcepacks", "shaderpacks", "saves"] {
std::fs::create_dir_all(minecraft_dir.join(subdir))?;
let path = minecraft_dir.join(subdir);
std::fs::create_dir_all(&path)?;
tracing::trace!("Ensured instance subdirectory {}", path.display());
}
// forge insists on this file existing, even if it's empty json. thanks forge.
let launcher_profiles_path = minecraft_dir.join("launcher_profiles.json");
if !launcher_profiles_path.exists() {
std::fs::write(&launcher_profiles_path, "{}")?;
tracing::debug!(
"Created launcher_profiles.json for '{}': {}",
name,
launcher_profiles_path.display()
);
}
for meta_subdir in &[
@@ -101,22 +156,44 @@ impl InstanceManager {
self.meta_dir.join("assets").join("indexes"),
] {
std::fs::create_dir_all(meta_subdir)?;
tracing::trace!("Ensured metadata directory {}", meta_subdir.display());
}
tracing::debug!("Fetching Mojang version manifest for '{}'", name);
let manifest = crate::net::mojang::fetch_version_manifest(&self.client).await?;
tracing::debug!(
"Loaded Mojang manifest with {} version(s); latest release={} snapshot={}",
manifest.versions.len(),
manifest.latest.release,
manifest.latest.snapshot
);
let version_entry = match manifest.versions.iter().find(|v| v.id == game_version) {
Some(v) => v,
Some(v) => {
tracing::debug!(
"Resolved Minecraft version '{}' as {} entry",
game_version,
v.version_type
);
v
}
None => {
return Err(InstanceError::InvalidName(format!(
"Minecraft version '{}' not found in manifest",
game_version
"Minecraft version '{}' not found in manifest with {} entries",
game_version,
manifest.versions.len()
)));
}
};
let (version_meta, raw_meta_bytes) =
crate::net::mojang::fetch_version_meta_with_raw(&self.client, version_entry).await?;
tracing::debug!(
"Fetched version meta '{}' with {} libraries and asset index {}",
version_meta.id,
version_meta.libraries.len(),
version_meta.asset_index.id
);
crate::net::mojang::download_client_jar(&self.client, &version_meta, &self.meta_dir)
.await?;
@@ -129,10 +206,20 @@ impl InstanceManager {
if let Some(parent) = meta_json_path.parent()
&& let Err(e) = std::fs::create_dir_all(parent)
{
tracing::warn!("Failed to ensure meta dir exists: {}", e);
tracing::warn!(
"Failed to ensure meta dir {} exists: {}",
parent.display(),
e
);
}
if let Err(e) = std::fs::write(&meta_json_path, &raw_meta_bytes) {
tracing::warn!("Failed to save version meta: {}", e);
tracing::warn!(
"Failed to save version meta {}: {}",
meta_json_path.display(),
e
);
} else {
tracing::debug!("Saved version meta to {}", meta_json_path.display());
}
crate::net::mojang::download_libraries(&self.client, &version_meta, &self.meta_dir).await?;
@@ -150,6 +237,12 @@ impl InstanceManager {
)));
}
};
tracing::debug!(
"Installing loader {} {} for instance '{}'",
loader,
effective_loader_version,
name
);
installer
.install(
&self.client,
@@ -158,7 +251,13 @@ impl InstanceManager {
instance_dir,
&self.meta_dir,
)
.await?;
.await
.map_err(|e| match e {
InstallError::Download(net_error) => InstanceError::Download(net_error),
InstallError::Installer(installer_error) => {
InstanceError::InstallerError(installer_error)
}
})?;
let config = InstanceConfig {
name: name.to_string(),
@@ -172,9 +271,11 @@ impl InstanceManager {
memory_min: None,
jvm_args: vec![],
resolution: None,
config_sync_profile: None,
};
self.save(&config)?;
tracing::info!("Created instance '{}'", name);
crate::tui::progress::clear();
Ok(config)
@@ -183,9 +284,22 @@ impl InstanceManager {
pub fn delete(&self, name: &str) -> Result<(), InstanceError> {
let instance_dir = self.instances_dir.join(name);
if !instance_dir.exists() {
tracing::warn!(
"Cannot delete missing instance '{}': {}",
name,
instance_dir.display()
);
return Err(InstanceError::NotFound(name.to_string()));
}
std::fs::remove_dir_all(&instance_dir)?;
tracing::info!("Deleting instance '{}' at {}", name, instance_dir.display());
if let Err(e) = std::fs::remove_dir_all(&instance_dir) {
tracing::error!(
"Failed to delete instance directory {}: {}",
instance_dir.display(),
e
);
return Err(e.into());
}
if let Err(e) = crate::instance::desktop::remove(name) {
tracing::warn!("Failed to remove desktop shortcut for '{}': {}", name, e);
}
@@ -195,22 +309,44 @@ impl InstanceManager {
pub fn rename(&self, old_name: &str, new_name: &str) -> Result<(), InstanceError> {
let new_name = new_name.trim();
if new_name.is_empty() {
tracing::warn!("Cannot rename instance '{}': new name is empty", old_name);
return Err(InstanceError::InvalidName(
"Name cannot be empty".to_string(),
));
}
if old_name == new_name {
tracing::debug!("Ignoring no-op instance rename '{}'", old_name);
return Ok(());
}
let old_dir = self.instances_dir.join(old_name);
let new_dir = self.instances_dir.join(new_name);
if !old_dir.exists() {
tracing::warn!(
"Cannot rename missing instance '{}': {}",
old_name,
old_dir.display()
);
return Err(InstanceError::NotFound(old_name.to_string()));
}
if new_dir.exists() {
tracing::warn!(
"Cannot rename instance '{}' to '{}': destination exists at {}",
old_name,
new_name,
new_dir.display()
);
return Err(InstanceError::AlreadyExists(new_name.to_string()));
}
std::fs::rename(&old_dir, &new_dir)?;
tracing::info!("Renaming instance '{}' to '{}'", old_name, new_name);
if let Err(e) = std::fs::rename(&old_dir, &new_dir) {
tracing::error!(
"Failed to rename instance directory {} to {}: {}",
old_dir.display(),
new_dir.display(),
e
);
return Err(e.into());
}
let config_path = new_dir.join("instance.json");
if let Ok(data) = std::fs::read_to_string(&config_path)
@@ -223,6 +359,11 @@ impl InstanceManager {
if let Err(e) = crate::instance::desktop::rename(old_name, &config) {
tracing::warn!("Failed to rename desktop shortcut: {}", e);
}
} else {
tracing::warn!(
"Renamed instance directory but could not update config at {}",
config_path.display()
);
}
Ok(())
@@ -230,10 +371,15 @@ impl InstanceManager {
pub fn load_all(&self) -> Vec<InstanceConfig> {
let mut instances = vec![];
tracing::debug!("Loading instances from {}", self.instances_dir.display());
let read_dir = match std::fs::read_dir(&self.instances_dir) {
Ok(rd) => rd,
Err(e) => {
tracing::error!("Failed to read instances directory: {}", e);
tracing::error!(
"Failed to read instances directory {}: {}",
self.instances_dir.display(),
e
);
return instances;
}
};
@@ -247,6 +393,7 @@ impl InstanceManager {
};
let config_path = entry.path().join("instance.json");
if !config_path.exists() {
tracing::trace!("Skipping non-instance directory {}", entry.path().display());
continue;
}
let contents = match std::fs::read_to_string(&config_path) {
@@ -263,6 +410,7 @@ impl InstanceManager {
}
}
}
tracing::debug!("Loaded {} instance(s)", instances.len());
instances
}
@@ -271,11 +419,39 @@ impl InstanceManager {
let config_path = self.instances_dir.join(name).join("instance.json");
if !config_path.exists() {
tracing::warn!(
"Instance '{}' config is missing at {}",
name,
config_path.display()
);
return Err(InstanceError::NotFound(name.to_string()));
}
let contents = std::fs::read_to_string(&config_path)?;
Ok(serde_json::from_str::<InstanceConfig>(&contents)?)
tracing::debug!("Loading instance '{}' from {}", name, config_path.display());
let contents = match std::fs::read_to_string(&config_path) {
Ok(contents) => contents,
Err(e) => {
tracing::error!(
"Failed to read instance '{}' config {}: {}",
name,
config_path.display(),
e
);
return Err(e.into());
}
};
match serde_json::from_str::<InstanceConfig>(&contents) {
Ok(config) => Ok(config),
Err(e) => {
tracing::error!(
"Failed to parse instance '{}' config {}: {}",
name,
config_path.display(),
e
);
Err(e.into())
}
}
}
pub fn save(&self, instance: &InstanceConfig) -> Result<(), InstanceError> {
@@ -283,12 +459,18 @@ impl InstanceManager {
let config_path = instance_dir.join("instance.json");
let json = serde_json::to_string_pretty(instance)?;
std::fs::write(&config_path, &json)?;
tracing::debug!(
"Saved instance '{}' config to {}",
instance.name,
config_path.display()
);
Ok(())
}
pub fn touch_last_played(&self, name: &str) -> Result<(), InstanceError> {
let mut config = self.load_one(name)?;
config.last_played = Some(chrono::Utc::now());
tracing::debug!("Updating last_played for '{}'", name);
self.save(&config)
}
}
@@ -339,6 +521,7 @@ mod tests {
memory_min: None,
jvm_args: vec![],
resolution: None,
config_sync_profile: None,
}
}
@@ -468,7 +651,9 @@ mod tests {
manager.touch_last_played("ticker").expect("touch");
let reloaded = manager.load_one("ticker").unwrap();
let stamp = reloaded.last_played.expect("last_played should be Some now");
let stamp = reloaded
.last_played
.expect("last_played should be Some now");
let age = chrono::Utc::now() - stamp;
assert!(
age.num_seconds().abs() < 5,
+4 -5
View File
@@ -1,5 +1,7 @@
// instance management: creation, launching, importing modpacks, and all the
// bookkeeping that comes with pretending to be a real launcher
pub mod config_sync;
pub mod content;
pub mod desktop;
pub mod import;
@@ -11,11 +13,8 @@ pub mod models;
pub mod screenshots;
pub use content::{
ContentEntry, toggle_entry,
scan_mods, scan_one_mod,
scan_resource_packs, scan_one_resource_pack,
scan_shaders, scan_one_shader,
scan_worlds, scan_one_world,
ContentEntry, scan_mods, scan_one_mod, scan_one_resource_pack, scan_one_shader, scan_one_world,
scan_resource_packs, scan_shaders, scan_worlds, toggle_entry,
};
pub use launch::LaunchError;
pub use loader::{GameVersion, ModLoaderInstaller, VanillaInstaller, get_installer};
+3
View File
@@ -47,6 +47,8 @@ pub struct InstanceConfig {
pub jvm_args: Vec<String>,
#[serde(default)]
pub resolution: Option<(u32, u32)>,
#[serde(default)]
pub config_sync_profile: Option<String>,
}
pub fn normalize_memory_value(raw: &str) -> Option<String> {
@@ -137,6 +139,7 @@ mod tests {
memory_min: Some("512M".to_string()),
jvm_args: vec![],
resolution: Some((1920, 1080)),
config_sync_profile: None,
};
let json = serde_json::to_string_pretty(&config).expect("serialize");
let parsed: InstanceConfig = serde_json::from_str(&json).expect("deserialize");
-1
View File
@@ -45,4 +45,3 @@ pub fn scan_screenshots(instances_dir: &Path, instance_name: &str) -> Vec<Screen
entries.sort_by(|a, b| b.name.cmp(&a.name));
entries
}
+36 -3
View File
@@ -6,28 +6,61 @@ use std::collections::{HashMap, VecDeque};
use std::sync::LazyLock;
use std::sync::{Arc, Mutex};
use crate::instance::launch::parser::{LogLevel, LogStream, ParsedLogEvent};
const MAX_LINES: usize = 2000;
type LogsMap = Arc<Mutex<HashMap<String, VecDeque<String>>>>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LiveLogLine {
pub level: LogLevel,
pub stream: LogStream,
pub text: String,
}
type LogsMap = Arc<Mutex<HashMap<String, VecDeque<LiveLogLine>>>>;
pub static LOGS: LazyLock<LogsMap> = LazyLock::new(|| Arc::new(Mutex::new(HashMap::new())));
pub fn push(name: &str, line: impl Into<String>) {
push_line(name, LogLevel::Info, LogStream::Stdout, line);
}
pub fn push_event(name: &str, event: ParsedLogEvent) {
for line in event.lines {
push_line(name, event.level, event.primary_stream, line);
}
}
pub fn push_line(name: &str, level: LogLevel, stream: LogStream, line: impl Into<String>) {
if let Ok(mut logs) = LOGS.lock() {
let buf = logs.entry(name.to_string()).or_insert_with(VecDeque::new);
buf.push_back(line.into());
buf.push_back(LiveLogLine {
level,
stream,
text: line.into(),
});
while buf.len() > MAX_LINES {
buf.pop_front();
}
}
}
pub fn get_all(name: &str) -> Vec<String> {
pub fn get_entries(name: &str) -> Vec<LiveLogLine> {
LOGS.lock()
.ok()
.and_then(|logs| logs.get(name).map(|buf| buf.iter().cloned().collect()))
.unwrap_or_default()
}
pub fn get_all(name: &str) -> Vec<String> {
LOGS.lock()
.ok()
.and_then(|logs| {
logs.get(name)
.map(|buf| buf.iter().map(|line| line.text.clone()).collect())
})
.unwrap_or_default()
}
pub fn clear(name: &str) {
if let Ok(mut logs) = LOGS.lock() {
logs.remove(name);
+4 -1
View File
@@ -113,7 +113,10 @@ fn os_version_matches(pattern: &str, host_version: &str) -> bool {
fn features_match(required: &FeatureSet, current: &FeatureSet) -> bool {
let pairs = [
(required.is_demo_user, current.is_demo_user),
(required.has_custom_resolution, current.has_custom_resolution),
(
required.has_custom_resolution,
current.has_custom_resolution,
),
(
required.has_quick_plays_support,
current.has_quick_plays_support,
+8 -2
View File
@@ -165,7 +165,10 @@ mod tests {
#[case::unclosed_placeholder("--prefix ${unclosed", "--prefix ${unclosed")]
#[case::dollar_without_brace("$$ literal $5 $", "$$ literal $5 $")]
#[case::multiple("${version_name}-${auth_player_name}", "1.20.1-Player")]
#[case::path("-DlibraryDirectory=${library_directory}", "-DlibraryDirectory=/m/libraries")]
#[case::path(
"-DlibraryDirectory=${library_directory}",
"-DlibraryDirectory=/m/libraries"
)]
#[case::empty_input("", "")]
fn substitute_handles(#[case] input: &str, #[case] expected: &str) {
let fx = Fixture::unix();
@@ -178,7 +181,10 @@ mod tests {
// pattern. it should NOT trigger another substitution pass.
let mut fx = Fixture::unix();
fx.user_properties = "${version_name}".to_string();
assert_eq!(substitute("${user_properties}", &fx.ctx()), "${version_name}");
assert_eq!(
substitute("${user_properties}", &fx.ctx()),
"${version_name}"
);
}
#[test]
+2
View File
@@ -4,8 +4,10 @@ async fn main() {
// Guard must stay in scope to keep the log file writer alive
let _guard = rmcl::tui::logging::init();
tracing::info!("Starting rmcl {}", env!("CARGO_PKG_VERSION"));
if let Err(e) = color_eyre::install() {
eprintln!("Failed to install color-eyre: {}", e);
tracing::warn!("Failed to install color-eyre handler: {}", e);
}
rmcl::cli_init().await
+5 -1
View File
@@ -39,7 +39,11 @@ fn rename_top_level(old: &Path, new: &Path) {
return;
}
match fs::rename(old, new) {
Ok(_) => eprintln!("rmcl migration: moved {} -> {}", old.display(), new.display()),
Ok(_) => eprintln!(
"rmcl migration: moved {} -> {}",
old.display(),
new.display()
),
Err(e) if e.kind() == io::ErrorKind::CrossesDevices => {
if let Err(e2) = copy_dir_recursive(old, new) {
eprintln!(
+28 -3
View File
@@ -56,7 +56,9 @@ pub async fn fetch_fabric_game_versions_from(
meta_base: &str,
) -> Result<Vec<GameVersion>, NetError> {
let url = format!("{}/versions/game", meta_base);
tracing::debug!("Fetching Fabric game versions from {}", url);
let versions: Vec<FabricGameVersion> = client.get_json(&url).await?;
tracing::debug!("Fetched {} Fabric game version(s)", versions.len());
Ok(versions
.into_iter()
@@ -80,7 +82,14 @@ pub async fn fetch_fabric_versions_from(
game_version: &str,
) -> Result<Vec<FabricLoaderVersion>, NetError> {
let url = format!("{}/versions/loader/{}", meta_base, game_version);
client.get_json(&url).await
tracing::debug!("Fetching Fabric loader versions for {}", game_version);
let versions: Vec<FabricLoaderVersion> = client.get_json(&url).await?;
tracing::debug!(
"Fetched {} Fabric loader version(s) for {}",
versions.len(),
game_version
);
Ok(versions)
}
pub async fn fetch_fabric_profile(
@@ -101,6 +110,11 @@ pub async fn fetch_fabric_profile_from(
"{}/versions/loader/{}/{}/profile/json",
meta_base, game_version, loader_version
);
tracing::debug!(
"Fetching Fabric profile for Minecraft {} loader {}",
game_version,
loader_version
);
client.get_json(&url).await
}
@@ -113,8 +127,7 @@ pub async fn fetch_fabric_profile_with_raw(
game_version: &str,
loader_version: &str,
) -> Result<(FabricProfile, Vec<u8>), NetError> {
fetch_fabric_profile_with_raw_from(client, FABRIC_META_BASE, game_version, loader_version)
.await
fetch_fabric_profile_with_raw_from(client, FABRIC_META_BASE, game_version, loader_version).await
}
pub async fn fetch_fabric_profile_with_raw_from(
@@ -127,6 +140,11 @@ pub async fn fetch_fabric_profile_with_raw_from(
"{}/versions/loader/{}/{}/profile/json",
meta_base, game_version, loader_version
);
tracing::debug!(
"Fetching raw Fabric profile for Minecraft {} loader {}",
game_version,
loader_version
);
client.get_json_with_raw(&url, "Fabric profile").await
}
@@ -138,6 +156,11 @@ pub async fn download_fabric_libraries(
meta_dir: &Path,
) -> Result<(), NetError> {
let libraries_dir = meta_dir.join("libraries");
tracing::debug!(
"Resolving {} Fabric libraries into {}",
profile.libraries.len(),
libraries_dir.display()
);
for lib in &profile.libraries {
let maven_path = match crate::net::maven_coord_to_path(&lib.name) {
@@ -162,10 +185,12 @@ pub async fn download_fabric_libraries(
set_sub_action(&lib.name);
tracing::info!("Downloading Fabric library: {}", lib.name);
tracing::trace!("Fabric library destination: {}", dest.display());
download_file(client, &download_url, &dest, |_, _| {}).await?;
}
tracing::debug!("Fabric library resolution complete for {}", profile.id);
Ok(())
}
+105 -33
View File
@@ -7,7 +7,7 @@ use std::path::Path;
use serde::Deserialize;
use crate::instance::loader::GameVersion;
use crate::instance::loader::{GameVersion, InstallError, InstallerError};
use crate::net::{HttpClient, NetError, download_file};
use crate::tui::progress::{set_action, set_sub_action};
@@ -47,6 +47,11 @@ pub async fn fetch_forge_versions_from(
versions.sort();
versions.dedup();
tracing::debug!(
"Resolved {} Forge version(s) for Minecraft {} from promotions",
versions.len(),
game_version
);
Ok(versions)
}
@@ -70,6 +75,10 @@ pub async fn fetch_forge_game_versions_from(
game_versions.sort();
game_versions.dedup();
game_versions.reverse();
tracing::debug!(
"Resolved {} Forge game version(s) from promotions",
game_versions.len()
);
Ok(game_versions
.into_iter()
@@ -104,13 +113,20 @@ pub async fn download_forge_installer(
let mut last_err = None;
for slug in &slugs {
let url = format!("{}/{slug}/forge-{slug}-installer.jar", FORGE_MAVEN_BASE,);
tracing::debug!("Trying Forge installer slug '{}'", slug);
match download_file(client, &url, dest, |downloaded, total| {
crate::tui::progress::set_progress(downloaded, total);
})
.await
{
Ok(()) => return Ok(()),
Err(e) => last_err = Some(e),
Ok(()) => {
tracing::debug!("Downloaded Forge installer using slug '{}'", slug);
return Ok(());
}
Err(e) => {
tracing::debug!("Forge installer slug '{}' failed: {}", slug, e);
last_err = Some(e);
}
}
}
@@ -125,7 +141,7 @@ pub async fn run_forge_installer(
installer_path: &Path,
instance_dir: &Path,
java_path: &str,
) -> Result<(), NetError> {
) -> Result<(), InstallerError> {
use tokio::process::Command;
set_action("Running Forge installer...");
@@ -140,7 +156,13 @@ pub async fn run_forge_installer(
{
Ok(o) => o,
Err(e) => {
return Err(NetError::Io(e));
tracing::debug!(
"Failed to spawn Forge installer {} with Java {}: {}",
installer_path.display(),
java_path,
e
);
return Err(InstallerError::Io(e));
}
};
@@ -151,9 +173,16 @@ pub async fn run_forge_installer(
} else {
stderr.lines().last().unwrap_or("unknown error").to_string()
};
return Err(NetError::InstallerFailed(detail));
tracing::debug!(
"Forge installer {} failed with status {:?}: {}",
installer_path.display(),
output.status.code(),
detail
);
return Err(InstallerError::ProcessFailed(detail));
}
tracing::debug!("Forge installer completed successfully");
Ok(())
}
@@ -186,68 +215,103 @@ pub(crate) async fn install_forge_from_profile(
installer_path: &Path,
meta_dir: &Path,
profile_filename: &str,
) -> Result<(), NetError> {
) -> Result<(), InstallError> {
use std::io::Read;
set_action("Installing legacy Forge from profile...");
tracing::debug!(
"Installing legacy Forge from {} into {}",
installer_path.display(),
meta_dir.display()
);
let file = std::fs::File::open(installer_path)?;
let mut archive = zip::ZipArchive::new(file)
.map_err(|e| NetError::Parse(format!("Failed to open installer as ZIP: {e}")))?;
let file = std::fs::File::open(installer_path)
.map_err(|e| InstallError::Installer(InstallerError::Io(e)))?;
let mut archive = zip::ZipArchive::new(file).map_err(|e| {
InstallError::Installer(InstallerError::Profile(format!(
"Failed to open installer as ZIP: {e}"
)))
})?;
let profile_data: serde_json::Value = {
let entry = archive.by_name("install_profile.json").map_err(|e| {
NetError::Parse(format!("install_profile.json not found in installer: {e}"))
InstallError::Installer(InstallerError::Profile(format!(
"install_profile.json not found in installer: {e}"
)))
})?;
serde_json::from_reader(entry)
.map_err(|e| NetError::Parse(format!("Failed to parse install_profile.json: {e}")))?
serde_json::from_reader(entry).map_err(|e| {
InstallError::Installer(InstallerError::Profile(format!(
"Failed to parse install_profile.json: {e}"
)))
})?
};
let version_info = profile_data
.get("versionInfo")
.ok_or_else(|| NetError::Parse("install_profile.json missing versionInfo".into()))?;
let install_info = profile_data
.get("install")
.ok_or_else(|| NetError::Parse("install_profile.json missing install section".into()))?;
let version_info = profile_data.get("versionInfo").ok_or_else(|| {
InstallError::Installer(InstallerError::Profile(
"install_profile.json missing versionInfo".into(),
))
})?;
let install_info = profile_data.get("install").ok_or_else(|| {
InstallError::Installer(InstallerError::Profile(
"install_profile.json missing install section".into(),
))
})?;
let libraries = version_info
.get("libraries")
.and_then(|v| v.as_array())
.ok_or_else(|| NetError::Parse("missing versionInfo.libraries".into()))?;
.ok_or_else(|| {
InstallError::Installer(InstallerError::Profile(
"missing versionInfo.libraries".into(),
))
})?;
let file_path = install_info
.get("filePath")
.and_then(|v| v.as_str())
.ok_or_else(|| NetError::Parse("missing install.filePath".into()))?;
.ok_or_else(|| {
InstallError::Installer(InstallerError::Profile("missing install.filePath".into()))
})?;
let install_path_coord = install_info
.get("path")
.and_then(|v| v.as_str())
.ok_or_else(|| NetError::Parse("missing install.path".into()))?;
.ok_or_else(|| {
InstallError::Installer(InstallerError::Profile("missing install.path".into()))
})?;
// extract the universal jar to the correct maven location
let universal_maven_path =
crate::net::maven_coord_to_path(install_path_coord).ok_or_else(|| {
NetError::Parse(format!(
InstallError::Installer(InstallerError::Profile(format!(
"Invalid maven coord in install.path: {install_path_coord}"
))
)))
})?;
set_sub_action("Extracting universal JAR...");
let universal_dest = meta_dir.join("libraries").join(&universal_maven_path);
if let Some(parent) = universal_dest.parent() {
std::fs::create_dir_all(parent)?;
std::fs::create_dir_all(parent)
.map_err(|e| InstallError::Installer(InstallerError::Io(e)))?;
}
{
let mut entry = archive.by_name(file_path).map_err(|e| {
NetError::Parse(format!(
InstallError::Installer(InstallerError::Profile(format!(
"Universal JAR '{file_path}' not found in installer: {e}"
))
)))
})?;
let mut buf = Vec::new();
entry.read_to_end(&mut buf)?;
std::fs::write(&universal_dest, &buf)?;
entry
.read_to_end(&mut buf)
.map_err(|e| InstallError::Installer(InstallerError::Io(e)))?;
std::fs::write(&universal_dest, &buf)
.map_err(|e| InstallError::Installer(InstallerError::Io(e)))?;
tracing::debug!(
"Extracted legacy Forge universal JAR to {} ({} bytes)",
universal_dest.display(),
buf.len()
);
}
// download libraries needed by this forge version. libs with a url field
@@ -261,12 +325,15 @@ pub(crate) async fn install_forge_from_profile(
let maven_path = match crate::net::maven_coord_to_path(name) {
Some(p) => p,
None => {
return Err(NetError::Parse(format!("Invalid Maven coordinate: {name}")));
return Err(InstallError::Installer(InstallerError::Profile(format!(
"Invalid Maven coordinate: {name}"
))));
}
};
let dest = libraries_dir.join(&maven_path);
if dest.exists() {
tracing::trace!("Legacy Forge library already cached: {}", name);
continue;
}
@@ -278,6 +345,7 @@ pub(crate) async fn install_forge_from_profile(
let download_url = format!("{base_url}/{maven_path}");
set_sub_action(name);
tracing::debug!("Downloading legacy Forge library {}", name);
download_file(client, &download_url, &dest, |_, _| {}).await?;
}
@@ -295,9 +363,13 @@ pub(crate) async fn install_forge_from_profile(
// and whitespace may differ from the original installer JSON because
// the source is a serde_json::Value (which doesn't preserve order),
// but no field is silently dropped.
let serialized = serde_json::to_vec(version_info)
.map_err(|e| NetError::Parse(format!("Failed to serialize Forge profile: {e}")))?;
crate::instance::loader::save_profile_bytes(meta_dir, profile_filename, &serialized)?;
let serialized = serde_json::to_vec(version_info).map_err(|e| {
InstallError::Installer(InstallerError::Profile(format!(
"Failed to serialize Forge profile: {e}"
)))
})?;
crate::instance::loader::save_profile_bytes(meta_dir, profile_filename, &serialized)
.map_err(|e| InstallError::Installer(InstallerError::Io(e)))?;
Ok(())
}
+77 -41
View File
@@ -23,8 +23,6 @@ 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),
}
@@ -42,14 +40,19 @@ impl Default for HttpClient {
impl HttpClient {
pub fn new() -> Self {
let user_agent = format!("rmcl/{} (Minecraft Launcher)", env!("CARGO_PKG_VERSION"));
let client = Client::builder()
.user_agent(format!(
"rmcl/{} (Minecraft Launcher)",
env!("CARGO_PKG_VERSION")
))
.user_agent(user_agent.clone())
.timeout(std::time::Duration::from_secs(30))
.build()
.unwrap_or_else(|_| Client::new());
.unwrap_or_else(|e| {
tracing::warn!(
"Failed to build configured HTTP client, falling back to reqwest default: {}",
e
);
Client::new()
});
tracing::trace!("Created HTTP client with user-agent '{}'", user_agent);
Self { inner: client }
}
@@ -58,13 +61,20 @@ impl HttpClient {
}
pub async fn get(&self, url: &str) -> Result<reqwest::Response, NetError> {
tracing::trace!("HTTP GET {}", url);
let response = self.inner.get(url).send().await?;
if !response.status().is_success() {
tracing::debug!(
"HTTP GET {} returned non-success status {}",
url,
response.status()
);
return Err(NetError::StatusError {
status: response.status().as_u16(),
url: url.to_string(),
});
}
tracing::trace!("HTTP GET {} succeeded with {}", url, response.status());
Ok(response)
}
@@ -90,7 +100,9 @@ impl HttpClient {
url: &str,
label: &str,
) -> Result<(T, Vec<u8>), NetError> {
tracing::debug!("Fetching {} JSON from {}", label, url);
let raw = self.get_bytes(url).await?;
tracing::trace!("Fetched {} byte(s) for {}", raw.len(), label);
let parsed: T = serde_json::from_slice(&raw)
.map_err(|e| NetError::Parse(format!("Failed to parse {label}: {e}")))?;
Ok((parsed, raw))
@@ -105,35 +117,47 @@ where
F: Fn(reqwest::Response) -> Fut,
Fut: std::future::Future<Output = Result<T, NetError>>,
{
let mut last_error = None;
for attempt in 0..=MAX_RETRIES {
if attempt > 0 {
let delay = RETRY_BASE_DELAY_MS * 2u64.pow(attempt - 1);
tracing::warn!(
"retrying request (attempt {}/{}): {}",
attempt + 1,
MAX_RETRIES + 1,
url
);
tokio::time::sleep(std::time::Duration::from_millis(delay)).await;
}
match client.get(url).await {
Ok(resp) => match decode(resp).await {
Ok(value) => return Ok(value),
Err(e) if is_retryable(&e) => last_error = Some(e),
Err(e) if is_retryable(&e) => {
if attempt == MAX_RETRIES {
return Err(e);
}
sleep_before_retry("request", url, attempt, &e).await;
}
Err(e) => return Err(e),
},
Err(e) if is_retryable(&e) => last_error = Some(e),
Err(e) if is_retryable(&e) => {
if attempt == MAX_RETRIES {
return Err(e);
}
sleep_before_retry("request", url, attempt, &e).await;
}
Err(e) => return Err(e),
}
}
Err(last_error.unwrap())
unreachable!("retry loop returns on success or final error")
}
const MAX_RETRIES: u32 = 3;
const RETRY_BASE_DELAY_MS: u64 = 500;
async fn sleep_before_retry(kind: &str, url: &str, attempt: u32, err: &NetError) {
let delay = RETRY_BASE_DELAY_MS * 2u64.pow(attempt);
tracing::warn!(
"{} failed, retrying after {}ms (attempt {}/{}): {}: {}",
kind,
delay,
attempt + 2,
MAX_RETRIES + 1,
url,
err
);
tokio::time::sleep(std::time::Duration::from_millis(delay)).await;
}
// streams a file to disk in chunks, calling progress_cb(downloaded, total) along the way.
// total will be 0 if the server doesn't send content-length, so callers
// should handle that gracefully. retries transient failures with exponential backoff.
@@ -143,30 +167,25 @@ pub async fn download_file(
dest: &Path,
progress_cb: impl Fn(u64, u64),
) -> Result<(), NetError> {
let mut last_error = None;
tracing::debug!("Downloading {} to {}", url, dest.display());
for attempt in 0..=MAX_RETRIES {
if attempt > 0 {
let delay = RETRY_BASE_DELAY_MS * 2u64.pow(attempt - 1);
tracing::warn!(
"retrying download (attempt {}/{}): {}",
attempt + 1,
MAX_RETRIES + 1,
url
);
tokio::time::sleep(std::time::Duration::from_millis(delay)).await;
}
match download_file_once(client, url, dest, &progress_cb).await {
Ok(()) => return Ok(()),
Ok(()) => {
tracing::debug!("Downloaded {} to {}", url, dest.display());
return Ok(());
}
Err(e) if is_retryable(&e) => {
last_error = Some(e);
if attempt == MAX_RETRIES {
return Err(e);
}
sleep_before_retry("download", url, attempt, &e).await;
}
Err(e) => return Err(e),
}
}
Err(last_error.unwrap())
unreachable!("retry loop returns on success or final error")
}
// single attempt at downloading a file to disk
@@ -180,6 +199,7 @@ async fn download_file_once(
let response = client.get(url).await?;
let total = response.content_length().unwrap_or(0);
tracing::trace!("Download content length for {}: {}", url, total);
if let Some(parent) = dest.parent() {
tokio::fs::create_dir_all(parent).await?;
@@ -194,6 +214,7 @@ async fn download_file_once(
downloaded += chunk.len() as u64;
progress_cb(downloaded, total);
}
file.flush().await?;
Ok(())
}
@@ -217,12 +238,28 @@ pub fn detect_java_path() -> 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() {
tracing::trace!("Detected Java from JAVA_HOME: {}", bin.display());
return bin.to_string_lossy().to_string();
}
tracing::warn!(
"JAVA_HOME is set to {}, but {} does not exist",
java_home,
bin.display()
);
}
match which::which("java") {
Ok(path) => {
tracing::trace!("Detected Java from PATH: {}", path.display());
path.to_string_lossy().to_string()
}
Err(e) => {
tracing::warn!(
"Could not find java on PATH, falling back to literal 'java': {}",
e
);
"java".to_string()
}
}
which::which("java")
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_else(|_| "java".to_string())
}
// converts maven coordinates like "org.example:artifact:1.0" into a
@@ -297,5 +334,4 @@ mod tests {
fn maven_empty_string() {
assert_eq!(maven_coord_to_path(""), None);
}
}
+56 -5
View File
@@ -66,9 +66,16 @@ pub fn loader_from_dependencies(
];
for (key, loader) in &loaders {
if let Some(version) = deps.get(*key) {
tracing::trace!(
"Resolved Modrinth loader dependency {}={} as {}",
key,
version,
loader
);
return (Some(*loader), Some(version.clone()));
}
}
tracing::trace!("No Modrinth loader dependency found; treating pack as vanilla");
(None, None)
}
@@ -101,7 +108,14 @@ pub async fn fetch_project(
slug_or_id: &str,
) -> Result<ProjectInfo, crate::net::NetError> {
let url = format!("{}/project/{}", API_BASE, url_encode(slug_or_id));
client.get_json(&url).await
tracing::debug!("Fetching Modrinth project '{}'", slug_or_id);
let project: ProjectInfo = client.get_json(&url).await?;
tracing::debug!(
"Fetched Modrinth project '{}' ({})",
project.slug,
project.id
);
Ok(project)
}
pub async fn fetch_versions(
@@ -113,7 +127,14 @@ pub async fn fetch_versions(
API_BASE,
url_encode(slug_or_id)
);
client.get_json(&url).await
tracing::debug!("Fetching Modrinth versions for project '{}'", slug_or_id);
let versions: Vec<VersionInfo> = client.get_json(&url).await?;
tracing::debug!(
"Fetched {} Modrinth version(s) for project '{}'",
versions.len(),
slug_or_id
);
Ok(versions)
}
pub async fn fetch_version(
@@ -121,7 +142,15 @@ pub async fn fetch_version(
version_id: &str,
) -> Result<VersionInfo, crate::net::NetError> {
let url = format!("{}/version/{}", API_BASE, url_encode(version_id));
client.get_json(&url).await
tracing::debug!("Fetching Modrinth version '{}'", version_id);
let version: VersionInfo = client.get_json(&url).await?;
tracing::debug!(
"Fetched Modrinth version '{}' ({}) with {} file(s)",
version.name,
version.id,
version.files.len()
);
Ok(version)
}
// grabs the primary file from a version, falling back to the first file
@@ -135,22 +164,44 @@ pub async fn download_mrpack(
.files
.iter()
.find(|f| f.primary)
.or_else(|| version.files.first())
.or_else(|| {
tracing::warn!(
"Modrinth version '{}' has no primary file; using first file",
version.id
);
version.files.first()
})
.ok_or_else(|| crate::net::NetError::Parse("No files in version".to_string()))?;
let mrpack_path = dest.join(&file.filename);
tracing::info!(
"Downloading Modrinth pack file '{}' for version '{}' to {}",
file.filename,
version.id,
mrpack_path.display()
);
crate::net::download_file(client, &file.url, &mrpack_path, |_, _| {}).await?;
Ok(mrpack_path)
}
// .mrpack is just a zip with modrinth.index.json at the root
pub fn parse_mrpack(path: &std::path::Path) -> Result<MrpackIndex, String> {
tracing::debug!("Parsing .mrpack manifest from {}", path.display());
let file = std::fs::File::open(path).map_err(|e| format!("Cannot open .mrpack: {e}"))?;
let mut archive = zip::ZipArchive::new(file).map_err(|e| format!("Invalid ZIP: {e}"))?;
let entry = archive
.by_name("modrinth.index.json")
.map_err(|_| "Missing modrinth.index.json in .mrpack".to_string())?;
serde_json::from_reader(entry).map_err(|e| format!("Invalid manifest JSON: {e}"))
let index: MrpackIndex =
serde_json::from_reader(entry).map_err(|e| format!("Invalid manifest JSON: {e}"))?;
tracing::debug!(
"Parsed .mrpack '{}' version_id={} files={} deps={}",
index.name,
index.version_id,
index.files.len(),
index.dependencies.len()
);
Ok(index)
}
#[cfg(test)]
+71 -9
View File
@@ -120,7 +120,15 @@ pub async fn fetch_version_manifest_from(
client: &HttpClient,
url: &str,
) -> Result<VersionManifest, NetError> {
client.get_json(url).await
tracing::debug!("Fetching Mojang version manifest from {}", url);
let manifest: VersionManifest = client.get_json(url).await?;
tracing::debug!(
"Fetched Mojang manifest with {} version(s); latest release={} snapshot={}",
manifest.versions.len(),
manifest.latest.release,
manifest.latest.snapshot
);
Ok(manifest)
}
// fetches and parses a version's metadata. also returns the raw response
@@ -131,6 +139,11 @@ pub async fn fetch_version_meta_with_raw(
client: &HttpClient,
entry: &VersionEntry,
) -> Result<(VersionMeta, Vec<u8>), NetError> {
tracing::debug!(
"Fetching Mojang version meta '{}' from {}",
entry.id,
entry.url
);
client.get_json_with_raw(&entry.url, "version meta").await
}
@@ -146,10 +159,16 @@ pub async fn download_client_jar(
if jar_path.exists() {
tracing::info!("Client JAR already cached: {}", meta.id);
tracing::trace!("Cached client JAR path: {}", jar_path.display());
return Ok(());
}
set_action(format!("Downloading Minecraft {}...", meta.id));
tracing::info!(
"Downloading Minecraft client JAR {} to {}",
meta.id,
jar_path.display()
);
let result = download_file(
client,
@@ -171,6 +190,11 @@ pub async fn download_libraries(
meta_dir: &Path,
) -> Result<(), NetError> {
set_action("Downloading libraries...");
tracing::debug!(
"Resolving {} libraries for Minecraft {}",
meta.libraries.len(),
meta.id
);
let features = crate::launch_profile::rules::FeatureSet::default();
let host_os_version = crate::launch_profile::system::mojang_os_version();
@@ -186,17 +210,25 @@ pub async fn download_libraries(
if let Some(rules) = &library.rules
&& !crate::launch_profile::rules::evaluate(rules, &rule_ctx)
{
tracing::trace!("Skipping library {} due to platform rules", library.name);
continue;
}
let artifact = match &library.downloads.artifact {
Some(artifact) => artifact,
None => continue,
None => {
tracing::trace!(
"Skipping library {} without artifact download",
library.name
);
continue;
}
};
let destination = meta_dir.join("libraries").join(&artifact.path);
if destination.exists() {
tracing::trace!("Library already cached: {}", artifact.path);
continue;
}
@@ -209,6 +241,7 @@ pub async fn download_libraries(
return Ok(());
}
tracing::debug!("Downloading {} missing libraries", downloads.len());
let result = run_parallel_downloads(client, downloads, false).await;
clear();
result
@@ -231,6 +264,11 @@ pub async fn download_assets_from(
assets_base: &str,
) -> Result<(), NetError> {
set_action("Downloading assets...");
tracing::debug!(
"Fetching asset index {} from {}",
meta.asset_index.id,
meta.asset_index.url
);
let asset_index: AssetIndexContent = match client.get_json(&meta.asset_index.url).await {
Ok(index) => index,
@@ -251,19 +289,25 @@ pub async fn download_assets_from(
match tokio::fs::create_dir_all(parent).await {
Ok(_) => {}
Err(e) => {
tracing::error!("Failed to create asset index dir: {}", e);
tracing::debug!("Failed to create asset index dir: {}", e);
}
}
}
match tokio::fs::write(&index_path, json).await {
Ok(_) => {}
Ok(_) => {
tracing::debug!("Saved asset index to {}", index_path.display());
}
Err(e) => {
tracing::error!("Failed to write asset index: {}", e);
tracing::debug!(
"Failed to write asset index {}: {}",
index_path.display(),
e
);
}
}
}
Err(e) => {
tracing::error!("Failed to serialize asset index: {}", e);
tracing::debug!("Failed to serialize asset index: {}", e);
}
}
}
@@ -301,6 +345,11 @@ pub async fn download_assets_from(
return Ok(());
}
tracing::debug!(
"Downloading {} missing asset(s) from index {}",
downloads.len(),
meta.asset_index.id
);
let result = run_parallel_downloads(client, downloads, true).await;
clear();
result
@@ -315,6 +364,11 @@ async fn run_parallel_downloads(
report_count_progress: bool,
) -> Result<(), NetError> {
let total_downloads = downloads.len() as u64;
tracing::debug!(
"Starting {} parallel download job(s), max_concurrent={}",
total_downloads,
MAX_CONCURRENT_DOWNLOADS
);
let completed = Arc::new(AtomicU64::new(0));
let mut queue = downloads.into_iter();
let mut set = JoinSet::new();
@@ -340,13 +394,13 @@ async fn run_parallel_downloads(
set_sub_action(label);
}
Ok(Err(e)) => {
tracing::error!("Download failed: {}", e);
tracing::debug!("Download failed: {}", e);
if first_error.is_none() {
first_error = Some(e);
}
}
Err(e) => {
tracing::error!("Task panicked: {}", e);
tracing::debug!("Task panicked: {}", e);
if first_error.is_none() {
first_error = Some(NetError::TaskFailed(format!("Join error: {}", e)));
}
@@ -376,8 +430,16 @@ fn spawn_download_task(
let task_client = client.clone();
set.spawn(async move {
tracing::trace!(
"Starting parallel download '{}' to {}",
label,
destination.display()
);
let result = download_file(&task_client, &url, &destination, |_current, _total| {}).await;
result.map(|()| label)
result.map(|()| {
tracing::trace!("Finished parallel download '{}'", label);
label
})
});
}
+78 -17
View File
@@ -8,6 +8,7 @@ use std::path::Path;
use serde::Deserialize;
use crate::instance::loader::GameVersion;
use crate::instance::loader::InstallerError;
use crate::net::{HttpClient, NetError, download_file};
use crate::tui::progress::set_action;
@@ -20,8 +21,10 @@ struct NeoForgeMavenVersions {
versions: Vec<String>,
}
// neoforge dropped the "1." from minecraft versions in their scheme,
// so "1.20.4" becomes prefix "20.4." and "1.21" becomes "21.0."
// neoforge historically dropped the "1." from minecraft versions in
// their scheme, so "1.20.4" becomes prefix "20.4." and "1.21" becomes
// "21.0.". newer minecraft versions such as "26.1.2" keep their full
// version at the start of the neoforge coordinate: "26.1.2.76".
fn game_version_to_neoforge_prefix(game_version: &str) -> Option<String> {
let parts: Vec<&str> = game_version.split('.').collect();
match parts.as_slice() {
@@ -29,10 +32,45 @@ 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)),
// "26.1.2" → prefix "26.1.2."
[major, minor, patch] if leading_u32(major).is_some_and(|major| major >= 26) => {
Some(format!("{major}.{minor}.{patch}."))
}
// "26.1" → prefix "26.1."
[major, minor] if leading_u32(major).is_some_and(|major| major >= 26) => {
Some(format!("{major}.{minor}."))
}
_ => None,
}
}
fn leading_u32(raw: &str) -> Option<u32> {
let digits: String = raw.chars().take_while(|c| c.is_ascii_digit()).collect();
if digits.is_empty() {
None
} else {
digits.parse().ok()
}
}
fn neoforge_version_to_game_version(version: &str) -> Option<String> {
let parts: Vec<&str> = version.split('.').collect();
let major = leading_u32(parts.first()?)?;
if major >= 26 {
let minor = leading_u32(parts.get(1)?)?;
let patch = leading_u32(parts.get(2)?)?;
return Some(format!("{major}.{minor}.{patch}"));
}
let minor = leading_u32(parts.get(1)?)?;
Some(if minor == 0 {
format!("1.{major}")
} else {
format!("1.{major}.{minor}")
})
}
pub async fn fetch_neoforge_versions(
client: &HttpClient,
game_version: &str,
@@ -64,6 +102,12 @@ pub async fn fetch_neoforge_versions_from(
.filter(|v| v.starts_with(&prefix) && !v.contains("-beta") && !v.contains("-alpha"))
.collect();
tracing::debug!(
"Resolved {} NeoForge version(s) for Minecraft {} with prefix {}",
versions.len(),
game_version,
prefix
);
Ok(versions)
}
@@ -83,22 +127,14 @@ pub async fn fetch_neoforge_game_versions_from(
let mut game_versions: Vec<String> = Vec::new();
for version in &maven.versions {
let parts: Vec<&str> = version.split('.').collect();
if parts.len() >= 2
&& let (Ok(major), Ok(minor)) = (parts[0].parse::<u32>(), parts[1].parse::<u32>())
if let Some(mc_version) = neoforge_version_to_game_version(version)
&& !game_versions.contains(&mc_version)
{
let mc_version = if minor == 0 {
format!("1.{}", major)
} else {
format!("1.{}.{}", major, minor)
};
if !game_versions.contains(&mc_version) {
game_versions.push(mc_version);
}
game_versions.push(mc_version);
}
}
game_versions.reverse();
tracing::debug!("Resolved {} NeoForge game version(s)", game_versions.len());
Ok(game_versions
.into_iter()
@@ -120,6 +156,11 @@ pub async fn download_neoforge_installer(
);
set_action(format!("Downloading NeoForge {}...", neoforge_version));
tracing::info!(
"Downloading NeoForge installer {} to {}",
neoforge_version,
dest.display()
);
download_file(client, &url, dest, |downloaded, total| {
crate::tui::progress::set_progress(downloaded, total);
@@ -131,12 +172,13 @@ pub async fn run_neoforge_installer(
installer_path: &Path,
instance_dir: &Path,
java_path: &str,
) -> Result<(), NetError> {
) -> Result<(), InstallerError> {
use tokio::process::Command;
set_action("Running NeoForge installer...");
let output = match Command::new(java_path)
.arg(format!("-Duser.home={}", instance_dir.display()))
.arg("-jar")
.arg(installer_path)
.arg("--installClient")
@@ -146,17 +188,32 @@ pub async fn run_neoforge_installer(
{
Ok(o) => o,
Err(e) => {
return Err(NetError::Io(e));
tracing::debug!(
"Failed to spawn NeoForge installer {} with Java {}: {}",
installer_path.display(),
java_path,
e
);
return Err(InstallerError::Io(e));
}
};
if !output.status.success() {
return Err(NetError::InstallerFailed(format!(
let stderr = String::from_utf8_lossy(&output.stderr);
let detail = stderr.lines().last().unwrap_or("").trim();
tracing::debug!(
"NeoForge installer {} failed with status {:?}: {}",
installer_path.display(),
output.status.code(),
detail
);
return Err(InstallerError::ProcessFailed(format!(
"NeoForge installer exited with {:?}",
output.status.code()
)));
}
tracing::debug!("NeoForge installer completed successfully");
Ok(())
}
@@ -207,6 +264,10 @@ mod tests {
game_version_to_neoforge_prefix("1.21.1"),
Some("21.1.".to_string())
);
assert_eq!(
game_version_to_neoforge_prefix("26.1.2"),
Some("26.1.2.".to_string())
);
assert_eq!(game_version_to_neoforge_prefix("invalid"), None);
}
}
+27 -1
View File
@@ -52,7 +52,9 @@ pub async fn fetch_quilt_game_versions_from(
meta_base: &str,
) -> Result<Vec<GameVersion>, NetError> {
let url = format!("{}/versions/game", meta_base);
tracing::debug!("Fetching Quilt game versions from {}", url);
let versions: Vec<QuiltGameVersion> = client.get_json(&url).await?;
tracing::debug!("Fetched {} Quilt game version(s)", versions.len());
Ok(versions
.into_iter()
@@ -76,7 +78,14 @@ pub async fn fetch_quilt_versions_from(
game_version: &str,
) -> Result<Vec<QuiltLoaderVersion>, NetError> {
let url = format!("{}/versions/loader/{}", meta_base, game_version);
client.get_json(&url).await
tracing::debug!("Fetching Quilt loader versions for {}", game_version);
let versions: Vec<QuiltLoaderVersion> = client.get_json(&url).await?;
tracing::debug!(
"Fetched {} Quilt loader version(s) for {}",
versions.len(),
game_version
);
Ok(versions)
}
pub async fn fetch_quilt_profile(
@@ -97,6 +106,11 @@ pub async fn fetch_quilt_profile_from(
"{}/versions/loader/{}/{}/profile/json",
meta_base, game_version, loader_version
);
tracing::debug!(
"Fetching Quilt profile for Minecraft {} loader {}",
game_version,
loader_version
);
client.get_json(&url).await
}
@@ -122,6 +136,11 @@ pub async fn fetch_quilt_profile_with_raw_from(
"{}/versions/loader/{}/{}/profile/json",
meta_base, game_version, loader_version
);
tracing::debug!(
"Fetching raw Quilt profile for Minecraft {} loader {}",
game_version,
loader_version
);
client.get_json_with_raw(&url, "Quilt profile").await
}
@@ -131,6 +150,11 @@ pub async fn download_quilt_libraries(
meta_dir: &Path,
) -> Result<(), NetError> {
let libraries_dir = meta_dir.join("libraries");
tracing::debug!(
"Resolving {} Quilt libraries into {}",
profile.libraries.len(),
libraries_dir.display()
);
for lib in &profile.libraries {
let maven_path = match crate::net::maven_coord_to_path(&lib.name) {
@@ -155,10 +179,12 @@ pub async fn download_quilt_libraries(
set_sub_action(&lib.name);
tracing::info!("Downloading Quilt library: {}", lib.name);
tracing::trace!("Quilt library destination: {}", dest.display());
download_file(client, &download_url, &dest, |_, _| {}).await?;
}
tracing::debug!("Quilt library resolution complete for {}", profile.id);
Ok(())
}
+3
View File
@@ -33,12 +33,14 @@ pub static KILL_SENDERS: LazyLock<KillSenders> =
pub fn set_state(name: &str, state: RunState) {
if let Ok(mut map) = RUNNING.lock() {
map.insert(name.to_string(), state);
crate::tui::request_redraw();
}
}
pub fn remove(name: &str) {
if let Ok(mut map) = RUNNING.lock() {
map.remove(name);
crate::tui::request_redraw();
}
}
@@ -59,6 +61,7 @@ pub fn all() -> Vec<(String, RunState)> {
pub fn push_last_played(name: &str, time: DateTime<Utc>) {
if let Ok(mut q) = PENDING_LAST_PLAYED.lock() {
q.push((name.to_string(), time));
crate::tui::request_redraw();
}
}
+2
View File
@@ -29,6 +29,7 @@ pub struct App {
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) settings_state: widgets::settings::SettingsState,
pub(super) picker: ratatui_image::picker::Picker,
pub(super) instance_manager: InstanceManager,
pub(super) log_overlay_scroll: usize,
@@ -87,6 +88,7 @@ impl App {
worlds_state: widgets::content::list::ContentListState::default(),
logs_state: widgets::logs_viewer::LogsState::default(),
account_state: widgets::account::AccountState::default(),
settings_state: widgets::settings::SettingsState::new(manager.meta_dir.clone()),
screenshots_state: {
let mut s = widgets::screenshots_grid::ScreenshotsState::default();
s.font_size = picker.font_size();
+8 -1
View File
@@ -38,6 +38,7 @@ pub fn push_error(event: ErrorEvent) {
while events.len() > MAX_ERROR_EVENTS {
events.pop_front();
}
crate::tui::request_redraw();
}
Err(e) => {
tracing::error!("Error buffer lock poisoned: {}", e);
@@ -56,7 +57,13 @@ pub fn has_errors() -> bool {
#[must_use]
pub fn pop_error() -> Option<ErrorEvent> {
match ERROR_EVENTS.lock() {
Ok(mut events) => events.pop_front(),
Ok(mut events) => {
let event = events.pop_front();
if event.is_some() {
crate::tui::request_redraw();
}
event
}
Err(_) => None,
}
}
+43 -16
View File
@@ -11,9 +11,13 @@ use crate::tui::error_buffer;
use crate::tui::progress;
impl App {
/// main loop: drain async results, render, handle input, repeat at ~60fps
/// main loop: poll async results and input at ~60Hz, drawing only when state changes
pub async fn run(&mut self, terminal: &mut Tui) -> color_eyre::Result<()> {
let mut last_draw = std::time::Instant::now()
.checked_sub(Duration::from_secs(1))
.unwrap_or_else(std::time::Instant::now);
while !self.exit {
let redraw_requested = super::take_redraw_request();
// check if any popup wizard finished and wants to create/import
if let Some(params) = new_instance::take_result() {
self.spawn_create(params);
@@ -32,12 +36,20 @@ impl App {
self.drain_pending_last_played();
self.mods_state.drain_pending();
self.mods_state.drain_watcher();
self.mods_state.request_image_loads(&self.picker);
self.mods_state.drain_image_loads(&self.picker);
self.resource_packs_state.drain_pending();
self.resource_packs_state.drain_watcher();
self.resource_packs_state.request_image_loads(&self.picker);
self.resource_packs_state.drain_image_loads(&self.picker);
self.shaders_state.drain_pending();
self.shaders_state.drain_watcher();
self.shaders_state.request_image_loads(&self.picker);
self.shaders_state.drain_image_loads(&self.picker);
self.worlds_state.drain_pending();
self.worlds_state.drain_watcher();
self.worlds_state.request_image_loads(&self.picker);
self.worlds_state.drain_image_loads(&self.picker);
self.logs_state.drain_pending();
self.logs_state.try_rescan();
self.account_state.drain_auth_result();
@@ -45,14 +57,26 @@ impl App {
self.screenshots_state.drain_pending_entries();
self.screenshots_state.request_visible_loads();
self.create_screenshot_protocols();
// only advance the spinner every 8 ticks to keep it readable
self.throbber_tick = self.throbber_tick.wrapping_add(1);
if self.throbber_tick.is_multiple_of(8) {
self.throbber_state.calc_next();
let progress_active = progress::is_active();
if progress_active {
// only advance the spinner every 8 ticks to keep it readable
self.throbber_tick = self.throbber_tick.wrapping_add(1);
if self.throbber_tick.is_multiple_of(8) {
self.throbber_state.calc_next();
}
}
terminal.draw(|frame| self.render_frame(frame))?;
self.handle_events().wrap_err("handle events failed")?;
let input_changed = self.handle_events().wrap_err("handle events failed")?;
let continuously_animated = progress_active || error_buffer::has_errors();
let safety_refresh = last_draw.elapsed() >= Duration::from_secs(1);
if input_changed
|| continuously_animated
|| safety_refresh
|| redraw_requested
{
terminal.draw(|frame| self.render_frame(frame))?;
last_draw = std::time::Instant::now();
}
if let Some(path) = self.pending_editor.take()
&& Self::run_editor(terminal, &path)
@@ -65,22 +89,24 @@ impl App {
// polls for input with a 16ms timeout (~60fps). only key presses are handled,
// releases and repeats are ignored thanks to the enhanced keyboard protocol
fn handle_events(&mut self) -> color_eyre::Result<()> {
fn handle_events(&mut self) -> color_eyre::Result<bool> {
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(()),
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(true)
}
Ok(_) => Ok(true),
Err(e) => {
tracing::error!("Event read error: {}", e);
Ok(())
Ok(false)
}
},
Ok(false) => Ok(()),
Ok(false) => Ok(false),
Err(e) => {
tracing::error!("Event poll error: {}", e);
Ok(())
Ok(false)
}
}
}
@@ -107,6 +133,7 @@ impl App {
Ok(config) => {
if let Ok(mut pending) = pending_instances.lock() {
pending.push(config);
crate::tui::request_redraw();
}
}
Err(e) => {
@@ -133,6 +160,7 @@ impl App {
Ok(config) => {
if let Ok(mut pending) = pending_instances.lock() {
pending.push(config);
crate::tui::request_redraw();
}
}
Err(e) => {
@@ -254,7 +282,6 @@ impl App {
let instance = match self.instance_manager.load_one(&instance.name) {
Ok(config) => config,
Err(e) => {
tracing::error!("Failed to load instance '{}': {}", instance.name, e);
error_buffer::push_error(error_buffer::ErrorEvent {
id: 0,
level: tracing::Level::ERROR,
+207 -31
View File
@@ -70,24 +70,69 @@ impl App {
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);
let focus_after = match confirm_popup::pending_target() {
Some(confirm_popup::ConfirmTarget::Instance { name }) => {
match self.instance_manager.delete(&name) {
Ok(_) => {
self.instances_state.remove_instance(&name);
}
Err(e) => {
tracing::error!("Failed to delete instance '{}': {}", name, e);
}
}
FocusedArea::Instances
}
}
Some(confirm_popup::ConfirmTarget::Account { index, .. }) => {
let count = self.account_state.store.accounts.len();
self.account_state.store.remove(index);
if count > 1 {
self.account_state.list_state.selected = Some(index.min(
self.account_state.store.accounts.len().saturating_sub(1),
));
} else {
self.account_state.list_state.selected = None;
}
FocusedArea::Account
}
Some(confirm_popup::ConfirmTarget::ConfigProfile { profile }) => {
if let Err(e) = self.delete_config_profile(&profile) {
error_buffer::push_error(error_buffer::ErrorEvent {
id: 0,
level: tracing::Level::ERROR,
message: e.to_string(),
pushed_at: std::time::Instant::now(),
});
}
FocusedArea::Settings
}
Some(confirm_popup::ConfirmTarget::Content { name, path }) => {
match delete_content_path(&path) {
Ok(()) => {
self.remove_content_path_from_states(&path);
}
Err(e) => {
tracing::error!("Failed to delete content '{}': {}", name, e);
}
}
FocusedArea::Content
}
None => FocusedArea::Instances,
};
confirm_popup::clear_pending();
self.focused = FocusedArea::Instances;
self.focused = focus_after;
return Ok(());
}
KeyCode::Esc | KeyCode::Char('n') | KeyCode::Char('N') => {
let focus_after = match confirm_popup::pending_target() {
Some(confirm_popup::ConfirmTarget::Content { .. }) => FocusedArea::Content,
Some(confirm_popup::ConfirmTarget::Account { .. }) => FocusedArea::Account,
Some(confirm_popup::ConfirmTarget::ConfigProfile { .. }) => {
FocusedArea::Settings
}
_ => FocusedArea::Instances,
};
confirm_popup::clear_pending();
self.focused = FocusedArea::Instances;
self.focused = focus_after;
return Ok(());
}
_ => {
@@ -97,17 +142,41 @@ impl App {
}
// content area delegates to whichever tab is active.
// worlds get handle_key_no_toggle because you can't "disable" a world like you can a mod
// worlds use the same list navigation without the toggle
if self.focused == FocusedArea::Content {
if self.content_tab == widgets::content::ContentTab::Logs {
if key_event.code == KeyCode::Char('d')
&& !self.logs_state.search.active
&& !self.logs_state.viewer_search.active
{
if let Some(pending) = self.logs_state.pending_delete() {
confirm_popup::set_pending_content_delete(pending.name, pending.path);
self.focused = FocusedArea::ConfirmDelete;
}
return Ok(());
}
if widgets::logs_viewer::handle_key(&key_event, &mut self.logs_state) {
return Ok(());
}
} else if self.content_tab == widgets::content::ContentTab::Screenshots {
if key_event.code == KeyCode::Char('d') && !self.screenshots_state.search.active {
if let Some(pending) = self.screenshots_state.pending_delete() {
confirm_popup::set_pending_content_delete(pending.name, pending.path);
self.focused = FocusedArea::ConfirmDelete;
}
return Ok(());
}
if widgets::screenshots_grid::handle_key(&key_event, &mut self.screenshots_state) {
return Ok(());
}
} else if self.content_tab == widgets::content::ContentTab::Worlds {
if key_event.code == KeyCode::Char('d') && !self.worlds_state.search.active {
if let Some(pending) = self.worlds_state.pending_delete() {
confirm_popup::set_pending_content_delete(pending.name, pending.path);
self.focused = FocusedArea::ConfirmDelete;
}
return Ok(());
}
if widgets::content::list::handle_key_no_toggle(&key_event, &mut self.worlds_state)
{
return Ok(());
@@ -121,14 +190,34 @@ impl App {
widgets::content::ContentTab::Shaders => Some(&mut self.shaders_state),
_ => None,
};
if let Some(state) = state
&& widgets::content::list::handle_key(&key_event, state)
{
return Ok(());
if let Some(state) = state {
if key_event.code == KeyCode::Char('d') && !state.search.active {
if let Some(pending) = state.pending_delete() {
confirm_popup::set_pending_content_delete(pending.name, pending.path);
self.focused = FocusedArea::ConfirmDelete;
}
return Ok(());
}
if widgets::content::list::handle_key(&key_event, state) {
return Ok(());
}
}
}
}
if self.focused == FocusedArea::Account
&& let KeyCode::Char('d') = key_event.code
&& let Some(index) = self.account_state.list_state.selected
&& let Some(account) = self.account_state.store.accounts.get(index)
{
confirm_popup::set_pending(confirm_popup::ConfirmTarget::Account {
username: account.username.clone(),
index,
});
self.focused = FocusedArea::ConfirmDelete;
return Ok(());
}
if self.focused == FocusedArea::Account
&& widgets::account::handle_key(&key_event, &mut self.account_state)
{
@@ -138,6 +227,7 @@ impl App {
if self.focused == FocusedArea::Settings {
match widgets::settings::handle_key(
&key_event,
&mut self.settings_state,
self.instances_state.selected_instance(),
&self.instance_manager.instances_dir,
) {
@@ -173,6 +263,53 @@ impl App {
}
return Ok(());
}
widgets::settings::SettingsAction::SelectProfile(profile) => {
if let Some(inst) = self.instances_state.selected_instance().cloned() {
let instance_dir = self.instance_manager.instances_dir.join(&inst.name);
match crate::instance::config_sync::switch_profile(
&inst.name,
inst.config_sync_profile.as_deref(),
profile.as_deref(),
&self.instance_manager.meta_dir,
&instance_dir,
) {
Ok(selected) => {
let mut updated = inst.clone();
updated.config_sync_profile = selected;
if let Err(e) = self.instance_manager.save(&updated) {
tracing::error!("Failed to save config profile: {}", e);
} else {
self.instances_state.replace_instance(&inst.name, updated);
}
}
Err(e) => {
error_buffer::push_error(error_buffer::ErrorEvent {
id: 0,
level: tracing::Level::ERROR,
message: e.to_string(),
pushed_at: std::time::Instant::now(),
});
}
}
}
return Ok(());
}
widgets::settings::SettingsAction::ConfirmDeleteProfile(profile) => {
confirm_popup::set_pending(confirm_popup::ConfirmTarget::ConfigProfile {
profile,
});
self.focused = FocusedArea::ConfirmDelete;
return Ok(());
}
widgets::settings::SettingsAction::Error(message) => {
error_buffer::push_error(error_buffer::ErrorEvent {
id: 0,
level: tracing::Level::ERROR,
message,
pushed_at: std::time::Instant::now(),
});
return Ok(());
}
widgets::settings::SettingsAction::None => {}
}
}
@@ -192,20 +329,14 @@ impl App {
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);
}
if let Ok(()) = self.instance_manager.rename(&old_name, &new_name)
&& let Some(inst) = self
.instances_state
.instances
.iter_mut()
.find(|i| i.name == old_name)
{
inst.name = new_name.trim().to_owned();
}
}
}
@@ -259,7 +390,7 @@ impl App {
{
if let Some(instance) = self.instances_state.selected_instance() {
let name = instance.name.clone();
confirm_popup::set_pending_delete(&name);
confirm_popup::set_pending_instance_delete(&name);
self.focused = FocusedArea::ConfirmDelete;
}
}
@@ -345,4 +476,49 @@ impl App {
Ok(())
}
fn delete_config_profile(&mut self, profile: &str) -> color_eyre::Result<()> {
let instances = self.instance_manager.load_all();
for instance in instances
.into_iter()
.filter(|instance| instance.config_sync_profile.as_deref() == Some(profile))
{
let instance_dir = self.instance_manager.instances_dir.join(&instance.name);
let mut updated = instance.clone();
updated.config_sync_profile = crate::instance::config_sync::switch_profile(
&instance.name,
instance.config_sync_profile.as_deref(),
None,
&self.instance_manager.meta_dir,
&instance_dir,
)?;
self.instance_manager.save(&updated)?;
self.instances_state
.replace_instance(&instance.name, updated);
}
crate::instance::config_sync::delete_profile(&self.instance_manager.meta_dir, profile)?;
self.settings_state
.profiles
.retain(|candidate| candidate != profile);
Ok(())
}
fn remove_content_path_from_states(&mut self, path: &std::path::Path) {
self.mods_state.remove_path(path);
self.resource_packs_state.remove_path(path);
self.shaders_state.remove_path(path);
self.worlds_state.remove_path(path);
self.screenshots_state.remove_path(path);
self.logs_state.remove_path(path);
}
}
fn delete_content_path(path: &std::path::Path) -> std::io::Result<()> {
match std::fs::metadata(path) {
Ok(meta) if meta.is_dir() => std::fs::remove_dir_all(path),
Ok(_) => std::fs::remove_file(path),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(e),
}
}
+59 -9
View File
@@ -8,6 +8,7 @@ use std::sync::{Arc, Mutex};
use tracing::field::{Field, Visit};
use tracing::{Level, Subscriber};
use tracing_appender::non_blocking::WorkerGuard;
use tracing_subscriber::filter::filter_fn;
use tracing_subscriber::layer::Context;
use tracing_subscriber::prelude::*;
use tracing_subscriber::{EnvFilter, Layer};
@@ -16,6 +17,9 @@ use std::sync::LazyLock;
use crate::tui::error_buffer::{self, ErrorEvent};
const MINECRAFT_LOG_TARGET: &str = "mc_instance";
const DEFAULT_FILE_FILTER: &str = "warn,rmcl=trace";
// capped at 5000 lines so it doesn't eat all the ram if something goes haywire
static APP_LOG_LINES: LazyLock<Arc<Mutex<Vec<String>>>> =
LazyLock::new(|| Arc::new(Mutex::new(Vec::new())));
@@ -58,10 +62,10 @@ pub fn init() -> WorkerGuard {
let file_appender = tracing_appender::rolling::never(&log_dir, format!("rmcl_{now}.log"));
let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);
let env_filter = EnvFilter::builder()
.with_default_directive(Level::INFO.into())
.from_env_lossy()
.add_directive("mc_instance=off".parse().unwrap());
let file_filter =
EnvFilter::try_from_env("RUST_LOG").unwrap_or_else(|_| EnvFilter::new(DEFAULT_FILE_FILTER));
let file_filter =
file_filter.add_directive(format!("{MINECRAFT_LOG_TARGET}=off").parse().unwrap());
let rust_log = std::env::var("RUST_LOG").unwrap_or_default().to_lowercase();
let tui_level = if rust_log.contains("debug") || rust_log.contains("trace") {
@@ -83,10 +87,18 @@ pub fn init() -> WorkerGuard {
tracing_subscriber::fmt::layer()
.with_writer(non_blocking)
.with_ansi(false)
.with_filter(env_filter),
.with_filter(file_filter),
)
.with(
tui_logger::TuiTracingSubscriberLayer.with_filter(filter_fn(|metadata| {
should_record_app_log(metadata.target(), *metadata.level())
})),
)
.with(
StatusLayer::new(error_buffer::ERROR_EVENTS.clone()).with_filter(filter_fn(
|metadata| should_record_app_log(metadata.target(), *metadata.level()),
)),
)
.with(tui_logger::TuiTracingSubscriberLayer)
.with(StatusLayer::new(error_buffer::ERROR_EVENTS.clone()))
.init();
guard
@@ -119,9 +131,11 @@ impl<S: Subscriber> Layer<S> for StatusLayer {
Level::TRACE => "TRACE",
};
let now = chrono::Local::now().format("%H:%M:%S");
push_app_log(format!("{now}:{level_str}:{target}: {}", visitor.message));
if should_record_app_log(target, level) {
push_app_log(format!("{now}:{level_str}:{target}: {}", visitor.message));
}
if level <= Level::WARN {
if level <= Level::WARN && should_record_app_log(target, level) {
error_buffer::push_error(ErrorEvent {
id: 0,
level,
@@ -132,6 +146,14 @@ impl<S: Subscriber> Layer<S> for StatusLayer {
}
}
fn should_record_app_log(target: &str, level: Level) -> bool {
if target == MINECRAFT_LOG_TARGET {
return false;
}
target == "rmcl" || target.starts_with("rmcl::") || level <= Level::WARN
}
#[derive(Default)]
struct MessageVisitor {
message: String,
@@ -157,3 +179,31 @@ impl Visit for MessageVisitor {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn minecraft_events_are_not_general_app_logs() {
assert!(!should_record_app_log(MINECRAFT_LOG_TARGET, Level::ERROR));
}
#[test]
fn rmcl_events_are_general_app_logs() {
assert!(should_record_app_log(
"rmcl::instance::manager",
Level::TRACE
));
}
#[test]
fn dependency_debug_events_are_not_general_app_logs() {
assert!(!should_record_app_log("log", Level::DEBUG));
}
#[test]
fn dependency_warnings_are_general_app_logs() {
assert!(should_record_app_log("notify", Level::WARN));
}
}
+32 -1
View File
@@ -9,6 +9,18 @@ pub mod progress;
mod render;
pub mod widgets;
use std::sync::atomic::{AtomicBool, Ordering};
static REDRAW_REQUESTED: AtomicBool = AtomicBool::new(true);
pub fn request_redraw() {
REDRAW_REQUESTED.store(true, Ordering::Release);
}
pub(super) fn take_redraw_request() -> bool {
REDRAW_REQUESTED.swap(false, Ordering::AcqRel)
}
pub type Tui = ratatui::DefaultTerminal;
pub async fn show() -> color_eyre::Result<()> {
@@ -37,8 +49,27 @@ pub async fn show() -> color_eyre::Result<()> {
// figure out the terminal's font cell size for rendering images.
// falls back to halfblock characters if the terminal doesn't respond
let picker = ratatui_image::picker::Picker::from_query_stdio()
let mut picker = ratatui_image::picker::Picker::from_query_stdio()
.unwrap_or_else(|_| ratatui_image::picker::Picker::halfblocks());
let detected_protocol = picker.protocol_type();
let requested_protocol = match crate::config::SETTINGS.ui.image_protocol {
crate::config::settings::ImageProtocol::Halfblocks
| crate::config::settings::ImageProtocol::Quadrants => {
ratatui_image::picker::ProtocolType::Halfblocks
}
crate::config::settings::ImageProtocol::Kitty
if detected_protocol == ratatui_image::picker::ProtocolType::Kitty =>
{
ratatui_image::picker::ProtocolType::Kitty
}
crate::config::settings::ImageProtocol::Iterm2
if detected_protocol == ratatui_image::picker::ProtocolType::Iterm2 =>
{
ratatui_image::picker::ProtocolType::Iterm2
}
_ => ratatui_image::picker::ProtocolType::Halfblocks,
};
picker.set_protocol_type(requested_protocol);
let result = app::App::new(picker).run(&mut terminal).await;
+10
View File
@@ -19,6 +19,7 @@ pub fn set_action(text: impl Into<String>) {
match PROGRESS.lock() {
Ok(mut state) => {
state.current_action = Some(text.clone());
crate::tui::request_redraw();
}
Err(e) => {
tracing::error!("Progress lock poisoned: {}", e);
@@ -31,6 +32,7 @@ pub fn set_progress(current: u64, total: u64) {
match PROGRESS.lock() {
Ok(mut state) => {
state.progress = Some((current, total));
crate::tui::request_redraw();
}
Err(e) => {
tracing::error!("Progress lock poisoned: {}", e);
@@ -43,6 +45,7 @@ pub fn set_sub_action(text: impl Into<String>) {
match PROGRESS.lock() {
Ok(mut state) => {
state.sub_action = Some(text.clone());
crate::tui::request_redraw();
}
Err(e) => {
tracing::error!("Progress lock poisoned: {}", e);
@@ -57,9 +60,16 @@ pub fn clear() {
state.current_action = None;
state.progress = None;
state.sub_action = None;
crate::tui::request_redraw();
}
Err(e) => {
tracing::error!("Progress lock poisoned: {}", e);
}
}
}
pub fn is_active() -> bool {
PROGRESS
.lock()
.is_ok_and(|state| state.current_action.is_some())
}
+9 -8
View File
@@ -65,13 +65,14 @@ impl App {
&mut self.screenshots_state,
&mut self.logs_state,
&self.instance_manager.instances_dir,
&self.picker,
);
let bottom_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage(30),
Constraint::Percentage(40),
Constraint::Percentage(24),
Constraint::Percentage(46),
Constraint::Percentage(30),
])
.split(main_chunks[2]);
@@ -86,6 +87,7 @@ impl App {
frame,
bottom_chunks[1],
self.focused,
&mut self.settings_state,
self.instances_state.selected_instance(),
&self.instance_manager.instances_dir,
);
@@ -123,12 +125,11 @@ impl App {
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);
}
if self.focused == FocusedArea::ConfirmDelete
&& let Some(target) = confirm_popup::pending_target()
{
let area = confirm_popup_area(frame.area(), &target);
frame.render_widget(ConfirmPopup::for_target(&target), area);
}
}
+5 -73
View File
@@ -27,7 +27,6 @@ pub enum AddMode {
ChooseType,
OfflineNameInput(String),
OfflineBlocked,
ConfirmDelete(usize),
DeviceCodeWaiting {
info: DeviceCodeInfo,
pending: Arc<Mutex<Option<AuthResult>>>,
@@ -163,28 +162,6 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut AccountState) -> bool {
}
_ => true,
},
AddMode::ConfirmDelete(idx) => {
let idx = *idx;
match key_event.code {
KeyCode::Enter | KeyCode::Char('y') | KeyCode::Char('Y') => {
let count = state.store.accounts.len();
state.store.remove(idx);
if count > 1 {
state.list_state.selected =
Some(idx.min(state.store.accounts.len().saturating_sub(1)));
} else {
state.list_state.selected = None;
}
state.add_mode = AddMode::None;
true
}
KeyCode::Esc | KeyCode::Char('n') | KeyCode::Char('N') => {
state.add_mode = AddMode::None;
true
}
_ => true,
}
}
AddMode::None => {
let count = state.store.accounts.len();
match key_event.code {
@@ -192,12 +169,6 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut AccountState) -> bool {
state.add_mode = AddMode::ChooseType;
true
}
KeyCode::Char('d') => {
if let Some(idx) = state.list_state.selected {
state.add_mode = AddMode::ConfirmDelete(idx);
}
true
}
KeyCode::Enter => {
if let Some(idx) = state.list_state.selected {
state.store.set_active(idx);
@@ -276,7 +247,6 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut A
AddMode::ChooseType => render_choose_popup(frame),
AddMode::OfflineNameInput(name) => render_offline_popup(frame, name),
AddMode::OfflineBlocked => render_offline_blocked_popup(frame),
AddMode::ConfirmDelete(idx) => render_confirm_delete(frame, state, *idx),
AddMode::DeviceCodeWaiting { info, .. } => render_device_code_popup(frame, info),
AddMode::None => {}
}
@@ -310,9 +280,11 @@ fn render_account_list(
let (username, acc_type, is_active) = &accounts[context.index];
let show_selected = is_focused && context.is_selected;
let stripe_bg = theme.background();
let bg = stripe_bg;
let bg = if show_selected {
theme.stripe()
} else {
theme.background()
};
let active_marker = if *is_active { "\u{25b8} " } else { " " };
@@ -493,46 +465,6 @@ fn render_offline_blocked_popup(frame: &mut Frame) {
.render(area, frame.buffer_mut());
}
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
.get(idx)
.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(border_color)
.add_modifier(Modifier::BOLD),
));
let body = "This will permanently remove this account";
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,
bg: Some(bg_color),
keybinds: Some(keybind_line(&[("Enter", " confirm")])),
search_line: None,
content: Box::new(move |inner, buf| {
Paragraph::new("This will permanently remove this account")
.style(Style::default().fg(text_color))
.render(inner, buf);
}),
}
.render(area, frame.buffer_mut());
}
fn render_device_code_popup(frame: &mut Frame, info: &DeviceCodeInfo) {
use super::popups::{base::PopupFrame, keybind_line};
let theme = THEME.as_ref();
+431 -54
View File
@@ -4,7 +4,7 @@
// also handles minecraft's formatting codes for colored mod names/descriptions
// because apparently mojang thought terminal UIs would need that. thanks guys
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::sync::{Arc, Mutex, mpsc};
@@ -16,12 +16,12 @@ use ratatui::{
text::{Line, Span, Text},
widgets::{Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState},
};
use ratatui_image::{CropOptions, Resize, StatefulImage, protocol::StatefulProtocol};
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
use crate::config::theme::THEME;
use crate::instance::content::mods::{ContentEntry, IconCell};
type SnapshotRow = (String, String, bool, Option<Vec<Vec<IconCell>>>);
type ScanOneFn = fn(&Path, &str, bool) -> ContentEntry;
struct CachedList {
@@ -29,6 +29,18 @@ struct CachedList {
selected: Option<usize>,
}
struct PendingContentImage {
file_stem: String,
path: std::path::PathBuf,
icon_lines: Vec<Vec<IconCell>>,
image: Option<image::DynamicImage>,
}
struct DisplayMetadata {
description: String,
has_description: bool,
}
// result from the notify-triggered background diff
struct WatcherDiff {
toggled: Vec<(String, bool, std::path::PathBuf)>,
@@ -42,6 +54,11 @@ pub struct ContentListState {
pub scrollbar_state: ScrollbarState,
pub loaded_for: Option<String>,
pub loading: bool,
image_protocols: HashMap<String, StatefulProtocol>,
requested_images: HashSet<String>,
pending_images: Arc<Mutex<Vec<PendingContentImage>>>,
images_dirty: bool,
display_metadata: HashMap<String, DisplayMetadata>,
pub search: crate::tui::widgets::search::SearchState,
cache: HashMap<String, CachedList>,
// streaming: individual entries arrive here during initial load
@@ -56,6 +73,12 @@ pub struct ContentListState {
content_ext: Option<&'static str>,
}
#[derive(Clone, Debug)]
pub struct PendingContentDelete {
pub name: String,
pub path: std::path::PathBuf,
}
impl Default for ContentListState {
fn default() -> Self {
Self {
@@ -64,6 +87,11 @@ impl Default for ContentListState {
scrollbar_state: ScrollbarState::default(),
loaded_for: None,
loading: false,
image_protocols: HashMap::new(),
requested_images: HashSet::new(),
pending_images: Arc::new(Mutex::new(Vec::new())),
images_dirty: true,
display_metadata: HashMap::new(),
search: crate::tui::widgets::search::SearchState::default(),
cache: HashMap::new(),
stream_rx: None,
@@ -77,6 +105,108 @@ impl Default for ContentListState {
}
impl ContentListState {
pub fn request_image_loads(&mut self, picker: &ratatui_image::picker::Picker) {
if !self.images_dirty {
return;
}
self.images_dirty = false;
let use_image_protocol =
picker.protocol_type() != ratatui_image::picker::ProtocolType::Halfblocks;
let use_quadrants = crate::config::SETTINGS.ui.image_protocol
== crate::config::settings::ImageProtocol::Quadrants;
if !use_image_protocol {
self.image_protocols.clear();
}
let valid_stems: HashSet<&str> = self
.entries
.iter()
.map(|entry| entry.file_stem.as_str())
.collect();
self.image_protocols
.retain(|stem, _| valid_stems.contains(stem.as_str()));
self.requested_images
.retain(|stem| valid_stems.contains(stem.as_str()));
let font_size = picker.font_size();
for entry in &self.entries {
if entry.icon_bytes.is_none()
|| !self.requested_images.insert(entry.file_stem.clone())
{
continue;
}
let file_stem = entry.file_stem.clone();
let path = entry.path.clone();
let bytes = entry.icon_bytes.clone().unwrap_or_default();
let rows = entry.icon_lines.as_ref().map_or(3, Vec::len) as u32;
let columns = square_icon_columns(rows as u16, font_size);
let pending = self.pending_images.clone();
tokio::spawn(async move {
let result = tokio::task::spawn_blocking(move || {
let image = image::load_from_memory(&bytes).ok()?;
let icon_lines = if use_quadrants {
crate::instance::content::mods::make_icon_quadrants_from_image(
&image,
columns,
rows as u16,
)
} else {
crate::instance::content::mods::make_icon_pixels_from_image(
&image,
columns,
rows as u16,
)
};
let side = rows * u32::from(font_size.1.max(1));
let image = use_image_protocol.then(|| {
image.resize_exact(side, side, image::imageops::FilterType::Lanczos3)
});
Some(PendingContentImage {
file_stem,
path,
icon_lines,
image,
})
})
.await
.ok()
.flatten();
if let Some(result) = result
&& let Ok(mut pending) = pending.lock()
{
pending.push(result);
crate::tui::request_redraw();
}
});
}
}
pub fn drain_image_loads(&mut self, picker: &ratatui_image::picker::Picker) {
let images = match self.pending_images.lock() {
Ok(mut pending) => std::mem::take(&mut *pending),
Err(_) => return,
};
for result in images {
if let Some(entry) = self
.entries
.iter_mut()
.find(|entry| {
entry.file_stem == result.file_stem && entry.path == result.path
})
{
entry.icon_lines = Some(result.icon_lines);
if let Some(image) = result.image {
self.image_protocols
.insert(result.file_stem, picker.new_resize_protocol(image));
}
}
}
}
// drain streaming entries from the initial load. each entry arrives
// individually and is inserted in sorted position for a smooth fill-in
pub fn drain_pending(&mut self) {
@@ -85,16 +215,19 @@ impl ContentListState {
};
let mut received = false;
let mut received_count = 0usize;
let mut finished = false;
loop {
match rx.try_recv() {
Ok(entry) => {
received = true;
self.images_dirty = true;
received_count += 1;
self.display_metadata
.insert(entry.file_stem.clone(), display_metadata(&entry));
let pos = self
.entries
.binary_search_by(|e| {
e.name.to_lowercase().cmp(&entry.name.to_lowercase())
})
.binary_search_by(|e| e.name.to_lowercase().cmp(&entry.name.to_lowercase()))
.unwrap_or_else(|i| i);
self.entries.insert(pos, entry);
}
@@ -109,6 +242,20 @@ impl ContentListState {
if received || finished {
self.loading = false;
if received_count > 0 {
tracing::trace!(
"Drained {} streamed content entries for {}",
received_count,
self.loaded_for.as_deref().unwrap_or("<unknown>")
);
}
if finished {
tracing::debug!(
"Finished content scan for {} with {} entries",
self.loaded_for.as_deref().unwrap_or("<unknown>"),
self.entries.len()
);
}
if self.list_state.selected.is_none() && !self.entries.is_empty() {
self.list_state.selected = Some(0);
}
@@ -131,8 +278,16 @@ impl ContentListState {
let Some(diff) = diff else {
return;
};
self.images_dirty = true;
// apply toggles (enabled/path changes)
tracing::debug!(
"Applying content watcher diff for {}: toggled={} removed={} added={}",
self.loaded_for.as_deref().unwrap_or("<unknown>"),
diff.toggled.len(),
diff.removed.len(),
diff.added.len()
);
for (stem, enabled, path) in &diff.toggled {
if let Some(entry) = self.entries.iter_mut().find(|e| &e.file_stem == stem) {
entry.enabled = *enabled;
@@ -144,10 +299,15 @@ impl ContentListState {
if !diff.removed.is_empty() {
self.entries
.retain(|e| !diff.removed.contains(&e.file_stem));
for stem in &diff.removed {
self.display_metadata.remove(stem);
}
}
// insert new entries in sorted position
for entry in diff.added {
self.display_metadata
.insert(entry.file_stem.clone(), display_metadata(&entry));
let pos = self
.entries
.binary_search_by(|e| e.name.to_lowercase().cmp(&entry.name.to_lowercase()))
@@ -160,8 +320,7 @@ impl ContentListState {
if self.entries.is_empty() {
self.list_state.selected = None;
} else {
self.list_state.selected =
Some(sel.min(self.entries.len().saturating_sub(1)));
self.list_state.selected = Some(sel.min(self.entries.len().saturating_sub(1)));
}
}
@@ -192,7 +351,12 @@ impl ContentListState {
let watch_dir = dir.clone();
let watcher = notify::recommended_watcher(move |res: Result<notify::Event, _>| {
if res.is_err() {
if let Err(e) = &res {
tracing::warn!(
"Content watcher event error for {}: {}",
watch_dir.display(),
e
);
return;
}
@@ -235,11 +399,7 @@ impl ContentListState {
for (stem, (old_path, old_enabled)) in known_map.iter() {
if let Some((disk_path, disk_enabled)) = on_disk.get(stem) {
if *disk_enabled != *old_enabled || *disk_path != *old_path {
toggled.push((
stem.clone(),
*disk_enabled,
disk_path.clone(),
));
toggled.push((stem.clone(), *disk_enabled, disk_path.clone()));
}
} else {
removed.push(stem.clone());
@@ -267,6 +427,7 @@ impl ContentListState {
&& let Ok(mut slot) = diff_slot.lock()
{
*slot = Some(diff);
crate::tui::request_redraw();
}
if !dirty.load(Ordering::Relaxed) {
@@ -281,6 +442,7 @@ impl ContentListState {
if let Err(e) = w.watch(&dir, RecursiveMode::NonRecursive) {
tracing::warn!("Failed to watch {}: {e}", dir.display());
} else {
tracing::debug!("Watching content directory {}", dir.display());
self._watcher = Some(w);
}
}
@@ -300,6 +462,16 @@ impl ContentListState {
.map(|(i, _)| i)
.collect()
}
pub fn pending_delete(&self) -> Option<PendingContentDelete> {
let filtered = self.filtered_indices();
let real_idx = self.list_state.selected.and_then(|i| filtered.get(i))?;
let entry = self.entries.get(*real_idx)?;
Some(PendingContentDelete {
name: entry.name.clone(),
path: entry.path.clone(),
})
}
}
impl ContentListState {
@@ -315,11 +487,19 @@ impl ContentListState {
) {
self.scan_one_fn = Some(scan_one_fn);
self.content_ext = Some(ext);
self.images_dirty = true;
self.image_protocols.clear();
self.requested_images.clear();
// save current entries to cache
if let Some(prev) = self.loaded_for.take()
&& !self.entries.is_empty()
{
tracing::trace!(
"Caching {} content entries for {}",
self.entries.len(),
prev
);
self.cache.insert(
prev,
CachedList {
@@ -332,16 +512,23 @@ impl ContentListState {
// try cache first
if let Some(cached) = self.cache.remove(instance_name) {
self.entries = cached.entries;
self.rebuild_display_metadata();
self.list_state.selected = cached.selected;
self.loading = false;
self.stream_rx = None;
self.loaded_for = Some(instance_name.to_string());
self.update_scrollbar();
tracing::debug!(
"Restored {} cached content entries for {}",
self.entries.len(),
instance_name
);
return;
}
// no cache, stream entries one by one as each file is scanned
self.entries.clear();
self.display_metadata.clear();
self.list_state = TuiListState::default();
self.loading = true;
self.loaded_for = Some(instance_name.to_string());
@@ -351,36 +538,53 @@ impl ContentListState {
self.stream_rx = Some(rx);
let dir = content_dir.to_path_buf();
tracing::debug!(
"Starting content scan for {} in {}",
instance_name,
content_dir.display()
);
tokio::spawn(async move {
let _ = tokio::task::spawn_blocking(move || {
let read_dir = match std::fs::read_dir(&dir) {
Ok(rd) => rd,
Err(_) => return,
Err(e) => {
tracing::warn!("Failed to read content directory {}: {}", dir.display(), e);
return;
}
};
let disabled_ext = format!("{ext}.disabled");
for dir_entry in read_dir.flatten() {
let path = dir_entry.path();
let Some(fname) = path.file_name().and_then(|n| n.to_str()) else {
tracing::trace!(
"Skipping content path with invalid filename: {}",
path.display()
);
continue;
};
let (enabled, file_stem) =
if let Some(stem) = fname.strip_suffix(&disabled_ext) {
(false, stem.to_owned())
} else if let Some(stem) = fname.strip_suffix(ext) {
(true, stem.to_owned())
} else if path.is_dir() {
crate::instance::content::parse_enabled_stem_dir(fname)
} else {
continue;
};
let (enabled, file_stem) = if let Some(stem) = fname.strip_suffix(&disabled_ext)
{
(false, stem.to_owned())
} else if let Some(stem) = fname.strip_suffix(ext) {
(true, stem.to_owned())
} else if path.is_dir() {
crate::instance::content::parse_enabled_stem_dir(fname)
} else {
tracing::trace!(
"Skipping content path with unsupported extension: {}",
path.display()
);
continue;
};
let entry = scan_one_fn(&path, &file_stem, enabled);
if tx.send(entry).is_err() {
break; // receiver dropped (instance switched)
}
crate::tui::request_redraw();
}
})
.await;
@@ -394,6 +598,14 @@ impl ContentListState {
self.scrollbar_state = ScrollbarState::new(max).position(pos);
}
fn rebuild_display_metadata(&mut self) {
self.display_metadata = self
.entries
.iter()
.map(|entry| (entry.file_stem.clone(), display_metadata(entry)))
.collect();
}
// enable/disable by renaming the file with/without .disabled extension.
// this is how most minecraft launchers handle it
pub fn toggle_selected(&mut self) {
@@ -429,10 +641,40 @@ impl ContentListState {
entry.path = new_path;
}
Err(e) => {
tracing::error!("Failed to toggle '{}': {}", entry.file_stem, e);
tracing::error!(
"Failed to toggle '{}' from {} to {}: {}",
entry.file_stem,
entry.path.display(),
new_path.display(),
e
);
}
}
}
pub fn remove_path(&mut self, path: &Path) {
let file_stem = self
.entries
.iter()
.find(|entry| entry.path == path)
.map(|entry| entry.file_stem.clone());
self.entries.retain(|entry| entry.path != path);
if let Some(file_stem) = file_stem {
self.image_protocols.remove(&file_stem);
self.requested_images.remove(&file_stem);
self.display_metadata.remove(&file_stem);
}
self.images_dirty = true;
if let Some(sel) = self.list_state.selected {
let visible_count = self.filtered_indices().len();
if visible_count == 0 {
self.list_state.selected = None;
} else {
self.list_state.selected = Some(sel.min(visible_count.saturating_sub(1)));
}
}
self.update_scrollbar();
}
}
fn handle_search_keys(key_event: &KeyEvent, state: &mut ContentListState) -> bool {
@@ -477,6 +719,7 @@ pub fn handle_key_no_toggle(key_event: &KeyEvent, state: &mut ContentListState)
}
let filtered = state.filtered_indices();
let count = filtered.len();
match key_event.code {
KeyCode::Char('j') | KeyCode::Down => {
if count == 0 {
@@ -512,6 +755,7 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut ContentListState) -> bool {
}
let filtered = state.filtered_indices();
let count = filtered.len();
match key_event.code {
KeyCode::Char('j') | KeyCode::Down => {
if count == 0 {
@@ -557,6 +801,7 @@ pub fn render(
is_focused: bool,
loading_text: &str,
empty_text: &str,
picker: &ratatui_image::picker::Picker,
) {
let theme = THEME.as_ref();
if state.loading {
@@ -587,24 +832,23 @@ pub fn render(
state.list_state.selected = Some(count.saturating_sub(1));
}
let snapshot: Vec<SnapshotRow> = filtered
.iter()
.map(|&i| {
let entry = &state.entries[i];
(
entry.name.clone(),
entry.description.clone(),
entry.enabled,
entry.icon_lines.clone(),
)
})
.collect();
let use_image_protocol =
picker.protocol_type() != ratatui_image::picker::ProtocolType::Halfblocks;
let entries = &state.entries;
let display_metadata = &state.display_metadata;
let filtered_rows = &filtered;
let builder = ListBuilder::new(move |context| {
let theme = THEME.as_ref();
let (name, description, enabled, icon_pixels) = &snapshot[context.index];
let entry = &entries[filtered_rows[context.index]];
let name = &entry.name;
let metadata = display_metadata.get(&entry.file_stem);
let enabled = entry.enabled;
let icon_pixels = &entry.icon_lines;
let has_image = entry.icon_bytes.is_some();
let protocol_columns = protocol_icon_columns(entry, picker) as usize;
let show_selected = is_focused && context.is_selected;
let use_mc_colors = *enabled;
let use_mc_colors = enabled;
let stripe_bg = if context.index % 2 == 0 {
theme.background()
@@ -612,7 +856,7 @@ pub fn render(
theme.stripe()
};
let (name_style, description_style, background) = match (*enabled, show_selected) {
let (name_style, description_style, background) = match (enabled, show_selected) {
(true, true) => (
Style::default()
.fg(theme.accent())
@@ -644,9 +888,8 @@ pub fn render(
};
let has_icon = icon_pixels.is_some();
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 stripped_desc = metadata.map_or("", |metadata| metadata.description.as_str());
let has_description = metadata.is_some_and(|metadata| metadata.has_description);
let compact = !has_icon && !has_description;
let selector = if show_selected {
@@ -678,7 +921,12 @@ pub fn render(
};
let mut line_0 = vec![selector.clone()];
line_0.extend(icon_spans(icon_pixels.as_ref(), 0));
line_0.extend(icon_spans(
icon_pixels.as_ref(),
0,
use_image_protocol && has_image,
protocol_columns,
));
line_0.push(Span::raw(" "));
if use_mc_colors {
line_0.extend(parse_mc_text(name, name_style));
@@ -690,16 +938,26 @@ pub fn render(
if has_description {
let mut row = vec![pad.clone()];
row.extend(icon_spans(icon_pixels.as_ref(), 1));
row.extend(icon_spans(
icon_pixels.as_ref(),
1,
use_image_protocol && has_image,
protocol_columns,
));
row.push(Span::raw(" "));
row.push(Span::styled(stripped_desc.clone(), description_style));
row.push(Span::styled(stripped_desc.to_string(), description_style));
lines.push(Line::from(row));
}
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));
row.extend(icon_spans(
icon_pixels.as_ref(),
r,
use_image_protocol && has_image,
protocol_columns,
));
lines.push(Line::from(row));
}
@@ -724,7 +982,7 @@ pub fn render(
};
lines.push(Line::from(vec![
pad,
Span::styled(stripped_desc.clone(), description_style),
Span::styled(stripped_desc.to_string(), description_style),
]));
}
@@ -737,6 +995,10 @@ pub fn render(
let list = ListView::new(builder, count);
frame.render_stateful_widget(list, area, &mut state.list_state);
if picker.protocol_type() != ratatui_image::picker::ProtocolType::Halfblocks {
render_image_icons(frame, area, state, &filtered, picker);
}
let scrollbar_area = Rect {
x: area.x + area.width.saturating_sub(0),
y: area.y + 1,
@@ -760,6 +1022,76 @@ pub fn render(
);
}
fn render_image_icons(
frame: &mut Frame,
area: Rect,
state: &mut ContentListState,
filtered: &[usize],
picker: &ratatui_image::picker::Picker,
) {
let truncation = state.list_state.scroll_truncation();
let mut y = area.y;
let first = state.list_state.scroll_offset_index();
for (visible_index, &entry_index) in filtered.iter().enumerate().skip(first) {
let Some(entry) = state.entries.get(entry_index) else {
continue;
};
let icon_rows = entry.icon_lines.as_ref().map_or(0, Vec::len);
let has_description = state
.display_metadata
.get(&entry.file_stem)
.is_some_and(|metadata| metadata.has_description);
let height = icon_rows.max(if has_description { 2 } else { 1 }) as u16;
if y >= area.y + area.height {
break;
}
let top_crop = if visible_index == first {
truncation.min(icon_rows as u16)
} else {
0
};
let visible_icon_rows = (icon_rows as u16)
.saturating_sub(top_crop)
.min(area.y + area.height - y);
if visible_icon_rows > 0
&& entry.icon_bytes.is_some()
&& let Some(protocol) = state.image_protocols.get_mut(&entry.file_stem)
{
let icon_area = Rect {
x: area.x + 1,
y,
width: protocol_icon_columns(entry, picker).min(area.width.saturating_sub(1)),
height: visible_icon_rows,
};
if icon_area.height > 0 && icon_area.width > 0 {
let clipped = top_crop > 0 || visible_icon_rows < icon_rows as u16;
let resize = if clipped {
Resize::Crop(Some(CropOptions {
clip_top: top_crop > 0,
clip_left: false,
}))
} else {
Resize::Scale(None)
};
let widget: StatefulImage<StatefulProtocol> =
StatefulImage::default().resize(resize);
frame.render_stateful_widget(widget, icon_area, protocol);
}
}
let visible_height = if visible_index == first {
height.saturating_sub(truncation)
} else {
height
};
y = y.saturating_add(visible_height);
if visible_index + 1 >= filtered.len() {
break;
}
}
}
// minecraft's 16-color palette, keyed by the formatting code character.
// these exact RGB values come from the minecraft wiki
fn mc_color(code: char) -> Option<Color> {
@@ -849,16 +1181,33 @@ fn strip_mc_codes(text: &str) -> String {
result
}
fn display_metadata(entry: &ContentEntry) -> DisplayMetadata {
let description = strip_mc_codes(&entry.description);
let description = description.lines().next().unwrap_or("").trim().to_string();
DisplayMetadata {
has_description: !description.is_empty(),
description,
}
}
// renders one row of a mod icon using half-block characters (U+2584).
// each cell packs two vertical pixels via fg/bg colors, giving
// double the vertical resolution out of the terminal
fn icon_spans(icon_pixels: Option<&Vec<Vec<IconCell>>>, row: usize) -> Vec<Span<'static>> {
fn icon_spans(
icon_pixels: Option<&Vec<Vec<IconCell>>>,
row: usize,
use_image_protocol: bool,
protocol_columns: usize,
) -> Vec<Span<'static>> {
if use_image_protocol {
return vec![Span::raw(" ".repeat(protocol_columns))];
}
match icon_pixels.and_then(|rows| rows.get(row)) {
Some(cols) => cols
.iter()
.map(|cell| {
Span::styled(
"\u{2584}",
cell.symbol.to_string(),
Style::default()
.fg(Color::Rgb(cell.fg_r, cell.fg_g, cell.fg_b))
.bg(Color::Rgb(cell.bg_r, cell.bg_g, cell.bg_b)),
@@ -875,14 +1224,25 @@ fn icon_spans(icon_pixels: Option<&Vec<Vec<IconCell>>>, row: usize) -> Vec<Span<
}
}
fn protocol_icon_columns(
entry: &crate::instance::content::mods::ContentEntry,
picker: &ratatui_image::picker::Picker,
) -> u16 {
let rows = entry.icon_lines.as_ref().map_or(3, Vec::len) as u16;
square_icon_columns(rows, picker.font_size())
}
fn square_icon_columns(rows: u16, font_size: (u16, u16)) -> u16 {
let width = u32::from(font_size.0.max(1));
let height = u32::from(font_size.1.max(1));
((u32::from(rows) * height + width / 2) / width).max(1) as u16
}
// reads a content directory and builds a stem -> (path, enabled) map.
// used both by watch_dir to initialize known state and by the watcher
// thread to detect changes. when ext is empty (worlds), only directories
// are included.
fn read_dir_stems(
dir: &std::path::Path,
ext: &str,
) -> HashMap<String, (std::path::PathBuf, bool)> {
fn read_dir_stems(dir: &std::path::Path, ext: &str) -> HashMap<String, (std::path::PathBuf, bool)> {
let mut map = HashMap::new();
let Ok(read_dir) = std::fs::read_dir(dir) else {
return map;
@@ -915,3 +1275,20 @@ fn read_dir_stems(
map
}
#[cfg(test)]
mod tests {
use super::square_icon_columns;
#[test]
fn square_columns_follow_terminal_cell_ratio() {
assert_eq!(square_icon_columns(3, (8, 16)), 6);
assert_eq!(square_icon_columns(3, (8, 18)), 7);
assert_eq!(square_icon_columns(6, (8, 18)), 14);
}
#[test]
fn square_columns_handle_missing_cell_size() {
assert_eq!(square_icon_columns(3, (0, 0)), 3);
}
}
+50 -8
View File
@@ -80,6 +80,7 @@ pub fn render(
screenshots_state: &mut crate::tui::widgets::screenshots_grid::ScreenshotsState,
logs_state: &mut crate::tui::widgets::logs_viewer::LogsState,
instances_dir: &std::path::Path,
picker: &ratatui_image::picker::Picker,
) {
let theme = THEME.as_ref();
let is_focused = focused == FocusedArea::Content;
@@ -148,12 +149,14 @@ pub fn render(
ContentTab::Mods | ContentTab::ResourcePacks | ContentTab::Shaders => &[
("j/k", " navigate"),
("⏎", " toggle"),
("d", " delete"),
("Shift+⏎", " open dir"),
("h/l", " tabs"),
("/", " search"),
],
ContentTab::Worlds => &[
("j/k", " navigate"),
("d", " delete"),
("Shift+⏎", " open dir"),
("h/l", " tabs"),
("/", " search"),
@@ -161,6 +164,7 @@ pub fn render(
ContentTab::Screenshots => &[
("Shift+HJKL", " grid"),
("⏎", " open"),
("d", " delete"),
("Shift+⏎", " open dir"),
("h/l", " tabs"),
("/", " search"),
@@ -170,6 +174,7 @@ pub fn render(
&[
("j/k", " scroll"),
("g/G", " top/bottom"),
("d", " delete"),
("Esc", " back"),
("/", " search"),
]
@@ -177,6 +182,7 @@ pub fn render(
&[
("j/k", " navigate"),
("⏎", " view"),
("d", " delete"),
("h/l", " tabs"),
("/", " search"),
]
@@ -215,8 +221,16 @@ pub fn render(
ContentTab::Mods => {
if let Some(instance) = instance {
if mods_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
let content_dir = instances_dir.join(&instance.name).join(".minecraft").join("mods");
mods_state.start_load(&content_dir, &instance.name, crate::instance::scan_one_mod, ".jar");
let content_dir = instances_dir
.join(&instance.name)
.join(".minecraft")
.join("mods");
mods_state.start_load(
&content_dir,
&instance.name,
crate::instance::scan_one_mod,
".jar",
);
mods_state.watch_dir(content_dir);
}
super::list::render(
@@ -226,6 +240,7 @@ pub fn render(
is_focused,
"Loading mods...",
"No mods installed.",
picker,
);
} else {
frame.render_widget(
@@ -238,8 +253,16 @@ pub fn render(
ContentTab::ResourcePacks => {
if let Some(instance) = instance {
if resource_packs_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
let content_dir = instances_dir.join(&instance.name).join(".minecraft").join("resourcepacks");
resource_packs_state.start_load(&content_dir, &instance.name, crate::instance::scan_one_resource_pack, ".zip");
let content_dir = instances_dir
.join(&instance.name)
.join(".minecraft")
.join("resourcepacks");
resource_packs_state.start_load(
&content_dir,
&instance.name,
crate::instance::scan_one_resource_pack,
".zip",
);
resource_packs_state.watch_dir(content_dir);
}
super::list::render(
@@ -249,6 +272,7 @@ pub fn render(
is_focused,
"Loading resource packs...",
"No resource packs installed.",
picker,
);
} else {
frame.render_widget(
@@ -261,8 +285,16 @@ pub fn render(
ContentTab::Shaders => {
if let Some(instance) = instance {
if shaders_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
let content_dir = instances_dir.join(&instance.name).join(".minecraft").join("shaderpacks");
shaders_state.start_load(&content_dir, &instance.name, crate::instance::scan_one_shader, ".zip");
let content_dir = instances_dir
.join(&instance.name)
.join(".minecraft")
.join("shaderpacks");
shaders_state.start_load(
&content_dir,
&instance.name,
crate::instance::scan_one_shader,
".zip",
);
shaders_state.watch_dir(content_dir);
}
super::list::render(
@@ -272,6 +304,7 @@ pub fn render(
is_focused,
"Loading shaders...",
"No shaders installed.",
picker,
);
} else {
frame.render_widget(
@@ -322,8 +355,16 @@ pub fn render(
ContentTab::Worlds => {
if let Some(instance) = instance {
if worlds_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
let content_dir = instances_dir.join(&instance.name).join(".minecraft").join("saves");
worlds_state.start_load(&content_dir, &instance.name, crate::instance::scan_one_world, "");
let content_dir = instances_dir
.join(&instance.name)
.join(".minecraft")
.join("saves");
worlds_state.start_load(
&content_dir,
&instance.name,
crate::instance::scan_one_world,
"",
);
worlds_state.watch_dir(content_dir);
}
super::list::render(
@@ -333,6 +374,7 @@ pub fn render(
is_focused,
"Loading worlds...",
"No worlds saved.",
picker,
);
} else {
frame.render_widget(
+1
View File
@@ -387,6 +387,7 @@ mod tests {
memory_min: None,
jvm_args: vec![],
resolution: None,
config_sync_profile: None,
}
}
+89 -18
View File
@@ -17,6 +17,7 @@ use ratatui::{
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
use crate::config::theme::{BORDER_STYLE, THEME};
use crate::instance::launch::parser::LogLevel;
use crate::instance::log_files::{LogFileEntry, read_log_file, scan_log_files};
type PendingLogs = Arc<Mutex<Option<(String, Vec<LogFileEntry>)>>>;
@@ -36,7 +37,7 @@ pub struct LogsState {
pub viewer_search: super::search::SearchState,
selected_path: Option<std::path::PathBuf>,
pending: PendingLogs,
rescan_counter: u8,
last_rescan: std::time::Instant,
instances_dir_cache: Option<std::path::PathBuf>,
was_live: bool,
}
@@ -58,7 +59,7 @@ impl Default for LogsState {
viewer_search: super::search::SearchState::default(),
selected_path: None,
pending: Arc::new(Mutex::new(None)),
rescan_counter: 0,
last_rescan: std::time::Instant::now(),
instances_dir_cache: None,
was_live: false,
}
@@ -76,6 +77,7 @@ impl LogsState {
self.viewer_scroll = 0;
self.viewer_focused = false;
self.selected_path = None;
self.last_rescan = std::time::Instant::now();
let dir = instances_dir.to_path_buf();
let tag = instance_name.to_string();
@@ -91,17 +93,13 @@ impl LogsState {
if let Ok(mut slot) = pending.lock() {
*slot = Some((tag, entries));
crate::tui::request_redraw();
}
});
}
pub fn drain_pending(&mut self) {
// when the instance stops while viewing the live log, transition
// to the on-disk log file so the viewer doesn't go blank
let live_now = self.has_live();
if self.was_live && !live_now && self.list_state.selected == Some(0) {
self.load_selected_content();
}
self.was_live = live_now;
let taken = match self.pending.lock() {
@@ -132,16 +130,25 @@ impl LogsState {
}
// periodically re-scan log files in case new ones appeared while playing.
// only triggers every 120 ticks to avoid hammering the filesystem
pub fn try_rescan(&mut self) {
self.rescan_counter = self.rescan_counter.wrapping_add(1);
if !self.rescan_counter.is_multiple_of(120) {
if self.last_rescan.elapsed() < std::time::Duration::from_secs(2) {
return;
}
self.last_rescan = std::time::Instant::now();
let (Some(dir), Some(name)) = (&self.instances_dir_cache, &self.loaded_for) else {
return;
};
if !matches!(
crate::running::get(name),
Some(
crate::running::RunState::Authenticating
| crate::running::RunState::Starting
| crate::running::RunState::Running
)
) {
return;
}
let dir = dir.clone();
let tag = name.clone();
@@ -157,16 +164,20 @@ impl LogsState {
if let Ok(mut slot) = pending.lock() {
*slot = Some((tag, entries));
crate::tui::request_redraw();
}
});
}
// when an instance is running, a synthetic "Live" entry is injected at index 0
// when an instance is active or has just crashed, a synthetic "Live" entry
// is injected at index 0 so parsed live log styling is retained.
fn has_live(&self) -> bool {
let name = self.loaded_for.as_deref().unwrap_or("");
matches!(
crate::running::get(name),
Some(crate::running::RunState::Running) | Some(crate::running::RunState::Starting)
Some(crate::running::RunState::Running)
| Some(crate::running::RunState::Starting)
| Some(crate::running::RunState::Crashed(_))
)
}
@@ -229,6 +240,33 @@ impl LogsState {
self.viewer_scrollbar_state =
ScrollbarState::new(self.viewer_max_scroll).position(self.viewer_scroll);
}
pub fn pending_delete(
&self,
) -> Option<crate::tui::widgets::content::list::PendingContentDelete> {
let index = self.file_index_for_selected()?;
let entry = self.entries.get(index)?;
Some(crate::tui::widgets::content::list::PendingContentDelete {
name: entry.name.clone(),
path: entry.path.clone(),
})
}
pub fn remove_path(&mut self, path: &Path) {
self.entries.retain(|entry| entry.path != path);
let display_count = self.display_count();
if display_count == 0 {
self.list_state.selected = None;
self.viewer_focused = false;
self.selected_path = None;
self.viewer_lines.clear();
self.viewer_scroll = 0;
} else if let Some(sel) = self.list_state.selected {
self.list_state.selected = Some(sel.min(display_count.saturating_sub(1)));
self.load_selected_content();
}
self.update_scrollbar();
}
}
pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool {
@@ -515,16 +553,27 @@ fn render_viewer(
let theme = THEME.as_ref();
let is_live = has_live && state.list_state.selected == Some(0);
let all_lines: Vec<String> = if is_live {
let all_lines: Vec<ViewerLine> = if is_live {
let name = state.loaded_for.as_deref().unwrap_or("");
crate::instance_logs::get_all(name)
crate::instance_logs::get_entries(name)
.into_iter()
.map(|line| ViewerLine {
text: line.text,
level: Some(line.level),
})
.collect()
} else {
state.viewer_lines.clone()
state
.viewer_lines
.iter()
.cloned()
.map(|text| ViewerLine { text, level: None })
.collect()
};
let lines: Vec<&String> = all_lines
let lines: Vec<&ViewerLine> = all_lines
.iter()
.filter(|l| state.viewer_search.matches(l))
.filter(|l| state.viewer_search.matches(&l.text))
.collect();
let visible_height = area.height as usize;
@@ -548,7 +597,14 @@ fn render_viewer(
.iter()
.skip(state.viewer_scroll)
.take(visible_height)
.map(|line| search.highlight_line(line, line_level_style(line)))
.map(|line| {
search.highlight_line(
&line.text,
line.level
.map(log_level_style)
.unwrap_or_else(|| line_level_style(&line.text)),
)
})
.collect();
frame.render_widget(Paragraph::new(styled_lines), area);
@@ -576,6 +632,21 @@ fn render_viewer(
);
}
struct ViewerLine {
text: String,
level: Option<LogLevel>,
}
fn log_level_style(level: LogLevel) -> Style {
let theme = THEME.as_ref();
match level {
LogLevel::Error => Style::default().fg(theme.error()),
LogLevel::Warn => Style::default().fg(theme.warning()),
LogLevel::Debug | LogLevel::Trace => Style::default().fg(theme.text_dim()),
LogLevel::Info => Style::default().fg(theme.text()),
}
}
// color-code log lines by severity so errors actually stand out
// instead of drowning in a wall of white text
fn line_level_style(line: &str) -> Style {
+1 -1
View File
@@ -9,12 +9,12 @@ use ratatui::{
pub mod account;
pub mod content;
pub mod settings;
pub mod instances;
pub mod logs_viewer;
pub mod popups;
pub mod screenshots_grid;
pub mod search;
pub mod settings;
pub mod status;
// highlight the first character of a title with the accent color,
+82 -18
View File
@@ -1,4 +1,4 @@
// "are you sure?" popup for instance deletion. uses global state so the
// "are you sure?" popup for destructive actions. uses global state so the
// confirmation target persists across render frames.
use std::sync::LazyLock;
@@ -19,13 +19,57 @@ static CONFIRM_STATE: LazyLock<Mutex<ConfirmState>> =
#[derive(Debug, Default)]
struct ConfirmState {
instance_name: String,
target: Option<ConfirmTarget>,
}
pub fn set_pending_delete(name: impl Into<String>) {
#[derive(Debug, Clone)]
pub enum ConfirmTarget {
Instance {
name: String,
},
Account {
username: String,
index: usize,
},
ConfigProfile {
profile: String,
},
Content {
name: String,
path: std::path::PathBuf,
},
}
impl ConfirmTarget {
fn title(&self) -> String {
format!(" Delete '{}' ", self.name())
}
fn body(&self) -> &'static str {
match self {
ConfirmTarget::Instance { .. } => "This will permanently remove the instance",
ConfirmTarget::Account { .. } => "This will permanently remove this account",
ConfirmTarget::ConfigProfile { .. } => {
"This will permanently remove this config profile"
}
ConfirmTarget::Content { .. } => "This will permanently remove the selected item",
}
}
pub fn name(&self) -> &str {
match self {
ConfirmTarget::Instance { name } => name,
ConfirmTarget::Account { username, .. } => username,
ConfirmTarget::ConfigProfile { profile } => profile,
ConfirmTarget::Content { name, .. } => name,
}
}
}
pub fn set_pending(target: ConfirmTarget) {
match CONFIRM_STATE.lock() {
Ok(mut s) => {
s.instance_name = name.into();
s.target = Some(target);
}
Err(e) => {
tracing::error!("Confirm popup state lock poisoned: {}", e);
@@ -33,17 +77,32 @@ pub fn set_pending_delete(name: impl Into<String>) {
}
}
pub fn pending_delete_name() -> String {
pub fn set_pending_delete(name: impl Into<String>) {
set_pending(ConfirmTarget::Instance { name: name.into() });
}
pub fn set_pending_instance_delete(name: impl Into<String>) {
set_pending_delete(name);
}
pub fn set_pending_content_delete(name: impl Into<String>, path: impl Into<std::path::PathBuf>) {
set_pending(ConfirmTarget::Content {
name: name.into(),
path: path.into(),
});
}
pub fn pending_target() -> Option<ConfirmTarget> {
match CONFIRM_STATE.lock() {
Ok(s) => s.instance_name.clone(),
Err(_) => String::new(),
Ok(s) => s.target.clone(),
Err(_) => None,
}
}
pub fn clear_pending() {
match CONFIRM_STATE.lock() {
Ok(mut s) => {
s.instance_name.clear();
s.target = None;
}
Err(e) => {
tracing::error!("Confirm popup state lock poisoned: {}", e);
@@ -52,15 +111,21 @@ pub fn clear_pending() {
}
pub struct ConfirmPopup {
instance_name: String,
title: String,
body: &'static str,
}
impl ConfirmPopup {
pub fn new(instance_name: impl Into<String>) -> Self {
pub fn new(title: impl Into<String>, body: &'static str) -> Self {
Self {
instance_name: instance_name.into(),
title: title.into(),
body,
}
}
pub fn for_target(target: &ConfirmTarget) -> Self {
Self::new(target.title(), target.body())
}
}
impl Widget for ConfirmPopup {
@@ -69,7 +134,7 @@ impl Widget for ConfirmPopup {
let theme = THEME.as_ref();
let title = Line::from(vec![Span::styled(
format!(" Delete '{}' ", self.instance_name),
self.title,
Style::default()
.fg(theme.text_dim())
.add_modifier(Modifier::BOLD),
@@ -86,7 +151,7 @@ impl Widget for ConfirmPopup {
keybinds: Some(kb),
search_line: None,
content: Box::new(move |inner, buf| {
Paragraph::new("This will permanently remove the instance")
Paragraph::new(self.body)
.style(Style::default().fg(text_color))
.render(inner, buf);
}),
@@ -96,15 +161,14 @@ impl Widget for ConfirmPopup {
}
}
pub fn confirm_popup_area(frame_area: Rect, name: &str) -> Rect {
pub fn confirm_popup_area(frame_area: Rect, target: &ConfirmTarget) -> Rect {
use super::word_wrap_size;
use ratatui::layout::Constraint;
const MAX_W: usize = 48;
const BODY: &str = "This will permanently remove the instance";
let title_w = name.len() + 12;
let (body_w, _) = word_wrap_size(BODY, MAX_W);
let title_w = target.name().len() + 12;
let (body_w, _) = word_wrap_size(target.body(), MAX_W);
let inner_w = title_w.max(body_w).min(MAX_W);
let (_, lines) = word_wrap_size(BODY, inner_w);
let (_, lines) = word_wrap_size(target.body(), inner_w);
let popup_w = ((inner_w + 2) as u16).min(frame_area.width.saturating_sub(4));
let popup_h = ((lines + 2) as u16).min(frame_area.height.saturating_sub(4));
frame_area.centered(Constraint::Length(popup_w), Constraint::Length(popup_h))
@@ -426,11 +426,8 @@ mod tests {
id: "1.20.1".into(),
stable: true,
}]);
guard.loader_versions = LoadState::Loaded(vec![
"47.2.0".into(),
"47.1.0".into(),
"47.0.50".into(),
]);
guard.loader_versions =
LoadState::Loaded(vec!["47.2.0".into(), "47.1.0".into(), "47.0.50".into()]);
}
let backend = TestBackend::new(60, 14);
+26
View File
@@ -92,6 +92,7 @@ impl ScreenshotsState {
if let Ok(mut slot) = pending.lock() {
*slot = Some((tag, entries));
crate::tui::request_redraw();
}
});
}
@@ -148,6 +149,7 @@ impl ScreenshotsState {
&& let Ok(mut slot) = pending.lock()
{
slot.push((idx, img));
crate::tui::request_redraw();
}
});
}
@@ -173,6 +175,30 @@ impl ScreenshotsState {
}
self.entries.len().div_ceil(self.cols)
}
pub fn pending_delete(
&self,
) -> Option<crate::tui::widgets::content::list::PendingContentDelete> {
let entry = self.entries.get(self.selected)?;
Some(crate::tui::widgets::content::list::PendingContentDelete {
name: entry.name.clone(),
path: entry.path.clone(),
})
}
pub fn remove_path(&mut self, path: &Path) {
self.entries.retain(|entry| entry.path != path);
self.protocols.clear();
self.requested.clear();
if self.entries.is_empty() {
self.selected = 0;
self.scroll_row = 0;
} else {
self.selected = self.selected.min(self.entries.len().saturating_sub(1));
self.ensure_visible();
}
}
}
pub fn handle_key(key_event: &KeyEvent, state: &mut ScreenshotsState) -> bool {
+476 -59
View File
@@ -1,27 +1,193 @@
// settings panel: shows instance config (memory, java, jvm args, resolution)
// and provides keybinds to open config files in $EDITOR
// settings panel: manages config profiles and shows compact instance info.
// also provides keybinds to open config files in $EDITOR.
use ratatui::{
Frame,
layout::Rect,
style::{Modifier, Style},
text::{Line, Span},
widgets::{Block, Borders, Paragraph},
use std::{
path::{Path, PathBuf},
process::Command,
};
use crate::config::{SETTINGS, theme::{BORDER_STYLE, THEME}};
use crossterm::event::{KeyCode, KeyEvent};
use ratatui::{
Frame,
layout::{Constraint, Direction, Layout, Rect},
style::{Modifier, Style},
text::{Line, Span},
widgets::{Block, Borders, Paragraph, Widget},
};
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
use crate::config::{
SETTINGS,
theme::{BORDER_STYLE, THEME},
};
use crate::instance::models::InstanceConfig;
use crate::tui::app::FocusedArea;
use super::styled_title;
const LOCAL_PROFILE_LABEL: &str = "instance default";
#[derive(Default)]
pub enum AddMode {
#[default]
None,
ProfileName(String),
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SettingsPane {
#[default]
Profile,
Info,
}
pub struct SettingsState {
pub list_state: TuiListState,
pub profiles: Vec<String>,
pub add_mode: AddMode,
pub pane: SettingsPane,
meta_dir: PathBuf,
active_profile: Option<String>,
instance_name: Option<String>,
java_key: Option<String>,
java_source: Option<String>,
java_label: String,
}
impl SettingsState {
pub fn new(meta_dir: PathBuf) -> Self {
let profiles = crate::instance::config_sync::list_profiles(&meta_dir).unwrap_or_else(|e| {
tracing::warn!("Failed to load config sync profiles: {}", e);
Vec::new()
});
let mut state = Self {
list_state: TuiListState::default(),
profiles,
add_mode: AddMode::None,
pane: SettingsPane::Profile,
meta_dir,
active_profile: None,
instance_name: None,
java_key: None,
java_source: None,
java_label: "unknown".to_string(),
};
state.select_active();
state
}
fn reload_profiles(&mut self) {
match crate::instance::config_sync::list_profiles(&self.meta_dir) {
Ok(mut profiles) => {
add_active_profile(&mut profiles, self.active_profile.as_deref());
self.profiles = profiles;
}
Err(e) => tracing::warn!("Failed to reload config sync profiles: {}", e),
}
}
fn select_active(&mut self) {
self.list_state.selected = Some(
self.active_profile
.as_deref()
.and_then(|active| self.profiles.iter().position(|profile| profile == active))
.map(|idx| idx + 1)
.unwrap_or(0),
);
}
fn count(&self) -> usize {
self.profiles.len() + 1
}
fn update_for_instance(&mut self, instance: Option<&InstanceConfig>) {
let instance_name = instance.map(|inst| inst.name.clone());
let active_profile = instance.and_then(|inst| inst.config_sync_profile.clone());
let active_profile = active_profile
.filter(|profile| self.profiles.iter().any(|candidate| candidate == profile));
if self.instance_name != instance_name || self.active_profile != active_profile {
self.instance_name = instance_name;
self.active_profile = active_profile;
add_active_profile(&mut self.profiles, self.active_profile.as_deref());
self.select_active();
}
let java_key = instance.map(java_path_key);
if self.java_key != java_key {
let java_source = instance.map(effective_java_path);
self.java_label = java_source
.as_deref()
.map(java_version_label)
.unwrap_or_else(|| "unknown".to_string());
self.java_key = java_key;
self.java_source = java_source;
}
}
}
fn add_active_profile(profiles: &mut Vec<String>, active_profile: Option<&str>) {
if let Some(active) = active_profile
&& !profiles.iter().any(|profile| profile == active)
{
profiles.push(active.to_string());
profiles.sort_unstable();
}
}
fn java_path_key(instance: &InstanceConfig) -> String {
instance
.java_path
.as_deref()
.filter(|path| !path.is_empty())
.or_else(|| SETTINGS.paths.effective_java_path())
.unwrap_or("<auto>")
.to_string()
}
fn effective_java_path(instance: &InstanceConfig) -> String {
instance
.java_path
.clone()
.or_else(|| SETTINGS.paths.effective_java_path().map(str::to_string))
.unwrap_or_else(crate::net::detect_java_path)
}
fn java_version_label(java_path: &str) -> String {
let output = Command::new(java_path).arg("-version").output();
let Ok(output) = output else {
return "unknown".to_string();
};
let raw = String::from_utf8_lossy(if output.stderr.is_empty() {
&output.stdout
} else {
&output.stderr
});
let first_line = raw.lines().next().unwrap_or_default();
let Some(version) = first_line.split('"').nth(1) else {
return "unknown".to_string();
};
let major = if let Some(stripped) = version.strip_prefix("1.") {
stripped.split('.').next().unwrap_or(stripped)
} else {
version.split('.').next().unwrap_or(version)
};
if major.is_empty() {
"unknown".to_string()
} else {
format!("jdk{major}")
}
}
pub fn render(
frame: &mut Frame,
area: Rect,
focused: FocusedArea,
state: &mut SettingsState,
instance: Option<&InstanceConfig>,
_instances_dir: &std::path::Path,
_instances_dir: &Path,
) {
state.update_for_instance(instance);
let theme = THEME.as_ref();
let color = if focused == FocusedArea::Settings {
theme.accent()
@@ -36,14 +202,22 @@ pub fn render(
.border_style(Style::default().fg(color));
if focused == FocusedArea::Settings {
let lines = super::popups::keybind_lines_wrapped(
&[
("e", " edit instance"),
("g", " edit global"),
("d", " desktop"),
let keybinds: &[(&str, &str)] = match state.pane {
SettingsPane::Profile => &[
("⏎", " select"),
("a", " add"),
("d", " del"),
("j/k", " move"),
("h/l", " tab"),
],
area.width.saturating_sub(2),
);
SettingsPane::Info => &[
("e", " inst"),
("g", " global"),
("d", " desk"),
("h/l", " tab"),
],
};
let lines = super::popups::keybind_lines_wrapped(keybinds, area.width.saturating_sub(2));
for line in lines {
block = block.title_bottom(line);
}
@@ -52,74 +226,317 @@ pub fn render(
let inner = block.inner(area);
frame.render_widget(block, area);
let Some(inst) = instance else {
frame.render_widget(
Paragraph::new("No instance selected.").style(Style::default().fg(theme.text_dim())),
inner,
);
return;
};
if inner.width >= 42 {
let chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage(50),
Constraint::Length(3),
Constraint::Percentage(50),
])
.split(inner);
render_profile_list(frame, chunks[0], focused, state);
render_separator(frame, chunks[1], focused, state.pane);
render_instance_info(frame, chunks[2], focused, state, instance);
} else {
render_profile_list(frame, inner, focused, state);
}
if let AddMode::ProfileName(name) = &state.add_mode {
render_add_profile_popup(frame, name);
}
}
fn render_separator(frame: &mut Frame, area: Rect, focused: FocusedArea, pane: SettingsPane) {
let theme = THEME.as_ref();
let color = if focused == FocusedArea::Settings && pane == SettingsPane::Info {
theme.accent()
} else {
theme.border()
};
let line = if area.width >= 3 {
" │ \n".repeat(area.height as usize)
} else {
"│\n".repeat(area.height as usize)
};
frame.render_widget(Paragraph::new(line).style(Style::default().fg(color)), area);
}
fn render_instance_info(
frame: &mut Frame,
area: Rect,
focused: FocusedArea,
state: &SettingsState,
instance: Option<&InstanceConfig>,
) {
let theme = THEME.as_ref();
let label_style = Style::default().fg(theme.text_dim());
let value_style = Style::default()
.fg(theme.text())
.add_modifier(Modifier::BOLD);
let dim_style = Style::default().fg(theme.text_dim());
let memory_min = inst.memory_min.as_deref().unwrap_or(&SETTINGS.defaults.memory_min);
let memory_max = inst.memory_max.as_deref().unwrap_or(&SETTINGS.defaults.memory_max);
let java_path = inst
.java_path
.as_deref()
.or_else(|| SETTINGS.paths.effective_java_path())
.unwrap_or("system");
let jvm_args = if inst.jvm_args.is_empty() {
"none".to_string()
} else {
inst.jvm_args.join(" ")
let Some(inst) = instance else {
frame.render_widget(
Paragraph::new("No instance selected.").style(Style::default().fg(theme.text_dim())),
area,
);
return;
};
let resolution = inst
.resolution
.map(|(w, h)| format!("{}x{}", w, h))
.unwrap_or_else(|| "default".to_string());
let memory_min = inst
.memory_min
.as_deref()
.unwrap_or(&SETTINGS.defaults.memory_min);
let memory_max = inst
.memory_max
.as_deref()
.unwrap_or(&SETTINGS.defaults.memory_max);
let active_style = if focused == FocusedArea::Settings && state.pane == SettingsPane::Info {
value_style.fg(theme.accent())
} else {
value_style
};
let desktop = if crate::instance::desktop::exists(&inst.name) {
"yes"
} else {
"no"
};
let lines = vec![
Line::from(vec![
Span::styled("Memory ", label_style),
Span::styled(format!("{memory_min} - {memory_max}"), value_style),
Span::styled("Memory ", label_style),
Span::styled(format!("{memory_min} - {memory_max}"), active_style),
]),
Line::from(vec![
Span::styled("Java ", label_style),
Span::styled(java_path, value_style),
Span::styled("Java ", label_style),
Span::styled(state.java_label.as_str(), active_style),
]),
Line::from(vec![
Span::styled("JVM ", label_style),
Span::styled(jvm_args, dim_style),
]),
Line::from(vec![
Span::styled("Display ", label_style),
Span::styled(resolution, value_style),
Span::styled("Desktop ", label_style),
Span::styled(desktop, active_style),
]),
];
frame.render_widget(Paragraph::new(lines), inner);
frame.render_widget(Paragraph::new(lines), area);
}
fn render_profile_list(
frame: &mut Frame,
area: Rect,
focused: FocusedArea,
state: &mut SettingsState,
) {
let is_focused = focused == FocusedArea::Settings;
let pane = state.pane;
let active_profile = state.active_profile.clone();
let profiles = state.profiles.clone();
let count = profiles.len() + 1;
let builder = ListBuilder::new(move |context| {
let theme = THEME.as_ref();
let name = if context.index == 0 {
LOCAL_PROFILE_LABEL.to_string()
} else {
profiles[context.index - 1].clone()
};
let is_active = if context.index == 0 {
active_profile.is_none()
} else {
active_profile.as_deref() == Some(name.as_str())
};
let show_selected = is_focused && pane == SettingsPane::Profile && context.is_selected;
let marker = if is_active { "\u{25b8} " } else { " " };
let background = if show_selected {
theme.stripe()
} else {
theme.background()
};
let style = if show_selected {
Style::default()
.fg(theme.accent())
.add_modifier(Modifier::BOLD)
} else if is_active {
Style::default()
.fg(theme.text())
.add_modifier(Modifier::BOLD)
} else {
Style::default().fg(theme.text())
};
let line = Line::from(vec![
Span::styled(marker, Style::default().fg(theme.success())),
Span::styled(name, style),
]);
(
ratatui::text::Text::from(line).style(Style::default().bg(background)),
1,
)
});
frame.render_stateful_widget(ListView::new(builder, count), area, &mut state.list_state);
}
fn render_add_profile_popup(frame: &mut Frame, name: &str) {
use super::popups::{base::PopupFrame, keybind_line};
let theme = THEME.as_ref();
let area = popup_area(frame, 42, 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(
" Config Profile ",
Style::default()
.fg(border_color)
.add_modifier(Modifier::BOLD),
))
.centered(),
border_color,
bg: Some(bg_color),
keybinds: Some(keybind_line(&[("Enter", " create"), ("Esc", " cancel")])),
search_line: None,
content: Box::new(move |inner, buf| {
let line = if name.is_empty() {
Line::from(vec![
Span::styled("Profile name...", Style::default().fg(dim_color)),
Span::styled(
"\u{2588}",
Style::default()
.fg(border_color)
.add_modifier(Modifier::SLOW_BLINK),
),
])
} else {
Line::from(vec![
Span::styled(name.as_str(), Style::default().fg(text_color)),
Span::styled(
"\u{2588}",
Style::default()
.fg(border_color)
.add_modifier(Modifier::SLOW_BLINK),
),
])
};
Paragraph::new(line).render(inner, buf);
}),
}
.render(area, frame.buffer_mut());
}
fn popup_area(frame: &Frame, width: u16, height: u16) -> Rect {
let area = frame.area();
let x = area.x + (area.width.saturating_sub(width)) / 2;
let y = area.y + (area.height.saturating_sub(height)) / 2;
Rect {
x,
y,
width: width.min(area.width),
height: height.min(area.height),
}
}
pub enum SettingsAction {
None,
EditInstance(std::path::PathBuf),
EditGlobal(std::path::PathBuf),
EditInstance(PathBuf),
EditGlobal(PathBuf),
ToggleDesktop,
SelectProfile(Option<String>),
ConfirmDeleteProfile(String),
Error(String),
}
pub fn handle_key(
key_event: &crossterm::event::KeyEvent,
key_event: &KeyEvent,
state: &mut SettingsState,
instance: Option<&InstanceConfig>,
instances_dir: &std::path::Path,
instances_dir: &Path,
) -> SettingsAction {
if let AddMode::ProfileName(name) = &state.add_mode {
match key_event.code {
KeyCode::Enter => {
let name = name.trim().to_string();
state.add_mode = AddMode::None;
if name.is_empty() {
return SettingsAction::None;
}
return match crate::instance::config_sync::create_profile(&state.meta_dir, &name) {
Ok(profile) => {
state.reload_profiles();
state.active_profile = Some(profile);
state.select_active();
SettingsAction::SelectProfile(state.active_profile.clone())
}
Err(e) => SettingsAction::Error(e.to_string()),
};
}
KeyCode::Esc => {
state.add_mode = AddMode::None;
return SettingsAction::None;
}
KeyCode::Backspace => {
let mut new_name = name.clone();
new_name.pop();
state.add_mode = AddMode::ProfileName(new_name);
return SettingsAction::None;
}
KeyCode::Char(c) => {
let mut new_name = name.clone();
new_name.push(c);
state.add_mode = AddMode::ProfileName(new_name);
return SettingsAction::None;
}
_ => return SettingsAction::None,
}
}
match key_event.code {
crossterm::event::KeyCode::Char('e') => {
KeyCode::Char('h') | KeyCode::Left => {
state.pane = SettingsPane::Profile;
SettingsAction::None
}
KeyCode::Char('l') | KeyCode::Right => {
state.pane = SettingsPane::Info;
SettingsAction::None
}
KeyCode::Enter if state.pane == SettingsPane::Profile => {
let selected = state.list_state.selected.unwrap_or(0);
let profile = if selected == 0 {
None
} else {
state.profiles.get(selected - 1).cloned()
};
SettingsAction::SelectProfile(profile)
}
KeyCode::Char('a') if state.pane == SettingsPane::Profile => {
state.add_mode = AddMode::ProfileName(String::new());
SettingsAction::None
}
KeyCode::Char('d') if state.pane == SettingsPane::Profile => {
let selected = state.list_state.selected.unwrap_or(0);
if selected == 0 {
SettingsAction::None
} else if let Some(profile) = state.profiles.get(selected - 1) {
SettingsAction::ConfirmDeleteProfile(profile.clone())
} else {
SettingsAction::None
}
}
KeyCode::Char('j') | KeyCode::Down if state.pane == SettingsPane::Profile => {
let count = state.count();
if count > 0 {
let cur = state.list_state.selected.unwrap_or(0);
state.list_state.selected = Some((cur + 1).min(count - 1));
}
SettingsAction::None
}
KeyCode::Char('k') | KeyCode::Up if state.pane == SettingsPane::Profile => {
let cur = state.list_state.selected.unwrap_or(0);
state.list_state.selected = Some(cur.saturating_sub(1));
SettingsAction::None
}
KeyCode::Char('e') if state.pane == SettingsPane::Info => {
if let Some(inst) = instance {
let path = instances_dir.join(&inst.name).join("instance.json");
SettingsAction::EditInstance(path)
@@ -127,11 +544,11 @@ pub fn handle_key(
SettingsAction::None
}
}
crossterm::event::KeyCode::Char('g') => {
KeyCode::Char('g') if state.pane == SettingsPane::Info => {
let path = crate::config::get_config_path().join("config.toml");
SettingsAction::EditGlobal(path)
}
crossterm::event::KeyCode::Char('d') => SettingsAction::ToggleDesktop,
KeyCode::Char('d') if state.pane == SettingsPane::Info => SettingsAction::ToggleDesktop,
_ => SettingsAction::None,
}
}
+71 -16
View File
@@ -52,9 +52,26 @@ fn make_config_with(
memory_min: None,
jvm_args: Vec::new(),
resolution: None,
config_sync_profile: None,
}
}
#[cfg(unix)]
fn fake_java(tmp: &TempDir, major: u32) -> String {
use std::os::unix::fs::PermissionsExt;
let path = tmp.path().join(format!("java-{major}"));
std::fs::write(
&path,
format!("#!/bin/sh\necho 'openjdk version \"{major}.0.1\"' >&2\n"),
)
.unwrap();
let mut permissions = std::fs::metadata(&path).unwrap().permissions();
permissions.set_mode(0o755);
std::fs::set_permissions(&path, permissions).unwrap();
path.to_string_lossy().into_owned()
}
// builds the on-disk layout that build_launch_invocation expects:
// <tmp>/instances/<name>/.minecraft/ (instance dir, created empty)
// <tmp>/meta/versions/<game_version>/meta.json
@@ -148,6 +165,16 @@ fn modern_vanilla_meta(id: &str) -> serde_json::Value {
})
}
#[cfg(unix)]
fn modern_vanilla_meta_with_java(id: &str, java_major: u32) -> serde_json::Value {
let mut meta = modern_vanilla_meta(id);
meta["javaVersion"] = json!({
"component": format!("java-runtime-{java_major}"),
"majorVersion": java_major
});
meta
}
fn legacy_vanilla_meta(id: &str) -> serde_json::Value {
json!({
"id": id,
@@ -182,14 +209,11 @@ async fn vanilla_modern_builds_complete_invocation() {
assert_eq!(inv.main_class, "net.minecraft.client.main.Main");
assert!(inv.extra_args.is_empty());
let expected_natives = fx
.meta_dir
.join("versions")
.join("1.20.1")
.join("natives");
let expected_natives = fx.meta_dir.join("versions").join("1.20.1").join("natives");
assert!(
inv.jvm_args.iter().any(|a| a
== &format!("-Djava.library.path={}", expected_natives.display())),
inv.jvm_args
.iter()
.any(|a| a == &format!("-Djava.library.path={}", expected_natives.display())),
"jvm_args missing natives substitution: {:?}",
inv.jvm_args
);
@@ -215,6 +239,34 @@ async fn vanilla_modern_builds_complete_invocation() {
assert!(inv.classpath.contains(&client_jar));
}
#[cfg(unix)]
#[tokio::test]
async fn launch_fails_when_selected_java_is_older_than_profile_requires() {
let fx = Fixture::new(
"java-old",
"26.1.2",
modern_vanilla_meta_with_java("26.1.2", 25),
);
let mut config = make_config("java-old", "26.1.2", ModLoader::Vanilla);
config.java_path = Some(fake_java(&fx._tmp, 21));
let err = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth())
.await
.expect_err("java 21 should fail for a Java 25 profile");
assert!(
matches!(
err,
LaunchError::JavaTooOld {
required: 25,
detected: 21,
..
}
),
"expected JavaTooOld, got {err:?}"
);
}
#[tokio::test]
async fn vanilla_legacy_args_format_substitutes_tokens() {
let fx = Fixture::new("vlegacy", "1.7.10", legacy_vanilla_meta("1.7.10"));
@@ -270,7 +322,10 @@ async fn forge_modern_includes_add_opens() {
.await
.unwrap();
assert_eq!(inv.main_class, "cpw.mods.bootstraplauncher.BootstrapLauncher");
assert_eq!(
inv.main_class,
"cpw.mods.bootstraplauncher.BootstrapLauncher"
);
assert!(
inv.jvm_args.iter().any(|a| a == "--add-opens"),
"Forge --add-opens missing: {:?}",
@@ -311,9 +366,9 @@ async fn forge_local_lib_dir_preferred_over_meta_dir() {
// drop fmlloader into the instance-local libraries dir so the launcher
// finds it there rather than under the shared meta cache.
let local_lib =
fx.instance_libraries_dir("f2")
.join("net/minecraftforge/fmlloader/1.20.1-47.2.0");
let local_lib = fx
.instance_libraries_dir("f2")
.join("net/minecraftforge/fmlloader/1.20.1-47.2.0");
std::fs::create_dir_all(&local_lib).unwrap();
let local_jar = local_lib.join("fmlloader-1.20.1-47.2.0.jar");
std::fs::write(&local_jar, b"jar").unwrap();
@@ -412,7 +467,10 @@ async fn neoforge_inheritsfrom_resolves() {
.await
.unwrap();
assert_eq!(inv.main_class, "cpw.mods.bootstraplauncher.BootstrapLauncher");
assert_eq!(
inv.main_class,
"cpw.mods.bootstraplauncher.BootstrapLauncher"
);
assert!(
inv.jvm_args
.windows(2)
@@ -527,9 +585,7 @@ async fn rule_disallow_excludes_library() {
.await
.unwrap();
let denied = fx
.meta_dir
.join("libraries/com/denied/lib/1.0/lib-1.0.jar");
let denied = fx.meta_dir.join("libraries/com/denied/lib/1.0/lib-1.0.jar");
assert!(
!inv.classpath.contains(&denied),
"denied library was included: {:?}",
@@ -680,4 +736,3 @@ async fn legacy_loader_profile_missing_installer_json_errors() {
"expected Parse error about missing installer JSON, got: {err:?}"
);
}
+42 -10
View File
@@ -130,13 +130,15 @@ async fn fabric_fetch_profile_parses_libraries() {
.mount(&server)
.await;
let profile =
fetch_fabric_profile_from(&HttpClient::new(), &server.uri(), "1.20.1", "0.15.0")
.await
.expect("fabric profile");
let profile = fetch_fabric_profile_from(&HttpClient::new(), &server.uri(), "1.20.1", "0.15.0")
.await
.expect("fabric profile");
assert_eq!(profile.id, "fabric-loader-0.15.0-1.20.1");
assert_eq!(profile.main_class, "net.fabricmc.loader.impl.launch.knot.KnotClient");
assert_eq!(
profile.main_class,
"net.fabricmc.loader.impl.launch.knot.KnotClient"
);
assert_eq!(profile.libraries.len(), 1);
assert_eq!(profile.libraries[0].url, "https://maven.fabricmc.net/");
}
@@ -192,13 +194,15 @@ async fn quilt_fetch_profile_parses_libraries() {
.mount(&server)
.await;
let profile =
fetch_quilt_profile_from(&HttpClient::new(), &server.uri(), "1.20.1", "0.23.0")
.await
.expect("quilt profile");
let profile = fetch_quilt_profile_from(&HttpClient::new(), &server.uri(), "1.20.1", "0.23.0")
.await
.expect("quilt profile");
assert_eq!(profile.id, "quilt-loader-0.23.0-1.20.1");
assert_eq!(profile.libraries[0].url, "https://maven.quiltmc.org/repository/release/");
assert_eq!(
profile.libraries[0].url,
"https://maven.quiltmc.org/repository/release/"
);
}
// ---------- neoforge ----------
@@ -229,6 +233,30 @@ async fn neoforge_fetch_versions_filters_by_prefix() {
assert_eq!(versions, vec!["20.4.190", "20.4.150"]);
}
#[tokio::test]
async fn neoforge_fetch_versions_supports_modern_minecraft_numbering() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/maven-api"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"versions": [
"26.1.2.76",
"26.1.2.75",
"26.1.1.15",
"21.1.233"
]
})))
.mount(&server)
.await;
let url = format!("{}/maven-api", server.uri());
let versions = fetch_neoforge_versions_from(&HttpClient::new(), &url, "26.1.2")
.await
.expect("neoforge versions");
assert_eq!(versions, vec!["26.1.2.76", "26.1.2.75"]);
}
#[tokio::test]
async fn neoforge_fetch_game_versions_reverse_engineers_mc_versions() {
// neoforge "21.0.x" maps back to MC 1.21 (minor=0 strips the suffix);
@@ -239,6 +267,8 @@ async fn neoforge_fetch_game_versions_reverse_engineers_mc_versions() {
.and(path("/maven-api"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"versions": [
"26.1.2.76",
"26.1.1.15",
"21.0.10",
"21.0.5",
"20.4.190",
@@ -255,6 +285,8 @@ async fn neoforge_fetch_game_versions_reverse_engineers_mc_versions() {
let ids: Vec<&str> = versions.iter().map(|v| v.id.as_str()).collect();
// dedup keeps the first occurrence, output is reversed, so the
// resulting list is in upstream maven-version order, deduped.
assert!(ids.contains(&"26.1.2"));
assert!(ids.contains(&"26.1.1"));
assert!(ids.contains(&"1.21"));
assert!(ids.contains(&"1.20.4"));
// both versions should be marked stable (no snapshot flag in maven)
+6 -5
View File
@@ -10,7 +10,7 @@ use wiremock::{Mock, MockServer, ResponseTemplate};
use rmcl::net::HttpClient;
use rmcl::net::mojang::{
AssetIndex, Artifact, Download, JavaVersion, Library, LibraryDownloads, VersionDownloads,
Artifact, AssetIndex, Download, JavaVersion, Library, LibraryDownloads, VersionDownloads,
VersionEntry, VersionMeta, download_assets, download_assets_from, download_libraries,
fetch_version_manifest_from, fetch_version_meta_with_raw,
};
@@ -226,9 +226,7 @@ async fn download_assets_from_writes_index_and_assets() {
.await;
// asset hash starts with "ab" so the per-asset URL is /<base>/ab/<hash>.
Mock::given(method("GET"))
.and(path(
"/cdn/ab/ab1234567890abcdef1234567890abcdef123456",
))
.and(path("/cdn/ab/ab1234567890abcdef1234567890abcdef123456"))
.respond_with(ResponseTemplate::new(200).set_body_bytes(b"asset-bytes".to_vec()))
.expect(1)
.mount(&server)
@@ -272,7 +270,10 @@ async fn download_assets_writes_index_when_objects_is_empty() {
.expect("download_assets index-only");
let index_path = tmp.path().join("assets/indexes/5.json");
assert!(index_path.exists(), "expected asset index at {index_path:?}");
assert!(
index_path.exists(),
"expected asset index at {index_path:?}"
);
let body: serde_json::Value =
serde_json::from_slice(&std::fs::read(&index_path).unwrap()).unwrap();
assert!(body.get("objects").is_some());