Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

102 changes: 92 additions & 10 deletions crates/openrage-app/src/oiv/install.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,20 @@
//! The same walk over the package script runs in two modes: a dry run that
//! reads everything and reports what would happen (and what cannot work), and
//! the real installation. Archive changes are batched per top-level archive
//! and written with the in-place editor; text and XML edits read the current
//! file (including earlier changes of the same package). All journal entries
//! and written with the in-place editor; text, XML and PSO edits read the
//! current file (including earlier changes of the same package). All journal entries
//! carry the package's group, so the package can be uninstalled as a whole.

use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::sync::Arc;

use anyhow::{Result, bail};
use anyhow::{Context, Result, bail};
use rage_crypto::GtaVKeys;
use rage_rpf::ArchiveWriter;
use rage_rpf::vfs::{self, Node};

use super::package::{Command, Package};
use super::package::{Command, Package, XmlCmd};
use super::{text, xml};
use crate::install::{self, Op};
use crate::journal::{Entry, Journal};
Expand Down Expand Up @@ -55,8 +55,11 @@ fn norm(p: &str) -> String {
fn escaping_path(cmd: &Command) -> Option<&str> {
let raw = match cmd {
Command::Add { target, .. } | Command::Delete { target } => target,
Command::Archive { path, .. } | Command::Text { path, .. } | Command::Xml { path, .. } => path,
Command::Pso { .. } | Command::Defragment { .. } => return None,
Command::Archive { path, .. }
| Command::Text { path, .. }
| Command::Xml { path, .. }
| Command::Pso { path, .. } => path,
Command::Defragment { .. } => return None,
};
let n = norm(raw);
(!n.is_empty() && vfs::safe_relative_path(&n).is_none()).then_some(raw.as_str())
Expand All @@ -70,6 +73,16 @@ fn join(a: &str, b: &str) -> String {
}
}

#[cfg(test)]
mod tests {
#[test]
fn xpath_literals() {
assert_eq!(super::quoted("/A/Item[Name = 'adder']/B[@x=\"1\"]"), ["adder", "1"]);
assert!(super::quoted("/A/B").is_empty());
assert_eq!(super::changed_lines("a\n b\nc", "a\nb\nd\ne"), (2, 1));
}
}

#[derive(Clone, Copy)]
enum Encoding {
Utf8,
Expand Down Expand Up @@ -348,10 +361,19 @@ impl Run<'_> {
self.step("Edit", &vpath, format!("{} XML command(s)", commands.len()));
self.write_edited(scope, path, encode(&doc, enc))?;
}
Command::Pso { path } => {
self.report
.blockers
.push(format!("{}: PSO/META edits are not supported yet", Self::vpath(scope, path)));
Command::Pso { path, commands } => {
let vpath = Self::vpath(scope, path);
let Some(bytes) = self.read(&vpath) else {
self.report.blockers.push(format!("PSO file {vpath} does not exist"));
continue;
};
match edit_pso(&bytes, commands) {
Ok((data, detail)) => {
self.step("Edit", &vpath, detail);
self.write_edited(scope, path, data)?;
}
Err(e) => self.report.blockers.push(format!("{vpath}: {e:#}")),
}
}
Command::Defragment { archive } => {
self.report.warnings.push(format!("defragmentation of {archive} skipped (only saves disk space)"));
Expand All @@ -362,6 +384,66 @@ impl Run<'_> {
}
}

/// Applies XML edits to a PSO file: converts it to XML, edits that, and
/// writes it back with the file's own schema. Returns the new file and a
/// summary of the change for the preview.
fn edit_pso(bytes: &[u8], commands: &[XmlCmd]) -> Result<(Vec<u8>, String)> {
use rage_formats::pso;
if !pso::is_pso(bytes) {
bail!("not a PSO file (only PSO metadata can be edited with <pso>; resource metadata cannot yet)");
}
// Hashes print as names only when the name is known: names the XPaths
// compare with (`Item[Name = 'adder']`) are made known first, so they
// select what the author meant.
rage_formats::names::register(commands.iter().flat_map(|c| {
let xpath = match c {
XmlCmd::Add { xpath, .. } | XmlCmd::Replace { xpath, .. } | XmlCmd::Remove { xpath } => xpath,
};
quoted(xpath)
}));
let file = pso::parse(bytes)?;
let (before, problems) = file.to_xml_with_limit(1 << 30);
if let Some(p) = problems.first() {
bail!("parts of the file cannot be read ({p}), so it cannot be written back safely");
}
let mut doc = before.clone();
for c in commands {
doc = xml::apply(&doc, c)?;
}
let data = file.from_xml(&doc).context("the edited XML does not fit the file's structure")?;
let (added, removed) = changed_lines(&before, &doc);
let detail = format!("{} XML command(s) on the PSO data: {added} line(s) added, {removed} removed", commands.len());
Ok((data, detail))
}

/// The quoted literals of an XPath (`'…'` or `"…"`).
fn quoted(xpath: &str) -> Vec<String> {
let mut out = Vec::new();
let mut rest = xpath;
while let Some(start) = rest.find(['\'', '"']) {
let q = &rest[start..start + 1];
let Some(len) = rest[start + 1..].find(q) else { break };
out.push(rest[start + 1..start + 1 + len].to_owned());
rest = &rest[start + 2 + len..];
}
out
}

/// Lines only in `after` and lines only in `before` (counted with repeats).
fn changed_lines(before: &str, after: &str) -> (usize, usize) {
let mut count: HashMap<&str, isize> = HashMap::new();
// Trimmed, so that re-indented lines do not count as changed.
for l in before.lines() {
*count.entry(l.trim()).or_default() -= 1;
}
for l in after.lines() {
*count.entry(l.trim()).or_default() += 1;
}
let added = count.values().filter(|n| **n > 0).map(|n| *n as usize).sum();
let removed = count.values().filter(|n| **n < 0).map(|n| n.unsigned_abs()).sum();
(added, removed)
}

fn run(game_dir: &Path, keys: Option<Arc<GtaVKeys>>, pkg: &Package, dry: bool) -> Result<Report> {
let mut r = Run {
game_dir,
Expand Down
78 changes: 50 additions & 28 deletions crates/openrage-app/src/oiv/package.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,11 @@ pub enum Command {
path: String,
commands: Vec<XmlCmd>,
},
/// PSO/META edits (`<pso>`); need a PSO converter, not supported yet.
/// Edits of a binary PSO metadata file (`<pso>`): converted to XML, edited
/// with the same commands as `<xml>`, and written back as PSO.
Pso {
path: String,
commands: Vec<XmlCmd>,
},
/// Archive rebuild to reclaim space; optional, skipped.
Defragment {
Expand Down Expand Up @@ -275,33 +277,14 @@ fn parse_commands(source: &str, node: roxmltree::Node<'_, '_>) -> Result<Vec<Com
commands,
}
}
"xml" => {
let mut commands = Vec::new();
for x in c.children().filter(|x| x.is_element()) {
let xpath = attr(x, "xpath").context("XML command without xpath")?;
commands.push(match x.tag_name().name().to_ascii_lowercase().as_str() {
"add" => XmlCmd::Add {
append: match attr(x, "append")
.unwrap_or_else(|| "Last".into())
.to_ascii_lowercase()
.as_str()
{
"first" => Append::First,
"before" => Append::Before,
"after" => Append::After,
_ => Append::Last,
},
content: inner_xml(source, x),
xpath,
},
"replace" => XmlCmd::Replace { content: inner_xml(source, x), xpath },
"remove" => XmlCmd::Remove { xpath },
other => bail!("unknown XML command <{other}>"),
});
}
Command::Xml { path: attr(c, "path").context("<xml> without path")?, commands }
}
"pso" => Command::Pso { path: attr(c, "path").unwrap_or_default() },
"xml" => Command::Xml {
path: attr(c, "path").context("<xml> without path")?,
commands: xml_commands(source, c)?,
},
"pso" => Command::Pso {
path: attr(c, "path").context("<pso> without path")?,
commands: xml_commands(source, c)?,
},
"defragmentation" => Command::Defragment { archive: attr(c, "archive").unwrap_or_default() },
other => bail!("unknown package command <{other}>"),
};
Expand All @@ -310,6 +293,30 @@ fn parse_commands(source: &str, node: roxmltree::Node<'_, '_>) -> Result<Vec<Com
Ok(out)
}

/// The XML edits inside an `<xml>` or `<pso>` command.
fn xml_commands(source: &str, c: roxmltree::Node<'_, '_>) -> Result<Vec<XmlCmd>> {
let mut commands = Vec::new();
for x in c.children().filter(|x| x.is_element()) {
let xpath = attr(x, "xpath").context("XML command without xpath")?;
commands.push(match x.tag_name().name().to_ascii_lowercase().as_str() {
"add" => XmlCmd::Add {
append: match attr(x, "append").unwrap_or_else(|| "Last".into()).to_ascii_lowercase().as_str() {
"first" => Append::First,
"before" => Append::Before,
"after" => Append::After,
_ => Append::Last,
},
content: inner_xml(source, x),
xpath,
},
"replace" => XmlCmd::Replace { content: inner_xml(source, x), xpath },
"remove" => XmlCmd::Remove { xpath },
other => bail!("unknown XML command <{other}>"),
});
}
Ok(commands)
}

fn parse_assembly(text: &str) -> Result<Package> {
let doc = roxmltree::Document::parse(text).context("assembly.xml is not valid XML")?;
let root = doc.root_element();
Expand Down Expand Up @@ -414,6 +421,21 @@ mod tests {
assert_eq!(text[1], TextCmd::Delete { line: "#*".into(), condition: Condition::Mask });
}

#[test]
fn parses_pso_edits() {
let pso = ASSEMBLY.replace(
"<defragmentation archive=\"update\\update.rpf\"/>",
r#"<pso path="x64\data\carcols.ymt"><remove xpath="/CVehicleModColors/kits/Item[1]"/></pso>"#,
);
let p = parse_assembly(&pso).unwrap();
let Command::Pso { path, commands } = &p.commands[2] else { panic!("{:?}", p.commands[2]) };
assert_eq!(path, "x64\\data\\carcols.ymt");
assert_eq!(commands, &[XmlCmd::Remove { xpath: "/CVehicleModColors/kits/Item[1]".into() }]);
assert!(
parse_assembly(&ASSEMBLY.replace("<defragmentation archive=\"update\\update.rpf\"/>", "<pso/>")).is_err()
);
}

#[test]
fn rejects_other_games() {
let other = ASSEMBLY.replace("target=\"Five\"", "target=\"IV\"");
Expand Down
45 changes: 44 additions & 1 deletion crates/openrage-app/tests/oiv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,35 @@ fn fake_game(name: &str) -> PathBuf {
w.add_file("common/data/dlclist.xml", DLCLIST.as_bytes().to_vec()).unwrap();
w.add_file("common/data/settings.txt", b"a=1\nb=2\n".to_vec()).unwrap();
w.add_file("common/data/old.dat", b"old".to_vec()).unwrap();
w.add_file("common/data/peds.ymt", tiny_pso()).unwrap();
std::fs::write(root.join("update/update.rpf"), w.build().unwrap()).unwrap();
std::fs::write(root.join("GTA5.exe"), b"").unwrap();
root
}

/// A PSO file like the game's: a list of two items (a hash and a float each),
/// the items in block 1 and the root structure in block 2.
fn tiny_pso() -> Vec<u8> {
use rage_core::hash::{jenkins_bytes, joaat};
let h = |name: &str| jenkins_bytes(name.as_bytes());
let (root, item) = (h("CPedModelInfo__InitDataList"), h("CPedModelInfo__InitData"));
let be = |values: &[u32]| values.iter().flat_map(|v| v.to_be_bytes()).collect::<Vec<u8>>();
let mut psin = b"PSIN\0\0\0\0pppppppp".to_vec();
psin.extend(be(&[joaat("adder"), 1.5f32.to_bits(), joaat("banshee"), 2f32.to_bits()]));
psin.extend(be(&[1, 0, 0x0002_0002, 0])); // pointer to block 1, count and capacity 2
psin[4..8].copy_from_slice(&48u32.to_be_bytes());
let mut pmap = b"PMAP".to_vec();
pmap.extend(be(&[48, 2, 0x0002_7070, item, 16, 0, 16, root, 32, 0, 16]));
// Structure infos: entry count, length, 0, then (name, type << 24 | subtype << 16 | offset, key).
let root_info = be(&[2, 16, 0, 0x100, 0x0c00_0000, item, h("InitDatas"), 0x0d00_0000, 0]);
let item_info = be(&[2, 8, 0, h("Name"), 0x0b07_0000, 0, h("Radius"), 0x0700_0004, 0]);
let mut psch = b"PSCH".to_vec();
psch.extend(be(&[28 + 36 + 36, 2, root, 28, item, 28 + 36]));
psch.extend(root_info);
psch.extend(item_info);
[psin, pmap, psch].concat()
}

fn package(assembly: &str, files: &[(&str, &[u8])]) -> Package {
let mut buf = std::io::Cursor::new(Vec::new());
{
Expand Down Expand Up @@ -65,6 +89,17 @@ const ASSEMBLY: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<replace line="b=" condition="StartWith">b=42</replace>
<add>c=3</add>
</text>
<pso path="common\data\peds.ymt">
<replace xpath="/CPedModelInfo__InitDataList/InitDatas/Item[Name = 'banshee']/Radius">
<Radius value="4.5" />
</replace>
<add xpath="/CPedModelInfo__InitDataList/InitDatas" append="Last">
<Item>
<Name>zentorno</Name>
<Radius value="3" />
</Item>
</add>
</pso>
<xml path="common\data\dlclist.xml">
<add xpath="/SMandatoryPacksData/Paths" append="Last">
<Item>dlcpacks:/testmod/</Item>
Expand Down Expand Up @@ -92,6 +127,8 @@ fn installs_and_uninstalls() {
assert!(actions.contains(&"Add plugin.asi".to_owned()), "{actions:?}");
assert!(actions.contains(&"Delete update/update.rpf/common/data/old.dat".to_owned()));
assert!(actions.contains(&"Create update/x64/dlcpacks/testmod/dlc.rpf".to_owned()));
let pso_step = plan.steps.iter().find(|s| s.target.ends_with("peds.ymt")).expect("PSO edit planned");
assert_eq!(pso_step.detail, "2 XML command(s) on the PSO data: 5 line(s) added, 1 removed");
// The dry run changed nothing.
assert!(!game.join("mods").exists() && !game.join("plugin.asi").exists());

Expand All @@ -107,6 +144,11 @@ fn installs_and_uninstalls() {
"{dlclist}"
);
assert_eq!(read(&game, "update/x64/dlcpacks/testmod/dlc.rpf/setup2.xml").unwrap(), b"<setup/>");
let peds = read(&game, "update/update.rpf/common/data/peds.ymt").unwrap();
let (xml, errors) = rage_formats::pso::to_xml(&peds).unwrap();
assert!(errors.is_empty(), "{errors:?}");
assert!(xml.contains("<Radius value=\"4.5\" />") && xml.contains("<Radius value=\"1.5\" />"), "{xml}");
assert_eq!(xml.matches("<Item>").count(), 3, "{xml}");
assert_eq!(std::fs::read(game.join("update/update.rpf")).unwrap(), original, "game archive untouched");

let undone = uninstall(&game, "Test Mod 1.0").unwrap();
Expand All @@ -115,6 +157,7 @@ fn installs_and_uninstalls() {
assert!(!game.join("mods/update/x64/dlcpacks/testmod/dlc.rpf").exists());
assert!(!game.join("mods/update/update.rpf").exists());
assert_eq!(read(&game, "update/update.rpf/common/data/old.dat").unwrap(), b"old");
assert_eq!(read(&game, "update/update.rpf/common/data/peds.ymt").unwrap(), tiny_pso());
}

#[test]
Expand All @@ -124,7 +167,7 @@ fn reports_blockers() {
r#"createIfNotExist="False" type="RPF7">
<add source="water.xml">"#,
r#"createIfNotExist="False" type="RPF7">
<pso path="x.ymt"/>
<pso path="x.ymt"><remove xpath="/A"/></pso>
<add source="water.xml">"#,
);
let pkg = package(&bad, &[("plugin.asi", b"ASI")]);
Expand Down
6 changes: 6 additions & 0 deletions crates/openrage-cli/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ pub(crate) enum Command {
/// With --textures: also rebuild every dictionary and check that it reads back identically.
/// With --models: write every GTA V Enhanced drawable (.ydr) anew with its own meshes and
/// check that it reads back identically.
/// With --meta: convert every PSO file (.ymt, .ymf, .pso, …) to XML and back, and check
/// that it comes out byte for byte the same or at least reads back to the same XML.
/// GTA IV without --textures: rebuild the table of every .rpf package in memory and
/// check that it matches the stored one byte for byte (nothing is written).
#[arg(long)]
Expand Down Expand Up @@ -208,6 +210,10 @@ pub(crate) enum Command {
/// Instead of only reading files, convert all metadata (.ymap, .ytyp, .ymt, .ymf) to XML.
#[arg(long, conflicts_with_all = ["textures", "models", "text"])]
meta: bool,
/// With --meta: convert every PSO file to XML and back, and check that it comes out the
/// same bytes or at least reads back to the same XML.
#[arg(long, requires = "meta")]
rebuild: bool,
/// Instead of only reading files, decode every sound of every audio container.
#[arg(long, conflicts_with_all = ["textures", "models", "text", "meta"])]
audio: bool,
Expand Down
Loading