refactor: clarify content and tui ownership

This commit is contained in:
objz committed 2026-07-27 11:03:46 +02:00
1 parent 078afe4b9d
commit 15d76c18a0
32 files changed
+893 -1144

No files matched your search

+1 -1
View File
@@ -106,7 +106,7 @@ fn toggle_entry(
return Ok(());
}
crate::instance::content::mods::toggle_entry(entry)?;
crate::instance::toggle_entry(entry)?;
println!(
"{}d '{}'.",
if should_enable { "Enable" } else { "Disable" },
+2 -10
View File
@@ -87,7 +87,7 @@ impl ContentProvider for ModrinthProvider {
) -> Result<DiscoveryResults, crate::net::NetError> {
crate::net::modrinth::search_discovery(
&self.client,
discovery_kind(kind),
kind,
query,
&instance.game_version,
instance.loader,
@@ -151,7 +151,7 @@ impl ContentProvider for ModrinthProvider {
crate::net::modrinth::fetch_content_versions(
&self.client,
project_id,
discovery_kind(kind),
kind,
game_version,
loader,
)
@@ -182,14 +182,6 @@ impl ContentProvider for ModrinthProvider {
}
}
fn discovery_kind(kind: ContentKind) -> crate::net::modrinth::DiscoveryKind {
match kind {
ContentKind::Mod => crate::net::modrinth::DiscoveryKind::Mod,
ContentKind::ResourcePack => crate::net::modrinth::DiscoveryKind::ResourcePack,
ContentKind::Shader => crate::net::modrinth::DiscoveryKind::Shader,
}
}
pub struct ProviderRegistry {
providers: Vec<Box<dyn ContentProvider>>,
}
+41
View File
@@ -0,0 +1,41 @@
use std::path::PathBuf;
use super::icons::IconCell;
#[derive(Debug, Clone)]
pub struct ContentEntry {
pub file_stem: String,
pub name: String,
pub source_slug: Option<String>,
pub installed_path: Option<PathBuf>,
pub provider_project: Option<super::manifest::ProviderProject>,
pub title_suffix: Option<String>,
pub footer_label: Option<String>,
pub description: String,
pub enabled: bool,
pub icon_bytes: Option<Vec<u8>>,
pub provider_icon: bool,
pub provider_description: bool,
pub path: PathBuf,
pub icon_lines: Option<Vec<Vec<IconCell>>>,
}
// enable/disable by renaming the file with/without ".disabled" suffix.
pub fn toggle_entry(entry: &ContentEntry) -> Result<(), std::io::Error> {
toggle_entry_path(entry).map(drop)
}
pub(crate) fn toggle_entry_path(entry: &ContentEntry) -> Result<Option<PathBuf>, std::io::Error> {
let Some(file_name) = entry.path.file_name().and_then(|name| name.to_str()) else {
return Ok(None);
};
let new_name = if entry.enabled {
format!("{file_name}.disabled")
} else {
file_name.trim_end_matches(".disabled").to_owned()
};
let mut new_path = entry.path.clone();
new_path.set_file_name(new_name);
std::fs::rename(&entry.path, &new_path)?;
Ok(Some(new_path))
}
+274
View File
@@ -0,0 +1,274 @@
// terminal icon rasterization shared by every content type and markdown.
// a single "pixel" in a terminal icon.
#[derive(Debug, Clone, Copy)]
pub struct IconCell {
pub symbol: char,
pub bg_r: u8,
pub bg_g: u8,
pub bg_b: u8,
pub fg_r: u8,
pub fg_g: u8,
pub fg_b: u8,
}
pub(crate) fn make_icon_pixels(
bytes: &[u8],
width: u16,
height: u16,
) -> Option<Vec<Vec<IconCell>>> {
let image = image::load_from_memory(bytes).ok()?;
Some(make_icon_pixels_from_image(&image, width, height))
}
pub(crate) fn make_icon_pixels_from_image(
image: &image::DynamicImage,
width: u16,
height: u16,
) -> Vec<Vec<IconCell>> {
let resized = image.resize_exact(
u32::from(width),
u32::from(height) * 2,
image::imageops::FilterType::Nearest,
);
let rgb = resized.to_rgb8();
let mut rows = Vec::new();
for row in 0..height {
let mut columns = Vec::new();
for column in 0..width {
let top_y = u32::from(row) * 2;
let bottom_y = (top_y + 1).min(rgb.height().saturating_sub(1));
let [tr, tg, tb] = rgb.get_pixel(u32::from(column), top_y).0;
let [br, bg, bb] = rgb.get_pixel(u32::from(column), bottom_y).0;
columns.push(IconCell {
symbol: '\u{2584}',
bg_r: br,
bg_g: bg,
bg_b: bb,
fg_r: tr,
fg_g: tg,
fg_b: tb,
});
}
rows.push(columns);
}
rows
}
pub(crate) fn make_icon_quadrants_from_image(
image: &image::DynamicImage,
width: u16,
height: u16,
) -> Vec<Vec<IconCell>> {
let resized = image
.resize_exact(
u32::from(width) * 2,
u32::from(height) * 2,
image::imageops::FilterType::Lanczos3,
)
.to_rgb8();
(0..height)
.map(|row| {
(0..width)
.map(|column| {
let x = u32::from(column) * 2;
let y = u32::from(row) * 2;
quadrant_cell([
resized.get_pixel(x, y).0,
resized.get_pixel(x + 1, y).0,
resized.get_pixel(x, y + 1).0,
resized.get_pixel(x + 1, y + 1).0,
])
})
.collect()
})
.collect()
}
fn quadrant_cell(pixels: [[u8; 3]; 4]) -> IconCell {
let mut pair = (0, 0);
let mut max_distance = 0;
for left in 0..pixels.len() {
for right in (left + 1)..pixels.len() {
let distance = color_distance(pixels[left], pixels[right]);
if distance > max_distance {
max_distance = distance;
pair = (left, right);
}
}
}
let bg = pixels[pair.0];
let fg = pixels[pair.1];
let mask = pixels
.iter()
.enumerate()
.fold(0_u8, |mask, (index, pixel)| {
if color_distance(*pixel, fg) <= color_distance(*pixel, bg) {
mask | (1 << index)
} else {
mask
}
});
let symbol = match mask {
0 => ' ',
1 => '\u{2598}',
2 => '\u{259d}',
3 => '\u{2580}',
4 => '\u{2596}',
5 => '\u{258c}',
6 => '\u{259e}',
7 => '\u{259b}',
8 => '\u{2597}',
9 => '\u{259a}',
10 => '\u{2590}',
11 => '\u{259c}',
12 => '\u{2584}',
13 => '\u{2599}',
14 => '\u{259f}',
_ => '\u{2588}',
};
IconCell {
symbol,
bg_r: bg[0],
bg_g: bg[1],
bg_b: bg[2],
fg_r: fg[0],
fg_g: fg[1],
fg_b: fg[2],
}
}
fn color_distance(left: [u8; 3], right: [u8; 3]) -> u32 {
left.into_iter()
.zip(right)
.map(|(left, right)| {
let delta = i32::from(left) - i32::from(right);
(delta * delta) as u32
})
.sum()
}
// 6 columns by 3 terminal rows is physically square with the usual 1:2 cell ratio.
pub(crate) fn fallback_icon() -> Vec<Vec<IconCell>> {
const MASK: [[bool; 6]; 6] = [
[false, true, true, true, true, false],
[true, false, false, false, false, true],
[false, false, false, true, true, false],
[false, false, true, true, false, false],
[false, false, false, false, false, false],
[false, false, true, true, false, false],
];
MASK.chunks_exact(2)
.map(|pair| {
pair[0]
.iter()
.zip(pair[1])
.map(|(&top, bottom)| fallback_cell(top, bottom))
.collect()
})
.collect()
}
fn fallback_cell(top: bool, bottom: bool) -> IconCell {
let background = if top { 150 } else { 45 };
let foreground = if bottom { 150 } else { 45 };
IconCell {
symbol: '\u{2584}',
bg_r: background,
bg_g: background,
bg_b: background,
fg_r: foreground,
fg_g: foreground,
fg_b: foreground,
}
}
pub(crate) fn fallback_icon_large() -> Vec<Vec<IconCell>> {
let background = IconCell {
symbol: '\u{2584}',
bg_r: 50,
bg_g: 50,
bg_b: 50,
fg_r: 50,
fg_g: 50,
fg_b: 50,
};
let bottom = IconCell {
symbol: '\u{2584}',
bg_r: 50,
bg_g: 50,
bg_b: 50,
fg_r: 130,
fg_g: 130,
fg_b: 130,
};
let top = IconCell {
symbol: '\u{2584}',
bg_r: 130,
bg_g: 130,
bg_b: 130,
fg_r: 50,
fg_g: 50,
fg_b: 50,
};
vec![
vec![
background, background, bottom, bottom, bottom, bottom, bottom, bottom, bottom, bottom,
background, background,
],
vec![
background, background, bottom, bottom, bottom, bottom, bottom, bottom, bottom, bottom,
background, background,
],
vec![
background, background, background, background, background, background, top, top, top,
top, background, background,
],
vec![
background, background, background, background, background, background, top, top, top,
top, background, background,
],
vec![
background, background, background, background, top, top, top, top, background,
background, background, background,
],
vec![
background, background, background, background, top, top, top, top, background,
background, background, background,
],
]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn quadrant_raster_has_requested_dimensions() {
let image = image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(
2,
2,
image::Rgb([12, 34, 56]),
));
let rows = make_icon_quadrants_from_image(&image, 7, 3);
assert_eq!(rows.len(), 3);
assert!(rows.iter().all(|row| row.len() == 7));
assert!(rows.iter().flatten().all(|cell| cell.symbol == '\u{2588}'));
}
#[test]
fn fallback_icon_is_square_and_contains_a_separate_question_mark_dot() {
let icon = fallback_icon();
assert_eq!(icon.len(), 3);
assert!(icon.iter().all(|row| row.len() == 6));
assert_eq!(icon[2][2].bg_r, 45);
assert_eq!(icon[2][2].fg_r, 150);
assert_eq!(icon[2][3].fg_r, 150);
}
}
+11
View File
@@ -27,6 +27,17 @@ impl ContentKind {
Self::Shader => "shaderpacks",
}
}
pub fn unavailable_message(self, loader: crate::instance::ModLoader) -> Option<&'static str> {
if loader != crate::instance::ModLoader::Vanilla {
return None;
}
match self {
Self::Mod => Some("Vanilla does not support mods."),
Self::Shader => Some("Vanilla does not support shaders."),
Self::ResourcePack => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+10 -2
View File
@@ -1,15 +1,23 @@
// scanning and toggling instance content (mods, resource packs, shaders, worlds).
// minecraft uses a ".disabled" suffix convention for disabled content, so this leans on that heavily.
mod entry;
mod icons;
pub mod manifest;
pub mod mods;
mod packs;
pub mod reconcile;
pub mod resource_packs;
pub mod shaders;
pub mod worlds;
pub use mods::scan_one_mod;
pub use mods::{ContentEntry, scan_mods, toggle_entry};
pub(crate) use entry::toggle_entry_path;
pub use entry::{ContentEntry, toggle_entry};
pub(crate) use icons::{
IconCell, fallback_icon, fallback_icon_large, make_icon_pixels, make_icon_pixels_from_image,
make_icon_quadrants_from_image,
};
pub use mods::{scan_mods, scan_one_mod};
pub use resource_packs::{scan_one_resource_pack, scan_resource_packs};
pub use shaders::{scan_one_shader, scan_shaders};
pub use worlds::{scan_one_world, scan_worlds};
+6 -294
View File
@@ -1,44 +1,17 @@
// mod scanning, metadata extraction, and icon rendering for the content list.
// mod scanning and loader-specific metadata extraction.
// jar files are just zips, so it cracks them open looking for loader-specific
// 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::path::{Path, PathBuf};
use std::path::Path;
use serde::Deserialize;
// a single "pixel" in the terminal icon. uses the unicode half-block trick
// where each character cell shows two vertical pixels (fg = top, bg = bottom)
#[derive(Debug, Clone, Copy)]
pub struct IconCell {
pub symbol: char,
pub bg_r: u8,
pub bg_g: u8,
pub bg_b: u8,
pub fg_r: u8,
pub fg_g: u8,
pub fg_b: u8,
}
#[derive(Debug, Clone)]
pub struct ContentEntry {
pub file_stem: String,
pub name: String,
pub source_slug: Option<String>,
pub installed_path: Option<PathBuf>,
pub provider_project: Option<super::manifest::ProviderProject>,
pub title_suffix: Option<String>,
pub footer_label: Option<String>,
pub description: String,
pub enabled: bool,
pub icon_bytes: Option<Vec<u8>>,
pub provider_icon: bool,
pub provider_description: bool,
pub path: PathBuf,
pub icon_lines: Option<Vec<Vec<IconCell>>>,
}
pub use super::entry::{ContentEntry, toggle_entry};
pub use super::icons::IconCell;
use super::icons::{fallback_icon, make_icon_pixels};
#[derive(Deserialize, Default)]
struct FabricModJson {
@@ -382,271 +355,10 @@ fn read_zip_bytes(archive: &mut zip::ZipArchive<std::fs::File>, path: &str) -> O
Some(bytes)
}
// downscales an icon to terminal resolution. resizes to height*2 because each
// terminal cell renders two vertical pixels using half-block characters (▀)
pub(crate) fn make_icon_pixels(
bytes: &[u8],
width: u16,
height: u16,
) -> Option<Vec<Vec<IconCell>>> {
let img = image::load_from_memory(bytes).ok()?;
Some(make_icon_pixels_from_image(&img, width, height))
}
pub(crate) fn make_icon_pixels_from_image(
img: &image::DynamicImage,
width: u16,
height: u16,
) -> Vec<Vec<IconCell>> {
let resized = img.resize_exact(
u32::from(width),
u32::from(height) * 2,
image::imageops::FilterType::Nearest,
);
let rgb = resized.to_rgb8();
let mut rows = Vec::new();
for row in 0..height {
let mut cols = Vec::new();
for col in 0..width {
let top_y = u32::from(row) * 2;
let bottom_y = (u32::from(row) * 2 + 1).min(rgb.height().saturating_sub(1));
let [tr, tg, tb] = rgb.get_pixel(u32::from(col), top_y).0;
let [br, bg, bb] = rgb.get_pixel(u32::from(col), bottom_y).0;
cols.push(IconCell {
symbol: '\u{2584}',
bg_r: br,
bg_g: bg,
bg_b: bb,
fg_r: tr,
fg_g: tg,
fg_b: tb,
});
}
rows.push(cols);
}
rows
}
pub(crate) fn make_icon_quadrants_from_image(
img: &image::DynamicImage,
width: u16,
height: u16,
) -> Vec<Vec<IconCell>> {
let resized = img
.resize_exact(
u32::from(width) * 2,
u32::from(height) * 2,
image::imageops::FilterType::Lanczos3,
)
.to_rgb8();
(0..height)
.map(|row| {
(0..width)
.map(|col| {
let x = u32::from(col) * 2;
let y = u32::from(row) * 2;
let pixels = [
resized.get_pixel(x, y).0,
resized.get_pixel(x + 1, y).0,
resized.get_pixel(x, y + 1).0,
resized.get_pixel(x + 1, y + 1).0,
];
quadrant_cell(pixels)
})
.collect()
})
.collect()
}
fn quadrant_cell(pixels: [[u8; 3]; 4]) -> IconCell {
let mut pair = (0, 0);
let mut max_distance = 0;
for left in 0..pixels.len() {
for right in (left + 1)..pixels.len() {
let distance = color_distance(pixels[left], pixels[right]);
if distance > max_distance {
max_distance = distance;
pair = (left, right);
}
}
}
let bg = pixels[pair.0];
let fg = pixels[pair.1];
let mask = pixels
.iter()
.enumerate()
.fold(0_u8, |mask, (index, pixel)| {
if color_distance(*pixel, fg) <= color_distance(*pixel, bg) {
mask | (1 << index)
} else {
mask
}
});
let symbol = match mask {
0 => ' ',
1 => '\u{2598}',
2 => '\u{259d}',
3 => '\u{2580}',
4 => '\u{2596}',
5 => '\u{258c}',
6 => '\u{259e}',
7 => '\u{259b}',
8 => '\u{2597}',
9 => '\u{259a}',
10 => '\u{2590}',
11 => '\u{259c}',
12 => '\u{2584}',
13 => '\u{2599}',
14 => '\u{259f}',
_ => '\u{2588}',
};
IconCell {
symbol,
bg_r: bg[0],
bg_g: bg[1],
bg_b: bg[2],
fg_r: fg[0],
fg_g: fg[1],
fg_b: fg[2],
}
}
fn color_distance(left: [u8; 3], right: [u8; 3]) -> u32 {
left.into_iter()
.zip(right)
.map(|(left, right)| {
let delta = i32::from(left) - i32::from(right);
(delta * delta) as u32
})
.sum()
}
// 6 columns by 3 terminal rows is physically square with the usual 1:2 cell ratio.
pub(crate) fn fallback_icon() -> Vec<Vec<IconCell>> {
const MASK: [[bool; 6]; 6] = [
[false, true, true, true, true, false],
[true, false, false, false, false, true],
[false, false, false, true, true, false],
[false, false, true, true, false, false],
[false, false, false, false, false, false],
[false, false, true, true, false, false],
];
MASK.chunks_exact(2)
.map(|pair| {
pair[0]
.iter()
.zip(pair[1])
.map(|(&top, bottom)| fallback_cell(top, bottom))
.collect()
})
.collect()
}
fn fallback_cell(top: bool, bottom: bool) -> IconCell {
let background = if top { 150 } else { 45 };
let foreground = if bottom { 150 } else { 45 };
IconCell {
symbol: '\u{2584}',
bg_r: background,
bg_g: background,
bg_b: background,
fg_r: foreground,
fg_g: foreground,
fg_b: foreground,
}
}
// 12x6 fallback icon showing a "?" pattern for worlds without icons.
pub(super) fn fallback_icon_large() -> Vec<Vec<IconCell>> {
let b = IconCell {
symbol: '\u{2584}',
bg_r: 50,
bg_g: 50,
bg_b: 50,
fg_r: 50,
fg_g: 50,
fg_b: 50,
};
let tb = IconCell {
symbol: '\u{2584}',
bg_r: 50,
bg_g: 50,
bg_b: 50,
fg_r: 130,
fg_g: 130,
fg_b: 130,
};
let bt = IconCell {
symbol: '\u{2584}',
bg_r: 130,
bg_g: 130,
bg_b: 130,
fg_r: 50,
fg_g: 50,
fg_b: 50,
};
vec![
vec![b, b, tb, tb, tb, tb, tb, tb, tb, tb, b, b],
vec![b, b, tb, tb, tb, tb, tb, tb, tb, tb, b, b],
vec![b, b, b, b, b, b, bt, bt, bt, bt, b, b],
vec![b, b, b, b, b, b, bt, bt, bt, bt, b, b],
vec![b, b, b, b, bt, bt, bt, bt, b, b, b, b],
vec![b, b, b, b, bt, bt, bt, bt, b, b, b, b],
]
}
// enable/disable by renaming the file with/without ".disabled" suffix.
// the minecraft way, apparently.
pub fn toggle_entry(entry: &ContentEntry) -> Result<(), std::io::Error> {
let file_name = match entry.path.file_name().and_then(|name| name.to_str()) {
Some(name) => name,
None => return Ok(()),
};
let new_name = if entry.enabled {
format!("{file_name}.disabled")
} else {
file_name.trim_end_matches(".disabled").to_string()
};
let mut new_path = entry.path.clone();
new_path.set_file_name(new_name);
std::fs::rename(&entry.path, new_path)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn quadrant_raster_has_requested_dimensions() {
let image = image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(
2,
2,
image::Rgb([12, 34, 56]),
));
let rows = make_icon_quadrants_from_image(&image, 7, 3);
assert_eq!(rows.len(), 3);
assert!(rows.iter().all(|row| row.len() == 7));
assert!(rows.iter().flatten().all(|cell| cell.symbol == '\u{2588}'));
}
#[test]
fn fallback_icon_is_square_and_contains_a_separate_question_mark_dot() {
let icon = fallback_icon();
assert_eq!(icon.len(), 3);
assert!(icon.iter().all(|row| row.len() == 6));
assert_eq!(icon[2][2].bg_r, 45);
assert_eq!(icon[2][2].fg_r, 150);
assert_eq!(icon[2][3].fg_r, 150);
}
use std::path::PathBuf;
fn setup_mods_dir(tmp: &Path, instance: &str) -> PathBuf {
let dir = tmp
+123
View File
@@ -0,0 +1,123 @@
// shared pack.mcmeta scanning for resource packs and shader packs.
use std::path::Path;
use serde::Deserialize;
use super::{ContentEntry, fallback_icon, make_icon_pixels};
#[derive(Deserialize, Default)]
struct PackMcMeta {
#[serde(default)]
pack: PackInfo,
}
#[derive(Deserialize, Default)]
struct PackInfo {
#[serde(default)]
description: serde_json::Value,
}
pub(crate) fn extract_description(value: &serde_json::Value) -> String {
match value {
serde_json::Value::String(text) => text.clone(),
serde_json::Value::Object(object) => object
.get("text")
.and_then(|value| value.as_str())
.unwrap_or("")
.to_owned(),
serde_json::Value::Array(values) => values
.iter()
.filter_map(|value| match value {
serde_json::Value::String(text) => Some(text.as_str()),
serde_json::Value::Object(object) => {
object.get("text").and_then(|value| value.as_str())
}
_ => None,
})
.collect::<Vec<_>>()
.join(""),
_ => String::new(),
}
}
pub(crate) fn scan_one_pack(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry {
let (description, icon_bytes) = if path.is_dir() {
read_metadata_from_dir(path)
} else {
read_metadata_from_zip(path)
};
let icon_lines = icon_bytes
.as_ref()
.and_then(|bytes| make_icon_pixels(bytes, 6, 3))
.or_else(|| Some(fallback_icon()));
ContentEntry {
file_stem: file_stem.to_owned(),
name: file_stem.to_owned(),
source_slug: None,
installed_path: None,
provider_project: None,
title_suffix: None,
footer_label: None,
description,
enabled,
icon_bytes,
provider_icon: false,
provider_description: false,
path: path.to_path_buf(),
icon_lines,
}
}
pub(crate) fn scan_packs(
instances_dir: &Path,
instance_name: &str,
directory: &str,
) -> Vec<ContentEntry> {
let directory = instances_dir
.join(instance_name)
.join(crate::storage::MINECRAFT_DIR_NAME)
.join(directory);
let Ok(entries) = std::fs::read_dir(directory) else {
return Vec::new();
};
let mut packs = entries
.flatten()
.filter_map(|entry| {
let path = entry.path();
let file_name = path.file_name()?.to_str()?;
let (enabled, file_stem) = if path.is_dir() {
super::parse_enabled_stem_dir(file_name)
} else {
super::parse_enabled_stem(file_name, ".zip")?
};
Some(scan_one_pack(&path, &file_stem, enabled))
})
.collect::<Vec<_>>();
packs.sort_by_cached_key(|entry| entry.name.to_lowercase());
packs
}
fn read_metadata_from_zip(path: &Path) -> (String, Option<Vec<u8>>) {
let Some(mut archive) = super::open_zip(path) else {
return (String::new(), None);
};
let description = archive
.by_name("pack.mcmeta")
.ok()
.and_then(|entry| serde_json::from_reader::<_, PackMcMeta>(entry).ok())
.map(|meta| extract_description(&meta.pack.description))
.unwrap_or_default();
let icon_bytes = super::read_icon_from_zip(&mut archive);
(description, icon_bytes)
}
fn read_metadata_from_dir(path: &Path) -> (String, Option<Vec<u8>>) {
let description = std::fs::read_to_string(path.join("pack.mcmeta"))
.ok()
.and_then(|content| serde_json::from_str::<PackMcMeta>(&content).ok())
.map(|meta| extract_description(&meta.pack.description))
.unwrap_or_default();
(description, std::fs::read(path.join("pack.png")).ok())
}
+5 -141
View File
@@ -1,159 +1,23 @@
// resource pack scanning. packs can be either .zip files or plain directories,
// and metadata lives in pack.mcmeta (which mojang decided should have like 3
// different ways to encode a description, because why not)
// resource pack scanner backed by the shared pack.mcmeta reader.
use std::path::Path;
use serde::Deserialize;
use super::mods::{ContentEntry, make_icon_pixels};
#[derive(Deserialize, Default)]
pub(crate) struct PackMcMeta {
#[serde(default)]
pub pack: PackInfo,
}
#[derive(Deserialize, Default)]
pub(crate) struct PackInfo {
#[serde(default)]
pub description: serde_json::Value,
}
// description can be a plain string, a chat component object with "text",
// or an array mixing both. thanks mojang, very cool.
pub(crate) fn extract_description(value: &serde_json::Value) -> String {
match value {
serde_json::Value::String(s) => s.clone(),
serde_json::Value::Object(obj) => obj
.get("text")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string(),
serde_json::Value::Array(arr) => arr
.iter()
.filter_map(|v| match v {
serde_json::Value::String(s) => Some(s.as_str()),
serde_json::Value::Object(obj) => obj.get("text").and_then(|v| v.as_str()),
_ => None,
})
.collect::<Vec<_>>()
.join(""),
_ => String::new(),
}
}
use super::ContentEntry;
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,
source_slug: None,
installed_path: None,
provider_project: None,
title_suffix: None,
footer_label: None,
description,
enabled,
icon_bytes,
provider_icon: false,
provider_description: false,
path: path.to_path_buf(),
icon_lines,
}
super::packs::scan_one_pack(path, file_stem, enabled)
}
pub fn scan_resource_packs(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
let packs_dir = instances_dir
.join(instance_name)
.join(crate::storage::MINECRAFT_DIR_NAME)
.join("resourcepacks");
let read_dir = match std::fs::read_dir(&packs_dir) {
Ok(rd) => rd,
Err(_) => return Vec::new(),
};
let mut entries = Vec::new();
for entry in read_dir.flatten() {
let path = entry.path();
let file_name = match path.file_name().and_then(|n| n.to_str()) {
Some(n) => n.to_string(),
None => continue,
};
let (enabled, file_stem) = if path.is_dir() {
super::parse_enabled_stem_dir(&file_name)
} else if let Some(pair) = super::parse_enabled_stem(&file_name, ".zip") {
pair
} else {
continue;
};
entries.push(scan_one_resource_pack(&path, &file_stem, enabled));
}
entries.sort_by_cached_key(|e| e.name.to_lowercase());
entries
}
fn read_pack_metadata_from_zip(zip_path: &Path) -> (String, String, Option<Vec<u8>>) {
let Some(mut archive) = super::open_zip(zip_path) else {
return (String::new(), String::new(), None);
};
let description = read_pack_description(&mut archive);
let icon_bytes = super::read_icon_from_zip(&mut archive);
(String::new(), description, icon_bytes)
}
fn read_pack_description(archive: &mut zip::ZipArchive<std::fs::File>) -> String {
archive
.by_name("pack.mcmeta")
.ok()
.and_then(|entry| serde_json::from_reader::<_, PackMcMeta>(entry).ok())
.map(|meta| extract_description(&meta.pack.description))
.unwrap_or_default()
}
fn read_pack_metadata_from_dir(dir: &Path) -> (String, String, Option<Vec<u8>>) {
let description = std::fs::read_to_string(dir.join("pack.mcmeta"))
.ok()
.and_then(|content| serde_json::from_str::<PackMcMeta>(&content).ok())
.map(|meta| extract_description(&meta.pack.description))
.unwrap_or_default();
let icon_bytes = std::fs::read(dir.join("pack.png")).ok();
(String::new(), description, icon_bytes)
super::packs::scan_packs(instances_dir, instance_name, "resourcepacks")
}
#[cfg(test)]
mod tests {
use super::*;
use super::super::packs::extract_description;
use serde_json::json;
// every case exercises a distinct match arm in extract_description.
// string + object{text} + object{no text} + array(string) +
// array(object) + array(mixed) + array(empty) + null + number + bool.
// mutating any arm to fall through to "" would fail at least one case.
#[rstest::rstest]
#[case::string(json!("Simple pack"), "Simple pack")]
#[case::object_with_text(json!({"text": "Hello world"}), "Hello world")]
+4 -90
View File
@@ -1,99 +1,13 @@
// shader pack scanning. structurally almost identical to resource packs
// (zip or dir, pack.mcmeta for metadata, pack.png for icon)
// shader pack scanner backed by the shared pack.mcmeta reader.
use std::path::Path;
use super::mods::{ContentEntry, make_icon_pixels};
use super::resource_packs::{PackMcMeta, extract_description};
use super::ContentEntry;
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))
.or_else(|| Some(super::mods::fallback_icon()));
ContentEntry {
file_stem: file_stem.to_owned(),
name: file_stem.to_owned(),
source_slug: None,
installed_path: None,
provider_project: None,
title_suffix: None,
footer_label: None,
description,
enabled,
icon_bytes,
provider_icon: false,
provider_description: false,
path: path.to_path_buf(),
icon_lines,
}
super::packs::scan_one_pack(path, file_stem, enabled)
}
pub fn scan_shaders(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
let shaders_dir = instances_dir
.join(instance_name)
.join(crate::storage::MINECRAFT_DIR_NAME)
.join("shaderpacks");
let read_dir = match std::fs::read_dir(&shaders_dir) {
Ok(rd) => rd,
Err(_) => return Vec::new(),
};
let mut entries = Vec::new();
for entry in read_dir.flatten() {
let path = entry.path();
let file_name = match path.file_name().and_then(|n| n.to_str()) {
Some(n) => n.to_string(),
None => continue,
};
let (enabled, file_stem) = if path.is_dir() {
super::parse_enabled_stem_dir(&file_name)
} else if let Some(pair) = super::parse_enabled_stem(&file_name, ".zip") {
pair
} else {
continue;
};
entries.push(scan_one_shader(&path, &file_stem, enabled));
}
entries.sort_by_cached_key(|e| e.name.to_lowercase());
entries
}
fn read_shader_metadata_from_zip(zip_path: &Path) -> (String, Option<Vec<u8>>) {
let Some(mut archive) = super::open_zip(zip_path) else {
return (String::new(), None);
};
let description = archive
.by_name("pack.mcmeta")
.ok()
.and_then(|entry| serde_json::from_reader::<_, PackMcMeta>(entry).ok())
.map(|meta| extract_description(&meta.pack.description))
.unwrap_or_default();
let icon_bytes = super::read_icon_from_zip(&mut archive);
(description, icon_bytes)
}
fn read_shader_metadata_from_dir(dir: &Path) -> (String, Option<Vec<u8>>) {
let description = std::fs::read_to_string(dir.join("pack.mcmeta"))
.ok()
.and_then(|content| serde_json::from_str::<PackMcMeta>(&content).ok())
.map(|meta| extract_description(&meta.pack.description))
.unwrap_or_default();
let icon_bytes = std::fs::read(dir.join("pack.png")).ok();
(description, icon_bytes)
super::packs::scan_packs(instances_dir, instance_name, "shaderpacks")
}
+2 -2
View File
@@ -4,14 +4,14 @@
use std::path::Path;
use super::mods::{ContentEntry, make_icon_pixels};
use super::{ContentEntry, fallback_icon_large, 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()));
.or_else(|| Some(fallback_icon_large()));
let description = world_description(path);
+79 -6
View File
@@ -1,17 +1,91 @@
// modrinth .mrpack import: parse the manifest, download all the mods,
// and extract config/resource overrides from the zip
use std::collections::HashMap;
use std::path::Path;
use serde::Deserialize;
use crate::instance::manager::InstanceManager;
use crate::instance::models::ModLoader;
use crate::net::modrinth::MrpackIndex;
use crate::tui::progress;
use super::{ImportSummary, PackFormat};
#[derive(Debug, Clone, Deserialize)]
pub struct MrpackIndex {
#[serde(rename = "formatVersion")]
pub format_version: u32,
pub game: String,
#[serde(rename = "versionId")]
pub version_id: String,
pub name: String,
#[serde(default)]
pub dependencies: HashMap<String, String>,
#[serde(default)]
pub files: Vec<MrpackFile>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct MrpackFile {
pub path: String,
pub downloads: Vec<String>,
#[serde(rename = "fileSize")]
pub file_size: u64,
}
// .mrpack is just a zip with modrinth.index.json at the root
pub fn parse_mrpack(path: &Path) -> Result<MrpackIndex, String> {
tracing::debug!("Parsing .mrpack manifest from {}", path.display());
let file = std::fs::File::open(path).map_err(|e| format!("Cannot open .mrpack: {e}"))?;
let mut archive = zip::ZipArchive::new(file).map_err(|e| format!("Invalid ZIP: {e}"))?;
let entry = archive
.by_name("modrinth.index.json")
.map_err(|_| "Missing modrinth.index.json in .mrpack".to_string())?;
let index: MrpackIndex =
serde_json::from_reader(entry).map_err(|e| format!("Invalid manifest JSON: {e}"))?;
tracing::debug!(
"Parsed .mrpack '{}' version_id={} files={} deps={}",
index.name,
index.version_id,
index.files.len(),
index.dependencies.len()
);
Ok(index)
}
// mrpack dependencies use keys like "fabric-loader", "forge", etc.
// checks in priority order and returns the first match.
pub fn loader_from_dependencies(
deps: &HashMap<String, String>,
) -> (Option<ModLoader>, Option<String>) {
let loaders = [
("fabric-loader", ModLoader::Fabric),
("forge", ModLoader::Forge),
("neoforge", ModLoader::NeoForge),
("quilt-loader", ModLoader::Quilt),
];
for (key, loader) in &loaders {
if let Some(version) = deps.get(*key) {
tracing::trace!(
"Resolved Modrinth loader dependency {}={} as {}",
key,
version,
loader
);
return (Some(*loader), Some(version.clone()));
}
}
tracing::trace!("No Modrinth loader dependency found; treating pack as vanilla");
(None, None)
}
pub fn game_version_from_dependencies(deps: &HashMap<String, String>) -> Option<String> {
deps.get("minecraft").cloned()
}
pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
let index = crate::net::modrinth::parse_mrpack(path)?;
let index = parse_mrpack(path)?;
tracing::debug!(
"Parsed .mrpack '{}' version_id={} files={} deps={}",
index.name,
@@ -20,11 +94,10 @@ pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
index.dependencies.len()
);
let game_version = crate::net::modrinth::game_version_from_dependencies(&index.dependencies)
let game_version = game_version_from_dependencies(&index.dependencies)
.ok_or_else(|| "Manifest missing minecraft dependency".to_string())?;
let (loader_opt, loader_version) =
crate::net::modrinth::loader_from_dependencies(&index.dependencies);
let (loader_opt, loader_version) = loader_from_dependencies(&index.dependencies);
let loader = loader_opt.unwrap_or(ModLoader::Vanilla);
let override_count = count_overrides(path).unwrap_or(0);
@@ -93,7 +166,7 @@ pub async fn execute_import(
.join(crate::storage::MINECRAFT_DIR_NAME);
let result: Result<(), Box<dyn std::error::Error + Send + Sync>> = async {
let index = crate::net::modrinth::parse_mrpack(&summary.archive_path)
let index = parse_mrpack(&summary.archive_path)
.map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { e.into() })?;
download_mod_files(&index, &minecraft_dir).await?;
extract_overrides(&summary.archive_path, &minecraft_dir)?;
+38 -1
View File
@@ -1,8 +1,8 @@
use std::collections::HashMap;
use std::io::Write;
use std::path::{Path, PathBuf};
use super::*;
use crate::net::modrinth::MrpackFile;
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
@@ -53,6 +53,43 @@ fn summary_counts_both_override_roots() {
assert_eq!(summary.override_count, 2);
}
#[test]
fn dependencies_resolve_fabric_loader() {
let dependencies = HashMap::from([
("minecraft".to_owned(), "1.21.4".to_owned()),
("fabric-loader".to_owned(), "0.16.10".to_owned()),
]);
assert_eq!(
loader_from_dependencies(&dependencies),
(Some(ModLoader::Fabric), Some("0.16.10".to_owned()))
);
assert_eq!(
game_version_from_dependencies(&dependencies),
Some("1.21.4".to_owned())
);
}
#[test]
fn dependencies_resolve_forge_loader() {
let dependencies = HashMap::from([
("minecraft".to_owned(), "1.20.1".to_owned()),
("forge".to_owned(), "47.2.0".to_owned()),
]);
assert_eq!(
loader_from_dependencies(&dependencies),
(Some(ModLoader::Forge), Some("47.2.0".to_owned()))
);
}
#[test]
fn dependencies_without_a_loader_are_vanilla() {
let dependencies = HashMap::from([("minecraft".to_owned(), "1.21.4".to_owned())]);
assert_eq!(loader_from_dependencies(&dependencies), (None, None));
}
#[test]
fn extraction_merges_both_override_roots() {
let tmp = tempfile::tempdir().unwrap();
+26 -202
View File
@@ -1,9 +1,12 @@
// modrinth modpack support: fetches project metadata, downloads .mrpack files,
// and extracts loader info from pack manifests.
// modrinth api client and provider file downloads.
use serde::Deserialize;
use std::collections::HashMap;
pub use crate::instance::import::mrpack::{
MrpackFile, MrpackIndex, game_version_from_dependencies, loader_from_dependencies, parse_mrpack,
};
#[derive(Debug, Clone, Deserialize, serde::Serialize)]
pub struct ProjectInfo {
pub id: String,
@@ -41,57 +44,9 @@ pub struct VersionFile {
pub hashes: HashMap<String, String>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct MrpackIndex {
#[serde(rename = "formatVersion")]
pub format_version: u32,
pub game: String,
#[serde(rename = "versionId")]
pub version_id: String,
pub name: String,
#[serde(default)]
pub dependencies: HashMap<String, String>,
#[serde(default)]
pub files: Vec<MrpackFile>,
}
use crate::instance::{ContentKind, ModLoader};
#[derive(Debug, Clone, Deserialize)]
pub struct MrpackFile {
pub path: String,
pub downloads: Vec<String>,
#[serde(rename = "fileSize")]
pub file_size: u64,
}
use crate::instance::models::ModLoader;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiscoveryKind {
Mod,
ResourcePack,
Shader,
}
impl DiscoveryKind {
fn project_type(self) -> &'static str {
match self {
Self::Mod => "mod",
Self::ResourcePack => "resourcepack",
Self::Shader => "shader",
}
}
pub fn unavailable_message(self, loader: ModLoader) -> Option<&'static str> {
if loader != ModLoader::Vanilla {
return None;
}
match self {
Self::Mod => Some("Vanilla does not support mods."),
Self::Shader => Some("Vanilla does not support shaders."),
Self::ResourcePack => None,
}
}
}
pub type DiscoveryKind = ContentKind;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiscoveryProject {
@@ -145,7 +100,7 @@ impl From<DiscoverySearchHit> for DiscoveryProject {
pub async fn search_discovery(
client: &crate::net::HttpClient,
kind: DiscoveryKind,
kind: ContentKind,
query: &str,
game_version: &str,
loader: ModLoader,
@@ -188,12 +143,12 @@ pub async fn search_discovery(
})
}
fn discovery_facets(kind: DiscoveryKind, game_version: &str, loader: ModLoader) -> String {
let mut facets = vec![vec![format!("project_type:{}", kind.project_type())]];
fn discovery_facets(kind: ContentKind, game_version: &str, loader: ModLoader) -> String {
let mut facets = vec![vec![format!("project_type:{}", project_type(kind))]];
if !game_version.is_empty() {
facets.push(vec![format!("versions:{game_version}")]);
}
if kind == DiscoveryKind::Mod
if kind == ContentKind::Mod
&& let Some(loader) = loader_facet(loader)
{
facets.push(vec![format!("categories:{loader}")]);
@@ -201,6 +156,14 @@ fn discovery_facets(kind: DiscoveryKind, game_version: &str, loader: ModLoader)
serde_json::to_string(&facets).unwrap_or_else(|_| "[]".to_string())
}
fn project_type(kind: ContentKind) -> &'static str {
match kind {
ContentKind::Mod => "mod",
ContentKind::ResourcePack => "resourcepack",
ContentKind::Shader => "shader",
}
}
fn loader_facet(loader: ModLoader) -> Option<&'static str> {
match loader {
ModLoader::Vanilla => None,
@@ -211,36 +174,6 @@ fn loader_facet(loader: ModLoader) -> Option<&'static str> {
}
}
// mrpack dependencies use keys like "fabric-loader", "forge", etc.
// checks in priority order and returns the first match.
pub fn loader_from_dependencies(
deps: &HashMap<String, String>,
) -> (Option<ModLoader>, Option<String>) {
let loaders = [
("fabric-loader", ModLoader::Fabric),
("forge", ModLoader::Forge),
("neoforge", ModLoader::NeoForge),
("quilt-loader", ModLoader::Quilt),
];
for (key, loader) in &loaders {
if let Some(version) = deps.get(*key) {
tracing::trace!(
"Resolved Modrinth loader dependency {}={} as {}",
key,
version,
loader
);
return (Some(*loader), Some(version.clone()));
}
}
tracing::trace!("No Modrinth loader dependency found; treating pack as vanilla");
(None, None)
}
pub fn game_version_from_dependencies(deps: &HashMap<String, String>) -> Option<String> {
deps.get("minecraft").cloned()
}
const API_BASE: &str = "https://api.modrinth.com/v2";
// hand-rolled percent encoding because pulling in a crate for RFC 3986
@@ -298,7 +231,7 @@ pub async fn fetch_versions(
pub async fn fetch_content_versions(
client: &crate::net::HttpClient,
project_id: &str,
kind: DiscoveryKind,
kind: ContentKind,
game_version: &str,
loader: ModLoader,
) -> Result<Vec<VersionInfo>, crate::net::NetError> {
@@ -325,7 +258,7 @@ pub async fn fetch_content_versions(
fn content_versions_url(
api_base: &str,
project_id: &str,
kind: DiscoveryKind,
kind: ContentKind,
game_version: &str,
loader: ModLoader,
) -> String {
@@ -336,7 +269,7 @@ fn content_versions_url(
url_encode(&serde_json::to_string(&[game_version]).unwrap_or_default())
),
];
if kind == DiscoveryKind::Mod
if kind == ContentKind::Mod
&& let Some(loader) = loader_facet(loader)
{
params.push(format!(
@@ -541,26 +474,6 @@ pub async fn download_mrpack(
Ok(mrpack_path)
}
// .mrpack is just a zip with modrinth.index.json at the root
pub fn parse_mrpack(path: &std::path::Path) -> Result<MrpackIndex, String> {
tracing::debug!("Parsing .mrpack manifest from {}", path.display());
let file = std::fs::File::open(path).map_err(|e| format!("Cannot open .mrpack: {e}"))?;
let mut archive = zip::ZipArchive::new(file).map_err(|e| format!("Invalid ZIP: {e}"))?;
let entry = archive
.by_name("modrinth.index.json")
.map_err(|_| "Missing modrinth.index.json in .mrpack".to_string())?;
let index: MrpackIndex =
serde_json::from_reader(entry).map_err(|e| format!("Invalid manifest JSON: {e}"))?;
tracing::debug!(
"Parsed .mrpack '{}' version_id={} files={} deps={}",
index.name,
index.version_id,
index.files.len(),
index.dependencies.len()
);
Ok(index)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -580,7 +493,7 @@ mod tests {
#[test]
fn discovery_mod_facets_include_instance_compatibility() {
let facets = discovery_facets(DiscoveryKind::Mod, "1.21.1", ModLoader::Fabric);
let facets = discovery_facets(ContentKind::Mod, "1.21.1", ModLoader::Fabric);
assert_eq!(
serde_json::from_str::<Vec<Vec<String>>>(&facets).unwrap(),
vec![
@@ -593,39 +506,19 @@ mod tests {
#[test]
fn discovery_resource_pack_facets_do_not_require_loader() {
let facets = discovery_facets(DiscoveryKind::ResourcePack, "1.20.1", ModLoader::Forge);
let facets = discovery_facets(ContentKind::ResourcePack, "1.20.1", ModLoader::Forge);
assert_eq!(
serde_json::from_str::<Vec<Vec<String>>>(&facets).unwrap(),
vec![vec!["project_type:resourcepack"], vec!["versions:1.20.1"]]
);
}
#[test]
fn vanilla_discovery_only_supports_resource_packs() {
assert_eq!(
DiscoveryKind::Mod.unavailable_message(ModLoader::Vanilla),
Some("Vanilla does not support mods.")
);
assert_eq!(
DiscoveryKind::Shader.unavailable_message(ModLoader::Vanilla),
Some("Vanilla does not support shaders.")
);
assert_eq!(
DiscoveryKind::ResourcePack.unavailable_message(ModLoader::Vanilla),
None
);
assert_eq!(
DiscoveryKind::Mod.unavailable_message(ModLoader::Fabric),
None
);
}
#[test]
fn compatible_mod_versions_filter_by_game_and_loader() {
let url = content_versions_url(
"https://example.test/v2",
"fabric-api",
DiscoveryKind::Mod,
ContentKind::Mod,
"1.21.1",
ModLoader::Fabric,
);
@@ -640,7 +533,7 @@ mod tests {
let url = content_versions_url(
"https://example.test/v2",
"stay-true",
DiscoveryKind::ResourcePack,
ContentKind::ResourcePack,
"1.21.1",
ModLoader::Fabric,
);
@@ -781,73 +674,4 @@ mod tests {
fn url_encode_handles(#[case] input: &str, #[case] expected: &str) {
assert_eq!(url_encode(input), expected);
}
#[test]
fn loader_from_fabric_deps() {
let mut deps = HashMap::new();
deps.insert("minecraft".to_string(), "1.21.4".to_string());
deps.insert("fabric-loader".to_string(), "0.16.10".to_string());
let (loader, version) = loader_from_dependencies(&deps);
assert_eq!(loader, Some(ModLoader::Fabric));
assert_eq!(version, Some("0.16.10".to_string()));
}
#[test]
fn loader_from_forge_deps() {
let mut deps = HashMap::new();
deps.insert("minecraft".to_string(), "1.20.1".to_string());
deps.insert("forge".to_string(), "47.2.0".to_string());
let (loader, version) = loader_from_dependencies(&deps);
assert_eq!(loader, Some(ModLoader::Forge));
assert_eq!(version, Some("47.2.0".to_string()));
}
#[test]
fn loader_from_vanilla_deps() {
let mut deps = HashMap::new();
deps.insert("minecraft".to_string(), "1.21.4".to_string());
let (loader, version) = loader_from_dependencies(&deps);
assert!(loader.is_none());
assert!(version.is_none());
}
#[test]
fn game_version_from_deps() {
let mut deps = HashMap::new();
deps.insert("minecraft".to_string(), "1.21.4".to_string());
assert_eq!(
game_version_from_dependencies(&deps),
Some("1.21.4".to_string())
);
}
#[test]
fn parse_mrpack_index_json() {
let json = r#"{
"formatVersion": 1,
"game": "minecraft",
"versionId": "6.5.0",
"name": "Fabulously Optimized",
"dependencies": {
"minecraft": "1.21.4",
"fabric-loader": "0.16.10"
},
"files": [
{
"path": "mods/fabric-api.jar",
"downloads": ["https://cdn.modrinth.com/data/abc/fabric-api.jar"],
"fileSize": 12345
}
]
}"#;
let index: MrpackIndex = serde_json::from_str(json).unwrap();
assert_eq!(index.name, "Fabulously Optimized");
assert_eq!(index.version_id, "6.5.0");
assert_eq!(index.files.len(), 1);
assert_eq!(index.files[0].path, "mods/fabric-api.jar");
assert_eq!(
game_version_from_dependencies(&index.dependencies),
Some("1.21.4".to_string())
);
}
}
+3 -3
View File
@@ -112,15 +112,15 @@ impl App {
instances_state,
mods_state,
mods_discovery_state: widgets::content::DiscoveryState::new(
crate::net::modrinth::DiscoveryKind::Mod,
crate::instance::ContentKind::Mod,
),
resource_packs_state,
resource_packs_discovery_state: widgets::content::DiscoveryState::new(
crate::net::modrinth::DiscoveryKind::ResourcePack,
crate::instance::ContentKind::ResourcePack,
),
shaders_state,
shaders_discovery_state: widgets::content::DiscoveryState::new(
crate::net::modrinth::DiscoveryKind::Shader,
crate::instance::ContentKind::Shader,
),
worlds_state: widgets::content::list::ContentListState::default(),
logs_state: widgets::logs_viewer::LogsState::default(),
+23 -48
View File
@@ -34,45 +34,29 @@ impl App {
// get scanned/loaded on separate tokio tasks
self.drain_pending_instances();
self.drain_pending_last_played();
let local_streamed = self.mods_state.drain_pending();
let mods_update = self.mods_state.drain_watcher();
self.mods_state.drain_provider_icons();
self.mods_state.request_image_loads(&self.picker);
self.mods_state.drain_image_loads(&self.picker);
self.mods_discovery_state.drain_pending();
self.mods_discovery_state.list.drain_pending();
self.mods_discovery_state
.list
.request_image_loads(&self.picker);
self.mods_discovery_state
.list
.drain_image_loads(&self.picker);
let local_streamed = self.resource_packs_state.drain_pending() || local_streamed;
let resource_packs_update = self.resource_packs_state.drain_watcher();
self.resource_packs_state.drain_provider_icons();
self.resource_packs_state.request_image_loads(&self.picker);
self.resource_packs_state.drain_image_loads(&self.picker);
self.resource_packs_discovery_state.drain_pending();
self.resource_packs_discovery_state.list.drain_pending();
self.resource_packs_discovery_state
.list
.request_image_loads(&self.picker);
self.resource_packs_discovery_state
.list
.drain_image_loads(&self.picker);
let local_streamed = self.shaders_state.drain_pending() || local_streamed;
let shaders_update = self.shaders_state.drain_watcher();
self.shaders_state.drain_provider_icons();
self.shaders_state.request_image_loads(&self.picker);
self.shaders_state.drain_image_loads(&self.picker);
self.shaders_discovery_state.drain_pending();
self.shaders_discovery_state.list.drain_pending();
self.shaders_discovery_state
.list
.request_image_loads(&self.picker);
self.shaders_discovery_state
.list
.drain_image_loads(&self.picker);
let mut local_streamed = false;
let mut content_changed = false;
let mut toggles = Vec::new();
for (local, discovery) in [
(&mut self.mods_state, &mut self.mods_discovery_state),
(
&mut self.resource_packs_state,
&mut self.resource_packs_discovery_state,
),
(&mut self.shaders_state, &mut self.shaders_discovery_state),
] {
local_streamed |= local.drain_pending();
let update = local.drain_watcher();
content_changed |= update.requires_reconcile;
toggles.extend(update.toggles);
local.drain_provider_icons();
local.request_image_loads(&self.picker);
local.drain_image_loads(&self.picker);
discovery.drain_pending();
discovery.list.drain_pending();
discovery.list.request_image_loads(&self.picker);
discovery.list.drain_image_loads(&self.picker);
}
self.worlds_state.drain_pending();
self.worlds_state.drain_watcher();
self.worlds_state.request_image_loads(&self.picker);
@@ -84,15 +68,6 @@ impl App {
self.screenshots_state.drain_pending_entries();
self.screenshots_state.request_visible_loads();
self.create_screenshot_protocols();
let mut content_changed = mods_update.requires_reconcile
|| resource_packs_update.requires_reconcile
|| shaders_update.requires_reconcile;
let toggles = mods_update
.toggles
.into_iter()
.chain(resource_packs_update.toggles)
.chain(shaders_update.toggles)
.collect::<Vec<_>>();
if !toggles.is_empty() {
content_changed |= self.persist_content_toggles(&toggles);
}
+29 -96
View File
@@ -32,18 +32,9 @@ impl App {
{
return;
}
let link = match self.content_tab {
widgets::content::ContentTab::Mods => self
.mods_discovery_state
.project_link_at(event.column, event.row),
widgets::content::ContentTab::ResourcePacks => self
.resource_packs_discovery_state
.project_link_at(event.column, event.row),
widgets::content::ContentTab::Shaders => self
.shaders_discovery_state
.project_link_at(event.column, event.row),
_ => None,
};
let link = self
.active_discovery_state_mut()
.and_then(|state| state.project_link_at(event.column, event.row));
if let Some(link) = link
&& let Err(error) = open::that_detached(link)
{
@@ -232,24 +223,16 @@ impl App {
if self.focused == FocusedArea::Content
&& self.content_mode == widgets::content::ContentMode::Discover
{
let (search_active, popup_open, project_page_open) = match self.content_tab {
widgets::content::ContentTab::Mods => (
self.mods_discovery_state.search.active,
self.mods_discovery_state.version_popup.is_some(),
self.mods_discovery_state.project_page_open(),
),
widgets::content::ContentTab::ResourcePacks => (
self.resource_packs_discovery_state.search.active,
self.resource_packs_discovery_state.version_popup.is_some(),
self.resource_packs_discovery_state.project_page_open(),
),
widgets::content::ContentTab::Shaders => (
self.shaders_discovery_state.search.active,
self.shaders_discovery_state.version_popup.is_some(),
self.shaders_discovery_state.project_page_open(),
),
_ => (false, false, false),
};
let (search_active, popup_open, project_page_open) = self
.active_discovery_state_mut()
.map(|state| {
(
state.search.active,
state.version_popup.is_some(),
state.project_page_open(),
)
})
.unwrap_or_default();
if !search_active
&& !popup_open
&& !project_page_open
@@ -292,23 +275,9 @@ impl App {
}
return Ok(());
}
let handled = {
let state = match self.content_tab {
widgets::content::ContentTab::Mods => Some(&mut self.mods_discovery_state),
widgets::content::ContentTab::ResourcePacks => {
Some(&mut self.resource_packs_discovery_state)
}
widgets::content::ContentTab::Shaders => {
Some(&mut self.shaders_discovery_state)
}
_ => None,
};
if let Some(state) = state {
widgets::content::discovery::handle_key(&key_event, state)
} else {
false
}
};
let handled = self
.active_discovery_state_mut()
.is_some_and(|state| widgets::content::discovery::handle_key(&key_event, state));
if handled {
if matches!(
key_event.code,
@@ -726,7 +695,7 @@ impl App {
Some(provider) => match provider
.compatible_versions(
&request.project_id,
discovery_content_kind(kind),
kind,
&instance.game_version,
instance.loader,
)
@@ -875,18 +844,11 @@ impl App {
let Some(instance) = self.instances_state.selected_instance().cloned() else {
return;
};
let kind = match self.content_tab {
widgets::content::ContentTab::Mods => crate::net::modrinth::DiscoveryKind::Mod,
widgets::content::ContentTab::ResourcePacks => {
crate::net::modrinth::DiscoveryKind::ResourcePack
}
widgets::content::ContentTab::Shaders => crate::net::modrinth::DiscoveryKind::Shader,
_ => return,
let Some(state) = self.active_discovery_state_mut() else {
return;
};
let Some(request) = self
.active_discovery_state_mut()
.and_then(widgets::content::DiscoveryState::begin_install)
else {
let kind = state.kind;
let Some(request) = state.begin_install() else {
return;
};
let destination = self
@@ -894,23 +856,12 @@ impl App {
.instances_dir
.join(&instance.name)
.join(crate::storage::MINECRAFT_DIR_NAME)
.join(match kind {
crate::net::modrinth::DiscoveryKind::Mod => "mods",
crate::net::modrinth::DiscoveryKind::ResourcePack => "resourcepacks",
crate::net::modrinth::DiscoveryKind::Shader => "shaderpacks",
});
.join(kind.directory());
let instance_paths = crate::storage::InstancePaths::new(
self.instance_manager.instances_dir.join(&instance.name),
);
let manifest_path = instance_paths.content_manifest();
let minecraft_dir = instance_paths.minecraft();
let content_kind = match kind {
crate::net::modrinth::DiscoveryKind::Mod => crate::instance::ContentKind::Mod,
crate::net::modrinth::DiscoveryKind::ResourcePack => {
crate::instance::ContentKind::ResourcePack
}
crate::net::modrinth::DiscoveryKind::Shader => crate::instance::ContentKind::Shader,
};
tokio::spawn(async move {
let action = if request.installed_path.is_some() {
format!("Changing {} version", request.project_title)
@@ -949,7 +900,7 @@ impl App {
let fingerprint = crate::instance::content::manifest::fingerprint(&path)?;
let record = crate::instance::ContentFileRecord {
relative_path,
kind: content_kind,
kind,
enabled: !path
.file_name()
.and_then(|name| name.to_str())
@@ -1023,11 +974,8 @@ impl App {
.minecraft();
let icon_cache = crate::storage::MetadataPaths::new(&self.instance_manager.meta_dir)
.provider_icons("modrinth");
let state = match self.content_tab {
widgets::content::ContentTab::Mods => &mut self.mods_discovery_state,
widgets::content::ContentTab::ResourcePacks => &mut self.resource_packs_discovery_state,
widgets::content::ContentTab::Shaders => &mut self.shaders_discovery_state,
_ => return,
let Some(state) = self.active_discovery_state_mut() else {
return;
};
if state.unavailable_message(&instance).is_some() {
state.set_unavailable(&instance);
@@ -1062,11 +1010,8 @@ impl App {
.minecraft();
let icon_cache = crate::storage::MetadataPaths::new(&self.instance_manager.meta_dir)
.provider_icons("modrinth");
let state = match self.content_tab {
widgets::content::ContentTab::Mods => &mut self.mods_discovery_state,
widgets::content::ContentTab::ResourcePacks => &mut self.resource_packs_discovery_state,
widgets::content::ContentTab::Shaders => &mut self.shaders_discovery_state,
_ => return,
let Some(state) = self.active_discovery_state_mut() else {
return;
};
if state.unavailable_message(&instance).is_some() {
state.set_unavailable(&instance);
@@ -1090,7 +1035,7 @@ impl App {
fn spawn_discovery_request(
instance: crate::instance::InstanceConfig,
kind: crate::net::modrinth::DiscoveryKind,
kind: crate::instance::ContentKind,
query: String,
manifest: Option<crate::instance::ContentManifest>,
minecraft_dir: std::path::PathBuf,
@@ -1113,7 +1058,7 @@ impl App {
Some(provider) => {
provider
.search(
discovery_content_kind(kind),
kind,
&query,
&instance,
offset,
@@ -1282,18 +1227,6 @@ impl App {
}
}
fn discovery_content_kind(
kind: crate::net::modrinth::DiscoveryKind,
) -> crate::instance::ContentKind {
match kind {
crate::net::modrinth::DiscoveryKind::Mod => crate::instance::ContentKind::Mod,
crate::net::modrinth::DiscoveryKind::ResourcePack => {
crate::instance::ContentKind::ResourcePack
}
crate::net::modrinth::DiscoveryKind::Shader => crate::instance::ContentKind::Shader,
}
}
fn delete_content_path(path: &std::path::Path) -> std::io::Result<()> {
match std::fs::metadata(path) {
Ok(meta) if meta.is_dir() => std::fs::remove_dir_all(path),
+3 -3
View File
@@ -57,15 +57,15 @@ impl UiHarness {
instances_state: widgets::instances::State::default(),
mods_state: widgets::content::ContentListState::default(),
mods_discovery_state: widgets::content::DiscoveryState::new(
crate::net::modrinth::DiscoveryKind::Mod,
crate::instance::ContentKind::Mod,
),
resource_packs_state: widgets::content::ContentListState::default(),
resource_packs_discovery_state: widgets::content::DiscoveryState::new(
crate::net::modrinth::DiscoveryKind::ResourcePack,
crate::instance::ContentKind::ResourcePack,
),
shaders_state: widgets::content::ContentListState::default(),
shaders_discovery_state: widgets::content::DiscoveryState::new(
crate::net::modrinth::DiscoveryKind::Shader,
crate::instance::ContentKind::Shader,
),
worlds_state: widgets::content::ContentListState::default(),
screenshots_state: {
+23 -19
View File
@@ -72,7 +72,7 @@ fn install_and_change_version_popups_only_differ_in_title() {
icon_url: None,
icon_bytes: None,
};
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
let mut state = DiscoveryState::new(ContentKind::Mod);
state
.list
.entries
@@ -104,7 +104,7 @@ fn compatible_versions_populate_the_open_popup() {
icon_url: None,
icon_bytes: None,
};
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
let mut state = DiscoveryState::new(ContentKind::Mod);
state.list.entries.push(project_entry(project, None));
state.list.list_state.selected = Some(0);
let request = state.begin_versions().unwrap();
@@ -136,7 +136,7 @@ fn project_page_loads_for_the_selected_discovery_entry() {
icon_url: None,
icon_bytes: None,
};
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
let mut state = DiscoveryState::new(ContentKind::Mod);
state.list.entries.push(project_entry(project, None));
state.list.list_state.selected = Some(0);
@@ -174,7 +174,7 @@ fn project_page_loads_for_the_selected_discovery_entry() {
#[test]
fn project_page_navigation_is_bounded_and_can_go_back() {
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
let mut state = DiscoveryState::new(ContentKind::Mod);
state.project_page = Some(ProjectPageState {
request_id: 1,
project_id: "project".to_owned(),
@@ -215,7 +215,7 @@ fn confirmation_can_return_to_version_selection() {
icon_url: None,
icon_bytes: None,
};
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
let mut state = DiscoveryState::new(ContentKind::Mod);
state.list.entries.push(project_entry(project, None));
state.list.list_state.selected = Some(0);
let request = state.begin_versions().unwrap();
@@ -252,7 +252,7 @@ fn discovery_delete_only_clears_the_matching_installed_badge() {
icon_url: None,
icon_bytes: None,
};
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
let mut state = DiscoveryState::new(ContentKind::Mod);
state
.list
.entries
@@ -295,7 +295,7 @@ fn successful_install_marks_the_project_and_closes_the_popup() {
icon_url: None,
icon_bytes: None,
};
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
let mut state = DiscoveryState::new(ContentKind::Mod);
state.list.entries.push(project_entry(project, None));
state.list.list_state.selected = Some(0);
let versions_request = state.begin_versions().unwrap();
@@ -350,7 +350,7 @@ fn installed_labels_follow_exact_manifest_projects() {
icon_url: None,
icon_bytes: None,
};
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
let mut state = DiscoveryState::new(ContentKind::Mod);
state.list.entries.push(project_entry(project, None));
let mut manifest = crate::instance::ContentManifest::default();
@@ -392,7 +392,7 @@ fn installed_labels_follow_exact_manifest_projects() {
#[test]
fn changing_instance_invalidates_results() {
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
let mut state = DiscoveryState::new(ContentKind::Mod);
let first = instance("one", "1.21.1");
let second = instance("two", "1.21.1");
let _request = state.begin_search(&first);
@@ -403,7 +403,7 @@ fn changing_instance_invalidates_results() {
#[test]
fn unavailable_vanilla_discovery_clears_cached_results() {
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
let mut state = DiscoveryState::new(ContentKind::Mod);
state.list.entries.push(project_entry(
DiscoveryProject {
id: "cached".to_owned(),
@@ -418,6 +418,10 @@ fn unavailable_vanilla_discovery_clears_cached_results() {
));
let mut vanilla = instance("vanilla", "1.21.1");
vanilla.loader = ModLoader::Vanilla;
assert_eq!(
state.unavailable_message(&vanilla),
Some("Vanilla does not support mods.")
);
state.set_unavailable(&vanilla);
@@ -428,7 +432,7 @@ fn unavailable_vanilla_discovery_clears_cached_results() {
#[test]
fn changing_instance_compatibility_invalidates_results() {
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
let mut state = DiscoveryState::new(ContentKind::Mod);
let original = instance("one", "1.21.1");
let mut other_version = original.clone();
other_version.game_version = "1.20.1".to_owned();
@@ -442,7 +446,7 @@ fn changing_instance_compatibility_invalidates_results() {
#[test]
fn stale_search_result_is_ignored() {
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
let mut state = DiscoveryState::new(ContentKind::Mod);
let instance = instance("one", "1.21.1");
let old = state.begin_search(&instance);
let _new = state.begin_search(&instance);
@@ -464,7 +468,7 @@ fn stale_search_result_is_ignored() {
#[test]
fn next_page_prefetches_before_selection_reaches_the_end() {
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
let mut state = DiscoveryState::new(ContentKind::Mod);
state.set_viewport_rows(30);
let instance = instance("one", "1.21.1");
let first = state.begin_search(&instance);
@@ -502,7 +506,7 @@ fn next_page_prefetches_before_selection_reaches_the_end() {
#[test]
fn large_page_fills_a_tall_viewport_without_another_request() {
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
let mut state = DiscoveryState::new(ContentKind::Mod);
state.set_viewport_rows(90);
let first = state.begin_search(&instance("one", "1.21.1"));
for index in 0..PAGE_SIZE {
@@ -536,7 +540,7 @@ fn large_page_fills_a_tall_viewport_without_another_request() {
#[test]
fn typing_keeps_loaded_results_until_remote_search_is_due() {
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
let mut state = DiscoveryState::new(ContentKind::Mod);
let request = state.begin_search(&instance("one", "1.21.1"));
for title in ["Sodium", "Lithium"] {
assert!(request.stream.send(project_entry(
@@ -574,7 +578,7 @@ fn typing_keeps_loaded_results_until_remote_search_is_due() {
#[test]
fn search_refresh_keeps_rows_until_the_diff_arrives() {
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
let mut state = DiscoveryState::new(ContentKind::Mod);
let instance = instance("one", "1.21.1");
let initial = state.begin_search(&instance);
for title in ["Sodium", "Lithium"] {
@@ -606,7 +610,7 @@ fn search_refresh_keeps_rows_until_the_diff_arrives() {
#[test]
fn pagination_continues_across_multiple_pages() {
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
let mut state = DiscoveryState::new(ContentKind::Mod);
let instance = instance("one", "1.21.1");
let first = state.begin_search(&instance);
for index in 0..PAGE_SIZE {
@@ -670,7 +674,7 @@ fn pagination_continues_across_multiple_pages() {
#[test]
fn permanent_pagination_failure_stops_without_discarding_loaded_entries() {
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
let mut state = DiscoveryState::new(ContentKind::Mod);
let first = state.begin_search(&instance("one", "1.21.1"));
for index in 0..PAGE_SIZE {
assert!(first.stream.upsert(project_entry(
@@ -717,7 +721,7 @@ fn permanent_pagination_failure_stops_without_discarding_loaded_entries() {
#[test]
fn transient_pagination_failure_retries_the_same_offset_after_a_delay() {
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
let mut state = DiscoveryState::new(ContentKind::Mod);
let first = state.begin_search(&instance("one", "1.21.1"));
DiscoveryState::push_result(
&first.pending,
+25 -4
View File
@@ -4,7 +4,7 @@ use std::{
sync::{Arc, Mutex},
};
use crate::instance::content::mods::ContentEntry;
use crate::instance::ContentEntry;
use ratatui::{
buffer::Buffer,
layout::Rect,
@@ -38,6 +38,27 @@ fn entry(name: &str) -> ContentEntry {
}
}
#[test]
fn toggling_a_selected_entry_renames_and_updates_it() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("example.jar");
std::fs::write(&path, b"mod").unwrap();
let mut content = entry("Example");
content.path = path.clone();
let mut state = ContentListState::default();
state.entries.push(content);
state.list_state.selected = Some(0);
state.toggle_selected();
assert!(!path.exists());
assert_eq!(
state.entries[0].path,
temp.path().join("example.jar.disabled")
);
assert!(!state.entries[0].enabled);
}
#[test]
fn content_watcher_ignores_file_access_events() {
assert_eq!(
@@ -295,14 +316,14 @@ fn source_refresh_reconciles_without_rebuilding_unchanged_entries() {
fn provider_icons_are_requested_only_for_visible_missing_icons() {
let mut state = ContentListState::default();
let mut visible = entry("Visible");
visible.icon_lines = Some(crate::instance::content::mods::fallback_icon());
visible.icon_lines = Some(crate::instance::content::fallback_icon());
visible.provider_project = Some(crate::instance::ProviderProject {
provider: "modrinth".to_owned(),
project_id: "visible-project".to_owned(),
version_id: "version".to_owned(),
});
let mut offscreen = entry("Offscreen");
offscreen.icon_lines = Some(crate::instance::content::mods::fallback_icon());
offscreen.icon_lines = Some(crate::instance::content::fallback_icon());
offscreen.provider_project = Some(crate::instance::ProviderProject {
provider: "modrinth".to_owned(),
project_id: "offscreen-project".to_owned(),
@@ -322,7 +343,7 @@ fn embedded_icons_do_not_request_provider_fallbacks() {
let mut state = ContentListState::default();
let mut visible = entry("Visible");
visible.icon_bytes = Some(vec![1, 2, 3]);
visible.icon_lines = Some(crate::instance::content::mods::fallback_icon());
visible.icon_lines = Some(crate::instance::content::fallback_icon());
visible.provider_project = Some(crate::instance::ProviderProject {
provider: "modrinth".to_owned(),
project_id: "visible-project".to_owned(),
+5 -6
View File
@@ -3,9 +3,8 @@ use std::sync::{Arc, Mutex};
use crossterm::event::{KeyCode, KeyEvent};
use crate::instance::content::mods::ContentEntry;
use crate::instance::{InstanceConfig, ModLoader};
use crate::net::modrinth::{DiscoveryKind, DiscoveryProject, VersionInfo};
use crate::instance::{ContentEntry, ContentKind, InstanceConfig, ModLoader};
use crate::net::modrinth::{DiscoveryProject, VersionInfo};
use super::list::{ContentListState, ContentStream};
@@ -159,7 +158,7 @@ pub enum DiscoveryActionResult {
pub(crate) type PendingActions = Arc<Mutex<Vec<DiscoveryActionResult>>>;
pub struct DiscoveryState {
pub kind: DiscoveryKind,
pub kind: ContentKind,
pub list: ContentListState,
pub search: crate::tui::widgets::search::SearchState,
pub total_hits: usize,
@@ -184,7 +183,7 @@ pub struct DiscoveryState {
}
impl DiscoveryState {
pub fn new(kind: DiscoveryKind) -> Self {
pub fn new(kind: ContentKind) -> Self {
Self {
kind,
list: ContentListState::default(),
@@ -859,7 +858,7 @@ pub(crate) fn project_entry(
provider_icon,
provider_description: false,
path: PathBuf::from(project.id),
icon_lines: Some(crate::instance::content::mods::fallback_icon()),
icon_lines: Some(crate::instance::content::fallback_icon()),
}
}
+22 -65
View File
@@ -20,7 +20,7 @@ use ratatui_image::{CropOptions, Resize, StatefulImage, protocol::StatefulProtoc
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
use crate::config::theme::THEME;
use crate::instance::content::mods::{ContentEntry, IconCell};
use crate::instance::content::{ContentEntry, IconCell};
type ScanOneFn = fn(&Path, &str, bool) -> ContentEntry;
static PROVIDER_ICON_SLOTS: LazyLock<Arc<tokio::sync::Semaphore>> =
@@ -249,7 +249,7 @@ impl ContentListState {
if entry.provider_project.take().is_some() {
if entry.provider_icon {
entry.icon_bytes = None;
entry.icon_lines = Some(crate::instance::content::mods::fallback_icon());
entry.icon_lines = Some(crate::instance::content::fallback_icon());
entry.provider_icon = false;
invalidated_icons.push(entry.file_stem.clone());
}
@@ -268,7 +268,7 @@ impl ContentListState {
if entry.provider_project != project {
if entry.provider_icon {
entry.icon_bytes = None;
entry.icon_lines = Some(crate::instance::content::mods::fallback_icon());
entry.icon_lines = Some(crate::instance::content::fallback_icon());
entry.provider_icon = false;
invalidated_icons.push(entry.file_stem.clone());
}
@@ -524,18 +524,18 @@ impl ContentListState {
return PendingContentImage {
file_stem,
path,
icon_lines: crate::instance::content::mods::fallback_icon(),
icon_lines: crate::instance::content::fallback_icon(),
image: None,
};
};
let icon_lines = if use_quadrants {
crate::instance::content::mods::make_icon_quadrants_from_image(
crate::instance::content::make_icon_quadrants_from_image(
&image,
columns,
rows as u16,
)
} else {
crate::instance::content::mods::make_icon_pixels_from_image(
crate::instance::content::make_icon_pixels_from_image(
&image,
columns,
rows as u16,
@@ -1161,37 +1161,18 @@ impl ContentListState {
let Some(entry) = self.entries.get(index) else {
return;
};
let new_path = if entry.enabled {
let fname = match entry.path.file_name().and_then(|n| n.to_str()) {
Some(n) => n,
None => return,
};
let mut p = entry.path.clone();
p.set_file_name(format!("{fname}.disabled"));
p
} else {
let fname = match entry.path.file_name().and_then(|n| n.to_str()) {
Some(n) => n,
None => return,
};
let mut p = entry.path.clone();
p.set_file_name(fname.trim_end_matches(".disabled"));
p
};
match std::fs::rename(&entry.path, &new_path) {
Ok(()) => {
match crate::instance::content::toggle_entry_path(entry) {
Ok(Some(new_path)) => {
let entry = &mut self.entries[index];
entry.enabled = !entry.enabled;
entry.path = new_path;
}
Ok(None) => {}
Err(e) => {
tracing::error!(
"Failed to toggle '{}' from {} to {}: {}",
"Failed to toggle '{}' at {}: {}",
entry.file_stem,
entry.path.display(),
new_path.display(),
e
);
}
@@ -1329,42 +1310,18 @@ async fn load_provider_metadata(
}
pub fn handle_key_no_toggle(key_event: &KeyEvent, state: &mut ContentListState) -> bool {
if handle_search_keys(key_event, state) {
return true;
}
let filtered = state.filtered_indices();
let count = filtered.len();
match key_event.code {
KeyCode::Char('j') | KeyCode::Down => {
if count == 0 {
return true;
}
let current = state.list_state.selected.unwrap_or(0);
state.list_state.selected = Some((current + 1).min(count - 1));
state.update_scrollbar();
true
}
KeyCode::Char('k') | KeyCode::Up => {
let current = state.list_state.selected.unwrap_or(0);
state.list_state.selected = Some(current.saturating_sub(1));
state.update_scrollbar();
true
}
KeyCode::Enter if key_event.modifiers.contains(KeyModifiers::SHIFT) => {
if let Some(&real_idx) = state.list_state.selected.and_then(|i| filtered.get(i))
&& let Some(dir) = state.entries[real_idx].path.parent()
&& let Err(e) = open::that_detached(dir)
{
tracing::error!("Failed to open directory: {}", e);
}
true
}
_ => false,
}
handle_key_inner(key_event, state, false)
}
pub fn handle_key(key_event: &KeyEvent, state: &mut ContentListState) -> bool {
handle_key_inner(key_event, state, true)
}
fn handle_key_inner(
key_event: &KeyEvent,
state: &mut ContentListState,
toggle_on_enter: bool,
) -> bool {
if handle_search_keys(key_event, state) {
return true;
}
@@ -1396,7 +1353,7 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut ContentListState) -> bool {
}
true
}
KeyCode::Enter => {
KeyCode::Enter if toggle_on_enter => {
if let Some(&real_idx) = state.list_state.selected.and_then(|i| filtered.get(i)) {
state.list_state.selected = Some(real_idx);
state.toggle_selected();
@@ -1998,7 +1955,7 @@ fn ellipsize(text: &str, max_width: usize) -> String {
}
fn protocol_icon_columns(
entry: &crate::instance::content::mods::ContentEntry,
entry: &crate::instance::ContentEntry,
picker: &ratatui_image::picker::Picker,
) -> u16 {
let rows = entry.icon_lines.as_ref().map_or(3, Vec::len) as u16;
@@ -2124,7 +2081,7 @@ fn diff_event_paths(
fn watcher_diff(
toggled: Vec<(String, bool, std::path::PathBuf)>,
removed: Vec<String>,
added: Vec<crate::instance::content::mods::ContentEntry>,
added: Vec<crate::instance::ContentEntry>,
) -> Option<WatcherDiff> {
if toggled.is_empty() && removed.is_empty() && added.is_empty() {
None
+113 -132
View File
@@ -17,6 +17,17 @@ use crate::tui::widgets::content::{ContentMode, DiscoveryState};
use crate::tui::widgets::styled_title;
type ContentScanner = fn(&std::path::Path, &str, bool) -> crate::instance::ContentEntry;
#[derive(Clone, Copy)]
struct DownloadableTab {
directory: &'static str,
extension: &'static str,
scanner: ContentScanner,
loading_text: &'static str,
empty_text: &'static str,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum ContentTab {
#[default]
@@ -79,6 +90,33 @@ impl ContentTab {
pub fn previous_for_mode(self, mode: ContentMode) -> Self {
cycle_tab(self, visible_tabs(mode), false)
}
fn downloadable(self) -> Option<DownloadableTab> {
match self {
Self::Mods => Some(DownloadableTab {
directory: "mods",
extension: ".jar",
scanner: crate::instance::scan_one_mod,
loading_text: "Loading mods...",
empty_text: "No mods installed.",
}),
Self::ResourcePacks => Some(DownloadableTab {
directory: "resourcepacks",
extension: ".zip",
scanner: crate::instance::scan_one_resource_pack,
loading_text: "Loading resource packs...",
empty_text: "No resource packs installed.",
}),
Self::Shaders => Some(DownloadableTab {
directory: "shaderpacks",
extension: ".zip",
scanner: crate::instance::scan_one_shader,
loading_text: "Loading shaders...",
empty_text: "No shaders installed.",
}),
_ => None,
}
}
}
fn visible_tabs(mode: ContentMode) -> &'static [ContentTab] {
@@ -340,140 +378,31 @@ pub fn render(
content_area =
crate::tui::widgets::popups::render_keybind_overflow(frame, content_area, &keybind_lines);
let downloadable_state = match tab {
ContentTab::Mods => Some((mods_state, mods_discovery_state)),
ContentTab::ResourcePacks => Some((resource_packs_state, resource_packs_discovery_state)),
ContentTab::Shaders => Some((shaders_state, shaders_discovery_state)),
_ => None,
};
if let Some((state, discovery_state)) = downloadable_state {
render_downloadable(
frame,
content_area,
instance,
state,
discovery_state,
tab.downloadable().expect("downloadable tab config"),
mode,
is_focused,
instances_dir,
picker,
);
return;
}
// lazy-load: only scan when switching to an instance that hasn't been loaded yet
match tab {
ContentTab::Mods => {
if let Some(instance) = instance {
if mods_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
let content_dir = instances_dir
.join(&instance.name)
.join(crate::storage::MINECRAFT_DIR_NAME)
.join("mods");
mods_state.start_load(
&content_dir,
&instance.name,
crate::instance::scan_one_mod,
".jar",
);
mods_state.watch_dir(content_dir);
}
if mode == ContentMode::Discover {
render_discovery(
frame,
content_area,
mods_discovery_state,
instance,
is_focused,
"Searching Modrinth...",
picker,
);
} else {
super::list::render(
frame,
content_area,
mods_state,
is_focused,
"Loading mods...",
"No mods installed.",
picker,
);
}
} else {
frame.render_widget(
Paragraph::new("No instance selected.")
.style(Style::default().fg(theme.text_dim())),
content_area,
);
}
}
ContentTab::ResourcePacks => {
if let Some(instance) = instance {
if resource_packs_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
let content_dir = instances_dir
.join(&instance.name)
.join(crate::storage::MINECRAFT_DIR_NAME)
.join("resourcepacks");
resource_packs_state.start_load(
&content_dir,
&instance.name,
crate::instance::scan_one_resource_pack,
".zip",
);
resource_packs_state.watch_dir(content_dir);
}
if mode == ContentMode::Discover {
render_discovery(
frame,
content_area,
resource_packs_discovery_state,
instance,
is_focused,
"Searching Modrinth...",
picker,
);
} else {
super::list::render(
frame,
content_area,
resource_packs_state,
is_focused,
"Loading resource packs...",
"No resource packs installed.",
picker,
);
}
} else {
frame.render_widget(
Paragraph::new("No instance selected.")
.style(Style::default().fg(theme.text_dim())),
content_area,
);
}
}
ContentTab::Shaders => {
if let Some(instance) = instance {
if shaders_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
let content_dir = instances_dir
.join(&instance.name)
.join(crate::storage::MINECRAFT_DIR_NAME)
.join("shaderpacks");
shaders_state.start_load(
&content_dir,
&instance.name,
crate::instance::scan_one_shader,
".zip",
);
shaders_state.watch_dir(content_dir);
}
if mode == ContentMode::Discover {
render_discovery(
frame,
content_area,
shaders_discovery_state,
instance,
is_focused,
"Searching Modrinth...",
picker,
);
} else {
super::list::render(
frame,
content_area,
shaders_state,
is_focused,
"Loading shaders...",
"No shaders installed.",
picker,
);
}
} else {
frame.render_widget(
Paragraph::new("No instance selected.")
.style(Style::default().fg(theme.text_dim())),
content_area,
);
}
}
ContentTab::Mods | ContentTab::ResourcePacks | ContentTab::Shaders => unreachable!(),
ContentTab::Logs => {
if let Some(instance) = instance {
if logs_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
@@ -547,6 +476,58 @@ pub fn render(
}
}
#[allow(clippy::too_many_arguments)]
fn render_downloadable(
frame: &mut Frame,
area: Rect,
instance: Option<&crate::instance::InstanceConfig>,
state: &mut super::list::ContentListState,
discovery_state: &mut DiscoveryState,
tab: DownloadableTab,
mode: ContentMode,
is_focused: bool,
instances_dir: &std::path::Path,
picker: &ratatui_image::picker::Picker,
) {
let Some(instance) = instance else {
frame.render_widget(
Paragraph::new("No instance selected.")
.style(Style::default().fg(THEME.as_ref().text_dim())),
area,
);
return;
};
if state.loaded_for.as_deref() != Some(instance.name.as_str()) {
let content_dir = instances_dir
.join(&instance.name)
.join(crate::storage::MINECRAFT_DIR_NAME)
.join(tab.directory);
state.start_load(&content_dir, &instance.name, tab.scanner, tab.extension);
state.watch_dir(content_dir);
}
if mode == ContentMode::Discover {
render_discovery(
frame,
area,
discovery_state,
instance,
is_focused,
"Searching Modrinth...",
picker,
);
} else {
super::list::render(
frame,
area,
state,
is_focused,
tab.loading_text,
tab.empty_text,
picker,
);
}
}
fn render_discovery(
frame: &mut Frame,
area: Rect,
+1 -1
View File
@@ -25,7 +25,7 @@ use unicode_segmentation::UnicodeSegmentation;
use crate::config::settings::ImageProtocol;
use crate::config::theme::THEME;
use crate::instance::content::mods::{
use crate::instance::content::{
IconCell, fallback_icon, make_icon_pixels_from_image, make_icon_quadrants_from_image,
};
@@ -1,8 +1,8 @@
// rendering for the modpack import wizard. same pattern as new_instance:
// snapshot the state, pick the right step renderer, done.
use super::super::LoadState;
use super::super::base::PopupFrame;
use super::super::new_instance::LoadState;
use super::state::{IMPORT_STATE, ImportStep, ImportWizardState};
use crate::config::theme::THEME;
use crate::tui::app::FocusedArea;
@@ -3,7 +3,7 @@
// (.mrpack, mmc/prism zips). remote packs go through version selection,
// local files skip straight to the confirm step.
use super::super::new_instance::LoadState;
use super::super::LoadState;
use crate::instance::import::{ImportInput, ImportSummary, parse_import_input};
use crate::net::modrinth::{self, VersionInfo};
use crate::tui::widgets::instances;
+8
View File
@@ -0,0 +1,8 @@
#[derive(Debug, Clone, Default)]
pub enum LoadState<T> {
#[default]
Idle,
Loading,
Loaded(T),
Error(String),
}
+3
View File
@@ -5,8 +5,11 @@ pub mod base;
pub mod confirm;
pub mod error;
pub mod import_modpack;
mod load_state;
pub mod new_instance;
pub use load_state::LoadState;
use ratatui::{
Frame,
layout::{Alignment, Constraint, Layout, Rect},
+2 -1
View File
@@ -1,9 +1,10 @@
mod render;
mod state;
pub use super::LoadState;
pub(crate) use render::render_select_list;
pub use render::{popup_rect, render};
pub use state::{LoadState, WizardParams, WizardState, WizardStep, handle_key, take_result};
pub use state::{WizardParams, WizardState, WizardStep, handle_key, take_result};
#[cfg(test)]
pub(crate) fn reset_for_test() {
@@ -1,9 +1,10 @@
// rendering for the new instance wizard. each step gets its own render fn
// and the popup resizes itself based on which step is active.
use super::super::LoadState;
use super::state::{
LoadState, WIZARD_STATE, WizardState, WizardStep, clamp_loader_version_index,
clamp_version_index, ensure_loader_versions_loaded, ensure_versions_loaded, visible_versions,
WIZARD_STATE, WizardState, WizardStep, clamp_loader_version_index, clamp_version_index,
ensure_loader_versions_loaded, ensure_versions_loaded, visible_versions,
};
use crate::config::theme::THEME;
use crate::instance::models::ModLoader;
+2 -9
View File
@@ -12,6 +12,8 @@ use std::sync::LazyLock;
use std::sync::{Arc, Mutex};
use tui_prompts::{FocusState, State as PromptState, TextState};
use super::super::LoadState;
pub(crate) static WIZARD_STATE: LazyLock<Arc<Mutex<WizardState>>> =
LazyLock::new(|| Arc::new(Mutex::new(WizardState::default())));
// populated on confirm, consumed by the main event loop to actually create the instance
@@ -36,15 +38,6 @@ pub enum WizardStep {
Confirm,
}
#[derive(Debug, Clone, Default)]
pub enum LoadState<T> {
#[default]
Idle,
Loading,
Loaded(T),
Error(String),
}
#[derive(Debug, Clone)]
pub struct WizardState {
pub step: WizardStep,