diff --git a/Cargo.lock b/Cargo.lock index d44f44f5bb..9a4de2e07d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5049,6 +5049,7 @@ dependencies = [ "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)", "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)", "flate2", + "image", ] [[package]] diff --git a/crates/engine/src/compare.rs b/crates/engine/src/compare.rs index d9dd0eae57..3daac1ce26 100644 --- a/crates/engine/src/compare.rs +++ b/crates/engine/src/compare.rs @@ -197,7 +197,10 @@ pub struct OfficeExport { /// Pages (0-based) that draw forms nested deeper than [`MAX_FORM_DEPTH`] or more of them /// than [`MAX_FORM_VISITS`], or pictures past [`MAX_EXPORT_IMAGE_BYTES`] or past what one export /// may decode: export stops reading there to stay bounded on hostile files, so the text and images of those forms, or - /// those pictures, are missing from `bytes`. + /// those pictures, are missing from `bytes`. RTF also lists the pages that lost a picture to + /// its own limits (it repeats a picture's data at every placement) or one whose rotation it + /// couldn't bake in; their other content is kept. A picture no format can encode (a JPX image, + /// say) is left out of every format without being listed. pub truncated_pages: Vec, } @@ -330,7 +333,7 @@ impl crate::Document { /// ([`OfficeExport::truncated_pages`]). pub fn export_office_checked(&self, format: OfficeFormat) -> OfficeExport { // Markdown leaves pictures out. - let (pages, truncated_pages) = self.export_pages_checked(!matches!(format, OfficeFormat::Markdown), MAX_EXPORT_IMAGE_BYTES); + let (pages, mut truncated_pages) = self.export_pages_checked(!matches!(format, OfficeFormat::Markdown), MAX_EXPORT_IMAGE_BYTES); let title = self.info.title.clone().unwrap_or_else(|| self.name.trim_end_matches(".pdf").to_string()); // Word and HTML name the document's language (`/Lang`), so spelling is checked in it. let language = self.initial_view().language; @@ -339,7 +342,13 @@ impl crate::Document { OfficeFormat::Pptx => pdfcraft_export::pptx(&pages, &title), OfficeFormat::Html => pdfcraft_export::html_with_language(&pages, &title, language.as_deref()).into_bytes(), OfficeFormat::HtmlSimple => pdfcraft_export::html_simple_with_language(&pages, &title, language.as_deref()).into_bytes(), - OfficeFormat::Rtf => pdfcraft_export::rtf_with_title(&pages, &title).into_bytes(), + OfficeFormat::Rtf => { + let (rtf, omitted) = pdfcraft_export::rtf_with_title_checked(&pages, &title); + truncated_pages.extend(omitted); + truncated_pages.sort_unstable(); + truncated_pages.dedup(); + rtf.into_bytes() + } OfficeFormat::Markdown => pdfcraft_export::markdown(&pages).into_bytes(), }; OfficeExport { bytes, truncated_pages } diff --git a/crates/export/Cargo.toml b/crates/export/Cargo.toml index c23ef4ec71..ade5308749 100644 --- a/crates/export/Cargo.toml +++ b/crates/export/Cargo.toml @@ -16,6 +16,7 @@ craft-mime.workspace = true craft-rtf = { workspace = true, features = ["doc"] } craft-wordmodel.workspace = true craft-docx.workspace = true +image = { version = "0.25", default-features = false, features = ["png", "jpeg"] } craft-pptx.workspace = true craft-xml.workspace = true craft-zip.workspace = true diff --git a/crates/export/src/as_rtf.rs b/crates/export/src/as_rtf.rs index b5ae44d137..1828600c43 100644 --- a/crates/export/src/as_rtf.rs +++ b/crates/export/src/as_rtf.rs @@ -19,5 +19,12 @@ pub fn rtf(pages: &[Page]) -> String { /// [`rtf`] with the document's title (`\info\title`). pub fn rtf_with_title(pages: &[Page], title: &str) -> String { - craft_rtf::doc::export_with_generator(&flow_doc(pages, &Meta { title, language: None, font: FONT }), GENERATOR) + rtf_with_title_checked(pages, title).0 +} + +/// [`rtf_with_title`], and the pages (0-based) that lost a picture: one past the RTF's limits on +/// its pictures, or one it couldn't prepare. Those pages keep their other content. +pub fn rtf_with_title_checked(pages: &[Page], title: &str) -> (String, Vec) { + let (doc, omitted) = flow_doc(pages, &Meta { title, language: None, font: FONT }); + (craft_rtf::doc::export_with_generator(&doc, GENERATOR), omitted) } diff --git a/crates/export/src/as_word.rs b/crates/export/src/as_word.rs index 03a9ceaca1..6bcb44e746 100644 --- a/crates/export/src/as_word.rs +++ b/crates/export/src/as_word.rs @@ -4,6 +4,8 @@ //! page flowing ([`flow_doc`]); Word writes it with craft-docx, pages that can't flow kept as //! positioned text boxes and pictures ([`word_doc`]). +mod pictures; + use super::as_docx::{rgb8, room_for}; use super::as_html::{allowed, language_tag}; use super::layout::{Image, Item, Page, Table, body_size, items, reading_order}; @@ -41,7 +43,7 @@ fn push_text(p: &mut Paragraph, text: &str, props: CharProps) { pub(crate) fn table(t: &Table) -> craft_wordmodel::Table { let mut edges = t.cols.clone(); edges.push(t.rect[2]); - // Whole twips, at least 3 pt wide (Word's narrowest column), as `as_docx` writes them. + // Whole twips, at least 20 pt wide, and within Word's range of 3 pt to 22 inches. let widths: Vec = edges.windows(2).map(|w| (((w[1] - w[0]).max(20.0) * 20.0).round().clamp(60.0, 31680.0) / 20.0) as f32).collect(); let [top, left, bottom, right] = t.ruled.unwrap_or_default(); let inside = t.ruled.is_some(); @@ -172,10 +174,17 @@ struct Builder<'a> { doc: Document, body: Vec, media: Vec<(String, &'a Image)>, + /// For RTF, which repeats a picture's data at every placement and doesn't turn pictures: what + /// its pictures may still cost, and the rotations baked into them ([`pictures::Budget`]). + rtf: Option, + /// The page (0-based) being built, and the pages that lost a picture to a limit or to a + /// picture that couldn't be prepared. + page: usize, + omitted: Vec, } impl<'a> Builder<'a> { - fn new(pages: &[Page], meta: &Meta) -> Self { + fn new(pages: &[Page], meta: &Meta, rtf: Option) -> Self { let mut doc = Document::new(); doc.styles = std::sync::Arc::new(styles(meta.font, meta.language)); doc.core.title = meta.title.to_string(); @@ -185,15 +194,29 @@ impl<'a> Builder<'a> { if let Some(c) = shared.filter(|c| *c != [255; 3] && pages.iter().all(|p| p.background.map(rgb8) == Some(*c))) { doc.settings.page_color = Some(Rgb(c[0], c[1], c[2])); } - Builder { doc, body: Vec::new(), media: Vec::new() } + Builder { doc, body: Vec::new(), media: Vec::new(), rtf, page: 0, omitted: Vec::new() } } - /// The media key for `im`, or `None` past the limits. + /// The media key for `im`, or `None` for an empty picture, and past the limits or for one that + /// can't be prepared, which marks the page as having lost it. fn add_media(&mut self, im: &'a Image) -> Option { - if !room_for(&self.media, im) { + if im.bytes.is_empty() { return None; } - let key = self.doc.add_media(im.bytes.to_vec(), im.ext); + let prepared = if !room_for(&self.media, im) { + None + } else if let Some(budget) = &mut self.rtf { + budget.prepare(im) + } else { + Some((im.bytes.to_vec(), im.ext)) + }; + let Some((bytes, ext)) = prepared else { + if self.omitted.last() != Some(&self.page) { + self.omitted.push(self.page); + } + return None; + }; + let key = self.doc.add_media(bytes, ext); self.media.push((key.clone(), im)); Some(key) } @@ -221,22 +244,7 @@ impl<'a> Builder<'a> { } Item::Img(im) => { let Some(media) = self.add_media(im) else { return }; - let text_w = f64::from((sec.page_w - sec.margin_left - sec.margin_right).max(1.0)); - let (w, h) = ((im.rect[2] - im.rect[0]).max(1.0), (im.rect[3] - im.rect[1]).max(1.0)); - let k = (text_w / w).min(1.0); - let pic = InlineObject::Image { - media, - w: (w * k) as f32, - h: (h * k) as f32, - alt: String::new(), - float: Float::default(), - crop: [0.0; 4], - fx: Default::default(), - ole: None, - }; - let mut p = Paragraph::new(); - p.push_object(pic, &CharProps::default()); - self.body.push(Block::Para(p)); + self.body.push(Block::Para(picture(media, im, sec))); } Item::PageBreak => {} } @@ -258,6 +266,28 @@ impl<'a> Builder<'a> { } } +/// A paragraph holding the picture `media`, scaled down to fit between the margins of `sec`, side +/// to side and top to bottom. +fn picture(media: String, im: &Image, sec: &SectionProps) -> Paragraph { + let text_w = f64::from((sec.page_w - sec.margin_left - sec.margin_right).max(1.0)); + let text_h = f64::from((sec.page_h - sec.margin_top - sec.margin_bottom).max(1.0)); + let (w, h) = ((im.rect[2] - im.rect[0]).max(1.0), (im.rect[3] - im.rect[1]).max(1.0)); + let k = (text_w / w).min(text_h / h).min(1.0); + let pic = InlineObject::Image { + media, + w: (w * k) as f32, + h: (h * k) as f32, + alt: String::new(), + float: Float::default(), + crop: [0.0; 4], + fx: Default::default(), + ole: None, + }; + let mut p = Paragraph::new(); + p.push_object(pic, &CharProps::default()); + p +} + /// A paragraph that takes no room: no space around it and a 1 pt line. fn exact_1pt() -> ParaProps { ParaProps { space_before: Some(0.0), space_after: Some(0.0), line_spacing: Some(LineSpacing::Exactly(1.0)), ..ParaProps::default() } @@ -266,20 +296,26 @@ fn exact_1pt() -> ParaProps { /// The pages as one flowing document: each page a section of its own size (so a page always /// starts a new one, blank pages included), its paragraphs, tables and pictures in reading order. /// Headings are told from the whole document's body size. -pub(crate) fn flow_doc(pages: &[Page], meta: &Meta) -> Document { - let mut b = Builder::new(pages, meta); - let mut page = 0usize; +/// Its pictures are prepared for RTF ([`pictures::Budget`]); the pages (0-based) that lost one +/// come with it, their other content kept. +pub(crate) fn flow_doc(pages: &[Page], meta: &Meta) -> (Document, Vec) { + flow_doc_with_budget(pages, meta, pictures::Budget::default()) +} + +fn flow_doc_with_budget(pages: &[Page], meta: &Meta, budget: pictures::Budget) -> (Document, Vec) { + let mut b = Builder::new(pages, meta, Some(budget)); let mut sec = pages.first().map(section).unwrap_or_default(); for it in items(pages) { if matches!(it, Item::PageBreak) { b.end_page(sec); - page += 1; - sec = pages.get(page).map(section).unwrap_or_default(); + b.page += 1; + sec = pages.get(b.page).map(section).unwrap_or_default(); } else { b.flow(it, &sec); } } - b.finish(sec) + let omitted = std::mem::take(&mut b.omitted); + (b.finish(sec), omitted) } /// Pages with rotated text, or text that actually overlaps an image or an oversized @@ -422,9 +458,10 @@ fn positioned_page<'a>(b: &mut Builder<'a>, page: &'a Page) { /// positioned text boxes and pictures, and the others flow as paragraphs, tables and pictures. /// Each page is a section of its own size, and its headings are told from its own body size. pub(crate) fn word_doc(pages: &[Page], meta: &Meta) -> Document { - let mut b = Builder::new(pages, meta); + let mut b = Builder::new(pages, meta, None); let mut last = SectionProps::default(); for (i, page) in pages.iter().enumerate() { + b.page = i; let sec = section(page); if positioned(page) { positioned_page(&mut b, page); diff --git a/crates/export/src/as_word/pictures.rs b/crates/export/src/as_word/pictures.rs new file mode 100644 index 0000000000..d3b93d31ba --- /dev/null +++ b/crates/export/src/as_word/pictures.rs @@ -0,0 +1,291 @@ +//! RTF repeats encoded image data at every placement. Bound that expansion before copying, +//! and bake rotations because its inline picture writer does not apply DrawingML transforms. +use super::Image; +use image::{ImageEncoder, RgbaImage}; +use std::io::{self, Write}; + +const MAX_ENCODED: usize = 512 << 20; +const MAX_PIXELS: u64 = 16 << 20; +const MAX_RASTER_WORK: u64 = 64 << 20; +const MAX_PROBE_INPUT: usize = 512 << 20; + +#[derive(Default)] +pub(super) struct Budget { + encoded: usize, + raster: u64, + probe_input: usize, +} + +fn rtf_bytes(bytes: usize) -> Option { + bytes.checked_mul(2)?.checked_add(bytes.div_ceil(64))?.checked_add(256) +} + +impl Budget { + pub(super) fn prepare(&mut self, im: &Image) -> Option<(Vec, &'static str)> { + let rotation = im.rotation.rem_euclid(360.0); + if !rotation.is_finite() || !matches!(im.ext, "png" | "jpg" | "jpeg") { + return None; + } + let remaining = MAX_ENCODED.checked_sub(self.encoded)?; + if im.bytes.is_empty() || rtf_bytes(im.bytes.len())? > remaining { + return None; + } + let (bytes, ext) = if rotation == 0.0 { + (im.bytes.to_vec(), im.ext) + } else { + // JPEG dimension probes copy the input. Charge every attempt before probing, + // including failures, so repeated rejected placements cannot multiply that work. + let probe_input = self.probe_input.checked_add(im.bytes.len())?; + if probe_input > MAX_PROBE_INPUT { + return None; + } + self.probe_input = probe_input; + let (w, h) = image::ImageReader::new(io::Cursor::new(&im.bytes)).with_guessed_format().ok()?.into_dimensions().ok()?; + let pixels = u64::from(w).checked_mul(u64::from(h))?; + if w == 0 || h == 0 || w > 4096 || h > 4096 || pixels > MAX_PIXELS { + return None; + } + let [pw, ph] = im.size; + if !pw.is_finite() || !ph.is_finite() || pw <= 0.0 || ph <= 0.0 { + return None; + } + let (sin, cos) = rotation.to_radians().sin_cos(); + let bw = pw * cos.abs() + ph * sin.abs(); + let bh = pw * sin.abs() + ph * cos.abs(); + let density = (f64::from(w) / pw).min(f64::from(h) / ph); + // Exact quarter turns preserve every source pixel even when the PDF stretches + // the image anisotropically. Its physical aspect remains in the displayed rect. + let (ow, oh) = if rotation == 90.0 || rotation == 270.0 { + (f64::from(h), f64::from(w)) + } else if rotation == 180.0 { + (f64::from(w), f64::from(h)) + } else { + // Arbitrary angles use bounded nearest-neighbour resampling at the lower + // source density; unlike quarter turns this can lose detail when stretched. + ((bw * density).round().max(1.0), (bh * density).round().max(1.0)) + }; + if !ow.is_finite() || !oh.is_finite() || ow > 4096.0 || oh > 4096.0 { + return None; + } + let (ow, oh) = (ow as u32, oh as u32); + let output_pixels = u64::from(ow) * u64::from(oh); + if output_pixels > MAX_PIXELS { + return None; + } + let raster = self.raster.checked_add(pixels)?.checked_add(output_pixels)?; + if raster > MAX_RASTER_WORK { + return None; + } + // Charge only accepted work, but retain the charge if decoding later fails. + self.raster = raster; + let mut limits = image::Limits::default(); + limits.max_image_width = Some(4096); + limits.max_image_height = Some(4096); + limits.max_alloc = Some(64 << 20); + let mut reader = image::ImageReader::new(io::Cursor::new(&im.bytes)).with_guessed_format().ok()?; + reader.limits(limits); + let source = reader.decode().ok()?.into_rgba8(); + let mut output = RgbaImage::new(ow, oh); + for (x, y, pixel) in output.enumerate_pixels_mut() { + let exact = if rotation == 90.0 { + Some((w - 1 - y, x)) + } else if rotation == 180.0 { + Some((w - 1 - x, h - 1 - y)) + } else if rotation == 270.0 { + Some((y, h - 1 - x)) + } else { + None + }; + if let Some((sx, sy)) = exact { + *pixel = *source.get_pixel(sx, sy); + continue; + } + let dx = (f64::from(x) + 0.5) * bw / f64::from(ow) - bw / 2.0; + let dy = (f64::from(y) + 0.5) * bh / f64::from(oh) - bh / 2.0; + // PDF rotation is counterclockwise in y-up space; raster rows are y-down. + let sx = (cos * dx - sin * dy + pw / 2.0) * f64::from(w) / pw; + let sy = (sin * dx + cos * dy + ph / 2.0) * f64::from(h) / ph; + if sx >= 0.0 && sy >= 0.0 && sx < f64::from(w) && sy < f64::from(h) { + *pixel = *source.get_pixel(sx as u32, sy as u32); + } + } + let mut sink = Limited { bytes: Vec::new(), cap: remaining.saturating_sub(256) / 3 }; + image::codecs::png::PngEncoder::new(&mut sink).write_image(output.as_raw(), ow, oh, image::ExtendedColorType::Rgba8).ok()?; + (sink.bytes, "png") + }; + self.encoded = self.encoded.checked_add(rtf_bytes(bytes.len())?)?; + if self.encoded > MAX_ENCODED { + return None; + } + Some((bytes, ext)) + } +} + +struct Limited { + bytes: Vec, + cap: usize, +} +impl Write for Limited { + fn write(&mut self, data: &[u8]) -> io::Result { + if data.len() > self.cap.saturating_sub(self.bytes.len()) { + return Err(io::Error::other("RTF picture byte budget")); + } + self.bytes.extend_from_slice(data); + Ok(data.len()) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sample(rotation: f64) -> Image { + let pixels = RgbaImage::from_raw(2, 1, vec![255, 0, 0, 255, 0, 0, 255, 255]).expect("two pixels"); + let mut bytes = Vec::new(); + image::codecs::png::PngEncoder::new(&mut bytes).write_image(pixels.as_raw(), 2, 1, image::ExtendedColorType::Rgba8).expect("encode tiny PNG"); + Image { ext: "png", bytes: bytes.into(), rect: [0.0, 0.0, 1.0, 2.0], size: [2.0, 1.0], rotation } + } + + #[test] + fn pdf_counterclockwise_rotations_are_baked_into_asymmetric_pixels() { + for (angle, dims, first, last) in [ + (90.0, (1, 2), [0, 0, 255, 255], [255, 0, 0, 255]), + (180.0, (2, 1), [0, 0, 255, 255], [255, 0, 0, 255]), + (270.0, (1, 2), [255, 0, 0, 255], [0, 0, 255, 255]), + (-90.0, (1, 2), [255, 0, 0, 255], [0, 0, 255, 255]), + ] { + let (bytes, ext) = Budget::default().prepare(&sample(angle)).expect("rotated picture"); + assert_eq!(ext, "png"); + let pixels = image::load_from_memory(&bytes).expect("PNG").into_rgba8(); + assert_eq!(pixels.dimensions(), dims); + assert_eq!(pixels.get_pixel(0, 0).0, first); + assert_eq!(pixels.get_pixel(dims.0 - 1, dims.1 - 1).0, last); + } + } + + #[test] + fn quarter_turns_preserve_pixels_when_physical_size_is_stretched() { + for (angle, dims, first, last) in [ + (90.0, (1, 2), [0, 0, 255, 255], [255, 0, 0, 255]), + (180.0, (2, 1), [0, 0, 255, 255], [255, 0, 0, 255]), + (270.0, (1, 2), [255, 0, 0, 255], [0, 0, 255, 255]), + ] { + let mut im = sample(angle); + im.size = [1.0, 1.0]; + let (bytes, _) = Budget::default().prepare(&im).expect("stretched rotated picture"); + let pixels = image::load_from_memory(&bytes).expect("PNG").into_rgba8(); + assert_eq!(pixels.dimensions(), dims); + assert_eq!(pixels.get_pixel(0, 0).0, first); + assert_eq!(pixels.get_pixel(dims.0 - 1, dims.1 - 1).0, last); + } + } + + #[test] + fn flow_document_embeds_rotated_pixels_not_original_bytes() { + let page = + crate::layout::Page { width: 10.0, height: 10.0, blocks: Vec::new(), images: vec![sample(90.0)], background: None, rules: Vec::new() }; + let (doc, _) = super::super::flow_doc(&[page], &super::super::Meta { title: "", language: None, font: "Helvetica" }); + let bytes = doc.media.values().next().expect("picture retained"); + let pixels = image::load_from_memory(bytes).expect("PNG").into_rgba8(); + assert_eq!(pixels.dimensions(), (1, 2)); + assert_eq!(pixels.get_pixel(0, 0).0, [0, 0, 255, 255]); + assert_eq!(pixels.get_pixel(0, 1).0, [255, 0, 0, 255]); + } + + #[test] + fn repeated_allocations_pay_each_hex_expansion_before_copying() { + let im = sample(0.0); + let cost = rtf_bytes(im.bytes.len()).expect("small"); + let mut budget = Budget { encoded: MAX_ENCODED - cost * 2, raster: 0, ..Default::default() }; + assert_eq!(budget.prepare(&im).expect("first").0, im.bytes.as_ref()); + assert!(budget.prepare(&im).is_some()); + assert!(budget.prepare(&im).is_none()); + assert_eq!(budget.encoded, MAX_ENCODED); + assert!(rtf_bytes(usize::MAX).is_none()); + } + + #[test] + fn flow_budget_counts_reused_media_at_each_placement() { + let im = sample(0.0); + let cost = rtf_bytes(im.bytes.len()).expect("small"); + let page = crate::layout::Page { width: 10.0, height: 10.0, blocks: Vec::new(), images: vec![im; 3], background: None, rules: Vec::new() }; + let (doc, omitted) = super::super::flow_doc_with_budget( + &[page], + &super::super::Meta { title: "", language: None, font: "Helvetica" }, + Budget { encoded: MAX_ENCODED - 2 * cost, raster: 0, ..Default::default() }, + ); + assert_eq!(omitted, [0]); + let count: usize = doc + .body + .iter() + .map(|block| match &**block { + craft_wordmodel::Block::Para(p) => p.objects.len(), + _ => 0, + }) + .sum(); + assert_eq!(count, 2); + let rtf = craft_rtf::doc::export_with_generator(&doc, "PdfCraft"); + assert_eq!(rtf.matches("\\pngblip").count(), 2); + } + + #[test] + fn rejected_raster_charge_leaves_room_for_a_smaller_picture() { + let mut budget = Budget { encoded: 0, raster: MAX_RASTER_WORK - 4, ..Default::default() }; + assert!(budget.prepare(&sample(45.0)).is_none()); + assert_eq!(budget.raster, MAX_RASTER_WORK - 4); + assert!(budget.prepare(&sample(90.0)).is_some()); + assert_eq!(budget.raster, MAX_RASTER_WORK); + } + + #[test] + fn rejected_probes_pay_input_budget_before_retrying() { + let mut im = sample(90.0); + im.ext = "jpg"; + im.bytes = vec![0xff, 0xd8, 0xff, 0xe0, 0, 2, 0xff, 0xd9].into(); + let cost = im.bytes.len(); + let mut budget = Budget { probe_input: MAX_PROBE_INPUT - 2 * cost, ..Default::default() }; + assert!(budget.prepare(&im).is_none()); + assert_eq!(budget.probe_input, MAX_PROBE_INPUT - cost); + assert!(budget.prepare(&im).is_none()); + assert_eq!(budget.probe_input, MAX_PROBE_INPUT); + assert!(budget.prepare(&im).is_none()); + assert_eq!(budget.probe_input, MAX_PROBE_INPUT); + assert_eq!(budget.encoded, 0); + assert_eq!(budget.raster, 0); + // Exhausting rotated probes must not suppress unrotated byte-preserving pictures. + assert!(budget.prepare(&sample(0.0)).is_some()); + } + + #[test] + fn picture_fits_both_text_area_dimensions() { + let mut im = sample(0.0); + im.rect = [0.0, 0.0, 100.0, 1000.0]; + let section = craft_wordmodel::SectionProps { + page_w: 600.0, + page_h: 400.0, + margin_top: 50.0, + margin_bottom: 50.0, + margin_left: 50.0, + margin_right: 50.0, + ..Default::default() + }; + let p = super::super::picture(String::new(), &im, §ion); + assert!(matches!(p.objects.first(), Some(craft_wordmodel::InlineObject::Image { w, h, .. }) if *w == 30.0 && *h == 300.0)); + } + + #[test] + fn raster_work_and_encoded_writer_are_bounded() { + assert!(Budget { encoded: 0, raster: MAX_RASTER_WORK, ..Default::default() }.prepare(&sample(45.0)).is_none()); + assert!(Budget::default().prepare(&sample(f64::NAN)).is_none()); + let mut bad = sample(45.0); + bad.size[0] = f64::INFINITY; + assert!(Budget::default().prepare(&bad).is_none()); + let mut sink = Limited { bytes: Vec::new(), cap: 3 }; + assert!(sink.write_all(&[1, 2, 3]).is_ok()); + assert!(sink.write_all(&[4]).is_err()); + assert_eq!(sink.bytes, [1, 2, 3]); + } +} diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rs index 93d93fc2a5..42279325ab 100644 --- a/crates/export/src/lib.rs +++ b/crates/export/src/lib.rs @@ -36,7 +36,7 @@ pub use as_html::{html, html_simple, html_simple_with_language, html_with_langua pub use as_markdown::markdown; #[cfg(test)] use as_markdown::{emphasis, paragraph}; -pub use as_rtf::{rtf, rtf_with_title}; +pub use as_rtf::{rtf, rtf_with_title, rtf_with_title_checked}; pub use clip::{ClipBuilder, ClipSpan, ClipStyle, ClipText, MAX_CLIP_HTML_BYTES, MAX_CLIP_SPANS, MAX_CLIP_TEXT_BYTES, clip_html, font_family}; #[cfg(test)] use flow::list_item; diff --git a/crates/export/src/tests.rs b/crates/export/src/tests.rs index 76da4c6981..2decd3b515 100644 --- a/crates/export/src/tests.rs +++ b/crates/export/src/tests.rs @@ -1726,3 +1726,18 @@ fn word_keeps_line_breaks_and_tabs_inside_paragraphs_and_cells() { .collect(); assert!(cells.contains(&"Meter\nnumber".to_string()) && cells.contains(&"kWh\tunit".to_string()), "{cells:?}"); } + +#[test] +fn checked_rtf_reports_omitted_pictures_once_per_page_without_dropping_text() { + let mut first = page(); + first.images[0].rotation = f64::NAN; + first.images.push(first.images[0].clone()); + let clean = page(); + let mut third = first.clone(); + third.blocks[0].text = "Surviving last-page text".into(); + let pages = [first, clean, third]; + let (output, omitted) = crate::rtf_with_title_checked(&pages, "Partial"); + assert_eq!(omitted, [0, 2]); + assert!(output.contains("Surviving last-page text")); + assert_eq!(output, crate::rtf_with_title(&pages, "Partial")); +}