From 402ff3024e23b43b963ff2de37c6483faecff983 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 23:48:23 -0800 Subject: [PATCH] Fix #10902: PDF spot images and image masks keep their fill overprint PDF import read overprint for paths and text only, so an image in a Separation space or an image mask drawn under /op true opened knocking out, and a separations export of the document lost the ink beneath it. The interpreter reports the graphics state's overprint before each image; the importer now keeps the fill's on the image's colorize paint, as the .ai reader does. - Each draw of an image takes the state of that draw, so one XObject drawn twice can overprint once and knock out once. - A process color overprinting in mode 0 gives the same warning as a path does. - A page whose paths can't be counted drops the paths' overprint and keeps the images'. - An isolated group holding an overprinting image stays isolated. - Images read inside pattern cells, soft masks and type 3 glyphs knock out, as paths there do. --- crates/doc/src/overprint.rs | 25 +++-- crates/pdf/src/import/builder.rs | 38 ++++++-- crates/pdf/src/import/device.rs | 4 + crates/pdf/src/import/state.rs | 3 + crates/pdf/src/tests/import_overprint.rs | 115 +++++++++++++++++++++++ 5 files changed, 170 insertions(+), 15 deletions(-) diff --git a/crates/doc/src/overprint.rs b/crates/doc/src/overprint.rs index 7c13b8f755..eb882f5e77 100644 --- a/crates/doc/src/overprint.rs +++ b/crates/doc/src/overprint.rs @@ -368,18 +368,29 @@ impl Document { } } -/// Whether any fill or stroke of `n`'s subtree overprints, characters' too. -fn overprints_anywhere(n: &Node) -> bool { +/// Whether any fill or stroke of `n`'s subtree overprints, characters' too, and with `images` an +/// image's color. +fn overprints_anywhere(n: &Node, images: bool) -> bool { n.appearance.items.iter().any(|i| i.overprint()) - || n.extras().colorize_overprint + || (images && n.extras().colorize_overprint) || matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke)) - || n.children().is_some_and(|c| c.iter().any(|c| overprints_anywhere(c))) + || n.children().is_some_and(|c| c.iter().any(|c| overprints_anywhere(c, images))) } /// Stop every fill and stroke of `a`'s subtree overprinting (characters' too), copying only the /// nodes on the way to them. pub fn clear_overprints(a: &mut Arc) { - if !overprints_anywhere(a) { + clear(a, true); +} + +/// [`clear_overprints`] for fills, strokes and characters only: the colors of images keep their +/// overprint ([`crate::NodeExtras::colorize_overprint`]). +pub fn clear_paint_overprints(a: &mut Arc) { + clear(a, false); +} + +fn clear(a: &mut Arc, images: bool) { + if !overprints_anywhere(a, images) { return; } let n = Arc::make_mut(a); @@ -392,11 +403,11 @@ pub fn clear_overprints(a: &mut Arc) { } } // Also the flag an image keeps after its color is removed. - if n.extras().colorize_overprint { + if images && n.extras().colorize_overprint { n.extras_mut().colorize_overprint = false; } for c in n.children_mut().into_iter().flatten() { - clear_overprints(c); + clear(c, images); } } diff --git a/crates/pdf/src/import/builder.rs b/crates/pdf/src/import/builder.rs index 64da7fb8d5..cd248a7689 100644 --- a/crates/pdf/src/import/builder.rs +++ b/crates/pdf/src/import/builder.rs @@ -83,6 +83,7 @@ impl<'p> Builder<'p> { cmyk_keys: HashSet::new(), intent_cmyk: None, separation_paints: HashMap::new(), + fill_overprint: (false, 0), opaque: HashSet::new(), warnings: vec![], fonts: HashMap::new(), @@ -155,6 +156,7 @@ impl<'p> Builder<'p> { self.stack = vec![Frame::new(FrameKind::Root)]; self.root_groups.clear(); self.blend = BlendMode::Normal; + self.fill_overprint = (false, 0); self.glyphs = None; self.type3_run = None; self.text = None; @@ -182,6 +184,21 @@ impl<'p> Builder<'p> { self.scan.overprints && self.scan.paints.get(self.paint_at - 1).copied().unwrap_or(false) } + /// Whether the image the interpreter draws now, colorized by `paint`, overprints: its fill + /// overprint, as the interpreter reported it for this image. Off in a nested reading, as for + /// paths. A process color (one without a swatch) overprinting in mode 0 is reported as paths + /// are ([`OVERPRINT_ZERO_MODE`]). + pub(super) fn image_overprint(&mut self, paint: &Paint) -> bool { + let (on, mode) = self.fill_overprint; + if !on || self.nested > 0 { + return false; + } + if mode == 0 && matches!(paint, Paint::Solid { swatch: None, .. }) { + self.warn(OVERPRINT_ZERO_MODE); + } + true + } + /// What the interpreter draws now, as the page's walk counts it: the path whose turn comes /// next, or the `text` before it. `None` in a nested reading, which the walk doesn't follow. pub(super) fn walked(&self, text: bool) -> Option { @@ -207,9 +224,10 @@ impl<'p> Builder<'p> { pub(super) fn end_page(&mut self) -> Vec<(Option, Vec>)> { let mut children = self.close_frames(); // The interpreter drew another number of paths than the file was read to paint: which - // of them overprint can't be trusted. + // of them overprint can't be trusted. An image's overprint comes from the interpreter + // itself, so it stays. if self.scan.overprints && self.paint_at != self.scan.paints.len() { - children.iter_mut().for_each(vectorcraft_doc::overprint::clear_overprints); + children.iter_mut().for_each(vectorcraft_doc::overprint::clear_paint_overprints); self.warn(OVERPRINT_UNREAD); } let groups = std::mem::take(&mut self.root_groups); @@ -1114,7 +1132,8 @@ impl<'p> Builder<'p> { } /// An image of key `key` (its blob made by `make` the first time), placed by `xf`, with opacity - /// mask `mask` and the solid paint that colorizes it (`colorize`, for a grayscale image). + /// mask `mask` and the solid paint that colorizes it (`colorize`, for a grayscale image), which + /// overprints when the interpreter says the image does ([`Self::image_overprint`]). pub(super) fn add_image_masked( &mut self, key: u128, @@ -1123,6 +1142,7 @@ impl<'p> Builder<'p> { mask: Option, colorize: Option, ) { + let overprint = colorize.as_ref().is_some_and(|p| self.image_overprint(p)); let (k, w, h) = if let Some(v) = self.image_keys.get(&key).cloned() { v } else { @@ -1143,6 +1163,7 @@ impl<'p> Builder<'p> { ); n.extras_mut().mask = mask.map(Box::new); n.extras_mut().colorize = colorize.map(Box::new); + n.extras_mut().colorize_overprint = overprint; self.push_node(n); } @@ -1616,14 +1637,15 @@ fn visual_glyph_text(text: String) -> String { order.iter().filter_map(|&i| chars.get(i)).collect() } -/// Whether a visible fill or stroke among `children` overprints, characters' too, directly or -/// through children that don't isolate. In an isolated group an overprinting object is drawn on -/// the group's empty backdrop, so it covers the inks of the art below the group that it does not -/// paint; without isolation it leaves them. +/// Whether a visible fill or stroke among `children` overprints, characters' and colorized +/// images' too, directly or through children that don't isolate. In an isolated group an +/// overprinting object is drawn on the group's empty backdrop, so it covers the inks of the art +/// below the group that it does not paint; without isolation it leaves them. fn children_overprint(children: &[Arc]) -> bool { children.iter().any(|c| { c.visible - && (c.appearance.items.iter().any(|i| i.visible() && i.overprint()) + && (c.colorize_overprints() + || c.appearance.items.iter().any(|i| i.visible() && i.overprint()) || matches!(&c.kind, NodeKind::Text(t) if t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke)) || (!c.isolate && c.children().is_some_and(|ch| children_overprint(ch)))) }) diff --git a/crates/pdf/src/import/device.rs b/crates/pdf/src/import/device.rs index cd40578cec..cab5fc9afb 100644 --- a/crates/pdf/src/import/device.rs +++ b/crates/pdf/src/import/device.rs @@ -31,6 +31,10 @@ impl<'a> Device<'a> for Builder<'_> { } } + fn set_overprint(&mut self, fill: bool, _stroke: bool, mode: u8) { + self.fill_overprint = (fill, mode); + } + fn draw_path(&mut self, path: &BezPath, transform: Affine, paint: &craft::pdf::interpret::Paint<'a>, draw_mode: &PathDrawMode) { self.flush_glyphs(); self.flush_type3(); diff --git a/crates/pdf/src/import/state.rs b/crates/pdf/src/import/state.rs index c85f36bd7f..1cdc9e8bc2 100644 --- a/crates/pdf/src/import/state.rs +++ b/crates/pdf/src/import/state.rs @@ -144,6 +144,9 @@ pub(super) struct Builder<'p> { /// Images in a Separation space, by key: the paint of their ink, or `None` when they open in /// RGB (an ink that can't be told, tints that can't be read). pub(super) separation_paints: HashMap>, + /// The fill overprint (`/op`) and overprint mode (`/OPM`) the interpreter reported last. It + /// reports them before each image it draws, and an image paints with the fill's overprint. + pub(super) fill_overprint: (bool, u8), /// Mask keys of CMYK images whose mask turned out to hide nothing. pub(super) opaque: HashSet, pub(super) warnings: Vec, diff --git a/crates/pdf/src/tests/import_overprint.rs b/crates/pdf/src/tests/import_overprint.rs index 96a7a83e6a..1e7059ec2a 100644 --- a/crates/pdf/src/tests/import_overprint.rs +++ b/crates/pdf/src/tests/import_overprint.rs @@ -134,3 +134,118 @@ fn hidden_optional_content_and_pattern_cells_dont_shift_the_count() { assert!(about_overprint(&r).is_empty(), "layers {layers}: {:?}", r.warnings); } } + +/// A 2 × 1 image in the spot ink `Spot1` (a Separation space): it opens colorized by the ink. +const SPOT_IMAGE: &str = "<< /Type /XObject /Subtype /Image /Width 2 /Height 1 /ColorSpace [/Separation /Spot1 /DeviceCMYK << /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 1 0 0] /N 1 >>] /BitsPerComponent 8 /Filter /ASCIIHexDecode /Length 5 >>\nstream\nFF00>\nendstream"; + +/// An 8 × 1 image mask: it opens colorized by the color that paints it. +const MASK: &str = "<< /Type /XObject /Subtype /Image /Width 8 /Height 1 /ImageMask true /BitsPerComponent 1 /Filter /ASCIIHexDecode /Length 3 >>\nstream\nC3>\nendstream"; + +/// A page drawing `image` as `/Im1` with `content`, then the `extra` objects after it. +fn open_image(content: &str, image: &str, extra: &[&str]) -> ImportReport { + let mut objects = vec![image]; + objects.extend_from_slice(extra); + open(content, &format!("{SPOT} /XObject << /Im1 {} 0 R /X0 {} 0 R >>", first_extra(1), first_extra(1) + 1), &objects) +} + +/// Each colorized image in paint order: whether its color overprints. +fn image_overprints(d: &Document) -> Vec { + let mut out = vec![]; + d.walk(|n: &Node| { + if matches!(n.kind, NodeKind::Image(_)) && n.extras().colorize.is_some() { + out.push(n.colorize_overprints()); + } + }); + out +} + +/// One placement of `/Im1`, `i` steps down the page. +fn draw(i: u32) -> String { + format!("q 80 0 0 10 10 {} cm /Im1 Do Q", 10 + 20 * i) +} + +#[test] +fn a_spot_image_overprints_as_its_fill_does() { + // `/op` is the fill's; `/OP` alone is both; a stroke's `/OP` beside `/op false` is not the image's. + let content = format!("/On gs {} /Off gs {} /Stroke gs {} /Both gs {}", draw(0), draw(1), draw(2), draw(3)); + let r = open_image(&content, SPOT_IMAGE, &[]); + assert_eq!(image_overprints(&r.document), [true, false, false, true], "{:?}", r.warnings); + assert!(about_overprint(&r).is_empty(), "{:?}", r.warnings); + // Written with its overprint and read again, each keeps it. + let back = import_with_report(&export(&r.document, &PdfOptions::uncompressed()).unwrap(), &ImportOptions::default()).unwrap(); + assert_eq!(image_overprints(&back.document), [true, false, false, true], "{:?}", back.warnings); +} + +#[test] +fn an_image_mask_overprints_as_its_fill_does() { + let r = open_image(&format!("/CS0 cs 1 scn /On gs {} /Off gs {}", draw(0), draw(1)), MASK, &[]); + assert_eq!(image_overprints(&r.document), [true, false], "{:?}", r.warnings); + assert!(about_overprint(&r).is_empty(), "{:?}", r.warnings); + // Overprint mode 0 changes nothing for a spot color; a process color's zero tints would knock out. + let r = open_image(&format!("/Zero gs /CS0 cs 1 scn {}", draw(0)), MASK, &[]); + assert_eq!(image_overprints(&r.document), [true]); + assert!(about_overprint(&r).is_empty(), "{:?}", r.warnings); + let r = open_image(&format!("/Zero gs 0 0 0 1 k {}", draw(0)), MASK, &[]); + assert_eq!(image_overprints(&r.document), [true]); + assert_eq!(about_overprint(&r).len(), 1, "{:?}", r.warnings); + assert!(about_overprint(&r)[0].contains("/OPM 0")); +} + +#[test] +fn an_image_in_a_form_overprints_as_the_form_sets_it() { + // The page's state, then the form's own. + let form = stream("/Type /XObject /Subtype /Form /BBox [0 0 400 400]", &format!("{} /Off gs {}", draw(0), draw(1))); + let r = open_image("/On gs /X0 Do", SPOT_IMAGE, &[&form]); + assert_eq!(image_overprints(&r.document), [true, false], "{:?}", r.warnings); +} + +#[test] +fn an_isolated_form_holding_only_an_overprinting_image_stays_isolated() { + let form = stream("/Type /XObject /Subtype /Form /BBox [0 0 400 400] /Group << /S /Transparency /I true >>", &draw(0)); + let r = open_image("/On gs /X0 Do", SPOT_IMAGE, &[&form]); + let mut groups = vec![]; + r.document.walk(|n: &Node| { + if matches!(n.kind, NodeKind::Group { .. }) { + groups.push(n.isolate); + } + }); + assert_eq!(image_overprints(&r.document), [true]); + assert!(groups.contains(&true), "{groups:?}"); +} + +#[test] +fn an_image_in_a_pattern_cell_knocks_out_as_the_cells_paths_do() { + let (x, cell) = (first_extra(1), first_extra(1) + 1); + let cell_stream = stream( + &format!( + "/Type /Pattern /PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 10 10] /XStep 10 /YStep 10 /Resources << {ON} /XObject << /Im1 {x} 0 R >> >>" + ), + "/On gs 0 0 1 rg 0 0 5 5 re f q 10 0 0 10 0 0 cm /Im1 Do Q", + ); + let r = open("/On gs /Pattern cs /P0 scn 0 0 100 100 re f", &format!("/Pattern << /P0 {cell} 0 R >>"), &[SPOT_IMAGE, &cell_stream]); + let mut art = vec![]; + for p in r.document.patterns.iter() { + for a in &p.art { + a.walk(&mut |n: &Node| { + if matches!(n.kind, NodeKind::Image(_)) { + art.push(n.colorize_overprints()); + } + }); + } + } + assert_eq!(art, [false], "{:?}", r.warnings); +} + +#[test] +fn an_image_keeps_its_overprint_on_a_page_whose_paths_cant_be_counted() { + // The paths' overprint is dropped (see above); the image's comes from the interpreter. + let content = format!("0 0 1 rg /Sh0 sh /On gs 10 10 50 50 re f {}", draw(4)); + let page = PdfPage { + resources: format!("{ON} /Shading << /Sh0 << /ShadingType 99 >> >> /XObject << /Im1 {} 0 R >>", first_extra(1)), + ..PdfPage::new(400.0, 400.0, &content) + }; + let r = import_with_report(&pdf_with(&[page], &[SPOT_IMAGE], None), &ImportOptions::default()).unwrap(); + assert_eq!(overprints(&r.document), [(Some(false), None)]); + assert_eq!(image_overprints(&r.document), [true]); + assert_eq!(about_overprint(&r).len(), 1, "{:?}", r.warnings); +}