diff --git a/crates/drawingml/src/part.rs b/crates/drawingml/src/part.rs index 27215f85d..af2f6b736 100644 --- a/crates/drawingml/src/part.rs +++ b/crates/drawingml/src/part.rs @@ -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#" + + + + + +"#; + + 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#""#), "{xml}"); + assert!(xml.contains(r#""#), "{xml}"); + assert!(xml.contains(r#""#), "{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#""#), "{xml}"); + assert!(xml.contains(r#""#), "{xml}"); + assert!(xml.contains(r#""#), "{xml}"); + assert!(xml.contains(r#""#), "{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("") < at("") && at("") < at(""#), "{xml}"); + assert!(xml.contains(r#""#), "{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#""#), "{xml}"); + assert!(!xml.contains("020F0502020204030204"), "{xml}"); + assert!(xml.contains(r#""#, r#""#) + .replace(r#""#, r#""#); + let t = crate::theme::read_theme(&mut Part::new(), &parse(file.as_bytes()).unwrap()); + let (xml, _) = theme_round_trip(&t); + assert!(xml.contains(r#""#), "{xml}"); + assert!(xml.contains(r#""#), "{xml}"); + } + + #[test] + fn custom_colours_and_family_id_without_object_defaults_follow_an_empty_one() { + let file = THEME_FILE.replace("", ""); + 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("") < at(""), "{xml}"); + assert!(at("") < at(""#; + 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#"{}"#, w.finish()); + assert!(xml.find("{}"#, 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(), ""); + // 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")); + } } diff --git a/crates/drawingml/src/read.rs b/crates/drawingml/src/read.rs index 9e9f8ff3e..f26bf2073 100644 --- a/crates/drawingml/src/read.rs +++ b/crates/drawingml/src/read.rs @@ -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::().ok()) else { continue }; if !(1..=9).contains(&l) { continue; diff --git a/crates/drawingml/src/text.rs b/crates/drawingml/src/text.rs index f60f23236..dc34cf10f 100644 --- a/crates/drawingml/src/text.rs +++ b/crates/drawingml/src/text.rs @@ -706,6 +706,12 @@ pub struct LevelStyle { pub struct ListStyle { /// Levels 1–9 (index 0–8); `None` = not specified. pub levels: Vec>, + /// 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>, } 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` (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::() <= 32, "{}", std::mem::size_of::()); + } + #[test] fn alternate_language_inherits_and_native_input_is_bounded() { let mut child = RunProps::default(); diff --git a/crates/drawingml/src/theme.rs b/crates/drawingml/src/theme.rs index 69d7c2af6..bfe435be9 100644 --- a/crates/drawingml/src/theme.rs +++ b/crates/drawingml/src/theme.rs @@ -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, } +/// 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, + pub pitch_family: Option, + pub charset: Option, +} + +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, } +/// A colour slot written as a system colour (``). +#[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, + /// 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, } @@ -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, } } diff --git a/crates/drawingml/src/theme/read.rs b/crates/drawingml/src/theme/read.rs index 29e49dc93..0f4e4b2f0 100644 --- a/crates/drawingml/src/theme/read.rs +++ b/crates/drawingml/src/theme/read.rs @@ -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(); diff --git a/crates/drawingml/src/theme/write.rs b/crates/drawingml/src/theme/write.rs index 5e95e57eb..bc46d59e3 100644 --- a/crates/drawingml/src/theme/write.rs +++ b/crates/drawingml/src/theme/write.rs @@ -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 { 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); diff --git a/crates/drawingml/src/write.rs b/crates/drawingml/src/write.rs index 25bfb89db..da3f10d79 100644 --- a/crates/drawingml/src/write.rs +++ b/crates/drawingml/src/write.rs @@ -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); diff --git a/crates/drawingml/src/xmlx.rs b/crates/drawingml/src/xmlx.rs index d31616b39..27fa58dc7 100644 --- a/crates/drawingml/src/xmlx.rs +++ b/crates/drawingml/src/xmlx.rs @@ -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>) -> 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 (``): 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#""#, + ) + .unwrap(); + let ns = ns_decls(&root); + let kid = |n: &str| root.child(Local(n)).unwrap(); + assert_eq!(keep_xml(kid("custClrLst"), &ns), r#""#); + assert_eq!(keep_xml(kid("y"), &ns), r#""#, "prefixed: as before"); + assert_eq!(keep_xml(kid("z"), &ns), r#""#, "an unprefixed descendant"); + assert_eq!(keep_xml(kid("own"), &ns), r#""#, "its own default wins"); + assert_eq!(keep_xml(kid("u"), &ns), r#""#, "an undeclared default stays"); + // A part with no default namespace: unprefixed names stay in no namespace. + let plain = parse(br#""#).unwrap(); + assert_eq!(keep_xml(plain.child(Local("x")).unwrap(), &ns_decls(&plain)), ""); + // The default declaration spends the budget like the others. + let budget = Cell::new(3); + assert_eq!( + keep_with(kid("custClrLst"), &[&ns], Some(&budget)), + r#""# + ); + } + #[test] fn inner_declarations_are_found_and_clashing_ones_dropped() { let root = parse(br#""#).unwrap(); diff --git a/crates/pptx/tests/read.rs b/crates/pptx/tests/read.rs index 5fe263f02..fd03d2d98 100644 --- a/crates/pptx/tests/read.rs +++ b/crates/pptx/tests/read.rs @@ -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 { let open = r#""#; let tree = format!("{}{}{}", open.repeat(40), sp(4, "Deep", "", XFRM, "x"), "".repeat(40)); let pres = format!(r#""#); let slide = format!(r#"{tree}{}"#, 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(); +} diff --git a/crates/pptx/tests/write.rs b/crates/pptx/tests/write.rs index bec5fb239..46f7513e7 100644 --- a/crates/pptx/tests/write.rs +++ b/crates/pptx/tests/write.rs @@ -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 { + fn rec(e: &craft_xml::El, scope: &mut Vec<(String, String)>, local: &str, out: &mut Vec) { + 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#""#; + +/// The deck with its theme part replaced by `theme`. +fn with_theme(theme: &str) -> Vec { + 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("").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#""# + ); + 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#""#; + let (open, close) = (format!("<{root} "), format!("")); + 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 { + 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();