Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

PDF: Bounding Box crops are measured from the page's drawing, not a render

aiongg0437ab27f5d3
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index e041f4dff..440ef6bc9 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -474,7 +474,7 @@ impl Asset {
}
/// A Bounding Box crop ([`PdfCrop::ContentVisible`], [`PdfCrop::ContentAll`]) whose box isn't
- /// stored yet: finding it needs the page rendered.
+ /// stored yet: finding it needs the page's drawing interpreted.
pub fn content_box_pending(&self) -> bool {
self.pdf_box.is_none() && matches!(self.pdf_crop, PdfCrop::ContentVisible | PdfCrop::ContentAll) && self.mime == "application/pdf"
}
diff --git a/crates/engine/src/cmd/interchange.rs b/crates/engine/src/cmd/interchange.rs
index 3f9046a44..3f7f96697 100644
--- a/crates/engine/src/cmd/interchange.rs
+++ b/crates/engine/src/cmd/interchange.rs
@@ -68,8 +68,8 @@ pub fn import(bytes: &[u8], dir: Option<&std::path::Path>) -> Result<Document> {
/// Placed PDFs read from IDML name their crop (`PDFCrop`): find where each box sits on its page,
/// which the IDML reader can't (it doesn't parse PDFs). The box spans the graphic's
-/// `GraphicBounds`; a graphic without bounds takes the box's size. Bounding Box crops render the
-/// page to find the box, so they wait for drawing or export ([`designcraft_render::shown_box`],
+/// `GraphicBounds`; a graphic without bounds takes the box's size. Bounding Box crops interpret
+/// the page's drawing to find the box, so they wait for drawing or export ([`designcraft_render::shown_box`],
/// [`with_pdf_boxes`]) unless a graphic needs the box's size now.
pub(crate) fn resolve_pdf_crops(d: &mut Document) {
use std::collections::{HashMap, HashSet};
diff --git a/crates/idml/src/lib.rs b/crates/idml/src/lib.rs
index f33c53ae5..a65dad2d0 100644
--- a/crates/idml/src/lib.rs
+++ b/crates/idml/src/lib.rs
@@ -39,9 +39,8 @@
//! `GraphicBounds` span the chosen box. Where that box sits on the page needs the PDF parsed,
//! which this crate doesn't do: the engine finds it after import (`file.openIdml`), and when the
//! PDF's data isn't available the page's crop box fills `GraphicBounds`. The content crops
-//! (`CropContentVisibleLayers`, `CropContentAllLayers`) are the bounds of the page's
-//! non-transparent pixels on a render about 2048 pixels on its long side, so they can differ
-//! from a vector bounding box by a fraction of a point.
+//! (`CropContentVisibleLayers`, `CropContentAllLayers`) are the bounds of what the page draws:
+//! its paths, text and images, each cut to the clip in force.
//! - Unknown elements are ignored; nothing is preserved opaquely for round-trip yet.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs
index bb7101cca..8d1ae5001 100644
--- a/crates/render/src/lib.rs
+++ b/crates/render/src/lib.rs
@@ -31,6 +31,7 @@ pub fn effect_outset(it: &Item) -> f64 {
fx::outset(it)
}
pub mod glyphs;
+mod pdf_bounds;
mod pdf_layers;
pub use pdf_layers::{pdf_hide_layers, pdf_layers};
pub mod images;
@@ -1061,9 +1062,17 @@ pub fn pdf_page_png(bytes: &[u8], page: usize, max_side: u32, hidden: &[String],
Some(Rendered { width: pm.width() as u32, height: pm.height() as u32, pixels }.to_png())
}
+#[cfg(test)]
+thread_local! {
+ /// How many PDF pages [`render_pdf_page`] rasterized on this thread.
+ static PDF_RENDERS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
+}
+
/// Rasterize PDF page `page` so its longer side is about `max_side` pixels (screen display; PDF
/// export embeds the page as vectors).
pub fn render_pdf_page(bytes: &[u8], page: usize, max_side: u32) -> Option<Pixmap> {
+ #[cfg(test)]
+ PDF_RENDERS.with(|n| n.set(n.get() + 1));
let pdf = hayro::hayro_syntax::Pdf::new(std::sync::Arc::new(bytes.to_vec())).ok()?;
let p = pdf.pages().get(page)?;
let (w, h) = p.render_dimensions();
@@ -1079,7 +1088,7 @@ pub fn render_pdf_page(bytes: &[u8], page: usize, max_side: u32) -> Option<Pixma
/// The part of PDF page `page` that `crop` shows: its left, top, right and bottom edges as
/// fractions of the page as rendered (its visible crop box, rotated as it displays), and its size
/// in points. A box the page doesn't define is its crop box, as PDF readers do. The content boxes
-/// are the bounds of what the page draws, found on a render about 2048 pixels on its long side
+/// are the bounds of what the page draws, found from its drawing operations without rendering it
/// (the whole page when it draws nothing).
pub fn pdf_crop_box(bytes: &[u8], page: usize, crop: designcraft_doc::PdfCrop) -> Option<([f64; 4], (f64, f64))> {
use designcraft_doc::PdfCrop;
@@ -1094,10 +1103,10 @@ pub fn pdf_crop_box(bytes: &[u8], page: usize, crop: designcraft_doc::PdfCrop) -
}
let frac = match crop {
PdfCrop::Crop => WHOLE,
- PdfCrop::ContentVisible => content_bounds(bytes, page).unwrap_or(WHOLE),
+ PdfCrop::ContentVisible => pdf_bounds::page_content_bounds(bytes, page).unwrap_or(WHOLE),
PdfCrop::ContentAll => {
let all_on = pdf_hide_layers(bytes, &[]);
- content_bounds(all_on.as_deref().unwrap_or(bytes), page).unwrap_or(WHOLE)
+ pdf_bounds::page_content_bounds(all_on.as_deref().unwrap_or(bytes), page).unwrap_or(WHOLE)
}
PdfCrop::Art | PdfCrop::Trim | PdfCrop::Bleed | PdfCrop::Media => {
let media = p.media_box();
@@ -1123,7 +1132,7 @@ pub fn pdf_crop_box(bytes: &[u8], page: usize, crop: designcraft_doc::PdfCrop) -
/// The part of the page a placed PDF shows ([`designcraft_doc::Asset::shown_box`]). A Bounding
/// Box crop that import left unmeasured is measured here, once per file, page and crop: that
-/// renders the page, which only drawing or exporting the graphic needs.
+/// interprets the page's drawing, which only drawing or exporting the graphic needs.
pub fn shown_box(asset: &designcraft_doc::Asset) -> Option<[f64; 4]> {
if !asset.content_box_pending() {
return asset.shown_box();
@@ -1154,23 +1163,6 @@ fn content_box(bytes: &Arc<Vec<u8>>, page: u32, crop: designcraft_doc::PdfCrop)
b
}
-/// The bounds of the non-transparent pixels of PDF page `page`, as fractions of the page.
-fn content_bounds(bytes: &[u8], page: usize) -> Option<[f64; 4]> {
- let pm = render_pdf_page(bytes, page, 2048)?;
- let (pw, ph) = (usize::from(pm.width()), usize::from(pm.height()));
- let (mut x0, mut y0, mut x1, mut y1) = (usize::MAX, usize::MAX, 0, 0);
- for (i, px) in pm.data().iter().enumerate() {
- if px.a > 0 {
- let (x, y) = (i % pw.max(1), i / pw.max(1));
- x0 = x0.min(x);
- y0 = y0.min(y);
- x1 = x1.max(x + 1);
- y1 = y1.max(y + 1);
- }
- }
- (x0 < x1 && y0 < y1 && pw > 0 && ph > 0).then(|| [x0 as f64 / pw as f64, y0 as f64 / ph as f64, x1 as f64 / pw as f64, y1 as f64 / ph as f64])
-}
-
/// The part of `pm` inside `frac` (left, top, right, bottom as fractions of it); what lies outside
/// `pm` is transparent.
pub fn crop_pixmap(pm: &Pixmap, frac: [f64; 4]) -> Option<Pixmap> {
@@ -1632,4 +1624,43 @@ mod tests {
.count();
assert!(dark > 30, "cell text pixels: {dark}");
}
+
+ /// A one-page PDF (612 x 792 pt) that draws `content`.
+ fn one_page_pdf(content: &str) -> Vec<u8> {
+ let objects = [
+ "<< /Type /Catalog /Pages 2 0 R >>".to_string(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R >>".to_string(),
+ format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()),
+ ];
+ let mut out = b"%PDF-1.4\n".to_vec();
+ let mut offsets = Vec::new();
+ for (i, o) in objects.iter().enumerate() {
+ offsets.push(out.len());
+ out.extend(format!("{} 0 obj\n{o}\nendobj\n", i + 1).bytes());
+ }
+ let xref = out.len();
+ out.extend(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).bytes());
+ for o in offsets {
+ out.extend(format!("{o:010} 00000 n \n").bytes());
+ }
+ out.extend(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).bytes());
+ out
+ }
+
+ /// A Bounding Box crop is the exact extent of what the page draws, strokes included, found
+ /// without rasterizing the page: PDF export of a document that places a complex illustration
+ /// cropped that way spent seconds rendering it just to measure it.
+ #[test]
+ fn content_crop_box_is_measured_without_rendering_the_page() {
+ // A filled rectangle 100..300 x 532..592 (PDF y up) and a 10 pt horizontal line at
+ // y 100 from x 400 to 500, butt capped. Clipped away: a rectangle off to the left.
+ let pdf = one_page_pdf("0 0 0 rg 100 532 200 60 re f 10 w 400 100 m 500 100 l S q 0 0 50 50 re W n 100 0 10 10 re f Q");
+ let before = PDF_RENDERS.with(std::cell::Cell::get);
+ let (frac, size) = pdf_crop_box(&pdf, 0, designcraft_doc::PdfCrop::ContentVisible).unwrap();
+ assert_eq!(PDF_RENDERS.with(std::cell::Cell::get), before, "the page was rasterized");
+ let want = [100.0 / 612.0, 200.0 / 792.0, 500.0 / 612.0, 697.0 / 792.0];
+ assert!(frac.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-6), "{frac:?} vs {want:?}");
+ assert!((size.0 - 400.0).abs() < 1e-3 && (size.1 - 497.0).abs() < 1e-3, "{size:?}");
+ }
}
diff --git a/crates/render/src/pdf_bounds.rs b/crates/render/src/pdf_bounds.rs
new file mode 100644
index 000000000..47a021529
--- /dev/null
+++ b/crates/render/src/pdf_bounds.rs
@@ -0,0 +1,133 @@
+//! The bounds of what a PDF page draws, found by interpreting its drawing operations: the union
+//! of every painted path, glyph and image, each cut to the clip in force when it's painted.
+//! Nothing is rasterized, so measuring a page costs a fraction of drawing it.
+
+use hayro::hayro_interpret::font::Glyph;
+use hayro::hayro_interpret::{
+ BlendMode, ClipPath, Context, Device, FillRule, GlyphDrawMode, Image, InterpreterCache, InterpreterSettings, Paint, PathDrawMode, RectExt,
+ SoftMask, TransformExt, interpret_page,
+};
+use vello_cpu::kurbo::{self, Affine, BezPath, Rect, Shape};
+
+/// The bounds of what PDF page `page` draws, as fractions of the page as rendered (its visible
+/// crop box, rotated as it displays): left, top, right, bottom. `None` when it draws nothing.
+pub(crate) fn page_content_bounds(bytes: &[u8], page: usize) -> Option<[f64; 4]> {
+ let pdf = hayro::hayro_syntax::Pdf::new(std::sync::Arc::new(bytes.to_vec())).ok()?;
+ let p = pdf.pages().get(page)?;
+ let (w, h) = p.render_dimensions();
+ let (w, h) = (f64::from(w), f64::from(h));
+ if !(w > 0.0 && h > 0.0) {
+ return None;
+ }
+ let initial = p.initial_transform(true).to_kurbo();
+ let page_rect = Rect::new(0.0, 0.0, w, h);
+ let crop = (initial * p.intersected_crop_box().to_kurbo().to_path(0.1)).bounding_box().intersect(page_rect);
+ let cache = InterpreterCache::new();
+ let mut ctx = Context::new(initial, page_rect, &cache, p.xref(), InterpreterSettings::default());
+ let mut dev = Bounds { clips: vec![crop], hidden: Vec::new(), out: None };
+ interpret_page(p, &mut ctx, &mut dev);
+ let r = dev.out?;
+ let frac = [r.x0 / w, r.y0 / h, r.x1 / w, r.y1 / h];
+ frac.iter().all(|v| v.is_finite()).then_some(frac)
+}
+
+/// A [`Device`] that collects bounds instead of drawing.
+struct Bounds {
+ /// The bounding box of each clip in force, innermost last (device space); the first is the
+ /// page's crop box.
+ clips: Vec<Rect>,
+ /// For each open transparency group: whether nothing in it can show (opacity 0).
+ hidden: Vec<bool>,
+ out: Option<Rect>,
+}
+
+impl Bounds {
+ fn add(&mut self, r: Rect) {
+ if self.hidden.last().copied().unwrap_or(false) {
+ return;
+ }
+ let Some(clip) = self.clips.last() else { return };
+ let r = r.intersect(*clip);
+ if !(r.width() > 0.0 && r.height() > 0.0) || ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) {
+ return;
+ }
+ self.out = Some(self.out.map_or(r, |o| o.union(r)));
+ }
+
+ fn add_path(&mut self, path: &BezPath, transform: Affine, paint: &Paint<'_>, mode: &PathDrawMode) {
+ if let Paint::Color(c) = paint
+ && c.to_rgba().to_rgba8()[3] == 0
+ {
+ return;
+ }
+ let r = match mode {
+ PathDrawMode::Fill(_) => (transform * path.clone()).bounding_box(),
+ PathDrawMode::Stroke(s) => {
+ // Dashes only remove parts of the line: the undashed stroke bounds them.
+ let stroke = kurbo::Stroke {
+ width: f64::from(s.line_width.max(0.0)),
+ join: s.line_join,
+ miter_limit: f64::from(s.miter_limit),
+ start_cap: s.line_cap,
+ end_cap: s.line_cap,
+ dash_pattern: Default::default(),
+ dash_offset: 0.0,
+ };
+ // A quarter point on the page, in the path's own units.
+ let scale = transform.determinant().abs().sqrt();
+ let tolerance = if scale.is_finite() && scale > 1e-9 { (0.25 / scale).min(1e6) } else { 0.25 };
+ let outline = kurbo::stroke(path.iter(), &stroke, &kurbo::StrokeOpts::default(), tolerance);
+ (transform * outline).bounding_box()
+ }
+ };
+ self.add(r);
+ }
+}
+
+impl<'a> Device<'a> for Bounds {
+ fn set_soft_mask(&mut self, _: Option<SoftMask<'a>>) {}
+
+ fn set_blend_mode(&mut self, _: BlendMode) {}
+
+ fn draw_path(&mut self, path: &BezPath, transform: Affine, paint: &Paint<'a>, mode: &PathDrawMode) {
+ self.add_path(path, transform, paint, mode);
+ }
+
+ fn push_clip_path(&mut self, clip: &ClipPath) {
+ let top = self.clips.last().copied().unwrap_or(Rect::ZERO);
+ self.clips.push(clip.path.bounding_box().intersect(top));
+ }
+
+ fn push_transparency_group(&mut self, opacity: f32, _: Option<SoftMask<'a>>, _: BlendMode) {
+ let parent = self.hidden.last().copied().unwrap_or(false);
+ self.hidden.push(parent || opacity <= 0.0);
+ }
+
+ fn draw_glyph(&mut self, glyph: &Glyph<'a>, transform: Affine, glyph_transform: Affine, paint: &Paint<'a>, mode: &GlyphDrawMode) {
+ let mode = match mode {
+ GlyphDrawMode::Invisible => return,
+ GlyphDrawMode::Fill => PathDrawMode::Fill(FillRule::NonZero),
+ GlyphDrawMode::Stroke(s) => PathDrawMode::Stroke(s.clone()),
+ };
+ match glyph {
+ Glyph::Outline(o) => self.add_path(&o.outline(), transform * glyph_transform, paint, &mode),
+ Glyph::Type3(g) => g.interpret(self, transform, glyph_transform, paint),
+ }
+ }
+
+ fn draw_image(&mut self, image: Image<'a, '_>, transform: Affine) {
+ let r = Rect::new(0.0, 0.0, f64::from(image.width()), f64::from(image.height()));
+ self.add((transform * r.to_path(0.1)).bounding_box());
+ }
+
+ fn pop_clip_path(&mut self) {
+ // The crop box stays.
+ if self.clips.len() > 1 {
+ self.clips.pop();
+ }
+ }
+
+ fn pop_transparency_group(&mut self) {
+ self.hidden.pop();
+ }
+}