//! Placing a Word 97-2003 document (`.doc`): its main text set as area type with the character and //! paragraph formatting VectorCraft has, read as \[MS-DOC\] describes the Word Binary File Format //! () //! from the compound file \[MS-CFB\] describes //! (). //! //! - The `WordDocument` stream starts with the file information block (FIB, §2.5.1), which locates //! the structures read from the `0Table` or `1Table` stream (`fWhichTblStm`). Documents saved by //! Word 97 and later (`nFib` 0x00C1 and above) are read; older ones, encrypted or obfuscated ones //! and ones last saved with fast save (`fComplex`) are refused. //! - Text: the main document's `ccpText` characters, from the pieces the Clx's PlcPcd lists //! (§2.9.38, §2.8.35) in their order, each in 16-bit Unicode or in compressed 8-bit text with the //! mapping §2.9.73 gives; 16-bit text with half of a surrogate pair is refused. A paragraph mark //! (U+000D) ends a paragraph, and so does a page or section break (U+000C) at the end of a //! paragraph's properties (PapxFkp); a line break //! (U+000B) starts a new paragraph in the same formatting. A table's cells (cell marks, U+0007) //! are separated by tabs and each row (a table terminating mark) is a paragraph. Tabs are tabs, //! and U+001E and U+001F are the nonbreaking and optional hyphens. Of a field (U+0013, U+0014 and //! U+0015), its result is read. //! - Character formatting: the font (`sprmCRgFtc0`, named by the font table SttbfFfn), the size, //! bold, italic, underline (every style but none), strikethrough and double strikethrough, all //! caps, small caps, superscript and subscript, raised and lowered text (`sprmCHpsPos`) and the //! color (`sprmCIco`, `sprmCCv`). //! - Paragraph formatting: alignment (`sprmPJc80`, then `sprmPJc`: start and end follow the //! direction, and the kashida alignments are justified with Short, Medium or Long kashidas), the //! left and right indents (the physical ones Word 97 writes, unless the logical ones later //! versions write are given), first-line indent, space before and after, and direction //! (`sprmPFBiDi`). //! - Formatting is resolved as "Determining Formatting Properties" describes: the style sheet's //! default font and 10 pt, then the paragraph style (STSH, §2.9.271) and the styles it is based //! on, then the run's character style (`sprmCIstd`) and the styles it is based on, then the //! direct formatting of the run (Chpx) and of the paragraph (Papx). A toggle operand of 0x80 or //! 0x81 takes or reverses the value the styles give. //! //! Hidden text, deleted revisions, field instructions, pictures and embedded objects, note and //! comment references and the other stories (footnotes, endnotes, headers, footers, comments and //! text boxes) are left out. The reply's warnings name each kind of content that was left out or //! changed, once: pictures and objects, fields, fields left out (no result, or nested too deep), the //! other stories, tracked changes and tables. A stream larger than [`MAX_STREAM`] bytes, a main //! text longer than [`text::MAX_TEXT`] characters, more than [`MAX_PIECES`] pieces or //! [`MAX_PAGES`] property pages, more than [`MAX_RUNS`] runs of character or of paragraph //! properties, more than [`MAX_PRL_BYTES`] bytes of properties in the styles and property runs, //! more than [`MAX_PARAGRAPHS`] paragraphs (hidden and deleted ones and those in field //! instructions included), and placed type of more than [`MAX_RUNS`] runs are refused, and so are //! a structure that lies outside its stream, property pages whose runs are listed twice or //! overlap, and styles based on each other in a loop. use std::io::{Cursor, Read}; use vectorcraft_doc::text::Kashida; use vectorcraft_doc::{CharPosition, CharStyle, Justify, ParaDirection, ParaStyle, ScriptMetrics, TextRun}; use super::text::{self, Story}; use super::{EngineError, Paint, Result, bad, fileio}; /// Word 97-2003 documents as `file.place` reports them (not a format `document.open` reads). pub(super) const FORMAT: fileio::Format = fileio::Format { id: "doc", label: "Word 97-2003", extensions: fileio::DOC_EXTS, mime: "application/msword", read: true, write: false, raster: false, options: &[], }; /// The first bytes of a compound file (\[MS-CFB\] §2.2). const SIGNATURE: [u8; 8] = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]; /// The most bytes a stream read from the compound file may hold. const MAX_STREAM: u64 = 64 << 20; /// The most pieces the main text may be made of. const MAX_PIECES: usize = 100_000; /// The most 512-byte pages of character or of paragraph properties read. const MAX_PAGES: usize = 16_384; /// The style count `Stshif.cstd` must be below. const MAX_STYLES: usize = 0x0FFE; /// The most fonts read from the font table (SttbfFfn's `cData` is at most 0x7FF0). const MAX_FONTS: usize = 0x7FF0; /// The most bytes of a font name kept. const MAX_NAME: usize = 256; /// The most paragraphs placed type takes from one Word document. const MAX_PARAGRAPHS: usize = 100_000; /// The most runs of one character formatting placed type takes from one Word document, and the /// most runs of character or of paragraph properties read from its property pages. const MAX_RUNS: usize = 100_000; /// The most bytes of properties (Prls) read from the style sheet's styles and the property runs; /// each style's and each run's properties are applied once. const MAX_PRL_BYTES: usize = 16 << 20; /// The deepest nesting of fields read; deeper ones are left out with their results. const MAX_FIELDS: usize = 64; /// `istdBase` of a style that is based on none. const NO_STYLE: u16 = 0x0FFF; /// The FibRgFcLcb97 pairs read (§2.5.6), by their index. const STSHF: usize = 1; const PLCF_BTE_CHPX: usize = 12; const PLCF_BTE_PAPX: usize = 13; const STTBF_FFN: usize = 15; const CLX: usize = 33; /// The number of pairs FibRgFcLcb97 holds. const FC_LCB_97: u16 = 0x005D; /// Is the file `name` with `bytes` a Word 97-2003 document: a compound file named `.doc`, or one /// that holds a `WordDocument` stream? pub(super) fn is_doc(name: &str, bytes: &[u8]) -> bool { bytes.starts_with(&SIGNATURE) && (fileio::DOC_EXTS.contains(&fileio::extension(name).as_str()) || cfb::CompoundFile::open(Cursor::new(bytes)).is_ok_and(|f| f.is_stream("/WordDocument"))) } /// The main text of a Word 97-2003 document's `bytes` (a compound file) with its character and /// paragraph formatting, and a warning for each kind of content left out or changed. pub(super) fn import(bytes: &[u8], cmd: &str) -> Result<(Story, Vec)> { let mut file = cfb::CompoundFile::open(Cursor::new(bytes)).map_err(|_| damaged(cmd, "its compound file structure is damaged"))?; let wd = stream(&mut file, "WordDocument", cmd)?.ok_or_else(|| bad(cmd, "not a Word document: its compound file has no WordDocument stream"))?; let fib = Fib::read(&wd, cmd)?; let table_name = if fib.table_one { "1Table" } else { "0Table" }; let table = stream(&mut file, table_name, cmd)?.ok_or_else(|| damaged(cmd, format!("it has no {table_name} stream")))?; let clx = fib.part(&table, CLX, cmd)?.ok_or_else(|| damaged(cmd, "it has no piece table"))?; let text = main_text(&wd, &pieces(clx, cmd)?, fib.ccp_text, cmd)?; let mut prl_left = MAX_PRL_BYTES; let chpx = match fib.part(&table, PLCF_BTE_CHPX, cmd)? { Some(plc) => runs(&wd, plc, Fkp::Chpx, &mut prl_left, cmd)?, None => vec![], }; let papx = match fib.part(&table, PLCF_BTE_PAPX, cmd)? { Some(plc) => runs(&wd, plc, Fkp::Papx, &mut prl_left, cmd)?, None => vec![], }; let sheet = match fib.part(&table, STSHF, cmd)? { Some(stsh) => Sheet::read(stsh, &mut prl_left, cmd)?, None => Sheet::default(), }; let fonts = match fib.part(&table, STTBF_FFN, cmd)? { Some(sttb) => fonts(sttb, cmd)?, None => vec![], }; let mut r = Reader::new(&sheet, &fonts); r.read(&text, &chpx, &papx); let warnings = r.warnings(&fib); Ok((r.finish(cmd)?, warnings)) } /// The error for a Word document whose structures can't be read. fn damaged(cmd: &str, why: impl std::fmt::Display) -> EngineError { bad(cmd, format!("can't read this Word document: {why}")) } /// Takes `bytes` of properties from `left`, the bytes of the [`MAX_PRL_BYTES`] not yet read; an /// error when fewer are left. fn spend(left: &mut usize, bytes: usize, cmd: &str) -> Result<()> { *left = left .checked_sub(bytes) .ok_or_else(|| bad(cmd, format!("the Word document has more than {} MB of formatting properties, too many to place", MAX_PRL_BYTES >> 20)))?; Ok(()) } /// The stream `name` of the compound file; None when it has no such stream. fn stream(file: &mut cfb::CompoundFile>, name: &str, cmd: &str) -> Result>> { if !file.is_stream(name) { return Ok(None); } let s = file.open_stream(name).map_err(|_| damaged(cmd, format!("its {name} stream is damaged")))?; if s.len() > MAX_STREAM { return Err(bad(cmd, format!("the Word document is too large to place (its {name} stream holds more than {} MB)", MAX_STREAM >> 20))); } let mut out = vec![]; s.take(MAX_STREAM).read_to_end(&mut out).map_err(|_| damaged(cmd, format!("its {name} stream is damaged")))?; Ok(Some(out)) } /// The little-endian 16-bit integer at `at`. fn u16_at(b: &[u8], at: usize) -> Option { b.get(at..at.checked_add(2)?).and_then(|s| s.try_into().ok()).map(u16::from_le_bytes) } /// The little-endian 32-bit integer at `at`. fn u32_at(b: &[u8], at: usize) -> Option { b.get(at..at.checked_add(4)?).and_then(|s| s.try_into().ok()).map(u32::from_le_bytes) } /// `len` bytes of `b` from `at`. fn bytes_at(b: &[u8], at: usize, len: usize) -> Option<&[u8]> { b.get(at..at.checked_add(len)?) } /// What the reader takes from the file information block. struct Fib { /// The table stream is `1Table` (else `0Table`). table_one: bool, /// The main document's length in characters. ccp_text: u32, /// The lengths of the footnotes, headers and footers, comments, endnotes, text boxes and /// header text boxes (`ccpFtn`, `ccpHdd`, `ccpAtn`, `ccpEdn`, `ccpTxbx`, `ccpHdrTxbx`). stories: [u32; 6], /// FibRgFcLcb's offset and size pairs. fc_lcb: Vec<(u32, u32)>, } impl Fib { /// The FIB at the start of the WordDocument stream `wd` (§2.5.1). fn read(wd: &[u8], cmd: &str) -> Result { if u16_at(wd, 0) != Some(0xA5EC) { return Err(bad(cmd, "not a Word document: its WordDocument stream doesn't start with a file information block")); } let field = |at: usize| u16_at(wd, at).ok_or_else(|| damaged(cmd, "its file information block is cut short")); if field(2)? < 0x00C1 { return Err(bad( cmd, "the Word document was saved by Word 6.0 or Word 95, which VectorCraft doesn't read; save it as a Word 97-2003 document", )); } let flags = field(10)?; // fEncrypted (fObfuscated only says how). if flags & 0x0100 != 0 { return Err(bad(cmd, "the Word document is encrypted or protected with a password; save it without one to place it")); } // fComplex: the last save was an incremental (fast) save. if flags & 0x0004 != 0 { return Err(bad( cmd, "the Word document was last saved with fast save, which VectorCraft doesn't read; save it again with fast save turned off", )); } // csw (14 16-bit values) and cslw (22 32-bit values) are fixed. if field(32)? != 0x000E || field(62)? != 0x0016 { return Err(damaged(cmd, "its file information block is damaged")); } let count = field(152)?; if count < FC_LCB_97 { return Err(damaged(cmd, "its file information block is damaged")); } let pair = |i: usize| Some((u32_at(wd, 154 + 8 * i)?, u32_at(wd, 158 + 8 * i)?)); let fc_lcb = (0..usize::from(count)).map(pair).collect::>>().ok_or_else(|| damaged(cmd, "its file information block is cut short"))?; // FibRgLw97 starts at 64: ccpText is its fourth value. let lw = |i: usize| u32_at(wd, 64 + 4 * i).unwrap_or_default(); Ok(Self { table_one: flags & 0x0200 != 0, ccp_text: lw(3), stories: [lw(4), lw(5), lw(7), lw(8), lw(9), lw(10)], fc_lcb }) } /// The structure FibRgFcLcb's pair `index` locates in the table stream `table`; None when it /// is empty. fn part<'a>(&self, table: &'a [u8], index: usize, cmd: &str) -> Result> { let Some(&(fc, lcb)) = self.fc_lcb.get(index).filter(|(_, lcb)| *lcb > 0) else { return Ok(None) }; bytes_at(table, fc as usize, lcb as usize).map(Some).ok_or_else(|| damaged(cmd, "a table it lists lies outside its table stream")) } } /// A piece of the text (Pcd): characters `cp..end`, stored from file position `fc`. struct Piece { cp: u32, end: u32, fc: u32, /// Compressed 8-bit text (else 16-bit Unicode). compressed: bool, } /// The pieces the Clx `clx` lists (§2.9.38), in character order. fn pieces(clx: &[u8], cmd: &str) -> Result> { let broken = || damaged(cmd, "its piece table is damaged"); let mut at = 0usize; // Prc records (property modifiers for pieces) come first. while clx.get(at) == Some(&0x01) { let size = u16_at(clx, at + 1).map(|v| v as i16).filter(|v| *v >= 0).ok_or_else(broken)?; at += 3 + size as usize; } if clx.get(at) != Some(&0x02) { return Err(broken()); } let lcb = u32_at(clx, at + 1).ok_or_else(broken)? as usize; let plc = bytes_at(clx, at + 5, lcb).ok_or_else(broken)?; if lcb < 4 || !(lcb - 4).is_multiple_of(12) { return Err(broken()); } let n = (lcb - 4) / 12; if n > MAX_PIECES { return Err(bad(cmd, format!("the Word document's text is made of more than {MAX_PIECES} pieces, too many to place"))); } let mut out = Vec::with_capacity(n); for i in 0..n { let (cp, end) = (u32_at(plc, 4 * i).ok_or_else(broken)?, u32_at(plc, 4 * i + 4).ok_or_else(broken)?); // A Pcd: 2 bytes of flags, then FcCompressed (fc in bits 0 to 29, fCompressed in bit 30). let raw = u32_at(plc, 4 * (n + 1) + 8 * i + 2).ok_or_else(broken)?; if end <= cp || out.last().is_some_and(|p: &Piece| p.end != cp) || (i == 0 && cp != 0) { return Err(broken()); } let compressed = raw & 0x4000_0000 != 0; let fc = raw & 0x3FFF_FFFF; out.push(Piece { cp, end, fc: if compressed { fc / 2 } else { fc }, compressed }); } Ok(out) } /// A character of the main text: the character, the file position of its bytes, and their number. type Char = (char, u32, u8); /// The first `ccp` characters of the pieces, read from the WordDocument stream `wd`. fn main_text(wd: &[u8], pieces: &[Piece], ccp: u32, cmd: &str) -> Result> { if ccp as usize > text::MAX_TEXT { return Err(bad(cmd, format!("the Word document has too much text to place as type (at most {} MB)", text::MAX_TEXT >> 20))); } if pieces.last().is_none_or(|p| p.end < ccp) { return Err(damaged(cmd, "its piece table doesn't cover its text")); } let outside = || damaged(cmd, "a piece of its text lies outside its WordDocument stream"); // Each character position's UTF-16 code unit, file position and byte count, in character // order; a surrogate pair may be split between two pieces. let mut units: Vec<(u16, u32, u8)> = Vec::with_capacity(ccp as usize); for p in pieces.iter().take_while(|p| p.cp < ccp) { let n = (p.end.min(ccp) - p.cp) as usize; if p.compressed { let b = bytes_at(wd, p.fc as usize, n).ok_or_else(outside)?; // Every character compressed text maps to is in the Basic Multilingual Plane. units.extend(b.iter().zip(p.fc..).map(|(&c, fc)| (u16::try_from(u32::from(compressed(c))).unwrap_or(0xFFFD), fc, 1))); continue; } let b = bytes_at(wd, p.fc as usize, n.checked_mul(2).ok_or_else(outside)?).ok_or_else(outside)?; units.extend(b.as_chunks::<2>().0.iter().zip((p.fc..).step_by(2)).map(|(&u, fc)| (u16::from_le_bytes(u), fc, 2))); } let mut out = Vec::with_capacity(units.len()); let mut i = 0; while let Some(&(u, fc, width)) = units.get(i) { let low = units.get(i + 1).map(|&(low, _, w)| (low, w)).filter(|(low, _)| (0xD800..0xDC00).contains(&u) && (0xDC00..0xE000).contains(low)); let c = match low { Some((low, _)) => char::decode_utf16([u, low]).next().and_then(|c| c.ok()), None => char::from_u32(u32::from(u)), }; let c = c.ok_or_else(|| damaged(cmd, "its text holds half of a UTF-16 surrogate pair"))?; out.push((c, fc, low.map_or(width, |(_, w)| width + w))); i += if low.is_some() { 2 } else { 1 }; } Ok(out) } /// Byte `b` of compressed text (§2.9.73): the byte as a Unicode character, except the ones that /// stand for these. fn compressed(b: u8) -> char { const MAPPED: [(u8, char); 24] = [ (0x82, '\u{201A}'), (0x83, '\u{0192}'), (0x84, '\u{201E}'), (0x85, '\u{2026}'), (0x86, '\u{2020}'), (0x87, '\u{2021}'), (0x88, '\u{02C6}'), (0x89, '\u{2030}'), (0x8A, '\u{0160}'), (0x8B, '\u{2039}'), (0x8C, '\u{0152}'), (0x91, '\u{2018}'), (0x92, '\u{2019}'), (0x93, '\u{201C}'), (0x94, '\u{201D}'), (0x95, '\u{2022}'), (0x96, '\u{2013}'), (0x97, '\u{2014}'), (0x98, '\u{02DC}'), (0x99, '\u{2122}'), (0x9A, '\u{0161}'), (0x9B, '\u{203A}'), (0x9C, '\u{0153}'), (0x9F, '\u{0178}'), ]; MAPPED.iter().find(|(k, _)| *k == b).map_or(char::from(b), |(_, c)| *c) } /// Which property pages a bin table points to. #[derive(Clone, Copy, PartialEq)] enum Fkp { /// ChpxFkp (§2.9.33): character properties. Chpx, /// PapxFkp (§2.9.174): paragraph properties. Papx, } /// The file positions `start..end` and the properties a property page gives them. struct Run<'a> { start: u32, end: u32, /// The paragraph style (Papx only). istd: u16, /// The properties, in their property page. grpprl: &'a [u8], } /// The runs of the property pages the bin table `plc` (PlcBteChpx or PlcBtePapx) points to, in /// the WordDocument stream `wd`, ordered by file position. The bin table's file positions rise /// ("MUST be sorted in ascending order", and a PlcBteChpx "MUST NOT contain duplicate stream /// offsets"), and so do the runs of its pages one after another: a page listed twice, or pages /// whose runs overlap, are damaged. More than [`MAX_RUNS`] runs are refused, and each run's /// properties are taken from `prl_left`. fn runs<'a>(wd: &'a [u8], plc: &[u8], kind: Fkp, prl_left: &mut usize, cmd: &str) -> Result>> { let broken = || damaged(cmd, "its character or paragraph properties are damaged"); if plc.len() < 4 || !(plc.len() - 4).is_multiple_of(8) { return Err(broken()); } let n = (plc.len() - 4) / 8; if n > MAX_PAGES { return Err(bad(cmd, format!("the Word document has more than {MAX_PAGES} pages of properties, too many to place"))); } let fcs = (0..=n).map(|i| u32_at(plc, 4 * i)).collect::>>().ok_or_else(broken)?; if fcs.windows(2).any(|w| w.first() >= w.get(1)) { return Err(broken()); } let mut out: Vec> = vec![]; for i in 0..n { // PnFkpChpx and PnFkpPapx: the page number in bits 0 to 21. let pn = u32_at(plc, 4 * (n + 1) + 4 * i).ok_or_else(broken)? & 0x003F_FFFF; let page = bytes_at(wd, pn as usize * 512, 512).ok_or_else(broken)?; let first = out.len(); page_runs(page, kind, &mut out).ok_or_else(broken)?; // A page's own runs rise (rgfc); its first starts at or after the end of the page before. let before = first.checked_sub(1).and_then(|k| out.get(k)).map(|r| r.end); if before.zip(out.get(first)).is_some_and(|(end, r)| r.start < end) { return Err(broken()); } if out.len() > MAX_RUNS { return Err(bad(cmd, format!("the Word document has more than {MAX_RUNS} runs of character or paragraph properties, too many to place"))); } spend(prl_left, out.get(first..).unwrap_or_default().iter().map(|r| r.grpprl.len()).sum(), cmd)?; } Ok(out) } /// The runs of one 512-byte property page; None when it is damaged. fn page_runs<'a>(page: &'a [u8], kind: Fkp, out: &mut Vec>) -> Option<()> { let count = usize::from(*page.get(511)?); let most = if kind == Fkp::Chpx { 0x65 } else { 0x1D }; if count == 0 || count > most { return None; } for i in 0..count { let (start, end) = (u32_at(page, 4 * i)?, u32_at(page, 4 * i + 4)?); // ChpxFkp's rgb: one byte each; PapxFkp's rgbx: 13-byte BxPap, its first byte the offset. let entry = 4 * (count + 1) + if kind == Fkp::Chpx { i } else { 13 * i }; let offset = usize::from(*page.get(entry)?) * 2; let (istd, grpprl) = match (offset, kind) { (0, _) => (0, &[][..]), (_, Fkp::Chpx) => { let cb = usize::from(*page.get(offset)?); (0, bytes_at(page, offset + 1, cb).filter(|_| offset + 1 + cb <= 511)?) } (_, Fkp::Papx) => { // PapxInFkp: 2 × cb − 1 bytes, or (cb = 0) 2 × cb′ bytes after cb′. let (at, len) = match usize::from(*page.get(offset)?) { 0 => (offset + 2, usize::from(*page.get(offset + 1)?) * 2), cb => (offset + 1, 2 * cb - 1), }; let grp = bytes_at(page, at, len).filter(|_| at + len <= 511 && len >= 2)?; (u16_at(grp, 0)?, grp.get(2..)?) } }; // rgfc "MUST be sorted in ascending order and MUST NOT contain duplicates": each run ends // where the next starts. if end <= start { return None; } out.push(Run { start, end, istd, grpprl }); } Some(()) } /// The run of `runs` (ordered by file position) that holds file position `fc`. fn run_at(runs: &[Run], fc: u32) -> Option { let i = runs.partition_point(|r| r.start <= fc).checked_sub(1)?; runs.get(i).filter(|r| fc < r.end).map(|_| i) } /// The size of the operand of `sprm` (§2.2.5.1) whose bytes start `rest`. fn operand_len(sprm: u16, rest: &[u8]) -> Option { Some(match sprm >> 13 { 0 | 1 => 1, 2 | 4 | 5 => 2, 3 => 4, 7 => 3, // sprmTDefTable: a 2-byte size of the rest, plus 1. _ if sprm == 0xD608 => usize::from(u16_at(rest, 0)?) + 1, // sprmPChgTabs with cb 255: the deleted tabs with their close tolerances, then the added // tabs with their descriptors. _ if sprm == 0xC615 && rest.first() == Some(&255) => { let deleted = usize::from(*rest.get(1)?); let added = usize::from(*rest.get(2 + 4 * deleted)?); 3 + 4 * deleted + 3 * added } _ => usize::from(*rest.first()?) + 1, }) } /// Calls `f` with each Prl of `grpprl`: its sprm and its operand. fn each_prl(grpprl: &[u8], mut f: impl FnMut(u16, &[u8])) { let mut at = 0; while let Some(sprm) = u16_at(grpprl, at) { let rest = grpprl.get(at + 2..).unwrap_or_default(); let Some((n, op)) = operand_len(sprm, rest).and_then(|n| Some((n, rest.get(..n)?))) else { return }; // A variable operand's bytes follow its size. let op = if sprm >> 13 == 6 && !matches!(sprm, 0xD608 | 0xC615) { op.get(1..).unwrap_or_default() } else { op }; f(sprm, op); at += 2 + n; } } /// A style of the style sheet. struct Style { /// 1: paragraph style, 2: character style. stk: u8, base: u16, papx: Vec, chpx: Vec, } /// The style sheet: each style's formatting with that of the styles it is based on, by istd, and /// its default font. #[derive(Default)] struct Sheet { /// Paragraph styles: their paragraph formatting and their text's. paragraph: Vec>, /// Character styles: what they do to the formatting of the text they are applied to. character: Vec>, /// `Stshif.ftcAsci`. font: Option, } impl Sheet { /// The style sheet STSH (§2.9.271); its styles' properties are taken from `prl_left`. fn read(stsh: &[u8], prl_left: &mut usize, cmd: &str) -> Result { let broken = || damaged(cmd, "its style sheet is damaged"); let size = usize::from(u16_at(stsh, 0).ok_or_else(broken)?); let stshi = bytes_at(stsh, 2, size).ok_or_else(broken)?; let count = usize::from(u16_at(stshi, 0).ok_or_else(broken)?); if count >= MAX_STYLES { return Err(broken()); } // cbSTDBaseInFile: StdfBase, and StdfPost2000 when it is 18. let base_size = usize::from(u16_at(stshi, 2).ok_or_else(broken)?).max(10); let font = u16_at(stshi, 12); let mut at = 2 + size; let mut styles = Vec::with_capacity(count); for _ in 0..count { let len = u16_at(stsh, at).ok_or_else(broken)?; let std = bytes_at(stsh, at + 2, usize::from(len)).ok_or_else(broken)?; styles.push(if std.is_empty() { None } else { Some(style(std, base_size).ok_or_else(broken)?) }); // LPStd records start on even offsets. at += 2 + usize::from(len) + usize::from(len) % 2; } spend(prl_left, styles.iter().flatten().map(|s| s.papx.len() + s.chpx.len()).sum(), cmd)?; let root = (Para::default(), Chars { font, ..Chars::default() }); let paragraph = resolve(&styles, 1, root, |(mut para, chars), s| { para.apply(&s.papx); (para, chars.with(&CharsChange::of(&s.chpx))) }) .ok_or_else(broken)?; let character = resolve(&styles, 2, CharsChange::default(), |change, s| change.then(&CharsChange::of(&s.chpx))).ok_or_else(broken)?; Ok(Self { paragraph, character, font }) } /// Paragraph style `istd`'s paragraph formatting and its text's; the document defaults when /// it is no paragraph style. fn paragraph_style(&self, istd: u16) -> (Para, Chars) { self.paragraph.get(usize::from(istd)).copied().flatten().unwrap_or((Para::default(), Chars { font: self.font, ..Chars::default() })) } /// What character style `istd` does to text; nothing when it is no character style. fn character_style(&self, istd: u16) -> CharsChange { self.character.get(usize::from(istd)).copied().flatten().unwrap_or_default() } } /// The formatting of each style of `styles` of kind `stk` with that of the styles it is based on: /// `root` with `own` applied for each style of its chain of `istdBase`, the first of the chain /// first. Each style's formatting is worked out once, on that of the style it is based on. A chain /// ends at a style of another kind or none. None when `istdBase` makes a loop (which it "MUST /// NOT", StdfBase). fn resolve(styles: &[Option