diff --git a/ASSETS.md b/ASSETS.md
index 029a978153..ffa455079d 100644
--- a/ASSETS.md
+++ b/ASSETS.md
@@ -115,6 +115,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/icons/dc-anchor-smooth.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-appearance.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-arc.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
+| `assets/icons/dc-arc-three-point.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | The Three-Point Arc tool: an arc through its two ends and a third point |
| `assets/icons/dc-arrow-down.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-arrow-extend.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-arrow-fill.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | The Selection and Direct Selection arrows' fill, painted black or white under their outline |
diff --git a/Cargo.lock b/Cargo.lock
index 65cc426291..9acedd45bd 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1009,6 +1009,15 @@ dependencies = [
"ruzstd",
]
+[[package]]
+name = "craft-cms"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
+dependencies = [
+ "md-5",
+ "rayon",
+]
+
[[package]]
name = "craft-codepage"
version = "0.1.0"
@@ -6741,6 +6750,7 @@ dependencies = [
name = "vectorcraft-color"
version = "0.24.1"
dependencies = [
+ "craft-cms",
"kurbo 0.13.1",
"moxcms",
"proptest",
diff --git a/Cargo.toml b/Cargo.toml
index fea9cdda55..d60edf2af7 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -11,6 +11,7 @@ rust-version = "1.95"
repository = "https://github.com/storytold/vectorcraft"
[workspace.dependencies]
+craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", default-features = false, features = ["interpret", "write"] }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
diff --git a/ROADMAP.md b/ROADMAP.md
index c4a6edc8fb..90a6100167 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -128,6 +128,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-14: Built-in symbol library Weather Icons: adds a sixth procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Sun, Moon, Cloud, Rain, Thunder, Snow) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged.
- 2026-11-14: Built-in Tech Circuit brush library: Circuit Trace (chamfered art with 45-degree elbows and terminal pads), Bus Lines (parallel conductor pattern) and Terminal Nodes (repeating solder pads, test points and leads), all original geometry generated in code. Ten built-in brush libraries; G5 remaining estimate 3–13 h (estimated), headline numbers unchanged.
+- 2026-11-18: Built-in Paint brush library: Flat Sweep, Dry Drag, Loaded Stroke and Fan Sweep, original art brushes generated in code that take the stroke color as tints. Thirteen built-in brush libraries; headline numbers unchanged.
- 2026-11-05: Window › Toolbars › Keep Tools Beside the Canvas, off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and the canvas's left edge then also docks a floating Tools panel (`window.toolsBesideCanvas`, #5395). Workspaces keep the setting; workspaces saved without it keep Tools at the window's edge. An optional VectorCraft layout choice; headline numbers unchanged.
- 2026-11-17: The canvas's left edge docks a floating Tools panel whichever way Keep Tools Beside the Canvas is set: a drop there, right of panels docked on the left, turns the setting on, and a drop on the window's left edge turns it off (#7837). Headline numbers unchanged.
@@ -145,7 +146,9 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-17: Curvature Circle tool (after the Circle tool in its group): a click on a path draws the circle that touches it there and bends as it bends, on the side it bends toward, or with Shift on the other side; a segment that is the usual cubic of a circular arc of 90° or less gives the arc's own radius, so a click on a circle draws that circle; the tool shows the circle, its center and its radius (with an asterisk for an arc's radius) until the click, or "Straight segment", "Cusp", "Corner" or "Circle too large" where it draws none (`shape.curvatureCircle`). One undo step per circle. A VectorCraft addition: headline numbers unchanged.
- 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged.
- 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged.
+- 2026-11-17: Circle Tool Options (double-click the Circle tool): Show Center, Show Radii and Show Diameter switch what the tool shows while a circle is drawn, Color sets the color of the center cross and radius lines, Anchors at Standard Positions off puts the circle's anchors at the points it was drawn through (`shape.circleThroughPoints {anchors: "points"}`), and Third Point by Dragging off draws a three-point circle with three clicks and a two-point circle with a double-click on the second point. A VectorCraft addition: headline numbers unchanged.
- 2026-11-19: Quick Pen tool, in the Pen tool's group (Alt+P, Option+P on macOS): clicks or drags add straight lines, continuous arcs or sharp-corner arcs; Alt tapped on its own switches the action, C flips the last arc, `[` and `]` size it, a click on the first point closes the path and a click on an open end continues it (`path.quickPen`, part of #2660). Headline numbers unchanged.
+- 2026-11-19: Quick Pen toolbar on the canvas while the tool is active: Straight Line, Continuous Arc and Sharp Corner Arc, Flip Arc, and More Options with Hide Toolbar, Pin Toolbar Position and Reset Toolbar Position; it follows the drawing beside the path's last point and its handle drags it (`tool.quickPen.flipArc`, `window.quickPenToolbar`, Window › Quick Pen Toolbar; part of #2660). Headline numbers unchanged.
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
- 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
- 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
@@ -162,6 +165,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-17: Tangent Circle Tool joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools, and the All Tools drawer): click a path segment, then another, to draw the circle tangent to the first where it was clicked that touches the second; Shift uses the tool's radius and a drag from the second segment sets the radius (Shift in round steps, Cmd/Ctrl slowly), the circle then touching the first segment anywhere along it. The circle shows with its center and radii before the click, one undo step (`tangentCircle`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-18: Common Tangents also takes a point (a path of one anchor) and a convex closed path: the lines from the point that touch the path, and the line from the point to the path's center if asked; a point on the outline gets the one tangent there, and a point inside gets none, with a message (#7846). A VectorCraft addition: headline numbers unchanged.
- 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged.
+- 2026-11-17: Three-Point Arc tool, in the Line Segment tool's group after the Arc tool: two ends placed by a drag or two clicks, then a third point the open circular arc passes through, or with Third Point Sets Direction (Tool Options, or `]` while drawing) the direction the arc leaves an end in; it previews the arc, its center and, with Measurement Labels on, its radius, and draws it in one undo step (`shape.threePointArc`). Points with no arc are refused with a message. A VectorCraft addition: headline numbers unchanged.
- 2026-11-15: Smooth Bridge joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): two selected circles become one closed outline joined by two concave arcs that touch both circles, so every anchor is smooth; the arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default), and Keep Originals adds the outline above the circles instead of replacing them. A dialog with Preview, one undo step (`addon.pathtools.bridge`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-18: Smooth Bridge also joins three or more circles: every two whose outlines are within Reach (10 pt by default) are joined, the bridges that connect become one shape each, and a circle bridged to no other stays as it is (at most 2000 circles); with Constant Gap the arcs' radius is the smaller circle's radius plus a gap (#8030). A VectorCraft addition: headline numbers unchanged.
- 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged.
diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs
index 5dfe7386f6..533074b9b5 100644
--- a/apps/vectorcraft-cli/src/main.rs
+++ b/apps/vectorcraft-cli/src/main.rs
@@ -253,6 +253,7 @@ fn with_stores(mut h: Headless) -> Headless {
prefs_dir::attach_pdf_preset_store(&mut h.session);
prefs_dir::attach_custom_dictionary(&mut h.session);
prefs_dir::attach_arrowheads(&mut h.session);
+ prefs_dir::attach_bevels(&mut h.session);
h
}
diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs
index aa62211500..29cb56bdfa 100644
--- a/apps/vectorcraft/src/main.rs
+++ b/apps/vectorcraft/src/main.rs
@@ -567,6 +567,8 @@ fn main() -> std::process::ExitCode {
prefs_dir::attach_custom_dictionary(&mut app.session);
// The custom arrowheads, kept in their own file next to the preferences.
prefs_dir::attach_arrowheads(&mut app.session);
+ // The custom bevels, kept in their own file next to the preferences.
+ prefs_dir::attach_bevels(&mut app.session);
// Fit the window to its monitor, or put it back where it was (still hidden).
let winit_window = cc.winit_window().cloned();
if let Some(w) = &winit_window {
diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs
index f863a6eba3..492e2ea7bf 100644
--- a/apps/vectorcraft/src/prefs_dir.rs
+++ b/apps/vectorcraft/src/prefs_dir.rs
@@ -122,6 +122,14 @@ pub fn attach_arrowheads(session: &mut vectorcraft_engine::Session) {
}
}
+/// Keep the custom bevels (`threeD.bevels.edit`) in the `Bevels.vectorcraft` file next to the
+/// settings, and list the bevels it holds.
+pub fn attach_bevels(session: &mut vectorcraft_engine::Session) {
+ if let Some(path) = store_dir(vectorcraft_engine::cmd::bevels::FILE_NAME) {
+ session.attach_bevels_file(path.to_string_lossy().to_string());
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/assets/icons/dc-arc-three-point.svg b/assets/icons/dc-arc-three-point.svg
new file mode 100644
index 0000000000..479a9a5930
--- /dev/null
+++ b/assets/icons/dc-arc-three-point.svg
@@ -0,0 +1 @@
+
diff --git a/crates/cad/src/scene.rs b/crates/cad/src/scene.rs
index 3fc68180d0..700632313e 100644
--- a/crates/cad/src/scene.rs
+++ b/crates/cad/src/scene.rs
@@ -34,6 +34,7 @@ const WIDE_LINES: &str =
"lines wider than 2.11 mm (the widest lineweight) are written at 2.11 mm: Alter Paths for Appearance writes their true width";
const STROKE_EXTRAS: &str = "stroke alignment, width profiles, arrowheads and brushes are left out (Maximize Editability writes strokes as lines)";
const CLIPPING: &str = "clipping masks are not applied: the art they clip is written whole";
+const DISTORTED_IMAGES: &str = "images changed by Perspective Distort or Free Distort are written as the nearest parallelogram";
const TYPE_ITEMS: &str = "fills and strokes added to whole type objects are left out of text entities (outline the text to keep them)";
/// The warning for an image left out because it can't be decoded: the note raster exports give
/// (`vectorcraft-engine`'s `rasterfx::undecoded_warning`).
@@ -671,7 +672,18 @@ impl<'a> Scene<'a> {
self.shape(n, &bp, *rule);
}
NodeKind::Text(t) => self.text(n, t),
- NodeKind::Image(im) => self.image(&self.doc.shown_image(n, im)),
+ NodeKind::Image(im) => match vectorcraft_doc::image_quad::nearest_affine(n) {
+ // DXF clips nothing, so a distorted image is written at the affine placement nearest
+ // its corners, with the warning once it is written.
+ Some(xf) => {
+ if self.image(&ImageObject { xf, ..self.doc.shown_image(n, im).into_owned() }) {
+ self.warn(DISTORTED_IMAGES);
+ }
+ }
+ None => {
+ self.image(&self.doc.shown_image(n, im));
+ }
+ },
NodeKind::SymbolInstance { symbol, xf } => {
let doc = self.doc;
if self.symbol_nodes >= vectorcraft_doc::MAX_SYMBOL_NODES {
@@ -1325,18 +1337,19 @@ impl<'a> Scene<'a> {
name
}
- /// A placed image, linked to its file (written once per image).
- fn image(&mut self, im: &ImageObject) {
+ /// A placed image, linked to its file (written once per image). False when no `IMAGE` entity is
+ /// written.
+ fn image(&mut self, im: &ImageObject) -> bool {
if !self.o.version.handles() {
self.warn(NO_IMAGES);
- return;
+ return false;
}
if !self.o.include_images {
self.note_setting(IMAGES_OFF);
- return;
+ return false;
}
- let Some(i) = self.image_def(im) else { return };
- let Some((dw, dh)) = self.images.get(i).map(|d| (f64::from(d.size.0), f64::from(d.size.1))) else { return };
+ let Some(i) = self.image_def(im) else { return false };
+ let Some((dw, dh)) = self.images.get(i).map(|d| (f64::from(d.size.0), f64::from(d.size.1))) else { return false };
let (w, h) = (f64::from(im.width.max(1)), f64::from(im.height.max(1)));
let map = self.to_dxf * im.xf;
let lin = |v: kurbo::Vec2| (map * v.to_point()) - (map * Point::ZERO);
@@ -1349,7 +1362,7 @@ impl<'a> Scene<'a> {
let at = map * Point::new(0.0, h);
let handle = self.handle();
let reactor = self.handle();
- let Some(def) = self.images.get_mut(i) else { return };
+ let Some(def) = self.images.get_mut(i) else { return false };
def.reactors.push((reactor, handle));
let def = def.handle;
let layer = self.layer.clone();
@@ -1375,6 +1388,7 @@ impl<'a> Scene<'a> {
if self.o.version >= crate::DxfVersion::R2010 {
self.e.int(290, 0);
}
+ true
}
/// The image file for image `im`, encoded once in the chosen format (`None`: left out).
diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs
index 797223b688..35a1e8c45d 100644
--- a/crates/cad/src/tests.rs
+++ b/crates/cad/src/tests.rs
@@ -984,6 +984,37 @@ fn images_can_be_left_out_with_their_files() {
assert!(r12.warnings.iter().any(|w| w.contains("no images")) && r12.setting_notes.is_empty());
}
+/// DXF does not clip, so an image changed by Perspective Distort is written as one image at the
+/// placement nearest its corners, with a warning; an undistorted image gets no warning.
+#[test]
+fn a_distorted_image_is_written_as_its_nearest_parallelogram_with_a_warning() {
+ let mut d = image_and_fill_doc(Paint::None);
+ let warned = |o: &DxfOutput| o.warnings.iter().any(|w| w.contains("Perspective Distort or Free Distort"));
+ assert!(!warned(&export(&d, &opts(&d)).unwrap()));
+ let id = d.layers[0].children().unwrap()[1].id;
+ let q = [(12.0, 20.0), (28.0, 20.0), (30.0, 30.0), (10.0, 30.0)].map(|(x, y)| Point::new(x, y));
+ d.node_mut(id).unwrap().set_image_corners(q).unwrap();
+ let out = export(&d, &opts(&d)).unwrap();
+ assert!(warned(&out), "{:?}", out.warnings);
+ assert_eq!(kinds(&out).iter().filter(|k| *k == "IMAGE").count(), 1, "{:?}", kinds(&out));
+ // Placed as an undistorted image with the nearest affine placement as its transform would be.
+ let near = vectorcraft_doc::image_quad::nearest_affine(d.node(id).unwrap()).unwrap();
+ let mut plain = d.clone();
+ let n = plain.node_mut(id).unwrap();
+ n.extras_mut().image_quad = None;
+ if let NodeKind::Image(im) = &mut n.kind {
+ im.xf = near;
+ }
+ let placement = |o: &DxfOutput| {
+ let e = entities(o).into_iter().find(|e| kind(e) == "IMAGE").expect("an IMAGE");
+ [10, 20, 11, 21, 12, 22].map(|c| all(&e, c))
+ };
+ assert_eq!(placement(&out), placement(&export(&plain, &opts(&plain)).unwrap()));
+ // With images left out, no IMAGE is written and the distortion warning does not appear.
+ let left_out = export(&d, &DxfOptions { include_images: false, ..opts(&d) }).unwrap();
+ assert!(!warned(&left_out), "{:?}", left_out.warnings);
+}
+
#[test]
fn images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both() {
let d = image_and_fill_doc(Paint::solid(Color::rgb(1.0, 0.0, 0.0)));
diff --git a/crates/color/Cargo.toml b/crates/color/Cargo.toml
index a007ede39f..1273b5d0ad 100644
--- a/crates/color/Cargo.toml
+++ b/crates/color/Cargo.toml
@@ -9,6 +9,7 @@ description = "VectorCraft color"
workspace = true
[dependencies]
+craft-cms = { workspace = true }
kurbo = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs
index fa8cd564f2..c3d74615ae 100644
--- a/crates/color/src/lib.rs
+++ b/crates/color/src/lib.rs
@@ -10,6 +10,7 @@ pub mod freeform;
pub mod gradient;
pub mod harmony;
pub mod libraries;
+pub mod oklab;
pub mod palette_io;
pub mod recolor;
pub mod swatch;
@@ -340,6 +341,49 @@ pub fn hsb_to_rgb([h, s, v]: [f32; 3]) -> [f32; 3] {
[r + m, g + m, b + m]
}
+/// HSL (hue in degrees 0..360, saturation and lightness 0..1) of RGB numbers 0..1, with no color
+/// conversion, as CSS Color 4 converts sRGB to HSL
+/// (). The hue is 0 while the saturation is
+/// powerless, and a color outside 0..1 that gives a negative saturation turns its hue by 180°. As in
+/// the specification's conversion, a lightness of 0.00001 or less, a lightness less than 0.00001
+/// below 1, or a saturation of 0.00001 or less reads as a gray.
+pub fn rgb_to_hsl([r, g, b]: [f32; 3]) -> [f32; 3] {
+ const EPSILON: f32 = 1e-5;
+ let max = r.max(g).max(b);
+ let min = r.min(g).min(b);
+ let d = max - min;
+ let l = (max + min) / 2.0;
+ if d <= 0.0 {
+ return [0.0, 0.0, l];
+ }
+ let mut s = if l.abs() <= EPSILON || (1.0 - l).abs() < EPSILON { 0.0 } else { (max - l) / l.min(1.0 - l) };
+ let mut h = rgb_to_hsb([r, g, b])[0];
+ if s < 0.0 {
+ h += 180.0;
+ s = -s;
+ }
+ if s <= EPSILON {
+ return [0.0, 0.0, l];
+ }
+ let h = h.rem_euclid(360.0);
+ [if h >= 360.0 { 0.0 } else { h }, s, l]
+}
+
+/// RGB numbers 0..1 of HSL `[h, s, l]` (hue in degrees, saturation and lightness 0..1), as CSS
+/// Color 4 converts HSL to sRGB (): the inverse of
+/// [`rgb_to_hsl`]. A hue outside 0..360 wraps into that range before the conversion, so -120°
+/// gives the color of 240° and a hue of 10,000,000,000° the color of 280°. The specification's
+/// sample code uses JavaScript's remainder operator and gives a different color for a negative hue.
+pub fn hsl_to_rgb([h, s, l]: [f32; 3]) -> [f32; 3] {
+ let h = h.rem_euclid(360.0);
+ let a = s * l.min(1.0 - l);
+ let f = |n: f32| {
+ let k = (n + h / 30.0).rem_euclid(12.0);
+ l - a * (k - 3.0).min(9.0 - k).clamp(-1.0, 1.0)
+ };
+ [f(0.0), f(8.0), f(4.0)]
+}
+
/// `new` expressed in the colour model of `orig` ([`Color::in_model`]): results of colour operations
/// (harmonies, blends, inversions, recolouring) keep the model of the colour they came from.
pub fn keep_model(orig: Color, new: Color) -> Color {
@@ -499,6 +543,59 @@ mod tests {
}
}
+ /// The HSL examples of CSS Color 4, section 7 (),
+ /// the first six rows, and two hues outside 0..360 that wrap into that range.
+ #[test]
+ fn hsl_follows_css_color_4() {
+ for (hsl, hex) in [
+ ([0.0, 1.0, 0.5], "#ff0000"),
+ ([120.0, 1.0, 0.5], "#00ff00"),
+ ([120.0, 1.0, 0.25], "#008000"),
+ ([120.0, 1.0, 0.75], "#80ff80"),
+ ([240.0, 1.0, 0.5], "#0000ff"),
+ ([60.0, 1.0, 0.5], "#ffff00"),
+ ([360.0, 1.0, 0.5], "#ff0000"),
+ ([-120.0, 1.0, 0.5], "#0000ff"),
+ ] {
+ let [r, g, b] = hsl_to_rgb(hsl);
+ assert_eq!(Color::rgb(r, g, b).to_hex(), hex, "{hsl:?}");
+ }
+ let [h, s, l] = rgb_to_hsl([1.0, 0.5, 0.0]);
+ assert!((h - 30.0).abs() < 1e-4 && (s - 1.0).abs() < 1e-6 && (l - 0.5).abs() < 1e-6, "{h} {s} {l}");
+ let [h, s, l] = rgb_to_hsl(Color::rgb8(255, 128, 0).to_rgb_uncalibrated());
+ assert!((h - 30.0).abs() < 0.2 && (s - 1.0).abs() < 1e-6 && (l - 0.5).abs() < 1e-3, "{h} {s} {l}");
+ // A gray has no hue: the hue is 0 and the saturation 0, at any lightness.
+ for v in [0.0, 0.25, 0.5, 1.0] {
+ assert_eq!(rgb_to_hsl([v, v, v]), [0.0, 0.0, v]);
+ }
+ // Black and white keep any hue and saturation they are given.
+ assert_eq!(hsl_to_rgb([200.0, 0.7, 0.0]), [0.0, 0.0, 0.0]);
+ assert_eq!(hsl_to_rgb([200.0, 0.7, 1.0]), [1.0, 1.0, 1.0]);
+ // A color past the gamut that gives a negative saturation turns its hue by 180°.
+ let [h, s, _] = rgb_to_hsl([1.2, 1.5, 1.4]);
+ assert!(s > 0.0 && (h - (160.0 + 180.0)).abs() < 1e-3, "{h} {s}");
+ // A huge hue wraps before the channels are worked out: 10,000,000,000° is 280°.
+ let (huge, wrapped) = (hsl_to_rgb([10_000_000_000.0, 1.0, 0.5]), hsl_to_rgb([280.0, 1.0, 0.5]));
+ assert!((0..3).all(|i| (huge[i] - wrapped[i]).abs() < 1e-6), "{huge:?} {wrapped:?}");
+ }
+
+ /// The 216 web colors go to HSL and back to the same 8-bit color.
+ #[test]
+ fn hsl_roundtrip() {
+ let steps = [0x00, 0x33, 0x66, 0x99, 0xcc, 0xff];
+ for r in steps {
+ for g in steps {
+ for b in steps {
+ let c = Color::rgb8(r, g, b);
+ let [h, s, l] = rgb_to_hsl(c.to_rgb_uncalibrated());
+ assert!((0.0..360.0).contains(&h) && (0.0..=1.0).contains(&s) && (0.0..=1.0).contains(&l), "{}", c.to_hex());
+ let back = hsl_to_rgb([h, s, l]).map(|v| (v * 255.0).round() as u8);
+ assert_eq!(back, [r, g, b], "{}", c.to_hex());
+ }
+ }
+ }
+ }
+
#[test]
fn cmyk_conversions() {
assert_eq!(Color::cmyk(0.0, 0.0, 0.0, 1.0).to_rgb_uncalibrated(), [0.0, 0.0, 0.0]);
diff --git a/crates/color/src/libraries.rs b/crates/color/src/libraries.rs
index 5fc952a061..c2946d92a2 100644
--- a/crates/color/src/libraries.rs
+++ b/crates/color/src/libraries.rs
@@ -99,18 +99,24 @@ pub fn builtin_library(id: &str) -> Option> {
// ---------- colour construction ----------
-/// sRGB (0..=1, gamma encoded) of OKLab `(l, a, b)`, unclamped.
+/// sRGB (0..=1, gamma encoded) of OKLab `(l, a, b)`, unclamped. A linear channel below
+/// −0.0031308 is encoded with the curve's sign turned, as CSS Color 4's extended sRGB does
+/// ().
pub(crate) fn oklab_to_srgb(l: f64, a: f64, b: f64) -> [f64; 3] {
+ oklab_to_linear_srgb(l, a, b).map(|v| if v.abs() <= 0.003_130_8 { 12.92 * v } else { v.signum() * (1.055 * v.abs().powf(1.0 / 2.4) - 0.055) })
+}
+
+/// Linear sRGB of OKLab `(l, a, b)`, unclamped.
+pub(crate) fn oklab_to_linear_srgb(l: f64, a: f64, b: f64) -> [f64; 3] {
let l_ = l + 0.396_337_777_4 * a + 0.215_803_757_3 * b;
let m_ = l - 0.105_561_345_8 * a - 0.063_854_172_8 * b;
let s_ = l - 0.089_484_177_5 * a - 1.291_485_548_0 * b;
let (l3, m3, s3) = (l_ * l_ * l_, m_ * m_ * m_, s_ * s_ * s_);
- let lin = [
+ [
4.076_741_662_1 * l3 - 3.307_711_591_3 * m3 + 0.230_969_929_2 * s3,
-1.268_438_004_6 * l3 + 2.609_757_401_1 * m3 - 0.341_319_396_5 * s3,
-0.004_196_086_3 * l3 - 0.703_418_614_7 * m3 + 1.707_614_701_0 * s3,
- ];
- lin.map(|v| if v <= 0.003_130_8 { 12.92 * v } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 })
+ ]
}
/// OKLab `[l, a, b]` of a colour's display RGB.
@@ -118,11 +124,13 @@ pub fn to_oklab(c: &Color) -> [f64; 3] {
srgb_to_oklab(c.to_rgb_uncalibrated())
}
-/// OKLab `[l, a, b]` of sRGB `rgb` (0..=1, gamma encoded).
+/// OKLab `[l, a, b]` of sRGB `rgb` (0..=1, gamma encoded). A channel below −0.04045 is decoded
+/// with the curve's sign turned, as CSS Color 4's extended sRGB does
+/// ().
pub(crate) fn srgb_to_oklab(rgb: [f32; 3]) -> [f64; 3] {
let [r, g, b] = rgb.map(|v| {
let v = f64::from(v);
- if v <= 0.040_45 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
+ if v.abs() <= 0.040_45 { v / 12.92 } else { v.signum() * ((v.abs() + 0.055) / 1.055).powf(2.4) }
});
let l = (0.412_221_470_8 * r + 0.536_332_536_3 * g + 0.051_445_992_9 * b).cbrt();
let m = (0.211_903_498_2 * r + 0.680_699_545_1 * g + 0.107_396_956_6 * b).cbrt();
diff --git a/crates/color/src/oklab.rs b/crates/color/src/oklab.rs
new file mode 100644
index 0000000000..31500d1ac5
--- /dev/null
+++ b/crates/color/src/oklab.rs
@@ -0,0 +1,266 @@
+//! OKLCH, the polar form of Oklab, as CSS Color 4 defines it
+//! (): lightness L from 0 to 1, chroma
+//! C (CSS reads 100% as 0.4) and hue H in degrees from the positive `a` axis. The conversions take
+//! and give gamma-encoded sRGB through the Oklab matrices of [`crate::libraries`].
+
+use crate::libraries::{oklab_to_linear_srgb, oklab_to_srgb, srgb_to_oklab};
+
+/// The chroma CSS reads as 100%.
+pub const CHROMA_FULL: f64 = 0.4;
+
+/// Chroma at or below which the hue is powerless (CSS Color 4's ε); [`to_oklch`] gives hue 0 there.
+pub const POWERLESS_CHROMA: f64 = 0.000_004;
+
+/// How far outside 0..=1 an sRGB component may be and still count as inside the gamut.
+const GAMUT_SLACK: f64 = 1e-4;
+
+/// OKLCH `[l, c, h°]` of sRGB `rgb` (gamma encoded). Values outside 0..=1 are converted as they
+/// are. The hue is in 0..360, and 0 while the chroma is powerless.
+pub fn to_oklch(rgb: [f32; 3]) -> [f64; 3] {
+ let [l, a, b] = srgb_to_oklab(rgb);
+ let c = a.hypot(b);
+ if c <= POWERLESS_CHROMA {
+ return [l, 0.0, 0.0];
+ }
+ [l, c, b.atan2(a).to_degrees().rem_euclid(360.0)]
+}
+
+/// sRGB (gamma encoded) of OKLCH `(l, c, h°)`, unclamped.
+pub fn oklch_to_srgb(l: f64, c: f64, h: f64) -> [f64; 3] {
+ let (sin, cos) = h.to_radians().sin_cos();
+ oklab_to_srgb(l, c * cos, c * sin)
+}
+
+/// Whether sRGB `rgb` lies inside the sRGB gamut.
+pub fn in_srgb(rgb: [f64; 3]) -> bool {
+ rgb.iter().all(|v| (-GAMUT_SLACK..=1.0 + GAMUT_SLACK).contains(v))
+}
+
+/// The largest chroma sRGB holds at lightness `l` and hue `h°`: 0 at or outside black and white.
+pub fn max_chroma(l: f64, h: f64) -> f64 {
+ largest_fitting_chroma(l, h, f64::INFINITY)
+}
+
+/// The largest chroma no more than `limit` that sRGB holds at lightness `l` and hue `h°`: 0 at or
+/// outside black and white.
+///
+/// The chromas sRGB holds along the ray can come in several stretches: at the lightness and hue of
+/// blue the ray leaves sRGB at a chroma of about 0.266 and comes back at blue itself, about 0.313,
+/// and near black the gamut slack opens stretches of its own. Each linear sRGB channel is a cubic
+/// in the chroma, so every stretch ends where a channel's cubic meets a bound of the gamut. The
+/// search finds each such chroma between the cubic's turning points and takes the largest one that
+/// fits.
+fn largest_fitting_chroma(l: f64, h: f64, limit: f64) -> f64 {
+ if !(l > 0.0 && l < 1.0) || !h.is_finite() {
+ return 0.0;
+ }
+ let top = limit.min(0.5);
+ if top <= 0.0 {
+ return 0.0;
+ }
+ let fits = |c: f64| in_srgb(oklch_to_srgb(l, c, h));
+ if fits(top) {
+ return top;
+ }
+ let (sin, cos) = h.to_radians().sin_cos();
+ let lin = |c: f64| oklab_to_linear_srgb(l, c * cos, c * sin);
+ // The linear channels at chromas 0, s, 2s and 3s give each cubic's coefficients in t = c / s.
+ let s = top / 3.0;
+ let y = [lin(0.0), lin(s), lin(2.0 * s), lin(3.0 * s)];
+ let bounds = [-GAMUT_SLACK / 12.92, ((1.0 + GAMUT_SLACK + 0.055) / 1.055).powf(2.4)];
+ let mut ends = vec![0.0];
+ for ch in 0..3 {
+ let [y0, y1, y2, y3] = [y[0][ch], y[1][ch], y[2][ch], y[3][ch]];
+ let (d1, d2, d3) = (y1 - y0, y2 - 2.0 * y1 + y0, y3 - 3.0 * y2 + 3.0 * y1 - y0);
+ let k = [y0, d1 - d2 / 2.0 + d3 / 3.0, d2 / 2.0 - d3 / 2.0, d3 / 6.0];
+ let p = |t: f64| ((k[3] * t + k[2]) * t + k[1]) * t + k[0];
+ // The cubic rises or falls on each stretch between its turning points.
+ let mut cuts = vec![0.0, 3.0];
+ cuts.extend(turning_points(3.0 * k[3], 2.0 * k[2], k[1]).into_iter().filter(|t| *t > 0.0 && *t < 3.0));
+ cuts.sort_by(f64::total_cmp);
+ ends.extend(cuts.iter().map(|t| t * s));
+ for w in cuts.windows(2) {
+ for bound in bounds {
+ let (mut a, mut b) = (w[0], w[1]);
+ let fa = p(a) - bound;
+ if fa * (p(b) - bound) > 0.0 {
+ continue;
+ }
+ for _ in 0..60 {
+ let mid = (a + b) / 2.0;
+ if (p(mid) - bound) * fa > 0.0 { a = mid } else { b = mid }
+ }
+ ends.extend([a * s, b * s]);
+ }
+ }
+ }
+ ends.sort_by(|a, b| b.total_cmp(a));
+ ends.into_iter().flat_map(|c| [c, c - 1e-9]).find(|c| (0.0..=top).contains(c) && fits(*c)).unwrap_or(0.0)
+}
+
+/// The real roots of `a t² + b t + c`.
+fn turning_points(a: f64, b: f64, c: f64) -> Vec {
+ if a.abs() < 1e-15 {
+ return if b.abs() < 1e-15 { Vec::new() } else { vec![-c / b] };
+ }
+ let disc = b * b - 4.0 * a * c;
+ if disc < 0.0 {
+ return Vec::new();
+ }
+ let r = disc.sqrt();
+ vec![(-b - r) / (2.0 * a), (-b + r) / (2.0 * a)]
+}
+
+/// The sRGB color (gamma encoded, 0..=1) of OKLCH `(l, c, h°)`, and whether its chroma was lowered:
+/// a color outside sRGB keeps its lightness and hue and takes the largest chroma below it that
+/// fits. Lightness is clamped to 0..=1 and chroma to 0 or more.
+pub fn from_oklch(l: f64, c: f64, h: f64) -> ([f32; 3], bool) {
+ let l = if l.is_nan() { 0.0 } else { l.clamp(0.0, 1.0) };
+ let c = if c.is_nan() { 0.0 } else { c.max(0.0) };
+ let h = if h.is_finite() { h } else { 0.0 };
+ let exact = oklch_to_srgb(l, c, h);
+ let (rgb, lowered) = if in_srgb(exact) { (exact, false) } else { (oklch_to_srgb(l, largest_fitting_chroma(l, h, c), h), true) };
+ (rgb.map(|v| v.clamp(0.0, 1.0) as f32), lowered)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn eight(rgb: [f32; 3]) -> [u8; 3] {
+ rgb.map(|v| (v * 255.0).round() as u8)
+ }
+
+ #[test]
+ fn red_has_the_oklch_of_the_oklab_matrices_and_converts_back() {
+ let [l, c, h] = to_oklch([1.0, 0.0, 0.0]);
+ assert!((l - 0.6280).abs() < 5e-5 && (c - 0.2577).abs() < 5e-5 && (h - 29.23).abs() < 5e-3, "{l} {c} {h}");
+ let (rgb, lowered) = from_oklch(l, c, h);
+ assert_eq!((eight(rgb), lowered), ([255, 0, 0], false));
+ }
+
+ /// CSS Color 4's examples convert to the hue its oklab() and oklch() forms give.
+ #[test]
+ fn the_polar_form_matches_the_css_examples() {
+ for ([l, a, b], [cl, cc, ch]) in
+ [([0.40101, 0.1147, 0.0453], [0.40101, 0.12332, 21.555]), ([0.65125, -0.0320, 0.1274], [0.65125, 0.13138, 104.097])]
+ {
+ let rgb = oklab_to_srgb(l, a, b).map(|v| v as f32);
+ let [ol, oc, oh] = to_oklch(rgb);
+ assert!((ol - cl).abs() < 1e-4 && (oc - cc).abs() < 1e-4 && (oh - ch).abs() < 0.05, "{ol} {oc} {oh}");
+ }
+ }
+
+ #[test]
+ fn the_216_web_colors_round_trip() {
+ let steps = [0u8, 0x33, 0x66, 0x99, 0xcc, 0xff];
+ for r in steps {
+ for g in steps {
+ for b in steps {
+ let rgb = [r, g, b].map(|v| f32::from(v) / 255.0);
+ let [l, c, h] = to_oklch(rgb);
+ assert_eq!(eight(from_oklch(l, c, h).0), [r, g, b], "{l} {c} {h}");
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn grays_have_no_chroma_and_hue_zero() {
+ for v in [0.0, 0.5, 1.0] {
+ let [_, c, h] = to_oklch([v, v, v]);
+ assert!(c <= POWERLESS_CHROMA && h == 0.0, "{c} {h}");
+ }
+ }
+
+ /// A chroma past the gamut gives a color inside it with the same lightness and hue, and says so.
+ #[test]
+ fn a_chroma_past_the_gamut_is_lowered_keeping_lightness_and_hue() {
+ let (l, h) = (0.7, 150.0);
+ let max = max_chroma(l, h);
+ assert!(max > 0.05 && max < CHROMA_FULL, "{max}");
+ assert!(in_srgb(oklch_to_srgb(l, max, h)) && !in_srgb(oklch_to_srgb(l, max + 1e-3, h)));
+ let (rgb, lowered) = from_oklch(l, CHROMA_FULL, h);
+ assert!(lowered);
+ let [ol, oc, oh] = to_oklch(rgb);
+ assert!((ol - l).abs() < 2e-3 && (oh - h).abs() < 1.0 && (oc - max).abs() < 2e-3, "{ol} {oc} {oh}");
+ assert!(!from_oklch(l, max * 0.5, h).1);
+ }
+
+ /// At the lightness and hue of blue the ray leaves sRGB and comes back at blue itself, so the
+ /// largest chroma is blue's, and a chroma past it gives blue.
+ #[test]
+ fn the_largest_chroma_at_blues_hue_is_blues() {
+ let [l, c, h] = to_oklch([0.0, 0.0, 1.0]);
+ let max = max_chroma(l, h);
+ assert!((max - c).abs() < 1e-4 && in_srgb(oklch_to_srgb(l, max, h)), "{max} {c}");
+ let (rgb, lowered) = from_oklch(l, CHROMA_FULL, h);
+ assert_eq!((eight(rgb), lowered), ([0, 0, 255], true));
+ // A chroma between the two stretches takes the end of the first one, inside sRGB.
+ let (rgb, lowered) = from_oklch(l, 0.29, h);
+ let [_, gc, _] = to_oklch(rgb);
+ assert!(lowered && gc < 0.27 && in_srgb(oklch_to_srgb(l, gc, h)), "{gc}");
+ // A hue just past blue's: a narrow second stretch ends just below the line from black to blue.
+ let (l, h) = (0.44, 264.06);
+ let max = max_chroma(l, h);
+ assert!(max > 0.304 && max < 0.305 && in_srgb(oklch_to_srgb(l, max, h)), "{max}");
+ let [_, got, _] = to_oklch(from_oklch(l, 0.35, h).0);
+ assert!(got > 0.303, "{got}");
+ // A darker blue on the line from black to blue.
+ let [l, c, h] = to_oklch([0.0, 0.0, 0.25]);
+ assert!((max_chroma(l, h) - c).abs() < 1e-4, "{} {c}", max_chroma(l, h));
+ }
+
+ /// Just below blue's lightness the line from black to blue passes a chroma of 0.3125, where a
+ /// search from 0 to 0.5 lands first. A chroma asked for below that line still gives a color
+ /// inside sRGB with the lightness and hue asked for.
+ #[test]
+ fn a_chroma_below_the_line_from_black_to_blue_stays_inside_srgb() {
+ let [bl, bc, h] = to_oklch([0.0, 0.0, 1.0]);
+ let l = bl * 0.3125 / bc;
+ let (rgb, lowered) = from_oklch(l, 0.29, h);
+ let [gl, gc, gh] = to_oklch(rgb);
+ assert!(lowered && gc < 0.29 && in_srgb(oklch_to_srgb(l, gc, h)), "{gc}");
+ assert!((gl - l).abs() < 2e-3 && (gh - h).abs() < 1.0, "{gl} {gh}");
+ }
+
+ /// sRGB channels below 0 go through the transfer curve with its sign turned, as CSS Color 4's
+ /// extended sRGB does, in both directions.
+ #[test]
+ fn negative_channels_use_the_signed_transfer_curve() {
+ let linear = -((0.5_f64 + 0.055) / 1.055).powf(2.4);
+ let [l, c, _] = to_oklch([-0.5; 3]);
+ assert!((l - linear.cbrt()).abs() < 1e-4 && c <= POWERLESS_CHROMA, "{l} {c}");
+ for v in oklch_to_srgb(linear.cbrt(), 0.0, 0.0) {
+ assert!((v + 0.5).abs() < 1e-4, "{v}");
+ }
+ // Small values near 0 keep the straight part of the curve.
+ let [l, _, _] = to_oklch([-0.01; 3]);
+ assert!((l - (-0.01_f64 / 12.92).cbrt()).abs() < 1e-4, "{l}");
+ }
+
+ /// The largest chroma fits and is at least the largest one a scan in steps of 0.0005 finds, at
+ /// every hue and at lightnesses near black too, where the ray can come back into sRGB away from
+ /// any primary color's hue (L 0.02 and H 242° fit up to about 0.022 after leaving near 0.012).
+ #[test]
+ fn the_largest_chroma_is_never_below_a_scan_of_the_ray() {
+ let scan = |l: f64, h: f64| (0..=1000).map(|i| f64::from(i) * 0.0005).filter(|c| in_srgb(oklch_to_srgb(l, *c, h))).fold(0.0, f64::max);
+ assert!(max_chroma(0.02, 242.0) > 0.02, "{}", max_chroma(0.02, 242.0));
+ for l in [0.005, 0.02, 0.05, 0.1, 0.3, 0.44, 0.6, 0.8, 0.95, 0.99] {
+ for h in (0..72).map(|i| f64::from(i) * 5.0 + 2.0) {
+ let max = max_chroma(l, h);
+ assert!(in_srgb(oklch_to_srgb(l, max, h)) && max >= scan(l, h), "L {l} H {h}: {max} < {}", scan(l, h));
+ }
+ }
+ }
+
+ #[test]
+ fn black_white_and_bad_numbers_hold_no_chroma() {
+ assert_eq!(max_chroma(0.0, 30.0), 0.0);
+ assert_eq!(max_chroma(1.0, 30.0), 0.0);
+ assert_eq!(max_chroma(f64::NAN, 30.0), 0.0);
+ assert_eq!(max_chroma(0.5, f64::INFINITY), 0.0);
+ assert_eq!(eight(from_oklch(f64::NAN, f64::NAN, f64::NAN).0), [0, 0, 0]);
+ assert_eq!(eight(from_oklch(2.0, -1.0, 0.0).0), [255, 255, 255]);
+ }
+}
diff --git a/crates/color/src/palette_io.rs b/crates/color/src/palette_io.rs
index 9be00b4b21..c14075bd2e 100644
--- a/crates/color/src/palette_io.rs
+++ b/crates/color/src/palette_io.rs
@@ -6,6 +6,8 @@
use std::collections::{HashMap, HashSet};
+pub use craft_cms::palette::css_property;
+use craft_cms::palette::{self as cms_palette, Palette, PaletteColor, PaletteError, PaletteGroup, PaletteSwatch};
use serde::{Deserialize, Serialize};
use crate::{Color, GradientKind, Paint, Swatch, SwatchGroup, SwatchLibrary};
@@ -83,18 +85,93 @@ struct NativeFile {
const NATIVE_FORMAT: &str = "vcswatches";
const GPL_HEADER: &str = "GIMP Palette";
-const GPL_GROUP: &str = "# Group:";
const ASE_SIGNATURE: &[u8] = b"ASEF";
-const ASE_GROUP_START: u16 = 0xC001;
-const ASE_GROUP_END: u16 = 0xC002;
-const ASE_COLOR: u16 = 0x0001;
-/// The most colors and groups read from one `.ase` file.
-const ASE_MAX_ENTRIES: usize = 100_000;
-/// The most UTF-16 code units of a name that are kept.
-const ASE_MAX_NAME: usize = 1024;
-const ASE_CUT_SHORT: &str = "the swatch exchange file is cut short";
const ACB_SIGNATURE: &[u8] = b"8BCB";
-const ACB_CUT_SHORT: &str = "the color book is cut short";
+#[cfg(test)]
+const ASE_GROUP_START: u16 = 0xC001;
+#[cfg(test)]
+const ASE_MAX_ENTRIES: usize = 100_000;
+
+fn color_to_cms(c: Color) -> PaletteColor {
+ match c {
+ Color::Rgb { r, g, b } => PaletteColor::Rgb { r, g, b },
+ Color::Cmyk { c, m, y, k } => PaletteColor::Cmyk { c, m, y, k },
+ Color::Lab { l, a, b } => PaletteColor::Lab { l, a, b },
+ Color::Gray { k } => PaletteColor::Gray { k },
+ }
+}
+
+fn color_from_cms(c: PaletteColor) -> Color {
+ match c {
+ PaletteColor::Rgb { r, g, b } => Color::rgb(r, g, b),
+ PaletteColor::Cmyk { c, m, y, k } => Color::cmyk(c, m, y, k),
+ PaletteColor::Lab { l, a, b } => Color::lab(l, a, b),
+ PaletteColor::Gray { k } => Color::gray(k),
+ }
+}
+
+// GPL must retain the app-managed display conversion; ASE preserves authoring models.
+fn swatches_to_cms(list: &[Swatch], rgb_only: bool) -> Vec {
+ list.iter()
+ .filter_map(|w| {
+ w.paint.color().map(|c| PaletteSwatch {
+ name: w.name.clone(),
+ color: if rgb_only {
+ let [r, g, b, _] = c.to_rgba8(1.0);
+ PaletteColor::rgb8(r, g, b)
+ } else {
+ color_to_cms(c)
+ },
+ global: w.global,
+ spot: w.spot,
+ })
+ })
+ .collect()
+}
+
+fn swatches_from_cms(list: Vec) -> Vec {
+ list.into_iter().map(|w| Swatch { name: w.name, paint: Paint::solid(color_from_cms(w.color)), global: w.global, spot: w.spot }).collect()
+}
+
+fn to_cms_palette(lib: &SwatchLibrary, rgb_only: bool) -> Palette {
+ Palette {
+ name: lib.name.clone(),
+ swatches: swatches_to_cms(&lib.swatches, rgb_only),
+ groups: lib.groups.iter().map(|g| PaletteGroup { name: g.name.clone(), swatches: swatches_to_cms(&g.swatches, rgb_only) }).collect(),
+ }
+}
+
+fn from_cms_palette(p: Palette) -> SwatchLibrary {
+ SwatchLibrary {
+ name: p.name,
+ swatches: swatches_from_cms(p.swatches),
+ groups: p.groups.into_iter().map(|g| SwatchGroup { name: g.name, swatches: swatches_from_cms(g.swatches) }).collect(),
+ }
+}
+
+/// Maps structured shared palette errors to VectorCraft's translatable messages.
+fn palette_error(err: PaletteError) -> String {
+ match err {
+ PaletteError::UnsupportedFormat => "not a supported palette (.gpl, .ase, or .acb)".into(),
+ PaletteError::TruncatedAse => "the swatch exchange file is cut short".into(),
+ PaletteError::TruncatedAcb => "the color book is cut short".into(),
+ PaletteError::AseWriteEntryLimit { limit, entries } => format!(
+ "VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries}",
+ ASE_MAX_ENTRIES = limit
+ ),
+ PaletteError::AseReadEntryLimit { limit } => {
+ format!("the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups", ASE_MAX_ENTRIES = limit)
+ }
+ PaletteError::AseBlockCount => "too many swatch exchange blocks".into(),
+ PaletteError::AseBlockLength => "a swatch exchange block is too long".into(),
+ PaletteError::AseNameLength => "a swatch exchange name is too long".into(),
+ PaletteError::AseVersion { major, minor } => format!("swatch exchange version {major}.{minor} isn't supported (only 1.x)"),
+ PaletteError::AcbVersion { version } => format!("color book version {version} isn't supported (only 1)"),
+ PaletteError::AcbEntryLimit { limit } => format!("the color book holds more than {ASE_MAX_ENTRIES} colors", ASE_MAX_ENTRIES = limit),
+ PaletteError::AcbColorSpace { space: other } => format!("color books in color space {other} aren't supported (only RGB, CMYK and Lab)"),
+ PaletteError::AcbNameBytes { limit } => format!("the color book's names take more than {} MB", limit >> 20),
+ }
+}
/// Write `lib` in `format` → the file's bytes. Pattern swatches (their tiles live in a document)
/// and None are left out; `.gpl` keeps solid colours only, as 8-bit RGB, and `.ase` keeps solid
@@ -113,8 +190,12 @@ pub fn write(lib: &SwatchLibrary, format: PaletteFormat) -> Result, Stri
let file = NativeFile { format: NATIVE_FORMAT.into(), version: 1, library };
serde_json::to_string_pretty(&file).unwrap_or_default()
}
- PaletteFormat::Gpl => write_gpl(lib),
- PaletteFormat::Ase => return write_ase(lib),
+ PaletteFormat::Gpl => {
+ return cms_palette::write_palette_typed(&to_cms_palette(lib, true), cms_palette::PaletteFormat::Gpl).map_err(palette_error);
+ }
+ PaletteFormat::Ase => {
+ return cms_palette::write_palette_typed(&to_cms_palette(lib, false), cms_palette::PaletteFormat::Ase).map_err(palette_error);
+ }
PaletteFormat::Css => write_css(lib, keep),
};
Ok(text.into_bytes())
@@ -125,49 +206,6 @@ fn one_line(s: &str) -> String {
s.split(['\n', '\r', '\t']).collect::>().join(" ").trim().to_string()
}
-fn write_gpl(lib: &SwatchLibrary) -> String {
- let mut out = format!("{GPL_HEADER}\nName: {}\nColumns: 0\n#\n", one_line(&lib.name));
- let colors = |out: &mut String, list: &[Swatch]| {
- for w in list {
- if let Some(c) = w.paint.color() {
- let [r, g, b, _] = c.to_rgba8(1.0);
- out.push_str(&format!("{r:3} {g:3} {b:3}\t{}\n", one_line(&w.name)));
- }
- }
- };
- colors(&mut out, &lib.swatches);
- for g in &lib.groups {
- out.push_str(&format!("{GPL_GROUP} {}\n", one_line(&g.name)));
- colors(&mut out, &g.swatches);
- }
- out
-}
-
-/// `name` as a CSS custom property (`--` and an escaped identifier): lower case, spaces as
-/// hyphens, other characters an identifier can't hold escaped with a backslash.
-pub fn css_property(name: &str) -> String {
- let mut out = String::from("--");
- for word in name.split_whitespace() {
- if out.len() > 2 {
- out.push('-');
- }
- for ch in word.chars().flat_map(char::to_lowercase) {
- if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' || !ch.is_ascii() {
- out.push(ch);
- } else if ch.is_ascii_graphic() {
- out.push('\\');
- out.push(ch);
- } else {
- out.push_str(&format!("\\{:x} ", ch as u32));
- }
- }
- }
- if out.len() == 2 {
- out.push_str("swatch");
- }
- out
-}
-
/// A colour as CSS (`#rrggbb`, or `#rrggbbaa` below full opacity).
fn css_color(c: &Color, opacity: f32) -> String {
let [r, g, b, a] = c.to_rgba8(opacity);
@@ -265,108 +303,12 @@ fn write_css(lib: &SwatchLibrary, keep: impl Fn(&&Swatch) -> bool) -> String {
out
}
-/// `.ase`, as [`read_ase`] reads it: version 1.0, the ungrouped colors, then each color group as a
-/// group start (its name), its colors and a group end, also for a group without colors. A color is
-/// written in its own model: RGB, CMYK and gray components from 0 to 1 (gray as a level, 1 is
-/// white), Lab lightness as a fraction of 100 and a and b from −128 to 127. Components are clamped
-/// to those ranges, and a component that isn't a finite number is written as 0. The color type is
-/// 1 for a spot color, 0 for another global color and 2 for a process color.
-///
-/// A swatch exchange file holds solid colors only: gradients, patterns and None are left out, and
-/// a tint swatch is written as the color it shows, a process color without its link to its base.
-/// The file has no library name ([`read_ase`] names a library after its file). More than
-/// [`ASE_MAX_ENTRIES`] colors and groups is an error.
-fn write_ase(lib: &SwatchLibrary) -> Result, String> {
- let solid = |list: &[Swatch]| list.iter().filter(|w| w.paint.color().is_some()).count();
- let entries = solid(&lib.swatches) + lib.groups.iter().map(|g| 1 + solid(&g.swatches)).sum::();
- if entries > ASE_MAX_ENTRIES {
- return Err(format!(
- "VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries}"
- ));
- }
- let mut body = vec![];
- let mut blocks = put_ase_colors(&mut body, &lib.swatches)?;
- for g in &lib.groups {
- let mut name = vec![];
- put_ase_name(&mut name, &g.name)?;
- put_ase_block(&mut body, ASE_GROUP_START, &name)?;
- blocks += 2 + put_ase_colors(&mut body, &g.swatches)?;
- put_ase_block(&mut body, ASE_GROUP_END, &[])?;
- }
- let blocks = u32::try_from(blocks).map_err(|_| "too many swatch exchange blocks".to_string())?;
- let mut out = ASE_SIGNATURE.to_vec();
- out.extend(1u16.to_be_bytes());
- out.extend(0u16.to_be_bytes());
- out.extend(blocks.to_be_bytes());
- out.extend(body);
- Ok(out)
-}
-
-/// The color blocks of the solid colors in `list` → how many were written.
-fn put_ase_colors(out: &mut Vec, list: &[Swatch]) -> Result {
- let unit = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
- let ab = |v: f32| if v.is_finite() { v.clamp(-128.0, 127.0) } else { 0.0 };
- let mut n = 0;
- for (w, color) in list.iter().filter_map(|w| Some((w, w.paint.color()?))) {
- let mut body = vec![];
- put_ase_name(&mut body, &w.name)?;
- let (model, values): (&[u8; 4], Vec) = match color {
- Color::Rgb { r, g, b } => (b"RGB ", vec![unit(r), unit(g), unit(b)]),
- Color::Cmyk { c, m, y, k } => (b"CMYK", vec![unit(c), unit(m), unit(y), unit(k)]),
- Color::Lab { l, a, b } => (b"LAB ", vec![unit(l / 100.0), ab(a), ab(b)]),
- Color::Gray { k } => (b"Gray", vec![1.0 - unit(k)]),
- };
- body.extend(model);
- body.extend(values.iter().flat_map(|v| v.to_be_bytes()));
- let kind: u16 = if w.spot {
- 1
- } else if w.global {
- 0
- } else {
- 2
- };
- body.extend(kind.to_be_bytes());
- put_ase_block(out, ASE_COLOR, &body)?;
- n += 1;
- }
- Ok(n)
-}
-
-/// A block: its type, the length of its body and the body.
-fn put_ase_block(out: &mut Vec, kind: u16, body: &[u8]) -> Result<(), String> {
- let len = u32::try_from(body.len()).map_err(|_| "a swatch exchange block is too long".to_string())?;
- out.extend(kind.to_be_bytes());
- out.extend(len.to_be_bytes());
- out.extend_from_slice(body);
- Ok(())
-}
-
-/// A name as `.ase` stores it: a `u16` count of UTF-16 code units, the terminating zero included,
-/// then the units. NUL characters are left out, and a name longer than [`ASE_MAX_NAME`] code units
-/// is cut before the character that would pass that limit.
-fn put_ase_name(out: &mut Vec, name: &str) -> Result<(), String> {
- let mut units: Vec = vec![];
- for c in name.chars().filter(|&c| c != '\0') {
- let mut buf = [0; 2];
- let encoded = c.encode_utf16(&mut buf);
- if units.len() + encoded.len() > ASE_MAX_NAME {
- break;
- }
- units.extend_from_slice(encoded);
- }
- units.push(0);
- let count = u16::try_from(units.len()).map_err(|_| "a swatch exchange name is too long".to_string())?;
- out.extend(count.to_be_bytes());
- out.extend(units.iter().flat_map(|u| u.to_be_bytes()));
- Ok(())
-}
-
/// Read a `.vcswatches` or `.gpl` library (detected from its content). `name` names it when the
/// file doesn't.
pub fn read(text: &str, name: &str) -> Result {
let text = text.trim_start_matches('\u{feff}').trim_start();
if text.starts_with(GPL_HEADER) {
- return Ok(read_gpl(text, name));
+ return cms_palette::read_palette_typed(text.as_bytes(), name).map(from_cms_palette).map_err(palette_error);
}
if text.starts_with('{') {
let f: NativeFile = serde_json::from_str(text).map_err(|e| format!("not a swatch library: {e}"))?;
@@ -391,11 +333,8 @@ pub fn sniff(text: &str) -> bool {
/// Read the bytes of a library file: a swatch exchange `.ase` file, else a `.vcswatches` or
/// `.gpl` library ([`read`]). `name` names it when the file doesn't.
pub fn read_bytes(bytes: &[u8], name: &str) -> Result {
- if bytes.starts_with(ASE_SIGNATURE) {
- return read_ase(bytes, name);
- }
- if bytes.starts_with(ACB_SIGNATURE) {
- return read_acb(bytes, name).map_err(|e| if e == ASE_CUT_SHORT { ACB_CUT_SHORT.into() } else { e });
+ if bytes.starts_with(ASE_SIGNATURE) || bytes.starts_with(ACB_SIGNATURE) {
+ return cms_palette::read_palette_typed(bytes, name).map(from_cms_palette).map_err(palette_error);
}
read(&String::from_utf8_lossy(bytes), name)
}
@@ -409,303 +348,5 @@ pub fn sniff_bytes(bytes: &[u8]) -> bool {
|| sniff(&String::from_utf8_lossy(bytes.get(..1024).unwrap_or(bytes)))
}
-/// `.gpl`: `Name:` names the library, `# Group: name` starts a colour group, other `#` lines and
-/// headers (`Columns:`) are skipped, as are lines that aren't `r g b [name]`. Unnamed colors are
-/// named by their values and unnamed groups "Color Group"; a name a color or group already has gets
-/// a number ([`UniqueNames`]).
-fn read_gpl(text: &str, fallback: &str) -> SwatchLibrary {
- let mut lib = SwatchLibrary { name: fallback.into(), ..Default::default() };
- let mut names = UniqueNames::default();
- for line in text.lines().skip(1) {
- let line = line.trim();
- if let Some(g) = line.strip_prefix(GPL_GROUP) {
- lib.groups.push(SwatchGroup { name: names.unique(group_name(g)), swatches: vec![] });
- continue;
- }
- if let Some(n) = line.strip_prefix("Name:") {
- if !n.trim().is_empty() {
- lib.name = n.trim().to_string();
- }
- continue;
- }
- // Comments, headers (`Columns: 4`) and anything else that isn't a colour are skipped.
- let words: Vec<&str> = line.split_whitespace().collect();
- let rgb: Vec = words.iter().take(3).map_while(|v| v.parse().ok()).collect();
- let [r, g, b] = rgb[..] else { continue };
- let rest = words[3..].join(" ");
- let base = if rest.is_empty() { format!("R={r} G={g} B={b}") } else { rest };
- let w = Swatch { name: names.unique(base), paint: Paint::solid(Color::rgb8(r, g, b)), global: false, spot: false };
- match lib.groups.last_mut() {
- Some(grp) => grp.swatches.push(w),
- None => lib.swatches.push(w),
- }
- }
- lib
-}
-
-/// `.ase`, from public descriptions of the format: the layout from
-/// , the component ranges from
-/// . After the signature come, big-endian, a `u16` major (1) and
-/// minor version, a `u32` block count and the blocks, each a `u16` type, a `u32` body length and
-/// the body. A group start's body is a name. A color's body is a name, a four-character model
-/// (`RGB `, `CMYK`, `LAB `, `Gray`), its components as `f32` (3, 4, 3 and 1 of them) and a `u16`
-/// color type (0 global, 1 spot, 2 process). RGB, CMYK and gray components run from 0 to 1 (a
-/// gray level of 1 is white), Lab lightness from 0 to 1 and a and b from −128 to 127. A lightness
-/// above 1 is read as L* itself. A name is a `u16` count of UTF-16 code units, the terminating zero
-/// included, then the units.
-///
-/// Color groups become groups: a group start inside an open group ends that group, and a group
-/// left open ends with the file. Blocks of other types and colors in other models are skipped.
-/// Unnamed colors are named by their values and unnamed groups "Color Group"; a name a color or
-/// group already has gets a number ([`UniqueNames`]). A truncated file, a major version other than
-/// 1 or more than [`ASE_MAX_ENTRIES`] colors and groups is an error.
-fn read_ase(bytes: &[u8], fallback: &str) -> Result {
- let mut data = AseData(bytes);
- data.bytes(ASE_SIGNATURE.len())?;
- let (major, minor) = (data.u16()?, data.u16()?);
- if major != 1 {
- return Err(format!("swatch exchange version {major}.{minor} isn't supported (only 1.x)"));
- }
- let blocks = data.u32()?;
- let mut lib = SwatchLibrary { name: fallback.into(), ..Default::default() };
- let mut names = UniqueNames::default();
- let (mut in_group, mut entries) = (false, 0usize);
- for _ in 0..blocks {
- let kind = data.u16()?;
- let len = usize::try_from(data.u32()?).unwrap_or(usize::MAX);
- let mut body = AseData(data.bytes(len)?);
- if matches!(kind, ASE_GROUP_START | ASE_COLOR) {
- entries += 1;
- if entries > ASE_MAX_ENTRIES {
- return Err(format!("the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups"));
- }
- }
- match kind {
- ASE_GROUP_START => {
- lib.groups.push(SwatchGroup { name: names.unique(group_name(&body.name()?)), swatches: vec![] });
- in_group = true;
- }
- ASE_GROUP_END => in_group = false,
- ASE_COLOR => {
- let Some(mut w) = ase_swatch(&mut body)? else { continue };
- w.name = names.unique(std::mem::take(&mut w.name));
- match lib.groups.last_mut().filter(|_| in_group) {
- Some(g) => g.swatches.push(w),
- None => lib.swatches.push(w),
- }
- }
- // Other blocks are skipped.
- _ => {}
- }
- }
- Ok(lib)
-}
-
-/// `.acb` (a color book, read only), from public descriptions of the format: after the signature
-/// come, big-endian, a `u16` version (1) and book id, the title, prefix, suffix and description
-/// as strings, a `u16` color count, page size and page selector offset, a `u16` color space (0
-/// RGB, 2 CMYK, 7 Lab) and the colors: each a name, a six-character catalog code and its
-/// components as bytes. RGB runs from 0 to 255, CMYK ink is stored inverted (255 is no ink), Lab
-/// lightness is 0 to 255 for 0 to 100 and a and b are offset by 128. A string is a `u32` count of
-/// UTF-16 code units, then the units; a `$$$/key=Text` string means `Text`, and `^R`, `^C` stand
-/// for ® and ©. An optional `spflspot` or `spflproc` at the end says whether the colors are spot
-/// or process colors (a book without it is a spot color book).
-///
-/// The book's colors are named with its prefix and suffix ("PANTONE 185 C"); colors without a
-/// name (the padding of a book's pages) are left out. A version other than 1, a color space other
-/// than those three or more than [`ASE_MAX_ENTRIES`] colors is an error.
-fn read_acb(bytes: &[u8], fallback: &str) -> Result {
- let mut data = AseData(bytes);
- data.bytes(ACB_SIGNATURE.len())?;
- let version = data.u16()?;
- if version != 1 {
- return Err(format!("color book version {version} isn't supported (only 1)"));
- }
- let _book_id = data.u16()?;
- let [title, prefix, suffix, _description] = [data.acb_string()?, data.acb_string()?, data.acb_string()?, data.acb_string()?];
- let count = usize::from(data.u16()?);
- if count > ASE_MAX_ENTRIES {
- return Err(format!("the color book holds more than {ASE_MAX_ENTRIES} colors"));
- }
- let (_page_size, _page_offset) = (data.u16()?, data.u16()?);
- let space = data.u16()?;
- let mut colors = Vec::with_capacity(count);
- for _ in 0..count {
- let name = data.acb_string()?;
- let _code = data.bytes(6)?;
- let color = match space {
- 0 => {
- let [r, g, b] = data.array::<3>()?;
- Color::rgb8(r, g, b)
- }
- 2 => {
- let ink = |v: u8| f32::from(255 - v) / 255.0;
- let [c, m, y, k] = data.array::<4>()?;
- Color::cmyk(ink(c), ink(m), ink(y), ink(k))
- }
- 7 => {
- let [l, a, b] = data.array::<3>()?;
- Color::lab(f32::from(l) * 100.0 / 255.0, f32::from(a) - 128.0, f32::from(b) - 128.0)
- }
- other => return Err(format!("color books in color space {other} aren't supported (only RGB, CMYK and Lab)")),
- };
- colors.push((name, color));
- }
- // Spot colors unless the book says process ones.
- let spot = data.0.windows(8).last() != Some(b"spflproc".as_slice());
- let mut lib = SwatchLibrary { name: if title.is_empty() { fallback.into() } else { title }, ..Default::default() };
- let mut names = UniqueNames::default();
- // Every name gets the prefix and the suffix, and is kept twice (the swatch's and the set of
- // names taken): a megabyte book of long affixes and many colors came to hundreds of MB.
- let mut kept = 0usize;
- for (name, color) in colors.into_iter().filter(|(n, _)| !n.trim().is_empty()) {
- kept = kept.saturating_add(2 * (prefix.len() + name.len() + suffix.len()));
- if kept > ACB_MAX_NAME_BYTES {
- return Err(format!("the color book's names take more than {} MB", ACB_MAX_NAME_BYTES >> 20));
- }
- let name = names.unique(format!("{prefix}{name}{suffix}").trim().to_string());
- lib.swatches.push(Swatch { name, paint: Paint::solid(color), global: spot, spot });
- }
- Ok(lib)
-}
-
-/// Most bytes a color book's full color names (with its prefix and suffix) may take, counted
-/// twice as they are kept twice.
-const ACB_MAX_NAME_BYTES: usize = 64 << 20;
-
-/// The swatch of an `.ase` color block, `None` for a model other than RGB, CMYK, Lab and Gray.
-/// Components are clamped to their ranges.
-fn ase_swatch(body: &mut AseData) -> Result