craft-drawingml: keep theme sysClr, custClrLst, theme family id, font panose and a:defPPr on save

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
vangel76andClaude Sonnet 5.5 committed 2026-11-15 18:38:29 +01:00
1 parent c9de09877b
commit 88c52213b4
7 files changed
+167 -11

No files matched your search

+80
View File
@@ -239,4 +239,84 @@ mod tests {
assert_eq!(back.extra.len(), MAX_EXTRA_COLORS);
assert_eq!(back.extra[0].tints.as_deref(), Some(&long[..MAX_TINT_ROWS]));
}
const THEME_FILE: &str = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office Theme"><a:themeElements>
<a:clrScheme name="Office"><a:dk1><a:sysClr val="windowText" lastClr="000000"/></a:dk1><a:lt1><a:sysClr val="window" lastClr="FFFFFF"/></a:lt1><a:dk2><a:srgbClr val="44546A"/></a:dk2><a:lt2><a:srgbClr val="E7E6E6"/></a:lt2><a:accent1><a:srgbClr val="4472C4"/></a:accent1><a:accent2><a:srgbClr val="ED7D31"/></a:accent2><a:accent3><a:srgbClr val="A5A5A5"/></a:accent3><a:accent4><a:srgbClr val="FFC000"/></a:accent4><a:accent5><a:srgbClr val="5B9BD5"/></a:accent5><a:accent6><a:srgbClr val="70AD47"/></a:accent6><a:hlink><a:srgbClr val="0563C1"/></a:hlink><a:folHlink><a:srgbClr val="954F72"/></a:folHlink></a:clrScheme>
<a:fontScheme name="Office"><a:majorFont><a:latin typeface="Calibri Light" panose="020F0302020204030204" pitchFamily="34" charset="0"/><a:ea typeface="" panose="02010600030101010101" charset="-122"/><a:cs typeface="" panose="020B0604020202020204"/></a:majorFont><a:minorFont><a:latin typeface="Calibri" panose="020F0502020204030204"/><a:ea typeface=""/><a:cs typeface=""/></a:minorFont></a:fontScheme>
<a:fmtScheme name="Office"><a:fillStyleLst><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:fillStyleLst><a:lnStyleLst><a:ln w="6350"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:ln><a:ln w="12700"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:ln><a:ln w="19050"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:ln></a:lnStyleLst><a:effectStyleLst><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle></a:effectStyleLst><a:bgFillStyleLst><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:bgFillStyleLst></a:fmtScheme></a:themeElements>
<a:objectDefaults/><a:extraClrSchemeLst/><a:custClrLst><a:custClr name="Brand red"><a:srgbClr val="C00000"/></a:custClr><a:custClr name="Brand teal"><a:srgbClr val="008080"/></a:custClr></a:custClrLst>
<a:extLst><a:ext uri="{05A4C25C-085E-4340-85A3-A5531E510DB2}"><thm15:themeFamily xmlns:thm15="http://schemas.microsoft.com/office/thememl/2012/main" name="Office Theme" id="{62F939B6-93AF-4DB8-9C6B-D6C7DFDC589F}" vid="{4A3C46E8-61CC-4603-A589-7422A47A8E4A}"/></a:ext></a:extLst></a:theme>"#;
fn theme_round_trip(t: &Theme) -> (String, Theme) {
let xml = String::from_utf8(crate::theme::theme_xml(&mut Part::new(), t)).unwrap();
let back = crate::theme::read_theme(&mut Part::new(), &parse(xml.as_bytes()).unwrap());
(xml, back)
}
#[test]
fn a_theme_keeps_system_colours_custom_colours_family_id_and_font_panose() {
let t = crate::theme::read_theme(&mut Part::new(), &parse(THEME_FILE.as_bytes()).unwrap());
assert_eq!(t.sys_colors.len(), 2);
let (xml, back) = theme_round_trip(&t);
assert!(xml.contains(r#"<a:dk1><a:sysClr val="windowText" lastClr="000000"/></a:dk1>"#), "{xml}");
assert!(xml.contains(r#"<a:lt1><a:sysClr val="window" lastClr="FFFFFF"/></a:lt1>"#), "{xml}");
assert!(xml.contains(r#"<a:dk2><a:srgbClr val="44546A"/></a:dk2>"#), "{xml}");
assert!(xml.contains("Brand red") && xml.contains("C00000") && xml.contains("Brand teal") && xml.contains("008080"), "{xml}");
assert!(xml.contains("thm15:themeFamily") && xml.contains("{62F939B6-93AF-4DB8-9C6B-D6C7DFDC589F}") && xml.contains("{4A3C46E8-61CC-4603-A589-7422A47A8E4A}"), "{xml}");
assert!(xml.contains(r#"<a:latin typeface="Calibri Light" panose="020F0302020204030204" pitchFamily="34" charset="0"/>"#), "{xml}");
assert!(xml.contains(r#"<a:ea typeface="" panose="02010600030101010101" charset="-122"/>"#), "{xml}");
assert!(xml.contains(r#"<a:cs typeface="" panose="020B0604020202020204"/>"#), "{xml}");
assert!(xml.contains(r#"<a:latin typeface="Calibri" panose="020F0502020204030204"/>"#), "{xml}");
assert_eq!((&back.sys_colors, &back.colors.colors, &back.fonts, &back.raw_extra), (&t.sys_colors, &t.colors.colors, &t.fonts, &t.raw_extra), "read, write, read changes nothing");
// Order: the colour list comes before the extension list, both after the theme elements.
let at = |n: &str| xml.find(n).unwrap_or_else(|| panic!("{n} in {xml}"));
assert!(at("</a:themeElements>") < at("<a:custClrLst>") && at("<a:custClrLst>") < at("<a:extLst><a:ext uri=\"{05A4"), "{xml}");
}
#[test]
fn a_system_colour_slot_that_was_changed_is_written_as_srgb_and_absent_parts_stay_absent() {
let mut t = crate::theme::read_theme(&mut Part::new(), &parse(THEME_FILE.as_bytes()).unwrap());
t.colors.set(SchemeSlot::Dk1, crate::color::Rgba::rgb(0x11, 0x22, 0x33));
let (xml, _) = theme_round_trip(&t);
assert!(xml.contains(r#"<a:dk1><a:srgbClr val="112233"/></a:dk1>"#), "{xml}");
assert!(xml.contains(r#"<a:lt1><a:sysClr val="window" lastClr="FFFFFF"/></a:lt1>"#), "{xml}");
let (plain, back) = theme_round_trip(&Theme::default());
assert!(!plain.contains("sysClr") && !plain.contains("custClrLst") && !plain.contains("themeFamily") && !plain.contains("panose"), "{plain}");
assert!(back.sys_colors.is_empty() && back.fonts.minor.latin_attrs.is_empty());
}
#[test]
fn list_styles_keep_def_ppr_in_every_place_they_are_written() {
use crate::text::{ListStyle, TextBody};
let src = r#"<p:x xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"><a:defPPr marL="457200" algn="ctr"><a:defRPr lang="de-DE" sz="1800"/></a:defPPr><a:lvl1pPr marL="0"><a:defRPr sz="4400"/></a:lvl1pPr></p:x>"#;
let ls = crate::read::list_style(&mut Part::new(), &parse(src.as_bytes()).unwrap());
let d = ls.default_level.as_ref().expect("defPPr read");
assert_eq!((d.para.margin_left, d.para.align, d.run.lang.as_deref(), d.run.size), (Some(36.0), Some(crate::text::Align::Center), Some("de-DE"), Some(18.0)));
assert_eq!(ls.level(0).and_then(|l| l.run.size), Some(44.0));
for tag in ["p:defaultTextStyle", "p:titleStyle", "p:bodyStyle", "p:otherStyle", "p:notesStyle", "a:lstStyle"] {
let mut w = craft_xml::Writer::new();
crate::write::list_style(&mut w, &mut Part::new(), tag, &ls);
let xml = format!(r#"<p:x xmlns:a="a" xmlns:p="p">{}</p:x>"#, w.finish());
assert!(xml.find("<a:defPPr").unwrap() < xml.find("<a:lvl1pPr").unwrap(), "{tag}: {xml}");
let back = crate::read::list_style(&mut Part::new(), parse(xml.as_bytes()).unwrap().child(craft_xml::Local(&tag[2..])).unwrap());
assert_eq!(back, ls, "{tag}");
}
// A text body's own list style, and an explicit but empty `a:defPPr`.
let tb = TextBody { list_style: ls.clone(), ..TextBody::from_text("x") };
let mut w = craft_xml::Writer::new();
crate::write::text_body(&mut w, &mut Part::new(), "p:txBody", &tb, false);
let xml = format!(r#"<r xmlns:a="a" xmlns:p="p">{}</r>"#, w.finish());
let back = crate::read::text_body(&mut Part::new(), parse(xml.as_bytes()).unwrap().child(craft_xml::Local("txBody")).unwrap());
assert_eq!(back.list_style, ls);
let empty = ListStyle { default_level: Some(Default::default()), ..Default::default() };
assert!(!empty.is_empty());
let mut w = craft_xml::Writer::new();
crate::write::list_style(&mut w, &mut Part::new(), "p:defaultTextStyle", &empty);
assert_eq!(w.finish(), "<p:defaultTextStyle><a:defPPr/></p:defaultTextStyle>");
// Without `a:defPPr` none is written.
let mut w = craft_xml::Writer::new();
crate::write::list_style(&mut w, &mut Part::new(), "p:defaultTextStyle", &ListStyle { default_level: None, ..ls });
assert!(!w.finish().contains("defPPr"));
}
}
+5
View File
@@ -623,6 +623,11 @@ pub fn list_style(src: &mut dyn Source, ls: &El) -> ListStyle {
let mut out = ListStyle::default();
for e in ls.elements() {
let n = e.local();
if n == "defPPr" {
let (_, para, run) = ppr(src, e);
out.default_level = Some(LevelStyle { para, run: run.unwrap_or_default() });
continue;
}
let Some(l) = n.strip_prefix("lvl").and_then(|r| r.strip_suffix("pPr")).and_then(|d| d.parse::<u8>().ok()) else { continue };
if !(1..=9).contains(&l) {
continue;
+5 -1
View File
@@ -706,6 +706,10 @@ pub struct LevelStyle {
pub struct ListStyle {
/// Levels 1–9 (index 0–8); `None` = not specified.
pub levels: Vec<Option<LevelStyle>>,
/// The default paragraph style (`a:defPPr`) that sits under levels 1–9; `None` = the list
/// style has no `a:defPPr`.
#[serde(skip_serializing_if = "Option::is_none")]
pub default_level: Option<LevelStyle>,
}
impl ListStyle {
@@ -722,7 +726,7 @@ impl ListStyle {
}
}
pub fn is_empty(&self) -> bool {
self.levels.iter().all(Option::is_none)
self.default_level.is_none() && self.levels.iter().all(Option::is_none)
}
}
+44 -1
View File
@@ -11,11 +11,35 @@ pub struct FontSet {
pub latin: String,
pub ea: String,
pub cs: String,
/// The `panose`, `pitchFamily` and `charset` the file gives the Latin, East Asian and complex
/// script typefaces; `None` = the attribute is absent.
#[serde(skip_serializing_if = "TypefaceAttrs::is_empty")]
pub latin_attrs: TypefaceAttrs,
#[serde(skip_serializing_if = "TypefaceAttrs::is_empty")]
pub ea_attrs: TypefaceAttrs,
#[serde(skip_serializing_if = "TypefaceAttrs::is_empty")]
pub cs_attrs: TypefaceAttrs,
/// Per-script typefaces (`a:font script="Arab" typeface="…"`), in document order.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub scripts: Vec<ScriptFont>,
}
/// The font-matching attributes of a theme typeface (`a:latin`, `a:ea`, `a:cs`).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct TypefaceAttrs {
/// Ten hex byte pairs, as written.
pub panose: Option<String>,
pub pitch_family: Option<String>,
pub charset: Option<String>,
}
impl TypefaceAttrs {
pub fn is_empty(&self) -> bool {
self.panose.is_none() && self.pitch_family.is_none() && self.charset.is_none()
}
}
/// A theme font for one script (ISO 15924 tag, e.g. `Arab`).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
@@ -53,6 +77,17 @@ pub struct FormatScheme {
pub bg_fills: Vec<Fill>,
}
/// A colour slot written as a system colour (`<a:dk1><a:sysClr val="windowText" lastClr="000000"/>`).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SysColor {
pub slot: SchemeSlot,
/// The `val` (`windowText`, `window`…).
pub name: String,
/// The `lastClr`.
pub last: Rgba,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Theme {
@@ -60,7 +95,14 @@ pub struct Theme {
pub colors: ColorScheme,
pub fonts: FontScheme,
pub format: FormatScheme,
/// Raw theme XML extras kept for round-trip (object defaults, extra colour lists).
/// The colour slots the file wrote as `a:sysClr` (`dk1` `windowText`, `lt1` `window`), in
/// document order. The writer keeps a slot as `a:sysClr` while its colour still equals
/// `last`; a slot whose colour was changed is written as `a:srgbClr`.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub sys_colors: Vec<SysColor>,
/// Raw theme XML extras kept for round-trip, in document order: object defaults, extra
/// colour lists, custom colours (`a:custClrLst`) and the extension list (`a:extLst`, which
/// holds the theme family id).
#[serde(skip_serializing_if = "Option::is_none")]
pub raw_extra: Option<String>,
}
@@ -76,6 +118,7 @@ impl Default for Theme {
colors: ColorScheme::new("Default", colors.map(hex)),
fonts: FontScheme::default(),
format: default_format(),
sys_colors: Vec::new(),
raw_extra: None,
}
}
+12 -4
View File
@@ -2,7 +2,7 @@
use crate::color::{ColorScheme, Rgba, SchemeSlot};
use crate::style::{ColorBase, Effects};
use crate::theme::{FontScheme, FontSet, FormatScheme, ScriptFont, Theme, default_format};
use crate::theme::{FontScheme, FontSet, FormatScheme, ScriptFont, SysColor, Theme, TypefaceAttrs, default_format};
use craft_xml::{El, Local};
@@ -21,7 +21,12 @@ fn font_set(e: Option<&El>) -> FontSet {
.collect()
})
.unwrap_or_default();
FontSet { latin: tf("latin"), ea: tf("ea"), cs: tf("cs"), scripts }
let attrs = |n: &str| {
let c = e.and_then(|e| e.child(Local(n)));
let at = |a: &str| c.and_then(|c| c.attr_local(a)).map(String::from);
TypefaceAttrs { panose: at("panose"), pitch_family: at("pitchFamily"), charset: at("charset") }
};
FontSet { latin: tf("latin"), ea: tf("ea"), cs: tf("cs"), latin_attrs: attrs("latin"), ea_attrs: attrs("ea"), cs_attrs: attrs("cs"), scripts }
}
pub fn read_theme(src: &mut dyn Source, root: &El) -> Theme {
@@ -33,7 +38,10 @@ pub fn read_theme(src: &mut dyn Source, root: &El) -> Theme {
if let Some(c) = cs.child(Local(slot.xml_name())).and_then(dml::color) {
let rgb = match c.base {
ColorBase::Rgb { rgb } => rgb,
ColorBase::System { last, .. } => last,
ColorBase::System { name, last } => {
t.sys_colors.push(SysColor { slot, name, last });
last
}
ColorBase::Preset { name } => crate::color::preset(&name).unwrap_or(Rgba::BLACK),
ColorBase::Scheme { .. } => continue,
};
@@ -90,7 +98,7 @@ pub fn read_theme(src: &mut dyn Source, root: &El) -> Theme {
}
let extra: String = root
.elements()
.filter(|e| e.is(Local("objectDefaults")) || e.is(Local("extraClrSchemeLst")))
.filter(|e| ["objectDefaults", "extraClrSchemeLst", "custClrLst", "extLst"].iter().any(|n| e.is(Local(n))))
.filter(|e| !crate::xmlx::has_rel_refs(e))
.map(|e| src.keep(e))
.collect();
+17 -5
View File
@@ -2,7 +2,7 @@
use crate::color::{ColorScheme, Rgba, SchemeSlot};
use crate::style::{ColorRef, Effects, Fill};
use crate::theme::{FontSet, Theme, default_format};
use crate::theme::{FontSet, Theme, TypefaceAttrs, default_format};
use craft_xml::Writer;
@@ -12,9 +12,17 @@ use crate::write as dml;
fn font_set(w: &mut Writer, tag: &str, f: &FontSet) {
w.open(tag, &[]);
w.tag("a:latin").attr("typeface", if f.latin.is_empty() { "Arial" } else { &f.latin }).empty();
w.tag("a:ea").attr("typeface", &f.ea).empty();
w.tag("a:cs").attr("typeface", &f.cs).empty();
let face = |w: &mut Writer, tag: &str, name: &str, a: &TypefaceAttrs| {
w.tag(tag)
.attr("typeface", name)
.attr_opt("panose", a.panose.as_deref())
.attr_opt("pitchFamily", a.pitch_family.as_deref())
.attr_opt("charset", a.charset.as_deref())
.empty();
};
face(w, "a:latin", if f.latin.is_empty() { "Arial" } else { &f.latin }, &f.latin_attrs);
face(w, "a:ea", &f.ea, &f.ea_attrs);
face(w, "a:cs", &f.cs, &f.cs_attrs);
for sf in &f.scripts {
w.tag("a:font").attr("script", &sf.script).attr("typeface", &sf.typeface).empty();
}
@@ -74,7 +82,11 @@ pub fn theme_xml(out: &mut dyn Sink, t: &Theme) -> Vec<u8> {
for slot in SchemeSlot::THEME {
let tag = format!("a:{}", slot.xml_name());
w.open(&tag, &[]);
w.tag("a:srgbClr").attr("val", t.colors.get(slot).hex()).empty();
let rgb = t.colors.get(slot);
match t.sys_colors.iter().find(|s| s.slot == slot && s.last == rgb && crate::color::is_system_name(&s.name)) {
Some(s) => w.tag("a:sysClr").attr("val", &s.name).attr("lastClr", rgb.hex()).empty(),
None => w.tag("a:srgbClr").attr("val", rgb.hex()).empty(),
}
w.close();
}
extra_colors(&mut w, &t.colors);
+4
View File
@@ -777,6 +777,10 @@ pub fn list_style(w: &mut Writer, out: &mut dyn Sink, tag: &str, ls: &ListStyle)
return;
}
w.open(tag, &[]);
if let Some(l) = &ls.default_level {
let def = (l.run != RunProps::default()).then_some(&l.run);
ppr(w, out, "a:defPPr", None, &l.para, def);
}
for (i, l) in ls.levels.iter().enumerate().take(9) {
if let Some(l) = l {
let t = format!("a:lvl{}pPr", i + 1);