mod build;
pub(crate) mod inherit;
pub(crate) mod media;
mod order;
pub(crate) mod package;
mod rules;
pub(crate) mod text;
use crate::model::{Document, Span};
use crate::word::docx::{Rel, parse, read_rels};
use crate::word::ir::{Inline, Item, Para, WordDoc};
use crate::word::xml::child;
use crate::word::zip::ZipArchive;
use anyhow::{Context, Result};
use build::SlideContent;
use inherit::Inheritance;
use media::Media;
use package::{P_NS, Presentation, SlideRef};
use roxmltree::{Document as Xml, Node};
use std::collections::HashMap;
use text::TextContext;
const DEFAULT_BODY_SIZE_PT: f32 = 18.0;
const NOTES_HEADING: &str = "Notes";
const DEFAULT_DECK_TITLE: &str = "PowerPoint Presentation";
pub(crate) const DEFAULT_BODY_FONT: &str = "Calibri";
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PowerPointConfig {
pub title_top_ratio: f32,
pub title_min_size_pt: f32,
pub title_size_ratio: f32,
pub title_max_words: usize,
pub title_slide_max_words: usize,
pub furniture_max_words: usize,
pub furniture_edge_ratio: f32,
pub furniture_slides_ratio: f32,
pub reading_overlap_pt: f32,
}
impl Default for PowerPointConfig {
fn default() -> Self {
Self {
title_top_ratio: 0.25,
title_min_size_pt: 20.0,
title_size_ratio: 1.1,
title_max_words: 30,
title_slide_max_words: 60,
furniture_max_words: 12,
furniture_edge_ratio: 0.15,
furniture_slides_ratio: 0.5,
reading_overlap_pt: 2.0,
}
}
}
const FURNITURE_MIN_SLIDES: usize = 3;
pub fn detect(data: &[u8]) -> bool {
data.starts_with(b"PK\x03\x04")
&& ZipArchive::new(data)
.ok()
.is_some_and(|zip| package::presentation_part(&zip).is_some())
}
pub fn read(data: &[u8], source: Option<String>) -> Result<Document> {
let zip = ZipArchive::new(data)?;
let presentation = Presentation::read(&zip)?;
let mut parts = Parts::new(&zip);
let presentation_xml = parts.text(&presentation.part).unwrap_or_default();
let presentation_doc = parse(&presentation_xml).with_context(|| format!("reading {}", presentation.part))?;
let defaults = child(presentation_doc.root_element(), P_NS, "defaultTextStyle");
let theme = parts
.related(&presentation.part, "theme")
.and_then(|part| zip.read(&part).ok().flatten());
let mut media = Media::new(&zip, theme.as_deref());
let mut word = WordDoc {
title: crate::word::docx::document_title(&zip)?.filter(|title| title.trim() != DEFAULT_DECK_TITLE),
body_size_pt: DEFAULT_BODY_SIZE_PT,
body_font: DEFAULT_BODY_FONT.to_string(),
..Default::default()
};
let config = PowerPointConfig::default();
let height_pt = presentation.size_pt.1;
let shown: Vec<&SlideRef> = presentation.visible().collect();
let mut slides = Vec::with_capacity(shown.len());
for slide in &shown {
crate::common::cancel::check();
slides.push(parts.slide(slide, defaults, &mut media, config.reading_overlap_pt)?);
}
for content in &mut slides {
rules::infer_title(content, height_pt, &config);
}
rules::remove_furniture(&mut slides, height_pt, &config);
let sectioned = presentation.sections.len() > 1;
let slide_level = if sectioned { 2 } else { 1 };
let mut section = None;
for (index, (slide, content)) in shown.iter().zip(slides).enumerate() {
let notes = parts.notes(slide);
let mut content = content;
if index == 0
&& (content.title_slide
|| rules::looks_like_title_slide(&content, &config)
|| rules::title_from_first_paragraph(&mut content, &config))
{
front_matter(content, &config, &mut word.body);
push_notes(notes, slide_level, &mut word.body);
continue;
}
if content.is_empty() && notes.is_empty() {
continue;
}
let current = presentation.section_of(&slide.id).filter(|_| sectioned);
let mut section_name = "";
if current != section {
section = current;
section_name = current.map_or("", |index| presentation.sections[index].name.trim());
if !section_name.is_empty() {
word.body
.push(Item::Para(heading(vec![Inline::Text(Span::plain(section_name))], 1)));
}
}
let title = content
.title
.unwrap_or_else(|| vec![Inline::Text(Span::plain(format!("Slide {}", slide.number)))]);
let repeats_section = !section_name.is_empty()
&& text::inlines_text(&title)
.split_whitespace()
.eq(section_name.split_whitespace());
if !repeats_section {
word.body.push(Item::Para(heading(title, slide_level)));
}
word.body.extend(content.subtitle.into_iter().map(Item::Para));
word.body
.extend(build::ordered_items(content.pieces, config.reading_overlap_pt));
let notes_level = if repeats_section { slide_level } else { slide_level + 1 };
push_notes(notes, notes_level, &mut word.body);
}
word.pictures = media.pictures;
Ok(crate::word::build_document(word, source))
}
fn front_matter(content: SlideContent, config: &PowerPointConfig, body: &mut Vec<Item>) {
if let Some(title) = content.title {
body.push(Item::Para(Para {
style: "Title".to_string(),
inlines: title,
..Default::default()
}));
}
let as_subtitle = |para: Para| {
Item::Para(Para {
style: "Subtitle".to_string(),
..para
})
};
body.extend(content.subtitle.into_iter().map(as_subtitle));
let mut pictures = Vec::new();
for item in build::ordered_items(content.pieces, config.reading_overlap_pt) {
match item {
Item::Para(para) if !text::inlines_text(¶.inlines).trim().is_empty() => body.push(as_subtitle(para)),
other => pictures.push(other),
}
}
body.extend(pictures);
}
fn push_notes(notes: Vec<Para>, level: u8, body: &mut Vec<Item>) {
if notes.is_empty() {
return;
}
body.push(Item::Para(heading(
vec![Inline::Text(Span::plain(NOTES_HEADING))],
level,
)));
body.extend(notes.into_iter().map(Item::Para));
}
fn heading(inlines: Vec<Inline>, level: u8) -> Para {
Para {
style: format!("heading {level}"),
inlines,
..Default::default()
}
}
pub(crate) struct Parts<'z> {
zip: &'z ZipArchive<'z>,
texts: HashMap<String, Option<String>>,
}
impl<'z> Parts<'z> {
pub(crate) fn new(zip: &'z ZipArchive<'z>) -> Self {
Self {
zip,
texts: HashMap::new(),
}
}
pub(crate) fn text(&mut self, path: &str) -> Option<String> {
self.texts
.entry(path.to_string())
.or_insert_with(|| self.zip.read_text(path).ok().flatten())
.clone()
}
pub(crate) fn related(&self, part: &str, kind: &str) -> Option<String> {
read_rels(self.zip, part)
.ok()?
.into_iter()
.find(|(_, own, rel)| own == kind && !rel.external)
.map(|(_, _, rel)| rel.target)
}
fn slide(
&mut self,
slide: &SlideRef,
defaults: Option<Node<'_, '_>>,
media: &mut Media<'_>,
overlap_pt: f32,
) -> Result<SlideContent> {
let Some(slide_xml) = self.text(&slide.part) else {
return Ok(SlideContent::default());
};
let layout_part = self.related(&slide.part, "slideLayout");
let master_part = layout_part
.as_deref()
.and_then(|part| self.related(part, "slideMaster"));
let layout_xml = layout_part.and_then(|part| self.text(&part));
let master_xml = master_part.and_then(|part| self.text(&part));
let slide_doc = parse(&slide_xml).with_context(|| format!("reading {}", slide.part))?;
let layout_doc = layout_xml.as_deref().and_then(|xml| parse(xml).ok());
let master_doc = master_xml.as_deref().and_then(|xml| parse(xml).ok());
let inheritance = Inheritance {
layout: layout_doc.as_ref().and_then(shape_tree),
master: master_doc.as_ref().and_then(shape_tree),
styles: master_doc
.as_ref()
.and_then(|doc| child(doc.root_element(), P_NS, "txStyles")),
defaults,
};
let rels: HashMap<String, Rel> = read_rels(self.zip, &slide.part)
.unwrap_or_default()
.into_iter()
.map(|(id, _, rel)| (id, rel))
.collect();
let context = TextContext {
number: slide.number,
rels: &rels,
};
let mut content = shape_tree(&slide_doc).map_or_else(SlideContent::default, |tree| {
build::slide(tree, &inheritance, &context, media, overlap_pt)
});
content.title_slide |= layout_doc
.as_ref()
.is_some_and(|doc| doc.root_element().attribute("type") == Some("title"));
Ok(content)
}
}
impl Parts<'_> {
fn notes(&mut self, slide: &SlideRef) -> Vec<Para> {
let Some(part) = self.related(&slide.part, "notesSlide") else {
return Vec::new();
};
let Some(xml) = self.text(&part) else {
return Vec::new();
};
let master_xml = self.related(&part, "notesMaster").and_then(|master| self.text(&master));
let (Ok(doc), master_doc) = (parse(&xml), master_xml.as_deref().map(parse)) else {
return Vec::new();
};
let master_doc = master_doc.and_then(Result::ok);
let inheritance = Inheritance {
master: master_doc.as_ref().and_then(shape_tree),
defaults: master_doc
.as_ref()
.and_then(|doc| child(doc.root_element(), P_NS, "notesStyle")),
..Default::default()
};
let rels: HashMap<String, Rel> = read_rels(self.zip, &part)
.unwrap_or_default()
.into_iter()
.map(|(id, _, rel)| (id, rel))
.collect();
let context = TextContext {
number: slide.number,
rels: &rels,
};
let Some(tree) = shape_tree(&doc) else {
return Vec::new();
};
let mut out = Vec::new();
for shape in tree.descendants().filter(|node| node.tag_name().name() == "sp") {
let Some(ph) = inherit::placeholder(shape) else {
continue;
};
if ph.kind != "body" {
continue;
}
if let Some(body) = child(shape, P_NS, "txBody") {
out.extend(text::paragraphs(body, &inheritance.list_styles(shape), &context));
}
}
out
}
}
pub(crate) fn shape_tree<'a, 'input>(doc: &'a Xml<'input>) -> Option<Node<'a, 'input>> {
child(doc.root_element(), P_NS, "cSld").and_then(|slide| child(slide, P_NS, "spTree"))
}