Skip to content

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

Colour: craft-cms for ICC transforms; Coated FOGRA39 default CMYK, BPC display, FOGRA39 output intent

aionggb6c63d89c236
diff --git a/Cargo.lock b/Cargo.lock
index ef525c84e..18e0e26de 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -796,6 +796,14 @@ dependencies = [
"libm",
]
+[[package]]
+name = "craft-cms"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=e9546e191dd62f2bc1d61eca45dbdc2f1b3c1d8e#e9546e191dd62f2bc1d61eca45dbdc2f1b3c1d8e"
+dependencies = [
+ "rayon",
+]
+
[[package]]
name = "craft-print"
version = "0.1.0"
@@ -922,8 +930,8 @@ dependencies = [
name = "designcraft-color"
version = "0.7.1"
dependencies = [
+ "craft-cms",
"kurbo",
- "moxcms",
"proptest",
"serde",
"serde_json",
diff --git a/Cargo.toml b/Cargo.toml
index b08a82fc2..dc38e06a0 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -12,6 +12,8 @@ repository = "https://github.com/storytold/designcraft"
[workspace.dependencies]
craft-print = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "d991bf6792f8ade99c51358bf3c1d902c8cd96b5" }
+# ICC colour management: working spaces, transforms, black point compensation.
+craft-cms = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e9546e191dd62f2bc1d61eca45dbdc2f1b3c1d8e" }
# internal
designcraft-geom = { path = "crates/geom" }
designcraft-color = { path = "crates/color" }
diff --git a/ROADMAP.md b/ROADMAP.md
index 8a0f82071..1c3b3c3f7 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -129,6 +129,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m
Newest first.
+- **2026-10-13** · Colour management runs on craft-libs' `craft-cms`. The default CMYK working space is its Coated FOGRA39 profile (Generic CMYK and Device CMYK stay selectable); CMYK swatches show relative colorimetric with the settings' black point compensation, and PDF/X-4 output intents embed the working CMYK profile (FOGRA39 by default). Profile names the built-in stands in for resolve to it; other unknown names are an error, and saved settings naming one start with the default. No readiness percentage change.
- **2026-10-12** · macOS Dock Quit uses the same unsaved-document prompts as window and menu Quit. Repeated requests keep the current answers; Cancel retains every tab and unsaved recovery checkpoint, and completed Save/Don't Save answers exit through the ordinary event loop. No readiness percentage change.
- **2026-10-12** · Orderly native exit writes the latest recovery state after finalizing current quit approvals; incomplete or stale plans keep their documents, and Undo to the saved state clears stale recovery. Unavailable or failed recovery is reported. Cancelable macOS Dock Quit remains open (#544). No readiness percentage change.
- **2026-10-12** · Recovered documents keep a checkpoint until saved, closed or reverted, including a second crash before autosave. Restarted document IDs and explicit recovery folders preserve other snapshots; failed republishing retains the original. No readiness percentage change.
diff --git a/crates/color/Cargo.toml b/crates/color/Cargo.toml
index ca707a0d2..39459b426 100644
--- a/crates/color/Cargo.toml
+++ b/crates/color/Cargo.toml
@@ -12,7 +12,7 @@ workspace = true
kurbo = { workspace = true }
serde = { workspace = true }
thiserror = { workspace = true }
-moxcms = "0.8"
+craft-cms = { workspace = true }
[dev-dependencies]
proptest = { workspace = true }
diff --git a/crates/color/src/cms/icc.rs b/crates/color/src/cms/icc.rs
index 565ae0b70..ceed81a57 100644
--- a/crates/color/src/cms/icc.rs
+++ b/crates/color/src/cms/icc.rs
@@ -1,36 +1,38 @@
-//! ICC profiles through `moxcms` (pure Rust): built-in RGB spaces and user-supplied `.icc` files.
+//! ICC profiles through `craft-cms` (pure Rust): built-in RGB and CMYK spaces and user-supplied
+//! `.icc` files.
use std::sync::{Arc, OnceLock};
-use moxcms::{ColorProfile, DataColorSpace, Layout, ProfileText, RenderingIntent, TransformF32Executor, TransformOptions};
+use craft_cms::{Builtin, ColorSpace, Profile, Transform, TransformOptions};
+use super::lab::Lab;
use super::{CmsError, Intent, ProfileKind};
-fn moxcms_intent(i: Intent) -> RenderingIntent {
- match i {
- Intent::Perceptual => RenderingIntent::Perceptual,
- Intent::RelativeColorimetric => RenderingIntent::RelativeColorimetric,
- Intent::Saturation => RenderingIntent::Saturation,
- Intent::AbsoluteColorimetric => RenderingIntent::AbsoluteColorimetric,
- }
-}
+type Xf = Option<Arc<Transform>>;
-const INTENTS: [Intent; 4] = [Intent::Perceptual, Intent::RelativeColorimetric, Intent::Saturation, Intent::AbsoluteColorimetric];
+/// One transform per intent (in [`Intent::ALL`] order), without and with black point
+/// compensation.
+type Slots = [[OnceLock<Xf>; 2]; 4];
-fn intent_index(i: Intent) -> usize {
- INTENTS.iter().position(|x| *x == i).unwrap_or(1)
+fn slot(slots: &Slots, intent: Intent, bpc: bool) -> &OnceLock<Xf> {
+ let by_intent = match intent {
+ Intent::Perceptual => &slots[0],
+ Intent::RelativeColorimetric => &slots[1],
+ Intent::Saturation => &slots[2],
+ Intent::AbsoluteColorimetric => &slots[3],
+ };
+ if bpc { &by_intent[1] } else { &by_intent[0] }
}
-type Xf = Option<Arc<TransformF32Executor>>;
-
-/// A parsed ICC profile plus lazily-built transforms to/from sRGB.
+/// A parsed ICC profile plus lazily built transforms to and from sRGB and Lab.
pub struct IccProfile {
pub name: String,
pub kind: ProfileKind,
- profile: ColorProfile,
- srgb: ColorProfile,
- to_srgb: [OnceLock<Xf>; 4],
- from_srgb: [OnceLock<Xf>; 4],
+ profile: Arc<Profile>,
+ to_srgb: Slots,
+ from_srgb: Slots,
+ to_lab: OnceLock<Xf>,
+ from_lab: Slots,
}
impl std::fmt::Debug for IccProfile {
@@ -39,39 +41,58 @@ impl std::fmt::Debug for IccProfile {
}
}
-fn text(t: &Option<ProfileText>) -> Option<String> {
- match t.as_ref()? {
- ProfileText::PlainString(s) => Some(s.clone()),
- ProfileText::Localizable(v) => v.iter().find(|l| l.language == "en").or(v.first()).map(|l| l.value.clone()),
- ProfileText::Description(d) => Some(if d.ascii_string.is_empty() { d.unicode_string.clone() } else { d.ascii_string.clone() }),
+fn build(src: &Profile, dst: &Profile, intent: Intent, bpc: bool) -> Xf {
+ Transform::with_options(src, dst, TransformOptions { intent: intent.into(), bpc, precise_float: true }).ok().map(Arc::new)
+}
+
+/// Evaluate one colour exactly, each output clamped to 0..1; `None` when the transform's channel
+/// counts don't fit or the result isn't finite.
+fn eval(x: &Transform, src: &[f32], outputs: usize) -> Option<Vec<f32>> {
+ if x.inputs() != src.len() || x.outputs() != outputs {
+ return None;
+ }
+ let src: Vec<f32> = src.iter().map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }).collect();
+ let mut out = vec![0.0f32; outputs];
+ x.eval(&src, &mut out).ok()?;
+ out.iter().all(|o| o.is_finite()).then(|| out.into_iter().map(|v| v.clamp(0.0, 1.0)).collect())
+}
+
+fn eval3(x: &Transform, src: &[f32]) -> Option<[f32; 3]> {
+ match eval(x, src, 3)?.as_slice() {
+ &[a, b, c] => Some([a, b, c]),
+ _ => None,
}
- .map(|s| s.trim_matches(char::from(0)).trim().to_string())
- .filter(|s| !s.is_empty())
}
impl IccProfile {
- pub fn from_profile(name: Option<String>, profile: ColorProfile) -> Result<Self, CmsError> {
+ pub fn from_profile(name: Option<String>, profile: Arc<Profile>) -> Result<Self, CmsError> {
let kind = match profile.color_space {
- DataColorSpace::Rgb => ProfileKind::Rgb,
- DataColorSpace::Cmyk => ProfileKind::Cmyk,
- DataColorSpace::Gray => ProfileKind::Gray,
+ ColorSpace::Rgb => ProfileKind::Rgb,
+ ColorSpace::Cmyk => ProfileKind::Cmyk,
+ ColorSpace::Gray => ProfileKind::Gray,
other => return Err(CmsError::Unsupported(format!("profile colour space {other:?} is not RGB, CMYK or Gray"))),
};
- let name = name.or_else(|| text(&profile.description)).unwrap_or_else(|| format!("Untitled {kind:?} profile"));
- Ok(Self { name, kind, profile, srgb: ColorProfile::new_srgb(), to_srgb: Default::default(), from_srgb: Default::default() })
+ let desc = profile.description.trim_matches(char::from(0)).trim();
+ let name = name.or_else(|| (!desc.is_empty()).then(|| desc.to_string())).unwrap_or_else(|| format!("Untitled {kind:?} profile"));
+ Ok(Self {
+ name,
+ kind,
+ profile,
+ to_srgb: Default::default(),
+ from_srgb: Default::default(),
+ to_lab: OnceLock::new(),
+ from_lab: Default::default(),
+ })
}
pub fn from_bytes(name: Option<String>, bytes: &[u8]) -> Result<Self, CmsError> {
- let p = ColorProfile::new_from_slice(bytes).map_err(|e| CmsError::BadProfile(format!("{e:?}")))?;
- Self::from_profile(name, p)
+ let p = Profile::parse(bytes).map_err(|e| CmsError::BadProfile(e.to_string()))?;
+ Self::from_profile(name, Arc::new(p))
}
- fn layout(&self) -> Layout {
- match self.kind {
- ProfileKind::Cmyk => Layout::Rgba, // 4 channels
- ProfileKind::Gray => Layout::Gray,
- ProfileKind::Rgb => Layout::Rgb,
- }
+ /// The parsed profile.
+ pub fn profile(&self) -> &Arc<Profile> {
+ &self.profile
}
fn channels(&self) -> usize {
@@ -82,54 +103,67 @@ impl IccProfile {
}
}
- fn opts(intent: Intent) -> TransformOptions {
- TransformOptions { rendering_intent: moxcms_intent(intent), ..Default::default() }
+ fn to_xf(&self, intent: Intent, bpc: bool) -> Xf {
+ slot(&self.to_srgb, intent, bpc).get_or_init(|| build(&self.profile, Builtin::Srgb.profile(), intent, bpc)).clone()
}
- fn to_xf(&self, intent: Intent) -> Xf {
- self.to_srgb[intent_index(intent)]
- .get_or_init(|| self.profile.create_transform_f32(self.layout(), &self.srgb, Layout::Rgb, Self::opts(intent)).ok())
- .clone()
+ fn inverse_xf(&self, intent: Intent, bpc: bool) -> Xf {
+ slot(&self.from_srgb, intent, bpc).get_or_init(|| build(Builtin::Srgb.profile(), &self.profile, intent, bpc)).clone()
}
- fn inverse_xf(&self, intent: Intent) -> Xf {
- self.from_srgb[intent_index(intent)]
- .get_or_init(|| self.srgb.create_transform_f32(Layout::Rgb, &self.profile, self.layout(), Self::opts(intent)).ok())
- .clone()
+ /// Device values (RGB / CMYK / Gray, 0..1; missing channels are 0) → sRGB.
+ pub fn to_srgb(&self, v: &[f32], intent: Intent, bpc: bool) -> Option<[f32; 3]> {
+ let mut src = v.to_vec();
+ src.resize(self.channels(), 0.0);
+ eval3(&*self.to_xf(intent, bpc)?, &src)
+ }
+
+ /// sRGB → device values.
+ pub fn from_srgb(&self, rgb: [f32; 3], intent: Intent, bpc: bool) -> Option<Vec<f32>> {
+ let x = self.inverse_xf(intent, bpc)?;
+ eval(&x, &rgb, self.channels())
}
- /// Device values (RGB / CMYK / Gray, 0..1) → sRGB.
- pub fn to_srgb(&self, v: &[f32], intent: Intent) -> Option<[f32; 3]> {
- let xf = self.to_xf(intent)?;
+ /// Media-relative Lab (D50) of device values: relative colorimetric, no black point
+ /// compensation.
+ pub fn to_lab(&self, v: &[f32]) -> Option<Lab> {
+ let x = self.to_lab.get_or_init(|| build(&self.profile, Builtin::LabD50.profile(), Intent::RelativeColorimetric, false)).clone()?;
let mut src = v.to_vec();
src.resize(self.channels(), 0.0);
- let mut dst = [0.0f32; 3];
- xf.transform(&src, &mut dst).ok()?;
- Some(dst.map(|x| x.clamp(0.0, 1.0)))
+ let [l, a, b] = eval3(&x, &src)?;
+ // Lab D50 device values use the ICC v4 encoding: L/100, (a + 128)/255.
+ Some(Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0))
}
- /// sRGB → device values.
- pub fn from_srgb(&self, rgb: [f32; 3], intent: Intent) -> Option<Vec<f32>> {
- let xf = self.inverse_xf(intent)?;
- let mut dst = vec![0.0f32; self.channels()];
- xf.transform(&rgb, &mut dst).ok()?;
- Some(dst.into_iter().map(|x| x.clamp(0.0, 1.0)).collect())
+ /// Lab (D50) → device values with `intent`.
+ pub fn from_lab(&self, lab: Lab, intent: Intent, bpc: bool) -> Option<Vec<f32>> {
+ let x = slot(&self.from_lab, intent, bpc).get_or_init(|| build(Builtin::LabD50.profile(), &self.profile, intent, bpc)).clone()?;
+ eval(&x, &[lab.l / 100.0, (lab.a + 128.0) / 255.0, (lab.b + 128.0) / 255.0], self.channels())
}
/// Whether transforms can be built for this profile (checked at registration).
pub fn usable(&self) -> bool {
- self.to_xf(Intent::RelativeColorimetric).is_some() && self.inverse_xf(Intent::RelativeColorimetric).is_some()
+ self.to_xf(Intent::RelativeColorimetric, false).is_some() && self.inverse_xf(Intent::RelativeColorimetric, false).is_some()
}
}
-/// Built-in RGB working spaces from `moxcms`'s standard primaries.
+fn builtin(name: &str, b: Builtin) -> Option<IccProfile> {
+ IccProfile::from_profile(Some(name.to_string()), Arc::new(b.profile().clone())).ok()
+}
+
+/// Built-in RGB working spaces from craft-cms's built-in profiles.
pub fn builtin_rgb(name: &str) -> Option<IccProfile> {
- let p = match name {
- super::ADOBE_RGB => ColorProfile::new_adobe_rgb(),
- super::DISPLAY_P3 => ColorProfile::new_display_p3(),
- super::PROPHOTO_RGB => ColorProfile::new_pro_photo_rgb(),
- super::SRGB => ColorProfile::new_srgb(),
+ let b = match name {
+ super::ADOBE_RGB => Builtin::AdobeRgbCompat,
+ super::DISPLAY_P3 => Builtin::DisplayP3,
+ super::PROPHOTO_RGB => Builtin::ProPhotoCompat,
+ super::SRGB => Builtin::Srgb,
_ => return None,
};
- IccProfile::from_profile(Some(name.to_string()), p).ok()
+ builtin(name, b)
+}
+
+/// The Coated FOGRA39 built-in, listed as [`super::COATED_FOGRA39`].
+pub fn coated_fogra39() -> Option<IccProfile> {
+ builtin(super::COATED_FOGRA39, Builtin::CoatedFogra39)
}
diff --git a/crates/color/src/cms/icc_out.rs b/crates/color/src/cms/icc_out.rs
index 60b98f176..0f900f707 100644
--- a/crates/color/src/cms/icc_out.rs
+++ b/crates/color/src/cms/icc_out.rs
@@ -5,97 +5,74 @@
use std::sync::OnceLock;
-use moxcms::{
- ColorProfile, DataColorSpace, LocalizableString, LutDataType, LutStore, LutType, LutWarehouse, Matrix3d, ProfileClass, ProfileText,
- RenderingIntent,
-};
+use craft_cms::profile::{Lut, LutKind};
+use craft_cms::{Builtin, Clut, Curve, Intent as CmsIntent, Profile, pipeline::Stage};
-use super::Intent;
use super::lab::Lab;
+use super::{CmsError, Intent};
const A2B_GRID: usize = 9;
const B2A_GRID: usize = 17;
-/// ICC v2 legacy 16-bit Lab encoding (lut16Type).
-fn enc_lab(l: Lab) -> [u16; 3] {
- let q = |v: f32| v.round().clamp(0.0, 65535.0) as u16;
- [q(l.l * 652.8), q((l.a + 128.0) * 256.0), q((l.b + 128.0) * 256.0)]
-}
+/// ICC v2 legacy 16-bit Lab encoding (lut16Type), normalised to 0..1.
+const V2_L: f32 = 100.0 * 65535.0 / 65280.0;
+const V2_AB: f32 = 65535.0 / 256.0;
-fn dec_lab(v: [u16; 3]) -> Lab {
- Lab::new(v[0] as f32 / 652.8, v[1] as f32 / 256.0 - 128.0, v[2] as f32 / 256.0 - 128.0)
+fn enc_lab(l: Lab) -> [f32; 3] {
+ [l.l / V2_L, (l.a + 128.0) / V2_AB, (l.b + 128.0) / V2_AB].map(|v| v.clamp(0.0, 1.0))
}
-fn lut(inputs: u8, outputs: u8, grid: usize, clut: Vec<u16>) -> LutWarehouse {
- let ident = |n: u8| LutStore::Store16((0..n).flat_map(|_| [0u16, 65535]).collect());
- LutWarehouse::Lut(LutDataType {
- num_input_channels: inputs,
- num_output_channels: outputs,
- num_clut_grid_points: grid as u8,
- matrix: Matrix3d::IDENTITY,
- num_input_table_entries: 2,
- num_output_table_entries: 2,
- input_table: ident(inputs),
- clut_table: LutStore::Store16(clut),
- output_table: ident(outputs),
- lut_type: LutType::Lut16,
- })
+fn dec_lab(v: &[f32]) -> Lab {
+ let at = |i: usize| v.get(i).copied().unwrap_or(0.0);
+ Lab::new(at(0) * V2_L, at(1) * V2_AB - 128.0, at(2) * V2_AB - 128.0)
}
-fn text(s: &str) -> Option<ProfileText> {
- Some(ProfileText::Localizable(vec![LocalizableString::new("en".into(), "US".into(), s.into())]))
+fn lut16(clut: Clut) -> Lut {
+ let (i, o) = (clut.inputs(), clut.outputs());
+ let ident = |n: usize| Stage::Curves(vec![Curve::Table(vec![0.0, 1.0]); n]);
+ Lut { kind: LutKind::Lut16, inputs: i, outputs: o, stages: vec![ident(i), Stage::Clut(clut), ident(o)] }
}
/// The Generic CMYK model as an ICC output profile (built once).
-pub fn generic_cmyk_icc() -> &'static [u8] {
- static P: OnceLock<Vec<u8>> = OnceLock::new();
- P.get_or_init(|| {
- let g = super::generic();
- let step = |i: usize, n: usize| i as f32 / (n - 1) as f32;
- // CMYK → Lab (media-relative), first input channel varying slowest.
- let mut a2b = Vec::with_capacity(A2B_GRID.pow(4) * 3);
- for c in 0..A2B_GRID {
- for m in 0..A2B_GRID {
- for y in 0..A2B_GRID {
- for k in 0..A2B_GRID {
- let lab = g.to_lab_rel([step(c, A2B_GRID), step(m, A2B_GRID), step(y, A2B_GRID), step(k, A2B_GRID)]);
- a2b.extend(enc_lab(lab));
- }
- }
- }
- }
- // Lab → CMYK through the model's separation.
- let mut b2a = Vec::with_capacity(B2A_GRID.pow(3) * 4);
- let e = |i: usize| (i as f32 * 65535.0 / (B2A_GRID - 1) as f32).round() as u16;
- for l in 0..B2A_GRID {
- for a in 0..B2A_GRID {
- for b in 0..B2A_GRID {
- let lab = dec_lab([e(l), e(a), e(b)]);
- let cmyk = g.from_lab(lab, Intent::RelativeColorimetric, true);
- b2a.extend(cmyk.map(|v| (v.clamp(0.0, 1.0) * 65535.0).round() as u16));
- }
- }
- }
- let a2b = lut(4, 3, A2B_GRID, a2b);
- let b2a = lut(3, 4, B2A_GRID, b2a);
- let mut p = ColorProfile::default();
- p.pcs = DataColorSpace::Lab;
- p.color_space = DataColorSpace::Cmyk;
- p.profile_class = ProfileClass::OutputDevice;
- p.rendering_intent = RenderingIntent::RelativeColorimetric;
- let d50 = moxcms::Xyzd { x: 0.9642, y: 1.0, z: 0.8249 };
- p.white_point = d50;
- p.media_white_point = Some(d50);
- p.lut_a_to_b_perceptual = Some(a2b.clone());
- p.lut_a_to_b_colorimetric = Some(a2b.clone());
- p.lut_a_to_b_saturation = Some(a2b);
- p.lut_b_to_a_perceptual = Some(b2a.clone());
- p.lut_b_to_a_colorimetric = Some(b2a.clone());
- p.lut_b_to_a_saturation = Some(b2a);
- p.description = text(super::GENERIC_CMYK);
- p.copyright = text("No copyright; made by DesignCraft from its parametric press model. Use freely.");
- p.encode().unwrap_or_default()
+pub fn generic_cmyk_profile() -> Result<&'static Profile, CmsError> {
+ static P: OnceLock<Result<Profile, CmsError>> = OnceLock::new();
+ P.get_or_init(build_generic_cmyk).as_ref().map_err(Clone::clone)
+}
+
+fn build_generic_cmyk() -> Result<Profile, CmsError> {
+ let bad = |e: craft_cms::CmsError| CmsError::BadProfile(format!("{}: {e}", super::GENERIC_CMYK));
+ let g = super::generic();
+ // CMYK → Lab (media-relative).
+ let a2b = Clut::sample(vec![A2B_GRID; 4], 3, |inp, out| {
+ let at = |i: usize| inp.get(i).copied().unwrap_or(0.0);
+ out.copy_from_slice(&enc_lab(g.to_lab_rel([at(0), at(1), at(2), at(3)])));
+ })
+ .map_err(bad)?;
+ // Lab → CMYK through the model's separation.
+ let b2a = Clut::sample(vec![B2A_GRID; 3], 4, |inp, out| {
+ let cmyk = g.from_lab(dec_lab(inp), Intent::RelativeColorimetric, true);
+ out.copy_from_slice(&cmyk.map(|v| v.clamp(0.0, 1.0)));
})
+ .map_err(bad)?;
+ let (a2b, b2a) = (lut16(a2b), lut16(b2a));
+ // craft-cms profiles can't be constructed field by field outside the crate, so the
+ // tables replace those of a built-in CMYK output profile and the result is re-encoded.
+ let mut p = Builtin::CoatedCmyk.profile().clone();
+ p.rendering_intent = CmsIntent::RelativeColorimetric;
+ p.description = super::GENERIC_CMYK.into();
+ p.copyright = "No copyright; made by DesignCraft from its parametric press model. Use freely.".into();
+ p.white_point = [0.9642, 1.0, 0.8249];
+ p.black_point = None;
+ p.chad = None;
+ p.a2b = [Some(a2b.clone()), Some(a2b.clone()), Some(a2b)];
+ p.b2a = [Some(b2a.clone()), Some(b2a.clone()), Some(b2a)];
+ Ok(p.with_encoded_bytes())
+}
+
+/// [`generic_cmyk_profile`]'s ICC bytes.
+pub fn generic_cmyk_icc() -> Result<&'static [u8], CmsError> {
+ static B: OnceLock<Result<std::sync::Arc<Vec<u8>>, CmsError>> = OnceLock::new();
+ B.get_or_init(|| generic_cmyk_profile().map(Profile::to_bytes)).as_ref().map(|b| b.as_slice()).map_err(Clone::clone)
}
#[cfg(test)]
@@ -104,16 +81,17 @@ mod tests {
#[test]
fn generic_cmyk_profile_round_trips() {
- let bytes = generic_cmyk_icc();
+ let bytes = generic_cmyk_icc().unwrap();
assert!(bytes.len() > 1000);
assert_eq!(&bytes[36..40], b"acsp");
assert_eq!(&bytes[16..20], b"CMYK");
assert_eq!(&bytes[12..16], b"prtr");
// Read back: CMYK → sRGB through the profile is close to the model.
let p = super::super::icc::IccProfile::from_bytes(None, bytes).expect("parses");
+ assert_eq!(p.name, super::super::GENERIC_CMYK);
let g = super::super::generic();
for cmyk in [[0.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 1.0, 0.0], [0.2, 0.3, 0.1, 0.5]] {
- let via = p.to_srgb(&cmyk, Intent::RelativeColorimetric).expect("converts");
+ let via = p.to_srgb(&cmyk, Intent::RelativeColorimetric, false).expect("converts");
let model = g.to_srgb(cmyk, false);
for i in 0..3 {
assert!((via[i] - model[i]).abs() < 0.04, "{cmyk:?}: {via:?} vs {model:?}");
diff --git a/crates/color/src/cms/mod.rs b/crates/color/src/cms/mod.rs
index 2294d764e..cbbefdd2b 100644
--- a/crates/color/src/cms/mod.rs
+++ b/crates/color/src/cms/mod.rs
@@ -1,11 +1,12 @@
//! Colour management: working spaces, RGB ↔ CMYK ↔ Lab conversions with rendering intents,
//! gamut checks and soft-proof transforms.
//!
-//! * **RGB working spaces** are ICC matrix/shaper profiles via [`moxcms`] (sRGB, Adobe RGB (1998)
-//! compatible, Display P3, ProPhoto RGB) or user `.icc` files. Display output is sRGB.
-//! * **CMYK spaces:** [`GENERIC_CMYK`] is our own documented parametric press model
-//! ([`generic`]); [`DEVICE_CMYK`] is the old profile-free formula (kept for exact legacy numbers);
-//! any CMYK `.icc` the user loads goes through `moxcms` (LUT-based profiles).
+//! * **ICC profiles** go through `craft-cms`: the built-in RGB working spaces (sRGB, Adobe RGB
+//! (1998) compatible, Display P3, ProPhoto RGB), the default CMYK space [`COATED_FOGRA39`],
+//! and any `.icc` the user loads. Display output is sRGB; CMYK is shown relative colorimetric
+//! with the settings' black point compensation, as placed CMYK images are.
+//! * **Other CMYK spaces:** [`GENERIC_CMYK`] is our own documented parametric press model
+//! ([`generic`]); [`DEVICE_CMYK`] is the old profile-free formula (kept for exact legacy numbers).
//! * The **active settings** (Edit → Color Settings) are process-wide; [`crate::Color::to_rgb`]
//! uses them. Code that needs deterministic numbers builds its own [`Cms`] with [`Cms::new`].
@@ -14,6 +15,7 @@ pub mod icc;
pub mod icc_out;
pub mod lab;
+use std::borrow::Cow;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, OnceLock, RwLock};
@@ -29,6 +31,9 @@ pub const SRGB: &str = "sRGB IEC61966-2.1";
pub const ADOBE_RGB: &str = "Adobe RGB (1998) compatible";
pub const DISPLAY_P3: &str = "Display P3";
pub const PROPHOTO_RGB: &str = "ProPhoto RGB";
+/// craft-cms's coated offset profile fitted to the FOGRA39 characterisation data: the default
+/// CMYK working space.
+pub const COATED_FOGRA39: &str = craft_cms::builtin::COATED_FOGRA39_DESCRIPTION;
/// Our parametric press model (see [`generic`]). Not an Adobe/ECI profile.
pub const GENERIC_CMYK: &str = "DesignCraft Generic CMYK (SWOP-like)";
/// Profile-free CMYK (`rgb = (1−c)(1−k)` …): uncalibrated, kept for legacy numbers.
@@ -78,6 +83,17 @@ impl Intent {
}
}
+impl From<Intent> for craft_cms::Intent {
+ fn from(i: Intent) -> Self {
+ match i {
+ Intent::Perceptual => craft_cms::Intent::Perceptual,
+ Intent::RelativeColorimetric => craft_cms::Intent::RelativeColorimetric,
+ Intent::Saturation => craft_cms::Intent::Saturation,
+ Intent::AbsoluteColorimetric => craft_cms::Intent::AbsoluteColorimetric,
+ }
+ }
+}
+
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ProfileKind {
@@ -122,10 +138,33 @@ pub struct ColorSettings {
impl Default for ColorSettings {
fn default() -> Self {
- Self { rgb: SRGB.into(), cmyk: GENERIC_CMYK.into(), intent: Intent::RelativeColorimetric, bpc: true }
+ Self { rgb: SRGB.into(), cmyk: COATED_FOGRA39.into(), intent: Intent::RelativeColorimetric, bpc: true }
}
}
+impl ColorSettings {
+ /// These settings with each working space that isn't available (a profile that is no longer
+ /// loaded, a name from another version) replaced by the default one: for saved settings.
+ pub fn with_known_profiles(&self) -> Self {
+ let d = Self::default();
+ Self {
+ rgb: if rgb_space(&self.rgb).is_ok() { self.rgb.clone() } else { d.rgb },
+ cmyk: if cmyk_space(&self.cmyk).is_ok() { self.cmyk.clone() } else { d.cmyk },
+ ..self.clone()
+ }
+ }
+}
+
+/// A PDF/X output intent: the destination profile and the condition it names.
+#[derive(Clone, Debug)]
+pub struct OutputIntent {
+ pub icc: Cow<'static, [u8]>,
+ /// `OutputConditionIdentifier`: a registered characterisation, or `Custom`.
+ pub identifier: &'static str,
+ /// `OutputCondition` / `Info`: the profile's name.
+ pub condition: String,
+}
+
/// Target colour model for [`Cms::convert`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Model {
@@ -147,6 +186,12 @@ enum RgbSpace {
Icc(Arc<IccProfile>),
}
+/// The built-in Coated FOGRA39 space; `None` only if craft-cms can't use its own profile.
+fn fogra39() -> Option<Arc<IccProfile>> {
+ static P: OnceLock<Option<Arc<IccProfile>>> = OnceLock::new();
+ P.get_or_init(|| icc::coated_fogra39().map(Arc::new)).clone()
+}
+
fn generic() -> Arc<GenericCmyk> {
static G: OnceLock<Arc<GenericCmyk>> = OnceLock::new();
G.get_or_init(|| Arc::new(GenericCmyk::new(generic::swop_like()))).clone()
@@ -169,13 +214,21 @@ fn user_profile(name: &str) -> Option<Arc<IccProfile>> {
USER.read().unwrap_or_else(|e| e.into_inner()).iter().find(|p| p.name == name).cloned()
}
+/// The default CMYK space: Coated FOGRA39, or Generic CMYK should that profile be unusable.
+fn default_cmyk() -> CmykSpace {
+ fogra39().map_or_else(|| CmykSpace::Generic(generic()), CmykSpace::Icc)
+}
+
fn cmyk_space(name: &str) -> Result<CmykSpace, CmsError> {
match name {
GENERIC_CMYK => Ok(CmykSpace::Generic(generic())),
DEVICE_CMYK => Ok(CmykSpace::Device),
+ COATED_FOGRA39 => Ok(default_cmyk()),
_ => match user_profile(name) {
Some(p) if p.kind == ProfileKind::Cmyk => Ok(CmykSpace::Icc(p)),
Some(_) => Err(CmsError::Unsupported(format!("{name} is not a CMYK profile"))),
+ // Names of the profiles the built-in stands in for (Coated FOGRA39 (ISO 12647-2:2004), ISO Coated v2 (ECI) …).
+ None if craft_cms::Builtin::stand_in_for(name) == Some(craft_cms::Builtin::CoatedFogra39) => Ok(default_cmyk()),
None => Err(CmsError::UnknownProfile(name.into())),
},
}
@@ -200,7 +253,7 @@ pub fn profiles() -> Vec<ProfileInfo> {
let mut v: Vec<ProfileInfo> = [SRGB, ADOBE_RGB, DISPLAY_P3, PROPHOTO_RGB]
.iter()
.map(|n| ProfileInfo { name: (*n).into(), kind: ProfileKind::Rgb, builtin: true })
- .chain([GENERIC_CMYK, DEVICE_CMYK].iter().map(|n| ProfileInfo { name: (*n).into(), kind: ProfileKind::Cmyk, builtin: true }))
+ .chain([COATED_FOGRA39, GENERIC_CMYK, DEVICE_CMYK].iter().map(|n| ProfileInfo { name: (*n).into(), kind: ProfileKind::Cmyk, builtin: true }))
.collect();
for p in USER.read().unwrap_or_else(|e| e.into_inner()).iter() {
v.push(ProfileInfo { name: p.name.clone(), kind: p.kind, builtin: false });
@@ -215,7 +268,7 @@ pub fn register_icc(bytes: &[u8], name: Option<String>) -> Result<ProfileInfo, C
if p.kind == ProfileKind::Gray {
return Err(CmsError::Unsupported("grayscale profiles can't be working spaces yet".into()));
}
- if [SRGB, ADOBE_RGB, DISPLAY_P3, PROPHOTO_RGB, GENERIC_CMYK, DEVICE_CMYK].contains(&p.name.as_str()) {
+ if [SRGB, ADOBE_RGB, DISPLAY_P3, PROPHOTO_RGB, COATED_FOGRA39, GENERIC_CMYK, DEVICE_CMYK].contains(&p.name.as_str()) {
return Err(CmsError::Unsupported(format!("{} clashes with a built-in profile name", p.name)));
}
if !p.usable() {
@@ -253,7 +306,7 @@ impl std::fmt::Debug for Cms {
impl Default for Cms {
fn default() -> Self {
- Self { settings: ColorSettings::default(), rgb: RgbSpace::Srgb, cmyk: CmykSpace::Generic(generic()) }
+ Self { settings: ColorSettings::default(), rgb: RgbSpace::Srgb, cmyk: default_cmyk() }
}
}
@@ -268,29 +321,48 @@ impl Cms {
matches!(self.rgb, RgbSpace::Srgb)
}
+ /// The PDF/X output intent for the working CMYK space. Device CMYK has no profile and is
+ /// described by the Generic CMYK one.
+ pub fn output_intent(&self) -> Result<OutputIntent, CmsError> {
+ Ok(match &self.cmyk {
+ CmykSpace::Icc(p) if p.name == COATED_FOGRA39 => {
+ OutputIntent { icc: Cow::Borrowed(craft_cms::builtin::COATED_FOGRA39_ICC), identifier: "FOGRA39", condition: COATED_FOGRA39.into() }
+ }
+ CmykSpace::Icc(p) => OutputIntent { icc: Cow::Owned(p.profile().to_bytes().to_vec()), identifier: "Custom", condition: p.name.clone() },
+ CmykSpace::Generic(_) | CmykSpace::Device => {
+ OutputIntent { icc: Cow::Borrowed(icc_out::generic_cmyk_icc()?), identifier: "Custom", condition: GENERIC_CMYK.into() }
+ }
+ })
+ }
+
/// Working RGB → display sRGB.
pub fn rgb_to_srgb(&self, rgb: [f32; 3]) -> [f32; 3] {
match &self.rgb {
RgbSpace::Srgb => rgb,
- RgbSpace::Icc(p) => p.to_srgb(&rgb, Intent::RelativeColorimetric).unwrap_or(rgb),
+ RgbSpace::Icc(p) => p.to_srgb(&rgb, Intent::RelativeColorimetric, false).unwrap_or(rgb),
}
}
/// Display sRGB → working RGB.
pub fn srgb_to_rgb(&self, srgb: [f32; 3]) -> [f32; 3] {
match &self.rgb {
RgbSpace::Srgb => srgb,
- RgbSpace::Icc(p) => p.from_srgb(srgb, Intent::RelativeColorimetric).map(|v| [v[0], v[1], v[2]]).unwrap_or(srgb),
+ RgbSpace::Icc(p) => match p.from_srgb(srgb, Intent::RelativeColorimetric, false).as_deref() {
+ Some(&[r, g, b]) => [r, g, b],
+ _ => srgb,
+ },
}
}
- fn cmyk_to_srgb_in(space: &CmykSpace, cmyk: [f32; 4], absolute: bool) -> [f32; 3] {
+ /// `absolute` simulates the paper colour (absolute colorimetric, no black point
+ /// compensation); otherwise relative colorimetric with `bpc`.
+ fn cmyk_to_srgb_in(space: &CmykSpace, cmyk: [f32; 4], absolute: bool, bpc: bool) -> [f32; 3] {
let cmyk = cmyk.map(|v| v.clamp(0.0, 1.0));
match space {
CmykSpace::Generic(g) => g.to_srgb(cmyk, absolute),
CmykSpace::Device => naive_cmyk_to_rgb(cmyk),
CmykSpace::Icc(p) => {
- let i = if absolute { Intent::AbsoluteColorimetric } else { Intent::RelativeColorimetric };
- p.to_srgb(&cmyk, i).unwrap_or_else(|| naive_cmyk_to_rgb(cmyk))
+ let (i, bpc) = if absolute { (Intent::AbsoluteColorimetric, false) } else { (Intent::RelativeColorimetric, bpc) };
+ p.to_srgb(&cmyk, i, bpc).unwrap_or_else(|| naive_cmyk_to_rgb(cmyk))
}
}
}
@@ -299,13 +371,13 @@ impl Cms {
match space {
CmykSpace::Generic(g) => g.from_srgb(srgb, intent, bpc),
CmykSpace::Device => naive_rgb_to_cmyk(srgb),
- CmykSpace::Icc(p) => p.from_srgb(srgb, intent).map(|v| [v[0], v[1], v[2], v[3]]).unwrap_or_else(|| naive_rgb_to_cmyk(srgb)),
+ CmykSpace::Icc(p) => cmyk4(p.from_srgb(srgb, intent, bpc)).unwrap_or_else(|| naive_rgb_to_cmyk(srgb)),
}
}
/// CMYK in the working space → display sRGB (`absolute` simulates the paper colour).
pub fn cmyk_to_srgb(&self, cmyk: [f32; 4], absolute: bool) -> [f32; 3] {
- Self::cmyk_to_srgb_in(&self.cmyk, cmyk, absolute)
+ Self::cmyk_to_srgb_in(&self.cmyk, cmyk, absolute, self.settings.bpc)
}
/// Display sRGB → working CMYK with `intent`.
pub fn srgb_to_cmyk(&self, srgb: [f32; 3], intent: Intent) -> [f32; 4] {
@@ -313,16 +385,19 @@ impl Cms {
}
/// Media-relative Lab of a working-space CMYK colour.
pub fn cmyk_to_lab(&self, cmyk: [f32; 4]) -> Lab {
+ let cmyk = cmyk.map(|v| v.clamp(0.0, 1.0));
match &self.cmyk {
- CmykSpace::Generic(g) => g.to_lab_rel(cmyk.map(|v| v.clamp(0.0, 1.0))),
- _ => lab::srgb_to_lab(self.cmyk_to_srgb(cmyk, false)),
+ CmykSpace::Generic(g) => g.to_lab_rel(cmyk),
+ CmykSpace::Icc(p) => p.to_lab(&cmyk).unwrap_or_else(|| lab::srgb_to_lab(naive_cmyk_to_rgb(cmyk))),
+ CmykSpace::Device => lab::srgb_to_lab(self.cmyk_to_srgb(cmyk, false)),
}
}
/// Lab → working CMYK with `intent`.
pub fn lab_to_cmyk(&self, l: Lab, intent: Intent) -> [f32; 4] {
match &self.cmyk {
CmykSpace::Generic(g) => g.from_lab(l, intent, self.settings.bpc),
- _ => self.srgb_to_cmyk(lab::lab_to_srgb(l), intent),
+ CmykSpace::Icc(p) => cmyk4(p.from_lab(l, intent, self.settings.bpc)).unwrap_or_else(|| self.srgb_to_cmyk(lab::lab_to_srgb(l), intent)),
+ CmykSpace::Device => self.srgb_to_cmyk(lab::lab_to_srgb(l), intent),
}
}
@@ -388,10 +463,11 @@ impl Cms {
match &self.cmyk {
CmykSpace::Generic(g) => g.gamut_error(src),
CmykSpace::Device => 0.0,
- CmykSpace::Icc(_) => {
- let back = self.cmyk_to_srgb(self.srgb_to_cmyk(srgb, Intent::RelativeColorimetric), false);
- delta_e2000(src, lab::srgb_to_lab(back))
- }
+ // The colour sent to the press (relative colorimetric, clipped) and measured back.
+ CmykSpace::Icc(p) => match p.from_srgb(srgb, Intent::RelativeColorimetric, false).and_then(|cmyk| p.to_lab(&cmyk)) {
+ Some(back) => delta_e2000(src, back),
+ None => 0.0,
+ },
}
}
_ => 0.0,
@@ -418,7 +494,7 @@ impl Cms {
ProofTarget::Cmyk(name) => match cmyk_space(name) {
Ok(sp) => {
let cmyk = Self::srgb_to_cmyk_in(&sp, srgb, proof.intent, self.settings.bpc);
- Self::cmyk_to_srgb_in(&sp, cmyk, proof.simulate_paper)
+ Self::cmyk_to_srgb_in(&sp, cmyk, proof.simulate_paper, self.settings.bpc)
}
Err(_) => srgb,
},
@@ -429,7 +505,7 @@ impl Cms {
pub fn proof_cmyk_to_srgb(&self, cmyk: [f32; 4], proof: &ProofSetup) -> [f32; 3] {
match &proof.target {
ProofTarget::Cmyk(name) => match cmyk_space(name) {
- Ok(sp) => Self::cmyk_to_srgb_in(&sp, cmyk, proof.simulate_paper),
+ Ok(sp) => Self::cmyk_to_srgb_in(&sp, cmyk, proof.simulate_paper, self.settings.bpc),
Err(_) => self.cmyk_to_srgb(cmyk, proof.simulate_paper),
},
_ => self.cmyk_to_srgb(cmyk, proof.simulate_paper),
@@ -458,6 +534,13 @@ fn clear_proof_cache() {
PROOF_CACHE.lock().unwrap_or_else(|e| e.into_inner()).clear();
}
+fn cmyk4(v: Option<Vec<f32>>) -> Option<[f32; 4]> {
+ match v?.as_slice() {
+ &[c, m, y, k] => Some([c, m, y, k]),
+ _ => None,
+ }
+}
+
pub(crate) fn naive_cmyk_to_rgb([c, m, y, k]: [f32; 4]) -> [f32; 3] {
[(1.0 - c) * (1.0 - k), (1.0 - m) * (1.0 - k), (1.0 - y) * (1.0 - k)]
}
diff --git a/crates/color/src/cms/tests.rs b/crates/color/src/cms/tests.rs
index 4e4f1d8b7..d9e5ef195 100644
--- a/crates/color/src/cms/tests.rs
+++ b/crates/color/src/cms/tests.rs
@@ -23,22 +23,83 @@ fn intents_parse_and_name() {
}
#[test]
-fn srgb_via_moxcms_matches_analytic() {
- // The built-in sRGB ICC profile through moxcms agrees with our analytic sRGB maths.
+fn srgb_profile_matches_analytic() {
+ // The built-in sRGB ICC profile agrees with our analytic sRGB maths.
let p = icc::builtin_rgb(SRGB).unwrap();
for rgb in [[0.2, 0.5, 0.8], [1.0, 0.0, 0.0], [0.5, 0.5, 0.5]] {
- let out = p.to_srgb(&rgb, Intent::RelativeColorimetric).unwrap();
+ let out = p.to_srgb(&rgb, Intent::RelativeColorimetric, false).unwrap();
assert!(de(out, rgb) < 0.5, "{rgb:?} → {out:?}");
}
}
+/// sRGB 0..255 of CMYK percentages.
+fn shown(c: &Cms, [cy, m, y, k]: [f32; 4]) -> [f32; 3] {
+ c.display_rgb(&Color::cmyk(cy / 100.0, m / 100.0, y / 100.0, k / 100.0)).map(|v| v * 255.0)
+}
+
+/// Swatches in the default CMYK space (Coated FOGRA39), shown relative colorimetric with black
+/// point compensation, and the sRGB reference values they show as (u8, within 2).
+const FOGRA39_ANCHORS: [([f32; 4], [f32; 3]); 4] = [
+ ([0.0, 50.0, 100.0, 0.0], [243.0, 146.0, 0.0]),
+ ([0.0, 60.0, 100.0, 0.0], [239.0, 123.0, 0.0]),
+ ([0.0, 0.0, 0.0, 100.0], [28.0, 28.0, 27.0]),
+ ([100.0, 100.0, 0.0, 0.0], [48.0, 38.0, 131.0]),
+];
+
+#[test]
+fn default_cmyk_swatches_show_as_coated_fogra39() {
+ assert_eq!(ColorSettings::default().cmyk, COATED_FOGRA39);
+ for c in [Cms::default(), cms()] {
+ for (cmyk, want) in FOGRA39_ANCHORS {
+ let got = shown(&c, cmyk);
+ assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() <= 2.0), "{cmyk:?}: {got:?} vs {want:?}");
+ }
+ }
+}
+
+#[test]
+fn saved_cmyk_names_still_load() {
+ for name in [GENERIC_CMYK, DEVICE_CMYK, COATED_FOGRA39] {
+ let s = ColorSettings { cmyk: name.into(), ..Default::default() };
+ assert!(Cms::new(&s).is_ok(), "{name}");
+ assert_eq!(s.with_known_profiles(), s);
+ }
+ // The names of the profiles the built-in stands in for show the same colours.
+ let stand_in = Cms::new(&ColorSettings { cmyk: "Coated FOGRA39 (ISO 12647-2:2004)".into(), ..Default::default() }).unwrap();
+ assert_eq!(shown(&stand_in, [0.0, 50.0, 100.0, 0.0]), shown(&cms(), [0.0, 50.0, 100.0, 0.0]));
+ // A related press condition with a different ink limit has no stand-in.
+ let iso300 = ColorSettings { cmyk: "ISO Coated v2 300% (ECI)".into(), ..Default::default() };
+ assert!(matches!(Cms::new(&iso300), Err(CmsError::UnknownProfile(_))));
+ // A name that isn't available falls back to the default, keeping the other settings.
+ let saved = ColorSettings { rgb: ADOBE_RGB.into(), cmyk: "Some Press (gone)".into(), bpc: false, ..Default::default() };
+ assert!(Cms::new(&saved).is_err());
+ let loaded = saved.with_known_profiles();
+ assert_eq!(loaded, ColorSettings { rgb: ADOBE_RGB.into(), cmyk: COATED_FOGRA39.into(), bpc: false, ..Default::default() });
+ assert!(Cms::new(&loaded).is_ok());
+}
+
+#[test]
+fn output_intent_follows_the_working_cmyk_space() {
+ let fogra = cms().output_intent().unwrap();
+ assert_eq!((fogra.identifier, fogra.condition.as_str()), ("FOGRA39", COATED_FOGRA39));
+ assert_eq!(&*fogra.icc, craft_cms::builtin::COATED_FOGRA39_ICC);
+ for name in [GENERIC_CMYK, DEVICE_CMYK] {
+ let g = Cms::new(&ColorSettings { cmyk: name.into(), ..Default::default() }).unwrap().output_intent().unwrap();
+ assert_eq!((g.identifier, g.condition.as_str()), ("Custom", GENERIC_CMYK), "{name}");
+ assert_eq!(&*g.icc, icc_out::generic_cmyk_icc().unwrap());
+ }
+}
+
#[test]
fn paper_white_and_rich_black() {
let c = cms();
assert_eq!(c.srgb_to_cmyk([1.0, 1.0, 1.0], Intent::RelativeColorimetric), [0.0; 4]);
+ for intent in [Intent::Perceptual, Intent::RelativeColorimetric, Intent::Saturation] {
+ assert_eq!(c.lab_to_cmyk(lab::Lab::new(100.0, 0.0, 0.0), intent), [0.0; 4], "{intent:?}");
+ }
let k = c.srgb_to_cmyk([0.0, 0.0, 0.0], Intent::RelativeColorimetric);
assert!(k[3] > 0.8, "black generation puts most of the black in K: {k:?}");
- assert!(k.iter().sum::<f32>() <= 3.0 + 1e-3, "TAC limit: {k:?}");
+ assert!(k.iter().sum::<f32>() <= 3.3 + 1e-3, "Coated FOGRA39 total ink limit (330 %): {k:?}");
assert!(k[0] > 0.3 && k[1] > 0.3 && k[2] > 0.3, "rich black: {k:?}");
assert_eq!(c.cmyk_to_srgb([0.0; 4], false), [1.0, 1.0, 1.0]);
}
@@ -112,6 +173,10 @@ fn simulate_paper_tints_white() {
let rel = c.cmyk_to_srgb([0.0; 4], false);
let abs = c.cmyk_to_srgb([0.0; 4], true);
assert_eq!(rel, [1.0; 3]);
+ // FOGRA39 paper is slightly blue (b* -2); Generic CMYK's slightly warm.
+ assert!(abs.iter().all(|v| *v < 0.97) && abs[2] > abs[0], "paper is darker and slightly blue: {abs:?}");
+ let g = Cms::new(&ColorSettings { cmyk: GENERIC_CMYK.into(), ..Default::default() }).unwrap();
+ let abs = g.cmyk_to_srgb([0.0; 4], true);
assert!(abs[0] < 0.98 && abs[2] < abs[0], "paper is darker and slightly warm: {abs:?}");
}
diff --git a/crates/pdf/src/pdfx.rs b/crates/pdf/src/pdfx.rs
index 3218ffc76..76992b982 100644
--- a/crates/pdf/src/pdfx.rs
+++ b/crates/pdf/src/pdfx.rs
@@ -1,4 +1,4 @@
-//! PDF/X-4: the output intent (our Generic CMYK profile), the PDF/X version in the document
+//! PDF/X-4: the output intent (the working CMYK space's profile), the PDF/X version in the document
//! information and XMP, written as an incremental update of krilla's PDF 1.6 output; and a
//! check of the requirements this exporter is responsible for.
@@ -46,19 +46,19 @@ pub fn make_pdfx4(pdf: &[u8], title: &str) -> Option<Vec<u8>> {
out.extend_from_slice(b"\nendobj\n");
};
// The output profile and the output intent.
- let icc = designcraft_color::cms::icc_out::generic_cmyk_icc();
+ let intent = designcraft_color::cms::active().output_intent().ok()?;
let (icc_id, oi_id) = (size, size + 1);
- let mut s = format!("<</N 4/Length {}>>\nstream\n", icc.len()).into_bytes();
- s.extend_from_slice(icc);
+ let mut s = format!("<</N 4/Length {}>>\nstream\n", intent.icc.len()).into_bytes();
+ s.extend_from_slice(&intent.icc);
s.extend_from_slice(b"\nendstream");
put(&mut out, icc_id, &s);
- let cond = designcraft_color::cms::GENERIC_CMYK;
+ let cond = &intent.condition;
put(
&mut out,
oi_id,
format!(
"<</Type/OutputIntent/S/GTS_PDFX/OutputConditionIdentifier{}/OutputCondition{}/Info{}/RegistryName(http://www.color.org)/DestOutputProfile {icc_id} 0 R>>",
- lit("Custom"),
+ lit(intent.identifier),
lit(cond),
lit(cond)
)
diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs
index 9ac53d057..72a341e99 100644
--- a/crates/pdf/src/tests.rs
+++ b/crates/pdf/src/tests.rs
@@ -175,7 +175,9 @@ fn standards() {
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
assert!(crate::check_pdfx4(&r.bytes).is_empty());
let text = String::from_utf8_lossy(&r.bytes).to_string();
- assert!(text.contains("/OutputIntents[") && text.contains("DesignCraft Generic CMYK"));
+ // The default working CMYK space is the built-in Coated FOGRA39.
+ assert!(text.contains("/OutputIntents[") && text.contains("/OutputConditionIdentifier(FOGRA39)"), "output intent");
+ assert!(text.contains(r"/OutputCondition(Coated FOGRA39 \(fitted, craft-cms\))"), "output condition");
// A plain export fails the checks; both read with the same pages.
let plain = export_pdf(&d, &Cache::new(), &PdfOptions::default()).unwrap();
assert_eq!(hayro_syntax::Pdf::new(r.bytes.clone()).unwrap().pages().len(), hayro_syntax::Pdf::new(plain.clone()).unwrap().pages().len());
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index fc7a3e634..a22378d03 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -764,7 +764,7 @@ impl DesignApp {
if !self.color_applied {
self.color_applied = true;
if let Some(cs) = self.ui.color_settings.clone() {
- let _ = designcraft_color::cms::set_active(&cs);
+ let _ = designcraft_color::cms::set_active(&cs.with_known_profiles());
}
}
let scale = self.ui.ui_scale.clamp(0.5, 3.0);
diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md
index eb7d7e5c1..60fc09a7a 100644
--- a/docs/target-app-parity.md
+++ b/docs/target-app-parity.md
@@ -1,6 +1,6 @@
# DesignCraft parity with Adobe InDesign
-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (cancelable macOS Dock Quit) · **Target:** Adobe InDesign 2026 (21.6.0.57, macOS)
+> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (colour management on craft-cms, Coated FOGRA39 default CMYK) · **Target:** Adobe InDesign 2026 (21.6.0.57, macOS)
The authoritative assessment of how close DesignCraft is to Adobe InDesign. [ROADMAP.md](../ROADMAP.md)
summarizes it; [gaps.md](gaps.md) lists every known shortfall one at a time; the feature-by-feature
@@ -368,10 +368,10 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level
- Right-to-left text (World-Ready basics): right-to-left runs are shaped right to left, lines are reordered by the Unicode Bidirectional Algorithm (matched against the reference implementation), Paragraph Direction (`type.para {direction}`, Paragraph panel, IDML ParagraphDirection, EPUB `dir`). Digits (`digits`: Default, Arabic, Hindi, Farsi, Native by language; Character panel for right-to-left text; IDML DigitsType) draw 0–9 in another script. Kashidas (`kashidas` paragraph attribute, on by default): justified Arabic lines stretch at one join per word (after seen/sad when possible, never inside lam–alef) with a drawn tatweel before word spaces widen. Carets follow the drawing: the caret before a right-to-left glyph sits at its right edge, arrow keys move as drawn (by words in the line's direction), clicks find the nearest drawn caret position and selections highlight the selected glyphs. Binding: Right to Left (Document Setup, `layout.documentSetup {binding}`, IDML PageBinding) makes page 1 a left page and lays spreads out right to left.
- Interface language (Edit ▸ Interface Language, `app.language`): German, French, Spanish, Italian, Japanese, Simplified Chinese and Arabic menu titles, common menu items and panel names (our own translations). Common dialog, panel and tooltip labels are also localized, with English fallback for untranslated strings. Arabic translations cover every key in the shared interface translation table, including menu commands and utility labels. The Type menu's Story Direction, Horizontal/Vertical, Tate-Chu-Yoko, Ruby… and Kenten are translated too. Arabic labels use Unicode bidi run ordering and contextual shaping; welcome and new-document form layouts follow RTL direction independently of document binding. CJK and Arabic glyphs come from [craft-fonts](https://github.com/storytold/craft-fonts) when built with `CRAFT_FONTS_DIR` (all releases): BIZ UDPGothic and Noto Sans CJK SC for the UI (Chinese forms first in the Chinese interface), Noto Sans Arabic, and Mincho for Japanese documents (the web build embeds BIZ UDPGothic only); otherwise from system fonts. Ukrainian covers all 1,430 existing catalog keys, including publishing dialogs and built-in names, with persisted selection, grammatical count captions, English fallback and bundled Cyrillic UI glyph coverage.
- Page transitions (`page.transition/transitions`, Page Transitions panel): twelve transition types with speed and direction per spread, written into exported PDFs as `/Trans` entries through an incremental update.
-- PDF/X-4 export (`file.exportPdf {standard: "x4"}`): an output intent with our own Generic CMYK ICC profile (lut16 tables generated from the parametric press model), GTS_PDFXVersion in Info and XMP, `pdf:Trapped` in XMP as in Info, RGB images without a profile tagged sRGB, no image interpolation (none in PDF/A either), and built-in PDF/X-4 checks reported as warnings. qpdf finds no errors in the result.
+- PDF/X-4 export (`file.exportPdf {standard: "x4"}`): an output intent with the working CMYK space's profile (by default craft-cms's Coated FOGRA39 profile, identifier FOGRA39; Generic CMYK and Device CMYK embed our Generic CMYK profile, lut16 tables generated from the parametric press model), GTS_PDFXVersion in Info and XMP, `pdf:Trapped` in XMP as in Info, RGB images without a profile tagged sRGB, no image interpolation (none in PDF/A either), and built-in PDF/X-4 checks reported as warnings. qpdf finds no errors in the result.
- EPS place: placed at its (high-resolution) bounding box and shown, printed and exported through its TIFF preview, or a placeholder when it has none. PostScript itself isn't interpreted.
- Preferences: Dictionary (user dictionary; `spelling.setWords/words`), Spelling (Dynamic Spelling: red squiggles on the canvas, also Edit ▸ Spelling), Autocorrect (word list, applied as you type), Notes, Track Changes, Story Editor Display and File Handling (recovery interval) sections.
-- Colour management exposed: Edit ▸ Color Settings (`color.settings`: RGB/CMYK working spaces, intent, black-point compensation; `color.loadProfile` for ICC files; `color.convert` through the working spaces, with gamut checks) and View ▸ Proof Setup / Proof Colors (press, sRGB, legacy Mac RGB, colour-blindness simulations, simulate paper) on the canvas.
+- Colour management exposed (ICC through the craft-libs `craft-cms` crate): Edit ▸ Color Settings (`color.settings`: RGB/CMYK working spaces, default CMYK Coated FOGRA39 with CMYK swatches shown relative colorimetric with black-point compensation, Generic CMYK and Device CMYK still selectable, intent, black-point compensation; `color.loadProfile` for ICC files; `color.convert` through the working spaces, with gamut checks) and View ▸ Proof Setup / Proof Colors (press, sRGB, legacy Mac RGB, colour-blindness simulations, simulate paper) on the canvas.
- Keyboard: Tab / Shift+Tab hide and show all panels / all but Tools (`window.hidePanels`, `window.hidePanelsExceptTools`); Cmd+F6 / Cmd+Shift+F6 cycle documents; panel fields are reached with Tab and Escape returns to the layout.
- Smart guides and snapping (View ▸ Snap to Guides / Snap to Document Grid / Smart Guides, `view.snapPreferences` and Preferences ▸ Guides & Pasteboard): moving, drawing, resizing, rotating and pen/anchor drags snap in order to the document and baseline grids, ruler guides, margins and columns, other objects' edges and centres (parent-page items too, by visible stroked bounds), equal spacing, matching dimensions and matching rotation, with guides, gap marks and measurements drawn on the canvas. Shift and Cmd constrain the gesture.
- View ▸ Rotate Spread (`view.rotateSpread`, `layout.rotateSpreadView`): the spread in view turns in quarter turns on screen (stored with the document; output is unaffected). The canvas maps each spread through its own transform, so tools, snapping, resize handles, guides, overlays and rendering all follow the turned spread.