diff --git a/crates/doc/src/overprint.rs b/crates/doc/src/overprint.rs index 056c8c888f..59ff63a392 100644 --- a/crates/doc/src/overprint.rs +++ b/crates/doc/src/overprint.rs @@ -46,14 +46,20 @@ impl Default for OverprintBlack { } impl OverprintBlack { - /// Whether `p` is black: a solid colour (linked to one of the spot swatches `spots` only with - /// [`Self::spot`]), or a gradient whose every stop is. + /// Whether `p` is black: a solid color (linked to one of the spot swatches `spots` only with + /// [`Self::spot`]), a gradient whose every stop is, or a freeform gradient with color points + /// whose every point is (it draws from its points, not its stops). fn black(&self, p: &Paint, spots: &[String]) -> bool { + let ink = |color: &Color, swatch: &Option| { + (self.spot || !swatch.as_ref().is_some_and(|s| spots.contains(s))) && is_black_ink(color, self.min_k, self.rich) + }; match p { - Paint::Solid { color, swatch, .. } => { - (self.spot || !swatch.as_ref().is_some_and(|s| spots.contains(s))) && is_black_ink(color, self.min_k, self.rich) - } - Paint::Gradient(g) => !g.gradient.stops.is_empty() && g.gradient.stops.iter().all(|s| is_black_ink(&s.color, self.min_k, self.rich)), + Paint::Solid { color, swatch, .. } => ink(color, swatch), + Paint::Gradient(g) => match g.freeform.as_ref().filter(|f| !f.points.is_empty()) { + Some(f) => f.points.iter().all(|pt| is_black_ink(&pt.color, self.min_k, self.rich)), + // Without points of its own a freeform gradient places them from its stops. + None => !g.gradient.stops.is_empty() && g.gradient.stops.iter().all(|s| ink(&s.color, &s.swatch)), + }, _ => false, } } @@ -85,6 +91,52 @@ impl OverprintBlack { } changed } + + /// [`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 { + match self.marked(a, spots) { + Some(n) => { + *a = n; + true + } + None => false, + } + } + + /// `n`'s subtree with [`Self::apply`] done to each node, when that changes anything (`None` + /// otherwise). Each node is visited once, and only the nodes on the way to a change are copied. + fn marked(&self, n: &Arc, spots: &[String]) -> Option> { + let members: Vec<(usize, Arc)> = + n.children().into_iter().flatten().enumerate().filter_map(|(i, c)| Some((i, self.marked(c, spots)?))).collect(); + if members.is_empty() && !self.changes(n, spots) { + return None; + } + let mut copy = Arc::clone(n); + let m = Arc::make_mut(&mut copy); + self.apply(m, spots); + if let Some(children) = m.children_mut() { + for (i, c) in members { + if let Some(slot) = children.get_mut(i) { + *slot = c; + } + } + } + Some(copy) + } + + /// Whether [`Self::apply`] changes a fill, stroke or character of `n` itself. + fn changes(&self, n: &Node, spots: &[String]) -> bool { + let on = !self.remove; + let item = |it: &crate::AppearanceItem| { + it.overprint() != on && (if it.is_fill() { self.fill } else { self.stroke }) && self.black(it.paint(), spots) + }; + let run = |r: &crate::TextRun| { + (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)) + } } impl Node { @@ -236,6 +288,60 @@ mod tests { assert!(tx.runs[0].style.overprint_fill); } + #[test] + fn a_freeform_gradient_is_black_when_every_point_is() { + use vectorcraft_color::freeform::{Freeform, FreeformPoint}; + let k = Color::cmyk(0.0, 0.0, 0.0, 1.0); + let mut g = vectorcraft_color::GradientPaint::new(Default::default()); + for s in &mut g.gradient.stops { + s.color = k; + } + let points = vec![FreeformPoint::new(Point::ZERO, k), FreeformPoint::new(Point::new(10.0, 0.0), Color::cmyk(1.0, 0.0, 0.0, 0.0))]; + g.freeform = Some(Freeform { points, ..Default::default() }); + let fill = |g: &vectorcraft_color::GradientPaint| Appearance::basic(Paint::Gradient(Box::new(g.clone())), Paint::None, 0.0); + let mut n = Node::path(NodeId(1), Default::default(), fill(&g)); + assert!(!OverprintBlack::default().apply(&mut n, &[]), "a cyan point is drawn, whatever the stops"); + if let Some(f) = &mut g.freeform { + f.points[1].color = Color::gray(1.0); + } + let mut n = Node::path(NodeId(1), Default::default(), fill(&g)); + assert!(OverprintBlack::default().apply(&mut n, &[]), "every point black"); + g.freeform = Some(Freeform::default()); + let mut n = Node::path(NodeId(1), Default::default(), fill(&g)); + assert!(OverprintBlack::default().apply(&mut n, &[]), "no points: placed from the black stops"); + } + + #[test] + fn a_gradient_with_a_spot_linked_stop_is_black_only_with_spot() { + let mut g = vectorcraft_color::GradientPaint::new(Default::default()); + for s in &mut g.gradient.stops { + s.color = Color::cmyk(0.0, 0.0, 0.0, 1.0); + } + g.gradient.stops[0].swatch = Some("Ink".into()); + let k = Paint::Gradient(Box::new(g)); + let mut n = Node::path(NodeId(1), Default::default(), Appearance::basic(k, Paint::None, 0.0)); + let spots = ["Ink".to_string()]; + assert!(!OverprintBlack::default().apply(&mut n, &spots), "a stop linked to a spot swatch is not process black"); + assert!(OverprintBlack { spot: true, ..Default::default() }.apply(&mut n, &spots), "Include Spot Blacks takes it"); + } + + #[test] + fn apply_deep_copies_only_the_nodes_that_change() { + let k = cmyk(0.0, 0.0, 0.0, 1.0); + let black = Arc::new(Node::path(NodeId(2), Default::default(), Appearance::basic(k, Paint::None, 0.0))); + let cyan = Arc::new(Node::path(NodeId(3), Default::default(), Appearance::basic(cmyk(1.0, 0.0, 0.0, 0.0), Paint::None, 0.0))); + let mut group = Arc::new(Node::group(NodeId(1), vec![black.clone(), cyan.clone()])); + let before = group.clone(); + assert!(OverprintBlack::default().apply_deep(&mut group, &[])); + let members = group.children().unwrap(); + assert!(members[0].appearance.fill().unwrap().overprint && !black.has_overprint(), "the copy is marked, not the original"); + assert!(Arc::ptr_eq(&members[1], &cyan), "the cyan member is shared, not copied"); + assert!(!before.has_overprint()); + let marked = group.clone(); + assert!(!OverprintBlack::default().apply_deep(&mut group, &[]), "nothing left to change"); + assert!(Arc::ptr_eq(&group, &marked), "and nothing is copied"); + } + #[test] fn legacy_overprint_black_list_migrates() { let mut d = Document::new(100.0, 100.0); diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index 628facc1c3..bc3c90f321 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { "Print Setup", [], None, - "{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100} (% with custom and tiling), overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one grey page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colours keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colours are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)", + "{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100} (% with custom and tiling), overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one gray page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, overprintBlack: false (separations: solid 100% K or 100% gray fills, strokes and characters, to within half a percent, overprint in the printed copy, gradients when every stop is (every point of a freeform one); rich, RGB, spot-linked and lighter blacks knock out; composite ignores it), inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colors keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colors are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)", has_doc, setup ), diff --git a/crates/engine/src/tests/print.rs b/crates/engine/src/tests/print.rs index f10bf65c94..88ee16c384 100644 --- a/crates/engine/src/tests/print.rs +++ b/crates/engine/src/tests/print.rs @@ -47,6 +47,28 @@ fn setup_is_saved_with_the_document_as_one_undo_step() { assert!(vectorcraft_format::load(v.to_string().as_bytes()).unwrap().print_setup.is_none()); } +#[test] +fn overprint_black_is_saved_with_the_setup_and_in_presets() { + let (mut s, _) = session(); + assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"]["output"]["overprintBlack"], false, "off by default"); + let v = s.execute("print.setup", &json!({"settings": {"output": {"mode": "separations", "overprintBlack": true}}})).unwrap(); + assert_eq!(v["settings"]["output"]["overprintBlack"], true); + let doc = &s.doc().unwrap().doc; + let back = vectorcraft_format::load(&vectorcraft_format::save(doc, false)).unwrap(); + assert!(back.print_setup.as_ref().is_some_and(|p| p["output"]["overprintBlack"] == true), "kept in the native file"); + // Settings saved before the option load with it off; a value that is not true or false is refused. + let old: vectorcraft_pdf::PrintSettings = serde_json::from_value(json!({"output": {"mode": "separations"}})).unwrap(); + assert!(!old.output.overprint_black); + assert!(matches!(s.execute("print.setup", &json!({"settings": {"output": {"overprintBlack": "yes"}}})), Err(EngineError::BadParams { .. }))); + // Print presets keep it and list it as a change from [Default]. + let mut s = Session::new(); + s.execute("print.presets.save", &json!({"name": "Seps", "settings": {"output": {"overprintBlack": true}}})).unwrap(); + assert!(s.prefs.print_presets[0].settings.output.overprint_black); + let v = s.execute("print.presets.list", &json!({})).unwrap(); + let changed: Vec<&str> = v["presets"][1]["changed"].as_array().unwrap().iter().map(|c| c["option"].as_str().unwrap()).collect(); + assert_eq!(changed, ["output.overprintBlack"]); +} + #[test] fn print_writes_the_saved_setup_with_overrides() { let (mut s, _) = session(); diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs index 66d49a3bc4..1e7a3fc71a 100644 --- a/crates/pdf/src/export.rs +++ b/crates/pdf/src/export.rs @@ -108,6 +108,9 @@ pub(crate) struct Exporter<'a> { paper: Rect, /// Overprinting fills and strokes are drawn as forms marked to overprint. pub overprint: bool, + /// Overprinting characters' fills and strokes are drawn with Darken, as a separation's plate + /// draws its overprinting fills and strokes ([`vectorcraft_doc::overprint::darken_overprints`]). + pub darken_overprints: bool, /// An overprinting fill or stroke was drawn so. pub overprinted: bool, /// Characters with neither fill nor stroke, or whose fill is drawn as art (outlines filled diff --git a/crates/pdf/src/export/exporter.rs b/crates/pdf/src/export/exporter.rs index a116f8bc2a..2d18888525 100644 --- a/crates/pdf/src/export/exporter.rs +++ b/crates/pdf/src/export/exporter.rs @@ -62,6 +62,7 @@ impl<'a> Exporter<'a> { in_knockout_mask: false, mask_art_left_out: false, overprint: false, + darken_overprints: false, overprinted: false, invisible: false, inline_depth: 0, diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index 71b65e65d0..c2b67757fc 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -611,6 +611,20 @@ impl Exporter<'_> { } } + /// [`Self::overprinting`] for a character fill or stroke, which has no blend mode of its own: + /// 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; + if overprints && self.darken_overprints && !paint.is_none() && !white { + s.push_blend_mode(krilla::blend::BlendMode::Darken); + self.overprinting(s, overprints, paint, draw); + s.pop(); + } else { + self.overprinting(s, overprints, paint, draw); + } + } + /// Is `p` a paint PDF has no paint for when it paints a fill (`fill`) or a stroke, which /// [`Self::area`] draws as art: a pattern swatch or a gradient drawn as pixels /// ([`vectorcraft_color::GradientPaint::draws_as_pixels`]), but not a Perceptual one of spot diff --git a/crates/pdf/src/export/text.rs b/crates/pdf/src/export/text.rs index ea29167f1b..c3d30b7953 100644 --- a/crates/pdf/src/export/text.rs +++ b/crates/pdf/src/export/text.rs @@ -1,6 +1,6 @@ use vectorcraft_geom::Point; -use super::exporter::{GlyphLine, MAX_INLINE_DEPTH, in_range, norm, to_path, writable, xf}; +use super::exporter::{GlyphLine, MAX_INLINE_DEPTH, blend, in_range, norm, to_path, writable, xf}; use super::images::embed; use super::{ Affine, AppearanceItem, BezPath, BlendMode, Color, Cow, Embedding, Exporter, Fill, FillRule, Glyph, GlyphId, KrillaGlyph, ListMarker, Mark, Node, @@ -56,7 +56,7 @@ impl Exporter<'_> { let fill = &run.style.fill; // Colour bitmap glyphs (emoji) real text doesn't write: all of them, or those it leaves. let mut images: Option> = None; - self.overprinting(s, run.style.overprint_fill, fill, |ex, s| { + self.char_overprinting(s, run.style.overprint_fill, fill, |ex, s| { s.push_transform(&text_space); // The outlines left to fill as paths: all of them, or those real text leaves. let outlines = match plain.as_deref().filter(|_| !fill.is_none() && !ex.area_paint(fill, true)) { @@ -121,7 +121,7 @@ impl Exporter<'_> { if let Some(path) = path { // Character strokes are drawn in text space, with their cap, join and dashes. let st = run.style.stroke_layer(); - self.overprinting(s, st.overprint, &st.paint, |ex, s| { + self.char_overprinting(s, st.overprint, &st.paint, |ex, s| { s.push_transform(&text_space); ex.stroke(s, &bp, &path, FillRule::NonZero, &st, page, layout.bounds); s.pop(); @@ -157,9 +157,16 @@ impl Exporter<'_> { if !ex.area(s, path, krilla::paint::FillRule::NonZero, &fl.paint, (fl.opacity, fl.blend), tb, bp.bounding_box(), true) && let Some(paint) = ex.paint(s, &fl.paint, tb) { + let bl = fl.blend != BlendMode::Normal; + if bl { + s.push_blend_mode(blend(fl.blend)); + } s.set_stroke(None); s.set_fill(Some(Fill { paint, opacity: norm(fl.opacity), rule: krilla::paint::FillRule::NonZero })); s.draw_path(path); + if bl { + s.pop(); + } } }), AppearanceItem::Stroke(st) if st.visible && st.width > 0.0 => { diff --git a/crates/pdf/src/print.rs b/crates/pdf/src/print.rs index 54e85f44b4..a33a997971 100644 --- a/crates/pdf/src/print.rs +++ b/crates/pdf/src/print.rs @@ -39,7 +39,7 @@ use kurbo::{Affine, Rect, Vec2}; use serde::Serialize; use vectorcraft_color::cms::{self, ProfileKind}; use vectorcraft_doc::marks::PrinterMarks; -use vectorcraft_doc::overprint::{clear_overprints, darken_overprints}; +use vectorcraft_doc::overprint::{OverprintBlack, clear_overprints, darken_overprints}; use vectorcraft_doc::{ColorMode, Document, Node, NodeKind}; pub use layout::{MAX_COPIES_PER_SHEET, MAX_TILES, TileGrid}; @@ -181,7 +181,7 @@ pub fn keep_layers(nodes: &mut Vec>, which: PrintLayers) { /// `doc` as `set` prints it: live effects applied (raster effects are rendered by the app first), /// only the layers that print, overprints in composite output as [`PrintAdvanced::overprints`] -/// says. +/// says, and black art overprinting in separations with [`PrintOutput::overprint_black`]. pub fn printed_document<'a>(doc: &'a Document, set: &PrintSettings) -> Cow<'a, Document> { // The layers that do not print are left out first, so the art placed for symbols is only // the art that prints; the layers kept are shown. @@ -190,9 +190,28 @@ pub fn printed_document<'a>(doc: &'a Document, set: &PrintSettings) -> Cow<'a, D let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false }; let mut d = vectorcraft_effects::bake_document_placing_symbols(&kept, true, layers).unwrap_or(kept); composite_overprints(&mut d, set); + separation_overprint_black(&mut d, set); Cow::Owned(d) } +/// Output › Overprint Black in separations: every fill and stroke of solid 100% process black or +/// 100% gray, each to within half a percent ([`vectorcraft_doc::overprint::is_black_ink`]), or a +/// gradient whose every stop is (every point of a freeform one), the characters' too, overprints. Rich black, RGB and Lab black, +/// tints below 99.5%, and colors linked to a spot swatch or to Registration keep +/// knocking out ([`OverprintBlack::default`]). Art that overprints already keeps doing so. +fn separation_overprint_black(doc: &mut Document, set: &PrintSettings) { + if set.output.mode != OutputMode::Separations || !set.output.overprint_black { + return; + } + let mut spots = doc.spot_names(); + spots.push(vectorcraft_color::swatch::REGISTRATION.to_string()); + let op = OverprintBlack::default(); + let symbols = doc.symbols.iter_mut().map(|s| &mut s.art); + for n in doc.layers.iter_mut().chain(symbols).chain(doc.patterns.iter_mut().flat_map(|p| p.art.iter_mut())) { + op.apply_deep(n, &spots); + } +} + /// Overprinting fills and strokes in composite output: discarded (they knock out) or simulated /// (drawn with Darken, as Overprint Preview shows them), after which nothing overprints any /// more; or preserved. Separations always honour them. @@ -482,6 +501,8 @@ fn print_inner(doc: &Document, opts: &PrintOptions, left_out: &mut HashSet Separator<'a> { }); } + /// Whether paint `p` puts none of ink `plate` down, to within half a percent (the other inks a + /// black may carry and still count as black, [`vectorcraft_doc::overprint::is_black_ink`]): a + /// solid color, a gradient whose every stop does, or a freeform gradient with color points + /// whose every point does (points carry no swatch link). + fn no_ink(&self, plate: &str, p: &Paint) -> bool { + const NONE: f32 = 0.005; + match p { + Paint::Solid { color, swatch, tint } => self.ink(plate, color, swatch.as_deref().map(|s| (s, *tint))) <= NONE, + Paint::Gradient(g) => match g.freeform.as_ref().filter(|f| !f.points.is_empty()) { + Some(f) => f.points.iter().all(|pt| self.ink(plate, &pt.color, None) <= NONE), + None => { + !g.gradient.stops.is_empty() + && g.gradient.stops.iter().all(|s| self.stop_ink(plate, &s.color, s.swatch.as_deref().map(|n| (n, s.tint)), s.plates) <= NONE) + } + }, + _ => false, + } + } + + /// 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, + /// where it would draw their Darken as a knockout. + 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); + let n = Arc::make_mut(a); + for it in &mut n.appearance.items { + let normal = match it { + AppearanceItem::Fill(l) => l.blend == BlendMode::Normal, + AppearanceItem::Stroke(l) => l.blend == BlendMode::Normal, + }; + if normal && inkless(it.overprint(), it.paint()) { + *it.paint_mut() = Paint::None; + } + } + if let NodeKind::Text(t) = &mut n.kind { + for r in &mut t.runs { + if inkless(r.style.overprint_fill, &r.style.fill) { + r.style.fill = Paint::None; + } + if inkless(r.style.overprint_stroke, &r.style.stroke) { + r.style.stroke = Paint::None; + } + } + } + for c in n.children_mut().into_iter().flatten() { + self.clear_inkless_overprints(plate, c, discard_white); + } + } + /// The document as plate `plate`: art, symbols, pattern tiles and images in the grey of the /// ink's coverage. Overprinting fills and strokes darken, so where they have none of this /// ink the plate below shows through instead of being knocked out. @@ -140,6 +191,7 @@ impl<'a> Separator<'a> { 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.node(plate, Arc::make_mut(n)); keep_colorized_pixels(n, &d.images, &mut colorized); diff --git a/crates/pdf/src/print/settings.rs b/crates/pdf/src/print/settings.rs index d59e99dab7..aeb9005501 100644 --- a/crates/pdf/src/print/settings.rs +++ b/crates/pdf/src/print/settings.rs @@ -437,6 +437,9 @@ pub struct PrintOutput { pub image: PrintImage, /// Separate spot colours into process inks: no spot plates. pub spots_to_process: bool, + /// Separations: solid 100% black fills and strokes overprint, the characters' too, in the + /// printed copy only ([`super::printed_document`]). Composite output leaves it unused. + pub overprint_black: bool, /// Per-ink options, by ink name; inks not listed print with their defaults. pub inks: Vec, } diff --git a/crates/pdf/src/tests/print.rs b/crates/pdf/src/tests/print.rs index 7fa887a90f..52dc3dac48 100644 --- a/crates/pdf/src/tests/print.rs +++ b/crates/pdf/src/tests/print.rs @@ -615,6 +615,137 @@ fn cmyk_and_a_spot_separate_into_five_plates() { assert_eq!(inks(&p[2]), [0.0, 40.0], "the gold's yellow"); } +/// A 200 × 100 pt CMYK document filled with cyan, with spot swatch `Ink` (100% K) and the objects +/// `art` over the cyan. +fn over_cyan(art: Vec) -> Document { + let mut d = doc(200.0, 100.0, &[(Rect::new(0.0, 0.0, 200.0, 100.0), Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0)))]); + d.color_mode = vectorcraft_doc::ColorMode::Cmyk; + d.swatches.push(Swatch { name: "Ink".into(), paint: Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)), global: true, spot: true }); + let layer = d.default_layer().unwrap(); + for mut n in art { + n.id = d.alloc_id(); + d.insert(Some(layer), usize::MAX, n).unwrap(); + } + d +} + +#[test] +fn overprint_black_keeps_the_inks_under_solid_black_on_separations() { + let k = |v: f32| Paint::solid(Color::cmyk(0.0, 0.0, 0.0, v)); + let spot = Paint::Solid { color: Color::cmyk(0.0, 0.0, 0.0, 1.0), swatch: Some("Ink".into()), tint: 1.0 }; + let stops = vec![GradientStop::new(0.0, Color::cmyk(0.0, 0.0, 0.0, 1.0)), GradientStop::new(1.0, Color::cmyk(0.0, 0.0, 0.0, 0.0))]; + let fade = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + let square = |x: f64, fill: Paint, stroke: Paint| { + Node::path(vectorcraft_doc::NodeId(0), shapes::rectangle(Rect::new(x, 15.0, x + 20.0, 35.0)), Appearance::basic(fill, stroke, 4.0)) + }; + // (left edge, fill, whether the cyan below prints under it with the option on). + let cases = [ + (10.0, k(1.0), true), + (40.0, Paint::solid(Color::gray(1.0)), true), + (70.0, Paint::solid(Color::cmyk(0.6, 0.4, 0.4, 1.0)), false), + (100.0, k(0.99), false), + (130.0, spot, false), + (160.0, fade, false), + ]; + let mut art: Vec = cases.iter().map(|(x, p, _)| square(*x, p.clone(), Paint::None)).collect(); + // A black stroke with no fill: its left side runs down x = 184. + art.push(square(184.0, Paint::None, k(1.0))); + let d = over_cyan(art); + let plates = |v: serde_json::Value| -> Vec { + let opts = PrintOptions { settings: settings(v), ..Default::default() }; + plan(&d, &opts).unwrap().plates.iter().map(|p| render_region(p, Rect::new(0.0, 0.0, 200.0, 100.0), 1.0)).collect() + }; + // Full ink at x on the plate (a rich black's 60% cyan is not). + let inked = |img: &vectorcraft_testkit::raster::Image, x: f64| img.over_white(x as u32, 25)[0] < 40; + let off = plates(json!({"output": {"mode": "separations"}})); + let on = plates(json!({"output": {"mode": "separations", "overprintBlack": true}})); + for (x, _, overprints) in &cases { + assert!(!inked(&off[0], x + 10.0), "off: the art at {x} knocks the cyan out"); + assert_eq!(inked(&on[0], x + 10.0), *overprints, "on: the cyan under the art at {x}"); + } + assert!(!inked(&off[0], 184.0) && inked(&on[0], 184.0), "a black stroke overprints too"); + assert!(inked(&on[0], 194.0), "inside the unfilled square: cyan"); + assert!(inked(&on[3], 20.0) && inked(&off[3], 20.0), "the black prints on the Black plate either way"); + assert!(!inked(&on[3], 2.0), "no black is added where there is none"); + // The K and gray squares put no cyan down, so the cyan plate draws them as nothing: a writer + // without blending modes (PostScript) keeps the cyan under them too. + let opts = PrintOptions { + settings: settings(json!({"output": {"mode": "separations", "overprintBlack": true}})), + postscript: true, + ..Default::default() + }; + let p = plan(&d, &opts).unwrap(); + let fills = |doc: &Document| { + let mut count = 0; + doc.walk(|n| count += usize::from(n.appearance.fill().is_some_and(|f| !f.paint.is_none()))); + count + }; + assert_eq!((fills(&d), fills(&p.plates[0]), fills(&p.plates[3])), (7, 5, 7), "the cyan plate, the Black plate"); + // The document keeps its own settings; composite output ignores the option. + assert!(!d.layers.iter().any(|l| l.has_overprint())); + let marked = |v| printed_document(&d, &settings(v)).layers.iter().any(|l| l.has_overprint()); + assert!(marked(json!({"output": {"mode": "separations", "overprintBlack": true}}))); + assert!(!marked(json!({"output": {"overprintBlack": true}})), "composite"); + assert!(!marked(json!({"output": {"mode": "separations"}})), "off by default"); +} + +#[test] +fn overprint_black_keeps_the_cyan_under_near_and_freeform_blacks_on_postscript_plates() { + // 0.4% cyan beside 100% K counts as black, as does a freeform gradient of black points, and the + // cyan plate draws both as nothing. + let near = Paint::solid(Color::cmyk(0.004, 0.0, 0.0, 1.0)); + let k = Color::cmyk(0.0, 0.0, 0.0, 1.0); + let mut g = GradientPaint::new(Gradient::new(GradientKind::Freeform, vec![GradientStop::new(0.0, k), GradientStop::new(1.0, k)])); + let points = vec![FreeformPoint::new(kurbo::Point::new(45.0, 20.0), k), FreeformPoint::new(kurbo::Point::new(55.0, 30.0), Color::gray(1.0))]; + g.freeform = Some(Freeform { points, ..Default::default() }); + let square = |x: f64, fill: Paint| { + Node::path(vectorcraft_doc::NodeId(0), shapes::rectangle(Rect::new(x, 15.0, x + 20.0, 35.0)), Appearance::basic(fill, Paint::None, 0.0)) + }; + let d = over_cyan(vec![square(10.0, near), square(40.0, Paint::Gradient(Box::new(g)))]); + let opts = PrintOptions { + settings: settings(json!({"output": {"mode": "separations", "overprintBlack": true}})), + postscript: true, + ..Default::default() + }; + let p = plan(&d, &opts).unwrap(); + let fills = |doc: &Document| { + let mut count = 0; + doc.walk(|n| count += usize::from(n.appearance.fill().is_some_and(|f| !f.paint.is_none()))); + count + }; + assert_eq!((fills(&p.plates[0]), fills(&p.plates[3])), (1, 3), "the cyan plate, the Black plate"); +} + +#[test] +fn overprinting_type_leaves_the_inks_below_on_separations() { + let style = vectorcraft_doc::CharStyle { fill: Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)), ..Default::default() }; + let text = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(20.0, 60.0), "Hi", style); + let mut d = over_cyan(vec![Node::new(vectorcraft_doc::NodeId(0), NodeKind::Text(Box::new(text)))]); + let darkens = |d: &Document, v| String::from_utf8_lossy(&job(d, v).bytes).contains("/Darken"); + let seps = json!({"output": {"mode": "separations"}}); + assert!(!darkens(&d, seps.clone()), "black type knocks out"); + assert!(darkens(&d, json!({"output": {"mode": "separations", "overprintBlack": true}})), "Overprint Black: the type overprints"); + // A character fill set to overprint does so on the plates without the option too. + let layer = d.default_layer().unwrap(); + let id = d.node(layer).and_then(|l| l.children()).and_then(|c| c.last()).map(|n| n.id).unwrap(); + let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { panic!("type") }; + t.runs[0].style.overprint_fill = true; + assert!(darkens(&d, seps), "an overprinting character fill"); +} + +#[test] +fn a_type_objects_own_black_fill_overprints_on_separations() { + // No character fill: the type object's own fill paints the characters. + let style = vectorcraft_doc::CharStyle { fill: Paint::None, ..Default::default() }; + let text = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(20.0, 60.0), "Hi", style); + let mut n = Node::new(vectorcraft_doc::NodeId(0), NodeKind::Text(Box::new(text))); + n.appearance = Appearance::basic(Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)), Paint::None, 0.0).into(); + let d = over_cyan(vec![n]); + let darkens = |v| String::from_utf8_lossy(&job(&d, v).bytes).contains("/Darken"); + assert!(!darkens(json!({"output": {"mode": "separations"}})), "it knocks out"); + assert!(darkens(json!({"output": {"mode": "separations", "overprintBlack": true}})), "Overprint Black: it overprints"); +} + /// A 100 pt CMYK document with spot swatch `Gold` and a square filled with gradient `g`. fn gold_gradient_doc(g: GradientPaint) -> Document { let mut d = doc(100.0, 100.0, &[(Rect::new(0.0, 0.0, 50.0, 50.0), Paint::Gradient(Box::new(g)))]); diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index 807beed25a..9c68539120 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -689,6 +689,7 @@ fn output(ui: &mut egui::Ui, d: &mut Dialog, pv: &Result) { }); let separations = choice::(d, "output.mode") == Some(OutputMode::Separations); flag(ui, d, "output.spotsToProcess", tl!("Convert All Spot Colors to Process"), separations); + flag(ui, d, "output.overprintBlack", tl!("Overprint Black"), separations); heading(ui, tl!("Document Ink Options")); let inks = pv.as_ref().ok().and_then(|v| v["inks"].as_array()).map(Vec::as_slice).unwrap_or_default(); if !separations || inks.is_empty() { diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index fcc034cd0f..0679711ede 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -2834,6 +2834,7 @@ digits Malayalam Malajalam Collate Složi po kopijama Composite colours are converted to it; separations separate with it when it is a CMYK profile. Kompozitne boje se pretvaraju u njega; separacije se razdvajaju njime kad je CMYK profil. Convert All Spot Colors to Process Pretvori sve spot boje u procesne + Overprint Black Pretisak crne Default Printer Zadani štampač Document Ink Options Opcije tinti dokumenta Download: Preuzimanje: diff --git a/docs/mcp.md b/docs/mcp.md index c7aa202d3f..61de0b46cd 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8531,10 +8531,18 @@ documents every field: them all. - `marks` and `bleed` as `document.exportPdf` takes them (the bleed is the document's unless `useDocument: false`), drawn around the artboard at the paper's scale; the page information adds the tile and the ink with its screen. -- `output: {mode: composite|separations, emulsion: up|down, image: positive|negative, spotsToProcess, inks: [{name, - print, frequency, angle}]}`: separations print one page per ink in the grey of its coverage (images too; - overprinting fills and strokes don't knock out), Registration on every plate; emulsion down mirrors the page and a - negative inverts it. +- `output: {mode: composite|separations, emulsion: up|down, image: positive|negative, spotsToProcess, overprintBlack, + inks: [{name, print, frequency, angle}]}`: separations print one page per ink in the gray of its coverage (images + too; overprinting fills, strokes and characters don't knock out), Registration on every plate; emulsion down mirrors + the page and a negative inverts it. +- `output.overprintBlack` (default false) makes black ink overprint in separations, as the Output step of + [Print color separations](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) describes: + black art leaves the inks under it on the other plates. Which paints count as black is VectorCraft's own rule: a + fill, stroke or character paint of solid 100% process K or 100% gray, or a gradient whose every stop is (every + color point of a freeform gradient), each to within half a percent (99.5% K counts, and so does 0.4% cyan beside + it). Rich black, RGB and Lab black, tints below 99.5% and colors linked to a spot swatch or to Registration still + knock out. Only the printed copy is marked: the document and its own overprint settings do not change. Composite + output ignores the option, and the Print dialog's Overprint Black checkbox is disabled unless Mode is Separations. - `graphics: {autoFlatness, flatness, fonts}` and `color: {intent, preserveNumbers}` (the intent colours separate with; without preserveNumbers CMYK colours are separated again). diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index af7974b880..c82e9269bf 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1972,6 +1972,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The Place dialog has a Show Import Options checkbox after Link, Template and Replace ([Place multiple files in a document](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/place-multiple-files-in-a-document.html)). On (VectorCraft's default, saved with the preferences), each PDF, DXF or text file asks for its import options before it is placed, also in the place cursor; off (`file.place {showImportOptions: false}`), it is placed with the options last confirmed for its format, and only an encrypted PDF asks, for its password. Text Import Options now starts from the options confirmed last (`crates/ui-egui/src/tests/place.rs`). - Separations Preview shows placed and embedded raster images on the visible plates, as it shows vector art (#4153): an RGB image's pixels are separated into process inks with the proof setup's intent, a CMYK image shows its own inks, a hidden plate's ink leaves the image, and with one plate visible the image shows that plate's ink as a grey. Raster images carry no spot ink, so a spot plate shown alone shows them as paper; a colorized image shows its color's plates. Emoji and other bitmap glyphs follow the same rule. The plate-filtered pixels and their reduced-size copies are kept apart from the image's own pixels, for each set of visible plates, proof setup and color settings, and with the preview off nothing changes. Evidence: `tests::colorize::separations_preview_shows_an_rgb_images_process_inks`, `separations_preview_shows_a_cmyk_images_own_inks`, `separations_preview_keeps_an_images_pixels_per_plate_set`. Print preview fidelity remains the open gap, so scores and hours are unchanged. - Desktop print transport uses `craft-print` for CUPS and modern Windows. Sheet composition, copies, separations and colour management remain in VectorCraft. The Print dialog's Media list also carries the Japanese papers — JIS B4 257 × 364 mm, JIS B5 182 × 257 mm and JIS B6 128 × 182 mm beside the ISO B4/B5 (250 × 353 and 176 × 250 mm, kept so settings and presets saved before them keep their paper), and はがき 100 × 148 mm, 往復はがき 148 × 200 mm, 封筒 長形3号 120 × 235 mm, 長形4号 90 × 225 mm, 角形2号 240 × 332 mm, 角形3号 216 × 277 mm and 四六判 127 × 188 mm; the JSON id or the dialog label names a paper, any case and spacing (`B5 (JIS)` or `b5jis`) (`crates/pdf/src/print/settings.rs`, `crates/pdf/src/tests/print.rs`). The print-preview and physical-device fidelity gaps remain, so print scores and hours are unchanged. + - The Print dialog's Output section has Overprint Black under Convert All Spot Colors to Process, off by default and available with Separations ([Print color separations](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) lists it among the separation options): black art then leaves the inks under it on the other plates (`print.setup {settings: {output: {overprintBlack: true}}}`, kept with the document and in print presets). Solid 100% K or 100% gray fills, strokes and characters (to within half a percent, as Edit › Edit Colors › Overprint Black counts them), and gradients whose every stop (every color point of a freeform gradient) is, overprint; rich, RGB, Lab, spot-linked and lighter blacks knock out, and only the printed copy is marked. These limits are VectorCraft's own rules. Characters set to overprint now also leave the inks below them on printed PDF plates, a type object's own fill in a PDF is drawn with its blending mode, and Edit › Edit Colors › Overprint Black counts a gradient with a stop linked to a spot swatch as a spot black, as it counts a solid one, and a freeform gradient by the color points it draws from. Evidence: `print::overprint_black_keeps_the_inks_under_solid_black_on_separations`, `print::overprint_black_keeps_the_cyan_under_near_and_freeform_blacks_on_postscript_plates`, `print::overprinting_type_leaves_the_inks_below_on_separations`, `print::a_type_objects_own_black_fill_overprints_on_separations`, `tests::print::overprint_black_is_saved_with_the_setup_and_in_presets`, `overprint::tests::a_gradient_with_a_spot_linked_stop_is_black_only_with_spot`, `overprint::tests::a_freeform_gradient_is_black_when_every_point_is`. Print scores and hours are unchanged. - A PDF, PDF-compatible `.ai` or `.ait` opened from its pages or its editing copy opens with the File Info that its XMP packet and its document information dictionary give: the title (`dc:title`, its `x-default` item first, else Info `Title`), the author, description, keywords, copyright status, notice and URL, and the created and modified dates, the XMP packet's value where both give one (`crates/pdf/src/tests/file_info.rs`, `crates/engine/src/tests/fileinfo.rs`). An SVG opens with the title of its root ``. The title is File Info's alone (`DocMetadata::title`): the document's name stays the file's name with its extension, a file that gives no title leaves File Info with that name, and exports (PDF, SVG, PNG, EPS, `.ai`) and native saves carry it; changing the title in File Info sets the document's name as before (#3626). - PDF export and PDF-compatible `.ai` and `.ait` saves write the document's File Info created date as the file's creation date, or the time of writing when the document has none, and the time of writing as its modification date; the page information mark still prints the time of writing (`crates/engine/src/tests/fileinfo.rs`, `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/marks.rs`). - PDF export and PDF-compatible `.ai` and `.ait` saves write File Info's copyright notice, URL and status to the XMP packet (`dc:rights`, `xmpRights:WebStatement`, `xmpRights:Marked`), so a PDF or `.ai` opened from its pages keeps them (`crates/pdf/src/tests/file_info.rs`, `crates/engine/src/tests/fileinfo.rs`).