mirror of
https://github.com/storytold/indd-utils.git
synced 2026-11-30 10:04:22 +01:00
TextFramePreference gets the maximum column width, fixed column width, auto-sizing minimums, text wrap override, column rule width and colour, footnote spacings and the inset spacing (from the frame), read from their chunks. Attributes that IDML writes only on some frames, with one value wherever it does, are generated as WhenWritten values and also give the versions from which column rules and footnotes exist. Value coverage on trustworthy pairs: 82.03 % to 83.37 %.
469 lines
16 KiB
Rust
469 lines
16 KiB
Rust
//! Values written from IDML observation: what every InDesign-exported IDML
|
|
//! 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`, and on the other elements the converter writes
|
|
//! (`element_values.xml`, generated by `tools/element_values.py`). See
|
|
//! `docs/format/idml-values.md`.
|
|
|
|
use super::xml::Xml;
|
|
|
|
/// An element of the values file.
|
|
#[derive(Debug, Clone, PartialEq, Default)]
|
|
pub struct Node {
|
|
pub tag: String,
|
|
pub attrs: Vec<(String, String)>,
|
|
pub text: Option<String>,
|
|
pub children: Vec<Node>,
|
|
}
|
|
|
|
impl Node {
|
|
pub fn child(&self, tag: &str) -> Option<&Node> {
|
|
self.children.iter().find(|c| c.tag == tag)
|
|
}
|
|
|
|
pub fn attr(&self, name: &str) -> Option<&str> {
|
|
self.attrs
|
|
.iter()
|
|
.find(|(k, _)| k == name)
|
|
.map(|(_, v)| v.as_str())
|
|
}
|
|
|
|
/// Set the attributes of the descendant at `path`, creating missing
|
|
/// elements (`Properties` as the first child), replacing values
|
|
/// already there in place and adding the others at the end.
|
|
pub fn set(&mut self, path: &[&str], attrs: Vec<(&str, String)>) {
|
|
let mut node = self;
|
|
for tag in path {
|
|
let i = match node.children.iter().position(|c| c.tag == *tag) {
|
|
Some(i) => i,
|
|
None => {
|
|
let new = Node {
|
|
tag: tag.to_string(),
|
|
..Node::default()
|
|
};
|
|
if *tag == "Properties" {
|
|
node.children.insert(0, new);
|
|
0
|
|
} else {
|
|
node.children.push(new);
|
|
node.children.len() - 1
|
|
}
|
|
}
|
|
};
|
|
node = &mut node.children[i];
|
|
}
|
|
for (k, v) in attrs {
|
|
match node.attrs.iter_mut().find(|(a, _)| a == k) {
|
|
Some(e) => e.1 = v,
|
|
None => node.attrs.push((k.to_string(), v)),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Add the attributes and children of `other` that `self` lacks.
|
|
/// Children with the same tag are merged.
|
|
pub fn merge(&mut self, other: &Node) {
|
|
for (k, v) in &other.attrs {
|
|
if self.attr(k).is_none() {
|
|
self.attrs.push((k.clone(), v.clone()));
|
|
}
|
|
}
|
|
if self.text.is_none() {
|
|
self.text = other.text.clone();
|
|
}
|
|
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()),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Write this element and its children.
|
|
pub fn write(&self, x: &mut Xml) {
|
|
x.start(&self.tag);
|
|
for (k, v) in &self.attrs {
|
|
x.attr(k, v);
|
|
}
|
|
if let Some(t) = &self.text {
|
|
x.text(t);
|
|
}
|
|
for c in &self.children {
|
|
c.write(x);
|
|
}
|
|
x.end();
|
|
}
|
|
}
|
|
|
|
const ROOT_VALUES: &str = include_str!("root_values.xml");
|
|
|
|
/// The observed values of root style element `tag` (`ParagraphStyle`,
|
|
/// `ObjectStyle`, ...) for a document of InDesign version `major`.
|
|
pub fn root_style(tag: &str, major: u32) -> Node {
|
|
let mut out = Node {
|
|
tag: tag.to_string(),
|
|
..Node::default()
|
|
};
|
|
let root = parse(ROOT_VALUES).expect("root_values.xml is well-formed");
|
|
for block in &root.children {
|
|
let since = block
|
|
.attr("MinimumVersion")
|
|
.map_or(0, |v| v.parse().expect("MinimumVersion is a number"));
|
|
if since <= major
|
|
&& let Some(n) = block.child(tag)
|
|
{
|
|
out.merge(n);
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
const OBJECT_STYLE_VALUES: &str = include_str!("object_style_values.xml");
|
|
|
|
/// The observed values of object styles other than the root `[None]`, for
|
|
/// a document of InDesign version `major`.
|
|
pub fn object_style(major: u32) -> Node {
|
|
let mut out = Node {
|
|
tag: "ObjectStyle".to_string(),
|
|
..Node::default()
|
|
};
|
|
// Parsed once: the converter asks for these values for every page item.
|
|
static PARSED: std::sync::OnceLock<Node> = std::sync::OnceLock::new();
|
|
let root = PARSED.get_or_init(|| {
|
|
parse(OBJECT_STYLE_VALUES).expect("object_style_values.xml is well-formed")
|
|
});
|
|
for block in &root.children {
|
|
let since = block
|
|
.attr("MinimumVersion")
|
|
.map_or(0, |v| v.parse().expect("MinimumVersion is a number"));
|
|
if since <= major
|
|
&& let Some(n) = block.child("ObjectStyle")
|
|
{
|
|
out.merge(n);
|
|
}
|
|
}
|
|
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<Node> {
|
|
let root = parse(PREFERENCE_VALUES).expect("preference_values.xml is well-formed");
|
|
let mut out: Vec<Node> = 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
|
|
}
|
|
|
|
const ELEMENT_VALUES: &str = include_str!("element_values.xml");
|
|
|
|
fn element_values() -> &'static Node {
|
|
static PARSED: std::sync::OnceLock<Node> = std::sync::OnceLock::new();
|
|
PARSED.get_or_init(|| parse(ELEMENT_VALUES).expect("element_values.xml is well-formed"))
|
|
}
|
|
|
|
/// Whether a block of `element_values.xml` applies to InDesign version
|
|
/// `major`.
|
|
fn applies(block: &Node, major: u32) -> bool {
|
|
let bound = |name: &str| {
|
|
block
|
|
.attr(name)
|
|
.map(|v| v.parse::<u32>().expect("version bounds are numbers"))
|
|
};
|
|
bound("MinimumVersion").is_none_or(|v| v <= major)
|
|
&& bound("MaximumVersion").is_none_or(|v| major <= v)
|
|
}
|
|
|
|
/// The observed values of the elements on `path` (a tag, or a tag and a
|
|
/// child tag such as `Spread/FlattenerPreference`) for a document of
|
|
/// InDesign version `major`, from `element_values.xml`. `None` if the
|
|
/// file has no values for it.
|
|
pub fn element(path: &str, major: u32) -> Option<Node> {
|
|
blocks_element("Values", path, major)
|
|
}
|
|
|
|
/// The values of attributes that only some elements on `path` have, for
|
|
/// the converter to write where it writes the attribute (`WhenWritten`
|
|
/// blocks of `element_values.xml`).
|
|
pub fn when_written(path: &str, major: u32) -> Vec<(String, String)> {
|
|
blocks_element("WhenWritten", path, major)
|
|
.map(|n| n.attrs)
|
|
.unwrap_or_default()
|
|
}
|
|
|
|
fn blocks_element(block_tag: &str, path: &str, major: u32) -> Option<Node> {
|
|
let (parent, child) = match path.split_once('/') {
|
|
Some((p, c)) => (p, Some(c)),
|
|
None => (path, None),
|
|
};
|
|
let mut out: Option<Node> = None;
|
|
for block in element_values()
|
|
.children
|
|
.iter()
|
|
.filter(|b| b.tag == block_tag)
|
|
{
|
|
if !applies(block, major) {
|
|
continue;
|
|
}
|
|
let Some(mut n) = block.child(parent) else {
|
|
continue;
|
|
};
|
|
if let Some(c) = child {
|
|
match n.child(c) {
|
|
Some(cn) => n = cn,
|
|
None => continue,
|
|
}
|
|
}
|
|
let mut n = n.clone();
|
|
if child.is_none() {
|
|
// Children are other paths.
|
|
n.children.retain(|c| c.tag == "Properties");
|
|
}
|
|
match &mut out {
|
|
Some(o) => o.merge(&n),
|
|
None => out = Some(n),
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// The observed attributes of the elements on `path`, without `Present`.
|
|
pub fn element_attrs(path: &str, major: u32) -> Vec<(String, String)> {
|
|
element(path, major)
|
|
.map(|n| {
|
|
n.attrs
|
|
.into_iter()
|
|
.filter(|(k, _)| k != "Present")
|
|
.collect()
|
|
})
|
|
.unwrap_or_default()
|
|
}
|
|
|
|
/// The element on `path` every IDML of InDesign version `major` in the
|
|
/// corpus has (`Present="true"` in `element_values.xml`), with its
|
|
/// observed values; `None` if not every IDML has it.
|
|
pub fn present(path: &str, major: u32) -> Option<Node> {
|
|
let mut n = element(path, major)?;
|
|
if n.attr("Present") != Some("true") {
|
|
return None;
|
|
}
|
|
n.attrs.retain(|(k, _)| k != "Present");
|
|
Some(n)
|
|
}
|
|
|
|
/// The list of `tag` elements every IDML of InDesign version `major` in
|
|
/// the corpus has, in order (`List` blocks of `element_values.xml`);
|
|
/// empty if there is none.
|
|
pub fn list(tag: &str, major: u32) -> Vec<Node> {
|
|
element_values()
|
|
.children
|
|
.iter()
|
|
.filter(|b| b.tag == "List" && b.attr("Tag") == Some(tag) && applies(b, major))
|
|
.flat_map(|b| b.children.clone())
|
|
.collect()
|
|
}
|
|
|
|
/// The observed values of a `tag` element whose key attribute (such as
|
|
/// `Name`) has `value` (`Keyed` blocks of `element_values.xml`).
|
|
pub fn keyed(tag: &str, value: &str) -> Option<Node> {
|
|
let block = element_values()
|
|
.children
|
|
.iter()
|
|
.find(|b| b.tag == "Keyed" && b.attr("Tag") == Some(tag))?;
|
|
let key = block.attr("Key")?;
|
|
block
|
|
.children
|
|
.iter()
|
|
.find(|n| n.attr(key) == Some(value))
|
|
.cloned()
|
|
}
|
|
|
|
fn unescape(s: &str) -> String {
|
|
s.replace("<", "<")
|
|
.replace(">", ">")
|
|
.replace(""", "\"")
|
|
.replace("'", "'")
|
|
.replace("&", "&")
|
|
}
|
|
|
|
/// Parse the small, trusted XML subset of the values file: elements,
|
|
/// attributes in single or double quotes, text, comments and the XML
|
|
/// declaration.
|
|
fn parse(s: &str) -> Option<Node> {
|
|
let mut stack: Vec<Node> = vec![Node::default()];
|
|
let mut rest = s;
|
|
while !rest.is_empty() {
|
|
if let Some(r) = rest.strip_prefix("<?") {
|
|
rest = &r[r.find("?>")? + 2..];
|
|
} else if let Some(r) = rest.strip_prefix("<!--") {
|
|
rest = &r[r.find("-->")? + 3..];
|
|
} else if let Some(r) = rest.strip_prefix("</") {
|
|
rest = &r[r.find('>')? + 1..];
|
|
let done = stack.pop()?;
|
|
stack.last_mut()?.children.push(done);
|
|
} else if let Some(r) = rest.strip_prefix('<') {
|
|
let end = r.find('>')?;
|
|
let (mut head, empty) = match r[..end].strip_suffix('/') {
|
|
Some(h) => (h.trim_end(), true),
|
|
None => (&r[..end], false),
|
|
};
|
|
rest = &r[end + 1..];
|
|
let name_end = head.find(char::is_whitespace).unwrap_or(head.len());
|
|
let mut node = Node {
|
|
tag: head[..name_end].to_string(),
|
|
..Node::default()
|
|
};
|
|
head = head[name_end..].trim_start();
|
|
while !head.is_empty() {
|
|
let eq = head.find('=')?;
|
|
let key = head[..eq].trim();
|
|
let value = head[eq + 1..].trim_start();
|
|
let quote = value.chars().next()?;
|
|
let close = value[1..].find(quote)? + 1;
|
|
node.attrs
|
|
.push((key.to_string(), unescape(&value[1..close])));
|
|
head = value[close + 1..].trim_start();
|
|
}
|
|
if empty {
|
|
stack.last_mut()?.children.push(node);
|
|
} else {
|
|
stack.push(node);
|
|
}
|
|
} else {
|
|
let end = rest.find('<').unwrap_or(rest.len());
|
|
let text = &rest[..end];
|
|
if !text.trim().is_empty() {
|
|
stack.last_mut()?.text = Some(unescape(text));
|
|
}
|
|
rest = &rest[end..];
|
|
}
|
|
}
|
|
let mut top = stack.pop()?;
|
|
stack.is_empty().then_some(())?;
|
|
top.children.pop()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn parses_values_subset() {
|
|
let n = parse(
|
|
"<?xml version=\"1.0\"?>\n<!-- c -->\n<A x=\"1 & 2\" y='q\"'>\n\t<B />\n\t<C type=\"string\">t < u</C>\n</A>\n",
|
|
)
|
|
.unwrap();
|
|
assert_eq!(n.tag, "A");
|
|
assert_eq!(n.attr("x"), Some("1 & 2"));
|
|
assert_eq!(n.attr("y"), Some("q\""));
|
|
assert_eq!(n.children.len(), 2);
|
|
assert_eq!(n.child("C").unwrap().text.as_deref(), Some("t < u"));
|
|
}
|
|
|
|
#[test]
|
|
fn gates_values_by_version() {
|
|
let old = root_style("ParagraphStyle", 7);
|
|
let new = root_style("ParagraphStyle", 21);
|
|
assert_eq!(old.attr("KeepFirstLines"), Some("2"));
|
|
assert_eq!(old.attr("KeepAllLinesTogether"), Some("false"));
|
|
assert!(old.attr("EmitCss").is_none());
|
|
assert_eq!(new.attr("EmitCss"), Some("true"));
|
|
let props = new.child("Properties").unwrap();
|
|
assert!(props.child("RuleAboveType").is_some());
|
|
assert!(props.child("ParagraphBorderType").is_some());
|
|
let os = root_style("ObjectStyle", 21);
|
|
assert!(
|
|
os.child("TextFramePreference")
|
|
.unwrap()
|
|
.attr("TextColumnCount")
|
|
.is_some()
|
|
);
|
|
assert!(
|
|
os.child("TextFramePreference")
|
|
.unwrap()
|
|
.attr("AutoSizingType")
|
|
.is_some()
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn gates_object_style_values_by_version() {
|
|
let old = object_style(7);
|
|
let new = object_style(21);
|
|
assert!(old.child("ObjectExportOption").is_none());
|
|
assert!(new.child("ObjectExportOption").is_some());
|
|
// Values that vary between styles are not in the file.
|
|
assert!(new.attr("FillColor").is_none());
|
|
let mut n = new.clone();
|
|
n.set(
|
|
&["TextWrapPreference", "Properties", "TextWrapOffset"],
|
|
vec![("Top", "1".into())],
|
|
);
|
|
let wrap = n.child("TextWrapPreference").unwrap();
|
|
assert_eq!(wrap.children[0].tag, "Properties");
|
|
}
|
|
|
|
#[test]
|
|
fn gates_element_values_by_version() {
|
|
let old = element("TextFrame", 7).unwrap();
|
|
assert_eq!(old.attr("LocalDisplaySetting"), Some("Default"));
|
|
// Values of child paths are not attributes of the parent.
|
|
assert!(old.child("ObjectExportOption").is_none());
|
|
let new = element("Polygon/ObjectExportOption", 21).unwrap();
|
|
assert!(new.child("Properties").is_some());
|
|
// Export options differ between versions.
|
|
assert!(new.attr("EpubType").is_some());
|
|
assert_eq!(list("TrapPreset", 21).len(), 2);
|
|
let tfp = when_written("TextFrame/TextFramePreference", 21);
|
|
assert!(tfp.iter().any(|(k, _)| k == "ColumnRuleOffset"));
|
|
let tfp = when_written("TextFrame/TextFramePreference", 14);
|
|
assert!(!tfp.iter().any(|(k, _)| k == "ColumnRuleOffset"));
|
|
let en = keyed("Language", "$ID/English: USA").unwrap();
|
|
assert_eq!(en.attr("DoubleQuotes"), Some("\u{201C}\u{201D}"));
|
|
let w = present("Document/WatermarkPreference", 21).unwrap();
|
|
assert!(w.attr("Present").is_none());
|
|
assert!(present("Document/EndnoteOption", 12).is_none());
|
|
assert!(
|
|
element("Polygon/ObjectExportOption", 8)
|
|
.unwrap()
|
|
.attr("EpubType")
|
|
.is_none()
|
|
);
|
|
}
|
|
|
|
#[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());
|
|
}
|
|
}
|