Merge pull request #2601 from ludovic111/feat/launcher-packs-core
🤖 Agent: launcher-features-1 checked this: base main, clean merge with main, launcher CI green; fmt, clippy -D warnings and the launcher tests pass locally. Queued for merge.
This commit is contained in:
@@ -374,6 +374,64 @@ Move a world to the system's trash.
|
||||
|
||||
MCP: `worlds_delete`, needs `confirm: true`.
|
||||
|
||||
## `horizon-launcher packs list`
|
||||
|
||||
The resource and shader packs, and which are on (the default).
|
||||
|
||||
horizon-launcher packs list
|
||||
|
||||
- `--kind` (resource, shader): Only this kind
|
||||
- `--instance`: The instance (default: the selected one)
|
||||
|
||||
MCP: `packs_list`.
|
||||
|
||||
## `horizon-launcher packs add`
|
||||
|
||||
Copy a pack file in: a resource pack .zip, a shader pack .zip or a .hshader.
|
||||
|
||||
horizon-launcher packs add <FILE>
|
||||
|
||||
- `FILE`
|
||||
- `--instance`
|
||||
|
||||
MCP: `packs_add`.
|
||||
|
||||
## `horizon-launcher packs on`
|
||||
|
||||
Turn a pack on (a resource pack goes on top; a shader pack replaces the one that was on).
|
||||
|
||||
horizon-launcher packs on <PACK>
|
||||
|
||||
- `PACK`: Its file name or title
|
||||
- `--kind` (resource, shader)
|
||||
- `--instance`
|
||||
|
||||
MCP: `packs_on`.
|
||||
|
||||
## `horizon-launcher packs off`
|
||||
|
||||
Turn a pack off.
|
||||
|
||||
horizon-launcher packs off <PACK>
|
||||
|
||||
- `PACK`
|
||||
- `--kind` (resource, shader)
|
||||
- `--instance`
|
||||
|
||||
MCP: `packs_off`.
|
||||
|
||||
## `horizon-launcher packs remove`
|
||||
|
||||
Turn a pack off and move it to the system's trash.
|
||||
|
||||
horizon-launcher packs remove <PACK>
|
||||
|
||||
- `PACK`
|
||||
- `--kind` (resource, shader)
|
||||
- `--instance`
|
||||
|
||||
MCP: `packs_remove`, needs `confirm: true`.
|
||||
|
||||
## `horizon-launcher screenshots list`
|
||||
|
||||
The screenshots, the newest first, with their files (the default).
|
||||
|
||||
Generated
+1
@@ -2764,6 +2764,7 @@ dependencies = [
|
||||
"sha1",
|
||||
"sha2 0.10.9",
|
||||
"tar",
|
||||
"toml 1.1.8+spec-1.1.0",
|
||||
"trash",
|
||||
"ureq",
|
||||
"winresource",
|
||||
|
||||
@@ -19,6 +19,7 @@ sha2 = "0.10"
|
||||
pulldown-cmark = { version = "0.12", default-features = false }
|
||||
flate2 = "1"
|
||||
tar = { version = "0.4", default-features = false }
|
||||
toml = "1.1"
|
||||
zip = { version = "2", default-features = false, features = ["deflate"] }
|
||||
dirs = "5"
|
||||
self-replace = "1"
|
||||
|
||||
@@ -214,6 +214,65 @@ enum WorldsCmd {
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, clap::ValueEnum)]
|
||||
enum PackKindArg {
|
||||
Resource,
|
||||
Shader,
|
||||
}
|
||||
|
||||
impl From<PackKindArg> for horizon_launcher::packs::Kind {
|
||||
fn from(k: PackKindArg) -> Self {
|
||||
match k {
|
||||
PackKindArg::Resource => Self::Resource,
|
||||
PackKindArg::Shader => Self::Shader,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum PacksCmd {
|
||||
/// The resource and shader packs, and which are on (the default)
|
||||
List {
|
||||
/// Only this kind
|
||||
#[arg(long, value_enum)]
|
||||
kind: Option<PackKindArg>,
|
||||
/// The instance (default: the selected one)
|
||||
#[arg(long)]
|
||||
instance: Option<String>,
|
||||
},
|
||||
/// Copy a pack file in: a resource pack .zip, a shader pack .zip or a .hshader
|
||||
Add {
|
||||
file: PathBuf,
|
||||
#[arg(long)]
|
||||
instance: Option<String>,
|
||||
},
|
||||
/// Turn a pack on (a resource pack goes on top; a shader pack replaces the one that was on)
|
||||
On {
|
||||
/// Its file name or title
|
||||
pack: String,
|
||||
#[arg(long, value_enum, default_value_t = PackKindArg::Resource)]
|
||||
kind: PackKindArg,
|
||||
#[arg(long)]
|
||||
instance: Option<String>,
|
||||
},
|
||||
/// Turn a pack off
|
||||
Off {
|
||||
pack: String,
|
||||
#[arg(long, value_enum, default_value_t = PackKindArg::Resource)]
|
||||
kind: PackKindArg,
|
||||
#[arg(long)]
|
||||
instance: Option<String>,
|
||||
},
|
||||
/// Turn a pack off and move it to the system's trash
|
||||
Remove {
|
||||
pack: String,
|
||||
#[arg(long, value_enum, default_value_t = PackKindArg::Resource)]
|
||||
kind: PackKindArg,
|
||||
#[arg(long)]
|
||||
instance: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum ScreenshotsCmd {
|
||||
/// The screenshots, the newest first, with their files (the default)
|
||||
@@ -459,6 +518,11 @@ enum Cmd {
|
||||
#[command(subcommand)]
|
||||
action: Option<WorldsCmd>,
|
||||
},
|
||||
/// An instance's resource and shader packs: list, add, turn on or off, remove
|
||||
Packs {
|
||||
#[command(subcommand)]
|
||||
action: Option<PacksCmd>,
|
||||
},
|
||||
/// The screenshots F2 took in an instance: list, delete
|
||||
Screenshots {
|
||||
#[command(subcommand)]
|
||||
@@ -933,6 +997,13 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> {
|
||||
action.unwrap_or(WorldsCmd::List { instance: None }),
|
||||
as_json,
|
||||
)?,
|
||||
Cmd::Packs { action } => game_packs(
|
||||
action.unwrap_or(PacksCmd::List {
|
||||
kind: None,
|
||||
instance: None,
|
||||
}),
|
||||
as_json,
|
||||
)?,
|
||||
Cmd::Screenshots { action } => screenshots(
|
||||
action.unwrap_or(ScreenshotsCmd::List { instance: None }),
|
||||
as_json,
|
||||
@@ -1568,6 +1639,90 @@ fn instance(action: InstanceCmd, as_json: bool) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn game_packs(action: PacksCmd, as_json: bool) -> Result<(), String> {
|
||||
use horizon_launcher::packs::{self, Kind};
|
||||
let home = |instance: Option<String>| -> Result<PathBuf, String> {
|
||||
Ok(match instance {
|
||||
Some(name) => instances::find(&name)?.home,
|
||||
None => instances::selected().home,
|
||||
})
|
||||
};
|
||||
let value = |p: &packs::Pack| {
|
||||
serde_json::json!({
|
||||
"kind": format!("{:?}", p.kind).to_lowercase(), "file": p.file, "title": p.title,
|
||||
"description": p.description, "enabled": p.enabled, "path": p.path,
|
||||
})
|
||||
};
|
||||
match action {
|
||||
PacksCmd::List { kind, instance } => {
|
||||
let home = home(instance)?;
|
||||
let kinds = match kind {
|
||||
Some(k) => vec![Kind::from(k)],
|
||||
None => vec![Kind::Resource, Kind::Shader],
|
||||
};
|
||||
let all: Vec<packs::Pack> = kinds.iter().flat_map(|k| packs::list(&home, *k)).collect();
|
||||
if as_json {
|
||||
json(all.iter().map(value).collect());
|
||||
}
|
||||
for k in kinds.iter().filter(|_| !as_json) {
|
||||
println!("{}:", k.folder());
|
||||
let these: Vec<_> = all.iter().filter(|p| p.kind == *k).collect();
|
||||
if these.is_empty() {
|
||||
println!(" none");
|
||||
}
|
||||
for p in these {
|
||||
let on = if p.enabled { "on " } else { "off" };
|
||||
match p.title == p.file {
|
||||
true => println!(" {on} {}", p.file),
|
||||
false => println!(" {on} {} ({})", p.title, p.file),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
PacksCmd::Add { file, instance } => {
|
||||
let pack = packs::add(&home(instance)?, &file)?;
|
||||
match as_json {
|
||||
true => json(value(&pack)),
|
||||
false => println!("Added {} to {} (off).", pack.file, pack.kind.folder()),
|
||||
}
|
||||
}
|
||||
PacksCmd::On {
|
||||
pack,
|
||||
kind,
|
||||
instance,
|
||||
} => set_pack(&home(instance)?, kind.into(), &pack, true)?,
|
||||
PacksCmd::Off {
|
||||
pack,
|
||||
kind,
|
||||
instance,
|
||||
} => set_pack(&home(instance)?, kind.into(), &pack, false)?,
|
||||
PacksCmd::Remove {
|
||||
pack,
|
||||
kind,
|
||||
instance,
|
||||
} => {
|
||||
let home = home(instance)?;
|
||||
let p = packs::find(&home, kind.into(), &pack)?;
|
||||
packs::remove(&home, &p)?;
|
||||
println!("{} is in the trash.", p.file);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_pack(
|
||||
home: &std::path::Path,
|
||||
kind: horizon_launcher::packs::Kind,
|
||||
query: &str,
|
||||
on: bool,
|
||||
) -> Result<(), String> {
|
||||
use horizon_launcher::packs;
|
||||
let pack = packs::find(home, kind, query)?;
|
||||
packs::set_enabled(home, &pack, on)?;
|
||||
println!("{} is {}.", pack.title, if on { "on" } else { "off" });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn screenshots(action: ScreenshotsCmd, as_json: bool) -> Result<(), String> {
|
||||
use horizon_launcher::screenshots;
|
||||
let home = |instance: Option<String>| -> Result<PathBuf, String> {
|
||||
|
||||
@@ -29,6 +29,7 @@ pub const DESTRUCTIVE: &[&str] = &[
|
||||
"worlds delete",
|
||||
"multiplayer remove",
|
||||
"screenshots delete",
|
||||
"packs remove",
|
||||
];
|
||||
|
||||
/// Commands that send something or reach other people: only when the player asks.
|
||||
|
||||
@@ -10,6 +10,7 @@ pub mod heads;
|
||||
pub mod instances;
|
||||
pub mod modpacks;
|
||||
pub mod mojang;
|
||||
pub mod packs;
|
||||
pub mod process;
|
||||
pub mod proxy;
|
||||
pub mod screenshots;
|
||||
|
||||
@@ -0,0 +1,338 @@
|
||||
//! An instance's resource packs and shader packs, as the game finds and picks them.
|
||||
//!
|
||||
//! - Resource packs: `resourcepacks/` in the game folder, each a `.zip` or a folder with a
|
||||
//! `pack.mcmeta`. The ones turned on are `options.txt`'s `resourcePacks` list (vanilla's
|
||||
//! format, `"file/<name>"`, the bottom first), so the game's Resource Packs screen shows the
|
||||
//! same choice. A pack turned on here goes on top, as the screen puts a newly picked one.
|
||||
//! - Shader packs: `shaderpacks/`, Horizon's own (a folder with `horizon-shaders.toml`, or a
|
||||
//! `.hshader`) and those in the `shaders/` format (a `.zip`, or a folder with `shaders/`), as
|
||||
//! the game's Shader Packs page lists them (`shader_pack_list`). One at most is on:
|
||||
//! `pickedShaderPack` in `horizon-graphics.txt`.
|
||||
//!
|
||||
//! Every other line of both files is written back as it was.
|
||||
use std::fs;
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const OPTIONS: &str = "options.txt";
|
||||
const GRAPHICS: &str = "horizon-graphics.txt";
|
||||
const SHADER_MANIFEST: &str = "horizon-shaders.toml";
|
||||
const SHADER_PACKAGE: &str = "hshader";
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Kind {
|
||||
Resource,
|
||||
Shader,
|
||||
}
|
||||
|
||||
impl Kind {
|
||||
pub fn folder(self) -> &'static str {
|
||||
match self {
|
||||
Kind::Resource => "resourcepacks",
|
||||
Kind::Shader => "shaderpacks",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Pack {
|
||||
pub kind: Kind,
|
||||
/// Its file or folder name in the pack folder: the id commands take.
|
||||
pub file: String,
|
||||
pub path: PathBuf,
|
||||
/// A Horizon shader pack's own name, else the file's.
|
||||
pub title: String,
|
||||
/// `pack.mcmeta`'s description as plain text; a shader pack's format.
|
||||
pub description: String,
|
||||
/// `pack.png`, a resource pack's picture.
|
||||
pub icon: Option<Vec<u8>>,
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
/// The packs of `kind` in the game folder `home`, by name: turning one on or off leaves it where
|
||||
/// it is.
|
||||
pub fn list(home: &Path, kind: Kind) -> Vec<Pack> {
|
||||
let on = enabled(home, kind);
|
||||
let mut packs: Vec<Pack> = fs::read_dir(home.join(kind.folder()))
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.filter_map(|e| read(&e.path(), kind, &on))
|
||||
.collect();
|
||||
packs.sort_by_key(|p| p.title.to_lowercase());
|
||||
packs
|
||||
}
|
||||
|
||||
/// The file names turned on, bottom first.
|
||||
fn enabled(home: &Path, kind: Kind) -> Vec<String> {
|
||||
match kind {
|
||||
Kind::Resource => option_list(&fs::read_to_string(home.join(OPTIONS)).unwrap_or_default())
|
||||
.into_iter()
|
||||
.filter_map(|id| id.strip_prefix("file/").map(str::to_string))
|
||||
.collect(),
|
||||
Kind::Shader => line_value(
|
||||
&fs::read_to_string(home.join(GRAPHICS)).unwrap_or_default(),
|
||||
"pickedShaderPack",
|
||||
)
|
||||
.filter(|v| !v.is_empty())
|
||||
.into_iter()
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn read(path: &Path, kind: Kind, on: &[String]) -> Option<Pack> {
|
||||
let file = path.file_name()?.to_str()?.to_string();
|
||||
if file.starts_with('.') {
|
||||
return None;
|
||||
}
|
||||
let ext =
|
||||
|x: &str| path.is_file() && path.extension().is_some_and(|e| e.eq_ignore_ascii_case(x));
|
||||
let (title, description, icon) = match kind {
|
||||
Kind::Resource => {
|
||||
let meta = entry(path, "pack.mcmeta")?;
|
||||
let meta: serde_json::Value = serde_json::from_slice(&meta).ok()?;
|
||||
(
|
||||
file.clone(),
|
||||
plain(&meta["pack"]["description"]),
|
||||
entry(path, "pack.png"),
|
||||
)
|
||||
}
|
||||
Kind::Shader if path.join(SHADER_MANIFEST).is_file() || ext(SHADER_PACKAGE) => {
|
||||
let name = entry(path, SHADER_MANIFEST)
|
||||
.and_then(|t| toml::from_slice::<toml::Table>(&t).ok())
|
||||
.and_then(|t| t.get("name")?.as_str().map(str::to_string));
|
||||
(
|
||||
name.unwrap_or_else(|| file.clone()),
|
||||
"Horizon shader pack".into(),
|
||||
None,
|
||||
)
|
||||
}
|
||||
Kind::Shader if ext("zip") || path.join("shaders").is_dir() => {
|
||||
(file.clone(), "shaders/ format".into(), None)
|
||||
}
|
||||
Kind::Shader => return None,
|
||||
};
|
||||
Some(Pack {
|
||||
kind,
|
||||
enabled: on.contains(&file),
|
||||
path: path.to_path_buf(),
|
||||
file,
|
||||
title,
|
||||
description,
|
||||
icon,
|
||||
})
|
||||
}
|
||||
|
||||
/// A file at the root of a pack folder or zip, at most 4 MB.
|
||||
fn entry(path: &Path, name: &str) -> Option<Vec<u8>> {
|
||||
let mut out = Vec::new();
|
||||
if path.is_dir() {
|
||||
fs::File::open(path.join(name))
|
||||
.ok()?
|
||||
.take(4 << 20)
|
||||
.read_to_end(&mut out)
|
||||
.ok()?;
|
||||
} else {
|
||||
let mut zip = zip::ZipArchive::new(fs::File::open(path).ok()?).ok()?;
|
||||
let entry = zip.by_name(name).ok()?;
|
||||
entry.take(4 << 20).read_to_end(&mut out).ok()?;
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// A text component as plain text: its strings, without `§` formatting codes.
|
||||
fn plain(component: &serde_json::Value) -> String {
|
||||
fn walk(v: &serde_json::Value, out: &mut String) {
|
||||
match v {
|
||||
serde_json::Value::String(s) => out.push_str(s),
|
||||
serde_json::Value::Array(a) => a.iter().for_each(|v| walk(v, out)),
|
||||
serde_json::Value::Object(o) => {
|
||||
if let Some(t) = o.get("text").or_else(|| o.get("translate")) {
|
||||
walk(t, out);
|
||||
}
|
||||
if let Some(extra) = o.get("extra") {
|
||||
walk(extra, out);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut raw = String::new();
|
||||
walk(component, &mut raw);
|
||||
let mut out = String::new();
|
||||
let mut chars = raw.chars();
|
||||
while let Some(c) = chars.next() {
|
||||
match c {
|
||||
'§' => {
|
||||
chars.next();
|
||||
}
|
||||
'\n' => out.push(' '),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out.trim().to_string()
|
||||
}
|
||||
|
||||
/// `key:value` in a `key:value` per line file.
|
||||
fn line_value(text: &str, key: &str) -> Option<String> {
|
||||
text.lines()
|
||||
.find_map(|l| l.strip_prefix(key)?.strip_prefix(':'))
|
||||
.map(str::to_string)
|
||||
}
|
||||
|
||||
/// `resourcePacks:["vanilla","file/x.zip"]` in options.txt.
|
||||
fn option_list(options: &str) -> Vec<String> {
|
||||
line_value(options, "resourcePacks")
|
||||
.and_then(|v| serde_json::from_str(&v).ok())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Sets `key:value` in the file, or adds the line; every other line stays.
|
||||
fn set_line(path: &Path, key: &str, value: &str) -> Result<(), String> {
|
||||
let text = fs::read_to_string(path).unwrap_or_default();
|
||||
let mut found = false;
|
||||
let mut out: Vec<String> = text
|
||||
.lines()
|
||||
.map(
|
||||
|l| match l.strip_prefix(key).and_then(|r| r.strip_prefix(':')) {
|
||||
Some(_) if !found => {
|
||||
found = true;
|
||||
format!("{key}:{value}")
|
||||
}
|
||||
_ => l.to_string(),
|
||||
},
|
||||
)
|
||||
.collect();
|
||||
if !found {
|
||||
out.push(format!("{key}:{value}"));
|
||||
}
|
||||
let mut text = out.join("\n");
|
||||
text.push('\n');
|
||||
if let Some(dir) = path.parent() {
|
||||
fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
}
|
||||
fs::write(path, text).map_err(|e| format!("{}: {e}", path.display()))
|
||||
}
|
||||
|
||||
/// Turns a pack on or off. A resource pack turned on goes on top; a shader pack turned on
|
||||
/// replaces the one that was.
|
||||
pub fn set_enabled(home: &Path, pack: &Pack, on: bool) -> Result<(), String> {
|
||||
match pack.kind {
|
||||
Kind::Resource => {
|
||||
let options = home.join(OPTIONS);
|
||||
let text = fs::read_to_string(&options).unwrap_or_default();
|
||||
let id = format!("file/{}", pack.file);
|
||||
let mut list = option_list(&text);
|
||||
list.retain(|i| *i != id);
|
||||
if list.is_empty() {
|
||||
list.push("vanilla".into());
|
||||
}
|
||||
if on {
|
||||
list.push(id.clone());
|
||||
} else {
|
||||
// The game's "use it anyway" answer goes with it.
|
||||
let mut incompatible: Vec<String> = line_value(&text, "incompatibleResourcePacks")
|
||||
.and_then(|v| serde_json::from_str(&v).ok())
|
||||
.unwrap_or_default();
|
||||
if incompatible.contains(&id) {
|
||||
incompatible.retain(|i| *i != id);
|
||||
let value = serde_json::to_string(&incompatible).unwrap();
|
||||
set_line(&options, "incompatibleResourcePacks", &value)?;
|
||||
}
|
||||
}
|
||||
set_line(
|
||||
&options,
|
||||
"resourcePacks",
|
||||
&serde_json::to_string(&list).unwrap(),
|
||||
)
|
||||
}
|
||||
Kind::Shader => {
|
||||
let value = if on { pack.file.as_str() } else { "" };
|
||||
set_line(&home.join(GRAPHICS), "pickedShaderPack", value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The pack a command names: its file name, or its title (any case).
|
||||
pub fn find(home: &Path, kind: Kind, query: &str) -> Result<Pack, String> {
|
||||
let all = list(home, kind);
|
||||
all.iter()
|
||||
.find(|p| p.file == query)
|
||||
.or_else(|| all.iter().find(|p| p.title.eq_ignore_ascii_case(query)))
|
||||
.cloned()
|
||||
.ok_or_else(|| format!("No pack {query} in {}", home.join(kind.folder()).display()))
|
||||
}
|
||||
|
||||
/// What a dropped or picked file is: a resource pack (a zip with `pack.mcmeta`), a Horizon
|
||||
/// shader pack (`.hshader`), or a shader pack in the `shaders/` format (a zip with `shaders/`).
|
||||
pub fn kind_of(file: &Path) -> Result<Kind, String> {
|
||||
let name = file
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_default();
|
||||
let ext = file
|
||||
.extension()
|
||||
.map(|e| e.to_string_lossy().to_ascii_lowercase());
|
||||
match ext.as_deref() {
|
||||
Some(SHADER_PACKAGE) => return Ok(Kind::Shader),
|
||||
Some("zip") => {}
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"{name} is not a pack: packs are .zip or .hshader files."
|
||||
))
|
||||
}
|
||||
}
|
||||
let zip = fs::File::open(file)
|
||||
.ok()
|
||||
.and_then(|f| zip::ZipArchive::new(f).ok())
|
||||
.ok_or_else(|| format!("{name} is not a zip file that can be read."))?;
|
||||
if zip.index_for_name("pack.mcmeta").is_some() {
|
||||
Ok(Kind::Resource)
|
||||
} else if zip.file_names().any(|n| n.starts_with("shaders/")) {
|
||||
Ok(Kind::Shader)
|
||||
} else {
|
||||
Err(format!(
|
||||
"{name} has neither a pack.mcmeta (a resource pack) nor a shaders folder (a shader pack)."
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// Copies a pack file into the right folder of `home`, under a name not taken yet. Returns it,
|
||||
/// turned off.
|
||||
pub fn add(home: &Path, file: &Path) -> Result<Pack, String> {
|
||||
let kind = kind_of(file)?;
|
||||
let dir = home.join(kind.folder());
|
||||
fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
let name = file.file_name().ok_or("A pack file has a name")?;
|
||||
let stem = Path::new(name)
|
||||
.file_stem()
|
||||
.unwrap_or(name)
|
||||
.to_string_lossy();
|
||||
let ext = Path::new(name)
|
||||
.extension()
|
||||
.map(|e| format!(".{}", e.to_string_lossy()))
|
||||
.unwrap_or_default();
|
||||
let target = (1..)
|
||||
.map(|n| match n {
|
||||
1 => dir.join(name),
|
||||
n => dir.join(format!("{stem} ({n}){ext}")),
|
||||
})
|
||||
.find(|p| !p.exists())
|
||||
.unwrap();
|
||||
fs::copy(file, &target).map_err(|e| format!("Could not copy {}: {e}", file.display()))?;
|
||||
read(&target, kind, &[])
|
||||
.ok_or_else(|| format!("{} is not a pack the game reads", target.display()))
|
||||
}
|
||||
|
||||
/// Turns the pack off and moves it to the system's trash.
|
||||
pub fn remove(home: &Path, pack: &Pack) -> Result<(), String> {
|
||||
if pack.enabled {
|
||||
set_enabled(home, pack, false)?;
|
||||
}
|
||||
crate::worlds::to_trash(&pack.path)
|
||||
.map_err(|e| format!("Could not move {} to the trash: {e}", pack.file))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "packs/tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,174 @@
|
||||
use super::*;
|
||||
use std::io::Write;
|
||||
|
||||
fn scratch(name: &str) -> PathBuf {
|
||||
let root = std::env::temp_dir().join(format!(
|
||||
"horizon-launcher-packs-{name}-{}",
|
||||
std::process::id()
|
||||
));
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
fs::create_dir_all(&root).unwrap();
|
||||
root
|
||||
}
|
||||
|
||||
fn zip_file(path: &Path, files: &[(&str, &[u8])]) {
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
let mut zip = zip::ZipWriter::new(fs::File::create(path).unwrap());
|
||||
for (name, bytes) in files {
|
||||
zip.start_file(*name, zip::write::SimpleFileOptions::default())
|
||||
.unwrap();
|
||||
zip.write_all(bytes).unwrap();
|
||||
}
|
||||
zip.finish().unwrap();
|
||||
}
|
||||
|
||||
const META: &[u8] = "{\"pack\":{\"pack_format\":69,\"description\":[\"\",{\"text\":\"Smooth \u{a7}aglass\"},\"\\nand more\"]}}"
|
||||
.as_bytes();
|
||||
|
||||
/// A game folder with three resource packs (one on), and shader packs of both kinds.
|
||||
fn home(name: &str) -> PathBuf {
|
||||
let home = scratch(name);
|
||||
let rp = home.join("resourcepacks");
|
||||
zip_file(
|
||||
&rp.join("Glass.zip"),
|
||||
&[("pack.mcmeta", META), ("pack.png", b"png")],
|
||||
);
|
||||
zip_file(&rp.join("Broken.zip"), &[("readme.txt", b"no meta")]);
|
||||
fs::create_dir_all(rp.join("Folder Pack")).unwrap();
|
||||
fs::write(
|
||||
rp.join("Folder Pack/pack.mcmeta"),
|
||||
br#"{"pack":{"description":"Mine"}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
zip_file(&rp.join("Zed.zip"), &[("pack.mcmeta", META)]);
|
||||
let sp = home.join("shaderpacks");
|
||||
fs::create_dir_all(sp.join("warm")).unwrap();
|
||||
fs::write(
|
||||
sp.join("warm/horizon-shaders.toml"),
|
||||
"schema = 1\nid = \"warm\"\nname = \"Warm Light\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
zip_file(&sp.join("Classic.zip"), &[("shaders/final.fsh", b"")]);
|
||||
fs::write(sp.join("notes.txt"), b"").unwrap();
|
||||
fs::write(
|
||||
home.join("options.txt"),
|
||||
"version:4786\nresourcePacks:[\"vanilla\",\"file/Zed.zip\"]\nincompatibleResourcePacks:[\"file/Zed.zip\"]\nlang:fr_ch\n",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
home.join("horizon-graphics.txt"),
|
||||
"preset:custom\npickedShaderPack:\nfxaa:true\n",
|
||||
)
|
||||
.unwrap();
|
||||
home
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lists_what_the_game_reads_and_which_are_on() {
|
||||
let home = home("list");
|
||||
let rp = list(&home, Kind::Resource);
|
||||
let names: Vec<(&str, bool)> = rp.iter().map(|p| (p.file.as_str(), p.enabled)).collect();
|
||||
assert_eq!(
|
||||
names,
|
||||
[
|
||||
("Folder Pack", false),
|
||||
("Glass.zip", false),
|
||||
("Zed.zip", true)
|
||||
],
|
||||
"by name; the pack without pack.mcmeta is left out, as the game does"
|
||||
);
|
||||
let glass = &rp[1];
|
||||
assert_eq!(glass.description, "Smooth glass and more");
|
||||
assert_eq!(glass.icon.as_deref(), Some(&b"png"[..]));
|
||||
let sp = list(&home, Kind::Shader);
|
||||
let names: Vec<&str> = sp.iter().map(|p| p.title.as_str()).collect();
|
||||
assert_eq!(names, ["Classic.zip", "Warm Light"]);
|
||||
assert!(list(&home.join("none"), Kind::Shader).is_empty());
|
||||
fs::remove_dir_all(&home).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turning_packs_on_and_off_writes_the_games_own_lines() {
|
||||
let home = home("toggle");
|
||||
let glass = find(&home, Kind::Resource, "Glass.zip").unwrap();
|
||||
set_enabled(&home, &glass, true).unwrap();
|
||||
let folder = find(&home, Kind::Resource, "folder pack").unwrap();
|
||||
set_enabled(&home, &folder, true).unwrap();
|
||||
assert!(
|
||||
fs::read_to_string(home.join("options.txt")).unwrap().contains(
|
||||
"resourcePacks:[\"vanilla\",\"file/Zed.zip\",\"file/Glass.zip\",\"file/Folder Pack\"]\n"
|
||||
),
|
||||
"the newest on top"
|
||||
);
|
||||
let zed = find(&home, Kind::Resource, "Zed.zip").unwrap();
|
||||
set_enabled(&home, &zed, false).unwrap();
|
||||
assert_eq!(
|
||||
fs::read_to_string(home.join("options.txt")).unwrap(),
|
||||
"version:4786\nresourcePacks:[\"vanilla\",\"file/Glass.zip\",\"file/Folder Pack\"]\nincompatibleResourcePacks:[]\nlang:fr_ch\n"
|
||||
);
|
||||
|
||||
let warm = find(&home, Kind::Shader, "Warm Light").unwrap();
|
||||
set_enabled(&home, &warm, true).unwrap();
|
||||
let classic = find(&home, Kind::Shader, "Classic.zip").unwrap();
|
||||
set_enabled(&home, &classic, true).unwrap();
|
||||
assert_eq!(
|
||||
fs::read_to_string(home.join("horizon-graphics.txt")).unwrap(),
|
||||
"preset:custom\npickedShaderPack:Classic.zip\nfxaa:true\n",
|
||||
"one shader pack at a time"
|
||||
);
|
||||
set_enabled(
|
||||
&home,
|
||||
&find(&home, Kind::Shader, "Classic.zip").unwrap(),
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(list(&home, Kind::Shader).iter().all(|p| !p.enabled));
|
||||
|
||||
// A fresh instance has neither file yet.
|
||||
let fresh = scratch("fresh");
|
||||
fs::create_dir_all(fresh.join("resourcepacks")).unwrap();
|
||||
fs::copy(
|
||||
home.join("resourcepacks/Zed.zip"),
|
||||
fresh.join("resourcepacks/Zed.zip"),
|
||||
)
|
||||
.unwrap();
|
||||
set_enabled(
|
||||
&fresh,
|
||||
&find(&fresh, Kind::Resource, "Zed.zip").unwrap(),
|
||||
true,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
fs::read_to_string(fresh.join("options.txt")).unwrap(),
|
||||
"resourcePacks:[\"vanilla\",\"file/Zed.zip\"]\n"
|
||||
);
|
||||
fs::remove_dir_all(&home).unwrap();
|
||||
fs::remove_dir_all(&fresh).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_file_goes_to_its_folder_under_a_free_name() {
|
||||
let home = home("add");
|
||||
let drops = scratch("drops");
|
||||
zip_file(&drops.join("Zed.zip"), &[("pack.mcmeta", META)]);
|
||||
zip_file(&drops.join("Shiny.zip"), &[("shaders/composite.fsh", b"")]);
|
||||
fs::write(drops.join("glow.hshader"), b"PK").unwrap();
|
||||
zip_file(&drops.join("random.zip"), &[("a.txt", b"")]);
|
||||
fs::write(drops.join("picture.png"), b"").unwrap();
|
||||
|
||||
let added = add(&home, &drops.join("Zed.zip")).unwrap();
|
||||
assert_eq!(
|
||||
(added.kind, added.file.as_str(), added.enabled),
|
||||
(Kind::Resource, "Zed (2).zip", false)
|
||||
);
|
||||
assert_eq!(
|
||||
add(&home, &drops.join("Shiny.zip")).unwrap().kind,
|
||||
Kind::Shader
|
||||
);
|
||||
assert!(home.join("shaderpacks/Shiny.zip").is_file());
|
||||
assert_eq!(kind_of(&drops.join("glow.hshader")).unwrap(), Kind::Shader);
|
||||
assert!(add(&home, &drops.join("random.zip")).is_err());
|
||||
assert!(add(&home, &drops.join("picture.png")).is_err());
|
||||
fs::remove_dir_all(&home).unwrap();
|
||||
fs::remove_dir_all(&drops).unwrap();
|
||||
}
|
||||
Reference in New Issue
Block a user