mirror of
https://github.com/storytold/indd-utils.git
synced 2026-11-26 04:12:04 +01:00
refactor: carry the byte order and string tag in an Encoding instead of thread-locals
Add indd::convert, convert_file and convert_into, which return the IDML package and typed warnings and keep no thread-local state.
This commit is contained in:
1 parent
01044d4c65
commit
bd9ee4490d
26 files changed
+717
-509
No files matched your search
+3
-4
@@ -14,7 +14,7 @@
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
|
||||
use crate::{Container, Error, object};
|
||||
use crate::{Container, Error};
|
||||
|
||||
/// Kinds of attribute lists, by where the converter parses them. IDs mean
|
||||
/// different things in different kinds, so they are counted per kind.
|
||||
@@ -173,15 +173,14 @@ pub struct Audit {
|
||||
/// Convert `indd` (output discarded) and report what was not read.
|
||||
pub fn audit(indd: &[u8], name: &str) -> Result<Audit, Error> {
|
||||
let recorder = Recorder::start();
|
||||
let result = crate::convert(indd, name, std::io::sink());
|
||||
let result = crate::convert_into(indd, name, std::io::sink());
|
||||
let log = recorder.take();
|
||||
|
||||
let container = Container::parse(indd)?;
|
||||
let _order = object::use_byte_order(container.header.byte_order);
|
||||
let db = container.database()?;
|
||||
let mut out = Audit::default();
|
||||
match result {
|
||||
Ok(w) => out.warnings = w,
|
||||
Ok(w) => out.warnings = w.into_iter().map(|w| w.to_string()).collect(),
|
||||
Err(e) => out.error = Some(e.to_string()),
|
||||
}
|
||||
for uid in db.uids() {
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::container::PAGE_SIZE;
|
||||
use crate::object::Encoding;
|
||||
use crate::{Container, Error};
|
||||
|
||||
/// Page types, from the u32 at 0xFF4 of every database page.
|
||||
@@ -77,6 +78,8 @@ pub struct Database<'a> {
|
||||
classes: Vec<(u32, u32)>,
|
||||
/// UIDs listed in the third tree. They have no class entry.
|
||||
unclassed: Vec<u32>,
|
||||
/// The encoding of object data.
|
||||
encoding: Encoding,
|
||||
}
|
||||
|
||||
fn corrupt(msg: impl Into<String>) -> Error {
|
||||
@@ -92,6 +95,7 @@ impl<'a> Database<'a> {
|
||||
entries: Vec::new(),
|
||||
classes: Vec::new(),
|
||||
unclassed: Vec::new(),
|
||||
encoding: Encoding::of(&container.header),
|
||||
};
|
||||
let directory = db.u32(master + MASTER_LOGICAL_DIR)?;
|
||||
let db_pages = container.master().db_pages;
|
||||
@@ -318,9 +322,15 @@ impl<'a> Database<'a> {
|
||||
uid,
|
||||
class: self.class_of(uid),
|
||||
bytes,
|
||||
encoding: self.encoding,
|
||||
}))
|
||||
}
|
||||
|
||||
/// The encoding of object data in this database.
|
||||
pub fn encoding(&self) -> Encoding {
|
||||
self.encoding
|
||||
}
|
||||
|
||||
/// The complete byte stream of object `uid`, or `None` if it doesn't exist.
|
||||
pub fn object(&self, uid: u32) -> Result<Option<Vec<u8>>, Error> {
|
||||
let start = self.entries.partition_point(|e| e.uid < uid);
|
||||
@@ -381,6 +391,7 @@ pub(crate) mod synthetic {
|
||||
entries,
|
||||
classes,
|
||||
unclassed: Vec::new(),
|
||||
encoding: Encoding::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -439,6 +450,7 @@ mod tests {
|
||||
entries: Vec::new(),
|
||||
classes: Vec::new(),
|
||||
unclassed: Vec::new(),
|
||||
encoding: Encoding::default(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+87
-8
@@ -2,6 +2,32 @@
|
||||
//!
|
||||
//! The format is undocumented. Everything this crate knows about it is
|
||||
//! recorded in `docs/format/`; see `CLEANROOM.md` for how it was learned.
|
||||
//!
|
||||
//! The main entry points convert an INDD file to IDML:
|
||||
//!
|
||||
//! ```no_run
|
||||
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
//! let conversion = indd::convert_file("brochure.indd")?;
|
||||
//! std::fs::write("brochure.idml", &conversion.idml)?;
|
||||
//! for warning in &conversion.warnings {
|
||||
//! eprintln!("warning: {warning}");
|
||||
//! }
|
||||
//! # Ok(())
|
||||
//! # }
|
||||
//! ```
|
||||
//!
|
||||
//! Bytes that are not an INDD file give an error:
|
||||
//!
|
||||
//! ```
|
||||
//! let bytes = vec![0u8; 4096];
|
||||
//! let err = indd::convert(&bytes, "empty.indd").unwrap_err();
|
||||
//! assert!(matches!(err, indd::Error::NotIndd));
|
||||
//! ```
|
||||
//!
|
||||
//! A conversion keeps no global or thread-local state, so documents can be
|
||||
//! converted on several threads at once. Lower layers are public for tools
|
||||
//! that inspect files: [`Header`], [`Container`], [`Database`], [`Object`]
|
||||
//! and the [`model`].
|
||||
|
||||
pub mod audit;
|
||||
pub mod container;
|
||||
@@ -14,7 +40,7 @@ pub mod object;
|
||||
pub use container::{Container, ContigObject, MasterPage};
|
||||
pub use database::{Database, Entry};
|
||||
pub use header::{ByteOrder, Header, Version};
|
||||
pub use object::{Chunk, Cursor, Object};
|
||||
pub use object::{Chunk, Cursor, Encoding, Object};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
@@ -102,16 +128,69 @@ pub fn read_header(path: impl AsRef<std::path::Path>) -> Result<Header, Error> {
|
||||
Header::parse(&buf[..got])
|
||||
}
|
||||
|
||||
/// Convert INDD bytes to an IDML package written to `out`. `name` is the
|
||||
/// document name recorded in the package (normally the INDD file name).
|
||||
/// Returns warnings about content that could not be converted.
|
||||
pub fn convert(indd: &[u8], name: &str, out: impl std::io::Write) -> Result<Vec<String>, Error> {
|
||||
/// A problem that did not stop a conversion: content that was left out
|
||||
/// or could not be converted exactly.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Warning {
|
||||
message: String,
|
||||
}
|
||||
|
||||
impl Warning {
|
||||
pub fn message(&self) -> &str {
|
||||
&self.message
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Warning {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(&self.message)
|
||||
}
|
||||
}
|
||||
|
||||
/// The result of a conversion: the IDML package and the warnings.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Conversion {
|
||||
/// The IDML package (a ZIP file).
|
||||
pub idml: Vec<u8>,
|
||||
pub warnings: Vec<Warning>,
|
||||
}
|
||||
|
||||
/// Convert INDD bytes to an IDML package. `name` is the document name the
|
||||
/// package records (normally the INDD file name).
|
||||
///
|
||||
/// The conversion keeps no state outside its own call, so documents can
|
||||
/// be converted on several threads at once.
|
||||
pub fn convert(indd: &[u8], name: &str) -> Result<Conversion, Error> {
|
||||
let mut idml = Vec::new();
|
||||
let warnings = convert_into(indd, name, &mut idml)?;
|
||||
Ok(Conversion { idml, warnings })
|
||||
}
|
||||
|
||||
/// Convert the INDD file at `path`. The package records the file name as
|
||||
/// the document name.
|
||||
pub fn convert_file(path: impl AsRef<std::path::Path>) -> Result<Conversion, Error> {
|
||||
let path = path.as_ref();
|
||||
let indd = std::fs::read(path)?;
|
||||
let name = path
|
||||
.file_name()
|
||||
.map_or_else(|| path.to_string_lossy(), |n| n.to_string_lossy());
|
||||
convert(&indd, &name)
|
||||
}
|
||||
|
||||
/// Convert INDD bytes to an IDML package written to `out`, and return the
|
||||
/// warnings. See [`convert`].
|
||||
pub fn convert_into(
|
||||
indd: &[u8],
|
||||
name: &str,
|
||||
out: impl std::io::Write,
|
||||
) -> Result<Vec<Warning>, Error> {
|
||||
let container = Container::parse(indd)?;
|
||||
let _order = object::use_byte_order(container.header.byte_order);
|
||||
let _tag = object::use_string_tag(object::string_tag_for(container.header.version));
|
||||
let db = container.database()?;
|
||||
let doc = model::Reader::new(&db).document(container.header.version)?;
|
||||
let mut warnings = doc.warnings.clone();
|
||||
warnings.extend(idml::write(&doc, name, out)?);
|
||||
Ok(warnings)
|
||||
Ok(warnings
|
||||
.into_iter()
|
||||
.map(|message| Warning { message })
|
||||
.collect())
|
||||
}
|
||||
+1
-3
@@ -271,8 +271,6 @@ fn parse_uid(s: &str) -> Result<u32, Box<dyn std::error::Error>> {
|
||||
fn dump(path: &str, uids: &[u32], limit: usize) -> CliResult {
|
||||
let bytes = std::fs::read(path)?;
|
||||
let c = indd::Container::parse(&bytes)?;
|
||||
let _order = indd::object::use_byte_order(c.header.byte_order);
|
||||
let _tag = indd::object::use_string_tag(indd::object::string_tag_for(c.header.version));
|
||||
let db = c.database()?;
|
||||
let mut out = std::io::stdout().lock();
|
||||
for &uid in uids {
|
||||
@@ -317,7 +315,7 @@ fn convert(input: &str, output: &str) -> CliResult {
|
||||
.file_name()
|
||||
.map_or_else(|| input.to_string(), |n| n.to_string_lossy().into_owned());
|
||||
let file = std::io::BufWriter::new(std::fs::File::create(output)?);
|
||||
for warning in indd::convert(&bytes, &name, file)? {
|
||||
for warning in indd::convert_into(&bytes, &name, file)? {
|
||||
eprintln!("warning: {warning}");
|
||||
}
|
||||
Ok(())
|
||||
|
||||
+30
-29
@@ -6,7 +6,7 @@
|
||||
|
||||
use crate::Error;
|
||||
use crate::audit::{self, List};
|
||||
use crate::object::{Cursor, f64_from, i32_from, u16_from, u32_from};
|
||||
use crate::object::{Cursor, Encoding};
|
||||
|
||||
/// Value type codes.
|
||||
pub mod ty {
|
||||
@@ -178,15 +178,15 @@ impl Attrs {
|
||||
}
|
||||
|
||||
/// A page item list (chunk 0x6E03): u32 count, then records.
|
||||
pub fn parse(data: &[u8], list: List) -> Result<Attrs, Error> {
|
||||
let mut c = Cursor::new(data);
|
||||
pub fn parse(enc: Encoding, data: &[u8], list: List) -> Result<Attrs, Error> {
|
||||
let mut c = enc.cursor(data);
|
||||
let n = c.u32()? as usize;
|
||||
Attrs::records(&mut c, n, decode, list)
|
||||
}
|
||||
|
||||
/// A page item attribute list with a u16 count, as object styles hold.
|
||||
pub fn parse_short(data: &[u8], list: List) -> Result<Attrs, Error> {
|
||||
let mut c = Cursor::new(data);
|
||||
pub fn parse_short(enc: Encoding, data: &[u8], list: List) -> Result<Attrs, Error> {
|
||||
let mut c = enc.cursor(data);
|
||||
let n = c.u16()? as usize;
|
||||
Attrs::records(&mut c, n, decode, list)
|
||||
}
|
||||
@@ -200,14 +200,15 @@ impl Attrs {
|
||||
fn records(
|
||||
c: &mut Cursor,
|
||||
n: usize,
|
||||
decode: fn(u32, u32, &[u8]) -> Value,
|
||||
decode: fn(Encoding, u32, u32, &[u8]) -> Value,
|
||||
list: List,
|
||||
) -> Result<Attrs, Error> {
|
||||
let enc = c.encoding();
|
||||
let mut out = Vec::with_capacity(n.min(1024));
|
||||
for _ in 0..n {
|
||||
let id = c.u32()?;
|
||||
let size = c.u16()? as usize;
|
||||
let mut p = Cursor::new(c.bytes(size)?);
|
||||
let mut p = enc.cursor(c.bytes(size)?);
|
||||
// A record without values (for example a merged-cell marker).
|
||||
if size < 2 {
|
||||
continue;
|
||||
@@ -219,9 +220,9 @@ impl Attrs {
|
||||
let len = p.u16()? as usize;
|
||||
let data = p.bytes(len)?;
|
||||
match (i, &first) {
|
||||
(0, _) => first = Some(decode(id, t, data)),
|
||||
(0, _) => first = Some(decode(enc, id, t, data)),
|
||||
(1, Some(Value::Ref(r))) if t == ty::CODE && len == 4 => {
|
||||
let code = u32_from(data.try_into().unwrap());
|
||||
let code = enc.u32_from(data.try_into().unwrap());
|
||||
first = Some(Value::RefOrCode(*r, code));
|
||||
}
|
||||
_ => {}
|
||||
@@ -273,16 +274,16 @@ fn text_layout(id: u32) -> Option<Layout> {
|
||||
/// 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 {
|
||||
fn decode_text(enc: Encoding, 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())),
|
||||
8 => Value::Double(enc.f64_from(data.try_into().unwrap())),
|
||||
4 => Value::Ref(enc.u32_from(data.try_into().unwrap())),
|
||||
2 => Value::Enum(enc.u16_from(data.try_into().unwrap())),
|
||||
_ => Value::Other(t, data.to_vec()),
|
||||
};
|
||||
};
|
||||
let mut c = Cursor::new(data);
|
||||
let mut c = enc.cursor(data);
|
||||
let value = match layout {
|
||||
Layout::Point if data.len() == 16 => {
|
||||
(|| Ok::<_, Error>(Value::Point(c.f64()?, c.f64()?)))().ok()
|
||||
@@ -304,7 +305,7 @@ fn decode_text(id: u32, t: u32, data: &[u8]) -> Value {
|
||||
Layout::NestedStyles | Layout::StyleList => c.u32().ok().map(|count| Value::StyleList {
|
||||
count,
|
||||
nested: match layout {
|
||||
Layout::NestedStyles => nested_styles(&mut Cursor::new(data)),
|
||||
Layout::NestedStyles => nested_styles(&mut enc.cursor(data)),
|
||||
_ => None,
|
||||
},
|
||||
}),
|
||||
@@ -373,30 +374,30 @@ fn nested_styles(c: &mut Cursor) -> Option<Vec<NestedStyle>> {
|
||||
/// 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());
|
||||
fn decode(enc: Encoding, id: u32, t: u32, data: &[u8]) -> Value {
|
||||
let f = |o: usize| enc.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)
|
||||
.map(|b| enc.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)))
|
||||
.map(|i| [0, 1, 2].map(|k| f(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())),
|
||||
(ty::ENUM, 2) => Value::Enum(u16_from(data.try_into().unwrap())),
|
||||
(ty::REF, 4) => Value::Ref(u32_from(data.try_into().unwrap())),
|
||||
(ty::POINT, 16) => Value::Point(f64_at(0), f64_at(8)),
|
||||
(ty::DOUBLE, 8) => Value::Double(f(0)),
|
||||
(ty::INT, 4) => Value::Int(enc.i32_from(data.try_into().unwrap())),
|
||||
(ty::ENUM, 2) => Value::Enum(enc.u16_from(data.try_into().unwrap())),
|
||||
(ty::REF, 4) => Value::Ref(enc.u32_from(data.try_into().unwrap())),
|
||||
(ty::POINT, 16) => Value::Point(f(0), f(8)),
|
||||
// Other 4-byte types are references or codes (for example a
|
||||
// corner effect ID); keep the number.
|
||||
(_, 4) => Value::Ref(u32_from(data.try_into().unwrap())),
|
||||
(_, 4) => Value::Ref(enc.u32_from(data.try_into().unwrap())),
|
||||
_ => Value::Other(t, data.to_vec()),
|
||||
}
|
||||
}
|
||||
@@ -418,7 +419,7 @@ mod tests {
|
||||
d.extend_from_slice(&0x6E63u32.to_le_bytes());
|
||||
d.extend_from_slice(&6u16.to_le_bytes());
|
||||
d.extend_from_slice(&[0; 6]);
|
||||
let a = Attrs::parse(&d, List::Item).unwrap();
|
||||
let a = Attrs::parse(Encoding::default(), &d, List::Item).unwrap();
|
||||
assert_eq!(a.get(0x6E65), Some(&Value::Double(0.25)));
|
||||
}
|
||||
|
||||
@@ -437,7 +438,7 @@ mod tests {
|
||||
d.extend_from_slice(&0x6E63u32.to_le_bytes());
|
||||
d.extend_from_slice(&6u16.to_le_bytes());
|
||||
d.extend_from_slice(&[0; 6]);
|
||||
let a = Attrs::parse(&d, List::Item).unwrap();
|
||||
let a = Attrs::parse(Encoding::default(), &d, List::Item).unwrap();
|
||||
assert_eq!(a.get(0x6E6E), Some(&Value::RefOrCode(0, 0x5A39)));
|
||||
}
|
||||
|
||||
@@ -454,7 +455,7 @@ mod tests {
|
||||
|
||||
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();
|
||||
let a = Attrs::parse_text(&mut Encoding::default().cursor(&d), 1, List::Text).unwrap();
|
||||
a.get(id).unwrap().clone()
|
||||
}
|
||||
|
||||
@@ -562,7 +563,7 @@ mod tests {
|
||||
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();
|
||||
let a = Attrs::parse(Encoding::default(), &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]]))
|
||||
|
||||
+10
-7
@@ -2,7 +2,7 @@
|
||||
//! See `docs/format/fonts.md` and `docs/format/objects.md`.
|
||||
|
||||
use crate::Error;
|
||||
use crate::object::{Cursor, u16_from};
|
||||
use crate::object::Cursor;
|
||||
|
||||
pub mod class {
|
||||
pub const COMPOSITE_FONT: u32 = 0xCB02;
|
||||
@@ -71,10 +71,11 @@ impl CompositeFontEntry {
|
||||
/// Chunk 0xCB03: name, u32 font family, font style, four f64, u16 1,
|
||||
/// u16 range count, ranges (first, last, first), four u16.
|
||||
pub fn read(uid: u32, obj: &crate::Object) -> Result<Option<CompositeFontEntry>, Error> {
|
||||
let enc = obj.encoding;
|
||||
let Some(d) = obj.chunk(chunk::COMPOSITE_FONT_ENTRY) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut c = Cursor::new(d);
|
||||
let mut c = enc.cursor(d);
|
||||
let name = flagged_name(&mut c)?;
|
||||
let font_family = c.u32()?;
|
||||
let font_style = flagged_name(&mut c)?;
|
||||
@@ -114,19 +115,20 @@ impl CompositeFont {
|
||||
/// the entry UIDs, which end the chunk. Returns the name and the
|
||||
/// entry UIDs.
|
||||
pub fn read(obj: &crate::Object) -> Result<Option<(String, Vec<u32>)>, Error> {
|
||||
let enc = obj.encoding;
|
||||
let Some(d) = obj.chunk(chunk::COMPOSITE_FONT) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut c = Cursor::new(d);
|
||||
let mut c = enc.cursor(d);
|
||||
let name = flagged_name(&mut c)?;
|
||||
let start = c.pos();
|
||||
let Some(p) = (start..d.len().saturating_sub(1)).find(|&p| {
|
||||
let n = u16_from([d[p], d[p + 1]]) as usize;
|
||||
let n = enc.u16_from([d[p], d[p + 1]]) as usize;
|
||||
n > 0 && p + 2 + 4 * n == d.len()
|
||||
}) else {
|
||||
return Ok(Some((name, Vec::new())));
|
||||
};
|
||||
let mut c = Cursor::new(&d[p..]);
|
||||
let mut c = enc.cursor(&d[p..]);
|
||||
let n = c.u16()?;
|
||||
let entries = (0..n).map(|_| c.u32()).collect::<Result<Vec<_>, _>>()?;
|
||||
Ok(Some((name, entries)))
|
||||
@@ -147,13 +149,14 @@ pub struct CjkTable {
|
||||
|
||||
impl CjkTable {
|
||||
pub fn read(uid: u32, cls: u32, obj: &crate::Object) -> Result<Option<CjkTable>, Error> {
|
||||
let enc = obj.encoding;
|
||||
let Some(d) = obj.chunk(chunk::TABLE_NAME) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let name = flagged_name(&mut Cursor::new(d))?;
|
||||
let name = flagged_name(&mut enc.cursor(d))?;
|
||||
let chars = match obj.chunk(chunk::KINSOKU_CHARS) {
|
||||
Some(d) if cls == class::CUSTOM_KINSOKU => {
|
||||
let mut c = Cursor::new(d);
|
||||
let mut c = enc.cursor(d);
|
||||
let counts = [c.u16()?, c.u16()?, c.u16()?, c.u16()?, c.u16()?];
|
||||
let mut lists: [String; 5] = Default::default();
|
||||
for (list, n) in lists.iter_mut().zip(counts) {
|
||||
|
||||
+81
-77
@@ -1,7 +1,6 @@
|
||||
//! Colours and swatches. See `docs/format/objects.md`.
|
||||
|
||||
use crate::Error;
|
||||
use crate::object::Cursor;
|
||||
|
||||
pub mod class {
|
||||
pub const COLOR: u32 = 0x1F05;
|
||||
@@ -87,19 +86,20 @@ impl Gradient {
|
||||
}
|
||||
|
||||
pub fn read(uid: u32, obj: &crate::Object) -> Result<Option<Gradient>, Error> {
|
||||
let enc = obj.encoding;
|
||||
let (Some(stops), Some(name)) = (
|
||||
obj.chunk(chunk::GRADIENT_STOPS),
|
||||
obj.chunk(chunk::GRADIENT_NAME),
|
||||
) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut c = Cursor::new(stops);
|
||||
let mut c = enc.cursor(stops);
|
||||
let n = c.u16()? as usize;
|
||||
let colors = (0..n).map(|_| c.u32()).collect::<Result<Vec<_>, _>>()?;
|
||||
let locations = (0..n).map(|_| c.f64()).collect::<Result<Vec<_>, _>>()?;
|
||||
let midpoints = (0..n).map(|_| c.f64()).collect::<Result<Vec<_>, _>>()?;
|
||||
let kind = c.u32()?;
|
||||
let mut nc = Cursor::new(name);
|
||||
let mut nc = enc.cursor(name);
|
||||
let builtin_name = nc.flag()? == 1;
|
||||
let name = nc.string()?;
|
||||
let flags = nc.u32()?;
|
||||
@@ -135,6 +135,7 @@ pub struct Tint {
|
||||
|
||||
impl Tint {
|
||||
pub fn read(uid: u32, obj: &crate::Object) -> Result<Option<Tint>, Error> {
|
||||
let enc = obj.encoding;
|
||||
if obj.chunk(chunk::COLOR_NAME).is_some() {
|
||||
return Ok(None);
|
||||
}
|
||||
@@ -144,8 +145,8 @@ impl Tint {
|
||||
) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let base = Cursor::new(base).u32()?;
|
||||
let mut c = Cursor::new(tint);
|
||||
let base = enc.cursor(base).u32()?;
|
||||
let mut c = enc.cursor(tint);
|
||||
let value = c.f64()?;
|
||||
let color_override = c.u32()?;
|
||||
if base == 0 || value < 0.0 {
|
||||
@@ -302,12 +303,13 @@ impl Color {
|
||||
}
|
||||
|
||||
pub fn read(uid: u32, obj: &crate::Object) -> Result<Option<Color>, Error> {
|
||||
let enc = obj.encoding;
|
||||
let (Some(name), Some(value)) =
|
||||
(obj.chunk(chunk::COLOR_NAME), obj.chunk(chunk::COLOR_VALUE))
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut c = Cursor::new(name);
|
||||
let mut c = enc.cursor(name);
|
||||
let builtin_name = c.flag()? == 1;
|
||||
let name_str = c.string()?;
|
||||
let flags = c.u32()?;
|
||||
@@ -320,7 +322,7 @@ impl Color {
|
||||
.transpose()?;
|
||||
let alternate = match obj.chunk(chunk::COLOR_ALTERNATE) {
|
||||
Some(d) => {
|
||||
let mut a = Cursor::new(d);
|
||||
let mut a = enc.cursor(d);
|
||||
let space = a.u32()?;
|
||||
let n = a.u16()?;
|
||||
Some((
|
||||
@@ -330,7 +332,7 @@ impl Color {
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let mut v = Cursor::new(value);
|
||||
let mut v = enc.cursor(value);
|
||||
let space = match v.u32()? {
|
||||
5 => Space::Rgb,
|
||||
6 => Space::Cmyk,
|
||||
@@ -341,11 +343,11 @@ impl Color {
|
||||
let n = v.u16()?;
|
||||
let values = (0..n).map(|_| v.f64()).collect::<Result<Vec<_>, _>>()?;
|
||||
let model = match obj.chunk(chunk::COLOR_MODEL) {
|
||||
Some(d) => Cursor::new(d).u32()?,
|
||||
Some(d) => enc.cursor(d).u32()?,
|
||||
None => 0,
|
||||
};
|
||||
let color_override = match obj.chunk(chunk::COLOR_OVERRIDE) {
|
||||
Some(d) if d.len() >= 12 => Cursor::new(&d[8..]).u32()?,
|
||||
Some(d) if d.len() >= 12 => enc.cursor(&d[8..]).u32()?,
|
||||
_ => 0,
|
||||
};
|
||||
Ok(Some(Color {
|
||||
@@ -377,6 +379,75 @@ impl Color {
|
||||
}
|
||||
}
|
||||
|
||||
/// An ink (class 0x1F07). Chunk 0x1F0D: flag byte and name, then fields
|
||||
/// at offsets from the end of the name: f64 neutral density at 14, u32
|
||||
/// trap order − 1 at 26, f64 frequency at 32, f64 angle at 40.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Ink {
|
||||
pub uid: u32,
|
||||
/// The IDML name, with `$ID/` for a built-in name.
|
||||
pub name: String,
|
||||
/// `None` when the stored value is outside the 0.001–10 the IDML
|
||||
/// schema allows (−1 in some files; `objects.md`).
|
||||
pub neutral_density: Option<f64>,
|
||||
pub trap_order: u32,
|
||||
pub frequency: f64,
|
||||
pub angle: f64,
|
||||
}
|
||||
|
||||
impl Ink {
|
||||
pub fn read(uid: u32, obj: &crate::Object) -> Result<Option<Ink>, Error> {
|
||||
let enc = obj.encoding;
|
||||
let Some(d) = obj.chunk(chunk::INK) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut c = enc.cursor(d);
|
||||
let builtin = c.flag()? == 1;
|
||||
let name = c.string()?;
|
||||
let end = c.pos();
|
||||
if d.len() < end + 48 {
|
||||
return Ok(None);
|
||||
}
|
||||
let f = |o: usize| enc.cursor(&d[end + o..]).f64();
|
||||
Ok(Some(Ink {
|
||||
uid,
|
||||
name: if builtin { format!("$ID/{name}") } else { name },
|
||||
neutral_density: Some(f(14)?).filter(|v| (0.001..=10.0).contains(v)),
|
||||
trap_order: enc.cursor(&d[end + 26..]).u32()? + 1,
|
||||
frequency: f(32)?,
|
||||
angle: f(40)?,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
/// A colour group (class 0x1F39): chunk 0x13C is a flag byte and the name,
|
||||
/// chunk 0x1F60 a UID list of its swatches.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ColorGroup {
|
||||
pub uid: u32,
|
||||
pub name: String,
|
||||
pub swatches: Vec<u32>,
|
||||
}
|
||||
|
||||
impl ColorGroup {
|
||||
pub fn read(uid: u32, obj: &crate::Object) -> Result<Option<ColorGroup>, Error> {
|
||||
let enc = obj.encoding;
|
||||
let Some(d) = obj.chunk(chunk::COLOR_GROUP_NAME) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let name = enc.cursor(&d[1.min(d.len())..]).string()?;
|
||||
let swatches = match obj.chunk(chunk::COLOR_GROUP_SWATCHES) {
|
||||
Some(d) => enc.cursor(d).u32_list()?,
|
||||
None => Vec::new(),
|
||||
};
|
||||
Ok(Some(ColorGroup {
|
||||
uid,
|
||||
name,
|
||||
swatches,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -449,70 +520,3 @@ mod tests {
|
||||
assert_eq!(g.idml_midpoint(3), None);
|
||||
}
|
||||
}
|
||||
|
||||
/// An ink (class 0x1F07). Chunk 0x1F0D: flag byte and name, then fields
|
||||
/// at offsets from the end of the name: f64 neutral density at 14, u32
|
||||
/// trap order − 1 at 26, f64 frequency at 32, f64 angle at 40.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Ink {
|
||||
pub uid: u32,
|
||||
/// The IDML name, with `$ID/` for a built-in name.
|
||||
pub name: String,
|
||||
/// `None` when the stored value is outside the 0.001–10 the IDML
|
||||
/// schema allows (−1 in some files; `objects.md`).
|
||||
pub neutral_density: Option<f64>,
|
||||
pub trap_order: u32,
|
||||
pub frequency: f64,
|
||||
pub angle: f64,
|
||||
}
|
||||
|
||||
impl Ink {
|
||||
pub fn read(uid: u32, obj: &crate::Object) -> Result<Option<Ink>, Error> {
|
||||
let Some(d) = obj.chunk(chunk::INK) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut c = Cursor::new(d);
|
||||
let builtin = c.flag()? == 1;
|
||||
let name = c.string()?;
|
||||
let end = c.pos();
|
||||
if d.len() < end + 48 {
|
||||
return Ok(None);
|
||||
}
|
||||
let f = |o: usize| Cursor::new(&d[end + o..]).f64();
|
||||
Ok(Some(Ink {
|
||||
uid,
|
||||
name: if builtin { format!("$ID/{name}") } else { name },
|
||||
neutral_density: Some(f(14)?).filter(|v| (0.001..=10.0).contains(v)),
|
||||
trap_order: Cursor::new(&d[end + 26..]).u32()? + 1,
|
||||
frequency: f(32)?,
|
||||
angle: f(40)?,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
/// A colour group (class 0x1F39): chunk 0x13C is a flag byte and the name,
|
||||
/// chunk 0x1F60 a UID list of its swatches.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ColorGroup {
|
||||
pub uid: u32,
|
||||
pub name: String,
|
||||
pub swatches: Vec<u32>,
|
||||
}
|
||||
|
||||
impl ColorGroup {
|
||||
pub fn read(uid: u32, obj: &crate::Object) -> Result<Option<ColorGroup>, Error> {
|
||||
let Some(d) = obj.chunk(chunk::COLOR_GROUP_NAME) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let name = Cursor::new(&d[1.min(d.len())..]).string()?;
|
||||
let swatches = match obj.chunk(chunk::COLOR_GROUP_SWATCHES) {
|
||||
Some(d) => Cursor::new(d).u32_list()?,
|
||||
None => Vec::new(),
|
||||
};
|
||||
Ok(Some(ColorGroup {
|
||||
uid,
|
||||
name,
|
||||
swatches,
|
||||
}))
|
||||
}
|
||||
}
|
||||
@@ -135,7 +135,7 @@ impl<'a> Reader<'a> {
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let active_layer = self
|
||||
.chunk(DOC, chunk::DOC_ACTIVE_LAYER)?
|
||||
.map(|d| Cursor::new(&d).u32())
|
||||
.map(|d| self.cursor(&d).u32())
|
||||
.transpose()?;
|
||||
let (spreads, master_spreads) = self.document_spreads()?;
|
||||
let stories = self.document_stories()?;
|
||||
@@ -168,7 +168,7 @@ impl<'a> Reader<'a> {
|
||||
.map(|uid| self.section(uid))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let bookmark_order = match self.chunk(DOC, hyperlink::chunk::DOCUMENT_LISTS)? {
|
||||
Some(d) => hyperlink::document_bookmarks(&d, version.major)?,
|
||||
Some(d) => hyperlink::document_bookmarks(self.enc(), &d, version.major)?,
|
||||
None => Vec::new(),
|
||||
};
|
||||
let composite_fonts = objects
|
||||
@@ -267,7 +267,7 @@ impl<'a> Reader<'a> {
|
||||
fn xml_story(&self) -> Result<Option<Story>, Error> {
|
||||
Ok(match self.chunk(DOC, xml::chunk::NODE_REF)? {
|
||||
Some(d) if d.len() >= 4 => {
|
||||
let s = Cursor::new(&d).u32()?;
|
||||
let s = self.cursor(&d).u32()?;
|
||||
match self.class(s) {
|
||||
Some(class::STORY) => Some(self.story(s)?),
|
||||
_ => None,
|
||||
@@ -478,7 +478,7 @@ impl<'a> Reader<'a> {
|
||||
Ok(match self.chunk(uid, font::chunk::FAMILY)? {
|
||||
Some(d) => Some(FontFamily {
|
||||
uid,
|
||||
name: find_string(&d, 0)?,
|
||||
name: find_string(self.enc(), &d, 0)?,
|
||||
fonts: Vec::new(),
|
||||
writing_script: 0,
|
||||
}),
|
||||
@@ -544,20 +544,20 @@ impl<'a> Reader<'a> {
|
||||
let Some(d) = self.chunk(uid, chunk::XML_TAG_NAME)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut c = Cursor::new(&d);
|
||||
let mut c = self.cursor(&d);
|
||||
let n = c.u32()? as usize;
|
||||
// Files from InDesign 2.0 to 4.0 hold a flag byte and an in-object
|
||||
// string instead.
|
||||
let name = match c.segments(n) {
|
||||
Ok(name) => name,
|
||||
Err(_) => {
|
||||
let mut c = Cursor::new(&d);
|
||||
let mut c = self.cursor(&d);
|
||||
c.flag()?;
|
||||
c.string()?
|
||||
}
|
||||
};
|
||||
let color = match self.chunk(uid, chunk::XML_TAG_COLOR)? {
|
||||
Some(d) if d.len() >= 4 => self.ui_color(Cursor::new(&d).u32()?)?,
|
||||
Some(d) if d.len() >= 4 => self.ui_color(self.cursor(&d).u32()?)?,
|
||||
_ => None,
|
||||
};
|
||||
Ok(Some((name, color)))
|
||||
|
||||
+20
-11
@@ -1,7 +1,7 @@
|
||||
//! Font families (class 0x3E03). See `docs/format/fonts.md`.
|
||||
|
||||
use crate::Error;
|
||||
use crate::object::{Cursor, Object};
|
||||
use crate::object::{Encoding, Object};
|
||||
|
||||
pub mod chunk {
|
||||
/// Family name and font records.
|
||||
@@ -54,14 +54,14 @@ impl FontFamily {
|
||||
};
|
||||
// Files from InDesign 3.0 and 4.0 use older font records; one is
|
||||
// taken only if it reads the chunk to its end.
|
||||
let mut family = match parse(uid, data, Record::Current) {
|
||||
let mut family = match parse(obj.encoding, uid, data, Record::Current) {
|
||||
Ok(f) => f,
|
||||
Err(e) => parse(uid, data, Record::Version4)
|
||||
.or_else(|_| parse(uid, data, Record::Version3))
|
||||
Err(e) => parse(obj.encoding, uid, data, Record::Version4)
|
||||
.or_else(|_| parse(obj.encoding, uid, data, Record::Version3))
|
||||
.map_err(|_| e)?,
|
||||
};
|
||||
if let Some(ids) = obj.chunk(chunk::TYPEKIT_IDS) {
|
||||
for (font, id) in family.fonts.iter_mut().zip(typekit_ids(ids)?) {
|
||||
for (font, id) in family.fonts.iter_mut().zip(typekit_ids(obj.encoding, ids)?) {
|
||||
font.typekit_id = id;
|
||||
}
|
||||
}
|
||||
@@ -81,8 +81,8 @@ enum Record {
|
||||
|
||||
/// Chunk 0x3E05: u8, u16, name, u8, native name, 6 bytes, u16 font count,
|
||||
/// font records, u32 writing script.
|
||||
fn parse(uid: u32, data: &[u8], record: Record) -> Result<FontFamily, Error> {
|
||||
let mut c = Cursor::new(data);
|
||||
fn parse(enc: Encoding, uid: u32, data: &[u8], record: Record) -> Result<FontFamily, Error> {
|
||||
let mut c = enc.cursor(data);
|
||||
c.skip(3)?;
|
||||
let name = c.string()?;
|
||||
c.skip(1)?;
|
||||
@@ -141,8 +141,8 @@ fn parse(uid: u32, data: &[u8], record: Record) -> Result<FontFamily, Error> {
|
||||
|
||||
/// Chunk 0x3EEB: u32 count, then per font a flag byte (1 = `$ID/` key)
|
||||
/// and a string.
|
||||
fn typekit_ids(data: &[u8]) -> Result<Vec<String>, Error> {
|
||||
let mut c = Cursor::new(data);
|
||||
fn typekit_ids(enc: Encoding, data: &[u8]) -> Result<Vec<String>, Error> {
|
||||
let mut c = enc.cursor(data);
|
||||
let n = c.u32()?;
|
||||
let mut out = Vec::new();
|
||||
for _ in 0..n {
|
||||
@@ -187,7 +187,13 @@ mod tests {
|
||||
d.extend(0x400Bu16.to_le_bytes());
|
||||
d.extend(b"Version 2.1");
|
||||
d.extend(1u32.to_le_bytes());
|
||||
let f = parse(0x9E, &d, Record::Current).unwrap();
|
||||
let f = parse(
|
||||
crate::object::Encoding::default(),
|
||||
0x9E,
|
||||
&d,
|
||||
Record::Current,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(f.name, "Myriad Pro");
|
||||
assert_eq!(f.writing_script, 1);
|
||||
let font = &f.fonts[0];
|
||||
@@ -205,6 +211,9 @@ mod tests {
|
||||
d.extend(string(""));
|
||||
d.push(0);
|
||||
d.extend(string("TkD-1-ab"));
|
||||
assert_eq!(typekit_ids(&d).unwrap(), ["$ID/", "TkD-1-ab"]);
|
||||
assert_eq!(
|
||||
typekit_ids(crate::object::Encoding::default(), &d).unwrap(),
|
||||
["$ID/", "TkD-1-ab"]
|
||||
);
|
||||
}
|
||||
}
|
||||
+23
-15
@@ -4,7 +4,7 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::Error;
|
||||
use crate::object::{Cursor, Object};
|
||||
use crate::object::{Cursor, Encoding, Object};
|
||||
|
||||
pub mod class {
|
||||
pub const HYPERLINK: u32 = 0x13501;
|
||||
@@ -130,10 +130,11 @@ const SAMPLE_APPEARANCE: &[[u8; 18]] = &[
|
||||
|
||||
impl Hyperlink {
|
||||
pub fn read(uid: u32, obj: &Object) -> Result<Option<Hyperlink>, Error> {
|
||||
let enc = obj.encoding;
|
||||
let Some(d) = obj.chunk(chunk::HYPERLINK) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut c = Cursor::new(d);
|
||||
let mut c = enc.cursor(d);
|
||||
let source = c.u32()?;
|
||||
c.skip(2)?;
|
||||
let hidden = c.u16()? != 0;
|
||||
@@ -158,16 +159,17 @@ impl Hyperlink {
|
||||
|
||||
impl TextSource {
|
||||
pub fn read(uid: u32, obj: &Object) -> Result<Option<TextSource>, Error> {
|
||||
let enc = obj.encoding;
|
||||
let Some(d) = obj.chunk(chunk::TEXT_SOURCE) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut c = Cursor::new(d);
|
||||
let mut c = enc.cursor(d);
|
||||
let hidden = c.u8()? != 0;
|
||||
c.skip(5)?;
|
||||
let name = flagged_string(&mut c)?;
|
||||
let character_style = match obj.chunk(chunk::TEXT_SOURCE_RANGE) {
|
||||
Some(r) => {
|
||||
let mut c = Cursor::new(r);
|
||||
let mut c = enc.cursor(r);
|
||||
c.skip(8)?;
|
||||
Some(c.u32()?).filter(|&s| s != 0)
|
||||
}
|
||||
@@ -185,6 +187,7 @@ impl TextSource {
|
||||
|
||||
impl Destination {
|
||||
pub fn read(uid: u32, class: u32, obj: &Object) -> Result<Option<Destination>, Error> {
|
||||
let enc = obj.encoding;
|
||||
let id = if class == class::PAGE_DESTINATION {
|
||||
chunk::PAGE_DESTINATION
|
||||
} else {
|
||||
@@ -193,7 +196,7 @@ impl Destination {
|
||||
let Some(d) = obj.chunk(id) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut c = Cursor::new(d);
|
||||
let mut c = enc.cursor(d);
|
||||
let hidden = c.u8()? != 0;
|
||||
c.skip(1)?;
|
||||
let name = flagged_string(&mut c)?;
|
||||
@@ -202,14 +205,14 @@ impl Destination {
|
||||
let Some(v) = obj.chunk(chunk::PAGE_DESTINATION_VIEW) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut c = Cursor::new(v);
|
||||
let mut c = enc.cursor(v);
|
||||
let page = c.u32()?;
|
||||
let zoom = Some(c.f64()?).filter(|z| (0.05..=40.0).contains(z));
|
||||
let view = c.u32()?;
|
||||
DestinationKind::Page { page, zoom, view }
|
||||
} else {
|
||||
let url = match obj.chunk(chunk::URL) {
|
||||
Some(u) => flagged_string(&mut Cursor::new(u))?,
|
||||
Some(u) => flagged_string(&mut enc.cursor(u))?,
|
||||
None => name.clone(),
|
||||
};
|
||||
DestinationKind::Url { url }
|
||||
@@ -226,10 +229,11 @@ impl Destination {
|
||||
|
||||
impl Bookmark {
|
||||
pub fn read(uid: u32, obj: &Object) -> Result<Option<Bookmark>, Error> {
|
||||
let enc = obj.encoding;
|
||||
let Some(d) = obj.chunk(chunk::BOOKMARK) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut c = Cursor::new(d);
|
||||
let mut c = enc.cursor(d);
|
||||
let name = flagged_string(&mut c)?;
|
||||
c.skip(4)?;
|
||||
let parent = c.u32()?;
|
||||
@@ -249,8 +253,8 @@ impl Bookmark {
|
||||
/// u16, then UID lists of text sources, hyperlinks and bookmarks. In 3.0
|
||||
/// to 5.0 files: UID lists of text sources, destinations, hyperlinks and
|
||||
/// bookmarks (`docs/format/hyperlinks.md`).
|
||||
pub fn document_bookmarks(data: &[u8], major: u32) -> Result<Vec<u32>, Error> {
|
||||
let mut c = Cursor::new(data);
|
||||
pub fn document_bookmarks(enc: Encoding, data: &[u8], major: u32) -> Result<Vec<u32>, Error> {
|
||||
let mut c = enc.cursor(data);
|
||||
if major <= 5 {
|
||||
for _ in 0..3 {
|
||||
c.u32_list()?;
|
||||
@@ -284,8 +288,8 @@ struct Node {
|
||||
|
||||
/// Read the nodes of one range tree page (chunk 0x16127) into `nodes`, by
|
||||
/// node index. Returns the next page's UID (0 for none).
|
||||
fn read_page(data: &[u8], nodes: &mut BTreeMap<u32, Node>) -> Result<u32, Error> {
|
||||
let mut c = Cursor::new(data);
|
||||
fn read_page(enc: Encoding, data: &[u8], nodes: &mut BTreeMap<u32, Node>) -> Result<u32, Error> {
|
||||
let mut c = enc.cursor(data);
|
||||
let next = c.u32()?;
|
||||
c.skip(12)?;
|
||||
let n = c.u32()? as usize;
|
||||
@@ -298,7 +302,7 @@ fn read_page(data: &[u8], nodes: &mut BTreeMap<u32, Node>) -> Result<u32, Error>
|
||||
if class != class::RANGE_NODE || size != 60 {
|
||||
continue;
|
||||
}
|
||||
let mut b = Cursor::new(body);
|
||||
let mut b = enc.cursor(body);
|
||||
b.skip(12)?;
|
||||
let mut refs = [0u32; 4];
|
||||
for r in &mut refs {
|
||||
@@ -327,6 +331,7 @@ fn read_page(data: &[u8], nodes: &mut BTreeMap<u32, Node>) -> Result<u32, Error>
|
||||
/// its parent, a right child `value` after it; the root's value is its
|
||||
/// start.
|
||||
pub fn source_ranges(
|
||||
enc: Encoding,
|
||||
first_page: u32,
|
||||
mut page_data: impl FnMut(u32) -> Result<Option<Vec<u8>>, Error>,
|
||||
) -> Result<Vec<SourceRange>, Error> {
|
||||
@@ -336,7 +341,7 @@ pub fn source_ranges(
|
||||
while page != 0 && !seen.contains(&page) {
|
||||
seen.push(page);
|
||||
let Some(data) = page_data(page)? else { break };
|
||||
page = read_page(&data, &mut nodes)?;
|
||||
page = read_page(enc, &data, &mut nodes)?;
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let roots: Vec<u32> = nodes
|
||||
@@ -410,7 +415,10 @@ mod tests {
|
||||
page.extend(node(2, 1, 0, 0, 138, 22, 0xA));
|
||||
page.extend(node(0, 2, 1, 3, 260, 38, 0xB));
|
||||
page.extend(node(2, 3, 0, 0, 120, 15, 0xC));
|
||||
let ranges = source_ranges(7, |_| Ok(Some(page.clone()))).unwrap();
|
||||
let ranges = source_ranges(crate::object::Encoding::default(), 7, |_| {
|
||||
Ok(Some(page.clone()))
|
||||
})
|
||||
.unwrap();
|
||||
let got: Vec<_> = ranges.iter().map(|r| (r.start, r.len, r.source)).collect();
|
||||
assert_eq!(got, [(122, 22, 0xA), (260, 38, 0xB), (380, 15, 0xC)]);
|
||||
}
|
||||
|
||||
+45
-45
@@ -276,7 +276,7 @@ impl<'a> Reader<'a> {
|
||||
if d.len() < 48 {
|
||||
return Ok(Some(None));
|
||||
}
|
||||
let Matrix([a, b, c, dd, _, _]) = Matrix::read(&mut Cursor::new(&d))?;
|
||||
let Matrix([a, b, c, dd, _, _]) = Matrix::read(&mut self.cursor(&d))?;
|
||||
Ok(Some(match [a, b, c, dd] {
|
||||
[1.0, 0.0, 0.0, 1.0] => Some(Orientation::Horizontal),
|
||||
[0.0, 1.0, -1.0, 0.0] => Some(Orientation::Vertical),
|
||||
@@ -301,25 +301,25 @@ impl<'a> Reader<'a> {
|
||||
return Ok(None);
|
||||
}
|
||||
let minimum_sizes = (just.len() >= 48).then(|| {
|
||||
let flag = |at| u16_at(&just, at).is_some_and(|v| v != 0);
|
||||
let flag = |at| self.enc().u16_at(&just, at).is_some_and(|v| v != 0);
|
||||
(
|
||||
[flag(26), flag(36)],
|
||||
[
|
||||
f64_at(&just, 28).unwrap_or(0.0),
|
||||
f64_at(&just, 38).unwrap_or(0.0),
|
||||
self.enc().f64_at(&just, 28).unwrap_or(0.0),
|
||||
self.enc().f64_at(&just, 38).unwrap_or(0.0),
|
||||
],
|
||||
flag(46),
|
||||
)
|
||||
});
|
||||
let column_rule = match self.chunk(mcf, chunk::FRAME_COLUMN_RULE)? {
|
||||
Some(d) => match (f64_at(&d, 28), u32_at(&d, 36)) {
|
||||
Some(d) => match (self.enc().f64_at(&d, 28), self.enc().u32_at(&d, 36)) {
|
||||
(Some(w), Some(c)) => Some((w, c)),
|
||||
_ => None,
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
let footnotes = match self.chunk(mcf, chunk::FRAME_FOOTNOTES)? {
|
||||
Some(d) => match (f64_at(&d, 4), f64_at(&d, 12)) {
|
||||
Some(d) => match (self.enc().f64_at(&d, 4), self.enc().f64_at(&d, 12)) {
|
||||
(Some(a), Some(b)) => Some([a, b]),
|
||||
_ => None,
|
||||
},
|
||||
@@ -329,30 +329,30 @@ impl<'a> Reader<'a> {
|
||||
// right, bottom.
|
||||
let inset = match self.chunk(frame, chunk::FRAME_INSET)? {
|
||||
Some(d) if d.len() >= 44 => {
|
||||
let f = |at| f64_at(&d, at).unwrap_or(0.0);
|
||||
let f = |at| self.enc().f64_at(&d, at).unwrap_or(0.0);
|
||||
[f(20), f(12), f(36), f(28)]
|
||||
}
|
||||
_ => [0.0; 4],
|
||||
};
|
||||
Ok(Some(TextFramePreferences {
|
||||
column_count: Cursor::new(&cols).u32()?,
|
||||
column_gutter: Cursor::new(&cols[4..]).f64()?,
|
||||
column_fixed_width: Cursor::new(&cols[14..]).f64()?,
|
||||
first_baseline_offset: Cursor::new(&just).u16()?,
|
||||
vertical_justification: Cursor::new(&just[2..]).u16()?,
|
||||
vertical_balance_columns: Cursor::new(&just[20..]).u16()? != 0,
|
||||
auto_sizing_type: Cursor::new(&just[22..]).u16()?,
|
||||
auto_sizing_reference_point: Cursor::new(&just[24..]).u16()?,
|
||||
column_count: self.cursor(&cols).u32()?,
|
||||
column_gutter: self.cursor(&cols[4..]).f64()?,
|
||||
column_fixed_width: self.cursor(&cols[14..]).f64()?,
|
||||
first_baseline_offset: self.cursor(&just).u16()?,
|
||||
vertical_justification: self.cursor(&just[2..]).u16()?,
|
||||
vertical_balance_columns: self.cursor(&just[20..]).u16()? != 0,
|
||||
auto_sizing_type: self.cursor(&just[22..]).u16()?,
|
||||
auto_sizing_reference_point: self.cursor(&just[24..]).u16()?,
|
||||
use_fixed_width: cols.get(12).is_some_and(|&b| b != 0),
|
||||
max_width: if cols.len() >= 40 {
|
||||
f64_at(&cols, 32)
|
||||
self.enc().f64_at(&cols, 32)
|
||||
} else {
|
||||
None
|
||||
},
|
||||
minimum_sizes,
|
||||
ignore_wrap: self
|
||||
.chunk(mcf, chunk::FRAME_IGNORE_WRAP)?
|
||||
.and_then(|d| u16_at(&d, 0))
|
||||
.and_then(|d| self.enc().u16_at(&d, 0))
|
||||
.map(|v| v != 0),
|
||||
column_rule,
|
||||
column_rule_override: self
|
||||
@@ -372,7 +372,7 @@ impl<'a> Reader<'a> {
|
||||
};
|
||||
let name = match self.chunk(uid, name_chunk)? {
|
||||
Some(d) => {
|
||||
let mut c = Cursor::new(&d);
|
||||
let mut c = self.cursor(&d);
|
||||
let builtin = c.flag()? == 1;
|
||||
Some(ItemName {
|
||||
builtin,
|
||||
@@ -385,7 +385,7 @@ impl<'a> Reader<'a> {
|
||||
let Some(d) = self.chunk(uid, id)? else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let mut c = Cursor::new(&d);
|
||||
let mut c = self.cursor(&d);
|
||||
let n = c.u32()? as usize;
|
||||
if n > d.len() / 8 {
|
||||
return Err(Error::Corrupt(format!("item {uid}: {n} change counts")));
|
||||
@@ -394,7 +394,7 @@ impl<'a> Reader<'a> {
|
||||
};
|
||||
let overridden = match self.chunk(uid, chunk::ITEM_OVERRIDE)? {
|
||||
Some(d) => {
|
||||
let mut c = Cursor::new(&d);
|
||||
let mut c = self.cursor(&d);
|
||||
let master = c.u32()?;
|
||||
Some((master, c.u32_list()?))
|
||||
}
|
||||
@@ -404,10 +404,10 @@ impl<'a> Reader<'a> {
|
||||
name,
|
||||
hidden: self
|
||||
.chunk(uid, chunk::ITEM_VISIBLE)?
|
||||
.is_some_and(|d| d.len() >= 2 && Cursor::new(&d).u16().ok() == Some(0)),
|
||||
.is_some_and(|d| d.len() >= 2 && self.cursor(&d).u16().ok() == Some(0)),
|
||||
locked: self
|
||||
.chunk(uid, chunk::ITEM_LOCKED)?
|
||||
.is_some_and(|d| d.len() >= 4 && Cursor::new(&d).u32().ok() == Some(1)),
|
||||
.is_some_and(|d| d.len() >= 4 && self.cursor(&d).u32().ok() == Some(1)),
|
||||
layout_constraints: self
|
||||
.chunk(uid, chunk::ITEM_LAYOUT_CONSTRAINTS)?
|
||||
.and_then(|d| d.first().copied()),
|
||||
@@ -419,7 +419,7 @@ impl<'a> Reader<'a> {
|
||||
overridden,
|
||||
graphic_frame: self
|
||||
.chunk(uid, chunk::ITEM_CONTENT)?
|
||||
.is_some_and(|d| d.len() >= 2 && Cursor::new(&d).u16().ok() == Some(1)),
|
||||
.is_some_and(|d| d.len() >= 2 && self.cursor(&d).u16().ok() == Some(1)),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -437,7 +437,7 @@ impl<'a> Reader<'a> {
|
||||
if d.len() < 44 {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut c = Cursor::new(&d);
|
||||
let mut c = self.cursor(&d);
|
||||
let mode = c.u32()?;
|
||||
c.skip(4)?;
|
||||
let offsets = [c.f64()?, c.f64()?, c.f64()?, c.f64()?];
|
||||
@@ -461,7 +461,7 @@ impl<'a> Reader<'a> {
|
||||
let Some(data) = self.chunk(uid, chunk::ITEM_PATHS)? else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let mut c = Cursor::new(&data);
|
||||
let mut c = self.cursor(&data);
|
||||
let n = c.u32()?;
|
||||
let mut paths = Vec::new();
|
||||
for _ in 0..n {
|
||||
@@ -545,10 +545,10 @@ impl<'a> Reader<'a> {
|
||||
) -> Result<Option<PageItem>, Error> {
|
||||
// Groups without chunk 0x151 have their transform in chunk 0x40D.
|
||||
let transform = match self.chunk(uid, chunk::ITEM_TRANSFORM)? {
|
||||
Some(d) => Matrix::read(&mut Cursor::new(&d))?,
|
||||
Some(d) => Matrix::read(&mut self.cursor(&d))?,
|
||||
None => match self.chunk(uid, chunk::GROUP_TRANSFORM)? {
|
||||
Some(d) if cls == Some(class::GROUP) && d.len() >= 48 => {
|
||||
Matrix::read(&mut Cursor::new(&d))?
|
||||
Matrix::read(&mut self.cursor(&d))?
|
||||
}
|
||||
_ => Matrix::IDENTITY,
|
||||
},
|
||||
@@ -575,11 +575,11 @@ impl<'a> Reader<'a> {
|
||||
}
|
||||
let paths = self.paths(uid)?;
|
||||
let attrs = match self.chunk(uid, chunk::ITEM_ATTRS)? {
|
||||
Some(d) => Attrs::parse(&d, List::Item).unwrap_or_default(),
|
||||
Some(d) => Attrs::parse(self.enc(), &d, List::Item).unwrap_or_default(),
|
||||
None => Attrs::default(),
|
||||
};
|
||||
let object_style = match self.chunk(uid, chunk::ITEM_OBJECT_STYLE)? {
|
||||
Some(d) => uid_or_none(Cursor::new(&d).u32()?),
|
||||
Some(d) => uid_or_none(self.cursor(&d).u32()?),
|
||||
None => None,
|
||||
};
|
||||
let kind = if cls == Some(class::GROUP) {
|
||||
@@ -605,7 +605,7 @@ impl<'a> Reader<'a> {
|
||||
} else {
|
||||
let code = self
|
||||
.chunk(uid, chunk::ITEM_SHAPE)?
|
||||
.and_then(|d| u32_at(&d, 2));
|
||||
.and_then(|d| self.enc().u32_at(&d, 2));
|
||||
ItemKind::Shape(classify(&paths, code))
|
||||
};
|
||||
Ok(Some(PageItem {
|
||||
@@ -636,18 +636,18 @@ impl<'a> Reader<'a> {
|
||||
_ => return Ok(None),
|
||||
};
|
||||
let transform = match self.chunk(uid, chunk::ITEM_TRANSFORM)? {
|
||||
Some(d) => Matrix::read(&mut Cursor::new(&d))?,
|
||||
Some(d) => Matrix::read(&mut self.cursor(&d))?,
|
||||
None => Matrix::IDENTITY,
|
||||
};
|
||||
let bounds = match self.chunk(uid, chunk::GRAPHIC_BOUNDS)? {
|
||||
Some(d) => {
|
||||
let mut c = Cursor::new(&d);
|
||||
let mut c = self.cursor(&d);
|
||||
[c.f64()?, c.f64()?, c.f64()?, c.f64()?]
|
||||
}
|
||||
None => [0.0; 4],
|
||||
};
|
||||
let link = match self.chunk(uid, chunk::GRAPHIC_LINK)? {
|
||||
Some(d) if d.len() >= 12 => self.link(Cursor::new(&d[8..]).u32()?)?,
|
||||
Some(d) if d.len() >= 12 => self.link(self.cursor(&d[8..]).u32()?)?,
|
||||
_ => None,
|
||||
};
|
||||
let (link, contents) = match link {
|
||||
@@ -660,7 +660,7 @@ impl<'a> Reader<'a> {
|
||||
};
|
||||
let data = match id {
|
||||
Some(id) => match self.chunk(uid, id)? {
|
||||
Some(d) if d.len() >= 4 => self.raw_data(Cursor::new(&d).u32()?)?,
|
||||
Some(d) if d.len() >= 4 => self.raw_data(self.cursor(&d).u32()?)?,
|
||||
_ => None,
|
||||
},
|
||||
None => None,
|
||||
@@ -677,25 +677,25 @@ impl<'a> Reader<'a> {
|
||||
contents,
|
||||
text_wrap: self.text_wrap(uid)?,
|
||||
contour_type: match self.chunk(uid, chunk::CONTOUR_OPTION)? {
|
||||
Some(d) if d.len() >= 4 => Some(Cursor::new(&d).u32()?),
|
||||
Some(d) if d.len() >= 4 => Some(self.cursor(&d).u32()?),
|
||||
_ => None,
|
||||
},
|
||||
clipping: match self.chunk(uid, chunk::CLIPPING_PATH)? {
|
||||
Some(d) if d.len() >= 26 => {
|
||||
let f = |o: usize| Cursor::new(&d[o..]).f64();
|
||||
let f = |o: usize| self.cursor(&d[o..]).f64();
|
||||
Some(ClippingPath {
|
||||
kind: Cursor::new(&d).u32()?,
|
||||
kind: self.cursor(&d).u32()?,
|
||||
tolerance: f(4)?,
|
||||
inset: f(12)?,
|
||||
threshold: d[20],
|
||||
index: i16_from([d[23], d[24]]),
|
||||
index: self.enc().i16_from([d[23], d[24]]),
|
||||
high_resolution: d[25],
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
},
|
||||
photoshop_clipping: match self.chunk(uid, chunk::PHOTOSHOP_CLIPPING)? {
|
||||
Some(d) if d.len() >= 2 => Some(Cursor::new(&d).u16()?),
|
||||
Some(d) if d.len() >= 2 => Some(self.cursor(&d).u16()?),
|
||||
_ => None,
|
||||
},
|
||||
}))
|
||||
@@ -722,10 +722,10 @@ impl<'a> Reader<'a> {
|
||||
if info.len() < 12 {
|
||||
return Ok(None);
|
||||
}
|
||||
let resource = Cursor::new(&info[8..]).u32()?;
|
||||
let resource = self.cursor(&info[8..]).u32()?;
|
||||
let (uri, data) = match self.chunk(resource, chunk::LINK_RESOURCE_URI)? {
|
||||
Some(d) if d.len() >= 5 => {
|
||||
let mut c = Cursor::new(&d);
|
||||
let mut c = self.cursor(&d);
|
||||
c.u8()?;
|
||||
let n = c.u32()? as usize;
|
||||
let uri = String::from_utf8_lossy(c.bytes(n.min(c.remaining()))?).into_owned();
|
||||
@@ -760,11 +760,11 @@ impl<'a> Reader<'a> {
|
||||
let Some(d) = self.chunk(column, chunk::COLUMN_FRAME_LIST)? else {
|
||||
return Ok(none);
|
||||
};
|
||||
let list = Cursor::new(&d).u32()?;
|
||||
let list = self.cursor(&d).u32()?;
|
||||
let Some(d) = self.chunk(list, chunk::FRAME_LIST_FRAMES)? else {
|
||||
return Ok(none);
|
||||
};
|
||||
let mut c = Cursor::new(&d);
|
||||
let mut c = self.cursor(&d);
|
||||
let story = uid_or_none(c.u32()?);
|
||||
let columns = c.u32_list()?;
|
||||
// Columns belong to frames: column -> multi-column frame -> spline item.
|
||||
@@ -772,11 +772,11 @@ impl<'a> Reader<'a> {
|
||||
let Some(h) = self.chunk(col, chunk::ITEM_HIERARCHY)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mcf = Cursor::new(&h[4..]).u32()?;
|
||||
let mcf = self.cursor(&h[4..]).u32()?;
|
||||
let Some(h) = self.chunk(mcf, chunk::ITEM_HIERARCHY)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(uid_or_none(Cursor::new(&h[4..]).u32()?))
|
||||
Ok(uid_or_none(self.cursor(&h[4..]).u32()?))
|
||||
};
|
||||
let mut frames: Vec<u32> = Vec::new();
|
||||
for col in columns.iter().copied() {
|
||||
|
||||
+1
-1
@@ -49,7 +49,7 @@ pub use variable::TextVariable;
|
||||
pub use xref::CrossReferenceFormat;
|
||||
|
||||
use crate::audit::List;
|
||||
use crate::object::{Cursor, Object, f64_at, i16_from, u16_at, u16_from, u32_at, u32_from};
|
||||
use crate::object::{Cursor, Encoding, Object};
|
||||
use crate::{Database, Error, Version};
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+30
-27
@@ -5,7 +5,7 @@
|
||||
use super::{Attrs, Reader, chunk, class};
|
||||
use crate::Error;
|
||||
use crate::audit::List;
|
||||
use crate::object::{Cursor, big_endian};
|
||||
use crate::object::{Cursor, Encoding};
|
||||
|
||||
/// A value for an element of `Resources/Preferences.xml` or a document
|
||||
/// setting in `designmap.xml`.
|
||||
@@ -56,6 +56,7 @@ fn flagged(c: &mut Cursor) -> Result<(u8, String), Error> {
|
||||
/// Print settings (chunk 0xA4C, and 0xAF2 for booklets): see
|
||||
/// `docs/format/preferences.md`, print preferences.
|
||||
fn print_prefs(
|
||||
enc: Encoding,
|
||||
d: &[u8],
|
||||
element: &'static str,
|
||||
values: &mut Vec<PrefValue>,
|
||||
@@ -69,7 +70,7 @@ fn print_prefs(
|
||||
value,
|
||||
})
|
||||
};
|
||||
let mut c = Cursor::new(d);
|
||||
let mut c = enc.cursor(d);
|
||||
let has_record = c.u8()? != 0;
|
||||
c.u8()?;
|
||||
let n = c.u32()? as usize;
|
||||
@@ -137,18 +138,18 @@ fn print_prefs(
|
||||
props.push((element, "PaperSize", PrefProp::Text(ty, text)));
|
||||
}
|
||||
let q = c.pos();
|
||||
let f = |o: usize| Cursor::new(&d[q + o..]).f64();
|
||||
let f = |o: usize| enc.cursor(&d[q + o..]).f64();
|
||||
set("PaperWidthRange", format!("{} {}", num(f(8)?), num(f(16)?)));
|
||||
set(
|
||||
"PaperHeightRange",
|
||||
format!("{} {}", num(f(32)?), num(f(40)?)),
|
||||
);
|
||||
match Cursor::new(&d[q + 84..]).u16()? {
|
||||
match enc.cursor(&d[q + 84..]).u16()? {
|
||||
0 => set("PrintPageOrientation", "Portrait".into()),
|
||||
1 => set("PrintPageOrientation", "Landscape".into()),
|
||||
_ => {}
|
||||
}
|
||||
set("Copies", Cursor::new(&d[q + 104..]).u32()?.to_string());
|
||||
set("Copies", enc.cursor(&d[q + 104..]).u32()?.to_string());
|
||||
match d.get(q + 118) {
|
||||
Some(0) => set("PrintBlankPages", "false".into()),
|
||||
Some(1) => set("PrintBlankPages", "true".into()),
|
||||
@@ -271,7 +272,7 @@ impl Reader<'_> {
|
||||
let mut text_defaults = None;
|
||||
// The layouts below are those of InDesign CS5 (7.0) and later in
|
||||
// little-endian files: the versions the corpus pairs show.
|
||||
if major < 7 || big_endian() {
|
||||
if major < 7 || self.enc().big_endian() {
|
||||
return Ok(Prefs::default());
|
||||
}
|
||||
let Some(&(uid, _)) = self
|
||||
@@ -293,7 +294,7 @@ impl Reader<'_> {
|
||||
// A u16 flag; `absent` is the value of documents without the chunk.
|
||||
let flag = |id: u32, absent: bool| -> Result<Option<String>, Error> {
|
||||
Ok(match get(id)? {
|
||||
Some(d) if d.len() == 2 => match Cursor::new(&d).u16()? {
|
||||
Some(d) if d.len() == 2 => match self.cursor(&d).u16()? {
|
||||
0 => Some("false".into()),
|
||||
1 => Some("true".into()),
|
||||
_ => None,
|
||||
@@ -313,7 +314,7 @@ impl Reader<'_> {
|
||||
}
|
||||
}
|
||||
if let Some(d) = get(id::COLOR_PROFILES)? {
|
||||
let mut c = Cursor::new(&d);
|
||||
let mut c = self.cursor(&d);
|
||||
c.u16()?;
|
||||
let n = c.u32()? as usize;
|
||||
c.skip(4 * n)?;
|
||||
@@ -324,7 +325,7 @@ impl Reader<'_> {
|
||||
Some("$ID/".to_string())
|
||||
} else if self.class(profile) == Some(class::COLOR_PROFILE) {
|
||||
match self.chunk(profile, id::PROFILE_NAME)? {
|
||||
Some(s) if s.len() > 1 => Cursor::new(&s[1..]).string().ok(),
|
||||
Some(s) if s.len() > 1 => self.cursor(&s[1..]).string().ok(),
|
||||
_ => None,
|
||||
}
|
||||
} else {
|
||||
@@ -338,7 +339,7 @@ impl Reader<'_> {
|
||||
}
|
||||
let intent = match get(id::COLOR_INTENT)? {
|
||||
None => Some("UseColorSettings"),
|
||||
Some(d) if d.len() >= 4 => match Cursor::new(&d[2..]).u16()? {
|
||||
Some(d) if d.len() >= 4 => match self.cursor(&d[2..]).u16()? {
|
||||
0 => Some("Perceptual"),
|
||||
2 => Some("RelativeColorimetric"),
|
||||
11 => Some("UseColorSettings"),
|
||||
@@ -358,7 +359,7 @@ impl Reader<'_> {
|
||||
|
||||
// View settings.
|
||||
if let Some(d) = get(id::VIEW)?.filter(|d| d.len() == 56) {
|
||||
let mut c = Cursor::new(&d);
|
||||
let mut c = self.cursor(&d);
|
||||
let units: Vec<u32> = (0..6).map(|_| c.u32()).collect::<Result<_, _>>()?;
|
||||
for (i, names) in [
|
||||
&["HorizontalMeasurementUnits"][..],
|
||||
@@ -422,7 +423,7 @@ impl Reader<'_> {
|
||||
|
||||
// Document setup beyond `DocumentPreferences`.
|
||||
if let Some(d) = get(chunk::DOCUMENT_PREFERENCES)?.filter(|d| d.len() >= 146) {
|
||||
let f = |o: usize| Cursor::new(&d[o..]).f64();
|
||||
let f = |o: usize| self.cursor(&d[o..]).f64();
|
||||
let b = |o: usize| (d[o] != 0).to_string();
|
||||
set("DocumentPreference", "DocumentBleedUniformSize", b(102));
|
||||
set("DocumentPreference", "SlugInsideOrLeftOffset", num(f(104)?));
|
||||
@@ -438,7 +439,7 @@ impl Reader<'_> {
|
||||
|
||||
// Text preferences and the default text frame columns.
|
||||
if let Some(d) = get(id::TEXT)?.filter(|d| d.len() >= 174) {
|
||||
let f = |o: usize| Cursor::new(&d[o..]).f64();
|
||||
let f = |o: usize| self.cursor(&d[o..]).f64();
|
||||
let b = |o: usize| (d[o] != 0).to_string();
|
||||
for (o, name) in [
|
||||
(0, "SmallCap"),
|
||||
@@ -469,7 +470,7 @@ impl Reader<'_> {
|
||||
set(
|
||||
"TextFramePreference",
|
||||
"TextColumnCount",
|
||||
Cursor::new(&d[112..]).u32()?.to_string(),
|
||||
self.cursor(&d[112..]).u32()?.to_string(),
|
||||
);
|
||||
const BASELINE: [&str; 5] = [
|
||||
"LeadingOffset",
|
||||
@@ -503,7 +504,7 @@ impl Reader<'_> {
|
||||
// Default margins and columns of new pages.
|
||||
let margins = match get(id::MARGINS)? {
|
||||
Some(d) if d.len() >= 32 => {
|
||||
let f = |o: usize| Cursor::new(&d[o..]).f64();
|
||||
let f = |o: usize| self.cursor(&d[o..]).f64();
|
||||
Some([f(0)?, f(8)?, f(16)?, f(24)?])
|
||||
}
|
||||
Some(_) => None,
|
||||
@@ -516,7 +517,7 @@ impl Reader<'_> {
|
||||
set("MarginPreference", "Bottom", num(bottom));
|
||||
}
|
||||
let columns = match get(id::COLUMNS)? {
|
||||
Some(d) if d.len() >= 12 => Some((Cursor::new(&d).u32()?, Cursor::new(&d[4..]).f64()?)),
|
||||
Some(d) if d.len() >= 12 => Some((self.cursor(&d).u32()?, self.cursor(&d[4..]).f64()?)),
|
||||
Some(_) => None,
|
||||
None => Some((1, 12.0)),
|
||||
};
|
||||
@@ -536,7 +537,7 @@ impl Reader<'_> {
|
||||
// Pasteboard: f64 horizontal and vertical margins.
|
||||
let pasteboard = match get(id::PASTEBOARD)? {
|
||||
Some(d) if d.len() >= 16 => {
|
||||
let f = |o: usize| Cursor::new(&d[o..]).f64();
|
||||
let f = |o: usize| self.cursor(&d[o..]).f64();
|
||||
Some((f(0)?, f(8)?))
|
||||
}
|
||||
Some(_) => None,
|
||||
@@ -557,7 +558,7 @@ impl Reader<'_> {
|
||||
// Default XML tags: name (u32 length, text segments) and u32 UID of
|
||||
// an interface colour, for story, table, (untagged), cell, image.
|
||||
if let Some(d) = get(id::XML_TAGS)? {
|
||||
let mut c = Cursor::new(&d);
|
||||
let mut c = self.cursor(&d);
|
||||
for (name, color) in [
|
||||
(Some("DefaultStoryTagName"), "DefaultStoryTagColor"),
|
||||
(Some("DefaultTableTagName"), "DefaultTableTagColor"),
|
||||
@@ -586,9 +587,9 @@ impl Reader<'_> {
|
||||
{
|
||||
Some(&(u, _)) => match self.chunk(u, id::ITEM_DEFAULTS)? {
|
||||
Some(d) if d.len() >= 12 => {
|
||||
let n = Cursor::new(&d[8..]).u32()? as usize;
|
||||
let n = self.cursor(&d[8..]).u32()? as usize;
|
||||
d.get(12 + 12 * n..)
|
||||
.and_then(|rest| Attrs::parse(rest, List::Item).ok())
|
||||
.and_then(|rest| Attrs::parse(self.enc(), rest, List::Item).ok())
|
||||
}
|
||||
_ => None,
|
||||
},
|
||||
@@ -606,7 +607,7 @@ impl Reader<'_> {
|
||||
let (mut v, mut p, mut r) = (Vec::new(), Vec::new(), Vec::new());
|
||||
// A layout the corpus does not show leaves the element as
|
||||
// observed.
|
||||
if print_prefs(&d, element, &mut v, &mut p, &mut r).is_ok() {
|
||||
if print_prefs(self.enc(), &d, element, &mut v, &mut p, &mut r).is_ok() {
|
||||
for pv in v {
|
||||
set(pv.element, pv.name, pv.value);
|
||||
}
|
||||
@@ -618,7 +619,7 @@ impl Reader<'_> {
|
||||
|
||||
// Grids.
|
||||
if let Some(d) = get(id::BASELINE_GRID)?.filter(|d| d.len() >= 26) {
|
||||
let f = |o: usize| Cursor::new(&d[o..]).f64();
|
||||
let f = |o: usize| self.cursor(&d[o..]).f64();
|
||||
set("GridPreference", "BaselineDivision", num(f(2)?));
|
||||
set("GridPreference", "BaselineStart", num(f(10)?));
|
||||
set(
|
||||
@@ -629,8 +630,8 @@ impl Reader<'_> {
|
||||
}
|
||||
let (h, hs, v, vs) = match get(id::DOCUMENT_GRID)? {
|
||||
Some(d) if d.len() >= 32 => {
|
||||
let f = |o: usize| Cursor::new(&d[o..]).f64();
|
||||
let u = |o: usize| Cursor::new(&d[o..]).u32();
|
||||
let f = |o: usize| self.cursor(&d[o..]).f64();
|
||||
let u = |o: usize| self.cursor(&d[o..]).u32();
|
||||
(f(8)?, u(16)?, f(20)?, u(28)?)
|
||||
}
|
||||
Some(_) => (f64::NAN, 0, f64::NAN, 0),
|
||||
@@ -651,7 +652,7 @@ impl Reader<'_> {
|
||||
// (u32 length, then text segments), the point size and the UID
|
||||
// of an interface colour.
|
||||
if let Some(d) = get(id::WATERMARK)?.filter(|d| d.len() > 10) {
|
||||
let mut c = Cursor::new(&d[10..]);
|
||||
let mut c = self.cursor(&d[10..]);
|
||||
let n = c.u32()? as usize;
|
||||
let family = c.segments(n)?;
|
||||
let n = c.u32()? as usize;
|
||||
@@ -667,7 +668,7 @@ impl Reader<'_> {
|
||||
|
||||
// Text defaults: a text attribute list, as styles have.
|
||||
if let Some(d) = get(chunk::STYLE_ATTRS)?.filter(|d| d.len() >= 2) {
|
||||
let mut c = Cursor::new(&d);
|
||||
let mut c = self.cursor(&d);
|
||||
let n = c.u16()? as usize;
|
||||
text_defaults = Attrs::parse_text(&mut c, n, List::Style).ok();
|
||||
}
|
||||
@@ -675,7 +676,9 @@ impl Reader<'_> {
|
||||
values,
|
||||
colors,
|
||||
text_defaults,
|
||||
anchor: anchor.as_deref().map(super::AnchorSettings::read),
|
||||
anchor: anchor
|
||||
.as_deref()
|
||||
.map(|d| super::AnchorSettings::read(self.enc(), d)),
|
||||
item_defaults,
|
||||
props,
|
||||
print_records,
|
||||
|
||||
+12
-2
@@ -48,6 +48,16 @@ impl<'a> Reader<'a> {
|
||||
Ok(obj)
|
||||
}
|
||||
|
||||
/// The encoding of the document's object data.
|
||||
pub fn enc(&self) -> Encoding {
|
||||
self.db.encoding()
|
||||
}
|
||||
|
||||
/// A cursor over object data (normally a chunk) of this document.
|
||||
pub fn cursor<'d>(&self, data: &'d [u8]) -> Cursor<'d> {
|
||||
self.db.encoding().cursor(data)
|
||||
}
|
||||
|
||||
/// Record a problem that does not stop the conversion.
|
||||
pub fn warn(&self, msg: String) {
|
||||
self.warnings.borrow_mut().push(msg);
|
||||
@@ -68,7 +78,7 @@ impl<'a> Reader<'a> {
|
||||
|
||||
pub(super) fn uid_list(&self, uid: u32, id: u32) -> Result<Vec<u32>, Error> {
|
||||
match self.chunk(uid, id)? {
|
||||
Some(data) => Cursor::new(&data).u32_list(),
|
||||
Some(data) => self.cursor(&data).u32_list(),
|
||||
None => Ok(Vec::new()),
|
||||
}
|
||||
}
|
||||
@@ -77,7 +87,7 @@ impl<'a> Reader<'a> {
|
||||
pub(super) fn children(&self, uid: u32, id: u32) -> Result<Vec<u32>, Error> {
|
||||
match self.chunk(uid, id)? {
|
||||
Some(d) => {
|
||||
let mut c = Cursor::new(&d);
|
||||
let mut c = self.cursor(&d);
|
||||
c.skip(8)?;
|
||||
c.u32_list()
|
||||
}
|
||||
|
||||
+19
-15
@@ -72,7 +72,7 @@ impl<'a> Reader<'a> {
|
||||
let Some(d) = self.chunk(uid, chunk::BULLETS)? else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let mut c = Cursor::new(&d);
|
||||
let mut c = self.cursor(&d);
|
||||
if c.u16()? != 1 {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
@@ -141,9 +141,9 @@ impl<'a> Reader<'a> {
|
||||
));
|
||||
return Ok(None);
|
||||
}
|
||||
let f = |o: usize| Cursor::new(&d[o..]).f64();
|
||||
let u = |o: usize| Cursor::new(&d[o..]).u32();
|
||||
let binding = Cursor::new(&d[64..]).u16()?;
|
||||
let f = |o: usize| self.cursor(&d[o..]).f64();
|
||||
let u = |o: usize| self.cursor(&d[o..]).u32();
|
||||
let binding = self.cursor(&d[64..]).u16()?;
|
||||
if binding > 1 {
|
||||
self.warn(format!(
|
||||
"document preferences: page binding code {binding} is not known; left out"
|
||||
@@ -164,7 +164,7 @@ impl<'a> Reader<'a> {
|
||||
let Some(d) = self.chunk(doc, chunk::DOC_USERS)? else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let mut c = Cursor::new(&d);
|
||||
let mut c = self.cursor(&d);
|
||||
let n = c.u32()?;
|
||||
if n as usize > d.len() / 9 {
|
||||
return Err(Error::Corrupt(format!("{n} document users")));
|
||||
@@ -197,10 +197,10 @@ impl<'a> Reader<'a> {
|
||||
let Ok(Some(d)) = self.chunk(uid, chunk::INDEX_GROUPS) else {
|
||||
return Vec::new();
|
||||
};
|
||||
if crate::object::big_endian() {
|
||||
if self.enc().big_endian() {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(count) = u32_at(&d, 0) else {
|
||||
let Some(count) = self.enc().u32_at(&d, 0) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut out: Vec<(String, bool, u16)> = Vec::new();
|
||||
@@ -208,7 +208,7 @@ impl<'a> Reader<'a> {
|
||||
if d[i] != 1 || d[i + 1] != 2 {
|
||||
continue;
|
||||
}
|
||||
let mut c = Cursor::new(&d[i + 1..]);
|
||||
let mut c = self.cursor(&d[i + 1..]);
|
||||
let Ok(name) = c.string() else { continue };
|
||||
if !(name.starts_with("kIndexGroup_") || name.starts_with("kWRIndexGroup_"))
|
||||
|| out.iter().any(|(n, _, _)| *n == name)
|
||||
@@ -216,7 +216,7 @@ impl<'a> Reader<'a> {
|
||||
continue;
|
||||
}
|
||||
let at = i + 1 + c.pos();
|
||||
let (Some(&include), Some(header)) = (d.get(at), u16_at(&d, at + 2)) else {
|
||||
let (Some(&include), Some(header)) = (d.get(at), self.enc().u16_at(&d, at + 2)) else {
|
||||
continue;
|
||||
};
|
||||
out.push((name, include != 0, header));
|
||||
@@ -242,7 +242,7 @@ impl<'a> Reader<'a> {
|
||||
uids.sort_unstable();
|
||||
uids.into_iter().find_map(|uid| {
|
||||
let d = self.chunk(uid, chunk::SMOOTH_SHADE).ok()??;
|
||||
if d.len() != 92 || u32_at(&d, 60) != Some(28) {
|
||||
if d.len() != 92 || self.enc().u32_at(&d, 60) != Some(28) {
|
||||
return None;
|
||||
}
|
||||
let name = self
|
||||
@@ -250,14 +250,18 @@ impl<'a> Reader<'a> {
|
||||
.ok()
|
||||
.flatten()
|
||||
.and_then(|n| {
|
||||
let mut c = Cursor::new(&n);
|
||||
let mut c = self.cursor(&n);
|
||||
let builtin = c.flag().ok()? == 1;
|
||||
Some((builtin, c.string().ok()?))
|
||||
});
|
||||
Some(ConstantShade {
|
||||
uid,
|
||||
count: u32_at(&d, 64)?,
|
||||
values: [f64_at(&d, 68)?, f64_at(&d, 76)?, f64_at(&d, 84)?],
|
||||
count: self.enc().u32_at(&d, 64)?,
|
||||
values: [
|
||||
self.enc().f64_at(&d, 68)?,
|
||||
self.enc().f64_at(&d, 76)?,
|
||||
self.enc().f64_at(&d, 84)?,
|
||||
],
|
||||
name,
|
||||
})
|
||||
})
|
||||
@@ -274,7 +278,7 @@ impl<'a> Reader<'a> {
|
||||
let Some(d) = self.chunk(uid, chunk::NAMED_GRID)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut c = Cursor::new(&d);
|
||||
let mut c = self.cursor(&d);
|
||||
c.u32()?;
|
||||
let builtin = c.flag()? == 1;
|
||||
Ok(Some((uid, builtin, c.string()?)))
|
||||
@@ -300,7 +304,7 @@ impl<'a> Reader<'a> {
|
||||
if d.len() <= 1 {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut c = Cursor::new(&d);
|
||||
let mut c = self.cursor(&d);
|
||||
c.flag()?;
|
||||
let name = c.string()?;
|
||||
// Then the primary and secondary names, u16 ID, and two vendors
|
||||
|
||||
+32
-32
@@ -250,7 +250,7 @@ impl<'a> Reader<'a> {
|
||||
let Some(d) = self.chunk(uid, color::chunk::COLOR_VALUE)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut c = Cursor::new(&d);
|
||||
let mut c = self.cursor(&d);
|
||||
if c.u32()? != 5 || c.u16()? != 3 {
|
||||
return Ok(None);
|
||||
}
|
||||
@@ -272,7 +272,7 @@ impl<'a> Reader<'a> {
|
||||
// page number start, u32 numbering style, u32 continue, u32, then
|
||||
// u8 and string (alternate layout).
|
||||
if let Some(d) = self.chunk(uid, chunk::SECTION_INFO)? {
|
||||
let mut c = Cursor::new(&d);
|
||||
let mut c = self.cursor(&d);
|
||||
let parsed = (|| -> Result<(String, String, [u32; 4]), Error> {
|
||||
c.u8()?;
|
||||
let prefix = c.string()?;
|
||||
@@ -306,12 +306,12 @@ impl<'a> Reader<'a> {
|
||||
|
||||
pub(super) fn layer(&self, uid: u32) -> Result<Layer, Error> {
|
||||
let data = self.required(uid, chunk::LAYER_PROPS)?;
|
||||
let mut c = Cursor::new(&data);
|
||||
let mut c = self.cursor(&data);
|
||||
let locked = c.u16()? != 0;
|
||||
let visible = c.u16()? != 0;
|
||||
c.skip(14)?;
|
||||
// A string follows; its position varies, so search for the tag.
|
||||
let name = find_string(&data, 18)?;
|
||||
let name = find_string(self.enc(), &data, 18)?;
|
||||
let settings = self.layer_settings(&data)?;
|
||||
Ok(Layer {
|
||||
uid,
|
||||
@@ -327,14 +327,14 @@ impl<'a> Reader<'a> {
|
||||
/// all corpus pairs: u16 printable at 4, u16 lock guides at 6, u32
|
||||
/// colour at 10, u16 UI at 14; after the name, u16 ignore wrap.
|
||||
pub(super) fn layer_settings(&self, data: &[u8]) -> Result<Option<LayerSettings>, Error> {
|
||||
if crate::object::big_endian() || data.len() < 23 || data[19] != 2 {
|
||||
if self.enc().big_endian() || data.len() < 23 || data[19] != 2 {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut c = Cursor::new(&data[19..]);
|
||||
let mut c = self.cursor(&data[19..]);
|
||||
c.string()?;
|
||||
let ignore_wrap = c.u16()? != 0;
|
||||
let flag = |at: usize| u16_at(data, at).is_some_and(|v| v != 0);
|
||||
let color = match u32_at(data, 10) {
|
||||
let flag = |at: usize| self.enc().u16_at(data, at).is_some_and(|v| v != 0);
|
||||
let color = match self.enc().u32_at(data, 10) {
|
||||
Some(u) => self.ui_color(u)?,
|
||||
None => None,
|
||||
};
|
||||
@@ -361,16 +361,16 @@ impl<'a> Reader<'a> {
|
||||
|
||||
pub(super) fn spread(&self, uid: u32) -> Result<Spread, Error> {
|
||||
let transform = match self.chunk(uid, chunk::SPREAD_TRANSFORM)? {
|
||||
Some(d) => Matrix::read(&mut Cursor::new(&d))?,
|
||||
Some(d) => Matrix::read(&mut self.cursor(&d))?,
|
||||
None => Matrix::IDENTITY,
|
||||
};
|
||||
let binding_location = match self.chunk(uid, chunk::SPREAD_BINDING)? {
|
||||
Some(d) => Cursor::new(&d).u32()?,
|
||||
Some(d) => self.cursor(&d).u32()?,
|
||||
None => 0,
|
||||
};
|
||||
let master_name = match self.chunk(uid, chunk::MASTER_NAME)? {
|
||||
Some(d) => {
|
||||
let mut c = Cursor::new(&d);
|
||||
let mut c = self.cursor(&d);
|
||||
c.u8()?;
|
||||
let prefix = c.string()?;
|
||||
c.u8()?;
|
||||
@@ -380,7 +380,7 @@ impl<'a> Reader<'a> {
|
||||
None => None,
|
||||
};
|
||||
let children = self.required(uid, chunk::SPREAD_CHILDREN)?;
|
||||
let mut c = Cursor::new(&children);
|
||||
let mut c = self.cursor(&children);
|
||||
c.skip(8)?;
|
||||
let spread_layers = c.u32_list()?;
|
||||
let mut pages = Vec::new();
|
||||
@@ -388,7 +388,7 @@ impl<'a> Reader<'a> {
|
||||
let mut guides = Vec::new();
|
||||
for sl in spread_layers {
|
||||
let layer = match self.chunk(sl, chunk::SPREAD_LAYER_LAYER)? {
|
||||
Some(d) => Cursor::new(&d).u32()?,
|
||||
Some(d) => self.cursor(&d).u32()?,
|
||||
None => 0,
|
||||
};
|
||||
for child in self.children(sl, chunk::SPREAD_LAYER_CHILDREN)? {
|
||||
@@ -404,7 +404,7 @@ impl<'a> Reader<'a> {
|
||||
}
|
||||
}
|
||||
if let Some(d) = self.chunk(uid, chunk::SPREAD_TAB_ORDERS)? {
|
||||
let mut c = Cursor::new(&d);
|
||||
let mut c = self.cursor(&d);
|
||||
let n = c.u32()?;
|
||||
for _ in 0..n {
|
||||
let page = c.u32()?;
|
||||
@@ -415,14 +415,14 @@ impl<'a> Reader<'a> {
|
||||
}
|
||||
}
|
||||
let flattener_resolution = match self.chunk(uid, chunk::SPREAD_FLATTENER)? {
|
||||
Some(d) => match (f64_at(&d, 20), f64_at(&d, 28)) {
|
||||
Some(d) => match (self.enc().f64_at(&d, 20), self.enc().f64_at(&d, 28)) {
|
||||
(Some(a), Some(b)) => Some([a, b]),
|
||||
_ => None,
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
let short = |id: u32| -> Result<Option<u16>, Error> {
|
||||
Ok(self.chunk(uid, id)?.and_then(|d| u16_at(&d, 0)))
|
||||
Ok(self.chunk(uid, id)?.and_then(|d| self.enc().u16_at(&d, 0)))
|
||||
};
|
||||
Ok(Spread {
|
||||
uid,
|
||||
@@ -453,9 +453,9 @@ impl<'a> Reader<'a> {
|
||||
));
|
||||
return Ok(None);
|
||||
}
|
||||
let f = |o: usize| Cursor::new(&d[o..]).f64();
|
||||
let u = |o: usize| Cursor::new(&d[o..]).u32();
|
||||
let h = |o: usize| Cursor::new(&d[o..]).u16();
|
||||
let f = |o: usize| self.cursor(&d[o..]).f64();
|
||||
let u = |o: usize| self.cursor(&d[o..]).u32();
|
||||
let h = |o: usize| self.cursor(&d[o..]).u16();
|
||||
Ok(Some(Guide {
|
||||
uid,
|
||||
position: f(0)?,
|
||||
@@ -468,11 +468,11 @@ impl<'a> Reader<'a> {
|
||||
layer,
|
||||
locked: self
|
||||
.chunk(uid, chunk::ITEM_LOCKED)?
|
||||
.is_some_and(|d| u32_at(&d, 0) == Some(1)),
|
||||
.is_some_and(|d| self.enc().u32_at(&d, 0) == Some(1)),
|
||||
zone: if d.len() >= 52 { Some(f(44)?) } else { None },
|
||||
overridden: match self.chunk(uid, chunk::ITEM_OVERRIDE)? {
|
||||
Some(o) => {
|
||||
let mut c = Cursor::new(&o);
|
||||
let mut c = self.cursor(&o);
|
||||
let master = c.u32()?;
|
||||
Some((master, c.u32_list()?))
|
||||
}
|
||||
@@ -488,16 +488,16 @@ impl<'a> Reader<'a> {
|
||||
Some(d) => d,
|
||||
None => self.required(uid, chunk::ITEM_TRANSFORM)?,
|
||||
};
|
||||
let transform = Matrix::read(&mut Cursor::new(&transform))?;
|
||||
let transform = Matrix::read(&mut self.cursor(&transform))?;
|
||||
let b = match self.chunk(uid, chunk::PAGE_BOUNDS)? {
|
||||
Some(d) => d,
|
||||
None => self.required(uid, chunk::OLD_PAGE_BOUNDS)?,
|
||||
};
|
||||
let mut c = Cursor::new(&b);
|
||||
let mut c = self.cursor(&b);
|
||||
let bounds = [c.f64()?, c.f64()?, c.f64()?, c.f64()?];
|
||||
let (master, master_transform) = match self.chunk(uid, chunk::PAGE_MASTER)? {
|
||||
Some(d) => {
|
||||
let mut c = Cursor::new(&d);
|
||||
let mut c = self.cursor(&d);
|
||||
let m = c.u32()?;
|
||||
c.skip(2)?;
|
||||
// The matrix is missing in files from InDesign 3.0 and 4.0.
|
||||
@@ -511,7 +511,7 @@ impl<'a> Reader<'a> {
|
||||
};
|
||||
let margins = match self.chunk(uid, chunk::PAGE_MARGINS)? {
|
||||
Some(d) if d.len() >= 34 => {
|
||||
let mut c = Cursor::new(&d);
|
||||
let mut c = self.cursor(&d);
|
||||
Some(Margins {
|
||||
left: c.f64()?,
|
||||
top: c.f64()?,
|
||||
@@ -524,7 +524,7 @@ impl<'a> Reader<'a> {
|
||||
};
|
||||
let columns = match self.chunk(uid, chunk::PAGE_COLUMNS)? {
|
||||
Some(d) => {
|
||||
let mut c = Cursor::new(&d);
|
||||
let mut c = self.cursor(&d);
|
||||
let n = c.u32()? as usize;
|
||||
if n > d.len() / 8 {
|
||||
return Err(Error::Corrupt(format!("page {uid}: {n} column positions")));
|
||||
@@ -540,7 +540,7 @@ impl<'a> Reader<'a> {
|
||||
};
|
||||
let grid = match self.chunk(uid, chunk::PAGE_GRID)? {
|
||||
Some(d) => {
|
||||
let mut c = Cursor::new(&d);
|
||||
let mut c = self.cursor(&d);
|
||||
let font = c.u32()?;
|
||||
c.u8()?;
|
||||
let font_style = c.string()?;
|
||||
@@ -557,8 +557,8 @@ impl<'a> Reader<'a> {
|
||||
};
|
||||
// u32 count, then (unless it is 0) the two lists.
|
||||
let overrides = match self.chunk(uid, chunk::PAGE_OVERRIDES)? {
|
||||
Some(d) if u32_at(&d, 0).is_some_and(|n| n > 0) => {
|
||||
let mut c = Cursor::new(&d[4..]);
|
||||
Some(d) if self.enc().u32_at(&d, 0).is_some_and(|n| n > 0) => {
|
||||
let mut c = self.cursor(&d[4..]);
|
||||
let items = c.u32_list()?;
|
||||
let with = c.u32_list()?;
|
||||
items.into_iter().zip(with).collect()
|
||||
@@ -569,14 +569,14 @@ impl<'a> Reader<'a> {
|
||||
overrides,
|
||||
use_master_grid: self
|
||||
.chunk(uid, chunk::PAGE_GRID_USE)?
|
||||
.and_then(|d| u16_at(&d, 4))
|
||||
.and_then(|d| self.enc().u16_at(&d, 4))
|
||||
.map(|v| v != 0),
|
||||
layout_rule: self
|
||||
.chunk(uid, chunk::PAGE_LAYOUT_RULE)?
|
||||
.and_then(|d| u32_at(&d, 4)),
|
||||
.and_then(|d| self.enc().u32_at(&d, 4)),
|
||||
color: match self
|
||||
.chunk(uid, chunk::PAGE_COLOR)?
|
||||
.and_then(|d| u32_at(&d, 0))
|
||||
.and_then(|d| self.enc().u32_at(&d, 0))
|
||||
{
|
||||
Some(code) => self.ui_color_ref(code)?,
|
||||
None => UiColorRef::UseMaster,
|
||||
|
||||
+14
-14
@@ -163,7 +163,7 @@ impl<'a> Reader<'a> {
|
||||
|
||||
pub(super) fn story(&self, uid: u32) -> Result<Story, Error> {
|
||||
let data = self.required(uid, chunk::STORY_STRANDS)?;
|
||||
let mut c = Cursor::new(&data);
|
||||
let mut c = self.cursor(&data);
|
||||
c.skip(6)?;
|
||||
let mut strands = vec![c.u32()?];
|
||||
strands.extend(c.u32_list()?);
|
||||
@@ -187,9 +187,9 @@ impl<'a> Reader<'a> {
|
||||
&& let Some(tree) = self.chunk(strand, hyperlink::chunk::RANGE_TREE)?
|
||||
&& tree.len() >= 4
|
||||
{
|
||||
let first = u32_from(tree[..4].try_into().unwrap());
|
||||
let first = self.enc().u32_from(tree[..4].try_into().unwrap());
|
||||
let pages = |uid| self.chunk(uid, hyperlink::chunk::RANGE_PAGE);
|
||||
match hyperlink::source_ranges(first, pages) {
|
||||
match hyperlink::source_ranges(self.enc(), first, pages) {
|
||||
Ok(r) => sources.extend(r),
|
||||
Err(e) => self.warn(format!("story {uid}: hyperlink sources left out: {e}")),
|
||||
}
|
||||
@@ -197,14 +197,14 @@ impl<'a> Reader<'a> {
|
||||
let Some(list) = self.chunk(strand, chunk::STRAND_DATA)? else {
|
||||
continue;
|
||||
};
|
||||
let mut c = Cursor::new(&list);
|
||||
let mut c = self.cursor(&list);
|
||||
let n = c.u16()?;
|
||||
let mut base = 0usize;
|
||||
for _ in 0..n {
|
||||
let data_len = c.u32()? as usize;
|
||||
let data_uid = c.u32()?;
|
||||
let runs = self.required(data_uid, chunk::STRAND_RUNS)?;
|
||||
let mut r = Cursor::new(&runs);
|
||||
let mut r = self.cursor(&runs);
|
||||
let kind = r.u32()?;
|
||||
r.skip(4)?;
|
||||
let count = r.u16()?;
|
||||
@@ -213,7 +213,7 @@ impl<'a> Reader<'a> {
|
||||
for _ in 0..count {
|
||||
let size = r.u32()? as usize;
|
||||
let rec = r.bytes(size)?;
|
||||
let mut rc = Cursor::new(rec);
|
||||
let mut rc = self.cursor(rec);
|
||||
let len = rc.u32()? as usize;
|
||||
let start = pos;
|
||||
pos += len;
|
||||
@@ -293,7 +293,7 @@ impl<'a> Reader<'a> {
|
||||
};
|
||||
let xml_element = match self.chunk(uid, xml::chunk::NODE_REF)? {
|
||||
Some(d) if d.len() >= 8 => {
|
||||
let mut c = Cursor::new(&d);
|
||||
let mut c = self.cursor(&d);
|
||||
Some((c.u32()?, c.u32()?))
|
||||
}
|
||||
_ => None,
|
||||
@@ -310,7 +310,7 @@ impl<'a> Reader<'a> {
|
||||
class::ANCHOR => {
|
||||
let settings = self
|
||||
.chunk(item, chunk::ANCHOR_SETTINGS)?
|
||||
.map(|d| AnchorSettings::read(&d));
|
||||
.map(|d| AnchorSettings::read(self.enc(), &d));
|
||||
for child in self.children(item, chunk::ANCHOR_CHILDREN)? {
|
||||
if let Some(mut pi) = self.page_item(child, None)? {
|
||||
pi.anchor = settings.clone();
|
||||
@@ -399,12 +399,12 @@ impl<'a> Reader<'a> {
|
||||
// is the TOC style.
|
||||
toc_style: match self
|
||||
.chunk(uid, chunk::STORY_TOC)?
|
||||
.and_then(|d| u32_at(&d, 0))
|
||||
.and_then(|d| self.enc().u32_at(&d, 0))
|
||||
.and_then(uid_or_none)
|
||||
{
|
||||
Some(toc) => self
|
||||
.chunk(toc, chunk::TOC_STYLE_OF)?
|
||||
.and_then(|d| u32_at(&d, 0))
|
||||
.and_then(|d| self.enc().u32_at(&d, 0))
|
||||
.and_then(uid_or_none),
|
||||
None => None,
|
||||
},
|
||||
@@ -424,16 +424,16 @@ impl<'a> Reader<'a> {
|
||||
) -> Result<BTreeMap<usize, XmlMarker>, Error> {
|
||||
let mut out = BTreeMap::new();
|
||||
let first = match self.chunk(uid, xml::chunk::STORE)? {
|
||||
Some(d) if d.len() >= 4 => Cursor::new(&d).u32()?,
|
||||
Some(d) if d.len() >= 4 => self.cursor(&d).u32()?,
|
||||
_ => return Ok(out),
|
||||
};
|
||||
let nodes = xml::read_store(first, |p| self.chunk(p, xml::chunk::PAGE))?;
|
||||
let nodes = xml::read_store(self.enc(), first, |p| self.chunk(p, xml::chunk::PAGE))?;
|
||||
if nodes.is_empty() {
|
||||
return Ok(out);
|
||||
}
|
||||
let positions = match marker_strand.map(|s| self.chunk(s, xml::chunk::MARKER_TREE)) {
|
||||
Some(r) => match r? {
|
||||
Some(d) => xml::marker_positions(&d)?,
|
||||
Some(d) => xml::marker_positions(self.enc(), &d)?,
|
||||
None => BTreeMap::new(),
|
||||
},
|
||||
None => BTreeMap::new(),
|
||||
@@ -529,7 +529,7 @@ impl<'a> Reader<'a> {
|
||||
Some(xml::class::CONTENT_HOLDER) => {
|
||||
match self.chunk(node.content, chunk::ITEM_HIERARCHY)? {
|
||||
Some(d) if d.len() >= 8 => {
|
||||
(uid_or_none(Cursor::new(&d[4..]).u32()?), false)
|
||||
(uid_or_none(self.cursor(&d[4..]).u32()?), false)
|
||||
}
|
||||
_ => (None, false),
|
||||
}
|
||||
|
||||
+10
-9
@@ -10,11 +10,12 @@ use super::*;
|
||||
/// whether the flag is 1, and the string. In big-endian data the flag and
|
||||
/// the string's tag (2) are swapped (`docs/format/big-endian.md`).
|
||||
pub(super) fn find_flagged_string(
|
||||
enc: Encoding,
|
||||
data: &[u8],
|
||||
from: usize,
|
||||
accept: impl Fn(&str) -> bool,
|
||||
) -> Option<(usize, bool, String)> {
|
||||
let big = crate::object::big_endian();
|
||||
let big = enc.big_endian();
|
||||
(from..data.len().saturating_sub(6)).find_map(|i| {
|
||||
let header = match big {
|
||||
false => data[i] <= 2 && data[i + 1] == 2,
|
||||
@@ -23,7 +24,7 @@ pub(super) fn find_flagged_string(
|
||||
if !header {
|
||||
return None;
|
||||
}
|
||||
let mut c = Cursor::new(&data[i..]);
|
||||
let mut c = enc.cursor(&data[i..]);
|
||||
let builtin = c.flag().ok()? == 1;
|
||||
let s = c.string().ok()?;
|
||||
accept(&s).then_some((i, builtin, s))
|
||||
@@ -31,15 +32,15 @@ pub(super) fn find_flagged_string(
|
||||
}
|
||||
|
||||
/// Find the first in-object string at or after `from`.
|
||||
pub(super) fn find_string(data: &[u8], from: usize) -> Result<String, Error> {
|
||||
if crate::object::big_endian() {
|
||||
pub(super) fn find_string(enc: Encoding, data: &[u8], from: usize) -> Result<String, Error> {
|
||||
if enc.big_endian() {
|
||||
// The tag (2), the byte before it in little-endian data, then the
|
||||
// rest of the header (`Cursor::string`).
|
||||
for i in from..data.len().saturating_sub(5) {
|
||||
if data[i] == 2
|
||||
&& data[i + 1] <= 2
|
||||
&& u16_from([data[i + 3], data[i + 4]]) > 0
|
||||
&& let Ok(s) = Cursor::new(&data[i..]).string()
|
||||
&& enc.u16_from([data[i + 3], data[i + 4]]) > 0
|
||||
&& let Ok(s) = enc.cursor(&data[i..]).string()
|
||||
{
|
||||
return Ok(s);
|
||||
}
|
||||
@@ -48,11 +49,11 @@ pub(super) fn find_string(data: &[u8], from: usize) -> Result<String, Error> {
|
||||
}
|
||||
for i in from..data.len().saturating_sub(4) {
|
||||
if data[i] == 2 && data[i + 1] == 0 {
|
||||
let n = u16_from([data[i + 2], data[i + 3]]) as usize;
|
||||
let n = enc.u16_from([data[i + 2], data[i + 3]]) as usize;
|
||||
if n > 0
|
||||
&& i + 6 <= data.len()
|
||||
&& (u16_from([data[i + 4], data[i + 5]]) & 0xC000) != 0
|
||||
&& let Ok(s) = Cursor::new(&data[i..]).string()
|
||||
&& (enc.u16_from([data[i + 4], data[i + 5]]) & 0xC000) != 0
|
||||
&& let Ok(s) = enc.cursor(&data[i..]).string()
|
||||
{
|
||||
return Ok(s);
|
||||
}
|
||||
|
||||
+35
-31
@@ -129,7 +129,7 @@ impl<'a> Reader<'a> {
|
||||
let Some(data) = self.chunk(uid, chunk::STYLE_INFO)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut c = Cursor::new(&data);
|
||||
let mut c = self.cursor(&data);
|
||||
let next = c.u32()?;
|
||||
let based_on = c.u32()?;
|
||||
// The header before the name is 4 bytes shorter in files from
|
||||
@@ -137,14 +137,14 @@ impl<'a> Reader<'a> {
|
||||
// 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 {
|
||||
let Some((at, builtin, name)) = find_flagged_string(self.enc(), &data, 12, |_| true) else {
|
||||
return Err(Error::Corrupt(format!("style {uid}: no name")));
|
||||
};
|
||||
let paragraph = Cursor::new(&data[at - 4..]).u16()? != 0;
|
||||
let imported = Cursor::new(&data[at - 2..]).u16()? != 0;
|
||||
let paragraph = self.cursor(&data[at - 4..]).u16()? != 0;
|
||||
let imported = self.cursor(&data[at - 2..]).u16()? != 0;
|
||||
let shortcut = if at >= 10 {
|
||||
Some((
|
||||
Cursor::new(&data[at - 10..]).u32()?,
|
||||
self.cursor(&data[at - 10..]).u32()?,
|
||||
data[at - 6],
|
||||
data[at - 5],
|
||||
))
|
||||
@@ -153,17 +153,17 @@ impl<'a> Reader<'a> {
|
||||
};
|
||||
// A 36-character in-object string after the name: a GUID.
|
||||
const GUID: [u8; 6] = [2, 0, 36, 0, 36, 0x40];
|
||||
let unique_id = if crate::object::big_endian() {
|
||||
let unique_id = if self.enc().big_endian() {
|
||||
None
|
||||
} else {
|
||||
data[at..]
|
||||
.windows(GUID.len())
|
||||
.position(|w| w == GUID)
|
||||
.and_then(|i| Cursor::new(&data[at + i..]).string().ok())
|
||||
.and_then(|i| self.cursor(&data[at + i..]).string().ok())
|
||||
};
|
||||
let attrs = match self.chunk(uid, chunk::STYLE_ATTRS)? {
|
||||
Some(d) if d.len() >= 2 => {
|
||||
let mut c = Cursor::new(&d);
|
||||
let mut c = self.cursor(&d);
|
||||
let n = c.u16()? as usize;
|
||||
Attrs::parse_text(&mut c, n, List::Style).unwrap_or_default()
|
||||
}
|
||||
@@ -194,7 +194,7 @@ impl<'a> Reader<'a> {
|
||||
let Some(d) = self.chunk(uid, chunk::TOC_STYLE)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut c = Cursor::new(&d);
|
||||
let mut c = self.cursor(&d);
|
||||
let builtin = c.flag()? == 1;
|
||||
let name = c.string()?;
|
||||
c.skip(8)?;
|
||||
@@ -232,7 +232,7 @@ impl<'a> Reader<'a> {
|
||||
/// cell or table styles): its kind (chunk 0x28C2) and children.
|
||||
pub(super) fn style_root_group(&self, uid: u32) -> Result<StyleGroup, Error> {
|
||||
let kind = match self.chunk(uid, chunk::ROOT_GROUP_KIND)? {
|
||||
Some(d) => Cursor::new(&d).u32()?,
|
||||
Some(d) => self.cursor(&d).u32()?,
|
||||
None => 0,
|
||||
};
|
||||
let mut children = Vec::new();
|
||||
@@ -258,7 +258,7 @@ impl<'a> Reader<'a> {
|
||||
pub(super) fn style_group(&self, uid: u32) -> Result<StyleGroup, Error> {
|
||||
let name = match self.chunk(uid, chunk::STYLE_GROUP_NAME)? {
|
||||
Some(d) if d.len() > 1 => {
|
||||
let mut c = Cursor::new(&d);
|
||||
let mut c = self.cursor(&d);
|
||||
c.flag()?;
|
||||
c.string()?
|
||||
}
|
||||
@@ -279,13 +279,13 @@ impl<'a> Reader<'a> {
|
||||
let Some(d) = self.chunk(uid, chunk::OBJECT_STYLE_INFO)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut c = Cursor::new(&d);
|
||||
let mut c = self.cursor(&d);
|
||||
let based_on = c.u32()?;
|
||||
let builtin = c.flag()? == 1;
|
||||
let name = c.string()?;
|
||||
let u32_chunk = |id: u32| -> Result<Option<u32>, Error> {
|
||||
match self.chunk(uid, id)? {
|
||||
Some(d) if d.len() >= 4 => Ok(Some(Cursor::new(&d).u32()?)),
|
||||
Some(d) if d.len() >= 4 => Ok(Some(self.cursor(&d).u32()?)),
|
||||
_ => Ok(None),
|
||||
}
|
||||
};
|
||||
@@ -295,11 +295,15 @@ impl<'a> Reader<'a> {
|
||||
builtin,
|
||||
based_on: uid_or_none(based_on),
|
||||
fitting: match self.chunk(uid, chunk::OBJECT_STYLE_FITTING)? {
|
||||
Some(d) => Attrs::parse_short(&d, List::ObjectStyleFitting).unwrap_or_default(),
|
||||
Some(d) => {
|
||||
Attrs::parse_short(self.enc(), &d, List::ObjectStyleFitting).unwrap_or_default()
|
||||
}
|
||||
None => Attrs::default(),
|
||||
},
|
||||
attrs: match self.chunk(uid, chunk::OBJECT_STYLE_ATTRS)? {
|
||||
Some(d) => Attrs::parse_short(&d, List::ObjectStyle).unwrap_or_default(),
|
||||
Some(d) => {
|
||||
Attrs::parse_short(self.enc(), &d, List::ObjectStyle).unwrap_or_default()
|
||||
}
|
||||
None => Attrs::default(),
|
||||
},
|
||||
// The layout is known for these sizes only
|
||||
@@ -312,25 +316,25 @@ impl<'a> Reader<'a> {
|
||||
));
|
||||
None
|
||||
}
|
||||
d => d.as_deref().map(ObjectStyleFrame::read),
|
||||
d => d.map(|d| ObjectStyleFrame::read(self.enc(), &d)),
|
||||
},
|
||||
story: self
|
||||
.chunk(uid, chunk::OBJECT_STYLE_STORY)?
|
||||
.and_then(|d| StorySettings::read(&d)),
|
||||
.and_then(|d| StorySettings::read(self.enc(), &d)),
|
||||
direction: match self.chunk(uid, chunk::OBJECT_STYLE_DIRECTION)? {
|
||||
Some(d) if d.len() >= 2 => Some(Cursor::new(&d).u16()?),
|
||||
Some(d) if d.len() >= 2 => Some(self.cursor(&d).u16()?),
|
||||
_ => None,
|
||||
},
|
||||
text_wrap: self.wrap_chunk(uid, chunk::OBJECT_STYLE_WRAP)?,
|
||||
contour_type: u32_chunk(chunk::OBJECT_STYLE_CONTOUR)?,
|
||||
enabled: match self.chunk(uid, chunk::OBJECT_STYLE_ENABLED)? {
|
||||
Some(d) => Some(Cursor::new(&d).u32_list()?),
|
||||
Some(d) => Some(self.cursor(&d).u32_list()?),
|
||||
None => None,
|
||||
},
|
||||
paragraph_style: u32_chunk(chunk::OBJECT_STYLE_PARAGRAPH_STYLE)?,
|
||||
anchor: self
|
||||
.chunk(uid, chunk::ANCHOR_SETTINGS)?
|
||||
.map(|d| AnchorSettings::read(&d)),
|
||||
.map(|d| AnchorSettings::read(self.enc(), &d)),
|
||||
}))
|
||||
}
|
||||
}
|
||||
@@ -349,10 +353,10 @@ pub struct AnchorSettings {
|
||||
}
|
||||
|
||||
impl AnchorSettings {
|
||||
pub(super) fn read(d: &[u8]) -> AnchorSettings {
|
||||
let u = |o: usize| u16_at(d, o).unwrap_or_default();
|
||||
pub(super) fn read(enc: Encoding, d: &[u8]) -> AnchorSettings {
|
||||
let u = |o: usize| enc.u16_at(d, o).unwrap_or_default();
|
||||
AnchorSettings {
|
||||
offset: (d.len() >= 54).then(|| (f64_at(d, 0).unwrap_or_default(), u(52))),
|
||||
offset: (d.len() >= 54).then(|| (enc.f64_at(d, 0).unwrap_or_default(), u(52))),
|
||||
fields: (d.len() >= 58).then(|| ([u(46), u(50), u(56)], [u(40), u(48)])),
|
||||
}
|
||||
}
|
||||
@@ -381,15 +385,15 @@ pub struct ObjectStyleFrame {
|
||||
}
|
||||
|
||||
impl ObjectStyleFrame {
|
||||
pub(super) fn read(d: &[u8]) -> ObjectStyleFrame {
|
||||
let f = |o: usize| f64_at(d, o);
|
||||
pub(super) fn read(enc: Encoding, d: &[u8]) -> ObjectStyleFrame {
|
||||
let f = |o: usize| enc.f64_at(d, o);
|
||||
ObjectStyleFrame {
|
||||
column_fixed_width: f(0),
|
||||
column_gutter: f(8),
|
||||
insets: (|| Some([f(34)?, f(42)?, f(50)?, f(58)?]))(),
|
||||
column_count: u32_at(d, 66),
|
||||
footnotes: (|| Some((u16_at(d, 144)?, f(146)?, f(154)?)))(),
|
||||
column_rule: (|| Some((f(190)?, u32_at(d, 198)?, f(210)?)))(),
|
||||
column_count: enc.u32_at(d, 66),
|
||||
footnotes: (|| Some((enc.u16_at(d, 144)?, f(146)?, f(154)?)))(),
|
||||
column_rule: (|| Some((f(190)?, enc.u32_at(d, 198)?, f(210)?)))(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -403,10 +407,10 @@ pub struct StorySettings {
|
||||
}
|
||||
|
||||
impl StorySettings {
|
||||
pub(super) fn read(d: &[u8]) -> Option<StorySettings> {
|
||||
pub(super) fn read(enc: Encoding, d: &[u8]) -> Option<StorySettings> {
|
||||
Some(StorySettings {
|
||||
orientation: u16_at(d, 0)?,
|
||||
frame_type: u16_at(d, 14)?,
|
||||
orientation: enc.u16_at(d, 0)?,
|
||||
frame_type: enc.u16_at(d, 14)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
+23
-19
@@ -3,7 +3,7 @@
|
||||
use super::{Attrs, Reader, TextRun, Value};
|
||||
use crate::Error;
|
||||
use crate::audit::List;
|
||||
use crate::object::{Cursor, f64_at};
|
||||
use crate::object::{Cursor, Encoding};
|
||||
|
||||
pub mod class {
|
||||
pub const CELL_STYLE: u32 = 0x2021A;
|
||||
@@ -107,8 +107,8 @@ pub struct Table {
|
||||
|
||||
/// Groups of rows or columns sharing attributes: u32 group count; per
|
||||
/// group u32 count, u16, u16 attribute count, attributes, 8 bytes.
|
||||
fn groups(data: &[u8]) -> Result<Vec<(usize, Attrs)>, Error> {
|
||||
let mut c = Cursor::new(data);
|
||||
fn groups(enc: Encoding, data: &[u8]) -> Result<Vec<(usize, Attrs)>, Error> {
|
||||
let mut c = enc.cursor(data);
|
||||
let n = c.u32()?;
|
||||
let mut out = Vec::new();
|
||||
for _ in 0..n {
|
||||
@@ -141,7 +141,7 @@ impl Reader<'_> {
|
||||
fn counted_attrs(&self, uid: u32, id: u32) -> Result<Attrs, Error> {
|
||||
Ok(match self.chunk(uid, id)? {
|
||||
Some(d) if d.len() >= 2 => {
|
||||
let mut c = Cursor::new(&d);
|
||||
let mut c = self.cursor(&d);
|
||||
let n = c.u16()? as usize;
|
||||
Attrs::parse_text(&mut c, n, List::Table)?
|
||||
}
|
||||
@@ -159,9 +159,10 @@ impl Reader<'_> {
|
||||
let Some(data) = self.chunk(uid, super::chunk::STYLE_INFO)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let based_on = Cursor::new(&data[4.min(data.len())..]).u32()?;
|
||||
let based_on = self.cursor(&data[4.min(data.len())..]).u32()?;
|
||||
// A flag byte (1 = built-in name), then a non-empty in-object string.
|
||||
let Some((_, builtin, name)) = super::find_flagged_string(&data, 12, |n| !n.is_empty())
|
||||
let Some((_, builtin, name)) =
|
||||
super::find_flagged_string(self.enc(), &data, 12, |n| !n.is_empty())
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
@@ -179,7 +180,7 @@ impl Reader<'_> {
|
||||
let Some(d) = self.chunk(anchor, chunk::ANCHOR_TABLE)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let uid = Cursor::new(&d).u32()?;
|
||||
let uid = self.cursor(&d).u32()?;
|
||||
if self.class(uid) != Some(class::TABLE) {
|
||||
return Ok(None);
|
||||
}
|
||||
@@ -188,18 +189,18 @@ impl Reader<'_> {
|
||||
|
||||
fn table(&self, uid: u32) -> Result<Table, Error> {
|
||||
let size = self.required(uid, chunk::TABLE_SIZE)?;
|
||||
let mut c = Cursor::new(&size);
|
||||
let mut c = self.cursor(&size);
|
||||
let nrows = c.u32()? as usize;
|
||||
let ncols = c.u32()? as usize;
|
||||
let header_rows = c.u32()?;
|
||||
let footer_rows = c.u32()?;
|
||||
|
||||
let column_groups = match self.chunk(uid, chunk::TABLE_COLUMNS)? {
|
||||
Some(d) => groups(&d)?,
|
||||
Some(d) => groups(self.enc(), &d)?,
|
||||
None => Vec::new(),
|
||||
};
|
||||
let row_groups = match self.chunk(uid, chunk::TABLE_ROWS)? {
|
||||
Some(d) => groups(&d)?,
|
||||
Some(d) => groups(self.enc(), &d)?,
|
||||
None => Vec::new(),
|
||||
};
|
||||
// The cell data has a row of grid positions for every table row,
|
||||
@@ -244,7 +245,7 @@ impl Reader<'_> {
|
||||
|
||||
let cells = cells_from_grid(&grid, &rows, &columns);
|
||||
let style = match self.chunk(uid, chunk::TABLE_STYLE)? {
|
||||
Some(d) => super::uid_or_none(Cursor::new(&d).u32()?),
|
||||
Some(d) => super::uid_or_none(self.cursor(&d).u32()?),
|
||||
None => None,
|
||||
};
|
||||
let attrs = self.counted_attrs(uid, chunk::TABLE_ATTRS)?;
|
||||
@@ -263,7 +264,7 @@ impl Reader<'_> {
|
||||
/// Grid positions by row, from the cell strand's row groups.
|
||||
fn cell_grid(&self, table: u32) -> Result<Vec<Vec<Position>>, Error> {
|
||||
let parts = self.required(table, chunk::TABLE_PARTS)?;
|
||||
let mut c = Cursor::new(&parts);
|
||||
let mut c = self.cursor(&parts);
|
||||
let n = c.u32()?;
|
||||
let mut owner = None;
|
||||
for _ in 0..n {
|
||||
@@ -279,17 +280,17 @@ impl Reader<'_> {
|
||||
let Some(list) = self.chunk(owner, super::chunk::STRAND_DATA)? else {
|
||||
return Ok(grid);
|
||||
};
|
||||
let mut lc = Cursor::new(&list);
|
||||
let mut lc = self.cursor(&list);
|
||||
let count = lc.u16()?;
|
||||
for _ in 0..count {
|
||||
lc.u32()?;
|
||||
let data = self.required(lc.u32()?, super::chunk::STRAND_RUNS)?;
|
||||
let mut r = Cursor::new(&data);
|
||||
let mut r = self.cursor(&data);
|
||||
r.skip(8)?;
|
||||
let groups = r.u16()?;
|
||||
for _ in 0..groups {
|
||||
let size = r.u32()? as usize;
|
||||
let mut g = Cursor::new(r.bytes(size)?);
|
||||
let mut g = self.cursor(r.bytes(size)?);
|
||||
// Attribute sets, each shared by a run of columns: u32
|
||||
// number of columns, u16 1 if attributes follow (u16 count,
|
||||
// attributes), u32 cell style priority, u32 cell style.
|
||||
@@ -334,7 +335,9 @@ impl Reader<'_> {
|
||||
.enumerate()
|
||||
.map(|(k, (id, (aid, value)))| Position {
|
||||
id,
|
||||
size: (aid == attr::CELL).then(|| cell_size(&value)).flatten(),
|
||||
size: (aid == attr::CELL)
|
||||
.then(|| cell_size(self.enc(), &value))
|
||||
.flatten(),
|
||||
covered: aid == attr::COVERED,
|
||||
format: formats.get(k).cloned(),
|
||||
})
|
||||
@@ -349,12 +352,13 @@ impl Reader<'_> {
|
||||
|
||||
/// Attribute records keeping the raw payload of their second value.
|
||||
fn raw_attrs(c: &mut Cursor, n: usize) -> Result<Vec<(u32, Vec<u8>)>, Error> {
|
||||
let enc = c.encoding();
|
||||
let mut out = Vec::with_capacity(n);
|
||||
for _ in 0..n {
|
||||
let id = c.u32()?;
|
||||
let size = c.u16()? as usize;
|
||||
let payload = c.bytes(size)?;
|
||||
let mut p = Cursor::new(payload);
|
||||
let mut p = enc.cursor(payload);
|
||||
let mut second = Vec::new();
|
||||
if size >= 2 {
|
||||
let count = p.u16()?;
|
||||
@@ -373,8 +377,8 @@ fn raw_attrs(c: &mut Cursor, n: usize) -> Result<Vec<(u32, Vec<u8>)>, Error> {
|
||||
}
|
||||
|
||||
/// Text area width and height of a cell record.
|
||||
fn cell_size(v: &[u8]) -> Option<(f64, f64)> {
|
||||
let f = |o: usize| f64_at(v, o);
|
||||
fn cell_size(enc: Encoding, v: &[u8]) -> Option<(f64, f64)> {
|
||||
let f = |o: usize| enc.f64_at(v, o);
|
||||
Some((f(32)?, f(40)?))
|
||||
}
|
||||
|
||||
|
||||
+16
-11
@@ -2,7 +2,7 @@
|
||||
//! (class 0xCA64). See `docs/format/text-variables.md`.
|
||||
|
||||
use crate::Error;
|
||||
use crate::object::{Cursor, Object, u32_at, u32_from};
|
||||
use crate::object::{Cursor, Encoding, Object};
|
||||
|
||||
pub mod chunk {
|
||||
/// Definition: name, text, type and settings.
|
||||
@@ -51,7 +51,7 @@ impl TextVariable {
|
||||
let Some(data) = obj.chunk(chunk::DEFINITION) else {
|
||||
return Ok(None);
|
||||
};
|
||||
parse(uid, data).map(Some)
|
||||
parse(obj.encoding, uid, data).map(Some)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,8 +64,8 @@ fn counted(c: &mut Cursor) -> Result<String, Error> {
|
||||
}
|
||||
|
||||
/// Chunk 0x28BD: name, text, u32 type, then 20 bytes.
|
||||
fn parse(uid: u32, data: &[u8]) -> Result<TextVariable, Error> {
|
||||
let mut c = Cursor::new(data);
|
||||
fn parse(enc: Encoding, uid: u32, data: &[u8]) -> Result<TextVariable, Error> {
|
||||
let mut c = enc.cursor(data);
|
||||
let name = counted(&mut c)?;
|
||||
let text = counted(&mut c)?;
|
||||
let kind = c.u32()?;
|
||||
@@ -76,11 +76,11 @@ fn parse(uid: u32, data: &[u8]) -> Result<TextVariable, Error> {
|
||||
&& match kind {
|
||||
// Dates: the first u32 is 0 or 0xCAB3 in the samples.
|
||||
0xCAA1 | 0xCAAB | 0xCAAC => {
|
||||
(zero(&rest[..4]) || u32_at(rest, 0) == Some(0xCAB3)) && zero(&rest[4..])
|
||||
(zero(&rest[..4]) || enc.u32_at(rest, 0) == Some(0xCAB3)) && zero(&rest[4..])
|
||||
}
|
||||
0xCAC0 => u32_at(rest, 0) == Some(0x8C64) && zero(&rest[4..]),
|
||||
0xCAC0 => enc.u32_at(rest, 0) == Some(0x8C64) && zero(&rest[4..]),
|
||||
0xCAAA => {
|
||||
style = Some(u32_from(rest[4..8].try_into().unwrap()));
|
||||
style = Some(enc.u32_from(rest[4..8].try_into().unwrap()));
|
||||
zero(&rest[..4]) && zero(&rest[8..])
|
||||
}
|
||||
_ => zero(rest) && text.is_empty(),
|
||||
@@ -105,9 +105,10 @@ pub struct Instance {
|
||||
|
||||
impl Instance {
|
||||
pub fn read(uid: u32, obj: &Object) -> Result<Instance, Error> {
|
||||
let enc = obj.encoding;
|
||||
let name = match obj.chunk(chunk::INSTANCE_NAME) {
|
||||
Some(d) if d.len() > 1 => {
|
||||
let mut c = Cursor::new(d);
|
||||
let mut c = enc.cursor(d);
|
||||
c.flag()?;
|
||||
c.string()?
|
||||
}
|
||||
@@ -137,7 +138,7 @@ mod tests {
|
||||
d.extend(0xCAA1u32.to_le_bytes());
|
||||
d.extend([0xB3, 0xCA, 0, 0]);
|
||||
d.extend([0; 16]);
|
||||
let v = parse(0x84, &d).unwrap();
|
||||
let v = parse(crate::object::Encoding::default(), 0x84, &d).unwrap();
|
||||
assert_eq!(v.name, "Output Date");
|
||||
assert_eq!(v.text, "dd.MM.yy");
|
||||
assert_eq!(v.type_name(), Some("OutputDateType"));
|
||||
@@ -152,12 +153,16 @@ mod tests {
|
||||
d.extend([0; 4]);
|
||||
d.extend(0x81u32.to_le_bytes());
|
||||
d.extend([0; 12]);
|
||||
let v = parse(0x89, &d).unwrap();
|
||||
let v = parse(crate::object::Encoding::default(), 0x89, &d).unwrap();
|
||||
assert_eq!(v.style, Some(0x81));
|
||||
assert!(v.as_in_samples);
|
||||
// Another value in a field not identified.
|
||||
let last = d.len() - 1;
|
||||
d[last] = 1;
|
||||
assert!(!parse(0x89, &d).unwrap().as_in_samples);
|
||||
assert!(
|
||||
!parse(crate::object::Encoding::default(), 0x89, &d)
|
||||
.unwrap()
|
||||
.as_in_samples
|
||||
);
|
||||
}
|
||||
}
|
||||
+24
-17
@@ -4,7 +4,7 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::Error;
|
||||
use crate::object::Cursor;
|
||||
use crate::object::Encoding;
|
||||
|
||||
pub mod class {
|
||||
/// Node type of the document node, the parent of the root element.
|
||||
@@ -57,6 +57,7 @@ pub struct Node {
|
||||
|
||||
/// Read the nodes of a store, following the pages from `first_page`.
|
||||
pub fn read_store(
|
||||
enc: Encoding,
|
||||
first_page: u32,
|
||||
mut page_data: impl FnMut(u32) -> Result<Option<Vec<u8>>, Error>,
|
||||
) -> Result<Vec<Node>, Error> {
|
||||
@@ -66,7 +67,7 @@ pub fn read_store(
|
||||
while page != 0 && !seen.contains(&page) {
|
||||
seen.push(page);
|
||||
let Some(data) = page_data(page)? else { break };
|
||||
page = read_page(&data, &mut out)?;
|
||||
page = read_page(enc, &data, &mut out)?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -74,8 +75,8 @@ pub fn read_store(
|
||||
/// One store page (chunk 0x16127): u32 next page, u32 previous page, u32
|
||||
/// story, u32, u32 *n*, *n* node IDs, u32 node count, then the nodes, each
|
||||
/// u32 type, u32 size and the node data. Returns the next page.
|
||||
fn read_page(data: &[u8], out: &mut Vec<Node>) -> Result<u32, Error> {
|
||||
let mut c = Cursor::new(data);
|
||||
fn read_page(enc: Encoding, data: &[u8], out: &mut Vec<Node>) -> Result<u32, Error> {
|
||||
let mut c = enc.cursor(data);
|
||||
let next = c.u32()?;
|
||||
c.skip(12)?;
|
||||
let n = c.u32()? as usize;
|
||||
@@ -86,15 +87,15 @@ fn read_page(data: &[u8], out: &mut Vec<Node>) -> Result<u32, Error> {
|
||||
let size = c.u32()? as usize;
|
||||
let body = c.bytes(size)?;
|
||||
if kind == class::DOCUMENT_NODE || kind == class::ELEMENT {
|
||||
out.push(parse_node(kind, body)?);
|
||||
out.push(parse_node(enc, kind, body)?);
|
||||
}
|
||||
}
|
||||
Ok(next)
|
||||
}
|
||||
|
||||
/// Node data: u16 count, then that many (u32 ID, u32 length, data) parts.
|
||||
fn parse_node(kind: u32, body: &[u8]) -> Result<Node, Error> {
|
||||
let mut c = Cursor::new(body);
|
||||
fn parse_node(enc: Encoding, kind: u32, body: &[u8]) -> Result<Node, Error> {
|
||||
let mut c = enc.cursor(body);
|
||||
let n = c.u16()?;
|
||||
let mut node = None;
|
||||
let mut markers = (NONE, NONE);
|
||||
@@ -105,7 +106,7 @@ fn parse_node(kind: u32, body: &[u8]) -> Result<Node, Error> {
|
||||
match id {
|
||||
chunk::NODE => node = Some(data),
|
||||
chunk::MARKERS if len >= 8 => {
|
||||
let mut m = Cursor::new(data);
|
||||
let mut m = enc.cursor(data);
|
||||
markers = (m.u32()?, m.u32()?);
|
||||
}
|
||||
_ => {}
|
||||
@@ -117,13 +118,13 @@ fn parse_node(kind: u32, body: &[u8]) -> Result<Node, Error> {
|
||||
let fixed = [22, 20, 4]
|
||||
.into_iter()
|
||||
.find(|&n| {
|
||||
let mut c = Cursor::new(data);
|
||||
let mut c = enc.cursor(data);
|
||||
c.skip(n + 24).is_ok()
|
||||
&& c.u32()
|
||||
.is_ok_and(|k| (k as usize).checked_mul(8) == Some(c.remaining()))
|
||||
})
|
||||
.ok_or_else(|| Error::Corrupt("XML node of unknown layout".into()))?;
|
||||
let mut c = Cursor::new(data);
|
||||
let mut c = enc.cursor(data);
|
||||
let tag = c.u32()?;
|
||||
let content = c.u32()?;
|
||||
c.skip(fixed)?;
|
||||
@@ -155,10 +156,10 @@ fn parse_node(kind: u32, body: &[u8]) -> Result<Node, Error> {
|
||||
/// value, u32 marker ID, u32 length (1), u16 flags (1 = has a left child,
|
||||
/// 2 = has a right child). The root's value is its position; a left child
|
||||
/// is *value* before its parent, a right child *value* after it.
|
||||
pub fn marker_positions(data: &[u8]) -> Result<BTreeMap<u32, usize>, Error> {
|
||||
pub fn marker_positions(enc: Encoding, data: &[u8]) -> Result<BTreeMap<u32, usize>, Error> {
|
||||
let bad = || Error::Corrupt("XML marker tree is inconsistent".into());
|
||||
let mut out = BTreeMap::new();
|
||||
let mut c = Cursor::new(data);
|
||||
let mut c = enc.cursor(data);
|
||||
if c.u16()? == 0 {
|
||||
return Ok(out);
|
||||
}
|
||||
@@ -212,12 +213,18 @@ mod tests {
|
||||
d.extend(tree_node(5, 6, 0));
|
||||
d.extend(tree_node(1, 7, 0));
|
||||
d.extend([0x37, 0, 0, 0, 0, 0, 0, 0]);
|
||||
let got: Vec<_> = marker_positions(&d).unwrap().into_iter().collect();
|
||||
let got: Vec<_> = marker_positions(crate::object::Encoding::default(), &d)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.collect();
|
||||
assert_eq!(got, [(5, 7), (6, 2), (7, 9), (9, 8)]);
|
||||
assert!(
|
||||
marker_positions(&[0, 0, 1, 0, 0, 0, 0, 0, 0, 0])
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
marker_positions(
|
||||
crate::object::Encoding::default(),
|
||||
&[0, 0, 1, 0, 0, 0, 0, 0, 0, 0]
|
||||
)
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -241,7 +248,7 @@ mod tests {
|
||||
body.extend(chunk::NODE.to_le_bytes());
|
||||
body.extend((node.len() as u32).to_le_bytes());
|
||||
body.extend(&node);
|
||||
let n = parse_node(class::ELEMENT, &body).unwrap();
|
||||
let n = parse_node(crate::object::Encoding::default(), class::ELEMENT, &body).unwrap();
|
||||
assert_eq!(n.key, (0x9C, 0x1F));
|
||||
assert_eq!(n.parent, (0x9C, 0xF));
|
||||
assert_eq!(n.children, [(0xE4, 4)]);
|
||||
|
||||
+5
-5
@@ -2,7 +2,7 @@
|
||||
//! `docs/format/cross-references.md`.
|
||||
|
||||
use crate::Error;
|
||||
use crate::object::{Cursor, Object};
|
||||
use crate::object::{Cursor, Encoding, Object};
|
||||
|
||||
pub const CLASS: u32 = 0x1355E;
|
||||
pub const CHUNK: u32 = 0x13593;
|
||||
@@ -53,14 +53,14 @@ impl CrossReferenceFormat {
|
||||
let Some(d) = obj.chunk(CHUNK) else {
|
||||
return Ok(None);
|
||||
};
|
||||
parse(uid, d).map(Some)
|
||||
parse(obj.encoding, uid, d).map(Some)
|
||||
}
|
||||
}
|
||||
|
||||
/// Chunk 0x13593: flag byte and name, u32 character style, u16, u32 block
|
||||
/// count, blocks: u32 type, 10 bytes, flag byte and custom text.
|
||||
fn parse(uid: u32, data: &[u8]) -> Result<CrossReferenceFormat, Error> {
|
||||
let mut c = Cursor::new(data);
|
||||
fn parse(enc: Encoding, uid: u32, data: &[u8]) -> Result<CrossReferenceFormat, Error> {
|
||||
let mut c = enc.cursor(data);
|
||||
c.u8()?;
|
||||
let name = c.string()?;
|
||||
let character_style = c.u32()?;
|
||||
@@ -114,7 +114,7 @@ mod tests {
|
||||
d.extend([0; 10]);
|
||||
d.push(1);
|
||||
d.extend(string(""));
|
||||
let f = parse(0xA7, &d).unwrap();
|
||||
let f = parse(crate::object::Encoding::default(), 0xA7, &d).unwrap();
|
||||
assert_eq!(f.name, "Page Number");
|
||||
assert_eq!(f.blocks.len(), 2);
|
||||
assert_eq!(f.blocks[0].text, "page ");
|
||||
|
||||
+126
-114
@@ -3,91 +3,104 @@
|
||||
//! Most objects are a sequence of chunks: u32 chunk ID, u32 length, data.
|
||||
//! Some objects (embedded files, the XMP packet) are plain byte streams.
|
||||
|
||||
use std::cell::Cell;
|
||||
use crate::{ByteOrder, Error, Header, Version};
|
||||
|
||||
use crate::{ByteOrder, Error, Version};
|
||||
|
||||
thread_local! {
|
||||
static BIG_ENDIAN: Cell<bool> = const { Cell::new(false) };
|
||||
static STRING_TAG: Cell<u8> = const { Cell::new(2) };
|
||||
/// How the object data of one file is encoded: its byte order
|
||||
/// (`docs/format/objects.md`) and the first byte of its in-object strings.
|
||||
/// Every decoder of object data takes it from the [`Object`] or [`Cursor`]
|
||||
/// it reads, so files of different encodings can be read at the same time.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Encoding {
|
||||
big_endian: bool,
|
||||
string_tag: u8,
|
||||
}
|
||||
|
||||
/// Object data is in the file's byte order (`docs/format/objects.md`).
|
||||
/// Everything that decodes object data on this thread uses the byte order
|
||||
/// set here, until the returned guard is dropped.
|
||||
pub fn use_byte_order(order: ByteOrder) -> ByteOrderGuard {
|
||||
ByteOrderGuard(BIG_ENDIAN.replace(order == ByteOrder::Big))
|
||||
}
|
||||
|
||||
/// Restores the previous byte order when dropped.
|
||||
pub struct ByteOrderGuard(bool);
|
||||
|
||||
impl Drop for ByteOrderGuard {
|
||||
fn drop(&mut self) {
|
||||
BIG_ENDIAN.set(self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether object data on this thread is big-endian.
|
||||
pub fn big_endian() -> bool {
|
||||
BIG_ENDIAN.get()
|
||||
}
|
||||
|
||||
/// The first byte of an in-object string: 1 in files from InDesign 2.0, 2
|
||||
/// in later files (`docs/format/objects.md`).
|
||||
pub fn string_tag_for(version: Version) -> u8 {
|
||||
if version.major <= 2 { 1 } else { 2 }
|
||||
}
|
||||
|
||||
/// Everything that decodes object data on this thread expects in-object
|
||||
/// strings to start with `tag`, until the returned guard is dropped.
|
||||
pub fn use_string_tag(tag: u8) -> StringTagGuard {
|
||||
StringTagGuard(STRING_TAG.replace(tag))
|
||||
}
|
||||
|
||||
/// Restores the previous string tag when dropped.
|
||||
pub struct StringTagGuard(u8);
|
||||
|
||||
impl Drop for StringTagGuard {
|
||||
fn drop(&mut self) {
|
||||
STRING_TAG.set(self.0);
|
||||
impl Default for Encoding {
|
||||
/// Little-endian, from InDesign 3.0 or later.
|
||||
fn default() -> Encoding {
|
||||
Encoding {
|
||||
big_endian: false,
|
||||
string_tag: 2,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! decoders {
|
||||
($($name:ident, $enc:ident: $t:ty;)*) => {$(
|
||||
/// Decode object data in the current byte order.
|
||||
pub fn $name(b: [u8; size_of::<$t>()]) -> $t {
|
||||
if big_endian() { <$t>::from_be_bytes(b) } else { <$t>::from_le_bytes(b) }
|
||||
($($name:ident, $at:ident, $enc:ident: $t:ty;)*) => {$(
|
||||
/// Decode object data in this byte order.
|
||||
pub fn $name(self, b: [u8; size_of::<$t>()]) -> $t {
|
||||
if self.big_endian { <$t>::from_be_bytes(b) } else { <$t>::from_le_bytes(b) }
|
||||
}
|
||||
/// Encode a value as object data in the current byte order.
|
||||
pub fn $enc(v: $t) -> [u8; size_of::<$t>()] {
|
||||
if big_endian() { v.to_be_bytes() } else { v.to_le_bytes() }
|
||||
/// Decode the value at `offset`, if `b` is long enough.
|
||||
pub fn $at(self, b: &[u8], offset: usize) -> Option<$t> {
|
||||
let end = offset.checked_add(size_of::<$t>())?;
|
||||
Some(self.$name(b.get(offset..end)?.try_into().ok()?))
|
||||
}
|
||||
/// Encode a value as object data in this byte order.
|
||||
pub fn $enc(self, v: $t) -> [u8; size_of::<$t>()] {
|
||||
if self.big_endian { v.to_be_bytes() } else { v.to_le_bytes() }
|
||||
}
|
||||
)*};
|
||||
}
|
||||
|
||||
decoders! {
|
||||
u16_from, u16_bytes: u16;
|
||||
i16_from, i16_bytes: i16;
|
||||
u32_from, u32_bytes: u32;
|
||||
i32_from, i32_bytes: i32;
|
||||
f64_from, f64_bytes: f64;
|
||||
}
|
||||
impl Encoding {
|
||||
/// The encoding of a file with this byte order and version. In-object
|
||||
/// strings start with 1 in files from InDesign 2.0, with 2 in later
|
||||
/// files (`docs/format/objects.md`).
|
||||
pub fn new(order: ByteOrder, version: Version) -> Encoding {
|
||||
Encoding {
|
||||
big_endian: order == ByteOrder::Big,
|
||||
string_tag: if version.major <= 2 { 1 } else { 2 },
|
||||
}
|
||||
}
|
||||
|
||||
/// Decode a u32 at `offset`, if there are four bytes there.
|
||||
pub fn u32_at(b: &[u8], offset: usize) -> Option<u32> {
|
||||
Some(u32_from(b.get(offset..offset + 4)?.try_into().ok()?))
|
||||
}
|
||||
/// The encoding of the file with this header.
|
||||
pub fn of(header: &Header) -> Encoding {
|
||||
Encoding::new(header.byte_order, header.version)
|
||||
}
|
||||
|
||||
/// Decode an f64 at `offset`, if there are eight bytes there.
|
||||
pub fn f64_at(b: &[u8], offset: usize) -> Option<f64> {
|
||||
Some(f64_from(b.get(offset..offset + 8)?.try_into().ok()?))
|
||||
}
|
||||
pub fn big_endian(self) -> bool {
|
||||
self.big_endian
|
||||
}
|
||||
|
||||
/// Decode a u16 at `offset`, if there are two bytes there.
|
||||
pub fn u16_at(b: &[u8], offset: usize) -> Option<u16> {
|
||||
Some(u16_from(b.get(offset..offset + 2)?.try_into().ok()?))
|
||||
/// The first byte of an in-object string.
|
||||
pub fn string_tag(self) -> u8 {
|
||||
self.string_tag
|
||||
}
|
||||
|
||||
/// A cursor over object data in this encoding.
|
||||
pub fn cursor(self, data: &[u8]) -> Cursor<'_> {
|
||||
Cursor {
|
||||
data,
|
||||
pos: 0,
|
||||
tag_read: false,
|
||||
enc: self,
|
||||
}
|
||||
}
|
||||
|
||||
decoders! {
|
||||
u16_from, u16_at, u16_bytes: u16;
|
||||
i16_from, i16_at, i16_bytes: i16;
|
||||
u32_from, u32_at, u32_bytes: u32;
|
||||
i32_from, i32_at, i32_bytes: i32;
|
||||
f64_from, f64_at, f64_bytes: f64;
|
||||
}
|
||||
|
||||
/// Split an object's bytes into chunks. `None` if the bytes are not a
|
||||
/// chunk sequence.
|
||||
pub fn chunks(self, bytes: &[u8]) -> Option<Vec<Chunk<'_>>> {
|
||||
let mut out = Vec::new();
|
||||
let mut pos = 0;
|
||||
while pos < bytes.len() {
|
||||
let head = bytes.get(pos..pos + 8)?;
|
||||
let id = self.u32_from(head[..4].try_into().unwrap());
|
||||
let len = self.u32_from(head[4..].try_into().unwrap()) as usize;
|
||||
let data = bytes.get(pos + 8..(pos + 8).checked_add(len)?)?;
|
||||
out.push(Chunk { id, data });
|
||||
pos += 8 + len;
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -96,33 +109,25 @@ pub struct Chunk<'a> {
|
||||
pub data: &'a [u8],
|
||||
}
|
||||
|
||||
/// Split an object's bytes into chunks. `None` if the bytes are not a
|
||||
/// chunk sequence.
|
||||
pub fn chunks(bytes: &[u8]) -> Option<Vec<Chunk<'_>>> {
|
||||
let mut out = Vec::new();
|
||||
let mut pos = 0;
|
||||
while pos < bytes.len() {
|
||||
let head = bytes.get(pos..pos + 8)?;
|
||||
let id = u32_from(head[..4].try_into().unwrap());
|
||||
let len = u32_from(head[4..].try_into().unwrap()) as usize;
|
||||
let data = bytes.get(pos + 8..pos + 8 + len)?;
|
||||
out.push(Chunk { id, data });
|
||||
pos += 8 + len;
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// A decoded object: its UID, class and chunks.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Object {
|
||||
pub uid: u32,
|
||||
pub class: Option<u32>,
|
||||
pub bytes: Vec<u8>,
|
||||
/// The encoding of the file the object comes from.
|
||||
pub encoding: Encoding,
|
||||
}
|
||||
|
||||
impl Object {
|
||||
pub fn chunks(&self) -> Option<Vec<Chunk<'_>>> {
|
||||
chunks(&self.bytes)
|
||||
self.encoding.chunks(&self.bytes)
|
||||
}
|
||||
|
||||
/// A cursor over `data` (normally a chunk of this object) in the
|
||||
/// object's encoding.
|
||||
pub fn cursor<'d>(&self, data: &'d [u8]) -> Cursor<'d> {
|
||||
self.encoding.cursor(data)
|
||||
}
|
||||
|
||||
/// Data of the first chunk with this ID.
|
||||
@@ -135,7 +140,8 @@ impl Object {
|
||||
}
|
||||
}
|
||||
|
||||
/// Cursor over object data, in the byte order set by [`use_byte_order`].
|
||||
/// Cursor over object data in one [`Encoding`]. Make one with
|
||||
/// [`Encoding::cursor`] or [`Object::cursor`].
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Cursor<'a> {
|
||||
data: &'a [u8],
|
||||
@@ -143,6 +149,7 @@ pub struct Cursor<'a> {
|
||||
/// Big-endian data: [`Cursor::flag`] has read the tag of the next
|
||||
/// string.
|
||||
tag_read: bool,
|
||||
enc: Encoding,
|
||||
}
|
||||
|
||||
fn short(what: &str, pos: usize) -> Error {
|
||||
@@ -150,12 +157,14 @@ fn short(what: &str, pos: usize) -> Error {
|
||||
}
|
||||
|
||||
impl<'a> Cursor<'a> {
|
||||
pub fn new(data: &'a [u8]) -> Cursor<'a> {
|
||||
Cursor {
|
||||
data,
|
||||
pos: 0,
|
||||
tag_read: false,
|
||||
}
|
||||
/// The encoding of the data.
|
||||
pub fn encoding(&self) -> Encoding {
|
||||
self.enc
|
||||
}
|
||||
|
||||
/// A cursor over other data in the same encoding.
|
||||
pub fn sub<'d>(&self, data: &'d [u8]) -> Cursor<'d> {
|
||||
self.enc.cursor(data)
|
||||
}
|
||||
|
||||
pub fn pos(&self) -> usize {
|
||||
@@ -184,19 +193,19 @@ impl<'a> Cursor<'a> {
|
||||
}
|
||||
|
||||
pub fn u16(&mut self) -> Result<u16, Error> {
|
||||
Ok(u16_from(self.bytes(2)?.try_into().unwrap()))
|
||||
Ok(self.enc.u16_from(self.bytes(2)?.try_into().unwrap()))
|
||||
}
|
||||
|
||||
pub fn u32(&mut self) -> Result<u32, Error> {
|
||||
Ok(u32_from(self.bytes(4)?.try_into().unwrap()))
|
||||
Ok(self.enc.u32_from(self.bytes(4)?.try_into().unwrap()))
|
||||
}
|
||||
|
||||
pub fn i32(&mut self) -> Result<i32, Error> {
|
||||
Ok(i32_from(self.bytes(4)?.try_into().unwrap()))
|
||||
Ok(self.enc.i32_from(self.bytes(4)?.try_into().unwrap()))
|
||||
}
|
||||
|
||||
pub fn f64(&mut self) -> Result<f64, Error> {
|
||||
Ok(f64_from(self.bytes(8)?.try_into().unwrap()))
|
||||
Ok(self.enc.f64_from(self.bytes(8)?.try_into().unwrap()))
|
||||
}
|
||||
|
||||
/// A u32 count followed by that many u32 values.
|
||||
@@ -258,8 +267,8 @@ impl<'a> Cursor<'a> {
|
||||
|
||||
/// The flag byte before a string (see [`Cursor::string`]).
|
||||
pub fn flag(&mut self) -> Result<u8, Error> {
|
||||
let tag = STRING_TAG.get();
|
||||
if big_endian() && self.data.get(self.pos) == Some(&tag) && self.remaining() >= 2 {
|
||||
let tag = self.enc.string_tag;
|
||||
if self.enc.big_endian && self.data.get(self.pos) == Some(&tag) && self.remaining() >= 2 {
|
||||
self.tag_read = true;
|
||||
self.pos += 2;
|
||||
return Ok(self.data[self.pos - 1]);
|
||||
@@ -268,7 +277,7 @@ impl<'a> Cursor<'a> {
|
||||
}
|
||||
|
||||
/// A string stored inside object data: u8 2 (1 in files from InDesign
|
||||
/// 2.0, see [`use_string_tag`]), a u8 whose meaning is unknown (usually
|
||||
/// 2.0, see [`Encoding::new`]), a u8 whose meaning is unknown (usually
|
||||
/// 0), u16 length in UTF-16 code units, then segments.
|
||||
///
|
||||
/// The byte before the 2 is often a flag (1 = the string is a built-in
|
||||
@@ -278,8 +287,8 @@ impl<'a> Cursor<'a> {
|
||||
/// instead, the 2 is that byte (`docs/format/big-endian.md`).
|
||||
pub fn string(&mut self) -> Result<String, Error> {
|
||||
let start = self.pos;
|
||||
let expected = STRING_TAG.get();
|
||||
if big_endian() {
|
||||
let expected = self.enc.string_tag;
|
||||
if self.enc.big_endian {
|
||||
if !std::mem::take(&mut self.tag_read) {
|
||||
let before = start.checked_sub(1).map(|i| self.data[i]);
|
||||
if before != Some(expected) && self.u8()? != expected {
|
||||
@@ -317,7 +326,8 @@ mod tests {
|
||||
b.extend_from_slice(&[7, 8]);
|
||||
b.extend_from_slice(&0x15bu32.to_le_bytes());
|
||||
b.extend_from_slice(&0u32.to_le_bytes());
|
||||
let c = chunks(&b).unwrap();
|
||||
let le = Encoding::default();
|
||||
let c = le.chunks(&b).unwrap();
|
||||
assert_eq!(c.len(), 2);
|
||||
assert_eq!(
|
||||
c[0],
|
||||
@@ -327,54 +337,56 @@ mod tests {
|
||||
}
|
||||
);
|
||||
assert!(c[1].data.is_empty());
|
||||
assert!(chunks(&b[..b.len() - 1]).is_none());
|
||||
assert!(le.chunks(&b[..b.len() - 1]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_mixed_segments() {
|
||||
let le = Encoding::default();
|
||||
// "WOMEN’S\r": 5 single-byte, 1 UTF-16, 2 single-byte.
|
||||
let data = [
|
||||
0x05, 0x40, b'W', b'O', b'M', b'E', b'N', 0x01, 0x80, 0x19, 0x20, 0x02, 0x40, b'S',
|
||||
b'\r',
|
||||
];
|
||||
assert_eq!(Cursor::new(&data).segments(8).unwrap(), "WOMEN\u{2019}S\r");
|
||||
assert_eq!(le.cursor(&data).segments(8).unwrap(), "WOMEN\u{2019}S\r");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_object_string() {
|
||||
let le = Encoding::default();
|
||||
let data = [
|
||||
2, 0, 7, 0, 7, 0x40, b'R', b'e', b'g', b'u', b'l', b'a', b'r',
|
||||
];
|
||||
assert_eq!(Cursor::new(&data).string().unwrap(), "Regular");
|
||||
assert_eq!(le.cursor(&data).string().unwrap(), "Regular");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_version_2_string() {
|
||||
let _tag = use_string_tag(string_tag_for(Version { major: 2, minor: 0 }));
|
||||
let le = Encoding::new(ByteOrder::Little, Version { major: 2, minor: 0 });
|
||||
let data = [1, 0, 5, 0, 5, 0x40, b'R', b'o', b'm', b'a', b'n'];
|
||||
assert_eq!(Cursor::new(&data).string().unwrap(), "Roman");
|
||||
assert_eq!(le.cursor(&data).string().unwrap(), "Roman");
|
||||
let data = [2, 0, 5, 0, 5, 0x40, b'R', b'o', b'm', b'a', b'n'];
|
||||
assert!(Cursor::new(&data).string().is_err());
|
||||
assert!(le.cursor(&data).string().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_big_endian_data() {
|
||||
let _order = use_byte_order(ByteOrder::Big);
|
||||
let be = Encoding::new(ByteOrder::Big, Version { major: 4, minor: 0 });
|
||||
// A colour name from the InDesign 4.0 fixture: 2, flag 0, 0, length
|
||||
// 5, then a single-byte segment, and a u32 after it.
|
||||
let data = [
|
||||
2, 0, 0, 0, 5, 0x40, 5, b'B', b'l', b'a', b'c', b'k', 0, 0, 0, 0x0A,
|
||||
];
|
||||
let mut c = Cursor::new(&data);
|
||||
let mut c = be.cursor(&data);
|
||||
assert_eq!(c.flag().unwrap(), 0);
|
||||
assert_eq!(c.string().unwrap(), "Black");
|
||||
assert_eq!(c.u32().unwrap(), 10);
|
||||
// Code that skips the flag byte skips the 2 instead.
|
||||
let mut c = Cursor::new(&data);
|
||||
let mut c = be.cursor(&data);
|
||||
c.skip(1).unwrap();
|
||||
assert_eq!(c.string().unwrap(), "Black");
|
||||
// UTF-16 code units are big-endian too.
|
||||
let data = [0x80, 0x01, 0x5C, 0x0F];
|
||||
assert_eq!(Cursor::new(&data).segments(1).unwrap(), "\u{5C0F}");
|
||||
assert_eq!(be.cursor(&data).segments(1).unwrap(), "\u{5C0F}");
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -170,7 +170,7 @@ fn every_corpus_file_converts() {
|
||||
let mut failures = Vec::new();
|
||||
for p in &files {
|
||||
let bytes = std::fs::read(p).unwrap();
|
||||
match indd::convert(&bytes, "test.indd", std::io::sink()) {
|
||||
match indd::convert_into(&bytes, "test.indd", std::io::sink()) {
|
||||
Err(e) if !known_unreadable(&e) => failures.push(format!("{}: {e}", p.display())),
|
||||
_ => {}
|
||||
}
|
||||
|
||||
+50
-5
@@ -156,7 +156,7 @@ fn big_endian_fixtures_convert() {
|
||||
] {
|
||||
let bytes = std::fs::read(root.join(rel)).unwrap_or_else(|e| panic!("{rel}: {e}"));
|
||||
let mut out = Vec::new();
|
||||
indd::convert(&bytes, "test.indd", &mut out).unwrap_or_else(|e| panic!("{rel}: {e}"));
|
||||
indd::convert_into(&bytes, "test.indd", &mut out).unwrap_or_else(|e| panic!("{rel}: {e}"));
|
||||
assert_eq!(&out[..4], b"PK\x03\x04", "{rel}");
|
||||
let text = String::from_utf8_lossy(&out);
|
||||
for e in expected {
|
||||
@@ -177,7 +177,7 @@ fn little_endian_fixtures_convert() {
|
||||
] {
|
||||
let bytes = std::fs::read(root.join(rel)).unwrap_or_else(|e| panic!("{rel}: {e}"));
|
||||
let mut out = Vec::new();
|
||||
indd::convert(&bytes, "test.indd", &mut out).unwrap_or_else(|e| panic!("{rel}: {e}"));
|
||||
indd::convert_into(&bytes, "test.indd", &mut out).unwrap_or_else(|e| panic!("{rel}: {e}"));
|
||||
assert_eq!(&out[..4], b"PK\x03\x04", "{rel}");
|
||||
assert_eq!(&out[30..38], b"mimetype", "{rel}: mimetype must be first");
|
||||
let text = String::from_utf8_lossy(&out);
|
||||
@@ -195,7 +195,7 @@ fn style_kind_is_a_u16() {
|
||||
};
|
||||
let bytes = std::fs::read(root.join("scml-template/scml.indt")).unwrap();
|
||||
let mut out = Vec::new();
|
||||
indd::convert(&bytes, "test.indd", &mut out).unwrap();
|
||||
indd::convert_into(&bytes, "test.indd", &mut out).unwrap();
|
||||
let text = String::from_utf8_lossy(&out);
|
||||
assert!(text.contains(r#"<CharacterStyle Self="CharacterStyle/abbr" Name="abbr" "#));
|
||||
// The u16 after the kind is the imported flag.
|
||||
@@ -217,7 +217,6 @@ fn audit_accounts_for_every_object() {
|
||||
let a = indd::audit::audit(&bytes, rel).unwrap_or_else(|e| panic!("{rel}: {e}"));
|
||||
assert_eq!(a.error, None, "{rel}");
|
||||
let c = indd::Container::parse(&bytes).unwrap();
|
||||
let _order = indd::object::use_byte_order(c.header.byte_order);
|
||||
let db = c.database().unwrap();
|
||||
let with_data = db
|
||||
.uids()
|
||||
@@ -228,7 +227,53 @@ fn audit_accounts_for_every_object() {
|
||||
// The document object is always read.
|
||||
assert!(a.classes[&Some(0xE01)].read > 0, "{rel}");
|
||||
// Auditing reports the same warnings as converting.
|
||||
let warnings = indd::convert(&bytes, rel, std::io::sink()).unwrap();
|
||||
let warnings: Vec<String> = indd::convert(&bytes, rel)
|
||||
.unwrap()
|
||||
.warnings
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect();
|
||||
assert_eq!(a.warnings, warnings, "{rel}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Big- and little-endian files converted at the same time on several
|
||||
/// threads give the same packages and warnings as converted one by one:
|
||||
/// a conversion keeps no global or thread-local state.
|
||||
#[test]
|
||||
fn conversions_on_several_threads_are_independent() {
|
||||
let Some(root) = fixtures() else {
|
||||
return;
|
||||
};
|
||||
let files: Vec<Vec<u8>> = [
|
||||
"opf-neddy-flyer/Neddy_Flyer_HeatherRyan.indd",
|
||||
"scml-template/scml.indt",
|
||||
"xmp-toolkit-bluesquare/BlueSquare.indd",
|
||||
"lizdenys-minizine/indesign-minizine-template.indd",
|
||||
]
|
||||
.iter()
|
||||
.map(|rel| std::fs::read(root.join(rel)).unwrap())
|
||||
.collect();
|
||||
let one_by_one: Vec<_> = files
|
||||
.iter()
|
||||
.map(|b| indd::convert(b, "test.indd").unwrap())
|
||||
.collect();
|
||||
let parallel: Vec<_> = std::thread::scope(|s| {
|
||||
let handles: Vec<_> = files
|
||||
.iter()
|
||||
.map(|b| s.spawn(move || indd::convert(b, "test.indd").unwrap()))
|
||||
.collect();
|
||||
handles.into_iter().map(|h| h.join().unwrap()).collect()
|
||||
});
|
||||
for (a, b) in one_by_one.iter().zip(¶llel) {
|
||||
assert_eq!(a.idml, b.idml);
|
||||
assert_eq!(a.warnings, b.warnings);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn results_can_be_sent_between_threads() {
|
||||
fn send_sync<T: Send + Sync>() {}
|
||||
send_sync::<indd::Conversion>();
|
||||
send_sync::<indd::Error>();
|
||||
}
|
||||
Reference in new issue
Block a user