Merge pull request #1682 from vangel76/fix/drawingml-theme-roundtrip-1676

Saving a presentation keeps the theme's system colours, custom colours, theme family id, font panose and default paragraph style
This commit is contained in:
Dylan M. Taylor authored and GitHub committed 2026-11-16 16:14:28 -05:00
commit c012a1f397
10 files changed
+431 -19

No files matched your search

+125
View File
@@ -239,4 +239,129 @@ 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 font_panose_is_dropped_when_the_typeface_changes() {
let mut t = crate::theme::read_theme(&mut Part::new(), &parse(THEME_FILE.as_bytes()).unwrap());
t.fonts.minor.latin = "Arial".into();
let (xml, _) = theme_round_trip(&t);
assert!(xml.contains(r#"<a:latin typeface="Arial"/>"#), "{xml}");
assert!(!xml.contains("020F0502020204030204"), "{xml}");
assert!(xml.contains(r#"<a:latin typeface="Calibri Light" panose="020F0302020204030204""#), "the unchanged major font keeps it: {xml}");
}
#[test]
fn system_colour_without_last_clr_gets_it_and_an_unknown_name_becomes_srgb() {
let file = THEME_FILE
.replace(r#"<a:sysClr val="windowText" lastClr="000000"/>"#, r#"<a:sysClr val="windowText"/>"#)
.replace(r#"<a:sysClr val="window" lastClr="FFFFFF"/>"#, r#"<a:sysClr val="notAColor" lastClr="123456"/>"#);
let t = crate::theme::read_theme(&mut Part::new(), &parse(file.as_bytes()).unwrap());
let (xml, _) = 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:srgbClr val="123456"/></a:lt1>"#), "{xml}");
}
#[test]
fn custom_colours_and_family_id_without_object_defaults_follow_an_empty_one() {
let file = THEME_FILE.replace("<a:objectDefaults/><a:extraClrSchemeLst/>", "");
let t = crate::theme::read_theme(&mut Part::new(), &parse(file.as_bytes()).unwrap());
let (xml, back) = theme_round_trip(&t);
let at = |n: &str| xml.find(n).unwrap_or_else(|| panic!("{n} in {xml}"));
assert!(at("</a:themeElements>") < at("<a:objectDefaults") && at("<a:objectDefaults") < at("<a:custClrLst>"), "{xml}");
assert!(at("<a:custClrLst>") < at("<a:extLst><a:ext uri=\"{05A4"), "{xml}");
let raw = back.raw_extra.unwrap_or_default();
assert!(raw.contains("Brand teal") && raw.contains("{62F939B6-93AF-4DB8-9C6B-D6C7DFDC589F}"), "{raw}");
}
#[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(Box::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(Box::new(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;
+15 -1
View File
@@ -706,6 +706,12 @@ 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`. Boxed: it sits inline in every `ListStyle`, hence in every text
/// body and shape, and the recursive group readers (pptx) would otherwise overflow the stack
/// of a debug build on Windows (1 MiB main thread) at the nesting depth the tests cut at.
#[serde(skip_serializing_if = "Option::is_none")]
pub default_level: Option<Box<LevelStyle>>,
}
impl ListStyle {
@@ -722,7 +728,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)
}
}
@@ -759,6 +765,14 @@ mod tests {
use super::*;
use crate::color::Rgba;
/// `ListStyle` sits inline in every `TextBody`/`Shape`, which the pptx group reader holds on the
/// stack once per nesting level. Keep it at `Vec` (24) + `Option<Box>` (8) bytes (the `defPPr`
/// level is boxed) so a debug build does not overflow the 1 MiB Windows main-thread stack.
#[test]
fn list_style_stays_small() {
assert!(std::mem::size_of::<ListStyle>() <= 32, "{}", std::mem::size_of::<ListStyle>());
}
#[test]
fn alternate_language_inherits_and_native_input_is_bounded() {
let mut child = RunProps::default();
+46 -1
View File
@@ -11,11 +11,37 @@ 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 {
/// The typeface name these attributes belong to; the writer drops them once the typeface changed.
pub typeface: String,
/// 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 +79,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 +97,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 +120,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 { typeface: at("typeface").unwrap_or_default(), 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();
+20 -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,20 @@ 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| {
// Panose and the like describe one font: a changed typeface does not keep them.
let none = TypefaceAttrs::default();
let a = if a.typeface == name { a } else { &none };
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 +85,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);
+47 -3
View File
@@ -156,7 +156,20 @@ fn used_prefixes(el: &El) -> HashSet<&str> {
used
}
/// Serialize `el`, declaring every prefix it uses that the source root declared.
/// Does `el` or a descendant have an unprefixed name that no `xmlns` inside `el` binds? Such a
/// name is in the default namespace of the part it was read from. Attributes never are.
fn uses_outer_default(el: &El) -> bool {
fn rec(e: &El, depth: usize) -> bool {
if depth > MAX_DEPTH || e.attrs.iter().any(|(k, _)| k == "xmlns") {
return false;
}
!e.name.contains(':') || e.elements().any(|c| rec(c, depth + 1))
}
rec(el, 0)
}
/// Serialize `el`, declaring every prefix it uses that the source root declared, and the
/// root's default namespace when an unprefixed name in `el` depends on it.
pub fn keep_xml(el: &El, ns: &[(String, String)]) -> String {
keep_with(el, &[ns], None)
}
@@ -166,11 +179,15 @@ pub fn keep_xml(el: &El, ns: &[(String, String)]) -> String {
/// [`MAX_COPIED_NS_BYTES`]).
pub fn keep_with(el: &El, decls: &[&[(String, String)]], budget: Option<&Cell<usize>>) -> String {
let used = used_prefixes(el);
let default = uses_outer_default(el);
let mut have: HashSet<&str> = el.attrs.iter().map(|(a, _)| a.as_str()).collect();
let mut extra = Vec::new();
for (k, v) in decls.iter().flat_map(|d| d.iter()) {
let p = k.strip_prefix("xmlns:").unwrap_or("");
if !p.is_empty() && used.contains(p) && v.len() <= MAX_NS_VALUE && !have.contains(k.as_str()) {
let wanted = match k.strip_prefix("xmlns:") {
Some(p) => !p.is_empty() && used.contains(p),
None => k == "xmlns" && default,
};
if wanted && v.len() <= MAX_NS_VALUE && !have.contains(k.as_str()) {
let cost = k.len() + v.len();
if let Some(b) = budget {
if b.get() < cost {
@@ -324,6 +341,33 @@ mod tests {
assert!(!has_rel_refs(root.child(Local("z")).unwrap()));
}
/// A part written with a default namespace (`<theme xmlns="…/main">`): an unprefixed
/// fragment, or one with an unprefixed descendant, carries that namespace; a prefixed one
/// and one that declares its own default are written as before.
#[test]
fn a_kept_fragment_carries_the_default_namespace_its_names_depend_on() {
let root = parse(
br#"<theme xmlns="D" xmlns:r="R"><custClrLst><custClr name="x"><srgbClr val="FF0000"/></custClr></custClrLst><r:y/><r:z><w/></r:z><own xmlns="O"><v/></own><r:u><t xmlns=""/></r:u></theme>"#,
)
.unwrap();
let ns = ns_decls(&root);
let kid = |n: &str| root.child(Local(n)).unwrap();
assert_eq!(keep_xml(kid("custClrLst"), &ns), r#"<custClrLst xmlns="D"><custClr name="x"><srgbClr val="FF0000"/></custClr></custClrLst>"#);
assert_eq!(keep_xml(kid("y"), &ns), r#"<r:y xmlns:r="R"/>"#, "prefixed: as before");
assert_eq!(keep_xml(kid("z"), &ns), r#"<r:z xmlns="D" xmlns:r="R"><w/></r:z>"#, "an unprefixed descendant");
assert_eq!(keep_xml(kid("own"), &ns), r#"<own xmlns="O"><v/></own>"#, "its own default wins");
assert_eq!(keep_xml(kid("u"), &ns), r#"<r:u xmlns:r="R"><t xmlns=""/></r:u>"#, "an undeclared default stays");
// A part with no default namespace: unprefixed names stay in no namespace.
let plain = parse(br#"<p:sld xmlns:p="P"><x/></p:sld>"#).unwrap();
assert_eq!(keep_xml(plain.child(Local("x")).unwrap(), &ns_decls(&plain)), "<x/>");
// The default declaration spends the budget like the others.
let budget = Cell::new(3);
assert_eq!(
keep_with(kid("custClrLst"), &[&ns], Some(&budget)),
r#"<custClrLst><custClr name="x"><srgbClr val="FF0000"/></custClr></custClrLst>"#
);
}
#[test]
fn inner_declarations_are_found_and_clashing_ones_dropped() {
let root = parse(br#"<r xmlns:a="A"><x xmlns:b="B"><y xmlns:c="C1"/></x><z xmlns:c="C2" xmlns:a="A"/></r>"#).unwrap();
+34 -5
View File
@@ -217,23 +217,52 @@ fn other_files_are_refused() {
assert!(craft_pptx::import_theme(&doc).is_err());
}
/// Groups nested past 32 levels are cut there; the rest of the slide is read.
#[test]
fn deep_group_nesting_is_cut() {
/// A slide whose group tree is 40 levels deep, with a shape after it.
fn deep_group_deck() -> Vec<u8> {
let open = r#"<p:grpSp><p:nvGrpSpPr><p:cNvPr id="0" name="G"/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr/>"#;
let tree = format!("{}{}{}", open.repeat(40), sp(4, "Deep", "", XFRM, "x"), "</p:grpSp>".repeat(40));
let pres = format!(r#"<p:presentation {NS}><p:sldIdLst><p:sldId id="256" r:id="rId1"/></p:sldIdLst></p:presentation>"#);
let slide = format!(r#"<p:sld {NS}><p:cSld><p:spTree>{tree}{}</p:spTree></p:cSld></p:sld>"#, sp(5, "Top", "", XFRM, "y"));
let bytes = package(
package(
&[
("ppt/presentation.xml", CT_PRES, pres),
("ppt/slides/slide1.xml", "application/vnd.openxmlformats-officedocument.presentationml.slide+xml", slide),
],
&[("", &[("officeDocument", "ppt/presentation.xml")]), ("ppt/presentation.xml", &[("slide", "slides/slide1.xml")])],
);
)
}
/// Groups nested past 32 levels are cut there; the rest of the slide is read.
#[test]
fn deep_group_nesting_is_cut() {
let bytes = deep_group_deck();
let p = craft_pptx::import(&bytes, &Plain).unwrap();
let mut depth = 0;
craft_pptx::walk(&p.slides[0].shapes, &mut |_, d| depth = depth.max(d));
assert_eq!(depth, 32, "33 levels of groups, the last one empty");
assert!(p.slides[0].shapes.iter().any(|s| s.name == "Top"));
}
/// The group reader recurses once per nesting level and keeps a `Shape` per level on the stack, so
/// anything that makes `Shape` (or `TextBody`/`ListStyle` inside it) bigger shows up here first.
/// A debug build is the worst case, so import the deepest accepted tree on a stack that is small
/// but ample for the current size: measured in a Linux debug build, this import needs about
/// 1.3 MiB, and about 2 MiB when `ListStyle` holds its `defPPr` level inline. Fails with a stack
/// overflow (the process aborts) when a type on the recursive path grows by value. Linux only:
/// frame sizes differ per platform, and the Windows CI runs `deep_group_nesting_is_cut` on the
/// default stack, where that growth first showed up.
#[test]
#[cfg(target_os = "linux")]
fn deep_group_import_fits_a_small_stack() {
const STACK: usize = 1664 * 1024;
std::thread::Builder::new()
.stack_size(STACK)
.spawn(|| {
let bytes = deep_group_deck();
let p = craft_pptx::import(&bytes, &Plain).unwrap();
assert!(p.slides[0].shapes.iter().any(|s| s.name == "Top"));
})
.unwrap()
.join()
.unwrap();
}
+123
View File
@@ -1,5 +1,7 @@
//! The writer, read back with the reader.
mod common;
use std::sync::Arc;
use craft_pptx::table::{Cell, Table};
@@ -193,6 +195,127 @@ fn reads_the_theme_of_a_pptx_and_of_a_thmx() {
}
}
const NS_A: &str = "http://schemas.openxmlformats.org/drawingml/2006/main";
const NS_P: &str = "http://schemas.openxmlformats.org/presentationml/2006/main";
const NS_THM15: &str = "http://schemas.microsoft.com/office/thememl/2012/main";
/// The namespace of every element named `local` in `xml`, resolved through the declarations in
/// scope (`""` for none).
fn namespaces_of(xml: &str, local: &str) -> Vec<String> {
fn rec(e: &craft_xml::El, scope: &mut Vec<(String, String)>, local: &str, out: &mut Vec<String>) {
let n = scope.len();
scope.extend(e.ns_decls().map(|(p, u)| (p.to_string(), u.to_string())));
if e.local() == local {
out.push(scope.iter().rev().find(|(p, _)| p == e.prefix()).map(|(_, u)| u.clone()).unwrap_or_default());
}
for c in e.elements() {
rec(c, scope, local, out);
}
scope.truncate(n);
}
let root = craft_xml::Options::default().strict().parse(xml.as_bytes()).unwrap_or_else(|e| panic!("not well-formed: {e}\n{xml}"));
let mut out = vec![];
rec(&root, &mut vec![], local, &mut out);
out
}
/// A theme with a custom colour list and a theme family id, with the `a:` prefix.
const PREFIXED_THEME: &str = r#"<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" name="Harbour"><a:themeElements><a:clrScheme name="Harbour"><a:dk1><a:srgbClr val="000000"/></a:dk1><a:lt1><a:srgbClr val="FFFFFF"/></a:lt1><a:dk2><a:srgbClr val="1F1F1F"/></a:dk2><a:lt2><a:srgbClr val="EEEEEE"/></a:lt2><a:accent1><a:srgbClr val="123456"/></a:accent1><a:accent2><a:srgbClr val="222222"/></a:accent2><a:accent3><a:srgbClr val="333333"/></a:accent3><a:accent4><a:srgbClr val="444444"/></a:accent4><a:accent5><a:srgbClr val="555555"/></a:accent5><a:accent6><a:srgbClr val="666666"/></a:accent6><a:hlink><a:srgbClr val="0000FF"/></a:hlink><a:folHlink><a:srgbClr val="800080"/></a:folHlink></a:clrScheme><a:fontScheme name="Harbour"><a:majorFont><a:latin typeface="Lato"/><a:ea typeface=""/><a:cs typeface=""/></a:majorFont><a:minorFont><a:latin typeface="Calibri"/><a:ea typeface=""/><a:cs typeface=""/></a:minorFont></a:fontScheme><a:fmtScheme name="Harbour"><a:fillStyleLst/><a:lnStyleLst/><a:effectStyleLst><a:effectStyle><a:effectLst/><a:scene3d><a:camera prst="orthographicFront"/><a:lightRig rig="threePt" dir="t"/></a:scene3d><a:sp3d><a:bevelT w="63500" h="25400"/></a:sp3d></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle></a:effectStyleLst><a:bgFillStyleLst/></a:fmtScheme></a:themeElements><a:objectDefaults/><a:extraClrSchemeLst/><a:custClrLst><a:custClr name="Brand"><a:srgbClr val="C00000"/></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="Harbour" id="{62F939B6-93AF-4DB8-9C6B-D6C7DFDC589F}" vid="{4A3C46E8-61CC-4603-A589-7422A47A8E4A}"/></a:ext></a:extLst></a:theme>"#;
/// The deck with its theme part replaced by `theme`.
fn with_theme(theme: &str) -> Vec<u8> {
let pptx = craft_pptx::export(&deck(), &Plain).unwrap();
common::rewrite(&pptx, |name, data| Some(if name == "ppt/theme/theme1.xml" { theme.as_bytes().to_vec() } else { data.to_vec() }), &[])
}
/// A theme written with a default namespace instead of the `a:` prefix: the parts kept as
/// written (custom colours, theme family id) stay in the DrawingML namespace on save.
#[test]
fn a_default_namespace_theme_keeps_its_kept_parts_in_the_drawingml_namespace() {
let theme = PREFIXED_THEME.replace("<a:", "<").replace("</a:", "</").replace("xmlns:a=", "xmlns=");
assert!(!theme.contains("a:"), "{theme}");
let p = craft_pptx::import(&with_theme(&theme), &Plain).unwrap();
assert_eq!(p.masters[0].theme.colors.get(SchemeSlot::Accent1), Rgba::rgb(0x12, 0x34, 0x56));
let once = craft_pptx::export(&p, &Plain).unwrap();
let xml = part(&once, "ppt/theme/theme1.xml");
// The writer may add an `a:extLst` of its own to the colour scheme, so every one is checked.
for local in ["objectDefaults", "custClrLst", "custClr", "extLst", "ext", "srgbClr"] {
let ns = namespaces_of(&xml, local);
assert!(!ns.is_empty() && ns.iter().all(|n| n == NS_A), "{local}: {ns:?}\n{xml}");
}
assert_eq!(namespaces_of(&xml, "themeFamily"), [NS_THM15], "{xml}");
// The effect style's 3-D is kept as written too.
assert_eq!(namespaces_of(&xml, "scene3d"), [NS_A], "{xml}");
assert_eq!(namespaces_of(&xml, "sp3d"), [NS_A], "{xml}");
// The second save writes the same kept parts.
let kept = |x: &str| x[x.find("</a:themeElements>").expect("themeElements")..].to_string();
let twice = craft_pptx::export(&craft_pptx::import(&once, &Plain).unwrap(), &Plain).unwrap();
assert_eq!(kept(&part(&twice, "ppt/theme/theme1.xml")), kept(&xml));
}
/// The same theme with the `a:` prefix: the kept parts are written as before (each declaring
/// the `a:` it uses), with no default namespace added.
#[test]
fn a_prefixed_theme_keeps_its_kept_parts_unchanged() {
let p = craft_pptx::import(&with_theme(PREFIXED_THEME), &Plain).unwrap();
let xml = part(&craft_pptx::export(&p, &Plain).unwrap(), "ppt/theme/theme1.xml");
assert!(!xml.contains(r#" xmlns=""#), "{xml}");
let a = format!(r#"xmlns:a="{NS_A}""#);
let kept = format!(
r#"<a:objectDefaults {a}/><a:extraClrSchemeLst {a}/><a:custClrLst {a}><a:custClr name="Brand"><a:srgbClr val="C00000"/></a:custClr></a:custClrLst><a:extLst {a}><a:ext uri="{{05A4C25C-085E-4340-85A3-A5531E510DB2}}"><thm15:themeFamily xmlns:thm15="{NS_THM15}" name="Harbour" id="{{62F939B6-93AF-4DB8-9C6B-D6C7DFDC589F}}" vid="{{4A3C46E8-61CC-4603-A589-7422A47A8E4A}}"/></a:ext></a:extLst></a:theme>"#
);
assert!(xml.contains(&kept), "{xml}");
}
/// The deck with part `name` (root `root`) given a default PresentationML namespace and an
/// unprefixed extension list, saved again: the part as written.
fn default_namespace_extensions(name: &str, root: &str) -> String {
let pptx = craft_pptx::export(&deck(), &Plain).unwrap();
let ext = r#"<extLst><ext uri="{11111111-2222-3333-4444-555555555555}"><t:data xmlns:t="urn:test" v="1"/></ext></extLst>"#;
let (open, close) = (format!("<{root} "), format!("</{root}>"));
let doc = common::rewrite(
&pptx,
|n, data| {
if n != name {
return Some(data.to_vec());
}
let xml = String::from_utf8(data.to_vec()).unwrap();
assert!(xml.contains(&open) && xml.contains(&close) && !xml.contains("extLst"), "{xml}");
Some(xml.replacen(&open, &format!(r#"<{root} xmlns="{NS_P}" "#), 1).replace(&close, &format!("{ext}{close}")).into_bytes())
},
&[],
);
let p = craft_pptx::import(&doc, &Plain).unwrap();
part(&craft_pptx::export(&p, &Plain).unwrap(), name)
}
/// The namespaces of the `ext` elements in `xml` other than DrawingML's `a:ext` (an extent).
fn extension_namespaces(xml: &str) -> Vec<String> {
namespaces_of(xml, "ext").into_iter().filter(|n| n != NS_A).collect()
}
/// A slide written with a default PresentationML namespace: its kept extension list stays in
/// that namespace under the writer's `p:extLst`.
#[test]
fn a_default_namespace_slide_keeps_its_extensions_in_the_presentationml_namespace() {
let xml = default_namespace_extensions("ppt/slides/slide1.xml", "p:sld");
assert!(xml.contains("{11111111-2222-3333-4444-555555555555}"), "{xml}");
assert_eq!(extension_namespaces(&xml), [NS_P], "{xml}");
assert_eq!(namespaces_of(&xml, "data"), ["urn:test"], "{xml}");
}
/// The same for a layout and a master, whose kept extension list is written back through
/// `ext_children`.
#[test]
fn a_default_namespace_layout_and_master_keep_their_extensions_in_the_presentationml_namespace() {
for (name, root) in [("ppt/slideLayouts/slideLayout1.xml", "p:sldLayout"), ("ppt/slideMasters/slideMaster1.xml", "p:sldMaster")] {
let xml = default_namespace_extensions(name, root);
assert!(xml.contains("{11111111-2222-3333-4444-555555555555}"), "{name}: {xml}");
assert_eq!(extension_namespaces(&xml), [NS_P], "{name}: {xml}");
assert_eq!(namespaces_of(&xml, "data"), ["urn:test"], "{name}: {xml}");
}
}
#[test]
fn templates_and_shows_differ_in_the_main_content_type() {
let p = deck();