diff --git a/Cargo.lock b/Cargo.lock index aa73eb9..f695b48 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3770,6 +3770,7 @@ dependencies = [ "paleto-formats", "paleto-rpf", "tempfile", + "zip", ] [[package]] diff --git a/README.md b/README.md index e114be0..1996060 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ - View, export and replace textures (`.ytd`) from DDS or PNG; preview 3D models; play and replace sounds. **Install mods** -- Install `.oiv` packages and add-on packs (`dlc.rpf`), with the DLC list updated for you. +- Install `.oiv` and `.oivs` packages and add-on packs (`dlc.rpf`), with the DLC list updated for you. - On Enhanced, convert models and textures made for Legacy, built in (CodeWalker's converter, no Wine). - Export your own changes as an `.oiv`, to share them or reinstall them later. diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index 726cfc3..4f110b9 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -20,3 +20,4 @@ libc = "0.2" [dev-dependencies] tempfile = "3" +zip = { version = "9", default-features = false, features = ["deflate"] } diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index c741deb..0d93391 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -161,10 +161,11 @@ enum Command { Mkdir { path: String }, /// Create a new, empty archive. New { path: PathBuf }, - /// Install an OIV package into the mods folder, or an add-on pack: a - /// dlc.rpf (or a folder holding them) goes to update/x64/dlcpacks// - /// and into the DLC list. For the Enhanced edition, files made for Legacy - /// are converted first (when paleto-cwconv is installed). + /// Install an OIV package (.oiv, or a super package .oivs) into the mods + /// folder, or an add-on pack: a dlc.rpf (or a folder holding them) goes to + /// update/x64/dlcpacks// and into the DLC list. For the Enhanced + /// edition, files made for Legacy are converted first (when paleto-cwconv + /// is installed). Install { package: PathBuf, /// Install files made for Legacy as they are. @@ -173,6 +174,14 @@ enum Command { /// The add-on pack's name (by default its folder's, or the one in its setup2.xml). #[arg(long)] name: Option, + /// What to install of a super package, over what it ticks itself: + /// MODULE ticks a module, -MODULE unticks one, GROUP=OPTION or + /// GROUP=none chooses in a group. Example: "visuals,-sfx,alt=both". + #[arg(long, value_name = "CHOICES", allow_hyphen_values = true)] + select: Option, + /// Show what a super package offers and what would be installed; install nothing. + #[arg(long)] + list: bool, }, /// Convert Legacy models, textures and particles to the Enhanced format /// (with CodeWalker's converter, paleto-cwconv). Without files: every such @@ -823,8 +832,9 @@ fn main() -> Result<()> { } } } - Command::Install { package, no_convert, name } if !package.extension().is_some_and(|e| e.eq_ignore_ascii_case("oiv")) => { + Command::Install { package, no_convert, name, select, list } if !package.extension().is_some_and(|e| e.eq_ignore_ascii_case("oiv") || e.eq_ignore_ascii_case("oivs")) => { use paleto_core::addon; + anyhow::ensure!(select.is_none() && !list, "--select and --list are for super packages (.oivs)"); let game = find_game(cli.game.as_deref(), None)?; let keys = game.keys()?; let packs = addon::find_packs(std::slice::from_ref(&package), Some(&keys)); @@ -839,12 +849,29 @@ fn main() -> Result<()> { println!(" {line}"); } } - Command::Install { package, no_convert, .. } => { - let game = find_game(cli.game.as_deref(), None)?; - let keys = game.keys()?; + Command::Install { package, no_convert, select, list, .. } => { let mut pkg = Package::open(&package).with_context(|| format!("opening {}", package.display()))?; let m = &pkg.metadata; - println!("{} {} by {} (OIV {})", m.name, m.version, m.author, m.format_version); + println!("{} {} by {} ({} {})", m.name, m.version, m.author, if pkg.choices.is_some() { "OIVS" } else { "OIV" }, m.format_version); + match pkg.choices.clone() { + Some(choices) => { + let selection = choices.parse_selection(select.as_deref().unwrap_or_default())?; + print_choices(&choices, &selection); + if list { + return Ok(()); + } + anyhow::ensure!(choices.installs_anything(&selection), "nothing is chosen: choose with --select (the ids above)"); + pkg.select(&selection)?; + } + None => anyhow::ensure!(select.is_none() && !list, "--select and --list are for super packages (.oivs)"), + } + let game = find_game(cli.game.as_deref(), None)?; + let keys = game.keys()?; + if let Some(made) = pkg.metadata.game_version + && made != game.edition + { + println!("! the package is made for GTA V {made:?}, the game is {:?}: it may crash on it", game.edition); + } if game.edition == paleto_core::Edition::Enhanced { let legacy = pkg.legacy_files(Some(&keys))?; if !legacy.is_empty() { @@ -1268,6 +1295,26 @@ fn write_file(path: &Path, data: &[u8]) -> Result<()> { Ok(()) } +/// What a super package offers, marked as `selection` chooses it, with the ids `--select` takes. +fn print_choices(choices: &paleto_core::oiv::Choices, selection: &paleto_core::oiv::Selection) { + let mark = |on: bool, mark: char| if on { mark } else { ' ' }; + if !choices.modules.is_empty() { + println!("modules:"); + } + for (m, &on) in choices.modules.iter().zip(&selection.modules) { + println!(" [{}] {:<20} {}{}", mark(on || m.required, 'x'), m.part.id, m.part.label(), if m.required { " (required)" } else { "" }); + } + for (g, &choice) in choices.groups.iter().zip(&selection.groups) { + println!("group {} ({}):", g.id, g.label()); + if g.allow_none { + println!(" ({}) none", mark(choice.is_none(), '*')); + } + for (i, o) in g.options.iter().enumerate() { + println!(" ({}) {:<20} {}", mark(choice == Some(i), '*'), o.id, o.label()); + } + } +} + /// What the writer noted when it finished (a backup it could not remove). fn show_notes(log: Vec) { for line in log { @@ -1417,7 +1464,7 @@ fn changes_game(command: &Command) -> Option> { } Command::Xml { path, import: Some(_), .. } | Command::Text { path, import: Some(_), .. } => inside(path), Command::Audio { path, replace, .. } if !replace.is_empty() => inside(path), - Command::Install { .. } | Command::Clean { delete: true } => Some(None), + Command::Install { list: false, .. } | Command::Clean { delete: true } => Some(None), Command::Hunt { action } if !matches!(action, None | Some(HuntAction::Status)) => Some(None), Command::Snapshot { action: Some(SnapshotAction::Save { .. } | SnapshotAction::Restore { .. } | SnapshotAction::Delete { .. }) } => Some(None), Command::Convert { undo: Some(_), .. } => Some(None), diff --git a/crates/cli/tests/install.rs b/crates/cli/tests/install.rs new file mode 100644 index 0000000..bed2bf7 --- /dev/null +++ b/crates/cli/tests/install.rs @@ -0,0 +1,66 @@ +//! `paleto install` of a super package (.oivs): what it offers, and choosing from it. + +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; + +fn paleto(dir: &Path, args: &[&str]) -> Output { + let mut cmd = Command::new(env!("CARGO_BIN_EXE_paleto")); + // No game or settings of the user's: an empty home. + cmd.env("HOME", dir).env_remove("XDG_CONFIG_HOME").env_remove("XDG_DATA_HOME").current_dir(dir).args(args); + cmd.output().unwrap() +} + +fn zip(path: &Path, entries: &[(&str, &str)]) -> PathBuf { + let mut zip = zip::ZipWriter::new(std::fs::File::create(path).unwrap()); + for (name, data) in entries { + zip.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap(); + zip.write_all(data.as_bytes()).unwrap(); + } + zip.finish().unwrap(); + path.to_path_buf() +} + +const SUPER: &str = r#"Pack10 + +scripts\b.asi +scripts\e.asi + + + +"#; + +#[test] +fn lists_and_chooses_what_a_super_package_offers() { + let dir = tempfile::tempdir().unwrap(); + let package = zip(&dir.path().join("pack.oivs"), &[("super.xml", SUPER), ("content/b.asi", "b"), ("content/e.asi", "e"), ("content/o.asi", "o")]); + let package = package.to_string_lossy(); + let out = paleto(dir.path(), &["install", "--list", "--select", "extra,alt=one", &package]); + let text = String::from_utf8_lossy(&out.stdout); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + for line in ["Pack 1.0 by (OIVS 1.0)", "[x] base", "(required)", "[x] extra", "group alt (Alternative):", "( ) none", "(*) one"] { + assert!(text.contains(line), "{line}: {text}"); + } + let unknown = paleto(dir.path(), &["install", "--select", "nope", &package]); + assert!(!unknown.status.success() && String::from_utf8_lossy(&unknown.stderr).contains("no module nope")); + // A value that starts with '-' unticks a module. + let out = paleto(dir.path(), &["install", "--list", "--select", "-extra", &package]); + assert!(out.status.success() && String::from_utf8_lossy(&out.stdout).contains("[ ] extra"), "{}", String::from_utf8_lossy(&out.stderr)); + // Not for an add-on pack, which would be installed. + std::fs::write(dir.path().join("dlc.rpf"), b"").unwrap(); + let out = paleto(dir.path(), &["install", "--list", &dir.path().join("dlc.rpf").to_string_lossy()]); + assert!(!out.status.success() && String::from_utf8_lossy(&out.stderr).contains("are for super packages (.oivs)")); + let plain = zip(&dir.path().join("plain.oiv"), &[("assembly.xml", r#"P"#)]); + let out = paleto(dir.path(), &["install", "--list", &plain.to_string_lossy()]); + assert!(!out.status.success() && String::from_utf8_lossy(&out.stderr).contains("are for super packages (.oivs)")); +} + +#[test] +fn a_super_package_with_nothing_chosen_installs_nothing() { + let dir = tempfile::tempdir().unwrap(); + let manifest = SUPER.replace(r#"required="true""#, r#"required="false""#); + let package = zip(&dir.path().join("pack.oivs"), &[("super.xml", &manifest), ("content/b.asi", "b"), ("content/e.asi", "e"), ("content/o.asi", "o")]); + let out = paleto(dir.path(), &["install", &package.to_string_lossy()]); + assert!(!out.status.success()); + assert!(String::from_utf8_lossy(&out.stderr).contains("nothing is chosen: choose with --select"), "{}", String::from_utf8_lossy(&out.stderr)); +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 653560b..dd324b1 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -35,6 +35,8 @@ mod link_matrix_tests; #[cfg(test)] mod oiv_txn_tests; #[cfg(test)] +mod oivs_tests; +#[cfg(test)] mod write_safety_tests; pub use game::{Edition, Game}; diff --git a/crates/core/src/oiv.rs b/crates/core/src/oiv.rs index a9ca996..a9f55c4 100644 --- a/crates/core/src/oiv.rs +++ b/crates/core/src/oiv.rs @@ -1,5 +1,8 @@ //! OpenIV packages (`.oiv`, format 2.x): a zip with `assembly.xml`, an -//! optional `icon.png` and a `content/` folder. +//! optional `icon.png` and a `content/` folder. Super packages (`.oivs`, made +//! for CodeWalker's OIV Package Installer) have `super.xml` instead, whose +//! modules and groups of options each hold the commands of an `assembly.xml` +//! (see [`Choices`]), and pictures in `media/`. //! //! Installation always targets the mods folder for game data; the original //! game files are never modified. @@ -17,7 +20,7 @@ use zip::ZipArchive; use crate::budget::{self, Budget, Limits, Scratch}; use crate::convert; use crate::fsroot::{Dir, GameRoots, Resolved, RootKind}; -use crate::game::Game; +use crate::game::{Edition, Game}; use crate::relpath::RelPath; use crate::txn::{self, Staged, Txn, TxnFailure}; use crate::text::{self, Condition, TextOp}; @@ -32,6 +35,8 @@ pub struct Metadata { pub version: String, pub author: String, pub description: String, + /// The edition the package says it is made for (``), if it says. + pub game_version: Option, } #[derive(Debug, Clone)] @@ -50,12 +55,70 @@ enum Command { pub struct Package { entries: Entries, pub metadata: Metadata, + /// What a super package lets the user choose; none for a plain one. + pub choices: Option, + /// What [`Package::install`] runs: a super package's chosen parts (see [`Package::select`]). content: Vec, /// Content converted to the Enhanced format, by zip entry name (lower case), /// installed in place of the package's own. converted: HashMap, } +/// What a super package installs: the modules ticked, each of its own, and one option of each group. The +/// modules come first in their order, then the groups', so a later one replaces a file an earlier one adds. +#[derive(Debug, Clone, Default)] +pub struct Choices { + pub modules: Vec, + pub groups: Vec, +} + +#[derive(Debug, Clone)] +pub struct Module { + pub part: Part, + /// Always installed. + pub required: bool, + /// Ticked at first. + pub default: bool, +} + +/// A choice of one option, or of none if `allow_none`. +#[derive(Debug, Clone)] +pub struct Group { + pub id: String, + pub title: String, + pub description: String, + pub allow_none: bool, + /// The option chosen at first. + pub default: Option, + pub options: Vec, +} + +/// A module or an option: what it is called, says and shows, and its commands. +#[derive(Debug, Clone)] +pub struct Part { + pub id: String, + pub name: String, + pub description: String, + pub media: Vec, + content: Vec, +} + +/// A picture of a part, by its path in the package (read it with [`Package::media`]). +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Media { + Image { src: String, caption: String }, + /// The game before and after the part. + Compare { title: String, before: String, after: String }, +} + +/// What to install of a super package: whether each module is ticked and the option chosen in each group, +/// in the package's order (required modules are installed whatever their flag says). +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Selection { + pub modules: Vec, + pub groups: Vec>, +} + /// Converted content: small files are held, an archive stays in a file (its folder already gone). enum Converted { Bytes(Vec), @@ -65,6 +128,9 @@ enum Converted { /// How many nodes `assembly.xml` may have (a legitimate one has a few thousand). const MAX_NODES: u32 = 2_000_000; +/// The largest picture of a super package that is read: a 4096×4096 screenshot as a PNG (CodeWalker's packer makes them smaller). +pub const MAX_MEDIA: u64 = 32 << 20; + impl Package { pub fn open(path: &Path) -> Result { Self::open_with(path, Limits::PACKAGE) @@ -77,22 +143,33 @@ impl Package { budget::zip_precheck(&mut file, &limits)?; let zip = budget::zip_open(file).map_err(zip_err)?; let mut entries = Entries::new(zip, limits)?; - let assembly = entries.read("assembly.xml", limits.manifest)?; + let manifest = if entries.find("super.xml").is_ok() { "super.xml" } else { "assembly.xml" }; + let (tag, major) = if manifest == "super.xml" { ("superpackage", "1.") } else { ("package", "2.") }; + let assembly = entries.read(manifest, limits.manifest)?; let assembly = String::from_utf8_lossy(assembly.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(&assembly)).into_owned(); let options = roxmltree::ParsingOptions { nodes_limit: MAX_NODES, ..Default::default() }; - let doc = roxmltree::Document::parse_with_options(&assembly, options).map_err(|e| Error::Package(format!("assembly.xml: {e}")))?; + let doc = roxmltree::Document::parse_with_options(&assembly, options).map_err(|e| Error::Package(format!("{manifest}: {e}")))?; let root = doc.root_element(); - if !root.has_tag_name("package") { - return Err(Error::Package("assembly.xml: root is not ".into())); + if !root.has_tag_name(tag) { + return Err(Error::Package(format!("{manifest}: root is not <{tag}>"))); } let format_version = root.attribute("version").unwrap_or("").to_string(); - if !format_version.starts_with("2.") { + // A super package without a version is read too, as CodeWalker's installer reads it (that one reads any version). + if !format_version.starts_with(major) && !(tag == "superpackage" && format_version.is_empty()) { return Err(Error::Package(format!("unsupported package format {format_version}"))); } if let Some(target) = root.attribute("target") && !target.eq_ignore_ascii_case("five") { return Err(Error::Package(format!("package is for another game ({target})"))); } + // Anywhere in the file, as CodeWalker's installer reads it. + let game_version = root.descendants().find(|n| n.is_element() && n.tag_name().name().eq_ignore_ascii_case("gameversion")).and_then(|n| { + match n.text().unwrap_or("").trim().to_ascii_lowercase().as_str() { + "enhanced" | "gen9" => Some(Edition::Enhanced), + "legacy" | "gen8" => Some(Edition::Legacy), + _ => None, + } + }); let meta = child(root, "metadata"); let text_of = |path: &[&str]| -> String { @@ -114,11 +191,41 @@ impl Package { version, author: text_of(&["author", "displayName"]), description: text_of(&["description"]), + game_version, }; + if manifest == "super.xml" { + let choices = Choices::parse(root, &assembly, &entries)?; + let content = choices.content(&choices.default_selection())?; + return Ok(Package { entries, metadata, choices: Some(choices), content, converted: HashMap::new() }); + } let content = child(root, "content").ok_or_else(|| Error::Package("assembly.xml: missing ".into()))?; let content = parse_commands(content, assembly.as_str())?; - Ok(Package { entries, metadata, content, converted: HashMap::new() }) + Ok(Package { entries, metadata, choices: None, content, converted: HashMap::new() }) + } + + /// Chooses what a super package installs (at first, [`Choices::default_selection`]); before + /// [`Package::convert_legacy`] and [`Package::install`]. A plain package has nothing to choose. + pub fn select(&mut self, selection: &Selection) -> Result<(), Error> { + if let Some(choices) = &self.choices { + self.content = choices.content(selection)?; + } + Ok(()) + } + + /// A picture of a super package's [`Media`], by its path in the package; none if there is none or it is + /// over [`MAX_MEDIA`] (it is not read then). + pub fn media(&mut self, src: &str) -> Option> { + self.entries.fresh(); + self.entries.read(src.trim_start_matches(['/', '\\']), MAX_MEDIA.min(self.entries.budget.limits().in_memory)).ok() + } + + /// The width and height a picture of [`Package::media`] says it has, from its PNG header (nothing more is read); none + /// if there is none or it is not a PNG. + pub fn media_size(&mut self, src: &str) -> Option<(u32, u32)> { + let head = self.entries.head(src.trim_start_matches(['/', '\\']), 24).ok()?; + let be = |at: usize| u32::from_be_bytes([head[at], head[at + 1], head[at + 2], head[at + 3]]); + (head.len() == 24 && head.starts_with(b"\x89PNG\r\n\x1a\n") && &head[12..16] == b"IHDR").then(|| (be(16), be(20))) } /// The package's picture; none if there is none or it is over the limit (it is not read then). @@ -127,8 +234,8 @@ impl Package { self.entries.read("icon.png", self.entries.budget.limits().icon).ok() } - /// The `` sources, at every level. - fn add_sources(&self) -> Vec { + /// The `` sources, at every level: of what is chosen, or with `all` of every part of a super package. + fn add_sources(&self, all: bool) -> Vec { fn walk(cmds: &[Command], out: &mut Vec) { for cmd in cmds { match cmd { @@ -140,6 +247,9 @@ impl Package { } let mut out = Vec::new(); walk(&self.content, &mut out); + for part in self.choices.iter().filter(|_| all).flat_map(Choices::parts) { + walk(&part.content, &mut out); + } out.sort(); out.dedup(); out @@ -147,11 +257,12 @@ impl Package { /// The package's files that the Enhanced game needs converted: models, /// textures and particles made for Legacy, loose or inside the archives it - /// adds ("dlc.rpf/x64/vehicles.rpf/car.yft"). Paths use '/' separators. + /// adds ("dlc.rpf/x64/vehicles.rpf/car.yft"), in every part of a super + /// package, chosen or not. Paths use '/' separators. pub fn legacy_files(&mut self, keys: Option<&Keys>) -> Result, Error> { self.entries.fresh(); let mut found = Vec::new(); - for source in self.add_sources() { + for source in self.add_sources(true) { let name = source.replace('\\', "/"); let entry = content_path(&source); if name.to_ascii_lowercase().ends_with(".rpf") { @@ -162,23 +273,23 @@ impl Package { if let Ok(archive) = paleto_rpf::Archive::open(&disk, keys) { found.extend(convert::legacy_in_archive(&archive, keys).into_iter().map(|p| format!("{name}/{p}"))); } - } else if convert::convertible(&name) && convert::needs_conversion(&name, &self.entries.head(&entry)?) { + } else if convert::convertible(&name) && convert::needs_conversion(&name, &self.entries.head(&entry, 16)?) { found.push(name); } } Ok(found) } - /// Converts the package's Legacy files (see [`Package::legacy_files`]) - /// with `tool`, so that [`Package::install`] installs the Enhanced ones. - /// Returns a log; files that cannot be converted are reported there and - /// installed as they are. + /// Converts the package's Legacy files (see [`Package::legacy_files`]) that + /// will be installed (of a super package, what is chosen) with `tool`, so + /// that [`Package::install`] installs the Enhanced ones. Returns a log; + /// files that cannot be converted are reported there and installed as they are. pub fn convert_legacy(&mut self, tool: &Path, keys: Option<&Keys>) -> Result, Error> { self.entries.fresh(); let in_memory = self.entries.budget.limits().in_memory; let mut log = Vec::new(); let mut loose = Vec::new(); - for source in self.add_sources() { + for source in self.add_sources(false) { let name = source.replace('\\', "/"); let entry = content_path(&source).to_ascii_lowercase(); if name.to_ascii_lowercase().ends_with(".rpf") { @@ -199,7 +310,7 @@ impl Package { if let Some((file, len)) = converted? { self.converted.insert(entry, Converted::File(file, len)); } - } else if convert::convertible(&name) && convert::needs_conversion(&name, &self.entries.head(&entry)?) { + } else if convert::convertible(&name) && convert::needs_conversion(&name, &self.entries.head(&entry, 16)?) { let data = self.entries.read(&entry, in_memory)?; loose.push((name, entry, data)); } @@ -303,6 +414,129 @@ impl Package { } } +impl Choices { + /// The `` and `` of `super.xml`. + fn parse(root: roxmltree::Node, src: &str, entries: &Entries) -> Result { + let mut choices = Choices::default(); + let mut folders = Folders::new(entries); + for m in child(root, "modules").into_iter().flat_map(|n| children(n, "module")) { + choices.modules.push(Module { part: Part::parse(m, src, &mut folders)?, required: flag(m, "required"), default: flag(m, "default") }); + } + for g in child(root, "groups").into_iter().flat_map(|n| children(n, "group")) { + let kind = g.attribute("type").unwrap_or("single"); + if !kind.eq_ignore_ascii_case("single") { + return Err(Error::Package(format!("super.xml: unsupported group type {kind}"))); + } + let options = children(g, "option").map(|o| Part::parse(o, src, &mut folders)).collect::, _>>()?; + let allow_none = !g.attribute("allowNone").is_some_and(|v| v.eq_ignore_ascii_case("false")); + let named = g.attribute("default").filter(|d| !d.eq_ignore_ascii_case("none")).and_then(|d| options.iter().position(|o| o.id.eq_ignore_ascii_case(d))); + let default = named.or((!allow_none && !options.is_empty()).then_some(0)); + choices.groups.push(Group { id: attr(g, "id"), title: attr(g, "title"), description: child_text(g, "description"), allow_none, default, options }); + } + Ok(choices) + } + + /// The required modules and those ticked at first, and each group's first option. + pub fn default_selection(&self) -> Selection { + Selection { modules: self.modules.iter().map(|m| m.required || m.default).collect(), groups: self.groups.iter().map(|g| g.default).collect() } + } + + /// A selection from words, over the default one: `id` ticks a module, `-id` (or `!id`) unticks one, and + /// `group=option` or `group=none` chooses in a group; separated by commas. Ids ignore case. This is how + /// CodeWalker's installer takes `--select`. + pub fn parse_selection(&self, spec: &str) -> Result { + let mut sel = self.default_selection(); + for token in spec.split([',', ';']).map(str::trim).filter(|t| !t.is_empty()) { + if let Some((group, option)) = token.split_once('=') { + let (group, option) = (group.trim(), option.trim()); + let g = self.groups.iter().position(|g| g.id.eq_ignore_ascii_case(group)).ok_or_else(|| Error::Package(format!("the package has no group {group}")))?; + sel.groups[g] = if option.eq_ignore_ascii_case("none") { + None + } else { + let found = self.groups[g].options.iter().position(|o| o.id.eq_ignore_ascii_case(option)); + Some(found.ok_or_else(|| Error::Package(format!("the group {group} has no option {option}")))?) + }; + } else { + let (off, id) = token.strip_prefix(['-', '!']).map_or((false, token), |id| (true, id.trim())); + let m = self.modules.iter().position(|m| m.part.id.eq_ignore_ascii_case(id)).ok_or_else(|| Error::Package(format!("the package has no module {id}")))?; + if off && self.modules[m].required { + return Err(Error::Package(format!("the module {id} is required"))); + } + sel.modules[m] = !off; + } + } + self.content(&sel)?; + Ok(sel) + } + + /// Whether `selection` installs anything at all. + pub fn installs_anything(&self, selection: &Selection) -> bool { + self.chosen(selection).is_ok_and(|parts| parts.iter().any(|p| !p.content.is_empty())) + } + + /// The commands of what `selection` chooses, in the order they run. + fn content(&self, selection: &Selection) -> Result, Error> { + Ok(self.chosen(selection)?.into_iter().flat_map(|p| p.content.iter().cloned()).collect()) + } + + /// The parts `selection` chooses, in the order they run. + fn chosen(&self, selection: &Selection) -> Result, Error> { + if selection.modules.len() != self.modules.len() || selection.groups.len() != self.groups.len() { + return Err(Error::Package("the selection is not one of this package".into())); + } + let mut parts: Vec<&Part> = self.modules.iter().zip(&selection.modules).filter(|(m, on)| **on || m.required).map(|(m, _)| &m.part).collect(); + for (group, choice) in self.groups.iter().zip(&selection.groups) { + match choice { + Some(i) => parts.push(group.options.get(*i).ok_or_else(|| Error::Package(format!("the group {} has no option {}", group.id, i + 1)))?), + None if !group.allow_none && !group.options.is_empty() => return Err(Error::Package(format!("{} needs one of its options", group.label()))), + None => {} + } + } + Ok(parts) + } + + /// Every module and option. + fn parts(&self) -> impl Iterator { + self.modules.iter().map(|m| &m.part).chain(self.groups.iter().flat_map(|g| &g.options)) + } +} + +impl Group { + /// What to call it: its title, else its id. + pub fn label(&self) -> &str { + if self.title.trim().is_empty() { &self.id } else { &self.title } + } +} + +impl Part { + /// A `` or an `"#); + let open = |name: &str, extra: &str| Package::open(&oiv_raw(dir.path(), name, [("assembly.xml".to_string(), assembly(extra).into_bytes())], true)).unwrap(); + assert_eq!(open("a.oiv", "gen8").metadata.game_version, Some(Edition::Legacy)); + assert_eq!(open("b.oiv", "Enhanced").metadata.game_version, Some(Edition::Enhanced)); + let plain = open("c.oiv", ""); + assert_eq!(plain.metadata.game_version, None); + assert!(plain.choices.is_none()); +} + +#[test] +fn legacy_files_of_every_part_are_found() { + let res = |v: u32| [b"RSC7".as_slice(), &v.to_le_bytes(), &((v >> 4) << 28).to_le_bytes(), &((v & 15) << 28).to_le_bytes(), b"payload"].concat(); + let manifest = r#" + car.yft + "#; + let dir = tempfile::tempdir().unwrap(); + let car = res(162); + let mut pkg = Package::open(&oivs(dir.path(), "car.oivs", manifest, &[("content/car/car.yft", &car)])).unwrap(); + // Not chosen, yet in the package. + assert!(!pkg.choices.as_ref().unwrap().installs_anything(&pkg.choices.as_ref().unwrap().default_selection())); + assert_eq!(pkg.legacy_files(None).unwrap(), ["car/car.yft"]); +} + +#[test] +fn the_size_of_a_picture_is_read_from_its_header() { + let dir = tempfile::tempdir().unwrap(); + let head = [b"\x89PNG\r\n\x1a\n\0\0\0\x0dIHDR".as_slice(), &1280u32.to_be_bytes(), &720u32.to_be_bytes(), b"and the rest"].concat(); + let mut pkg = Package::open(&oivs(dir.path(), "p.oivs", SUPER, &[("media/a.png", &head), ("media/b.png", b"not a picture at all")])).unwrap(); + assert_eq!(pkg.media_size("\\Media\\A.png"), Some((1280, 720))); + assert_eq!(pkg.media_size("media/b.png"), None); + assert_eq!(pkg.media_size("media/none.png"), None); +} diff --git a/crates/gui/src/actions.rs b/crates/gui/src/actions.rs index 06853a5..774881a 100644 --- a/crates/gui/src/actions.rs +++ b/crates/gui/src/actions.rs @@ -378,7 +378,7 @@ impl App { } } Action::PickPackage => { - let dialog = rfd::FileDialog::new().add_filter("Mod package (.oiv, dlc.rpf)", &["oiv", "rpf"]).set_title("Install a package or an add-on pack"); + let dialog = rfd::FileDialog::new().add_filter("Mod package (.oiv, .oivs, dlc.rpf)", &["oiv", "oivs", "rpf"]).set_title("Install a package or an add-on pack"); if let Some(path) = dialog.pick_file() { if path.extension().is_some_and(|e| e.eq_ignore_ascii_case("rpf")) { let packs = paleto_core::addon::find_packs(std::slice::from_ref(&path), self.keys.as_deref()); @@ -397,8 +397,12 @@ impl App { let Some(mut package) = dialog.package.take() else { return }; let (game, keys) = (game.clone(), keys.clone()); let tool = (dialog.convert && !dialog.legacy.is_empty()).then(paleto_core::convert::converter).flatten(); + let selection = dialog.selection.clone(); self.task = Some(Task::spawn(format!("Installing {}", dialog.metadata.name), ctx, move || { let mut log = Vec::new(); + if let Err(e) = package.select(&selection) { + return Outcome::Installed(Err(install_failure(&e, log))); + } if let Some(tool) = &tool { match package.convert_legacy(tool, Some(&keys)) { Ok(converted) => log = converted, diff --git a/crates/gui/src/app.rs b/crates/gui/src/app.rs index 96483b0..1bf8c09 100644 --- a/crates/gui/src/app.rs +++ b/crates/gui/src/app.rs @@ -996,7 +996,7 @@ impl eframe::App for App { } if !dropped.is_empty() { let (packages, files): (Vec<_>, Vec<_>) = - dropped.into_iter().partition(|p| p.extension().is_some_and(|e| e.eq_ignore_ascii_case("oiv"))); + dropped.into_iter().partition(|p| p.extension().is_some_and(|e| e.eq_ignore_ascii_case("oiv") || e.eq_ignore_ascii_case("oivs"))); if self.busy() { self.status = Status::Error("Wait for the current operation to finish, then drop the files again.".into()); } else if dialog { diff --git a/crates/gui/src/dialogs.rs b/crates/gui/src/dialogs.rs index 042a3d1..b01a139 100644 --- a/crates/gui/src/dialogs.rs +++ b/crates/gui/src/dialogs.rs @@ -1,10 +1,11 @@ //! The dialogs of the app window: installing packages and add-on packs, saving the previewed //! text, replacing textures, asking for a name, deleting. +use std::collections::HashMap; use std::path::{Path, PathBuf}; use eframe::egui::{self, RichText}; -use paleto_core::oiv::Metadata; +use paleto_core::oiv::{Choices, Media, Metadata, Part, Selection}; use paleto_core::texture_batch::{self, TextureBatch}; use paleto_core::{ArchivePath, Package}; @@ -15,7 +16,7 @@ use crate::textures::TextureEdit; use crate::actions::{Action, Unsaved}; use crate::app::{App, Info, Status}; use crate::menus::{about, format_combo, getting_started, shortcuts}; -use crate::preview::{PreviewSource, load_icon}; +use crate::preview::{PreviewSource, load_icon, load_picture}; /// Add-on packs (dlc.rpf) dropped or chosen, to install into the mods folder. @@ -45,6 +46,233 @@ pub(crate) struct InstallDialog { /// Convert them before installing. pub(crate) convert: bool, result: Option, + /// What a super package lets the user choose (a copy: the package itself goes to the install task). + choices: Option, + /// What is chosen of `choices`; empty for a plain package. + pub(crate) selection: Selection, + /// The module or option whose pictures are shown. + focus: Option, + /// How wide the widest row of pictures of the package is for each point of its height (an image: its width over its + /// height; a comparison: both side by side); none if it has no pictures. The dialog is sized for it once, so that it + /// does not change size as the pointer moves over the parts. + widest: Option, + /// Decoded pictures by their path in the package; none for one that is missing or cannot be decoded. + pictures: HashMap>, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Focus { + Module(usize), + /// An option of a group. + Option(usize, usize), +} + +/// The longest side a picture of a package is kept at for display. +const PICTURE_SIDE: u32 = 1024; + +/// The width of the list of choices beside the pictures. +const LIST_WIDTH: f32 = 400.0; + +/// The most media items shown for one module or option (a comparison is two pictures, each decoded when first shown). +const MAX_PICTURES: usize = 4; + +impl InstallDialog { + fn part(&self, focus: Focus) -> Option<&Part> { + let choices = self.choices.as_ref()?; + match focus { + Focus::Module(m) => choices.modules.get(m).map(|m| &m.part), + Focus::Option(g, o) => choices.groups.get(g)?.options.get(o), + } + } + + /// The picture at `src`, read from the package and decoded the first time it is asked for under any spelling. + fn picture(&mut self, ctx: &egui::Context, src: &str) -> Option { + // The package finds a name in any case and with either separator. + let key = src.replace('\\', "/").trim_start_matches('/').to_ascii_lowercase(); + if !self.pictures.contains_key(&key) { + let png = self.package.as_mut()?.media(src); + let texture = png.and_then(|png| load_picture(ctx, &key, &png, PICTURE_SIDE)); + self.pictures.insert(key.clone(), texture); + } + self.pictures[&key].clone() + } +} + +/// The modules and groups of a super package to choose from, and the pictures of the one in focus beside them. +fn choices_section(ui: &mut egui::Ui, d: &mut InstallDialog, height: f32) { + let spacing = ui.spacing().item_spacing.x; + let has_media = d.widest.is_some(); + let list_width = if has_media { LIST_WIDTH } else { ui.available_width() }; + let pictures_width = (ui.available_width() - list_width - spacing).max(0.0); + // Both columns keep the same height whatever is shown: a dialog that changed size would move the parts under the + // pointer, and hovering a part shows its pictures. + ui.horizontal_top(|ui| { + ui.vertical(|ui| { + ui.set_width(list_width); + if has_media { + ui.set_min_height(height); + } + egui::ScrollArea::vertical().id_salt("install-choices").max_height(height).show(ui, |ui| choices_list(ui, d)); + }); + if has_media { + ui.vertical(|ui| { + ui.set_width(pictures_width); + ui.set_min_height(height); + pictures(ui, d, height); + }); + } + }); +} + +fn choices_list(ui: &mut egui::Ui, d: &mut InstallDialog) { + let (Some(choices), selection, focus) = (&d.choices, &mut d.selection, &mut d.focus) else { return }; + for (m, module) in choices.modules.iter().enumerate() { + let part = &module.part; + let block = ui.vertical(|ui| { + let mut on = module.required || selection.modules[m]; + let text = if module.required { format!("{} (required)", part.label()) } else { part.label().to_string() }; + let response = ui.add_enabled(!module.required, egui::Checkbox::new(&mut on, text)); + if response.changed() { + selection.modules[m] = on; + } + describe(ui, ("module", m), &part.description); + response + }); + if !part.media.is_empty() && (block.inner.clicked() || block.response.contains_pointer()) { + *focus = Some(Focus::Module(m)); + } + ui.add_space(4.0); + } + for (g, group) in choices.groups.iter().enumerate() { + ui.separator(); + ui.label(RichText::new(group.label()).strong()); + describe(ui, ("group", g), &group.description); + let none = group.allow_none.then_some(None).into_iter(); + for (o, choice) in none.chain((0..group.options.len()).map(Some)).enumerate() { + let part = choice.map(|o| &group.options[o]); + let block = ui.vertical(|ui| { + let response = ui.radio_value(&mut selection.groups[g], choice, part.map_or("None", Part::label)); + if let Some(part) = part { + describe(ui, ("option", g, o), &part.description); + } + response + }); + if let (Some(option), Some(part)) = (choice, part) + && !part.media.is_empty() + && (block.inner.clicked() || block.response.contains_pointer()) + { + *focus = Some(Focus::Option(g, option)); + } + ui.add_space(2.0); + } + } +} + +/// A part's description under its control, a little indented. +fn describe(ui: &mut egui::Ui, id: impl std::hash::Hash + std::fmt::Debug, text: &str) { + if text.trim().is_empty() { + return; + } + ui.scope(|ui| { + ui.visuals_mut().indent_has_left_vline = false; + ui.indent(id, |ui| ui.label(RichText::new(text.trim()).weak())); + }); +} + +/// The pictures of the module or option in focus, each as large as the room allows: an image with its caption, a comparison +/// as before and after side by side. `height` is the room for one row with its labels; more rows scroll. +fn pictures(ui: &mut egui::Ui, d: &mut InstallDialog, height: f32) { + let Some(focus) = d.focus else { return }; + let Some(part) = d.part(focus) else { return }; + let (label, media) = (part.label().to_string(), part.media.clone()); + let ctx = ui.ctx().clone(); + // A row of text, and what follows each item (its spacing and the space after it), so that one item fits without scrolling. + let (row, trail) = (label_row(ui), ui.spacing().item_spacing.y + ITEM_GAP); + egui::ScrollArea::vertical().id_salt("install-pictures").max_height(height).show(ui, |ui| { + ui.label(RichText::new(label).strong()); + let width = ui.available_width(); + for item in media.iter().take(MAX_PICTURES) { + match item { + Media::Image { src, caption } => { + let Some(texture) = d.picture(&ctx, src) else { continue }; + let captioned = !caption.trim().is_empty(); + show_picture(ui, &texture, egui::vec2(width, height - trail - row * if captioned { 2.0 } else { 1.0 })); + if captioned { + ui.label(RichText::new(caption.trim()).weak()); + } + } + Media::Compare { title, before, after } => { + let shots = [("Before", d.picture(&ctx, before)), ("After", d.picture(&ctx, after))]; + if shots.iter().all(|(_, texture)| texture.is_none()) { + continue; + } + let titled = !title.trim().is_empty(); + if titled { + ui.label(title.trim()); + } + let half = (width - ui.spacing().item_spacing.x) / 2.0; + let room = egui::vec2(half, height - trail - row * if titled { 3.0 } else { 2.0 }); + ui.horizontal_top(|ui| { + for (name, texture) in &shots { + let Some(texture) = texture else { continue }; + ui.vertical(|ui| { + ui.set_width(half); + ui.label(RichText::new(*name).weak()); + show_picture(ui, texture, room); + }); + } + }); + } + } + ui.add_space(ITEM_GAP); + } + }); +} + +/// The space after each picture item. +const ITEM_GAP: f32 = 6.0; + +/// A picture as large as it fits in `room`, in the middle of its width. +fn show_picture(ui: &mut egui::Ui, texture: &egui::TextureHandle, room: egui::Vec2) { + let size = fit(texture.size_vec2(), room); + ui.allocate_ui_with_layout(egui::vec2(room.x, size.y), egui::Layout::top_down(egui::Align::Center), |ui| ui.add(egui::Image::new(texture).fit_to_exact_size(size))); +} + +/// A picture of `size` as large as it fits in `room`, keeping its shape. +fn fit(size: egui::Vec2, room: egui::Vec2) -> egui::Vec2 { + size * (room.x / size.x).min(room.y / size.y).max(0.0) +} + +/// The height of a line of text and the space after it. +fn label_row(ui: &egui::Ui) -> f32 { + ui.text_style_height(&egui::TextStyle::Body) + ui.spacing().item_spacing.y +} + +/// See [`InstallDialog::widest`]. Read from the pictures' headers; one that says nothing counts as 16:9, and a picture +/// counts as no narrower than 1:2 and no wider than 3:1, so that a strange one cannot squeeze the dialog. +fn widest_row(package: &mut Package, choices: &Choices) -> f32 { + let mut shape = |src: &str| package.media_size(src).filter(|&(w, h)| w > 0 && h > 0).map_or(16.0 / 9.0, |(w, h)| (w as f32 / h as f32).clamp(0.5, 3.0)); + let parts = choices.modules.iter().map(|m| &m.part).chain(choices.groups.iter().flat_map(|g| &g.options)); + parts + .flat_map(|p| p.media.iter().take(MAX_PICTURES)) + .map(|m| match m { + Media::Image { src, .. } => shape(src), + Media::Compare { before, after, .. } => shape(before) + shape(after), + }) + .fold(0.5, f32::max) +} + +/// The first module or option that has a picture. +fn first_with_media(choices: &Choices) -> Option { + let module = choices.modules.iter().position(|m| !m.part.media.is_empty()).map(Focus::Module); + module.or_else(|| choices.groups.iter().enumerate().find_map(|(g, group)| group.options.iter().position(|o| !o.media.is_empty()).map(|o| Focus::Option(g, o)))) +} + +fn edition_name(edition: paleto_core::Edition) -> &'static str { + match edition { + paleto_core::Edition::Legacy => "Legacy", + paleto_core::Edition::Enhanced => "Enhanced", + } } /// The log of an install, or why it failed and what it did and undid before. @@ -91,7 +319,11 @@ impl App { _ => Vec::new(), }; let convert = paleto_core::convert::converter().is_some(); - self.install = Some(InstallDialog { path: path.to_path_buf(), package: Some(package), metadata, icon, legacy, convert, result: None }); + let choices = package.choices.clone(); + let selection = choices.as_ref().map(Choices::default_selection).unwrap_or_default(); + let focus = choices.as_ref().and_then(first_with_media); + let widest = choices.as_ref().filter(|_| focus.is_some()).map(|c| widest_row(&mut package, c)); + self.install = Some(InstallDialog { path: path.to_path_buf(), package: Some(package), metadata, icon, legacy, convert, result: None, choices, selection, focus, widest, pictures: HashMap::new() }); } Err(e) => self.status = Status::Error(format!("{}: {e}", path.display())), } @@ -152,10 +384,21 @@ impl App { legacy: Vec::new(), convert: false, result: None, + choices: None, + selection: Selection::default(), + focus: None, + widest: None, + pictures: HashMap::new(), }); dialog.result = Some(result); } + /// What the install dialog has chosen of a super package, while it is open. + #[doc(hidden)] + pub fn install_selection(&self) -> Option<&Selection> { + self.install.as_ref().filter(|d| d.choices.is_some()).map(|d| &d.selection) + } + /// Shows this failed install as if it had just run, for the tests. #[doc(hidden)] pub fn offer_install_failure(&mut self, e: &paleto_core::Error) { @@ -206,9 +449,20 @@ impl App { let busy = self.busy(); let (game_ready, keys_ready, keys_pending) = (self.game.is_some(), self.keys.is_some(), self.keys_task.is_some()); let can_convert = paleto_core::convert::converter().is_some(); + let edition = self.game.as_ref().map(|g| g.edition); let Some(d) = &mut self.install else { return }; + let screen = ctx.content_rect(); + // The dialog keeps about this much for its header, description, notes and buttons; the rest may go to the pictures. + let picture_height = (screen.height() - 340.0).clamp(100.0, 540.0); egui::Modal::new(egui::Id::unique("install")).show(ctx, |ui| { - ui.set_width(520.0); + // A row of pictures with the part's name above and "Before"/"After" over a comparison. + let section_height = picture_height + 2.0 * label_row(ui); + let width = match (&d.choices, d.widest) { + (None, _) => 520.0, + (Some(_), None) => 560.0, + (Some(_), Some(widest)) => (LIST_WIDTH + 3.0 * ui.spacing().item_spacing.x + picture_height * widest).clamp(560.0, (screen.width() - 60.0).max(560.0)), + }; + ui.set_width(width); ui.horizontal(|ui| { if let Some(icon) = &d.icon { ui.add(egui::Image::new(icon).fit_to_exact_size(egui::vec2(64.0, 64.0))); @@ -229,11 +483,28 @@ impl App { ui.separator(); match &d.result { None => { - egui::ScrollArea::vertical().max_height(crate::widgets::dialog_list_height(ui.ctx())).show(ui, |ui| { + let list_height = crate::widgets::dialog_list_height(ui.ctx()); + let description_height = if d.choices.is_some() { list_height.min(80.0) } else { list_height }; + egui::ScrollArea::vertical().max_height(description_height).show(ui, |ui| { ui.label(&d.metadata.description); }); ui.separator(); + if d.choices.is_some() { + ui.label(RichText::new("What to install").strong()); + choices_section(ui, d, if d.widest.is_some() { section_height } else { list_height + 40.0 }); + ui.separator(); + } + let installs = d.choices.as_ref().is_none_or(|c| c.installs_anything(&d.selection)); crate::widgets::hint(ui, "Game data is installed into the mods folder; the original files are not modified."); + if let (Some(made_for), Some(chosen)) = (d.metadata.game_version, edition) + && made_for != chosen + { + let dark = ui.visuals().dark_mode; + ui.horizontal_wrapped(|ui| { + ui.label(RichText::new("⚠").color(theme::warning(dark))); + ui.label(format!("This package is made for GTA V {}; the chosen game is {}: it may crash.", edition_name(made_for), edition_name(chosen))); + }); + } if !d.legacy.is_empty() { let dark = ui.visuals().dark_mode; ui.horizontal_wrapped(|ui| { @@ -283,7 +554,8 @@ impl App { actions.push(Action::CloseInstall); } } else { - if ui.add(crate::widgets::primary(ui, "Install")).clicked() { + let install = crate::widgets::primary(ui, "Install"); + if ui.add_enabled(installs, install).on_disabled_hover_text("Choose something to install").clicked() { actions.push(Action::Install); } if ui.button("Cancel").clicked() { @@ -826,3 +1098,43 @@ pub(crate) fn desktop_notify(summary: &str, body: &str) { .status(); }); } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_picture_fills_its_room_and_keeps_its_shape() { + let wide = egui::vec2(1280.0, 720.0); + assert_eq!(fit(wide, egui::vec2(640.0, 1000.0)), egui::vec2(640.0, 360.0)); + assert_eq!(fit(wide, egui::vec2(2000.0, 360.0)), egui::vec2(640.0, 360.0)); + // Larger than it is, when there is room. + assert_eq!(fit(egui::vec2(100.0, 50.0), egui::vec2(400.0, 400.0)), egui::vec2(400.0, 200.0)); + } + + #[test] + fn the_dialog_is_as_wide_as_the_widest_row_of_pictures() { + use std::io::Write; + let png = |w: u32, h: u32| [b"\x89PNG\r\n\x1a\n\0\0\0\x0dIHDR".as_slice(), &w.to_be_bytes(), &h.to_be_bytes()].concat(); + let package = |media: &str, files: &[(&str, Vec)]| { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("p.oivs"); + let mut zip = zip::ZipWriter::new(std::fs::File::create(&path).unwrap()); + let xml = format!(r#"{media}"#); + for (name, data) in [("super.xml", xml.as_bytes())].into_iter().chain(files.iter().map(|(n, d)| (*n, d.as_slice()))) { + zip.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); + zip.write_all(data).unwrap(); + } + zip.finish().unwrap(); + let mut package = Package::open(&path).unwrap(); + let choices = package.choices.clone().unwrap(); + widest_row(&mut package, &choices) + }; + let wide = ("media/wide.png", png(1280, 720)); + // A comparison of two squares is wider than one 16:9 picture. + assert_eq!(package(r#""#, &[wide.clone(), ("media/a.png", png(500, 500))]), 2.0); + // A picture that cannot be read counts as 16:9; a strange shape counts as at most 3:1. + assert_eq!(package(r#""#, std::slice::from_ref(&wide)), 1280.0 / 720.0); + assert_eq!(package(r#""#, &[wide, ("media/line.png", png(10000, 1))]), 3.0); + } +} diff --git a/crates/gui/src/menus.rs b/crates/gui/src/menus.rs index 0bc74ba..4b8c79c 100644 --- a/crates/gui/src/menus.rs +++ b/crates/gui/src/menus.rs @@ -190,7 +190,7 @@ impl App { let install = egui::Button::new(RichText::new(label).color(selection.stroke.color)).fill(selection.bg_fill); // Short on a narrow window, where it saves room. let width = if narrow { 0.0 } else { right_width(ui) }; - if crate::widgets::bar_button(ui, install, width).on_hover_text("Install an OpenIV package (.oiv) or an add-on pack (dlc.rpf) into the mods folder").clicked() { + if crate::widgets::bar_button(ui, install, width).on_hover_text("Install an OpenIV package (.oiv, .oivs) or an add-on pack (dlc.rpf) into the mods folder").clicked() { actions.push(Action::PickPackage); } } @@ -462,10 +462,10 @@ impl App { ), Some(folder) => { let name = folder.inner.last().cloned().unwrap_or_else(|| folder.disk.file_name().unwrap_or_default().to_string_lossy().into_owned()); - (format!("Add to {name}"), "Files are added to this archive folder; .oiv packages open the installer.".to_string()) + (format!("Add to {name}"), "Files are added to this archive folder; .oiv and .oivs packages open the installer.".to_string()) } None => ( - "Install an .oiv package".to_string(), + "Install an .oiv or .oivs package".to_string(), "To add other files, first open a folder inside an archive (.rpf).".to_string(), ), }; @@ -596,7 +596,7 @@ pub(crate) fn getting_started(ui: &mut egui::Ui) { ui, "4. Install mods", &[ - "Install .oiv packages with Install package… (top right) or by dropping them on the window; add-on packs (dlc.rpf) \ + "Install .oiv and .oivs packages with Install package… (top right) or by dropping them on the window; add-on packs (dlc.rpf) \ the same way. Game data goes to the mods folder, plugins and scripts to the game folder.", "On the Enhanced edition, files made for Legacy are found and can be converted while they are installed.", "Prefix tweaks (beside Install) prepares the game's Wine prefix for ScriptHookVDotNet mods: it installs .NET Framework 4.8, \ diff --git a/crates/gui/src/preview.rs b/crates/gui/src/preview.rs index 4554349..bd9f782 100644 --- a/crates/gui/src/preview.rs +++ b/crates/gui/src/preview.rs @@ -127,7 +127,7 @@ impl App { let ext = path.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default(); if path.is_dir() { self.go(Location::Folder(path)); - } else if ext == "oiv" { + } else if ext == "oiv" || ext == "oivs" { self.open_package(&path, ctx); } else if ext == "rpf" { self.open(ArchivePath::new(path)); @@ -658,6 +658,25 @@ pub(crate) fn load_icon(ctx: &egui::Context, png: &[u8]) -> Option Option { + let mut limits = image::Limits::default(); + limits.max_image_width = Some(4096); + limits.max_image_height = Some(4096); + limits.max_alloc = Some(192 << 20); + let mut reader = image::ImageReader::with_format(std::io::Cursor::new(png), image::ImageFormat::Png); + reader.limits(limits); + let mut img = reader.decode().ok()?; + if img.width() > max_side || img.height() > max_side { + img = img.resize(max_side, max_side, image::imageops::FilterType::Triangle); + } + let img = img.to_rgba8(); + let size = [img.width() as usize, img.height() as usize]; + let color = egui::ColorImage::from_rgba_unmultiplied(size, img.as_raw()); + Some(ctx.load_texture(name, color, egui::TextureOptions::LINEAR)) +} + pub(crate) fn extension(name: &str) -> String { name.rsplit_once('.').map(|(_, e)| e.to_ascii_uppercase()).unwrap_or_default() } diff --git a/crates/gui/src/settings.rs b/crates/gui/src/settings.rs index e358db1..b17429d 100644 --- a/crates/gui/src/settings.rs +++ b/crates/gui/src/settings.rs @@ -194,7 +194,7 @@ impl FileClass { pub fn of(name: &str) -> Self { let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default(); match ext.as_str() { - "rpf" | "oiv" => Self::Archive, + "rpf" | "oiv" | "oivs" => Self::Archive, "ytd" | "dds" | "png" | "jpg" | "jpeg" | "bmp" | "gfx" => Self::Texture, "ydr" | "ydd" | "yft" | "ybn" | "ynv" | "ycd" | "ypt" | "ymf" => Self::Model, "ymap" | "ytyp" | "ynd" | "ymt" => Self::Map, diff --git a/crates/gui/tests/oivs.rs b/crates/gui/tests/oivs.rs new file mode 100644 index 0000000..99f6b5e --- /dev/null +++ b/crates/gui/tests/oivs.rs @@ -0,0 +1,175 @@ +//! Super packages (.oivs) in the install dialog: the choices and their pictures, what an install writes of them, and the warning for a package made for the other edition. + +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use paleto_core::oiv::Selection; +use paleto_modkit::App; + +fn settle(harness: &mut Harness<'_, App>) { + for _ in 0..500 { + harness.step(); + if harness.state().idle() { + break; + } + std::thread::sleep(Duration::from_millis(10)); + } + harness.run_steps(3); +} + +fn png(color: [u8; 4]) -> Vec { + let mut out = Vec::new(); + image::RgbaImage::from_pixel(8, 8, image::Rgba(color)).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out +} + +fn zip_of(path: &Path, files: &[(&str, &[u8])]) { + let mut zip = zip::ZipWriter::new(std::fs::File::create(path).unwrap()); + for (name, data) in files { + zip.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap(); + zip.write_all(data).unwrap(); + } + zip.finish().unwrap(); +} + +/// A super package of a module `base` (required or not), an optional module `extra` with a before/after pair, and a group of two options (or none) whose first has a picture and whose second names a picture the package lacks. +fn super_package(dir: &Path, game_version: &str, base_required: bool) -> PathBuf { + let xml = format!( + r#"{game_version} +Pack10Med + +Always neededscripts\a.asi +Optional extrascripts\b.asi + + + + +"# + ); + let path = dir.join("pack.oivs"); + zip_of( + &path, + &[ + ("super.xml", xml.as_bytes()), + ("content/base/a.asi", b"base"), + ("content/extra/b.asi", b"extra"), + ("content/g/one.asi", b"one"), + ("content/g/two.asi", b"two"), + ("media/a.png", &png([200, 30, 30, 255])), + ("media/b.png", &png([30, 30, 200, 255])), + ], + ); + path +} + +/// The dialog of `package` over a fake Enhanced game folder. +fn open(dir: &Path, package: &Path) -> (Harness<'static, App>, PathBuf) { + let root = dir.join("Grand Theft Auto V Enhanced"); + std::fs::create_dir_all(root.join("mods")).unwrap(); + std::fs::write(root.join("GTA5_Enhanced.exe"), b"").unwrap(); + let mut harness = Harness::builder().with_size([1000.0, 700.0]).build_eframe(|cc| App::new(cc)); + let ctx = harness.ctx.clone(); + harness.state_mut().select_game_folder(&root, &ctx); + settle(&mut harness); + harness.state_mut().open_package(package, &ctx); + // A dialog grows to its size over a few frames; a click must find its controls where they stay. + harness.run_steps(10); + (harness, root) +} + +fn labels(harness: &Harness<'_, App>) -> Vec { + harness.query_all_by_label_contains("").filter_map(|n| n.accesskit_node().label()).collect() +} + +fn selection(modules: &[bool], groups: &[Option]) -> Option { + Some(Selection { modules: modules.to_vec(), groups: groups.to_vec() }) +} + +#[test] +fn the_dialog_lists_the_modules_and_the_options() { + let dir = tempfile::tempdir().unwrap(); + let (harness, _) = open(dir.path(), &super_package(dir.path(), "", true)); + harness.get_by_label("Pack"); + harness.get_by_label("What to install"); + let base = harness.get_by_role_and_label(Role::CheckBox, "Base (required)"); + assert!(base.accesskit_node().is_disabled()); + harness.get_by_label("Always needed"); + let extra = harness.get_by_role_and_label(Role::CheckBox, "Extra"); + assert!(!extra.accesskit_node().is_disabled()); + harness.get_by_label("Optional extra"); + harness.get_by_label("Choice"); + for option in ["One", "Two", "None"] { + harness.get_by_role_and_label(Role::RadioButton, option); + } + assert_eq!(harness.state().install_selection().cloned(), selection(&[true, false], &[None])); +} + +#[test] +fn the_pictures_follow_the_item_last_clicked() { + let dir = tempfile::tempdir().unwrap(); + let (mut harness, _) = open(dir.path(), &super_package(dir.path(), "", true)); + // The first item with pictures is shown at first. + harness.get_by_label("Before"); + harness.get_by_label("After"); + assert!(harness.query_by_label("Dusk").is_none()); + + harness.get_by_role_and_label(Role::RadioButton, "One").click(); + harness.run_steps(3); + harness.get_by_label("Dusk"); + assert!(harness.query_by_label("Before").is_none()); + + // A picture the package lacks shows nothing. + harness.get_by_role_and_label(Role::RadioButton, "Two").click(); + harness.run_steps(3); + assert!(harness.query_by_label("Dusk").is_none() && harness.query_by_label("Before").is_none(), "{:?}", labels(&harness)); +} + +/// What the dialog chooses is what the install gets (`Package::select` before installing; the install itself needs the +/// game's keys, which a fake game has none of, and is tested in paleto-core). +#[test] +fn ticking_and_choosing_make_the_selection() { + let dir = tempfile::tempdir().unwrap(); + let (mut harness, _) = open(dir.path(), &super_package(dir.path(), "", false)); + assert_eq!(harness.state().install_selection().cloned(), selection(&[false, false], &[None])); + harness.get_by_role_and_label(Role::CheckBox, "Extra").click(); + harness.run_steps(3); + harness.get_by_role_and_label(Role::RadioButton, "Two").click(); + harness.run_steps(3); + assert_eq!(harness.state().install_selection().cloned(), selection(&[false, true], &[Some(1)])); + harness.get_by_role_and_label(Role::RadioButton, "None").click(); + harness.get_by_role_and_label(Role::CheckBox, "Extra").click(); + harness.run_steps(3); + assert_eq!(harness.state().install_selection().cloned(), selection(&[false, false], &[None])); + + // A required module cannot be unticked. + let dir = tempfile::tempdir().unwrap(); + let (mut harness, _) = open(dir.path(), &super_package(dir.path(), "", true)); + harness.get_by_role_and_label(Role::CheckBox, "Base (required)").click(); + harness.run_steps(3); + assert_eq!(harness.state().install_selection().cloned(), selection(&[true, false], &[None])); +} + +#[test] +fn a_package_made_for_the_other_edition_warns() { + let dir = tempfile::tempdir().unwrap(); + let (harness, _) = open(dir.path(), &super_package(dir.path(), "legacy", true)); + harness.get_by_label("⚠"); + harness.get_by_label_contains("This package is made for GTA V Legacy; the chosen game is Enhanced"); + + let dir = tempfile::tempdir().unwrap(); + let (harness, _) = open(dir.path(), &super_package(dir.path(), "enhanced", true)); + assert!(!labels(&harness).iter().any(|l| l.contains("This package is made for")), "{:?}", labels(&harness)); + + // A plain package says it in the same way. + let dir = tempfile::tempdir().unwrap(); + let oiv = dir.path().join("plain.oiv"); + let assembly = r#"Plainlegacy"#; + zip_of(&oiv, &[("assembly.xml", assembly.as_bytes())]); + let (harness, _) = open(dir.path(), &oiv); + harness.get_by_label_contains("This package is made for GTA V Legacy; the chosen game is Enhanced"); + assert!(!labels(&harness).iter().any(|l| l == "What to install")); +} diff --git a/docs/cli.md b/docs/cli.md index 5ec000b..79861bd 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -146,6 +146,10 @@ This writes `out/prop_x.ydr.xml`, and one DDS file per texture the model names i # Install an OIV package paleto install my-mod.oiv +# Super package (.oivs): list its modules and groups, then choose +paleto install pack.oivs --list +paleto install pack.oivs --select "extra,-clouds,weather=rain" + # Install an add-on pack: a dlc.rpf, or a mod's folder holding it, into # mods/update/x64/dlcpacks// and the DLC list paleto install ~/Downloads/SuperCar @@ -228,7 +232,7 @@ See [troubleshooting.md](troubleshooting.md) for what these find. | `mv PATH NEW_NAME` | Rename a file or folder inside an archive | | `mkdir PATH` | Create a folder (and missing parents) inside an archive | | `new PATH` | Create a new, empty archive | -| `install PACKAGE [--name NAME] [--no-convert]` | Install an OIV package or an add-on pack | +| `install PACKAGE [--name NAME] [--no-convert] [--select CHOICES] [--list]` | Install an OIV package, an `.oivs` super package or an add-on pack. For `.oivs` only: `--select` chooses its parts (the syntax of CodeWalker's installer, see `--help`), `--list` shows them and installs nothing | | `convert [FILES…] [-o DIR] [--no-backup] [--undo [TIME]]` | Convert Legacy files to the Enhanced format, or undo a conversion | | `export [OUTPUT] [--only TEXT…] [--name] [--version] [--author]` | Make an OIV package of the mods folder's changes | | `crash [DUMP]` | Read the game's last crash | diff --git a/docs/mods.md b/docs/mods.md index afa39ee..aab41f2 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -36,6 +36,8 @@ The installer shows the package's name, version, author and description before a Paleto Modkit supports OIV format 2.x: adding and deleting files, nested archives, text edits, XPath edits of XML files and of binary metadata, and archive defragmentation. [oiv.md](oiv.md) lists what each action does. +An `.oivs` super package (made for CodeWalker's OIV Package Installer) is opened the same way. Its installer lists the parts to pick from; see [oiv.md](oiv.md#super-packages-oivs). + On the Enhanced edition, files made for Legacy in the package are noticed before installing, and can be converted while installing (see [below](#legacy-files-on-the-enhanced-edition)). ## Add-on packs diff --git a/docs/oiv.md b/docs/oiv.md index e04243a..2e083ab 100644 --- a/docs/oiv.md +++ b/docs/oiv.md @@ -26,6 +26,26 @@ Paleto Modkit follows OpenIV's package format 2.x (`` whose XPath matches nothing is not an error: the node was already gone. Other edits that find nothing to change are logged as warnings, and the installation goes on. +## Super packages (`.oivs`) + +An `.oivs` file is a super package, made for [CodeWalker's OIV Package Installer](https://www.gta5-mods.com/tools/oiv-package-installer): one package with parts the user picks from. It is a zip with `super.xml` (``, or no version), `icon.png`, `content/` and `media/`. It is recognised by its manifest, not by the extension. Everything above (where changes go, the transaction, the limits, the log) applies to it too. + +| Element | What it does | +| :--- | :--- | +| `` → `` | A part that is ticked or not. A `required` one is always installed; `default="true"` is ticked at first. | +| `` → `` → `