Merge main into fix/canvas-process-swatch-source-color

This commit is contained in:
dotCooCoo
2026-11-26 11:16:35 -08:00
39 changed files with 4247 additions and 24 deletions
+9
View File
@@ -16,6 +16,15 @@
| `crates/text/patterns/hyph-or.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-or.tex | MIT (selected option) | Unmodified; full license in file |
| `crates/text/patterns/hyph-as.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-as.tex | MIT (selected option) | Unmodified; full license in file |
## Printing-condition characterization data
Fogra's terms (https://fogra.org/en/downloads/work-tools/characterisation-data): "Free use and redistribution of the Fogra characterisation data is permitted, including redistribution as part of commercial and non-commercial software, provided that the data are distributed unmodified and Fogra is identified as the source. The designation FOGRAxx may be used solely to identify the respective reference data. Such use does not imply certification, approval or endorsement by Fogra." VectorCraft computes its Coated CMYK (FOGRA51) and Uncoated CMYK (FOGRA52) working spaces from these files at run time; the files themselves are not changed.
| Asset | Author | Source | Licence | Notes |
|---|---|---|---|---|
| `crates/color/data/FOGRA51.txt` | Fogra Forschungsgesellschaft Druck e.V. (www.fogra.org) | https://fogra.org/fileadmin/files/7_downloads/Charakterisierungsdaten/F51-52.zip | Fogra characterization data terms (above): redistribution of the unmodified data with Fogra named as the source | Unmodified, byte for byte (SHA-256 `ad472a1c0bdafd558597ff93eeda5175805086565af814cb6346e910e2f25aa5`, checked by a test) |
| `crates/color/data/FOGRA52.txt` | Fogra Forschungsgesellschaft Druck e.V. (www.fogra.org) | https://fogra.org/fileadmin/files/7_downloads/Charakterisierungsdaten/F51-52.zip | Fogra characterization data terms (above): redistribution of the unmodified data with Fogra named as the source | Unmodified, byte for byte (SHA-256 `be4f0732328ed62ade63ec7f317d3b9e9dad6bbe2430fefddaf0f901d5ba13d6`, checked by a test) |
Every non-code asset in this repository (icons, images, fonts, example art, colour profiles, presets) is listed here with its author, source and licence. `cargo xtask assets` (part of `cargo xtask ci`) fails if an asset file is missing from this table.
**Policy (mandatory):** VectorCraft contains **no Adobe iconography, images, artwork, presets, swatch/brush/symbol/pattern libraries or ICC profiles**. Every asset is either original work by VectorCraft contributors, or third-party material under an open licence (OSI open source, public domain / CC0, or Creative Commons that allows redistribution), and it is attributed below. Screenshots of Adobe software are never committed. The one exception is the ArtCraft name, wordmark and logos in `docs/brand/`: ArtCraft trademarks, not open source, usable only under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt).
Generated
+1
View File
@@ -8480,6 +8480,7 @@ dependencies = [
"proptest",
"serde",
"serde_json",
"sha2 0.10.9",
"thiserror 2.0.21",
]
+11
View File
@@ -152,6 +152,17 @@ Copyright (C) 2016 Santhosh Thottingal, used under the MIT license option.
Original copyright and full license notices are preserved in each hyph-*.tex file.
Source: hyphenation/tex-hyphen, commit 5684c0f51c0b81133db2efbe60a408b4155a3ff5.
FOGRA51 and FOGRA52 characterization data (crates/color/data/):
Source: Fogra Forschungsgesellschaft Druck e.V., www.fogra.org,
https://fogra.org/en/downloads/work-tools/characterisation-data. The files are distributed
unmodified. Fogra's terms: "Free use and redistribution of the Fogra characterisation data is
permitted, including redistribution as part of commercial and non-commercial software, provided
that the data are distributed unmodified and Fogra is identified as the source. The designation
FOGRAxx may be used solely to identify the respective reference data. Such use does not imply
certification, approval or endorsement by Fogra." VectorCraft's Coated CMYK (FOGRA51) and
Uncoated CMYK (FOGRA52) working spaces are computed from this data by VectorCraft's own code;
they are not Fogra profiles.
JPEG encoder dependency notices
+1
View File
@@ -22,3 +22,4 @@ moxcms = "0.8"
[dev-dependencies]
proptest = { workspace = true }
serde_json = { workspace = true }
sha2 = { version = "0.10", default-features = false }
+2
View File
@@ -0,0 +1,2 @@
# The characterization data files are kept byte for byte as published (CRLF line endings).
*.txt -text
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+41 -6
View File
@@ -5,7 +5,9 @@
//! (1998 primaries), Display P3, ProPhoto RGB) or user `.icc` files. Display output is sRGB;
//! the desktop canvas converts it into the display's own profile last, in the app.
//! * **CMYK spaces:** [`GENERIC_CMYK`] is our own documented parametric press model
//! ([`generic`]); [`DEVICE_CMYK`] is the old profile-free formula (kept for exact legacy numbers);
//! ([`generic`]); [`FOGRA51_CMYK`] and [`FOGRA52_CMYK`] are the same model computed from
//! Fogra's published characterization data ([`measured`]); [`DEVICE_CMYK`] is the old
//! profile-free formula (kept for exact legacy numbers);
//! any CMYK `.icc` the user loads goes through `moxcms` (LUT-based profiles).
//! * The **active settings** are process-wide: the working settings (Edit → Color Settings), with
//! the profiles [`use_document_profiles`] last put in place of the working spaces;
@@ -16,6 +18,7 @@
pub mod generic;
pub mod icc;
pub mod lab;
pub mod measured;
use std::cell::{Cell, RefCell};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
@@ -36,6 +39,12 @@ pub const DISPLAY_P3: &str = "Display P3";
pub const PROPHOTO_RGB: &str = "ProPhoto RGB";
/// Our parametric press model (see [`generic`]). Not an Adobe/ECI profile.
pub const GENERIC_CMYK: &str = "VectorCraft Generic CMYK (SWOP-like)";
/// VectorCraft's own press model computed from Fogra's FOGRA51 characterization data (offset on
/// premium coated paper, see [`measured`]).
pub const FOGRA51_CMYK: &str = "VectorCraft Coated CMYK (FOGRA51)";
/// VectorCraft's own press model computed from Fogra's FOGRA52 characterization data (offset on
/// wood-free uncoated paper, see [`measured`]).
pub const FOGRA52_CMYK: &str = "VectorCraft Uncoated CMYK (FOGRA52)";
/// Profile-free CMYK (`rgb = (1−c)(1−k)` …): uncalibrated, kept for legacy numbers.
pub const DEVICE_CMYK: &str = "Device CMYK (uncalibrated)";
/// The grey space greyscale exports are written in: sRGB's tone curve (a grey shows as on screen).
@@ -43,7 +52,7 @@ pub const GRAY: &str = "Gray (sRGB tone curve)";
/// Built-in RGB and CMYK working spaces, in menu order.
const BUILTIN_RGB: [&str; 4] = [SRGB, WIDE_GAMUT_RGB, DISPLAY_P3, PROPHOTO_RGB];
const BUILTIN_CMYK: [&str; 2] = [GENERIC_CMYK, DEVICE_CMYK];
const BUILTIN_CMYK: [&str; 4] = [GENERIC_CMYK, FOGRA51_CMYK, FOGRA52_CMYK, DEVICE_CMYK];
/// Names earlier versions gave built-in profiles: (old name, current name). Settings, documents
/// and commands that still use an old name get the current profile.
@@ -239,6 +248,21 @@ fn generic() -> Arc<GenericCmyk> {
G.get_or_init(|| Arc::new(GenericCmyk::new(generic::swop_like()))).clone()
}
/// The working space of `condition`, computed from its data once and kept.
fn measured_space(condition: &measured::Condition) -> Result<Arc<GenericCmyk>, CmsError> {
static SPACES: [OnceLock<Option<Arc<GenericCmyk>>>; measured::CONDITIONS.len()] = [const { OnceLock::new() }; measured::CONDITIONS.len()];
let slot = measured::CONDITIONS.iter().position(|c| c.name == condition.name).and_then(|i| SPACES.get(i));
slot.and_then(|s| s.get_or_init(|| measured::model(condition).map(Arc::new)).clone())
.ok_or_else(|| CmsError::BadProfile(format!("{}: the {} data does not give a press model", condition.name, condition.reference)))
}
/// The registered printing condition a built-in CMYK working space characterizes: its reference
/// name, the `/OutputConditionIdentifier` of a PDF/X output intent, and the registry it belongs
/// to (by its current or legacy name). `None` for every other profile.
pub fn characterization(name: &str) -> Option<(&'static str, &'static str)> {
measured::condition(canonical_name(name)).map(|c| (c.reference, measured::REGISTRY))
}
static USER: RwLock<Vec<Arc<IccProfile>>> = RwLock::new(Vec::new());
/// Counts the profiles [`register_icc`] has registered ([`profiles_generation`]).
static PROFILES_GENERATION: AtomicU64 = AtomicU64::new(0);
@@ -259,7 +283,11 @@ fn user_profile(name: &str) -> Option<Arc<IccProfile>> {
}
fn cmyk_space(name: &str) -> Result<CmykSpace, CmsError> {
match canonical_name(name) {
let canonical = canonical_name(name);
if let Some(c) = measured::condition(canonical) {
return measured_space(c).map(CmykSpace::Generic);
}
match canonical {
GENERIC_CMYK => Ok(CmykSpace::Generic(generic())),
DEVICE_CMYK => Ok(CmykSpace::Device),
_ => match user_profile(name) {
@@ -382,9 +410,13 @@ pub fn icc_bytes(name: &str) -> Result<Arc<[u8]>, CmsError> {
CmykSpace::Generic(g) => g.paper_xyz(),
CmykSpace::Device | CmykSpace::Icc(_) => lab::D50,
};
let copyright = match measured::condition(name) {
Some(c) => format!("Computed by VectorCraft from the {} characterization data. Data source: Fogra, www.fogra.org", c.reference),
None => icc::NO_COPYRIGHT.to_string(),
};
let to_lab = |c| cms.cmyk_to_lab(c);
let shadows = |l| mapped.lab_to_cmyk(l, Intent::RelativeColorimetric);
icc::encode(&icc::cmyk_profile(name, paper, to_lab, shadows, |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))?
icc::encode(&icc::cmyk_profile(name, paper, &copyright, to_lab, shadows, |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))?
} else {
icc::builtin_rgb_bytes(name)?
}
@@ -496,7 +528,8 @@ impl Cms {
/// directly into the RGB profile: not through display sRGB, which would clip colours a wider
/// RGB space holds (Wide Gamut RGB keeps CMYK cyan that sRGB can't show), and with the
/// settings' black-point compensation. The built-in CMYK spaces go through sRGB as before
/// (Generic CMYK compensates in its own model).
/// (Generic CMYK compensates in its own model); with the absolute colorimetric intent the
/// paper colour shows.
pub fn cmyk_to_rgb(&self, cmyk: [f32; 4], intent: Intent) -> [f32; 3] {
let cmyk = cmyk.map(|v| v.clamp(0.0, 1.0));
let src = match &self.cmyk {
@@ -509,7 +542,7 @@ impl Cms {
};
src.zip(dest)
.and_then(|(s, d)| s.to_rgb_of(&d, &cmyk, intent, self.settings.bpc))
.unwrap_or_else(|| self.srgb_to_rgb(self.cmyk_to_srgb(cmyk, false)))
.unwrap_or_else(|| self.srgb_to_rgb(self.cmyk_to_srgb(cmyk, intent == Intent::AbsoluteColorimetric)))
}
/// Display sRGB → working CMYK with `intent`.
pub fn srgb_to_cmyk(&self, srgb: [f32; 3], intent: Intent) -> [f32; 4] {
@@ -1315,3 +1348,5 @@ pub(crate) fn cmyk_is_device() -> bool {
mod tests;
#[cfg(test)]
mod tests_icc;
#[cfg(test)]
mod tests_measured;
+30 -2
View File
@@ -30,6 +30,7 @@ use std::sync::OnceLock;
use super::Intent;
use super::lab::{D50, Lab, delta_e2000, lab_to_xyz, srgb_to_lab, xyz_to_lab, xyz_to_srgb};
use super::measured::Lattice;
/// Black generation.
#[derive(Clone, Copy, Debug, PartialEq)]
@@ -129,6 +130,9 @@ pub struct GenericCmyk {
paper_xyz: [f32; 3],
/// Media-relative XYZ of the black point (for black-point compensation).
black_rel: [f32; 3],
/// A media-relative Lab correction added to the model, fitted to measured data
/// ([`super::measured`]).
correction: Option<Lattice>,
gbd: OnceLock<Gbd>,
}
@@ -139,6 +143,15 @@ impl GenericCmyk {
}
pub fn new(params: GenericCmykParams) -> Self {
Self::build(params, None)
}
/// The model of `params` with `correction` added to its media-relative Lab.
pub fn with_correction(params: GenericCmykParams, correction: Lattice) -> Self {
Self::build(params, Some(correction))
}
fn build(params: GenericCmykParams, correction: Option<Lattice>) -> Self {
let paper_xyz = lab_to_xyz(params.paper);
let mut prim = [D50; 16];
for (p, lab) in prim[1..].iter_mut().zip(params.primaries.iter()) {
@@ -149,7 +162,7 @@ impl GenericCmyk {
let g = params.tvi50[i];
if g > 1e-6 { (1.0 - params.tvi40[i] / (0.96 * g)) / 0.2 } else { 0.0 }
});
let mut g = Self { params, prim, skew, paper_xyz, black_rel: [0.0; 3], gbd: OnceLock::new() };
let mut g = Self { params, prim, skew, paper_xyz, black_rel: [0.0; 3], correction, gbd: OnceLock::new() };
g.black_rel = g.to_xyz_rel(g.black_point_build());
g
}
@@ -218,6 +231,14 @@ impl GenericCmyk {
/// Media-relative XYZ (paper = D50 white).
pub fn to_xyz_rel(&self, cmyk: [f32; 4]) -> [f32; 3] {
match &self.correction {
Some(_) => lab_to_xyz(self.to_lab_rel(cmyk)),
None => self.neugebauer(cmyk),
}
}
/// Media-relative XYZ of the Neugebauer model alone.
fn neugebauer(&self, cmyk: [f32; 4]) -> [f32; 3] {
let e = [0, 1, 2, 3].map(|i| self.gain(i, cmyk[i]));
let mut out = [0.0f32; 3];
for (i, p) in self.prim.iter().enumerate() {
@@ -236,7 +257,14 @@ impl GenericCmyk {
}
pub fn to_lab_rel(&self, cmyk: [f32; 4]) -> Lab {
xyz_to_lab(self.to_xyz_rel(cmyk))
let lab = xyz_to_lab(self.neugebauer(cmyk));
match &self.correction {
Some(c) => {
let d = c.at(cmyk);
Lab::new((lab.l + d[0]).max(0.0), lab.a + d[1], lab.b + d[2])
}
None => lab,
}
}
pub fn to_lab_abs(&self, cmyk: [f32; 4]) -> Lab {
xyz_to_lab(self.to_xyz(cmyk))
+12 -4
View File
@@ -432,10 +432,17 @@ fn text_tag(s: &str) -> Option<ProfileText> {
Some(ProfileText::Localizable(vec![LocalizableString::new("en".into(), "US".into(), s.into())]))
}
/// The copyright text of profiles made here: they carry no copyright claim.
pub(super) const NO_COPYRIGHT: &str = "No copyright, use freely";
/// Profiles made here carry their name and no copyright claim.
fn labelled(mut p: ColorProfile, name: &str) -> ColorProfile {
fn labelled(p: ColorProfile, name: &str) -> ColorProfile {
with_copyright(p, name, NO_COPYRIGHT)
}
fn with_copyright(mut p: ColorProfile, name: &str, copyright: &str) -> ColorProfile {
p.description = text_tag(name);
p.copyright = text_tag("No copyright, use freely");
p.copyright = text_tag(copyright);
p
}
@@ -452,10 +459,11 @@ const GAMUT_GRID: usize = 9;
/// 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.
/// the ICC-absolute colorimetric intent reproduces; the copyright tag holds `copyright`.
pub(super) fn cmyk_profile(
name: &str,
paper: [f32; 3],
copyright: &str,
to_lab: impl Fn([f32; 4]) -> lab::Lab,
mapped: impl Fn(lab::Lab) -> [f32; 4],
colorimetric: impl Fn(lab::Lab) -> [f32; 4],
@@ -520,7 +528,7 @@ pub(super) fn cmyk_profile(
p.lut_b_to_a_saturation = Some(b2a_mapped);
p.lut_b_to_a_colorimetric = Some(b2a);
p.gamut = Some(gamut);
labelled(p, name)
with_copyright(p, name, copyright)
}
/// The grey space of greyscale exports: sRGB's tone curve, D50 white.
+378
View File
@@ -0,0 +1,378 @@
//! CMYK working spaces computed from published characterization data.
//!
//! Fogra publishes the measured colors of its reference printing conditions
//! (<https://fogra.org/en/downloads/work-tools/characterisation-data>) and allows the data to be
//! redistributed unmodified, with Fogra named as the source. VectorCraft embeds the FOGRA51 and
//! FOGRA52 files byte for byte (`crates/color/data/`) and computes each press model from them the
//! first time it is used:
//!
//! * The paper is the measured blank patch. The 15 solids and overprints of the
//! [`super::generic`] model are the measured patches of those builds, and each ink's tone curve
//! is fitted to its single-ink ramp.
//! * What that model still misses at each patch (in media-relative Lab) is fitted with a smoothed
//! lattice over CMYK ([`Lattice`]), which [`GenericCmyk::to_xyz_rel`] adds to the model. The
//! smoothing carries the fit into regions the patch set does not sample, such as dark builds
//! with more than 60% black.
//!
//! The total ink limit and the black generation are VectorCraft's own values.
use super::generic::{GenericCmyk, GenericCmykParams, swop_like};
use super::lab::{D50, Lab, lab_to_xyz, xyz_to_lab};
/// A printing condition with published characterization data.
#[derive(Clone, Copy, Debug)]
pub struct Condition {
/// The working space's name.
pub name: &'static str,
/// The reference name of the characterization data, which a PDF/X output intent uses as
/// its `/OutputConditionIdentifier`.
pub reference: &'static str,
/// The characterization data file, as published.
pub data: &'static [u8],
/// Total area coverage limit (sum of inks, 1.0 = 100%): VectorCraft's own value.
pub tac: f32,
}
/// The registry that the reference names of [`CONDITIONS`] belong to
/// (<https://registry.color.org/cmyk-registry/>).
pub const REGISTRY: &str = "http://www.color.org";
/// The printing conditions VectorCraft computes working spaces for.
pub const CONDITIONS: [Condition; 2] = [
Condition { name: super::FOGRA51_CMYK, reference: "FOGRA51", data: include_bytes!("../../data/FOGRA51.txt"), tac: 3.0 },
Condition { name: super::FOGRA52_CMYK, reference: "FOGRA52", data: include_bytes!("../../data/FOGRA52.txt"), tac: 3.0 },
];
/// The condition a working space of [`CONDITIONS`] is computed for.
pub fn condition(name: &str) -> Option<&'static Condition> {
CONDITIONS.iter().find(|c| c.name == name)
}
/// One measured patch: nominal inks (0..1) and absolute Lab (D50).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Patch {
pub cmyk: [f32; 4],
pub lab: Lab,
}
/// The most patches [`parse`] reads.
const MAX_PATCHES: usize = 20_000;
/// The patches of a CGATS / ISO 28178 characterization data file with `CMYK_C`, `CMYK_M`,
/// `CMYK_Y`, `CMYK_K`, `LAB_L`, `LAB_A` and `LAB_B` fields. `None` when a field is missing, a
/// row is short or holds a value that is not a finite number, an ink is outside 0 to 100, the
/// file has no rows, the rows do not end with `END_DATA`, or a `NUMBER_OF_SETS` in the header is
/// not the number of rows.
pub fn parse(data: &[u8]) -> Option<Vec<Patch>> {
let text = std::str::from_utf8(data).ok()?;
let sets = text.lines().map(str::trim).take_while(|l| *l != "BEGIN_DATA").find_map(|l| {
let mut words = l.split_whitespace();
(words.next() == Some("NUMBER_OF_SETS")).then(|| words.next().map(|n| n.trim_matches('"')))
});
let sets = match sets {
Some(n) => Some(n?.parse::<usize>().ok()?),
None => None,
};
let mut lines = text.lines().map(str::trim);
lines.by_ref().find(|l| *l == "BEGIN_DATA_FORMAT")?;
let mut fields = vec![];
for line in lines.by_ref() {
if line == "END_DATA_FORMAT" {
break;
}
fields.extend(line.split_whitespace());
}
let at = |f: &str| fields.iter().position(|x| *x == f);
let cols = [at("CMYK_C")?, at("CMYK_M")?, at("CMYK_Y")?, at("CMYK_K")?, at("LAB_L")?, at("LAB_A")?, at("LAB_B")?];
lines.by_ref().find(|l| *l == "BEGIN_DATA")?;
let mut out = vec![];
let mut ended = false;
for line in lines {
if line == "END_DATA" {
ended = true;
break;
}
if line.is_empty() {
continue;
}
if out.len() >= MAX_PATCHES {
return None;
}
let row: Vec<&str> = line.split_whitespace().collect();
let mut v = [0f32; 7];
for (slot, &col) in v.iter_mut().zip(&cols) {
*slot = row.get(col)?.parse::<f32>().ok().filter(|x| x.is_finite())?;
}
if v[..4].iter().any(|x| !(0.0..=100.0).contains(x)) {
return None;
}
out.push(Patch { cmyk: [v[0], v[1], v[2], v[3]].map(|x| x / 100.0), lab: Lab::new(v[4], v[5], v[6]) });
}
(ended && !out.is_empty() && sets.is_none_or(|n| n == out.len())).then_some(out)
}
/// Absolute Lab → media-relative Lab (`paper` maps to the D50 white).
fn relative(lab: Lab, paper: [f32; 3]) -> Lab {
let x = lab_to_xyz(lab);
xyz_to_lab([0, 1, 2].map(|i| x[i] * D50[i] / paper[i]))
}
/// The mean of the Lab values of the patches whose inks are `inks`, in XYZ.
fn mean_lab(patches: &[Patch], inks: [f32; 4]) -> Option<Lab> {
let mut sum = [0f32; 3];
let mut n = 0;
for p in patches.iter().filter(|p| p.cmyk.iter().zip(&inks).all(|(a, b)| (a - b).abs() < 1e-4)) {
let x = lab_to_xyz(p.lab);
for i in 0..3 {
sum[i] += x[i];
}
n += 1;
}
(n > 0).then(|| xyz_to_lab(sum.map(|v| v / n as f32)))
}
/// The tone value increase at 50% and 40% of ink `ink`, fitted to its single-ink ramp with the
/// curve of [`super::generic`]: the effective area is `a + u·4a(1−a) + v·4a(1−a)(2a−1)`, so the
/// 50% increase is `u` and the 40% increase is `0.96·u − 0.192·v`. Each patch's effective area
/// comes from the Murray–Davies formula in the media-relative XYZ channel the ink darkens most
/// (`paper` is the paper's absolute XYZ, `solid` the solid's media-relative XYZ).
fn tone_increase(patches: &[Patch], ink: usize, paper: [f32; 3], solid: [f32; 3]) -> Option<(f32, f32)> {
let ch = (0..3).max_by(|&a, &b| (D50[a] - solid[a]).abs().total_cmp(&(D50[b] - solid[b]).abs()))?;
let span = D50[ch] - solid[ch];
if span.abs() < 1e-4 {
return None;
}
let (mut s11, mut s12, mut s22, mut r1, mut r2) = (0f64, 0f64, 0f64, 0f64, 0f64);
for p in patches {
let a = p.cmyk[ink];
let alone = p.cmyk.iter().enumerate().all(|(i, v)| i == ink || *v == 0.0);
if !alone || a <= 0.0 || a >= 1.0 {
continue;
}
let e = (D50[ch] - relative_xyz(p.lab, paper)[ch]) / span;
let (b1, b2) = (f64::from(4.0 * a * (1.0 - a)), f64::from(4.0 * a * (1.0 - a) * (2.0 * a - 1.0)));
let d = f64::from(e - a);
s11 += b1 * b1;
s12 += b1 * b2;
s22 += b2 * b2;
r1 += b1 * d;
r2 += b2 * d;
}
let det = s11 * s22 - s12 * s12;
if det.abs() < 1e-12 {
return None;
}
let u = ((r1 * s22 - r2 * s12) / det) as f32;
let v = ((s11 * r2 - s12 * r1) / det) as f32;
let tvi50 = u.clamp(0.0, 0.45);
let tvi40 = (0.96 * u - 0.192 * v).clamp(0.0, 0.45);
Some((tvi50, tvi40))
}
/// Absolute Lab → media-relative XYZ.
fn relative_xyz(lab: Lab, paper: [f32; 3]) -> [f32; 3] {
let x = lab_to_xyz(lab);
[0, 1, 2].map(|i| x[i] * D50[i] / paper[i])
}
/// The press model of `condition`, computed from its data. `None` when the data does not parse,
/// lacks the paper, a solid or overprint, or a single-ink ramp, or gives a paper whose XYZ is not
/// positive and finite.
pub fn model(condition: &Condition) -> Option<GenericCmyk> {
fit(condition, &parse(condition.data)?, SMOOTHING)
}
/// The press model of `condition` fitted to `patches`, with the lattice's `smoothing` (`None` in
/// the cases [`model`] lists).
pub(crate) fn fit(condition: &Condition, patches: &[Patch], smoothing: f64) -> Option<GenericCmyk> {
let paper = mean_lab(patches, [0.0; 4])?;
let paper_xyz = lab_to_xyz(paper);
if paper_xyz.iter().any(|v| !v.is_finite() || *v <= 0.0) {
return None;
}
let mut primaries = [Lab::new(0.0, 0.0, 0.0); 15];
for (i, slot) in primaries.iter_mut().enumerate() {
let bits = i + 1;
let inks = [0, 1, 2, 3].map(|b| if bits & (1 << b) != 0 { 1.0 } else { 0.0 });
*slot = relative(mean_lab(patches, inks)?, paper_xyz);
}
let mut tvi50 = [0f32; 4];
let mut tvi40 = [0f32; 4];
for ink in 0..4 {
let solid = lab_to_xyz(primaries[(1 << ink) - 1]);
(tvi50[ink], tvi40[ink]) = tone_increase(patches, ink, paper_xyz, solid)?;
}
let params = GenericCmykParams { name: condition.name, paper, primaries, tvi50, tvi40, tac: condition.tac, bg: swop_like().bg };
let base = GenericCmyk::new(params.clone());
let points: Vec<([f32; 4], [f32; 3])> = patches
.iter()
.map(|p| {
let want = relative(p.lab, paper_xyz);
let got = base.to_lab_rel(p.cmyk);
(p.cmyk, [want.l - got.l, want.a - got.a, want.b - got.b])
})
.collect();
Some(GenericCmyk::with_correction(params, Lattice::fit(&points, smoothing)))
}
/// Weight of the lattice's smoothness against its fit to the patches.
pub(crate) const SMOOTHING: f64 = 0.02;
/// Knots of each ink's axis of the [`Lattice`]: the steps of the published single-ink ramps.
const KNOTS: [f32; 9] = [0.0, 0.1, 0.2, 0.3, 0.4, 0.55, 0.7, 0.85, 1.0];
const N: usize = KNOTS.len();
const NODES: usize = N * N * N * N;
/// A Lab correction over CMYK, read by multilinear interpolation between nodes at [`KNOTS`].
#[derive(Clone, Debug)]
pub struct Lattice {
values: Vec<[f32; 3]>,
}
/// The cell of `v` along an axis and its position in it.
fn locate(v: f32) -> (usize, f32) {
let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
let i = KNOTS.iter().skip(1).position(|k| v <= *k).unwrap_or(N - 2).min(N - 2);
let (lo, hi) = (KNOTS[i], KNOTS[i + 1]);
(i, ((v - lo) / (hi - lo)).clamp(0.0, 1.0))
}
/// The 16 nodes around `cmyk` with their interpolation weights.
fn corners(cmyk: [f32; 4]) -> [(usize, f32); 16] {
let cells = cmyk.map(locate);
let mut out = [(0, 0.0); 16];
for (corner, slot) in out.iter_mut().enumerate() {
let mut index = 0;
let mut w = 1.0;
for (axis, (cell, t)) in cells.iter().enumerate() {
let up = corner & (1 << axis) != 0;
index = index * N + cell + usize::from(up);
w *= if up { *t } else { 1.0 - t };
}
*slot = (index, w);
}
out
}
/// Index strides of the four axes (C is the slowest).
const STRIDES: [usize; 4] = [N * N * N, N * N, N, 1];
impl Lattice {
/// The correction at `cmyk`.
pub fn at(&self, cmyk: [f32; 4]) -> [f32; 3] {
let mut out = [0f32; 3];
for (i, w) in corners(cmyk) {
if w == 0.0 {
continue;
}
let v = self.values.get(i).copied().unwrap_or_default();
for c in 0..3 {
out[c] += w * v[c];
}
}
out
}
/// The lattice that best fits `points` (inks, correction) in the least-squares sense, with
/// `smoothing` times the squared second differences of the nodes along each axis added to the
/// error. The node at no ink stays 0, so the paper keeps the model's color (white, media-
/// relative). Solved by conjugate gradients, one Lab channel at a time.
pub fn fit(points: &[([f32; 4], [f32; 3])], smoothing: f64) -> Lattice {
let weights: Vec<[(usize, f32); 16]> = points.iter().map(|(cmyk, _)| corners(*cmyk)).collect();
// The divided second difference at interior knot j, scaled to a unit spacing of 1/8.
let curvature: Vec<[f64; 3]> = (1..N - 1)
.map(|j| {
let (h1, h2) = (f64::from(KNOTS[j] - KNOTS[j - 1]), f64::from(KNOTS[j + 1] - KNOTS[j]));
let s = 0.125f64 * 0.125;
[2.0 / (h1 * (h1 + h2)) * s, -2.0 / (h1 * h2) * s, 2.0 / (h2 * (h1 + h2)) * s]
})
.collect();
let apply = |x: &[f64], out: &mut [f64]| {
out.fill(0.0);
for w in &weights {
let v: f64 = w.iter().map(|(i, w)| f64::from(*w) * x.get(*i).copied().unwrap_or(0.0)).sum();
for (i, w) in w {
if let Some(o) = out.get_mut(*i) {
*o += f64::from(*w) * v;
}
}
}
for node in 0..NODES {
let mut rest = node;
for stride in STRIDES {
let j = rest / stride;
rest %= stride;
// Only interior knots (1 to N − 2) have a second difference.
let Some(c) = j.checked_sub(1).and_then(|k| curvature.get(k)) else { continue };
let idx = [node - stride, node, node + stride];
let d: f64 = idx.iter().zip(c).map(|(i, c)| c * x.get(*i).copied().unwrap_or(0.0)).sum();
for (i, c) in idx.iter().zip(c) {
if let Some(o) = out.get_mut(*i) {
*o += smoothing * c * d;
}
}
}
}
for (o, v) in out.iter_mut().zip(x) {
*o += 1e-9 * v;
}
// The paper's node is held: with its right-hand side 0 it stays 0 in every iterate.
if let (Some(o), Some(v)) = (out.first_mut(), x.first()) {
*o = *v;
}
};
let mut values = vec![[0f32; 3]; NODES];
for ch in 0..3 {
let mut b = vec![0f64; NODES];
for (w, (_, r)) in weights.iter().zip(points) {
for (i, w) in w {
if let Some(o) = b.get_mut(*i) {
*o += f64::from(*w) * f64::from(r[ch]);
}
}
}
if let Some(o) = b.first_mut() {
*o = 0.0;
}
let x = conjugate_gradients(&apply, &b, 4000);
for (v, x) in values.iter_mut().zip(&x) {
v[ch] = *x as f32;
}
}
Lattice { values }
}
}
/// Solve `A x = b` for the symmetric positive definite `A` that `apply` multiplies by.
fn conjugate_gradients(apply: &dyn Fn(&[f64], &mut [f64]), b: &[f64], max_iterations: usize) -> Vec<f64> {
let n = b.len();
let mut x = vec![0f64; n];
let mut r = b.to_vec();
let mut p = r.clone();
let mut ap = vec![0f64; n];
let dot = |a: &[f64], b: &[f64]| a.iter().zip(b).map(|(a, b)| a * b).sum::<f64>();
let mut rr = dot(&r, &r);
let stop = rr * 1e-20;
for _ in 0..max_iterations {
if rr <= stop || rr == 0.0 {
break;
}
apply(&p, &mut ap);
let pap = dot(&p, &ap);
if pap <= 0.0 || !pap.is_finite() {
break;
}
let alpha = rr / pap;
for i in 0..n {
x[i] += alpha * p[i];
r[i] -= alpha * ap[i];
}
let next = dot(&r, &r);
let beta = next / rr;
rr = next;
for i in 0..n {
p[i] = r[i] + beta * p[i];
}
}
x
}
+250
View File
@@ -0,0 +1,250 @@
use super::*;
use sha2::{Digest, Sha256};
fn hex(bytes: &[u8]) -> String {
Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect()
}
/// The data files ship exactly as Fogra publishes them in
/// https://fogra.org/fileadmin/files/7_downloads/Charakterisierungsdaten/F51-52.zip.
#[test]
fn characterization_data_is_the_published_files() {
let want = [
("FOGRA51", "ad472a1c0bdafd558597ff93eeda5175805086565af814cb6346e910e2f25aa5", 57_111),
("FOGRA52", "be4f0732328ed62ade63ec7f317d3b9e9dad6bbe2430fefddaf0f901d5ba13d6", 56_781),
];
for (c, (reference, sha, len)) in measured::CONDITIONS.iter().zip(want) {
assert_eq!(c.reference, reference);
assert_eq!((c.data.len(), hex(c.data).as_str()), (len, sha), "{reference}");
}
}
#[test]
fn the_data_parses_into_its_patches() {
for c in &measured::CONDITIONS {
let patches = measured::parse(c.data).unwrap();
assert_eq!(patches.len(), 1617, "{}", c.reference);
assert_eq!(patches[0].cmyk, [0.0; 4]);
}
let p = measured::parse(measured::CONDITIONS[0].data).unwrap();
assert_eq!(p[0].lab, Lab::new(95.0, 1.5, -6.0));
assert_eq!(p[1].cmyk, [0.0, 0.1, 0.0, 0.0]);
assert_eq!(p[1].lab, Lab::new(90.08, 8.15, -7.42));
}
#[test]
fn malformed_data_is_refused() {
let file = |format: &str, rows: &str| format!("ISO28178\nBEGIN_DATA_FORMAT\n{format}\nEND_DATA_FORMAT\nBEGIN_DATA\n{rows}\nEND_DATA\n");
let fields = "SAMPLE_ID CMYK_C CMYK_M CMYK_Y CMYK_K LAB_L LAB_A LAB_B";
let good = file(fields, "1 0 0 0 0 95 1 -6\n2 100 0 0 0 55 -37 -50");
assert_eq!(measured::parse(good.as_bytes()).map(|p| p.len()), Some(2));
for bad in [
file("SAMPLE_ID CMYK_C CMYK_M CMYK_Y LAB_L LAB_A LAB_B", "1 0 0 0 95 1 -6"),
file(fields, "1 0 0 0 0 95 1"),
file(fields, "1 0 0 0 0 95 NaN -6"),
file(fields, "1 0 0 0 0 95 x -6"),
file(fields, "1 0 0 0 101 95 1 -6"),
file(fields, "1 -1 0 0 0 95 1 -6"),
file(fields, ""),
"BEGIN_DATA\n1 0 0 0 0 95 1 -6\nEND_DATA\n".into(),
] {
assert_eq!(measured::parse(bad.as_bytes()), None, "{bad}");
}
assert_eq!(measured::parse(&[0xff, 0xfe, 0x00]), None);
// The rows end with END_DATA, and a NUMBER_OF_SETS in the header counts them.
let rows = "1 0 0 0 0 95 1 -6\n2 100 0 0 0 55 -37 -50";
let header = |sets: &str| format!("ISO28178\nBEGIN_DATA_FORMAT\n{fields}\nEND_DATA_FORMAT\n{sets}\nBEGIN_DATA\n{rows}\n");
assert_eq!(measured::parse(header("NUMBER_OF_SETS\t2").as_bytes()), None, "no END_DATA");
for (sets, len) in [
("NUMBER_OF_SETS\t2", Some(2)),
("NUMBER_OF_SETS\t3", None),
("NUMBER_OF_SETS\t1", None),
("NUMBER_OF_SETS\tx", None),
("NUMBER_OF_SETS", None),
] {
assert_eq!(measured::parse(format!("{}END_DATA\n", header(sets)).as_bytes()).map(|p| p.len()), len, "{sets}");
}
}
/// A paper measured as black has no XYZ to make the other patches relative to.
#[test]
fn a_paper_without_light_is_refused() {
let c = &measured::CONDITIONS[0];
let mut patches = measured::parse(c.data).unwrap();
for p in patches.iter_mut().filter(|p| p.cmyk == [0.0; 4]) {
p.lab = Lab::new(0.0, 0.0, 0.0);
}
assert!(measured::fit(c, &patches, measured::SMOOTHING).is_none());
}
/// ΔE2000 between each measured patch and the model's absolute Lab for its inks: (mean, max).
fn accuracy(g: &GenericCmyk, patches: &[measured::Patch]) -> (f32, f32) {
let errors: Vec<f32> = patches.iter().map(|p| delta_e2000(g.to_lab_abs(p.cmyk), p.lab)).collect();
(errors.iter().sum::<f32>() / errors.len() as f32, errors.iter().copied().fold(0.0, f32::max))
}
#[test]
fn the_working_spaces_reproduce_the_measured_patches() {
for c in &measured::CONDITIONS {
let patches = measured::parse(c.data).unwrap();
let start = std::time::Instant::now();
let g = measured::model(c).unwrap();
let took = start.elapsed();
let (mean, max) = accuracy(&g, &patches);
println!("{}: computed in {took:?}, mean ΔE2000 {mean:.3}, max {max:.3}", c.reference);
assert!(mean < 0.1 && max < 0.6, "{}: mean {mean}, max {max}", c.reference);
// The paper is the measured blank patch.
assert!(delta_e2000(g.to_lab_abs([0.0; 4]), patches[0].lab) < 0.05);
}
}
/// A model fitted without every fourth patch (the paper and the solids and overprints stay in)
/// predicts the patches it left out. The data repeats some builds, and every row of a build is
/// on the side of the build's first row, so the fit never sees a left-out build.
#[test]
fn the_fit_predicts_patches_it_left_out() {
for c in &measured::CONDITIONS {
let patches = measured::parse(c.data).unwrap();
let corner = |p: &measured::Patch| p.cmyk.iter().all(|v| *v == 0.0 || *v == 1.0);
let first = |p: &measured::Patch| patches.iter().position(|q| q.cmyk == p.cmyk).unwrap_or(0);
let (kept, left): (Vec<&measured::Patch>, Vec<_>) = patches.iter().partition(|p| first(p) % 4 != 3 || corner(p));
assert!(left.iter().all(|l| kept.iter().all(|k| k.cmyk != l.cmyk)), "{}", c.reference);
let kept: Vec<measured::Patch> = kept.into_iter().copied().collect();
let left: Vec<measured::Patch> = left.into_iter().copied().collect();
let g = measured::fit(c, &kept, measured::SMOOTHING).unwrap();
let (mean, max) = accuracy(&g, &left);
println!("{}: {} patches left out, mean ΔE2000 {mean:.3}, max {max:.3}", c.reference, left.len());
assert!(mean < 0.3 && max < 2.5, "{}: mean {mean}, max {max}", c.reference);
}
}
/// More of any ink makes a build lighter by less than 0.3 L*, also where the data has few patches
/// (black above 60%, and builds over the ink limit).
#[test]
fn more_ink_lightens_a_build_by_less_than_0_3_l() {
let steps: Vec<f32> = (0..=20).map(|i| i as f32 / 20.0).collect();
let coarse = [0.0, 0.25, 0.5, 0.75, 1.0];
for c in &measured::CONDITIONS {
let g = measured::model(c).unwrap();
let mut worst = 0f32;
for ink in 0..4 {
for a in coarse {
for b in coarse {
for d in coarse {
let mut others = [a, b, d].into_iter();
let mut build = [0f32; 4];
for (i, slot) in build.iter_mut().enumerate() {
if i != ink {
*slot = others.next().unwrap();
}
}
let mut last = f32::INFINITY;
for &v in &steps {
build[ink] = v;
let l = g.to_lab_rel(build).l;
worst = worst.max(l - last);
last = l;
}
}
}
}
}
println!("{}: largest L* rise with more ink {worst:.3}", c.reference);
assert!(worst < 0.3, "{}: {worst}", c.reference);
}
}
#[test]
fn the_working_spaces_follow_generic_cmyk_in_the_list() {
let cmyk: Vec<String> = profiles().into_iter().filter(|p| p.kind == ProfileKind::Cmyk && p.builtin).map(|p| p.name).collect();
assert_eq!(cmyk, [GENERIC_CMYK, FOGRA51_CMYK, FOGRA52_CMYK, DEVICE_CMYK]);
assert_eq!(ColorSettings::default().cmyk, GENERIC_CMYK);
assert_eq!(characterization(FOGRA51_CMYK), Some(("FOGRA51", "http://www.color.org")));
assert_eq!(characterization(FOGRA52_CMYK), Some(("FOGRA52", "http://www.color.org")));
assert_eq!(characterization(GENERIC_CMYK), None);
assert!(matches!(register_icc(&icc_bytes(FOGRA51_CMYK).unwrap(), None), Err(CmsError::Unsupported(_))));
}
#[test]
fn colors_separate_and_come_back_in_the_measured_spaces() {
for name in [FOGRA51_CMYK, FOGRA52_CMYK] {
let cms = Cms::new(&ColorSettings { cmyk: name.into(), ..ColorSettings::default() }).unwrap();
// A 50% gray (L* 53) lies well inside both measured gamuts (the darkest patches measure
// L* 11.43 and 26.36), so it comes back whatever the gamut check says.
let gray = [0.5, 0.5, 0.5];
for srgb in [[0.8, 0.3, 0.2], [0.2, 0.5, 0.7], gray, [0.9, 0.85, 0.6], [0.1, 0.1, 0.1]] {
let inks = cms.srgb_to_cmyk(srgb, Intent::RelativeColorimetric);
assert!(inks.iter().sum::<f32>() <= 3.0 + 1e-3, "{name} {srgb:?}: {inks:?}");
if srgb == gray || cms.gamut_error(&Color::Rgb { r: srgb[0], g: srgb[1], b: srgb[2] }) < GAMUT_THRESHOLD {
let back = cms.cmyk_to_srgb(inks, false);
let de = delta_e2000(lab::srgb_to_lab(srgb), lab::srgb_to_lab(back));
assert!(de < 1.5, "{name} {srgb:?}: {inks:?} -> {back:?} (ΔE {de})");
}
}
// White is paper with no ink, and black is the darkest build within the ink limit.
assert_eq!(cms.srgb_to_cmyk([1.0; 3], Intent::RelativeColorimetric), [0.0; 4]);
let black = cms.srgb_to_cmyk([0.0; 3], Intent::RelativeColorimetric);
assert!(black[3] > 0.8 && black.iter().sum::<f32>() <= 3.0 + 1e-3, "{name}: {black:?}");
}
// The coated paper prints a larger gamut than the uncoated one.
let blue = Color::Rgb { r: 0.1, g: 0.2, b: 0.6 };
let coated = Cms::new(&ColorSettings { cmyk: FOGRA51_CMYK.into(), ..ColorSettings::default() }).unwrap();
let uncoated = Cms::new(&ColorSettings { cmyk: FOGRA52_CMYK.into(), ..ColorSettings::default() }).unwrap();
assert!(coated.gamut_error(&blue) < uncoated.gamut_error(&blue));
}
/// Absolute Lab of `cmyk` in a context whose CMYK space is one of the Generic-type spaces.
fn absolute_lab(cms: &Cms, cmyk: [f32; 4]) -> Lab {
match &cms.cmyk {
CmykSpace::Generic(g) => g.to_lab_abs(cmyk),
CmykSpace::Device | CmykSpace::Icc(_) => panic!("not a Generic-type CMYK space"),
}
}
#[test]
fn absolute_cmyk_to_rgb_shows_the_paper() {
for name in [GENERIC_CMYK, FOGRA51_CMYK, FOGRA52_CMYK] {
let cms = Cms::new(&ColorSettings { cmyk: name.into(), ..ColorSettings::default() }).unwrap();
let paper = cms.cmyk_to_rgb([0.0; 4], Intent::AbsoluteColorimetric);
assert_eq!(paper, cms.srgb_to_rgb(cms.cmyk_to_srgb([0.0; 4], true)), "{name}");
assert_ne!(paper, cms.cmyk_to_rgb([0.0; 4], Intent::RelativeColorimetric), "{name}");
}
}
#[test]
fn absolute_cmyk_conversion_keeps_the_source_paper() {
// Generic CMYK's paper (L* 93, b* 2.5) is darker and yellower than FOGRA51's (L* 95, b* -6),
// so printing it on FOGRA51 paper takes ink.
let generic = Cms::new(&ColorSettings { cmyk: GENERIC_CMYK.into(), ..ColorSettings::default() }).unwrap();
let coated = Cms::new(&ColorSettings { cmyk: FOGRA51_CMYK.into(), ..ColorSettings::default() }).unwrap();
let Color::Cmyk { c, m, y, k } = generic.convert_into(&coated, &Color::Cmyk { c: 0.0, m: 0.0, y: 0.0, k: 0.0 }, Intent::AbsoluteColorimetric)
else {
panic!("a CMYK colour converts to CMYK");
};
let inks = [c, m, y, k];
assert!(inks.iter().sum::<f32>() > 0.01, "{inks:?}");
let de = delta_e2000(absolute_lab(&coated, inks), absolute_lab(&generic, [0.0; 4]));
assert!(de < 2.0, "{inks:?}: ΔE {de}");
}
#[test]
fn the_profiles_carry_the_paper_and_the_data_source() {
for c in &measured::CONDITIONS {
let start = std::time::Instant::now();
let bytes = icc_bytes(c.name).unwrap();
println!("{}: {} bytes in {:?}", c.reference, bytes.len(), start.elapsed());
let p = moxcms::ColorProfile::new_from_slice(&bytes).unwrap();
assert_eq!(
(p.profile_class, p.color_space, p.pcs),
(moxcms::ProfileClass::OutputDevice, moxcms::DataColorSpace::Cmyk, moxcms::DataColorSpace::Lab)
);
assert!(p.lut_a_to_b_perceptual.is_some() && p.lut_b_to_a_perceptual.is_some() && p.lut_a_to_b_colorimetric.is_some());
let paper = lab::lab_to_xyz(measured::parse(c.data).unwrap()[0].lab);
let white = p.media_white_point.unwrap();
for (got, want) in [white.x, white.y, white.z].iter().zip(paper) {
assert!((*got - f64::from(want)).abs() < 2e-3, "{}: {white:?} vs {paper:?}", c.reference);
}
let text = format!("{:?}", p.copyright);
assert!(text.contains(c.reference) && text.contains("Fogra"), "{text}");
}
}
+1 -1
View File
@@ -39,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Color Settings…",
["Edit"],
Some("Cmd+Shift+K"),
"{rgb?: profile, cmyk?: profile, intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool, rgbPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\", cmykPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\"|\"preserveNumbers\", askMismatchOpen?: bool, askMismatchPaste?: bool, askMissingOpen?: bool (all false by default)} set the working spaces, the color management policies and the Ask boxes → {rgb, cmyk, intent, bpc, rgbPolicy, cmykPolicy, askMismatchOpen, askMismatchPaste, askMissingOpen, profiles: [{name, kind, builtin}]}. With askMismatchOpen or askMissingOpen on, the desktop app's File › Open asks what to do when the profile of a document's color mode is not the working space, or it has none (document.open takes the answer as profileChoice; it never asks); with askMismatchPaste on, Paste asks whether colors copied from a document with another profile keep their numbers or convert (edit.paste takes it as profileMismatch; see clipboard.profileMismatch). A policy decides what opening a document (document.open, file.newFromTemplate, file.revert) does with an RGB or CMYK profile it is tagged with that is not the working space: preserveEmbedded (default) keeps it; off and preserveNumbers take it off and keep the color numbers; convert converts the colors of that model into the working space with the intent and bpc and takes it off. The open reply's warnings name each profile taken off or converted, and a document a policy changed opens with unsaved changes. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults",
"{rgb?: profile, cmyk?: profile (built in: \"VectorCraft Generic CMYK (SWOP-like)\" (default), \"VectorCraft Coated CMYK (FOGRA51)\" and \"VectorCraft Uncoated CMYK (FOGRA52)\" (computed from Fogra's characterization data), \"Device CMYK (uncalibrated)\"), intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool, rgbPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\", cmykPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\"|\"preserveNumbers\", askMismatchOpen?: bool, askMismatchPaste?: bool, askMissingOpen?: bool (all false by default)} set the working spaces, the color management policies and the Ask boxes → {rgb, cmyk, intent, bpc, rgbPolicy, cmykPolicy, askMismatchOpen, askMismatchPaste, askMissingOpen, profiles: [{name, kind, builtin}]}. With askMismatchOpen or askMissingOpen on, the desktop app's File › Open asks what to do when the profile of a document's color mode is not the working space, or it has none (document.open takes the answer as profileChoice; it never asks); with askMismatchPaste on, Paste asks whether colors copied from a document with another profile keep their numbers or convert (edit.paste takes it as profileMismatch; see clipboard.profileMismatch). A policy decides what opening a document (document.open, file.newFromTemplate, file.revert) does with an RGB or CMYK profile it is tagged with that is not the working space: preserveEmbedded (default) keeps it; off and preserveNumbers take it off and keep the color numbers; convert converts the colors of that model into the working space with the intent and bpc and takes it off. The open reply's warnings name each profile taken off or converted, and a document a policy changed opens with unsaved changes. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults",
always,
color_settings
),
File diff suppressed because one or more lines are too long
+11 -7
View File
@@ -615,6 +615,10 @@ impl Dest {
/// The catalog entries `set` asks for (none in PDF/A files, which carry their own); a PDF/X file's
/// output intent profile is `cmyk_profile` (the CMYK profile in effect) unless `set` names one.
/// When the settings leave the condition identifier blank, a profile computed for a registered
/// printing condition ([`cms::characterization`]) gives the condition's name as the identifier,
/// and its registry when the settings leave the registry blank too. An identifier set in the
/// settings is written as given, with the settings' registry.
fn catalog(set: &PdfSettings, cmyk_profile: &str) -> Option<Catalog> {
let o = &set.output;
if set.standard == Standard::PdfA2b {
@@ -631,13 +635,13 @@ fn catalog(set: &PdfSettings, cmyk_profile: &str) -> Option<Catalog> {
ProfileKind::Gray => None,
});
let text = |s: &str| s.trim().chars().take(MAX_TEXT).collect::<String>();
OutputIntent {
id: text(if id.is_empty() { name } else { id }),
condition: text(&o.output_condition),
registry: text(&o.registry),
info: text(name),
profile,
}
// Without a condition identifier, a profile computed for a registered printing condition
// names that condition and, unless the settings name one, the registry it belongs to.
let (id, registry) = match cms::characterization(name) {
Some((reference, registry)) if id.is_empty() => (reference, if o.registry.trim().is_empty() { registry } else { o.registry.as_str() }),
_ => (if id.is_empty() { name } else { id }, o.registry.as_str()),
};
OutputIntent { id: text(id), condition: text(&o.output_condition), registry: text(registry), info: text(name), profile }
});
let trapped = (o.trapped || intent.is_some()).then_some(o.trapped);
(intent.is_some() || trapped.is_some()).then_some(Catalog { intent, trapped })
+69
View File
@@ -151,6 +151,75 @@ fn each_standard_writes_its_header_output_intent_boxes_and_identification() {
assert!(matches!(e, Err(PdfError::BadSetting(m)) if m.contains("embeds")));
}
/// The ICC tag signatures of `icc`'s tag table.
fn icc_tags(icc: &[u8]) -> Vec<String> {
let count = u32::from_be_bytes(icc[128..132].try_into().unwrap()) as usize;
(0..count).map(|i| String::from_utf8_lossy(&icc[132 + 12 * i..136 + 12 * i]).into_owned()).collect()
}
#[test]
fn a_registered_condition_profile_names_its_condition_and_embeds_itself() {
use std::io::Read;
let d = doc(&[Color::cmyk(0.0, 1.0, 1.0, 0.0), Color::cmyk(0.6, 0.0, 0.2, 0.1)]);
for (profile, reference) in [(cms::FOGRA51_CMYK, "FOGRA51"), (cms::FOGRA52_CMYK, "FOGRA52")] {
let r = export_with_report(&d, &opts(Standard::PdfX4, |s| s.output.output_intent = profile.into())).unwrap();
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
let t = text(&r.bytes);
let info = profile.replace('(', r"\(").replace(')', r"\)");
for want in [
"/S/GTS_PDFX".to_string(),
format!("/OutputConditionIdentifier({reference})"),
"/RegistryName(http://www.color.org)".into(),
format!("/Info({info})"),
] {
assert!(t.contains(&want), "{profile}: {want}");
}
// The embedded profile is the working space's: a CMYK output profile with Lab tables both
// ways, read from the file's bytes.
let oi: u32 = t.split("/DestOutputProfile ").nth(1).unwrap().split(' ').next().unwrap().parse().unwrap();
let (start, end) = crate::patch::Xref::read(&r.bytes).unwrap().dict(&r.bytes, oi).unwrap();
let obj = &r.bytes[start..end];
let at = crate::lab_spot::find(obj, b"/Length", 0).unwrap();
let (length, _) = crate::patch::number(obj, at + b"/Length".len()).unwrap();
let mut data = crate::lab_spot::find(obj, b"stream", at).unwrap() + b"stream".len();
data += obj[data..].iter().take(2).take_while(|b| matches!(b, b'\r' | b'\n')).count();
let raw = &obj[data..data + length];
let mut icc = vec![];
if crate::lab_spot::find(&obj[..data], b"/FlateDecode", 0).is_some() {
flate2::read::ZlibDecoder::new(raw).read_to_end(&mut icc).unwrap();
} else {
icc = raw.to_vec();
}
assert_eq!(icc.as_slice(), &*cms::icc_bytes(profile).unwrap());
assert_eq!((&icc[12..16], &icc[16..20], &icc[20..24], &icc[36..40]), (&b"prtr"[..], &b"CMYK"[..], &b"Lab "[..], &b"acsp"[..]));
assert!(matches!(icc[8], 2 | 4), "ICC version {}", icc[8]);
let tags = icc_tags(&icc);
for tag in ["A2B0", "B2A0", "A2B1", "B2A1", "gamt", "wtpt", "desc", "cprt"] {
assert!(tags.iter().any(|t| t == tag), "{profile}: {tag} in {tags:?}");
}
let back = cms::IccProfile::from_bytes(None, &icc).unwrap();
assert_eq!((back.name.as_str(), back.kind), (profile, cms::ProfileKind::Cmyk));
assert!(import(&r.bytes).is_ok());
}
// A condition identifier or registry the settings give stays.
let o = opts(Standard::PdfX4, |s| {
s.output.output_intent = cms::FOGRA51_CMYK.into();
s.output.output_condition_id = "Press 2".into();
});
let t = text(&export(&d, &o).unwrap());
assert!(t.contains("/OutputConditionIdentifier(Press 2)") && !t.contains("/RegistryName"), "{t}");
let o = opts(Standard::PdfX4, |s| {
s.output.output_intent = cms::FOGRA51_CMYK.into();
s.output.registry = "https://example.com/registry".into();
});
let t = text(&export(&d, &o).unwrap());
assert!(t.contains("/OutputConditionIdentifier(FOGRA51)") && t.contains("/RegistryName(https://example.com/registry)"));
// Other profiles keep their name as the identifier, with no registry.
let t = text(&export(&d, &opts(Standard::PdfX4, |s| s.output.output_intent = GENERIC_CMYK.into())).unwrap());
let id = GENERIC_CMYK.replace('(', r"\(").replace(')', r"\)");
assert!(t.contains(&format!("/OutputConditionIdentifier({id})")) && !t.contains("/RegistryName"), "{t}");
}
#[test]
fn pdfx_1a_files_have_no_rgb() {
let mut d = doc(&[Color::rgb(0.9, 0.1, 0.1), Color::Lab { l: 50.0, a: 40.0, b: -20.0 }, Color::gray(0.5), Color::cmyk(0.1, 0.2, 0.3, 0.4)]);
+2
View File
@@ -6624,6 +6624,8 @@ arrowhead Feather Перо
VectorCraft Default По подразбиране за VectorCraft
VectorCraft Defaults Стандартни настройки на VectorCraft
VectorCraft Generic CMYK (SWOP-like) Общ CMYK за VectorCraft (подобен на SWOP)
VectorCraft Coated CMYK (FOGRA51) Мелиран CMYK за VectorCraft (FOGRA51)
VectorCraft Uncoated CMYK (FOGRA52) Немелиран CMYK за VectorCraft (FOGRA52)
VectorCraft Swatches (.vcswatches) Образци на VectorCraft (.vcswatches)
Vertical Align Вертикално подравняване
Vertical Area Type Вертикално въвеждане в област
Can't render this file because it is too large.
+2
View File
@@ -657,6 +657,8 @@
RGB RGB
sRGB IEC61966-2.1 sRGB IEC61966-2.1
VectorCraft Generic CMYK (SWOP-like) VectorCraft generički CMYK (sličan SWOP-u)
VectorCraft Coated CMYK (FOGRA51) VectorCraft premazani CMYK (FOGRA51)
VectorCraft Uncoated CMYK (FOGRA52) VectorCraft nepremazani CMYK (FOGRA52)
Legacy Macintosh RGB (Gamma 1.8) Naslijeđeni Macintosh RGB (gama 1.8)
Internet Standard RGB (sRGB) Internet standardni RGB (sRGB)
Monitor RGB RGB monitora
Can't render this file because it contains an unexpected character in line 2 and column 73.
+2
View File
@@ -5970,6 +5970,8 @@ digits Malayalam Malaiàlam
VectorCraft didn't quit normally last time. These documents had unsaved changes: VectorCraft no es va tancar correctament l’última vegada. Aquests documents tenien canvis no desats:
VectorCraft documents: one locked object, updated when the file changes. Documents de VectorCraft: un objecte bloquejat, actualitzat quan canvia el fitxer.
VectorCraft Generic CMYK (SWOP-like) CMYK genèric de VectorCraft (similar a SWOP)
VectorCraft Coated CMYK (FOGRA51) CMYK estucat de VectorCraft (FOGRA51)
VectorCraft Uncoated CMYK (FOGRA52) CMYK no estucat de VectorCraft (FOGRA52)
VectorCraft Help… Ajuda de VectorCraft…
VectorCraft on getartcraft.com VectorCraft a getartcraft.com
VectorCraft on GitHub VectorCraft al GitHub
Can't render this file because it is too large.
+2
View File
@@ -669,6 +669,8 @@
RGB RGB
sRGB IEC61966-2.1 sRGB IEC61966-2.1
VectorCraft Generic CMYK (SWOP-like) VectorCraft obecný CMYK (podobný SWOP)
VectorCraft Coated CMYK (FOGRA51) VectorCraft natíraný CMYK (FOGRA51)
VectorCraft Uncoated CMYK (FOGRA52) VectorCraft nenatíraný CMYK (FOGRA52)
Legacy Macintosh RGB (Gamma 1.8) Starší Macintosh RGB (gama 1,8)
Internet Standard RGB (sRGB) Standardní internetové RGB (sRGB)
Monitor RGB RGB monitoru
Can't render this file because it is too large.
+2
View File
@@ -3441,6 +3441,8 @@ liquify-list-end {0}, {1} {0} og {1}
RGB RGB
sRGB IEC61966-2.1 sRGB IEC61966-2.1
VectorCraft Generic CMYK (SWOP-like) VectorCraft-generisk CMYK (SWOP-lignende)
VectorCraft Coated CMYK (FOGRA51) VectorCraft bestrøget CMYK (FOGRA51)
VectorCraft Uncoated CMYK (FOGRA52) VectorCraft ubestrøget CMYK (FOGRA52)
Legacy Macintosh RGB (Gamma 1.8) Ældre Macintosh RGB (gamma 1,8)
Internet Standard RGB (sRGB) Internetstandard-RGB (sRGB)
Monitor RGB Skærm-RGB
Can't render this file because it is too large.
+2
View File
@@ -6625,6 +6625,8 @@ arrowhead Feather Φτερό
VectorCraft Default Προεπιλογή VectorCraft
VectorCraft Defaults Προεπιλογές VectorCraft
VectorCraft Generic CMYK (SWOP-like) Γενικό CMYK του VectorCraft (τύπου SWOP)
VectorCraft Coated CMYK (FOGRA51) CMYK επιχρισμένου χαρτιού του VectorCraft (FOGRA51)
VectorCraft Uncoated CMYK (FOGRA52) CMYK μη επιχρισμένου χαρτιού του VectorCraft (FOGRA52)
VectorCraft Swatches (.vcswatches) Δείγματα χρωμάτων VectorCraft (.vcswatches)
Vertical Align Κατακόρυφη στοίχιση
Vertical Area Type Κατακόρυφο κείμενο περιοχής
Can't render this file because it is too large.
+2
View File
@@ -6795,6 +6795,8 @@ mark-style Japanese Japonesas
Variation Variación
VectorCraft Default Predeterminado de VectorCraft
VectorCraft Generic CMYK (SWOP-like) CMYK genérico de VectorCraft (similar a SWOP)
VectorCraft Coated CMYK (FOGRA51) CMYK estucado de VectorCraft (FOGRA51)
VectorCraft Uncoated CMYK (FOGRA52) CMYK no estucado de VectorCraft (FOGRA52)
VectorCraft Swatches (.vcswatches) Muestras de VectorCraft (.vcswatches)
Vertical Area Type Texto de área vertical
Vertical Type Texto vertical
Can't render this file because it is too large.
+2
View File
@@ -663,6 +663,8 @@
RGB RGB
sRGB IEC61966-2.1 sRGB IEC61966-2.1
VectorCraft Generic CMYK (SWOP-like) VectorCraftin yleinen CMYK (SWOP-tyyppinen)
VectorCraft Coated CMYK (FOGRA51) VectorCraftin päällystetty CMYK (FOGRA51)
VectorCraft Uncoated CMYK (FOGRA52) VectorCraftin päällystämätön CMYK (FOGRA52)
Legacy Macintosh RGB (Gamma 1.8) Vanha Macintosh RGB (gamma 1.8)
Internet Standard RGB (sRGB) Internetin standardi-RGB (sRGB)
Monitor RGB Näytön RGB
Can't render this file because it is too large.
+2
View File
@@ -6906,6 +6906,8 @@ arrowhead Feather Empennage
VectorCraft Default VectorCraft par défaut
VectorCraft Defaults Valeurs par défaut de VectorCraft
VectorCraft Generic CMYK (SWOP-like) CMJN générique VectorCraft (de type SWOP)
VectorCraft Coated CMYK (FOGRA51) CMJN couché VectorCraft (FOGRA51)
VectorCraft Uncoated CMYK (FOGRA52) CMJN non couché VectorCraft (FOGRA52)
VectorCraft Swatches (.vcswatches) Nuances VectorCraft (.vcswatches)
Vertical Align Alignement vertical
Vertical Area Type Texte captif vertical
Can't render this file because it is too large.
+2
View File
@@ -6399,6 +6399,8 @@ arrowhead Feather पंख
VectorCraft didn't quit normally last time. These documents had unsaved changes: पिछली बार VectorCraft सामान्य तरीके से बंद नहीं हुआ था। इन डॉक्यूमेंट्स में बिना सेव किए बदलाव थे:
VectorCraft documents: one locked object, updated when the file changes. VectorCraft डॉक्यूमेंट्स: एक लॉक्ड ऑब्जेक्ट, जो फ़ाइल बदलने पर अपडेट होता है।
VectorCraft Generic CMYK (SWOP-like) वेक्टर क्रेफ्ट जेनेरिक CMYK (SWOP-like)
VectorCraft Coated CMYK (FOGRA51) वेक्टर क्रेफ्ट कोटेड CMYK (FOGRA51)
VectorCraft Uncoated CMYK (FOGRA52) वेक्टर क्रेफ्ट अनकोटेड CMYK (FOGRA52)
VectorCraft Help… VectorCraft मदद…
VectorCraft on getartcraft.com getartcraft.com पर VectorCraft
VectorCraft on GitHub GitHub पर VectorCraft
Can't render this file because it is too large.
+2
View File
@@ -5344,6 +5344,8 @@ mark-style Japanese Japán
VectorCraft didn't quit normally last time. These documents had unsaved changes: A VectorCraft legutóbb nem szabályosan lépett ki. Ezekben a dokumentumokban mentetlen módosítások voltak:
VectorCraft documents: one locked object, updated when the file changes. VectorCraft-dokumentumok: egyetlen zárolt objektum, amely a fájl változásakor frissül.
VectorCraft Generic CMYK (SWOP-like) VectorCraft általános CMYK (SWOP-szerű)
VectorCraft Coated CMYK (FOGRA51) VectorCraft mázolt CMYK (FOGRA51)
VectorCraft Uncoated CMYK (FOGRA52) VectorCraft mázolatlan CMYK (FOGRA52)
VectorCraft Help… VectorCraft súgó…
VectorCraft on getartcraft.com A VectorCraft a getartcraft.com oldalon
VectorCraft on GitHub A VectorCraft a GitHubon
Can't render this file because it is too large.
+2
View File
@@ -1316,6 +1316,8 @@
RGB RGB
sRGB IEC61966-2.1 sRGB IEC61966-2.1
VectorCraft Generic CMYK (SWOP-like) CMYK generik VectorCraft (mirip SWOP)
VectorCraft Coated CMYK (FOGRA51) CMYK kertas berlapis VectorCraft (FOGRA51)
VectorCraft Uncoated CMYK (FOGRA52) CMYK kertas tanpa lapisan VectorCraft (FOGRA52)
Legacy Macintosh RGB (Gamma 1.8) RGB Macintosh lama (Gamma 1.8)
Internet Standard RGB (sRGB) RGB standar Internet (sRGB)
Monitor RGB RGB monitor
Can't render this file because it is too large.
+2
View File
@@ -8403,6 +8403,8 @@ mark-style Japanese იაპონური
Variation ვარიაცია
VectorCraft Default VectorCraft-ის ნაგულისხმევი
VectorCraft Generic CMYK (SWOP-like) VectorCraft-ის ზოგადი CMYK (SWOP-ის მსგავსი)
VectorCraft Coated CMYK (FOGRA51) VectorCraft-ის ცარციანი ქაღალდის CMYK (FOGRA51)
VectorCraft Uncoated CMYK (FOGRA52) VectorCraft-ის უცარცო ქაღალდის CMYK (FOGRA52)
VectorCraft Swatches (.vcswatches) VectorCraft-ის ფერის ნიმუშები (.vcswatches)
Vertical Area Type ვერტიკალური არის ტექსტი
Vertical Type ვერტიკალური ტექსტი
Can't render this file because it is too large.
+2
View File
@@ -1302,6 +1302,8 @@ liquify-list-end {0}, {1} {0} en {1}
RGB RGB
sRGB IEC61966-2.1 sRGB IEC61966-2.1
VectorCraft Generic CMYK (SWOP-like) Generieke VectorCraft-CMYK (SWOP-achtig)
VectorCraft Coated CMYK (FOGRA51) Gestreken VectorCraft-CMYK (FOGRA51)
VectorCraft Uncoated CMYK (FOGRA52) Ongestreken VectorCraft-CMYK (FOGRA52)
Legacy Macintosh RGB (Gamma 1.8) Verouderde Macintosh-RGB (Gamma 1.8)
Internet Standard RGB (sRGB) Internetstandaard-RGB (sRGB)
Monitor RGB Monitor-RGB
Can't render this file because it is too large.
+2
View File
@@ -6773,6 +6773,8 @@ mark-style Japanese Japonesas
Variation Variação
VectorCraft Default Padrão do VectorCraft
VectorCraft Generic CMYK (SWOP-like) CMYK Genérico do VectorCraft (tipo SWOP)
VectorCraft Coated CMYK (FOGRA51) CMYK Revestido do VectorCraft (FOGRA51)
VectorCraft Uncoated CMYK (FOGRA52) CMYK Não Revestido do VectorCraft (FOGRA52)
VectorCraft Swatches (.vcswatches) Amostras do VectorCraft (.vcswatches)
Vertical Area Type Texto de Área Vertical
Vertical Type Texto Vertical
Can't render this file because it is too large.
+2
View File
@@ -8005,6 +8005,8 @@ arrowhead Target Мишень
VectorCraft Default VectorCraft по умолчанию
VectorCraft Defaults Стандартные VectorCraft
VectorCraft Generic CMYK (SWOP-like) Общий CMYK VectorCraft (как SWOP)
VectorCraft Coated CMYK (FOGRA51) CMYK VectorCraft для мелованной бумаги (FOGRA51)
VectorCraft Uncoated CMYK (FOGRA52) CMYK VectorCraft для немелованной бумаги (FOGRA52)
VectorCraft Swatches (.vcswatches) Образцы VectorCraft (.vcswatches)
Vertical Align Вертикальное выравнивание
Vertical Area Type Вертикальный текст в области
Can't render this file because it is too large.
+2
View File
@@ -6817,6 +6817,8 @@ arrowhead Feather Fjäder
VectorCraft Default VectorCraft-standard
VectorCraft Defaults VectorCraft-standardvärden
VectorCraft Generic CMYK (SWOP-like) VectorCraft allmän CMYK (SWOP-liknande)
VectorCraft Coated CMYK (FOGRA51) VectorCraft bestruken CMYK (FOGRA51)
VectorCraft Uncoated CMYK (FOGRA52) VectorCraft obestruken CMYK (FOGRA52)
VectorCraft Swatches (.vcswatches) VectorCraft-färgrutor (.vcswatches)
Vertical Align Vertikal justering
Vertical Area Type Vertikal områdestext
Can't render this file because it is too large.
+2
View File
@@ -6662,6 +6662,8 @@ arrowhead Feather Tüy
VectorCraft Default VectorCraft Varsayılanı
VectorCraft Defaults VectorCraft Varsayılanları
VectorCraft Generic CMYK (SWOP-like) VectorCraft Genel CMYK (SWOP benzeri)
VectorCraft Coated CMYK (FOGRA51) VectorCraft Kaplamalı CMYK (FOGRA51)
VectorCraft Uncoated CMYK (FOGRA52) VectorCraft Kaplamasız CMYK (FOGRA52)
VectorCraft Swatches (.vcswatches) VectorCraft Renk Örnekleri (.vcswatches)
Vertical Align Dikey Hizalama
Vertical Area Type Dikey Alan Türü
Can't render this file because it is too large.
+2
View File
@@ -6212,6 +6212,8 @@ liquify-list-end {0}, {1} {0}和{1}
Photo Low Fidelity 低保真照片
Restricted Colors 受限颜色
VectorCraft Generic CMYK (SWOP-like) VectorCraft 通用 CMYK (类 SWOP)
VectorCraft Coated CMYK (FOGRA51) VectorCraft 涂布纸 CMYK (FOGRA51)
VectorCraft Uncoated CMYK (FOGRA52) VectorCraft 非涂布纸 CMYK (FOGRA52)
sRGB IEC61966-2.1 sRGB IEC61966-2.1
Working RGB 工作 RGB
Dot Gain 15% 网点扩大 15%
Can't render this file because it is too large.
+87
View File
@@ -59,6 +59,15 @@ pub(crate) fn row(ui: &mut Ui, label: &str, value: &str) -> bool {
clicked
}
/// Whether no artwork is selected. Artboards the Artboard tool has selected are not artwork:
/// `document.info` lists them under Document whatever this says.
fn no_artwork_selected(app: &VectorcraftApp) -> bool {
match app.session.active() {
Some(st) => st.selection.objects.is_empty(),
None => true,
}
}
/// `document.info` with its categories, fetched again only when the document, the scope or the
/// artboards the Artboard tool has selected change. A frame that fetches nothing returns the stored
/// result without copying it and stores nothing; a failed fetch leaves the stored result as it was.
@@ -85,6 +94,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let DocInfoView { selection_only: sel_only, category } = app.ui.doc_info.clone();
let mut copy = None;
Stack::new().show(ui, |ui, _| {
if sel_only && no_artwork_selected(app) {
Text::new(tl!("(No artwork selected)").to_string()).shade(Shade::Muted).show(ui);
}
let sections = i["sections"].as_array().map_or(&[][..], Vec::as_slice);
let shown = sections.iter().filter(|s| category.is_empty() || s["id"] == category.as_str());
for (n, s) in shown.enumerate() {
@@ -919,4 +931,79 @@ mod tests {
assert_eq!(in_lang("de", &json!({"type": "grid", "rows": 1, "cols": 3, "instances": 3})), "Rasterwiederholung, 1 Zeile × 3 Spalten");
assert_eq!(repeat_value(&json!({"type": "spiral", "instances": 2})), None);
}
/// Objects rows the panel paints with Selection Only `on`, the Objects category shown.
fn objects_panel(app: &mut VectorcraftApp, on: bool) -> String {
app.ui.doc_info.selection_only = on;
app.ui.doc_info.category = "objects".to_string();
crate::tests_labels::painted_text(app, show)
}
/// With Selection Only off, Objects counts every object in the document.
#[test]
fn test_doc_info_counts_entire_document() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 20})).unwrap();
app.session.execute("shape.rectangle", &json!({"x": 80, "y": 10, "width": 30, "height": 20})).unwrap();
app.session.execute("text.create", &json!({"x": 10, "y": 80, "text": "Hi"})).unwrap();
app.session.execute("select.none", &json!({})).unwrap();
let text = objects_panel(&mut app, false);
assert!(text.contains("Paths\n2\n") && text.contains("Text Objects\n1\n"), "{text}");
assert!(!text.contains("(No artwork selected)"), "{text}");
}
/// Selection Only counts the selected object and what it holds, and an empty selection says so.
#[test]
fn test_doc_info_selection_only_toggles_and_filters_counts() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let path = app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 20})).unwrap()["id"].clone();
let text_id = app.session.execute("text.create", &json!({"x": 10, "y": 80, "text": "Hi"})).unwrap()["id"].clone();
app.session.execute("select.set", &json!({"ids": [text_id]})).unwrap();
let text = objects_panel(&mut app, true);
assert!(text.contains("Text Objects\n1\n") && !text.contains("Paths\n"), "the selected type only: {text}");
app.session.execute("select.set", &json!({"ids": [path]})).unwrap();
let path_only = objects_panel(&mut app, true);
assert!(path_only.contains("Paths\n1\n") && !path_only.contains("Text Objects\n"), "the selected path only: {path_only}");
app.session.execute("select.none", &json!({})).unwrap();
let empty = objects_panel(&mut app, true);
assert!(empty.contains("(No artwork selected)") && !empty.contains("Paths\n") && !empty.contains("Text Objects\n"), "{empty}");
}
/// With Selection Only on, an artboard the Artboard tool has selected still shows under
/// Document when no artwork is selected, and the empty-state message speaks of artwork only.
#[test]
fn test_doc_info_selection_only_keeps_selected_artboard() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
app.session.execute("artboard.new", &json!({"x": 150, "y": 40, "width": 60, "height": 80})).unwrap();
app.session.execute("artboard.setProps", &json!({"index": 1, "name": "Back"})).unwrap();
app.session.execute("select.none", &json!({})).unwrap();
app.select_tool("artboard");
app.session.set_tool_option("selected", &json!([1]));
app.ui.doc_info.selection_only = true;
app.ui.doc_info.category = "document".to_string();
let text = crate::tests_labels::painted_text(&mut app, show);
assert!(text.contains("Back"), "the selected artboard: {text}");
assert!(!text.contains("(No selection)"), "no generic empty state: {text}");
assert!(text.contains("(No artwork selected)"), "{text}");
}
/// The panel menu's Selection Only item toggles `selection_only` and updates its checked state.
#[test]
fn test_doc_info_panel_menu_toggles_state() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let check = |app: &VectorcraftApp| {
let mut states = CommandStates::default();
menu_states(app, &mut states);
states.get(&CommandRef::new("ui.docInfo.selectionOnly")).and_then(CommandState::is_checked)
};
assert_eq!(check(&app), Some(false));
run(&mut app, "ui.docInfo.selectionOnly", &json!({})).unwrap().unwrap();
assert_eq!(check(&app), Some(true));
run(&mut app, "ui.docInfo.selectionOnly", &json!({})).unwrap().unwrap();
assert_eq!(check(&app), Some(false));
}
}
+5 -1
View File
File diff suppressed because one or more lines are too long
+12
View File
@@ -11839,6 +11839,18 @@ PDF/X-4 always embeds one), a TrimBox on every page (the artboard), `/Trapped` T
document has none) and dates; type is outlined or embedded; editing data, passwords and, in PDF/X-1a and PDF/X-3, PDF
layers are refused.
The built-in CMYK working spaces `VectorCraft Coated CMYK (FOGRA51)` and `VectorCraft Uncoated CMYK (FOGRA52)` are
VectorCraft's own press models, computed when first used from the FOGRA51 and FOGRA52 characterization data that Fogra
publishes (<https://fogra.org/en/downloads/work-tools/characterisation-data>); the data files ship unmodified in
`crates/color/data/`. An output intent with one of them, and with `output.outputConditionId` blank, has the
`/OutputConditionIdentifier` `FOGRA51` or `FOGRA52` and, unless `output.registry` names another, the `/RegistryName`
`http://www.color.org` (<https://registry.color.org/cmyk-registry/>), with the profile embedded. Their total ink limit
(300%) and black generation are VectorCraft's own values.
```json
{"name":"run_command","arguments":{"command":"document.exportPdf","params":{"path":"/tmp/press.pdf","preset":"PDF/X-4:2010","output":{"outputIntent":"VectorCraft Coated CMYK (FOGRA51)"}}}}
```
- **pdfX1a** (PDF/X-1a:2001, written as PDF 1.3): CMYK, grey and spot colours only. Every colour and image is converted
to `output.destination` (blank: the output intent's CMYK profile, else the working CMYK profile), untagged; an RGB
destination or output intent is refused. Transparency is flattened before writing.
File diff suppressed because one or more lines are too long