From a9985b37757c8f8439e1af72292b4f527ddefe7b Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Wed, 7 Oct 2026 03:50:08 +0000 Subject: [PATCH] fix: validate every corpus output and fix the two schema failures compare.py --all now also converts the INDD and INDT files that have no same-version IDML (any version, either byte order), validates them and counts converter warnings by kind. validate.sh runs Jing once per schema instead of once per file, which makes validating the whole corpus take about 3 minutes. Two schema failures showed up in files without an IDML: - Gradient swatch midpoints are stored as positions from the start of the gradient. IDML wants them relative to the gap between two stops, as for opacity gradient stops. Values outside 13-87 are left out with a warning. - The style kind is a u16, not a u32. One InDesign 7.5 template has a non-zero u16 after it, which made 151 character styles paragraph styles. --- CLAUDE.md | 9 ++- docs/format/objects.md | 58 +++++++++++++++++--- src/idml/mod.rs | 7 +-- src/model/color.rs | 47 +++++++++++++++- src/model/mod.rs | 15 ++++- tests/fixtures.rs | 12 ++++ tools/compare.py | 122 +++++++++++++++++++++++++++++++++++------ tools/validate.sh | 25 +++++---- 8 files changed, 250 insertions(+), 45 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 4668e0e..5b3609c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -49,8 +49,15 @@ the INDD version were probably re-saved after export; trust them less. - `python3 -I tools/compare.py [--detail TAG --show N]`: convert every corpus pair and compare with the reference IDML. This is the main measure of progress; run it after every change. +- `compare.py --all` also converts every other INDD/INDT under `corpus/` + (any version, either byte order) and reports their failures; every run + counts converter warnings by kind (`--warnings N` lists N kinds). + `--exclude PREFIX` leaves out files whose path under `corpus/` starts + with PREFIX; committed numbers must not include the privately held file. - Schema validation: `tools/validate.sh out.idml `, or - `compare.py --schemas --jing `. The IDML RelaxNG schemas + `compare.py --schemas --jing ` (validations run in parallel, + `--jobs N`). Run `compare.py --all --schemas … --jing …` after changes + to the IDML writer: it takes about 3 minutes. The IDML RelaxNG schemas (generated by InDesign, published in the metanorma/idml repo) and Jing (Maven Central) are kept outside the repo, for example in the session scratchpad; do not commit them. diff --git a/docs/format/objects.md b/docs/format/objects.md index 6a36cdc..2ba7037 100644 --- a/docs/format/objects.md +++ b/docs/format/objects.md @@ -561,13 +561,29 @@ last paragraph return of a story is not written to IDML. ## Styles (0x205) Paragraph and character styles share the class. Chunk 0x230: u32 next -style (0 = itself), u32 based-on style, fields not yet identified, u32 1 -for paragraph styles or 0 for character styles, u8 1 if the name is a -built-in key (`$ID/` in IDML), the name as an in-object string, then a GUID -string in newer files. The name's offset varies (23–26 bytes), so the -converter locates it as a flag byte followed by a valid in-object string. +style (0 = itself), u32 based-on style, fields not yet identified, u16 1 +for paragraph styles or 0 for character styles, u16 not identified, u8 1 +if the name is a built-in key (`$ID/` in IDML), the name as an in-object +string, then a GUID string in newer files. The name's offset varies (23–26 +bytes), so the converter locates it as a flag byte followed by a valid +in-object string. All 486 style names and 291 `NextStyle` values in the pairs match. +**Kind field.** The kind and the unidentified u16 after it can be read +as one u32 in most files, because the second u16 is 0. The InDesign 7.5 +template in `tests/fixtures/scml-template/` (no IDML) has 1 there in 600 +of its styles: 151 have `00 00 01 00` before the flag and 449 have +`01 00 01 00`. The 151 are all listed in the tree of the root character +style group (chunk 0x28C2 = 0xCA0D, below) and the 449 in the tree of the +root paragraph style group, so the kind is the first u16 alone. Read as a +u32, the 151 character styles were taken for paragraph styles, which gave +`ParagraphStyle/…` references and a `NextStyle` that the schema does not +allow on a character style. In every other distinct little-endian corpus +file the u32 is 0 or 1 (2,125 styles), and the kind agrees with the root +group in all of them. In the two big-endian files the u16 kind is also +the first two bytes (`00 01` for their three paragraph styles, `00 00` +for their two character styles). + IDML writes a `BasedOn` of the root `[No paragraph style]` or `[No character style]` as a string (`$ID/[No paragraph style]`), and any other base as an object reference. @@ -841,10 +857,34 @@ pairs. The `None` swatch is class 0x6E0B (name in chunk 0x1F30). **Gradients (0x5503).** Chunk 0x5503: u16 stop count *n*, *n* u32 stop -colour UIDs, *n* f64 locations (0–1), *n* f64 midpoints (the midpoint -between stops i and i+1 is stored with stop i), u32 type (1 linear). -Chunk 0x5505: flag byte, name, u32 flags as for colours. All 99 gradients -and 198 stops in the pairs match. +colour UIDs, *n* f64 locations (0–1), *n* f64 midpoints, u32 type (1 +linear). Chunk 0x5505: flag byte, name, u32 flags as for colours. All 99 +gradients and 198 stops in the pairs match. + +The midpoint stored with stop *i* is the position of the midpoint between +stops *i* and *i*+1, measured from the start of the gradient (0–1), as +for opacity gradient stops (`transparency.md`). IDML writes it on stop +*i*+1 as a percentage of the distance between the two stops: +`Midpoint` = (midpoint *i* − location *i*) / (location *i*+1 − location +*i*) × 100. Evidence: + +- Most pairs have two stops at locations 0 and 1, where both readings + give the same value. Two gradients in one pair have their first stop at + 0.0037; stored midpoints 0.50184 and 0.60147 give IDML `Midpoint` 50 + and 60 with this formula (2 of 2), not 50.18 and 60.15. +- Gradients with more than two stops, or with stops not at 0 and 1, + occur in 26 files, 392 gradients. Only the two above are in a + reference IDML. In all 426 stop gaps of non-zero width, the stored midpoint lies + between the two stops' locations, as a position from the start of the + gradient must (for example stops at 0, 0.5 and 1 with stored midpoints + 0.25 and 0.75). Written to IDML unconverted, 13 of them were outside + the 13–87 that the IDML schema allows for `Midpoint`; converted, all + 426 are inside it. +- 8 gaps, all in one file, have width 0 (two stops at the same + location), so the formula gives no value. + +When the computed value is outside 13–87 or there is none, the converter +leaves the `Midpoint` out and warns. ## Inks (0x1F07) diff --git a/src/idml/mod.rs b/src/idml/mod.rs index 0d3283a..d409e0c 100644 --- a/src/idml/mod.rs +++ b/src/idml/mod.rs @@ -643,7 +643,7 @@ pub fn num(v: f64) -> String { } /// Round away binary noise from scaled values (0.8 * 100 = 80.00000000000001). -fn round(v: f64) -> f64 { +pub(crate) fn round(v: f64) -> f64 { (v * 1e9).round() / 1e9 } @@ -1425,9 +1425,8 @@ impl Writer<'_> { .attr("Self", format!("{}GradientStop{i}", uref(Some(g.uid)))) .attr("StopColor", color) .attr("Location", num(round(stop.location * 100.0))); - // The midpoint between stops i-1 and i is stored with stop i-1. - if i > 0 { - x.attr("Midpoint", num(round(g.stops[i - 1].midpoint * 100.0))); + if let Some(m) = g.idml_midpoint(i) { + x.attr("Midpoint", num(m)); } x.end(); } diff --git a/src/model/color.rs b/src/model/color.rs index ba1cfaf..b796d67 100644 --- a/src/model/color.rs +++ b/src/model/color.rs @@ -34,7 +34,8 @@ pub struct GradientStop { pub color: u32, /// 0–1. pub location: f64, - /// 0–1, between this stop and the next one. + /// Position of the midpoint between this stop and the next one, 0–1, + /// measured from the start of the gradient. pub midpoint: f64, } @@ -63,6 +64,18 @@ impl Gradient { } } + /// IDML `Midpoint` of stop `i` (from 1): the midpoint between stops + /// `i`−1 and `i`, in percent of the distance between them. `None` for + /// the first stop, and when the value is outside the 13–87 that IDML + /// allows. + pub fn idml_midpoint(&self, i: usize) -> Option { + let (prev, stop) = (self.stops.get(i.checked_sub(1)?)?, self.stops.get(i)?); + let m = (prev.midpoint - prev.location) / (stop.location - prev.location) * 100.0; + // Rounded as IDML writes it, so that 12.9999999 counts as 13. + let m = crate::idml::round(m); + (13.0..=87.0).contains(&m).then_some(m) + } + pub fn idml_name(&self) -> String { if self.builtin_name { format!("$ID/{}", self.name) @@ -327,6 +340,38 @@ mod tests { assert_eq!(t.idml_name(&color("Black", 2)), "[Black] 40%"); assert_eq!(t.reference(&color("Gold", 0)), "Tint/Gold 40%25"); } + + #[test] + fn gradient_midpoints_are_relative_to_the_gap() { + let stop = |location, midpoint| GradientStop { + color: 0, + location, + midpoint, + }; + let g = Gradient { + uid: 0x100, + name: String::new(), + builtin_name: false, + kind: 1, + // Stops at 0, 0.5, 0.5 and 1; the stored midpoints are positions + // from the start of the gradient. + stops: vec![ + stop(0.0, 0.25), + stop(0.5, 0.5), + stop(0.5, 0.95), + stop(1.0, 1.0), + ], + removable: true, + visible: true, + editable: true, + }; + assert_eq!(g.idml_midpoint(0), None); + assert_eq!(g.idml_midpoint(1), Some(50.0)); + // No gap between two stops at the same location. + assert_eq!(g.idml_midpoint(2), None); + // 90 % is outside what IDML allows. + assert_eq!(g.idml_midpoint(3), None); + } } /// An ink (class 0x1F07). Chunk 0x1F0D: flag byte and name, then fields diff --git a/src/model/mod.rs b/src/model/mod.rs index 8201030..c162076 100644 --- a/src/model/mod.rs +++ b/src/model/mod.rs @@ -900,6 +900,14 @@ impl<'a> Reader<'a> { } color::class::GRADIENT => { if let Some(g) = Gradient::read(uid, &*self.object(uid)?)? { + for i in 1..g.stops.len() { + if g.idml_midpoint(i).is_none() { + self.warn(format!( + "gradient {uid}: midpoint before stop {i} is not \ + within 13–87 %; left out" + )); + } + } swatches.insert(uid, g.reference()); gradients.push(g); } @@ -1786,12 +1794,13 @@ impl<'a> Reader<'a> { let based_on = c.u32()?; // The header before the name is 4 bytes shorter in files from // InDesign 13 and earlier, so locate the name by its structure: a - // flag byte (1 = built-in name), then an in-object string. The u32 - // before the flag is 1 for paragraph styles and 0 for character styles. + // flag byte (1 = built-in name), then an in-object string. Four + // bytes before the flag, a u16 is 1 for paragraph styles and 0 for + // character styles; the u16 after it is not identified. let Some((at, builtin, name)) = find_flagged_string(&data, 12, |_| true) else { return Err(Error::Corrupt(format!("style {uid}: no name"))); }; - let paragraph = Cursor::new(&data[at - 4..]).u32()? != 0; + let paragraph = Cursor::new(&data[at - 4..]).u16()? != 0; let attrs = match self.chunk(uid, chunk::STYLE_ATTRS)? { Some(d) if d.len() >= 2 => { let mut c = Cursor::new(&d); diff --git a/tests/fixtures.rs b/tests/fixtures.rs index 8406bdb..43455d0 100644 --- a/tests/fixtures.rs +++ b/tests/fixtures.rs @@ -151,3 +151,15 @@ fn little_endian_fixtures_convert() { assert!(text.contains("designmap.xml"), "{rel}"); } } + +/// The InDesign 7.5 template has character styles whose kind field is +/// followed by a non-zero u16 (`docs/format/objects.md`, Styles). +#[test] +fn style_kind_is_a_u16() { + let bytes = std::fs::read(fixture("scml-template/scml.indt")).unwrap(); + let mut out = Vec::new(); + indd::convert(&bytes, "test.indd", &mut out).unwrap(); + let text = String::from_utf8_lossy(&out); + assert!(text.contains(r#""#)); + assert!(!text.contains(r#" ` rather than as the full text. """ import argparse import hashlib +import os import re import subprocess import sys @@ -26,21 +34,23 @@ import tempfile import xml.etree.ElementTree as ET import zipfile from collections import Counter, defaultdict +from concurrent.futures import ThreadPoolExecutor from pathlib import Path ROOT = Path(__file__).resolve().parent.parent BIN = ROOT / "target" / "release" / "indd" -def pairs(limit, substr): +def pairs(limit, substr, exclude, seen): + """Corpus files with a same-version reference IDML, without duplicates. + Adds the digest of each file to `seen`.""" rows = (ROOT / "corpus" / "inventory.tsv").read_text().splitlines()[1:] - seen = set() out = [] for row in rows: path, _size, _valid, order, ver, _creator, dom = row.split("\t") if order != "LE" or not dom or ver.split(".")[0] != dom.split(".")[0]: continue - if substr and substr not in path: + if substr and substr not in path or any(path.startswith(e) for e in exclude): continue indd = ROOT / "corpus" / path digest = hashlib.md5(indd.read_bytes()).hexdigest() @@ -51,6 +61,40 @@ def pairs(limit, substr): return out[:limit] if limit else out +def unpaired(substr, exclude, seen): + """Every other INDD and INDT file under corpus/, without duplicates.""" + out = [] + for indd in sorted((ROOT / "corpus").rglob("*")): + if indd.suffix.lower() not in (".indd", ".indt") or not indd.is_file(): + continue + path = str(indd.relative_to(ROOT / "corpus")) + if substr and substr not in path or any(path.startswith(e) for e in exclude): + continue + digest = hashlib.md5(indd.read_bytes()).hexdigest() + if digest in seen: + continue + seen.add(digest) + out.append(indd) + return out + + +def warning_kind(msg): + """A warning with its numbers and quoted names replaced, for counting.""" + msg = re.sub(r'"[^"]*"', '"…"', msg) + msg = re.sub(r"\b0x[0-9a-fA-F]+\b", "#", msg) + return re.sub(r"\b\d+(\.\d+)?\b", "#", msg) + + +def validate(out, args): + """Schema errors of an output (empty if valid); runs tools/validate.sh.""" + v = subprocess.run( + [ROOT / "tools" / "validate.sh", out, args.schemas, args.jing], + capture_output=True, text=True) + if v.returncode == 0: + return [] + return v.stdout.strip().splitlines() or [v.stderr.strip()] + + def text_ranges(story): """Map text offset -> attributes of the paragraph and character range starting there, with keys prefixed PSR. and CSR.""" @@ -170,7 +214,16 @@ def main(): ap.add_argument("--schemas", help="IDML RelaxNG schema directory (validate output)") ap.add_argument("--jing", help="directory with jing.jar, isorelax.jar, saxon.jar") ap.add_argument("--bin", default=str(BIN), help="converter binary") + ap.add_argument("--all", action="store_true", + help="also convert and validate files without a reference IDML") + ap.add_argument("--exclude", action="append", default=[], + help="leave out files whose path under corpus/ starts with this (repeatable)") + ap.add_argument("--warnings", type=int, default=15, + help="number of warning kinds to list") + ap.add_argument("--jobs", type=int, default=os.cpu_count() or 1, + help="schema validations run in parallel") args = ap.parse_args() + check = bool(args.schemas and args.jing) found = Counter() total = Counter() @@ -178,20 +231,41 @@ def main(): examples = defaultdict(list) story_ok = Counter() failures = [] - invalid = [] + warnings = Counter() + warned_files = Counter() + seen = set() + todo = pairs(args.limit, args.file, args.exclude, seen) + others = unpaired(args.file, args.exclude, seen) if args.all else [] + other_failures = [] + pool = ThreadPoolExecutor(max(1, args.jobs)) + checks = [] # (name, paired, future of schema errors) + + def convert(indd, out): + r = subprocess.run([args.bin, "convert", indd, out], capture_output=True, text=True) + kinds = set() + for line in r.stderr.splitlines(): + if line.startswith("warning: "): + kind = warning_kind(line[len("warning: "):]) + warnings[kind] += 1 + kinds.add(kind) + for kind in kinds: + warned_files[kind] += 1 + if r.returncode == 0 and check: + checks.append((indd.name, pool.submit(validate, out, args))) + return r + with tempfile.TemporaryDirectory() as tmp: - out = Path(tmp) / "out.idml" - for indd, idml in pairs(args.limit, args.file): - r = subprocess.run([args.bin, "convert", indd, out], capture_output=True, text=True) + for n, indd in enumerate(others): + r = convert(indd, Path(tmp) / f"other{n}.idml") + if r.returncode != 0: + other_failures.append((indd.name, r.stderr.strip())) + n_others = len(checks) + for n, (indd, idml) in enumerate(todo): + out = Path(tmp) / f"pair{n}.idml" + r = convert(indd, out) if r.returncode != 0: failures.append((indd.name, r.stderr.strip())) continue - if args.schemas and args.jing: - v = subprocess.run( - [ROOT / "tools" / "validate.sh", out, args.schemas, args.jing], - capture_output=True, text=True) - if v.returncode != 0: - invalid.append((indd.name, v.stdout.strip().splitlines()[:3])) ref_el, ref_st, ref_rg = load(idml) our_el, our_st, our_rg = load(out) for (tag, s), el in ref_el.items(): @@ -240,14 +314,30 @@ def main(): story_ok["wrong"] += 1 if len(examples[("Story", "text")]) < max(args.show, 3): examples[("Story", "text")].append((indd.name, sid, text[:80], our_st[sid][:80])) + invalid = [(name, f.result()) for name, f in checks] + pool.shutdown() + other_invalid = [(name, errs) for name, errs in invalid[:n_others] if errs] + invalid = [(name, errs) for name, errs in invalid[n_others:] if errs] - print(f"conversion failures: {len(failures)}") + print(f"conversion failures: {len(failures)} of {len(todo)} paired files") for name, err in failures[:10]: print(f" {name}: {err}") - if args.schemas: + if check: print(f"schema validation failures: {len(invalid)}") for name, errs in invalid[:10]: - print(f" {name}: {errs}") + print(f" {name}: {len(errs)} errors, {errs[:3]}") + if args.all: + print(f"files without a reference: {len(others)}, " + f"conversion failures: {len(other_failures)}") + for name, err in other_failures[:10]: + print(f" {name}: {err}") + if check: + print(f"files without a reference: schema validation failures: {len(other_invalid)}") + for name, errs in other_invalid[:10]: + print(f" {name}: {len(errs)} errors, {errs[:3]}") + print(f"warnings: {sum(warnings.values())} (count, files, kind)") + for kind, count in warnings.most_common(args.warnings): + print(f" {count:6} {warned_files[kind]:4} {kind[:150]}") st = sum(story_ok.values()) print(f"story text: {story_ok['ok']}/{st} exact, {story_ok['wrong']} differ, {story_ok['missing']} missing") print("\nelements (produced / in reference):") diff --git a/tools/validate.sh b/tools/validate.sh index 95784b0..9321b65 100755 --- a/tools/validate.sh +++ b/tools/validate.sh @@ -7,7 +7,7 @@ # jing-dir: directory with jing.jar, isorelax.jar, saxon.jar # The schemas and Jing are not part of this repository. set -eu -idml=$1; schemas=$2; jing=$3 +idml=$1; schemas=$(cd "$2" && pwd); jing=$(cd "$3" && pwd) tmp=$(mktemp -d) trap 'rm -rf "$tmp"' EXIT unzip -qq "$idml" -d "$tmp" @@ -18,19 +18,22 @@ dom=$(grep -o 'DOMVersion="[^"]*"' "$schemas/designmap.rnc" | head -1) find "$tmp" -name '*.xml' -exec sed -i "s/DOMVersion=\"[^\"]*\"/$dom/" {} + cp="$jing/jing.jar:$jing/isorelax.jar:$jing/saxon.jar" status=0 -check() { # file schema - [ -f "$tmp/$1" ] || return 0 - if ! out=$(java -cp "$cp" com.thaiopensource.relaxng.util.Driver -c "$schemas/$2" "$tmp/$1" 2>&1); then +check() { # schema file... (one Jing run per schema) + schema=$1; shift + [ $# -gt 0 ] || return 0 + if ! out=$(java -cp "$cp" com.thaiopensource.relaxng.util.Driver -c "$schemas/$schema" "$@" 2>&1); then status=1 fi [ -n "$out" ] && printf '%s\n' "$out" | sed "s|$tmp/||" return 0 } -check designmap.xml designmap.rnc -for f in "$tmp"/Spreads/*.xml; do [ -e "$f" ] && check "Spreads/$(basename "$f")" Spreads/Spread.rnc; done -for f in "$tmp"/MasterSpreads/*.xml; do [ -e "$f" ] && check "MasterSpreads/$(basename "$f")" MasterSpreads/MasterSpread.rnc; done -for f in "$tmp"/Stories/*.xml; do [ -e "$f" ] && check "Stories/$(basename "$f")" Stories/Story.rnc; done -for p in Fonts Graphic Preferences Styles; do check "Resources/$p.xml" "Resources/$p.rnc"; done -check XML/BackingStory.xml XML/BackingStory.rnc -check XML/Tags.xml XML/Tags.rnc +existing() { for f in "$@"; do [ -f "$f" ] && printf '%s\n' "$f"; done; } +cd "$tmp" +check designmap.rnc $(existing designmap.xml) +check Spreads/Spread.rnc $(existing Spreads/*.xml) +check MasterSpreads/MasterSpread.rnc $(existing MasterSpreads/*.xml) +check Stories/Story.rnc $(existing Stories/*.xml) +for p in Fonts Graphic Preferences Styles; do check "Resources/$p.rnc" $(existing "Resources/$p.xml"); done +check XML/BackingStory.rnc $(existing XML/BackingStory.xml) +check XML/Tags.rnc $(existing XML/Tags.xml) exit $status