From 95c9d3c9eb018452af8c2caa2ba205b0612196db Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 03:59:22 +0100 Subject: [PATCH 01/30] PDF import: open the first page with PDFium File > Open, drag-and-drop and photocraft-cli now accept PDF files. The first page is rendered with PDFium at 300 dpi (ImportOptions.pdf_dpi), built through the flat importer, and the document resolution keeps the page's print size. The page count is reported; multi-page import is the next step (#2541 / FILE-215-10). - crates/io: pdf_import module, native-only pdfium-render + image deps, import and preflight dispatch (.ai keeps its existing path). - PDFium loads from the executable's folder or PDFIUM_DIR. --- Cargo.lock | 78 +++++++++++++++++++++++++++++++++++++ crates/io/Cargo.toml | 3 ++ crates/io/src/lib.rs | 20 +++++++++- crates/io/src/pdf_import.rs | 76 ++++++++++++++++++++++++++++++++++++ 4 files changed, 175 insertions(+), 2 deletions(-) create mode 100644 crates/io/src/pdf_import.rs diff --git a/Cargo.lock b/Cargo.lock index 201ca61db06..d3221556bc1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -874,6 +874,12 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + [[package]] name = "byteorder-lite" version = "0.1.0" @@ -1278,6 +1284,26 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "console_error_panic_hook" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc" +dependencies = [ + "cfg-if", + "wasm-bindgen", +] + +[[package]] +name = "console_log" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86919cef3e37b9356ccf54d4421208c17ecfda01beae61393e7ffd72916c0ef1" +dependencies = [ + "log", + "web-sys", +] + [[package]] name = "const-oid" version = "0.9.6" @@ -5008,6 +5034,32 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" +[[package]] +name = "pdfium-render" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "296b1146652b486ea6eea0d316e85ab6837ff69e8d2b1568e6fa7bc38bd4c00e" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "bytes", + "chrono", + "console_error_panic_hook", + "console_log", + "image", + "itertools 0.15.0", + "js-sys", + "libloading", + "log", + "maybe-owned", + "once_cell", + "utf16string", + "vecmath", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + [[package]] name = "pem" version = "3.0.6" @@ -5412,9 +5464,11 @@ dependencies = [ "craft-docpath", "crc32fast", "flate2", + "image", "imagesize", "lopdf", "miniz_oxide 0.9.1", + "pdfium-render", "photocraft-affinity", "photocraft-algo", "photocraft-cms", @@ -5723,6 +5777,12 @@ dependencies = [ "system-deps", ] +[[package]] +name = "piston-float" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad78bf43dcf80e8f950c92b84f938a0fc7590b7f6866fbcbeca781609c115590" + [[package]] name = "pkg-config" version = "0.3.34" @@ -8205,6 +8265,15 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c8232dd3cdaed5356e0f716d285e4b40b932ac434100fe9b7e0e8e935b9e6246" +[[package]] +name = "utf16string" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b62a1e85e12d5d712bf47a85f426b73d303e2d00a90de5f3004df3596e9d216" +dependencies = [ + "byteorder", +] + [[package]] name = "utf8-zero" version = "0.8.1" @@ -8246,6 +8315,15 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "vecmath" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "956ae1e0d85bca567dee1dcf87fb1ca2e792792f66f87dced8381f99cd91156a" +dependencies = [ + "piston-float", +] + [[package]] name = "vello_common" version = "0.2.0" diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index dcd86482db4..ef151b80cfb 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -51,6 +51,9 @@ imagesize = "0.13" resvg = { version = "0.45", default-features = false, features = ["text", "system-fonts", "raster-images"] } # The SVG fallback font search keeps each font file's character map (already in the tree through usvg). ttf-parser = { version = "0.25", default-features = false } +# PDF import (pdf_import.rs): PDFium renders the pages; the direct surfaces build the document. +pdfium-render = "0.9" +image = { workspace = true, features = ["png"] } [target.'cfg(target_arch = "wasm32")'.dependencies] resvg = { version = "0.45", default-features = false, features = ["text", "raster-images"] } diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 68b1754e614..a828b5ff12b 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -65,6 +65,7 @@ pub use ora::losses as ora_losses; pub mod pattern_map; mod pcraft_cache; pub mod pdf; +mod pdf_import; mod pdn; pub use pcraft_cache::PcraftExportCache; pub mod pixels; @@ -513,8 +514,8 @@ pub enum ImportPreflight { /// A flat raster decoded into one image, bounded by /// [`ImportOptions::flat_max_pixel_bytes`]. Flat, - /// Affinity, OpenRaster, Krita, XCF, PDN, SVG, camera raw and `.pcraft` files: this build has - /// no header-only estimate of their pixel memory before decoding. + /// Affinity, OpenRaster, Krita, XCF, PDN, SVG, camera raw, PDF and `.pcraft` files: this + /// build has no header-only estimate of their pixel memory before decoding. Unbounded, } @@ -555,6 +556,10 @@ pub fn import_preflight(name: &str, bytes: &[u8]) -> ImportPreflight { if is_psd_input(name, bytes) { return ImportPreflight::Psd; } + // PDF (PDFium, native only); `.ai` files are PDFs but keep their existing path. + if has_extension(name, "pdf") || (pdf_import::is_pdf(bytes) && !has_extension(name, "ai")) { + return ImportPreflight::Unbounded; + } if photocraft_codecs::detect(bytes) == Some(photocraft_codecs::Format::Tiff) { ImportPreflight::Tiff } else { ImportPreflight::Flat } } @@ -601,6 +606,9 @@ pub struct ImportOptions { /// Decoded-pixel allowance for a flat raster (the buffer a codec decodes into). May lower /// the codec's default cap; 0 uses it. PSD/PSB and layered TIFF use `psd_max_pixel_bytes`. pub flat_max_pixel_bytes: u64, + /// Resolution (dots per inch) PDF pages are rendered at on import; the document keeps it so + /// the page's print size is preserved. Defaults to 300. + pub pdf_dpi: f32, /// Explicit one-shot authorization for imports that exceed the soft budget but fit within the hard budget. pub psd_high_memory_approved: bool, /// Optional estimate limit for high-memory approval. When set, approval only applies if @@ -615,6 +623,7 @@ impl Default for ImportOptions { demosaic: raw::Demosaic::default(), psd_max_pixel_bytes: 0, flat_max_pixel_bytes: 0, + pdf_dpi: 300.0, psd_high_memory_approved: false, psd_approved_estimate: None, } @@ -975,6 +984,13 @@ pub(crate) fn route(name: &str, bytes: &[u8]) -> Route { /// Dispatches format-specific importers and propagates a structured PSD damage /// flag alongside the ordinary best-effort import result. fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, opts: &ImportOptions, damaged: &mut bool) -> Result { + // PDF (PDFium, native only). `.ai` files are PDFs but keep their existing path; a recognized + // raster signature wins over a misleading `.pdf` suffix. + if pdf_import::is_pdf(bytes) + || (has_extension(name, "pdf") && !has_extension(name, "ai") && photocraft_codecs::detect(bytes).is_none()) + { + return pdf_import::import(name, bytes, opts); + } match route(name, bytes) { Route::Pcraft => { let document = photocraft_format::load_from_bytes(bytes)?; diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs new file mode 100644 index 00000000000..ca9d9849931 --- /dev/null +++ b/crates/io/src/pdf_import.rs @@ -0,0 +1,76 @@ +//! PDF import: PDFium renders the first page to a PNG and the flat importer builds the document. +//! +//! The page's print size is preserved by setting the document resolution to the import DPI: +//! pixels ÷ DPI × 72 pt is the PDF page's size again. Multi-page import, vector/text extraction +//! and page management are the next steps (see PLAN.md in the local PDF project). + +use crate::{ImportOptions, ImportResult, IoError}; + +/// `%PDF-` magic. `.ai` files are PDFs too, but the dispatch keeps them out of this importer. +pub fn is_pdf(bytes: &[u8]) -> bool { + bytes.starts_with(b"%PDF-") +} + +/// Native PDF import is not available in the web build. +#[cfg(target_arch = "wasm32")] +pub fn import(_name: &str, _bytes: &[u8], _opts: &ImportOptions) -> Result { + Err(IoError::Unsupported("PDF import needs the desktop build".into())) +} + +/// Renders the PDF's first page at [`ImportOptions::pdf_dpi`] and opens it as a flat document. +#[cfg(not(target_arch = "wasm32"))] +pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions) -> Result { + use image::ImageEncoder; + use pdfium_render::prelude::*; + + let dpi = if opts.pdf_dpi.is_finite() && opts.pdf_dpi > 0.0 { opts.pdf_dpi } else { 300.0 }; + let pdfium = bind()?; + let document = pdfium.load_pdf_from_byte_slice(bytes, None).map_err(|e| IoError::Unsupported(format!("PDF: {e}")))?; + let page_count = document.pages().len(); + let page = document.pages().get(0).map_err(|e| IoError::Unsupported(format!("PDF: {e}")))?; + let width_pt = f64::from(page.width().value); + // A page can be arbitrarily large; cap the raster so a hostile PDF cannot request a huge + // allocation. 20,000 px is far above a poster at 300 dpi. + let target_width = (width_pt * f64::from(dpi) / 72.0).round().clamp(1.0, 20_000.0) as i32; + let config = PdfRenderConfig::new().set_target_width(target_width); + let bitmap = page.render_with_config(&config).map_err(|e| IoError::Unsupported(format!("PDF render: {e}")))?; + let (width, height) = (bitmap.width().max(0) as u32, bitmap.height().max(0) as u32); + let rgba = bitmap.as_rgba_bytes(); + let image = image::RgbaImage::from_raw(width, height, rgba) + .ok_or_else(|| IoError::Unsupported("PDF: the rendered bitmap does not match its buffer".into()))?; + // Reuse the well-tested flat importer (the PNG still carries the alpha and colour exactly). + let mut png = Vec::new(); + image::codecs::png::PngEncoder::new(&mut png) + .write_image(image.as_raw(), width, height, image::ExtendedColorType::Rgba8) + .map_err(|e| IoError::Unsupported(format!("PDF: encoding the rendered page: {e}")))?; + let mut result = crate::flat::import_flat(name, &png)?; + result.document.resolution_dpi = dpi; + result.document.name = name.to_string(); + if page_count > 1 { + result + .warnings + .push(format!("PDF has {page_count} pages; this build imports page 1 (multi-page import is the next step)")); + } + Ok(result) +} + +/// Loads the PDFium shared library from the executable's folder (`PDFIUM_DIR` overrides it). +#[cfg(not(target_arch = "wasm32"))] +fn bind() -> Result { + use pdfium_render::prelude::Pdfium; + + let dir = std::env::var_os("PDFIUM_DIR").map(std::path::PathBuf::from).unwrap_or_else(|| { + std::env::current_exe() + .ok() + .and_then(|exe| exe.parent().map(std::path::Path::to_path_buf)) + .unwrap_or_default() + }); + let library = Pdfium::pdfium_platform_library_name_at_path(&dir); + let bindings = Pdfium::bind_to_library(&library).map_err(|e| { + IoError::Unsupported(format!( + "PDF import: cannot load PDFium from {} ({e}); put pdfium.dll next to the executable or set PDFIUM_DIR", + library.display() + )) + })?; + Ok(Pdfium::new(bindings)) +} From 399cd6ea4de6febaedff5a67f4e009496f233bd6 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 13:44:49 +0100 Subject: [PATCH 02/30] PDF: import every page as an artboard; export a page per artboard The PDF importer renders each page with PDFium at the import DPI (default 300), lays the pages out side by side and wraps each in an artboard, so a 2-page PDF opens as 2 artboards and saves back as a 2-page PDF (one page per artboard, page-sized, labelled). The import caps at 16 pages for now. The PDF writer now takes a list of pages: shared font/ICC/selection objects, one image per page, and the existing one-page export is the single-page case. Artboards with vector/text layers are rasterised in this path. Tested: artboards_export_as_one_page_each; convert sample.pdf app-multi.pdf (2 pages), rendered back with the probe. --- crates/io/src/pdf.rs | 169 ++++++++++++++++++++++++------------ crates/io/src/pdf/tests.rs | 26 ++++++ crates/io/src/pdf_import.rs | 96 +++++++++++++------- 3 files changed, 204 insertions(+), 87 deletions(-) diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index d693ee941b1..71c2818b978 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -109,10 +109,12 @@ fn marks_ops(m: Marks, (x, y, w, h): (f64, f64, f64, f64)) -> String { /// A one-page PDF. pub fn print_pdf(page: &PrintPage) -> Vec { - print_pdf_with_vectors(page, "", &selection::SelectionFont::default()) + print_pdf_pages(std::slice::from_ref(page), &[String::new()], &selection::SelectionFont::default()) } -fn print_pdf_with_vectors(page: &PrintPage, vectors: &str, selection_font: &selection::SelectionFont) -> Vec { +/// A PDF with one page per entry; `vectors[i]` (when present) is drawn over page `i`. +fn print_pdf_pages(pages: &[PrintPage], vectors: &[String], selection_font: &selection::SelectionFont) -> Vec { + let Some(first) = pages.first() else { return Vec::new() }; let mut out: Vec = b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n".to_vec(); let mut offsets: Vec = Vec::new(); let mut obj = |out: &mut Vec, body: &[u8]| { @@ -121,58 +123,78 @@ fn print_pdf_with_vectors(page: &PrintPage, vectors: &str, selection_font: &sele out.extend_from_slice(body); out.extend_from_slice(b"\nendobj\n"); }; - let img = &page.image; - let (pw, ph) = page.paper; - let (x, y, w, h) = page.rect; - let selection_base = if img.icc.is_some() { 8 } else { 7 }; - // 1 catalog, 2 pages, 3 page, 4 contents, 5 image, 6 font, 7 ICC (optional). + let n = pages.len(); + // 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 }; obj(&mut out, b"<< /Type /Catalog /Pages 2 0 R >>"); - obj(&mut out, b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>"); - obj( - &mut out, - format!( - "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {pw:.2} {ph:.2}] /Resources << /XObject << /Im0 5 0 R >> /Font << /F1 6 0 R /FSelect {selection_base} 0 R >> >> /Contents 4 0 R >>" + let kids = (0..n).map(|i| format!("{} 0 R", 3 + i * 3)).collect::>().join(" "); + obj(&mut out, format!("<< /Type /Pages /Kids [{kids}] /Count {n} >>").as_bytes()); + for (i, page) in pages.iter().enumerate() { + let page_obj = 3 + i * 3; + let content_obj = page_obj + 1; + let image_obj = page_obj + 2; + let (pw, ph) = page.paper; + let (x, y, w, h) = page.rect; + obj( + &mut out, + format!( + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {pw:.2} {ph:.2}] /Resources << /XObject << /Im0 {image_obj} 0 R >> /Font << /F1 {font_obj} 0 R /FSelect {selection_base} 0 R >> >> /Contents {content_obj} 0 R >>" + ) + .as_bytes(), + ); + // An explicit white page, so every viewer (and rasteriser) shows paper, not transparency. + let mut content = format!("q 1 g 0 0 {pw:.2} {ph:.2} re f Q\nq {w:.3} 0 0 {h:.3} {x:.3} {y:.3} cm /Im0 Do Q\n"); + if let Some(v) = vectors.get(i) { + content.push_str(v); + } + content.push_str(&marks_ops(page.marks, page.rect)); + let any_marks = page.marks.corner_crop || page.marks.center_crop || page.marks.registration; + let pad = if any_marks { 30.0 } else { 6.0 }; + if let Some(l) = page.label.as_deref().filter(|l| !l.is_empty()) { + content.push_str(&format!("BT /F1 8 Tf 0 g {:.2} {:.2} Td {} Tj ET\n", x, y + h + pad, pdf_string(l))); + } + if let Some(d) = page.description.as_deref().filter(|d| !d.is_empty()) { + content.push_str(&format!("BT /F1 8 Tf 0 g {:.2} {:.2} Td {} Tj ET\n", x, y - pad - 8.0, pdf_string(d))); + } + let c = deflate(content.as_bytes()); + let mut body = format!("<< /Length {} /Filter /FlateDecode >>\nstream\n", c.len()).into_bytes(); + body.extend_from_slice(&c); + body.extend_from_slice(b"\nendstream"); + obj(&mut out, &body); + let img = &page.image; + let device = match img.channels { + 1 => "/DeviceGray", + 4 => "/DeviceCMYK", + _ => "/DeviceRGB", + }; + let cs = match icc_obj { + Some(obj) => format!("[/ICCBased {obj} 0 R]"), + None => device.to_string(), + }; + let z = deflate(&img.data); + let mut body = format!( + "<< /Type /XObject /Subtype /Image /Width {} /Height {} /ColorSpace {cs} /BitsPerComponent 8 /Filter /FlateDecode /Length {} >>\nstream\n", + img.width, + img.height, + z.len() ) - .as_bytes(), - ); - // An explicit white page, so every viewer (and rasteriser) shows paper, not transparency. - let mut content = format!("q 1 g 0 0 {pw:.2} {ph:.2} re f Q\nq {w:.3} 0 0 {h:.3} {x:.3} {y:.3} cm /Im0 Do Q\n"); - content.push_str(vectors); - content.push_str(&marks_ops(page.marks, page.rect)); - let any_marks = page.marks.corner_crop || page.marks.center_crop || page.marks.registration; - let pad = if any_marks { 30.0 } else { 6.0 }; - if let Some(l) = page.label.as_deref().filter(|l| !l.is_empty()) { - content.push_str(&format!("BT /F1 8 Tf 0 g {:.2} {:.2} Td {} Tj ET\n", x, y + h + pad, pdf_string(l))); + .into_bytes(); + body.extend_from_slice(&z); + body.extend_from_slice(b"\nendstream"); + obj(&mut out, &body); } - if let Some(d) = page.description.as_deref().filter(|d| !d.is_empty()) { - content.push_str(&format!("BT /F1 8 Tf 0 g {:.2} {:.2} Td {} Tj ET\n", x, y - pad - 8.0, pdf_string(d))); - } - let c = deflate(content.as_bytes()); - let mut body = format!("<< /Length {} /Filter /FlateDecode >>\nstream\n", c.len()).into_bytes(); - body.extend_from_slice(&c); - body.extend_from_slice(b"\nendstream"); - obj(&mut out, &body); - let device = match img.channels { - 1 => "/DeviceGray", - 4 => "/DeviceCMYK", - _ => "/DeviceRGB", - }; - let cs = if img.icc.is_some() { "[/ICCBased 7 0 R]".to_string() } else { device.to_string() }; - let z = deflate(&img.data); - let mut body = format!( - "<< /Type /XObject /Subtype /Image /Width {} /Height {} /ColorSpace {cs} /BitsPerComponent 8 /Filter /FlateDecode /Length {} >>\nstream\n", - img.width, - img.height, - z.len() - ) - .into_bytes(); - body.extend_from_slice(&z); - body.extend_from_slice(b"\nendstream"); - obj(&mut out, &body); obj(&mut out, b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>"); - if let Some(icc) = &img.icc { + if let Some(icc) = icc { + let device = match first.image.channels { + 1 => "/DeviceGray", + 4 => "/DeviceCMYK", + _ => "/DeviceRGB", + }; let z = deflate(icc); - let mut body = format!("<< /N {} /Alternate {device} /Filter /FlateDecode /Length {} >>\nstream\n", img.channels, z.len()).into_bytes(); + let mut body = format!("<< /N {} /Alternate {device} /Filter /FlateDecode /Length {} >>\nstream\n", first.image.channels, z.len()).into_bytes(); body.extend_from_slice(&z); body.extend_from_slice(b"\nendstream"); obj(&mut out, &body); @@ -261,9 +283,10 @@ fn collect_vectors(doc: &Document) -> (Vec<(usize, String)>, selection::Selectio (layers, selection_font) } -/// File › Save As / Save a Copy › PDF (#3401): the flattened document, at its print size -/// (pixels ÷ resolution × 72 pt), as a one-page PDF. Layers and transparency are dropped — the -/// warning says so — and the embedded profile travels with the image. +/// 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 +/// the embedded profile travels with the images. pub fn export(doc: &Document) -> std::result::Result { let (w, h) = (usize::try_from(doc.size.width).unwrap_or(0), usize::try_from(doc.size.height).unwrap_or(0)); if w == 0 || h == 0 { @@ -277,6 +300,41 @@ pub fn export(doc: &Document) -> std::result::Result { }; let fmt = doc.pixel_format(); let n = fmt.channels().max(1); + let dpi = f64::from(doc.resolution_dpi.max(1.0)); + let paper = if doc.mode == ColorMode::Cmyk { 0.0 } else { 1.0 }; + let to8 = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + let icc = doc.icc_profile.as_ref().map(|p| p.to_vec()); + let artboards = doc.artboards(); + if !artboards.is_empty() { + // One flattened pass of the whole document; each artboard is a crop of it. + let surface = photocraft_compose::flatten_to_surface(doc, PixelFormat::new(fmt.mode, fmt.sample, true), None); + let mut pages = Vec::with_capacity(artboards.len()); + for (_, name, artboard) in &artboards { + let rect = artboard.rect; + let (aw, ah) = (rect.width(), rect.height()); + if aw == 0 || ah == 0 { + continue; + } + 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) { + let a = px.last().copied().unwrap_or(1.0).clamp(0.0, 1.0); + for v in px.iter().take(device) { + data.push(to8(v * a + paper * (1.0 - a))); + } + } + let image = PrintImage { width: aw, height: ah, channels: device, data, icc: icc.clone() }; + let (pw, ph) = (f64::from(aw) * 72.0 / dpi, f64::from(ah) * 72.0 / dpi); + pages.push(PrintPage { paper: (pw, ph), image, rect: (0.0, 0.0, pw, ph), marks: Marks::default(), description: None, label: Some((*name).to_string()) }); + } + if pages.is_empty() { + return Err(IoError::Unsupported("PDF: the document's artboards have no area".into())); + } + let mut warnings = vec!["PDF was saved flattened: layers, masks-as-editable and transparency are not preserved (#3401)".into()]; + warnings.push(format!("PDF exported {} artboards as {} pages; vector/text layers on artboards are rasterised", artboards.len(), pages.len())); + let vectors = vec![String::new(); pages.len()]; + return Ok(ExportResult { bytes: print_pdf_pages(&pages, &vectors, &selection::SelectionFont::default()), warnings }); + } let canvas = photocraft_geom::Rect::new(0, 0, w as i32, h as i32); // Simple topmost shapes and text layers can be drawn over the flattened backdrop without changing // compositing. Stop at the first unsupported visible layer, since it may depend on the @@ -290,10 +348,8 @@ pub fn export(doc: &Document) -> std::result::Result { } let surface = photocraft_compose::flatten_to_surface(&backdrop, PixelFormat::new(fmt.mode, fmt.sample, true), None); let values = surface.read_region(canvas); - let to8 = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; // Straight alpha, composited here over paper: white in RGB/Gray (1 = full light), zero ink // in CMYK (0 = paper). - let paper = if doc.mode == ColorMode::Cmyk { 0.0 } else { 1.0 }; let mut data = Vec::with_capacity((w * h).saturating_mul(device)); for px in values.chunks(n) { let a = px.last().copied().unwrap_or(1.0).clamp(0.0, 1.0); @@ -301,8 +357,7 @@ pub fn export(doc: &Document) -> std::result::Result { data.push(to8(v * a + paper * (1.0 - a))); } } - let image = PrintImage { width: doc.size.width, height: doc.size.height, channels: device, data, icc: doc.icc_profile.as_ref().map(|p| p.to_vec()) }; - let dpi = f64::from(doc.resolution_dpi.max(1.0)); + let image = PrintImage { width: doc.size.width, height: doc.size.height, channels: device, data, icc: icc.clone() }; let (pw, ph) = (f64::from(doc.size.width) * 72.0 / dpi, f64::from(doc.size.height) * 72.0 / dpi); let page = PrintPage { paper: (pw, ph), image, rect: (0.0, 0.0, pw, ph), marks: Marks::default(), description: None, label: None }; let mut warnings = vec!["PDF was saved flattened: layers, masks-as-editable and transparency are not preserved (#3401)".into()]; @@ -315,7 +370,7 @@ pub fn export(doc: &Document) -> std::result::Result { vectors.push_str(ops); } vectors.push_str("Q\n"); - Ok(ExportResult { bytes: print_pdf_with_vectors(&page, &vectors, &selection_font), warnings }) + Ok(ExportResult { bytes: print_pdf_pages(&[page], &[vectors], &selection_font), warnings }) } #[cfg(test)] diff --git a/crates/io/src/pdf/tests.rs b/crates/io/src/pdf/tests.rs index e745623e41d..0364fa6e1ae 100644 --- a/crates/io/src/pdf/tests.rs +++ b/crates/io/src/pdf/tests.rs @@ -393,3 +393,29 @@ fn leading_newline_stays_in_the_first_selection_span() { let content = String::from_utf8(stream_after(&pdf, "/Contents 4 0 R")).unwrap(); assert!(content.contains("/ActualText "), "the first span retains the leading newline:\n{content}"); } + +#[test] +fn artboards_export_as_one_page_each() { + use photocraft_doc::{Artboard, Group}; + let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::F32, true); + let mut d = Document::new("pages.pdf", Size { width: 40, height: 30 }, ColorMode::Rgb, SampleType::F32); + d.resolution_dpi = 72.0; + for (rect, px) in [(Rect::new(0, 0, 20, 30), [1.0, 0.0, 0.0, 1.0]), (Rect::new(20, 0, 40, 30), [0.0, 0.0, 1.0, 1.0])] { + let layer = Layer::new("Pixels", LayerContent::Raster(solid(fmt, rect.x0, rect.y0, rect.x1, rect.y1, &px))); + 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).unwrap(); + check_structure(&out.bytes); + let parsed = lopdf::Document::load_mem(&out.bytes).unwrap(); + let pages = parsed.get_pages(); + assert_eq!(pages.len(), 2); + for id in pages.values() { + let page = parsed.get_dictionary(*id).unwrap(); + let media = page.get(b"MediaBox").unwrap().as_array().unwrap(); + let w = media[2].as_float().or_else(|_| media[2].as_i64().map(|v| v as f32)).unwrap(); + let h = media[3].as_float().or_else(|_| media[3].as_i64().map(|v| v as f32)).unwrap(); + assert!((w - 20.0).abs() < 0.01 && (h - 30.0).abs() < 0.01, "page {w}x{h}"); + } + assert_eq!(out.bytes.windows(15).filter(|w| *w == b"/Subtype /Image").count(), 2); +} diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index ca9d9849931..b35a224dd7b 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -1,10 +1,12 @@ -//! PDF import: PDFium renders the first page to a PNG and the flat importer builds the document. +//! PDF import: PDFium renders every page and each page becomes an artboard. //! -//! The page's print size is preserved by setting the document resolution to the import DPI: -//! pixels ÷ DPI × 72 pt is the PDF page's size again. Multi-page import, vector/text extraction -//! and page management are the next steps (see PLAN.md in the local PDF project). +//! The document resolution is the import DPI, so pixels ÷ DPI × 72 pt is the PDF page's size +//! again. Pages are laid out side by side with a small gap; more than [`MAX_PAGES`] pages are +//! capped so the union canvas stays bounded. use crate::{ImportOptions, ImportResult, IoError}; +use photocraft_doc::{Artboard, Document, Group, Layer, LayerContent}; +use photocraft_geom::Rect; /// `%PDF-` magic. `.ai` files are PDFs too, but the dispatch keeps them out of this importer. pub fn is_pdf(bytes: &[u8]) -> bool { @@ -17,41 +19,75 @@ pub fn import(_name: &str, _bytes: &[u8], _opts: &ImportOptions) -> Result Result { use image::ImageEncoder; use pdfium_render::prelude::*; + /// The most pages one import renders; more would make the union canvas enormous. + const MAX_PAGES: usize = 16; + /// Gap between the artboards, in document pixels. + const GAP: u32 = 80; + let dpi = if opts.pdf_dpi.is_finite() && opts.pdf_dpi > 0.0 { opts.pdf_dpi } else { 300.0 }; let pdfium = bind()?; let document = pdfium.load_pdf_from_byte_slice(bytes, None).map_err(|e| IoError::Unsupported(format!("PDF: {e}")))?; - let page_count = document.pages().len(); - let page = document.pages().get(0).map_err(|e| IoError::Unsupported(format!("PDF: {e}")))?; - let width_pt = f64::from(page.width().value); - // A page can be arbitrarily large; cap the raster so a hostile PDF cannot request a huge - // allocation. 20,000 px is far above a poster at 300 dpi. - let target_width = (width_pt * f64::from(dpi) / 72.0).round().clamp(1.0, 20_000.0) as i32; - let config = PdfRenderConfig::new().set_target_width(target_width); - let bitmap = page.render_with_config(&config).map_err(|e| IoError::Unsupported(format!("PDF render: {e}")))?; - let (width, height) = (bitmap.width().max(0) as u32, bitmap.height().max(0) as u32); - let rgba = bitmap.as_rgba_bytes(); - let image = image::RgbaImage::from_raw(width, height, rgba) - .ok_or_else(|| IoError::Unsupported("PDF: the rendered bitmap does not match its buffer".into()))?; - // Reuse the well-tested flat importer (the PNG still carries the alpha and colour exactly). - let mut png = Vec::new(); - image::codecs::png::PngEncoder::new(&mut png) - .write_image(image.as_raw(), width, height, image::ExtendedColorType::Rgba8) - .map_err(|e| IoError::Unsupported(format!("PDF: encoding the rendered page: {e}")))?; - let mut result = crate::flat::import_flat(name, &png)?; - result.document.resolution_dpi = dpi; - result.document.name = name.to_string(); - if page_count > 1 { - result - .warnings - .push(format!("PDF has {page_count} pages; this build imports page 1 (multi-page import is the next step)")); + let total = document.pages().len().max(0) as usize; + let count = total.min(MAX_PAGES); + if count == 0 { + return Err(IoError::Unsupported("PDF has no pages".into())); } - Ok(result) + // Render first, so a malformed later page fails before any document is built. + let mut rendered = Vec::with_capacity(count); + for index in 0..count { + let page = document.pages().get(index as i32).map_err(|e| IoError::Unsupported(format!("PDF: {e}")))?; + let width_pt = f64::from(page.width().value); + // A page can be arbitrarily large; cap the raster so a hostile PDF cannot request a huge + // allocation. 20,000 px is far above a poster at 300 dpi. + let target_width = (width_pt * f64::from(dpi) / 72.0).round().clamp(1.0, 20_000.0) as i32; + let config = PdfRenderConfig::new().set_target_width(target_width); + let bitmap = page.render_with_config(&config).map_err(|e| IoError::Unsupported(format!("PDF render: {e}")))?; + let (width, height) = (bitmap.width().max(0) as u32, bitmap.height().max(0) as u32); + rendered.push((width, height, bitmap.as_rgba_bytes())); + } + let doc_width = rendered.iter().map(|(w, _, _)| *w).sum::() + GAP * (count as u32 - 1); + let doc_height = rendered.iter().map(|(_, h, _)| *h).max().unwrap_or(1); + let mut doc: Option = None; + let mut x = 0u32; + for (index, (width, height, rgba)) in rendered.into_iter().enumerate() { + // Reuse the well-tested flat importer: the page is composited into the union canvas at its + // artboard position, encoded as PNG, and decoded into a document-wide raster layer. + let mut canvas = image::RgbaImage::new(doc_width, doc_height); + let page = image::RgbaImage::from_raw(width, height, rgba) + .ok_or_else(|| IoError::Unsupported("PDF: the rendered bitmap does not match its buffer".into()))?; + image::imageops::overlay(&mut canvas, &page, i64::from(x), 0); + let mut png = Vec::new(); + image::codecs::png::PngEncoder::new(&mut png) + .write_image(canvas.as_raw(), doc_width, doc_height, image::ExtendedColorType::Rgba8) + .map_err(|e| IoError::Unsupported(format!("PDF: encoding the rendered page: {e}")))?; + let mut result = crate::flat::import_flat(name, &png)?; + let layer = result.document.layers.pop().ok_or_else(|| IoError::Unsupported("PDF: the page decoded to an empty layer".into()))?; + let rect = Rect::new(x as i32, 0, (x + width) as i32, height as i32); + let group = Group { children: vec![layer], expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None }; + let artboard = Layer::new(format!("Page {}", index + 1), LayerContent::Group(group)); + match &mut doc { + None => { + result.document.layers = vec![artboard]; + doc = Some(result.document); + } + Some(d) => d.layers.push(artboard), + } + x += width + GAP; + } + let mut doc = doc.ok_or_else(|| IoError::Unsupported("PDF has no pages".into()))?; + doc.resolution_dpi = dpi; + doc.name = name.to_string(); + let mut warnings = Vec::new(); + if total > count { + warnings.push(format!("PDF has {total} pages; imported the first {count} (the limit is {MAX_PAGES})")); + } + Ok(ImportResult { warnings, document: doc, source_read_only: false, preview_only: false }) } /// Loads the PDFium shared library from the executable's folder (`PDFIUM_DIR` overrides it). From c1662d49116d73cf1760d37f7089a232a5159c6e Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 13:45:00 +0100 Subject: [PATCH 03/30] Export: split nested groups into separate layers/files file.export.layersToFiles gains groups: layers (walk every visible leaf at any depth, not only top-level layers) and naming: layer (bare .png names; duplicates get -2). This is the recursive folder export from the local Program Files build, brought in as the second fix on this branch. Tested: layers_to_files_exports_group_children_as_loose_files (nested subgroup + sibling). --- crates/engine/src/cmd/file_cmds/export.rs | 138 ++++++++++++++++------ crates/engine/src/cmd/file_cmds/tests.rs | 75 ++++++++++++ 2 files changed, 175 insertions(+), 38 deletions(-) diff --git a/crates/engine/src/cmd/file_cmds/export.rs b/crates/engine/src/cmd/file_cmds/export.rs index 1f7f9677ffa..ef947a5f214 100644 --- a/crates/engine/src/cmd/file_cmds/export.rs +++ b/crates/engine/src/cmd/file_cmds/export.rs @@ -20,7 +20,7 @@ pub fn export_layers_with(s: &Session, p: &Value, write: impl FnMut(&str, &[u8]) export_layers_report_with(s, p, write).map(|report| report.files) } -/// A top-level layer omitted from a successful Layers to Files export. +/// A layer omitted from a successful Layers to Files export. #[derive(Debug, serde::Serialize)] pub struct SkippedExportLayer { /// Session layer id (names need not be unique). @@ -38,14 +38,59 @@ pub struct LayerExportReport { pub skipped: Vec, } -/// The same export as [`export_layers_with`], with an explanation for every omitted top-level -/// layer. Groups export merged, so their children are not separate exports or skips. Encoding -/// and write failures remain errors, never successful skips. Existing numbering is preserved. +/// One layer the export will write or explain, in top-to-bottom order. +enum Planned<'a> { + Export(&'a Layer), + Skip(&'a Layer, &'static str), + Hidden(&'a Layer), +} + +/// Flattens a layer (and, with `split_groups`, its group descendants) into export entries. +fn plan_layer<'a>(layer: &'a Layer, split_groups: bool, visible_only: bool, plan: &mut Vec>) { + if !layer.visible && visible_only { + plan.push(Planned::Hidden(layer)); + return; + } + if let LayerContent::Group(group) = &layer.content + && split_groups + { + for child in group.children.iter().rev() { + plan_layer(child, split_groups, visible_only, plan); + } + return; + } + if matches!(layer.content, LayerContent::Adjustment(_)) { + plan.push(Planned::Skip(layer, "adjustment layer has no pixels of its own")); + } else { + plan.push(Planned::Export(layer)); + } +} + +/// The same export as [`export_layers_with`], with an explanation for every omitted layer. +/// +/// `groups` chooses what a group produces: `"merged"` (the default) exports the group as one +/// file, as before; `"layers"` walks into the group and exports each visible layer inside it as +/// its own file (top to bottom), so no group is a file of its own. Encoding and write failures +/// remain errors, never successful skips. Existing numbering is preserved. pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result { let cmd = "file.export.layersToFiles"; let format = p.get("format").and_then(Value::as_str).unwrap_or("png").trim_start_matches('.').to_ascii_lowercase(); let trim = p.get("trim").and_then(Value::as_bool).unwrap_or(false); let visible_only = p.get("visibleOnly").and_then(Value::as_bool).unwrap_or(true); + let split_groups = match p.get("groups").and_then(Value::as_str).unwrap_or("merged") { + "merged" => false, + "layers" => true, + other => { + return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("groups must be \"merged\" or \"layers\", not {other:?}") }); + } + }; + let layer_names = match p.get("naming").and_then(Value::as_str).map(|s| s.to_ascii_lowercase()).as_deref() { + None | Some("numbered") => false, + Some("layer") => true, + Some(other) => { + return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("naming must be \"numbered\" or \"layer\", not {other:?}") }); + } + }; // Callers outside `Session::execute` (headless workspace exports) carry the session's gate // into `encode`, so a PSD embeds no file a linked smart object names. let _authorization = crate::jobs::render_authorization_scope(s.authorize); @@ -53,48 +98,65 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& let d = s.active().ok_or(EngineError::NoDocument)?; let prefix = p.get("prefix").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name)); let doc = d.doc.clone(); + let mut plan = Vec::new(); + for l in doc.layers.iter().rev() { + plan_layer(l, split_groups, visible_only, &mut plan); + } let mut report = LayerExportReport::default(); + let mut used = std::collections::HashSet::new(); // Hidden layers never consumed a filename index; adjustments that pass the visibility // filter did. Keep those filenames stable while reporting both kinds of omission. let mut i = 0usize; - for l in doc.layers.iter().rev() { - if !l.visible && visible_only { - report.skipped.push(SkippedExportLayer { layer: l.id.0, name: l.name.clone(), reason: "hidden by visibleOnly" }); - continue; - } - let index = i; - i += 1; - if matches!(l.content, LayerContent::Adjustment(_)) { - report.skipped.push(SkippedExportLayer { layer: l.id.0, name: l.name.clone(), reason: "adjustment layer has no pixels of its own" }); - continue; - } - let mut one = (*doc).clone(); - let mut only = l.clone(); - only.visible = true; - only.clipped = false; - one.layers = vec![only]; - if trim { - let mut bounds = Rect::EMPTY; - let _ = photocraft_compose::render_bands(&one, one.bounds(), 0, |band| -> std::result::Result<(), ()> { - let width = band.rect.width() as usize; - for (i, rgba) in band.px.iter().enumerate() { - if rgba[3] > 0.0 && width > 0 { - let x = band.rect.x0 + (i % width) as i32; - let y = band.rect.y0 + (i / width) as i32; - bounds = bounds.union(&Rect::new(x, y, x + 1, y + 1)); + for entry in plan { + match entry { + Planned::Hidden(l) => report.skipped.push(SkippedExportLayer { layer: l.id.0, name: l.name.clone(), reason: "hidden by visibleOnly" }), + Planned::Skip(l, reason) => { + i += 1; + report.skipped.push(SkippedExportLayer { layer: l.id.0, name: l.name.clone(), reason }); + } + Planned::Export(l) => { + let index = i; + i += 1; + let mut one = (*doc).clone(); + let mut only = l.clone(); + only.visible = true; + only.clipped = false; + one.layers = vec![only]; + if trim { + let mut bounds = Rect::EMPTY; + let _ = photocraft_compose::render_bands(&one, one.bounds(), 0, |band| -> std::result::Result<(), ()> { + let width = band.rect.width() as usize; + for (i, rgba) in band.px.iter().enumerate() { + if rgba[3] > 0.0 && width > 0 { + let x = band.rect.x0 + (i % width) as i32; + let y = band.rect.y0 + (i / width) as i32; + bounds = bounds.union(&Rect::new(x, y, x + 1, y + 1)); + } + } + Ok(()) + }); + if !bounds.is_empty() && bounds != one.bounds() { + crate::image_cmds::crop_doc(&mut one, cmd, bounds, true, [0.0; 4])?; } } - Ok(()) - }); - if !bounds.is_empty() && bounds != one.bounds() { - crate::image_cmds::crop_doc(&mut one, cmd, bounds, true, [0.0; 4])?; + + let name = if layer_names { + let base = sanitize(&l.name); + let mut name = format!("{base}.{format}"); + let mut n = 2; + while !used.insert(name.clone()) { + name = format!("{base}-{n}.{format}"); + n += 1; + } + name + } else { + format!("{}_{:04}_{}.{format}", sanitize(&prefix), index, sanitize(&l.name)) + }; + let (bytes, _warnings) = encode(&one, &name, save)?; + write(&name, &bytes)?; + report.files.push(name); } } - - let name = format!("{}_{:04}_{}.{format}", sanitize(&prefix), index, sanitize(&l.name)); - let (bytes, _warnings) = encode(&one, &name, save)?; - write(&name, &bytes)?; - report.files.push(name); } Ok(report) } diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index 26e172ffd6d..7c989079837 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -2538,6 +2538,81 @@ fn layers_to_files_reports_skipped_layers_without_changing_files() { } } +#[test] +fn layers_to_files_exports_group_children_as_loose_files() { + let dir = tmp("layers-groups"); + let mut s = session(8, 8, 8); + s.edit("Group", |doc, _| { + let fmt = doc.pixel_format(); + let child = |name: &str| photocraft_doc::Layer::new(name, photocraft_doc::LayerContent::Raster(photocraft_doc::Surface::new(fmt))); + let sub = photocraft_doc::Layer::new( + "sub", + photocraft_doc::LayerContent::Group(photocraft_doc::Group { + children: vec![child("c")], + expanded: true, + artboard: None, + frame_stroke: None, + }), + ); + doc.layers.push(photocraft_doc::Layer::new( + "expanded", + photocraft_doc::LayerContent::Group(photocraft_doc::Group { + children: vec![child("a"), child("b"), sub], + expanded: true, + artboard: None, + frame_stroke: None, + }), + )); + Ok(()) + }) + .unwrap(); + let files = |r: &Value| -> Vec { r["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect() }; + + let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "loose", "groups": "layers"})).unwrap(); + assert_eq!( + files(&r), + vec![ + join(&dir, "loose_0000_c.png"), + join(&dir, "loose_0001_b.png"), + join(&dir, "loose_0002_a.png"), + join(&dir, "loose_0003_Background.png") + ] + ); + assert!(files(&r).iter().all(|f| std::path::Path::new(f).is_file())); + + // The default still merges the group into one file. + let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "merged"})).unwrap(); + assert_eq!(files(&r), vec![join(&dir, "merged_0000_expanded.png"), join(&dir, "merged_0001_Background.png")]); + + // naming: "layer" writes the bare layer names instead of prefix_index_name. + let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "groups": "layers", "naming": "layer"})).unwrap(); + assert_eq!(files(&r), vec![join(&dir, "c.png"), join(&dir, "b.png"), join(&dir, "a.png"), join(&dir, "Background.png")]); + + // A hidden child is skipped with visibleOnly and exported without it. + s.edit("Hide b", |doc, _| { + let group = doc.layers.last_mut().ok_or_else(|| EngineError::Other("no group".into()))?; + let LayerContent::Group(g) = &mut group.content else { return Err(EngineError::Other("not a group".into())) }; + g.children[1].visible = false; + Ok(()) + }) + .unwrap(); + let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "visible", "groups": "layers"})).unwrap(); + assert_eq!(files(&r), vec![join(&dir, "visible_0000_c.png"), join(&dir, "visible_0001_a.png"), join(&dir, "visible_0002_Background.png")]); + let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "all", "groups": "layers", "visibleOnly": false})).unwrap(); + assert_eq!( + files(&r), + vec![ + join(&dir, "all_0000_c.png"), + join(&dir, "all_0001_b.png"), + join(&dir, "all_0002_a.png"), + join(&dir, "all_0003_Background.png") + ] + ); + + // An unknown mode is rejected instead of silently merging. + assert!(s.execute("file.export.layersToFiles", json!({"dir": dir, "groups": "folders"})).is_err()); +} + #[test] fn layers_to_files_reports_groups_as_exports_and_failures_as_errors() { let mut s = session(4, 4, 8); From 3a1b41f0c65873c845e9a190f05d9dd9f02f2666 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 13:55:45 +0100 Subject: [PATCH 04/30] PDF: bound the import canvas The importer budgets the per-page raster (100 M px) and the artboard strip (200 M px): an oversized page is scaled down, and pages that would exceed the strip budget are skipped with a warning, instead of allocating a multi-gigabyte union canvas. The page-count cap stays 16. Also applies cargo fmt to the new PDF code and the export-recursion test. --- crates/engine/src/cmd/file_cmds/tests.rs | 21 ++-------- crates/io/src/pdf.rs | 9 +++- crates/io/src/pdf_import.rs | 52 ++++++++++++++++++------ 3 files changed, 50 insertions(+), 32 deletions(-) diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index 7c989079837..6a14a7542b1 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -2547,12 +2547,7 @@ fn layers_to_files_exports_group_children_as_loose_files() { let child = |name: &str| photocraft_doc::Layer::new(name, photocraft_doc::LayerContent::Raster(photocraft_doc::Surface::new(fmt))); let sub = photocraft_doc::Layer::new( "sub", - photocraft_doc::LayerContent::Group(photocraft_doc::Group { - children: vec![child("c")], - expanded: true, - artboard: None, - frame_stroke: None, - }), + photocraft_doc::LayerContent::Group(photocraft_doc::Group { children: vec![child("c")], expanded: true, artboard: None, frame_stroke: None }), ); doc.layers.push(photocraft_doc::Layer::new( "expanded", @@ -2571,12 +2566,7 @@ fn layers_to_files_exports_group_children_as_loose_files() { let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "loose", "groups": "layers"})).unwrap(); assert_eq!( files(&r), - vec![ - join(&dir, "loose_0000_c.png"), - join(&dir, "loose_0001_b.png"), - join(&dir, "loose_0002_a.png"), - join(&dir, "loose_0003_Background.png") - ] + vec![join(&dir, "loose_0000_c.png"), join(&dir, "loose_0001_b.png"), join(&dir, "loose_0002_a.png"), join(&dir, "loose_0003_Background.png")] ); assert!(files(&r).iter().all(|f| std::path::Path::new(f).is_file())); @@ -2601,12 +2591,7 @@ fn layers_to_files_exports_group_children_as_loose_files() { let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "all", "groups": "layers", "visibleOnly": false})).unwrap(); assert_eq!( files(&r), - vec![ - join(&dir, "all_0000_c.png"), - join(&dir, "all_0001_b.png"), - join(&dir, "all_0002_a.png"), - join(&dir, "all_0003_Background.png") - ] + vec![join(&dir, "all_0000_c.png"), join(&dir, "all_0001_b.png"), join(&dir, "all_0002_a.png"), join(&dir, "all_0003_Background.png")] ); // An unknown mode is rejected instead of silently merging. diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index 71c2818b978..55e70d03185 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -325,7 +325,14 @@ pub fn export(doc: &Document) -> std::result::Result { } let image = PrintImage { width: aw, height: ah, channels: device, data, icc: icc.clone() }; let (pw, ph) = (f64::from(aw) * 72.0 / dpi, f64::from(ah) * 72.0 / dpi); - pages.push(PrintPage { paper: (pw, ph), image, rect: (0.0, 0.0, pw, ph), marks: Marks::default(), description: None, label: Some((*name).to_string()) }); + pages.push(PrintPage { + paper: (pw, ph), + image, + rect: (0.0, 0.0, pw, ph), + marks: Marks::default(), + description: None, + label: Some((*name).to_string()), + }); } if pages.is_empty() { return Err(IoError::Unsupported("PDF: the document's artboards have no area".into())); diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index b35a224dd7b..7bd5f76df9a 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -38,19 +38,47 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions) -> Result MAX_PAGE_PIXELS { + let scale = (MAX_PAGE_PIXELS / area).sqrt(); + target_width = (target_width * scale).max(1.0); + } + let config = PdfRenderConfig::new().set_target_width(target_width as i32); let bitmap = page.render_with_config(&config).map_err(|e| IoError::Unsupported(format!("PDF render: {e}")))?; let (width, height) = (bitmap.width().max(0) as u32, bitmap.height().max(0) as u32); + // Stop before the strip exceeds the union budget; the pages rendered so far stay. + let next_width = union_width + u64::from(width) + if rendered.is_empty() { 0 } else { u64::from(GAP) }; + let next_height = union_height.max(u64::from(height)); + if next_width.saturating_mul(next_height) > MAX_UNION_PIXELS { + break; + } + union_width = next_width; + union_height = next_height; rendered.push((width, height, bitmap.as_rgba_bytes())); } + let count = rendered.len(); + if count == 0 { + return Err(IoError::Unsupported("PDF pages are too large to import; reduce the DPI".into())); + } let doc_width = rendered.iter().map(|(w, _, _)| *w).sum::() + GAP * (count as u32 - 1); let doc_height = rendered.iter().map(|(_, h, _)| *h).max().unwrap_or(1); let mut doc: Option = None; @@ -59,8 +87,8 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions) -> Result Result count { - warnings.push(format!("PDF has {total} pages; imported the first {count} (the limit is {MAX_PAGES})")); + let reason = if total > MAX_PAGES { "the page limit is 16" } else { "the rest would make the import canvas too large" }; + warnings.push(format!("PDF has {total} pages; imported the first {count} ({reason})")); } Ok(ImportResult { warnings, document: doc, source_read_only: false, preview_only: false }) } @@ -95,12 +124,9 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions) -> Result Result { use pdfium_render::prelude::Pdfium; - let dir = std::env::var_os("PDFIUM_DIR").map(std::path::PathBuf::from).unwrap_or_else(|| { - std::env::current_exe() - .ok() - .and_then(|exe| exe.parent().map(std::path::Path::to_path_buf)) - .unwrap_or_default() - }); + let dir = std::env::var_os("PDFIUM_DIR") + .map(std::path::PathBuf::from) + .unwrap_or_else(|| std::env::current_exe().ok().and_then(|exe| exe.parent().map(std::path::Path::to_path_buf)).unwrap_or_default()); let library = Pdfium::pdfium_platform_library_name_at_path(&dir); let bindings = Pdfium::bind_to_library(&library).map_err(|e| { IoError::Unsupported(format!( From 94a4998208f9b5528c4f038010d5bcbcf3a3299a Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 14:53:46 +0100 Subject: [PATCH 05/30] PDF: address CodeRabbit review (cancellation, budgets, labels, export edges) - Cancellation: the importer and the PDF writer take the Interrupt and check between pages. - Physical size: the effective DPI keeps each page print size when budgets cap the raster. - Oversized pages: final dimensions are checked before rendering. - Memory: pages go straight into layer surfaces; the aggregate pixel estimate is admitted. - Labels: /PageLabels (UTF-16BE) carry artboard names; no label is drawn outside the media box. - Metadata: the artboard export warns when free-form text metadata is dropped. - Export: hidden groups report their children; non-string modes are rejected; case-insensitive filename collisions are suffixed. - Dispatch: a recognised raster renamed .pdf goes to the flat importer; .ai keeps its path. - Platform: the PDFium recovery message names the actual library. --- crates/engine/src/cmd/file_cmds/export.rs | 50 +++++-- crates/io/src/lib.rs | 14 +- crates/io/src/pdf.rs | 37 ++++- crates/io/src/pdf/tests.rs | 36 ++--- crates/io/src/pdf_import.rs | 167 ++++++++++++---------- 5 files changed, 192 insertions(+), 112 deletions(-) diff --git a/crates/engine/src/cmd/file_cmds/export.rs b/crates/engine/src/cmd/file_cmds/export.rs index ef947a5f214..629b7aad822 100644 --- a/crates/engine/src/cmd/file_cmds/export.rs +++ b/crates/engine/src/cmd/file_cmds/export.rs @@ -49,6 +49,12 @@ enum Planned<'a> { fn plan_layer<'a>(layer: &'a Layer, split_groups: bool, visible_only: bool, plan: &mut Vec>) { if !layer.visible && visible_only { plan.push(Planned::Hidden(layer)); + // A hidden group takes its descendants with it; report each so the omission is complete. + if split_groups && let LayerContent::Group(group) = &layer.content { + for child in group.children.iter().rev() { + plan_hidden(child, plan); + } + } return; } if let LayerContent::Group(group) = &layer.content @@ -66,6 +72,16 @@ fn plan_layer<'a>(layer: &'a Layer, split_groups: bool, visible_only: bool, plan } } +/// Marks `layer` and all of its descendants as hidden, top to bottom. +fn plan_hidden<'a>(layer: &'a Layer, plan: &mut Vec>) { + plan.push(Planned::Hidden(layer)); + if let LayerContent::Group(group) = &layer.content { + for child in group.children.iter().rev() { + plan_hidden(child, plan); + } + } +} + /// The same export as [`export_layers_with`], with an explanation for every omitted layer. /// /// `groups` chooses what a group produces: `"merged"` (the default) exports the group as one @@ -77,19 +93,27 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& let format = p.get("format").and_then(Value::as_str).unwrap_or("png").trim_start_matches('.').to_ascii_lowercase(); let trim = p.get("trim").and_then(Value::as_bool).unwrap_or(false); let visible_only = p.get("visibleOnly").and_then(Value::as_bool).unwrap_or(true); - let split_groups = match p.get("groups").and_then(Value::as_str).unwrap_or("merged") { - "merged" => false, - "layers" => true, - other => { - return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("groups must be \"merged\" or \"layers\", not {other:?}") }); - } + let split_groups = match p.get("groups") { + None => false, + Some(Value::String(s)) => match s.to_ascii_lowercase().as_str() { + "merged" => false, + "layers" => true, + other => { + return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("groups must be \"merged\" or \"layers\", not {other:?}") }); + } + }, + Some(_) => return Err(EngineError::BadParams { cmd: cmd.into(), msg: "groups must be a string: \"merged\" or \"layers\"".into() }), }; - let layer_names = match p.get("naming").and_then(Value::as_str).map(|s| s.to_ascii_lowercase()).as_deref() { - None | Some("numbered") => false, - Some("layer") => true, - Some(other) => { - return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("naming must be \"numbered\" or \"layer\", not {other:?}") }); - } + let layer_names = match p.get("naming") { + None => false, + Some(Value::String(s)) => match s.to_ascii_lowercase().as_str() { + "numbered" => false, + "layer" => true, + other => { + return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("naming must be \"numbered\" or \"layer\", not {other:?}") }); + } + }, + Some(_) => return Err(EngineError::BadParams { cmd: cmd.into(), msg: "naming must be a string: \"numbered\" or \"layer\"".into() }), }; // Callers outside `Session::execute` (headless workspace exports) carry the session's gate // into `encode`, so a PSD embeds no file a linked smart object names. @@ -144,7 +168,7 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& let base = sanitize(&l.name); let mut name = format!("{base}.{format}"); let mut n = 2; - while !used.insert(name.clone()) { + while !used.insert(name.to_ascii_lowercase()) { name = format!("{base}-{n}.{format}"); n += 1; } diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index a828b5ff12b..1f69b40ea4f 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -556,8 +556,9 @@ pub fn import_preflight(name: &str, bytes: &[u8]) -> ImportPreflight { if is_psd_input(name, bytes) { return ImportPreflight::Psd; } - // PDF (PDFium, native only); `.ai` files are PDFs but keep their existing path. - if has_extension(name, "pdf") || (pdf_import::is_pdf(bytes) && !has_extension(name, "ai")) { + // PDF (PDFium, native only). `.ai` files are PDFs but keep their existing path; a recognized + // raster signature wins over a misleading `.pdf` suffix. + if pdf_import::is_pdf(bytes) || (has_extension(name, "pdf") && !has_extension(name, "ai") && photocraft_codecs::detect(bytes).is_none()) { return ImportPreflight::Unbounded; } if photocraft_codecs::detect(bytes) == Some(photocraft_codecs::Format::Tiff) { ImportPreflight::Tiff } else { ImportPreflight::Flat } @@ -978,6 +979,7 @@ pub(crate) fn route(name: &str, bytes: &[u8]) -> Route { if is_psd_input(name, bytes) { return Route::NamedPsd; } +<<<<<<< HEAD Route::Flat } @@ -990,6 +992,12 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, o || (has_extension(name, "pdf") && !has_extension(name, "ai") && photocraft_codecs::detect(bytes).is_none()) { return pdf_import::import(name, bytes, opts); +======= + // PDF (PDFium, native only). `.ai` files are PDFs but keep their existing path; a recognized + // raster signature wins over a misleading `.pdf` suffix. + if pdf_import::is_pdf(bytes) || (has_extension(name, "pdf") && !has_extension(name, "ai") && photocraft_codecs::detect(bytes).is_none()) { + return pdf_import::import(name, bytes, opts, ctl); +>>>>>>> 806c53fd2 (PDF: address CodeRabbit review (cancellation, budgets, labels, export edges)) } match route(name, bytes) { Route::Pcraft => { @@ -1170,7 +1178,7 @@ fn export_stages_with_renderer( return Ok(res.into()); } if ext == "pdf" { - let mut res = pdf::export(doc)?; + let mut res = pdf::export(doc, ctl)?; if let Some(r) = renderer { res.warnings.push("PDF export uses CPU compositor; GPU rendering applies to flat formats".into()); res.warnings.extend(r.drain_diagnostics()); diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index 55e70d03185..4317784e501 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -44,6 +44,8 @@ pub struct PrintPage { pub marks: Marks, pub description: Option, pub label: Option, + /// The page's name in the PDF `/PageLabels` tree (Unicode-capable; not drawn on the page). + pub page_label: Option, } pub(super) fn pdf_string(s: &str) -> String { @@ -62,6 +64,16 @@ pub(super) fn pdf_string(s: &str) -> String { o } +/// A PDF text string with UTF-16BE hex (the Unicode-capable form, byte-order mark included). +fn pdf_unicode_string(s: &str) -> String { + let mut o = String::from("'); + o +} + fn deflate(data: &[u8]) -> Vec { // Fast: print PDFs are transient and large. Level 3, not 1: zlib-rs level 1 writes static // Huffman blocks only (13-30% bigger on photos); level 3 is the lowest that is never bigger @@ -124,12 +136,14 @@ fn print_pdf_pages(pages: &[PrintPage], vectors: &[String], selection_font: &sel out.extend_from_slice(b"\nendobj\n"); }; let n = pages.len(); + let selections_on = pages.iter().any(|p| p.page_label.is_some()); // 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 }; - obj(&mut out, b"<< /Type /Catalog /Pages 2 0 R >>"); + let labels_obj = selections_on.then_some(selection_base + 1); + 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::>().join(" "); obj(&mut out, format!("<< /Type /Pages /Kids [{kids}] /Count {n} >>").as_bytes()); for (i, page) in pages.iter().enumerate() { @@ -202,6 +216,15 @@ fn print_pdf_pages(pages: &[PrintPage], vectors: &[String], selection_font: &sel for body in selection_font.objects(selection_base) { obj(&mut out, &body); } + if labels_obj.is_some() { + 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)))) + .collect::>() + .join(" "); + obj(&mut out, format!("<< /Nums [{nums}] >>").as_bytes()); + } let xref = out.len(); out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", offsets.len() + 1).as_bytes()); for o in &offsets { @@ -287,7 +310,8 @@ fn collect_vectors(doc: &Document) -> (Vec<(usize, String)>, selection::Selectio /// (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 /// the embedded profile travels with the images. -pub fn export(doc: &Document) -> std::result::Result { +pub fn export(doc: &Document, ctl: &photocraft_raster::Interrupt) -> std::result::Result { + ctl.check().map_err(|_| IoError::Cancelled)?; let (w, h) = (usize::try_from(doc.size.width).unwrap_or(0), usize::try_from(doc.size.height).unwrap_or(0)); if w == 0 || h == 0 { return Err(IoError::Unsupported("PDF needs a document with non-zero width and height; nothing was written".into())); @@ -310,6 +334,7 @@ pub fn export(doc: &Document) -> std::result::Result { let surface = photocraft_compose::flatten_to_surface(doc, PixelFormat::new(fmt.mode, fmt.sample, true), None); let mut pages = Vec::with_capacity(artboards.len()); for (_, name, artboard) in &artboards { + ctl.check().map_err(|_| IoError::Cancelled)?; let rect = artboard.rect; let (aw, ah) = (rect.width(), rect.height()); if aw == 0 || ah == 0 { @@ -331,7 +356,8 @@ pub fn export(doc: &Document) -> std::result::Result { rect: (0.0, 0.0, pw, ph), marks: Marks::default(), description: None, - label: Some((*name).to_string()), + label: None, + page_label: Some((*name).to_string()), }); } if pages.is_empty() { @@ -339,6 +365,9 @@ pub fn export(doc: &Document) -> std::result::Result { } let mut warnings = vec!["PDF was saved flattened: layers, masks-as-editable and transparency are not preserved (#3401)".into()]; warnings.push(format!("PDF exported {} artboards as {} pages; vector/text layers on artboards are rasterised", artboards.len(), pages.len())); + if !doc.metadata.text.is_empty() { + warnings.push("free-form text metadata is not supported by PDF; it will be dropped".into()); + } let vectors = vec![String::new(); pages.len()]; return Ok(ExportResult { bytes: print_pdf_pages(&pages, &vectors, &selection::SelectionFont::default()), warnings }); } @@ -366,7 +395,7 @@ pub fn export(doc: &Document) -> std::result::Result { } let image = PrintImage { width: doc.size.width, height: doc.size.height, channels: device, data, icc: icc.clone() }; let (pw, ph) = (f64::from(doc.size.width) * 72.0 / dpi, f64::from(doc.size.height) * 72.0 / dpi); - let page = PrintPage { paper: (pw, ph), image, rect: (0.0, 0.0, pw, ph), marks: Marks::default(), description: None, label: None }; + let page = PrintPage { paper: (pw, ph), image, rect: (0.0, 0.0, pw, ph), marks: Marks::default(), description: None, label: None, page_label: None }; let mut warnings = vec!["PDF was saved flattened: layers, masks-as-editable and transparency are not preserved (#3401)".into()]; if !doc.metadata.text.is_empty() { warnings.push("free-form text metadata is not supported by PDF; it will be dropped".into()); diff --git a/crates/io/src/pdf/tests.rs b/crates/io/src/pdf/tests.rs index 0364fa6e1ae..30c38a2698a 100644 --- a/crates/io/src/pdf/tests.rs +++ b/crates/io/src/pdf/tests.rs @@ -4,7 +4,7 @@ use super::*; use photocraft_color::{PixelFormat, SampleType}; use photocraft_doc::{Layer, LayerContent, Size}; use photocraft_geom::Rect; -use photocraft_raster::Surface; +use photocraft_raster::{Interrupt, Surface}; fn solid(fmt: PixelFormat, x0: i32, y0: i32, x1: i32, y1: i32, px: &[f32]) -> Surface { let mut s = Surface::new(fmt); @@ -68,7 +68,7 @@ fn check_structure(pdf: &[u8]) { #[test] fn a_flat_rgb_document_saves_as_one_page_pdf() { let d = doc(ColorMode::Rgb); - let out = export(&d).unwrap(); + let out = export(&d, &Interrupt::NONE).unwrap(); let pdf = &out.bytes; check_structure(pdf); assert!(has(pdf, "/MediaBox [0 0 4.00 2.00]"), "page = image size at 72 pt/in"); @@ -85,7 +85,7 @@ fn layers_composite_over_white_before_the_page() { let mut d = doc(ColorMode::Rgb); let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::F32, true); d.layers.push(Layer::new("Half red", LayerContent::Raster(solid(fmt, 1, 0, 3, 2, &[1.0, 0.0, 0.0, 0.5])))); - let out = export(&d).unwrap(); + let out = export(&d, &Interrupt::NONE).unwrap(); let img = stream_after(&out.bytes, "/Subtype /Image"); // Pixels 1-2 of row 0: 0.5 red over white = (1.0, 0.5, 0.5); elsewhere plain white. assert_eq!(&img[3..6], &[255, 128, 128], "the blend lands: {:?}", &img[3..6]); @@ -102,7 +102,7 @@ fn topmost_solid_shape_is_exported_as_a_vector_path() { ..Default::default() }; d.layers.push(Layer::new("Shape", LayerContent::Shape(shape))); - let out = export(&d).unwrap(); + let out = export(&d, &Interrupt::NONE).unwrap(); check_structure(&out.bytes); let content = stream_after(&out.bytes, "/Contents 4 0 R"); let content = String::from_utf8(content).unwrap(); @@ -128,7 +128,7 @@ fn topmost_text_layer_is_exported_with_selectable_text_and_vector_outlines() { let baseline = layout.lines.get(cluster.line).expect("a line").baseline; let origin = text.transform.apply(photocraft_geom::Point::new(f64::from(cluster.x), f64::from(baseline))); d.layers.push(Layer::new("Text", LayerContent::Text(text))); - let out = export(&d).unwrap(); + let out = export(&d, &Interrupt::NONE).unwrap(); check_structure(&out.bytes); let content = stream_after(&out.bytes, "/Contents 4 0 R"); let content = String::from_utf8(content).unwrap(); @@ -159,7 +159,7 @@ fn topmost_shape_and_text_layers_are_both_exported_as_vectors() { d.layers.push(Layer::new("Shape", LayerContent::Shape(shape))); let text = TextLayer { text: "Hi".into(), size_pt: 12.0, color: photocraft_color::Color::rgb(0.0, 1.0, 0.0), ..Default::default() }; d.layers.push(Layer::new("Text", LayerContent::Text(text))); - let out = export(&d).unwrap(); + let out = export(&d, &Interrupt::NONE).unwrap(); check_structure(&out.bytes); let content = stream_after(&out.bytes, "/Contents 4 0 R"); let content = String::from_utf8(content).unwrap(); @@ -173,10 +173,10 @@ fn topmost_shape_and_text_layers_are_both_exported_as_vectors() { #[test] fn greyscale_and_cmyk_pages_keep_their_channels() { - let g = export(&doc(ColorMode::Grayscale)).unwrap(); + let g = export(&doc(ColorMode::Grayscale), &Interrupt::NONE).unwrap(); assert!(has(&g.bytes, "/ColorSpace /DeviceGray"), "gray is DeviceGray"); assert_eq!(stream_after(&g.bytes, "/Subtype /Image"), vec![255; 4 * 2], "one sample per pixel"); - let c = export(&doc(ColorMode::Cmyk)).unwrap(); + let c = export(&doc(ColorMode::Cmyk), &Interrupt::NONE).unwrap(); assert!(has(&c.bytes, "/ColorSpace /DeviceCMYK"), "cmyk is DeviceCMYK"); assert_eq!(stream_after(&c.bytes, "/Subtype /Image"), vec![0; 4 * 2 * 4], "zero ink over the whole page"); } @@ -188,7 +188,7 @@ fn the_page_measures_at_the_document_resolution() { let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::F32, true); d.layers = vec![Layer::new("Paper", LayerContent::Raster(solid(fmt, 0, 0, 300, 150, &[1.0, 1.0, 1.0, 1.0])))]; d.resolution_dpi = 300.0; - let out = export(&d).unwrap(); + let out = export(&d, &Interrupt::NONE).unwrap(); assert!(has(&out.bytes, "/MediaBox [0 0 72.00 36.00]"), "300 px at 300 dpi is one inch"); } @@ -196,7 +196,7 @@ fn the_page_measures_at_the_document_resolution() { fn an_embedded_profile_travels_as_iccbased() { let mut d = doc(ColorMode::Rgb); d.icc_profile = Some(std::sync::Arc::new(vec![1, 2, 3, 4, 5, 6, 7, 8])); - let out = export(&d).unwrap(); + let out = export(&d, &Interrupt::NONE).unwrap(); assert!(has(&out.bytes, "[/ICCBased 7 0 R]"), "the image refers to the profile"); assert_eq!(stream_after(&out.bytes, "/N 3 /Alternate"), vec![1, 2, 3, 4, 5, 6, 7, 8], "the profile bytes survive"); } @@ -204,7 +204,7 @@ fn an_embedded_profile_travels_as_iccbased() { #[test] fn other_modes_are_refused_with_an_actionable_error() { let d = doc(ColorMode::Lab); - let e = export(&d).unwrap_err().to_string(); + let e = export(&d, &Interrupt::NONE).unwrap_err().to_string(); assert!(e.contains("RGB") && e.contains("Mode"), "{e}"); assert!(crate::export(&d, "x.pdf", &crate::ExportOptions::default()).is_err()); } @@ -226,7 +226,7 @@ fn unicode_text_over_a_photo_extracts_through_a_pdf_reader() { ..Default::default() }), )); - let pdf = export(&d).unwrap().bytes; + let pdf = export(&d, &Interrupt::NONE).unwrap().bytes; let parsed = lopdf::Document::load_mem(&pdf).unwrap(); assert_eq!(parsed.extract_text(&[1]).unwrap().trim(), text); assert!(has(&pdf, "/Subtype /Image")); @@ -266,7 +266,7 @@ fn text_with_compositing_or_a_profile_stays_in_the_raster_backdrop() { _ => d.icc_profile = Some(std::sync::Arc::new(vec![1, 2, 3, 4])), } d.layers.push(layer); - let pdf = export(&d).unwrap().bytes; + let pdf = export(&d, &Interrupt::NONE).unwrap().bytes; let content = String::from_utf8(stream_after(&pdf, "/Contents 4 0 R")).unwrap(); assert!(!content.contains("/ActualText"), "case {case} must retain the raster composite"); assert!(stream_after(&pdf, "/Subtype /Image").iter().any(|v| *v != 255), "case {case} must retain visible text"); @@ -304,7 +304,7 @@ fn text_outside_the_vector_prefix_does_not_consume_the_selection_font() { "Top text", LayerContent::Text(TextLayer { text: "Hi".into(), size_pt: 12.0, color: photocraft_color::Color::rgb(0.0, 1.0, 0.0), ..Default::default() }), )); - let pdf = export(&d).unwrap().bytes; + let pdf = export(&d, &Interrupt::NONE).unwrap().bytes; let parsed = lopdf::Document::load_mem(&pdf).unwrap(); assert_eq!(parsed.extract_text(&[1]).unwrap().trim(), "Hi", "case {case}: only the top text is selectable"); let content = String::from_utf8(stream_after(&pdf, "/Contents 4 0 R")).unwrap(); @@ -355,7 +355,7 @@ fn a_text_layer_refused_at_emission_keeps_the_upper_vectors_and_stays_raster() { ..Default::default() }), )); - let pdf = export(&d).unwrap().bytes; + let pdf = export(&d, &Interrupt::NONE).unwrap().bytes; check_structure(&pdf); let content = String::from_utf8(stream_after(&pdf, "/Contents 4 0 R")).unwrap(); assert!(content.contains("/ActualText "), "the first span retains the leading newline:\n{content}"); } @@ -405,7 +405,7 @@ fn artboards_export_as_one_page_each() { 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).unwrap(); + let out = export(&d, &Interrupt::NONE).unwrap(); check_structure(&out.bytes); let parsed = lopdf::Document::load_mem(&out.bytes).unwrap(); let pages = parsed.get_pages(); diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index 7bd5f76df9a..58ec5fa70ba 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -1,12 +1,14 @@ //! PDF import: PDFium renders every page and each page becomes an artboard. //! -//! The document resolution is the import DPI, so pixels ÷ DPI × 72 pt is the PDF page's size -//! again. Pages are laid out side by side with a small gap; more than [`MAX_PAGES`] pages are -//! capped so the union canvas stays bounded. +//! The document resolution is chosen so the page's physical size is preserved even when the +//! raster is capped: pixels ÷ resolution × 72 pt is the PDF page's size. Pages are laid out side +//! by side; page count, per-page pixels, union pixels and the aggregate pixel budget are bounded. use crate::{ImportOptions, ImportResult, IoError}; +use photocraft_color::{ColorMode, PixelFormat, SampleType}; use photocraft_doc::{Artboard, Document, Group, Layer, LayerContent}; -use photocraft_geom::Rect; +use photocraft_geom::{Rect, Size}; +use photocraft_raster::{Interrupt, Surface}; /// `%PDF-` magic. `.ai` files are PDFs too, but the dispatch keeps them out of this importer. pub fn is_pdf(bytes: &[u8]) -> bool { @@ -15,22 +17,24 @@ pub fn is_pdf(bytes: &[u8]) -> bool { /// Native PDF import is not available in the web build. #[cfg(target_arch = "wasm32")] -pub fn import(_name: &str, _bytes: &[u8], _opts: &ImportOptions) -> Result { +pub fn import(_name: &str, _bytes: &[u8], _opts: &ImportOptions, _ctl: &Interrupt) -> Result { Err(IoError::Unsupported("PDF import needs the desktop build".into())) } -/// Renders every PDF page at [`ImportOptions::pdf_dpi`] and opens it as one artboard per page. +/// Renders every PDF page and opens it as one artboard per page. #[cfg(not(target_arch = "wasm32"))] -pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions) -> Result { - use image::ImageEncoder; +pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) -> Result { use pdfium_render::prelude::*; - /// The most pages one import renders; more would make the union canvas enormous. + /// The most pages one import renders. const MAX_PAGES: usize = 16; /// Gap between the artboards, in document pixels. const GAP: u32 = 80; + /// Per-page and per-artboard-strip pixel budgets; a poster at 300 dpi is far below these. + const MAX_PAGE_PIXELS: f64 = 100_000_000.0; + const MAX_UNION_PIXELS: u64 = 200_000_000; - let dpi = if opts.pdf_dpi.is_finite() && opts.pdf_dpi > 0.0 { opts.pdf_dpi } else { 300.0 }; + let requested = if opts.pdf_dpi.is_finite() && opts.pdf_dpi > 0.0 { f64::from(opts.pdf_dpi) } else { 300.0 }; let pdfium = bind()?; let document = pdfium.load_pdf_from_byte_slice(bytes, None).map_err(|e| IoError::Unsupported(format!("PDF: {e}")))?; let total = document.pages().len().max(0) as usize; @@ -38,87 +42,101 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions) -> Result MAX_PAGE_PIXELS { - let scale = (MAX_PAGE_PIXELS / area).sqrt(); - target_width = (target_width * scale).max(1.0); - } - let config = PdfRenderConfig::new().set_target_width(target_width as i32); - let bitmap = page.render_with_config(&config).map_err(|e| IoError::Unsupported(format!("PDF render: {e}")))?; - let (width, height) = (bitmap.width().max(0) as u32, bitmap.height().max(0) as u32); - // Stop before the strip exceeds the union budget; the pages rendered so far stay. - let next_width = union_width + u64::from(width) + if rendered.is_empty() { 0 } else { u64::from(GAP) }; - let next_height = union_height.max(u64::from(height)); - if next_width.saturating_mul(next_height) > MAX_UNION_PIXELS { - break; - } - union_width = next_width; - union_height = next_height; - rendered.push((width, height, bitmap.as_rgba_bytes())); + sizes.push((w, h)); } - let count = rendered.len(); - if count == 0 { - return Err(IoError::Unsupported("PDF pages are too large to import; reduce the DPI".into())); + let dpi = effective_dpi(requested, &sizes, GAP, MAX_PAGE_PIXELS, MAX_UNION_PIXELS); + let doc_width = sizes.iter().map(|(w, _)| (w * dpi / 72.0).round() as u64).sum::() + u64::from(GAP) * (count as u64 - 1); + let doc_height = sizes.iter().map(|(_, h)| (h * dpi / 72.0).round() as u64).max().unwrap_or(1); + if doc_width == 0 || doc_height == 0 { + return Err(IoError::Unsupported("PDF pages have no area".into())); } - let doc_width = rendered.iter().map(|(w, _, _)| *w).sum::() + GAP * (count as u32 - 1); - let doc_height = rendered.iter().map(|(_, h, _)| *h).max().unwrap_or(1); - let mut doc: Option = None; + // The aggregate budget: the rendered pages and the document's raster tiles both hold pixels. + let page_pixels = sizes.iter().map(|(w, h)| (w * dpi / 72.0).round().max(1.0) * (h * dpi / 72.0).round().max(1.0)).sum::(); + let estimate = (page_pixels * 4.0 * 2.0) as u64; + if opts.flat_max_pixel_bytes > 0 && estimate > opts.flat_max_pixel_bytes { + return Err(IoError::Unsupported(format!( + "PDF import needs about {} MB of pixel memory; the limit is {} MB (lower the import DPI)", + estimate >> 20, + opts.flat_max_pixel_bytes >> 20 + ))); + } + let mut doc = Document::new(name, Size::new(doc_width as u32, doc_height as u32), ColorMode::Rgb, SampleType::U8); + doc.resolution_dpi = dpi as f32; let mut x = 0u32; - for (index, (width, height, rgba)) in rendered.into_iter().enumerate() { - // Reuse the well-tested flat importer: the page is composited into the union canvas at its - // artboard position, encoded as PNG, and decoded into a document-wide raster layer. - let mut canvas = image::RgbaImage::new(doc_width, doc_height); - let page = - image::RgbaImage::from_raw(width, height, rgba).ok_or_else(|| IoError::Unsupported("PDF: the rendered bitmap does not match its buffer".into()))?; - image::imageops::overlay(&mut canvas, &page, i64::from(x), 0); - let mut png = Vec::new(); - image::codecs::png::PngEncoder::new(&mut png) - .write_image(canvas.as_raw(), doc_width, doc_height, image::ExtendedColorType::Rgba8) - .map_err(|e| IoError::Unsupported(format!("PDF: encoding the rendered page: {e}")))?; - let mut result = crate::flat::import_flat(name, &png)?; - let layer = result.document.layers.pop().ok_or_else(|| IoError::Unsupported("PDF: the page decoded to an empty layer".into()))?; + for (index, (w_pt, h_pt)) in sizes.iter().enumerate() { + ctl.check().map_err(|_| IoError::Cancelled)?; + let target_width = (w_pt * dpi / 72.0).round().max(1.0) as i32; + let target_height = (h_pt * dpi / 72.0).round().max(1.0) as i32; + // A one-pixel-wide page would otherwise produce an arbitrarily tall bitmap before the + // union check runs; reject the final dimensions up front. + if f64::from(target_width) * f64::from(target_height) > MAX_PAGE_PIXELS { + return Err(IoError::Unsupported(format!( + "PDF page {} is too large at {dpi} dpi ({} x {} px); lower the import DPI", + index + 1, + target_width, + target_height + ))); + } + let page = document.pages().get(index as i32).map_err(|e| IoError::Unsupported(format!("PDF: {e}")))?; + let bitmap = + page.render_with_config(&PdfRenderConfig::new().set_target_width(target_width)).map_err(|e| IoError::Unsupported(format!("PDF render: {e}")))?; + let (width, height) = (bitmap.width().max(0) as u32, bitmap.height().max(0) as u32); + // The page's pixels go straight into the document-wide layer surface: no full-strip + // canvas and no PNG round-trip, so the peak is the page bitmap plus its tiles. + let mut surface = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, true)); + let rgba = bitmap.as_rgba_bytes(); + let mut data = Vec::with_capacity(rgba.len()); + for chunk in rgba.as_chunks::<4>().0 { + for &v in &chunk[..3] { + data.push(f32::from(v) / 255.0); + } + data.push(f32::from(chunk[3]) / 255.0); + } + surface.write_region(Rect::from_xywh(x as i32, 0, width, height), &data); + let layer = Layer::new(format!("Page {}", index + 1), LayerContent::Raster(surface)); let rect = Rect::new(x as i32, 0, (x + width) as i32, height as i32); let group = Group { children: vec![layer], expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None }; - let artboard = Layer::new(format!("Page {}", index + 1), LayerContent::Group(group)); - match &mut doc { - None => { - result.document.layers = vec![artboard]; - doc = Some(result.document); - } - Some(d) => d.layers.push(artboard), - } + doc.layers.push(Layer::new(format!("Page {}", index + 1), LayerContent::Group(group))); x += width + GAP; + ctl.progress((index + 1) as f32 / count as f32); } - let mut doc = doc.ok_or_else(|| IoError::Unsupported("PDF has no pages".into()))?; - doc.resolution_dpi = dpi; - doc.name = name.to_string(); let mut warnings = Vec::new(); if total > count { - let reason = if total > MAX_PAGES { "the page limit is 16" } else { "the rest would make the import canvas too large" }; + let reason = if count < total.min(MAX_PAGES) { "the rest would make the import canvas too large" } else { "the page limit is 16" }; warnings.push(format!("PDF has {total} pages; imported the first {count} ({reason})")); } Ok(ImportResult { warnings, document: doc, source_read_only: false, preview_only: false }) } +/// The highest DPI not above `requested` that keeps every page and the artboard strip within +/// their pixel budgets. Rendering at that DPI keeps each page's physical size unchanged. +#[cfg(not(target_arch = "wasm32"))] +fn effective_dpi(requested: f64, sizes: &[(f64, f64)], gap: u32, max_page: f64, max_union: u64) -> f64 { + let mut dpi = requested; + for (w, h) in sizes { + dpi = dpi.min(72.0 * (max_page / (w * h)).sqrt()); + } + let n = sizes.len() as f64; + let sum_w: f64 = sizes.iter().map(|(w, _)| w).sum(); + let max_h = sizes.iter().map(|(_, h)| h).fold(0.0_f64, |a, &h| a.max(h)); + // (sum_w * k + gaps) * (max_h * k) <= max_union, where k = dpi / 72: solve a k² + b k - c = 0. + let gaps = f64::from(gap) * (n - 1.0); + let a = sum_w * max_h; + let b = gaps * max_h; + let k = if a > 0.0 { (-b + (b * b + 4.0 * a * max_union as f64).sqrt()) / (2.0 * a) } else { f64::INFINITY }; + dpi.min(72.0 * k).max(1.0) +} + /// Loads the PDFium shared library from the executable's folder (`PDFIUM_DIR` overrides it). #[cfg(not(target_arch = "wasm32"))] fn bind() -> Result { @@ -128,9 +146,10 @@ fn bind() -> Result { .map(std::path::PathBuf::from) .unwrap_or_else(|| std::env::current_exe().ok().and_then(|exe| exe.parent().map(std::path::Path::to_path_buf)).unwrap_or_default()); let library = Pdfium::pdfium_platform_library_name_at_path(&dir); + let platform = Pdfium::pdfium_platform_library_name().to_string_lossy().into_owned(); let bindings = Pdfium::bind_to_library(&library).map_err(|e| { IoError::Unsupported(format!( - "PDF import: cannot load PDFium from {} ({e}); put pdfium.dll next to the executable or set PDFIUM_DIR", + "PDF import: cannot load PDFium from {} ({e}); put {platform} next to the executable or set PDFIUM_DIR", library.display() )) })?; From b1870f1950d5d4b1a9f69fbe4c04a48d9ae61c8f Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 15:15:57 +0100 Subject: [PATCH 06/30] PDF: second CodeRabbit round (render size, buffer estimate, label tree) --- crates/io/src/lib.rs | 9 --------- crates/io/src/pdf.rs | 7 ++++--- crates/io/src/pdf_import.rs | 12 +++++++++++- 3 files changed, 15 insertions(+), 13 deletions(-) diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 1f69b40ea4f..285e0d8602b 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -979,25 +979,16 @@ pub(crate) fn route(name: &str, bytes: &[u8]) -> Route { if is_psd_input(name, bytes) { return Route::NamedPsd; } -<<<<<<< HEAD Route::Flat } /// Dispatches format-specific importers and propagates a structured PSD damage /// flag alongside the ordinary best-effort import result. fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, opts: &ImportOptions, damaged: &mut bool) -> Result { - // PDF (PDFium, native only). `.ai` files are PDFs but keep their existing path; a recognized - // raster signature wins over a misleading `.pdf` suffix. - if pdf_import::is_pdf(bytes) - || (has_extension(name, "pdf") && !has_extension(name, "ai") && photocraft_codecs::detect(bytes).is_none()) - { - return pdf_import::import(name, bytes, opts); -======= // PDF (PDFium, native only). `.ai` files are PDFs but keep their existing path; a recognized // raster signature wins over a misleading `.pdf` suffix. if pdf_import::is_pdf(bytes) || (has_extension(name, "pdf") && !has_extension(name, "ai") && photocraft_codecs::detect(bytes).is_none()) { return pdf_import::import(name, bytes, opts, ctl); ->>>>>>> 806c53fd2 (PDF: address CodeRabbit review (cancellation, budgets, labels, export edges)) } match route(name, bytes) { Route::Pcraft => { diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index 4317784e501..35c0fdecf58 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -142,7 +142,8 @@ fn print_pdf_pages(pages: &[PrintPage], vectors: &[String], selection_font: &sel 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 labels_obj = selections_on.then_some(selection_base + 1); + let selection_objects = selection_font.objects(selection_base); + let labels_obj = selections_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::>().join(" "); obj(&mut out, format!("<< /Type /Pages /Kids [{kids}] /Count {n} >>").as_bytes()); @@ -213,8 +214,8 @@ fn print_pdf_pages(pages: &[PrintPage], vectors: &[String], selection_font: &sel body.extend_from_slice(b"\nendstream"); obj(&mut out, &body); } - for body in selection_font.objects(selection_base) { - obj(&mut out, &body); + for body in &selection_objects { + obj(&mut out, body); } if labels_obj.is_some() { let nums = pages diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index 58ec5fa70ba..ec58153ad4e 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -62,7 +62,8 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - } // The aggregate budget: the rendered pages and the document's raster tiles both hold pixels. let page_pixels = sizes.iter().map(|(w, h)| (w * dpi / 72.0).round().max(1.0) * (h * dpi / 72.0).round().max(1.0)).sum::(); - let estimate = (page_pixels * 4.0 * 2.0) as u64; + // The RGBA bitmap, the f32 conversion buffer (16 bytes/px) and the document tiles. + let estimate = (page_pixels * 24.0) as u64; if opts.flat_max_pixel_bytes > 0 && estimate > opts.flat_max_pixel_bytes { return Err(IoError::Unsupported(format!( "PDF import needs about {} MB of pixel memory; the limit is {} MB (lower the import DPI)", @@ -91,6 +92,15 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - let bitmap = page.render_with_config(&PdfRenderConfig::new().set_target_width(target_width)).map_err(|e| IoError::Unsupported(format!("PDF render: {e}")))?; let (width, height) = (bitmap.width().max(0) as u32, bitmap.height().max(0) as u32); + // The rounded target width can render a taller bitmap than the pre-check predicted. + if f64::from(width) * f64::from(height) > MAX_PAGE_PIXELS { + return Err(IoError::Unsupported(format!( + "PDF page {} rendered larger than the {MAX_PAGE_PIXELS} px budget ({} x {}); lower the import DPI", + index + 1, + width, + height + ))); + } // The page's pixels go straight into the document-wide layer surface: no full-strip // canvas and no PNG round-trip, so the peak is the page bitmap plus its tiles. let mut surface = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, true)); From ef7699ae9a6074ab51fb32b085289c87907cda01 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:46:00 +0100 Subject: [PATCH 07/30] PDF: render each artboard rect instead of a whole-document crop --- crates/io/src/pdf.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index 35c0fdecf58..a6aa68cd33a 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -331,8 +331,6 @@ pub fn export(doc: &Document, ctl: &photocraft_raster::Interrupt) -> std::result let icc = doc.icc_profile.as_ref().map(|p| p.to_vec()); let artboards = doc.artboards(); if !artboards.is_empty() { - // One flattened pass of the whole document; each artboard is a crop of it. - let surface = photocraft_compose::flatten_to_surface(doc, PixelFormat::new(fmt.mode, fmt.sample, true), None); let mut pages = Vec::with_capacity(artboards.len()); for (_, name, artboard) in &artboards { ctl.check().map_err(|_| IoError::Cancelled)?; @@ -341,6 +339,8 @@ pub fn export(doc: &Document, ctl: &photocraft_raster::Interrupt) -> std::result if aw == 0 || ah == 0 { continue; } + // 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 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) { From 06a6442076055b094824a0c4d1868eb37febcc96 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:57:00 +0100 Subject: [PATCH 08/30] PDF: SVG precedence, hidden artboards, export budget, writer cancellation --- crates/io/src/lib.rs | 5 +++++ crates/io/src/pdf.rs | 46 +++++++++++++++++++++++++++++++++++++------- 2 files changed, 44 insertions(+), 7 deletions(-) diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 285e0d8602b..ebceff36421 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -985,6 +985,11 @@ pub(crate) fn route(name: &str, bytes: &[u8]) -> Route { /// Dispatches format-specific importers and propagates a structured PSD damage /// flag alongside the ordinary best-effort import result. fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, opts: &ImportOptions, damaged: &mut bool) -> Result { + // SVG content wins over a misleading `.pdf` suffix, matching the preflight (which checks SVG + // before PDF). + if is_svg_input(name, bytes) { + return svg::import_svg_with_group_depth(name, bytes, opts.max_group_depth); + } // PDF (PDFium, native only). `.ai` files are PDFs but keep their existing path; a recognized // raster signature wins over a misleading `.pdf` suffix. if pdf_import::is_pdf(bytes) || (has_extension(name, "pdf") && !has_extension(name, "ai") && photocraft_codecs::detect(bytes).is_none()) { diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index a6aa68cd33a..7bf228320f4 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -121,12 +121,20 @@ fn marks_ops(m: Marks, (x, y, w, h): (f64, f64, f64, f64)) -> String { /// A one-page PDF. pub fn print_pdf(page: &PrintPage) -> Vec { - print_pdf_pages(std::slice::from_ref(page), &[String::new()], &selection::SelectionFont::default()) + print_pdf_pages(std::slice::from_ref(page), &[String::new()], &selection::SelectionFont::default(), &photocraft_raster::Interrupt::NONE).unwrap_or_default() } /// A PDF with one page per entry; `vectors[i]` (when present) is drawn over page `i`. -fn print_pdf_pages(pages: &[PrintPage], vectors: &[String], selection_font: &selection::SelectionFont) -> Vec { - let Some(first) = pages.first() else { return Vec::new() }; +fn print_pdf_pages( + pages: &[PrintPage], + vectors: &[String], + selection_font: &selection::SelectionFont, + ctl: &photocraft_raster::Interrupt, +) -> std::result::Result, IoError> { + if ctl.check().is_err() { + return Err(IoError::Cancelled); + } + let Some(first) = pages.first() else { return Ok(Vec::new()) }; let mut out: Vec = b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n".to_vec(); let mut offsets: Vec = Vec::new(); let mut obj = |out: &mut Vec, body: &[u8]| { @@ -232,7 +240,7 @@ fn print_pdf_pages(pages: &[PrintPage], vectors: &[String], selection_font: &sel out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); } out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", offsets.len() + 1).as_bytes()); - out + Ok(out) } /// The vector operators for the contiguous visible top prefix of `doc`, top to bottom, with the @@ -331,14 +339,38 @@ pub fn export(doc: &Document, ctl: &photocraft_raster::Interrupt) -> std::result let icc = doc.icc_profile.as_ref().map(|p| p.to_vec()); let artboards = doc.artboards(); 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; + if estimate > MAX_PDF_EXPORT_BYTES { + return Err(IoError::Unsupported(format!( + "PDF export would need about {} MB for {} artboards; export them in smaller batches", + estimate >> 20, + artboards.len() + ))); + } let mut pages = Vec::with_capacity(artboards.len()); - for (_, name, artboard) in &artboards { + for (id, name, artboard) in &artboards { ctl.check().map_err(|_| IoError::Cancelled)?; let rect = artboard.rect; let (aw, ah) = (rect.width(), rect.height()); if aw == 0 || ah == 0 { continue; } + // 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 + }; // 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 values = surface.read_region(rect); @@ -370,7 +402,7 @@ pub fn export(doc: &Document, ctl: &photocraft_raster::Interrupt) -> std::result warnings.push("free-form text metadata is not supported by PDF; it will be dropped".into()); } let vectors = vec![String::new(); pages.len()]; - return Ok(ExportResult { bytes: print_pdf_pages(&pages, &vectors, &selection::SelectionFont::default()), warnings }); + return Ok(ExportResult { bytes: print_pdf_pages(&pages, &vectors, &selection::SelectionFont::default(), ctl)?, warnings }); } let canvas = photocraft_geom::Rect::new(0, 0, w as i32, h as i32); // Simple topmost shapes and text layers can be drawn over the flattened backdrop without changing @@ -407,7 +439,7 @@ pub fn export(doc: &Document, ctl: &photocraft_raster::Interrupt) -> std::result vectors.push_str(ops); } vectors.push_str("Q\n"); - Ok(ExportResult { bytes: print_pdf_pages(&[page], &[vectors], &selection_font), warnings }) + Ok(ExportResult { bytes: print_pdf_pages(&[page], &[vectors], &selection_font, ctl)?, warnings }) } #[cfg(test)] From 244a6287ab8f504ad52089f2027385b78321f6c3 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:14:21 +0100 Subject: [PATCH 09/30] PDF: import options (page range, DPI, editable text/vector) and DLL packaging - ImportOptions gains pdf_pages (1-based inclusive), pdf_text and pdf_vectors; the importer maps PDF text objects to editable text layers and vector paths to shape layers through the effective DPI. - photocraft-cli convert gains --pdf-dpi and --pdf-pages. - Preferences gain pdf_dpi/pdf_pages, wired through jobs::import_options. - apps/photocraft/build.rs copies PDFIUM_DLL beside the exe; the MSI installs it. --- apps/photocraft-cli/src/args.rs | 6 ++ apps/photocraft-cli/src/document.rs | 19 +++- apps/photocraft/build.rs | 13 +++ crates/engine/src/jobs.rs | 2 + crates/engine/src/prefs.rs | 6 ++ crates/io/src/lib.rs | 9 ++ crates/io/src/pdf_import.rs | 145 ++++++++++++++++++++++++---- packaging/windows/photocraft.wxs | 2 + 8 files changed, 183 insertions(+), 19 deletions(-) diff --git a/apps/photocraft-cli/src/args.rs b/apps/photocraft-cli/src/args.rs index 3f29309ad5e..e8060854182 100644 --- a/apps/photocraft-cli/src/args.rs +++ b/apps/photocraft-cli/src/args.rs @@ -107,6 +107,12 @@ pub(crate) struct ConvertArgs { /// Explicitly approve high-memory PSD/PSB imports within the hard memory budget #[arg(long)] pub(crate) approve_high_memory: bool, + /// PDF import resolution in DPI (default 300) + #[arg(long)] + pub(crate) pdf_dpi: Option, + /// PDF pages to import, 1-based: "3" or "2-7" (default all) + #[arg(long)] + pub(crate) pdf_pages: Option, #[command(flatten)] pub(crate) gpu: GpuArgs, #[command(flatten)] diff --git a/apps/photocraft-cli/src/document.rs b/apps/photocraft-cli/src/document.rs index 95e8d4d8e2e..ab9e3cfd35e 100644 --- a/apps/photocraft-cli/src/document.rs +++ b/apps/photocraft-cli/src/document.rs @@ -26,11 +26,28 @@ fn refuse_overwriting_input(in_place: bool, input: &Path, output: &Path) -> Resu Ok(()) } +/// `N` or `N-M`, 1-based and inclusive, into a normalized `(first, last)`. +fn parse_pdf_pages(s: &str) -> Result<(u32, u32)> { + let (a, b) = s.split_once('-').unwrap_or((s, s)); + let bad = || CliError::Other(format!("invalid --pdf-pages {s:?}; use N or N-M")); + let a = a.trim().parse::().map_err(|_| bad())?; + let b = b.trim().parse::().map_err(|_| bad())?; + if a == 0 || b == 0 { + return Err(CliError::Other(format!("--pdf-pages is 1-based; {s:?} starts at 0"))); + } + Ok((a.min(b), a.max(b))) +} + pub(crate) fn convert(a: &ConvertArgs, _out: &mut dyn Write, err: &mut dyn Write) -> Result { let (input, output) = (&a.input, &a.output); let opts = ExportOptions::from(&a.export); refuse_overwriting_input(a.in_place, input, output)?; - let import_opts = photocraft_io::ImportOptions { psd_high_memory_approved: a.approve_high_memory, ..Default::default() }; + let import_opts = photocraft_io::ImportOptions { + psd_high_memory_approved: a.approve_high_memory, + pdf_dpi: a.pdf_dpi.unwrap_or(300.0), + pdf_pages: a.pdf_pages.as_deref().map(parse_pdf_pages).transpose()?, + ..Default::default() + }; let mut o = files::open_with_options(input, &import_opts)?; // Preferences › Raw Defaults › Resolution at its default, as `run` and `info` open a raw. photocraft_engine::file_cmds::raw_defaults(&photocraft_engine::Session::new(), &o.warnings, &mut o.document); diff --git a/apps/photocraft/build.rs b/apps/photocraft/build.rs index 48abc9f1a51..e750904018a 100644 --- a/apps/photocraft/build.rs +++ b/apps/photocraft/build.rs @@ -11,6 +11,19 @@ fn main() { if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") { return; } + // PDF import loads PDFium at runtime. When the build provides the shared library + // (`PDFIUM_DLL`, set by the release packaging step), copy it beside the executable so the + // installer's pdfium.dll and the running app agree. + println!("cargo:rerun-if-env-changed=PDFIUM_DLL"); + if let (Some(dll), Ok(out)) = (std::env::var_os("PDFIUM_DLL"), std::env::var("OUT_DIR")) { + let dll = std::path::PathBuf::from(dll); + if let Some(profile_dir) = std::path::Path::new(&out).ancestors().nth(3) { + let dest = profile_dir.join(dll.file_name().unwrap_or_default()); + if let Err(e) = std::fs::copy(&dll, &dest) { + println!("cargo:warning=could not copy PDFium to {}: {e}", dest.display()); + } + } + } // Printing to PDF (winprint's `PdfCreateRenderer`) imports Windows.Data.Pdf.dll, which // stripped Windows images (NTLite, some N/LTSC builds) lack. A load-time import stops the exe // from starting at all ("windows.data.pdf.dll was not found", #5884), so load it on first use; diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index ba82bd9028b..a68606eeba0 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -956,6 +956,8 @@ pub fn import_options(prefs: &crate::prefs::Preferences) -> photocraft_io::Impor photocraft_io::ImportOptions { max_group_depth: prefs.file_handling.rasterize_svg_groups_deeper_than as usize, demosaic: prefs.raw_defaults.demosaic.method(), + pdf_dpi: prefs.file_handling.pdf_dpi, + pdf_pages: prefs.file_handling.pdf_pages, ..Default::default() } } diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index ee61af791ca..1750310d267 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -493,6 +493,10 @@ pub struct FileHandling { pub recover_on_launch: bool, /// Open a file with no ICC profile as untagged even when its EXIF ColorSpace tag says sRGB. pub ignore_exif_profile_tag: bool, + /// PDF import resolution in DPI; the document keeps it so the page's print size is preserved. + pub pdf_dpi: f32, + /// PDF import page range, 1-based and inclusive; `None` imports every page. + pub pdf_pages: Option<(u32, u32)>, /// Most renderers write ACEScg EXRs without stating the colour space. With this on, an EXR /// that would otherwise open as linear sRGB opens as ACEScg (AP1, linear) instead. pub exr_aces_cg: bool, @@ -530,6 +534,8 @@ impl Default for FileHandling { autosave_minutes: 10, recover_on_launch: true, ignore_exif_profile_tag: false, + pdf_dpi: 300.0, + pdf_pages: None, exr_aces_cg: false, ask_before_saving_layered_tiff: true, maximize_psd_compatibility: Ask::Always, diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index ebceff36421..599f1104105 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -610,6 +610,12 @@ pub struct ImportOptions { /// Resolution (dots per inch) PDF pages are rendered at on import; the document keeps it so /// the page's print size is preserved. Defaults to 300. pub pdf_dpi: f32, + /// The 1-based, inclusive page range to import; `None` imports every page (up to the cap). + pub pdf_pages: Option<(u32, u32)>, + /// Import PDF text objects as editable text layers (default on). + pub pdf_text: bool, + /// Import PDF vector paths as editable shape layers (default on). + pub pdf_vectors: bool, /// Explicit one-shot authorization for imports that exceed the soft budget but fit within the hard budget. pub psd_high_memory_approved: bool, /// Optional estimate limit for high-memory approval. When set, approval only applies if @@ -625,6 +631,9 @@ impl Default for ImportOptions { psd_max_pixel_bytes: 0, flat_max_pixel_bytes: 0, pdf_dpi: 300.0, + pdf_pages: None, + pdf_text: true, + pdf_vectors: true, psd_high_memory_approved: false, psd_approved_estimate: None, } diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index ec58153ad4e..ab77a78b3ea 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -1,13 +1,16 @@ -//! PDF import: PDFium renders every page and each page becomes an artboard. +//! PDF import: PDFium renders the selected pages and each page becomes an artboard. //! //! The document resolution is chosen so the page's physical size is preserved even when the //! raster is capped: pixels ÷ resolution × 72 pt is the PDF page's size. Pages are laid out side //! by side; page count, per-page pixels, union pixels and the aggregate pixel budget are bounded. +//! +//! Text and vector page objects can be imported as editable layers (`ImportOptions::pdf_text` / +//! `pdf_vectors`); their page-space points are mapped to document pixels through the effective DPI. use crate::{ImportOptions, ImportResult, IoError}; use photocraft_color::{ColorMode, PixelFormat, SampleType}; -use photocraft_doc::{Artboard, Document, Group, Layer, LayerContent}; -use photocraft_geom::{Rect, Size}; +use photocraft_doc::{Artboard, Color, Document, Fill, Group, Knot, Layer, LayerContent, Path, PathOp, ShapeLayer, ShapeStroke, Subpath, TextLayer}; +use photocraft_geom::{Affine, Point, Rect, Size}; use photocraft_raster::{Interrupt, Surface}; /// `%PDF-` magic. `.ai` files are PDFs too, but the dispatch keeps them out of this importer. @@ -21,7 +24,7 @@ pub fn import(_name: &str, _bytes: &[u8], _opts: &ImportOptions, _ctl: &Interrup Err(IoError::Unsupported("PDF import needs the desktop build".into())) } -/// Renders every PDF page and opens it as one artboard per page. +/// Renders the selected PDF pages and opens each as one artboard. #[cfg(not(target_arch = "wasm32"))] pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) -> Result { use pdfium_render::prelude::*; @@ -38,19 +41,29 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - let pdfium = bind()?; let document = pdfium.load_pdf_from_byte_slice(bytes, None).map_err(|e| IoError::Unsupported(format!("PDF: {e}")))?; let total = document.pages().len().max(0) as usize; - let count = total.min(MAX_PAGES); - if count == 0 { - return Err(IoError::Unsupported("PDF has no pages".into())); + let (first, last) = match opts.pdf_pages { + Some((a, b)) => { + let a = (a.max(1) as usize).min(total.max(1)); + let b = (b.max(1) as usize).min(total.max(1)); + (a.min(b), a.max(b)) + } + None => (1, total), + }; + if total == 0 || first > total { + return Err(IoError::Unsupported("PDF has no pages in the requested range".into())); } + let page_count = last - first + 1; + let count = page_count.min(MAX_PAGES); // The page sizes in points first: the effective DPI must fit the budgets, and capping the // raster must not change the page's physical size. let mut sizes = Vec::with_capacity(count); for index in 0..count { ctl.check().map_err(|_| IoError::Cancelled)?; - let page = document.pages().get(index as i32).map_err(|e| IoError::Unsupported(format!("PDF: {e}")))?; + let page_index = first - 1 + index; + let page = document.pages().get(page_index as i32).map_err(|e| IoError::Unsupported(format!("PDF: {e}")))?; let (w, h) = (f64::from(page.width().value), f64::from(page.height().value)); if w <= 0.0 || h <= 0.0 { - return Err(IoError::Unsupported(format!("PDF page {} has no area", index + 1))); + return Err(IoError::Unsupported(format!("PDF page {} has no area", page_index + 1))); } sizes.push((w, h)); } @@ -76,6 +89,7 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - let mut x = 0u32; for (index, (w_pt, h_pt)) in sizes.iter().enumerate() { ctl.check().map_err(|_| IoError::Cancelled)?; + let page_index = first - 1 + index; let target_width = (w_pt * dpi / 72.0).round().max(1.0) as i32; let target_height = (h_pt * dpi / 72.0).round().max(1.0) as i32; // A one-pixel-wide page would otherwise produce an arbitrarily tall bitmap before the @@ -83,12 +97,12 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - if f64::from(target_width) * f64::from(target_height) > MAX_PAGE_PIXELS { return Err(IoError::Unsupported(format!( "PDF page {} is too large at {dpi} dpi ({} x {} px); lower the import DPI", - index + 1, + page_index + 1, target_width, target_height ))); } - let page = document.pages().get(index as i32).map_err(|e| IoError::Unsupported(format!("PDF: {e}")))?; + let page = document.pages().get(page_index as i32).map_err(|e| IoError::Unsupported(format!("PDF: {e}")))?; let bitmap = page.render_with_config(&PdfRenderConfig::new().set_target_width(target_width)).map_err(|e| IoError::Unsupported(format!("PDF render: {e}")))?; let (width, height) = (bitmap.width().max(0) as u32, bitmap.height().max(0) as u32); @@ -96,7 +110,7 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - if f64::from(width) * f64::from(height) > MAX_PAGE_PIXELS { return Err(IoError::Unsupported(format!( "PDF page {} rendered larger than the {MAX_PAGE_PIXELS} px budget ({} x {}); lower the import DPI", - index + 1, + page_index + 1, width, height ))); @@ -113,21 +127,116 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - data.push(f32::from(chunk[3]) / 255.0); } surface.write_region(Rect::from_xywh(x as i32, 0, width, height), &data); - let layer = Layer::new(format!("Page {}", index + 1), LayerContent::Raster(surface)); + let layer = Layer::new(format!("Page {}", page_index + 1), LayerContent::Raster(surface)); let rect = Rect::new(x as i32, 0, (x + width) as i32, height as i32); - let group = Group { children: vec![layer], expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None }; - doc.layers.push(Layer::new(format!("Page {}", index + 1), LayerContent::Group(group))); + let mut children = vec![layer]; + if opts.pdf_text || opts.pdf_vectors { + children.extend(object_layers(&page, *h_pt, dpi, x, opts)); + } + let group = Group { children, expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None }; + doc.layers.push(Layer::new(format!("Page {}", page_index + 1), LayerContent::Group(group))); x += width + GAP; ctl.progress((index + 1) as f32 / count as f32); } let mut warnings = Vec::new(); - if total > count { - let reason = if count < total.min(MAX_PAGES) { "the rest would make the import canvas too large" } else { "the page limit is 16" }; - warnings.push(format!("PDF has {total} pages; imported the first {count} ({reason})")); + if first > 1 || last < total || count < page_count { + let shown_last = first + count - 1; + let reason = if count < page_count { " (the page limit is 16)" } else { "" }; + warnings.push(format!("PDF has {total} pages; imported pages {first}-{shown_last}{reason}")); } Ok(ImportResult { warnings, document: doc, source_read_only: false, preview_only: false }) } +/// Editable text and shape layers for one rendered page, in document pixels. +#[cfg(not(target_arch = "wasm32"))] +fn object_layers(page: &pdfium_render::prelude::PdfPage, height_pt: f64, dpi: f64, x: u32, opts: &ImportOptions) -> Vec { + use pdfium_render::prelude::*; + + let to_x = |v: f32| f64::from(v) * dpi / 72.0; + let objects = page.objects(); + let mut layers = Vec::new(); + for object in objects.iter() { + match object { + PdfPageObject::Text(text) if opts.pdf_text => { + let content = text.text(); + if content.trim().is_empty() { + continue; + } + let Ok(bounds) = text.bounds() else { continue }; + let x_px = to_x(bounds.left().value).round() + f64::from(x); + let y_px = (height_pt - to_x(bounds.top().value)).round(); + // The text layer's size is in points; the transform is in document pixels. + let size_pt = f64::from(text.scaled_font_size().value).max(1.0); + layers.push(Layer::new( + "Text", + LayerContent::Text(TextLayer { + text: content, + font_family: text.font().family(), + size_pt: size_pt as f32, + color: Color::BLACK, + transform: Affine::translate(x_px, y_px), + ..Default::default() + }), + )); + } + PdfPageObject::Path(path) if opts.pdf_vectors => { + let mut subpaths: Vec = Vec::new(); + let mut knots: Vec = Vec::new(); + let mut closed = false; + let mut bezier: Vec<(f64, f64)> = Vec::new(); + for segment in path.segments().iter() { + let point = || (to_x(segment.x().value).round(), (height_pt - to_x(segment.y().value)).round()); + if segment.is_close() { + closed = true; + continue; + } + match segment.segment_type() { + PdfPathSegmentType::MoveTo => { + if !knots.is_empty() { + subpaths.push(Subpath { closed, knots: std::mem::take(&mut knots), op: PathOp::Combine }); + closed = false; + } + let (px, py) = point(); + knots.push(Knot::corner(px, py)); + } + PdfPathSegmentType::LineTo => { + let (px, py) = point(); + knots.push(Knot::corner(px, py)); + } + PdfPathSegmentType::BezierTo => { + // PDF draws a cubic Bézier as three consecutive BezierTo points: the + // two control points, then the end point. + bezier.push(point()); + if bezier.len() == 3 { + let ((c1x, c1y), (c2x, c2y), (ex, ey)) = (bezier[0], bezier[1], bezier[2]); + if let Some(prev) = knots.last_mut() { + prev.out_ctrl = Point::new(c1x, c1y); + } + knots.push(Knot::smooth(Point::new(ex, ey), Point::new(c2x, c2y), Point::new(ex, ey))); + bezier.clear(); + } + } + PdfPathSegmentType::Unknown => {} + } + } + if !knots.is_empty() { + subpaths.push(Subpath { closed, knots, op: PathOp::Combine }); + } + if subpaths.is_empty() { + continue; + } + let stroke = path.is_stroked().unwrap_or(false).then(|| ShapeStroke { paint: Fill::Solid(Color::BLACK), width: 1.0, ..Default::default() }); + layers.push(Layer::new( + "Path", + LayerContent::Shape(ShapeLayer { path: Path::new(subpaths), fill: Some(Fill::Solid(Color::BLACK)), stroke, ..Default::default() }), + )); + } + _ => {} + } + } + layers +} + /// The highest DPI not above `requested` that keeps every page and the artboard strip within /// their pixel budgets. Rendering at that DPI keeps each page's physical size unchanged. #[cfg(not(target_arch = "wasm32"))] diff --git a/packaging/windows/photocraft.wxs b/packaging/windows/photocraft.wxs index 6ff961fd994..020f7aa89cf 100644 --- a/packaging/windows/photocraft.wxs +++ b/packaging/windows/photocraft.wxs @@ -71,6 +71,8 @@ + + From fb66c11df6aafe5127b159e897348ab1c3fc73cf Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:35:02 +0100 Subject: [PATCH 10/30] PDF: CodeRabbit SVG signature fix, sampled text colour, Preferences page fields - A PDF named .svg now keeps the PDF importer; other signatures beat the .svg suffix fallback (regression test). - Text layers sample their fill colour from the rendered page and use the PDF font family/name. - File Handling preferences expose pdf_dpi, pdf_first_page and pdf_last_page; the page range maps to ImportOptions.pdf_pages. --- crates/io/src/lib.rs | 35 ++++++++++++++++++++++++++++++++--- crates/io/src/pdf_import.rs | 32 ++++++++++++++++++++++++++++---- 2 files changed, 60 insertions(+), 7 deletions(-) diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 599f1104105..54a4d1577e3 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -1028,10 +1028,28 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, o pub fn is_svg_input(name: &str, bytes: &[u8]) -> bool { // Keep the SVG extension as a fallback for malformed files so the SVG parser can return an // actionable SVG error. A recognized raster signature still wins over a misleading `.svg` - // suffix (for example, a WebP downloaded as Firefox_logo.svg). + // suffix (for example, a WebP downloaded as Firefox_logo.svg), and so does every other + // format's signature: a PDF named `.svg` must reach the PDF importer. svg::is_svg(bytes) - || (has_extension(name, "svg") && photocraft_codecs::detect(bytes).is_none()) - || (has_extension(name, "svgz") && bytes.starts_with(&[0x1f, 0x8b])) + || (has_extension(name, "svg") && photocraft_codecs::detect(bytes).is_none() && !has_format_signature(name, bytes)) + || (has_extension(name, "svgz") && bytes.starts_with(&[0x1f, 0x8b]) && !has_format_signature(name, bytes)) +} + +/// A non-raster format's signature or declared extension, checked before the `.svg` suffix +/// fallback so a misnamed file keeps its own importer. +fn has_format_signature(name: &str, bytes: &[u8]) -> bool { + is_psd(bytes) + || pdf_import::is_pdf(bytes) + || is_psd_input(name, bytes) + || raw::is_raw(bytes) + || affinity::is_affinity(bytes) + || ora::is_ora(bytes) + || kra::is_kra(bytes) + || xcf::is_xcf(bytes) + || has_extension(name, "pdn") + || bytes.starts_with(b"PDN3") + || photocraft_format::is_pcraft(bytes) + || has_extension(name, photocraft_format::EXTENSION) } fn extension(name_or_ext: &str) -> String { @@ -1599,4 +1617,15 @@ mod tests { assert_eq!(d.bounds().height(), 8, "{name}"); } } + + /// A PDF named `.svg` (a save-as mistake) must reach the PDF importer, not the SVG parser; + /// SVG content still wins over a `.pdf` suffix. + #[test] + fn a_pdf_named_svg_stays_a_pdf() { + let pdf = b"%PDF-1.4\n1 0 obj\n<< /Type /Catalog >>\nendobj\ntrailer\n<< /Root 1 0 R >>\n%%EOF\n"; + assert!(!is_svg_input("drawing.svg", pdf)); + assert!(!is_svg_input("drawing.svgz", pdf)); + assert!(is_svg_input("drawing.svg", b"")); + assert_eq!(crate::route("drawing.svg", pdf), crate::Route::Flat); + } } diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index ab77a78b3ea..e82bc20c841 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -131,7 +131,7 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - let rect = Rect::new(x as i32, 0, (x + width) as i32, height as i32); let mut children = vec![layer]; if opts.pdf_text || opts.pdf_vectors { - children.extend(object_layers(&page, *h_pt, dpi, x, opts)); + children.extend(object_layers(&page, opts, &PageFrame { height_pt: *h_pt, dpi, x, rgba: &bitmap.as_rgba_bytes(), width, height })); } let group = Group { children, expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None }; doc.layers.push(Layer::new(format!("Page {}", page_index + 1), LayerContent::Group(group))); @@ -147,11 +147,23 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - Ok(ImportResult { warnings, document: doc, source_read_only: false, preview_only: false }) } +/// One rendered page's frame: its point height, DPI, document x, and the RGBA pixels. +struct PageFrame<'a> { + height_pt: f64, + dpi: f64, + x: u32, + rgba: &'a [u8], + width: u32, + height: u32, +} + /// Editable text and shape layers for one rendered page, in document pixels. #[cfg(not(target_arch = "wasm32"))] -fn object_layers(page: &pdfium_render::prelude::PdfPage, height_pt: f64, dpi: f64, x: u32, opts: &ImportOptions) -> Vec { +fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, frame: &PageFrame) -> Vec { use pdfium_render::prelude::*; + let PageFrame { height_pt, dpi, x, rgba, width: page_width, height: page_height } = *frame; + let to_x = |v: f32| f64::from(v) * dpi / 72.0; let objects = page.objects(); let mut layers = Vec::new(); @@ -166,14 +178,26 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, height_pt: f64, dpi: f6 let x_px = to_x(bounds.left().value).round() + f64::from(x); let y_px = (height_pt - to_x(bounds.top().value)).round(); // The text layer's size is in points; the transform is in document pixels. + // The text object does not expose its fill colour; sample the rendered page at the + // text's centre so the editable layer starts with the right colour. + let cx = (to_x(bounds.left().value).round().max(0.0) as u32).min(page_width.saturating_sub(1)); + let cy = ((height_pt - to_x(bounds.top().value)).round().max(0.0) as u32).min(page_height.saturating_sub(1)); + let i = (cy as usize * page_width as usize + cx as usize) * 4; + let color = if i + 3 < rgba.len() && rgba[i + 3] > 0 { + Color::rgb(f32::from(rgba[i]) / 255.0, f32::from(rgba[i + 1]) / 255.0, f32::from(rgba[i + 2]) / 255.0) + } else { + Color::BLACK + }; let size_pt = f64::from(text.scaled_font_size().value).max(1.0); + let font = text.font(); + let family = if font.family().is_empty() { font.name() } else { font.family() }; layers.push(Layer::new( "Text", LayerContent::Text(TextLayer { text: content, - font_family: text.font().family(), + font_family: family, size_pt: size_pt as f32, - color: Color::BLACK, + color, transform: Affine::translate(x_px, y_px), ..Default::default() }), From 84644de10225b17c39bae4e5b595abf224854639 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:36:49 +0100 Subject: [PATCH 11/30] PDF: expose the page range as two Preferences numbers --- crates/engine/src/jobs.rs | 5 ++++- crates/engine/src/prefs.rs | 9 ++++++--- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index a68606eeba0..ddd9ac1f681 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -957,7 +957,10 @@ pub fn import_options(prefs: &crate::prefs::Preferences) -> photocraft_io::Impor max_group_depth: prefs.file_handling.rasterize_svg_groups_deeper_than as usize, demosaic: prefs.raw_defaults.demosaic.method(), pdf_dpi: prefs.file_handling.pdf_dpi, - pdf_pages: prefs.file_handling.pdf_pages, + pdf_pages: (prefs.file_handling.pdf_first_page > 0).then(|| { + let first = prefs.file_handling.pdf_first_page; + (first, prefs.file_handling.pdf_last_page.max(first)) + }), ..Default::default() } } diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 1750310d267..19c114fa29a 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -495,8 +495,10 @@ pub struct FileHandling { pub ignore_exif_profile_tag: bool, /// PDF import resolution in DPI; the document keeps it so the page's print size is preserved. pub pdf_dpi: f32, - /// PDF import page range, 1-based and inclusive; `None` imports every page. - pub pdf_pages: Option<(u32, u32)>, + /// The first PDF page to import (1-based; 0 imports from the first page). + pub pdf_first_page: u32, + /// The last PDF page to import (1-based; 0 imports to the last page). + pub pdf_last_page: u32, /// Most renderers write ACEScg EXRs without stating the colour space. With this on, an EXR /// that would otherwise open as linear sRGB opens as ACEScg (AP1, linear) instead. pub exr_aces_cg: bool, @@ -535,7 +537,8 @@ impl Default for FileHandling { recover_on_launch: true, ignore_exif_profile_tag: false, pdf_dpi: 300.0, - pdf_pages: None, + pdf_first_page: 0, + pdf_last_page: 0, exr_aces_cg: false, ask_before_saving_layered_tiff: true, maximize_psd_compatibility: Ask::Always, From adbe906eaf0fb2c5d669ca6a7330274c3e3e55c0 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 20:11:03 +0100 Subject: [PATCH 12/30] PDF: fix CI packaging and CodeRabbit findings - Stage pdfium.dll for the MSI fixtures (install-policy payload) and for the real package stage/portable zip; the package script downloads it before cargo. - Regenerate docs/scorecard.md for the new Preferences fields. - Text y positions convert the page height to pixels; invisible PDF text stays hidden. - Page ranges that start past the PDF are refused; zero first/last bounds are independent. --- crates/engine/src/jobs.rs | 11 +++++++---- crates/io/src/pdf_import.rs | 22 +++++++++++++++------- docs/scorecard.md | 4 ++-- packaging/windows/install-policy.json | 3 ++- packaging/windows/package.ps1 | 19 +++++++++++++++++++ 5 files changed, 45 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index ddd9ac1f681..13c36a82c1c 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -957,10 +957,13 @@ pub fn import_options(prefs: &crate::prefs::Preferences) -> photocraft_io::Impor max_group_depth: prefs.file_handling.rasterize_svg_groups_deeper_than as usize, demosaic: prefs.raw_defaults.demosaic.method(), pdf_dpi: prefs.file_handling.pdf_dpi, - pdf_pages: (prefs.file_handling.pdf_first_page > 0).then(|| { - let first = prefs.file_handling.pdf_first_page; - (first, prefs.file_handling.pdf_last_page.max(first)) - }), + pdf_pages: match (prefs.file_handling.pdf_first_page, prefs.file_handling.pdf_last_page) { + (0, 0) => None, + (first, last) => { + let first = first.max(1); + Some((first, if last == 0 { u32::MAX } else { last.max(first) })) + } + }, ..Default::default() } } diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index e82bc20c841..48b8d518586 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -43,9 +43,12 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - let total = document.pages().len().max(0) as usize; let (first, last) = match opts.pdf_pages { Some((a, b)) => { - let a = (a.max(1) as usize).min(total.max(1)); - let b = (b.max(1) as usize).min(total.max(1)); - (a.min(b), a.max(b)) + let a = a.max(1); + let b = if b == 0 { u32::MAX } else { b.max(a) }; + if u64::from(a) > total as u64 { + return Err(IoError::Unsupported(format!("PDF page range starts at {a}, but the PDF has {total} pages"))); + } + ((a as usize).min(total), (b as usize).min(total)) } None => (1, total), }; @@ -163,6 +166,7 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f use pdfium_render::prelude::*; let PageFrame { height_pt, dpi, x, rgba, width: page_width, height: page_height } = *frame; + let height_px = height_pt * dpi / 72.0; let to_x = |v: f32| f64::from(v) * dpi / 72.0; let objects = page.objects(); @@ -176,12 +180,12 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f } let Ok(bounds) = text.bounds() else { continue }; let x_px = to_x(bounds.left().value).round() + f64::from(x); - let y_px = (height_pt - to_x(bounds.top().value)).round(); + let y_px = (height_px - to_x(bounds.top().value)).round(); // The text layer's size is in points; the transform is in document pixels. // The text object does not expose its fill colour; sample the rendered page at the // text's centre so the editable layer starts with the right colour. let cx = (to_x(bounds.left().value).round().max(0.0) as u32).min(page_width.saturating_sub(1)); - let cy = ((height_pt - to_x(bounds.top().value)).round().max(0.0) as u32).min(page_height.saturating_sub(1)); + let cy = ((height_px - to_x(bounds.top().value)).round().max(0.0) as u32).min(page_height.saturating_sub(1)); let i = (cy as usize * page_width as usize + cx as usize) * 4; let color = if i + 3 < rgba.len() && rgba[i + 3] > 0 { Color::rgb(f32::from(rgba[i]) / 255.0, f32::from(rgba[i + 1]) / 255.0, f32::from(rgba[i + 2]) / 255.0) @@ -191,7 +195,7 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f let size_pt = f64::from(text.scaled_font_size().value).max(1.0); let font = text.font(); let family = if font.family().is_empty() { font.name() } else { font.family() }; - layers.push(Layer::new( + let mut layer = Layer::new( "Text", LayerContent::Text(TextLayer { text: content, @@ -201,7 +205,11 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f transform: Affine::translate(x_px, y_px), ..Default::default() }), - )); + ); + if !text.is_visible() { + layer.visible = false; + } + layers.push(layer); } PdfPageObject::Path(path) if opts.pdf_vectors => { let mut subpaths: Vec = Vec::new(); diff --git a/docs/scorecard.md b/docs/scorecard.md index a3ecd984cbd..ece2924bedf 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Performance](#performance) | 3 | 22 | 51 | 85 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 47 not run, 4 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 11 | 14 | 2 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 190/258, round trip ≥ 258/258 | | [Tools](#tools) | 36 | 9 | 0 | | -| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 10 of 192 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 10 of 195 (target 0) | | [Type](#type) | 5 | 5 | 0 | | | [Automation](#automation) | 5 | 3 | 3 | 660 of 660 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present | @@ -209,7 +209,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu ## Workspace and UI -**Settings that do nothing: 10 of 192** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 10 of 195** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. Unread: `general.color_picker`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `performance.legacy_compositing`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `type_.text_engine`, `enhanced_controls.scrubby_slider_acceleration`. diff --git a/packaging/windows/install-policy.json b/packaging/windows/install-policy.json index fcba1850ae2..8d01fab4ac6 100644 --- a/packaging/windows/install-policy.json +++ b/packaging/windows/install-policy.json @@ -15,7 +15,8 @@ ], "payloads": [ "photocraft-cli.exe", - "photocraft.exe" + "photocraft.exe", + "pdfium.dll" ], "registry": [ [ diff --git a/packaging/windows/package.ps1 b/packaging/windows/package.ps1 index d984e3930a6..1f072fedb51 100644 --- a/packaging/windows/package.ps1 +++ b/packaging/windows/package.ps1 @@ -55,6 +55,23 @@ New-Item -ItemType Directory -Force -Path $Dist | Out-Null if (-not $env:PHOTOCRAFT_BUILD_SHA) { $env:PHOTOCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) } if (-not $env:PHOTOCRAFT_BUILD_DATE) { $env:PHOTOCRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') } +# PDF import loads PDFium at runtime. Stage the Windows build's DLL before cargo, so the app's +# build script copies it beside the exe and both the MSI and the portable ZIP ship it. +$PdfiumDir = Join-Path $Root "target\pdfium\$Arch" +$PdfiumDll = Join-Path $PdfiumDir 'pdfium.dll' +if (-not (Test-Path -LiteralPath $PdfiumDll)) { + $tgz = Join-Path $env:TEMP "pdfium-win-$Arch.tgz" + Invoke-Native "download PDFium ($Arch)" { + Invoke-WebRequest -Uri "https://github.com/bblanchon/pdfium-binaries/releases/latest/download/pdfium-win-$Arch.tgz" -OutFile $tgz + New-Item -ItemType Directory -Force -Path $PdfiumDir | Out-Null + tar -xzf $tgz -C $PdfiumDir + $extracted = Join-Path $PdfiumDir 'bin\pdfium.dll' + if (-not (Test-Path -LiteralPath $extracted)) { throw 'PDFium archive had no bin/pdfium.dll' } + Move-Item -Force $extracted $PdfiumDll + } +} +$env:PDFIUM_DLL = $PdfiumDll + Write-Output "PhotoCraft $Version for Windows $Arch ($Target)" if (-not $SkipBuild) { @@ -89,6 +106,7 @@ $Stage = Join-Path $TargetDir "windows-package\$Arch" Remove-Item -Recurse -Force $Stage -ErrorAction SilentlyContinue New-Item -ItemType Directory -Force -Path $Stage | Out-Null Copy-Item (Join-Path $Bin 'photocraft.exe'), (Join-Path $Bin 'photocraft-cli.exe') $Stage +Copy-Item -LiteralPath $PdfiumDll -Destination $Stage & (Join-Path $PSScriptRoot 'sign.ps1') (Join-Path $Stage 'photocraft.exe') (Join-Path $Stage 'photocraft-cli.exe') @@ -171,6 +189,7 @@ $Portable = Join-Path $TargetDir "windows-package\photocraft-$Version-windows-$A Remove-Item -Recurse -Force $Portable -ErrorAction SilentlyContinue New-Item -ItemType Directory -Force -Path $Portable | Out-Null Copy-Item (Join-Path $Stage '*.exe') $Portable +Copy-Item -LiteralPath $PdfiumDll -Destination $Portable foreach ($f in 'README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') { $p = Join-Path $Root $f if (Test-Path $p) { Copy-Item $p $Portable } From 36e7c50178460e2b45a9245c7d0079c9f3169e54 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 20:34:01 +0100 Subject: [PATCH 13/30] PDF: transform imported paths by their object matrix - Apply PdfPageObject::matrix() to path segments: PDFium returns raw object-space points, so scaled or rotated paths landed in the wrong place. - Flip path y with the page height in pixels, not points; paths were off-canvas at any DPI other than 72. - Take fill and stroke presence from the path's draw mode: stroke-only paths no longer get a black fill, and paths that are neither filled nor stroked are skipped. - Estimate import pixel memory as retained tiles (4 B/px over all pages) plus the converting page's peak (24 B/px), defaulting to a 2 GiB budget when the caller sets none. Reuse the RGBA copy and reserve the f32 buffer fallibly. --- crates/io/src/pdf_import.rs | 49 ++++++++++++++++++++++++++++--------- 1 file changed, 37 insertions(+), 12 deletions(-) diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index 48b8d518586..34db0767d81 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -36,6 +36,9 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - /// Per-page and per-artboard-strip pixel budgets; a poster at 300 dpi is far below these. const MAX_PAGE_PIXELS: f64 = 100_000_000.0; const MAX_UNION_PIXELS: u64 = 200_000_000; + /// The default pixel-memory budget when the caller sets none: a zero + /// [`ImportOptions::flat_max_pixel_bytes`] still bounds the import. + const DEFAULT_MAX_PIXEL_BYTES: u64 = 2 << 30; let requested = if opts.pdf_dpi.is_finite() && opts.pdf_dpi > 0.0 { f64::from(opts.pdf_dpi) } else { 300.0 }; let pdfium = bind()?; @@ -76,15 +79,20 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - if doc_width == 0 || doc_height == 0 { return Err(IoError::Unsupported("PDF pages have no area".into())); } - // The aggregate budget: the rendered pages and the document's raster tiles both hold pixels. - let page_pixels = sizes.iter().map(|(w, h)| (w * dpi / 72.0).round().max(1.0) * (h * dpi / 72.0).round().max(1.0)).sum::(); - // The RGBA bitmap, the f32 conversion buffer (16 bytes/px) and the document tiles. - let estimate = (page_pixels * 24.0) as u64; - if opts.flat_max_pixel_bytes > 0 && estimate > opts.flat_max_pixel_bytes { + // The aggregate budget: the document keeps every page's raster tiles, while one page at a + // time is converted through the PDFium bitmap, its RGBA copy and the f32 buffer. + let page_px = |w: f64, h: f64| (w * dpi / 72.0).round().max(1.0) * (h * dpi / 72.0).round().max(1.0); + let page_pixels = sizes.iter().map(|&(w, h)| page_px(w, h)).sum::(); + let max_page_pixels = sizes.iter().map(|&(w, h)| page_px(w, h)).fold(0.0_f64, f64::max); + // 4 bytes/px of retained RGBA tiles for every page, plus 24 bytes/px (bitmap, RGBA copy, + // f32 conversion buffer) for the page being converted. + let estimate = (page_pixels * 4.0 + max_page_pixels * 24.0) as u64; + let budget = if opts.flat_max_pixel_bytes > 0 { opts.flat_max_pixel_bytes } else { DEFAULT_MAX_PIXEL_BYTES }; + if estimate > budget { return Err(IoError::Unsupported(format!( "PDF import needs about {} MB of pixel memory; the limit is {} MB (lower the import DPI)", estimate >> 20, - opts.flat_max_pixel_bytes >> 20 + budget >> 20 ))); } let mut doc = Document::new(name, Size::new(doc_width as u32, doc_height as u32), ColorMode::Rgb, SampleType::U8); @@ -122,7 +130,10 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - // canvas and no PNG round-trip, so the peak is the page bitmap plus its tiles. let mut surface = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, true)); let rgba = bitmap.as_rgba_bytes(); - let mut data = Vec::with_capacity(rgba.len()); + let mut data = Vec::new(); + if data.try_reserve_exact(rgba.len()).is_err() { + return Err(IoError::Unsupported(format!("PDF page {} needs more memory than is available", page_index + 1))); + } for chunk in rgba.as_chunks::<4>().0 { for &v in &chunk[..3] { data.push(f32::from(v) / 255.0); @@ -134,7 +145,7 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - let rect = Rect::new(x as i32, 0, (x + width) as i32, height as i32); let mut children = vec![layer]; if opts.pdf_text || opts.pdf_vectors { - children.extend(object_layers(&page, opts, &PageFrame { height_pt: *h_pt, dpi, x, rgba: &bitmap.as_rgba_bytes(), width, height })); + children.extend(object_layers(&page, opts, &PageFrame { height_pt: *h_pt, dpi, x, rgba: &rgba, width, height })); } let group = Group { children, expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None }; doc.layers.push(Layer::new(format!("Page {}", page_index + 1), LayerContent::Group(group))); @@ -212,12 +223,21 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f layers.push(layer); } PdfPageObject::Path(path) if opts.pdf_vectors => { + // PDFium reports the segments in object space; the object's matrix places them on + // the page. Without it, scaled or rotated paths land in the wrong place. + let matrix = path.matrix().unwrap_or(PdfMatrix::IDENTITY); + // The fill and stroke modes are exposed; the colours and dash pattern are not. + let filled = !matches!(path.fill_mode(), Ok(PdfPathFillMode::None)); + let stroked = path.is_stroked().unwrap_or(false); + if !filled && !stroked { + continue; + } let mut subpaths: Vec = Vec::new(); let mut knots: Vec = Vec::new(); let mut closed = false; let mut bezier: Vec<(f64, f64)> = Vec::new(); - for segment in path.segments().iter() { - let point = || (to_x(segment.x().value).round(), (height_pt - to_x(segment.y().value)).round()); + for segment in path.segments().transform(matrix).iter() { + let point = || (to_x(segment.x().value).round(), (height_px - to_x(segment.y().value)).round()); if segment.is_close() { closed = true; continue; @@ -257,10 +277,15 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f if subpaths.is_empty() { continue; } - let stroke = path.is_stroked().unwrap_or(false).then(|| ShapeStroke { paint: Fill::Solid(Color::BLACK), width: 1.0, ..Default::default() }); + let stroke = stroked.then(|| ShapeStroke { paint: Fill::Solid(Color::BLACK), width: 1.0, ..Default::default() }); layers.push(Layer::new( "Path", - LayerContent::Shape(ShapeLayer { path: Path::new(subpaths), fill: Some(Fill::Solid(Color::BLACK)), stroke, ..Default::default() }), + LayerContent::Shape(ShapeLayer { + path: Path::new(subpaths), + fill: filled.then_some(Fill::Solid(Color::BLACK)), + stroke, + ..Default::default() + }), )); } _ => {} From 192b075bfacb1b805c0fdcb83e0534eb0c033299 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 21:29:06 +0100 Subject: [PATCH 14/30] PDF: map editable objects through one page-to-document transform - Paths on page 2+ were placed without the page's document X offset; text and paths now share PageFrame::to_doc, which applies the DPI scale, the Y flip and the page offset in one place. - Flip Y in pixels and round once, so text placement, text colour sampling and path points all stay in the same coordinate system. - Add unit tests for 72/300 dpi, the page-2 offset and the sampled colour; they need no PDFium. --- crates/io/src/pdf_import.rs | 71 ++++++++++++++++++++++++++++--------- 1 file changed, 55 insertions(+), 16 deletions(-) diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index 34db0767d81..05973548269 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -171,15 +171,32 @@ struct PageFrame<'a> { height: u32, } +impl PageFrame<'_> { + /// Maps a point in PDF page space (points, origin bottom-left) to document pixels: the Y flip + /// and the page's X offset both belong to this mapping. + fn to_doc(&self, x_pt: f32, y_pt: f32) -> (f64, f64) { + let x_px = f64::from(x_pt) * self.dpi / 72.0 + f64::from(self.x); + let y_px = (self.height_pt - f64::from(y_pt)) * self.dpi / 72.0; + (x_px.round(), y_px.round()) + } + + /// The rendered page's colour at local pixel (`x`, `y`), or black outside it. + fn color_at(&self, x: u32, y: u32) -> Color { + let i = (y as usize * self.width as usize + x as usize) * 4; + if i + 3 < self.rgba.len() && self.rgba[i + 3] > 0 { + Color::rgb(f32::from(self.rgba[i]) / 255.0, f32::from(self.rgba[i + 1]) / 255.0, f32::from(self.rgba[i + 2]) / 255.0) + } else { + Color::BLACK + } + } +} + /// Editable text and shape layers for one rendered page, in document pixels. #[cfg(not(target_arch = "wasm32"))] fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, frame: &PageFrame) -> Vec { use pdfium_render::prelude::*; - let PageFrame { height_pt, dpi, x, rgba, width: page_width, height: page_height } = *frame; - let height_px = height_pt * dpi / 72.0; - - let to_x = |v: f32| f64::from(v) * dpi / 72.0; + let PageFrame { x, width: page_width, height: page_height, .. } = *frame; let objects = page.objects(); let mut layers = Vec::new(); for object in objects.iter() { @@ -190,19 +207,13 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f continue; } let Ok(bounds) = text.bounds() else { continue }; - let x_px = to_x(bounds.left().value).round() + f64::from(x); - let y_px = (height_px - to_x(bounds.top().value)).round(); + let (x_px, y_px) = frame.to_doc(bounds.left().value, bounds.top().value); // The text layer's size is in points; the transform is in document pixels. // The text object does not expose its fill colour; sample the rendered page at the - // text's centre so the editable layer starts with the right colour. - let cx = (to_x(bounds.left().value).round().max(0.0) as u32).min(page_width.saturating_sub(1)); - let cy = ((height_px - to_x(bounds.top().value)).round().max(0.0) as u32).min(page_height.saturating_sub(1)); - let i = (cy as usize * page_width as usize + cx as usize) * 4; - let color = if i + 3 < rgba.len() && rgba[i + 3] > 0 { - Color::rgb(f32::from(rgba[i]) / 255.0, f32::from(rgba[i + 1]) / 255.0, f32::from(rgba[i + 2]) / 255.0) - } else { - Color::BLACK - }; + // text's top-left corner so the editable layer starts with the right colour. + let cx = ((x_px - f64::from(x)).max(0.0) as u32).min(page_width.saturating_sub(1)); + let cy = (y_px.max(0.0) as u32).min(page_height.saturating_sub(1)); + let color = frame.color_at(cx, cy); let size_pt = f64::from(text.scaled_font_size().value).max(1.0); let font = text.font(); let family = if font.family().is_empty() { font.name() } else { font.family() }; @@ -237,7 +248,7 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f let mut closed = false; let mut bezier: Vec<(f64, f64)> = Vec::new(); for segment in path.segments().transform(matrix).iter() { - let point = || (to_x(segment.x().value).round(), (height_px - to_x(segment.y().value)).round()); + let point = || frame.to_doc(segment.x().value, segment.y().value); if segment.is_close() { closed = true; continue; @@ -331,3 +342,31 @@ fn bind() -> Result { })?; Ok(Pdfium::new(bindings)) } + +#[cfg(test)] +mod tests { + use super::PageFrame; + + fn frame(dpi: f64, x: u32) -> PageFrame<'static> { + PageFrame { height_pt: 842.0, dpi, x, rgba: &[], width: 595, height: 842 } + } + + #[test] + fn page_points_map_to_document_pixels() { + assert_eq!(frame(72.0, 0).to_doc(60.0, 420.0), (60.0, 422.0)); + // The same point at four times the resolution. + assert_eq!(frame(300.0, 0).to_doc(60.0, 420.0), (250.0, 1758.0)); + // Page 2 starts after page 1's width: the document X offset is part of the mapping. + assert_eq!(frame(300.0, 2480).to_doc(60.0, 420.0), (2730.0, 1758.0)); + } + + #[test] + fn samples_the_rendered_page() { + // Two pixels: white then black. + let rgba = [255u8, 255, 255, 255, 0, 0, 0, 255]; + let page = PageFrame { height_pt: 842.0, dpi: 72.0, x: 0, rgba: &rgba, width: 2, height: 1 }; + assert_eq!(page.color_at(0, 0), photocraft_doc::Color::rgb(1.0, 1.0, 1.0)); + assert_eq!(page.color_at(1, 0), photocraft_doc::Color::BLACK); + assert_eq!(page.color_at(2, 0), photocraft_doc::Color::BLACK); + } +} From fabfbb5d5a2f7a727d1658244a736874752ca19b Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 22:15:50 +0100 Subject: [PATCH 15/30] PDF: fix segment closing, admission, glyph colour and PDFium reuse - Process a closing segment's own geometry before marking the subpath closed, so a closing Bezier endpoint cannot leak control points into the next curve. - Estimate retained memory from tile-aligned page bounds (including the page's X offset) instead of raw pixels: a 1 x 10,000 px page admits its 40 tiles, not 10,000 pixels. - Sample text colour from the glyph ink (the pixel farthest from the box's dominant colour) instead of the bounds' top-left corner, which was usually background or antialiasing. - Cache the PDFium bind: pdfium-render binds once per process, so a second PDF import in one session failed with PdfiumLibraryBindingsAlreadyInitialized. - Add a PDFium-backed two-page end-to-end test with a transformed path on page 2 and non-origin red/green text at 72 and 300 dpi; it prints an explicit SKIPPED line when PDFium is unavailable. - package.ps1: pin pdfium-binaries chromium/8138, verify the archive and any cached DLL against SHA-256, drop a stale bin/pdfium.dll before extraction and check tar's exit status. --- crates/io/src/pdf_import.rs | 137 +++++++++++++++++++++++------ crates/io/tests/it/main.rs | 1 + crates/io/tests/it/pdf_import.rs | 143 +++++++++++++++++++++++++++++++ packaging/windows/package.ps1 | 40 ++++++++- 4 files changed, 291 insertions(+), 30 deletions(-) create mode 100644 crates/io/tests/it/pdf_import.rs diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index 05973548269..679198ff8b3 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -82,11 +82,21 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - // The aggregate budget: the document keeps every page's raster tiles, while one page at a // time is converted through the PDFium bitmap, its RGBA copy and the f32 buffer. let page_px = |w: f64, h: f64| (w * dpi / 72.0).round().max(1.0) * (h * dpi / 72.0).round().max(1.0); - let page_pixels = sizes.iter().map(|&(w, h)| page_px(w, h)).sum::(); let max_page_pixels = sizes.iter().map(|&(w, h)| page_px(w, h)).fold(0.0_f64, f64::max); - // 4 bytes/px of retained RGBA tiles for every page, plus 24 bytes/px (bitmap, RGBA copy, - // f32 conversion buffer) for the page being converted. - let estimate = (page_pixels * 4.0 + max_page_pixels * 24.0) as u64; + // Retained backing: a page occupies whole 256 px tiles, including the ones its document X + // offset steps into. A 1 x 10,000 px page is 40 tiles (10 MiB), not 10,000 pixels. + const TILE: u64 = 256; + let mut retained: u64 = 0; + let mut page_x: u64 = 0; + for &(w, h) in &sizes { + let px = (w * dpi / 72.0).round().max(1.0) as u64; + let py = (h * dpi / 72.0).round().max(1.0) as u64; + let tiles_x = (page_x + px).div_ceil(TILE) - page_x / TILE; + retained = retained.saturating_add(tiles_x.saturating_mul(py.div_ceil(TILE)).saturating_mul(TILE * TILE * 4)); + page_x += px + u64::from(GAP); + } + // Plus 24 bytes/px (bitmap, RGBA copy, f32 conversion buffer) for the page being converted. + let estimate = retained.saturating_add((max_page_pixels * 24.0) as u64); let budget = if opts.flat_max_pixel_bytes > 0 { opts.flat_max_pixel_bytes } else { DEFAULT_MAX_PIXEL_BYTES }; if estimate > budget { return Err(IoError::Unsupported(format!( @@ -189,6 +199,56 @@ impl PageFrame<'_> { Color::BLACK } } + + /// The ink colour of the text in `bounds` (page points). + /// + /// The box holds both glyphs and the page behind them, so sampling one corner usually finds + /// background or an antialiased edge. Take the pixel farthest from the box's most common + /// colour instead: for dark text on a light page that is a glyph core, and for light text on a + /// dark page it is the glyph rather than the background. + fn text_color(&self, left: f32, top: f32, right: f32, bottom: f32) -> Color { + let x0 = (f64::from(left) * self.dpi / 72.0).floor().max(0.0) as u32; + let x1 = (f64::from(right) * self.dpi / 72.0).ceil().clamp(0.0, f64::from(self.width)) as u32; + // PDF's Y grows up; the rendered page's Y grows down. + let y0 = ((self.height_pt - f64::from(top)) * self.dpi / 72.0).floor().max(0.0) as u32; + let y1 = ((self.height_pt - f64::from(bottom)) * self.dpi / 72.0).ceil().clamp(0.0, f64::from(self.height)) as u32; + if x1 <= x0 || y1 <= y0 { + return Color::BLACK; + } + // At most ~4096 samples, so a page-sized text box stays cheap. + let step = ((f64::from(x1 - x0) * f64::from(y1 - y0) / 4096.0).sqrt().ceil() as u32).max(1); + let mut samples: Vec<[f32; 3]> = Vec::new(); + let mut buckets: std::collections::HashMap = std::collections::HashMap::new(); + let mut y = y0; + while y < y1 { + let mut x = x0; + while x < x1 { + let c = self.color_at(x, y); + let rgb = [c.c[0], c.c[1], c.c[2]]; + let key = (rgb[0] * 31.0) as u32 * 1024 + (rgb[1] * 31.0) as u32 * 32 + (rgb[2] * 31.0) as u32; + let entry = buckets.entry(key).or_insert((0, [0.0; 3])); + entry.0 += 1; + for (sum, v) in entry.1.iter_mut().zip(rgb) { + *sum += v; + } + samples.push(rgb); + x += step; + } + y += step; + } + let Some((_, (count, sum))) = buckets.iter().max_by_key(|(_, (count, _))| *count) else { return Color::BLACK }; + let mode = [sum[0] / *count as f32, sum[1] / *count as f32, sum[2] / *count as f32]; + let mut best = mode; + let mut best_distance = -1.0f32; + for rgb in samples { + let distance = (rgb[0] - mode[0]).powi(2) + (rgb[1] - mode[1]).powi(2) + (rgb[2] - mode[2]).powi(2); + if distance > best_distance { + best_distance = distance; + best = rgb; + } + } + Color::rgb(best[0], best[1], best[2]) + } } /// Editable text and shape layers for one rendered page, in document pixels. @@ -196,7 +256,6 @@ impl PageFrame<'_> { fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, frame: &PageFrame) -> Vec { use pdfium_render::prelude::*; - let PageFrame { x, width: page_width, height: page_height, .. } = *frame; let objects = page.objects(); let mut layers = Vec::new(); for object in objects.iter() { @@ -208,12 +267,9 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f } let Ok(bounds) = text.bounds() else { continue }; let (x_px, y_px) = frame.to_doc(bounds.left().value, bounds.top().value); - // The text layer's size is in points; the transform is in document pixels. - // The text object does not expose its fill colour; sample the rendered page at the - // text's top-left corner so the editable layer starts with the right colour. - let cx = ((x_px - f64::from(x)).max(0.0) as u32).min(page_width.saturating_sub(1)); - let cy = (y_px.max(0.0) as u32).min(page_height.saturating_sub(1)); - let color = frame.color_at(cx, cy); + // The text layer's size is in points; the transform is in document pixels. The + // text object does not expose its fill colour; sample the glyph ink from the page. + let color = frame.text_color(bounds.left().value, bounds.top().value, bounds.right().value, bounds.bottom().value); let size_pt = f64::from(text.scaled_font_size().value).max(1.0); let font = text.font(); let family = if font.family().is_empty() { font.name() } else { font.family() }; @@ -249,10 +305,6 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f let mut bezier: Vec<(f64, f64)> = Vec::new(); for segment in path.segments().transform(matrix).iter() { let point = || frame.to_doc(segment.x().value, segment.y().value); - if segment.is_close() { - closed = true; - continue; - } match segment.segment_type() { PdfPathSegmentType::MoveTo => { if !knots.is_empty() { @@ -281,6 +333,11 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f } PdfPathSegmentType::Unknown => {} } + // A closing segment can also be the endpoint that closes a Bézier; process it + // above before marking the subpath closed so its control points are consumed. + if segment.is_close() { + closed = true; + } } if !knots.is_empty() { subpaths.push(Subpath { closed, knots, op: PathOp::Combine }); @@ -325,22 +382,35 @@ fn effective_dpi(requested: f64, sizes: &[(f64, f64)], gap: u32, max_page: f64, } /// Loads the PDFium shared library from the executable's folder (`PDFIUM_DIR` overrides it). +/// +/// pdfium-render keeps the bindings in a process-wide static: the first import initializes them +/// and later `bind_to_library` calls fail with `PdfiumLibraryBindingsAlreadyInitialized`. Remember +/// the outcome and reuse the initialized bindings, so opening a second PDF in one session works. #[cfg(not(target_arch = "wasm32"))] fn bind() -> Result { use pdfium_render::prelude::Pdfium; - let dir = std::env::var_os("PDFIUM_DIR") - .map(std::path::PathBuf::from) - .unwrap_or_else(|| std::env::current_exe().ok().and_then(|exe| exe.parent().map(std::path::Path::to_path_buf)).unwrap_or_default()); - let library = Pdfium::pdfium_platform_library_name_at_path(&dir); - let platform = Pdfium::pdfium_platform_library_name().to_string_lossy().into_owned(); - let bindings = Pdfium::bind_to_library(&library).map_err(|e| { - IoError::Unsupported(format!( - "PDF import: cannot load PDFium from {} ({e}); put {platform} next to the executable or set PDFIUM_DIR", - library.display() - )) - })?; - Ok(Pdfium::new(bindings)) + static INIT: std::sync::OnceLock> = std::sync::OnceLock::new(); + let init = INIT.get_or_init(|| { + let dir = std::env::var_os("PDFIUM_DIR") + .map(std::path::PathBuf::from) + .unwrap_or_else(|| std::env::current_exe().ok().and_then(|exe| exe.parent().map(std::path::Path::to_path_buf)).unwrap_or_default()); + let library = Pdfium::pdfium_platform_library_name_at_path(&dir); + let platform = Pdfium::pdfium_platform_library_name().to_string_lossy().into_owned(); + match Pdfium::bind_to_library(&library) { + Ok(bindings) => { + // Initializes the library inside pdfium-render's process-wide bindings. + drop(Pdfium::new(bindings)); + Ok(()) + } + Err(e) => Err(format!("PDF import: cannot load PDFium from {} ({e}); put {platform} next to the executable or set PDFIUM_DIR", library.display())), + } + }); + match init { + // The bindings are already initialized; `default()` re-uses them. + Ok(()) => Ok(Pdfium::default()), + Err(message) => Err(IoError::Unsupported(message.clone())), + } } #[cfg(test)] @@ -369,4 +439,17 @@ mod tests { assert_eq!(page.color_at(1, 0), photocraft_doc::Color::BLACK); assert_eq!(page.color_at(2, 0), photocraft_doc::Color::BLACK); } + + #[test] + fn text_colour_samples_the_glyph_ink() { + // An 8 x 4 white page with one black glyph pixel at (2, 1). + let mut rgba = vec![255u8; 8 * 4 * 4]; + let glyph = (8 + 2) * 4; + rgba[glyph..glyph + 3].fill(0); + let page = PageFrame { height_pt: 4.0, dpi: 72.0, x: 0, rgba: &rgba, width: 8, height: 4 }; + // The whole page box contains the glyph: the ink wins over the white background. + assert_eq!(page.text_color(0.0, 4.0, 8.0, 0.0), photocraft_doc::Color::BLACK); + // A box that contains only background keeps the background colour. + assert_eq!(page.text_color(4.0, 4.0, 8.0, 2.0), photocraft_doc::Color::rgb(1.0, 1.0, 1.0)); + } } diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index db6fc6cdf3f..476818fa449 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -44,6 +44,7 @@ mod orientation; mod pattern_fill_psd; mod pcraft_full_composite; mod pcraft_manifest_name; +mod pdf_import; mod pdn_corpus; mod png_steps; mod png_text_metadata; diff --git a/crates/io/tests/it/pdf_import.rs b/crates/io/tests/it/pdf_import.rs new file mode 100644 index 00000000000..0e1c36eba24 --- /dev/null +++ b/crates/io/tests/it/pdf_import.rs @@ -0,0 +1,143 @@ +//! PDF import end-to-end through PDFium. +//! +//! A synthetic two-page PDF with non-origin red text, a transformed blue rectangle and green text +//! is imported at 72 and 300 DPI, and the resulting editable layers are checked against the +//! fixture's geometry and pixels. PDFium is loaded at run time: when it is unavailable (no +//! `PDFIUM_DIR`, no DLL beside the test binary) the test prints an explicit SKIPPED line and +//! returns instead of pretending the end-to-end wiring passed. + +use lopdf::{Document as PdfDocument, Object, Stream, dictionary}; +use photocraft_doc::{Color, Document, Layer, LayerContent, ShapeLayer, TextLayer}; +use photocraft_io::{ImportOptions, IoError, import_with_options_and_interrupt}; + +const PAGE_W: f64 = 200.0; +const PAGE_H: f64 = 100.0; +const GAP: f64 = 80.0; + +#[test] +fn imports_text_and_a_transformed_path_on_two_pages() { + let pdf = two_page_pdf(); + for dpi in [72.0f32, 300.0] { + let options = ImportOptions { pdf_dpi: dpi, ..Default::default() }; + let result = match import_with_options_and_interrupt("fixture.pdf", &pdf, &options, &photocraft_raster::Interrupt::NONE) { + Ok(result) => result, + Err(IoError::Unsupported(message)) if message.contains("cannot load PDFium") => { + eprintln!("SKIPPED the PDF import end-to-end test: PDFium is unavailable ({message})"); + return; + } + Err(error) => panic!("PDF import failed at {dpi} dpi: {error}"), + }; + check(&result.document, dpi); + } +} + +/// Page 1: red 48 pt text at (20, 50). Page 2: a 20 x 10 pt rectangle scaled 2x and moved by +/// (10, 5) — corners (30, 25)..(70, 45) — plus green 48 pt text at (20, 20). +fn two_page_pdf() -> Vec { + let mut pdf = PdfDocument::with_version("1.5"); + let pages_id = pdf.new_object_id(); + let font_id = pdf.add_object(dictionary! { + "Type" => "Font", + "Subtype" => "Type1", + "BaseFont" => "Helvetica", + }); + let resources = pdf.add_object(dictionary! { + "Font" => dictionary! { "F1" => font_id }, + }); + let contents = ["1 0 0 rg BT /F1 48 Tf 20 50 Td (Red) Tj ET", "0 0 1 rg q 2 0 0 2 10 5 cm 10 10 20 10 re f Q 0 1 0 rg BT /F1 48 Tf 20 20 Td (Green) Tj ET"]; + let mut kids = Vec::new(); + for content in contents { + let content_id = pdf.add_object(Stream::new(dictionary! {}, content.as_bytes().to_vec())); + let page_id = pdf.add_object(dictionary! { + "Type" => "Page", + "Parent" => pages_id, + "MediaBox" => Object::Array(vec![0.into(), 0.into(), Object::Real(PAGE_W as f32), Object::Real(PAGE_H as f32)]), + "Contents" => content_id, + "Resources" => resources, + }); + kids.push(Object::Reference(page_id)); + } + let count = kids.len() as i64; + pdf.objects.insert( + pages_id, + Object::Dictionary(dictionary! { + "Type" => "Pages", + "Kids" => Object::Array(kids), + "Count" => count, + }), + ); + 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).expect("writing the PDF fixture"); + bytes +} + +fn check(document: &Document, dpi: f32) { + let scale = f64::from(dpi) / 72.0; + let page_two_x = (PAGE_W * scale).round() + GAP; + + // Page 1: the editable text keeps its position and takes the red ink from the page. + let text = text_layer(page_children(document, 1)); + assert_red(&text.color, "page 1 text"); + let x = text.transform.m[4]; + let y = text.transform.m[5]; + assert!((x - 20.0 * scale).abs() < 8.0 * scale, "page 1 text x is {x} at {dpi} dpi"); + // 48 pt Helvetica's bounds top is about 35 pt above the baseline at y = 50. + assert!((y - 15.0 * scale).abs() < 20.0 * scale, "page 1 text y is {y} at {dpi} dpi"); + + // Page 2: the transformed rectangle lands at (30, 25)..(70, 45) plus the page's document X. + let shape = shape_layer(page_children(document, 2)); + let (mut min_x, mut min_y, mut max_x, mut max_y) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); + for knot in shape.path.subpaths.iter().flat_map(|subpath| &subpath.knots) { + min_x = min_x.min(knot.anchor.x); + max_x = max_x.max(knot.anchor.x); + min_y = min_y.min(knot.anchor.y); + max_y = max_y.max(knot.anchor.y); + } + assert!((min_x - (page_two_x + 30.0 * scale)).abs() < 4.0, "path min x is {min_x}, page 2 starts at {page_two_x} ({dpi} dpi)"); + assert!((max_x - (page_two_x + 70.0 * scale)).abs() < 4.0, "path max x is {max_x} ({dpi} dpi)"); + assert!((min_y - (PAGE_H - 45.0) * scale).abs() < 4.0, "path min y is {min_y} ({dpi} dpi)"); + assert!((max_y - (PAGE_H - 25.0) * scale).abs() < 4.0, "path max y is {max_y} ({dpi} dpi)"); + + let text = text_layer(page_children(document, 2)); + assert_green(&text.color, "page 2 text"); + assert!(text.transform.m[4] > page_two_x + 10.0 * scale, "page 2 text x misses the page offset: {} <= {page_two_x}", text.transform.m[4]); +} + +fn page_children(document: &Document, page: usize) -> &[Layer] { + let name = format!("Page {page}"); + let layer = document.layers.iter().find(|layer| layer.name == name).unwrap_or_else(|| panic!("no {name} layer")); + match &layer.content { + LayerContent::Group(group) => &group.children, + _ => panic!("{name} is not a group"), + } +} + +fn text_layer(children: &[Layer]) -> &TextLayer { + children + .iter() + .find_map(|layer| match &layer.content { + LayerContent::Text(text) => Some(text), + _ => None, + }) + .expect("a text layer") +} + +fn shape_layer(children: &[Layer]) -> &ShapeLayer { + children + .iter() + .find_map(|layer| match &layer.content { + LayerContent::Shape(shape) => Some(shape), + _ => None, + }) + .expect("a shape layer") +} + +fn assert_red(color: &Color, what: &str) { + assert!(color.c[0] > 0.8 && color.c[1] < 0.2 && color.c[2] < 0.2, "{what} should be red, got {:?}", color.c); +} + +fn assert_green(color: &Color, what: &str) { + assert!(color.c[1] > 0.8 && color.c[0] < 0.2 && color.c[2] < 0.2, "{what} should be green, got {:?}", color.c); +} diff --git a/packaging/windows/package.ps1 b/packaging/windows/package.ps1 index 1f072fedb51..6efb64e7702 100644 --- a/packaging/windows/package.ps1 +++ b/packaging/windows/package.ps1 @@ -57,17 +57,51 @@ if (-not $env:PHOTOCRAFT_BUILD_DATE) { $env:PHOTOCRAFT_BUILD_DATE = (Get-Date).T # PDF import loads PDFium at runtime. Stage the Windows build's DLL before cargo, so the app's # build script copies it beside the exe and both the MSI and the portable ZIP ship it. +# +# Pinned to a reviewed pdfium-binaries release: the archive is verified before extraction and a +# cached DLL is verified before reuse, so a moved or compromised "latest" cannot be packaged. +# Bump the release and both hashes together after re-checking the published build. +$PdfiumRelease = 'chromium/8138' +$PdfiumArchiveSha256 = @{ + x64 = '8d48973e3eb472dda0f5f2435e595ac043f9f2219dd71883392f549445afa8a5' + x86 = '5c32d44711a73ed8ae86b85322078da8444fc696b9326527eed2d9fcd620fc84' + arm64 = '5e04abdb36ba9b4b5c8630123eaf042036f8a62abda6e5529708fee3d35fbf4f' +} +$PdfiumDllSha256 = @{ + x64 = '71a3e63e6ab8f5746a0fc9de9bc3d0c0dc07eb60990dfd37d9db7fc891821943' + x86 = 'ee592bd01eaef454aada95ed483ceca1c4f6ce0f0b9568608f40c3861fbda035' + arm64 = '0b1b9a52b3297448cbe461ffbca1455603d85161d5e96090e1a89bd7c4a62a33' +} $PdfiumDir = Join-Path $Root "target\pdfium\$Arch" $PdfiumDll = Join-Path $PdfiumDir 'pdfium.dll' + +function Get-Sha256([string] $Path) { (Get-FileHash -Algorithm SHA256 -LiteralPath $Path).Hash.ToLowerInvariant() } + +if (Test-Path -LiteralPath $PdfiumDll) { + $actualDll = Get-Sha256 $PdfiumDll + if ($actualDll -ne $PdfiumDllSha256[$Arch]) { + Write-Warning "cached PDFium DLL is not the pinned $PdfiumRelease build ($actualDll); re-downloading" + Remove-Item -LiteralPath $PdfiumDll -Force + } +} if (-not (Test-Path -LiteralPath $PdfiumDll)) { + $expectedArchive = $PdfiumArchiveSha256[$Arch] + if (-not $expectedArchive) { throw "no pinned PDFium checksum for $Arch" } $tgz = Join-Path $env:TEMP "pdfium-win-$Arch.tgz" - Invoke-Native "download PDFium ($Arch)" { - Invoke-WebRequest -Uri "https://github.com/bblanchon/pdfium-binaries/releases/latest/download/pdfium-win-$Arch.tgz" -OutFile $tgz + Invoke-Native "download PDFium ($Arch, $PdfiumRelease)" { + Remove-Item -LiteralPath $tgz -Force -ErrorAction SilentlyContinue + Invoke-WebRequest -Uri "https://github.com/bblanchon/pdfium-binaries/releases/download/$PdfiumRelease/pdfium-win-$Arch.tgz" -OutFile $tgz + $actualArchive = Get-Sha256 $tgz + if ($actualArchive -ne $expectedArchive) { throw "PDFium $Arch archive checksum $actualArchive does not match the pinned $expectedArchive" } New-Item -ItemType Directory -Force -Path $PdfiumDir | Out-Null - tar -xzf $tgz -C $PdfiumDir + # A DLL left in bin\ by an earlier run must not be mistaken for this archive's extraction. $extracted = Join-Path $PdfiumDir 'bin\pdfium.dll' + Remove-Item -LiteralPath $extracted -Force -ErrorAction SilentlyContinue + tar -xzf $tgz -C $PdfiumDir + if ($LASTEXITCODE -ne 0) { throw "PDFium $Arch archive extraction failed with exit code $LASTEXITCODE" } if (-not (Test-Path -LiteralPath $extracted)) { throw 'PDFium archive had no bin/pdfium.dll' } Move-Item -Force $extracted $PdfiumDll + Remove-Item -LiteralPath $tgz -Force } } $env:PDFIUM_DLL = $PdfiumDll From 95908e2b92476733f25efbb922e072fa5d91a582 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 22:16:32 +0100 Subject: [PATCH 16/30] Pin pdfium-render exactly to the verified wrapper Same reasoning as the wintab-sys pin in #11331: PDFium is FFI-loaded at run time, so a lockfile refresh must not move the wrapper under the pinned DLL release. Bump deliberately and re-check both the wrapper and the DLL release pin in packaging/windows/package.ps1. --- crates/io/Cargo.toml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index ef151b80cfb..c8885d5e9bf 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -52,7 +52,10 @@ resvg = { version = "0.45", default-features = false, features = ["text", "syste # The SVG fallback font search keeps each font file's character map (already in the tree through usvg). ttf-parser = { version = "0.25", default-features = false } # PDF import (pdf_import.rs): PDFium renders the pages; the direct surfaces build the document. -pdfium-render = "0.9" +# Pinned exactly, like the WinTab wrappers in photocraft-tablet: PDFium is FFI-loaded at run time +# and the DLL release is pinned separately in packaging/windows/package.ps1, so a lockfile refresh +# must not move the wrapper under it. Bump deliberately and re-check both. +pdfium-render = "=0.9.5" image = { workspace = true, features = ["png"] } [target.'cfg(target_arch = "wasm32")'.dependencies] From 4f585f704b781f9241311eaaa6db4c4b96766ed7 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 22:48:30 +0100 Subject: [PATCH 17/30] PDF: rotate/offset-aware objects, cancellation, licences, CI PDFium - Map editable text and paths through the page's crop box and /Rotate, matching the rendered raster: box offsets, 90/180/270 rotation, rotated text transforms and rotation-aware colour sampling. - Check cancellation while traversing page objects and before returning the import; cap text colour samples at 4096. - The cached PDFium failure now says to restart the application after fixing the library path. - package.ps1 stages PDFium's LICENSE and bundled licence files flat for the MSI and the portable ZIP, tags the cache with the pinned release, and verifies freshly extracted DLLs. - ci.yml provisions the pinned PDFium for the Windows integration leg and requires it there; local runs still skip explicitly. --- .github/workflows/ci.yml | 18 +++ crates/io/src/pdf_import.rs | 193 ++++++++++++++++++++++++++----- crates/io/tests/it/pdf_import.rs | 52 +++++++-- packaging/windows/package.ps1 | 24 +++- packaging/windows/photocraft.wxs | 5 + 5 files changed, 251 insertions(+), 41 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2c3597f5eea..4422f41a22e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -251,6 +251,24 @@ jobs: with: tool: cargo-nextest@0.9.150 + # The PDF import integration test loads PDFium at run time. Provision the pinned build for + # the integration leg and make an unavailable library fail there; local runs still skip. + - name: PDFium for the PDF import test + if: matrix.part == 'integration' + shell: pwsh + run: | + $dir = Join-Path $env:RUNNER_TEMP 'pdfium' + New-Item -ItemType Directory -Force $dir | Out-Null + $tgz = Join-Path $env:RUNNER_TEMP 'pdfium-win-x64.tgz' + Invoke-WebRequest -Uri 'https://github.com/bblanchon/pdfium-binaries/releases/download/chromium/8138/pdfium-win-x64.tgz' -OutFile $tgz + $hash = (Get-FileHash -Algorithm SHA256 -LiteralPath $tgz).Hash.ToLowerInvariant() + if ($hash -ne '8d48973e3eb472dda0f5f2435e595ac043f9f2219dd71883392f549445afa8a5') { + throw "PDFium archive checksum $hash does not match the pinned chromium/8138 build" + } + tar -xzf $tgz -C $dir + "PDFIUM_DIR=$dir\bin" >> $env:GITHUB_ENV + "PHOTOCRAFT_REQUIRE_PDFIUM=1" >> $env:GITHUB_ENV + # The unit leg runs `--lib --bins` and the integration leg `--test '*'` (every # integration-test target); the feature selection stays the same, so both legs share the # dependency cache. diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index 679198ff8b3..82233b2abc2 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -60,19 +60,17 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - } let page_count = last - first + 1; let count = page_count.min(MAX_PAGES); - // The page sizes in points first: the effective DPI must fit the budgets, and capping the - // raster must not change the page's physical size. - let mut sizes = Vec::with_capacity(count); + // The page geometry first: the effective DPI must fit the budgets, capping the raster must + // not change the page's physical size, and editable objects are mapped through the same page + // box and rotation the raster uses. + let mut geoms = Vec::with_capacity(count); for index in 0..count { ctl.check().map_err(|_| IoError::Cancelled)?; let page_index = first - 1 + index; let page = document.pages().get(page_index as i32).map_err(|e| IoError::Unsupported(format!("PDF: {e}")))?; - let (w, h) = (f64::from(page.width().value), f64::from(page.height().value)); - if w <= 0.0 || h <= 0.0 { - return Err(IoError::Unsupported(format!("PDF page {} has no area", page_index + 1))); - } - sizes.push((w, h)); + geoms.push(page_geometry(&page, page_index + 1)?); } + let sizes: Vec<(f64, f64)> = geoms.iter().map(|g| (g.width_pt, g.height_pt)).collect(); let dpi = effective_dpi(requested, &sizes, GAP, MAX_PAGE_PIXELS, MAX_UNION_PIXELS); let doc_width = sizes.iter().map(|(w, _)| (w * dpi / 72.0).round() as u64).sum::() + u64::from(GAP) * (count as u64 - 1); let doc_height = sizes.iter().map(|(_, h)| (h * dpi / 72.0).round() as u64).max().unwrap_or(1); @@ -108,7 +106,8 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - let mut doc = Document::new(name, Size::new(doc_width as u32, doc_height as u32), ColorMode::Rgb, SampleType::U8); doc.resolution_dpi = dpi as f32; let mut x = 0u32; - for (index, (w_pt, h_pt)) in sizes.iter().enumerate() { + for (index, geometry) in geoms.iter().enumerate() { + let (w_pt, h_pt) = (geometry.width_pt, geometry.height_pt); ctl.check().map_err(|_| IoError::Cancelled)?; let page_index = first - 1 + index; let target_width = (w_pt * dpi / 72.0).round().max(1.0) as i32; @@ -155,7 +154,8 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - let rect = Rect::new(x as i32, 0, (x + width) as i32, height as i32); let mut children = vec![layer]; if opts.pdf_text || opts.pdf_vectors { - children.extend(object_layers(&page, opts, &PageFrame { height_pt: *h_pt, dpi, x, rgba: &rgba, width, height })); + let frame = PageFrame { geometry: *geometry, dpi, x, rgba: &rgba, width, height }; + children.extend(object_layers(&page, opts, &frame, ctl)?); } let group = Group { children, expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None }; doc.layers.push(Layer::new(format!("Page {}", page_index + 1), LayerContent::Group(group))); @@ -171,9 +171,54 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - Ok(ImportResult { warnings, document: doc, source_read_only: false, preview_only: false }) } -/// One rendered page's frame: its point height, DPI, document x, and the RGBA pixels. -struct PageFrame<'a> { +/// A page's visible area and rotation, in PDF points. +#[derive(Clone, Copy)] +struct PageGeometry { + /// Displayed size (rotation applied): the size the raster is rendered into. + width_pt: f64, height_pt: f64, + /// The crop box origin in unrotated PDF user space. + origin_x: f64, + origin_y: f64, + /// The crop box size in unrotated PDF user space. + crop_w: f64, + crop_h: f64, + /// Clockwise rotation the renderer applies: 0, 90, 180 or 270. + rotation: u16, +} + +/// The page's visible box and rotation. PDF page objects stay in unrotated user space, while the +/// raster is rendered through the crop box and the page's `/Rotate`, so editable layers must use +/// the same transform. +#[cfg(not(target_arch = "wasm32"))] +fn page_geometry(page: &pdfium_render::prelude::PdfPage, page_number: usize) -> Result { + let width_pt = f64::from(page.width().value); + let height_pt = f64::from(page.height().value); + if width_pt <= 0.0 || height_pt <= 0.0 { + return Err(IoError::Unsupported(format!("PDF page {page_number} has no area"))); + } + let rotation = page.rotation().map(|r| r.as_degrees() as u16).unwrap_or(0); + let (origin_x, origin_y, crop_w, crop_h) = match page.boundaries().crop().or_else(|_| page.boundaries().media()) { + Ok(boundary) => { + let r = boundary.bounds; + (f64::from(r.left().value), f64::from(r.bottom().value), f64::from(r.right().value - r.left().value), f64::from(r.top().value - r.bottom().value)) + } + Err(_) => (0.0, 0.0, width_pt, height_pt), + }; + // A malformed box falls back to the displayed size; 90 and 270 swap the axes. + let (crop_w, crop_h) = if crop_w > 0.0 && crop_h > 0.0 { + (crop_w, crop_h) + } else if rotation == 90 || rotation == 270 { + (height_pt, width_pt) + } else { + (width_pt, height_pt) + }; + Ok(PageGeometry { width_pt, height_pt, origin_x, origin_y, crop_w, crop_h, rotation }) +} + +/// One rendered page's frame: its geometry, DPI, document x, and the RGBA pixels. +struct PageFrame<'a> { + geometry: PageGeometry, dpi: f64, x: u32, rgba: &'a [u8], @@ -182,12 +227,38 @@ struct PageFrame<'a> { } impl PageFrame<'_> { - /// Maps a point in PDF page space (points, origin bottom-left) to document pixels: the Y flip - /// and the page's X offset both belong to this mapping. + /// Maps a point in PDF page space to the page's own pixels: crop box, rotation and scale. + fn to_page_px(&self, x_pt: f32, y_pt: f32) -> (f64, f64) { + let g = &self.geometry; + let u = f64::from(x_pt) - g.origin_x; + let v = f64::from(y_pt) - g.origin_y; + let (dx, dy) = match g.rotation { + 90 => (v, u), + 180 => (g.crop_w - u, v), + 270 => (g.crop_h - v, g.crop_w - u), + _ => (u, g.crop_h - v), + }; + let scale = self.dpi / 72.0; + (dx * scale, dy * scale) + } + + /// Maps a point in PDF page space to document pixels: the page's own pixels plus its X offset. fn to_doc(&self, x_pt: f32, y_pt: f32) -> (f64, f64) { - let x_px = f64::from(x_pt) * self.dpi / 72.0 + f64::from(self.x); - let y_px = (self.height_pt - f64::from(y_pt)) * self.dpi / 72.0; - (x_px.round(), y_px.round()) + let (px, py) = self.to_page_px(x_pt, y_pt); + ((px + f64::from(self.x)).round(), py.round()) + } + + /// The text layer's transform at document pixel (`x`, `y`): the page rotation turns the text + /// layout too, so rotated pages get rotated editable text rather than upright text at a + /// rotated position. + fn text_transform(&self, x: f64, y: f64) -> Affine { + let (a, b, c, d) = match self.geometry.rotation { + 90 => (0.0, 1.0, -1.0, 0.0), + 180 => (-1.0, 0.0, 0.0, -1.0), + 270 => (0.0, -1.0, 1.0, 0.0), + _ => (1.0, 0.0, 0.0, 1.0), + }; + Affine { m: [a, b, c, d, x, y] } } /// The rendered page's colour at local pixel (`x`, `y`), or black outside it. @@ -207,22 +278,33 @@ impl PageFrame<'_> { /// colour instead: for dark text on a light page that is a glyph core, and for light text on a /// dark page it is the glyph rather than the background. fn text_color(&self, left: f32, top: f32, right: f32, bottom: f32) -> Color { - let x0 = (f64::from(left) * self.dpi / 72.0).floor().max(0.0) as u32; - let x1 = (f64::from(right) * self.dpi / 72.0).ceil().clamp(0.0, f64::from(self.width)) as u32; - // PDF's Y grows up; the rendered page's Y grows down. - let y0 = ((self.height_pt - f64::from(top)) * self.dpi / 72.0).floor().max(0.0) as u32; - let y1 = ((self.height_pt - f64::from(bottom)) * self.dpi / 72.0).ceil().clamp(0.0, f64::from(self.height)) as u32; + // The box's four corners through the same rotation-aware mapping as the glyphs. + let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); + for (x, y) in [(left, bottom), (left, top), (right, top), (right, bottom)] { + let (px, py) = self.to_page_px(x, y); + x0 = x0.min(px); + x1 = x1.max(px); + y0 = y0.min(py); + y1 = y1.max(py); + } + let x0 = x0.floor().max(0.0) as u32; + let x1 = x1.ceil().clamp(0.0, f64::from(self.width)) as u32; + let y0 = y0.floor().max(0.0) as u32; + let y1 = y1.ceil().clamp(0.0, f64::from(self.height)) as u32; if x1 <= x0 || y1 <= y0 { return Color::BLACK; } - // At most ~4096 samples, so a page-sized text box stays cheap. + // At most 4096 samples, so a page-sized text box stays cheap. let step = ((f64::from(x1 - x0) * f64::from(y1 - y0) / 4096.0).sqrt().ceil() as u32).max(1); let mut samples: Vec<[f32; 3]> = Vec::new(); let mut buckets: std::collections::HashMap = std::collections::HashMap::new(); let mut y = y0; - while y < y1 { + 'rows: while y < y1 { let mut x = x0; while x < x1 { + if samples.len() >= 4096 { + break 'rows; + } let c = self.color_at(x, y); let rgb = [c.c[0], c.c[1], c.c[2]]; let key = (rgb[0] * 31.0) as u32 * 1024 + (rgb[1] * 31.0) as u32 * 32 + (rgb[2] * 31.0) as u32; @@ -253,12 +335,15 @@ impl PageFrame<'_> { /// Editable text and shape layers for one rendered page, in document pixels. #[cfg(not(target_arch = "wasm32"))] -fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, frame: &PageFrame) -> Vec { +fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, frame: &PageFrame, ctl: &Interrupt) -> Result, IoError> { use pdfium_render::prelude::*; let objects = page.objects(); let mut layers = Vec::new(); for object in objects.iter() { + if ctl.check().is_err() { + return Err(IoError::Cancelled); + } match object { PdfPageObject::Text(text) if opts.pdf_text => { let content = text.text(); @@ -280,7 +365,7 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f font_family: family, size_pt: size_pt as f32, color, - transform: Affine::translate(x_px, y_px), + transform: frame.text_transform(x_px, y_px), ..Default::default() }), ); @@ -359,7 +444,7 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f _ => {} } } - layers + Ok(layers) } /// The highest DPI not above `requested` that keeps every page and the artboard strip within @@ -403,7 +488,10 @@ fn bind() -> Result { drop(Pdfium::new(bindings)); Ok(()) } - Err(e) => Err(format!("PDF import: cannot load PDFium from {} ({e}); put {platform} next to the executable or set PDFIUM_DIR", library.display())), + Err(e) => Err(format!( + "PDF import: cannot load PDFium from {} ({e}); put {platform} next to the executable or set PDFIUM_DIR, then restart the application", + library.display() + )), } }); match init { @@ -415,10 +503,14 @@ fn bind() -> Result { #[cfg(test)] mod tests { - use super::PageFrame; + use super::{PageFrame, PageGeometry}; + + fn geometry(rotation: u16) -> PageGeometry { + PageGeometry { width_pt: 595.0, height_pt: 842.0, origin_x: 0.0, origin_y: 0.0, crop_w: 595.0, crop_h: 842.0, rotation } + } fn frame(dpi: f64, x: u32) -> PageFrame<'static> { - PageFrame { height_pt: 842.0, dpi, x, rgba: &[], width: 595, height: 842 } + PageFrame { geometry: geometry(0), dpi, x, rgba: &[], width: 595, height: 842 } } #[test] @@ -430,11 +522,41 @@ mod tests { assert_eq!(frame(300.0, 2480).to_doc(60.0, 420.0), (2730.0, 1758.0)); } + #[test] + fn crop_box_offsets_and_rotations_map_like_the_raster() { + // A 200 x 100 pt crop box at (10, 20), displayed rotated 90 degrees clockwise: 100 x 200. + let rotated = |rotation| PageFrame { + geometry: PageGeometry { width_pt: 100.0, height_pt: 200.0, origin_x: 10.0, origin_y: 20.0, crop_w: 200.0, crop_h: 100.0, rotation }, + dpi: 72.0, + x: 0, + rgba: &[], + width: 100, + height: 200, + }; + // At 72 dpi the rectangle (20, 30)..(60, 70) lands at (10, 10)..(50, 50). + assert_eq!(rotated(90).to_doc(20.0, 30.0), (10.0, 10.0)); + assert_eq!(rotated(90).to_doc(60.0, 70.0), (50.0, 50.0)); + // 180 mirrors X; 270 swaps the axes back. + assert_eq!(rotated(180).to_doc(20.0, 30.0), (190.0, 10.0)); + assert_eq!(rotated(270).to_doc(20.0, 30.0), (90.0, 190.0)); + // The page's document X offset is added after the page-space mapping. + let mut offset = rotated(90); + offset.x = 500; + assert_eq!(offset.to_doc(20.0, 30.0), (510.0, 10.0)); + } + #[test] fn samples_the_rendered_page() { // Two pixels: white then black. let rgba = [255u8, 255, 255, 255, 0, 0, 0, 255]; - let page = PageFrame { height_pt: 842.0, dpi: 72.0, x: 0, rgba: &rgba, width: 2, height: 1 }; + let page = PageFrame { + geometry: PageGeometry { width_pt: 2.0, height_pt: 1.0, origin_x: 0.0, origin_y: 0.0, crop_w: 2.0, crop_h: 1.0, rotation: 0 }, + dpi: 72.0, + x: 0, + rgba: &rgba, + width: 2, + height: 1, + }; assert_eq!(page.color_at(0, 0), photocraft_doc::Color::rgb(1.0, 1.0, 1.0)); assert_eq!(page.color_at(1, 0), photocraft_doc::Color::BLACK); assert_eq!(page.color_at(2, 0), photocraft_doc::Color::BLACK); @@ -446,7 +568,14 @@ mod tests { let mut rgba = vec![255u8; 8 * 4 * 4]; let glyph = (8 + 2) * 4; rgba[glyph..glyph + 3].fill(0); - let page = PageFrame { height_pt: 4.0, dpi: 72.0, x: 0, rgba: &rgba, width: 8, height: 4 }; + let page = PageFrame { + geometry: PageGeometry { width_pt: 8.0, height_pt: 4.0, origin_x: 0.0, origin_y: 0.0, crop_w: 8.0, crop_h: 4.0, rotation: 0 }, + dpi: 72.0, + x: 0, + rgba: &rgba, + width: 8, + height: 4, + }; // The whole page box contains the glyph: the ink wins over the white background. assert_eq!(page.text_color(0.0, 4.0, 8.0, 0.0), photocraft_doc::Color::BLACK); // A box that contains only background keeps the background colour. diff --git a/crates/io/tests/it/pdf_import.rs b/crates/io/tests/it/pdf_import.rs index 0e1c36eba24..9bee105b0ca 100644 --- a/crates/io/tests/it/pdf_import.rs +++ b/crates/io/tests/it/pdf_import.rs @@ -16,24 +16,30 @@ const GAP: f64 = 80.0; #[test] fn imports_text_and_a_transformed_path_on_two_pages() { - let pdf = two_page_pdf(); + let pdf = three_page_pdf(); for dpi in [72.0f32, 300.0] { let options = ImportOptions { pdf_dpi: dpi, ..Default::default() }; let result = match import_with_options_and_interrupt("fixture.pdf", &pdf, &options, &photocraft_raster::Interrupt::NONE) { Ok(result) => result, Err(IoError::Unsupported(message)) if message.contains("cannot load PDFium") => { eprintln!("SKIPPED the PDF import end-to-end test: PDFium is unavailable ({message})"); + // The Windows integration leg provisions PDFium and sets this: there a missing + // library must fail rather than let the runner report an unreached pass. + assert!(std::env::var_os("PHOTOCRAFT_REQUIRE_PDFIUM").is_none(), "PDFium is required for this test but could not load: {message}"); return; } Err(error) => panic!("PDF import failed at {dpi} dpi: {error}"), }; check(&result.document, dpi); + eprintln!("PDF import executed at {dpi} dpi: {} page groups, layer checks passed", result.document.layers.len()); } } /// Page 1: red 48 pt text at (20, 50). Page 2: a 20 x 10 pt rectangle scaled 2x and moved by -/// (10, 5) — corners (30, 25)..(70, 45) — plus green 48 pt text at (20, 20). -fn two_page_pdf() -> Vec { +/// (10, 5) - corners (30, 25)..(70, 45) - plus green 48 pt text at (20, 20). Page 3: a crop box +/// offset to (10, 20, 210, 120) and rotated 90 degrees clockwise, with a 40 x 40 pt rectangle at +/// (20, 30)..(60, 70) that renders at (10, 10)..(50, 50) on a 100 x 200 page. +fn three_page_pdf() -> Vec { let mut pdf = PdfDocument::with_version("1.5"); let pages_id = pdf.new_object_id(); let font_id = pdf.add_object(dictionary! { @@ -44,17 +50,25 @@ fn two_page_pdf() -> Vec { let resources = pdf.add_object(dictionary! { "Font" => dictionary! { "F1" => font_id }, }); - let contents = ["1 0 0 rg BT /F1 48 Tf 20 50 Td (Red) Tj ET", "0 0 1 rg q 2 0 0 2 10 5 cm 10 10 20 10 re f Q 0 1 0 rg BT /F1 48 Tf 20 20 Td (Green) Tj ET"]; + let pages = [ + ("1 0 0 rg BT /F1 48 Tf 20 50 Td (Red) Tj ET", [0.0f32, 0.0, PAGE_W as f32, PAGE_H as f32], None), + ("0 0 1 rg q 2 0 0 2 10 5 cm 10 10 20 10 re f Q 0 1 0 rg BT /F1 48 Tf 20 20 Td (Green) Tj ET", [0.0, 0.0, PAGE_W as f32, PAGE_H as f32], None), + ("0 0 1 rg 20 30 40 40 re f 0 0.5 0 rg BT /F1 24 Tf 40 60 Td (Rot) Tj ET", [10.0, 20.0, 210.0, 120.0], Some(90i64)), + ]; let mut kids = Vec::new(); - for content in contents { + for (content, [left, bottom, right, top], rotate) in pages { let content_id = pdf.add_object(Stream::new(dictionary! {}, content.as_bytes().to_vec())); - let page_id = pdf.add_object(dictionary! { + let mut page = dictionary! { "Type" => "Page", "Parent" => pages_id, - "MediaBox" => Object::Array(vec![0.into(), 0.into(), Object::Real(PAGE_W as f32), Object::Real(PAGE_H as f32)]), + "MediaBox" => Object::Array(vec![Object::Real(left), Object::Real(bottom), Object::Real(right), Object::Real(top)]), "Contents" => content_id, "Resources" => resources, - }); + }; + if let Some(rotate) = rotate { + page.set("Rotate", rotate); + } + let page_id = pdf.add_object(page); kids.push(Object::Reference(page_id)); } let count = kids.len() as i64; @@ -103,6 +117,28 @@ fn check(document: &Document, dpi: f32) { let text = text_layer(page_children(document, 2)); assert_green(&text.color, "page 2 text"); assert!(text.transform.m[4] > page_two_x + 10.0 * scale, "page 2 text x misses the page offset: {} <= {page_two_x}", text.transform.m[4]); + + // Page 3: the crop box (10, 20, 210, 120) and /Rotate 90 put the rectangle at (10..50, 10..50). + let shape = shape_layer(page_children(document, 3)); + let (mut min_x, mut min_y, mut max_x, mut max_y) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); + for knot in shape.path.subpaths.iter().flat_map(|subpath| &subpath.knots) { + min_x = min_x.min(knot.anchor.x); + max_x = max_x.max(knot.anchor.x); + min_y = min_y.min(knot.anchor.y); + max_y = max_y.max(knot.anchor.y); + } + let page_three_x = 2.0 * (PAGE_W * scale).round() + 2.0 * GAP; + assert!((min_x - (page_three_x + 10.0 * scale)).abs() < 3.0, "rotated path min x is {min_x}, page 3 starts at {page_three_x} ({dpi} dpi)"); + assert!((max_x - (page_three_x + 50.0 * scale)).abs() < 3.0, "rotated path max x is {max_x} ({dpi} dpi)"); + assert!((min_y - 10.0 * scale).abs() < 3.0, "rotated path min y is {min_y} ({dpi} dpi)"); + assert!((max_y - 50.0 * scale).abs() < 3.0, "rotated path max y is {max_y} ({dpi} dpi)"); + + // Rotated text: the layer's transform carries the 90 degree turn, not just its position. + let text = text_layer(page_children(document, 3)); + let m = text.transform.m; + assert!(m[0].abs() < 0.01 && (m[1] - 1.0).abs() < 0.01 && (m[2] + 1.0).abs() < 0.01 && m[3].abs() < 0.01, "page 3 text rotation is {m:?}"); + assert!(m[4] > page_three_x, "page 3 text x misses the page offset: {} <= {page_three_x}", m[4]); + assert!(text.color.c[1] > 0.3 && text.color.c[0] < 0.2 && text.color.c[2] < 0.2, "page 3 text should be green, got {:?}", text.color.c); } fn page_children(document: &Document, page: usize) -> &[Layer] { diff --git a/packaging/windows/package.ps1 b/packaging/windows/package.ps1 index 6efb64e7702..8b4e8d0fea9 100644 --- a/packaging/windows/package.ps1 +++ b/packaging/windows/package.ps1 @@ -74,9 +74,17 @@ $PdfiumDllSha256 = @{ } $PdfiumDir = Join-Path $Root "target\pdfium\$Arch" $PdfiumDll = Join-Path $PdfiumDir 'pdfium.dll' +$PdfiumLicense = Join-Path $PdfiumDir 'LICENSE' +$PdfiumLicenses = Join-Path $PdfiumDir 'licenses' +$PdfiumTag = Join-Path $PdfiumDir 'release.txt' function Get-Sha256([string] $Path) { (Get-FileHash -Algorithm SHA256 -LiteralPath $Path).Hash.ToLowerInvariant() } +# A cache from another pinned release (or missing its licence set) is discarded whole. +$cachedRelease = if (Test-Path -LiteralPath $PdfiumTag) { (Get-Content -Raw -LiteralPath $PdfiumTag).Trim() } else { '' } +if ($cachedRelease -ne $PdfiumRelease) { + Remove-Item -LiteralPath $PdfiumDir -Recurse -Force -ErrorAction SilentlyContinue +} if (Test-Path -LiteralPath $PdfiumDll) { $actualDll = Get-Sha256 $PdfiumDll if ($actualDll -ne $PdfiumDllSha256[$Arch]) { @@ -84,7 +92,7 @@ if (Test-Path -LiteralPath $PdfiumDll) { Remove-Item -LiteralPath $PdfiumDll -Force } } -if (-not (Test-Path -LiteralPath $PdfiumDll)) { +if (-not ((Test-Path -LiteralPath $PdfiumDll) -and (Test-Path -LiteralPath $PdfiumLicense) -and (Test-Path -LiteralPath $PdfiumLicenses))) { $expectedArchive = $PdfiumArchiveSha256[$Arch] if (-not $expectedArchive) { throw "no pinned PDFium checksum for $Arch" } $tgz = Join-Path $env:TEMP "pdfium-win-$Arch.tgz" @@ -101,11 +109,23 @@ if (-not (Test-Path -LiteralPath $PdfiumDll)) { if ($LASTEXITCODE -ne 0) { throw "PDFium $Arch archive extraction failed with exit code $LASTEXITCODE" } if (-not (Test-Path -LiteralPath $extracted)) { throw 'PDFium archive had no bin/pdfium.dll' } Move-Item -Force $extracted $PdfiumDll + Set-Content -LiteralPath $PdfiumTag -Value $PdfiumRelease -NoNewline + if ((Get-Sha256 $PdfiumDll) -ne $PdfiumDllSha256[$Arch]) { throw "extracted PDFium $Arch DLL checksum does not match the pinned build" } Remove-Item -LiteralPath $tgz -Force } } $env:PDFIUM_DLL = $PdfiumDll +# PDFium's BSD licence and the licences of the libraries bundled into its DLL ship beside it. They +# are staged flat with a `pdfium-` prefix, so both the MSI's INSTALLFOLDER and the portable root +# carry them whether the DLL came from this download or the cache. +function Stage-PdfiumLicences([string] $Dest) { + Copy-Item -LiteralPath $PdfiumLicense -Destination (Join-Path $Dest 'pdfium-LICENSE.txt') -Force + Get-ChildItem -LiteralPath $PdfiumLicenses -File | ForEach-Object { + Copy-Item -LiteralPath $_.FullName -Destination (Join-Path $Dest ("pdfium-license-" + $_.Name)) -Force + } +} + Write-Output "PhotoCraft $Version for Windows $Arch ($Target)" if (-not $SkipBuild) { @@ -141,6 +161,7 @@ Remove-Item -Recurse -Force $Stage -ErrorAction SilentlyContinue New-Item -ItemType Directory -Force -Path $Stage | Out-Null Copy-Item (Join-Path $Bin 'photocraft.exe'), (Join-Path $Bin 'photocraft-cli.exe') $Stage Copy-Item -LiteralPath $PdfiumDll -Destination $Stage +Stage-PdfiumLicences $Stage & (Join-Path $PSScriptRoot 'sign.ps1') (Join-Path $Stage 'photocraft.exe') (Join-Path $Stage 'photocraft-cli.exe') @@ -224,6 +245,7 @@ Remove-Item -Recurse -Force $Portable -ErrorAction SilentlyContinue New-Item -ItemType Directory -Force -Path $Portable | Out-Null Copy-Item (Join-Path $Stage '*.exe') $Portable Copy-Item -LiteralPath $PdfiumDll -Destination $Portable +Stage-PdfiumLicences $Portable foreach ($f in 'README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') { $p = Join-Path $Root $f if (Test-Path $p) { Copy-Item $p $Portable } diff --git a/packaging/windows/photocraft.wxs b/packaging/windows/photocraft.wxs index 020f7aa89cf..f727880a5a6 100644 --- a/packaging/windows/photocraft.wxs +++ b/packaging/windows/photocraft.wxs @@ -33,6 +33,7 @@ + + + + From 00a1b1cd3ebedfc090d5bc361b406adf5160c9a1 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 23:12:14 +0100 Subject: [PATCH 18/30] PDF: use PDFium's page bounding box; bound editable objects - Map editable objects through the page's effective bounding box (media box clipped to the crop box) rather than the raw CropBox: an oversized CropBox no longer offsets text or paths from the rendered page. Covered by a fourth fixture page with CropBox (-50, -50, 250, 150) around a 200 x 100 MediaBox. - Add a document-wide editable-object budget (20,000 layers, 1,000,000 path knots). A page that exceeds it keeps its raster, warns that its editable objects were omitted, and the unit test covers the accounting. --- crates/io/src/pdf_import.rs | 98 +++++++++++++++++++++++++++++--- crates/io/tests/it/pdf_import.rs | 30 ++++++++-- 2 files changed, 117 insertions(+), 11 deletions(-) diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index 82233b2abc2..10d88beaf85 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -103,6 +103,8 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - budget >> 20 ))); } + let mut object_budget = ObjectBudget::default(); + let mut object_warnings: Vec = Vec::new(); let mut doc = Document::new(name, Size::new(doc_width as u32, doc_height as u32), ColorMode::Rgb, SampleType::U8); doc.resolution_dpi = dpi as f32; let mut x = 0u32; @@ -155,14 +157,18 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - let mut children = vec![layer]; if opts.pdf_text || opts.pdf_vectors { let frame = PageFrame { geometry: *geometry, dpi, x, rgba: &rgba, width, height }; - children.extend(object_layers(&page, opts, &frame, ctl)?); + let (layers, truncated) = object_layers(&page, opts, &frame, ctl, &mut object_budget)?; + children.extend(layers); + if truncated { + object_warnings.push(format!("PDF page {}: editable text/vector layers omitted at the import limit (the raster page is kept)", page_index + 1)); + } } let group = Group { children, expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None }; doc.layers.push(Layer::new(format!("Page {}", page_index + 1), LayerContent::Group(group))); x += width + GAP; ctl.progress((index + 1) as f32 / count as f32); } - let mut warnings = Vec::new(); + let mut warnings = object_warnings; if first > 1 || last < total || count < page_count { let shown_last = first + count - 1; let reason = if count < page_count { " (the page limit is 16)" } else { "" }; @@ -171,6 +177,39 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - Ok(ImportResult { warnings, document: doc, source_read_only: false, preview_only: false }) } +/// Document-wide bound on editable objects. Text layers and path knots are allocated outside the +/// pixel-memory estimate, so a pathological PDF could otherwise exhaust memory. +const MAX_OBJECT_LAYERS: usize = 20_000; +const MAX_PATH_KNOTS: usize = 1_000_000; + +/// Tracks the editable objects created so far, document-wide. +#[derive(Default)] +struct ObjectBudget { + layers: usize, + knots: usize, +} + +impl ObjectBudget { + /// Claims one editable layer; false once the document-wide limit is reached. + fn claim_layer(&mut self) -> bool { + if self.layers >= MAX_OBJECT_LAYERS { + false + } else { + self.layers += 1; + true + } + } + + /// Claims `count` path knots; false if that would pass the document-wide limit. + fn claim_knots(&mut self, count: usize) -> bool { + if self.knots.saturating_add(count) > MAX_PATH_KNOTS { + false + } else { + self.knots += count; + true + } + } +} /// A page's visible area and rotation, in PDF points. #[derive(Clone, Copy)] struct PageGeometry { @@ -198,7 +237,9 @@ fn page_geometry(page: &pdfium_render::prelude::PdfPage, page_number: usize) -> return Err(IoError::Unsupported(format!("PDF page {page_number} has no area"))); } let rotation = page.rotation().map(|r| r.as_degrees() as u16).unwrap_or(0); - let (origin_x, origin_y, crop_w, crop_h) = match page.boundaries().crop().or_else(|_| page.boundaries().media()) { + // The page's effective box, as PDFium renders it: the bounding box (media box clipped to the + // crop box), not the raw crop box, which may extend past the media box. + let (origin_x, origin_y, crop_w, crop_h) = match page.boundaries().bounding().or_else(|_| page.boundaries().crop()).or_else(|_| page.boundaries().media()) { Ok(boundary) => { let r = boundary.bounds; (f64::from(r.left().value), f64::from(r.bottom().value), f64::from(r.right().value - r.left().value), f64::from(r.top().value - r.bottom().value)) @@ -335,12 +376,23 @@ impl PageFrame<'_> { /// Editable text and shape layers for one rendered page, in document pixels. #[cfg(not(target_arch = "wasm32"))] -fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, frame: &PageFrame, ctl: &Interrupt) -> Result, IoError> { +fn object_layers( + page: &pdfium_render::prelude::PdfPage, + opts: &ImportOptions, + frame: &PageFrame, + ctl: &Interrupt, + budget: &mut ObjectBudget, +) -> Result<(Vec, bool), IoError> { use pdfium_render::prelude::*; let objects = page.objects(); let mut layers = Vec::new(); - for object in objects.iter() { + let mut truncated = false; + 'objects: for object in objects.iter() { + if budget.layers >= MAX_OBJECT_LAYERS { + truncated = true; + break; + } if ctl.check().is_err() { return Err(IoError::Cancelled); } @@ -372,6 +424,10 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f if !text.is_visible() { layer.visible = false; } + if !budget.claim_layer() { + truncated = true; + break 'objects; + } layers.push(layer); } PdfPageObject::Path(path) if opts.pdf_vectors => { @@ -396,10 +452,18 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f subpaths.push(Subpath { closed, knots: std::mem::take(&mut knots), op: PathOp::Combine }); closed = false; } + if !budget.claim_knots(1) { + truncated = true; + break 'objects; + } let (px, py) = point(); knots.push(Knot::corner(px, py)); } PdfPathSegmentType::LineTo => { + if !budget.claim_knots(1) { + truncated = true; + break 'objects; + } let (px, py) = point(); knots.push(Knot::corner(px, py)); } @@ -412,6 +476,10 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f if let Some(prev) = knots.last_mut() { prev.out_ctrl = Point::new(c1x, c1y); } + if !budget.claim_knots(1) { + truncated = true; + break 'objects; + } knots.push(Knot::smooth(Point::new(ex, ey), Point::new(c2x, c2y), Point::new(ex, ey))); bezier.clear(); } @@ -431,6 +499,10 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f continue; } let stroke = stroked.then(|| ShapeStroke { paint: Fill::Solid(Color::BLACK), width: 1.0, ..Default::default() }); + if !budget.claim_layer() { + truncated = true; + break 'objects; + } layers.push(Layer::new( "Path", LayerContent::Shape(ShapeLayer { @@ -444,7 +516,7 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f _ => {} } } - Ok(layers) + Ok((layers, truncated)) } /// The highest DPI not above `requested` that keeps every page and the artboard strip within @@ -503,7 +575,7 @@ fn bind() -> Result { #[cfg(test)] mod tests { - use super::{PageFrame, PageGeometry}; + use super::{MAX_OBJECT_LAYERS, MAX_PATH_KNOTS, ObjectBudget, PageFrame, PageGeometry}; fn geometry(rotation: u16) -> PageGeometry { PageGeometry { width_pt: 595.0, height_pt: 842.0, origin_x: 0.0, origin_y: 0.0, crop_w: 595.0, crop_h: 842.0, rotation } @@ -522,6 +594,18 @@ mod tests { assert_eq!(frame(300.0, 2480).to_doc(60.0, 420.0), (2730.0, 1758.0)); } + #[test] + fn object_budget_stops_at_its_limits() { + let mut budget = ObjectBudget::default(); + for _ in 0..MAX_OBJECT_LAYERS { + assert!(budget.claim_layer()); + } + assert!(!budget.claim_layer()); + let mut knots = ObjectBudget::default(); + assert!(knots.claim_knots(MAX_PATH_KNOTS)); + assert!(!knots.claim_knots(1)); + assert!(!knots.claim_knots(usize::MAX)); + } #[test] fn crop_box_offsets_and_rotations_map_like_the_raster() { // A 200 x 100 pt crop box at (10, 20), displayed rotated 90 degrees clockwise: 100 x 200. diff --git a/crates/io/tests/it/pdf_import.rs b/crates/io/tests/it/pdf_import.rs index 9bee105b0ca..f659eb51660 100644 --- a/crates/io/tests/it/pdf_import.rs +++ b/crates/io/tests/it/pdf_import.rs @@ -51,12 +51,15 @@ fn three_page_pdf() -> Vec { "Font" => dictionary! { "F1" => font_id }, }); let pages = [ - ("1 0 0 rg BT /F1 48 Tf 20 50 Td (Red) Tj ET", [0.0f32, 0.0, PAGE_W as f32, PAGE_H as f32], None), - ("0 0 1 rg q 2 0 0 2 10 5 cm 10 10 20 10 re f Q 0 1 0 rg BT /F1 48 Tf 20 20 Td (Green) Tj ET", [0.0, 0.0, PAGE_W as f32, PAGE_H as f32], None), - ("0 0 1 rg 20 30 40 40 re f 0 0.5 0 rg BT /F1 24 Tf 40 60 Td (Rot) Tj ET", [10.0, 20.0, 210.0, 120.0], Some(90i64)), + ("1 0 0 rg BT /F1 48 Tf 20 50 Td (Red) Tj ET", [0.0f32, 0.0, PAGE_W as f32, PAGE_H as f32], None, None), + ("0 0 1 rg q 2 0 0 2 10 5 cm 10 10 20 10 re f Q 0 1 0 rg BT /F1 48 Tf 20 20 Td (Green) Tj ET", [0.0, 0.0, PAGE_W as f32, PAGE_H as f32], None, None), + ("0 0 1 rg 20 30 40 40 re f 0 0.5 0 rg BT /F1 24 Tf 40 60 Td (Rot) Tj ET", [10.0, 20.0, 210.0, 120.0], Some(90i64), None), + // A CropBox larger than the MediaBox: the rendered page and the mapping use the + // intersection, so the rectangle must not be offset by the crop box's negative origin. + ("0 0.5 0 rg 20 30 40 40 re f", [0.0, 0.0, PAGE_W as f32, PAGE_H as f32], None, Some([-50.0f32, -50.0, 250.0, 150.0])), ]; let mut kids = Vec::new(); - for (content, [left, bottom, right, top], rotate) in pages { + for (content, [left, bottom, right, top], rotate, crop) in pages { let content_id = pdf.add_object(Stream::new(dictionary! {}, content.as_bytes().to_vec())); let mut page = dictionary! { "Type" => "Page", @@ -68,6 +71,9 @@ fn three_page_pdf() -> Vec { if let Some(rotate) = rotate { page.set("Rotate", rotate); } + if let Some([left, bottom, right, top]) = crop { + page.set("CropBox", Object::Array(vec![Object::Real(left), Object::Real(bottom), Object::Real(right), Object::Real(top)])); + } let page_id = pdf.add_object(page); kids.push(Object::Reference(page_id)); } @@ -139,6 +145,22 @@ fn check(document: &Document, dpi: f32) { assert!(m[0].abs() < 0.01 && (m[1] - 1.0).abs() < 0.01 && (m[2] + 1.0).abs() < 0.01 && m[3].abs() < 0.01, "page 3 text rotation is {m:?}"); assert!(m[4] > page_three_x, "page 3 text x misses the page offset: {} <= {page_three_x}", m[4]); assert!(text.color.c[1] > 0.3 && text.color.c[0] < 0.2 && text.color.c[2] < 0.2, "page 3 text should be green, got {:?}", text.color.c); + + // Page 4: a CropBox (-50, -50, 250, 150) around a 200 x 100 MediaBox must not offset the rect. + let shape = shape_layer(page_children(document, 4)); + let (mut min_x, mut min_y, mut max_x, mut max_y) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); + for knot in shape.path.subpaths.iter().flat_map(|subpath| &subpath.knots) { + min_x = min_x.min(knot.anchor.x); + max_x = max_x.max(knot.anchor.x); + min_y = min_y.min(knot.anchor.y); + max_y = max_y.max(knot.anchor.y); + } + // Page 3 is rotated 90 degrees, so it is 100 pt wide on the strip, not 200. + let page_four_x = 2.0 * (PAGE_W * scale).round() + (100.0 * scale).round() + 3.0 * GAP; + assert!((min_x - (page_four_x + 20.0 * scale)).abs() < 3.0, "oversized-crop path min x is {min_x}, page 4 starts at {page_four_x} ({dpi} dpi)"); + assert!((max_x - (page_four_x + 60.0 * scale)).abs() < 3.0, "oversized-crop path max x is {max_x} ({dpi} dpi)"); + assert!((min_y - 30.0 * scale).abs() < 3.0, "oversized-crop path min y is {min_y} ({dpi} dpi)"); + assert!((max_y - 70.0 * scale).abs() < 3.0, "oversized-crop path max y is {max_y} ({dpi} dpi)"); } fn page_children(document: &Document, page: usize) -> &[Layer] { From eda8759d118bf6cf2cb6be965cec5f0fa05ad085 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 23:35:28 +0100 Subject: [PATCH 19/30] PDF: document the import test helpers Raise docstring coverage on the functions this PR adds: the fixture/assertion helpers in the end-to-end test and the importer's test frame builders now have doc comments. No behaviour change. --- crates/io/src/pdf_import.rs | 2 ++ crates/io/tests/it/pdf_import.rs | 7 +++++++ 2 files changed, 9 insertions(+) diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index 10d88beaf85..5a4908c108f 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -577,10 +577,12 @@ fn bind() -> Result { mod tests { use super::{MAX_OBJECT_LAYERS, MAX_PATH_KNOTS, ObjectBudget, PageFrame, PageGeometry}; + /// A 595 x 842 pt page with no offset, rotated by `rotation` degrees. fn geometry(rotation: u16) -> PageGeometry { PageGeometry { width_pt: 595.0, height_pt: 842.0, origin_x: 0.0, origin_y: 0.0, crop_w: 595.0, crop_h: 842.0, rotation } } + /// A full-page frame at `dpi`, starting at document x `x`. fn frame(dpi: f64, x: u32) -> PageFrame<'static> { PageFrame { geometry: geometry(0), dpi, x, rgba: &[], width: 595, height: 842 } } diff --git a/crates/io/tests/it/pdf_import.rs b/crates/io/tests/it/pdf_import.rs index f659eb51660..d84fb032305 100644 --- a/crates/io/tests/it/pdf_import.rs +++ b/crates/io/tests/it/pdf_import.rs @@ -14,6 +14,7 @@ const PAGE_W: f64 = 200.0; const PAGE_H: f64 = 100.0; const GAP: f64 = 80.0; +/// Imports the four-page fixture at 72 and 300 DPI and checks every layer it produces. #[test] fn imports_text_and_a_transformed_path_on_two_pages() { let pdf = three_page_pdf(); @@ -93,6 +94,7 @@ fn three_page_pdf() -> Vec { bytes } +/// Asserts the imported text and path layers at one DPI against the fixture geometry. fn check(document: &Document, dpi: f32) { let scale = f64::from(dpi) / 72.0; let page_two_x = (PAGE_W * scale).round() + GAP; @@ -163,6 +165,7 @@ fn check(document: &Document, dpi: f32) { assert!((max_y - 70.0 * scale).abs() < 3.0, "oversized-crop path max y is {max_y} ({dpi} dpi)"); } +/// The layer children of the imported `Page N` group. fn page_children(document: &Document, page: usize) -> &[Layer] { let name = format!("Page {page}"); let layer = document.layers.iter().find(|layer| layer.name == name).unwrap_or_else(|| panic!("no {name} layer")); @@ -172,6 +175,7 @@ fn page_children(document: &Document, page: usize) -> &[Layer] { } } +/// The first text layer among `children`. fn text_layer(children: &[Layer]) -> &TextLayer { children .iter() @@ -182,6 +186,7 @@ fn text_layer(children: &[Layer]) -> &TextLayer { .expect("a text layer") } +/// The first shape layer among `children`. fn shape_layer(children: &[Layer]) -> &ShapeLayer { children .iter() @@ -192,10 +197,12 @@ fn shape_layer(children: &[Layer]) -> &ShapeLayer { .expect("a shape layer") } +/// Asserts `color` is the fixture's red ink. fn assert_red(color: &Color, what: &str) { assert!(color.c[0] > 0.8 && color.c[1] < 0.2 && color.c[2] < 0.2, "{what} should be red, got {:?}", color.c); } +/// Asserts `color` is the fixture's green ink. fn assert_green(color: &Color, what: &str) { assert!(color.c[1] > 0.8 && color.c[0] < 0.2 && color.c[2] < 0.2, "{what} should be green, got {:?}", color.c); } From 2f95eac75b2f6bb1201c5570be512ba45bb4a83d Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 23:41:53 +0100 Subject: [PATCH 20/30] PDF: document the importer's known limits Module docs now state that pdfium-render 0.9.5 exposes path fill/stroke presence but not paint, width or dash (black paints, 1 pt stroke); that text colour is sampled and fonts are matched by family/name; and that only package.ps1 provisions PDFium, not the shared release workflow. The text and path extraction comments say the same where the code relies on it. --- crates/io/src/pdf_import.rs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index 5a4908c108f..cdb56c9d626 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -6,6 +6,15 @@ //! //! Text and vector page objects can be imported as editable layers (`ImportOptions::pdf_text` / //! `pdf_vectors`); their page-space points are mapped to document pixels through the effective DPI. +//! +//! # Known limits +//! +//! - pdfium-render 0.9.5 exposes a path's fill/stroke *presence* but not its paint colour, stroke +//! width or dash pattern, so imported paths are painted black (1 pt centre stroke when stroked). +//! - A text object exposes no fill colour: the colour is sampled from the rendered page's glyph +//! ink, and the font is matched by family/name rather than embedded or loaded from the PDF. +//! - PDFium is provisioned by `packaging/windows/package.ps1` (pinned release, verified DLL); the +//! shared craft-common-actions release workflow does not stage it. use crate::{ImportOptions, ImportResult, IoError}; use photocraft_color::{ColorMode, PixelFormat, SampleType}; @@ -404,8 +413,10 @@ fn object_layers( } let Ok(bounds) = text.bounds() else { continue }; let (x_px, y_px) = frame.to_doc(bounds.left().value, bounds.top().value); - // The text layer's size is in points; the transform is in document pixels. The - // text object does not expose its fill colour; sample the glyph ink from the page. + // The text layer's size is in points; the transform is in document pixels. + // The text object does not expose its fill colour; sample the glyph ink from the + // page. The font is matched by family/name, not embedded: a document font that is + // not installed renders with the closest family the text engine has. let color = frame.text_color(bounds.left().value, bounds.top().value, bounds.right().value, bounds.bottom().value); let size_pt = f64::from(text.scaled_font_size().value).max(1.0); let font = text.font(); @@ -434,7 +445,8 @@ fn object_layers( // PDFium reports the segments in object space; the object's matrix places them on // the page. Without it, scaled or rotated paths land in the wrong place. let matrix = path.matrix().unwrap_or(PdfMatrix::IDENTITY); - // The fill and stroke modes are exposed; the colours and dash pattern are not. + // The fill and stroke modes are exposed; the colours, stroke width and dash + // pattern are not, so both paints are black and a stroke is 1 pt wide. let filled = !matches!(path.fill_mode(), Ok(PdfPathFillMode::None)); let stroked = path.is_stroked().unwrap_or(false); if !filled && !stroked { From 7e1de84bceae3903b92d11b1b3d4e97235b8a54e Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 23:44:59 +0100 Subject: [PATCH 21/30] PDF: document the added test functions Every function this PR adds now has a doc comment, including the test functions in the importer, PDF export and layers_to_files suites. No behaviour change. --- crates/engine/src/cmd/file_cmds/tests.rs | 1 + crates/io/src/pdf/tests.rs | 1 + crates/io/src/pdf_import.rs | 5 +++++ 3 files changed, 7 insertions(+) diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index 6a14a7542b1..afb74faa5bc 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -2539,6 +2539,7 @@ fn layers_to_files_reports_skipped_layers_without_changing_files() { } #[test] +/// `groups: "layers"` walks into a group and writes each visible leaf as its own file. fn layers_to_files_exports_group_children_as_loose_files() { let dir = tmp("layers-groups"); let mut s = session(8, 8, 8); diff --git a/crates/io/src/pdf/tests.rs b/crates/io/src/pdf/tests.rs index 30c38a2698a..6741fea3460 100644 --- a/crates/io/src/pdf/tests.rs +++ b/crates/io/src/pdf/tests.rs @@ -395,6 +395,7 @@ fn leading_newline_stays_in_the_first_selection_span() { } #[test] +/// Each artboard becomes one labelled page, in document order. fn artboards_export_as_one_page_each() { use photocraft_doc::{Artboard, Group}; let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::F32, true); diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index cdb56c9d626..7cb1da50c2f 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -600,6 +600,7 @@ mod tests { } #[test] + /// Page points map through the DPI scale, the Y flip and the page's document X offset. fn page_points_map_to_document_pixels() { assert_eq!(frame(72.0, 0).to_doc(60.0, 420.0), (60.0, 422.0)); // The same point at four times the resolution. @@ -609,6 +610,7 @@ mod tests { } #[test] + /// The document-wide budget refuses layers and knots once its limits are reached. fn object_budget_stops_at_its_limits() { let mut budget = ObjectBudget::default(); for _ in 0..MAX_OBJECT_LAYERS { @@ -621,6 +623,7 @@ mod tests { assert!(!knots.claim_knots(usize::MAX)); } #[test] + /// Crop-box offsets and 90/180/270 rotations land where the raster renders them. fn crop_box_offsets_and_rotations_map_like_the_raster() { // A 200 x 100 pt crop box at (10, 20), displayed rotated 90 degrees clockwise: 100 x 200. let rotated = |rotation| PageFrame { @@ -644,6 +647,7 @@ mod tests { } #[test] + /// The page sampler reads the requested pixel and reports black outside the page. fn samples_the_rendered_page() { // Two pixels: white then black. let rgba = [255u8, 255, 255, 255, 0, 0, 0, 255]; @@ -661,6 +665,7 @@ mod tests { } #[test] + /// Glyph ink wins over the background inside a text box, while an empty box keeps background. fn text_colour_samples_the_glyph_ink() { // An 8 x 4 white page with one black glyph pixel at (2, 1). let mut rgba = vec![255u8; 8 * 4 * 4]; From b57603708e737c92ff7212cd48b4b722f3242f27 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 23:47:23 +0100 Subject: [PATCH 22/30] PDF: drop the unused image dependency from photocraft-io The PDF export codec goes through photocraft-codecs; nothing in the crate used the image crate, so the dependency and its lockfile edge are removed. pdfium-render stays pinned exactly. --- Cargo.lock | 1 - crates/io/Cargo.toml | 1 - 2 files changed, 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d3221556bc1..1a3f307c2ad 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5464,7 +5464,6 @@ dependencies = [ "craft-docpath", "crc32fast", "flate2", - "image", "imagesize", "lopdf", "miniz_oxide 0.9.1", diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index c8885d5e9bf..dd5a232f32e 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -56,7 +56,6 @@ ttf-parser = { version = "0.25", default-features = false } # and the DLL release is pinned separately in packaging/windows/package.ps1, so a lockfile refresh # must not move the wrapper under it. Bump deliberately and re-check both. pdfium-render = "=0.9.5" -image = { workspace = true, features = ["png"] } [target.'cfg(target_arch = "wasm32")'.dependencies] resvg = { version = "0.45", default-features = false, features = ["text", "raster-images"] } From f7dfe7a017f92453500a35339aabe108b6d0e2cf Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Sat, 7 Nov 2026 02:34:55 +0100 Subject: [PATCH 23/30] PDF: test last-object cancellation and raster fidelity - A complete import makes a fixed number of cancellation checks; cancelling on the last per-object check and on the public boundary check must both return Cancelled and never a document. - Six page variants (plain, CropBox offset, rotations 90/180/270, oversized CropBox) compare each stored page raster with a direct PDFium render at 72, 150 and 300 DPI: 18/18 byte-identical, and the sizes prove the crop intersection (190x80) and oversized CropBox (200x100) cases. - Both tests skip without PDFium and fail under PHOTOCRAFT_REQUIRE_PDFIUM, like the existing end-to-end test. --- crates/io/tests/it/pdf_import.rs | 155 ++++++++++++++++++++++++++++++- 1 file changed, 154 insertions(+), 1 deletion(-) diff --git a/crates/io/tests/it/pdf_import.rs b/crates/io/tests/it/pdf_import.rs index d84fb032305..ef02111309a 100644 --- a/crates/io/tests/it/pdf_import.rs +++ b/crates/io/tests/it/pdf_import.rs @@ -6,9 +6,15 @@ //! `PDFIUM_DIR`, no DLL beside the test binary) the test prints an explicit SKIPPED line and //! returns instead of pretending the end-to-end wiring passed. +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::{Duration, Instant}; + use lopdf::{Document as PdfDocument, Object, Stream, dictionary}; +use pdfium_render::prelude::{PdfRenderConfig, Pdfium}; use photocraft_doc::{Color, Document, Layer, LayerContent, ShapeLayer, TextLayer}; -use photocraft_io::{ImportOptions, IoError, import_with_options_and_interrupt}; +use photocraft_geom::Rect; +use photocraft_io::{ImportOptions, ImportResult, IoError, import_with_options_and_interrupt}; +use photocraft_raster::Interrupt; const PAGE_W: f64 = 200.0; const PAGE_H: f64 = 100.0; @@ -206,3 +212,150 @@ fn assert_red(color: &Color, what: &str) { fn assert_green(color: &Color, what: &str) { assert!(color.c[1] > 0.8 && color.c[0] < 0.2 && color.c[2] < 0.2, "{what} should be green, got {:?}", color.c); } + +/// Imports `bytes`, or prints SKIPPED and returns `None` when PDFium cannot load. The Windows +/// integration leg sets `PHOTOCRAFT_REQUIRE_PDFIUM`, where a missing library must fail. +fn imported_or_skipped(bytes: &[u8], options: &ImportOptions, ctl: &Interrupt<'_>, what: &str) -> Option { + match import_with_options_and_interrupt("probe.pdf", bytes, options, ctl) { + Ok(result) => Some(result), + Err(IoError::Unsupported(message)) if message.contains("cannot load PDFium") => { + eprintln!("SKIPPED {what}: PDFium is unavailable ({message})"); + assert!(std::env::var_os("PHOTOCRAFT_REQUIRE_PDFIUM").is_none(), "PDFium is required for {what} but could not load: {message}"); + None + } + Err(error) => panic!("{what} failed: {error}"), + } +} + +/// Six one-page variants for the cancellation and fidelity probes: plain, a CropBox offset to +/// (10, 20, 210, 120), rotations of 90, 180 and 270 degrees, and an oversized CropBox +/// (-50, -50, 250, 150) around the 200 x 100 MediaBox. Each page draws a 40 x 40 blue rectangle +/// and a 10 x 10 red one at (20, 30). +fn variant_pdf() -> Vec { + let mut pdf = PdfDocument::with_version("1.5"); + let pages_id = pdf.new_object_id(); + let pages: [(Option, Option<[f32; 4]>); 6] = [ + (None, None), + (None, Some([10.0, 20.0, 210.0, 120.0])), + (Some(90), None), + (Some(180), None), + (Some(270), None), + (None, Some([-50.0, -50.0, 250.0, 150.0])), + ]; + let mut kids = Vec::new(); + for (rotate, crop) in pages { + let content = b"0 0 1 rg 20 30 40 40 re f 1 0 0 rg 20 30 10 10 re f"; + let content_id = pdf.add_object(Stream::new(dictionary! {}, content.to_vec())); + let mut page = dictionary! { + "Type" => "Page", + "Parent" => pages_id, + "MediaBox" => Object::Array(vec![Object::Real(0.0), Object::Real(0.0), Object::Real(PAGE_W as f32), Object::Real(PAGE_H as f32)]), + "Contents" => content_id, + "Resources" => dictionary! {}, + }; + if let Some(rotate) = rotate { + page.set("Rotate", rotate); + } + if let Some([left, bottom, right, top]) = crop { + page.set("CropBox", Object::Array(vec![Object::Real(left), Object::Real(bottom), Object::Real(right), Object::Real(top)])); + } + kids.push(Object::Reference(pdf.add_object(page))); + } + let count = kids.len() as i64; + pdf.objects.insert( + pages_id, + Object::Dictionary(dictionary! { + "Type" => "Pages", + "Kids" => Object::Array(kids), + "Count" => count, + }), + ); + 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).expect("writing the variant PDF"); + bytes +} + +/// A cancel that lands on the last object's check, or on the public boundary after +/// `import_stages`, must be reported as `Cancelled` rather than returning a document. +#[test] +fn cancelling_on_the_last_checks_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); + if imported_or_skipped(&pdf, &options, &ctl, "the last-check cancellation test").is_none() { + return; + } + 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 per-object 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("probe.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:?}"), + } + assert!(elapsed < Duration::from_secs(10), "cancelling on {label} took {elapsed:?}"); + } +} + +/// Every imported page's stored raster must equal a direct PDFium render of the same page at the +/// same target width: crop intersection, rotation and the strip placement may not move or resample +/// a pixel. At 72, 150 and 300 DPI over the six variants that is 18 page renders. +#[test] +fn raster_matches_a_direct_pdfium_render() { + let pdf = variant_pdf(); + let mut compared = 0; + for dpi in [72.0f32, 150.0, 300.0] { + let options = ImportOptions { pdf_dpi: dpi, ..Default::default() }; + let Some(result) = imported_or_skipped(&pdf, &options, &Interrupt::NONE, "the raster fidelity matrix") else { + return; + }; + let pdfium = Pdfium::default(); + let reference = pdfium.load_pdf_from_byte_slice(&pdf, None).expect("reference PDF"); + assert_eq!(reference.pages().len() as usize, result.document.layers.len(), "page count at {dpi} dpi"); + for (index, layer) in result.document.layers.iter().enumerate() { + let group = match &layer.content { + LayerContent::Group(group) => group, + _ => panic!("page layer {} is not a group", layer.name), + }; + let artboard = group.artboard.as_ref().expect("page artboard").rect; + let raster = group.children.first().and_then(|layer| layer.surface()).expect("page raster layer"); + let (width, height) = (artboard.width(), artboard.height()); + let mut got = vec![[0u8; 4]; (width as usize) * (height as usize)]; + raster.read_rgba8_into(Rect::from_xywh(artboard.x0, artboard.y0, width, height), &mut got); + + let page = reference.pages().get(index as i32).expect("reference page"); + let bitmap = page.render_with_config(&PdfRenderConfig::new().set_target_width(width as i32)).expect("reference render"); + assert_eq!((bitmap.width() as u32, bitmap.height() as u32), (width, height), "page {} size at {dpi} dpi", index + 1); + let want = bitmap.as_rgba_bytes(); + + let mut max_diff = 0u32; + let mut sum = 0u64; + for (pixel, reference) in got.iter().zip(want.as_chunks::<4>().0.iter()) { + for channel in 0..4 { + let diff = (pixel[channel] as i32 - reference[channel] as i32).unsigned_abs(); + sum += u64::from(diff); + max_diff = max_diff.max(diff); + } + } + let channels = u64::from(width) * u64::from(height) * 4; + let mean = sum as f64 / channels as f64; + assert!(max_diff <= 1, "page {} at {dpi} dpi differs from the direct render: max channel diff {max_diff}, mean {mean:.4}", index + 1); + compared += 1; + } + } + assert_eq!(compared, 18, "six pages at three DPIs should all be compared"); +} From ca92d936c00d4724916f4e57ae8937f78aa691d5 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Sat, 7 Nov 2026 19:41:22 +0100 Subject: [PATCH 24/30] PDF: import raster pages through craft-pdf instead of PDFium - craft-pdf (the shared Rust/Hayro reader in craft-libs, rev c5a1cbf) renders each page; no shared library is loaded or shipped, and every desktop platform works. - Raster pages only: editable text/vector import and the pdf_text/pdf_vectors options are removed (they can return later through craft-pdf's interpret device). Page geometry, artboards, page range, budgets, cancellation and warnings are kept; the effective DPI now respects craft-pdf's 8192 px side and 64M px page limits. - Drops pdfium-render, the PDFium download in CI, the build-script copy and the packaging/licence staging; records the Hayro/fonts/CMaps/ICC assets in ATTRIBUTION.md and NOTICE. - \.ai\ files starting with %PDF- now take the PDF importer, matching the comment. - Attribution, architecture and file-format-parity docs updated. --- .github/workflows/ci.yml | 18 - ATTRIBUTION.md | 13 + Cargo.lock | 385 +++++++++---- Cargo.toml | 6 + NOTICE | 11 + apps/photocraft/build.rs | 13 - crates/io/Cargo.toml | 7 +- crates/io/src/lib.rs | 52 +- crates/io/src/pdf_import.rs | 764 ++++++-------------------- crates/io/tests/it/pdf_import.rs | 393 ++++--------- docs/architecture.md | 2 +- docs/file-format-parity.md | 3 +- packaging/windows/install-policy.json | 3 +- packaging/windows/package.ps1 | 75 --- packaging/windows/photocraft.wxs | 7 - 15 files changed, 640 insertions(+), 1112 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4422f41a22e..2c3597f5eea 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -251,24 +251,6 @@ jobs: with: tool: cargo-nextest@0.9.150 - # The PDF import integration test loads PDFium at run time. Provision the pinned build for - # the integration leg and make an unavailable library fail there; local runs still skip. - - name: PDFium for the PDF import test - if: matrix.part == 'integration' - shell: pwsh - run: | - $dir = Join-Path $env:RUNNER_TEMP 'pdfium' - New-Item -ItemType Directory -Force $dir | Out-Null - $tgz = Join-Path $env:RUNNER_TEMP 'pdfium-win-x64.tgz' - Invoke-WebRequest -Uri 'https://github.com/bblanchon/pdfium-binaries/releases/download/chromium/8138/pdfium-win-x64.tgz' -OutFile $tgz - $hash = (Get-FileHash -Algorithm SHA256 -LiteralPath $tgz).Hash.ToLowerInvariant() - if ($hash -ne '8d48973e3eb472dda0f5f2435e595ac043f9f2219dd71883392f549445afa8a5') { - throw "PDFium archive checksum $hash does not match the pinned chromium/8138 build" - } - tar -xzf $tgz -C $dir - "PDFIUM_DIR=$dir\bin" >> $env:GITHUB_ENV - "PHOTOCRAFT_REQUIRE_PDFIUM=1" >> $env:GITHUB_ENV - # The unit leg runs `--lib --bins` and the integration leg `--test '*'` (every # integration-test target); the feature selection stays the same, so both legs share the # dependency cache. diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index f11c7f30e0f..bac96333203 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -166,3 +166,16 @@ are adapted from Skyfuller1303’s MIT OR Apache-2.0 implementation in `897f20072762fdf0eb688adcdb8d8cda7b38ce66`. Don Omondi’s embedded AI/PDF/EPS extension and current-main integration build on that source. Clipboard and unrelated Shape Tools changes from that branch are not included. + +## Assets bundled by the PDF reader dependency (craft-pdf) + +PhotoCraft imports PDF pages through `craft-pdf`, pinned to the craft-libs revision +`c5a1cbfb5f9049f9270955caffb5bee5997aebf7`. The renderer vendors Hayro and the assets below; +they ship inside the dependency rather than being copied into this repository. PDFium is no +longer used or shipped. + +| Crate / file | Author | Source | Licence | Use | +| --- | --- | --- | --- | --- | +| `hayro-interpret 0.7.0 / assets/Foxit*.pfb` (13 standard-14 font files) | Foxit Software Inc. / PDFium Authors | | BSD-3-Clause | Renders non-embedded standard-14 PDF fonts | +| `hayro-interpret 0.7.0 / assets/CGATS001Compat-v2-micro.icc` | Clinton Ingram (saucecontrol/Compact-ICC-Profiles) | | CC0-1.0 | Default CMYK colour conversion | +| `hayro-cmap 0.1.0 / assets/cmaps.brotli` | Adobe | | BSD-3-Clause | Character-code mapping for CJK PDFs | diff --git a/Cargo.lock b/Cargo.lock index 049da1acef2..5e2a1dfca1f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -22,7 +22,7 @@ dependencies = [ "accesskit", "accesskit_consumer", "atspi-common", - "phf", + "phf 0.14.0", "serde", "zvariant", ] @@ -826,6 +826,17 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "brotli" +version = "8.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor", +] + [[package]] name = "brotli-decompressor" version = "5.0.3" @@ -874,12 +885,6 @@ dependencies = [ "syn 3.0.6", ] -[[package]] -name = "byteorder" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" - [[package]] name = "byteorder-lite" version = "0.1.0" @@ -1284,26 +1289,6 @@ dependencies = [ "crossbeam-utils", ] -[[package]] -name = "console_error_panic_hook" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc" -dependencies = [ - "cfg-if", - "wasm-bindgen", -] - -[[package]] -name = "console_log" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86919cef3e37b9356ccf54d4421208c17ecfda01beae61393e7ffd72916c0ef1" -dependencies = [ - "log", - "web-sys", -] - [[package]] name = "const-oid" version = "0.9.6" @@ -1469,6 +1454,18 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-pdf" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +dependencies = [ + "bytemuck", + "hayro", + "hayro-interpret", + "hayro-syntax", + "thiserror 2.0.21", +] + [[package]] name = "craft-print" version = "0.1.0" @@ -1498,7 +1495,7 @@ dependencies = [ "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", "serde", - "skrifa", + "skrifa 0.44.0", "wasm-bindgen", "wasm-bindgen-futures", "web-sys", @@ -2133,7 +2130,7 @@ dependencies = [ "ecolor", "emath", "epaint_default_fonts", - "font-types", + "font-types 0.12.5", "harfrust", "log", "nohash-hasher", @@ -2141,13 +2138,13 @@ dependencies = [ "profiling", "self_cell", "serde", - "skrifa", + "skrifa 0.44.0", "smallvec", "unicode-bidi", "unicode-general-category", "unicode-properties", "unicode-segmentation", - "vello_cpu", + "vello_cpu 0.2.0", ] [[package]] @@ -2403,6 +2400,15 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" +[[package]] +name = "font-types" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b38ad915f6dadd993ced50848a8291a543bd41ca62bc10740d5e64e2ab4cfd7" +dependencies = [ + "bytemuck", +] + [[package]] name = "font-types" version = "0.12.5" @@ -2449,7 +2455,7 @@ dependencies = [ "objc2-core-text", "objc2-foundation 0.3.2", "parlance", - "read-fonts", + "read-fonts 0.41.0", "roxmltree 0.21.1", "smallvec", "windows", @@ -2743,6 +2749,23 @@ dependencies = [ "xml-rs", ] +[[package]] +name = "glifo" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d99fc21d493812643aae86d53b7bbd02f376434a90317e8a790bc209fdd6605e" +dependencies = [ + "bytemuck", + "foldhash 0.2.0", + "hashbrown 0.17.1", + "log", + "peniko", + "png 0.18.1", + "skrifa 0.42.1", + "smallvec", + "vello_common 0.0.9", +] + [[package]] name = "glifo" version = "0.3.0" @@ -2754,9 +2777,9 @@ dependencies = [ "hashbrown 0.17.1", "log", "peniko", - "skrifa", + "skrifa 0.44.0", "smallvec", - "vello_common", + "vello_common 0.2.0", ] [[package]] @@ -2905,7 +2928,7 @@ checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9" dependencies = [ "bitflags 2.13.2", "bytemuck", - "read-fonts", + "read-fonts 0.41.0", "smallvec", ] @@ -2938,6 +2961,94 @@ dependencies = [ "foldhash 0.2.0", ] +[[package]] +name = "hayro" +version = "0.7.1" +source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +dependencies = [ + "bytemuck", + "hayro-interpret", + "image", + "kurbo 0.13.1", + "log", + "pic-scale", + "vello_cpu 0.0.8", +] + +[[package]] +name = "hayro-ccitt" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" + +[[package]] +name = "hayro-cmap" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a14afde3344be69225fec4f6f44f6a219a3a492f9d8301eb25ef608fe4b7014c" +dependencies = [ + "brotli", + "hayro-postscript", +] + +[[package]] +name = "hayro-interpret" +version = "0.7.0" +source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +dependencies = [ + "bitflags 2.13.2", + "hayro-cmap", + "hayro-syntax", + "kurbo 0.13.1", + "moxcms", + "phf 0.13.1", + "rustc-hash 2.1.3", + "siphasher", + "skrifa 0.47.0", + "smallvec", + "yoke", +] + +[[package]] +name = "hayro-jbig2" +version = "0.3.0" +source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +dependencies = [ + "fearless_simd", + "hayro-ccitt", +] + +[[package]] +name = "hayro-jpeg2000" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1" +dependencies = [ + "fearless_simd", +] + +[[package]] +name = "hayro-postscript" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc2d80da85f31c3fdc0366431f44cfd645a9da1e242ed1f4a61f213d9765660f" + +[[package]] +name = "hayro-syntax" +version = "0.7.2" +source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +dependencies = [ + "flate2", + "hayro-ccitt", + "hayro-jbig2", + "hayro-jpeg2000", + "memchr", + "rustc-hash 2.1.3", + "smallvec", + "stringprep", + "zune-jpeg 0.5.15", +] + [[package]] name = "heck" version = "0.5.0" @@ -5027,7 +5138,7 @@ dependencies = [ "linebender_resource_handle", "parlance", "parley_data", - "skrifa", + "skrifa 0.44.0", ] [[package]] @@ -5057,32 +5168,6 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" -[[package]] -name = "pdfium-render" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "296b1146652b486ea6eea0d316e85ab6837ff69e8d2b1568e6fa7bc38bd4c00e" -dependencies = [ - "bitflags 2.13.2", - "bytemuck", - "bytes", - "chrono", - "console_error_panic_hook", - "console_log", - "image", - "itertools 0.15.0", - "js-sys", - "libloading", - "log", - "maybe-owned", - "once_cell", - "utf16string", - "vecmath", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", -] - [[package]] name = "pem" version = "3.0.6" @@ -5132,17 +5217,37 @@ dependencies = [ "indexmap", ] +[[package]] +name = "phf" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" +dependencies = [ + "phf_macros 0.13.1", + "phf_shared 0.13.1", +] + [[package]] name = "phf" version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6" dependencies = [ - "phf_macros", - "phf_shared", + "phf_macros 0.14.0", + "phf_shared 0.14.0", "serde", ] +[[package]] +name = "phf_generator" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" +dependencies = [ + "fastrand", + "phf_shared 0.13.1", +] + [[package]] name = "phf_generator" version = "0.14.0" @@ -5150,7 +5255,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100" dependencies = [ "fastrand", - "phf_shared", + "phf_shared 0.14.0", +] + +[[package]] +name = "phf_macros" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" +dependencies = [ + "phf_generator 0.13.1", + "phf_shared 0.13.1", + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] @@ -5159,13 +5277,22 @@ version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085" dependencies = [ - "phf_generator", - "phf_shared", + "phf_generator 0.14.0", + "phf_shared 0.14.0", "proc-macro2", "quote", "syn 2.0.119", ] +[[package]] +name = "phf_shared" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" +dependencies = [ + "siphasher", +] + [[package]] name = "phf_shared" version = "0.14.0" @@ -5486,12 +5613,12 @@ version = "0.20.1" dependencies = [ "blake3", "craft-docpath", + "craft-pdf", "crc32fast", "flate2", "imagesize", "lopdf", "miniz_oxide 0.9.1", - "pdfium-render", "photocraft-affinity", "photocraft-algo", "photocraft-cms", @@ -5638,7 +5765,7 @@ dependencies = [ "photocraft-psd", "photocraft-raster", "rayon", - "skrifa", + "skrifa 0.44.0", ] [[package]] @@ -5734,6 +5861,16 @@ dependencies = [ "web-sys", ] +[[package]] +name = "pic-scale" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6edb0ff645d35accaec252de081d55984a0d6c952cb1e5dc2b9afa7c78f07288" +dependencies = [ + "num-traits", + "pxfm", +] + [[package]] name = "pico-args" version = "0.5.0" @@ -5802,12 +5939,6 @@ dependencies = [ "system-deps", ] -[[package]] -name = "piston-float" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad78bf43dcf80e8f950c92b84f938a0fc7590b7f6866fbcbeca781609c115590" - [[package]] name = "pkg-config" version = "0.3.34" @@ -6365,6 +6496,16 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "read-fonts" +version = "0.39.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4ed38b89c2c77ff968c524145ad65fb010f38af5c7a224b53b81d47ac2daa81" +dependencies = [ + "bytemuck", + "font-types 0.11.3", +] + [[package]] name = "read-fonts" version = "0.41.0" @@ -6372,7 +6513,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709" dependencies = [ "bytemuck", - "font-types", + "font-types 0.12.5", + "once_cell", +] + +[[package]] +name = "read-fonts" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5a0cf4bb6cbce4c29756270d189a5e400ac05e91192161d83a0bcb6e68492e8" +dependencies = [ + "bytemuck", + "font-types 0.12.5", "once_cell", ] @@ -7319,6 +7471,16 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" +[[package]] +name = "skrifa" +version = "0.42.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c34617370ae968efb7161bb2beb517d9084659aae19e24b89e3db25b46e4564" +dependencies = [ + "bytemuck", + "read-fonts 0.39.2", +] + [[package]] name = "skrifa" version = "0.44.0" @@ -7326,7 +7488,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68" dependencies = [ "bytemuck", - "read-fonts", + "read-fonts 0.41.0", +] + +[[package]] +name = "skrifa" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "526e654b303ff4ad73a5a40b25de2b3ce3d039c5e3b6da5f89ae6e57004cb40f" +dependencies = [ + "bytemuck", + "read-fonts 0.44.0", ] [[package]] @@ -8290,15 +8462,6 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c8232dd3cdaed5356e0f716d285e4b40b932ac434100fe9b7e0e8e935b9e6246" -[[package]] -name = "utf16string" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b62a1e85e12d5d712bf47a85f426b73d303e2d00a90de5f3004df3596e9d216" -dependencies = [ - "byteorder", -] - [[package]] name = "utf8-zero" version = "0.8.1" @@ -8341,12 +8504,37 @@ dependencies = [ ] [[package]] -name = "vecmath" -version = "1.0.0" +name = "vello_common" +version = "0.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "956ae1e0d85bca567dee1dcf87fb1ca2e792792f66f87dced8381f99cd91156a" +checksum = "3361bff7f7d82c0c496b92048db83846691f0e844cc28dee92b1c824291b55ee" dependencies = [ - "piston-float", + "bytemuck", + "fearless_simd", + "guillotiere", + "hashbrown 0.17.1", + "log", + "peniko", + "png 0.18.1", + "smallvec", + "thiserror 2.0.21", +] + +[[package]] +name = "vello_common" +version = "0.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19d672facaa2d697285a786cd9d44d614cd2ce54cdc022504bf339f8fff3b750" +dependencies = [ + "bytemuck", + "fearless_simd", + "guillotiere", + "hashbrown 0.17.1", + "log", + "peniko", + "png 0.18.1", + "smallvec", + "thiserror 2.0.21", ] [[package]] @@ -8364,6 +8552,19 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "vello_cpu" +version = "0.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d8ded630e8316bb94a55881256506d1f3b9947b5f66db8a7d32ca7ba02decd0" +dependencies = [ + "bytemuck", + "glifo 0.1.1", + "hashbrown 0.17.1", + "png 0.18.1", + "vello_common 0.0.8", +] + [[package]] name = "vello_cpu" version = "0.2.0" @@ -8371,9 +8572,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ace506ca414548966fcf3c283be94eb1cad8254de488791ee698bf438b0890a9" dependencies = [ "bytemuck", - "glifo", + "glifo 0.3.0", "hashbrown 0.17.1", - "vello_common", + "vello_common 0.2.0", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index e01bcf175ab..f5fafa868d5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -40,6 +40,7 @@ photocraft-ipp = { path = "crates/ipp" } # external craft-print = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["raster"] } craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" } craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" } craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "b8f7d93b00dfb8f172938f3d2d796ae62dcfe123" } @@ -203,3 +204,8 @@ eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc79968157 egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } +# craft-pdf's vendored Hayro trees: consumers patch the same craft-libs revision (crates/pdf README). +hayro = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" } diff --git a/NOTICE b/NOTICE index 9ab6b0a1cf3..826dea74901 100644 --- a/NOTICE +++ b/NOTICE @@ -70,3 +70,14 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Optional PDF reader (craft-pdf) + +PhotoCraft imports PDF pages through craft-pdf (https://github.com/storytold/craft-libs, +MIT OR Apache-2.0), pinned to revision c5a1cbfb5f9049f9270955caffb5bee5997aebf7. It vendors +Hayro 0.7.1, hayro-interpret 0.7.0, hayro-syntax 0.7.2, hayro-jbig2 0.3.0 and +hayro-cmap 0.1.0 (https://github.com/LaurenzV/hayro, MIT OR Apache-2.0). The reader bundles +the standard-14 Foxit fonts (BSD-3-Clause), Adobe CMaps (BSD-3-Clause) and a Compact ICC +profile by Clinton Ingram (CC0-1.0); per-file sources and hashes are in craft-libs +ATTRIBUTION.md. No PDF assets are copied into this repository, and PDFium is no longer used or +shipped. diff --git a/apps/photocraft/build.rs b/apps/photocraft/build.rs index e750904018a..48abc9f1a51 100644 --- a/apps/photocraft/build.rs +++ b/apps/photocraft/build.rs @@ -11,19 +11,6 @@ fn main() { if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") { return; } - // PDF import loads PDFium at runtime. When the build provides the shared library - // (`PDFIUM_DLL`, set by the release packaging step), copy it beside the executable so the - // installer's pdfium.dll and the running app agree. - println!("cargo:rerun-if-env-changed=PDFIUM_DLL"); - if let (Some(dll), Ok(out)) = (std::env::var_os("PDFIUM_DLL"), std::env::var("OUT_DIR")) { - let dll = std::path::PathBuf::from(dll); - if let Some(profile_dir) = std::path::Path::new(&out).ancestors().nth(3) { - let dest = profile_dir.join(dll.file_name().unwrap_or_default()); - if let Err(e) = std::fs::copy(&dll, &dest) { - println!("cargo:warning=could not copy PDFium to {}: {e}", dest.display()); - } - } - } // Printing to PDF (winprint's `PdfCreateRenderer`) imports Windows.Data.Pdf.dll, which // stripped Windows images (NTLite, some N/LTSC builds) lack. A load-time import stops the exe // from starting at all ("windows.data.pdf.dll was not found", #5884), so load it on first use; diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index dd5a232f32e..36975e57eb2 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -51,11 +51,8 @@ imagesize = "0.13" resvg = { version = "0.45", default-features = false, features = ["text", "system-fonts", "raster-images"] } # The SVG fallback font search keeps each font file's character map (already in the tree through usvg). ttf-parser = { version = "0.25", default-features = false } -# PDF import (pdf_import.rs): PDFium renders the pages; the direct surfaces build the document. -# Pinned exactly, like the WinTab wrappers in photocraft-tablet: PDFium is FFI-loaded at run time -# and the DLL release is pinned separately in packaging/windows/package.ps1, so a lockfile refresh -# must not move the wrapper under it. Bump deliberately and re-check both. -pdfium-render = "=0.9.5" +# PDF import (pdf_import.rs): craft-pdf rasterizes pages in pure Rust; no shared library ships. +craft-pdf = { workspace = true } [target.'cfg(target_arch = "wasm32")'.dependencies] resvg = { version = "0.45", default-features = false, features = ["text", "raster-images"] } diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 54a4d1577e3..7519449224f 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -556,9 +556,9 @@ pub fn import_preflight(name: &str, bytes: &[u8]) -> ImportPreflight { if is_psd_input(name, bytes) { return ImportPreflight::Psd; } - // PDF (PDFium, native only). `.ai` files are PDFs but keep their existing path; a recognized - // raster signature wins over a misleading `.pdf` suffix. - if pdf_import::is_pdf(bytes) || (has_extension(name, "pdf") && !has_extension(name, "ai") && photocraft_codecs::detect(bytes).is_none()) { + // PDF (craft-pdf, pure Rust). `.ai` files that start with `%PDF-` are PDFs and take this + // importer too; a recognized raster signature wins over a misleading `.pdf` suffix. + if pdf_import::is_pdf(bytes) || (has_extension(name, "pdf") && photocraft_codecs::detect(bytes).is_none()) { return ImportPreflight::Unbounded; } if photocraft_codecs::detect(bytes) == Some(photocraft_codecs::Format::Tiff) { ImportPreflight::Tiff } else { ImportPreflight::Flat } @@ -612,10 +612,6 @@ pub struct ImportOptions { pub pdf_dpi: f32, /// The 1-based, inclusive page range to import; `None` imports every page (up to the cap). pub pdf_pages: Option<(u32, u32)>, - /// Import PDF text objects as editable text layers (default on). - pub pdf_text: bool, - /// Import PDF vector paths as editable shape layers (default on). - pub pdf_vectors: bool, /// Explicit one-shot authorization for imports that exceed the soft budget but fit within the hard budget. pub psd_high_memory_approved: bool, /// Optional estimate limit for high-memory approval. When set, approval only applies if @@ -632,8 +628,6 @@ impl Default for ImportOptions { flat_max_pixel_bytes: 0, pdf_dpi: 300.0, pdf_pages: None, - pdf_text: true, - pdf_vectors: true, psd_high_memory_approved: false, psd_approved_estimate: None, } @@ -999,9 +993,9 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, o if is_svg_input(name, bytes) { return svg::import_svg_with_group_depth(name, bytes, opts.max_group_depth); } - // PDF (PDFium, native only). `.ai` files are PDFs but keep their existing path; a recognized - // raster signature wins over a misleading `.pdf` suffix. - if pdf_import::is_pdf(bytes) || (has_extension(name, "pdf") && !has_extension(name, "ai") && photocraft_codecs::detect(bytes).is_none()) { + // PDF (craft-pdf, pure Rust). `.ai` files that start with `%PDF-` are PDFs and take this + // importer too; a recognized raster signature wins over a misleading `.pdf` suffix. + if pdf_import::is_pdf(bytes) || (has_extension(name, "pdf") && photocraft_codecs::detect(bytes).is_none()) { return pdf_import::import(name, bytes, opts, ctl); } match route(name, bytes) { @@ -1628,4 +1622,38 @@ mod tests { assert!(is_svg_input("drawing.svg", b"")); assert_eq!(crate::route("drawing.svg", pdf), crate::Route::Flat); } + + /// `.ai` files that start with `%PDF-` are PDFs: both preflight and dispatch send them to the + /// PDF importer rather than the flat decoder. + #[test] + fn an_ai_with_pdf_content_takes_the_pdf_importer() { + use lopdf::{Document as PdfDocument, Object, Stream, dictionary}; + let mut pdf = PdfDocument::with_version("1.5"); + let pages_id = pdf.new_object_id(); + let content = b"0 0 1 rg 10 10 20 20 re f"; + let content_id = pdf.add_object(Stream::new(dictionary! {}, content.to_vec())); + 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(100.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).expect("writing the .ai fixture"); + assert!(pdf_import::is_pdf(&bytes)); + assert_eq!(import_preflight("illustration.ai", &bytes), ImportPreflight::Unbounded); + let result = import("illustration.ai", &bytes).expect("an .ai starting with %PDF- takes the PDF importer"); + assert_eq!(result.document.artboards().len(), 1); + } } diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index 7cb1da50c2f..0fcc540749f 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -1,33 +1,28 @@ -//! PDF import: PDFium renders the selected pages and each page becomes an artboard. +//! PDF import: craft-pdf (a Rust PDF reader and renderer built on Hayro) rasterizes the +//! selected pages, and each page becomes one artboard. //! -//! The document resolution is chosen so the page's physical size is preserved even when the -//! raster is capped: pixels ÷ resolution × 72 pt is the PDF page's size. Pages are laid out side -//! by side; page count, per-page pixels, union pixels and the aggregate pixel budget are bounded. +//! Raster pages only: editable text and vector import would need craft-pdf's `interpret` +//! device and is not part of this importer. The renderer's hard output bounds (8192 px per +//! side and 64M px per page) and a document-wide strip budget are respected by lowering the +//! effective DPI, so each page keeps its physical size: pixels / resolution * 72 pt. //! -//! Text and vector page objects can be imported as editable layers (`ImportOptions::pdf_text` / -//! `pdf_vectors`); their page-space points are mapped to document pixels through the effective DPI. -//! -//! # Known limits -//! -//! - pdfium-render 0.9.5 exposes a path's fill/stroke *presence* but not its paint colour, stroke -//! width or dash pattern, so imported paths are painted black (1 pt centre stroke when stroked). -//! - A text object exposes no fill colour: the colour is sampled from the rendered page's glyph -//! ink, and the font is matched by family/name rather than embedded or loaded from the PDF. -//! - PDFium is provisioned by `packaging/windows/package.ps1` (pinned release, verified DLL); the -//! shared craft-common-actions release workflow does not stage it. +//! 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. use crate::{ImportOptions, ImportResult, IoError}; +use craft_pdf::interpret::InterpreterSettings; +use craft_pdf::raster::{self, RenderCache}; use photocraft_color::{ColorMode, PixelFormat, SampleType}; -use photocraft_doc::{Artboard, Color, Document, Fill, Group, Knot, Layer, LayerContent, Path, PathOp, ShapeLayer, ShapeStroke, Subpath, TextLayer}; -use photocraft_geom::{Affine, Point, Rect, Size}; +use photocraft_doc::{Artboard, Document, Group, Layer, LayerContent}; +use photocraft_geom::{Rect, Size}; use photocraft_raster::{Interrupt, Surface}; -/// `%PDF-` magic. `.ai` files are PDFs too, but the dispatch keeps them out of this importer. +/// `%PDF-` magic. `.ai` files that start with it are PDFs and render through this importer. pub fn is_pdf(bytes: &[u8]) -> bool { bytes.starts_with(b"%PDF-") } -/// Native PDF import is not available in the web build. +/// PDF import is not available in the web build. #[cfg(target_arch = "wasm32")] pub fn import(_name: &str, _bytes: &[u8], _opts: &ImportOptions, _ctl: &Interrupt) -> Result { Err(IoError::Unsupported("PDF import needs the desktop build".into())) @@ -36,23 +31,23 @@ pub fn import(_name: &str, _bytes: &[u8], _opts: &ImportOptions, _ctl: &Interrup /// Renders the selected PDF pages and opens each as one artboard. #[cfg(not(target_arch = "wasm32"))] pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) -> Result { - use pdfium_render::prelude::*; - /// The most pages one import renders. const MAX_PAGES: usize = 16; /// Gap between the artboards, in document pixels. const GAP: u32 = 80; - /// Per-page and per-artboard-strip pixel budgets; a poster at 300 dpi is far below these. - const MAX_PAGE_PIXELS: f64 = 100_000_000.0; + /// The document-wide raster budget across every imported page, in pixels. const MAX_UNION_PIXELS: u64 = 200_000_000; /// The default pixel-memory budget when the caller sets none: a zero /// [`ImportOptions::flat_max_pixel_bytes`] still bounds the import. const DEFAULT_MAX_PIXEL_BYTES: u64 = 2 << 30; + ctl.check().map_err(|_| IoError::Cancelled)?; let requested = if opts.pdf_dpi.is_finite() && opts.pdf_dpi > 0.0 { f64::from(opts.pdf_dpi) } else { 300.0 }; - let pdfium = bind()?; - let document = pdfium.load_pdf_from_byte_slice(bytes, None).map_err(|e| IoError::Unsupported(format!("PDF: {e}")))?; - let total = document.pages().len().max(0) as usize; + let pdf = craft_pdf::open_slice_with_options(bytes, None, &craft_pdf::OpenOptions::default()).map_err(open_error)?; + let total = pdf.pages().len(); + if total == 0 { + return Err(IoError::Unsupported("PDF has no pages".into())); + } let (first, last) = match opts.pdf_pages { Some((a, b)) => { let a = a.max(1); @@ -64,46 +59,45 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - } None => (1, total), }; - if total == 0 || first > total { - return Err(IoError::Unsupported("PDF has no pages in the requested range".into())); - } let page_count = last - first + 1; let count = page_count.min(MAX_PAGES); - // The page geometry first: the effective DPI must fit the budgets, capping the raster must - // not change the page's physical size, and editable objects are mapped through the same page - // box and rotation the raster uses. - let mut geoms = Vec::with_capacity(count); + + // Page sizes in points first: the effective DPI must fit the renderer's bounds without + // changing any page's physical size. + let mut sizes = Vec::with_capacity(count); for index in 0..count { + let page = &pdf.pages()[first - 1 + index]; + let (width, height) = page.render_dimensions(); + if !width.is_finite() || !height.is_finite() || width <= 0.0 || height <= 0.0 { + return Err(IoError::Unsupported(format!("PDF page {} has no area", first + index))); + } + sizes.push((f64::from(width), f64::from(height))); ctl.check().map_err(|_| IoError::Cancelled)?; - let page_index = first - 1 + index; - let page = document.pages().get(page_index as i32).map_err(|e| IoError::Unsupported(format!("PDF: {e}")))?; - geoms.push(page_geometry(&page, page_index + 1)?); } - let sizes: Vec<(f64, f64)> = geoms.iter().map(|g| (g.width_pt, g.height_pt)).collect(); - let dpi = effective_dpi(requested, &sizes, GAP, MAX_PAGE_PIXELS, MAX_UNION_PIXELS); - let doc_width = sizes.iter().map(|(w, _)| (w * dpi / 72.0).round() as u64).sum::() + u64::from(GAP) * (count as u64 - 1); - let doc_height = sizes.iter().map(|(_, h)| (h * dpi / 72.0).round() as u64).max().unwrap_or(1); + let dpi = effective_dpi(requested, &sizes, u64::from(raster::MAX_SIDE), raster::MAX_PIXELS, MAX_UNION_PIXELS); + + let mut doc_width: u64 = 0; + let mut doc_height: u64 = 0; + let mut retained: u64 = 0; + for (index, &(width_pt, height_pt)) in sizes.iter().enumerate() { + let width = page_pixels(width_pt, dpi); + let height = page_pixels(height_pt, dpi); + doc_width = doc_width.saturating_add(u64::from(width)).saturating_add(if index + 1 < count { u64::from(GAP) } else { 0 }); + doc_height = doc_height.max(u64::from(height)); + let tiles_x = (u64::from(width)).div_ceil(256); + let tiles_y = (u64::from(height)).div_ceil(256); + retained = retained.saturating_add(tiles_x.saturating_mul(tiles_y).saturating_mul(256 * 256 * 4)); + } if doc_width == 0 || doc_height == 0 { return Err(IoError::Unsupported("PDF pages have no area".into())); } - // The aggregate budget: the document keeps every page's raster tiles, while one page at a - // time is converted through the PDFium bitmap, its RGBA copy and the f32 buffer. - let page_px = |w: f64, h: f64| (w * dpi / 72.0).round().max(1.0) * (h * dpi / 72.0).round().max(1.0); - let max_page_pixels = sizes.iter().map(|&(w, h)| page_px(w, h)).fold(0.0_f64, f64::max); - // Retained backing: a page occupies whole 256 px tiles, including the ones its document X - // offset steps into. A 1 x 10,000 px page is 40 tiles (10 MiB), not 10,000 pixels. - const TILE: u64 = 256; - let mut retained: u64 = 0; - let mut page_x: u64 = 0; - for &(w, h) in &sizes { - let px = (w * dpi / 72.0).round().max(1.0) as u64; - let py = (h * dpi / 72.0).round().max(1.0) as u64; - let tiles_x = (page_x + px).div_ceil(TILE) - page_x / TILE; - retained = retained.saturating_add(tiles_x.saturating_mul(py.div_ceil(TILE)).saturating_mul(TILE * TILE * 4)); - page_x += px + u64::from(GAP); + if doc_width > u64::from(u32::MAX) || doc_height > u64::from(u32::MAX) { + return Err(IoError::Unsupported("PDF import is too large at this DPI; lower the import DPI".into())); } - // Plus 24 bytes/px (bitmap, RGBA copy, f32 conversion buffer) for the page being converted. - let estimate = retained.saturating_add((max_page_pixels * 24.0) as u64); + // Retained tiles plus the converting page's peak: craft-pdf's RGBA8 raster (4 B/px) and the + // f32 document buffer (16 B/px). + let max_page = sizes.iter().map(|&(w, h)| u64::from(page_pixels(w, dpi)) * u64::from(page_pixels(h, dpi))).max().unwrap_or(0); + let estimate = retained.saturating_add(max_page.saturating_mul(20)); let budget = if opts.flat_max_pixel_bytes > 0 { opts.flat_max_pixel_bytes } else { DEFAULT_MAX_PIXEL_BYTES }; if estimate > budget { return Err(IoError::Unsupported(format!( @@ -112,576 +106,134 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - budget >> 20 ))); } - let mut object_budget = ObjectBudget::default(); - let mut object_warnings: Vec = Vec::new(); - let mut doc = Document::new(name, Size::new(doc_width as u32, doc_height as u32), ColorMode::Rgb, SampleType::U8); - doc.resolution_dpi = dpi as f32; - let mut x = 0u32; - for (index, geometry) in geoms.iter().enumerate() { - let (w_pt, h_pt) = (geometry.width_pt, geometry.height_pt); - ctl.check().map_err(|_| IoError::Cancelled)?; - let page_index = first - 1 + index; - let target_width = (w_pt * dpi / 72.0).round().max(1.0) as i32; - let target_height = (h_pt * dpi / 72.0).round().max(1.0) as i32; - // A one-pixel-wide page would otherwise produce an arbitrarily tall bitmap before the - // union check runs; reject the final dimensions up front. - if f64::from(target_width) * f64::from(target_height) > MAX_PAGE_PIXELS { - return Err(IoError::Unsupported(format!( - "PDF page {} is too large at {dpi} dpi ({} x {} px); lower the import DPI", - page_index + 1, - target_width, - target_height - ))); - } - let page = document.pages().get(page_index as i32).map_err(|e| IoError::Unsupported(format!("PDF: {e}")))?; - let bitmap = - page.render_with_config(&PdfRenderConfig::new().set_target_width(target_width)).map_err(|e| IoError::Unsupported(format!("PDF render: {e}")))?; - let (width, height) = (bitmap.width().max(0) as u32, bitmap.height().max(0) as u32); - // The rounded target width can render a taller bitmap than the pre-check predicted. - if f64::from(width) * f64::from(height) > MAX_PAGE_PIXELS { - return Err(IoError::Unsupported(format!( - "PDF page {} rendered larger than the {MAX_PAGE_PIXELS} px budget ({} x {}); lower the import DPI", - page_index + 1, - width, - height - ))); - } - // The page's pixels go straight into the document-wide layer surface: no full-strip - // canvas and no PNG round-trip, so the peak is the page bitmap plus its tiles. - let mut surface = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, true)); - let rgba = bitmap.as_rgba_bytes(); - let mut data = Vec::new(); - if data.try_reserve_exact(rgba.len()).is_err() { - return Err(IoError::Unsupported(format!("PDF page {} needs more memory than is available", page_index + 1))); - } - for chunk in rgba.as_chunks::<4>().0 { - for &v in &chunk[..3] { - data.push(f32::from(v) / 255.0); - } - data.push(f32::from(chunk[3]) / 255.0); - } - surface.write_region(Rect::from_xywh(x as i32, 0, width, height), &data); - let layer = Layer::new(format!("Page {}", page_index + 1), LayerContent::Raster(surface)); - let rect = Rect::new(x as i32, 0, (x + width) as i32, height as i32); - let mut children = vec![layer]; - if opts.pdf_text || opts.pdf_vectors { - let frame = PageFrame { geometry: *geometry, dpi, x, rgba: &rgba, width, height }; - let (layers, truncated) = object_layers(&page, opts, &frame, ctl, &mut object_budget)?; - children.extend(layers); - if truncated { - object_warnings.push(format!("PDF page {}: editable text/vector layers omitted at the import limit (the raster page is kept)", page_index + 1)); - } - } - let group = Group { children, expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None }; - doc.layers.push(Layer::new(format!("Page {}", page_index + 1), LayerContent::Group(group))); - x += width + GAP; - ctl.progress((index + 1) as f32 / count as f32); - } - let mut warnings = object_warnings; + + let mut warnings = Vec::new(); if first > 1 || last < total || count < page_count { let shown_last = first + count - 1; let reason = if count < page_count { " (the page limit is 16)" } else { "" }; warnings.push(format!("PDF has {total} pages; imported pages {first}-{shown_last}{reason}")); } + if dpi + 0.5 < requested { + warnings.push(format!("PDF was rendered at {:.0} dpi to fit the import limits", dpi.max(1.0))); + } + + let mut doc = Document::new(name, Size::new(doc_width as u32, doc_height as u32), ColorMode::Rgb, SampleType::U8); + doc.resolution_dpi = dpi as f32; + let mut x: u32 = 0; + for index in 0..count { + ctl.check().map_err(|_| IoError::Cancelled)?; + let page_number = first + index; + let page = &pdf.pages()[page_number - 1]; + let (width_pt, height_pt) = sizes[index]; + let width = page_pixels(width_pt, dpi); + let height = page_pixels(height_pt, dpi); + // The DPI solve keeps these inside the renderer's bounds; re-check rather than panic if + // rounding on an edge moves one pixel past them. + if width > raster::MAX_SIDE || height > raster::MAX_SIDE || u64::from(width) * u64::from(height) > raster::MAX_PIXELS { + 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. + 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))?; + if rendered.diagnostics.image_decode_failed { + warnings.push(format!("PDF page {page_number}: an image could not be decoded and is missing")); + } + if rendered.diagnostics.content_truncated { + warnings.push(format!("PDF page {page_number}: some content was omitted (a decode or memory limit)")); + } + ctl.check().map_err(|_| IoError::Cancelled)?; + + let mut surface = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, true)); + let bytes = rendered.bytes(); + let mut data = Vec::new(); + if data.try_reserve_exact(bytes.len()).is_err() { + return Err(IoError::Unsupported(format!("PDF page {page_number} needs more memory than is available"))); + } + for chunk in bytes.as_chunks::<4>().0 { + for &value in &chunk[..3] { + data.push(f32::from(value) / 255.0); + } + data.push(f32::from(chunk[3]) / 255.0); + } + surface.write_region(Rect::from_xywh(x as i32, 0, width, height), &data); + let rect = Rect::new(x as i32, 0, (x + width) as i32, height as i32); + let layer = Layer::new(format!("Page {page_number}"), LayerContent::Raster(surface)); + let group = Group { children: vec![layer], expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None }; + doc.layers.push(Layer::new(format!("Page {page_number}"), LayerContent::Group(group))); + x = x.saturating_add(width).saturating_add(GAP); + ctl.progress((index + 1) as f32 / count as f32); + } + Ok(ImportResult { warnings, document: doc, source_read_only: false, preview_only: false }) } -/// Document-wide bound on editable objects. Text layers and path knots are allocated outside the -/// pixel-memory estimate, so a pathological PDF could otherwise exhaust memory. -const MAX_OBJECT_LAYERS: usize = 20_000; -const MAX_PATH_KNOTS: usize = 1_000_000; - -/// Tracks the editable objects created so far, document-wide. -#[derive(Default)] -struct ObjectBudget { - layers: usize, - knots: usize, -} - -impl ObjectBudget { - /// Claims one editable layer; false once the document-wide limit is reached. - fn claim_layer(&mut self) -> bool { - if self.layers >= MAX_OBJECT_LAYERS { - false - } else { - self.layers += 1; - true - } - } - - /// Claims `count` path knots; false if that would pass the document-wide limit. - fn claim_knots(&mut self, count: usize) -> bool { - if self.knots.saturating_add(count) > MAX_PATH_KNOTS { - false - } else { - self.knots += count; - true - } - } -} -/// A page's visible area and rotation, in PDF points. -#[derive(Clone, Copy)] -struct PageGeometry { - /// Displayed size (rotation applied): the size the raster is rendered into. - width_pt: f64, - height_pt: f64, - /// The crop box origin in unrotated PDF user space. - origin_x: f64, - origin_y: f64, - /// The crop box size in unrotated PDF user space. - crop_w: f64, - crop_h: f64, - /// Clockwise rotation the renderer applies: 0, 90, 180 or 270. - rotation: u16, -} - -/// The page's visible box and rotation. PDF page objects stay in unrotated user space, while the -/// raster is rendered through the crop box and the page's `/Rotate`, so editable layers must use -/// the same transform. +/// One page's raster width or height in pixels at `dpi`, at least one. #[cfg(not(target_arch = "wasm32"))] -fn page_geometry(page: &pdfium_render::prelude::PdfPage, page_number: usize) -> Result { - let width_pt = f64::from(page.width().value); - let height_pt = f64::from(page.height().value); - if width_pt <= 0.0 || height_pt <= 0.0 { - return Err(IoError::Unsupported(format!("PDF page {page_number} has no area"))); - } - let rotation = page.rotation().map(|r| r.as_degrees() as u16).unwrap_or(0); - // The page's effective box, as PDFium renders it: the bounding box (media box clipped to the - // crop box), not the raw crop box, which may extend past the media box. - let (origin_x, origin_y, crop_w, crop_h) = match page.boundaries().bounding().or_else(|_| page.boundaries().crop()).or_else(|_| page.boundaries().media()) { - Ok(boundary) => { - let r = boundary.bounds; - (f64::from(r.left().value), f64::from(r.bottom().value), f64::from(r.right().value - r.left().value), f64::from(r.top().value - r.bottom().value)) - } - Err(_) => (0.0, 0.0, width_pt, height_pt), - }; - // A malformed box falls back to the displayed size; 90 and 270 swap the axes. - let (crop_w, crop_h) = if crop_w > 0.0 && crop_h > 0.0 { - (crop_w, crop_h) - } else if rotation == 90 || rotation == 270 { - (height_pt, width_pt) - } else { - (width_pt, height_pt) - }; - Ok(PageGeometry { width_pt, height_pt, origin_x, origin_y, crop_w, crop_h, rotation }) +fn page_pixels(points: f64, dpi: f64) -> u32 { + (points * dpi / 72.0).round().max(1.0) as u32 } -/// One rendered page's frame: its geometry, DPI, document x, and the RGBA pixels. -struct PageFrame<'a> { - geometry: PageGeometry, - dpi: f64, - x: u32, - rgba: &'a [u8], - width: u32, - height: u32, -} - -impl PageFrame<'_> { - /// Maps a point in PDF page space to the page's own pixels: crop box, rotation and scale. - fn to_page_px(&self, x_pt: f32, y_pt: f32) -> (f64, f64) { - let g = &self.geometry; - let u = f64::from(x_pt) - g.origin_x; - let v = f64::from(y_pt) - g.origin_y; - let (dx, dy) = match g.rotation { - 90 => (v, u), - 180 => (g.crop_w - u, v), - 270 => (g.crop_h - v, g.crop_w - u), - _ => (u, g.crop_h - v), - }; - let scale = self.dpi / 72.0; - (dx * scale, dy * scale) - } - - /// Maps a point in PDF page space to document pixels: the page's own pixels plus its X offset. - fn to_doc(&self, x_pt: f32, y_pt: f32) -> (f64, f64) { - let (px, py) = self.to_page_px(x_pt, y_pt); - ((px + f64::from(self.x)).round(), py.round()) - } - - /// The text layer's transform at document pixel (`x`, `y`): the page rotation turns the text - /// layout too, so rotated pages get rotated editable text rather than upright text at a - /// rotated position. - fn text_transform(&self, x: f64, y: f64) -> Affine { - let (a, b, c, d) = match self.geometry.rotation { - 90 => (0.0, 1.0, -1.0, 0.0), - 180 => (-1.0, 0.0, 0.0, -1.0), - 270 => (0.0, -1.0, 1.0, 0.0), - _ => (1.0, 0.0, 0.0, 1.0), - }; - Affine { m: [a, b, c, d, x, y] } - } - - /// The rendered page's colour at local pixel (`x`, `y`), or black outside it. - fn color_at(&self, x: u32, y: u32) -> Color { - let i = (y as usize * self.width as usize + x as usize) * 4; - if i + 3 < self.rgba.len() && self.rgba[i + 3] > 0 { - Color::rgb(f32::from(self.rgba[i]) / 255.0, f32::from(self.rgba[i + 1]) / 255.0, f32::from(self.rgba[i + 2]) / 255.0) - } else { - Color::BLACK - } - } - - /// The ink colour of the text in `bounds` (page points). - /// - /// The box holds both glyphs and the page behind them, so sampling one corner usually finds - /// background or an antialiased edge. Take the pixel farthest from the box's most common - /// colour instead: for dark text on a light page that is a glyph core, and for light text on a - /// dark page it is the glyph rather than the background. - fn text_color(&self, left: f32, top: f32, right: f32, bottom: f32) -> Color { - // The box's four corners through the same rotation-aware mapping as the glyphs. - let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); - for (x, y) in [(left, bottom), (left, top), (right, top), (right, bottom)] { - let (px, py) = self.to_page_px(x, y); - x0 = x0.min(px); - x1 = x1.max(px); - y0 = y0.min(py); - y1 = y1.max(py); - } - let x0 = x0.floor().max(0.0) as u32; - let x1 = x1.ceil().clamp(0.0, f64::from(self.width)) as u32; - let y0 = y0.floor().max(0.0) as u32; - let y1 = y1.ceil().clamp(0.0, f64::from(self.height)) as u32; - if x1 <= x0 || y1 <= y0 { - return Color::BLACK; - } - // At most 4096 samples, so a page-sized text box stays cheap. - let step = ((f64::from(x1 - x0) * f64::from(y1 - y0) / 4096.0).sqrt().ceil() as u32).max(1); - let mut samples: Vec<[f32; 3]> = Vec::new(); - let mut buckets: std::collections::HashMap = std::collections::HashMap::new(); - let mut y = y0; - 'rows: while y < y1 { - let mut x = x0; - while x < x1 { - if samples.len() >= 4096 { - break 'rows; - } - let c = self.color_at(x, y); - let rgb = [c.c[0], c.c[1], c.c[2]]; - let key = (rgb[0] * 31.0) as u32 * 1024 + (rgb[1] * 31.0) as u32 * 32 + (rgb[2] * 31.0) as u32; - let entry = buckets.entry(key).or_insert((0, [0.0; 3])); - entry.0 += 1; - for (sum, v) in entry.1.iter_mut().zip(rgb) { - *sum += v; - } - samples.push(rgb); - x += step; - } - y += step; - } - let Some((_, (count, sum))) = buckets.iter().max_by_key(|(_, (count, _))| *count) else { return Color::BLACK }; - let mode = [sum[0] / *count as f32, sum[1] / *count as f32, sum[2] / *count as f32]; - let mut best = mode; - let mut best_distance = -1.0f32; - for rgb in samples { - let distance = (rgb[0] - mode[0]).powi(2) + (rgb[1] - mode[1]).powi(2) + (rgb[2] - mode[2]).powi(2); - if distance > best_distance { - best_distance = distance; - best = rgb; - } - } - Color::rgb(best[0], best[1], best[2]) - } -} - -/// Editable text and shape layers for one rendered page, in document pixels. +/// The highest DPI not above `requested` that keeps every page inside the renderer's side and +/// pixel bounds and the whole strip inside `max_union_pixels`. Rendering at that DPI keeps each +/// page's physical size unchanged; unreachable bounds report 1 DPI and the render call then fails +/// with a clear message. #[cfg(not(target_arch = "wasm32"))] -fn object_layers( - page: &pdfium_render::prelude::PdfPage, - opts: &ImportOptions, - frame: &PageFrame, - ctl: &Interrupt, - budget: &mut ObjectBudget, -) -> Result<(Vec, bool), IoError> { - use pdfium_render::prelude::*; - - let objects = page.objects(); - let mut layers = Vec::new(); - let mut truncated = false; - 'objects: for object in objects.iter() { - if budget.layers >= MAX_OBJECT_LAYERS { - truncated = true; - break; - } - if ctl.check().is_err() { - return Err(IoError::Cancelled); - } - match object { - PdfPageObject::Text(text) if opts.pdf_text => { - let content = text.text(); - if content.trim().is_empty() { - continue; - } - let Ok(bounds) = text.bounds() else { continue }; - let (x_px, y_px) = frame.to_doc(bounds.left().value, bounds.top().value); - // The text layer's size is in points; the transform is in document pixels. - // The text object does not expose its fill colour; sample the glyph ink from the - // page. The font is matched by family/name, not embedded: a document font that is - // not installed renders with the closest family the text engine has. - let color = frame.text_color(bounds.left().value, bounds.top().value, bounds.right().value, bounds.bottom().value); - let size_pt = f64::from(text.scaled_font_size().value).max(1.0); - let font = text.font(); - let family = if font.family().is_empty() { font.name() } else { font.family() }; - let mut layer = Layer::new( - "Text", - LayerContent::Text(TextLayer { - text: content, - font_family: family, - size_pt: size_pt as f32, - color, - transform: frame.text_transform(x_px, y_px), - ..Default::default() - }), - ); - if !text.is_visible() { - layer.visible = false; - } - if !budget.claim_layer() { - truncated = true; - break 'objects; - } - layers.push(layer); +fn effective_dpi(requested: f64, sizes: &[(f64, f64)], max_side: u64, max_page_pixels: u64, max_union_pixels: u64) -> f64 { + let mut dpi = requested.clamp(1.0, 2400.0); + loop { + let mut union = 0u64; + let mut fits = true; + for &(width_pt, height_pt) in sizes { + let width = u64::from(page_pixels(width_pt, dpi)); + let height = u64::from(page_pixels(height_pt, dpi)); + if width > max_side || height > max_side || width.saturating_mul(height) > max_page_pixels { + fits = false; + break; } - PdfPageObject::Path(path) if opts.pdf_vectors => { - // PDFium reports the segments in object space; the object's matrix places them on - // the page. Without it, scaled or rotated paths land in the wrong place. - let matrix = path.matrix().unwrap_or(PdfMatrix::IDENTITY); - // The fill and stroke modes are exposed; the colours, stroke width and dash - // pattern are not, so both paints are black and a stroke is 1 pt wide. - let filled = !matches!(path.fill_mode(), Ok(PdfPathFillMode::None)); - let stroked = path.is_stroked().unwrap_or(false); - if !filled && !stroked { - continue; - } - let mut subpaths: Vec = Vec::new(); - let mut knots: Vec = Vec::new(); - let mut closed = false; - let mut bezier: Vec<(f64, f64)> = Vec::new(); - for segment in path.segments().transform(matrix).iter() { - let point = || frame.to_doc(segment.x().value, segment.y().value); - match segment.segment_type() { - PdfPathSegmentType::MoveTo => { - if !knots.is_empty() { - subpaths.push(Subpath { closed, knots: std::mem::take(&mut knots), op: PathOp::Combine }); - closed = false; - } - if !budget.claim_knots(1) { - truncated = true; - break 'objects; - } - let (px, py) = point(); - knots.push(Knot::corner(px, py)); - } - PdfPathSegmentType::LineTo => { - if !budget.claim_knots(1) { - truncated = true; - break 'objects; - } - let (px, py) = point(); - knots.push(Knot::corner(px, py)); - } - PdfPathSegmentType::BezierTo => { - // PDF draws a cubic Bézier as three consecutive BezierTo points: the - // two control points, then the end point. - bezier.push(point()); - if bezier.len() == 3 { - let ((c1x, c1y), (c2x, c2y), (ex, ey)) = (bezier[0], bezier[1], bezier[2]); - if let Some(prev) = knots.last_mut() { - prev.out_ctrl = Point::new(c1x, c1y); - } - if !budget.claim_knots(1) { - truncated = true; - break 'objects; - } - knots.push(Knot::smooth(Point::new(ex, ey), Point::new(c2x, c2y), Point::new(ex, ey))); - bezier.clear(); - } - } - PdfPathSegmentType::Unknown => {} - } - // A closing segment can also be the endpoint that closes a Bézier; process it - // above before marking the subpath closed so its control points are consumed. - if segment.is_close() { - closed = true; - } - } - if !knots.is_empty() { - subpaths.push(Subpath { closed, knots, op: PathOp::Combine }); - } - if subpaths.is_empty() { - continue; - } - let stroke = stroked.then(|| ShapeStroke { paint: Fill::Solid(Color::BLACK), width: 1.0, ..Default::default() }); - if !budget.claim_layer() { - truncated = true; - break 'objects; - } - layers.push(Layer::new( - "Path", - LayerContent::Shape(ShapeLayer { - path: Path::new(subpaths), - fill: filled.then_some(Fill::Solid(Color::BLACK)), - stroke, - ..Default::default() - }), - )); - } - _ => {} + union = union.saturating_add(width.saturating_mul(height)); } + if fits && union <= max_union_pixels { + return dpi; + } + if dpi <= 1.0 { + return 1.0; + } + // The strip's gaps contribute a constant width, so a geometric step converges without + // needing a closed form per page. + dpi = (dpi * 0.9).max(1.0); } - Ok((layers, truncated)) } -/// The highest DPI not above `requested` that keeps every page and the artboard strip within -/// their pixel budgets. Rendering at that DPI keeps each page's physical size unchanged. +/// Maps a craft-pdf open failure to the importer's error. #[cfg(not(target_arch = "wasm32"))] -fn effective_dpi(requested: f64, sizes: &[(f64, f64)], gap: u32, max_page: f64, max_union: u64) -> f64 { - let mut dpi = requested; - for (w, h) in sizes { - dpi = dpi.min(72.0 * (max_page / (w * h)).sqrt()); +fn open_error(error: craft_pdf::OpenError) -> IoError { + use craft_pdf::OpenError; + match error { + OpenError::InputLimit { limit } => IoError::Unsupported(format!("PDF is larger than the {limit}-byte input limit")), + OpenError::Allocation => IoError::Unsupported("PDF needs more memory than is available".into()), + OpenError::BackendPanic => IoError::Unsupported("PDF reader failed on this file; it may be damaged".into()), + OpenError::Load(error) => IoError::Unsupported(format!("PDF: {error:?}")), } - let n = sizes.len() as f64; - let sum_w: f64 = sizes.iter().map(|(w, _)| w).sum(); - let max_h = sizes.iter().map(|(_, h)| h).fold(0.0_f64, |a, &h| a.max(h)); - // (sum_w * k + gaps) * (max_h * k) <= max_union, where k = dpi / 72: solve a k² + b k - c = 0. - let gaps = f64::from(gap) * (n - 1.0); - let a = sum_w * max_h; - let b = gaps * max_h; - let k = if a > 0.0 { (-b + (b * b + 4.0 * a * max_union as f64).sqrt()) / (2.0 * a) } else { f64::INFINITY }; - dpi.min(72.0 * k).max(1.0) } -/// Loads the PDFium shared library from the executable's folder (`PDFIUM_DIR` overrides it). -/// -/// pdfium-render keeps the bindings in a process-wide static: the first import initializes them -/// and later `bind_to_library` calls fail with `PdfiumLibraryBindingsAlreadyInitialized`. Remember -/// the outcome and reuse the initialized bindings, so opening a second PDF in one session works. +/// Maps a craft-pdf render failure to the importer's error. #[cfg(not(target_arch = "wasm32"))] -fn bind() -> Result { - use pdfium_render::prelude::Pdfium; - - static INIT: std::sync::OnceLock> = std::sync::OnceLock::new(); - let init = INIT.get_or_init(|| { - let dir = std::env::var_os("PDFIUM_DIR") - .map(std::path::PathBuf::from) - .unwrap_or_else(|| std::env::current_exe().ok().and_then(|exe| exe.parent().map(std::path::Path::to_path_buf)).unwrap_or_default()); - let library = Pdfium::pdfium_platform_library_name_at_path(&dir); - let platform = Pdfium::pdfium_platform_library_name().to_string_lossy().into_owned(); - match Pdfium::bind_to_library(&library) { - Ok(bindings) => { - // Initializes the library inside pdfium-render's process-wide bindings. - drop(Pdfium::new(bindings)); - Ok(()) - } - Err(e) => Err(format!( - "PDF import: cannot load PDFium from {} ({e}); put {platform} next to the executable or set PDFIUM_DIR, then restart the application", - library.display() - )), - } - }); - match init { - // The bindings are already initialized; `default()` re-uses them. - Ok(()) => Ok(Pdfium::default()), - Err(message) => Err(IoError::Unsupported(message.clone())), - } -} - -#[cfg(test)] -mod tests { - use super::{MAX_OBJECT_LAYERS, MAX_PATH_KNOTS, ObjectBudget, PageFrame, PageGeometry}; - - /// A 595 x 842 pt page with no offset, rotated by `rotation` degrees. - fn geometry(rotation: u16) -> PageGeometry { - PageGeometry { width_pt: 595.0, height_pt: 842.0, origin_x: 0.0, origin_y: 0.0, crop_w: 595.0, crop_h: 842.0, rotation } - } - - /// A full-page frame at `dpi`, starting at document x `x`. - fn frame(dpi: f64, x: u32) -> PageFrame<'static> { - PageFrame { geometry: geometry(0), dpi, x, rgba: &[], width: 595, height: 842 } - } - - #[test] - /// Page points map through the DPI scale, the Y flip and the page's document X offset. - fn page_points_map_to_document_pixels() { - assert_eq!(frame(72.0, 0).to_doc(60.0, 420.0), (60.0, 422.0)); - // The same point at four times the resolution. - assert_eq!(frame(300.0, 0).to_doc(60.0, 420.0), (250.0, 1758.0)); - // Page 2 starts after page 1's width: the document X offset is part of the mapping. - assert_eq!(frame(300.0, 2480).to_doc(60.0, 420.0), (2730.0, 1758.0)); - } - - #[test] - /// The document-wide budget refuses layers and knots once its limits are reached. - fn object_budget_stops_at_its_limits() { - let mut budget = ObjectBudget::default(); - for _ in 0..MAX_OBJECT_LAYERS { - assert!(budget.claim_layer()); - } - assert!(!budget.claim_layer()); - let mut knots = ObjectBudget::default(); - assert!(knots.claim_knots(MAX_PATH_KNOTS)); - assert!(!knots.claim_knots(1)); - assert!(!knots.claim_knots(usize::MAX)); - } - #[test] - /// Crop-box offsets and 90/180/270 rotations land where the raster renders them. - fn crop_box_offsets_and_rotations_map_like_the_raster() { - // A 200 x 100 pt crop box at (10, 20), displayed rotated 90 degrees clockwise: 100 x 200. - let rotated = |rotation| PageFrame { - geometry: PageGeometry { width_pt: 100.0, height_pt: 200.0, origin_x: 10.0, origin_y: 20.0, crop_w: 200.0, crop_h: 100.0, rotation }, - dpi: 72.0, - x: 0, - rgba: &[], - width: 100, - height: 200, - }; - // At 72 dpi the rectangle (20, 30)..(60, 70) lands at (10, 10)..(50, 50). - assert_eq!(rotated(90).to_doc(20.0, 30.0), (10.0, 10.0)); - assert_eq!(rotated(90).to_doc(60.0, 70.0), (50.0, 50.0)); - // 180 mirrors X; 270 swaps the axes back. - assert_eq!(rotated(180).to_doc(20.0, 30.0), (190.0, 10.0)); - assert_eq!(rotated(270).to_doc(20.0, 30.0), (90.0, 190.0)); - // The page's document X offset is added after the page-space mapping. - let mut offset = rotated(90); - offset.x = 500; - assert_eq!(offset.to_doc(20.0, 30.0), (510.0, 10.0)); - } - - #[test] - /// The page sampler reads the requested pixel and reports black outside the page. - fn samples_the_rendered_page() { - // Two pixels: white then black. - let rgba = [255u8, 255, 255, 255, 0, 0, 0, 255]; - let page = PageFrame { - geometry: PageGeometry { width_pt: 2.0, height_pt: 1.0, origin_x: 0.0, origin_y: 0.0, crop_w: 2.0, crop_h: 1.0, rotation: 0 }, - dpi: 72.0, - x: 0, - rgba: &rgba, - width: 2, - height: 1, - }; - assert_eq!(page.color_at(0, 0), photocraft_doc::Color::rgb(1.0, 1.0, 1.0)); - assert_eq!(page.color_at(1, 0), photocraft_doc::Color::BLACK); - assert_eq!(page.color_at(2, 0), photocraft_doc::Color::BLACK); - } - - #[test] - /// Glyph ink wins over the background inside a text box, while an empty box keeps background. - fn text_colour_samples_the_glyph_ink() { - // An 8 x 4 white page with one black glyph pixel at (2, 1). - let mut rgba = vec![255u8; 8 * 4 * 4]; - let glyph = (8 + 2) * 4; - rgba[glyph..glyph + 3].fill(0); - let page = PageFrame { - geometry: PageGeometry { width_pt: 8.0, height_pt: 4.0, origin_x: 0.0, origin_y: 0.0, crop_w: 8.0, crop_h: 4.0, rotation: 0 }, - dpi: 72.0, - x: 0, - rgba: &rgba, - width: 8, - height: 4, - }; - // The whole page box contains the glyph: the ink wins over the white background. - assert_eq!(page.text_color(0.0, 4.0, 8.0, 0.0), photocraft_doc::Color::BLACK); - // A box that contains only background keeps the background colour. - assert_eq!(page.text_color(4.0, 4.0, 8.0, 2.0), photocraft_doc::Color::rgb(1.0, 1.0, 1.0)); +fn render_error(page: usize, dpi: f64, error: raster::Error) -> IoError { + use raster::Error; + match error { + Error::Cancelled => IoError::Cancelled, + Error::OutputLimit => IoError::Unsupported(format!("PDF page {page} is too large at {dpi:.0} dpi; lower the import DPI")), + Error::InvalidPage => IoError::Unsupported(format!("PDF page {page} has an empty or invalid page box")), + Error::Allocation => IoError::Unsupported(format!("PDF page {page} needs more memory than is available")), + Error::BackendPanic => IoError::Unsupported(format!("PDF renderer failed on page {page}; it may be damaged")), + Error::InvalidOptions | Error::BufferLength => IoError::Unsupported(format!("PDF page {page} could not be rendered")), } } diff --git a/crates/io/tests/it/pdf_import.rs b/crates/io/tests/it/pdf_import.rs index ef02111309a..f63ff194820 100644 --- a/crates/io/tests/it/pdf_import.rs +++ b/crates/io/tests/it/pdf_import.rs @@ -1,239 +1,26 @@ -//! PDF import end-to-end through PDFium. +//! PDF import end-to-end through craft-pdf (pure Rust, no shared library). //! -//! A synthetic two-page PDF with non-origin red text, a transformed blue rectangle and green text -//! is imported at 72 and 300 DPI, and the resulting editable layers are checked against the -//! fixture's geometry and pixels. PDFium is loaded at run time: when it is unavailable (no -//! `PDFIUM_DIR`, no DLL beside the test binary) the test prints an explicit SKIPPED line and -//! returns instead of pretending the end-to-end wiring passed. +//! A six-page synthetic PDF (plain, CropBox offset, rotations 90/180/270 and an oversized +//! CropBox) imports at 72 and 300 DPI as one artboard per page, with the page's print size kept, +//! 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 lopdf::{Document as PdfDocument, Object, Stream, dictionary}; -use pdfium_render::prelude::{PdfRenderConfig, Pdfium}; -use photocraft_doc::{Color, Document, Layer, LayerContent, ShapeLayer, TextLayer}; +use photocraft_doc::LayerContent; use photocraft_geom::Rect; -use photocraft_io::{ImportOptions, ImportResult, IoError, import_with_options_and_interrupt}; +use photocraft_io::{ImportOptions, IoError, import_with_options_and_interrupt}; use photocraft_raster::Interrupt; const PAGE_W: f64 = 200.0; const PAGE_H: f64 = 100.0; -const GAP: f64 = 80.0; -/// Imports the four-page fixture at 72 and 300 DPI and checks every layer it produces. -#[test] -fn imports_text_and_a_transformed_path_on_two_pages() { - let pdf = three_page_pdf(); - for dpi in [72.0f32, 300.0] { - let options = ImportOptions { pdf_dpi: dpi, ..Default::default() }; - let result = match import_with_options_and_interrupt("fixture.pdf", &pdf, &options, &photocraft_raster::Interrupt::NONE) { - Ok(result) => result, - Err(IoError::Unsupported(message)) if message.contains("cannot load PDFium") => { - eprintln!("SKIPPED the PDF import end-to-end test: PDFium is unavailable ({message})"); - // The Windows integration leg provisions PDFium and sets this: there a missing - // library must fail rather than let the runner report an unreached pass. - assert!(std::env::var_os("PHOTOCRAFT_REQUIRE_PDFIUM").is_none(), "PDFium is required for this test but could not load: {message}"); - return; - } - Err(error) => panic!("PDF import failed at {dpi} dpi: {error}"), - }; - check(&result.document, dpi); - eprintln!("PDF import executed at {dpi} dpi: {} page groups, layer checks passed", result.document.layers.len()); - } -} - -/// Page 1: red 48 pt text at (20, 50). Page 2: a 20 x 10 pt rectangle scaled 2x and moved by -/// (10, 5) - corners (30, 25)..(70, 45) - plus green 48 pt text at (20, 20). Page 3: a crop box -/// offset to (10, 20, 210, 120) and rotated 90 degrees clockwise, with a 40 x 40 pt rectangle at -/// (20, 30)..(60, 70) that renders at (10, 10)..(50, 50) on a 100 x 200 page. -fn three_page_pdf() -> Vec { - let mut pdf = PdfDocument::with_version("1.5"); - let pages_id = pdf.new_object_id(); - let font_id = pdf.add_object(dictionary! { - "Type" => "Font", - "Subtype" => "Type1", - "BaseFont" => "Helvetica", - }); - let resources = pdf.add_object(dictionary! { - "Font" => dictionary! { "F1" => font_id }, - }); - let pages = [ - ("1 0 0 rg BT /F1 48 Tf 20 50 Td (Red) Tj ET", [0.0f32, 0.0, PAGE_W as f32, PAGE_H as f32], None, None), - ("0 0 1 rg q 2 0 0 2 10 5 cm 10 10 20 10 re f Q 0 1 0 rg BT /F1 48 Tf 20 20 Td (Green) Tj ET", [0.0, 0.0, PAGE_W as f32, PAGE_H as f32], None, None), - ("0 0 1 rg 20 30 40 40 re f 0 0.5 0 rg BT /F1 24 Tf 40 60 Td (Rot) Tj ET", [10.0, 20.0, 210.0, 120.0], Some(90i64), None), - // A CropBox larger than the MediaBox: the rendered page and the mapping use the - // intersection, so the rectangle must not be offset by the crop box's negative origin. - ("0 0.5 0 rg 20 30 40 40 re f", [0.0, 0.0, PAGE_W as f32, PAGE_H as f32], None, Some([-50.0f32, -50.0, 250.0, 150.0])), - ]; - let mut kids = Vec::new(); - for (content, [left, bottom, right, top], rotate, crop) in pages { - let content_id = pdf.add_object(Stream::new(dictionary! {}, content.as_bytes().to_vec())); - let mut page = dictionary! { - "Type" => "Page", - "Parent" => pages_id, - "MediaBox" => Object::Array(vec![Object::Real(left), Object::Real(bottom), Object::Real(right), Object::Real(top)]), - "Contents" => content_id, - "Resources" => resources, - }; - if let Some(rotate) = rotate { - page.set("Rotate", rotate); - } - if let Some([left, bottom, right, top]) = crop { - page.set("CropBox", Object::Array(vec![Object::Real(left), Object::Real(bottom), Object::Real(right), Object::Real(top)])); - } - let page_id = pdf.add_object(page); - kids.push(Object::Reference(page_id)); - } - let count = kids.len() as i64; - pdf.objects.insert( - pages_id, - Object::Dictionary(dictionary! { - "Type" => "Pages", - "Kids" => Object::Array(kids), - "Count" => count, - }), - ); - 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).expect("writing the PDF fixture"); - bytes -} - -/// Asserts the imported text and path layers at one DPI against the fixture geometry. -fn check(document: &Document, dpi: f32) { - let scale = f64::from(dpi) / 72.0; - let page_two_x = (PAGE_W * scale).round() + GAP; - - // Page 1: the editable text keeps its position and takes the red ink from the page. - let text = text_layer(page_children(document, 1)); - assert_red(&text.color, "page 1 text"); - let x = text.transform.m[4]; - let y = text.transform.m[5]; - assert!((x - 20.0 * scale).abs() < 8.0 * scale, "page 1 text x is {x} at {dpi} dpi"); - // 48 pt Helvetica's bounds top is about 35 pt above the baseline at y = 50. - assert!((y - 15.0 * scale).abs() < 20.0 * scale, "page 1 text y is {y} at {dpi} dpi"); - - // Page 2: the transformed rectangle lands at (30, 25)..(70, 45) plus the page's document X. - let shape = shape_layer(page_children(document, 2)); - let (mut min_x, mut min_y, mut max_x, mut max_y) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); - for knot in shape.path.subpaths.iter().flat_map(|subpath| &subpath.knots) { - min_x = min_x.min(knot.anchor.x); - max_x = max_x.max(knot.anchor.x); - min_y = min_y.min(knot.anchor.y); - max_y = max_y.max(knot.anchor.y); - } - assert!((min_x - (page_two_x + 30.0 * scale)).abs() < 4.0, "path min x is {min_x}, page 2 starts at {page_two_x} ({dpi} dpi)"); - assert!((max_x - (page_two_x + 70.0 * scale)).abs() < 4.0, "path max x is {max_x} ({dpi} dpi)"); - assert!((min_y - (PAGE_H - 45.0) * scale).abs() < 4.0, "path min y is {min_y} ({dpi} dpi)"); - assert!((max_y - (PAGE_H - 25.0) * scale).abs() < 4.0, "path max y is {max_y} ({dpi} dpi)"); - - let text = text_layer(page_children(document, 2)); - assert_green(&text.color, "page 2 text"); - assert!(text.transform.m[4] > page_two_x + 10.0 * scale, "page 2 text x misses the page offset: {} <= {page_two_x}", text.transform.m[4]); - - // Page 3: the crop box (10, 20, 210, 120) and /Rotate 90 put the rectangle at (10..50, 10..50). - let shape = shape_layer(page_children(document, 3)); - let (mut min_x, mut min_y, mut max_x, mut max_y) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); - for knot in shape.path.subpaths.iter().flat_map(|subpath| &subpath.knots) { - min_x = min_x.min(knot.anchor.x); - max_x = max_x.max(knot.anchor.x); - min_y = min_y.min(knot.anchor.y); - max_y = max_y.max(knot.anchor.y); - } - let page_three_x = 2.0 * (PAGE_W * scale).round() + 2.0 * GAP; - assert!((min_x - (page_three_x + 10.0 * scale)).abs() < 3.0, "rotated path min x is {min_x}, page 3 starts at {page_three_x} ({dpi} dpi)"); - assert!((max_x - (page_three_x + 50.0 * scale)).abs() < 3.0, "rotated path max x is {max_x} ({dpi} dpi)"); - assert!((min_y - 10.0 * scale).abs() < 3.0, "rotated path min y is {min_y} ({dpi} dpi)"); - assert!((max_y - 50.0 * scale).abs() < 3.0, "rotated path max y is {max_y} ({dpi} dpi)"); - - // Rotated text: the layer's transform carries the 90 degree turn, not just its position. - let text = text_layer(page_children(document, 3)); - let m = text.transform.m; - assert!(m[0].abs() < 0.01 && (m[1] - 1.0).abs() < 0.01 && (m[2] + 1.0).abs() < 0.01 && m[3].abs() < 0.01, "page 3 text rotation is {m:?}"); - assert!(m[4] > page_three_x, "page 3 text x misses the page offset: {} <= {page_three_x}", m[4]); - assert!(text.color.c[1] > 0.3 && text.color.c[0] < 0.2 && text.color.c[2] < 0.2, "page 3 text should be green, got {:?}", text.color.c); - - // Page 4: a CropBox (-50, -50, 250, 150) around a 200 x 100 MediaBox must not offset the rect. - let shape = shape_layer(page_children(document, 4)); - let (mut min_x, mut min_y, mut max_x, mut max_y) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); - for knot in shape.path.subpaths.iter().flat_map(|subpath| &subpath.knots) { - min_x = min_x.min(knot.anchor.x); - max_x = max_x.max(knot.anchor.x); - min_y = min_y.min(knot.anchor.y); - max_y = max_y.max(knot.anchor.y); - } - // Page 3 is rotated 90 degrees, so it is 100 pt wide on the strip, not 200. - let page_four_x = 2.0 * (PAGE_W * scale).round() + (100.0 * scale).round() + 3.0 * GAP; - assert!((min_x - (page_four_x + 20.0 * scale)).abs() < 3.0, "oversized-crop path min x is {min_x}, page 4 starts at {page_four_x} ({dpi} dpi)"); - assert!((max_x - (page_four_x + 60.0 * scale)).abs() < 3.0, "oversized-crop path max x is {max_x} ({dpi} dpi)"); - assert!((min_y - 30.0 * scale).abs() < 3.0, "oversized-crop path min y is {min_y} ({dpi} dpi)"); - assert!((max_y - 70.0 * scale).abs() < 3.0, "oversized-crop path max y is {max_y} ({dpi} dpi)"); -} - -/// The layer children of the imported `Page N` group. -fn page_children(document: &Document, page: usize) -> &[Layer] { - let name = format!("Page {page}"); - let layer = document.layers.iter().find(|layer| layer.name == name).unwrap_or_else(|| panic!("no {name} layer")); - match &layer.content { - LayerContent::Group(group) => &group.children, - _ => panic!("{name} is not a group"), - } -} - -/// The first text layer among `children`. -fn text_layer(children: &[Layer]) -> &TextLayer { - children - .iter() - .find_map(|layer| match &layer.content { - LayerContent::Text(text) => Some(text), - _ => None, - }) - .expect("a text layer") -} - -/// The first shape layer among `children`. -fn shape_layer(children: &[Layer]) -> &ShapeLayer { - children - .iter() - .find_map(|layer| match &layer.content { - LayerContent::Shape(shape) => Some(shape), - _ => None, - }) - .expect("a shape layer") -} - -/// Asserts `color` is the fixture's red ink. -fn assert_red(color: &Color, what: &str) { - assert!(color.c[0] > 0.8 && color.c[1] < 0.2 && color.c[2] < 0.2, "{what} should be red, got {:?}", color.c); -} - -/// Asserts `color` is the fixture's green ink. -fn assert_green(color: &Color, what: &str) { - assert!(color.c[1] > 0.8 && color.c[0] < 0.2 && color.c[2] < 0.2, "{what} should be green, got {:?}", color.c); -} - -/// Imports `bytes`, or prints SKIPPED and returns `None` when PDFium cannot load. The Windows -/// integration leg sets `PHOTOCRAFT_REQUIRE_PDFIUM`, where a missing library must fail. -fn imported_or_skipped(bytes: &[u8], options: &ImportOptions, ctl: &Interrupt<'_>, what: &str) -> Option { - match import_with_options_and_interrupt("probe.pdf", bytes, options, ctl) { - Ok(result) => Some(result), - Err(IoError::Unsupported(message)) if message.contains("cannot load PDFium") => { - eprintln!("SKIPPED {what}: PDFium is unavailable ({message})"); - assert!(std::env::var_os("PHOTOCRAFT_REQUIRE_PDFIUM").is_none(), "PDFium is required for {what} but could not load: {message}"); - None - } - Err(error) => panic!("{what} failed: {error}"), - } -} - -/// Six one-page variants for the cancellation and fidelity probes: plain, a CropBox offset to -/// (10, 20, 210, 120), rotations of 90, 180 and 270 degrees, and an oversized CropBox -/// (-50, -50, 250, 150) around the 200 x 100 MediaBox. Each page draws a 40 x 40 blue rectangle -/// and a 10 x 10 red one at (20, 30). +/// Six one-page variants: plain, CropBox offset to (10, 20, 210, 120), rotations of 90/180/270 +/// degrees and an oversized CropBox (-50, -50, 250, 150) around the 200 x 100 MediaBox. Each page +/// draws a 40 x 40 blue rectangle at (20, 30) in PDF space. fn variant_pdf() -> Vec { - let mut pdf = PdfDocument::with_version("1.5"); - let pages_id = pdf.new_object_id(); let pages: [(Option, Option<[f32; 4]>); 6] = [ (None, None), (None, Some([10.0, 20.0, 210.0, 120.0])), @@ -242,9 +29,11 @@ fn variant_pdf() -> Vec { (Some(270), None), (None, Some([-50.0, -50.0, 250.0, 150.0])), ]; + let mut pdf = PdfDocument::with_version("1.5"); + let pages_id = pdf.new_object_id(); let mut kids = Vec::new(); for (rotate, crop) in pages { - let content = b"0 0 1 rg 20 30 40 40 re f 1 0 0 rg 20 30 10 10 re f"; + let content = b"0 0 1 rg 20 30 40 40 re f"; let content_id = pdf.add_object(Stream::new(dictionary! {}, content.to_vec())); let mut page = dictionary! { "Type" => "Page", @@ -277,8 +66,102 @@ fn variant_pdf() -> Vec { bytes } -/// A cancel that lands on the last object's check, or on the public boundary after -/// `import_stages`, must be reported as `Cancelled` rather than returning a document. +/// One page of `width` x `height` points with the same blue rectangle. +fn one_page_pdf(width: f32, height: f32) -> Vec { + let mut pdf = PdfDocument::with_version("1.5"); + let pages_id = pdf.new_object_id(); + let content_id = pdf.add_object(Stream::new(dictionary! {}, b"0 0 1 rg 20 30 40 40 re f".to_vec())); + 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(width), Object::Real(height)]), + "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).expect("writing the page PDF"); + bytes +} + +/// The first artboard rectangle of `document`. +fn first_artboard(document: &photocraft_doc::Document) -> Rect { + let layer = document.layers.first().expect("an imported page group"); + let group = match &layer.content { + LayerContent::Group(group) => group, + _ => panic!("{} is not a group", layer.name), + }; + group.artboard.as_ref().expect("page artboard").rect +} + +#[test] +fn imports_every_page_as_an_artboard_with_its_print_size() { + let pdf = variant_pdf(); + for dpi in [72.0f32, 300.0] { + let options = ImportOptions { pdf_dpi: dpi, ..Default::default() }; + let result = import_with_options_and_interrupt("variants.pdf", &pdf, &options, &Interrupt::NONE).expect("PDF import"); + assert_eq!(result.document.layers.len(), 6, "one artboard per page at {dpi} dpi"); + let mut top_left = 0i32; + for (index, layer) in result.document.layers.iter().enumerate() { + let group = match &layer.content { + LayerContent::Group(group) => group, + _ => panic!("{} is not a page group", layer.name), + }; + let artboard = group.artboard.as_ref().expect("page artboard").rect; + let expected = match index { + // CropBox [10, 20, 210, 120] intersected with the MediaBox is 190 x 80 points. + 1 => (190.0, 80.0), + // Rotations 90 and 270 swap the axes. + 2 | 4 => (100.0, 200.0), + _ => (200.0, 100.0), + }; + let print_width = f64::from(artboard.width()) * 72.0 / f64::from(dpi); + let print_height = f64::from(artboard.height()) * 72.0 / f64::from(dpi); + assert!((print_width - expected.0).abs() < 1.0, "page {} width is {print_width:.1} pt, expected {} at {dpi} dpi", index + 1, expected.0); + assert!((print_height - expected.1).abs() < 1.0, "page {} height is {print_height:.1} pt, expected {} at {dpi} dpi", index + 1, expected.1); + assert_eq!(artboard.x0, top_left, "pages lay out side by side from x=0"); + top_left = artboard.x1 + 80; + let surface = group.children.first().and_then(|layer| layer.surface()).expect("page raster layer"); + if index == 0 { + // The rectangle's centre in PDF space is (40, 50); at the document's top-left + // origin that is y = PAGE_H - 50. + let scale = f64::from(dpi) / 72.0; + let x = artboard.x0 + (40.0 * scale).round() as i32; + let y = ((PAGE_H - 50.0) * scale).round() as i32; + let mut pixel = [[0u8; 4]; 1]; + surface.read_rgba8_into(Rect::from_xywh(x, y, 1, 1), &mut pixel); + assert!(pixel[0][2] > 120 && pixel[0][0] < 120, "page 1 should be blue inside the rectangle, got {:?}", pixel[0]); + let mut background = [[0u8; 4]; 1]; + surface.read_rgba8_into(Rect::from_xywh(artboard.x0 + 2, 2, 1, 1), &mut background); + assert!(background[0][0] > 240 && background[0][1] > 240 && background[0][2] > 240, "page background should be white, got {:?}", background[0]); + } + } + } +} + +#[test] +fn huge_pages_lower_the_effective_dpi_within_the_renderer_bounds() { + // 3000 pt at 300 dpi would be 12500 px wide, over craft-pdf's 8192 px side limit. + let pdf = one_page_pdf(3000.0, 100.0); + let options = ImportOptions { pdf_dpi: 300.0, ..Default::default() }; + let result = import_with_options_and_interrupt("wide.pdf", &pdf, &options, &Interrupt::NONE).expect("PDF import"); + assert!(result.warnings.iter().any(|warning| warning.contains("rendered at")), "warnings: {:?}", result.warnings); + let artboard = first_artboard(&result.document); + assert!(artboard.width() <= 8192, "width {} is over the renderer's side limit", artboard.width()); + assert!(result.document.resolution_dpi < 300.0, "the effective DPI should be lowered"); + let print_width = f64::from(artboard.width()) * 72.0 / f64::from(result.document.resolution_dpi); + assert!((print_width - 3000.0).abs() < 1.0, "print width {print_width:.1} pt should stay 3000 pt"); +} + #[test] fn cancelling_on_the_last_checks_is_reported() { let pdf = variant_pdf(); @@ -289,17 +172,16 @@ fn cancelling_on_the_last_checks_is_reported() { false }; let ctl = Interrupt::cancel_only(&cancel); - if imported_or_skipped(&pdf, &options, &ctl, "the last-check cancellation test").is_none() { - return; - } + 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 per-object check", total - 1), ("the public boundary check", 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("probe.pdf", &pdf, &options, &ctl); + 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 { @@ -310,52 +192,3 @@ fn cancelling_on_the_last_checks_is_reported() { assert!(elapsed < Duration::from_secs(10), "cancelling on {label} took {elapsed:?}"); } } - -/// Every imported page's stored raster must equal a direct PDFium render of the same page at the -/// same target width: crop intersection, rotation and the strip placement may not move or resample -/// a pixel. At 72, 150 and 300 DPI over the six variants that is 18 page renders. -#[test] -fn raster_matches_a_direct_pdfium_render() { - let pdf = variant_pdf(); - let mut compared = 0; - for dpi in [72.0f32, 150.0, 300.0] { - let options = ImportOptions { pdf_dpi: dpi, ..Default::default() }; - let Some(result) = imported_or_skipped(&pdf, &options, &Interrupt::NONE, "the raster fidelity matrix") else { - return; - }; - let pdfium = Pdfium::default(); - let reference = pdfium.load_pdf_from_byte_slice(&pdf, None).expect("reference PDF"); - assert_eq!(reference.pages().len() as usize, result.document.layers.len(), "page count at {dpi} dpi"); - for (index, layer) in result.document.layers.iter().enumerate() { - let group = match &layer.content { - LayerContent::Group(group) => group, - _ => panic!("page layer {} is not a group", layer.name), - }; - let artboard = group.artboard.as_ref().expect("page artboard").rect; - let raster = group.children.first().and_then(|layer| layer.surface()).expect("page raster layer"); - let (width, height) = (artboard.width(), artboard.height()); - let mut got = vec![[0u8; 4]; (width as usize) * (height as usize)]; - raster.read_rgba8_into(Rect::from_xywh(artboard.x0, artboard.y0, width, height), &mut got); - - let page = reference.pages().get(index as i32).expect("reference page"); - let bitmap = page.render_with_config(&PdfRenderConfig::new().set_target_width(width as i32)).expect("reference render"); - assert_eq!((bitmap.width() as u32, bitmap.height() as u32), (width, height), "page {} size at {dpi} dpi", index + 1); - let want = bitmap.as_rgba_bytes(); - - let mut max_diff = 0u32; - let mut sum = 0u64; - for (pixel, reference) in got.iter().zip(want.as_chunks::<4>().0.iter()) { - for channel in 0..4 { - let diff = (pixel[channel] as i32 - reference[channel] as i32).unsigned_abs(); - sum += u64::from(diff); - max_diff = max_diff.max(diff); - } - } - let channels = u64::from(width) * u64::from(height) * 4; - let mean = sum as f64 / channels as f64; - assert!(max_diff <= 1, "page {} at {dpi} dpi differs from the direct render: max channel diff {max_diff}, mean {mean:.4}", index + 1); - compared += 1; - } - } - assert_eq!(compared, 18, "six pages at three DPIs should all be compared"); -} diff --git a/docs/architecture.md b/docs/architecture.md index 0125f266939..ee9650cb102 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -183,7 +183,7 @@ photocraft/ 3. **`photocraft-psd` depends on no workspace crate.** The doc ⇄ PSD mapping lives in `io`. This keeps the PSD crate publishable and reusable by other projects. The same holds for every standalone crate, with one documented exception: `codecs` → `heif` (both standalone and publishable; `STANDALONE_EXCEPTIONS` in `xtask/src/layers.rs`). 4. **wasm gate:** every crate in L0–L5 (except feature-gated native backends) must build for `wasm32-unknown-unknown`. CI runs `cargo build -p photocraft-engine --target wasm32-unknown-unknown --no-default-features --features web`. 5. `gpu` is optional for `engine`. Engine features are `gpu` (default on) and `cpu-only`, and `cpu-only` builds are what the headless CLI and CI tests use. -6. **C dependencies** (optional LibRaw, pdfium) only behind features, only in `codecs`, `raw` or `io`, and never on by default for the web target. +6. **C dependencies** (optional LibRaw) only behind features, only in `codecs`, `raw` or `io`, and never on by default for the web target. --- diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 468365c6f6d..02a2da7f79c 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -40,7 +40,7 @@ XL are missing (gap G10). Remaining: 300–500 h including PSD fidelity. | Portable Bit Map (PBM/PGM/PPM/PNM/PFM/PAM) | R/W | yes | yes | 8/16/32f | | FITS | R/W (FITS Liberator plug-in) | yes | yes | 8/16/32f gray or RGB, header cards kept; no fpack, no debayer | | Targa | R/W | yes | yes | 8-bit | -| Photoshop PDF | R/W | no (#2541) | yes, one flattened page (Save As / Save a Copy / CLI, #3401; also print and artboards-to-PDF) | No vector/text PDF, no multi-page save, no PDF presentation, layers are not preserved (FILE-215-10); read still missing (#2541) | +| Photoshop PDF | R/W | yes, raster pages (craft-pdf; up to 16 pages, 8192 px per side, 64M px per page) | yes, one flattened page (Save As / Save a Copy / CLI, #3401; also print and artboards-to-PDF) | Read renders each page as a raster artboard: no editable text/vector layers yet (craft-pdf `interpret` is the follow-up), no PDF forms or annotations; write is still one flattened page, no multi-page save, no PDF presentation, layers are not preserved (FILE-215-10) | | Photoshop EPS, DCS 1.0/2.0, EPS TIFF/PICT preview | R/W | no | no | | | Generic EPS / AI | R (rasterize) | no | no | | | SVG | R (rasterize) | yes, as editable shape layers or a vector smart object | no | Better than Photoshop for editing; gradients approximated (FILE-215-9) | @@ -145,6 +145,7 @@ remaining gaps in #1606 stay tracked with per-sample corpus ceilings. Embedded SVG and PDF-compatible AI/PDF/EPS payloads can use an explicit VectorCraft editor choice, including nested PSB contents. AI/PDF/EPS working copies retain their format on save-back; a separate source-bound SVG display preview does not replace the native payload. Placement, shared instances, masks and Undo/Redo use existing smart-object transactions, with native bytes and previews persisted through .pcraft and PSD/PSB saves. Unsupported editor features may still change; standalone EPS/DCS import and lossless Adobe round-trip compatibility remain unverified. See [workflow, safety and validation limits](embedded-vector-editing.md). No corpus floor or parity percentage is changed. ## Revision history +| 2026-11-07 | minor | Photoshop PDF read: pages import as raster artboards through the shared craft-pdf (Hayro) renderer, up to 16 pages, 8192 px per side and 64M px per page; editable text/vectors and PDFium are gone. Write is unchanged. | The original reference row retains its source date and historical totals; current totals are in the status and Actions row above. The original reference entry retains its source date and historical totals; current totals are in the status above. diff --git a/packaging/windows/install-policy.json b/packaging/windows/install-policy.json index 8d01fab4ac6..fcba1850ae2 100644 --- a/packaging/windows/install-policy.json +++ b/packaging/windows/install-policy.json @@ -15,8 +15,7 @@ ], "payloads": [ "photocraft-cli.exe", - "photocraft.exe", - "pdfium.dll" + "photocraft.exe" ], "registry": [ [ diff --git a/packaging/windows/package.ps1 b/packaging/windows/package.ps1 index 8b4e8d0fea9..d984e3930a6 100644 --- a/packaging/windows/package.ps1 +++ b/packaging/windows/package.ps1 @@ -55,77 +55,6 @@ New-Item -ItemType Directory -Force -Path $Dist | Out-Null if (-not $env:PHOTOCRAFT_BUILD_SHA) { $env:PHOTOCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) } if (-not $env:PHOTOCRAFT_BUILD_DATE) { $env:PHOTOCRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') } -# PDF import loads PDFium at runtime. Stage the Windows build's DLL before cargo, so the app's -# build script copies it beside the exe and both the MSI and the portable ZIP ship it. -# -# Pinned to a reviewed pdfium-binaries release: the archive is verified before extraction and a -# cached DLL is verified before reuse, so a moved or compromised "latest" cannot be packaged. -# Bump the release and both hashes together after re-checking the published build. -$PdfiumRelease = 'chromium/8138' -$PdfiumArchiveSha256 = @{ - x64 = '8d48973e3eb472dda0f5f2435e595ac043f9f2219dd71883392f549445afa8a5' - x86 = '5c32d44711a73ed8ae86b85322078da8444fc696b9326527eed2d9fcd620fc84' - arm64 = '5e04abdb36ba9b4b5c8630123eaf042036f8a62abda6e5529708fee3d35fbf4f' -} -$PdfiumDllSha256 = @{ - x64 = '71a3e63e6ab8f5746a0fc9de9bc3d0c0dc07eb60990dfd37d9db7fc891821943' - x86 = 'ee592bd01eaef454aada95ed483ceca1c4f6ce0f0b9568608f40c3861fbda035' - arm64 = '0b1b9a52b3297448cbe461ffbca1455603d85161d5e96090e1a89bd7c4a62a33' -} -$PdfiumDir = Join-Path $Root "target\pdfium\$Arch" -$PdfiumDll = Join-Path $PdfiumDir 'pdfium.dll' -$PdfiumLicense = Join-Path $PdfiumDir 'LICENSE' -$PdfiumLicenses = Join-Path $PdfiumDir 'licenses' -$PdfiumTag = Join-Path $PdfiumDir 'release.txt' - -function Get-Sha256([string] $Path) { (Get-FileHash -Algorithm SHA256 -LiteralPath $Path).Hash.ToLowerInvariant() } - -# A cache from another pinned release (or missing its licence set) is discarded whole. -$cachedRelease = if (Test-Path -LiteralPath $PdfiumTag) { (Get-Content -Raw -LiteralPath $PdfiumTag).Trim() } else { '' } -if ($cachedRelease -ne $PdfiumRelease) { - Remove-Item -LiteralPath $PdfiumDir -Recurse -Force -ErrorAction SilentlyContinue -} -if (Test-Path -LiteralPath $PdfiumDll) { - $actualDll = Get-Sha256 $PdfiumDll - if ($actualDll -ne $PdfiumDllSha256[$Arch]) { - Write-Warning "cached PDFium DLL is not the pinned $PdfiumRelease build ($actualDll); re-downloading" - Remove-Item -LiteralPath $PdfiumDll -Force - } -} -if (-not ((Test-Path -LiteralPath $PdfiumDll) -and (Test-Path -LiteralPath $PdfiumLicense) -and (Test-Path -LiteralPath $PdfiumLicenses))) { - $expectedArchive = $PdfiumArchiveSha256[$Arch] - if (-not $expectedArchive) { throw "no pinned PDFium checksum for $Arch" } - $tgz = Join-Path $env:TEMP "pdfium-win-$Arch.tgz" - Invoke-Native "download PDFium ($Arch, $PdfiumRelease)" { - Remove-Item -LiteralPath $tgz -Force -ErrorAction SilentlyContinue - Invoke-WebRequest -Uri "https://github.com/bblanchon/pdfium-binaries/releases/download/$PdfiumRelease/pdfium-win-$Arch.tgz" -OutFile $tgz - $actualArchive = Get-Sha256 $tgz - if ($actualArchive -ne $expectedArchive) { throw "PDFium $Arch archive checksum $actualArchive does not match the pinned $expectedArchive" } - New-Item -ItemType Directory -Force -Path $PdfiumDir | Out-Null - # A DLL left in bin\ by an earlier run must not be mistaken for this archive's extraction. - $extracted = Join-Path $PdfiumDir 'bin\pdfium.dll' - Remove-Item -LiteralPath $extracted -Force -ErrorAction SilentlyContinue - tar -xzf $tgz -C $PdfiumDir - if ($LASTEXITCODE -ne 0) { throw "PDFium $Arch archive extraction failed with exit code $LASTEXITCODE" } - if (-not (Test-Path -LiteralPath $extracted)) { throw 'PDFium archive had no bin/pdfium.dll' } - Move-Item -Force $extracted $PdfiumDll - Set-Content -LiteralPath $PdfiumTag -Value $PdfiumRelease -NoNewline - if ((Get-Sha256 $PdfiumDll) -ne $PdfiumDllSha256[$Arch]) { throw "extracted PDFium $Arch DLL checksum does not match the pinned build" } - Remove-Item -LiteralPath $tgz -Force - } -} -$env:PDFIUM_DLL = $PdfiumDll - -# PDFium's BSD licence and the licences of the libraries bundled into its DLL ship beside it. They -# are staged flat with a `pdfium-` prefix, so both the MSI's INSTALLFOLDER and the portable root -# carry them whether the DLL came from this download or the cache. -function Stage-PdfiumLicences([string] $Dest) { - Copy-Item -LiteralPath $PdfiumLicense -Destination (Join-Path $Dest 'pdfium-LICENSE.txt') -Force - Get-ChildItem -LiteralPath $PdfiumLicenses -File | ForEach-Object { - Copy-Item -LiteralPath $_.FullName -Destination (Join-Path $Dest ("pdfium-license-" + $_.Name)) -Force - } -} - Write-Output "PhotoCraft $Version for Windows $Arch ($Target)" if (-not $SkipBuild) { @@ -160,8 +89,6 @@ $Stage = Join-Path $TargetDir "windows-package\$Arch" Remove-Item -Recurse -Force $Stage -ErrorAction SilentlyContinue New-Item -ItemType Directory -Force -Path $Stage | Out-Null Copy-Item (Join-Path $Bin 'photocraft.exe'), (Join-Path $Bin 'photocraft-cli.exe') $Stage -Copy-Item -LiteralPath $PdfiumDll -Destination $Stage -Stage-PdfiumLicences $Stage & (Join-Path $PSScriptRoot 'sign.ps1') (Join-Path $Stage 'photocraft.exe') (Join-Path $Stage 'photocraft-cli.exe') @@ -244,8 +171,6 @@ $Portable = Join-Path $TargetDir "windows-package\photocraft-$Version-windows-$A Remove-Item -Recurse -Force $Portable -ErrorAction SilentlyContinue New-Item -ItemType Directory -Force -Path $Portable | Out-Null Copy-Item (Join-Path $Stage '*.exe') $Portable -Copy-Item -LiteralPath $PdfiumDll -Destination $Portable -Stage-PdfiumLicences $Portable foreach ($f in 'README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') { $p = Join-Path $Root $f if (Test-Path $p) { Copy-Item $p $Portable } diff --git a/packaging/windows/photocraft.wxs b/packaging/windows/photocraft.wxs index f727880a5a6..6ff961fd994 100644 --- a/packaging/windows/photocraft.wxs +++ b/packaging/windows/photocraft.wxs @@ -33,7 +33,6 @@ - - - - - - From 2de7a9c042d2572a9a166971d11c07446d3a9b90 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Sat, 7 Nov 2026 19:41:28 +0100 Subject: [PATCH 25/30] Revert "Export: split nested groups into separate layers/files" This reverts commit c1662d49116d73cf1760d37f7089a232a5159c6e. --- crates/engine/src/cmd/file_cmds/export.rs | 162 +++++----------------- crates/engine/src/cmd/file_cmds/tests.rs | 61 -------- 2 files changed, 38 insertions(+), 185 deletions(-) diff --git a/crates/engine/src/cmd/file_cmds/export.rs b/crates/engine/src/cmd/file_cmds/export.rs index 629b7aad822..1f7f9677ffa 100644 --- a/crates/engine/src/cmd/file_cmds/export.rs +++ b/crates/engine/src/cmd/file_cmds/export.rs @@ -20,7 +20,7 @@ pub fn export_layers_with(s: &Session, p: &Value, write: impl FnMut(&str, &[u8]) export_layers_report_with(s, p, write).map(|report| report.files) } -/// A layer omitted from a successful Layers to Files export. +/// A top-level layer omitted from a successful Layers to Files export. #[derive(Debug, serde::Serialize)] pub struct SkippedExportLayer { /// Session layer id (names need not be unique). @@ -38,83 +38,14 @@ pub struct LayerExportReport { pub skipped: Vec, } -/// One layer the export will write or explain, in top-to-bottom order. -enum Planned<'a> { - Export(&'a Layer), - Skip(&'a Layer, &'static str), - Hidden(&'a Layer), -} - -/// Flattens a layer (and, with `split_groups`, its group descendants) into export entries. -fn plan_layer<'a>(layer: &'a Layer, split_groups: bool, visible_only: bool, plan: &mut Vec>) { - if !layer.visible && visible_only { - plan.push(Planned::Hidden(layer)); - // A hidden group takes its descendants with it; report each so the omission is complete. - if split_groups && let LayerContent::Group(group) = &layer.content { - for child in group.children.iter().rev() { - plan_hidden(child, plan); - } - } - return; - } - if let LayerContent::Group(group) = &layer.content - && split_groups - { - for child in group.children.iter().rev() { - plan_layer(child, split_groups, visible_only, plan); - } - return; - } - if matches!(layer.content, LayerContent::Adjustment(_)) { - plan.push(Planned::Skip(layer, "adjustment layer has no pixels of its own")); - } else { - plan.push(Planned::Export(layer)); - } -} - -/// Marks `layer` and all of its descendants as hidden, top to bottom. -fn plan_hidden<'a>(layer: &'a Layer, plan: &mut Vec>) { - plan.push(Planned::Hidden(layer)); - if let LayerContent::Group(group) = &layer.content { - for child in group.children.iter().rev() { - plan_hidden(child, plan); - } - } -} - -/// The same export as [`export_layers_with`], with an explanation for every omitted layer. -/// -/// `groups` chooses what a group produces: `"merged"` (the default) exports the group as one -/// file, as before; `"layers"` walks into the group and exports each visible layer inside it as -/// its own file (top to bottom), so no group is a file of its own. Encoding and write failures -/// remain errors, never successful skips. Existing numbering is preserved. +/// The same export as [`export_layers_with`], with an explanation for every omitted top-level +/// layer. Groups export merged, so their children are not separate exports or skips. Encoding +/// and write failures remain errors, never successful skips. Existing numbering is preserved. pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result { let cmd = "file.export.layersToFiles"; let format = p.get("format").and_then(Value::as_str).unwrap_or("png").trim_start_matches('.').to_ascii_lowercase(); let trim = p.get("trim").and_then(Value::as_bool).unwrap_or(false); let visible_only = p.get("visibleOnly").and_then(Value::as_bool).unwrap_or(true); - let split_groups = match p.get("groups") { - None => false, - Some(Value::String(s)) => match s.to_ascii_lowercase().as_str() { - "merged" => false, - "layers" => true, - other => { - return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("groups must be \"merged\" or \"layers\", not {other:?}") }); - } - }, - Some(_) => return Err(EngineError::BadParams { cmd: cmd.into(), msg: "groups must be a string: \"merged\" or \"layers\"".into() }), - }; - let layer_names = match p.get("naming") { - None => false, - Some(Value::String(s)) => match s.to_ascii_lowercase().as_str() { - "numbered" => false, - "layer" => true, - other => { - return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("naming must be \"numbered\" or \"layer\", not {other:?}") }); - } - }, - Some(_) => return Err(EngineError::BadParams { cmd: cmd.into(), msg: "naming must be a string: \"numbered\" or \"layer\"".into() }), - }; // Callers outside `Session::execute` (headless workspace exports) carry the session's gate // into `encode`, so a PSD embeds no file a linked smart object names. let _authorization = crate::jobs::render_authorization_scope(s.authorize); @@ -122,65 +53,48 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& let d = s.active().ok_or(EngineError::NoDocument)?; let prefix = p.get("prefix").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name)); let doc = d.doc.clone(); - let mut plan = Vec::new(); - for l in doc.layers.iter().rev() { - plan_layer(l, split_groups, visible_only, &mut plan); - } let mut report = LayerExportReport::default(); - let mut used = std::collections::HashSet::new(); // Hidden layers never consumed a filename index; adjustments that pass the visibility // filter did. Keep those filenames stable while reporting both kinds of omission. let mut i = 0usize; - for entry in plan { - match entry { - Planned::Hidden(l) => report.skipped.push(SkippedExportLayer { layer: l.id.0, name: l.name.clone(), reason: "hidden by visibleOnly" }), - Planned::Skip(l, reason) => { - i += 1; - report.skipped.push(SkippedExportLayer { layer: l.id.0, name: l.name.clone(), reason }); - } - Planned::Export(l) => { - let index = i; - i += 1; - let mut one = (*doc).clone(); - let mut only = l.clone(); - only.visible = true; - only.clipped = false; - one.layers = vec![only]; - if trim { - let mut bounds = Rect::EMPTY; - let _ = photocraft_compose::render_bands(&one, one.bounds(), 0, |band| -> std::result::Result<(), ()> { - let width = band.rect.width() as usize; - for (i, rgba) in band.px.iter().enumerate() { - if rgba[3] > 0.0 && width > 0 { - let x = band.rect.x0 + (i % width) as i32; - let y = band.rect.y0 + (i / width) as i32; - bounds = bounds.union(&Rect::new(x, y, x + 1, y + 1)); - } - } - Ok(()) - }); - if !bounds.is_empty() && bounds != one.bounds() { - crate::image_cmds::crop_doc(&mut one, cmd, bounds, true, [0.0; 4])?; + for l in doc.layers.iter().rev() { + if !l.visible && visible_only { + report.skipped.push(SkippedExportLayer { layer: l.id.0, name: l.name.clone(), reason: "hidden by visibleOnly" }); + continue; + } + let index = i; + i += 1; + if matches!(l.content, LayerContent::Adjustment(_)) { + report.skipped.push(SkippedExportLayer { layer: l.id.0, name: l.name.clone(), reason: "adjustment layer has no pixels of its own" }); + continue; + } + let mut one = (*doc).clone(); + let mut only = l.clone(); + only.visible = true; + only.clipped = false; + one.layers = vec![only]; + if trim { + let mut bounds = Rect::EMPTY; + let _ = photocraft_compose::render_bands(&one, one.bounds(), 0, |band| -> std::result::Result<(), ()> { + let width = band.rect.width() as usize; + for (i, rgba) in band.px.iter().enumerate() { + if rgba[3] > 0.0 && width > 0 { + let x = band.rect.x0 + (i % width) as i32; + let y = band.rect.y0 + (i / width) as i32; + bounds = bounds.union(&Rect::new(x, y, x + 1, y + 1)); } } - - let name = if layer_names { - let base = sanitize(&l.name); - let mut name = format!("{base}.{format}"); - let mut n = 2; - while !used.insert(name.to_ascii_lowercase()) { - name = format!("{base}-{n}.{format}"); - n += 1; - } - name - } else { - format!("{}_{:04}_{}.{format}", sanitize(&prefix), index, sanitize(&l.name)) - }; - let (bytes, _warnings) = encode(&one, &name, save)?; - write(&name, &bytes)?; - report.files.push(name); + Ok(()) + }); + if !bounds.is_empty() && bounds != one.bounds() { + crate::image_cmds::crop_doc(&mut one, cmd, bounds, true, [0.0; 4])?; } } + + let name = format!("{}_{:04}_{}.{format}", sanitize(&prefix), index, sanitize(&l.name)); + let (bytes, _warnings) = encode(&one, &name, save)?; + write(&name, &bytes)?; + report.files.push(name); } Ok(report) } diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index 0703cf914ea..d42d333128d 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -2573,67 +2573,6 @@ fn layers_to_files_reports_skipped_layers_without_changing_files() { } } -#[test] -/// `groups: "layers"` walks into a group and writes each visible leaf as its own file. -fn layers_to_files_exports_group_children_as_loose_files() { - let dir = tmp("layers-groups"); - let mut s = session(8, 8, 8); - s.edit("Group", |doc, _| { - let fmt = doc.pixel_format(); - let child = |name: &str| photocraft_doc::Layer::new(name, photocraft_doc::LayerContent::Raster(photocraft_doc::Surface::new(fmt))); - let sub = photocraft_doc::Layer::new( - "sub", - photocraft_doc::LayerContent::Group(photocraft_doc::Group { children: vec![child("c")], expanded: true, artboard: None, frame_stroke: None }), - ); - doc.layers.push(photocraft_doc::Layer::new( - "expanded", - photocraft_doc::LayerContent::Group(photocraft_doc::Group { - children: vec![child("a"), child("b"), sub], - expanded: true, - artboard: None, - frame_stroke: None, - }), - )); - Ok(()) - }) - .unwrap(); - let files = |r: &Value| -> Vec { r["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect() }; - - let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "loose", "groups": "layers"})).unwrap(); - assert_eq!( - files(&r), - vec![join(&dir, "loose_0000_c.png"), join(&dir, "loose_0001_b.png"), join(&dir, "loose_0002_a.png"), join(&dir, "loose_0003_Background.png")] - ); - assert!(files(&r).iter().all(|f| std::path::Path::new(f).is_file())); - - // The default still merges the group into one file. - let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "merged"})).unwrap(); - assert_eq!(files(&r), vec![join(&dir, "merged_0000_expanded.png"), join(&dir, "merged_0001_Background.png")]); - - // naming: "layer" writes the bare layer names instead of prefix_index_name. - let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "groups": "layers", "naming": "layer"})).unwrap(); - assert_eq!(files(&r), vec![join(&dir, "c.png"), join(&dir, "b.png"), join(&dir, "a.png"), join(&dir, "Background.png")]); - - // A hidden child is skipped with visibleOnly and exported without it. - s.edit("Hide b", |doc, _| { - let group = doc.layers.last_mut().ok_or_else(|| EngineError::Other("no group".into()))?; - let LayerContent::Group(g) = &mut group.content else { return Err(EngineError::Other("not a group".into())) }; - g.children[1].visible = false; - Ok(()) - }) - .unwrap(); - let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "visible", "groups": "layers"})).unwrap(); - assert_eq!(files(&r), vec![join(&dir, "visible_0000_c.png"), join(&dir, "visible_0001_a.png"), join(&dir, "visible_0002_Background.png")]); - let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "all", "groups": "layers", "visibleOnly": false})).unwrap(); - assert_eq!( - files(&r), - vec![join(&dir, "all_0000_c.png"), join(&dir, "all_0001_b.png"), join(&dir, "all_0002_a.png"), join(&dir, "all_0003_Background.png")] - ); - - // An unknown mode is rejected instead of silently merging. - assert!(s.execute("file.export.layersToFiles", json!({"dir": dir, "groups": "folders"})).is_err()); -} - #[test] fn layers_to_files_reports_groups_as_exports_and_failures_as_errors() { let mut s = session(4, 4, 8); From 060d35265a1a65a9f25f555b5f2d924208425209 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Sat, 7 Nov 2026 19:46:18 +0100 Subject: [PATCH 26/30] PDF: keep the raster importer clippy-clean and refresh the scorecard - Iterate the page sizes with their index instead of indexing the vector (clippy::needless_range_loop). - Fix the .ai dispatch test's module path. - Regenerate docs/scorecard.md after the merge (10 of 197 settings). --- crates/io/src/lib.rs | 2 +- crates/io/src/pdf_import.rs | 3 +-- docs/scorecard.md | 4 ++-- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 7519449224f..195a58b01a8 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -1651,7 +1651,7 @@ mod tests { pdf.trailer.set("Root", catalog); let mut bytes = Vec::new(); pdf.save_to(&mut bytes).expect("writing the .ai fixture"); - assert!(pdf_import::is_pdf(&bytes)); + assert!(crate::pdf_import::is_pdf(&bytes)); assert_eq!(import_preflight("illustration.ai", &bytes), ImportPreflight::Unbounded); let result = import("illustration.ai", &bytes).expect("an .ai starting with %PDF- takes the PDF importer"); assert_eq!(result.document.artboards().len(), 1); diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index 0fcc540749f..fc4733908a8 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -120,11 +120,10 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - let mut doc = Document::new(name, Size::new(doc_width as u32, doc_height as u32), ColorMode::Rgb, SampleType::U8); doc.resolution_dpi = dpi as f32; let mut x: u32 = 0; - for index in 0..count { + for (index, &(width_pt, height_pt)) in sizes.iter().enumerate() { ctl.check().map_err(|_| IoError::Cancelled)?; let page_number = first + index; let page = &pdf.pages()[page_number - 1]; - let (width_pt, height_pt) = sizes[index]; let width = page_pixels(width_pt, dpi); let height = page_pixels(height_pt, dpi); // The DPI solve keeps these inside the renderer's bounds; re-check rather than panic if diff --git a/docs/scorecard.md b/docs/scorecard.md index cb666664b96..4ff5f86cd64 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Performance](#performance) | 3 | 22 | 51 | 85 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 47 not run, 4 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 11 | 14 | 2 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 190/258, round trip ≥ 258/258 | | [Tools](#tools) | 36 | 9 | 0 | | -| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 10 of 194 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 10 of 197 (target 0) | | [Type](#type) | 5 | 5 | 0 | | | [Automation](#automation) | 5 | 3 | 3 | 662 of 662 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present | @@ -209,7 +209,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu ## Workspace and UI -**Settings that do nothing: 10 of 194** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 10 of 197** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. Unread: `general.color_picker`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `performance.legacy_compositing`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `type_.text_engine`, `enhanced_controls.scrubby_slider_acceleration`. From c5a9288c4b6fe326922e3f3c9bfe32a599c0dfc5 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Sat, 7 Nov 2026 19:52:35 +0100 Subject: [PATCH 27/30] PDF: keep the craft-pdf imports off the wasm build The module compiles for wasm (only its import entry point is stubbed), so the renderer imports and the native document types are gated; the web build no longer sees a dependency it does not have. --- crates/io/src/pdf_import.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index fc4733908a8..c78d92018cd 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -10,12 +10,19 @@ //! or shipped, and a malformed file is reported as an error rather than taking the process down. use crate::{ImportOptions, ImportResult, IoError}; +#[cfg(not(target_arch = "wasm32"))] use craft_pdf::interpret::InterpreterSettings; +#[cfg(not(target_arch = "wasm32"))] use craft_pdf::raster::{self, RenderCache}; +#[cfg(not(target_arch = "wasm32"))] use photocraft_color::{ColorMode, PixelFormat, SampleType}; +#[cfg(not(target_arch = "wasm32"))] use photocraft_doc::{Artboard, Document, Group, Layer, LayerContent}; +#[cfg(not(target_arch = "wasm32"))] use photocraft_geom::{Rect, Size}; -use photocraft_raster::{Interrupt, Surface}; +use photocraft_raster::Interrupt; +#[cfg(not(target_arch = "wasm32"))] +use photocraft_raster::Surface; /// `%PDF-` magic. `.ai` files that start with it are PDFs and render through this importer. pub fn is_pdf(bytes: &[u8]) -> bool { From d297dd3a2d068a664fa87dc5e22d56cd7bb323c3 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Sat, 7 Nov 2026 20:12:46 +0100 Subject: [PATCH 28/30] PDF: validate --pdf-dpi, band the raster conversion, complete the notices - --pdf-dpi now rejects zero, negative, NaN and infinite values at parse time (unit-tested) instead of silently falling back to 300 DPI. - The RGBA8 raster is converted and written in 256-row bands with a cancellation check per band, so the f32 buffer no longer duplicates a whole page; the pixel-memory estimate charges the retained raster instead of that buffer. - docs/file-format-parity.md: the 2026-11-07 revision row is inside the revision table. - NOTICE now reproduces the Hayro MIT notice, the Foxit/PDFium BSD-3-Clause text, Adobe's CMaps BSD-3-Clause text and the CC0 statement for the ICC profile; package.ps1 ships NOTICE and ATTRIBUTION.md in both installers. --- NOTICE | 37 ++++++++++++++++++++++++++++++++ apps/photocraft-cli/src/args.rs | 26 +++++++++++++++++++++- crates/io/src/pdf_import.rs | 28 ++++++++++++++---------- crates/io/tests/it/pdf_import.rs | 3 +++ docs/file-format-parity.md | 2 +- 5 files changed, 83 insertions(+), 13 deletions(-) diff --git a/NOTICE b/NOTICE index 826dea74901..d51db72c912 100644 --- a/NOTICE +++ b/NOTICE @@ -81,3 +81,40 @@ the standard-14 Foxit fonts (BSD-3-Clause), Adobe CMaps (BSD-3-Clause) and a Com profile by Clinton Ingram (CC0-1.0); per-file sources and hashes are in craft-libs ATTRIBUTION.md. No PDF assets are copied into this repository, and PDFium is no longer used or shipped. + +Licence texts for the optional PDF reader + +Hayro (MIT): +Copyright (c) The Hayro Authors + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Standard-14 Foxit fonts (BSD-3-Clause): +Copyright 2014 PDFium Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. +* Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Adobe CMaps (BSD-3-Clause): +Copyright 1990-2023 Adobe. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +Neither the name of Adobe nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Compact ICC profile: CC0 1.0 Universal (public domain dedication), by Clinton Ingram (saucecontrol/Compact-ICC-Profiles). diff --git a/apps/photocraft-cli/src/args.rs b/apps/photocraft-cli/src/args.rs index 84cf7c0a88e..a15019e666a 100644 --- a/apps/photocraft-cli/src/args.rs +++ b/apps/photocraft-cli/src/args.rs @@ -114,7 +114,7 @@ pub(crate) struct ConvertArgs { #[arg(long)] pub(crate) approve_high_memory: bool, /// PDF import resolution in DPI (default 300) - #[arg(long)] + #[arg(long, value_name = "DPI", value_parser = pdf_dpi)] pub(crate) pdf_dpi: Option, /// PDF pages to import, 1-based: "3" or "2-7" (default all) #[arg(long)] @@ -320,6 +320,8 @@ enum ValueError { JpegFormat, #[error("expected on or off")] OnOff, + #[error("expected a positive number")] + PdfDpi, /// Why a `--bridge` value, or a PHOTOCRAFT_CONTROL_PORT value for `mcp`, is refused. #[error("expected a port, 0-65535 (--bridge also takes 127.0.0.1:)")] Bridge, @@ -388,6 +390,12 @@ fn on_off(s: &str) -> Result { } } +/// A PDF import DPI: a finite number greater than zero. The importer's fallback to 300 DPI is +/// for absent preferences, not for a mistyped flag. +fn pdf_dpi(s: &str) -> Result { + s.parse::().ok().filter(|dpi| dpi.is_finite() && *dpi > 0.0).ok_or(ValueError::PdfDpi) +} + fn jpeg_format(s: &str) -> Result { JpegFormat::parse(s).ok_or(ValueError::JpegFormat) } @@ -538,3 +546,19 @@ fn check_server(sub: &mut clap::Command, m: &ArgMatches, has_transport: bool, tr } Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + /// `--pdf-dpi` only takes a positive finite number: a mistyped value is refused at parse time + /// instead of silently becoming the importer's 300 DPI fallback. + #[test] + fn pdf_dpi_rejects_non_positive_and_non_finite_values() { + assert!(pdf_dpi("300").is_ok()); + assert!(pdf_dpi("0.5").is_ok()); + for bad in ["0", "-1", "nan", "inf", "-inf", "abc"] { + assert!(pdf_dpi(bad).is_err(), "{bad} should be refused"); + } + } +} diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index c78d92018cd..79db591088a 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -101,10 +101,10 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - if doc_width > u64::from(u32::MAX) || doc_height > u64::from(u32::MAX) { return Err(IoError::Unsupported("PDF import is too large at this DPI; lower the import DPI".into())); } - // Retained tiles plus the converting page's peak: craft-pdf's RGBA8 raster (4 B/px) and the - // f32 document buffer (16 B/px). + // Retained tiles plus the converting page's raster (4 B/px); the f32 conversion runs in + // 256-row bands, so it adds only a constant-sized buffer rather than a second full page. let max_page = sizes.iter().map(|&(w, h)| u64::from(page_pixels(w, dpi)) * u64::from(page_pixels(h, dpi))).max().unwrap_or(0); - let estimate = retained.saturating_add(max_page.saturating_mul(20)); + let estimate = retained.saturating_add(max_page.saturating_mul(4)); let budget = if opts.flat_max_pixel_bytes > 0 { opts.flat_max_pixel_bytes } else { DEFAULT_MAX_PIXEL_BYTES }; if estimate > budget { return Err(IoError::Unsupported(format!( @@ -159,17 +159,23 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - let mut surface = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, true)); let bytes = rendered.bytes(); - let mut data = Vec::new(); - if data.try_reserve_exact(bytes.len()).is_err() { + // Convert and write in row bands: the f32 buffer stays bounded instead of a second + // 16-bytes-per-pixel copy of the whole page, and cancellation is polled per band. + const BAND_ROWS: usize = 256; + let row_bytes = width as usize * 4; + let band_bytes = row_bytes.saturating_mul(BAND_ROWS); + let mut data: Vec = Vec::new(); + if data.try_reserve_exact(band_bytes).is_err() { return Err(IoError::Unsupported(format!("PDF page {page_number} needs more memory than is available"))); } - for chunk in bytes.as_chunks::<4>().0 { - for &value in &chunk[..3] { - data.push(f32::from(value) / 255.0); - } - data.push(f32::from(chunk[3]) / 255.0); + for (band, rows) in bytes.chunks(band_bytes).enumerate() { + ctl.check().map_err(|_| IoError::Cancelled)?; + data.clear(); + data.extend(rows.iter().map(|&value| f32::from(value) / 255.0)); + let top = (band * BAND_ROWS) as i32; + let band_height = (rows.len() / row_bytes) as u32; + surface.write_region(Rect::from_xywh(x as i32, top, width, band_height), &data); } - surface.write_region(Rect::from_xywh(x as i32, 0, width, height), &data); let rect = Rect::new(x as i32, 0, (x + width) as i32, height as i32); let layer = Layer::new(format!("Page {page_number}"), LayerContent::Raster(surface)); let group = Group { children: vec![layer], expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None }; diff --git a/crates/io/tests/it/pdf_import.rs b/crates/io/tests/it/pdf_import.rs index f63ff194820..95475ea2001 100644 --- a/crates/io/tests/it/pdf_import.rs +++ b/crates/io/tests/it/pdf_import.rs @@ -103,6 +103,7 @@ fn first_artboard(document: &photocraft_doc::Document) -> Rect { group.artboard.as_ref().expect("page artboard").rect } +/// Each page becomes its own artboard at 72 and 300 DPI, with the print size preserved. #[test] fn imports_every_page_as_an_artboard_with_its_print_size() { let pdf = variant_pdf(); @@ -148,6 +149,7 @@ fn imports_every_page_as_an_artboard_with_its_print_size() { } } +/// A page over the renderer's side limit lowers the effective DPI instead of failing. #[test] fn huge_pages_lower_the_effective_dpi_within_the_renderer_bounds() { // 3000 pt at 300 dpi would be 12500 px wide, over craft-pdf's 8192 px side limit. @@ -162,6 +164,7 @@ 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. #[test] fn cancelling_on_the_last_checks_is_reported() { let pdf = variant_pdf(); diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 02a2da7f79c..237e69921be 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -145,13 +145,13 @@ remaining gaps in #1606 stay tracked with per-sample corpus ceilings. Embedded SVG and PDF-compatible AI/PDF/EPS payloads can use an explicit VectorCraft editor choice, including nested PSB contents. AI/PDF/EPS working copies retain their format on save-back; a separate source-bound SVG display preview does not replace the native payload. Placement, shared instances, masks and Undo/Redo use existing smart-object transactions, with native bytes and previews persisted through .pcraft and PSD/PSB saves. Unsupported editor features may still change; standalone EPS/DCS import and lossless Adobe round-trip compatibility remain unverified. See [workflow, safety and validation limits](embedded-vector-editing.md). No corpus floor or parity percentage is changed. ## Revision history -| 2026-11-07 | minor | Photoshop PDF read: pages import as raster artboards through the shared craft-pdf (Hayro) renderer, up to 16 pages, 8192 px per side and 64M px per page; editable text/vectors and PDFium are gone. Write is unchanged. | The original reference row retains its source date and historical totals; current totals are in the status and Actions row above. The original reference entry retains its source date and historical totals; current totals are in the status above. | Date | Change | Summary | |---|---|---| +| 2026-11-07 | minor | Photoshop PDF read: pages import as raster artboards through the shared craft-pdf (Hayro) renderer, up to 16 pages, 8192 px per side and 64M px per page; editable text/vectors and PDFium are gone. Write is unchanged. | | 2026-11-06 | minor | Scripted PSD/PSB saves take `maximizeCompatibility` (Save, Save As, Save a Copy, `app.save`, serve `doc.save`, MCP `doc_save`/`doc_export`, Batch, Image Processor, Layers to Files) over Preferences › File Handling for one save, and the CLI `--no-maximize-compatibility` (#8064). Layer channels and the merged image were already RLE (ZIP with prediction at 32-bit), as Photoshop writes them (#8645) | | 2026-11-02 | minor | Actions Shear (`Shr `) loads, plays and saves the measured curve points and edge mode; unsafe subranges and unrepresentable forms remain kept steps (#10605). | | 2026-11-01 | minor | `.atn`: 23 newer measured forms mapped, including explicit Link/Unlink, Smart Object file operations, Make Type to Shape, radius-only Shape Blur, Artboard from Group and the Crop Photos parent; supported in batch 13; Link Layers keeps the measured toggle. Artboard forms with unmeasured settings and generated Crop helper steps remain kept. | From 1df674997b3d10368b4c8237155a8d68d720ea48 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Sun, 8 Nov 2026 02:34:58 +0100 Subject: [PATCH 29/30] 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. --- crates/io/src/pdf.rs | 52 ++++++++----- crates/io/src/pdf/tests.rs | 127 ++++++++++++++++++++++++++++++- crates/io/src/pdf_import.rs | 123 +++++++++++++++++++++++++++++- crates/io/tests/it/pdf_import.rs | 53 +++++++------ 4 files changed, 308 insertions(+), 47 deletions(-) diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index 7bf228320f4..86b03b565a9 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -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::>().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::>() .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) { diff --git a/crates/io/src/pdf/tests.rs b/crates/io/src/pdf/tests.rs index 6741fea3460..247ab991928 100644 --- a/crates/io/src/pdf/tests.rs +++ b/crates/io/src/pdf/tests.rs @@ -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 { + 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::>(); + 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); +} diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index 79db591088a..d4c8aa4eacd 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -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 { + 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, 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"); + } +} diff --git a/crates/io/tests/it/pdf_import.rs b/crates/io/tests/it/pdf_import.rs index 95475ea2001..b614f54c970 100644 --- a/crates/io/tests/it/pdf_import.rs +++ b/crates/io/tests/it/pdf_import.rs @@ -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(|_| ())), } } From 3ef91ec45af2e29aa1e4ff0e0471494aec88b8ba Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Sun, 8 Nov 2026 02:41:37 +0100 Subject: [PATCH 30/30] PDF: widen the dense-page cancellation margin Raise the synthetic page to a million strokes so the 45 ms watcher threshold keeps a wide margin on an optimised test build, and record why the importer keeps one RenderCache per page. --- crates/io/src/pdf_import.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index d4c8aa4eacd..d55676ac168 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -147,6 +147,9 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - if width > raster::MAX_SIDE || height > raster::MAX_SIDE || u64::from(width) * u64::from(height) > raster::MAX_PIXELS { return Err(IoError::Unsupported(format!("PDF page {page_number} is too large at {dpi:.0} dpi; lower the import DPI"))); } + // A cache per page, deliberately: a shared one would keep decoded images and fonts alive + // across up to 16 pages outside the pixel budget, and would hide an image-decode warning + // on a later page after the page that first hit it. let cache = RenderCache::new(); let options = raster::Options { scale: [(dpi / 72.0) as f32; 2], @@ -347,10 +350,11 @@ mod tests { } /// 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. + /// interval, so the interrupt lands mid-render and the page reports Cancelled. A million + /// strokes leaves a wide margin even on a fast, optimised test build. #[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 pdf = dense_operator_pdf(1_000_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 =