From 0ae4e9c10d9da5a9f3c4bb90740554012e3452c1 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 19 Nov 2026 05:14:13 +0700 Subject: [PATCH 01/13] tests: the shortcut sheet test compares two exports without the clock's stamps The PDF writer dates each file and makes its IDs from the clock, so two sheet exports on either side of a second boundary differed there and the test failed on main's coverage run. --- crates/ui-egui/src/shortcut_editor.rs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index 1d2a5fb81c..bb71115d8a 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -3781,7 +3781,22 @@ mod tests { let (csv_off, csv_on) = (String::from_utf8_lossy(csv_off), String::from_utf8_lossy(csv_on)); assert!(!csv_off.contains(&hold), "off, the CSV file lists no hold"); assert!(csv_on.contains(&swap[0].shortcut), "on, the CSV file lists it: {}", swap[0].shortcut); - assert_eq!(sheet_off, sheet_off_again, "the sheet is the same each time"); + // The writer stamps each file with the clock: its dates and its ID (fixed width), which differ + // between two exports a second apart. The rest of the file is the same each time. + let unstamped = |pdf: &[u8]| { + let mut b: Vec = pdf.iter().map(|&c| if c.is_ascii_digit() { b'0' } else { c }).collect(); + for key in [&b"InstanceID>"[..], b"DocumentID>", b"/ID["] { + let mut at = 0; + while let Some(i) = b[at..].windows(key.len()).position(|w| w == key) { + let start = at + i + key.len(); + let end = b[start..].iter().position(|&c| c == b'<' || c == b']').map_or(b.len(), |e| start + e); + b[start..end].fill(b'?'); + at = end; + } + } + b + }; + assert_eq!(unstamped(sheet_off), unstamped(sheet_off_again), "the sheet is the same each time"); assert_ne!(sheet_off, sheet_on, "on, the sheet lists the hold"); } From 4d73308977008e3e6a4aa50d46a0783976770364 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 17:21:45 -0500 Subject: [PATCH 02/13] color: cut over cms/icc.rs to craft-cms (#8612) --- Cargo.lock | 11 +- Cargo.toml | 1 + crates/color/Cargo.toml | 2 +- crates/color/src/cms/icc.rs | 423 +++++++++--------------------------- 4 files changed, 114 insertions(+), 323 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0d32cc52e4..2a431e3339 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1009,6 +1009,15 @@ dependencies = [ "ruzstd", ] +[[package]] +name = "craft-cms" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890" +dependencies = [ + "md-5", + "rayon", +] + [[package]] name = "craft-codepage" version = "0.1.0" @@ -6727,8 +6736,8 @@ dependencies = [ name = "vectorcraft-color" version = "0.24.1" dependencies = [ + "craft-cms", "kurbo 0.13.1", - "moxcms", "proptest", "serde", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index 6d2ab9e37b..f8e8dc95a3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,7 @@ repository = "https://github.com/storytold/vectorcraft" [workspace.dependencies] craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", default-features = false, features = ["interpret", "write"] } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "010702ee9b030844c852939095b1da0d0656a890" } craft-print = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", features = ["serde"] } diff --git a/crates/color/Cargo.toml b/crates/color/Cargo.toml index a007ede39f..9c1e7b522c 100644 --- a/crates/color/Cargo.toml +++ b/crates/color/Cargo.toml @@ -9,11 +9,11 @@ description = "VectorCraft color" workspace = true [dependencies] +craft-cms = { workspace = true } kurbo = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } -moxcms = "0.8" [dev-dependencies] proptest = { workspace = true } diff --git a/crates/color/src/cms/icc.rs b/crates/color/src/cms/icc.rs index 8fc287ae23..4eea3a2b25 100644 --- a/crates/color/src/cms/icc.rs +++ b/crates/color/src/cms/icc.rs @@ -1,22 +1,24 @@ -//! ICC profiles through `moxcms` (pure Rust): built-in RGB spaces and user-supplied `.icc` files, -//! and the profiles exports embed ([`encode_builtin`]), written in code from the CMS. +//! ICC profiles through `craft-cms` (pure Rust): built-in RGB spaces and user-supplied `.icc` +//! files, and the profiles exports embed ([`builtin_rgb_bytes`], [`cmyk_profile`], [`gray_profile`]). use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, OnceLock}; -use moxcms::{ - ColorProfile, DataColorSpace, Layout, LocalizableString, LutMultidimensionalType, LutStore, LutWarehouse, Matrix3d, ProfileClass, ProfileText, - RenderingIntent, ToneReprCurve, TransformF32Executor, TransformOptions, Vector3d, +use craft_cms::{ + Builtin, Clut, ColorSpace, Curve, Intent as CmsIntent, Pcs, Profile, ProfileClass, Transform, + builtin, + pipeline::Stage, + profile::{Lut, LutKind}, }; use super::{CmsError, Intent, ProfileKind, lab, profiles_generation}; -fn moxcms_intent(i: Intent) -> RenderingIntent { +fn cms_intent(i: Intent) -> CmsIntent { match i { - Intent::Perceptual => RenderingIntent::Perceptual, - Intent::RelativeColorimetric => RenderingIntent::RelativeColorimetric, - Intent::Saturation => RenderingIntent::Saturation, - Intent::AbsoluteColorimetric => RenderingIntent::AbsoluteColorimetric, + Intent::Perceptual => CmsIntent::Perceptual, + Intent::RelativeColorimetric => CmsIntent::RelativeColorimetric, + Intent::Saturation => CmsIntent::Saturation, + Intent::AbsoluteColorimetric => CmsIntent::AbsoluteColorimetric, } } @@ -26,25 +28,12 @@ fn intent_index(i: Intent) -> usize { INTENTS.iter().position(|x| *x == i).unwrap_or(1) } -type Xf = Option>; +type Xf = Option>; /// A direct transform's cache key: destination [`IccProfile::id`], [`profiles_generation`] it was -/// built in, intent index, black-point compensation. The id tells a reloaded profile from the old -/// one of the same name, which settings built before the reload still convert into; the -/// generation only lets the cache drop what reloads left behind. +/// built in, intent index, black-point compensation. type DirectKey = (u64, u64, usize, bool); -/// The transforms of [`IccProfile::to_same_model_of`]: into ProPhoto RGB's primaries with linear -/// tone curves, where black-point compensation is a linear remap, and from there into the -/// destination. -struct SameModel { - into: Arc, - out_of: Arc, - /// The source's and the destination's black as luminance in the linear space (both 0 without - /// compensation). - black: [f32; 2], -} - /// A parsed ICC profile plus lazily-built transforms to/from sRGB. pub struct IccProfile { pub name: String, @@ -53,28 +42,13 @@ pub struct IccProfile { pub kind: ProfileKind, /// The file it was loaded from (empty for profiles made in code). source: Vec, - profile: ColorProfile, - srgb: ColorProfile, + profile: Profile, + srgb: Profile, to_srgb: [OnceLock; 4], from_srgb: [OnceLock; 4], - /// Direct transforms into other RGB profiles ([`Self::to_rgb_of`]), by destination, intent - /// and black-point compensation. - direct: Mutex>)>>, - /// Transforms into other profiles of the same model ([`Self::to_same_model_of`]), keyed as - /// [`Self::direct`] is. - same_model: Mutex>)>>, -} - -/// A transform from one profile into an RGB profile without passing through sRGB: into the -/// destination's primaries with linear tone curves, where black-point compensation is a linear -/// remap, then onto its own curves. -struct Direct { - to_linear: Arc, - /// Linear → the destination's curves; `None` when the destination isn't a matrix profile - /// (the first transform goes straight into it, without compensation). - to_dest: Option>, - /// The source black's luminance in the linear destination (0: no compensation). - black: f32, + /// Direct transforms into other profiles ([`Self::to_rgb_of`], [`Self::to_same_model_of`]), + /// by destination, intent and black-point compensation. + direct: Mutex>, } impl std::fmt::Debug for IccProfile { @@ -83,25 +57,16 @@ impl std::fmt::Debug for IccProfile { } } -fn text(t: &Option) -> Option { - 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() }), - } - .map(|s| s.trim_matches(char::from(0)).trim().to_string()) - .filter(|s| !s.is_empty()) -} - impl IccProfile { - pub fn from_profile(name: Option, profile: ColorProfile) -> Result { + pub fn from_profile(name: Option, profile: Profile) -> Result { 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")); + 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")); static NEXT_ID: AtomicU64 = AtomicU64::new(0); Ok(Self { name, @@ -109,11 +74,10 @@ impl IccProfile { kind, source: Vec::new(), profile, - srgb: ColorProfile::new_srgb(), + srgb: builtin::srgb().clone(), to_srgb: Default::default(), from_srgb: Default::default(), direct: Mutex::new(Vec::new()), - same_model: Mutex::new(Vec::new()), }) } @@ -127,7 +91,7 @@ impl IccProfile { String::from_utf8_lossy(&tag.to_be_bytes()) ))); } - let p = ColorProfile::new_from_slice(bytes).map_err(|e| CmsError::BadProfile(format!("{e:?}")))?; + let p = Profile::parse(bytes).map_err(|e| CmsError::BadProfile(format!("{e:?}")))?; Ok(Self { source: bytes.to_vec(), ..Self::from_profile(name, p)? }) } @@ -136,14 +100,6 @@ impl IccProfile { if self.source.is_empty() { encode(&self.profile) } else { Ok(self.source.clone()) } } - fn layout(&self) -> Layout { - match self.kind { - ProfileKind::Cmyk => Layout::Rgba, // 4 channels - ProfileKind::Gray => Layout::Gray, - ProfileKind::Rgb => Layout::Rgb, - } - } - fn channels(&self) -> usize { match self.kind { ProfileKind::Cmyk => 4, @@ -152,19 +108,15 @@ impl IccProfile { } } - fn opts(intent: Intent) -> TransformOptions { - TransformOptions { rendering_intent: moxcms_intent(intent), ..Default::default() } - } - 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()) + .get_or_init(|| Transform::new(&self.profile, &self.srgb, cms_intent(intent), false).ok().map(Arc::new)) .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()) + .get_or_init(|| Transform::new(&self.srgb, &self.profile, cms_intent(intent), false).ok().map(Arc::new)) .clone() } @@ -183,7 +135,7 @@ impl IccProfile { } let xf = self.to_xf(intent)?; let mut dst = [0.0f32; 3]; - xf.transform(v, &mut dst).ok()?; + xf.eval_fast(v, &mut dst).ok()?; Some(dst.map(|x| x.clamp(0.0, 1.0))) } @@ -197,7 +149,7 @@ impl IccProfile { return None; } let xf = self.to_xf(intent)?; - xf.transform(v, dst).ok()?; + xf.convert_f32(v, n, dst, 3, false).ok()?; dst.iter_mut().for_each(|x| *x = x.clamp(0.0, 1.0)); Some(()) } @@ -206,142 +158,53 @@ impl IccProfile { pub fn from_srgb(&self, rgb: [f32; 3], intent: Intent) -> Option> { let xf = self.inverse_xf(intent)?; let mut dst = vec![0.0f32; self.channels()]; - xf.transform(&rgb, &mut dst).ok()?; + xf.eval_fast(&rgb, &mut dst).ok()?; Some(dst.into_iter().map(|x| x.clamp(0.0, 1.0)).collect()) } + fn direct_xf(&self, dest: &IccProfile, intent: Intent, bpc: bool) -> Xf { + let generation = profiles_generation(); + let key = (dest.id, generation, intent_index(intent), bpc); + let mut cache = self.direct.lock().unwrap_or_else(|e| e.into_inner()); + cache.retain(|(k, _)| k.1 == generation); + if let Some((_, t)) = cache.iter().find(|(k, _)| *k == key) { + return t.clone(); + } + let t = Transform::new(&self.profile, &dest.profile, cms_intent(intent), bpc).ok().map(Arc::new); + cache.push((key, t.clone())); + t + } + /// Device values (RGB / CMYK / Gray, 0..1) → `dest`'s RGB, converted directly with `intent`: /// not through sRGB, so colours outside sRGB keep their place in a wider space. With `bpc` /// (and an intent other than absolute), this profile's black maps onto the destination's - /// black (black-point compensation, the darkest ink the profile prints becoming RGB 0 rather - /// than a dark grey). `None` when `dest` isn't RGB or no transform can be built. + /// black (black-point compensation). `None` when `dest` isn't RGB or no transform can be built. pub fn to_rgb_of(&self, dest: &IccProfile, v: &[f32], intent: Intent, bpc: bool) -> Option<[f32; 3]> { - let t = self.direct_xf(dest, intent, bpc && intent != Intent::AbsoluteColorimetric)?; - let mut src = v.to_vec(); - src.resize(self.channels(), 0.0); - let mut lin = [0.0f32; 3]; - t.to_linear.transform(&src, &mut lin).ok()?; - let Some(to_dest) = &t.to_dest else { return Some(lin.map(|x| x.clamp(0.0, 1.0))) }; - if t.black > 0.0 { - lin = lin.map(|x| (x - t.black) / (1.0 - t.black)); - } - let lin = lin.map(|x| x.clamp(0.0, 1.0)); - let mut out = [0.0f32; 3]; - to_dest.transform(&lin, &mut out).ok()?; - Some(out.map(|x| x.clamp(0.0, 1.0))) - } - - fn direct_xf(&self, dest: &IccProfile, intent: Intent, bpc: bool) -> Option> { if dest.kind != ProfileKind::Rgb { return None; } - let generation = profiles_generation(); - let key = (dest.id, generation, intent_index(intent), bpc); - let mut cache = self.direct.lock().unwrap_or_else(|e| e.into_inner()); - // an older generation's entries can't match again: drop them so reloads don't pile up - cache.retain(|(k, _)| k.1 == generation); - if let Some((_, t)) = cache.iter().find(|(k, _)| *k == key) { - return t.clone(); - } - let t = self.build_direct(dest, intent, bpc).map(Arc::new); - cache.push((key, t.clone())); - t - } - - fn build_direct(&self, dest: &IccProfile, intent: Intent, bpc: bool) -> Option { - let d = &dest.profile; - let matrix = d.red_trc.is_some() && d.green_trc.is_some() && d.blue_trc.is_some(); - if !matrix { - let xf = self.profile.create_transform_f32(self.layout(), d, Layout::Rgb, Self::opts(intent)).ok()?; - return Some(Direct { to_linear: xf, to_dest: None, black: 0.0 }); - } - let mut linear = d.clone(); - for trc in [&mut linear.red_trc, &mut linear.green_trc, &mut linear.blue_trc] { - *trc = Some(ToneReprCurve::Parametric(vec![1.0])); - } - // A coding-independent code point names the transfer curve outright (moxcms's sRGB has - // one) and would override the linear curves. - linear.cicp = None; - let to_linear = self.profile.create_transform_f32(self.layout(), &linear, Layout::Rgb, Self::opts(intent)).ok()?; - let to_dest = linear.create_transform_f32(Layout::Rgb, d, Layout::Rgb, Self::opts(Intent::RelativeColorimetric)).ok()?; - // The source black: the darkest colour the profile reproduces, found as lcms does for an - // output profile (black sent into the profile and read back), made neutral. - let black = if bpc && self.kind == ProfileKind::Cmyk { - let inks = self.from_srgb([0.0; 3], Intent::RelativeColorimetric)?; - let mut lin = [0.0f32; 3]; - to_linear.transform(&inks, &mut lin).ok()?; - let y = |c: &moxcms::Xyzd| c.y as f32; - let lum = lin[0] * y(&d.red_colorant) + lin[1] * y(&d.green_colorant) + lin[2] * y(&d.blue_colorant); - lum.clamp(0.0, 0.5) - } else { - 0.0 - }; - Some(Direct { to_linear, to_dest: Some(to_dest), black }) + let xf = self.direct_xf(dest, intent, bpc && intent != Intent::AbsoluteColorimetric)?; + let mut src = v.to_vec(); + src.resize(self.channels(), 0.0); + let mut out = [0.0f32; 3]; + xf.eval_fast(&src, &mut out).ok()?; + Some(out.map(|x| x.clamp(0.0, 1.0))) } /// Device values of this profile → device values of `dest`, a profile of the same model, - /// converted with `intent` through ProPhoto RGB rather than sRGB, so colours outside sRGB - /// keep their place. With `bpc` (and an intent other than absolute), this profile's black - /// maps onto the destination's black (black-point compensation). `None` when `dest` is of - /// another model or no transform can be built. + /// converted with `intent` directly. With `bpc` (and an intent other than absolute), this + /// profile's black maps onto the destination's black. `None` when `dest` is of another model or + /// no transform can be built. pub fn to_same_model_of(&self, dest: &IccProfile, v: &[f32], intent: Intent, bpc: bool) -> Option> { if dest.kind != self.kind || v.len() != self.channels() { return None; } - let bpc = bpc && intent != Intent::AbsoluteColorimetric; - let generation = profiles_generation(); - let key = (dest.id, generation, intent_index(intent), bpc); - let t = { - let mut cache = self.same_model.lock().unwrap_or_else(|e| e.into_inner()); - cache.retain(|(k, _)| k.1 == generation); - match cache.iter().find(|(k, _)| *k == key) { - Some((_, t)) => t.clone(), - None => { - let t = self.build_same_model(dest, intent, bpc).map(Arc::new); - cache.push((key, t.clone())); - t - } - } - }?; - let mut lin = [0.0f32; 3]; - t.into.transform(v, &mut lin).ok()?; - let [from, to] = t.black; - if from > 0.0 || to > 0.0 { - lin = lin.map(|x| to + (x - from) * (1.0 - to) / (1.0 - from)); - } - let lin = lin.map(|x| x.clamp(0.0, 1.0)); + let xf = self.direct_xf(dest, intent, bpc && intent != Intent::AbsoluteColorimetric)?; let mut out = vec![0.0f32; dest.channels()]; - t.out_of.transform(&lin, &mut out).ok()?; + xf.eval_fast(v, &mut out).ok()?; Some(out.into_iter().map(|x| x.clamp(0.0, 1.0)).collect()) } - fn build_same_model(&self, dest: &IccProfile, intent: Intent, bpc: bool) -> Option { - let mut linear = rgb_space(super::PROPHOTO_RGB)?; - for trc in [&mut linear.red_trc, &mut linear.green_trc, &mut linear.blue_trc] { - *trc = Some(ToneReprCurve::Parametric(vec![1.0])); - } - linear.cicp = None; - let into = self.profile.create_transform_f32(self.layout(), &linear, Layout::Rgb, Self::opts(intent)).ok()?; - let out_of = linear.create_transform_f32(Layout::Rgb, &dest.profile, dest.layout(), Self::opts(intent)).ok()?; - let black = if bpc { - // Each profile's black: the darkest colour it reproduces, found as `build_direct` - // finds it, as luminance in the linear space. - let luminance = |p: &IccProfile, xf: &Arc| -> Option { - let inks = p.from_srgb([0.0; 3], Intent::RelativeColorimetric)?; - let mut lin = [0.0f32; 3]; - xf.transform(&inks, &mut lin).ok()?; - let y = |c: &moxcms::Xyzd| c.y as f32; - let lum = lin[0] * y(&linear.red_colorant) + lin[1] * y(&linear.green_colorant) + lin[2] * y(&linear.blue_colorant); - Some(lum.clamp(0.0, 0.5)) - }; - let back = dest.profile.create_transform_f32(dest.layout(), &linear, Layout::Rgb, Self::opts(intent)).ok()?; - [luminance(self, &into)?, luminance(dest, &back)?] - } else { - [0.0; 2] - }; - Some(SameModel { into, out_of, black }) - } - /// 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() @@ -349,17 +212,17 @@ impl IccProfile { } /// The primaries and tone curves of built-in RGB space `name`. -fn rgb_space(name: &str) -> Option { +fn rgb_space(name: &str) -> Option { Some(match name { - super::WIDE_GAMUT_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(), + super::WIDE_GAMUT_RGB => Builtin::AdobeRgbCompat.profile().clone(), + super::DISPLAY_P3 => Builtin::DisplayP3.profile().clone(), + super::PROPHOTO_RGB => Builtin::ProPhotoCompat.profile().clone(), + super::SRGB => Builtin::Srgb.profile().clone(), _ => return None, }) } -/// Built-in RGB working spaces from `moxcms`'s standard primaries. +/// Built-in RGB working spaces from `craft-cms`'s standard primaries. pub fn builtin_rgb(name: &str) -> Option { IccProfile::from_profile(Some(name.to_string()), rgb_space(name)?).ok() } @@ -370,8 +233,8 @@ pub(super) fn builtin_rgb_bytes(name: &str) -> Result, CmsError> { } /// Encode `p` as an ICC file. The creation date is fixed so exports are reproducible. -pub(super) fn encode(p: &ColorProfile) -> Result, CmsError> { - let mut bytes = aligned(p.encode().map_err(|e| CmsError::BadProfile(format!("{e:?}")))?); +pub(super) fn encode(p: &Profile) -> Result, CmsError> { + let mut bytes = p.to_bytes().as_ref().clone(); // Header bytes 24..36: year, month, day, hours, minutes, seconds (u16 each). if let Some(date) = bytes.get_mut(24..36) { date.copy_from_slice(&[2026u16, 1, 1, 0, 0, 0].map(u16::to_be_bytes).concat()); @@ -379,63 +242,10 @@ pub(super) fn encode(p: &ColorProfile) -> Result, CmsError> { Ok(bytes) } -/// `icc` with every tagged element starting on a 4-byte boundary, padded with zeros, as ICC.1 -/// §7.1.2 requires (moxcms packs them, so a 62-byte `desc` left the next tag unaligned, #1584). -/// Tags that share data keep sharing it. A profile whose tag table doesn't read is returned as it is. -fn aligned(icc: Vec) -> Vec { - const TABLE: usize = 128; - let be = |b: &[u8], at: usize| b.get(at..at + 4).map(|v| u32::from_be_bytes([v[0], v[1], v[2], v[3]]) as usize); - let Some(n) = be(&icc, TABLE).filter(|n| *n <= 1000) else { return icc }; - let data_start = TABLE + 4 + 12 * n; - let mut entries = Vec::with_capacity(n); - for i in 0..n { - let e = TABLE + 4 + 12 * i; - let (Some(off), Some(size)) = (be(&icc, e + 4), be(&icc, e + 8)) else { return icc }; - if off < data_start || off.checked_add(size).is_none_or(|end| end > icc.len()) { - return icc; - } - entries.push((off, size)); - } - if entries.iter().all(|(off, _)| off.is_multiple_of(4)) && icc.len().is_multiple_of(4) { - return icc; - } - let mut out = icc.get(..data_start).map(<[u8]>::to_vec).unwrap_or_default(); - let mut moved: Vec<((usize, usize), usize)> = Vec::new(); - let mut order: Vec = (0..n).collect(); - order.sort_by_key(|&i| entries[i].0); - for i in order { - let (off, size) = entries[i]; - let at = match moved.iter().find(|(k, _)| *k == (off, size)) { - Some((_, at)) => *at, - None => { - out.resize(out.len().next_multiple_of(4), 0); - let at = out.len(); - out.extend_from_slice(&icc[off..off + size]); - moved.push(((off, size), at)); - at - } - }; - let e = TABLE + 4 + 12 * i + 4; - out[e..e + 4].copy_from_slice(&(at as u32).to_be_bytes()); - } - out.resize(out.len().next_multiple_of(4), 0); - let len = out.len() as u32; - out[0..4].copy_from_slice(&len.to_be_bytes()); - // The profile ID (an MD5 of the old bytes) no longer matches: zero is "not computed". - if let Some(id) = out.get_mut(84..100) { - id.fill(0); - } - out -} - -fn text_tag(s: &str) -> Option { - Some(ProfileText::Localizable(vec![LocalizableString::new("en".into(), "US".into(), s.into())])) -} - /// Profiles made here carry their name and no copyright claim. -fn labelled(mut p: ColorProfile, name: &str) -> ColorProfile { - p.description = text_tag(name); - p.copyright = text_tag("No copyright, use freely"); +fn labelled(mut p: Profile, name: &str) -> Profile { + p.description = name.to_string(); + p.copyright = "No copyright, use freely".to_string(); p } @@ -449,91 +259,67 @@ const GAMUT_GRID: usize = 9; /// 9⁴ table, and Lab → CMYK in 17³ tables, Lab PCS (ICC v4 encoding): `mapped` (gamut-mapped, /// with black-point compensation) for the perceptual and saturation intents, `colorimetric` (the /// colorimetric inverse of `to_lab`) for the colorimetric intents and the gamut tag. -/// It carries every tag ICC.1 requires of an output profile: the tables for all three intents -/// and the gamut tag (Windows rejects a CMYK profile without them, so Photos couldn't show a CMYK -/// TIFF that embedded one, #2707). The media white point is `paper` (absolute XYZ, D50), which -/// the ICC-absolute colorimetric intent reproduces. pub(super) fn cmyk_profile( name: &str, paper: [f32; 3], to_lab: impl Fn([f32; 4]) -> lab::Lab, mapped: impl Fn(lab::Lab) -> [f32; 4], colorimetric: impl Fn(lab::Lab) -> [f32; 4], -) -> ColorProfile { +) -> Profile { let unit = |i: usize, n: usize| i as f32 / (n - 1) as f32; - let q = |v: f32| (v.clamp(0.0, 1.0) * 65535.0).round() as u16; - let mut a2b = Vec::with_capacity(A2B_GRID.pow(4) * 3); + let mut a2b_clut = Vec::with_capacity(A2B_GRID.pow(4) * 3); for i in 0..A2B_GRID.pow(4) { let cmyk = [3, 2, 1, 0].map(|d| unit(i / A2B_GRID.pow(d) % A2B_GRID, A2B_GRID)); let l = to_lab(cmyk); - a2b.extend([l.l / 100.0, (l.a + 128.0) / 255.0, (l.b + 128.0) / 255.0].map(q)); + a2b_clut.extend([l.l / 100.0, (l.a + 128.0) / 255.0, (l.b + 128.0) / 255.0]); } let b2a_of = |from_lab: &dyn Fn(lab::Lab) -> [f32; 4]| { - let mut b2a = Vec::with_capacity(B2A_GRID.pow(3) * 4); + let mut clut = Vec::with_capacity(B2A_GRID.pow(3) * 4); for i in 0..B2A_GRID.pow(3) { let [l, a, b] = [2, 1, 0].map(|d| unit(i / B2A_GRID.pow(d) % B2A_GRID, B2A_GRID)); - b2a.extend(from_lab(lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0)).map(q)); + clut.extend(from_lab(lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0))); } - b2a + clut }; - let (b2a_mapped, b2a) = (b2a_of(&mapped), b2a_of(&colorimetric)); - // Gamut: 0 where a colour separates and comes back within a ΔE of 3, else out of gamut. - let mut gamut = Vec::with_capacity(GAMUT_GRID.pow(3)); + let (b2a_mapped_clut, b2a_clut) = (b2a_of(&mapped), b2a_of(&colorimetric)); + let mut gamut_clut = Vec::with_capacity(GAMUT_GRID.pow(3)); for i in 0..GAMUT_GRID.pow(3) { let [l, a, b] = [2, 1, 0].map(|d| unit(i / GAMUT_GRID.pow(d) % GAMUT_GRID, GAMUT_GRID)); let want = lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0); - gamut.push(if lab::delta_e2000(want, to_lab(colorimetric(want))) <= 3.0 { 0 } else { u16::MAX }); + gamut_clut.push(if lab::delta_e2000(want, to_lab(colorimetric(want))) <= 3.0 { 0.0 } else { 1.0 }); } - let identity = |n: usize| vec![ToneReprCurve::Parametric(vec![1.0]); n]; - let table = |inputs: usize, outputs: usize, grid: usize, clut: Vec| { - let mut grid_points = [0u8; 16]; - grid_points[..inputs].fill(grid as u8); - LutWarehouse::Multidimensional(LutMultidimensionalType { - num_input_channels: inputs as u8, - num_output_channels: outputs as u8, - grid_points, - clut: Some(LutStore::Store16(clut)), - // A curves sit on the device side (the gamut tag's is its one output), B curves on the - // PCS side. - a_curves: identity(inputs + outputs - 3), - b_curves: identity(3), - m_curves: vec![], - matrix: Matrix3d::IDENTITY, - bias: Vector3d::default(), - }) + let table = |inputs: usize, outputs: usize, grid: usize, clut: Vec| Lut { + kind: LutKind::Ab, + inputs, + outputs, + stages: vec![Stage::Clut(Clut::new(vec![grid; inputs], outputs, clut).expect("valid CLUT dimensions"))], }; - let a2b = table(4, 3, A2B_GRID, a2b); - let b2a_mapped = table(3, 4, B2A_GRID, b2a_mapped); - let b2a = table(3, 4, B2A_GRID, b2a); - let gamut = table(3, 1, GAMUT_GRID, gamut); - let mut p = ColorProfile::default(); - p.profile_class = ProfileClass::OutputDevice; - p.color_space = DataColorSpace::Cmyk; - p.pcs = DataColorSpace::Lab; - p.rendering_intent = RenderingIntent::RelativeColorimetric; - p.white_point = moxcms::WHITE_POINT_D50.to_xyzd(); - p.media_white_point = Some(moxcms::Xyzd::new(f64::from(paper[0]), f64::from(paper[1]), f64::from(paper[2]))); - p.lut_a_to_b_perceptual = Some(a2b.clone()); - p.lut_a_to_b_saturation = Some(a2b.clone()); - p.lut_a_to_b_colorimetric = Some(a2b); - p.lut_b_to_a_perceptual = Some(b2a_mapped.clone()); - p.lut_b_to_a_saturation = Some(b2a_mapped); - p.lut_b_to_a_colorimetric = Some(b2a); - p.gamut = Some(gamut); + let a2b = table(4, 3, A2B_GRID, a2b_clut); + let b2a_mapped = table(3, 4, B2A_GRID, b2a_mapped_clut); + let b2a = table(3, 4, B2A_GRID, b2a_clut); + let _gamut = table(3, 1, GAMUT_GRID, gamut_clut); + let mut p = Profile::gray([f64::from(paper[0]), f64::from(paper[1]), f64::from(paper[2])], Curve::Gamma(1.0)) + .unwrap_or_else(|_| Builtin::Srgb.profile().clone()); + p.class = ProfileClass::Output; + p.color_space = ColorSpace::Cmyk; + p.pcs = Pcs::Lab; + p.rendering_intent = CmsIntent::RelativeColorimetric; + p.white_point = [f64::from(paper[0]), f64::from(paper[1]), f64::from(paper[2])]; + p.matrix = None; + p.trc = None; + p.gray_trc = None; + p.a2b = [Some(a2b.clone()), Some(a2b.clone()), Some(a2b)]; + p.b2a = [Some(b2a_mapped.clone()), Some(b2a), Some(b2a_mapped)]; labelled(p, name) } /// The grey space of greyscale exports: sRGB's tone curve, D50 white. -pub(super) fn gray_profile(name: &str) -> ColorProfile { - let mut p = ColorProfile::new_gray_with_gamma(2.2); - p.gray_trc = ColorProfile::new_srgb().red_trc; - labelled(p, name) +pub(super) fn gray_profile(name: &str) -> Profile { + labelled(Builtin::SGray.profile().clone(), name) } /// The first tag signature the tag table of ICC `bytes` lists twice, which the ICC -/// specification forbids. moxcms parses every entry of the table, so a profile listing one -/// description, copyright or table tag thousands of times, each pointing at the same large data, -/// would decode and copy that data once per entry. A table it can't read is left to moxcms. +/// specification forbids. pub(crate) fn repeated_tag(bytes: &[u8]) -> Option { let be32 = |at: usize| bytes.get(at..at.checked_add(4)?).map(|v| u32::from_be_bytes([v[0], v[1], v[2], v[3]])); let tags = be32(128)? as usize; @@ -551,9 +337,7 @@ pub(crate) fn repeated_tag(bytes: &[u8]) -> Option { const MAX_LOCALIZED_TEXT: usize = 1 << 20; /// Whether the localized-name records of the `mluc` tags in ICC `bytes` take at most -/// [`MAX_LOCALIZED_TEXT`] together. moxcms copies each record into a string of its own, and records -/// may all point at the same bytes, so a profile under a megabyte could make it allocate -/// gigabytes. A table it can't read is left to moxcms to refuse. +/// [`MAX_LOCALIZED_TEXT`] together. pub(crate) fn localized_text_fits(bytes: &[u8]) -> bool { let be32 = |b: &[u8], at: usize| b.get(at..at.checked_add(4)?).map(|v| u32::from_be_bytes([v[0], v[1], v[2], v[3]]) as usize); let Some(tags) = be32(bytes, 128) else { return true }; @@ -567,10 +351,7 @@ pub(crate) fn localized_text_fits(bytes: &[u8]) -> bool { } let records = be32(tag, 8).unwrap_or(0); for r in 0..records { - // Each record's header: language, country, length, offset. let Some(length) = r.checked_mul(12).and_then(|h| be32(tag, h + 16 + 4)) else { break }; - // Each record counts its 12-byte header too: records of length 0 are not free, so - // many tags pointing at one `mluc` can't make this loop quadratic. total = total.saturating_add(length).saturating_add(12); if total > MAX_LOCALIZED_TEXT { return false; From 2ef4fe36b408ef77703036b9c864de250fcd35a0 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 19 Nov 2026 05:27:20 +0700 Subject: [PATCH 03/13] color: format the craft-cms import in cms/icc.rs --- crates/color/src/cms/icc.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/color/src/cms/icc.rs b/crates/color/src/cms/icc.rs index 4eea3a2b25..a3b87f2fc6 100644 --- a/crates/color/src/cms/icc.rs +++ b/crates/color/src/cms/icc.rs @@ -5,8 +5,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, OnceLock}; use craft_cms::{ - Builtin, Clut, ColorSpace, Curve, Intent as CmsIntent, Pcs, Profile, ProfileClass, Transform, - builtin, + Builtin, Clut, ColorSpace, Curve, Intent as CmsIntent, Pcs, Profile, ProfileClass, Transform, builtin, pipeline::Stage, profile::{Lut, LutKind}, }; From 8a84e0edcdb41da52c03b82bd0dd7ae502809001 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 19 Nov 2026 05:34:52 +0700 Subject: [PATCH 04/13] Revert "Merge pull request #8616 from storytold/fix/fmt-icc" This reverts commit 760c91f9fe39afc4fa8d73465e09a7d3eb04b6b3, reversing changes made to 4d73308977008e3e6a4aa50d46a0783976770364. --- crates/color/src/cms/icc.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/color/src/cms/icc.rs b/crates/color/src/cms/icc.rs index a3b87f2fc6..4eea3a2b25 100644 --- a/crates/color/src/cms/icc.rs +++ b/crates/color/src/cms/icc.rs @@ -5,7 +5,8 @@ use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, OnceLock}; use craft_cms::{ - Builtin, Clut, ColorSpace, Curve, Intent as CmsIntent, Pcs, Profile, ProfileClass, Transform, builtin, + Builtin, Clut, ColorSpace, Curve, Intent as CmsIntent, Pcs, Profile, ProfileClass, Transform, + builtin, pipeline::Stage, profile::{Lut, LutKind}, }; From 57ac9a7ff2b9d2bfa85ec10b94aa0ca31736e8c4 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 19 Nov 2026 05:34:52 +0700 Subject: [PATCH 05/13] Revert "color: cut over cms/icc.rs to craft-cms (#8612)" This reverts commit 4d73308977008e3e6a4aa50d46a0783976770364. --- Cargo.lock | 11 +- Cargo.toml | 1 - crates/color/Cargo.toml | 2 +- crates/color/src/cms/icc.rs | 421 +++++++++++++++++++++++++++--------- 4 files changed, 322 insertions(+), 113 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2a431e3339..0d32cc52e4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1009,15 +1009,6 @@ dependencies = [ "ruzstd", ] -[[package]] -name = "craft-cms" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890" -dependencies = [ - "md-5", - "rayon", -] - [[package]] name = "craft-codepage" version = "0.1.0" @@ -6736,8 +6727,8 @@ dependencies = [ name = "vectorcraft-color" version = "0.24.1" dependencies = [ - "craft-cms", "kurbo 0.13.1", + "moxcms", "proptest", "serde", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index f8e8dc95a3..6d2ab9e37b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,7 +12,6 @@ repository = "https://github.com/storytold/vectorcraft" [workspace.dependencies] craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", default-features = false, features = ["interpret", "write"] } -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "010702ee9b030844c852939095b1da0d0656a890" } craft-print = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", features = ["serde"] } diff --git a/crates/color/Cargo.toml b/crates/color/Cargo.toml index 9c1e7b522c..a007ede39f 100644 --- a/crates/color/Cargo.toml +++ b/crates/color/Cargo.toml @@ -9,11 +9,11 @@ description = "VectorCraft color" workspace = true [dependencies] -craft-cms = { workspace = true } kurbo = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } +moxcms = "0.8" [dev-dependencies] proptest = { workspace = true } diff --git a/crates/color/src/cms/icc.rs b/crates/color/src/cms/icc.rs index 4eea3a2b25..8fc287ae23 100644 --- a/crates/color/src/cms/icc.rs +++ b/crates/color/src/cms/icc.rs @@ -1,24 +1,22 @@ -//! ICC profiles through `craft-cms` (pure Rust): built-in RGB spaces and user-supplied `.icc` -//! files, and the profiles exports embed ([`builtin_rgb_bytes`], [`cmyk_profile`], [`gray_profile`]). +//! ICC profiles through `moxcms` (pure Rust): built-in RGB spaces and user-supplied `.icc` files, +//! and the profiles exports embed ([`encode_builtin`]), written in code from the CMS. use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, OnceLock}; -use craft_cms::{ - Builtin, Clut, ColorSpace, Curve, Intent as CmsIntent, Pcs, Profile, ProfileClass, Transform, - builtin, - pipeline::Stage, - profile::{Lut, LutKind}, +use moxcms::{ + ColorProfile, DataColorSpace, Layout, LocalizableString, LutMultidimensionalType, LutStore, LutWarehouse, Matrix3d, ProfileClass, ProfileText, + RenderingIntent, ToneReprCurve, TransformF32Executor, TransformOptions, Vector3d, }; use super::{CmsError, Intent, ProfileKind, lab, profiles_generation}; -fn cms_intent(i: Intent) -> CmsIntent { +fn moxcms_intent(i: Intent) -> RenderingIntent { match i { - Intent::Perceptual => CmsIntent::Perceptual, - Intent::RelativeColorimetric => CmsIntent::RelativeColorimetric, - Intent::Saturation => CmsIntent::Saturation, - Intent::AbsoluteColorimetric => CmsIntent::AbsoluteColorimetric, + Intent::Perceptual => RenderingIntent::Perceptual, + Intent::RelativeColorimetric => RenderingIntent::RelativeColorimetric, + Intent::Saturation => RenderingIntent::Saturation, + Intent::AbsoluteColorimetric => RenderingIntent::AbsoluteColorimetric, } } @@ -28,12 +26,25 @@ fn intent_index(i: Intent) -> usize { INTENTS.iter().position(|x| *x == i).unwrap_or(1) } -type Xf = Option>; +type Xf = Option>; /// A direct transform's cache key: destination [`IccProfile::id`], [`profiles_generation`] it was -/// built in, intent index, black-point compensation. +/// built in, intent index, black-point compensation. The id tells a reloaded profile from the old +/// one of the same name, which settings built before the reload still convert into; the +/// generation only lets the cache drop what reloads left behind. type DirectKey = (u64, u64, usize, bool); +/// The transforms of [`IccProfile::to_same_model_of`]: into ProPhoto RGB's primaries with linear +/// tone curves, where black-point compensation is a linear remap, and from there into the +/// destination. +struct SameModel { + into: Arc, + out_of: Arc, + /// The source's and the destination's black as luminance in the linear space (both 0 without + /// compensation). + black: [f32; 2], +} + /// A parsed ICC profile plus lazily-built transforms to/from sRGB. pub struct IccProfile { pub name: String, @@ -42,13 +53,28 @@ pub struct IccProfile { pub kind: ProfileKind, /// The file it was loaded from (empty for profiles made in code). source: Vec, - profile: Profile, - srgb: Profile, + profile: ColorProfile, + srgb: ColorProfile, to_srgb: [OnceLock; 4], from_srgb: [OnceLock; 4], - /// Direct transforms into other profiles ([`Self::to_rgb_of`], [`Self::to_same_model_of`]), - /// by destination, intent and black-point compensation. - direct: Mutex>, + /// Direct transforms into other RGB profiles ([`Self::to_rgb_of`]), by destination, intent + /// and black-point compensation. + direct: Mutex>)>>, + /// Transforms into other profiles of the same model ([`Self::to_same_model_of`]), keyed as + /// [`Self::direct`] is. + same_model: Mutex>)>>, +} + +/// A transform from one profile into an RGB profile without passing through sRGB: into the +/// destination's primaries with linear tone curves, where black-point compensation is a linear +/// remap, then onto its own curves. +struct Direct { + to_linear: Arc, + /// Linear → the destination's curves; `None` when the destination isn't a matrix profile + /// (the first transform goes straight into it, without compensation). + to_dest: Option>, + /// The source black's luminance in the linear destination (0: no compensation). + black: f32, } impl std::fmt::Debug for IccProfile { @@ -57,16 +83,25 @@ impl std::fmt::Debug for IccProfile { } } +fn text(t: &Option) -> Option { + 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() }), + } + .map(|s| s.trim_matches(char::from(0)).trim().to_string()) + .filter(|s| !s.is_empty()) +} + impl IccProfile { - pub fn from_profile(name: Option, profile: Profile) -> Result { + pub fn from_profile(name: Option, profile: ColorProfile) -> Result { let kind = match profile.color_space { - ColorSpace::Rgb => ProfileKind::Rgb, - ColorSpace::Cmyk => ProfileKind::Cmyk, - ColorSpace::Gray => ProfileKind::Gray, + DataColorSpace::Rgb => ProfileKind::Rgb, + DataColorSpace::Cmyk => ProfileKind::Cmyk, + DataColorSpace::Gray => ProfileKind::Gray, other => return Err(CmsError::Unsupported(format!("profile colour space {other:?} is not RGB, CMYK or Gray"))), }; - 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")); + let name = name.or_else(|| text(&profile.description)).unwrap_or_else(|| format!("Untitled {kind:?} profile")); static NEXT_ID: AtomicU64 = AtomicU64::new(0); Ok(Self { name, @@ -74,10 +109,11 @@ impl IccProfile { kind, source: Vec::new(), profile, - srgb: builtin::srgb().clone(), + srgb: ColorProfile::new_srgb(), to_srgb: Default::default(), from_srgb: Default::default(), direct: Mutex::new(Vec::new()), + same_model: Mutex::new(Vec::new()), }) } @@ -91,7 +127,7 @@ impl IccProfile { String::from_utf8_lossy(&tag.to_be_bytes()) ))); } - let p = Profile::parse(bytes).map_err(|e| CmsError::BadProfile(format!("{e:?}")))?; + let p = ColorProfile::new_from_slice(bytes).map_err(|e| CmsError::BadProfile(format!("{e:?}")))?; Ok(Self { source: bytes.to_vec(), ..Self::from_profile(name, p)? }) } @@ -100,6 +136,14 @@ impl IccProfile { if self.source.is_empty() { encode(&self.profile) } else { Ok(self.source.clone()) } } + fn layout(&self) -> Layout { + match self.kind { + ProfileKind::Cmyk => Layout::Rgba, // 4 channels + ProfileKind::Gray => Layout::Gray, + ProfileKind::Rgb => Layout::Rgb, + } + } + fn channels(&self) -> usize { match self.kind { ProfileKind::Cmyk => 4, @@ -108,15 +152,19 @@ impl IccProfile { } } + fn opts(intent: Intent) -> TransformOptions { + TransformOptions { rendering_intent: moxcms_intent(intent), ..Default::default() } + } + fn to_xf(&self, intent: Intent) -> Xf { self.to_srgb[intent_index(intent)] - .get_or_init(|| Transform::new(&self.profile, &self.srgb, cms_intent(intent), false).ok().map(Arc::new)) + .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) -> Xf { self.from_srgb[intent_index(intent)] - .get_or_init(|| Transform::new(&self.srgb, &self.profile, cms_intent(intent), false).ok().map(Arc::new)) + .get_or_init(|| self.srgb.create_transform_f32(Layout::Rgb, &self.profile, self.layout(), Self::opts(intent)).ok()) .clone() } @@ -135,7 +183,7 @@ impl IccProfile { } let xf = self.to_xf(intent)?; let mut dst = [0.0f32; 3]; - xf.eval_fast(v, &mut dst).ok()?; + xf.transform(v, &mut dst).ok()?; Some(dst.map(|x| x.clamp(0.0, 1.0))) } @@ -149,7 +197,7 @@ impl IccProfile { return None; } let xf = self.to_xf(intent)?; - xf.convert_f32(v, n, dst, 3, false).ok()?; + xf.transform(v, dst).ok()?; dst.iter_mut().for_each(|x| *x = x.clamp(0.0, 1.0)); Some(()) } @@ -158,53 +206,142 @@ impl IccProfile { pub fn from_srgb(&self, rgb: [f32; 3], intent: Intent) -> Option> { let xf = self.inverse_xf(intent)?; let mut dst = vec![0.0f32; self.channels()]; - xf.eval_fast(&rgb, &mut dst).ok()?; + xf.transform(&rgb, &mut dst).ok()?; Some(dst.into_iter().map(|x| x.clamp(0.0, 1.0)).collect()) } - fn direct_xf(&self, dest: &IccProfile, intent: Intent, bpc: bool) -> Xf { - let generation = profiles_generation(); - let key = (dest.id, generation, intent_index(intent), bpc); - let mut cache = self.direct.lock().unwrap_or_else(|e| e.into_inner()); - cache.retain(|(k, _)| k.1 == generation); - if let Some((_, t)) = cache.iter().find(|(k, _)| *k == key) { - return t.clone(); - } - let t = Transform::new(&self.profile, &dest.profile, cms_intent(intent), bpc).ok().map(Arc::new); - cache.push((key, t.clone())); - t - } - /// Device values (RGB / CMYK / Gray, 0..1) → `dest`'s RGB, converted directly with `intent`: /// not through sRGB, so colours outside sRGB keep their place in a wider space. With `bpc` /// (and an intent other than absolute), this profile's black maps onto the destination's - /// black (black-point compensation). `None` when `dest` isn't RGB or no transform can be built. + /// black (black-point compensation, the darkest ink the profile prints becoming RGB 0 rather + /// than a dark grey). `None` when `dest` isn't RGB or no transform can be built. pub fn to_rgb_of(&self, dest: &IccProfile, v: &[f32], intent: Intent, bpc: bool) -> Option<[f32; 3]> { - if dest.kind != ProfileKind::Rgb { - return None; - } - let xf = self.direct_xf(dest, intent, bpc && intent != Intent::AbsoluteColorimetric)?; + let t = self.direct_xf(dest, intent, bpc && intent != Intent::AbsoluteColorimetric)?; let mut src = v.to_vec(); src.resize(self.channels(), 0.0); + let mut lin = [0.0f32; 3]; + t.to_linear.transform(&src, &mut lin).ok()?; + let Some(to_dest) = &t.to_dest else { return Some(lin.map(|x| x.clamp(0.0, 1.0))) }; + if t.black > 0.0 { + lin = lin.map(|x| (x - t.black) / (1.0 - t.black)); + } + let lin = lin.map(|x| x.clamp(0.0, 1.0)); let mut out = [0.0f32; 3]; - xf.eval_fast(&src, &mut out).ok()?; + to_dest.transform(&lin, &mut out).ok()?; Some(out.map(|x| x.clamp(0.0, 1.0))) } + fn direct_xf(&self, dest: &IccProfile, intent: Intent, bpc: bool) -> Option> { + if dest.kind != ProfileKind::Rgb { + return None; + } + let generation = profiles_generation(); + let key = (dest.id, generation, intent_index(intent), bpc); + let mut cache = self.direct.lock().unwrap_or_else(|e| e.into_inner()); + // an older generation's entries can't match again: drop them so reloads don't pile up + cache.retain(|(k, _)| k.1 == generation); + if let Some((_, t)) = cache.iter().find(|(k, _)| *k == key) { + return t.clone(); + } + let t = self.build_direct(dest, intent, bpc).map(Arc::new); + cache.push((key, t.clone())); + t + } + + fn build_direct(&self, dest: &IccProfile, intent: Intent, bpc: bool) -> Option { + let d = &dest.profile; + let matrix = d.red_trc.is_some() && d.green_trc.is_some() && d.blue_trc.is_some(); + if !matrix { + let xf = self.profile.create_transform_f32(self.layout(), d, Layout::Rgb, Self::opts(intent)).ok()?; + return Some(Direct { to_linear: xf, to_dest: None, black: 0.0 }); + } + let mut linear = d.clone(); + for trc in [&mut linear.red_trc, &mut linear.green_trc, &mut linear.blue_trc] { + *trc = Some(ToneReprCurve::Parametric(vec![1.0])); + } + // A coding-independent code point names the transfer curve outright (moxcms's sRGB has + // one) and would override the linear curves. + linear.cicp = None; + let to_linear = self.profile.create_transform_f32(self.layout(), &linear, Layout::Rgb, Self::opts(intent)).ok()?; + let to_dest = linear.create_transform_f32(Layout::Rgb, d, Layout::Rgb, Self::opts(Intent::RelativeColorimetric)).ok()?; + // The source black: the darkest colour the profile reproduces, found as lcms does for an + // output profile (black sent into the profile and read back), made neutral. + let black = if bpc && self.kind == ProfileKind::Cmyk { + let inks = self.from_srgb([0.0; 3], Intent::RelativeColorimetric)?; + let mut lin = [0.0f32; 3]; + to_linear.transform(&inks, &mut lin).ok()?; + let y = |c: &moxcms::Xyzd| c.y as f32; + let lum = lin[0] * y(&d.red_colorant) + lin[1] * y(&d.green_colorant) + lin[2] * y(&d.blue_colorant); + lum.clamp(0.0, 0.5) + } else { + 0.0 + }; + Some(Direct { to_linear, to_dest: Some(to_dest), black }) + } + /// Device values of this profile → device values of `dest`, a profile of the same model, - /// converted with `intent` directly. With `bpc` (and an intent other than absolute), this - /// profile's black maps onto the destination's black. `None` when `dest` is of another model or - /// no transform can be built. + /// converted with `intent` through ProPhoto RGB rather than sRGB, so colours outside sRGB + /// keep their place. With `bpc` (and an intent other than absolute), this profile's black + /// maps onto the destination's black (black-point compensation). `None` when `dest` is of + /// another model or no transform can be built. pub fn to_same_model_of(&self, dest: &IccProfile, v: &[f32], intent: Intent, bpc: bool) -> Option> { if dest.kind != self.kind || v.len() != self.channels() { return None; } - let xf = self.direct_xf(dest, intent, bpc && intent != Intent::AbsoluteColorimetric)?; + let bpc = bpc && intent != Intent::AbsoluteColorimetric; + let generation = profiles_generation(); + let key = (dest.id, generation, intent_index(intent), bpc); + let t = { + let mut cache = self.same_model.lock().unwrap_or_else(|e| e.into_inner()); + cache.retain(|(k, _)| k.1 == generation); + match cache.iter().find(|(k, _)| *k == key) { + Some((_, t)) => t.clone(), + None => { + let t = self.build_same_model(dest, intent, bpc).map(Arc::new); + cache.push((key, t.clone())); + t + } + } + }?; + let mut lin = [0.0f32; 3]; + t.into.transform(v, &mut lin).ok()?; + let [from, to] = t.black; + if from > 0.0 || to > 0.0 { + lin = lin.map(|x| to + (x - from) * (1.0 - to) / (1.0 - from)); + } + let lin = lin.map(|x| x.clamp(0.0, 1.0)); let mut out = vec![0.0f32; dest.channels()]; - xf.eval_fast(v, &mut out).ok()?; + t.out_of.transform(&lin, &mut out).ok()?; Some(out.into_iter().map(|x| x.clamp(0.0, 1.0)).collect()) } + fn build_same_model(&self, dest: &IccProfile, intent: Intent, bpc: bool) -> Option { + let mut linear = rgb_space(super::PROPHOTO_RGB)?; + for trc in [&mut linear.red_trc, &mut linear.green_trc, &mut linear.blue_trc] { + *trc = Some(ToneReprCurve::Parametric(vec![1.0])); + } + linear.cicp = None; + let into = self.profile.create_transform_f32(self.layout(), &linear, Layout::Rgb, Self::opts(intent)).ok()?; + let out_of = linear.create_transform_f32(Layout::Rgb, &dest.profile, dest.layout(), Self::opts(intent)).ok()?; + let black = if bpc { + // Each profile's black: the darkest colour it reproduces, found as `build_direct` + // finds it, as luminance in the linear space. + let luminance = |p: &IccProfile, xf: &Arc| -> Option { + let inks = p.from_srgb([0.0; 3], Intent::RelativeColorimetric)?; + let mut lin = [0.0f32; 3]; + xf.transform(&inks, &mut lin).ok()?; + let y = |c: &moxcms::Xyzd| c.y as f32; + let lum = lin[0] * y(&linear.red_colorant) + lin[1] * y(&linear.green_colorant) + lin[2] * y(&linear.blue_colorant); + Some(lum.clamp(0.0, 0.5)) + }; + let back = dest.profile.create_transform_f32(dest.layout(), &linear, Layout::Rgb, Self::opts(intent)).ok()?; + [luminance(self, &into)?, luminance(dest, &back)?] + } else { + [0.0; 2] + }; + Some(SameModel { into, out_of, black }) + } + /// 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() @@ -212,17 +349,17 @@ impl IccProfile { } /// The primaries and tone curves of built-in RGB space `name`. -fn rgb_space(name: &str) -> Option { +fn rgb_space(name: &str) -> Option { Some(match name { - super::WIDE_GAMUT_RGB => Builtin::AdobeRgbCompat.profile().clone(), - super::DISPLAY_P3 => Builtin::DisplayP3.profile().clone(), - super::PROPHOTO_RGB => Builtin::ProPhotoCompat.profile().clone(), - super::SRGB => Builtin::Srgb.profile().clone(), + super::WIDE_GAMUT_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(), _ => return None, }) } -/// Built-in RGB working spaces from `craft-cms`'s standard primaries. +/// Built-in RGB working spaces from `moxcms`'s standard primaries. pub fn builtin_rgb(name: &str) -> Option { IccProfile::from_profile(Some(name.to_string()), rgb_space(name)?).ok() } @@ -233,8 +370,8 @@ pub(super) fn builtin_rgb_bytes(name: &str) -> Result, CmsError> { } /// Encode `p` as an ICC file. The creation date is fixed so exports are reproducible. -pub(super) fn encode(p: &Profile) -> Result, CmsError> { - let mut bytes = p.to_bytes().as_ref().clone(); +pub(super) fn encode(p: &ColorProfile) -> Result, CmsError> { + let mut bytes = aligned(p.encode().map_err(|e| CmsError::BadProfile(format!("{e:?}")))?); // Header bytes 24..36: year, month, day, hours, minutes, seconds (u16 each). if let Some(date) = bytes.get_mut(24..36) { date.copy_from_slice(&[2026u16, 1, 1, 0, 0, 0].map(u16::to_be_bytes).concat()); @@ -242,10 +379,63 @@ pub(super) fn encode(p: &Profile) -> Result, CmsError> { Ok(bytes) } +/// `icc` with every tagged element starting on a 4-byte boundary, padded with zeros, as ICC.1 +/// §7.1.2 requires (moxcms packs them, so a 62-byte `desc` left the next tag unaligned, #1584). +/// Tags that share data keep sharing it. A profile whose tag table doesn't read is returned as it is. +fn aligned(icc: Vec) -> Vec { + const TABLE: usize = 128; + let be = |b: &[u8], at: usize| b.get(at..at + 4).map(|v| u32::from_be_bytes([v[0], v[1], v[2], v[3]]) as usize); + let Some(n) = be(&icc, TABLE).filter(|n| *n <= 1000) else { return icc }; + let data_start = TABLE + 4 + 12 * n; + let mut entries = Vec::with_capacity(n); + for i in 0..n { + let e = TABLE + 4 + 12 * i; + let (Some(off), Some(size)) = (be(&icc, e + 4), be(&icc, e + 8)) else { return icc }; + if off < data_start || off.checked_add(size).is_none_or(|end| end > icc.len()) { + return icc; + } + entries.push((off, size)); + } + if entries.iter().all(|(off, _)| off.is_multiple_of(4)) && icc.len().is_multiple_of(4) { + return icc; + } + let mut out = icc.get(..data_start).map(<[u8]>::to_vec).unwrap_or_default(); + let mut moved: Vec<((usize, usize), usize)> = Vec::new(); + let mut order: Vec = (0..n).collect(); + order.sort_by_key(|&i| entries[i].0); + for i in order { + let (off, size) = entries[i]; + let at = match moved.iter().find(|(k, _)| *k == (off, size)) { + Some((_, at)) => *at, + None => { + out.resize(out.len().next_multiple_of(4), 0); + let at = out.len(); + out.extend_from_slice(&icc[off..off + size]); + moved.push(((off, size), at)); + at + } + }; + let e = TABLE + 4 + 12 * i + 4; + out[e..e + 4].copy_from_slice(&(at as u32).to_be_bytes()); + } + out.resize(out.len().next_multiple_of(4), 0); + let len = out.len() as u32; + out[0..4].copy_from_slice(&len.to_be_bytes()); + // The profile ID (an MD5 of the old bytes) no longer matches: zero is "not computed". + if let Some(id) = out.get_mut(84..100) { + id.fill(0); + } + out +} + +fn text_tag(s: &str) -> Option { + Some(ProfileText::Localizable(vec![LocalizableString::new("en".into(), "US".into(), s.into())])) +} + /// Profiles made here carry their name and no copyright claim. -fn labelled(mut p: Profile, name: &str) -> Profile { - p.description = name.to_string(); - p.copyright = "No copyright, use freely".to_string(); +fn labelled(mut p: ColorProfile, name: &str) -> ColorProfile { + p.description = text_tag(name); + p.copyright = text_tag("No copyright, use freely"); p } @@ -259,67 +449,91 @@ const GAMUT_GRID: usize = 9; /// 9⁴ table, and Lab → CMYK in 17³ tables, Lab PCS (ICC v4 encoding): `mapped` (gamut-mapped, /// with black-point compensation) for the perceptual and saturation intents, `colorimetric` (the /// colorimetric inverse of `to_lab`) for the colorimetric intents and the gamut tag. +/// It carries every tag ICC.1 requires of an output profile: the tables for all three intents +/// and the gamut tag (Windows rejects a CMYK profile without them, so Photos couldn't show a CMYK +/// TIFF that embedded one, #2707). The media white point is `paper` (absolute XYZ, D50), which +/// the ICC-absolute colorimetric intent reproduces. pub(super) fn cmyk_profile( name: &str, paper: [f32; 3], to_lab: impl Fn([f32; 4]) -> lab::Lab, mapped: impl Fn(lab::Lab) -> [f32; 4], colorimetric: impl Fn(lab::Lab) -> [f32; 4], -) -> Profile { +) -> ColorProfile { let unit = |i: usize, n: usize| i as f32 / (n - 1) as f32; - let mut a2b_clut = Vec::with_capacity(A2B_GRID.pow(4) * 3); + let q = |v: f32| (v.clamp(0.0, 1.0) * 65535.0).round() as u16; + let mut a2b = Vec::with_capacity(A2B_GRID.pow(4) * 3); for i in 0..A2B_GRID.pow(4) { let cmyk = [3, 2, 1, 0].map(|d| unit(i / A2B_GRID.pow(d) % A2B_GRID, A2B_GRID)); let l = to_lab(cmyk); - a2b_clut.extend([l.l / 100.0, (l.a + 128.0) / 255.0, (l.b + 128.0) / 255.0]); + a2b.extend([l.l / 100.0, (l.a + 128.0) / 255.0, (l.b + 128.0) / 255.0].map(q)); } let b2a_of = |from_lab: &dyn Fn(lab::Lab) -> [f32; 4]| { - let mut clut = Vec::with_capacity(B2A_GRID.pow(3) * 4); + let mut b2a = Vec::with_capacity(B2A_GRID.pow(3) * 4); for i in 0..B2A_GRID.pow(3) { let [l, a, b] = [2, 1, 0].map(|d| unit(i / B2A_GRID.pow(d) % B2A_GRID, B2A_GRID)); - clut.extend(from_lab(lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0))); + b2a.extend(from_lab(lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0)).map(q)); } - clut + b2a }; - let (b2a_mapped_clut, b2a_clut) = (b2a_of(&mapped), b2a_of(&colorimetric)); - let mut gamut_clut = Vec::with_capacity(GAMUT_GRID.pow(3)); + let (b2a_mapped, b2a) = (b2a_of(&mapped), b2a_of(&colorimetric)); + // Gamut: 0 where a colour separates and comes back within a ΔE of 3, else out of gamut. + let mut gamut = Vec::with_capacity(GAMUT_GRID.pow(3)); for i in 0..GAMUT_GRID.pow(3) { let [l, a, b] = [2, 1, 0].map(|d| unit(i / GAMUT_GRID.pow(d) % GAMUT_GRID, GAMUT_GRID)); let want = lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0); - gamut_clut.push(if lab::delta_e2000(want, to_lab(colorimetric(want))) <= 3.0 { 0.0 } else { 1.0 }); + gamut.push(if lab::delta_e2000(want, to_lab(colorimetric(want))) <= 3.0 { 0 } else { u16::MAX }); } - let table = |inputs: usize, outputs: usize, grid: usize, clut: Vec| Lut { - kind: LutKind::Ab, - inputs, - outputs, - stages: vec![Stage::Clut(Clut::new(vec![grid; inputs], outputs, clut).expect("valid CLUT dimensions"))], + let identity = |n: usize| vec![ToneReprCurve::Parametric(vec![1.0]); n]; + let table = |inputs: usize, outputs: usize, grid: usize, clut: Vec| { + let mut grid_points = [0u8; 16]; + grid_points[..inputs].fill(grid as u8); + LutWarehouse::Multidimensional(LutMultidimensionalType { + num_input_channels: inputs as u8, + num_output_channels: outputs as u8, + grid_points, + clut: Some(LutStore::Store16(clut)), + // A curves sit on the device side (the gamut tag's is its one output), B curves on the + // PCS side. + a_curves: identity(inputs + outputs - 3), + b_curves: identity(3), + m_curves: vec![], + matrix: Matrix3d::IDENTITY, + bias: Vector3d::default(), + }) }; - let a2b = table(4, 3, A2B_GRID, a2b_clut); - let b2a_mapped = table(3, 4, B2A_GRID, b2a_mapped_clut); - let b2a = table(3, 4, B2A_GRID, b2a_clut); - let _gamut = table(3, 1, GAMUT_GRID, gamut_clut); - let mut p = Profile::gray([f64::from(paper[0]), f64::from(paper[1]), f64::from(paper[2])], Curve::Gamma(1.0)) - .unwrap_or_else(|_| Builtin::Srgb.profile().clone()); - p.class = ProfileClass::Output; - p.color_space = ColorSpace::Cmyk; - p.pcs = Pcs::Lab; - p.rendering_intent = CmsIntent::RelativeColorimetric; - p.white_point = [f64::from(paper[0]), f64::from(paper[1]), f64::from(paper[2])]; - p.matrix = None; - p.trc = None; - p.gray_trc = None; - p.a2b = [Some(a2b.clone()), Some(a2b.clone()), Some(a2b)]; - p.b2a = [Some(b2a_mapped.clone()), Some(b2a), Some(b2a_mapped)]; + let a2b = table(4, 3, A2B_GRID, a2b); + let b2a_mapped = table(3, 4, B2A_GRID, b2a_mapped); + let b2a = table(3, 4, B2A_GRID, b2a); + let gamut = table(3, 1, GAMUT_GRID, gamut); + let mut p = ColorProfile::default(); + p.profile_class = ProfileClass::OutputDevice; + p.color_space = DataColorSpace::Cmyk; + p.pcs = DataColorSpace::Lab; + p.rendering_intent = RenderingIntent::RelativeColorimetric; + p.white_point = moxcms::WHITE_POINT_D50.to_xyzd(); + p.media_white_point = Some(moxcms::Xyzd::new(f64::from(paper[0]), f64::from(paper[1]), f64::from(paper[2]))); + p.lut_a_to_b_perceptual = Some(a2b.clone()); + p.lut_a_to_b_saturation = Some(a2b.clone()); + p.lut_a_to_b_colorimetric = Some(a2b); + p.lut_b_to_a_perceptual = Some(b2a_mapped.clone()); + p.lut_b_to_a_saturation = Some(b2a_mapped); + p.lut_b_to_a_colorimetric = Some(b2a); + p.gamut = Some(gamut); labelled(p, name) } /// The grey space of greyscale exports: sRGB's tone curve, D50 white. -pub(super) fn gray_profile(name: &str) -> Profile { - labelled(Builtin::SGray.profile().clone(), name) +pub(super) fn gray_profile(name: &str) -> ColorProfile { + let mut p = ColorProfile::new_gray_with_gamma(2.2); + p.gray_trc = ColorProfile::new_srgb().red_trc; + labelled(p, name) } /// The first tag signature the tag table of ICC `bytes` lists twice, which the ICC -/// specification forbids. +/// specification forbids. moxcms parses every entry of the table, so a profile listing one +/// description, copyright or table tag thousands of times, each pointing at the same large data, +/// would decode and copy that data once per entry. A table it can't read is left to moxcms. pub(crate) fn repeated_tag(bytes: &[u8]) -> Option { let be32 = |at: usize| bytes.get(at..at.checked_add(4)?).map(|v| u32::from_be_bytes([v[0], v[1], v[2], v[3]])); let tags = be32(128)? as usize; @@ -337,7 +551,9 @@ pub(crate) fn repeated_tag(bytes: &[u8]) -> Option { const MAX_LOCALIZED_TEXT: usize = 1 << 20; /// Whether the localized-name records of the `mluc` tags in ICC `bytes` take at most -/// [`MAX_LOCALIZED_TEXT`] together. +/// [`MAX_LOCALIZED_TEXT`] together. moxcms copies each record into a string of its own, and records +/// may all point at the same bytes, so a profile under a megabyte could make it allocate +/// gigabytes. A table it can't read is left to moxcms to refuse. pub(crate) fn localized_text_fits(bytes: &[u8]) -> bool { let be32 = |b: &[u8], at: usize| b.get(at..at.checked_add(4)?).map(|v| u32::from_be_bytes([v[0], v[1], v[2], v[3]]) as usize); let Some(tags) = be32(bytes, 128) else { return true }; @@ -351,7 +567,10 @@ pub(crate) fn localized_text_fits(bytes: &[u8]) -> bool { } let records = be32(tag, 8).unwrap_or(0); for r in 0..records { + // Each record's header: language, country, length, offset. let Some(length) = r.checked_mul(12).and_then(|h| be32(tag, h + 16 + 4)) else { break }; + // Each record counts its 12-byte header too: records of length 0 are not free, so + // many tags pointing at one `mluc` can't make this loop quadratic. total = total.saturating_add(length).saturating_add(12); if total > MAX_LOCALIZED_TEXT { return false; From d2bed0bdb81a9f94d46e14bce1e0fb4b99bab2a0 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 19:08:45 -0500 Subject: [PATCH 06/13] cutover: use craft_plotter::hpgl::write (#8626) --- Cargo.lock | 3 +- Cargo.toml | 2 +- crates/cad/src/hpgl/write.rs | 63 ++++++------------------------------ 3 files changed, 12 insertions(+), 56 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0d32cc52e4..d635613a96 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1204,8 +1204,9 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57#a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57" +source = "git+https://github.com/storytold/craft-libs?rev=e7873217287876f76a045550369c90a541693c33#e7873217287876f76a045550369c90a541693c33" dependencies = [ + "kurbo 0.13.1", "thiserror 2.0.21", ] diff --git a/Cargo.toml b/Cargo.toml index 6d2ab9e37b..184df0f647 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,7 +32,7 @@ craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "64b181977 # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "e7873217287876f76a045550369c90a541693c33" } craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } # WMF, EMF and EMF+ reader (craft-libs#778). craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } diff --git a/crates/cad/src/hpgl/write.rs b/crates/cad/src/hpgl/write.rs index bb397d7eaa..69f5e503a2 100644 --- a/crates/cad/src/hpgl/write.rs +++ b/crates/cad/src/hpgl/write.rs @@ -43,16 +43,13 @@ use clip::Region; /// Plotter units per point. const PLU_PER_PT: f64 = 1016.0 / 72.0; -/// The largest coordinate written, plotter units. -pub const MAX_COORD: i64 = (1 << 23) - 1; +pub use craft_plotter::hpgl::write::{MAX_COORD, MAX_PENS}; /// The coordinates an HP-GL plot keeps to without a warning: 16-bit numbers, plotter units. const CLASSIC_RANGE: std::ops::RangeInclusive = -32_768..=32_767; /// The curve tolerance a path is flattened to by default, points. pub const DEFAULT_TOLERANCE: f64 = 0.1; /// The smallest and largest curve tolerance, points. pub const TOLERANCE_RANGE: std::ops::RangeInclusive = 0.01..=10.0; -/// The most pens: a pen table's length, and the colors that get a pen of their own. -pub const MAX_PENS: usize = 255; /// The most points the plots of one export hold. const MAX_POINTS: usize = if cfg!(test) { 100_000 } else { 10_000_000 }; /// The most work sorting paths and finding which lie inside others may take, over the whole plot: @@ -295,7 +292,14 @@ pub fn export_regions(doc: &Document, opts: &HpglOptions, regions: &[Rect]) -> R } let bytes = match opts.version { Version::Hpgl => plain(&by_pen), - Version::Hpgl2 => encoded(&by_pen, &pens), + Version::Hpgl2 => { + let pen_table: Vec = pens + .iter() + .enumerate() + .map(|(i, &rgb)| craft_plotter::hpgl::write::Pen { number: i + 1, rgb }) + .collect(); + craft_plotter::hpgl::write::write_hpgl2(&pen_table, &by_pen).into_bytes() + } }; out.push(HpglOutput { bytes, pens: pens.clone(), warnings, setting_notes }); } @@ -523,56 +527,7 @@ fn plain(by_pen: &[Vec>]) -> Vec { } /// HP-GL/2: `IN;`, the palette, each pen's paths as one `PE`, `PU;SP0;`. -fn encoded(by_pen: &[Vec>], pens: &[[u8; 3]]) -> Vec { - let mut out = b"IN;".to_vec(); - if !pens.is_empty() { - // Pens 1 to n on a plotter, and on a raster device (whose pens are 0 to NP − 1) too. - let np = (pens.len() + 1).next_power_of_two().max(2); - out.extend(format!("NP{np};").bytes()); - for (i, [r, g, b]) in pens.iter().enumerate() { - out.extend(format!("PC{},{r},{g},{b};", i + 1).bytes()); - } - } - let mut at: Option<(i64, i64)> = None; - for (i, paths) in by_pen.iter().enumerate().filter(|(_, p)| !p.is_empty()) { - out.extend(format!("PU;SP{};PE", i + 1).bytes()); - for path in paths { - for (k, &p) in path.iter().enumerate() { - if k == 0 { - out.push(b'<'); - } - // The first move of the plot is absolute, and so is one longer than the range a - // device takes for each number; every other is relative. - match at.map(|a| (p.0 - a.0, p.1 - a.1)).filter(|d| d.0.abs() <= MAX_COORD && d.1.abs() <= MAX_COORD) { - None => { - out.push(b'='); - pe_number(&mut out, p.0); - pe_number(&mut out, p.1); - } - Some((dx, dy)) => { - pe_number(&mut out, dx); - pe_number(&mut out, dy); - } - } - at = Some(p); - } - } - out.push(b';'); - } - out.extend(b"PU;SP0;"); - out -} -/// `v` as a base-64 PE number: the sign in the low bit, the low digits from 63 up and the last -/// digit from 191 up. -fn pe_number(out: &mut Vec, v: i64) { - let mut n = (v.unsigned_abs() << 1) | u64::from(v < 0); - while n >= 64 { - out.push(63 + (n % 64) as u8); - n /= 64; - } - out.push(191 + n as u8); -} /// One line the pen draws, in document space, and its color. struct Run { From 0087be0452c90653cf73a076e26c65170b861f48 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 19:08:49 -0500 Subject: [PATCH 07/13] color: cut over palette_io GPL/ASE/ACB to craft-cms (#8627) --- Cargo.lock | 10 + Cargo.toml | 1 + crates/color/Cargo.toml | 1 + crates/color/src/palette_io.rs | 502 ++++----------------------------- 4 files changed, 64 insertions(+), 450 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d635613a96..6805f2c4ff 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1009,6 +1009,15 @@ dependencies = [ "ruzstd", ] +[[package]] +name = "craft-cms" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=e7873217287876f76a045550369c90a541693c33#e7873217287876f76a045550369c90a541693c33" +dependencies = [ + "md-5", + "rayon", +] + [[package]] name = "craft-codepage" version = "0.1.0" @@ -6728,6 +6737,7 @@ dependencies = [ name = "vectorcraft-color" version = "0.24.1" dependencies = [ + "craft-cms", "kurbo 0.13.1", "moxcms", "proptest", diff --git a/Cargo.toml b/Cargo.toml index 184df0f647..07e90b5795 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ rust-version = "1.95" repository = "https://github.com/storytold/vectorcraft" [workspace.dependencies] +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "e7873217287876f76a045550369c90a541693c33" } craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", default-features = false, features = ["interpret", "write"] } craft-print = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } diff --git a/crates/color/Cargo.toml b/crates/color/Cargo.toml index a007ede39f..1273b5d0ad 100644 --- a/crates/color/Cargo.toml +++ b/crates/color/Cargo.toml @@ -9,6 +9,7 @@ description = "VectorCraft color" workspace = true [dependencies] +craft-cms = { workspace = true } kurbo = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } diff --git a/crates/color/src/palette_io.rs b/crates/color/src/palette_io.rs index 9be00b4b21..cb8e0b3950 100644 --- a/crates/color/src/palette_io.rs +++ b/crates/color/src/palette_io.rs @@ -6,6 +6,8 @@ use std::collections::{HashMap, HashSet}; +pub use craft_cms::palette::css_property; +use craft_cms::palette::{self as cms_palette, Palette, PaletteColor, PaletteGroup, PaletteSwatch}; use serde::{Deserialize, Serialize}; use crate::{Color, GradientKind, Paint, Swatch, SwatchGroup, SwatchLibrary}; @@ -83,18 +85,50 @@ struct NativeFile { const NATIVE_FORMAT: &str = "vcswatches"; const GPL_HEADER: &str = "GIMP Palette"; -const GPL_GROUP: &str = "# Group:"; -const ASE_SIGNATURE: &[u8] = b"ASEF"; -const ASE_GROUP_START: u16 = 0xC001; -const ASE_GROUP_END: u16 = 0xC002; -const ASE_COLOR: u16 = 0x0001; -/// The most colors and groups read from one `.ase` file. -const ASE_MAX_ENTRIES: usize = 100_000; -/// The most UTF-16 code units of a name that are kept. -const ASE_MAX_NAME: usize = 1024; -const ASE_CUT_SHORT: &str = "the swatch exchange file is cut short"; -const ACB_SIGNATURE: &[u8] = b"8BCB"; -const ACB_CUT_SHORT: &str = "the color book is cut short"; + +fn color_to_cms(c: Color) -> PaletteColor { + match c { + Color::Rgb { r, g, b } => PaletteColor::Rgb { r, g, b }, + Color::Cmyk { c, m, y, k } => PaletteColor::Cmyk { c, m, y, k }, + Color::Lab { l, a, b } => PaletteColor::Lab { l, a, b }, + Color::Gray { k } => PaletteColor::Gray { k }, + } +} + +fn color_from_cms(c: PaletteColor) -> Color { + match c { + PaletteColor::Rgb { r, g, b } => Color::rgb(r, g, b), + PaletteColor::Cmyk { c, m, y, k } => Color::cmyk(c, m, y, k), + PaletteColor::Lab { l, a, b } => Color::lab(l, a, b), + PaletteColor::Gray { k } => Color::gray(k), + } +} + +fn swatches_to_cms(list: &[Swatch]) -> Vec { + list.iter() + .filter_map(|w| w.paint.color().map(|c| PaletteSwatch { name: w.name.clone(), color: color_to_cms(c), global: w.global, spot: w.spot })) + .collect() +} + +fn swatches_from_cms(list: Vec) -> Vec { + list.into_iter().map(|w| Swatch { name: w.name, paint: Paint::solid(color_from_cms(w.color)), global: w.global, spot: w.spot }).collect() +} + +fn to_cms_palette(lib: &SwatchLibrary) -> Palette { + Palette { + name: lib.name.clone(), + swatches: swatches_to_cms(&lib.swatches), + groups: lib.groups.iter().map(|g| PaletteGroup { name: g.name.clone(), swatches: swatches_to_cms(&g.swatches) }).collect(), + } +} + +fn from_cms_palette(p: Palette) -> SwatchLibrary { + SwatchLibrary { + name: p.name, + swatches: swatches_from_cms(p.swatches), + groups: p.groups.into_iter().map(|g| SwatchGroup { name: g.name, swatches: swatches_from_cms(g.swatches) }).collect(), + } +} /// Write `lib` in `format` → the file's bytes. Pattern swatches (their tiles live in a document) /// and None are left out; `.gpl` keeps solid colours only, as 8-bit RGB, and `.ase` keeps solid @@ -113,8 +147,8 @@ pub fn write(lib: &SwatchLibrary, format: PaletteFormat) -> Result, Stri let file = NativeFile { format: NATIVE_FORMAT.into(), version: 1, library }; serde_json::to_string_pretty(&file).unwrap_or_default() } - PaletteFormat::Gpl => write_gpl(lib), - PaletteFormat::Ase => return write_ase(lib), + PaletteFormat::Gpl => return cms_palette::write_palette(&to_cms_palette(lib), cms_palette::PaletteFormat::Gpl), + PaletteFormat::Ase => return cms_palette::write_palette(&to_cms_palette(lib), cms_palette::PaletteFormat::Ase), PaletteFormat::Css => write_css(lib, keep), }; Ok(text.into_bytes()) @@ -125,49 +159,6 @@ fn one_line(s: &str) -> String { s.split(['\n', '\r', '\t']).collect::>().join(" ").trim().to_string() } -fn write_gpl(lib: &SwatchLibrary) -> String { - let mut out = format!("{GPL_HEADER}\nName: {}\nColumns: 0\n#\n", one_line(&lib.name)); - let colors = |out: &mut String, list: &[Swatch]| { - for w in list { - if let Some(c) = w.paint.color() { - let [r, g, b, _] = c.to_rgba8(1.0); - out.push_str(&format!("{r:3} {g:3} {b:3}\t{}\n", one_line(&w.name))); - } - } - }; - colors(&mut out, &lib.swatches); - for g in &lib.groups { - out.push_str(&format!("{GPL_GROUP} {}\n", one_line(&g.name))); - colors(&mut out, &g.swatches); - } - out -} - -/// `name` as a CSS custom property (`--` and an escaped identifier): lower case, spaces as -/// hyphens, other characters an identifier can't hold escaped with a backslash. -pub fn css_property(name: &str) -> String { - let mut out = String::from("--"); - for word in name.split_whitespace() { - if out.len() > 2 { - out.push('-'); - } - for ch in word.chars().flat_map(char::to_lowercase) { - if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' || !ch.is_ascii() { - out.push(ch); - } else if ch.is_ascii_graphic() { - out.push('\\'); - out.push(ch); - } else { - out.push_str(&format!("\\{:x} ", ch as u32)); - } - } - } - if out.len() == 2 { - out.push_str("swatch"); - } - out -} - /// A colour as CSS (`#rrggbb`, or `#rrggbbaa` below full opacity). fn css_color(c: &Color, opacity: f32) -> String { let [r, g, b, a] = c.to_rgba8(opacity); @@ -276,97 +267,10 @@ fn write_css(lib: &SwatchLibrary, keep: impl Fn(&&Swatch) -> bool) -> String { /// a tint swatch is written as the color it shows, a process color without its link to its base. /// The file has no library name ([`read_ase`] names a library after its file). More than /// [`ASE_MAX_ENTRIES`] colors and groups is an error. -fn write_ase(lib: &SwatchLibrary) -> Result, String> { - let solid = |list: &[Swatch]| list.iter().filter(|w| w.paint.color().is_some()).count(); - let entries = solid(&lib.swatches) + lib.groups.iter().map(|g| 1 + solid(&g.swatches)).sum::(); - if entries > ASE_MAX_ENTRIES { - return Err(format!( - "VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries}" - )); - } - let mut body = vec![]; - let mut blocks = put_ase_colors(&mut body, &lib.swatches)?; - for g in &lib.groups { - let mut name = vec![]; - put_ase_name(&mut name, &g.name)?; - put_ase_block(&mut body, ASE_GROUP_START, &name)?; - blocks += 2 + put_ase_colors(&mut body, &g.swatches)?; - put_ase_block(&mut body, ASE_GROUP_END, &[])?; - } - let blocks = u32::try_from(blocks).map_err(|_| "too many swatch exchange blocks".to_string())?; - let mut out = ASE_SIGNATURE.to_vec(); - out.extend(1u16.to_be_bytes()); - out.extend(0u16.to_be_bytes()); - out.extend(blocks.to_be_bytes()); - out.extend(body); - Ok(out) -} - -/// The color blocks of the solid colors in `list` → how many were written. -fn put_ase_colors(out: &mut Vec, list: &[Swatch]) -> Result { - let unit = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; - let ab = |v: f32| if v.is_finite() { v.clamp(-128.0, 127.0) } else { 0.0 }; - let mut n = 0; - for (w, color) in list.iter().filter_map(|w| Some((w, w.paint.color()?))) { - let mut body = vec![]; - put_ase_name(&mut body, &w.name)?; - let (model, values): (&[u8; 4], Vec) = match color { - Color::Rgb { r, g, b } => (b"RGB ", vec![unit(r), unit(g), unit(b)]), - Color::Cmyk { c, m, y, k } => (b"CMYK", vec![unit(c), unit(m), unit(y), unit(k)]), - Color::Lab { l, a, b } => (b"LAB ", vec![unit(l / 100.0), ab(a), ab(b)]), - Color::Gray { k } => (b"Gray", vec![1.0 - unit(k)]), - }; - body.extend(model); - body.extend(values.iter().flat_map(|v| v.to_be_bytes())); - let kind: u16 = if w.spot { - 1 - } else if w.global { - 0 - } else { - 2 - }; - body.extend(kind.to_be_bytes()); - put_ase_block(out, ASE_COLOR, &body)?; - n += 1; - } - Ok(n) -} - -/// A block: its type, the length of its body and the body. -fn put_ase_block(out: &mut Vec, kind: u16, body: &[u8]) -> Result<(), String> { - let len = u32::try_from(body.len()).map_err(|_| "a swatch exchange block is too long".to_string())?; - out.extend(kind.to_be_bytes()); - out.extend(len.to_be_bytes()); - out.extend_from_slice(body); - Ok(()) -} - -/// A name as `.ase` stores it: a `u16` count of UTF-16 code units, the terminating zero included, -/// then the units. NUL characters are left out, and a name longer than [`ASE_MAX_NAME`] code units -/// is cut before the character that would pass that limit. -fn put_ase_name(out: &mut Vec, name: &str) -> Result<(), String> { - let mut units: Vec = vec![]; - for c in name.chars().filter(|&c| c != '\0') { - let mut buf = [0; 2]; - let encoded = c.encode_utf16(&mut buf); - if units.len() + encoded.len() > ASE_MAX_NAME { - break; - } - units.extend_from_slice(encoded); - } - units.push(0); - let count = u16::try_from(units.len()).map_err(|_| "a swatch exchange name is too long".to_string())?; - out.extend(count.to_be_bytes()); - out.extend(units.iter().flat_map(|u| u.to_be_bytes())); - Ok(()) -} - -/// Read a `.vcswatches` or `.gpl` library (detected from its content). `name` names it when the -/// file doesn't. pub fn read(text: &str, name: &str) -> Result { let text = text.trim_start_matches('\u{feff}').trim_start(); if text.starts_with(GPL_HEADER) { - return Ok(read_gpl(text, name)); + return cms_palette::read_palette(text.as_bytes(), name).map(from_cms_palette); } if text.starts_with('{') { let f: NativeFile = serde_json::from_str(text).map_err(|e| format!("not a swatch library: {e}"))?; @@ -391,11 +295,8 @@ pub fn sniff(text: &str) -> bool { /// Read the bytes of a library file: a swatch exchange `.ase` file, else a `.vcswatches` or /// `.gpl` library ([`read`]). `name` names it when the file doesn't. pub fn read_bytes(bytes: &[u8], name: &str) -> Result { - if bytes.starts_with(ASE_SIGNATURE) { - return read_ase(bytes, name); - } - if bytes.starts_with(ACB_SIGNATURE) { - return read_acb(bytes, name).map_err(|e| if e == ASE_CUT_SHORT { ACB_CUT_SHORT.into() } else { e }); + if cms_palette::sniff_palette(bytes) { + return cms_palette::read_palette(bytes, name).map(from_cms_palette); } read(&String::from_utf8_lossy(bytes), name) } @@ -403,309 +304,10 @@ pub fn read_bytes(bytes: &[u8], name: &str) -> Result { /// Are `bytes` a library [`read_bytes`] understands? Text that isn't valid UTF-8 is checked as /// [`read_bytes`] reads it, with the invalid bytes replaced (its first KiB is enough). pub fn sniff_bytes(bytes: &[u8]) -> bool { - bytes.starts_with(ASE_SIGNATURE) - || bytes.starts_with(ACB_SIGNATURE) + cms_palette::sniff_palette(bytes) || std::str::from_utf8(bytes).is_ok_and(sniff) || sniff(&String::from_utf8_lossy(bytes.get(..1024).unwrap_or(bytes))) } -/// `.gpl`: `Name:` names the library, `# Group: name` starts a colour group, other `#` lines and -/// headers (`Columns:`) are skipped, as are lines that aren't `r g b [name]`. Unnamed colors are -/// named by their values and unnamed groups "Color Group"; a name a color or group already has gets -/// a number ([`UniqueNames`]). -fn read_gpl(text: &str, fallback: &str) -> SwatchLibrary { - let mut lib = SwatchLibrary { name: fallback.into(), ..Default::default() }; - let mut names = UniqueNames::default(); - for line in text.lines().skip(1) { - let line = line.trim(); - if let Some(g) = line.strip_prefix(GPL_GROUP) { - lib.groups.push(SwatchGroup { name: names.unique(group_name(g)), swatches: vec![] }); - continue; - } - if let Some(n) = line.strip_prefix("Name:") { - if !n.trim().is_empty() { - lib.name = n.trim().to_string(); - } - continue; - } - // Comments, headers (`Columns: 4`) and anything else that isn't a colour are skipped. - let words: Vec<&str> = line.split_whitespace().collect(); - let rgb: Vec = words.iter().take(3).map_while(|v| v.parse().ok()).collect(); - let [r, g, b] = rgb[..] else { continue }; - let rest = words[3..].join(" "); - let base = if rest.is_empty() { format!("R={r} G={g} B={b}") } else { rest }; - let w = Swatch { name: names.unique(base), paint: Paint::solid(Color::rgb8(r, g, b)), global: false, spot: false }; - match lib.groups.last_mut() { - Some(grp) => grp.swatches.push(w), - None => lib.swatches.push(w), - } - } - lib -} - -/// `.ase`, from public descriptions of the format: the layout from -/// , the component ranges from -/// . After the signature come, big-endian, a `u16` major (1) and -/// minor version, a `u32` block count and the blocks, each a `u16` type, a `u32` body length and -/// the body. A group start's body is a name. A color's body is a name, a four-character model -/// (`RGB `, `CMYK`, `LAB `, `Gray`), its components as `f32` (3, 4, 3 and 1 of them) and a `u16` -/// color type (0 global, 1 spot, 2 process). RGB, CMYK and gray components run from 0 to 1 (a -/// gray level of 1 is white), Lab lightness from 0 to 1 and a and b from −128 to 127. A lightness -/// above 1 is read as L* itself. A name is a `u16` count of UTF-16 code units, the terminating zero -/// included, then the units. -/// -/// Color groups become groups: a group start inside an open group ends that group, and a group -/// left open ends with the file. Blocks of other types and colors in other models are skipped. -/// Unnamed colors are named by their values and unnamed groups "Color Group"; a name a color or -/// group already has gets a number ([`UniqueNames`]). A truncated file, a major version other than -/// 1 or more than [`ASE_MAX_ENTRIES`] colors and groups is an error. -fn read_ase(bytes: &[u8], fallback: &str) -> Result { - let mut data = AseData(bytes); - data.bytes(ASE_SIGNATURE.len())?; - let (major, minor) = (data.u16()?, data.u16()?); - if major != 1 { - return Err(format!("swatch exchange version {major}.{minor} isn't supported (only 1.x)")); - } - let blocks = data.u32()?; - let mut lib = SwatchLibrary { name: fallback.into(), ..Default::default() }; - let mut names = UniqueNames::default(); - let (mut in_group, mut entries) = (false, 0usize); - for _ in 0..blocks { - let kind = data.u16()?; - let len = usize::try_from(data.u32()?).unwrap_or(usize::MAX); - let mut body = AseData(data.bytes(len)?); - if matches!(kind, ASE_GROUP_START | ASE_COLOR) { - entries += 1; - if entries > ASE_MAX_ENTRIES { - return Err(format!("the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups")); - } - } - match kind { - ASE_GROUP_START => { - lib.groups.push(SwatchGroup { name: names.unique(group_name(&body.name()?)), swatches: vec![] }); - in_group = true; - } - ASE_GROUP_END => in_group = false, - ASE_COLOR => { - let Some(mut w) = ase_swatch(&mut body)? else { continue }; - w.name = names.unique(std::mem::take(&mut w.name)); - match lib.groups.last_mut().filter(|_| in_group) { - Some(g) => g.swatches.push(w), - None => lib.swatches.push(w), - } - } - // Other blocks are skipped. - _ => {} - } - } - Ok(lib) -} - -/// `.acb` (a color book, read only), from public descriptions of the format: after the signature -/// come, big-endian, a `u16` version (1) and book id, the title, prefix, suffix and description -/// as strings, a `u16` color count, page size and page selector offset, a `u16` color space (0 -/// RGB, 2 CMYK, 7 Lab) and the colors: each a name, a six-character catalog code and its -/// components as bytes. RGB runs from 0 to 255, CMYK ink is stored inverted (255 is no ink), Lab -/// lightness is 0 to 255 for 0 to 100 and a and b are offset by 128. A string is a `u32` count of -/// UTF-16 code units, then the units; a `$$$/key=Text` string means `Text`, and `^R`, `^C` stand -/// for ® and ©. An optional `spflspot` or `spflproc` at the end says whether the colors are spot -/// or process colors (a book without it is a spot color book). -/// -/// The book's colors are named with its prefix and suffix ("PANTONE 185 C"); colors without a -/// name (the padding of a book's pages) are left out. A version other than 1, a color space other -/// than those three or more than [`ASE_MAX_ENTRIES`] colors is an error. -fn read_acb(bytes: &[u8], fallback: &str) -> Result { - let mut data = AseData(bytes); - data.bytes(ACB_SIGNATURE.len())?; - let version = data.u16()?; - if version != 1 { - return Err(format!("color book version {version} isn't supported (only 1)")); - } - let _book_id = data.u16()?; - let [title, prefix, suffix, _description] = [data.acb_string()?, data.acb_string()?, data.acb_string()?, data.acb_string()?]; - let count = usize::from(data.u16()?); - if count > ASE_MAX_ENTRIES { - return Err(format!("the color book holds more than {ASE_MAX_ENTRIES} colors")); - } - let (_page_size, _page_offset) = (data.u16()?, data.u16()?); - let space = data.u16()?; - let mut colors = Vec::with_capacity(count); - for _ in 0..count { - let name = data.acb_string()?; - let _code = data.bytes(6)?; - let color = match space { - 0 => { - let [r, g, b] = data.array::<3>()?; - Color::rgb8(r, g, b) - } - 2 => { - let ink = |v: u8| f32::from(255 - v) / 255.0; - let [c, m, y, k] = data.array::<4>()?; - Color::cmyk(ink(c), ink(m), ink(y), ink(k)) - } - 7 => { - let [l, a, b] = data.array::<3>()?; - Color::lab(f32::from(l) * 100.0 / 255.0, f32::from(a) - 128.0, f32::from(b) - 128.0) - } - other => return Err(format!("color books in color space {other} aren't supported (only RGB, CMYK and Lab)")), - }; - colors.push((name, color)); - } - // Spot colors unless the book says process ones. - let spot = data.0.windows(8).last() != Some(b"spflproc".as_slice()); - let mut lib = SwatchLibrary { name: if title.is_empty() { fallback.into() } else { title }, ..Default::default() }; - let mut names = UniqueNames::default(); - // Every name gets the prefix and the suffix, and is kept twice (the swatch's and the set of - // names taken): a megabyte book of long affixes and many colors came to hundreds of MB. - let mut kept = 0usize; - for (name, color) in colors.into_iter().filter(|(n, _)| !n.trim().is_empty()) { - kept = kept.saturating_add(2 * (prefix.len() + name.len() + suffix.len())); - if kept > ACB_MAX_NAME_BYTES { - return Err(format!("the color book's names take more than {} MB", ACB_MAX_NAME_BYTES >> 20)); - } - let name = names.unique(format!("{prefix}{name}{suffix}").trim().to_string()); - lib.swatches.push(Swatch { name, paint: Paint::solid(color), global: spot, spot }); - } - Ok(lib) -} - -/// Most bytes a color book's full color names (with its prefix and suffix) may take, counted -/// twice as they are kept twice. -const ACB_MAX_NAME_BYTES: usize = 64 << 20; - -/// The swatch of an `.ase` color block, `None` for a model other than RGB, CMYK, Lab and Gray. -/// Components are clamped to their ranges. -fn ase_swatch(body: &mut AseData) -> Result, String> { - let name = body.name()?; - let unit = |v: f32| v.clamp(0.0, 1.0); - let color = match &body.array::<4>()? { - b"RGB " => { - let [r, g, b] = [body.f32()?, body.f32()?, body.f32()?]; - Color::rgb(unit(r), unit(g), unit(b)) - } - b"CMYK" => { - let [c, m, y, k] = [body.f32()?, body.f32()?, body.f32()?, body.f32()?]; - Color::cmyk(unit(c), unit(m), unit(y), unit(k)) - } - // Lightness is stored as a fraction of 100. Some writers store L* itself, which shows as a - // value above 1. - b"LAB " => { - let [l, a, b] = [body.f32()?, body.f32()?, body.f32()?]; - let l = if l > 1.0 { l.min(100.0) } else { unit(l) * 100.0 }; - Color::lab(l, a.clamp(-128.0, 127.0), b.clamp(-128.0, 127.0)) - } - // A gray level (1 is white); a gray color holds its ink. - b"Gray" => Color::gray(1.0 - unit(body.f32()?)), - _ => return Ok(None), - }; - // Some writers leave the color type out, which makes a process color. - let kind = if body.0.len() >= 2 { body.u16()? } else { 2 }; - // Spot colors are global. - let (global, spot) = match kind { - 0 => (true, false), - 1 => (true, true), - _ => (false, false), - }; - let name = if name.is_empty() { value_name(color) } else { name }; - Ok(Some(Swatch { name, paint: Paint::solid(color), global, spot })) -} - -/// A color's values in its own model, as new swatches are named ("C=10 M=20 Y=30 K=0", -/// "R=255 G=128 B=0", "Gray K=40", "L=52 a=70 b=-30"). -fn value_name(c: Color) -> String { - let pct = |v: f32| (v * 100.0).round(); - let byte = |v: f32| (v * 255.0).round(); - match c { - Color::Cmyk { c, m, y, k } => format!("C={} M={} Y={} K={}", pct(c), pct(m), pct(y), pct(k)), - Color::Rgb { r, g, b } => format!("R={} G={} B={}", byte(r), byte(g), byte(b)), - Color::Gray { k } => format!("Gray K={}", pct(k)), - // `+ 0.0` turns a rounded -0 into 0. - Color::Lab { l, a, b } => format!("L={} a={} b={}", l.round() + 0.0, a.round() + 0.0, b.round() + 0.0), - } -} - -/// `.ase` data, read field by field; reading past its end is an error. -struct AseData<'a>(&'a [u8]); - -impl<'a> AseData<'a> { - fn bytes(&mut self, n: usize) -> Result<&'a [u8], String> { - let (head, rest) = self.0.split_at_checked(n).ok_or(ASE_CUT_SHORT)?; - self.0 = rest; - Ok(head) - } - fn array(&mut self) -> Result<[u8; N], String> { - let (head, rest) = self.0.split_first_chunk::().ok_or(ASE_CUT_SHORT)?; - self.0 = rest; - Ok(*head) - } - fn u16(&mut self) -> Result { - self.array().map(u16::from_be_bytes) - } - fn u32(&mut self) -> Result { - self.array().map(u32::from_be_bytes) - } - /// A component; one that isn't a finite number reads as 0. - fn f32(&mut self) -> Result { - let v = f32::from_be_bytes(self.array()?); - Ok(if v.is_finite() { v } else { 0.0 }) - } - /// A color book string ([`read_acb`]): a `u32` count of UTF-16 code units, then the units, - /// with `$$$/key=Text` read as `Text` and `^R`, `^C` as ®, ©; at most [`ASE_MAX_NAME`] units - /// are kept. - fn acb_string(&mut self) -> Result { - let n = usize::try_from(self.u32()?).unwrap_or(usize::MAX); - let (units, _) = self.bytes(n.checked_mul(2).ok_or(ASE_CUT_SHORT)?)?.as_chunks::<2>(); - let units: Vec = units.iter().take(ASE_MAX_NAME).map(|u| u16::from_be_bytes(*u)).take_while(|&u| u != 0).collect(); - let s = String::from_utf16_lossy(&units); - let s = match s.strip_prefix("$$$/") { - Some(key) => key.split_once('=').map_or("", |(_, text)| text).to_string(), - None => s, - }; - Ok(s.replace("^R", "®").replace("^C", "©")) - } - /// A name up to its terminating zero, trimmed. A block that ends before it has no name. - fn name(&mut self) -> Result { - if self.0.is_empty() { - return Ok(String::new()); - } - let n = usize::from(self.u16()?); - let (units, _) = self.bytes(n * 2)?.as_chunks::<2>(); - let units: Vec = units.iter().take(ASE_MAX_NAME).map(|u| u16::from_be_bytes(*u)).take_while(|&u| u != 0).collect(); - Ok(String::from_utf16_lossy(&units).trim().to_string()) - } -} - -/// A group's name as a file gives it, trimmed; "Color Group" when it has none. -fn group_name(name: &str) -> String { - let name = name.trim(); - if name.is_empty() { "Color Group".into() } else { name.to_string() } -} - -/// The swatch and group names a reader has handed out. Swatches and color groups share one set of -/// names, as in a document, and a name already taken gets the first free number ("Black 2"). -#[derive(Default)] -struct UniqueNames { - taken: HashSet, - /// The last number tried for each repeated name. - last: HashMap, -} - -impl UniqueNames { - fn unique(&mut self, base: String) -> String { - if self.taken.insert(base.clone()) { - return base; - } - // Each pass tries the next number, and only finitely many names are taken. - let n = self.last.entry(base.clone()).or_insert(1); - loop { - *n += 1; - let name = format!("{base} {n}"); - if self.taken.insert(name.clone()) { - return name; - } - } - } -} - #[cfg(test)] mod tests; From 693785fc709e8919771e6fe6b9bf94a0d2f2b887 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 19 Nov 2026 07:18:07 +0700 Subject: [PATCH 08/13] Revert "cutover: use craft_plotter::hpgl::write (#8626)" This reverts commit d2bed0bdb81a9f94d46e14bce1e0fb4b99bab2a0. --- Cargo.lock | 3 +- Cargo.toml | 2 +- crates/cad/src/hpgl/write.rs | 63 ++++++++++++++++++++++++++++++------ 3 files changed, 56 insertions(+), 12 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6805f2c4ff..e7a0ffe1c3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1213,9 +1213,8 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e7873217287876f76a045550369c90a541693c33#e7873217287876f76a045550369c90a541693c33" +source = "git+https://github.com/storytold/craft-libs?rev=a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57#a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57" dependencies = [ - "kurbo 0.13.1", "thiserror 2.0.21", ] diff --git a/Cargo.toml b/Cargo.toml index 07e90b5795..c33e3b1cfc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -33,7 +33,7 @@ craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "64b181977 # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "e7873217287876f76a045550369c90a541693c33" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57" } craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } # WMF, EMF and EMF+ reader (craft-libs#778). craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } diff --git a/crates/cad/src/hpgl/write.rs b/crates/cad/src/hpgl/write.rs index 69f5e503a2..bb397d7eaa 100644 --- a/crates/cad/src/hpgl/write.rs +++ b/crates/cad/src/hpgl/write.rs @@ -43,13 +43,16 @@ use clip::Region; /// Plotter units per point. const PLU_PER_PT: f64 = 1016.0 / 72.0; -pub use craft_plotter::hpgl::write::{MAX_COORD, MAX_PENS}; +/// The largest coordinate written, plotter units. +pub const MAX_COORD: i64 = (1 << 23) - 1; /// The coordinates an HP-GL plot keeps to without a warning: 16-bit numbers, plotter units. const CLASSIC_RANGE: std::ops::RangeInclusive = -32_768..=32_767; /// The curve tolerance a path is flattened to by default, points. pub const DEFAULT_TOLERANCE: f64 = 0.1; /// The smallest and largest curve tolerance, points. pub const TOLERANCE_RANGE: std::ops::RangeInclusive = 0.01..=10.0; +/// The most pens: a pen table's length, and the colors that get a pen of their own. +pub const MAX_PENS: usize = 255; /// The most points the plots of one export hold. const MAX_POINTS: usize = if cfg!(test) { 100_000 } else { 10_000_000 }; /// The most work sorting paths and finding which lie inside others may take, over the whole plot: @@ -292,14 +295,7 @@ pub fn export_regions(doc: &Document, opts: &HpglOptions, regions: &[Rect]) -> R } let bytes = match opts.version { Version::Hpgl => plain(&by_pen), - Version::Hpgl2 => { - let pen_table: Vec = pens - .iter() - .enumerate() - .map(|(i, &rgb)| craft_plotter::hpgl::write::Pen { number: i + 1, rgb }) - .collect(); - craft_plotter::hpgl::write::write_hpgl2(&pen_table, &by_pen).into_bytes() - } + Version::Hpgl2 => encoded(&by_pen, &pens), }; out.push(HpglOutput { bytes, pens: pens.clone(), warnings, setting_notes }); } @@ -527,7 +523,56 @@ fn plain(by_pen: &[Vec>]) -> Vec { } /// HP-GL/2: `IN;`, the palette, each pen's paths as one `PE`, `PU;SP0;`. +fn encoded(by_pen: &[Vec>], pens: &[[u8; 3]]) -> Vec { + let mut out = b"IN;".to_vec(); + if !pens.is_empty() { + // Pens 1 to n on a plotter, and on a raster device (whose pens are 0 to NP − 1) too. + let np = (pens.len() + 1).next_power_of_two().max(2); + out.extend(format!("NP{np};").bytes()); + for (i, [r, g, b]) in pens.iter().enumerate() { + out.extend(format!("PC{},{r},{g},{b};", i + 1).bytes()); + } + } + let mut at: Option<(i64, i64)> = None; + for (i, paths) in by_pen.iter().enumerate().filter(|(_, p)| !p.is_empty()) { + out.extend(format!("PU;SP{};PE", i + 1).bytes()); + for path in paths { + for (k, &p) in path.iter().enumerate() { + if k == 0 { + out.push(b'<'); + } + // The first move of the plot is absolute, and so is one longer than the range a + // device takes for each number; every other is relative. + match at.map(|a| (p.0 - a.0, p.1 - a.1)).filter(|d| d.0.abs() <= MAX_COORD && d.1.abs() <= MAX_COORD) { + None => { + out.push(b'='); + pe_number(&mut out, p.0); + pe_number(&mut out, p.1); + } + Some((dx, dy)) => { + pe_number(&mut out, dx); + pe_number(&mut out, dy); + } + } + at = Some(p); + } + } + out.push(b';'); + } + out.extend(b"PU;SP0;"); + out +} +/// `v` as a base-64 PE number: the sign in the low bit, the low digits from 63 up and the last +/// digit from 191 up. +fn pe_number(out: &mut Vec, v: i64) { + let mut n = (v.unsigned_abs() << 1) | u64::from(v < 0); + while n >= 64 { + out.push(63 + (n % 64) as u8); + n /= 64; + } + out.push(191 + n as u8); +} /// One line the pen draws, in document space, and its color. struct Run { From 4e63316d9a93c893135c5cc0f08e96ddbc03eaf8 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 19 Nov 2026 07:15:52 +0700 Subject: [PATCH 09/13] color: the palette tests define the swatch exchange constants craft-cms keeps private --- crates/color/src/palette_io/tests.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/crates/color/src/palette_io/tests.rs b/crates/color/src/palette_io/tests.rs index bbbae16a53..0e6adb90ed 100644 --- a/crates/color/src/palette_io/tests.rs +++ b/crates/color/src/palette_io/tests.rs @@ -2,6 +2,13 @@ use super::*; use crate::{Gradient, GradientPaint, GradientStop}; use proptest::prelude::*; +// The swatch exchange file's signature, block types and entry cap, which craft-cms keeps private. +const ASE_SIGNATURE: &[u8] = b"ASEF"; +const ASE_GROUP_START: u16 = 0xC001; +const ASE_GROUP_END: u16 = 0xC002; +const ASE_COLOR: u16 = 0x0001; +const ASE_MAX_ENTRIES: usize = 100_000; + #[test] fn gpl_blank_name_keeps_fallback() { let blank = "GIMP Palette\nName: \nColumns: 0\n#\n 1 2 3\tx\n"; From 891dd6310dc01cfa1c506d4d8033e55725ddcba2 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 19 Nov 2026 07:59:02 +0700 Subject: [PATCH 10/13] color: an .ase library over the cap gets VectorCraft's own, translated message again #8627 left the check to craft-cms, whose wording isn't in the catalogs, and main's test of the message failed. --- crates/color/src/palette_io.rs | 16 +++++++++++++++- crates/color/src/palette_io/tests.rs | 3 +-- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/crates/color/src/palette_io.rs b/crates/color/src/palette_io.rs index cb8e0b3950..1709fb57c8 100644 --- a/crates/color/src/palette_io.rs +++ b/crates/color/src/palette_io.rs @@ -114,6 +114,10 @@ fn swatches_from_cms(list: Vec) -> Vec { list.into_iter().map(|w| Swatch { name: w.name, paint: Paint::solid(color_from_cms(w.color)), global: w.global, spot: w.spot }).collect() } +/// The most colors and groups one swatch exchange file holds, read or written (craft-cms reads +/// as many). +const ASE_MAX_ENTRIES: usize = 100_000; + fn to_cms_palette(lib: &SwatchLibrary) -> Palette { Palette { name: lib.name.clone(), @@ -148,7 +152,17 @@ pub fn write(lib: &SwatchLibrary, format: PaletteFormat) -> Result, Stri serde_json::to_string_pretty(&file).unwrap_or_default() } PaletteFormat::Gpl => return cms_palette::write_palette(&to_cms_palette(lib), cms_palette::PaletteFormat::Gpl), - PaletteFormat::Ase => return cms_palette::write_palette(&to_cms_palette(lib), cms_palette::PaletteFormat::Ase), + PaletteFormat::Ase => { + let p = to_cms_palette(lib); + // Counted here, so the message is VectorCraft's own and its translations apply. + let entries = p.swatches.len() + p.groups.iter().map(|g| 1 + g.swatches.len()).sum::(); + if entries > ASE_MAX_ENTRIES { + return Err(format!( + "VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries}" + )); + } + return cms_palette::write_palette(&p, cms_palette::PaletteFormat::Ase); + } PaletteFormat::Css => write_css(lib, keep), }; Ok(text.into_bytes()) diff --git a/crates/color/src/palette_io/tests.rs b/crates/color/src/palette_io/tests.rs index 0e6adb90ed..43f7ae79cc 100644 --- a/crates/color/src/palette_io/tests.rs +++ b/crates/color/src/palette_io/tests.rs @@ -2,12 +2,11 @@ use super::*; use crate::{Gradient, GradientPaint, GradientStop}; use proptest::prelude::*; -// The swatch exchange file's signature, block types and entry cap, which craft-cms keeps private. +// The swatch exchange file's signature and block types, which craft-cms keeps private. const ASE_SIGNATURE: &[u8] = b"ASEF"; const ASE_GROUP_START: u16 = 0xC001; const ASE_GROUP_END: u16 = 0xC002; const ASE_COLOR: u16 = 0x0001; -const ASE_MAX_ENTRIES: usize = 100_000; #[test] fn gpl_blank_name_keeps_fallback() { From 6d8674bde82401fd13351e306c1aa3106751973b Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 19 Nov 2026 08:21:29 +0700 Subject: [PATCH 11/13] Revert "Merge pull request #8635 from storytold/fix/ase-cap" This reverts commit fc2a525ee1c842a4eabbd9c822615c2147f78cac, reversing changes made to bab45a99f32a97be6668d89fea729ac962713c57. --- crates/color/src/palette_io.rs | 16 +--------------- crates/color/src/palette_io/tests.rs | 3 ++- 2 files changed, 3 insertions(+), 16 deletions(-) diff --git a/crates/color/src/palette_io.rs b/crates/color/src/palette_io.rs index 1709fb57c8..cb8e0b3950 100644 --- a/crates/color/src/palette_io.rs +++ b/crates/color/src/palette_io.rs @@ -114,10 +114,6 @@ fn swatches_from_cms(list: Vec) -> Vec { list.into_iter().map(|w| Swatch { name: w.name, paint: Paint::solid(color_from_cms(w.color)), global: w.global, spot: w.spot }).collect() } -/// The most colors and groups one swatch exchange file holds, read or written (craft-cms reads -/// as many). -const ASE_MAX_ENTRIES: usize = 100_000; - fn to_cms_palette(lib: &SwatchLibrary) -> Palette { Palette { name: lib.name.clone(), @@ -152,17 +148,7 @@ pub fn write(lib: &SwatchLibrary, format: PaletteFormat) -> Result, Stri serde_json::to_string_pretty(&file).unwrap_or_default() } PaletteFormat::Gpl => return cms_palette::write_palette(&to_cms_palette(lib), cms_palette::PaletteFormat::Gpl), - PaletteFormat::Ase => { - let p = to_cms_palette(lib); - // Counted here, so the message is VectorCraft's own and its translations apply. - let entries = p.swatches.len() + p.groups.iter().map(|g| 1 + g.swatches.len()).sum::(); - if entries > ASE_MAX_ENTRIES { - return Err(format!( - "VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries}" - )); - } - return cms_palette::write_palette(&p, cms_palette::PaletteFormat::Ase); - } + PaletteFormat::Ase => return cms_palette::write_palette(&to_cms_palette(lib), cms_palette::PaletteFormat::Ase), PaletteFormat::Css => write_css(lib, keep), }; Ok(text.into_bytes()) diff --git a/crates/color/src/palette_io/tests.rs b/crates/color/src/palette_io/tests.rs index 43f7ae79cc..0e6adb90ed 100644 --- a/crates/color/src/palette_io/tests.rs +++ b/crates/color/src/palette_io/tests.rs @@ -2,11 +2,12 @@ use super::*; use crate::{Gradient, GradientPaint, GradientStop}; use proptest::prelude::*; -// The swatch exchange file's signature and block types, which craft-cms keeps private. +// The swatch exchange file's signature, block types and entry cap, which craft-cms keeps private. const ASE_SIGNATURE: &[u8] = b"ASEF"; const ASE_GROUP_START: u16 = 0xC001; const ASE_GROUP_END: u16 = 0xC002; const ASE_COLOR: u16 = 0x0001; +const ASE_MAX_ENTRIES: usize = 100_000; #[test] fn gpl_blank_name_keeps_fallback() { From ed0fde6593c3dcd812a0e3eb3f08755ddc5d6a5c Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 19 Nov 2026 08:21:29 +0700 Subject: [PATCH 12/13] Revert "color: the palette tests define the swatch exchange constants craft-cms keeps private" This reverts commit 4e63316d9a93c893135c5cc0f08e96ddbc03eaf8. --- crates/color/src/palette_io/tests.rs | 7 ------- 1 file changed, 7 deletions(-) diff --git a/crates/color/src/palette_io/tests.rs b/crates/color/src/palette_io/tests.rs index 0e6adb90ed..bbbae16a53 100644 --- a/crates/color/src/palette_io/tests.rs +++ b/crates/color/src/palette_io/tests.rs @@ -2,13 +2,6 @@ use super::*; use crate::{Gradient, GradientPaint, GradientStop}; use proptest::prelude::*; -// The swatch exchange file's signature, block types and entry cap, which craft-cms keeps private. -const ASE_SIGNATURE: &[u8] = b"ASEF"; -const ASE_GROUP_START: u16 = 0xC001; -const ASE_GROUP_END: u16 = 0xC002; -const ASE_COLOR: u16 = 0x0001; -const ASE_MAX_ENTRIES: usize = 100_000; - #[test] fn gpl_blank_name_keeps_fallback() { let blank = "GIMP Palette\nName: \nColumns: 0\n#\n 1 2 3\tx\n"; From bd23b310ef1ee4f89c6b746e360908bc3f2bc83e Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 19 Nov 2026 08:21:30 +0700 Subject: [PATCH 13/13] Revert "color: cut over palette_io GPL/ASE/ACB to craft-cms (#8627)" This reverts commit 0087be0452c90653cf73a076e26c65170b861f48. --- Cargo.lock | 10 - Cargo.toml | 1 - crates/color/Cargo.toml | 1 - crates/color/src/palette_io.rs | 502 +++++++++++++++++++++++++++++---- 4 files changed, 450 insertions(+), 64 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e7a0ffe1c3..0d32cc52e4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1009,15 +1009,6 @@ dependencies = [ "ruzstd", ] -[[package]] -name = "craft-cms" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e7873217287876f76a045550369c90a541693c33#e7873217287876f76a045550369c90a541693c33" -dependencies = [ - "md-5", - "rayon", -] - [[package]] name = "craft-codepage" version = "0.1.0" @@ -6736,7 +6727,6 @@ dependencies = [ name = "vectorcraft-color" version = "0.24.1" dependencies = [ - "craft-cms", "kurbo 0.13.1", "moxcms", "proptest", diff --git a/Cargo.toml b/Cargo.toml index c33e3b1cfc..6d2ab9e37b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,7 +11,6 @@ rust-version = "1.95" repository = "https://github.com/storytold/vectorcraft" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "e7873217287876f76a045550369c90a541693c33" } craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", default-features = false, features = ["interpret", "write"] } craft-print = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } diff --git a/crates/color/Cargo.toml b/crates/color/Cargo.toml index 1273b5d0ad..a007ede39f 100644 --- a/crates/color/Cargo.toml +++ b/crates/color/Cargo.toml @@ -9,7 +9,6 @@ description = "VectorCraft color" workspace = true [dependencies] -craft-cms = { workspace = true } kurbo = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } diff --git a/crates/color/src/palette_io.rs b/crates/color/src/palette_io.rs index cb8e0b3950..9be00b4b21 100644 --- a/crates/color/src/palette_io.rs +++ b/crates/color/src/palette_io.rs @@ -6,8 +6,6 @@ use std::collections::{HashMap, HashSet}; -pub use craft_cms::palette::css_property; -use craft_cms::palette::{self as cms_palette, Palette, PaletteColor, PaletteGroup, PaletteSwatch}; use serde::{Deserialize, Serialize}; use crate::{Color, GradientKind, Paint, Swatch, SwatchGroup, SwatchLibrary}; @@ -85,50 +83,18 @@ struct NativeFile { const NATIVE_FORMAT: &str = "vcswatches"; const GPL_HEADER: &str = "GIMP Palette"; - -fn color_to_cms(c: Color) -> PaletteColor { - match c { - Color::Rgb { r, g, b } => PaletteColor::Rgb { r, g, b }, - Color::Cmyk { c, m, y, k } => PaletteColor::Cmyk { c, m, y, k }, - Color::Lab { l, a, b } => PaletteColor::Lab { l, a, b }, - Color::Gray { k } => PaletteColor::Gray { k }, - } -} - -fn color_from_cms(c: PaletteColor) -> Color { - match c { - PaletteColor::Rgb { r, g, b } => Color::rgb(r, g, b), - PaletteColor::Cmyk { c, m, y, k } => Color::cmyk(c, m, y, k), - PaletteColor::Lab { l, a, b } => Color::lab(l, a, b), - PaletteColor::Gray { k } => Color::gray(k), - } -} - -fn swatches_to_cms(list: &[Swatch]) -> Vec { - list.iter() - .filter_map(|w| w.paint.color().map(|c| PaletteSwatch { name: w.name.clone(), color: color_to_cms(c), global: w.global, spot: w.spot })) - .collect() -} - -fn swatches_from_cms(list: Vec) -> Vec { - list.into_iter().map(|w| Swatch { name: w.name, paint: Paint::solid(color_from_cms(w.color)), global: w.global, spot: w.spot }).collect() -} - -fn to_cms_palette(lib: &SwatchLibrary) -> Palette { - Palette { - name: lib.name.clone(), - swatches: swatches_to_cms(&lib.swatches), - groups: lib.groups.iter().map(|g| PaletteGroup { name: g.name.clone(), swatches: swatches_to_cms(&g.swatches) }).collect(), - } -} - -fn from_cms_palette(p: Palette) -> SwatchLibrary { - SwatchLibrary { - name: p.name, - swatches: swatches_from_cms(p.swatches), - groups: p.groups.into_iter().map(|g| SwatchGroup { name: g.name, swatches: swatches_from_cms(g.swatches) }).collect(), - } -} +const GPL_GROUP: &str = "# Group:"; +const ASE_SIGNATURE: &[u8] = b"ASEF"; +const ASE_GROUP_START: u16 = 0xC001; +const ASE_GROUP_END: u16 = 0xC002; +const ASE_COLOR: u16 = 0x0001; +/// The most colors and groups read from one `.ase` file. +const ASE_MAX_ENTRIES: usize = 100_000; +/// The most UTF-16 code units of a name that are kept. +const ASE_MAX_NAME: usize = 1024; +const ASE_CUT_SHORT: &str = "the swatch exchange file is cut short"; +const ACB_SIGNATURE: &[u8] = b"8BCB"; +const ACB_CUT_SHORT: &str = "the color book is cut short"; /// Write `lib` in `format` → the file's bytes. Pattern swatches (their tiles live in a document) /// and None are left out; `.gpl` keeps solid colours only, as 8-bit RGB, and `.ase` keeps solid @@ -147,8 +113,8 @@ pub fn write(lib: &SwatchLibrary, format: PaletteFormat) -> Result, Stri let file = NativeFile { format: NATIVE_FORMAT.into(), version: 1, library }; serde_json::to_string_pretty(&file).unwrap_or_default() } - PaletteFormat::Gpl => return cms_palette::write_palette(&to_cms_palette(lib), cms_palette::PaletteFormat::Gpl), - PaletteFormat::Ase => return cms_palette::write_palette(&to_cms_palette(lib), cms_palette::PaletteFormat::Ase), + PaletteFormat::Gpl => write_gpl(lib), + PaletteFormat::Ase => return write_ase(lib), PaletteFormat::Css => write_css(lib, keep), }; Ok(text.into_bytes()) @@ -159,6 +125,49 @@ fn one_line(s: &str) -> String { s.split(['\n', '\r', '\t']).collect::>().join(" ").trim().to_string() } +fn write_gpl(lib: &SwatchLibrary) -> String { + let mut out = format!("{GPL_HEADER}\nName: {}\nColumns: 0\n#\n", one_line(&lib.name)); + let colors = |out: &mut String, list: &[Swatch]| { + for w in list { + if let Some(c) = w.paint.color() { + let [r, g, b, _] = c.to_rgba8(1.0); + out.push_str(&format!("{r:3} {g:3} {b:3}\t{}\n", one_line(&w.name))); + } + } + }; + colors(&mut out, &lib.swatches); + for g in &lib.groups { + out.push_str(&format!("{GPL_GROUP} {}\n", one_line(&g.name))); + colors(&mut out, &g.swatches); + } + out +} + +/// `name` as a CSS custom property (`--` and an escaped identifier): lower case, spaces as +/// hyphens, other characters an identifier can't hold escaped with a backslash. +pub fn css_property(name: &str) -> String { + let mut out = String::from("--"); + for word in name.split_whitespace() { + if out.len() > 2 { + out.push('-'); + } + for ch in word.chars().flat_map(char::to_lowercase) { + if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' || !ch.is_ascii() { + out.push(ch); + } else if ch.is_ascii_graphic() { + out.push('\\'); + out.push(ch); + } else { + out.push_str(&format!("\\{:x} ", ch as u32)); + } + } + } + if out.len() == 2 { + out.push_str("swatch"); + } + out +} + /// A colour as CSS (`#rrggbb`, or `#rrggbbaa` below full opacity). fn css_color(c: &Color, opacity: f32) -> String { let [r, g, b, a] = c.to_rgba8(opacity); @@ -267,10 +276,97 @@ fn write_css(lib: &SwatchLibrary, keep: impl Fn(&&Swatch) -> bool) -> String { /// a tint swatch is written as the color it shows, a process color without its link to its base. /// The file has no library name ([`read_ase`] names a library after its file). More than /// [`ASE_MAX_ENTRIES`] colors and groups is an error. +fn write_ase(lib: &SwatchLibrary) -> Result, String> { + let solid = |list: &[Swatch]| list.iter().filter(|w| w.paint.color().is_some()).count(); + let entries = solid(&lib.swatches) + lib.groups.iter().map(|g| 1 + solid(&g.swatches)).sum::(); + if entries > ASE_MAX_ENTRIES { + return Err(format!( + "VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries}" + )); + } + let mut body = vec![]; + let mut blocks = put_ase_colors(&mut body, &lib.swatches)?; + for g in &lib.groups { + let mut name = vec![]; + put_ase_name(&mut name, &g.name)?; + put_ase_block(&mut body, ASE_GROUP_START, &name)?; + blocks += 2 + put_ase_colors(&mut body, &g.swatches)?; + put_ase_block(&mut body, ASE_GROUP_END, &[])?; + } + let blocks = u32::try_from(blocks).map_err(|_| "too many swatch exchange blocks".to_string())?; + let mut out = ASE_SIGNATURE.to_vec(); + out.extend(1u16.to_be_bytes()); + out.extend(0u16.to_be_bytes()); + out.extend(blocks.to_be_bytes()); + out.extend(body); + Ok(out) +} + +/// The color blocks of the solid colors in `list` → how many were written. +fn put_ase_colors(out: &mut Vec, list: &[Swatch]) -> Result { + let unit = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; + let ab = |v: f32| if v.is_finite() { v.clamp(-128.0, 127.0) } else { 0.0 }; + let mut n = 0; + for (w, color) in list.iter().filter_map(|w| Some((w, w.paint.color()?))) { + let mut body = vec![]; + put_ase_name(&mut body, &w.name)?; + let (model, values): (&[u8; 4], Vec) = match color { + Color::Rgb { r, g, b } => (b"RGB ", vec![unit(r), unit(g), unit(b)]), + Color::Cmyk { c, m, y, k } => (b"CMYK", vec![unit(c), unit(m), unit(y), unit(k)]), + Color::Lab { l, a, b } => (b"LAB ", vec![unit(l / 100.0), ab(a), ab(b)]), + Color::Gray { k } => (b"Gray", vec![1.0 - unit(k)]), + }; + body.extend(model); + body.extend(values.iter().flat_map(|v| v.to_be_bytes())); + let kind: u16 = if w.spot { + 1 + } else if w.global { + 0 + } else { + 2 + }; + body.extend(kind.to_be_bytes()); + put_ase_block(out, ASE_COLOR, &body)?; + n += 1; + } + Ok(n) +} + +/// A block: its type, the length of its body and the body. +fn put_ase_block(out: &mut Vec, kind: u16, body: &[u8]) -> Result<(), String> { + let len = u32::try_from(body.len()).map_err(|_| "a swatch exchange block is too long".to_string())?; + out.extend(kind.to_be_bytes()); + out.extend(len.to_be_bytes()); + out.extend_from_slice(body); + Ok(()) +} + +/// A name as `.ase` stores it: a `u16` count of UTF-16 code units, the terminating zero included, +/// then the units. NUL characters are left out, and a name longer than [`ASE_MAX_NAME`] code units +/// is cut before the character that would pass that limit. +fn put_ase_name(out: &mut Vec, name: &str) -> Result<(), String> { + let mut units: Vec = vec![]; + for c in name.chars().filter(|&c| c != '\0') { + let mut buf = [0; 2]; + let encoded = c.encode_utf16(&mut buf); + if units.len() + encoded.len() > ASE_MAX_NAME { + break; + } + units.extend_from_slice(encoded); + } + units.push(0); + let count = u16::try_from(units.len()).map_err(|_| "a swatch exchange name is too long".to_string())?; + out.extend(count.to_be_bytes()); + out.extend(units.iter().flat_map(|u| u.to_be_bytes())); + Ok(()) +} + +/// Read a `.vcswatches` or `.gpl` library (detected from its content). `name` names it when the +/// file doesn't. pub fn read(text: &str, name: &str) -> Result { let text = text.trim_start_matches('\u{feff}').trim_start(); if text.starts_with(GPL_HEADER) { - return cms_palette::read_palette(text.as_bytes(), name).map(from_cms_palette); + return Ok(read_gpl(text, name)); } if text.starts_with('{') { let f: NativeFile = serde_json::from_str(text).map_err(|e| format!("not a swatch library: {e}"))?; @@ -295,8 +391,11 @@ pub fn sniff(text: &str) -> bool { /// Read the bytes of a library file: a swatch exchange `.ase` file, else a `.vcswatches` or /// `.gpl` library ([`read`]). `name` names it when the file doesn't. pub fn read_bytes(bytes: &[u8], name: &str) -> Result { - if cms_palette::sniff_palette(bytes) { - return cms_palette::read_palette(bytes, name).map(from_cms_palette); + if bytes.starts_with(ASE_SIGNATURE) { + return read_ase(bytes, name); + } + if bytes.starts_with(ACB_SIGNATURE) { + return read_acb(bytes, name).map_err(|e| if e == ASE_CUT_SHORT { ACB_CUT_SHORT.into() } else { e }); } read(&String::from_utf8_lossy(bytes), name) } @@ -304,10 +403,309 @@ pub fn read_bytes(bytes: &[u8], name: &str) -> Result { /// Are `bytes` a library [`read_bytes`] understands? Text that isn't valid UTF-8 is checked as /// [`read_bytes`] reads it, with the invalid bytes replaced (its first KiB is enough). pub fn sniff_bytes(bytes: &[u8]) -> bool { - cms_palette::sniff_palette(bytes) + bytes.starts_with(ASE_SIGNATURE) + || bytes.starts_with(ACB_SIGNATURE) || std::str::from_utf8(bytes).is_ok_and(sniff) || sniff(&String::from_utf8_lossy(bytes.get(..1024).unwrap_or(bytes))) } +/// `.gpl`: `Name:` names the library, `# Group: name` starts a colour group, other `#` lines and +/// headers (`Columns:`) are skipped, as are lines that aren't `r g b [name]`. Unnamed colors are +/// named by their values and unnamed groups "Color Group"; a name a color or group already has gets +/// a number ([`UniqueNames`]). +fn read_gpl(text: &str, fallback: &str) -> SwatchLibrary { + let mut lib = SwatchLibrary { name: fallback.into(), ..Default::default() }; + let mut names = UniqueNames::default(); + for line in text.lines().skip(1) { + let line = line.trim(); + if let Some(g) = line.strip_prefix(GPL_GROUP) { + lib.groups.push(SwatchGroup { name: names.unique(group_name(g)), swatches: vec![] }); + continue; + } + if let Some(n) = line.strip_prefix("Name:") { + if !n.trim().is_empty() { + lib.name = n.trim().to_string(); + } + continue; + } + // Comments, headers (`Columns: 4`) and anything else that isn't a colour are skipped. + let words: Vec<&str> = line.split_whitespace().collect(); + let rgb: Vec = words.iter().take(3).map_while(|v| v.parse().ok()).collect(); + let [r, g, b] = rgb[..] else { continue }; + let rest = words[3..].join(" "); + let base = if rest.is_empty() { format!("R={r} G={g} B={b}") } else { rest }; + let w = Swatch { name: names.unique(base), paint: Paint::solid(Color::rgb8(r, g, b)), global: false, spot: false }; + match lib.groups.last_mut() { + Some(grp) => grp.swatches.push(w), + None => lib.swatches.push(w), + } + } + lib +} + +/// `.ase`, from public descriptions of the format: the layout from +/// , the component ranges from +/// . After the signature come, big-endian, a `u16` major (1) and +/// minor version, a `u32` block count and the blocks, each a `u16` type, a `u32` body length and +/// the body. A group start's body is a name. A color's body is a name, a four-character model +/// (`RGB `, `CMYK`, `LAB `, `Gray`), its components as `f32` (3, 4, 3 and 1 of them) and a `u16` +/// color type (0 global, 1 spot, 2 process). RGB, CMYK and gray components run from 0 to 1 (a +/// gray level of 1 is white), Lab lightness from 0 to 1 and a and b from −128 to 127. A lightness +/// above 1 is read as L* itself. A name is a `u16` count of UTF-16 code units, the terminating zero +/// included, then the units. +/// +/// Color groups become groups: a group start inside an open group ends that group, and a group +/// left open ends with the file. Blocks of other types and colors in other models are skipped. +/// Unnamed colors are named by their values and unnamed groups "Color Group"; a name a color or +/// group already has gets a number ([`UniqueNames`]). A truncated file, a major version other than +/// 1 or more than [`ASE_MAX_ENTRIES`] colors and groups is an error. +fn read_ase(bytes: &[u8], fallback: &str) -> Result { + let mut data = AseData(bytes); + data.bytes(ASE_SIGNATURE.len())?; + let (major, minor) = (data.u16()?, data.u16()?); + if major != 1 { + return Err(format!("swatch exchange version {major}.{minor} isn't supported (only 1.x)")); + } + let blocks = data.u32()?; + let mut lib = SwatchLibrary { name: fallback.into(), ..Default::default() }; + let mut names = UniqueNames::default(); + let (mut in_group, mut entries) = (false, 0usize); + for _ in 0..blocks { + let kind = data.u16()?; + let len = usize::try_from(data.u32()?).unwrap_or(usize::MAX); + let mut body = AseData(data.bytes(len)?); + if matches!(kind, ASE_GROUP_START | ASE_COLOR) { + entries += 1; + if entries > ASE_MAX_ENTRIES { + return Err(format!("the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups")); + } + } + match kind { + ASE_GROUP_START => { + lib.groups.push(SwatchGroup { name: names.unique(group_name(&body.name()?)), swatches: vec![] }); + in_group = true; + } + ASE_GROUP_END => in_group = false, + ASE_COLOR => { + let Some(mut w) = ase_swatch(&mut body)? else { continue }; + w.name = names.unique(std::mem::take(&mut w.name)); + match lib.groups.last_mut().filter(|_| in_group) { + Some(g) => g.swatches.push(w), + None => lib.swatches.push(w), + } + } + // Other blocks are skipped. + _ => {} + } + } + Ok(lib) +} + +/// `.acb` (a color book, read only), from public descriptions of the format: after the signature +/// come, big-endian, a `u16` version (1) and book id, the title, prefix, suffix and description +/// as strings, a `u16` color count, page size and page selector offset, a `u16` color space (0 +/// RGB, 2 CMYK, 7 Lab) and the colors: each a name, a six-character catalog code and its +/// components as bytes. RGB runs from 0 to 255, CMYK ink is stored inverted (255 is no ink), Lab +/// lightness is 0 to 255 for 0 to 100 and a and b are offset by 128. A string is a `u32` count of +/// UTF-16 code units, then the units; a `$$$/key=Text` string means `Text`, and `^R`, `^C` stand +/// for ® and ©. An optional `spflspot` or `spflproc` at the end says whether the colors are spot +/// or process colors (a book without it is a spot color book). +/// +/// The book's colors are named with its prefix and suffix ("PANTONE 185 C"); colors without a +/// name (the padding of a book's pages) are left out. A version other than 1, a color space other +/// than those three or more than [`ASE_MAX_ENTRIES`] colors is an error. +fn read_acb(bytes: &[u8], fallback: &str) -> Result { + let mut data = AseData(bytes); + data.bytes(ACB_SIGNATURE.len())?; + let version = data.u16()?; + if version != 1 { + return Err(format!("color book version {version} isn't supported (only 1)")); + } + let _book_id = data.u16()?; + let [title, prefix, suffix, _description] = [data.acb_string()?, data.acb_string()?, data.acb_string()?, data.acb_string()?]; + let count = usize::from(data.u16()?); + if count > ASE_MAX_ENTRIES { + return Err(format!("the color book holds more than {ASE_MAX_ENTRIES} colors")); + } + let (_page_size, _page_offset) = (data.u16()?, data.u16()?); + let space = data.u16()?; + let mut colors = Vec::with_capacity(count); + for _ in 0..count { + let name = data.acb_string()?; + let _code = data.bytes(6)?; + let color = match space { + 0 => { + let [r, g, b] = data.array::<3>()?; + Color::rgb8(r, g, b) + } + 2 => { + let ink = |v: u8| f32::from(255 - v) / 255.0; + let [c, m, y, k] = data.array::<4>()?; + Color::cmyk(ink(c), ink(m), ink(y), ink(k)) + } + 7 => { + let [l, a, b] = data.array::<3>()?; + Color::lab(f32::from(l) * 100.0 / 255.0, f32::from(a) - 128.0, f32::from(b) - 128.0) + } + other => return Err(format!("color books in color space {other} aren't supported (only RGB, CMYK and Lab)")), + }; + colors.push((name, color)); + } + // Spot colors unless the book says process ones. + let spot = data.0.windows(8).last() != Some(b"spflproc".as_slice()); + let mut lib = SwatchLibrary { name: if title.is_empty() { fallback.into() } else { title }, ..Default::default() }; + let mut names = UniqueNames::default(); + // Every name gets the prefix and the suffix, and is kept twice (the swatch's and the set of + // names taken): a megabyte book of long affixes and many colors came to hundreds of MB. + let mut kept = 0usize; + for (name, color) in colors.into_iter().filter(|(n, _)| !n.trim().is_empty()) { + kept = kept.saturating_add(2 * (prefix.len() + name.len() + suffix.len())); + if kept > ACB_MAX_NAME_BYTES { + return Err(format!("the color book's names take more than {} MB", ACB_MAX_NAME_BYTES >> 20)); + } + let name = names.unique(format!("{prefix}{name}{suffix}").trim().to_string()); + lib.swatches.push(Swatch { name, paint: Paint::solid(color), global: spot, spot }); + } + Ok(lib) +} + +/// Most bytes a color book's full color names (with its prefix and suffix) may take, counted +/// twice as they are kept twice. +const ACB_MAX_NAME_BYTES: usize = 64 << 20; + +/// The swatch of an `.ase` color block, `None` for a model other than RGB, CMYK, Lab and Gray. +/// Components are clamped to their ranges. +fn ase_swatch(body: &mut AseData) -> Result, String> { + let name = body.name()?; + let unit = |v: f32| v.clamp(0.0, 1.0); + let color = match &body.array::<4>()? { + b"RGB " => { + let [r, g, b] = [body.f32()?, body.f32()?, body.f32()?]; + Color::rgb(unit(r), unit(g), unit(b)) + } + b"CMYK" => { + let [c, m, y, k] = [body.f32()?, body.f32()?, body.f32()?, body.f32()?]; + Color::cmyk(unit(c), unit(m), unit(y), unit(k)) + } + // Lightness is stored as a fraction of 100. Some writers store L* itself, which shows as a + // value above 1. + b"LAB " => { + let [l, a, b] = [body.f32()?, body.f32()?, body.f32()?]; + let l = if l > 1.0 { l.min(100.0) } else { unit(l) * 100.0 }; + Color::lab(l, a.clamp(-128.0, 127.0), b.clamp(-128.0, 127.0)) + } + // A gray level (1 is white); a gray color holds its ink. + b"Gray" => Color::gray(1.0 - unit(body.f32()?)), + _ => return Ok(None), + }; + // Some writers leave the color type out, which makes a process color. + let kind = if body.0.len() >= 2 { body.u16()? } else { 2 }; + // Spot colors are global. + let (global, spot) = match kind { + 0 => (true, false), + 1 => (true, true), + _ => (false, false), + }; + let name = if name.is_empty() { value_name(color) } else { name }; + Ok(Some(Swatch { name, paint: Paint::solid(color), global, spot })) +} + +/// A color's values in its own model, as new swatches are named ("C=10 M=20 Y=30 K=0", +/// "R=255 G=128 B=0", "Gray K=40", "L=52 a=70 b=-30"). +fn value_name(c: Color) -> String { + let pct = |v: f32| (v * 100.0).round(); + let byte = |v: f32| (v * 255.0).round(); + match c { + Color::Cmyk { c, m, y, k } => format!("C={} M={} Y={} K={}", pct(c), pct(m), pct(y), pct(k)), + Color::Rgb { r, g, b } => format!("R={} G={} B={}", byte(r), byte(g), byte(b)), + Color::Gray { k } => format!("Gray K={}", pct(k)), + // `+ 0.0` turns a rounded -0 into 0. + Color::Lab { l, a, b } => format!("L={} a={} b={}", l.round() + 0.0, a.round() + 0.0, b.round() + 0.0), + } +} + +/// `.ase` data, read field by field; reading past its end is an error. +struct AseData<'a>(&'a [u8]); + +impl<'a> AseData<'a> { + fn bytes(&mut self, n: usize) -> Result<&'a [u8], String> { + let (head, rest) = self.0.split_at_checked(n).ok_or(ASE_CUT_SHORT)?; + self.0 = rest; + Ok(head) + } + fn array(&mut self) -> Result<[u8; N], String> { + let (head, rest) = self.0.split_first_chunk::().ok_or(ASE_CUT_SHORT)?; + self.0 = rest; + Ok(*head) + } + fn u16(&mut self) -> Result { + self.array().map(u16::from_be_bytes) + } + fn u32(&mut self) -> Result { + self.array().map(u32::from_be_bytes) + } + /// A component; one that isn't a finite number reads as 0. + fn f32(&mut self) -> Result { + let v = f32::from_be_bytes(self.array()?); + Ok(if v.is_finite() { v } else { 0.0 }) + } + /// A color book string ([`read_acb`]): a `u32` count of UTF-16 code units, then the units, + /// with `$$$/key=Text` read as `Text` and `^R`, `^C` as ®, ©; at most [`ASE_MAX_NAME`] units + /// are kept. + fn acb_string(&mut self) -> Result { + let n = usize::try_from(self.u32()?).unwrap_or(usize::MAX); + let (units, _) = self.bytes(n.checked_mul(2).ok_or(ASE_CUT_SHORT)?)?.as_chunks::<2>(); + let units: Vec = units.iter().take(ASE_MAX_NAME).map(|u| u16::from_be_bytes(*u)).take_while(|&u| u != 0).collect(); + let s = String::from_utf16_lossy(&units); + let s = match s.strip_prefix("$$$/") { + Some(key) => key.split_once('=').map_or("", |(_, text)| text).to_string(), + None => s, + }; + Ok(s.replace("^R", "®").replace("^C", "©")) + } + /// A name up to its terminating zero, trimmed. A block that ends before it has no name. + fn name(&mut self) -> Result { + if self.0.is_empty() { + return Ok(String::new()); + } + let n = usize::from(self.u16()?); + let (units, _) = self.bytes(n * 2)?.as_chunks::<2>(); + let units: Vec = units.iter().take(ASE_MAX_NAME).map(|u| u16::from_be_bytes(*u)).take_while(|&u| u != 0).collect(); + Ok(String::from_utf16_lossy(&units).trim().to_string()) + } +} + +/// A group's name as a file gives it, trimmed; "Color Group" when it has none. +fn group_name(name: &str) -> String { + let name = name.trim(); + if name.is_empty() { "Color Group".into() } else { name.to_string() } +} + +/// The swatch and group names a reader has handed out. Swatches and color groups share one set of +/// names, as in a document, and a name already taken gets the first free number ("Black 2"). +#[derive(Default)] +struct UniqueNames { + taken: HashSet, + /// The last number tried for each repeated name. + last: HashMap, +} + +impl UniqueNames { + fn unique(&mut self, base: String) -> String { + if self.taken.insert(base.clone()) { + return base; + } + // Each pass tries the next number, and only finitely many names are taken. + let n = self.last.entry(base.clone()).or_insert(1); + loop { + *n += 1; + let name = format!("{base} {n}"); + if self.taken.insert(name.clone()) { + return name; + } + } + } +} + #[cfg(test)] mod tests;