craft-docx: theme font slots survive a save (#2197)

* craft-docx: theme font slots survive a save

w:rFonts' w:eastAsiaTheme and w:cstheme slots are kept on read and written
back. Word picks the East Asian and complex-script fonts through them, so
dropping them changed which font Word used for East Asian punctuation and
its line breaks. The Latin slots (w:asciiTheme, w:hAnsiTheme) are kept when
the run's font came from them and written back only while they still name
that font in the document's theme, so a font chosen later is not hidden.

craft-wordmodel: a one-byte ThemeFont and CharProps font_ascii_theme,
font_hansi_theme, font_ea_theme and font_cs_theme. Overlaying a named font
without its slot clears the slot; minus keeps a slot whose font stays.

Ported from storytold/wordcraft#5772.

* craft-docx: keep the theme's East Asian and script fonts; exact slot replacement

The saved theme wrote empty a:ea and a:cs faces and no per-script fonts, so
a kept w:eastAsiaTheme or w:cstheme slot named no font in Word. The reader
now keeps the theme's ea, cs and a:font script entries (THEME_FONTS) and
the writer puts them back.

craft-wordmodel: a named font replaces both Latin slots with its own, so a
patch with one slot no longer leaves the other stale. minus keeps a font
equal to the base's when its slots differ, so a font that clears the
base's slots still clears them when overlaid. latin_slot compares the
theme face without cloning it.

* craft-docx: theme fonts keep faces and scripts apart; limit only usable scripts

THEME_FONTS lines now say whether they hold a default face (a:ea, a:cs) or a
per-script font, so an a:font script="cs" is no longer written back as the
a:cs face. The 256-entry limit applies to usable per-script fonts only, so
empty default faces no longer push the last one out.

A test pins down Latin slots that name different faces: the model has one
Latin font, so only the slot that still names it is written.

* craft-docx: a long theme script id never pushes out one font resolution uses

The kept per-script fonts count script ids of 8 characters or fewer (the
ones font resolution takes) and longer ones (language tags such as
zh-Hant-TW) apart, 256 each, so a long one can't use up the place of a
mapping resolution keeps.

* craft-docx: THEME_FONTS names both per-script caps
This commit is contained in:
Kevin Joseph
2026-11-18 15:35:36 -05:00
committed by GitHub
parent 6242f65262
commit 0c3793eadd
12 changed files with 580 additions and 15 deletions
+7
View File
@@ -114,6 +114,13 @@ pub const CUSTOM_XML_ROOTS: &str = "wordcraft:customXml.roots";
/// The original `word/settings.xml` when it holds settings the model doesn't (merged into on
/// save by `write::settings_merge`). Not a package part: WordCraft's own bookkeeping.
pub const SETTINGS_ORIG: &str = "wordcraft:settings.orig";
/// The theme's East Asian, complex-script and per-script fonts (`a:ea`, `a:cs`, `a:font
/// script="Hans"` in `a:majorFont` / `a:minorFont`), which the model doesn't hold: `major|minor
/// \tface\tea|cs\ttypeface` and `major|minor\tscript\t<script>\ttypeface` lines (per font, at
/// most 256 script ids of 8 characters or fewer and 256 longer ones, such as `zh-Hant-TW`). Written back into the theme on save, so the
/// `w:eastAsiaTheme` and `w:cstheme` slots a save keeps still name a font in Word. Not a package
/// part: WordCraft's own bookkeeping.
pub const THEME_FONTS: &str = "wordcraft:theme.fonts";
/// Extended properties (`docProps/app.xml`) the model doesn't hold but a save keeps
/// ([`APP_KEPT_PROPS`]): `name\tvalue` lines. Not a package part: WordCraft's own bookkeeping.
pub const APP_KEPT: &str = "wordcraft:app.kept";
+27
View File
@@ -227,6 +227,33 @@ impl Reader<'_> {
};
self.pc.major_scripts = scripts("a:majorFont");
self.pc.minor_scripts = scripts("a:minorFont");
// Kept for the save, which writes the theme from the model (`package::THEME_FONTS`).
let mut kept = String::new();
for (key, tag) in [("major", "a:majorFont"), ("minor", "a:minorFont")] {
let Some(f) = fs.child(tag) else { continue };
let clean = |v: &str| !v.is_empty() && v.len() < 256 && !v.contains(['\t', '\n', '\r']);
// The default faces and the per-script ones are told apart by their kind, so an
// `a:font script="cs"` is not taken for the `a:cs` face.
let faces = ["a:ea", "a:cs"].into_iter().filter_map(|n| Some(("face", &n[2..], f.child(n)?.attr("typeface")?)));
for (kind, which, face) in faces.filter(|(_, _, face)| clean(face)) {
kept.push_str(&format!("{key}\t{kind}\t{which}\t{face}\n"));
}
// At most 256 of the script ids font resolution takes (8 characters or fewer, as
// above) and 256 longer ones (a language tag such as `zh-Hant-TW`), counted apart
// so the longer ones never push out a mapping resolution uses.
let mut counts = (0usize, 0usize);
let per_script = f.els().filter(|e| e.name == "a:font").filter_map(|e| Some((e.attr("script")?, e.attr("typeface")?)));
for (script, face) in per_script.filter(|(script, face)| clean(script) && clean(face)) {
let n = if script.len() <= 8 { &mut counts.0 } else { &mut counts.1 };
if *n < 256 {
*n += 1;
kept.push_str(&format!("{key}\tscript\t{script}\t{face}\n"));
}
}
}
if !kept.is_empty() {
self.doc.passthrough.insert(crate::package::THEME_FONTS.into(), Arc::new(kept.into_bytes()));
}
}
self.pc.major_font = self.doc.settings.major_font.clone();
self.pc.minor_font = self.doc.settings.minor_font.clone();
+13 -1
View File
@@ -6,7 +6,7 @@ use craft_wordmodel::para::cap_alt;
use craft_wordmodel::props::{
Align, Border, BorderStyle, Borders, CellProps, CharProps, CombineBrackets, EastAsianLayout, HeightRule, Highlight, Kashida, LineSpacing, NumRef,
ParaProps, ParagraphTextDirection, Rgb, RowProps, TabAlign, TabLeader, TabStop, TableFloat, TableLook, TableProps, TextAlignment, TextColor,
TextDirection, Underline, VAlign, VMerge, VertAlign,
TextDirection, ThemeFont, Underline, VAlign, VMerge, VertAlign,
};
use craft_wordmodel::section::{
Columns, DocGrid, DocGridType, LineNumberRestart, LineNumbering, MAX_CHAR_SPACE, MAX_GRID_PITCH, NotePos, NoteProps, NoteRestart, NumFormat,
@@ -277,6 +277,18 @@ impl PropCtx {
// The East Asian font (Chinese, Japanese, Korean text). A `w:eastAsiaTheme` font
// is left to inherit, like `w:cstheme`.
c.font_ea = k.attr("w:eastAsia").filter(|f| !f.is_empty() && f.len() < 256).map(str::to_string);
// The theme slots themselves are kept for saving: Word resolves them (over the
// named fonts) when it lays the text out, and dropping them changes its line
// breaks in a document with an East Asian language.
c.font_ea_theme = k.attr("w:eastAsiaTheme").and_then(ThemeFont::parse);
c.font_cs_theme = k.attr("w:cstheme").and_then(ThemeFont::parse);
// The Latin slots too, when `font` came from them: saving writes them back while
// they still name `font`, so the text keeps following the theme in Word.
if c.font.is_some() {
let latin = |a: &str| k.attr(a).and_then(ThemeFont::parse).filter(|t| t.is_latin());
c.font_ascii_theme = latin("w:asciiTheme");
c.font_hansi_theme = latin("w:hAnsiTheme");
}
}
"w:b" => c.bold = Some(on_off(k)),
"w:bCs" => c.bold_cs = Some(on_off(k)),
+2
View File
@@ -12,6 +12,8 @@ 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).
pub(crate) fn write_parts(doc: &Document, flavor: Flavor) -> Result<Vec<(String, Vec<u8>)>, DocxError> {
// Theme font slots are written while they name the run's font in this theme.
let _theme_fonts = super::props::ThemeFontsGuard::set(&doc.settings.major_font, &doc.settings.minor_font);
// A range field must be whole in the file: drop markers that lost their partner in editing.
let balanced;
let doc = if doc.has_unbalanced_field_ranges() {
+58 -7
View File
@@ -2,12 +2,46 @@
use craft_wordmodel::props::{
Align, Border, BorderStyle, Borders, CellProps, CharProps, EastAsianLayout, HeightRule, Highlight, Kashida, LineSpacing, ParaProps, RowProps,
TabAlign, TabLeader, TableFloat, TableLook, TableProps, TextColor, VAlign, VMerge, VertAlign,
TabAlign, TabLeader, TableFloat, TableLook, TableProps, TextColor, ThemeFont, VAlign, VMerge, VertAlign,
};
use crate::units::{n, twips};
use crate::xml::W;
thread_local! {
/// The theme's (major, minor) Latin fonts of the document being saved, for [`latin_slot`].
static THEME_FONTS: std::cell::RefCell<Option<(String, String)>> = const { std::cell::RefCell::new(None) };
}
/// Holds the document's theme fonts while a package is written; restores the previous ones on
/// drop (a nested write, as for an embedded document, gets its own).
pub(crate) struct ThemeFontsGuard(Option<(String, String)>);
impl ThemeFontsGuard {
pub(crate) fn set(major: &str, minor: &str) -> ThemeFontsGuard {
ThemeFontsGuard(THEME_FONTS.with(|t| t.replace(Some((major.to_string(), minor.to_string())))))
}
}
impl Drop for ThemeFontsGuard {
fn drop(&mut self) {
let prev = self.0.take();
THEME_FONTS.with(|t| *t.borrow_mut() = prev);
}
}
/// A Latin theme slot worth writing: it names `font` in the theme being saved. Otherwise (the
/// font was changed, or the theme was, or no theme is known) it is left out, so Word shows
/// `font` as WordCraft does.
fn latin_slot(slot: Option<ThemeFont>, font: Option<&String>) -> Option<&'static str> {
let (slot, font) = (slot?, font?);
let names = |(major, minor): &(String, String)| {
let named = if slot.is_major() { major } else { minor };
!named.is_empty() && named.eq_ignore_ascii_case(font)
};
THEME_FONTS.with(|t| t.borrow().as_ref().is_some_and(names)).then_some(slot.as_str())
}
fn toggle(w: &mut W, name: &str, v: Option<bool>) {
match v {
Some(true) => w.empty(name, &[]),
@@ -21,12 +55,8 @@ fn round(v: f32) -> i64 {
v.round().clamp(-1e9, 1e9) as i64
}
/// `w:rPr` content (without the wrapper). Link and revision marks are not run properties.
pub fn rpr_inner(w: &mut W, c: &CharProps) {
if let Some(s) = &c.style {
w.val("w:rStyle", s);
}
// Emit only explicit properties so absent values keep inheriting from the style chain.
/// `w:rFonts`: the named fonts, then the theme slots still worth writing.
fn rfonts(w: &mut W, c: &CharProps) {
let mut fonts: Vec<(&str, &str)> = Vec::new();
if let Some(f) = &c.font {
fonts.extend([("w:ascii", f.as_str()), ("w:hAnsi", f.as_str())]);
@@ -37,9 +67,30 @@ pub fn rpr_inner(w: &mut W, c: &CharProps) {
if let Some(cs) = &c.font_cs {
fonts.push(("w:cs", cs));
}
if let Some(t) = latin_slot(c.font_ascii_theme, c.font.as_ref()) {
fonts.push(("w:asciiTheme", t));
}
if let Some(t) = latin_slot(c.font_hansi_theme, c.font.as_ref()) {
fonts.push(("w:hAnsiTheme", t));
}
if let Some(t) = c.font_ea_theme {
fonts.push(("w:eastAsiaTheme", t.as_str()));
}
if let Some(t) = c.font_cs_theme {
fonts.push(("w:cstheme", t.as_str()));
}
if !fonts.is_empty() {
w.empty("w:rFonts", &fonts);
}
}
/// `w:rPr` content (without the wrapper). Link and revision marks are not run properties.
pub fn rpr_inner(w: &mut W, c: &CharProps) {
if let Some(s) = &c.style {
w.val("w:rStyle", s);
}
// Emit only explicit properties so absent values keep inheriting from the style chain.
rfonts(w, c);
toggle(w, "w:b", c.bold);
toggle(w, "w:bCs", c.bold_cs);
toggle(w, "w:i", c.italic);
+17 -3
View File
@@ -245,11 +245,25 @@ pub(super) fn theme_xml(doc: &Document) -> Vec<u8> {
}
w.close("a:clrScheme");
w.open("a:fontScheme", &[("name", name)]);
for (tag, face) in [("a:majorFont", &s.major_font), ("a:minorFont", &s.minor_font)] {
// The file's own East Asian, complex-script and per-script fonts, as read
// (`package::THEME_FONTS`): the theme slots a save keeps resolve through them in Word.
let kept = doc.passthrough.get(crate::package::THEME_FONTS).map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default();
let kept: Vec<[&str; 4]> = kept
.lines()
.filter_map(|l| {
let mut it = l.splitn(4, '\t');
Some([it.next()?, it.next()?, it.next()?, it.next()?])
})
.collect();
for (key, tag, face) in [("major", "a:majorFont", &s.major_font), ("minor", "a:minorFont", &s.minor_font)] {
let of = |which: &str| kept.iter().find(|[k, kind, w, _]| *k == key && *kind == "face" && *w == which).map_or("", |[.., f]| *f);
w.open(tag, &[]);
w.empty("a:latin", &[("typeface", face)]);
w.empty("a:ea", &[("typeface", "")]);
w.empty("a:cs", &[("typeface", "")]);
w.empty("a:ea", &[("typeface", of("ea"))]);
w.empty("a:cs", &[("typeface", of("cs"))]);
for [_, _, script, f] in kept.iter().filter(|[k, kind, ..]| *k == key && *kind == "script") {
w.empty("a:font", &[("script", script), ("typeface", f)]);
}
w.close(tag);
}
w.close("a:fontScheme");
+186
View File
@@ -0,0 +1,186 @@
//! Theme font slots of Latin text (`w:rFonts/@w:asciiTheme`, `@w:hAnsiTheme`, ISO/IEC 29500-1
//! §17.3.2.26). Saved as the font they name, the text looked the same in Word but no longer
//! followed a change of the theme's fonts. Saving writes a slot back only while it still names the
//! text's font in the document's theme, so a font chosen later is never hidden by it.
use std::io::{Read, Write};
const THEME: &str = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="T"><a:themeElements><a:fontScheme name="T"><a:majorFont><a:latin typeface="Georgia"/><a:ea typeface=""/><a:cs typeface=""/></a:majorFont><a:minorFont><a:latin typeface="Verdana"/><a:ea typeface="SimSun"/><a:cs typeface="Arial"/><a:font script="Jpan" typeface="MS Mincho"/><a:font script="Hans" typeface="DengXian"/></a:minorFont></a:fontScheme></a:themeElements></a:theme>"#;
fn docx(body: &str, styles: &str) -> Vec<u8> {
docx_with_theme(body, styles, THEME)
}
fn docx_with_theme(body: &str, styles: &str, theme: &str) -> Vec<u8> {
let root = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
let doc_rels = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme" Target="theme/theme1.xml"/></Relationships>"#;
let doc = format!(
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
);
let styles = format!(
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">{styles}</w:styles>"#
);
let parts = [
("_rels/.rels", root.to_string()),
("word/document.xml", doc),
("word/_rels/document.xml.rels", doc_rels.to_string()),
("word/styles.xml", styles),
("word/theme/theme1.xml", theme.to_string()),
];
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
for (name, xml) in &parts {
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(xml.as_bytes()).unwrap();
}
zw.finish().unwrap().into_inner()
}
fn part(bytes: &[u8], name: &str) -> String {
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let mut s = String::new();
z.by_name(name).unwrap().read_to_string(&mut s).unwrap();
s
}
fn rfonts(xml: &str) -> Vec<String> {
xml.match_indices("<w:rFonts").map(|(i, _)| xml[i..].split('>').next().unwrap_or("").to_string()).collect()
}
// As pandoc and Word write them: the minor font in the defaults, the major one on a run.
const STYLES: &str = r#"<w:docDefaults><w:rPrDefault><w:rPr><w:rFonts w:asciiTheme="minorHAnsi" w:hAnsiTheme="minorHAnsi" w:eastAsiaTheme="minorEastAsia" w:cstheme="minorBidi"/></w:rPr></w:rPrDefault></w:docDefaults>"#;
const BODY: &str = r#"<w:p><w:r><w:rPr><w:rFonts w:asciiTheme="majorHAnsi" w:hAnsiTheme="majorHAnsi"/></w:rPr><w:t>Heading text</w:t></w:r></w:p>"#;
#[test]
fn latin_theme_slots_survive_a_save() {
let d = craft_docx::read(&docx(BODY, STYLES)).unwrap();
assert_eq!(d.styles.default_chr.font.as_deref(), Some("Verdana"), "layout still reads the font the slot names");
assert_eq!(d.styles.default_chr.font_ascii_theme, Some(craft_wordmodel::props::ThemeFont::MinorHAnsi));
let run = &d.body[0].as_para().unwrap().runs[0];
assert_eq!((run.props.font.as_deref(), run.props.font_hansi_theme), (Some("Georgia"), Some(craft_wordmodel::props::ThemeFont::MajorHAnsi)));
let out = craft_docx::write(&d).unwrap();
let styles = rfonts(&part(&out, "word/styles.xml"));
assert!(styles.iter().any(|f| f.contains(r#"w:asciiTheme="minorHAnsi""#) && f.contains(r#"w:hAnsiTheme="minorHAnsi""#)), "{styles:?}");
let doc = rfonts(&part(&out, "word/document.xml"));
assert!(doc.iter().any(|f| f.contains(r#"w:asciiTheme="majorHAnsi""#) && f.contains(r#"w:hAnsiTheme="majorHAnsi""#)), "{doc:?}");
// And again after a second round trip.
let again = craft_docx::read(&out).unwrap();
assert_eq!(again.styles.default_chr.font_ascii_theme, Some(craft_wordmodel::props::ThemeFont::MinorHAnsi));
}
#[test]
fn a_font_chosen_later_is_not_hidden_by_the_slot() {
let mut d = craft_docx::read(&docx(BODY, STYLES)).unwrap();
// Set directly, as the font commands do, without touching the slots.
if let Some(craft_wordmodel::Block::Para(p)) = d.body.get_mut(0).map(std::sync::Arc::make_mut) {
p.runs[0].props.font = Some("Courier New".into());
}
let doc = rfonts(&part(&craft_docx::write(&d).unwrap(), "word/document.xml"));
assert!(doc.iter().any(|f| f.contains(r#"w:ascii="Courier New""#)), "{doc:?}");
assert!(!doc.iter().any(|f| f.contains("w:asciiTheme") || f.contains("w:hAnsiTheme")), "the slot would show Georgia in Word: {doc:?}");
}
#[test]
fn a_theme_font_change_without_the_text_drops_the_slot() {
let mut d = craft_docx::read(&docx(BODY, STYLES)).unwrap();
// The theme's minor font changes but the defaults keep Verdana: the slot no longer names it.
d.settings.minor_font = "Arial".into();
let styles = rfonts(&part(&craft_docx::write(&d).unwrap(), "word/styles.xml"));
assert!(!styles.iter().any(|f| f.contains(r#"w:asciiTheme="minorHAnsi""#)), "{styles:?}");
assert!(styles.iter().any(|f| f.contains(r#"w:ascii="Verdana""#)), "{styles:?}");
}
#[test]
fn a_named_font_overlaid_replaces_the_latin_slots() {
use craft_wordmodel::props::CharProps;
let mut base = CharProps {
font: Some("Verdana".into()),
font_ascii_theme: Some(craft_wordmodel::props::ThemeFont::MinorHAnsi),
font_hansi_theme: Some(craft_wordmodel::props::ThemeFont::MinorHAnsi),
..Default::default()
};
base.overlay(&CharProps { font: Some("Courier New".into()), ..Default::default() });
assert_eq!((base.font_ascii_theme, base.font_hansi_theme), (None, None));
let mut themed = CharProps { font: Some("Verdana".into()), ..Default::default() };
themed.overlay(&CharProps {
font: Some("Georgia".into()),
font_ascii_theme: Some(craft_wordmodel::props::ThemeFont::MajorHAnsi),
..Default::default()
});
assert_eq!(themed.font_ascii_theme, Some(craft_wordmodel::props::ThemeFont::MajorHAnsi));
}
/// The theme's East Asian, complex-script and per-script fonts are written back with it: the
/// `w:eastAsiaTheme` and `w:cstheme` slots a save keeps resolve through them in Word, and an
/// empty `a:ea` would leave them naming no font.
#[test]
fn the_themes_east_asian_and_script_fonts_survive_a_save() {
let out = craft_docx::write(&craft_docx::read(&docx(BODY, STYLES)).unwrap()).unwrap();
let theme = part(&out, "word/theme/theme1.xml");
let minor = theme.split("<a:minorFont>").nth(1).and_then(|m| m.split("</a:minorFont>").next()).unwrap_or_default();
for want in [
r#"<a:ea typeface="SimSun"/>"#,
r#"<a:cs typeface="Arial"/>"#,
r#"<a:font script="Jpan" typeface="MS Mincho"/>"#,
r#"<a:font script="Hans" typeface="DengXian"/>"#,
] {
assert!(minor.contains(want), "{want} missing from the minor font: {theme}");
}
let major = theme.split("<a:majorFont>").nth(1).and_then(|m| m.split("</a:majorFont>").next()).unwrap_or_default();
assert!(major.contains(r#"<a:ea typeface=""/>"#) && !major.contains("a:font "), "the major font keeps its empty faces: {theme}");
}
/// The minor font's part of a saved theme.
fn minor_font(out: &[u8]) -> String {
let theme = part(out, "word/theme/theme1.xml");
theme.split("<a:minorFont>").nth(1).and_then(|m| m.split("</a:minorFont>").next()).unwrap_or_default().to_string()
}
/// A per-script font for a script called `cs` stays a per-script font: it is not taken for the
/// theme's `a:cs` face.
#[test]
fn a_script_named_cs_is_not_the_cs_face() {
let theme = THEME.replace(r#"<a:font script="Jpan""#, r#"<a:font script="cs" typeface="Tahoma"/><a:font script="Jpan""#);
let minor = minor_font(&craft_docx::write(&craft_docx::read(&docx_with_theme(BODY, STYLES, &theme)).unwrap()).unwrap());
assert!(minor.contains(r#"<a:cs typeface="Arial"/>"#), "{minor}");
assert!(minor.contains(r#"<a:font script="cs" typeface="Tahoma"/>"#), "{minor}");
}
/// The 256 per-script fonts kept are 256 usable ones: empty default faces don't use them up.
#[test]
fn empty_default_faces_dont_count_against_the_script_limit() {
let scripts: String = (0..256).map(|i| format!(r#"<a:font script="S{i}" typeface="F{i}"/>"#)).collect();
let theme = THEME.replace(
r#"<a:ea typeface="SimSun"/><a:cs typeface="Arial"/><a:font script="Jpan" typeface="MS Mincho"/><a:font script="Hans" typeface="DengXian"/>"#,
&format!(r#"<a:ea typeface=""/><a:cs typeface=""/>{scripts}"#),
);
let minor = minor_font(&craft_docx::write(&craft_docx::read(&docx_with_theme(BODY, STYLES, &theme)).unwrap()).unwrap());
assert!(minor.contains(r#"<a:font script="S255" typeface="F255"/>"#), "{minor}");
}
/// Latin slots naming different faces: the model has one Latin font, the ASCII one, so only the
/// slot that still names it is written; the other is left out rather than made to name a face
/// it didn't.
#[test]
fn a_latin_slot_naming_another_face_is_not_written() {
let body = r#"<w:p><w:r><w:rPr><w:rFonts w:asciiTheme="minorHAnsi" w:hAnsiTheme="majorHAnsi"/></w:rPr><w:t>Mixed</w:t></w:r></w:p>"#;
let d = craft_docx::read(&docx(body, STYLES)).unwrap();
assert_eq!(d.body[0].as_para().unwrap().runs[0].props.font.as_deref(), Some("Verdana"));
let doc = rfonts(&part(&craft_docx::write(&d).unwrap(), "word/document.xml"));
let run = doc.iter().find(|f| f.contains("Verdana")).unwrap_or_else(|| panic!("{doc:?}"));
assert!(run.contains(r#"w:asciiTheme="minorHAnsi""#) && !run.contains("w:hAnsiTheme"), "{run}");
}
/// A long script id (a language tag, which DrawingML allows) doesn't use up a place the
/// mappings font resolution takes need: the last of 256 short ones is still saved.
#[test]
fn a_language_tag_script_doesnt_push_out_a_short_one() {
let short: String = (0..255).map(|i| format!(r#"<a:font script="S{i}" typeface="F{i}"/>"#)).collect();
let theme = THEME.replace(
r#"<a:font script="Jpan" typeface="MS Mincho"/><a:font script="Hans" typeface="DengXian"/>"#,
&format!(r#"<a:font script="zh-Hant-TW" typeface="PMingLiU"/>{short}<a:font script="Arab" typeface="Times New Roman"/>"#),
);
let minor = minor_font(&craft_docx::write(&craft_docx::read(&docx_with_theme(BODY, STYLES, &theme)).unwrap()).unwrap());
assert!(minor.contains(r#"<a:font script="Arab" typeface="Times New Roman"/>"#), "{minor}");
assert!(minor.contains(r#"<a:font script="zh-Hant-TW" typeface="PMingLiU"/>"#), "{minor}");
}
+2
View File
@@ -23,6 +23,7 @@ mod font_table;
mod glossary;
mod heading_levels;
mod kashida;
mod latin_theme_slots;
mod legacy_forms;
mod ligatures;
mod line_numbering;
@@ -48,6 +49,7 @@ mod settings_merge;
mod strict_drawings;
mod text_alignment;
mod text_boxes;
mod theme_font_slots;
mod toc_ranges;
mod twips_wrap;
mod undefined_style;
+7 -1
View File
@@ -68,6 +68,9 @@ fn every_char_prop_round_trips() {
let all = CharProps {
style: Some("Strong".into()),
font: Some("Georgia".into()),
// Theme slots naming Georgia in the document's theme (set below).
font_ascii_theme: Some(craft_wordmodel::props::ThemeFont::MajorHAnsi),
font_hansi_theme: Some(craft_wordmodel::props::ThemeFont::MajorAscii),
// The symbol's own font: the run is written as `w:sym` characters (#2036).
sym_font: Some("Wingdings".into()),
size: Some(10.5),
@@ -124,6 +127,8 @@ fn every_char_prop_round_trips() {
cs: Some(true),
font_cs: Some("B Nazanin".into()),
font_ea: Some("宋体".into()),
font_ea_theme: Some(craft_wordmodel::props::ThemeFont::MinorEastAsia),
font_cs_theme: Some(craft_wordmodel::props::ThemeFont::MinorBidi),
size_cs: Some(13.0),
bold_cs: Some(false),
italic_cs: Some(true),
@@ -143,7 +148,8 @@ fn every_char_prop_round_trips() {
};
let auto =
CharProps { color: Some(TextColor::Auto), highlight: Some(Highlight::None), vert_align: Some(VertAlign::Subscript), ..Default::default() };
let d = doc_with(vec![para_runs(&[("plain ", CharProps::default()), ("everything", all.clone()), (" auto", auto.clone())])]);
let mut d = doc_with(vec![para_runs(&[("plain ", CharProps::default()), ("everything", all.clone()), (" auto", auto.clone())])]);
d.settings.major_font = "Georgia".into();
let r = rt(&d);
let p = paras(&r)[0];
assert_eq!(p.text, "plain everything auto");
+67
View File
@@ -0,0 +1,67 @@
//! Theme font slots of the East Asian and complex-script fonts (`w:rFonts/@w:eastAsiaTheme`,
//! `@w:cstheme`, ISO/IEC 29500-1 §17.3.2.26). Word picks those fonts through the slot, so a save
//! that drops it changes the font of East Asian punctuation and, with it, Word's line breaks.
use std::io::{Read, Write};
fn docx(body: &str, styles: &str) -> Vec<u8> {
let root = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
let doc_rels = r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
let doc = format!(
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}</w:body></w:document>"#
);
let styles = format!(
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">{styles}</w:styles>"#
);
let parts = [
("_rels/.rels", root.to_string()),
("word/document.xml", doc),
("word/_rels/document.xml.rels", doc_rels.to_string()),
("word/styles.xml", styles),
];
let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
for (name, xml) in &parts {
zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
zw.write_all(xml.as_bytes()).unwrap();
}
zw.finish().unwrap().into_inner()
}
fn part(bytes: &[u8], name: &str) -> String {
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let mut s = String::new();
z.by_name(name).unwrap().read_to_string(&mut s).unwrap();
s
}
fn rfonts(xml: &str) -> Vec<String> {
xml.match_indices("<w:rFonts").map(|(i, _)| xml[i..].split('>').next().unwrap_or("").to_string()).collect()
}
#[test]
fn theme_font_slots_survive_a_save() {
// As pandoc writes them: theme slots only, in the document defaults, and on a run.
let styles = r#"<w:docDefaults><w:rPrDefault><w:rPr><w:rFonts w:asciiTheme="minorHAnsi" w:eastAsiaTheme="minorEastAsia" w:hAnsiTheme="minorHAnsi" w:cstheme="minorBidi"/><w:lang w:val="en-US" w:eastAsia="zh-CN"/></w:rPr></w:rPrDefault></w:docDefaults>"#;
let body = r#"<w:p><w:r><w:rPr><w:rFonts w:eastAsiaTheme="majorEastAsia" w:cstheme="bogus"/></w:rPr><w:t>“Quoted” text</w:t></w:r></w:p>"#;
let d = craft_docx::read(&docx(body, styles)).unwrap();
let run = &d.body[0].as_para().unwrap().runs[0];
assert_eq!(run.props.font_ea_theme, Some(craft_wordmodel::props::ThemeFont::MajorEastAsia));
assert_eq!(run.props.font_cs_theme, None, "a name outside ST_Theme is not kept");
let out = craft_docx::write(&d).unwrap();
let styles_out = rfonts(&part(&out, "word/styles.xml"));
assert!(
styles_out.iter().any(|f| f.contains(r#"w:eastAsiaTheme="minorEastAsia""#) && f.contains(r#"w:cstheme="minorBidi""#)),
"the document defaults keep their theme slots: {styles_out:?}"
);
let doc_out = rfonts(&part(&out, "word/document.xml"));
assert!(doc_out.iter().any(|f| f.contains(r#"w:eastAsiaTheme="majorEastAsia""#)), "the run keeps its slot: {doc_out:?}");
}
#[test]
fn a_named_east_asian_font_replaces_the_theme_slot() {
let mut base = craft_wordmodel::props::CharProps { font_ea_theme: Some(craft_wordmodel::props::ThemeFont::MinorEastAsia), ..Default::default() };
base.overlay(&craft_wordmodel::props::CharProps { font_ea: Some("SimSun".into()), ..Default::default() });
assert_eq!(base.font_ea.as_deref(), Some("SimSun"));
assert_eq!(base.font_ea_theme, None, "the slot would otherwise win over the font just chosen");
}
+64 -1
View File
@@ -23,7 +23,8 @@ mod para_props;
mod table_props;
pub use char_props::{
CharProps, CombineBrackets, DEFAULT_FONT_SIZE, EastAsianLayout, EmphasisMark, Highlight, Ligatures, NumChange, PropChange, Underline, VertAlign,
CharProps, CombineBrackets, DEFAULT_FONT_SIZE, EastAsianLayout, EmphasisMark, Highlight, Ligatures, NumChange, PropChange, ThemeFont, Underline,
VertAlign,
};
pub use color::{Rgb, TextColor};
pub use para_props::{
@@ -39,6 +40,68 @@ pub use table_props::{
mod tests {
use super::*;
/// A run's theme slot equal to its base's stays while the run's named font differs: overlaid
/// alone, that font would clear the base's slot, so the round trip would lose the slot.
#[test]
fn minus_keeps_a_theme_slot_whose_font_stays() {
let s = |v: &str| Some(v.to_string());
let base = CharProps {
font: s("Aptos"),
font_ascii_theme: Some(ThemeFont::MinorHAnsi),
font_hansi_theme: Some(ThemeFont::MinorHAnsi),
font_ea: s("SimSun"),
font_ea_theme: Some(ThemeFont::MinorEastAsia),
font_cs: s("Arial"),
font_cs_theme: Some(ThemeFont::MinorBidi),
..Default::default()
};
let run = CharProps { font: s("Georgia"), font_ea: s("MS Mincho"), font_cs: s("Times New Roman"), ..base.clone() };
let patch = run.clone().minus(&base);
assert_eq!((patch.font_ea_theme, patch.font_cs_theme), (Some(ThemeFont::MinorEastAsia), Some(ThemeFont::MinorBidi)));
assert_eq!(patch.font_ascii_theme, Some(ThemeFont::MinorHAnsi));
let mut back = base.clone();
back.overlay(&patch);
assert_eq!(back, run, "base plus the patch is the run again");
// A font equal to the base's goes, and its slot with it.
let same = base.clone().minus(&base);
assert_eq!((same.font_ea_theme, same.font_cs_theme, same.font_ascii_theme), (None, None, None));
}
/// A run that names its base's font but none of its slots (a font chosen in place of the
/// theme's) keeps that font in the patch, so overlaying it clears the slots again.
#[test]
fn minus_keeps_a_same_font_that_clears_its_slots() {
let s = |v: &str| Some(v.to_string());
let base = CharProps {
font: s("Aptos"),
font_ascii_theme: Some(ThemeFont::MinorHAnsi),
font_hansi_theme: Some(ThemeFont::MinorHAnsi),
font_ea: s("SimSun"),
font_ea_theme: Some(ThemeFont::MinorEastAsia),
font_cs: s("Arial"),
font_cs_theme: Some(ThemeFont::MinorBidi),
..Default::default()
};
let run = CharProps { font_ascii_theme: None, font_hansi_theme: None, font_ea_theme: None, font_cs_theme: None, ..base.clone() };
let mut back = base.clone();
back.overlay(&run.clone().minus(&base));
assert_eq!(back, run);
}
/// A named font with only one of its Latin slots replaces the other slot too: the base's
/// would name another font.
#[test]
fn a_font_with_one_latin_slot_replaces_both() {
let mut base = CharProps {
font: Some("Verdana".into()),
font_ascii_theme: Some(ThemeFont::MinorHAnsi),
font_hansi_theme: Some(ThemeFont::MinorHAnsi),
..Default::default()
};
base.overlay(&CharProps { font: Some("Georgia".into()), font_ascii_theme: Some(ThemeFont::MajorAscii), ..Default::default() });
assert_eq!((base.font_ascii_theme, base.font_hansi_theme), (Some(ThemeFont::MajorAscii), None));
}
#[test]
fn rgb_hex() {
assert_eq!(Rgb(255, 0, 16).hex(), "FF0010");
+130 -2
View File
@@ -105,6 +105,64 @@ impl Ligatures {
}
}
/// A theme font slot (ST_Theme, ISO/IEC 29500-1 §17.18.96): which of the theme's major
/// (headings) or minor (body) fonts, for which script. One byte, where a string took 24 in every
/// `CharProps`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ThemeFont {
MajorEastAsia,
MajorBidi,
MajorAscii,
MajorHAnsi,
MinorEastAsia,
MinorBidi,
MinorAscii,
MinorHAnsi,
}
impl ThemeFont {
const ALL: [ThemeFont; 8] = [
ThemeFont::MajorEastAsia,
ThemeFont::MajorBidi,
ThemeFont::MajorAscii,
ThemeFont::MajorHAnsi,
ThemeFont::MinorEastAsia,
ThemeFont::MinorBidi,
ThemeFont::MinorAscii,
ThemeFont::MinorHAnsi,
];
/// The slot's OOXML name (`minorHAnsi`…).
pub fn as_str(self) -> &'static str {
match self {
ThemeFont::MajorEastAsia => "majorEastAsia",
ThemeFont::MajorBidi => "majorBidi",
ThemeFont::MajorAscii => "majorAscii",
ThemeFont::MajorHAnsi => "majorHAnsi",
ThemeFont::MinorEastAsia => "minorEastAsia",
ThemeFont::MinorBidi => "minorBidi",
ThemeFont::MinorAscii => "minorAscii",
ThemeFont::MinorHAnsi => "minorHAnsi",
}
}
/// The slot named `s` (`None` for any other value).
pub fn parse(s: &str) -> Option<ThemeFont> {
ThemeFont::ALL.into_iter().find(|t| t.as_str() == s)
}
/// Whether the slot picks one of the theme's major (heading) fonts.
pub fn is_major(self) -> bool {
matches!(self, ThemeFont::MajorEastAsia | ThemeFont::MajorBidi | ThemeFont::MajorAscii | ThemeFont::MajorHAnsi)
}
/// Whether the slot is one of Latin text's (`w:asciiTheme`, `w:hAnsiTheme`).
pub fn is_latin(self) -> bool {
matches!(self, ThemeFont::MajorAscii | ThemeFont::MajorHAnsi | ThemeFont::MinorAscii | ThemeFont::MinorHAnsi)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub enum VertAlign {
@@ -239,6 +297,14 @@ pub struct CharProps {
pub style: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub font: Option<String>,
/// The theme font slots `font` came from (`w:rFonts/@w:asciiTheme`, `@w:hAnsiTheme`:
/// `minorHAnsi`, `majorAscii`…), kept so saving writes them back and the text keeps following
/// the theme's fonts in Word. Layout reads `font` only. Saving writes a slot only while it
/// still names `font` in the document's theme, so a font chosen later is never hidden by it.
#[serde(skip_serializing_if = "Option::is_none")]
pub font_ascii_theme: Option<ThemeFont>,
#[serde(skip_serializing_if = "Option::is_none")]
pub font_hansi_theme: Option<ThemeFont>,
/// The symbol's own font (OOXML `w:sym/@w:font`, ECMA-376 §17.3.3.30), set on a symbol
/// character from a `w:sym` or Insert › Symbol: it is shown in this font whatever `font` is,
/// so changing the text's font keeps the symbol. `None` = the run's font.
@@ -333,6 +399,16 @@ pub struct CharProps {
/// inherit, then `font`.
#[serde(skip_serializing_if = "Option::is_none")]
pub font_ea: Option<String>,
/// The theme font slot of the East Asian font (`w:rFonts/@w:eastAsiaTheme`: `minorEastAsia`,
/// `majorEastAsia`…), kept so saving writes it back. Word picks the East Asian font through it
/// (over `font_ea`); losing it changes which font Word uses for CJK and East Asian punctuation,
/// and so the line breaks. Layout doesn't read it: `font_ea` and inheritance decide there.
#[serde(skip_serializing_if = "Option::is_none")]
pub font_ea_theme: Option<ThemeFont>,
/// The theme font slot of the complex-script font (`w:rFonts/@w:cstheme`: `minorBidi`…), kept
/// so saving writes it back, like `font_ea_theme`.
#[serde(skip_serializing_if = "Option::is_none")]
pub font_cs_theme: Option<ThemeFont>,
/// Complex-script size, points (`w:szCs`). `None` leaves the inherited value unchanged.
#[serde(skip_serializing_if = "Option::is_none")]
pub size_cs: Option<f32>,
@@ -496,13 +572,30 @@ impl CharProps {
/// The fields of `self` that differ from `base` (equal ones unset): what `self` adds when
/// overlaid on `base`.
pub fn minus(mut self, base: &CharProps) -> CharProps {
let font = self.font.clone();
self.minus_text_style(base);
self.minus_latin_theme(base, font);
self.minus_run_visibility(base);
self.minus_script_style(base);
self.minus_document_marks(base);
self
}
fn minus_latin_theme(&mut self, base: &CharProps, font: Option<String>) {
// A slot stays with a font that stays: overlaid alone, the font would clear the base's
// slots (`overlay_latin_theme`), so dropping a slot equal to the base's would lose it.
let keep = (self.font_ascii_theme, self.font_hansi_theme);
drop_same_fields!(self, base; font_ascii_theme, font_hansi_theme);
// And a font equal to the base's stays when its slots differ (a chosen font clears
// them): without it the patch's `None` slots would inherit the base's again.
if self.font.is_none() && font.is_some() && keep != (base.font_ascii_theme, base.font_hansi_theme) {
self.font = font;
}
if self.font.is_some() {
(self.font_ascii_theme, self.font_hansi_theme) = keep;
}
}
fn minus_text_style(&mut self, base: &CharProps) {
drop_same_fields!(self, base; style, font, sym_font, size, bold, italic, underline, underline_color, strike, double_strike, color, highlight,
shading, border, vert_align, caps, small_caps, hidden, spacing, scale, position, kern, outline, shadow, emboss, engrave, lang, no_proof, rtl);
@@ -513,7 +606,23 @@ impl CharProps {
}
fn minus_script_style(&mut self, base: &CharProps) {
drop_same_fields!(self, base; cs, font_cs, font_ea, size_cs, bold_cs, italic_cs, lang_bidi, lang_ea, east_asian_layout);
// As for the Latin slots: a slot stays while its named font does.
let keep = (self.font_ea_theme, self.font_cs_theme);
let (ea, cs) = (self.font_ea.clone(), self.font_cs.clone());
drop_same_fields!(self, base; cs, font_cs, font_ea, font_ea_theme, font_cs_theme, size_cs, bold_cs, italic_cs, lang_bidi, lang_ea, east_asian_layout);
// A font equal to the base's stays when its slot differs, as for the Latin slots.
if self.font_ea.is_none() && keep.0 != base.font_ea_theme {
self.font_ea = ea;
}
if self.font_cs.is_none() && keep.1 != base.font_cs_theme {
self.font_cs = cs;
}
if self.font_ea.is_some() {
self.font_ea_theme = keep.0;
}
if self.font_cs.is_some() {
self.font_cs_theme = keep.1;
}
}
fn minus_document_marks(&mut self, base: &CharProps) {
@@ -526,6 +635,7 @@ impl CharProps {
/// format both scripts must set both values explicitly.
pub fn overlay(&mut self, patch: &CharProps) {
self.overlay_text_style(patch);
self.overlay_latin_theme(patch);
self.overlay_run_visibility(patch);
self.overlay_script_style(patch);
self.overlay_document_marks(patch);
@@ -534,6 +644,16 @@ impl CharProps {
}
}
fn overlay_latin_theme(&mut self, patch: &CharProps) {
// A font set replaces both slots with its own, `None` included (as for `font_ea_theme`):
// a slot left from the base would name another font, and Word reads it over `font`.
if patch.font.is_some() {
(self.font_ascii_theme, self.font_hansi_theme) = (patch.font_ascii_theme, patch.font_hansi_theme);
} else {
overlay_fields!(self, patch; font_ascii_theme, font_hansi_theme);
}
}
fn overlay_text_style(&mut self, patch: &CharProps) {
overlay_fields!(self, patch; style, font, sym_font, size, bold, italic, underline, underline_color, strike, double_strike, color, highlight,
shading, border, vert_align, caps, small_caps, hidden, spacing, scale, position, kern, outline, shadow, emboss, engrave, lang, no_proof, rtl);
@@ -544,7 +664,15 @@ impl CharProps {
}
fn overlay_script_style(&mut self, patch: &CharProps) {
overlay_fields!(self, patch; cs, font_cs, font_ea, size_cs, bold_cs, italic_cs, lang_bidi, lang_ea, east_asian_layout);
// A font set without a theme slot replaces the slot too: in Word the slot wins over the
// named font, so keeping it would hide the font just chosen.
if patch.font_ea.is_some() && patch.font_ea_theme.is_none() {
self.font_ea_theme = None;
}
if patch.font_cs.is_some() && patch.font_cs_theme.is_none() {
self.font_cs_theme = None;
}
overlay_fields!(self, patch; cs, font_cs, font_ea, font_ea_theme, font_cs_theme, size_cs, bold_cs, italic_cs, lang_bidi, lang_ea, east_asian_layout);
}
fn overlay_document_marks(&mut self, patch: &CharProps) {