diff --git a/crates/color/Cargo.toml b/crates/color/Cargo.toml new file mode 100644 index 000000000..33cab3c95 --- /dev/null +++ b/crates/color/Cargo.toml @@ -0,0 +1,45 @@ +[package] +name = "craft-color" +description = "Colour for Craft apps: the colour picker, wells, swatch tables, ramps and the hex field." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true +autotests = false + +[lib] +# The lib's test target is the crate's one test executable: its trials and, with `screen-testing`, the +# screen tests in tests/it. +harness = false + +[lints] +workspace = true + +[features] +default = [] +# The colour widgets (`craft_color::ui`). +ui = ["dep:craft-behavior", "dep:craft-keymap", "dep:craft-ui", "dep:egui", "dep:craft-settings", "dep:craft-window", "craft-platform/screen"] +# Screenshot and input tests of the widgets with egui_kittest (desktop only). +screen-testing = ["ui", "craft-ui/testing"] + +[dependencies] +craft-behavior = { workspace = true, optional = true } +craft-cms = { workspace = true } +craft-host = { workspace = true } +craft-i18n = { workspace = true } +craft-keymap = { workspace = true, optional = true } +craft-platform = { workspace = true } +craft-settings = { workspace = true, optional = true } +craft-theme = { workspace = true } +craft-ui = { workspace = true, optional = true } +craft-window = { workspace = true, optional = true } +egui = { workspace = true, optional = true } +serde = { workspace = true } + +[dev-dependencies] +craft-ui = { workspace = true, features = ["testing"] } +egui = { workspace = true } + +[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] +egui_kittest = { version = "0.37", features = ["wgpu"] } diff --git a/crates/color/README.md b/crates/color/README.md new file mode 100644 index 000000000..2f4a1d0a5 --- /dev/null +++ b/crates/color/README.md @@ -0,0 +1,9 @@ +# craft-color + +Colour for Craft apps. With the `ui` feature, `craft_color::ui` has the colour picker (`ColorPicker`, `ColorPopover`, `ColorArea`, `ColorStrip`, `ColorWheel`, `ColorDisc`, `ColorRamp`), the wells (`SwatchPair`, `Well`), `SwatchPalette` tables and the `HexField`. It also has the colour features built on them: the Color Picker dialog (`ColorPickerDialog`), dialog droppers (`DropperButton`, `DropperState`), the Eyedropper's options and ring, Color Sampler points, the screen colour picker (`ScreenColorPicker`), `ColorChoice`, `PaintChip` and `PaintList` (with their `PaintKindLabels` and `PaintListLabels`), the Color and Swatches panels (`ColorPanel`, `SwatchesPanel`), the profile mismatch prompt, the harmony wheel and Color Guide panel, and the `LutPicker`. + +Stories: `patterns/color/{picker-dialog, panel, swatches, eyedropper-bar, samplers, paint-chip, choice, harmony, lut-picker, profile-mismatch}` show each of those features in its states. The two dialogs run on a `DialogHost` (a "Show dialog" button in an Overview tile). The screen eyedropper is off in the stories, so none starts a screen capture. + +Without `ui`: `CmykModel` (CMYK through a craft-cms profile), swatch files (`palette`: `.aco`, `.act`, `.ase`, `.gpl`, `.css`), the display transform and its caches (`display`), and colour harmonies (`harmony`). + +The colour model and conversions are in `craft-theme`; profiles and transforms in `craft-cms`. diff --git a/crates/color/src/cmyk.rs b/crates/color/src/cmyk.rs new file mode 100644 index 000000000..868796ec7 --- /dev/null +++ b/crates/color/src/cmyk.rs @@ -0,0 +1,73 @@ +//! [`CmykModel`]: a colour as the inks of one CMYK profile. + +use craft_cms::convert::CmykConverter; +use craft_theme::{Channel, ColorModel, DefaultOn, MAX_CHANNELS, ModelValues, Srgba}; + +/// CMYK through a CMYK profile, as Photoshop's and PhotoCraft's Color Picker show it: four +/// channels C, M, Y and K, ink in percent (0 no ink, 100 full). It converts through the +/// [`CmykConverter`] it holds (the document's CMYK profile, or the built-in coated CMYK), so the +/// same sRGB colour reads as different inks in different documents. +/// +/// A host offers it by passing it to the picker +/// (`ColorPicker::models`, feature `ui`); the +/// `ColorPickerDialog` adds it when it is given a +/// `ColorPickerDialog::gamut`. Inks the user typed stay as typed while they +/// still give the colour (`PickedColor::model`): a CMYK document +/// fills with them, not with what its sRGB stand-in converts back to (storytold/photocraft#4196). +#[derive(Clone)] +pub struct CmykModel { + converter: CmykConverter, +} + +const CMYK_CHANNELS: [Channel; 4] = [ + Channel { name: "Cyan", qualified: "CMYK cyan", label: "C", min: 0.0, max: 100.0, unit: "%", decimals: 0, step: 1.0, track_stops: 9 }, + Channel { name: "Magenta", qualified: "CMYK magenta", label: "M", min: 0.0, max: 100.0, unit: "%", decimals: 0, step: 1.0, track_stops: 9 }, + Channel { name: "Yellow", qualified: "CMYK yellow", label: "Y", min: 0.0, max: 100.0, unit: "%", decimals: 0, step: 1.0, track_stops: 9 }, + Channel { name: "Black", qualified: "CMYK black", label: "K", min: 0.0, max: 100.0, unit: "%", decimals: 0, step: 1.0, track_stops: 9 }, +]; + +impl CmykModel { + /// The model on `converter` (cheap: the transforms are shared). + pub fn new(converter: CmykConverter) -> CmykModel { + CmykModel { converter } + } + + /// The converter the model converts through. + pub fn converter(&self) -> &CmykConverter { + &self.converter + } +} + +impl std::fmt::Debug for CmykModel { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CmykModel").field("profile", &self.converter.profile().description).finish() + } +} + +impl ColorModel for CmykModel { + fn id(&self) -> &'static str { + "cmyk" + } + fn name(&self) -> &'static str { + "CMYK" + } + fn channels(&self) -> &[Channel] { + &CMYK_CHANNELS + } + // pc: crates/ui-egui/src/dialogs/color_picker_ui.rs:298 `Components` (cmyk from + // `photocraft_color::convert::rgb_to_cmyk`); `self.converter.from_srgb([r, g, b])` scaled to + // percent. + fn from_srgb(&self, color: Srgba) -> ModelValues { + let inks = self.converter.from_srgb([color.r, color.g, color.b]); + ModelValues::new("cmyk", &inks.map(|v| v * 100.0)) + } + // pc: crates/ui-egui/src/dialogs/color_picker_ui.rs:722 (typed inks to sRGB through + // `cmyk_to_rgb`); `self.converter.to_srgb(values / 100)`, opaque. + fn to_srgb(&self, values: &[f32; MAX_CHANNELS]) -> Srgba { + let rgb = self.converter.to_srgb([values[0] / 100.0, values[1] / 100.0, values[2] / 100.0, values[3] / 100.0]); + Srgba { r: rgb[0].clamp(0.0, 1.0), g: rgb[1].clamp(0.0, 1.0), b: rgb[2].clamp(0.0, 1.0), a: 1.0 } + } + fn default_on(&self) -> DefaultOn { + DefaultOn { full: false, compact: false } + } +} diff --git a/crates/color/src/display.rs b/crates/color/src/display.rs new file mode 100644 index 000000000..00a4428df --- /dev/null +++ b/crates/color/src/display.rs @@ -0,0 +1,332 @@ +//! The display transform (F04.11): how a canvas shows a document's colours on a monitor. Pixels +//! in the document's profile go through one cached transform to the monitor's profile; when that +//! transform changes nothing, the canvas skips it. +//! +//! The monitor profile comes from the platform (craft-platform's display reading, or the ICC +//! bytes of a `craft_platform::screen::ScreenImage`) or from the app's Color Settings; a +//! profile that is missing, unreadable, not RGB or unusable as a destination falls back to sRGB, +//! and [`MonitorStatus`] says why. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use craft_cms::transform::{TransformOptions, cached}; +use craft_cms::{Builtin, CmsError, ColorSpace, Profile, Transform}; + +/// Rendering intent and black point compensation of every display transform: relative +/// colorimetric with BPC, as Photoshop's default monitor conversion and PhotoCraft's. +pub const DISPLAY_INTENT: craft_cms::Intent = craft_cms::Intent::RelativeColorimetric; + +/// A display, as the platform numbers it; `None` is "the main window's display". +pub type DisplayId = Option; + +/// Bytes per conversion chunk of [`DisplayTransform::apply_rgba8`] (a whole number of pixels). +const CHUNK_BYTES: usize = 4 * 65536; + +/// Most cached transforms before the cache is cleared. +const MAX_TRANSFORMS: usize = 32; + +fn hash_of(v: impl std::hash::Hash) -> u64 { + use std::hash::Hasher; + let mut h = std::collections::hash_map::DefaultHasher::new(); + v.hash(&mut h); + h.finish() +} + +/// The [`DisplayTransform::key`] of a source and monitor pair. Whether the transform is the +/// identity follows from the pair, so it is not part of the key. +fn signature(source: &Profile, monitor: &Profile) -> u64 { + hash_of((source.content_hash(), monitor.content_hash())) +} + +/// Does `t` map every lattice point (the neutral axis only for a grey source) to itself within +/// half an 8-bit step? +fn is_identity(t: &Transform, neutral_only: bool) -> bool { + const N: usize = 9; + let s = (N - 1) as f32; + let mut out = [0.0f32; 16]; + let mut check = |v: [f32; 3]| match t.eval(&v, &mut out) { + Ok(()) => (0..3).all(|i| (out[i] - v[i]).abs() <= 0.5 / 255.0), + Err(_) => false, + }; + if neutral_only { + return (0..=32).all(|i| check([i as f32 / 32.0; 3])); + } + (0..N).all(|b| (0..N).all(|g| (0..N).all(|r| check([r as f32 / s, g as f32 / s, b as f32 / s])))) +} + +/// `profile` as a monitor profile: it must be RGB and usable as the destination of a transform +/// from sRGB, otherwise the canvas would silently stay unmanaged. +fn usable_monitor(profile: Profile) -> Result, MonitorProblem> { + if profile.color_space != ColorSpace::Rgb { + return Err(MonitorProblem::NotRgb { description: profile.description, space: profile.color_space }); + } + let opts = TransformOptions { intent: DISPLAY_INTENT, bpc: true, ..TransformOptions::default() }; + cached(Builtin::Srgb.profile(), &profile, opts) + .map_err(|e| MonitorProblem::CannotLink { description: profile.description.clone(), reason: e.to_string() })?; + Ok(Arc::new(profile)) +} + +fn srgb_entry(status: MonitorStatus) -> MonitorEntry { + MonitorEntry { profile: Arc::new(Builtin::Srgb.profile().clone()), status } +} + +/// How one document profile shows on one monitor. +#[derive(Debug)] +pub struct DisplayTransform { + /// The profile of the values the canvas texture holds (the document's composite profile). + pub source: Arc, + /// The monitor profile. + pub monitor: Arc, + /// Texture values to monitor values; `None` when that is the identity within half an 8-bit + /// step on every lattice point (the neutral axis only for a grey source). + pub transform: Option>, + /// Changes whenever any of the above changes, for the canvas's LUT and texture caches. + pub key: u64, +} + +impl DisplayTransform { + /// The transform from `source` to `monitor` ([`DISPLAY_INTENT`], BPC), built through + /// `craft_cms::cached`; `transform` is `None` when it is the identity. + // pc: crates/engine/src/display_color.rs:413 `canvas_display_for` (the build part) and :151 + // `is_identity` (9³ lattice, half an 8-bit step; the 33 grey steps for a grey source). + pub fn new(source: Arc, monitor: Arc) -> Result { + let key = signature(&source, &monitor); + let transform = if source.content_hash() == monitor.content_hash() { + None + } else { + let opts = TransformOptions { intent: DISPLAY_INTENT, bpc: true, ..TransformOptions::default() }; + let t = cached(&source, &monitor, opts)?; + (!is_identity(&t, source.color_space == ColorSpace::Gray)).then_some(t) + }; + Ok(DisplayTransform { source, monitor, transform, key }) + } + + /// Values go to the screen unchanged. + pub fn is_identity(&self) -> bool { + self.transform.is_none() + } + + /// `rgb` (0–1 each, in the source profile) as the monitor shows it. + // pc: crates/engine/src/display_color.rs:38 `CanvasDisplay` (callers use `transform.eval`). + pub fn apply(&self, rgb: [f32; 3]) -> [f32; 3] { + let Some(t) = &self.transform else { return rgb }; + let mut out = [0.0f32; 16]; + match t.eval(&rgb, &mut out) { + Ok(()) => [out[0], out[1], out[2]], + Err(_) => rgb, + } + } + + /// RGBA8 pixels converted in place (alpha untouched); nothing happens for the identity. + // new: the canvas's CPU path and the screen picker's loupe convert whole rows. + pub fn apply_rgba8(&self, pixels: &mut [u8]) { + let Some(t) = &self.transform else { return }; + // `convert_u8` reads and writes separate buffers: convert from a copy, a chunk at a time. + let mut src = Vec::with_capacity(CHUNK_BYTES.min(pixels.len())); + for chunk in pixels.chunks_mut(CHUNK_BYTES).map(|c| { + let n = c.len() / 4 * 4; + &mut c[..n] + }) { + src.clear(); + src.extend_from_slice(chunk); + if t.convert_u8(&src, 4, chunk, 4, true).is_err() { + chunk.copy_from_slice(&src); + } + } + } +} + +/// Why the monitor profile is what it is. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum MonitorStatus { + /// The display's own profile, as the platform reported it. + Detected, + /// The profile the app chose (Color Settings › Monitor Profile). + Chosen, + /// sRGB: the platform reports no profile for the display. + NoProfile, + /// sRGB: the profile could not be used, with the reason. + Unusable(MonitorProblem), +} + +/// Why a monitor profile cannot be used. The UI words it (`MonitorProblem::label`, with the +/// `ui` feature). +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum MonitorProblem { + /// The profile describes another colour space than RGB. + NotRgb { + /// The profile's description text, for display. + description: String, + /// The colour space the profile declares. + space: ColorSpace, + }, + /// The profile cannot link to sRGB as a destination; `reason` is the colour engine's text. + CannotLink { + /// The profile's description text, for display. + description: String, + /// The colour engine's error text. + reason: String, + }, + /// The profile bytes do not parse; `reason` is the parser's text. + Unreadable { + /// The parser's error text. + reason: String, + }, +} + +/// One monitor's profile and how it was resolved. +#[derive(Clone, Debug)] +struct MonitorEntry { + profile: Arc, + status: MonitorStatus, +} + +/// The app's display caches: the monitor profile per display, and the [`DisplayTransform`] per +/// document profile and display. Shared by every window; `Sync`. +#[derive(Default)] +pub struct DisplayCaches { + monitors: Mutex>, + chosen: Mutex>, + transforms: Mutex>>, +} + +fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + +const _: () = { + const fn shared() {} + shared::(); +}; + +impl DisplayCaches { + /// Empty caches: no monitor profile and no transform yet. + pub fn new() -> DisplayCaches { + DisplayCaches::default() + } + + /// Records the platform's reading of `display`'s profile (`icc` bytes, `None` when it has + /// none). A reading that fails to parse keeps the previous good one. Drops the cached + /// transforms of that display. + // pc: crates/engine/src/display_color.rs:301 (`set_displays`: a failed re-read keeps the + // displays read before) and the monitor cache at :268. + pub fn set_monitor(&self, display: DisplayId, icc: Option<&[u8]>) { + let entry = match icc { + None => srgb_entry(MonitorStatus::NoProfile), + Some(bytes) => match Profile::parse(bytes) { + Ok(p) => match usable_monitor(p) { + Ok(profile) => MonitorEntry { profile, status: MonitorStatus::Detected }, + Err(reason) => srgb_entry(MonitorStatus::Unusable(reason)), + }, + Err(e) => { + if let std::collections::hash_map::Entry::Vacant(v) = lock(&self.monitors).entry(display) { + v.insert(srgb_entry(MonitorStatus::Unusable(MonitorProblem::Unreadable { reason: e.to_string() }))); + lock(&self.transforms).clear(); + } + return; + } + }, + }; + lock(&self.monitors).insert(display, entry); + // The main window's display also stands in for unknown displays. + lock(&self.transforms).clear(); + } + + /// The app's choice of monitor profile (Color Settings), or `None` to use each display's own. + /// Drops every cached transform. + // pc: crates/engine/src/display_color.rs:338 `resolved_monitor` (the `auto` / chosen branch). + pub fn choose_monitor(&self, profile: Option>) { + let entry = profile.map(|p| match usable_monitor((*p).clone()) { + Ok(profile) => MonitorEntry { profile, status: MonitorStatus::Chosen }, + Err(reason) => srgb_entry(MonitorStatus::Unusable(reason)), + }); + *lock(&self.chosen) = entry; + lock(&self.transforms).clear(); + } + + /// The monitor profile for `display`: the chosen one, else the display's own, else the + /// primary display's when `display` is unknown, else sRGB. + // pc: crates/engine/src/display_color.rs:284 `monitor_for`, :338 `resolved_monitor`. + pub fn monitor_for(&self, display: DisplayId) -> Arc { + self.resolve(display).profile + } + + /// What [`monitor_for`](Self::monitor_for) resolved to, and why. + // pc: crates/engine/src/display_color.rs:294 `monitor_status_for`. + pub fn monitor_status(&self, display: DisplayId) -> MonitorStatus { + self.resolve(display).status + } + + fn resolve(&self, display: DisplayId) -> MonitorEntry { + if let Some(e) = lock(&self.chosen).clone() { + return e; + } + let monitors = lock(&self.monitors); + monitors.get(&display).or_else(|| monitors.get(&None)).cloned().unwrap_or_else(|| srgb_entry(MonitorStatus::NoProfile)) + } + + /// How a canvas in `source`'s profile shows on `display`, cached per source content and + /// display. + // pc: crates/engine/src/display_color.rs:413 `canvas_display_for`. + pub fn canvas_display_for(&self, source: &Arc, display: DisplayId) -> Result, CmsError> { + let monitor = self.monitor_for(display); + let cache_key = (source.content_hash(), display); + if let Some(d) = lock(&self.transforms).get(&cache_key) + && d.monitor.content_hash() == monitor.content_hash() + { + return Ok(d.clone()); + } + let d = Arc::new(DisplayTransform::new(source.clone(), monitor)?); + let mut cache = lock(&self.transforms); + if cache.len() >= MAX_TRANSFORMS { + cache.clear(); + } + cache.insert(cache_key, d.clone()); + Ok(d) + } + + /// Changes whenever the transform of `source` on `display` changes (source, monitor, chosen + /// profile): what a canvas compares to know its texture or LUT is stale. + // pc: crates/engine/src/display_color.rs:453 `display_signature_for` (without Proof Colors, + // Gamut Warning and the 32-bit preview: those are the app's and go into its own key). + pub fn display_signature(&self, source: &Profile, display: DisplayId) -> u64 { + signature(source, &self.monitor_for(display)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use craft_ui::testing::trial; + + fn p3() -> Arc { + Arc::new(Builtin::DisplayP3.profile().clone()) + } + + fn srgb() -> Arc { + Arc::new(Builtin::Srgb.profile().clone()) + } + + /// Choosing another monitor profile changes the signature and drops the cached transform. + #[trial] + fn choosing_a_monitor_profile_changes_the_signature() { + let caches = DisplayCaches::new(); + let source = srgb(); + let before = caches.display_signature(&source, None); + let first = caches.canvas_display_for(&source, None).unwrap(); + assert!(Arc::ptr_eq(&first, &caches.canvas_display_for(&source, None).unwrap())); + + caches.choose_monitor(Some(p3())); + assert_eq!(caches.monitor_status(None), MonitorStatus::Chosen); + assert_ne!(caches.display_signature(&source, None), before); + let second = caches.canvas_display_for(&source, None).unwrap(); + assert!(!Arc::ptr_eq(&first, &second)); + assert_eq!(second.key, caches.display_signature(&source, None)); + + caches.choose_monitor(None); + assert_eq!(caches.display_signature(&source, None), before); + } +} diff --git a/crates/color/src/gray.rs b/crates/color/src/gray.rs new file mode 100644 index 000000000..c06ff3cf5 --- /dev/null +++ b/crates/color/src/gray.rs @@ -0,0 +1,35 @@ +//! [`GrayModel`]: the grey level of a colour. + +use craft_theme::{Channel, ColorModel, DefaultOn, MAX_CHANNELS, ModelValues, Srgba}; + +/// Grayscale, as Photoshop's Color panel Grayscale Slider: one channel, K, the black ink in +/// percent (0 white, 100 black). A colour reads as the luma of its encoded sRGB values (Rec. 601 +/// weights); K converts back to the equal grey. Offered in no picker unless the host asks. +#[derive(Clone, Copy, Debug)] +pub struct GrayModel; + +const GRAY_CHANNELS: [Channel; 1] = + [Channel { name: "Gray", qualified: "Grayscale gray", label: "K", min: 0.0, max: 100.0, unit: "%", decimals: 0, step: 1.0, track_stops: 2 }]; + +impl ColorModel for GrayModel { + fn id(&self) -> &'static str { + "gray" + } + fn name(&self) -> &'static str { + "Grayscale" + } + fn channels(&self) -> &[Channel] { + &GRAY_CHANNELS + } + fn from_srgb(&self, color: Srgba) -> ModelValues { + let luma = 0.299 * color.r + 0.587 * color.g + 0.114 * color.b; + ModelValues::new(self.id(), &[(1.0 - luma) * 100.0]) + } + fn to_srgb(&self, values: &[f32; MAX_CHANNELS]) -> Srgba { + let level = 1.0 - values[0] / 100.0; + Srgba::rgb(level, level, level) + } + fn default_on(&self) -> DefaultOn { + DefaultOn { full: false, compact: false } + } +} diff --git a/crates/color/src/harmony.rs b/crates/color/src/harmony.rs new file mode 100644 index 000000000..24e53899f --- /dev/null +++ b/crates/color/src/harmony.rs @@ -0,0 +1,385 @@ +//! Colour harmonies (F04.16): groups of colours built from a base colour by turning its hue and +//! scaling its saturation and brightness, the variation grid round each, and five-colour themes. +//! VectorCraft's Color Guide and Color Themes math, on encoded sRGB through HSB. +//! +//! ```no_run +//! use craft_color::harmony::{Guide, GuideOptions, Harmony}; +//! use craft_theme::Srgba; +//! let base = Srgba::rgb(0.24, 0.39, 0.87); +//! let triad = Harmony::Triad.apply(base); // base first, then two partners +//! let guide = Guide::new(base, Harmony::Triad, &GuideOptions::default()); +//! ``` + +use craft_theme::{Hsb, Srgba}; + +/// A harmony rule: a group of colours built from a base colour, base first. VectorCraft's 21 +/// rules, in its menu order ([`Harmony::ALL`]). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Harmony { + #[default] + #[allow(missing_docs)] + Complementary, + #[allow(missing_docs)] + Complementary2, + #[allow(missing_docs)] + SplitComplementary, + #[allow(missing_docs)] + LeftComplement, + #[allow(missing_docs)] + RightComplement, + #[allow(missing_docs)] + Analogous, + #[allow(missing_docs)] + Analogous2, + #[allow(missing_docs)] + Monochromatic, + #[allow(missing_docs)] + Shades, + #[allow(missing_docs)] + Triad, + #[allow(missing_docs)] + Triad2, + #[allow(missing_docs)] + Triad3, + #[allow(missing_docs)] + Tetrad, + #[allow(missing_docs)] + Tetrad2, + #[allow(missing_docs)] + Tetrad3, + #[allow(missing_docs)] + Compound, + #[allow(missing_docs)] + Compound2, + #[allow(missing_docs)] + HighContrast, + #[allow(missing_docs)] + HighContrast2, + #[allow(missing_docs)] + HighContrast3, + #[allow(missing_docs)] + Pentagram, +} + +/// One colour of a rule: the base turned by `turn` degrees of hue, its saturation scaled by `sat` +/// and its brightness scaled or flipped to the contrasting one. +#[derive(Clone, Copy)] +struct Tone { + turn: f32, + sat: f32, + bright: Bright, +} + +#[derive(Clone, Copy)] +enum Bright { + Times(f32), + /// Dark for a light base, light for a dark one ([`contrast`]). + Contrast, +} + +const fn sv(turn: f32, sat: f32, bright: f32) -> Tone { + Tone { turn, sat, bright: Bright::Times(bright) } +} +/// The base's hue turned by `turn`. +const fn t(turn: f32) -> Tone { + sv(turn, 1.0, 1.0) +} +/// A softer (half as saturated) partner. +const fn soft(turn: f32) -> Tone { + sv(turn, 0.5, 1.0) +} +/// A deeper (darker) partner. +const fn deep(turn: f32) -> Tone { + sv(turn, 1.0, 0.6) +} +/// A partner of contrasting brightness. +const fn hc(turn: f32) -> Tone { + Tone { turn, sat: 1.0, bright: Bright::Contrast } +} + +/// The brightness that contrasts with `v`. +fn contrast(v: f32) -> f32 { + if v >= 0.5 { v * 0.3 } else { 0.7 + 0.3 * v } +} + +fn lab(c: Srgba) -> [f64; 3] { + let l = c.to_lab(); + [l.l, l.a, l.b].map(f64::from) +} + +fn hsb(h: f32, s: f32, b: f32) -> Srgba { + Srgba::from_hsb(Hsb { h, s, b }) +} + +impl Harmony { + /// Every rule, in the menu's order. + pub const ALL: [Harmony; 21] = [ + Harmony::Complementary, + Harmony::Complementary2, + Harmony::SplitComplementary, + Harmony::LeftComplement, + Harmony::RightComplement, + Harmony::Analogous, + Harmony::Analogous2, + Harmony::Monochromatic, + Harmony::Shades, + Harmony::Triad, + Harmony::Triad2, + Harmony::Triad3, + Harmony::Tetrad, + Harmony::Tetrad2, + Harmony::Tetrad3, + Harmony::Compound, + Harmony::Compound2, + Harmony::HighContrast, + Harmony::HighContrast2, + Harmony::HighContrast3, + Harmony::Pentagram, + ]; + + /// The rule's id, camelCase as its serialised name ("splitComplementary", "highContrast2"): the + /// key of its name among the UI's words (`harmony.rule.`). + pub fn id(self) -> &'static str { + match self { + Harmony::Complementary => "complementary", + Harmony::Complementary2 => "complementary2", + Harmony::SplitComplementary => "splitComplementary", + Harmony::LeftComplement => "leftComplement", + Harmony::RightComplement => "rightComplement", + Harmony::Analogous => "analogous", + Harmony::Analogous2 => "analogous2", + Harmony::Monochromatic => "monochromatic", + Harmony::Shades => "shades", + Harmony::Triad => "triad", + Harmony::Triad2 => "triad2", + Harmony::Triad3 => "triad3", + Harmony::Tetrad => "tetrad", + Harmony::Tetrad2 => "tetrad2", + Harmony::Tetrad3 => "tetrad3", + Harmony::Compound => "compound", + Harmony::Compound2 => "compound2", + Harmony::HighContrast => "highContrast", + Harmony::HighContrast2 => "highContrast2", + Harmony::HighContrast3 => "highContrast3", + Harmony::Pentagram => "pentagram", + } + } + + /// The rule's colours, the base first. Each partner is the base with its hue turned, its + /// saturation scaled and its brightness scaled or flipped to the contrasting one (dark for a + /// light base, light for a dark one). Alpha is the base's. + // inv-vectorcraft: crates/color/src/harmony.rs:178 `apply`, with the `tones` table at :36–70 + // (`t`, `soft`, `deep`, `hc`) and `contrast` at :72; `keep_model` is not needed (sRGB only). + pub fn apply(self, base: Srgba) -> Vec { + let Hsb { h, s, b: v } = base.to_hsb(); + std::iter::once(base) + .chain(self.tones()[1..].iter().map(|tone| { + let b = match tone.bright { + Bright::Times(f) => v * f, + Bright::Contrast => contrast(v), + }; + hsb(h + tone.turn, (s * tone.sat).clamp(0.0, 1.0), b.clamp(0.0, 1.0)).with_alpha(base.a) + })) + .collect() + } + + fn tones(self) -> &'static [Tone] { + match self { + Harmony::Complementary => const { &[t(0.0), t(180.0)] }, + Harmony::Complementary2 => const { &[t(0.0), soft(0.0), t(180.0), soft(180.0)] }, + Harmony::SplitComplementary => const { &[t(0.0), t(150.0), t(210.0)] }, + Harmony::LeftComplement => const { &[t(0.0), t(-30.0), t(150.0)] }, + Harmony::RightComplement => const { &[t(0.0), t(30.0), t(210.0)] }, + Harmony::Analogous => const { &[t(0.0), t(30.0), t(-30.0)] }, + Harmony::Analogous2 => const { &[t(0.0), t(30.0), t(60.0), t(-30.0), t(-60.0)] }, + Harmony::Monochromatic => const { &[t(0.0), sv(0.0, 0.5, 1.0), sv(0.0, 1.0, 0.6), sv(0.0, 0.25, 1.0), sv(0.0, 1.0, 0.35)] }, + Harmony::Shades => const { &[t(0.0), sv(0.0, 1.0, 0.8), sv(0.0, 1.0, 0.6), sv(0.0, 1.0, 0.4), sv(0.0, 1.0, 0.2)] }, + Harmony::Triad => const { &[t(0.0), t(120.0), t(240.0)] }, + Harmony::Triad2 => const { &[t(0.0), t(120.0), soft(120.0), t(240.0), soft(240.0)] }, + Harmony::Triad3 => const { &[t(0.0), t(120.0), deep(120.0), t(240.0), deep(240.0)] }, + Harmony::Tetrad => const { &[t(0.0), t(60.0), t(180.0), t(240.0)] }, + Harmony::Tetrad2 => const { &[t(0.0), t(90.0), t(180.0), t(270.0)] }, + Harmony::Tetrad3 => const { &[t(0.0), t(30.0), t(180.0), t(210.0)] }, + Harmony::Compound => const { &[t(0.0), t(40.0), t(160.0), t(200.0)] }, + Harmony::Compound2 => const { &[t(0.0), t(-40.0), t(160.0), t(200.0)] }, + Harmony::HighContrast => const { &[t(0.0), hc(180.0)] }, + Harmony::HighContrast2 => const { &[t(0.0), hc(0.0), t(180.0), hc(180.0)] }, + Harmony::HighContrast3 => const { &[t(0.0), hc(120.0), hc(240.0)] }, + Harmony::Pentagram => const { &[t(0.0), t(72.0), t(144.0), t(216.0), t(288.0)] }, + } + } + + /// A [`THEME_SIZE`]-colour theme from `base`: the rule's colours, each followed by lighter or + /// darker variations that fill the remaining places (the rule's first colours get them + /// first), base first. + // inv-vectorcraft: crates/color/src/harmony.rs:194 `theme`. + pub fn theme(self, base: Srgba) -> Vec { + let colors = self.apply(base); + let n = colors.len(); + let mut rows: Vec> = colors.iter().map(|c| vec![*c]).collect(); + let options = GuideOptions::default(); + for k in 0..THEME_SIZE.saturating_sub(n) { + let (i, pass) = (k % n, k / n); + // Alternate lighter and darker along the rule and from one pass to the next. + let step = if (i + pass) % 2 == 0 { 3 } else { -3 }; + rows[i].push(variation(colors[i], &options, step)); + } + rows.into_iter().flatten().take(THEME_SIZE).collect() + } +} + +/// The number of colours in a colour theme. +pub const THEME_SIZE: usize = 5; + +/// Moves colour `i` of a harmony on the hue and saturation wheel to `hsb` (hue in degrees, +/// saturation and brightness 0–1). With `linked` the other colours keep their relation to it: +/// they turn by the same hue, scale their saturation alike and shift their brightness by as +/// much. An index past the end changes nothing. +// inv-vectorcraft: crates/color/src/harmony.rs:216 `move_on_wheel`. +pub fn move_on_wheel(colors: &mut [Srgba], i: usize, target: [f32; 3], linked: bool) { + let Some(&old) = colors.get(i) else { return }; + let Hsb { h: h0, s: s0, b: v0 } = old.to_hsb(); + let (dh, ratio, dv) = (target[0] - h0, if s0 > 0.01 { target[1] / s0 } else { 1.0 }, target[2] - v0); + for (j, c) in colors.iter_mut().enumerate() { + let new = if j == i { + target + } else if linked { + let Hsb { h, s, b } = c.to_hsb(); + [h + dh, (s * ratio).clamp(0.0, 1.0), (b + dv).clamp(0.0, 1.0)] + } else { + continue; + }; + *c = hsb(new[0], new[1], new[2]).with_alpha(c.a); + } +} + +/// What the variation grid varies. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Variation { + /// Towards black (left) and white (right): Show Tints/Shades. + #[default] + TintsShades, + /// Towards cool and warm: Show Warm/Cool. + WarmCool, + /// Towards grey and full saturation: Show Vivid/Muted. + VividMuted, +} + +impl Variation { + /// The three variations in menu order. + pub const ALL: [Variation; 3] = [Variation::TintsShades, Variation::WarmCool, Variation::VividMuted]; + + /// The grid's ends, English (words keys): ("Shades", "Tints"), ("Cool", "Warm"), + /// ("Muted", "Vivid"). + pub fn sides(self) -> (&'static str, &'static str) { + match self { + Variation::TintsShades => ("Shades", "Tints"), + Variation::WarmCool => ("Cool", "Warm"), + Variation::VividMuted => ("Muted", "Vivid"), + } + } +} + +/// The variation grid's options: what it varies, steps on each side and how far they reach. +#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct GuideOptions { + /// Which axis the grid varies along. + pub variation: Variation, + /// Variations on each side of a harmony colour, 1 to [`GuideOptions::MAX_STEPS`]. + pub steps: u32, + /// How far the outermost variations go, 0–100 (Less … More): 10 % to 90 % of the way. + pub amount: f32, +} + +impl Default for GuideOptions { + fn default() -> Self { + GuideOptions { variation: Variation::TintsShades, steps: 4, amount: 50.0 } + } +} + +impl GuideOptions { + /// Largest accepted value of `steps`. + pub const MAX_STEPS: u32 = 20; + + /// The options with `steps` and `amount` in their ranges. + pub fn clamped(self) -> GuideOptions { + GuideOptions { steps: self.steps.clamp(1, Self::MAX_STEPS), amount: self.amount.clamp(0.0, 100.0), ..self } + } +} + +/// The variation of `color` at `step` (−steps to +steps; negative towards shades, cool or muted, +/// positive towards tints, warm or vivid; 0 is `color`). +// inv-vectorcraft: crates/color/src/harmony.rs:299 `variation`, :292 `reach`. +pub fn variation(color: Srgba, options: &GuideOptions, step: i32) -> Srgba { + if step == 0 { + return color; + } + let reach = 0.1 + 0.8 * options.amount.clamp(0.0, 100.0) / 100.0; + let f = (step.unsigned_abs() as f32 / options.steps.max(1) as f32).min(1.0) * reach; + let lerp = |to: Srgba, t: f32| Srgba::rgb(color.r + (to.r - color.r) * t, color.g + (to.g - color.g) * t, color.b + (to.b - color.b) * t); + let v = match options.variation { + Variation::TintsShades => lerp(if step < 0 { Srgba::BLACK } else { Srgba::WHITE }, f), + Variation::WarmCool => lerp(if step < 0 { Srgba::rgb(0.2, 0.45, 1.0) } else { Srgba::rgb(1.0, 0.55, 0.1) }, f * 0.6), + Variation::VividMuted => { + let Hsb { h, s, b } = color.to_hsb(); + let s2 = if step < 0 { s * (1.0 - f) } else { s + (1.0 - s) * f }; + hsb(h, s2.clamp(0.0, 1.0), b) + } + }; + v.with_alpha(color.a) +} + +/// The Color Guide for a base colour: the harmony colours and, per colour, its row of variations +/// from −steps to +steps, the colour itself in the centre column. +#[derive(Clone, Debug, PartialEq)] +pub struct Guide { + /// The harmony colours, base first. + pub colors: Vec, + /// One row per harmony colour, each with `2 * steps + 1` variations from shades to tints. + pub grid: Vec>, +} + +impl Guide { + // inv-vectorcraft: crates/color/src/harmony.rs:328 `Guide::new`. + /// Builds the guide for `base` under `rule`; `options` is clamped first. + pub fn new(base: Srgba, rule: Harmony, options: &GuideOptions) -> Guide { + let options = options.clamped(); + let n = options.steps as i32; + let colors = rule.apply(base); + let grid = colors.iter().map(|c| (-n..=n).map(|step| variation(*c, &options, step)).collect()).collect(); + Guide { colors, grid } + } + + /// The index of the centre column (the harmony colours) in each row. + pub fn centre(&self) -> usize { + self.grid.first().map_or(0, |row| row.len() / 2) + } + + /// The guide with every colour moved to the nearest of `palette` (Limit to Library; ΔE2000 + /// in Lab), the centre column too. An empty palette changes nothing. + // inv-vectorcraft: crates/color/src/harmony.rs:342 `limited`. + pub fn limited(mut self, palette: &[Srgba]) -> Guide { + if palette.is_empty() { + return self; + } + let labs: Vec<[f64; 3]> = palette.iter().map(|c| lab(*c)).collect(); + let nearest = |c: Srgba| { + let l = lab(c); + let best = + (0..palette.len()).min_by(|&a, &b| craft_cms::math::delta_e2000(labs[a], l).total_cmp(&craft_cms::math::delta_e2000(labs[b], l))); + best.map_or(c, |i| palette[i]) + }; + let centre = self.centre(); + for (row, c) in self.grid.iter_mut().zip(&mut self.colors) { + for v in row.iter_mut() { + *v = nearest(*v); + } + // The centre column is the harmony colour itself. + *c = row[centre]; + } + self + } +} diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs new file mode 100644 index 000000000..80172fde7 --- /dev/null +++ b/crates/color/src/lib.rs @@ -0,0 +1,33 @@ +//! Colour for Craft apps: the colour picker, wells, swatch tables, ramps and the hex field. +//! +//! The widgets are behind the `ui` feature; the colour model and conversions are in `craft-theme`. +//! Without `ui`, the crate has the helpers that need no egui: [`AreaMode`], [`GrayModel`], +//! [`CmykModel`], web-safe colours ([`web_safe`], [`not_web_safe`]), swatch files ([`palette`]), the display transform ([`display`]) and colour +//! harmonies ([`harmony`]). +//! [`AreaMode`] (and `ui::RampKind`) serialize as their [`key`](AreaMode::key); the swatch and harmony settings types serialize too. + +mod cmyk; +pub mod display; +mod gray; +pub mod harmony; +mod mode; +pub mod palette; +#[cfg(feature = "ui")] +pub mod ui; +mod web; + +pub use cmyk::CmykModel; +pub use gray::GrayModel; +pub use mode::AreaMode; +pub use web::{not_web_safe, web_safe}; + +#[cfg(all(test, feature = "screen-testing"))] +extern crate self as craft_color; +#[cfg(all(test, feature = "screen-testing"))] +#[path = "../tests/it/main.rs"] +mod integration; + +#[cfg(test)] +fn main() { + craft_ui::testing::run(module_path!(), env!("CARGO_PKG_NAME"), &craft_ui::testing::registered_in(env!("CARGO_PKG_NAME"))); +} diff --git a/crates/color/src/mode.rs b/crates/color/src/mode.rs new file mode 100644 index 000000000..1aab606fe --- /dev/null +++ b/crates/color/src/mode.rs @@ -0,0 +1,175 @@ +//! [`AreaMode`]: what a colour area and its strip show. + +#[cfg(feature = "ui")] +use craft_theme::ModelValues; +use craft_theme::{ColorModel, HsbModel, LabModel, OklchModel, RgbModel}; + +/// What the area and the strip show: the strip's component and the area's two, across (growing to +/// the right) and down (growing upwards). The nine modes of PhotoCraft's Color Picker, with +/// Photoshop's axes, and three for OKLCH laid out as the HSB ones. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub enum AreaMode { + /// Hue in the strip; saturation across, brightness down (HSB). + #[default] + #[serde(rename = "h")] + Hue, + /// Saturation in the strip; hue across, brightness down (HSB). + #[serde(rename = "s")] + Saturation, + /// Brightness in the strip; hue across, saturation down (HSB). + #[serde(rename = "v")] + Brightness, + /// Red in the strip; blue across, green down (RGB). + #[serde(rename = "r")] + Red, + /// Green in the strip; blue across, red down (RGB). + #[serde(rename = "g")] + Green, + /// Blue in the strip; red across, green down (RGB). + #[serde(rename = "b")] + Blue, + /// Lab lightness in the strip; a across, b down. + #[serde(rename = "lab_l")] + LabL, + /// Lab a in the strip; b across, lightness down. + #[serde(rename = "lab_a")] + LabA, + /// Lab b in the strip; a across, lightness down. + #[serde(rename = "lab_b")] + LabB, + /// OKLCH lightness in the strip; hue across, chroma down. + #[serde(rename = "oklch_l")] + OklchL, + /// OKLCH chroma in the strip; hue across, lightness down. + #[serde(rename = "oklch_c")] + OklchC, + /// OKLCH hue in the strip; chroma across, lightness down. + #[serde(rename = "oklch_h")] + OklchH, +} + +impl AreaMode { + /// PhotoCraft's nine modes, in its radio order: H, S, B, R, G, B, L, a, b. + pub const PHOTOSHOP: [AreaMode; 9] = [ + AreaMode::Hue, + AreaMode::Saturation, + AreaMode::Brightness, + AreaMode::Red, + AreaMode::Green, + AreaMode::Blue, + AreaMode::LabL, + AreaMode::LabA, + AreaMode::LabB, + ]; + + /// The OKLCH modes: L, C, H. + pub const OKLCH: [AreaMode; 3] = [AreaMode::OklchL, AreaMode::OklchC, AreaMode::OklchH]; + + /// Every mode: PhotoCraft's nine, then OKLCH's three. + pub const ALL: [AreaMode; 12] = [ + AreaMode::Hue, + AreaMode::Saturation, + AreaMode::Brightness, + AreaMode::Red, + AreaMode::Green, + AreaMode::Blue, + AreaMode::LabL, + AreaMode::LabA, + AreaMode::LabB, + AreaMode::OklchL, + AreaMode::OklchC, + AreaMode::OklchH, + ]; + + /// The mode's key, as PhotoCraft stores it: `"h"`, `"s"`, `"v"` (brightness), `"r"`, `"g"`, + /// `"b"`, `"lab_l"`, `"lab_a"`, `"lab_b"`, and `"oklch_l"`, `"oklch_c"`, `"oklch_h"`. + pub fn key(self) -> &'static str { + match self { + AreaMode::Hue => "h", + AreaMode::Saturation => "s", + AreaMode::Brightness => "v", + AreaMode::Red => "r", + AreaMode::Green => "g", + AreaMode::Blue => "b", + AreaMode::LabL => "lab_l", + AreaMode::LabA => "lab_a", + AreaMode::LabB => "lab_b", + AreaMode::OklchL => "oklch_l", + AreaMode::OklchC => "oklch_c", + AreaMode::OklchH => "oklch_h", + } + } + + /// The mode with `key` ([`key`](AreaMode::key)); `None` for any other text. + pub fn from_key(key: &str) -> Option { + AreaMode::ALL.into_iter().find(|mode| mode.key() == key) + } + + /// The area's accessible name, English, its two components across and down: the key a host + /// translates ("Saturation and brightness"). + pub fn name(self) -> &'static str { + match self { + AreaMode::Hue => "Saturation and brightness", + AreaMode::Saturation => "Hue and brightness", + AreaMode::Brightness => "Hue and saturation", + AreaMode::Red => "Blue and green", + AreaMode::Green => "Blue and red", + AreaMode::Blue => "Red and green", + AreaMode::LabL => "Green-red and blue-yellow", + AreaMode::LabA => "Blue-yellow and lightness", + AreaMode::LabB => "Green-red and lightness", + AreaMode::OklchL => "Hue and chroma", + AreaMode::OklchC => "Hue and lightness", + AreaMode::OklchH => "Chroma and lightness", + } + } + + /// The model whose values the area and strip edit. + pub fn model(self) -> &'static dyn ColorModel { + match self { + AreaMode::Hue | AreaMode::Saturation | AreaMode::Brightness => &HsbModel, + AreaMode::Red | AreaMode::Green | AreaMode::Blue => &RgbModel, + AreaMode::LabL | AreaMode::LabA | AreaMode::LabB => &LabModel, + AreaMode::OklchL | AreaMode::OklchC | AreaMode::OklchH => &OklchModel, + } + } + + /// The strip's channel, an index into the model's channels. + pub fn strip(self) -> usize { + match self { + AreaMode::Hue | AreaMode::Red | AreaMode::LabL | AreaMode::OklchL => 0, + AreaMode::Saturation | AreaMode::Green | AreaMode::LabA | AreaMode::OklchC => 1, + AreaMode::Brightness | AreaMode::Blue | AreaMode::LabB | AreaMode::OklchH => 2, + } + } + + /// The area's channels, across and down. + pub fn area(self) -> [usize; 2] { + match self { + AreaMode::Hue => [1, 2], + AreaMode::Saturation => [0, 2], + AreaMode::Brightness => [0, 1], + AreaMode::Red => [2, 1], + AreaMode::Green => [2, 0], + AreaMode::Blue => [0, 1], + AreaMode::LabL => [1, 2], + AreaMode::LabA => [2, 0], + AreaMode::LabB => [1, 0], + AreaMode::OklchL => [2, 1], + AreaMode::OklchC => [2, 0], + AreaMode::OklchH => [1, 0], + } + } + + /// The values the strip's colours are drawn with: the colour's own, except that the HSB hue + /// strip shows pure hues (full saturation and brightness), as Photoshop's. + #[cfg(feature = "ui")] + pub(crate) fn strip_base(self, values: &ModelValues) -> ModelValues { + let mut base = *values; + if self == AreaMode::Hue { + base.values[1] = 100.0; + base.values[2] = 100.0; + } + base + } +} diff --git a/crates/color/src/palette.rs b/crates/color/src/palette.rs new file mode 100644 index 000000000..c0c8d976a --- /dev/null +++ b/crates/color/src/palette.rs @@ -0,0 +1,492 @@ +//! Swatch files (F04.14): Photoshop's `.aco` swatches and `.act` colour tables, swatch exchange +//! `.ase` files, GIMP `.gpl` palettes and CSS custom properties, read into [`SwatchGroup`]s of +//! [`SwatchEntry`]s and written back. +//! +//! Each colour stays in its own model ([`SwatchColor`]): a CMYK swatch keeps its inks and a Lab +//! swatch its values through a read and a write. What a format cannot hold is reported, not +//! dropped silently ([`SwatchReport`]). +//! +//! ```no_run +//! use craft_color::palette::{SwatchFormat, read_swatches, write_swatches}; +//! # let bytes: Vec = Vec::new(); +//! let (groups, report) = read_swatches(&bytes, "Brand.ase")?; +//! let (aco, report) = write_swatches(&groups, SwatchFormat::Aco)?; +//! # Ok::<(), craft_color::palette::SwatchError>(()) +//! ``` + +use craft_cms::convert::CmykConverter; +use craft_theme::{Hsb, Lab, Srgba}; + +/// A swatch file format. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum SwatchFormat { + /// Photoshop swatches (`.aco`, binary, versions 1 and 2): RGB, HSB, CMYK, Lab and grey + /// colours with names, no groups. Colour-book colours are kept as they are. + Aco, + /// Photoshop colour table (`.act`, 768 bytes of RGB plus an optional count and transparent + /// index): 8-bit RGB, no names. Recognised by its file name only: the bytes have no + /// signature. + Act, + /// Adobe swatch exchange (`.ase`, binary): RGB, CMYK, Lab and grey colours, global, spot or + /// process, in groups. + Ase, + /// GIMP palette (`.gpl`, text): 8-bit RGB with names; groups as `# Group:` comment headers + /// (VectorCraft's convention). + Gpl, + /// CSS custom properties on `:root` (`--brand-blue: #3e63dd;`), one comment per group. + /// Written only. + Css, +} + +impl SwatchFormat { + /// Every format, in the Export menu's order. + pub const ALL: [SwatchFormat; 5] = [SwatchFormat::Aco, SwatchFormat::Act, SwatchFormat::Ase, SwatchFormat::Gpl, SwatchFormat::Css]; + + /// The file extension, without the dot. + pub fn extension(self) -> &'static str { + match self { + SwatchFormat::Aco => "aco", + SwatchFormat::Act => "act", + SwatchFormat::Ase => "ase", + SwatchFormat::Gpl => "gpl", + SwatchFormat::Css => "css", + } + } + + /// The format a file name's extension names (case-insensitive), if any. + // pc: crates/engine/src/cmd/swatch_cmds.rs:377 `Format::parse`, :394 `ext_format`. + pub fn from_name(file_name: &str) -> Option { + let extension = std::path::Path::new(file_name).extension()?.to_str()?.to_ascii_lowercase(); + SwatchFormat::ALL.into_iter().find(|f| f.extension() == extension) + } + + /// Whether [`read_swatches`] reads the format (every one but CSS). + pub fn can_read(self) -> bool { + self != SwatchFormat::Css + } + + /// The format of `bytes`: the `ASEF` signature, `GIMP Palette` on the first line, an `.aco` + /// version header that parses; `.act` only by `file_name` (768 or 772 bytes). + // inv-vectorcraft: crates/color/src/palette_io.rs:346 `sniff`, :365 `sniff_bytes`; pc: + // crates/engine/src/cmd/swatch_cmds.rs:394 `ext_format` for the name fallback. + pub fn sniff(bytes: &[u8], file_name: &str) -> Option { + let by_name = SwatchFormat::from_name(file_name); + let act_length = bytes.len() == ACT_PALETTE_LEN || bytes.len() == ACT_PALETTE_LEN + ACT_TRAILER_LEN; + if act_length && by_name == Some(SwatchFormat::Act) { + return Some(SwatchFormat::Act); + } + if bytes.starts_with(ASE_SIGNATURE) { + return Some(SwatchFormat::Ase); + } + if is_gpl(bytes) { + return Some(SwatchFormat::Gpl); + } + // An `.act` whose first colour is `0, 1, x` starts like an `.aco`: at `.act` lengths the + // header counts only when its sections fill the file exactly. + if matches!(bytes.get(..2), Some([0, 1] | [0, 2])) + && let Ok((_, len)) = parse_aco(bytes) + && (!act_length || len == bytes.len()) + { + return Some(SwatchFormat::Aco); + } + by_name + } +} + +/// A swatch colour in its own model. +#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[serde(tag = "model", content = "values", rename_all = "camelCase")] +pub enum SwatchColor { + /// Encoded RGB, 0–1 each, in the RGB working space. + Rgb([f32; 3]), + /// Hue 0–360°, saturation and brightness 0–1 (a view of an RGB colour). + Hsb([f32; 3]), + /// Cyan, magenta, yellow and black ink, 0–1 each, in the CMYK working space. + Cmyk([f32; 4]), + /// L* 0–100, a*, b* (D50). + Lab([f32; 3]), + /// Black ink 0–1 (0 white), as Photoshop's K. + Gray(f32), + /// A colour space this crate does not model (colour-book colours in an `.aco` file), kept + /// as stored so it survives a round trip. Shows as black. + Book { + /// The colour-book space id stored in the file. + space: u16, + /// The four stored channel values, untouched. + values: [u16; 4], + }, +} + +impl SwatchColor { + /// The colour as encoded sRGB for drawing: CMYK through `cmyk` (the document's converter), + /// Lab through D50, HSB and grey directly; a [`Book`](SwatchColor::Book) colour is black. + // pc: crates/ui-egui/src/panels/swatches_ui.rs:40 (`conv.rgb(&s.color)` per swatch). + pub fn to_srgb(&self, cmyk: &CmykConverter) -> Srgba { + match *self { + SwatchColor::Rgb(v) => Srgba::from_rgb_array(v.map(unit)), + SwatchColor::Hsb(v) => Srgba::from_rgb_array(hsb_to_rgb(v)), + SwatchColor::Cmyk(v) => Srgba::from_rgb_array(cmyk.to_srgb(v.map(unit)).map(unit)), + SwatchColor::Lab([l, a, b]) => { + let (l, a, b) = (finite(l), finite(a), finite(b)); + // ICC v4 Lab encoding (the Lab D50 profile's device values). + let encoded = [unit(l / 100.0), unit((a + 128.0) / 255.0), unit((b + 128.0) / 255.0)]; + match profile_to_srgb(&working_transforms().lab, &encoded) { + Some(rgb) => Srgba::from_rgb_array(rgb), + None => Srgba::from_lab(Lab { l, a, b }), + } + } + SwatchColor::Gray(k) => { + let level = 1.0 - unit(k); + Srgba::from_rgb_array(profile_to_srgb(&working_transforms().gray, &[level]).unwrap_or([level; 3])) + } + SwatchColor::Book { .. } => Srgba::rgb(0.0, 0.0, 0.0), + } + } +} + +/// How an `.ase` file marks a colour. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum SwatchKind { + #[default] + #[allow(missing_docs)] + Process, + #[allow(missing_docs)] + Global, + #[allow(missing_docs)] + Spot, +} + +/// One named swatch. +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct SwatchEntry { + /// The swatch's label. + pub name: String, + /// The swatch's colour. + pub color: SwatchColor, + #[serde(default)] + /// How the file marks the colour; `Process` unless the file says otherwise. + pub kind: SwatchKind, +} + +impl SwatchEntry { + /// A process swatch. + pub fn new(name: impl Into, color: SwatchColor) -> SwatchEntry { + SwatchEntry { name: name.into(), color, kind: SwatchKind::Process } + } +} + +/// A named group of swatches, as the Swatches panel shows them. A file without groups reads as +/// one group named after the file. +#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct SwatchGroup { + /// The group's label. + pub name: String, + /// The group's swatches in display order. + pub entries: Vec, +} + +/// What a read or a write could not keep. Each item is a sentence the app can show; the +/// variants let it word them itself. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SwatchReport { + /// What was dropped or changed, in the order it was found. + pub notes: Vec, +} + +/// One thing a read or a write could not keep. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum SwatchNote { + /// Colour-book colours (`.aco` colours in a space this crate does not model) read as black, + /// or left out of a format that cannot hold them, with their count. + BookColors(usize), + /// `.ase` colours in a colour model this crate does not read were skipped, with their count. + Skipped(usize), + /// The format has no groups: the swatches were written as one list. + GroupsFlattened, + /// The format has only 8-bit RGB: CMYK, Lab and grey colours were converted, with their count. + ConvertedToRgb(usize), + /// The format has no spot or global colours: they were written as process colours, with their + /// count. + KindsDropped(usize), + /// `.act` holds at most 256 colours: the rest were left out, with their count. + Truncated(usize), + /// Names were cut to what the format holds (`.ase`: 1024 UTF-16 units). + NamesCut(usize), +} + +/// Why a swatch file could not be read or written. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum SwatchError { + /// Neither the content nor the name says what the file is. + UnknownFormat, + /// The format is write-only (CSS). + CannotRead(SwatchFormat), + /// The file is cut short or malformed, with the parser's message. + Malformed(SwatchFormat, String), + /// Nothing to write (no swatches in any group). + Empty, +} + +impl std::fmt::Display for SwatchError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + SwatchError::UnknownFormat => f.write_str("not a swatch file"), + SwatchError::CannotRead(format) => write!(f, ".{} files can be written, not read", format.extension()), + SwatchError::Malformed(format, message) => write!(f, "not a readable .{} file: {message}", format.extension()), + SwatchError::Empty => f.write_str("there are no swatches to write"), + } + } +} + +impl std::error::Error for SwatchError {} + +/// Reads a swatch file: the format from the content ([`SwatchFormat::sniff`]), `.act` from +/// `file_name`. Ungrouped colours go into a group named after the file (its stem); a swatch +/// without a name is "Swatch N". Names are cut to one line. +// pc: crates/engine/src/cmd/swatch_cmds.rs:491 `read_file` (`.aco`, `.act`, `.ase` with +// :406 `from_aco`, :435 `from_ase`), crates/psd/src/aco.rs:150 `parse`, crates/psd/src/ase.rs:180 +// `parse`, crates/psd/src/act.rs:46 `parse`; inv-vectorcraft: crates/color/src/palette_io.rs:376 +// `read_gpl`. The binary parsers move here (craft-color has no psd crate). +pub fn read_swatches(bytes: &[u8], file_name: &str) -> Result<(Vec, SwatchReport), SwatchError> { + let format = SwatchFormat::sniff(bytes, file_name).ok_or(SwatchError::UnknownFormat)?; + let stem = stem_of(file_name); + let mut report = SwatchReport::default(); + let mut groups: Vec = Vec::new(); + match format { + SwatchFormat::Css => return Err(SwatchError::CannotRead(format)), + SwatchFormat::Aco => { + let (swatches, _) = parse_aco(bytes).map_err(|e| malformed(format, e))?; + let books = swatches.iter().filter(|(_, c)| matches!(c, AcoColor::Other { .. })).count(); + push_note(&mut report, books, SwatchNote::BookColors); + let entries = + swatches.into_iter().enumerate().map(|(i, (name, color))| SwatchEntry::new(entry_name(i, &name), from_aco(color))).collect(); + groups.push(SwatchGroup { name: stem, entries }); + } + SwatchFormat::Act => { + let used = act_used(bytes).map_err(|e| malformed(format, e))?; + let entries = used + .iter() + .enumerate() + .map(|(i, c)| SwatchEntry::new(format!("Swatch {}", i + 1), SwatchColor::Rgb(c.map(|v| f32::from(v) / 255.0)))) + .collect(); + groups.push(SwatchGroup { name: stem, entries }); + } + SwatchFormat::Ase => { + let items = parse_ase(bytes).map_err(|e| malformed(format, e))?; + let (mut n, mut skipped) = (0usize, 0usize); + let mut convert = |s: &AseSwatch| { + n += 1; + let entry = from_ase(&s.color).map(|color| SwatchEntry { name: entry_name(n - 1, &s.name), color, kind: s.kind }); + skipped += usize::from(entry.is_none()); + entry + }; + let mut loose = Vec::new(); + for item in &items { + match item { + AseItem::Swatch(s) => loose.extend(convert(s)), + AseItem::Group(name, swatches) => { + let entries = swatches.iter().filter_map(&mut convert).collect(); + let name = clip_name(name); + groups.push(SwatchGroup { name: if name.is_empty() { stem.clone() } else { name }, entries }); + } + } + } + if !loose.is_empty() || groups.is_empty() { + groups.insert(0, SwatchGroup { name: stem, entries: loose }); + } + push_note(&mut report, skipped, SwatchNote::Skipped); + } + SwatchFormat::Gpl => groups = read_gpl(bytes, file_name), + } + if count_swatches(&groups) == 0 { + return Err(malformed(format, "the file holds no swatches")); + } + Ok((groups, report)) +} + +/// Writes `groups` as `format`, with what the format could not hold. +// pc: crates/engine/src/cmd/swatch_cmds.rs:566 `write_file` (`.aco` with :418 `to_aco`, `.ase` +// with :447 `to_ase`, `.act`), crates/psd/src/aco.rs:201 `write` (version 1 then 2), +// crates/psd/src/act.rs:63 `write`; inv-vectorcraft: crates/color/src/palette_io.rs:128 +// `write_gpl`, :182 `write_css` with :148 `css_property`. +pub fn write_swatches(groups: &[SwatchGroup], format: SwatchFormat) -> Result<(Vec, SwatchReport), SwatchError> { + if count_swatches(groups) == 0 { + return Err(SwatchError::Empty); + } + let mut report = SwatchReport::default(); + let all = || groups.iter().flat_map(|g| g.entries.iter()); + let kinds = all().filter(|e| e.kind != SwatchKind::Process).count(); + let flattened = groups.len() > 1; + match format { + SwatchFormat::Aco => { + if count_swatches(groups) > ACO_MAX_SWATCHES { + return Err(malformed(format, "an .aco file holds at most 65535 swatches")); + } + let entries: Vec<(String, AcoColor)> = all().map(|e| (e.name.clone(), to_aco(&e.color))).collect(); + if flattened { + report.notes.push(SwatchNote::GroupsFlattened); + } + push_note(&mut report, kinds, SwatchNote::KindsDropped); + push_note(&mut report, names_cut(groups, false), SwatchNote::NamesCut); + Ok((write_aco(&entries), report)) + } + SwatchFormat::Act => { + let (colors, books, converted) = rgb_colors(groups); + let mut triplets: Vec<[u8; 3]> = colors.iter().flatten().map(|(_, c, _)| *c).collect(); + if triplets.is_empty() { + return Err(SwatchError::Empty); + } + let left_out = triplets.len().saturating_sub(ACT_COLORS); + triplets.truncate(ACT_COLORS); + if flattened { + report.notes.push(SwatchNote::GroupsFlattened); + } + push_note(&mut report, books, SwatchNote::BookColors); + push_note(&mut report, converted, SwatchNote::ConvertedToRgb); + push_note(&mut report, kinds, SwatchNote::KindsDropped); + push_note(&mut report, left_out, SwatchNote::Truncated); + let mut out: Vec = triplets.iter().flatten().copied().collect(); + out.resize(ACT_PALETTE_LEN, 0); + out.extend((triplets.len() as u16).to_be_bytes()); + out.extend(0xFFFFu16.to_be_bytes()); + Ok((out, report)) + } + SwatchFormat::Ase => { + if count_swatches(groups) > ASE_MAX_SWATCHES || groups.len() > ASE_MAX_GROUPS { + return Err(malformed(format, "too many swatches or groups for an .ase file")); + } + let mut body = Vec::new(); + let (mut blocks, mut books) = (0u32, 0usize); + for g in groups { + let mut name = Vec::new(); + put_ase_name(&mut name, &g.name); + put_ase_block(&mut body, ASE_GROUP_START, &name); + blocks += 2; + for e in &g.entries { + match to_ase(&e.color) { + Some(color) => { + put_ase_color(&mut body, &e.name, &color, e.kind); + blocks += 1; + } + None => books += 1, + } + } + put_ase_block(&mut body, ASE_GROUP_END, &[]); + } + push_note(&mut report, books, SwatchNote::BookColors); + push_note(&mut report, names_cut(groups, true), SwatchNote::NamesCut); + let mut out = Vec::with_capacity(12 + body.len()); + out.extend(ASE_SIGNATURE); + out.extend(1u16.to_be_bytes()); + out.extend(0u16.to_be_bytes()); + out.extend(blocks.to_be_bytes()); + out.extend(body); + Ok((out, report)) + } + SwatchFormat::Gpl | SwatchFormat::Css => { + let (colors, books, converted) = rgb_colors(groups); + push_note(&mut report, books, SwatchNote::BookColors); + push_note(&mut report, converted, SwatchNote::ConvertedToRgb); + let text = if format == SwatchFormat::Gpl { + push_note(&mut report, kinds, SwatchNote::KindsDropped); + let plain: Vec> = colors.iter().map(|l| l.iter().map(|(n, c, _)| (n.clone(), *c)).collect()).collect(); + write_gpl(groups, &plain) + } else { + write_css(groups, &colors) + }; + Ok((text.into_bytes(), report)) + } + } +} + +/// PhotoCraft's default swatches (46 RGB colours in five groups: Grays, the exact RGB primaries +/// and secondaries, Pastel, Pure and Dark hues), what Reset Swatches restores. +// pc: crates/engine/src/presets/swatches.rs:294 `builtin`. +pub fn default_swatches() -> Vec { + let rgb = |name: &str, c: [u8; 3]| SwatchEntry::new(name, SwatchColor::Rgb(c.map(|v| f32::from(v) / 255.0))); + let grays = [ + ("Black", 0), + ("90% Gray", 26), + ("80% Gray", 51), + ("70% Gray", 77), + ("60% Gray", 102), + ("50% Gray", 128), + ("40% Gray", 153), + ("30% Gray", 179), + ("20% Gray", 204), + ("White", 255), + ]; + let hues = ["Red", "Orange", "Yellow", "Yellow Green", "Green", "Cyan Green", "Cyan", "Blue", "Violet", "Magenta"]; + let pastel: [[u8; 3]; 10] = [ + [236, 128, 128], + [244, 176, 132], + [250, 224, 128], + [214, 240, 128], + [150, 232, 150], + [128, 232, 200], + [128, 220, 240], + [128, 176, 244], + [168, 144, 244], + [232, 144, 232], + ]; + let pure: [[u8; 3]; 10] = [ + [230, 40, 40], + [245, 120, 30], + [250, 210, 30], + [160, 220, 40], + [40, 200, 80], + [30, 200, 170], + [30, 170, 230], + [40, 100, 230], + [120, 70, 220], + [210, 50, 180], + ]; + let dark: [[u8; 3]; 10] = [ + [120, 20, 20], + [130, 60, 10], + [130, 110, 10], + [80, 120, 20], + [20, 100, 40], + [10, 100, 90], + [10, 80, 120], + [20, 50, 120], + [60, 30, 110], + [110, 20, 90], + ]; + let row = |prefix: &str, colors: [[u8; 3]; 10]| -> Vec { + hues.iter().zip(colors).map(|(hue, c)| rgb(&if prefix.is_empty() { (*hue).to_string() } else { format!("{prefix} {hue}") }, c)).collect() + }; + // Photoshop's order: red, yellow, green, cyan, blue, magenta. + let exact: [(&str, [u8; 3]); 6] = [ + ("RGB Red", [255, 0, 0]), + ("RGB Yellow", [255, 255, 0]), + ("RGB Green", [0, 255, 0]), + ("RGB Cyan", [0, 255, 255]), + ("RGB Blue", [0, 0, 255]), + ("RGB Magenta", [255, 0, 255]), + ]; + let group = |name: &str, entries: Vec| SwatchGroup { name: name.into(), entries }; + vec![ + group("Grays", grays.iter().map(|(n, v)| rgb(n, [*v; 3])).collect()), + group("RGB", exact.iter().map(|(n, c)| rgb(n, *c)).collect()), + group("Pastel", row("Pastel", pastel)), + group("Pure", row("", pure)), + group("Dark", row("Dark", dark)), + ] +} + +mod aco; +mod ase; +mod reader; +#[cfg(test)] +mod tests; +mod text; + +use aco::*; +use ase::*; +use reader::*; +use text::*; diff --git a/crates/color/src/palette/aco.rs b/crates/color/src/palette/aco.rs new file mode 100644 index 000000000..3b9a6d9c8 --- /dev/null +++ b/crates/color/src/palette/aco.rs @@ -0,0 +1,167 @@ +//! Photoshop `.aco` swatches and `.act` colour tables. + +use super::reader::*; +use super::*; + +// ---------------------------------------------------------------- .aco + +/// A colour record as stored, at 16 bits (CMYK as ink amounts). +#[derive(Clone, Copy)] +pub(super) enum AcoColor { + Rgb([u16; 3]), + Hsb([u16; 3]), + Cmyk([u16; 4]), + Lab { l: u16, a: i16, b: i16 }, + Gray(u16), + Other { space: u16, values: [u16; 4] }, +} + +const ACO_RGB: u16 = 0; +const ACO_HSB: u16 = 1; +const ACO_CMYK: u16 = 2; +const ACO_LAB: u16 = 7; +const ACO_GRAY: u16 = 8; + +impl AcoColor { + fn from_record(space: u16, v: [u16; 4]) -> AcoColor { + match space { + ACO_RGB => AcoColor::Rgb([v[0], v[1], v[2]]), + ACO_HSB => AcoColor::Hsb([v[0], v[1], v[2]]), + ACO_CMYK => AcoColor::Cmyk(v.map(|x| u16::MAX - x)), + ACO_LAB => AcoColor::Lab { l: v[0], a: v[1] as i16, b: v[2] as i16 }, + ACO_GRAY => AcoColor::Gray(v[0]), + _ => AcoColor::Other { space, values: v }, + } + } + + fn to_record(self) -> (u16, [u16; 4]) { + match self { + AcoColor::Rgb([r, g, b]) => (ACO_RGB, [r, g, b, 0]), + AcoColor::Hsb([h, s, b]) => (ACO_HSB, [h, s, b, 0]), + AcoColor::Cmyk(c) => (ACO_CMYK, c.map(|x| u16::MAX - x)), + AcoColor::Lab { l, a, b } => (ACO_LAB, [l, a as u16, b as u16, 0]), + AcoColor::Gray(g) => (ACO_GRAY, [g, 0, 0, 0]), + AcoColor::Other { space, values } => (space, values), + } + } +} + +fn q16(v: f32) -> u16 { + (unit(v) * 65535.0).round() as u16 +} + +pub(super) fn from_aco(c: AcoColor) -> SwatchColor { + let f = |v: u16| f32::from(v) / 65535.0; + match c { + AcoColor::Rgb(v) => SwatchColor::Rgb(v.map(f)), + AcoColor::Hsb([h, sa, b]) => SwatchColor::Hsb([f(h) * 360.0, f(sa), f(b)]), + AcoColor::Cmyk(v) => SwatchColor::Cmyk(v.map(f)), + AcoColor::Lab { l, a, b } => SwatchColor::Lab([f32::from(l.min(10000)) / 100.0, f32::from(a) / 100.0, f32::from(b) / 100.0]), + AcoColor::Gray(g) => SwatchColor::Gray(1.0 - f32::from(g.min(10000)) / 10000.0), + AcoColor::Other { space, values } => SwatchColor::Book { space, values }, + } +} + +pub(super) fn to_aco(c: &SwatchColor) -> AcoColor { + match *c { + SwatchColor::Rgb(v) => AcoColor::Rgb(v.map(q16)), + SwatchColor::Hsb([h, sa, b]) => { + let h = finite(h).rem_euclid(360.0); + AcoColor::Hsb([((h / 360.0) * 65535.0).round().min(65535.0) as u16, q16(sa), q16(b)]) + } + SwatchColor::Cmyk(v) => AcoColor::Cmyk(v.map(q16)), + SwatchColor::Lab([l, a, b]) => { + let ab = |v: f32| (finite(v) * 100.0).round().clamp(-12800.0, 12700.0) as i16; + AcoColor::Lab { l: (finite(l) * 100.0).round().clamp(0.0, 10000.0) as u16, a: ab(a), b: ab(b) } + } + SwatchColor::Gray(k) => AcoColor::Gray(((1.0 - unit(k)) * 10000.0).round() as u16), + SwatchColor::Book { space, values } => AcoColor::Other { space, values }, + } +} + +fn aco_record(r: &mut Reader<'_>) -> Result { + let space = r.u16()?; + let v = [r.u16()?, r.u16()?, r.u16()?, r.u16()?]; + Ok(AcoColor::from_record(space, v)) +} + +fn aco_section(r: &mut Reader<'_>, named: bool) -> Result, String> { + let count = usize::from(r.u16()?); + r.check_count(count as u64, if named { 14 } else { 10 })?; + let mut out = Vec::with_capacity(count); + for _ in 0..count { + let color = aco_record(r)?; + let name = if named { + let n = r.u32()?; + r.units(usize::try_from(n).map_err(|_| "a name is too long".to_string())?)? + } else { + String::new() + }; + out.push((name, color)); + } + Ok(out) +} + +/// The swatches of an `.aco` file (version 2 names when the file has them) and how many bytes its +/// sections span. +pub(super) fn parse_aco(data: &[u8]) -> Result<(Vec<(String, AcoColor)>, usize), String> { + let mut r = Reader::new(data); + match r.u16()? { + 1 => { + let v1 = aco_section(&mut r, false)?; + // Files from Photoshop 6 on follow with a version 2 section; other trailing bytes are + // padding. + if r.remaining() >= 4 && data[r.pos..].get(..2) == Some(&[0, 2]) { + r.u16()?; + let v2 = aco_section(&mut r, true)?; + return Ok((v2, r.pos)); + } + Ok((v1, r.pos)) + } + 2 => { + let v2 = aco_section(&mut r, true)?; + Ok((v2, r.pos)) + } + v => Err(format!("unsupported version {v}")), + } +} + +pub(super) fn write_aco(entries: &[(String, AcoColor)]) -> Vec { + let count = entries.len() as u16; + let mut out = Vec::with_capacity(8 + entries.len() * 40); + for version in [1u16, 2] { + out.extend(version.to_be_bytes()); + out.extend(count.to_be_bytes()); + for (name, color) in entries { + let (space, v) = color.to_record(); + out.extend(space.to_be_bytes()); + for x in v { + out.extend(x.to_be_bytes()); + } + if version == 2 { + let units = utf16_units(name, MAX_NAME_UNITS); + // The length counts the terminating null. + out.extend((units.len() as u32 + 1).to_be_bytes()); + for u in units { + out.extend(u.to_be_bytes()); + } + out.extend(0u16.to_be_bytes()); + } + } + } + out +} + +// ---------------------------------------------------------------- .act + +pub(super) fn act_used(data: &[u8]) -> Result, String> { + if data.len() != ACT_PALETTE_LEN && data.len() != ACT_PALETTE_LEN + ACT_TRAILER_LEN { + return Err("an .act file is 768 bytes, or 772 with the count trailer".into()); + } + let mut colors: Vec<[u8; 3]> = data[..ACT_PALETTE_LEN].as_chunks::<3>().0.to_vec(); + if data.len() > ACT_PALETTE_LEN { + let count = usize::from(u16::from_be_bytes([data[ACT_PALETTE_LEN], data[ACT_PALETTE_LEN + 1]])); + colors.truncate(count.min(ACT_COLORS)); + } + Ok(colors) +} diff --git a/crates/color/src/palette/ase.rs b/crates/color/src/palette/ase.rs new file mode 100644 index 000000000..a1b694e43 --- /dev/null +++ b/crates/color/src/palette/ase.rs @@ -0,0 +1,197 @@ +//! Adobe swatch exchange (`.ase`) files. + +use super::reader::*; +use super::*; + +// ---------------------------------------------------------------- .ase + +pub(super) fn from_ase(c: &AseColor) -> Option { + Some(match *c { + AseColor::Rgb(v) => SwatchColor::Rgb(v), + AseColor::Cmyk(v) => SwatchColor::Cmyk(v), + // L is stored as a fraction (L*/100); a few writers store L* itself, which can only be told + // apart above 1. + AseColor::Lab([l, a, b]) => SwatchColor::Lab([if l > 1.0 { l } else { l * 100.0 }, a, b]), + AseColor::Gray(g) => SwatchColor::Gray(1.0 - g), + AseColor::Other => return None, + }) +} + +pub(super) fn to_ase(c: &SwatchColor) -> Option { + Some(match *c { + SwatchColor::Rgb(v) => AseColor::Rgb(v), + SwatchColor::Hsb(v) => AseColor::Rgb(hsb_to_rgb(v)), + SwatchColor::Cmyk(v) => AseColor::Cmyk(v), + SwatchColor::Lab([l, a, b]) => AseColor::Lab([l / 100.0, a, b]), + SwatchColor::Gray(k) => AseColor::Gray(1.0 - k), + SwatchColor::Book { .. } => return None, + }) +} + +pub(super) fn hsb_to_rgb([h, s, b]: [f32; 3]) -> [f32; 3] { + Srgba::from_hsb(Hsb { h: finite(h), s: unit(s), b: unit(b) }).to_rgb_array().map(unit) +} + +pub(super) enum AseColor { + Rgb([f32; 3]), + Cmyk([f32; 4]), + Lab([f32; 3]), + Gray(f32), + /// A colour model this crate does not read. + Other, +} + +pub(super) struct AseSwatch { + pub(super) name: String, + pub(super) color: AseColor, + pub(super) kind: SwatchKind, +} + +pub(super) enum AseItem { + Swatch(AseSwatch), + Group(String, Vec), +} + +fn ase_name(r: &mut Reader<'_>) -> Result { + if r.remaining() == 0 { + return Ok(String::new()); + } + let n = usize::from(r.u16()?); + r.units(n) +} + +fn ase_color(body: &mut Reader<'_>) -> Result { + let name = ase_name(body)?; + let model: [u8; 4] = body.array()?; + let color = match &model { + b"RGB " => AseColor::Rgb([body.f32()?, body.f32()?, body.f32()?]), + b"CMYK" => AseColor::Cmyk([body.f32()?, body.f32()?, body.f32()?, body.f32()?]), + b"LAB " => AseColor::Lab([body.f32()?, body.f32()?, body.f32()?]), + b"Gray" => AseColor::Gray(body.f32()?), + _ => { + // Everything but the trailing colour type belongs to the unknown model. + let n = body.remaining().saturating_sub(2); + body.bytes(n)?; + AseColor::Other + } + }; + // Some writers omit the colour type; it defaults to process. + let kind = if body.remaining() >= 2 { + match body.u16()? { + 0 => SwatchKind::Global, + 1 => SwatchKind::Spot, + _ => SwatchKind::Process, + } + } else { + SwatchKind::Process + }; + Ok(AseSwatch { name, color, kind }) +} + +pub(super) fn parse_ase(data: &[u8]) -> Result, String> { + let mut r = Reader::new(data); + let sig: [u8; 4] = r.array()?; + if &sig != ASE_SIGNATURE { + return Err("the ASEF signature is missing".into()); + } + let major = r.u16()?; + let _minor = r.u16()?; + if major != 1 { + return Err(format!("unsupported version {major}")); + } + let count = u64::from(r.u32()?); + // Every block has at least a type and a length. + r.check_count(count, 6)?; + let mut items = Vec::new(); + let mut open: Option<(String, Vec)> = None; + let (mut total, mut groups) = (0usize, 0usize); + for _ in 0..count { + let kind = r.u16()?; + let len = usize::try_from(r.u32()?).map_err(|_| "a block is too long".to_string())?; + let mut body = Reader::new(r.bytes(len)?); + match kind { + ASE_GROUP_START => { + groups += 1; + if groups > ASE_MAX_GROUPS { + return Err("too many groups".into()); + } + if let Some((name, swatches)) = open.take() { + items.push(AseItem::Group(name, swatches)); + } + open = Some((ase_name(&mut body)?, Vec::new())); + } + ASE_GROUP_END => { + if let Some((name, swatches)) = open.take() { + items.push(AseItem::Group(name, swatches)); + } + } + ASE_COLOR => { + total += 1; + if total > ASE_MAX_SWATCHES { + return Err("too many swatches".into()); + } + let s = ase_color(&mut body)?; + match open.as_mut() { + Some((_, v)) => v.push(s), + None => items.push(AseItem::Swatch(s)), + } + } + _ => {} + } + } + if let Some((name, swatches)) = open.take() { + items.push(AseItem::Group(name, swatches)); + } + Ok(items) +} + +pub(super) fn put_ase_name(out: &mut Vec, name: &str) { + let units = utf16_units(name, MAX_NAME_UNITS); + out.extend((units.len() as u16 + 1).to_be_bytes()); + for u in units { + out.extend(u.to_be_bytes()); + } + out.extend(0u16.to_be_bytes()); +} + +pub(super) fn put_ase_block(out: &mut Vec, kind: u16, body: &[u8]) { + out.extend(kind.to_be_bytes()); + out.extend((body.len() as u32).to_be_bytes()); + out.extend(body); +} + +pub(super) fn put_ase_color(out: &mut Vec, name: &str, color: &AseColor, kind: SwatchKind) { + let mut b = Vec::with_capacity(64); + put_ase_name(&mut b, name); + let floats = |b: &mut Vec, v: &[f32]| { + for x in v { + b.extend(x.to_bits().to_be_bytes()); + } + }; + match color { + AseColor::Rgb(c) => { + b.extend(b"RGB "); + floats(&mut b, c); + } + AseColor::Cmyk(c) => { + b.extend(b"CMYK"); + floats(&mut b, c); + } + AseColor::Lab(c) => { + b.extend(b"LAB "); + floats(&mut b, c); + } + AseColor::Gray(g) => { + b.extend(b"Gray"); + floats(&mut b, &[*g]); + } + AseColor::Other => {} + } + let code: u16 = match kind { + SwatchKind::Global => 0, + SwatchKind::Spot => 1, + SwatchKind::Process => 2, + }; + b.extend(code.to_be_bytes()); + put_ase_block(out, ASE_COLOR, &b); +} diff --git a/crates/color/src/palette/reader.rs b/crates/color/src/palette/reader.rs new file mode 100644 index 000000000..a0272a0c1 --- /dev/null +++ b/crates/color/src/palette/reader.rs @@ -0,0 +1,189 @@ +//! Byte reader, name and count helpers and limits shared by the swatch codecs. + +use super::*; + +// ---------------------------------------------------------------- file helpers + +/// Longest name in a binary swatch file, in UTF-16 code units. +pub(super) const MAX_NAME_UNITS: usize = 1024; +/// Longest swatch or group name kept from a file, in characters. +const MAX_NAME_CHARS: usize = 255; +pub(super) const GPL_HEADER: &str = "GIMP Palette"; +pub(super) const GPL_GROUP: &str = "# Group:"; +pub(super) const ASE_SIGNATURE: &[u8; 4] = b"ASEF"; +pub(super) const ASE_GROUP_START: u16 = 0xC001; +pub(super) const ASE_GROUP_END: u16 = 0xC002; +pub(super) const ASE_COLOR: u16 = 0x0001; +pub(super) const ASE_MAX_SWATCHES: usize = 100_000; +pub(super) const ASE_MAX_GROUPS: usize = 10_000; +pub(super) const ACO_MAX_SWATCHES: usize = u16::MAX as usize; +pub(super) const ACT_COLORS: usize = 256; +pub(super) const ACT_PALETTE_LEN: usize = ACT_COLORS * 3; +pub(super) const ACT_TRAILER_LEN: usize = 4; + +/// Transforms from the Lab D50 and sGray profiles to sRGB (relative colorimetric, black point +/// compensation); `None` when one does not link. +pub(super) struct WorkingTransforms { + pub(super) lab: Option>, + pub(super) gray: Option>, +} + +pub(super) fn working_transforms() -> &'static WorkingTransforms { + static TRANSFORMS: std::sync::OnceLock = std::sync::OnceLock::new(); + TRANSFORMS.get_or_init(|| { + let opts = craft_cms::TransformOptions { intent: craft_cms::Intent::RelativeColorimetric, bpc: true, ..Default::default() }; + let srgb = craft_cms::Builtin::Srgb.profile(); + let link = |source: &craft_cms::Profile| craft_cms::cached(source, srgb, opts).ok(); + WorkingTransforms { lab: link(craft_cms::Builtin::LabD50.profile()), gray: link(craft_cms::Builtin::SGray.profile()) } + }) +} + +pub(super) fn profile_to_srgb(transform: &Option>, input: &[f32]) -> Option<[f32; 3]> { + let mut out = [0.0f32; 3]; + transform.as_ref()?.eval(input, &mut out).ok()?; + Some(out.map(unit)) +} + +pub(super) fn malformed(format: SwatchFormat, message: impl Into) -> SwatchError { + SwatchError::Malformed(format, message.into()) +} + +pub(super) fn unit(v: f32) -> f32 { + if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 } +} + +pub(super) fn finite(v: f32) -> f32 { + if v.is_finite() { v } else { 0.0 } +} + +/// One line of text, cut to the length a name may have. +pub(super) fn clip_name(name: &str) -> String { + let line = name.split(['\n', '\r', '\t']).collect::>().join(" "); + line.trim().chars().take(MAX_NAME_CHARS).collect() +} + +pub(super) fn entry_name(index: usize, name: &str) -> String { + let name = clip_name(name); + if name.is_empty() { format!("Swatch {}", index + 1) } else { name } +} + +/// The group name for ungrouped colours: the file's stem. +pub(super) fn stem_of(file_name: &str) -> String { + let stem = std::path::Path::new(file_name).file_stem().and_then(|s| s.to_str()).unwrap_or(""); + let stem = clip_name(stem); + if stem.is_empty() { "Imported Swatches".into() } else { stem } +} + +pub(super) fn count_swatches(groups: &[SwatchGroup]) -> usize { + groups.iter().map(|g| g.entries.len()).sum() +} + +/// Whole UTF-16 scalar values of `name` that fit in `max` units. +pub(super) fn utf16_units(name: &str, max: usize) -> Vec { + let mut units = Vec::new(); + for c in name.chars() { + if units.len() + c.len_utf16() > max { + break; + } + let mut buf = [0u16; 2]; + units.extend_from_slice(c.encode_utf16(&mut buf)); + } + units +} + +pub(super) fn names_cut(groups: &[SwatchGroup], include_groups: bool) -> usize { + let cut = |name: &str| name.encode_utf16().count() > MAX_NAME_UNITS; + let swatches = groups.iter().flat_map(|g| g.entries.iter()).filter(|e| cut(&e.name)).count(); + swatches + if include_groups { groups.iter().filter(|g| cut(&g.name)).count() } else { 0 } +} + +/// A bounds-checked big-endian cursor. +pub(super) struct Reader<'a> { + data: &'a [u8], + pub(super) pos: usize, +} + +impl<'a> Reader<'a> { + pub(super) fn new(data: &'a [u8]) -> Self { + Reader { data, pos: 0 } + } + pub(super) fn remaining(&self) -> usize { + self.data.len() - self.pos + } + pub(super) fn bytes(&mut self, n: usize) -> Result<&'a [u8], String> { + if n > self.remaining() { + return Err(format!("the file is cut short at byte {}", self.pos)); + } + let out = &self.data[self.pos..self.pos + n]; + self.pos += n; + Ok(out) + } + pub(super) fn array(&mut self) -> Result<[u8; N], String> { + let mut out = [0u8; N]; + out.copy_from_slice(self.bytes(N)?); + Ok(out) + } + pub(super) fn u16(&mut self) -> Result { + Ok(u16::from_be_bytes(self.array()?)) + } + pub(super) fn u32(&mut self) -> Result { + Ok(u32::from_be_bytes(self.array()?)) + } + pub(super) fn f32(&mut self) -> Result { + Ok(finite(f32::from_bits(self.u32()?))) + } + /// Fails when `count` items of at least `min_size` bytes cannot fit in what is left. + pub(super) fn check_count(&self, count: u64, min_size: u64) -> Result<(), String> { + if count.saturating_mul(min_size) > self.remaining() as u64 { Err(format!("the file is cut short at byte {}", self.pos)) } else { Ok(()) } + } + /// A name of `n` UTF-16 units that include the trailing null; units past the limit are dropped. + pub(super) fn units(&mut self, n: usize) -> Result { + self.check_count(n as u64, 2)?; + let mut units = Vec::with_capacity(n.min(MAX_NAME_UNITS)); + for _ in 0..n { + let u = self.u16()?; + if units.len() < MAX_NAME_UNITS { + units.push(u); + } + } + while units.last() == Some(&0) { + units.pop(); + } + Ok(String::from_utf16_lossy(&units)) + } +} + +/// Name, 8-bit colour and whether it is a spot colour. +pub(super) type RgbSwatch = (String, [u8; 3], bool); + +/// The colours of a format that holds only 8-bit RGB: other models converted, colour-book colours +/// left out. Returns the colours per group with the `BookColors` and `ConvertedToRgb` counts. +pub(super) fn rgb_colors(groups: &[SwatchGroup]) -> (Vec>, usize, usize) { + let (mut books, mut converted) = (0, 0); + let out = groups + .iter() + .map(|g| { + g.entries + .iter() + .filter_map(|e| { + match e.color { + SwatchColor::Book { .. } => { + books += 1; + return None; + } + SwatchColor::Cmyk(_) | SwatchColor::Lab(_) | SwatchColor::Gray(_) => converted += 1, + SwatchColor::Rgb(_) | SwatchColor::Hsb(_) => {} + } + Some((e.name.clone(), rgb8(e.color.to_srgb(CmykConverter::coated()).to_rgb_array()), e.kind == SwatchKind::Spot)) + }) + .collect() + }) + .collect(); + (out, books, converted) +} + +pub(super) fn push_note(report: &mut SwatchReport, count: usize, note: impl FnOnce(usize) -> SwatchNote) { + if count > 0 { + report.notes.push(note(count)); + } +} diff --git a/crates/color/src/palette/tests.rs b/crates/color/src/palette/tests.rs new file mode 100644 index 000000000..787ec78f2 --- /dev/null +++ b/crates/color/src/palette/tests.rs @@ -0,0 +1,91 @@ +//! Tests for the swatch file codecs. + +use super::*; +use craft_ui::testing::trial; + +fn values(c: &SwatchColor) -> Vec { + match *c { + SwatchColor::Rgb(v) | SwatchColor::Hsb(v) | SwatchColor::Lab(v) => v.to_vec(), + SwatchColor::Cmyk(v) => v.to_vec(), + SwatchColor::Gray(k) => vec![k], + SwatchColor::Book { .. } => Vec::new(), + } +} + +fn assert_same(a: &SwatchColor, b: &SwatchColor) { + assert_eq!(std::mem::discriminant(a), std::mem::discriminant(b), "{a:?} vs {b:?}"); + if let (SwatchColor::Book { .. }, SwatchColor::Book { .. }) = (a, b) { + assert_eq!(a, b); + } + for (x, y) in values(a).into_iter().zip(values(b)) { + assert!((x - y).abs() < 1e-3, "{a:?} vs {b:?}"); + } +} + +fn group(name: &str, entries: Vec) -> SwatchGroup { + SwatchGroup { name: name.into(), entries } +} + +/// An `.aco` file with RGB, CMYK and Lab swatches round-trips with each colour in its model. +#[trial] +fn aco_round_trips_colours_in_their_own_model() { + let colors = [ + ("Red", SwatchColor::Rgb([1.0, 0.0, 0.25])), + ("Hue", SwatchColor::Hsb([120.0, 0.5, 0.75])), + ("Cyan ink", SwatchColor::Cmyk([1.0, 0.0, 0.25, 0.1])), + ("Lab", SwatchColor::Lab([53.0, -80.0, 67.5])), + ("Gray", SwatchColor::Gray(0.4)), + ("Book 日本", SwatchColor::Book { space: 3, values: [1, 2, 3, 4] }), + ]; + let entries = colors.iter().map(|(n, c)| SwatchEntry::new(*n, *c)).collect(); + let (bytes, report) = write_swatches(&[group("All", entries)], SwatchFormat::Aco).unwrap(); + assert!(report.notes.is_empty(), "{report:?}"); + let (groups, report) = read_swatches(&bytes, "Brand.aco").unwrap(); + assert_eq!(report.notes, [SwatchNote::BookColors(1)]); + assert_eq!(groups.len(), 1); + assert_eq!(groups[0].name, "Brand"); + for ((name, color), entry) in colors.iter().zip(&groups[0].entries) { + assert_eq!(entry.name, *name); + assert_same(color, &entry.color); + } + // A version 1 section comes first, then version 2 with the names. + assert_eq!(&bytes[..4], &[0, 1, 0, 6]); + assert!(bytes.windows(4).any(|w| w == [0, 2, 0, 6])); +} + +/// `.ase` keeps groups and spot colours; `.aco` flattens them and says so. +#[trial] +fn ase_keeps_groups_and_aco_reports_flattening() { + let mut spot = SwatchEntry::new("Spot Orange", SwatchColor::Cmyk([0.0, 0.5, 1.0, 0.0])); + spot.kind = SwatchKind::Spot; + let groups = vec![ + group("Brand", vec![SwatchEntry::new("Blue", SwatchColor::Rgb([0.0, 0.0, 1.0])), spot]), + group("Greys", vec![SwatchEntry::new("Mid", SwatchColor::Gray(0.5))]), + ]; + let (ase, report) = write_swatches(&groups, SwatchFormat::Ase).unwrap(); + assert!(report.notes.is_empty()); + let (back, _) = read_swatches(&ase, "x.ase").unwrap(); + assert_eq!(back.iter().map(|g| g.name.as_str()).collect::>(), ["Brand", "Greys"]); + assert_eq!(back[0].entries[1].kind, SwatchKind::Spot); + assert_same(&back[0].entries[1].color, &groups[0].entries[1].color); + assert_same(&back[1].entries[0].color, &SwatchColor::Gray(0.5)); + + // A colour in a model this crate does not read is skipped and counted. + let mut unknown = Vec::new(); + put_ase_name(&mut unknown, "Odd"); + unknown.extend(b"XYZ "); + unknown.extend([0u8; 12]); + unknown.extend(2u16.to_be_bytes()); + let mut file = ase.clone(); + put_ase_block(&mut file, ASE_COLOR, &unknown); + file[8..12].copy_from_slice(&(u32::from_be_bytes(ase[8..12].try_into().unwrap()) + 1).to_be_bytes()); + let (skipped, report) = read_swatches(&file, "x.ase").unwrap(); + assert_eq!(report.notes, [SwatchNote::Skipped(1)]); + assert_eq!(count_swatches(&skipped), 3); + + let (aco, report) = write_swatches(&groups, SwatchFormat::Aco).unwrap(); + assert_eq!(report.notes, [SwatchNote::GroupsFlattened, SwatchNote::KindsDropped(1)]); + let (flat, _) = read_swatches(&aco, "x.aco").unwrap(); + assert_eq!(flat.len(), 1); + assert_eq!(flat[0].entries.len(), 3); +} diff --git a/crates/color/src/palette/text.rs b/crates/color/src/palette/text.rs new file mode 100644 index 000000000..fc9841692 --- /dev/null +++ b/crates/color/src/palette/text.rs @@ -0,0 +1,121 @@ +//! GIMP `.gpl` palettes and CSS custom properties. + +use super::reader::*; +use super::*; + +// ---------------------------------------------------------------- .gpl and .css + +fn one_line(s: &str) -> String { + s.split(['\n', '\r', '\t']).collect::>().join(" ").trim().to_string() +} + +pub(super) fn rgb8(c: [f32; 3]) -> [u8; 3] { + c.map(|v| (unit(v) * 255.0).round() as u8) +} + +pub(super) fn read_gpl(bytes: &[u8], file_name: &str) -> Vec { + let text = String::from_utf8_lossy(bytes); + let text = text.trim_start_matches('\u{feff}'); + let mut groups: Vec = Vec::new(); + let mut seen = 0usize; + let mut grouped = false; + for line in text.lines().skip(1) { + let line = line.trim(); + if let Some(g) = line.strip_prefix(GPL_GROUP) { + let name = clip_name(g); + groups.push(SwatchGroup { name: if name.is_empty() { "Color Group".into() } else { name }, entries: Vec::new() }); + grouped = true; + continue; + } + 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 entry = SwatchEntry::new(entry_name(seen, &words[3..].join(" ")), SwatchColor::Rgb([r, g, b].map(|v| f32::from(v) / 255.0))); + seen += 1; + if !grouped && groups.is_empty() { + groups.push(SwatchGroup { name: stem_of(file_name), entries: Vec::new() }); + } + if let Some(group) = groups.last_mut() { + group.entries.push(entry); + } + } + groups +} + +pub(super) fn write_gpl(groups: &[SwatchGroup], colors: &[Vec<(String, [u8; 3])>]) -> String { + let title = groups.first().map_or_else(String::new, |g| one_line(&g.name)); + let mut out = format!("{GPL_HEADER}\nName: {title}\nColumns: 0\n#\n"); + for (group, list) in groups.iter().zip(colors) { + out.push_str(&format!("{GPL_GROUP} {}\n", one_line(&group.name))); + for (name, [r, g, b]) in list { + out.push_str(&format!("{r:3} {g:3} {b:3}\t{}\n", one_line(name))); + } + } + 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(super) 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 comment's text: `*/` can't end it early. +fn css_comment(s: &str) -> String { + one_line(s).replace("*/", "* /") +} + +pub(super) fn write_css(groups: &[SwatchGroup], colors: &[Vec]) -> String { + let mut out = String::from(":root {\n"); + let mut taken: std::collections::HashSet = std::collections::HashSet::new(); + // The next number to try for each base, so repeated names don't search the ones used before. + let mut next: std::collections::HashMap = std::collections::HashMap::new(); + for (group, list) in groups.iter().zip(colors) { + out.push_str(&format!(" /* {} */\n", css_comment(&group.name))); + for (name, [r, g, b], spot) in list { + // Names differing only in case or punctuation map to one property: number the others. + let base = css_property(name); + let property = if taken.insert(base.clone()) { + base + } else { + let n = next.entry(base.clone()).or_insert(1); + loop { + *n += 1; + let candidate = format!("{base}-{n}"); + if taken.insert(candidate.clone()) { + break candidate; + } + } + }; + let note = if *spot { " /* spot */" } else { "" }; + out.push_str(&format!(" {property}: #{r:02x}{g:02x}{b:02x};{note}\n")); + } + } + out.push_str("}\n"); + out +} + +/// Whether the head of `bytes` reads as a GIMP palette. +pub(super) fn is_gpl(bytes: &[u8]) -> bool { + let head = String::from_utf8_lossy(bytes.get(..1024).unwrap_or(bytes)); + head.trim_start_matches('\u{feff}').trim_start().starts_with(GPL_HEADER) +} diff --git a/crates/color/src/ui/area.rs b/crates/color/src/ui/area.rs new file mode 100644 index 000000000..91fc3f2c8 --- /dev/null +++ b/crates/color/src/ui/area.rs @@ -0,0 +1,208 @@ +//! [`ColorArea`]: two components of a colour across and down a field, the others fixed. + +use super::channels::{QUANTIZE_CELLS, channel_range, channel_step, quantized, settled, snapped, spoken}; +use crate::AreaMode; +use craft_behavior::{Metrics, Mixed, Proposal, Sense}; +use craft_theme::ModelValues; +use craft_ui::contract::{ + Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, MeasureCx, PaintUi, Props as _, Role, WordSetCx as _, +}; +use craft_ui::primitives::ContentPainterCx; +use craft_ui::runtime::env::Label; +use craft_ui::style::{ComponentStyle, StyleCx}; +use craft_ui::value_drag::PointPicker; +use egui::{Mesh, Rect, Vec2, pos2}; + +#[cfg(feature = "screen-testing")] +mod stories; + +/// Vertices along each side of the area's colour mesh (PhotoCraft's 32). +const MESH: usize = 32; + +/// The style of a colour area: the field is a point picker, which brings its own look. +#[derive(Clone, Debug, PartialEq, ComponentStyle)] +#[non_exhaustive] +pub struct ColorAreaStyle { + #[style(metrics)] + metrics: Metrics, +} + +/// The 2D field of a colour picker: two components of the colour across and down, the others fixed, as an +/// [`AreaMode`] lays them out (PhotoCraft's Color Picker field). It shows a `PointPicker` over the mode's two +/// channels, with the colours of the field as the picker's backdrop, so pointer, keys, wheel and AccessKit are the +/// picker's: a press jumps the point there, a drag follows the pointer (also outside the area, where the value stays +/// at the edge), the arrow keys step the across and down components (Up raises the down one, Shift steps ten) and a +/// step is the channel's (1 degree, 1 percent, 1 of 255, 0.001 of chroma). +/// +/// The host gives the colour as the mode's model values and gets them back with only the area's two components +/// changed, so a host that keeps the values it was sent keeps the hue of a grey and the hue and saturation of black. +/// The area keeps its axes right to left: across still grows to the right. Its value text names both components +/// ("Saturation 40 %, Brightness 70 %", from [`names`](ColorArea::names)). +#[derive(craft_ui::contract::Component, craft_ui::contract::Props)] +pub struct ColorArea<'a> { + #[common] + common: Common, + mode: AreaMode, + values: Bind<'a, ModelValues>, + /// Puts the colour the area reports on this many levels (at least two) per red, green and blue channel, whatever + /// the mode: a web-safe field has 6. The pointer takes the nearest such colour and a key steps one level of the + /// channel's range. The field shows flat cells of the snapped colours. + #[prop] + quantize: Option, + /// The names of the across and down components in the value text; the model's channel names without them. + #[prop] + names: Option<[Label; 2]>, +} + +impl<'a> ColorArea<'a> { + /// An area named `label` ("Saturation and brightness") showing `values`, values of `mode`'s model. + pub fn new(label: impl Into