10 Commits
Author SHA1 Message Date
objz de9d11e2f3 chore(release): v0.2.2 2026-04-25 15:41:31 +02:00
objz b43ed3e807 fix(ci): include version in release tarball filenames
tarballs are now named mcl-{version}-{target}.tar.gz instead of
mcl-{target}.tar.gz so each release has unique filenames. this
prevents package manager caches from serving stale downloads.
2026-04-25 15:40:38 +02:00
objz 035bae98d9 fix(logs): show real filename for live log and keep content on instance stop
the live log entry now shows the actual log filename in green instead
of a generic "Live" label. when the instance stops while viewing the
live log, the viewer transitions to the on-disk file so the content
stays visible instead of going blank.
2026-04-25 15:34:20 +02:00
objz 82665bd4e6 merge: resolve conflicts keeping streaming load and notify watcher 2026-04-25 15:23:49 +02:00
objz 82d215f58b feat(content): streaming load and event-driven file watching with notify
replace mtime polling with the notify crate (v8) for cross-platform
file watching via inotify/FSEvents/ReadDirectoryChanges. the initial
load now streams entries one by one through an mpsc channel so mods
appear as they are scanned instead of waiting for the full batch.

file changes detected by notify trigger a background directory diff
that applies incremental updates: toggles, removals, and per-file
scans for new entries. no full rescan ever happens after initial load.
instance switching restores from the in-memory cache instantly.
2026-04-25 15:19:54 +02:00
objz 52747158e9 refactor(content): extract per-file scan functions for incremental updates
split scan_one_mod, scan_one_resource_pack, scan_one_shader, and
scan_one_world out of their directory-level scan functions. the
directory-level wrappers now delegate to these. this allows the file
watcher to scan individual new files without rescanning the entire
directory.
2026-04-25 15:19:43 +02:00
objz 1019169100 fix(tui): restore terminal on panic to prevent apparent freezes
without a panic hook, any panic left the terminal in raw mode with
the alternate screen active, making it look like the app froze.
2026-04-25 15:19:34 +02:00
objz 5dbb2be873 no-mistakes(lint): fix(lint): rustfmt formatting in mods.rs 2026-04-25 14:25:04 +02:00
objz 9f463c80bc feat(content): extract mod icons and metadata from all loader formats
adds support for quilt.mod.json, META-INF/mods.toml (forge),
META-INF/neoforge.mods.toml, and mcmod.info (legacy forge) in
addition to fabric.mod.json. falls back to logo.png, icon.png,
and pack.png at the jar root when metadata has no icon path.
2026-04-25 13:02:33 +02:00
objz aa19e5bde1 fix(tui): allow navigating filtered results after searching
enter now confirms the search and returns focus to the list so items
can be selected, toggled, etc. pressing / returns to the search bar
with the query intact, esc clears it.
2026-04-25 12:40:42 +02:00
56 changed files with 1311 additions and 466 deletions

No files matched your search

+11 -4
View File
@@ -55,23 +55,30 @@ jobs:
CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER: aarch64-linux-gnu-gcc CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER: aarch64-linux-gnu-gcc
run: cargo build --release --target ${{ matrix.target }} run: cargo build --release --target ${{ matrix.target }}
- name: get version
id: version
shell: bash
run: |
version=$(grep '^version' Cargo.toml | head -1 | sed 's/.*"\(.*\)".*/\1/')
echo "version=$version" >> "$GITHUB_OUTPUT"
- name: package (unix) - name: package (unix)
if: runner.os != 'Windows' if: runner.os != 'Windows'
run: | run: |
cd target/${{ matrix.target }}/release cd target/${{ matrix.target }}/release
tar czf ../../../mcl-${{ matrix.target }}.tar.gz ${{ matrix.artifact }} tar czf ../../../mcl-${{ steps.version.outputs.version }}-${{ matrix.target }}.tar.gz ${{ matrix.artifact }}
- name: package (windows) - name: package (windows)
if: runner.os == 'Windows' if: runner.os == 'Windows'
run: | run: |
cd target/${{ matrix.target }}/release cd target/${{ matrix.target }}/release
Compress-Archive -Path ${{ matrix.artifact }} -DestinationPath ../../../mcl-${{ matrix.target }}.zip Compress-Archive -Path ${{ matrix.artifact }} -DestinationPath ../../../mcl-${{ steps.version.outputs.version }}-${{ matrix.target }}.zip
- name: upload artifact - name: upload artifact
uses: actions/upload-artifact@v7 uses: actions/upload-artifact@v7
with: with:
name: mcl-${{ matrix.target }} name: mcl-${{ steps.version.outputs.version }}-${{ matrix.target }}
path: mcl-${{ matrix.target }}.* path: mcl-${{ steps.version.outputs.version }}-${{ matrix.target }}.*
release: release:
needs: build needs: build
Generated
+106 -1
View File
@@ -1023,6 +1023,15 @@ dependencies = [
"percent-encoding", "percent-encoding",
] ]
[[package]]
name = "fsevent-sys"
version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76ee7a02da4d231650c7cea31349b889be2f45ddb3ef3032d2ec8185f6313fd2"
dependencies = [
"libc",
]
[[package]] [[package]]
name = "funty" name = "funty"
version = "2.0.0" version = "2.0.0"
@@ -1508,6 +1517,26 @@ dependencies = [
"rustversion", "rustversion",
] ]
[[package]]
name = "inotify"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bd5b3eaf1a28b758ac0faa5a4254e8ab2705605496f1b1f3fbbc3988ad73d199"
dependencies = [
"bitflags 2.11.1",
"inotify-sys",
"libc",
]
[[package]]
name = "inotify-sys"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e05c02b5e89bff3b946cedeca278abc628fe811e604f027c45a8aa3cf793d0eb"
dependencies = [
"libc",
]
[[package]] [[package]]
name = "inout" name = "inout"
version = "0.1.4" version = "0.1.4"
@@ -1692,6 +1721,26 @@ dependencies = [
"syn 2.0.117", "syn 2.0.117",
] ]
[[package]]
name = "kqueue"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eac30106d7dce88daf4a3fcb4879ea939476d5074a9b7ddd0fb97fa4bed5596a"
dependencies = [
"kqueue-sys",
"libc",
]
[[package]]
name = "kqueue-sys"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed9625ffda8729b85e45cf04090035ac368927b8cebc34898e7c120f52e4838b"
dependencies = [
"bitflags 1.3.2",
"libc",
]
[[package]] [[package]]
name = "lab" name = "lab"
version = "0.11.0" version = "0.11.0"
@@ -1830,7 +1879,7 @@ dependencies = [
[[package]] [[package]]
name = "mcl-launcher" name = "mcl-launcher"
version = "0.2.1" version = "0.2.2"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"chrono", "chrono",
@@ -1843,6 +1892,7 @@ dependencies = [
"image", "image",
"log", "log",
"minecraft-msa-auth", "minecraft-msa-auth",
"notify",
"oauth2", "oauth2",
"open", "open",
"ratatui", "ratatui",
@@ -1972,6 +2022,33 @@ dependencies = [
"minimal-lexical", "minimal-lexical",
] ]
[[package]]
name = "notify"
version = "8.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4d3d07927151ff8575b7087f245456e549fea62edf0ec4e565a5ee50c8402bc3"
dependencies = [
"bitflags 2.11.1",
"fsevent-sys",
"inotify",
"kqueue",
"libc",
"log",
"mio",
"notify-types",
"walkdir",
"windows-sys 0.60.2",
]
[[package]]
name = "notify-types"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42b8cfee0e339a0337359f3c88165702ac6e600dc01c0cc9579a92d62b08477a"
dependencies = [
"bitflags 2.11.1",
]
[[package]] [[package]]
name = "nu-ansi-term" name = "nu-ansi-term"
version = "0.50.3" version = "0.50.3"
@@ -3017,6 +3094,15 @@ dependencies = [
"bytemuck", "bytemuck",
] ]
[[package]]
name = "same-file"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
dependencies = [
"winapi-util",
]
[[package]] [[package]]
name = "scopeguard" name = "scopeguard"
version = "1.2.0" version = "1.2.0"
@@ -3972,6 +4058,16 @@ dependencies = [
"utf8parse", "utf8parse",
] ]
[[package]]
name = "walkdir"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
dependencies = [
"same-file",
"winapi-util",
]
[[package]] [[package]]
name = "want" name = "want"
version = "0.3.1" version = "0.3.1"
@@ -4245,6 +4341,15 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-util"
version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.61.2",
]
[[package]] [[package]]
name = "winapi-x86_64-pc-windows-gnu" name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0" version = "0.4.0"
+2 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "mcl-launcher" name = "mcl-launcher"
version = "0.2.1" version = "0.2.2"
authors = ["objz"] authors = ["objz"]
edition = "2024" edition = "2024"
description = "A fully featured Minecraft launcher TUI" description = "A fully featured Minecraft launcher TUI"
@@ -50,6 +50,7 @@ oauth2 = "5.0.0"
open = "5" open = "5"
which = "8.0.2" which = "8.0.2"
dirs = "6.0.0" dirs = "6.0.0"
notify = "8"
[profile.release] [profile.release]
+2 -2
View File
@@ -10,8 +10,8 @@ depends=()
provides=('mcl-launcher') provides=('mcl-launcher')
conflicts=('mcl-launcher' 'mcl-launcher-git') conflicts=('mcl-launcher' 'mcl-launcher-git')
source=("LICENSE-${pkgver}::${url}/raw/v${pkgver}/LICENSE" "README-${pkgver}::${url}/raw/v${pkgver}/README.md") source=("LICENSE-${pkgver}::${url}/raw/v${pkgver}/LICENSE" "README-${pkgver}::${url}/raw/v${pkgver}/README.md")
source_x86_64=("${url}/releases/download/v${pkgver}/mcl-x86_64-unknown-linux-gnu.tar.gz") source_x86_64=("${url}/releases/download/v${pkgver}/mcl-${pkgver}-x86_64-unknown-linux-gnu.tar.gz")
source_aarch64=("${url}/releases/download/v${pkgver}/mcl-aarch64-unknown-linux-gnu.tar.gz") source_aarch64=("${url}/releases/download/v${pkgver}/mcl-${pkgver}-aarch64-unknown-linux-gnu.tar.gz")
sha256sums=('SKIP' 'SKIP') sha256sums=('SKIP' 'SKIP')
sha256sums_x86_64=('SKIP') sha256sums_x86_64=('SKIP')
sha256sums_aarch64=('SKIP') sha256sums_aarch64=('SKIP')
+3 -3
View File
@@ -3,7 +3,7 @@ mod accounts;
mod oauth; mod oauth;
pub use accounts::{ pub use accounts::{
account_store_path, create_offline_account, offline_uuid, Account, AccountStore, AccountType, Account, AccountStore, AccountType, AuthResult, account_store_path, create_offline_account,
AuthResult, offline_uuid,
}; };
pub use oauth::{refresh_and_get_token, start_microsoft_auth, DeviceCodeInfo, DEVICE_CODE_DISPLAY}; pub use oauth::{DEVICE_CODE_DISPLAY, DeviceCodeInfo, refresh_and_get_token, start_microsoft_auth};
+5 -3
View File
@@ -81,7 +81,8 @@ async fn add_microsoft_account() -> CliResult {
// wait for the device code to become available before showing it // wait for the device code to become available before showing it
loop { loop {
if let Ok(slot) = crate::auth::DEVICE_CODE_DISPLAY.lock() if let Ok(slot) = crate::auth::DEVICE_CODE_DISPLAY.lock()
&& let Some(info) = slot.as_ref() { && let Some(info) = slot.as_ref()
{
println!("Open: {}", info.verification_uri); println!("Open: {}", info.verification_uri);
println!("Code: {}", info.user_code); println!("Code: {}", info.user_code);
break; break;
@@ -92,7 +93,8 @@ async fn add_microsoft_account() -> CliResult {
// now wait for the user to complete auth in their browser // now wait for the user to complete auth in their browser
loop { loop {
if let Ok(slot) = result_arc.lock() if let Ok(slot) = result_arc.lock()
&& let Some(result) = slot.as_ref() { && let Some(result) = slot.as_ref()
{
return match result { return match result {
AuthResult::Success(account) => { AuthResult::Success(account) => {
let mut store = AccountStore::load(); let mut store = AccountStore::load();
@@ -153,7 +155,7 @@ use super::utils::{confirm, required_arg};
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::{add_offline_account, AccountStoreLike}; use super::{AccountStoreLike, add_offline_account};
use crate::auth::{Account, AccountType}; use crate::auth::{Account, AccountType};
#[derive(Default)] #[derive(Default)]
+1 -1
View File
@@ -2,8 +2,8 @@
// resolves the input, downloads if needed, then hands off to the import engine. // resolves the input, downloads if needed, then hands off to the import engine.
use clap::ArgMatches; use clap::ArgMatches;
use crate::instance::import::{parse_import_input, ImportInput};
use crate::instance::InstanceManager; use crate::instance::InstanceManager;
use crate::instance::import::{ImportInput, parse_import_input};
use crate::net::modrinth; use crate::net::modrinth;
type CliResult = Result<(), Box<dyn std::error::Error>>; type CliResult = Result<(), Box<dyn std::error::Error>>;
+1 -5
View File
@@ -34,11 +34,7 @@ pub fn format_datetime(value: &DateTime<Utc>) -> String {
} }
pub fn active_marker(active: bool) -> &'static str { pub fn active_marker(active: bool) -> &'static str {
if active { if active { ">" } else { " " }
">"
} else {
" "
}
} }
// find the widest value in each column to pad everything evenly // find the widest value in each column to pad everything evenly
+1 -1
View File
@@ -9,8 +9,8 @@ use clap::ArgMatches;
use crate::cli::instance::parse_loader; use crate::cli::instance::parse_loader;
use crate::cli::output::print_table; use crate::cli::output::print_table;
use crate::instance::ModLoader; use crate::instance::ModLoader;
use crate::net::mojang::{VersionEntry, VersionManifest};
use crate::net::HttpClient; use crate::net::HttpClient;
use crate::net::mojang::{VersionEntry, VersionManifest};
type CliResult = Result<(), Box<dyn std::error::Error>>; type CliResult = Result<(), Box<dyn std::error::Error>>;
+2 -1
View File
@@ -53,7 +53,8 @@ pub fn resolve_path(raw: &str) -> PathBuf {
return home.join(stripped); return home.join(stripped);
} }
} else if raw == "~" } else if raw == "~"
&& let Some(home) = dirs_next::home_dir() { && let Some(home) = dirs_next::home_dir()
{
return home; return home;
} }
PathBuf::from(raw) PathBuf::from(raw)
+4 -3
View File
@@ -7,9 +7,10 @@ pub mod shaders;
pub mod worlds; pub mod worlds;
pub use mods::{ContentEntry, scan_mods, toggle_entry}; pub use mods::{ContentEntry, scan_mods, toggle_entry};
pub use resource_packs::scan_resource_packs; pub use mods::scan_one_mod;
pub use shaders::scan_shaders; pub use resource_packs::{scan_resource_packs, scan_one_resource_pack};
pub use worlds::scan_worlds; pub use shaders::{scan_shaders, scan_one_shader};
pub use worlds::{scan_worlds, scan_one_world};
use std::io::Read; use std::io::Read;
+361 -33
View File
@@ -1,6 +1,8 @@
// mod scanning, metadata extraction, and icon rendering for the content list. // mod scanning, metadata extraction, and icon rendering for the content list.
// jar files are just zips, so it cracks them open looking for fabric.mod.json to get // jar files are just zips, so it cracks them open looking for loader-specific
// names, descriptions, and icons. if that fails, just the filename is used. it's fine. // metadata (fabric.mod.json, quilt.mod.json, mods.toml, mcmod.info) to get
// names, descriptions, and icons. if none of those work, falls back to common
// root-level icon paths (logo.png, icon.png, pack.png) or just the filename.
use std::io::Read; use std::io::Read;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@@ -41,10 +43,15 @@ struct FabricModJson {
} }
impl FabricModJson { impl FabricModJson {
// fabric's icon field can be a string path or a map of resolution -> path.
// if it's a map, just grab the first one. good enough.
fn icon_path(&self) -> String { fn icon_path(&self) -> String {
match &self.icon { icon_path_from_value(&self.icon)
}
}
// fabric and quilt both support icon as a string path or a map of
// resolution -> path. if it's a map, just grab the first one.
fn icon_path_from_value(value: &serde_json::Value) -> String {
match value {
serde_json::Value::String(s) => s.clone(), serde_json::Value::String(s) => s.clone(),
serde_json::Value::Object(map) => map serde_json::Value::Object(map) => map
.values() .values()
@@ -53,6 +60,58 @@ impl FabricModJson {
.to_owned(), .to_owned(),
_ => String::new(), _ => String::new(),
} }
}
// quilt puts its metadata under a "metadata" sub-object
#[derive(Deserialize, Default)]
struct QuiltModJson {
#[serde(default)]
quilt_loader: QuiltLoader,
}
#[derive(Deserialize, Default)]
struct QuiltLoader {
#[serde(default)]
metadata: QuiltMetadata,
}
#[derive(Deserialize, Default)]
struct QuiltMetadata {
#[serde(default)]
name: String,
#[serde(default)]
description: String,
#[serde(default)]
icon: serde_json::Value,
}
impl QuiltMetadata {
fn icon_path(&self) -> String {
icon_path_from_value(&self.icon)
}
}
pub fn scan_one_mod(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry {
let (name, description, icon_bytes) = read_mod_metadata(path);
let icon_lines = icon_bytes
.as_ref()
.and_then(|bytes| make_icon_pixels(bytes, 6, 3))
.or_else(|| Some(fallback_icon()));
let display_name = if name.is_empty() {
file_stem.to_owned()
} else {
name
};
ContentEntry {
file_stem: file_stem.to_owned(),
name: display_name,
description,
enabled,
icon_bytes,
path: path.to_path_buf(),
icon_lines,
} }
} }
@@ -80,34 +139,17 @@ pub fn scan_mods(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry>
continue; continue;
}; };
let (name, description, icon_bytes) = read_mod_metadata(&path); entries.push(scan_one_mod(&path, &file_stem, enabled));
let icon_lines = icon_bytes
.as_ref()
.and_then(|bytes| make_icon_pixels(bytes, 6, 3))
.or_else(|| Some(fallback_icon()));
let display_name = if name.is_empty() {
file_stem.clone()
} else {
name
};
entries.push(ContentEntry {
file_stem,
name: display_name,
description,
enabled,
icon_bytes,
path,
icon_lines,
});
} }
entries.sort_by_cached_key(|e| e.name.to_lowercase()); entries.sort_by_cached_key(|e| e.name.to_lowercase());
entries entries
} }
// tries fabric.mod.json first for rich metadata. if that's missing (forge/other mods), // tries each loader's metadata file to extract name, description, and icon.
// still attempts to grab pack.png as a last resort for an icon // checks fabric.mod.json, quilt.mod.json, META-INF/mods.toml (forge),
// META-INF/neoforge.mods.toml, and mcmod.info (legacy forge). if none of
// those yield an icon, falls back to common root-level paths.
fn read_mod_metadata(jar_path: &Path) -> (String, String, Option<Vec<u8>>) { fn read_mod_metadata(jar_path: &Path) -> (String, String, Option<Vec<u8>>) {
let file = match std::fs::File::open(jar_path) { let file = match std::fs::File::open(jar_path) {
Ok(file) => file, Ok(file) => file,
@@ -119,19 +161,43 @@ fn read_mod_metadata(jar_path: &Path) -> (String, String, Option<Vec<u8>>) {
Err(_) => return (String::new(), String::new(), None), Err(_) => return (String::new(), String::new(), None),
}; };
if let Some((name, description, icon_path)) = read_fabric_meta(&mut archive) { // try each loader's metadata in order. if we get metadata but the
let icon_bytes = if icon_path.is_empty() { // declared icon path is missing, fall back to common root-level icons.
type MetaReader = fn(&mut zip::ZipArchive<std::fs::File>) -> Option<(String, String, String)>;
let readers: [MetaReader; 4] = [
read_fabric_meta,
read_quilt_meta,
read_forge_toml_meta,
read_mcmod_info,
];
for reader in &readers {
if let Some((name, description, icon_path)) = reader(&mut archive) {
let icon_path = icon_path.trim_start_matches('/');
let icon = if icon_path.is_empty() {
None None
} else { } else {
read_zip_bytes(&mut archive, &icon_path) read_zip_bytes(&mut archive, icon_path)
}; }
return (name, description, icon_bytes); .or_else(|| try_fallback_icons(&mut archive));
return (name, description, icon);
}
} }
let icon_bytes = read_zip_bytes(&mut archive, "pack.png"); // no recognized metadata at all, try common icon paths
let icon_bytes = try_fallback_icons(&mut archive);
(String::new(), String::new(), icon_bytes) (String::new(), String::new(), icon_bytes)
} }
fn try_fallback_icons(archive: &mut zip::ZipArchive<std::fs::File>) -> Option<Vec<u8>> {
for path in ["logo.png", "icon.png", "pack.png"] {
if let Some(bytes) = read_zip_bytes(archive, path) {
return Some(bytes);
}
}
None
}
fn read_fabric_meta( fn read_fabric_meta(
archive: &mut zip::ZipArchive<std::fs::File>, archive: &mut zip::ZipArchive<std::fs::File>,
) -> Option<(String, String, String)> { ) -> Option<(String, String, String)> {
@@ -144,6 +210,98 @@ fn read_fabric_meta(
Some((data.name, data.description, icon)) Some((data.name, data.description, icon))
} }
fn read_quilt_meta(
archive: &mut zip::ZipArchive<std::fs::File>,
) -> Option<(String, String, String)> {
let mut entry = archive.by_name("quilt.mod.json").ok()?;
let mut raw = String::new();
entry.read_to_string(&mut raw).ok()?;
let sanitized = sanitize_json_strings(&raw);
let data: QuiltModJson = serde_json::from_str(&sanitized).ok()?;
let meta = data.quilt_loader.metadata;
let icon = meta.icon_path();
Some((meta.name, meta.description, icon))
}
// forge (META-INF/mods.toml) and neoforge (META-INF/neoforge.mods.toml)
// share the same format. we only need the top-level logoFile and the first
// [[mods]] entry for name/description.
// some jars (e.g. dependency-only libs) have a mods.toml with logoFile
// but no [[mods]] section. we still want the icon in that case.
fn read_forge_toml_meta(
archive: &mut zip::ZipArchive<std::fs::File>,
) -> Option<(String, String, String)> {
let raw = read_zip_string(archive, "META-INF/neoforge.mods.toml")
.or_else(|| read_zip_string(archive, "META-INF/mods.toml"))?;
let table: toml::Table = raw.parse().ok()?;
let logo = table
.get("logoFile")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_owned();
let (name, description) = table
.get("mods")
.and_then(|v| v.as_array())
.and_then(|a| a.first())
.and_then(|v| v.as_table())
.map(|first| {
let n = first
.get("displayName")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_owned();
let d = first
.get("description")
.and_then(|v| v.as_str())
.unwrap_or("")
.trim()
.to_owned();
(n, d)
})
.unwrap_or_default();
Some((name, description, logo))
}
// legacy forge mcmod.info is either a bare json array of mod entries
// or an object with a "modList" key wrapping the array
fn read_mcmod_info(
archive: &mut zip::ZipArchive<std::fs::File>,
) -> Option<(String, String, String)> {
let mut entry = archive.by_name("mcmod.info").ok()?;
let mut raw = String::new();
entry.read_to_string(&mut raw).ok()?;
let sanitized = sanitize_json_strings(&raw);
let parsed: serde_json::Value = serde_json::from_str(&sanitized).ok()?;
let first = match &parsed {
serde_json::Value::Array(arr) => arr.first()?,
serde_json::Value::Object(obj) => obj.get("modList")?.as_array()?.first()?,
_ => return None,
};
let name = first
.get("name")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_owned();
let description = first
.get("description")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_owned();
let logo = first
.get("logoFile")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_owned();
Some((name, description, logo))
}
fn read_zip_string(archive: &mut zip::ZipArchive<std::fs::File>, path: &str) -> Option<String> {
let mut entry = archive.by_name(path).ok()?;
let mut s = String::new();
entry.read_to_string(&mut s).ok()?;
Some(s)
}
// some mod authors put raw newlines/tabs inside json string values which is // some mod authors put raw newlines/tabs inside json string values which is
// technically invalid json. walks through character by character, tracking // technically invalid json. walks through character by character, tracking
// whether it's inside a string, and escapes the offending characters. // whether it's inside a string, and escapes the offending characters.
@@ -407,6 +565,176 @@ mod tests {
assert!(dir.join("mymod.jar").exists()); assert!(dir.join("mymod.jar").exists());
} }
use std::io::Write as _;
// helper to create a jar (zip) file with the given entries
fn make_jar(dir: &Path, name: &str, entries: &[(&str, &[u8])]) {
let path = dir.join(name);
let file = std::fs::File::create(&path).unwrap();
let mut zip = zip::ZipWriter::new(file);
let options: zip::write::FileOptions<()> =
zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Stored);
for (entry_name, data) in entries {
zip.start_file(*entry_name, options).unwrap();
zip.write_all(data).unwrap();
}
zip.finish().unwrap();
}
#[test]
fn scan_mods_reads_fabric_metadata() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_mods_dir(tmp.path(), "inst");
let meta = r#"{"name":"Fabric Mod","description":"A fabric mod","icon":"icon.png"}"#;
make_jar(
&dir,
"fabric-mod.jar",
&[("fabric.mod.json", meta.as_bytes())],
);
let mods = scan_mods(tmp.path(), "inst");
assert_eq!(mods.len(), 1);
assert_eq!(mods[0].name, "Fabric Mod");
assert_eq!(mods[0].description, "A fabric mod");
}
#[test]
fn scan_mods_reads_quilt_metadata() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_mods_dir(tmp.path(), "inst");
let meta =
r#"{"quilt_loader":{"metadata":{"name":"Quilt Mod","description":"A quilt mod"}}}"#;
make_jar(
&dir,
"quilt-mod.jar",
&[("quilt.mod.json", meta.as_bytes())],
);
let mods = scan_mods(tmp.path(), "inst");
assert_eq!(mods.len(), 1);
assert_eq!(mods[0].name, "Quilt Mod");
assert_eq!(mods[0].description, "A quilt mod");
}
#[test]
fn scan_mods_reads_forge_toml_metadata() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_mods_dir(tmp.path(), "inst");
let meta = r#"
logoFile = "logo.png"
[[mods]]
displayName = "Forge Mod"
description = "A forge mod"
"#;
make_jar(
&dir,
"forge-mod.jar",
&[("META-INF/mods.toml", meta.as_bytes())],
);
let mods = scan_mods(tmp.path(), "inst");
assert_eq!(mods.len(), 1);
assert_eq!(mods[0].name, "Forge Mod");
assert_eq!(mods[0].description, "A forge mod");
}
#[test]
fn scan_mods_reads_neoforge_toml_metadata() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_mods_dir(tmp.path(), "inst");
let meta = r#"
logoFile = "logo.png"
[[mods]]
displayName = "NeoForge Mod"
description = "A neoforge mod"
"#;
make_jar(
&dir,
"neoforge-mod.jar",
&[("META-INF/neoforge.mods.toml", meta.as_bytes())],
);
let mods = scan_mods(tmp.path(), "inst");
assert_eq!(mods.len(), 1);
assert_eq!(mods[0].name, "NeoForge Mod");
assert_eq!(mods[0].description, "A neoforge mod");
}
#[test]
fn scan_mods_reads_mcmod_info_array() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_mods_dir(tmp.path(), "inst");
let meta = r#"[{"name":"Legacy Mod","description":"An old forge mod"}]"#;
make_jar(&dir, "legacy-mod.jar", &[("mcmod.info", meta.as_bytes())]);
let mods = scan_mods(tmp.path(), "inst");
assert_eq!(mods.len(), 1);
assert_eq!(mods[0].name, "Legacy Mod");
assert_eq!(mods[0].description, "An old forge mod");
}
#[test]
fn scan_mods_reads_mcmod_info_modlist() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_mods_dir(tmp.path(), "inst");
let meta = r#"{"modList":[{"name":"Wrapped Mod","description":"Has modList wrapper"}]}"#;
make_jar(&dir, "wrapped-mod.jar", &[("mcmod.info", meta.as_bytes())]);
let mods = scan_mods(tmp.path(), "inst");
assert_eq!(mods.len(), 1);
assert_eq!(mods[0].name, "Wrapped Mod");
assert_eq!(mods[0].description, "Has modList wrapper");
}
#[test]
fn scan_mods_prefers_fabric_over_forge() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_mods_dir(tmp.path(), "inst");
let fabric = r#"{"name":"Fabric Name","description":"fabric desc"}"#;
let forge = "[[mods]]\ndisplayName = \"Forge Name\"\ndescription = \"forge desc\"\n";
make_jar(
&dir,
"multi.jar",
&[
("fabric.mod.json", fabric.as_bytes()),
("META-INF/mods.toml", forge.as_bytes()),
],
);
let mods = scan_mods(tmp.path(), "inst");
assert_eq!(mods[0].name, "Fabric Name");
}
#[test]
fn scan_mods_fallback_icon_paths() {
let tmp = tempfile::tempdir().unwrap();
let dir = setup_mods_dir(tmp.path(), "inst");
// jar with no metadata but has logo.png
let png_bytes = b"\x89PNG fake";
make_jar(&dir, "no-meta.jar", &[("logo.png", png_bytes)]);
let mods = scan_mods(tmp.path(), "inst");
assert_eq!(mods.len(), 1);
// should use filename as name since no metadata
assert_eq!(mods[0].name, "no-meta");
// icon_bytes should contain the logo.png content
assert_eq!(mods[0].icon_bytes.as_deref(), Some(png_bytes.as_slice()));
}
#[test]
fn icon_path_from_value_string() {
let val = serde_json::json!("assets/icon.png");
assert_eq!(icon_path_from_value(&val), "assets/icon.png");
}
#[test]
fn icon_path_from_value_map() {
let val = serde_json::json!({"64": "icon_64.png", "128": "icon_128.png"});
let result = icon_path_from_value(&val);
// should return one of the values
assert!(result == "icon_64.png" || result == "icon_128.png");
}
#[test]
fn icon_path_from_value_null() {
let val = serde_json::Value::Null;
assert_eq!(icon_path_from_value(&val), "");
}
#[test] #[test]
fn toggle_entry_disable() { fn toggle_entry_disable() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
+34 -28
View File
@@ -6,7 +6,7 @@ use std::path::Path;
use serde::Deserialize; use serde::Deserialize;
use super::mods::{make_icon_pixels, ContentEntry}; use super::mods::{ContentEntry, make_icon_pixels};
#[derive(Deserialize, Default)] #[derive(Deserialize, Default)]
pub(crate) struct PackMcMeta { pub(crate) struct PackMcMeta {
@@ -43,6 +43,36 @@ pub(crate) fn extract_description(value: &serde_json::Value) -> String {
} }
} }
pub fn scan_one_resource_pack(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry {
let is_dir = path.is_dir();
let (name, description, icon_bytes) = if is_dir {
read_pack_metadata_from_dir(path)
} else {
read_pack_metadata_from_zip(path)
};
let icon_lines = icon_bytes
.as_ref()
.and_then(|bytes| make_icon_pixels(bytes, 6, 3))
.or_else(|| Some(super::mods::fallback_icon()));
let display_name = if name.is_empty() {
file_stem.to_owned()
} else {
name
};
ContentEntry {
file_stem: file_stem.to_owned(),
name: display_name,
description,
enabled,
icon_bytes,
path: path.to_path_buf(),
icon_lines,
}
}
pub fn scan_resource_packs(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> { pub fn scan_resource_packs(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
let packs_dir = instances_dir let packs_dir = instances_dir
.join(instance_name) .join(instance_name)
@@ -63,8 +93,7 @@ pub fn scan_resource_packs(instances_dir: &Path, instance_name: &str) -> Vec<Con
None => continue, None => continue,
}; };
let is_dir = path.is_dir(); let (enabled, file_stem) = if path.is_dir() {
let (enabled, file_stem) = if is_dir {
super::parse_enabled_stem_dir(&file_name) super::parse_enabled_stem_dir(&file_name)
} else if let Some(pair) = super::parse_enabled_stem(&file_name, ".zip") { } else if let Some(pair) = super::parse_enabled_stem(&file_name, ".zip") {
pair pair
@@ -72,27 +101,7 @@ pub fn scan_resource_packs(instances_dir: &Path, instance_name: &str) -> Vec<Con
continue; continue;
}; };
let (name, description, icon_bytes) = if is_dir { entries.push(scan_one_resource_pack(&path, &file_stem, enabled));
read_pack_metadata_from_dir(&path)
} else {
read_pack_metadata_from_zip(&path)
};
let icon_lines = icon_bytes
.as_ref()
.and_then(|bytes| make_icon_pixels(bytes, 6, 3))
.or_else(|| Some(super::mods::fallback_icon()));
let display_name = if name.is_empty() { file_stem.clone() } else { name };
entries.push(ContentEntry {
file_stem,
name: display_name,
description,
enabled,
icon_bytes,
path,
icon_lines,
});
} }
entries.sort_by_cached_key(|e| e.name.to_lowercase()); entries.sort_by_cached_key(|e| e.name.to_lowercase());
@@ -194,10 +203,7 @@ mod tests {
} }
fn setup_packs_dir(tmp: &std::path::Path, instance: &str) -> std::path::PathBuf { fn setup_packs_dir(tmp: &std::path::Path, instance: &str) -> std::path::PathBuf {
let dir = tmp let dir = tmp.join(instance).join(".minecraft").join("resourcepacks");
.join(instance)
.join(".minecraft")
.join("resourcepacks");
std::fs::create_dir_all(&dir).unwrap(); std::fs::create_dir_all(&dir).unwrap();
dir dir
} }
+27 -23
View File
@@ -3,8 +3,31 @@
use std::path::Path; use std::path::Path;
use super::mods::{make_icon_pixels, ContentEntry}; use super::mods::{ContentEntry, make_icon_pixels};
use super::resource_packs::{extract_description, PackMcMeta}; use super::resource_packs::{PackMcMeta, extract_description};
pub fn scan_one_shader(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry {
let is_dir = path.is_dir();
let (description, icon_bytes) = if is_dir {
read_shader_metadata_from_dir(path)
} else {
read_shader_metadata_from_zip(path)
};
let icon_lines = icon_bytes
.as_ref()
.and_then(|bytes| make_icon_pixels(bytes, 6, 3));
ContentEntry {
file_stem: file_stem.to_owned(),
name: file_stem.to_owned(),
description,
enabled,
icon_bytes,
path: path.to_path_buf(),
icon_lines,
}
}
pub fn scan_shaders(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> { pub fn scan_shaders(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
let shaders_dir = instances_dir let shaders_dir = instances_dir
@@ -26,8 +49,7 @@ pub fn scan_shaders(instances_dir: &Path, instance_name: &str) -> Vec<ContentEnt
None => continue, None => continue,
}; };
let is_dir = path.is_dir(); let (enabled, file_stem) = if path.is_dir() {
let (enabled, file_stem) = if is_dir {
super::parse_enabled_stem_dir(&file_name) super::parse_enabled_stem_dir(&file_name)
} else if let Some(pair) = super::parse_enabled_stem(&file_name, ".zip") { } else if let Some(pair) = super::parse_enabled_stem(&file_name, ".zip") {
pair pair
@@ -35,25 +57,7 @@ pub fn scan_shaders(instances_dir: &Path, instance_name: &str) -> Vec<ContentEnt
continue; continue;
}; };
let (description, icon_bytes) = if is_dir { entries.push(scan_one_shader(&path, &file_stem, enabled));
read_shader_metadata_from_dir(&path)
} else {
read_shader_metadata_from_zip(&path)
};
let icon_lines = icon_bytes
.as_ref()
.and_then(|bytes| make_icon_pixels(bytes, 6, 3));
entries.push(ContentEntry {
name: file_stem.clone(),
file_stem,
description,
enabled,
icon_bytes,
path,
icon_lines,
});
} }
entries.sort_by_cached_key(|e| e.name.to_lowercase()); entries.sort_by_cached_key(|e| e.name.to_lowercase());
+36 -24
View File
@@ -4,7 +4,27 @@
use std::path::Path; use std::path::Path;
use super::mods::{make_icon_pixels, ContentEntry}; use super::mods::{ContentEntry, make_icon_pixels};
pub fn scan_one_world(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry {
let icon_bytes = std::fs::read(path.join("icon.png")).ok();
let icon_lines = icon_bytes
.as_ref()
.and_then(|bytes| make_icon_pixels(bytes, 12, 6))
.or_else(|| Some(super::mods::fallback_icon_large()));
let description = world_description(path);
ContentEntry {
name: file_stem.to_owned(),
file_stem: file_stem.to_owned(),
description,
enabled,
icon_bytes,
path: path.to_path_buf(),
icon_lines,
}
}
pub fn scan_worlds(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> { pub fn scan_worlds(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
let saves_dir = instances_dir let saves_dir = instances_dir
@@ -31,24 +51,7 @@ pub fn scan_worlds(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntr
}; };
let (enabled, file_stem) = super::parse_enabled_stem_dir(&file_name); let (enabled, file_stem) = super::parse_enabled_stem_dir(&file_name);
entries.push(scan_one_world(&path, &file_stem, enabled));
let icon_bytes = std::fs::read(path.join("icon.png")).ok();
let icon_lines = icon_bytes
.as_ref()
.and_then(|bytes| make_icon_pixels(bytes, 12, 6))
.or_else(|| Some(super::mods::fallback_icon_large()));
let description = world_description(&path);
entries.push(ContentEntry {
name: file_stem.clone(),
file_stem,
description,
enabled,
icon_bytes,
path,
icon_lines,
});
} }
entries.sort_by_cached_key(|e| e.name.to_lowercase()); entries.sort_by_cached_key(|e| e.name.to_lowercase());
@@ -77,12 +80,14 @@ fn world_description(world_dir: &Path) -> String {
let mut lines = Vec::new(); let mut lines = Vec::new();
if let Some(secs) = created if let Some(secs) = created
&& let Some(dt) = chrono::DateTime::from_timestamp(secs as i64, 0) { && let Some(dt) = chrono::DateTime::from_timestamp(secs as i64, 0)
{
lines.push(format!("Created: {}", dt.format("%Y-%m-%d %H:%M"))); lines.push(format!("Created: {}", dt.format("%Y-%m-%d %H:%M")));
} }
if let Some(secs) = modified if let Some(secs) = modified
&& let Some(dt) = chrono::DateTime::from_timestamp(secs as i64, 0) { && let Some(dt) = chrono::DateTime::from_timestamp(secs as i64, 0)
{
lines.push(format!("Played: {}", dt.format("%Y-%m-%d %H:%M"))); lines.push(format!("Played: {}", dt.format("%Y-%m-%d %H:%M")));
} }
@@ -100,7 +105,8 @@ fn dir_size_approx(path: &Path) -> u64 {
if let Ok(rd) = std::fs::read_dir(path) { if let Ok(rd) = std::fs::read_dir(path) {
for entry in rd.flatten() { for entry in rd.flatten() {
if let Ok(meta) = entry.metadata() if let Ok(meta) = entry.metadata()
&& meta.is_file() { && meta.is_file()
{
total += meta.len(); total += meta.len();
} }
} }
@@ -181,8 +187,14 @@ mod tests {
std::fs::create_dir(dir.join("ActiveWorld")).unwrap(); std::fs::create_dir(dir.join("ActiveWorld")).unwrap();
std::fs::create_dir(dir.join("HiddenWorld.disabled")).unwrap(); std::fs::create_dir(dir.join("HiddenWorld.disabled")).unwrap();
let worlds = scan_worlds(tmp.path(), "inst"); let worlds = scan_worlds(tmp.path(), "inst");
let active = worlds.iter().find(|w| w.file_stem == "ActiveWorld").unwrap(); let active = worlds
let hidden = worlds.iter().find(|w| w.file_stem == "HiddenWorld").unwrap(); .iter()
.find(|w| w.file_stem == "ActiveWorld")
.unwrap();
let hidden = worlds
.iter()
.find(|w| w.file_stem == "HiddenWorld")
.unwrap();
assert!(active.enabled); assert!(active.enabled);
assert!(!hidden.enabled); assert!(!hidden.enabled);
} }
+1 -2
View File
@@ -59,8 +59,7 @@ pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
let (loader_opt, loader_version) = pack.loader(); let (loader_opt, loader_version) = pack.loader();
let loader = loader_opt.unwrap_or(ModLoader::Vanilla); let loader = loader_opt.unwrap_or(ModLoader::Vanilla);
let name = instance_name_from_cfg(path) let name = instance_name_from_cfg(path).unwrap_or_else(|| "Imported Pack".to_string());
.unwrap_or_else(|| "Imported Pack".to_string());
let (mod_count, override_count) = count_content_files(path)?; let (mod_count, override_count) = count_content_files(path)?;
+18 -7
View File
@@ -70,17 +70,20 @@ pub struct ImportSummary {
// peeks inside a zip to figure out what format it is. // peeks inside a zip to figure out what format it is.
// checks for modrinth.index.json first, then mmc-pack.json. // checks for modrinth.index.json first, then mmc-pack.json.
pub fn detect_format(path: &Path) -> Result<PackFormat, String> { pub fn detect_format(path: &Path) -> Result<PackFormat, String> {
let file = std::fs::File::open(path) let file =
.map_err(|e| format!("Cannot open '{}': {e}", path.display()))?; std::fs::File::open(path).map_err(|e| format!("Cannot open '{}': {e}", path.display()))?;
let archive = zip::ZipArchive::new(file) let archive =
.map_err(|e| format!("Invalid ZIP '{}': {e}", path.display()))?; zip::ZipArchive::new(file).map_err(|e| format!("Invalid ZIP '{}': {e}", path.display()))?;
if archive.file_names().any(|n| n == "modrinth.index.json") { if archive.file_names().any(|n| n == "modrinth.index.json") {
return Ok(PackFormat::Mrpack); return Ok(PackFormat::Mrpack);
} }
// mmc-pack.json can be at root or one directory deep // mmc-pack.json can be at root or one directory deep
if archive.file_names().any(|n| n == "mmc-pack.json" || n.ends_with("/mmc-pack.json")) { if archive
.file_names()
.any(|n| n == "mmc-pack.json" || n.ends_with("/mmc-pack.json"))
{
return Ok(PackFormat::Mmc); return Ok(PackFormat::Mmc);
} }
@@ -100,12 +103,20 @@ pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
pub fn unique_instance_name(base: &str, instances_dir: &Path) -> String { pub fn unique_instance_name(base: &str, instances_dir: &Path) -> String {
let candidate = base.to_string(); let candidate = base.to_string();
if !instances_dir.join(&candidate).join("instance.json").exists() { if !instances_dir
.join(&candidate)
.join("instance.json")
.exists()
{
return candidate; return candidate;
} }
for n in 2..100 { for n in 2..100 {
let candidate = format!("{base} ({n})"); let candidate = format!("{base} ({n})");
if !instances_dir.join(&candidate).join("instance.json").exists() { if !instances_dir
.join(&candidate)
.join("instance.json")
.exists()
{
return candidate; return candidate;
} }
} }
+1 -1
View File
@@ -87,8 +87,8 @@ async fn download_mod_files(
index: &MrpackIndex, index: &MrpackIndex,
minecraft_dir: &Path, minecraft_dir: &Path,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> { ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc; use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
let client = crate::net::HttpClient::new(); let client = crate::net::HttpClient::new();
let total = index.files.len(); let total = index.files.len();
+3 -1
View File
@@ -306,7 +306,9 @@ async fn replace_log4j_fixed(lib_dir: &Path, classpath: &mut [PathBuf]) {
} }
let client = crate::net::HttpClient::new(); let client = crate::net::HttpClient::new();
if let Err(e) = crate::net::download_file(&client, url, &fixed_path, |_, _| {}).await { if let Err(e) = crate::net::download_file(&client, url, &fixed_path, |_, _| {}).await {
tracing::error!("Failed to download patched {old_name}: {e}, continuing with unpatched version"); tracing::error!(
"Failed to download patched {old_name}: {e}, continuing with unpatched version"
);
continue; continue;
} }
} }
+1 -1
View File
@@ -7,7 +7,7 @@ use async_trait::async_trait;
use super::{GameVersion, ModLoaderInstaller}; use super::{GameVersion, ModLoaderInstaller};
use crate::instance::models::ModLoader; use crate::instance::models::ModLoader;
use crate::net::{fabric as fabric_api, HttpClient, NetError}; use crate::net::{HttpClient, NetError, fabric as fabric_api};
pub struct FabricInstaller; pub struct FabricInstaller;
+1 -1
View File
@@ -8,7 +8,7 @@ use async_trait::async_trait;
use super::{GameVersion, ModLoaderInstaller}; use super::{GameVersion, ModLoaderInstaller};
use crate::instance::models::ModLoader; use crate::instance::models::ModLoader;
use crate::net::{forge as forge_api, HttpClient, NetError}; use crate::net::{HttpClient, NetError, forge as forge_api};
pub struct ForgeInstaller; pub struct ForgeInstaller;
+6 -2
View File
@@ -7,7 +7,7 @@ use async_trait::async_trait;
use super::{GameVersion, ModLoaderInstaller}; use super::{GameVersion, ModLoaderInstaller};
use crate::instance::models::ModLoader; use crate::instance::models::ModLoader;
use crate::net::{neoforge as neoforge_api, HttpClient, NetError}; use crate::net::{HttpClient, NetError, neoforge as neoforge_api};
pub struct NeoForgeInstaller; pub struct NeoForgeInstaller;
@@ -65,7 +65,11 @@ impl ModLoaderInstaller for NeoForgeInstaller {
} }
} }
fn save_neoforge_profile(instance_dir: &Path, meta_dir: &Path, loader_version: &str) -> Result<(), NetError> { fn save_neoforge_profile(
instance_dir: &Path,
meta_dir: &Path,
loader_version: &str,
) -> Result<(), NetError> {
let version_dir_name = format!("neoforge-{loader_version}"); let version_dir_name = format!("neoforge-{loader_version}");
let profile_filename = format!("neoforge-{loader_version}.json"); let profile_filename = format!("neoforge-{loader_version}.json");
super::save_installer_profile(instance_dir, meta_dir, &version_dir_name, &profile_filename) super::save_installer_profile(instance_dir, meta_dir, &version_dir_name, &profile_filename)
+2 -3
View File
@@ -7,7 +7,7 @@ use async_trait::async_trait;
use super::{GameVersion, ModLoaderInstaller}; use super::{GameVersion, ModLoaderInstaller};
use crate::instance::models::ModLoader; use crate::instance::models::ModLoader;
use crate::net::{quilt as quilt_api, HttpClient, NetError}; use crate::net::{HttpClient, NetError, quilt as quilt_api};
pub struct QuiltInstaller; pub struct QuiltInstaller;
@@ -41,8 +41,7 @@ impl ModLoaderInstaller for QuiltInstaller {
_instance_dir: &Path, _instance_dir: &Path,
meta_dir: &Path, meta_dir: &Path,
) -> Result<(), NetError> { ) -> Result<(), NetError> {
let profile = let profile = quilt_api::fetch_quilt_profile(client, game_version, loader_version).await?;
quilt_api::fetch_quilt_profile(client, game_version, loader_version).await?;
quilt_api::download_quilt_libraries(client, &profile, meta_dir).await?; quilt_api::download_quilt_libraries(client, &profile, meta_dir).await?;
super::save_profile_json( super::save_profile_json(
+1 -1
View File
@@ -8,7 +8,7 @@ use async_trait::async_trait;
use super::{GameVersion, ModLoaderInstaller}; use super::{GameVersion, ModLoaderInstaller};
use crate::instance::models::ModLoader; use crate::instance::models::ModLoader;
use crate::net::{mojang, HttpClient, NetError}; use crate::net::{HttpClient, NetError, mojang};
pub struct VanillaInstaller; pub struct VanillaInstaller;
+3 -3
View File
@@ -137,8 +137,7 @@ impl InstanceManager {
} }
} }
crate::net::mojang::download_libraries(&self.client, &version_meta, &self.meta_dir) crate::net::mojang::download_libraries(&self.client, &version_meta, &self.meta_dir).await?;
.await?;
crate::net::mojang::download_assets(&self.client, &version_meta, &self.meta_dir).await?; crate::net::mojang::download_assets(&self.client, &version_meta, &self.meta_dir).await?;
@@ -217,7 +216,8 @@ impl InstanceManager {
let config_path = new_dir.join("instance.json"); let config_path = new_dir.join("instance.json");
if let Ok(data) = std::fs::read_to_string(&config_path) if let Ok(data) = std::fs::read_to_string(&config_path)
&& let Ok(mut config) = serde_json::from_str::<InstanceConfig>(&data) { && let Ok(mut config) = serde_json::from_str::<InstanceConfig>(&data)
{
config.name = new_name.to_string(); config.name = new_name.to_string();
if let Ok(json) = serde_json::to_string_pretty(&config) { if let Ok(json) = serde_json::to_string_pretty(&config) {
let _ = std::fs::write(&config_path, json); let _ = std::fs::write(&config_path, json);
+9 -3
View File
@@ -10,8 +10,14 @@ pub mod manager;
pub mod models; pub mod models;
pub mod screenshots; pub mod screenshots;
pub use content::{scan_mods, toggle_entry, ContentEntry, scan_resource_packs, scan_shaders, scan_worlds}; 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,
};
pub use launch::LaunchError; pub use launch::LaunchError;
pub use loader::{get_installer, GameVersion, ModLoaderInstaller, VanillaInstaller}; pub use loader::{GameVersion, ModLoaderInstaller, VanillaInstaller, get_installer};
pub use manager::{InstanceError, InstanceManager}; pub use manager::{InstanceError, InstanceManager};
pub use models::{normalize_memory_value, InstanceConfig, ModLoader}; pub use models::{InstanceConfig, ModLoader, normalize_memory_value};
+1 -3
View File
@@ -56,9 +56,7 @@ pub fn normalize_memory_value(raw: &str) -> Option<String> {
} }
let (digits, suffix) = match trimmed.chars().last() { let (digits, suffix) = match trimmed.chars().last() {
Some(c) if c.is_ascii_alphabetic() => { Some(c) if c.is_ascii_alphabetic() => (&trimmed[..trimmed.len() - c.len_utf8()], Some(c)),
(&trimmed[..trimmed.len() - c.len_utf8()], Some(c))
}
Some(_) => (trimmed, None), Some(_) => (trimmed, None),
None => return None, None => return None,
}; };
+4 -2
View File
@@ -76,9 +76,11 @@ mod tests {
} }
let lines = get_all(name); let lines = get_all(name);
assert_eq!(lines.len(), MAX_LINES); assert_eq!(lines.len(), MAX_LINES);
assert!(lines assert!(
lines
.last() .last()
.unwrap() .unwrap()
.contains(&format!("{}", MAX_LINES + 99))); .contains(&format!("{}", MAX_LINES + 99))
);
} }
} }
+1 -2
View File
@@ -6,7 +6,7 @@ use std::path::Path;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::instance::loader::GameVersion; use crate::instance::loader::GameVersion;
use crate::net::{download_file, HttpClient, NetError}; use crate::net::{HttpClient, NetError, download_file};
use crate::tui::progress::set_sub_action; use crate::tui::progress::set_sub_action;
const FABRIC_META_BASE: &str = "https://meta.fabricmc.net/v2"; const FABRIC_META_BASE: &str = "https://meta.fabricmc.net/v2";
@@ -152,5 +152,4 @@ mod tests {
Err(e) => panic!("fetch_fabric_game_versions failed: {}", e), Err(e) => panic!("fetch_fabric_game_versions failed: {}", e),
} }
} }
} }
+20 -23
View File
@@ -87,10 +87,7 @@ pub async fn download_forge_installer(
let mut last_err = None; let mut last_err = None;
for slug in &slugs { for slug in &slugs {
let url = format!( let url = format!("{}/{slug}/forge-{slug}-installer.jar", FORGE_MAVEN_BASE,);
"{}/{slug}/forge-{slug}-installer.jar",
FORGE_MAVEN_BASE,
);
match download_file(client, &url, dest, |downloaded, total| { match download_file(client, &url, dest, |downloaded, total| {
crate::tui::progress::set_progress(downloaded, total); crate::tui::progress::set_progress(downloaded, total);
}) })
@@ -179,25 +176,23 @@ pub(crate) async fn install_forge_from_profile(
set_action("Installing legacy Forge from profile..."); set_action("Installing legacy Forge from profile...");
let file = std::fs::File::open(installer_path)?; let file = std::fs::File::open(installer_path)?;
let mut archive = zip::ZipArchive::new(file).map_err(|e| { let mut archive = zip::ZipArchive::new(file)
NetError::Parse(format!("Failed to open installer as ZIP: {e}")) .map_err(|e| NetError::Parse(format!("Failed to open installer as ZIP: {e}")))?;
})?;
let profile_data: serde_json::Value = { let profile_data: serde_json::Value = {
let entry = archive.by_name("install_profile.json").map_err(|e| { let entry = archive.by_name("install_profile.json").map_err(|e| {
NetError::Parse(format!("install_profile.json not found in installer: {e}")) NetError::Parse(format!("install_profile.json not found in installer: {e}"))
})?; })?;
serde_json::from_reader(entry).map_err(|e| { serde_json::from_reader(entry)
NetError::Parse(format!("Failed to parse install_profile.json: {e}")) .map_err(|e| NetError::Parse(format!("Failed to parse install_profile.json: {e}")))?
})?
}; };
let version_info = profile_data.get("versionInfo").ok_or_else(|| { let version_info = profile_data
NetError::Parse("install_profile.json missing versionInfo".into()) .get("versionInfo")
})?; .ok_or_else(|| NetError::Parse("install_profile.json missing versionInfo".into()))?;
let install_info = profile_data.get("install").ok_or_else(|| { let install_info = profile_data
NetError::Parse("install_profile.json missing install section".into()) .get("install")
})?; .ok_or_else(|| NetError::Parse("install_profile.json missing install section".into()))?;
let main_class = version_info let main_class = version_info
.get("mainClass") .get("mainClass")
@@ -221,9 +216,11 @@ pub(crate) async fn install_forge_from_profile(
.ok_or_else(|| NetError::Parse("missing install.path".into()))?; .ok_or_else(|| NetError::Parse("missing install.path".into()))?;
// extract the universal jar to the correct maven location // extract the universal jar to the correct maven location
let universal_maven_path = crate::net::maven_coord_to_path(install_path_coord) let universal_maven_path =
.ok_or_else(|| { crate::net::maven_coord_to_path(install_path_coord).ok_or_else(|| {
NetError::Parse(format!("Invalid maven coord in install.path: {install_path_coord}")) NetError::Parse(format!(
"Invalid maven coord in install.path: {install_path_coord}"
))
})?; })?;
set_sub_action("Extracting universal JAR..."); set_sub_action("Extracting universal JAR...");
@@ -234,7 +231,9 @@ pub(crate) async fn install_forge_from_profile(
{ {
let mut entry = archive.by_name(file_path).map_err(|e| { let mut entry = archive.by_name(file_path).map_err(|e| {
NetError::Parse(format!("Universal JAR '{file_path}' not found in installer: {e}")) NetError::Parse(format!(
"Universal JAR '{file_path}' not found in installer: {e}"
))
})?; })?;
let mut buf = Vec::new(); let mut buf = Vec::new();
entry.read_to_end(&mut buf)?; entry.read_to_end(&mut buf)?;
@@ -252,9 +251,7 @@ pub(crate) async fn install_forge_from_profile(
let maven_path = match crate::net::maven_coord_to_path(name) { let maven_path = match crate::net::maven_coord_to_path(name) {
Some(p) => p, Some(p) => p,
None => { None => {
return Err(NetError::Parse(format!( return Err(NetError::Parse(format!("Invalid Maven coordinate: {name}")));
"Invalid Maven coordinate: {name}"
)));
} }
}; };
+6 -1
View File
@@ -90,7 +90,12 @@ pub async fn download_file(
for attempt in 0..=MAX_RETRIES { for attempt in 0..=MAX_RETRIES {
if attempt > 0 { if attempt > 0 {
let delay = RETRY_BASE_DELAY_MS * 2u64.pow(attempt - 1); let delay = RETRY_BASE_DELAY_MS * 2u64.pow(attempt - 1);
tracing::warn!("retrying download (attempt {}/{}): {}", attempt + 1, MAX_RETRIES + 1, url); tracing::warn!(
"retrying download (attempt {}/{}): {}",
attempt + 1,
MAX_RETRIES + 1,
url
);
tokio::time::sleep(std::time::Duration::from_millis(delay)).await; tokio::time::sleep(std::time::Duration::from_millis(delay)).await;
} }
+9 -3
View File
@@ -55,7 +55,9 @@ use crate::instance::models::ModLoader;
// mrpack dependencies use keys like "fabric-loader", "forge", etc. // mrpack dependencies use keys like "fabric-loader", "forge", etc.
// checks in priority order and returns the first match. // checks in priority order and returns the first match.
pub fn loader_from_dependencies(deps: &HashMap<String, String>) -> (Option<ModLoader>, Option<String>) { pub fn loader_from_dependencies(
deps: &HashMap<String, String>,
) -> (Option<ModLoader>, Option<String>) {
let loaders = [ let loaders = [
("fabric-loader", ModLoader::Fabric), ("fabric-loader", ModLoader::Fabric),
("forge", ModLoader::Forge), ("forge", ModLoader::Forge),
@@ -108,7 +110,8 @@ pub async fn fetch_versions(
) -> Result<Vec<VersionInfo>, crate::net::NetError> { ) -> Result<Vec<VersionInfo>, crate::net::NetError> {
let url = format!( let url = format!(
"{}/project/{}/version?loaders=[\"fabric\",\"forge\",\"neoforge\",\"quilt\"]", "{}/project/{}/version?loaders=[\"fabric\",\"forge\",\"neoforge\",\"quilt\"]",
API_BASE, url_encode(slug_or_id) API_BASE,
url_encode(slug_or_id)
); );
client.get_json(&url).await client.get_json(&url).await
} }
@@ -187,7 +190,10 @@ mod tests {
fn game_version_from_deps() { fn game_version_from_deps() {
let mut deps = HashMap::new(); let mut deps = HashMap::new();
deps.insert("minecraft".to_string(), "1.21.4".to_string()); deps.insert("minecraft".to_string(), "1.21.4".to_string());
assert_eq!(game_version_from_dependencies(&deps), Some("1.21.4".to_string())); assert_eq!(
game_version_from_dependencies(&deps),
Some("1.21.4".to_string())
);
} }
#[test] #[test]
+2 -1
View File
@@ -78,7 +78,8 @@ pub fn register_kill(name: &str, tx: tokio::sync::oneshot::Sender<()>) {
pub fn send_kill(name: &str) -> bool { pub fn send_kill(name: &str) -> bool {
if let Ok(mut map) = KILL_SENDERS.lock() if let Ok(mut map) = KILL_SENDERS.lock()
&& let Some(tx) = map.remove(name) { && let Some(tx) = map.remove(name)
{
let _ = tx.send(()); let _ = tx.send(());
return true; return true;
} }
+8 -8
View File
@@ -3,9 +3,9 @@ use crossterm::event::{self, Event};
use ratatui::crossterm::event::KeyEventKind; use ratatui::crossterm::event::KeyEventKind;
use std::time::Duration; use std::time::Duration;
use super::Tui;
use super::app::{App, PENDING_INSTANCES}; use super::app::{App, PENDING_INSTANCES};
use super::widgets::{self, popups::import_modpack, popups::new_instance}; use super::widgets::{self, popups::import_modpack, popups::new_instance};
use super::Tui;
use crate::instance::InstanceManager; use crate::instance::InstanceManager;
use crate::tui::error_buffer; use crate::tui::error_buffer;
use crate::tui::progress; use crate::tui::progress;
@@ -31,13 +31,13 @@ impl App {
self.drain_pending_instances(); self.drain_pending_instances();
self.drain_pending_last_played(); self.drain_pending_last_played();
self.mods_state.drain_pending(); self.mods_state.drain_pending();
self.mods_state.try_rescan(); self.mods_state.drain_watcher();
self.resource_packs_state.drain_pending(); self.resource_packs_state.drain_pending();
self.resource_packs_state.try_rescan(); self.resource_packs_state.drain_watcher();
self.shaders_state.drain_pending(); self.shaders_state.drain_pending();
self.shaders_state.try_rescan(); self.shaders_state.drain_watcher();
self.worlds_state.drain_pending(); self.worlds_state.drain_pending();
self.worlds_state.try_rescan(); self.worlds_state.drain_watcher();
self.logs_state.drain_pending(); self.logs_state.drain_pending();
self.logs_state.try_rescan(); self.logs_state.try_rescan();
self.account_state.drain_auth_result(); self.account_state.drain_auth_result();
@@ -153,10 +153,10 @@ impl App {
// editor fights with ratatui for the terminal. GUI editors just get spawned detached. // editor fights with ratatui for the terminal. GUI editors just get spawned detached.
fn run_editor(terminal: &mut ratatui::DefaultTerminal, path: &std::path::Path) -> bool { fn run_editor(terminal: &mut ratatui::DefaultTerminal, path: &std::path::Path) -> bool {
use ratatui::crossterm::{ use ratatui::crossterm::{
terminal::{
disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
},
ExecutableCommand, ExecutableCommand,
terminal::{
EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
},
}; };
use std::io::stdout; use std::io::stdout;
+12 -4
View File
@@ -6,7 +6,9 @@
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use super::app::{App, FocusedArea}; use super::app::{App, FocusedArea};
use super::widgets::{self, popups::confirm as confirm_popup, popups::import_modpack, popups::new_instance, WidgetKey}; use super::widgets::{
self, WidgetKey, popups::confirm as confirm_popup, popups::import_modpack, popups::new_instance,
};
use crate::tui::error_buffer; use crate::tui::error_buffer;
impl App { impl App {
@@ -15,6 +17,9 @@ impl App {
if self.focused == FocusedArea::OverviewExpanded { if self.focused == FocusedArea::OverviewExpanded {
if self.log_overlay_search.active { if self.log_overlay_search.active {
match key_event.code { match key_event.code {
KeyCode::Enter => {
self.log_overlay_search.confirm();
}
KeyCode::Esc => { KeyCode::Esc => {
self.log_overlay_search.deactivate(); self.log_overlay_search.deactivate();
} }
@@ -103,7 +108,8 @@ impl App {
return Ok(()); return Ok(());
} }
} else if self.content_tab == widgets::content::ContentTab::Worlds { } else if self.content_tab == widgets::content::ContentTab::Worlds {
if widgets::content::list::handle_key_no_toggle(&key_event, &mut self.worlds_state) { if widgets::content::list::handle_key_no_toggle(&key_event, &mut self.worlds_state)
{
return Ok(()); return Ok(());
} }
} else { } else {
@@ -116,7 +122,8 @@ impl App {
_ => None, _ => None,
}; };
if let Some(state) = state if let Some(state) = state
&& widgets::content::list::handle_key(&key_event, state) { && widgets::content::list::handle_key(&key_event, state)
{
return Ok(()); return Ok(());
} }
} }
@@ -178,7 +185,8 @@ impl App {
import_modpack::handle_key(&key_event, &mut self.instances_state); import_modpack::handle_key(&key_event, &mut self.instances_state);
} }
_ => { _ => {
if self.focused == FocusedArea::Instances && self.instances_state.renaming.is_some() { if self.focused == FocusedArea::Instances && self.instances_state.renaming.is_some()
{
match key_event.code { match key_event.code {
KeyCode::Enter => { KeyCode::Enter => {
let new_name = self.instances_state.renaming.take().unwrap_or_default(); let new_name = self.instances_state.renaming.take().unwrap_or_default();
+4 -4
View File
@@ -34,10 +34,10 @@ fn push_app_log(line: String) {
} }
} }
// returns a WorkerGuard that must be held alive for the duration of the // returns a WorkerGuard that must be held alive for the duration of the
// program, otherwise the file logging thread gets dropped immediately. // program, otherwise the file logging thread gets dropped immediately.
// yes, you will spend 30 minutes debugging "why aren't my logs writing" // yes, you will spend 30 minutes debugging "why aren't my logs writing"
// before you remember this. ask me how i know. // before you remember this. ask me how i know.
pub fn init() -> WorkerGuard { pub fn init() -> WorkerGuard {
let log_dir = match dirs_next::cache_dir() { let log_dir = match dirs_next::cache_dir() {
Some(d) => d.join("mcl"), Some(d) => d.join("mcl"),
+12
View File
@@ -12,6 +12,18 @@ pub mod widgets;
pub type Tui = ratatui::DefaultTerminal; pub type Tui = ratatui::DefaultTerminal;
pub async fn show() -> color_eyre::Result<()> { pub async fn show() -> color_eyre::Result<()> {
// restore the terminal before printing a panic. without this, a panic
// leaves raw mode + alternate screen active and looks like a freeze
let default_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
let _ = crossterm::execute!(
std::io::stdout(),
crossterm::event::PopKeyboardEnhancementFlags
);
ratatui::restore();
default_hook(info);
}));
let mut terminal = ratatui::init(); let mut terminal = ratatui::init();
// opt into enhanced keyboard protocol to distinguish key press vs release // opt into enhanced keyboard protocol to distinguish key press vs release
+34 -15
View File
@@ -4,22 +4,24 @@
// popups and error toasts render on top of everything. // popups and error toasts render on top of everything.
use ratatui::{ use ratatui::{
layout::{Constraint, Direction, Layout},
Frame, Frame,
layout::{Constraint, Direction, Layout},
}; };
use tachyonfx::{fx, EffectRenderer, Interpolation, Motion}; use tachyonfx::{EffectRenderer, Interpolation, Motion, fx};
use super::app::{App, ErrorEffectState, FocusedArea}; use super::app::{App, ErrorEffectState, FocusedArea};
use super::widgets::{self, popups::confirm as confirm_popup, popups::import_modpack, popups::new_instance}; use super::widgets::{
self, popups::confirm as confirm_popup, popups::import_modpack, popups::new_instance,
};
use crate::tui::error_buffer; use crate::tui::error_buffer;
use crate::tui::widgets::popups::confirm::{confirm_popup_area, ConfirmPopup}; use crate::tui::widgets::popups::confirm::{ConfirmPopup, confirm_popup_area};
use crate::tui::widgets::popups::error::{popup_area, ErrorPopup}; use crate::tui::widgets::popups::error::{ErrorPopup, popup_area};
impl App { impl App {
pub(super) fn render_frame(&mut self, frame: &mut Frame) { pub(super) fn render_frame(&mut self, frame: &mut Frame) {
use crate::config::theme::THEME; use crate::config::theme::THEME;
use ratatui::widgets::Block;
use ratatui::style::Style; use ratatui::style::Style;
use ratatui::widgets::Block;
let theme = THEME.as_ref(); let theme = THEME.as_ref();
frame.render_widget( frame.render_widget(
@@ -29,10 +31,7 @@ impl App {
let chunks = Layout::default() let chunks = Layout::default()
.direction(Direction::Horizontal) .direction(Direction::Horizontal)
.constraints([ .constraints([Constraint::Percentage(20), Constraint::Percentage(80)])
Constraint::Percentage(20),
Constraint::Percentage(80),
])
.split(frame.area()); .split(frame.area());
widgets::instances::render(frame, chunks[0], self.focused, &mut self.instances_state); widgets::instances::render(frame, chunks[0], self.focused, &mut self.instances_state);
@@ -136,7 +135,7 @@ impl App {
// full-screen log viewer with search highlighting and auto-scroll. // full-screen log viewer with search highlighting and auto-scroll.
// auto-sticks to the bottom unless the user scrolled up manually // auto-sticks to the bottom unless the user scrolled up manually
fn render_log_overlay(&mut self, frame: &mut Frame) { fn render_log_overlay(&mut self, frame: &mut Frame) {
use crate::config::theme::{THEME, BORDER_STYLE}; use crate::config::theme::{BORDER_STYLE, THEME};
use crate::tui::logging::get_app_logs; use crate::tui::logging::get_app_logs;
use ratatui::{ use ratatui::{
layout::{Alignment, Margin}, layout::{Alignment, Margin},
@@ -247,7 +246,13 @@ impl App {
for event in events { for event in events {
self.error_effects.entry(event.id).or_insert_with(|| { self.error_effects.entry(event.id).or_insert_with(|| {
ErrorEffectState::SlidingIn( ErrorEffectState::SlidingIn(
fx::slide_in(Motion::RightToLeft, 4, 0, bg, (250, Interpolation::CubicOut)), fx::slide_in(
Motion::RightToLeft,
4,
0,
bg,
(250, Interpolation::CubicOut),
),
std::time::Instant::now(), std::time::Instant::now(),
) )
}); });
@@ -278,7 +283,13 @@ impl App {
.or_insert(ErrorEffectState::Idle); .or_insert(ErrorEffectState::Idle);
if !matches!(entry, ErrorEffectState::FadingOut(..)) { if !matches!(entry, ErrorEffectState::FadingOut(..)) {
*entry = ErrorEffectState::FadingOut( *entry = ErrorEffectState::FadingOut(
fx::slide_out(Motion::LeftToRight, 4, 0, bg, (fly_out_ms as u32, Interpolation::CubicIn)), fx::slide_out(
Motion::LeftToRight,
4,
0,
bg,
(fly_out_ms as u32, Interpolation::CubicIn),
),
std::time::Instant::now(), std::time::Instant::now(),
); );
} }
@@ -289,7 +300,11 @@ impl App {
ErrorEffectState::SlidingIn(effect, started) => { ErrorEffectState::SlidingIn(effect, started) => {
let dt = started.elapsed().as_millis() as u32; let dt = started.elapsed().as_millis() as u32;
if effect.running() { if effect.running() {
frame.render_effect(effect, area, tachyonfx::Duration::from_millis(dt.min(32))); frame.render_effect(
effect,
area,
tachyonfx::Duration::from_millis(dt.min(32)),
);
*started = std::time::Instant::now(); *started = std::time::Instant::now();
} else { } else {
*effect_state = ErrorEffectState::Idle; *effect_state = ErrorEffectState::Idle;
@@ -299,7 +314,11 @@ impl App {
ErrorEffectState::FadingOut(effect, started) => { ErrorEffectState::FadingOut(effect, started) => {
let dt = started.elapsed().as_millis() as u32; let dt = started.elapsed().as_millis() as u32;
if effect.running() { if effect.running() {
frame.render_effect(effect, area, tachyonfx::Duration::from_millis(dt.min(32))); frame.render_effect(
effect,
area,
tachyonfx::Duration::from_millis(dt.min(32)),
);
*started = std::time::Instant::now(); *started = std::time::Instant::now();
} }
} }
+19 -28
View File
@@ -6,17 +6,17 @@ use std::sync::{Arc, Mutex};
use crossterm::event::{KeyCode, KeyEvent}; use crossterm::event::{KeyCode, KeyEvent};
use ratatui::{ use ratatui::{
Frame,
layout::Rect, layout::Rect,
style::{Modifier, Style}, style::{Modifier, Style},
text::{Line, Span}, text::{Line, Span},
widgets::{Block, Borders, Paragraph, Widget}, widgets::{Block, Borders, Paragraph, Widget},
Frame,
}; };
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView}; use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
use crate::auth::{self, AccountStore, AccountType, AuthResult, DeviceCodeInfo}; use crate::auth::{self, AccountStore, AccountType, AuthResult, DeviceCodeInfo};
use crate::config::theme::{BORDER_STYLE, THEME};
use crate::tui::app::FocusedArea; use crate::tui::app::FocusedArea;
use crate::config::theme::{THEME, BORDER_STYLE};
use super::styled_title; use super::styled_title;
@@ -59,11 +59,10 @@ impl AccountState {
// can't block on it because the TUI needs to keep rendering // can't block on it because the TUI needs to keep rendering
pub fn drain_auth_result(&mut self) { pub fn drain_auth_result(&mut self) {
if let AddMode::DeviceCodeWaiting { pending, .. } = &self.add_mode { if let AddMode::DeviceCodeWaiting { pending, .. } = &self.add_mode {
let result = match pending.lock() { Ok(mut slot) => { let result = match pending.lock() {
slot.take() Ok(mut slot) => slot.take(),
} _ => { _ => None,
None };
}};
if let Some(result) = result { if let Some(result) = result {
match result { match result {
@@ -211,7 +210,8 @@ pub fn drain_device_code(state: &mut AccountState) {
if let AddMode::DeviceCodeWaiting { info, .. } = &mut state.add_mode if let AddMode::DeviceCodeWaiting { info, .. } = &mut state.add_mode
&& info.user_code.is_empty() && info.user_code.is_empty()
&& let Ok(mut slot) = auth::DEVICE_CODE_DISPLAY.lock() && let Ok(mut slot) = auth::DEVICE_CODE_DISPLAY.lock()
&& let Some(dc_info) = slot.take() { && let Some(dc_info) = slot.take()
{
info.user_code = dc_info.user_code; info.user_code = dc_info.user_code;
info.verification_uri = dc_info.verification_uri; info.verification_uri = dc_info.verification_uri;
} }
@@ -246,8 +246,7 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut A
if state.store.accounts.is_empty() { if state.store.accounts.is_empty() {
frame.render_widget( frame.render_widget(
Paragraph::new("No accounts.") Paragraph::new("No accounts.").style(Style::default().fg(theme.text_dim())),
.style(Style::default().fg(theme.text_dim())),
inner, inner,
); );
} else { } else {
@@ -299,7 +298,9 @@ fn render_account_list(
let active_marker = if *is_active { "\u{25b8} " } else { " " }; let active_marker = if *is_active { "\u{25b8} " } else { " " };
let style = if show_selected { let style = if show_selected {
Style::default().fg(theme.accent()).add_modifier(Modifier::BOLD) Style::default()
.fg(theme.accent())
.add_modifier(Modifier::BOLD)
} else if *is_active { } else if *is_active {
Style::default() Style::default()
.fg(theme.text()) .fg(theme.text())
@@ -315,7 +316,9 @@ fn render_account_list(
if *acc_type == AccountType::Offline { if *acc_type == AccountType::Offline {
let offline_style = if show_selected { let offline_style = if show_selected {
Style::default().fg(theme.accent()).add_modifier(Modifier::BOLD) Style::default()
.fg(theme.accent())
.add_modifier(Modifier::BOLD)
} else { } else {
Style::default().fg(theme.text_dim()) Style::default().fg(theme.text_dim())
}; };
@@ -372,10 +375,7 @@ fn render_choose_popup(frame: &mut Frame) {
.fg(accent_color) .fg(accent_color)
.add_modifier(Modifier::BOLD), .add_modifier(Modifier::BOLD),
), ),
Span::styled( Span::styled("Microsoft Account", Style::default().fg(text_color)),
"Microsoft Account",
Style::default().fg(text_color),
),
]), ]),
Line::from(vec![ Line::from(vec![
Span::styled( Span::styled(
@@ -384,10 +384,7 @@ fn render_choose_popup(frame: &mut Frame) {
.fg(accent_color) .fg(accent_color)
.add_modifier(Modifier::BOLD), .add_modifier(Modifier::BOLD),
), ),
Span::styled( Span::styled("Offline Account", Style::default().fg(text_color)),
"Offline Account",
Style::default().fg(text_color),
),
]), ]),
]; ];
Paragraph::new(text).render(inner, buf); Paragraph::new(text).render(inner, buf);
@@ -422,10 +419,7 @@ fn render_offline_popup(frame: &mut Frame, name: &str) {
content: Box::new(move |inner, buf| { content: Box::new(move |inner, buf| {
let line = if name.is_empty() { let line = if name.is_empty() {
Line::from(vec![ Line::from(vec![
Span::styled( Span::styled("Username...", Style::default().fg(dim_color)),
"Username...",
Style::default().fg(dim_color),
),
Span::styled( Span::styled(
"\u{2588}", "\u{2588}",
Style::default() Style::default()
@@ -534,10 +528,7 @@ fn render_device_code_popup(frame: &mut Frame, info: &DeviceCodeInfo) {
)), )),
Line::from(""), Line::from(""),
Line::from(vec![ Line::from(vec![
Span::styled( Span::styled("Enter code: ", Style::default().fg(dim_color)),
"Enter code: ",
Style::default().fg(dim_color),
),
Span::styled( Span::styled(
code.as_str(), code.as_str(),
Style::default() Style::default()
+332 -73
View File
@@ -6,7 +6,7 @@
use std::collections::HashMap; use std::collections::HashMap;
use std::path::Path; use std::path::Path;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex, mpsc};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::{ use ratatui::{
@@ -21,14 +21,21 @@ use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
use crate::config::theme::THEME; use crate::config::theme::THEME;
use crate::instance::content::mods::{ContentEntry, IconCell}; use crate::instance::content::mods::{ContentEntry, IconCell};
type PendingContent = Arc<Mutex<Option<(String, Vec<ContentEntry>)>>>;
type SnapshotRow = (String, String, bool, Option<Vec<Vec<IconCell>>>); type SnapshotRow = (String, String, bool, Option<Vec<Vec<IconCell>>>);
type ScanOneFn = fn(&Path, &str, bool) -> ContentEntry;
struct CachedList { struct CachedList {
entries: Vec<ContentEntry>, entries: Vec<ContentEntry>,
selected: Option<usize>, selected: Option<usize>,
} }
// result from the notify-triggered background diff
struct WatcherDiff {
toggled: Vec<(String, bool, std::path::PathBuf)>,
removed: Vec<String>,
added: Vec<ContentEntry>,
}
pub struct ContentListState { pub struct ContentListState {
pub entries: Vec<ContentEntry>, pub entries: Vec<ContentEntry>,
pub list_state: TuiListState, pub list_state: TuiListState,
@@ -37,10 +44,16 @@ pub struct ContentListState {
pub loading: bool, pub loading: bool,
pub search: crate::tui::widgets::search::SearchState, pub search: crate::tui::widgets::search::SearchState,
cache: HashMap<String, CachedList>, cache: HashMap<String, CachedList>,
pending: PendingContent, // streaming: individual entries arrive here during initial load
check_counter: u16, stream_rx: Option<mpsc::Receiver<ContentEntry>>,
// file watcher: notify callback spawns background work,
// precomputed diff lands here for the UI to pick up
watcher_diff: Arc<Mutex<Option<WatcherDiff>>>,
_watcher: Option<notify::RecommendedWatcher>,
watched_dir: Option<std::path::PathBuf>, watched_dir: Option<std::path::PathBuf>,
last_dir_mtime: Option<std::time::SystemTime>, // stored for the watcher to scan individual new files
scan_one_fn: Option<ScanOneFn>,
content_ext: Option<&'static str>,
} }
impl Default for ContentListState { impl Default for ContentListState {
@@ -53,41 +66,229 @@ impl Default for ContentListState {
loading: false, loading: false,
search: crate::tui::widgets::search::SearchState::default(), search: crate::tui::widgets::search::SearchState::default(),
cache: HashMap::new(), cache: HashMap::new(),
pending: Arc::new(Mutex::new(None)), stream_rx: None,
check_counter: 0, watcher_diff: Arc::new(Mutex::new(None)),
_watcher: None,
watched_dir: None, watched_dir: None,
last_dir_mtime: None, scan_one_fn: None,
content_ext: None,
} }
} }
} }
impl ContentListState { impl ContentListState {
// poll the content directory for changes every ~120 ticks. // drain streaming entries from the initial load. each entry arrives
// if the dir's mtime changed, invalidate the cache to pick up // individually and is inserted in sorted position for a smooth fill-in
// mods/packs the user dropped in from outside the launcher pub fn drain_pending(&mut self) {
pub fn try_rescan(&mut self) { let Some(rx) = &self.stream_rx else {
self.check_counter = self.check_counter.wrapping_add(1);
if !self.check_counter.is_multiple_of(120) {
return;
}
let Some(dir) = &self.watched_dir else {
return; return;
}; };
let current_mtime = std::fs::metadata(dir).ok().and_then(|m| m.modified().ok()); let mut received = false;
let mut finished = false;
if current_mtime != self.last_dir_mtime { loop {
self.last_dir_mtime = current_mtime; match rx.try_recv() {
if let Some(name) = &self.loaded_for { Ok(entry) => {
self.cache.remove(name); received = true;
self.loaded_for = None; let pos = self
.entries
.binary_search_by(|e| {
e.name.to_lowercase().cmp(&entry.name.to_lowercase())
})
.unwrap_or_else(|i| i);
self.entries.insert(pos, entry);
}
Err(mpsc::TryRecvError::Empty) => break,
Err(mpsc::TryRecvError::Disconnected) => {
self.stream_rx = None;
finished = true;
break;
} }
} }
} }
if received || finished {
self.loading = false;
if self.list_state.selected.is_none() && !self.entries.is_empty() {
self.list_state.selected = Some(0);
}
self.update_scrollbar();
}
}
// pick up the precomputed diff from the notify watcher callback.
// skip while streaming is in progress to avoid duplicate entries.
pub fn drain_watcher(&mut self) {
if self.stream_rx.is_some() {
return;
}
let diff = match self.watcher_diff.lock() {
Ok(mut slot) => slot.take(),
_ => None,
};
let Some(diff) = diff else {
return;
};
// apply toggles (enabled/path changes)
for (stem, enabled, path) in &diff.toggled {
if let Some(entry) = self.entries.iter_mut().find(|e| &e.file_stem == stem) {
entry.enabled = *enabled;
entry.path = path.clone();
}
}
// apply removals
if !diff.removed.is_empty() {
self.entries
.retain(|e| !diff.removed.contains(&e.file_stem));
}
// insert new entries in sorted position
for entry in diff.added {
let pos = self
.entries
.binary_search_by(|e| e.name.to_lowercase().cmp(&entry.name.to_lowercase()))
.unwrap_or_else(|i| i);
self.entries.insert(pos, entry);
}
// clamp selected
if let Some(sel) = self.list_state.selected {
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.update_scrollbar();
}
// starts a notify file watcher on the given directory. changes trigger
// a background diff that lands in watcher_diff for drain_watcher to apply.
pub fn watch_dir(&mut self, dir: std::path::PathBuf) { pub fn watch_dir(&mut self, dir: std::path::PathBuf) {
self.last_dir_mtime = std::fs::metadata(&dir).ok().and_then(|m| m.modified().ok()); use notify::{RecursiveMode, Watcher};
use std::sync::atomic::{AtomicBool, Ordering};
// drop previous watcher
self._watcher = None;
let watcher_diff = self.watcher_diff.clone();
let ext: &'static str = self.content_ext.unwrap_or(".jar");
let scan_one = self.scan_one_fn;
let dirty = Arc::new(AtomicBool::new(false));
let running = Arc::new(AtomicBool::new(false));
let dirty_cb = dirty.clone();
let running_cb = running.clone();
// initialize known stems from the current directory state so existing
// files are not treated as "new" on the first notify event
let known_stems = Arc::new(Mutex::new(read_dir_stems(&dir, ext)));
let watch_dir = dir.clone();
let watcher = notify::recommended_watcher(move |res: Result<notify::Event, _>| {
if res.is_err() {
return;
}
// mark dirty. if a thread is already running it will loop to
// pick up the change after its current diff
dirty_cb.store(true, Ordering::Relaxed);
if running_cb.swap(true, Ordering::Relaxed) {
return;
}
let dir = watch_dir.clone();
let diff_slot = watcher_diff.clone();
let dirty = dirty_cb.clone();
let running = running_cb.clone();
let known = known_stems.clone();
std::thread::spawn(move || {
// always clear `running` even if we panic
struct ResetOnDrop(Arc<AtomicBool>);
impl Drop for ResetOnDrop {
fn drop(&mut self) {
self.0.store(false, Ordering::Relaxed);
}
}
let _guard = ResetOnDrop(running);
loop {
dirty.store(false, Ordering::Relaxed);
std::thread::sleep(std::time::Duration::from_millis(100));
let result = (|| {
let on_disk = read_dir_stems(&dir, ext);
let mut known_map = known.lock().ok()?;
let mut toggled = Vec::new();
let mut removed = Vec::new();
let mut added = Vec::new();
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(),
));
}
} else {
removed.push(stem.clone());
}
}
for (stem, (path, enabled)) in &on_disk {
if !known_map.contains_key(stem)
&& let Some(scan_one) = scan_one
{
added.push(scan_one(path, stem, *enabled));
}
}
*known_map = on_disk;
Some(WatcherDiff {
toggled,
removed,
added,
})
})();
if let Some(diff) = result
&& let Ok(mut slot) = diff_slot.lock()
{
*slot = Some(diff);
}
if !dirty.load(Ordering::Relaxed) {
break;
}
}
});
});
match watcher {
Ok(mut w) => {
if let Err(e) = w.watch(&dir, RecursiveMode::NonRecursive) {
tracing::warn!("Failed to watch {}: {e}", dir.display());
} else {
self._watcher = Some(w);
}
}
Err(e) => {
tracing::warn!("Failed to create file watcher: {e}");
}
}
self.watched_dir = Some(dir); self.watched_dir = Some(dir);
} }
@@ -103,11 +304,19 @@ impl ContentListState {
impl ContentListState { impl ContentListState {
// saves current entries to cache before loading new ones, and restores // saves current entries to cache before loading new ones, and restores
// from cache if this instance was seen before (avoids re-scanning) // from cache if this instance was seen before (avoids re-scanning).
pub fn start_load<F>(&mut self, instances_dir: &Path, instance_name: &str, scan_fn: F) // content_dir is the actual directory to scan (e.g. .minecraft/mods).
where pub fn start_load(
F: FnOnce(&Path, &str) -> Vec<ContentEntry> + Send + 'static, &mut self,
{ content_dir: &Path,
instance_name: &str,
scan_one_fn: ScanOneFn,
ext: &'static str,
) {
self.scan_one_fn = Some(scan_one_fn);
self.content_ext = Some(ext);
// save current entries to cache
if let Some(prev) = self.loaded_for.take() if let Some(prev) = self.loaded_for.take()
&& !self.entries.is_empty() && !self.entries.is_empty()
{ {
@@ -120,66 +329,62 @@ impl ContentListState {
); );
} }
// try cache first
if let Some(cached) = self.cache.remove(instance_name) { if let Some(cached) = self.cache.remove(instance_name) {
self.entries = cached.entries; self.entries = cached.entries;
self.list_state.selected = cached.selected; self.list_state.selected = cached.selected;
self.loading = false; self.loading = false;
} else { self.stream_rx = None;
self.loaded_for = Some(instance_name.to_string());
self.update_scrollbar();
return;
}
// no cache, stream entries one by one as each file is scanned
self.entries.clear(); self.entries.clear();
self.list_state = TuiListState::default(); self.list_state = TuiListState::default();
self.loading = true; self.loading = true;
}
self.loaded_for = Some(instance_name.to_string()); self.loaded_for = Some(instance_name.to_string());
self.update_scrollbar(); self.update_scrollbar();
let dir = instances_dir.to_path_buf(); let (tx, rx) = mpsc::channel();
let tag = instance_name.to_string(); self.stream_rx = Some(rx);
let pending = self.pending.clone();
let dir = content_dir.to_path_buf();
tokio::spawn(async move { tokio::spawn(async move {
let scan_dir = dir.clone(); let _ = tokio::task::spawn_blocking(move || {
let scan_name = tag.clone(); let read_dir = match std::fs::read_dir(&dir) {
let entries = tokio::task::spawn_blocking(move || scan_fn(&scan_dir, &scan_name)) Ok(rd) => rd,
.await Err(_) => return,
.unwrap_or_default(); };
let disabled_ext = format!("{ext}.disabled");
if let Ok(mut slot) = pending.lock() { for dir_entry in read_dir.flatten() {
*slot = Some((tag, entries)); let path = dir_entry.path();
} let Some(fname) = path.file_name().and_then(|n| n.to_str()) else {
}); continue;
}
pub fn drain_pending(&mut self) {
let taken = match self.pending.lock() {
Ok(mut slot) => slot.take(),
_ => None,
}; };
if let Some((instance_name, entries)) = taken let (enabled, file_stem) =
&& (self.loaded_for.as_deref() == Some(&instance_name) || instance_name.is_empty()) if let Some(stem) = fname.strip_suffix(&disabled_ext) {
{ (false, stem.to_owned())
let selected_name = self } else if let Some(stem) = fname.strip_suffix(ext) {
.list_state (true, stem.to_owned())
.selected } else if path.is_dir() {
.and_then(|i| self.entries.get(i)) crate::instance::content::parse_enabled_stem_dir(fname)
.map(|e| e.name.clone());
self.entries = entries;
self.loading = false;
if !self.entries.is_empty() {
let new_index = selected_name
.and_then(|name| self.entries.iter().position(|e| e.name == name))
.or(self.list_state.selected)
.map(|i| i.min(self.entries.len().saturating_sub(1)))
.unwrap_or(0);
self.list_state.selected = Some(new_index);
} else { } else {
self.list_state.selected = None; continue;
};
let entry = scan_one_fn(&path, &file_stem, enabled);
if tx.send(entry).is_err() {
break; // receiver dropped (instance switched)
} }
self.update_scrollbar();
} }
})
.await;
});
} }
fn update_scrollbar(&mut self) { fn update_scrollbar(&mut self) {
@@ -233,6 +438,11 @@ impl ContentListState {
fn handle_search_keys(key_event: &KeyEvent, state: &mut ContentListState) -> bool { fn handle_search_keys(key_event: &KeyEvent, state: &mut ContentListState) -> bool {
if state.search.active { if state.search.active {
match key_event.code { match key_event.code {
KeyCode::Enter => {
state.search.confirm();
state.list_state.selected = Some(0);
state.update_scrollbar();
}
KeyCode::Esc => { KeyCode::Esc => {
state.search.deactivate(); state.search.deactivate();
state.list_state.selected = Some(0); state.list_state.selected = Some(0);
@@ -360,6 +570,7 @@ pub fn render(
let filtered = state.filtered_indices(); let filtered = state.filtered_indices();
if filtered.is_empty() { if filtered.is_empty() {
state.list_state.selected = None;
frame.render_widget( frame.render_widget(
Paragraph::new(empty_text).style(Style::default().fg(theme.text_dim())), Paragraph::new(empty_text).style(Style::default().fg(theme.text_dim())),
area, area,
@@ -369,6 +580,13 @@ pub fn render(
let count = filtered.len(); let count = filtered.len();
// clamp selected so the ListView builder never gets an out-of-bounds index
if let Some(sel) = state.list_state.selected
&& sel >= count
{
state.list_state.selected = Some(count.saturating_sub(1));
}
let snapshot: Vec<SnapshotRow> = filtered let snapshot: Vec<SnapshotRow> = filtered
.iter() .iter()
.map(|&i| { .map(|&i| {
@@ -656,3 +874,44 @@ fn icon_spans(icon_pixels: Option<&Vec<Vec<IconCell>>>, row: usize) -> Vec<Span<
} }
} }
} }
// 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)> {
let mut map = HashMap::new();
let Ok(read_dir) = std::fs::read_dir(dir) else {
return map;
};
let dirs_only = ext.is_empty();
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 {
continue;
};
if dirs_only {
if !path.is_dir() && !fname.ends_with(".disabled") {
continue;
}
let (enabled, stem) = crate::instance::content::parse_enabled_stem_dir(fname);
map.insert(stem, (path, enabled));
continue;
}
if let Some(stem) = fname.strip_suffix(&disabled_ext) {
map.insert(stem.to_owned(), (path, false));
} else if let Some(stem) = fname.strip_suffix(ext) {
map.insert(stem.to_owned(), (path, true));
} else if path.is_dir() {
let (enabled, stem) = crate::instance::content::parse_enabled_stem_dir(fname);
map.insert(stem, (path, enabled));
}
}
map
}
+1 -1
View File
@@ -3,5 +3,5 @@
pub mod list; pub mod list;
pub mod tabs; pub mod tabs;
pub use tabs::{ContentTab, render, title};
pub use list::{ContentListState, handle_key, handle_key_no_toggle}; pub use list::{ContentListState, handle_key, handle_key_no_toggle};
pub use tabs::{ContentTab, render, title};
+29 -31
View File
@@ -3,16 +3,16 @@
// also renders the instance name/version header with run state indicators. // also renders the instance name/version header with run state indicators.
use ratatui::{ use ratatui::{
Frame,
layout::{Alignment, Constraint, Layout, Rect}, layout::{Alignment, Constraint, Layout, Rect},
style::{Modifier, Style}, style::{Modifier, Style},
text::{Line, Span}, text::{Line, Span},
widgets::{Block, Borders, Paragraph}, widgets::{Block, Borders, Paragraph},
Frame,
}; };
use throbber_widgets_tui::{Throbber, ThrobberState}; use throbber_widgets_tui::{Throbber, ThrobberState};
use crate::config::theme::{BORDER_STYLE, THEME};
use crate::tui::app::FocusedArea; use crate::tui::app::FocusedArea;
use crate::config::theme::{THEME, BORDER_STYLE};
use crate::tui::widgets::styled_title; use crate::tui::widgets::styled_title;
@@ -200,7 +200,8 @@ pub fn render(
}; };
if let Some(kb) = kb { if let Some(kb) = kb {
let lines = crate::tui::widgets::popups::keybind_lines_wrapped(kb, area.width.saturating_sub(2)); let lines =
crate::tui::widgets::popups::keybind_lines_wrapped(kb, area.width.saturating_sub(2));
for line in lines { for line in lines {
block = block.title_bottom(line); block = block.title_bottom(line);
} }
@@ -214,12 +215,9 @@ pub fn render(
ContentTab::Mods => { ContentTab::Mods => {
if let Some(instance) = instance { if let Some(instance) = instance {
if mods_state.loaded_for.as_deref() != Some(instance.name.as_str()) { if mods_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
mods_state.start_load( let content_dir = instances_dir.join(&instance.name).join(".minecraft").join("mods");
instances_dir, mods_state.start_load(&content_dir, &instance.name, crate::instance::scan_one_mod, ".jar");
&instance.name, mods_state.watch_dir(content_dir);
crate::instance::scan_mods,
);
mods_state.watch_dir(instances_dir.join(&instance.name).join(".minecraft").join("mods"));
} }
super::list::render( super::list::render(
frame, frame,
@@ -240,12 +238,9 @@ pub fn render(
ContentTab::ResourcePacks => { ContentTab::ResourcePacks => {
if let Some(instance) = instance { if let Some(instance) = instance {
if resource_packs_state.loaded_for.as_deref() != Some(instance.name.as_str()) { if resource_packs_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
resource_packs_state.start_load( let content_dir = instances_dir.join(&instance.name).join(".minecraft").join("resourcepacks");
instances_dir, resource_packs_state.start_load(&content_dir, &instance.name, crate::instance::scan_one_resource_pack, ".zip");
&instance.name, resource_packs_state.watch_dir(content_dir);
crate::instance::scan_resource_packs,
);
resource_packs_state.watch_dir(instances_dir.join(&instance.name).join(".minecraft").join("resourcepacks"));
} }
super::list::render( super::list::render(
frame, frame,
@@ -266,12 +261,9 @@ pub fn render(
ContentTab::Shaders => { ContentTab::Shaders => {
if let Some(instance) = instance { if let Some(instance) = instance {
if shaders_state.loaded_for.as_deref() != Some(instance.name.as_str()) { if shaders_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
shaders_state.start_load( let content_dir = instances_dir.join(&instance.name).join(".minecraft").join("shaderpacks");
instances_dir, shaders_state.start_load(&content_dir, &instance.name, crate::instance::scan_one_shader, ".zip");
&instance.name, shaders_state.watch_dir(content_dir);
crate::instance::scan_shaders,
);
shaders_state.watch_dir(instances_dir.join(&instance.name).join(".minecraft").join("shaderpacks"));
} }
super::list::render( super::list::render(
frame, frame,
@@ -294,7 +286,12 @@ pub fn render(
if logs_state.loaded_for.as_deref() != Some(instance.name.as_str()) { if logs_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
logs_state.start_load(instances_dir, &instance.name); logs_state.start_load(instances_dir, &instance.name);
} }
crate::tui::widgets::logs_viewer::render(frame, content_area, logs_state, is_focused); crate::tui::widgets::logs_viewer::render(
frame,
content_area,
logs_state,
is_focused,
);
} else { } else {
frame.render_widget( frame.render_widget(
Paragraph::new("No instance selected.") Paragraph::new("No instance selected.")
@@ -308,7 +305,12 @@ pub fn render(
if screenshots_state.loaded_for.as_deref() != Some(instance.name.as_str()) { if screenshots_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
screenshots_state.start_load(instances_dir, &instance.name); screenshots_state.start_load(instances_dir, &instance.name);
} }
crate::tui::widgets::screenshots_grid::render(frame, content_area, screenshots_state, is_focused); crate::tui::widgets::screenshots_grid::render(
frame,
content_area,
screenshots_state,
is_focused,
);
} else { } else {
frame.render_widget( frame.render_widget(
Paragraph::new("No instance selected.") Paragraph::new("No instance selected.")
@@ -320,12 +322,9 @@ pub fn render(
ContentTab::Worlds => { ContentTab::Worlds => {
if let Some(instance) = instance { if let Some(instance) = instance {
if worlds_state.loaded_for.as_deref() != Some(instance.name.as_str()) { if worlds_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
worlds_state.start_load( let content_dir = instances_dir.join(&instance.name).join(".minecraft").join("saves");
instances_dir, worlds_state.start_load(&content_dir, &instance.name, crate::instance::scan_one_world, "");
&instance.name, worlds_state.watch_dir(content_dir);
crate::instance::scan_worlds,
);
worlds_state.watch_dir(instances_dir.join(&instance.name).join(".minecraft").join("saves"));
} }
super::list::render( super::list::render(
frame, frame,
@@ -374,8 +373,7 @@ pub fn title(
match instance { match instance {
None => { None => {
frame.render_widget( frame.render_widget(
Paragraph::new("No instance selected") Paragraph::new("No instance selected").style(Style::default().fg(theme.text_dim())),
.style(Style::default().fg(theme.text_dim())),
inner, inner,
); );
} }
+3 -4
View File
@@ -2,16 +2,16 @@
// and provides keybinds to open config files in $EDITOR // and provides keybinds to open config files in $EDITOR
use ratatui::{ use ratatui::{
Frame,
layout::Rect, layout::Rect,
style::{Modifier, Style}, style::{Modifier, Style},
text::{Line, Span}, text::{Line, Span},
widgets::{Block, Borders, Paragraph}, widgets::{Block, Borders, Paragraph},
Frame,
}; };
use crate::config::theme::{BORDER_STYLE, THEME};
use crate::instance::models::InstanceConfig; use crate::instance::models::InstanceConfig;
use crate::tui::app::FocusedArea; use crate::tui::app::FocusedArea;
use crate::config::theme::{THEME, BORDER_STYLE};
use super::styled_title; use super::styled_title;
@@ -54,8 +54,7 @@ pub fn render(
let Some(inst) = instance else { let Some(inst) = instance else {
frame.render_widget( frame.render_widget(
Paragraph::new("No instance selected.") Paragraph::new("No instance selected.").style(Style::default().fg(theme.text_dim())),
.style(Style::default().fg(theme.text_dim())),
inner, inner,
); );
return; return;
+19 -10
View File
@@ -2,22 +2,22 @@
// handles search/filter, scrollbar sync, and inline renaming. // handles search/filter, scrollbar sync, and inline renaming.
// each row shows instance name + "last played" or current run state. // each row shows instance name + "last played" or current run state.
use crate::config::theme::{THEME, BORDER_STYLE}; use crate::config::theme::{BORDER_STYLE, THEME};
use crossterm::event::KeyCode; use crossterm::event::KeyCode;
use ratatui::{ use ratatui::{
Frame,
layout::Rect, layout::Rect,
style::{Modifier, Style}, style::{Modifier, Style},
text::{Line, Span, Text}, text::{Line, Span, Text},
widgets::{Block, Borders, Scrollbar, ScrollbarOrientation, ScrollbarState}, widgets::{Block, Borders, Scrollbar, ScrollbarOrientation, ScrollbarState},
Frame,
}; };
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView}; use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
use crate::instance::models::InstanceConfig; use crate::instance::models::InstanceConfig;
use crate::running::{get as get_run_state, RunState}; use crate::running::{RunState, get as get_run_state};
use crate::tui::app::FocusedArea; use crate::tui::app::FocusedArea;
use super::{search::SearchState, styled_title, WidgetKey}; use super::{WidgetKey, search::SearchState, styled_title};
// rough human-friendly time delta. not trying to be precise here, // rough human-friendly time delta. not trying to be precise here,
// "2 months ago" is close enough when months are ~30 days // "2 months ago" is close enough when months are ~30 days
@@ -168,6 +168,11 @@ impl WidgetKey for State {
fn handle_key(&mut self, key_event: &crossterm::event::KeyEvent) { fn handle_key(&mut self, key_event: &crossterm::event::KeyEvent) {
if self.search.active { if self.search.active {
match key_event.code { match key_event.code {
KeyCode::Enter => {
self.search.confirm();
self.list_state.selected = Some(0);
self.update_scrollbar();
}
KeyCode::Esc => { KeyCode::Esc => {
self.search.deactivate(); self.search.deactivate();
self.list_state.selected = Some(0); self.list_state.selected = Some(0);
@@ -250,7 +255,9 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut S
let (name_style, meta_style, bg) = if context.is_selected { let (name_style, meta_style, bg) = if context.is_selected {
( (
Style::default().fg(theme.accent()).add_modifier(Modifier::BOLD), Style::default()
.fg(theme.accent())
.add_modifier(Modifier::BOLD),
Style::default().fg(theme.text_dim()), Style::default().fg(theme.text_dim()),
stripe_bg, stripe_bg,
) )
@@ -295,14 +302,16 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut S
"Authenticating".to_string(), "Authenticating".to_string(),
Style::default().fg(theme.success()), Style::default().fg(theme.success()),
), ),
Some(RunState::Running) | Some(RunState::Starting) => ( Some(RunState::Running) | Some(RunState::Starting) => {
"Playing".to_string(), ("Playing".to_string(), Style::default().fg(theme.success()))
Style::default().fg(theme.success()), }
),
_ => (format_last_played(instance.last_played), meta_style), _ => (format_last_played(instance.last_played), meta_style),
}; };
let meta_line = Line::from(vec![selector.clone(), Span::styled(meta_text, meta_text_style)]); let meta_line = Line::from(vec![
selector.clone(),
Span::styled(meta_text, meta_text_style),
]);
let item = Text::from(vec![name_line, meta_line]).style(Style::default().bg(bg)); let item = Text::from(vec![name_line, meta_line]).style(Style::default().bg(bg));
(item, 2) (item, 2)
+47 -14
View File
@@ -8,16 +8,16 @@ use std::sync::{Arc, Mutex};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::{ use ratatui::{
Frame,
layout::{Constraint, Layout, Rect}, layout::{Constraint, Layout, Rect},
style::{Modifier, Style}, style::{Modifier, Style},
text::{Line, Span}, text::{Line, Span},
widgets::{Block, Borders, Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState}, widgets::{Block, Borders, Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState},
Frame,
}; };
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView}; use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
use crate::instance::log_files::{read_log_file, scan_log_files, LogFileEntry}; use crate::config::theme::{BORDER_STYLE, THEME};
use crate::config::theme::{THEME, BORDER_STYLE}; use crate::instance::log_files::{LogFileEntry, read_log_file, scan_log_files};
type PendingLogs = Arc<Mutex<Option<(String, Vec<LogFileEntry>)>>>; type PendingLogs = Arc<Mutex<Option<(String, Vec<LogFileEntry>)>>>;
@@ -38,6 +38,7 @@ pub struct LogsState {
pending: PendingLogs, pending: PendingLogs,
rescan_counter: u8, rescan_counter: u8,
instances_dir_cache: Option<std::path::PathBuf>, instances_dir_cache: Option<std::path::PathBuf>,
was_live: bool,
} }
impl Default for LogsState { impl Default for LogsState {
@@ -59,6 +60,7 @@ impl Default for LogsState {
pending: Arc::new(Mutex::new(None)), pending: Arc::new(Mutex::new(None)),
rescan_counter: 0, rescan_counter: 0,
instances_dir_cache: None, instances_dir_cache: None,
was_live: false,
} }
} }
} }
@@ -94,14 +96,22 @@ impl LogsState {
} }
pub fn drain_pending(&mut self) { pub fn drain_pending(&mut self) {
let taken = match self.pending.lock() { Ok(mut slot) => { // when the instance stops while viewing the live log, transition
slot.take() // to the on-disk log file so the viewer doesn't go blank
} _ => { let live_now = self.has_live();
None 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() {
Ok(mut slot) => slot.take(),
_ => None,
};
if let Some((instance_name, entries)) = taken if let Some((instance_name, entries)) = taken
&& self.loaded_for.as_deref() == Some(&instance_name) { && self.loaded_for.as_deref() == Some(&instance_name)
{
let prev_selected = self.list_state.selected; let prev_selected = self.list_state.selected;
self.entries = entries; self.entries = entries;
self.loading = false; self.loading = false;
@@ -112,7 +122,9 @@ impl LogsState {
self.list_state.selected = Some(0); self.list_state.selected = Some(0);
self.load_selected_content(); self.load_selected_content();
} else if let Some(sel) = prev_selected } else if let Some(sel) = prev_selected
&& sel >= display_count && display_count > 0 { && sel >= display_count
&& display_count > 0
{
self.list_state.selected = Some(display_count - 1); self.list_state.selected = Some(display_count - 1);
} }
self.update_scrollbar(); self.update_scrollbar();
@@ -225,6 +237,10 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool {
if state.viewer_focused { if state.viewer_focused {
if state.viewer_search.active { if state.viewer_search.active {
match key_event.code { match key_event.code {
KeyCode::Enter => {
state.viewer_search.confirm();
state.viewer_scroll = 0;
}
KeyCode::Esc => { KeyCode::Esc => {
state.viewer_search.deactivate(); state.viewer_search.deactivate();
state.viewer_scroll = 0; state.viewer_scroll = 0;
@@ -288,6 +304,11 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool {
} else { } else {
if state.search.active { if state.search.active {
match key_event.code { match key_event.code {
KeyCode::Enter => {
state.search.confirm();
state.list_state.selected = Some(0);
state.update_scrollbar();
}
KeyCode::Esc => { KeyCode::Esc => {
state.search.deactivate(); state.search.deactivate();
state.list_state.selected = Some(0); state.list_state.selected = Some(0);
@@ -408,7 +429,12 @@ fn render_list(
let entries_snapshot: Vec<(String, bool)> = { let entries_snapshot: Vec<(String, bool)> = {
let mut v = Vec::new(); let mut v = Vec::new();
if has_live { if has_live {
v.push(("\u{25cf} Live".to_string(), true)); let live_name = state
.entries
.first()
.map(|e| e.name.trim_end_matches(".log"))
.unwrap_or("Live");
v.push((live_name.to_string(), true));
} }
for e in &state.entries { for e in &state.entries {
v.push((e.name.trim_end_matches(".log").to_string(), false)); v.push((e.name.trim_end_matches(".log").to_string(), false));
@@ -421,11 +447,15 @@ fn render_list(
let show_selected = list_focused && context.is_selected; let show_selected = list_focused && context.is_selected;
let style = if *is_live && show_selected { let style = if *is_live && show_selected {
Style::default().fg(theme.success()).add_modifier(Modifier::BOLD) Style::default()
.fg(theme.success())
.add_modifier(Modifier::BOLD)
} else if *is_live { } else if *is_live {
Style::default().fg(theme.success()) Style::default().fg(theme.success())
} else if show_selected { } else if show_selected {
Style::default().fg(theme.accent()).add_modifier(Modifier::BOLD) Style::default()
.fg(theme.accent())
.add_modifier(Modifier::BOLD)
} else { } else {
Style::default().fg(theme.text()) Style::default().fg(theme.text())
}; };
@@ -441,7 +471,10 @@ fn render_list(
} else { } else {
Span::raw(" ") Span::raw(" ")
}; };
let item = ratatui::text::Text::from(Line::from(vec![selector, Span::styled(name.clone(), style)])) let item = ratatui::text::Text::from(Line::from(vec![
selector,
Span::styled(name.clone(), style),
]))
.style(Style::default().bg(bg)); .style(Style::default().bg(bg));
(item, 1) (item, 1)
}); });
+1 -1
View File
@@ -10,9 +10,9 @@ use ratatui::{
pub mod account; pub mod account;
pub mod content; pub mod content;
pub mod details; pub mod details;
pub mod instances;
pub mod logs_viewer; pub mod logs_viewer;
pub mod popups; pub mod popups;
pub mod instances;
pub mod screenshots_grid; pub mod screenshots_grid;
pub mod search; pub mod search;
pub mod status; pub mod status;
+2 -1
View File
@@ -14,7 +14,8 @@ use ratatui::{
use crate::config::theme::THEME; use crate::config::theme::THEME;
static CONFIRM_STATE: LazyLock<Mutex<ConfirmState>> = LazyLock::new(|| Mutex::new(ConfirmState::default())); static CONFIRM_STATE: LazyLock<Mutex<ConfirmState>> =
LazyLock::new(|| Mutex::new(ConfirmState::default()));
#[derive(Debug, Default)] #[derive(Debug, Default)]
struct ConfirmState { struct ConfirmState {
+1 -1
View File
@@ -12,8 +12,8 @@ use tracing::Level;
use super::base::PopupFrame; use super::base::PopupFrame;
use crate::config::SETTINGS; use crate::config::SETTINGS;
use crate::tui::error_buffer::ErrorEvent;
use crate::config::theme::THEME; use crate::config::theme::THEME;
use crate::tui::error_buffer::ErrorEvent;
pub struct ErrorPopup { pub struct ErrorPopup {
pub event: ErrorEvent, pub event: ErrorEvent,
+1 -1
View File
@@ -2,4 +2,4 @@ mod render;
mod state; mod state;
pub use render::{popup_rect, render}; pub use render::{popup_rect, render};
pub use state::{handle_key, take_result, ImportResult, ImportStep, ImportWizardState}; pub use state::{ImportResult, ImportStep, ImportWizardState, handle_key, take_result};
+10 -27
View File
@@ -3,15 +3,15 @@
use super::super::base::PopupFrame; use super::super::base::PopupFrame;
use super::super::new_instance::LoadState; use super::super::new_instance::LoadState;
use super::state::{ImportStep, ImportWizardState, IMPORT_STATE}; use super::state::{IMPORT_STATE, ImportStep, ImportWizardState};
use crate::tui::app::FocusedArea;
use crate::config::theme::THEME; use crate::config::theme::THEME;
use crate::tui::app::FocusedArea;
use ratatui::{ use ratatui::{
Frame,
layout::{Constraint, Direction, Layout, Rect}, layout::{Constraint, Direction, Layout, Rect},
style::{Modifier, Style}, style::{Modifier, Style},
text::{Line, Span}, text::{Line, Span},
widgets::{List, ListItem, ListState, Paragraph, StatefulWidget, Widget, Wrap}, widgets::{List, ListItem, ListState, Paragraph, StatefulWidget, Widget, Wrap},
Frame,
}; };
pub fn render(frame: &mut Frame, area: Rect, _focused: FocusedArea) { pub fn render(frame: &mut Frame, area: Rect, _focused: FocusedArea) {
@@ -85,11 +85,7 @@ pub fn popup_rect(frame_area: Rect) -> Rect {
} }
} }
fn render_input_step( fn render_input_step(state: &ImportWizardState, area: Rect, buf: &mut ratatui::buffer::Buffer) {
state: &ImportWizardState,
area: Rect,
buf: &mut ratatui::buffer::Buffer,
) {
let theme = THEME.as_ref(); let theme = THEME.as_ref();
let chunks = Layout::default() let chunks = Layout::default()
.direction(Direction::Vertical) .direction(Direction::Vertical)
@@ -115,10 +111,7 @@ fn render_input_step(
]) ])
} else { } else {
Line::from(vec![ Line::from(vec![
Span::styled( Span::styled(state.input.clone(), Style::default().fg(theme.text())),
state.input.clone(),
Style::default().fg(theme.text()),
),
Span::styled( Span::styled(
"\u{2588}", "\u{2588}",
Style::default() Style::default()
@@ -137,11 +130,7 @@ fn render_fetching_step(area: Rect, buf: &mut ratatui::buffer::Buffer) {
.render(area, buf); .render(area, buf);
} }
fn render_version_step( fn render_version_step(state: &ImportWizardState, area: Rect, buf: &mut ratatui::buffer::Buffer) {
state: &ImportWizardState,
area: Rect,
buf: &mut ratatui::buffer::Buffer,
) {
let theme = THEME.as_ref(); let theme = THEME.as_ref();
match &state.versions { match &state.versions {
LoadState::Idle | LoadState::Loading => { LoadState::Idle | LoadState::Loading => {
@@ -182,11 +171,7 @@ fn render_version_step(
} }
} }
fn render_confirm_step( fn render_confirm_step(state: &ImportWizardState, area: Rect, buf: &mut ratatui::buffer::Buffer) {
state: &ImportWizardState,
area: Rect,
buf: &mut ratatui::buffer::Buffer,
) {
let theme = THEME.as_ref(); let theme = THEME.as_ref();
let summary = match &state.summary { let summary = match &state.summary {
Some(s) => s, Some(s) => s,
@@ -247,11 +232,9 @@ fn step_keybinds(state: &ImportWizardState) -> Line<'static> {
match state.step { match state.step {
ImportStep::Input => keybind_line(&[("Enter", " fetch")]), ImportStep::Input => keybind_line(&[("Enter", " fetch")]),
ImportStep::Fetching => keybind_line(&[("Esc", " cancel")]), ImportStep::Fetching => keybind_line(&[("Esc", " cancel")]),
ImportStep::Version => keybind_line(&[ ImportStep::Version => {
("/", " search"), keybind_line(&[("/", " search"), ("h", " back"), ("Enter", " select")])
("h", " back"), }
("Enter", " select"),
]),
ImportStep::Confirm => keybind_line(&[("h", " back"), ("Enter", " import")]), ImportStep::Confirm => keybind_line(&[("h", " back"), ("Enter", " import")]),
} }
} }
@@ -4,7 +4,7 @@
// local files skip straight to the confirm step. // local files skip straight to the confirm step.
use super::super::new_instance::LoadState; use super::super::new_instance::LoadState;
use crate::instance::import::{parse_import_input, ImportInput, ImportSummary}; use crate::instance::import::{ImportInput, ImportSummary, parse_import_input};
use crate::net::modrinth::{self, VersionInfo}; use crate::net::modrinth::{self, VersionInfo};
use crate::tui::widgets::instances; use crate::tui::widgets::instances;
use crate::tui::widgets::search::SearchState; use crate::tui::widgets::search::SearchState;
@@ -309,8 +309,7 @@ async fn resolve_version_id(
} }
match modrinth::download_mrpack(client, &version, &tmp_dir).await { match modrinth::download_mrpack(client, &version, &tmp_dir).await {
Ok(mrpack_path) => { Ok(mrpack_path) => match crate::instance::import::build_summary(&mrpack_path) {
match crate::instance::import::build_summary(&mrpack_path) {
Ok(summary) => { Ok(summary) => {
if let Ok(mut s) = state_arc.lock() { if let Ok(mut s) = state_arc.lock() {
s.summary = Some(summary); s.summary = Some(summary);
@@ -322,8 +321,7 @@ async fn resolve_version_id(
format!("Failed to build summary: {}", e), format!("Failed to build summary: {}", e),
ImportStep::Input, ImportStep::Input,
), ),
} },
}
Err(e) => set_error_and_back( Err(e) => set_error_and_back(
&state_arc, &state_arc,
format!("Failed to download mrpack: {}", e), format!("Failed to download mrpack: {}", e),
@@ -383,8 +381,7 @@ fn start_version_download(state: &mut ImportWizardState) {
} }
match modrinth::download_mrpack(&client, &version, &tmp_dir).await { match modrinth::download_mrpack(&client, &version, &tmp_dir).await {
Ok(mrpack_path) => { Ok(mrpack_path) => match crate::instance::import::build_summary(&mrpack_path) {
match crate::instance::import::build_summary(&mrpack_path) {
Ok(summary) => { Ok(summary) => {
if let Ok(mut s) = state_arc.lock() { if let Ok(mut s) = state_arc.lock() {
s.summary = Some(summary); s.summary = Some(summary);
@@ -396,8 +393,7 @@ fn start_version_download(state: &mut ImportWizardState) {
format!("Failed to build summary: {}", e), format!("Failed to build summary: {}", e),
ImportStep::Version, ImportStep::Version,
), ),
} },
}
Err(e) => set_error_and_back( Err(e) => set_error_and_back(
&state_arc, &state_arc,
format!("Failed to download mrpack: {}", e), format!("Failed to download mrpack: {}", e),
+1 -1
View File
@@ -2,4 +2,4 @@ mod render;
mod state; mod state;
pub use render::{popup_rect, render}; pub use render::{popup_rect, render};
pub use state::{handle_key, take_result, LoadState, WizardParams, WizardStep, WizardState}; pub use state::{LoadState, WizardParams, WizardState, WizardStep, handle_key, take_result};
@@ -2,21 +2,21 @@
// and the popup resizes itself based on which step is active. // and the popup resizes itself based on which step is active.
use super::state::{ use super::state::{
clamp_loader_version_index, clamp_version_index, ensure_loader_versions_loaded, LoadState, WIZARD_STATE, WizardState, WizardStep, clamp_loader_version_index,
ensure_versions_loaded, visible_versions, LoadState, WizardState, WizardStep, WIZARD_STATE, clamp_version_index, ensure_loader_versions_loaded, ensure_versions_loaded, visible_versions,
}; };
use crate::config::theme::THEME;
use crate::instance::models::ModLoader; use crate::instance::models::ModLoader;
use crate::tui::app::FocusedArea; use crate::tui::app::FocusedArea;
use crate::config::theme::THEME;
use crate::tui::widgets::popups::base::PopupFrame; use crate::tui::widgets::popups::base::PopupFrame;
use tui_prompts::State as PromptState;
use ratatui::{ use ratatui::{
Frame,
layout::{Constraint, Direction, Layout, Rect}, layout::{Constraint, Direction, Layout, Rect},
style::{Modifier, Style}, style::{Modifier, Style},
text::{Line, Span}, text::{Line, Span},
widgets::{List, ListItem, ListState, Paragraph, StatefulWidget, Widget, Wrap}, widgets::{List, ListItem, ListState, Paragraph, StatefulWidget, Widget, Wrap},
Frame,
}; };
use tui_prompts::State as PromptState;
pub fn render(frame: &mut Frame, area: Rect, _focused: FocusedArea) { pub fn render(frame: &mut Frame, area: Rect, _focused: FocusedArea) {
// grab the lock, kick off any lazy-loading, then clone and release. // grab the lock, kick off any lazy-loading, then clone and release.
@@ -140,10 +140,7 @@ fn render_name_step(state: &WizardState, area: Rect, buf: &mut ratatui::buffer::
// \u{2588} is the full block char used as a fake blinking cursor // \u{2588} is the full block char used as a fake blinking cursor
let line = if value.is_empty() { let line = if value.is_empty() {
Line::from(vec![ Line::from(vec![
Span::styled( Span::styled("Instance name...", Style::default().fg(theme.text_dim())),
"Instance name...",
Style::default().fg(theme.text_dim()),
),
Span::styled( Span::styled(
"\u{2588}", "\u{2588}",
Style::default() Style::default()
+25 -21
View File
@@ -8,16 +8,16 @@ use std::sync::{Arc, Mutex};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::{ use ratatui::{
Frame,
layout::{Constraint, Layout, Rect}, layout::{Constraint, Layout, Rect},
style::{Modifier, Style}, style::{Modifier, Style},
text::Span, text::Span,
widgets::{Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState}, widgets::{Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState},
Frame,
}; };
use ratatui_image::{protocol::StatefulProtocol, Resize, StatefulImage}; use ratatui_image::{Resize, StatefulImage, protocol::StatefulProtocol};
use crate::instance::screenshots::ScreenshotEntry;
use crate::config::theme::THEME; use crate::config::theme::THEME;
use crate::instance::screenshots::ScreenshotEntry;
// grid cell sizing constraints in terminal columns. // grid cell sizing constraints in terminal columns.
// the grid auto-fits columns within these bounds depending on terminal width // the grid auto-fits columns within these bounds depending on terminal width
@@ -97,14 +97,14 @@ impl ScreenshotsState {
} }
pub fn drain_pending_entries(&mut self) { pub fn drain_pending_entries(&mut self) {
let taken = match self.pending_entries.lock() { Ok(mut slot) => { let taken = match self.pending_entries.lock() {
slot.take() Ok(mut slot) => slot.take(),
} _ => { _ => None,
None };
}};
if let Some((instance_name, entries)) = taken if let Some((instance_name, entries)) = taken
&& self.loaded_for.as_deref() == Some(&instance_name) { && self.loaded_for.as_deref() == Some(&instance_name)
{
self.entries = entries; self.entries = entries;
self.loading = false; self.loading = false;
self.selected = 0; self.selected = 0;
@@ -113,11 +113,10 @@ impl ScreenshotsState {
} }
pub fn take_pending_images(&mut self) -> Vec<(usize, image::DynamicImage)> { pub fn take_pending_images(&mut self) -> Vec<(usize, image::DynamicImage)> {
match self.pending_images.lock() { Ok(mut slot) => { match self.pending_images.lock() {
std::mem::take(&mut *slot) Ok(mut slot) => std::mem::take(&mut *slot),
} _ => { _ => Vec::new(),
Vec::new() }
}}
} }
pub fn set_protocol(&mut self, idx: usize, proto: StatefulProtocol) { pub fn set_protocol(&mut self, idx: usize, proto: StatefulProtocol) {
@@ -146,7 +145,8 @@ impl ScreenshotsState {
.unwrap_or(None); .unwrap_or(None);
if let Some(img) = img if let Some(img) = img
&& let Ok(mut slot) = pending.lock() { && let Ok(mut slot) = pending.lock()
{
slot.push((idx, img)); slot.push((idx, img));
} }
}); });
@@ -182,6 +182,10 @@ impl ScreenshotsState {
pub fn handle_key(key_event: &KeyEvent, state: &mut ScreenshotsState) -> bool { pub fn handle_key(key_event: &KeyEvent, state: &mut ScreenshotsState) -> bool {
if state.search.active { if state.search.active {
match key_event.code { match key_event.code {
KeyCode::Enter => {
state.search.confirm();
state.selected = 0;
}
KeyCode::Esc => { KeyCode::Esc => {
state.search.deactivate(); state.search.deactivate();
state.selected = 0; state.selected = 0;
@@ -225,14 +229,16 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut ScreenshotsState) -> bool {
KeyCode::Enter if key_event.modifiers.contains(KeyModifiers::SHIFT) => { KeyCode::Enter if key_event.modifiers.contains(KeyModifiers::SHIFT) => {
if let Some(entry) = state.entries.get(state.selected) if let Some(entry) = state.entries.get(state.selected)
&& let Some(dir) = entry.path.parent() && let Some(dir) = entry.path.parent()
&& let Err(e) = open::that(dir) { && let Err(e) = open::that(dir)
{
tracing::error!("Failed to open directory: {}", e); tracing::error!("Failed to open directory: {}", e);
} }
true true
} }
KeyCode::Enter => { KeyCode::Enter => {
if let Some(entry) = state.entries.get(state.selected) if let Some(entry) = state.entries.get(state.selected)
&& let Err(e) = open::that(&entry.path) { && let Err(e) = open::that(&entry.path)
{
tracing::error!("Failed to open file: {}", e); tracing::error!("Failed to open file: {}", e);
} }
true true
@@ -272,8 +278,7 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut ScreenshotsState, is_fo
let theme = THEME.as_ref(); let theme = THEME.as_ref();
if state.loading { if state.loading {
frame.render_widget( frame.render_widget(
Paragraph::new("Loading screenshots...") Paragraph::new("Loading screenshots...").style(Style::default().fg(theme.text_dim())),
.style(Style::default().fg(theme.text_dim())),
area, area,
); );
return; return;
@@ -281,8 +286,7 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut ScreenshotsState, is_fo
if state.entries.is_empty() { if state.entries.is_empty() {
frame.render_widget( frame.render_widget(
Paragraph::new("No screenshots.") Paragraph::new("No screenshots.").style(Style::default().fg(theme.text_dim())),
.style(Style::default().fg(theme.text_dim())),
area, area,
); );
return; return;
+50
View File
@@ -24,6 +24,12 @@ impl SearchState {
self.query.clear(); self.query.clear();
} }
// exit search mode but keep the filter active so the user can
// navigate the filtered results
pub fn confirm(&mut self) {
self.active = false;
}
pub fn push(&mut self, c: char) { pub fn push(&mut self, c: char) {
self.query.push(c); self.query.push(c);
} }
@@ -103,3 +109,47 @@ impl SearchState {
Some(Line::from(spans).right_aligned()) Some(Line::from(spans).right_aligned())
} }
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn confirm_keeps_query_but_deactivates() {
let mut s = SearchState::default();
s.activate();
s.push('a');
s.push('b');
s.confirm();
assert!(!s.active);
assert_eq!(s.query, "ab");
// filter should still match
assert!(s.matches("abc"));
assert!(!s.matches("xyz"));
}
#[test]
fn deactivate_clears_query() {
let mut s = SearchState::default();
s.activate();
s.push('x');
s.deactivate();
assert!(!s.active);
assert!(s.query.is_empty());
// with empty query, everything matches
assert!(s.matches("anything"));
}
#[test]
fn confirm_then_reactivate_preserves_query() {
let mut s = SearchState::default();
s.activate();
s.push('t');
s.push('e');
s.confirm();
// user presses search key again to edit
s.activate();
assert!(s.active);
assert_eq!(s.query, "te");
}
}
+4 -10
View File
@@ -2,17 +2,17 @@
// shows a gauge when the total is known, or a spinner when it's not. // shows a gauge when the total is known, or a spinner when it's not.
use ratatui::{ use ratatui::{
Frame,
layout::{Constraint, Layout, Rect}, layout::{Constraint, Layout, Rect},
style::{Modifier, Style}, style::{Modifier, Style},
text::Span, text::Span,
widgets::{Block, Borders, Gauge, Paragraph}, widgets::{Block, Borders, Gauge, Paragraph},
Frame,
}; };
use throbber_widgets_tui::{Throbber, ThrobberState}; use throbber_widgets_tui::{Throbber, ThrobberState};
use crate::config::theme::{BORDER_STYLE, THEME};
use crate::tui::app::FocusedArea; use crate::tui::app::FocusedArea;
use crate::tui::progress::PROGRESS; use crate::tui::progress::PROGRESS;
use crate::config::theme::{THEME, BORDER_STYLE};
use super::styled_title; use super::styled_title;
@@ -39,10 +39,7 @@ pub fn render(
Ok(s) => s.clone(), Ok(s) => s.clone(),
Err(_) => { Err(_) => {
frame.render_widget( frame.render_widget(
Paragraph::new(Span::styled( Paragraph::new(Span::styled("Ready", Style::default().fg(theme.text_dim())))
"Ready",
Style::default().fg(theme.text_dim()),
))
.block(block), .block(block),
area, area,
); );
@@ -52,10 +49,7 @@ pub fn render(
if state.current_action.is_none() { if state.current_action.is_none() {
frame.render_widget( frame.render_widget(
Paragraph::new(Span::styled( Paragraph::new(Span::styled("Ready", Style::default().fg(theme.text_dim())))
"Ready",
Style::default().fg(theme.text_dim()),
))
.block(block), .block(block),
area, area,
); );