Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

Merge print-color-preview into print-color-separations

aiongg1284bf400dda
diff --cc Cargo.lock
index 95bc03bea,886cdf4f5..6e354d92e
--- a/Cargo.lock
+++ b/Cargo.lock
@@@ -816,6 -816,14 +816,14 @@@ dependencies =
"rustix 1.1.5",
]
+ [[package]]
+ name = "craft-cms"
+ version = "0.1.0"
-source = "git+https://github.com/aiongg/craft-libs?rev=0fe6156614de2e8780f34612fa6a577c745f35bc#0fe6156614de2e8780f34612fa6a577c745f35bc"
++source = "git+https://github.com/aiongg/craft-libs?rev=8fbfea8840f0a0f5a22df18901e9db324894b2ce#8fbfea8840f0a0f5a22df18901e9db324894b2ce"
+ dependencies = [
+ "rayon",
+ ]
+
[[package]]
name = "craft-cms"
version = "0.1.0"
@@@ -832,12 -840,26 +840,26 @@@ source = "git+https://github.com/storyt
[[package]]
name = "craft-pdf"
version = "0.1.0"
-source = "git+https://github.com/aiongg/craft-libs?rev=0fe6156614de2e8780f34612fa6a577c745f35bc#0fe6156614de2e8780f34612fa6a577c745f35bc"
+source = "git+https://github.com/aiongg/craft-libs?rev=8fbfea8840f0a0f5a22df18901e9db324894b2ce#8fbfea8840f0a0f5a22df18901e9db324894b2ce"
dependencies = [
+ "bytemuck",
+ "hayro",
+ "hayro-interpret",
+ "hayro-syntax",
"krilla",
"thiserror 2.0.21",
]
+ [[package]]
+ name = "craft-prepress"
+ version = "0.1.0"
-source = "git+https://github.com/aiongg/craft-libs?rev=0fe6156614de2e8780f34612fa6a577c745f35bc#0fe6156614de2e8780f34612fa6a577c745f35bc"
++source = "git+https://github.com/aiongg/craft-libs?rev=8fbfea8840f0a0f5a22df18901e9db324894b2ce#8fbfea8840f0a0f5a22df18901e9db324894b2ce"
+ dependencies = [
- "craft-cms 0.1.0 (git+https://github.com/aiongg/craft-libs?rev=0fe6156614de2e8780f34612fa6a577c745f35bc)",
++ "craft-cms 0.1.0 (git+https://github.com/aiongg/craft-libs?rev=8fbfea8840f0a0f5a22df18901e9db324894b2ce)",
+ "craft-pdf",
+ "thiserror 2.0.21",
+ ]
+
[[package]]
name = "craft-print"
version = "0.1.0"
@@@ -1142,8 -1165,8 +1165,9 @@@ dependencies =
name = "designcraft-pdf"
version = "0.9.0"
dependencies = [
- "craft-cms",
++ "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e9546e191dd62f2bc1d61eca45dbdc2f1b3c1d8e)",
"craft-pdf",
+ "craft-prepress",
"designcraft-color",
"designcraft-compose",
"designcraft-doc",
@@@ -2106,7 -2130,7 +2131,7 @@@ dependencies =
[[package]]
name = "hayro"
version = "0.7.1"
- source = "git+https://github.com/storytold/pdfcraft?rev=b5467d93a0ffaa5e5e6658bccdf8655a3ba689c9#b5467d93a0ffaa5e5e6658bccdf8655a3ba689c9"
-source = "git+https://github.com/aiongg/craft-libs?rev=0fe6156614de2e8780f34612fa6a577c745f35bc#0fe6156614de2e8780f34612fa6a577c745f35bc"
++source = "git+https://github.com/aiongg/craft-libs?rev=8fbfea8840f0a0f5a22df18901e9db324894b2ce#8fbfea8840f0a0f5a22df18901e9db324894b2ce"
dependencies = [
"bytemuck",
"hayro-interpret",
@@@ -2136,7 -2160,7 +2161,7 @@@ dependencies =
[[package]]
name = "hayro-interpret"
version = "0.7.0"
- source = "git+https://github.com/storytold/pdfcraft?rev=b5467d93a0ffaa5e5e6658bccdf8655a3ba689c9#b5467d93a0ffaa5e5e6658bccdf8655a3ba689c9"
-source = "git+https://github.com/aiongg/craft-libs?rev=0fe6156614de2e8780f34612fa6a577c745f35bc#0fe6156614de2e8780f34612fa6a577c745f35bc"
++source = "git+https://github.com/aiongg/craft-libs?rev=8fbfea8840f0a0f5a22df18901e9db324894b2ce#8fbfea8840f0a0f5a22df18901e9db324894b2ce"
dependencies = [
"bitflags 2.13.2",
"hayro-cmap",
@@@ -2154,7 -2178,7 +2179,7 @@@
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
- source = "git+https://github.com/storytold/pdfcraft?rev=b5467d93a0ffaa5e5e6658bccdf8655a3ba689c9#b5467d93a0ffaa5e5e6658bccdf8655a3ba689c9"
-source = "git+https://github.com/aiongg/craft-libs?rev=0fe6156614de2e8780f34612fa6a577c745f35bc#0fe6156614de2e8780f34612fa6a577c745f35bc"
++source = "git+https://github.com/aiongg/craft-libs?rev=8fbfea8840f0a0f5a22df18901e9db324894b2ce#8fbfea8840f0a0f5a22df18901e9db324894b2ce"
dependencies = [
"fearless_simd",
"hayro-ccitt",
@@@ -2178,7 -2202,7 +2203,7 @@@ checksum = "885c5ef0654933139a9b9546fc2
[[package]]
name = "hayro-syntax"
version = "0.7.2"
- source = "git+https://github.com/storytold/pdfcraft?rev=b5467d93a0ffaa5e5e6658bccdf8655a3ba689c9#b5467d93a0ffaa5e5e6658bccdf8655a3ba689c9"
-source = "git+https://github.com/aiongg/craft-libs?rev=0fe6156614de2e8780f34612fa6a577c745f35bc#0fe6156614de2e8780f34612fa6a577c745f35bc"
++source = "git+https://github.com/aiongg/craft-libs?rev=8fbfea8840f0a0f5a22df18901e9db324894b2ce#8fbfea8840f0a0f5a22df18901e9db324894b2ce"
dependencies = [
"flate2",
"hayro-ccitt",
diff --cc Cargo.toml
index ed60ece2d,14aabc7e8..c162a83a9
--- a/Cargo.toml
+++ b/Cargo.toml
@@@ -119,9 -119,10 +119,10 @@@ debug =
# Opt-in cancelable macOS termination on the pinned winit 0.30 line.
[patch.crates-io]
winit = { git = "https://github.com/skylartaylor/winit.git", rev = "3d51077fd1a966f84df9ef287839dc84fd5b4ca7" }
-krilla = { git = "https://github.com/aiongg/craft-libs", rev = "0fe6156614de2e8780f34612fa6a577c745f35bc", version = "=0.8.2" }
+krilla = { git = "https://github.com/aiongg/craft-libs", rev = "8fbfea8840f0a0f5a22df18901e9db324894b2ce", version = "=0.8.2" }
- # The hayro crates from pdfcraft's vendor/ directory, with the patches its README lists.
- hayro = { git = "https://github.com/storytold/pdfcraft", rev = "b5467d93a0ffaa5e5e6658bccdf8655a3ba689c9" }
- hayro-interpret = { git = "https://github.com/storytold/pdfcraft", rev = "b5467d93a0ffaa5e5e6658bccdf8655a3ba689c9" }
- hayro-syntax = { git = "https://github.com/storytold/pdfcraft", rev = "b5467d93a0ffaa5e5e6658bccdf8655a3ba689c9" }
- hayro-jbig2 = { git = "https://github.com/storytold/pdfcraft", rev = "b5467d93a0ffaa5e5e6658bccdf8655a3ba689c9" }
+ # The hayro crates from craft-libs' vendor/ directory (pdfcraft's, plus the plate mode and decode
+ # limits craft-pdf and craft-prepress need); same revision as craft-pdf.
-hayro = { git = "https://github.com/aiongg/craft-libs", rev = "0fe6156614de2e8780f34612fa6a577c745f35bc" }
-hayro-interpret = { git = "https://github.com/aiongg/craft-libs", rev = "0fe6156614de2e8780f34612fa6a577c745f35bc" }
-hayro-syntax = { git = "https://github.com/aiongg/craft-libs", rev = "0fe6156614de2e8780f34612fa6a577c745f35bc" }
-hayro-jbig2 = { git = "https://github.com/aiongg/craft-libs", rev = "0fe6156614de2e8780f34612fa6a577c745f35bc" }
++hayro = { git = "https://github.com/aiongg/craft-libs", rev = "8fbfea8840f0a0f5a22df18901e9db324894b2ce" }
++hayro-interpret = { git = "https://github.com/aiongg/craft-libs", rev = "8fbfea8840f0a0f5a22df18901e9db324894b2ce" }
++hayro-syntax = { git = "https://github.com/aiongg/craft-libs", rev = "8fbfea8840f0a0f5a22df18901e9db324894b2ce" }
++hayro-jbig2 = { git = "https://github.com/aiongg/craft-libs", rev = "8fbfea8840f0a0f5a22df18901e9db324894b2ce" }
diff --cc ROADMAP.md
index 047694816,44cec5c1b..37b290b47
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@@ -348,8 -347,7 +347,9 @@@ list) · [roadmap.md](docs/roadmap.md)
Newest first.
+- **2026-10-20** · Print color (craft-libs#190): CMYK print PDFs blend in DeviceCMYK through craft-pdf's print settings instead of byte rewrites, with the CMYK working space as the output intent in PDF/X-4 only; overprint (Overprint Fill, Stroke and Gap, overprinting text, 100% [Black]) is written as `/op` `/OP` `/OPM 1`; Knockout Group writes `/K true` instead of becoming an image; File › Print prints the PDF Export PDF writes. No readiness percentage change.
+- **2026-10-20** · Spot gradients print on their plates. A gradient stop keeps the swatch it was given (Gradient panel drop, `swatch.create {gradient}`, `object.gradient`, IDML `StopColor`), following its renames and edits. PDF export shades one spot with its tints or [Paper] as a Separation, and a spot with process inks or a second spot as DeviceN; a process gradient to [Paper] prints in DeviceCMYK. Documents with plain-colour stops export as before. No readiness percentage change.
+ - **2026-10-20** · Separations Preview shows the plates the exported PDF prints, spot plates included: each visible spread is exported in memory with the Export PDF settings and separated by craft-prepress off the UI thread, then shown as all inks, one plate or an ink limit. The Ink Manager builds craft-prepress's `InkSet` from the document for export and preview. On the sample magazine the first preview of a spread takes about 0.6–1.1 s, most of it the PDF export. No readiness percentage change.
- **2026-10-16** · Type › Reload Fonts (`font.reload`): fonts installed, edited or removed while DesignCraft runs are read again without a restart, and the open documents recompose with them (#328, #547). An edited font file is noticed by its length and modification time; bundled, added and document fonts stay as they are. InDesign does this by itself, so noticing changes automatically is still open (gap 6). No readiness percentage change.
- **2026-10-16** · Parents can be deleted from their Pages-panel context menu or `layout.parents.delete {id}`. Applied-page and based-on references are cleared, local override copies survive, and Undo restores the parent. Addresses the deletion portion of #956; no readiness percentage change.
- **2026-10-17** · File › Package writes the document's and the IDML's links relative to the package (`Links/logo.png`, `file:Links/logo.png`), so a package holds no path from the machine that made it; opening a document resolves them to the files beside it. Links › Copy Link(s) To still links by full path. (#340). No readiness percentage change.
diff --cc crates/engine/src/cmd/export.rs
index 7b1db1afb,61fb6f946..2567154e1
--- a/crates/engine/src/cmd/export.rs
+++ b/crates/engine/src/cmd/export.rs
@@@ -705,55 -707,67 +705,82 @@@ fn first_page_ref(pdf: &[u8]) -> Option
s[i..].split_whitespace().next()?.parse().ok()
}
+fn export_pdf(s: &mut Session, p: &Value) -> Result<Value> {
+ let r = pdf_export(s, p)?;
+ match str_param(p, "path") {
+ Some(path) => {
+ write_file(path, &r.bytes)?;
+ Ok(json!({"path": path, "bytes": r.bytes.len(), "pages": r.pages, "warnings": r.warnings}))
+ }
+ None => Ok(json!({"base64": super::base64_encode(&r.bytes), "bytes": r.bytes.len(), "pages": r.pages, "warnings": r.warnings})),
+ }
+}
+
- /// The PDF that File › Export PDF writes for `p`, with its warnings: the flattener, placed PDFs
- /// with hidden layers and soft effects as images, the PDF itself and its view options, timings
- /// and transitions. File › Print prints it.
- pub(crate) fn pdf_export(s: &Session, p: &Value) -> Result<designcraft_pdf::ExportReport> {
- let st = s.doc()?;
- let opts = options(p, st.doc.page_count())?;
- // Transparency Flattener presets: High / Medium / Low Resolution, or a ppi.
- let ppi = match p.get("flatten") {
+ /// Transparency Flattener presets (`flatten`): High / Medium / Low Resolution, or a ppi.
+ pub(crate) fn flatten_ppi(id: &str, p: &Value) -> Result<Option<f64>> {
+ Ok(match p.get("flatten") {
None | Some(Value::Null) | Some(Value::Bool(false)) => None,
Some(Value::String(s)) if s == "high" => Some(300.0),
Some(Value::String(s)) if s == "medium" => Some(150.0),
Some(Value::String(s)) if s == "low" => Some(72.0),
Some(Value::Bool(true)) => Some(300.0),
- Some(v) => Some(
- v.as_f64().filter(|v| (36.0..=1200.0).contains(v)).ok_or_else(|| bad("file.exportPdf", "`flatten`: high|medium|low or 36–1200 ppi"))?,
- ),
- };
- let flattened = ppi.map(|ppi| flatten(&st.doc, &s.cache, ppi));
+ Some(v) => Some(v.as_f64().filter(|v| (36.0..=1200.0).contains(v)).ok_or_else(|| bad(id, "`flatten`: high|medium|low or 36–1200 ppi"))?),
+ })
+ }
+
-/// The print PDF of `opts`' pages, as Export PDF writes it before its interactive options:
-/// transparency flattened at `ppi` (if any), placed PDFs with hidden layers and soft effects
-/// rasterized, the PDF boxes of placed graphics applied, and the transparency blend space set.
++/// The print PDF of `opts`' pages: the transparency flattener at `ppi` (if any), placed PDFs
++/// with hidden layers and soft effects as images, the PDF boxes of placed graphics, the PDF
++/// itself and its transparency blend space. Export PDF and File › Print add their view options
++/// to it ([`pdf_export`]); Separations Preview separates it as it is.
+ pub(crate) fn print_pdf(
+ d: &designcraft_doc::Document,
+ cache: &designcraft_compose::Cache,
+ opts: &PdfOptions,
+ ppi: Option<f64>,
+ ) -> Result<designcraft_pdf::ExportReport> {
+ let flattened = ppi.map(|ppi| flatten(d, cache, ppi));
// Placed PDFs with hidden layers go out as images showing just their visible layers.
- let base: &designcraft_doc::Document = flattened.as_ref().map_or(&st.doc, |f| &f.0);
+ let base: &designcraft_doc::Document = flattened.as_ref().map_or(d, |f| &f.0);
let (layered, layer_count) = rasterize_layered(base);
let base2: &designcraft_doc::Document = layered.as_ref().unwrap_or(base);
- let (fx_doc, fx_count) = rasterize_effects(base2, &s.cache);
+ let (fx_doc, fx_count) = rasterize_effects(base2, cache);
let doc: &designcraft_doc::Document = fx_doc.as_ref().unwrap_or(base2);
let boxed = super::interchange::with_pdf_boxes(doc);
let doc: &designcraft_doc::Document = &boxed;
- let r = designcraft_pdf::export_pdf_with_report(doc, &s.cache, &opts).map_err(|e| EngineError::Other(e.to_string()))?;
- let mut r = r;
+ let mut r = designcraft_pdf::export_pdf_with_report(doc, cache, opts).map_err(|e| EngineError::Other(e.to_string()))?;
- // Transparency Blend Space: the page group of pages with transparency.
+ // Transparency Blend Space: the page group of pages with transparency. CMYK print output
+ // gets its CMYK page groups from the writer.
- let spreads = designcraft_pdf::sheet_spreads(doc, &opts);
+ let spreads = designcraft_pdf::sheet_spreads(doc, opts);
let blended: Vec<bool> = spreads.iter().map(|si| doc.spreads.get(*si).is_some_and(|sp| sp.items.iter().any(|it| transparent(it)))).collect();
- if !designcraft_pdf::print_color(doc, &opts) && blended.iter().any(|b| *b) {
- if blended.iter().any(|b| *b) {
++ if !designcraft_pdf::print_color(doc, opts) && blended.iter().any(|b| *b) {
match designcraft_pdf::add_blend_space(&r.bytes, &blended, doc.settings.blend_space == designcraft_doc::BlendSpace::Cmyk) {
Some(b) => r.bytes = b,
None => r.warnings.push("the transparency blend space couldn't be set".into()),
}
}
+ if fx_count > 0 {
- r.warnings.push(format!("{fx_count} object(s) with soft effects (shadows, glows, feathers, bevels) or knockout groups exported as images"));
++ r.warnings.push(format!("{fx_count} object(s) with soft effects (shadows, glows, feathers, bevels) exported as images"));
+ }
+ if layer_count > 0 {
+ r.warnings.push(format!("{layer_count} placed PDF(s) with hidden layers exported as images"));
+ }
+ if let Some((_, n)) = &flattened
+ && *n > 0
+ {
+ r.warnings.push(format!("transparency flattened: {n} region(s) rasterised"));
+ }
+ Ok(r)
+ }
+
-fn export_pdf(s: &mut Session, p: &Value) -> Result<Value> {
++/// The PDF that File › Export PDF writes for `p`, with its warnings: the print PDF
++/// ([`print_pdf`]) with its view options, timings and transitions. File › Print prints it.
++pub(crate) fn pdf_export(s: &Session, p: &Value) -> Result<designcraft_pdf::ExportReport> {
+ let st = s.doc()?;
+ let opts = options(p, st.doc.page_count())?;
+ let ppi = flatten_ppi("file.exportPdf", p)?;
+ let mut r = print_pdf(&st.doc, &s.cache, &opts, ppi)?;
+ let doc: &designcraft_doc::Document = &st.doc;
+ let spreads = designcraft_pdf::sheet_spreads(doc, &opts);
// Interactive PDF view options.
let mut cat = String::new();
if p.get("fullScreen").and_then(Value::as_bool) == Some(true) {
@@@ -806,18 -820,13 +833,7 @@@
None => r.warnings.push("page transitions couldn't be added to this PDF".into()),
}
}
- if fx_count > 0 {
- r.warnings.push(format!("{fx_count} object(s) with soft effects (shadows, glows, feathers, bevels) exported as images"));
- }
- if layer_count > 0 {
- r.warnings.push(format!("{layer_count} placed PDF(s) with hidden layers exported as images"));
- }
- if let Some((_, n)) = &flattened
- && *n > 0
- {
- r.warnings.push(format!("transparency flattened: {n} region(s) rasterised"));
- match str_param(p, "path") {
- Some(path) => {
- write_file(path, &r.bytes)?;
- Ok(json!({"path": path, "bytes": r.bytes.len(), "pages": r.pages, "warnings": r.warnings}))
- }
- None => Ok(json!({"base64": super::base64_encode(&r.bytes), "bytes": r.bytes.len(), "pages": r.pages, "warnings": r.warnings})),
-- }
+ Ok(r)
}
#[cfg(not(target_arch = "wasm32"))]
diff --cc crates/pdf/Cargo.toml
index a98047bb0,efb059bfc..a4ed14d6b
--- a/crates/pdf/Cargo.toml
+++ b/crates/pdf/Cargo.toml
@@@ -15,7 -15,7 +15,8 @@@ designcraft-doc = { workspace = true
designcraft-fonts = { workspace = true }
designcraft-compose = { workspace = true }
craft-pdf = { workspace = true, features = ["write-pdf"] }
+craft-cms = { workspace = true }
+ craft-prepress = { workspace = true }
krilla-svg = { workspace = true }
designcraft-images = { workspace = true }
image = { workspace = true }
diff --cc crates/pdf/src/export.rs
index 5779146ca,d528a7b7c..429691bad
--- a/crates/pdf/src/export.rs
+++ b/crates/pdf/src/export.rs
@@@ -495,6 -482,8 +497,8 @@@ impl std::hash::Hasher for ConstantImag
pub(crate) struct Exporter<'a> {
pub doc: &'a Document,
+ /// The document's inks with its Ink Manager settings.
- inks: craft_prepress::InkSet,
++ pub(crate) inks: craft_prepress::InkSet,
pub cache: &'a Cache,
pub opts: &'a PdfOptions,
/// Current sheet's visible area (spread space) for culling.
diff --cc crates/pdf/src/gradient_inks.rs
index a0d682563,000000000..fa77b57a4
mode 100644,000000..100644
--- a/crates/pdf/src/gradient_inks.rs
+++ b/crates/pdf/src/gradient_inks.rs
@@@ -1,194 -1,0 +1,194 @@@
+//! Gradients written in their inks. A gradient whose stops name a spot swatch shades in that
+//! spot: one spot with paper or tints of itself is a Separation shading, a spot with process
+//! inks or a second spot a DeviceN shading (process colorants in CMYK order, then the spots).
+//! In print, a process gradient with a `[Paper]` stop shades in DeviceCMYK.
+
+use craft_pdf::write::backend as krilla;
+use designcraft_color::swatch::{ColorType, SwatchValue, apply_tint};
+use designcraft_color::{Color, Gradient};
+use krilla::color::device_n::{self, Colorant, DeviceNSpace, Process};
+use krilla::color::separation::{self, SeparationColorant, SeparationSpace};
+use krilla::paint::Stop;
+
+use crate::export::{Exporter, norm, q, regular};
+
+/// A stop as inks.
+enum Ink {
+ /// CMYK tints (0..=1); `[Paper]` is all zero.
+ Process([f32; 4]),
+ Spot {
+ name: String,
+ alternate: Color,
+ tint: f32,
+ },
+}
+
+/// Inks of a plain colour: CMYK as it is, grey as black. RGB has none.
+fn process_inks(c: Color) -> Option<[f32; 4]> {
+ let tint = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
+ match c {
+ Color::Cmyk { c, m, y, k } => Some([tint(c), tint(m), tint(y), tint(k)]),
+ Color::Gray { k } => Some([0.0, 0.0, 0.0, tint(k)]),
+ Color::Rgb { .. } => None,
+ }
+}
+
+/// The shading's color space.
+enum Space {
+ Separation(SeparationSpace),
+ DeviceN(DeviceNSpace),
+}
+
+impl Exporter<'_> {
+ /// The inks a stop prints with, following tints and the Ink Manager as solid fills do.
+ /// `None` when they can't go into an ink shading (RGB, `[Registration]`).
+ fn stop_ink(&self, stop: &designcraft_color::GradientStop) -> Option<Ink> {
+ let Some(mut n) = stop.swatch.as_deref() else { return process_inks(stop.color).map(Ink::Process) };
+ let mut t = 1.0f32;
+ for _ in 0..8 {
+ // A swatch that's gone leaves the stop's own colour.
+ let Some(sw) = self.doc.swatch(n) else { return process_inks(stop.color).map(Ink::Process) };
+ match &sw.value {
+ SwatchValue::Paper { .. } => return Some(Ink::Process([0.0; 4])),
+ SwatchValue::Tint { base, tint } => {
+ t *= tint;
+ n = base;
+ }
+ SwatchValue::Color { color_type: ColorType::Spot, .. } => {
- let (ink, process) = self.doc.inks.resolve(&sw.name);
++ let (ink, process) = crate::inks::spot_output(self.doc, &self.inks, &sw.name);
+ let target =
+ self.doc.swatch(ink).filter(|w| matches!(w.value, SwatchValue::Color { color_type: ColorType::Spot, .. })).unwrap_or(sw);
+ let SwatchValue::Color { color, .. } = &target.value else { return None };
+ if process {
+ return process_inks(apply_tint(*color, t)).map(Ink::Process);
+ }
+ let tint = if t.is_finite() { t.clamp(0.0, 1.0) } else { 1.0 };
+ return Some(Ink::Spot { name: target.name.clone(), alternate: *color, tint });
+ }
+ SwatchValue::Color { color, .. } => return process_inks(apply_tint(*color, t)).map(Ink::Process),
+ SwatchValue::Registration | SwatchValue::None | SwatchValue::Gradient { .. } => return None,
+ }
+ }
+ None
+ }
+
+ /// The gradient's stops in its inks, or `None` to write it in device colours (no spot, or
+ /// inks that can't share one shading space, which is warned about).
+ pub(crate) fn ink_gradient_stops(&mut self, g: &Gradient, swatch: &str) -> Option<Vec<Stop>> {
+ // Plain-colour stops (all older documents) keep their device colours.
+ if g.stops.iter().all(|s| s.swatch.is_none()) {
+ return None;
+ }
+ let inks: Vec<Option<Ink>> = g.stops.iter().map(|s| self.stop_ink(s)).collect();
+ let has_spot = inks.iter().any(|i| matches!(i, Some(Ink::Spot { .. })));
+ let on_paper = g.stops.iter().any(|s| s.swatch.as_deref() == Some(designcraft_color::swatch::PAPER));
+ if !has_spot && !(on_paper && self.for_print() && !self.rgb_only) {
+ return None;
+ }
+ let Some(inks) = inks.into_iter().collect::<Option<Vec<Ink>>>() else {
+ return self.unshaded(swatch, "a stop has no inks (RGB or [Registration])", has_spot);
+ };
+ // Spots in the order the stops name them; process inks a stop sets.
+ let mut spots: Vec<(String, Color)> = Vec::new();
+ let mut process = [false; 4];
+ for i in &inks {
+ match i {
+ Ink::Process(v) => {
+ for (used, v) in process.iter_mut().zip(v) {
+ *used |= *v > 1e-6;
+ }
+ }
+ Ink::Spot { name, alternate, .. } => {
+ if !spots.iter().any(|(n, _)| n == name) {
+ spots.push((name.clone(), *alternate));
+ }
+ }
+ }
+ }
+ let process: Vec<usize> = (0..4).filter(|j| process.get(*j).copied().unwrap_or(false)).collect();
+ let space = match (spots.as_slice(), process.is_empty()) {
+ ([], _) => None,
+ ([(name, alternate)], true) => {
+ Some(Space::Separation(SeparationSpace::new(SeparationColorant::Custom(name.clone()), regular(alternate, self.rgb_only))))
+ }
+ _ => {
+ if self.rgb_only {
+ return self.unshaded(swatch, "DeviceN isn't allowed in PDF/A", true);
+ }
+ let mut colorants: Vec<Colorant> = process.iter().filter_map(|j| Process::ALL.get(*j).copied().map(Colorant::Process)).collect();
+ for (name, alternate) in &spots {
+ let Color::Cmyk { c, m, y, k } = *alternate else {
+ return self.unshaded(swatch, &format!("'{name}' has no CMYK values"), true);
+ };
+ colorants.push(Colorant::Spot { name: name.clone(), alternate: krilla::color::cmyk::Color::new(q(c), q(m), q(y), q(k)) });
+ }
+ match DeviceNSpace::new(colorants) {
+ Some(s) => Some(Space::DeviceN(s)),
+ None => return self.unshaded(swatch, "its inks don't fit one DeviceN space", true),
+ }
+ }
+ };
+ // Tints per colorant at each authored stop.
+ let tints: Vec<Vec<f32>> = inks
+ .iter()
+ .map(|i| {
+ let mut v = vec![0.0f32; process.len() + spots.len()];
+ match i {
+ Ink::Process(p) => {
+ for (slot, j) in v.iter_mut().zip(&process) {
+ *slot = p.get(*j).copied().unwrap_or(0.0);
+ }
+ }
+ Ink::Spot { name, tint, .. } => {
+ if let Some(slot) = spots.iter().position(|(n, _)| n == name).and_then(|k| v.get_mut(process.len() + k)) {
+ *slot = *tint;
+ }
+ }
+ }
+ v
+ })
+ .collect();
+ // A midpoint becomes a stop halfway between its neighbours' tints, as the display does.
+ let mut expanded: Vec<(f32, Vec<f32>, f32)> = Vec::with_capacity(tints.len() * 2);
+ for (k, (s, v)) in g.stops.iter().zip(&tints).enumerate() {
+ expanded.push((s.offset, v.clone(), s.opacity));
+ if let (Some(n), Some(nv)) = (g.stops.get(k + 1), tints.get(k + 1))
+ && (s.midpoint - 0.5).abs() > 1e-3
+ {
+ let mid: Vec<f32> = v.iter().zip(nv).map(|(a, b)| (a + b) / 2.0).collect();
+ expanded.push((s.offset + (n.offset - s.offset) * s.midpoint, mid, (s.opacity + n.opacity) / 2.0));
+ }
+ }
+ let mut stops = Vec::with_capacity(expanded.len());
+ let mut last = 0.0f32;
+ for (o, v, a) in expanded {
+ let o = if o.is_finite() { o.clamp(last, 1.0) } else { last };
+ last = o;
+ let color: krilla::color::Color = match &space {
+ Some(Space::Separation(sp)) => separation::Color::new(q(v.first().copied().unwrap_or(0.0)), sp.clone()).into(),
+ Some(Space::DeviceN(sp)) => device_n::Color::new(v.iter().map(|t| q(*t)).collect(), sp.clone())?.into(),
+ // Process inks only (a gradient to [Paper] in print).
+ None => {
+ let mut cmyk = [0.0f32; 4];
+ for (t, j) in v.iter().zip(&process) {
+ if let Some(slot) = cmyk.get_mut(*j) {
+ *slot = *t;
+ }
+ }
+ let [c, m, y, k] = cmyk;
+ krilla::color::cmyk::Color::new(q(c), q(m), q(y), q(k)).into()
+ }
+ };
+ stops.push(Stop { offset: norm(o), color, opacity: norm(a) });
+ }
+ (!stops.is_empty()).then_some(stops)
+ }
+
+ /// Falls back to device colours, warning when that loses a spot ink.
+ fn unshaded(&mut self, swatch: &str, why: &str, has_spot: bool) -> Option<Vec<Stop>> {
+ if has_spot {
+ self.warn(format!("gradient '{swatch}': spot inks printed as process colour ({why})"));
+ }
+ None
+ }
+}
diff --cc crates/pdf/src/lib.rs
index 25045c71e,92a73d206..4fa7e8a60
--- a/crates/pdf/src/lib.rs
+++ b/crates/pdf/src/lib.rs
@@@ -35,7 -30,7 +35,8 @@@
#![forbid(unsafe_code)]
mod export;
+mod gradient_inks;
+ pub mod inks;
mod links;
mod marks;
mod text;
diff --cc crates/pdf/tests/spot_gradients.rs
index 426e7bf1b,000000000..153a94ab6
mode 100644,000000..100644
--- a/crates/pdf/tests/spot_gradients.rs
+++ b/crates/pdf/tests/spot_gradients.rs
@@@ -1,177 -1,0 +1,190 @@@
+//! Gradients on spot swatches shade in their inks: Separation for one spot, DeviceN for a spot
+//! with process inks or a second spot.
+use designcraft_color::{Color, ColorType, Gradient, GradientKind, GradientStop, Swatch, SwatchValue};
+use designcraft_compose::Cache;
+use designcraft_doc::{Document, Fill, Item, ItemId, Shape, SpreadRef, build::NewDocument};
+use designcraft_geom::{Rect, shapes};
+use designcraft_pdf::{PdfOptions, Standard, export_pdf_with_report};
+use hayro_syntax::{
+ Pdf,
+ object::{Array, Dict, Name},
+};
+
+const CYAN: &str = "C=100 M=0 Y=0 K=0";
+
+fn spot(d: &mut Document, name: &str, color: Color) {
+ d.swatches.push(Swatch { value: SwatchValue::Color { color, color_type: ColorType::Spot }, ..Swatch::color(name, color) });
+}
+
+/// A document with spot inks Gold and Silver, a 40 % tint of Gold, and one box filled with a gradient on `stops`
+/// (swatch name or plain colour, location).
+fn document(stops: &[(Result<&str, Color>, f32)], midpoint: f32) -> Document {
+ let mut d = Document::new(&NewDocument { width: 120.0, height: 120.0, facing_pages: false, ..Default::default() });
+ spot(&mut d, "Gold", Color::cmyk(0.0, 0.3, 0.9, 0.1));
+ spot(&mut d, "Silver", Color::cmyk(0.2, 0.15, 0.1, 0.3));
+ d.swatches.push(Swatch { value: SwatchValue::Tint { base: "Gold".into(), tint: 0.4 }, ..Swatch::color("Gold 40%", Color::BLACK) });
+ let stops = stops
+ .iter()
+ .map(|(s, offset)| match s {
+ Ok(name) => GradientStop { swatch: Some(name.to_string()), midpoint, ..GradientStop::new(*offset, d.resolve_color(name, 1.0).unwrap()) },
+ Err(c) => GradientStop { midpoint, ..GradientStop::new(*offset, *c) },
+ })
+ .collect();
+ d.swatches.push(Swatch {
+ value: SwatchValue::Gradient { gradient: Gradient { kind: GradientKind::Linear, stops } },
+ ..Swatch::color("Fade", Color::BLACK)
+ });
+ let mut item = Item::new(ItemId(d.alloc()), d.default_layer(), Shape::Rectangle, shapes::rectangle(Rect::new(10.0, 10.0, 110.0, 110.0)));
+ item.fill = Fill::swatch("Fade");
+ d.insert_item(SpreadRef::Doc(0), item, None).unwrap();
+ d
+}
+
+fn endpoint(function: &Dict<'_>, first: bool) -> Vec<f32> {
+ if let Some(functions) = function.get::<Array<'_>>(b"Functions") {
+ let functions: Vec<_> = functions.iter::<Dict<'_>>().collect();
+ return endpoint(if first { functions.first().unwrap() } else { functions.last().unwrap() }, first);
+ }
+ function.get::<Array<'_>>(if first { b"C0" } else { b"C1" }).unwrap().iter::<f32>().collect()
+}
+
+/// Each shading on the page: its color space family, colorant names, and the colours at its
+/// two ends.
+struct Shading {
+ family: String,
+ colorants: Vec<String>,
+ start: Vec<f32>,
+ end: Vec<f32>,
+}
+
+fn export(d: &Document, standard: Standard) -> (Vec<Shading>, Vec<String>) {
+ let report = export_pdf_with_report(d, &Cache::new(), &PdfOptions { standard, compress: false, ..Default::default() }).unwrap();
+ let pdf = Pdf::new(report.bytes).unwrap();
+ let patterns = &pdf.pages()[0].resources().patterns;
+ let mut out = Vec::new();
+ for (name, _) in patterns.entries() {
+ let pattern = patterns.get::<Dict<'_>>(name.as_ref()).unwrap();
+ let shading = pattern.get::<Dict<'_>>(b"Shading").unwrap();
+ let text = |n: Name<'_>| String::from_utf8_lossy(n.as_ref()).into_owned();
+ let (family, colorants) = match shading.get::<Name<'_>>(b"ColorSpace") {
+ Some(n) => (text(n), Vec::new()),
+ None => {
+ let space = shading.get::<Array<'_>>(b"ColorSpace").unwrap();
+ let mut it = space.flex_iter();
+ let family = text(it.next::<Name<'_>>().unwrap());
+ let colorants = match family.as_str() {
+ "Separation" => vec![text(it.next::<Name<'_>>().unwrap())],
+ "DeviceN" => it.next::<Array<'_>>().unwrap().iter::<Name<'_>>().map(text).collect(),
+ _ => Vec::new(),
+ };
+ (family, colorants)
+ }
+ };
+ let function = shading.get::<Dict<'_>>(b"Function").unwrap();
+ out.push(Shading { family, colorants, start: endpoint(&function, true), end: endpoint(&function, false) });
+ }
+ assert!(!out.is_empty(), "the gradient is a shading");
+ (out, report.warnings)
+}
+
+fn close(a: &[f32], b: &[f32]) -> bool {
+ a.len() == b.len() && a.iter().zip(b).all(|(a, b)| (a - b).abs() < 0.01)
+}
+
+fn no_conversion(warnings: &[String]) {
+ assert!(!warnings.iter().any(|w| w.contains("Fade")), "{warnings:?}");
+}
+
+#[test]
+fn a_spot_to_paper_gradient_is_a_separation_shading() {
+ for standard in [Standard::None, Standard::PdfX4] {
+ let (shadings, warnings) = export(&document(&[(Ok("Gold"), 0.0), (Ok("[Paper]"), 1.0)], 0.5), standard);
+ no_conversion(&warnings);
+ let s = &shadings[0];
+ assert_eq!((s.family.as_str(), s.colorants.as_slice()), ("Separation", &["Gold".to_string()][..]), "{standard:?}");
+ assert!(close(&s.start, &[1.0]) && close(&s.end, &[0.0]), "{:?} → {:?}", s.start, s.end);
+ }
+ // A tint of the spot shades in the same Separation.
+ let (shadings, _) = export(&document(&[(Ok("Gold"), 0.0), (Ok("Gold 40%"), 1.0)], 0.5), Standard::PdfX4);
+ assert_eq!(shadings[0].family, "Separation");
+ assert!(close(&shadings[0].end, &[0.4]), "{:?}", shadings[0].end);
+ // Converted to process in the Ink Manager: CMYK.
+ let mut d = document(&[(Ok("Gold"), 0.0), (Ok("[Paper]"), 1.0)], 0.5);
+ d.inks.to_process.push("Gold".into());
+ let (shadings, _) = export(&d, Standard::PdfX4);
+ assert_eq!(shadings[0].family, "DeviceCMYK");
+ assert!(close(&shadings[0].start, &[0.0, 0.3, 0.9, 0.1]), "{:?}", shadings[0].start);
+}
+
++/// Stops follow the Ink Manager as fills do (`designcraft_pdf::inks`): an alias that would close
++/// a loop is left out, so Gold prints on Silver's plate and Silver on its own.
++#[test]
++fn gradient_stops_follow_ink_aliases_as_fills_do() {
++ let mut d = document(&[(Ok("Gold"), 0.0), (Ok("[Paper]"), 1.0)], 0.5);
++ d.inks.aliases = vec![("Gold".into(), "Silver".into()), ("Silver".into(), "Gold".into())];
++ let set = designcraft_pdf::inks::ink_set(&d);
++ assert_eq!(designcraft_pdf::inks::spot_output(&d, &set, "Gold"), ("Silver", false));
++ let (shadings, _) = export(&d, Standard::PdfX4);
++ assert_eq!((shadings[0].family.as_str(), shadings[0].colorants.as_slice()), ("Separation", &["Silver".to_string()][..]));
++ assert!(close(&shadings[0].start, &[1.0]), "{:?}", shadings[0].start);
++}
++
+#[test]
+fn a_spot_to_cyan_gradient_is_a_device_n_shading() {
+ let (shadings, warnings) = export(&document(&[(Ok("Gold"), 0.0), (Ok(CYAN), 1.0)], 0.5), Standard::PdfX4);
+ no_conversion(&warnings);
+ let s = &shadings[0];
+ assert_eq!(s.family, "DeviceN");
+ assert_eq!(s.colorants, ["Cyan", "Gold"]);
+ assert!(close(&s.start, &[0.0, 1.0]) && close(&s.end, &[1.0, 0.0]), "{:?} → {:?}", s.start, s.end);
+ // A midpoint stays in the inks: the colours at the ends are unchanged and in DeviceN.
+ let (shadings, _) = export(&document(&[(Ok("Gold"), 0.0), (Ok(CYAN), 1.0)], 0.25), Standard::PdfX4);
+ assert_eq!(shadings[0].family, "DeviceN");
+ assert!(close(&shadings[0].start, &[0.0, 1.0]) && close(&shadings[0].end, &[1.0, 0.0]));
+}
+
+#[test]
+fn a_two_spot_gradient_is_a_device_n_shading() {
+ let (shadings, warnings) = export(&document(&[(Ok("Gold"), 0.0), (Ok("Silver"), 1.0)], 0.5), Standard::PdfX4);
+ no_conversion(&warnings);
+ let s = &shadings[0];
+ assert_eq!(s.family, "DeviceN");
+ assert_eq!(s.colorants, ["Gold", "Silver"]);
+ assert!(close(&s.start, &[1.0, 0.0]) && close(&s.end, &[0.0, 1.0]), "{:?} → {:?}", s.start, s.end);
+ // Stop opacity is a soft mask over the same inks.
+ let mut d = document(&[(Ok("Gold"), 0.0), (Ok("Silver"), 1.0)], 0.5);
+ if let Some(SwatchValue::Gradient { gradient }) = d.swatches.iter_mut().find(|w| w.name == "Fade").map(|w| &mut w.value) {
+ gradient.stops[0].opacity = 0.4;
+ }
+ let (shadings, warnings) = export(&d, Standard::PdfX4);
+ no_conversion(&warnings);
+ assert!(shadings.iter().any(|s| s.family == "DeviceN" && s.colorants == ["Gold", "Silver"]));
+}
+
+#[test]
+fn a_process_gradient_to_paper_prints_in_cmyk() {
+ let (shadings, warnings) = export(&document(&[(Ok(CYAN), 0.0), (Ok("[Paper]"), 1.0)], 0.5), Standard::PdfX4);
+ no_conversion(&warnings);
+ assert_eq!(shadings[0].family, "DeviceCMYK");
+ assert!(close(&shadings[0].start, &[1.0, 0.0, 0.0, 0.0]) && close(&shadings[0].end, &[0.0, 0.0, 0.0, 0.0]));
+}
+
+/// PDF/A forbids DeviceN's PostScript tint transform: the gradient goes to process colour, with
+/// a warning, and the export still succeeds.
+#[test]
+fn pdf_a_writes_mixed_spot_gradients_in_process_colour() {
+ let (shadings, warnings) = export(&document(&[(Ok("Gold"), 0.0), (Ok(CYAN), 1.0)], 0.5), Standard::PdfA2b);
+ assert!(warnings.iter().any(|w| w.contains("'Fade'") && w.contains("spot inks printed as process")), "{warnings:?}");
+ assert!(shadings.iter().all(|s| s.family != "DeviceN"));
+}
+
+/// Stops with plain colours (every document saved before stops named swatches) export as they
+/// did: the spot's values in DeviceCMYK.
+#[test]
+fn plain_colour_stops_keep_their_device_space() {
+ let gold = Color::cmyk(0.0, 0.3, 0.9, 0.1);
+ let (shadings, warnings) = export(&document(&[(Err(gold), 0.0), (Err(Color::cmyk(1.0, 0.0, 0.0, 0.0)), 1.0)], 0.5), Standard::PdfX4);
+ no_conversion(&warnings);
+ assert_eq!(shadings[0].family, "DeviceCMYK");
+ assert!(close(&shadings[0].start, &[0.0, 0.3, 0.9, 0.1]));
+}
diff --cc crates/render/src/lib.rs
index c42d8c897,904590811..2dfb59268
--- a/crates/render/src/lib.rs
+++ b/crates/render/src/lib.rs
@@@ -145,9 -145,9 +145,9 @@@ pub struct RenderOptions
pub change_markup: bool,
/// View › Structure › Show Tag Markers: brackets around inline-tagged text (screen view).
pub tag_markers: bool,
- /// Separations Preview: draw one process plate (0 = cyan … 3 = black) as grey ink coverage,
- /// from each object's own colour (CMYK as authored, others through the colour settings).
- /// 4 (internal, the CMYK blend space): cyan, magenta and yellow coverage in red, green, blue.
- /// The CMYK blend space's ink passes (internal): 3 draws black ink coverage as grey, 4 cyan,
- /// magenta and yellow coverage in red, green and blue, from each object's own colour (CMYK as
- /// authored, others through the colour settings); 0–2 draw cyan, magenta or yellow as grey.
++ /// The CMYK blend space's ink passes (internal): 3 draws black ink coverage as gray, 4 cyan,
++ /// magenta and yellow coverage in red, green and blue, from each object's own color (CMYK as
++ /// authored, others through the color settings); 0–2 draw cyan, magenta or yellow as gray.
pub plate: Option<u8>,
/// View › Display Performance.
pub quality: DisplayQuality,
diff --cc crates/ui-egui/src/menus.rs
index 79b8b2c4e,bfd33b7ce..2a7fa07a8
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@@ -2053,6 -2051,61 +2051,61 @@@ fn export_bytes(app: &mut DesignApp, p
}
}
+ /// View › Separations Preview (`view.separations`): updates the plate and the ink limit and
-/// reports the plates of the spread nearest the view centre.
++/// reports the plates of the spread nearest the view center.
+ fn separations_view(app: &mut DesignApp, p: &Value) -> Result<Value, String> {
+ let mut sep = app.ui.separations.clone().unwrap_or_default();
+ let mut on = app.ui.separations.is_some();
+ match p.get("plate") {
+ Some(Value::String(s)) if s.eq_ignore_ascii_case("all") || s.is_empty() => {
+ sep.plate = None;
+ on = true;
+ }
+ Some(Value::String(s)) => {
+ let process = ["Cyan", "Magenta", "Yellow", "Black"].into_iter().find(|n| n.eq_ignore_ascii_case(s));
+ sep.plate = Some(process.map_or_else(|| s.clone(), str::to_string));
+ on = true;
+ }
+ Some(Value::Null) => {
+ sep.plate = None;
+ on = false;
+ }
+ Some(v) => return Err(format!("`plate`: an ink name, \"all\" or null, not {v}")),
+ None => {}
+ }
+ match p.get("inkLimit") {
+ Some(Value::Null) => sep.ink_limit = None,
+ Some(v) => {
+ let l = v.as_f64().filter(|l| l.is_finite() && *l >= 0.0).ok_or_else(|| format!("`inkLimit`: a percentage, not {v}"))?;
+ sep.ink_limit = Some(l as f32);
+ on = true;
+ }
+ None => {}
+ }
+ on |= sep.ink_limit.is_some();
+ if let Some(v) = p.get("on").and_then(Value::as_bool) {
+ on = v;
+ }
+ app.ui.separations = on.then_some(sep.clone());
+ let mut out = json!({"on": on, "plate": sep.plate.as_deref().unwrap_or("all"), "inkLimit": sep.ink_limit});
+ if on && app.session.active().is_some() {
+ match crate::separations::current_sheet(app) {
+ Ok(sheet) => {
+ if let Some(name) = &sep.plate
+ && sheet.ink(name).is_none()
+ {
+ out["warning"] = json!(format!("this spread prints no `{name}` plate"));
+ }
+ out["spread"] = json!(sheet.spread);
+ out["dpi"] = json!(sheet.plates.dpi);
+ out["inks"] = sheet.inks().into_iter().map(|(name, spot)| json!({"name": name, "spot": spot})).collect();
+ }
+ Err(e) => out["error"] = json!(e),
+ }
+ }
+ Ok(out)
+ }
+
/// File › Export PDF…: ask for a path, export through `file.exportPdf` and write the bytes with the
/// platform writer (a download on the web).
pub(crate) fn export_pdf(app: &mut DesignApp, p: &Value) -> Result<Value, String> {
diff --cc crates/ui-egui/src/panels/separations.rs
index 000000000,78b038288..a685bee18
mode 000000,100644..100644
--- a/crates/ui-egui/src/panels/separations.rs
+++ b/crates/ui-egui/src/panels/separations.rs
@@@ -1,0 -1,116 +1,116 @@@
+ //! Window › Output › Separations Preview: the plates the print PDF of the spread nearest the
-//! view centre puts on film, each ink's percentage under the pointer, one plate or all inks,
++//! view center puts on film, each ink's percentage under the pointer, one plate or all inks,
+ //! and the ink limit.
+
+ use craft_prepress::{Alternate, Ink, Process};
+ use serde_json::json;
+
+ use crate::DesignApp;
+ use crate::i18n::tr;
+ use crate::theme::Tokens;
+
+ /// A swatch for an ink's row.
+ fn ink_color(ink: &Ink) -> egui::Color32 {
+ match ink {
+ Ink::Process(Process::Cyan) => egui::Color32::from_rgb(0, 174, 239),
+ Ink::Process(Process::Magenta) => egui::Color32::from_rgb(236, 0, 140),
+ Ink::Process(Process::Yellow) => egui::Color32::from_rgb(255, 242, 0),
+ Ink::Process(Process::Black) => egui::Color32::from_rgb(35, 31, 32),
+ Ink::Spot(s) => {
+ let rgb = match s.alternate {
+ Alternate::Lab([l, a, b]) => designcraft_color::cms::lab::lab_to_srgb(designcraft_color::cms::Lab { l, a, b }),
+ Alternate::Cmyk([c, m, y, k]) => designcraft_color::Color::Cmyk { c, m, y, k }.to_rgb(),
+ };
+ let [r, g, b] = rgb.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8);
+ egui::Color32::from_rgb(r, g, b)
+ }
+ }
+ }
+
+ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) {
+ let t = Tokens::get(ui.ctx());
+ let lang = app.ui.language.clone();
+ let sep = app.ui.separations.clone();
+ let mut run = None;
+ ui.horizontal(|ui| {
+ let limit = sep.as_ref().and_then(|s| s.ink_limit);
+ let modes = [
+ ("Off", sep.is_none(), json!({"plate": null, "inkLimit": null})),
+ ("Separations", sep.is_some() && limit.is_none(), json!({"plate": "all", "inkLimit": null})),
+ ("Ink Limit", limit.is_some(), json!({"inkLimit": limit.unwrap_or(300.0)})),
+ ];
+ for (label, on, params) in modes {
+ if ui.selectable_label(on, crate::rtl::widget(ui, tr(&lang, label))).clicked() && !on {
+ run = Some(params);
+ }
+ }
+ });
+ if let Some(mut limit) = sep.as_ref().and_then(|s| s.ink_limit) {
+ ui.horizontal(|ui| {
+ ui.label(crate::rtl::widget(ui, tr(&lang, "Ink Limit")));
+ if ui.add(egui::DragValue::new(&mut limit).range(0.0..=400.0).suffix("%")).changed() {
+ run = Some(json!({"inkLimit": limit}));
+ }
+ });
+ }
+ if let Some(p) = run.take() {
+ if let Err(e) = app.run("view.separations", p) {
+ app.status_error("Separations Preview", e);
+ }
+ return;
+ }
+ let Some(sep) = sep else {
+ ui.label(egui::RichText::new(tr(&lang, "Shows the plates the exported PDF prints.")).size(11.0).color(t.text_dim));
+ return;
+ };
+ ui.separator();
+ let Some(designcraft_doc::SpreadRef::Doc(si)) = crate::canvas::current_spread(app) else { return };
+ let sheet = match app.canvas.separations.sheet(si) {
+ None => {
+ ui.label(egui::RichText::new(tr(&lang, "Separating…")).size(11.0).color(t.text_dim));
+ return;
+ }
+ Some(Err(e)) => {
+ ui.label(egui::RichText::new(e.as_str()).size(11.0).color(t.text_dim));
+ return;
+ }
+ Some(Ok(sheet)) => sheet.clone(),
+ };
+ // Each ink's percentage under the pointer.
+ let k = f64::from(sheet.plates.dpi) / 72.0;
+ let coverage = app.canvas.separations.pointer.filter(|(psi, _)| *psi == si).and_then(|(_, p)| {
+ let (x, y) = ((p.x - sheet.area.x0) * k, (p.y - sheet.area.y0) * k);
+ (x >= 0.0 && y >= 0.0).then(|| sheet.plates.coverage_at(x as u32, y as u32, &[])).flatten()
+ });
+ let pct = |v: Option<f32>| v.map_or_else(String::new, |v| format!("{v:.0}%"));
+ let row = |ui: &mut egui::Ui, selected: bool, color: Option<egui::Color32>, name: &str, value: String| {
+ ui.horizontal(|ui| {
+ let (r, _) = ui.allocate_exact_size(egui::vec2(12.0, 12.0), egui::Sense::hover());
+ if let Some(c) = color {
+ ui.painter().rect_filled(r, 1.0, c);
+ }
+ let clicked = ui.selectable_label(selected, name).clicked();
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| ui.label(egui::RichText::new(value).size(11.0)));
+ clicked
+ })
+ .inner
+ };
+ if row(ui, sep.plate.is_none(), None, tr(&lang, "All Inks"), pct(coverage.as_ref().map(|c| c.total))) {
+ run = Some(json!({"plate": "all"}));
+ }
+ for (id, ink) in sheet.plates.inks.iter() {
+ let selected = sep.plate.as_deref().and_then(|n| sheet.ink(n)) == Some(id);
+ let value = pct(coverage.as_ref().and_then(|c| c.inks.get(id.index()).copied()));
+ if row(ui, selected, Some(ink_color(ink)), ink.name(), value) {
+ run = Some(json!({"plate": if selected { "all" } else { ink.name() }}));
+ }
+ }
+ for name in &sheet.plates.unseparated {
+ ui.label(egui::RichText::new(format!("{name} ({})", tr(&lang, "not separated"))).size(11.0).color(t.text_dim));
+ }
+ if let Some(p) = run
+ && let Err(e) = app.run("view.separations", p)
+ {
+ app.status_error("Separations Preview", e);
+ }
+ }
diff --cc crates/ui-egui/src/separations.rs
index 000000000,3e635cf3d..8d96e0248
mode 000000,100644..100644
--- a/crates/ui-egui/src/separations.rs
+++ b/crates/ui-egui/src/separations.rs
@@@ -1,0 -1,377 +1,377 @@@
+ //! View › Separations Preview on the canvas: each visible spread exported as Export PDF prints
+ //! it and separated into plates (`designcraft_engine::separations`), drawn over the spread.
+ //!
+ //! Sheets are kept per spread, keyed by document revision, resolution and print settings, so
+ //! panning and redrawing reuse them. Separating runs on a background thread (native); while it
+ //! runs the previous sheet of that spread stays on screen. On the web it runs on the UI thread
+ //! at a lower resolution.
+
+ use std::sync::Arc;
+
+ use designcraft_doc::SpreadRef;
+ use designcraft_engine::separations::{MAX_DPI, MIN_DPI, Print, Sheet};
+ use designcraft_geom::Point;
+ use designcraft_tools::CanvasLayout;
+ use egui::{Color32, pos2};
+
+ use crate::DesignApp;
+ use crate::canvas::Xf;
+
+ /// View › Separations Preview settings (`None` in `UiState::separations` is off).
+ #[derive(Clone, Debug, Default, PartialEq)]
+ pub struct Separations {
+ /// The ink shown alone as film; `None` shows every ink as printed.
+ pub plate: Option<String>,
+ /// Ink Limit: areas whose total ink is over this percentage show in red over gray.
+ pub ink_limit: Option<f32>,
+ }
+
+ /// Sheets kept at most (each holds one plane per ink).
+ const MAX_SHEETS: usize = 6;
+ /// The highest resolution the web build separates at (on the UI thread).
+ #[cfg(target_arch = "wasm32")]
+ const WEB_MAX_DPI: f32 = 72.0;
+
+ /// What a sheet was separated from.
+ #[derive(Clone, Debug, PartialEq)]
+ pub struct Key {
+ pub uid: u64,
+ pub revision: u64,
+ pub spread: usize,
+ pub dpi: f32,
+ pub print: Print,
+ }
+
+ struct Entry {
+ key: Key,
+ sheet: Result<Arc<Sheet>, String>,
+ /// The texture of the current view of `sheet`.
+ texture: Option<(Separations, egui::TextureHandle)>,
+ /// The frame it was last drawn in.
+ used: u64,
+ }
+
+ struct Job {
+ key: Key,
+ doc: Arc<designcraft_doc::Document>,
+ cache: Arc<designcraft_compose::Cache>,
+ }
+
+ struct Done {
+ key: Key,
+ sheet: Result<Sheet, String>,
+ ms: f64,
+ }
+
+ #[cfg(not(target_arch = "wasm32"))]
+ struct Worker {
+ tx: std::sync::mpsc::Sender<Job>,
+ rx: std::sync::mpsc::Receiver<Done>,
+ }
+
+ #[cfg(not(target_arch = "wasm32"))]
+ impl Worker {
+ fn spawn(ctx: egui::Context) -> Option<Self> {
+ let (tx, jobs) = std::sync::mpsc::channel::<Job>();
+ let (done_tx, rx) = std::sync::mpsc::channel::<Done>();
+ std::thread::Builder::new()
+ .name("designcraft-separations".into())
+ .spawn(move || {
+ while let Ok(first) = jobs.recv() {
+ // Of the jobs waiting, only the newest per spread matters.
+ let mut batch = vec![first];
+ while let Ok(next) = jobs.try_recv() {
+ batch.retain(|j| j.key.spread != next.key.spread);
+ batch.push(next);
+ }
+ for job in batch {
+ let done = separate(job);
+ if done_tx.send(done).is_err() {
+ return;
+ }
+ ctx.request_repaint();
+ }
+ }
+ })
+ .ok()?;
+ Some(Worker { tx, rx })
+ }
+ }
+
+ fn separate(job: Job) -> Done {
+ let t0 = crate::now_ms();
+ let sheet =
+ designcraft_engine::separations::separate(&job.doc, &job.cache, job.key.spread, job.key.dpi, &job.key.print).map_err(|e| e.to_string());
+ Done { key: job.key, sheet, ms: crate::now_ms() - t0 }
+ }
+
+ /// The canvas's separated sheets.
+ #[derive(Default)]
+ pub struct Preview {
+ entries: Vec<Entry>,
+ pending: Vec<Key>,
+ #[cfg(not(target_arch = "wasm32"))]
+ worker: Option<Worker>,
+ #[cfg(not(target_arch = "wasm32"))]
+ worker_started: bool,
+ frame: u64,
+ /// The spread and the point in it under the pointer, for the panel's readout.
+ pub pointer: Option<(usize, Point)>,
+ /// How long the last separation took, in milliseconds.
+ pub last_ms: f64,
+ /// The pixels per point the canvas last drew at (0 before it drew).
+ ppp: f64,
+ }
+
+ impl Preview {
+ fn insert(&mut self, key: Key, sheet: Result<Arc<Sheet>, String>) {
+ self.pending.retain(|k| *k != key);
+ let frame = self.frame;
+ match self.entries.iter_mut().find(|e| e.key.spread == key.spread) {
+ Some(e) => *e = Entry { key, sheet, texture: None, used: frame },
+ None => self.entries.push(Entry { key, sheet, texture: None, used: frame }),
+ }
+ if self.entries.len() > MAX_SHEETS {
+ self.entries.sort_by_key(|e| std::cmp::Reverse(e.used));
+ self.entries.truncate(MAX_SHEETS);
+ }
+ }
+
+ /// Collects finished separations.
+ fn poll(&mut self) {
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ let mut done = Vec::new();
+ if let Some(w) = &self.worker {
+ while let Ok(d) = w.rx.try_recv() {
+ done.push(d);
+ }
+ }
+ for d in done {
+ self.last_ms = d.ms;
+ self.insert(d.key, d.sheet.map(Arc::new));
+ }
+ }
+ }
+
+ /// Asks for `key` to be separated, unless it is already or is being.
+ fn request(&mut self, ctx: &egui::Context, job: Job) {
+ if self.pending.contains(&job.key) || self.entries.iter().any(|e| e.key == job.key) {
+ return;
+ }
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ if !self.worker_started {
+ self.worker_started = true;
+ self.worker = Worker::spawn(ctx.clone());
+ }
+ if let Some(w) = &self.worker {
+ self.pending.push(job.key.clone());
+ if w.tx.send(job).is_ok() {
+ return;
+ }
+ self.pending.pop();
+ self.worker = None;
+ return;
+ }
+ }
+ let _ = ctx;
+ let done = separate(job);
+ self.last_ms = done.ms;
+ self.insert(done.key, done.sheet.map(Arc::new));
+ }
+
+ /// The newest sheet of spread `si` (it may be of an earlier revision while the current one
+ /// is being separated).
+ pub fn sheet(&self, si: usize) -> Option<&Result<Arc<Sheet>, String>> {
+ self.entries.iter().find(|e| e.key.spread == si).map(|e| &e.sheet)
+ }
+ }
+
+ /// The Export PDF settings the preview separates with.
+ pub fn print_settings(app: &DesignApp) -> Print {
+ let s = &app.ui.pdf_export;
+ let flatten = if s.flatten.is_empty() { app.ui.flattener.as_str() } else { s.flatten.as_str() };
+ Print {
+ standard: designcraft_engine::separations::Standard::parse(&s.standard).unwrap_or_default(),
+ compress_images: s.compress_images,
+ flatten: match flatten {
+ "high" => Some(300.0),
+ "medium" => Some(150.0),
+ "low" => Some(72.0),
+ _ => None,
+ },
+ }
+ }
+
+ /// The resolution for a view at `zoom` with `ppp` pixels per point: device pixels per point,
+ /// rounded up to a power of two of 72 dpi so that zooming within a step keeps the plates.
+ pub fn dpi_for(zoom: f64, ppp: f64) -> f32 {
+ let want = (zoom * ppp).max(1e-3);
+ let step = want.log2().ceil().exp2() * 72.0;
+ let dpi = (step as f32).clamp(MIN_DPI, MAX_DPI);
+ #[cfg(target_arch = "wasm32")]
+ let dpi = dpi.min(WEB_MAX_DPI);
+ dpi
+ }
+
+ fn key(app: &DesignApp, si: usize, dpi: f32) -> Option<(Key, Job)> {
+ let st = app.session.active()?;
+ let key = Key { uid: st.uid, revision: st.revision, spread: si, dpi, print: print_settings(app) };
+ Some((key.clone(), Job { key, doc: st.doc.clone(), cache: app.session.cache.clone() }))
+ }
+
-/// The sheet of the spread nearest the view centre, separated now if the canvas hasn't yet
++/// The sheet of the spread nearest the view center, separated now if the canvas hasn't yet
+ /// (for commands and automation, which want an answer).
+ pub fn current_sheet(app: &mut DesignApp) -> Result<Arc<Sheet>, String> {
+ let st = app.session.active().ok_or("no document")?;
+ let layout = CanvasLayout::new(&st.doc, st.editing_parents);
+ let slot = crate::canvas::current_slot(app, &layout).and_then(|i| layout.slots.get(i)).map(|s| s.spread);
+ let si = match slot {
+ Some(SpreadRef::Doc(si)) => si,
+ Some(_) => return Err("parent spreads aren't separated".into()),
+ None => st.doc.page_loc(0).map(|(si, _)| si).ok_or("no spread")?,
+ };
+ let ppp = if app.canvas.separations.ppp > 0.0 { app.canvas.separations.ppp } else { 1.0 };
+ let dpi = app.view().map_or(72.0, |v| dpi_for(v.zoom, ppp));
+ let (key, job) = key(app, si, dpi).ok_or("no document")?;
+ let preview = &mut app.canvas.separations;
+ preview.poll();
+ if let Some(e) =
+ preview.entries.iter().find(|e| e.key.uid == key.uid && e.key.revision == key.revision && e.key.spread == si && e.key.print == key.print)
+ {
+ return e.sheet.clone();
+ }
+ let done = separate(job);
+ preview.last_ms = done.ms;
+ let sheet = done.sheet.map(Arc::new);
+ preview.insert(done.key, sheet.clone());
+ sheet
+ }
+
+ /// The preview's state for `ui.inspect`: the view, and each kept sheet's plates (`null` when the
+ /// preview is off).
+ pub fn inspect(app: &DesignApp) -> serde_json::Value {
+ let Some(view) = &app.ui.separations else { return serde_json::Value::Null };
+ let revision = app.session.active().map(|st| (st.uid, st.revision));
+ let preview = &app.canvas.separations;
+ let sheets: Vec<serde_json::Value> = preview
+ .entries
+ .iter()
+ .map(|e| {
+ let mut v = serde_json::json!({"spread": e.key.spread, "dpi": e.key.dpi, "current": revision == Some((e.key.uid, e.key.revision))});
+ match &e.sheet {
+ Ok(sheet) => v["inks"] = sheet.inks().into_iter().map(|(name, spot)| serde_json::json!({"name": name, "spot": spot})).collect(),
+ Err(err) => v["error"] = serde_json::json!(err),
+ }
+ v
+ })
+ .collect();
+ serde_json::json!({
+ "plate": view.plate.as_deref().unwrap_or("all"),
+ "inkLimit": view.ink_limit,
+ "pending": preview.pending.len(),
+ "lastMs": preview.last_ms,
+ "sheets": sheets,
+ })
+ }
+
+ /// Draws the preview over each visible spread of the canvas.
+ pub fn paint(app: &mut DesignApp, ctx: &egui::Context, painter: &egui::Painter, xf: &Xf, layout: &CanvasLayout, screen: egui::Rect) {
+ let Some(view) = app.ui.separations.clone() else {
+ // Off: free the plates.
+ app.canvas.separations.entries.clear();
+ return;
+ };
+ let ppp = f64::from(ctx.pixels_per_point());
+ let dpi = dpi_for(xf.zoom, ppp);
+ app.canvas.separations.ppp = ppp;
+ app.canvas.separations.poll();
+ app.canvas.separations.frame += 1;
+ let frame = app.canvas.separations.frame;
+ let hover = ctx.pointer_hover_pos().filter(|p| screen.contains(*p)).map(|p| xf.to_canvas(p));
+ app.canvas.separations.pointer = None;
+ let Some(st) = app.session.active() else { return };
+ let doc = st.doc.clone();
+ for slot in &layout.slots {
+ let SpreadRef::Doc(si) = slot.spread else { continue };
+ let Some(sp) = doc.spreads.get(si) else { continue };
+ if !xf.rect(slot.xf.transform_rect_bbox(sp.bounds())).intersects(screen) {
+ continue;
+ }
+ if let Some(c) = hover {
+ let p = slot.xf.inverse() * c;
+ if sp.bounds().contains(p) {
+ app.canvas.separations.pointer = Some((si, p));
+ }
+ }
+ if let Some((_, job)) = key(app, si, dpi) {
+ app.canvas.separations.request(ctx, job);
+ }
+ let Some(entry) = app.canvas.separations.entries.iter_mut().find(|e| e.key.spread == si) else { continue };
+ entry.used = frame;
+ let Ok(sheet) = &entry.sheet else { continue };
+ let texture = match &entry.texture {
+ Some((v, tex)) if *v == view => tex.clone(),
+ _ => {
+ let plate = view.plate.as_deref().and_then(|n| sheet.ink(n));
+ let rgba = sheet.image(plate, view.ink_limit);
+ let size = [sheet.plates.width as usize, sheet.plates.height as usize];
+ if size[0] == 0 || size[1] == 0 || rgba.len() != size[0] * size[1] * 4 {
+ continue;
+ }
+ let ci = egui::ColorImage::from_rgba_unmultiplied(size, &rgba);
+ let ci = crate::widgets::fit_texture(ci, ctx.input(|i| i.max_texture_side));
+ let tex = ctx.load_texture(format!("separations-{si}"), ci, egui::TextureOptions::LINEAR);
+ entry.texture = Some((view.clone(), tex.clone()));
+ tex
+ }
+ };
+ let a = sheet.area;
+ let corners = [
+ (Point::new(a.x0, a.y0), pos2(0.0, 0.0)),
+ (Point::new(a.x1, a.y0), pos2(1.0, 0.0)),
+ (Point::new(a.x1, a.y1), pos2(1.0, 1.0)),
+ (Point::new(a.x0, a.y1), pos2(0.0, 1.0)),
+ ];
+ let mut mesh = egui::Mesh::with_texture(texture.id());
+ for (c, uv) in corners {
+ mesh.vertices.push(egui::epaint::Vertex { pos: xf.to_screen(slot.xf * c), uv, color: Color32::WHITE });
+ }
+ mesh.indices.extend([0, 1, 2, 0, 2, 3]);
+ painter.add(egui::Shape::mesh(mesh));
+ }
+ }
+
+ #[cfg(test)]
+ mod tests {
+ use serde_json::{Value, json};
+
+ use crate::menus::run_ui;
+
+ #[test]
+ fn view_separations_lists_the_spot_plate_and_shows_it_alone() {
+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.session.execute("file.new", &json!({})).unwrap();
+ app.session.execute("swatch.create", &json!({"name": "Gold", "spot": true, "color": {"c": 0, "m": 20, "y": 80, "k": 10}})).unwrap();
+ let id = app.session.execute("frame.create", &json!({"rect": [72, 72, 172, 172]})).unwrap()["id"].clone();
+ app.session.execute("object.fill", &json!({"swatch": "Gold", "ids": [id]})).unwrap();
+
+ let r = run_ui(&mut app, "view.separations", &json!({"plate": "Gold"})).unwrap().unwrap();
+ assert_eq!((r["on"].clone(), r["plate"].clone()), (json!(true), json!("Gold")), "{r}");
+ let inks: Vec<(String, bool)> =
+ r["inks"].as_array().unwrap().iter().map(|i| (i["name"].as_str().unwrap().to_string(), i["spot"] == true)).collect();
+ assert_eq!(inks.last(), Some(&("Gold".to_string(), true)), "{r}");
+ assert_eq!(inks.len(), 5, "the process inks and Gold: {r}");
+ assert_eq!(app.ui.separations.as_ref().and_then(|s| s.plate.as_deref()), Some("Gold"));
+
+ // The menu's params keep working.
+ run_ui(&mut app, "view.separations", &json!({"plate": "cyan"})).unwrap().unwrap();
+ assert_eq!(app.ui.separations.as_ref().and_then(|s| s.plate.as_deref()), Some("Cyan"));
+ let r = run_ui(&mut app, "view.separations", &json!({"inkLimit": 300})).unwrap().unwrap();
+ assert_eq!(r["inkLimit"], 300.0);
+ let r = run_ui(&mut app, "view.separations", &json!({"plate": null, "inkLimit": null})).unwrap().unwrap();
+ assert_eq!(r["on"], false);
+ assert!(app.ui.separations.is_none() && r.get("inks").is_none_or(Value::is_null));
+ }
+ }