From 0dc40563ab33df1a408e6f5f71300cd631bda780 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Wed, 7 Oct 2026 00:35:38 +0000 Subject: [PATCH] feat: write preference values that every exported IDML has --- docs/format/idml-values.md | 48 ++++++- src/idml/mod.rs | 50 +++++-- src/idml/preference_values.xml | 254 +++++++++++++++++++++++++++++++++ src/idml/values.rs | 50 ++++++- tools/root_values.py | 144 ++++++++++++++++++- 5 files changed, 519 insertions(+), 27 deletions(-) create mode 100644 src/idml/preference_values.xml diff --git a/docs/format/idml-values.md b/docs/format/idml-values.md index 896319a..794633e 100644 --- a/docs/format/idml-values.md +++ b/docs/format/idml-values.md @@ -1,7 +1,8 @@ # Values written from IDML observation Some values the converter writes do not come from the INDD file. They are -values that every IDML exported by InDesign in the corpus has. They are +values that every IDML exported by InDesign in the corpus has, on the +root styles and in the preferences. They are facts about InDesign's IDML output, not about the INDD format, and the evidence is the corpus IDML files alone. @@ -100,10 +101,43 @@ element in the package. `PlatformName` is `$ID/` in all 4,464 `Font` elements of the corpus IDML files (`fonts.md`). The converter writes that value on every font. -## Not yet written +## Preferences -`Resources/Preferences.xml` has more elements that every corpus IDML has -(`TextDefault`, `TextPreference`, `PageItemDefault`, `StoryPreference`, -`FootnoteOption` and others). Many of their attributes are the same in -all 88 files (for example 196 of the 276 attributes of `TextDefault`), -but others vary and may be stored in the INDD. They are not written yet. +`Resources/Preferences.xml` of every corpus IDML has the same 41 +top-level elements (`TextDefault`, `TextPreference`, +`TextFramePreference`, `PageItemDefault`, `StoryPreference`, +`FootnoteOption`, `TransparencyDefaultContainerObject` and others; the +DOM 7 file lacks `EPubFixedLayoutExportPreference`). `tools/root_values.py` +collects each attribute, `Properties` child and child element attribute +of these elements with the same rule as for the root styles, and writes +the kept values to `src/idml/preference_values.xml`. The converter writes +those elements in the order the IDML files list them. + +| Values | Same in | Written for version | +|---|---|---| +| 1,041 | 88 of 88 files | all | +| 66 | 87 of 87 files with DOM 12 or later | 12 and later | +| 46 | 80 of 80 files with DOM 15 or later | 15 and later | + +For example `TextDefault` keeps 264 of its 317 values, +`TransparencyDefaultContainerObject` all 352 and `TextFramePreference` +32 of 34. + +**Left out:** + +- 230 values that vary between files, for example the page size, + margins and grid settings, 53 values of `TextDefault` (among them the + font and point size) and 12 of `TextPreference`. +- The document setup the converter reads from the INDD (`objects.md`): + `PageHeight`, `PageWidth`, `FacingPages`, `Intent` and the four bleed + offsets of `DocumentPreference`. The converter writes its own values + for these and adds the observed values for the rest of the element. + `ViewPreference` gets `RulerOrigin="SpreadOrigin"`, as before. +- 3 values that name a style other than a root style, which the package + need not contain: `AppliedTextObjectStyle` and `AppliedGridObjectStyle` + of `PageItemDefault`, `FootnoteTextStyle` of `FootnoteOption`. +- 20 values that only the 2 files with DOM 20 have. A value first seen + in a later version is kept only when at least 10 files show it. + +Some of these values are probably stored in the INDD and may differ in a +document outside the corpus; none of them is read from the INDD yet. diff --git a/src/idml/mod.rs b/src/idml/mod.rs index 2fb3760..6d4d215 100644 --- a/src/idml/mod.rs +++ b/src/idml/mod.rs @@ -1676,25 +1676,53 @@ impl Writer<'_> { fn preferences(&self) -> String { let mut x = Xml::new(); self.package_root(&mut x, "Preferences"); + // Values every exported IDML has (docs/format/idml-values.md); + // values read from the INDD take precedence. + let mut nodes = values::preferences(self.doc.version.major); + let mut set = |tag: &str, ours: Vec<(&str, String)>| { + let i = match nodes.iter().position(|n| n.tag == tag) { + Some(i) => i, + None => { + nodes.push(Node { + tag: tag.to_string(), + ..Node::default() + }); + nodes.len() - 1 + } + }; + let node = &mut nodes[i]; + node.attrs + .retain(|(k, _)| !ours.iter().any(|(o, _)| o == k)); + let rest = std::mem::take(&mut node.attrs); + node.attrs = ours.into_iter().map(|(k, v)| (k.to_string(), v)).collect(); + node.attrs.extend(rest); + }; if let Some(p) = &self.doc.preferences { const INTENT: [&str; 3] = ["PrintIntent", "WebIntent", "MobileIntent"]; let [top, bottom, inside, outside] = p.bleed; - x.start("DocumentPreference") - .attr("PageHeight", num(p.page_height)) - .attr("PageWidth", num(p.page_width)) - .attr("FacingPages", p.facing_pages.to_string()) - .attr("DocumentBleedTopOffset", num(top)) - .attr("DocumentBleedBottomOffset", num(bottom)) - .attr("DocumentBleedInsideOrLeftOffset", num(inside)) - .attr("DocumentBleedOutsideOrRightOffset", num(outside)); + let mut ours = vec![ + ("PageHeight", num(p.page_height)), + ("PageWidth", num(p.page_width)), + ("FacingPages", p.facing_pages.to_string()), + ("DocumentBleedTopOffset", num(top)), + ("DocumentBleedBottomOffset", num(bottom)), + ("DocumentBleedInsideOrLeftOffset", num(inside)), + ("DocumentBleedOutsideOrRightOffset", num(outside)), + ]; if let Some(i) = INTENT.get(p.intent as usize) { - x.attr("Intent", *i); + ours.push(("Intent", i.to_string())); } - x.end(); + set("DocumentPreference", ours); } // Guide locations are written measured from the spread (see // `guide`), so the ruler origin is stated rather than read. - x.empty("ViewPreference", &[("RulerOrigin", "SpreadOrigin".into())]); + set( + "ViewPreference", + vec![("RulerOrigin", "SpreadOrigin".into())], + ); + for n in &nodes { + n.write(&mut x); + } x.end(); x.finish() } diff --git a/src/idml/preference_values.xml b/src/idml/preference_values.xml new file mode 100644 index 0000000..6f2d95d --- /dev/null +++ b/src/idml/preference_values.xml @@ -0,0 +1,254 @@ + + + + + + + + Auto + Auto + Default + Default + UseDocument + Default + AllPages + + + + + AllPages + + + + + Auto + Auto + Default + Default + UseDocument + Default + Default + + + + + + + + 0000 + + + + + + NoBalancing + Text Color + Swatch/None + StrokeStyle/$ID/Solid + Swatch/None + StrokeStyle/$ID/Solid + Text Color + Swatch/None + StrokeStyle/$ID/Solid + Text Color + Swatch/None + StrokeStyle/$ID/Solid + All + Text Color + Text Color + $ID/ + Nothing + Text Color + Text Color + $ID/ + Nothing + + $ID/ + Nothing + CharacterStyle/$ID/[No character style] + NumberingList/$ID/[Default] + 1, 2, 3, 4... + + + + + + + + + LightBlue + + + + + Arabic + DontRestart + NoPrefixSuffix + SuperscriptMarker + StrokeStyle/$ID/Solid + Color/Black + Swatch/None + StrokeStyle/$ID/Solid + Color/Black + Swatch/None + + + + + + + + + + + + StylesheetInXML + + + + + + Nothing + StylesheetInXML + + + + + BrickRed + DarkBlue + GrassGreen + Violet + + + + + + + + /////wAAAAAAAAAA + + + + + 1, 2, 3, 4... + + + + + Violet + Magenta + + + + + LightGray + LightBlue + + + + + Cyan + + + + + + Fiesta + GridBlue + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + GridGreen + + + + + + + + + + + + + + + + + + + + + + + Color/Black + Swatch/None + StrokeStyle/$ID/Solid + + + + + + + diff --git a/src/idml/values.rs b/src/idml/values.rs index 30fa296..718884f 100644 --- a/src/idml/values.rs +++ b/src/idml/values.rs @@ -1,6 +1,7 @@ //! Values written from IDML observation: what every InDesign-exported IDML -//! in the corpus has on the root styles (`root_values.xml`, generated by -//! `tools/root_values.py`). See `docs/format/idml-values.md`. +//! in the corpus has on the root styles (`root_values.xml`) and in its +//! preferences (`preference_values.xml`), both generated by +//! `tools/root_values.py`. See `docs/format/idml-values.md`. use super::xml::Xml; @@ -39,6 +40,8 @@ impl Node { for c in &other.children { match self.children.iter_mut().find(|m| m.tag == c.tag) { Some(m) => m.merge(c), + // The schema puts `Properties` before other children. + None if c.tag == "Properties" => self.children.insert(0, c.clone()), None => self.children.push(c.clone()), } } @@ -83,6 +86,30 @@ pub fn root_style(tag: &str, major: u32) -> Node { out } +const PREFERENCE_VALUES: &str = include_str!("preference_values.xml"); + +/// The observed preference elements (`TextDefault`, ...) for a document of +/// InDesign version `major`, in the order the IDML files list them. +pub fn preferences(major: u32) -> Vec { + let root = parse(PREFERENCE_VALUES).expect("preference_values.xml is well-formed"); + let mut out: Vec = Vec::new(); + for block in &root.children { + let since = block + .attr("MinimumVersion") + .map_or(0, |v| v.parse().expect("MinimumVersion is a number")); + if since > major { + continue; + } + for n in &block.children { + match out.iter_mut().find(|m| m.tag == n.tag) { + Some(m) => m.merge(n), + None => out.push(n.clone()), + } + } + } + out +} + fn unescape(s: &str) -> String { s.replace("<", "<") .replace(">", ">") @@ -190,4 +217,23 @@ mod tests { .is_some() ); } + + #[test] + fn gates_preferences_by_version() { + let old = preferences(7); + let new = preferences(21); + assert!( + old.iter() + .all(|n| n.tag != "EPubFixedLayoutExportPreference") + ); + assert!( + new.iter() + .any(|n| n.tag == "EPubFixedLayoutExportPreference") + ); + let text = new.iter().find(|n| n.tag == "TextDefault").unwrap(); + assert!(text.attr("PointSize").is_none()); + // Values the converter reads from the INDD are not in the file. + let doc = new.iter().find(|n| n.tag == "DocumentPreference").unwrap(); + assert!(doc.attr("PageWidth").is_none()); + } } diff --git a/tools/root_values.py b/tools/root_values.py index 65bf3b9..8fa06b7 100644 --- a/tools/root_values.py +++ b/tools/root_values.py @@ -1,17 +1,23 @@ #!/usr/bin/env python3 -"""Find the values that every corpus IDML has on its root styles. +"""Find the values that every corpus IDML has on its root styles and in +its preferences. -Reads Resources/Styles.xml of every IDML in the corpus pairs (distinct -files only) and collects each attribute, Properties child and child -element attribute of the root styles. A value is kept when it is the same -in every IDML from some DOM version on and present in all of them; the +Reads Resources/Styles.xml and Resources/Preferences.xml of every IDML in +the corpus pairs (distinct files only) and collects each attribute, +Properties child and child element attribute of the root styles and of +the top-level preference elements. A value is kept when it is the same in +every IDML from some DOM version on and present in all of them; the earliest such version is its minimum version. Attributes the converter reads from the INDD (the TEXT_ATTRS table in src/idml/mod.rs) are left -out for the paragraph and character root styles. +out for the paragraph and character root styles, and the document setup +it reads is left out of the preferences. Preference values that refer to +a style other than a root style are left out, since the package need not +have that style. Usage: python3 -I tools/root_values.py [--write] Prints the evidence counts. With --write, regenerates -src/idml/root_values.xml. See docs/format/idml-values.md. +src/idml/root_values.xml and src/idml/preference_values.xml. See +docs/format/idml-values.md. """ import hashlib @@ -25,6 +31,38 @@ from xml.sax.saxutils import quoteattr ROOT = Path(__file__).resolve().parent.parent OUT = ROOT / "src" / "idml" / "root_values.xml" +PREF_OUT = ROOT / "src" / "idml" / "preference_values.xml" + +# Preference attributes the converter reads from the INDD. +PREF_SKIP = { + ("DocumentPreference", "PageHeight"), ("DocumentPreference", "PageWidth"), + ("DocumentPreference", "FacingPages"), ("DocumentPreference", "Intent"), + ("DocumentPreference", "DocumentBleedTopOffset"), + ("DocumentPreference", "DocumentBleedBottomOffset"), + ("DocumentPreference", "DocumentBleedInsideOrLeftOffset"), + ("DocumentPreference", "DocumentBleedOutsideOrRightOffset"), + ("ViewPreference", "RulerOrigin"), +} +# Styles a preference value may refer to: those every package has. +ROOT_STYLES = { + "ParagraphStyle/$ID/[No paragraph style]", + "CharacterStyle/$ID/[No character style]", + "ObjectStyle/$ID/[None]", +} +# A preference value first seen in a later version is kept only when at +# least this many files show it. +MIN_FILES = 10 +STYLE_REF = re.compile(r"(?:>|^)(Paragraph|Character|Object|Cell|Table)Style/[^<]*") + +PREF_HEADER = """ + +""" TARGETS = OrderedDict([ ("ParagraphStyle", "ParagraphStyle/$ID/[No paragraph style]"), @@ -123,6 +161,83 @@ def analyse(): return pairs, idmls, doms, kept, left_out, order +def since_of(by_file, doms): + """The first DOM version from which every file has the same value, and + the number of those files; None if there is none.""" + for m in sorted({doms[i] for i in by_file}): + files = [i for i, d in enumerate(doms) if d >= m] + if all(i in by_file for i in files): + if len({by_file[i] for i in files}) == 1: + return (m, len(files)) + return None + return None + + +def style_ref(v): + m = STYLE_REF.search(v) + return m and m.group(0).lstrip(">") not in ROOT_STYLES + + +def analyse_preferences(idmls, doms): + values = defaultdict(dict) + order = defaultdict(dict) + tags = OrderedDict() + for i, (_dom, idml) in enumerate(idmls): + root = ET.fromstring(zipfile.ZipFile(idml).read("Resources/Preferences.xml")) + for el in root: + tags.setdefault(el.tag, len(tags)) + out = {} + leaves(el, (), out, order[el.tag]) + for k, v in out.items(): + values[(el.tag, k)][i] = v + kept = defaultdict(list) + left_out = defaultdict(lambda: defaultdict(list)) + for (tag, key), by_file in values.items(): + path, name = key + plain = name.split("/", 1)[1] if name.startswith("P/") else name[1:] + if not path and (tag, plain) in PREF_SKIP: + left_out[tag]["read from the INDD"].append(plain) + continue + since = since_of(by_file, doms) + if since is None: + left_out[tag]["varies"].append("/".join(path + (plain,))) + continue + if since[1] < MIN_FILES: + left_out[tag][f"in fewer than {MIN_FILES} files"].append("/".join(path + (plain,))) + continue + value = next(iter(by_file.values())) + if style_ref(value): + left_out[tag]["refers to a style"].append("/".join(path + (plain,))) + continue + kept[tag].append((key, value, since)) + return tags, kept, left_out, order + + +def write_preferences(tags, kept, order, first): + blocks = [] + for since in sorted({s for items in kept.values() for _, _, (s, _) in items}): + gate = "" if since == first else f' MinimumVersion="{since}"' + s = f"\t\n" + for tag in tags: + items = sorted((it for it in kept[tag] if it[2][0] == since), + key=lambda it: order[tag][it[0]]) + if not items: + continue + tree = {"attrs": [], "props": [], "children": OrderedDict()} + for (path, name), v, _ in items: + node = tree + for p in path: + node = node["children"].setdefault( + p, {"attrs": [], "props": [], "children": OrderedDict()}) + if name.startswith("@"): + node["attrs"].append((name[1:], v)) + else: + node["props"].append(v) + s += element(tag, tree, "\t\t") + blocks.append(s + "\t\n") + PREF_OUT.write_text(PREF_HEADER + "\n" + "".join(blocks) + "\n") + + def element(tag, node, indent): attrs = "".join(f" {k}={quoteattr(v)}" for k, v in node["attrs"]) if not node["props"] and not node["children"]: @@ -174,9 +289,24 @@ def main(): print(f" {k:4} values, the same in {n} of {n} IDML files with DOM >= {since}") for why, names in left_out[tag].items(): print(f" {len(names):4} left out ({why}): {', '.join(sorted(names))}") + tags, pkept, pleft, porder = analyse_preferences(idmls, doms) + print("\nPreferences:") + total = defaultdict(int) + for tag in tags: + for _, _, since in pkept[tag]: + total[since] += 1 + for (since, n), k in sorted(total.items()): + print(f" {k:4} values, the same in {n} of {n} IDML files with DOM >= {since}") + for tag in tags: + counts = {why: len(names) for why, names in pleft[tag].items()} + print(f" {tag}: {len(pkept[tag])} kept, left out {counts}") + if pleft[tag].get("refers to a style") or pleft[tag].get("read from the INDD"): + print(f" {pleft[tag].get('refers to a style', [])} {pleft[tag].get('read from the INDD', [])}") if "--write" in sys.argv: write(kept, order, min(doms)) print(f"\nwrote {OUT.relative_to(ROOT)}") + write_preferences(tags, pkept, porder, min(doms)) + print(f"wrote {PREF_OUT.relative_to(ROOT)}") if __name__ == "__main__":