mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
PDF: cancel dense pages, complete page labels, isolate artboards
- render_page: forward Interrupt to craft-pdf through an owned flag and a scoped 5 ms watcher, so dense vector pages stop mid-render. - Warn when craft-pdf reports a substituted font (the backend does not emit the flag yet). - /PageLabels: emit an entry for every page, start at 0, and write no tree when every artboard name is empty. - Export budget: charge retained page data plus the largest page's two f32 buffers instead of the whole document canvas, saturating on overflow. - Render each artboard from a document holding only its group, so overlapping boards no longer paint on each other's pages. One document shell is cloned and reused. - Tests: dense-page cancellation, labels with an empty middle name and all empty, overlapping artboard pixels, sparse 9000x9000 canvas, seven US Letter pages.
This commit is contained in:
1 parent
0525197133
commit
1df674997b
4 files changed
+308
-47
No files matched your search
+35
-17
@@ -144,14 +144,16 @@ fn print_pdf_pages(
|
||||
out.extend_from_slice(b"\nendobj\n");
|
||||
};
|
||||
let n = pages.len();
|
||||
let selections_on = pages.iter().any(|p| p.page_label.is_some());
|
||||
// A label tree is written only for a non-empty name: an all-empty tree would be `/Nums []`,
|
||||
// and filtering the first empty name away would start the tree at page index 1, not 0.
|
||||
let labels_on = pages.iter().any(|p| p.page_label.as_deref().is_some_and(|label| !label.is_empty()));
|
||||
// 1 catalog, 2 pages, then per page: page, contents, image; then the shared font/ICC/selection.
|
||||
let font_obj = 3 + n * 3;
|
||||
let icc = first.image.icc.as_ref();
|
||||
let icc_obj = icc.map(|_| font_obj + 1);
|
||||
let selection_base = font_obj + if icc.is_some() { 2 } else { 1 };
|
||||
let selection_objects = selection_font.objects(selection_base);
|
||||
let labels_obj = selections_on.then_some((selection_base + selection_objects.len()) as u32);
|
||||
let labels_obj = labels_on.then_some((selection_base + selection_objects.len()) as u32);
|
||||
obj(&mut out, format!("<< /Type /Catalog /Pages 2 0 R{} >>", labels_obj.map(|o| format!(" /PageLabels {o} 0 R")).unwrap_or_default()).as_bytes());
|
||||
let kids = (0..n).map(|i| format!("{} 0 R", 3 + i * 3)).collect::<Vec<_>>().join(" ");
|
||||
obj(&mut out, format!("<< /Type /Pages /Kids [{kids}] /Count {n} >>").as_bytes());
|
||||
@@ -226,10 +228,16 @@ fn print_pdf_pages(
|
||||
obj(&mut out, body);
|
||||
}
|
||||
if labels_obj.is_some() {
|
||||
// Every page gets an entry: a number-tree range runs until the next key, so omitting an
|
||||
// empty name would make that page inherit the previous page's label. An empty
|
||||
// dictionary gives the page the default (decimal) label instead.
|
||||
let nums = pages
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, p)| p.page_label.as_deref().filter(|l| !l.is_empty()).map(|l| format!("{i} << /P {} >>", pdf_unicode_string(l))))
|
||||
.map(|(i, p)| match p.page_label.as_deref().filter(|label| !label.is_empty()) {
|
||||
Some(label) => format!("{i} << /P {} >>", pdf_unicode_string(label)),
|
||||
None => format!("{i} << >>"),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
obj(&mut out, format!("<< /Nums [{nums}] >>").as_bytes());
|
||||
@@ -315,6 +323,11 @@ fn collect_vectors(doc: &Document) -> (Vec<(usize, String)>, selection::Selectio
|
||||
(layers, selection_font)
|
||||
}
|
||||
|
||||
/// Pixels in `rect`, saturating on overflow.
|
||||
fn rect_pixels(rect: photocraft_geom::Rect) -> u64 {
|
||||
u64::from(rect.width()).saturating_mul(u64::from(rect.height()))
|
||||
}
|
||||
|
||||
/// File › Save As / Save a Copy › PDF (#3401): the flattened document at its print size
|
||||
/// (pixels ÷ resolution × 72 pt). One page per artboard when the document has artboards, else one
|
||||
/// page for the whole document. Layers and transparency are dropped — the warning says so — and
|
||||
@@ -341,8 +354,13 @@ pub fn export(doc: &Document, ctl: &photocraft_raster::Interrupt) -> std::result
|
||||
if !artboards.is_empty() {
|
||||
// Every page's encoded pixels are kept until the PDF is assembled; bound that peak.
|
||||
const MAX_PDF_EXPORT_BYTES: u64 = 1 << 30;
|
||||
let pixels: u64 = artboards.iter().map(|(_, _, a)| u64::from(a.rect.width()) * u64::from(a.rect.height())).sum();
|
||||
let estimate = pixels.saturating_mul(device as u64) + w as u64 * h as u64 * n as u64 * 4;
|
||||
let page_pixels: u64 = artboards.iter().fold(0u64, |bytes, (_, _, a)| bytes.saturating_add(rect_pixels(a.rect)));
|
||||
let retained = page_pixels.saturating_mul(device as u64);
|
||||
// One page renders at a time: its f32 composite surface plus the region read back from
|
||||
// it, both `n` channels at 4 bytes per pixel. The whole-document canvas is never held.
|
||||
let largest = artboards.iter().map(|(_, _, a)| rect_pixels(a.rect)).max().unwrap_or(0);
|
||||
let temporary = largest.saturating_mul(n as u64).saturating_mul(4).saturating_mul(2);
|
||||
let estimate = retained.saturating_add(temporary);
|
||||
if estimate > MAX_PDF_EXPORT_BYTES {
|
||||
return Err(IoError::Unsupported(format!(
|
||||
"PDF export would need about {} MB for {} artboards; export them in smaller batches",
|
||||
@@ -350,6 +368,12 @@ pub fn export(doc: &Document, ctl: &photocraft_raster::Interrupt) -> std::result
|
||||
artboards.len()
|
||||
)));
|
||||
}
|
||||
// One document shell is reused for every page. Each page renders a document holding only
|
||||
// its artboard group (the same isolation as `artboard_document`), so an overlapping board
|
||||
// cannot paint on another board's page. Layer pixels are shared with `doc`; this one
|
||||
// clone and the per-page group clone hold no new pixel buffers, but they are outside the
|
||||
// 1 GiB estimate because they are not retained page data.
|
||||
let mut one = doc.clone();
|
||||
let mut pages = Vec::with_capacity(artboards.len());
|
||||
for (id, name, artboard) in &artboards {
|
||||
ctl.check().map_err(|_| IoError::Cancelled)?;
|
||||
@@ -360,19 +384,13 @@ pub fn export(doc: &Document, ctl: &photocraft_raster::Interrupt) -> std::result
|
||||
}
|
||||
// A hidden artboard still gets its page, rendered from its own content rather than
|
||||
// left blank by the group's visibility.
|
||||
let shown;
|
||||
let doc = if doc.layer(*id).is_some_and(|l| !l.visible) {
|
||||
let mut copy = doc.clone();
|
||||
if let Some(layer) = copy.layer_mut(*id) {
|
||||
layer.visible = true;
|
||||
}
|
||||
shown = copy;
|
||||
&shown
|
||||
} else {
|
||||
doc
|
||||
};
|
||||
let Some(layer) = doc.layer(*id) else { continue };
|
||||
let mut group = layer.clone();
|
||||
group.visible = true;
|
||||
one.layers.clear();
|
||||
one.layers.push(group);
|
||||
// Render only this artboard's rect; the surface never holds the whole document.
|
||||
let surface = photocraft_compose::composite_to_surface(doc, rect, PixelFormat::new(fmt.mode, fmt.sample, true), None);
|
||||
let surface = photocraft_compose::composite_to_surface(&one, rect, PixelFormat::new(fmt.mode, fmt.sample, true), None);
|
||||
let values = surface.read_region(rect);
|
||||
let mut data = Vec::with_capacity((aw as usize * ah as usize).saturating_mul(device));
|
||||
for px in values.chunks(n) {
|
||||
|
||||
+126
-1
@@ -1,8 +1,9 @@
|
||||
//! PDF export: structure, pixel oracle, colour modes and refusal paths.
|
||||
|
||||
use super::*;
|
||||
use lopdf::{Object, StringFormat};
|
||||
use photocraft_color::{PixelFormat, SampleType};
|
||||
use photocraft_doc::{Layer, LayerContent, Size};
|
||||
use photocraft_doc::{Artboard, Group, Layer, LayerContent, Size};
|
||||
use photocraft_geom::Rect;
|
||||
use photocraft_raster::{Interrupt, Surface};
|
||||
|
||||
@@ -420,3 +421,127 @@ fn artboards_export_as_one_page_each() {
|
||||
}
|
||||
assert_eq!(out.bytes.windows(15).filter(|w| *w == b"/Subtype /Image").count(), 2);
|
||||
}
|
||||
|
||||
/// Side-by-side 2x2 artboards at 72 dpi, named by `names` (empty names are kept).
|
||||
fn artboard_doc(names: &[&str]) -> Document {
|
||||
let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::F32, true);
|
||||
let width = (names.len() as u32).saturating_mul(2).max(2);
|
||||
let mut d = Document::new("labels.pdf", Size { width, height: 2 }, ColorMode::Rgb, SampleType::F32);
|
||||
d.resolution_dpi = 72.0;
|
||||
for (index, name) in names.iter().enumerate() {
|
||||
let x0 = (index as i32) * 2;
|
||||
let rect = Rect::new(x0, 0, x0 + 2, 2);
|
||||
let layer = Layer::new("Pixels", LayerContent::Raster(solid(fmt, rect.x0, rect.y0, rect.x1, rect.y1, &[0.5, 0.5, 0.5, 1.0])));
|
||||
let group = Group { children: vec![layer], expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None };
|
||||
d.layers.push(Layer::new(*name, LayerContent::Group(group)));
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
/// The decompressed samples of page `id`'s first image XObject (`/Im0`).
|
||||
fn page_image(pdf: &lopdf::Document, id: lopdf::ObjectId) -> Vec<u8> {
|
||||
let page = pdf.get_dictionary(id).expect("page dictionary");
|
||||
let resources = page.get(b"Resources").expect("page resources").as_dict().expect("resources dictionary");
|
||||
let xobjects = resources.get(b"XObject").expect("xobjects").as_dict().expect("xobject dictionary");
|
||||
let image = xobjects.get(b"Im0").expect("Im0").as_reference().expect("image reference");
|
||||
pdf.get_object(image).expect("image object").as_stream().expect("image stream").decompressed_content().expect("image samples")
|
||||
}
|
||||
|
||||
/// A named artboard gives every page a `/PageLabels` entry, and an empty name gets an empty
|
||||
/// label dictionary rather than inheriting the previous name.
|
||||
#[test]
|
||||
fn page_labels_name_every_page_and_an_empty_name_does_not_inherit() {
|
||||
let d = artboard_doc(&["A", "", "C"]);
|
||||
let pdf = export(&d, &Interrupt::NONE).unwrap().bytes;
|
||||
check_structure(&pdf);
|
||||
let parsed = lopdf::Document::load_mem(&pdf).unwrap();
|
||||
let labels = parsed
|
||||
.catalog()
|
||||
.unwrap()
|
||||
.get(b"PageLabels")
|
||||
.expect("a named artboard gives the PDF page labels")
|
||||
.as_reference()
|
||||
.expect("the label tree is an indirect object");
|
||||
let nums = parsed.get_dictionary(labels).unwrap().get(b"Nums").unwrap().as_array().unwrap();
|
||||
assert_eq!(nums.len(), 6, "one key and one label dictionary per page");
|
||||
for page in 0..3 {
|
||||
assert_eq!(nums[page * 2].as_i64().unwrap(), page as i64, "the tree starts at page index 0 and covers every page");
|
||||
}
|
||||
let label = |page: usize| nums[page * 2 + 1].as_dict().unwrap();
|
||||
assert_eq!(label(0).get(b"P").unwrap(), &Object::String(vec![0xFE, 0xFF, 0x00, 0x41], StringFormat::Hexadecimal), "page 1 is A");
|
||||
assert!(label(1).get(b"P").is_err(), "the empty name gets an empty dictionary, not A");
|
||||
assert_eq!(label(2).get(b"P").unwrap(), &Object::String(vec![0xFE, 0xFF, 0x00, 0x43], StringFormat::Hexadecimal), "page 3 is C");
|
||||
assert_eq!(parsed.get_pages().len(), 3);
|
||||
}
|
||||
|
||||
/// With no non-empty name there is no label tree at all: an empty `/Nums` would be invalid.
|
||||
#[test]
|
||||
fn an_all_empty_artboard_names_document_has_no_page_labels_tree() {
|
||||
let d = artboard_doc(&["", "", ""]);
|
||||
let pdf = export(&d, &Interrupt::NONE).unwrap().bytes;
|
||||
check_structure(&pdf);
|
||||
let parsed = lopdf::Document::load_mem(&pdf).unwrap();
|
||||
assert!(parsed.catalog().unwrap().get(b"PageLabels").is_err(), "no names means no /PageLabels");
|
||||
assert!(!has(&pdf, "/PageLabels"));
|
||||
assert_eq!(parsed.get_pages().len(), 3, "the pages themselves are still written");
|
||||
}
|
||||
|
||||
/// Two artboards at the same rectangle: each page must hold only its own board's pixels, not
|
||||
/// the other board composited over it.
|
||||
#[test]
|
||||
fn overlapping_artboards_export_only_their_own_pixels() {
|
||||
let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::F32, true);
|
||||
let mut d = Document::new("overlap.pdf", Size { width: 2, height: 2 }, ColorMode::Rgb, SampleType::F32);
|
||||
d.resolution_dpi = 72.0;
|
||||
for (name, color) in [("Red", [1.0, 0.0, 0.0, 1.0]), ("Blue", [0.0, 0.0, 1.0, 1.0])] {
|
||||
let layer = Layer::new("Pixels", LayerContent::Raster(solid(fmt, 0, 0, 2, 2, &color)));
|
||||
let group = Group { children: vec![layer], expanded: true, artboard: Some(Artboard::new(Rect::new(0, 0, 2, 2))), frame_stroke: None };
|
||||
d.layers.push(Layer::new(name, LayerContent::Group(group)));
|
||||
}
|
||||
let pdf = export(&d, &Interrupt::NONE).unwrap().bytes;
|
||||
let parsed = lopdf::Document::load_mem(&pdf).unwrap();
|
||||
let pages = parsed.get_pages();
|
||||
let images = pages.values().map(|id| page_image(&parsed, *id)).collect::<Vec<_>>();
|
||||
assert_eq!(images.len(), 2);
|
||||
assert_eq!(images[0], [255u8, 0, 0].repeat(4), "the bottom board's page is red, not blue over red");
|
||||
assert_eq!(images[1], [0u8, 0, 255].repeat(4), "the top board's page is blue");
|
||||
}
|
||||
|
||||
/// A large, mostly empty canvas must not be charged as if its whole area were rendered.
|
||||
#[test]
|
||||
fn sparse_canvas_artboards_export_without_a_false_memory_limit() {
|
||||
let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::F32, true);
|
||||
let mut d = Document::new("sparse.pdf", Size { width: 9000, height: 9000 }, ColorMode::Rgb, SampleType::F32);
|
||||
d.resolution_dpi = 72.0;
|
||||
for index in 0..2 {
|
||||
let x0 = index * 10;
|
||||
let rect = Rect::new(x0, 0, x0 + 2, 2);
|
||||
let layer = Layer::new("Pixels", LayerContent::Raster(solid(fmt, rect.x0, 0, rect.x1, 2, &[1.0, 0.0, 0.0, 1.0])));
|
||||
let group = Group { children: vec![layer], expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None };
|
||||
d.layers.push(Layer::new("Page", LayerContent::Group(group)));
|
||||
}
|
||||
let out = export(&d, &Interrupt::NONE).expect("two 2x2 boards on a 9000x9000 canvas must fit the export budget");
|
||||
let parsed = lopdf::Document::load_mem(&out.bytes).unwrap();
|
||||
assert_eq!(parsed.get_pages().len(), 2);
|
||||
}
|
||||
|
||||
/// Seven US Letter boards at 300 dpi with the importer's gaps: the pages are retained as encoded
|
||||
/// data, but no whole-canvas buffer exists, so the old whole-canvas charge rejected this.
|
||||
#[test]
|
||||
fn seven_us_letter_artboards_export_without_a_false_memory_limit() {
|
||||
const PAGE_W: u32 = 2550;
|
||||
const PAGE_H: u32 = 3300;
|
||||
const GAP: u32 = 80;
|
||||
const PAGES: u32 = 7;
|
||||
let mut d = Document::new("letters.pdf", Size { width: PAGES * PAGE_W + (PAGES - 1) * GAP, height: PAGE_H }, ColorMode::Rgb, SampleType::F32);
|
||||
d.resolution_dpi = 300.0;
|
||||
for index in 0..PAGES {
|
||||
let x0 = (index * (PAGE_W + GAP)) as i32;
|
||||
let rect = Rect::new(x0, 0, x0 + PAGE_W as i32, PAGE_H as i32);
|
||||
let group = Group { children: Vec::new(), expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None };
|
||||
d.layers.push(Layer::new(format!("Letter {}", index + 1), LayerContent::Group(group)));
|
||||
}
|
||||
let out = export(&d, &Interrupt::NONE).expect("seven US Letter pages at 300 dpi fit the export budget");
|
||||
let parsed = lopdf::Document::load_mem(&out.bytes).unwrap();
|
||||
assert_eq!(parsed.get_pages().len(), 7);
|
||||
}
|
||||
+121
-2
@@ -8,6 +8,9 @@
|
||||
//!
|
||||
//! The renderer is pure Rust and runs on every desktop platform: no shared library is loaded
|
||||
//! or shipped, and a malformed file is reported as an error rather than taking the process down.
|
||||
//!
|
||||
//! Pages are drawn with the interpreter's default annotation settings, so annotations and
|
||||
//! filled-in form fields are rendered; comments are not hidden.
|
||||
|
||||
use crate::{ImportOptions, ImportResult, IoError};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -23,6 +26,12 @@ use photocraft_geom::{Rect, Size};
|
||||
use photocraft_raster::Interrupt;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use photocraft_raster::Surface;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use std::sync::Arc;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use std::time::Duration;
|
||||
|
||||
/// `%PDF-` magic. `.ai` files that start with it are PDFs and render through this importer.
|
||||
pub fn is_pdf(bytes: &[u8]) -> bool {
|
||||
@@ -139,19 +148,26 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) -
|
||||
return Err(IoError::Unsupported(format!("PDF page {page_number} is too large at {dpi:.0} dpi; lower the import DPI")));
|
||||
}
|
||||
let cache = RenderCache::new();
|
||||
let settings = InterpreterSettings::default();
|
||||
let options = raster::Options {
|
||||
scale: [(dpi / 72.0) as f32; 2],
|
||||
size: Some([width, height]),
|
||||
offset: [0.0, 0.0],
|
||||
// PDF pages composite onto white, as every PDF viewer and the previous importer did.
|
||||
// craft-pdf returns premultiplied RGBA8; an opaque background makes alpha 1, so the
|
||||
// bytes below can be written as straight alpha. A transparent background would need
|
||||
// un-premultiplying (dividing each colour by alpha) first.
|
||||
background: [255, 255, 255, 255],
|
||||
color_replacement: None,
|
||||
};
|
||||
let rendered = raster::render(page, &cache, &settings, &options).map_err(|error| render_error(page_number, dpi, error))?;
|
||||
let rendered = render_page(page, &cache, &options, ctl).map_err(|error| render_error(page_number, dpi, error))?;
|
||||
if rendered.diagnostics.image_decode_failed {
|
||||
warnings.push(format!("PDF page {page_number}: an image could not be decoded and is missing"));
|
||||
}
|
||||
// craft-pdf's hayro backend does not emit this flag yet (its README says so); keep the
|
||||
// warning ready so a backend that starts reporting font substitution needs no change here.
|
||||
if rendered.diagnostics.unsupported_font {
|
||||
warnings.push(format!("PDF page {page_number}: a font could not be used and was substituted, so text may look different"));
|
||||
}
|
||||
if rendered.diagnostics.content_truncated {
|
||||
warnings.push(format!("PDF page {page_number}: some content was omitted (a decode or memory limit)"));
|
||||
}
|
||||
@@ -187,6 +203,43 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) -
|
||||
Ok(ImportResult { warnings, document: doc, source_read_only: false, preview_only: false })
|
||||
}
|
||||
|
||||
/// Renders one page, forwarding `ctl`'s cancellation to craft-pdf while it interprets content.
|
||||
///
|
||||
/// craft-pdf checks `InterpreterSettings::cancelled` between content operators, so a dense
|
||||
/// vector page (CAD, maps) can be stopped part-way through. `Interrupt` is a borrowed callback
|
||||
/// while the setting needs an owned flag, so a scoped watcher thread copies one into the other
|
||||
/// every few milliseconds until the render returns.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn render_page<'a>(
|
||||
page: &'a craft_pdf::syntax::page::Page<'a>,
|
||||
cache: &RenderCache<'a>,
|
||||
options: &raster::Options,
|
||||
ctl: &Interrupt,
|
||||
) -> Result<raster::Raster, raster::Error> {
|
||||
if ctl.cancelled() {
|
||||
return Err(raster::Error::Cancelled);
|
||||
}
|
||||
let cancelled = Arc::new(AtomicBool::new(false));
|
||||
let finished = Arc::new(AtomicBool::new(false));
|
||||
let settings = InterpreterSettings { cancelled: Some(Arc::clone(&cancelled)), ..InterpreterSettings::default() };
|
||||
std::thread::scope(|scope| {
|
||||
let flag = Arc::clone(&cancelled);
|
||||
let done = Arc::clone(&finished);
|
||||
let ctl = *ctl;
|
||||
scope.spawn(move || {
|
||||
while !done.load(Ordering::Relaxed) {
|
||||
if ctl.cancelled() {
|
||||
flag.store(true, Ordering::Relaxed);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
});
|
||||
let rendered = raster::render(page, cache, &settings, options);
|
||||
finished.store(true, Ordering::Relaxed);
|
||||
rendered
|
||||
})
|
||||
}
|
||||
|
||||
/// One page's raster width or height in pixels at `dpi`, at least one.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn page_pixels(points: f64, dpi: f64) -> u32 {
|
||||
@@ -249,3 +302,69 @@ fn render_error(page: usize, dpi: f64, error: raster::Error) -> IoError {
|
||||
Error::InvalidOptions | Error::BufferLength => IoError::Unsupported(format!("PDF page {page} could not be rendered")),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod tests {
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
|
||||
use lopdf::{Document as PdfDocument, Object, Stream, dictionary};
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A one-page PDF whose content stream is `operators` short strokes: rendering costs time
|
||||
/// per operator, not per pixel.
|
||||
fn dense_operator_pdf(operators: usize) -> Result<Vec<u8>, lopdf::Error> {
|
||||
let mut pdf = PdfDocument::with_version("1.5");
|
||||
let pages_id = pdf.new_object_id();
|
||||
let mut content = String::with_capacity(operators.saturating_mul(24));
|
||||
content.push_str("0 0 1 RG 0.5 w\n");
|
||||
for i in 0..operators {
|
||||
let x = (i % 200) as f32 * 0.5;
|
||||
let y = ((i / 200) % 100) as f32 * 0.5;
|
||||
content.push_str(&format!("{x:.1} {y:.1} m {:.1} {y:.1} l S\n", x + 0.4));
|
||||
}
|
||||
let content_id = pdf.add_object(Stream::new(dictionary! {}, content.into_bytes()));
|
||||
let page_id = pdf.add_object(dictionary! {
|
||||
"Type" => "Page",
|
||||
"Parent" => pages_id,
|
||||
"MediaBox" => Object::Array(vec![Object::Real(0.0), Object::Real(0.0), Object::Real(200.0), Object::Real(100.0)]),
|
||||
"Contents" => content_id,
|
||||
"Resources" => dictionary! {},
|
||||
});
|
||||
pdf.objects.insert(
|
||||
pages_id,
|
||||
Object::Dictionary(dictionary! {
|
||||
"Type" => "Pages",
|
||||
"Kids" => Object::Array(vec![Object::Reference(page_id)]),
|
||||
"Count" => 1,
|
||||
}),
|
||||
);
|
||||
let catalog = pdf.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages_id });
|
||||
pdf.trailer.set("Root", catalog);
|
||||
let mut bytes = Vec::new();
|
||||
pdf.save_to(&mut bytes)?;
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// Hundreds of thousands of path operators take far longer than the watcher's polling
|
||||
/// interval, so the interrupt lands mid-render and the page reports Cancelled.
|
||||
#[test]
|
||||
fn a_dense_page_stops_when_the_interrupt_fires_mid_render() {
|
||||
let pdf = dense_operator_pdf(300_000).expect("writing the dense PDF");
|
||||
let document = craft_pdf::open_slice_with_options(&pdf, None, &craft_pdf::OpenOptions::default()).expect("the dense PDF opens");
|
||||
let cache = RenderCache::new();
|
||||
let options =
|
||||
raster::Options { scale: [1.0, 1.0], size: Some([200, 100]), offset: [0.0, 0.0], background: [255, 255, 255, 255], color_replacement: None };
|
||||
let polls = AtomicUsize::new(0);
|
||||
// `render_page` checks once before spawning; the watcher then polls every 5 ms. Ten
|
||||
// polls put the cancellation about 45 ms into a render that takes much longer.
|
||||
let cancel = || polls.fetch_add(1, Ordering::SeqCst) >= 9;
|
||||
let ctl = Interrupt::cancel_only(&cancel);
|
||||
let error = match render_page(&document.pages()[0], &cache, &options, &ctl) {
|
||||
Err(error) => error,
|
||||
Ok(_) => panic!("the dense page rendered to completion before the interrupt fired"),
|
||||
};
|
||||
assert!(matches!(render_error(1, 72.0, error), IoError::Cancelled), "the render error maps to Cancelled");
|
||||
assert!(polls.load(Ordering::SeqCst) >= 10, "the watcher must keep polling the interrupt");
|
||||
}
|
||||
}
|
||||
@@ -5,8 +5,7 @@
|
||||
//! a blue rectangle sampled from the raster, and the renderer's side/pixel limits respected by
|
||||
//! lowering the effective DPI on a huge page.
|
||||
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use lopdf::{Document as PdfDocument, Object, Stream, dictionary};
|
||||
use photocraft_doc::LayerContent;
|
||||
@@ -164,34 +163,34 @@ fn huge_pages_lower_the_effective_dpi_within_the_renderer_bounds() {
|
||||
assert!((print_width - 3000.0).abs() < 1.0, "print width {print_width:.1} pt should stay 3000 pt");
|
||||
}
|
||||
|
||||
/// Cancelling on the last page check or the public boundary returns Cancelled, never a document.
|
||||
/// Cancelling at the public boundary or between pages returns Cancelled, never a document.
|
||||
///
|
||||
/// The renderer's watcher polls the interrupt while a page is being interpreted, so the number
|
||||
/// of checks is not fixed any more; these triggers do not depend on counting them.
|
||||
#[test]
|
||||
fn cancelling_on_the_last_checks_is_reported() {
|
||||
fn cancelling_before_and_between_pages_is_reported() {
|
||||
let pdf = variant_pdf();
|
||||
let options = ImportOptions { pdf_dpi: 72.0, ..Default::default() };
|
||||
let count = AtomicUsize::new(0);
|
||||
let cancel = || {
|
||||
count.fetch_add(1, Ordering::SeqCst);
|
||||
false
|
||||
};
|
||||
let ctl = Interrupt::cancel_only(&cancel);
|
||||
let result = import_with_options_and_interrupt("variants.pdf", &pdf, &options, &ctl);
|
||||
assert!(result.is_ok(), "uncancelled import failed: {:?}", result.err());
|
||||
let total = count.load(Ordering::SeqCst);
|
||||
assert!(total >= 3, "a complete import should check cancellation at least three times, got {total}");
|
||||
for (label, threshold) in [("the last page check", total - 1), ("the public boundary check", total)] {
|
||||
let seen = AtomicUsize::new(0);
|
||||
let cancel = || seen.fetch_add(1, Ordering::SeqCst) + 1 >= threshold;
|
||||
let ctl = Interrupt::cancel_only(&cancel);
|
||||
let started = Instant::now();
|
||||
let result = import_with_options_and_interrupt("variants.pdf", &pdf, &options, &ctl);
|
||||
let elapsed = started.elapsed();
|
||||
assert_eq!(seen.load(Ordering::SeqCst), threshold, "cancelling on {label} should stop at check {threshold} of {total}");
|
||||
match result {
|
||||
Err(IoError::Cancelled) => {}
|
||||
Ok(_) => panic!("cancelling on {label} returned a document"),
|
||||
Err(error) => panic!("cancelling on {label} returned {error:?}"),
|
||||
|
||||
// The boundary check before dispatch: already cancelled.
|
||||
let always = || true;
|
||||
let ctl = Interrupt::cancel_only(&always);
|
||||
match import_with_options_and_interrupt("variants.pdf", &pdf, &options, &ctl) {
|
||||
Err(IoError::Cancelled) => {}
|
||||
other => panic!("an already-cancelled import returned {:?}", other.map(|_| ())),
|
||||
}
|
||||
|
||||
// The per-page loop's check: the first page's progress cancels the next iteration.
|
||||
let cancelled = AtomicBool::new(false);
|
||||
let cancel = || cancelled.load(Ordering::SeqCst);
|
||||
let progress = |fraction: f32| {
|
||||
if fraction > 0.0 {
|
||||
cancelled.store(true, Ordering::SeqCst);
|
||||
}
|
||||
assert!(elapsed < Duration::from_secs(10), "cancelling on {label} took {elapsed:?}");
|
||||
};
|
||||
let ctl = Interrupt::new(&cancel, &progress);
|
||||
match import_with_options_and_interrupt("variants.pdf", &pdf, &options, &ctl) {
|
||||
Err(IoError::Cancelled) => {}
|
||||
other => panic!("cancelling after the first page returned {:?}", other.map(|_| ())),
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user