diff --git a/crates/docx/src/write.rs b/crates/docx/src/write.rs index 4ba486a6c..3153534f7 100644 --- a/crates/docx/src/write.rs +++ b/crates/docx/src/write.rs @@ -2,6 +2,7 @@ mod bidi; mod embed; +mod font_table; mod glossary; mod settings_merge; pub(crate) use settings_merge::has_unowned as settings_has_unowned; diff --git a/crates/docx/src/write/embed.rs b/crates/docx/src/write/embed.rs index 7673a6f26..939d2a2d7 100644 --- a/crates/docx/src/write/embed.rs +++ b/crates/docx/src/write/embed.rs @@ -102,12 +102,13 @@ impl<'d> EmbedWriter<'d> { } /// Write the font table kept from a file, with the fonts it embeds, relating it from `rels`. - pub fn font_table(&mut self, rels: &mut PartRels) { + /// Whether there was one to write. + pub fn font_table(&mut self, rels: &mut PartRels) -> bool { let mut written = Vec::new(); - let Some(root) = crate::package::font_table_key(self.passthrough).map(str::to_string) else { return }; - if let Some(name) = self.copy_tree(&root, &mut HashMap::new(), &mut written) { - rels.add(rt::FONT_TABLE, &relative(STORY_PART, &name), false); - } + let Some(root) = crate::package::font_table_key(self.passthrough).map(str::to_string) else { return false }; + let Some(name) = self.copy_tree(&root, &mut HashMap::new(), &mut written) else { return false }; + rels.add(rt::FONT_TABLE, &relative(STORY_PART, &name), false); + true } /// Reserve the names of the media files this writer writes. diff --git a/crates/docx/src/write/font_table.rs b/crates/docx/src/write/font_table.rs new file mode 100644 index 000000000..6ffe759e8 --- /dev/null +++ b/crates/docx/src/write/font_table.rs @@ -0,0 +1,98 @@ +//! A font table (`word/fontTable.xml`, ECMA-376 Part 1 §17.8) for a document that brings none of +//! its own: one built in code, or read from another format. It names each font the document +//! uses with its generic family and pitch, so a reader without the font draws a like one (a sans +//! for Arial, not its own serif default). A table read from a file is written back as it was +//! instead ([`super::embed::EmbedWriter::font_table`]). + +use std::collections::BTreeSet; + +use craft_wordmodel::font_kind::GenericFamily; +use craft_wordmodel::props::CharProps; +use craft_wordmodel::symbol_fonts::is_symbol_font; +use craft_wordmodel::walk::each_para; +use craft_wordmodel::{Document, Paragraph}; + +use crate::xml::W; + +/// Most fonts the table names (hostile input: a font per run). +const MAX_FONTS: usize = 1000; +/// Longest font name it keeps, bytes (as the reader, `MAX_FONT_NAME`). +const MAX_NAME: usize = 256; + +/// Add the fonts `c` names to `out`, up to [`MAX_FONTS`]. +fn take<'a>(c: &'a CharProps, out: &mut BTreeSet<&'a str>) { + for f in [&c.font, &c.font_ea, &c.font_cs, &c.sym_font].into_iter().flatten() { + let f = f.trim(); + if out.len() < MAX_FONTS && !f.is_empty() && f.len() <= MAX_NAME { + out.insert(f); + } + } +} + +/// The fonts `doc` names, sorted: the document defaults', its styles' and list levels', and +/// every run's and paragraph mark's in every story. +fn used_fonts(doc: &Document) -> BTreeSet<&str> { + let mut out = BTreeSet::new(); + take(&doc.styles.default_chr, &mut out); + for s in &doc.styles.styles { + take(&s.chr, &mut out); + } + for a in &doc.numbering.abstracts { + for l in &a.levels { + take(&l.chr, &mut out); + } + } + for n in &doc.numbering.nums { + for (_, l) in &n.level_overrides { + take(&l.chr, &mut out); + } + } + let stories = std::iter::once(&doc.body).chain(doc.parts.values().map(|p| &p.blocks)); + for b in stories.flat_map(|blocks| blocks.iter()) { + if out.len() >= MAX_FONTS { + break; + } + each_para(b, 0, &mut |p: &Paragraph| { + take(&p.mark, &mut out); + for r in &p.runs { + take(&r.props, &mut out); + } + }); + } + out +} + +/// `word/fontTable.xml` for `doc`, or `None` when it names no font. +pub(super) fn font_table_xml(doc: &Document) -> Option> { + let fonts = used_fonts(doc); + if fonts.is_empty() { + return None; + } + let mut w = W::new(); + w.open( + "w:fonts", + &[ + ("xmlns:w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main"), + ("xmlns:r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"), + ], + ); + for name in fonts { + w.open("w:font", &[("w:name", name)]); + if is_symbol_font(name) { + // Symbol, Wingdings…: the symbol character set, so a reader maps their codes as the + // font's own and doesn't substitute a text face. + w.val("w:charset", "02"); + w.val("w:family", "auto"); + w.val("w:pitch", "variable"); + } else { + // A family the file's own table named roman stays roman (Word draws it in a serif). + let family = + if doc.settings.roman_fonts.iter().any(|r| r.eq_ignore_ascii_case(name)) { GenericFamily::Roman } else { GenericFamily::of(name) }; + w.val("w:family", family.name()); + w.val("w:pitch", if family.fixed_pitch() { "fixed" } else { "variable" }); + } + w.close("w:font"); + } + w.close("w:fonts"); + Some(w.into_bytes()) +} diff --git a/crates/docx/src/write/parts.rs b/crates/docx/src/write/parts.rs index 4cb847276..942da56c2 100644 --- a/crates/docx/src/write/parts.rs +++ b/crates/docx/src/write/parts.rs @@ -7,6 +7,7 @@ use super::{ BTreeMap, Blocks, CT_WML, Document, DocxError, Flavor, HashMap, MAX_VBA_RELATED, PartRels, VBA_PROJECT_PART, VBA_RELATED, W, Writer, embed, glossary, rt, settings_merge, watermark, xml, }; +use crate::package::FONT_TABLE_PART; /// The parts of the package [`write_as`] zips, in order, `[Content_Types].xml` first: (part name /// without the leading `/`, bytes). @@ -160,7 +161,13 @@ pub(crate) fn write_parts(doc: &Document, flavor: Flavor) -> Result = BTreeMap::new(); diff --git a/crates/docx/tests/it/content_control_save_cost.rs b/crates/docx/tests/it/content_control_save_cost.rs index dec621510..9b96aeb7b 100644 --- a/crates/docx/tests/it/content_control_save_cost.rs +++ b/crates/docx/tests/it/content_control_save_cost.rs @@ -221,6 +221,8 @@ const PINNED_PARTS: &[&str] = &[ "word/styles.xml", "word/settings.xml", "word/theme/theme1.xml", + // The fonts the document uses, with their families: it brings no font table of its own. + "word/fontTable.xml", "docProps/core.xml", "docProps/app.xml", ]; diff --git a/crates/docx/tests/it/font_table.rs b/crates/docx/tests/it/font_table.rs new file mode 100644 index 000000000..e4a8b03a1 --- /dev/null +++ b/crates/docx/tests/it/font_table.rs @@ -0,0 +1,106 @@ +//! A document that brings no font table of its own (one built in code, or read from another +//! format) gets one naming the fonts it uses, with their generic family and pitch: a reader +//! without Arial then draws a sans, not its own serif default. +use std::collections::BTreeMap; +use std::io::Read; +use std::sync::Arc; + +use craft_wordmodel::props::CharProps; +use craft_wordmodel::table::Table; +use craft_wordmodel::{Block, Document, Paragraph}; + +fn unzip(bytes: &[u8]) -> BTreeMap { + let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut out = BTreeMap::new(); + for i in 0..z.len() { + let mut f = z.by_index(i).unwrap(); + let mut s = String::new(); + if f.read_to_string(&mut s).is_ok() { + out.insert(f.name().unwrap().to_string(), s); + } + } + out +} + +/// The `w:font` element for `name` in `table`. +fn font<'a>(table: &'a str, name: &str) -> &'a str { + let open = format!(""); + let at = table.find(&open).unwrap_or_else(|| panic!("no {name} in {table}")); + let rest = &table[at..]; + &rest[..rest.find("").unwrap()] +} + +fn append(p: &mut Paragraph, s: &str, props: &CharProps) { + let at = p.len(); + p.insert_text(at, s, props).unwrap(); +} + +fn run(text: &str, font: &str) -> Paragraph { + Paragraph::with_text(text, CharProps { font: Some(font.into()), ..Default::default() }) +} + +#[test] +fn a_built_document_names_its_fonts_with_their_family_and_pitch() { + let mut d = Document::new(); + let mut table = Table::new(1, 1, 200.0); + if let Some(c) = table.rows.first_mut().and_then(|r| r.cells.first_mut()) { + c.blocks = vec![Arc::new(Block::Para(run("cell", "Courier New")))]; + } + let mut symbol = Paragraph::new(); + append(&mut symbol, "\u{F0B7}", &CharProps { sym_font: Some("Symbol".into()), ..Default::default() }); + let mut serif = run("serif", "Times New Roman"); + append(&mut serif, " east", &CharProps { font_ea: Some("MS Mincho".into()), ..Default::default() }); + d.body = + vec![Arc::new(Block::Para(run("sans", "Arial"))), Arc::new(Block::Table(table)), Arc::new(Block::Para(serif)), Arc::new(Block::Para(symbol))]; + let files = unzip(&craft_docx::write(&d).unwrap()); + let t = files.get("word/fontTable.xml").unwrap_or_else(|| panic!("no font table in {:?}", files.keys())); + assert!(font(t, "Arial").contains(r#""#), "{t}"); + assert!(font(t, "Times New Roman").contains(r#""#), "{t}"); + assert!(font(t, "Courier New").contains(r#""#), "a table cell's font: {t}"); + assert!(font(t, "MS Mincho").contains(""#), "a symbol font has the symbol set: {t}"); + // The built-in styles' fonts are there too. + let body = d.styles.default_chr.font.clone().unwrap(); + font(t, &body); + assert_eq!(t.matches(r#""#).count(), 1, "each font once"); + // Related from the document and typed. + assert!( + files["word/_rels/document.xml.rels"].contains(r#"relationships/fontTable" Target="fontTable.xml""#), + "{}", + files["word/_rels/document.xml.rels"] + ); + assert!(files["[Content_Types].xml"].contains("wordprocessingml.fontTable+xml")); + // The reader takes the families back: Times New Roman is a serif. + let back = craft_docx::read(&craft_docx::write(&d).unwrap()).unwrap(); + assert!(back.settings.roman_fonts.iter().any(|f| f == "Times New Roman"), "{:?}", back.settings.roman_fonts); + assert!(!back.settings.roman_fonts.iter().any(|f| f == "Arial")); + // Saved again, the table read back is written as it was. + let again = unzip(&craft_docx::write(&back).unwrap()); + assert_eq!(again.get("word/fontTable.xml"), Some(t)); +} + +#[test] +fn a_file_font_table_family_wins_over_the_name() { + // A file's table classes "Fancy Face" as roman: the generated table, written when that one is + // gone, keeps it a serif. + let mut d = Document::new(); + d.body = vec![Arc::new(Block::Para(run("x", "Fancy Face")))]; + d.settings.roman_fonts = vec!["Fancy Face".into()]; + let files = unzip(&craft_docx::write(&d).unwrap()); + assert!(font(&files["word/fontTable.xml"], "Fancy Face").contains(r#""#)); +} + +#[test] +fn hostile_font_counts_and_names_are_bounded() { + let mut d = Document::new(); + let mut p = Paragraph::new(); + for i in 0..5000 { + append(&mut p, "x", &CharProps { font: Some(format!("Face {i}")), ..Default::default() }); + } + append(&mut p, "y", &CharProps { font: Some("N".repeat(10_000)), ..Default::default() }); + d.body = vec![Arc::new(Block::Para(p))]; + let files = unzip(&craft_docx::write(&d).unwrap()); + let t = &files["word/fontTable.xml"]; + assert!(t.matches("")); assert!(text.contains("pkg:name=\"/word/document.xml\"") && text.contains("")); assert_eq!(craft_docx::sniff_xml(&xml), craft_docx::XmlKind::FlatOpc); - let back = craft_docx::read_xml(&xml).expect("read flat"); - assert_eq!(back, rt(&d)); + let mut back = craft_docx::read_xml(&xml).expect("read flat"); + // `pkg:xmlData` inlines a part without its XML declaration, so a kept XML part (the font + // table) comes back without one; the markup is the same. + let mut want = rt(&d); + for doc in [&mut back, &mut want] { + for v in doc.passthrough.values_mut() { + if let Some(rest) = + v.strip_prefix(b"').map(|e| r[e + 1..].trim_ascii_start().to_vec())) + { + *v = std::sync::Arc::new(rest); + } + } + } + assert!(back.passthrough.contains_key("word/fontTable.xml")); + assert_eq!(back, want); assert_eq!(back.media.len(), 1); } diff --git a/crates/flow/src/from_doc.rs b/crates/flow/src/from_doc.rs index d85953a0a..11d71dd05 100644 --- a/crates/flow/src/from_doc.rs +++ b/crates/flow/src/from_doc.rs @@ -18,11 +18,7 @@ pub(super) fn uses_kind(blocks: &[FBlock], k: Kind, depth: usize) -> bool { // --------------------------------------------------------------------------------------------- // Document → Flow -/// Is this a monospace family name? -pub fn is_mono(font: &str) -> bool { - let f = font.to_ascii_lowercase(); - f.contains("courier") || f.contains("mono") || f.contains("consolas") || f.contains("menlo") || f.contains("code") || f == "monaco" -} +pub use craft_wordmodel::font_kind::is_mono; fn is_code_style(doc: &Document, id: &str) -> bool { let names = |s: &str| { diff --git a/crates/odf/src/text/package.rs b/crates/odf/src/text/package.rs index f43692be9..e7744a4e8 100644 --- a/crates/odf/src/text/package.rs +++ b/crates/odf/src/text/package.rs @@ -1583,32 +1583,8 @@ fn with_font_faces(xml: &str) -> String { /// A font family's generic family and pitch (§20.270, §20.271), from its name: monospaced /// families are `modern` and fixed, serif ones `roman`, the rest `swiss`. fn font_kind(family: &str) -> (&'static str, &'static str) { - let f = family.to_ascii_lowercase(); - if model::is_mono(family) { - return ("modern", "fixed"); - } - const SERIF: [&str; 16] = [ - "serif", - "times", - "georgia", - "cambria", - "caladea", - "garamond", - "palatino", - "book", - "roman", - "libertine", - "minion", - "baskerville", - "bodoni", - "didot", - "charter", - "constantia", - ]; - if SERIF.iter().any(|s| f.contains(s)) && !f.contains("sans") { - return ("roman", "variable"); - } - ("swiss", "variable") + let generic = craft_wordmodel::font_kind::GenericFamily::of(family); + (generic.name(), if generic.fixed_pitch() { "fixed" } else { "variable" }) } #[cfg(test)] diff --git a/crates/wordmodel/src/font_kind.rs b/crates/wordmodel/src/font_kind.rs new file mode 100644 index 000000000..7f8692783 --- /dev/null +++ b/crates/wordmodel/src/font_kind.rs @@ -0,0 +1,91 @@ +//! The generic family of a font, guessed from its name: what a reader without the font should draw +//! instead. The writers that declare one share it: OOXML's font table (`w:family`, `w:pitch`), +//! ODF's font faces (`style:font-family-generic`, `style:font-pitch`) and RTF's (`\fmodern`). + +/// A font's generic family. The names are the values OOXML (`ST_FontFamily`) and ODF give them. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum GenericFamily { + /// Serif faces (Times New Roman, Georgia, Cambria…). + Roman, + /// Sans-serif faces (Arial, Calibri, Liberation Sans…), and any name not known to be another. + Swiss, + /// Monospace faces (Courier New, Consolas…). + Modern, +} + +/// Words in the names of serif faces. +const SERIF: [&str; 16] = [ + "serif", + "times", + "georgia", + "cambria", + "caladea", + "garamond", + "palatino", + "book", + "roman", + "libertine", + "minion", + "baskerville", + "bodoni", + "didot", + "charter", + "constantia", +]; + +impl GenericFamily { + /// The family of the font named `name`. + pub fn of(name: &str) -> GenericFamily { + if is_mono(name) { + return GenericFamily::Modern; + } + let f = name.to_ascii_lowercase(); + if SERIF.iter().any(|s| f.contains(s)) && !f.contains("sans") { + return GenericFamily::Roman; + } + GenericFamily::Swiss + } + + /// `roman`, `swiss` or `modern`. + pub fn name(self) -> &'static str { + match self { + GenericFamily::Roman => "roman", + GenericFamily::Swiss => "swiss", + GenericFamily::Modern => "modern", + } + } + + /// Whether its faces are fixed pitch (monospace). + pub fn fixed_pitch(self) -> bool { + self == GenericFamily::Modern + } +} + +/// Is this a monospace family name? +pub fn is_mono(font: &str) -> bool { + let f = font.to_ascii_lowercase(); + f.contains("courier") || f.contains("mono") || f.contains("consolas") || f.contains("menlo") || f.contains("code") || f == "monaco" +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn families_from_names() { + for (name, want) in [ + ("Arial", GenericFamily::Swiss), + ("Liberation Sans", GenericFamily::Swiss), + ("Unknown Face", GenericFamily::Swiss), + ("Times New Roman", GenericFamily::Roman), + ("Liberation Serif", GenericFamily::Roman), + ("Caladea", GenericFamily::Roman), + ("Noto Sans Serif", GenericFamily::Swiss), + ("Courier New", GenericFamily::Modern), + ("Liberation Mono", GenericFamily::Modern), + ] { + assert_eq!(GenericFamily::of(name), want, "{name}"); + } + assert!(GenericFamily::Modern.fixed_pitch() && !GenericFamily::Roman.fixed_pitch()); + } +} diff --git a/crates/wordmodel/src/lib.rs b/crates/wordmodel/src/lib.rs index 5fb2d14d8..2b3fb2626 100644 --- a/crates/wordmodel/src/lib.rs +++ b/crates/wordmodel/src/lib.rs @@ -29,6 +29,7 @@ pub mod effects; pub mod eq; pub mod fields; pub mod fill; +pub mod font_kind; pub mod freeform; pub mod geom; pub mod graphic;