refactor: upgrade crates and restructure project
This commit is contained in:
1 parent
ea093c044f
commit
47dad69321
80 files changed
+6094
-6125
No files matched your search
@@ -0,0 +1,51 @@
|
||||
pub mod mods;
|
||||
pub mod resource_packs;
|
||||
pub mod shaders;
|
||||
pub mod worlds;
|
||||
|
||||
pub use mods::{scan_mods, toggle_entry, ContentEntry};
|
||||
pub use resource_packs::scan_resource_packs;
|
||||
pub use shaders::scan_shaders;
|
||||
pub use worlds::scan_worlds;
|
||||
|
||||
use std::io::Read;
|
||||
|
||||
/// Determine enabled/disabled state and file stem from a filename.
|
||||
///
|
||||
/// Given the file extension (e.g. ".jar", ".zip") and the file name, returns
|
||||
/// `Some((enabled, file_stem))` or `None` if the file doesn't match.
|
||||
pub(crate) fn parse_enabled_stem(file_name: &str, ext: &str) -> Option<(bool, String)> {
|
||||
let disabled_ext = format!("{ext}.disabled");
|
||||
if let Some(stem) = file_name.strip_suffix(&disabled_ext) {
|
||||
Some((false, stem.to_string()))
|
||||
} else if let Some(stem) = file_name.strip_suffix(ext) {
|
||||
Some((true, stem.to_string()))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// For directories: check if the name ends in `.disabled`.
|
||||
pub(crate) fn parse_enabled_stem_dir(file_name: &str) -> (bool, String) {
|
||||
if let Some(stem) = file_name.strip_suffix(".disabled") {
|
||||
(false, stem.to_string())
|
||||
} else {
|
||||
(true, file_name.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// Read icon bytes from a zip archive (pack.png).
|
||||
pub(crate) fn read_icon_from_zip(
|
||||
archive: &mut zip::ZipArchive<std::fs::File>,
|
||||
) -> Option<Vec<u8>> {
|
||||
let mut entry = archive.by_name("pack.png").ok()?;
|
||||
let mut buf = Vec::new();
|
||||
entry.read_to_end(&mut buf).ok()?;
|
||||
Some(buf)
|
||||
}
|
||||
|
||||
/// Open a zip file and return the archive handle.
|
||||
pub(crate) fn open_zip(path: &std::path::Path) -> Option<zip::ZipArchive<std::fs::File>> {
|
||||
let file = std::fs::File::open(path).ok()?;
|
||||
zip::ZipArchive::new(file).ok()
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
/// A single icon cell representing two vertically stacked pixels using the "▄" half-block.
|
||||
/// `bg_*` = top pixel (background color), `fg_*` = bottom pixel (foreground color).
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct IconCell {
|
||||
pub bg_r: u8,
|
||||
pub bg_g: u8,
|
||||
pub bg_b: u8,
|
||||
pub fg_r: u8,
|
||||
pub fg_g: u8,
|
||||
pub fg_b: u8,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ContentEntry {
|
||||
pub file_stem: String,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub enabled: bool,
|
||||
pub icon_bytes: Option<Vec<u8>>,
|
||||
pub path: PathBuf,
|
||||
pub icon_lines: Option<Vec<Vec<IconCell>>>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
struct FabricModJson {
|
||||
#[serde(default)]
|
||||
name: String,
|
||||
#[serde(default)]
|
||||
description: String,
|
||||
#[serde(default)]
|
||||
icon: serde_json::Value,
|
||||
}
|
||||
|
||||
impl FabricModJson {
|
||||
fn icon_path(&self) -> String {
|
||||
match &self.icon {
|
||||
serde_json::Value::String(s) => s.clone(),
|
||||
serde_json::Value::Object(map) => map
|
||||
.values()
|
||||
.find_map(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_owned(),
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn scan_mods(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
|
||||
let mods_dir = instances_dir
|
||||
.join(instance_name)
|
||||
.join(".minecraft")
|
||||
.join("mods");
|
||||
|
||||
let read_dir = match std::fs::read_dir(&mods_dir) {
|
||||
Ok(read_dir) => read_dir,
|
||||
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(|name| name.to_str()) {
|
||||
Some(name) => name.to_string(),
|
||||
None => continue,
|
||||
};
|
||||
|
||||
let Some((enabled, file_stem)) = super::parse_enabled_stem(&file_name, ".jar") else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let (name, description, icon_bytes) = read_mod_metadata(&path);
|
||||
let icon_lines = icon_bytes
|
||||
.as_ref()
|
||||
.and_then(|bytes| make_icon_pixels(bytes, 6, 3))
|
||||
.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
|
||||
}
|
||||
|
||||
fn read_mod_metadata(jar_path: &Path) -> (String, String, Option<Vec<u8>>) {
|
||||
let file = match std::fs::File::open(jar_path) {
|
||||
Ok(file) => file,
|
||||
Err(_) => return (String::new(), String::new(), None),
|
||||
};
|
||||
|
||||
let mut archive = match zip::ZipArchive::new(file) {
|
||||
Ok(archive) => archive,
|
||||
Err(_) => return (String::new(), String::new(), None),
|
||||
};
|
||||
|
||||
if let Some((name, description, icon_path)) = read_fabric_meta(&mut archive) {
|
||||
let icon_bytes = if icon_path.is_empty() {
|
||||
None
|
||||
} else {
|
||||
read_zip_bytes(&mut archive, &icon_path)
|
||||
};
|
||||
return (name, description, icon_bytes);
|
||||
}
|
||||
|
||||
let icon_bytes = read_zip_bytes(&mut archive, "pack.png");
|
||||
(String::new(), String::new(), icon_bytes)
|
||||
}
|
||||
|
||||
fn read_fabric_meta(
|
||||
archive: &mut zip::ZipArchive<std::fs::File>,
|
||||
) -> Option<(String, String, String)> {
|
||||
let mut entry = archive.by_name("fabric.mod.json").ok()?;
|
||||
let mut raw = String::new();
|
||||
entry.read_to_string(&mut raw).ok()?;
|
||||
// Some mods have literal newlines in JSON strings — sanitize them
|
||||
let sanitized = sanitize_json_strings(&raw);
|
||||
let data: FabricModJson = serde_json::from_str(&sanitized).ok()?;
|
||||
let icon = data.icon_path();
|
||||
Some((data.name, data.description, icon))
|
||||
}
|
||||
|
||||
/// Replace literal control characters inside JSON string values with escaped versions.
|
||||
fn sanitize_json_strings(input: &str) -> String {
|
||||
let mut result = String::with_capacity(input.len());
|
||||
let mut in_string = false;
|
||||
let mut escape_next = false;
|
||||
|
||||
for ch in input.chars() {
|
||||
if escape_next {
|
||||
result.push(ch);
|
||||
escape_next = false;
|
||||
continue;
|
||||
}
|
||||
if ch == '\\' && in_string {
|
||||
result.push(ch);
|
||||
escape_next = true;
|
||||
continue;
|
||||
}
|
||||
if ch == '"' {
|
||||
in_string = !in_string;
|
||||
result.push(ch);
|
||||
continue;
|
||||
}
|
||||
if in_string && ch == '\n' {
|
||||
result.push_str("\\n");
|
||||
} else if in_string && ch == '\r' {
|
||||
result.push_str("\\r");
|
||||
} else if in_string && ch == '\t' {
|
||||
result.push_str("\\t");
|
||||
} else {
|
||||
result.push(ch);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn read_zip_bytes(archive: &mut zip::ZipArchive<std::fs::File>, path: &str) -> Option<Vec<u8>> {
|
||||
let mut entry = archive.by_name(path).ok()?;
|
||||
let mut bytes = Vec::new();
|
||||
entry.read_to_end(&mut bytes).ok()?;
|
||||
Some(bytes)
|
||||
}
|
||||
|
||||
pub(crate) fn make_icon_pixels(
|
||||
bytes: &[u8],
|
||||
width: u16,
|
||||
height: u16,
|
||||
) -> Option<Vec<Vec<IconCell>>> {
|
||||
let img = image::load_from_memory(bytes).ok()?;
|
||||
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 { bg_r: br, bg_g: bg, bg_b: bb, fg_r: tr, fg_g: tg, fg_b: tb });
|
||||
}
|
||||
rows.push(cols);
|
||||
}
|
||||
|
||||
Some(rows)
|
||||
}
|
||||
|
||||
/// 6x3 fallback icon showing a "?" pattern for mods without icons.
|
||||
fn fallback_icon() -> Vec<Vec<IconCell>> {
|
||||
let b = IconCell { bg_r: 50, bg_g: 50, bg_b: 50, fg_r: 50, fg_g: 50, fg_b: 50 };
|
||||
let tb = IconCell { bg_r: 50, bg_g: 50, bg_b: 50, fg_r: 130, fg_g: 130, fg_b: 130 };
|
||||
let bt = IconCell { bg_r: 130, bg_g: 130, bg_b: 130, fg_r: 50, fg_g: 50, fg_b: 50 };
|
||||
vec![
|
||||
vec![b, tb, tb, tb, tb, b],
|
||||
vec![b, b, b, bt, bt, b],
|
||||
vec![b, b, bt, bt, b, b],
|
||||
]
|
||||
}
|
||||
|
||||
pub fn toggle_entry(entry: &ContentEntry) -> Result<(), std::io::Error> {
|
||||
let file_name = match entry.path.file_name().and_then(|name| name.to_str()) {
|
||||
Some(name) => name,
|
||||
None => return Ok(()),
|
||||
};
|
||||
|
||||
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::*;
|
||||
|
||||
fn setup_mods_dir(tmp: &Path, instance: &str) -> PathBuf {
|
||||
let dir = tmp.join(instance).join(".minecraft").join("mods");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_mods_empty_dir() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
setup_mods_dir(tmp.path(), "inst");
|
||||
let mods = scan_mods(tmp.path(), "inst");
|
||||
assert!(mods.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_mods_missing_dir_returns_empty() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mods = scan_mods(tmp.path(), "ghost");
|
||||
assert!(mods.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_mods_finds_jar_files() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
||||
std::fs::write(dir.join("cool-mod.jar"), b"PK\x03\x04").unwrap();
|
||||
std::fs::write(dir.join("other-mod.jar.disabled"), b"PK\x03\x04").unwrap();
|
||||
let mods = scan_mods(tmp.path(), "inst");
|
||||
assert_eq!(mods.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_mods_enabled_disabled_flags() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
||||
std::fs::write(dir.join("active.jar"), b"PK\x03\x04").unwrap();
|
||||
std::fs::write(dir.join("inactive.jar.disabled"), b"PK\x03\x04").unwrap();
|
||||
let mods = scan_mods(tmp.path(), "inst");
|
||||
let active = mods.iter().find(|m| m.file_stem == "active").unwrap();
|
||||
let inactive = mods.iter().find(|m| m.file_stem == "inactive").unwrap();
|
||||
assert!(active.enabled);
|
||||
assert!(!inactive.enabled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_mods_ignores_non_jar() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
||||
std::fs::write(dir.join("readme.txt"), "not a mod").unwrap();
|
||||
std::fs::write(dir.join("config.json"), "{}").unwrap();
|
||||
std::fs::write(dir.join("real.jar"), b"PK\x03\x04").unwrap();
|
||||
let mods = scan_mods(tmp.path(), "inst");
|
||||
assert_eq!(mods.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_mods_sorted_case_insensitive() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
||||
std::fs::write(dir.join("Zebra.jar"), b"PK\x03\x04").unwrap();
|
||||
std::fs::write(dir.join("alpha.jar"), b"PK\x03\x04").unwrap();
|
||||
std::fs::write(dir.join("Beta.jar"), b"PK\x03\x04").unwrap();
|
||||
let mods = scan_mods(tmp.path(), "inst");
|
||||
let names: Vec<&str> = mods.iter().map(|m| m.name.as_str()).collect();
|
||||
assert_eq!(names, vec!["alpha", "Beta", "Zebra"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggle_entry_enable() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
||||
let disabled_path = dir.join("mymod.jar.disabled");
|
||||
std::fs::write(&disabled_path, b"PK\x03\x04").unwrap();
|
||||
|
||||
let entry = ContentEntry {
|
||||
file_stem: "mymod".to_string(),
|
||||
name: "mymod".to_string(),
|
||||
description: String::new(),
|
||||
enabled: false,
|
||||
icon_bytes: None,
|
||||
path: disabled_path.clone(),
|
||||
icon_lines: None,
|
||||
};
|
||||
|
||||
toggle_entry(&entry).unwrap();
|
||||
assert!(!disabled_path.exists());
|
||||
assert!(dir.join("mymod.jar").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggle_entry_disable() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
||||
let enabled_path = dir.join("mymod.jar");
|
||||
std::fs::write(&enabled_path, b"PK\x03\x04").unwrap();
|
||||
|
||||
let entry = ContentEntry {
|
||||
file_stem: "mymod".to_string(),
|
||||
name: "mymod".to_string(),
|
||||
description: String::new(),
|
||||
enabled: true,
|
||||
icon_bytes: None,
|
||||
path: enabled_path.clone(),
|
||||
icon_lines: None,
|
||||
};
|
||||
|
||||
toggle_entry(&entry).unwrap();
|
||||
assert!(!enabled_path.exists());
|
||||
assert!(dir.join("mymod.jar.disabled").exists());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
use std::path::Path;
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
use super::mods::{make_icon_pixels, ContentEntry};
|
||||
|
||||
#[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,
|
||||
}
|
||||
|
||||
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(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn scan_resource_packs(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
|
||||
let packs_dir = instances_dir
|
||||
.join(instance_name)
|
||||
.join(".minecraft")
|
||||
.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 is_dir = path.is_dir();
|
||||
let (enabled, file_stem) = if is_dir {
|
||||
super::parse_enabled_stem_dir(&file_name)
|
||||
} else if let Some(pair) = super::parse_enabled_stem(&file_name, ".zip") {
|
||||
pair
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
|
||||
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));
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn extract_description_from_string() {
|
||||
let val = serde_json::json!("Simple pack");
|
||||
assert_eq!(extract_description(&val), "Simple pack");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_description_from_object_with_text() {
|
||||
let val = serde_json::json!({"text": "Hello world"});
|
||||
assert_eq!(extract_description(&val), "Hello world");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_description_from_object_without_text() {
|
||||
let val = serde_json::json!({"color": "red"});
|
||||
assert_eq!(extract_description(&val), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_description_from_array_of_strings() {
|
||||
let val = serde_json::json!(["Hello", " ", "world"]);
|
||||
assert_eq!(extract_description(&val), "Hello world");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_description_from_array_of_objects() {
|
||||
let val = serde_json::json!([{"text": "A"}, {"text": "B"}]);
|
||||
assert_eq!(extract_description(&val), "AB");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_description_from_mixed_array() {
|
||||
let val = serde_json::json!(["Prefix ", {"text": "suffix"}]);
|
||||
assert_eq!(extract_description(&val), "Prefix suffix");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_description_from_empty_array() {
|
||||
let val = serde_json::json!([]);
|
||||
assert_eq!(extract_description(&val), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_description_from_null() {
|
||||
let val = serde_json::Value::Null;
|
||||
assert_eq!(extract_description(&val), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_description_from_number() {
|
||||
let val = serde_json::json!(42);
|
||||
assert_eq!(extract_description(&val), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_description_from_bool() {
|
||||
let val = serde_json::json!(true);
|
||||
assert_eq!(extract_description(&val), "");
|
||||
}
|
||||
|
||||
fn setup_packs_dir(tmp: &std::path::Path, instance: &str) -> std::path::PathBuf {
|
||||
let dir = tmp
|
||||
.join(instance)
|
||||
.join(".minecraft")
|
||||
.join("resourcepacks");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_resource_packs_empty_dir() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
setup_packs_dir(tmp.path(), "inst");
|
||||
let packs = scan_resource_packs(tmp.path(), "inst");
|
||||
assert!(packs.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_resource_packs_missing_dir_returns_empty() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let packs = scan_resource_packs(tmp.path(), "ghost");
|
||||
assert!(packs.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_resource_packs_finds_zips_and_dirs() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = setup_packs_dir(tmp.path(), "inst");
|
||||
std::fs::write(dir.join("pack-a.zip"), b"PK\x03\x04").unwrap();
|
||||
std::fs::create_dir(dir.join("pack-b")).unwrap();
|
||||
let packs = scan_resource_packs(tmp.path(), "inst");
|
||||
assert_eq!(packs.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_resource_packs_disabled_variants() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = setup_packs_dir(tmp.path(), "inst");
|
||||
std::fs::write(dir.join("on.zip"), b"PK\x03\x04").unwrap();
|
||||
std::fs::write(dir.join("off.zip.disabled"), b"PK\x03\x04").unwrap();
|
||||
std::fs::create_dir(dir.join("diron")).unwrap();
|
||||
std::fs::create_dir(dir.join("diroff.disabled")).unwrap();
|
||||
let packs = scan_resource_packs(tmp.path(), "inst");
|
||||
assert_eq!(packs.len(), 4);
|
||||
let on_zip = packs.iter().find(|p| p.file_stem == "on").unwrap();
|
||||
let off_zip = packs.iter().find(|p| p.file_stem == "off").unwrap();
|
||||
let on_dir = packs.iter().find(|p| p.file_stem == "diron").unwrap();
|
||||
let off_dir = packs.iter().find(|p| p.file_stem == "diroff").unwrap();
|
||||
assert!(on_zip.enabled);
|
||||
assert!(!off_zip.enabled);
|
||||
assert!(on_dir.enabled);
|
||||
assert!(!off_dir.enabled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_resource_packs_ignores_non_pack_files() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = setup_packs_dir(tmp.path(), "inst");
|
||||
std::fs::write(dir.join("notes.txt"), "not a pack").unwrap();
|
||||
std::fs::write(dir.join("valid.zip"), b"PK\x03\x04").unwrap();
|
||||
let packs = scan_resource_packs(tmp.path(), "inst");
|
||||
assert_eq!(packs.len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
use std::path::Path;
|
||||
|
||||
use super::mods::{make_icon_pixels, ContentEntry};
|
||||
use super::resource_packs::{extract_description, PackMcMeta};
|
||||
|
||||
pub fn scan_shaders(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
|
||||
let shaders_dir = instances_dir
|
||||
.join(instance_name)
|
||||
.join(".minecraft")
|
||||
.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 is_dir = path.is_dir();
|
||||
let (enabled, file_stem) = if is_dir {
|
||||
super::parse_enabled_stem_dir(&file_name)
|
||||
} else if let Some(pair) = super::parse_enabled_stem(&file_name, ".zip") {
|
||||
pair
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
|
||||
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));
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn setup_shaders_dir(tmp: &std::path::Path, instance: &str) -> std::path::PathBuf {
|
||||
let dir = tmp.join(instance).join(".minecraft").join("shaderpacks");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_shaders_empty_dir() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
setup_shaders_dir(tmp.path(), "inst");
|
||||
let shaders = scan_shaders(tmp.path(), "inst");
|
||||
assert!(shaders.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_shaders_missing_dir_returns_empty() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let shaders = scan_shaders(tmp.path(), "ghost");
|
||||
assert!(shaders.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_shaders_finds_zip_and_dir() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = setup_shaders_dir(tmp.path(), "inst");
|
||||
std::fs::write(dir.join("shader-a.zip"), b"PK\x03\x04").unwrap();
|
||||
std::fs::create_dir(dir.join("shader-b")).unwrap();
|
||||
let shaders = scan_shaders(tmp.path(), "inst");
|
||||
assert_eq!(shaders.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_shaders_disabled_variants() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = setup_shaders_dir(tmp.path(), "inst");
|
||||
std::fs::write(dir.join("active.zip"), b"PK\x03\x04").unwrap();
|
||||
std::fs::write(dir.join("off.zip.disabled"), b"PK\x03\x04").unwrap();
|
||||
std::fs::create_dir(dir.join("dirshader.disabled")).unwrap();
|
||||
let shaders = scan_shaders(tmp.path(), "inst");
|
||||
let active = shaders.iter().find(|s| s.file_stem == "active").unwrap();
|
||||
let off = shaders.iter().find(|s| s.file_stem == "off").unwrap();
|
||||
let diroff = shaders.iter().find(|s| s.file_stem == "dirshader").unwrap();
|
||||
assert!(active.enabled);
|
||||
assert!(!off.enabled);
|
||||
assert!(!diroff.enabled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_shaders_ignores_non_shader_files() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = setup_shaders_dir(tmp.path(), "inst");
|
||||
std::fs::write(dir.join("readme.txt"), "not a shader").unwrap();
|
||||
std::fs::write(dir.join("valid.zip"), b"PK\x03\x04").unwrap();
|
||||
let shaders = scan_shaders(tmp.path(), "inst");
|
||||
assert_eq!(shaders.len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
use std::path::Path;
|
||||
|
||||
use super::mods::{make_icon_pixels, ContentEntry};
|
||||
|
||||
pub fn scan_worlds(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
|
||||
let saves_dir = instances_dir
|
||||
.join(instance_name)
|
||||
.join(".minecraft")
|
||||
.join("saves");
|
||||
|
||||
let read_dir = match std::fs::read_dir(&saves_dir) {
|
||||
Ok(rd) => rd,
|
||||
Err(_) => return Vec::new(),
|
||||
};
|
||||
|
||||
let mut entries = Vec::new();
|
||||
|
||||
for entry in read_dir.flatten() {
|
||||
let path = entry.path();
|
||||
if !path.is_dir() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let file_name = match path.file_name().and_then(|n| n.to_str()) {
|
||||
Some(n) => n.to_string(),
|
||||
None => continue,
|
||||
};
|
||||
|
||||
let (enabled, file_stem) = super::parse_enabled_stem_dir(&file_name);
|
||||
|
||||
let icon_bytes = std::fs::read(path.join("icon.png")).ok();
|
||||
let icon_lines = icon_bytes
|
||||
.as_ref()
|
||||
.and_then(|bytes| make_icon_pixels(bytes, 12, 6));
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
fn world_description(world_dir: &Path) -> String {
|
||||
let level_dat = world_dir.join("level.dat");
|
||||
|
||||
let created = world_dir
|
||||
.metadata()
|
||||
.ok()
|
||||
.and_then(|m| m.created().ok().or_else(|| m.modified().ok()))
|
||||
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
|
||||
.map(|d| d.as_secs());
|
||||
|
||||
let modified = level_dat
|
||||
.metadata()
|
||||
.ok()
|
||||
.and_then(|m| m.modified().ok())
|
||||
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
|
||||
.map(|d| d.as_secs());
|
||||
|
||||
let dir_size = dir_size_approx(world_dir);
|
||||
|
||||
let mut lines = Vec::new();
|
||||
|
||||
if let Some(secs) = created {
|
||||
if let Some(dt) = chrono::DateTime::from_timestamp(secs as i64, 0) {
|
||||
lines.push(format!("Created: {}", dt.format("%Y-%m-%d %H:%M")));
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(secs) = modified {
|
||||
if let Some(dt) = chrono::DateTime::from_timestamp(secs as i64, 0) {
|
||||
lines.push(format!("Played: {}", dt.format("%Y-%m-%d %H:%M")));
|
||||
}
|
||||
}
|
||||
|
||||
if dir_size > 0 {
|
||||
lines.push(format!("Size: {}", format_size(dir_size)));
|
||||
}
|
||||
|
||||
lines.join("\n")
|
||||
}
|
||||
|
||||
fn dir_size_approx(path: &Path) -> u64 {
|
||||
let mut total = 0u64;
|
||||
if let Ok(rd) = std::fs::read_dir(path) {
|
||||
for entry in rd.flatten() {
|
||||
if let Ok(meta) = entry.metadata() {
|
||||
if meta.is_file() {
|
||||
total += meta.len();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Check region folder too (main chunk data)
|
||||
let region = path.join("region");
|
||||
if let Ok(rd) = std::fs::read_dir(region) {
|
||||
for entry in rd.flatten() {
|
||||
if let Ok(meta) = entry.metadata() {
|
||||
total += meta.len();
|
||||
}
|
||||
}
|
||||
}
|
||||
total
|
||||
}
|
||||
|
||||
fn format_size(bytes: u64) -> String {
|
||||
if bytes < 1024 {
|
||||
format!("{} B", bytes)
|
||||
} else if bytes < 1024 * 1024 {
|
||||
format!("{:.1} KB", bytes as f64 / 1024.0)
|
||||
} else if bytes < 1024 * 1024 * 1024 {
|
||||
format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0))
|
||||
} else {
|
||||
format!("{:.2} GB", bytes as f64 / (1024.0 * 1024.0 * 1024.0))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn setup_saves_dir(tmp: &Path, instance: &str) -> std::path::PathBuf {
|
||||
let dir = tmp.join(instance).join(".minecraft").join("saves");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_worlds_empty_dir() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
setup_saves_dir(tmp.path(), "inst");
|
||||
let worlds = scan_worlds(tmp.path(), "inst");
|
||||
assert!(worlds.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_worlds_missing_dir_returns_empty() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let worlds = scan_worlds(tmp.path(), "ghost");
|
||||
assert!(worlds.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_worlds_finds_directories() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = setup_saves_dir(tmp.path(), "inst");
|
||||
std::fs::create_dir(dir.join("My World")).unwrap();
|
||||
std::fs::create_dir(dir.join("Creative")).unwrap();
|
||||
let worlds = scan_worlds(tmp.path(), "inst");
|
||||
assert_eq!(worlds.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_worlds_ignores_files() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = setup_saves_dir(tmp.path(), "inst");
|
||||
std::fs::create_dir(dir.join("World1")).unwrap();
|
||||
std::fs::write(dir.join("stray-file.txt"), "not a world").unwrap();
|
||||
let worlds = scan_worlds(tmp.path(), "inst");
|
||||
assert_eq!(worlds.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_worlds_disabled_world() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = setup_saves_dir(tmp.path(), "inst");
|
||||
std::fs::create_dir(dir.join("ActiveWorld")).unwrap();
|
||||
std::fs::create_dir(dir.join("HiddenWorld.disabled")).unwrap();
|
||||
let worlds = scan_worlds(tmp.path(), "inst");
|
||||
let active = worlds.iter().find(|w| w.file_stem == "ActiveWorld").unwrap();
|
||||
let hidden = worlds.iter().find(|w| w.file_stem == "HiddenWorld").unwrap();
|
||||
assert!(active.enabled);
|
||||
assert!(!hidden.enabled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_worlds_sorted_case_insensitive() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = setup_saves_dir(tmp.path(), "inst");
|
||||
std::fs::create_dir(dir.join("Zeta")).unwrap();
|
||||
std::fs::create_dir(dir.join("alpha")).unwrap();
|
||||
std::fs::create_dir(dir.join("Beta")).unwrap();
|
||||
let worlds = scan_worlds(tmp.path(), "inst");
|
||||
let names: Vec<&str> = worlds.iter().map(|w| w.name.as_str()).collect();
|
||||
assert_eq!(names, vec!["alpha", "Beta", "Zeta"]);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user