DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Never crash: render and pdf
Brandon Thomas82d6def80bd5
diff --git a/clippy.toml b/clippy.tomlnew file mode 100644index 000000000..4b6c79f55--- /dev/null+++ b/clippy.toml@@ -0,0 +1,4 @@+allow-unwrap-in-tests = true+allow-expect-in-tests = true+allow-panic-in-tests = true+allow-indexing-slicing-in-tests = truediff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rsindex 9665b41a0..145b44d2a 100644--- a/crates/pdf/src/export.rs+++ b/crates/pdf/src/export.rs@@ -663,7 +663,7 @@ impl Exporter<'_> {let kind: krilla::tagging::TagKind = match tag.as_str() {h if h.len() == 2 && h.starts_with('h') => {let n = h[1..].parse::<u16>().unwrap_or(1).clamp(1, 6);- Tag::Hn(std::num::NonZeroU16::new(n).expect("1–6"), text()).into()+ Tag::Hn(std::num::NonZeroU16::new(n).unwrap_or(std::num::NonZeroU16::MIN), text()).into()}"blockquote" => Tag::BlockQuote.into(),_ => Tag::P.into(),diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rsindex 909a3ab9e..41f89305a 100644--- a/crates/pdf/src/lib.rs+++ b/crates/pdf/src/lib.rs@@ -23,6 +23,7 @@//! PDF/X support) — the export report says so.//!//! Not yet: tagged PDF, bookmarks, hyperlinks, overprint, layers as optional content.+#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]#![forbid(unsafe_code)]mod export;diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rsindex 2818fea6f..77bb18780 100644--- a/crates/render/src/fx.rs+++ b/crates/render/src/fx.rs@@ -355,7 +355,7 @@ impl Renderer {let screen = Rect::new(0.0, 0.0, ctx.width() as f64, ctx.height() as f64).inflate(spread, spread);let r = f.view.transform_rect_bbox(reach).inflate(spread, spread).intersect(screen);let (x0, y0) = (r.x0.floor(), r.y0.floor());- let (w, h) = ((r.x1.ceil() - x0).min(u16::MAX as f64), (r.y1.ceil() - y0).min(u16::MAX as f64));+ let (w, h) = ((r.x1.ceil() - x0).min(crate::MAX_SIDE as f64), (r.y1.ceil() - y0).min(crate::MAX_SIDE as f64));if w < 1.0 || h < 1.0 {return;}diff --git a/crates/render/src/glyphs.rs b/crates/render/src/glyphs.rsindex 3cf584df8..9c9b9dae2 100644--- a/crates/render/src/glyphs.rs+++ b/crates/render/src/glyphs.rs@@ -39,7 +39,9 @@ pub fn glyph_grid(family: &str, style: &str, chars: &[char], cols: u32, cell: u3ctx.flush();let mut pixels = vec![0u8; w as usize * h as usize * 4];let mut res = Resources::new();- ctx.render(vello_cpu::PixmapMut::new(w, h, &mut pixels).expect("buffer size"), &mut res);+ if let Some(pm) = vello_cpu::PixmapMut::new(w, h, &mut pixels) {+ ctx.render(pm, &mut res);+ }Rendered { width: w as u32, height: h as u32, pixels }}@@ -71,7 +73,9 @@ pub fn text_line(family: &str, style: &str, text: &str, height: u32, color: [u8;ctx.flush();let mut pixels = vec![0u8; w as usize * h as usize * 4];let mut res = Resources::new();- ctx.render(vello_cpu::PixmapMut::new(w, h, &mut pixels).expect("buffer size"), &mut res);+ if let Some(pm) = vello_cpu::PixmapMut::new(w, h, &mut pixels) {+ ctx.render(pm, &mut res);+ }Rendered { width: w as u32, height: h as u32, pixels }}diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rsindex 80acb00ef..e86478c3d 100644--- a/crates/render/src/lib.rs+++ b/crates/render/src/lib.rs@@ -6,6 +6,7 @@//!//! Callers pass a list of spreads with their placement on a shared canvas and a canvas → pixel//! view transform, so the UI can render exactly its viewport with every visible spread.+#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]#![forbid(unsafe_code)]use std::collections::HashMap;@@ -35,6 +36,14 @@ pub use pdf_layers::{pdf_hide_layers, pdf_layers};pub mod images;mod text;+/// Largest side of a raster the renderer draws. vello_cpu keeps sizes in `u16` and rounds them+/// up to its tiles (4 px) and depth buckets (128 px), so a side near `u16::MAX` overflows inside+/// it: stay a few buckets below.+pub const MAX_SIDE: u32 = u16::MAX as u32 + 1 - 512;++/// Largest page raster [`Renderer::render_page`] makes (2 GiB of RGBA).+pub const MAX_PAGE_PIXELS: u64 = 1 << 29;+/// A rendered image (premultiplied RGBA8, row-major).#[derive(Clone)]pub struct Rendered {@@ -56,10 +65,20 @@ impl Rendered {}out}+ /// PNG bytes (empty, with the error logged, if the image can't be encoded).pub fn to_png(&self) -> Vec<u8> {let mut buf = Vec::new();- let img = image::RgbaImage::from_raw(self.width, self.height, self.to_straight()).expect("size");- img.write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png).expect("png encode");+ let mut px = self.to_straight();+ // `pixels` is public: a mismatched buffer is padded or cut to the stated size.+ px.resize(self.width as usize * self.height as usize * 4, 0);+ let Some(img) = image::RgbaImage::from_raw(self.width, self.height, px) else {+ log::error!("PNG encode: {}×{} image is too large", self.width, self.height);+ return Vec::new();+ };+ if let Err(e) = img.write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png) {+ log::error!("PNG encode: {e}");+ return Vec::new();+ }buf}pub fn to_jpeg(&self, quality: u8) -> Vec<u8> {@@ -271,8 +290,8 @@ impl Renderer {opts: &RenderOptions,) -> Rendered {let start = now();- let w = width.clamp(1, u16::MAX as u32) as u16;- let h = height.clamp(1, u16::MAX as u32) as u16;+ let w = width.clamp(1, MAX_SIDE) as u16;+ let h = height.clamp(1, MAX_SIDE) as u16;let mut ctx = match self.ctx.take() {Some(mut c) if c.width() == w && c.height() == h && c.render_settings().num_threads == self.threads => {c.reset();@@ -308,7 +327,9 @@ impl Renderer {ctx.flush();// Render straight into the returned buffer (no extra copy of the frame).let mut pixels = vec![0u8; w as usize * h as usize * 4];- ctx.render(vello_cpu::PixmapMut::new(w, h, &mut pixels).expect("buffer size"), &mut self.resources);+ if let Some(pm) = vello_cpu::PixmapMut::new(w, h, &mut pixels) {+ ctx.render(pm, &mut self.resources);+ }if opts.blend_space_view && doc.settings.blend_space == designcraft_doc::BlendSpace::Cmyk && opts.plate.is_none() {let mut img = Rendered { width: w as u32, height: h as u32, pixels };for pl in spreads {@@ -338,6 +359,10 @@ impl Renderer {}let w = (r.width() * scale).round().max(1.0) as u32;let h = (r.height() * scale).round().max(1.0) as u32;+ if w > MAX_SIDE || h > MAX_SIDE || w as u64 * h as u64 > MAX_PAGE_PIXELS {+ log::warn!("page {abs} at {scale} px/pt would be {w}×{h} pixels: too large to render");+ return None;+ }let view = Affine::scale(scale) * Affine::translate(-r.origin().to_vec2());let mut o = opts.clone();o.background = Some([255, 255, 255, 255]);@@ -1143,6 +1168,32 @@ mod tests {use designcraft_doc::build::NewDocument;use designcraft_doc::{Fill, ParaFormat};+ /// `Rendered` has public fields: a buffer that doesn't match the stated size used to panic+ /// in `to_png`.+ /// A canvas 65535 pixels wide (any render wider than that was clamped to it) panicked inside+ /// vello_cpu when it snapped the width up to its tiles; a huge page export now declines.+ #[test]+ fn very_wide_renders_do_not_panic() {+ let doc = Document::new(&NewDocument::default());+ let cache = Cache::new();+ let mut r = Renderer::new();+ let img = r.render(&doc, &cache, &[], 70_000, 4, Affine::IDENTITY, &RenderOptions::default());+ assert_eq!(img.width, MAX_SIDE);+ let page = [Placed { spread: SpreadRef::Doc(0), xf: Affine::IDENTITY }];+ let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };+ let img = r.render(&doc, &cache, &page, 70_000, 64, Affine::scale(120.0), &opts);+ assert_eq!(img.width, MAX_SIDE);+ assert!(r.render_page(&doc, &cache, 0, 500.0, true, &RenderOptions::default()).is_none());+ }++ #[test]+ fn to_png_survives_a_mismatched_buffer() {+ let short = Rendered { width: 4, height: 4, pixels: vec![255; 10] };+ let png = short.to_png();+ assert_eq!(image::load_from_memory(&png).map(|i| (i.width(), i.height())).ok(), Some((4, 4)));+ assert!(Rendered { width: 0, height: 0, pixels: vec![] }.to_png().len() < 1024);+ }+#[test]fn proof_view_simulates_the_target() {use designcraft_color::cms::{ProofSetup, ProofTarget};diff --git a/crates/render/src/text.rs b/crates/render/src/text.rsindex 51aeb8558..165366eb7 100644--- a/crates/render/src/text.rs+++ b/crates/render/src/text.rs@@ -136,13 +136,14 @@ fn build_line(db: &FontDb, cs: &ComposedStory, l: &Line, vertical: bool) -> Line// Upright in vertical text.a = turn * a;}- let bp = match runs.iter_mut().find(|r| r.0 == g.style) {- Some(r) => &mut r.1,+ let k = match runs.iter().position(|r| r.0 == g.style) {+ Some(k) => k,None => {runs.push((g.style, BezPath::new()));- &mut runs.last_mut().expect("pushed").1+ runs.len() - 1}};+ let bp = &mut runs[k].1;for el in outline.elements() {bp.push(transform_el(a, *el));}