Skip to content

A fast, helpful, and open-source document parser

wip

Logan Markewich5bc4063f3624
diff --git a/crates/liteparse-ooxml/src/pptx/cascade.rs b/crates/liteparse-ooxml/src/pptx/cascade.rs
index 08ddc63..30d9fc0 100644
--- a/crates/liteparse-ooxml/src/pptx/cascade.rs
+++ b/crates/liteparse-ooxml/src/pptx/cascade.rs
@@ -72,6 +72,7 @@ use std::collections::HashMap;
use crate::model::{ColorMap, Theme, Transform2D};
use crate::render::layout::draw_command::ResolvedFill;
use crate::render::resolve::drawing_color::DrawingColorContext;
+use crate::render::resolve::images::PartMedia;
use crate::render::resolve::shape_visuals::{resolve_background_fill, resolve_fill};
use super::shapes::{Background, Placeholder, PlaceholderKind, Shape};
@@ -311,15 +312,21 @@ pub fn resolve_background<'a>(
/// `color_map` is the slide's effective §19.3.1.6 map, without which a
/// `<a:schemeClr val="bg1"/>` backdrop under a swapped master resolves to the
/// wrong end of the theme's light/dark pair.
+/// `media` must be the [`PartMedia`] of the part the background was resolved
+/// *from* — the [`BackgroundSource`] rung, which is the slide's own on 58
+/// corpus slides, its layout's on 95 and its master's on 1,125. Passing the
+/// slide's own table for a master's photograph is the inherited-`rId1` trap:
+/// a real image, from the wrong relationship.
pub fn background_fill(
bg: &Background,
theme: Option<&Theme>,
color_map: Option<ColorMap>,
+ media: Option<&PartMedia>,
) -> ResolvedFill {
let ctx = DrawingColorContext::new(theme).with_color_map(color_map);
match bg {
- Background::Properties(fill) => resolve_fill(fill, &ctx),
- Background::Reference(r) => resolve_background_fill(r, theme, &ctx),
+ Background::Properties(fill) => resolve_fill(fill, &ctx, media),
+ Background::Reference(r) => resolve_background_fill(r, theme, &ctx, media),
}
}
@@ -591,7 +598,7 @@ mod tests {
] {
let (src, bg) = resolve_background(slide, layout, master).expect("resolves");
assert_eq!(src, want_src);
- assert_eq!(solid_rgb(&background_fill(bg, None, None)), want_rgb);
+ assert_eq!(solid_rgb(&background_fill(bg, None, None, None)), want_rgb);
}
}
@@ -624,7 +631,7 @@ mod tests {
color: None,
});
assert_eq!(
- solid_rgb(&background_fill(&bg, Some(&theme), None)),
+ solid_rgb(&background_fill(&bg, Some(&theme), None, None)),
0x00AA00
);
@@ -634,7 +641,7 @@ mod tests {
color: None,
});
assert_eq!(
- solid_rgb(&background_fill(&bg2, Some(&theme), None)),
+ solid_rgb(&background_fill(&bg2, Some(&theme), None, None)),
0x00BB00
);
@@ -645,7 +652,7 @@ mod tests {
color: None,
});
assert_eq!(
- solid_rgb(&background_fill(&bg3, Some(&theme), None)),
+ solid_rgb(&background_fill(&bg3, Some(&theme), None, None)),
0xBB0000
);
}
@@ -659,7 +666,7 @@ mod tests {
color: None,
});
assert!(matches!(
- background_fill(&bg, Some(&Theme::default()), None),
+ background_fill(&bg, Some(&Theme::default()), None, None),
ResolvedFill::None
));
}
@@ -677,7 +684,7 @@ mod tests {
color: None,
});
assert!(matches!(
- background_fill(&bg, Some(&theme), None),
+ background_fill(&bg, Some(&theme), None, None),
ResolvedFill::None
));
}
diff --git a/crates/liteparse-ooxml/src/pptx/media.rs b/crates/liteparse-ooxml/src/pptx/media.rs
new file mode 100644
index 0000000..f62847a
--- /dev/null
+++ b/crates/liteparse-ooxml/src/pptx/media.rs
@@ -0,0 +1,164 @@
+//! Image bytes, resolved per part and shared per package path.
+//!
+//! ## Why this is keyed two ways
+//!
+//! A blip names its image with an `r:embed`, and an `r:id` is scoped to the
+//! part that writes it: a slide's `rId1`, its layout's `rId1` and its master's
+//! `rId1` are three unrelated relationships, and on this corpus they routinely
+//! name three different images. So the painter needs a **per-part** table
+//! ([`PartMedia`]), or an inherited picture silently acquires whatever the
+//! slide's `rId1` happens to point at — a real photograph, from the wrong
+//! relationship, which no "did it resolve?" gate can see.
+//!
+//! The *bytes*, on the other hand, are shared. One logo referenced by 60
+//! slides is one media part, and [`MediaEntry`]'s `Arc` identity is what the
+//! painter's bitmap cache keys on, so each part must become exactly one `Arc`
+//! however many relationships point at it. Hence `by_path` under `by_part`:
+//! the first deduplicates bytes, the second scopes ids.
+//!
+//! ## Nothing is read until something asks for it
+//!
+//! `PackageContents` holds the whole zip, and the corpus's media is 378 MB
+//! across 45 decks — of which the deck-wide totals are misleading, because
+//! 139 `.svg` and 23 `.wdp` parts are never a blip target at all (Office
+//! writes them as alternatives and effect backups). Copying every media part
+//! into an `Arc` up front would pay for all of them. Resolution is therefore
+//! lazy per path, and a part that no blip reaches is never copied.
+//!
+//! A **negative** result is cached too, as `None`. A missing or undecodable
+//! target is a property of the package, not of the caller asking, so the
+//! second of 60 references must not re-walk the zip to rediscover it.
+
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use crate::docx::relationships::{RelationshipType, TargetMode};
+use crate::model::{ImageFormat, RelId};
+use crate::render::resolve::images::{MediaEntry, PartMedia};
+
+use super::package::{Part, PresentationPackage};
+
+/// Per-part `r:embed` tables over a shared pool of image bytes.
+#[derive(Default)]
+pub struct MediaCache {
+ /// Package path → the bytes behind it, `None` when the package has no such
+ /// part. One `Arc` per path, which is the identity the painter caches on.
+ by_path: HashMap<String, Option<MediaEntry>>,
+ /// Part path → that part's own image relationships, resolved.
+ by_part: HashMap<String, PartMedia>,
+ /// Handed out for a part that does not exist — a slide with no reachable
+ /// master, say. A borrowable empty table rather than an `Option` so that
+ /// every paint site takes the same code path, and "this rung has no media"
+ /// cannot accidentally become "resolve against whatever is in scope".
+ empty: PartMedia,
+}
+
+impl MediaCache {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// The image relationships `part` itself declares, built once per part.
+ ///
+ /// Only `RelationshipType::Image` relationships are included. Filtering on
+ /// the declared type rather than on "did the target decode?" keeps this
+ /// table an answer about the *package* — a slide's layout rel and its
+ /// notes rel resolve to real bytes too, and folding them in would make a
+ /// missing image indistinguishable from an id that never named one.
+ pub fn part_media(&mut self, pkg: &PresentationPackage, part: &Part) -> &PartMedia {
+ if !self.by_part.contains_key(&part.path) {
+ let mut table = PartMedia::new();
+ for rel in part.rels.all() {
+ if rel.rel_type != RelationshipType::Image {
+ continue;
+ }
+ // §15.2.10 external: the bytes live outside the package, so
+ // there is nothing to put in the table. Left absent rather
+ // than inserted-as-missing; the caller's "not declared" and
+ // "declared elsewhere" both correctly paint nothing.
+ if rel.target_mode == TargetMode::External {
+ continue;
+ }
+ let Some(path) = part.resolve_rel(rel.id.as_str()) else {
+ continue;
+ };
+ if let Some(entry) = Self::load(&mut self.by_path, pkg, &path) {
+ table.insert(rel.id.clone(), entry);
+ }
+ }
+ self.by_part.insert(part.path.clone(), table);
+ }
+ &self.by_part[&part.path]
+ }
+
+ /// One media part's bytes, read and format-detected at most once.
+ ///
+ /// Format detection goes through [`ImageFormat::detect`], which tries the
+ /// extension and *then* the magic bytes. That fallback is load-bearing
+ /// here rather than defensive: 21 corpus blips point at `.jfif` parts,
+ /// which are byte-for-byte JPEG and which an extension-only reading drops.
+ /// Undecodable formats (EMF/WMF/SVG) are still entered — the painter is
+ /// the layer that knows what it can rasterize, and a resolver that hid
+ /// them here would report them as missing images instead of unsupported
+ /// ones.
+ fn load(
+ by_path: &mut HashMap<String, Option<MediaEntry>>,
+ pkg: &PresentationPackage,
+ path: &str,
+ ) -> Option<MediaEntry> {
+ if !by_path.contains_key(path) {
+ let entry = pkg.package.get_part(path).map(|bytes| MediaEntry {
+ data: Arc::from(bytes),
+ format: ImageFormat::detect(path, bytes),
+ });
+ by_path.insert(path.to_string(), entry);
+ }
+ by_path[path].clone()
+ }
+
+ /// A part's already-built table. Separate from [`Self::part_media`] so a
+ /// caller can prime several parts and *then* borrow them all at once,
+ /// which `&mut self` on the builder forbids.
+ ///
+ /// Falls back to an empty table rather than `None`: see the `empty` field.
+ pub fn get(&self, part_path: Option<&str>) -> &PartMedia {
+ part_path
+ .and_then(|p| self.by_part.get(p))
+ .unwrap_or(&self.empty)
+ }
+
+ /// How many distinct media parts have been read into memory. Reported by
+ /// the probe so that "the deck has images" and "the painter reached them"
+ /// stay separate claims.
+ pub fn parts_loaded(&self) -> usize {
+ self.by_path.values().filter(|v| v.is_some()).count()
+ }
+
+ /// Package paths a relationship named that the package does not contain.
+ pub fn parts_missing(&self) -> usize {
+ self.by_path.values().filter(|v| v.is_none()).count()
+ }
+}
+
+/// Look one `r:embed` up in a part's table. A thin helper so callers do not
+/// have to build a [`RelId`] to ask.
+pub fn media_entry<'a>(media: &'a PartMedia, embed: &str) -> Option<&'a MediaEntry> {
+ media.get(&RelId::new(embed))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn jfif_extension_falls_through_to_magic_bytes() {
+ // The 21-reference case: an extension OOXML §M.1.1 does not list, over
+ // bytes that are plainly JPEG. Extension-only detection returns
+ // `Unknown` and the painter drops the image.
+ let jpeg = [0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, b'J', b'F', b'I', b'F'];
+ assert_eq!(
+ ImageFormat::detect("ppt/media/image7.jfif", &jpeg),
+ ImageFormat::Jpeg
+ );
+ }
+}
diff --git a/crates/liteparse-ooxml/src/pptx/mod.rs b/crates/liteparse-ooxml/src/pptx/mod.rs
index 6b8634e..596f81d 100644
--- a/crates/liteparse-ooxml/src/pptx/mod.rs
+++ b/crates/liteparse-ooxml/src/pptx/mod.rs
@@ -12,6 +12,7 @@
pub mod cascade;
pub mod geometry;
+pub mod media;
pub mod package;
pub mod shapes;
pub mod text;
@@ -22,6 +23,7 @@ pub use cascade::{
apply_slide, background_fill, resolve_background,
};
pub use geometry::{GeometryStats, SlideRect, apply_slide_geometry};
+pub use media::MediaCache;
pub use package::{EMU_PER_POINT, Part, PresentationInfo, PresentationPackage, SlideParts, walk};
pub use shapes::{
AutoShape, Background, Connector, GraphicFrame, GraphicFramePayload, Group, Placeholder,
diff --git a/crates/liteparse-ooxml/src/render/layout/build/floating.rs b/crates/liteparse-ooxml/src/render/layout/build/floating.rs
index 4952dfc..737f2da 100644
--- a/crates/liteparse-ooxml/src/render/layout/build/floating.rs
+++ b/crates/liteparse-ooxml/src/render/layout/build/floating.rs
@@ -249,6 +249,12 @@ pub(super) fn extract_floating_shapes(
&crate::render::resolve::drawing_color::DrawingColorContext::new(
ctx.resolved.theme.as_ref(),
),
+ // No media channel on the Word shape path. A `w:drawing` picture
+ // reaches the page as a `DrawCommand::Image` through
+ // `resolve::images`, not as a shape fill, so a blip *fill* on a
+ // Word autoshape stays unpainted — as it was before this argument
+ // existed. Wiring it is a DOCX-side step with its own corpus.
+ None,
);
// §20.1.7.6 transform attributes (rotation/flip) live on the shape's
diff --git a/crates/liteparse-ooxml/src/render/layout/draw_command.rs b/crates/liteparse-ooxml/src/render/layout/draw_command.rs
index b372958..7c5b7ed 100644
--- a/crates/liteparse-ooxml/src/render/layout/draw_command.rs
+++ b/crates/liteparse-ooxml/src/render/layout/draw_command.rs
@@ -300,7 +300,10 @@ pub enum ResolvedGradientKind {
}
/// Painter-ready image fill — pointer to decoded bytes + source crop.
-#[derive(Clone, Debug)]
+///
+/// `Debug` is hand-written (see below): the derived one prints every byte of
+/// the image, which turns any `{:?}` of a command list into megabytes.
+#[derive(Clone)]
pub struct ResolvedBlip {
pub data: std::sync::Arc<[u8]>,
pub format: crate::model::ImageFormat,
@@ -312,6 +315,23 @@ pub struct ResolvedBlip {
pub src_rect: Option<PtRect>,
}
+impl std::fmt::Debug for ResolvedBlip {
+ /// Identity and shape, never contents. A `DrawCommand` list holding a
+ /// full-slide photograph is routine, and a derived `Debug` makes printing
+ /// one — in a probe, a test failure, a `log::debug!` — dump the whole JPEG.
+ /// The pointer is included because it *is* the identity the rasterizer's
+ /// bitmap cache keys on, so two placements sharing one decode are visible
+ /// here rather than having to be inferred.
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("ResolvedBlip")
+ .field("format", &self.format)
+ .field("bytes", &self.data.len())
+ .field("data_ptr", &self.data.as_ptr())
+ .field("src_rect", &self.src_rect)
+ .finish()
+ }
+}
+
/// Painter-ready pattern fill — foreground/background + preset id.
#[derive(Clone, Debug)]
pub struct ResolvedPattern {
diff --git a/crates/liteparse-ooxml/src/render/raster.rs b/crates/liteparse-ooxml/src/render/raster.rs
index 16f316d..15865e0 100644
--- a/crates/liteparse-ooxml/src/render/raster.rs
+++ b/crates/liteparse-ooxml/src/render/raster.rs
@@ -13,13 +13,17 @@
//! Fidelity tiers, mirroring the vendored painter's own tiering:
//! - **Rendered faithfully**: text (monochrome outlines), underlines, lines,
//! rects, images (PNG/JPEG/GIF/BMP/TIFF/WebP incl. `src_rect` crops), shape
-//! paths with solid fills and solid/dashed strokes.
+//! paths with solid or **stretched-blip** fills and solid/dashed strokes. A
+//! blip fill clips to the path, so a picture in an `ellipse` or `custGeom`
+//! frame is cropped to its shape rather than drawn as a rectangle.
//! - **Approximated**: gradient fills collapse to their mean stop color
//! (logged once); emoji clusters draw monochrome outlines when the resolved
//! face has them, else nothing.
-//! - **Skipped**: blip/pattern fills, effects (shadow/glow), EMF/WMF/SVG
-//! media (no decoder — same set `collect_images` skips), color glyph
-//! tables. Each skip logs once per process, never per command.
+//! - **Skipped**: tiled blip fills (refused upstream in `resolve_fill` rather
+//! than stretched, which would be wrong rather than coarse), pattern fills,
+//! effects (shadow/glow), EMF/WMF/SVG media (no decoder — same set
+//! `collect_images` skips), color glyph tables. Each skip logs once per
+//! process, never per command.
//!
//! The output is plain `{rgba, width, height}` so consumers need no tiny-skia
//! types; the buffer is effectively straight (non-premultiplied) RGBA because
@@ -99,6 +103,9 @@ pub fn rasterize_page(
// covers text/shading — rare, and its fill still paints. A shape's own
// text-box text is emitted as separate `Text` commands, so it stays over
// its fill in the ink pass.
+ // Outside the pass loop: the same image can be a shape fill and a placed
+ // picture on one page, and every pass walks the whole command list.
+ let mut images = ImageCache::default();
for pass in [
RasterPass::Shape,
RasterPass::Shading,
@@ -200,8 +207,22 @@ pub fn rasterize_page(
let transform = device.pre_concat(place_transform(
*origin, *rotation, *flip_h, *flip_v, *extent,
));
+ // Decoded once per `Path`, not once per subpath: a
+ // `custGeom` picture frame routinely has several.
+ let blip = match fill {
+ ResolvedFill::Blip(b) => images.get(&b.data, b.format, b.src_rect.as_ref()),
+ _ => None,
+ };
for sub in paths {
- draw_subpath(&mut pixmap, sub, fill, stroke.as_ref(), transform);
+ draw_subpath(
+ &mut pixmap,
+ sub,
+ fill,
+ blip,
+ *extent,
+ stroke.as_ref(),
+ transform,
+ );
}
}
// Non-drawing commands: link/destination/outline metadata
@@ -457,18 +478,59 @@ fn draw_image(
}
_ => {}
}
- let Ok(decoded) = image::load_from_memory(&media.data) else {
- log::warn!(
- "undecodable {:?} media ({} bytes)",
- media.format,
- media.data.len()
- );
+ let Some(src) = decode_media(&media.data, media.format, src_rect) else {
+ return;
+ };
+ let (iw, ih) = (src.width(), src.height());
+
+ let sx = rect.size.width.raw() / iw as f32;
+ let sy = rect.size.height.raw() / ih as f32;
+ if sx <= 0.0 || sy <= 0.0 {
return;
+ }
+ let transform = device.pre_concat(
+ Transform::from_translate(rect.origin.x.raw(), rect.origin.y.raw())
+ .pre_concat(Transform::from_scale(sx, sy)),
+ );
+ let paint = PixmapPaint {
+ quality: tiny_skia::FilterQuality::Bilinear,
+ ..PixmapPaint::default()
+ };
+ pixmap.draw_pixmap(0, 0, src.as_ref(), &paint, transform, None);
+}
+
+/// Decode one media entry into a premultiplied tiny-skia pixmap, applying the
+/// §20.1.10.48 `srcRect` crop.
+///
+/// **The single decode path**, shared by [`DrawCommand::Image`] (Word's placed
+/// pictures) and by the blip *fill* on a [`DrawCommand::Path`] (PowerPoint's).
+/// The crop is the reason it has to be shared rather than merely similar: the
+/// fraction rect both callers hand in comes from one converter
+/// (`relative_rect_to_fraction`), and a second copy of the pixel arithmetic
+/// here would let a cropped picture and a cropped fill drift apart while both
+/// kept passing every count.
+fn decode_media(data: &[u8], format: ImageFormat, src_rect: Option<&PtRect>) -> Option<Pixmap> {
+ static VECTOR_ONCE: Once = Once::new();
+ match format {
+ ImageFormat::Emf | ImageFormat::Wmf | ImageFormat::Svg | ImageFormat::Unknown => {
+ VECTOR_ONCE.call_once(|| {
+ log::info!("EMF/WMF/SVG media are not rasterized; placements render blank");
+ });
+ return None;
+ }
+ _ => {}
+ }
+ let decoded = match image::load_from_memory(data) {
+ Ok(d) => d,
+ Err(_) => {
+ log::warn!("undecodable {:?} media ({} bytes)", format, data.len());
+ return None;
+ }
};
let mut rgba = decoded.to_rgba8();
// §20.1.10.48 srcRect: fractional crop of the natural extent, applied
- // before stretching into `rect`.
+ // before stretching into the destination.
if let Some(crop) = src_rect {
let (w, h) = (rgba.width() as f32, rgba.height() as f32);
let x = (crop.origin.x.raw() * w).round().clamp(0.0, w) as u32;
@@ -491,27 +553,49 @@ fn draw_image(
px[2] = ((px[2] as u16 * a) / 255) as u8;
}
}
- let Some(size) = tiny_skia::IntSize::from_wh(iw, ih) else {
- return;
- };
- let Some(src) = Pixmap::from_vec(data, size) else {
- return;
- };
+ let size = tiny_skia::IntSize::from_wh(iw, ih)?;
+ Pixmap::from_vec(data, size)
+}
- let sx = rect.size.width.raw() / iw as f32;
- let sy = rect.size.height.raw() / ih as f32;
- if sx <= 0.0 || sy <= 0.0 {
- return;
+/// Decoded bitmaps for one page, keyed by image identity and crop.
+///
+/// A deck puts one logo on 60 slides and one background photograph behind
+/// every shape on a slide; without this, each placement re-runs a full PNG
+/// decode. The key's first half is the `Arc`'s **pointer**, which is exactly
+/// the identity `MediaEntry` was built to preserve — `resolve` hands out
+/// clones of one allocation per media part, so pointer equality means "the
+/// same image" without hashing megabytes to find out.
+///
+/// The crop is part of the key because two placements of one image may crop it
+/// differently — the same photograph cropped square for a thumbnail and wide
+/// for a banner is two bitmaps, and keying on the pointer alone would serve
+/// the second placement the first one's crop.
+#[derive(Default)]
+struct ImageCache {
+ entries: std::collections::HashMap<(usize, [u32; 4]), Option<Pixmap>>,
+}
+
+impl ImageCache {
+ fn get(
+ &mut self,
+ data: &std::sync::Arc<[u8]>,
+ format: ImageFormat,
+ src_rect: Option<&PtRect>,
+ ) -> Option<&Pixmap> {
+ let crop = src_rect.map_or([0u32; 4], |r| {
+ [
+ r.origin.x.raw().to_bits(),
+ r.origin.y.raw().to_bits(),
+ r.size.width.raw().to_bits(),
+ r.size.height.raw().to_bits(),
+ ]
+ });
+ let key = (data.as_ptr() as usize, crop);
+ self.entries
+ .entry(key)
+ .or_insert_with(|| decode_media(data, format, src_rect))
+ .as_ref()
}
- let transform = device.pre_concat(
- Transform::from_translate(rect.origin.x.raw(), rect.origin.y.raw())
- .pre_concat(Transform::from_scale(sx, sy)),
- );
- let paint = PixmapPaint {
- quality: tiny_skia::FilterQuality::Bilinear,
- ..PixmapPaint::default()
- };
- pixmap.draw_pixmap(0, 0, src.as_ref(), &paint, transform, None);
}
// ─── Shape paths ────────────────────────────────────────────────────────────
@@ -520,15 +604,17 @@ fn draw_subpath(
pixmap: &mut Pixmap,
sub: &SubPath,
fill: &ResolvedFill,
+ blip: Option<&Pixmap>,
+ extent: crate::render::geometry::PtSize,
stroke: Option<&ResolvedStroke>,
transform: Transform,
) {
let Some(path) = build_path(sub) else { return };
- if sub.fill_mode != PathFillMode::None {
- if let Some(paint) = fill_paint(fill) {
- pixmap.fill_path(&path, &paint, FillRule::EvenOdd, transform, None);
- }
+ if sub.fill_mode != PathFillMode::None
+ && let Some(paint) = fill_paint(fill, blip, extent)
+ {
+ pixmap.fill_path(&path, &paint, FillRule::EvenOdd, transform, None);
}
if sub.stroked
&& let Some(s) = stroke
@@ -630,10 +716,20 @@ fn build_path(sub: &SubPath) -> Option<tiny_skia::Path> {
pb.finish()
}
-/// Tier-0 fill: solid faithfully; gradient as the mean stop color (logged
-/// once); blip/pattern skipped (logged once). Inventing pixels quietly is the
-/// silent-corruption trap; a one-time log keeps the approximation loud.
-fn fill_paint(fill: &ResolvedFill) -> Option<Paint<'static>> {
+/// Tier-0 fill: solid and blip faithfully; gradient as the mean stop color
+/// (logged once); pattern skipped (logged once). Inventing pixels quietly is
+/// the silent-corruption trap; a one-time log keeps the approximation loud.
+///
+/// `blip` is the already-decoded bitmap for a [`ResolvedFill::Blip`] and
+/// `extent` the shape's local size — the box the image stretches into. The
+/// decode happens in the caller because it needs `&mut ImageCache` while this
+/// function borrows the result, and because one `Path` with four subpaths must
+/// decode once, not four times.
+fn fill_paint<'a>(
+ fill: &ResolvedFill,
+ blip: Option<&'a Pixmap>,
+ extent: crate::render::geometry::PtSize,
+) -> Option<Paint<'a>> {
static GRADIENT_ONCE: Once = Once::new();
static TEXTURE_ONCE: Once = Once::new();
match fill {
@@ -662,9 +758,40 @@ fn fill_paint(fill: &ResolvedFill) -> Option<Paint<'static>> {
};
(c.a > 0.0).then(|| solid(rgba_color(c)))
}
- ResolvedFill::Blip(_) | ResolvedFill::Pattern(_) => {
+ ResolvedFill::Blip(_) => {
+ // `None` here is an undecodable or missing image, already logged
+ // by `decode_media`. The path then paints nothing, which is the
+ // honest outcome — an EMF drawn as a grey box would be a wrong
+ // slide rather than an incomplete one.
+ let src = blip?;
+ let (iw, ih) = (src.width() as f32, src.height() as f32);
+ let (ew, eh) = (extent.width.raw(), extent.height.raw());
+ if iw <= 0.0 || ih <= 0.0 || ew <= 0.0 || eh <= 0.0 {
+ return None;
+ }
+ // §20.1.8.14 `a:stretch`: the image fills the shape's box, aspect
+ // ratio not preserved. Tiling never reaches here — `resolve_fill`
+ // refuses `a:tile` rather than letting it stretch silently.
+ //
+ // `SpreadMode::Pad` rather than `Clamp`-to-transparent so that a
+ // path whose geometry runs a fraction of a point past the extent
+ // — an antialiased `roundRect` corner, a stroked edge — takes the
+ // edge pixel instead of a transparent notch.
+ Some(Paint {
+ shader: tiny_skia::Pattern::new(
+ src.as_ref(),
+ tiny_skia::SpreadMode::Pad,
+ tiny_skia::FilterQuality::Bilinear,
+ 1.0,
+ Transform::from_scale(ew / iw, eh / ih),
+ ),
+ anti_alias: true,
+ ..Paint::default()
+ })
+ }
+ ResolvedFill::Pattern(_) => {
TEXTURE_ONCE.call_once(|| {
- log::info!("blip/pattern fills are not rasterized; interiors render unfilled");
+ log::info!("pattern fills are not rasterized; interiors render unfilled");
});
None
}
diff --git a/crates/liteparse-ooxml/src/render/resolve/images.rs b/crates/liteparse-ooxml/src/render/resolve/images.rs
index 0d570c8..21f6b99 100644
--- a/crates/liteparse-ooxml/src/render/resolve/images.rs
+++ b/crates/liteparse-ooxml/src/render/resolve/images.rs
@@ -19,6 +19,23 @@ pub struct MediaEntry {
pub format: ImageFormat,
}
+/// The media one package part can reach, keyed by the `r:embed` ids **that
+/// part itself declares**.
+///
+/// Per part, not per package, and that is the load-bearing half rather than a
+/// caching detail. A slide, its layout and its master each carry their own
+/// `.rels`, and `rId1` in all three routinely names three different images —
+/// so an inherited picture resolved against the *slide's* table returns a real
+/// photograph from the wrong relationship. That is the same failure class as
+/// `bgRef@idx` reading `fillStyleLst` and as a deck-wide theme colouring a
+/// second master's slides: a well-typed answer that is wrong, and invisible to
+/// any gate that only asks whether resolution succeeded.
+///
+/// A missing key means "this part declares no such relationship, or it points
+/// outside the package" (`r:link`), which the caller reports rather than
+/// silently painting nothing.
+pub type PartMedia = std::collections::HashMap<RelId, MediaEntry>;
+
/// Extract the embedded image relationship ID from a DrawingML Image.
/// Navigates: Image → graphic → Picture → blip_fill → blip → embed.
pub fn extract_image_rel_id(image: &Image) -> Option<&RelId> {
diff --git a/crates/liteparse-ooxml/src/render/resolve/shape_visuals.rs b/crates/liteparse-ooxml/src/render/resolve/shape_visuals.rs
index 6919dba..27387dd 100644
--- a/crates/liteparse-ooxml/src/render/resolve/shape_visuals.rs
+++ b/crates/liteparse-ooxml/src/render/resolve/shape_visuals.rs
@@ -9,17 +9,18 @@
use crate::model::dimension::{Dimension, Emu};
use crate::model::{
- DrawingFill, Effect, GlowEffect, InnerShadowEffect, LineCap, LineDash, LineJoin,
+ BlipFillKind, DrawingFill, Effect, GlowEffect, InnerShadowEffect, LineCap, LineDash, LineJoin,
OuterShadowEffect, Outline, PathFillMode, PresetShadowEffect, ReflectionEffect,
ShapeProperties, SoftEdgeEffect, StyleMatrixRef, Theme,
};
use crate::render::dimension::Pt;
use crate::render::geometry::PtOffset;
use crate::render::layout::draw_command::{
- ResolvedDashPattern, ResolvedEffect, ResolvedFill, ResolvedLineCap, ResolvedLineJoin,
- ResolvedStroke,
+ ResolvedBlip, ResolvedDashPattern, ResolvedEffect, ResolvedFill, ResolvedLineCap,
+ ResolvedLineJoin, ResolvedStroke,
};
use crate::render::resolve::drawing_color::{DrawingColorContext, Rgba, resolve_drawing_color};
+use crate::render::resolve::images::{PartMedia, relative_rect_to_fraction};
/// Resolved bundle for one shape.
pub struct ResolvedVisuals {
@@ -47,6 +48,7 @@ pub fn resolve_shape_visuals(
style_effect_ref: Option<&StyleMatrixRef>,
style_fill_ref: Option<&StyleMatrixRef>,
ctx: &DrawingColorContext<'_>,
+ media: Option<&PartMedia>,
) -> ResolvedVisuals {
let theme = ctx.theme;
let props = match props {
@@ -54,7 +56,7 @@ pub fn resolve_shape_visuals(
None => {
// No spPr, but a bare `<wps:style>` may still carry a fillRef.
return ResolvedVisuals {
- fill: resolve_theme_fill(style_fill_ref, theme, ctx),
+ fill: resolve_theme_fill(style_fill_ref, theme, ctx, media),
stroke: None,
effects: Vec::new(),
};
@@ -64,8 +66,8 @@ pub fn resolve_shape_visuals(
// §20.1.4.1.13: a direct spPr fill wins; otherwise fall back to the theme
// fill style referenced by `<a:fillRef>` (recolored by its phClr).
let fill = match props.fill.as_ref() {
- Some(f) => resolve_fill(f, ctx),
- None => resolve_theme_fill(style_fill_ref, theme, ctx),
+ Some(f) => resolve_fill(f, ctx, media),
+ None => resolve_theme_fill(style_fill_ref, theme, ctx, media),
};
let theme_ln = theme_line_style(style_line_ref, theme);
@@ -100,6 +102,7 @@ fn resolve_theme_fill(
style_fill_ref: Option<&StyleMatrixRef>,
theme: Option<&Theme>,
ctx: &DrawingColorContext<'_>,
+ media: Option<&PartMedia>,
) -> ResolvedFill {
let Some(r) = style_fill_ref else {
return ResolvedFill::None;
@@ -119,7 +122,7 @@ fn resolve_theme_fill(
Some(c) => ctx.with_placeholder(resolve_drawing_color(c, ctx)),
None => *ctx,
};
- resolve_fill(fill, &fill_ctx)
+ resolve_fill(fill, &fill_ctx, media)
}
/// §19.3.1.3: resolve a slide/layout/master `<p:bgRef>` against the theme.
@@ -141,6 +144,7 @@ pub fn resolve_background_fill(
bg_ref: &StyleMatrixRef,
theme: Option<&Theme>,
ctx: &DrawingColorContext<'_>,
+ media: Option<&PartMedia>,
) -> ResolvedFill {
// §20.1.4.2.19: 0 is the no-reference sentinel, here meaning "no
// background" rather than "inherit".
@@ -162,7 +166,7 @@ pub fn resolve_background_fill(
Some(c) => ctx.with_placeholder(resolve_drawing_color(c, ctx)),
None => *ctx,
};
- resolve_fill(fill, &fill_ctx)
+ resolve_fill(fill, &fill_ctx, media)
}
/// Look up a theme line style by its 1-based `lnRef` index.
@@ -210,7 +214,18 @@ pub fn default_path_fill_for_stroked_shape() -> PathFillMode {
// ── Fills ───────────────────────────────────────────────────────────────────
-pub fn resolve_fill(fill: &DrawingFill, ctx: &DrawingColorContext<'_>) -> ResolvedFill {
+/// Resolve one fill descriptor.
+///
+/// `media` is the [`PartMedia`] of the part that **declares** this fill, and
+/// `None` means the caller has no media channel at all (the DOCX shape path
+/// today). A blip fill without one resolves to [`ResolvedFill::None`]: the
+/// alternative — resolving against whatever table happened to be in scope —
+/// is how an inherited picture acquires the slide's `rId1` instead of its own.
+pub fn resolve_fill(
+ fill: &DrawingFill,
+ ctx: &DrawingColorContext<'_>,
+ media: Option<&PartMedia>,
+) -> ResolvedFill {
match fill {
DrawingFill::None => ResolvedFill::None,
DrawingFill::Solid(color) => ResolvedFill::Solid(resolve_drawing_color(color, ctx)),
@@ -237,10 +252,7 @@ pub fn resolve_fill(fill: &DrawingFill, ctx: &DrawingColorContext<'_>) -> Resolv
};
ResolvedFill::Gradient(ResolvedGradient { stops, kind })
}
- DrawingFill::Blip(_) => {
- log::warn!("shape_visuals: blip fill not yet resolved (Tier 2)");
- ResolvedFill::None
- }
+ DrawingFill::Blip(blip_fill) => resolve_blip_fill(blip_fill, media),
DrawingFill::Pattern(_) => {
log::warn!("shape_visuals: pattern fill not yet resolved (Tier 3)");
ResolvedFill::None
@@ -254,6 +266,60 @@ pub fn resolve_fill(fill: &DrawingFill, ctx: &DrawingColorContext<'_>) -> Resolv
}
}
+/// §20.1.8.14 `a:blipFill` → the bytes the painter stretches into the path.
+///
+/// Four of the five ways this returns `None` are *correct* readings of the
+/// file rather than gaps, which is why they are separated by a log level the
+/// caller can act on:
+///
+/// * **no `a:blip` child** — an empty picture placeholder ("click to add
+/// picture"). 157 on the PPTX corpus, every one of them in a layout or
+/// master, and painting anything for them would stamp a phantom frame on
+/// every slide under that rung.
+/// * **`r:link`** — the image lives outside the package; there are no bytes to
+/// draw and never will be from this file alone.
+/// * **an `r:embed` the part does not declare**, or one whose target is
+/// missing from the zip: a broken package, reported rather than guessed at.
+/// * **`a:tile`** — the image repeats rather than stretching. Returned as
+/// `None` on purpose: painting a tile stretched is a *wrong* slide in
+/// exactly the way an unbuildable preset drawn as its bounding box would be,
+/// and the corpus has **zero** of them, so strictness here costs nothing and
+/// keeps the first real one from rendering silently wrong.
+///
+/// The crop goes through [`relative_rect_to_fraction`], shared with the
+/// picture path, so a cropped fill and a cropped picture cannot diverge.
+pub fn resolve_blip_fill(fill: &crate::model::BlipFill, media: Option<&PartMedia>) -> ResolvedFill {
+ let Some(blip) = fill.blip.as_ref() else {
+ log::debug!("shape_visuals: blipFill with no a:blip — empty picture placeholder");
+ return ResolvedFill::None;
+ };
+ if let BlipFillKind::Tile(_) = fill.fill_kind {
+ log::warn!("shape_visuals: tiled blip fill not painted — a stretch would be wrong");
+ return ResolvedFill::None;
+ }
+ let Some(embed) = blip.embed.as_ref() else {
+ // `r:link` is the only other way to name an image, and it is external.
+ log::debug!("shape_visuals: blip has no r:embed (external r:link?) — nothing to paint");
+ return ResolvedFill::None;
+ };
+ let Some(media) = media else {
+ log::debug!("shape_visuals: blip fill on a path with no media channel");
+ return ResolvedFill::None;
+ };
+ let Some(entry) = media.get(embed) else {
+ log::warn!(
+ "shape_visuals: blip r:embed {} not declared by the part that uses it",
+ embed.as_str()
+ );
+ return ResolvedFill::None;
+ };
+ ResolvedFill::Blip(ResolvedBlip {
+ data: entry.data.clone(),
+ format: entry.format,
+ src_rect: fill.src_rect.as_ref().and_then(relative_rect_to_fraction),
+ })
+}
+
// ── Outline → Stroke ────────────────────────────────────────────────────────
fn resolve_outline(
@@ -473,7 +539,14 @@ mod tests {
#[test]
fn empty_props_resolves_to_none_visuals() {
- let v = resolve_shape_visuals(None, None, None, None, &DrawingColorContext::new(None));
+ let v = resolve_shape_visuals(
+ None,
+ None,
+ None,
+ None,
+ &DrawingColorContext::new(None),
+ None,
+ );
assert!(matches!(v.fill, ResolvedFill::None));
assert!(v.stroke.is_none());
assert!(v.effects.is_empty());
@@ -495,6 +568,7 @@ mod tests {
None,
None,
&DrawingColorContext::new(None),
+ None,
);
let ResolvedFill::Solid(c) = v.fill else {
panic!()
@@ -525,6 +599,7 @@ mod tests {
None,
None,
&DrawingColorContext::new(None),
+ None,
);
let s = v.stroke.unwrap();
assert_eq!(s.width, Pt::new(0.75));
@@ -557,6 +632,7 @@ mod tests {
None,
None,
&DrawingColorContext::new(None),
+ None,
);
let s = v.stroke.unwrap();
assert_eq!(s.width, Pt::new(0.75));
@@ -586,6 +662,7 @@ mod tests {
None,
None,
&DrawingColorContext::new(None),
+ None,
);
assert!(v.stroke.is_none());
}
@@ -642,6 +719,7 @@ mod tests {
None,
None,
&DrawingColorContext::new(Some(&theme)),
+ None,
);
let s = v.stroke.unwrap();
assert_eq!(s.width, Pt::new(2.0));
@@ -684,6 +762,7 @@ mod tests {
Some(&er),
None,
&DrawingColorContext::new(Some(&theme)),
+ None,
);
assert_eq!(v.effects.len(), 1);
}
@@ -737,6 +816,7 @@ mod tests {
Some(&er),
None,
&DrawingColorContext::new(Some(&theme)),
+ None,
);
let ResolvedEffect::OuterShadow {
blur_radius, color, ..
@@ -775,6 +855,7 @@ mod tests {
None,
None,
&DrawingColorContext::new(None),
+ None,
);
assert_eq!(v.effects.len(), 1);
let ResolvedEffect::OuterShadow {
@@ -818,6 +899,7 @@ mod tests {
None,
Some(&fill_ref),
&DrawingColorContext::new(Some(&theme)),
+ None,
);
let ResolvedFill::Solid(c) = v.fill else {
panic!("expected solid theme fill, got {:?}", v.fill);
@@ -849,6 +931,7 @@ mod tests {
None,
Some(&fill_ref),
&DrawingColorContext::new(Some(&theme)),
+ None,
);
let ResolvedFill::Solid(c) = v.fill else {
panic!("expected solid fill");
@@ -870,7 +953,115 @@ mod tests {
None,
Some(&fill_ref),
&DrawingColorContext::new(Some(&theme)),
+ None,
);
assert!(matches!(v.fill, ResolvedFill::None));
}
+
+ // ── blip fills ──────────────────────────────────────────────────────────
+
+ fn blip_fill(embed: Option<&str>, kind: BlipFillKind) -> crate::model::BlipFill {
+ crate::model::BlipFill {
+ rotate_with_shape: None,
+ dpi: None,
+ blip: embed.map(|e| crate::model::Blip {
+ embed: Some(crate::model::RelId::new(e)),
+ link: None,
+ compression: None,
+ }),
+ src_rect: None,
+ fill_kind: kind,
+ }
+ }
+
+ fn media_with(id: &str) -> PartMedia {
+ let mut m = PartMedia::new();
+ m.insert(
+ crate::model::RelId::new(id),
+ crate::render::resolve::images::MediaEntry {
+ data: std::sync::Arc::from(&b"\x89PNG\r\n\x1a\n"[..]),
+ format: crate::model::ImageFormat::Png,
+ },
+ );
+ m
+ }
+
+ #[test]
+ fn blip_resolves_against_its_own_parts_table() {
+ let media = media_with("rId7");
+ let fill = blip_fill(Some("rId7"), BlipFillKind::Unspecified);
+ let ResolvedFill::Blip(b) = resolve_blip_fill(&fill, Some(&media)) else {
+ panic!("expected a blip fill");
+ };
+ assert_eq!(b.format, crate::model::ImageFormat::Png);
+ assert!(b.src_rect.is_none(), "no a:srcRect declared");
+ }
+
+ #[test]
+ fn blip_embed_absent_from_this_parts_table_is_not_painted() {
+ // The inherited-`rId1` trap, as a unit test: a layout picture's id
+ // looked up in the *slide's* table must resolve to nothing rather than
+ // to whatever that table happens to hold under the same id.
+ let media = media_with("rId1");
+ let fill = blip_fill(Some("rId9"), BlipFillKind::Unspecified);
+ assert!(matches!(
+ resolve_blip_fill(&fill, Some(&media)),
+ ResolvedFill::None
+ ));
+ }
+
+ #[test]
+ fn blip_fill_with_no_blip_child_is_an_empty_placeholder() {
+ // 157 on the PPTX corpus, all in layouts and masters: "click to add
+ // picture". Correctly paints nothing.
+ let fill = blip_fill(None, BlipFillKind::Unspecified);
+ assert!(matches!(
+ resolve_blip_fill(&fill, Some(&media_with("rId1"))),
+ ResolvedFill::None
+ ));
+ }
+
+ #[test]
+ fn tiled_blip_is_refused_rather_than_stretched() {
+ // A tile drawn stretched is a *wrong* slide, not a coarse one — the
+ // same rule that forbids drawing an unbuildable preset as its bbox.
+ let media = media_with("rId7");
+ let tile = BlipFillKind::Tile(crate::model::TileFill {
+ tx: None,
+ ty: None,
+ sx: None,
+ sy: None,
+ flip: None,
+ alignment: None,
+ });
+ let fill = blip_fill(Some("rId7"), tile);
+ assert!(matches!(
+ resolve_blip_fill(&fill, Some(&media)),
+ ResolvedFill::None
+ ));
+ }
+
+ #[test]
+ fn blip_with_no_media_channel_is_not_painted() {
+ let fill = blip_fill(Some("rId7"), BlipFillKind::Unspecified);
+ assert!(matches!(resolve_blip_fill(&fill, None), ResolvedFill::None));
+ }
+
+ #[test]
+ fn blip_src_rect_uses_the_shared_converter() {
+ let media = media_with("rId7");
+ let mut fill = blip_fill(Some("rId7"), BlipFillKind::Unspecified);
+ fill.src_rect = Some(crate::model::RelativeRect {
+ left: Some(Dimension::new(25000)),
+ top: None,
+ right: Some(Dimension::new(10000)),
+ bottom: Some(Dimension::new(10000)),
+ });
+ let ResolvedFill::Blip(b) = resolve_blip_fill(&fill, Some(&media)) else {
+ panic!("expected a blip fill");
+ };
+ let r = b.src_rect.expect("crop present");
+ assert!((r.origin.x.raw() - 0.25).abs() < 1e-5);
+ assert!((r.size.width.raw() - 0.65).abs() < 1e-5);
+ }
}
diff --git a/crates/liteparse/src/office/pptx.rs b/crates/liteparse/src/office/pptx.rs
index 7b8b889..037d3f7 100644
--- a/crates/liteparse/src/office/pptx.rs
+++ b/crates/liteparse/src/office/pptx.rs
@@ -19,6 +19,7 @@ use liteparse_ooxml::pptx::{
PlaceholderTextStyles, PresentationPackage, ResolvedTextStyle, Shape, ShapeKind, Table,
TextBody, TextCascade, TextParagraph, TextStyles,
};
+use liteparse_ooxml::render::resolve::images::PartMedia;
use std::collections::HashMap;
use crate::error::LiteParseError;
@@ -127,6 +128,11 @@ pub struct Deck {
/// §19.3.1.39 `p:sldLayout/@showMasterSp` — whether slides under this
/// layout draw the master's shapes. 25 of the corpus's 415 layouts say no.
layout_shows_master: HashMap<String, bool>,
+ /// Image relationships per part, over one shared pool of bytes. On the
+ /// deck for the same reason the other rungs are: a layout's media table is
+ /// rebuilt 60 times otherwise, and its `Arc`s must be the *same* `Arc`s
+ /// each time or the rasterizer's bitmap cache misses on every slide.
+ media: pptx::MediaCache,
default_text_style: ListStyle,
/// The rung-7-only defaults a slide falls back to when its master has no
/// entry. Stored on the deck rather than built as a local in the walk so
@@ -187,6 +193,21 @@ pub struct PreparedSlide<'d> {
/// opt-outs and a deck whose layout parse silently failed would report the
/// same numbers.
pub declined: [bool; 2],
+ /// The slide's own `r:embed` table, and its master's and layout's in the
+ /// same `[master, layout]` order as `inherited`.
+ ///
+ /// Three tables rather than one because an `r:id` is scoped to the part
+ /// that writes it: a layout picture's `rId1` and the slide's `rId1` are
+ /// unrelated relationships that regularly name different images, so a
+ /// single merged table would paint real photographs in the wrong places.
+ pub media: &'d PartMedia,
+ pub inherited_media: [&'d PartMedia; 2],
+ /// The table for the part the **background** came from, which is the
+ /// master's on 1,125 corpus slides and the slide's own on 58. Carried
+ /// separately rather than derived by the caller, because the rung is
+ /// already known here (`BackgroundSource`) and re-deriving it at the paint
+ /// site is how the two would drift.
+ pub background_media: &'d PartMedia,
layout_text: Option<&'d PlaceholderTextStyles>,
master_text: Option<&'d PlaceholderTextStyles>,
deck_defaults: &'d DeckTextDefaults,
@@ -224,6 +245,7 @@ impl Deck {
master_shapes: HashMap::new(),
layout_shapes: HashMap::new(),
layout_shows_master: HashMap::new(),
+ media: pptx::MediaCache::new(),
fallback_defaults: DeckTextDefaults {
master_styles: TextStyles::default(),
default_text_style: default_text_style.clone(),
@@ -237,8 +259,21 @@ impl Deck {
///
/// `None` when the shape tree will not parse — fail-open, the same slide
/// is skipped by every walk.
- pub fn prepare(&mut self, slide: &pptx::SlideParts) -> Option<PreparedSlide<'_>> {
+ pub fn prepare(
+ &mut self,
+ pkg: &PresentationPackage,
+ slide: &pptx::SlideParts,
+ ) -> Option<PreparedSlide<'_>> {
self.prime(slide);
+ // Primed before anything borrows, because building a table needs
+ // `&mut self` and the three that come out of it are held at once.
+ self.media.part_media(pkg, &slide.slide);
+ for part in [slide.layout.as_ref(), slide.master.as_ref()]
+ .into_iter()
+ .flatten()
+ {
+ self.media.part_media(pkg, part);
+ }
let part = pptx::parse_slide_part(&slide.slide.xml).ok()?;
let mut shapes = part.shapes;
@@ -320,12 +355,27 @@ impl Deck {
.master
.as_ref()
.and_then(|m| self.master_text.get(&m.path));
+ let layout_path = slide.layout.as_ref().map(|l| l.path.as_str());
+ let master_path = slide.master.as_ref().map(|m| m.path.as_str());
+ // The background's own rung, not the slide's. `resolve_background`
+ // already decided which part won; asking it again here is the whole
+ // point of carrying `BackgroundSource` on the result.
+ let background_media = self
+ .media
+ .get(match background.as_ref().map(|(src, _)| src) {
+ Some(BackgroundSource::Layout) => layout_path,
+ Some(BackgroundSource::Master) => master_path,
+ _ => Some(slide.slide.path.as_str()),
+ });
Some(PreparedSlide {
shapes,
background,
color_map,
inherited,
declined: [!shows_master, !shows_layout],
+ media: self.media.get(Some(slide.slide.path.as_str())),
+ inherited_media: [self.media.get(master_path), self.media.get(layout_path)],
+ background_media,
layout_text: slide
.layout
.as_ref()
@@ -339,7 +389,7 @@ impl Deck {
let mut out = Vec::new();
for (idx, slide) in pkg.slides.iter().enumerate() {
- let Some(prepared) = self.prepare(slide) else {
+ let Some(prepared) = self.prepare(pkg, slide) else {
continue;
};
let shapes = &prepared.shapes;
diff --git a/crates/liteparse/src/office/pptx_layout.rs b/crates/liteparse/src/office/pptx_layout.rs
index 1b03846..05ecb37 100644
--- a/crates/liteparse/src/office/pptx_layout.rs
+++ b/crates/liteparse/src/office/pptx_layout.rs
@@ -74,8 +74,9 @@ use liteparse_ooxml::render::layout::shape_body::{layout_shape_body, measure_sha
use liteparse_ooxml::render::resolve::color::{RgbColor, rgb_from_u32};
use liteparse_ooxml::render::resolve::drawing_color::{DrawingColorContext, resolve_drawing_color};
use liteparse_ooxml::render::resolve::fonts::resolve_font_set_themes;
+use liteparse_ooxml::render::resolve::images::PartMedia;
use liteparse_ooxml::render::resolve::shape_geometry::build_geometry;
-use liteparse_ooxml::render::resolve::shape_visuals::resolve_shape_visuals;
+use liteparse_ooxml::render::resolve::shape_visuals::{resolve_blip_fill, resolve_shape_visuals};
use std::collections::HashMap;
@@ -210,6 +211,26 @@ pub struct SlideGeometry {
/// "asked to paint nothing here" are different claims.
pub slides_declining_layout: usize,
pub slides_declining_master: usize,
+ /// `p:pic` shapes the paint walk reached, on any rung.
+ pub pictures_seen: usize,
+ /// Pictures whose blip resolves to no image: an empty picture placeholder
+ /// (157 on the corpus, all in layouts and masters — correct, not a gap),
+ /// an external `r:link`, or media with no decoder (39 EMF/WMF references).
+ ///
+ /// Pooled deliberately with the correct cases, because the *ratio* is the
+ /// claim this pass can make honestly; splitting it further would need the
+ /// resolver to report a reason, which is its own change.
+ pub pictures_unresolved: usize,
+ /// Pictures that declare no `prstGeom` and took the schema's implicit
+ /// `rect`. 41 on the corpus.
+ pub pictures_implicit_rect: usize,
+ /// Shapes painted with an image fill — pictures and `spPr` blip fills
+ /// together. The number that says the emitter put photographs on slides,
+ /// as opposed to merely resolving them.
+ pub blips_painted: usize,
+ /// Slides whose background is an image this pass now paints. Carved out of
+ /// `unrenderable_backgrounds`, which was 63 before this step.
+ pub blip_backgrounds_painted: usize,
/// Runs whose resolved colour is **exactly the colour of the slide's own
/// background**, i.e. text that cannot be read.
///
@@ -313,6 +334,11 @@ fn layout_deck(pkg: &PresentationPackage, registry: &FontRegistry) -> SlideGeome
runs_colour_declared: 0,
runs_colour_defaulted: 0,
runs_invisible_on_background: 0,
+ pictures_seen: 0,
+ pictures_unresolved: 0,
+ pictures_implicit_rect: 0,
+ blips_painted: 0,
+ blip_backgrounds_painted: 0,
};
for (idx, slide) in pkg.slides.iter().enumerate() {
@@ -323,7 +349,7 @@ fn layout_deck(pkg: &PresentationPackage, registry: &FontRegistry) -> SlideGeome
let theme = slide_theme(pkg, slide, &mut themes);
// A slide whose shape tree will not parse still yields a page. Page
// count must equal slide count — a consumer indexes pages by slide.
- if let Some(prepared) = deck.prepare(slide) {
+ if let Some(prepared) = deck.prepare(pkg, slide) {
let cascade = prepared.cascade();
let mut ctx = ShapeCtx {
cascade,
@@ -351,19 +377,29 @@ fn layout_deck(pkg: &PresentationPackage, registry: &FontRegistry) -> SlideGeome
runs_colour_declared: &mut out.runs_colour_declared,
runs_colour_defaulted: &mut out.runs_colour_defaulted,
runs_invisible_on_background: &mut out.runs_invisible_on_background,
+ pictures_seen: &mut out.pictures_seen,
+ pictures_unresolved: &mut out.pictures_unresolved,
+ pictures_implicit_rect: &mut out.pictures_implicit_rect,
+ blips_painted: &mut out.blips_painted,
+ blip_backgrounds_painted: &mut out.blip_backgrounds_painted,
};
// Two walks over one `prepare`, in the order the raster wants
// them. See [`paint_shape`] for why they cannot be one walk. The
// background goes first because the command list *is* the z-order.
- background_at = paint_background(prepared.background.as_ref(), page_size, &mut ctx);
+ background_at = paint_background(
+ prepared.background.as_ref(),
+ prepared.background_media,
+ page_size,
+ &mut ctx,
+ );
// ...and so is this: master under layout under slide. §19.3.1.39
// builds the page by drawing each rung over the one it inherits
// from, which is why an inherited panel is a backdrop for the
// slide's own shapes rather than a lid over them.
- for rung in prepared.inherited {
- paint_shapes(rung, Rung::Inherited, &mut ctx);
+ for (rung, media) in prepared.inherited.into_iter().zip(prepared.inherited_media) {
+ paint_shapes(rung, Source::inherited(media), &mut ctx);
}
- paint_shapes(&prepared.shapes, Rung::Slide, &mut ctx);
+ paint_shapes(&prepared.shapes, Source::slide(prepared.media), &mut ctx);
for shape in reading_order(&prepared.shapes) {
layout_shape(shape, &mut ctx);
}
@@ -434,6 +470,11 @@ struct ShapeCtx<'a, 'r> {
runs_colour_declared: &'a mut usize,
runs_colour_defaulted: &'a mut usize,
runs_invisible_on_background: &'a mut usize,
+ pictures_seen: &'a mut usize,
+ pictures_unresolved: &'a mut usize,
+ pictures_implicit_rect: &'a mut usize,
+ blips_painted: &'a mut usize,
+ blip_backgrounds_painted: &'a mut usize,
}
/// Which part a painted shape came from.
@@ -450,6 +491,34 @@ enum Rung {
Inherited,
}
+/// The part a paint walk is reading, and the media that part can reach.
+///
+/// The two travel together because they are answers about the *same* part, and
+/// separating them is how an inherited picture ends up resolved against the
+/// slide's relationship table — a real image from the wrong `rId1`, which no
+/// count in the probe could distinguish from the right one.
+#[derive(Clone, Copy)]
+struct Source<'a> {
+ rung: Rung,
+ media: &'a PartMedia,
+}
+
+impl<'a> Source<'a> {
+ fn slide(media: &'a PartMedia) -> Self {
+ Self {
+ rung: Rung::Slide,
+ media,
+ }
+ }
+
+ fn inherited(media: &'a PartMedia) -> Self {
+ Self {
+ rung: Rung::Inherited,
+ media,
+ }
+ }
+}
+
impl ShapeCtx<'_, '_> {
/// Record one shape's outcome against the rung it came from.
fn tally(&mut self, rung: Rung, painted: bool) {
@@ -507,6 +576,7 @@ impl ShapeCtx<'_, '_> {
/// [`Deck::prepare`]: crate::office::pptx::Deck::prepare
fn paint_background(
background: Option<&(pptx::BackgroundSource, pptx::Background)>,
+ media: &PartMedia,
page_size: PtSize,
ctx: &mut ShapeCtx<'_, '_>,
) -> Option<usize> {
@@ -514,7 +584,7 @@ fn paint_background(
*ctx.undeclared_backgrounds += 1;
return None;
};
- let fill = pptx::background_fill(bg, ctx.theme, ctx.color_map);
+ let fill = pptx::background_fill(bg, ctx.theme, ctx.color_map, Some(media));
if matches!(fill, ResolvedFill::None) {
// Two very different slides land here, and the resolved fill cannot
// tell them apart: `resolve_fill` collapses blip, pattern and `grpFill`
@@ -540,6 +610,9 @@ fn paint_background(
page_size,
)?;
*ctx.painted_backgrounds += 1;
+ if matches!(fill, ResolvedFill::Blip(_)) {
+ *ctx.blip_backgrounds_painted += 1;
+ }
if let ResolvedFill::Solid(rgba) = fill {
ctx.background_rgb = Some(rgba.to_rgb24());
}
@@ -576,14 +649,14 @@ fn paint_background(
/// chrome filter: this walk paints chrome, the text walk still drops it, and
/// the 347 chrome shapes that carry text are a divergence this step leaves
/// open rather than closes (see the module-level note in the plan).
-fn paint_shapes(shapes: &[Shape], rung: Rung, ctx: &mut ShapeCtx<'_, '_>) {
+fn paint_shapes(shapes: &[Shape], from: Source<'_>, ctx: &mut ShapeCtx<'_, '_>) {
for shape in shapes {
- paint_shape(shape, rung, ctx);
+ paint_shape(shape, from, ctx);
if let ShapeKind::Group(group) = &shape.kind {
// A group's own `grpSpPr` fill is not lowered to `ShapeProperties`
// at all, so a group paints nothing itself — its children carry
// every fill, in their own declaration order.
- paint_shapes(&group.children, rung, ctx);
+ paint_shapes(&group.children, from, ctx);
}
}
}
@@ -596,7 +669,7 @@ fn paint_shapes(shapes: &[Shape], rung: Rung, ctx: &mut ShapeCtx<'_, '_>) {
/// self-placing. That also lets it carry the two flips, which a text bracket
/// deliberately does not — §20.1.7.6 mirrors a shape's *geometry*, and
/// PowerPoint does not mirror the text inside it.
-fn paint_shape(shape: &Shape, rung: Rung, ctx: &mut ShapeCtx<'_, '_>) {
+fn paint_shape(shape: &Shape, from: Source<'_>, ctx: &mut ShapeCtx<'_, '_>) {
let Some(props) = shape_properties(shape) else {
return;
};
@@ -604,27 +677,45 @@ fn paint_shape(shape: &Shape, rung: Rung, ctx: &mut ShapeCtx<'_, '_>) {
// whether or not the shape also puts ink down, and a 237-shape gap that
// only reported itself on shapes that happened to have a fill would be a
// number that under-reports exactly where it matters.
- if rung == Rung::Inherited && shape_text_len(shape) > 0 {
+ if from.rung == Rung::Inherited && shape_text_len(shape) > 0 {
*ctx.inherited_shapes_with_text += 1;
}
// `p:style`'s `fillRef`/`lnRef`/`effectRef` are not parsed yet, so the
// three style arguments are `None` and 3,381 corpus shapes with no `spPr`
// fill element resolve to nothing. That is an *under*-paint: visible, but
// never misleading.
- let visuals = resolve_shape_visuals(
+ let mut visuals = resolve_shape_visuals(
Some(props),
None,
None,
None,
&DrawingColorContext::new(ctx.theme).with_color_map(ctx.color_map),
+ Some(from.media),
);
+ // §19.3.1.37: a `p:pic`'s image is its own `p:blipFill`, a sibling of
+ // `spPr` — not an `spPr` fill element. So the picture's fill has to be
+ // resolved separately and take precedence; reading `shape_properties`
+ // alone finds the frame's *background* (usually absent) and never the
+ // photograph.
+ if let ShapeKind::Picture(pic) = &shape.kind {
+ *ctx.pictures_seen += 1;
+ let blip = resolve_blip_fill(&pic.blip_fill, Some(from.media));
+ if matches!(blip, ResolvedFill::None) {
+ // An empty picture placeholder, an `r:link`, or media we cannot
+ // decode (39 EMF/WMF references on the corpus). Counted rather
+ // than silently falling back to the frame's own fill.
+ *ctx.pictures_unresolved += 1;
+ } else {
+ visuals.fill = blip;
+ }
+ }
let paints = !matches!(visuals.fill, ResolvedFill::None) || visuals.stroke.is_some();
if !paints {
return;
}
let Some(slide_rect) = shape.slide_rect else {
- ctx.tally(rung, false);
+ ctx.tally(from.rung, false);
return;
};
// The *bounding* box, not the raw rect: `pptx::geometry` composes group
@@ -635,22 +726,44 @@ fn paint_shape(shape: &Shape, rung: Rung, ctx: &mut ShapeCtx<'_, '_>) {
width: emu_to_pt(box_.size.width.raw()),
height: emu_to_pt(box_.size.height.raw()),
};
- let Some(geometry) = props.geometry.as_ref() else {
- ctx.tally(rung, false);
- return;
+ // §19.3.1.37: a picture frame with no `prstGeom` is a rectangle — the
+ // image fills its box. 41 corpus pictures declare none.
+ //
+ // This is **not** the "never approximate an unbuildable preset by its
+ // bounding box" rule being relaxed. That rule is about a `cloud` we cannot
+ // build, where any substitute is a guess at a shape the file named. Here
+ // the file names no shape at all, and the schema supplies the default.
+ let implicit_rect;
+ let geometry = match props.geometry.as_ref() {
+ Some(g) => g,
+ None if matches!(shape.kind, ShapeKind::Picture(_)) => {
+ implicit_rect = ShapeGeometry::Preset(PresetGeometryDef {
+ preset: PresetShapeType::Rect,
+ adjust_values: Vec::new(),
+ });
+ *ctx.pictures_implicit_rect += 1;
+ &implicit_rect
+ }
+ None => {
+ ctx.tally(from.rung, false);
+ return;
+ }
};
let Some(path) = build_geometry(geometry, extent) else {
// An unimplemented preset. Counted, never approximated by its bounding
// box: a `rect` drawn where a `cloud` was asked for is a wrong slide,
// not a coarse one.
- ctx.tally(rung, false);
+ ctx.tally(from.rung, false);
return;
};
if visuals.stroke.is_some() && props.outline.as_ref().is_some_and(|o| o.fill.is_none()) {
*ctx.outlines_defaulted_black += 1;
}
- ctx.tally(rung, true);
+ ctx.tally(from.rung, true);
+ if matches!(visuals.fill, ResolvedFill::Blip(_)) {
+ *ctx.blips_painted += 1;
+ }
ctx.commands.push(DrawCommand::Path {
origin: PtOffset::new(
emu_to_pt(box_.origin.x.raw()),