feat: convert text formatting

Parse attribute lists in style objects and in paragraph and character
style runs, and write 40 text attributes (font, style, size, leading,
colour, tracking, kerning method, indents, spacing, justification,
underline, rules, hyphenation and more) on styles and text ranges. Read
font family names.

tools/compare.py now also compares text range attributes at matching text
offsets; every mapped attribute matches the reference in all ranges.
This commit is contained in:
aiongg committed 2026-10-06 16:33:53 +00:00
1 parent 0e20d76f2a
commit 5f87710d92
5 files changed
+438 -43

No files matched your search

+77
View File
@@ -40,3 +40,80 @@ list and absent from the IDML.
| 0x6E64 | `StrokeColor` (swatch UID) | 78 of 82 |
| 0x6E65 | `StrokeWeight` | 171 of 171 |
| 0x6E6D | `MiterLimit` | 778 of 778 |
## Text attribute lists
Text formatting uses the same record layout with a **u16** count. It
appears in:
- **Styles:** chunk 0x23F of a style object (u16 count, records).
- **Story runs:** each paragraph-style or character-style run record
(chunk 0x262, see `objects.md`) continues after the style UID with a u16
count and records. These are the run's local overrides.
Value types are specific to each attribute (for example 0x1B05 for swatch
references, 0x1B28 for point size), so the converter decodes text values
by length: 8 bytes f64, 4 bytes u32, 2 bytes u16, other lengths raw.
String values (`FontStyle`) are a flag byte followed by an in-object
string.
### Mapping and evidence
Found by aligning IDML `ParagraphStyleRange` and `CharacterStyleRange`
elements with INDD runs at the same text offset (1,562 ranges), and IDML
styles with INDD styles of the same name (486 styles), then checked with
`tools/compare.py`. Counts are matches/total in the current comparison
(ranges + paragraph styles + character styles where present).
| ID | IDML attribute | Encoding | Evidence |
|---|---|---|---|
| 0x1B01 | `FillColor` | swatch UID | 354/354 ranges, 226/226 styles |
| 0x1B02 | `FontStyle` | flag + string | 474/474 ranges, 202/202 styles |
| 0x1B03 | `PointSize` | f64 | 1,090/1,090 ranges |
| 0x1B06 | `HorizontalScale` | fraction ×100 | 2/2 ranges, 75/75 styles |
| 0x1B07 | `KerningMethod` | code: 15972 Metrics, 79875 Optical | 20/20 ranges, 81/81 styles |
| 0x1B08 | `Ligatures` | 1 = true | 201/201 ranges |
| 0x1B0A | `StrokeWeight` | f64 | 241/241 ranges |
| 0x1B0B | `Tracking` | thousandths of an em ×1000 | 49/49 ranges, 94/94 styles |
| 0x1B0C | `Composer` | code: 0x2001 HL Single, 0x2002 HL Composer, 0x2078 HL Composer Optyca | 4/4 ranges, 114/114 styles |
| 0x1B11 | `Capitalization` | 0 Normal, 2 AllCaps | 77/77 styles |
| 0x1B12 | `StrokeColor` | swatch UID | 75/75 styles |
| 0x1B16 | `LeftIndent` | f64 | 22/22 ranges |
| 0x1B18 | `FirstLineIndent` | f64 | 12/12 ranges |
| 0x1B1A | `AutoLeading` | fraction ×100 | 75/75 styles |
| 0x1B1B | `Leading` (Properties) | f64; negative = Auto | 43/43 ranges, 137/137 styles |
| 0x1B1F | `Hyphenation` | 3 = true, 0 = false | 204/204 ranges |
| 0x1B25 | `HyphenationZone` | f64 | 155/155 ranges |
| 0x1B26 | `SpaceBefore` | f64 | 13/13 ranges |
| 0x1B27 | `SpaceAfter` | f64 | 42/42 ranges |
| 0x1B2A | `Underline` | 1 = true | 81/81 ranges |
| 0x1B2B | `AppliedFont` (Properties) | font family UID | 1,071/1,071 ranges, 236/247 styles |
| 0x1B2E | `MaximumWordSpacing` | fraction ×100 | 77/77 styles |
| 0x1B2F | `MinimumWordSpacing` | fraction ×100 | 77/77 styles |
| 0x1B42 | `FillTint` | f64 | 24/24 ranges |
| 0x1B4D | `RuleAboveLineWeight` | f64 | 155/155 ranges |
| 0x1B4F | `RuleAboveOffset` | f64 | 78/78 styles |
| 0x1B54 | `RuleBelowLineWeight` | f64 | 155/155 ranges |
| 0x1B55 | `RuleBelowTint` | f64 | 78/78 styles |
| 0x1B56 | `RuleBelowOffset` | f64 | 78/78 styles |
| 0x1B7E | `Justification` | 0 LeftAlign, 1 CenterAlign, 2 RightAlign, 4 LeftJustified, 5 CenterJustified | 70/70 ranges |
| 0x1B80 | `DropcapDetail` | u32 | styles only |
| 0x1B8C | `OTFContextualAlternate` | 1 = true | 220/220 ranges |
| 0x1B8D | `UnderlineColor` (Properties) | swatch UID, 0 = "Text Color" | 81/81 ranges |
| 0x1B91 | `UnderlineOffset` | f64 | 81/81 ranges |
| 0x1B94 | `UnderlineWeight` | f64 | 81/81 ranges |
| 0x1BB7 | `MiterLimit` | f64 | 161/161 ranges |
| 0x1BBF | `SplitColumnInsideGutter` | f64 | 155/155 ranges |
| 0x1BD2 | `ParagraphShadingColor` (Properties) | swatch UID | 25/25 ranges |
| 0x1BD3 | `ParagraphShadingTint` | f64 | 79/79 styles |
| 0x1A401 | `BulletsAndNumberingListType` | 0 NoList, 1 BulletList | 10/12 ranges |
Attributes whose value never varies in the corpus (for example
`BaselineShift`, `RightIndent`) cannot be located this way and are not
written; InDesign then uses its defaults.
**Font family names.** Font families are class 0x3E03; chunk 0x3E05 holds
a flag byte, u16, then the family name as an in-object string. IDML
`Fonts.xml` names a family `di<UID hex>`. In 7 of 362 families IDML adds a
technology suffix (`Montserrat (OTF)`, `Times (TT)`) that the INDD data
does not determine; the converter writes the plain name.
+215 -24
View File
@@ -15,6 +15,107 @@ enum AttrKind {
Swatch,
}
#[derive(Clone, Copy)]
enum TextKind {
Number,
/// Stored as a fraction, written as a percentage.
Percent,
/// Multiplied by the factor when written.
Scale(f64),
/// True when the value equals the given code.
Bool(u32),
Enum(&'static [(u32, &'static str)]),
Swatch,
/// A swatch, or 0 for "Text Color" (written in Properties).
SwatchOrText,
Font,
FontStyle,
Leading,
}
/// Text attributes: ID, IDML name, kind, written in `<Properties>`.
/// See `docs/format/attributes.md` for the evidence behind each entry.
const TEXT_ATTRS: &[(u32, &str, TextKind, bool)] = &[
(0x1B01, "FillColor", TextKind::Swatch, false),
(0x1B02, "FontStyle", TextKind::FontStyle, false),
(0x1B03, "PointSize", TextKind::Number, false),
(0x1B06, "HorizontalScale", TextKind::Percent, false),
(0x1B08, "Ligatures", TextKind::Bool(1), false),
(
0x1B07,
"KerningMethod",
TextKind::Enum(&[(15972, "$ID/Metrics"), (79875, "$ID/Optical")]),
false,
),
(0x1B0A, "StrokeWeight", TextKind::Number, false),
(0x1B0B, "Tracking", TextKind::Scale(1000.0), false),
(
0x1B0C,
"Composer",
TextKind::Enum(&[
(0x2001, "HL Single"),
(0x2002, "HL Composer"),
(0x2078, "HL Composer Optyca"),
]),
false,
),
(
0x1B11,
"Capitalization",
TextKind::Enum(&[(0, "Normal"), (2, "AllCaps")]),
false,
),
(0x1B12, "StrokeColor", TextKind::Swatch, false),
(0x1B16, "LeftIndent", TextKind::Number, false),
(0x1B18, "FirstLineIndent", TextKind::Number, false),
(0x1B1A, "AutoLeading", TextKind::Percent, false),
(0x1B1B, "Leading", TextKind::Leading, true),
(0x1B1F, "Hyphenation", TextKind::Bool(3), false),
(0x1B25, "HyphenationZone", TextKind::Number, false),
(0x1B26, "SpaceBefore", TextKind::Number, false),
(0x1B27, "SpaceAfter", TextKind::Number, false),
(0x1B2A, "Underline", TextKind::Bool(1), false),
(0x1B2B, "AppliedFont", TextKind::Font, true),
(0x1B2E, "MaximumWordSpacing", TextKind::Percent, false),
(0x1B2F, "MinimumWordSpacing", TextKind::Percent, false),
(0x1B42, "FillTint", TextKind::Number, false),
(0x1B4D, "RuleAboveLineWeight", TextKind::Number, false),
(0x1B4F, "RuleAboveOffset", TextKind::Number, false),
(0x1B54, "RuleBelowLineWeight", TextKind::Number, false),
(0x1B55, "RuleBelowTint", TextKind::Number, false),
(0x1B56, "RuleBelowOffset", TextKind::Number, false),
(
0x1B7E,
"Justification",
TextKind::Enum(&[
(0, "LeftAlign"),
(1, "CenterAlign"),
(2, "RightAlign"),
(4, "LeftJustified"),
(5, "CenterJustified"),
]),
false,
),
(0x1B80, "DropcapDetail", TextKind::Number, false),
(0x1B8C, "OTFContextualAlternate", TextKind::Bool(1), false),
(0x1B8D, "UnderlineColor", TextKind::SwatchOrText, true),
(0x1B91, "UnderlineOffset", TextKind::Number, false),
(0x1B94, "UnderlineWeight", TextKind::Number, false),
(0x1BB7, "MiterLimit", TextKind::Number, false),
(0x1BBF, "SplitColumnInsideGutter", TextKind::Number, false),
(0x1BD2, "ParagraphShadingColor", TextKind::Swatch, true),
(0x1BD3, "ParagraphShadingTint", TextKind::Number, false),
(
0x1A401,
"BulletsAndNumberingListType",
TextKind::Enum(&[(0, "NoList"), (1, "BulletList")]),
false,
),
];
/// An attribute written as a `<Properties>` child: name, type, text.
type Property = (&'static str, &'static str, String);
/// Page item attributes: attribute-list ID, IDML name, value kind.
/// See `docs/format/attributes.md` for the evidence behind each entry.
const ITEM_ATTRS: &[(u32, &str, AttrKind)] = &[
@@ -37,6 +138,11 @@ pub fn num(v: f64) -> String {
format!("{v}")
}
/// Round away binary noise from scaled values (0.8 * 100 = 80.00000000000001).
fn round(v: f64) -> f64 {
(v * 1e9).round() / 1e9
}
fn nums(v: &[f64]) -> String {
v.iter().map(|&x| num(x)).collect::<Vec<_>>().join(" ")
}
@@ -195,6 +301,63 @@ impl Writer<'_> {
x.finish()
}
/// IDML attributes and properties for a text attribute list.
fn text_attrs(&self, attrs: &Attrs) -> (Vec<(&'static str, String)>, Vec<Property>) {
let mut plain = Vec::new();
let mut props = Vec::new();
for &(id, name, kind, in_props) in TEXT_ATTRS {
let Some(v) = attrs.get(id) else { continue };
let swatch = |u: u32| self.doc.swatches.get(&u).cloned();
let out: Option<(&'static str, String)> = match kind {
TextKind::Number => v.as_f64().map(|f| ("unit", num(f))),
TextKind::Percent => v.as_f64().map(|f| ("unit", num(round(f * 100.0)))),
TextKind::Scale(k) => v.as_f64().map(|f| ("unit", num(round(f * k)))),
TextKind::Bool(t) => v.as_u32().map(|u| ("boolean", (u == t).to_string())),
TextKind::Enum(map) => v
.as_u32()
.and_then(|u| map.iter().find(|(k, _)| *k == u))
.map(|(_, n)| ("enumeration", n.to_string())),
TextKind::Swatch => v.as_u32().and_then(swatch).map(|s| ("object", s)),
TextKind::SwatchOrText => match v.as_u32() {
Some(0) => Some(("string", "Text Color".into())),
Some(u) => swatch(u).map(|s| ("object", s)),
None => None,
},
TextKind::Font => v
.as_u32()
.and_then(|u| self.doc.fonts.get(&u).cloned())
.map(|f| ("string", f)),
TextKind::FontStyle => v.as_string().map(|s| ("string", s)),
TextKind::Leading => v.as_f64().map(|f| {
if f < 0.0 {
("enumeration", "Auto".into())
} else {
("unit", num(f))
}
}),
};
if let Some((ty, text)) = out {
if in_props {
props.push((name, ty, text));
} else {
plain.push((name, text));
}
}
}
(plain, props)
}
fn properties(x: &mut Xml, props: &[Property]) {
if props.is_empty() {
return;
}
x.start("Properties");
for (name, ty, text) in props {
x.start(name).attr("type", *ty).text(text).end();
}
x.end();
}
/// Write page item attributes from the item's attribute list.
fn item_attrs(&self, x: &mut Xml, attrs: &Attrs) {
for &(id, name, kind) in ITEM_ATTRS {
@@ -244,25 +407,34 @@ impl Writer<'_> {
let name = style_name(s);
have_default |=
name == "$ID/[No paragraph style]" || name == "$ID/[No character style]";
let (plain, mut props) = self.text_attrs(&s.attrs);
x.start(tag)
.attr("Self", format!("{tag}/{}", self_name(&name)))
.attr("Name", &name);
if paragraph {
x.attr("NextStyle", self.style_ref(s.next.or(Some(s.uid)), true));
}
for (k, v) in &plain {
x.attr(k, v);
}
if let Some(base) = s.based_on.and_then(|b| doc.styles.get(&b)) {
// The root "[No ... style]" is written as a string.
let base_name = style_name(base);
let root = base.builtin && base.name.starts_with("[No ");
let (kind, value) = if root {
("string", base_name)
if root {
props.insert(0, ("BasedOn", "string", base_name));
} else {
("object", format!("{tag}/{}", self_name(&base_name)))
};
x.start("Properties");
x.start("BasedOn").attr("type", kind).text(&value).end();
x.end();
props.insert(
0,
(
"BasedOn",
"object",
format!("{tag}/{}", self_name(&base_name)),
),
);
}
}
Self::properties(&mut x, &props);
x.end();
}
if !have_default && !paragraph {
@@ -386,28 +558,47 @@ impl Writer<'_> {
let mut x = Xml::new();
self.package_root(&mut x, "Story");
x.start("Story").attr("Self", uref(Some(s.uid)));
// Group runs by paragraph style, then emit character runs inside.
let mut runs: Vec<_> = s
.runs
.iter()
.map(|r| (r.paragraph_style, r.character_style, r.text.clone()))
.collect();
let mut runs: Vec<_> = s.runs.iter().collect();
// The story's final paragraph return is implicit in IDML.
if let Some(last) = runs.last_mut()
&& last.2.ends_with('\r')
let mut last_text = None;
if let Some(last) = runs.last()
&& last.text.ends_with('\r')
{
last.2.pop();
last_text = Some(last.text[..last.text.len() - 1].to_string());
if last_text.as_deref() == Some("") && runs.len() > 1 {
runs.pop();
last_text = None;
}
}
let n = runs.len();
let text_of = |i: usize| -> &str {
match (&last_text, i + 1 == n) {
(Some(t), true) => t,
_ => &runs[i].text,
}
};
let mut i = 0;
while i < runs.len() {
let para = runs[i].0;
while i < n {
let para = (runs[i].paragraph_style, &runs[i].paragraph_attrs);
let (plain, props) = self.text_attrs(para.1);
x.start("ParagraphStyleRange")
.attr("AppliedParagraphStyle", self.style_ref(para, true));
while i < runs.len() && runs[i].0 == para {
let (_, chr, text) = &runs[i];
x.start("CharacterStyleRange")
.attr("AppliedCharacterStyle", self.style_ref(*chr, false));
let mut parts = text.split('\r').peekable();
.attr("AppliedParagraphStyle", self.style_ref(para.0, true));
for (k, v) in &plain {
x.attr(k, v);
}
Self::properties(&mut x, &props);
while i < n && (runs[i].paragraph_style, &runs[i].paragraph_attrs) == para {
let r = runs[i];
let (plain, props) = self.text_attrs(&r.character_attrs);
x.start("CharacterStyleRange").attr(
"AppliedCharacterStyle",
self.style_ref(r.character_style, false),
);
for (k, v) in &plain {
x.attr(k, v);
}
Self::properties(&mut x, &props);
let mut parts = text_of(i).split('\r').peekable();
while let Some(part) = parts.next() {
if !part.is_empty() {
// INDD stores a forced line break as LF; IDML as U+2028.
+40 -2
View File
@@ -42,6 +42,24 @@ impl Value {
_ => None,
}
}
/// Integer value of a reference, integer or enumeration.
pub fn as_u32(&self) -> Option<u32> {
match *self {
Value::Ref(v) => Some(v),
Value::Int(v) => Some(v as u32),
Value::Enum(v) => Some(v as u32),
_ => None,
}
}
/// A string value: a flag byte, then an in-object string.
pub fn as_string(&self) -> Option<String> {
match self {
Value::Other(_, b) if b.len() > 1 => Cursor::new(&b[1..]).string().ok(),
_ => None,
}
}
}
#[derive(Debug, Clone, Default, PartialEq)]
@@ -52,10 +70,21 @@ impl Attrs {
self.0.iter().find(|(a, _)| *a == id).map(|(_, v)| v)
}
/// A page item list (chunk 0x6E03): u32 count, then records.
pub fn parse(data: &[u8]) -> Result<Attrs, Error> {
let mut c = Cursor::new(data);
let n = c.u32()?;
let mut out = Vec::with_capacity(n.min(1024) as usize);
let n = c.u32()? as usize;
Attrs::records(&mut c, n, decode)
}
/// A text attribute list: `count` records at the cursor. Text value
/// types differ per attribute, so values are decoded by length.
pub fn parse_text(c: &mut Cursor, count: usize) -> Result<Attrs, Error> {
Attrs::records(c, count, decode_text)
}
fn records(c: &mut Cursor, n: usize, decode: fn(u32, &[u8]) -> Value) -> Result<Attrs, Error> {
let mut out = Vec::with_capacity(n.min(1024));
for _ in 0..n {
let id = c.u32()?;
let size = c.u16()? as usize;
@@ -78,6 +107,15 @@ impl Attrs {
}
}
fn decode_text(t: u32, data: &[u8]) -> Value {
match data.len() {
8 => Value::Double(f64::from_le_bytes(data.try_into().unwrap())),
4 => Value::Ref(u32::from_le_bytes(data.try_into().unwrap())),
2 => Value::Enum(u16::from_le_bytes(data.try_into().unwrap())),
_ => Value::Other(t, data.to_vec()),
}
}
fn decode(t: u32, data: &[u8]) -> Value {
let f64_at = |o: usize| f64::from_le_bytes(data[o..o + 8].try_into().unwrap());
match (t, data.len()) {
+62 -14
View File
@@ -28,6 +28,7 @@ pub mod class {
pub const STORY: u32 = 0x201;
pub const STYLE: u32 = 0x205;
pub const SECTION: u32 = 0x4C01;
pub const FONT_FAMILY: u32 = 0x3E03;
}
/// Chunk IDs.
@@ -57,6 +58,8 @@ pub mod chunk {
pub const STRAND_RUNS: u32 = 0x262;
pub const STYLE_INFO: u32 = 0x230;
pub const ITEM_ATTRS: u32 = 0x6E03;
pub const STYLE_ATTRS: u32 = 0x23F;
pub const FONT_FAMILY: u32 = 0x3E05;
pub const SWATCH_NAME: u32 = 0x1F30;
}
@@ -167,6 +170,7 @@ pub struct Style {
pub paragraph: bool,
pub based_on: Option<u32>,
pub next: Option<u32>,
pub attrs: Attrs,
}
/// A stretch of story text with one paragraph style and one character style.
@@ -175,6 +179,10 @@ pub struct TextRun {
pub text: String,
pub paragraph_style: Option<u32>,
pub character_style: Option<u32>,
/// Local paragraph formatting.
pub paragraph_attrs: Attrs,
/// Local character formatting.
pub character_attrs: Attrs,
}
#[derive(Debug, Clone, PartialEq)]
@@ -195,6 +203,8 @@ pub struct Document {
pub colors: Vec<Color>,
/// IDML reference (`Color/...`, `Swatch/None`) for each swatch UID.
pub swatches: BTreeMap<u32, String>,
/// Font family name for each font family UID.
pub fonts: BTreeMap<u32, String>,
}
/// Reads typed objects from a database, caching them.
@@ -278,6 +288,7 @@ impl<'a> Reader<'a> {
let mut styles = BTreeMap::new();
let mut colors = Vec::new();
let mut swatches = BTreeMap::new();
let mut fonts = BTreeMap::new();
for &(uid, cls) in self.db.classes() {
match cls {
class::STYLE => {
@@ -297,6 +308,11 @@ impl<'a> Reader<'a> {
color::class::SWATCH_NONE => {
swatches.insert(uid, "Swatch/None".into());
}
class::FONT_FAMILY => {
if let Some(d) = self.chunk(uid, chunk::FONT_FAMILY)? {
fonts.insert(uid, find_string(&d, 0)?);
}
}
_ => {}
}
}
@@ -310,6 +326,7 @@ impl<'a> Reader<'a> {
styles,
colors,
swatches,
fonts,
})
}
@@ -560,6 +577,14 @@ impl<'a> Reader<'a> {
};
let paragraph = Cursor::new(&data[at - 4..]).u32()? != 0;
let name = Cursor::new(&data[at + 1..]).string()?;
let attrs = match self.chunk(uid, chunk::STYLE_ATTRS)? {
Some(d) if d.len() >= 2 => {
let mut c = Cursor::new(&d);
let n = c.u16()? as usize;
Attrs::parse_text(&mut c, n).unwrap_or_default()
}
_ => Attrs::default(),
};
Ok(Some(Style {
uid,
name,
@@ -567,6 +592,7 @@ impl<'a> Reader<'a> {
paragraph,
based_on: uid_or_none(based_on),
next: uid_or_none(next),
attrs,
}))
}
@@ -577,8 +603,8 @@ impl<'a> Reader<'a> {
let mut strands = vec![c.u32()?];
strands.extend(c.u32_list()?);
let mut text: Vec<u16> = Vec::new();
let mut para: Vec<(usize, u32)> = Vec::new();
let mut chars: Vec<(usize, u32)> = Vec::new();
let mut para: Vec<StyleRun> = Vec::new();
let mut chars: Vec<StyleRun> = Vec::new();
for strand in strands {
let Some(list) = self.chunk(strand, chunk::STRAND_DATA)? else {
continue;
@@ -602,8 +628,17 @@ impl<'a> Reader<'a> {
strand::TEXT => {
text.extend(rc.segment_units(len)?);
}
strand::PARAGRAPH_STYLE => para.push((len, rc.u32()?)),
strand::CHARACTER_STYLE => chars.push((len, rc.u32()?)),
strand::PARAGRAPH_STYLE | strand::CHARACTER_STYLE => {
let style = rc.u32()?;
let n = rc.u16()? as usize;
let attrs = Attrs::parse_text(&mut rc, n).unwrap_or_default();
let list = if kind == strand::PARAGRAPH_STYLE {
&mut para
} else {
&mut chars
};
list.push((len, style, attrs));
}
_ => {}
}
}
@@ -635,22 +670,24 @@ fn find_string(data: &[u8], from: usize) -> Result<String, Error> {
/// Combine text with paragraph-style and character-style run lengths
/// (counted in UTF-16 code units) into runs with both styles constant.
fn split_runs(utf16: &[u16], para: &[(usize, u32)], chars: &[(usize, u32)]) -> Vec<TextRun> {
type StyleRun = (usize, u32, Attrs);
fn split_runs(utf16: &[u16], para: &[StyleRun], chars: &[StyleRun]) -> Vec<TextRun> {
let mut cuts: Vec<usize> = vec![0, utf16.len()];
for list in [para, chars] {
let mut pos = 0;
for &(len, _) in list {
for (len, _, _) in list {
pos += len;
cuts.push(pos.min(utf16.len()));
}
}
cuts.sort_unstable();
cuts.dedup();
let style_at = |list: &[(usize, u32)], at: usize| {
let run_at = |list: &[StyleRun], at: usize| -> Option<(Option<u32>, Attrs)> {
let mut pos = 0;
for &(len, style) in list {
for (len, style, attrs) in list {
if at < pos + len {
return uid_or_none(style);
return Some((uid_or_none(*style), attrs.clone()));
}
pos += len;
}
@@ -658,10 +695,16 @@ fn split_runs(utf16: &[u16], para: &[(usize, u32)], chars: &[(usize, u32)]) -> V
};
cuts.windows(2)
.filter(|w| w[0] < w[1])
.map(|w| TextRun {
text: String::from_utf16_lossy(&utf16[w[0]..w[1]]),
paragraph_style: style_at(para, w[0]),
character_style: style_at(chars, w[0]),
.map(|w| {
let (paragraph_style, paragraph_attrs) = run_at(para, w[0]).unwrap_or_default();
let (character_style, character_attrs) = run_at(chars, w[0]).unwrap_or_default();
TextRun {
text: String::from_utf16_lossy(&utf16[w[0]..w[1]]),
paragraph_style,
character_style,
paragraph_attrs,
character_attrs,
}
})
.collect()
}
@@ -703,7 +746,12 @@ mod tests {
#[test]
fn splits_runs_at_style_boundaries() {
let text: Vec<u16> = "abcdef".encode_utf16().collect();
let runs = split_runs(&text, &[(4, 10), (2, 11)], &[(2, 20), (4, 21)]);
let a = Attrs::default;
let runs = split_runs(
&text,
&[(4, 10, a()), (2, 11, a())],
&[(2, 20, a()), (4, 21, a())],
);
let texts: Vec<_> = runs.iter().map(|r| r.text.as_str()).collect();
assert_eq!(texts, ["ab", "cd", "ef"]);
assert_eq!(runs[1].paragraph_style, Some(10));
+44 -3
View File
@@ -45,11 +45,32 @@ def pairs(limit, substr):
return out[:limit] if limit else out
def text_ranges(story):
"""Map text offset -> attributes of the paragraph and character range
starting there, with keys prefixed PSR. and CSR."""
out = {}
pos = 0
for psr in story.findall("ParagraphStyleRange"):
pa = {"PSR." + k: v for k, v in props(psr).items()}
for csr in psr.findall("CharacterStyleRange"):
start = pos
for el in csr:
if el.tag == "Content":
pos += len((el.text or "").encode("utf-16-le")) // 2
elif el.tag != "Properties":
pos += 1
if pos > start:
ca = {"CSR." + k: v for k, v in props(csr).items()}
out[start] = {**pa, **ca}
return out
def load(path):
"""Map Self -> element, plus story texts, from an IDML package."""
z = zipfile.ZipFile(path)
elements = {}
stories = {}
ranges = {}
for name in z.namelist():
if not name.endswith(".xml"):
continue
@@ -64,7 +85,8 @@ def load(path):
if name.startswith("Stories/"):
for st in root.iter("Story"):
stories[st.get("Self")] = story_text(st)
return elements, stories
ranges[st.get("Self")] = text_ranges(st)
return elements, stories, ranges
def story_text(story):
@@ -120,8 +142,8 @@ def main():
if r.returncode != 0:
failures.append((indd.name, r.stderr.strip()))
continue
ref_el, ref_st = load(idml)
our_el, our_st = load(out)
ref_el, ref_st, ref_rg = load(idml)
our_el, our_st, our_rg = load(out)
for (tag, s), el in ref_el.items():
total[tag] += 1
mine = our_el.get((tag, s))
@@ -140,6 +162,25 @@ def main():
attr_ok[(tag, k)]["wrong"] += 1
if len(examples[(tag, k)]) < args.show:
examples[(tag, k)].append((indd.name, s, v, ours[k]))
for sid, rgs in ref_rg.items():
if our_st.get(sid) != ref_st.get(sid):
continue
mine = our_rg.get(sid, {})
for start, attrs in rgs.items():
total["TextRange"] += 1
if start not in mine:
continue
found["TextRange"] += 1
for k, v in attrs.items():
o = mine[start].get(k)
if o is None:
attr_ok[("TextRange", k)]["missing"] += 1
elif norm(o) == norm(v):
attr_ok[("TextRange", k)]["ok"] += 1
else:
attr_ok[("TextRange", k)]["wrong"] += 1
if len(examples[("TextRange", k)]) < args.show:
examples[("TextRange", k)].append((indd.name, sid, start, v, o))
for sid, text in ref_st.items():
if sid not in our_st:
story_ok["missing"] += 1