diff --git a/crates/doc/src/appearance/layers.rs b/crates/doc/src/appearance/layers.rs index 11d2b0664d..614616dadd 100644 --- a/crates/doc/src/appearance/layers.rs +++ b/crates/doc/src/appearance/layers.rs @@ -13,6 +13,18 @@ pub struct Effect { pub visible: bool, } +impl Effect { + /// Whether this effect gives an image's fill or stroke a shape to paint: it is a visible + /// Convert to Shape or Outline Object. + pub fn gives_image_shape(&self) -> bool { + self.visible + && matches!( + self.id.as_str(), + "convertToShape.rectangle" | "convertToShape.roundedRectangle" | "convertToShape.ellipse" | "path.outlineObject" + ) + } +} + fn yes() -> bool { true } diff --git a/crates/doc/src/live.rs b/crates/doc/src/live.rs index 3813b24950..e9d5296470 100644 --- a/crates/doc/src/live.rs +++ b/crates/doc/src/live.rs @@ -1340,6 +1340,33 @@ mod tests { assert!(piece.knockout_outline().is_none()); } + /// Each piece of a mesh-warped colorized image keeps its color and whether it overprints. + #[test] + fn mesh_warp_image_pieces_keep_an_overprinting_color() { + let im = crate::ImageObject { + key: "pic".into(), + width: 4, + height: 4, + xf: Affine::scale(10.0), + link: None, + placement: Default::default(), + pixels: None, + }; + let mut n = Node::new(NodeId(3), NodeKind::Image(Box::new(im.clone()))); + n.extras_mut().colorize = Some(Box::new(Paint::solid(Color::BLACK))); + n.extras_mut().colorize_overprint = true; + for masked in [false, true] { + let g = mesh_warp_image(&n, &im, &|p| p, 2, false, masked); + let mut pieces = vec![]; + g.walk(&mut |c| { + if matches!(c.kind, NodeKind::Image(_)) { + pieces.push(c.colorize_overprints()); + } + }); + assert_eq!(pieces, [true; 8], "masked {masked}"); + } + } + /// More cells than the objects live art may make cut no pieces (the count overflowed). #[test] fn mesh_warp_image_past_the_budget_makes_an_empty_group() { diff --git a/crates/doc/src/live/expand.rs b/crates/doc/src/live/expand.rs index e1eb3acc3d..f0b5d98879 100644 --- a/crates/doc/src/live/expand.rs +++ b/crates/doc/src/live/expand.rs @@ -231,13 +231,15 @@ pub(crate) fn mesh_warp_image_with( g.knockout = crate::Knockout::On; if let Some(e) = g.extras_if_any() { e.colorize = None; + e.colorize_overprint = false; e.image_quad = None; } if mesh_warp_cost(k) > MAX_GENERATED { return g; } - // A grayscale image's fill color colorizes each piece; the group of pieces takes none. - let colorize = n.extras().colorize.clone(); + // A grayscale image's fill color colorizes each piece, overprinting as the image's does; the + // group of pieces takes none. + let (colorize, colorize_overprint) = (n.extras().colorize.clone(), n.extras().colorize_overprint); // Each piece shows what the image shows: its color mask's masked pixels. let color_mask = n.extras().color_mask.clone(); let (pw, ph) = (im.width as f64, im.height as f64); @@ -271,6 +273,7 @@ pub(crate) fn mesh_warp_image_with( let mut image = Node::new(n.id, NodeKind::Image(Box::new(ImageObject { xf, ..im.clone() }))); image.extras_mut().pixelated = pixelated; image.extras_mut().colorize = colorize.clone(); + image.extras_mut().colorize_overprint = colorize_overprint; image.extras_mut().color_mask = color_mask.clone(); if masked { // Preserve Shape Using Transparency: the triangle is the piece's alpha (a diff --git a/crates/doc/src/node/extras.rs b/crates/doc/src/node/extras.rs index 439d3605fd..0eed9c7829 100644 --- a/crates/doc/src/node/extras.rs +++ b/crates/doc/src/node/extras.rs @@ -63,6 +63,10 @@ pub struct NodeExtras { /// colorizes it. Each pixel is drawn in this color, as opaque as the pixel is dark, so white /// pixels are transparent. `None`: the image shows its own pixels. pub colorize: Option>, + /// Attributes panel › Overprint Fill on a colorized image: its color prints over the inks + /// below instead of knocking them out. It counts only while [`Self::colorize`] is set + /// ([`crate::Node::colorize_overprints`]). + pub colorize_overprint: bool, /// Pathfinder panel › Make Compound Shape: this group is a compound shape /// ([`Node::is_compound_shape`], [`crate::compound_shape`]). pub compound_shape: bool, @@ -115,6 +119,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras { live_paint_gaps: None, objects_on_path: None, colorize: None, + colorize_overprint: false, compound_shape: false, shape_mode: crate::ShapeMode::Add, symbol_overrides: Vec::new(), diff --git a/crates/doc/src/node/wire.rs b/crates/doc/src/node/wire.rs index 60a3c75d79..d9642e7866 100644 --- a/crates/doc/src/node/wire.rs +++ b/crates/doc/src/node/wire.rs @@ -51,6 +51,7 @@ impl Serialize for Node { e.live_paint_gaps.is_none(), e.objects_on_path.is_none(), e.colorize.is_none(), + is_default(&e.colorize_overprint), is_default(&e.compound_shape), is_default(&e.shape_mode), e.symbol_overrides.is_empty(), @@ -99,6 +100,7 @@ impl Serialize for Node { field!("live_paint_gaps", &e.live_paint_gaps); field!("objects_on_path", &e.objects_on_path); field!("colorize", &e.colorize); + field!("colorize_overprint", &e.colorize_overprint); field!("compound_shape", &e.compound_shape); field!("shape_mode", &e.shape_mode); field!("symbol_overrides", &e.symbol_overrides); @@ -244,6 +246,8 @@ pub(super) struct NodeWire { #[serde(default)] colorize: Option>, #[serde(default)] + colorize_overprint: bool, + #[serde(default)] compound_shape: bool, #[serde(default)] shape_mode: crate::ShapeMode, @@ -477,6 +481,7 @@ impl From for Node { live_paint_gaps: w.live_paint_gaps, objects_on_path: w.objects_on_path, colorize: w.colorize, + colorize_overprint: w.colorize_overprint, compound_shape: w.compound_shape, shape_mode: w.shape_mode, symbol_overrides: w.symbol_overrides, diff --git a/crates/doc/src/overprint.rs b/crates/doc/src/overprint.rs index 58f6b5abc2..38a62e0341 100644 --- a/crates/doc/src/overprint.rs +++ b/crates/doc/src/overprint.rs @@ -2,11 +2,12 @@ //! over the inks below instead of knocking them out ([`crate::FillLayer::overprint`]). //! Edit → Edit Colors → Overprint Black sets it on black fills and strokes ([`OverprintBlack`]). +use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use vectorcraft_color::{BlendMode, Color, GradientKind, Paint}; -use crate::{Document, Node, NodeId, NodeKind}; +use crate::{Document, ImageBlob, Node, NodeId, NodeKind}; /// `Document.unknown` key of files from before per-fill/stroke overprint: the ids of objects /// marked Overprint Black ([`Document::migrate_overprint_black`]). @@ -65,7 +66,8 @@ impl OverprintBlack { } } - /// Set (or clear) the overprint of `n`'s own black fills and strokes and its characters'. + /// Set (or clear) the overprint of `n`'s own black fills and strokes, its characters' and, + /// for a colorized image, its color's. /// `spots`: the document's spot swatch names ([`Document::spot_names`]). Returns whether /// anything changed. pub fn apply(&self, n: &mut Node, spots: &[String]) -> bool { @@ -90,9 +92,18 @@ impl OverprintBlack { } } } + if self.colorize_black(n, spots) { + set(&mut n.extras_mut().colorize_overprint); + } changed } + /// Whether `n` is an image colorized with a black color that [`Self::fill`] covers: the color + /// of a gray or 1-bit image is its fill ([`crate::NodeExtras::colorize`]). + fn colorize_black(&self, n: &Node, spots: &[String]) -> bool { + self.fill && matches!(n.kind, NodeKind::Image(_)) && n.extras().colorize.as_deref().is_some_and(|p| self.black(p, spots)) + } + /// [`Self::apply`] to every node of `a`'s subtree, copying only the nodes on the way to those /// that change. Returns whether anything changed. pub fn apply_deep(&self, a: &mut Arc, spots: &[String]) -> bool { @@ -136,38 +147,138 @@ impl OverprintBlack { (self.fill && r.style.overprint_fill != on && self.black(&r.style.fill, spots)) || (self.stroke && r.style.overprint_stroke != on && self.black(&r.style.stroke, spots)) }; - n.appearance.items.iter().any(item) || matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(run)) + n.appearance.items.iter().any(item) + || matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(run)) + || (n.extras().colorize_overprint != on && self.colorize_black(n, spots)) } } impl Node { /// Whether any fill or stroke of this subtree overprints (characters' aside). pub fn has_overprint(&self) -> bool { - self.appearance.items.iter().any(|i| i.overprint()) || self.children().is_some_and(|c| c.iter().any(|c| c.has_overprint())) + self.appearance.items.iter().any(|i| i.overprint()) + || self.colorize_overprints() + || self.children().is_some_and(|c| c.iter().any(|c| c.has_overprint())) } + + /// Whether this is an image colorized with a color ([`crate::NodeExtras::colorize`]) that + /// overprints ([`crate::NodeExtras::colorize_overprint`]). + pub fn colorize_overprints(&self) -> bool { + let e = self.extras(); + matches!(self.kind, NodeKind::Image(_)) && e.colorize_overprint && e.colorize.as_deref().is_some_and(|p| !p.is_none()) + } +} + +/// Whether fill or stroke row `i` of an image draws: it is visible, has a paint and an opacity +/// above 0 (a stroke a width too) and a visible Convert to Shape or Outline Object, which gives a +/// row on an image a shape of its own ([`crate::Effect::gives_image_shape`]). +pub fn image_row_draws(i: &crate::AppearanceItem) -> bool { + let width = match i { + crate::AppearanceItem::Stroke(s) => s.width > 0.0, + crate::AppearanceItem::Fill(_) => true, + }; + i.visible() && i.opacity() > 0.0 && !i.paint().is_none() && width && i.effects().iter().any(crate::Effect::gives_image_shape) +} + +/// Whether paint `paint` of blend mode `blend` darkens when `overprint` asks it to: with the +/// Normal blend, and not a white that `discard_white` knocks out ([`DiscardWhite::discards`]). +fn darkens(overprint: bool, blend: BlendMode, paint: &Paint, discard_white: &DiscardWhite) -> bool { + overprint && blend == BlendMode::Normal && !discard_white.discards(paint) +} + +/// The effects that only move or reshape what an object draws, keeping its own colors, besides +/// those whose ids start with `warp.`, `convertToShape.` or `addon.path.` ([`reshapes_only`]). +const RESHAPING_EFFECTS: [&str; 12] = [ + "distort.freeDistort", + "distort.puckerBloat", + "distort.roughen", + "distort.transform", + "distort.tweak", + "distort.twist", + "distort.zigZag", + "path.offsetPath", + "path.outlineObject", + "path.outlineStroke", + "stylize.roundCorners", + "stylize.scribble", +]; + +/// Whether effect `id` only moves or reshapes what an object draws ([`RESHAPING_EFFECTS`]). +/// Any other effect (a shadow, a glow, a raster effect, a color adjustment, a plug-in effect) +/// paints colors of its own. +pub fn reshapes_only(id: &str) -> bool { + ["warp.", "convertToShape.", "addon.path."].iter().any(|p| id.starts_with(p)) || RESHAPING_EFFECTS.contains(&id) +} + +/// Whether `n` is an image with no pixels of its own and a colorize paint. +pub fn is_colorized_image(n: &Node) -> bool { + matches!(n.kind, NodeKind::Image(ref im) if im.pixels.is_none()) && n.extras().colorize.is_some() +} + +/// The key of the pixels colorized image `n` shows in `images`: its color mask's when the mask +/// was made for it and is there ([`Document::shown_image`]), else its own. `None` for any other +/// node. +pub fn colorized_shown_key(n: &Node, images: &BTreeMap) -> Option { + match &n.kind { + NodeKind::Image(im) if is_colorized_image(n) => { + let mask = Document::color_mask_of(n).filter(|m| m.made_for(im) && images.contains_key(&m.key)); + Some(mask.map_or(&im.key, |m| &m.key).clone()) + } + _ => None, + } +} + +/// Whether colorized image `n` shows pixels in `images` that don't take its colorize paint +/// ([`ImageBlob::takes_colorize`]), so it is drawn and separated as those pixels and not as its +/// color. +pub fn refuses_colorize(n: &Node, images: &BTreeMap) -> bool { + colorized_shown_key(n, images).and_then(|key| images.get(&key)).is_some_and(|b| !b.takes_colorize()) +} + +/// Whether colorized image `n` is drawn overprinting as a whole: its color overprints +/// ([`Node::colorize_overprints`]) with the Normal blend and is not a white `discard_white` knocks out, +/// the pixels it shows in `images` take its color ([`refuses_colorize`]), each of its own visible +/// effects only reshapes it ([`reshapes_only`]), and each row that draws ([`image_row_draws`]) +/// overprints that way too. A colorized image's color is not a fill row, so the whole node +/// overprints or none of it does. +pub fn image_overprints_whole(n: &Node, discard_white: &DiscardWhite, images: &BTreeMap) -> bool { + let row = |i: &crate::AppearanceItem| match i { + crate::AppearanceItem::Fill(l) => darkens(l.overprint, l.blend, &l.paint, discard_white), + crate::AppearanceItem::Stroke(l) => darkens(l.overprint, l.blend, &l.paint, discard_white), + }; + let paints_past = n.appearance.effects.iter().any(|e| e.visible && !reshapes_only(&e.id)); + n.colorize_overprints() + && n.extras().colorize.as_deref().is_some_and(|p| darkens(true, n.blend, p, discard_white)) + && !paints_past + && n.appearance.items.iter().filter(|i| image_row_draws(i)).all(row) + && !refuses_colorize(n, images) } /// Draw the overprinting fills and strokes of `a`'s subtree with Darken (those with a blend /// mode of their own keep it), copying only the nodes on the way to them: on screen and on a /// printed plate this approximates their inks printing over the inks below. Darken keeps the /// stronger ink of each plate (and each additive channel), so a colour overprinting itself stays -/// that colour, where Multiply would darken it. With `discard_white` -/// (Document Setup → Discard White Overprint) white fills and strokes knock out instead. -pub fn darken_overprints(a: &mut Arc, discard_white: bool) { +/// that colour, where Multiply would darken it. White fills and strokes that `discard_white` +/// (Document Setup → Discard White Overprint) knocks out do so instead. A colorized image +/// darkens as a whole ([`image_overprints_whole`], with the document's `images`). +pub fn darken_overprints(a: &mut Arc, discard_white: &DiscardWhite, images: &BTreeMap) { if !a.has_overprint() { return; } let n = Arc::make_mut(a); - let darkens = |overprint: bool, blend: BlendMode, paint: &Paint| overprint && blend == BlendMode::Normal && !(discard_white && is_white(paint)); + let whole = image_overprints_whole(n, discard_white, images); for it in &mut n.appearance.items { match it { - crate::AppearanceItem::Fill(l) if darkens(l.overprint, l.blend, &l.paint) => l.blend = BlendMode::Darken, - crate::AppearanceItem::Stroke(l) if darkens(l.overprint, l.blend, &l.paint) => l.blend = BlendMode::Darken, + crate::AppearanceItem::Fill(l) if darkens(l.overprint, l.blend, &l.paint, discard_white) => l.blend = BlendMode::Darken, + crate::AppearanceItem::Stroke(l) if darkens(l.overprint, l.blend, &l.paint, discard_white) => l.blend = BlendMode::Darken, _ => {} } } + if whole { + n.blend = BlendMode::Darken; + } for c in n.children_mut().into_iter().flatten() { - darken_overprints(c, discard_white); + darken_overprints(c, discard_white, images); } } @@ -182,12 +293,53 @@ pub fn is_white(p: &Paint) -> bool { } } +/// Discard White Overprint (Document Setup) as output applies it: whether it is on, and the spot +/// inks a white tint of which still overprints ([`Document::spot_ink`]). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct DiscardWhite { + on: bool, + spot_inks: BTreeSet, +} + +impl DiscardWhite { + /// The document's setting and spot inks. + pub fn of(doc: &Document) -> Self { + let spot_inks = doc.swatches_iter().map(|s| &s.name).filter(|n| doc.swatch(n).is_some_and(|s| s.spot && s.paint.color().is_some())); + Self { on: doc.setup.discard_white_overprint, spot_inks: spot_inks.cloned().collect() } + } + + /// The setting `on`, with no spot inks. + pub fn new(on: bool) -> Self { + Self { on, spot_inks: BTreeSet::new() } + } + + /// Whether `p` loses its overprint: the setting is on and `p` is paper white + /// ([`is_white`]), not a tint above 0% of a spot ink, which prints as that ink. + pub fn discards(&self, p: &Paint) -> bool { + let spot = matches!(p, Paint::Solid { swatch: Some(name), tint, .. } if *tint > 0.0 && self.spot_inks.contains(name)); + self.on && is_white(p) && !spot + } +} + impl Document { /// The names of the spot swatches. pub fn spot_names(&self) -> Vec { self.swatches_iter().filter(|s| s.spot).map(|s| s.name.clone()).collect() } + /// Whether `p` is a tint above 0% of a spot swatch with a solid color, which prints as an ink + /// of its own even when its color is white ([`is_white`]); a link is judged by the first + /// swatch of its name. + pub fn spot_ink(&self, p: &Paint) -> bool { + matches!(p, Paint::Solid { swatch: Some(name), tint, .. } if *tint > 0.0 && self.swatch(name).is_some_and(|s| s.spot && s.paint.color().is_some())) + } + + /// Whether Discard White Overprint (Document Setup) takes the overprint off `p` + /// ([`DiscardWhite::discards`]). + pub fn discards_white_overprint(&self, p: &Paint) -> bool { + self.setup.discard_white_overprint && is_white(p) && !self.spot_ink(p) + } + /// Files from before per-fill/stroke overprint listed the objects marked Overprint Black /// under [`LEGACY_OVERPRINT_KEY`]: their 100% black fills and strokes overprint now. pub fn migrate_overprint_black(&mut self) { @@ -208,6 +360,7 @@ impl Document { /// Whether any fill or stroke of `n`'s subtree overprints, characters' too. fn overprints_anywhere(n: &Node) -> bool { n.appearance.items.iter().any(|i| i.overprint()) + || 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))) } @@ -227,6 +380,10 @@ pub fn clear_overprints(a: &mut Arc) { (r.style.overprint_fill, r.style.overprint_stroke) = (false, false); } } + // Also the flag an image keeps after its color is removed. + if n.extras().colorize_overprint { + n.extras_mut().colorize_overprint = false; + } for c in n.children_mut().into_iter().flatten() { clear_overprints(c); } @@ -348,6 +505,178 @@ mod tests { assert!(Arc::ptr_eq(&group, &marked), "and nothing is copied"); } + /// A gray image colorized with `color`, its color overprinting, with the fill row `fill`. + fn colorized(color: Paint, fill: Paint) -> Node { + let im = crate::ImageObject { + key: "pic".into(), + width: 1, + height: 1, + xf: vectorcraft_geom::Affine::IDENTITY, + link: None, + placement: Default::default(), + pixels: None, + }; + let mut n = Node::new(NodeId(1), NodeKind::Image(Box::new(im))); + n.appearance = Appearance::basic(fill, Paint::None, 0.0).into(); + n.extras_mut().colorize = Some(Box::new(color)); + n.extras_mut().colorize_overprint = true; + n + } + + #[test] + fn a_white_colorized_image_knocks_out_under_discard_white() { + let image = |color: Paint, discard_white: bool| { + let mut a = Arc::new(colorized(color, Paint::None)); + darken_overprints(&mut a, &DiscardWhite::new(discard_white), &BTreeMap::new()); + a.blend + }; + let white = Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 0.0)); + assert_eq!(image(white.clone(), true), BlendMode::Normal, "white knocks out, as a white fill does"); + assert_eq!(image(white, false), BlendMode::Darken); + assert_eq!(image(cmyk(0.0, 0.0, 0.0, 1.0), true), BlendMode::Darken); + } + + /// A tint above 0% of a spot ink whose color is white keeps overprinting with Discard White + /// Overprint, as an image's color and as a fill; a 0% tint, a process white and a swatch that + /// is not spot knock out. + #[test] + fn a_white_spot_ink_keeps_overprinting_under_discard_white() { + let mut doc = Document::new(100.0, 100.0); + let white = Color::cmyk(0.0, 0.0, 0.0, 0.0); + doc.swatches.push(crate::Swatch { name: "White Ink".into(), paint: Paint::solid(white), global: true, spot: true }); + doc.swatches.push(crate::Swatch { name: "Paper".into(), paint: Paint::solid(white), global: true, spot: false }); + doc.setup.discard_white_overprint = true; + let discard = DiscardWhite::of(&doc); + let linked = |name: &str, tint: f32| Paint::Solid { color: white, swatch: Some(name.into()), tint }; + let blend = |color: Paint, fill: Paint| { + let mut n = colorized(color, Paint::None); + if let Some(f) = n.appearance.fill_mut() { + f.paint = fill; + f.overprint = true; + } + let mut a = Arc::new(n); + darken_overprints(&mut a, &discard, &BTreeMap::new()); + (a.blend, a.appearance.fill().map(|f| f.blend)) + }; + let spot = linked("White Ink", 0.5); + assert_eq!(blend(spot.clone(), spot.clone()), (BlendMode::Darken, Some(BlendMode::Darken))); + assert!(doc.spot_ink(&spot) && !discard.discards(&spot)); + for knocks_out in [linked("White Ink", 0.0), linked("Paper", 1.0), Paint::solid(white)] { + assert!(discard.discards(&knocks_out), "{knocks_out:?}"); + assert_eq!(blend(knocks_out.clone(), knocks_out.clone()).0, BlendMode::Normal, "{knocks_out:?}"); + } + assert!(!DiscardWhite::new(false).discards(&Paint::solid(white))); + } + + #[test] + fn a_colorized_image_showing_pixels_that_refuse_its_color_keeps_knocking_out() { + let blend = |images: &BTreeMap| { + let mut a = Arc::new(colorized(cmyk(0.0, 0.0, 0.0, 1.0), Paint::None)); + darken_overprints(&mut a, &DiscardWhite::new(false), images); + a.blend + }; + let bytes = crate::links::missing_placeholder().unwrap(); + let preview = Arc::new(bytes.clone()); + let shown = ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview), file_font: Default::default() }; + assert!(!shown.takes_colorize()); + assert_eq!(blend(&BTreeMap::from([("pic".to_string(), shown)])), BlendMode::Normal, "a full-color preview is drawn as it is"); + let own = ImageBlob::new("image/png", bytes); + assert_eq!(blend(&BTreeMap::from([("pic".to_string(), own)])), BlendMode::Darken, "the image's own pixels take the color"); + } + + #[test] + fn a_colorized_image_darkens_unless_its_rows_draw_an_effect() { + let blend = |effect: Option<(&str, bool)>, overprint: bool| { + let mut n = colorized(cmyk(0.0, 0.0, 0.0, 1.0), cmyk(1.0, 0.0, 0.0, 0.0)); + if let Some(f) = n.appearance.fill_mut() { + f.overprint = overprint; + if let Some((id, visible)) = effect { + f.effects.push(crate::Effect { id: id.into(), params: serde_json::json!({}), visible }); + } + } + let mut a = Arc::new(n); + darken_overprints(&mut a, &DiscardWhite::new(false), &BTreeMap::new()); + a.blend + }; + let shape = "convertToShape.rectangle"; + assert_eq!(blend(None, false), BlendMode::Darken, "a row with no effect paints nothing on an image"); + assert_eq!(blend(Some((shape, false)), false), BlendMode::Darken, "nor one whose effect is hidden"); + assert_eq!(blend(Some(("path.offsetPath", true)), false), BlendMode::Darken, "nor one whose effect gives it no shape"); + assert_eq!(blend(Some((shape, true)), false), BlendMode::Normal, "a knocking-out row drawn by its effect keeps knocking out"); + assert_eq!(blend(Some(("path.outlineObject", true)), false), BlendMode::Normal, "Outline Object gives a row a shape too"); + assert_eq!(blend(Some((shape, true)), true), BlendMode::Darken, "with an overprinting row the whole image overprints"); + } + + #[test] + fn a_colorized_image_darkens_past_a_row_with_no_opacity() { + let blend = |stroke: bool, opacity: f32| { + let mut n = colorized(cmyk(0.0, 0.0, 0.0, 1.0), Paint::None); + let effect = crate::Effect { id: "convertToShape.rectangle".into(), params: serde_json::json!({}), visible: true }; + if stroke { + if let Some(s) = n.appearance.stroke_mut() { + s.paint = cmyk(1.0, 0.0, 0.0, 0.0); + s.width = 1.0; + s.opacity = opacity; + s.effects.push(effect); + } + } else if let Some(f) = n.appearance.fill_mut() { + f.paint = cmyk(1.0, 0.0, 0.0, 0.0); + f.opacity = opacity; + f.effects.push(effect); + } + let mut a = Arc::new(n); + darken_overprints(&mut a, &DiscardWhite::new(false), &BTreeMap::new()); + a.blend + }; + assert_eq!(blend(false, 0.0), BlendMode::Darken, "a fill with no opacity paints nothing"); + assert_eq!(blend(true, 0.0), BlendMode::Darken, "nor a stroke with no opacity"); + assert_eq!(blend(false, 0.5), BlendMode::Normal, "a fill with some opacity still knocks out"); + assert_eq!(blend(true, 0.5), BlendMode::Normal, "and so does a stroke"); + } + + #[test] + fn a_colorized_image_with_a_node_effect_keeps_knocking_out() { + let blend = |id: &str, visible: bool| { + let mut n = colorized(cmyk(0.0, 0.0, 0.0, 1.0), Paint::None); + n.appearance.effects.push(crate::Effect { id: id.into(), params: serde_json::json!({}), visible }); + let mut a = Arc::new(n); + darken_overprints(&mut a, &DiscardWhite::new(false), &BTreeMap::new()); + a.blend + }; + assert_eq!(blend("stylize.dropShadow", true), BlendMode::Normal, "a drop shadow is not darkened with the image"); + assert_eq!(blend("stylize.outerGlow", true), BlendMode::Normal, "nor an outer glow"); + assert_eq!(blend("stylize.innerGlow", true), BlendMode::Normal, "nor an inner glow"); + assert_eq!(blend("artistic.neonGlow", true), BlendMode::Normal, "nor a raster effect"); + assert_eq!(blend("stylize.dropShadow", false), BlendMode::Darken, "a hidden effect draws nothing"); + assert_eq!(blend("distort.roughen", true), BlendMode::Darken, "a geometry effect reshapes the image itself"); + assert_eq!(blend("warp.arc", true), BlendMode::Darken, "so does a warp"); + } + + #[test] + fn overprint_black_takes_a_black_colorized_image() { + let off = |mut n: Node| { + n.extras_mut().colorize_overprint = false; + Arc::new(n) + }; + let mut a = off(colorized(cmyk(0.0, 0.0, 0.0, 1.0), Paint::None)); + assert!(!OverprintBlack { fill: false, ..Default::default() }.apply_deep(&mut a, &[]), "the color is the image's fill"); + assert!(OverprintBlack::default().apply_deep(&mut a, &[]) && a.colorize_overprints()); + assert!(!OverprintBlack::default().apply_deep(&mut a, &[]), "nothing left to change"); + assert!(OverprintBlack { remove: true, ..Default::default() }.apply_deep(&mut a, &[]) && !a.colorize_overprints()); + let mut cyan = off(colorized(cmyk(1.0, 0.0, 0.0, 0.0), Paint::None)); + assert!(!OverprintBlack::default().apply_deep(&mut cyan, &[]), "a cyan image is not black"); + } + + #[test] + fn clearing_overprints_clears_the_flag_of_an_image_without_a_color() { + let mut n = colorized(cmyk(0.0, 0.0, 0.0, 1.0), Paint::None); + n.extras_mut().colorize = None; + let mut a = Arc::new(n); + clear_overprints(&mut a); + Arc::make_mut(&mut a).extras_mut().colorize = Some(Box::new(cmyk(0.0, 0.0, 0.0, 1.0))); + assert!(!a.colorize_overprints(), "a color given later knocks out"); + } + #[test] fn legacy_overprint_black_list_migrates() { let mut d = Document::new(100.0, 100.0); diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index c7ab85e7a8..ee68067d2f 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -495,10 +495,9 @@ fn add_to_instance(n: &mut Node, fill: &[Effect], stroke: &[Effect]) { } /// Does effect `e` give an image's fill or stroke a shape to paint (a visible Convert to Shape or -/// Outline Object)? +/// Outline Object, [`Effect::gives_image_shape`])? fn gives_shape(e: &Effect) -> bool { - e.visible - && matches!(e.id.as_str(), "convertToShape.rectangle" | "convertToShape.roundedRectangle" | "convertToShape.ellipse" | "path.outlineObject") + e.gives_image_shape() } /// Does `item`, a fill or stroke of an image, paint something: does it paint and carry an effect @@ -1277,6 +1276,7 @@ fn as_art_opts( { let mut e = image.extras_mut(); e.colorize = n.extras().colorize.clone(); + e.colorize_overprint = n.extras().colorize_overprint; e.pixelated = n.extras().pixelated; e.color_mask = n.extras().color_mask.clone(); e.image_quad = n.extras().image_quad.clone(); diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs index 348d21ba38..3b0acaa821 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -148,6 +148,14 @@ fn nine_slice_painted_effects_are_raster_effects() { } } +/// The effects that leave a colorized image overprinting as a whole are the geometry effects. +#[test] +fn image_overprint_reshaping_effects_are_the_geometry_effects() { + for id in crate::catalog::catalog_index().keys() { + assert_eq!(vectorcraft_doc::overprint::reshapes_only(id), is_geometry(id), "{id}"); + } +} + #[test] fn open_paths_stay_open() { let line = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(50.0, 20.0), Point::new(100.0, 0.0)], false)); @@ -701,21 +709,22 @@ fn a_nested_groups_gradient_follows_its_warped_image() { } /// An image under a geometry effect other than a Warp draws as the image does: colorized by -/// a grayscale image's fill color, and smoothed or not. +/// a grayscale image's fill color, overprinting as it does, and smoothed or not. #[test] fn an_image_under_a_geometry_effect_keeps_its_color_and_smoothing() { let mut n = (*warp_test_image(1)).clone(); n.appearance.effects = vec![fx("distort.roughen", json!({"size": 5, "detail": 10}))]; n.extras_mut().colorize = Some(Box::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)))); + n.extras_mut().colorize_overprint = true; n.extras_mut().pixelated = true; let art = crate::reshape::reshape(None, &n, None).unwrap(); let mut seen = vec![]; art.walk(&mut |c| { if matches!(c.kind, NodeKind::Image(_)) { - seen.push((c.extras().colorize.clone(), c.extras().pixelated)); + seen.push((c.extras().colorize.clone(), c.colorize_overprints(), c.extras().pixelated)); } }); - assert_eq!(seen, vec![(n.extras().colorize.clone(), true)]); + assert_eq!(seen, vec![(n.extras().colorize.clone(), true, true)]); } /// What `effects` make of `path` within `budget`. diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs index 703d81ddc3..f17f93ff9b 100644 --- a/crates/engine/src/cmd/addons/color.rs +++ b/crates/engine/src/cmd/addons/color.rs @@ -52,7 +52,7 @@ pub fn specs() -> Vec { "Print Ink Fixes", ["Object", "Plug-ins", "Color Effects"], None, - "{scope?: \"selection\" (the selection, or `ids`; by default, the document while nothing is selected) | \"document\" (every layer), inkLimit?: total ink % 1..400 (0 or left out: off), excludePureBlack?: true (black-only and grey colours keep their ink), removeWhiteOverprint?: false (white fills and strokes stop overprinting), overprintBlack?: black % 1..100 (black-only and grey fills and strokes this dark or darker overprint, as edit.colors.overprintBlack; 0 or left out: off), textOnly?: false (Overprint Black on type only), fill?: true, stroke?: true, ids?: [id…]} prepare a CMYK document's inks for print as one undo step: CMYK colours (solid, gradient stops, gradient meshes) with more total ink than inkLimit are scaled down to it (colours of spot swatches and Registration stay), white overprint is removed and black overprint set. Refused in RGB documents (File › Document Color Mode › CMYK Color first). On a path directly in a graph series, the graph also stores a paint the ink limit changes on the topmost visible fill or stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, inkLimited: paints and meshes scaled, whiteOverprintRemoved: objects, blackOverprinted: objects}", + "{scope?: \"selection\" (the selection, or `ids`; by default, the document while nothing is selected) | \"document\" (every layer), inkLimit?: total ink % 1..400 (0 or left out: off), excludePureBlack?: true (black-only and grey colours keep their ink), removeWhiteOverprint?: false (white fills and strokes, and colorized images with a white color, stop overprinting), overprintBlack?: black % 1..100 (black-only and grey fills and strokes this dark or darker overprint, as edit.colors.overprintBlack; 0 or left out: off), textOnly?: false (Overprint Black on type only), fill?: true, stroke?: true, ids?: [id…]} prepare a CMYK document's inks for print as one undo step: CMYK colours (solid, gradient stops, gradient meshes) with more total ink than inkLimit are scaled down to it (colours of spot swatches and Registration stay), white overprint is removed and black overprint set. Refused in RGB documents (File › Document Color Mode › CMYK Color first). On a path directly in a graph series, the graph also stores a paint the ink limit changes on the topmost visible fill or stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, inkLimited: paints and meshes scaled, whiteOverprintRemoved: objects, blackOverprinted: objects}", has_doc, print_fixes::run ), diff --git a/crates/engine/src/cmd/addons/color/print_fixes.rs b/crates/engine/src/cmd/addons/color/print_fixes.rs index c5f430eb76..8440e597f0 100644 --- a/crates/engine/src/cmd/addons/color/print_fixes.rs +++ b/crates/engine/src/cmd/addons/color/print_fixes.rs @@ -98,6 +98,11 @@ impl Fixes { off(self.stroke, is_white(&r.style.stroke), &mut r.style.overprint_stroke); } } + // A colorized image's color is its fill. + if n.colorize_overprints() { + let white = n.extras().colorize.as_deref().is_some_and(is_white); + off(self.fill, white, &mut n.extras_mut().colorize_overprint); + } changed } diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 1b394fa95c..54e7a3bbf4 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -169,7 +169,7 @@ pub fn specs() -> Vec { "Overprint Black…", ["Edit", "Edit Colors"], None, - "{remove?: false, percentage?: 100, fill?: true, stroke?: true, includeCmyBlacks?: false, includeSpotBlacks?: false, ids?} make the black fills and/or strokes of the selection (or ids; groups: their contents; type: its characters) overprint, or stop (remove). Black: K ≥ percentage with no C, M or Y (any with includeCmyBlacks), not linked to a spot swatch (unless includeSpotBlacks); a gradient is black when every stop is → {changed: objects}", + "{remove?: false, percentage?: 100, fill?: true, stroke?: true, includeCmyBlacks?: false, includeSpotBlacks?: false, ids?} make the black fills and/or strokes of the selection (or ids; groups: their contents; type: its characters; a grayscale or 1-bit image colorized by paint.setFill: its color, as a fill) overprint, or stop (remove). Black: K ≥ percentage with no C, M or Y (any with includeCmyBlacks), not linked to a spot swatch (unless includeSpotBlacks); a gradient is black when every stop is → {changed: objects}", has_doc, super::overprint::overprint_black ), diff --git a/crates/engine/src/cmd/flatten/apply.rs b/crates/engine/src/cmd/flatten/apply.rs index 1525a97e1d..fe1e183d16 100644 --- a/crates/engine/src/cmd/flatten/apply.rs +++ b/crates/engine/src/cmd/flatten/apply.rs @@ -1154,11 +1154,16 @@ fn drop_own_overprints(n: &mut Node) { (r.style.overprint_fill, r.style.overprint_stroke) = (false, false); } } + // An image keeps the flag after its color is removed, and a later color would overprint. + if n.extras().colorize_overprint { + n.extras_mut().colorize_overprint = false; + } } } fn overprints(n: &Node) -> bool { n.appearance.items.iter().any(AppearanceItem::overprint) + || n.extras().colorize_overprint || matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke)) } diff --git a/crates/engine/src/cmd/overprint.rs b/crates/engine/src/cmd/overprint.rs index 4c0b3ea9f4..9256062e66 100644 --- a/crates/engine/src/cmd/overprint.rs +++ b/crates/engine/src/cmd/overprint.rs @@ -21,7 +21,7 @@ pub fn specs() -> Vec { "Overprint", [], None, - "{fill?: bool, stroke?: bool, item?: appearance item index|null, ids?|id?, target?: \"object\"|\"contents\"} make fills and/or strokes overprint (Overprint Preview, Separations Preview) or knock out: item's, else every fill or stroke of the painted objects (groups: their contents; type: its characters too). Without item and ids, the Appearance panel's active item stands in when it is of that kind. A whole Live Paint group (also its contents with `item`) takes the fill flags on its faces and the stroke flags on its edges, and its hidden source paths keep theirs → {changed: objects}", + "{fill?: bool, stroke?: bool, item?: appearance item index|null, ids?|id?, target?: \"object\"|\"contents\"} make fills and/or strokes overprint (Overprint Preview, Separations Preview) or knock out: item's, else every fill or stroke of the painted objects (groups: their contents; type: its characters too; a grayscale or 1-bit image colorized by paint.setFill: without item, the fill flags set whether its color overprints). Without item and ids, the Appearance panel's active item stands in when it is of that kind. A whole Live Paint group (also its contents with `item`) takes the fill flags on its faces and the stroke flags on its edges, and its hidden source paths keep theirs → {changed: objects}", has_doc, set_overprint ), @@ -97,9 +97,18 @@ fn flags(n: &Node, fill: bool, index: Option) -> Vec { if let (None, NodeKind::Text(t)) = (index, &n.kind) { v.extend(t.runs.iter().map(|r| if fill { r.style.overprint_fill } else { r.style.overprint_stroke })); } + if fill && index.is_none() && colorized(n) { + v.push(n.extras().colorize_overprint); + } v } +/// Is `n` an image colorized with a color, whose fill overprint is its color's +/// ([`vectorcraft_doc::NodeExtras::colorize_overprint`])? +fn colorized(n: &Node) -> bool { + matches!(n.kind, NodeKind::Image(_)) && n.extras().colorize.as_deref().is_some_and(|p| !p.is_none()) +} + /// [`flags`], to change. fn flags_mut(n: &mut Node, fill: bool, index: Option) -> Vec<&mut bool> { let mut v: Vec<&mut bool> = n @@ -178,6 +187,10 @@ pub(super) fn apply_overprint(d: &mut Document, jobs: &[OverprintJob], cmd: &str changed.insert(*id); } } + if *fill && index.is_none() && colorized(n) && n.extras().colorize_overprint != *on { + n.extras_mut().colorize_overprint = *on; + changed.insert(*id); + } } } Ok(()) diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 56c5a9e75e..d8fdcb310f 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -678,7 +678,13 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) characters.borrow_mut().push(n.id); } if index.is_none() && colorized.contains(&n.id) { - n.extras_mut().colorize = paint.color().map(|_| Box::new(paint.clone())); + let colorize = paint.color().map(|_| Box::new(paint.clone())); + // Without a color the image has nothing to overprint, and a later color starts + // knocking out. + if colorize.is_none() { + n.extras_mut().colorize_overprint = false; + } + n.extras_mut().colorize = colorize; return Ok(()); } if index.is_none() diff --git a/crates/engine/src/tests/colorize.rs b/crates/engine/src/tests/colorize.rs index 5a108d1695..00b20ca6a1 100644 --- a/crates/engine/src/tests/colorize.rs +++ b/crates/engine/src/tests/colorize.rs @@ -707,6 +707,131 @@ fn a_color_image_takes_a_fill_item_as_before() { assert!(s.doc().unwrap().doc.node(id).unwrap().appearance.fill().is_some(), "a fill item, as before"); } +#[test] +fn overprint_fill_makes_a_colorized_images_color_overprint() { + let mut s = session(); + let id = image(&mut s, "gray", gray(false)); + let overprints = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().colorize_overprints(); + // Before the image is colorized it has no fill to overprint. + let r = s.execute("object.setOverprint", &json!({"fill": true})).unwrap(); + assert_eq!(r["changed"], 0); + s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap(); + let r = s.execute("object.setOverprint", &json!({"fill": true})).unwrap(); + assert_eq!(r["changed"], 1); + assert!(overprints(&s)); + assert_eq!(s.execute("attributes.info", &json!({})).unwrap()["overprintFill"], true); + // A second time nothing changes, and no undo step is recorded. + let r = s.execute("object.setOverprint", &json!({"fill": true})).unwrap(); + assert_eq!(r["changed"], 0); + + // Native files keep it. + let d = &s.doc().unwrap().doc; + let back = vectorcraft_format::load(&vectorcraft_format::save(d, false)).unwrap(); + assert!(back.node(id).unwrap().colorize_overprints()); + + // EPS turns overprinting on for the image's ink. + let out = s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": false})).unwrap(); + let bytes = vectorcraft_format::base64_decode(out["dataBase64"].as_str().unwrap()).unwrap(); + let ps = String::from_utf8_lossy(&bytes); + let (Some(on), Some(mask)) = (ps.find("true op"), ps.find("imagemask")) else { panic!("{ps}") }; + assert!(on < mask, "overprint is on before the image is drawn"); + + // A legacy .ai file writes the image mask with its fill overprint, which opens again. + let r = s.execute("file.saveCopy", &json!({"format": "ai", "aiVersion": "7"})).unwrap(); + let mut t = Session::new(); + t.execute("document.open", &json!({"name": "t.ai", "dataBase64": r["dataBase64"]})).unwrap(); + let mut opened = vec![]; + t.doc().unwrap().doc.walk(|n| { + if matches!(n.kind, NodeKind::Image(_)) { + opened.push(n.colorize_overprints()); + } + }); + assert_eq!(opened, [true]); + + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!overprints(&s), "undo makes it knock out again"); + assert_eq!(s.execute("attributes.info", &json!({})).unwrap()["overprintFill"], false); + + // Taking the color off drops its overprint, so a new color knocks out. + s.execute("object.setOverprint", &json!({"fill": true})).unwrap(); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + assert!(!s.doc().unwrap().doc.node(id).unwrap().extras().colorize_overprint); + s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap(); + assert!(!overprints(&s), "a new color starts knocking out"); +} + +/// Overprint Black and Print Ink Fixes' Remove White Overprint treat a colorized image's color as +/// its fill. +#[test] +fn overprint_black_and_print_fixes_reach_a_colorized_images_color() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200, "colorMode": "cmyk"})).unwrap(); + let id = image(&mut s, "gray", gray(false)); + let overprints = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().colorize_overprints(); + s.execute("paint.setFill", &json!({"color": {"c": 0, "m": 0, "y": 0, "k": 100}})).unwrap(); + let v = s.execute("edit.colors.overprintBlack", &json!({})).unwrap(); + assert!(overprints(&s), "a black image overprints: {v}"); + s.execute("paint.setFill", &json!({"color": {"c": 0, "m": 0, "y": 0, "k": 0}})).unwrap(); + assert!(overprints(&s), "a new color keeps the flag"); + let v = s.execute("addon.color.printFixes", &json!({"removeWhiteOverprint": true})).unwrap(); + assert_eq!(v["whiteOverprintRemoved"], 1, "{v}"); + assert!(!overprints(&s), "white knocks out again"); +} + +/// A flattening for a file that writes colorized images in their ink (EPS) keeps the image, and +/// without Preserve Overprints its color knocks out again, as fills do; with it, the color keeps +/// overprinting. +#[test] +fn flattening_without_preserve_overprints_drops_a_colorized_images_overprint() { + let mut s = session(); + image(&mut s, "gray", gray(false)); + s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap(); + s.execute("object.setOverprint", &json!({"fill": true})).unwrap(); + // A translucent square elsewhere gives the flattener something to flatten. + let square = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("transparency.set", &json!({"ids": [square], "opacity": 50})).unwrap(); + let overprints = |preserve: bool| { + let mut options = crate::cmd::flatten::FlattenOptions::preset("low").unwrap(); + (options.keeps_colorize, options.preserve_overprints) = (true, preserve); + let flat = crate::cmd::flatten::flatten_document(&s.doc().unwrap().doc, &options).unwrap().unwrap(); + let mut found = vec![]; + flat.walk(|n| { + if matches!(n.kind, NodeKind::Image(_)) { + found.push(n.colorize_overprints()); + } + }); + found + }; + assert_eq!(overprints(true), [true]); + assert_eq!(overprints(false), [false]); +} + +/// Flattening without Preserve Overprints also clears the overprint an image keeps after its +/// color was removed, so a color given to it later knocks out. +#[test] +fn flattening_without_preserve_overprints_clears_an_uncolored_images_overprint() { + let mut s = session(); + let id = image(&mut s, "gray", gray(false)); + s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap(); + s.execute("object.setOverprint", &json!({"fill": true})).unwrap(); + let square = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("transparency.set", &json!({"ids": [square], "opacity": 50})).unwrap(); + let mut d = (*s.doc().unwrap().doc).clone(); + let Some(n) = d.node_mut(id) else { panic!("the image") }; + n.extras_mut().colorize = None; + assert!(n.extras().colorize_overprint && !n.colorize_overprints(), "the flag outlives the color"); + let mut options = crate::cmd::flatten::FlattenOptions::preset("low").unwrap(); + (options.keeps_colorize, options.preserve_overprints) = (true, false); + let flat = crate::cmd::flatten::flatten_document(&d, &options).unwrap().unwrap(); + let mut found = vec![]; + flat.walk(|n| { + if matches!(n.kind, NodeKind::Image(_)) { + found.push(n.extras().colorize_overprint); + } + }); + assert_eq!(found, [false]); +} + #[test] fn colorized_images_save_and_open_with_their_color() { let mut s = session(); diff --git a/crates/eps/src/import/ai/read/art.rs b/crates/eps/src/import/ai/read/art.rs index 3887da7f33..030c70aa51 100644 --- a/crates/eps/src/import/ai/read/art.rs +++ b/crates/eps/src/import/ai/read/art.rs @@ -821,7 +821,8 @@ impl<'a> Reader<'a> { } /// Add an image object with the state's transparency, `mask` as its opacity mask and - /// `colorize` as the color that colorizes it. + /// `colorize` as the color that colorizes it, which overprints while the fill overprint (`O`) + /// in force is on. fn add_image_colorized(&mut self, im: ImageObject, mask: Option, colorize: Option, hidden: bool) -> Result<(), String> { let gs = self.gs.clone(); let mut node = self.new_node(NodeKind::Image(Box::new(im)), &gs); @@ -829,6 +830,7 @@ impl<'a> Reader<'a> { node.blend = gs.blend; node.knockout_shape = gs.knockout_shape; node.extras_mut().mask = mask.map(Box::new); + node.extras_mut().colorize_overprint = colorize.is_some() && gs.overprint_fill; node.extras_mut().colorize = colorize.map(Box::new); self.add(node, hidden)?; self.image_tail = self.after_object; diff --git a/crates/eps/src/legacy_ai/prolog.rs b/crates/eps/src/legacy_ai/prolog.rs index 38058e6abd..10c1f65ec1 100644 --- a/crates/eps/src/legacy_ai/prolog.rs +++ b/crates/eps/src/legacy_ai/prolog.rs @@ -96,10 +96,10 @@ VCLegacy begin /_l 256 string def /_s 128 string def /_row {{currentfile _l readline not {exit} if dup length 1 gt {exit} if pop} loop dup length 1 gt {dup length 1 sub 1 exch getinterval /ASCIIHexDecode filter _s readstring pop} {pop ()} ifelse} bd -% An image mask (ImageMask 1) paints its 0 bits in the fill color. +% An image mask (ImageMask 1) paints its 0 bits in the fill color, with the fill overprint. /XI {1 eq /_im exch def pop pop pop /_ic exch def /_ib exch def /_ih exch def /_iw exch def pop pop pop pop [1 0 0 -1 0 0] exch matrix concatmatrix - _on {gsave concat _im {_fc _iw _ih false [1 0 0 1 0 0] /_row load imagemask} + _on {gsave concat _im {_fc _fo setoverprint _iw _ih false [1 0 0 1 0 0] /_row load imagemask} {_iw _ih _ib [1 0 0 1 0 0] /_row load false _ic 1 eq {1} {_ic} ifelse colorimage} ifelse grestore} {pop} ifelse} bd % Type (15) is set by the app that reads the file: its operators take their operands and mark % nothing; encodings (3.3) are skipped. diff --git a/crates/eps/src/legacy_ai/tests.rs b/crates/eps/src/legacy_ai/tests.rs index 2f5a528340..e43f2a1227 100644 --- a/crates/eps/src/legacy_ai/tests.rs +++ b/crates/eps/src/legacy_ai/tests.rs @@ -1039,7 +1039,8 @@ fn colorized_images_keep_their_color() { // Each row is a byte: the black pixels are 0 bits. assert_eq!(data, &["%6996"], "{text}"); let at = text.find("%AI5_File:\n").unwrap(); - assert!(text[..at].ends_with("0 0.5 1 0 k\n"), "{text}"); + // Its color, and its fill overprint off. + assert!(text[..at].ends_with("0 0.5 1 0 k\n0 O\n"), "{text}"); assert!(out.warnings.is_empty(), "{:?}", out.warnings); let read = crate::import(&out.bytes).unwrap().document; let mut found = vec![]; @@ -1066,6 +1067,45 @@ fn colorized_images_keep_their_color() { assert_eq!(out.warnings, [IMAGE_ALPHA]); } +/// A colorized image mask takes the fill overprint in force: its own `O`, or without one the +/// last `O` before it, as it takes the fill color. +#[test] +fn a_colorized_image_mask_takes_the_fill_overprint_in_force() { + let opened = |square_overprints: bool, image_overprints: bool, drop_own: bool| { + let mut doc = Document::new(200.0, 100.0); + doc.layers.clear(); + let layer = doc.add_layer(Some("Art")); + let mut square = shape(&mut doc, shapes::rectangle(Rect::new(5.0, 5.0, 45.0, 30.0)), red(), Paint::None); + if let Some(f) = square.appearance.fill_mut() { + f.overprint = square_overprints; + } + doc.insert(Some(layer), usize::MAX, square).unwrap(); + let paint = Paint::solid(Color::cmyk(0.0, 0.5, 1.0, 0.0)); + let mask: Vec = "1001011001101001".bytes().map(|b| if b == b'1' { 0 } else { 255 }).collect(); + let mut bitmap = colorized_image(&mut doc, (8, 2), mask, &paint, (10.0, 10.0)); + bitmap.extras_mut().colorize_overprint = image_overprints; + doc.insert(Some(layer), usize::MAX, bitmap).unwrap(); + let mut text = String::from_utf8(write(&doc).bytes).unwrap(); + if drop_own { + let own = format!("0 0.5 1 0 k\n{} O\n", u8::from(image_overprints)); + assert!(text.contains(&own), "{text}"); + text = text.replace(&own, "0 0.5 1 0 k\n"); + } + let read = crate::import(text.as_bytes()).unwrap().document; + let mut found = vec![]; + read.walk(|n| { + if matches!(n.kind, NodeKind::Image(_)) { + found.push(n.colorize_overprints()); + } + }); + found + }; + assert_eq!(opened(false, true, false), [true]); + assert_eq!(opened(true, false, false), [false]); + assert_eq!(opened(true, false, true), [true], "the square's overprint stays in force"); + assert_eq!(opened(false, true, true), [false], "and so does the square's knockout"); +} + /// The pieces of a colorized warped image work out the image's coverage once, and an image with /// other data works out its own: a black and white image's pieces are written as image masks /// in its color, and a gray image's pieces with its color in their pixels. diff --git a/crates/eps/src/legacy_ai/writer.rs b/crates/eps/src/legacy_ai/writer.rs index 2fa0fcb6c2..dfe159cb59 100644 --- a/crates/eps/src/legacy_ai/writer.rs +++ b/crates/eps/src/legacy_ai/writer.rs @@ -362,7 +362,7 @@ impl<'a> Writer<'a> { } None => im.xf, }; - self.image(blob, im.width, im.height, xf, colorize); + self.image(blob, im.width, im.height, xf, colorize.map(|p| (p, n.colorize_overprints()))); } NodeKind::SymbolInstance { symbol, xf } => { self.warn(LIVE); @@ -1129,13 +1129,14 @@ impl<'a> Writer<'a> { /// `%AI5_EndRaster`, then `F`. §8.4's examples have no `F`; without it, an app reading the file /// can leave out an image in a clipping group and the art after it. No path is open there, so /// the `F` paints nothing. `blob` holds the pixels, placed as a grid of `width` × `height` - /// by `xf`, and `colorize` is the solid color the image is colorized with. A colorized image - /// whose pixels are all black or white is written as an image mask (ImageMask 1, §8.1): its - /// color as the fill, then 1-bit samples, a 0 bit for each black pixel, which takes the color, - /// and a 1 bit for each white pixel, which is clear. Another colorized image is written with + /// by `xf`, and `colorize` is the solid color the image is colorized with and whether it + /// overprints. A colorized image whose pixels are all black or white is written as an image + /// mask (ImageMask 1, §8.1): its color as the fill with its fill overprint, then 1-bit + /// samples, a 0 bit for each black pixel, which takes the color, and a 1 bit for each white + /// pixel, which is clear. Another colorized image is written with /// its color in its pixels. In a clipping group, an image whose pixels were written whole /// already is written as the part of them the group shows ([`ai_ops::image_window`]). - fn image(&mut self, blob: Option<&ImageBlob>, width: u32, height: u32, xf: Affine, colorize: Option<&Paint>) { + fn image(&mut self, blob: Option<&ImageBlob>, width: u32, height: u32, xf: Affine, colorize: Option<(&Paint, bool)>) { let flip = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 0.0]); let m = self.to_art * xf * flip; if !invertible(m) { @@ -1157,12 +1158,12 @@ impl<'a> Writer<'a> { // The object places the image's own pixel grid (its width × height) wherever the file's is. let fit = Affine::scale_non_uniform(f64::from(width.max(1)) / f64::from(w), f64::from(height.max(1)) / f64::from(h)); let coverage = match colorize { - Some(paint) => { + Some((paint, overprint)) => { let Some((_, _, coverage)) = self.coverage(blob).filter(|(cw, ch, _)| (*cw, *ch) == (w, h)) else { self.warn(UNDECODED); return; }; - Some((paint, coverage)) + Some((paint, overprint, coverage)) } None => None, }; @@ -1179,7 +1180,7 @@ impl<'a> Writer<'a> { let (w, h) = (x1 - x0, y1 - y0); // Over white. let over = |c: u8, a: u8| ((u32::from(c) * u32::from(a) + 255 * (255 - u32::from(a)) + 127) / 255) as u8; - if let Some((paint, coverage)) = coverage { + if let Some((paint, overprint, coverage)) = coverage { let coverage = ai_ops::window_samples(&coverage, img.width(), 1, window); if coverage.iter().all(|&v| v == 0 || v == 255) { let stride = (w as usize).div_ceil(8); @@ -1191,6 +1192,7 @@ impl<'a> Writer<'a> { } } self.color(paint, false); + self.line(if overprint { "1 O" } else { "0 O" }); self.raster(m, &format!("0 0 {w} {h} {w} {h} 1 1 0 0 0 1"), &bits); return; } diff --git a/crates/eps/src/scene.rs b/crates/eps/src/scene.rs index 3d93703cd7..d80314978c 100644 --- a/crates/eps/src/scene.rs +++ b/crates/eps/src/scene.rs @@ -219,6 +219,13 @@ enum Ink { Spot { space: usize, tint: f32 }, } +/// One drawing of an overprinting colorized image: the name of the color space it is drawn in +/// and the amount of each of that space's inks ([`Scene::overprint_passes`]). +struct InkPass { + space: String, + values: Vec, +} + fn unit(v: f32) -> f32 { if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 } } @@ -589,8 +596,21 @@ impl<'a> Scene<'a> { let im = &*shown; let blob = self.doc.image_blob(im); match n.extras().colorize.as_deref() { + // On a plate, an overprinting image whose color puts none of the plate's ink + // down is drawn as nothing, as such a solid color is ([`Self::on_plate`]). + Some(p) + if self.plate + && self.o.overprint == Overprint::Preserve + && n.colorize_overprints() + && vectorcraft_doc::overprint::is_white(p) => {} + // Off a plate, a white process color knocks out with Discard White Overprint + // (a plate's colors come from the separator, which has applied it already); a + // spot ink with a white color still overprints, as it is written as that ink. Some(p @ Paint::Solid { .. }) if blob.is_none_or(|b| b.gray_source().is_some()) => { - self.colorized_image(&im.key, blob, im.width, im.height, im.xf, p); + let discarded = !self.plate && self.doc.discards_white_overprint(p); + let on = self.overprint_on(n.colorize_overprints() && !discarded); + self.colorized_image(im, blob, p, on); + self.overprint_off(on); } _ => self.image(&im.key, blob, im.width, im.height, im.xf), } @@ -1875,14 +1895,90 @@ impl<'a> Scene<'a> { i } - /// Gray coverage in the selected process or Separation ink. Binary coverage is a stencil; - /// continuous coverage leaves zero pixels untouched at Level 3 and writes them as paper at Level 2. - fn colorized_image(&mut self, key: &str, blob: Option<&ImageBlob>, width: u32, height: u32, xf: Affine, paint: &Paint) { - let place = xf * Affine::scale_non_uniform(f64::from(width.max(1)), f64::from(height.max(1))); + /// Image `im` (its pixels `blob`) as gray coverage in the selected process or Separation ink. + /// Binary coverage is a stencil; continuous coverage leaves zero pixels untouched at Level 3 + /// and writes them as paper at Level 2. With `overprint` a CMYK or gray color is written in only the + /// process inks it puts down ([`Self::overprint_passes`]), since a zero sample in an image + /// replaces the ink below it. + fn colorized_image(&mut self, im: &vectorcraft_doc::ImageObject, blob: Option<&ImageBlob>, paint: &Paint, overprint: bool) { + let place = im.xf * Affine::scale_non_uniform(f64::from(im.width.max(1)), f64::from(im.height.max(1))); if !invertible(place) { return; } - let cache = (key.to_string(), format!("{paint:?}")); + match overprint.then(|| self.overprint_passes(paint)).flatten() { + Some(passes) => { + // A pass turned away (at the page limit) takes back the passes before it, so the + // image is never written with some of its inks. + let (was, placed, codes) = (self.body.len(), self.placements.len(), self.codes.len()); + for pass in &passes { + let before = self.placements.len(); + self.colorized_pass(&im.key, blob, place, paint, Some(pass)); + if self.placements.len() == before { + self.body.truncate(was); + self.unplace(placed); + self.forget_codes(codes); + return; + } + } + } + None => self.colorized_pass(&im.key, blob, place, paint, None), + } + } + + /// The color spaces an overprinting colorized image of `paint` is drawn in, each with the + /// amounts of its inks, when `paint` is a CMYK or gray process color (gray is black ink): at + /// Level 3 one DeviceN space of the process inks it puts down, at Level 2 a Separation space + /// for each of them. No pass when it puts no ink down. `None` for another paint, which is drawn + /// as it is without overprinting. + fn overprint_passes(&mut self, paint: &Paint) -> Option> { + let Paint::Solid { color, swatch, tint } = paint else { return None }; + let c = match self.solid(color, swatch.as_deref(), *tint) { + Ink::Process(Space::Cmyk, c) => c, + // PostScript's gray is lightness. + Ink::Process(Space::Gray, [lightness, ..]) => [0.0, 0.0, 0.0, unit(1.0 - lightness)], + _ => return None, + }; + let process: Vec = (0..4).filter(|&i| c[i] > 0.0).collect(); + if process.is_empty() { + return Some(vec![]); + } + if self.o.level == Level::Three { + let GradientSpace::Inks(space, _) = self.device_n_space(&process, &[])? else { return None }; + return Some(vec![InkPass { space, values: process.iter().map(|&i| c[i]).collect() }]); + } + Some(process.iter().map(|&i| InkPass { space: self.process_separation(i), values: vec![c[i]] }).collect()) + } + + /// The name of a Separation color space of process ink `i` (an index into CMYK) alone, + /// defined in the setup the first time. + fn process_separation(&mut self, i: usize) -> String { + const SEPARATIONS: [&str; 4] = [ + "/Cyan /DeviceCMYK {0 0 0}", + "/Magenta /DeviceCMYK {0 exch 0 0}", + "/Yellow /DeviceCMYK {0 0 3 -1 roll 0}", + "/Black /DeviceCMYK {0 0 0 4 -1 roll}", + ]; + let def = format!("[/Separation {}]", SEPARATIONS[i.min(3)]); + let i = match self.device_n.iter().position(|d| *d == def) { + Some(i) => i, + None => { + let i = self.device_n.len(); + let _ = writeln!(self.setup, "/VCdn{i} {def} def"); + self.device_n.push(def); + i + } + }; + format!("VCdn{i}") + } + + /// One drawing of a colorized image on the unit square mapped by `place`: in `paint`, or with + /// `pass` in that pass's inks alone ([`Self::overprint_passes`]). + fn colorized_pass(&mut self, key: &str, blob: Option<&ImageBlob>, place: Affine, paint: &Paint, pass: Option<&InkPass>) { + let mut look = format!("{paint:?}"); + if let Some(pass) = pass { + let _ = write!(look, "\u{0}{} {:?}", pass.space, pass.values); + } + let cache = (key.to_string(), look); let encoded = match self.colorized_images.get(&cache) { Some(e) => *e, None => { @@ -1898,7 +1994,7 @@ impl<'a> Scene<'a> { { self.encodes += 1; } - let code = self.encode_colorized(blob, paint); + let code = self.encode_colorized(blob, paint, pass); // An image that can't be placed isn't kept. if let Some(c) = &code && self.size().saturating_add(c.inline_len).saturating_add(64) > self.max_body @@ -1917,7 +2013,8 @@ impl<'a> Scene<'a> { } } - fn encode_colorized(&mut self, blob: Option<&ImageBlob>, paint: &Paint) -> Option { + /// The operators and data of a colorized image of `paint`, or with `pass` of that pass's inks. + fn encode_colorized(&mut self, blob: Option<&ImageBlob>, paint: &Paint, pass: Option<&InkPass>) -> Option { let Some((w, h, coverage)) = blob.and_then(ImageBlob::coverage) else { self.warn(UNDECODED); return None; @@ -1937,13 +2034,20 @@ impl<'a> Scene<'a> { if !binary && clear && !keyed { self.warn(IMAGE_ALPHA_L2); } - // Zero tint is uncommon for covered spot pixels; process uses the same rare key as - // ordinary images. Nudge a covered collision so only clear pixels match the mask. + // Zero tint is uncommon for covered spot pixels (and those of a pass's inks); process + // uses the same rare key as ordinary images. Nudge a covered collision so only clear + // pixels match the mask. let key = match ink { + _ if pass.is_some() => [0, 0, 0, 0], Ink::Spot { .. } => [0, 0, 0, 0], Ink::Process(Space::Gray, ..) => [0, 0, 0, 0], Ink::Process(..) => [255, 0, 255, 0], }; + let n = match (pass, ink) { + (Some(pass), _) => pass.values.len(), + (None, Ink::Spot { .. }) => 1, + (None, Ink::Process(space, ..)) => space.n(), + }; let mut data = Vec::new(); if binary { let stride = (w as usize).div_ceil(8); @@ -1958,14 +2062,21 @@ impl<'a> Scene<'a> { } else { for &v in &coverage { if v == 0 && keyed { - let n = match ink { - Ink::Spot { .. } => 1, - Ink::Process(space, ..) => space.n(), - }; data.extend(key.iter().take(n)); continue; } let a = f32::from(v) / 255.0; + if let Some(pass) = pass { + let mut samples: Vec = pass.values.iter().map(|&v| (255.0 * v * a).round() as u8).collect(); + if keyed + && samples.iter().all(|&s| s == 0) + && let Some(first) = samples.first_mut() + { + *first = 1; + } + data.extend(samples); + continue; + } match ink { Ink::Spot { tint, .. } => { let mut sample = (255.0 * tint * a).round() as u8; @@ -1999,7 +2110,17 @@ impl<'a> Scene<'a> { } }; let mut prelude = String::new(); - if binary { + if let Some(pass) = pass { + let _ = write!(prelude, "{} setcolorspace", pass.space); + if binary { + // imagemask takes its current ink from the graphics state. + for v in &pass.values { + let _ = write!(prelude, " {}", ps::num(f64::from(*v))); + } + prelude.push_str(" setcolor"); + } + prelude.push('\n'); + } else if binary { // imagemask takes its current ink from the graphics state. prelude.push_str(&self.ink_code(ink)); } else { @@ -2012,10 +2133,6 @@ impl<'a> Scene<'a> { } } } - let n = match ink { - Ink::Spot { .. } => 1, - Ink::Process(space, ..) => space.n(), - }; let decode = if binary { "1 0".to_string() } else { "0 1 ".repeat(n).trim_end().to_string() }; let mut dict = format!( "<< /ImageType {} /Width {w} /Height {h} /BitsPerComponent {} /Decode [{decode}] /ImageMatrix [{w} 0 0 {h} 0 0]", diff --git a/crates/eps/src/tests.rs b/crates/eps/src/tests.rs index e6161da23d..f505dbc0ec 100644 --- a/crates/eps/src/tests.rs +++ b/crates/eps/src/tests.rs @@ -1163,6 +1163,130 @@ fn continuous_colorized_coverage_without_clear_pixels_only_warns_for_midtones() assert_eq!(&pixels[6..], &[255, 0, 255]); } +/// A CMYK document holding [`colorized_doc`]'s image of `gray` colorized with `color`, its color +/// overprinting or not. +fn overprinting_colorized_doc(gray: Vec, color: Color, overprint: bool) -> Document { + let mut d = colorized_doc(gray, Some(Paint::solid(color))); + d.color_mode = vectorcraft_doc::ColorMode::Cmyk; + let id = d.layers[0].children().unwrap()[0].id; + d.node_mut(id).unwrap().extras_mut().colorize_overprint = overprint; + d +} + +/// At the page limit the Level 2 passes of an overprinting colorized image are left out +/// together: the image is never written with some of its inks. +#[test] +fn an_overprinting_colorized_image_at_the_page_limit_keeps_all_its_inks_or_none() { + let gray: Vec = (0..2000u32).map(|i| (i * 37 % 251) as u8).collect(); + let one = overprinting_colorized_doc(gray.clone(), Color::cmyk(0.0, 0.0, 0.0, 1.0), true); + let two = overprinting_colorized_doc(gray, Color::cmyk(0.4, 0.0, 0.0, 1.0), true); + let o = EpsOptions { level: Level::Two, ..opts(&two) }; + let (one, all) = (crate::scene::Scene::new(&one, &o).run().body.len(), crate::scene::Scene::new(&two, &o).run().body.len()); + assert!(all > one + 1000, "{one} {all}"); + let page = crate::scene::Scene::new(&two, &o).with_max_body(one + (all - one) / 2).run(); + assert!(page.warnings.iter().any(|w| w.contains("too large")), "{:?}", page.warnings); + assert!(!page.body.contains("image") && !page.body.contains("VCdn"), "{}", page.body); +} + +/// An overprinting colorized image in a CMYK color is written in only the process inks it puts +/// down, so the plates it leaves at zero keep the inks below: one DeviceN image at Level 3, a +/// Separation image for each ink at Level 2. Not overprinting, it stays one CMYK image. +#[test] +fn an_overprinting_colorized_image_writes_only_its_process_inks() { + let doc = overprinting_colorized_doc; + let ink = Color::cmyk(0.4, 0.0, 0.0, 1.0); + let d = doc(vec![0, 128, 255], ink, true); + + let (ps, pixels, _) = colorized_samples(&d, Level::Three); + assert!(ps.contains("/VCdn0 [/DeviceN [/Cyan /Black ] /DeviceCMYK") && ps.contains("VCdn0 setcolorspace"), "{ps}"); + assert!(!ps.contains("/DeviceCMYK setcolorspace") && ps.contains("/MaskColor [0 0 0 0]"), "{ps}"); + assert_eq!(pixels, vec![102, 255, 51, 127, 0, 0]); + + let (ps, pixels, _) = colorized_samples(&d, Level::Two); + assert!(ps.contains("/VCdn0 [/Separation /Cyan /DeviceCMYK {0 0 0}] def"), "{ps}"); + assert!(ps.contains("/VCdn1 [/Separation /Black /DeviceCMYK {0 0 0 4 -1 roll}] def"), "{ps}"); + assert!(ps.contains("VCdn0 setcolorspace") && ps.contains("VCdn1 setcolorspace") && !ps.contains("/DeviceN"), "{ps}"); + assert_eq!(pixels, vec![102, 51, 0], "the cyan pass first"); + assert_eq!(ps.matches("/ImageType 1").count(), 2, "one image per ink: {ps}"); + + // A gray color is black ink alone. + let gray = doc(vec![0, 128, 255], Color::Gray { k: 0.6 }, true); + for level in Level::ALL { + let (ps, ..) = colorized_samples(&gray, level); + assert!(ps.contains("/Black") && !ps.contains("/DeviceGray setcolorspace") && !ps.contains("/Cyan"), "{ps}"); + } + + // A stencil sets the pass's inks as its color. + let (ps, ..) = colorized_samples(&doc(vec![0, 255, 0], ink, true), Level::Three); + assert!(ps.contains("VCdn0 setcolorspace 0.4 1 setcolor") && ps.contains("imagemask"), "{ps}"); + + // Without overprinting, and with overprints discarded, one CMYK image as before. + let off = doc(vec![0, 128, 255], ink, false); + let discarded = |d: &Document, level| text(&export(d, &EpsOptions { level, overprint: Overprint::Discard, ..opts(d) }, None, None).unwrap()); + for level in Level::ALL { + for ps in [colorized_samples(&off, level).0, discarded(&d, level)] { + assert!(ps.contains("/DeviceCMYK setcolorspace") && !ps.contains("VCdn"), "{ps}"); + } + } + + // Paper white that overprints (Discard White Overprint off) puts no ink down. + let mut white = doc(vec![0, 128, 255], Color::cmyk(0.0, 0.0, 0.0, 0.0), true); + white.setup.discard_white_overprint = false; + for level in Level::ALL { + let ps = page_of(&white, &EpsOptions { level, ..opts(&white) }); + assert!(!ps.contains("image"), "{ps}"); + } + // With Discard White Overprint on, it knocks out: one CMYK image, drawn without overprinting. + white.setup.discard_white_overprint = true; + for level in Level::ALL { + let ps = text(&export(&white, &EpsOptions { level, ..opts(&white) }, None, None).unwrap()); + assert!(ps.contains("/DeviceCMYK setcolorspace") && !ps.contains("VCdn") && !ps.contains("true op"), "{ps}"); + } + + // The same image and color placed overprinting and not keeps two encodings. + let mut both = d.clone(); + let mut n = (*both.layers[0].children().unwrap()[0]).clone(); + n.id = both.alloc_id(); + n.extras_mut().colorize_overprint = false; + both.insert(both.default_layer(), usize::MAX, n).unwrap(); + let ps = text(&export(&both, &EpsOptions { level: Level::Three, ..opts(&both) }, None, None).unwrap()); + assert!(ps.contains("VCdn0 setcolorspace") && ps.contains("/DeviceCMYK setcolorspace"), "{ps}"); +} + +/// On a separation plate, an overprinting colorized image whose color puts none of the plate's ink +/// down is drawn as nothing, so the ink below stays; one that knocks out, or whose overprint is +/// discarded, is drawn as paper. (The plate's colors come from the separator, which has already +/// applied Discard White Overprint.) +#[test] +fn a_plate_leaves_out_an_overprinting_image_without_its_ink() { + let body = |overprint: bool, preserve: bool| { + let mut d = colorized_doc(vec![0, 128, 255], Some(Paint::solid(Color::WHITE))); + d.setup.discard_white_overprint = false; + let id = d.layers[0].children().unwrap()[0].id; + d.node_mut(id).unwrap().extras_mut().colorize_overprint = overprint; + let o = EpsOptions { overprint: if preserve { Overprint::Preserve } else { Overprint::Discard }, ..opts(&d) }; + crate::scene::Scene::new(&d, &o).on_plate(true).run().body + }; + assert!(!body(true, true).contains("image"), "{}", body(true, true)); + assert!(body(false, true).contains("image"), "{}", body(false, true)); + assert!(body(true, false).contains("image"), "{}", body(true, false)); +} + +/// With Discard White Overprint on, an overprinting colorized image in a tint of a spot ink whose +/// color is white still overprints: it is written as that ink, which is not paper white. +#[test] +fn a_white_spot_ink_colorized_image_overprints_with_discard_white_overprint() { + let mut d = overprinting_colorized_doc(vec![0, 128, 255], Color::WHITE, true); + d.swatches.push(Swatch { name: "White Ink".into(), paint: Paint::solid(Color::WHITE), global: true, spot: true }); + let id = d.layers[0].children().unwrap()[0].id; + d.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::Solid { color: Color::WHITE, swatch: Some("White Ink".into()), tint: 0.5 })); + d.setup.discard_white_overprint = true; + for level in Level::ALL { + let ps = text(&export(&d, &EpsOptions { level, ..opts(&d) }, None, None).unwrap()); + assert!(ps.contains("(White Ink) cvn") && ps.contains("true op"), "{ps}"); + } +} + #[test] fn uncolorized_image_stays_on_original_eps_path() { let d = colorized_doc(vec![0, 128, 255], None); diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index 7e7dbbd5fc..454a86fc34 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -63,12 +63,18 @@ impl Exporter<'_> { /// missing or left out, its pixels can't be decoded, or its color channel exceeds /// [`vectorcraft_doc::MAX_RASTER_ALLOC`]; cached by key and paint (and size when images are /// resampled), image rejections too. - /// With `interpolate` (and the export's own setting), viewers may smooth it. - pub(super) fn colorized_image(&mut self, im: &vectorcraft_doc::ImageObject, paint: &Paint, interpolate: bool) -> Option { + /// With `interpolate` (and the export's own setting), viewers may smooth it. With `overprint` + /// a gray or CMYK color is written as a DeviceN space of the process inks it holds, so the plates it + /// leaves at zero keep the inks below: the nonzero overprint mode does not apply to an image's + /// samples (ISO 32000-1 §8.6.7). + pub(super) fn colorized_image(&mut self, im: &vectorcraft_doc::ImageObject, paint: &Paint, interpolate: bool, overprint: bool) -> Option { let Paint::Solid { color, swatch, tint } = paint else { return None }; let size = self.image_size(im); let interpolate = interpolate && self.interpolate; let mut cache = format!("{}\u{0}{paint:?}", im.key); + if overprint { + cache.push_str("\u{0}overprint"); + } if self.downsampled() { cache.push_str(&format!("\u{0}{:.3}x{:.3}", size.0, size.1)); } @@ -103,14 +109,24 @@ impl Exporter<'_> { } else { DeviceNSpace::new(spot_colorants) }; - let (samples, space) = match &device_n { - Some(d) if registration => (vec![q(*tint); d.colorants().len()], ImageColorspace::DeviceN), - Some(_) => (vec![q(*tint)], ImageColorspace::DeviceN), - None if registration => (vec![q(*tint); 4], ImageColorspace::Cmyk), + let (samples, space, device_n) = match &device_n { + Some(d) if registration => (vec![q(*tint); d.colorants().len()], ImageColorspace::DeviceN, Some(d.clone())), + Some(d) => (vec![q(*tint)], ImageColorspace::DeviceN, Some(d.clone())), + None if registration => (vec![q(*tint); 4], ImageColorspace::Cmyk, None), None => match self.page_color(color) { - Color::Gray { k } => (vec![q(1.0 - k)], ImageColorspace::Luma), - Color::Cmyk { c, m, y, k } => ([c, m, y, k].map(q).to_vec(), ImageColorspace::Cmyk), - other => (other.to_rgb().map(q).to_vec(), ImageColorspace::Rgb), + // An overprinting gray: black ink only. + Color::Gray { k } if overprint && k > 0.0 => { + (vec![q(k)], ImageColorspace::DeviceN, DeviceNSpace::new([Colorant::Process(Process::Black)])) + } + Color::Gray { k } => (vec![q(1.0 - k)], ImageColorspace::Luma, None), + // An overprinting CMYK color: the process inks it puts down. + Color::Cmyk { c, m, y, k } if overprint && [c, m, y, k].iter().any(|v| *v > 0.0) => { + let inks: Vec<(Process, f32)> = Process::ALL.into_iter().zip([c, m, y, k]).filter(|(_, v)| *v > 0.0).collect(); + let space = DeviceNSpace::new(inks.iter().map(|(p, _)| Colorant::Process(*p))); + (inks.iter().map(|(_, v)| q(*v)).collect(), ImageColorspace::DeviceN, space) + } + Color::Cmyk { c, m, y, k } => ([c, m, y, k].map(q).to_vec(), ImageColorspace::Cmyk, None), + other => (other.to_rgb().map(q).to_vec(), ImageColorspace::Rgb, None), }, }; if tinted_color_len(samples.len(), n).is_none() { @@ -465,10 +481,10 @@ mod tests { for key in ["missing", "bad", "left-out"] { let image = ImageObject { key: key.into(), width: 1, height: 1, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; - assert!(exporter.colorized_image(&image, &paint, true).is_none(), "{key}"); + assert!(exporter.colorized_image(&image, &paint, true, false).is_none(), "{key}"); let cache = format!("{key}\u{0}{paint:?}"); assert!(matches!(exporter.images.get(&cache), Some(None)), "rejection for {key} was not cached"); - assert!(exporter.colorized_image(&image, &paint, true).is_none(), "second call for {key}"); + assert!(exporter.colorized_image(&image, &paint, true, false).is_none(), "second call for {key}"); } assert_eq!(exporter.images.len(), 3); } @@ -500,7 +516,7 @@ mod tests { pixels: None, }; for scale in [10.0, 20.0] { - assert!(exporter.colorized_image(&image("pic", scale), &paint, true).is_some(), "colorized at {scale}"); + assert!(exporter.colorized_image(&image("pic", scale), &paint, true, false).is_some(), "colorized at {scale}"); let art = vectorcraft_doc::Node::new(doc.layers[0].id, vectorcraft_doc::NodeKind::Image(Box::new(image("alpha", scale)))); let mask = vectorcraft_doc::OpacityMask::new(art, true); let inks = image("inks", scale); diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index 1d514a569d..6a511260a2 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -434,12 +434,7 @@ impl Exporter<'_> { (Some(p @ Paint::Solid { .. }), im) if self.doc.image_blob(&im).is_none_or(vectorcraft_doc::ImageBlob::takes_colorize) => { let im = &*im; if writable(s, im.xf, Rect::new(0.0, 0.0, im.width.max(1).into(), im.height.max(1).into())) { - if let Some(colorized) = self.colorized_image(im, p, !n.extras().pixelated) { - self.image(s, im, Some(colorized), n.extras().pixelated); - } else { - self.image_left_out = self.image_left_out.map(|_| true); - self.warn(UNDECODED); - } + self.colorized(s, n, im, p); } else if self.image_left_out.is_some() { self.image_left_out = Some(true); self.warn(super::exporter::UNWRITABLE_IMAGE); @@ -527,6 +522,27 @@ impl Exporter<'_> { } } + /// Draw image `im` of node `n` colorized with `p` ([`Self::colorized_image`]), overprinting + /// when its color does ([`Node::colorize_overprints`]). A white color that is not a spot ink + /// ([`Document::spot_ink`]) and overprints (Discard White Overprint off) puts no ink down, so + /// it paints nothing. + fn colorized(&mut self, s: &mut Surface, n: &Node, im: &vectorcraft_doc::ImageObject, p: &Paint) { + let overprint = n.colorize_overprints() && self.overprint; + if overprint && !self.doc.setup.discard_white_overprint && !self.doc.spot_ink(p) && vectorcraft_doc::overprint::is_white(p) { + return; + } + match self.colorized_image(im, p, !n.extras().pixelated, overprint) { + Some(colorized) => { + let pixelated = n.extras().pixelated; + self.overprinting(s, overprint, p, |ex, s| ex.image(s, im, Some(colorized), pixelated)); + } + None => { + self.image_left_out = self.image_left_out.map(|_| true); + self.warn(UNDECODED); + } + } + } + /// Gradient mesh `m` as one PDF Type 6 (Coons patch) shading filling its outline (ISO 32000-1, /// 8.7.4.5.7): each patch blends its corner colours bilinearly, as the canvas draws it, and /// the viewer or RIP does so smoothly at its own resolution. Cutting the mesh into flat quads @@ -619,9 +635,9 @@ impl Exporter<'_> { /// Draw a fill or stroke of `paint` with `draw`: as a form marked to overprint when it /// `overprints`, paints and overprints are kept (but not a white one with Discard White - /// Overprint). + /// Overprint, [`Document::discards_white_overprint`]). pub(super) fn overprinting(&mut self, s: &mut Surface, overprints: bool, paint: &Paint, draw: impl FnOnce(&mut Self, &mut Surface)) { - let white = || self.doc.setup.discard_white_overprint && vectorcraft_doc::overprint::is_white(paint); + let white = || self.doc.discards_white_overprint(paint); if overprints && self.overprint && !paint.is_none() && !white() { self.overprinted = true; crate::forms::form(s, Mark::Overprint, |s| draw(self, s)); @@ -634,7 +650,7 @@ impl Exporter<'_> { /// with [`Self::darken_overprints`] an overprinting one is drawn with Darken (not a white one /// with Discard White Overprint). pub(super) fn char_overprinting(&mut self, s: &mut Surface, overprints: bool, paint: &Paint, draw: impl FnOnce(&mut Self, &mut Surface)) { - let white = vectorcraft_doc::overprint::is_white(paint) && self.doc.setup.discard_white_overprint; + let white = self.doc.discards_white_overprint(paint); if overprints && self.darken_overprints && !paint.is_none() && !white { s.push_blend_mode(krilla::blend::BlendMode::Darken); self.overprinting(s, overprints, paint, draw); diff --git a/crates/pdf/src/print.rs b/crates/pdf/src/print.rs index 975ec6e628..2ea6906b6c 100644 --- a/crates/pdf/src/print.rs +++ b/crates/pdf/src/print.rs @@ -40,7 +40,7 @@ use kurbo::{Affine, Rect, Vec2}; use serde::Serialize; use vectorcraft_color::cms::{self, ProfileKind}; use vectorcraft_doc::marks::PrinterMarks; -use vectorcraft_doc::overprint::{OverprintBlack, clear_overprints, darken_overprints}; +use vectorcraft_doc::overprint::{DiscardWhite, OverprintBlack, clear_overprints, darken_overprints}; use vectorcraft_doc::{ColorMode, Document, Node, NodeKind}; pub use layout::{MAX_COPIES_PER_SHEET, MAX_TILES, TileGrid}; @@ -411,12 +411,12 @@ fn composite_overprints(doc: &mut Document, set: &PrintSettings) { if set.output.mode == OutputMode::Separations || how == PrintOverprints::Preserve { return; } - let discard_white = doc.setup.discard_white_overprint; + let discard_white = DiscardWhite::of(doc); let symbols = doc.symbols.iter_mut().map(|s| &mut s.art); let nodes = doc.layers.iter_mut().chain(symbols).chain(doc.patterns.iter_mut().flat_map(|p| p.art.iter_mut())); for n in nodes { if how == PrintOverprints::Simulate { - darken_overprints(n, discard_white); + darken_overprints(n, &discard_white, &doc.images); } clear_overprints(n); } diff --git a/crates/pdf/src/print/plates.rs b/crates/pdf/src/print/plates.rs index dada741c9d..66c5092391 100644 --- a/crates/pdf/src/print/plates.rs +++ b/crates/pdf/src/print/plates.rs @@ -9,7 +9,9 @@ use vectorcraft_color::cms::{self, Cms, Model, ProfileKind}; use vectorcraft_color::swatch::REGISTRATION; use vectorcraft_color::{BlendMode, Color, GradientKind, GradientStop, Paint}; use vectorcraft_doc::inks::{Link, StopPlates, inks, plates, spot_color, stop_inks, visit_node_colors}; -use vectorcraft_doc::overprint::{darken_overprints, is_black_ink, is_white}; +use vectorcraft_doc::overprint::{ + DiscardWhite, colorized_shown_key, darken_overprints, image_overprints_whole, image_row_draws, is_black_ink, is_colorized_image, refuses_colorize, +}; use vectorcraft_doc::{AppearanceItem, ColorMode, Document, ImageBlob, Node, NodeKind}; use super::{DEFAULT_FREQUENCY, InkSettings, PrintInk, PrintSettings}; @@ -236,16 +238,26 @@ impl<'a> Separator<'a> { /// Overprinting fills and strokes of `a`'s subtree with a Normal blending mode, and /// overprinting character fills and strokes, that put none of ink `plate` down leave its plate - /// as it is: they are drawn as nothing on it (white ones with `discard_white` aside, which - /// knock out). A writer without blending modes (PostScript) then keeps the ink below them, + /// as it is: they are drawn as nothing on it (white ones that `discard_white` knocks out + /// aside, [`DiscardWhite::discards`]). A writer without blending modes (PostScript) then keeps the ink below them, /// where it would draw their Darken as a knockout. One that puts any ink down is drawn, and on /// a PostScript plate its ink replaces the ink below, as a nonzero component of an overprinting /// color replaces the backdrop's with overprint mode 1 (ISO 32000-1, 11.7.4.2). On a /// PostScript plate, the stops and points of such a gradient that put none of the ink down - /// become paper white ([`Self::clear_inkless_stops`]), which the writer leaves out there. - fn clear_inkless_overprints(&self, plate: &str, a: &mut Arc, discard_white: bool) { - let inkless = |overprint: bool, p: &Paint| overprint && !p.is_none() && !(discard_white && is_white(p)) && self.no_ink(plate, p); + /// become paper white ([`Self::clear_inkless_stops`]), which the writer leaves out there. A + /// colorized image that overprints as a whole ([`image_overprints_whole`]) and whose color puts + /// none of the ink down is hidden on the plate once none of its rows draws there; while a row + /// draws, the PostScript writer leaves out the image's paper-white pixels and draws the row. + /// A colorized image that does not overprint as a whole, or whose pixels don't take its color + /// ([`refuses_colorize`]) and so print as they are, knocks out on the plate. + fn clear_inkless_overprints(&self, plate: &str, a: &mut Arc, discard_white: &DiscardWhite) { + let inkless = |overprint: bool, p: &Paint| overprint && !p.is_none() && !discard_white.discards(p) && self.no_ink(plate, p); let n = Arc::make_mut(a); + let whole = image_overprints_whole(n, discard_white, &self.doc.images); + if n.colorize_overprints() && !whole { + n.extras_mut().colorize_overprint = false; + } + let image = whole && n.extras().colorize.as_deref().is_some_and(|p| self.no_ink(plate, p)); for it in &mut n.appearance.items { let normal = match it { AppearanceItem::Fill(l) => l.blend == BlendMode::Normal, @@ -257,6 +269,9 @@ impl<'a> Separator<'a> { self.clear_inkless_stops(plate, it.paint_mut()); } } + if image && !n.appearance.items.iter().any(image_row_draws) { + n.visible = false; + } if let NodeKind::Text(t) = &mut n.kind { for r in &mut t.runs { if inkless(r.style.overprint_fill, &r.style.fill) { @@ -281,12 +296,12 @@ impl<'a> Separator<'a> { /// ink the plate below shows through instead of being knocked out. pub fn plate(&self, plate: &str) -> Document { let mut d = self.doc.clone(); - let discard_white = d.setup.discard_white_overprint; + let discard_white = DiscardWhite::of(self.doc); let mut colorized = BTreeSet::new(); let nodes = d.layers.iter_mut().chain(d.symbols.iter_mut().map(|s| &mut s.art)).chain(d.patterns.iter_mut().flat_map(|p| p.art.iter_mut())); for n in nodes { - self.clear_inkless_overprints(plate, n, discard_white); - darken_overprints(n, discard_white); + self.clear_inkless_overprints(plate, n, &discard_white); + darken_overprints(n, &discard_white, &d.images); self.node(plate, Arc::make_mut(n)); keep_colorized_pixels(n, &d.images, &mut colorized); } @@ -345,22 +360,15 @@ fn colorized_key(key: &str) -> String { /// paint ([`ImageBlob::takes_colorize`]) loses the paint instead, and is separated as the image it /// shows. fn keep_colorized_pixels(n: &mut Arc, images: &BTreeMap, keys: &mut BTreeSet) { - let colorized = |n: &Node| matches!(n.kind, NodeKind::Image(ref im) if im.pixels.is_none()) && n.extras().colorize.is_some(); - if !colorized(n) && n.children().is_none_or(|ch| ch.is_empty()) { + if !is_colorized_image(n) && n.children().is_none_or(|ch| ch.is_empty()) { return; } let node = Arc::make_mut(n); - let shown = match &node.kind { - NodeKind::Image(im) if colorized(node) => { - let mask = Document::color_mask_of(node).filter(|m| m.made_for(im) && images.contains_key(&m.key)); - Some(mask.map_or(&im.key, |m| &m.key).clone()) - } - _ => None, - }; - if shown.as_ref().and_then(|key| images.get(key)).is_some_and(|b| !b.takes_colorize()) { + let shown = colorized_shown_key(node, images); + if refuses_colorize(node, images) { node.extras_mut().colorize = None; } - if let Some(key) = shown.filter(|_| colorized(node)) { + if let Some(key) = shown.filter(|_| is_colorized_image(node)) { if let Some(e) = node.extras_if_any() { e.color_mask = None; } diff --git a/crates/pdf/src/tests/colorize.rs b/crates/pdf/src/tests/colorize.rs index bd9f2b2dee..1287c814d5 100644 --- a/crates/pdf/src/tests/colorize.rs +++ b/crates/pdf/src/tests/colorize.rs @@ -121,6 +121,40 @@ fn a_process_color_writes_the_image_in_that_color_with_a_soft_mask() { assert_eq!(images(&pdf(&doc(ColorMode::Cmyk, None))), [("DeviceGray".into(), vec![], false)]); } +/// A colorized image whose color overprints is drawn with an overprinting graphics state +/// (ISO 32000-1 §8.6.7), its DeviceN image unchanged; one that knocks out sets none. +#[test] +fn an_overprinting_colorized_image_sets_overprint() { + let spot = Paint::Solid { color: Color::cmyk(0.0, 1.0, 1.0, 0.0), swatch: Some("Ink".into()), tint: 1.0 }; + let mut d = doc(ColorMode::Cmyk, Some(spot)); + let text = |d: &Document| String::from_utf8_lossy(&pdf(d)).into_owned(); + assert!(!text(&d).contains("/OP true"), "a knocking-out image sets no overprint"); + let Some(id) = d.layers[0].children().and_then(|c| c.first()).map(|n| n.id) else { panic!("the image") }; + d.node_mut(id).unwrap().extras_mut().colorize_overprint = true; + let out = pdf(&d); + assert!(text(&d).contains("/OP true/op true"), "the image overprints"); + assert!(images(&out).contains(&("DeviceN".into(), vec!["Ink".into()], true)), "still the ink's DeviceN image"); + + // A process color is written in only the process inks it puts down, so its zero plates keep + // the inks below: an image's samples take no part in the nonzero overprint mode. + let mut d = doc(ColorMode::Cmyk, Some(Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)))); + assert_eq!(images(&pdf(&d)), [("DeviceGray".into(), vec![], false), ("DeviceCMYK".into(), vec![], true)], "knocking out: CMYK"); + let Some(id) = d.layers[0].children().and_then(|c| c.first()).map(|n| n.id) else { panic!("the image") }; + d.node_mut(id).unwrap().extras_mut().colorize_overprint = true; + assert!(images(&pdf(&d)).contains(&("DeviceN".into(), vec!["Black".into()], true)), "{:?}", images(&pdf(&d))); + // A gray color is black ink alone. + d.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::solid(Color::Gray { k: 0.6 }))); + assert!(images(&pdf(&d)).contains(&("DeviceN".into(), vec!["Black".into()], true)), "{:?}", images(&pdf(&d))); + + // White knocks out with Discard White Overprint (the default), as a white fill does; without + // it, an overprinting white process color puts no ink down and paints nothing. + d.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 0.0)))); + assert_eq!(images(&pdf(&d)).len(), 2, "the white image and its soft mask"); + assert!(!text(&d).contains("/OP true"), "white knocks out"); + d.setup.discard_white_overprint = false; + assert!(images(&pdf(&d)).is_empty(), "{:?}", images(&pdf(&d))); +} + /// Registration prints on every plate: the process inks and the document's spot inks. #[test] fn registration_writes_the_image_in_every_ink() { @@ -303,6 +337,96 @@ fn separations_print_the_image_on_its_ink_plate() { } } +/// On printed separations an overprinting colorized image is hidden on the plates its color puts +/// no ink on, so a writer without blending modes (PostScript) keeps the ink below it there; a +/// knocking-out one is drawn on every plate. +#[test] +fn separations_hide_an_overprinting_image_on_plates_without_its_ink() { + let spot = Paint::Solid { color: Color::cmyk(0.0, 1.0, 1.0, 0.0), swatch: Some("Ink".into()), tint: 1.0 }; + let shown = |overprint: bool, postscript: bool| { + let mut d = doc(ColorMode::Cmyk, Some(spot.clone())); + let id = d.layers[0].children().unwrap()[0].id; + d.node_mut(id).unwrap().extras_mut().colorize_overprint = overprint; + let settings: PrintSettings = serde_json::from_value(serde_json::json!({"output": {"mode": "separations"}})).unwrap(); + let names: Vec = print_inks(&d, &settings).0.into_iter().map(|i| i.name).collect(); + let job = plan(&d, &PrintOptions { settings, postscript, ..Default::default() }).unwrap(); + names.into_iter().zip(&job.plates).map(|(name, p)| (name, p.layers[0].children().unwrap()[0].visible)).collect::>() + }; + for postscript in [true, false] { + let knocking = shown(false, postscript); + assert!(knocking.len() > 1 && knocking.iter().all(|(_, v)| *v), "{knocking:?}"); + for (name, visible) in shown(true, postscript) { + assert_eq!(visible, name == "Ink", "{name}"); + } + } + + // With a drop shadow of its own the image knocks out on every plate, so the PostScript + // writer draws it there. + let mut d = doc(ColorMode::Cmyk, Some(spot)); + let id = d.layers[0].children().unwrap()[0].id; + let n = d.node_mut(id).unwrap(); + n.extras_mut().colorize_overprint = true; + n.appearance.effects.push(vectorcraft_doc::Effect { id: "stylize.dropShadow".into(), params: serde_json::json!({}), visible: true }); + let settings: PrintSettings = serde_json::from_value(serde_json::json!({"output": {"mode": "separations"}})).unwrap(); + let job = plan(&d, &PrintOptions { settings, postscript: true, ..Default::default() }).unwrap(); + for p in &job.plates { + let image = &p.layers[0].children().unwrap()[0]; + assert!(image.visible && !image.extras().colorize_overprint, "{:?}", image.extras()); + } +} + +/// With Discard White Overprint on, an overprinting colorized image in a tint of a spot ink whose +/// color is white still overprints, in the PDF and on printed separations: it prints as that ink, +/// not as paper white. +#[test] +fn a_white_spot_ink_image_overprints_with_discard_white_overprint() { + let white = Color::cmyk(0.0, 0.0, 0.0, 0.0); + let spot = Paint::Solid { color: white, swatch: Some("White Ink".into()), tint: 0.5 }; + let mut d = doc(ColorMode::Cmyk, Some(spot)); + d.swatches.push(Swatch { name: "White Ink".into(), paint: Paint::solid(white), global: true, spot: true }); + d.setup.discard_white_overprint = true; + let id = d.layers[0].children().unwrap()[0].id; + d.node_mut(id).unwrap().extras_mut().colorize_overprint = true; + let out = pdf(&d); + assert!(String::from_utf8_lossy(&out).contains("/OP true/op true"), "the image overprints"); + assert!(images(&out).contains(&("DeviceN".into(), vec!["White Ink".into()], true)), "{:?}", images(&out)); + + let settings: PrintSettings = serde_json::from_value(serde_json::json!({"output": {"mode": "separations"}})).unwrap(); + let names: Vec = print_inks(&d, &settings).0.into_iter().map(|i| i.name).collect(); + for postscript in [true, false] { + let job = plan(&d, &PrintOptions { settings: settings.clone(), postscript, ..Default::default() }).unwrap(); + for (name, p) in names.iter().zip(&job.plates) { + assert_eq!(p.layers[0].children().unwrap()[0].visible, name == "White Ink", "{name}"); + } + } +} + +/// An overprinting colorized image whose pixels don't take its color (a color preview of its +/// file) is separated as those pixels on every plate, so it is not hidden on the plates its +/// color puts no ink on. +#[test] +fn separations_show_an_overprinting_image_whose_pixels_refuse_its_color() { + let spot = Paint::Solid { color: Color::cmyk(0.0, 1.0, 1.0, 0.0), swatch: Some("Ink".into()), tint: 1.0 }; + for postscript in [true, false] { + let mut d = doc(ColorMode::Cmyk, Some(spot.clone())); + let preview = Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap()); + d.images.insert( + "pic".into(), + ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview), file_font: Default::default() }, + ); + let id = d.layers[0].children().unwrap()[0].id; + d.node_mut(id).unwrap().extras_mut().colorize_overprint = true; + let settings: PrintSettings = serde_json::from_value(serde_json::json!({"output": {"mode": "separations"}})).unwrap(); + let job = plan(&d, &PrintOptions { settings, postscript, ..Default::default() }).unwrap(); + assert!(job.plates.len() > 1); + for p in &job.plates { + let n = &p.layers[0].children().unwrap()[0]; + assert!(n.visible, "postscript {postscript}: the pixels print on every plate"); + assert!(n.extras().colorize.is_none() && !n.extras().colorize_overprint, "postscript {postscript}: {:?}", n.extras()); + } + } +} + /// Printed separations separate a colorized image with a color mask as it shows: the pixels the /// mask hides print on no plate. #[test] diff --git a/crates/render/src/proof.rs b/crates/render/src/proof.rs index dd7d28eb23..18e25a1e5a 100644 --- a/crates/render/src/proof.rs +++ b/crates/render/src/proof.rs @@ -25,7 +25,8 @@ //! [`crate::RenderOptions`] with [`active_proof`] and [`overprint_preview_on`]. use std::borrow::Cow; -use std::collections::HashMap; +use std::collections::{BTreeMap, HashMap}; +use std::hash::{DefaultHasher, Hash, Hasher}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, OnceLock, RwLock, Weak}; @@ -34,7 +35,7 @@ pub use vectorcraft_color::cms::{Intent, ProofSetup, ProofTarget}; use vectorcraft_color::{Color, Paint, Swatch, SwatchGroup}; pub use vectorcraft_doc::inks::{Inks, Link, Plate, inks, map_document_colors, map_node_colors, plates, spot_color}; use vectorcraft_doc::inks::{StopPlates, map_node_inks, stop_inks}; -use vectorcraft_doc::overprint::darken_overprints; +use vectorcraft_doc::overprint::{DiscardWhite, darken_overprints}; use vectorcraft_doc::{AppearanceItem, Document, ImageBlob, Node, NodeId, Shared}; use vello_cpu::Pixmap; use vello_cpu::color::PremulRgba8; @@ -398,10 +399,25 @@ pub(crate) struct Prepared { /// What [`prepare`] reads besides the art. #[derive(PartialEq)] struct Inputs { - discard_white: bool, + /// Discard White Overprint, with the spot inks a white tint of which still overprints. + discard_white: DiscardWhite, + /// [`images_state`]: which pixels a colorized image shows, and whether they take its color + /// ([`ImageBlob::takes_colorize`]), and so whether it darkens, depend on the document's images. + images: u64, plates: Option, } +/// A hash of `images`' keys and the address of each one's bytes and whether they are a preview +/// ([`ImageBlob::is_proxy`]): it changes when an image is added, removed or given other bytes, +/// without reading any pixels. +fn images_state(images: &BTreeMap) -> u64 { + let mut h = DefaultHasher::new(); + for (key, b) in images { + (key, Arc::as_ptr(&b.bytes), b.is_proxy()).hash(&mut h); + } + h.finish() +} + /// What the colors of Separations Preview's plates are made from ([`plate_color`]). struct Plates { /// The proof setup, with the visible plates. @@ -429,21 +445,21 @@ impl PartialEq for Plates { /// print it ([`plate_color`]). struct How<'a> { doc: &'a Document, - discard_white: bool, + discard_white: DiscardWhite, /// Separations Preview: the color settings, the proof setup and the visible plates. plates: Option<(&'a Cms, &'a ProofSetup, &'a [String])>, } impl How<'_> { /// Whether [`Self::apply`] can change `n`: with Separations Preview any node, else a node with - /// an overprinting fill or stroke. + /// an overprinting fill or stroke, or a colorized image whose color overprints. fn changes(&self, n: &Node) -> bool { - self.plates.is_some() || n.appearance.items.iter().any(|i| i.overprint()) + self.plates.is_some() || n.appearance.items.iter().any(|i| i.overprint()) || n.colorize_overprints() } /// Change the fills, strokes and other colors of node `a`, which holds no members. fn apply(&self, a: &mut Arc) { - darken_overprints(a, self.discard_white); + darken_overprints(a, &self.discard_white, &self.doc.images); if let Some((c, proof, visible)) = self.plates { map_node_inks(Arc::make_mut(a), &mut |col, sw, plates| plate_color(self.doc, c, proof, visible, col, sw, plates)); } @@ -462,7 +478,8 @@ pub(crate) fn prepare<'a>(doc: &'a Document, opts: &RenderOptions, kept: &mut Op let seps = opts.proof.as_ref().and_then(|p| p.separations.as_ref().map(|s| (p, s))); let c = cms::active(); let inputs = Inputs { - discard_white: doc.setup.discard_white_overprint, + discard_white: DiscardWhite::of(doc), + images: images_state(&doc.images), plates: seps.map(|(proof, _)| Plates { proof: proof.clone(), swatches: doc.swatches.clone(), @@ -473,7 +490,7 @@ pub(crate) fn prepare<'a>(doc: &'a Document, opts: &RenderOptions, kept: &mut Op }), }; let earlier = kept.take().filter(|k| k.inputs == inputs); - let how = How { doc, discard_white: inputs.discard_white, plates: seps.map(|(proof, visible)| (&*c, proof, visible.as_slice())) }; + let how = How { doc, discard_white: inputs.discard_white.clone(), plates: seps.map(|(proof, visible)| (&*c, proof, visible.as_slice())) }; let none = (vec![], vec![]); let (layers, art) = earlier.as_ref().map_or((&none, &none), |k| (&k.layers, &k.art)); let made_layers = prepare_list(&doc.layers, &layers.0, &layers.1, &how); diff --git a/crates/render/src/tests/colorize.rs b/crates/render/src/tests/colorize.rs index d1c5082c14..84a68e5f8b 100644 --- a/crates/render/src/tests/colorize.rs +++ b/crates/render/src/tests/colorize.rs @@ -318,6 +318,46 @@ fn separations_preview_shows_the_image_on_its_spot_plate() { assert!(off[..3].iter().all(|v| *v >= 250), "the process plates show paper, got {off:?}"); } +/// A spot-colorized image over a cyan square knocks the cyan out where it is dark, unless its +/// color overprints: then Separations Preview's Cyan plate keeps the square under it, its Ink +/// plate still shows the image, and Overprint Preview darkens the two together. +#[test] +fn an_overprinting_colorized_image_keeps_the_ink_below_in_the_previews() { + let ink = Color::cmyk(0.0, 1.0, 1.0, 0.0); + let shown = |overprint: bool, plates: Option<&[&str]>| { + let mut d = Document::new_with_mode(40.0, 20.0, vectorcraft_doc::ColorMode::Cmyk); + d.swatches.push(vectorcraft_color::Swatch { name: "Ink".into(), paint: Paint::solid(ink), global: true, spot: true }); + let square = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(0.0, 0.0, 40.0, 20.0)), + Appearance::basic(Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0)), Paint::None, 0.0), + ); + d.insert(Some(d.layers[0].id), 0, square).unwrap(); + d.images.insert("pic".into(), ImageBlob::new("image/png", gray_png())); + let im = + ImageObject { key: "pic".into(), width: 2, height: 1, xf: Affine::scale(20.0), link: None, placement: Default::default(), pixels: None }; + let mut n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))); + n.extras_mut().colorize = Some(Box::new(Paint::Solid { color: ink, swatch: Some("Ink".into()), tint: 1.0 })); + n.extras_mut().colorize_overprint = overprint; + d.insert(Some(d.layers[0].id), 1, n).unwrap(); + let opts = match plates { + Some(plates) => separations(plates), + None => RenderOptions { overprint_preview: true, smooth_images: false, ..Default::default() }, + }; + Renderer::new().render(&d, 40, 20, Affine::IDENTITY, &opts).pixel(10, 10) + }; + let knocked = shown(false, Some(&["Cyan"])); + assert!(knocked[..3].iter().all(|v| *v >= 250), "knocking out, the Cyan plate is paper under the image, got {knocked:?}"); + let kept = shown(true, Some(&["Cyan"])); + assert!(kept[..3].iter().all(|v| *v < 128), "overprinting, the Cyan plate keeps the square, got {kept:?}"); + let on = shown(true, Some(&["Ink"])); + assert!(on[..3].iter().all(|v| *v < 128), "the Ink plate shows the image, got {on:?}"); + // Overprint Preview alone: the red ink over cyan darkens to near black where it knocked out + // to red. + let (red, dark) = (shown(false, None), shown(true, None)); + assert!(red[0] > 128 && dark[0] < 128, "knocking out {red:?}, overprinting {dark:?}"); +} + /// Separations Preview shows an image placed from a DCS file through its own plates: its spot /// plate on that ink's plate only, its cyan plate on the cyan plate only. Without the preview it /// shows its composite, the spot ink mixed in. diff --git a/docs/mcp.md b/docs/mcp.md index 7b1285a41b..bc3818c87a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5140,12 +5140,25 @@ on OK. Cancel restores the original artwork. Each fill and stroke (and each character's fill and stroke) can overprint: its inks print over the inks below instead of knocking them out. `object.setOverprint {fill?, stroke?, item?, ids?}` sets it (groups set their contents, type its -characters too; `item` aims at one appearance item) and `attributes.info {ids?}` reads it back (`null` where the +characters too; `item` aims at one appearance item; without `item`, `fill` on a grayscale or 1-bit image colorized by +`paint.setFill` sets whether its color overprints) and `attributes.info {ids?}` reads it back (`null` where the objects differ). Overprint Preview (`view.overprintPreview`) and Separations Preview show it; rendering approximates -it by darkening (the stronger ink of each plate wins, so a colour overprinting itself stays that colour). Older files that listed Overprint Black objects in the document get the flags on load. +it by darkening (the stronger ink of each plate wins, so a colour overprinting itself stays that colour). A colorized +image overprints as a whole: when one of its fills or strokes with an opacity above 0 draws a shape (Convert to Shape +or Outline Object) and does not overprint, the whole image knocks out in the previews and on printed plates. On +printed plates an image whose pixels do not take its color (a preview of its file) knocks out and prints as those +pixels. Older files that listed Overprint Black objects in the document get the flags on load. PDF export writes them with `advanced.overprint: "preserve"` (the default): each overprinting fill and stroke sets a graphics state with `/OP true /op true /OPM 1` (`/OPM 0` in PDF/A). With `discardWhiteOverprint` (`document.setup`, on by -default) white ones knock out instead; `"discard"` writes none. +default) white ones knock out instead, but not a tint above 0% of a spot swatch, which prints as that ink; +`"discard"` writes none. EPS export (`overprints: "preserve"`, the default) turns +overprinting on for a colorized image's color as it does for fills and strokes, except a white color with +`discardWhiteOverprint` on, which knocks out unless it is such a spot tint. PDF export writes an overprinting +colorized image in a gray or CMYK color in only the process inks the color puts down, and EPS export does too (one +DeviceN image at Level 3, one Separation image per ink at Level 2). The previews and printed separations show a +colorized image knocking out when it has a visible effect of its own other than a warp or a geometry effect (a drop +shadow, a glow, a raster effect or a color adjustment). PDF and EPS export leave raster effects out and still +overprint such an image. ```json {"name":"run_command","arguments":{"command":"object.setOverprint","params":{"ids":[12],"stroke":true}}} @@ -15514,7 +15527,7 @@ document's inks for print, as one undo step: | `scope` | `selection`, `document` (the selection, or the document while nothing is selected) | What it fixes; `ids` stand for the selection | | `inkLimit` | total ink % 1…400, 0 off (off) | CMYK colours (solid, gradient stops, gradient meshes) with more ink than this are scaled down to it; colours of spot swatches and Registration stay | | `excludePureBlack` | bool (true) | Black-only CMYK and grey colours keep their ink | -| `removeWhiteOverprint` | bool (false) | White fills and strokes, and characters', stop overprinting | +| `removeWhiteOverprint` | bool (false) | White fills and strokes, characters' and the white color of a colorized image stop overprinting | | `overprintBlack` | black % 1…100, 0 off (off) | Black-only and grey fills and strokes this dark or darker overprint, as `edit.colors.overprintBlack` sets it (not spot-linked or rich blacks) | | `textOnly` | bool (false) | Overprint Black on type only | | `fill`, `stroke` | bool (true) | Which paints the fixes reach | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f0fc51a803..8b4a1045eb 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2007,6 +2007,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Colorized images (#1466):** a fill color applied to a selected grayscale or 1-bit image (`paint.setFill`) colorizes it with black, white, a process color or a spot color, and refuses a process color when the image has an alpha channel ([Convert color modes](https://web.archive.org/web/20251220223850/https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/convert-color-modes.html), "Colorize Grayscale or 1-bit images"); black and white are accepted there too. The canvas draws each pixel in the color as far as the pixel is dark, with white pixels transparent; PDF export writes the image in the color (a spot color as its ink, Registration in every ink) with the image as its soft mask; Separations Preview and printed separations show it on its color's plates; native files keep the color. SVG writes the fill color through a coverage mask (or a colorized PNG in Tiny 1.2); EPS writes binary coverage as an image mask in the color's ink, and a grayscale image as ink samples scaled by coverage, with white pixels left out at Level 3 and gray midtones written over white. The prompt for deleting several swatches and groups uses the interface language's plural form for the count. Evidence: `deleting_several_swatches_uses_each_count_form` in `crates/ui-egui/src/panels/swatches/tests.rs`. - **Colorized images (#1466):** a fill color applied to a selected grayscale or 1-bit image (`paint.setFill`) colorizes it with black, white, a process color or a spot color, and refuses a process color when the image has an alpha channel ([Convert color modes](https://web.archive.org/web/20251220223850/https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/convert-color-modes.html), "Colorize Grayscale or 1-bit images"); black and white are accepted there too. The canvas draws each pixel in the color as far as the pixel is dark, with white pixels transparent; PDF export writes the image in the color (a spot color as its ink, Registration in every ink) with the image as its soft mask; Separations Preview and printed separations show it on its color's plates; native files keep the color. EPS and SVG write the image's own pixels. + - **Colorized images overprint:** Overprint Fill (`object.setOverprint {fill: true}`) on a colorized grayscale or 1-bit image makes its color print over the inks below instead of knocking them out. Raster art has an overprint setting in the [scripting reference](https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/). `attributes.info` reports it, native files keep it, and Overprint Preview, Separations Preview and printed separations show it; they show an image knocking out when it has a visible effect of its own other than a warp or a geometry effect (a drop shadow, a glow, a raster effect or a color adjustment), or a fill or stroke with an opacity above 0 that draws a shape with Convert to Shape or Outline Object and does not overprint. Printed separations also show an image knocking out when its pixels do not take its color (a preview of its file), and separate those pixels as they are. PDF and EPS export leave raster effects out and still overprint such an image. PDF export draws the image with an overprinting graphics state and writes a gray or process color as an image of only the process inks it puts down (ISO 32000-1 §8.6.7). EPS export turns overprinting on for it and writes a gray or process color in only the process inks it puts down (one DeviceN image at Level 3, one Separation image per ink at Level 2). A legacy `.ai` file writes it with the image mask's fill overprint, and reading one takes the fill overprint in force at the image mask. White follows the rule for white fills: with Discard White Overprint on, PDF export, EPS export, the previews and printed separations show a white color knocking out, but a tint above 0% of a spot swatch whose color is white keeps overprinting, as it does for fills and strokes in PDF export, the previews and printed separations ([White overprint](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/white-overprint.html)). Taking the color off with a fill of None also turns its overprint off. Edit › Edit Colors › Overprint Black and Print Ink Fixes' Remove White Overprint reach a colorized image's color as its fill. Evidence: engine `tests::colorize::overprint_fill_makes_a_colorized_images_color_overprint`, `tests::colorize::overprint_black_and_print_fixes_reach_a_colorized_images_color`, `tests::colorize::flattening_without_preserve_overprints_drops_a_colorized_images_overprint`, `tests::colorize::flattening_without_preserve_overprints_clears_an_uncolored_images_overprint`, doc `overprint::tests::a_white_colorized_image_knocks_out_under_discard_white`, `overprint::tests::a_white_spot_ink_keeps_overprinting_under_discard_white`, `overprint::tests::a_colorized_image_darkens_unless_its_rows_draw_an_effect`, `overprint::tests::a_colorized_image_darkens_past_a_row_with_no_opacity`, `overprint::tests::a_colorized_image_with_a_node_effect_keeps_knocking_out`, `overprint::tests::overprint_black_takes_a_black_colorized_image`, `overprint::tests::clearing_overprints_clears_the_flag_of_an_image_without_a_color`, render `tests::colorize::an_overprinting_colorized_image_keeps_the_ink_below_in_the_previews`, pdf `tests::colorize::an_overprinting_colorized_image_sets_overprint`, `tests::colorize::separations_hide_an_overprinting_image_on_plates_without_its_ink`, `tests::colorize::separations_show_an_overprinting_image_whose_pixels_refuse_its_color`, `tests::colorize::a_white_spot_ink_image_overprints_with_discard_white_overprint`, eps `tests::an_overprinting_colorized_image_writes_only_its_process_inks`, `tests::a_white_spot_ink_colorized_image_overprints_with_discard_white_overprint`, `tests::a_plate_leaves_out_an_overprinting_image_without_its_ink`, `tests::an_overprinting_colorized_image_at_the_page_limit_keeps_all_its_inks_or_none`, `legacy_ai::tests::a_colorized_image_mask_takes_the_fill_overprint_in_force`, doc `live::tests::mesh_warp_image_pieces_keep_an_overprinting_color`, effects `tests::an_image_under_a_geometry_effect_keeps_its_color_and_smoothing`. - **Missing library files:** a persistent swatch or graphic style library panel whose file is gone at startup reopens and stays in the preferences, showing the file's path with Locate Library… (`ui.libraryPanel.locate`), which reads the file from where it is now into the same panel. - **Swatch library and Recolor Artwork parameters:** the `swatch.library.*` commands, `swatch.resetDefaults`, the graphic style library save, load and add, the `recolor.*` commands and `color.harmony`'s `limitTo` refuse parameters of the wrong form, such as `names: "Grays"`, `limitTo: 5` or `includeImages: "false"`. Errors name the parameter, except that a `limitTo` that is not a string, such as `5`, gets an unknown-library error. A `null` counts as left out except for `recolor.apply`'s `model`, which must be a string when given. - **OKLCH Sliders (Color Wheel panel):** as VectorCraft's own addition, the Color Wheel panel's menu item OKLCH Sliders (`ui.colorWheel {sliders: "oklch"}`, kept with the preferences) shows L, C and H rows under the wheel or the box that edit the color by the OKLCH lightness (0 to 100 %), chroma (0 to 100 % of 0.4) and hue (0 to 360°) of its display sRGB, as CSS Color 4 defines them (https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch). Each track dims the colors outside sRGB, and a tick on the C track marks the largest chroma sRGB holds at the row's L and H; a color outside sRGB keeps L and H and takes the largest chroma that fits, and the C row keeps the chroma asked for. The rows take the arrow keys after a click and report their names, values, ranges and adjust actions to screen readers. While the active document's RGB space (its assigned profile, else the working RGB space of Edit › Color Settings) is not sRGB, the unchecked item is gray and `ui.colorWheel {sliders: "oklch"}` answers an error; rows shown before the space changed are gray, and the checked item still hides them. `color.convert {color, to: "oklch"}` answers the same L, C and H for a color inside sRGB. For a color outside sRGB, it clips the display RGB to 0 to 1 first, so its L, C and H can differ from the rows' values. Evidence: `crates/color/src/oklab.rs` tests; `convert_to_oklch_answers_lightness_chroma_and_hue` in `crates/engine/src/tests/colormgmt.rs`; the OKLCH tests in `crates/ui-egui/src/panels/tests_color_wheel.rs`, `the_oklch_tracks_dim_the_colors_outside_srgb_and_the_tick_marks_the_largest_chroma` and `oklch_sliders_are_gray_after_the_working_space_changes` among them. Scores and estimates are unchanged.