refactor: decode structured attribute values in the model

This commit is contained in:
aiongg committed 2026-10-07 19:17:50 +00:00
1 parent deeae26ba5
commit 4dc5fcbc45
5 files changed
+486 -235

No files matched your search

+81 -148
View File
@@ -7,6 +7,7 @@
//! attributes) and `objects.md` (anchored object settings).
use super::*;
use crate::model::attrs::{Delimiter, NestedStyle, TabStop};
#[derive(Clone, Copy)]
pub(super) enum AttrKind {
@@ -614,111 +615,55 @@ pub(super) const CELL_STYLE_PARAGRAPH_STYLE: u32 = 0x10463;
pub(super) const CELL_NO_STROKE_TYPE: u32 = 0x1040C;
/// Report an attribute value that the converter has no IDML value for to
/// `indd audit`: its code, or for a stroke type the code in its first four
/// bytes.
/// `indd audit`: its code (see [`Value::code`]).
pub(super) fn unknown_code(attrs: &Attrs, id: u32, v: &Value) {
let code = v
.as_u32()
.or_else(|| match v {
Value::RefOrCode(_, code) => Some(*code),
_ => u32_at(&raw_bytes(v), 0),
})
.unwrap_or(u32::MAX);
crate::audit::unknown_code(attrs.1, id, code);
crate::audit::unknown_code(attrs.1, id, v.code().unwrap_or(u32::MAX));
}
/// The bytes of a value as stored: list values of two, four or eight bytes
/// are decoded as numbers by the attribute reader.
pub(super) fn raw_bytes(v: &Value) -> Vec<u8> {
match v {
Value::Double(f) => f64_bytes(*f).to_vec(),
Value::Int(i) => i32_bytes(*i).to_vec(),
Value::Enum(e) => u16_bytes(*e).to_vec(),
Value::Ref(r) => u32_bytes(*r).to_vec(),
Value::Point(a, b) => [f64_bytes(*a), f64_bytes(*b)].concat(),
Value::RefOrCode(r, _) => u32_bytes(*r).to_vec(),
Value::Other(_, b) => b.clone(),
}
}
/// Records of a `TabList`: u16 count, then per stop f64 position, u16
/// alignment, u16 leader length and the leader in UTF-16 code units. See
/// `docs/format/attributes.md`. `None` for an unknown alignment code.
pub(super) fn tab_list(data: &[u8]) -> Option<Vec<Vec<Field>>> {
let mut c = Cursor::new(data);
let n = c.u16().ok()?;
let mut out = Vec::new();
for _ in 0..n {
let position = c.f64().ok()?;
let alignment = match c.u16().ok()? {
0 => "LeftAlign",
2 => "RightAlign",
_ => return None,
};
let len = c.u16().ok()? as usize;
let units = (0..len)
.map(|_| c.u16())
.collect::<Result<Vec<_>, _>>()
.ok()?;
out.push(vec![
("Alignment", "enumeration", alignment.to_string()),
("AlignmentCharacter", "string", ".".to_string()),
("Leader", "string", String::from_utf16_lossy(&units)),
("Position", "unit", num(position)),
]);
}
(c.remaining() == 0).then_some(out)
}
/// `BulletChar` attributes: u32 character type, u32 character value.
/// Records of a `TabList`. `None` for an alignment code without evidence.
/// See `docs/format/attributes.md`.
pub(super) fn bullet_char(data: &[u8]) -> Option<PropValue> {
let mut c = Cursor::new(data);
let kind = match c.u32().ok()? {
pub(super) fn tab_list(stops: &[TabStop]) -> Option<Vec<Vec<Field>>> {
stops
.iter()
.map(|t| {
let alignment = match t.alignment {
0 => "LeftAlign",
2 => "RightAlign",
_ => return None,
};
Some(vec![
("Alignment", "enumeration", alignment.to_string()),
("AlignmentCharacter", "string", ".".to_string()),
("Leader", "string", t.leader.clone()),
("Position", "unit", num(t.position)),
])
})
.collect()
}
/// `BulletChar` attributes. See `docs/format/attributes.md`.
pub(super) fn bullet_char(kind: u32, value: u32) -> Option<PropValue> {
let kind = match kind {
0 => "UnicodeOnly",
1 => "UnicodeWithFont",
2 => "GlyphWithFont",
_ => return None,
};
let value = c.u32().ok()?;
(c.remaining() == 0).then(|| {
PropValue::Attributes(vec![
("BulletCharacterType", kind.into()),
("BulletCharacterValue", value.to_string()),
])
})
Some(PropValue::Attributes(vec![
("BulletCharacterType", kind.into()),
("BulletCharacterValue", value.to_string()),
]))
}
/// Delimiter field, repetition and inclusiveness of a nested style's
/// delimiter code (`^c`, or `(d)` / `[d]` followed by an optional count).
/// See `docs/format/attributes.md`.
pub(super) fn nested_delimiter(code: &str) -> Option<(Field, u32, bool)> {
/// The IDML field of a nested style delimiter.
pub(super) fn delimiter_field(d: &Delimiter) -> Field {
let enumeration = |v: &str| ("Delimiter", "enumeration", v.to_string());
if code == "^c" {
return Some((enumeration("Dropcap"), 1, true));
match d {
Delimiter::Dropcap => enumeration("Dropcap"),
Delimiter::AnyWord => enumeration("AnyWord"),
Delimiter::AnyCharacter => enumeration("AnyCharacter"),
Delimiter::Character(c) => ("Delimiter", "string", c.clone()),
}
let (inclusive, close) = match code.chars().next()? {
'(' => (true, ')'),
'[' => (false, ']'),
_ => return None,
};
let end = code.rfind(close)?;
let inner = &code[1..end];
let count = &code[end + 1..];
let repetition = if count.is_empty() {
1
} else {
count.parse().ok()?
};
let delimiter = match inner {
"^w" => enumeration("AnyWord"),
"^?" => enumeration("AnyCharacter"),
_ if inner.chars().count() == 1 && inner != "^" => {
("Delimiter", "string", inner.to_string())
}
_ => return None,
};
Some((delimiter, repetition, inclusive))
}
impl Writer<'_> {
@@ -729,11 +674,20 @@ impl Writer<'_> {
for &(id, name, kind, in_props) in TEXT_ATTRS {
let Some(v) = attrs.get(id) else { continue };
let out: Option<(&'static str, PropValue)> = match kind {
TextKind::TabList => tab_list(&raw_bytes(v)).map(|l| ("list", PropValue::List(l))),
TextKind::NestedStyles => self
.nested_styles(&raw_bytes(v))
.map(|l| ("list", PropValue::List(l))),
TextKind::BulletChar => bullet_char(&raw_bytes(v)).map(|a| ("", a)),
TextKind::TabList => match v {
Value::TabList(stops) => tab_list(stops).map(|l| ("list", PropValue::List(l))),
_ => None,
},
TextKind::NestedStyles => match v {
Value::StyleList {
nested: Some(n), ..
} => Some(("list", PropValue::List(self.nested_styles(n)))),
_ => None,
},
TextKind::BulletChar => match *v {
Value::BulletChar { kind, value } => bullet_char(kind, value).map(|a| ("", a)),
_ => None,
},
_ => self.text_value(kind, v).map(|(t, s)| (t, s.into())),
};
if out.is_none() && matches!(kind, TextKind::Enum(_)) {
@@ -758,11 +712,8 @@ impl Writer<'_> {
.as_f64()
.or(v.as_u32().map(f64::from))
.map(|f| ("unit", num(f))),
TextKind::Point => match raw_bytes(v).as_slice() {
b if b.len() == 16 => {
let f = |o: usize| f64_from(b[o..o + 8].try_into().unwrap());
Some(("unit", nums(&[f(0), f(8)])))
}
TextKind::Point => match *v {
Value::Point(x, y) => Some(("unit", nums(&[x, y]))),
_ => None,
},
TextKind::Percent => v.as_f64().map(|f| ("unit", num(round(f * 100.0)))),
@@ -840,15 +791,10 @@ impl Writer<'_> {
.as_u32()
.filter(|&u| u != 0)
.map(|u| ("long", u.to_string())),
TextKind::Text => {
let b = raw_bytes(v);
let mut c = Cursor::new(&b);
let n = c.u32().ok()? as usize;
c.segments(n)
.ok()
.filter(|t| !t.is_empty())
.map(|t| ("string", t))
}
TextKind::Text => match v {
Value::Text(t) if !t.is_empty() => Some(("string", t.clone())),
_ => None,
},
TextKind::StringOrNothing => v.as_string().map(|s| {
if s.is_empty() {
("enumeration", "Nothing".into())
@@ -861,31 +807,22 @@ impl Writer<'_> {
}
/// Records of an `AllNestedStyles` list. See `docs/format/attributes.md`.
pub(super) fn nested_styles(&self, data: &[u8]) -> Option<Vec<Vec<Field>>> {
let mut c = Cursor::new(data);
let n = c.u32().ok()?;
let mut out = Vec::new();
for _ in 0..n {
let style = c.u32().ok()?;
let len = c.u32().ok()? as usize;
let code = if len == 0 {
String::new()
} else {
c.segments(len).ok()?
};
let (delimiter, repetition, inclusive) = nested_delimiter(&code)?;
out.push(vec![
(
"AppliedCharacterStyle",
"object",
self.style_ref(Some(style).filter(|&u| u != 0), false),
),
delimiter,
("Repetition", "long", repetition.to_string()),
("Inclusive", "boolean", inclusive.to_string()),
]);
}
(c.remaining() == 0).then_some(out)
pub(super) fn nested_styles(&self, styles: &[NestedStyle]) -> Vec<Vec<Field>> {
styles
.iter()
.map(|n| {
vec![
(
"AppliedCharacterStyle",
"object",
self.style_ref(Some(n.style).filter(|&u| u != 0), false),
),
delimiter_field(&n.delimiter),
("Repetition", "long", n.repetition.to_string()),
("Inclusive", "boolean", n.inclusive.to_string()),
]
})
.collect()
}
/// Write page item attributes from the item's attribute list.
@@ -985,18 +922,14 @@ impl Writer<'_> {
.as_u32()
.and_then(|u| map.iter().find(|(k, _)| *k == u))
.map(|(_, n)| n.to_string()),
CellKind::StrokeType => {
let b = raw_bytes(v);
let word = |i: usize| u32_at(&b, i);
match (word(0), word(4)) {
(Some(CELL_NO_STROKE_TYPE), Some(0)) => Some("n".to_string()),
(Some(code), Some(0)) => STROKE_TYPES
.iter()
.find(|(k, _)| *k == code)
.map(|(_, n)| format!("StrokeStyle/$ID/{n}")),
_ => None,
}
}
CellKind::StrokeType => match *v {
Value::Words(CELL_NO_STROKE_TYPE, 0) => Some("n".to_string()),
Value::Words(code, 0) => STROKE_TYPES
.iter()
.find(|(k, _)| *k == code)
.map(|(_, n)| format!("StrokeStyle/$ID/{n}")),
_ => None,
},
CellKind::CellStyle => v.as_u32().and_then(|u| self.cell_style_ref(u)),
}
}
+13 -37
View File
@@ -40,9 +40,7 @@ use crate::model::{
use values::Node;
use xml::Xml;
use crate::object::{
Cursor, f64_bytes, f64_from, i32_bytes, u16_bytes, u16_from, u32_at, u32_bytes,
};
use crate::object::{Cursor, f64_from, u16_from};
const PACKAGING_NS: &str = "http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging";
const MIMETYPE: &str = "application/vnd.adobe.indesign-idml-package";
@@ -424,51 +422,29 @@ mod tests {
}
#[test]
fn decodes_tab_stops() {
// Two stops: 12 pt left aligned, 237.5 pt right aligned with "." leader.
let mut b = 2u16.to_le_bytes().to_vec();
b.extend(12f64.to_le_bytes());
b.extend([0, 0, 0, 0]);
b.extend(237.5f64.to_le_bytes());
b.extend([2, 0, 1, 0, b'.', 0]);
let stops = tab_list(&b).unwrap();
assert_eq!(stops.len(), 2);
fn writes_tab_stops() {
let stop = |position, alignment, leader: &str| crate::model::attrs::TabStop {
position,
alignment,
leader: leader.into(),
};
let stops = tab_list(&[stop(12.0, 0, ""), stop(237.5, 2, ".")]).unwrap();
assert_eq!(stops[0][0].2, "LeftAlign");
assert_eq!(stops[0][3].2, "12");
assert_eq!(stops[1][0].2, "RightAlign");
assert_eq!(stops[1][2].2, ".");
assert_eq!(stops[1][3].2, "237.5");
assert_eq!(tab_list(&[0, 0]).unwrap().len(), 0);
// Unknown alignment code.
let mut b = 1u16.to_le_bytes().to_vec();
b.extend(12f64.to_le_bytes());
b.extend([1, 0, 0, 0]);
assert!(tab_list(&b).is_none());
assert!(tab_list(&[stop(12.0, 1, "")]).is_none());
}
#[test]
fn decodes_nested_style_delimiters() {
let d = |c| nested_delimiter(c).map(|(f, r, i)| (f.1, f.2, r, i));
assert_eq!(d("^c"), Some(("enumeration", "Dropcap".into(), 1, true)));
assert_eq!(d("[.]"), Some(("string", ".".into(), 1, false)));
assert_eq!(d("(:)"), Some(("string", ":".into(), 1, true)));
assert_eq!(d("(^w)5"), Some(("enumeration", "AnyWord".into(), 5, true)));
assert_eq!(
d("(^?)"),
Some(("enumeration", "AnyCharacter".into(), 1, true))
);
assert_eq!(d("(^x)"), None);
assert_eq!(d("^t"), None);
}
#[test]
fn decodes_bullet_char() {
let b = [0, 0, 0, 0, 0x22, 0x20, 0, 0];
let Some(PropValue::Attributes(a)) = bullet_char(&b) else {
panic!("not decoded");
fn writes_bullet_char() {
let Some(PropValue::Attributes(a)) = bullet_char(0, 0x2022) else {
panic!("not written");
};
assert_eq!(a[0].1, "UnicodeOnly");
assert_eq!(a[1].1, "8226");
assert!(bullet_char(&[3, 0, 0, 0, 0x22, 0x20, 0, 0]).is_none());
assert!(bullet_char(3, 0x2022).is_none());
}
}
+1 -4
View File
@@ -640,10 +640,7 @@ impl Writer<'_> {
for _ in 0..32 {
let Some(st) = cur else { break };
if let Some(v) = st.attrs.get(id) {
return match v {
Value::Other(_, b) => b.len() >= 4 && b[..4] != [0, 0, 0, 0],
_ => false,
};
return matches!(v, Value::StyleList { count, .. } if *count != 0);
}
cur = st.based_on.and_then(|b| self.doc.styles.get(&b));
}
+15 -30
View File
@@ -5,7 +5,6 @@ use std::collections::BTreeMap;
use super::num;
use super::xml::Xml;
use crate::model::{Attrs, Value};
use crate::object::{f64_from, u32_at};
#[derive(Clone, Copy)]
enum Kind {
@@ -224,29 +223,23 @@ struct Stop {
midpoint: Option<f64>,
}
/// Opacity stops: u32 count, then per stop f64 location (0–1), f64
/// position of the midpoint to the next stop (0–1, absolute), f64 opacity
/// in percent.
fn stops(data: &[u8]) -> Option<Vec<Stop>> {
let n = u32_at(data, 0)? as usize;
if n == 0 || data.len() != 4 + n * 24 {
return None;
}
let f = |i: usize| f64_from(data[4 + i * 8..12 + i * 8].try_into().unwrap());
// Two stops at the same location leave the midpoint undefined.
if (1..n).any(|i| f(3 * i) == f(3 * (i - 1))) {
/// Opacity stops as IDML writes them, from the stops of the attribute
/// list (location, absolute midpoint position, opacity). `None` for no
/// stops, or two stops at the same location (the midpoint is undefined).
fn stops(raw: &[[f64; 3]]) -> Option<Vec<Stop>> {
if raw.is_empty() || (1..raw.len()).any(|i| raw[i][0] == raw[i - 1][0]) {
return None;
}
Some(
(0..n)
.map(|i| {
let location = f(3 * i);
raw.iter()
.enumerate()
.map(|(i, &[location, _, opacity])| {
let midpoint = (i > 0).then(|| {
let (prev, mid) = (f(3 * (i - 1)), f(3 * (i - 1) + 1));
let [prev, mid, _] = raw[i - 1];
(mid - prev) / (location - prev) * 100.0
});
Stop {
opacity: f(3 * i + 2),
opacity,
location: super::round(location * 100.0),
midpoint,
}
@@ -326,7 +319,7 @@ pub(super) fn write(
.iter()
.find(|(_, s)| *s == setting)
.and_then(|(id, _)| match attrs.get(*id) {
Some(Value::Other(_, data)) => stops(data),
Some(Value::Stops(raw)) => stops(raw),
_ => None,
})
.unwrap_or_default()
@@ -371,14 +364,10 @@ mod tests {
use super::*;
#[test]
fn decodes_opacity_stops() {
fn converts_opacity_stops() {
// Two stops: location 0.15, midpoint at 0.5, opacity 100; location
// 0.85, midpoint 1, opacity 0.
let mut d = 2u32.to_le_bytes().to_vec();
for v in [0.15, 0.5, 100.0, 0.85, 1.0, 0.0f64] {
d.extend_from_slice(&v.to_le_bytes());
}
let s = stops(&d).unwrap();
let s = stops(&[[0.15, 0.5, 100.0], [0.85, 1.0, 0.0]]).unwrap();
assert_eq!(s.len(), 2);
assert_eq!(
(s[0].opacity, s[0].location, s[0].midpoint),
@@ -386,15 +375,11 @@ mod tests {
);
assert_eq!(s[1].location, 85.0);
assert!((s[1].midpoint.unwrap() - 50.0).abs() < 1e-9);
assert_eq!(stops(&0u32.to_le_bytes()), None);
assert_eq!(stops(&[]), None);
}
#[test]
fn stops_at_one_location_are_not_read() {
let mut d = 2u32.to_le_bytes().to_vec();
for v in [0.5, 0.5, 100.0, 0.5, 1.0, 0.0f64] {
d.extend_from_slice(&v.to_le_bytes());
}
assert_eq!(stops(&d), None);
assert_eq!(stops(&[[0.5, 0.5, 100.0], [0.5, 1.0, 0.0]]), None);
}
}
+376 -16
View File
@@ -29,9 +29,94 @@ pub enum Value {
/// A reference followed by a built-in code (value type 0x6E64), as in
/// a stroke type: the reference is 0 for a built-in style.
RefOrCode(u32, u32),
/// Two u32, as in a cell edge stroke type: a code and 0.
Words(u32, u32),
/// A flag byte, then an in-object string.
String(String),
/// u32 length in characters, then text segments.
Text(String),
/// A tab list.
TabList(Vec<TabStop>),
/// A list of nested, line or GREP styles: u32 count, then records.
/// The records are decoded for nested styles only; `nested` is `None`
/// if they cannot be.
StyleList {
count: u32,
nested: Option<Vec<NestedStyle>>,
},
/// u32 bullet character type and u32 character value.
BulletChar {
kind: u32,
value: u32,
},
/// Opacity gradient stops: location (0–1), absolute position of the
/// midpoint to the next stop (0–1), opacity in percent.
Stops(Vec<[f64; 3]>),
/// A value whose layout is not known: its type code and bytes.
Other(u32, Vec<u8>),
}
/// A tab stop. See `docs/format/attributes.md`, tab lists.
#[derive(Debug, Clone, PartialEq)]
pub struct TabStop {
pub position: f64,
/// 0 left, 2 right; other codes have no evidence.
pub alignment: u16,
pub leader: String,
}
/// A nested style: the character style it applies (0 for none) and up to
/// where. See `docs/format/attributes.md`, nested styles.
#[derive(Debug, Clone, PartialEq)]
pub struct NestedStyle {
pub style: u32,
pub delimiter: Delimiter,
pub repetition: u32,
pub inclusive: bool,
}
/// Where a nested style ends.
#[derive(Debug, Clone, PartialEq)]
pub enum Delimiter {
/// `^c`: the drop cap.
Dropcap,
/// `^w`
AnyWord,
/// `^?`
AnyCharacter,
/// A single character.
Character(String),
}
/// Delimiter, repetition and inclusiveness of a nested style's delimiter
/// code: `^c`, or `(d)` / `[d]` followed by an optional count. `None` for
/// codes without evidence. See `docs/format/attributes.md`.
pub fn nested_delimiter(code: &str) -> Option<(Delimiter, u32, bool)> {
if code == "^c" {
return Some((Delimiter::Dropcap, 1, true));
}
let (inclusive, close) = match code.chars().next()? {
'(' => (true, ')'),
'[' => (false, ']'),
_ => return None,
};
let end = code.rfind(close)?;
let inner = &code[1..end];
let count = &code[end + 1..];
let repetition = if count.is_empty() {
1
} else {
count.parse().ok()?
};
let delimiter = match inner {
"^w" => Delimiter::AnyWord,
"^?" => Delimiter::AnyCharacter,
_ if inner.chars().count() == 1 && inner != "^" => Delimiter::Character(inner.to_string()),
_ => return None,
};
Some((delimiter, repetition, inclusive))
}
impl Value {
pub fn as_f64(&self) -> Option<f64> {
match *self {
@@ -59,17 +144,23 @@ impl Value {
}
}
/// A string value: a flag byte, then an in-object string.
/// A string value.
pub fn as_string(&self) -> Option<String> {
match self {
Value::Other(_, b) if b.len() > 1 => {
let mut c = Cursor::new(b);
c.flag().ok()?;
c.string().ok()
}
Value::String(s) => Some(s.clone()),
_ => None,
}
}
/// The code `indd audit` reports for a value without an IDML value:
/// its integer, the code of a reference-or-code or the first of two
/// words.
pub fn code(&self) -> Option<u32> {
match *self {
Value::RefOrCode(_, code) | Value::Words(code, _) => Some(code),
_ => self.as_u32(),
}
}
}
/// Attribute IDs and values, and the kind of list they come from (for
@@ -109,7 +200,7 @@ impl Attrs {
fn records(
c: &mut Cursor,
n: usize,
decode: fn(u32, &[u8]) -> Value,
decode: fn(u32, u32, &[u8]) -> Value,
list: List,
) -> Result<Attrs, Error> {
let mut out = Vec::with_capacity(n.min(1024));
@@ -128,7 +219,7 @@ impl Attrs {
let len = p.u16()? as usize;
let data = p.bytes(len)?;
match (i, &first) {
(0, _) => first = Some(decode(t, data)),
(0, _) => first = Some(decode(id, t, data)),
(1, Some(Value::Ref(r))) if t == ty::CODE && len == 4 => {
let code = u32_from(data.try_into().unwrap());
first = Some(Value::RefOrCode(*r, code));
@@ -145,17 +236,158 @@ impl Attrs {
}
}
fn decode_text(t: u32, data: &[u8]) -> Value {
match data.len() {
8 => Value::Double(f64_from(data.try_into().unwrap())),
4 => Value::Ref(u32_from(data.try_into().unwrap())),
2 => Value::Enum(u16_from(data.try_into().unwrap())),
_ => Value::Other(t, data.to_vec()),
}
/// How the value of a text, table or cell attribute is laid out, for the
/// attributes whose value is not a single number. See
/// `docs/format/attributes.md` and `tables.md`.
#[derive(Clone, Copy)]
enum Layout {
/// Two f64.
Point,
/// A flag byte and an in-object string.
String,
/// u32 length, then text segments.
Text,
TabList,
NestedStyles,
/// Line or GREP styles: u32 count, then records not decoded.
StyleList,
BulletChar,
/// Two u32.
Words,
}
fn decode(t: u32, data: &[u8]) -> Value {
fn text_layout(id: u32) -> Option<Layout> {
Some(match id {
0x1B4A => Layout::Point,
0x1B02 | 0x1A414 | 0x1A423 => Layout::String,
0x422E => Layout::Text,
0x1B29 => Layout::TabList,
0x1B75 => Layout::NestedStyles,
0x1BBA | 0x1BBB => Layout::StyleList,
0x1A406 => Layout::BulletChar,
0xB64D | 0xB64E | 0xB64F | 0xB650 | 0xB688 => Layout::Words,
_ => return None,
})
}
/// A text, table or cell attribute value. Values of the attributes in
/// [`text_layout`] are decoded by their layout (`Other` if they do not
/// fit it); the others are numbers of 8, 4 or 2 bytes.
fn decode_text(id: u32, t: u32, data: &[u8]) -> Value {
let Some(layout) = text_layout(id) else {
return match data.len() {
8 => Value::Double(f64_from(data.try_into().unwrap())),
4 => Value::Ref(u32_from(data.try_into().unwrap())),
2 => Value::Enum(u16_from(data.try_into().unwrap())),
_ => Value::Other(t, data.to_vec()),
};
};
let mut c = Cursor::new(data);
let value = match layout {
Layout::Point if data.len() == 16 => {
(|| Ok::<_, Error>(Value::Point(c.f64()?, c.f64()?)))().ok()
}
Layout::Point => None,
Layout::String => (|| {
c.flag()?;
c.string()
})()
.ok()
.map(Value::String),
Layout::Text => (|| {
let n = c.u32()? as usize;
c.segments(n)
})()
.ok()
.map(Value::Text),
Layout::TabList => tab_list(&mut c).map(Value::TabList),
Layout::NestedStyles | Layout::StyleList => c.u32().ok().map(|count| Value::StyleList {
count,
nested: match layout {
Layout::NestedStyles => nested_styles(&mut Cursor::new(data)),
_ => None,
},
}),
Layout::BulletChar if data.len() == 8 => (|| {
Ok::<_, Error>(Value::BulletChar {
kind: c.u32()?,
value: c.u32()?,
})
})()
.ok(),
Layout::BulletChar => None,
Layout::Words => (|| Ok::<_, Error>(Value::Words(c.u32()?, c.u32()?)))().ok(),
};
value.unwrap_or_else(|| Value::Other(t, data.to_vec()))
}
/// A tab list: u16 count, then per stop f64 position, u16 alignment, u16
/// leader length and the leader in UTF-16 code units. `None` unless the
/// stops fill the value exactly.
fn tab_list(c: &mut Cursor) -> Option<Vec<TabStop>> {
let n = c.u16().ok()?;
let mut out = Vec::new();
for _ in 0..n {
let position = c.f64().ok()?;
let alignment = c.u16().ok()?;
let len = c.u16().ok()? as usize;
let units = (0..len)
.map(|_| c.u16())
.collect::<Result<Vec<_>, _>>()
.ok()?;
out.push(TabStop {
position,
alignment,
leader: String::from_utf16_lossy(&units),
});
}
(c.remaining() == 0).then_some(out)
}
/// Nested styles: u32 count, then per style u32 character style, u32
/// length and the delimiter code as text segments. `None` unless every
/// delimiter is known and the styles fill the value exactly.
fn nested_styles(c: &mut Cursor) -> Option<Vec<NestedStyle>> {
let n = c.u32().ok()?;
let mut out = Vec::new();
for _ in 0..n {
let style = c.u32().ok()?;
let len = c.u32().ok()? as usize;
let code = if len == 0 {
String::new()
} else {
c.segments(len).ok()?
};
let (delimiter, repetition, inclusive) = nested_delimiter(&code)?;
out.push(NestedStyle {
style,
delimiter,
repetition,
inclusive,
});
}
(c.remaining() == 0).then_some(out)
}
/// Page item attributes whose value is a list of opacity gradient stops:
/// u32 count, then three f64 per stop. See `docs/format/transparency.md`.
pub const OPACITY_STOPS: [u32; 3] = [0x1EB8C, 0x1EB95, 0x1EB9E];
fn decode(id: u32, t: u32, data: &[u8]) -> Value {
let f64_at = |o: usize| f64_from(data[o..o + 8].try_into().unwrap());
if OPACITY_STOPS.contains(&id)
&& let Some(n) = data
.get(..4)
.map(|b| u32_from(b.try_into().unwrap()) as usize)
&& n > 0
&& data.len() == 4 + n * 24
{
return Value::Stops(
(0..n)
.map(|i| [0, 1, 2].map(|k| f64_at(4 + (3 * i + k) * 8)))
.collect(),
);
}
match (t, data.len()) {
(ty::DOUBLE, 8) => Value::Double(f64_at(0)),
(ty::INT, 4) => Value::Int(i32_from(data.try_into().unwrap())),
@@ -208,4 +440,132 @@ mod tests {
let a = Attrs::parse(&d, List::Item).unwrap();
assert_eq!(a.get(0x6E6E), Some(&Value::RefOrCode(0, 0x5A39)));
}
/// One text attribute record: ID, then a single value of type 0.
fn text_record(id: u32, value: &[u8]) -> Vec<u8> {
let mut d = id.to_le_bytes().to_vec();
d.extend_from_slice(&(8 + value.len() as u16).to_le_bytes());
d.extend_from_slice(&1u16.to_le_bytes());
d.extend_from_slice(&0u32.to_le_bytes());
d.extend_from_slice(&(value.len() as u16).to_le_bytes());
d.extend_from_slice(value);
d
}
fn text_value(id: u32, value: &[u8]) -> Value {
let d = text_record(id, value);
let a = Attrs::parse_text(&mut Cursor::new(&d), 1, List::Text).unwrap();
a.get(id).unwrap().clone()
}
#[test]
fn decodes_tab_stops() {
// Two stops: 12 pt left aligned, 237.5 pt right aligned with "." leader.
let mut b = 2u16.to_le_bytes().to_vec();
b.extend(12f64.to_le_bytes());
b.extend([0, 0, 0, 0]);
b.extend(237.5f64.to_le_bytes());
b.extend([2, 0, 1, 0, b'.', 0]);
let Value::TabList(stops) = text_value(0x1B29, &b) else {
panic!("not a tab list");
};
assert_eq!(stops.len(), 2);
assert_eq!((stops[0].position, stops[0].alignment), (12.0, 0));
assert_eq!(
(
stops[1].position,
stops[1].alignment,
stops[1].leader.as_str()
),
(237.5, 2, ".")
);
assert_eq!(text_value(0x1B29, &[0, 0]), Value::TabList(Vec::new()));
// A stop cut short.
assert!(matches!(text_value(0x1B29, &b[..20]), Value::Other(..)));
}
#[test]
fn decodes_nested_style_delimiters() {
let d = |c| nested_delimiter(c);
assert_eq!(d("^c"), Some((Delimiter::Dropcap, 1, true)));
assert_eq!(d("[.]"), Some((Delimiter::Character(".".into()), 1, false)));
assert_eq!(d("(:)"), Some((Delimiter::Character(":".into()), 1, true)));
assert_eq!(d("(^w)5"), Some((Delimiter::AnyWord, 5, true)));
assert_eq!(d("(^?)"), Some((Delimiter::AnyCharacter, 1, true)));
assert_eq!(d("(^x)"), None);
assert_eq!(d("^t"), None);
}
#[test]
fn decodes_nested_styles() {
// One style: character style 7 up to and including 2 words.
let mut b = 1u32.to_le_bytes().to_vec();
b.extend(7u32.to_le_bytes());
b.extend(5u32.to_le_bytes());
b.extend([5, 0x40, b'(', b'^', b'w', b')', b'2']);
let nested = vec![NestedStyle {
style: 7,
delimiter: Delimiter::AnyWord,
repetition: 2,
inclusive: true,
}];
assert_eq!(
text_value(0x1B75, &b),
Value::StyleList {
count: 1,
nested: Some(nested)
}
);
// GREP styles: only the count is read.
assert_eq!(
text_value(0x1BBA, &b),
Value::StyleList {
count: 1,
nested: None
}
);
}
#[test]
fn decodes_bullet_chars_and_strings() {
let b = [0, 0, 0, 0, 0x22, 0x20, 0, 0];
assert_eq!(
text_value(0x1A406, &b),
Value::BulletChar {
kind: 0,
value: 0x2022
}
);
// Font style: flag byte, then an in-object string.
let b = [0, 2, 0, 4, 0, 4, 0x40, b'B', b'o', b'l', b'd'];
assert_eq!(text_value(0x1B02, &b), Value::String("Bold".into()));
// Ruby text: u32 length, then segments.
let b = [2, 0, 0, 0, 2, 0x40, b'a', b'b'];
assert_eq!(text_value(0x422E, &b), Value::Text("ab".into()));
// Other attributes are numbers by length.
assert_eq!(
text_value(0x1B03, &12f64.to_le_bytes()),
Value::Double(12.0)
);
}
#[test]
fn decodes_opacity_stops() {
let mut v = 2u32.to_le_bytes().to_vec();
for f in [0.15, 0.5, 100.0, 0.85, 1.0, 0.0f64] {
v.extend(f.to_le_bytes());
}
let mut d = 1u32.to_le_bytes().to_vec();
d.extend(0x1EB8Cu32.to_le_bytes());
d.extend((8 + v.len() as u16).to_le_bytes());
d.extend(1u16.to_le_bytes());
d.extend(0u32.to_le_bytes());
d.extend((v.len() as u16).to_le_bytes());
d.extend(&v);
let a = Attrs::parse(&d, List::Item).unwrap();
assert_eq!(
a.get(0x1EB8C),
Some(&Value::Stops(vec![[0.15, 0.5, 100.0], [0.85, 1.0, 0.0]]))
);
}
}