docx: write a font table naming the fonts a document uses (#1948)

This commit is contained in:
keithcsqueensu
2026-11-16 21:29:43 -05:00
committed by GitHub
parent 81092ab15a
commit 738bf6fafe
12 changed files with 332 additions and 39 deletions
+1
View File
@@ -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;
+6 -5
View File
@@ -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.
+98
View File
@@ -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<Vec<u8>> {
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())
}
+8 -1
View File
@@ -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<Vec<(String,
PartRels::default(),
);
wr.embeds.font_table(&mut rels);
// The file's own font table, else one naming the fonts the document uses.
if !wr.embeds.font_table(&mut rels)
&& let Some(table) = super::font_table::font_table_xml(doc)
{
rels.add(rt::FONT_TABLE, "fontTable.xml", false);
push_part(&mut entries, &mut overrides, FONT_TABLE_PART, table, &format!("{CT_WML}fontTable+xml"), PartRels::default());
}
// Media referenced by some drawing (orphan parts would make the package suspect).
let mut media_types: BTreeMap<String, &str> = BTreeMap::new();
@@ -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",
];
+106
View File
@@ -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<String, String> {
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!("<w:font w:name=\"{name}\">");
let at = table.find(&open).unwrap_or_else(|| panic!("no {name} in {table}"));
let rest = &table[at..];
&rest[..rest.find("</w:font>").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#"<w:family w:val="swiss"/><w:pitch w:val="variable"/>"#), "{t}");
assert!(font(t, "Times New Roman").contains(r#"<w:family w:val="roman"/>"#), "{t}");
assert!(font(t, "Courier New").contains(r#"<w:family w:val="modern"/><w:pitch w:val="fixed"/>"#), "a table cell's font: {t}");
assert!(font(t, "MS Mincho").contains("<w:family "), "an East Asian font: {t}");
assert!(font(t, "Symbol").contains(r#"<w:charset w:val="02"/>"#), "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#"<w:font w:name="Arial">"#).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#"<w:family w:val="roman"/>"#));
}
#[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("<w:font ").count() <= 1000, "{}", t.matches("<w:font ").count());
assert!(!t.contains(&"N".repeat(300)));
}
+1
View File
@@ -18,6 +18,7 @@ mod east_asian_lang;
mod east_asian_layout;
mod emphasis_marks;
mod fixtures;
mod font_table;
mod glossary;
mod heading_levels;
mod kashida;
+15 -2
View File
@@ -1901,8 +1901,21 @@ fn flat_opc_round_trip_equals_docx() {
assert!(text.starts_with("<?xml") && text.contains("<?mso-application progid=\"Word.Document\"?>"));
assert!(text.contains("pkg:name=\"/word/document.xml\"") && text.contains("<pkg:binaryData>"));
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"<?xml").and_then(|r| r.iter().position(|&b| b == 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);
}
+1 -5
View File
@@ -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| {
+2 -26
View File
@@ -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)]
+91
View File
@@ -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());
}
}
+1
View File
@@ -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;