diff --git a/crates/doc/src/overprint.rs b/crates/doc/src/overprint.rs index 056c8c888f..58f6b5abc2 100644 --- a/crates/doc/src/overprint.rs +++ b/crates/doc/src/overprint.rs @@ -4,7 +4,7 @@ use std::sync::Arc; -use vectorcraft_color::{BlendMode, Color, Paint}; +use vectorcraft_color::{BlendMode, Color, GradientKind, Paint}; use crate::{Document, Node, NodeId, NodeKind}; @@ -46,14 +46,21 @@ 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), + // Only a freeform gradient draws its points; another kind draws its stops whatever it holds. + Paint::Gradient(g) => match g.freeform.as_ref().filter(|f| g.gradient.kind == GradientKind::Freeform && !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 +92,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 +289,65 @@ 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(vectorcraft_color::Gradient { kind: GradientKind::Freeform, ..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"); + // Another kind of gradient draws its black stops, not the points it still holds. + let mut linear = g.clone(); + linear.gradient.kind = GradientKind::Linear; + let mut n = Node::path(NodeId(1), Default::default(), fill(&linear)); + assert!(OverprintBlack::default().apply(&mut n, &[]), "a linear gradient is judged by its 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..504a67d644 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 (1–1000 % with custom and tiling), linked: true (width and height stay equal: give one and the other follows, and turning it on sets the height to the width; a different width and height without linked turn it off, and with linked: true, or linked: null over a linked scale, are an error; a saved scale without linked reads it as false)}, 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 ), @@ -82,11 +82,38 @@ pub(crate) fn settings_over(cmd: &str, mut v: Value, p: &Value) -> Result merge(&mut v, over), Some(_) => return Err(bad(cmd, "settings must be an object")), } + link_scale(cmd, &mut v, p.get("settings").and_then(|s| s.get("scale")).filter(|s| s.is_object()))?; let set = PrintSettings::deserialize(&v).map_err(|e| bad(cmd, format!("print settings: {e}")))?; set.check().map_err(|e| pdf_error(cmd, e))?; Ok(set) } +/// Keep the custom scale's width and height equal in the merged settings `v` while `scale.linked` +/// is on, after `over` (the request's `scale`) was merged in: the one side the request gives sets +/// the other, and otherwise the height takes the width (as turning the link on does). A request +/// that gives a different width and height without a `linked` key turns the link off; with +/// `linked: true`, or with `linked: null` over a linked scale, it is refused. +fn link_scale(cmd: &str, v: &mut Value, over: Option<&Value>) -> Result<()> { + let given = |k: &str| over.and_then(|o| o.get(k)).filter(|x| !x.is_null()); + let (width, height) = (given("width").cloned(), given("height").cloned()); + let apart = matches!((&width, &height), (Some(w), Some(h)) if w.as_f64() != h.as_f64()); + let Some(scale) = v.get_mut("scale").and_then(Value::as_object_mut) else { return Ok(()) }; + if apart && over.and_then(|o| o.get("linked")).is_none() { + scale.insert("linked".into(), Value::Bool(false)); + } + if scale.get("linked") != Some(&Value::Bool(true)) { + return Ok(()); + } + if apart { + return Err(bad(cmd, "scale: give one percentage, or the same width and height, while scale.linked is on (linked: false scales them apart)")); + } + let (from, to) = if width.is_none() && height.is_some() { ("height", "width") } else { ("width", "height") }; + if let Some(value) = scale.get(from).cloned() { + scale.insert(to.into(), value); + } + Ok(()) +} + pub(crate) fn to_json(set: &PrintSettings) -> Result { serde_json::to_value(set).map_err(|e| EngineError::Other(e.to_string())) } diff --git a/crates/engine/src/tests/print.rs b/crates/engine/src/tests/print.rs index f10bf65c94..e2ea85d54f 100644 --- a/crates/engine/src/tests/print.rs +++ b/crates/engine/src/tests/print.rs @@ -47,6 +47,81 @@ 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 the_scale_link_keeps_width_and_height_equal() { + let (mut s, _) = session(); + let scale = |s: &mut Session, p: Value| s.execute("print.setup", &json!({ "settings": p })).unwrap()["settings"]["scale"].clone(); + assert_eq!(scale(&mut s, json!({})), json!({"width": 100.0, "height": 100.0, "linked": true}), "on for a new job"); + // Linked, one percentage sets the other, whichever it is. + assert_eq!(scale(&mut s, json!({"scaling": "custom", "scale": {"width": 40}})), json!({"width": 40.0, "height": 40.0, "linked": true})); + assert_eq!(scale(&mut s, json!({"scale": {"height": 250}})), json!({"width": 250.0, "height": 250.0, "linked": true})); + assert_eq!(scale(&mut s, json!({"scale": {"width": 60, "height": 60.0}})), json!({"width": 60.0, "height": 60.0, "linked": true})); + // Two different percentages with linked: true are refused and keep what was saved. + let apart = s.execute("print.setup", &json!({"settings": {"scale": {"width": 50, "height": 200, "linked": true}}})); + assert!(matches!(apart, Err(EngineError::BadParams { .. })), "{apart:?}"); + assert!(s.execute("print.preview", &json!({"settings": {"scale": {"width": 50, "height": 200, "linked": true}}})).is_err()); + // `linked: null` keeps the saved link, as null keeps any saved setting. + let kept = s.execute("print.setup", &json!({"settings": {"scale": {"width": 50, "height": 200, "linked": null}}})); + assert!(matches!(kept, Err(EngineError::BadParams { .. })), "{kept:?}"); + assert_eq!(scale(&mut s, json!({}))["width"], 60.0); + // Without linked, two different percentages turn the link off and print as given. + assert_eq!(scale(&mut s, json!({"scale": {"width": 50, "height": 200}})), json!({"width": 50.0, "height": 200.0, "linked": false})); + assert_eq!(s.execute("print.preview", &json!({})).unwrap()["sheets"][0]["scale"], json!([50.0, 200.0])); + // Unlinked, each changes alone; turning the link on sets the height to the width. + assert_eq!(scale(&mut s, json!({"scale": {"height": 120}})), json!({"width": 50.0, "height": 120.0, "linked": false})); + assert_eq!(scale(&mut s, json!({"scale": {"linked": true}})), json!({"width": 50.0, "height": 50.0, "linked": true})); + assert_eq!(s.execute("print.preview", &json!({})).unwrap()["sheets"][0]["scale"], json!([50.0, 50.0])); + // Kept in the native file and in print presets. + let doc = &s.doc().unwrap().doc; + let back = vectorcraft_format::load(&vectorcraft_format::save(doc, false)).unwrap(); + assert_eq!(back.print_setup.as_ref().map(|p| p["scale"].clone()), Some(json!({"width": 50.0, "height": 50.0, "linked": true}))); + s.execute("print.presets.save", &json!({"name": "Apart", "settings": {"scaling": "custom", "scale": {"width": 30, "height": 90}}})).unwrap(); + let preset = s.prefs.print_presets.iter().find(|p| p.name == "Apart").map(|p| p.settings.scale.clone()); + assert_eq!(preset.map(|p| (p.width, p.height, p.linked)), Some((30.0, 90.0, false))); + assert_eq!(scale(&mut s, json!({}))["linked"], true, "saving a preset leaves the document's settings"); + let v = s.execute("print.setup", &json!({"preset": "Apart"})).unwrap(); + assert_eq!(v["settings"]["scale"], json!({"width": 30.0, "height": 90.0, "linked": false})); +} + +#[test] +fn a_scale_saved_without_the_link_keeps_its_width_and_height() { + let (mut s, _) = session(); + // Settings saved before the link had no `linked`: they print as they did, unlinked. + let mut old = serde_json::to_value(vectorcraft_pdf::PrintSettings::default()).unwrap(); + old["scaling"] = json!("custom"); + old["scale"] = json!({"width": 50, "height": 200}); + let mut doc = (*s.doc().unwrap().doc).clone(); + doc.print_setup = Some(old); + s.doc_mut().unwrap().doc = std::sync::Arc::new(doc); + let pv = s.execute("print.preview", &json!({})).unwrap(); + assert_eq!(pv["sheets"][0]["scale"], json!([50.0, 200.0])); + assert_eq!(pv["settings"]["scale"]["linked"], false); + // One percentage changes alone until the link is turned on. + assert_eq!(s.execute("print.preview", &json!({"settings": {"scale": {"width": 80}}})).unwrap()["sheets"][0]["scale"], json!([80.0, 200.0])); +} + #[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..c6b165bbd5 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -39,14 +39,15 @@ impl Exporter<'_> { cover(&mut ms, page, if m.clip { 0 } else { 255 }, 1.0); } // Mask art is a picture of its own: it takes no part in a knockout group around the object, - // and has no inks to overprint. + // and has no inks to overprint (its characters do not darken either). let knockout = std::mem::take(&mut self.knockout); let overprint = std::mem::take(&mut self.overprint); + let darken = std::mem::take(&mut self.darken_overprints); let image_left_out = self.image_left_out.replace(false); self.node(&mut ms, &m.art, page, true); let incomplete = self.image_left_out.unwrap_or(false); self.image_left_out = image_left_out.map(|outer| outer || incomplete); - (self.knockout, self.overprint) = (knockout, overprint); + (self.knockout, self.overprint, self.darken_overprints) = (knockout, overprint, darken); if incomplete { ms.pop(); ms.finish(); @@ -611,6 +612,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..ba4fc5589f 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,213 @@ 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. A +/// symbol instance that repaints its art is judged by the paints it prints with +/// ([`place_repainted_instances`]). +fn separation_overprint_black(doc: &mut Document, set: &PrintSettings) { + if set.output.mode != OutputMode::Separations || !set.output.overprint_black { + return; + } + place_repainted_instances(doc); + 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); + } +} + +/// Replace each symbol instance in `doc`'s layers and patterns whose own fill or stroke changes +/// ([`vectorcraft_doc::symbol_overrides::SymbolOverride`]) or fill stain repaint its symbol's art +/// ([`repaints`]), or whose symbol's art holds such an instance at any depth, with that art as +/// the instance prints it ([`Placing::instance`]). Then the same is done inside the art of the +/// symbols type shows as inline graphics ([`inline_symbols`]), which draw their symbol's art as it +/// is; the other symbols' own art stays as it is, and so do hidden objects and template layers. +/// Once the layers and patterns, with the art placed for symbols already, hold +/// [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects, the remaining instances stay as they are, and so +/// do instances whose art would draw deeper than [`vectorcraft_doc::depth::MAX_DRAWN_DEPTH`]. +fn place_repainted_instances(doc: &mut Document) { + let holders = repainting_symbols(doc); + let art = || doc.layers.iter().chain(doc.patterns.iter().flat_map(|p| p.art.iter())); + if holders.is_empty() && !art().any(|n| holds_repaint(n, &holders)) { + return; + } + let held = art().map(|n| n.count_with_masks() as u64).fold(0u64, u64::saturating_add); + let mut placing = + Placing { holders, heights: vectorcraft_doc::depth::DrawnHeights::of(doc), budget: vectorcraft_doc::MAX_SYMBOL_NODES.saturating_sub(held) }; + // The art placed for an instance holds the instances inside it: each pass places those, up + // to the depth objects are drawn to. + for _ in 0..=vectorcraft_doc::depth::MAX_DRAWN_DEPTH { + let mut changed = false; + for i in 0..doc.layers.len() { + if let Some(layer) = placing.subtree(doc, &doc.layers[i], 1) { + doc.layers[i] = layer; + changed = true; + } + } + for p in 0..doc.patterns.len() { + for i in 0..doc.patterns[p].art.len() { + if let Some(art) = placing.subtree(doc, &doc.patterns[p].art[i], 1) { + doc.patterns[p].art[i] = art; + changed = true; + } + } + } + if !changed { + break; + } + } + let inline = inline_symbols(doc); + for _ in 0..=vectorcraft_doc::depth::MAX_DRAWN_DEPTH { + let mut changed = false; + for i in 0..doc.symbols.len() { + if inline.contains(&doc.symbols[i].name) + && let Some(art) = placing.subtree(doc, &doc.symbols[i].art, 1) + { + doc.symbols[i].art = art; + changed = true; + } + } + if !changed { + return; + } + } +} + +/// The names of the symbols that type in `doc` shows as inline graphics, in its layers, symbols +/// and patterns. +fn inline_symbols(doc: &Document) -> HashSet { + fn visit(n: &Node, out: &mut HashSet) { + if let NodeKind::Text(t) = &n.kind { + out.extend(t.runs.iter().filter_map(|r| r.inline.as_ref()).map(|i| i.symbol.clone())); + } + for c in n.children().into_iter().flatten() { + visit(c, out); + } + } + let mut out = HashSet::new(); + for n in doc.layers.iter().chain(doc.symbols.iter().map(|s| &s.art)).chain(doc.patterns.iter().flat_map(|p| p.art.iter())) { + visit(n, &mut out); + } + out +} + +/// Does symbol instance `n` repaint its symbol's art: with its own fill or stroke changes, or with +/// its fill's stain? +fn repaints(n: &Node) -> bool { + matches!(n.kind, NodeKind::SymbolInstance { .. }) + && (n.extras().symbol_overrides.iter().any(|o| o.fill.is_some() || o.stroke.is_some()) + || vectorcraft_doc::symbol_overrides::stain(n).is_some()) +} + +/// Does `n`'s subtree hold a repainting instance ([`repaints`]) or an instance of one of the +/// symbols `holders`? +fn holds_repaint(n: &Node, holders: &HashSet) -> bool { + repaints(n) + || matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if holders.contains(symbol)) + || n.children().is_some_and(|c| c.iter().any(|c| holds_repaint(c, holders))) +} + +/// The names of the symbols whose art holds a repainting instance ([`repaints`]) at any depth, +/// through the instances of other symbols too. +fn repainting_symbols(doc: &Document) -> HashSet { + let mut out = HashSet::new(); + loop { + let before = out.len(); + for s in &doc.symbols { + if !out.contains(&s.name) && holds_repaint(&s.art, &out) { + out.insert(s.name.clone()); + } + } + if out.len() == before { + return out; + } + } +} + +/// What [`place_repainted_instances`] places instances with. +struct Placing { + /// The symbols whose art holds a repainting instance ([`repainting_symbols`]). + holders: HashSet, + heights: vectorcraft_doc::depth::DrawnHeights, + /// The objects left to place. + budget: u64, +} + +impl Placing { + /// `n`'s subtree, `n` placed `level` deep, with its instances that [`Self::instance`] places + /// placed, copying only the nodes on the way to them; `None` when there is none. Hidden + /// objects and template layers do not print and are left as they are. + fn subtree(&mut self, doc: &Document, n: &Arc, level: usize) -> Option> { + if !n.visible || matches!(n.kind, NodeKind::Layer { template: true, .. }) { + return None; + } + if let Some(g) = self.instance(doc, n, level) { + return Some(Arc::new(g)); + } + let members: Vec<(usize, Arc)> = + n.children().into_iter().flatten().enumerate().filter_map(|(i, c)| Some((i, self.subtree(doc, c, level + 1)?))).collect(); + if members.is_empty() { + return None; + } + let mut copy = Arc::clone(n); + if let Some(children) = Arc::make_mut(&mut copy).children_mut() { + for (i, c) in members { + if let Some(slot) = children.get_mut(i) { + *slot = c; + } + } + } + Some(copy) + } + + /// Symbol instance `n`, placed `level` deep, when it repaints its art ([`repaints`]) or its + /// symbol is one of [`Self::holders`], as a group of that art placed as the exporter places + /// it, with the instance's id, name, visibility, transparency, opacity mask, effects and + /// attributes. `None` for other objects, for instances of a missing symbol, when the art does + /// not fit in [`Self::budget`] (which it is taken from), and when it would draw deeper than + /// [`vectorcraft_doc::depth::MAX_DRAWN_DEPTH`]. + fn instance(&mut self, doc: &Document, n: &Node, level: usize) -> Option { + let NodeKind::SymbolInstance { symbol, xf } = &n.kind else { return None }; + if !repaints(n) && !self.holders.contains(symbol) { + return None; + } + let sym = doc.symbols.iter().find(|s| s.name == *symbol)?; + let art = vectorcraft_doc::symbol_overrides::instance_art(&sym.art, n); + // The most objects placing it can make, counted before it is placed. + let most = doc.symbol_slice_map(symbol, *xf).map_or(art.count_with_masks() as u64, |m| m.most_placed(&art, doc)); + let left = self.budget.checked_sub(most)?; + let placed = doc.place_symbol_art(symbol, &art, *xf)?; + let mut g = Node::group(n.id, vec![Arc::new(placed)]); + g.name = n.name.clone(); + g.visible = n.visible; + g.opacity = n.opacity; + g.blend = n.blend; + g.isolate = n.isolate; + // One element of an enclosing knockout group, as the instance is: its pieces never knock + // each other out. + g.knockout = vectorcraft_doc::Knockout::Off; + g.knockout_shape = n.knockout_shape; + g.appearance.effects = n.appearance.effects.clone(); + g.extras_mut().mask = n.extras().mask.clone(); + g.extras_mut().attrs = n.extras().attrs.clone(); + if self.heights.deepest(&g, level) > vectorcraft_doc::depth::MAX_DRAWN_DEPTH { + return None; + } + self.budget = left; + Some(g) + } +} + /// 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. @@ -404,7 +608,7 @@ pub fn plan<'a>(doc: &'a Document, opts: &PrintOptions) -> Result, let job = Job::new(doc, set, opts.postscript)?; let title = opts.title.clone().unwrap_or_else(|| job.doc.title.clone()); let created = opts.created.or_else(vectorcraft_doc::metadata::output_time); - let sep = Separator::new(&job.doc, set); + let sep = Separator::new(&job.doc, set, opts.postscript); let plates: Vec = (0..job.plates.len()).filter_map(|p| job.ink(Some(p))).map(|i| sep.plate(&i.name)).collect(); let marks = set.marks.printer_marks(); let sheets = job @@ -482,6 +686,8 @@ fn print_inner(doc: &Document, opts: &PrintOptions, left_out: &mut HashSet { pub doc: &'a Document, cms: Arc, set: &'a PrintSettings, + /// The plates are written as PostScript, which has no blending modes. + postscript: bool, } impl<'a> Separator<'a> { - pub fn new(doc: &'a Document, set: &'a PrintSettings) -> Self { - Self { doc, cms: separation_cms(doc, set), set } + pub fn new(doc: &'a Document, set: &'a PrintSettings, postscript: bool) -> Self { + Self { doc, cms: separation_cms(doc, set), set, postscript } } /// How much of ink `plate` colour `c` (with swatch link `link`) prints, 0..1. @@ -131,6 +133,57 @@ impl<'a> Separator<'a> { }); } + /// Whether paint `p` puts none of ink `plate` down: 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). On PostScript plates, to within half a percent (the other inks a black may + /// carry and still count as black, [`vectorcraft_doc::overprint::is_black_ink`]). + fn no_ink(&self, plate: &str, p: &Paint) -> bool { + let none = if self.postscript { 0.005 } else { 0.0 }; + 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| g.gradient.kind == GradientKind::Freeform && !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 +193,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..15e029a13a 100644 --- a/crates/pdf/src/print/settings.rs +++ b/crates/pdf/src/print/settings.rs @@ -420,11 +420,15 @@ pub struct Placement { pub struct PrintScale { pub width: f64, pub height: f64, + /// The link between the width and the height: on, both are the same percentage. On for new + /// settings; a saved scale without it reads as off, so its width and height stay as saved. + #[serde(default)] + pub linked: bool, } impl Default for PrintScale { fn default() -> Self { - Self { width: 100.0, height: 100.0 } + Self { width: 100.0, height: 100.0, linked: true } } } @@ -437,6 +441,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, } @@ -582,6 +589,12 @@ impl PrintSettings { within("placement.y", self.placement.y, -14_400.0, 14_400.0, " pt")?; within("scale.width", self.scale.width, 1.0, 1000.0, "%")?; within("scale.height", self.scale.height, 1.0, 1000.0, "%")?; + if self.scale.linked && self.scale.width != self.scale.height { + return Err(PdfError::BadSetting(format!( + "scale: width ({}%) and height ({}%) must be equal while scale.linked is on", + self.scale.width, self.scale.height + ))); + } within("overlap", self.overlap, 0.0, 720.0, " pt")?; within("gutter", self.gutter, 0.0, 720.0, " pt")?; within("margin", self.margin, 0.0, 144.0, " pt")?; diff --git a/crates/pdf/src/tests/print.rs b/crates/pdf/src/tests/print.rs index 7fa887a90f..2ae14a8d55 100644 --- a/crates/pdf/src/tests/print.rs +++ b/crates/pdf/src/tests/print.rs @@ -105,6 +105,28 @@ fn defaults_and_json() { assert_eq!(Media::A4.size().map(|(w, h)| (w.round(), h.round())), Some((595.0, 842.0))); } +#[test] +fn the_scale_link_is_on_for_new_settings_and_off_for_a_saved_scale_without_it() { + let s = PrintSettings::default(); + assert!(s.scale.linked, "new settings keep W and H equal"); + assert_eq!(serde_json::to_value(&s).unwrap()["scale"], json!({"width": 100.0, "height": 100.0, "linked": true})); + // Settings without a scale are new settings; a scale saved before the link reads as unlinked, + // so its width and height print as they did. + assert!(settings(json!({"copies": 2})).scale.linked); + let old = settings(json!({"scaling": "custom", "scale": {"width": 50, "height": 200}})); + assert_eq!((old.scale.width, old.scale.height, old.scale.linked), (50.0, 200.0, false)); + assert!(old.check().is_ok()); + // Linked, the two must be equal; the range still holds for both. + let apart = settings(json!({"scale": {"width": 50, "height": 200, "linked": true}})); + assert!(matches!(apart.check(), Err(PdfError::BadSetting(_)))); + for bad in + [json!({"width": 0, "height": 0, "linked": true}), json!({"width": 1001, "height": 1001, "linked": true}), json!({"width": -5, "height": 50})] + { + assert!(matches!(settings(json!({ "scale": bad })).check(), Err(PdfError::BadSetting(_))), "{bad}"); + } + assert!(settings(json!({"scale": {"width": 1000, "height": 1000, "linked": true}})).check().is_ok()); +} + #[test] fn japanese_paper_sizes() { // The Japanese papers: JIS B4, B5 and B6 are the sizes Japanese printing uses (JIS X 6310), @@ -615,6 +637,239 @@ 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 do a freeform gradient of black points and a + // linear gradient of black stops, and the cyan plate draws them all 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() }); + // A linear gradient draws its black stops, not the cyan point it still holds. + let mut linear = g.clone(); + linear.gradient.kind = GradientKind::Linear; + if let Some(f) = &mut linear.freeform { + f.points[1].color = Color::cmyk(1.0, 0.0, 0.0, 0.0); + } + 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))), square(70.0, Paint::Gradient(Box::new(linear)))]); + 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, 4), "the cyan plate, the Black plate"); +} + +#[test] +fn an_overprinting_fill_keeps_its_faint_ink_on_pdf_plates() { + // 0.4% cyan beside 100% K, set to overprint: a PDF plate draws it with Darken, a PostScript + // plate draws it as nothing (it has no blending modes). + let mut square = Node::path( + vectorcraft_doc::NodeId(0), + shapes::rectangle(Rect::new(10.0, 15.0, 30.0, 35.0)), + Appearance::basic(Paint::solid(Color::cmyk(0.004, 0.0, 0.0, 1.0)), Paint::None, 0.0), + ); + if let Some(f) = square.appearance.fill_mut() { + f.overprint = true; + } + let d = over_cyan(vec![square]); + let fills = |postscript: bool| { + let opts = PrintOptions { settings: settings(json!({"output": {"mode": "separations"}})), postscript, ..Default::default() }; + let p = plan(&d, &opts).unwrap(); + let mut count = 0; + p.plates[0].walk(|n| count += usize::from(n.appearance.fill().is_some_and(|f| !f.paint.is_none()))); + count + }; + assert_eq!((fills(false), fills(true)), (2, 1), "the cyan plate as PDF, as PostScript"); +} + +#[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"); +} + +#[test] +fn overprint_black_follows_a_symbol_instances_own_fill_on_separations() { + use vectorcraft_doc::symbol_overrides::SymbolOverride; + let (k, magenta) = (Color::cmyk(0.0, 0.0, 0.0, 1.0), Color::cmyk(0.0, 1.0, 0.0, 0.0)); + let square = |x: f64, c: Color| { + let r = shapes::rectangle(Rect::new(x, 15.0, x + 20.0, 35.0)); + Arc::new(Node::path(vectorcraft_doc::NodeId(0), r, Appearance::basic(Paint::solid(c), Paint::None, 0.0))) + }; + let instance = |symbol: &str, fill: Color| { + let mut n = Node::new(vectorcraft_doc::NodeId(0), NodeKind::SymbolInstance { symbol: symbol.into(), xf: Default::default() }); + n.extras_mut().symbol_overrides = vec![SymbolOverride { path: vec![], fill: Some(Paint::solid(fill)), ..Default::default() }]; + n + }; + // An instance of "Outer", whose art is the magenta symbol's instance painted black, moved right. + let outer = + Node::new(vectorcraft_doc::NodeId(0), NodeKind::SymbolInstance { symbol: "Outer".into(), xf: kurbo::Affine::translate((140.0, 0.0)) }); + let mut d = over_cyan(vec![instance("Magenta", k), instance("Black", magenta), outer]); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: true, name: "Magenta".into(), art: square(10.0, magenta) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: true, name: "Black".into(), art: square(40.0, k) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Outer".into(), art: Arc::new(instance("Magenta", k)) }); + let opts = PrintOptions { settings: settings(json!({"output": {"mode": "separations", "overprintBlack": true}})), ..Default::default() }; + let p = plan(&d, &opts).unwrap(); + let cyan = render_region(&p.plates[0], Rect::new(0.0, 0.0, 200.0, 100.0), 1.0); + let inked = |x: u32| cyan.over_white(x, 25)[0] < 40; + assert!(inked(20), "a magenta symbol's instance painted black overprints the cyan"); + assert!(!inked(50), "a black symbol's instance painted magenta knocks the cyan out"); + assert!(inked(160), "the instance painted black inside another symbol's art overprints too"); + assert!(!d.symbols.iter().any(|s| s.art.has_overprint()), "the document keeps its own settings"); +} + +#[test] +fn overprint_black_follows_instance_paints_in_inline_graphics() { + use vectorcraft_doc::symbol_overrides::SymbolOverride; + // Type shows symbol "Holder" inline; its art is an instance of a black symbol painted magenta. + let k = Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)); + let r = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)); + let mut inst = Node::new(vectorcraft_doc::NodeId(0), NodeKind::SymbolInstance { symbol: "Black".into(), xf: Default::default() }); + let magenta = Paint::solid(Color::cmyk(0.0, 1.0, 0.0, 0.0)); + inst.extras_mut().symbol_overrides = vec![SymbolOverride { path: vec![], fill: Some(magenta), ..Default::default() }]; + let mut text = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(20.0, 60.0), "Hi", Default::default()); + text.runs.push(vectorcraft_doc::TextRun::inline(vectorcraft_doc::InlineArt::new("Holder"), Default::default())); + let mut d = over_cyan(vec![Node::new(vectorcraft_doc::NodeId(0), NodeKind::Text(Box::new(text)))]); + let black = Arc::new(Node::path(vectorcraft_doc::NodeId(0), r, Appearance::basic(k, Paint::None, 0.0))); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: true, name: "Black".into(), art: black }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Holder".into(), art: Arc::new(inst) }); + let printed = printed_document(&d, &settings(json!({"output": {"mode": "separations", "overprintBlack": true}}))); + let holder = printed.symbols.iter().find(|s| s.name == "Holder").unwrap(); + let mut instances = 0; + holder.art.walk(&mut |n: &Node| instances += usize::from(matches!(n.kind, NodeKind::SymbolInstance { .. }))); + assert_eq!(instances, 0, "the instance is placed as the art it prints"); + assert!(!holder.art.has_overprint(), "its magenta fill knocks out"); + assert!(matches!(d.symbols[1].art.kind, NodeKind::SymbolInstance { .. }), "the document keeps its art"); +} + +#[test] +fn overprinting_type_in_an_opacity_mask_does_not_darken_on_separations() { + // Mask art has no inks: an overprinting gray character in an inverted clipping mask keeps its + // luminance on every plate. + let style = vectorcraft_doc::CharStyle { fill: Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 0.5)), overprint_fill: true, ..Default::default() }; + let text = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(20.0, 60.0), "Hi", style); + let mut mask = vectorcraft_doc::OpacityMask::new(Node::new(vectorcraft_doc::NodeId(0), NodeKind::Text(Box::new(text))), true); + mask.invert = true; + let square = Node::path( + vectorcraft_doc::NodeId(0), + shapes::rectangle(Rect::new(10.0, 10.0, 90.0, 90.0)), + Appearance::basic(Paint::solid(Color::cmyk(0.0, 1.0, 0.0, 0.0)), Paint::None, 0.0), + ) + .with_mask(Some(Box::new(mask))); + let d = over_cyan(vec![square]); + let bytes = job(&d, json!({"output": {"mode": "separations"}})).bytes; + assert!(!String::from_utf8_lossy(&bytes).contains("/Darken"), "the mask's character is drawn as it is"); +} + /// 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..017e669d9c 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -69,6 +69,11 @@ pub(super) fn defaults(kind: &str) -> Option<&'static Value> { /// Set when the Print Tiling tool placed the pages (`tileOrigin`): the placement is ignored. const PLACED: &str = "tileOrigin.placed"; +/// The link between Scale W and H. +const SCALE_LINKED: &str = "scale.linked"; +/// Scale W and H as [`link_scale`] last left them, to tell which one changed since. +const SCALE_SEEN: &str = "__scaleSeen"; + /// The fields that aren't print settings. const NOT_SETTINGS: [&str; 5] = ["printer", "toFile", "discard", "preset", "name"]; @@ -97,6 +102,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { let preset = app.session.prefs.print_presets.iter().find(|p| p.settings == saved).map_or(DEFAULT_PRESET, |p| p.name.as_str()); fields.insert("preset".into(), json!(preset)); fields.insert(LOADED.into(), json!(preset)); + see_scale(&mut fields); app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); Ok(Value::Null) } @@ -118,6 +124,7 @@ fn sync_preset(app: &VectorcraftApp, d: &mut Dialog) -> Result<(), String> { d.fields.insert(LOADED.into(), json!(name)); let set = app.session.print_preset_settings(&name).ok_or_else(|| format!("no print preset named `{name}`"))?; d.fields.extend(fields_of(&set)?); + see_scale(&mut d.fields); Ok(()) } @@ -148,6 +155,7 @@ pub fn open_preset(app: &mut VectorcraftApp, params: &Value) -> Result Result Result { + let mut d = d.clone(); + link_scale(&mut d); + let d = &d; let (name, editing) = (d.str("name"), d.str(EDITING)); let p = if editing.is_empty() { if app.session.print_preset_settings(&name).is_some() { @@ -188,6 +199,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { // Done's flag holds for this press only: the dialog may stay open. let done = d.fields.remove("discard").is_some_and(|v| v == true); let synced = sync_preset(app, &mut d); + link_scale(&mut d); app.ui.dialog = Some(d.clone()); synced?; // While Save Preset… asks for a name, OK (and Enter) saves the preset instead. @@ -217,6 +229,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { if let Err(e) = sync_preset(app, d) { app.status(e); } + link_scale(d); if d.kind == PRESET_KIND { row_with(ui, tl!("Preset name:"), TOP_LABEL_WIDTH, |ui| { form::text_edit(ui, d, "name", 288.0); @@ -577,6 +590,75 @@ fn whole(ui: &mut egui::Ui, d: &mut Dialog, path: &str, range: std::ops::RangeIn }); } +/// A Scale percentage at `path`, 1–1000 %: the value typed, once one was. +fn percent(ui: &mut egui::Ui, d: &mut Dialog, path: &str, enabled: bool) -> Option { + let v = get(d, path).as_f64().unwrap_or(100.0); + let typed = ui.add_enabled_ui(enabled, |ui| widgets::range_field(ui, path, v, 1.0..=1000.0, "%", 3, 64.0)).inner; + if let Some(x) = typed { + set(d, path, json!(x)); + } + typed +} + +/// The link after Scale W and H: on, either field sets both, and turning it on sets H to W. With +/// the keyboard on it, Space or Enter toggles it unless it is dimmed. +fn scale_link(ui: &mut egui::Ui, d: &mut Dialog, linked: bool) { + const NAME: &str = "Constrain Width and Height Proportions"; + let size = crate::panels::transform::CONSTRAIN_LINK_SIZE; + let (_, at) = ui.allocate_exact_size(egui::Vec2::splat(size), egui::Sense::click()); + let enabled = ui.is_enabled(); + let keyed = enabled + && at.has_focus() + && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Space) | i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)); + let resp = widgets::paint_icon_button(ui, at, if linked { "link" } else { "link-2-off" }, NAME, linked); + // Off is a state too: screen readers hear the link as off, not as a plain button. + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, enabled, linked, tl!(NAME))); + if resp.clicked() || keyed { + set(d, SCALE_LINKED, json!(!linked)); + link_scale(d); + } +} + +/// While the Scale link is on, keep H equal to W: the field that changed since the last call (a +/// field typed in, or `ui.dialog.set`) gives its value to the other, and when neither changed H +/// takes W, as turning the link on does. As `print.setup` reads a `scale`: one set with W and H +/// apart and without a `linked` key turns the link off, one that leaves out W, H or `linked` (or +/// gives `null`) keeps it as it was, and one that changes both W and H apart while linked is left +/// as it is (and stays changed on later calls), for confirming to refuse. +fn link_scale(d: &mut Dialog) { + let seen = d.fields.get(SCALE_SEEN).cloned().unwrap_or_default(); + if let Some(Value::Object(s)) = d.fields.get_mut("scale") { + let num = |s: &serde_json::Map, k: &str| s.get(k).and_then(Value::as_f64); + let stated = |s: &serde_json::Map, k: &str| s.get(k).is_some_and(|v| !v.is_null()); + if s.get("linked").is_none() && num(s, "width").zip(num(s, "height")).is_some_and(|(w, h)| w != h) { + s.insert("linked".into(), json!(false)); + } + for (i, k) in ["width", "height", "linked"].into_iter().enumerate() { + if !stated(s, k) && !seen[i].is_null() { + s.insert(k.into(), seen[i].clone()); + } + } + } + let (w, h) = (get(d, "scale.width").clone(), get(d, "scale.height").clone()); + if get(d, SCALE_LINKED).as_bool() == Some(true) && w.as_f64() != h.as_f64() { + let (w_kept, h_kept) = (seen[0].as_f64() == w.as_f64(), seen[1].as_f64() == h.as_f64()); + if (w_kept && !h_kept) || w.as_f64().is_none() { + set(d, "scale.width", h); + } else if h_kept || seen.is_null() { + set(d, "scale.height", w); + } else { + return; + } + } + see_scale(&mut d.fields); +} + +/// Remember Scale W, H and the link as the fields hold them, for [`link_scale`]. +fn see_scale(fields: &mut serde_json::Map) { + let s = fields.get("scale").cloned().unwrap_or_default(); + fields.insert(SCALE_SEEN.into(), json!([s["width"], s["height"], s["linked"]])); +} + fn general(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { let unit = app.session.general_unit(); row(ui, tl!("Copies:"), |ui| { @@ -662,10 +744,16 @@ fn general(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { }); row(ui, tl!("Scale:"), |ui| { let on = scaling == PrintScaling::Custom || tiles; + let linked = get(d, SCALE_LINKED).as_bool() == Some(true); ui.label(tl!("W:")); - number(ui, d, "scale.width", "%", on); + if let Some(w) = percent(ui, d, "scale.width", on).filter(|_| linked) { + set(d, "scale.height", json!(w)); + } ui.label(tl!("H:")); - number(ui, d, "scale.height", "%", on); + if let Some(h) = percent(ui, d, "scale.height", on).filter(|_| linked) { + set(d, "scale.width", json!(h)); + } + ui.add_enabled_ui(on, |ui| scale_link(ui, d, linked)); }); row(ui, tl!("Overlap:"), |ui| length(ui, d, "overlap", unit, tiles)); row(ui, tl!("Tile Range:"), |ui| text(ui, d, "tileRange", tiles)); @@ -689,6 +777,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/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index 3bf847d0e7..f1baabc1b9 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -286,3 +286,157 @@ fn the_control_channel_fills_and_confirms_the_dialog() { assert_eq!(app.session.active().unwrap().doc.print_setup.as_ref().unwrap()["copies"], 5); assert_eq!(jobs.borrow().len(), 1); } + +/// Frames of the dialog layer with the accessibility tree on. +struct Screen { + ctx: egui::Context, + time: f64, +} + +impl Screen { + fn new() -> Self { + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + theme::install_fonts(&ctx); + Self { ctx, time: 0.0 } + } + + fn run(&mut self, app: &mut VectorcraftApp, events: Vec) -> egui::FullOutput { + self.time += 0.1; + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 900.0)); + let input = egui::RawInput { events, time: Some(self.time), screen_rect: Some(screen), ..Default::default() }; + let mut out = self.ctx.run_ui(input, |ui| super::show(app, ui.ctx())); + out.textures_delta.clear(); + out + } + + /// The Scale link as screen readers find it: its node, whether it is on, and whether it is dimmed. + fn link(&mut self, app: &mut VectorcraftApp) -> (egui::accesskit::NodeId, Option, bool) { + self.run(app, vec![]); + let out = self.run(app, vec![]); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let link = + nodes.iter().find(|(_, n)| n.label() == Some("Constrain Width and Height Proportions") && n.role() == egui::accesskit::Role::Button); + let (id, node) = link.expect("the Scale link"); + (*id, node.toggled(), node.is_disabled()) + } +} + +/// Scale W and H of the open dialog, and its link. +fn scale(app: &mut VectorcraftApp) -> (f64, f64, bool) { + let s = &dialog(app).fields["scale"]; + (s["width"].as_f64().unwrap_or(f64::NAN), s["height"].as_f64().unwrap_or(f64::NAN), s["linked"] == true) +} + +#[test] +fn the_scale_link_keeps_scale_width_and_height_equal() { + use egui::accesskit::{Action, ActionRequest, Toggled, TreeId}; + let (mut app, _) = app(); + app.run("file.print", json!({})).unwrap(); + let mut screen = Screen::new(); + // On for a new job, and dimmed with the fields until a scaling uses them. + let (link, on, dimmed) = screen.link(&mut app); + assert_eq!((on, dimmed), (Some(Toggled::True), true)); + set(&mut app, "scaling", json!("custom")); + assert!(!screen.link(&mut app).2, "Custom scales by W and H"); + // Linked, a new W sets H, and a new H sets W. + dialog(&mut app).fields["scale"]["width"] = json!(40); + screen.run(&mut app, vec![]); + assert_eq!(scale(&mut app), (40.0, 40.0, true)); + dialog(&mut app).fields["scale"]["height"] = json!(250); + screen.run(&mut app, vec![]); + assert_eq!(scale(&mut app), (250.0, 250.0, true)); + // A click turns it off: screen readers hear it off, and each field changes alone. + let request = |action| egui::Event::AccessKitActionRequest(ActionRequest { action, target_node: link, target_tree: TreeId::ROOT, data: None }); + screen.run(&mut app, vec![request(Action::Click)]); + assert_eq!(screen.link(&mut app).1, Some(Toggled::False)); + dialog(&mut app).fields["scale"]["width"] = json!(50); + screen.run(&mut app, vec![]); + assert_eq!(scale(&mut app), (50.0, 250.0, false)); + // Space on the focused link turns it on and sets H to W; Enter turns it off again. + let key = |key| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + screen.run(&mut app, vec![request(Action::Focus)]); + screen.run(&mut app, vec![key(egui::Key::Space)]); + assert_eq!(scale(&mut app), (50.0, 50.0, true)); + assert_eq!(screen.link(&mut app).1, Some(Toggled::True)); + screen.run(&mut app, vec![request(Action::Focus)]); + screen.run(&mut app, vec![key(egui::Key::Enter)]); + assert_eq!(scale(&mut app), (50.0, 50.0, false)); + // Done keeps the link with the document's settings, and the next Print opens with it. + dialog(&mut app).fields["scale"]["height"] = json!(75); + set(&mut app, "discard", json!(true)); + super::confirm(&mut app).unwrap(); + let saved = app.session.active().unwrap().doc.print_setup.clone().unwrap(); + assert_eq!(saved["scale"], json!({"width": 50.0, "height": 75.0, "linked": false})); + app.run("file.print", json!({})).unwrap(); + assert_eq!(scale(&mut app), (50.0, 75.0, false)); +} + +#[test] +fn a_print_preset_keeps_the_scale_link() { + let (mut app, _) = app(); + app.run("print.presets.save", json!({"name": "Apart", "settings": {"scaling": "custom", "scale": {"width": 30, "height": 90}}})).unwrap(); + app.run("file.print", json!({})).unwrap(); + assert_eq!(scale(&mut app), (100.0, 100.0, true)); + // Choosing the preset loads its unlinked W and H as they are. + set(&mut app, "preset", json!("Apart")); + frame(&mut app); + assert_eq!(scale(&mut app), (30.0, 90.0, false)); + // A scale set without the link and with W and H apart turns it off, as print.setup reads it. + set(&mut app, "preset", json!("[Default]")); + frame(&mut app); + assert_eq!(scale(&mut app), (100.0, 100.0, true)); + set(&mut app, "scale", json!({"width": 20, "height": 60})); + frame(&mut app); + assert_eq!(scale(&mut app), (20.0, 60.0, false)); + // `linked: null` keeps the link as it was, off here. + set(&mut app, "scale", json!({"width": 30, "height": 70, "linked": null})); + frame(&mut app); + assert_eq!(dialog(&mut app).fields["scale"], json!({"width": 30, "height": 70, "linked": false})); +} + +#[test] +fn a_scale_set_through_the_dialog_keeps_the_percentage_it_changes() { + let (mut app, _) = app(); + app.run("file.print", json!({})).unwrap(); + // A new H with the link on, set before any frame: W follows it, and Done saves both. + set(&mut app, "scale", json!({"width": 100, "height": 250, "linked": true})); + set(&mut app, "discard", json!(true)); + super::confirm(&mut app).unwrap(); + let saved = app.session.active().unwrap().doc.print_setup.clone().unwrap(); + assert_eq!(saved["scale"], json!({"width": 250.0, "height": 250.0, "linked": true})); + // A scale that gives only W keeps the link and H as they were, so H follows W. + app.run("file.print", json!({})).unwrap(); + set(&mut app, "scale", json!({"width": 40})); + frame(&mut app); + assert_eq!(scale(&mut app), (40.0, 40.0, true)); + // A new W and H apart with `linked: null` keep the link on: they stay as set, and confirming + // refuses them, as print.setup does, and saves nothing. + set(&mut app, "scale", json!({"width": 50, "height": 200, "linked": null})); + frame(&mut app); + frame(&mut app); + assert_eq!(scale(&mut app), (50.0, 200.0, true)); + set(&mut app, "discard", json!(true)); + assert!(super::confirm(&mut app).is_err()); + let saved = app.session.active().unwrap().doc.print_setup.clone().unwrap(); + assert_eq!(saved["scale"], json!({"width": 250.0, "height": 250.0, "linked": true})); +} + +#[test] +fn the_dimmed_scale_link_ignores_the_keyboard() { + use egui::accesskit::{Action, ActionRequest, TreeId}; + let (mut app, _) = app(); + app.run("file.print", json!({})).unwrap(); + let mut screen = Screen::new(); + set(&mut app, "scaling", json!("custom")); + let (link, _, _) = screen.link(&mut app); + let focus = + egui::Event::AccessKitActionRequest(ActionRequest { action: Action::Focus, target_node: link, target_tree: TreeId::ROOT, data: None }); + let space = egui::Event::Key { key: egui::Key::Space, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + screen.run(&mut app, vec![focus]); + // Scaling None dims the link while it has the keyboard: Space leaves it as it was. + set(&mut app, "scaling", json!("none")); + screen.run(&mut app, vec![space]); + screen.run(&mut app, vec![]); + assert_eq!(scale(&mut app), (100.0, 100.0, true)); +} diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 4665802fe3..2bf120fc30 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -2839,6 +2839,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 9a720638a1..8b314c8dc9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8622,7 +8622,16 @@ documents every field: `orientation`, `autoRotate` (on by default: the paper turns to each artboard), `transverse`; `printLayers: visiblePrintable|visible|all` (template layers never print); `placement: {origin, x, y}` places the printed area (artboard, bleed and marks) on the imageable area (the paper inside `margin`); `scaling: none|fit|custom|tileFull| - tileImageable` with `scale: {width, height}` (%), `overlap` and `tileRange` (tiles numbered across then down). + tileImageable` with `scale: {width, height, linked}` (1–1000 %), `overlap` and `tileRange` (tiles numbered across + then down). +- `scale.linked` keeps the custom scale's width and height equal, as the link by Custom's width and height does on + [the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/print-documents-in-illustrator.html), + where turning it off scales the two apart. The rest is VectorCraft's own rule. New settings have it on, and a saved + `scale` without `linked` reads it as false, so settings and presets saved before it print as they did. While it is + on, a request that gives one percentage sets the other, turning it on sets the height to the width, and a width and + height that differ are an error. A request that gives a different width and height without `linked` turns it off; + `linked: null` keeps the saved link, as `null` does for every setting. The Print dialog shows it as the link button after Scale W and H, dimmed with them unless Scaling is Custom or a + tiling choice. - Copies per sheet: with `copiesPerSheet: true` (off by default; not with tiling) each sheet holds as many copies of the artboard as fit the imageable area, each with its bleed and marks, across then down, `gutter` pt apart (0–720, default 0). The copies are not turned, and the placement places the whole grid. An artboard that doesn't fit prints @@ -8631,10 +8640,19 @@ 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. A symbol instance's art is judged with the paints the instance prints it in, its own fill and stroke + changes and its fill's stain included. 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 6c5a5f03c4..a9843f2044 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2036,6 +2036,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - A Shift-click with the loaded place cursor opens the current file's import options (text, DXF, PDF page or embedded PSD) and OK places it at the click, with Show Import Options on or off and for a cursor loaded by `file.place.queue` ([Place multiple files](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf)). VectorCraft's own rules: a file without such a dialog places as a click does, Cancel leaves the file unplaced, a Shift-drag places at the dragged size, and headless the Shift-click places as a click (`crates/tools/src/place.rs`, `crates/engine/src/tests/place.rs`, `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. + - The Print dialog's General section (and the print preset editor) has a link button after Scale W and H, as the Custom scale has one on [the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/print-documents-in-illustrator.html), where turning it off scales the width and height apart. While it is on, typing either percentage sets the other, and turning it on sets H to W. It is on for new settings, dimmed with the fields unless Scaling is Custom or a tiling choice, toggled with a click, Space or Enter, and named with its on or off state for screen readers. W and H take 1–1000% in the fields. The link is kept with the document's print settings and in print presets (`print.setup {settings: {scale: {linked}}}`); settings saved without it read it as off, so they print as before. Its default, the tiling choices and the agent rules are VectorCraft's own. Evidence: `print::the_scale_link_is_on_for_new_settings_and_off_for_a_saved_scale_without_it`, `tests::print::the_scale_link_keeps_width_and_height_equal`, `tests::print::a_scale_saved_without_the_link_keeps_its_width_and_height`, `dialogs::tests_print::the_scale_link_keeps_scale_width_and_height_equal`, `dialogs::tests_print::a_print_preset_keeps_the_scale_link`. 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`).