diff --git a/Cargo.lock b/Cargo.lock index 55ea98973..935348240 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -943,7 +943,7 @@ dependencies = [ [[package]] name = "craft-cfb" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10#ea24422ae9859dc5da398d0462bc87f8e02e0d10" +source = "git+https://github.com/storytold/craft-libs?rev=8048f8ef92da80fb3ce5a056d59ca591ee66faf1#8048f8ef92da80fb3ce5a056d59ca591ee66faf1" [[package]] name = "craft-codepage" @@ -970,20 +970,9 @@ dependencies = [ [[package]] name = "craft-drawingml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=44d83fa8f635333dcb3c231f87381387a1f5631b#44d83fa8f635333dcb3c231f87381387a1f5631b" +source = "git+https://github.com/storytold/craft-libs?rev=8048f8ef92da80fb3ce5a056d59ca591ee66faf1#8048f8ef92da80fb3ce5a056d59ca591ee66faf1" dependencies = [ - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=44d83fa8f635333dcb3c231f87381387a1f5631b)", - "kurbo", - "log", - "serde", -] - -[[package]] -name = "craft-drawingml" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=cff5af869dbf6926801c9ac63a927d155202ba3b#cff5af869dbf6926801c9ac63a927d155202ba3b" -dependencies = [ - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=cff5af869dbf6926801c9ac63a927d155202ba3b)", + "craft-xml", "kurbo", "log", "serde", @@ -1057,10 +1046,10 @@ dependencies = [ [[package]] name = "craft-opc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10#ea24422ae9859dc5da398d0462bc87f8e02e0d10" +source = "git+https://github.com/storytold/craft-libs?rev=8048f8ef92da80fb3ce5a056d59ca591ee66faf1#8048f8ef92da80fb3ce5a056d59ca591ee66faf1" dependencies = [ - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10)", - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10)", + "craft-xml", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=8048f8ef92da80fb3ce5a056d59ca591ee66faf1)", "log", "thiserror 2.0.21", ] @@ -1074,6 +1063,21 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-pptx" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8048f8ef92da80fb3ce5a056d59ca591ee66faf1#8048f8ef92da80fb3ce5a056d59ca591ee66faf1" +dependencies = [ + "craft-drawingml", + "craft-opc", + "craft-xml", + "kurbo", + "log", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-rtf" version = "0.1.0" @@ -1164,32 +1168,13 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=44d83fa8f635333dcb3c231f87381387a1f5631b#44d83fa8f635333dcb3c231f87381387a1f5631b" +source = "git+https://github.com/storytold/craft-libs?rev=8048f8ef92da80fb3ce5a056d59ca591ee66faf1#8048f8ef92da80fb3ce5a056d59ca591ee66faf1" dependencies = [ "quick-xml 0.41.0", "serde", "thiserror 2.0.21", ] -[[package]] -name = "craft-xml" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=cff5af869dbf6926801c9ac63a927d155202ba3b#cff5af869dbf6926801c9ac63a927d155202ba3b" -dependencies = [ - "quick-xml 0.41.0", - "serde", - "thiserror 2.0.21", -] - -[[package]] -name = "craft-xml" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10#ea24422ae9859dc5da398d0462bc87f8e02e0d10" -dependencies = [ - "quick-xml 0.41.0", - "thiserror 2.0.21", -] - [[package]] name = "craft-zip" version = "0.1.0" @@ -1203,7 +1188,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10#ea24422ae9859dc5da398d0462bc87f8e02e0d10" +source = "git+https://github.com/storytold/craft-libs?rev=8048f8ef92da80fb3ce5a056d59ca591ee66faf1#8048f8ef92da80fb3ce5a056d59ca591ee66faf1" dependencies = [ "flate2", "thiserror 2.0.21", @@ -1326,7 +1311,7 @@ dependencies = [ name = "deckcraft-color" version = "0.19.0" dependencies = [ - "craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=44d83fa8f635333dcb3c231f87381387a1f5631b)", + "craft-drawingml", ] [[package]] @@ -1384,7 +1369,7 @@ dependencies = [ name = "deckcraft-geom" version = "0.19.0" dependencies = [ - "craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=44d83fa8f635333dcb3c231f87381387a1f5631b)", + "craft-drawingml", "kurbo", "serde", ] @@ -1417,7 +1402,7 @@ dependencies = [ name = "deckcraft-model" version = "0.19.0" dependencies = [ - "craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=44d83fa8f635333dcb3c231f87381387a1f5631b)", + "craft-drawingml", "deckcraft-color", "deckcraft-geom", "serde", @@ -1464,17 +1449,15 @@ name = "deckcraft-pptx" version = "0.19.0" dependencies = [ "craft-cfb", - "craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=44d83fa8f635333dcb3c231f87381387a1f5631b)", - "craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=cff5af869dbf6926801c9ac63a927d155202ba3b)", + "craft-drawingml", "craft-opc", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10)", + "craft-pptx", + "craft-xml", "deckcraft-color", "deckcraft-engine", "deckcraft-geom", "deckcraft-model", - "deckcraft-text", "image", - "log", "quick-xml 0.41.0", "serde_json", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index ce055c54d..9d7380cc3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,16 +11,16 @@ rust-version = "1.95" repository = "https://github.com/storytold/deckcraft" [workspace.dependencies] -# OPC part-name primitives; relationship admission stays app-local. -craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9859dc5da398d0462bc87f8e02e0d10", version = "0.1.0" } +# OPC part-name primitives and package reader/writer. +craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "8048f8ef92da80fb3ce5a056d59ca591ee66faf1", version = "0.1.0" } # Compound File Binary directory reads (password-protected deck detection). -craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9859dc5da398d0462bc87f8e02e0d10", version = "0.1.0" } -# XML writer primitives; parser admission and OOXML policy stay app-local. -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9859dc5da398d0462bc87f8e02e0d10", version = "0.1.0" } -# DrawingML colours, themes and text (craft-libs#778, #792): the model DeckCraft reads and writes. -# Isolated table XML writer; existing DrawingML model/readers keep their revision. -craft-drawingml-table = { package = "craft-drawingml", git = "https://github.com/storytold/craft-libs", rev = "cff5af869dbf6926801c9ac63a927d155202ba3b" } -craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "44d83fa8f635333dcb3c231f87381387a1f5631b", version = "0.1.0" } +craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "8048f8ef92da80fb3ce5a056d59ca591ee66faf1", version = "0.1.0" } +# Bounded XML reader and writer primitives. +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "8048f8ef92da80fb3ce5a056d59ca591ee66faf1", version = "0.1.0" } +# DrawingML colours, themes, charts, tables and text (craft-libs#778, #792). +craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "8048f8ef92da80fb3ce5a056d59ca591ee66faf1", version = "0.1.0" } +# PresentationML PPTX/POTX/PPSX reader and writer (craft-libs#778). +craft-pptx = { git = "https://github.com/storytold/craft-libs", rev = "8048f8ef92da80fb3ce5a056d59ca591ee66faf1", version = "0.1.0" } # Shared MCP stdio framing and protocol constants (craft-libs#778). craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "bc186ca719958fcce3b6ee24794277eabed14609", version = "0.1.0" } # internal diff --git a/crates/pptx/Cargo.toml b/crates/pptx/Cargo.toml index f023baae5..48fdbcfd6 100644 --- a/crates/pptx/Cargo.toml +++ b/crates/pptx/Cargo.toml @@ -9,19 +9,15 @@ description = "DeckCraft PPTX: Office Open XML (PresentationML/DrawingML) import workspace = true [dependencies] +craft-pptx.workspace = true craft-opc.workspace = true craft-xml.workspace = true craft-cfb.workspace = true craft-drawingml.workspace = true -craft-drawingml-table.workspace = true deckcraft-model = { workspace = true } -deckcraft-text = { workspace = true } deckcraft-geom = { workspace = true } deckcraft-color = { workspace = true } -quick-xml = { workspace = true } -zip = { workspace = true } thiserror = { workspace = true } -log = { workspace = true } [dev-dependencies] deckcraft-engine = { workspace = true } @@ -29,4 +25,5 @@ serde_json = { workspace = true } deckcraft-color = { workspace = true } deckcraft-geom = { workspace = true } image = { workspace = true } +quick-xml = { workspace = true } zip = { workspace = true } diff --git a/crates/pptx/src/convert.rs b/crates/pptx/src/convert.rs new file mode 100644 index 000000000..3a31b1a3f --- /dev/null +++ b/crates/pptx/src/convert.rs @@ -0,0 +1,2321 @@ +//! Bidirectional conversion between DeckCraft's document model (`deckcraft_model`) and the +//! shared PresentationML/DrawingML model (`craft_pptx` / `craft_drawingml`). + +use std::sync::Arc; + +use craft_drawingml::chart as cd_chart; +use craft_drawingml::diagram as cd_dgm; +use craft_drawingml::style as cd_style; +use craft_drawingml::table as cd_table; +use craft_drawingml::text as cd_text; +use craft_drawingml::theme as cd_theme; +use craft_pptx::anim as cp_anim; +use deckcraft_model::anim as dm_anim; +use deckcraft_model::chart as dm_chart; +use deckcraft_model::style as dm_style; +use deckcraft_model::table as dm_table; +use deckcraft_model::text as dm_text; +use deckcraft_model::theme as dm_theme; + +// --------------------------------------------------------------------------- +// IDs +// --------------------------------------------------------------------------- + +fn media_id_to(id: deckcraft_model::MediaId) -> craft_pptx::MediaId { + craft_pptx::MediaId(id.0) +} +fn media_id_from(id: craft_pptx::MediaId) -> deckcraft_model::MediaId { + deckcraft_model::MediaId(id.0) +} +fn slide_id_to(id: deckcraft_model::SlideId) -> craft_pptx::SlideId { + craft_pptx::SlideId(id.0) +} +fn slide_id_from(id: craft_pptx::SlideId) -> deckcraft_model::SlideId { + deckcraft_model::SlideId(id.0) +} +fn shape_id_to(id: deckcraft_model::ShapeId) -> craft_pptx::ShapeId { + craft_pptx::ShapeId(id.0) +} +fn shape_id_from(id: craft_pptx::ShapeId) -> deckcraft_model::ShapeId { + deckcraft_model::ShapeId(id.0) +} +fn layout_id_to(id: deckcraft_model::LayoutId) -> craft_pptx::LayoutId { + craft_pptx::LayoutId(id.0) +} +fn layout_id_from(id: craft_pptx::LayoutId) -> deckcraft_model::LayoutId { + deckcraft_model::LayoutId(id.0) +} +fn master_id_to(id: deckcraft_model::MasterId) -> craft_pptx::MasterId { + craft_pptx::MasterId(id.0) +} +fn master_id_from(id: craft_pptx::MasterId) -> deckcraft_model::MasterId { + deckcraft_model::MasterId(id.0) +} + +// --------------------------------------------------------------------------- +// Style +// --------------------------------------------------------------------------- + +fn color_base_to(b: &dm_style::ColorBase) -> cd_style::ColorBase { + match b { + dm_style::ColorBase::Rgb { rgb } => cd_style::ColorBase::Rgb { rgb: *rgb }, + dm_style::ColorBase::Scheme { slot } => cd_style::ColorBase::Scheme { slot: *slot }, + dm_style::ColorBase::Preset { name } => cd_style::ColorBase::Preset { name: name.clone() }, + dm_style::ColorBase::System { name, last } => cd_style::ColorBase::System { name: name.clone(), last: *last }, + } +} + +fn color_base_from(b: cd_style::ColorBase) -> dm_style::ColorBase { + match b { + cd_style::ColorBase::Rgb { rgb } => dm_style::ColorBase::Rgb { rgb }, + cd_style::ColorBase::Scheme { slot } => dm_style::ColorBase::Scheme { slot }, + cd_style::ColorBase::Preset { name } => dm_style::ColorBase::Preset { name }, + cd_style::ColorBase::System { name, last } => dm_style::ColorBase::System { name, last }, + } +} + +fn color_ref_to(c: &dm_style::ColorRef) -> cd_style::ColorRef { + cd_style::ColorRef { base: color_base_to(&c.base), mods: c.mods.clone() } +} + +fn color_ref_from(c: cd_style::ColorRef) -> dm_style::ColorRef { + dm_style::ColorRef { base: color_base_from(c.base), mods: c.mods } +} + +fn gradient_flip_to(f: dm_style::GradientFlip) -> cd_style::GradientFlip { + match f { + dm_style::GradientFlip::None => cd_style::GradientFlip::None, + dm_style::GradientFlip::X => cd_style::GradientFlip::X, + dm_style::GradientFlip::Y => cd_style::GradientFlip::Y, + dm_style::GradientFlip::Xy => cd_style::GradientFlip::Xy, + } +} + +fn gradient_flip_from(f: cd_style::GradientFlip) -> dm_style::GradientFlip { + match f { + cd_style::GradientFlip::None => dm_style::GradientFlip::None, + cd_style::GradientFlip::X => dm_style::GradientFlip::X, + cd_style::GradientFlip::Y => dm_style::GradientFlip::Y, + cd_style::GradientFlip::Xy => dm_style::GradientFlip::Xy, + } +} + +fn gradient_shape_to(s: &dm_style::GradientShape) -> cd_style::GradientShape { + match s { + dm_style::GradientShape::Linear { angle, scaled } => cd_style::GradientShape::Linear { angle: *angle, scaled: *scaled }, + dm_style::GradientShape::Path { path, focus } => cd_style::GradientShape::Path { path: path.clone(), focus: *focus }, + } +} + +fn gradient_shape_from(s: cd_style::GradientShape) -> dm_style::GradientShape { + match s { + cd_style::GradientShape::Linear { angle, scaled } => dm_style::GradientShape::Linear { angle, scaled }, + cd_style::GradientShape::Path { path, focus } => dm_style::GradientShape::Path { path, focus }, + } +} + +fn gradient_to(g: &dm_style::Gradient) -> cd_style::Gradient { + cd_style::Gradient { + stops: g.stops.iter().map(|s| cd_style::GradientStop { pos: s.pos, color: color_ref_to(&s.color) }).collect(), + shape: Some(gradient_shape_to(&g.shape)), + flip: g.flip.map(gradient_flip_to), + rotate_with_shape: Some(g.rotate_with_shape), + tile: g.tile, + } +} + +fn gradient_from(g: cd_style::Gradient) -> dm_style::Gradient { + dm_style::Gradient { + stops: g.stops.into_iter().map(|s| dm_style::GradientStop { pos: s.pos, color: color_ref_from(s.color) }).collect(), + shape: g.shape.map(gradient_shape_from).unwrap_or(dm_style::GradientShape::Linear { angle: 0.0, scaled: false }), + flip: g.flip.map(gradient_flip_from), + rotate_with_shape: g.rotate_with_shape.unwrap_or(true), + tile: g.tile, + } +} + +fn picture_mode_to(m: &dm_style::PictureMode) -> cd_style::PictureMode { + match m { + dm_style::PictureMode::Stretch { fill_rect } => cd_style::PictureMode::Stretch { fill_rect: *fill_rect }, + dm_style::PictureMode::Tile { tx, ty, sx, sy, flip, align } => { + cd_style::PictureMode::Tile { tx: *tx, ty: *ty, sx: *sx, sy: *sy, flip: flip.clone(), align: align.clone() } + } + } +} + +fn picture_mode_from(m: cd_style::PictureMode) -> dm_style::PictureMode { + match m { + cd_style::PictureMode::Stretch { fill_rect } => dm_style::PictureMode::Stretch { fill_rect }, + cd_style::PictureMode::Tile { tx, ty, sx, sy, flip, align } => dm_style::PictureMode::Tile { tx, ty, sx, sy, flip, align }, + } +} + +fn picture_adjust_to(a: &dm_style::PictureAdjust) -> cd_style::PictureAdjust { + cd_style::PictureAdjust { + brightness: a.brightness, + contrast: a.contrast, + saturation: a.saturation, + grayscale: a.grayscale, + duotone: a.duotone.as_ref().map(|(d, l)| (color_ref_to(d), color_ref_to(l))), + clear_color: a.clear_color, + sharpen: a.sharpen, + bilevel: a.bilevel, + alpha_inv: a.alpha_inv, + } +} + +fn picture_adjust_from(a: cd_style::PictureAdjust) -> dm_style::PictureAdjust { + dm_style::PictureAdjust { + brightness: a.brightness, + contrast: a.contrast, + saturation: a.saturation, + grayscale: a.grayscale, + duotone: a.duotone.map(|(d, l)| (color_ref_from(d), color_ref_from(l))), + clear_color: a.clear_color, + sharpen: a.sharpen, + bilevel: a.bilevel, + alpha_inv: a.alpha_inv, + } +} + +fn picture_fill_to(p: &dm_style::PictureFill) -> cd_style::PictureFill { + cd_style::PictureFill { + media: media_id_to(p.media), + svg: None, + crop: p.crop, + mode: picture_mode_to(&p.mode), + alpha: p.alpha, + adjust: picture_adjust_to(&p.adjust), + upright: p.upright, + artistic: p.artistic.as_ref().map(|a| cd_style::Artistic { effect: a.effect.clone(), original: media_id_to(a.original) }), + } +} + +fn picture_fill_from(p: cd_style::PictureFill) -> dm_style::PictureFill { + dm_style::PictureFill { + media: media_id_from(p.media), + crop: p.crop, + mode: picture_mode_from(p.mode), + alpha: p.alpha, + adjust: picture_adjust_from(p.adjust), + upright: p.upright, + artistic: p.artistic.map(|a| dm_style::Artistic { effect: a.effect, original: media_id_from(a.original) }), + } +} + +fn fill_to(f: &dm_style::Fill) -> cd_style::Fill { + match f { + dm_style::Fill::None => cd_style::Fill::None, + dm_style::Fill::Solid { color } => cd_style::Fill::Solid { color: color_ref_to(color) }, + dm_style::Fill::Gradient(g) => cd_style::Fill::Gradient(gradient_to(g)), + dm_style::Fill::Picture(p) => cd_style::Fill::Picture(picture_fill_to(p)), + dm_style::Fill::Pattern(p) => { + cd_style::Fill::Pattern(cd_style::PatternFill { preset: p.preset.clone(), fg: color_ref_to(&p.fg), bg: color_ref_to(&p.bg) }) + } + dm_style::Fill::Group => cd_style::Fill::Group, + dm_style::Fill::Background => cd_style::Fill::Background, + } +} + +fn fill_from(f: cd_style::Fill) -> dm_style::Fill { + match f { + cd_style::Fill::None => dm_style::Fill::None, + cd_style::Fill::Solid { color } => dm_style::Fill::Solid { color: color_ref_from(color) }, + cd_style::Fill::Gradient(g) => dm_style::Fill::Gradient(gradient_from(g)), + cd_style::Fill::Picture(p) => dm_style::Fill::Picture(picture_fill_from(p)), + cd_style::Fill::Pattern(p) => { + dm_style::Fill::Pattern(dm_style::PatternFill { preset: p.preset, fg: color_ref_from(p.fg), bg: color_ref_from(p.bg) }) + } + cd_style::Fill::Group => dm_style::Fill::Group, + cd_style::Fill::Background => dm_style::Fill::Background, + } +} + +fn line_to(l: &dm_style::Line) -> cd_style::Line { + cd_style::Line { + fill: l.fill.as_ref().map(fill_to), + width: l.width, + dash: l.dash.as_ref().map(|d| match d { + dm_style::Dash::Preset { name } => cd_style::Dash::Preset { name: name.clone() }, + dm_style::Dash::Custom { pattern } => cd_style::Dash::Custom { pattern: pattern.clone() }, + }), + cap: l.cap.map(|c| match c { + dm_style::LineCap::Flat => cd_style::LineCap::Flat, + dm_style::LineCap::Round => cd_style::LineCap::Round, + dm_style::LineCap::Square => cd_style::LineCap::Square, + }), + join: l.join.map(|j| match j { + dm_style::LineJoin::Round => cd_style::LineJoin::Round, + dm_style::LineJoin::Bevel => cd_style::LineJoin::Bevel, + dm_style::LineJoin::Miter => cd_style::LineJoin::Miter, + }), + miter_limit: l.miter_limit, + align: l.align.map(|a| match a { + dm_style::LineAlign::Center => cd_style::LineAlign::Center, + dm_style::LineAlign::Inside => cd_style::LineAlign::Inside, + }), + compound: l.compound.map(|c| match c { + dm_style::Compound::Single => cd_style::Compound::Single, + dm_style::Compound::Double => cd_style::Compound::Double, + dm_style::Compound::ThickThin => cd_style::Compound::ThickThin, + dm_style::Compound::ThinThick => cd_style::Compound::ThinThick, + dm_style::Compound::Triple => cd_style::Compound::Triple, + }), + head: l.head.as_ref().map(|e| cd_style::LineEnd { kind: e.kind.clone(), w: e.w.clone(), len: e.len.clone() }), + tail: l.tail.as_ref().map(|e| cd_style::LineEnd { kind: e.kind.clone(), w: e.w.clone(), len: e.len.clone() }), + } +} + +fn line_from(l: cd_style::Line) -> dm_style::Line { + dm_style::Line { + fill: l.fill.map(fill_from), + width: l.width, + dash: l.dash.map(|d| match d { + cd_style::Dash::Preset { name } => dm_style::Dash::Preset { name }, + cd_style::Dash::Custom { pattern } => dm_style::Dash::Custom { pattern }, + }), + cap: l.cap.map(|c| match c { + cd_style::LineCap::Flat => dm_style::LineCap::Flat, + cd_style::LineCap::Round => dm_style::LineCap::Round, + cd_style::LineCap::Square => dm_style::LineCap::Square, + }), + join: l.join.map(|j| match j { + cd_style::LineJoin::Round => dm_style::LineJoin::Round, + cd_style::LineJoin::Bevel => dm_style::LineJoin::Bevel, + cd_style::LineJoin::Miter => dm_style::LineJoin::Miter, + }), + miter_limit: l.miter_limit, + align: l.align.map(|a| match a { + cd_style::LineAlign::Center => dm_style::LineAlign::Center, + cd_style::LineAlign::Inside => dm_style::LineAlign::Inside, + }), + compound: l.compound.map(|c| match c { + cd_style::Compound::Single => dm_style::Compound::Single, + cd_style::Compound::Double => dm_style::Compound::Double, + cd_style::Compound::ThickThin => dm_style::Compound::ThickThin, + cd_style::Compound::ThinThick => dm_style::Compound::ThinThick, + cd_style::Compound::Triple => dm_style::Compound::Triple, + }), + head: l.head.map(|e| dm_style::LineEnd { kind: e.kind, w: e.w, len: e.len }), + tail: l.tail.map(|e| dm_style::LineEnd { kind: e.kind, w: e.w, len: e.len }), + } +} + +fn shadow_to(s: &dm_style::Shadow) -> cd_style::Shadow { + cd_style::Shadow { + color: color_ref_to(&s.color), + blur: s.blur, + dist: s.dist, + dir: s.dir, + inner: s.inner, + sx: s.sx, + sy: s.sy, + kx: s.kx, + ky: s.ky, + align: s.align.clone(), + rotate_with_shape: s.rotate_with_shape, + } +} + +fn shadow_from(s: cd_style::Shadow) -> dm_style::Shadow { + dm_style::Shadow { + color: color_ref_from(s.color), + blur: s.blur, + dist: s.dist, + dir: s.dir, + inner: s.inner, + sx: s.sx, + sy: s.sy, + kx: s.kx, + ky: s.ky, + align: s.align, + rotate_with_shape: s.rotate_with_shape, + } +} + +fn glow_to(g: &dm_style::Glow) -> cd_style::Glow { + cd_style::Glow { color: color_ref_to(&g.color), radius: g.radius } +} + +fn glow_from(g: cd_style::Glow) -> dm_style::Glow { + dm_style::Glow { color: color_ref_from(g.color), radius: g.radius } +} + +fn reflection_to(r: &dm_style::Reflection) -> cd_style::Reflection { + cd_style::Reflection { + blur: r.blur, + start_alpha: r.start_alpha, + end_alpha: r.end_alpha, + end_pos: r.end_pos, + dist: r.dist, + st_pos: r.st_pos, + dir: r.dir, + fade_dir: r.fade_dir, + sx: r.sx, + sy: r.sy, + kx: r.kx, + ky: r.ky, + align: r.align.clone(), + rotate_with_shape: r.rotate_with_shape, + } +} + +fn reflection_from(r: cd_style::Reflection) -> dm_style::Reflection { + dm_style::Reflection { + blur: r.blur, + start_alpha: r.start_alpha, + end_alpha: r.end_alpha, + end_pos: r.end_pos, + dist: r.dist, + st_pos: r.st_pos, + dir: r.dir, + fade_dir: r.fade_dir, + sx: r.sx, + sy: r.sy, + kx: r.kx, + ky: r.ky, + align: r.align, + rotate_with_shape: r.rotate_with_shape, + } +} + +fn effects_to(e: &dm_style::Effects) -> cd_style::Effects { + cd_style::Effects { + outer_shadow: e.outer_shadow.as_ref().map(shadow_to), + inner_shadow: e.inner_shadow.as_ref().map(shadow_to), + glow: e.glow.as_ref().map(glow_to), + soft_edge: e.soft_edge, + reflection: e.reflection.as_ref().map(reflection_to), + bevel: e.bevel.clone(), + raw3d: e.raw3d.clone(), + fill_overlay: e.fill_overlay.as_ref().map(|o| cd_style::FillOverlay { blend: o.blend.clone(), fill: fill_to(&o.fill) }), + } +} + +fn effects_from(e: cd_style::Effects) -> dm_style::Effects { + dm_style::Effects { + outer_shadow: e.outer_shadow.map(shadow_from), + inner_shadow: e.inner_shadow.map(shadow_from), + glow: e.glow.map(glow_from), + soft_edge: e.soft_edge, + reflection: e.reflection.map(reflection_from), + bevel: e.bevel, + raw3d: e.raw3d, + fill_overlay: e.fill_overlay.map(|o| dm_style::FillOverlay { blend: o.blend, fill: fill_from(o.fill) }), + } +} + +fn shape_style_to(s: &dm_style::ShapeStyle) -> cd_style::ShapeStyle { + cd_style::ShapeStyle { + line_ref: (s.line_ref.0, color_ref_to(&s.line_ref.1)), + fill_ref: (s.fill_ref.0, color_ref_to(&s.fill_ref.1)), + effect_ref: (s.effect_ref.0, color_ref_to(&s.effect_ref.1)), + font_ref: (s.font_ref.0.clone(), s.font_ref.1.as_ref().map(color_ref_to)), + } +} + +fn shape_style_from(s: cd_style::ShapeStyle) -> dm_style::ShapeStyle { + dm_style::ShapeStyle { + line_ref: (s.line_ref.0, color_ref_from(s.line_ref.1)), + fill_ref: (s.fill_ref.0, color_ref_from(s.fill_ref.1)), + effect_ref: (s.effect_ref.0, color_ref_from(s.effect_ref.1)), + font_ref: (s.font_ref.0, s.font_ref.1.map(color_ref_from)), + } +} + +// --------------------------------------------------------------------------- +// Text +// --------------------------------------------------------------------------- + +fn anchor_to(a: dm_text::Anchor) -> cd_text::Anchor { + match a { + dm_text::Anchor::Top => cd_text::Anchor::Top, + dm_text::Anchor::Middle => cd_text::Anchor::Middle, + dm_text::Anchor::Bottom => cd_text::Anchor::Bottom, + dm_text::Anchor::Justified => cd_text::Anchor::Justified, + dm_text::Anchor::Distributed => cd_text::Anchor::Distributed, + } +} + +fn anchor_from(a: cd_text::Anchor) -> dm_text::Anchor { + match a { + cd_text::Anchor::Top => dm_text::Anchor::Top, + cd_text::Anchor::Middle => dm_text::Anchor::Middle, + cd_text::Anchor::Bottom => dm_text::Anchor::Bottom, + cd_text::Anchor::Justified => dm_text::Anchor::Justified, + cd_text::Anchor::Distributed => dm_text::Anchor::Distributed, + } +} + +fn text_dir_to(d: dm_text::TextDir) -> cd_text::TextDir { + match d { + dm_text::TextDir::Horizontal => cd_text::TextDir::Horizontal, + dm_text::TextDir::Vertical => cd_text::TextDir::Vertical, + dm_text::TextDir::Vertical270 => cd_text::TextDir::Vertical270, + dm_text::TextDir::Stacked => cd_text::TextDir::Stacked, + dm_text::TextDir::EaVertical => cd_text::TextDir::EaVertical, + dm_text::TextDir::MongolianVertical => cd_text::TextDir::MongolianVertical, + dm_text::TextDir::StackedRtl => cd_text::TextDir::StackedRtl, + } +} + +fn text_dir_from(d: cd_text::TextDir) -> dm_text::TextDir { + match d { + cd_text::TextDir::Horizontal => dm_text::TextDir::Horizontal, + cd_text::TextDir::Vertical => dm_text::TextDir::Vertical, + cd_text::TextDir::Vertical270 => dm_text::TextDir::Vertical270, + cd_text::TextDir::Stacked => dm_text::TextDir::Stacked, + cd_text::TextDir::EaVertical => dm_text::TextDir::EaVertical, + cd_text::TextDir::MongolianVertical => dm_text::TextDir::MongolianVertical, + cd_text::TextDir::StackedRtl => dm_text::TextDir::StackedRtl, + } +} + +fn text_overflow_to(o: dm_text::TextOverflow) -> cd_text::TextOverflow { + match o { + dm_text::TextOverflow::Overflow => cd_text::TextOverflow::Overflow, + dm_text::TextOverflow::Clip => cd_text::TextOverflow::Clip, + dm_text::TextOverflow::Ellipsis => cd_text::TextOverflow::Ellipsis, + } +} + +fn text_overflow_from(o: cd_text::TextOverflow) -> dm_text::TextOverflow { + match o { + cd_text::TextOverflow::Overflow => dm_text::TextOverflow::Overflow, + cd_text::TextOverflow::Clip => dm_text::TextOverflow::Clip, + cd_text::TextOverflow::Ellipsis => dm_text::TextOverflow::Ellipsis, + } +} + +fn body_props_to(b: &dm_text::BodyProps) -> cd_text::BodyProps { + cd_text::BodyProps { + inset_l: b.inset_l, + inset_t: b.inset_t, + inset_r: b.inset_r, + inset_b: b.inset_b, + anchor: b.anchor.map(anchor_to), + anchor_ctr: b.anchor_ctr, + wrap: b.wrap, + autofit: b.autofit.map(|a| match a { + dm_text::AutoFit::None => cd_text::AutoFit::None, + dm_text::AutoFit::Shrink { font_scale, line_reduction } => cd_text::AutoFit::Shrink { font_scale, line_reduction }, + dm_text::AutoFit::Shape => cd_text::AutoFit::Shape, + }), + vert: b.vert.map(text_dir_to), + rot: b.rot, + columns: b.columns, + col_spacing: b.col_spacing, + warp: b.warp.clone(), + warp_adj: b.warp_adj.clone(), + rtl_col: b.rtl_col, + upright: b.upright, + space_first_last: b.space_first_last, + compat_ln_spc: b.compat_ln_spc, + vert_overflow: b.vert_overflow.map(text_overflow_to), + horz_overflow: b.horz_overflow.map(text_overflow_to), + raw3d: b.raw3d.clone(), + } +} + +fn body_props_from(b: cd_text::BodyProps) -> dm_text::BodyProps { + dm_text::BodyProps { + inset_l: b.inset_l, + inset_t: b.inset_t, + inset_r: b.inset_r, + inset_b: b.inset_b, + anchor: b.anchor.map(anchor_from), + anchor_ctr: b.anchor_ctr, + wrap: b.wrap, + autofit: b.autofit.map(|a| match a { + cd_text::AutoFit::None => dm_text::AutoFit::None, + cd_text::AutoFit::Shrink { font_scale, line_reduction } => dm_text::AutoFit::Shrink { font_scale, line_reduction }, + cd_text::AutoFit::Shape => dm_text::AutoFit::Shape, + }), + vert: b.vert.map(text_dir_from), + rot: b.rot, + columns: b.columns, + col_spacing: b.col_spacing, + warp: b.warp, + warp_adj: b.warp_adj, + rtl_col: b.rtl_col, + upright: b.upright, + space_first_last: b.space_first_last, + compat_ln_spc: b.compat_ln_spc, + vert_overflow: b.vert_overflow.map(text_overflow_from), + horz_overflow: b.horz_overflow.map(text_overflow_from), + raw3d: b.raw3d, + } +} + +fn align_to(a: dm_text::Align) -> cd_text::Align { + match a { + dm_text::Align::Left => cd_text::Align::Left, + dm_text::Align::Center => cd_text::Align::Center, + dm_text::Align::Right => cd_text::Align::Right, + dm_text::Align::Justify => cd_text::Align::Justify, + dm_text::Align::JustLow => cd_text::Align::JustLow, + dm_text::Align::Distributed => cd_text::Align::Distributed, + dm_text::Align::ThaiDistributed => cd_text::Align::ThaiDistributed, + } +} + +fn align_from(a: cd_text::Align) -> dm_text::Align { + match a { + cd_text::Align::Left => dm_text::Align::Left, + cd_text::Align::Center => dm_text::Align::Center, + cd_text::Align::Right => dm_text::Align::Right, + cd_text::Align::Justify => dm_text::Align::Justify, + cd_text::Align::JustLow => dm_text::Align::JustLow, + cd_text::Align::Distributed => dm_text::Align::Distributed, + cd_text::Align::ThaiDistributed => dm_text::Align::ThaiDistributed, + } +} + +fn spacing_to(s: dm_text::Spacing) -> cd_text::Spacing { + match s { + dm_text::Spacing::Pct(v) => cd_text::Spacing::Pct(v), + dm_text::Spacing::Pts(v) => cd_text::Spacing::Pts(v), + } +} + +fn spacing_from(s: cd_text::Spacing) -> dm_text::Spacing { + match s { + cd_text::Spacing::Pct(v) => dm_text::Spacing::Pct(v), + cd_text::Spacing::Pts(v) => dm_text::Spacing::Pts(v), + } +} + +fn bullet_to(b: &dm_text::Bullet) -> cd_text::Bullet { + match b { + dm_text::Bullet::None => cd_text::Bullet::None, + dm_text::Bullet::Char { char } => cd_text::Bullet::Char { char: char.clone() }, + dm_text::Bullet::AutoNum { scheme, start_at } => cd_text::Bullet::AutoNum { scheme: scheme.clone(), start_at: *start_at }, + dm_text::Bullet::Picture { media } => cd_text::Bullet::Picture { media: media_id_to(*media) }, + } +} + +fn bullet_from(b: cd_text::Bullet) -> dm_text::Bullet { + match b { + cd_text::Bullet::None => dm_text::Bullet::None, + cd_text::Bullet::Char { char } => dm_text::Bullet::Char { char }, + cd_text::Bullet::AutoNum { scheme, start_at } => dm_text::Bullet::AutoNum { scheme, start_at }, + cd_text::Bullet::Picture { media } => dm_text::Bullet::Picture { media: media_id_from(media) }, + } +} + +fn para_props_to(p: &dm_text::ParaProps) -> cd_text::ParaProps { + cd_text::ParaProps { + align: p.align.map(align_to), + margin_left: p.margin_left, + margin_right: p.margin_right, + indent: p.indent, + line_spacing: p.line_spacing.map(spacing_to), + space_before: p.space_before.map(spacing_to), + space_after: p.space_after.map(spacing_to), + bullet: p.bullet.as_ref().map(bullet_to), + bullet_font: p.bullet_font.clone(), + bullet_font_follow_text: p.bullet_font_follow_text, + bullet_color: p.bullet_color.as_ref().map(color_ref_to), + bullet_color_follow_text: p.bullet_color_follow_text, + bullet_size: p.bullet_size, + bullet_size_points: p.bullet_size_points, + bullet_size_follow_text: p.bullet_size_follow_text, + tabs: p.tabs.as_ref().map(|ts| ts.iter().map(|t| cd_text::TabStop { pos: t.pos, align: t.align.clone() }).collect()), + default_tab: p.default_tab, + rtl: p.rtl, + font_align: p.font_align.clone(), + east_asian_line_break: p.east_asian_line_break, + latin_line_break: p.latin_line_break, + hanging_punct: p.hanging_punct, + } +} + +fn para_props_from(p: cd_text::ParaProps) -> dm_text::ParaProps { + dm_text::ParaProps { + align: p.align.map(align_from), + margin_left: p.margin_left, + margin_right: p.margin_right, + indent: p.indent, + line_spacing: p.line_spacing.map(spacing_from), + space_before: p.space_before.map(spacing_from), + space_after: p.space_after.map(spacing_from), + bullet: p.bullet.map(bullet_from), + bullet_font: p.bullet_font, + bullet_font_follow_text: p.bullet_font_follow_text, + bullet_color: p.bullet_color.map(color_ref_from), + bullet_color_follow_text: p.bullet_color_follow_text, + bullet_size: p.bullet_size, + bullet_size_points: p.bullet_size_points, + bullet_size_follow_text: p.bullet_size_follow_text, + tabs: p.tabs.map(|ts| ts.into_iter().map(|t| dm_text::TabStop { pos: t.pos, align: t.align }).collect()), + default_tab: p.default_tab, + rtl: p.rtl, + font_align: p.font_align, + east_asian_line_break: p.east_asian_line_break, + latin_line_break: p.latin_line_break, + hanging_punct: p.hanging_punct, + } +} + +fn action_to(a: &dm_text::Action) -> cd_text::Action { + match a { + dm_text::Action::Url { url } => cd_text::Action::Url { url: url.clone() }, + dm_text::Action::Slide { slide } => cd_text::Action::Slide { slide: slide_id_to(*slide) }, + dm_text::Action::NextSlide => cd_text::Action::NextSlide, + dm_text::Action::PreviousSlide => cd_text::Action::PreviousSlide, + dm_text::Action::FirstSlide => cd_text::Action::FirstSlide, + dm_text::Action::LastSlide => cd_text::Action::LastSlide, + dm_text::Action::EndShow => cd_text::Action::EndShow, + dm_text::Action::LastViewed => cd_text::Action::LastViewed, + dm_text::Action::CustomShow { name, returns } => cd_text::Action::CustomShow { name: name.clone(), returns: *returns }, + dm_text::Action::Program { path } => cd_text::Action::Program { path: path.clone() }, + dm_text::Action::PlayMedia => cd_text::Action::PlayMedia, + } +} + +fn action_from(a: cd_text::Action) -> dm_text::Action { + match a { + cd_text::Action::Url { url } => dm_text::Action::Url { url }, + cd_text::Action::Slide { slide } => dm_text::Action::Slide { slide: slide_id_from(slide) }, + cd_text::Action::NextSlide => dm_text::Action::NextSlide, + cd_text::Action::PreviousSlide => dm_text::Action::PreviousSlide, + cd_text::Action::FirstSlide => dm_text::Action::FirstSlide, + cd_text::Action::LastSlide => dm_text::Action::LastSlide, + cd_text::Action::EndShow => dm_text::Action::EndShow, + cd_text::Action::LastViewed => dm_text::Action::LastViewed, + cd_text::Action::CustomShow { name, returns } => dm_text::Action::CustomShow { name, returns }, + cd_text::Action::Program { path } => dm_text::Action::Program { path }, + cd_text::Action::PlayMedia => dm_text::Action::PlayMedia, + } +} + +fn hyperlink_to(h: &dm_text::Hyperlink) -> cd_text::Hyperlink { + cd_text::Hyperlink { + action: action_to(&h.action), + tooltip: h.tooltip.clone(), + highlight_click: h.highlight_click, + sound: h.sound.map(media_id_to), + stop_sound: h.stop_sound, + zoom_return: h.zoom_return.map(slide_id_to), + } +} + +fn hyperlink_from(h: cd_text::Hyperlink) -> dm_text::Hyperlink { + dm_text::Hyperlink { + action: action_from(h.action), + tooltip: h.tooltip, + highlight_click: h.highlight_click, + sound: h.sound.map(media_id_from), + stop_sound: h.stop_sound, + zoom_return: h.zoom_return.map(slide_id_from), + } +} + +fn run_props_to(r: &dm_text::RunProps) -> cd_text::RunProps { + cd_text::RunProps { + font: r.font.clone(), + font_ea: r.font_ea.clone(), + font_cs: r.font_cs.clone(), + font_sym: r.font_sym.clone(), + size: r.size, + bold: r.bold, + italic: r.italic, + underline: r.underline.clone(), + underline_color: r.underline_color.as_ref().map(color_ref_to), + strike: r.strike.map(|s| match s { + dm_text::Strike::None => cd_text::Strike::None, + dm_text::Strike::Single => cd_text::Strike::Single, + dm_text::Strike::Double => cd_text::Strike::Double, + }), + baseline: r.baseline, + caps: r.caps.map(|c| match c { + dm_text::Caps::None => cd_text::Caps::None, + dm_text::Caps::Small => cd_text::Caps::Small, + dm_text::Caps::All => cd_text::Caps::All, + }), + spacing: r.spacing, + kern: r.kern, + fill: r.fill.as_ref().map(fill_to), + outline: r.outline.as_ref().map(line_to), + highlight: r.highlight.as_ref().map(color_ref_to), + link: r.link.as_ref().map(hyperlink_to), + hover: r.hover.as_ref().map(hyperlink_to), + lang: r.lang.clone(), + alt_lang: r.alt_lang.clone(), + shadow: r.shadow.as_ref().map(shadow_to), + inner_shadow: r.inner_shadow.as_ref().map(shadow_to), + glow: r.glow.as_ref().map(glow_to), + reflection: r.reflection.as_ref().map(reflection_to), + soft_edge: r.soft_edge, + no_proof: r.no_proof, + normalize_height: r.normalize_height, + } +} + +fn run_props_from(r: cd_text::RunProps) -> dm_text::RunProps { + dm_text::RunProps { + font: r.font, + font_ea: r.font_ea, + font_cs: r.font_cs, + font_sym: r.font_sym, + size: r.size, + bold: r.bold, + italic: r.italic, + underline: r.underline, + underline_color: r.underline_color.map(color_ref_from), + strike: r.strike.map(|s| match s { + cd_text::Strike::None => dm_text::Strike::None, + cd_text::Strike::Single => dm_text::Strike::Single, + cd_text::Strike::Double => dm_text::Strike::Double, + }), + baseline: r.baseline, + caps: r.caps.map(|c| match c { + cd_text::Caps::None => dm_text::Caps::None, + cd_text::Caps::Small => dm_text::Caps::Small, + cd_text::Caps::All => dm_text::Caps::All, + }), + spacing: r.spacing, + kern: r.kern, + fill: r.fill.map(fill_from), + outline: r.outline.map(line_from), + highlight: r.highlight.map(color_ref_from), + link: r.link.map(hyperlink_from), + hover: r.hover.map(hyperlink_from), + lang: r.lang, + alt_lang: r.alt_lang, + shadow: r.shadow.map(shadow_from), + inner_shadow: r.inner_shadow.map(shadow_from), + glow: r.glow.map(glow_from), + reflection: r.reflection.map(reflection_from), + soft_edge: r.soft_edge, + no_proof: r.no_proof, + normalize_height: r.normalize_height, + } +} + +fn run_to(r: &dm_text::Run) -> cd_text::Run { + cd_text::Run { + text: r.text.clone(), + props: run_props_to(&r.props), + kind: match &r.kind { + dm_text::RunKind::Text => cd_text::RunKind::Text, + dm_text::RunKind::Break => cd_text::RunKind::Break, + dm_text::RunKind::Field { field } => cd_text::RunKind::Field { field: field.clone() }, + dm_text::RunKind::Math { omml } => cd_text::RunKind::Math { omml: omml.clone() }, + }, + } +} + +fn run_from(r: cd_text::Run) -> dm_text::Run { + dm_text::Run { + text: r.text, + props: run_props_from(r.props), + kind: match r.kind { + cd_text::RunKind::Text => dm_text::RunKind::Text, + cd_text::RunKind::Break => dm_text::RunKind::Break, + cd_text::RunKind::Field { field } => dm_text::RunKind::Field { field }, + cd_text::RunKind::Math { omml } => dm_text::RunKind::Math { omml }, + }, + } +} + +fn paragraph_to(p: &dm_text::Paragraph) -> cd_text::Paragraph { + cd_text::Paragraph { + level: p.level, + props: para_props_to(&p.props), + runs: p.runs.iter().map(run_to).collect(), + def_props: run_props_to(&p.def_props), + end_props: run_props_to(&p.end_props), + } +} + +fn paragraph_from(p: cd_text::Paragraph) -> dm_text::Paragraph { + dm_text::Paragraph { + level: p.level, + props: para_props_from(p.props), + runs: p.runs.into_iter().map(run_from).collect(), + def_props: run_props_from(p.def_props), + end_props: run_props_from(p.end_props), + } +} + +pub(crate) fn list_style_to_craft(l: &dm_text::ListStyle) -> cd_text::ListStyle { + cd_text::ListStyle { + levels: l + .levels + .iter() + .map(|opt| opt.as_ref().map(|lv| cd_text::LevelStyle { para: para_props_to(&lv.para), run: run_props_to(&lv.run) })) + .collect(), + default_level: None, + } +} + +fn list_style_from(l: cd_text::ListStyle) -> dm_text::ListStyle { + dm_text::ListStyle { + levels: l + .levels + .into_iter() + .map(|opt| opt.map(|lv| dm_text::LevelStyle { para: para_props_from(lv.para), run: run_props_from(lv.run) })) + .collect(), + } +} + +fn text_body_to(t: &dm_text::TextBody) -> cd_text::TextBody { + cd_text::TextBody { + body: body_props_to(&t.body), + list_style: list_style_to_craft(&t.list_style), + paragraphs: t.paragraphs.iter().map(paragraph_to).collect(), + } +} + +fn text_body_from(t: cd_text::TextBody) -> dm_text::TextBody { + dm_text::TextBody { + body: body_props_from(t.body), + list_style: list_style_from(t.list_style), + paragraphs: t.paragraphs.into_iter().map(paragraph_from).collect(), + } +} + +// --------------------------------------------------------------------------- +// Table +// --------------------------------------------------------------------------- + +fn cell_to(c: &dm_table::Cell) -> cd_table::Cell { + cd_table::Cell { + text: text_body_to(&c.text), + fill: c.fill.as_ref().map(fill_to), + borders: [ + c.borders[0].as_ref().map(line_to), + c.borders[1].as_ref().map(line_to), + c.borders[2].as_ref().map(line_to), + c.borders[3].as_ref().map(line_to), + ], + diag_down: c.diag_down.as_ref().map(line_to), + diag_up: c.diag_up.as_ref().map(line_to), + margins: c.margins, + anchor: c.anchor.map(anchor_to), + grid_span: c.grid_span, + row_span: c.row_span, + h_merge: c.h_merge, + v_merge: c.v_merge, + vertical: c.vertical.map(text_dir_to), + anchor_ctr: c.anchor_ctr, + horz_overflow: c.horz_overflow.map(text_overflow_to), + } +} + +fn cell_from(c: cd_table::Cell) -> dm_table::Cell { + let [b0, b1, b2, b3] = c.borders; + dm_table::Cell { + text: text_body_from(c.text), + fill: c.fill.map(fill_from), + borders: [b0.map(line_from), b1.map(line_from), b2.map(line_from), b3.map(line_from)], + diag_down: c.diag_down.map(line_from), + diag_up: c.diag_up.map(line_from), + margins: c.margins, + anchor: c.anchor.map(anchor_from), + grid_span: c.grid_span, + row_span: c.row_span, + h_merge: c.h_merge, + v_merge: c.v_merge, + vertical: c.vertical.map(text_dir_from), + anchor_ctr: c.anchor_ctr, + horz_overflow: c.horz_overflow.map(text_overflow_from), + } +} + +fn table_to(t: &dm_table::Table) -> cd_table::Table { + cd_table::Table { + cols: t.cols.clone(), + rows: t.rows.iter().map(|r| cd_table::Row { height: r.height, cells: r.cells.iter().map(cell_to).collect() }).collect(), + style: t.style.clone(), + first_row: t.first_row, + last_row: t.last_row, + first_col: t.first_col, + last_col: t.last_col, + band_row: t.band_row, + band_col: t.band_col, + rtl: t.rtl, + background: t.background.as_ref().map(fill_to), + } +} + +fn table_from(t: cd_table::Table) -> dm_table::Table { + dm_table::Table { + cols: t.cols, + rows: t.rows.into_iter().map(|r| dm_table::Row { height: r.height, cells: r.cells.into_iter().map(cell_from).collect() }).collect(), + style: t.style, + first_row: t.first_row, + last_row: t.last_row, + first_col: t.first_col, + last_col: t.last_col, + band_row: t.band_row, + band_col: t.band_col, + rtl: t.rtl, + background: t.background.map(fill_from), + } +} + +fn table_border_to(b: &dm_table::TableBorder) -> cd_table::TableBorder { + match b { + dm_table::TableBorder::Line { line } => cd_table::TableBorder::Line { line: line_to(line) }, + dm_table::TableBorder::Ref { idx, color } => cd_table::TableBorder::Ref { idx: *idx, color: color_ref_to(color) }, + } +} + +fn table_border_from(b: cd_table::TableBorder) -> dm_table::TableBorder { + match b { + cd_table::TableBorder::Line { line } => dm_table::TableBorder::Line { line: line_from(line) }, + cd_table::TableBorder::Ref { idx, color } => dm_table::TableBorder::Ref { idx, color: color_ref_from(color) }, + } +} + +fn table_part_style_to(p: &dm_table::TablePartStyle) -> cd_table::TablePartStyle { + cd_table::TablePartStyle { + fill: p.fill.as_ref().map(fill_to), + fill_ref: p.fill_ref.as_ref().map(|(idx, c)| (*idx, color_ref_to(c))), + borders: [ + p.borders[0].as_ref().map(table_border_to), + p.borders[1].as_ref().map(table_border_to), + p.borders[2].as_ref().map(table_border_to), + p.borders[3].as_ref().map(table_border_to), + p.borders[4].as_ref().map(table_border_to), + p.borders[5].as_ref().map(table_border_to), + ], + text_color: p.text_color.as_ref().map(color_ref_to), + bold: p.bold, + italic: p.italic, + } +} + +fn table_part_style_from(p: cd_table::TablePartStyle) -> dm_table::TablePartStyle { + let [b0, b1, b2, b3, b4, b5] = p.borders; + dm_table::TablePartStyle { + fill: p.fill.map(fill_from), + fill_ref: p.fill_ref.map(|(idx, c)| (idx, color_ref_from(c))), + borders: [ + b0.map(table_border_from), + b1.map(table_border_from), + b2.map(table_border_from), + b3.map(table_border_from), + b4.map(table_border_from), + b5.map(table_border_from), + ], + text_color: p.text_color.map(color_ref_from), + bold: p.bold, + italic: p.italic, + } +} + +fn table_part_to(p: &dm_table::TablePart) -> cd_table::TablePart { + match p { + dm_table::TablePart::WholeTbl => cd_table::TablePart::WholeTbl, + dm_table::TablePart::Band1H => cd_table::TablePart::Band1H, + dm_table::TablePart::Band2H => cd_table::TablePart::Band2H, + dm_table::TablePart::Band1V => cd_table::TablePart::Band1V, + dm_table::TablePart::Band2V => cd_table::TablePart::Band2V, + dm_table::TablePart::FirstRow => cd_table::TablePart::FirstRow, + dm_table::TablePart::LastRow => cd_table::TablePart::LastRow, + dm_table::TablePart::FirstCol => cd_table::TablePart::FirstCol, + dm_table::TablePart::LastCol => cd_table::TablePart::LastCol, + dm_table::TablePart::NwCell => cd_table::TablePart::NwCell, + dm_table::TablePart::NeCell => cd_table::TablePart::NeCell, + dm_table::TablePart::SwCell => cd_table::TablePart::SwCell, + dm_table::TablePart::SeCell => cd_table::TablePart::SeCell, + } +} + +fn table_part_from(p: cd_table::TablePart) -> dm_table::TablePart { + match p { + cd_table::TablePart::WholeTbl => dm_table::TablePart::WholeTbl, + cd_table::TablePart::Band1H => dm_table::TablePart::Band1H, + cd_table::TablePart::Band2H => dm_table::TablePart::Band2H, + cd_table::TablePart::Band1V => dm_table::TablePart::Band1V, + cd_table::TablePart::Band2V => dm_table::TablePart::Band2V, + cd_table::TablePart::FirstRow => dm_table::TablePart::FirstRow, + cd_table::TablePart::LastRow => dm_table::TablePart::LastRow, + cd_table::TablePart::FirstCol => dm_table::TablePart::FirstCol, + cd_table::TablePart::LastCol => dm_table::TablePart::LastCol, + cd_table::TablePart::NwCell => dm_table::TablePart::NwCell, + cd_table::TablePart::NeCell => dm_table::TablePart::NeCell, + cd_table::TablePart::SwCell => dm_table::TablePart::SwCell, + cd_table::TablePart::SeCell => dm_table::TablePart::SeCell, + } +} + +fn table_style_def_to(d: &dm_table::TableStyleDef) -> cd_table::TableStyleDef { + cd_table::TableStyleDef { + id: d.id.clone(), + name: d.name.clone(), + background: d.background.as_ref().map(table_part_style_to), + parts: d.parts.iter().map(|(k, v)| (table_part_to(k), table_part_style_to(v))).collect(), + raw: d.raw.clone(), + } +} + +fn table_style_def_from(d: cd_table::TableStyleDef) -> dm_table::TableStyleDef { + dm_table::TableStyleDef { + id: d.id, + name: d.name, + background: d.background.map(table_part_style_from), + parts: d.parts.into_iter().map(|(k, v)| (table_part_from(k), table_part_style_from(v))).collect(), + raw: d.raw, + } +} + +// --------------------------------------------------------------------------- +// Chart +// --------------------------------------------------------------------------- + +fn chart_type_to(k: dm_chart::ChartType) -> cd_chart::ChartType { + match k { + dm_chart::ChartType::Column => cd_chart::ChartType::Column, + dm_chart::ChartType::StackedColumn => cd_chart::ChartType::StackedColumn, + dm_chart::ChartType::PercentColumn => cd_chart::ChartType::PercentColumn, + dm_chart::ChartType::Bar => cd_chart::ChartType::Bar, + dm_chart::ChartType::StackedBar => cd_chart::ChartType::StackedBar, + dm_chart::ChartType::PercentBar => cd_chart::ChartType::PercentBar, + dm_chart::ChartType::Line => cd_chart::ChartType::Line, + dm_chart::ChartType::LineMarkers => cd_chart::ChartType::LineMarkers, + dm_chart::ChartType::StackedLine => cd_chart::ChartType::StackedLine, + dm_chart::ChartType::Area => cd_chart::ChartType::Area, + dm_chart::ChartType::StackedArea => cd_chart::ChartType::StackedArea, + dm_chart::ChartType::Pie => cd_chart::ChartType::Pie, + dm_chart::ChartType::Doughnut => cd_chart::ChartType::Doughnut, + dm_chart::ChartType::Scatter => cd_chart::ChartType::Scatter, + dm_chart::ChartType::Bubble => cd_chart::ChartType::Bubble, + dm_chart::ChartType::Radar => cd_chart::ChartType::Radar, + dm_chart::ChartType::FilledRadar => cd_chart::ChartType::FilledRadar, + dm_chart::ChartType::Stock => cd_chart::ChartType::Stock, + dm_chart::ChartType::Surface => cd_chart::ChartType::Surface, + dm_chart::ChartType::Histogram => cd_chart::ChartType::Histogram, + dm_chart::ChartType::Pareto => cd_chart::ChartType::Pareto, + dm_chart::ChartType::BoxWhisker => cd_chart::ChartType::BoxWhisker, + dm_chart::ChartType::Waterfall => cd_chart::ChartType::Waterfall, + dm_chart::ChartType::Funnel => cd_chart::ChartType::Funnel, + dm_chart::ChartType::Treemap => cd_chart::ChartType::Treemap, + dm_chart::ChartType::Sunburst => cd_chart::ChartType::Sunburst, + dm_chart::ChartType::RegionMap => cd_chart::ChartType::RegionMap, + dm_chart::ChartType::Combo => cd_chart::ChartType::Combo, + } +} + +fn chart_type_from(k: cd_chart::ChartType) -> dm_chart::ChartType { + match k { + cd_chart::ChartType::Column => dm_chart::ChartType::Column, + cd_chart::ChartType::StackedColumn => dm_chart::ChartType::StackedColumn, + cd_chart::ChartType::PercentColumn => dm_chart::ChartType::PercentColumn, + cd_chart::ChartType::Bar => dm_chart::ChartType::Bar, + cd_chart::ChartType::StackedBar => dm_chart::ChartType::StackedBar, + cd_chart::ChartType::PercentBar => dm_chart::ChartType::PercentBar, + cd_chart::ChartType::Line => dm_chart::ChartType::Line, + cd_chart::ChartType::LineMarkers => dm_chart::ChartType::LineMarkers, + cd_chart::ChartType::StackedLine => dm_chart::ChartType::StackedLine, + cd_chart::ChartType::Area => dm_chart::ChartType::Area, + cd_chart::ChartType::StackedArea => dm_chart::ChartType::StackedArea, + cd_chart::ChartType::Pie => dm_chart::ChartType::Pie, + cd_chart::ChartType::Doughnut => dm_chart::ChartType::Doughnut, + cd_chart::ChartType::Scatter => dm_chart::ChartType::Scatter, + cd_chart::ChartType::Bubble => dm_chart::ChartType::Bubble, + cd_chart::ChartType::Radar => dm_chart::ChartType::Radar, + cd_chart::ChartType::FilledRadar => dm_chart::ChartType::FilledRadar, + cd_chart::ChartType::Stock => dm_chart::ChartType::Stock, + cd_chart::ChartType::Surface => dm_chart::ChartType::Surface, + cd_chart::ChartType::Histogram => dm_chart::ChartType::Histogram, + cd_chart::ChartType::Pareto => dm_chart::ChartType::Pareto, + cd_chart::ChartType::BoxWhisker => dm_chart::ChartType::BoxWhisker, + cd_chart::ChartType::Waterfall => dm_chart::ChartType::Waterfall, + cd_chart::ChartType::Funnel => dm_chart::ChartType::Funnel, + cd_chart::ChartType::Treemap => dm_chart::ChartType::Treemap, + cd_chart::ChartType::Sunburst => dm_chart::ChartType::Sunburst, + cd_chart::ChartType::RegionMap => dm_chart::ChartType::RegionMap, + cd_chart::ChartType::Combo => dm_chart::ChartType::Combo, + } +} + +fn trendline_type_to(t: dm_chart::TrendlineType) -> cd_chart::TrendlineType { + match t { + dm_chart::TrendlineType::Exp => cd_chart::TrendlineType::Exp, + dm_chart::TrendlineType::Linear => cd_chart::TrendlineType::Linear, + dm_chart::TrendlineType::Log => cd_chart::TrendlineType::Log, + dm_chart::TrendlineType::MovingAvg => cd_chart::TrendlineType::MovingAvg, + dm_chart::TrendlineType::Poly => cd_chart::TrendlineType::Poly, + dm_chart::TrendlineType::Power => cd_chart::TrendlineType::Power, + } +} + +fn trendline_type_from(t: cd_chart::TrendlineType) -> dm_chart::TrendlineType { + match t { + cd_chart::TrendlineType::Exp => dm_chart::TrendlineType::Exp, + cd_chart::TrendlineType::Linear => dm_chart::TrendlineType::Linear, + cd_chart::TrendlineType::Log => dm_chart::TrendlineType::Log, + cd_chart::TrendlineType::MovingAvg => dm_chart::TrendlineType::MovingAvg, + cd_chart::TrendlineType::Poly => dm_chart::TrendlineType::Poly, + cd_chart::TrendlineType::Power => dm_chart::TrendlineType::Power, + } +} + +fn series_to(s: &dm_chart::Series) -> cd_chart::Series { + cd_chart::Series { + name: s.name.clone(), + values: s.values.clone(), + x_values: s.x_values.clone(), + sizes: s.sizes.clone(), + fill: s.fill.as_ref().map(fill_to), + line: s.line.as_ref().map(line_to), + point_fills: s.point_fills.iter().map(|(i, f)| (*i, fill_to(f))).collect(), + data_labels: s.data_labels, + smooth: s.smooth, + marker: s.marker.clone(), + kind: s.kind.map(chart_type_to), + secondary_axis: s.secondary_axis, + number_format: s.number_format.clone(), + trendlines: s + .trendlines + .iter() + .map(|t| cd_chart::Trendline { + kind: trendline_type_to(t.kind), + name: t.name.clone(), + order: t.order, + period: t.period, + forward: t.forward, + backward: t.backward, + intercept: t.intercept, + disp_eq: t.disp_eq, + disp_r_sqr: t.disp_r_sqr, + }) + .collect(), + error_bars: s.error_bars.as_ref().map(|e| cd_chart::ErrorBars { + bar_type: e.bar_type.clone(), + val_type: e.val_type.clone(), + value: e.value, + plus: e.plus.clone(), + minus: e.minus.clone(), + end_cap: e.end_cap, + }), + refs: cd_chart::SeriesRefs::default(), + } +} + +fn series_from(s: cd_chart::Series) -> dm_chart::Series { + dm_chart::Series { + name: s.name, + values: s.values, + x_values: s.x_values, + sizes: s.sizes, + fill: s.fill.map(fill_from), + line: s.line.map(line_from), + point_fills: s.point_fills.into_iter().map(|(i, f)| (i, fill_from(f))).collect(), + data_labels: s.data_labels, + smooth: s.smooth, + marker: s.marker, + kind: s.kind.map(chart_type_from), + secondary_axis: s.secondary_axis, + number_format: s.number_format, + trendlines: s + .trendlines + .into_iter() + .map(|t| dm_chart::Trendline { + kind: trendline_type_from(t.kind), + name: t.name, + order: t.order, + period: t.period, + forward: t.forward, + backward: t.backward, + intercept: t.intercept, + disp_eq: t.disp_eq, + disp_r_sqr: t.disp_r_sqr, + }) + .collect(), + error_bars: s.error_bars.map(|e| dm_chart::ErrorBars { + bar_type: e.bar_type, + val_type: e.val_type, + value: e.value, + plus: e.plus, + minus: e.minus, + end_cap: e.end_cap, + }), + } +} + +fn chart_kept_to(k: &dm_chart::ChartKept) -> cd_chart::ChartKept { + cd_chart::ChartKept { + rels: k + .rels + .iter() + .map(|r| cd_chart::ChartRel { + id: r.id.clone(), + rel_type: r.rel_type.clone(), + target: r.target.clone(), + part: r.part.clone(), + external: r.external, + }) + .collect(), + parts: k + .parts + .iter() + .map(|p| cd_chart::ChartPart { + name: p.name.clone(), + content_type: p.content_type.clone(), + bytes: p.bytes.clone(), + native_entry: p.native_entry.clone(), + }) + .collect(), + } +} + +fn chart_kept_from(k: cd_chart::ChartKept) -> dm_chart::ChartKept { + dm_chart::ChartKept { + rels: k + .rels + .into_iter() + .map(|r| dm_chart::ChartRel { id: r.id, rel_type: r.rel_type, target: r.target, part: r.part, external: r.external }) + .collect(), + parts: k + .parts + .into_iter() + .map(|p| dm_chart::ChartPart { name: p.name, content_type: p.content_type, bytes: p.bytes, native_entry: p.native_entry }) + .collect(), + } +} + +fn chart_to(c: &dm_chart::Chart) -> cd_chart::Chart { + let mut out = cd_chart::Chart { + kind: chart_type_to(c.kind), + title: c.title.clone(), + categories: c.categories.clone(), + series: c.series.iter().map(series_to).collect(), + legend: c.legend.clone(), + legend_overlay: c.legend_overlay, + legend_entries: c + .legend_entries + .iter() + .map(|e| cd_chart::LegendEntry { idx: e.idx, size: e.size, bold: e.bold, color: e.color.as_ref().map(color_ref_to) }) + .collect(), + text_size: c.text_size, + title_size: c.title_size, + data_labels: c.data_labels, + gridlines: c.gridlines, + minor_gridlines: c.minor_gridlines, + axis_titles: c.axis_titles.clone(), + style: c.style, + palette: c.palette.clone(), + plot_fill: c.plot_fill.as_ref().map(fill_to), + chart_fill: c.chart_fill.as_ref().map(fill_to), + text_color: c.text_color.as_ref().map(color_ref_to), + hole_size: c.hole_size, + gap_width: c.gap_width, + overlap: c.overlap, + vary_colors: c.vary_colors, + y_min: c.y_min, + y_max: c.y_max, + y_major: c.y_major, + y_log_base: c.y_log_base, + y_format: c.y_format.clone(), + y_hidden: c.y_hidden, + cat_reversed: c.cat_reversed, + y2_min: c.y2_min, + y2_max: c.y2_max, + y2_major: c.y2_major, + y2_format: c.y2_format.clone(), + y2_hidden: c.y2_hidden, + lang: c.lang.clone(), + subtotals: c.subtotals.clone(), + category_levels: c.category_levels.clone(), + inclusive_quartiles: c.inclusive_quartiles, + up_down_bars: c.up_down_bars, + bin_count: c.bin_count, + bin_size: c.bin_size, + data_table: None, + first_slice_angle: 0, + pivot_source: None, + raw: c.raw.clone(), + verbatim: c.verbatim, + kept: chart_kept_to(&c.kept), + }; + if !c.verbatim + && let Some(raw) = &c.raw + && let Some(parsed) = cd_chart::read::read_chart_xml(raw.as_bytes()).or_else(|| cd_chart::chartex::read_chartex_xml(raw.as_bytes())) + { + out.data_table = parsed.data_table; + out.first_slice_angle = parsed.first_slice_angle; + out.pivot_source = parsed.pivot_source; + for (dst, src) in out.series.iter_mut().zip(parsed.series) { + dst.refs = src.refs; + } + } + out +} + +fn apply_series_dlbls_delete(raw: &str, series: &mut [dm_chart::Series]) { + let Ok(root) = craft_drawingml::xmlx::parse(raw.as_bytes()) else { + return; + }; + let Some(pa) = root.path(&[craft_xml::Local("chart"), craft_xml::Local("plotArea")]) else { + return; + }; + let sers = pa.elements().flat_map(|g| g.children(craft_xml::Local("ser"))); + for (ser_el, dst) in sers.zip(series) { + let deleted = ser_el + .path(&[craft_xml::Local("dLbls"), craft_xml::Local("delete")]) + .map(|v| v.attr_local("val").and_then(craft_xml::value::to_bool).unwrap_or(true)); + if deleted == Some(true) { + dst.data_labels = Some(false); + } + } +} + +fn chart_from(c: cd_chart::Chart) -> dm_chart::Chart { + let mut out = dm_chart::Chart { + kind: chart_type_from(c.kind), + title: c.title, + categories: c.categories, + series: c.series.into_iter().map(series_from).collect(), + legend: c.legend, + legend_overlay: c.legend_overlay, + legend_entries: c + .legend_entries + .into_iter() + .map(|e| dm_chart::LegendEntry { idx: e.idx, size: e.size, bold: e.bold, color: e.color.map(color_ref_from) }) + .collect(), + text_size: c.text_size, + title_size: c.title_size, + data_labels: c.data_labels, + gridlines: c.gridlines, + minor_gridlines: c.minor_gridlines, + axis_titles: c.axis_titles, + style: c.style, + palette: c.palette, + plot_fill: c.plot_fill.map(fill_from), + chart_fill: c.chart_fill.map(fill_from), + text_color: c.text_color.map(color_ref_from), + hole_size: c.hole_size, + gap_width: c.gap_width, + overlap: c.overlap, + vary_colors: c.vary_colors, + y_min: c.y_min, + y_max: c.y_max, + y_major: c.y_major, + y_log_base: c.y_log_base, + y_format: c.y_format, + y_hidden: c.y_hidden, + cat_reversed: c.cat_reversed, + y2_min: c.y2_min, + y2_max: c.y2_max, + y2_major: c.y2_major, + y2_format: c.y2_format, + y2_hidden: c.y2_hidden, + lang: c.lang, + subtotals: c.subtotals, + category_levels: c.category_levels, + inclusive_quartiles: c.inclusive_quartiles, + up_down_bars: c.up_down_bars, + bin_count: c.bin_count, + bin_size: c.bin_size, + raw: c.raw, + verbatim: c.verbatim, + kept: chart_kept_from(c.kept), + }; + if let Some(raw) = &out.raw { + apply_series_dlbls_delete(raw, &mut out.series); + } + out +} + +// --------------------------------------------------------------------------- +// Theme +// --------------------------------------------------------------------------- + +fn font_set_to(f: &dm_theme::FontSet) -> cd_theme::FontSet { + cd_theme::FontSet { + latin: f.latin.clone(), + ea: f.ea.clone(), + cs: f.cs.clone(), + latin_attrs: cd_theme::TypefaceAttrs::default(), + ea_attrs: cd_theme::TypefaceAttrs::default(), + cs_attrs: cd_theme::TypefaceAttrs::default(), + scripts: f.scripts.iter().map(|s| cd_theme::ScriptFont { script: s.script.clone(), typeface: s.typeface.clone() }).collect(), + } +} + +fn font_set_from(f: cd_theme::FontSet) -> dm_theme::FontSet { + dm_theme::FontSet { + latin: f.latin, + ea: f.ea, + cs: f.cs, + scripts: f.scripts.into_iter().map(|s| dm_theme::ScriptFont { script: s.script, typeface: s.typeface }).collect(), + } +} + +pub(crate) fn theme_to_craft(t: &dm_theme::Theme) -> cd_theme::Theme { + cd_theme::Theme { + name: t.name.clone(), + colors: t.colors.clone(), + fonts: cd_theme::FontScheme { name: t.fonts.name.clone(), major: font_set_to(&t.fonts.major), minor: font_set_to(&t.fonts.minor) }, + format: cd_theme::FormatScheme { + name: t.format.name.clone(), + fills: t.format.fills.iter().map(fill_to).collect(), + lines: t.format.lines.iter().map(line_to).collect(), + effects: t.format.effects.iter().map(effects_to).collect(), + bg_fills: t.format.bg_fills.iter().map(fill_to).collect(), + }, + sys_colors: vec![], + raw_extra: t.raw_extra.clone(), + } +} + +pub(crate) fn theme_from_craft(t: cd_theme::Theme) -> dm_theme::Theme { + dm_theme::Theme { + name: t.name, + colors: t.colors, + fonts: dm_theme::FontScheme { name: t.fonts.name, major: font_set_from(t.fonts.major), minor: font_set_from(t.fonts.minor) }, + format: dm_theme::FormatScheme { + name: t.format.name, + fills: t.format.fills.into_iter().map(fill_from).collect(), + lines: t.format.lines.into_iter().map(line_from).collect(), + effects: t.format.effects.into_iter().map(effects_from).collect(), + bg_fills: t.format.bg_fills.into_iter().map(fill_from).collect(), + }, + raw_extra: t.raw_extra, + } +} + +// --------------------------------------------------------------------------- +// Animations & Transitions +// --------------------------------------------------------------------------- + +fn transition_to(t: &dm_anim::Transition) -> cp_anim::Transition { + cp_anim::Transition { + kind: t.kind.clone(), + option: t.option.clone(), + duration_ms: t.duration_ms, + advance_on_click: t.advance_on_click, + advance_after_ms: t.advance_after_ms, + sound: t.sound.map(media_id_to), + sound_loop: t.sound_loop, + stop_sound: t.stop_sound, + raw: t.raw.clone(), + } +} + +fn transition_from(t: cp_anim::Transition) -> dm_anim::Transition { + dm_anim::Transition { + kind: t.kind, + option: t.option, + duration_ms: t.duration_ms, + advance_on_click: t.advance_on_click, + advance_after_ms: t.advance_after_ms, + sound: t.sound.map(media_id_from), + sound_loop: t.sound_loop, + stop_sound: t.stop_sound, + raw: t.raw, + } +} + +fn anim_class_to(c: dm_anim::AnimClass) -> cp_anim::AnimClass { + match c { + dm_anim::AnimClass::Entrance => cp_anim::AnimClass::Entrance, + dm_anim::AnimClass::Emphasis => cp_anim::AnimClass::Emphasis, + dm_anim::AnimClass::Exit => cp_anim::AnimClass::Exit, + dm_anim::AnimClass::Path => cp_anim::AnimClass::Path, + dm_anim::AnimClass::Media => cp_anim::AnimClass::Media, + } +} + +fn anim_class_from(c: cp_anim::AnimClass) -> dm_anim::AnimClass { + match c { + cp_anim::AnimClass::Entrance => dm_anim::AnimClass::Entrance, + cp_anim::AnimClass::Emphasis => dm_anim::AnimClass::Emphasis, + cp_anim::AnimClass::Exit => dm_anim::AnimClass::Exit, + cp_anim::AnimClass::Path => dm_anim::AnimClass::Path, + cp_anim::AnimClass::Media => dm_anim::AnimClass::Media, + } +} + +fn anim_start_to(s: dm_anim::AnimStart) -> cp_anim::AnimStart { + match s { + dm_anim::AnimStart::OnClick => cp_anim::AnimStart::OnClick, + dm_anim::AnimStart::WithPrevious => cp_anim::AnimStart::WithPrevious, + dm_anim::AnimStart::AfterPrevious => cp_anim::AnimStart::AfterPrevious, + } +} + +fn anim_start_from(s: cp_anim::AnimStart) -> dm_anim::AnimStart { + match s { + cp_anim::AnimStart::OnClick => dm_anim::AnimStart::OnClick, + cp_anim::AnimStart::WithPrevious => dm_anim::AnimStart::WithPrevious, + cp_anim::AnimStart::AfterPrevious => dm_anim::AnimStart::AfterPrevious, + } +} + +fn text_build_to(b: dm_anim::TextBuild) -> cp_anim::TextBuild { + match b { + dm_anim::TextBuild::AsOne => cp_anim::TextBuild::AsOne, + dm_anim::TextBuild::ByParagraph => cp_anim::TextBuild::ByParagraph, + dm_anim::TextBuild::ByWord => cp_anim::TextBuild::ByWord, + dm_anim::TextBuild::ByLetter => cp_anim::TextBuild::ByLetter, + } +} + +fn text_build_from(b: cp_anim::TextBuild) -> dm_anim::TextBuild { + match b { + cp_anim::TextBuild::AsOne => dm_anim::TextBuild::AsOne, + cp_anim::TextBuild::ByParagraph => dm_anim::TextBuild::ByParagraph, + cp_anim::TextBuild::ByWord => dm_anim::TextBuild::ByWord, + cp_anim::TextBuild::ByLetter => dm_anim::TextBuild::ByLetter, + } +} + +fn animation_to(a: &dm_anim::Animation) -> cp_anim::Animation { + cp_anim::Animation { + shape: shape_id_to(a.shape), + class: anim_class_to(a.class), + effect: a.effect.clone(), + option: a.option.clone(), + start: anim_start_to(a.start), + duration_ms: a.duration_ms, + delay_ms: a.delay_ms, + repeat: a.repeat, + rewind: a.rewind, + text_build: text_build_to(a.text_build), + paragraph: a.paragraph, + path: a.path.clone(), + trigger: a.trigger.map(shape_id_to), + amount: a.amount, + color: a.color.as_ref().map(color_ref_to), + preset_id: a.preset_id, + preset_subtype: a.preset_subtype, + after: a.after.clone(), + sound: a.sound.map(media_id_to), + smooth_start: a.smooth_start, + smooth_end: a.smooth_end, + bounce_end: a.bounce_end, + auto_reverse: a.auto_reverse, + } +} + +fn animation_from(a: cp_anim::Animation) -> dm_anim::Animation { + dm_anim::Animation { + shape: shape_id_from(a.shape), + class: anim_class_from(a.class), + effect: a.effect, + option: a.option, + start: anim_start_from(a.start), + duration_ms: a.duration_ms, + delay_ms: a.delay_ms, + repeat: a.repeat, + rewind: a.rewind, + text_build: text_build_from(a.text_build), + paragraph: a.paragraph, + path: a.path, + trigger: a.trigger.map(shape_id_from), + amount: a.amount, + color: a.color.map(color_ref_from), + preset_id: a.preset_id, + preset_subtype: a.preset_subtype, + after: a.after, + sound: a.sound.map(media_id_from), + smooth_start: a.smooth_start, + smooth_end: a.smooth_end, + bounce_end: a.bounce_end, + auto_reverse: a.auto_reverse, + } +} + +// --------------------------------------------------------------------------- +// Shapes, Slides, Masters, Presentation +// --------------------------------------------------------------------------- + +fn ph_type_to(p: deckcraft_model::PhType) -> craft_pptx::PhType { + match p { + deckcraft_model::PhType::Title => craft_pptx::PhType::Title, + deckcraft_model::PhType::CtrTitle => craft_pptx::PhType::CtrTitle, + deckcraft_model::PhType::SubTitle => craft_pptx::PhType::SubTitle, + deckcraft_model::PhType::Body => craft_pptx::PhType::Body, + deckcraft_model::PhType::Obj => craft_pptx::PhType::Obj, + deckcraft_model::PhType::Chart => craft_pptx::PhType::Chart, + deckcraft_model::PhType::Table => craft_pptx::PhType::Table, + deckcraft_model::PhType::ClipArt => craft_pptx::PhType::ClipArt, + deckcraft_model::PhType::Diagram => craft_pptx::PhType::Diagram, + deckcraft_model::PhType::Media => craft_pptx::PhType::Media, + deckcraft_model::PhType::Picture => craft_pptx::PhType::Picture, + deckcraft_model::PhType::Date => craft_pptx::PhType::Date, + deckcraft_model::PhType::Footer => craft_pptx::PhType::Footer, + deckcraft_model::PhType::SlideNum => craft_pptx::PhType::SlideNum, + deckcraft_model::PhType::Header => craft_pptx::PhType::Header, + deckcraft_model::PhType::SlideImage => craft_pptx::PhType::SlideImage, + } +} + +fn ph_type_from(p: craft_pptx::PhType) -> deckcraft_model::PhType { + match p { + craft_pptx::PhType::Title => deckcraft_model::PhType::Title, + craft_pptx::PhType::CtrTitle => deckcraft_model::PhType::CtrTitle, + craft_pptx::PhType::SubTitle => deckcraft_model::PhType::SubTitle, + craft_pptx::PhType::Body => deckcraft_model::PhType::Body, + craft_pptx::PhType::Obj => deckcraft_model::PhType::Obj, + craft_pptx::PhType::Chart => deckcraft_model::PhType::Chart, + craft_pptx::PhType::Table => deckcraft_model::PhType::Table, + craft_pptx::PhType::ClipArt => deckcraft_model::PhType::ClipArt, + craft_pptx::PhType::Diagram => deckcraft_model::PhType::Diagram, + craft_pptx::PhType::Media => deckcraft_model::PhType::Media, + craft_pptx::PhType::Picture => deckcraft_model::PhType::Picture, + craft_pptx::PhType::Date => deckcraft_model::PhType::Date, + craft_pptx::PhType::Footer => deckcraft_model::PhType::Footer, + craft_pptx::PhType::SlideNum => deckcraft_model::PhType::SlideNum, + craft_pptx::PhType::Header => deckcraft_model::PhType::Header, + craft_pptx::PhType::SlideImage => deckcraft_model::PhType::SlideImage, + } +} + +fn geom_to(g: &deckcraft_model::Geom) -> craft_pptx::Geom { + match g { + deckcraft_model::Geom::Preset { name, adj } => craft_pptx::Geom::Preset { name: name.clone(), adj: adj.clone() }, + deckcraft_model::Geom::Custom { paths } => craft_pptx::Geom::Custom { + paths: paths.iter().map(|p| craft_pptx::CustomPath { w: p.w, h: p.h, d: p.d.clone(), fill: p.fill, stroke: p.stroke }).collect(), + }, + } +} + +fn geom_from(g: craft_pptx::Geom) -> deckcraft_model::Geom { + match g { + craft_pptx::Geom::Preset { name, adj } => deckcraft_model::Geom::Preset { name, adj }, + craft_pptx::Geom::Custom { paths } => deckcraft_model::Geom::Custom { + paths: paths.into_iter().map(|p| deckcraft_model::CustomPath { w: p.w, h: p.h, d: p.d, fill: p.fill, stroke: p.stroke }).collect(), + }, + } +} + +fn diagram_to(d: &deckcraft_model::Diagram) -> cd_dgm::Diagram { + cd_dgm::Diagram { + kind: d.kind.clone(), + nodes: d + .nodes + .iter() + .map(|n| cd_dgm::DiagramNode { + text: n.text.clone(), + level: n.level, + picture: n.picture.map(media_id_to), + assistant: n.assistant, + title: n.title.clone(), + }) + .collect(), + style: d.style.clone(), + colors: d.colors.clone(), + imported: d.imported, + layout_id: d.layout_id.clone(), + layout_xml: d.layout_xml.clone(), + style_xml: d.style_xml.clone(), + colors_xml: d.colors_xml.clone(), + } +} + +fn diagram_from(d: cd_dgm::Diagram) -> deckcraft_model::Diagram { + deckcraft_model::Diagram { + kind: d.kind, + nodes: d + .nodes + .into_iter() + .map(|n| deckcraft_model::DiagramNode { + text: n.text, + level: n.level, + picture: n.picture.map(media_id_from), + assistant: n.assistant, + title: n.title, + }) + .collect(), + style: d.style, + colors: d.colors, + imported: d.imported, + layout_id: d.layout_id, + layout_xml: d.layout_xml, + style_xml: d.style_xml, + colors_xml: d.colors_xml, + } +} + +fn media_clip_to(m: &deckcraft_model::MediaClip) -> craft_pptx::MediaClip { + craft_pptx::MediaClip { + media: media_id_to(m.media), + video: m.video, + poster: m.poster.map(media_id_to), + crop: m.crop, + trim_start_ms: m.trim_start_ms, + trim_end_ms: m.trim_end_ms, + fade_in_ms: m.fade_in_ms, + fade_out_ms: m.fade_out_ms, + volume: m.volume, + autoplay: m.autoplay, + loop_play: m.loop_play, + rewind: m.rewind, + play_across_slides: m.play_across_slides, + hide_while_not_playing: m.hide_while_not_playing, + full_screen: m.full_screen, + bookmarks: m.bookmarks.clone(), + duration_ms: m.duration_ms, + width: m.width, + height: m.height, + } +} + +fn media_clip_from(m: craft_pptx::MediaClip) -> deckcraft_model::MediaClip { + deckcraft_model::MediaClip { + media: media_id_from(m.media), + video: m.video, + poster: m.poster.map(media_id_from), + crop: m.crop, + trim_start_ms: m.trim_start_ms, + trim_end_ms: m.trim_end_ms, + fade_in_ms: m.fade_in_ms, + fade_out_ms: m.fade_out_ms, + volume: m.volume, + autoplay: m.autoplay, + loop_play: m.loop_play, + rewind: m.rewind, + play_across_slides: m.play_across_slides, + hide_while_not_playing: m.hide_while_not_playing, + full_screen: m.full_screen, + bookmarks: m.bookmarks, + duration_ms: m.duration_ms, + width: m.width, + height: m.height, + } +} + +fn shape_kind_to(k: &deckcraft_model::ShapeKind) -> craft_pptx::ShapeKind { + match k { + deckcraft_model::ShapeKind::Shape => craft_pptx::ShapeKind::Shape, + deckcraft_model::ShapeKind::Picture { fill } => craft_pptx::ShapeKind::Picture { fill: picture_fill_to(fill) }, + deckcraft_model::ShapeKind::Group { children, child } => { + craft_pptx::ShapeKind::Group { children: children.iter().map(shape_to).collect(), child: *child } + } + deckcraft_model::ShapeKind::Connector { start, end } => craft_pptx::ShapeKind::Connector { + start: start.map(|(id, idx)| (shape_id_to(id), idx)), + end: end.map(|(id, idx)| (shape_id_to(id), idx)), + }, + deckcraft_model::ShapeKind::Table(t) => craft_pptx::ShapeKind::Table(table_to(t)), + deckcraft_model::ShapeKind::Chart(c) => craft_pptx::ShapeKind::Chart(Box::new(chart_to(c))), + deckcraft_model::ShapeKind::Media(m) => craft_pptx::ShapeKind::Media(media_clip_to(m)), + deckcraft_model::ShapeKind::Ink { strokes } => craft_pptx::ShapeKind::Ink { + strokes: strokes + .iter() + .map(|s| craft_pptx::InkStroke { points: s.points.clone(), color: s.color, width: s.width, highlighter: s.highlighter }) + .collect(), + }, + deckcraft_model::ShapeKind::Model3d { media, poster } => { + craft_pptx::ShapeKind::Model3d { media: media_id_to(*media), poster: poster.map(media_id_to) } + } + deckcraft_model::ShapeKind::Opaque { xml, preview, label, parts } => craft_pptx::ShapeKind::Opaque { + xml: xml.clone(), + preview: preview.map(media_id_to), + label: label.clone(), + parts: parts.iter().map(|(r, t, m)| (r.clone(), t.clone(), media_id_to(*m))).collect(), + }, + } +} + +fn shape_kind_from(k: craft_pptx::ShapeKind) -> deckcraft_model::ShapeKind { + match k { + craft_pptx::ShapeKind::Shape => deckcraft_model::ShapeKind::Shape, + craft_pptx::ShapeKind::Picture { fill } => deckcraft_model::ShapeKind::Picture { fill: picture_fill_from(fill) }, + craft_pptx::ShapeKind::Group { children, child } => { + deckcraft_model::ShapeKind::Group { children: children.into_iter().map(shape_from).collect(), child } + } + craft_pptx::ShapeKind::Connector { start, end } => deckcraft_model::ShapeKind::Connector { + start: start.map(|(id, idx)| (shape_id_from(id), idx)), + end: end.map(|(id, idx)| (shape_id_from(id), idx)), + }, + craft_pptx::ShapeKind::Table(t) => deckcraft_model::ShapeKind::Table(table_from(t)), + craft_pptx::ShapeKind::Chart(c) => deckcraft_model::ShapeKind::Chart(Box::new(chart_from(*c))), + craft_pptx::ShapeKind::Media(m) => deckcraft_model::ShapeKind::Media(media_clip_from(m)), + craft_pptx::ShapeKind::Ink { strokes } => deckcraft_model::ShapeKind::Ink { + strokes: strokes + .into_iter() + .map(|s| deckcraft_model::InkStroke { points: s.points, color: s.color, width: s.width, highlighter: s.highlighter }) + .collect(), + }, + craft_pptx::ShapeKind::Model3d { media, poster } => { + deckcraft_model::ShapeKind::Model3d { media: media_id_from(media), poster: poster.map(media_id_from) } + } + craft_pptx::ShapeKind::Opaque { xml, preview, label, parts } => deckcraft_model::ShapeKind::Opaque { + xml, + preview: preview.map(media_id_from), + label, + parts: parts.into_iter().map(|(r, t, m)| (r, t, media_id_from(m))).collect(), + }, + } +} + +fn shape_to(s: &deckcraft_model::Shape) -> craft_pptx::Shape { + craft_pptx::Shape { + id: shape_id_to(s.id), + name: s.name.clone(), + xfrm: s.xfrm, + kind: shape_kind_to(&s.kind), + geom: geom_to(&s.geom), + ph: s.ph.as_ref().map(|p| craft_pptx::Placeholder { + kind: ph_type_to(p.kind), + idx: p.idx, + vertical: p.vertical, + size: p.size.clone(), + has_custom_prompt: p.has_custom_prompt, + }), + fill: s.fill.as_ref().map(fill_to), + line: s.line.as_ref().map(line_to), + effects: s.effects.as_ref().map(effects_to), + style: s.style.as_ref().map(shape_style_to), + text: s.text.as_ref().map(text_body_to), + hidden: s.hidden, + locked: s.locked, + text_box: s.text_box, + descr: s.descr.clone(), + title: s.title.clone(), + decorative: s.decorative, + click: s.click.as_ref().map(hyperlink_to), + hover: s.hover.as_ref().map(hyperlink_to), + tags: s.tags.clone(), + raw_ext: s.raw_ext.clone(), + diagram: s.diagram.as_ref().map(diagram_to), + } +} + +fn shape_from(s: craft_pptx::Shape) -> deckcraft_model::Shape { + deckcraft_model::Shape { + id: shape_id_from(s.id), + name: s.name, + xfrm: s.xfrm, + kind: shape_kind_from(s.kind), + geom: geom_from(s.geom), + ph: s.ph.map(|p| deckcraft_model::Placeholder { + kind: ph_type_from(p.kind), + idx: p.idx, + vertical: p.vertical, + size: p.size, + has_custom_prompt: p.has_custom_prompt, + }), + fill: s.fill.map(fill_from), + line: s.line.map(line_from), + effects: s.effects.map(effects_from), + style: s.style.map(shape_style_from), + text: s.text.map(text_body_from), + hidden: s.hidden, + locked: s.locked, + text_box: s.text_box, + descr: s.descr, + title: s.title, + decorative: s.decorative, + click: s.click.map(hyperlink_from), + hover: s.hover.map(hyperlink_from), + tags: s.tags, + raw_ext: s.raw_ext, + diagram: s.diagram.map(diagram_from), + } +} + +fn background_to(b: &deckcraft_model::Background) -> craft_pptx::Background { + match b { + deckcraft_model::Background::Fill { fill } => craft_pptx::Background::Fill { fill: fill_to(fill) }, + deckcraft_model::Background::Ref { idx, color } => craft_pptx::Background::Ref { idx: *idx, color: color_ref_to(color) }, + } +} + +fn background_from(b: craft_pptx::Background) -> deckcraft_model::Background { + match b { + craft_pptx::Background::Fill { fill } => deckcraft_model::Background::Fill { fill: fill_from(fill) }, + craft_pptx::Background::Ref { idx, color } => deckcraft_model::Background::Ref { idx, color: color_ref_from(color) }, + } +} + +fn comment_to(c: &deckcraft_model::Comment) -> craft_pptx::Comment { + craft_pptx::Comment { + author: c.author.clone(), + initials: c.initials.clone(), + text: c.text.clone(), + date: c.date.clone(), + x: c.x, + y: c.y, + resolved: c.resolved, + replies: c.replies.iter().map(comment_to).collect(), + shape: c.shape.map(shape_id_to), + } +} + +fn comment_from(c: craft_pptx::Comment) -> deckcraft_model::Comment { + deckcraft_model::Comment { + author: c.author, + initials: c.initials, + text: c.text, + date: c.date, + x: c.x, + y: c.y, + resolved: c.resolved, + replies: c.replies.into_iter().map(comment_from).collect(), + shape: c.shape.map(shape_id_from), + } +} + +fn slide_to(s: &deckcraft_model::Slide) -> craft_pptx::Slide { + craft_pptx::Slide { + id: slide_id_to(s.id), + layout: layout_id_to(s.layout), + name: s.name.clone(), + shapes: s.shapes.iter().map(shape_to).collect(), + background: s.background.as_ref().map(background_to), + hidden: s.hidden, + show_master_shapes: s.show_master_shapes, + transition: s.transition.as_ref().map(transition_to), + animations: s.animations.iter().map(animation_to).collect(), + notes: text_body_to(&s.notes), + has_notes_slide: s.has_notes_slide, + comments: s.comments.iter().map(comment_to).collect(), + color_map: s.color_map.clone(), + tags: s.tags.clone(), + raw_ext: s.raw_ext.clone(), + } +} + +fn slide_from(s: craft_pptx::Slide) -> deckcraft_model::Slide { + deckcraft_model::Slide { + id: slide_id_from(s.id), + layout: layout_id_from(s.layout), + name: s.name, + shapes: s.shapes.into_iter().map(shape_from).collect(), + background: s.background.map(background_from), + hidden: s.hidden, + show_master_shapes: s.show_master_shapes, + transition: s.transition.map(transition_from), + animations: s.animations.into_iter().map(animation_from).collect(), + notes: text_body_from(s.notes), + has_notes_slide: s.has_notes_slide, + comments: s.comments.into_iter().map(comment_from).collect(), + color_map: s.color_map, + tags: s.tags, + raw_ext: s.raw_ext, + } +} + +fn layout_type_to(k: deckcraft_model::LayoutType) -> craft_pptx::LayoutType { + match k { + deckcraft_model::LayoutType::Title => craft_pptx::LayoutType::Title, + deckcraft_model::LayoutType::TitleAndContent => craft_pptx::LayoutType::TitleAndContent, + deckcraft_model::LayoutType::SectionHeader => craft_pptx::LayoutType::SectionHeader, + deckcraft_model::LayoutType::TwoContent => craft_pptx::LayoutType::TwoContent, + deckcraft_model::LayoutType::Comparison => craft_pptx::LayoutType::Comparison, + deckcraft_model::LayoutType::TitleOnly => craft_pptx::LayoutType::TitleOnly, + deckcraft_model::LayoutType::Blank => craft_pptx::LayoutType::Blank, + deckcraft_model::LayoutType::ContentWithCaption => craft_pptx::LayoutType::ContentWithCaption, + deckcraft_model::LayoutType::PictureWithCaption => craft_pptx::LayoutType::PictureWithCaption, + deckcraft_model::LayoutType::TitleAndVerticalText => craft_pptx::LayoutType::TitleAndVerticalText, + deckcraft_model::LayoutType::VerticalTitleAndText => craft_pptx::LayoutType::VerticalTitleAndText, + deckcraft_model::LayoutType::Custom => craft_pptx::LayoutType::Custom, + } +} + +fn layout_type_from(k: craft_pptx::LayoutType) -> deckcraft_model::LayoutType { + match k { + craft_pptx::LayoutType::Title => deckcraft_model::LayoutType::Title, + craft_pptx::LayoutType::TitleAndContent => deckcraft_model::LayoutType::TitleAndContent, + craft_pptx::LayoutType::SectionHeader => deckcraft_model::LayoutType::SectionHeader, + craft_pptx::LayoutType::TwoContent => deckcraft_model::LayoutType::TwoContent, + craft_pptx::LayoutType::Comparison => deckcraft_model::LayoutType::Comparison, + craft_pptx::LayoutType::TitleOnly => deckcraft_model::LayoutType::TitleOnly, + craft_pptx::LayoutType::Blank => deckcraft_model::LayoutType::Blank, + craft_pptx::LayoutType::ContentWithCaption => deckcraft_model::LayoutType::ContentWithCaption, + craft_pptx::LayoutType::PictureWithCaption => deckcraft_model::LayoutType::PictureWithCaption, + craft_pptx::LayoutType::TitleAndVerticalText => deckcraft_model::LayoutType::TitleAndVerticalText, + craft_pptx::LayoutType::VerticalTitleAndText => deckcraft_model::LayoutType::VerticalTitleAndText, + craft_pptx::LayoutType::Custom => deckcraft_model::LayoutType::Custom, + } +} + +fn layout_to(l: &deckcraft_model::Layout) -> craft_pptx::Layout { + craft_pptx::Layout { + id: layout_id_to(l.id), + name: l.name.clone(), + kind: layout_type_to(l.kind), + shapes: l.shapes.iter().map(shape_to).collect(), + background: l.background.as_ref().map(background_to), + show_master_shapes: l.show_master_shapes, + preserve: l.preserve, + color_map: l.color_map.clone(), + raw_ext: l.raw_ext.clone(), + } +} + +fn layout_from(l: craft_pptx::Layout) -> deckcraft_model::Layout { + deckcraft_model::Layout { + id: layout_id_from(l.id), + name: l.name, + kind: layout_type_from(l.kind), + shapes: l.shapes.into_iter().map(shape_from).collect(), + background: l.background.map(background_from), + show_master_shapes: l.show_master_shapes, + preserve: l.preserve, + color_map: l.color_map, + raw_ext: l.raw_ext, + } +} + +pub(crate) fn master_to_craft(m: &deckcraft_model::Master) -> craft_pptx::Master { + craft_pptx::Master { + id: master_id_to(m.id), + name: m.name.clone(), + theme: theme_to_craft(&m.theme), + shapes: m.shapes.iter().map(shape_to).collect(), + background: m.background.as_ref().map(background_to), + title_style: list_style_to_craft(&m.title_style), + body_style: list_style_to_craft(&m.body_style), + other_style: list_style_to_craft(&m.other_style), + layouts: m.layouts.iter().map(layout_to).collect(), + color_map: m.color_map.clone(), + preserve: m.preserve, + raw_ext: m.raw_ext.clone(), + } +} + +fn master_from(m: craft_pptx::Master) -> deckcraft_model::Master { + deckcraft_model::Master { + id: master_id_from(m.id), + name: m.name, + theme: theme_from_craft(m.theme), + shapes: m.shapes.into_iter().map(shape_from).collect(), + background: m.background.map(background_from), + title_style: list_style_from(m.title_style), + body_style: list_style_from(m.body_style), + other_style: list_style_from(m.other_style), + layouts: m.layouts.into_iter().map(layout_from).collect(), + color_map: m.color_map, + preserve: m.preserve, + raw_ext: m.raw_ext, + } +} + +pub(crate) fn media_item_from_craft(m: craft_pptx::MediaItem) -> deckcraft_model::MediaItem { + deckcraft_model::MediaItem { id: media_id_from(m.id), name: m.name, content_type: m.content_type, data: m.data, link: m.link } +} + +fn media_item_to(m: &deckcraft_model::MediaItem) -> craft_pptx::MediaItem { + craft_pptx::MediaItem { + id: media_id_to(m.id), + name: m.name.clone(), + content_type: m.content_type.clone(), + data: Arc::clone(&m.data), + link: m.link.clone(), + } +} + +pub(crate) fn pres_to_craft(p: &deckcraft_model::Presentation) -> craft_pptx::Presentation { + craft_pptx::Presentation { + slide_size: p.slide_size, + notes_size: p.notes_size, + slides: p.slides.iter().map(|s| Arc::new(slide_to(s))).collect(), + masters: p.masters.iter().map(|m| Arc::new(master_to_craft(m))).collect(), + notes_master: p.notes_master.as_ref().map(|m| Arc::new(master_to_craft(m))), + handout_master: p.handout_master.as_ref().map(|m| Arc::new(master_to_craft(m))), + sections: p + .sections + .iter() + .map(|s| craft_pptx::Section { name: s.name.clone(), slides: s.slides.iter().copied().map(slide_id_to).collect() }) + .collect(), + custom_shows: p + .custom_shows + .iter() + .map(|c| craft_pptx::CustomShow { name: c.name.clone(), slides: c.slides.iter().copied().map(slide_id_to).collect() }) + .collect(), + show: craft_pptx::ShowSettings { + show_type: p.show.show_type.clone(), + loop_until_esc: p.show.loop_until_esc, + without_narration: p.show.without_narration, + without_animation: p.show.without_animation, + use_timings: p.show.use_timings, + range: p.show.range, + custom_show: p.show.custom_show.clone(), + pen_color: p.show.pen_color, + laser_color: p.show.laser_color, + show_media_controls: p.show.show_media_controls, + }, + header_footer: craft_pptx::HeaderFooter { + date: p.header_footer.date, + slide_number: p.header_footer.slide_number, + footer: p.header_footer.footer, + header: p.header_footer.header, + footer_text: p.header_footer.footer_text.clone(), + date_text: p.header_footer.date_text.clone(), + date_format: p.header_footer.date_format.clone(), + hide_on_title: p.header_footer.hide_on_title, + }, + props: craft_pptx::Properties { + title: p.props.title.clone(), + subject: p.props.subject.clone(), + author: p.props.author.clone(), + keywords: p.props.keywords.clone(), + comments: p.props.comments.clone(), + category: p.props.category.clone(), + company: p.props.company.clone(), + created: p.props.created.clone(), + modified: p.props.modified.clone(), + last_modified_by: p.props.last_modified_by.clone(), + revision: p.props.revision, + }, + default_text_style: list_style_to_craft(&p.default_text_style), + media: p.media.iter().map(media_item_to).collect(), + first_slide_number: p.first_slide_number, + next_id: p.next_id, + embedded_fonts: p + .embedded_fonts + .iter() + .map(|f| craft_pptx::EmbeddedFont { + typeface: f.typeface.clone(), + panose: f.panose.clone(), + pitch_family: f.pitch_family, + charset: f.charset, + regular: f.regular.map(media_id_to), + bold: f.bold.map(media_id_to), + italic: f.italic.map(media_id_to), + bold_italic: f.bold_italic.map(media_id_to), + }) + .collect(), + table_styles: p.table_styles.iter().map(table_style_def_to).collect(), + tags: p.tags.clone(), + kept_parts: p + .kept_parts + .iter() + .map(|k| craft_pptx::KeptPart { + name: k.name.clone(), + content_type: k.content_type.clone(), + xml: k.xml.clone(), + rel_type: k.rel_type.clone(), + from_root: k.from_root, + }) + .collect(), + guides: p.guides.iter().map(|g| craft_pptx::DrawGuide { vertical: g.vertical, pos: g.pos }).collect(), + raw_ext: p.raw_ext.clone(), + } +} + +const DATE_KINDS: [&str; 13] = [ + "datetime1", + "datetime2", + "datetime3", + "datetime4", + "datetime5", + "datetime6", + "datetime7", + "datetime8", + "datetime9", + "datetime10", + "datetime11", + "datetime12", + "datetime13", +]; + +fn infer_date_format(slides: &[Arc]) -> String { + for s in slides { + for sh in &s.shapes { + if sh.ph_type() != Some(deckcraft_model::PhType::Date) { + continue; + } + if let Some(kind) = sh.text.iter().flat_map(|t| t.paragraphs.iter()).flat_map(|p| p.runs.iter()).find_map(|r| match &r.kind { + dm_text::RunKind::Field { field } if DATE_KINDS.contains(&field.as_str()) => Some(field.as_str()), + _ => None, + }) { + return kind.to_string(); + } + } + } + String::new() +} + +pub(crate) fn pres_from_craft(p: craft_pptx::Presentation) -> deckcraft_model::Presentation { + let slides: Vec> = p.slides.into_iter().map(|s| Arc::new(slide_from((*s).clone()))).collect(); + let mut header_footer = deckcraft_model::HeaderFooter { + date: p.header_footer.date, + slide_number: p.header_footer.slide_number, + footer: p.header_footer.footer, + header: p.header_footer.header, + footer_text: p.header_footer.footer_text, + date_text: p.header_footer.date_text, + date_format: p.header_footer.date_format, + hide_on_title: p.header_footer.hide_on_title, + }; + if header_footer.date && header_footer.date_format.is_empty() && header_footer.date_text.is_empty() { + header_footer.date_format = infer_date_format(&slides); + } + deckcraft_model::Presentation { + slide_size: p.slide_size, + notes_size: p.notes_size, + slides, + masters: p.masters.into_iter().map(|m| Arc::new(master_from((*m).clone()))).collect(), + notes_master: p.notes_master.map(|m| Arc::new(master_from((*m).clone()))), + handout_master: p.handout_master.map(|m| Arc::new(master_from((*m).clone()))), + sections: p + .sections + .into_iter() + .map(|s| deckcraft_model::Section { name: s.name, slides: s.slides.into_iter().map(slide_id_from).collect() }) + .collect(), + custom_shows: p + .custom_shows + .into_iter() + .map(|c| deckcraft_model::CustomShow { name: c.name, slides: c.slides.into_iter().map(slide_id_from).collect() }) + .collect(), + show: deckcraft_model::ShowSettings { + show_type: p.show.show_type, + loop_until_esc: p.show.loop_until_esc, + without_narration: p.show.without_narration, + without_animation: p.show.without_animation, + use_timings: p.show.use_timings, + range: p.show.range, + custom_show: p.show.custom_show, + pen_color: p.show.pen_color, + laser_color: p.show.laser_color, + show_media_controls: p.show.show_media_controls, + }, + header_footer, + props: deckcraft_model::Properties { + title: p.props.title, + subject: p.props.subject, + author: p.props.author, + keywords: p.props.keywords, + comments: p.props.comments, + category: p.props.category, + company: p.props.company, + created: p.props.created, + modified: p.props.modified, + last_modified_by: p.props.last_modified_by, + revision: p.props.revision, + }, + default_text_style: list_style_from(p.default_text_style), + media: p.media.into_iter().map(media_item_from_craft).collect(), + first_slide_number: p.first_slide_number, + next_id: p.next_id, + embedded_fonts: p + .embedded_fonts + .into_iter() + .map(|f| deckcraft_model::EmbeddedFont { + typeface: f.typeface, + panose: f.panose, + pitch_family: f.pitch_family, + charset: f.charset, + regular: f.regular.map(media_id_from), + bold: f.bold.map(media_id_from), + italic: f.italic.map(media_id_from), + bold_italic: f.bold_italic.map(media_id_from), + }) + .collect(), + table_styles: p.table_styles.into_iter().map(table_style_def_from).collect(), + tags: p.tags, + kept_parts: p + .kept_parts + .into_iter() + .map(|k| deckcraft_model::KeptPart { + name: k.name, + content_type: k.content_type, + xml: k.xml, + rel_type: k.rel_type, + from_root: k.from_root, + }) + .collect(), + guides: p.guides.into_iter().map(|g| deckcraft_model::DrawGuide { vertical: g.vertical, pos: g.pos }).collect(), + raw_ext: p.raw_ext, + } +} diff --git a/crates/pptx/src/custgeom.rs b/crates/pptx/src/custgeom.rs deleted file mode 100644 index a3590de16..000000000 --- a/crates/pptx/src/custgeom.rs +++ /dev/null @@ -1,547 +0,0 @@ -//! DrawingML custom geometry (`a:custGeom`): guide formula evaluation and conversion of -//! `a:pathLst` to our `M L C Q Z` path syntax, and back. -//! -//! Formulas follow the ECMA-376 shape guide semantics (§20.1.9.11): angles are in 1/60 000 degree, -//! and every operand is a guide name, a built-in variable or an integer literal. - -use std::collections::HashMap; -use std::f64::consts::PI; -use std::fmt::Write as _; - -use deckcraft_geom::preset::FillMode; -use deckcraft_model::CustomPath; - -use crate::xml::{A, El, W}; - -const DEG: f64 = 60_000.0; - -/// Distinct path coordinate spaces whose guides are evaluated for one custom geometry; paths in -/// further spaces are left out. -const MAX_SPACES: usize = 16; - -/// Guide-name bytes all cached spaces may hold between them; the first space counts towards it but is always kept. -/// Every space copies the names, which the XML limits bound only once. -const MAX_SPACE_NAME_BYTES: usize = 4 << 20; - -/// Guide variables for one shape. -pub struct Guides { - vars: HashMap, -} - -fn to_rad(a: f64) -> f64 { - a / DEG * PI / 180.0 -} - -fn to_ang(r: f64) -> f64 { - r * 180.0 / PI * DEG -} - -fn finite(v: f64) -> f64 { - if v.is_finite() { v.clamp(-1.0e15, 1.0e15) } else { 0.0 } -} - -impl Guides { - /// Built-in variables for a shape `w` × `h` (in the shape's coordinate units). - pub fn new(w: f64, h: f64) -> Self { - let (w, h) = (finite(w), finite(h)); - let ss = w.min(h); - let ls = w.max(h); - let mut v = HashMap::new(); - let mut set = |k: &str, x: f64| { - v.insert(k.to_string(), x); - }; - set("w", w); - set("h", h); - set("l", 0.0); - set("t", 0.0); - set("r", w); - set("b", h); - set("hc", w / 2.0); - set("vc", h / 2.0); - set("ss", ss); - set("ls", ls); - for d in [2.0, 3.0, 4.0, 5.0, 6.0, 8.0, 10.0, 12.0, 16.0, 32.0] { - set(&format!("wd{d}"), w / d); - set(&format!("hd{d}"), h / d); - set(&format!("ssd{d}"), ss / d); - } - set("cd2", 10_800_000.0); - set("cd4", 5_400_000.0); - set("cd8", 2_700_000.0); - set("3cd4", 16_200_000.0); - set("3cd8", 8_100_000.0); - set("5cd8", 13_500_000.0); - set("7cd8", 18_900_000.0); - Guides { vars: v } - } - /// Bytes of the guide names held. - fn name_bytes(&self) -> usize { - self.vars.keys().map(String::len).sum() - } - pub fn get(&self, name: &str) -> f64 { - let name = name.trim(); - if let Some(v) = self.vars.get(name) { - return *v; - } - name.parse::().ok().map(finite).unwrap_or(0.0) - } - pub fn set(&mut self, name: &str, v: f64) { - if self.vars.len() < 10_000 { - self.vars.insert(name.to_string(), finite(v)); - } - } - /// Evaluate one formula (`*/ w 1 2`). - pub fn eval(&self, fmla: &str) -> f64 { - let mut it = fmla.split_whitespace(); - let op = it.next().unwrap_or(""); - let args: Vec = it.take(3).map(|a| self.get(a)).collect(); - let a = |i: usize| args.get(i).copied().unwrap_or(0.0); - let div = |n: f64, d: f64| if d == 0.0 { 0.0 } else { n / d }; - let r = match op { - "*/" => div(a(0) * a(1), a(2)), - "+-" => a(0) + a(1) - a(2), - "+/" => div(a(0) + a(1), a(2)), - "?:" => { - if a(0) > 0.0 { - a(1) - } else { - a(2) - } - } - "abs" => a(0).abs(), - "at2" => to_ang(a(1).atan2(a(0))), - "cat2" => a(0) * a(2).atan2(a(1)).cos(), - "sat2" => a(0) * a(2).atan2(a(1)).sin(), - "cos" => a(0) * to_rad(a(1)).cos(), - "sin" => a(0) * to_rad(a(1)).sin(), - "tan" => a(0) * to_rad(a(1)).tan(), - "max" => a(0).max(a(1)), - "min" => a(0).min(a(1)), - "mod" => (a(0) * a(0) + a(1) * a(1) + a(2) * a(2)).sqrt(), - "pin" => { - if a(1) < a(0) { - a(0) - } else if a(1) > a(2) { - a(2) - } else { - a(1) - } - } - "sqrt" => a(0).max(0.0).sqrt(), - "val" => a(0), - _ => 0.0, - }; - finite(r) - } - /// Evaluate a list of `a:gd` elements in order. - pub fn eval_list(&mut self, list: Option<&El>) { - let Some(list) = list else { return }; - for gd in list.children_named("gd").take(5000) { - let (Some(name), Some(f)) = (gd.attr("name"), gd.attr("fmla")) else { continue }; - let v = self.eval(f); - self.set(name, v); - } - } -} - -fn num(s: &mut String, v: f64) { - let v = finite(v); - let r = (v * 1000.0).round() / 1000.0; - if r == r.trunc() { - let _ = write!(s, "{}", r as i64); - } else { - let _ = write!(s, "{r}"); - } -} - -fn pt(g: &Guides, e: &El) -> (f64, f64) { - (g.get(e.attr("x").unwrap_or("0")), g.get(e.attr("y").unwrap_or("0"))) -} - -/// Convert `a:custGeom` to custom paths. `w`/`h` is the shape size in EMU (used for guides and for -/// paths that don't give their own coordinate space). -pub fn read_cust_geom(cg: &El, w_emu: f64, h_emu: f64) -> Vec { - read_cust_geom_counting(cg, w_emu, h_emu).0 -} - -/// [`read_cust_geom`], and how many paths were left out for lack of room in the guide caches -/// (`(too many coordinate spaces, too many guide-name bytes)`); each cause is also logged once. -fn read_cust_geom_counting(cg: &El, w_emu: f64, h_emu: f64) -> (Vec, (usize, usize)) { - let mut out = vec![]; - let mut dropped = (0usize, 0usize); - let Some(pl) = cg.child("pathLst") else { return (out, dropped) }; - let mut spaces: HashMap<(u64, u64), Guides> = HashMap::new(); - let mut name_bytes = 0usize; - let mut budget_full = false; - // The cap on cached spaces saves guide evaluation: a geometry without guides has none to save. - let guided = ["avLst", "gdLst"].iter().any(|n| cg.child(n).is_some_and(|l| l.elements().next().is_some())); - for p in pl.children_named("path").take(1000) { - let pw = p.f64("w").unwrap_or(0.0); - let ph = p.f64("h").unwrap_or(0.0); - // Guides are evaluated in the path's own space when it has one. - let (gw, gh) = if pw > 0.0 || ph > 0.0 { (pw, ph) } else { (w_emu, h_emu) }; - // The guide lists are evaluated once per coordinate space, not once per path. - let key = (gw.to_bits(), gh.to_bits()); - if !spaces.contains_key(&key) { - if guided && (budget_full || spaces.len() >= MAX_SPACES) { - if budget_full { - dropped.1 += 1; - } else { - dropped.0 += 1; - } - continue; - } - let mut g = Guides::new(gw, gh); - g.eval_list(cg.child("avLst")); - g.eval_list(cg.child("gdLst")); - // The first space is always kept; later ones only while the cache stays within budget. - let bytes = g.name_bytes(); - if guided && !spaces.is_empty() && name_bytes.saturating_add(bytes) > MAX_SPACE_NAME_BYTES { - // Every space holds the same names, so no later space fits either. - budget_full = true; - dropped.1 += 1; - continue; - } - name_bytes = name_bytes.saturating_add(bytes); - spaces.insert(key, g); - } - let Some(g) = spaces.get(&key) else { continue }; - let mut d = String::new(); - let mut cur = (0.0, 0.0); - let mut start = (0.0, 0.0); - for c in p.elements().take(100_000) { - match c.local() { - "moveTo" => { - if let Some(q) = c.child("pt") { - cur = pt(g, q); - start = cur; - d.push_str("M "); - num(&mut d, cur.0); - d.push(' '); - num(&mut d, cur.1); - d.push(' '); - } - } - "lnTo" => { - if let Some(q) = c.child("pt") { - cur = pt(g, q); - d.push_str("L "); - num(&mut d, cur.0); - d.push(' '); - num(&mut d, cur.1); - d.push(' '); - } - } - "cubicBezTo" => { - let pts: Vec<(f64, f64)> = c.children_named("pt").map(|q| pt(g, q)).collect(); - if let [a, b, e] = pts.as_slice() { - d.push_str("C "); - for (x, y) in [a, b, e] { - num(&mut d, *x); - d.push(' '); - num(&mut d, *y); - d.push(' '); - } - cur = *e; - } - } - "quadBezTo" => { - let pts: Vec<(f64, f64)> = c.children_named("pt").map(|q| pt(g, q)).collect(); - if let [a, e] = pts.as_slice() { - d.push_str("Q "); - for (x, y) in [a, e] { - num(&mut d, *x); - d.push(' '); - num(&mut d, *y); - d.push(' '); - } - cur = *e; - } - } - "arcTo" => { - let wr = g.get(c.attr("wR").unwrap_or("0")); - let hr = g.get(c.attr("hR").unwrap_or("0")); - let st = g.get(c.attr("stAng").unwrap_or("0")); - let sw = g.get(c.attr("swAng").unwrap_or("0")); - cur = arc_to(&mut d, cur, wr, hr, st, sw); - } - "close" => { - d.push_str("Z "); - cur = start; - } - _ => {} - } - } - let fill = match p.attr("fill").unwrap_or("norm") { - "none" => FillMode::None, - "lighten" => FillMode::Lighten, - "lightenLess" => FillMode::LightenLess, - "darken" => FillMode::Darken, - "darkenLess" => FillMode::DarkenLess, - _ => FillMode::Norm, - }; - let (ow, oh) = if pw > 0.0 || ph > 0.0 { (pw, ph) } else { (w_emu.max(1.0), h_emu.max(1.0)) }; - out.push(CustomPath { w: ow, h: oh, d: d.trim_end().to_string(), fill, stroke: p.bool("stroke").unwrap_or(true) }); - } - if dropped.0 > 0 { - log::warn!("pptx: a custom geometry uses more than {MAX_SPACES} distinct path coordinate spaces; {} later path(s) are not kept", dropped.0); - } - if dropped.1 > 0 { - log::warn!( - "pptx: a custom geometry's guide names pass {MAX_SPACE_NAME_BYTES} bytes across its coordinate spaces; {} later path(s) are not kept", - dropped.1 - ); - } - (out, dropped) -} - -/// Ellipse parametric angle for a visual angle `a` (radians). -fn param(a: f64, wr: f64, hr: f64) -> f64 { - (wr * a.sin()).atan2(hr * a.cos()) -} - -/// Append an elliptical arc as cubic Béziers; returns the end point. -fn arc_to(d: &mut String, cur: (f64, f64), wr: f64, hr: f64, st: f64, sw: f64) -> (f64, f64) { - if wr.abs() < 1e-9 || hr.abs() < 1e-9 || sw == 0.0 { - return cur; - } - let st_r = to_rad(st); - let sw_r = to_rad(sw).clamp(-4.0 * PI, 4.0 * PI); - let t0 = param(st_r, wr, hr); - let mut t1 = param(st_r + sw_r, wr, hr); - // Keep the sweep direction and size of the visual angle. - let full = sw_r.abs() >= 2.0 * PI - 1e-9; - if full { - t1 = t0 + sw_r.signum() * 2.0 * PI; - } else { - while sw_r > 0.0 && t1 < t0 { - t1 += 2.0 * PI; - } - while sw_r < 0.0 && t1 > t0 { - t1 -= 2.0 * PI; - } - } - let cx = cur.0 - wr * t0.cos(); - let cy = cur.1 - hr * t0.sin(); - let total = t1 - t0; - let n = ((total.abs() / (PI / 2.0)).ceil() as usize).clamp(1, 16); - let step = total / n as f64; - let k = 4.0 / 3.0 * (step / 4.0).tan(); - let mut a = t0; - let mut end = cur; - for _ in 0..n { - let b = a + step; - let (ca, sa, cb, sb) = (a.cos(), a.sin(), b.cos(), b.sin()); - let p1 = (cx + wr * (ca - k * sa), cy + hr * (sa + k * ca)); - let p2 = (cx + wr * (cb + k * sb), cy + hr * (sb - k * cb)); - end = (cx + wr * cb, cy + hr * sb); - d.push_str("C "); - for (x, y) in [p1, p2, end] { - num(d, x); - d.push(' '); - num(d, y); - d.push(' '); - } - a = b; - } - end -} - -/// Parse our path syntax into commands. -pub use craft_drawingml::custgeom::parse_path; - -/// Write custom paths as `a:custGeom`. Coordinates are integers in the file, so small path spaces -/// are scaled up. -pub fn write_cust_geom(w: &mut W, paths: &[CustomPath]) { - w.open0("a:custGeom"); - w.empty0("a:avLst"); - w.empty0("a:gdLst"); - w.empty0("a:ahLst"); - w.empty0("a:cxnLst"); - w.empty("a:rect", A::new().a("l", "l").a("t", "t").a("r", "r").a("b", "b")); - w.open0("a:pathLst"); - for p in paths { - let (pw, ph) = (finite(p.w).abs(), finite(p.h).abs()); - let m = pw.max(ph); - let k = if m > 0.0 && m < 20_000.0 { 100_000.0 / m } else { 1.0 }; - let r = |v: f64| (finite(v) * k).round().clamp(-2.0e9, 2.0e9) as i64; - let fill = match p.fill { - FillMode::Norm => None, - FillMode::None => Some("none"), - FillMode::Lighten => Some("lighten"), - FillMode::LightenLess => Some("lightenLess"), - FillMode::Darken => Some("darken"), - FillMode::DarkenLess => Some("darkenLess"), - }; - let a = A::new().a("w", r(pw).max(0)).a("h", r(ph).max(0)).o("fill", fill).o("stroke", (!p.stroke).then_some("0")); - w.open("a:path", a); - for (c, v) in parse_path(&p.d) { - let pts: Vec<(i64, i64)> = v - .chunks(2) - .filter_map(|c| match c { - [x, y] => Some((r(*x), r(*y))), - _ => None, - }) - .collect(); - let tag = match c { - 'M' => "a:moveTo", - 'L' => "a:lnTo", - 'C' => "a:cubicBezTo", - 'Q' => "a:quadBezTo", - 'Z' => { - w.empty0("a:close"); - continue; - } - _ => continue, - }; - w.open0(tag); - for (x, y) in pts { - w.empty("a:pt", A::new().a("x", x).a("y", y)); - } - w.close(tag); - } - w.close("a:path"); - } - w.close("a:pathLst"); - w.close("a:custGeom"); -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::xml::parse; - - #[test] - fn formulas() { - let mut g = Guides::new(1000.0, 500.0); - assert_eq!(g.eval("*/ w 1 2"), 500.0); - assert_eq!(g.eval("+- w h 100"), 1400.0); - assert_eq!(g.eval("+/ w h 3"), 500.0); - assert_eq!(g.eval("?: -1 5 7"), 7.0); - assert_eq!(g.eval("?: 1 5 7"), 5.0); - assert_eq!(g.eval("abs -42"), 42.0); - assert_eq!(g.eval("max 3 9"), 9.0); - assert_eq!(g.eval("min 3 9"), 3.0); - assert_eq!(g.eval("mod 3 4 0"), 5.0); - assert_eq!(g.eval("pin 0 150 100"), 100.0); - assert_eq!(g.eval("pin 0 -5 100"), 0.0); - assert_eq!(g.eval("sqrt 16"), 4.0); - assert_eq!(g.eval("val ss"), 500.0); - assert!((g.eval("at2 1 1") - 2_700_000.0).abs() < 1e-6); - assert!((g.eval("cos 100 5400000")).abs() < 1e-9); - assert!((g.eval("sin 100 5400000") - 100.0).abs() < 1e-9); - assert!((g.eval("tan 100 2700000") - 100.0).abs() < 1e-6); - assert!((g.eval("cat2 10 1 0") - 10.0).abs() < 1e-9); - assert!((g.eval("sat2 10 0 1") - 10.0).abs() < 1e-9); - assert_eq!(g.eval("*/ 1 1 0"), 0.0, "division by zero is 0"); - assert_eq!(g.eval("bogus 1 2"), 0.0); - assert_eq!(g.eval(""), 0.0); - g.set("x1", 7.0); - assert_eq!(g.eval("+- x1 0 2"), 5.0); - assert_eq!(g.get("hc"), 500.0); - assert_eq!(g.get("cd4"), 5_400_000.0); - } - - #[test] - fn custgeom_with_guides_and_arc() { - let x = br#" - - - "#; - let d = parse(x).unwrap(); - let paths = read_cust_geom(&d.root, 1000.0, 1000.0); - assert_eq!(paths.len(), 2); - assert!(paths[0].d.starts_with("M 0 0 L 100 100 C"), "{}", paths[0].d); - assert!(paths[0].d.ends_with('Z')); - // The quarter arc from (100,100) with centre (50,100) ends at (50,150). - assert!(paths[0].d.contains("50 150"), "{}", paths[0].d); - assert_eq!(paths[1].fill, FillMode::None); - assert!(!paths[1].stroke); - assert_eq!(paths[1].d, "M 1 1 Q 2 2 3 1"); - } - - #[test] - fn paths_share_guides_and_distinct_spaces_are_capped() { - let path = |w: usize| format!(r#""#); - let paths: String = (1..=40).map(|i| path(10 * i)).collect(); - let x = format!( - r#"{paths}{}"#, - path(10) - ); - let d = parse(x.as_bytes()).unwrap(); - let (out, dropped) = read_cust_geom_counting(&d.root, 1.0, 1.0); - assert_eq!(out.len(), MAX_SPACES + 1, "16 spaces plus the repeat of the first"); - assert_eq!(dropped, (40 - MAX_SPACES, 0), "the paths of later spaces are counted, to be warned about"); - assert!(out[0].d.starts_with("M 5 1"), "{}", out[0].d); - assert!(out[MAX_SPACES].d.starts_with("M 5 1"), "{}", out[MAX_SPACES].d); - } - - #[test] - fn guide_name_bytes_across_spaces_are_budgeted() { - let name = "n".repeat(3 << 20); - let path = |w: usize| format!(r#""#); - let x = format!( - r#"{}{}{}"#, - path(10), - path(20), - path(10) - ); - let d = parse(x.as_bytes()).unwrap(); - let (out, dropped) = read_cust_geom_counting(&d.root, 1.0, 1.0); - assert_eq!(out.len(), 2, "the second 3 MiB space is over budget and left out; the first space's repeat stays"); - assert_eq!(dropped, (0, 1), "the path left out is counted, to be warned about"); - } - - #[test] - fn guide_free_geometries_are_not_capped_by_space() { - let paths: String = (1..=40).map(|i| format!(r#""#, 10 * i)).collect(); - let x = format!(r#"{paths}"#); - let d = parse(x.as_bytes()).unwrap(); - assert_eq!(read_cust_geom(&d.root, 1.0, 1.0).len(), 40); - } - - #[test] - fn write_then_read_path() { - let p = CustomPath { w: 100.0, h: 50.0, d: "M 0 0 L 100 0 C 100 10 90 50 50 50 Q 0 50 0 0 Z".into(), fill: FillMode::Norm, stroke: true }; - let mut w = W::frag(); - write_cust_geom(&mut w, std::slice::from_ref(&p)); - let d = parse(w.s.as_bytes()).unwrap(); - let back = read_cust_geom(&d.root, 1.0, 1.0); - assert_eq!(back.len(), 1); - // Scaled by 1000 (100 → 100000). - assert_eq!(back[0].w, 100_000.0); - assert_eq!(back[0].d, "M 0 0 L 100000 0 C 100000 10000 90000 50000 50000 50000 Q 0 50000 0 0 Z"); - } - - #[test] - fn parse_path_uppercase_exponent() { - assert_eq!(parse_path("M 1E-5 2 L 3 4"), vec![('M', vec![1e-5, 2.0]), ('L', vec![3.0, 4.0])]); - assert_eq!(parse_path("M 1.5E3 2"), vec![('M', vec![1500.0, 2.0])]); - assert_eq!(parse_path("M 1e-5 2"), vec![('M', vec![1e-5, 2.0])]); - // An 'E' right after a number with no exponent digits is the end command. - assert_eq!(parse_path("M 0 0E"), vec![('M', vec![0.0, 0.0]), ('E', vec![])]); - } - - #[test] - fn parse_path_tokens() { - let v = parse_path("M0,0 L10-5 Z"); - assert_eq!(v.len(), 3); - assert_eq!(v[1], ('L', vec![10.0, -5.0])); - assert!(parse_path("garbage ### C 1").is_empty() || parse_path("garbage").is_empty()); - } -} - -#[cfg(test)] -mod shared_path_tests { - use super::parse_path; - - #[test] - fn shared_path_tokens_preserve_exponents_repeats_and_dropped_tails() { - assert_eq!( - parse_path("M1E2 -3E-1 4 5 L6-7 Q8 9 10 11 Z"), - vec![('M', vec![100.0, -0.3]), ('L', vec![4.0, 5.0]), ('L', vec![6.0, -7.0]), ('Q', vec![8.0, 9.0, 10.0, 11.0]), ('Z', vec![]),] - ); - assert_eq!(parse_path("M0 0 L1"), vec![('M', vec![0.0, 0.0])]); - assert_eq!(parse_path("MNaN 0 1 2"), vec![('M', vec![0.0, 1.0])]); - } -} diff --git a/crates/pptx/src/dgm.rs b/crates/pptx/src/dgm.rs deleted file mode 100644 index 70cb89cf2..000000000 --- a/crates/pptx/src/dgm.rs +++ /dev/null @@ -1,910 +0,0 @@ -//! SmartArt (DrawingML diagrams): the outline ⇄ the data model, and the layout, quick style and -//! colour definitions DeckCraft writes for its own layouts. -//! -//! A diagram's data part holds its points (`dgm:pt`: the document, one per node, and the -//! transitions PowerPoint pairs with each link) and its links (`dgm:cxn` of type `parOf`, parent → -//! child, ordered by `srcOrd`). The outline is that tree flattened depth first. - -use std::collections::HashMap; - -use deckcraft_model::{Diagram, DiagramNode}; - -use crate::xml::{A, El, W}; - -pub const NS_DGM: &str = "http://schemas.openxmlformats.org/drawingml/2006/diagram"; -pub const NS_DSP: &str = "http://schemas.microsoft.com/office/drawing/2008/diagram"; -pub const CT_DATA: &str = "application/vnd.openxmlformats-officedocument.drawingml.diagramData+xml"; -pub const CT_LAYOUT: &str = "application/vnd.openxmlformats-officedocument.drawingml.diagramLayout+xml"; -pub const CT_STYLE: &str = "application/vnd.openxmlformats-officedocument.drawingml.diagramStyle+xml"; -pub const CT_COLORS: &str = "application/vnd.openxmlformats-officedocument.drawingml.diagramColors+xml"; -pub const CT_DRAWING: &str = "application/vnd.ms-office.drawingml.diagramDrawing+xml"; -pub const RT_DRAWING: &str = "http://schemas.microsoft.com/office/2007/relationships/diagramDrawing"; -const QS_BASE: &str = "urn:microsoft.com/office/officeart/2005/8/quickstyle/"; -const CS_BASE: &str = "urn:microsoft.com/office/officeart/2005/8/colors/"; - -/// PowerPoint's quick style for a SmartArt Style. -pub fn qs_id(style: &str) -> String { - let s = match style { - "subtle" => "simple3", - "intense" => "simple5", - "outline" => "simple4", - "polished" => "3d1", - "inset" => "3d2", - "cartoon" => "3d3", - "powder" => "3d4", - "brick" => "3d5", - _ => "simple1", - }; - format!("{QS_BASE}{s}") -} - -/// The SmartArt Style closest to a quick style id. -pub fn style_for(qs: &str) -> &'static str { - match qs.rsplit('/').next().unwrap_or("") { - "simple1" | "" => "", - "simple4" => "outline", - "3d1" => "polished", - "3d2" => "inset", - "3d3" => "cartoon", - "3d4" => "powder", - "3d5" => "brick", - "simple2" | "simple3" => "subtle", - _ => "intense", - } -} - -/// PowerPoint's colour definition for Change Colors. -pub fn cs_id(colors: &str) -> String { - if let Some(a @ 2..=5) = colors.strip_prefix("range").and_then(|r| r.get(..1)).and_then(|n| n.parse::().ok()) { - return format!("{CS_BASE}colorful{a}"); - } - let grad = colors.ends_with("Grad"); - match colors.strip_prefix("accent").and_then(|r| r.get(..1)).and_then(|n| n.parse::().ok()) { - Some(n @ 1..=6) => format!("{CS_BASE}accent{n}_{}", if grad { 3 } else { 2 }), - _ => format!("{CS_BASE}colorful1"), - } -} - -/// The accents a Change Colors choice fills shapes with, in turn. -fn fill_accents(colors: &str) -> Vec { - if let Some(a @ 2..=5) = colors.strip_prefix("range").and_then(|r| r.get(..1)).and_then(|n| n.parse::().ok()) { - return vec![format!("accent{a}"), format!("accent{}", a + 1)]; - } - match colors.strip_prefix("accent").and_then(|r| r.get(..1)).and_then(|n| n.parse::().ok()) { - Some(n @ 1..=6) => vec![format!("accent{n}")], - _ => (1..=6).map(|k| format!("accent{k}")).collect(), - } -} - -/// Change Colors from a colour definition id: `accentN_…` keeps accent N, anything else is colourful. -pub fn colors_for(cs: &str) -> String { - let last = cs.rsplit('/').next().unwrap_or(""); - if let Some(a @ 2..=5) = last.strip_prefix("colorful").and_then(|n| n.parse::().ok()) { - return format!("range{a}{}", a + 1); - } - let mut parts = last.strip_prefix("accent").unwrap_or("").split('_'); - match (parts.next().and_then(|n| n.parse::().ok()), parts.next()) { - (Some(n @ 1..=6), Some("3" | "4" | "5")) => format!("accent{n}Grad"), - (Some(n @ 1..=6), _) => format!("accent{n}"), - _ => String::new(), - } -} -/// Most nodes read from one diagram. -const MAX_NODES: usize = 2000; - -/// PowerPoint's built-in layout DeckCraft's layout `kind` is written as. -pub fn layout_id(kind: &str) -> &'static str { - match kind { - "blockList" => "urn:microsoft.com/office/officeart/2005/8/layout/default", - "hBulletList" => "urn:microsoft.com/office/officeart/2005/8/layout/hList1", - "process" => "urn:microsoft.com/office/officeart/2005/8/layout/process1", - "chevron" => "urn:microsoft.com/office/officeart/2005/8/layout/chevron1", - "verticalProcess" => "urn:microsoft.com/office/officeart/2005/8/layout/process2", - "stepUp" => "urn:microsoft.com/office/officeart/2009/3/layout/StepUpProcess", - "cycle" => "urn:microsoft.com/office/officeart/2005/8/layout/cycle2", - "blockCycle" => "urn:microsoft.com/office/officeart/2005/8/layout/cycle5", - "radial" => "urn:microsoft.com/office/officeart/2005/8/layout/radial1", - "hierarchy" => "urn:microsoft.com/office/officeart/2005/8/layout/hierarchy1", - "pyramid" => "urn:microsoft.com/office/officeart/2005/8/layout/pyramid1", - "invertedPyramid" => "urn:microsoft.com/office/officeart/2005/8/layout/pyramid3", - "matrix" => "urn:microsoft.com/office/officeart/2005/8/layout/matrix3", - "titledMatrix" => "urn:microsoft.com/office/officeart/2005/8/layout/matrix1", - "pictureList" => "urn:microsoft.com/office/officeart/2005/8/layout/vList4", - "pictureCaption" => "urn:microsoft.com/office/officeart/2005/8/layout/pList1", - "pictureProcess" => "urn:microsoft.com/office/officeart/2005/8/layout/hProcess10", - "pictureHList" => "urn:microsoft.com/office/officeart/2005/8/layout/pList2", - "timeline" => "urn:microsoft.com/office/officeart/2005/8/layout/hProcess11", - "venn" => "urn:microsoft.com/office/officeart/2005/8/layout/venn1", - "target" => "urn:microsoft.com/office/officeart/2005/8/layout/target1", - "textCycle" => "urn:microsoft.com/office/officeart/2005/8/layout/cycle1", - "continuousCycle" => "urn:microsoft.com/office/officeart/2005/8/layout/cycle3", - "horizontalHierarchy" => "urn:microsoft.com/office/officeart/2005/8/layout/hierarchy2", - "gridMatrix" => "urn:microsoft.com/office/officeart/2005/8/layout/matrix2", - "gear" => "urn:microsoft.com/office/officeart/2005/8/layout/gear1", - "funnel" => "urn:microsoft.com/office/officeart/2005/8/layout/funnel1", - "segmentedCycle" => "urn:microsoft.com/office/officeart/2005/8/layout/cycle8", - "multidirectionalCycle" => "urn:microsoft.com/office/officeart/2005/8/layout/cycle7", - "orgChart" => "urn:microsoft.com/office/officeart/2005/8/layout/orgChart1", - "halfCircleOrgChart" => "urn:microsoft.com/office/officeart/2008/layout/HalfCircleOrganizationChart", - "nameTitleOrgChart" => "urn:microsoft.com/office/officeart/2008/layout/NameandTitleOrganizationalChart", - "verticalBoxList" => "urn:microsoft.com/office/officeart/2005/8/layout/list1", - "trapezoidList" => "urn:microsoft.com/office/officeart/2005/8/layout/hList6", - "tableList" => "urn:microsoft.com/office/officeart/2005/8/layout/hList3", - "accentProcess" => "urn:microsoft.com/office/officeart/2005/8/layout/process3", - "continuousBlockProcess" => "urn:microsoft.com/office/officeart/2005/8/layout/hProcess9", - "bendingProcess" => "urn:microsoft.com/office/officeart/2005/8/layout/process5", - "linearVenn" => "urn:microsoft.com/office/officeart/2005/8/layout/venn3", - "stackedVenn" => "urn:microsoft.com/office/officeart/2005/8/layout/venn2", - "nestedTarget" => "urn:microsoft.com/office/officeart/2005/8/layout/target2", - "cycleMatrix" => "urn:microsoft.com/office/officeart/2005/8/layout/cycle4", - "segmentedPyramid" => "urn:microsoft.com/office/officeart/2005/8/layout/pyramid4", - "pie" => "urn:microsoft.com/office/officeart/2005/8/layout/chart3", - _ => "urn:microsoft.com/office/officeart/2005/8/layout/vList2", - } -} - -/// The DeckCraft layout closest to a PowerPoint layout (by its id and category). -pub fn kind_for(layout_id: &str, category: &str) -> &'static str { - let last = layout_id.rsplit('/').next().unwrap_or("").to_ascii_lowercase(); - // DeckCraft before Picture Accent Process got its own id wrote it as pList2 (Horizontal - // Picture List) with its own layout part in the process category; PowerPoint's pList2 is a list. - if last == "plist2" && category.eq_ignore_ascii_case("process") { - return "pictureProcess"; - } - // Exact ids first: the layouts DeckCraft writes, and their closest siblings. - for k in [ - "blockList", - "hBulletList", - "process", - "chevron", - "verticalProcess", - "stepUp", - "cycle", - "blockCycle", - "radial", - "hierarchy", - "pyramid", - "invertedPyramid", - "matrix", - "titledMatrix", - "pictureList", - "pictureCaption", - "pictureProcess", - "pictureHList", - "timeline", - "venn", - "target", - "textCycle", - "continuousCycle", - "horizontalHierarchy", - "gridMatrix", - "gear", - "funnel", - "segmentedCycle", - "multidirectionalCycle", - "orgChart", - "halfCircleOrgChart", - "nameTitleOrgChart", - "verticalBoxList", - "trapezoidList", - "tableList", - "accentProcess", - "continuousBlockProcess", - "bendingProcess", - "linearVenn", - "stackedVenn", - "nestedTarget", - "cycleMatrix", - "segmentedPyramid", - "pie", - "list", - ] { - if layout_id == layout_id_of(k) { - return k; - } - } - let s = format!("{last} {}", category.to_ascii_lowercase()); - if s.contains("gear") { - "gear" - } else if s.contains("funnel") { - "funnel" - } else if s.contains("venn") { - "venn" - } else if s.contains("target") { - "target" - } else if s.contains("timeline") { - "timeline" - } else if s.contains("nameandtitle") { - "nameTitleOrgChart" - } else if s.contains("orgchart") || s.contains("organizationchart") || s.contains("organizationalchart") { - "orgChart" - } else if s.contains("hierarchy") { - "hierarchy" - } else if s.contains("radial") { - "radial" - } else if s.contains("cycle") { - "cycle" - } else if s.contains("pyramid") { - "pyramid" - } else if s.contains("matrix") { - "matrix" - } else if s.contains("chevron") { - "chevron" - } else if s.contains("process") || s.contains("arrow") { - "process" - } else if last == "default" { - "blockList" - } else if last.starts_with("hlist") { - "hBulletList" - } else { - "list" - } -} - -fn layout_id_of(kind: &str) -> &'static str { - layout_id(kind) -} - -fn category(kind: &str) -> &'static str { - match kind { - "process" - | "chevron" - | "verticalProcess" - | "stepUp" - | "pictureProcess" - | "timeline" - | "gear" - | "funnel" - | "accentProcess" - | "continuousBlockProcess" - | "bendingProcess" => "process", - "venn" | "target" | "linearVenn" | "stackedVenn" | "nestedTarget" => "relationship", - "cycle" | "blockCycle" | "radial" | "textCycle" | "continuousCycle" | "segmentedCycle" | "multidirectionalCycle" | "cycleMatrix" | "pie" => { - "cycle" - } - "hierarchy" | "horizontalHierarchy" | "orgChart" | "halfCircleOrgChart" | "nameTitleOrgChart" => "hierarchy", - "pyramid" | "invertedPyramid" | "segmentedPyramid" => "pyramid", - "matrix" | "titledMatrix" | "gridMatrix" => "matrix", - _ => "list", - } -} - -/// A model id, stable for a given diagram (`seed`) and point number. -fn guid(seed: u32, n: usize) -> String { - format!("{{{seed:08X}-D1A6-4C0A-9E5B-{n:012X}}}") -} - -fn text(w: &mut W, t: &str) { - w.open0("dgm:t"); - w.empty0("a:bodyPr"); - w.empty0("a:lstStyle"); - w.open0("a:p"); - if t.is_empty() { - w.empty("a:endParaRPr", A::new().a("lang", "en-US")); - } else { - w.open0("a:r"); - w.empty("a:rPr", A::new().a("lang", "en-US")); - w.elt("a:t", t); - w.close("a:r"); - } - w.close("a:p"); - w.close("dgm:t"); -} - -/// `ppt/diagrams/dataN.xml` for the outline. `drawing_rel` is the slide's relationship id of the -/// cached drawing; `pics` the data part's relationship ids of node pictures, by node index. -pub fn data_xml(d: &Diagram, seed: u32, drawing_rel: &str, pics: &[(usize, String)]) -> Vec { - let lo = if d.layout_id.is_empty() { layout_id(&d.kind).to_string() } else { d.layout_id.clone() }; - let mut w = W::new(); - w.open("dgm:dataModel", A::new().a("xmlns:dgm", NS_DGM).a("xmlns:a", crate::opc::NS_A).a("xmlns:r", crate::opc::NS_R)); - w.open0("dgm:ptLst"); - let doc = guid(seed, 0); - w.open("dgm:pt", A::new().a("modelId", &doc).a("type", "doc")); - w.empty( - "dgm:prSet", - A::new() - .a("loTypeId", &lo) - .a("loCatId", category(&d.kind)) - .a("qsTypeId", qs_id(&d.style)) - .a("qsCatId", "simple") - .a("csTypeId", cs_id(&d.colors)) - .a("csCatId", if d.colors.starts_with("accent") { d.colors.as_str() } else { "colorful" }) - .a("phldr", "1"), - ); - w.empty0("dgm:spPr"); - text(&mut w, ""); - w.close("dgm:pt"); - // Node k: model id 1 + 3k; its link's parent and sibling transitions 2 + 3k and 3 + 3k. - let node = |k: usize| guid(seed, 1 + 3 * k); - for (k, n) in d.nodes.iter().enumerate() { - let mut a = A::new().a("modelId", node(k)); - if n.assistant { - a = a.a("type", "asst"); - } - w.open("dgm:pt", a); - w.empty("dgm:prSet", A::new().a("phldrT", "[Text]")); - w.empty0("dgm:spPr"); - text(&mut w, &n.text); - w.close("dgm:pt"); - let cxn = guid(seed, 0x10_0000 + k); - for (i, ty) in [(2, "parTrans"), (3, "sibTrans")] { - w.open("dgm:pt", A::new().a("modelId", guid(seed, i + 3 * k)).a("type", ty).a("cxnId", &cxn)); - w.empty0("dgm:prSet"); - w.empty0("dgm:spPr"); - text(&mut w, ""); - w.close("dgm:pt"); - } - } - // A node's picture sits on the presentation point of its picture placeholder, as PowerPoint - // stores it (`presAssocID` names the node, the blip is a relationship of the data part). - // Name and Title: a node's title is the text of its title box's presentation point. - for (k, n) in d.nodes.iter().enumerate() { - if n.title.is_empty() { - continue; - } - w.open("dgm:pt", A::new().a("modelId", guid(seed, 0x30_0000 + k)).a("type", "pres")); - w.empty("dgm:prSet", A::new().a("presAssocID", node(k)).a("presName", "titleText1").a("presStyleLbl", "fgAcc1").a("custT", "1")); - w.empty0("dgm:spPr"); - text(&mut w, &n.title); - w.close("dgm:pt"); - } - for (k, rid) in pics { - if *k >= d.nodes.len() { - continue; - } - w.open("dgm:pt", A::new().a("modelId", guid(seed, 0x20_0000 + k)).a("type", "pres")); - w.empty("dgm:prSet", A::new().a("presAssocID", node(*k)).a("presName", "Image").a("presStyleLbl", "fgImgPlace1")); - w.open0("dgm:spPr"); - w.open0("a:blipFill"); - w.empty("a:blip", A::new().a("r:embed", rid.as_str())); - w.open0("a:stretch"); - w.empty0("a:fillRect"); - w.close("a:stretch"); - w.close("a:blipFill"); - w.close("dgm:spPr"); - w.close("dgm:pt"); - } - w.close("dgm:ptLst"); - w.open0("dgm:cxnLst"); - let mut stack: Vec<(u8, String)> = vec![]; - let mut ords: HashMap = HashMap::new(); - for (k, n) in d.nodes.iter().enumerate() { - while stack.last().is_some_and(|(l, _)| *l >= n.level) { - stack.pop(); - } - let parent = stack.last().map(|(_, id)| id.clone()).unwrap_or_else(|| doc.clone()); - let ord = ords.entry(parent.clone()).or_insert(0); - w.empty( - "dgm:cxn", - A::new() - .a("modelId", guid(seed, 0x10_0000 + k)) - .a("srcId", &parent) - .a("destId", node(k)) - .a("srcOrd", *ord) - .a("destOrd", 0) - .a("parTransId", guid(seed, 2 + 3 * k)) - .a("sibTransId", guid(seed, 3 + 3 * k)), - ); - *ord += 1; - stack.push((n.level, node(k))); - } - w.close("dgm:cxnLst"); - w.empty0("dgm:bg"); - w.empty0("dgm:whole"); - w.open0("dgm:extLst"); - w.open("a:ext", A::new().a("uri", "http://schemas.microsoft.com/office/drawing/2008/diagram")); - w.empty( - "dsp:dataModelExt", - A::new().a("xmlns:dsp", NS_DSP).a("relId", drawing_rel).a("minVer", "http://schemas.openxmlformats.org/drawingml/2006/diagram"), - ); - w.close("a:ext"); - w.close("dgm:extLst"); - w.close("dgm:dataModel"); - w.finish() -} - -/// The outline of a data part: the `parOf` tree under the document point, depth first, or the data points in `ptLst` order when no `parOf` connections exist. -pub fn outline(data: &El) -> Vec { - outline_ids(data).into_iter().map(|(_, n)| n).collect() -} - -/// The relationship ids (of the data part) of node pictures, by node index in [`outline`]: the -/// blip fill of a presentation point associated with the node. -pub fn node_pictures(data: &El) -> Vec<(usize, String)> { - let ids: HashMap = outline_ids(data).into_iter().enumerate().map(|(k, (id, _))| (id, k)).collect(); - let Some(pts) = data.child("ptLst") else { return vec![] }; - let mut out: Vec<(usize, String)> = vec![]; - for pt in pts.children_named("pt").take(MAX_NODES * 8) { - if pt.attr("type") != Some("pres") { - continue; - } - let Some(k) = pt.child("prSet").and_then(|p| p.attr("presAssocID")).and_then(|a| ids.get(a)) else { continue }; - let Some(rid) = pt.child("spPr").and_then(|s| s.child("blipFill")).and_then(|b| b.child("blip")).and_then(|b| b.attr("r:embed")) else { - continue; - }; - if !out.iter().any(|(j, _)| j == k) { - out.push((*k, rid.to_string())); - } - } - out -} - -/// Extracts diagram outline `(modelId, DiagramNode)` pairs in tree order from a `dgm:dataModel` element. -fn outline_ids(data: &El) -> Vec<(String, DiagramNode)> { - let Some(pts) = data.child("ptLst") else { return vec![] }; - let mut texts: HashMap<&str, String> = HashMap::new(); - let mut assistants: std::collections::HashSet<&str> = std::collections::HashSet::new(); - let mut titles: HashMap<&str, String> = HashMap::new(); - let mut pt_order: Vec<&str> = Vec::new(); - let mut doc: Option<&str> = None; - for pt in pts.children_named("pt").take(MAX_NODES * 4) { - let Some(id) = pt.attr("modelId") else { continue }; - match pt.attr("type").unwrap_or("node") { - "doc" => doc = doc.or(Some(id)), - ty @ ("node" | "asst") => { - let t = pt.child("t").map(paragraphs).unwrap_or_default(); - texts.insert(id, t); - pt_order.push(id); - if ty == "asst" { - assistants.insert(id); - } - } - "pres" => { - // Name and Title: the title box's own text, on its presentation point. - let pr = pt.child("prSet"); - if pr.and_then(|p| p.attr("presName")).is_some_and(|n| n.starts_with("titleText")) - && let Some(node) = pr.and_then(|p| p.attr("presAssocID")) - && let Some(t) = pt.child("t").map(paragraphs).filter(|t| !t.is_empty()) - { - titles.insert(node, t); - } - } - _ => {} - } - } - let mut kids: HashMap<&str, Vec<(i64, &str)>> = HashMap::new(); - if let Some(cx) = data.child("cxnLst") { - for c in cx.children_named("cxn").take(MAX_NODES * 4) { - if c.attr("type").unwrap_or("parOf") != "parOf" { - continue; - } - let (Some(src), Some(dst)) = (c.attr("srcId"), c.attr("destId")) else { continue }; - if texts.contains_key(dst) { - kids.entry(src).or_default().push((c.i64("srcOrd").unwrap_or(0), dst)); - } - } - } - for v in kids.values_mut() { - v.sort_by_key(|(o, _)| *o); - } - let mut out = vec![]; - let mut seen = std::collections::HashSet::new(); - // Depth first, iteratively; a node reached twice (a cycle in a hostile file) is skipped. - let mut stack: Vec<(&str, u8)> = doc.and_then(|d| kids.get(d)).map(|v| v.iter().rev().map(|(_, id)| (*id, 0u8)).collect()).unwrap_or_default(); - while let Some((id, level)) = stack.pop() { - if out.len() >= MAX_NODES || !seen.insert(id) { - continue; - } - out.push(( - id.to_string(), - DiagramNode { - text: texts.get(id).cloned().unwrap_or_default(), - level: level.min(8), - picture: None, - assistant: assistants.contains(id), - title: titles.get(id).cloned().unwrap_or_default(), - }, - )); - if let Some(v) = kids.get(id) { - stack.extend(v.iter().rev().map(|(_, c)| (*c, level.saturating_add(1)))); - } - } - if out.is_empty() && kids.is_empty() { - for id in pt_order { - if out.len() >= MAX_NODES || !seen.insert(id) { - continue; - } - out.push(( - id.to_string(), - DiagramNode { - text: texts.get(id).cloned().unwrap_or_default(), - level: 0, - picture: None, - assistant: assistants.contains(id), - title: titles.get(id).cloned().unwrap_or_default(), - }, - )); - } - } - out -} - -/// A text body's paragraphs joined by spaces. -fn paragraphs(t: &El) -> String { - t.children_named("p") - .map(|p| { - let mut v = vec![]; - p.find_all("t", &mut v); - v.iter().map(|e| e.text()).collect::() - }) - .filter(|s| !s.trim().is_empty()) - .collect::>() - .join(" ") -} - -/// The layout algorithm and node shape of a DeckCraft layout. -fn alg(kind: &str) -> (&'static str, Vec<(&'static str, &'static str)>, &'static str) { - match kind { - "process" | "stepUp" | "pictureProcess" | "pictureCaption" | "pictureHList" | "timeline" => { - ("lin", vec![("linDir", "fromL"), ("nodeVertAlign", "mid")], "roundRect") - } - "chevron" => ("lin", vec![("linDir", "fromL"), ("nodeVertAlign", "mid")], "chevron"), - "verticalProcess" => ("lin", vec![("linDir", "fromT"), ("nodeHorzAlign", "ctr")], "roundRect"), - "cycle" - | "radial" - | "venn" - | "target" - | "textCycle" - | "continuousCycle" - | "gear" - | "segmentedCycle" - | "multidirectionalCycle" - | "cycleMatrix" - | "pie" => ("cycle", vec![("stAng", "0"), ("spanAng", "360")], "ellipse"), - "blockCycle" => ("cycle", vec![("stAng", "0"), ("spanAng", "360")], "roundRect"), - "pyramid" | "invertedPyramid" | "segmentedPyramid" => { - ("pyra", vec![("linDir", if kind == "pyramid" { "fromT" } else { "fromB" }), ("txDir", "fromT"), ("pyraAcctPos", "bef")], "trapezoid") - } - "matrix" | "titledMatrix" | "gridMatrix" | "blockList" => ( - "snake", - vec![("grDir", "tL"), ("flowDir", "row"), ("contDir", "sameDir"), ("off", "ctr")], - if kind == "blockList" { "rect" } else { "roundRect" }, - ), - "hBulletList" => ("lin", vec![("linDir", "fromL"), ("nodeVertAlign", "t")], "roundRect"), - _ => ("lin", vec![("linDir", "fromT"), ("vertAlign", "mid")], "roundRect"), - } -} - -fn node_layout(w: &mut W, shape: &str, bullets: bool) { - w.open("dgm:layoutNode", A::new().a("name", "node")); - w.open0("dgm:varLst"); - w.empty("dgm:bulletEnabled", A::new().a("val", if bullets { "1" } else { "0" })); - w.close("dgm:varLst"); - w.empty("dgm:alg", A::new().a("type", "tx")); - w.open("dgm:shape", A::new().a("type", shape).a("r:blip", "")); - w.empty0("dgm:adjLst"); - w.close("dgm:shape"); - w.empty("dgm:presOf", A::new().a("axis", if bullets { "desOrSelf" } else { "self" }).a("ptType", "node")); - w.open0("dgm:constrLst"); - for side in ["tMarg", "bMarg", "lMarg", "rMarg"] { - w.empty("dgm:constr", A::new().a("type", side).a("refType", "primFontSz").a("fact", "0.3")); - } - w.close("dgm:constrLst"); - w.open0("dgm:ruleLst"); - w.empty("dgm:rule", A::new().a("type", "primFontSz").a("val", "5").a("fact", "NaN").a("max", "NaN")); - w.close("dgm:ruleLst"); - w.close("dgm:layoutNode"); -} - -fn space(w: &mut W) { - w.open("dgm:forEach", A::new().a("name", "sibling").a("axis", "followSib").a("ptType", "sibTrans").a("cnt", "1")); - w.open("dgm:layoutNode", A::new().a("name", "space")); - w.empty("dgm:alg", A::new().a("type", "sp")); - w.open("dgm:shape", A::new().a("r:blip", "")); - w.empty0("dgm:adjLst"); - w.close("dgm:shape"); - w.empty0("dgm:presOf"); - w.empty0("dgm:constrLst"); - w.empty0("dgm:ruleLst"); - w.close("dgm:layoutNode"); - w.close("dgm:forEach"); -} - -/// `ppt/diagrams/layoutN.xml`: a layout definition for DeckCraft's layout `kind`, under the id of -/// the closest built-in PowerPoint layout. -pub fn layout_xml(kind: &str) -> Vec { - let mut w = W::new(); - w.open( - "dgm:layoutDef", - A::new().a("xmlns:dgm", NS_DGM).a("xmlns:a", crate::opc::NS_A).a("xmlns:r", crate::opc::NS_R).a("uniqueId", layout_id(kind)), - ); - w.empty("dgm:title", A::new().a("val", "")); - w.empty("dgm:desc", A::new().a("val", "")); - w.open0("dgm:catLst"); - w.empty("dgm:cat", A::new().a("type", category(kind)).a("pri", "1000")); - w.close("dgm:catLst"); - w.open("dgm:layoutNode", A::new().a("name", "diagram")); - w.open0("dgm:varLst"); - w.empty0("dgm:dir"); - w.empty("dgm:resizeHandles", A::new().a("val", "exact")); - w.close("dgm:varLst"); - if matches!(kind, "hierarchy" | "horizontalHierarchy" | "orgChart" | "halfCircleOrgChart" | "nameTitleOrgChart") { - // Each node over the row of its children, recursively. - w.empty("dgm:alg", A::new().a("type", "hierChild")); - w.open("dgm:shape", A::new().a("r:blip", "")); - w.empty0("dgm:adjLst"); - w.close("dgm:shape"); - w.empty0("dgm:presOf"); - w.empty0("dgm:constrLst"); - w.empty0("dgm:ruleLst"); - w.open("dgm:forEach", A::new().a("name", "level").a("axis", "ch").a("ptType", "node")); - w.open("dgm:layoutNode", A::new().a("name", "hierRoot")); - w.empty("dgm:alg", A::new().a("type", "hierRoot")); - w.open("dgm:shape", A::new().a("r:blip", "")); - w.empty0("dgm:adjLst"); - w.close("dgm:shape"); - w.empty0("dgm:presOf"); - w.empty0("dgm:constrLst"); - w.empty0("dgm:ruleLst"); - node_layout(&mut w, "roundRect", false); - w.open("dgm:layoutNode", A::new().a("name", "hierChild")); - w.empty("dgm:alg", A::new().a("type", "hierChild")); - w.open("dgm:shape", A::new().a("r:blip", "")); - w.empty0("dgm:adjLst"); - w.close("dgm:shape"); - w.empty0("dgm:presOf"); - w.empty0("dgm:constrLst"); - w.empty0("dgm:ruleLst"); - w.empty("dgm:forEach", A::new().a("name", "repeat").a("ref", "level")); - w.close("dgm:layoutNode"); - w.close("dgm:layoutNode"); - w.close("dgm:forEach"); - } else { - let (ty, params, shape) = alg(kind); - w.open("dgm:alg", A::new().a("type", ty)); - for (k, v) in params { - w.empty("dgm:param", A::new().a("type", k).a("val", v)); - } - w.close("dgm:alg"); - w.open("dgm:shape", A::new().a("r:blip", "")); - w.empty0("dgm:adjLst"); - w.close("dgm:shape"); - w.empty0("dgm:presOf"); - w.open0("dgm:constrLst"); - w.empty("dgm:constr", A::new().a("type", "w").a("for", "ch").a("forName", "node").a("refType", "w")); - w.empty( - "dgm:constr", - A::new().a("type", "h").a("for", "ch").a("forName", "node").a("refType", "w").a("refFor", "ch").a("refForName", "node").a("fact", "0.6"), - ); - w.empty( - "dgm:constr", - A::new().a("type", "w").a("for", "ch").a("forName", "space").a("refType", "w").a("refFor", "ch").a("refForName", "node").a("fact", "0.1"), - ); - w.empty("dgm:constr", A::new().a("type", "primFontSz").a("for", "ch").a("forName", "node").a("op", "equ").a("val", "65")); - w.close("dgm:constrLst"); - w.empty0("dgm:ruleLst"); - w.open("dgm:forEach", A::new().a("name", "nodes").a("axis", "ch").a("ptType", "node")); - node_layout(&mut w, shape, true); - if !matches!(kind, "cycle" | "blockCycle" | "radial") { - space(&mut w); - } - w.close("dgm:forEach"); - } - w.close("dgm:layoutNode"); - w.close("dgm:layoutDef"); - w.finish() -} - -/// The top bevel (preset, width in EMU) of a 3-D SmartArt Style. -fn bevel(style: &str) -> Option<(&'static str, i64)> { - Some(match style { - "polished" => ("circle", 76200), - "inset" => ("relaxedInset", 63500), - "cartoon" => ("softRound", 50800), - "powder" => ("convex", 101600), - "brick" => ("slope", 50800), - _ => return None, - }) -} - -/// `ppt/diagrams/quickStyleN.xml`: flat shapes drawn from the theme's first styles. -pub fn style_xml(style: &str) -> Vec { - // Brick Scene looks at the diagram from above and to the side. - let camera = if style == "brick" { "isometricOffAxis2Top" } else { "orthographicFront" }; - let mut w = W::new(); - w.open("dgm:styleDef", A::new().a("xmlns:dgm", NS_DGM).a("xmlns:a", crate::opc::NS_A).a("uniqueId", qs_id(style))); - w.empty("dgm:title", A::new().a("val", "")); - w.empty("dgm:desc", A::new().a("val", "")); - w.open0("dgm:catLst"); - w.empty("dgm:cat", A::new().a("type", if bevel(style).is_some() { "3D" } else { "simple" }).a("pri", "10100")); - w.close("dgm:catLst"); - w.open0("dgm:scene3d"); - w.empty("a:camera", A::new().a("prst", camera)); - w.empty("a:lightRig", A::new().a("rig", "threePt").a("dir", "t")); - w.close("dgm:scene3d"); - w.open("dgm:styleLbl", A::new().a("name", "node1")); - w.open0("dgm:scene3d"); - w.empty("a:camera", A::new().a("prst", camera)); - w.empty("a:lightRig", A::new().a("rig", "threePt").a("dir", "t")); - w.close("dgm:scene3d"); - match bevel(style) { - Some((prst, w_emu)) => { - w.open0("dgm:sp3d"); - w.empty("a:bevelT", A::new().a("w", w_emu.to_string()).a("h", (w_emu * 3 / 5).to_string()).a("prst", prst)); - w.close("dgm:sp3d"); - } - None => w.empty0("dgm:sp3d"), - } - w.empty("dgm:txPr", A::new()); - w.open0("dgm:style"); - for (tag, idx) in [("a:lnRef", "2"), ("a:fillRef", "1"), ("a:effectRef", "0")] { - w.open(tag, A::new().a("idx", idx)); - w.empty("a:scrgbClr", A::new().a("r", "0").a("g", "0").a("b", "0")); - w.close(tag); - } - w.open("a:fontRef", A::new().a("idx", "minor")); - w.empty("a:schemeClr", A::new().a("val", "lt1")); - w.close("a:fontRef"); - w.close("dgm:style"); - w.close("dgm:styleLbl"); - w.close("dgm:styleDef"); - w.finish() -} - -/// `ppt/diagrams/colorsN.xml`: accent 1 fills with light text. -pub fn colors_xml(colors: &str) -> Vec { - let mut w = W::new(); - w.open("dgm:colorsDef", A::new().a("xmlns:dgm", NS_DGM).a("xmlns:a", crate::opc::NS_A).a("uniqueId", cs_id(colors))); - w.empty("dgm:title", A::new().a("val", "")); - w.empty("dgm:desc", A::new().a("val", "")); - let accents = fill_accents(colors); - let single = accents.len() == 1; - let cat = if single { accents.first().map(String::as_str).unwrap_or("accent1") } else { "colorful" }; - w.open0("dgm:catLst"); - w.empty("dgm:cat", A::new().a("type", cat).a("pri", "11200")); - w.close("dgm:catLst"); - w.open("dgm:styleLbl", A::new().a("name", "node1")); - if colors.ends_with("Grad") { - // Gradient Range: the accent shaded darker across the shapes. - w.open("dgm:fillClrLst", A::new().a("meth", "repeat")); - for k in 0..4 { - w.open("a:schemeClr", A::new().a("val", cat)); - w.empty("a:lumMod", A::new().a("val", (100_000 - k * 15_000).to_string())); - w.close("a:schemeClr"); - } - w.close("dgm:fillClrLst"); - } else { - w.open("dgm:fillClrLst", A::new().a("meth", "repeat")); - for a in &accents { - w.empty("a:schemeClr", A::new().a("val", a.as_str())); - } - w.close("dgm:fillClrLst"); - } - w.open("dgm:linClrLst", A::new().a("meth", "repeat")); - w.empty("a:schemeClr", A::new().a("val", "lt1")); - w.close("dgm:linClrLst"); - w.empty0("dgm:effectClrLst"); - w.empty0("dgm:txLinClrLst"); - w.empty0("dgm:txFillClrLst"); - w.empty0("dgm:txEffectClrLst"); - w.close("dgm:styleLbl"); - w.close("dgm:colorsDef"); - w.finish() -} - -#[cfg(test)] -mod tests { - use super::*; - - fn nodes(v: &[(&str, u8)]) -> Vec { - v.iter().map(|(t, l)| DiagramNode { text: (*t).into(), level: *l, picture: None, assistant: false, title: String::new() }).collect() - } - - #[test] - fn outline_survives_the_data_model() { - let d = - Diagram { kind: "hierarchy".into(), nodes: nodes(&[("CEO", 0), ("CTO", 1), ("Dev", 2), ("CFO", 1), ("Board", 0)]), ..Default::default() }; - let xml = data_xml(&d, 7, "rId9", &[]); - let doc = crate::xml::parse(&xml).unwrap(); - assert_eq!(outline(&doc.root), d.nodes); - let s = String::from_utf8(xml).unwrap(); - assert!(s.contains("hierarchy1") && s.contains("relId=\"rId9\"")); - for x in [ - layout_xml("hierarchy"), - layout_xml("cycle"), - style_xml("subtle"), - colors_xml(""), - colors_xml("accent3"), - style_xml("polished"), - colors_xml("range23"), - colors_xml("accent6Grad"), - layout_xml("pictureList"), - ] { - assert!(crate::xml::parse(&x).is_ok()); - } - } - - #[test] - fn assistants_survive_the_data_model() { - let mut v = nodes(&[("CEO", 0), ("Aide", 1), ("CTO", 1)]); - v[1].assistant = true; - v[0].title = "Chief Executive".into(); - let d = Diagram { kind: "orgChart".into(), nodes: v, ..Default::default() }; - let xml = data_xml(&d, 5, "rId1", &[]); - assert!(String::from_utf8(xml.clone()).unwrap().contains("type=\"asst\"")); - let doc = crate::xml::parse(&xml).unwrap(); - assert_eq!(outline(&doc.root), d.nodes); - } - - #[test] - fn node_pictures_come_from_presentation_points() { - let d = Diagram { kind: "pictureList".into(), nodes: nodes(&[("A", 0), ("a", 1), ("B", 0)]), ..Default::default() }; - let xml = data_xml(&d, 3, "rId1", &[(2, "rId7".into()), (9, "rId8".into())]); - let doc = crate::xml::parse(&xml).unwrap(); - assert_eq!(node_pictures(&doc.root), vec![(2, "rId7".to_string())]); - } - - #[test] - fn style_and_colour_ids_round_trip() { - for st in ["", "subtle", "intense", "outline", "polished", "inset", "cartoon", "powder", "brick"] { - assert_eq!(style_for(&qs_id(st)), st); - } - for c in ["", "range23", "range56", "accent1", "accent4Grad"] { - assert_eq!(colors_for(&cs_id(c)), c); - } - assert!(String::from_utf8(style_xml("cartoon")).unwrap().contains("bevelT")); - assert!(layout_id("pictureProcess").ends_with("/hProcess10"), "Picture Accent Process"); - assert!(layout_id("pictureHList").ends_with("/pList2"), "Horizontal Picture List"); - // Picture Accent Process as an earlier DeckCraft wrote it (pList2, process category). - assert_eq!(kind_for("urn:microsoft.com/office/officeart/2005/8/layout/pList2", "process"), "pictureProcess"); - assert_eq!(kind_for("urn:microsoft.com/office/officeart/2005/8/layout/pList2", "list"), "pictureHList"); - for k in [ - "pictureList", - "pictureCaption", - "pictureProcess", - "pictureHList", - "timeline", - "venn", - "target", - "textCycle", - "continuousCycle", - "horizontalHierarchy", - "gridMatrix", - "gear", - "funnel", - "segmentedCycle", - "multidirectionalCycle", - "orgChart", - "halfCircleOrgChart", - "cycleMatrix", - "segmentedPyramid", - "pie", - "nameTitleOrgChart", - "verticalBoxList", - "trapezoidList", - "tableList", - "accentProcess", - "continuousBlockProcess", - "bendingProcess", - "linearVenn", - "stackedVenn", - "nestedTarget", - ] { - assert_eq!(kind_for(layout_id(k), ""), k); - } - } - - #[test] - fn hostile_links_are_bounded() { - let xml = br#"A"#; - let doc = crate::xml::parse(xml).unwrap(); - assert_eq!(outline(&doc.root), nodes(&[("A", 0), ("", 1)])); - assert_eq!(kind_for("urn:microsoft.com/office/officeart/2005/8/layout/orgChart1", ""), "orgChart"); - assert_eq!(kind_for("urn:x/layout/NameandTitleOrganizationalChart", ""), "nameTitleOrgChart"); - assert_eq!(kind_for("urn:x/layout/chevron2", "process"), "chevron"); - assert_eq!(kind_for("urn:x/layout/hProcess9", "process"), "process"); - assert_eq!(kind_for("urn:x/layout/default", "list"), "blockList"); - assert_eq!(colors_for(&cs_id("accent4")), "accent4"); - assert_eq!(colors_for(&cs_id("")), ""); - assert_eq!(style_for(&qs_id("outline")), "outline"); - - let unconnected = br#"AlphaBeta"#; - let unconnected_doc = crate::xml::parse(unconnected).unwrap(); - assert_eq!(outline(&unconnected_doc.root), nodes(&[("Alpha", 0), ("Beta", 0)])); - - // When parOf connections exist but no root (type="doc") reaches them, do not flatten the hierarchy to level 0. - let unrooted_hierarchy = br#"ParentChild"#; - let unrooted_doc = crate::xml::parse(unrooted_hierarchy).unwrap(); - assert!(outline(&unrooted_doc.root).is_empty()); - } -} diff --git a/crates/pptx/src/lib.rs b/crates/pptx/src/lib.rs index 9335b4e26..d916f10db 100644 --- a/crates/pptx/src/lib.rs +++ b/crates/pptx/src/lib.rs @@ -1,5 +1,5 @@ -//! PPTX import and export: Office Open XML PresentationML / DrawingML, written from the public -//! ECMA-376 standard. +//! PPTX import and export: Office Open XML PresentationML / DrawingML, delegated to the shared +//! `craft-pptx` crate. //! //! [`import`] reads a package leniently (unknown parts are skipped, malformed parts are logged and //! ignored, every size and depth is bounded) into the DeckCraft model; [`export`] writes a valid @@ -8,28 +8,15 @@ #![forbid(unsafe_code)] mod cfb; -mod custgeom; -mod dgm; -mod maps; -mod opc; -mod png; -pub(crate) mod read; -pub use read::MAX_TAG_BYTES; -mod tables; -mod write; +mod convert; mod xml; +pub use craft_pptx::MAX_TAG_BYTES; /// The bounded XML reader the importer uses, for callers that read kept fragments (a shape's /// 3-D settings) instead of scanning strings. pub use xml::{Doc as XmlDoc, El as XmlEl, parse as parse_xml}; -use deckcraft_model::Presentation; - -/// Extension URI of the PowerPoint 2010 section list in `presentation.xml`. -pub(crate) const SECTION_EXT_URI: &str = "{521415D9-36F7-43E2-AB2F-B90AF26B5E84}"; - -/// Extension URI of the modern-comments anchor in a slide (names the threaded comment part). -pub(crate) const COMMENTS_EXT_URI: &str = "{6950BFC3-D8DA-4A85-94F7-54DA5524770B}"; +use deckcraft_model::{Presentation, Shape, ShapeKind, defaults}; #[derive(Debug, thiserror::Error)] pub enum PptxError { @@ -43,15 +30,50 @@ pub enum PptxError { Xml(String), } +impl From for PptxError { + fn from(e: craft_pptx::Error) -> Self { + match e { + craft_pptx::Error::NotPptx(m) => PptxError::NotPptx(m), + craft_pptx::Error::Unsupported(m) => PptxError::Unsupported(m), + craft_pptx::Error::Write(m) => PptxError::Write(m), + craft_pptx::Error::Xml(m) => PptxError::Xml(m), + } + } +} + +struct DeckDefaults; + +impl craft_pptx::Defaults for DeckDefaults { + fn master(&self, size: deckcraft_geom::Size, after: u32) -> (craft_pptx::Master, u32) { + let (m, last) = defaults::build_master(size, Default::default(), after); + (convert::master_to_craft(&m), last) + } + + fn theme(&self) -> craft_drawingml::theme::Theme { + convert::theme_to_craft(&deckcraft_model::theme::Theme::default()) + } + + fn master_styles(&self) -> (craft_drawingml::text::ListStyle, craft_drawingml::text::ListStyle, craft_drawingml::text::ListStyle) { + // An imported empty master style must stay empty on save; new decks already carry their + // populated master styles in the model. + Default::default() + } + + fn default_text_style(&self) -> craft_drawingml::text::ListStyle { + convert::list_style_to_craft(&defaults::default_text_style()) + } + + fn application(&self) -> &str { + "DeckCraft" + } +} + /// Does this look like an OOXML package (zip with `[Content_Types].xml`)? /// -/// The part is looked up in the zip's central directory, not in the leading bytes: writers may +/// The part is looked up in the archive's central directory, not in the leading bytes: writers may /// store it anywhere in the archive (recent PowerPoint builds put it last, megabytes in). pub fn sniff(bytes: &[u8]) -> bool { - if !bytes.starts_with(b"PK") { - return false; - } - zip::ZipArchive::new(std::io::Cursor::new(bytes)).map(|z| z.index_for_name("[Content_Types].xml").is_some()).unwrap_or(false) + craft_pptx::sniff(bytes) } /// Is this a password-protected presentation (an encrypted package inside a compound file)? @@ -59,81 +81,619 @@ pub fn is_encrypted(bytes: &[u8]) -> bool { cfb::is_encrypted(bytes) } +const MAX_SLIDE_ENTRIES: usize = 10_000; + +/// Checks `ppt/presentation.xml` for > 10,000 slide-list entries (refused instead of truncated) +/// and collects any `sldId` entries whose relationship is missing so `import_checked` / +/// `import_report` report them as lost slides. +fn preflight_slides(bytes: &[u8]) -> Result, PptxError> { + let Ok(mut pkg) = craft_opc::LazyPackage::open(bytes, &craft_pptx::LIMITS) else { + return Ok(vec![]); + }; + let root_rels = pkg.rels("").unwrap_or_default(); + let pres_path = root_rels.first("officeDocument").map(|r| r.target.clone()).unwrap_or_else(|| "ppt/presentation.xml".into()); + let Ok(Some(pres_bytes)) = pkg.read_limited(&pres_path, craft_pptx::MAX_XML_PART as u64) else { + return Ok(vec![]); + }; + let Ok(pres_el) = craft_drawingml::xmlx::parse(&pres_bytes) else { + return Ok(vec![]); + }; + let pres_rels = pkg.rels(&pres_path).unwrap_or_default(); + let mut lost = Vec::new(); + if let Some(list) = pres_el.child(craft_xml::Local("sldIdLst")) { + let mut count = 0usize; + for s in list.children(craft_xml::Local("sldId")) { + count += 1; + if count > MAX_SLIDE_ENTRIES { + return Err(PptxError::Unsupported(format!("presentation has more than {MAX_SLIDE_ENTRIES} slides"))); + } + let rid = s.attr_local("r:id").unwrap_or(""); + if pres_rels.target(rid).is_none() { + let id = s.attr_local("id").and_then(craft_xml::value::to_u32_lossy).unwrap_or(0); + lost.push(format!("slide {id} (missing relationship {rid})")); + } + } + } + Ok(lost) +} + +fn has_unfolded_paragraph_builds(p: &Presentation) -> bool { + p.slides.iter().any(|s| s.animations.windows(2).any(|w| w[0].paragraph.is_some() && w[1].paragraph.is_some() && w[0].shape == w[1].shape)) +} + +#[derive(Default)] +struct SlideTimingInfo { + opt_out: std::collections::HashSet, + offsets: std::collections::HashMap<(u32, u32), u32>, +} + +fn timing_ms(e: &craft_xml::El, name: &str) -> Option { + let v = e.attr_local(name)?.trim(); + if v == "indefinite" { + return None; + } + v.parse::().ok().filter(|n| n.is_finite() && *n >= 0.0).map(|n| n.min(u32::MAX as f64) as u32) +} + +fn collect_timing_offsets(e: &craft_xml::El, offset: u32, out: &mut std::collections::HashMap<(u32, u32), u32>, depth: usize) { + if depth > 64 { + return; + } + for c in e.elements() { + if c.is(craft_xml::Local("cTn")) && c.attr_local("presetClass").is_some() { + if let Some(sp) = c.find(craft_xml::Local("spTgt")) + && let Some(spid) = sp.attr_local("spid").and_then(craft_xml::value::to_u32_lossy) + && let Some(p) = sp + .path(&[craft_xml::Local("txEl"), craft_xml::Local("pRg")]) + .and_then(|r| r.attr_local("st")) + .and_then(craft_xml::value::to_u32_lossy) + { + out.entry((spid, p)).or_insert(offset); + } + continue; + } + let mut next_offset = offset; + if c.is(craft_xml::Local("cTn")) + && let Some(cond) = c.path(&[craft_xml::Local("stCondLst"), craft_xml::Local("cond")]) + { + if cond.attr_local("delay").map(str::trim) == Some("indefinite") { + next_offset = 0; + } else { + next_offset = next_offset.saturating_add(timing_ms(cond, "delay").unwrap_or(0)); + } + } + collect_timing_offsets(c, next_offset, out, depth + 1); + } +} + +fn defers_start(st: &craft_xml::El) -> bool { + let is_auto_begin = |c: &craft_xml::El| { + c.attr_local("evt") == Some("onBegin") + && c.attr_local("delay").map(str::trim) == Some("0") + && c.child(craft_xml::Local("tgtEl")).is_none() + && c.child(craft_xml::Local("tn")).is_none() + && c.child(craft_xml::Local("rtn")).is_none() + }; + let has_on_begin = st.children(craft_xml::Local("cond")).any(is_auto_begin); + st.children(craft_xml::Local("cond")) + .any(|c| (c.attr_local("evt").is_some() && !is_auto_begin(c)) || (!has_on_begin && c.attr_local("delay").map(str::trim) != Some("0"))) +} + +fn is_main_seq_auto(st: &craft_xml::El, main_seq_id: Option) -> bool { + let Some(ms_id) = main_seq_id else { + return false; + }; + let is_indefinite = |d: &craft_xml::El| { + d.attr_local("evt").is_none() + && d.attr_local("delay").map(str::trim) == Some("indefinite") + && d.child(craft_xml::Local("tgtEl")).is_none() + && d.child(craft_xml::Local("tn")).is_none() + && d.child(craft_xml::Local("rtn")).is_none() + }; + let is_main_seq_on_begin = |d: &craft_xml::El| { + d.attr_local("evt") == Some("onBegin") + && d.attr_local("delay").map(str::trim) == Some("0") + && d.child(craft_xml::Local("tgtEl")).is_none() + && d.child(craft_xml::Local("rtn")).is_none() + && d.child(craft_xml::Local("tn")).and_then(|tn| tn.attr_local("val")).and_then(craft_xml::value::to_u32_lossy) == Some(ms_id) + }; + st.children(craft_xml::Local("cond")).any(is_indefinite) + && st.children(craft_xml::Local("cond")).any(is_main_seq_on_begin) + && st.children(craft_xml::Local("cond")).all(|d| is_indefinite(d) || is_main_seq_on_begin(d)) +} + +fn collect_media_nodes<'a>(e: &'a craft_xml::El, deferred: bool, out: &mut Vec<(&'a craft_xml::El, bool)>, depth: usize) { + if depth > 64 || out.len() >= 10_000 { + return; + } + let mut deferred = deferred; + if e.is(craft_xml::Local("cTn")) + && let Some(st) = e.child(craft_xml::Local("stCondLst")) + && defers_start(st) + { + deferred = true; + } + if e.is(craft_xml::Local("video")) || e.is(craft_xml::Local("audio")) { + out.push((e, deferred)); + return; + } + for c in e.elements() { + collect_media_nodes(c, deferred, out, depth + 1); + } +} + +#[derive(Clone, Copy)] +struct MediaPlayAt { + trigger: Option, + main_seq_id: Option, + offset: u32, + deferred: bool, +} + +fn collect_media_plays<'a>(e: &'a craft_xml::El, at: MediaPlayAt, out: &mut Vec<(&'a craft_xml::El, MediaPlayAt)>, depth: usize) { + if depth > 64 || out.len() > 10_000 { + return; + } + for c in e.elements() { + if c.is(craft_xml::Local("cTn")) && c.attr_local("presetClass").is_some() { + let deferred = at.deferred || c.child(craft_xml::Local("stCondLst")).is_some_and(defers_start); + out.push((c, MediaPlayAt { deferred, ..at })); + continue; + } + let mut next = at; + if c.is(craft_xml::Local("seq")) + && let Some(ctn) = c.child(craft_xml::Local("cTn")) + && ctn.attr_local("nodeType") == Some("interactiveSeq") + { + next.trigger = ctn + .path(&[craft_xml::Local("stCondLst"), craft_xml::Local("cond"), craft_xml::Local("tgtEl"), craft_xml::Local("spTgt")]) + .and_then(|s| s.attr_local("spid")) + .and_then(craft_xml::value::to_u32_lossy); + next.main_seq_id = None; + } + if c.is(craft_xml::Local("cTn")) { + let is_main_seq = c.attr_local("nodeType") == Some("mainSeq"); + if let Some(st) = c.child(craft_xml::Local("stCondLst")) { + if !(!is_main_seq && !next.deferred && is_main_seq_auto(st, next.main_seq_id)) && defers_start(st) { + next.deferred = true; + } + if let Some(cond) = st.child(craft_xml::Local("cond")) { + if cond.attr_local("delay").map(str::trim) == Some("indefinite") { + next.offset = 0; + } else { + next.offset = next.offset.saturating_add(timing_ms(cond, "delay").unwrap_or(0)); + } + } + } + next.main_seq_id = if is_main_seq && !next.deferred { c.attr_local("id").and_then(craft_xml::value::to_u32_lossy) } else { None }; + } + collect_media_plays(c, next, out, depth + 1); + } +} + +fn apply_media_timing(timing: &craft_xml::El, shapes: &mut [Shape]) { + let mut nodes = Vec::new(); + collect_media_nodes(timing, false, &mut nodes, 0); + for (node, deferred) in nodes { + let Some(cm) = node.child(craft_xml::Local("cMediaNode")) else { continue }; + let Some(spid) = cm + .path(&[craft_xml::Local("tgtEl"), craft_xml::Local("spTgt")]) + .and_then(|t| t.attr_local("spid")) + .and_then(craft_xml::value::to_u32_lossy) + else { + continue; + }; + let Some(ShapeKind::Media(clip)) = deckcraft_model::find_shape_mut(shapes, deckcraft_model::ShapeId(spid)).map(|s| &mut s.kind) else { + continue; + }; + if cm.child(craft_xml::Local("cTn")).and_then(|c| c.attr_local("fill")) == Some("remove") { + clip.rewind = true; + } + if cm.attr_local("numSld").and_then(craft_xml::value::to_u32_lossy).is_some_and(|n| n > 1) { + clip.play_across_slides = true; + } + if !deferred + && cm + .path(&[craft_xml::Local("cTn"), craft_xml::Local("stCondLst"), craft_xml::Local("cond")]) + .is_some_and(|c| c.attr_local("evt").is_none() && c.attr_local("delay").map(str::trim) == Some("0")) + { + clip.autoplay = true; + } + } + let root_deferred = timing + .path(&[craft_xml::Local("tnLst"), craft_xml::Local("par"), craft_xml::Local("cTn"), craft_xml::Local("stCondLst")]) + .is_some_and(defers_start); + if !root_deferred && let Some(tn) = timing.child(craft_xml::Local("tnLst")) { + let mut found = Vec::new(); + collect_media_plays(tn, MediaPlayAt { trigger: None, main_seq_id: None, offset: 0, deferred: false }, &mut found, 0); + for (c, f) in found.into_iter().filter(|(_, f)| f.trigger.is_none()) { + if c.attr_local("nodeType") == Some("clickEffect") || f.deferred { + break; + } + let delay = c.path(&[craft_xml::Local("stCondLst"), craft_xml::Local("cond")]).and_then(|d| timing_ms(d, "delay")).unwrap_or(0); + if c.attr_local("presetClass") == Some("mediacall") + && c.attr_local("presetID").and_then(craft_xml::value::to_u32_lossy) == Some(1) + && f.offset == 0 + && delay == 0 + && let Some(spid) = c.find(craft_xml::Local("spTgt")).and_then(|t| t.attr_local("spid")).and_then(craft_xml::value::to_u32_lossy) + && let Some(ShapeKind::Media(clip)) = deckcraft_model::find_shape_mut(shapes, deckcraft_model::ShapeId(spid)).map(|s| &mut s.kind) + { + clip.autoplay = true; + } + } + } +} + +fn has_media_shapes(shapes: &[Shape]) -> bool { + shapes.iter().any(|s| match &s.kind { + ShapeKind::Media(_) => true, + ShapeKind::Group { children, .. } => has_media_shapes(children), + _ => false, + }) +} + +fn post_import_timing(bytes: &[u8], pres: &mut Presentation) { + let need_builds = has_unfolded_paragraph_builds(pres); + let need_media = pres.slides.iter().any(|s| has_media_shapes(&s.shapes)); + if !need_builds && !need_media { + return; + } + let Ok(mut pkg) = craft_opc::LazyPackage::open(bytes, &craft_pptx::LIMITS) else { + return; + }; + let root_rels = pkg.rels("").unwrap_or_default(); + let pres_path = root_rels.first("officeDocument").map(|r| r.target.clone()).unwrap_or_else(|| "ppt/presentation.xml".into()); + let Ok(Some(pres_bytes)) = pkg.read_limited(&pres_path, craft_pptx::MAX_XML_PART as u64) else { + return; + }; + let Ok(pres_el) = craft_drawingml::xmlx::parse(&pres_bytes) else { + return; + }; + let pres_rels = pkg.rels(&pres_path).unwrap_or_default(); + let Some(list) = pres_el.child(craft_xml::Local("sldIdLst")) else { + return; + }; + for (i, s) in list.children(craft_xml::Local("sldId")).take(MAX_SLIDE_ENTRIES).enumerate() { + let Some(slide_arc) = pres.slides.get_mut(i) else { break }; + let Some(target) = s.attr_local("r:id").and_then(|rid| pres_rels.target(rid)) else { continue }; + let Ok(Some(sb)) = pkg.read_limited(target, craft_pptx::MAX_XML_PART as u64) else { continue }; + let Ok(se) = craft_drawingml::xmlx::parse(&sb) else { continue }; + let Some(timing) = se.child(craft_xml::Local("timing")) else { continue }; + if need_media && has_media_shapes(&slide_arc.shapes) { + apply_media_timing(timing, &mut std::sync::Arc::make_mut(slide_arc).shapes); + } + if need_builds { + let mut info = SlideTimingInfo::default(); + collect_timing_offsets(timing, 0, &mut info.offsets, 0); + if let Some(bld_lst) = timing.child(craft_xml::Local("bldLst")) { + for b in bld_lst.children(craft_xml::Local("bldP")) { + if b.attr_local("build").unwrap_or("") != "p" + && let Some(spid) = b.attr_local("spid").and_then(craft_xml::value::to_u32_lossy) + { + info.opt_out.insert(spid); + } + } + } + fold_slide_paragraph_builds(std::sync::Arc::make_mut(slide_arc), &info); + } + } +} + +fn span_ms(a: &deckcraft_model::anim::Animation) -> u32 { + let iterations = if a.repeat == u32::MAX || a.repeat <= 1 { 1 } else { a.repeat.min(1_000) }; + a.duration_ms.saturating_mul(if a.auto_reverse { 2 } else { 1 }).saturating_mul(iterations) +} + +fn flat_starts(anims: &[&deckcraft_model::anim::Animation]) -> Vec { + let (mut begin, mut end) = (0u32, 0u32); + anims + .iter() + .map(|a| { + if a.start == deckcraft_model::anim::AnimStart::AfterPrevious { + begin = end; + } + let start = begin.saturating_add(a.delay_ms); + end = end.max(start.saturating_add(span_ms(a))); + start + }) + .collect() +} + +fn plays_as_build(effects: &[&deckcraft_model::anim::Animation], offsets: &[u32], text: &deckcraft_model::text::TextBody) -> bool { + use deckcraft_model::anim::{AnimStart, Animation, BuildRole, build_filled, paragraph_build_roles}; + let Some(first) = effects.first() else { return false }; + let off0 = offsets.first().copied().unwrap_or(0); + let flat = flat_starts(effects); + let parent_starts_match = offsets + .iter() + .zip(effects.iter()) + .zip(flat.iter()) + .all(|((&off, a), &ft)| off == off0 || off.saturating_add(a.delay_ms) == off0.saturating_add(ft)); + if !parent_starts_match || (first.start != AnimStart::OnClick && (span_ms(first) != 500 || first.delay_ms != 0 || off0 != 0)) { + return false; + } + let roles = paragraph_build_roles(text); + let expected = roles.iter().enumerate().filter(|(i, r)| match r { + BuildRole::Top => true, + BuildRole::Member(_) => text.paragraphs.get(*i).is_some_and(build_filled), + BuildRole::Unowned => false, + }); + let settings = |a: &Animation| Animation { start: AnimStart::OnClick, paragraph: None, ..a.clone() }; + let base = settings(first); + let mut matched = 0; + for (k, (i, role)) in expected.enumerate() { + let Some(a) = effects.get(k) else { return false }; + let start_ok = match role { + BuildRole::Top if k == 0 => true, + BuildRole::Top if first.start == AnimStart::OnClick => a.start == AnimStart::OnClick, + BuildRole::Top => a.start == AnimStart::AfterPrevious, + _ => a.start == AnimStart::WithPrevious, + }; + if a.paragraph != u32::try_from(i).ok() || !start_ok || settings(a) != base { + return false; + } + matched = k + 1; + } + matched == effects.len() +} + +fn fold_slide_paragraph_builds(slide: &mut deckcraft_model::Slide, info: &SlideTimingInfo) { + use deckcraft_model::anim::{Animation, TextBuild}; + let same = |x: &Animation, y: &Animation| { + x.paragraph.is_some() + && y.paragraph.is_some() + && x.text_build == TextBuild::AsOne + && y.text_build == TextBuild::AsOne + && x.shape == y.shape + && x.trigger == y.trigger + && !info.opt_out.contains(&x.shape.0) + }; + let mut folded = Vec::with_capacity(slide.animations.len()); + for run in slide.animations.chunk_by(same) { + let effects: Vec<&Animation> = run.iter().collect(); + let offsets: Vec = run.iter().map(|a| a.paragraph.and_then(|p| info.offsets.get(&(a.shape.0, p)).copied()).unwrap_or(0)).collect(); + let text = effects.first().and_then(|a| deckcraft_model::find_shape(&slide.shapes, a.shape)).and_then(|s| s.text.as_ref()); + if run.len() > 1 + && let (Some(first), Some(text)) = (effects.first(), text) + && !info.opt_out.contains(&first.shape.0) + && plays_as_build(&effects, &offsets, text) + { + folded.push(Animation { text_build: TextBuild::ByParagraph, paragraph: None, ..(*first).clone() }); + } else { + folded.extend(run.iter().cloned()); + } + } + slide.animations = folded; +} + /// Read a `.pptx` / `.potx` / `.ppsx` package. pub fn import(bytes: &[u8]) -> Result { - read::import(bytes) + preflight_slides(bytes)?; + let mut pres = craft_pptx::import(bytes, &DeckDefaults).map(convert::pres_from_craft)?; + post_import_timing(bytes, &mut pres); + Ok(pres) } /// [`import`], plus the part names of slides the file lists but that couldn't be read and were /// left out. /// Files with more than 10,000 slide-list entries return [`PptxError::Unsupported`] instead of a truncated presentation. pub fn import_checked(bytes: &[u8]) -> Result<(Presentation, Vec), PptxError> { - read::import_checked(bytes) + let (p, lost, _) = import_report(bytes)?; + Ok((p, lost)) } /// [`import_checked`], plus warnings for content cut to fit a limit (a table past the cell cap /// keeps its leading rows); the file still opens. pub fn import_report(bytes: &[u8]) -> Result<(Presentation, Vec, Vec), PptxError> { - read::import_report(bytes) + let mut missing = preflight_slides(bytes)?; + let (p, lost, warnings) = craft_pptx::import_report(bytes, &DeckDefaults)?; + missing.extend(lost); + let mut pres = convert::pres_from_craft(p); + post_import_timing(bytes, &mut pres); + Ok((pres, missing, warnings)) } /// [`import`] with a lower presentation-wide chart point budget, so tests reach the over-budget /// path without a multi-million-point chart. #[doc(hidden)] pub fn import_with_chart_budget(bytes: &[u8], points: usize) -> Result { - read::import_with_chart_points(bytes, points).map(|(p, _)| p) + preflight_slides(bytes)?; + let mut pres = craft_pptx::import_with_chart_budget(bytes, &DeckDefaults, points).map(convert::pres_from_craft)?; + post_import_timing(bytes, &mut pres); + Ok(pres) } /// Read the theme of a `.thmx` file, or of a `.pptx` / `.potx`'s first master, with its media. pub fn import_theme(bytes: &[u8]) -> Result<(deckcraft_model::theme::Theme, Vec), PptxError> { - read::import_theme(bytes) + let (theme, media) = craft_pptx::import_theme(bytes)?; + Ok((convert::theme_from_craft(theme), media.into_iter().map(convert::media_item_from_craft).collect())) +} + +fn shapes_have_over_cap_table(shapes: &[Shape]) -> bool { + shapes.iter().any(|s| match &s.kind { + ShapeKind::Table(t) => t.over_cap(), + ShapeKind::Group { children, .. } => shapes_have_over_cap_table(children), + _ => false, + }) +} + +fn check_table_caps(p: &Presentation) -> Result<(), PptxError> { + let over = p.slides.iter().any(|s| shapes_have_over_cap_table(&s.shapes)) + || p.masters.iter().any(|m| shapes_have_over_cap_table(&m.shapes) || m.layouts.iter().any(|l| shapes_have_over_cap_table(&l.shapes))); + if over { + return Err(PptxError::Unsupported(format!( + "a table has more than {} cells; export refused rather than drop rows", + deckcraft_model::table::MAX_CELLS + ))); + } + Ok(()) +} + +fn media_needs_timing(clip: &deckcraft_model::MediaClip) -> bool { + clip.autoplay + || (clip.volume - 1.0).abs() > 1e-6 + || clip.hide_while_not_playing + || clip.loop_play + || clip.rewind + || clip.play_across_slides + || (clip.video && clip.full_screen) +} + +fn collect_export_media<'a>(shapes: &'a [Shape]) -> Vec<(u32, &'a deckcraft_model::MediaClip)> { + let mut used = std::collections::HashSet::new(); + let mut max = 1u32; + deckcraft_model::walk(shapes, &mut |s, _| { + if s.id.0 >= 2 && s.id.0 < i32::MAX as u32 { + max = max.max(s.id.0); + } + }); + let mut next = max; + let mut media = Vec::new(); + deckcraft_model::walk(shapes, &mut |s, _| { + let spid = if s.id.0 >= 2 && s.id.0 < i32::MAX as u32 && !used.contains(&s.id.0) { + s.id.0 + } else { + next = next.saturating_add(1); + next + }; + used.insert(spid); + if let ShapeKind::Media(clip) = &s.kind + && media_needs_timing(clip) + { + media.push((spid, clip)); + } + }); + media +} + +fn write_media_node(w: &mut craft_xml::Writer, id: &mut u32, spid: u32, clip: &deckcraft_model::MediaClip) { + let tag = if clip.video { "p:video" } else { "p:audio" }; + let mut t = w.tag(tag); + if clip.video && clip.full_screen { + t = t.attr("fullScrn", "1"); + } + t.open(); + let vol = (clip.volume.clamp(0.0, 1.0) * 100_000.0).round() as u32; + let mut cm = w.tag("p:cMediaNode").attr("vol", vol); + if clip.volume <= 1e-6 { + cm = cm.attr("mute", "1"); + } + if clip.hide_while_not_playing { + cm = cm.attr("showWhenStopped", "0"); + } + if clip.play_across_slides { + cm = cm.attr("numSld", "999"); + } + cm.open(); + *id = id.saturating_add(1); + let mut ctn = w.tag("p:cTn").attr("id", *id).attr("fill", if clip.rewind { "remove" } else { "hold" }).attr("display", "0"); + if clip.loop_play { + ctn = ctn.attr("repeatCount", "indefinite"); + } + ctn.open(); + w.open("p:stCondLst", &[]); + w.tag("p:cond").attr("delay", if clip.autoplay { "0" } else { "indefinite" }).empty(); + w.close(); + w.close(); + w.open("p:tgtEl", &[]); + w.tag("p:spTgt").attr("spid", spid).empty(); + w.close(); + w.close(); + w.close(); +} + +fn max_ctn_id(e: &craft_xml::El, max_id: &mut u32, depth: usize) { + if depth > 64 { + return; + } + if e.is(craft_xml::Local("cTn")) + && let Some(id) = e.attr_local("id").and_then(craft_xml::value::to_u32_lossy) + { + *max_id = (*max_id).max(id); + } + for c in e.elements() { + max_ctn_id(c, max_id, depth + 1); + } +} + +fn patch_slide_media_timing(xml_bytes: &[u8], media: &[(u32, &deckcraft_model::MediaClip)]) -> Vec { + let Ok(mut xml) = String::from_utf8(xml_bytes.to_vec()) else { + return xml_bytes.to_vec(); + }; + let mut next_id = 1u32; + if let Ok(el) = craft_drawingml::xmlx::parse(xml_bytes) { + max_ctn_id(&el, &mut next_id, 0); + } + let mut w = craft_xml::Writer::new(); + for &(spid, clip) in media { + write_media_node(&mut w, &mut next_id, spid, clip); + } + let nodes = w.finish(); + if let Some(tn_end) = xml.rfind("") + && let Some(pos) = xml[..tn_end].rfind("") + { + xml.insert_str(pos, &nodes); + } else if let Some(pos) = xml.rfind("") { + let timing = format!( + r#"{nodes}"# + ); + xml.insert_str(pos, &timing); + } + xml.into_bytes() +} + +fn patch_exported_media_timing(p: &Presentation, bytes: Vec) -> Result, PptxError> { + let slide_media: Vec> = p.slides.iter().map(|s| collect_export_media(&s.shapes)).collect(); + if slide_media.iter().all(Vec::is_empty) { + return Ok(bytes); + } + let pkg = craft_opc::Package::open(&bytes, &craft_pptx::LIMITS).map_err(|e| PptxError::Write(e.to_string()))?; + let root_rels = pkg.rels(""); + let pres_path = root_rels.first("officeDocument").map(|r| r.target.clone()).unwrap_or_else(|| "ppt/presentation.xml".into()); + let pres_rels = pkg.rels(&pres_path); + let mut patches: std::collections::HashMap> = std::collections::HashMap::new(); + if let Some(pres_bytes) = pkg.get(&pres_path) + && let Ok(pres_el) = craft_drawingml::xmlx::parse(pres_bytes) + && let Some(list) = pres_el.child(craft_xml::Local("sldIdLst")) + { + for (i, s) in list.children(craft_xml::Local("sldId")).enumerate() { + let Some(media) = slide_media.get(i) else { break }; + if media.is_empty() { + continue; + } + if let Some(target) = s.attr_local("r:id").and_then(|rid| pres_rels.target(rid)) + && let Some(sb) = pkg.get(target) + { + patches.insert(target.to_string(), patch_slide_media_timing(sb, media)); + } + } + } + if patches.is_empty() { + return Ok(bytes); + } + let entries: Vec<(String, Vec)> = pkg + .names() + .filter_map(|name| { + let data = patches.remove(name).or_else(|| pkg.get(name).map(<[u8]>::to_vec))?; + Some((name.to_string(), data)) + }) + .collect(); + craft_opc::zip_entries(&entries).map_err(|e| PptxError::Write(e.to_string())) } /// Write a `.pptx` package. pub fn export(p: &Presentation) -> Result, PptxError> { - write::export(p, write::CT_PRES) + check_table_caps(p)?; + let bytes = craft_pptx::export(&convert::pres_to_craft(p), &DeckDefaults)?; + patch_exported_media_timing(p, bytes) } /// Write a package for `ext`: `potx` (template) and `ppsx` (slide show) differ from `pptx` only in /// the main part's content type. pub fn export_as(p: &Presentation, ext: &str) -> Result, PptxError> { - let ct = match ext { - "potx" => write::CT_TEMPLATE, - "ppsx" => write::CT_SHOW, - _ => write::CT_PRES, - }; - write::export(p, ct) -} - -/// Content type for a file name's extension. -pub(crate) fn mime_for(name: &str) -> &'static str { - let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default(); - match ext.as_str() { - "png" => "image/png", - "jpg" | "jpeg" | "jpe" => "image/jpeg", - "gif" => "image/gif", - "bmp" => "image/bmp", - "tif" | "tiff" => "image/tiff", - "svg" => "image/svg+xml", - "emf" => "image/x-emf", - "wmf" => "image/x-wmf", - "webp" => "image/webp", - "mp4" | "m4v" => "video/mp4", - "mov" => "video/quicktime", - "wmv" => "video/x-ms-wmv", - "avi" => "video/x-msvideo", - "webm" => "video/webm", - "mp3" => "audio/mpeg", - "wav" => "audio/wav", - "m4a" => "audio/mp4", - "wma" => "audio/x-ms-wma", - "ogg" => "audio/ogg", - "flac" => "audio/flac", - "glb" => "model/gltf-binary", - "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", - "fntdata" => "application/x-fontdata", - _ => "application/octet-stream", - } + check_table_caps(p)?; + let bytes = craft_pptx::export_as(&convert::pres_to_craft(p), &DeckDefaults, ext)?; + patch_exported_media_timing(p, bytes) } #[cfg(test)] @@ -228,4 +788,18 @@ mod table_direction_tests { } } } + + #[test] + fn over_cap_table_export_is_refused() { + let mut p = defaults::new_presentation(None); + let mut t = Table::new(1, 2, 200.0, 30.0); + t.rows.resize_with(deckcraft_model::table::MAX_CELLS / 2 + 1, || deckcraft_model::table::Row { + height: 20.0, + cells: vec![Cell::new("x"), Cell::new("y")], + }); + let shape = Shape { id: ShapeId(p.alloc_id().expect("id")), kind: ShapeKind::Table(t), ..Default::default() }; + Arc::make_mut(&mut p.slides[0]).shapes.push(shape); + let err = crate::export(&p).expect_err("over-cap table must be refused"); + assert!(matches!(err, crate::PptxError::Unsupported(_))); + } } diff --git a/crates/pptx/src/maps.rs b/crates/pptx/src/maps.rs deleted file mode 100644 index 6ce81a9be..000000000 --- a/crates/pptx/src/maps.rs +++ /dev/null @@ -1,449 +0,0 @@ -//! Mappings between our transition / animation ids and PresentationML elements and preset -//! numbers, shared by the reader and the writer. - -use deckcraft_model::anim::{ANIMATIONS, AnimClass}; - -use crate::xml::{A, El, W}; - -/// (our kind, namespace prefix, element) for transitions that map one-to-one. -const SIMPLE: &[(&str, &str, &str)] = - &[("dissolve", "p", "dissolve"), ("random", "p", "random"), ("honeycomb", "p14", "honeycomb"), ("flash", "p14", "flash")]; - -/// Read a transition effect element → (kind, option). `None` for effects we don't model. -pub fn transition_from_xml(e: &El) -> Option<(String, String)> { - let (k, o) = transition_from_xml_raw(e)?; - // Kinds without options keep none. - let has_opts = deckcraft_model::anim::TRANSITIONS.iter().find(|t| t.0 == k).is_none_or(|t| !t.4.is_empty()); - Some((k, if has_opts { o } else { String::new() })) -} - -/// Preset transitions (`p15:prstTrans`) whose "Left" option PowerPoint writes with `invX="1"` -/// (the others write it for "Right"), as observed on PowerPoint's own files. -const INVX_LEFT: &[&str] = &["wind", "airplane", "origami"]; - -fn transition_from_xml_raw(e: &El) -> Option<(String, String)> { - // Defaults are what PowerPoint leaves out: e.g. it writes Push Left as ``. - let dir = |d: &str| e.attr("dir").unwrap_or(d).to_string(); - let k = |s: &str| s.to_string(); - Some(match e.local() { - "fade" => (k("fade"), if e.bool("thruBlk") == Some(true) { k("throughBlack") } else { k("smoothly") }), - "cut" => (k("cut"), if e.bool("thruBlk") == Some(true) { k("throughBlack") } else { String::new() }), - "push" => (k("push"), dir("l")), - "wipe" => (k("wipe"), dir("l")), - // Diagonal wipes. - "strips" => (k("wipe"), dir("lu")), - "split" => { - let o = e.attr("orient").unwrap_or("horz"); - let d = e.attr("dir").unwrap_or("out"); - (k("split"), format!("{o}{}", if d == "in" { "In" } else { "Out" })) - } - "randomBar" => (k("randomBar"), dir("horz")), - "circle" => (k("shape"), k("circle")), - "diamond" => (k("shape"), k("diamond")), - "plus" => (k("shape"), k("plus")), - // Shape In / Out (the slide zooming in a box). - "zoom" => (k("shape"), if e.attr("dir") == Some("in") { k("in") } else { k("out") }), - // The Zoom transition, and its Zoom and Rotate option. - "warp" => (k("zoom"), if e.attr("dir") == Some("in") { k("in") } else { k("out") }), - "newsflash" => (k("zoom"), k("rotate")), - "pull" => (k("uncover"), dir("l")), - "cover" => (k("cover"), dir("l")), - "checker" => (k("checker"), dir("horz")), - "blinds" => (k("blinds"), dir("horz")), - "comb" => (k("comb"), dir("horz")), - "wheel" => (k("clock"), k("clockwise")), - "wheelReverse" => (k("clock"), k("counterClockwise")), - "wedge" => (k("clock"), k("wedge")), - "vortex" => (k("vortex"), dir("l")), - "switch" => (k("switch"), dir("r")), - "flip" => (k("flip"), dir("r")), - "ripple" => (k("ripple"), dir("center")), - "doors" => (k("doors"), dir("horz")), - "window" => (k("window"), dir("horz")), - "ferris" => (k("ferris"), dir("l")), - "gallery" => (k("gallery"), dir("l")), - "conveyor" => (k("conveyor"), dir("l")), - "pan" => (k("pan"), dir("l")), - "glitter" => { - let d = dir("l"); - if e.attr("pattern") == Some("hexagon") { (k("glitter"), format!("hex{}", d.to_ascii_uppercase())) } else { (k("glitter"), d) } - } - "shred" => { - // `crush` is what DeckCraft wrote before it knew PowerPoint's `rectangle`. - let particles = matches!(e.attr("pattern"), Some("rectangle" | "crush")); - let out = e.attr("dir") == Some("out"); - (k("shred"), format!("{}{}", if particles { "particles" } else { "strips" }, if out { "Out" } else { "In" })) - } - "reveal" => { - let black = e.bool("thruBlk") == Some(true); - let right = e.attr("dir") == Some("r"); - (k("reveal"), format!("{}{}", if black { "black" } else { "smoothly" }, if right { "Right" } else { "Left" })) - } - "flythrough" => { - let out = e.attr("dir") == Some("out"); - let b = e.bool("hasBounce") == Some(true); - (k("flythrough"), format!("{}{}", if out { "out" } else { "in" }, if b { "Bounce" } else { "" })) - } - "prism" => { - let content = e.bool("isContent") == Some(true); - let inv = e.bool("isInverted") == Some(true); - let kind = match (content, inv) { - (false, false) => "cube", - (false, true) => "box", - (true, false) => "rotate", - (true, true) => "orbit", - }; - (k(kind), dir("l")) - } - "prstTrans" => { - let prst = e.attr("prst").unwrap_or("fallOver"); - let inv = e.bool("invX") == Some(true); - if prst == "pageCurlSingle" { - return Some((k("pageCurlDouble"), if inv { k("singleR") } else { k("singleL") })); - } - let known = deckcraft_model::anim::TRANSITIONS.iter().any(|t| t.0 == prst); - if !known { - return None; - } - let left = if INVX_LEFT.contains(&prst) { inv } else { !inv }; - (k(prst), if left { k("l") } else { k("r") }) - } - "morph" => ( - k("morph"), - match e.attr("option") { - Some("byWord") => k("words"), - Some("byChar") => k("characters"), - _ => k("objects"), - }, - ), - other => (k(SIMPLE.iter().find(|s| s.2 == other)?.0), String::new()), - }) -} - -/// Write the effect element for a transition. Returns the namespace prefix it needs -/// (`p`, `p14`, `p15`, `p159`), or `None` when the kind is unknown. -pub fn transition_to_xml(w: &mut W, kind: &str, option: &str) -> Option<&'static str> { - let lr = |d: &'static str| match option { - "l" | "r" => option.to_string(), - _ => d.to_string(), - }; - let lrud = |d: &'static str| match option { - "l" | "r" | "u" | "d" => option.to_string(), - _ => d.to_string(), - }; - let hv = |d: &'static str| match option { - "horz" | "vert" => option.to_string(), - _ => d.to_string(), - }; - let eight = |d: &'static str| match option { - "l" | "r" | "u" | "d" | "lu" | "ru" | "ld" | "rd" => option.to_string(), - _ => d.to_string(), - }; - match kind { - "fade" => w.empty("p:fade", A::new().t("thruBlk", option == "throughBlack")), - "cut" => w.empty("p:cut", A::new().t("thruBlk", option == "throughBlack")), - "push" => w.empty("p:push", A::new().a("dir", lrud("u"))), - "wipe" => match option { - "lu" | "ru" | "ld" | "rd" => w.empty("p:strips", A::new().a("dir", option)), - _ => w.empty("p:wipe", A::new().a("dir", lrud("r"))), - }, - "split" => { - let (o, d) = match option { - "vertIn" => ("vert", "in"), - "vertOut" => ("vert", "out"), - "horzIn" => ("horz", "in"), - _ => ("horz", "out"), - }; - w.empty("p:split", A::new().a("orient", o).a("dir", d)); - } - "randomBar" => w.empty("p:randomBar", A::new().a("dir", hv("vert"))), - "shape" => match option { - "diamond" => w.empty0("p:diamond"), - "plus" => w.empty0("p:plus"), - "in" | "out" => w.empty("p:zoom", A::new().a("dir", option)), - _ => w.empty0("p:circle"), - }, - "zoom" => match option { - "rotate" => w.empty0("p:newsflash"), - _ => { - w.empty("p14:warp", A::new().a("dir", if option == "out" { "out" } else { "in" })); - return Some("p14"); - } - }, - "uncover" => w.empty("p:pull", A::new().a("dir", eight("l"))), - "cover" => w.empty("p:cover", A::new().a("dir", eight("l"))), - "checker" => w.empty("p:checker", A::new().a("dir", hv("horz"))), - "blinds" => w.empty("p:blinds", A::new().a("dir", hv("horz"))), - "comb" => w.empty("p:comb", A::new().a("dir", hv("horz"))), - "clock" => match option { - "counterClockwise" => { - w.empty("p14:wheelReverse", A::new().a("spokes", 1)); - return Some("p14"); - } - "wedge" => w.empty0("p:wedge"), - _ => w.empty("p:wheel", A::new().a("spokes", 1)), - }, - "dissolve" => w.empty0("p:dissolve"), - "random" => w.empty0("p:random"), - "honeycomb" => { - w.empty0("p14:honeycomb"); - return Some("p14"); - } - "flash" => { - w.empty0("p14:flash"); - return Some("p14"); - } - "vortex" => { - w.empty("p14:vortex", A::new().a("dir", lrud("l"))); - return Some("p14"); - } - "glitter" => { - let hex = option.starts_with("hex"); - let d = option.trim_start_matches("hex").to_ascii_lowercase(); - let d = if matches!(d.as_str(), "l" | "r" | "u" | "d") { d } else { "l".to_string() }; - w.empty("p14:glitter", A::new().a("dir", d).o("pattern", hex.then_some("hexagon"))); - return Some("p14"); - } - "switch" | "flip" | "gallery" | "conveyor" | "ferris" => { - let name = match kind { - "switch" => "p14:switch", - "flip" => "p14:flip", - "gallery" => "p14:gallery", - "conveyor" => "p14:conveyor", - _ => "p14:ferris", - }; - w.empty(name, A::new().a("dir", lr("l"))); - return Some("p14"); - } - "ripple" => { - let d = match option { - "lu" | "ru" | "ld" | "rd" => option, - _ => "center", - }; - w.empty("p14:ripple", A::new().a("dir", d)); - return Some("p14"); - } - "doors" | "window" => { - let name = if kind == "doors" { "p14:doors" } else { "p14:window" }; - w.empty(name, A::new().a("dir", hv("vert"))); - return Some("p14"); - } - "pan" => { - w.empty("p14:pan", A::new().a("dir", lrud("d"))); - return Some("p14"); - } - "shred" => { - let particles = option.starts_with("particles"); - w.empty( - "p14:shred", - A::new().a("pattern", if particles { "rectangle" } else { "strip" }).a("dir", if option.ends_with("Out") { "out" } else { "in" }), - ); - return Some("p14"); - } - "reveal" => { - w.empty("p14:reveal", A::new().t("thruBlk", option.starts_with("black")).a("dir", if option.ends_with("Right") { "r" } else { "l" })); - return Some("p14"); - } - "flythrough" => { - w.empty( - "p14:flythrough", - A::new().a("dir", if option.starts_with("out") { "out" } else { "in" }).t("hasBounce", option.ends_with("Bounce")), - ); - return Some("p14"); - } - "cube" | "box" | "rotate" | "orbit" => { - w.empty( - "p14:prism", - A::new().a("dir", lrud("l")).t("isContent", matches!(kind, "rotate" | "orbit")).t("isInverted", matches!(kind, "box" | "orbit")), - ); - return Some("p14"); - } - "pageCurlDouble" if option.starts_with("single") => { - w.empty("p15:prstTrans", A::new().a("prst", "pageCurlSingle").t("invX", option == "singleR")); - return Some("p15"); - } - "fallOver" | "drape" | "curtains" | "wind" | "prestige" | "fracture" | "crush" | "peelOff" | "pageCurlDouble" | "airplane" | "origami" => { - let inv = if INVX_LEFT.contains(&kind) { option == "l" } else { option == "r" }; - w.empty("p15:prstTrans", A::new().a("prst", kind).t("invX", inv)); - return Some("p15"); - } - "morph" => { - let o = match option { - "words" => "byWord", - "characters" => "byChar", - _ => "byObject", - }; - w.empty("p159:morph", A::new().a("option", o)); - return Some("p159"); - } - _ => return None, - } - Some("p") -} - -// --------------------------------------------------------------------------------------------- -// Animations - -/// Effect options ↔ preset subtypes. -const SUBTYPES: &[(&str, &[(&str, u32)])] = &[ - ("fly", DIR8), - ("flyOut", DIR8), - ("peek", DIR4), - ("wipe", DIR4), - ("wipeOut", DIR4), - ("strips", &[("lu", 9), ("ru", 3), ("ld", 12), ("rd", 6)]), - ("split", SPLIT), - ("splitOut", SPLIT), - ("zoom", INOUT), - ("zoomOut", INOUT), - ("box", INOUT), - ("circle", INOUT), - ("diamond", INOUT), - ("randomBars", HV), - ("randomBarsOut", HV), - ("blinds", HV), - ("swivel", HV), - ("swivelOut", HV), - ("blindsOut", HV), - ("boxOut", INOUT), - ("checkerboardOut", &[("across", 10), ("down", 5)]), - ("diamondOut", INOUT), - ("peekOut", DIR4), - ("stripsOut", &[("lu", 9), ("ru", 3), ("ld", 12), ("rd", 6)]), - ("checkerboard", &[("across", 10), ("down", 5)]), - ("wheel", WHEEL), - ("wheelOut", WHEEL), - ("float", &[("u", 0), ("d", 4)]), - ("floatOut", &[("u", 0), ("d", 4)]), - ( - "shape", - &[("circleIn", 16), ("circleOut", 32), ("boxIn", 16), ("boxOut", 32), ("diamondIn", 16), ("diamondOut", 32), ("plusIn", 16), ("plusOut", 32)], - ), - ("shapeOut", INOUT_SHAPE), - ("lines", &[("down", 4), ("up", 1), ("right", 2), ("left", 8)]), - ("arcs", &[("down", 4), ("up", 1), ("right", 2), ("left", 8)]), - ("turns", &[("down", 4), ("up", 1), ("right", 2), ("left", 8)]), -]; -const DIR8: &[(&str, u32)] = &[("b", 4), ("lb", 12), ("l", 8), ("lt", 9), ("t", 1), ("rt", 3), ("r", 2), ("rb", 6)]; -const DIR4: &[(&str, u32)] = &[("b", 4), ("l", 8), ("t", 1), ("r", 2)]; -const SPLIT: &[(&str, u32)] = &[("horzIn", 21), ("horzOut", 42), ("vertIn", 26), ("vertOut", 37)]; -const INOUT: &[(&str, u32)] = &[("in", 16), ("out", 32)]; -const INOUT_SHAPE: &[(&str, u32)] = &[("circleIn", 16), ("circleOut", 32)]; -const HV: &[(&str, u32)] = &[("horz", 10), ("vert", 5)]; -const WHEEL: &[(&str, u32)] = &[("1", 1), ("2", 2), ("3", 3), ("4", 4), ("8", 8)]; - -pub fn option_from_subtype(effect: &str, sub: u32) -> String { - SUBTYPES.iter().find(|(e, _)| *e == effect).and_then(|(_, m)| m.iter().find(|(_, s)| *s == sub)).map(|(o, _)| o.to_string()).unwrap_or_default() -} - -pub fn subtype_from_option(effect: &str, option: &str) -> Option { - SUBTYPES.iter().find(|(e, _)| *e == effect).and_then(|(_, m)| m.iter().find(|(o, _)| *o == option)).map(|(_, s)| *s) -} - -/// Our effect id for a preset (first match in [`ANIMATIONS`]). -pub fn effect_for_preset(class: AnimClass, preset: u32) -> Option<&'static str> { - ANIMATIONS.iter().find(|a| a.2 == class && a.3 == preset && a.0 != "customPath").map(|a| a.0) -} - -/// Effect used for presets we don't know. -pub fn fallback_effect(class: AnimClass) -> &'static str { - match class { - AnimClass::Entrance => "fade", - AnimClass::Exit => "fadeOut", - AnimClass::Emphasis => "pulse", - AnimClass::Path => "customPath", - AnimClass::Media => "play", - } -} - -/// The preset id to write for an animation. -pub fn preset_for(a: &deckcraft_model::Animation) -> u32 { - // Float Down is PowerPoint's preset 47 (Float Up is 42). - if matches!(a.effect.as_str(), "float" | "floatOut") && a.option == "d" { - return 47; - } - if let Some(p) = a.preset_id { - let consistent = match effect_for_preset(a.class, p) { - Some(e) => e == a.effect, - None => a.effect == fallback_effect(a.class), - }; - if consistent { - return p; - } - } - match deckcraft_model::anim::animation_info(&a.effect, a.class) { - Some(info) if info.2 == a.class => info.3, - _ => match a.class { - AnimClass::Entrance | AnimClass::Exit => 10, - AnimClass::Emphasis => 26, - AnimClass::Path => 0, - AnimClass::Media => 1, - }, - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::xml::parse; - - /// #147: these exits, with their directions, fell back to a plain fade (PowerPoint's ids). - #[test] - fn exit_presets_import_as_their_own_effects() { - for (preset, sub, effect, option) in [ - (3, 10, "blindsOut", "horz"), - (4, 32, "boxOut", "out"), - (5, 5, "checkerboardOut", "down"), - (8, 16, "diamondOut", "in"), - (12, 4, "peekOut", "b"), - (18, 6, "stripsOut", "rd"), - (37, 0, "sinkDown", ""), - (49, 0, "spinnerOut", ""), - (55, 0, "contract", ""), - ] { - let e = effect_for_preset(AnimClass::Exit, preset).expect("known exit"); - assert_eq!((e, option_from_subtype(e, sub).as_str()), (effect, option), "preset {preset}"); - } - } - - #[test] - fn every_transition_kind_round_trips() { - for (kind, _, _, _, opts) in deckcraft_model::anim::TRANSITIONS { - if *kind == "none" { - continue; - } - let opts: Vec<&str> = if opts.is_empty() { vec![""] } else { opts.to_vec() }; - for o in opts { - let mut w = W::frag(); - let ns = transition_to_xml(&mut w, kind, o).unwrap_or_else(|| panic!("no xml for {kind}")); - assert!(!ns.is_empty()); - let d = parse(w.s.as_bytes()).unwrap(); - let (k, opt) = transition_from_xml(&d.root).unwrap_or_else(|| panic!("no read for {kind}")); - assert_eq!(k, *kind, "kind for {kind}/{o}"); - if !o.is_empty() { - assert_eq!(opt, o, "option for {kind}"); - } - } - } - } - - #[test] - fn subtypes() { - assert_eq!(subtype_from_option("fly", "b"), Some(4)); - assert_eq!(option_from_subtype("fly", 8), "l"); - assert_eq!(option_from_subtype("fade", 0), ""); - assert_eq!(effect_for_preset(AnimClass::Entrance, 2), Some("fly")); - assert_eq!(effect_for_preset(AnimClass::Emphasis, 8), Some("spin")); - } - - /// PowerPoint's own ids: Darken is 24 and Desaturate 25 (read back from its saved file). - #[test] - fn darken_and_desaturate_use_powerpoints_ids() { - assert_eq!(effect_for_preset(AnimClass::Emphasis, 24), Some("darken")); - assert_eq!(effect_for_preset(AnimClass::Emphasis, 25), Some("desaturate")); - for (effect, id) in [("darken", 24), ("desaturate", 25)] { - let a = deckcraft_model::Animation { class: AnimClass::Emphasis, effect: effect.into(), ..Default::default() }; - assert_eq!(preset_for(&a), id, "{effect}"); - } - } -} diff --git a/crates/pptx/src/opc.rs b/crates/pptx/src/opc.rs deleted file mode 100644 index f8e582438..000000000 --- a/crates/pptx/src/opc.rs +++ /dev/null @@ -1,563 +0,0 @@ -//! Open Packaging Conventions: the zip container, part names, relationships and content types. - -use std::collections::HashMap; -use std::io::{Cursor, Read, Write}; - -use crate::PptxError; -use crate::xml::{self, A, W}; - -/// Largest single part we decompress (media included). -pub const MAX_PART: u64 = 512 * 1024 * 1024; -/// Largest XML part we parse. -pub const MAX_XML_PART: usize = 96 * 1024 * 1024; -/// Total decompressed bytes accepted for one package. -pub const MAX_TOTAL: u64 = 2 * 1024 * 1024 * 1024; -/// Total bytes we are willing to decompress for one package, counting parts we then discard -/// (too large, or failing part-way): bounds inflate work, not just what is kept. -pub const MAX_INFLATE_WORK: u64 = 2 * MAX_TOTAL; -/// Maximum number of zip entries. -pub const MAX_ENTRIES: usize = 50_000; - -pub const NS_A: &str = "http://schemas.openxmlformats.org/drawingml/2006/main"; -pub const NS_R: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; -pub const NS_P: &str = "http://schemas.openxmlformats.org/presentationml/2006/main"; -pub const NS_C: &str = "http://schemas.openxmlformats.org/drawingml/2006/chart"; -pub const NS_MC: &str = "http://schemas.openxmlformats.org/markup-compatibility/2006"; -pub const NS_P14: &str = "http://schemas.microsoft.com/office/powerpoint/2010/main"; -pub const NS_P15: &str = "http://schemas.microsoft.com/office/powerpoint/2012/main"; -pub const NS_P159: &str = "http://schemas.microsoft.com/office/powerpoint/2015/09/main"; -pub const NS_A14: &str = "http://schemas.microsoft.com/office/drawing/2010/main"; -/// Modern (threaded) comments, Office 2018/8 schema. -pub const NS_P188: &str = "http://schemas.microsoft.com/office/powerpoint/2018/8/main"; - -pub const RT_BASE: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/"; -pub const RT_MEDIA: &str = "http://schemas.microsoft.com/office/2007/relationships/media"; -/// A 3-D model part (`.glb`). Office relationship, not an ECMA-376 base type. -pub const RT_MODEL3D: &str = "http://schemas.microsoft.com/office/2017/06/relationships/model3d"; -pub const RT_CORE: &str = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties"; - -/// The files of a package, keyed by normalised part name (no leading slash, lowercase). -pub struct Package { - parts: HashMap)>, - ct_cache: std::sync::OnceLock<(HashMap, HashMap)>, -} - -impl Package { - pub fn open(bytes: &[u8]) -> Result { - Self::open_within(bytes, MAX_PART, MAX_TOTAL, MAX_INFLATE_WORK) - } - /// [`Package::open`] with explicit limits: per part, kept in total, and inflated in total. - fn open_within(bytes: &[u8], max_part: u64, max_total: u64, max_work: u64) -> Result { - let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| PptxError::NotPptx(format!("{e}")))?; - if zip.len() > MAX_ENTRIES { - return Err(PptxError::NotPptx(format!("too many entries ({})", zip.len()))); - } - let mut parts = HashMap::new(); - let mut total: u64 = 0; - let mut work: u64 = 0; - for i in 0..zip.len() { - if work >= max_work { - log::warn!("pptx: decompression budget spent; skipping the remaining {} entries", zip.len() - i); - break; - } - let mut f = match zip.by_index(i) { - Ok(f) => f, - Err(e) => { - log::warn!("pptx: skipping unreadable zip entry {i}: {e}"); - continue; - } - }; - if f.is_dir() { - continue; - } - let name = f.name().trim_start_matches('/').to_string(); - let declared = f.size(); - if declared > max_part { - log::warn!("pptx: skipping oversized part {name} ({declared} bytes)"); - continue; - } - let mut data = Vec::with_capacity(declared.min(16 * 1024 * 1024) as usize); - let cap = max_part.min(max_total.saturating_sub(total)).min(max_work.saturating_sub(work)); - let read = (&mut f).take(cap.saturating_add(1)).read_to_end(&mut data); - // Charge what was inflated whether or not the part is kept. - work = work.saturating_add(data.len() as u64); - match read { - Ok(_) if data.len() as u64 > cap => { - log::warn!("pptx: part {name} exceeds size limits; skipped"); - continue; - } - Ok(_) => {} - Err(e) => { - log::warn!("pptx: could not read {name}: {e}"); - continue; - } - } - total = total.saturating_add(data.len() as u64); - // A name kept with `\` would reach code that splits paths on `/`. - parts.insert(norm(&name), (name.replace('\\', "/"), data)); - } - Ok(Package { parts, ct_cache: std::sync::OnceLock::new() }) - } - pub fn get(&self, name: &str) -> Option<&[u8]> { - self.parts.get(&norm(name)).map(|(_, d)| d.as_slice()) - } - /// An XML part's bytes, when it is within the XML size limit. - pub fn xml_bytes(&self, name: &str) -> Option<&[u8]> { - let b = self.get(name)?; - if b.len() > MAX_XML_PART { - log::warn!("pptx: XML part {name} too large"); - return None; - } - Some(b) - } - /// Parse an XML part. - pub fn xml(&self, name: &str) -> Option { - let b = self.get(name)?; - if b.len() > MAX_XML_PART { - log::warn!("pptx: XML part {name} too large"); - return None; - } - match xml::parse(b) { - Ok(d) => Some(d), - Err(e) => { - log::warn!("pptx: {name}: {e}"); - None - } - } - } - /// Relationships of a part (`ppt/slides/slide1.xml` → `ppt/slides/_rels/slide1.xml.rels`). - pub fn rels(&self, part: &str) -> Rels { - let rp = rels_path(part); - let Some(doc) = self.xml(&rp) else { return Rels::default() }; - rels_of(&doc, part) - } - /// Content types: (extension defaults, part overrides). - pub fn content_type(&self, part: &str) -> Option { - let (overrides, defaults) = self.ct_cache.get_or_init(|| { - let mut ov = HashMap::new(); - let mut def = HashMap::new(); - if let Some(doc) = self.xml("[Content_Types].xml") { - for o in doc.root.children_named("Override") { - if let (Some(n), Some(ct)) = (o.attr("PartName"), o.attr("ContentType")) { - ov.insert(n.to_ascii_lowercase(), ct.to_string()); - } - } - for d in doc.root.children_named("Default") { - if let (Some(e), Some(ct)) = (d.attr("Extension"), d.attr("ContentType")) { - def.insert(e.to_ascii_lowercase(), ct.to_string()); - } - } - } - (ov, def) - }); - let p = format!("/{}", norm(part)); - if let Some(ct) = overrides.get(&p) { - return Some(ct.clone()); - } - let ext = part.rsplit('.').next().unwrap_or("").to_ascii_lowercase(); - defaults.get(&ext).cloned() - } - pub fn original_name(&self, name: &str) -> Option<&str> { - self.parts.get(&norm(name)).map(|(n, _)| n.as_str()) - } -} - -/// The relationships in a parsed rels part, with internal targets resolved against `part`'s folder. -fn rels_of(doc: &xml::Doc, part: &str) -> Rels { - let base = dir_of(part); - let mut out = Rels::default(); - for r in doc.root.children_named("Relationship") { - let (Some(id), Some(ty), Some(target)) = (r.attr("Id"), r.attr("Type"), r.attr("Target")) else { continue }; - let external = r.attr("TargetMode").is_some_and(|m| m.eq_ignore_ascii_case("external")); - let target_raw = target.to_string(); - let target = if external { target_raw.clone() } else { resolve(&base, target) }; - out.by_id.entry(id.to_string()).or_insert(out.items.len()); - out.items.push(Rel { - id: id.to_string(), - kind: ty.rsplit('/').next().unwrap_or(ty).to_string(), - ty: ty.to_string(), - target_raw, - target, - external, - }); - } - out -} - -/// The relationships of `part` from the bytes of its rels part (kept parts carried by a chart). -pub fn rels_from_bytes(bytes: &[u8], part: &str) -> Rels { - match xml::parse(bytes) { - Ok(doc) => rels_of(&doc, part), - Err(e) => { - log::warn!("pptx: relationships of {part}: {e}"); - Rels::default() - } - } -} - -#[derive(Clone, Debug, Default)] -pub struct Rel { - pub id: String, - /// Last segment of the relationship type (`slide`, `image`, `media`…). - pub kind: String, - /// Full relationship type URI. - pub ty: String, - /// `Target` as written in the rels part (relative path or URL). - pub target_raw: String, - /// Absolute part name for internal targets; the URL for external ones. - pub target: String, - pub external: bool, -} - -#[derive(Clone, Debug, Default)] -pub struct Rels { - pub items: Vec, - /// Id → index of its first relationship in `items`. - by_id: HashMap, -} - -impl Rels { - pub fn get(&self, id: &str) -> Option<&Rel> { - self.by_id.get(id).and_then(|&i| self.items.get(i)) - } - pub fn target(&self, id: &str) -> Option<&str> { - self.get(id).map(|r| r.target.as_str()) - } - pub fn first_of(&self, kind: &str) -> Option<&Rel> { - self.items.iter().find(|r| r.kind == kind) - } - pub fn all_of<'a>(&'a self, kind: &'a str) -> impl Iterator + 'a { - self.items.iter().filter(move |r| r.kind == kind) - } -} - -pub fn norm(name: &str) -> String { - name.trim_start_matches('/').replace('\\', "/").to_ascii_lowercase() -} - -/// A part a chart may carry along beside its own `chartN.xml` (workbook, style, drawing, picture). -/// Chart documents themselves are rewritten, and nothing outside these folders is copied: a relationship -/// must not be able to replace `ppt/slides/slide1.xml` on save. -pub fn sidecar_part(name: &str) -> bool { - let n = norm(name); - let segs: Vec<&str> = n.split('/').filter(|s| !s.is_empty()).collect(); - if segs.iter().any(|s| *s == "." || *s == "..") { - return false; - } - let (Some(root), Some(area)) = (segs.first().copied(), segs.get(1).copied()) else { return false }; - if root != "ppt" || !matches!(area, "embeddings" | "charts" | "drawings" | "media") { - return false; - } - let file = segs.last().copied().unwrap_or(""); - let stem = file.strip_prefix("chart").unwrap_or(""); - let num = stem.strip_suffix(".xml.rels").or_else(|| stem.strip_suffix(".xml")).unwrap_or(""); - !(stem != file && !num.is_empty() && num.chars().all(|c| c.is_ascii_digit())) -} - -pub fn dir_of(part: &str) -> String { - craft_opc::dir_of(part).to_owned() -} - -use craft_opc::percent_decode; -pub use craft_opc::{file_of, rels_path}; - -/// Resolve a relative target against a base directory into a part name. -pub fn resolve(base: &str, target: &str) -> String { - let target = percent_decode(target.split('#').next().unwrap_or("")).replace('\\', "/"); - let target = target.as_str(); - let mut segs: Vec<&str> = if target.starts_with('/') { vec![] } else { base.split('/').filter(|s| !s.is_empty()).collect() }; - for s in target.split('/') { - match s { - "" | "." => {} - ".." => { - segs.pop(); - } - s => segs.push(s), - } - } - segs.join("/") -} - -/// Relative target from the directory of `from` to part `to` (both absolute part names). -pub fn relative(from: &str, to: &str) -> String { - let fd_s = dir_of(from); - let fd: Vec<&str> = fd_s.split('/').filter(|s| !s.is_empty()).collect(); - let td_s = dir_of(to); - let td: Vec<&str> = td_s.split('/').filter(|s| !s.is_empty()).collect(); - let common = fd.iter().zip(td.iter()).take_while(|(a, b)| a == b).count(); - let mut out = String::new(); - for _ in common..fd.len() { - out.push_str("../"); - } - for s in td.iter().skip(common) { - out.push_str(s); - out.push('/'); - } - out.push_str(file_of(to)); - out -} - -// --------------------------------------------------------------------------------------------- -// Writing - -/// Relationships being built for one part. -#[derive(Default)] -pub struct RelsOut { - pub items: Vec<(String, String, String, bool)>, - /// (type, target, external) → id of the relationship [`RelsOut::add`] made for it. - added: HashMap<(String, String, bool), String>, -} - -impl RelsOut { - /// Add (or reuse) a relationship; `kind` is a full type URI or a suffix of the standard base. - pub fn add(&mut self, kind: &str, target: &str, external: bool) -> String { - let ty = if kind.starts_with("http") { kind.to_string() } else { format!("{RT_BASE}{kind}") }; - let key = (ty, target.to_string(), external); - if let Some(id) = self.added.get(&key) { - return id.clone(); - } - let id = format!("rId{}", self.items.len() + 1); - self.items.push((id.clone(), key.0.clone(), key.1.clone(), external)); - self.added.insert(key, id.clone()); - id - } - /// Always add a new relationship even if an identical one exists. - pub fn add_new(&mut self, kind: &str, target: &str, external: bool) -> String { - let ty = if kind.starts_with("http") { kind.to_string() } else { format!("{RT_BASE}{kind}") }; - let id = format!("rId{}", self.items.len() + 1); - // `add` reuses the first relationship for a target, whichever call made it. - self.added.entry((ty.clone(), target.to_string(), external)).or_insert_with(|| id.clone()); - self.items.push((id.clone(), ty, target.to_string(), external)); - id - } - pub fn to_xml(&self) -> Vec { - let mut w = W::new(); - w.open("Relationships", A::new().a("xmlns", "http://schemas.openxmlformats.org/package/2006/relationships")); - for (id, ty, target, ext) in &self.items { - let mut a = A::new().a("Id", id).a("Type", ty).a("Target", target); - if *ext { - a = a.a("TargetMode", "External"); - } - w.empty("Relationship", a); - } - w.close("Relationships"); - w.finish() - } -} - -/// A package being written. -pub struct PackageOut { - files: Vec<(String, Vec, bool)>, - defaults: Vec<(String, String)>, - overrides: Vec<(String, String)>, -} - -impl Default for PackageOut { - fn default() -> Self { - PackageOut { - files: vec![], - defaults: vec![ - ("rels".into(), "application/vnd.openxmlformats-package.relationships+xml".into()), - ("xml".into(), "application/xml".into()), - ], - overrides: vec![], - } - } -} - -impl PackageOut { - /// Add an XML part with its content type override. - pub fn xml_part(&mut self, name: &str, content_type: &str, data: Vec) { - self.overrides.push((format!("/{name}"), content_type.to_string())); - self.files.push((name.to_string(), data, true)); - } - pub fn rels(&mut self, part: &str, rels: &RelsOut) { - if rels.items.is_empty() { - return; - } - let path = rels_path(part); - if let Some(existing) = self.files.iter_mut().find(|(name, ..)| *name == path) { - existing.1 = rels.to_xml(); - } else { - self.files.push((path, rels.to_xml(), true)); - } - } - /// Add a part with no content type of its own (a relationships part). - pub fn raw(&mut self, name: &str, data: Vec) { - self.files.push((name.to_string(), data, true)); - } - /// Add a binary part; its extension gets a Default content type. - pub fn binary(&mut self, name: &str, content_type: &str, data: Vec) { - let ext = name.rsplit('.').next().unwrap_or("bin").to_ascii_lowercase(); - if !self.defaults.iter().any(|(e, _)| *e == ext) { - self.defaults.push((ext, content_type.to_string())); - } else if !self.defaults.iter().any(|(e, c)| *e == ext && c == content_type) { - self.overrides.push((format!("/{name}"), content_type.to_string())); - } - self.files.push((name.to_string(), data, false)); - } - pub fn finish(self) -> Result, PptxError> { - let mut ct = W::new(); - ct.open("Types", A::new().a("xmlns", "http://schemas.openxmlformats.org/package/2006/content-types")); - for (e, c) in &self.defaults { - ct.empty("Default", A::new().a("Extension", e).a("ContentType", c)); - } - for (p, c) in &self.overrides { - ct.empty("Override", A::new().a("PartName", p).a("ContentType", c)); - } - ct.close("Types"); - let mut zw = zip::ZipWriter::new(Cursor::new(Vec::new())); - let deflate = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated); - let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); - let err = |e: &dyn std::fmt::Display| PptxError::Write(e.to_string()); - zw.start_file("[Content_Types].xml", deflate).map_err(|e| err(&e))?; - zw.write_all(&ct.finish()).map_err(|e| err(&e))?; - let mut written = std::collections::HashSet::new(); - for (name, data, compress) in &self.files { - // Zip entry names must be unique: a second part under a name already written is - // dropped rather than producing a package readers reject or resolve differently. - if !written.insert(norm(name)) { - log::warn!("pptx: part {name} written twice; keeping the first"); - continue; - } - let large = data.len() as u64 >= u32::MAX as u64 / 2; - let opts = if *compress { deflate } else { stored }.large_file(large); - zw.start_file(name.as_str(), opts).map_err(|e| err(&e))?; - zw.write_all(data).map_err(|e| err(&e))?; - } - let cur = zw.finish().map_err(|e| err(&e))?; - Ok(cur.into_inner()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn shared_names_preserve_relationship_wire_policy() { - for (part, dir, file, rels) in [ - ("", "", "", "_rels/.rels"), - ("/", "", "", "_rels/.rels"), - ("///ppt/slides/slide1.xml", "ppt/slides", "slide1.xml", "ppt/slides/_rels/slide1.xml.rels"), - ("ppt/", "ppt", "", "ppt/_rels/.rels"), - ("é/😀.xml", "é", "😀.xml", "é/_rels/😀.xml.rels"), - ] { - assert_eq!(dir_of(part), dir); - assert_eq!(file_of(part), file); - assert_eq!(rels_path(part), rels); - } - assert_eq!(percent_decode("a+b%20c%2Fd%23e"), "a+b c/d#e"); - assert_eq!(percent_decode("% %1 %zz %+1 %ff"), "% %1 %zz %+1 �"); - // Keep Deck's policy: strip the raw fragment first, then decode percent escapes once. - assert_eq!(resolve("ppt/slides", "../media/a%23b.png#ignored"), "ppt/media/a#b.png"); - assert_eq!(resolve("ppt/slides", "%252e%252e/a"), "ppt/slides/%2e%2e/a"); - assert_eq!(resolve("ppt/slides", "%2e%2e/%2e%2e/%2e%2e/a"), "a"); - } - - #[test] - fn resolve_keeps_encoded_hash_and_strips_fragment() { - assert_eq!(resolve("ppt/slides", "../media/a%23b.png"), "ppt/media/a#b.png"); - assert_eq!(resolve("ppt/slides", "../media/a.png#frag"), "ppt/media/a.png"); - } - - #[test] - fn resolve_percent_decode_requires_two_hex_digits() { - assert_eq!(resolve("ppt/slides", "../media/a%+5b.png"), "ppt/media/a%+5b.png"); - assert_eq!(resolve("ppt/slides", "../media/a%20b.png"), "ppt/media/a b.png"); - } - - fn zip_of(entries: &[(&str, usize)]) -> Vec { - let mut zw = zip::ZipWriter::new(Cursor::new(Vec::new())); - let o = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated); - for (name, len) in entries { - zw.start_file(*name, o).unwrap(); - zw.write_all(&vec![b'x'; *len]).unwrap(); - } - zw.finish().unwrap().into_inner() - } - - #[test] - fn discarded_parts_count_against_the_inflate_budget() { - // Kept bytes cap at 100: b, c and d are inflated past what's left and discarded. That - // work is charged, so after d the budget (130) is spent and e is not read, although it - // would have fit. - let z = zip_of(&[("a", 80), ("b", 80), ("c", 80), ("d", 80), ("e", 5)]); - let p = Package::open_within(&z, 1000, 100, 130).unwrap(); - assert!(p.get("a").is_some()); - assert!(p.get("b").is_none() && p.get("d").is_none()); - assert!(p.get("e").is_none(), "the inflate budget stops reading"); - // With room to spare the same small part is kept. - let p = Package::open_within(&z, 1000, 100, 10_000).unwrap(); - assert!(p.get("e").is_some()); - } - - #[test] - fn many_relationships_are_found_by_index_and_first_id_wins() { - let n = 50_000; - let mut x = String::from(r#""#); - for i in 0..n { - x.push_str(&format!(r#""#)); - } - x.push_str(&format!(r#""#)); - let rels = rels_from_bytes(x.as_bytes(), "ppt/slides/slide1.xml"); - assert_eq!(rels.target("rId0"), Some("ppt/media/image0.png"), "the first of a repeated id wins"); - assert!((0..n).all(|i| rels.target(&format!("rId{i}")) == Some(&*format!("ppt/media/image{i}.png")))); - - let mut out = RelsOut::default(); - let ids: Vec = (0..n).map(|i| out.add("hyperlink", &format!("https://example.com/{i}"), true)).collect(); - assert_eq!(out.add("hyperlink", "https://example.com/7", true), ids[7], "an identical target reuses its id"); - assert_eq!(out.add("hyperlink", "https://example.com/7", false), format!("rId{}", n + 1), "internal is distinct"); - let fresh = out.add_new("image", "../media/a.png", false); - assert_ne!(out.add_new("image", "../media/a.png", false), fresh); - assert_eq!(out.add("image", "../media/a.png", false), fresh, "add reuses the first add_new made"); - } - - #[test] - fn backslash_zip_entry_names_are_found() { - let z = zip_of(&[("PPT\\Slides\\Slide1.xml", 3)]); - let p = Package::open(&z).unwrap(); - assert!(p.get("ppt/slides/slide1.xml").is_some()); - assert_eq!(p.original_name("ppt/slides/slide1.xml"), Some("PPT/Slides/Slide1.xml")); - } - - #[test] - fn xml_bytes_applies_the_xml_limit() { - let z = zip_of(&[("small.xml", 10)]); - let p = Package::open(&z).unwrap(); - assert_eq!(p.xml_bytes("small.xml").map(<[u8]>::len), Some(10)); - assert!(p.xml_bytes("missing.xml").is_none()); - } - - #[test] - fn resolve_backslash_target() { - assert_eq!(resolve("ppt/slides", "..\\media\\image1.png"), "ppt/media/image1.png"); - assert_eq!(resolve("ppt/slides", "\\ppt\\media\\a.png"), "ppt/media/a.png"); - } - - #[test] - fn path_resolution() { - assert_eq!(resolve("ppt/slides", "../media/image1.png"), "ppt/media/image1.png"); - assert_eq!(resolve("ppt", "slides/slide1.xml"), "ppt/slides/slide1.xml"); - assert_eq!(resolve("ppt/slides", "/ppt/media/a%20b.png"), "ppt/media/a b.png"); - assert_eq!(resolve("", "../../../x.xml"), "x.xml"); - assert_eq!(rels_path("ppt/presentation.xml"), "ppt/_rels/presentation.xml.rels"); - assert_eq!(rels_path("[Content_Types].xml"), "_rels/[Content_Types].xml.rels"); - assert_eq!(relative("ppt/slides/slide1.xml", "ppt/media/image1.png"), "../media/image1.png"); - assert_eq!(relative("ppt/presentation.xml", "ppt/slides/slide1.xml"), "slides/slide1.xml"); - assert_eq!(relative("ppt/slides/slide1.xml", "ppt/slides/slide2.xml"), "slide2.xml"); - } - - #[test] - fn sidecar_parts_stay_inside_chart_folders() { - assert!(sidecar_part("ppt/embeddings/Microsoft_Excel_Worksheet1.xlsx")); - assert!(sidecar_part("ppt/charts/style1.xml")); - assert!(sidecar_part("ppt/drawings/chartDrawing1.xml")); - assert!(sidecar_part("ppt/media/image1.png")); - assert!(!sidecar_part("ppt/charts/chart1.xml")); - assert!(!sidecar_part("ppt/charts/_rels/chart1.xml.rels")); - assert!(!sidecar_part("ppt/slides/slide1.xml")); - assert!(!sidecar_part("ppt/embeddings/../../ppt/slides/slide1.xml")); - assert!(!sidecar_part("/etc/passwd")); - } -} diff --git a/crates/pptx/src/png.rs b/crates/pptx/src/png.rs deleted file mode 100644 index 6f770bd29..000000000 --- a/crates/pptx/src/png.rs +++ /dev/null @@ -1,33 +0,0 @@ -//! The placeholder image written when a picture's media is missing: a 1×1 fully transparent RGBA -//! PNG, kept as its fixed bytes (signature, IHDR, one stored-deflate IDAT scanline, IEND) so the -//! app carries no PNG encoder of its own. - -/// The PNG file, byte for byte what the former local encoder produced. -const TRANSPARENT_1X1: [u8; 73] = [ - 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, - 0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x10, 0x49, 0x44, 0x41, 0x54, 0x78, 0x01, 0x01, 0x05, 0x00, 0xFA, 0xFF, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x01, 0x64, 0x78, 0x95, 0x38, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, - 0x82, -]; - -/// A 1×1 fully transparent RGBA PNG. -pub fn transparent_1x1() -> Vec { - TRANSPARENT_1X1.to_vec() -} - -#[cfg(test)] -mod tests { - #![allow(clippy::unwrap_used)] - - #[test] - fn placeholder_is_a_transparent_1x1_png() { - let png = super::transparent_1x1(); - assert!(png.starts_with(b"\x89PNG\r\n\x1a\n")); - // IHDR: 1×1, 8-bit RGBA, no interlace. - assert_eq!(&png[12..16], b"IHDR"); - assert_eq!(&png[16..29], &[0, 0, 0, 1, 0, 0, 0, 1, 8, 6, 0, 0, 0]); - assert!(png.ends_with(b"IEND\xAE\x42\x60\x82")); - // The stored scanline: filter byte 0, then one pixel with zero alpha. - assert_eq!(&png[49..54], &[0, 0, 0, 0, 0]); - } -} diff --git a/crates/pptx/src/read.rs b/crates/pptx/src/read.rs deleted file mode 100644 index f781dbc6d..000000000 --- a/crates/pptx/src/read.rs +++ /dev/null @@ -1,1788 +0,0 @@ -//! PPTX import: package → [`Presentation`]. - -pub(crate) mod chart; -mod chartex; -pub(crate) mod dml; -mod shapes; -mod theme; -mod timing; - -pub(crate) use chart::{chart_from as chart_from_el, read_chart_xml}; -pub(crate) use chartex::{chartex_from, read_chartex_xml}; - -use std::cell::Cell; -use std::collections::{HashMap, HashSet}; -use std::sync::Arc; - -use deckcraft_geom::{Size, emu_to_pt}; -use deckcraft_model::text::TextBody; -use deckcraft_model::{ - Background, Comment, CustomShow, EmbeddedFont, Geom, HeaderFooter, Layout, LayoutId, LayoutType, Master, MasterId, MediaId, MediaItem, PhType, - Presentation, Properties, Section, ShowSettings, Slide, SlideId, defaults, -}; - -use crate::PptxError; -use crate::opc::{self, Package, Rels}; -use crate::xml::{Doc, El, Node}; - -/// A snapshot of the import state a discarded read rolls back to. -pub struct Mark { - diagram_xml_bytes: usize, - media: usize, - media_keys: usize, - tag_bytes: usize, - tags_capped: bool, - kept_sidecar_bytes: usize, - kept_chart_keys: usize, -} - -/// Import state shared by all parts. -pub struct Imp<'a> { - pub pkg: &'a Package, - pub media: Vec, - pub media_by_part: HashMap, - /// Keys added to `media_by_part`, in order, so a rollback removes only its own. - pub media_keys: Vec, - pub next: u32, - pub slide_by_part: HashMap, - pub custom_show_names: HashMap, - /// GUIDs (upper case) of the table styles the file defines. - pub table_style_ids: Vec, - /// Per legacy VML drawing part: shape id → preview picture part (see `shapes::vml_preview`). - pub vml_previews: HashMap>, - /// Aggregate byte count of retained chart sidecars across the presentation. - pub kept_sidecar_bytes: usize, - /// Data slots of the charts decoded so far (see `chart::MAX_PRESENTATION_CHART_POINTS`). - pub chart_points: usize, - /// Points the presentation may hold across modelled charts. - pub chart_points_cap: usize, - /// Cached kept sidecars by normalized chart part name. - pub kept_charts: HashMap, - /// Keys added to `kept_charts`, in order, for rollback. - pub kept_chart_keys: Vec, - /// Chart parts whose sidecar capture was refused, with the retained-byte total it started from: - /// the same start gives the same refusal, so the copy is not repeated. - pub rejected_kept: HashMap, - /// Bytes of chart parts decoded so far, rejected ones included (see `chart::MAX_CHART_DECODE_BYTES`). - pub chart_decode_bytes: usize, - /// Add-in tags parts, parsed once each, by normalized part name. - pub tags_by_part: HashMap>, - /// Bytes of tags copied into the model so far (see [`MAX_TAG_BYTES`]). - pub tag_bytes: usize, - /// The tag budget ran out and the warning was given. - pub tags_capped: bool, - /// What the file lost that the reader kept going past (see [`MAX_IMPORT_WARNINGS`]). - pub warnings: Vec, - /// Bytes of preserved theme XML kept by the masters read so far. - pub theme_extra_bytes: usize, - /// Shapes read from SmartArt drawings so far (see `shapes::MAX_SMARTART_SHAPES`). - pub smartart_shapes: usize, - /// Bytes of SmartArt layout, style and colour definitions copied into diagrams so far. - pub diagram_xml_bytes: usize, - /// Whether a part has relationships of its own, by normalized part name: looked up once - /// however many embedded objects point at the part. - pub has_rels: HashMap, -} - -/// Import warnings kept; a hostile file with many oversized tables adds no more than this. -const MAX_IMPORT_WARNINGS: usize = 32; - -impl Imp<'_> { - /// Record something the file lost, and log it. - pub fn warn(&mut self, msg: String) { - log::warn!("pptx: {msg}"); - if self.warnings.len() < MAX_IMPORT_WARNINGS { - self.warnings.push(msg); - } - } - pub fn alloc(&mut self) -> u32 { - self.next = self.next.saturating_add(1); - self.next - } - /// Media item for an internal part, read once. - pub fn media_for(&mut self, part: &str) -> Option { - let key = opc::norm(part); - if let Some(m) = self.media_by_part.get(&key) { - return Some(*m); - } - let data = self.pkg.get(part)?.to_vec(); - let name = opc::file_of(self.pkg.original_name(part).unwrap_or(part)).to_string(); - let content_type = self.pkg.content_type(part).filter(|c| !c.is_empty()).unwrap_or_else(|| crate::mime_for(&name).to_string()); - let id = MediaId(self.alloc()); - self.media.push(MediaItem { id, name, content_type, data: Arc::new(data), link: None }); - self.media_keys.push(key.clone()); - self.media_by_part.insert(key, id); - Some(id) - } - /// What a discarded read must give back: the budgets it charged and the media and kept-chart - /// entries it added (see [`Imp::rollback`]). - pub fn mark(&self) -> Mark { - Mark { - diagram_xml_bytes: self.diagram_xml_bytes, - media: self.media.len(), - media_keys: self.media_keys.len(), - tag_bytes: self.tag_bytes, - tags_capped: self.tags_capped, - kept_sidecar_bytes: self.kept_sidecar_bytes, - kept_chart_keys: self.kept_chart_keys.len(), - } - } - /// Undo everything since `m`: only the entries added since are removed, so the cost follows - /// what the discarded read added, not the size of the caches. - pub fn rollback(&mut self, m: &Mark) { - self.diagram_xml_bytes = m.diagram_xml_bytes; - self.tag_bytes = m.tag_bytes; - self.tags_capped = m.tags_capped; - self.kept_sidecar_bytes = m.kept_sidecar_bytes; - self.media.truncate(m.media); - for k in self.media_keys.drain(m.media_keys..) { - self.media_by_part.remove(&k); - } - for k in self.kept_chart_keys.drain(m.kept_chart_keys..) { - self.kept_charts.remove(&k); - } - // Chart decode work (`chart_decode_bytes`, `chart_points`) stays charged: it was done, and - // giving it back would let a discarded read repeat it. `rejected_kept` is keyed by the - // retained total a refusal started from, so it stays valid after the rollback. - } - /// Media item for an external link. - pub fn media_link(&mut self, url: &str) -> MediaId { - if let Some(m) = self.media.iter().find(|m| m.link.as_deref() == Some(url)) { - return m.id; - } - let id = MediaId(self.alloc()); - let name = url.rsplit('/').next().unwrap_or(url).to_string(); - let content_type = crate::mime_for(&name).to_string(); - self.media.push(MediaItem { id, name, content_type, data: Arc::new(vec![]), link: Some(url.to_string()) }); - id - } -} - -/// One part being read: its name, relationships and root namespace declarations. -pub struct Part { - pub name: String, - pub rels: Rels, - pub ns: Vec<(String, String)>, - /// Prefixes bound below the root only (on a wrapper such as `mc:Choice`), each to one namespace. - pub inner_ns: Vec<(String, String)>, - /// Bytes of namespace declarations this part may still copy onto kept fragments. - ns_budget: Cell, -} - -impl Part { - pub fn new(pkg: &Package, name: &str, doc: &Doc) -> Self { - let ns = doc.ns_decls(); - Part { name: name.to_string(), rels: pkg.rels(name), inner_ns: inner_decls(&doc.root, &ns), ns, ns_budget: Cell::new(MAX_COPIED_NS_BYTES) } - } - /// Serialize an element with the namespace declarations it needs from the part root. - pub fn keep(&self, el: &El) -> String { - keep_with(el, &[&self.ns], Some(&self.ns_budget)) - } - /// Like [`Part::keep`], also declaring prefixes that only an enclosing wrapper binds. - pub fn keep_inner(&self, el: &El) -> String { - keep_with(el, &[&self.ns, &self.inner_ns], Some(&self.ns_budget)) - } -} - -/// Prefixes declared below the root but not on it, skipping any bound to different namespaces. -fn inner_decls(root: &El, ns: &[(String, String)]) -> Vec<(String, String)> { - fn rec(e: &El, out: &mut Vec<(String, String)>, out_map: &mut HashMap, clash: &mut HashSet, depth: usize) { - if depth > crate::xml::MAX_DEPTH { - return; - } - for (k, v) in e.attrs.iter().filter(|(k, _)| k.starts_with("xmlns:")) { - if let Some(existing) = out_map.get(k) { - if existing != v { - clash.insert(k.clone()); - } - } else if out.len() < 1000 { - out_map.insert(k.clone(), v.clone()); - out.push((k.clone(), v.clone())); - } - } - for c in e.elements() { - rec(c, out, out_map, clash, depth + 1); - } - } - let mut out = vec![]; - let mut out_map = HashMap::new(); - let mut clash = HashSet::new(); - let root_ns: HashSet<&str> = ns.iter().map(|(r, _)| r.as_str()).collect(); - for c in root.elements() { - rec(c, &mut out, &mut out_map, &mut clash, 1); - } - out.retain(|(k, _)| !clash.contains(k) && !root_ns.contains(k.as_str())); - out -} - -/// Longest namespace name copied onto a kept fragment or a resolved `mc` branch. Real ones are -/// URIs of well under 100 bytes; a longer one is not copied, so one declaration cannot be -/// multiplied by every fragment that uses its prefix. -const MAX_NS_VALUE: usize = 2048; - -/// Namespace declaration bytes one part may copy onto all its kept fragments together; past it a -/// fragment keeps its markup but is not given further declarations. -const MAX_COPIED_NS_BYTES: usize = 8 << 20; - -/// Prefixes `el` and its descendants use in element and attribute names, and those listed in -/// `mc:Ignorable` or `mc:MustUnderstand` (which must stay declared for the markup-compatibility rules to hold), -/// and those starting a QName-like attribute value. -fn used_prefixes(el: &El) -> HashSet<&str> { - fn rec<'a>(e: &'a El, used: &mut HashSet<&'a str>, depth: usize) { - if depth > crate::xml::MAX_DEPTH { - return; - } - if let Some((p, _)) = e.name.split_once(':') { - used.insert(p); - } - for (k, v) in &e.attrs { - if let Some((p, local)) = k.split_once(':') - && p != "xmlns" - && p != "xml" - { - used.insert(p); - if local == "Ignorable" || local == "MustUnderstand" { - used.extend(v.split_whitespace()); - } - } - // QName-valued attributes (`xsi:type="q:Item"`) need their prefix declared too. - if k != "xmlns" && !k.starts_with("xmlns:") { - for t in v.split_whitespace() { - if let Some((p, _)) = t.split_once(':') - && !p.is_empty() - { - used.insert(p); - } - } - } - } - for c in e.elements() { - rec(c, used, depth + 1); - } - } - let mut used = HashSet::new(); - rec(el, &mut used, 0); - used -} - -/// Serialize `el`, declaring every prefix it uses that the source root declared. -pub fn keep_xml(el: &El, ns: &[(String, String)]) -> String { - keep_with(el, &[ns], None) -} - -fn keep_with(el: &El, decls: &[&[(String, String)]], budget: Option<&Cell>) -> String { - let used = used_prefixes(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 cost = k.len() + v.len(); - if let Some(b) = budget { - if b.get() < cost { - continue; - } - b.set(b.get() - cost); - } - have.insert(k); - extra.push((k.clone(), v.clone())); - } - } - let mut el = el.clone(); - el.attrs.extend(extra); - el.to_xml() -} - -/// Namespace prefixes whose `mc:Choice` content we understand. -const SUPPORTED_MC: [&str; 10] = ["p14", "p15", "p159", "a14", "a16", "p1510", "a15", "c14", "p188", "cx1"]; - -/// Office 2016 charts sit in a `cx1` choice; take it only for a layout DeckCraft reads (the -/// fallback is a picture or "this chart isn't available" text). The part is checked later, when -/// the frame is read, so here only the namespace counts. -fn chartex_readable(ch: &El) -> bool { - let mut found = vec![]; - ch.find_all("graphicData", &mut found); - found.iter().any(|g| g.attr("uri").is_some_and(|u| u.ends_with("/chartex"))) -} - -/// A relationship to an embedded 3-D model (`.glb`). -pub(crate) fn is_model3d(rel: &opc::Rel) -> bool { - !rel.external && (rel.kind == "model3d" || rel.target.to_ascii_lowercase().ends_with(".glb")) -} - -fn choice_has_model3d(el: &El, rels: &Rels) -> bool { - fn rec(el: &El, rels: &Rels, depth: usize) -> bool { - if depth > 16 { - return false; - } - if el.is("contentPart") - && let Some(id) = el.attr("r:id").filter(|s| !s.is_empty()) - && rels.get(id).is_some_and(is_model3d) - { - return true; - } - el.elements().any(|c| rec(c, rels, depth + 1)) - } - rec(el, rels, 0) -} - -/// Bytes of tags one import copies into the model, every tags part and reference together: a -/// small compressed tags part listed by many shapes, or many times by one, must not grow without -/// bound (#1164). The package budgets (`opc::MAX_XML_PART`, `MAX_TOTAL`, #1283) bound what is -/// parsed; this bounds what is copied from it. -pub const MAX_TAG_BYTES: usize = 64 << 20; -/// What each copied pair costs besides its text, so empty pairs count too. -const TAG_PAIR_COST: usize = std::mem::size_of::<(String, String)>(); - -/// Add-in tags named by `holder`'s `p:custDataLst`: the name/value pairs of each tags part. -/// Each part is parsed once per import and counted once per holder. Once [`MAX_TAG_BYTES`] is -/// reached, no further tag parts are parsed or cached (#1164). -pub fn tags(imp: &mut Imp, part: &Part, holder: &El) -> Vec<(String, String)> { - if imp.tags_capped { - return vec![]; - } - let Some(list) = holder.child("custDataLst") else { return vec![] }; - let mut out = Vec::new(); - let mut seen = HashSet::new(); - for t in list.children_named("tags").take(100) { - if imp.tags_capped { - return out; - } - let Some(target) = t.attr("r:id").and_then(|id| part.rels.get(id)).map(|r| opc::norm(&r.target)) else { continue }; - if !seen.insert(target.clone()) { - continue; - } - let parsed = match imp.tags_by_part.get(&target) { - Some(p) => p.clone(), - None => { - if imp.tags_capped { - return out; - } - let p: Arc<[(String, String)]> = imp - .pkg - .xml(&target) - .map(|doc| { - doc.root - .children_named("tag") - .take(10_000) - .filter_map(|tag| Some((tag.attr("name")?.to_string(), tag.attr("val").unwrap_or("").to_string()))) - .collect() - }) - .unwrap_or_default(); - imp.tags_by_part.insert(target, p.clone()); - p - } - }; - for (name, val) in parsed.iter() { - let n = imp.tag_bytes.saturating_add(TAG_PAIR_COST + name.len() + val.len()); - if n > MAX_TAG_BYTES { - if !imp.tags_capped { - log::warn!("pptx: add-in tags over {MAX_TAG_BYTES} bytes; the rest are dropped"); - imp.tags_capped = true; - } - return out; - } - imp.tag_bytes = n; - out.push((name.clone(), val.clone())); - } - } - out -} - -/// Relationship types whose parts are kept verbatim, and whether they hang off the package root. -const KEPT_RELS: [(&str, bool); 3] = [ - ("http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml", false), - ("http://schemas.microsoft.com/office/2020/02/relationships/classificationlabels", true), - ("http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties", true), -]; - -/// A part we may keep: outside `ppt/` and the properties the writer makes itself. -fn keepable(name: &str) -> bool { - let n = name.to_ascii_lowercase(); - !n.is_empty() - && !n.contains("..") - && !n.starts_with("ppt/") - && n != "docprops/core.xml" - && n != "docprops/app.xml" - && !n.starts_with("[content_types]") -} - -/// Custom XML data, sensitivity labels and custom properties, with the parts they relate to -/// (`itemProps`) and their relationships parts, as written. -fn kept_parts(pkg: &Package, pres_path: &str) -> Vec { - use deckcraft_model::KeptPart; - let mut out: Vec = Vec::new(); - let text = |name: &str| pkg.get(name).and_then(|b| std::str::from_utf8(b).ok()).map(str::to_string); - for (holder, from_root) in [("", true), (pres_path, false)] { - let Some(doc) = pkg.xml(&opc::rels_path(holder)) else { continue }; - let base = opc::dir_of(holder); - for r in doc.root.children_named("Relationship") { - let (Some(ty), Some(target)) = (r.attr("Type"), r.attr("Target")) else { continue }; - if r.attr("TargetMode").is_some_and(|m| m.eq_ignore_ascii_case("external")) - || !KEPT_RELS.iter().any(|(t, root)| *t == ty && *root == from_root) - { - continue; - } - let name = opc::resolve(&base, target); - if !keepable(&name) || out.iter().any(|k| k.name.eq_ignore_ascii_case(&name)) || out.len() >= 400 { - continue; - } - let Some(xml) = text(&name) else { continue }; - out.push(KeptPart { - content_type: pkg.content_type(&name).unwrap_or_default(), - name: name.clone(), - xml, - rel_type: ty.to_string(), - from_root, - }); - // The part's own relationships (customXml item → itemProps) and their targets. - let rp = opc::rels_path(&name); - if let Some(rels_xml) = text(&rp) { - let mut capped = false; - for sub in pkg.rels(&name).items.iter().filter(|s| !s.external && keepable(&s.target)) { - // Checked before the part is read: repeated relationships to one large part - // must not copy it again each time. - if out.iter().any(|k| k.name.eq_ignore_ascii_case(&sub.target)) { - continue; - } - if out.len() >= 400 { - capped = true; - continue; - } - if let Some(x) = text(&sub.target) { - out.push(KeptPart { - content_type: pkg.content_type(&sub.target).unwrap_or_default(), - name: sub.target.clone(), - xml: x, - ..Default::default() - }); - } - } - if !capped && out.len() < 400 { - out.push(KeptPart { name: rp, xml: rels_xml, ..Default::default() }); - } - } - } - } - out -} - -/// Replace every `mc:AlternateContent` by the children of the branch we can read best. -/// A 3-D model choice is left in place (even when its `Requires` prefix is not one we otherwise -/// understand) so the shape reader can keep the model and its fallback picture. Ink content parts -/// still fall through to the fallback picture. -pub fn resolve_mc(el: &mut El, depth: usize) { - resolve_mc_rels(el, depth, None); -} - -fn resolve_mc_rels(el: &mut El, depth: usize, rels: Option<&Rels>) { - if depth > crate::xml::MAX_DEPTH { - return; - } - if el.children.iter().any(|c| matches!(c, Node::El(e) if e.is("AlternateContent"))) { - let mut out = Vec::with_capacity(el.children.len()); - for c in std::mem::take(&mut el.children) { - match c { - Node::El(ac) if ac.is("AlternateContent") => { - if rels.is_some_and(|rels| ac.children_named("Choice").any(|ch| choice_has_model3d(ch, rels))) { - out.push(Node::El(ac)); - continue; - } - let choice = ac.children_named("Choice").find(|ch| { - let req_ok = ch.attr("Requires").unwrap_or("").split_whitespace().all(|r| SUPPORTED_MC.contains(&r)); - // Ink content parts are not modelled; prefer their fallback picture. - let modelled = !ch.elements().any(|e| e.is("contentPart")) - && (!ch.attr("Requires").unwrap_or("").contains("cx1") || chartex_readable(ch)); - req_ok && modelled - }); - let branch = choice.or_else(|| ac.child("Fallback")); - if let Some(b) = branch { - // The branch's namespace declarations (the first usable one of each name, - // in order), indexed by prefix once: each child then looks up the prefixes - // it uses instead of scanning every declaration. - let mut decls: Vec<(&String, &String)> = Vec::new(); - // An oversized declaration still shadows an outer one of its name: its - // content is left unbound rather than bound to the outer namespace. - let mut by_prefix: HashMap<&str, Option> = HashMap::new(); - for (k, v) in b.attrs.iter().chain(ac.attrs.iter()) { - let prefix = if k == "xmlns" { Some("") } else { k.strip_prefix("xmlns:") }; - if let Some(p) = prefix - && !by_prefix.contains_key(p) - { - by_prefix.insert(p, (v.len() <= MAX_NS_VALUE).then_some(decls.len())); - if v.len() <= MAX_NS_VALUE { - decls.push((k, v)); - } - } - } - for n in &b.children { - if let Node::El(e) = n { - // Carry the namespace declarations from the branch that its content - // uses (all of them per child made children x declarations copies). - let used = used_prefixes(e); - let have: HashSet<&str> = e.attrs.iter().map(|(a, _)| a.as_str()).collect(); - let mut wanted: Vec = std::iter::once("") - .chain(used.iter().copied()) - .filter_map(|p| by_prefix.get(p).copied().flatten()) - .filter(|&i| !have.contains(decls[i].0.as_str())) - .collect(); - wanted.sort_unstable(); - wanted.dedup(); - let mut e = e.clone(); - e.attrs.extend(wanted.into_iter().map(|i| (decls[i].0.clone(), decls[i].1.clone()))); - out.push(Node::El(e)); - } - } - } - } - other => out.push(other), - } - } - el.children = out; - } - for c in el.elements_mut() { - resolve_mc_rels(c, depth + 1, rels); - } -} - -fn load(pkg: &Package, name: &str) -> Option { - let mut d = pkg.xml(name)?; - let rels = pkg.rels(name); - resolve_mc_rels(&mut d.root, 0, Some(&rels)); - Some(d) -} - -fn max_cnvpr(el: &El, m: &mut u32) { - let mut v = vec![]; - el.find_all("cNvPr", &mut v); - for c in v { - if let Some(id) = c.u32("id") - && id < shapes::MAX_KEPT_ID - { - *m = (*m).max(id); - } - } -} - -/// The theme of a `.thmx` theme file (its `officeDocument` is a theme part), or of the first -/// master of a `.pptx` / `.potx`, with the media its format scheme uses (ids from 1). -pub fn import_theme(bytes: &[u8]) -> Result<(deckcraft_model::theme::Theme, Vec), PptxError> { - let pkg = Package::open(bytes)?; - let target = pkg.rels("").first_of("officeDocument").map(|r| r.target.clone()); - let theme_path = match &target { - Some(t) if pkg.xml(t).is_some_and(|d| d.root.is("theme")) => t.clone(), - _ => { - // A presentation: its first master's theme. - let pres = target.unwrap_or_else(|| "ppt/presentation.xml".into()); - let pres_doc = load(&pkg, &pres).ok_or_else(|| PptxError::NotPptx("neither a theme nor a presentation".into()))?; - let pres_part = Part::new(&pkg, &pres, &pres_doc); - let master = pres_doc - .root - .child("sldMasterIdLst") - .and_then(|l| l.children_named("sldMasterId").next()) - .and_then(|m| pres_part.rels.target(m.attr("r:id").unwrap_or("")).map(String::from)) - .or_else(|| pres_part.rels.all_of("slideMaster").next().map(|r| r.target.clone())) - .ok_or_else(|| PptxError::NotPptx("the presentation has no slide master".into()))?; - pkg.rels(&master).first_of("theme").map(|r| r.target.clone()).ok_or_else(|| PptxError::NotPptx("the slide master has no theme".into()))? - } - }; - let doc = load(&pkg, &theme_path).ok_or_else(|| PptxError::NotPptx(format!("missing or unreadable {theme_path}")))?; - if !doc.root.is("theme") { - return Err(PptxError::NotPptx(format!("{theme_path} is not a theme part"))); - } - let mut imp = Imp { - pkg: &pkg, - media: vec![], - media_by_part: HashMap::new(), - media_keys: vec![], - next: 0, - slide_by_part: HashMap::new(), - custom_show_names: HashMap::new(), - table_style_ids: Vec::new(), - vml_previews: HashMap::new(), - kept_sidecar_bytes: 0, - chart_points: 0, - chart_points_cap: chart::MAX_PRESENTATION_CHART_POINTS, - kept_charts: HashMap::new(), - kept_chart_keys: vec![], - rejected_kept: HashMap::new(), - chart_decode_bytes: 0, - tags_by_part: HashMap::new(), - tag_bytes: 0, - tags_capped: false, - warnings: vec![], - theme_extra_bytes: 0, - smartart_shapes: 0, - diagram_xml_bytes: 0, - has_rels: HashMap::new(), - }; - let part = Part::new(&pkg, &theme_path, &doc); - let theme = theme::read_theme(&mut imp, &part, &doc.root); - Ok((theme, imp.media)) -} - -pub fn import(bytes: &[u8]) -> Result { - import_checked(bytes).map(|(p, _)| p) -} - -/// [`import`], plus the slides the file's slide list names but that couldn't be read (a missing -/// or truncated slide part, or an entry whose relationship is missing): those slides are left -/// out, so a caller can say so (#203). -pub fn import_checked(bytes: &[u8]) -> Result<(Presentation, Vec), PptxError> { - import_report(bytes).map(|(p, lost, _)| (p, lost)) -} - -/// [`import_checked`], plus warnings for content the file had that was cut to fit a limit (a -/// table past the cell cap keeps its leading rows). -pub fn import_report(bytes: &[u8]) -> Result<(Presentation, Vec, Vec), PptxError> { - import_report_with_chart_points(bytes, chart::MAX_PRESENTATION_CHART_POINTS) -} - -const MAX_SLIDE_ENTRIES: usize = 10_000; - -/// [`import_checked`] with the presentation's chart point budget set (tests lower it). -pub(crate) fn import_with_chart_points(bytes: &[u8], chart_points_cap: usize) -> Result<(Presentation, Vec), PptxError> { - import_report_with_chart_points(bytes, chart_points_cap).map(|(p, lost, _)| (p, lost)) -} - -/// [`import_report`] with the presentation's chart point budget set. -fn import_report_with_chart_points(bytes: &[u8], chart_points_cap: usize) -> Result<(Presentation, Vec, Vec), PptxError> { - let mut lost_slides: Vec = vec![]; - let pkg = Package::open(bytes)?; - let root_rels = pkg.rels(""); - let pres_path = root_rels.first_of("officeDocument").map(|r| r.target.clone()).unwrap_or_else(|| "ppt/presentation.xml".into()); - let pres_doc = load(&pkg, &pres_path).ok_or_else(|| PptxError::NotPptx(format!("missing or unreadable {pres_path}")))?; - let pres_el = &pres_doc.root; - if !pres_el.is("presentation") { - return Err(PptxError::NotPptx(format!("{pres_path} is not a presentation part"))); - } - // Refuse an oversized list before reading slide parts: truncating it would look like a - // complete import and allow a later save to overwrite the omitted slides (#1910). - // Looking only for the first entry past the cap keeps this check bounded. - if pres_el.child("sldIdLst").is_some_and(|list| list.children_named("sldId").nth(MAX_SLIDE_ENTRIES).is_some()) { - return Err(PptxError::Unsupported(format!("PPTX slide list exceeds the {MAX_SLIDE_ENTRIES}-entry import limit"))); - } - let pres_part = Part::new(&pkg, &pres_path, &pres_doc); - - let (master_paths, slide_entries) = master_and_slide_paths(pres_el, &pres_part, &mut lost_slides); - let (docs, max_id) = load_part_docs(&pkg, &master_paths, &slide_entries); - - let mut imp = Imp { - pkg: &pkg, - media: vec![], - media_by_part: HashMap::new(), - media_keys: vec![], - next: max_id.max(1), - slide_by_part: HashMap::new(), - custom_show_names: HashMap::new(), - table_style_ids: Vec::new(), - vml_previews: HashMap::new(), - kept_sidecar_bytes: 0, - chart_points: 0, - chart_points_cap, - kept_charts: HashMap::new(), - kept_chart_keys: vec![], - rejected_kept: HashMap::new(), - chart_decode_bytes: 0, - tags_by_part: HashMap::new(), - tag_bytes: 0, - tags_capped: false, - warnings: vec![], - theme_extra_bytes: 0, - smartart_shapes: 0, - diagram_xml_bytes: 0, - has_rels: HashMap::new(), - }; - // Slide ids first so hyperlinks anywhere can point at slides. - let slide_ids = register_slides(&mut imp, &docs, &slide_entries, &mut lost_slides); - read_custom_show_names(&mut imp, pres_el); - - let mut p = defaults::blank_presentation(defaults::WIDE, Default::default(), false); - p.masters.clear(); - p.media.clear(); - p.default_text_style = Default::default(); - - read_presentation_settings(&mut imp, &mut p, &pres_part, pres_el); - let layout_by_part = read_masters(&mut imp, &mut p, &master_paths, &docs); - let file_slide_ids = read_slides(&mut imp, &mut p, &pres_part, &docs, &slide_ids, &layout_by_part); - read_sections(&mut p, &pres_part, pres_el, &file_slide_ids); - p.tags = tags(&mut imp, &pres_part, pres_el); - read_custom_shows(&mut p, &imp, &pres_part, pres_el); - read_guides_and_show(&mut p, &imp, &pres_part); - read_notes_master(&mut imp, &mut p, &pres_part); - read_handout_master(&mut imp, &mut p, &pres_part); - read_document_properties(&mut p, &pkg, &root_rels); - - p.kept_parts = kept_parts(&pkg, &pres_path); - - inherit_placeholder_geometry(&mut p); - default_text_anchor(&mut p); - p.header_footer = header_footer(&p); - p.embedded_fonts = read_embedded_fonts(&mut imp, &pres_part, pres_el); - p.media = std::mem::take(&mut imp.media); - p.next_id = imp.next; - p.fix_next_id(); - Ok((p, lost_slides, std::mem::take(&mut imp.warnings))) -} - -/// Masters, layouts and slides to read, in file order and without duplicates: (master paths, -/// (file slide id, slide path)). -fn master_and_slide_paths(pres_el: &El, pres_part: &Part, lost_slides: &mut Vec) -> (Vec, Vec<(u32, String)>) { - let master_paths: Vec = pres_el - .child("sldMasterIdLst") - .map(|l| l.children_named("sldMasterId").filter_map(|m| pres_part.rels.target(m.attr("r:id").unwrap_or(""))).map(String::from).collect()) - .unwrap_or_default(); - let mut master_paths: Vec = - if master_paths.is_empty() { pres_part.rels.all_of("slideMaster").map(|r| r.target.clone()).collect() } else { master_paths }; - let mut slide_entries: Vec<(u32, String)> = pres_el - .child("sldIdLst") - .map(|l| { - l.children_named("sldId") - .take(MAX_SLIDE_ENTRIES) - .filter_map(|s| { - let rid = s.attr("r:id").unwrap_or(""); - let Some(path) = pres_part.rels.target(rid) else { - // A missing relationship still represents a lost slide. Report it so - // the engine opens a repaired copy instead of overwriting the original. - lost_slides.push(format!("slide {} (missing relationship {rid})", s.u32("id").unwrap_or(0))); - return None; - }; - Some((s.u32("id").unwrap_or(0), path.to_string())) - }) - .collect() - }) - .unwrap_or_default(); - let mut seen_masters = HashSet::new(); - master_paths.retain(|m| seen_masters.insert(opc::norm(m))); - let mut seen_slides = HashSet::new(); - slide_entries.retain(|(_, p)| seen_slides.insert(opc::norm(p))); - (master_paths, slide_entries) -} - -/// Loads every master, layout and slide part once. Returns them by normalized path and the -/// largest shape id found in them. -fn load_part_docs(pkg: &Package, master_paths: &[String], slide_entries: &[(u32, String)]) -> (HashMap, u32) { - let mut all_parts: Vec = master_paths.to_vec(); - let mut seen_layouts = HashSet::new(); - for m in master_paths { - for r in pkg.rels(m).all_of("slideLayout") { - let key = opc::norm(&r.target); - if seen_layouts.insert(key) { - all_parts.push(r.target.clone()); - } - } - } - all_parts.extend(slide_entries.iter().map(|(_, p)| p.clone())); - let mut docs: HashMap = HashMap::new(); - let mut max_id = 0u32; - for p in &all_parts { - let key = opc::norm(p); - if docs.contains_key(&key) { - continue; - } - if let Some(d) = load(pkg, p) { - max_cnvpr(&d.root, &mut max_id); - docs.insert(key, d); - } - } - (docs, max_id) -} - -/// Allocates an id for every readable slide; slides that are missing or unreadable are recorded in -/// `lost_slides` and left out. -fn register_slides( - imp: &mut Imp, - docs: &HashMap, - slide_entries: &[(u32, String)], - lost_slides: &mut Vec, -) -> Vec<(u32, String, SlideId)> { - let mut slide_ids: Vec<(u32, String, SlideId)> = vec![]; - for (file_id, path) in slide_entries { - if !docs.contains_key(&opc::norm(path)) { - log::warn!("pptx: slide {path} is missing or unreadable; skipped"); - lost_slides.push(path.clone()); - continue; - } - let id = SlideId(imp.alloc()); - imp.slide_by_part.insert(opc::norm(path), id); - slide_ids.push((*file_id, path.clone(), id)); - } - slide_ids -} - -fn read_custom_show_names(imp: &mut Imp, pres_el: &El) { - if let Some(l) = pres_el.child("custShowLst") { - for cs in l.children_named("custShow") { - if let (Some(id), Some(name)) = (cs.attr("id"), cs.attr("name")) { - imp.custom_show_names.insert(id.to_string(), name.to_string()); - } - } - } -} - -/// Slide and notes size, first slide number, default text style and table styles. -fn read_presentation_settings(imp: &mut Imp, p: &mut Presentation, pres_part: &Part, pres_el: &El) { - if let Some(sz) = pres_el.child("sldSz") { - let w = sz.i64("cx").map(emu_to_pt).unwrap_or(960.0); - let h = sz.i64("cy").map(emu_to_pt).unwrap_or(540.0); - p.slide_size = Size::new(sane_len(w, 960.0), sane_len(h, 540.0)); - } - if let Some(sz) = pres_el.child("notesSz") { - let w = sz.i64("cx").map(emu_to_pt).unwrap_or(540.0); - let h = sz.i64("cy").map(emu_to_pt).unwrap_or(720.0); - p.notes_size = Size::new(sane_len(w, 540.0), sane_len(h, 720.0)); - } - p.first_slide_number = pres_el.u32("firstSlideNum").unwrap_or(1).min(9999); - if let Some(dts) = pres_el.child("defaultTextStyle") { - p.default_text_style = dml::list_style(imp, pres_part, dts); - } - if let Some(r) = pres_part.rels.first_of("tableStyles") - && let Some(d) = load(imp.pkg, &r.target) - { - let part = Part::new(imp.pkg, &r.target, &d); - p.table_styles = table_styles(imp, &part, &d.root); - imp.table_style_ids = p.table_styles.iter().map(|s| s.id.clone()).collect(); - } -} - -/// Reads the slide masters and their layouts; a file without a readable master gets a default one. -fn read_masters(imp: &mut Imp, p: &mut Presentation, master_paths: &[String], docs: &HashMap) -> HashMap { - let mut layout_by_part: HashMap = HashMap::new(); - for mp in master_paths { - let Some(doc) = docs.get(&opc::norm(mp)) else { - log::warn!("pptx: master {mp} missing; skipped"); - continue; - }; - let master = read_master(imp, mp, doc, docs, &mut layout_by_part); - p.masters.push(Arc::new(master)); - } - if p.masters.is_empty() { - log::warn!("pptx: no readable slide master; using a default one"); - let (m, _) = defaults::build_master(p.slide_size, Default::default(), imp.next); - imp.next = imp.next.saturating_add(200); - p.masters.push(Arc::new(m)); - } - layout_by_part -} - -/// Reads every registered slide with its notes and comments. Returns the slide ids by file id. -fn read_slides( - imp: &mut Imp, - p: &mut Presentation, - pres_part: &Part, - docs: &HashMap, - slide_ids: &[(u32, String, SlideId)], - layout_by_part: &HashMap, -) -> HashMap { - let pkg = imp.pkg; - let fallback_layout = p.masters.first().and_then(|m| m.layouts.first()).map(|l| l.id).unwrap_or_default(); - let mut file_slide_ids: HashMap = HashMap::new(); - // A notes or comments part belongs to one slide; one shared by many must not be read (and - // copied) once per slide that names it. - let mut owned_parts: HashSet = HashSet::new(); - for (file_id, path, id) in slide_ids { - let Some(doc) = docs.get(&opc::norm(path)) else { continue }; - let part = Part::new(pkg, path, doc); - let layout = part.rels.first_of("slideLayout").and_then(|r| layout_by_part.get(&opc::norm(&r.target)).copied()).unwrap_or(fallback_layout); - let mut slide = read_slide(imp, &part, doc, *id, layout); - if let Some(notes) = slide_notes(imp, &part, &mut owned_parts) { - slide.notes = notes; - slide.has_notes_slide = true; - } - read_slide_comments(pkg, pres_part, &part, &mut slide, &mut owned_parts); - file_slide_ids.insert(*file_id, *id); - p.slides.push(Arc::new(slide)); - } - file_slide_ids -} - -/// The slide's notes text. A notes part is the notes of the first slide that names it. -fn slide_notes(imp: &mut Imp, part: &Part, owned: &mut HashSet) -> Option { - let n = part.rels.first_of("notesSlide")?; - if !owned.insert(opc::norm(&n.target)) { - log::warn!("pptx: notes part {} is named by more than one slide; kept on the first", n.target); - return None; - } - let pkg = imp.pkg; - let nd = load(pkg, &n.target)?; - let np = Part::new(pkg, &n.target, &nd); - Some(read_notes(imp, &np, &nd.root)) -} - -/// Comments. A modern part and the legacy part can describe the same threads (PowerPoint -/// writes both): the modern one wins, its flattened legacy copy is skipped. -/// Each comments part is read once, for the first slide that names it. -fn read_slide_comments(pkg: &Package, pres_part: &Part, part: &Part, slide: &mut Slide, owned: &mut HashSet) { - let mut parts: Vec<(Doc, bool, bool)> = vec![]; - for c in part.rels.all_of("comments") { - // An already-owned part is not re-read, but its kind still decides modern precedence. - let fresh = owned.insert(opc::norm(&c.target)); - if let Some(cd) = pkg.xml(&c.target) { - // The content type names the modern part; a package that types it only through a - // Default entry instead of an Override is still modern when its root is p188. - let modern = pkg.content_type(&c.target).as_deref() == Some(crate::write::CT_COMMENTS_MODERN) || cd.root.prefix() == "p188"; - parts.push((cd, modern, fresh)); - } - } - let has_modern = parts.iter().any(|(_, m, _)| *m); - for (cd, modern, fresh) in parts { - if !fresh || (has_modern && !modern) { - continue; - } - slide.comments.extend(read_comments(pkg, pres_part, &cd.root, modern)); - } -} - -/// Sections, and the extension elements the model does not understand (kept verbatim). -fn read_sections(p: &mut Presentation, pres_part: &Part, pres_el: &El, file_slide_ids: &HashMap) { - let Some(ext) = pres_el.child("extLst") else { return }; - if let Some(sl) = ext.find("sectionLst") { - for s in sl.children_named("section").take(10_000) { - let slides = s - .child("sldIdLst") - .map(|l| l.children_named("sldId").filter_map(|x| x.u32("id").and_then(|i| file_slide_ids.get(&i).copied())).collect()) - .unwrap_or_default(); - p.sections.push(Section { name: s.attr("name").unwrap_or("").to_string(), slides }); - } - } - let kept: String = - ext.children_named("ext").filter(|e| e.attr("uri") != Some(crate::SECTION_EXT_URI) && !has_rel_refs(e)).map(|e| pres_part.keep(e)).collect(); - if !kept.is_empty() { - p.raw_ext = Some(kept); - } -} - -fn read_custom_shows(p: &mut Presentation, imp: &Imp, pres_part: &Part, pres_el: &El) { - let Some(l) = pres_el.child("custShowLst") else { return }; - for cs in l.children_named("custShow") { - let slides = cs - .child("sldLst") - .map(|l| { - l.children_named("sld") - .filter_map(|s| pres_part.rels.target(s.attr("r:id").unwrap_or(""))) - .filter_map(|t| imp.slide_by_part.get(&opc::norm(t)).copied()) - .collect() - }) - .unwrap_or_default(); - p.custom_shows.push(CustomShow { name: cs.attr("name").unwrap_or("").to_string(), slides }); - } -} - -/// Drawing guides (eighths of a point) and slide show settings. -fn read_guides_and_show(p: &mut Presentation, imp: &Imp, pres_part: &Part) { - let pkg = imp.pkg; - if let Some(r) = pres_part.rels.first_of("viewProps") - && let Some(d) = pkg.xml(&r.target) - && let Some(lst) = d.root.find("slideViewPr").and_then(|v| v.find("guideLst")) - { - p.guides = lst - .children_named("guide") - .filter_map(|g| { - let pos = g.attr("pos").and_then(|v| v.parse::().ok()).unwrap_or(0.0) / 8.0; - pos.is_finite().then_some(deckcraft_model::DrawGuide { vertical: g.attr("orient") != Some("horz"), pos }) - }) - .take(1000) - .collect(); - } - if let Some(r) = pres_part.rels.first_of("presProps") - && let Some(d) = pkg.xml(&r.target) - && let Some(sp) = d.root.child("showPr") - { - p.show = read_show(sp, &imp.custom_show_names); - } -} - -/// Theme, background, shapes and colour map shared by the notes and handout masters. -fn read_aux_master(imp: &mut Imp, part: &Part, doc: &Doc, m: &mut Master) { - let mut ctx = shapes::IdCtx::default(); - if let Some(csld) = doc.root.child("cSld") { - m.background = background(imp, part, csld); - if let Some(tree) = csld.child("spTree") { - m.shapes = shapes::sp_tree(imp, part, &mut ctx, tree, 0); - } - } - if let Some(cm) = doc.root.child("clrMap") { - m.color_map = color_map(cm); - } -} - -/// Reads the part's own theme into the master, if it has one. -fn read_master_theme(imp: &mut Imp, part: &Part, m: &mut Master) -> bool { - let pkg = imp.pkg; - if let Some(t) = part.rels.first_of("theme") - && let Some(td) = pkg.xml(&t.target) - { - let tp = Part::new(pkg, &t.target, &td); - m.theme = theme::read_theme(imp, &tp, &td.root); - return true; - } - false -} - -fn read_notes_master(imp: &mut Imp, p: &mut Presentation, pres_part: &Part) { - let pkg = imp.pkg; - let Some(r) = pres_part.rels.first_of("notesMaster") else { return }; - let Some(d) = load(pkg, &r.target) else { return }; - let part = Part::new(pkg, &r.target, &d); - let mut m = Master { id: MasterId(imp.alloc()), name: "Notes Master".into(), ..Default::default() }; - read_master_theme(imp, &part, &mut m); - read_aux_master(imp, &part, &d, &mut m); - // Notes text styles are the body's list style; slide masters use title/body/other instead. - if let Some(ns) = d.root.child("notesStyle") { - m.body_style = dml::list_style(imp, &part, ns); - } - p.notes_master = Some(Arc::new(m)); -} - -/// Handout master (header, footer, date and slide number for printed handouts). -fn read_handout_master(imp: &mut Imp, p: &mut Presentation, pres_part: &Part) { - let pkg = imp.pkg; - let Some(r) = pres_part.rels.first_of("handoutMaster") else { return }; - let Some(d) = load(pkg, &r.target) else { return }; - let part = Part::new(pkg, &r.target, &d); - let mut m = Master { id: MasterId(imp.alloc()), name: "Handout Master".into(), ..Default::default() }; - if !read_master_theme(imp, &part, &mut m) - && let Some(first) = p.masters.first() - { - m.theme = first.theme.clone(); - } - if let Some(n) = d.root.child("cSld").and_then(|c| c.attr("name")).filter(|s| !s.is_empty()) { - m.name = n.to_string(); - } - read_aux_master(imp, &part, &d, &mut m); - p.handout_master = Some(Arc::new(m)); -} - -fn read_document_properties(p: &mut Presentation, pkg: &Package, root_rels: &Rels) { - if let Some(r) = root_rels.first_of("core-properties") - && let Some(d) = pkg.xml(&r.target) - { - read_core(&d.root, &mut p.props); - } - if let Some(r) = root_rels.first_of("extended-properties") - && let Some(d) = pkg.xml(&r.target) - { - p.props.company = d.root.child("Company").map(|c| c.text()).unwrap_or_default(); - } -} - -/// Embedded font faces in one file. Past this, further typefaces are dropped. -const MAX_EMBEDDED_FONTS: usize = 64; -/// One font part. A larger part is skipped; the rest of the file is still read. -const MAX_FONT_BYTES: usize = 32 * 1024 * 1024; - -/// `p:embeddedFontLst`: each typeface and the font parts its four face slots point at. -fn read_embedded_fonts(imp: &mut Imp, pres: &Part, root: &El) -> Vec { - let Some(list) = root.child("embeddedFontLst") else { return Vec::new() }; - let mut out = Vec::new(); - for e in list.children_named("embeddedFont").take(MAX_EMBEDDED_FONTS) { - let Some(font) = e.child("font") else { continue }; - let Some(typeface) = font.attr("typeface").map(str::trim).filter(|t| !t.is_empty()) else { continue }; - let typeface: String = typeface.chars().take(255).collect(); - let slot = |imp: &mut Imp, name: &str| -> Option { - let id = e.child(name)?.attr("r:id")?; - let part = pres.rels.target(id)?; - let data = imp.pkg.get(part)?; - if data.is_empty() || data.len() > MAX_FONT_BYTES { - log::warn!("pptx: embedded font {part} skipped ({} bytes)", data.len()); - return None; - } - imp.media_for(part) - }; - let regular = slot(imp, "regular"); - let bold = slot(imp, "bold"); - let italic = slot(imp, "italic"); - let bold_italic = slot(imp, "boldItalic"); - if regular.is_none() && bold.is_none() && italic.is_none() && bold_italic.is_none() { - continue; - } - out.push(EmbeddedFont { - typeface, - panose: panose_attr(font), - pitch_family: byte_attr(font, "pitchFamily"), - charset: byte_attr(font, "charset"), - regular, - bold, - italic, - bold_italic, - }); - } - out -} - -fn byte_attr(el: &El, name: &str) -> Option { - u8::try_from(el.u32(name)?).ok() -} - -/// `panose` is 20 hex digits (ST_Panose). Anything else is dropped. -fn panose_attr(el: &El) -> Option { - let v = el.attr("panose")?.trim(); - (v.len() == 20 && v.chars().all(|c| c.is_ascii_hexdigit())).then(|| v.to_string()) -} - -fn sane_len(v: f64, dflt: f64) -> f64 { - if v.is_finite() && (1.0..=20_000.0).contains(&v) { v } else { dflt } -} - -/// Does the element (or a descendant) reference a relationship? -pub fn has_rel_refs(el: &El) -> bool { - !rel_refs(el).is_empty() -} - -/// Is this attribute a relationship id (`r:id`, `r:embed`, `r:dm`…)? -pub fn is_rel_attr(k: &str, v: &str) -> bool { - !k.starts_with("xmlns") - && k.contains(':') - && matches!(k.rsplit(':').next(), Some("id" | "embed" | "link" | "dm" | "lo" | "qs" | "cs" | "pict" | "href")) - && !v.is_empty() -} - -/// Every relationship id `el` and its descendants use, sorted and without repeats. -pub fn rel_refs(el: &El) -> Vec { - fn rec(e: &El, out: &mut Vec, depth: usize) { - if depth > crate::xml::MAX_DEPTH { - return; - } - out.extend(e.attrs.iter().filter(|(k, v)| is_rel_attr(k, v)).map(|(_, v)| v.clone())); - for c in e.elements() { - rec(c, out, depth + 1); - } - } - let mut out = vec![]; - rec(el, &mut out, 0); - out.sort(); - out.dedup(); - out -} - -pub fn color_map(cm: &El) -> Vec<(String, String)> { - cm.attrs.iter().filter(|(k, _)| !k.starts_with("xmlns")).map(|(k, v)| (k.clone(), v.clone())).collect() -} - -/// A shape's text without an anchor of its own sits at the top, as the standard has it and as -/// PowerPoint draws it. The theme's shape defaults (`a:objectDefaults/a:spDef/a:bodyPr`, centred in -/// Office's themes) are for shapes inserted later, not for the file's own shapes: PowerPoint for -/// Mac draws `` at the top under an `spDef` with `anchor="ctr"`. The model's own default -/// for shapes is the middle, so a top or bottom anchor is made explicit here and a middle one left -/// unset (placeholders and text boxes keep inheriting). -fn default_text_anchor(p: &mut Presentation) { - fn fix(shapes: &mut [deckcraft_model::Shape]) { - walk_shapes_mut(shapes, &mut |s| { - if s.ph.is_none() - && !s.text_box - && !matches!(s.kind, deckcraft_model::ShapeKind::Table(_)) - && let Some(t) = &mut s.text - { - // Middle is the model's own default for shapes, so it is kept as unset. - let got = t.body.anchor.unwrap_or(deckcraft_model::text::Anchor::Top); - t.body.anchor = (got != deckcraft_model::text::Anchor::Middle).then_some(got); - } - }); - } - for m in &mut p.masters { - let m = Arc::make_mut(m); - fix(&mut m.shapes); - for l in &mut m.layouts { - fix(&mut l.shapes); - } - } - for s in &mut p.slides { - fix(&mut Arc::make_mut(s).shapes); - } -} - -/// Placeholders read without a geometry (an empty custom geometry, see `shapes::sp`) take the -/// geometry of the layout or master placeholder they inherit from, as PowerPoint draws them: a -/// layout's picture placeholder cut into a shape keeps that shape on the slide. Anything left -/// is a rectangle. -fn inherit_placeholder_geometry(p: &mut Presentation) { - let unset = |g: &Geom| matches!(g, Geom::Custom { paths } if paths.is_empty()); - // Masters first, then layouts (from their masters), then slides (from layouts and masters). - for m in &mut p.masters { - let m = Arc::make_mut(m); - walk_shapes_mut(&mut m.shapes, &mut |s| { - if unset(&s.geom) { - s.geom = Geom::default(); - } - }); - } - let mut layout_geoms: Vec<(LayoutId, usize, Geom)> = vec![]; - for m in &p.masters { - for l in &m.layouts { - let ctx = deckcraft_model::resolve::Ctx::for_layout(p, m, l); - for (i, s) in l.shapes.iter().enumerate() { - if unset(&s.geom) { - let (_, mp) = deckcraft_model::resolve::parents(&ctx, s); - layout_geoms.push((l.id, i, mp.map(|m| m.geom.clone()).filter(|g| !unset(g)).unwrap_or_default())); - } - } - } - } - for m in &mut p.masters { - let m = Arc::make_mut(m); - for l in &mut m.layouts { - for (id, i, g) in layout_geoms.iter().filter(|(id, _, _)| *id == l.id) { - let _ = id; - if let Some(s) = l.shapes.get_mut(*i) { - s.geom = g.clone(); - } - } - } - } - let mut slide_geoms: Vec<(usize, usize, Geom)> = vec![]; - for (si, sl) in p.slides.iter().enumerate() { - let Some(ctx) = deckcraft_model::resolve::Ctx::for_slide(p, sl) else { continue }; - for (i, s) in sl.shapes.iter().enumerate() { - if unset(&s.geom) { - let (lp, mp) = deckcraft_model::resolve::parents(&ctx, s); - let g = lp.map(|l| l.geom.clone()).filter(|g| !unset(g)).or_else(|| mp.map(|m| m.geom.clone()).filter(|g| !unset(g))); - slide_geoms.push((si, i, g.unwrap_or_default())); - } - } - } - for (si, i, g) in slide_geoms { - if let Some(sl) = p.slides.get_mut(si) - && let Some(s) = Arc::make_mut(sl).shapes.get_mut(i) - { - s.geom = g; - } - } - // Placeholders inside groups (rare) and anything still unset: rectangles. - for sl in &mut p.slides { - walk_shapes_mut(&mut Arc::make_mut(sl).shapes, &mut |s| { - if unset(&s.geom) { - s.geom = Geom::default(); - } - }); - } - for m in &mut p.masters { - for l in &mut Arc::make_mut(m).layouts { - walk_shapes_mut(&mut l.shapes, &mut |s| { - if unset(&s.geom) { - s.geom = Geom::default(); - } - }); - } - } -} - -/// Every shape, groups included. -fn walk_shapes_mut(shapes: &mut [deckcraft_model::Shape], f: &mut dyn FnMut(&mut deckcraft_model::Shape)) { - for s in shapes { - f(s); - if let deckcraft_model::ShapeKind::Group { children, .. } = &mut s.kind { - walk_shapes_mut(children, f); - } - } -} - -/// `a:tblStyleLst`: the table styles the file defines. -fn table_styles(imp: &mut Imp, part: &Part, root: &El) -> Vec { - use deckcraft_model::table::{TableBorder, TablePart, TablePartStyle, TableStyleDef}; - root.children_named("tblStyle") - .take(256) - .filter_map(|st| { - let id = st.attr("styleId")?.to_ascii_uppercase(); - let mut def = TableStyleDef { id, name: st.attr("styleName").unwrap_or("").to_string(), raw: part.keep(st), ..Default::default() }; - if let Some(bg) = st.child("tblBg") { - let mut ps = TablePartStyle::default(); - if let Some(f) = bg.elements().find(|e| e.local().ends_with("Fill")) { - ps.fill = dml::fill_el(imp, part, f); - } - if let Some(fr) = bg.child("fillRef") { - ps.fill_ref = Some(( - fr.u32("idx").unwrap_or(0), - dml::color(fr).unwrap_or(deckcraft_model::ColorRef::scheme(deckcraft_color::SchemeSlot::Accent1)), - )); - } - def.background = Some(ps); - } - for el in st.elements() { - let Some(kind) = TablePart::from_xml(el.local()) else { continue }; - let mut ps = TablePartStyle::default(); - if let Some(tx) = el.child("tcTxStyle") { - ps.text_color = dml::color(tx); - ps.bold = tx.attr("b").map(|v| v == "on"); - ps.italic = tx.attr("i").map(|v| v == "on"); - } - if let Some(tc) = el.child("tcStyle") { - if let Some(f) = tc.child("fill").and_then(|f| f.elements().next()) { - ps.fill = dml::fill_el(imp, part, f); - } - if let Some(fr) = tc.child("fillRef") { - ps.fill_ref = Some(( - fr.u32("idx").unwrap_or(0), - dml::color(fr).unwrap_or(deckcraft_model::ColorRef::scheme(deckcraft_color::SchemeSlot::Accent1)), - )); - } - if let Some(bd) = tc.child("tcBdr") { - for (i, side) in ["left", "right", "top", "bottom", "insideH", "insideV"].iter().enumerate() { - let Some(b) = bd.child(side) else { continue }; - let border = if let Some(ln) = b.child("ln") { - Some(TableBorder::Line { line: dml::line(imp, part, ln) }) - } else { - b.child("lnRef").map(|r| TableBorder::Ref { - idx: r.u32("idx").unwrap_or(0), - color: dml::color(r).unwrap_or(deckcraft_model::ColorRef::scheme(deckcraft_color::SchemeSlot::Accent1)), - }) - }; - if let Some(slot) = ps.borders.get_mut(i) { - *slot = border; - } - } - } - } - def.parts.push((kind, ps)); - } - Some(def) - }) - .collect() -} - -fn background(imp: &mut Imp, part: &Part, csld: &El) -> Option { - let bg = csld.child("bg")?; - if let Some(pr) = bg.child("bgPr") { - return Some(Background::Fill { fill: dml::fill_of(imp, part, pr).unwrap_or(deckcraft_model::Fill::None) }); - } - let r = bg.child("bgRef")?; - Some(Background::Ref { - idx: r.u32("idx").unwrap_or(1001), - color: dml::color(r).unwrap_or(deckcraft_model::ColorRef::scheme(deckcraft_color::SchemeSlot::Bg1)), - }) -} - -fn read_master(imp: &mut Imp, path: &str, doc: &Doc, docs: &HashMap, layout_by_part: &mut HashMap) -> Master { - let pkg = imp.pkg; - let part = Part::new(pkg, path, doc); - let root = &doc.root; - let mut m = Master { id: MasterId(0), preserve: root.bool("preserve").unwrap_or(false), ..Default::default() }; - if let Some(t) = part.rels.first_of("theme") - && let Some(td) = pkg.xml(&t.target) - { - let tp = Part::new(pkg, &t.target, &td); - m.theme = theme::read_theme(imp, &tp, &td.root); - } - m.id = MasterId(imp.alloc()); - if let Some(cm) = root.child("clrMap") { - m.color_map = color_map(cm); - } - if let Some(csld) = root.child("cSld") { - m.name = csld.attr("name").unwrap_or("").to_string(); - m.background = background(imp, &part, csld); - if let Some(tree) = csld.child("spTree") { - let mut ctx = shapes::IdCtx::default(); - m.shapes = shapes::sp_tree(imp, &part, &mut ctx, tree, 0); - } - } - if m.name.is_empty() { - m.name = m.theme.name.clone(); - } - if let Some(ts) = root.child("txStyles") { - if let Some(s) = ts.child("titleStyle") { - m.title_style = dml::list_style(imp, &part, s); - } - if let Some(s) = ts.child("bodyStyle") { - m.body_style = dml::list_style(imp, &part, s); - } - if let Some(s) = ts.child("otherStyle") { - m.other_style = dml::list_style(imp, &part, s); - } - } - // Layouts in list order, then any other related layouts. - let mut lpaths: Vec = root - .child("sldLayoutIdLst") - .map(|l| l.children_named("sldLayoutId").filter_map(|x| part.rels.target(x.attr("r:id").unwrap_or(""))).map(String::from).collect()) - .unwrap_or_default(); - for r in part.rels.all_of("slideLayout") { - if !lpaths.iter().any(|x| opc::norm(x) == opc::norm(&r.target)) { - lpaths.push(r.target.clone()); - } - } - for lp in lpaths.iter().take(1000) { - let key = opc::norm(lp); - if layout_by_part.contains_key(&key) { - continue; - } - let Some(ld) = docs.get(&key) else { continue }; - let lpart = Part::new(pkg, lp, ld); - let l = read_layout(imp, &lpart, ld); - layout_by_part.insert(key, l.id); - m.layouts.push(l); - } - if m.layouts.is_empty() { - // A master must have a layout for slides to use. - imp.next = imp.next.saturating_add(1); - m.layouts.push(Layout { - id: LayoutId(imp.next), - name: "Blank".into(), - kind: LayoutType::Blank, - show_master_shapes: true, - ..Default::default() - }); - } - if let Some(ext) = root.child("extLst").filter(|e| !has_rel_refs(e)) { - m.raw_ext = Some(ext.elements().map(|e| part.keep(e)).collect()); - } - m -} - -fn read_layout(imp: &mut Imp, part: &Part, doc: &Doc) -> Layout { - let root = &doc.root; - let mut l = Layout { - id: LayoutId(imp.alloc()), - kind: LayoutType::from_xml(root.attr("type").unwrap_or("cust")), - show_master_shapes: root.bool("showMasterSp").unwrap_or(true), - preserve: root.bool("preserve").unwrap_or(false), - ..Default::default() - }; - if let Some(csld) = root.child("cSld") { - l.name = csld.attr("name").unwrap_or("").to_string(); - l.background = background(imp, part, csld); - if let Some(tree) = csld.child("spTree") { - let mut ctx = shapes::IdCtx::default(); - l.shapes = shapes::sp_tree(imp, part, &mut ctx, tree, 0); - } - } - l.color_map = color_map_override(root); - if let Some(ext) = root.child("extLst").filter(|e| !has_rel_refs(e)) { - l.raw_ext = Some(ext.elements().map(|e| part.keep(e)).collect()); - } - l -} - -/// A layout's or slide's `clrMapOvr/overrideClrMapping` (None for `masterClrMapping` or none). -fn color_map_override(root: &El) -> Option> { - root.child("clrMapOvr")?.child("overrideClrMapping").map(color_map) -} - -fn read_slide(imp: &mut Imp, part: &Part, doc: &Doc, id: SlideId, layout: LayoutId) -> Slide { - let root = &doc.root; - let mut s = Slide { - id, - layout, - hidden: root.bool("show") == Some(false), - show_master_shapes: root.bool("showMasterSp").unwrap_or(true), - color_map: color_map_override(root), - ..Default::default() - }; - let mut ctx = shapes::IdCtx::default(); - if let Some(csld) = root.child("cSld") { - s.name = csld.attr("name").unwrap_or("").to_string(); - s.tags = tags(imp, part, csld); - s.background = background(imp, part, csld); - if let Some(tree) = csld.child("spTree") { - s.shapes = shapes::sp_tree(imp, part, &mut ctx, tree, 0); - } - if let Some(c) = csld.child("controls") { - let pics = shapes::controls(imp, part, &mut ctx, c); - s.shapes.extend(pics); - } - } - if let Some(t) = root.child("transition") { - s.transition = timing::transition(imp, part, t); - } - if let Some(t) = root.child("timing") { - s.animations = timing::animations(imp, part, &ctx, t, &s.shapes); - timing::media_settings(t, &ctx, &mut s.shapes); - } - if let Some(ext) = root.child("extLst").filter(|e| !has_rel_refs(e)) { - s.raw_ext = Some(ext.elements().map(|e| part.keep(e)).collect()); - } - s -} - -fn read_notes(imp: &mut Imp, part: &Part, root: &El) -> TextBody { - let Some(tree) = root.path(&["cSld", "spTree"]) else { return TextBody::default() }; - for sp in tree.children_named("sp") { - let ph = sp.path(&["nvSpPr", "nvPr", "ph"]); - let is_body = ph.is_some_and(|ph| matches!(ph.attr("type"), Some("body") | None) && ph.attr("type") != Some("sldImg")); - if is_body && let Some(tx) = sp.child("txBody") { - let mut t = dml::text_body(imp, part, tx); - // Notes keep only content: drop body formatting from the notes master placeholder. - t.list_style = Default::default(); - if t.is_empty() { - return TextBody::default(); - } - return t; - } - } - TextBody::default() -} - -fn read_comments(pkg: &Package, pres: &Part, root: &El, modern: bool) -> Vec { - // Authors: legacy commentAuthors.xml (numeric ids) and modern authors.xml (GUIDs). - let mut authors: HashMap = HashMap::new(); - for kind in ["commentAuthors", "authors"] { - if let Some(r) = pres.rels.first_of(kind) - && let Some(d) = pkg.xml(&r.target) - { - for a in d.root.elements() { - if let Some(id) = a.attr("id") { - authors.insert(id.to_string(), (a.attr("name").unwrap_or("").to_string(), a.attr("initials").unwrap_or("").to_string())); - } - } - } - } - // Legacy positions are 1/8 pt; the modern part's p188:pos is an a:CT_Point2D in EMU. - let scale = if modern { 12_700.0 } else { 8.0 }; - fn one(e: &El, authors: &HashMap, depth: usize, scale: f64) -> Comment { - let (author, initials) = e.attr("authorId").and_then(|a| authors.get(a).cloned()).unwrap_or_default(); - let text = if let Some(t) = e.child("text") { - t.text() - } else if let Some(tb) = e.child("txBody") { - tb.children_named("p").map(|p| p.text()).collect::>().join("\n") - } else { - String::new() - }; - let pos = e.child("pos"); - let replies = if depth < 4 { - e.child("replyLst").map(|l| l.children_named("reply").take(1000).map(|r| one(r, authors, depth + 1, scale)).collect()).unwrap_or_default() - } else { - vec![] - }; - Comment { - author, - initials, - text, - date: e.attr("dt").or(e.attr("created")).unwrap_or("").to_string(), - x: pos.and_then(|p| p.f64("x")).unwrap_or(0.0) / scale, - y: pos.and_then(|p| p.f64("y")).unwrap_or(0.0) / scale, - resolved: e.attr("status") == Some("resolved"), - replies, - shape: None, - } - } - root.children_named("cm").take(10_000).map(|c| one(c, &authors, 0, scale)).collect() -} - -fn read_show(sp: &El, shows: &HashMap) -> ShowSettings { - let mut s = ShowSettings { - loop_until_esc: sp.bool("loop").unwrap_or(false), - without_narration: sp.bool("showNarration") == Some(false), - without_animation: sp.bool("showAnimation") == Some(false), - use_timings: sp.bool("useTimings").unwrap_or(true), - show_media_controls: sp.find("showMediaCtrls").and_then(|e| e.bool("val")).unwrap_or(true), - ..Default::default() - }; - if sp.child("browse").is_some() { - s.show_type = "browsed".into(); - } else if sp.child("kiosk").is_some() { - s.show_type = "kiosk".into(); - } - if let Some(r) = sp.child("sldRg") { - s.range = Some((r.u32("st").unwrap_or(1).max(1), r.u32("end").unwrap_or(1).max(1))); - } - if let Some(c) = sp.child("custShow") { - let id = c.attr("id").unwrap_or(""); - s.custom_show = Some(shows.get(id).cloned().unwrap_or_else(|| id.to_string())); - } - if let Some(c) = sp.child("penClr").and_then(dml::color) - && let deckcraft_model::ColorBase::Rgb { rgb } = c.base - { - s.pen_color = rgb; - } - s -} - -fn read_core(root: &El, p: &mut Properties) { - for e in root.elements() { - let t = e.text(); - match e.local() { - "title" => p.title = t, - "subject" => p.subject = t, - "creator" => p.author = t, - "keywords" => p.keywords = t, - "description" => p.comments = t, - "category" => p.category = t, - "lastModifiedBy" => p.last_modified_by = t, - "revision" => p.revision = t.trim().parse().unwrap_or(0), - "created" => p.created = t, - "modified" => p.modified = t, - _ => {} - } - } -} - -/// Which footer placeholders the slides show. -fn header_footer(p: &Presentation) -> HeaderFooter { - let mut hf = HeaderFooter::default(); - for s in &p.slides { - for sh in &s.shapes { - match sh.ph_type() { - Some(PhType::SlideNum) => hf.slide_number = true, - Some(PhType::Date) => { - hf.date = true; - let field = sh.text.iter().flat_map(|t| t.paragraphs.iter()).flat_map(|p| p.runs.iter()).find_map(|r| match &r.kind { - deckcraft_model::text::RunKind::Field { field } if deckcraft_text::datetime::is_date_field(field) => Some(field.as_str()), - _ => None, - }); - match field { - // An automatic date: remember which of the thirteen formats it is, so the - // Header and Footer dialog opens on the deck's own choice instead of the - // default. An unknown spelling (`datetime`, `datetimeFigureOut`) is left - // as no choice rather than guessed at. - Some(kind) => { - if hf.date_format.is_empty() && deckcraft_text::datetime::DATE_KINDS.contains(&kind) { - hf.date_format = kind.to_string(); - } - } - // A fixed date: its text, as before. - None => { - if hf.date_text.is_empty() - && let Some(t) = &sh.text - { - hf.date_text = t.text(); - } - } - } - } - Some(PhType::Footer) => { - hf.footer = true; - if hf.footer_text.is_empty() - && let Some(t) = &sh.text - { - hf.footer_text = t.text(); - } - } - _ => {} - } - } - } - hf -} - -#[cfg(test)] -mod rollback_tests { - use super::*; - - /// A rolled-back read gives back its budgets and removes only the media and kept-chart entries it added. - #[test] - fn rollback_restores_budgets_and_removes_only_what_was_added() { - let bytes = crate::export(&deckcraft_model::Presentation::default()).expect("export"); - let pkg = Package::open(&bytes).expect("package"); - let mut imp = Imp { - pkg: &pkg, - media: vec![], - media_by_part: HashMap::new(), - media_keys: vec![], - next: 0, - slide_by_part: HashMap::new(), - custom_show_names: HashMap::new(), - table_style_ids: Vec::new(), - vml_previews: HashMap::new(), - kept_sidecar_bytes: 0, - chart_points: 0, - chart_points_cap: chart::MAX_PRESENTATION_CHART_POINTS, - kept_charts: HashMap::new(), - kept_chart_keys: vec![], - rejected_kept: HashMap::new(), - chart_decode_bytes: 0, - tags_by_part: HashMap::new(), - tag_bytes: 0, - tags_capped: false, - warnings: vec![], - theme_extra_bytes: 0, - smartart_shapes: 0, - diagram_xml_bytes: 0, - has_rels: HashMap::new(), - }; - let kept_before = imp.media_for("ppt/presentation.xml").expect("media"); - let (m, items) = (imp.mark(), imp.media.len()); - assert!(imp.media_for("ppt/presProps.xml").is_some()); - imp.kept_chart_keys.push("ppt/charts/chart1.xml".into()); - imp.kept_charts.insert("ppt/charts/chart1.xml".into(), Default::default()); - (imp.diagram_xml_bytes, imp.tag_bytes, imp.tags_capped, imp.kept_sidecar_bytes) = (7, 5, true, 9); - imp.rollback(&m); - assert_eq!(imp.media.len(), items); - assert_eq!(imp.media_by_part.get("ppt/presentation.xml"), Some(&kept_before)); - assert!(!imp.media_by_part.contains_key("ppt/presprops.xml") && imp.kept_charts.is_empty() && imp.kept_chart_keys.is_empty()); - assert_eq!((imp.diagram_xml_bytes, imp.tag_bytes, imp.tags_capped, imp.kept_sidecar_bytes), (0, 0, false, 0)); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn mc_branches_carry_only_the_declarations_their_content_uses() { - // 2,000 declarations on the branch and 2,000 children: each child gets the one it uses - // (and the default), not all 2,000. - let decls: String = (0..2000).map(|i| format!(r#" xmlns:n{i}="urn:n{i}""#)).collect(); - let kids: String = (0..2000).map(|i| format!("")).collect(); - let x = format!( - r#"{kids}"# - ); - let mut d = crate::xml::parse(x.as_bytes()).unwrap(); - resolve_mc(&mut d.root, 0); - let kids: Vec<&El> = d.root.elements().collect(); - assert_eq!(kids.len(), 2000); - assert_eq!(kids[7].attrs, vec![("xmlns".to_string(), "urn:d".to_string()), ("xmlns:n7".to_string(), "urn:n7".to_string())]); - } - - /// The branch's own declaration of a prefix wins over the `AlternateContent`'s; an oversized - /// one still shadows it (its content stays unbound); a child's own declaration is left alone. - #[test] - fn mc_branch_declarations_keep_their_precedence() { - let long = "u".repeat(MAX_NS_VALUE + 1); - let x = format!( - r#""# - ); - let mut d = crate::xml::parse(x.as_bytes()).unwrap(); - resolve_mc(&mut d.root, 0); - let kids: Vec<&El> = d.root.elements().collect(); - let attrs = |i: usize| kids[i].attrs.iter().map(|(k, v)| format!("{k}={v}")).collect::>(); - assert_eq!(attrs(0), ["xmlns:p=urn:b"]); - assert!(attrs(1).is_empty(), "{:?}", attrs(1)); - assert_eq!(attrs(2), ["xmlns:p=urn:own"]); - } - - #[test] - fn mc_branches_keep_prefixes_named_by_must_understand() { - let x = r#""#; - let mut d = crate::xml::parse(x.as_bytes()).unwrap(); - resolve_mc(&mut d.root, 0); - let kid = d.root.elements().next().unwrap(); - assert!(kid.attrs.iter().any(|(k, v)| k == "xmlns:q" && v == "urn:q"), "{:?}", kid.attrs); - } - - #[test] - fn mc_branches_keep_prefixes_used_in_qname_values() { - let x = r#""#; - let mut d = crate::xml::parse(x.as_bytes()).unwrap(); - resolve_mc(&mut d.root, 0); - let kid = d.root.elements().next().unwrap(); - assert!(kid.attrs.iter().any(|(k, v)| k == "xmlns:q" && v == "urn:q"), "{:?}", kid.attrs); - assert!(!kid.attrs.iter().any(|(k, _)| k == "xmlns:z"), "unused declarations stay out: {:?}", kid.attrs); - } - - #[test] - fn kept_fragments_skip_oversized_namespace_names() { - let big = "u".repeat(MAX_NS_VALUE + 1); - let ns = vec![("xmlns:a".to_string(), "urn:a".to_string()), ("xmlns:b".to_string(), big)]; - let d = crate::xml::parse(br#""#).unwrap(); - let mut el = d.root.clone(); - el.attrs.clear(); - let out = keep_xml(&el, &ns); - assert!(out.contains(r#"xmlns:a="urn:a""#), "{out}"); - assert!(!out.contains("uuuu"), "the oversized declaration is not copied"); - } - - #[test] - fn copied_namespace_bytes_are_budgeted_per_part() { - let d = crate::xml::parse(br#""#).unwrap(); - let mut el = d.root.clone(); - el.attrs.clear(); - let part = Part { - name: String::new(), - rels: Default::default(), - ns: vec![("xmlns:a".to_string(), "urn:a".to_string())], - inner_ns: vec![], - ns_budget: Cell::new(15), - }; - assert!(part.keep(&el).contains(r#"xmlns:a="urn:a""#), "within budget"); - assert!(part.ns_budget.get() < 15); - let again = part.keep(&el); - assert!(!again.contains("xmlns:a"), "budget spent, no further declarations: {again}"); - } -} diff --git a/crates/pptx/src/read/chart.rs b/crates/pptx/src/read/chart.rs deleted file mode 100644 index 9365fbaca..000000000 --- a/crates/pptx/src/read/chart.rs +++ /dev/null @@ -1,1012 +0,0 @@ -//! Chart parts (`c:chartSpace`) → [`Chart`]. The original XML is kept in `Chart.raw`. - -use deckcraft_model::chart::{Chart, ChartType, ErrorBars, Series, Trendline, TrendlineType}; -use deckcraft_model::style::Fill; - -use crate::xml::El; - -/// Fills of chart parts never reference images we keep; read colour and pattern fills only. -fn simple_fill(sp: Option<&El>) -> Option { - let sp = sp?; - for e in sp.elements() { - match e.local() { - "noFill" => return Some(Fill::None), - "solidFill" => return super::dml::color(e).map(|color| Fill::Solid { color }), - "gradFill" => return Some(Fill::Gradient(super::dml::gradient(e))), - "pattFill" => return Some(Fill::Pattern(super::dml::pattern(e))), - _ => {} - } - } - None -} - -fn simple_line(sp: Option<&El>) -> Option { - let ln = sp?.child("ln")?; - let mut l = deckcraft_model::Line { width: super::dml::pt(ln, "w"), ..Default::default() }; - l.fill = simple_fill(Some(ln)); - Some(l) -} - -pub(crate) fn rich_text(t: &El) -> Option { - let tx = t.child("tx")?; - if let Some(r) = tx.child("rich") { - let s = r.children_named("p").map(|p| p.text()).collect::>().join("\n"); - return Some(s); - } - tx.find("v").map(|v| v.text()) -} - -/// Most category/value/size slots one chart may decode across all its series and caches, so -/// sparse `ptCount`/`idx` declarations can't expand far beyond the XML they came from. -pub(crate) const MAX_CHART_POINTS: usize = 1_000_000; -/// Data slots (values and categories) the charts of one presentation may hold in all; a chart past -/// it is read as a placeholder frame. Each frame that references a chart decodes its own copy. -pub(crate) const MAX_PRESENTATION_CHART_POINTS: usize = 4_000_000; - -/// Chart part bytes all chart frames of a presentation may decode, counting every attempt: a -/// chart that is rejected, or has no data slots, would otherwise be decoded again for each frame -/// that shows it. -pub(crate) const MAX_CHART_DECODE_BYTES: usize = 256 * 1024 * 1024; - -/// Slots a decoded chart holds, counting the chart itself as at least one. -pub(crate) fn point_count(c: &Chart) -> usize { - let series = |s: &deckcraft_model::chart::Series| { - let bars = s.error_bars.as_ref().map_or(0, |e| e.plus.len().saturating_add(e.minus.len())); - s.values.len().saturating_add(s.x_values.len()).saturating_add(s.sizes.len()).saturating_add(bars) - }; - let levels: usize = c.category_levels.iter().map(Vec::len).sum(); - 1usize.saturating_add(c.categories.len()).saturating_add(levels).saturating_add(c.series.iter().map(series).fold(0, usize::saturating_add)) -} - -/// Bytes of the strings a kept relationship owns. -fn part_bytes(p: &deckcraft_model::chart::ChartPart) -> usize { - p.bytes.len() + p.name.len() + p.content_type.len() -} - -fn rel_bytes(r: &deckcraft_model::chart::ChartRel) -> usize { - r.id.len() + r.rel_type.len() + r.target.len() + r.part.len() -} - -/// Most slots one cache may hold. -const MAX_CACHE_POINTS: usize = 100_000; - -/// String values from `c:cat`/`c:tx` (str or num refs, caches or literals). Every slot returned -/// is taken from `budget`; once it runs out the values are cut short. -fn strings(e: &El, budget: &mut usize) -> Vec { - let cap = MAX_CACHE_POINTS.min(*budget); - let out = strings_capped(e, cap); - *budget = budget.saturating_sub(out.len()); - out -} - -fn strings_capped(e: &El, cap: usize) -> Vec { - let cache = e.find("strCache").or_else(|| e.find("numCache")).or_else(|| e.find("strLit")).or_else(|| e.find("numLit")); - if let Some(c) = cache { - let n = (c.child("ptCount").and_then(|p| p.u32("val")).unwrap_or(0) as usize).min(cap); - let mut out = vec![String::new(); n]; - for pt in c.children_named("pt").take(MAX_CACHE_POINTS) { - let i = pt.u32("idx").unwrap_or(0) as usize; - if i >= cap { - continue; - } - let v = pt.child("v").map(|v| v.text()).unwrap_or_default(); - if i >= out.len() { - out.resize(i + 1, String::new()); - } - if let Some(s) = out.get_mut(i) { - *s = v; - } - } - return out; - } - if let Some(ml) = e.find("multiLvlStrCache") { - // Use the innermost level. - if let Some(l) = ml.child("lvl") { - return l.children_named("pt").take(cap).map(|p| p.child("v").map(|v| v.text()).unwrap_or_default()).collect(); - } - } - if cap > 0 - && let Some(v) = e.child("v") - { - return vec![v.text()]; - } - vec![] -} - -fn numbers(e: &El, budget: &mut usize) -> Vec> { - strings(e, budget).into_iter().map(|s| s.trim().parse::().ok().filter(|v| v.is_finite())).collect() -} - -/// Parse a chart part. Returns `None` for something that isn't a chart we can read. -pub fn read_chart_xml(bytes: &[u8]) -> Option { - let doc = crate::xml::parse(bytes).ok()?; - let mut root = doc.root; - super::resolve_mc(&mut root, 0); - if !root.is("chartSpace") { - return None; - } - let mut c = chart_from(&root)?; - c.raw = Some(String::from_utf8_lossy(bytes).into_owned()); - Some(c) -} - -/// The chart a graphic frame points at. A chart that would cross the presentation's point or -/// decode limits is not modelled: it is kept as its original part with the relationships it -/// reaches (`verbatim`), so a save writes it back whole instead of dropping it and its workbook. -pub(crate) fn frame_chart(imp: &mut super::Imp, part: &super::Part, rid: &str, uri: &str) -> Option { - let rel = part.rels.get(rid)?; - let chartex = uri.ends_with("/chartex"); - let bytes = imp.pkg.xml_bytes(&rel.target)?; - if imp.chart_decode_bytes.saturating_add(bytes.len()) > MAX_CHART_DECODE_BYTES { - log::warn!("pptx: chart {} is past the presentation's chart decode limit and is not kept", rel.target); - return None; - } - imp.chart_decode_bytes += bytes.len(); - let parsed = if imp.chart_points < imp.chart_points_cap { - let c = if chartex { super::read_chartex_xml(bytes) } else { super::read_chart_xml(bytes) }?; - let n = point_count(&c); - if imp.chart_points.saturating_add(n) <= imp.chart_points_cap { - imp.chart_points = imp.chart_points.saturating_add(n); - let mut c = c; - c.kept = capture_kept(imp, &rel.target); - return Some(c); - } - Some(c) - } else { - None - }; - // Past the limit: keep the part itself (charged to the sidecar budget) and show an empty chart. - if chartex || imp.kept_sidecar_bytes.saturating_add(bytes.len()) > MAX_KEPT_TOTAL_BYTES { - log::warn!("pptx: chart {} is past the presentation's chart limits and is not kept", rel.target); - return None; - } - imp.kept_sidecar_bytes += bytes.len(); - log::warn!("pptx: chart {} is past the presentation's chart limits; shown empty and written back unchanged", rel.target); - let mut c = parsed.unwrap_or_default(); - c.series.clear(); - c.categories.clear(); - c.category_levels.clear(); - c.raw = Some(String::from_utf8_lossy(bytes).into_owned()); - c.verbatim = true; - c.kept = capture_kept(imp, &rel.target); - Some(c) -} - -pub(crate) fn chart_from(root: &El) -> Option { - chart_within(root, MAX_CHART_POINTS) -} - -/// [`chart_from`] decoding at most `budget` data slots in all. -fn chart_within(root: &El, mut budget: usize) -> Option { - let ch = root.child("chart")?; - let pa = ch.child("plotArea")?; - let mut c = Chart { categories: vec![], series: vec![], title: None, legend: None, gridlines: false, ..Default::default() }; - c.style = root.child_val("style").and_then(|v| v.parse().ok()).unwrap_or(2); - if let Some(t) = ch.child("title") { - c.title = Some(rich_text(t).unwrap_or_else(|| "Chart Title".into())); - } - if ch.child("autoTitleDeleted").and_then(|a| a.bool("val")) == Some(true) { - c.title = None; - } - c.legend = ch.child("legend").map(|l| l.child_val("legendPos").unwrap_or("r").to_string()); - c.legend_overlay = ch.child("legend").and_then(|l| l.child("overlay")).and_then(|o| o.bool("val")).unwrap_or(false); - // An entry's own text (`c:legendEntry/c:txPr`) over the legend's, as for any text. - c.legend_entries = ch - .child("legend") - .into_iter() - .flat_map(|l| l.children_named("legendEntry")) - .take(MAX_LEGEND_ENTRIES) - .filter_map(|e| { - // The paragraph's own run properties first, then the list style's defaults - // (`a:lstStyle` comes before `a:p`, and is the less specific of the two). - let tx = e.child("txPr"); - let para = tx.and_then(|t| t.child("p")); - let entry = deckcraft_model::chart::LegendEntry { - idx: e.child("idx").and_then(|i| i.u32("val"))?, - size: text_size(para).or_else(|| text_size(tx)), - bold: text_bold(para).or_else(|| text_bold(tx)), - color: text_color(para).or_else(|| text_color(tx)), - }; - (entry.size.is_some() || entry.bold.is_some() || entry.color.is_some()).then_some(entry) - }) - .collect(); - c.chart_fill = simple_fill(root.child("spPr")); - c.plot_fill = simple_fill(pa.child("spPr")); - - let mut kinds: Vec = vec![]; - // The value axis the first plot group uses is the primary one; a group on another value axis - // (a combo chart's line on the right) is on the secondary axis. - let val_map: std::collections::HashMap<&str, bool> = - pa.children_named("valAx").filter_map(|a| Some((a.child_val("axId")?, matches!(a.child_val("axPos"), Some("l" | "r"))))).collect(); - let primary_val = primary_value_axis(pa, &val_map); - for g in pa.elements() { - let name = g.local(); - if !name.ends_with("Chart") { - continue; - } - let Some(kind) = group_chart_type(name, g) else { continue }; - if name == "stockChart" { - c.up_down_bars = g.child("upDownBars").is_some(); - } - let group_labels = read_group_settings(g, &mut c); - kinds.push(kind); - let val_axis = group_value_axis(&val_map, g); - let secondary = val_axis.is_some() && val_axis != primary_val; - for s in g.children_named("ser").take(1000) { - let ser = read_series(s, g, (kind, secondary, group_labels), &mut c.categories, &mut budget); - c.series.push(ser); - } - } - // `autoTitleDeleted val="0"` without `c:title`: PowerPoint and LibreOffice draw the series name as the title of a single-series chart. - if ch.child("title").is_none() && ch.child("autoTitleDeleted").and_then(|a| a.bool("val")) == Some(false) && c.series.len() == 1 { - c.title = c.series.first().map(|s| s.name.clone()).filter(|n| !n.is_empty()); - } - let first = *kinds.first()?; - c.kind = if kinds.iter().any(|k| *k != first) { ChartType::Combo } else { first }; - if c.kind != ChartType::Combo { - for s in &mut c.series { - s.kind = None; - s.secondary_axis = false; - } - } - c.lang = root.child_val("lang").map(str::to_string); - let (val_ax, cat_ax) = read_axes(&mut c, pa, &primary_val); - read_text_styles(&mut c, root, ch, val_ax, cat_ax); - Some(c) -} - -/// A group's value axis: its vertical one when it has two (scatter), else its one. -fn group_value_axis(val_map: &std::collections::HashMap<&str, bool>, g: &El) -> Option { - let ids: Vec<(&str, bool)> = - g.children_named("axId").filter_map(|a| a.attr("val")).filter_map(|id| val_map.get(id).copied().map(|v| (id, v))).collect(); - ids.iter().find(|(_, vertical)| *vertical).or(ids.first()).map(|(id, _)| id.to_string()) -} - -/// The primary value axis is the one on the left (bottom for bar charts); the secondary one -/// sits on the right or top, or crosses the category axis at its maximum. -fn primary_value_axis(pa: &El, val_map: &std::collections::HashMap<&str, bool>) -> Option { - let secondary_placed = |a: &El| a.child_val("crosses") == Some("max") || matches!(a.child_val("axPos"), Some("r" | "t")); - let val_axes_by_id: std::collections::HashMap<&str, &El> = pa.children_named("valAx").filter_map(|a| Some((a.child_val("axId")?, a))).collect(); - let used: Vec = pa.elements().filter(|g| g.local().ends_with("Chart")).filter_map(|g| group_value_axis(val_map, g)).collect(); - used.iter().find(|id| val_axes_by_id.get(id.as_str()).is_some_and(|a| !secondary_placed(a))).or(used.first()).cloned() -} - -/// The chart type of a plot group (`name` is its element name), or `None` for an unknown group. -fn group_chart_type(name: &str, g: &El) -> Option { - let grouping = g.child_val("grouping").unwrap_or("clustered"); - Some(match name { - "barChart" | "bar3DChart" => { - let bar = g.child_val("barDir") == Some("bar"); - match (bar, grouping) { - (false, "stacked") => ChartType::StackedColumn, - (false, "percentStacked") => ChartType::PercentColumn, - (false, _) => ChartType::Column, - (true, "stacked") => ChartType::StackedBar, - (true, "percentStacked") => ChartType::PercentBar, - (true, _) => ChartType::Bar, - } - } - "lineChart" | "line3DChart" => { - let markers = g.child_val("marker").is_some_and(|v| v == "1" || v == "true") - && g.children_named("ser").all(|s| s.path(&["marker", "symbol"]).and_then(|m| m.attr("val")) != Some("none")); - match grouping { - "stacked" | "percentStacked" => ChartType::StackedLine, - _ if markers => ChartType::LineMarkers, - _ => ChartType::Line, - } - } - "areaChart" | "area3DChart" => { - if matches!(grouping, "stacked" | "percentStacked") { - ChartType::StackedArea - } else { - ChartType::Area - } - } - "pieChart" | "pie3DChart" | "ofPieChart" => ChartType::Pie, - "doughnutChart" => ChartType::Doughnut, - "scatterChart" => ChartType::Scatter, - "bubbleChart" => ChartType::Bubble, - "radarChart" => { - if g.child_val("radarStyle") == Some("filled") { - ChartType::FilledRadar - } else { - ChartType::Radar - } - } - "stockChart" => ChartType::Stock, - "surfaceChart" | "surface3DChart" => ChartType::Surface, - _ => return None, - }) -} - -/// Chart-wide settings a plot group carries (vary colours, gap, overlap, hole, data labels). -/// Returns the group's own data-label setting. -fn read_group_settings(g: &El, c: &mut Chart) -> Option { - // A missing means "vary by point" (the schema default is true), as PowerPoint draws it. - c.vary_colors = g.child_val("varyColors").is_none_or(|v| v == "1" || v == "true"); - // A bar group without c:gapWidth / c:overlap takes the schema's defaults (150 %, 0 %), - // not the 219 % / -27 % PowerPoint writes into its new charts. - let bar_group = g.is("barChart") || g.is("bar3DChart"); - if let Some(v) = g.child_val("gapWidth").and_then(|v| v.parse::().ok()) { - c.gap_width = (v / 100.0).clamp(0.0, 5.0); - } else if bar_group { - c.gap_width = 1.5; - } - if let Some(v) = g.child_val("overlap").and_then(|v| v.parse::().ok()) { - c.overlap = (v / 100.0).clamp(-1.0, 1.0); - } else if bar_group { - c.overlap = 0.0; - } - if let Some(v) = g.child_val("holeSize").and_then(|v| v.parse::().ok()) { - c.hole_size = (v / 100.0).clamp(0.0, 0.9); - } - // `` without a val attribute means true, as in the schema's default. - // The setting belongs to this plot group: a group that asks for no labels keeps them - // off, even when another group of a combo chart asks for them (#868). - let group_labels = g.path(&["dLbls", "showVal"]).map(|v| v.bool("val").unwrap_or(true)); - if group_labels == Some(true) { - c.data_labels = true; - } - group_labels -} - -/// Data labels' number format: the series' labels', the group's, else the source data's. -fn label_number_format(s: &El, g: &El) -> Option { - let label_fmt = |d: Option<&El>| { - d.and_then(|d| d.child("numFmt")).filter(|n| n.attr("sourceLinked") != Some("1")).and_then(|n| n.attr("formatCode")).map(str::to_string) - }; - let source = s.child("val").or_else(|| s.child("yVal")).and_then(|v| v.find("numCache")).and_then(|c| c.child("formatCode")).map(|f| f.text()); - label_fmt(s.child("dLbls")).or_else(|| label_fmt(g.child("dLbls"))).or(source).filter(|f| !f.is_empty()) -} - -/// Error bars on the values: a scatter chart's y bars, any other chart's only ones. -fn read_error_bars(s: &El, kind: ChartType, budget: &mut usize) -> Option { - let e = s - .children_named("errBars") - .find(|e| e.child_val("errDir").is_none_or(|d| d == "y" || !matches!(kind, ChartType::Scatter | ChartType::Bubble)))?; - let d = ErrorBars::default(); - Some(ErrorBars { - bar_type: e.child_val("errBarType").unwrap_or("both").to_string(), - val_type: e.child_val("errValType").unwrap_or("fixedVal").to_string(), - value: e.child_val("val").and_then(|v| v.parse().ok()).filter(|v: &f64| v.is_finite()).unwrap_or(d.value), - plus: e.child("plus").map(|p| numbers(p, budget)).unwrap_or_default(), - minus: e.child("minus").map(|p| numbers(p, budget)).unwrap_or_default(), - end_cap: e.child("noEndCap").and_then(|v| v.bool("val")) != Some(true), - }) -} - -/// One `c:ser` of group `g`. `group` is (chart type, on the secondary axis, the group's data-label -/// setting); the first series with categories sets `categories`. -fn read_series(s: &El, g: &El, group: (ChartType, bool, Option), categories: &mut Vec, budget: &mut usize) -> Series { - let (kind, secondary, group_labels) = group; - let mut ser = Series { - name: s.child("tx").map(|t| strings(t, budget)).and_then(|v| v.into_iter().next()).unwrap_or_default(), - fill: simple_fill(s.child("spPr")), - line: simple_line(s.child("spPr")), - smooth: s.child("smooth").and_then(|v| v.bool("val")).unwrap_or(false), - marker: s.path(&["marker", "symbol"]).and_then(|m| m.attr("val")).filter(|m| *m != "none").map(String::from), - kind: Some(kind), - secondary_axis: secondary, - ..Default::default() - }; - // `` hides every label of the series, whatever the group says. - if s.path(&["dLbls", "delete"]).map(|v| v.bool("val").unwrap_or(true)) == Some(true) { - ser.data_labels = Some(false); - // `` without a val attribute means true, as in the schema's default. - } else if let Some(d) = s.child("dLbls").and_then(|d| d.child("showVal")).map(|v| v.bool("val").unwrap_or(true)) { - ser.data_labels = Some(d); - } else if let Some(false) = group_labels { - // The group asks for no labels and the series does not say otherwise. - ser.data_labels = Some(false); - } - for t in s.children_named("trendline").take(16) { - if let Some(t) = trendline(t) { - ser.trendlines.push(t); - } - } - ser.number_format = label_number_format(s, g); - for dp in s.children_named("dPt") { - if let (Some(i), Some(f)) = (dp.child("idx").and_then(|i| i.u32("val")), simple_fill(dp.child("spPr"))) { - ser.point_fills.push((i as usize, f)); - } - } - if let Some(cat) = s.child("cat").or_else(|| s.child("xVal")) { - let cats = strings(cat, budget); - if matches!(kind, ChartType::Scatter | ChartType::Bubble) { - ser.x_values = cats.iter().map(|v| v.trim().parse::().ok()).collect(); - } - if categories.is_empty() { - *categories = cats; - } - } - if let Some(v) = s.child("val").or_else(|| s.child("yVal")) { - ser.values = numbers(v, budget); - } - ser.error_bars = read_error_bars(s, kind, budget); - if let Some(b) = s.child("bubbleSize") { - ser.sizes = numbers(b, budget); - } - ser -} - -/// Axis scaling, titles, number formats and visibility. Returns the primary value axis and the -/// category axis. -fn read_axes<'a>(c: &mut Chart, pa: &'a El, primary_val: &Option) -> (Option<&'a El>, Option<&'a El>) { - let vertical = |a: &&El| matches!(a.child_val("axPos"), Some("l" | "r")); - let by_id = |id: &Option| pa.children_named("valAx").find(|a| id.is_some() && a.child_val("axId") == id.as_deref()); - let val_ax = by_id(primary_val).or_else(|| pa.children_named("valAx").find(vertical)).or_else(|| pa.children_named("valAx").last()); - let num = |a: &El, k: &str| a.child_val(k).and_then(|v| v.parse::().ok()).filter(|v| v.is_finite()); - // An axis' number format: its own unless linked to the source (`sourceLinked="1"`, or no - // c:numFmt at all), in which case the data's format of the first series plotted on it. - let source_format = |ax: &El| { - let id = ax.child_val("axId"); - pa.elements() - .filter(|g| g.children_named("axId").any(|a| a.attr("val") == id)) - .flat_map(|g| g.children_named("ser")) - .find_map(|s| { - s.child("val").or_else(|| s.child("yVal")).and_then(|v| v.find("numCache")).and_then(|c| c.child("formatCode")).map(|f| f.text()) - }) - .filter(|f| !f.is_empty() && f != "General") - }; - let format_code = |a: &El| match a.child("numFmt") { - Some(n) if n.attr("sourceLinked") != Some("1") => n.attr("formatCode").map(str::to_string), - n => source_format(a).or_else(|| n.and_then(|n| n.attr("formatCode")).map(str::to_string)), - }; - // `c:tickLblPos val="none"` hides the labels just as `c:delete` does. - let deleted = |a: &El| a.child("delete").and_then(|d| d.bool("val")) == Some(true) || a.child_val("tickLblPos") == Some("none"); - // A gridline whose `c:spPr/a:ln` has `a:noFill` is not drawn, though the element is there. - let grid = - |a: &El, k: &str| a.child(k).is_some_and(|g| !g.child("spPr").and_then(|p| p.child("ln")).is_some_and(|l| l.child("noFill").is_some())); - if c.kind == ChartType::Combo && c.series.iter().any(|s| s.secondary_axis) { - let primary_id = val_ax.and_then(|a| a.child_val("axId")); - // The other vertical value axis is the secondary one. - if let Some(a) = pa.children_named("valAx").find(|a| a.child_val("axId") != primary_id && vertical(a)) { - let sc = a.child("scaling"); - c.y2_min = sc.and_then(|s| num(s, "min")); - c.y2_max = sc.and_then(|s| num(s, "max")); - c.y2_major = num(a, "majorUnit"); - c.y2_format = format_code(a); - c.y2_hidden = deleted(a); - } - } - let cat_ax = pa.child("catAx").or_else(|| pa.child("dateAx")).or_else(|| pa.children_named("valAx").find(|a| !vertical(a))); - if let Some(v) = val_ax { - c.gridlines = grid(v, "majorGridlines"); - c.minor_gridlines = grid(v, "minorGridlines"); - let sc = v.child("scaling"); - c.y_min = sc.and_then(|s| s.child_val("min")).and_then(|v| v.parse().ok()).filter(|v: &f64| v.is_finite()); - c.y_max = sc.and_then(|s| s.child_val("max")).and_then(|v| v.parse().ok()).filter(|v: &f64| v.is_finite()); - c.axis_titles.1 = v.child("title").map(|t| rich_text(t).unwrap_or_else(|| "Axis Title".into())); - c.y_major = num(v, "majorUnit"); - c.y_log_base = sc.and_then(|s| s.child_val("logBase")).and_then(|v| v.parse().ok()).filter(|b: &f64| b.is_finite() && *b >= 2.0); - c.y_format = format_code(v); - c.y_hidden = deleted(v); - } - if let Some(a) = cat_ax { - c.cat_reversed = a.child("scaling").and_then(|s| s.child_val("orientation")).is_some_and(|o| o == "maxMin"); - c.axis_titles.0 = a.child("title").map(|t| rich_text(t).unwrap_or_else(|| "Axis Title".into())); - } - (val_ax, cat_ax) -} - -/// Text sizes and colours as the file sets them. -fn read_text_styles(c: &mut Chart, root: &El, ch: &El, val_ax: Option<&El>, cat_ax: Option<&El>) { - // Text sizes as the file sets them (PowerPoint draws chart text at these sizes, not scaled to - // the chart): the axes' and legend's, else the whole chart's; the title's own. - let chart_size = text_size(root.child("txPr")); - c.text_size = [val_ax, cat_ax, ch.child("legend")].into_iter().flatten().find_map(|e| text_size(e.child("txPr"))).or(chart_size); - // Text colour likewise: the axes' and legend's, else the whole chart's. - c.text_color = [val_ax, cat_ax, ch.child("legend"), Some(root)].into_iter().flatten().find_map(|e| text_color(e.child("txPr"))); - c.title_size = ch.child("title").and_then(|t| text_size(t.child("tx").and_then(|x| x.child("rich"))).or_else(|| text_size(t.child("txPr")))); -} - -fn trend_num(e: &El, k: &str) -> Option { - e.child_val(k).and_then(|v| v.parse::().ok()).filter(|v| v.is_finite() && v.abs() <= 1.0e12) -} - -fn trend_name(s: &str) -> Option { - let cleaned: String = - s.chars().filter(|c| matches!(c, '\t' | '\n' | '\r') || (*c >= ' ' && *c != '\u{FFFE}' && *c != '\u{FFFF}')).take(255).collect(); - let cleaned = cleaned.trim(); - if cleaned.is_empty() { None } else { Some(cleaned.to_string()) } -} - -/// One `c:trendline`. Unknown types are skipped. -fn trendline(e: &El) -> Option { - let kind = TrendlineType::from_xml(e.child_val("trendlineType")?)?; - Some(Trendline { - kind, - name: e.child("name").map(|n| n.text()).as_deref().and_then(trend_name), - order: if kind == TrendlineType::Poly { e.child("order").and_then(|o| o.u32("val")).map(|v| v.clamp(2, 6)) } else { None }, - period: if kind == TrendlineType::MovingAvg { e.child("period").and_then(|o| o.u32("val")).map(|v| v.clamp(2, 255)) } else { None }, - forward: trend_num(e, "forward"), - backward: trend_num(e, "backward"), - intercept: trend_num(e, "intercept"), - disp_eq: e.child("dispEq").and_then(|d| d.bool("val")).unwrap_or(false), - disp_r_sqr: e.child("dispRSqr").and_then(|d| d.bool("val")).unwrap_or(false), - }) -} - -/// The colour of the first `a:defRPr` or `a:rPr` with a solid fill under `e`. -fn text_color(e: Option<&El>) -> Option { - fn rec(e: &El, depth: usize) -> Option { - if depth > 8 { - return None; - } - for c in e.elements() { - if (c.is("defRPr") || c.is("rPr")) - && let Some(Fill::Solid { color }) = simple_fill(Some(c)) - { - return Some(color); - } - if let Some(v) = rec(c, depth + 1) { - return Some(v); - } - } - None - } - rec(e?, 0) -} - -const MAX_KEPT_PARTS: usize = 256; -const MAX_KEPT_DEPTH: usize = 8; -pub const MAX_KEPT_TOTAL_BYTES: usize = 32 * 1024 * 1024; - -/// Relationships and parts a chart points at, so a later save can write them back. -pub(crate) fn capture_kept(imp: &mut super::Imp, chart_part: &str) -> deckcraft_model::chart::ChartKept { - use deckcraft_model::chart::{ChartKept, ChartRel}; - - let key = crate::opc::norm(chart_part); - if let Some(cached) = imp.kept_charts.get(&key) { - // Every frame that shows this chart gets its own copy, so each copy is charged like the first. - let bytes: usize = cached.parts.iter().map(part_bytes).sum::() + cached.rels.iter().map(rel_bytes).sum::(); - if imp.kept_sidecar_bytes.saturating_add(bytes) > MAX_KEPT_TOTAL_BYTES { - log::warn!("pptx: chart sidecar retained byte budget exceeded for {chart_part}"); - return ChartKept::default(); - } - imp.kept_sidecar_bytes += bytes; - return cached.clone(); - } - - let charged_before = imp.kept_sidecar_bytes; - if imp.rejected_kept.get(&key) == Some(&charged_before) { - return ChartKept::default(); - } - let mut kept = ChartKept::default(); - // The chart document itself is rewritten; don't store a second copy of it. - let mut seen = std::collections::HashMap::from([(key.clone(), true)]); - for r in imp.pkg.rels(chart_part).items { - if !safe_rel(&r.id, &r.ty, &r.target_raw) { - log::warn!("pptx: skipping chart relationship {}", r.id); - continue; - } - if r.external { - kept.rels.push(ChartRel { id: r.id, rel_type: r.ty, target: r.target_raw, part: String::new(), external: true }); - continue; - } - if copy_part(imp.pkg, &r.target, &mut kept.parts, &mut seen, &mut imp.kept_sidecar_bytes, 0) { - kept.rels.push(ChartRel { id: r.id, rel_type: r.ty, target: r.target_raw, part: r.target, external: false }); - } - } - // The first capture's relationship strings and the parts' names and content types are retained - // too (the part bytes were charged as copied). - let rel_total: usize = - kept.rels.iter().map(rel_bytes).sum::() + kept.parts.iter().map(|p| p.name.len() + p.content_type.len()).sum::(); - if imp.kept_sidecar_bytes.saturating_add(rel_total) > MAX_KEPT_TOTAL_BYTES { - log::warn!("pptx: chart sidecar retained byte budget exceeded for {chart_part}"); - // The dropped parts must not stay charged against later charts. - imp.kept_sidecar_bytes = charged_before; - imp.rejected_kept.insert(key, charged_before); - return ChartKept::default(); - } - imp.kept_sidecar_bytes += rel_total; - imp.kept_chart_keys.push(key.clone()); - imp.kept_charts.insert(key, kept.clone()); - kept -} - -fn safe_rel(id: &str, ty: &str, target: &str) -> bool { - [id, ty, target].iter().all(|s| !s.is_empty() && s.len() <= 4096 && !s.chars().any(|c| c.is_control() || matches!(c, '<' | '>' | '"' | '\''))) -} - -/// `true` when `part` is stored (now or from an earlier relationship). -fn copy_part( - pkg: &crate::opc::Package, - part: &str, - out: &mut Vec, - seen: &mut std::collections::HashMap, - retained_bytes: &mut usize, - depth: usize, -) -> bool { - use deckcraft_model::chart::ChartPart; - - if depth > MAX_KEPT_DEPTH || out.len() >= MAX_KEPT_PARTS { - log::warn!("pptx: chart part closure stopped at {part}"); - return false; - } - let key = crate::opc::norm(part); - if let Some(ok) = seen.get(&key) { - return *ok; - } - if !crate::opc::sidecar_part(part) { - log::warn!("pptx: chart relationship target {part} is not kept"); - seen.insert(key, false); - return false; - } - let Some(bytes) = pkg.get(part) else { - log::warn!("pptx: chart relationship target {part} is missing"); - seen.insert(key, false); - return false; - }; - let name = pkg.original_name(part).unwrap_or(part).trim_start_matches('/').to_string(); - if !crate::opc::sidecar_part(&name) { - log::warn!("pptx: chart part name {name} is not kept"); - seen.insert(key, false); - return false; - } - let content_type = pkg.content_type(part).unwrap_or_default(); - let stored_bytes = if *retained_bytes + bytes.len() <= MAX_KEPT_TOTAL_BYTES { - *retained_bytes += bytes.len(); - bytes.to_vec() - } else { - log::warn!("pptx: chart sidecar retained byte budget exceeded for {part}"); - Vec::new() - }; - out.push(ChartPart { name, content_type, bytes: stored_bytes, native_entry: None }); - seen.insert(key, true); - let rels_name = crate::opc::rels_path(part); - if crate::opc::sidecar_part(&rels_name) - && seen.get(&crate::opc::norm(&rels_name)).is_none() - && let Some(rels_bytes) = pkg.get(&rels_name) - { - seen.insert(crate::opc::norm(&rels_name), true); - let name = pkg.original_name(&rels_name).unwrap_or(&rels_name).trim_start_matches('/').to_string(); - let stored_rels = if *retained_bytes + rels_bytes.len() <= MAX_KEPT_TOTAL_BYTES { - *retained_bytes += rels_bytes.len(); - rels_bytes.to_vec() - } else { - Vec::new() - }; - out.push(ChartPart { - name, - content_type: "application/vnd.openxmlformats-package.relationships+xml".into(), - bytes: stored_rels, - native_entry: None, - }); - let targets: Vec = pkg.rels(part).items.into_iter().filter(|r| !r.external).map(|r| r.target).collect(); - for target in targets { - copy_part(pkg, &target, out, seen, retained_bytes, depth + 1); - } - } - true -} - -/// Legend entries read from one chart; a legend lists at most one per series or category. -const MAX_LEGEND_ENTRIES: usize = 1024; - -/// The weight (`b`) of the first `a:defRPr` or `a:rPr` that sets one under `e`. -fn text_bold(e: Option<&El>) -> Option { - fn rec(e: &El, depth: usize) -> Option { - if depth > 8 { - return None; - } - for c in e.elements() { - if (c.is("defRPr") || c.is("rPr")) - && let Some(b) = c.bool("b") - { - return Some(b); - } - if let Some(v) = rec(c, depth + 1) { - return Some(v); - } - } - None - } - rec(e?, 0) -} - -/// The size in points of the first `a:defRPr` or `a:rPr` with one under `e` (`sz` in hundredths). -fn text_size(e: Option<&El>) -> Option { - fn rec(e: &El, depth: usize) -> Option { - if depth > 8 { - return None; - } - for c in e.elements() { - if (c.is("defRPr") || c.is("rPr")) - && let Some(v) = c.attr("sz").and_then(|v| v.parse::().ok()).filter(|v| v.is_finite() && *v > 0.0) - { - return Some((v / 100.0).clamp(1.0, 400.0)); - } - if let Some(v) = rec(c, depth + 1) { - return Some(v); - } - } - None - } - rec(e?, 0) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn point_count_charges_every_retained_vector() { - let mut c = Chart { categories: vec!["a".into()], category_levels: vec![vec!["x".into(); 2], vec!["y".into(); 3]], ..Default::default() }; - let mut s = - deckcraft_model::chart::Series { values: vec![Some(1.0); 4], x_values: vec![None; 5], sizes: vec![None; 6], ..Default::default() }; - s.error_bars = Some(deckcraft_model::chart::ErrorBars { plus: vec![None; 7], minus: vec![None; 8], ..Default::default() }); - c.series = vec![s]; - assert_eq!(point_count(&c), 1 + 1 + 5 + 4 + 5 + 6 + 15); - } - - #[test] - fn sparse_caches_share_one_chart_wide_budget() { - // Every series declares 100000 points but writes one: without a chart-wide budget each - // would expand to the full count. - let ser = |n: usize| { - format!( - r#"{n}"# - ) - }; - let sers: String = (0..5).map(ser).collect(); - let xml = format!( - r#"{sers}"# - ); - let doc = crate::xml::parse(xml.as_bytes()).unwrap(); - let c = chart_within(&doc.root, 250_000).unwrap(); - let total: usize = c.series.iter().map(|s| s.values.len()).sum(); - assert!(total <= 250_000, "{total}"); - assert_eq!(c.series.len(), 5); - assert_eq!(c.series[0].values.len(), 100_000); - assert_eq!(c.series[0].values[0], Some(0.0)); - assert!(c.series[4].values.is_empty(), "the budget ran out before the last series"); - // A small chart is untouched by the default budget. - let c = chart_from(&doc.root).unwrap(); - assert!(c.series.iter().all(|s| s.values.len() == 100_000)); - } - - #[test] - fn minor_gridlines_are_read_and_written_back() { - let mut c = Chart::sample(ChartType::Line); - c.minor_gridlines = true; - let back = read_chart_xml(&crate::write::chart::chart_xml(&c).0).unwrap(); - assert!(back.gridlines && back.minor_gridlines); - c.minor_gridlines = false; - assert!(!read_chart_xml(&crate::write::chart::chart_xml(&c).0).unwrap().minor_gridlines); - } - - #[test] - fn series_pattern_fills_are_read_and_written_back() { - // A pattern-filled series and an empty one with an outline, as PowerPoint writes them. - let xml = br#"53"#; - let c = read_chart_xml(xml).unwrap(); - let accent4 = deckcraft_model::ColorRef::scheme(deckcraft_color::SchemeSlot::Accent4); - let pattern = deckcraft_model::style::PatternFill { - preset: "openDmnd".into(), - fg: accent4.clone(), - bg: deckcraft_model::ColorRef::scheme(deckcraft_color::SchemeSlot::Bg1), - }; - assert_eq!(c.series[0].fill, Some(Fill::Pattern(pattern.clone()))); - assert_eq!(c.series[1].fill, Some(Fill::None)); - assert_eq!(c.series[1].line.as_ref().and_then(|l| l.fill.clone()), Some(Fill::solid(accent4))); - // Written out from the model (an edited chart), the pattern survives. - let mut edited = c.clone(); - edited.raw = None; - edited.title = Some("Edited".into()); - let back = read_chart_xml(&crate::write::chart::chart_xml(&edited).0).unwrap(); - assert_eq!(back.series[0].fill, Some(Fill::Pattern(pattern))); - assert_eq!(back.series[1].fill, Some(Fill::None)); - } - - #[test] - fn log_base_is_read() { - let xml = br#""#; - assert_eq!(read_chart_xml(xml).unwrap().y_log_base, Some(10.0)); - } - - #[test] - fn error_bars_are_read() { - let xml = br#"5"#; - let c = read_chart_xml(xml).unwrap(); - let e = c.series[0].error_bars.clone().unwrap(); - assert_eq!((e.bar_type.as_str(), e.val_type.as_str(), e.value, e.end_cap), ("plus", "percentage", 20.0, false)); - } - - #[test] - fn legend_position_and_overlay_are_read() { - let legend = r#""#; - let xml = format!( - r#"{legend}"# - ); - let c = read_chart_xml(xml.as_bytes()).unwrap(); - assert_eq!(c.legend.as_deref(), Some("r")); - assert!(c.legend_overlay); - let xml = br#""#; - let c = read_chart_xml(xml).unwrap(); - assert_eq!(c.legend.as_deref(), Some("r")); - assert!(!c.legend_overlay); - } - - #[test] - fn combo_chart_with_a_secondary_axis() { - // Columns on axes 1/2, a line on axes 3/4 whose value axis is on the right. - let xml = br##" -SpendW1W2200000310000 -Clicks60007400 - - -"##; - let c = read_chart_xml(xml).unwrap(); - assert_eq!(c.kind, ChartType::Combo); - assert_eq!(c.series.len(), 2); - assert!(!c.series[0].secondary_axis); - assert!(c.series[1].secondary_axis); - assert_eq!(c.series[1].kind, Some(ChartType::LineMarkers)); - assert!(c.series[1].line.as_ref().is_some_and(|l| l.width.is_some_and(|w| (w - 2.25).abs() < 0.01))); - // Each value axis' number format, bounds and unit; the chart's language. - assert_eq!(c.y_format.as_deref(), Some("#,##0")); - assert_eq!((c.y_major, c.y2_max, c.y2_format.as_deref()), (Some(100000.0), Some(8000.0), Some("0.0"))); - assert_eq!(c.lang.as_deref(), Some("ru-RU")); - // Group order doesn't decide: columns on the right-hand axis are the secondary series even - // when their group comes first, and the line on the left is primary. - let swapped = String::from_utf8_lossy(xml) - .replace( - "", ""); - let c = read_chart_xml(single.as_bytes()).unwrap(); - assert!(c.series.iter().all(|s| !s.secondary_axis)); - } - - #[test] - fn linked_axis_formats_come_from_the_data() { - // No c:numFmt on the value axis, or a source-linked one: the series' own format. - let xml = |ax_fmt: &str| { - format!( - r#"#,##01200{ax_fmt}"# - ) - }; - let fmt = |x: &str| read_chart_xml(xml(x).as_bytes()).unwrap().y_format; - assert_eq!(fmt("").as_deref(), Some("#,##0")); - assert_eq!(fmt(r#""#).as_deref(), Some("#,##0")); - assert_eq!(fmt(r#""#).as_deref(), Some("0.0")); - } - - #[test] - fn text_colour_is_read_from_the_axes() { - // LibreOffice's templates set light axis text for dark slides on the axes' c:txPr. - let xml = r#"1"#; - let c = read_chart_xml(xml.as_bytes()).unwrap(); - assert_eq!(c.text_color, Some(deckcraft_model::ColorRef::rgb(deckcraft_color::Rgba::rgb(255, 255, 255)))); - assert!(!c.cat_reversed); - let rev = read_chart_xml( - xml.replace("", "") - .as_bytes(), - ) - .unwrap(); - assert!(rev.cat_reversed, "maxMin reverses the category axis"); - // No c:gapWidth / c:overlap: the schema's 150 % and 0 %. - assert_eq!((c.gap_width, c.overlap), (1.5, 0.0)); - } - - #[test] - fn text_sizes_are_read_from_the_file() { - // PowerPoint's new charts set the axes' and legend's text to 11.97 pt and the title's to - // 18.62 pt; a chart that only sets its overall text size uses it everywhere. - let ns = - r#"xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main""#; - let tx = |sz: u32| format!(r#""#); - let xml = format!( - r#"T{}{}"#, - tx(1197), - tx(1197) - ); - let c = read_chart_xml(xml.as_bytes()).unwrap(); - assert_eq!((c.text_size, c.title_size), (Some(11.97), Some(18.62))); - let xml = format!( - r#"{}"#, - tx(1400) - ); - let c = read_chart_xml(xml.as_bytes()).unwrap(); - assert_eq!((c.text_size, c.title_size), (Some(14.0), None)); - let xml = format!( - r#""# - ); - assert_eq!(read_chart_xml(xml.as_bytes()).unwrap().text_size, None, "no sizes: the renderer picks one"); - } - - #[test] - fn hidden_labels_and_unfilled_gridlines_are_read() { - let xml = |ax: &str| { - format!( - r#"{ax}"# - ) - }; - let no_fill = r#""#; - let c = read_chart_xml(xml(r#""#).as_bytes()).unwrap(); - assert!(c.gridlines && c.minor_gridlines && !c.y_hidden); - let c = read_chart_xml( - xml(&format!( - r#"{no_fill}{no_fill}"# - )) - .as_bytes(), - ) - .unwrap(); - assert!(!c.gridlines && !c.minor_gridlines && c.y_hidden); - } - - #[test] - fn trendlines_are_read() { - let xml = br#"Spend -Fit & forecast - - - -1"#; - let c = read_chart_xml(xml).unwrap(); - let t = &c.series[0].trendlines; - assert_eq!(t.len(), 3); - assert_eq!(t[0].name.as_deref(), Some("Fit & forecast")); - assert_eq!(t[0].kind, TrendlineType::Linear); - assert_eq!((t[0].forward, t[0].backward, t[0].intercept), (Some(1.0), Some(0.5), Some(0.0))); - assert!(t[0].disp_eq && t[0].disp_r_sqr); - assert_eq!((t[1].kind, t[1].order), (TrendlineType::Poly, Some(6))); - assert_eq!((t[2].kind, t[2].period), (TrendlineType::MovingAvg, Some(3))); - } - - const NS_C: &str = "http://schemas.openxmlformats.org/drawingml/2006/chart"; - const NS_A: &str = "http://schemas.openxmlformats.org/drawingml/2006/main"; - - fn chart(auto_deleted: &str, title: &str, series: usize) -> Chart { - let val = r#"1"#; - let ser: String = (0..series).map(|i| format!(r#"S{i}{val}"#)).collect(); - let plot = format!(r#"{ser}"#); - let xml = format!(r#"{title}{auto_deleted}{plot}"#); - read_chart_xml(xml.as_bytes()).unwrap() - } - - #[test] - fn single_series_gets_automatic_title() { - assert_eq!(chart(r#""#, "", 1).title.as_deref(), Some("S0")); - } - - #[test] - fn no_automatic_title_when_deleted_or_multi_series() { - assert_eq!(chart(r#""#, "", 1).title, None); - assert_eq!(chart("", "", 1).title, None); - assert_eq!(chart(r#""#, "", 2).title, None); - } - - #[test] - fn explicit_title_wins() { - let t = "Mine"; - assert_eq!(chart(r#""#, t, 1).title.as_deref(), Some("Mine")); - } - - const NS_CHART: &str = "http://schemas.openxmlformats.org/drawingml/2006/chart"; - - fn vary_xml(vary: &str) -> String { - let ser = r#""#; - let bar = format!(r#"{vary}{ser}"#); - format!(r#"{bar}"#) - } - - #[test] - fn missing_vary_colors_means_vary_by_point() { - assert!(read_chart_xml(vary_xml("").as_bytes()).is_some_and(|c| c.vary_colors)); - } - - #[test] - fn explicit_vary_colors_is_respected() { - assert!(read_chart_xml(vary_xml(r#""#).as_bytes()).is_some_and(|c| !c.vary_colors)); - assert!(read_chart_xml(vary_xml(r#""#).as_bytes()).is_some_and(|c| c.vary_colors)); - } -} diff --git a/crates/pptx/src/read/chartex.rs b/crates/pptx/src/read/chartex.rs deleted file mode 100644 index 407d9863d..000000000 --- a/crates/pptx/src/read/chartex.rs +++ /dev/null @@ -1,177 +0,0 @@ -//! Office 2016 charts (`cx:chartSpace`, the `chartEx` part): waterfall, funnel, treemap, -//! sunburst, histogram, Pareto and box & whisker. Their data sits in `cx:chartData` as levels of -//! points, and each series names its layout (`layoutId`). - -use super::chart::rich_text; -use crate::xml::El; -use deckcraft_model::chart::{Chart, ChartType, Series}; -use std::collections::HashMap; - -/// Points per level and levels per dimension we keep (guards against hostile parts). -const MAX_POINTS: usize = 100_000; -const MAX_CHARTEX_POINTS: usize = 1_000_000; - -/// One `cx:data`: its categories (the innermost level) and named numeric dimensions. -#[derive(Default)] -struct Data { - categories: Vec, - /// Outer category levels, innermost first. - levels: Vec>, - numbers: HashMap>, Option)>, -} - -/// A level's points, by `idx`. -fn points(lvl: &El, budget: &mut usize) -> Vec { - if *budget == 0 { - return Vec::new(); - } - let cap = MAX_POINTS.min(*budget); - let mut pts = Vec::new(); - let mut max_idx = 0; - for pt in lvl.children_named("pt").take(cap) { - let i = pt.u32("idx").unwrap_or(0) as usize; - if i >= cap { - continue; - } - max_idx = max_idx.max(i + 1); - pts.push((i, pt.text())); - } - if pts.is_empty() { - return Vec::new(); - } - let n = max_idx.min(cap); - let mut out = vec![String::new(); n]; - for (i, s) in pts { - if let Some(target) = out.get_mut(i) { - *target = s; - } - } - *budget = budget.saturating_sub(out.len()); - out -} - -fn data(d: &El, budget: &mut usize) -> Data { - let mut out = Data::default(); - for dim in d.elements().take(64) { - if *budget == 0 { - break; - } - // The first level is the innermost: a treemap's leaves, a waterfall's categories. - let Some(lvl) = dim.child("lvl") else { continue }; - let ty = dim.attr("type").unwrap_or(""); - if dim.is("strDim") || (dim.is("numDim") && ty == "cat") { - if ty == "cat" || out.categories.is_empty() { - out.categories = points(lvl, budget); - // Further levels are the hierarchy's parents, innermost first. - out.levels = dim.children_named("lvl").skip(1).take(deckcraft_model::chart::MAX_LEVELS).map(|l| points(l, budget)).collect(); - } - } else if dim.is("numDim") { - let vals = points(lvl, budget).into_iter().map(|s| s.trim().parse::().ok().filter(|v| v.is_finite())).collect(); - out.numbers.insert(ty.to_string(), (vals, lvl.attr("formatCode").map(str::to_string))); - } - } - out -} - -fn kind_of(layout: &str) -> Option { - Some(match layout { - "waterfall" => ChartType::Waterfall, - "funnel" => ChartType::Funnel, - "treemap" => ChartType::Treemap, - "sunburst" => ChartType::Sunburst, - "clusteredColumn" => ChartType::Histogram, - "boxWhisker" => ChartType::BoxWhisker, - "regionMap" => ChartType::RegionMap, - _ => return None, - }) -} - -/// Parse a `chartEx` part. `None` for anything else, and for layouts DeckCraft has no type for. -pub fn read_chartex_xml(bytes: &[u8]) -> Option { - let doc = crate::xml::parse(bytes).ok()?; - let mut root = doc.root; - super::resolve_mc(&mut root, 0); - let mut c = chartex_from(&root)?; - c.raw = Some(String::from_utf8_lossy(bytes).into_owned()); - Some(c) -} - -pub(crate) fn chartex_from(root: &El) -> Option { - if !root.is("chartSpace") { - return None; - } - let mut decode_budget = MAX_CHARTEX_POINTS; - let datas: HashMap = root - .child("chartData")? - .children_named("data") - .take(64) - .map(|d| (d.attr("id").unwrap_or("0").to_string(), data(d, &mut decode_budget))) - .collect(); - let ch = root.child("chart")?; - let region = ch.child("plotArea")?.child("plotAreaRegion")?; - let mut c = Chart { categories: vec![], series: vec![], title: None, legend: None, gridlines: false, ..Default::default() }; - c.title = ch.child("title").map(|t| rich_text(t).filter(|s| !s.is_empty()).unwrap_or_else(|| "Chart Title".into())); - c.legend = ch.child("legend").map(|l| l.attr("pos").unwrap_or("t").to_string()); - let mut kind = None; - let mut output_budget = MAX_CHARTEX_POINTS; - let mut categories_set = false; - for s in region.children_named("series").take(1000) { - let layout = s.attr("layoutId").unwrap_or(""); - if layout == "paretoLine" { - // The cumulative line PowerPoint adds to a Pareto histogram. - kind = Some(ChartType::Pareto); - continue; - } - let k = kind_of(layout)?; - if s.bool("hidden") == Some(true) { - continue; - } - kind = Some(match kind { - Some(ChartType::Pareto) => ChartType::Pareto, - _ => k, - }); - let d = datas.get(s.child("dataId").and_then(|i| i.attr("val")).unwrap_or("0"))?; - let (values_src, format) = ["val", "size", "colorVal"] - .iter() - .find_map(|t| d.numbers.get(*t)) - .or_else(|| d.numbers.values().next()) - .map(|(v, f)| (v.as_slice(), f.clone())) - .unwrap_or((&[], None)); - let take_len = values_src.len().min(output_budget); - let values = values_src[..take_len].to_vec(); - output_budget = output_budget.saturating_sub(values.len()); - if !categories_set && (!d.categories.is_empty() || !d.levels.is_empty()) { - categories_set = true; - c.categories = d.categories.clone(); - c.category_levels = d.levels.clone(); - output_budget = output_budget.saturating_sub(c.categories.len()); - for lvl in &c.category_levels { - output_budget = output_budget.saturating_sub(lvl.len()); - } - } - if let Some(st) = s.child("layoutPr").and_then(|l| l.child("statistics")) { - c.inclusive_quartiles = st.attr("quartileMethod") == Some("inclusive"); - } - if let Some(b) = s.child("layoutPr").and_then(|l| l.child("binning")) { - c.bin_count = b.child("binCount").and_then(|n| n.u32("val")).filter(|n| *n > 0); - c.bin_size = b.child("binSize").and_then(|n| n.attr("val")).and_then(|v| v.parse::().ok()).filter(|v| v.is_finite() && *v > 0.0); - } - if let Some(st) = s.child("layoutPr").and_then(|l| l.child("subtotals")) { - c.subtotals = st.children_named("idx").filter_map(|i| i.u32("val")).map(|i| i as usize).take(MAX_POINTS).collect(); - } - let name = s.child("tx").and_then(|t| t.find("v")).map(|v| v.text()).unwrap_or_default(); - c.series.push(Series { - name, - values, - data_labels: s.child("dataLabels").map(|l| l.bool("hidden") != Some(true)), - number_format: format, - ..Default::default() - }); - } - c.kind = kind?; - c.data_labels = c.series.iter().any(|s| s.data_labels == Some(true)); - c.vary_colors = matches!(c.kind, ChartType::Funnel | ChartType::Treemap | ChartType::Sunburst | ChartType::Waterfall); - // Waterfall, histogram and box charts have a value axis with gridlines by default. - c.gridlines = matches!(c.kind, ChartType::Waterfall | ChartType::Histogram | ChartType::Pareto | ChartType::BoxWhisker); - Some(c) -} diff --git a/crates/pptx/src/read/dml.rs b/crates/pptx/src/read/dml.rs deleted file mode 100644 index 10a0bac47..000000000 --- a/crates/pptx/src/read/dml.rs +++ /dev/null @@ -1,824 +0,0 @@ -//! DrawingML reading: colours, fills, lines, effects, transforms and text. - -use deckcraft_color::{ColorTransform, Rgba, SchemeSlot}; -use deckcraft_geom::{Xfrm, emu_to_pt}; -use deckcraft_model::style::{ - ColorBase, ColorRef, Compound, Dash, Effects, Fill, Glow, Gradient, GradientFlip, GradientShape, GradientStop, Line, LineAlign, LineCap, LineEnd, - LineJoin, PatternFill, PictureFill, PictureMode, Reflection, Shadow, -}; -use deckcraft_model::text::{ - Action, Align, Anchor, AutoFit, BodyProps, Bullet, Caps, Hyperlink, LevelStyle, ListStyle, ParaProps, Paragraph, Run, RunKind, RunProps, Spacing, - Strike, TabStop, TextBody, TextDir, -}; - -use super::{Imp, Part}; -use crate::xml::El; - -pub fn pt(e: &El, name: &str) -> Option { - e.i64(name).map(emu_to_pt) -} - -/// 1/100 000 → fraction. -pub fn pct(e: &El, name: &str) -> Option { - e.f64(name).map(|v| v / 100_000.0) -} - -fn bullet_size_points(value: Option<&str>) -> Option { - value.and_then(|v| v.trim().parse::().ok()).filter(|v| (100..=400_000).contains(v)).map(|v| v as f64 / 100.0) -} - -fn bullet_size_percent(value: Option<&str>) -> Option { - let value = value?.trim(); - let (value, scale) = if let Some(value) = value.strip_suffix('%') { (value.trim(), 100.0) } else { (value, 100_000.0) }; - value.parse::().ok().filter(|v| v.is_finite()).map(|v| v / scale) -} - -/// 1/60 000 degree → degrees. -pub fn ang(e: &El, name: &str) -> Option { - e.f64(name).map(|v| v / 60_000.0) -} - -fn lin_to_srgb(v: f64) -> f64 { - let v = v.clamp(0.0, 1.0); - if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 } -} - -/// A colour element (`srgbClr`, `schemeClr`, …) with its transforms. -pub fn color_el(c: &El) -> Option { - let base = match c.local() { - "srgbClr" => ColorBase::Rgb { rgb: Rgba::from_hex(c.attr("val").unwrap_or("000000")).unwrap_or(Rgba::BLACK) }, - "schemeClr" => ColorBase::Scheme { slot: c.attr("val").and_then(SchemeSlot::from_xml).unwrap_or(SchemeSlot::Tx1) }, - "sysClr" => ColorBase::System { - name: c.attr("val").unwrap_or("windowText").to_string(), - last: c.attr("lastClr").and_then(Rgba::from_hex).unwrap_or(if c.attr("val") == Some("window") { Rgba::WHITE } else { Rgba::BLACK }), - }, - "prstClr" => ColorBase::Preset { name: c.attr("val").unwrap_or("black").to_string() }, - "scrgbClr" => { - let f = |n: &str| lin_to_srgb(c.f64(n).unwrap_or(0.0) / 100_000.0); - ColorBase::Rgb { rgb: Rgba::from_f64(f("r"), f("g"), f("b"), 1.0) } - } - "hslClr" => { - let h = c.f64("hue").unwrap_or(0.0) / 60_000.0; - let s = c.f64("sat").unwrap_or(0.0) / 100_000.0; - let l = c.f64("lum").unwrap_or(0.0) / 100_000.0; - ColorBase::Rgb { rgb: Rgba::from_hsl(h, s, l, 255) } - } - _ => return None, - }; - let mods = c.elements().take(32).filter_map(|m| ColorTransform::from_xml(m.local(), m.i32("val"))).collect(); - Some(ColorRef { base, mods }) -} - -/// The first colour child of a container (`solidFill`, `fgClr`, `lnRef`…). -pub fn color(container: &El) -> Option { - container.elements().find_map(color_el) -} - -const FILL_NAMES: [&str; 6] = ["noFill", "solidFill", "gradFill", "blipFill", "pattFill", "grpFill"]; - -/// The fill child of `parent`, if any. -pub fn fill_of(imp: &mut Imp, part: &Part, parent: &El) -> Option { - parent.elements().find(|e| FILL_NAMES.contains(&e.local())).and_then(|f| fill_el(imp, part, f)) -} - -pub fn fill_el(imp: &mut Imp, part: &Part, f: &El) -> Option { - Some(match f.local() { - "noFill" => Fill::None, - "solidFill" => Fill::Solid { color: color(f).unwrap_or(ColorRef::rgb(Rgba::BLACK)) }, - "gradFill" => Fill::Gradient(gradient(f)), - "blipFill" => match blip_fill(imp, part, f) { - // A picture filling a shape or background with neither `a:stretch` nor `a:tile` is - // tiled at its own size, as PowerPoint draws it. - Some(mut p) if f.child("stretch").is_none() && f.child("tile").is_none() => { - p.mode = PictureMode::Tile { tx: 0.0, ty: 0.0, sx: 1.0, sy: 1.0, flip: "none".into(), align: "tl".into() }; - Fill::Picture(p) - } - Some(p) => Fill::Picture(p), - None => Fill::None, - }, - "pattFill" => Fill::Pattern(pattern(f)), - "grpFill" => Fill::Group, - _ => return None, - }) -} - -/// An `a:pattFill`: its preset (5 % dots when unset), foreground (black) and background (white). -pub fn pattern(f: &El) -> PatternFill { - PatternFill { - preset: f.attr("prst").unwrap_or("pct5").to_string(), - fg: f.child("fgClr").and_then(color).unwrap_or(ColorRef::rgb(Rgba::BLACK)), - bg: f.child("bgClr").and_then(color).unwrap_or(ColorRef::rgb(Rgba::WHITE)), - } -} - -pub fn gradient(f: &El) -> Gradient { - let mut stops: Vec = f - .child("gsLst") - .map(|l| { - l.children_named("gs") - .take(256) - .map(|g| GradientStop { pos: pct(g, "pos").unwrap_or(0.0).clamp(0.0, 1.0), color: color(g).unwrap_or(ColorRef::rgb(Rgba::BLACK)) }) - .collect() - }) - .unwrap_or_default(); - stops.sort_by(|a, b| a.pos.total_cmp(&b.pos)); - let shape = if let Some(l) = f.child("lin") { - GradientShape::Linear { angle: ang(l, "ang").unwrap_or(0.0), scaled: l.bool("scaled").unwrap_or(false) } - } else if let Some(p) = f.child("path") { - let r = p.child("fillToRect"); - let g = |n: &str| r.and_then(|r| pct(r, n)).unwrap_or(0.0); - GradientShape::Path { path: p.attr("path").unwrap_or("circle").to_string(), focus: [g("l"), g("t"), g("r"), g("b")] } - } else { - GradientShape::Linear { angle: 90.0, scaled: false } - }; - let tile = f.child("tileRect").map(|r| [pct(r, "l"), pct(r, "t"), pct(r, "r"), pct(r, "b")].map(|v| v.unwrap_or(0.0).clamp(-10.0, 10.0))); - Gradient { - tile: tile.unwrap_or_default(), - stops, - shape, - flip: f.attr("flip").and_then(GradientFlip::from_xml), - rotate_with_shape: f.bool("rotWithShape").unwrap_or(true), - } -} - -/// `blipFill` (either `a:` or `p:`) → picture fill, registering the image as media. -pub fn blip_fill(imp: &mut Imp, part: &Part, bf: &El) -> Option { - let blip = bf.child("blip"); - let media = blip.and_then(|b| media_ref(imp, part, b)); - let media = media?; - let mut pf = PictureFill { media, upright: !bf.bool("rotWithShape").unwrap_or(true), ..Default::default() }; - if let Some(layer) = blip.and_then(|b| b.child("extLst")).and_then(|x| x.find("imgLayer")) - && let Some(effect) = layer - .elements() - .filter(|e| e.local() == "imgEffect") - .flat_map(|e| e.elements()) - .map(|e| e.local().to_string()) - .find(|n| n.starts_with("artistic")) - && let Some(original) = media_ref(imp, part, layer) - { - pf.artistic = Some(deckcraft_model::style::Artistic { effect, original }); - } - if let Some(b) = blip { - for e in b.elements() { - match e.local() { - "alphaModFix" => pf.alpha = Some(pct(e, "amt").unwrap_or(1.0).clamp(0.0, 1.0)), - "lum" => { - pf.adjust.brightness = pct(e, "bright").unwrap_or(0.0).clamp(-1.0, 1.0); - pf.adjust.contrast = pct(e, "contrast").unwrap_or(0.0).clamp(-1.0, 1.0); - } - "grayscl" => pf.adjust.grayscale = true, - "biLevel" => pf.adjust.bilevel = Some(pct(e, "thresh").unwrap_or(0.5).clamp(0.0, 1.0)), - "alphaInv" => pf.adjust.alpha_inv = true, - "duotone" => { - let cs: Vec = e.elements().filter_map(color_el).collect(); - if let [a, b] = cs.as_slice() { - pf.adjust.duotone = Some((a.clone(), b.clone())); - } - } - "clrChange" => { - if let Some(ColorRef { base: ColorBase::Rgb { rgb }, .. }) = e.child("clrFrom").and_then(color) { - pf.adjust.clear_color = Some(rgb); - } - } - _ => {} - } - } - } - if let Some(r) = bf.child("srcRect") { - pf.crop = [pct(r, "l").unwrap_or(0.0), pct(r, "t").unwrap_or(0.0), pct(r, "r").unwrap_or(0.0), pct(r, "b").unwrap_or(0.0)] - .map(|v| v.clamp(-10.0, 1.0)); - } - if let Some(t) = bf.child("tile") { - pf.mode = PictureMode::Tile { - tx: pt(t, "tx").unwrap_or(0.0), - ty: pt(t, "ty").unwrap_or(0.0), - sx: pct(t, "sx").unwrap_or(1.0), - sy: pct(t, "sy").unwrap_or(1.0), - flip: t.attr("flip").unwrap_or("none").to_string(), - align: t.attr("algn").unwrap_or("tl").to_string(), - }; - } else { - let r = bf.path(&["stretch", "fillRect"]); - let g = |n: &str| r.and_then(|r| pct(r, n)).unwrap_or(0.0).clamp(-10.0, 1.0); - pf.mode = PictureMode::Stretch { fill_rect: [g("l"), g("t"), g("r"), g("b")] }; - } - Some(pf) -} - -/// Media for an element with `r:embed` (or `r:link`). -pub fn media_ref(imp: &mut Imp, part: &Part, b: &El) -> Option { - if let Some(id) = b.attr("r:embed").filter(|s| !s.is_empty()) - && let Some(r) = part.rels.get(id) - { - if r.external { - return Some(imp.media_link(&r.target)); - } - let t = r.target.clone(); - if let Some(m) = imp.media_for(&t) { - return Some(m); - } - } - if let Some(id) = b.attr("r:link").filter(|s| !s.is_empty()) - && let Some(r) = part.rels.get(id) - { - if r.external { - return Some(imp.media_link(&r.target)); - } - let t = r.target.clone(); - return imp.media_for(&t); - } - None -} - -pub fn line(imp: &mut Imp, part: &Part, ln: &El) -> Line { - let mut l = Line { width: pt(ln, "w").map(|w| w.clamp(0.0, 2000.0)), ..Default::default() }; - l.cap = ln.attr("cap").map(|c| match c { - "rnd" => LineCap::Round, - "sq" => LineCap::Square, - _ => LineCap::Flat, - }); - l.compound = ln.attr("cmpd").map(Compound::from_xml); - l.align = ln.attr("algn").and_then(LineAlign::from_xml); - l.fill = fill_of(imp, part, ln); - for e in ln.elements() { - match e.local() { - "prstDash" => l.dash = Some(Dash::Preset { name: e.attr("val").unwrap_or("solid").to_string() }), - "custDash" => { - let pattern = e.children_named("ds").take(64).map(|d| (pct(d, "d").unwrap_or(1.0), pct(d, "sp").unwrap_or(1.0))).collect(); - l.dash = Some(Dash::Custom { pattern }); - } - "round" => l.join = Some(LineJoin::Round), - "bevel" => l.join = Some(LineJoin::Bevel), - "miter" => { - l.join = Some(LineJoin::Miter); - l.miter_limit = e.attr("lim").and_then(parse_miter_limit); - } - "headEnd" => l.head = line_end(e), - "tailEnd" => l.tail = line_end(e), - _ => {} - } - } - l -} - -fn parse_miter_limit(value: &str) -> Option { - const MAX: u32 = i32::MAX as u32; - let value = value.trim(); - if let Some(percent) = value.strip_suffix('%') { - let units = percent.trim().parse::().ok()? * 1000.0; - (units.is_finite() && (0.0..=MAX as f64).contains(&units)).then(|| units.round() as u32) - } else { - value.parse::().ok().filter(|limit| *limit <= MAX) - } -} - -fn line_end(e: &El) -> Option { - let kind = e.attr("type").unwrap_or("none"); - Some(LineEnd { kind: kind.to_string(), w: e.attr("w").unwrap_or("med").to_string(), len: e.attr("len").unwrap_or("med").to_string() }) -} - -fn shadow(e: &El, inner: bool) -> Shadow { - Shadow { - color: color(e).unwrap_or(ColorRef::rgb(Rgba::BLACK)), - blur: pt(e, "blurRad").unwrap_or(0.0).max(0.0), - dist: pt(e, "dist").unwrap_or(0.0), - dir: ang(e, "dir").unwrap_or(0.0), - inner, - sx: pct(e, "sx").unwrap_or(1.0), - sy: pct(e, "sy").unwrap_or(1.0), - kx: ang(e, "kx").unwrap_or(0.0), - ky: ang(e, "ky").unwrap_or(0.0), - align: e.attr("algn").unwrap_or(if inner { "" } else { "b" }).to_string(), - rotate_with_shape: e.bool("rotWithShape").unwrap_or(true), - } -} - -/// `effectLst` → effects. -pub fn effects(el: &El) -> Effects { - let mut fx = Effects::default(); - for e in el.elements() { - match e.local() { - "outerShdw" => fx.outer_shadow = Some(shadow(e, false)), - "prstShdw" => { - let mut s = shadow(e, false); - s.align = "b".into(); - fx.outer_shadow = Some(s); - } - "innerShdw" => fx.inner_shadow = Some(shadow(e, true)), - "glow" => fx.glow = Some(Glow { color: color(e).unwrap_or(ColorRef::rgb(Rgba::BLACK)), radius: pt(e, "rad").unwrap_or(0.0).max(0.0) }), - "softEdge" => fx.soft_edge = Some(pt(e, "rad").unwrap_or(0.0).max(0.0)), - "fillOverlay" => { - let fill = e.elements().find_map(|f| match f.local() { - "solidFill" => color(f).map(|c| Fill::Solid { color: c }), - "gradFill" => Some(Fill::Gradient(gradient(f))), - _ => None, - }); - fx.fill_overlay = fill.map(|fill| deckcraft_model::style::FillOverlay { blend: e.attr("blend").unwrap_or("over").to_string(), fill }); - } - "reflection" => { - fx.reflection = Some(Reflection { - blur: pt(e, "blurRad").unwrap_or(0.0), - start_alpha: pct(e, "stA").unwrap_or(1.0), - end_alpha: pct(e, "endA").unwrap_or(0.0), - end_pos: pct(e, "endPos").unwrap_or(1.0), - dist: pt(e, "dist").unwrap_or(0.0), - st_pos: e.i64("stPos").and_then(|v| i32::try_from(v).ok()), - dir: e.i64("dir").and_then(|v| i32::try_from(v).ok()), - fade_dir: e.i64("fadeDir").and_then(|v| i32::try_from(v).ok()), - sx: e.i64("sx").and_then(|v| i32::try_from(v).ok()), - sy: e.i64("sy").and_then(|v| i32::try_from(v).ok()), - kx: e.i64("kx").and_then(|v| i32::try_from(v).ok()), - ky: e.i64("ky").and_then(|v| i32::try_from(v).ok()), - align: e.attr("algn").filter(|v| matches!(*v, "tl" | "t" | "tr" | "l" | "ctr" | "r" | "bl" | "b" | "br")).map(str::to_owned), - rotate_with_shape: e.bool("rotWithShape"), - }) - } - _ => {} - } - } - fx -} - -/// `a:xfrm` → (box, child box for groups). -pub fn xfrm(x: &El) -> (Xfrm, Option) { - let off = x.child("off"); - let ext = x.child("ext"); - let g = |e: Option<&El>, n: &str| e.and_then(|e| pt(e, n)).unwrap_or(0.0); - let mut xf = Xfrm::new(g(off, "x"), g(off, "y"), g(ext, "cx").max(0.0), g(ext, "cy").max(0.0)); - xf.rot = ang(x, "rot").unwrap_or(0.0); - if !xf.rot.is_finite() { - xf.rot = 0.0; - } - xf.flip_h = x.bool("flipH").unwrap_or(false); - xf.flip_v = x.bool("flipV").unwrap_or(false); - let child = match (x.child("chOff"), x.child("chExt")) { - (Some(o), Some(e)) => Some(Xfrm::new(g(Some(o), "x"), g(Some(o), "y"), g(Some(e), "cx").max(0.0), g(Some(e), "cy").max(0.0))), - _ => None, - }; - (xf, child) -} - -// --------------------------------------------------------------------------------------------- -// Text - -pub fn body_pr(b: &El) -> BodyProps { - let mut p = BodyProps { - inset_l: pt(b, "lIns"), - inset_t: pt(b, "tIns"), - inset_r: pt(b, "rIns"), - inset_b: pt(b, "bIns"), - anchor: b.attr("anchor").and_then(Anchor::from_xml), - anchor_ctr: b.bool("anchorCtr"), - wrap: b.attr("wrap").map(|w| w != "none"), - vert: b.attr("vert").and_then(TextDir::from_xml), - rot: ang(b, "rot"), - columns: b.u32("numCol").map(|n| n.clamp(1, 16)), - col_spacing: pt(b, "spcCol"), - rtl_col: b.bool("rtlCol"), - upright: b.bool("upright"), - space_first_last: b.bool("spcFirstLastPara"), - compat_ln_spc: b.bool("compatLnSpc"), - vert_overflow: b.attr("vertOverflow").and_then(deckcraft_model::text::TextOverflow::from_xml), - horz_overflow: b.attr("horzOverflow").and_then(deckcraft_model::text::TextOverflow::from_horz_xml), - ..Default::default() - }; - for e in b.elements() { - match e.local() { - "normAutofit" => { - p.autofit = Some(AutoFit::Shrink { - font_scale: pct(e, "fontScale").map(|v| v.clamp(0.01, 1.0)), - line_reduction: pct(e, "lnSpcReduction").unwrap_or(0.0).clamp(0.0, 1.0), - }) - } - "spAutoFit" => p.autofit = Some(AutoFit::Shape), - "noAutofit" => p.autofit = Some(AutoFit::None), - "prstTxWarp" => { - p.warp = e.attr("prst").filter(|w| *w != "textNoShape" && !w.is_empty()).map(String::from); - p.warp_adj = p.warp.as_deref().map(|w| warp_adjusts(w, e)).unwrap_or_default(); - } - _ => {} - } - } - p -} - -/// `prstTxWarp/avLst` guides `adj` / `adj1`… as raw values by index (empty when none is given); -/// slots the file leaves out keep the preset's default. -fn warp_adjusts(preset: &str, e: &El) -> Vec { - let mut adj: Vec = Vec::new(); - let Some(av) = e.child("avLst") else { return adj }; - let defaults = deckcraft_geom::warp::adjust_defaults(preset); - for gd in av.children_named("gd").take(16) { - let n = gd.attr("name").unwrap_or(""); - let idx = if n == "adj" { - 0 - } else if let Some(k) = n.strip_prefix("adj").and_then(|k| k.parse::().ok()).filter(|k| (1..=8).contains(k)) { - k - 1 - } else { - continue; - }; - let Some(v) = gd.attr("fmla").and_then(|f| f.trim().strip_prefix("val")).and_then(|v| v.trim().parse::().ok()).filter(|v| v.is_finite()) - else { - continue; - }; - while adj.len() <= idx { - adj.push(defaults.get(adj.len()).copied().unwrap_or(0.0)); - } - if let Some(slot) = adj.get_mut(idx) { - *slot = v.clamp(-1.0e9, 1.0e9); - } - } - adj -} - -fn spacing(e: &El) -> Option { - if let Some(p) = e.child("spcPct") { - return Some(Spacing::Pct(pct(p, "val").unwrap_or(1.0).clamp(0.0, 100.0))); - } - e.child("spcPts").map(|p| Spacing::Pts(p.f64("val").unwrap_or(0.0).clamp(0.0, 1_000_000.0) / 100.0)) -} - -/// `a:pPr` / `a:lvlNpPr` → (level, paragraph props, default run props). -pub fn ppr(imp: &mut Imp, part: &Part, p: &El) -> (Option, ParaProps, Option) { - let mut pp = ParaProps { - align: p.attr("algn").and_then(Align::from_xml), - margin_left: pt(p, "marL"), - margin_right: pt(p, "marR"), - indent: pt(p, "indent"), - rtl: p.bool("rtl"), - font_align: p.attr("fontAlgn").map(String::from), - east_asian_line_break: p.bool("eaLnBrk"), - latin_line_break: p.bool("latinLnBrk"), - hanging_punct: p.bool("hangingPunct"), - default_tab: pt(p, "defTabSz"), - ..Default::default() - }; - let lvl = p.u32("lvl").map(|l| l.min(8) as u8); - let mut def = None; - for e in p.elements() { - match e.local() { - "lnSpc" => pp.line_spacing = spacing(e), - "spcBef" => pp.space_before = spacing(e), - "spcAft" => pp.space_after = spacing(e), - "buNone" => pp.bullet = Some(Bullet::None), - "buChar" => pp.bullet = Some(Bullet::Char { char: e.attr("char").unwrap_or("•").chars().take(4).collect() }), - "buAutoNum" => { - pp.bullet = Some(Bullet::AutoNum { - scheme: e.attr("type").unwrap_or("arabicPeriod").to_string(), - start_at: e.u32("startAt").unwrap_or(1).clamp(1, 32767), - }) - } - "buBlip" => { - if let Some(m) = e.child("blip").and_then(|b| media_ref(imp, part, b)) { - pp.bullet = Some(Bullet::Picture { media: m }); - } - } - "buFont" => pp.bullet_font = e.attr("typeface").map(String::from), - "buFontTx" => pp.bullet_font_follow_text = Some(true), - "buClr" => pp.bullet_color = color(e), - "buSzPct" => { - pp.bullet_size_points = None; - pp.bullet_size_follow_text = None; - pp.bullet_size = bullet_size_percent(e.attr("val")).map(|v| v.clamp(0.25, 4.0)); - } - "buSzPts" => { - pp.bullet_size = None; - pp.bullet_size_follow_text = None; - pp.bullet_size_points = bullet_size_points(e.attr("val")); - } - "buClrTx" => pp.bullet_color_follow_text = Some(true), - "buSzTx" => { - pp.bullet_size = None; - pp.bullet_size_points = None; - pp.bullet_size_follow_text = Some(true); - } - "tabLst" => { - pp.tabs = Some( - e.children_named("tab") - .take(64) - .map(|t| TabStop { pos: pt(t, "pos").unwrap_or(0.0), align: t.attr("algn").unwrap_or("l").to_string() }) - .collect(), - ) - } - "defRPr" => def = Some(rpr(imp, part, e)), - _ => {} - } - } - (lvl, pp, def) -} - -pub fn hyperlink(imp: &mut Imp, part: &Part, h: &El) -> Option { - let rid = h.attr("r:id").unwrap_or(""); - let rel = part.rels.get(rid); - let action = h.attr("action").unwrap_or(""); - let a = if let Some(rest) = action.strip_prefix("ppaction://hlinkshowjump?jump=") { - match rest { - "nextslide" => Action::NextSlide, - "previousslide" => Action::PreviousSlide, - "firstslide" => Action::FirstSlide, - "lastslide" => Action::LastSlide, - "endshow" => Action::EndShow, - "lastslideviewed" => Action::LastViewed, - _ => return None, - } - } else if action.starts_with("ppaction://hlinksldjump") { - let slide = rel.and_then(|r| imp.slide_by_part.get(&crate::opc::norm(&r.target)).copied())?; - Action::Slide { slide } - } else if let Some(q) = action.strip_prefix("ppaction://customshow?") { - let id = q.split('&').find_map(|kv| kv.strip_prefix("id=")).unwrap_or("0"); - let returns = !matches!(q.split('&').find_map(|kv| kv.strip_prefix("return=")), Some("false" | "0")); - Action::CustomShow { name: imp.custom_show_names.get(id).cloned().unwrap_or_else(|| id.to_string()), returns } - } else if action.starts_with("ppaction://program") { - Action::Program { path: rel.map(|r| r.target.clone()).unwrap_or_default() } - } else if action.starts_with("ppaction://media") { - Action::PlayMedia - } else if action.is_empty() || action.starts_with("ppaction://hlinkfile") { - let r = rel?; - if r.target.is_empty() { - return None; - } - if !r.external - && let Some(s) = imp.slide_by_part.get(&crate::opc::norm(&r.target)) - { - Action::Slide { slide: *s } - } else { - Action::Url { url: r.target.clone() } - } - } else { - return None; - }; - Some(Hyperlink { - action: a, - tooltip: h.attr("tooltip").unwrap_or("").to_string(), - highlight_click: h.bool("highlightClick").unwrap_or(false), - stop_sound: h.bool("endSnd").unwrap_or(false), - sound: h.child("snd").and_then(|s| media_ref(imp, part, s)), - zoom_return: None, - }) -} - -fn typeface(e: &El) -> Option { - let t = e.attr("typeface").filter(|t| !t.is_empty())?; - Some(t.chars().take(256).collect()) -} - -pub fn rpr(imp: &mut Imp, part: &Part, r: &El) -> RunProps { - let mut p = RunProps { - lang: r.attr("lang").map(String::from), - alt_lang: r.attr("altLang").map(|lang| lang.chars().take(256).collect()), - size: r.f64("sz").map(|s| (s / 100.0).clamp(1.0, 4000.0)), - bold: r.bool("b"), - italic: r.bool("i"), - underline: r.attr("u").map(String::from), - strike: r.attr("strike").map(|s| match s { - "sngStrike" => Strike::Single, - "dblStrike" => Strike::Double, - _ => Strike::None, - }), - baseline: pct(r, "baseline").map(|b| b.clamp(-10.0, 10.0)), - caps: r.attr("cap").map(|c| match c { - "small" => Caps::Small, - "all" => Caps::All, - _ => Caps::None, - }), - spacing: r.f64("spc").map(|s| (s / 100.0).clamp(-4000.0, 4000.0)), - kern: r.f64("kern").map(|k| (k / 100.0).clamp(0.0, 4000.0)), - no_proof: r.bool("noProof"), - normalize_height: r.bool("normalizeH"), - ..Default::default() - }; - for e in r.elements() { - match e.local() { - "ln" => p.outline = Some(line(imp, part, e)), - n if FILL_NAMES.contains(&n) => p.fill = fill_el(imp, part, e), - "effectLst" => { - let fx = effects(e); - p.shadow = fx.outer_shadow; - p.inner_shadow = fx.inner_shadow; - p.glow = fx.glow; - p.reflection = fx.reflection; - p.soft_edge = fx.soft_edge; - } - "highlight" => p.highlight = color(e), - "uFill" => p.underline_color = e.child("solidFill").and_then(color), - "latin" => p.font = typeface(e), - "ea" => p.font_ea = typeface(e), - "cs" => p.font_cs = typeface(e), - "sym" => p.font_sym = typeface(e), - "hlinkClick" => p.link = hyperlink(imp, part, e), - "hlinkMouseOver" => p.hover = hyperlink(imp, part, e), - _ => {} - } - } - p -} - -/// `a:lstStyle`, `p:titleStyle`, `a:defaultTextStyle`… → list style. -pub fn list_style(imp: &mut Imp, part: &Part, ls: &El) -> ListStyle { - let mut out = ListStyle::default(); - for e in ls.elements() { - let n = e.local(); - 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; - } - let (_, para, run) = ppr(imp, part, e); - out.set(l - 1, LevelStyle { para, run: run.unwrap_or_default() }); - } - out -} - -pub fn text_body(imp: &mut Imp, part: &Part, tx: &El) -> TextBody { - let mut body = tx.child("bodyPr").map(body_pr).unwrap_or_default(); - if let Some(b) = tx.child("bodyPr") { - let mut raw3d = String::new(); - if let Some(sc) = b.child("scene3d") { - raw3d.push_str(&part.keep_inner(sc)); - } - if let Some(sp) = b.child("sp3d").or_else(|| b.child("flatTx")) { - raw3d.push_str(&part.keep_inner(sp)); - } - if !raw3d.is_empty() && raw3d.len() <= 64 * 1024 { - body.raw3d = Some(raw3d); - } - } - let list_style = tx.child("lstStyle").map(|l| list_style(imp, part, l)).unwrap_or_default(); - let paragraphs = tx.children_named("p").take(100_000).map(|p| paragraph(imp, part, p)).collect(); - TextBody { body, list_style, paragraphs } -} - -const MAX_PARAGRAPH_RUNS: usize = 10_000; - -/// The run properties of `e`'s `rPr` child, or the defaults. -fn run_props(imp: &mut Imp, part: &Part, e: &El) -> RunProps { - e.child("rPr").map(|r| rpr(imp, part, r)).unwrap_or_default() -} - -/// Appends the runs of an `a:r` text, where a vertical tab or line feed is a line break, as it -/// lays out and as export writes it. -fn push_text_runs(para: &mut Paragraph, props: RunProps, text: &str) { - for (i, piece) in text.split(['\u{b}', '\n']).enumerate() { - if para.runs.len() >= MAX_PARAGRAPH_RUNS { - break; - } - if i > 0 { - para.runs.push(Run { text: String::new(), props: props.clone(), kind: RunKind::Break }); - } - if !piece.is_empty() { - if para.runs.len() >= MAX_PARAGRAPH_RUNS { - break; - } - para.runs.push(Run { text: piece.to_string(), props: props.clone(), kind: RunKind::Text }); - } - } -} - -/// Appends an Office Math (a14:m) run: its plain text and its OMML. -fn push_math_run(para: &mut Paragraph, part: &Part, e: &El) { - if para.runs.len() < MAX_PARAGRAPH_RUNS { - // The text of the outermost `t` elements: a `t` nested in another is already part of - // the outer one's text, and taking it again would copy it once per nesting level. - fn outer_t(e: &El, depth: usize, text: &mut String) { - if depth > crate::xml::MAX_DEPTH { - return; - } - for c in e.elements() { - if c.is("t") { - text.push_str(&c.text()); - } else { - outer_t(c, depth + 1, text); - } - } - } - let mut text = String::new(); - outer_t(e, 0, &mut text); - let omml = e.elements().map(|c| part.keep_inner(c)).collect::(); - para.runs.push(Run { text, props: RunProps::default(), kind: RunKind::Math { omml } }); - } -} - -pub fn paragraph(imp: &mut Imp, part: &Part, p: &El) -> Paragraph { - let mut para = Paragraph::default(); - for e in p.elements() { - match e.local() { - "pPr" => { - let (lvl, pp, def) = ppr(imp, part, e); - para.level = lvl.unwrap_or(0); - para.props = pp; - if let Some(d) = def { - para.def_props = d; - } - } - "r" => { - let props = run_props(imp, part, e); - let text: String = e.child("t").map(|t| t.text()).unwrap_or_default(); - push_text_runs(&mut para, props, &text); - } - "br" if para.runs.len() < MAX_PARAGRAPH_RUNS => { - let props = run_props(imp, part, e); - para.runs.push(Run { text: String::new(), props, kind: RunKind::Break }); - } - "fld" if para.runs.len() < MAX_PARAGRAPH_RUNS => { - let props = run_props(imp, part, e); - let text = e.child("t").map(|t| t.text()).unwrap_or_default(); - para.runs.push(Run { text, props, kind: RunKind::Field { field: e.attr("type").unwrap_or("").to_string() } }); - } - "m" => push_math_run(&mut para, part, e), - "endParaRPr" => para.end_props = rpr(imp, part, e), - _ => {} - } - } - para -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::xml::parse; - - #[test] - fn nested_math_text_is_taken_once() { - // 200 `m:t` nested in each other around one word: the word, not 200 copies of it. - let x = format!(r#"{}word{}"#, "".repeat(200), "".repeat(200)); - let d = parse(x.as_bytes()).unwrap(); - let part = Part { - name: "ppt/slides/slide1.xml".into(), - rels: Default::default(), - ns: vec![], - inner_ns: vec![], - ns_budget: std::cell::Cell::new(1 << 20), - }; - let mut para = Paragraph::default(); - push_math_run(&mut para, &part, &d.root); - assert_eq!(para.runs[0].text, "word"); - } - - #[test] - fn colors_and_transforms() { - let d = parse( - br#""#, - ) - .unwrap(); - let c = color(&d.root).unwrap(); - assert_eq!(c.base, ColorBase::Scheme { slot: SchemeSlot::Accent2 }); - assert_eq!(c.mods, vec![ColorTransform::LumMod(75000), ColorTransform::Alpha(50000)]); - let d = parse(br#""#).unwrap(); - assert!(matches!(color(&d.root).unwrap().base, ColorBase::System { last: Rgba::WHITE, .. })); - let d = parse(br#""#).unwrap(); - assert_eq!(color(&d.root).unwrap().base, ColorBase::Rgb { rgb: Rgba::rgb(255, 0, 0) }); - } - - #[test] - fn bullet_point_size_trims_schema_whitespace() { - let d = parse(br#""#).unwrap(); - assert_eq!(bullet_size_points(d.root.attr("val")), Some(14.0)); - assert_eq!(bullet_size_points(Some("1400")), Some(14.0)); - } - - #[test] - fn bullet_percentage_size_accepts_numeric_and_percent_forms() { - assert_eq!(bullet_size_percent(Some("100000")), Some(1.0)); - assert_eq!(bullet_size_percent(Some("100%")), Some(1.0)); - assert_eq!(bullet_size_percent(Some(" 125% ")), Some(1.25)); - assert_eq!(bullet_size_percent(Some("invalid")), None); - } - - #[test] - fn miter_limit_accepts_both_percentage_forms_with_schema_bounds() { - assert_eq!(parse_miter_limit("200000"), Some(200_000)); - assert_eq!(parse_miter_limit("200%"), Some(200_000)); - assert_eq!(parse_miter_limit("1000001"), Some(1_000_001)); - assert_eq!(parse_miter_limit("malformed"), None); - assert_eq!(parse_miter_limit("2147483648"), None); - assert_eq!(parse_miter_limit("2147483.648%"), None); - } - - #[test] - fn body_props() { - let d = parse(br#""#).unwrap(); - let b = body_pr(&d.root); - assert_eq!(b.inset_l, Some(7.2)); - assert_eq!(b.anchor, Some(Anchor::Middle)); - assert_eq!(b.wrap, Some(false)); - assert_eq!(b.vert, Some(TextDir::Vertical270)); - assert_eq!(b.columns, Some(2)); - assert_eq!(b.autofit, Some(AutoFit::Shrink { font_scale: Some(0.625), line_reduction: 0.2 })); - assert_eq!(b.space_first_last, None); - // A bare `` keeps no scale: the schema default 100 % is drawn as it is, - // not the same as a saved 100 % (`fontScale="100000"`) (#724). - let d = parse(br#""#).unwrap(); - assert_eq!(body_pr(&d.root).autofit, Some(AutoFit::Shrink { font_scale: None, line_reduction: 0.0 })); - let d = parse(br#""#).unwrap(); - assert_eq!(body_pr(&d.root).autofit, Some(AutoFit::Shrink { font_scale: Some(1.0), line_reduction: 0.0 })); - let d = parse(br#""#).unwrap(); - assert_eq!(body_pr(&d.root).space_first_last, Some(true)); - // mongolianVert is its own direction (PowerPoint runs its lines left to right) and is - // written back as it was read. - let d = parse(br#""#).unwrap(); - let b = body_pr(&d.root); - assert_eq!(b.vert, Some(TextDir::MongolianVertical)); - assert_eq!(b.vert.map(|v| v.xml()), Some("mongolianVert")); - let d = parse(br#""#).unwrap(); - assert_eq!(body_pr(&d.root).vert.map(|v| v.xml()), Some("wordArtVertRtl")); - } -} diff --git a/crates/pptx/src/read/shapes.rs b/crates/pptx/src/read/shapes.rs deleted file mode 100644 index 7ff66018a..000000000 --- a/crates/pptx/src/read/shapes.rs +++ /dev/null @@ -1,924 +0,0 @@ -//! Shape trees: `p:sp`, `p:pic`, `p:grpSp`, `p:cxnSp`, `p:graphicFrame` (tables, charts, SmartArt, -//! OLE and other objects) and `p:contentPart` (3-D models). - -use std::collections::{HashMap, HashSet}; - -use deckcraft_color::SchemeSlot; -use deckcraft_geom::{Xfrm, preset}; -use deckcraft_model::style::{ColorRef, Effects, Fill}; -use deckcraft_model::table::{Cell, Row, Table}; -use deckcraft_model::text::{Anchor, TextDir}; -use deckcraft_model::{Geom, MediaClip, PhType, Placeholder, Shape, ShapeId, ShapeKind, ShapeStyle}; - -use super::{Imp, Part, dml}; -use crate::xml::El; - -/// File shape ids at or above this are reassigned. -pub const MAX_KEPT_ID: u32 = 1 << 30; -const MAX_TREE_DEPTH: usize = 32; -const MAX_SHAPES: usize = 20_000; - -/// Shape id bookkeeping for one part. -#[derive(Default)] -pub struct IdCtx { - pub used: HashSet, - /// File id → model id. - pub map: HashMap, - /// Always allocate new ids (shapes pulled in from other parts). - pub fresh: bool, - pub count: usize, -} - -impl IdCtx { - fn assign(&mut self, imp: &mut Imp, file_id: Option) -> ShapeId { - if !self.fresh - && let Some(i) = file_id - && (2..MAX_KEPT_ID).contains(&i) - && !self.used.contains(&i) - { - self.used.insert(i); - self.map.insert(i, ShapeId(i)); - return ShapeId(i); - } - let n = imp.alloc(); - self.used.insert(n); - if let Some(i) = file_id { - self.map.entry(i).or_insert(ShapeId(n)); - } - ShapeId(n) - } - pub fn lookup(&self, file_id: u32) -> Option { - self.map.get(&file_id).copied() - } -} - -/// Read the children of an `spTree` / `grpSp`. -pub fn sp_tree(imp: &mut Imp, part: &Part, ctx: &mut IdCtx, tree: &El, depth: usize) -> Vec { - let mut out = vec![]; - if depth > MAX_TREE_DEPTH { - log::warn!("pptx: group nesting too deep in {}", part.name); - return out; - } - for e in tree.elements() { - if ctx.count >= MAX_SHAPES { - log::warn!("pptx: too many shapes in {}", part.name); - break; - } - let s = match e.local() { - "sp" => Some(sp(imp, part, ctx, e)), - "pic" => Some(pic(imp, part, ctx, e)), - "grpSp" => Some(grp(imp, part, ctx, e, depth)), - "cxnSp" => Some(cxn(imp, part, ctx, e)), - "graphicFrame" => Some(frame(imp, part, ctx, e, depth)), - "contentPart" => content_part(imp, part, ctx, e).or_else(|| { - log::warn!("pptx: content part in {} not imported", part.name); - None - }), - "AlternateContent" => read_model_alternate(imp, part, ctx, e), - _ => None, - }; - if let Some(s) = s { - ctx.count += 1; - out.push(s); - } - } - if depth == 0 { - remap_connectors(&mut out, ctx, 0); - } - out -} - -/// ActiveX controls (`p:controls`): each control's picture (`p:pic`), the image PowerPoint shows -/// for it, as a picture above the slide's shapes. Controls without one are left out. -pub fn controls(imp: &mut Imp, part: &Part, ctx: &mut IdCtx, controls: &El) -> Vec { - let mut out = vec![]; - for c in controls.children_named("control") { - if ctx.count >= MAX_SHAPES { - break; - } - if let Some(p) = c.child("pic") { - ctx.count += 1; - out.push(pic(imp, part, ctx, p)); - } - } - out -} - -fn remap_connectors(shapes: &mut [Shape], ctx: &IdCtx, depth: usize) { - if depth > MAX_TREE_DEPTH { - return; - } - for s in shapes.iter_mut() { - match &mut s.kind { - ShapeKind::Connector { start, end } => { - for e in [start, end] { - *e = e.and_then(|(id, site)| ctx.lookup(id.0).map(|m| (m, site))); - } - } - ShapeKind::Group { children, .. } => remap_connectors(children, ctx, depth + 1), - _ => {} - } - } -} - -/// PowerPoint's Lock (right-click > Lock, the Selection pane padlock) writes a full set of locking -/// attributes; it reads an object as locked only when the whole set for its kind is there, so a -/// lone `noMove` or `noResize` (other tools' partial locks) isn't Lock. -fn is_locked(l: &El) -> bool { - let set: &[&str] = match l.local() { - "grpSpLocks" => &["noGrp", "noUngrp", "noRot", "noMove", "noResize"], - "graphicFrameLocks" => &["noGrp", "noDrilldown", "noMove", "noResize"], - _ => &["noGrp", "noRot", "noMove", "noResize", "noEditPoints", "noAdjustHandles", "noChangeArrowheads", "noChangeShapeType"], - }; - set.iter().all(|a| l.bool(a) == Some(true)) -} - -/// Common non-visual properties (`p:nvSpPr`, `p:nvPicPr`…). -fn base(imp: &mut Imp, part: &Part, ctx: &mut IdCtx, nv: Option<&El>) -> Shape { - let c = nv.and_then(|n| n.child("cNvPr")); - let mut s = Shape { id: ctx.assign(imp, c.and_then(|c| c.u32("id"))), ..Default::default() }; - if let Some(c) = c { - s.name = c.attr("name").unwrap_or("").to_string(); - s.descr = c.attr("descr").unwrap_or("").to_string(); - s.title = c.attr("title").unwrap_or("").to_string(); - s.hidden = c.bool("hidden").unwrap_or(false); - s.click = c.child("hlinkClick").and_then(|h| dml::hyperlink(imp, part, h)); - s.hover = c.child("hlinkHover").and_then(|h| dml::hyperlink(imp, part, h)); - s.decorative = c.find("decorative").and_then(|d| d.bool("val")).unwrap_or(false); - } - if let Some(nv) = nv { - for e in nv.elements() { - match e.local() { - "cNvSpPr" => { - s.text_box = e.bool("txBox").unwrap_or(false); - s.locked = e.child("spLocks").is_some_and(is_locked); - } - "cNvPicPr" | "cNvGrpSpPr" | "cNvCxnSpPr" | "cNvGraphicFramePr" => { - s.locked = e.elements().find(|l| l.local().ends_with("Locks")).is_some_and(is_locked); - } - "nvPr" => { - if let Some(ph) = e.child("ph") { - s.ph = Some(Placeholder { - kind: ph.attr("type").map(PhType::from_xml).unwrap_or(PhType::Obj), - idx: ph.u32("idx").unwrap_or(0), - vertical: ph.attr("orient") == Some("vert"), - size: ph.attr("sz").map(String::from), - has_custom_prompt: ph.bool("hasCustomPrompt").unwrap_or(false), - }); - } - s.tags = super::tags(imp, part, e); - } - _ => {} - } - } - } - s -} - -fn preset_geom(pg: &El) -> Geom { - let name = pg.attr("prst").unwrap_or("rect").to_string(); - let defaults: Vec = preset::adjust_defaults(&name).to_vec(); - let mut adj = defaults; - let mut any = false; - if let Some(av) = pg.child("avLst") { - for gd in av.children_named("gd").take(16) { - let n = gd.attr("name").unwrap_or(""); - let idx = if n == "adj" { - 0 - } else if let Some(k) = n.strip_prefix("adj").and_then(|k| k.parse::().ok()).filter(|k| (1..=16).contains(k)) { - k - 1 - } else { - continue; - }; - let Some(v) = - gd.attr("fmla").and_then(|f| f.trim().strip_prefix("val")).and_then(|v| v.trim().parse::().ok()).filter(|v| v.is_finite()) - else { - continue; - }; - if adj.len() <= idx { - adj.resize(idx + 1, 0.0); - } - if let Some(slot) = adj.get_mut(idx) { - *slot = v; - any = true; - } - } - } - if !any { - adj.clear(); - } - Geom::Preset { name, adj } -} - -/// A placeholder whose `spPr` names no geometry takes its layout's (or master's) placeholder's: -/// marked here with an empty custom geometry, filled in once the layouts are read -/// (`inherit_placeholder_geometry`). -fn mark_inherited_geometry(s: &mut Shape, pr: Option<&El>) { - if s.ph.is_some() && pr.is_none_or(|pr| pr.child("prstGeom").is_none() && pr.child("custGeom").is_none()) { - s.geom = Geom::Custom { paths: vec![] }; - } -} - -/// `spPr` → transform, geometry, fill, line, effects. -fn sp_pr(imp: &mut Imp, part: &Part, s: &mut Shape, pr: &El) { - if let Some(x) = pr.child("xfrm") { - s.xfrm = Some(dml::xfrm(x).0); - } - if let Some(pg) = pr.child("prstGeom") { - s.geom = preset_geom(pg); - } else if let Some(cg) = pr.child("custGeom") { - let (w, h) = s.xfrm.map(|x| (deckcraft_geom::pt_to_emu(x.w) as f64, deckcraft_geom::pt_to_emu(x.h) as f64)).unwrap_or((21600.0, 21600.0)); - let paths = crate::custgeom::read_cust_geom(cg, w, h); - if !paths.is_empty() { - s.geom = Geom::Custom { paths }; - } - } - s.fill = dml::fill_of(imp, part, pr); - if let Some(ln) = pr.child("ln") { - s.line = Some(dml::line(imp, part, ln)); - } - if let Some(fx) = pr.child("effectLst") { - s.effects = Some(dml::effects(fx)); - } - let raw: String = pr.elements().filter(|c| c.is("scene3d") || c.is("sp3d")).map(|c| part.keep(c)).collect(); - if !raw.is_empty() { - let fx = s.effects.get_or_insert_with(Effects::default); - fx.bevel = pr.path(&["sp3d", "bevelT"]).map(|b| b.attr("prst").unwrap_or("circle").to_string()); - fx.raw3d = Some(raw); - } -} - -fn style(st: &El) -> ShapeStyle { - let r = |n: &str| { - st.child(n) - .map(|e| (e.u32("idx").unwrap_or(0).min(1003), dml::color(e).unwrap_or(ColorRef::scheme(SchemeSlot::Accent1)))) - .unwrap_or((0, ColorRef::scheme(SchemeSlot::Accent1))) - }; - let font = st.child("fontRef"); - ShapeStyle { - line_ref: r("lnRef"), - fill_ref: r("fillRef"), - effect_ref: r("effectRef"), - font_ref: (font.and_then(|f| f.attr("idx")).unwrap_or("minor").to_string(), font.and_then(dml::color)), - } -} - -fn sp(imp: &mut Imp, part: &Part, ctx: &mut IdCtx, e: &El) -> Shape { - let mut s = base(imp, part, ctx, e.child("nvSpPr")); - if let Some(pr) = e.child("spPr") { - sp_pr(imp, part, &mut s, pr); - } - mark_inherited_geometry(&mut s, e.child("spPr")); - if e.bool("useBgFill") == Some(true) { - s.fill = Some(Fill::Background); - } - s.style = e.child("style").map(style); - s.text = e.child("txBody").map(|t| dml::text_body(imp, part, t)); - s -} - -fn ms(v: Option<&str>) -> u32 { - v.and_then(|v| v.trim().parse::().ok()).filter(|v| v.is_finite()).map(|v| v.clamp(0.0, u32::MAX as f64) as u32).unwrap_or(0) -} - -fn find_content_part(el: &El) -> Option<&El> { - fn rec(el: &El, depth: usize) -> Option<&El> { - if depth > 16 { - return None; - } - if el.is("contentPart") { - return Some(el); - } - el.elements().find_map(|c| rec(c, depth + 1)) - } - rec(el, 0) -} - -/// `p:contentPart` whose relationship is a 3-D model. Other content parts (ink) are left out. -fn content_part(imp: &mut Imp, part: &Part, ctx: &mut IdCtx, e: &El) -> Option { - let id = e.attr("r:id").filter(|s| !s.is_empty())?; - let rel = part.rels.get(id)?; - if !super::is_model3d(rel) { - return None; - } - let target = rel.target.clone(); - let media = imp.media_for(&target).or_else(|| { - log::warn!("pptx: 3-D model part missing in {}", part.name); - None - })?; - let mut s = base(imp, part, ctx, e.child("nvContentPartPr")); - if let Some(x) = e.child("xfrm") { - s.xfrm = Some(dml::xfrm(x).0); - } - s.kind = ShapeKind::Model3d { media, poster: None }; - Some(s) -} - -/// A 3-D model wrapped in `mc:AlternateContent`: the model choice, plus the fallback picture. -/// If the model part is missing, the fallback picture is the shape. -fn read_model_alternate(imp: &mut Imp, part: &Part, ctx: &mut IdCtx, e: &El) -> Option { - if let Some(content) = e.children_named("Choice").find_map(find_content_part) - && let Some(mut s) = content_part(imp, part, ctx, content) - { - let poster = e.child("Fallback").and_then(|fb| { - let mut pics = vec![]; - fb.find_all("blip", &mut pics); - pics.into_iter().find_map(|b| dml::media_ref(imp, part, b)) - }); - if let ShapeKind::Model3d { media, .. } = s.kind { - s.kind = ShapeKind::Model3d { media, poster }; - } - return Some(s); - } - e.child("Fallback").and_then(|fb| fb.elements().find(|c| c.is("pic")).map(|p| pic(imp, part, ctx, p))) -} - -fn pic(imp: &mut Imp, part: &Part, ctx: &mut IdCtx, e: &El) -> Shape { - let mut s = base(imp, part, ctx, e.child("nvPicPr")); - if let Some(pr) = e.child("spPr") { - sp_pr(imp, part, &mut s, pr); - } - // A picture in a picture placeholder is cut into the layout's shape (a circle, say). - mark_inherited_geometry(&mut s, e.child("spPr")); - s.style = e.child("style").map(style); - let pf = e.child("blipFill").and_then(|b| dml::blip_fill(imp, part, b)); - let nvpr = e.path(&["nvPicPr", "nvPr"]); - let vf = nvpr.and_then(|n| n.child("videoFile")); - let af = nvpr.and_then(|n| n.child("audioFile")); - let p14 = nvpr.and_then(|n| n.child("extLst")).and_then(|x| x.find("media")); - if vf.is_some() || af.is_some() || p14.is_some() { - let media = p14.and_then(|m| dml::media_ref(imp, part, m)).or_else(|| vf.or(af).and_then(|f| dml::media_ref(imp, part, f))); - if let Some(media) = media { - let mut clip = MediaClip { - media, - video: vf.is_some() || af.is_none(), - poster: pf.as_ref().map(|p| p.media), - crop: pf.as_ref().map(|p| p.crop).unwrap_or_default(), - volume: 1.0, - ..Default::default() - }; - if let Some(m) = p14 { - if let Some(t) = m.child("trim") { - clip.trim_start_ms = ms(t.attr("st")); - clip.trim_end_ms = ms(t.attr("end")); - } - if let Some(f) = m.child("fade") { - clip.fade_in_ms = ms(f.attr("in")); - clip.fade_out_ms = ms(f.attr("out")); - } - if let Some(l) = m.child("bmkLst") { - clip.bookmarks = - l.children_named("bmk").take(1000).map(|b| (b.attr("name").unwrap_or("").to_string(), ms(b.attr("time")))).collect(); - } - } - s.kind = ShapeKind::Media(clip); - return s; - } - } - match pf { - Some(fill) => s.kind = ShapeKind::Picture { fill }, - None => log::warn!("pptx: picture {} in {} has no readable image", s.name, part.name), - } - s -} - -fn grp(imp: &mut Imp, part: &Part, ctx: &mut IdCtx, e: &El, depth: usize) -> Shape { - let mut s = base(imp, part, ctx, e.child("nvGrpSpPr")); - let mut child = None; - if let Some(pr) = e.child("grpSpPr") { - if let Some(x) = pr.child("xfrm") { - let (xf, ch) = dml::xfrm(x); - s.xfrm = Some(xf); - child = ch; - } - s.fill = dml::fill_of(imp, part, pr); - if let Some(fx) = pr.child("effectLst") { - s.effects = Some(dml::effects(fx)); - } - if let Some(sc) = pr.child("scene3d") { - let raw = part.keep_inner(sc); - if !raw.is_empty() && raw.len() <= 64 * 1024 { - s.effects.get_or_insert_with(Effects::default).raw3d = Some(raw); - } - } - } - let children = sp_tree(imp, part, ctx, e, depth + 1); - let child = child.or_else(|| s.xfrm.map(|x| Xfrm::new(x.x, x.y, x.w, x.h))).unwrap_or_default(); - s.kind = ShapeKind::Group { children, child }; - s -} - -fn cxn(imp: &mut Imp, part: &Part, ctx: &mut IdCtx, e: &El) -> Shape { - let nv = e.child("nvCxnSpPr"); - let mut s = base(imp, part, ctx, nv); - if let Some(pr) = e.child("spPr") { - sp_pr(imp, part, &mut s, pr); - } - s.style = e.child("style").map(style); - let c = nv.and_then(|n| n.child("cNvCxnSpPr")); - let end = |n: &str| c.and_then(|c| c.child(n)).and_then(|x| Some((ShapeId(x.u32("id")?), x.u32("idx").unwrap_or(0)))); - s.kind = ShapeKind::Connector { start: end("stCxn"), end: end("endCxn") }; - s -} - -fn frame(imp: &mut Imp, part: &Part, ctx: &mut IdCtx, e: &El, depth: usize) -> Shape { - let mut s = base(imp, part, ctx, e.child("nvGraphicFramePr")); - if let Some(x) = e.child("xfrm") { - s.xfrm = Some(dml::xfrm(x).0); - } - let gd = e.path(&["graphic", "graphicData"]); - let uri = gd.and_then(|g| g.attr("uri")).unwrap_or(""); - if let Some(gd) = gd { - if let Some(tbl) = gd.child("tbl") { - s.kind = ShapeKind::Table(table(imp, part, tbl)); - return s; - } - if let Some(c) = gd.child("chart") - && let Some(chart) = super::chart::frame_chart(imp, part, c.attr("r:id").unwrap_or(""), uri) - { - s.kind = ShapeKind::Chart(Box::new(chart)); - return s; - } - if uri.ends_with("/diagram") - && let Some(g) = smartart(imp, part, gd, &s, depth) - { - return g; - } - } - // Something we don't model: keep its XML and show a preview picture when it has one. - let preview = { - let mut pics = vec![]; - e.find_all("blip", &mut pics); - pics.into_iter().find_map(|b| dml::media_ref(imp, part, b)) - } - .or_else(|| gd.and_then(|g| g.find("oleObj")).and_then(|o| vml_preview(imp, part, o.attr("spid")?))); - // An embedded object's fallback picture (`p:oleObj/p:pic`) can carry a fill and an outline, - // which PowerPoint draws behind and around the preview (old equation objects on coloured - // boxes). The frame's own position stays. - if let Some(pr) = gd.and_then(|g| g.find("oleObj")).and_then(|o| o.find("pic")).and_then(|p| p.child("spPr")) { - if s.fill.is_none() { - s.fill = dml::fill_of(imp, part, pr); - } - if s.line.is_none() { - s.line = pr.child("ln").map(|ln| dml::line(imp, part, ln)); - } - } - let label = if let Some(o) = gd.and_then(|g| g.find("oleObj")) { - o.attr("progId").or(o.attr("name")).unwrap_or("Object").to_string() - } else if uri.ends_with("/diagram") { - "SmartArt".to_string() - } else if uri.contains("chart") { - "Chart".to_string() - } else { - uri.rsplit('/').next().unwrap_or("Object").to_string() - }; - // Keep the parts it points to so a save writes it back whole (#203). A part with relationships - // of its own, or an external link, can't be carried: the save then falls back to the preview. - // Validate every relationship (and charge the budget) before copying anything, so a fallback - // that cannot be kept whole copies no part at all. - let mark = imp.mark(); - let mut planned = Vec::new(); - let mut spent = imp.diagram_xml_bytes; - let mut ok = true; - for id in super::rel_refs(e) { - let Some(rel) = part.rels.get(&id).filter(|r| !r.external) else { - ok = false; - break; - }; - let pkg = imp.pkg; - if *imp.has_rels.entry(crate::opc::norm(&rel.target)).or_insert_with(|| !pkg.rels(&rel.target).items.is_empty()) { - ok = false; - break; - } - // A diagram's definition parts copied here count against the same presentation-wide budget. - if rel.kind.starts_with("diagram") && !imp.media_by_part.contains_key(&crate::opc::norm(&rel.target)) { - let len = pkg.get(&rel.target).map_or(0, |b| b.len()); - if len > MAX_DIAGRAM_PART_BYTES || spent.saturating_add(len) > MAX_DIAGRAM_XML_BYTES { - ok = false; - break; - } - spent += len; - } - if pkg.get(&rel.target).is_none() { - ok = false; - break; - } - planned.push((id, rel.ty.clone(), rel.target.clone(), rel.kind == "diagramData")); - } - let parts = if ok { - imp.diagram_xml_bytes = spent; - let copied: Option> = planned - .into_iter() - .map(|(id, kind, target, data)| { - let media = if data { diagram_data(imp, &target) } else { imp.media_for(&target) }; - Some((id, kind, media?)) - }) - .collect(); - if copied.is_none() { - imp.rollback(&mark); - } - copied - } else { - None - }; - let parts = parts.unwrap_or_default(); - s.kind = ShapeKind::Opaque { xml: part.keep(e), preview, label, parts }; - s -} - -/// The preview picture of an old-style embedded object (`p:oleObj spid` with no `p:pic`): the -/// `v:imagedata` of the legacy VML drawing shape with that id, as PowerPoint 2007 wrote them. -fn vml_preview(imp: &mut Imp, part: &Part, spid: &str) -> Option { - for rel in part.rels.items.iter().filter(|r| r.kind == "vmlDrawing" && !r.external) { - let key = crate::opc::norm(&rel.target); - if !imp.vml_previews.contains_key(&key) { - let index = vml_index(imp.pkg, &rel.target); - imp.vml_previews.insert(key.clone(), index); - } - let Some(target) = imp.vml_previews.get(&key).and_then(|m| m.get(spid)).cloned() else { continue }; - return imp.media_for(&target); - } - None -} - -/// Every shape id in a VML drawing with a picture, mapped to that picture's part: parsed once per -/// drawing however many objects look it up. -fn vml_index(pkg: &crate::opc::Package, vml: &str) -> std::collections::HashMap { - let mut out = std::collections::HashMap::new(); - let Some(doc) = pkg.xml(vml) else { return out }; - let rels = pkg.rels(vml); - let mut shapes = vec![]; - doc.root.find_all("shape", &mut shapes); - for s in shapes { - let Some(id) = s.attr("id") else { continue }; - if out.contains_key(id) { - continue; // the first shape with an id wins, as the old lookup did - } - let Some(img) = s.find("imagedata") else { continue }; - let Some(rid) = img.attr("o:relid").or(img.attr("r:id")) else { continue }; - if let Some(r) = rels.get(rid).filter(|r| !r.external) { - out.insert(id.to_string(), r.target.clone()); - } - } - out -} - -/// A diagram's data part, without the link to its cached drawing: that link is a slide -/// relationship id, which a save renumbers. Only diagrams whose drawing is missing or empty get -/// here, and those are drawn from their data. -fn diagram_data(imp: &mut Imp, target: &str) -> Option { - let norm_target = crate::opc::norm(target); - if let Some(&id) = imp.media_by_part.get(&norm_target) { - return Some(id); - } - fn strip(e: &mut El, depth: usize) { - if depth > crate::xml::MAX_DEPTH { - return; - } - e.children.retain(|n| !matches!(n, crate::xml::Node::El(c) if c.is("ext") && c.find("dataModelExt").is_some())); - for c in e.elements_mut() { - strip(c, depth + 1); - } - } - let mut doc = imp.pkg.xml(target)?; - strip(&mut doc.root, 0); - let xml = format!("\n{}", doc.root.to_xml()); - let id = deckcraft_model::MediaId(imp.alloc()); - let content_type = imp.pkg.content_type(target)?; - imp.media.push(deckcraft_model::MediaItem { - id, - name: crate::opc::file_of(target).to_string(), - content_type, - data: std::sync::Arc::new(xml.into_bytes()), - link: None, - }); - imp.media_keys.push(norm_target.clone()); - imp.media_by_part.insert(norm_target, id); - Some(id) -} - -/// Shapes all SmartArt drawings of one presentation may add; a frame read after that is left as a -/// placeholder. Each frame that references a drawing reads it again. -const MAX_SMARTART_SHAPES: usize = 250_000; - -/// SmartArt definition XML (layout, style, colours) all diagrams of one presentation may copy. -const MAX_DIAGRAM_XML_BYTES: usize = 32 << 20; - -/// The largest single diagram definition part copied. -const MAX_DIAGRAM_PART_BYTES: usize = 4 << 20; - -fn count_shapes(shapes: &[Shape]) -> usize { - shapes.iter().map(|s| 1 + count_shapes(s.children())).sum() -} - -/// SmartArt: read the pre-drawn shapes of its drawing part as a group. -fn smartart(imp: &mut Imp, part: &Part, gd: &El, frame: &Shape, depth: usize) -> Option { - if depth > 8 || imp.smartart_shapes >= MAX_SMARTART_SHAPES { - return None; - } - let rel_ids = gd.child("relIds")?; - let dm = part.rels.get(rel_ids.attr("r:dm").unwrap_or(""))?; - let data = imp.pkg.xml(&dm.target)?; - let drawing_rel = data.root.find("dataModelExt").and_then(|x| x.attr("relId")).and_then(|id| part.rels.get(id)).map(|r| r.target.clone())?; - let mut d = imp.pkg.xml(&drawing_rel)?; - super::resolve_mc(&mut d.root, 0); - let dpart = Part::new(imp.pkg, &drawing_rel, &d); - let tree = d.root.child("spTree")?; - let mut sub = IdCtx { fresh: true, ..Default::default() }; - let before = imp.smartart_shapes; - let mark = imp.mark(); - let children = sp_tree(imp, &dpart, &mut sub, tree, depth + 1); - if children.is_empty() { - return None; - } - // Counted once here, nested SmartArt included: a drawing that frames reuse counts every time it is read. - let total = before.saturating_add(count_shapes(&children)); - if total > MAX_SMARTART_SHAPES { - // Over the presentation's remaining budget: a placeholder, and nothing charged, nested SmartArt included. - imp.smartart_shapes = before; - imp.rollback(&mark); - return None; - } - imp.smartart_shapes = total; - let children = smartart_text_rects(imp, &mut sub, tree, children, depth + 1); - let mut g = frame.clone(); - let x = frame.xfrm.unwrap_or_default(); - g.kind = ShapeKind::Group { children, child: Xfrm::new(0.0, 0.0, x.w, x.h) }; - g.diagram = diagram_outline(imp, part, rel_ids, &data.root); - // Node pictures, from the blips of the data model's presentation points. - if let Some(d) = &mut g.diagram { - let rels = imp.pkg.rels(&dm.target); - for (k, rid) in crate::dgm::node_pictures(&data.root) { - let Some(target) = rels.get(&rid).filter(|r| !r.external).map(|r| r.target.clone()) else { continue }; - let media = imp.media_for(&target); - if let Some(n) = d.nodes.get_mut(k) { - n.picture = media; - } - } - } - Some(g) -} - -/// A SmartArt drawing shape (`dsp:sp`) keeps its text rectangle in `dsp:txXfrm`, apart from the -/// shape's own box: the text of a narrow shape turned by 90° is often laid out across it. Put each -/// shape's text on that rectangle. `shapes` are what [`sp_tree`] read from `tree`, in order. -fn smartart_text_rects(imp: &mut Imp, ctx: &mut IdCtx, tree: &El, shapes: Vec, depth: usize) -> Vec { - if depth > MAX_TREE_DEPTH { - return shapes; - } - let mut out = Vec::with_capacity(shapes.len()); - let mut shapes = shapes.into_iter(); - // The same elements `sp_tree` turns into shapes. - for e in tree.elements().filter(|e| matches!(e.local(), "sp" | "pic" | "grpSp" | "cxnSp" | "graphicFrame")) { - let Some(mut s) = shapes.next() else { break }; - let mut text_box = None; - match (e.local(), &mut s.kind) { - ("grpSp", ShapeKind::Group { children, .. }) => { - let kids = std::mem::take(children); - *children = smartart_text_rects(imp, ctx, e, kids, depth + 1); - } - ("sp", ShapeKind::Shape) => { - if let Some(t) = e.child("txXfrm") { - text_box = text_on_rect(imp, ctx, &mut s, dml::xfrm(t).0); - } - } - _ => {} - } - out.push(s); - out.extend(text_box); - } - out.extend(shapes); - out -} - -/// Lay out the text of `s` on `t`, a text rectangle in the same space as the shape's box, turned by -/// the shape's rotation plus its own. When that is the shape's text area shrunk by some margin, the -/// shape keeps its text with wider insets. Otherwise (a rectangle reaching outside the shape, or -/// turned against it) the text moves to a new frameless text shape over `s`, which is returned: -/// both export as plain DrawingML that any reader lays out the same way. -fn text_on_rect(imp: &mut Imp, ctx: &mut IdCtx, s: &mut Shape, t: Xfrm) -> Option { - const EPS: f64 = 0.01; - let x = s.xfrm?; - if !x.is_finite() || !t.is_finite() || t.w <= EPS || t.h <= EPS { - return None; - } - let body = s.text.as_mut().filter(|b| !b.is_empty())?; - let turn = |a: f64| a.rem_euclid(360.0); - let upright = |a: f64| turn(a + EPS) < 2.0 * EPS; - let bp = &mut body.body; - if !x.flip_h - && !x.flip_v - && upright(t.rot) - && bp.rot.is_none_or(upright) - && bp.vert.is_none_or(|v| v == TextDir::Horizontal) - && bp.upright != Some(true) - { - // Same orientation as the shape: express the rectangle as insets from the shape's text area. - let c = x.affine().inverse() * t.center(); - let (l, top) = (c.x - t.w / 2.0, c.y - t.h / 2.0); - let (r, b) = (l + t.w, top + t.h); - let area = text_area(&s.geom, x.w, x.h); - let extra = [l - area.x0, top - area.y0, area.x1 - r, area.y1 - b]; - if extra.iter().all(|v| v.is_finite() && *v >= -EPS) { - let [el, et, er, eb] = extra.map(|v| v.max(0.0)); - bp.inset_l = Some(bp.inset_l.unwrap_or(7.2) + el); - bp.inset_t = Some(bp.inset_t.unwrap_or(3.6) + et); - bp.inset_r = Some(bp.inset_r.unwrap_or(7.2) + er); - bp.inset_b = Some(bp.inset_b.unwrap_or(3.6) + eb); - return None; - } - } - if ctx.count >= MAX_SHAPES || imp.smartart_shapes >= MAX_SMARTART_SHAPES { - return None; - } - ctx.count += 1; - imp.smartart_shapes += 1; - let text = s.text.take(); - // No fill, outline or effects; the style keeps only the text colour and font. - let style = s.style.clone().map(|mut st| { - st.fill_ref.0 = 0; - st.line_ref.0 = 0; - st.effect_ref.0 = 0; - st - }); - Some(Shape { - id: ctx.assign(imp, None), - name: s.name.clone(), - xfrm: Some(Xfrm { rot: turn(x.rot + t.rot), flip_h: false, flip_v: false, ..t }), - fill: Some(Fill::None), - line: Some(deckcraft_model::style::Line { fill: Some(Fill::None), ..Default::default() }), - style, - text, - click: s.click.clone(), - hover: s.hover.clone(), - ..Default::default() - }) -} - -/// Where a shape's geometry puts its text, in shape-local points (as the renderer computes it). -fn text_area(geom: &Geom, w: f64, h: f64) -> deckcraft_geom::Rect { - let full = deckcraft_geom::Rect::new(0.0, 0.0, w, h); - match geom { - Geom::Preset { name, adj } => { - preset::build(name, w, h, adj).or_else(|| preset::build("rect", w, h, &[])).map(|g| g.text_rect).unwrap_or(full) - } - Geom::Custom { .. } => full, - } -} - -/// The outline of a SmartArt graphic (for the Text Pane), with its layout, quick style and colour -/// parts kept to be written back. -fn diagram_outline(imp: &mut Imp, part: &Part, rel_ids: &El, data: &El) -> Option { - let nodes = crate::dgm::outline(data); - if nodes.is_empty() { - return None; - } - let (pkg, spent) = (imp.pkg, std::cell::Cell::new(imp.diagram_xml_bytes)); - let raw = |attr: &str| -> Option { - let rel = part.rels.get(rel_ids.attr(attr)?)?; - let bytes = pkg.get(&rel.target)?; - // Every diagram copies its definitions, so the copies share one presentation-wide budget. - if bytes.len() > MAX_DIAGRAM_PART_BYTES || spent.get().saturating_add(bytes.len()) > MAX_DIAGRAM_XML_BYTES { - return None; - } - let xml = String::from_utf8(bytes.to_vec()).ok()?; - spent.set(spent.get() + xml.len()); - Some(xml) - }; - let layout_xml = raw("r:lo"); - let (layout_id, cat) = layout_xml - .as_deref() - .and_then(|x| crate::xml::parse(x.as_bytes()).ok()) - .map(|d| { - let cat = d.root.child("catLst").and_then(|c| c.child("cat")).and_then(|c| c.attr("type")).unwrap_or("").to_string(); - (d.root.attr("uniqueId").unwrap_or("").to_string(), cat) - }) - .unwrap_or_default(); - let lo_type = data - .path(&["ptLst"]) - .and_then(|l| l.children_named("pt").find(|p| p.attr("type") == Some("doc"))) - .and_then(|p| p.child("prSet")) - .and_then(|p| p.attr("loTypeId")) - .unwrap_or(""); - let id = if layout_id.is_empty() { lo_type.to_string() } else { layout_id }; - let pr = data.path(&["ptLst"]).and_then(|l| l.children_named("pt").find(|p| p.attr("type") == Some("doc"))).and_then(|p| p.child("prSet")); - let style = crate::dgm::style_for(pr.and_then(|p| p.attr("qsTypeId")).unwrap_or("")).to_string(); - let colors = crate::dgm::colors_for(pr.and_then(|p| p.attr("csTypeId")).unwrap_or("")); - let (style_xml, colors_xml) = (raw("r:qs"), raw("r:cs")); - imp.diagram_xml_bytes = spent.get(); - Some(deckcraft_model::Diagram { - kind: crate::dgm::kind_for(&id, &cat).to_string(), - nodes, - style, - colors, - imported: true, - // Without the layout part the writer generates one for `kind`; empty keeps data's loTypeId in step with it. - layout_id: if layout_xml.is_some() { id } else { String::new() }, - layout_xml, - style_xml, - colors_xml, - }) -} - -fn table(imp: &mut Imp, part: &Part, tbl: &El) -> Table { - // A table naming no style is drawn by PowerPoint with thin dark grid lines ("No Style, Table - // Grid"), not without lines. - let mut t = Table { style: "grid".into(), first_row: false, band_row: false, ..Default::default() }; - if let Some(pr) = tbl.child("tblPr") { - t.background = pr.elements().find(|e| e.local().ends_with("Fill") && e.local() != "noFill").and_then(|f| dml::fill_el(imp, part, f)); - t.first_row = pr.bool("firstRow").unwrap_or(false); - t.first_col = pr.bool("firstCol").unwrap_or(false); - t.last_row = pr.bool("lastRow").unwrap_or(false); - t.last_col = pr.bool("lastCol").unwrap_or(false); - t.band_row = pr.bool("bandRow").unwrap_or(false); - t.band_col = pr.bool("bandCol").unwrap_or(false); - t.rtl = pr.bool("rtl"); - if let Some(id) = pr.child("tableStyleId").map(|e| e.text()) { - // A style the file defines is drawn from its definition (by its GUID). - // DeckCraft's own styles (written with GUIDs derived from their ids) map back to them. - let up = id.trim().to_ascii_uppercase(); - t.style = - if imp.table_style_ids.contains(&up) && !crate::tables::is_own_guid(&up) { up } else { crate::tables::style_from_guid(id.trim()) }; - } - } - t.cols = tbl - .child("tblGrid") - .map(|g| g.children_named("gridCol").take(1000).map(|c| dml::pt(c, "w").unwrap_or(72.0).clamp(0.0, 20_000.0)).collect()) - .unwrap_or_default(); - for tr in tbl.children_named("tr").take(1000) { - let mut row = Row { height: dml::pt(tr, "h").unwrap_or(0.0).clamp(0.0, 20_000.0), cells: vec![] }; - for tc in tr.children_named("tc").take(1000) { - row.cells.push(cell(imp, part, tc)); - } - t.rows.push(row); - } - if t.cols.is_empty() { - let n = t.rows.iter().map(|r| r.cells.len()).max().unwrap_or(0); - t.cols = vec![72.0; n]; - } - if t.over_cap() { - imp.warn(format!("a table in {} is over {} cells; its last rows were left out", part.name, deckcraft_model::table::MAX_CELLS)); - } - t.normalize(); - t -} - -fn cell(imp: &mut Imp, part: &Part, tc: &El) -> Cell { - let mut c = Cell { - grid_span: tc.u32("gridSpan").unwrap_or(1).clamp(1, 1000), - row_span: tc.u32("rowSpan").unwrap_or(1).clamp(1, 1000), - h_merge: tc.bool("hMerge").unwrap_or(false), - v_merge: tc.bool("vMerge").unwrap_or(false), - ..Default::default() - }; - if let Some(tx) = tc.child("txBody") { - c.text = dml::text_body(imp, part, tx); - } - if let Some(pr) = tc.child("tcPr") { - if ["marL", "marR", "marT", "marB"].iter().any(|n| pr.has_attr(n)) { - c.margins = Some([ - dml::pt(pr, "marL").unwrap_or(7.2), - dml::pt(pr, "marR").unwrap_or(7.2), - dml::pt(pr, "marT").unwrap_or(3.6), - dml::pt(pr, "marB").unwrap_or(3.6), - ]); - } - c.anchor = pr.attr("anchor").and_then(Anchor::from_xml); - c.anchor_ctr = pr.bool("anchorCtr"); - c.horz_overflow = pr.attr("horzOverflow").and_then(deckcraft_model::text::TextOverflow::from_horz_xml); - c.vertical = pr.attr("vert").and_then(TextDir::from_xml); - for (i, n) in ["lnL", "lnR", "lnT", "lnB"].iter().enumerate() { - if let Some(ln) = pr.child(n) - && let Some(b) = c.borders.get_mut(i) - { - *b = Some(dml::line(imp, part, ln)); - } - } - c.diag_down = pr.child("lnTlToBr").map(|l| dml::line(imp, part, l)); - c.diag_up = pr.child("lnBlToTr").map(|l| dml::line(imp, part, l)); - c.fill = dml::fill_of(imp, part, pr); - } - c -} - -#[cfg(test)] -mod preset_geom_tests { - use super::*; - - fn geom(xml: &str) -> Geom { - let doc = crate::xml::parse(xml.as_bytes()).unwrap(); - preset_geom(&doc.root) - } - - // A file may give some adjust values and rely on the defaults for the rest. A preset outside the - // gallery had no defaults, so a missing value read as 0: a bentConnector4 with only adj2 lost - // its middle leg. - #[test] - fn a_missing_adjust_value_takes_the_spec_default() { - let a = r#"xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main""#; - let g = geom(&format!(r#""#)); - assert!(matches!(&g, Geom::Preset { name, adj } if name == "bentConnector4" && adj == &[50000.0, 25000.0]), "{g:?}"); - let g = geom(&format!(r#""#)); - assert!(matches!(&g, Geom::Preset { adj, .. } if adj == &[50000.0, 50000.0, 10000.0]), "{g:?}"); - } -} diff --git a/crates/pptx/src/read/theme.rs b/crates/pptx/src/read/theme.rs deleted file mode 100644 index d5ca8df84..000000000 --- a/crates/pptx/src/read/theme.rs +++ /dev/null @@ -1,114 +0,0 @@ -//! Theme parts (`a:theme`). - -use deckcraft_color::{ColorScheme, Rgba, SchemeSlot}; -use deckcraft_model::style::{ColorBase, Effects}; -use deckcraft_model::theme::{FontScheme, FontSet, FormatScheme, ScriptFont, Theme, default_format}; - -use super::{Imp, Part, dml}; -use crate::xml::El; - -fn font_set(e: Option<&El>) -> FontSet { - let tf = |n: &str| e.and_then(|e| e.child(n)).and_then(|c| c.attr("typeface")).unwrap_or("").to_string(); - let scripts = e - .map(|e| { - e.children_named("font") - .filter_map(|f| Some(ScriptFont { script: f.attr("script")?.to_string(), typeface: f.attr("typeface").unwrap_or("").to_string() })) - .take(256) - .collect() - }) - .unwrap_or_default(); - FontSet { latin: tf("latin"), ea: tf("ea"), cs: tf("cs"), scripts } -} - -/// Bytes of preserved theme XML (object defaults and extra colour schemes) all masters of one -/// presentation may keep. -const MAX_THEME_EXTRA_BYTES: usize = 16 << 20; - -pub fn read_theme(imp: &mut Imp, part: &Part, root: &El) -> Theme { - let mut t = Theme { name: root.attr("name").unwrap_or("Theme").to_string(), ..Default::default() }; - let Some(te) = root.child("themeElements") else { return t }; - if let Some(cs) = te.child("clrScheme") { - let mut scheme = ColorScheme::new(cs.attr("name").unwrap_or("").to_string(), t.colors.colors); - for slot in SchemeSlot::THEME { - if let Some(c) = cs.child(slot.xml_name()).and_then(dml::color) { - let rgb = match c.base { - ColorBase::Rgb { rgb } => rgb, - ColorBase::System { last, .. } => last, - ColorBase::Preset { name } => deckcraft_color::preset(&name).unwrap_or(Rgba::BLACK), - ColorBase::Scheme { .. } => continue, - }; - scheme.set(slot, rgb); - } - } - t.colors = scheme; - } - if let Some(fs) = te.child("fontScheme") { - t.fonts = FontScheme { - name: fs.attr("name").unwrap_or("").to_string(), - major: font_set(fs.child("majorFont")), - minor: font_set(fs.child("minorFont")), - }; - } - if let Some(fm) = te.child("fmtScheme") { - let dflt = default_format(); - let mut f = FormatScheme { name: fm.attr("name").unwrap_or("").to_string(), ..Default::default() }; - if let Some(l) = fm.child("fillStyleLst") { - f.fills = l.elements().take(16).filter_map(|e| dml::fill_el(imp, part, e)).collect(); - } - if let Some(l) = fm.child("lnStyleLst") { - f.lines = l.children_named("ln").take(16).map(|e| dml::line(imp, part, e)).collect(); - } - if let Some(l) = fm.child("effectStyleLst") { - f.effects = l - .children_named("effectStyle") - .take(16) - .map(|e| { - let mut fx = e.child("effectLst").map(dml::effects).unwrap_or_default(); - if let Some(b) = e.path(&["sp3d", "bevelT"]) { - fx.bevel = Some(b.attr("prst").unwrap_or("circle").to_string()); - } - let raw: String = e.elements().filter(|c| c.is("scene3d") || c.is("sp3d")).map(|c| part.keep(c)).collect(); - if !raw.is_empty() { - fx.raw3d = Some(raw); - } - fx - }) - .collect(); - } - if let Some(l) = fm.child("bgFillStyleLst") { - f.bg_fills = l.elements().take(16).filter_map(|e| dml::fill_el(imp, part, e)).collect(); - } - // The style matrix needs three entries of each kind. - pad(&mut f.fills, &dflt.fills); - pad(&mut f.lines, &dflt.lines); - pad(&mut f.bg_fills, &dflt.bg_fills); - while f.effects.len() < 3 { - f.effects.push(Effects::default()); - } - t.format = f; - } - let extra: String = root - .elements() - .filter(|e| e.is("objectDefaults") || e.is("extraClrSchemeLst")) - .filter(|e| !super::has_rel_refs(e)) - .map(|e| part.keep(e)) - .collect(); - // Every master that references this theme keeps its own copy of the preserved XML, so the - // copies share one budget for the presentation. - if !extra.is_empty() && imp.theme_extra_bytes.saturating_add(extra.len()) <= MAX_THEME_EXTRA_BYTES { - imp.theme_extra_bytes += extra.len(); - t.raw_extra = Some(extra); - } else if !extra.is_empty() { - log::warn!("pptx: theme object defaults not kept; the preserved-XML budget is spent"); - } - t -} - -fn pad(v: &mut Vec, d: &[T]) { - while v.len() < 3 { - match d.get(v.len()) { - Some(x) => v.push(x.clone()), - None => break, - } - } -} diff --git a/crates/pptx/src/read/timing.rs b/crates/pptx/src/read/timing.rs deleted file mode 100644 index ca29f4592..000000000 --- a/crates/pptx/src/read/timing.rs +++ /dev/null @@ -1,493 +0,0 @@ -//! Slide transitions (`p:transition`) and animations (`p:timing`). - -use deckcraft_model::anim::{AnimClass, AnimStart, Animation, BuildRole, TextBuild, Transition, build_filled, paragraph_build_roles}; -use deckcraft_model::{Shape, ShapeKind, TextBody, find_shape, find_shape_mut}; - -use super::shapes::IdCtx; -use super::{Imp, Part, dml}; -use crate::maps; -use crate::xml::El; - -fn ms_attr(e: &El, name: &str) -> Option { - let v = e.attr(name)?.trim(); - if v == "indefinite" { - return None; - } - v.parse::().ok().filter(|v| v.is_finite()).map(|v| v.clamp(0.0, 86_400_000.0) as u32) -} - -pub fn transition(imp: &mut Imp, part: &Part, t: &El) -> Option { - let effect = t.elements().find(|e| !matches!(e.local(), "sndAc" | "extLst")); - let mut tr = Transition { advance_on_click: t.bool("advClick").unwrap_or(true), advance_after_ms: ms_attr(t, "advTm"), ..Default::default() }; - match effect.and_then(maps::transition_from_xml) { - Some((k, o)) => { - tr.kind = k; - tr.option = o; - } - None => match effect { - Some(e) => { - tr.kind = e.local().to_string(); - tr.raw = Some(part.keep(t)); - } - None => tr.kind = "none".into(), - }, - } - let default_dur = deckcraft_model::anim::TRANSITIONS.iter().find(|x| x.0 == tr.kind).map(|x| x.3).unwrap_or(1000); - // `spd` defaults to "fast" in the schema; PowerPoint omits both attributes for 0.5 s. - tr.duration_ms = ms_attr(t, "dur").unwrap_or(match t.attr("spd") { - Some("med") => 750, - Some("slow") => default_dur.max(1000), - _ => 500, - }); - if let Some(snd) = t.path(&["sndAc", "stSnd", "snd"]) { - tr.sound = dml::media_ref(imp, part, snd); - tr.sound_loop = t.path(&["sndAc", "stSnd"]).and_then(|s| s.attr("loop")).is_some_and(|v| v == "1" || v == "true"); - } - tr.stop_sound = t.path(&["sndAc", "endSnd"]).is_some(); - if tr.kind == "none" && tr.advance_on_click && tr.advance_after_ms.is_none() && tr.sound.is_none() && !tr.stop_sound { - return None; - } - Some(tr) -} - -struct Found<'a> { - ctn: &'a El, - trigger: Option, - /// Click group the effect sits in: a new one starts at every time node whose start is `indefinite`. - group: usize, - /// Sum of the start delays of the time nodes between the click group and the effect, in ms. - offset: u32, - /// Whether any ancestor time node defers start until an event (`onClick`, `onEnd`, targeted `onBegin`) or nonzero delay. - deferred: bool, -} - -/// Where `collect` is in the time tree: the click group and the delay accumulated inside it. -#[derive(Clone, Copy)] -struct At { - trigger: Option, - main_seq_id: Option, - group: usize, - offset: u32, - deferred: bool, -} - -/// Returns whether `st` (`p:stCondLst`) is PowerPoint's automatic main-sequence step wrapper: -/// `` paired only with `` -/// referencing the immediate enclosing `mainSeq` ``. -fn is_main_seq_auto(st: &El, main_seq_id: Option) -> bool { - let Some(ms_id) = main_seq_id else { - return false; - }; - let is_indefinite = |d: &El| { - d.attr("evt").is_none() - && d.attr("delay").map(str::trim) == Some("indefinite") - && d.child("tgtEl").is_none() - && d.child("tn").is_none() - && d.child("rtn").is_none() - }; - let is_main_seq_on_begin = |d: &El| { - d.attr("evt") == Some("onBegin") - && d.attr("delay").map(str::trim) == Some("0") - && d.child("tgtEl").is_none() - && d.child("rtn").is_none() - && d.child("tn").and_then(|tn| tn.u32("val")) == Some(ms_id) - }; - st.children_named("cond").any(is_indefinite) - && st.children_named("cond").any(is_main_seq_on_begin) - && st.children_named("cond").all(|d| is_indefinite(d) || is_main_seq_on_begin(d)) -} - -fn collect<'a>(e: &'a El, at: At, groups: &mut usize, out: &mut Vec>, depth: usize) { - if depth > 64 || out.len() > 10_000 { - return; - } - for c in e.elements() { - if c.is("cTn") && c.has_attr("presetClass") { - let deferred = at.deferred || c.child("stCondLst").is_some_and(defers_start); - out.push(Found { ctn: c, trigger: at.trigger, group: at.group, offset: at.offset, deferred }); - continue; - } - let mut at = at; - if c.is("seq") - && let Some(ctn) = c.child("cTn") - && ctn.attr("nodeType") == Some("interactiveSeq") - { - at.trigger = ctn.path(&["stCondLst", "cond", "tgtEl", "spTgt"]).and_then(|s| s.u32("spid")); - at.main_seq_id = None; - } - if c.is("cTn") { - let is_main_seq = c.attr("nodeType") == Some("mainSeq"); - if let Some(st) = c.child("stCondLst") { - if !(!is_main_seq && !at.deferred && is_main_seq_auto(st, at.main_seq_id)) && defers_start(st) { - at.deferred = true; - } - if let Some(cond) = st.child("cond") { - if cond.attr("delay").map(str::trim) == Some("indefinite") { - *groups += 1; - at.group = *groups; - at.offset = 0; - } else { - at.offset = at.offset.saturating_add(ms_attr(cond, "delay").unwrap_or(0)); - } - } - } - at.main_seq_id = if is_main_seq && !at.deferred { c.u32("id") } else { None }; - } - collect(c, at, groups, out, depth + 1); - } -} - -/// How long an effect holds back an After Previous one, as the show timeline counts it. -fn span_ms(a: &Animation) -> u32 { - let iterations = if a.repeat == u32::MAX || a.repeat <= 1 { 1 } else { a.repeat.min(1_000) }; - a.duration_ms.saturating_mul(if a.auto_reverse { 2 } else { 1 }).saturating_mul(iterations) -} - -/// Start times (ms after the click) that the flat effect list plays at, effect after effect. -fn flat_starts(anims: &[&Animation]) -> Vec { - let (mut begin, mut end) = (0u32, 0u32); - anims - .iter() - .map(|a| { - if a.start == AnimStart::AfterPrevious { - begin = end; - } - let start = begin.saturating_add(a.delay_ms); - end = end.max(start.saturating_add(span_ms(a))); - start - }) - .collect() -} - -/// PowerPoint places each effect at the delays of all its enclosing time nodes, so a file may list -/// effects out of time order (a countdown written first, then effects at 5 s placed only by their -/// parent's delay). The flat list only knows "after/with previous" plus the effect's own delay, so -/// a click group listed out of time order, whose flat reading disagrees with the file, is sorted by -/// start time and its starts and delays rewritten to land every effect where PowerPoint plays it. -/// Every other group is left untouched. -fn place_by_parent_delays(out: &mut [(Animation, u32, String, bool, usize, u32)], at: &[(Option, usize, u32)]) { - let mut groups: Vec> = vec![]; - let mut slot: std::collections::HashMap<(Option, usize), usize> = std::collections::HashMap::new(); - for (i, &(t, g, _)) in at.iter().enumerate() { - let n = *slot.entry((t, g)).or_insert_with(|| { - groups.push(vec![]); - groups.len() - 1 - }); - groups[n].push(i); - } - for idx in groups { - // More than one click in a group means the tree isn't one click per group: leave it. - if idx.iter().skip(1).any(|&i| out[i].0.start == AnimStart::OnClick) { - continue; - } - let abs: Vec = idx.iter().map(|&i| at[i].2.saturating_add(out[i].0.delay_ms)).collect(); - // Only a file that lists effects out of time order needs this: files PowerPoint or DeckCraft - // save are in order, and their reading stays exactly as before. - if abs.is_sorted() { - continue; - } - let flat = flat_starts(&idx.iter().map(|&i| &out[i].0).collect::>()); - if flat == abs { - continue; - } - // The group's click stays on whichever effect now plays first. - let had_click = out[idx[0]].0.start == AnimStart::OnClick; - let mut order: Vec = (0..idx.len()).collect(); - order.sort_by_key(|&k| abs[k]); - let mut sorted: Vec<(Animation, u32, String, bool, usize, u32)> = order.iter().map(|&k| out[idx[k]].clone()).collect(); - let (mut begin, mut end) = (0u32, 0u32); - for (n, (&k, item)) in order.iter().zip(sorted.iter_mut()).enumerate() { - let a = &mut item.0; - let t = abs[k]; - if n == 0 && had_click { - a.start = AnimStart::OnClick; - a.delay_ms = t; - } else if a.start == AnimStart::AfterPrevious && t >= end { - begin = end; - a.delay_ms = t - end; - } else { - a.start = AnimStart::WithPrevious; - a.delay_ms = t.saturating_sub(begin); - } - item.5 = 0; - end = end.max(t.saturating_add(span_ms(a))); - } - for (&i, item) in idx.iter().zip(sorted) { - out[i] = item; - } - } -} - -fn max_dur(e: &El, depth: usize) -> Option { - if depth > 64 { - return None; - } - let mut best: Option = None; - for c in e.elements() { - if c.is("cTn") - && let Some(d) = ms_attr(c, "dur") - && d > 1 - { - best = Some(best.map_or(d, |b: u32| b.max(d))); - } - if let Some(d) = max_dur(c, depth + 1) { - best = Some(best.map_or(d, |b| b.max(d))); - } - } - best -} - -/// Does every behaviour time node (`p:cBhvr/p:cTn`) under the effect node `c` carry `autoRev`? -fn behaviour_auto_reverses(c: &El) -> bool { - let mut behaviours = vec![]; - c.find_all("cBhvr", &mut behaviours); - !behaviours.is_empty() && behaviours.iter().all(|b| b.child("cTn").and_then(|t| t.bool("autoRev")).unwrap_or(false)) -} - -/// Volume, mute, Loop until Stopped, Hide While Not Playing and Play Full Screen live in the timing tree -/// (`p:video`/`p:audio` > `p:cMediaNode`), not on the picture: copy them onto the target's `MediaClip`. -/// Returns whether `st` (`p:stCondLst`) defers playback instead of starting immediately on slide entry. -fn defers_start(st: &El) -> bool { - let is_auto_begin = |c: &El| { - c.attr("evt") == Some("onBegin") - && c.attr("delay").map(str::trim) == Some("0") - && c.child("tgtEl").is_none() - && c.child("tn").is_none() - && c.child("rtn").is_none() - }; - let has_on_begin = st.children_named("cond").any(is_auto_begin); - st.children_named("cond") - .any(|c| (c.attr("evt").is_some() && !is_auto_begin(c)) || (!has_on_begin && c.attr("delay").map(str::trim) != Some("0"))) -} - -/// Applies `p:video`/`p:audio` timing node settings and main-sequence autoplay triggers to media shapes. -pub fn media_settings(timing: &El, ctx: &IdCtx, shapes: &mut [Shape]) { - fn collect_media<'a>(e: &'a El, deferred: bool, out: &mut Vec<(&'a El, bool)>, depth: usize) { - if depth > 64 || out.len() >= 10_000 { - return; - } - let mut deferred = deferred; - if e.is("cTn") - && let Some(st) = e.child("stCondLst") - && defers_start(st) - { - deferred = true; - } - if e.is("video") || e.is("audio") { - out.push((e, deferred)); - return; - } - for c in e.elements() { - collect_media(c, deferred, out, depth + 1); - } - } - let mut nodes = vec![]; - collect_media(timing, false, &mut nodes, 0); - for (node, deferred) in nodes { - let Some(cm) = node.child("cMediaNode") else { continue }; - let Some(id) = cm.path(&["tgtEl", "spTgt"]).and_then(|t| t.u32("spid")).and_then(|f| ctx.lookup(f)) else { continue }; - let Some(ShapeKind::Media(clip)) = find_shape_mut(shapes, id).map(|s| &mut s.kind) else { continue }; - if let Some(v) = cm.attr("vol").and_then(|v| v.trim().parse::().ok()).filter(|v| v.is_finite()) { - clip.volume = (v / 100_000.0).clamp(0.0, 1.0); - } - if cm.bool("mute") == Some(true) { - clip.volume = 0.0; - } - if cm.bool("showWhenStopped") == Some(false) { - clip.hide_while_not_playing = true; - } - if cm.child("cTn").and_then(|c| c.attr("repeatCount")) == Some("indefinite") { - clip.loop_play = true; - } - if cm.child("cTn").and_then(|c| c.attr("fill")) == Some("remove") { - clip.rewind = true; - } - if cm.u32("numSld").is_some_and(|n| n > 1) { - clip.play_across_slides = true; - } - if !deferred && cm.path(&["cTn", "stCondLst", "cond"]).is_some_and(|c| c.attr("evt").is_none() && c.attr("delay").map(str::trim) == Some("0")) - { - clip.autoplay = true; - } - if node.bool("fullScrn") == Some(true) { - clip.full_screen = true; - } - } - let root_deferred = timing.path(&["tnLst", "par", "cTn", "stCondLst"]).is_some_and(defers_start); - if !root_deferred && let Some(tn) = timing.child("tnLst") { - let mut found = vec![]; - collect(tn, At { trigger: None, main_seq_id: None, group: 0, offset: 0, deferred: false }, &mut 0, &mut found, 0); - for f in found.into_iter().filter(|f| f.trigger.is_none()) { - let c = f.ctn; - if c.attr("nodeType") == Some("clickEffect") || f.deferred { - break; - } - let class = AnimClass::from_xml(c.attr("presetClass").unwrap_or("entr")); - let preset = c.u32("presetID").unwrap_or(0); - let effect = maps::effect_for_preset(class, preset).unwrap_or_else(|| maps::fallback_effect(class)); - let delay = c.path(&["stCondLst", "cond"]).and_then(|d| ms_attr(d, "delay")).unwrap_or(0); - if class == AnimClass::Media - && effect == "play" - && f.offset == 0 - && delay == 0 - && let Some(id) = c.find("spTgt").and_then(|t| t.u32("spid")).and_then(|s| ctx.lookup(s)) - && let Some(ShapeKind::Media(clip)) = find_shape_mut(shapes, id).map(|s| &mut s.kind) - { - clip.autoplay = true; - } - } - } -} - -/// Flatten the timing tree into the Animation Pane list. -pub fn animations(imp: &mut Imp, part: &Part, ctx: &IdCtx, timing: &El, shapes: &[Shape]) -> Vec { - let _ = (imp, part); - let Some(tn) = timing.child("tnLst") else { return vec![] }; - let mut found = vec![]; - collect(tn, At { trigger: None, main_seq_id: None, group: 0, offset: 0, deferred: false }, &mut 0, &mut found, 0); - // Paragraph builds (`bldP`) by (spid, grpId) -> whether `build="p"`. - let bld_p: std::collections::HashMap<(u32, String), bool> = timing - .child("bldLst") - .map(|b| { - b.children_named("bldP") - .filter_map(|p| Some(((p.u32("spid")?, p.attr("grpId").unwrap_or("0").to_string()), p.attr("build") == Some("p")))) - .fold(std::collections::HashMap::new(), |mut m, (k, v)| { - m.entry(k).and_modify(|e| *e |= v).or_insert(v); - m - }) - }) - .unwrap_or_default(); - let mut out: Vec<(Animation, u32, String, bool, usize, u32)> = vec![]; - let mut at: Vec<(Option, usize, u32)> = vec![]; - for f in found { - let c = f.ctn; - let class = AnimClass::from_xml(c.attr("presetClass").unwrap_or("entr")); - let preset = c.u32("presetID").unwrap_or(0); - let sub = c.u32("presetSubtype").unwrap_or(0); - let Some(tgt) = c.find("spTgt") else { continue }; - let Some(file_id) = tgt.u32("spid") else { continue }; - let Some(shape) = ctx.lookup(file_id) else { continue }; - let paragraph = tgt.path(&["txEl", "pRg"]).and_then(|p| p.u32("st")); - let effect = maps::effect_for_preset(class, preset).unwrap_or_else(|| maps::fallback_effect(class)); - // PowerPoint writes Float Down as its own preset (47), not as Float with a direction. - let (effect, option) = match (class, preset) { - (AnimClass::Entrance, 47) => ("float", "d".to_string()), - (AnimClass::Exit, 47) => ("floatOut", "d".to_string()), - _ => (effect, maps::option_from_subtype(effect, sub)), - }; - let start = match c.attr("nodeType") { - Some("clickEffect") => AnimStart::OnClick, - Some("afterEffect") => AnimStart::AfterPrevious, - _ => AnimStart::WithPrevious, - }; - let mut a = Animation { - shape, - class, - effect: effect.to_string(), - option, - start, - duration_ms: max_dur(c, 0).unwrap_or(0), - delay_ms: c.path(&["stCondLst", "cond"]).and_then(|d| ms_attr(d, "delay")).unwrap_or(0), - paragraph, - trigger: f.trigger.and_then(|t| ctx.lookup(t)), - preset_id: Some(preset), - preset_subtype: Some(sub), - // PowerPoint's "Auto-reverse" is `autoRev` on the behaviour nodes (`p:cBhvr/p:cTn`); Color Pulse - // always writes it there and plays back and forth on its own, so it isn't read as the option. - auto_reverse: c.bool("autoRev").unwrap_or(false) || (effect != "colorPulse" && behaviour_auto_reverses(c)), - // PowerPoint's "Rewind when done playing" is `fill="remove"` on the effect node. - rewind: c.attr("fill") == Some("remove"), - smooth_start: c.f64("accel").map(|v| v / 100_000.0).unwrap_or(0.0), - smooth_end: c.f64("decel").map(|v| v / 100_000.0).unwrap_or(0.0), - bounce_end: c.f64("bounceEnd").map(|v| (v / 100_000.0).clamp(0.0, 1.0)).unwrap_or(0.0), - ..Default::default() - }; - a.repeat = match c.attr("repeatCount") { - Some("indefinite") => u32::MAX, - Some(v) => v.parse::().ok().filter(|v| v.is_finite()).map(|v| (v / 1000.0).round().clamp(1.0, 10_000.0) as u32).unwrap_or(1), - None => 1, - }; - if let Some(m) = c.find("animMotion") { - a.path = m.attr("path").map(String::from); - } - if let Some(r) = c.find("animRot") { - a.amount = r.f64("by").map(|v| v / 60_000.0); - if a.effect == "spin" && a.amount.is_some_and(|v| v < 0.0) { - a.option = "counterClockwise".into(); - } - } else if let Some(s) = c.find("animScale").and_then(|s| s.child("by")) { - a.amount = s.f64("x").map(|v| v / 100_000.0); - } - if let Some(clr) = c.find("animClr").and_then(|x| x.child("to")) { - a.color = dml::color(clr); - } - let grp = c.attr("grpId").unwrap_or("0").to_string(); - let build = paragraph.is_some() && bld_p.get(&(file_id, grp.clone())) != Some(&false); - out.push((a, file_id, grp, build, f.group, f.offset)); - at.push((f.trigger, f.group, f.offset)); - } - place_by_parent_delays(&mut out, &at); - // A paragraph build's effects, one per paragraph, become one by-paragraph animation only when - // the timeline plays that back exactly: PowerPoint lets each paragraph keep its own start and - // effect, and other shapes' effects can sit between them (#844). - let same_build = |x: &(Animation, u32, String, bool, usize, u32), y: &(Animation, u32, String, bool, usize, u32)| { - x.3 && y.3 && x.1 == y.1 && x.2 == y.2 && x.0.trigger == y.0.trigger - }; - let mut anims = Vec::with_capacity(out.len()); - for run in out.chunk_by(same_build) { - let effects: Vec<&Animation> = run.iter().map(|(a, ..)| a).collect(); - let offsets: Vec = run.iter().map(|r| r.5).collect(); - let build = run.first().is_some_and(|r| r.3); - let explicit_bld = run.first().is_some_and(|r| bld_p.get(&(r.1, r.2.clone())) == Some(&true)); - let same_click_group = run.first().is_some_and(|first| first.0.start == AnimStart::OnClick || run.iter().all(|r| r.4 == first.4)); - let text = effects.first().and_then(|a| find_shape(shapes, a.shape)).and_then(|s| s.text.as_ref()); - match (effects.first(), text) { - (Some(first), Some(text)) if build && (explicit_bld || same_click_group) && plays_as_build(&effects, &offsets, text, explicit_bld) => { - anims.push(Animation { text_build: TextBuild::ByParagraph, paragraph: None, ..(*first).clone() }); - } - _ => anims.extend(effects.into_iter().cloned()), - } - } - anims -} - -/// Are `effects` (paragraph effects of one shape, in file order) what a by-paragraph build of the -/// first one plays: one effect per paragraph the build animates, in paragraph order, later top -/// paragraphs on click (after previous when the build doesn't start on click), deeper ones with -/// their parent, all with the same settings? -fn plays_as_build(effects: &[&Animation], offsets: &[u32], text: &TextBody, explicit_bld: bool) -> bool { - let roles = paragraph_build_roles(text); - let expected = roles.iter().enumerate().filter(|(i, r)| match r { - BuildRole::Top => true, - BuildRole::Member(_) => text.paragraphs.get(*i).is_some_and(build_filled), - BuildRole::Unowned => false, - }); - let Some(first) = effects.first() else { return false }; - let off0 = offsets.first().copied().unwrap_or(0); - let flat = flat_starts(effects); - let parent_starts_match = offsets - .iter() - .zip(effects.iter()) - .zip(flat.iter()) - .all(|((&off, a), &ft)| off == off0 || off.saturating_add(a.delay_ms) == off0.saturating_add(ft)); - if !explicit_bld && (!parent_starts_match || (first.start != AnimStart::OnClick && (span_ms(first) != 500 || first.delay_ms != 0 || off0 != 0))) { - return false; - } - let settings = |a: &Animation| Animation { start: AnimStart::OnClick, paragraph: None, ..a.clone() }; - let base = settings(first); - let mut matched = 0; - for (k, (i, role)) in expected.enumerate() { - let Some(a) = effects.get(k) else { return false }; - let start_ok = match role { - BuildRole::Top if k == 0 => true, - BuildRole::Top if first.start == AnimStart::OnClick => a.start == AnimStart::OnClick, - BuildRole::Top => a.start == AnimStart::AfterPrevious, - _ => a.start == AnimStart::WithPrevious, - }; - if a.paragraph != u32::try_from(i).ok() || !start_ok || settings(a) != base { - return false; - } - matched = k + 1; - } - matched == effects.len() -} diff --git a/crates/pptx/src/tables.rs b/crates/pptx/src/tables.rs deleted file mode 100644 index 081433243..000000000 --- a/crates/pptx/src/tables.rs +++ /dev/null @@ -1,97 +0,0 @@ -//! Table style XML uses the shared writer; app XML admission remains unchanged. -pub use craft_drawingml::table::styles::{guid, guid_for_style, is_own_guid, style_from_guid}; - -pub fn table_styles_xml(used: &[String], defs: &[deckcraft_model::table::TableStyleDef]) -> Vec { - craft_drawingml_table::table::styles::table_styles_xml_with(used, defs.iter().map(|d| (d.id.as_str(), d.raw.as_str())), "DeckCraft", |raw| { - crate::xml::parse(raw.as_bytes()).is_ok_and(|x| x.root.is("tblStyle")) - }) -} - -#[cfg(test)] -#[path = "tables_legacy.rs"] -mod legacy; - -#[cfg(test)] -fn own_guid(style: &str) -> String { - guid(&format!("deckcraft-table-style:{style}")) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn shared_writer_matches_legacy_bytes_and_admission() { - use deckcraft_model::table::TableStyleDef; - let mut used: Vec = deckcraft_model::table::table_styles().into_iter().map(|(id, _)| id).collect(); - used.extend(["unknown<&\"".into(), "Custom".into(), "Custom".into(), "CUSTOM".into()]); - for raw in [ - "", - "", // Existing lenient partial-root policy. - "", - "", - "", - "", - "", - ] { - let defs = vec![ - TableStyleDef { id: "custom".into(), raw: raw.into(), ..Default::default() }, - TableStyleDef { id: "CUSTOM".into(), raw: "".into(), ..Default::default() }, - TableStyleDef { id: "unused".into(), raw: "".into(), ..Default::default() }, - ]; - for selection in [&used[..], &[][..]] { - assert_eq!(table_styles_xml(selection, &defs), legacy::table_styles_xml(selection, &defs), "{raw:?}"); - } - } - for depth in [255, 256, 257] { - let raw = format!("{}{}", "".repeat(depth), "".repeat(depth)); - let defs = [TableStyleDef { id: "custom".into(), raw, ..Default::default() }]; - assert_eq!(table_styles_xml(&used, &defs), legacy::table_styles_xml(&used, &defs)); - } - } - - #[test] - fn shared_style_catalog_matches_deckcraft() { - assert_eq!(deckcraft_model::table::table_styles(), craft_drawingml::table::table_styles()); - assert_eq!(style_from_guid(""), "none"); - let custom = "{abcdef00-0000-0000-0000-000000000000}"; - assert_eq!(style_from_guid(custom), custom); - assert_eq!(guid_for_style(custom), (custom.to_string(), false)); - assert_eq!(guid_for_style("unknown"), guid_for_style("medium2-accent1")); - for (id, _) in deckcraft_model::table::table_styles() { - let generated = own_guid(&id); - assert!(is_own_guid(&generated.to_ascii_lowercase())); - if guid_for_style(&id).1 { - assert_eq!(guid_for_style(&id).0, generated); - } - } - } - - #[test] - fn style_parts_follow_schema_order() { - const ORDER: [&str; 14] = [ - "tblBg", "wholeTbl", "band1H", "band2H", "band1V", "band2V", "lastCol", "firstCol", "lastRow", "seCell", "swCell", "firstRow", "neCell", - "nwCell", - ]; - let used: Vec = deckcraft_model::table::table_styles().into_iter().map(|(id, _)| id).collect(); - let d = crate::xml::parse(&table_styles_xml(&used, &[])).unwrap(); - let mut n = 0; - for st in d.root.children_named("tblStyle") { - n += 1; - let pos: Vec = st.elements().map(|e| ORDER.iter().position(|o| *o == e.local()).unwrap()).collect(); - assert!(pos.windows(2).all(|w| w[0] < w[1]), "{:?}: {pos:?}", st.attr("styleName")); - } - assert!(n > 30); - } - - #[test] - fn guids_round_trip() { - for (id, _) in deckcraft_model::table::table_styles() { - let (g, _) = guid_for_style(&id); - assert_eq!(style_from_guid(&g), id, "{id} via {g}"); - assert_eq!(g.len(), 38); - } - assert_eq!(style_from_guid("{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}"), "medium2-accent1"); - assert_eq!(style_from_guid("{ABCDEF00-0000-0000-0000-000000000000}"), "{ABCDEF00-0000-0000-0000-000000000000}"); - } -} diff --git a/crates/pptx/src/tables_legacy.rs b/crates/pptx/src/tables_legacy.rs deleted file mode 100644 index b5d71dc4b..000000000 --- a/crates/pptx/src/tables_legacy.rs +++ /dev/null @@ -1,182 +0,0 @@ -//! Table styles: our style ids ↔ table style GUIDs, and `tableStyles.xml` definitions for the -//! styles we write (generated from theme accents, matching how DeckCraft draws them). - -use crate::opc::NS_A; -use crate::xml::{A, W}; - -// Keep file-format identifiers in the shared DrawingML implementation. The local -// writer below still owns DeckCraft's table style definitions and XML policy. -pub use craft_drawingml::table::styles::{guid, guid_for_style}; - -fn own_guid(style: &str) -> String { - guid(&format!("deckcraft-table-style:{style}")) -} - -fn clr(w: &mut W, slot: &str, mods: &[(&str, i32)]) { - if mods.is_empty() { - w.val("a:schemeClr", slot); - return; - } - w.open("a:schemeClr", A::new().a("val", slot)); - for (n, v) in mods { - w.val(n, v); - } - w.close("a:schemeClr"); -} - -fn solid(w: &mut W, slot: &str, mods: &[(&str, i32)]) { - w.open0("a:fill"); - w.open0("a:solidFill"); - clr(w, slot, mods); - w.close("a:solidFill"); - w.close("a:fill"); -} - -fn borders(w: &mut W, b: Option<(&str, &[(&str, i32)], i32)>) { - w.open0("a:tcBdr"); - if let Some((slot, mods, width)) = b { - for side in ["a:left", "a:right", "a:top", "a:bottom", "a:insideH", "a:insideV"] { - w.open0(side); - w.open("a:ln", A::new().a("w", width).a("cmpd", "sng")); - w.open0("a:solidFill"); - clr(w, slot, mods); - w.close("a:solidFill"); - w.close("a:ln"); - w.close(side); - } - } - w.close("a:tcBdr"); -} - -fn txt(w: &mut W, bold: bool, color: Option<&str>) { - w.open("a:tcTxStyle", A::new().o("b", bold.then_some("on"))); - w.open("a:fontRef", A::new().a("idx", "minor")); - w.val("a:prstClr", "black"); - w.close("a:fontRef"); - match color { - Some(c) => w.val("a:schemeClr", c), - None => w.val("a:schemeClr", "dk1"), - } - w.close("a:tcTxStyle"); -} - -/// Write one `a:tblStyle` for our style id. -fn style_def(w: &mut W, id: &str, name: &str) { - let kind = id.split('-').next().unwrap_or("medium2"); - let acc = match id.rsplit('-').next().unwrap_or("accent1") { - "tx1" => "dk1", - a if a.starts_with("accent") => a, - _ => "accent1", - }; - let acc: &str = acc; - w.open("a:tblStyle", A::new().a("styleId", own_guid(id)).a("styleName", name)); - let part = - |w: &mut W, tag: &str, bold: bool, text: Option<&str>, fill: Option<(&str, &[(&str, i32)])>, bdr: Option<(&str, &[(&str, i32)], i32)>| { - w.open0(tag); - if bold || text.is_some() { - txt(w, bold, text); - } - w.open0("a:tcStyle"); - borders(w, bdr); - if let Some((s, m)) = fill { - solid(w, s, m); - } - w.close("a:tcStyle"); - w.close(tag); - }; - match kind { - "grid" => { - part(w, "a:wholeTbl", false, Some("dk1"), None, Some(("dk1", &[], 9525))); - } - "light1" => { - part(w, "a:wholeTbl", false, Some("dk1"), None, None); - part(w, "a:band1H", false, None, Some((acc, &[("a:tint", 20000)])), None); - part(w, "a:band1V", false, None, Some((acc, &[("a:tint", 20000)])), None); - part(w, "a:lastCol", true, None, None, None); - part(w, "a:firstCol", true, None, None, None); - part(w, "a:lastRow", true, None, None, None); - part(w, "a:firstRow", true, None, None, Some((acc, &[], 12700))); - } - "light2" => { - part(w, "a:wholeTbl", false, Some("dk1"), None, Some((acc, &[], 12700))); - // Schema order: … lastCol, firstCol, lastRow, …, firstRow. - part(w, "a:firstCol", true, None, None, None); - part(w, "a:lastRow", true, None, None, None); - part(w, "a:firstRow", true, Some("lt1"), Some((acc, &[])), Some((acc, &[], 12700))); - } - "dark1" => { - part(w, "a:wholeTbl", false, Some("lt1"), Some((acc, &[("a:shade", 75000)])), Some(("lt1", &[], 12700))); - part(w, "a:band1H", false, None, Some((acc, &[("a:shade", 60000)])), None); - part(w, "a:band1V", false, None, Some((acc, &[("a:shade", 60000)])), None); - part(w, "a:firstCol", true, None, None, None); - part(w, "a:lastRow", true, None, None, None); - part(w, "a:firstRow", true, Some("lt1"), Some(("dk1", &[])), None); - } - "medium4" => { - part(w, "a:wholeTbl", false, Some("dk1"), Some((acc, &[("a:tint", 20000)])), Some((acc, &[], 9525))); - part(w, "a:band1H", false, None, Some((acc, &[("a:tint", 40000)])), None); - part(w, "a:band1V", false, None, Some((acc, &[("a:tint", 40000)])), None); - part(w, "a:lastCol", true, None, None, None); - part(w, "a:firstCol", true, None, None, None); - part(w, "a:lastRow", true, None, None, None); - part(w, "a:firstRow", true, None, Some((acc, &[("a:tint", 40000)])), None); - } - _ => { - // medium2 - part(w, "a:wholeTbl", false, Some("dk1"), Some((acc, &[("a:tint", 20000)])), Some(("lt1", &[], 12700))); - part(w, "a:band1H", false, None, Some((acc, &[("a:tint", 40000)])), None); - part(w, "a:band1V", false, None, Some((acc, &[("a:tint", 40000)])), None); - part(w, "a:lastCol", true, Some("lt1"), Some((acc, &[])), None); - part(w, "a:firstCol", true, Some("lt1"), Some((acc, &[])), None); - part(w, "a:lastRow", true, Some("lt1"), Some((acc, &[])), None); - part(w, "a:firstRow", true, Some("lt1"), Some((acc, &[])), None); - } - } - w.close("a:tblStyle"); -} - -/// `ppt/tableStyles.xml` with definitions for the styles in `used`: ours, generated, and those the -/// opened file defined (`defs`), written back as they were read. -pub fn table_styles_xml(used: &[String], defs: &[deckcraft_model::table::TableStyleDef]) -> Vec { - let mut w = W::new(); - w.open("a:tblStyleLst", A::new().a("xmlns:a", NS_A).a("def", "{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}")); - let names = deckcraft_model::table::table_styles(); - // Indexes instead of scans: written ids (as given and ASCII lower-case), and the file's - // definitions by lower-case id (the first wins). - let mut done: std::collections::HashSet<&str> = std::collections::HashSet::new(); - let mut done_lower: std::collections::HashSet = std::collections::HashSet::new(); - let mut def_of: std::collections::HashMap = std::collections::HashMap::new(); - for d in defs { - def_of.entry(d.id.to_ascii_lowercase()).or_insert(d); - } - for s in used { - if !done.insert(s.as_str()) { - continue; - } - done_lower.insert(s.to_ascii_lowercase()); - if let Some(d) = def_of.get(&s.to_ascii_lowercase()) - && crate::xml::parse(d.raw.as_bytes()).is_ok_and(|x| x.root.is("tblStyle")) - { - w.raw(&d.raw); - continue; - } - let (_, define) = guid_for_style(s); - if !define { - continue; - } - let name = names.iter().find(|(id, _)| id == s).map(|(_, n)| format!("DeckCraft {n}")).unwrap_or_else(|| s.clone()); - style_def(&mut w, s, &name); - } - // Styles the file defined but no table uses still belong to the deck. - for d in defs { - if done_lower.contains(&d.id.to_ascii_lowercase()) { - continue; - } - if crate::xml::parse(d.raw.as_bytes()).is_ok_and(|x| x.root.is("tblStyle")) { - done_lower.insert(d.id.to_ascii_lowercase()); - w.raw(&d.raw); - } - } - w.close("a:tblStyleLst"); - w.finish() -} diff --git a/crates/pptx/src/write.rs b/crates/pptx/src/write.rs deleted file mode 100644 index 6a6ce6077..000000000 --- a/crates/pptx/src/write.rs +++ /dev/null @@ -1,1318 +0,0 @@ -//! PPTX export: [`Presentation`] → package. - -pub(crate) mod chart; -pub(crate) mod dml; -mod shapes; -mod theme; -mod timing; - -use std::collections::HashMap; -use std::sync::Arc; - -use deckcraft_geom::Xfrm; -use deckcraft_model::text::{ListStyle, Paragraph, TextBody}; -use deckcraft_model::theme::Theme; -use deckcraft_model::{ - Background, Comment, Layout, LayoutId, Master, MediaId, PhType, Placeholder, Presentation, Shape, ShapeId, Slide, SlideId, defaults, -}; - -use crate::PptxError; -use crate::opc::{self, NS_A, NS_P, NS_P14, NS_P188, NS_R, PackageOut, RelsOut}; -use crate::xml::{A, W}; - -pub(crate) const CT_PRES: &str = "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml"; -pub(crate) const CT_TEMPLATE: &str = "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml"; -pub(crate) const CT_SHOW: &str = "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml"; -const CT_SLIDE: &str = "application/vnd.openxmlformats-officedocument.presentationml.slide+xml"; -const CT_LAYOUT: &str = "application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml"; -const CT_MASTER: &str = "application/vnd.openxmlformats-officedocument.presentationml.slideMaster+xml"; -const CT_NOTES_MASTER: &str = "application/vnd.openxmlformats-officedocument.presentationml.notesMaster+xml"; -const CT_HANDOUT_MASTER: &str = "application/vnd.openxmlformats-officedocument.presentationml.handoutMaster+xml"; -const CT_NOTES: &str = "application/vnd.openxmlformats-officedocument.presentationml.notesSlide+xml"; -const CT_THEME: &str = "application/vnd.openxmlformats-officedocument.theme+xml"; -const CT_PRES_PROPS: &str = "application/vnd.openxmlformats-officedocument.presentationml.presProps+xml"; -const CT_VIEW_PROPS: &str = "application/vnd.openxmlformats-officedocument.presentationml.viewProps+xml"; -const CT_TABLE_STYLES: &str = "application/vnd.openxmlformats-officedocument.presentationml.tableStyles+xml"; -const CT_TAGS: &str = "application/vnd.openxmlformats-officedocument.presentationml.tags+xml"; -const CT_CHART: &str = "application/vnd.openxmlformats-officedocument.drawingml.chart+xml"; -const CT_CHARTEX: &str = "application/vnd.ms-office.chartex+xml"; -const RT_CHARTEX: &str = "http://schemas.microsoft.com/office/2014/relationships/chartEx"; -const CT_COMMENTS: &str = "application/vnd.openxmlformats-officedocument.presentationml.comments+xml"; -const CT_AUTHORS: &str = "application/vnd.openxmlformats-officedocument.presentationml.commentAuthors+xml"; -/// Modern threaded comments (read by PowerPoint 2021+ and DeckCraft; the flattened legacy -/// part next to it serves older readers). -pub(crate) const CT_COMMENTS_MODERN: &str = "application/vnd.ms-powerpoint.comments+xml"; -const CT_AUTHORS_MODERN: &str = "application/vnd.ms-powerpoint.authors+xml"; -const RT_COMMENTS_MODERN: &str = "http://schemas.microsoft.com/office/2018/10/relationships/comments"; -const RT_AUTHORS_MODERN: &str = "http://schemas.microsoft.com/office/2018/10/relationships/authors"; -const CT_CORE: &str = "application/vnd.openxmlformats-package.core-properties+xml"; -const CT_APP: &str = "application/vnd.openxmlformats-officedocument.extended-properties+xml"; - -/// Export state. -pub struct Exp<'a> { - pub p: &'a Presentation, - pub pkg: PackageOut, - media_parts: HashMap, - /// Each media id's item in `p.media` (the first with the id, as `Presentation::media`). - media_at: HashMap, - n_image: u32, - n_media: u32, - n_chart: u32, - n_diagram: u32, - n_tags: u32, - n_chartex: u32, - /// Parts kept from an unchanged chart (`ppt/…/keptN.ext`). - n_kept: u32, - pub slide_parts: HashMap, - pub table_styles: Vec, - /// A table past the cell cap was met; export fails rather than write a trimmed one. - pub table_over_cap: bool, - /// The ids in `table_styles`, for checking membership without a scan. - pub table_style_set: std::collections::HashSet, - placeholder: Option, -} - -/// A part being written: its name and relationships. -pub struct Out { - pub name: String, - pub rels: RelsOut, -} - -impl Out { - fn new(name: &str) -> Self { - Out { name: name.to_string(), rels: RelsOut::default() } - } -} - -fn ext_for(content_type: &str, name: &str, data: &[u8]) -> String { - let by_ct = match content_type { - "image/png" => "png", - "image/jpeg" | "image/jpg" => "jpeg", - "image/gif" => "gif", - "image/bmp" => "bmp", - "image/tiff" => "tiff", - "image/svg+xml" => "svg", - "image/x-emf" | "image/emf" => "emf", - "image/x-wmf" | "image/wmf" => "wmf", - "image/webp" => "webp", - "video/mp4" => "mp4", - "video/quicktime" => "mov", - "video/x-ms-wmv" => "wmv", - "video/x-msvideo" => "avi", - "video/webm" => "webm", - "audio/mpeg" => "mp3", - "audio/wav" | "audio/x-wav" | "audio/wave" => "wav", - "audio/mp4" | "audio/x-m4a" => "m4a", - "audio/x-ms-wma" => "wma", - "audio/ogg" => "ogg", - "audio/flac" => "flac", - "model/gltf-binary" => "glb", - _ => "", - }; - if !by_ct.is_empty() { - return by_ct.to_string(); - } - if data.starts_with(b"\x89PNG") { - return "png".into(); - } - if data.starts_with(&[0xFF, 0xD8]) { - return "jpeg".into(); - } - if data.starts_with(b"GIF8") { - return "gif".into(); - } - let e = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default(); - if !e.is_empty() && e.len() <= 5 && e.chars().all(|c| c.is_ascii_alphanumeric()) { e } else { "bin".into() } -} - -impl<'a> Exp<'a> { - /// The media item `id`, found through the index rather than a scan of every item. - pub fn media(&self, id: MediaId) -> Option<&'a deckcraft_model::MediaItem> { - let p: &'a Presentation = self.p; - self.media_at.get(&id).and_then(|&i| p.media.get(i)) - } - fn media_part(&mut self, id: MediaId) -> Option { - if let Some(p) = self.media_parts.get(&id) { - return Some(p.clone()); - } - let m = self.media(id)?; - if m.data.is_empty() { - return None; - } - let ext = ext_for(&m.content_type, &m.name, &m.data); - let ct = if m.content_type.is_empty() || !m.content_type.contains('/') { - crate::mime_for(&format!("x.{ext}")).to_string() - } else { - m.content_type.clone() - }; - let name = if ct.starts_with("image/") { - self.n_image += 1; - format!("ppt/media/image{}.{ext}", self.n_image) - } else { - self.n_media += 1; - format!("ppt/media/media{}.{ext}", self.n_media) - }; - self.pkg.binary(&name, &ct, m.data.as_ref().clone()); - self.media_parts.insert(id, name.clone()); - Some(name) - } - /// A relationship from `o` to a media item (embedded part, or external link). - pub fn media_rel(&mut self, o: &mut Out, id: MediaId, kind: &str) -> Option { - let m = self.media(id)?; - if m.data.is_empty() { - let link = m.link.clone()?; - return Some(o.rels.add(kind, &link, true)); - } - let part = self.media_part(id)?; - Some(o.rels.add(kind, &opc::relative(&o.name, &part), false)) - } - pub fn media_rel_new(&mut self, o: &mut Out, id: MediaId, kind: &str) -> Option { - let m = self.media(id)?; - if m.data.is_empty() { - return None; - } - let part = self.media_part(id)?; - Some(o.rels.add(kind, &opc::relative(&o.name, &part), false)) - } - /// A tiny transparent PNG for pictures whose image is missing. - pub fn placeholder_rel(&mut self, o: &mut Out) -> String { - let part = match &self.placeholder { - Some(p) => p.clone(), - None => { - self.n_image += 1; - let name = format!("ppt/media/image{}.png", self.n_image); - self.pkg.binary(&name, "image/png", crate::png::transparent_1x1()); - self.placeholder = Some(name.clone()); - name - } - }; - o.rels.add("image", &opc::relative(&o.name, &part), false) - } - /// The number of the next SmartArt graphic's parts. - pub fn next_diagram(&mut self) -> u32 { - self.n_diagram += 1; - self.n_diagram - } - /// A new `ppt/tags/tagN.xml` part holding `tags`, related from `o`. - pub fn tags_rel(&mut self, o: &mut Out, tags: &Tags) -> String { - self.n_tags += 1; - let name = format!("ppt/tags/tag{}.xml", self.n_tags); - let mut w = W::new(); - root_open(&mut w, "p:tagLst", A::new()); - for (n, v) in tags.iter().take(10_000) { - w.empty("p:tag", A::new().a("name", n).a("val", v)); - } - w.close("p:tagLst"); - self.pkg.xml_part(&name, CT_TAGS, w.finish()); - o.rels.add_new("tags", &opc::relative(&o.name, &name), false) - } - /// An unchanged Office 2016 chart's `chartEx` part and its relationship id. - pub fn chartex_rel(&mut self, o: &mut Out, c: &deckcraft_model::Chart) -> Option { - let (xml, preserved) = chart::chartex_part(c)?; - self.n_chartex += 1; - let name = format!("ppt/charts/chartEx{}.xml", self.n_chartex); - self.pkg.xml_part(&name, CT_CHARTEX, xml); - if preserved { - chart::write_kept(&mut self.pkg, &name, c, &mut self.n_kept); - } else if !c.kept.parts.is_empty() { - log::warn!("pptx: chart data changed; the embedded workbook was not written back"); - } - Some(o.rels.add_new(RT_CHARTEX, &opc::relative(&o.name, &name), false)) - } - - pub fn chart_rel(&mut self, o: &mut Out, c: &deckcraft_model::Chart) -> String { - self.n_chart += 1; - let name = format!("ppt/charts/chart{}.xml", self.n_chart); - let (xml, preserved) = chart::chart_xml(c); - self.pkg.xml_part(&name, CT_CHART, xml); - if preserved { - chart::write_kept(&mut self.pkg, &name, c, &mut self.n_kept); - } else if !c.kept.parts.is_empty() { - log::warn!("pptx: chart data changed; the embedded workbook was not written back"); - } - o.rels.add_new("chart", &opc::relative(&o.name, &name), false) - } -} - -/// `p:custDataLst` pointing at a tags part, when there are tags. -pub fn cust_data(w: &mut W, x: &mut Exp, o: &mut Out, tags: &Tags) { - if tags.is_empty() { - return; - } - let id = x.tags_rel(o, tags); - w.open0("p:custDataLst"); - w.empty("p:tags", A::new().a("r:id", id)); - w.close("p:custDataLst"); -} - -fn root_open(w: &mut W, tag: &str, extra: A) { - let mut a = A::new().a("xmlns:a", NS_A).a("xmlns:r", NS_R).a("xmlns:p", NS_P); - a.v.extend(extra.v); - w.open(tag, a); -} - -fn background(w: &mut W, x: &mut Exp, o: &mut Out, bg: &Background) { - w.open0("p:bg"); - match bg { - Background::Fill { fill } => { - w.open0("p:bgPr"); - match fill { - deckcraft_model::Fill::Background | deckcraft_model::Fill::Group => w.empty0("a:noFill"), - f => dml::fill(w, x, o, f), - } - w.empty0("a:effectLst"); - w.close("p:bgPr"); - } - Background::Ref { idx, color } => { - let idx = if (1..=3).contains(idx) || (1001..=1003).contains(idx) { *idx } else { 1001 }; - w.open("p:bgRef", A::new().a("idx", idx)); - dml::color(w, color); - w.close("p:bgRef"); - } - } - w.close("p:bg"); -} - -type Tags = [(String, String)]; - -fn csld(w: &mut W, x: &mut Exp, o: &mut Out, name: &str, bg: Option<&Background>, list: &[Shape], tags: &Tags) -> shapes::IdMap { - w.open("p:cSld", A::new().o("name", (!name.is_empty()).then_some(name))); - if let Some(bg) = bg { - background(w, x, o, bg); - } - w.open0("p:spTree"); - shapes::tree_header(w); - let mut ids = shapes::IdMap::build(list); - { - let mut cx = shapes::Ctx { ids: &mut ids, written: Default::default() }; - shapes::shapes(w, x, o, &mut cx, list, 0); - } - w.close("p:spTree"); - cust_data(w, x, o, tags); - w.close("p:cSld"); - ids -} - -const CLR_KEYS: [(&str, &str); 12] = [ - ("bg1", "lt1"), - ("tx1", "dk1"), - ("bg2", "lt2"), - ("tx2", "dk2"), - ("accent1", "accent1"), - ("accent2", "accent2"), - ("accent3", "accent3"), - ("accent4", "accent4"), - ("accent5", "accent5"), - ("accent6", "accent6"), - ("hlink", "hlink"), - ("folHlink", "folHlink"), -]; - -fn clr_map(w: &mut W, map: &[(String, String)]) { - w.empty("p:clrMap", clr_map_attrs(map)); -} - -/// `p:clrMapOvr`: the layout's or slide's own colour map, else `a:masterClrMapping`. -fn clr_map_ovr(w: &mut W, map: Option<&[(String, String)]>) { - w.open0("p:clrMapOvr"); - match map { - Some(m) => w.empty("a:overrideClrMapping", clr_map_attrs(m)), - None => w.empty0("a:masterClrMapping"), - } - w.close("p:clrMapOvr"); -} - -/// The twelve colour map attributes, each a theme slot (the default for anything else). -fn clr_map_attrs(map: &[(String, String)]) -> A { - let mut a = A::new(); - for (k, d) in CLR_KEYS { - let v = map - .iter() - .find(|(mk, _)| mk == k) - .map(|(_, v)| v.as_str()) - .filter(|v| deckcraft_color::SchemeSlot::from_xml(v).is_some_and(|s| deckcraft_color::SchemeSlot::THEME.contains(&s))) - .unwrap_or(d); - a = a.a(k, v); - } - a -} - -fn ext_list(w: &mut W, raw: Option<&str>) { - let Some(raw) = raw.filter(|r| !r.trim().is_empty()) else { return }; - // Only keep well-formed extension elements. - let Ok(d) = crate::xml::parse(format!("{raw}").as_bytes()) else { return }; - let exts: Vec = d.root.elements().filter(|e| e.is("ext") && e.has_attr("uri")).map(|e| e.to_xml()).collect(); - if exts.is_empty() { - return; - } - w.open0("p:extLst"); - for e in exts { - w.raw(&e); - } - w.close("p:extLst"); -} - -/// Strip an `` wrapper (masters/layouts keep the whole element). -fn ext_children(raw: Option<&str>) -> Option { - let raw = raw?; - let d = crate::xml::parse(raw.as_bytes()).ok()?; - if d.root.is("extLst") { - let ns = d.ns_decls(); - return Some(d.root.elements().map(|e| crate::read::keep_xml(e, &ns)).collect()); - } - Some(raw.to_string()) -} - -/// The slide's extension list, plus the modern-comments anchor when the slide has a threaded -/// comment part: the rel reference is how PowerPoint finds it. -fn slide_ext_list(w: &mut W, raw: Option<&str>, comment_rel: Option<&str>) { - let mut exts: Vec = raw - .filter(|r| !r.trim().is_empty()) - .and_then(|raw| crate::xml::parse(format!("{raw}").as_bytes()).ok()) - .map(|d| d.root.elements().filter(|e| e.is("ext") && e.has_attr("uri")).map(|e| e.to_xml()).collect()) - .unwrap_or_default(); - if let Some(rid) = comment_rel { - let mut e = W::frag(); - e.open("p:ext", A::new().a("uri", crate::COMMENTS_EXT_URI)); - e.empty("p188:commentRel", A::new().a("xmlns:p188", NS_P188).a("r:id", rid)); - e.close("p:ext"); - exts.push(e.s); - } - if exts.is_empty() { - return; - } - w.open0("p:extLst"); - for e in exts { - w.raw(&e); - } - w.close("p:extLst"); -} - -fn notes_master_shapes(size: deckcraft_geom::Size) -> Vec { - let (w, h) = (size.width, size.height); - let mk = |id: u32, name: &str, kind: PhType, idx: u32, x: f64, y: f64, ww: f64, hh: f64| Shape { - id: ShapeId(id), - name: name.into(), - xfrm: Some(Xfrm::new(x, y, ww, hh)), - ph: Some(Placeholder { kind, idx, size: (kind != PhType::SlideImage).then(|| "quarter".to_string()), ..Default::default() }), - text: (kind != PhType::SlideImage).then(TextBody::default), - ..Default::default() - }; - let mut img = mk(4, "Slide Image Placeholder 3", PhType::SlideImage, 2, w * 0.125, h * 0.125, w * 0.75, h * 0.375); - img.fill = Some(deckcraft_model::Fill::None); - img.line = Some(deckcraft_model::Line::solid(deckcraft_model::ColorRef::rgb(deckcraft_color::Rgba::BLACK), 1.0)); - let mut body = mk(5, "Notes Placeholder 4", PhType::Body, 3, w * 0.1, h * 0.53, w * 0.8, h * 0.36); - if let Some(t) = body.text.as_mut() { - t.paragraphs = vec![Paragraph::new("Click to edit Master text styles")]; - } - vec![ - mk(2, "Header Placeholder 1", PhType::Header, 0, 0.0, 0.0, w * 0.43, h * 0.05), - mk(3, "Date Placeholder 2", PhType::Date, 1, w * 0.57, 0.0, w * 0.43, h * 0.05), - img, - body, - mk(6, "Footer Placeholder 5", PhType::Footer, 4, 0.0, h * 0.95, w * 0.43, h * 0.05), - mk(7, "Slide Number Placeholder 6", PhType::SlideNum, 5, w * 0.57, h * 0.95, w * 0.43, h * 0.05), - ] -} - -/// What the notes master should be on save. A master we read is written back, including its -/// header, footer, date and slide-number text. A deck that has never had one gets the placeholders -/// we generate. -struct NotesMasterWrite { - shapes: Vec, - background: Option, - color_map: Vec<(String, String)>, - style: ListStyle, - theme: Option, -} - -fn notes_master_write(p: &Presentation) -> Option { - let nm = p.notes_master.as_deref(); - let kept = nm.filter(|m| !m.shapes.is_empty()); - let has_notes = p.slides.iter().any(|s| !s.notes.is_empty() || s.has_notes_slide); - if !has_notes && nm.is_none() { - return None; - } - let default_bg = || Background::Ref { idx: 1001, color: deckcraft_model::ColorRef::scheme(deckcraft_color::SchemeSlot::Bg1) }; - Some(match kept { - Some(m) => NotesMasterWrite { - shapes: m.shapes.clone(), - background: Some(m.background.clone().unwrap_or_else(default_bg)), - color_map: m.color_map.clone(), - style: if m.body_style.is_empty() { notes_style() } else { m.body_style.clone() }, - theme: Some(m.theme.clone()), - }, - // A master without placeholders of its own gets PowerPoint's defaults, keeping its - // background and colour map. - None => NotesMasterWrite { - shapes: notes_master_shapes(p.notes_size), - background: Some(nm.and_then(|m| m.background.clone()).unwrap_or_else(default_bg)), - color_map: nm.map(|m| m.color_map.clone()).unwrap_or_default(), - style: notes_style(), - theme: None, - }, - }) -} - -fn notes_style() -> ListStyle { - let mut ls = deckcraft_model::text::ListStyle::default(); - for i in 0..9u8 { - ls.set( - i, - deckcraft_model::text::LevelStyle { - para: deckcraft_model::text::ParaProps { - margin_left: Some(36.0 * i as f64), - align: Some(deckcraft_model::text::Align::Left), - ..Default::default() - }, - run: deckcraft_model::text::RunProps { - size: Some(12.0), - font: Some("+mn-lt".into()), - fill: Some(deckcraft_model::Fill::solid(deckcraft_model::ColorRef::scheme(deckcraft_color::SchemeSlot::Tx1))), - ..Default::default() - }, - }, - ); - } - ls -} - -/// A plausible xsd:dateTime (`YYYY-MM-DD[THH:MM:SS(.frac)?(Z|±HH:MM)?]`): the ranges are -/// checked, so a model value like `2025-13-45T99:99` falls back to the default instead of -/// reaching a required `dt`/`created` attribute. -fn valid_date(s: &str) -> bool { - let b = s.as_bytes(); - let n = |r: std::ops::Range| s.get(r).and_then(|v| v.parse::().ok()); - let (Some(_), Some(mo), Some(d)) = (n(0..4), n(5..7), n(8..10)) else { return false }; - if b.get(4) != Some(&b'-') || b.get(7) != Some(&b'-') || !(1..=12).contains(&mo) || !(1..=31).contains(&d) { - return false; - } - match b.get(10) { - None => true, - Some(b'T') => match (n(11..13), n(14..16), n(17..19)) { - (Some(h), Some(mi), Some(sec)) => h <= 23 && mi <= 59 && sec <= 60 && b.get(13) == Some(&b':') && b.get(16) == Some(&b':'), - _ => false, - }, - Some(_) => false, - } -} - -/// A copy of the presentation with every slide pointing at a layout that exists. -fn sanitized(p: &Presentation) -> std::borrow::Cow<'_, Presentation> { - let mut need = p.masters.is_empty() || p.masters.iter().any(|m| m.layouts.is_empty()); - let layouts: std::collections::HashSet<_> = p.masters.iter().flat_map(|m| m.layouts.iter().map(|l| l.id)).collect(); - need |= p.slides.iter().any(|s| !layouts.contains(&s.layout)); - if !need { - return std::borrow::Cow::Borrowed(p); - } - let mut q = p.clone(); - if q.masters.is_empty() { - let (m, next) = defaults::build_master(q.slide_size, Default::default(), q.next_id.max(1)); - q.next_id = next; - q.masters.push(Arc::new(m)); - } - for m in q.masters.iter_mut() { - if m.layouts.is_empty() { - // An exhausted id space exports without the synthesized layout rather than with a - // duplicated one (#407). - let Some(raw) = q.next_id.max(1).checked_add(1) else { continue }; - let id = LayoutId(raw); - q.next_id = raw; - Arc::make_mut(m).layouts.push(Layout { - id, - name: "Blank".into(), - kind: deckcraft_model::LayoutType::Blank, - show_master_shapes: true, - ..Default::default() - }); - } - } - let first = q.masters.first().and_then(|m| m.layouts.first()).map(|l| l.id).unwrap_or_default(); - let ok: Vec = q.masters.iter().flat_map(|m| m.layouts.iter().map(|l| l.id)).collect(); - for s in q.slides.iter_mut() { - if !ok.contains(&s.layout) { - Arc::make_mut(s).layout = first; - } - } - std::borrow::Cow::Owned(q) -} - -pub fn export(p: &Presentation, main_ct: &str) -> Result, PptxError> { - let p = sanitized(p); - let p: &Presentation = &p; - let mut x = Exp { - p, - pkg: PackageOut::default(), - media_parts: HashMap::new(), - media_at: { - let mut m = HashMap::new(); - for (i, item) in p.media.iter().enumerate() { - m.entry(item.id).or_insert(i); - } - m - }, - n_image: 0, - n_media: 0, - n_chart: 0, - n_diagram: 0, - n_tags: 0, - n_chartex: 0, - n_kept: 0, - slide_parts: HashMap::new(), - table_styles: vec![], - table_over_cap: false, - table_style_set: Default::default(), - placeholder: None, - }; - for (i, s) in p.slides.iter().enumerate() { - x.slide_parts.insert(s.id, format!("ppt/slides/slide{}.xml", i + 1)); - } - let mut pres = Out::new("ppt/presentation.xml"); - - // Masters, themes and layouts. - let mut master_rids = vec![]; - let mut layout_parts: HashMap = HashMap::new(); - let mut n_layout = 0u32; - let mut big_id: u64 = 2_147_483_648; - for (mi, m) in p.masters.iter().enumerate() { - let mname = format!("ppt/slideMasters/slideMaster{}.xml", mi + 1); - let tname = format!("ppt/theme/theme{}.xml", mi + 1); - let mut mo = Out::new(&mname); - let mut lrids = vec![]; - for l in &m.layouts { - n_layout += 1; - let lname = format!("ppt/slideLayouts/slideLayout{n_layout}.xml"); - layout_parts.insert(l.id, lname.clone()); - let rid = mo.rels.add("slideLayout", &opc::relative(&mname, &lname), false); - lrids.push(rid); - let mut lo = Out::new(&lname); - lo.rels.add("slideMaster", &opc::relative(&lname, &mname), false); - let xml = layout_xml(&mut x, &mut lo, l); - x.pkg.xml_part(&lname, CT_LAYOUT, xml); - x.pkg.rels(&lname, &lo.rels); - } - mo.rels.add("theme", &opc::relative(&mname, &tname), false); - let mut to = Out::new(&tname); - let txml = theme::theme_xml(&mut x, &mut to, &m.theme); - x.pkg.xml_part(&tname, CT_THEME, txml); - x.pkg.rels(&tname, &to.rels); - let master_id = big_id; - big_id += 1; - let mut layout_ids = vec![]; - for rid in lrids { - layout_ids.push((big_id, rid)); - big_id += 1; - } - let xml = master_xml(&mut x, &mut mo, m, &layout_ids); - x.pkg.xml_part(&mname, CT_MASTER, xml); - x.pkg.rels(&mname, &mo.rels); - master_rids.push((master_id, pres.rels.add("slideMaster", &opc::relative("ppt/presentation.xml", &mname), false))); - } - - // Notes master when a slide has notes, or the file already has one (its header and footer - // live on the master, not on the notes slides). - let notes_master = "ppt/notesMasters/notesMaster1.xml"; - let mut notes_master_rid = None; - if let Some(nm) = notes_master_write(p) { - let tname = format!("ppt/theme/theme{}.xml", p.masters.len() + 1); - let mut no = Out::new(notes_master); - no.rels.add("theme", &opc::relative(notes_master, &tname), false); - let theme = nm.theme.or_else(|| p.masters.first().map(|m| m.theme.clone())).unwrap_or_default(); - let mut to = Out::new(&tname); - let txml = theme::theme_xml(&mut x, &mut to, &theme); - x.pkg.xml_part(&tname, CT_THEME, txml); - x.pkg.rels(&tname, &to.rels); - let mut w = W::new(); - root_open(&mut w, "p:notesMaster", A::new()); - csld(&mut w, &mut x, &mut no, "", nm.background.as_ref(), &nm.shapes, &[]); - clr_map(&mut w, &nm.color_map); - dml::list_style(&mut w, &mut x, &mut no, "p:notesStyle", &nm.style); - w.close("p:notesMaster"); - x.pkg.xml_part(notes_master, CT_NOTES_MASTER, w.finish()); - x.pkg.rels(notes_master, &no.rels); - notes_master_rid = Some(pres.rels.add("notesMaster", &opc::relative("ppt/presentation.xml", notes_master), false)); - } - - // Handout master. Its header, footer, date and slide-number text live on this part; a deck - // that has never had one does not gain an empty master on save. - let handout_path = "ppt/handoutMasters/handoutMaster1.xml"; - let mut handout_rid = None; - if let Some(hm) = p.handout_master.as_ref() { - let tindex = p.masters.len() + 1 + usize::from(notes_master_rid.is_some()); - let tname = format!("ppt/theme/theme{tindex}.xml"); - let mut ho = Out::new(handout_path); - ho.rels.add("theme", &opc::relative(handout_path, &tname), false); - let mut to = Out::new(&tname); - let txml = theme::theme_xml(&mut x, &mut to, &hm.theme); - x.pkg.xml_part(&tname, CT_THEME, txml); - x.pkg.rels(&tname, &to.rels); - let mut w = W::new(); - root_open(&mut w, "p:handoutMaster", A::new()); - csld(&mut w, &mut x, &mut ho, &hm.name, hm.background.as_ref(), &hm.shapes, &[]); - clr_map(&mut w, &hm.color_map); - w.close("p:handoutMaster"); - x.pkg.xml_part(handout_path, CT_HANDOUT_MASTER, w.finish()); - x.pkg.rels(handout_path, &ho.rels); - handout_rid = Some(pres.rels.add("handoutMaster", &opc::relative("ppt/presentation.xml", handout_path), false)); - } - - // Comment authors. - let mut authors: Vec<(String, String, u32)> = vec![]; - let mut author_map: std::collections::HashMap = std::collections::HashMap::new(); - let mut n_comments = 0u32; - - // Slides. - let mut slide_rids = vec![]; - for (i, s) in p.slides.iter().enumerate() { - let sname = format!("ppt/slides/slide{}.xml", i + 1); - let mut so = Out::new(&sname); - if let Some(lp) = layout_parts.get(&s.layout) { - so.rels.add("slideLayout", &opc::relative(&sname, lp), false); - } - if !s.notes.is_empty() || s.has_notes_slide { - let nname = format!("ppt/notesSlides/notesSlide{}.xml", i + 1); - so.rels.add("notesSlide", &opc::relative(&sname, &nname), false); - let mut no = Out::new(&nname); - no.rels.add("notesMaster", &opc::relative(&nname, notes_master), false); - no.rels.add("slide", &opc::relative(&nname, &sname), false); - let xml = notes_xml(&mut x, &mut no, &s.notes); - x.pkg.xml_part(&nname, CT_NOTES, xml); - x.pkg.rels(&nname, &no.rels); - } - let mut comment_rel = None; - if !s.comments.is_empty() { - n_comments += 1; - let cname = format!("ppt/comments/comment{n_comments}.xml"); - so.rels.add("comments", &opc::relative(&sname, &cname), false); - x.pkg.xml_part(&cname, CT_COMMENTS, comments_xml(&s.comments, &mut authors, &mut author_map)); - // The modern threaded part next to the flattened legacy one (issue #70): - // PowerPoint 2021+ and DeckCraft read replies and resolved state from it, - // older readers keep the legacy part. - let mname = format!("ppt/comments/modernComment{n_comments}.xml"); - let rid = so.rels.add(RT_COMMENTS_MODERN, &opc::relative(&sname, &mname), false); - x.pkg.xml_part(&mname, CT_COMMENTS_MODERN, modern_comments_xml(&s.comments, &cname, &mut authors, &mut author_map)); - comment_rel = Some(rid); - } - let xml = slide_xml(&mut x, &mut so, s, comment_rel.as_deref()); - x.pkg.xml_part(&sname, CT_SLIDE, xml); - x.pkg.rels(&sname, &so.rels); - slide_rids.push(pres.rels.add("slide", &opc::relative("ppt/presentation.xml", &sname), false)); - } - if !authors.is_empty() { - let name = "ppt/commentAuthors.xml"; - let mut w = W::new(); - root_open(&mut w, "p:cmAuthorLst", A::new()); - for (i, (n, ini, last)) in authors.iter().enumerate() { - w.empty("p:cmAuthor", A::new().a("id", i).a("name", n).a("initials", ini).a("lastIdx", last).a("clrIdx", i % 8)); - } - w.close("p:cmAuthorLst"); - x.pkg.xml_part(name, CT_AUTHORS, w.finish()); - pres.rels.add("commentAuthors", "commentAuthors.xml", false); - // The modern authors part the threaded comments' authorId GUIDs point at. - let mut w = W::new(); - w.open("p188:authorLst", A::new().a("xmlns:p188", NS_P188)); - for (n, ini, _) in authors.iter() { - w.empty("p188:author", A::new().a("id", author_guid(n)).a("name", n).a("initials", ini).a("userId", "").a("providerId", "None")); - } - w.close("p188:authorLst"); - x.pkg.xml_part("ppt/authors.xml", CT_AUTHORS_MODERN, w.finish()); - pres.rels.add(RT_AUTHORS_MODERN, "authors.xml", false); - } - - // Presentation-level parts. - let theme1 = "theme/theme1.xml"; - pres.rels.add("theme", theme1, false); - pres.rels.add("presProps", "presProps.xml", false); - pres.rels.add("viewProps", "viewProps.xml", false); - pres.rels.add("tableStyles", "tableStyles.xml", false); - x.pkg.xml_part("ppt/presProps.xml", CT_PRES_PROPS, pres_props_xml(p)); - x.pkg.xml_part("ppt/viewProps.xml", CT_VIEW_PROPS, view_props_xml(p)); - let ts = crate::tables::table_styles_xml(&x.table_styles, &p.table_styles); - x.pkg.xml_part("ppt/tableStyles.xml", CT_TABLE_STYLES, ts); - let pxml = presentation_xml(&mut x, &mut pres, &master_rids, notes_master_rid.as_deref(), handout_rid.as_deref(), &slide_rids); - x.pkg.xml_part("ppt/presentation.xml", main_ct, pxml); - // Kept parts never replace a part the writer makes. - let kept: Vec<_> = p - .kept_parts - .iter() - .filter(|k| { - let n = k.name.to_ascii_lowercase(); - !n.is_empty() - && !n.contains("..") - && !n.starts_with("ppt/") - && !n.starts_with("docprops/core") - && !n.starts_with("docprops/app") - && !n.starts_with("[content_types]") - && n != "_rels/.rels" - }) - .collect(); - for k in kept.iter().filter(|k| !k.rel_type.is_empty() && !k.from_root) { - pres.rels.add_new(&k.rel_type, &opc::relative("ppt/presentation.xml", &k.name), false); - } - x.pkg.rels("ppt/presentation.xml", &pres.rels); - for k in &kept { - if k.content_type.is_empty() { - x.pkg.raw(&k.name, k.xml.clone().into_bytes()); - } else { - x.pkg.xml_part(&k.name, &k.content_type, k.xml.clone().into_bytes()); - } - } - - // Document properties and package relationships. - x.pkg.xml_part("docProps/core.xml", CT_CORE, core_xml(p)); - x.pkg.xml_part("docProps/app.xml", CT_APP, app_xml(p)); - let mut root = RelsOut::default(); - root.add("officeDocument", "ppt/presentation.xml", false); - root.add(opc::RT_CORE, "docProps/core.xml", false); - root.add("extended-properties", "docProps/app.xml", false); - for k in kept.iter().filter(|k| !k.rel_type.is_empty() && k.from_root) { - root.add_new(&k.rel_type, &k.name, false); - } - x.pkg.rels("", &root); - if x.table_over_cap { - return Err(PptxError::Unsupported(format!( - "a table has more than {} cells; export refused rather than drop rows", - deckcraft_model::table::MAX_CELLS - ))); - } - x.pkg.finish() -} - -fn layout_xml(x: &mut Exp, o: &mut Out, l: &Layout) -> Vec { - let mut w = W::new(); - root_open( - &mut w, - "p:sldLayout", - A::new().o("showMasterSp", (!l.show_master_shapes).then_some("0")).a("type", l.kind.xml()).t("preserve", l.preserve), - ); - csld(&mut w, x, o, &l.name, l.background.as_ref(), &l.shapes, &[]); - clr_map_ovr(&mut w, l.color_map.as_deref()); - ext_list(&mut w, ext_children(l.raw_ext.as_deref()).as_deref()); - w.close("p:sldLayout"); - w.finish() -} - -fn master_xml(x: &mut Exp, o: &mut Out, m: &Master, layouts: &[(u64, String)]) -> Vec { - let mut w = W::new(); - root_open(&mut w, "p:sldMaster", A::new().t("preserve", m.preserve)); - csld(&mut w, x, o, &m.name, m.background.as_ref(), &m.shapes, &[]); - clr_map(&mut w, &m.color_map); - w.open0("p:sldLayoutIdLst"); - for (id, rid) in layouts { - w.empty("p:sldLayoutId", A::new().a("id", id).a("r:id", rid)); - } - w.close("p:sldLayoutIdLst"); - w.open0("p:txStyles"); - // An imported empty body style has no bullets; saving must not author defaults into it. - // New decks already carry their populated master styles in the model. - dml::list_style(&mut w, x, o, "p:titleStyle", &m.title_style); - dml::list_style(&mut w, x, o, "p:bodyStyle", &m.body_style); - dml::list_style(&mut w, x, o, "p:otherStyle", &m.other_style); - w.close("p:txStyles"); - ext_list(&mut w, ext_children(m.raw_ext.as_deref()).as_deref()); - w.close("p:sldMaster"); - w.finish() -} - -fn slide_xml(x: &mut Exp, o: &mut Out, s: &Slide, comment_rel: Option<&str>) -> Vec { - let mut w = W::new(); - root_open(&mut w, "p:sld", A::new().o("showMasterSp", (!s.show_master_shapes).then_some("0")).o("show", s.hidden.then_some("0"))); - let ids = csld(&mut w, x, o, &s.name, s.background.as_ref(), &s.shapes, &s.tags); - clr_map_ovr(&mut w, s.color_map.as_deref()); - if let Some(t) = &s.transition { - timing::transition(&mut w, x, o, t); - } - timing::timing(&mut w, x, &s.animations, &s.shapes, &ids); - slide_ext_list(&mut w, s.raw_ext.as_deref(), comment_rel); - w.close("p:sld"); - w.finish() -} - -fn notes_xml(x: &mut Exp, o: &mut Out, notes: &TextBody) -> Vec { - let mut w = W::new(); - root_open(&mut w, "p:notes", A::new()); - let img = Shape { - id: ShapeId(2), - name: "Slide Image Placeholder 1".into(), - ph: Some(Placeholder { kind: PhType::SlideImage, ..Default::default() }), - ..Default::default() - }; - let mut tb = notes.clone(); - tb.body = Default::default(); - let body = Shape { - id: ShapeId(3), - name: "Notes Placeholder 2".into(), - ph: Some(Placeholder { kind: PhType::Body, idx: 1, ..Default::default() }), - text: Some(tb), - ..Default::default() - }; - csld(&mut w, x, o, "", None, &[img, body], &[]); - w.open0("p:clrMapOvr"); - w.empty0("a:masterClrMapping"); - w.close("p:clrMapOvr"); - w.close("p:notes"); - w.finish() -} - -fn comments_xml(list: &[Comment], authors: &mut Vec<(String, String, u32)>, author_map: &mut std::collections::HashMap) -> Vec { - let mut w = W::new(); - root_open(&mut w, "p:cmLst", A::new()); - let mut flat: Vec<&Comment> = vec![]; - for c in list.iter().take(10_000) { - flat.push(c); - for r in c.replies.iter().take(1000) { - flat.push(r); - } - } - for c in flat { - let ai = author_slot(c, authors, author_map); - let idx = match authors.get_mut(ai) { - Some(a) => { - a.2 += 1; - a.2 - } - None => 1, - }; - let dt = if valid_date(&c.date) { c.date.clone() } else { "2024-01-01T00:00:00.000".into() }; - w.open("p:cm", A::new().a("authorId", ai).a("dt", dt).a("idx", idx)); - let pos = |v: f64| if v.is_finite() { (v * 8.0).round().clamp(0.0, 1.0e9) as i64 } else { 0 }; - w.empty("p:pos", A::new().a("x", pos(c.x)).a("y", pos(c.y))); - w.elt("p:text", &c.text); - w.close("p:cm"); - } - w.close("p:cmLst"); - w.finish() -} - -/// The author's slot in the shared bucket list, adding them on first use. Legacy parts index the -/// list by number, the modern authors part gives every slot a GUID. -fn author_slot(c: &Comment, authors: &mut Vec<(String, String, u32)>, map: &mut std::collections::HashMap) -> usize { - let author = if c.author.is_empty() { "Author" } else { &c.author }; - if let Some(&i) = map.get(author) { - return i; - } - let ini = if c.initials.is_empty() { author.chars().filter(|ch| ch.is_alphabetic()).take(2).collect() } else { c.initials.clone() }; - let idx = authors.len(); - authors.push((author.to_string(), ini, 0)); - map.insert(author.to_string(), idx); - idx -} - -/// The modern (p188) threaded-comment part: replies nest and the resolved state is kept, which -/// the flattened legacy part cannot express (issue #70). -fn modern_comments_xml( - list: &[Comment], - part: &str, - authors: &mut Vec<(String, String, u32)>, - author_map: &mut std::collections::HashMap, -) -> Vec { - let mut w = W::new(); - w.open("p188:cmLst", A::new().a("xmlns:p188", NS_P188).a("xmlns:a", NS_A).a("xmlns:r", NS_R)); - for (ti, c) in list.iter().take(10_000).enumerate() { - modern_comment(&mut w, c, part, ti, authors, author_map, 0); - } - w.close("p188:cmLst"); - w.finish() -} - -fn modern_comment( - w: &mut W, - c: &Comment, - part: &str, - ti: usize, - authors: &mut Vec<(String, String, u32)>, - author_map: &mut std::collections::HashMap, - depth: usize, -) { - let ai = author_slot(c, authors, author_map); - let author = authors.get(ai).map(|(n, _, _)| n.clone()).unwrap_or_default(); - let dt = if valid_date(&c.date) { c.date.clone() } else { "2024-01-01T00:00:00.000".into() }; - let mut a = A::new().a("id", crate::tables::guid(&format!("deckcraft-comment:{part}:{ti}"))).a("authorId", author_guid(&author)).a("created", dt); - if c.resolved { - a = a.a("status", "resolved"); - } - w.open("p188:cm", a); - w.empty0("p188:unknownAnchor"); - let emu = |v: f64| if v.is_finite() { (v * 12_700.0).round().clamp(0.0, 1.0e9) as i64 } else { 0 }; - w.empty("p188:pos", A::new().a("x", emu(c.x)).a("y", emu(c.y))); - if depth < 4 && !c.replies.is_empty() { - w.open0("p188:replyLst"); - for (ri, r) in c.replies.iter().take(1000).enumerate() { - let ri_ai = author_slot(r, authors, author_map); - let r_author = authors.get(ri_ai).map(|(n, _, _)| n.clone()).unwrap_or_default(); - let rdt = if valid_date(&r.date) { r.date.clone() } else { "2024-01-01T00:00:00.000".into() }; - let mut ra = A::new() - .a("id", crate::tables::guid(&format!("deckcraft-comment:{part}:{ti}:{ri}"))) - .a("authorId", author_guid(&r_author)) - .a("created", rdt); - if r.resolved { - ra = ra.a("status", "resolved"); - } - w.open("p188:reply", ra); - tx_body(w, &r.text); - w.close("p188:reply"); - } - w.close("p188:replyLst"); - } - tx_body(w, &c.text); - w.close("p188:cm"); -} - -/// An `a:txBody` with one paragraph per line, the shape the reader re-joins with `\n`. -fn tx_body(w: &mut W, text: &str) { - w.open0("p188:txBody"); - w.empty0("a:bodyPr"); - for line in text.split('\n') { - w.open0("a:p"); - w.open0("a:r"); - w.empty("a:rPr", A::new().a("lang", "en-US")); - w.elt("a:t", line); - w.close("a:r"); - w.close("a:p"); - } - w.close("p188:txBody"); -} - -/// The modern author id for a name: the same GUID the authors part writes. -fn author_guid(name: &str) -> String { - crate::tables::guid(&format!("deckcraft-comment-author:{name}")) -} - -/// Sections with every slide in exactly one section, in slide order. -fn section_slides(p: &Presentation) -> Vec<(String, Vec)> { - let mut out: Vec<(String, Vec)> = p.sections.iter().map(|s| (s.name.clone(), vec![])).collect(); - if out.is_empty() { - return out; - } - // Each slide's first section, found once: a section may name a slide many times. - let mut first: HashMap = HashMap::new(); - for (k, sec) in p.sections.iter().enumerate() { - for id in &sec.slides { - first.entry(*id).or_insert(k); - } - } - let mut cur = 0usize; - for (i, s) in p.slides.iter().enumerate() { - if let Some(&k) = first.get(&s.id) - && k >= cur - { - cur = k; - } - if let Some(sec) = out.get_mut(cur) { - sec.1.push(i); - } - } - out -} - -/// One embedded typeface, with the relationship id of each face that had bytes. -struct WrittenFont { - typeface: String, - panose: Option, - pitch_family: Option, - charset: Option, - regular: Option, - bold: Option, - italic: Option, - bold_italic: Option, -} - -impl WrittenFont { - fn any(&self) -> bool { - self.regular.is_some() || self.bold.is_some() || self.italic.is_some() || self.bold_italic.is_some() - } -} - -/// Font parts for `p:embeddedFontLst`. One part per distinct media item, named `ppt/fonts/fontN.fntdata`. -fn write_embedded_fonts(x: &mut Exp, o: &mut Out) -> Vec { - struct Plan { - typeface: String, - panose: Option, - pitch_family: Option, - charset: Option, - regular: Option, - bold: Option, - italic: Option, - bold_italic: Option, - } - let mut plans = Vec::new(); - for font in x.p.embedded_fonts.iter().take(64) { - let typeface = font.typeface.trim(); - if typeface.is_empty() { - continue; - } - plans.push(Plan { - typeface: typeface.chars().take(255).collect(), - panose: font.panose.clone().filter(|s| s.len() == 20 && s.chars().all(|c| c.is_ascii_hexdigit())), - pitch_family: font.pitch_family, - charset: font.charset, - regular: font.regular, - bold: font.bold, - italic: font.italic, - bold_italic: font.bold_italic, - }); - } - let mut seen_part: HashMap = HashMap::new(); - let mut n = 0u32; - let mut rel = |x: &mut Exp, o: &mut Out, id: Option| -> Option { - let id = id?; - if let Some(rid) = seen_part.get(&id) { - return Some(rid.clone()); - } - let m = x.media(id)?; - if m.data.is_empty() || m.data.len() > 32 * 1024 * 1024 { - return None; - } - let bytes = m.data.as_ref().clone(); - n = n.saturating_add(1); - let name = format!("ppt/fonts/font{n}.fntdata"); - x.pkg.binary(&name, "application/x-fontdata", bytes); - let rid = o.rels.add("font", &opc::relative("ppt/presentation.xml", &name), false); - seen_part.insert(id, rid.clone()); - Some(rid) - }; - let mut seen_face = Vec::new(); - let mut out = Vec::new(); - for font in plans { - let written = WrittenFont { - typeface: font.typeface, - panose: font.panose, - pitch_family: font.pitch_family, - charset: font.charset, - regular: rel(x, o, font.regular), - bold: rel(x, o, font.bold), - italic: rel(x, o, font.italic), - bold_italic: rel(x, o, font.bold_italic), - }; - if written.any() && !seen_face.iter().any(|s| s == &written.typeface) { - seen_face.push(written.typeface.clone()); - out.push(written); - } - } - out -} - -fn presentation_xml(x: &mut Exp, o: &mut Out, masters: &[(u64, String)], notes: Option<&str>, handout: Option<&str>, slides: &[String]) -> Vec { - let fonts = write_embedded_fonts(x, o); - let p = x.p; - let mut w = W::new(); - let first = (p.first_slide_number != 1).then_some(p.first_slide_number.min(9999)); - root_open(&mut w, "p:presentation", A::new().a("saveSubsetFonts", 1).t("embedTrueTypeFonts", !fonts.is_empty()).o("firstSlideNum", first)); - w.open0("p:sldMasterIdLst"); - for (id, rid) in masters { - w.empty("p:sldMasterId", A::new().a("id", id).a("r:id", rid)); - } - w.close("p:sldMasterIdLst"); - if let Some(n) = notes { - w.open0("p:notesMasterIdLst"); - w.empty("p:notesMasterId", A::new().a("r:id", n)); - w.close("p:notesMasterIdLst"); - } - if let Some(h) = handout { - w.open0("p:handoutMasterIdLst"); - w.empty("p:handoutMasterId", A::new().a("r:id", h)); - w.close("p:handoutMasterIdLst"); - } - if !slides.is_empty() { - w.open0("p:sldIdLst"); - for (i, rid) in slides.iter().enumerate() { - w.empty("p:sldId", A::new().a("id", 256 + i).a("r:id", rid)); - } - w.close("p:sldIdLst"); - } - let clamp = |v: f64| dml::emu(v).clamp(914_400, 51_206_400); - w.empty("p:sldSz", A::new().a("cx", clamp(p.slide_size.width)).a("cy", clamp(p.slide_size.height))); - w.empty("p:notesSz", A::new().a("cx", dml::emu_pos(p.notes_size.width).max(1)).a("cy", dml::emu_pos(p.notes_size.height).max(1))); - if !fonts.is_empty() { - w.open0("p:embeddedFontLst"); - for f in &fonts { - w.open0("p:embeddedFont"); - w.empty( - "p:font", - A::new().a("typeface", &f.typeface).o("panose", f.panose.clone()).o("pitchFamily", f.pitch_family).o("charset", f.charset), - ); - for (tag, rid) in [("p:regular", &f.regular), ("p:bold", &f.bold), ("p:italic", &f.italic), ("p:boldItalic", &f.bold_italic)] { - if let Some(rid) = rid { - w.empty(tag, A::new().a("r:id", rid)); - } - } - w.close("p:embeddedFont"); - } - w.close("p:embeddedFontLst"); - } - if !p.custom_shows.is_empty() { - w.open0("p:custShowLst"); - for (i, cs) in p.custom_shows.iter().enumerate() { - w.open("p:custShow", A::new().a("name", &cs.name).a("id", i)); - w.open0("p:sldLst"); - for sid in &cs.slides { - if let Some(part) = x.slide_parts.get(sid).cloned() { - let rid = o.rels.add("slide", &opc::relative("ppt/presentation.xml", &part), false); - w.empty("p:sld", A::new().a("r:id", rid)); - } - } - w.close("p:sldLst"); - w.close("p:custShow"); - } - w.close("p:custShowLst"); - } - cust_data(&mut w, x, o, &p.tags); - let dts = if p.default_text_style.is_empty() { defaults::default_text_style() } else { p.default_text_style.clone() }; - dml::list_style(&mut w, x, o, "p:defaultTextStyle", &dts); - let sections = section_slides(p); - let raw = p.raw_ext.as_deref().filter(|r| !r.trim().is_empty()); - if !sections.is_empty() || raw.is_some() { - let mut inner = W::frag(); - if !sections.is_empty() { - inner.open("p:ext", A::new().a("uri", crate::SECTION_EXT_URI)); - inner.open("p14:sectionLst", A::new().a("xmlns:p14", NS_P14)); - for (i, (name, list)) in sections.iter().enumerate() { - inner.open("p14:section", A::new().a("name", name).a("id", crate::tables::guid(&format!("section:{i}:{name}")))); - inner.open0("p14:sldIdLst"); - for si in list { - inner.empty("p14:sldId", A::new().a("id", 256 + si)); - } - inner.close("p14:sldIdLst"); - inner.close("p14:section"); - } - inner.close("p14:sectionLst"); - inner.close("p:ext"); - } - if let Some(r) = raw { - inner.raw(r); - } - ext_list(&mut w, Some(&inner.s)); - } - w.close("p:presentation"); - w.finish() -} - -fn pres_props_xml(p: &Presentation) -> Vec { - let s = &p.show; - let mut w = W::new(); - root_open(&mut w, "p:presentationPr", A::new()); - w.open( - "p:showPr", - A::new() - .t("loop", s.loop_until_esc) - .a("showNarration", if s.without_narration { 0 } else { 1 }) - .o("showAnimation", s.without_animation.then_some("0")) - .o("useTimings", (!s.use_timings).then_some("0")), - ); - match s.show_type.as_str() { - "browsed" => w.empty("p:browse", A::new()), - "kiosk" => w.empty("p:kiosk", A::new()), - _ => w.empty0("p:present"), - } - let custom = s.custom_show.as_ref().and_then(|n| p.custom_shows.iter().position(|c| c.name == *n)); - match (custom, s.range) { - (Some(i), _) => w.empty("p:custShow", A::new().a("id", i)), - (None, Some((a, b))) => w.empty("p:sldRg", A::new().a("st", a.max(1)).a("end", b.max(a).max(1))), - _ => w.empty0("p:sldAll"), - } - w.open0("p:penClr"); - w.val("a:srgbClr", s.pen_color.hex()); - w.close("p:penClr"); - if !s.show_media_controls { - // "Show media controls" is PowerPoint's p14 extension; absent means shown. - w.open0("p:extLst"); - w.open("p:ext", A::new().a("uri", "{2FDB2607-1784-4EEB-B798-7EB5836EED8A}")); - w.empty("p14:showMediaCtrls", A::new().a("xmlns:p14", NS_P14).a("val", 0)); - w.close("p:ext"); - w.close("p:extLst"); - } - w.close("p:showPr"); - w.close("p:presentationPr"); - w.finish() -} - -fn view_props_xml(p: &Presentation) -> Vec { - let mut w = W::new(); - root_open(&mut w, "p:viewPr", A::new()); - w.open0("p:normalViewPr"); - w.empty("p:restoredLeft", A::new().a("sz", 15620)); - w.empty("p:restoredTop", A::new().a("sz", 94660)); - w.close("p:normalViewPr"); - if !p.guides.is_empty() { - // Drawing guides; `pos` is in eighths of a point (576 per inch). - w.open0("p:slideViewPr"); - w.open0("p:cSldViewPr"); - w.open0("p:cViewPr"); - w.open0("p:scale"); - w.empty("a:sx", A::new().a("n", 100).a("d", 100)); - w.empty("a:sy", A::new().a("n", 100).a("d", 100)); - w.close("p:scale"); - w.empty("p:origin", A::new().a("x", 0).a("y", 0)); - w.close("p:cViewPr"); - w.open0("p:guideLst"); - for g in p.guides.iter().take(1000) { - let pos = (g.pos * 8.0).round().clamp(-1.0e9, 1.0e9) as i64; - let a = if g.vertical { A::new().a("pos", pos) } else { A::new().a("orient", "horz").a("pos", pos) }; - w.empty("p:guide", a); - } - w.close("p:guideLst"); - w.close("p:cSldViewPr"); - w.close("p:slideViewPr"); - } - w.empty("p:gridSpacing", A::new().a("cx", 76200).a("cy", 76200)); - w.close("p:viewPr"); - w.finish() -} - -fn core_xml(p: &Presentation) -> Vec { - let pr = &p.props; - let mut w = W::new(); - w.open( - "cp:coreProperties", - A::new() - .a("xmlns:cp", "http://schemas.openxmlformats.org/package/2006/metadata/core-properties") - .a("xmlns:dc", "http://purl.org/dc/elements/1.1/") - .a("xmlns:dcterms", "http://purl.org/dc/terms/") - .a("xmlns:dcmitype", "http://purl.org/dc/dcmitype/") - .a("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"), - ); - for (tag, v) in [ - ("dc:title", &pr.title), - ("dc:subject", &pr.subject), - ("dc:creator", &pr.author), - ("cp:keywords", &pr.keywords), - ("dc:description", &pr.comments), - ("cp:category", &pr.category), - ("cp:lastModifiedBy", &pr.last_modified_by), - ] { - if !v.is_empty() { - w.elt(tag, v); - } - } - if pr.revision > 0 { - w.elt("cp:revision", &pr.revision.to_string()); - } - for (tag, v) in [("dcterms:created", &pr.created), ("dcterms:modified", &pr.modified)] { - if valid_date(v) { - w.open(tag, A::new().a("xsi:type", "dcterms:W3CDTF")); - w.text(v); - w.close(tag); - } - } - w.close("cp:coreProperties"); - w.finish() -} - -fn app_xml(p: &Presentation) -> Vec { - let mut w = W::new(); - w.open( - "Properties", - A::new() - .a("xmlns", "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties") - .a("xmlns:vt", "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"), - ); - w.elt("Application", "DeckCraft"); - w.elt("Slides", &p.slides.len().to_string()); - w.elt("Notes", &p.slides.iter().filter(|s| !s.notes.is_empty() || s.has_notes_slide).count().to_string()); - w.elt("HiddenSlides", &p.slides.iter().filter(|s| s.hidden).count().to_string()); - if !p.props.company.is_empty() { - w.elt("Company", &p.props.company); - } - w.close("Properties"); - w.finish() -} diff --git a/crates/pptx/src/write/chart.rs b/crates/pptx/src/write/chart.rs deleted file mode 100644 index e636ae251..000000000 --- a/crates/pptx/src/write/chart.rs +++ /dev/null @@ -1,1335 +0,0 @@ -//! Chart parts: a `c:chartSpace` with cached categories and values. -//! An unchanged chart also keeps the embedded workbook and the other parts it points at. - -use deckcraft_model::chart::{Chart, ChartType, ErrorBars, Series, Trendline, TrendlineType}; -use deckcraft_model::style::Fill; - -use crate::opc::{NS_A, NS_C, NS_R}; - -/// The Office 2016 chart namespace. -pub const NS_CX: &str = "http://schemas.microsoft.com/office/drawing/2014/chartex"; -use crate::xml::{A, W}; - -/// Column letter for a 0-based index (A, B, … Z, AA…). -fn col(i: usize) -> String { - let mut n = i + 1; - let mut s = String::new(); - while n > 0 && s.len() < 4 { - let r = (n - 1) % 26; - s.insert(0, (b'A' + r as u8) as char); - n = (n - 1) / 26; - } - s -} - -fn fmt_num(v: f64) -> String { - if v == v.trunc() && v.abs() < 1e15 { format!("{}", v as i64) } else { format!("{v}") } -} - -fn simple_fill(w: &mut W, f: &Fill) { - match f { - Fill::None => w.empty0("a:noFill"), - Fill::Solid { color } => super::dml::solid(w, color), - Fill::Pattern(p) => { - w.open("a:pattFill", A::new().a("prst", if p.preset.is_empty() { "pct5" } else { &p.preset })); - w.open0("a:fgClr"); - super::dml::color(w, &p.fg); - w.close("a:fgClr"); - w.open0("a:bgClr"); - super::dml::color(w, &p.bg); - w.close("a:bgClr"); - w.close("a:pattFill"); - } - Fill::Gradient(_) | Fill::Picture(_) | Fill::Group | Fill::Background => { - if let Fill::Gradient(g) = f - && let Some(s) = g.stops.first() - { - super::dml::solid(w, &s.color); - } - } - } -} - -fn sp_pr(w: &mut W, fill: Option<&Fill>, line: Option<&deckcraft_model::Line>) { - if fill.is_none() && line.is_none() { - return; - } - w.open0("c:spPr"); - if let Some(f) = fill { - simple_fill(w, f); - } - if let Some(l) = line { - w.open("a:ln", A::new().o("w", l.width.map(super::dml::emu_pos))); - if let Some(f) = &l.fill { - simple_fill(w, f); - } - w.close("a:ln"); - } - w.close("c:spPr"); -} - -/// `a:defRPr` carrying the chart's text colour, where PowerPoint keeps it: the paragraph -/// defaults of a title's rich text and of every `c:txPr`. -fn def_rpr(w: &mut W, color: Option<&deckcraft_model::ColorRef>) { - match color { - Some(c) => { - w.open0("a:defRPr"); - super::dml::solid(w, c); - w.close("a:defRPr"); - } - None => w.empty0("a:defRPr"), - } -} - -/// `c:txPr` with the chart's text colour (`Chart::text_color`) as the default run properties, on -/// the axes, the legend, the data labels and the chart itself, as PowerPoint writes it. Nothing -/// without a colour: the theme's default then applies on reading. -fn tx_pr(w: &mut W, c: &Chart) { - let Some(color) = &c.text_color else { return }; - w.open0("c:txPr"); - w.empty0("a:bodyPr"); - w.empty0("a:lstStyle"); - w.open0("a:p"); - w.open0("a:pPr"); - def_rpr(w, Some(color)); - w.close("a:pPr"); - w.empty("a:endParaRPr", A::new().a("lang", "en-US")); - w.close("a:p"); - w.close("c:txPr"); -} - -/// `c:legendEntry` with the entry's own text size, weight and colour. -fn legend_entry(w: &mut W, e: &deckcraft_model::chart::LegendEntry) { - w.open0("c:legendEntry"); - w.val("c:idx", e.idx); - w.open0("c:txPr"); - w.empty0("a:bodyPr"); - w.empty0("a:lstStyle"); - w.open0("a:p"); - w.open0("a:pPr"); - let mut a = A::new(); - if let Some(sz) = e.size.filter(|v| v.is_finite() && *v > 0.0) { - // 1 to 400 pt, as the reader takes it, so a size reads back as written. - a = a.a("sz", ((sz * 100.0).round().clamp(100.0, 40_000.0) as u32).to_string()); - } - if let Some(b) = e.bold { - a = a.a("b", if b { "1" } else { "0" }); - } - match &e.color { - Some(c) => { - w.open("a:defRPr", a); - super::dml::solid(w, c); - w.close("a:defRPr"); - } - None => w.empty("a:defRPr", a), - } - w.close("a:pPr"); - w.empty("a:endParaRPr", A::new().a("lang", "en-US")); - w.close("a:p"); - w.close("c:txPr"); - w.close("c:legendEntry"); -} - -fn rich(w: &mut W, text: &str, color: Option<&deckcraft_model::ColorRef>) { - w.open0("c:tx"); - w.open0("c:rich"); - w.empty0("a:bodyPr"); - w.empty0("a:lstStyle"); - for line in text.split('\n') { - w.open0("a:p"); - if color.is_some() { - w.open0("a:pPr"); - def_rpr(w, color); - w.close("a:pPr"); - } - w.open0("a:r"); - if let Some(c) = color { - w.open("a:rPr", A::new().a("lang", "en-US")); - super::dml::solid(w, c); - w.close("a:rPr"); - } - w.elt("a:t", line); - w.close("a:r"); - w.close("a:p"); - } - w.close("c:rich"); - w.close("c:tx"); -} - -/// A title (the chart's or an axis's) in the chart's text colour. -fn title(w: &mut W, text: &str, c: &Chart) { - w.open0("c:title"); - rich(w, text, c.text_color.as_ref()); - w.val("c:overlay", 0); - w.close("c:title"); -} - -/// Points one cache writes. Excel and PowerPoint hold 32,000 points per series, so this is far -/// above any chart they make; a longer vector is cut here with a warning, not refused. -const MAX_CACHE_POINTS: usize = 1_000_000; - -/// `vals` cut to [`MAX_CACHE_POINTS`]. -fn capped(vals: &[T]) -> &[T] { - if vals.len() > MAX_CACHE_POINTS { - log::warn!("pptx: chart data cache cut from {} to {MAX_CACHE_POINTS} points", vals.len()); - } - &vals[..vals.len().min(MAX_CACHE_POINTS)] -} - -fn str_cache(w: &mut W, f: &str, vals: &[String]) { - let vals = capped(vals); - w.open0("c:strRef"); - w.elt("c:f", f); - w.open0("c:strCache"); - w.val("c:ptCount", vals.len()); - for (i, v) in vals.iter().enumerate() { - w.open("c:pt", A::new().a("idx", i)); - w.elt("c:v", v); - w.close("c:pt"); - } - w.close("c:strCache"); - w.close("c:strRef"); -} - -fn num_cache(w: &mut W, f: &str, vals: &[Option]) { - let vals = capped(vals); - w.open0("c:numRef"); - w.elt("c:f", f); - w.open0("c:numCache"); - w.elt("c:formatCode", "General"); - w.val("c:ptCount", vals.len()); - for (i, v) in vals.iter().enumerate() { - if let Some(v) = v.filter(|v| v.is_finite()) { - w.open("c:pt", A::new().a("idx", i)); - w.elt("c:v", &fmt_num(v)); - w.close("c:pt"); - } - } - w.close("c:numCache"); - w.close("c:numRef"); -} - -/// Numbers written into the chart itself (`c:numLit`), with no worksheet range behind them. -fn num_lit(w: &mut W, vals: &[Option]) { - let vals = capped(vals); - w.open0("c:numLit"); - w.val("c:ptCount", vals.len()); - for (i, v) in vals.iter().enumerate() { - if let Some(v) = v.filter(|v| v.is_finite()) { - w.open("c:pt", A::new().a("idx", i)); - w.elt("c:v", &fmt_num(v)); - w.close("c:pt"); - } - } - w.close("c:numLit"); -} - -#[derive(Clone, Copy, PartialEq)] -enum Group { - Bar, - Line, - Area, - Pie, - Doughnut, - Scatter, - Radar, - Bubble, - Stock, -} - -fn group_of(k: ChartType) -> Group { - match k { - ChartType::Line | ChartType::LineMarkers | ChartType::StackedLine => Group::Line, - ChartType::Stock => Group::Stock, - ChartType::Area | ChartType::StackedArea | ChartType::Surface => Group::Area, - ChartType::Pie => Group::Pie, - ChartType::Doughnut | ChartType::Sunburst => Group::Doughnut, - ChartType::Scatter => Group::Scatter, - ChartType::Bubble => Group::Bubble, - ChartType::Radar | ChartType::FilledRadar => Group::Radar, - _ => Group::Bar, - } -} - -fn error_bars(w: &mut W, e: &ErrorBars, g: Group) { - let word = |v: &str, ok: &[&'static str], d: &'static str| ok.iter().copied().find(|o| *o == v).unwrap_or(d); - w.open0("c:errBars"); - if matches!(g, Group::Scatter | Group::Bubble) { - w.val("c:errDir", "y"); - } - w.val("c:errBarType", word(&e.bar_type, &["both", "plus", "minus"], "both")); - let vt = word(&e.val_type, &["fixedVal", "percentage", "stdDev", "stdErr", "cust"], "fixedVal"); - w.val("c:errValType", vt); - w.val("c:noEndCap", if e.end_cap { 0 } else { 1 }); - if vt == "cust" { - w.open0("c:plus"); - num_lit(w, &e.plus); - w.close("c:plus"); - w.open0("c:minus"); - num_lit(w, &e.minus); - w.close("c:minus"); - } else if e.value.is_finite() { - w.val("c:val", fmt_num(e.value)); - } - w.close("c:errBars"); -} - -/// Per-point fills of pie, doughnut and bar series. -fn point_fills(w: &mut W, s: &Series, g: Group) { - if !matches!(g, Group::Pie | Group::Doughnut | Group::Bar) { - return; - } - for (idx, f) in s.point_fills.iter().take(1000) { - w.open0("c:dPt"); - w.val("c:idx", idx); - if g == Group::Bar { - w.val("c:invertIfNegative", 0); - } - if g != Group::Bar { - w.val("c:bubble3D", 0); - } - sp_pr(w, Some(f), None); - w.close("c:dPt"); - } -} - -/// Data points (categories and values counted per series) one chart group writes to its caches. -const MAX_EXPORT_POINTS: usize = 4_000_000; - -fn series(w: &mut W, c: &Chart, s: &Series, i: usize, kind: ChartType, g: Group) { - w.open0("c:ser"); - w.val("c:idx", i); - w.val("c:order", i); - w.open0("c:tx"); - str_cache(w, &format!("Sheet1!${}$1", col(i + 1)), std::slice::from_ref(&s.name)); - w.close("c:tx"); - if g == Group::Stock && s.line.is_none() { - // A stock chart's series are points joined by the high-low lines, not lines of their own. - w.open0("c:spPr"); - w.open("a:ln", A::new().a("w", 19050)); - w.empty0("a:noFill"); - w.close("a:ln"); - w.close("c:spPr"); - } else { - sp_pr(w, s.fill.as_ref(), s.line.as_ref()); - } - if g == Group::Stock { - // High-low-close: the close is a dash on the high-low line; with up/down bars (or a set - // marker) the series keep their own. - let close = !c.up_down_bars && i + 1 == c.series.len() && c.series.len() == 3; - let sym = s.marker.as_deref().filter(|m| !m.is_empty() && m.chars().all(|ch| ch.is_ascii_alphanumeric())).unwrap_or(if close { - "dash" - } else { - "none" - }); - w.open0("c:marker"); - w.val("c:symbol", sym); - if sym != "none" { - w.val("c:size", 7); - } - w.close("c:marker"); - } - if g == Group::Bar { - w.val("c:invertIfNegative", 0); - } - if matches!(g, Group::Line | Group::Scatter | Group::Radar) { - let sym = match (&s.marker, kind) { - (Some(m), _) if !m.is_empty() => Some(m.as_str()), - (_, ChartType::LineMarkers) => None, - (_, ChartType::Scatter) => None, - _ => Some("none"), - }; - if let Some(sym) = sym.filter(|s| s.chars().all(|c| c.is_ascii_alphanumeric())) { - w.open0("c:marker"); - w.val("c:symbol", sym); - w.close("c:marker"); - } - } - point_fills(w, s, g); - if let Some(d) = s.data_labels { - data_labels(w, c, d); - } - // After labels, before the category and value caches (ECMA-376 series content order). - if matches!(g, Group::Bar | Group::Line | Group::Area | Group::Scatter) { - for t in s.trendlines.iter().take(16) { - trendline(w, t); - } - } - let n = c.categories.len().max(s.values.len()).min(MAX_CACHE_POINTS); - let last = n + 1; - if let Some(e) = &s.error_bars { - error_bars(w, e, g); - } - if matches!(g, Group::Scatter | Group::Bubble) { - let xs: Vec> = if s.x_values.is_empty() { (1..=s.values.len()).map(|v| Some(v as f64)).collect() } else { s.x_values.clone() }; - w.open0("c:xVal"); - num_cache(w, &format!("Sheet1!$A$2:$A${last}"), &xs); - w.close("c:xVal"); - w.open0("c:yVal"); - num_cache(w, &format!("Sheet1!${0}$2:${0}${last}", col(i + 1)), &s.values); - w.close("c:yVal"); - if g == Group::Bubble { - let sizes: Vec> = if s.sizes.is_empty() { s.values.iter().map(|_| Some(1.0)).collect() } else { s.sizes.clone() }; - w.open0("c:bubbleSize"); - num_cache(w, &format!("Sheet1!${0}$2:${0}${last}", col(i + 2)), &sizes); - w.close("c:bubbleSize"); - w.val("c:bubble3D", 0); - } else { - w.val("c:smooth", if s.smooth { 1 } else { 0 }); - } - } else { - w.open0("c:cat"); - str_cache(w, &format!("Sheet1!$A$2:$A${last}"), &c.categories); - w.close("c:cat"); - w.open0("c:val"); - num_cache(w, &format!("Sheet1!${0}$2:${0}${last}", col(i + 1)), &s.values); - w.close("c:val"); - if g == Group::Line { - w.val("c:smooth", if s.smooth { 1 } else { 0 }); - } - } - w.close("c:ser"); -} - -fn trend_num(v: Option) -> Option { - v.filter(|v| v.is_finite() && v.abs() <= 1.0e12) -} - -fn trend_name(s: &str) -> Option { - let cleaned: String = - s.chars().filter(|c| matches!(c, '\t' | '\n' | '\r') || (*c >= ' ' && *c != '\u{FFFE}' && *c != '\u{FFFF}')).take(255).collect(); - let cleaned = cleaned.trim(); - if cleaned.is_empty() { None } else { Some(cleaned.to_string()) } -} - -fn trendline(w: &mut W, t: &Trendline) { - w.open0("c:trendline"); - if let Some(name) = t.name.as_deref().and_then(trend_name) { - w.elt("c:name", &name); - } - w.val("c:trendlineType", t.kind.xml()); - if t.kind == TrendlineType::Poly - && let Some(o) = t.order - { - w.val("c:order", o.clamp(2, 6)); - } - if t.kind == TrendlineType::MovingAvg - && let Some(p) = t.period - { - w.val("c:period", p.clamp(2, 255)); - } - if let Some(v) = trend_num(t.forward) { - w.val("c:forward", fmt_num(v)); - } - if let Some(v) = trend_num(t.backward) { - w.val("c:backward", fmt_num(v)); - } - if let Some(v) = trend_num(t.intercept) { - w.val("c:intercept", fmt_num(v)); - } - if t.disp_r_sqr { - w.val("c:dispRSqr", 1); - } - if t.disp_eq { - w.val("c:dispEq", 1); - } - w.close("c:trendline"); -} - -fn data_labels(w: &mut W, c: &Chart, show: bool) { - w.open0("c:dLbls"); - tx_pr(w, c); - for (n, v) in [ - ("c:showLegendKey", false), - ("c:showVal", show), - ("c:showCatName", false), - ("c:showSerName", false), - ("c:showPercent", false), - ("c:showBubbleSize", false), - ] { - w.val(n, if v { 1 } else { 0 }); - } - w.close("c:dLbls"); -} - -const AX_CAT: u32 = 50_001; -const AX_VAL: u32 = 50_002; - -fn axes(w: &mut W, c: &Chart, g: Group) { - let horizontal = c.kind.horizontal() && g == Group::Bar; - let (cat_pos, val_pos) = if horizontal { ("l", "b") } else { ("b", "l") }; - if g == Group::Scatter || g == Group::Bubble { - w.open0("c:valAx"); - w.val("c:axId", AX_CAT); - w.open0("c:scaling"); - w.val("c:orientation", "minMax"); - w.close("c:scaling"); - w.val("c:delete", 0); - w.val("c:axPos", "b"); - if let Some(t) = &c.axis_titles.0 { - title(w, t, c); - } - w.empty("c:numFmt", A::new().a("formatCode", "General").a("sourceLinked", 1)); - w.val("c:majorTickMark", "out"); - w.val("c:minorTickMark", "none"); - w.val("c:tickLblPos", "nextTo"); - tx_pr(w, c); - w.val("c:crossAx", AX_VAL); - w.val("c:crosses", "autoZero"); - w.val("c:crossBetween", "midCat"); - w.close("c:valAx"); - } else { - w.open0("c:catAx"); - w.val("c:axId", AX_CAT); - w.open0("c:scaling"); - w.val("c:orientation", if c.cat_reversed { "maxMin" } else { "minMax" }); - w.close("c:scaling"); - w.val("c:delete", 0); - w.val("c:axPos", cat_pos); - if let Some(t) = &c.axis_titles.0 { - title(w, t, c); - } - w.empty("c:numFmt", A::new().a("formatCode", "General").a("sourceLinked", 1)); - w.val("c:majorTickMark", "none"); - w.val("c:minorTickMark", "none"); - w.val("c:tickLblPos", "nextTo"); - tx_pr(w, c); - w.val("c:crossAx", AX_VAL); - w.val("c:crosses", "autoZero"); - w.val("c:auto", 1); - w.val("c:lblAlgn", "ctr"); - w.val("c:lblOffset", 100); - w.val("c:noMultiLvlLbl", 0); - w.close("c:catAx"); - } - w.open0("c:valAx"); - w.val("c:axId", AX_VAL); - w.open0("c:scaling"); - if let Some(b) = c.y_log_base { - w.val("c:logBase", fmt_num(b)); - } - w.val("c:orientation", "minMax"); - if let Some(m) = c.y_max.filter(|v| v.is_finite()) { - w.val("c:max", fmt_num(m)); - } - if let Some(m) = c.y_min.filter(|v| v.is_finite()) { - w.val("c:min", fmt_num(m)); - } - w.close("c:scaling"); - w.val("c:delete", 0); - w.val("c:axPos", val_pos); - if c.gridlines { - w.empty0("c:majorGridlines"); - } - if c.minor_gridlines { - w.empty0("c:minorGridlines"); - } - if let Some(t) = &c.axis_titles.1 { - title(w, t, c); - } - match c.y_format.as_deref().filter(|f| !f.is_empty()) { - Some(f) => w.empty("c:numFmt", A::new().a("formatCode", f).a("sourceLinked", 0)), - None => w.empty("c:numFmt", A::new().a("formatCode", if c.kind.percent() { "0%" } else { "General" }).a("sourceLinked", 1)), - } - w.val("c:majorTickMark", "none"); - w.val("c:minorTickMark", "none"); - w.val("c:tickLblPos", "nextTo"); - tx_pr(w, c); - w.val("c:crossAx", AX_CAT); - w.val("c:crosses", "autoZero"); - w.val("c:crossBetween", if g == Group::Area || g == Group::Scatter { "midCat" } else { "between" }); - w.close("c:valAx"); -} - -/// Points `series` writes into its caches for group `g`, synthesized vectors included. -fn series_points(c: &Chart, s: &Series, g: Group) -> usize { - let v = s.values.len(); - if matches!(g, Group::Scatter | Group::Bubble) { - let xs = if s.x_values.is_empty() { v } else { s.x_values.len() }; - let sizes = if g != Group::Bubble { - 0 - } else if s.sizes.is_empty() { - v - } else { - s.sizes.len() - }; - xs.saturating_add(v).saturating_add(sizes) - } else { - c.categories.len().saturating_add(v) - } -} - -fn plot_group(w: &mut W, c: &Chart, kind: ChartType, list: &[(usize, &Series)]) { - let g = group_of(kind); - let grouping = if kind.percent() { - "percentStacked" - } else if kind.stacked() { - "stacked" - } else if matches!(g, Group::Bar) { - "clustered" - } else { - "standard" - }; - let vary = if c.vary_colors { 1 } else { 0 }; - let tag = match g { - Group::Bar => "c:barChart", - Group::Line => "c:lineChart", - Group::Area => "c:areaChart", - Group::Pie => "c:pieChart", - Group::Doughnut => "c:doughnutChart", - Group::Scatter => "c:scatterChart", - Group::Radar => "c:radarChart", - Group::Bubble => "c:bubbleChart", - Group::Stock => "c:stockChart", - }; - w.open0(tag); - match g { - Group::Bar => { - w.val("c:barDir", if kind.horizontal() { "bar" } else { "col" }); - w.val("c:grouping", grouping); - } - Group::Line | Group::Area => w.val("c:grouping", grouping), - Group::Scatter => w.val("c:scatterStyle", "lineMarker"), - Group::Radar => w.val("c:radarStyle", if kind == ChartType::FilledRadar { "filled" } else { "marker" }), - _ => {} - } - // `c:stockChart` has no `c:varyColors`. - if g != Group::Stock { - w.val("c:varyColors", vary); - } - // Each series repeats the categories in its own cache, so the output grows with series times - // categories: stop adding series once a group's caches pass the budget (the first is always written). - // The first series is always written; each of its caches is cut at MAX_CACHE_POINTS. - let mut left = MAX_EXPORT_POINTS; - for (n, (i, s)) in list.iter().enumerate() { - let cost = series_points(c, s, g); - if n > 0 && cost > left { - log::warn!("pptx: chart export stopped after {n} series; the data caches passed {MAX_EXPORT_POINTS} points"); - break; - } - left = left.saturating_sub(cost); - series(w, c, s, *i, kind, g); - } - if c.data_labels { - data_labels(w, c, true); - } - match g { - Group::Bar => { - w.val("c:gapWidth", (c.gap_width.clamp(0.0, 5.0) * 100.0).round() as i64); - let ov = if kind.stacked() { 100 } else { (c.overlap.clamp(-1.0, 1.0) * 100.0).round() as i64 }; - if ov != 0 { - w.val("c:overlap", ov); - } - } - Group::Line => w.val("c:marker", 1), - Group::Stock => { - w.open0("c:hiLowLines"); - w.open0("c:spPr"); - w.open("a:ln", A::new().a("w", 9525)); - w.open0("a:solidFill"); - w.empty("a:schemeClr", A::new().a("val", "tx1")); - w.close("a:solidFill"); - w.close("a:ln"); - w.close("c:spPr"); - w.close("c:hiLowLines"); - if c.up_down_bars { - w.open0("c:upDownBars"); - w.val("c:gapWidth", 150); - w.empty0("c:upBars"); - w.empty0("c:downBars"); - w.close("c:upDownBars"); - } - } - Group::Pie => w.val("c:firstSliceAng", 0), - Group::Doughnut => { - w.val("c:firstSliceAng", 0); - w.val("c:holeSize", (c.hole_size.clamp(0.1, 0.9) * 100.0).round() as i64); - } - _ => {} - } - if !matches!(g, Group::Pie | Group::Doughnut) { - w.val("c:axId", AX_CAT); - w.val("c:axId", AX_VAL); - } - w.close(tag); -} - -/// The `chartEx` part of an Office 2016 chart (waterfall, funnel…): the kept part when the chart -/// is unchanged since it was read, else one written from the model. `None` for other chart types. -#[cfg(test)] -pub fn chartex_xml(c: &Chart) -> Option> { - chartex_part(c).map(|(x, _)| x) -} - -/// [`chartex_xml`], and whether it is the original part (so its kept relationships still apply). -pub fn chartex_part(c: &Chart) -> Option<(Vec, bool)> { - kept_chartex(c).map(|x| (x, true)).or_else(|| c.kind.is_chartex().then(|| (build_chartex(c), false))) -} - -fn kept_chartex(c: &Chart) -> Option> { - let raw = c.raw.as_ref()?; - let doc = crate::xml::parse(raw.as_bytes()).ok()?; - let mut root = doc.root.clone(); - crate::read::resolve_mc(&mut root, 0); - let mut back = crate::read::chartex_from(&root)?; - back.raw = c.raw.clone(); - // The sidecar is not modelled chart state. - back.kept = c.kept.clone(); - if &back != c { - return None; - } - let mut keep = doc.root; - // The workbook link stays only when its part is written back. - drop_unkept_refs(&mut keep, c); - let mut w = W::new(); - w.raw(&keep.to_xml()); - Some(w.finish()) -} - -/// The chart part XML, and whether it is the original part (so its relationships still apply). -pub fn chart_xml(c: &Chart) -> (Vec, bool) { - // A chart too large to model is written back as it was read. - if c.verbatim - && let Some(raw) = &c.raw - && let Ok(doc) = crate::xml::parse(raw.as_bytes()) - && doc.root.is("chartSpace") - { - let mut keep = doc.root; - drop_unkept_refs(&mut keep, c); - let mut w = W::new(); - w.raw(&keep.to_xml()); - return (w.finish(), true); - } - // Reuse the kept part when the chart is unchanged since it was read. - if let Some(raw) = &c.raw - && !raw.contains(NS_CX) - && let Ok(doc) = crate::xml::parse(raw.as_bytes()) - && doc.root.is("chartSpace") - { - let mut root = doc.root.clone(); - crate::read::resolve_mc(&mut root, 0); - if let Some(back) = crate::read::chart_from_el(&root) { - let mut me = c.clone(); - me.raw = None; - // The sidecar is not modelled chart state. Comparing it would throw away an unchanged chart. - me.kept = Default::default(); - if back == me { - let mut keep = doc.root; - // Without the parts those elements point at, PowerPoint repairs the file. - drop_unkept_refs(&mut keep, c); - let mut w = W::new(); - w.raw(&keep.to_xml()); - return (w.finish(), true); - } - } - } - let mut w = W::new(); - w.open("c:chartSpace", A::new().a("xmlns:c", NS_C).a("xmlns:a", NS_A).a("xmlns:r", NS_R)); - w.val("c:date1904", 0); - w.val("c:roundedCorners", 0); - w.val("c:style", c.style.clamp(1, 48)); - w.open0("c:chart"); - match &c.title { - Some(t) => { - title(&mut w, t, c); - w.val("c:autoTitleDeleted", 0); - } - None => w.val("c:autoTitleDeleted", 1), - } - w.open0("c:plotArea"); - w.empty0("c:layout"); - let indexed: Vec<(usize, &Series)> = c.series.iter().enumerate().collect(); - let main = match c.kind { - ChartType::Combo => c.series.first().and_then(|s| s.kind).unwrap_or(ChartType::Column), - k => k, - }; - if c.kind == ChartType::Combo { - // One plot group per series type, sharing the axes. - let mut kinds: Vec = vec![]; - for s in &c.series { - let k = s.kind.unwrap_or(main); - let k = if matches!(group_of(k), Group::Pie | Group::Doughnut | Group::Scatter | Group::Bubble) { ChartType::Column } else { k }; - if !kinds.contains(&k) { - kinds.push(k); - } - } - for k in kinds { - let list: Vec<(usize, &Series)> = indexed - .iter() - .filter(|(_, s)| { - let sk = s.kind.unwrap_or(main); - let sk = - if matches!(group_of(sk), Group::Pie | Group::Doughnut | Group::Scatter | Group::Bubble) { ChartType::Column } else { sk }; - sk == k - }) - .copied() - .collect(); - plot_group(&mut w, c, k, &list); - } - axes(&mut w, c, Group::Bar); - } else { - if !matches!( - c.kind, - ChartType::Column - | ChartType::StackedColumn - | ChartType::PercentColumn - | ChartType::Bar - | ChartType::StackedBar - | ChartType::PercentBar - | ChartType::Line - | ChartType::LineMarkers - | ChartType::StackedLine - | ChartType::Area - | ChartType::StackedArea - | ChartType::Pie - | ChartType::Doughnut - | ChartType::Scatter - | ChartType::Bubble - | ChartType::Radar - | ChartType::FilledRadar - | ChartType::Stock - ) { - log::warn!("pptx: {} chart written as a column chart", c.kind.label()); - } - plot_group(&mut w, c, main, &indexed); - let g = group_of(main); - if !matches!(g, Group::Pie | Group::Doughnut) { - axes(&mut w, c, g); - } - } - if let Some(f) = &c.plot_fill { - sp_pr(&mut w, Some(f), None); - } - w.close("c:plotArea"); - if let Some(pos) = &c.legend { - let p = match pos.as_str() { - "b" | "t" | "l" | "r" | "tr" => pos.as_str(), - _ => "r", - }; - w.open0("c:legend"); - w.val("c:legendPos", p); - for e in &c.legend_entries { - legend_entry(&mut w, e); - } - w.val("c:overlay", u8::from(c.legend_overlay)); - tx_pr(&mut w, c); - w.close("c:legend"); - } - w.val("c:plotVisOnly", 1); - w.val("c:dispBlanksAs", "gap"); - w.close("c:chart"); - if let Some(f) = &c.chart_fill { - sp_pr(&mut w, Some(f), None); - } - tx_pr(&mut w, c); - w.close("c:chartSpace"); - (w.finish(), false) -} - -/// The relationship ids of an unchanged chart that [`write_kept`] writes back: external ones, and -/// internal ones whose part was kept. -fn kept_rel_ids(c: &Chart) -> std::collections::HashSet<&str> { - let parts: std::collections::HashSet = c.kept.parts.iter().filter(|p| kept_payload(&p.name)).map(|p| crate::opc::norm(&p.name)).collect(); - c.kept.rels.iter().filter(|r| r.external || parts.contains(&crate::opc::norm(&r.part))).map(|r| r.id.as_str()).collect() -} - -/// A kept part that is written as a part of its own (rels parts are rewritten instead). -fn kept_payload(name: &str) -> bool { - !name.to_ascii_lowercase().ends_with(".rels") && crate::opc::sidecar_part(name) -} - -/// Drop `c:externalData` / `c:userShapes` (and the `cx:` ones) that point at a relationship that -/// is not written back: without the part PowerPoint repairs the file. -fn drop_unkept_refs(root: &mut crate::xml::El, c: &Chart) { - let ids = kept_rel_ids(c); - fn rec(e: &mut crate::xml::El, ids: &std::collections::HashSet<&str>, depth: usize) { - if depth > crate::xml::MAX_DEPTH { - return; - } - e.children.retain(|n| match n { - crate::xml::Node::El(x) if x.is("externalData") || x.is("userShapes") => x.attr("r:id").is_some_and(|id| ids.contains(id)), - _ => true, - }); - for ch in e.elements_mut() { - rec(ch, ids, depth + 1); - } - } - rec(root, &ids, 0); -} - -/// A fresh name for a kept part: `ppt//keptN.`. The writer generates no `kept…` -/// names and `n` is unique within the package, so a kept part never lands on (or duplicates) a -/// part the writer makes, whatever the source file called it. -fn kept_name(original: &str, n: u32) -> String { - let norm = crate::opc::norm(original); - let area = norm.split('/').nth(1).unwrap_or("embeddings"); - let area = if matches!(area, "embeddings" | "charts" | "drawings" | "media") { area } else { "embeddings" }; - let file = crate::opc::file_of(&norm); - let ext = file - .rsplit_once('.') - .map(|(_, e)| e) - .filter(|e| !e.is_empty() && e.len() <= 8 && e.chars().all(|c| c.is_ascii_alphanumeric())) - .unwrap_or("bin"); - format!("ppt/{area}/kept{n}.{ext}") -} - -/// Write an unchanged chart's own relationships and the parts they reach. Each kept part is -/// written under a fresh name ([`kept_name`]) and the relationships between kept parts are -/// rewritten to those names; a relationship to anything that was not kept is dropped. -/// `n_kept` numbers kept parts across the package. -pub fn write_kept(pkg: &mut crate::opc::PackageOut, chart_name: &str, c: &Chart, n_kept: &mut u32) { - use std::collections::HashMap; - - use crate::opc::{RelsOut, norm, relative, rels_path}; - - if c.kept.rels.is_empty() { - return; - } - // Original part name (normalized) → the name written. - let mut names: HashMap = HashMap::new(); - for p in c.kept.parts.iter().filter(|p| kept_payload(&p.name)) { - let key = norm(&p.name); - if names.contains_key(&key) { - continue; - } - *n_kept += 1; - let new = kept_name(&p.name, *n_kept); - let ct = if !p.content_type.is_empty() { p.content_type.clone() } else { crate::mime_for(&p.name).to_string() }; - // An override per part: a kept part never sets the package-wide default for its extension. - pkg.xml_part(&new, &ct, p.bytes.clone()); - names.insert(key, new); - } - let mut rels = RelsOut::default(); - for r in &c.kept.rels { - if r.external { - rels.items.push((r.id.clone(), r.rel_type.clone(), r.target.clone(), true)); - } else if let Some(new) = names.get(&norm(&r.part)) { - rels.items.push((r.id.clone(), r.rel_type.clone(), relative(chart_name, new), false)); - } else { - log::warn!("pptx: chart relationship {} has no kept part; dropped", r.id); - } - } - pkg.rels(chart_name, &rels); - let mut parts_by_norm = std::collections::HashMap::new(); - for p in &c.kept.parts { - parts_by_norm.entry(norm(&p.name)).or_insert(p); - } - let mut seen_payloads = std::collections::HashSet::new(); - // The kept parts' own relationships, pointed at the new names. - for p in c.kept.parts.iter().filter(|p| kept_payload(&p.name)) { - let norm_name = norm(&p.name); - if !seen_payloads.insert(norm_name.clone()) { - continue; - } - let Some(new_source) = names.get(&norm_name) else { continue }; - let rp = norm(&rels_path(&p.name)); - let Some(rels_part) = parts_by_norm.get(&rp) else { continue }; - let mut out = RelsOut::default(); - for r in crate::opc::rels_from_bytes(&rels_part.bytes, &p.name).items { - if r.external { - out.items.push((r.id, r.ty, r.target_raw, true)); - } else if let Some(new) = names.get(&norm(&r.target)) { - out.items.push((r.id, r.ty, relative(new_source, new), false)); - } else { - log::warn!("pptx: relationship {} of kept chart part {} has no kept target; dropped", r.id, p.name); - } - } - pkg.rels(new_source, &out); - } -} - -/// A `cx:tx` holding plain text. -fn cx_text(w: &mut W, t: &str) { - w.open0("cx:tx"); - w.open0("cx:txData"); - w.open0("cx:v"); - w.text(t); - w.close("cx:v"); - w.close("cx:txData"); - w.close("cx:tx"); -} - -/// A `cx:lvl` of points. -fn cx_level(w: &mut W, pts: &[String], format: Option<&str>) { - let pts = capped(pts); - let mut a = A::new().a("ptCount", pts.len()); - if let Some(f) = format { - a = a.a("formatCode", f); - } - w.open("cx:lvl", a); - for (i, p) in pts.iter().enumerate() { - w.open("cx:pt", A::new().a("idx", i)); - w.text(p); - w.close("cx:pt"); - } - w.close("cx:lvl"); -} - -/// The `cx:layoutPr` of the region map series in a kept `chartEx` part. -fn kept_region_layout(raw: &str) -> Option { - let doc = crate::xml::parse(raw.as_bytes()).ok()?; - let mut root = doc.root; - crate::read::resolve_mc(&mut root, 0); - let region = root.child("chart")?.child("plotArea")?.child("plotAreaRegion")?; - let s = region.children_named("series").find(|s| s.attr("layoutId") == Some("regionMap"))?; - let lp = s.child("layoutPr")?; - // Written under our `cx` prefix; a part that bound chartex to another prefix is not copied. - lp.name.starts_with("cx:").then(|| lp.to_xml()) -} - -/// Points one `chartEx` part may carry in all, categories repeated for every series: Excel's 255 -/// series x 32,000 points. Series past it are left out with a warning (the first is always written). -const MAX_CHARTEX_POINTS: usize = 255 * 32_000; - -/// How many of `c`'s series fit [`MAX_CHARTEX_POINTS`] (at least one). -fn chartex_series_within_budget(c: &Chart) -> usize { - let level = |v: &Vec| v.len().min(MAX_CACHE_POINTS); - let cats = if c.categories.is_empty() { - 0 - } else { - level(&c.categories).saturating_add(c.category_levels.iter().map(level).fold(0usize, usize::saturating_add)) - }; - let mut left = MAX_CHARTEX_POINTS; - for (n, s) in c.series.iter().enumerate() { - let cost = cats.saturating_add(s.values.len().min(MAX_CACHE_POINTS)); - if n > 0 && cost > left { - log::warn!("pptx: chart part stopped after {n} series; its data passed {MAX_CHARTEX_POINTS} points"); - return n; - } - left = left.saturating_sub(cost); - } - c.series.len() -} - -/// Writes an Office 2016 chart from the model, as PowerPoint lays the part out: one `cx:data` -/// per series (categories and values), then the plot area with each series' layout, the axes -/// the layout uses, the title and the legend. -pub fn build_chartex(c: &Chart) -> Vec { - let n_series = chartex_series_within_budget(c); - let mut w = W::new(); - w.open("cx:chartSpace", A::new().a("xmlns:a", NS_A).a("xmlns:r", NS_R).a("xmlns:cx", NS_CX)); - w.open0("cx:chartData"); - for (i, s) in c.series.iter().enumerate().take(n_series) { - w.open("cx:data", A::new().a("id", i)); - if !c.categories.is_empty() { - w.open("cx:strDim", A::new().a("type", "cat")); - cx_level(&mut w, &c.categories, None); - for lv in &c.category_levels { - cx_level(&mut w, lv, None); - } - w.close("cx:strDim"); - } - let ty = match c.kind { - ChartType::Treemap | ChartType::Sunburst => "size", - ChartType::RegionMap => "colorVal", - _ => "val", - }; - w.open("cx:numDim", A::new().a("type", ty)); - let vals: Vec = s.values.iter().map(|v| v.map(fmt_num).unwrap_or_default()).collect(); - cx_level(&mut w, &vals, Some(s.number_format.as_deref().unwrap_or("General"))); - w.close("cx:numDim"); - w.close("cx:data"); - } - w.close("cx:chartData"); - w.open0("cx:chart"); - if let Some(t) = &c.title { - w.open("cx:title", A::new().a("pos", "t").a("align", "ctr").a("overlay", "0")); - cx_text(&mut w, t); - w.close("cx:title"); - } - w.open0("cx:plotArea"); - w.open0("cx:plotAreaRegion"); - let layout = match c.kind { - ChartType::Waterfall => "waterfall", - ChartType::Funnel => "funnel", - ChartType::Treemap => "treemap", - ChartType::Sunburst => "sunburst", - ChartType::BoxWhisker => "boxWhisker", - ChartType::RegionMap => "regionMap", - _ => "clusteredColumn", - }; - let one = !matches!(c.kind, ChartType::BoxWhisker); - for (i, s) in c.series.iter().enumerate().take(if one { 1 } else { n_series }) { - w.open("cx:series", A::new().a("layoutId", layout).a("uniqueId", format!("{{DC00000{i}-0000-4000-8000-000000000000}}"))); - cx_text(&mut w, &s.name); - if c.series_data_labels(s) { - w.open("cx:dataLabels", A::new().a("pos", if c.kind == ChartType::Funnel { "ctr" } else { "outEnd" })); - w.empty("cx:visibility", A::new().a("seriesName", "0").a("categoryName", "0").a("value", "1")); - w.close("cx:dataLabels"); - } - w.empty("cx:dataId", A::new().a("val", i)); - match c.kind { - ChartType::Waterfall if !c.subtotals.is_empty() => { - w.open0("cx:layoutPr"); - w.open0("cx:subtotals"); - for t in &c.subtotals { - w.empty("cx:idx", A::new().a("val", t)); - } - w.close("cx:subtotals"); - w.close("cx:layoutPr"); - } - ChartType::Histogram | ChartType::Pareto => { - w.open0("cx:layoutPr"); - w.open("cx:binning", A::new().a("intervalClosed", "r")); - if let Some(size) = c.bin_size { - w.empty("cx:binSize", A::new().a("val", fmt_num(size))); - } else if let Some(n) = c.bin_count { - w.empty("cx:binCount", A::new().a("val", n)); - } - w.close("cx:binning"); - w.close("cx:layoutPr"); - } - ChartType::BoxWhisker => { - w.open0("cx:layoutPr"); - w.empty("cx:visibility", A::new().a("meanLine", "0").a("meanMarker", "1").a("nonoutliers", "0").a("outliers", "1")); - w.empty("cx:statistics", A::new().a("quartileMethod", if c.inclusive_quartiles { "inclusive" } else { "exclusive" })); - w.close("cx:layoutPr"); - } - ChartType::RegionMap => { - // The map's geography (projection, region level and the cached boundaries - // PowerPoint downloaded) is not modelled: carry it over from the part we read. - if let Some(lp) = c.raw.as_deref().and_then(kept_region_layout) { - w.raw(&lp); - } - } - _ => {} - } - w.close("cx:series"); - } - if c.kind == ChartType::Pareto { - w.open("cx:series", A::new().a("layoutId", "paretoLine").a("ownerIdx", "0").a("uniqueId", "{DC0000FF-0000-4000-8000-000000000000}")); - w.empty("cx:axisId", A::new().a("val", "2")); - w.close("cx:series"); - } - w.close("cx:plotAreaRegion"); - if !matches!(c.kind, ChartType::Treemap | ChartType::Sunburst | ChartType::RegionMap) { - w.open("cx:axis", A::new().a("id", "0")); - w.empty("cx:catScaling", A::new().a("gapWidth", if matches!(c.kind, ChartType::Histogram | ChartType::Pareto) { "0" } else { "0.5" })); - w.empty0("cx:tickLabels"); - w.close("cx:axis"); - if c.kind != ChartType::Funnel { - w.open("cx:axis", A::new().a("id", "1")); - w.empty0("cx:valScaling"); - if c.gridlines { - w.empty0("cx:majorGridlines"); - } - w.empty0("cx:tickLabels"); - w.close("cx:axis"); - } - if c.kind == ChartType::Pareto { - w.open("cx:axis", A::new().a("id", "2")); - w.empty("cx:valScaling", A::new().a("max", "1").a("min", "0")); - w.empty0("cx:units"); - w.empty0("cx:tickLabels"); - w.close("cx:axis"); - } - } - w.close("cx:plotArea"); - if let Some(pos) = &c.legend { - w.empty("cx:legend", A::new().a("pos", pos.as_str()).a("align", "ctr").a("overlay", "0")); - } - w.close("cx:chart"); - w.close("cx:chartSpace"); - w.finish() -} - -#[cfg(test)] -mod region_map_tests { - use super::*; - - /// A region map part as PowerPoint writes it (our own numbers; the cached geography is a - /// stand-in blob). - const MAP: &str = r#"Sheet1!$A$2:$A$4MinskBrestGomelSheet1!$B$2:$B$41258Sheet1!$B$1SalesZGVja2NyYWZ0LXRlc3Q="#; - - #[test] - fn region_maps_keep_their_geography_through_save_and_edit() { - let c = crate::read::read_chartex_xml(MAP.as_bytes()).expect("a region map is read"); - assert_eq!(c.kind, ChartType::RegionMap); - assert_eq!(c.categories, ["Minsk", "Brest", "Gomel"]); - assert_eq!(c.series.first().map(|s| s.values.clone()), Some(vec![Some(12.0), Some(5.0), Some(8.0)])); - // Unchanged: written back as read. - let kept = String::from_utf8(chartex_xml(&c).unwrap_or_default()).unwrap_or_default(); - assert!(kept.contains("ZGVja2NyYWZ0LXRlc3Q=") && kept.contains("cultureRegion=\"BY\""), "{kept}"); - // Edited: rebuilt from the model, with the geography carried over. - let mut e = c.clone(); - if let Some(s) = e.series.first_mut() { - s.values[1] = Some(20.0); - } - let built = String::from_utf8(chartex_xml(&e).unwrap_or_default()).unwrap_or_default(); - assert!(built.contains("").count() >= 5, "{xml}"); - assert!(xml.contains(r#""#), "{xml}"); - assert!(xml.contains(""), "{xml}"); - assert_eq!(crate::read::chart::read_chart_xml(xml.as_bytes()).unwrap().text_color, Some(tinted)); - // An RGB colour and no colour at all round-trip too. - c.text_color = Some(ColorRef::rgb(Rgba::rgb(255, 255, 255))); - let xml = super::chart_xml(&c).0; - assert_eq!(crate::read::chart::read_chart_xml(&xml).unwrap().text_color, c.text_color); - c.text_color = None; - let xml = String::from_utf8(super::chart_xml(&c).0).unwrap(); - assert!(!xml.contains(""), "{xml}"); - assert_eq!(crate::read::chart::read_chart_xml(xml.as_bytes()).unwrap().text_color, None); - } - - /// An imported chart's `c:txPr` colour survives an edit that rebuilds the part from the model - /// (the colour used to be read but never written, so a save after any edit lost it). - #[test] - fn imported_text_colour_survives_an_edit_and_a_save() { - let xml = r#"1"#; - let c = crate::read::chart::read_chart_xml(xml.as_bytes()).unwrap(); - let grey = ColorRef::scheme(deckcraft_model::SchemeSlot::Tx1).with(ColorTransform::LumMod(65000)).with(ColorTransform::LumOff(35000)); - assert_eq!(c.text_color, Some(grey.clone())); - // Unchanged: the part is written back as read. - assert!(super::chart_xml(&c).1); - // Edited (a title; the editor drops `raw` on any edit): rebuilt with the colour. - let mut e = c.clone(); - e.title = Some("Units".into()); - e.raw = None; - let (out, kept) = super::chart_xml(&e); - assert!(!kept); - let back = crate::read::chart::read_chart_xml(&out).unwrap(); - assert_eq!(back.text_color, Some(grey)); - assert_eq!(back.title.as_deref(), Some("Units")); - } - - /// #2067: a legend entry's own text (`c:legendEntry/c:txPr`: size, bold, colour) is read, and - /// an edit that rebuilds the part writes it back, in schema order before `c:overlay`. - #[test] - fn legend_entry_text_is_read_and_survives_an_edit() { - let entry = |idx: u32, rgb: &str| { - format!( - r#""# - ) - }; - let xml = format!( - r#"1{}{}"#, - entry(0, "C00000"), - entry(1, "00B050") - ); - let c = crate::read::chart::read_chart_xml(xml.as_bytes()).unwrap(); - let want = |idx: u32, rgb: (u8, u8, u8)| deckcraft_model::chart::LegendEntry { - idx, - size: Some(20.0), - bold: Some(true), - color: Some(ColorRef::rgb(Rgba::rgb(rgb.0, rgb.1, rgb.2))), - }; - // The third entry sets nothing of its own and is not kept. - assert_eq!(c.legend_entries, vec![want(0, (0xC0, 0, 0)), want(1, (0, 0xB0, 0x50))]); - assert_eq!(c.text_size, Some(12.0), "the legend's own size stays the legend's"); - let mut e = c.clone(); - e.title = Some("Units".into()); - e.raw = None; - let (out, kept) = super::chart_xml(&e); - assert!(!kept); - let s = String::from_utf8(out.clone()).unwrap(); - let legend = &s[s.find("").unwrap()..]; - let (pos, entry0, overlay) = - (legend.find("").unwrap(), legend.find(""#, - r#""#, - 1, - ); - assert_ne!(listed, xml, "the list style was put in"); - let c = crate::read::chart::read_chart_xml(listed.as_bytes()).unwrap(); - assert_eq!(c.legend_entries[0], want(0, (0xC0, 0, 0)), "the paragraph's 20 pt, bold, C00000"); - // A size reads back as it was written, within the reader's 1-400 pt. - for (size, back) in [(20.5, 20.5), (400.0, 400.0), (500.0, 400.0)] { - let mut e = c.clone(); - e.raw = None; - e.legend_entries = vec![deckcraft_model::chart::LegendEntry { idx: 0, size: Some(size), bold: None, color: None }]; - let written = super::chart_xml(&e).0; - let sz = format!(r#"sz="{}""#, (back * 100.0) as u32); - assert!(String::from_utf8_lossy(&written).contains(&sz), "{size} pt is written as {sz}"); - let back_size = crate::read::chart::read_chart_xml(&written).unwrap().legend_entries[0].size; - assert_eq!(back_size, Some(back), "{size} pt"); - } - } - - #[test] - fn reversed_category_axis_round_trips() { - let mut c = Chart::sample(ChartType::Bar); - c.cat_reversed = true; - let xml = super::chart_xml(&c).0; - assert!(String::from_utf8_lossy(&xml).contains(r#""#)); - assert!(crate::read::chart::read_chart_xml(&xml).unwrap().cat_reversed); - c.cat_reversed = false; - assert!(!crate::read::chart::read_chart_xml(&super::chart_xml(&c).0).unwrap().cat_reversed); - } -} - -#[cfg(test)] -mod cache_cap_tests { - use super::*; - - #[test] - fn a_chartex_part_stops_adding_series_past_excels_point_count() { - const { assert!(MAX_CHARTEX_POINTS >= 255 * 32_000) }; - let mut c = Chart::sample(ChartType::Waterfall); - c.categories = vec![String::new(); 32_000]; - let mut s = c.series[0].clone(); - s.values = Vec::new(); - c.series = vec![s; 300]; - // 32,000 categories per series: 255 fit exactly, the 256th does not. - assert_eq!(chartex_series_within_budget(&c), 255); - c.series.truncate(3); - assert_eq!(chartex_series_within_budget(&c), 3); - } - - /// A cache longer than the cap is cut, never refused; anything a real chart holds (32,000 - /// points per series) is far under it. Zero-sized elements, so the test allocates nothing. - #[test] - fn caches_are_cut_at_the_cap_not_refused() { - const { assert!(MAX_CACHE_POINTS >= 32_000) }; - let over = vec![(); MAX_CACHE_POINTS + 1]; - assert_eq!(capped(&over).len(), MAX_CACHE_POINTS); - let real = vec![(); 32_000]; - assert_eq!(capped(&real).len(), 32_000); - } -} diff --git a/crates/pptx/src/write/dml.rs b/crates/pptx/src/write/dml.rs deleted file mode 100644 index d818c8e6b..000000000 --- a/crates/pptx/src/write/dml.rs +++ /dev/null @@ -1,871 +0,0 @@ -//! DrawingML writing: colours, fills, lines, effects, transforms and text. - -use deckcraft_geom::{Xfrm, pt_to_emu}; -use deckcraft_model::style::{ - ColorBase, ColorRef, Compound, Dash, Effects, Fill, GradientFlip, GradientShape, Line, LineAlign, LineCap, LineJoin, PictureFill, PictureMode, -}; -use deckcraft_model::text::{ - Action, AutoFit, BodyProps, Bullet, Caps, Hyperlink, ListStyle, ParaProps, Paragraph, RunKind, RunProps, Spacing, Strike, TextBody, -}; - -use super::{Exp, Out}; -use crate::xml::{A, W}; - -pub fn emu(pt: f64) -> i64 { - pt_to_emu(pt).clamp(-27_273_042_316_900, 27_273_042_316_900) -} - -/// Positive coordinate extent (ST_PositiveCoordinate). -pub fn emu_pos(pt: f64) -> i64 { - emu(pt).max(0) -} - -/// Fraction → 1/100 000. -pub fn pct(v: f64) -> i64 { - if v.is_finite() { (v * 100_000.0).round().clamp(-2.0e9, 2.0e9) as i64 } else { 0 } -} - -/// Degrees → 1/60 000 degree, normalised to 0..360. -pub fn ang(deg: f64) -> i64 { - if !deg.is_finite() { - return 0; - } - let d = deg.rem_euclid(360.0); - ((d * 60_000.0).round() as i64).clamp(0, 21_599_999) -} - -pub fn color(w: &mut W, c: &ColorRef) { - let (tag, a) = match &c.base { - ColorBase::Rgb { rgb } => ("a:srgbClr", A::new().a("val", rgb.hex())), - ColorBase::Scheme { slot } => ("a:schemeClr", A::new().a("val", slot.xml_name())), - // The reader keeps any name a file has; only names the schema allows are written. - ColorBase::Preset { name } => ("a:prstClr", A::new().a("val", if deckcraft_color::is_preset_name(name) { name } else { "black" })), - ColorBase::System { name, last } => { - ("a:sysClr", A::new().a("val", if deckcraft_color::is_system_name(name) { name } else { "windowText" }).a("lastClr", last.hex())) - } - }; - let rgb_alpha = match &c.base { - ColorBase::Rgb { rgb } if rgb.a < 255 && !c.mods.iter().any(|m| matches!(m, deckcraft_color::ColorTransform::Alpha(_))) => { - Some((rgb.a as i64 * 100_000 / 255) as i32) - } - _ => None, - }; - if c.mods.is_empty() && rgb_alpha.is_none() { - w.empty(tag, a); - return; - } - w.open(tag, a); - for m in &c.mods { - let name = format!("a:{}", m.xml_name()); - match m.value() { - Some(v) => w.val(&name, v), - None => w.empty0(&name), - } - } - if let Some(al) = rgb_alpha { - w.val("a:alpha", al); - } - w.close(tag); -} - -pub fn solid(w: &mut W, c: &ColorRef) { - w.open0("a:solidFill"); - color(w, c); - w.close("a:solidFill"); -} - -/// Write a fill. `Fill::Background` (only meaningful on `p:sp`) writes nothing. -pub fn fill(w: &mut W, x: &mut Exp, o: &mut Out, f: &Fill) { - match f { - Fill::None => w.empty0("a:noFill"), - Fill::Solid { color: c } => solid(w, c), - Fill::Gradient(g) => gradient(w, g), - Fill::Picture(pf) => blip_fill(w, x, o, "a:blipFill", pf), - Fill::Pattern(p) => { - w.open("a:pattFill", A::new().a("prst", if p.preset.is_empty() { "pct5" } else { &p.preset })); - w.open0("a:fgClr"); - color(w, &p.fg); - w.close("a:fgClr"); - w.open0("a:bgClr"); - color(w, &p.bg); - w.close("a:bgClr"); - w.close("a:pattFill"); - } - Fill::Group => w.empty0("a:grpFill"), - Fill::Background => {} - } -} - -/// `a:blipFill` / `p:blipFill`. -pub fn blip_fill(w: &mut W, x: &mut Exp, o: &mut Out, tag: &str, pf: &PictureFill) { - // An image that lives outside the package is a linked picture: `a:blip` names it through - // `r:link`; `r:embed` may only reference a part inside the package. - let linked = x.media(pf.media).is_some_and(|m| m.data.is_empty() && m.link.is_some()); - let rid = x.media_rel(o, pf.media, "image").unwrap_or_else(|| x.placeholder_rel(o)); - w.open(tag, A::new().a("rotWithShape", if pf.upright { "0" } else { "1" })); - let adj = &pf.adjust; - let has_kids = pf.alpha.is_some() - || adj.brightness != 0.0 - || adj.contrast != 0.0 - || adj.grayscale - || adj.duotone.is_some() - || adj.clear_color.is_some() - || adj.bilevel.is_some() - || adj.alpha_inv - || pf.artistic.is_some(); - let a = if linked { A::new().a("r:link", &rid) } else { A::new().a("r:embed", &rid) }; - if has_kids { - w.open("a:blip", a); - if let Some(c) = adj.clear_color { - w.open0("a:clrChange"); - w.open0("a:clrFrom"); - color(w, &ColorRef::rgb(c)); - w.close("a:clrFrom"); - w.open0("a:clrTo"); - color(w, &ColorRef::rgb(c).with(deckcraft_color::ColorTransform::Alpha(0))); - w.close("a:clrTo"); - w.close("a:clrChange"); - } - if let Some(al) = pf.alpha { - w.empty("a:alphaModFix", A::new().a("amt", pct(al.clamp(0.0, 1.0)))); - } - if adj.alpha_inv { - w.empty0("a:alphaInv"); - } - if let Some(t) = adj.bilevel { - w.empty("a:biLevel", A::new().a("thresh", pct(t.clamp(0.0, 1.0)))); - } - if let Some((d, l)) = &adj.duotone { - w.open0("a:duotone"); - color(w, d); - color(w, l); - w.close("a:duotone"); - } - if adj.grayscale { - w.empty0("a:grayscl"); - } - if adj.brightness != 0.0 || adj.contrast != 0.0 { - w.empty("a:lum", A::new().a("bright", pct(adj.brightness.clamp(-1.0, 1.0))).a("contrast", pct(adj.contrast.clamp(-1.0, 1.0)))); - } - // Artistic effect: the blip is the processed picture; the original rides in an - // `a14:imgLayer` with the effect's name, as PowerPoint writes it. - if let Some(art) = &pf.artistic - && art.effect.starts_with("artistic") - && art.effect.chars().all(|c| c.is_ascii_alphanumeric()) - && let Some(orig) = x.media_rel(o, art.original, "image") - { - w.open0("a:extLst"); - w.open("a:ext", A::new().a("uri", "{BEBA8EAE-BF5A-486C-A8C5-ECC9F3942E4B}")); - w.open("a14:imgProps", A::new().a("xmlns:a14", crate::opc::NS_A14)); - w.open("a14:imgLayer", A::new().a("r:embed", &orig)); - w.open0("a14:imgEffect"); - w.empty0(&format!("a14:{}", art.effect)); - w.close("a14:imgEffect"); - w.close("a14:imgLayer"); - w.close("a14:imgProps"); - w.close("a:ext"); - w.close("a:extLst"); - } - w.close("a:blip"); - } else { - w.empty("a:blip", a); - } - let c = pf.crop; - if c.iter().any(|v| *v != 0.0) { - w.empty("a:srcRect", A::new().a("l", pct(c[0])).a("t", pct(c[1])).a("r", pct(c[2])).a("b", pct(c[3]))); - } - match &pf.mode { - PictureMode::Stretch { fill_rect: r } => { - w.open0("a:stretch"); - if r.iter().any(|v| *v != 0.0) { - w.empty("a:fillRect", A::new().a("l", pct(r[0])).a("t", pct(r[1])).a("r", pct(r[2])).a("b", pct(r[3]))); - } else { - w.empty0("a:fillRect"); - } - w.close("a:stretch"); - } - PictureMode::Tile { tx, ty, sx, sy, flip, align } => { - let flip = match flip.as_str() { - "x" | "y" | "xy" => flip.as_str(), - _ => "none", - }; - let algn = match align.as_str() { - "tl" | "t" | "tr" | "l" | "ctr" | "r" | "bl" | "b" | "br" => align.as_str(), - _ => "tl", - }; - w.empty("a:tile", A::new().a("tx", emu(*tx)).a("ty", emu(*ty)).a("sx", pct(*sx)).a("sy", pct(*sy)).a("flip", flip).a("algn", algn)); - } - } - w.close(tag); -} - -pub fn line(w: &mut W, x: &mut Exp, o: &mut Out, tag: &str, l: &Line) { - let a = A::new() - .o("w", l.width.map(|v| emu(v.clamp(0.0, 1584.0)))) - .o( - "cap", - l.cap.map(|c| match c { - LineCap::Round => "rnd", - LineCap::Square => "sq", - LineCap::Flat => "flat", - }), - ) - .o("algn", l.align.map(LineAlign::xml)) - .o("cmpd", l.compound.map(Compound::xml)); - w.open(tag, a); - if let Some(f) = &l.fill { - match f { - Fill::None | Fill::Solid { .. } | Fill::Gradient(_) | Fill::Pattern(_) => fill(w, x, o, f), - _ => {} - } - } - match &l.dash { - Some(Dash::Preset { name }) => { - let n = if Dash::PRESETS.contains(&name.as_str()) { name.as_str() } else { "solid" }; - w.val("a:prstDash", n); - } - Some(Dash::Custom { pattern }) if !pattern.is_empty() => { - w.open0("a:custDash"); - for (d, s) in pattern.iter().take(64) { - w.empty("a:ds", A::new().a("d", pct(*d).max(0)).a("sp", pct(*s).max(0))); - } - w.close("a:custDash"); - } - _ => {} - } - match l.join { - Some(LineJoin::Round) => w.empty0("a:round"), - Some(LineJoin::Bevel) => w.empty0("a:bevel"), - Some(LineJoin::Miter) => { - let limit = l.miter_limit.filter(|limit| *limit <= i32::MAX as u32); - w.empty("a:miter", A::new().o("lim", limit)); - } - None => {} - } - for (t, e) in [("a:headEnd", &l.head), ("a:tailEnd", &l.tail)] { - if let Some(e) = e { - let kind = match e.kind.as_str() { - "triangle" | "stealth" | "diamond" | "oval" | "arrow" => e.kind.as_str(), - _ => "none", - }; - let sz = |s: &str| match s { - "sm" | "lg" => s.to_string(), - _ => "med".to_string(), - }; - w.empty(t, A::new().a("type", kind).a("w", sz(&e.w)).a("len", sz(&e.len))); - } - } - w.close(tag); -} - -fn shadow(w: &mut W, tag: &str, s: &deckcraft_model::style::Shadow) { - let mut a = A::new().a("blurRad", emu(s.blur).max(0)).a("dist", emu(s.dist).max(0)).a("dir", ang(s.dir)); - if tag == "a:outerShdw" { - if s.sx != 1.0 { - a = a.a("sx", pct(s.sx)); - } - if s.sy != 1.0 { - a = a.a("sy", pct(s.sy)); - } - if s.kx != 0.0 { - a = a.a("kx", (s.kx.clamp(-89.0, 89.0) * 60_000.0).round() as i64); - } - if s.ky != 0.0 { - a = a.a("ky", (s.ky.clamp(-89.0, 89.0) * 60_000.0).round() as i64); - } - let algn = match s.align.as_str() { - "tl" | "t" | "tr" | "l" | "ctr" | "r" | "bl" | "b" | "br" => s.align.as_str(), - _ => "b", - }; - a = a.a("algn", algn).a("rotWithShape", if s.rotate_with_shape { "1" } else { "0" }); - } - w.open(tag, a); - color(w, &s.color); - w.close(tag); -} - -fn gradient(w: &mut W, g: &deckcraft_model::style::Gradient) { - w.open("a:gradFill", A::new().o("flip", g.flip.map(GradientFlip::xml)).a("rotWithShape", if g.rotate_with_shape { "1" } else { "0" })); - // No stops: no `a:gsLst`, so the gradient keeps taking them from its style's fill. - let mut stops = g.stops.clone(); - if stops.len() == 1 { - let mut s = stops[0].clone(); - s.pos = 1.0; - stops.push(s); - } - if !stops.is_empty() { - w.open0("a:gsLst"); - for s in &stops { - w.open("a:gs", A::new().a("pos", pct(s.pos.clamp(0.0, 1.0)))); - color(w, &s.color); - w.close("a:gs"); - } - w.close("a:gsLst"); - } - match &g.shape { - GradientShape::Linear { angle, scaled } => w.empty("a:lin", A::new().a("ang", ang(*angle)).a("scaled", if *scaled { "1" } else { "0" })), - GradientShape::Path { path, focus } => { - let p = match path.as_str() { - "rect" | "shape" | "circle" => path.as_str(), - _ => "circle", - }; - w.open("a:path", A::new().a("path", p)); - w.empty("a:fillToRect", A::new().a("l", pct(focus[0])).a("t", pct(focus[1])).a("r", pct(focus[2])).a("b", pct(focus[3]))); - w.close("a:path"); - } - } - if g.tile.iter().any(|v| *v != 0.0) { - let [l, t, r, b] = g.tile; - w.empty("a:tileRect", A::new().a("l", pct(l)).a("t", pct(t)).a("r", pct(r)).a("b", pct(b))); - } - w.close("a:gradFill"); -} - -pub fn effects(w: &mut W, fx: &Effects) { - w.open0("a:effectLst"); - // Schema order: blur, fillOverlay, glow, innerShdw, outerShdw, prstShdw, reflection, softEdge. - if let Some(ov) = &fx.fill_overlay { - let blend = match ov.blend.as_str() { - b @ ("over" | "mult" | "screen" | "darken" | "lighten") => b, - _ => "over", - }; - w.open("a:fillOverlay", A::new().a("blend", blend)); - match &ov.fill { - Fill::Solid { color: c } => solid(w, c), - Fill::Gradient(g) => gradient(w, g), - _ => w.empty0("a:noFill"), - } - w.close("a:fillOverlay"); - } - if let Some(g) = &fx.glow { - w.open("a:glow", A::new().a("rad", emu(g.radius).max(0))); - color(w, &g.color); - w.close("a:glow"); - } - if let Some(s) = &fx.inner_shadow { - shadow(w, "a:innerShdw", s); - } - if let Some(s) = &fx.outer_shadow { - shadow(w, "a:outerShdw", s); - } - if let Some(r) = &fx.reflection { - w.empty( - "a:reflection", - A::new() - .a("blurRad", emu(r.blur).max(0)) - .a("stA", pct(r.start_alpha.clamp(0.0, 1.0))) - .a("endA", pct(r.end_alpha.clamp(0.0, 1.0))) - .a("endPos", pct(r.end_pos.clamp(0.0, 1.0))) - .a("dist", emu(r.dist).max(0)) - // Kept from a file as read: held to the schema's ranges so a stray value can't - // make PowerPoint repair the file (ST_PositiveFixedAngle, ST_FixedAngle, - // ST_PositiveFixedPercentage). - .o("stPos", r.st_pos.map(|v| v.clamp(0, 100_000))) - .o("dir", r.dir.map(|v| v.rem_euclid(21_600_000))) - .o("fadeDir", r.fade_dir.map(|v| v.rem_euclid(21_600_000))) - .o("sx", r.sx) - .o("sy", r.sy) - .o("kx", r.kx.map(|v| v.clamp(-5_399_999, 5_399_999))) - .o("ky", r.ky.map(|v| v.clamp(-5_399_999, 5_399_999))) - .o("algn", r.align.as_deref()) - .b("rotWithShape", r.rotate_with_shape), - ); - } - if let Some(r) = fx.soft_edge { - w.empty("a:softEdge", A::new().a("rad", emu(r).max(0))); - } - w.close("a:effectLst"); -} - -/// `a:sp3d` for a bevel preset when the shape or theme style has no kept 3-D XML. -/// The preset name is limited to ASCII letters and digits so it cannot break the markup. -pub fn bevel_sp3d(preset: &str) -> Option { - if preset.is_empty() || preset.len() > 32 || !preset.chars().all(|c| c.is_ascii_alphanumeric()) { - return None; - } - Some(format!("")) -} - -pub fn xfrm(w: &mut W, tag: &str, x: &Xfrm, child: Option<&Xfrm>) { - let x = if x.is_finite() { *x } else { Xfrm::default() }; - let rot = ang(x.rot); - w.open(tag, A::new().o("rot", (rot != 0).then_some(rot)).t("flipH", x.flip_h).t("flipV", x.flip_v)); - w.empty("a:off", A::new().a("x", emu(x.x)).a("y", emu(x.y))); - w.empty("a:ext", A::new().a("cx", emu_pos(x.w)).a("cy", emu_pos(x.h))); - if let Some(c) = child { - let c = if c.is_finite() { *c } else { Xfrm::default() }; - w.empty("a:chOff", A::new().a("x", emu(c.x)).a("y", emu(c.y))); - w.empty("a:chExt", A::new().a("cx", emu_pos(c.w)).a("cy", emu_pos(c.h))); - } - w.close(tag); -} - -// --------------------------------------------------------------------------------------------- -// Text - -pub fn hyperlink(w: &mut W, x: &mut Exp, o: &mut Out, tag: &str, h: &Hyperlink) { - let (rid, action) = match &h.action { - Action::Url { url } => { - if url.is_empty() { - return; - } - (o.rels.add("hyperlink", url, true), None) - } - Action::Slide { slide } => match x.slide_parts.get(slide) { - Some(target) => { - let rel = crate::opc::relative(&o.name, target); - (o.rels.add("slide", &rel, false), Some("ppaction://hlinksldjump".to_string())) - } - None => return, - }, - Action::NextSlide => (String::new(), Some("ppaction://hlinkshowjump?jump=nextslide".into())), - Action::PreviousSlide => (String::new(), Some("ppaction://hlinkshowjump?jump=previousslide".into())), - Action::FirstSlide => (String::new(), Some("ppaction://hlinkshowjump?jump=firstslide".into())), - Action::LastSlide => (String::new(), Some("ppaction://hlinkshowjump?jump=lastslide".into())), - Action::EndShow => (String::new(), Some("ppaction://hlinkshowjump?jump=endshow".into())), - Action::LastViewed => (String::new(), Some("ppaction://hlinkshowjump?jump=lastslideviewed".into())), - Action::CustomShow { name, returns } => { - let id = x.p.custom_shows.iter().position(|c| c.name == *name).unwrap_or(0); - let ret = if *returns { "true" } else { "false" }; - (String::new(), Some(format!("ppaction://customshow?id={id}&return={ret}"))) - } - Action::Program { path } => { - if path.is_empty() { - return; - } - (o.rels.add("hyperlink", path, true), Some("ppaction://program".into())) - } - Action::PlayMedia => (String::new(), Some("ppaction://media".into())), - }; - let attrs = A::new() - .a("r:id", rid) - .o("action", action) - .o("tooltip", (!h.tooltip.is_empty()).then_some(h.tooltip.as_str())) - .t("highlightClick", h.highlight_click) - .t("endSnd", h.stop_sound); - let sound = h.sound.and_then(|id| x.media_rel(o, id, "audio").map(|rid| (rid, id))); - let Some((sound_rid, sound_id)) = sound else { - w.empty(tag, attrs); - return; - }; - w.open(tag, attrs); - let name = x.media(sound_id).map(|m| sound_label(&m.name)).unwrap_or_else(|| "sound.wav".into()); - w.empty("a:snd", A::new().a("r:embed", sound_rid).a("name", name)); - w.close(tag); -} - -/// Display name PowerPoint stores on `a:snd`. -fn sound_label(name: &str) -> String { - let file = name.rsplit(['/', '\\']).next().unwrap_or(name); - let label: String = file.chars().filter(|c| c.is_ascii() && !c.is_control() && *c != '"' && *c != '<' && *c != '>').take(80).collect(); - if label.is_empty() { "sound.wav".into() } else { label } -} - -/// Validate an unmodelled 3-D fragment (`a:scene3d`, `a:sp3d`, `a:flatTx`) before writing raw XML. -pub fn valid_raw3d<'a>(raw: &'a str, allowed: &[&str]) -> Option<&'a str> { - if raw.is_empty() || raw.len() > 64 * 1024 { - return None; - } - let wrap = format!("{raw}", crate::opc::NS_A); - let doc = crate::xml::parse(wrap.as_bytes()).ok()?; - let els: Vec<_> = doc.root.elements().collect(); - (!els.is_empty() - && els.len() <= allowed.len() - && doc.root.children.len() == els.len() - && els.iter().all(|e| e.prefix() == "a" && allowed.contains(&e.local()) && !crate::read::has_rel_refs(e))) - .then_some(raw) -} - -pub fn body_pr(w: &mut W, b: &BodyProps) { - let a = A::new() - .o("rot", b.rot.map(|r| (r * 60_000.0).round().clamp(-21_600_000.0, 21_600_000.0) as i64)) - .o("vert", b.vert.map(|v| v.xml())) - .o("wrap", b.wrap.map(|v| if v { "square" } else { "none" })) - .o("lIns", b.inset_l.map(emu)) - .o("tIns", b.inset_t.map(emu)) - .o("rIns", b.inset_r.map(emu)) - .o("bIns", b.inset_b.map(emu)) - .o("numCol", b.columns.map(|c| c.clamp(1, 16))) - .o("spcCol", b.col_spacing.map(|v| emu(v).max(0))) - .b("rtlCol", b.rtl_col) - .o("anchor", b.anchor.map(|a| a.xml())) - .b("anchorCtr", b.anchor_ctr) - .b("upright", b.upright) - .b("spcFirstLastPara", b.space_first_last) - .b("compatLnSpc", b.compat_ln_spc) - .o("vertOverflow", b.vert_overflow.map(|v| v.xml())) - .o("horzOverflow", deckcraft_model::text::TextOverflow::horz_xml(b.horz_overflow)); - let warp = b.warp.as_deref().filter(|s| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric())); - let raw3d = b.raw3d.as_deref().and_then(|s| valid_raw3d(s, &["scene3d", "sp3d", "flatTx"])); - if warp.is_none() && b.autofit.is_none() && raw3d.is_none() { - w.empty("a:bodyPr", a); - return; - } - w.open("a:bodyPr", a); - if let Some(p) = warp { - w.open("a:prstTxWarp", A::new().a("prst", p)); - let adj: Vec<(usize, i64)> = - b.warp_adj.iter().take(8).enumerate().filter(|(_, v)| v.is_finite()).map(|(i, v)| (i, v.round().clamp(-2.0e9, 2.0e9) as i64)).collect(); - if adj.is_empty() { - w.empty0("a:avLst"); - } else { - let single = deckcraft_geom::warp::adjust_count(p) <= 1 && b.warp_adj.len() == 1; - w.open0("a:avLst"); - for (i, v) in adj { - let n = if single { "adj".to_string() } else { format!("adj{}", i + 1) }; - w.empty("a:gd", A::new().a("name", n).a("fmla", format!("val {v}"))); - } - w.close("a:avLst"); - } - w.close("a:prstTxWarp"); - } - match b.autofit { - Some(AutoFit::None) => w.empty0("a:noAutofit"), - Some(AutoFit::Shape) => w.empty0("a:spAutoFit"), - Some(AutoFit::Shrink { font_scale, line_reduction }) => { - // A scale the model holds is written, 100 % included: reopening then keeps the same - // "draw the saved scale" state instead of becoming a bare `` (#724). - let fs = font_scale.map(|s| pct(s.clamp(0.01, 1.0))); - let lr = pct(line_reduction.clamp(0.0, 1.0)); - w.empty("a:normAutofit", A::new().o("fontScale", fs).o("lnSpcReduction", (lr != 0).then_some(lr))); - } - None => {} - } - if let Some(raw) = raw3d { - w.raw(raw); - } - w.close("a:bodyPr"); -} - -fn spacing(w: &mut W, tag: &str, s: &Spacing) { - w.open0(tag); - match s { - Spacing::Pct(v) => w.val("a:spcPct", pct(v.clamp(0.0, 132.0))), - Spacing::Pts(v) => w.val("a:spcPts", (v.clamp(0.0, 1584.0) * 100.0).round() as i64), - } - w.close(tag); -} - -pub fn is_default_ppr(p: &ParaProps) -> bool { - *p == ParaProps::default() -} - -/// `a:pPr` / `a:lvlNpPr`. -pub fn ppr(w: &mut W, x: &mut Exp, o: &mut Out, tag: &str, level: Option, p: &ParaProps, def: Option<&RunProps>) { - let a = A::new() - .o("marL", p.margin_left.map(|v| emu(v.clamp(0.0, 4032.0)))) - .o("marR", p.margin_right.map(|v| emu(v.clamp(0.0, 4032.0)))) - .o("lvl", level.filter(|l| *l > 0).map(|l| l.min(8))) - .o("indent", p.indent.map(|v| emu(v.clamp(-4032.0, 4032.0)))) - .o("algn", p.align.map(|a| a.xml())) - .o("defTabSz", p.default_tab.map(|v| emu(v).max(0))) - .b("rtl", p.rtl) - .b("eaLnBrk", p.east_asian_line_break) - .b("latinLnBrk", p.latin_line_break) - .b("hangingPunct", p.hanging_punct) - .o("fontAlgn", p.font_align.as_deref().filter(|f| matches!(*f, "auto" | "t" | "ctr" | "base" | "b"))); - let has_kids = p.line_spacing.is_some() - || p.space_before.is_some() - || p.space_after.is_some() - || p.bullet.is_some() - || p.bullet_font.is_some() - || p.bullet_font_follow_text.is_some() - || p.bullet_color.is_some() - || p.bullet_color_follow_text.is_some() - || p.bullet_size.is_some() - || p.bullet_size_points.is_some() - || p.bullet_size_follow_text.is_some() - || p.tabs.is_some() - || def.is_some(); - if !has_kids { - w.empty(tag, a); - return; - } - w.open(tag, a); - if let Some(s) = &p.line_spacing { - spacing(w, "a:lnSpc", s); - } - if let Some(s) = &p.space_before { - spacing(w, "a:spcBef", s); - } - if let Some(s) = &p.space_after { - spacing(w, "a:spcAft", s); - } - if p.bullet_color.is_none() && p.bullet_color_follow_text == Some(true) { - w.empty0("a:buClrTx"); - } else if let Some(c) = &p.bullet_color { - w.open0("a:buClr"); - color(w, c); - w.close("a:buClr"); - } - if p.bullet_size.is_none() && p.bullet_size_points.is_none() && p.bullet_size_follow_text == Some(true) { - w.empty0("a:buSzTx"); - } else if let Some(s) = p.bullet_size_points.filter(|s| s.is_finite() && (1.0..=4000.0).contains(s)) { - w.val("a:buSzPts", ((s * 100.0).round() as u32).to_string()); - } else if let Some(s) = p.bullet_size { - w.val("a:buSzPct", pct(s.clamp(0.25, 4.0))); - } - if p.bullet_font.is_none() && p.bullet_font_follow_text == Some(true) { - w.empty0("a:buFontTx"); - } else if let Some(f) = &p.bullet_font { - w.empty("a:buFont", A::new().a("typeface", f)); - } - match &p.bullet { - Some(Bullet::None) => w.empty0("a:buNone"), - Some(Bullet::Char { char }) => w.empty("a:buChar", A::new().a("char", if char.is_empty() { "•" } else { char })), - Some(Bullet::AutoNum { scheme, start_at }) => { - let s = if scheme.is_empty() || !scheme.chars().all(|c| c.is_ascii_alphanumeric()) { "arabicPeriod" } else { scheme }; - w.empty("a:buAutoNum", A::new().a("type", s).o("startAt", (*start_at != 1).then_some((*start_at).clamp(1, 32767)))); - } - Some(Bullet::Picture { media }) => match x.media_rel(o, *media, "image") { - Some(rid) => { - w.open0("a:buBlip"); - let a = if x.media(*media).is_some_and(|m| m.data.is_empty() && m.link.is_some()) { - A::new().a("r:link", &rid) - } else { - A::new().a("r:embed", &rid) - }; - w.empty("a:blip", a); - w.close("a:buBlip"); - } - None => w.empty("a:buChar", A::new().a("char", "•")), - }, - None => {} - } - if let Some(t) = &p.tabs { - w.open0("a:tabLst"); - for tab in t.iter().take(32) { - let al = match tab.align.as_str() { - "ctr" | "r" | "dec" => tab.align.as_str(), - _ => "l", - }; - w.empty("a:tab", A::new().a("pos", emu(tab.pos)).a("algn", al)); - } - w.close("a:tabLst"); - } - if let Some(d) = def { - rpr(w, x, o, "a:defRPr", d); - } - w.close(tag); -} - -fn typeface(w: &mut W, tag: &str, f: &Option) { - if let Some(f) = f { - w.empty(tag, A::new().a("typeface", f)); - } -} - -/// `a:rPr`, `a:defRPr`, `a:endParaRPr`. -pub fn rpr(w: &mut W, x: &mut Exp, o: &mut Out, tag: &str, r: &RunProps) { - let a = A::new() - .o("lang", r.lang.as_deref().filter(|l| !l.is_empty())) - .o("altLang", r.alt_lang.as_deref().filter(|l| !l.is_empty())) - .o("sz", r.size.map(|s| (s.clamp(1.0, 4000.0) * 100.0).round() as i64)) - .b("b", r.bold) - .b("i", r.italic) - .o("u", r.underline.as_deref().filter(|u| !u.is_empty() && u.chars().all(|c| c.is_ascii_alphanumeric()))) - .o( - "strike", - r.strike.map(|s| match s { - Strike::None => "noStrike", - Strike::Single => "sngStrike", - Strike::Double => "dblStrike", - }), - ) - .o("kern", r.kern.map(|k| (k.clamp(0.0, 4000.0) * 100.0).round() as i64)) - .o( - "cap", - r.caps.map(|c| match c { - Caps::None => "none", - Caps::Small => "small", - Caps::All => "all", - }), - ) - .o("spc", r.spacing.map(|s| (s.clamp(-4000.0, 4000.0) * 100.0).round() as i64)) - .o("baseline", r.baseline.map(|b| pct(b.clamp(-10.0, 10.0)))) - .b("noProof", r.no_proof) - .b("normalizeH", r.normalize_height); - let has_fx = r.shadow.is_some() || r.inner_shadow.is_some() || r.glow.is_some() || r.reflection.is_some() || r.soft_edge.is_some(); - let has_kids = r.outline.is_some() - || r.fill.is_some() - || has_fx - || r.highlight.is_some() - || r.underline_color.is_some() - || r.font.is_some() - || r.font_ea.is_some() - || r.font_cs.is_some() - || r.font_sym.is_some() - || r.link.is_some() - || r.hover.is_some(); - if !has_kids { - w.empty(tag, a); - return; - } - w.open(tag, a); - if let Some(l) = &r.outline { - line(w, x, o, "a:ln", l); - } - if let Some(f) = &r.fill { - match f { - Fill::Background => {} - f => fill(w, x, o, f), - } - } - if has_fx { - // Same child order as a shape's effect list: glow, inner shadow, outer shadow, reflection, soft edge. - effects( - w, - &Effects { - outer_shadow: r.shadow.clone(), - inner_shadow: r.inner_shadow.clone(), - glow: r.glow.clone(), - reflection: r.reflection.clone(), - soft_edge: r.soft_edge, - ..Default::default() - }, - ); - } - if let Some(h) = &r.highlight { - w.open0("a:highlight"); - color(w, h); - w.close("a:highlight"); - } - if let Some(c) = &r.underline_color { - w.open0("a:uFill"); - solid(w, c); - w.close("a:uFill"); - } - typeface(w, "a:latin", &r.font); - typeface(w, "a:ea", &r.font_ea); - typeface(w, "a:cs", &r.font_cs); - typeface(w, "a:sym", &r.font_sym); - if let Some(h) = &r.link { - hyperlink(w, x, o, "a:hlinkClick", h); - } - // Schema order: hlinkClick, hlinkMouseOver. - if let Some(h) = &r.hover { - hyperlink(w, x, o, "a:hlinkMouseOver", h); - } - w.close(tag); -} - -/// `a:lstStyle`-like element (`a:lstStyle`, `p:titleStyle`, `p:defaultTextStyle`…). -pub fn list_style(w: &mut W, x: &mut Exp, o: &mut Out, tag: &str, ls: &ListStyle) { - if ls.is_empty() { - w.empty0(tag); - return; - } - w.open0(tag); - for (i, l) in ls.levels.iter().enumerate().take(9) { - if let Some(l) = l { - let t = format!("a:lvl{}pPr", i + 1); - let def = (l.run != RunProps::default()).then_some(&l.run); - ppr(w, x, o, &t, None, &l.para, def); - } - } - w.close(tag); -} - -/// Write `` text body (`p:txBody`, `a:txBody`). `math` selects the OMML form of equations. -pub fn text_body(w: &mut W, x: &mut Exp, o: &mut Out, tag: &str, tb: &TextBody, math: bool) { - w.open0(tag); - body_pr(w, &tb.body); - list_style(w, x, o, "a:lstStyle", &tb.list_style); - if tb.paragraphs.is_empty() { - w.empty0("a:p"); - } - for (pi, p) in tb.paragraphs.iter().enumerate() { - paragraph(w, x, o, p, math, pi); - } - w.close(tag); -} - -fn run_text(w: &mut W, x: &mut Exp, o: &mut Out, text: &str, props: &RunProps) { - // The run's properties are the same for every piece and line break: serialize them once. - let mut rpr_xml: Option = None; - let mut put_rpr = |w: &mut W| match &rpr_xml { - Some(xml) => w.s.push_str(xml), - None => { - let start = w.s.len(); - rpr(w, x, o, "a:rPr", props); - rpr_xml = Some(w.s[start..].to_string()); - } - }; - for (i, piece) in text.split(['\n', '\u{b}']).enumerate() { - if i > 0 { - w.open0("a:br"); - put_rpr(w); - w.close("a:br"); - } - if piece.is_empty() && i > 0 { - continue; - } - w.open0("a:r"); - put_rpr(w); - w.elt("a:t", piece); - w.close("a:r"); - } -} - -pub fn paragraph(w: &mut W, x: &mut Exp, o: &mut Out, p: &Paragraph, math: bool, index: usize) { - w.open0("a:p"); - let def = (p.def_props != RunProps::default()).then_some(&p.def_props); - if p.level > 0 || !is_default_ppr(&p.props) || def.is_some() { - ppr(w, x, o, "a:pPr", Some(p.level), &p.props, def); - } - for (ri, r) in p.runs.iter().enumerate() { - match &r.kind { - RunKind::Text => run_text(w, x, o, &r.text, &r.props), - RunKind::Break => { - w.open0("a:br"); - rpr(w, x, o, "a:rPr", &r.props); - w.close("a:br"); - } - RunKind::Field { field } => { - let id = crate::tables::guid(&format!("{}:{index}:{ri}:{field}", o.name)); - let ty = (!field.is_empty() && field.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')).then_some(field.as_str()); - w.open("a:fld", A::new().a("id", id).o("type", ty)); - rpr(w, x, o, "a:rPr", &r.props); - w.elt("a:t", &r.text); - w.close("a:fld"); - } - RunKind::Math { omml } => { - if math && !omml.is_empty() { - w.open("a14:m", A::new().a("xmlns:a14", crate::opc::NS_A14)); - w.raw(omml); - w.close("a14:m"); - } else { - run_text(w, x, o, &r.text, &r.props); - } - } - } - } - if p.end_props != RunProps::default() { - rpr(w, x, o, "a:endParaRPr", &p.end_props); - } - w.close("a:p"); -} - -pub fn has_math(tb: &TextBody) -> bool { - tb.paragraphs.iter().flat_map(|p| &p.runs).any(|r| matches!(&r.kind, RunKind::Math { omml } if !omml.is_empty())) -} - -#[cfg(test)] -mod tests { - use super::*; - use deckcraft_color::Rgba; - - #[test] - fn unknown_preset_and_system_names_save_as_black_and_window_text() { - let write = |base: ColorBase| { - let mut w = W::frag(); - color(&mut w, &ColorRef { base, mods: vec![] }); - w.s - }; - assert_eq!(write(ColorBase::Preset { name: "notAColor".into() }), r#""#); - assert_eq!(write(ColorBase::Preset { name: "darkBlue".into() }), r#""#); - let last = Rgba::rgb(0x12, 0x34, 0x56); - assert_eq!(write(ColorBase::System { name: "notAColor".into(), last }), r#""#); - assert_eq!(write(ColorBase::System { name: "3dLight".into(), last }), r#""#); - } -} diff --git a/crates/pptx/src/write/shapes.rs b/crates/pptx/src/write/shapes.rs deleted file mode 100644 index a5833c4d1..000000000 --- a/crates/pptx/src/write/shapes.rs +++ /dev/null @@ -1,1070 +0,0 @@ -//! Shape trees: autoshapes, pictures, groups, connectors, tables, charts, media, ink, 3-D models and kept objects. - -use std::collections::{HashMap, HashSet}; - -use deckcraft_geom::Xfrm; -use deckcraft_model::style::Fill; -use deckcraft_model::table::Table; -use deckcraft_model::{Geom, PhType, Shape, ShapeId, ShapeKind, ShapeStyle, walk}; - -use super::dml::{self, emu, emu_pos}; -use super::{Exp, Out}; -use crate::opc::NS_MC; -use crate::xml::{A, W}; - -/// cNvPr ids for one part. -pub struct IdMap { - pub map: HashMap, - next: u32, -} - -impl IdMap { - pub fn build(shapes: &[Shape]) -> Self { - let mut map = HashMap::new(); - let mut used = HashSet::new(); - let mut max = 1u32; - walk(shapes, &mut |s, _| { - if s.id.0 >= 2 && s.id.0 < i32::MAX as u32 { - max = max.max(s.id.0); - } - }); - let mut next = max; - walk(shapes, &mut |s, _| { - let id = if s.id.0 >= 2 && s.id.0 < i32::MAX as u32 && !used.contains(&s.id.0) { - s.id.0 - } else { - next = next.saturating_add(1); - next - }; - used.insert(id); - map.entry(s.id).or_insert(id); - }); - IdMap { map, next } - } - pub fn get(&self, id: ShapeId) -> Option { - self.map.get(&id).copied() - } - pub fn fresh(&mut self) -> u32 { - self.next = self.next.saturating_add(1); - self.next - } -} - -pub struct Ctx<'a> { - pub ids: &'a mut IdMap, - /// The shape id written for the shape currently being written (duplicate model ids get fresh ones). - pub written: HashSet, -} - -impl Ctx<'_> { - fn id_for(&mut self, s: &Shape) -> u32 { - let id = self.ids.get(s.id).unwrap_or(0); - if id >= 2 && self.written.insert(id) { - return id; - } - let f = self.ids.fresh(); - self.written.insert(f); - f - } -} - -fn preset_name(name: &str) -> &str { - if name == "textBox" || name.is_empty() || !name.chars().all(|c| c.is_ascii_alphanumeric()) { "rect" } else { name } -} - -/// Non-adjust shape guides some presets carry in their `avLst` (ECMA-376 default values). -fn extra_guides(name: &str) -> &'static [(&'static str, i64)] { - match name { - "star5" | "pentagon" => &[("hf", 105_146), ("vf", 110_557)], - "star7" | "heptagon" => &[("hf", 102_572), ("vf", 105_210)], - "star6" => &[("hf", 115_470)], - "star10" => &[("hf", 105_146)], - "hexagon" => &[("vf", 115_470)], - "decagon" => &[("vf", 105_146)], - _ => &[], - } -} - -pub fn geometry(w: &mut W, g: &Geom) { - match g { - Geom::Preset { name, adj } => { - let name = preset_name(name); - w.open("a:prstGeom", A::new().a("prst", name)); - if adj.is_empty() { - w.empty0("a:avLst"); - } else { - // PowerPoint wants the complete guide list once any is given. - let defaults = deckcraft_geom::preset::adjust_defaults(name); - let mut vals: Vec = adj.iter().take(16).copied().collect(); - while vals.len() < defaults.len() { - vals.push(defaults.get(vals.len()).copied().unwrap_or(0.0)); - } - w.open0("a:avLst"); - // A lone guide is `adj`, except in these presets, which name it `adj1` (as PowerPoint - // writes them); PowerPoint won't open a file that renames it (#214). - let adj1 = matches!(name, "bentConnector3" | "curvedConnector3" | "frame" | "mathPlus" | "mathMinus" | "mathMultiply"); - let single = !adj1 && if defaults.is_empty() { vals.len() == 1 } else { defaults.len() == 1 }; - for (i, v) in vals.iter().enumerate() { - let n = if single && i == 0 { "adj".to_string() } else { format!("adj{}", i + 1) }; - // A near-zero-width connector can need a large ratio for an ordinary-size bend. - // Keep guide literals bounded to the signed integer serialization domain. - let v = if v.is_finite() { v.round().clamp(i64::MIN as f64, i64::MAX as f64) as i64 } else { 0 }; - w.empty("a:gd", A::new().a("name", n).a("fmla", format!("val {v}"))); - } - for (n, v) in extra_guides(name) { - w.empty("a:gd", A::new().a("name", *n).a("fmla", format!("val {v}"))); - } - w.close("a:avLst"); - } - w.close("a:prstGeom"); - } - Geom::Custom { paths } => { - if paths.is_empty() { - w.open("a:prstGeom", A::new().a("prst", "rect")); - w.empty0("a:avLst"); - w.close("a:prstGeom"); - } else { - crate::custgeom::write_cust_geom(w, paths); - } - } - } -} - -fn cnvpr(w: &mut W, x: &mut Exp, o: &mut Out, id: u32, s: &Shape) { - let a = A::new() - .a("id", id) - .a("name", if s.name.is_empty() { format!("Shape {id}") } else { s.name.clone() }) - .o("descr", (!s.descr.is_empty()).then_some(s.descr.as_str())) - .t("hidden", s.hidden) - .o("title", (!s.title.is_empty()).then_some(s.title.as_str())); - if s.click.is_none() && s.hover.is_none() && !s.decorative { - w.empty("p:cNvPr", a); - return; - } - w.open("p:cNvPr", a); - if let Some(h) = &s.click { - dml::hyperlink(w, x, o, "a:hlinkClick", h); - } - if let Some(h) = &s.hover { - dml::hyperlink(w, x, o, "a:hlinkHover", h); - } - if s.decorative { - w.open0("a:extLst"); - w.open("a:ext", A::new().a("uri", "{C183D7F6-B498-43B3-948B-1728B52AA6E4}")); - w.empty("adec:decorative", A::new().a("xmlns:adec", "http://schemas.microsoft.com/office/drawing/2017/decorative").a("val", "1")); - w.close("a:ext"); - w.close("a:extLst"); - } - w.close("p:cNvPr"); -} - -fn nv_pr(w: &mut W, x: &mut Exp, o: &mut Out, s: &Shape) { - if s.ph.is_none() && s.tags.is_empty() { - w.empty0("p:nvPr"); - return; - } - w.open0("p:nvPr"); - if let Some(ph) = &s.ph { - let ty = match ph.kind { - PhType::Obj => None, - k => Some(k.xml()), - }; - let sz = ph.size.as_deref().filter(|z| matches!(*z, "full" | "half" | "quarter")); - w.empty( - "p:ph", - A::new() - .o("type", ty) - .o("orient", ph.vertical.then_some("vert")) - .o("sz", sz) - .o("idx", (ph.idx != 0).then_some(ph.idx)) - .t("hasCustomPrompt", ph.has_custom_prompt), - ); - } - super::cust_data(w, x, o, &s.tags); - w.close("p:nvPr"); -} - -/// Locking attributes. Lock writes the full set PowerPoint writes for the element's kind (and -/// reads back as locked): see `read::shapes::is_locked`. -fn locks(w: &mut W, tag: &str, s: &Shape, extra: A) { - let a = extra.t("noGrp", s.ph.is_some() || s.locked); - let a = match tag { - "a:grpSpLocks" => a.t("noUngrp", s.locked).t("noRot", s.locked).t("noMove", s.locked).t("noResize", s.locked), - _ => { - let a = a - .t("noRot", s.locked) - .t("noMove", s.locked) - .t("noResize", s.locked) - .t("noEditPoints", s.locked) - .t("noAdjustHandles", s.locked) - .t("noChangeArrowheads", s.locked) - .t("noChangeShapeType", s.locked); - if tag == "a:picLocks" { a.t("noCrop", s.locked) } else { a } - } - }; - if a.v.is_empty() { - return; - } - w.empty(tag, a); -} - -fn style(w: &mut W, st: &ShapeStyle) { - style_tag(w, st, "p:style"); -} - -fn style_tag(w: &mut W, st: &ShapeStyle, tag: &str) { - w.open0(tag); - for (tag, (idx, c)) in [("a:lnRef", &st.line_ref), ("a:fillRef", &st.fill_ref), ("a:effectRef", &st.effect_ref)] { - w.open(tag, A::new().a("idx", idx)); - dml::color(w, c); - w.close(tag); - } - let idx = match st.font_ref.0.as_str() { - "major" | "minor" | "none" => st.font_ref.0.as_str(), - _ => "minor", - }; - match &st.font_ref.1 { - Some(c) => { - w.open("a:fontRef", A::new().a("idx", idx)); - dml::color(w, c); - w.close("a:fontRef"); - } - None => w.empty("a:fontRef", A::new().a("idx", idx)), - } - w.close(tag); -} - -/// `p:spPr` contents (also used for pictures and connectors). -fn sp_pr(w: &mut W, x: &mut Exp, o: &mut Out, s: &Shape, geom: bool) { - sp_pr_tag(w, x, o, s, geom, "p:spPr"); -} - -fn sp_pr_tag(w: &mut W, x: &mut Exp, o: &mut Out, s: &Shape, geom: bool, tag: &str) { - w.open0(tag); - if let Some(xf) = &s.xfrm { - dml::xfrm(w, "a:xfrm", xf, None); - } - if geom && (s.xfrm.is_some() || s.ph.is_none() || !matches!(&s.geom, Geom::Preset { name, adj } if name == "rect" && adj.is_empty())) { - geometry(w, &s.geom); - } - if let Some(f) = &s.fill { - dml::fill(w, x, o, f); - } - if let Some(l) = &s.line { - dml::line(w, x, o, "a:ln", l); - } - if let Some(fx) = &s.effects { - dml::effects(w, fx); - if let Some(raw) = &fx.raw3d { - w.raw(raw); - } else if let Some(xml) = fx.bevel.as_deref().and_then(dml::bevel_sp3d) { - w.raw(&xml); - } - } - w.close(tag); -} - -/// Write the children of a shape tree. -pub fn shapes(w: &mut W, x: &mut Exp, o: &mut Out, cx: &mut Ctx, list: &[Shape], depth: usize) { - if depth > 32 { - return; - } - for s in list { - shape(w, x, o, cx, s, depth); - } -} - -pub fn shape(w: &mut W, x: &mut Exp, o: &mut Out, cx: &mut Ctx, s: &Shape, depth: usize) { - match &s.kind { - ShapeKind::Shape => { - if s.text.as_ref().is_some_and(dml::has_math) { - // Equations: OMML for readers that know it, plain text otherwise. - w.open("mc:AlternateContent", A::new().a("xmlns:mc", NS_MC)); - w.open("mc:Choice", A::new().a("xmlns:a14", crate::opc::NS_A14).a("Requires", "a14")); - let id = cx.id_for(s); - sp(w, x, o, id, s, true); - w.close("mc:Choice"); - w.open0("mc:Fallback"); - sp(w, x, o, id, s, false); - w.close("mc:Fallback"); - w.close("mc:AlternateContent"); - } else { - let id = cx.id_for(s); - sp(w, x, o, id, s, false); - } - } - ShapeKind::Picture { fill } => { - let id = cx.id_for(s); - w.open0("p:pic"); - w.open0("p:nvPicPr"); - cnvpr(w, x, o, id, s); - w.open0("p:cNvPicPr"); - locks(w, "a:picLocks", s, A::new().a("noChangeAspect", "1")); - w.close("p:cNvPicPr"); - nv_pr(w, x, o, s); - w.close("p:nvPicPr"); - dml::blip_fill(w, x, o, "p:blipFill", fill); - let mut s2 = s.clone(); - // Group fill is a separate backing behind transparent image pixels. - if matches!(s2.fill, Some(Fill::Picture(_) | Fill::Background)) { - s2.fill = None; - } - sp_pr(w, x, o, &s2, true); - if let Some(st) = &s.style { - style(w, st); - } - w.close("p:pic"); - } - ShapeKind::Group { children, child } if s.diagram.is_some() && depth < 32 => { - if let Some(d) = &s.diagram { - diagram(w, x, o, cx, s, d, children, child); - } - } - ShapeKind::Group { children, child } => { - let id = cx.id_for(s); - w.open0("p:grpSp"); - w.open0("p:nvGrpSpPr"); - cnvpr(w, x, o, id, s); - w.open0("p:cNvGrpSpPr"); - locks(w, "a:grpSpLocks", s, A::new()); - w.close("p:cNvGrpSpPr"); - nv_pr(w, x, o, s); - w.close("p:nvGrpSpPr"); - w.open0("p:grpSpPr"); - let xf = s.xfrm.unwrap_or(*child); - dml::xfrm(w, "a:xfrm", &xf, Some(child)); - if let Some(f) = &s.fill { - dml::fill(w, x, o, f); - } - if let Some(fx) = &s.effects { - if fx.fill_overlay.is_some() - || fx.glow.is_some() - || fx.inner_shadow.is_some() - || fx.outer_shadow.is_some() - || fx.reflection.is_some() - || fx.soft_edge.is_some() - { - dml::effects(w, fx); - } - if let Some(raw) = - fx.raw3d.as_deref().map(|s| s.find(" { - let id = cx.id_for(s); - w.open0("p:cxnSp"); - w.open0("p:nvCxnSpPr"); - cnvpr(w, x, o, id, s); - let st = start.and_then(|(sid, site)| cx.ids.get(sid).map(|i| (i, site))); - let en = end.and_then(|(sid, site)| cx.ids.get(sid).map(|i| (i, site))); - if st.is_none() && en.is_none() && !s.locked { - w.empty0("p:cNvCxnSpPr"); - } else { - w.open0("p:cNvCxnSpPr"); - locks(w, "a:cxnSpLocks", s, A::new()); - if let Some((i, site)) = st { - w.empty("a:stCxn", A::new().a("id", i).a("idx", site)); - } - if let Some((i, site)) = en { - w.empty("a:endCxn", A::new().a("id", i).a("idx", site)); - } - w.close("p:cNvCxnSpPr"); - } - nv_pr(w, x, o, s); - w.close("p:nvCxnSpPr"); - let mut s2 = s.clone(); - if matches!(s2.fill, Some(Fill::Background)) { - s2.fill = None; - } - if s2.geom.preset_name() == Some("rect") { - s2.geom = Geom::preset("line"); - } - sp_pr(w, x, o, &s2, true); - if let Some(st) = &s.style { - style(w, st); - } - w.close("p:cxnSp"); - } - ShapeKind::Table(t) => { - let id = cx.id_for(s); - frame_open(w, x, o, id, s); - w.open("a:graphicData", A::new().a("uri", "http://schemas.openxmlformats.org/drawingml/2006/table")); - table(w, x, o, t); - w.close("a:graphicData"); - frame_close(w); - } - ShapeKind::Chart(c) => { - let id = cx.id_for(s); - // An unchanged Office 2016 chart goes back as itself, with a plain chart of the same - // data for readers without `cx1`, as PowerPoint writes it. - let ex = x.chartex_rel(o, c); - if let Some(exid) = &ex { - w.open("mc:AlternateContent", A::new().a("xmlns:mc", "http://schemas.openxmlformats.org/markup-compatibility/2006")); - w.open("mc:Choice", A::new().a("xmlns:cx1", "http://schemas.microsoft.com/office/drawing/2015/9/8/chartex").a("Requires", "cx1")); - frame_open(w, x, o, id, s); - w.open("a:graphicData", A::new().a("uri", super::chart::NS_CX)); - w.empty("cx:chart", A::new().a("xmlns:cx", super::chart::NS_CX).a("r:id", exid)); - w.close("a:graphicData"); - frame_close(w); - w.close("mc:Choice"); - w.open0("mc:Fallback"); - } - let mut plain = (**c).clone(); - plain.raw = plain.raw.filter(|r| !r.contains(super::chart::NS_CX)); - if ex.is_some() { - // The kept workbook belongs to the `chartEx` part; the fallback has none. - plain.kept = Default::default(); - } - let rid = x.chart_rel(o, &plain); - frame_open(w, x, o, id, s); - w.open("a:graphicData", A::new().a("uri", "http://schemas.openxmlformats.org/drawingml/2006/chart")); - w.empty("c:chart", A::new().a("xmlns:c", crate::opc::NS_C).a("r:id", rid)); - w.close("a:graphicData"); - frame_close(w); - if ex.is_some() { - w.close("mc:Fallback"); - w.close("mc:AlternateContent"); - } - } - ShapeKind::Media(m) => { - let id = cx.id_for(s); - media(w, x, o, id, s, m); - } - ShapeKind::Model3d { media, poster } => write_model(w, x, o, cx, s, *media, *poster), - ShapeKind::Ink { strokes } => { - // Ink becomes a group of freeform lines. - let id = cx.id_for(s); - let xf = s.xfrm.unwrap_or_default(); - w.open0("p:grpSp"); - w.open0("p:nvGrpSpPr"); - cnvpr(w, x, o, id, s); - w.empty0("p:cNvGrpSpPr"); - w.empty0("p:nvPr"); - w.close("p:nvGrpSpPr"); - w.open0("p:grpSpPr"); - dml::xfrm(w, "a:xfrm", &xf, Some(&xf)); - w.close("p:grpSpPr"); - for (i, st) in strokes.iter().enumerate().take(10_000) { - let Some(stroke) = ink_shape(st, i) else { continue }; - let sid = cx.ids.fresh(); - sp(w, x, o, sid, &stroke, false); - } - w.close("p:grpSp"); - } - ShapeKind::Opaque { xml, preview, label, parts } => opaque(w, x, o, cx, s, xml, *preview, label, parts), - } -} - -fn model_rel(x: &mut Exp, o: &mut Out, media: deckcraft_model::MediaId) -> Option { - if x.media(media).is_none_or(|m| m.data.is_empty()) { - return None; - } - x.media_rel(o, media, crate::opc::RT_MODEL3D) -} - -fn write_model_part(w: &mut W, x: &mut Exp, o: &mut Out, id: u32, s: &Shape, rid: &str) { - w.open("p:contentPart", A::new().a("r:id", rid)); - w.open0("p:nvContentPartPr"); - cnvpr(w, x, o, id, s); - w.empty0("p:cNvContentPartPr"); - w.empty0("p:nvPr"); - w.close("p:nvContentPartPr"); - if let Some(xf) = &s.xfrm { - dml::xfrm(w, "p:xfrm", xf, None); - } - w.close("p:contentPart"); -} - -fn write_model( - w: &mut W, - x: &mut Exp, - o: &mut Out, - cx: &mut Ctx, - s: &Shape, - media: deckcraft_model::MediaId, - poster: Option, -) { - let Some(rid) = model_rel(x, o, media) else { - log::warn!("pptx: 3-D model '{}' has no embedded part", s.name); - return; - }; - let id = cx.id_for(s); - let poster = poster.filter(|p| x.media(*p).is_some_and(|m| !m.data.is_empty())); - let Some(poster) = poster else { - write_model_part(w, x, o, id, s, &rid); - return; - }; - // Older readers draw the fallback picture; readers that know `am3d` use the model. - w.open("mc:AlternateContent", A::new().a("xmlns:mc", NS_MC)); - w.open("mc:Choice", A::new().a("xmlns:am3d", "http://schemas.microsoft.com/office/drawing/2017/model3d").a("Requires", "am3d")); - write_model_part(w, x, o, id, s, &rid); - w.close("mc:Choice"); - w.open0("mc:Fallback"); - let pic = Shape { - id: ShapeId(0), - name: s.name.clone(), - xfrm: s.xfrm, - kind: ShapeKind::Picture { fill: deckcraft_model::style::PictureFill { media: poster, ..Default::default() } }, - ..Default::default() - }; - let pid = cx.ids.fresh(); - shape_with_id(w, x, o, cx, &pic, pid); - w.close("mc:Fallback"); - w.close("mc:AlternateContent"); -} - -/// A SmartArt graphic: a graphic frame naming its data, layout, quick style and colour parts, -/// with the group's shapes as the cached drawing PowerPoint shows until it lays the diagram out. -#[allow(clippy::too_many_arguments)] -fn diagram(w: &mut W, x: &mut Exp, o: &mut Out, cx: &mut Ctx, s: &Shape, d: &deckcraft_model::Diagram, children: &[Shape], child: &Xfrm) { - use crate::dgm; - let id = cx.id_for(s); - let n = x.next_diagram(); - let frame = s.xfrm.unwrap_or(*child); - let name = |kind: &str| format!("ppt/diagrams/{kind}{n}.xml"); - // The drawing: the group's shapes in the frame's own coordinates. - let dname = name("drawing"); - let mut dout = Out::new(&dname); - let mut dw = W::new(); - dw.open( - "dsp:drawing", - A::new().a("xmlns:dgm", dgm::NS_DGM).a("xmlns:dsp", dgm::NS_DSP).a("xmlns:a", crate::opc::NS_A).a("xmlns:r", crate::opc::NS_R), - ); - dw.open0("dsp:spTree"); - dw.open0("dsp:nvGrpSpPr"); - dw.empty("dsp:cNvPr", A::new().a("id", 0).a("name", "")); - dw.empty0("dsp:cNvGrpSpPr"); - dw.close("dsp:nvGrpSpPr"); - dw.empty0("dsp:grpSpPr"); - let (sx, sy) = (frame.w / child.w.max(1e-6), frame.h / child.h.max(1e-6)); - let mut k = 0; - let mut flat = vec![]; - walk(children, &mut |c, _| match &c.kind { - ShapeKind::Shape => flat.push(c.clone()), - ShapeKind::Connector { .. } => { - let mut sc = c.clone(); - if sc.geom.preset_name() == Some("rect") { - sc.geom = Geom::preset("line"); - } - flat.push(sc); - } - ShapeKind::Picture { fill } => { - let mut sc = c.clone(); - sc.kind = ShapeKind::Shape; - sc.fill = Some(deckcraft_model::style::Fill::Picture(fill.clone())); - flat.push(sc); - } - _ => {} - }); - for mut c in flat.into_iter().take(10_000) { - if let Some(xf) = &mut c.xfrm { - *xf = Xfrm { x: (xf.x - child.x) * sx, y: (xf.y - child.y) * sy, w: xf.w * sx, h: xf.h * sy, ..*xf }; - } - k += 1; - dw.open("dsp:sp", A::new().a("modelId", format!("{{{:08X}-5D1A-4C0A-9E5B-{k:012X}}}", s.id.0))); - dw.open0("dsp:nvSpPr"); - dw.empty("dsp:cNvPr", A::new().a("id", 0).a("name", "")); - dw.empty0("dsp:cNvSpPr"); - dw.close("dsp:nvSpPr"); - sp_pr_tag(&mut dw, x, &mut dout, &c, true, "dsp:spPr"); - if let Some(st) = &c.style { - style_tag(&mut dw, st, "dsp:style"); - } - if let Some(tb) = &c.text { - dml::text_body(&mut dw, x, &mut dout, "dsp:txBody", tb, false); - } - dw.close("dsp:sp"); - } - dw.close("dsp:spTree"); - dw.close("dsp:drawing"); - x.pkg.xml_part(&dname, dgm::CT_DRAWING, dw.finish()); - x.pkg.rels(&dname, &dout.rels); - let rel = |o: &mut Out, kind: &str, part: &str| o.rels.add_new(kind, &crate::opc::relative(&o.name, part), false); - let drawing_rel = rel(o, dgm::RT_DRAWING, &dname); - let data = name("data"); - // Node pictures: on the data model's presentation points, through the data part's rels. - let mut mout = Out::new(&data); - let pics: Vec<(usize, String)> = - d.nodes.iter().enumerate().filter_map(|(k, n)| n.picture.and_then(|m| x.media_rel(&mut mout, m, "image")).map(|r| (k, r))).collect(); - x.pkg.xml_part(&data, dgm::CT_DATA, dgm::data_xml(d, s.id.0, &drawing_rel, &pics)); - x.pkg.rels(&data, &mout.rels); - let dm = rel(o, "diagramData", &data); - let layout = name("layout"); - let lo_xml = d.layout_xml.clone().map(String::into_bytes).unwrap_or_else(|| dgm::layout_xml(&d.kind)); - x.pkg.xml_part(&layout, dgm::CT_LAYOUT, lo_xml); - let lo = rel(o, "diagramLayout", &layout); - let style = name("quickStyle"); - x.pkg.xml_part(&style, dgm::CT_STYLE, d.style_xml.clone().map(String::into_bytes).unwrap_or_else(|| dgm::style_xml(&d.style))); - let qs = rel(o, "diagramQuickStyle", &style); - let colors = name("colors"); - x.pkg.xml_part(&colors, dgm::CT_COLORS, d.colors_xml.clone().map(String::into_bytes).unwrap_or_else(|| dgm::colors_xml(&d.colors))); - let cs = rel(o, "diagramColors", &colors); - let mut fs = s.clone(); - fs.xfrm = Some(frame); - frame_open(w, x, o, id, &fs); - w.open("a:graphicData", A::new().a("uri", "http://schemas.openxmlformats.org/drawingml/2006/diagram")); - w.empty("dgm:relIds", A::new().a("xmlns:dgm", dgm::NS_DGM).a("r:dm", dm).a("r:lo", lo).a("r:qs", qs).a("r:cs", cs)); - w.close("a:graphicData"); - frame_close(w); -} - -fn ink_shape(st: &deckcraft_model::InkStroke, i: usize) -> Option { - let pts: Vec<(f64, f64)> = st.points.iter().filter(|p| p.0.is_finite() && p.1.is_finite()).map(|p| (p.0, p.1)).collect(); - let (x0, y0) = pts.iter().fold((f64::MAX, f64::MAX), |a, p| (a.0.min(p.0), a.1.min(p.1))); - let (x1, y1) = pts.iter().fold((f64::MIN, f64::MIN), |a, p| (a.0.max(p.0), a.1.max(p.1))); - if pts.len() < 2 { - return None; - } - let (w, h) = ((x1 - x0).max(1.0), (y1 - y0).max(1.0)); - // PPTX keeps one line width. A pressured stroke exports at its mean sample width; - // a legacy flat `0.5` stroke stays at the pen width. - let legacy = deckcraft_model::ink_pressure_is_legacy(&st.points); - let width = if legacy { - st.width - } else { - let n = st.points.len().max(1) as f64; - st.points.iter().map(|p| deckcraft_model::ink_sample_width(st.width, p.2, false)).sum::() / n - }; - let mut d = String::new(); - for (k, (px, py)) in pts.iter().enumerate() { - d.push_str(if k == 0 { "M " } else { "L " }); - d.push_str(&format!("{:.2} {:.2} ", px - x0, py - y0)); - } - let mut c = deckcraft_model::style::ColorRef::rgb(st.color.with_alpha(255)); - if st.highlighter { - c = c.with(deckcraft_color::ColorTransform::Alpha(50_000)); - } - Some(Shape { - id: ShapeId(0), - name: format!("Ink {}", i + 1), - xfrm: Some(Xfrm::new(x0, y0, w, h)), - geom: Geom::Custom { paths: vec![deckcraft_model::CustomPath { w, h, d, fill: deckcraft_geom::preset::FillMode::None, stroke: true }] }, - fill: Some(Fill::None), - line: Some(deckcraft_model::Line { - cap: Some(deckcraft_model::style::LineCap::Round), - join: Some(deckcraft_model::style::LineJoin::Round), - ..deckcraft_model::Line::solid(c, width.max(0.25)) - }), - ..Default::default() - }) -} - -fn sp(w: &mut W, x: &mut Exp, o: &mut Out, id: u32, s: &Shape, math: bool) { - w.open("p:sp", A::new().t("useBgFill", matches!(s.fill, Some(Fill::Background)))); - w.open0("p:nvSpPr"); - cnvpr(w, x, o, id, s); - let mut cnv = A::new(); - if s.text_box { - cnv = cnv.a("txBox", "1"); - } - let lock = s.ph.is_some() || s.locked; - if lock { - w.open("p:cNvSpPr", cnv); - locks(w, "a:spLocks", s, A::new()); - w.close("p:cNvSpPr"); - } else { - w.empty("p:cNvSpPr", cnv); - } - nv_pr(w, x, o, s); - w.close("p:nvSpPr"); - let tmp; - let sref = if matches!(s.fill, Some(Fill::Background)) { - let mut c = s.clone(); - c.fill = None; - tmp = c; - &tmp - } else { - s - }; - sp_pr(w, x, o, sref, true); - if let Some(st) = &s.style { - style(w, st); - } - if let Some(tb) = &s.text { - // A shape's text without its own anchor sits in the middle in the model; a file without - // one would put it at the top, so say so. - if s.ph.is_none() && !s.text_box && tb.body.anchor.is_none() { - let mut tb = tb.clone(); - tb.body.anchor = Some(deckcraft_model::text::Anchor::Middle); - dml::text_body(w, x, o, "p:txBody", &tb, math); - } else { - dml::text_body(w, x, o, "p:txBody", tb, math); - } - } - w.close("p:sp"); -} - -fn frame_open(w: &mut W, x: &mut Exp, o: &mut Out, id: u32, s: &Shape) { - w.open0("p:graphicFrame"); - w.open0("p:nvGraphicFramePr"); - cnvpr(w, x, o, id, s); - w.open0("p:cNvGraphicFramePr"); - w.empty("a:graphicFrameLocks", A::new().a("noGrp", "1").t("noDrilldown", s.locked).t("noMove", s.locked).t("noResize", s.locked)); - w.close("p:cNvGraphicFramePr"); - nv_pr(w, x, o, s); - w.close("p:nvGraphicFramePr"); - let xf = s.xfrm.unwrap_or_default(); - let mut xf0 = xf; - xf0.rot = 0.0; - xf0.flip_h = false; - xf0.flip_v = false; - dml::xfrm(w, "p:xfrm", &xf0, None); - w.open0("a:graphic"); -} - -fn frame_close(w: &mut W) { - w.close("a:graphic"); - w.close("p:graphicFrame"); -} - -fn table(w: &mut W, x: &mut Exp, o: &mut Out, t: &Table) { - x.table_over_cap |= t.over_cap(); - let t = t.normalized(); - w.open0("a:tbl"); - let (guid, _) = crate::tables::guid_for_style(&t.style); - if x.table_style_set.insert(t.style.clone()) { - x.table_styles.push(t.style.clone()); - } - w.open( - "a:tblPr", - A::new() - .t("firstRow", t.first_row) - .t("firstCol", t.first_col) - .t("lastRow", t.last_row) - .t("lastCol", t.last_col) - .t("bandRow", t.band_row) - .t("bandCol", t.band_col) - .b("rtl", t.rtl), - ); - if let Some(f) = &t.background { - dml::fill(w, x, o, f); - } - w.elt("a:tableStyleId", &guid); - w.close("a:tblPr"); - w.open0("a:tblGrid"); - for c in &t.cols { - w.empty("a:gridCol", A::new().a("w", emu_pos(*c))); - } - w.close("a:tblGrid"); - for row in &t.rows { - w.open("a:tr", A::new().a("h", emu_pos(row.height))); - for c in &row.cells { - w.open( - "a:tc", - A::new() - .o("gridSpan", (c.grid_span > 1).then_some(c.grid_span)) - .o("rowSpan", (c.row_span > 1).then_some(c.row_span)) - .t("hMerge", c.h_merge) - .t("vMerge", c.v_merge), - ); - dml::text_body(w, x, o, "a:txBody", &c.text, false); - let mut a = A::new(); - if let Some(m) = c.margins { - a = a.a("marL", emu(m[0])).a("marR", emu(m[1])).a("marT", emu(m[2])).a("marB", emu(m[3])); - } - a = a.o("vert", c.vertical.map(|v| v.xml())).o( - "anchor", - c.anchor.map(|a| match a { - deckcraft_model::text::Anchor::Justified | deckcraft_model::text::Anchor::Distributed => "t", - other => other.xml(), - }), - ); - a = a.b("anchorCtr", c.anchor_ctr); - a = a.o("horzOverflow", deckcraft_model::text::TextOverflow::horz_xml(c.horz_overflow)); - w.open("a:tcPr", a); - for (tag, l) in [ - ("a:lnL", &c.borders[0]), - ("a:lnR", &c.borders[1]), - ("a:lnT", &c.borders[2]), - ("a:lnB", &c.borders[3]), - ("a:lnTlToBr", &c.diag_down), - ("a:lnBlToTr", &c.diag_up), - ] { - if let Some(l) = l { - dml::line(w, x, o, tag, l); - } - } - if let Some(f) = &c.fill { - match f { - Fill::Background => {} - f => dml::fill(w, x, o, f), - } - } - w.close("a:tcPr"); - w.close("a:tc"); - } - w.close("a:tr"); - } - w.close("a:tbl"); -} - -fn media(w: &mut W, x: &mut Exp, o: &mut Out, id: u32, s: &Shape, m: &deckcraft_model::MediaClip) { - let kind = if m.video { "video" } else { "audio" }; - let link = x.media_rel(o, m.media, kind); - let embed = x.media_rel_new(o, m.media, crate::opc::RT_MEDIA); - w.open0("p:pic"); - w.open0("p:nvPicPr"); - let mut s2 = s.clone(); - if s2.click.is_none() { - s2.click = Some(deckcraft_model::text::Hyperlink { - action: deckcraft_model::text::Action::PlayMedia, - tooltip: String::new(), - highlight_click: false, - sound: None, - stop_sound: false, - zoom_return: None, - }); - } - cnvpr(w, x, o, id, &s2); - w.open0("p:cNvPicPr"); - w.empty("a:picLocks", A::new().a("noChangeAspect", "1")); - w.close("p:cNvPicPr"); - w.open0("p:nvPr"); - if let Some(ph) = &s.ph { - let _ = ph; - } - let tag = if m.video { "a:videoFile" } else { "a:audioFile" }; - if let Some(l) = &link { - w.empty(tag, A::new().a("r:link", l)); - } - if let Some(e) = &embed { - w.open0("p:extLst"); - w.open("p:ext", A::new().a("uri", "{DAA4B4D4-6D71-4841-9C94-3DE7FCFB9230}")); - w.open("p14:media", A::new().a("xmlns:p14", crate::opc::NS_P14).a("r:embed", e)); - if m.trim_start_ms > 0 || m.trim_end_ms > 0 { - w.empty( - "p14:trim", - A::new().o("st", (m.trim_start_ms > 0).then_some(m.trim_start_ms)).o("end", (m.trim_end_ms > 0).then_some(m.trim_end_ms)), - ); - } - if m.fade_in_ms > 0 || m.fade_out_ms > 0 { - w.empty("p14:fade", A::new().o("in", (m.fade_in_ms > 0).then_some(m.fade_in_ms)).o("out", (m.fade_out_ms > 0).then_some(m.fade_out_ms))); - } - if !m.bookmarks.is_empty() { - w.open0("p14:bmkLst"); - for (n, t) in m.bookmarks.iter().take(1000) { - w.empty("p14:bmk", A::new().a("name", n).a("time", t)); - } - w.close("p14:bmkLst"); - } - w.close("p14:media"); - w.close("p:ext"); - w.close("p:extLst"); - } - w.close("p:nvPr"); - w.close("p:nvPicPr"); - let poster = deckcraft_model::style::PictureFill { media: m.poster.unwrap_or_default(), crop: m.crop, ..Default::default() }; - dml::blip_fill(w, x, o, "p:blipFill", &poster); - let mut s3 = s.clone(); - s3.fill = None; - sp_pr(w, x, o, &s3, true); - w.close("p:pic"); -} - -#[allow(clippy::too_many_arguments)] -fn opaque( - w: &mut W, - x: &mut Exp, - o: &mut Out, - cx: &mut Ctx, - s: &Shape, - xml: &str, - preview: Option, - label: &str, - parts: &[(String, String, deckcraft_model::MediaId)], -) { - // Kept XML is written back as it was when every part it references was kept too, with those - // parts re-added under this slide's relationship ids. - if let Ok(doc) = crate::xml::parse(xml.as_bytes()) - && matches!(doc.root.local(), "graphicFrame" | "sp" | "grpSp" | "cxnSp") - { - let mut part_map: std::collections::HashMap<&str, (&str, deckcraft_model::MediaId)> = std::collections::HashMap::new(); - for (id, kind, m) in parts { - part_map.entry(id.as_str()).or_insert((kind.as_str(), *m)); - } - if let Some(ids) = crate::read::rel_refs(&doc.root) - .iter() - .map(|r| { - let (kind, m) = part_map.get(r.as_str())?; - Some((r.clone(), x.media_rel(o, *m, kind)?)) - }) - .collect::>>() - { - let mut root = doc.root; - set_rel_ids(&mut root, &ids, 0); - ole_fallback(&mut root, x, o, preview); - let id = cx.id_for(s); - set_cnvpr_id(&mut root, id); - w.raw(&root.to_xml()); - return; - } - } - log::warn!("pptx: object '{label}' written as its preview picture"); - let id = cx.id_for(s); - let mut p = s.clone(); - if p.name.is_empty() { - p.name = label.to_string(); - } - match preview { - Some(m) if x.media(m).is_some() => { - p.kind = ShapeKind::Picture { fill: deckcraft_model::style::PictureFill { media: m, ..Default::default() } }; - p.ph = None; - shape_with_id(w, x, o, cx, &p, id); - } - _ => { - p.kind = ShapeKind::Shape; - p.ph = None; - p.geom = Geom::preset("rect"); - p.fill = Some(Fill::None); - p.text = None; - sp(w, x, o, id, &p, false); - } - } -} - -fn shape_with_id(w: &mut W, x: &mut Exp, o: &mut Out, cx: &mut Ctx, s: &Shape, id: u32) { - // Pictures only: reuse the given id. - if let ShapeKind::Picture { fill } = &s.kind { - w.open0("p:pic"); - w.open0("p:nvPicPr"); - cnvpr(w, x, o, id, s); - w.open0("p:cNvPicPr"); - w.empty("a:picLocks", A::new().a("noChangeAspect", "1")); - w.close("p:cNvPicPr"); - w.empty0("p:nvPr"); - w.close("p:nvPicPr"); - dml::blip_fill(w, x, o, "p:blipFill", fill); - // As for any picture, a colour or pattern fill shows behind the image (an object's preview - // keeps its fallback picture's fill). - let mut s2 = s.clone(); - if matches!(s2.fill, Some(Fill::Picture(_) | Fill::Background)) { - s2.fill = None; - } - sp_pr(w, x, o, &s2, true); - w.close("p:pic"); - } else { - shape(w, x, o, cx, s, 0); - } -} - -/// A legacy OLE object finds its preview in the slide's VML drawing through `spid`, and PowerPoint -/// won't open the slide without it. We don't write that drawing, so write PowerPoint's own -/// fallback form instead: no `spid`, and the preview as a `p:pic`. -fn ole_fallback(root: &mut crate::xml::El, x: &mut Exp, o: &mut Out, preview: Option) { - let xfrm = root.child("xfrm").map(|t| { - let at = |e: &str, a: &str| t.child(e).and_then(|c| c.attr(a)).unwrap_or("0").to_string(); - (at("off", "x"), at("off", "y"), at("ext", "cx"), at("ext", "cy")) - }); - let Some(ole) = root - .elements_mut() - .find(|e| e.is("graphic")) - .and_then(|g| g.elements_mut().find(|e| e.is("graphicData"))) - .and_then(|d| d.elements_mut().find(|e| e.is("oleObj"))) - else { - return; - }; - if ole.child("pic").is_some() || ole.attr("spid").is_none() { - return; - } - ole.attrs.retain(|(k, _)| k != "spid"); - let rel = preview.and_then(|m| x.media_rel(o, m, "image")).unwrap_or_else(|| x.placeholder_rel(o)); - let (ox, oy, cx, cy) = xfrm.unwrap_or_default(); - let pic = format!( - r#""# - ); - if let Ok(d) = crate::xml::parse(pic.as_bytes()) { - ole.children.push(crate::xml::Node::El(d.root)); - } -} - -fn set_rel_ids(e: &mut crate::xml::El, ids: &std::collections::HashMap, depth: usize) { - if depth > crate::xml::MAX_DEPTH { - return; - } - for (k, v) in &mut e.attrs { - if crate::read::is_rel_attr(k, v) - && let Some(new) = ids.get(v.as_str()) - { - v.clone_from(new); - } - } - for c in e.elements_mut() { - set_rel_ids(c, ids, depth + 1); - } -} - -fn set_cnvpr_id(el: &mut crate::xml::El, id: u32) { - fn rec(e: &mut crate::xml::El, id: u32, depth: usize) -> bool { - if depth > 8 { - return false; - } - if e.is("cNvPr") { - e.set_attr("id", &id.to_string()); - return true; - } - e.elements_mut().any(|c| rec(c, id, depth + 1)) - } - rec(el, id, 0); -} - -/// The fixed group header every shape tree starts with. -pub fn tree_header(w: &mut W) { - w.open0("p:nvGrpSpPr"); - w.empty("p:cNvPr", A::new().a("id", 1).a("name", "")); - w.empty0("p:cNvGrpSpPr"); - w.empty0("p:nvPr"); - w.close("p:nvGrpSpPr"); - w.open0("p:grpSpPr"); - w.open0("a:xfrm"); - w.empty("a:off", A::new().a("x", 0).a("y", 0)); - w.empty("a:ext", A::new().a("cx", 0).a("cy", 0)); - w.empty("a:chOff", A::new().a("x", 0).a("y", 0)); - w.empty("a:chExt", A::new().a("cx", 0).a("cy", 0)); - w.close("a:xfrm"); - w.close("p:grpSpPr"); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn guide_literals_remain_finite_bounded_integers() { - for (guide, expected) in [ - (f64::NAN, 0), - (f64::INFINITY, 0), - (f64::NEG_INFINITY, 0), - (f64::MAX, i64::MAX), - (f64::MIN, i64::MIN), - (12500.6, 12501), - (-12500.6, -12501), - ] { - let mut w = W::frag(); - geometry(&mut w, &Geom::Preset { name: "bentConnector3".into(), adj: vec![guide] }); - assert!(w.s.contains(&format!(r#"fmla="val {expected}""#)), "{}", w.s); - } - } - - /// PowerPoint asks to repair a `star5` whose guide list lacks `hf`/`vf` (found black-box). - #[test] - fn preset_guides_are_complete() { - let mut w = W::frag(); - geometry(&mut w, &Geom::Preset { name: "star5".into(), adj: vec![20000.0] }); - assert_eq!( - w.s, - r#""# - ); - let mut w = W::frag(); - geometry(&mut w, &Geom::Preset { name: "rightArrow".into(), adj: vec![10000.0] }); - assert!(w.s.contains(r#"name="adj1" fmla="val 10000""#) && w.s.contains(r#"name="adj2" fmla="val 50000""#), "{}", w.s); - let mut w = W::frag(); - geometry(&mut w, &Geom::Preset { name: "textBox".into(), adj: vec![] }); - assert_eq!(w.s, r#""#); - } -} diff --git a/crates/pptx/src/write/theme.rs b/crates/pptx/src/write/theme.rs deleted file mode 100644 index 480394201..000000000 --- a/crates/pptx/src/write/theme.rs +++ /dev/null @@ -1,112 +0,0 @@ -//! Theme parts. - -use deckcraft_color::SchemeSlot; -use deckcraft_model::style::{ColorRef, Effects, Fill}; -use deckcraft_model::theme::{FontSet, Theme, default_format}; - -use super::{Exp, Out, dml}; -use crate::opc::{NS_A, NS_R}; -use crate::xml::{A, W}; - -fn font_set(w: &mut W, tag: &str, f: &FontSet) { - w.open0(tag); - w.empty("a:latin", A::new().a("typeface", if f.latin.is_empty() { "Arial" } else { &f.latin })); - w.empty("a:ea", A::new().a("typeface", &f.ea)); - w.empty("a:cs", A::new().a("typeface", &f.cs)); - for sf in &f.scripts { - w.empty("a:font", A::new().a("script", &sf.script).a("typeface", &sf.typeface)); - } - w.close(tag); -} - -fn style_fill(f: &Fill) -> Fill { - match f { - Fill::Background | Fill::Group => Fill::solid(ColorRef::scheme(SchemeSlot::PhClr)), - f => f.clone(), - } -} - -pub fn theme_xml(x: &mut Exp, o: &mut Out, t: &Theme) -> Vec { - let mut w = W::new(); - w.open("a:theme", A::new().a("xmlns:a", NS_A).a("xmlns:r", NS_R).a("name", if t.name.is_empty() { "Theme" } else { &t.name })); - w.open0("a:themeElements"); - w.open("a:clrScheme", A::new().a("name", if t.colors.name.is_empty() { &t.name } else { &t.colors.name })); - for slot in SchemeSlot::THEME { - let tag = format!("a:{}", slot.xml_name()); - w.open0(&tag); - w.val("a:srgbClr", t.colors.get(slot).hex()); - w.close(&tag); - } - w.close("a:clrScheme"); - w.open("a:fontScheme", A::new().a("name", if t.fonts.name.is_empty() { &t.name } else { &t.fonts.name })); - font_set(&mut w, "a:majorFont", &t.fonts.major); - font_set(&mut w, "a:minorFont", &t.fonts.minor); - w.close("a:fontScheme"); - let d = default_format(); - let f = &t.format; - w.open("a:fmtScheme", A::new().a("name", if f.name.is_empty() { &t.name } else { &f.name })); - let three = |v: &[Fill], d: &[Fill]| -> Vec { - let mut out: Vec = v.iter().map(style_fill).collect(); - while out.len() < 3 { - out.push(d.get(out.len()).cloned().unwrap_or(Fill::solid(ColorRef::scheme(SchemeSlot::PhClr)))); - } - out - }; - w.open0("a:fillStyleLst"); - for fl in three(&f.fills, &d.fills) { - dml::fill(&mut w, x, o, &fl); - } - w.close("a:fillStyleLst"); - w.open0("a:lnStyleLst"); - let mut lines = f.lines.clone(); - while lines.len() < 3 { - lines.push(d.lines.get(lines.len()).cloned().unwrap_or_default()); - } - for l in &lines { - let mut l = l.clone(); - if l.fill.is_none() { - l.fill = Some(Fill::solid(ColorRef::scheme(SchemeSlot::PhClr))); - } - if let Some(fl) = &l.fill { - l.fill = Some(style_fill(fl)); - } - dml::line(&mut w, x, o, "a:ln", &l); - } - w.close("a:lnStyleLst"); - w.open0("a:effectStyleLst"); - let mut fx = f.effects.clone(); - while fx.len() < 3 { - fx.push(Effects::default()); - } - for e in &fx { - w.open0("a:effectStyle"); - dml::effects(&mut w, e); - if let Some(raw) = &e.raw3d { - w.raw(raw); - } else if let Some(xml) = e.bevel.as_deref().and_then(dml::bevel_sp3d) { - w.raw(&xml); - } - w.close("a:effectStyle"); - } - w.close("a:effectStyleLst"); - w.open0("a:bgFillStyleLst"); - for fl in three(&f.bg_fills, &d.bg_fills) { - dml::fill(&mut w, x, o, &fl); - } - w.close("a:bgFillStyleLst"); - w.close("a:fmtScheme"); - w.close("a:themeElements"); - match &t.raw_extra { - Some(raw) if raw.contains("objectDefaults") => w.raw(raw), - Some(raw) => { - w.empty0("a:objectDefaults"); - w.raw(raw); - } - None => { - w.empty0("a:objectDefaults"); - w.empty0("a:extraClrSchemeLst"); - } - } - w.close("a:theme"); - w.finish() -} diff --git a/crates/pptx/src/write/timing.rs b/crates/pptx/src/write/timing.rs deleted file mode 100644 index 90daac780..000000000 --- a/crates/pptx/src/write/timing.rs +++ /dev/null @@ -1,830 +0,0 @@ -//! Transitions and the animation timing tree. - -use deckcraft_model::anim::{AnimClass, AnimStart, Animation, BuildRole, TextBuild, Transition, build_filled, paragraph_build_roles}; -use deckcraft_model::{Shape, ShapeId, ShapeKind}; - -use super::shapes::IdMap; -use super::{Exp, Out}; -use crate::opc::{NS_MC, NS_P14, NS_P15, NS_P159}; -use crate::xml::{A, W}; - -pub fn transition(w: &mut W, x: &mut Exp, o: &mut Out, t: &Transition) { - let adv_click = (!t.advance_on_click).then_some("0"); - let adv_tm = t.advance_after_ms.map(|v| v.min(86_400_000)); - let spd = match t.duration_ms { - 0..=600 => "fast", - 601..=900 => "med", - _ => "slow", - }; - let sound = t.sound.and_then(|m| x.media_rel(o, m, "audio").map(|r| (r, x.media(m).map(|i| i.name.clone()).unwrap_or_default()))); - let snd = |w: &mut W| { - if let Some((r, name)) = &sound { - w.open0("p:sndAc"); - w.open("p:stSnd", A::new().t("loop", t.sound_loop)); - let name = if name.is_empty() { "sound.wav" } else { name.as_str() }; - w.empty("p:snd", A::new().a("r:embed", r).a("name", name)); - w.close("p:stSnd"); - w.close("p:sndAc"); - } else if t.stop_sound { - w.open0("p:sndAc"); - w.empty0("p:endSnd"); - w.close("p:sndAc"); - } - }; - let mut effect = W::frag(); - let ns = if t.kind == "none" { Some("p") } else { super::super::maps::transition_to_xml(&mut effect, &t.kind, &t.option) }; - let ns = match ns { - Some(ns) => ns, - None => { - // Unknown kind: write the kept element if there is one, else a fade. - if let Some(raw) = &t.raw - && let Ok(d) = crate::xml::parse(raw.as_bytes()) - && let Some(e) = d.root.elements().find(|e| !matches!(e.local(), "sndAc" | "extLst")) - && !crate::read::has_rel_refs(e) - { - let prefix = e.prefix().to_string(); - let mut ns_decl = d.ns_decls(); - ns_decl.retain(|(k, _)| k == &format!("xmlns:{prefix}")); - let mut e2 = e.clone(); - for (k, v) in ns_decl { - e2.attrs.push((k, v)); - } - effect.raw(&e2.to_xml()); - match prefix.as_str() { - "p14" => "p14", - "p15" => "p15", - "p159" => "p159", - "p" => "p", - _ => { - effect = W::frag(); - effect.empty0("p:fade"); - "p" - } - } - } else { - effect.empty0("p:fade"); - "p" - } - } - }; - let is_none = t.kind == "none"; - let dur = t.duration_ms.min(60_000); - w.open("mc:AlternateContent", A::new().a("xmlns:mc", NS_MC)); - let mut ch = A::new().a("xmlns:p14", NS_P14); - let req = match ns { - "p15" => { - ch = ch.a("xmlns:p15", NS_P15); - "p15" - } - "p159" => { - ch = ch.a("xmlns:p159", NS_P159); - "p159" - } - _ => "p14", - }; - w.open("mc:Choice", ch.a("Requires", req)); - w.open("p:transition", A::new().a("spd", spd).o("p14:dur", (!is_none).then_some(dur)).o("advClick", adv_click).o("advTm", adv_tm)); - if !is_none { - w.raw(&effect.s); - } - snd(w); - w.close("p:transition"); - w.close("mc:Choice"); - w.open0("mc:Fallback"); - w.open("p:transition", A::new().a("spd", spd).o("advClick", adv_click).o("advTm", adv_tm)); - if !is_none { - if ns == "p" { - w.raw(&effect.s); - } else { - w.empty0("p:fade"); - } - } - snd(w); - w.close("p:transition"); - w.close("mc:Fallback"); - w.close("mc:AlternateContent"); -} - -/// One effect to write (an animation, or one paragraph of a by-paragraph build). -struct Eff<'a> { - a: &'a Animation, - spid: u32, - start: AnimStart, - paragraph: Option, - grp: u32, -} - -struct Ids(u32); - -impl Ids { - fn next(&mut self) -> u32 { - self.0 = self.0.saturating_add(1); - self.0 - } -} - -fn tgt(w: &mut W, spid: u32, para: Option) { - w.open0("p:tgtEl"); - match para { - Some(p) => { - w.open("p:spTgt", A::new().a("spid", spid)); - w.open0("p:txEl"); - w.empty("p:pRg", A::new().a("st", p).a("end", p)); - w.close("p:txEl"); - w.close("p:spTgt"); - } - None => w.empty("p:spTgt", A::new().a("spid", spid)), - } - w.close("p:tgtEl"); -} - -fn cbhvr(w: &mut W, ids: &mut Ids, e: &Eff, dur: u32, delay: Option, attrs: &[&str], additive: Option<&str>) { - w.open("p:cBhvr", A::new().o("additive", additive)); - let a = A::new().a("id", ids.next()).a("dur", dur.max(1)).a("fill", "hold"); - match delay { - Some(d) => { - w.open("p:cTn", a); - w.open0("p:stCondLst"); - w.empty("p:cond", A::new().a("delay", d)); - w.close("p:stCondLst"); - w.close("p:cTn"); - } - None => w.empty("p:cTn", a), - } - tgt(w, e.spid, e.paragraph); - if !attrs.is_empty() { - w.open0("p:attrNameLst"); - for n in attrs { - w.elt("p:attrName", n); - } - w.close("p:attrNameLst"); - } - w.close("p:cBhvr"); -} - -fn set_vis(w: &mut W, ids: &mut Ids, e: &Eff, delay: u32, visible: bool) { - w.open0("p:set"); - cbhvr(w, ids, e, 1, Some(delay), &["style.visibility"], None); - w.open0("p:to"); - w.val("p:strVal", if visible { "visible" } else { "hidden" }); - w.close("p:to"); - w.close("p:set"); -} - -fn anim_effect(w: &mut W, ids: &mut Ids, e: &Eff, dur: u32, filter: &str, out: bool) { - w.open("p:animEffect", A::new().a("transition", if out { "out" } else { "in" }).a("filter", filter)); - cbhvr(w, ids, e, dur, None, &[], None); - w.close("p:animEffect"); -} - -fn anim_prop(w: &mut W, ids: &mut Ids, e: &Eff, dur: u32, attr: &str, from: &str, to: &str) { - w.open("p:anim", A::new().a("calcmode", "lin").a("valueType", "num")); - cbhvr(w, ids, e, dur, None, &[attr], Some("base")); - w.open0("p:tavLst"); - for (tm, v) in [(0, from), (100_000, to)] { - w.open("p:tav", A::new().a("tm", tm)); - w.open0("p:val"); - w.val("p:strVal", v); - w.close("p:val"); - w.close("p:tav"); - } - w.close("p:tavLst"); - w.close("p:anim"); -} - -fn filter_for(effect: &str, option: &str) -> &'static str { - match effect { - "wipe" | "wipeOut" => match option { - "t" => "wipe(down)", - "l" => "wipe(right)", - "r" => "wipe(left)", - _ => "wipe(up)", - }, - "split" | "splitOut" => match option { - "horzOut" => "barn(outHorizontal)", - "vertIn" => "barn(inVertical)", - "vertOut" => "barn(outVertical)", - _ => "barn(inHorizontal)", - }, - "randomBars" | "randomBarsOut" => { - if option == "vert" { - "randombar(vertical)" - } else { - "randombar(horizontal)" - } - } - "blinds" | "blindsOut" => { - if option == "vert" { - "blinds(vertical)" - } else { - "blinds(horizontal)" - } - } - "box" | "boxOut" => { - if option == "out" { - "box(out)" - } else { - "box(in)" - } - } - "circle" => { - if option == "out" { - "circle(out)" - } else { - "circle(in)" - } - } - "diamond" | "diamondOut" => { - if option == "out" { - "diamond(out)" - } else { - "diamond(in)" - } - } - "shape" | "shapeOut" => match option { - "circleOut" => "circle(out)", - "boxIn" => "box(in)", - "boxOut" => "box(out)", - "diamondIn" => "diamond(in)", - "diamondOut" => "diamond(out)", - "plusIn" => "plus(in)", - "plusOut" => "plus(out)", - _ => "circle(in)", - }, - "checkerboard" | "checkerboardOut" => { - if option == "down" { - "checkerboard(down)" - } else { - "checkerboard(across)" - } - } - "dissolve" | "dissolveOut" => "dissolve", - "wheel" | "wheelOut" => match option { - "2" => "wheel(2)", - "3" => "wheel(3)", - "4" => "wheel(4)", - "8" => "wheel(8)", - _ => "wheel(1)", - }, - "strips" | "stripsOut" => match option { - "ru" => "strips(upRight)", - "ld" => "strips(downLeft)", - "rd" => "strips(downRight)", - _ => "strips(upLeft)", - }, - "peek" | "peekOut" => match option { - "t" => "slide(fromTop)", - "l" => "slide(fromLeft)", - "r" => "slide(fromRight)", - _ => "slide(fromBottom)", - }, - _ => "fade", - } -} - -fn fly_from(option: &str) -> (&'static str, &'static str) { - let x = if option.contains('l') { - "0-#ppt_w/2" - } else if option.contains('r') { - "1+#ppt_w/2" - } else { - "#ppt_x" - }; - let y = if option.contains('t') { - "0-#ppt_h/2" - } else if option.contains('b') || option.is_empty() { - "1+#ppt_h/2" - } else { - "#ppt_y" - }; - (x, y) -} - -fn behaviors(w: &mut W, x: &mut Exp, ids: &mut Ids, e: &Eff) { - let a = e.a; - let dur = a.duration_ms.clamp(1, 3_600_000); - match a.class { - AnimClass::Entrance => { - set_vis(w, ids, e, 0, true); - match a.effect.as_str() { - "appear" => {} - "fly" => { - let (fx, fy) = fly_from(&a.option); - anim_prop(w, ids, e, dur, "ppt_x", fx, "#ppt_x"); - anim_prop(w, ids, e, dur, "ppt_y", fy, "#ppt_y"); - } - "zoom" | "grow" | "expand" | "spinner" => { - anim_prop(w, ids, e, dur, "ppt_w", "0", "#ppt_w"); - anim_prop(w, ids, e, dur, "ppt_h", "0", "#ppt_h"); - anim_effect(w, ids, e, dur, "fade", false); - } - "float" | "rise" => { - anim_prop(w, ids, e, dur, "ppt_y", if a.option == "d" { "#ppt_y-.1" } else { "#ppt_y+.1" }, "#ppt_y"); - anim_effect(w, ids, e, dur, "fade", false); - } - other => anim_effect(w, ids, e, dur, filter_for(other, &a.option), false), - } - } - AnimClass::Exit => { - match a.effect.as_str() { - "disappear" => {} - "flyOut" => { - let (fx, fy) = fly_from(&a.option); - anim_prop(w, ids, e, dur, "ppt_x", "#ppt_x", fx); - anim_prop(w, ids, e, dur, "ppt_y", "#ppt_y", fy); - } - "floatOut" | "sinkDown" => { - let to = if a.effect == "sinkDown" || a.option == "d" { "#ppt_y+.1" } else { "#ppt_y-.1" }; - anim_prop(w, ids, e, dur, "ppt_y", "#ppt_y", to); - anim_effect(w, ids, e, dur, "fade", true); - } - "zoomOut" | "shrinkTurn" | "spinnerOut" | "contract" => { - anim_prop(w, ids, e, dur, "ppt_w", "#ppt_w", "0"); - anim_prop(w, ids, e, dur, "ppt_h", "#ppt_h", "0"); - anim_effect(w, ids, e, dur, "fade", true); - } - other => anim_effect(w, ids, e, dur, filter_for(other, &a.option), true), - } - set_vis(w, ids, e, if a.effect == "disappear" { 0 } else { dur.saturating_sub(1) }, false); - } - AnimClass::Emphasis => match a.effect.as_str() { - "spin" | "teeter" => { - let deg = a.amount.unwrap_or(if a.effect == "teeter" { 4.0 } else { 360.0 }); - let deg = if a.option == "counterClockwise" { -deg.abs() } else { deg }; - let by = (deg.clamp(-36_000.0, 36_000.0) * 60_000.0).round() as i64; - w.open("p:animRot", A::new().a("by", by)); - cbhvr(w, ids, e, dur, None, &["r"], None); - w.close("p:animRot"); - } - "transparency" => { - w.open0("p:set"); - cbhvr(w, ids, e, dur, None, &["style.opacity"], None); - w.open0("p:to"); - w.val("p:strVal", format!("{:.2}", (1.0 - a.amount.unwrap_or(0.5)).clamp(0.0, 1.0))); - w.close("p:to"); - w.close("p:set"); - } - "colorPulse" => { - // As PowerPoint writes it: text and fill go to the colour and back (autoRev). The behaviour - // duration is the one import reads as the effect duration. - let c = a.color.clone().unwrap_or(deckcraft_model::ColorRef::rgb(deckcraft_color::Rgba::rgb(0xC0, 0x00, 0x00))); - for (attr, child) in [("style.color", true), ("fillcolor", false)] { - w.open("p:animClr", A::new().a("clrSpc", "rgb").a("dir", "cw")); - w.open("p:cBhvr", A::new().o("override", child.then_some("childStyle"))); - w.empty("p:cTn", A::new().a("id", ids.next()).a("dur", dur.max(1)).a("autoRev", "1").a("fill", "remove")); - tgt(w, e.spid, e.paragraph); - w.open0("p:attrNameLst"); - w.elt("p:attrName", attr); - w.close("p:attrNameLst"); - w.close("p:cBhvr"); - w.open0("p:to"); - super::dml::color(w, &c); - w.close("p:to"); - w.close("p:animClr"); - } - } - // As PowerPoint writes them: a relative HSL shift of text, fill and line colour. - "darken" | "desaturate" => { - let (s, l) = if a.effect == "darken" { (0, -25_098) } else { (-70_588, 0) }; - for attr in ["style.color", "fillcolor", "stroke.color"] { - w.open("p:animClr", A::new().a("clrSpc", "hsl").a("dir", "cw")); - cbhvr(w, ids, e, dur, None, &[attr], None); - w.open0("p:by"); - w.empty("p:hsl", A::new().a("h", 0).a("s", s).a("l", l)); - w.close("p:by"); - w.close("p:animClr"); - } - } - "fillColor" | "objectColor" | "fontColor" | "lineColor" | "complementaryColor" | "lighten" => { - let attr = match a.effect.as_str() { - "fontColor" => "style.color", - "lineColor" => "stroke.color", - _ => "fillcolor", - }; - let c = a.color.clone().unwrap_or(deckcraft_model::ColorRef::scheme(deckcraft_color::SchemeSlot::Accent2)); - w.open("p:animClr", A::new().a("clrSpc", "rgb").a("dir", "cw")); - cbhvr(w, ids, e, dur, None, &[attr], None); - w.open0("p:to"); - super::dml::color(w, &c); - w.close("p:to"); - w.close("p:animClr"); - } - _ => { - let s = a.amount.filter(|v| v.is_finite() && *v > 0.0).unwrap_or(if a.effect == "growShrink" { 1.5 } else { 1.1 }); - let (sx, sy) = match a.option.as_str() { - "horz" => (s, 1.0), - "vert" => (1.0, s), - _ => (s, s), - }; - w.open0("p:animScale"); - cbhvr(w, ids, e, dur, None, &[], None); - w.empty( - "p:by", - A::new().a("x", (sx.clamp(0.01, 100.0) * 100_000.0).round() as i64).a("y", (sy.clamp(0.01, 100.0) * 100_000.0).round() as i64), - ); - w.close("p:animScale"); - } - }, - AnimClass::Path => { - let path = a - .path - .clone() - .filter(|p| !p.trim().is_empty() && p.chars().all(|c| c.is_ascii() && c != '"' && c != '<' && c != '&')) - .unwrap_or_else(|| { - match a.option.as_str() { - "up" => "M 0 0 L 0 -0.25 E", - "right" => "M 0 0 L 0.25 0 E", - "left" => "M 0 0 L -0.25 0 E", - _ => "M 0 0 L 0 0.25 E", - } - .to_string() - }); - w.open("p:animMotion", A::new().a("origin", "layout").a("path", path).a("pathEditMode", "relative").a("ptsTypes", "")); - cbhvr(w, ids, e, dur, None, &["ppt_x", "ppt_y"], None); - w.close("p:animMotion"); - } - AnimClass::Media => { - let cmd = match a.effect.as_str() { - "pause" => "togglePause", - "stop" => "stop", - _ => "playFrom(0.0)", - }; - w.open("p:cmd", A::new().a("type", "call").a("cmd", cmd)); - cbhvr(w, ids, e, 1, None, &[], None); - w.close("p:cmd"); - } - } - let _ = x; -} - -fn effect_par(w: &mut W, x: &mut Exp, ids: &mut Ids, e: &Eff, first_in_click: bool) { - let a = e.a; - let node = match e.start { - AnimStart::OnClick => "clickEffect", - AnimStart::WithPrevious => "withEffect", - AnimStart::AfterPrevious => "afterEffect", - }; - let _ = first_in_click; - let preset = crate::maps::preset_for(a); - let sub = if preset == 47 { - 0 - } else { - crate::maps::subtype_from_option(&a.effect, &a.option).or(a.preset_subtype.filter(|_| a.preset_id == Some(preset))).unwrap_or(0) - }; - let repeat = match a.repeat { - u32::MAX => Some("indefinite".to_string()), - 0 | 1 => None, - n => Some((n.min(10_000) * 1000).to_string()), - }; - let accel = (a.smooth_start > 0.0).then(|| (a.smooth_start.clamp(0.0, 1.0) * 100_000.0).round() as i64); - let decel = (a.smooth_end > 0.0).then(|| (a.smooth_end.clamp(0.0, 1.0) * 100_000.0).round() as i64); - // `bounceEnd` is a positive percentage (100000 = 100%), same scale as accel/decel. The model stores 0–1. - let bounce = - (a.bounce_end.is_finite() && a.bounce_end > 0.0).then(|| (a.bounce_end.clamp(0.0, 1.0) * 100_000.0).round() as i64).filter(|n| *n > 0); - w.open0("p:par"); - w.open( - "p:cTn", - A::new() - .a("id", ids.next()) - .a("presetID", preset) - .a("presetClass", a.class.xml()) - .a("presetSubtype", sub) - .o("repeatCount", repeat) - .o("accel", accel) - .o("decel", decel) - .o("bounceEnd", bounce) - .t("autoRev", a.auto_reverse) - .a("fill", if a.rewind { "remove" } else { "hold" }) - .a("grpId", e.grp) - .a("nodeType", node), - ); - w.open0("p:stCondLst"); - w.empty("p:cond", A::new().a("delay", a.delay_ms.min(3_600_000))); - w.close("p:stCondLst"); - w.open0("p:childTnLst"); - behaviors(w, x, ids, e); - w.close("p:childTnLst"); - w.close("p:cTn"); - w.close("p:par"); -} - -fn end_time(e: &Eff) -> u32 { - let rep = match e.a.repeat { - 0 | 1 => 1, - u32::MAX => 1, - n => n.min(100), - }; - e.a.delay_ms.saturating_add(e.a.duration_ms.saturating_mul(rep)).min(3_600_000) -} - -/// click groups → after-groups → effects -type Groups<'a> = Vec<(bool, Vec>>)>; - -fn group<'a>(effects: Vec>) -> Groups<'a> { - let mut clicks: Groups = vec![]; - for e in effects { - match e.start { - AnimStart::OnClick => clicks.push((false, vec![vec![e]])), - AnimStart::WithPrevious => match clicks.last_mut().and_then(|c| c.1.last_mut()) { - Some(g) => g.push(e), - None => clicks.push((true, vec![vec![e]])), - }, - AnimStart::AfterPrevious => match clicks.last_mut() { - Some(c) => c.1.push(vec![e]), - None => clicks.push((true, vec![vec![e]])), - }, - } - } - clicks -} - -fn click_pars(w: &mut W, x: &mut Exp, ids: &mut Ids, clicks: &Groups, interactive: bool) { - for (ci, (auto, afters)) in clicks.iter().enumerate() { - w.open0("p:par"); - w.open("p:cTn", A::new().a("id", ids.next()).a("fill", "hold")); - w.open0("p:stCondLst"); - if interactive && ci == 0 { - w.empty("p:cond", A::new().a("delay", 0)); - } else { - w.empty("p:cond", A::new().a("delay", "indefinite")); - if *auto { - w.open("p:cond", A::new().a("evt", "onBegin").a("delay", 0)); - w.val("p:tn", 2); - w.close("p:cond"); - } - } - w.close("p:stCondLst"); - w.open0("p:childTnLst"); - let mut t = 0u32; - for g in afters { - w.open0("p:par"); - w.open("p:cTn", A::new().a("id", ids.next()).a("fill", "hold")); - w.open0("p:stCondLst"); - w.empty("p:cond", A::new().a("delay", t)); - w.close("p:stCondLst"); - w.open0("p:childTnLst"); - for (i, e) in g.iter().enumerate() { - effect_par(w, x, ids, e, i == 0); - } - w.close("p:childTnLst"); - w.close("p:cTn"); - w.close("p:par"); - t = t.saturating_add(g.iter().map(end_time).max().unwrap_or(0)); - } - w.close("p:childTnLst"); - w.close("p:cTn"); - w.close("p:par"); - } -} - -/// Most effects one slide's timing writes; animations past it are left out. -const MAX_EFFECTS: usize = 100_000; - -/// The shapes of the tree by id, the first in document order for a repeated id (as `find_shape` -/// finds it), so each animation resolves its shape without a tree walk. -fn shape_index<'a>(shapes: &'a [Shape], depth: usize, out: &mut std::collections::HashMap) { - if depth > 64 { - return; - } - for s in shapes { - out.entry(s.id).or_insert(s); - shape_index(s.children(), depth + 1, out); - } -} - -/// Write `p:timing` for a slide's animations and media settings. -pub fn timing(w: &mut W, x: &mut Exp, anims: &[Animation], shapes: &[Shape], idmap: &IdMap) { - let mut grp_count: std::collections::HashMap = Default::default(); - let mut main: Vec = vec![]; - let mut triggered: Vec<(u32, Vec)> = vec![]; - let mut bld: Vec<(u32, u32, bool)> = vec![]; - // The last paragraph effect written: (shape, class, trigger, grpId). - let mut prev_para: Option<(ShapeId, AnimClass, Option, u32)> = None; - let mut by_id = std::collections::HashMap::new(); - shape_index(shapes, 0, &mut by_id); - let mut roles_of: std::collections::HashMap> = Default::default(); - let mut effect_count = 0usize; - let mut warned = false; - for a in anims.iter().take(10_000) { - if effect_count >= MAX_EFFECTS { - if !warned { - log::warn!("pptx: more than {MAX_EFFECTS} animation effects; the rest are left out"); - } - break; - } - let Some(spid) = idmap.get(a.shape) else { - log::warn!("pptx: animation on missing shape {} skipped", a.shape); - continue; - }; - let Some(&shape) = by_id.get(&a.shape) else { continue }; - let text_sp = matches!(shape.kind, ShapeKind::Shape) && shape.text.is_some(); - let is_text_sp = matches!(shape.kind, ShapeKind::Shape) && shape.text.as_ref().is_some_and(|t| !t.is_empty()); - let text = shape.text.as_ref().filter(|_| a.text_build == TextBuild::ByParagraph && is_text_sp); - let no_roles = Vec::new(); - let roles = match text { - Some(t) => roles_of.entry(a.shape).or_insert_with(|| paragraph_build_roles(t)), - None => &no_roles, - }; - let by_para = roles.contains(&BuildRole::Top); - // PowerPoint keeps a shape's consecutive paragraph effects in one build (`grpId`) marked - // `build="p"`; the reader turns them back into a by-paragraph build only if that plays them - // the same way. - let para_effect = !by_para && text_sp && a.paragraph.is_some(); - let joins = para_effect && prev_para.is_some_and(|(s, c, t, _)| s == a.shape && c == a.class && t == a.trigger); - let grp = match prev_para { - Some((.., g)) if joins => g, - _ => { - let c = grp_count.entry(spid).or_insert(0); - let g = *c; - *c += 1; - g - } - }; - prev_para = para_effect.then_some((a.shape, a.class, a.trigger, grp)); - let mut effs = vec![]; - if by_para { - // One effect per paragraph the build animates on its own, deeper ones with their - // parent; indices in the file count empty paragraphs too. - let mut tops = 0; - for (i, role) in roles.iter().enumerate() { - let start = match role { - BuildRole::Top => { - tops += 1; - if tops == 1 { - a.start - } else if a.start == AnimStart::OnClick { - AnimStart::OnClick - } else { - AnimStart::AfterPrevious - } - } - BuildRole::Member(_) if text.and_then(|t| t.paragraphs.get(i)).is_some_and(build_filled) => AnimStart::WithPrevious, - _ => continue, - }; - let Ok(pi) = u32::try_from(i) else { break }; - if effect_count + effs.len() >= MAX_EFFECTS { - if !warned { - log::warn!("pptx: more than {MAX_EFFECTS} animation effects; the rest are left out"); - warned = true; - } - break; - } - effs.push(Eff { a, spid, start, paragraph: Some(pi), grp }); - } - } else { - effs.push(Eff { a, spid, start: a.start, paragraph: a.paragraph, grp }); - } - effect_count += effs.len(); - if text_sp && !joins { - bld.push((spid, grp, by_para || para_effect)); - } - match a.trigger.and_then(|t| idmap.get(t)) { - Some(t) => match triggered.iter_mut().find(|(s, _)| *s == t) { - Some((_, v)) => v.extend(effs), - None => triggered.push((t, effs)), - }, - None => main.extend(effs), - } - } - let media = collect_media(shapes, idmap); - if main.is_empty() && triggered.is_empty() && media.is_empty() { - return; - } - let mut ids = Ids(0); - w.open0("p:timing"); - w.open0("p:tnLst"); - w.open0("p:par"); - w.open("p:cTn", A::new().a("id", ids.next()).a("dur", "indefinite").a("restart", "never").a("nodeType", "tmRoot")); - w.open0("p:childTnLst"); - if !main.is_empty() { - let clicks = group(main); - w.open("p:seq", A::new().a("concurrent", 1).a("nextAc", "seek")); - w.open("p:cTn", A::new().a("id", ids.next()).a("dur", "indefinite").a("nodeType", "mainSeq")); - w.open0("p:childTnLst"); - click_pars(w, x, &mut ids, &clicks, false); - w.close("p:childTnLst"); - w.close("p:cTn"); - w.open0("p:prevCondLst"); - w.open("p:cond", A::new().a("evt", "onPrev").a("delay", 0)); - w.open0("p:tgtEl"); - w.empty0("p:sldTgt"); - w.close("p:tgtEl"); - w.close("p:cond"); - w.close("p:prevCondLst"); - w.open0("p:nextCondLst"); - w.open("p:cond", A::new().a("evt", "onNext").a("delay", 0)); - w.open0("p:tgtEl"); - w.empty0("p:sldTgt"); - w.close("p:tgtEl"); - w.close("p:cond"); - w.close("p:nextCondLst"); - w.close("p:seq"); - } - for (trig, effs) in triggered { - // The first step starts with the button's click. Later On Click effects must remain - // separate steps; With/After Previous effects still belong to their preceding step. - let effs: Vec = - effs.into_iter().enumerate().map(|(i, e)| Eff { start: if i == 0 { AnimStart::OnClick } else { e.start }, ..e }).collect(); - let clicks = group(effs); - let trig_cond = |w: &mut W| { - w.open("p:cond", A::new().a("evt", "onClick").a("delay", 0)); - w.open0("p:tgtEl"); - w.empty("p:spTgt", A::new().a("spid", trig)); - w.close("p:tgtEl"); - w.close("p:cond"); - }; - w.open("p:seq", A::new().a("concurrent", 1).a("nextAc", "seek")); - w.open( - "p:cTn", - A::new() - .a("id", ids.next()) - .a("restart", "whenNotActive") - .a("fill", "hold") - .a("evtFilter", "cancelBubble") - .a("nodeType", "interactiveSeq"), - ); - w.open0("p:stCondLst"); - trig_cond(w); - w.close("p:stCondLst"); - w.open("p:endSync", A::new().a("evt", "end").a("delay", 0)); - w.empty("p:rtn", A::new().a("val", "all")); - w.close("p:endSync"); - w.open0("p:childTnLst"); - click_pars(w, x, &mut ids, &clicks, true); - w.close("p:childTnLst"); - w.close("p:cTn"); - w.open0("p:nextCondLst"); - trig_cond(w); - w.close("p:nextCondLst"); - w.close("p:seq"); - } - for (spid, clip) in &media { - write_media_node(w, &mut ids, *spid, clip); - } - w.close("p:childTnLst"); - w.close("p:cTn"); - w.close("p:par"); - w.close("p:tnLst"); - if !bld.is_empty() { - w.open0("p:bldLst"); - for (spid, grp, build_p) in bld { - w.empty("p:bldP", A::new().a("spid", spid).a("grpId", grp).o("build", build_p.then_some("p")).t("animBg", !build_p)); - } - w.close("p:bldLst"); - } - w.close("p:timing"); -} - -/// Collects media shapes on the slide that have non-default playback settings requiring a `p:video`/`p:audio` timing node. -fn collect_media<'a>(shapes: &'a [Shape], idmap: &IdMap) -> Vec<(u32, &'a deckcraft_model::MediaClip)> { - let mut media = Vec::new(); - deckcraft_model::walk(shapes, &mut |shape, _| { - if let ShapeKind::Media(clip) = &shape.kind - && (clip.autoplay - || (clip.volume - 1.0).abs() > 1e-6 - || clip.hide_while_not_playing - || clip.loop_play - || clip.rewind - || clip.play_across_slides - || (clip.video && clip.full_screen)) - && let Some(spid) = idmap.get(shape.id) - { - media.push((spid, clip)); - } - }); - media -} - -/// Writes a `p:video` or `p:audio` media timing node (`p:cMediaNode`) for a media shape. -fn write_media_node(w: &mut W, ids: &mut Ids, spid: u32, clip: &deckcraft_model::MediaClip) { - let tag = if clip.video { "p:video" } else { "p:audio" }; - w.open(tag, A::new().t("fullScrn", clip.video && clip.full_screen)); - let mut cm = A::new().a("vol", (clip.volume.clamp(0.0, 1.0) * 100_000.0).round() as u32); - if clip.volume <= 1e-6 { - cm = cm.t("mute", true); - } - if clip.hide_while_not_playing { - cm = cm.a("showWhenStopped", 0); - } - if clip.play_across_slides { - cm = cm.a("numSld", 999); - } - w.open("p:cMediaNode", cm); - w.open( - "p:cTn", - A::new() - .a("id", ids.next()) - .a("fill", if clip.rewind { "remove" } else { "hold" }) - .a("display", 0) - .o("repeatCount", clip.loop_play.then_some("indefinite")), - ); - w.open0("p:stCondLst"); - w.empty("p:cond", A::new().a("delay", if clip.autoplay { "0" } else { "indefinite" })); - w.close("p:stCondLst"); - w.close("p:cTn"); - w.open0("p:tgtEl"); - w.empty("p:spTgt", A::new().a("spid", spid)); - w.close("p:tgtEl"); - w.close("p:cMediaNode"); - w.close(tag); -} diff --git a/crates/pptx/src/xml.rs b/crates/pptx/src/xml.rs index 640844ad6..a365f4f77 100644 --- a/crates/pptx/src/xml.rs +++ b/crates/pptx/src/xml.rs @@ -1,23 +1,10 @@ -//! A small, bounded XML DOM over quick-xml for reading parts, plus an escaping string builder for -//! writing them. -//! -//! Reading is lenient about namespaces: elements and attributes are matched by local name, which is -//! how real-world files are best understood (prefixes are conventional and stable in practice). - -use std::fmt::Write as _; - -use quick_xml::events::Event; +//! Bounded XML DOM wrapper over [`craft_drawingml::xmlx::parse`] for callers that read kept +//! XML fragments (such as 3-D shape settings). use crate::PptxError; -/// Maximum element nesting accepted when parsing. -pub const MAX_DEPTH: usize = 256; -/// Maximum number of elements in one part. -pub const MAX_NODES: usize = 4_000_000; - #[derive(Clone, Debug, Default, PartialEq)] pub struct El { - /// Qualified name as written (`p:sp`). pub name: String, pub attrs: Vec<(String, String)>, pub children: Vec, @@ -30,515 +17,97 @@ pub enum Node { } fn local_of(name: &str) -> &str { - name.rsplit_once(':').map(|(_, l)| l).unwrap_or(name) + name.rsplit_once(':').map_or(name, |(_, l)| l) } impl El { pub fn local(&self) -> &str { local_of(&self.name) } + pub fn prefix(&self) -> &str { - self.name.split_once(':').map(|(p, _)| p).unwrap_or("") + self.name.split_once(':').map_or("", |(p, _)| p) } + pub fn is(&self, local: &str) -> bool { self.local() == local } - /// Attribute by local name (`id` matches `id`; `r:id` matches `id` only when no plain `id` - /// exists). Pass a qualified name (`r:id`) to require that prefix's local name with any prefix. + + pub fn to_xml(&self) -> String { + let mut out = String::new(); + self.write_xml(&mut out); + out + } + + fn write_xml(&self, out: &mut String) { + out.push('<'); + out.push_str(&self.name); + for (k, v) in &self.attrs { + out.push(' '); + out.push_str(k); + out.push_str("=\""); + craft_xml::push_esc_attr(out, v); + out.push('"'); + } + if self.children.is_empty() { + out.push_str("/>"); + return; + } + out.push('>'); + for c in &self.children { + match c { + Node::El(e) => e.write_xml(out), + Node::Text(t) => craft_xml::push_esc(out, t), + } + } + out.push_str("'); + } + pub fn attr(&self, name: &str) -> Option<&str> { - if let Some((_, l)) = name.split_once(':') { - return self.attrs.iter().find(|(k, _)| k.contains(':') && !k.starts_with("xmlns") && local_of(k) == l).map(|(_, v)| v.as_str()); - } - self.attrs - .iter() - .find(|(k, _)| k == name) - .or_else(|| self.attrs.iter().find(|(k, _)| !k.starts_with("xmlns") && local_of(k) == name)) - .map(|(_, v)| v.as_str()) - } - pub fn has_attr(&self, name: &str) -> bool { - self.attr(name).is_some() - } - pub fn set_attr(&mut self, name: &str, value: &str) { - if let Some(a) = self.attrs.iter_mut().find(|(k, _)| k == name) { - a.1 = value.to_string(); - } else { - self.attrs.push((name.to_string(), value.to_string())); - } - } - pub fn i64(&self, name: &str) -> Option { - let v = self.attr(name)?.trim(); - v.parse::().ok().or_else(|| v.parse::().ok().filter(|f| f.is_finite()).map(|f| f.clamp(-9.0e18, 9.0e18) as i64)) - } - pub fn i32(&self, name: &str) -> Option { - self.i64(name).map(|v| v.clamp(i32::MIN as i64, i32::MAX as i64) as i32) - } - pub fn u32(&self, name: &str) -> Option { - self.i64(name).map(|v| v.clamp(0, u32::MAX as i64) as u32) - } - pub fn f64(&self, name: &str) -> Option { - self.attr(name)?.trim().parse::().ok().filter(|f| f.is_finite()) - } - pub fn bool(&self, name: &str) -> Option { - match self.attr(name)?.trim() { - "1" | "true" | "on" => Some(true), - "0" | "false" | "off" => Some(false), - _ => None, - } + self.attrs.iter().find(|(k, _)| k == name || local_of(k) == name).map(|(_, v)| v.as_str()) } + pub fn elements(&self) -> impl Iterator { self.children.iter().filter_map(|n| match n { Node::El(e) => Some(e), Node::Text(_) => None, }) } - pub fn elements_mut(&mut self) -> impl Iterator { - self.children.iter_mut().filter_map(|n| match n { - Node::El(e) => Some(e), - Node::Text(_) => None, - }) - } + pub fn child(&self, local: &str) -> Option<&El> { - self.elements().find(|e| e.is(local)) + self.elements().find(|e| e.local() == local) } + pub fn children_named<'a>(&'a self, local: &'a str) -> impl Iterator + 'a { - self.elements().filter(move |e| e.is(local)) + self.elements().filter(move |e| e.local() == local) } - /// Follow a chain of child local names. - pub fn path(&self, names: &[&str]) -> Option<&El> { - let mut cur = self; - for n in names { - cur = cur.child(n)?; - } - Some(cur) - } - /// First descendant (depth-first, bounded) with this local name. - pub fn find(&self, local: &str) -> Option<&El> { - fn rec<'a>(e: &'a El, local: &str, depth: usize) -> Option<&'a El> { - if depth > MAX_DEPTH { - return None; - } - for c in e.elements() { - if c.is(local) { - return Some(c); - } - if let Some(f) = rec(c, local, depth + 1) { - return Some(f); - } - } - None - } - rec(self, local, 0) - } - /// All descendants with this local name (bounded depth). - pub fn find_all<'a>(&'a self, local: &str, out: &mut Vec<&'a El>) { - fn rec<'a>(e: &'a El, local: &str, depth: usize, out: &mut Vec<&'a El>) { - if depth > MAX_DEPTH { - return; - } - for c in e.elements() { - if c.is(local) { - out.push(c); - } - rec(c, local, depth + 1, out); - } - } - rec(self, local, 0, out) - } - /// Concatenated text content of this element and its descendants. - pub fn text(&self) -> String { - let mut s = String::new(); - fn rec(e: &El, s: &mut String, depth: usize) { - if depth > MAX_DEPTH { - return; - } - for c in &e.children { - match c { - Node::Text(t) => s.push_str(t), - Node::El(e) => rec(e, s, depth + 1), - } - } - } - rec(self, &mut s, 0); - s - } - /// Value of `` child. - pub fn child_val(&self, local: &str) -> Option<&str> { - self.child(local).and_then(|c| c.attr("val")) - } - /// Serialize to a string (no XML declaration). - pub fn to_xml(&self) -> String { - let mut s = String::new(); - write_el(self, &mut s, 0); - s + + pub fn path(&self, path: &[&str]) -> Option<&El> { + path.iter().try_fold(self, |cur, name| cur.child(name)) } } -fn write_el(e: &El, s: &mut String, depth: usize) { - if depth > MAX_DEPTH { - return; - } - s.push('<'); - s.push_str(&e.name); - for (k, v) in &e.attrs { - let _ = write!(s, " {}=\"{}\"", k, esc_attr(v)); - } - if e.children.is_empty() { - s.push_str("/>"); - return; - } - s.push('>'); - for c in &e.children { - match c { - Node::Text(t) => s.push_str(&esc(t)), - Node::El(c) => write_el(c, s, depth + 1), - } - } - s.push_str("'); -} - -/// A parsed document: its root element and the namespace declarations on the root. #[derive(Clone, Debug, Default)] pub struct Doc { pub root: El, } -impl Doc { - /// Namespace declarations (`xmlns:x`, `xmlns`) on the root element. - pub fn ns_decls(&self) -> Vec<(String, String)> { - self.root.attrs.iter().filter(|(k, _)| k == "xmlns" || k.starts_with("xmlns:")).cloned().collect() - } +fn from_craft_el(el: craft_xml::El) -> El { + let children = el + .children + .into_iter() + .filter_map(|n| match n { + craft_xml::Node::El(c) => Some(Node::El(from_craft_el(c))), + craft_xml::Node::Text(t) | craft_xml::Node::CData(t) => Some(Node::Text(t)), + craft_xml::Node::Pi { .. } | craft_xml::Node::Comment(_) => None, + }) + .collect(); + El { name: el.name, attrs: el.attrs, children } } -/// Parse XML bytes into a DOM. Bounded depth and node count; entity references are resolved. pub fn parse(bytes: &[u8]) -> Result { - // Skip a UTF-8 BOM; UTF-16 parts (rare) are decoded first. - let owned; - let bytes = if bytes.starts_with(&[0xFF, 0xFE]) || bytes.starts_with(&[0xFE, 0xFF]) { - owned = decode_utf16(bytes); - owned.as_bytes() - } else { - bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(bytes) - }; - let mut reader = quick_xml::Reader::from_reader(bytes); - { - let c = reader.config_mut(); - c.trim_text(false); - c.check_end_names = false; - c.allow_unmatched_ends = true; - c.expand_empty_elements = false; - } - let mut stack: Vec = vec![]; - let mut root: Option = None; - let mut nodes = 0usize; - let mut buf = Vec::new(); - loop { - let ev = reader.read_event_into(&mut buf).map_err(|e| PptxError::Xml(format!("{e}")))?; - match ev { - Event::Start(b) | Event::Empty(b) if root.is_some() => { - // Content after the root element: ignore. - let _ = b; - } - Event::Start(b) => { - nodes += 1; - if nodes > MAX_NODES || stack.len() >= MAX_DEPTH { - return Err(PptxError::Xml("document too large or too deeply nested".into())); - } - stack.push(start_el(&b, &reader)); - } - Event::Empty(b) => { - nodes += 1; - if nodes > MAX_NODES { - return Err(PptxError::Xml("document too large".into())); - } - let el = start_el(&b, &reader); - match stack.last_mut() { - Some(p) => p.children.push(Node::El(el)), - None => root = Some(el), - } - } - Event::End(_) => { - if let Some(el) = stack.pop() { - match stack.last_mut() { - Some(p) => p.children.push(Node::El(el)), - None => root = Some(el), - } - } - } - Event::Text(t) => { - if let Some(p) = stack.last_mut() { - let s = t.decode().map(|c| c.into_owned()).unwrap_or_default(); - push_text(p, &line_ends(s)); - } - } - Event::CData(t) => { - if let Some(p) = stack.last_mut() { - let s = String::from_utf8_lossy(&t).into_owned(); - push_text(p, &line_ends(s)); - } - } - Event::GeneralRef(r) => { - if let Some(p) = stack.last_mut() { - let s = if r.is_char_ref() { - r.resolve_char_ref().ok().flatten().map(String::from).unwrap_or_default() - } else { - match r.decode().map(|c| c.into_owned()).unwrap_or_default().as_str() { - "amp" => "&".into(), - "lt" => "<".into(), - "gt" => ">".into(), - "quot" => "\"".into(), - "apos" => "'".into(), - _ => String::new(), - } - }; - push_text(p, &s); - } - } - Event::Eof => break, - _ => {} - } - buf.clear(); - } - // Unclosed elements (truncated document): fold them up so partial content is still usable. - while let Some(el) = stack.pop() { - match stack.last_mut() { - Some(p) => p.children.push(Node::El(el)), - None => root = Some(el), - } - } - let root = root.ok_or_else(|| PptxError::Xml("no root element".into()))?; - Ok(Doc { root }) -} - -/// XML 1.0 §2.11: a literal CR LF or lone CR in the document reads as LF. A ` ` reference is -/// not literal and reaches `push_text` through `GeneralRef`, so it stays a CR. -fn line_ends(s: String) -> String { - if s.contains('\r') { s.replace("\r\n", "\n").replace('\r', "\n") } else { s } -} - -fn push_text(p: &mut El, s: &str) { - if s.is_empty() { - return; - } - if let Some(Node::Text(t)) = p.children.last_mut() { - t.push_str(s); - } else { - p.children.push(Node::Text(s.to_string())); - } -} - -fn start_el(b: &quick_xml::events::BytesStart, reader: &quick_xml::Reader<&[u8]>) -> El { - let name = String::from_utf8_lossy(b.name().as_ref()).into_owned(); - let mut attrs = vec![]; - for a in b.attributes().with_checks(false).flatten() { - let k = String::from_utf8_lossy(a.key.as_ref()).into_owned(); - let v = a - .decoded_and_normalized_value(quick_xml::XmlVersion::Implicit1_0, reader.decoder()) - .map(|c| c.into_owned()) - .unwrap_or_else(|_| String::from_utf8_lossy(&a.value).into_owned()); - attrs.push((k, v)); - } - El { name, attrs, children: vec![] } -} - -fn decode_utf16(bytes: &[u8]) -> String { - let le = bytes.starts_with(&[0xFF, 0xFE]); - let units: Vec = - bytes.get(2..).unwrap_or(&[]).as_chunks::<2>().0.iter().map(|c| if le { u16::from_le_bytes(*c) } else { u16::from_be_bytes(*c) }).collect(); - let s = String::from_utf16_lossy(&units); - // Drop the encoding declaration so quick-xml reads it as UTF-8. - match s.strip_prefix("").map(|i| i + 7)) { - Some(end) => s.get(end..).unwrap_or("").to_string(), - None => s, - } -} - -// Preserve the public writer helpers while sharing the XML 1.0 escaping rules. -pub use craft_xml::{esc, esc_attr}; - -/// A string builder for XML parts. -#[derive(Default)] -pub struct W { - pub s: String, -} - -/// Attribute list builder. -#[derive(Default)] -pub struct A { - pub v: Vec<(&'static str, String)>, -} - -impl A { - pub fn new() -> Self { - A { v: vec![] } - } - pub fn a(mut self, k: &'static str, v: impl ToString) -> Self { - self.v.push((k, v.to_string())); - self - } - pub fn o(mut self, k: &'static str, v: Option) -> Self { - if let Some(v) = v { - self.v.push((k, v.to_string())); - } - self - } - /// Boolean attribute written as `1`/`0` when `Some`. - pub fn b(mut self, k: &'static str, v: Option) -> Self { - if let Some(v) = v { - self.v.push((k, if v { "1" } else { "0" }.to_string())); - } - self - } - /// Boolean attribute written only when true. - pub fn t(mut self, k: &'static str, v: bool) -> Self { - if v { - self.v.push((k, "1".to_string())); - } - self - } -} - -impl W { - pub fn new() -> Self { - W { s: String::from("\n") } - } - pub fn frag() -> Self { - W { s: String::new() } - } - fn attrs(&mut self, a: &A) { - for (k, v) in &a.v { - let _ = write!(self.s, " {}=\"{}\"", k, esc_attr(v)); - } - } - pub fn open(&mut self, name: &str, a: A) { - self.s.push('<'); - self.s.push_str(name); - self.attrs(&a); - self.s.push('>'); - } - pub fn open0(&mut self, name: &str) { - self.s.push('<'); - self.s.push_str(name); - self.s.push('>'); - } - pub fn close(&mut self, name: &str) { - self.s.push_str("'); - } - pub fn empty(&mut self, name: &str, a: A) { - self.s.push('<'); - self.s.push_str(name); - self.attrs(&a); - self.s.push_str("/>"); - } - pub fn empty0(&mut self, name: &str) { - self.s.push('<'); - self.s.push_str(name); - self.s.push_str("/>"); - } - /// `` - pub fn val(&mut self, name: &str, v: impl ToString) { - self.empty(name, A::new().a("val", v)); - } - pub fn text(&mut self, t: &str) { - self.s.push_str(&esc(t)); - } - /// `text` - pub fn elt(&mut self, name: &str, t: &str) { - self.open0(name); - self.text(t); - self.close(name); - } - pub fn raw(&mut self, xml: &str) { - self.s.push_str(xml); - } - pub fn finish(self) -> Vec { - self.s.into_bytes() - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn literal_cr_lf_and_lone_cr_read_as_lf_but_char_ref_stays() { - let d = parse(b"one\r\ntwo\rthree four").expect("parse"); - let t: Vec = d.root.children_named("t").map(|t| t.text()).collect(); - assert_eq!(t, vec!["one\ntwo\nthree\rfour".to_string(), "x\ny".to_string()]); - } - - #[test] - fn cr_in_text_survives_write_read() { - assert_eq!(esc("a\rb"), "a b"); - let mut w = W::default(); - w.elt("a:t", "one\rtwo\r\nthree"); - let d = parse(w.s.as_bytes()).expect("parse"); - assert_eq!(d.root.text(), "one\rtwo\r\nthree"); - } - - #[test] - fn parse_basic_and_entities() { - let d = parse(b"A & B A <") - .unwrap(); - assert_eq!(d.root.local(), "p"); - assert_eq!(d.root.find("t").map(|t| t.text()), Some("A & B A <".to_string())); - let x = d.root.child("x").unwrap(); - assert_eq!(x.attr("id"), Some("5")); - assert_eq!(x.attr("r:id"), Some("rId1")); - assert_eq!(d.ns_decls().len(), 1); - } - - #[test] - fn truncated_and_garbage() { - assert!(parse(b"text").is_ok()); - assert!(parse(b"").is_err()); - let deep = "".repeat(MAX_DEPTH + 10); - assert!(parse(deep.as_bytes()).is_err()); - } - - #[test] - fn escape_drops_control_chars() { - assert_eq!(esc("a\u{b}b<\u{0}"), "ab<"); - assert_eq!(esc_attr("\"x\"\n"), ""x" "); - } - - #[test] - fn shared_escaping_preserves_xml_wire_bytes() { - let text = "&<>\"'\t\n\r\0\u{b}\u{fffe}\u{ffff}é😀 "; - assert_eq!(esc(text), "&<>\"'\t\n é😀&#13;"); - assert_eq!(esc_attr(text), "&<>"' é😀&#13;"); - assert_eq!(esc(""), ""); - assert_eq!(esc_attr(""), ""); - for code in 0..32 { - let c = char::from_u32(code).unwrap(); - let text = c.to_string(); - match c { - '\t' => { - assert_eq!(esc(&text), "\t"); - assert_eq!(esc_attr(&text), " "); - } - '\n' => { - assert_eq!(esc(&text), "\n"); - assert_eq!(esc_attr(&text), " "); - } - '\r' => { - assert_eq!(esc(&text), " "); - assert_eq!(esc_attr(&text), " "); - } - _ => { - assert_eq!(esc(&text), ""); - assert_eq!(esc_attr(&text), ""); - } - } - } - } - - #[test] - fn roundtrip_serialize() { - let d = parse(b"x & y").unwrap(); - assert_eq!(d.root.to_xml(), "x & y"); - } + let root = craft_drawingml::xmlx::parse(bytes).map_err(|e| PptxError::Xml(e.to_string()))?; + Ok(Doc { root: from_craft_el(root) }) }