From d2bed0bdb81a9f94d46e14bce1e0fb4b99bab2a0 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 19:08:45 -0500 Subject: [PATCH 1/9] cutover: use craft_plotter::hpgl::write (#8626) --- Cargo.lock | 3 +- Cargo.toml | 2 +- crates/cad/src/hpgl/write.rs | 63 ++++++------------------------------ 3 files changed, 12 insertions(+), 56 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0d32cc52e4..d635613a96 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1204,8 +1204,9 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57#a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57" +source = "git+https://github.com/storytold/craft-libs?rev=e7873217287876f76a045550369c90a541693c33#e7873217287876f76a045550369c90a541693c33" dependencies = [ + "kurbo 0.13.1", "thiserror 2.0.21", ] diff --git a/Cargo.toml b/Cargo.toml index 6d2ab9e37b..184df0f647 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,7 +32,7 @@ craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "64b181977 # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "e7873217287876f76a045550369c90a541693c33" } craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } # WMF, EMF and EMF+ reader (craft-libs#778). craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } diff --git a/crates/cad/src/hpgl/write.rs b/crates/cad/src/hpgl/write.rs index bb397d7eaa..69f5e503a2 100644 --- a/crates/cad/src/hpgl/write.rs +++ b/crates/cad/src/hpgl/write.rs @@ -43,16 +43,13 @@ use clip::Region; /// Plotter units per point. const PLU_PER_PT: f64 = 1016.0 / 72.0; -/// The largest coordinate written, plotter units. -pub const MAX_COORD: i64 = (1 << 23) - 1; +pub use craft_plotter::hpgl::write::{MAX_COORD, MAX_PENS}; /// The coordinates an HP-GL plot keeps to without a warning: 16-bit numbers, plotter units. const CLASSIC_RANGE: std::ops::RangeInclusive = -32_768..=32_767; /// The curve tolerance a path is flattened to by default, points. pub const DEFAULT_TOLERANCE: f64 = 0.1; /// The smallest and largest curve tolerance, points. pub const TOLERANCE_RANGE: std::ops::RangeInclusive = 0.01..=10.0; -/// The most pens: a pen table's length, and the colors that get a pen of their own. -pub const MAX_PENS: usize = 255; /// The most points the plots of one export hold. const MAX_POINTS: usize = if cfg!(test) { 100_000 } else { 10_000_000 }; /// The most work sorting paths and finding which lie inside others may take, over the whole plot: @@ -295,7 +292,14 @@ pub fn export_regions(doc: &Document, opts: &HpglOptions, regions: &[Rect]) -> R } let bytes = match opts.version { Version::Hpgl => plain(&by_pen), - Version::Hpgl2 => encoded(&by_pen, &pens), + Version::Hpgl2 => { + let pen_table: Vec = pens + .iter() + .enumerate() + .map(|(i, &rgb)| craft_plotter::hpgl::write::Pen { number: i + 1, rgb }) + .collect(); + craft_plotter::hpgl::write::write_hpgl2(&pen_table, &by_pen).into_bytes() + } }; out.push(HpglOutput { bytes, pens: pens.clone(), warnings, setting_notes }); } @@ -523,56 +527,7 @@ fn plain(by_pen: &[Vec>]) -> Vec { } /// HP-GL/2: `IN;`, the palette, each pen's paths as one `PE`, `PU;SP0;`. -fn encoded(by_pen: &[Vec>], pens: &[[u8; 3]]) -> Vec { - let mut out = b"IN;".to_vec(); - if !pens.is_empty() { - // Pens 1 to n on a plotter, and on a raster device (whose pens are 0 to NP − 1) too. - let np = (pens.len() + 1).next_power_of_two().max(2); - out.extend(format!("NP{np};").bytes()); - for (i, [r, g, b]) in pens.iter().enumerate() { - out.extend(format!("PC{},{r},{g},{b};", i + 1).bytes()); - } - } - let mut at: Option<(i64, i64)> = None; - for (i, paths) in by_pen.iter().enumerate().filter(|(_, p)| !p.is_empty()) { - out.extend(format!("PU;SP{};PE", i + 1).bytes()); - for path in paths { - for (k, &p) in path.iter().enumerate() { - if k == 0 { - out.push(b'<'); - } - // The first move of the plot is absolute, and so is one longer than the range a - // device takes for each number; every other is relative. - match at.map(|a| (p.0 - a.0, p.1 - a.1)).filter(|d| d.0.abs() <= MAX_COORD && d.1.abs() <= MAX_COORD) { - None => { - out.push(b'='); - pe_number(&mut out, p.0); - pe_number(&mut out, p.1); - } - Some((dx, dy)) => { - pe_number(&mut out, dx); - pe_number(&mut out, dy); - } - } - at = Some(p); - } - } - out.push(b';'); - } - out.extend(b"PU;SP0;"); - out -} -/// `v` as a base-64 PE number: the sign in the low bit, the low digits from 63 up and the last -/// digit from 191 up. -fn pe_number(out: &mut Vec, v: i64) { - let mut n = (v.unsigned_abs() << 1) | u64::from(v < 0); - while n >= 64 { - out.push(63 + (n % 64) as u8); - n /= 64; - } - out.push(191 + n as u8); -} /// One line the pen draws, in document space, and its color. struct Run { From 0087be0452c90653cf73a076e26c65170b861f48 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 19:08:49 -0500 Subject: [PATCH 2/9] color: cut over palette_io GPL/ASE/ACB to craft-cms (#8627) --- Cargo.lock | 10 + Cargo.toml | 1 + crates/color/Cargo.toml | 1 + crates/color/src/palette_io.rs | 502 ++++----------------------------- 4 files changed, 64 insertions(+), 450 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d635613a96..6805f2c4ff 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1009,6 +1009,15 @@ dependencies = [ "ruzstd", ] +[[package]] +name = "craft-cms" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=e7873217287876f76a045550369c90a541693c33#e7873217287876f76a045550369c90a541693c33" +dependencies = [ + "md-5", + "rayon", +] + [[package]] name = "craft-codepage" version = "0.1.0" @@ -6728,6 +6737,7 @@ dependencies = [ name = "vectorcraft-color" version = "0.24.1" dependencies = [ + "craft-cms", "kurbo 0.13.1", "moxcms", "proptest", diff --git a/Cargo.toml b/Cargo.toml index 184df0f647..07e90b5795 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ rust-version = "1.95" repository = "https://github.com/storytold/vectorcraft" [workspace.dependencies] +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "e7873217287876f76a045550369c90a541693c33" } craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", default-features = false, features = ["interpret", "write"] } craft-print = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } diff --git a/crates/color/Cargo.toml b/crates/color/Cargo.toml index a007ede39f..1273b5d0ad 100644 --- a/crates/color/Cargo.toml +++ b/crates/color/Cargo.toml @@ -9,6 +9,7 @@ description = "VectorCraft color" workspace = true [dependencies] +craft-cms = { workspace = true } kurbo = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } diff --git a/crates/color/src/palette_io.rs b/crates/color/src/palette_io.rs index 9be00b4b21..cb8e0b3950 100644 --- a/crates/color/src/palette_io.rs +++ b/crates/color/src/palette_io.rs @@ -6,6 +6,8 @@ use std::collections::{HashMap, HashSet}; +pub use craft_cms::palette::css_property; +use craft_cms::palette::{self as cms_palette, Palette, PaletteColor, PaletteGroup, PaletteSwatch}; use serde::{Deserialize, Serialize}; use crate::{Color, GradientKind, Paint, Swatch, SwatchGroup, SwatchLibrary}; @@ -83,18 +85,50 @@ struct NativeFile { const NATIVE_FORMAT: &str = "vcswatches"; const GPL_HEADER: &str = "GIMP Palette"; -const GPL_GROUP: &str = "# Group:"; -const ASE_SIGNATURE: &[u8] = b"ASEF"; -const ASE_GROUP_START: u16 = 0xC001; -const ASE_GROUP_END: u16 = 0xC002; -const ASE_COLOR: u16 = 0x0001; -/// The most colors and groups read from one `.ase` file. -const ASE_MAX_ENTRIES: usize = 100_000; -/// The most UTF-16 code units of a name that are kept. -const ASE_MAX_NAME: usize = 1024; -const ASE_CUT_SHORT: &str = "the swatch exchange file is cut short"; -const ACB_SIGNATURE: &[u8] = b"8BCB"; -const ACB_CUT_SHORT: &str = "the color book is cut short"; + +fn color_to_cms(c: Color) -> PaletteColor { + match c { + Color::Rgb { r, g, b } => PaletteColor::Rgb { r, g, b }, + Color::Cmyk { c, m, y, k } => PaletteColor::Cmyk { c, m, y, k }, + Color::Lab { l, a, b } => PaletteColor::Lab { l, a, b }, + Color::Gray { k } => PaletteColor::Gray { k }, + } +} + +fn color_from_cms(c: PaletteColor) -> Color { + match c { + PaletteColor::Rgb { r, g, b } => Color::rgb(r, g, b), + PaletteColor::Cmyk { c, m, y, k } => Color::cmyk(c, m, y, k), + PaletteColor::Lab { l, a, b } => Color::lab(l, a, b), + PaletteColor::Gray { k } => Color::gray(k), + } +} + +fn swatches_to_cms(list: &[Swatch]) -> Vec { + list.iter() + .filter_map(|w| w.paint.color().map(|c| PaletteSwatch { name: w.name.clone(), color: color_to_cms(c), global: w.global, spot: w.spot })) + .collect() +} + +fn swatches_from_cms(list: Vec) -> Vec { + list.into_iter().map(|w| Swatch { name: w.name, paint: Paint::solid(color_from_cms(w.color)), global: w.global, spot: w.spot }).collect() +} + +fn to_cms_palette(lib: &SwatchLibrary) -> Palette { + Palette { + name: lib.name.clone(), + swatches: swatches_to_cms(&lib.swatches), + groups: lib.groups.iter().map(|g| PaletteGroup { name: g.name.clone(), swatches: swatches_to_cms(&g.swatches) }).collect(), + } +} + +fn from_cms_palette(p: Palette) -> SwatchLibrary { + SwatchLibrary { + name: p.name, + swatches: swatches_from_cms(p.swatches), + groups: p.groups.into_iter().map(|g| SwatchGroup { name: g.name, swatches: swatches_from_cms(g.swatches) }).collect(), + } +} /// Write `lib` in `format` → the file's bytes. Pattern swatches (their tiles live in a document) /// and None are left out; `.gpl` keeps solid colours only, as 8-bit RGB, and `.ase` keeps solid @@ -113,8 +147,8 @@ pub fn write(lib: &SwatchLibrary, format: PaletteFormat) -> Result, Stri let file = NativeFile { format: NATIVE_FORMAT.into(), version: 1, library }; serde_json::to_string_pretty(&file).unwrap_or_default() } - PaletteFormat::Gpl => write_gpl(lib), - PaletteFormat::Ase => return write_ase(lib), + PaletteFormat::Gpl => return cms_palette::write_palette(&to_cms_palette(lib), cms_palette::PaletteFormat::Gpl), + PaletteFormat::Ase => return cms_palette::write_palette(&to_cms_palette(lib), cms_palette::PaletteFormat::Ase), PaletteFormat::Css => write_css(lib, keep), }; Ok(text.into_bytes()) @@ -125,49 +159,6 @@ fn one_line(s: &str) -> String { s.split(['\n', '\r', '\t']).collect::>().join(" ").trim().to_string() } -fn write_gpl(lib: &SwatchLibrary) -> String { - let mut out = format!("{GPL_HEADER}\nName: {}\nColumns: 0\n#\n", one_line(&lib.name)); - let colors = |out: &mut String, list: &[Swatch]| { - for w in list { - if let Some(c) = w.paint.color() { - let [r, g, b, _] = c.to_rgba8(1.0); - out.push_str(&format!("{r:3} {g:3} {b:3}\t{}\n", one_line(&w.name))); - } - } - }; - colors(&mut out, &lib.swatches); - for g in &lib.groups { - out.push_str(&format!("{GPL_GROUP} {}\n", one_line(&g.name))); - colors(&mut out, &g.swatches); - } - out -} - -/// `name` as a CSS custom property (`--` and an escaped identifier): lower case, spaces as -/// hyphens, other characters an identifier can't hold escaped with a backslash. -pub fn css_property(name: &str) -> String { - let mut out = String::from("--"); - for word in name.split_whitespace() { - if out.len() > 2 { - out.push('-'); - } - for ch in word.chars().flat_map(char::to_lowercase) { - if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' || !ch.is_ascii() { - out.push(ch); - } else if ch.is_ascii_graphic() { - out.push('\\'); - out.push(ch); - } else { - out.push_str(&format!("\\{:x} ", ch as u32)); - } - } - } - if out.len() == 2 { - out.push_str("swatch"); - } - out -} - /// A colour as CSS (`#rrggbb`, or `#rrggbbaa` below full opacity). fn css_color(c: &Color, opacity: f32) -> String { let [r, g, b, a] = c.to_rgba8(opacity); @@ -276,97 +267,10 @@ fn write_css(lib: &SwatchLibrary, keep: impl Fn(&&Swatch) -> bool) -> String { /// a tint swatch is written as the color it shows, a process color without its link to its base. /// The file has no library name ([`read_ase`] names a library after its file). More than /// [`ASE_MAX_ENTRIES`] colors and groups is an error. -fn write_ase(lib: &SwatchLibrary) -> Result, String> { - let solid = |list: &[Swatch]| list.iter().filter(|w| w.paint.color().is_some()).count(); - let entries = solid(&lib.swatches) + lib.groups.iter().map(|g| 1 + solid(&g.swatches)).sum::(); - if entries > ASE_MAX_ENTRIES { - return Err(format!( - "VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries}" - )); - } - let mut body = vec![]; - let mut blocks = put_ase_colors(&mut body, &lib.swatches)?; - for g in &lib.groups { - let mut name = vec![]; - put_ase_name(&mut name, &g.name)?; - put_ase_block(&mut body, ASE_GROUP_START, &name)?; - blocks += 2 + put_ase_colors(&mut body, &g.swatches)?; - put_ase_block(&mut body, ASE_GROUP_END, &[])?; - } - let blocks = u32::try_from(blocks).map_err(|_| "too many swatch exchange blocks".to_string())?; - let mut out = ASE_SIGNATURE.to_vec(); - out.extend(1u16.to_be_bytes()); - out.extend(0u16.to_be_bytes()); - out.extend(blocks.to_be_bytes()); - out.extend(body); - Ok(out) -} - -/// The color blocks of the solid colors in `list` → how many were written. -fn put_ase_colors(out: &mut Vec, list: &[Swatch]) -> Result { - let unit = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; - let ab = |v: f32| if v.is_finite() { v.clamp(-128.0, 127.0) } else { 0.0 }; - let mut n = 0; - for (w, color) in list.iter().filter_map(|w| Some((w, w.paint.color()?))) { - let mut body = vec![]; - put_ase_name(&mut body, &w.name)?; - let (model, values): (&[u8; 4], Vec) = match color { - Color::Rgb { r, g, b } => (b"RGB ", vec![unit(r), unit(g), unit(b)]), - Color::Cmyk { c, m, y, k } => (b"CMYK", vec![unit(c), unit(m), unit(y), unit(k)]), - Color::Lab { l, a, b } => (b"LAB ", vec![unit(l / 100.0), ab(a), ab(b)]), - Color::Gray { k } => (b"Gray", vec![1.0 - unit(k)]), - }; - body.extend(model); - body.extend(values.iter().flat_map(|v| v.to_be_bytes())); - let kind: u16 = if w.spot { - 1 - } else if w.global { - 0 - } else { - 2 - }; - body.extend(kind.to_be_bytes()); - put_ase_block(out, ASE_COLOR, &body)?; - n += 1; - } - Ok(n) -} - -/// A block: its type, the length of its body and the body. -fn put_ase_block(out: &mut Vec, kind: u16, body: &[u8]) -> Result<(), String> { - let len = u32::try_from(body.len()).map_err(|_| "a swatch exchange block is too long".to_string())?; - out.extend(kind.to_be_bytes()); - out.extend(len.to_be_bytes()); - out.extend_from_slice(body); - Ok(()) -} - -/// A name as `.ase` stores it: a `u16` count of UTF-16 code units, the terminating zero included, -/// then the units. NUL characters are left out, and a name longer than [`ASE_MAX_NAME`] code units -/// is cut before the character that would pass that limit. -fn put_ase_name(out: &mut Vec, name: &str) -> Result<(), String> { - let mut units: Vec = vec![]; - for c in name.chars().filter(|&c| c != '\0') { - let mut buf = [0; 2]; - let encoded = c.encode_utf16(&mut buf); - if units.len() + encoded.len() > ASE_MAX_NAME { - break; - } - units.extend_from_slice(encoded); - } - units.push(0); - let count = u16::try_from(units.len()).map_err(|_| "a swatch exchange name is too long".to_string())?; - out.extend(count.to_be_bytes()); - out.extend(units.iter().flat_map(|u| u.to_be_bytes())); - Ok(()) -} - -/// Read a `.vcswatches` or `.gpl` library (detected from its content). `name` names it when the -/// file doesn't. pub fn read(text: &str, name: &str) -> Result { let text = text.trim_start_matches('\u{feff}').trim_start(); if text.starts_with(GPL_HEADER) { - return Ok(read_gpl(text, name)); + return cms_palette::read_palette(text.as_bytes(), name).map(from_cms_palette); } if text.starts_with('{') { let f: NativeFile = serde_json::from_str(text).map_err(|e| format!("not a swatch library: {e}"))?; @@ -391,11 +295,8 @@ pub fn sniff(text: &str) -> bool { /// Read the bytes of a library file: a swatch exchange `.ase` file, else a `.vcswatches` or /// `.gpl` library ([`read`]). `name` names it when the file doesn't. pub fn read_bytes(bytes: &[u8], name: &str) -> Result { - if bytes.starts_with(ASE_SIGNATURE) { - return read_ase(bytes, name); - } - if bytes.starts_with(ACB_SIGNATURE) { - return read_acb(bytes, name).map_err(|e| if e == ASE_CUT_SHORT { ACB_CUT_SHORT.into() } else { e }); + if cms_palette::sniff_palette(bytes) { + return cms_palette::read_palette(bytes, name).map(from_cms_palette); } read(&String::from_utf8_lossy(bytes), name) } @@ -403,309 +304,10 @@ pub fn read_bytes(bytes: &[u8], name: &str) -> Result { /// Are `bytes` a library [`read_bytes`] understands? Text that isn't valid UTF-8 is checked as /// [`read_bytes`] reads it, with the invalid bytes replaced (its first KiB is enough). pub fn sniff_bytes(bytes: &[u8]) -> bool { - bytes.starts_with(ASE_SIGNATURE) - || bytes.starts_with(ACB_SIGNATURE) + cms_palette::sniff_palette(bytes) || std::str::from_utf8(bytes).is_ok_and(sniff) || sniff(&String::from_utf8_lossy(bytes.get(..1024).unwrap_or(bytes))) } -/// `.gpl`: `Name:` names the library, `# Group: name` starts a colour group, other `#` lines and -/// headers (`Columns:`) are skipped, as are lines that aren't `r g b [name]`. Unnamed colors are -/// named by their values and unnamed groups "Color Group"; a name a color or group already has gets -/// a number ([`UniqueNames`]). -fn read_gpl(text: &str, fallback: &str) -> SwatchLibrary { - let mut lib = SwatchLibrary { name: fallback.into(), ..Default::default() }; - let mut names = UniqueNames::default(); - for line in text.lines().skip(1) { - let line = line.trim(); - if let Some(g) = line.strip_prefix(GPL_GROUP) { - lib.groups.push(SwatchGroup { name: names.unique(group_name(g)), swatches: vec![] }); - continue; - } - if let Some(n) = line.strip_prefix("Name:") { - if !n.trim().is_empty() { - lib.name = n.trim().to_string(); - } - continue; - } - // Comments, headers (`Columns: 4`) and anything else that isn't a colour are skipped. - let words: Vec<&str> = line.split_whitespace().collect(); - let rgb: Vec = words.iter().take(3).map_while(|v| v.parse().ok()).collect(); - let [r, g, b] = rgb[..] else { continue }; - let rest = words[3..].join(" "); - let base = if rest.is_empty() { format!("R={r} G={g} B={b}") } else { rest }; - let w = Swatch { name: names.unique(base), paint: Paint::solid(Color::rgb8(r, g, b)), global: false, spot: false }; - match lib.groups.last_mut() { - Some(grp) => grp.swatches.push(w), - None => lib.swatches.push(w), - } - } - lib -} - -/// `.ase`, from public descriptions of the format: the layout from -/// , the component ranges from -/// . After the signature come, big-endian, a `u16` major (1) and -/// minor version, a `u32` block count and the blocks, each a `u16` type, a `u32` body length and -/// the body. A group start's body is a name. A color's body is a name, a four-character model -/// (`RGB `, `CMYK`, `LAB `, `Gray`), its components as `f32` (3, 4, 3 and 1 of them) and a `u16` -/// color type (0 global, 1 spot, 2 process). RGB, CMYK and gray components run from 0 to 1 (a -/// gray level of 1 is white), Lab lightness from 0 to 1 and a and b from −128 to 127. A lightness -/// above 1 is read as L* itself. A name is a `u16` count of UTF-16 code units, the terminating zero -/// included, then the units. -/// -/// Color groups become groups: a group start inside an open group ends that group, and a group -/// left open ends with the file. Blocks of other types and colors in other models are skipped. -/// Unnamed colors are named by their values and unnamed groups "Color Group"; a name a color or -/// group already has gets a number ([`UniqueNames`]). A truncated file, a major version other than -/// 1 or more than [`ASE_MAX_ENTRIES`] colors and groups is an error. -fn read_ase(bytes: &[u8], fallback: &str) -> Result { - let mut data = AseData(bytes); - data.bytes(ASE_SIGNATURE.len())?; - let (major, minor) = (data.u16()?, data.u16()?); - if major != 1 { - return Err(format!("swatch exchange version {major}.{minor} isn't supported (only 1.x)")); - } - let blocks = data.u32()?; - let mut lib = SwatchLibrary { name: fallback.into(), ..Default::default() }; - let mut names = UniqueNames::default(); - let (mut in_group, mut entries) = (false, 0usize); - for _ in 0..blocks { - let kind = data.u16()?; - let len = usize::try_from(data.u32()?).unwrap_or(usize::MAX); - let mut body = AseData(data.bytes(len)?); - if matches!(kind, ASE_GROUP_START | ASE_COLOR) { - entries += 1; - if entries > ASE_MAX_ENTRIES { - return Err(format!("the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups")); - } - } - match kind { - ASE_GROUP_START => { - lib.groups.push(SwatchGroup { name: names.unique(group_name(&body.name()?)), swatches: vec![] }); - in_group = true; - } - ASE_GROUP_END => in_group = false, - ASE_COLOR => { - let Some(mut w) = ase_swatch(&mut body)? else { continue }; - w.name = names.unique(std::mem::take(&mut w.name)); - match lib.groups.last_mut().filter(|_| in_group) { - Some(g) => g.swatches.push(w), - None => lib.swatches.push(w), - } - } - // Other blocks are skipped. - _ => {} - } - } - Ok(lib) -} - -/// `.acb` (a color book, read only), from public descriptions of the format: after the signature -/// come, big-endian, a `u16` version (1) and book id, the title, prefix, suffix and description -/// as strings, a `u16` color count, page size and page selector offset, a `u16` color space (0 -/// RGB, 2 CMYK, 7 Lab) and the colors: each a name, a six-character catalog code and its -/// components as bytes. RGB runs from 0 to 255, CMYK ink is stored inverted (255 is no ink), Lab -/// lightness is 0 to 255 for 0 to 100 and a and b are offset by 128. A string is a `u32` count of -/// UTF-16 code units, then the units; a `$$$/key=Text` string means `Text`, and `^R`, `^C` stand -/// for ® and ©. An optional `spflspot` or `spflproc` at the end says whether the colors are spot -/// or process colors (a book without it is a spot color book). -/// -/// The book's colors are named with its prefix and suffix ("PANTONE 185 C"); colors without a -/// name (the padding of a book's pages) are left out. A version other than 1, a color space other -/// than those three or more than [`ASE_MAX_ENTRIES`] colors is an error. -fn read_acb(bytes: &[u8], fallback: &str) -> Result { - let mut data = AseData(bytes); - data.bytes(ACB_SIGNATURE.len())?; - let version = data.u16()?; - if version != 1 { - return Err(format!("color book version {version} isn't supported (only 1)")); - } - let _book_id = data.u16()?; - let [title, prefix, suffix, _description] = [data.acb_string()?, data.acb_string()?, data.acb_string()?, data.acb_string()?]; - let count = usize::from(data.u16()?); - if count > ASE_MAX_ENTRIES { - return Err(format!("the color book holds more than {ASE_MAX_ENTRIES} colors")); - } - let (_page_size, _page_offset) = (data.u16()?, data.u16()?); - let space = data.u16()?; - let mut colors = Vec::with_capacity(count); - for _ in 0..count { - let name = data.acb_string()?; - let _code = data.bytes(6)?; - let color = match space { - 0 => { - let [r, g, b] = data.array::<3>()?; - Color::rgb8(r, g, b) - } - 2 => { - let ink = |v: u8| f32::from(255 - v) / 255.0; - let [c, m, y, k] = data.array::<4>()?; - Color::cmyk(ink(c), ink(m), ink(y), ink(k)) - } - 7 => { - let [l, a, b] = data.array::<3>()?; - Color::lab(f32::from(l) * 100.0 / 255.0, f32::from(a) - 128.0, f32::from(b) - 128.0) - } - other => return Err(format!("color books in color space {other} aren't supported (only RGB, CMYK and Lab)")), - }; - colors.push((name, color)); - } - // Spot colors unless the book says process ones. - let spot = data.0.windows(8).last() != Some(b"spflproc".as_slice()); - let mut lib = SwatchLibrary { name: if title.is_empty() { fallback.into() } else { title }, ..Default::default() }; - let mut names = UniqueNames::default(); - // Every name gets the prefix and the suffix, and is kept twice (the swatch's and the set of - // names taken): a megabyte book of long affixes and many colors came to hundreds of MB. - let mut kept = 0usize; - for (name, color) in colors.into_iter().filter(|(n, _)| !n.trim().is_empty()) { - kept = kept.saturating_add(2 * (prefix.len() + name.len() + suffix.len())); - if kept > ACB_MAX_NAME_BYTES { - return Err(format!("the color book's names take more than {} MB", ACB_MAX_NAME_BYTES >> 20)); - } - let name = names.unique(format!("{prefix}{name}{suffix}").trim().to_string()); - lib.swatches.push(Swatch { name, paint: Paint::solid(color), global: spot, spot }); - } - Ok(lib) -} - -/// Most bytes a color book's full color names (with its prefix and suffix) may take, counted -/// twice as they are kept twice. -const ACB_MAX_NAME_BYTES: usize = 64 << 20; - -/// The swatch of an `.ase` color block, `None` for a model other than RGB, CMYK, Lab and Gray. -/// Components are clamped to their ranges. -fn ase_swatch(body: &mut AseData) -> Result, String> { - let name = body.name()?; - let unit = |v: f32| v.clamp(0.0, 1.0); - let color = match &body.array::<4>()? { - b"RGB " => { - let [r, g, b] = [body.f32()?, body.f32()?, body.f32()?]; - Color::rgb(unit(r), unit(g), unit(b)) - } - b"CMYK" => { - let [c, m, y, k] = [body.f32()?, body.f32()?, body.f32()?, body.f32()?]; - Color::cmyk(unit(c), unit(m), unit(y), unit(k)) - } - // Lightness is stored as a fraction of 100. Some writers store L* itself, which shows as a - // value above 1. - b"LAB " => { - let [l, a, b] = [body.f32()?, body.f32()?, body.f32()?]; - let l = if l > 1.0 { l.min(100.0) } else { unit(l) * 100.0 }; - Color::lab(l, a.clamp(-128.0, 127.0), b.clamp(-128.0, 127.0)) - } - // A gray level (1 is white); a gray color holds its ink. - b"Gray" => Color::gray(1.0 - unit(body.f32()?)), - _ => return Ok(None), - }; - // Some writers leave the color type out, which makes a process color. - let kind = if body.0.len() >= 2 { body.u16()? } else { 2 }; - // Spot colors are global. - let (global, spot) = match kind { - 0 => (true, false), - 1 => (true, true), - _ => (false, false), - }; - let name = if name.is_empty() { value_name(color) } else { name }; - Ok(Some(Swatch { name, paint: Paint::solid(color), global, spot })) -} - -/// A color's values in its own model, as new swatches are named ("C=10 M=20 Y=30 K=0", -/// "R=255 G=128 B=0", "Gray K=40", "L=52 a=70 b=-30"). -fn value_name(c: Color) -> String { - let pct = |v: f32| (v * 100.0).round(); - let byte = |v: f32| (v * 255.0).round(); - match c { - Color::Cmyk { c, m, y, k } => format!("C={} M={} Y={} K={}", pct(c), pct(m), pct(y), pct(k)), - Color::Rgb { r, g, b } => format!("R={} G={} B={}", byte(r), byte(g), byte(b)), - Color::Gray { k } => format!("Gray K={}", pct(k)), - // `+ 0.0` turns a rounded -0 into 0. - Color::Lab { l, a, b } => format!("L={} a={} b={}", l.round() + 0.0, a.round() + 0.0, b.round() + 0.0), - } -} - -/// `.ase` data, read field by field; reading past its end is an error. -struct AseData<'a>(&'a [u8]); - -impl<'a> AseData<'a> { - fn bytes(&mut self, n: usize) -> Result<&'a [u8], String> { - let (head, rest) = self.0.split_at_checked(n).ok_or(ASE_CUT_SHORT)?; - self.0 = rest; - Ok(head) - } - fn array(&mut self) -> Result<[u8; N], String> { - let (head, rest) = self.0.split_first_chunk::().ok_or(ASE_CUT_SHORT)?; - self.0 = rest; - Ok(*head) - } - fn u16(&mut self) -> Result { - self.array().map(u16::from_be_bytes) - } - fn u32(&mut self) -> Result { - self.array().map(u32::from_be_bytes) - } - /// A component; one that isn't a finite number reads as 0. - fn f32(&mut self) -> Result { - let v = f32::from_be_bytes(self.array()?); - Ok(if v.is_finite() { v } else { 0.0 }) - } - /// A color book string ([`read_acb`]): a `u32` count of UTF-16 code units, then the units, - /// with `$$$/key=Text` read as `Text` and `^R`, `^C` as ®, ©; at most [`ASE_MAX_NAME`] units - /// are kept. - fn acb_string(&mut self) -> Result { - let n = usize::try_from(self.u32()?).unwrap_or(usize::MAX); - let (units, _) = self.bytes(n.checked_mul(2).ok_or(ASE_CUT_SHORT)?)?.as_chunks::<2>(); - let units: Vec = units.iter().take(ASE_MAX_NAME).map(|u| u16::from_be_bytes(*u)).take_while(|&u| u != 0).collect(); - let s = String::from_utf16_lossy(&units); - let s = match s.strip_prefix("$$$/") { - Some(key) => key.split_once('=').map_or("", |(_, text)| text).to_string(), - None => s, - }; - Ok(s.replace("^R", "®").replace("^C", "©")) - } - /// A name up to its terminating zero, trimmed. A block that ends before it has no name. - fn name(&mut self) -> Result { - if self.0.is_empty() { - return Ok(String::new()); - } - let n = usize::from(self.u16()?); - let (units, _) = self.bytes(n * 2)?.as_chunks::<2>(); - let units: Vec = units.iter().take(ASE_MAX_NAME).map(|u| u16::from_be_bytes(*u)).take_while(|&u| u != 0).collect(); - Ok(String::from_utf16_lossy(&units).trim().to_string()) - } -} - -/// A group's name as a file gives it, trimmed; "Color Group" when it has none. -fn group_name(name: &str) -> String { - let name = name.trim(); - if name.is_empty() { "Color Group".into() } else { name.to_string() } -} - -/// The swatch and group names a reader has handed out. Swatches and color groups share one set of -/// names, as in a document, and a name already taken gets the first free number ("Black 2"). -#[derive(Default)] -struct UniqueNames { - taken: HashSet, - /// The last number tried for each repeated name. - last: HashMap, -} - -impl UniqueNames { - fn unique(&mut self, base: String) -> String { - if self.taken.insert(base.clone()) { - return base; - } - // Each pass tries the next number, and only finitely many names are taken. - let n = self.last.entry(base.clone()).or_insert(1); - loop { - *n += 1; - let name = format!("{base} {n}"); - if self.taken.insert(name.clone()) { - return name; - } - } - } -} - #[cfg(test)] mod tests; From 693785fc709e8919771e6fe6b9bf94a0d2f2b887 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 19 Nov 2026 07:18:07 +0700 Subject: [PATCH 3/9] Revert "cutover: use craft_plotter::hpgl::write (#8626)" This reverts commit d2bed0bdb81a9f94d46e14bce1e0fb4b99bab2a0. --- Cargo.lock | 3 +- Cargo.toml | 2 +- crates/cad/src/hpgl/write.rs | 63 ++++++++++++++++++++++++++++++------ 3 files changed, 56 insertions(+), 12 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6805f2c4ff..e7a0ffe1c3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1213,9 +1213,8 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e7873217287876f76a045550369c90a541693c33#e7873217287876f76a045550369c90a541693c33" +source = "git+https://github.com/storytold/craft-libs?rev=a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57#a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57" dependencies = [ - "kurbo 0.13.1", "thiserror 2.0.21", ] diff --git a/Cargo.toml b/Cargo.toml index 07e90b5795..c33e3b1cfc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -33,7 +33,7 @@ craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "64b181977 # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "e7873217287876f76a045550369c90a541693c33" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57" } craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } # WMF, EMF and EMF+ reader (craft-libs#778). craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } diff --git a/crates/cad/src/hpgl/write.rs b/crates/cad/src/hpgl/write.rs index 69f5e503a2..bb397d7eaa 100644 --- a/crates/cad/src/hpgl/write.rs +++ b/crates/cad/src/hpgl/write.rs @@ -43,13 +43,16 @@ use clip::Region; /// Plotter units per point. const PLU_PER_PT: f64 = 1016.0 / 72.0; -pub use craft_plotter::hpgl::write::{MAX_COORD, MAX_PENS}; +/// The largest coordinate written, plotter units. +pub const MAX_COORD: i64 = (1 << 23) - 1; /// The coordinates an HP-GL plot keeps to without a warning: 16-bit numbers, plotter units. const CLASSIC_RANGE: std::ops::RangeInclusive = -32_768..=32_767; /// The curve tolerance a path is flattened to by default, points. pub const DEFAULT_TOLERANCE: f64 = 0.1; /// The smallest and largest curve tolerance, points. pub const TOLERANCE_RANGE: std::ops::RangeInclusive = 0.01..=10.0; +/// The most pens: a pen table's length, and the colors that get a pen of their own. +pub const MAX_PENS: usize = 255; /// The most points the plots of one export hold. const MAX_POINTS: usize = if cfg!(test) { 100_000 } else { 10_000_000 }; /// The most work sorting paths and finding which lie inside others may take, over the whole plot: @@ -292,14 +295,7 @@ pub fn export_regions(doc: &Document, opts: &HpglOptions, regions: &[Rect]) -> R } let bytes = match opts.version { Version::Hpgl => plain(&by_pen), - Version::Hpgl2 => { - let pen_table: Vec = pens - .iter() - .enumerate() - .map(|(i, &rgb)| craft_plotter::hpgl::write::Pen { number: i + 1, rgb }) - .collect(); - craft_plotter::hpgl::write::write_hpgl2(&pen_table, &by_pen).into_bytes() - } + Version::Hpgl2 => encoded(&by_pen, &pens), }; out.push(HpglOutput { bytes, pens: pens.clone(), warnings, setting_notes }); } @@ -527,7 +523,56 @@ fn plain(by_pen: &[Vec>]) -> Vec { } /// HP-GL/2: `IN;`, the palette, each pen's paths as one `PE`, `PU;SP0;`. +fn encoded(by_pen: &[Vec>], pens: &[[u8; 3]]) -> Vec { + let mut out = b"IN;".to_vec(); + if !pens.is_empty() { + // Pens 1 to n on a plotter, and on a raster device (whose pens are 0 to NP − 1) too. + let np = (pens.len() + 1).next_power_of_two().max(2); + out.extend(format!("NP{np};").bytes()); + for (i, [r, g, b]) in pens.iter().enumerate() { + out.extend(format!("PC{},{r},{g},{b};", i + 1).bytes()); + } + } + let mut at: Option<(i64, i64)> = None; + for (i, paths) in by_pen.iter().enumerate().filter(|(_, p)| !p.is_empty()) { + out.extend(format!("PU;SP{};PE", i + 1).bytes()); + for path in paths { + for (k, &p) in path.iter().enumerate() { + if k == 0 { + out.push(b'<'); + } + // The first move of the plot is absolute, and so is one longer than the range a + // device takes for each number; every other is relative. + match at.map(|a| (p.0 - a.0, p.1 - a.1)).filter(|d| d.0.abs() <= MAX_COORD && d.1.abs() <= MAX_COORD) { + None => { + out.push(b'='); + pe_number(&mut out, p.0); + pe_number(&mut out, p.1); + } + Some((dx, dy)) => { + pe_number(&mut out, dx); + pe_number(&mut out, dy); + } + } + at = Some(p); + } + } + out.push(b';'); + } + out.extend(b"PU;SP0;"); + out +} +/// `v` as a base-64 PE number: the sign in the low bit, the low digits from 63 up and the last +/// digit from 191 up. +fn pe_number(out: &mut Vec, v: i64) { + let mut n = (v.unsigned_abs() << 1) | u64::from(v < 0); + while n >= 64 { + out.push(63 + (n % 64) as u8); + n /= 64; + } + out.push(191 + n as u8); +} /// One line the pen draws, in document space, and its color. struct Run { From 4e63316d9a93c893135c5cc0f08e96ddbc03eaf8 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 19 Nov 2026 07:15:52 +0700 Subject: [PATCH 4/9] color: the palette tests define the swatch exchange constants craft-cms keeps private --- crates/color/src/palette_io/tests.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/crates/color/src/palette_io/tests.rs b/crates/color/src/palette_io/tests.rs index bbbae16a53..0e6adb90ed 100644 --- a/crates/color/src/palette_io/tests.rs +++ b/crates/color/src/palette_io/tests.rs @@ -2,6 +2,13 @@ use super::*; use crate::{Gradient, GradientPaint, GradientStop}; use proptest::prelude::*; +// The swatch exchange file's signature, block types and entry cap, which craft-cms keeps private. +const ASE_SIGNATURE: &[u8] = b"ASEF"; +const ASE_GROUP_START: u16 = 0xC001; +const ASE_GROUP_END: u16 = 0xC002; +const ASE_COLOR: u16 = 0x0001; +const ASE_MAX_ENTRIES: usize = 100_000; + #[test] fn gpl_blank_name_keeps_fallback() { let blank = "GIMP Palette\nName: \nColumns: 0\n#\n 1 2 3\tx\n"; From 891dd6310dc01cfa1c506d4d8033e55725ddcba2 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 19 Nov 2026 07:59:02 +0700 Subject: [PATCH 5/9] color: an .ase library over the cap gets VectorCraft's own, translated message again #8627 left the check to craft-cms, whose wording isn't in the catalogs, and main's test of the message failed. --- crates/color/src/palette_io.rs | 16 +++++++++++++++- crates/color/src/palette_io/tests.rs | 3 +-- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/crates/color/src/palette_io.rs b/crates/color/src/palette_io.rs index cb8e0b3950..1709fb57c8 100644 --- a/crates/color/src/palette_io.rs +++ b/crates/color/src/palette_io.rs @@ -114,6 +114,10 @@ fn swatches_from_cms(list: Vec) -> Vec { list.into_iter().map(|w| Swatch { name: w.name, paint: Paint::solid(color_from_cms(w.color)), global: w.global, spot: w.spot }).collect() } +/// The most colors and groups one swatch exchange file holds, read or written (craft-cms reads +/// as many). +const ASE_MAX_ENTRIES: usize = 100_000; + fn to_cms_palette(lib: &SwatchLibrary) -> Palette { Palette { name: lib.name.clone(), @@ -148,7 +152,17 @@ pub fn write(lib: &SwatchLibrary, format: PaletteFormat) -> Result, Stri serde_json::to_string_pretty(&file).unwrap_or_default() } PaletteFormat::Gpl => return cms_palette::write_palette(&to_cms_palette(lib), cms_palette::PaletteFormat::Gpl), - PaletteFormat::Ase => return cms_palette::write_palette(&to_cms_palette(lib), cms_palette::PaletteFormat::Ase), + PaletteFormat::Ase => { + let p = to_cms_palette(lib); + // Counted here, so the message is VectorCraft's own and its translations apply. + let entries = p.swatches.len() + p.groups.iter().map(|g| 1 + g.swatches.len()).sum::(); + if entries > ASE_MAX_ENTRIES { + return Err(format!( + "VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries}" + )); + } + return cms_palette::write_palette(&p, cms_palette::PaletteFormat::Ase); + } PaletteFormat::Css => write_css(lib, keep), }; Ok(text.into_bytes()) diff --git a/crates/color/src/palette_io/tests.rs b/crates/color/src/palette_io/tests.rs index 0e6adb90ed..43f7ae79cc 100644 --- a/crates/color/src/palette_io/tests.rs +++ b/crates/color/src/palette_io/tests.rs @@ -2,12 +2,11 @@ use super::*; use crate::{Gradient, GradientPaint, GradientStop}; use proptest::prelude::*; -// The swatch exchange file's signature, block types and entry cap, which craft-cms keeps private. +// The swatch exchange file's signature and block types, which craft-cms keeps private. const ASE_SIGNATURE: &[u8] = b"ASEF"; const ASE_GROUP_START: u16 = 0xC001; const ASE_GROUP_END: u16 = 0xC002; const ASE_COLOR: u16 = 0x0001; -const ASE_MAX_ENTRIES: usize = 100_000; #[test] fn gpl_blank_name_keeps_fallback() { From 6d8674bde82401fd13351e306c1aa3106751973b Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 19 Nov 2026 08:21:29 +0700 Subject: [PATCH 6/9] Revert "Merge pull request #8635 from storytold/fix/ase-cap" This reverts commit fc2a525ee1c842a4eabbd9c822615c2147f78cac, reversing changes made to bab45a99f32a97be6668d89fea729ac962713c57. --- crates/color/src/palette_io.rs | 16 +--------------- crates/color/src/palette_io/tests.rs | 3 ++- 2 files changed, 3 insertions(+), 16 deletions(-) diff --git a/crates/color/src/palette_io.rs b/crates/color/src/palette_io.rs index 1709fb57c8..cb8e0b3950 100644 --- a/crates/color/src/palette_io.rs +++ b/crates/color/src/palette_io.rs @@ -114,10 +114,6 @@ fn swatches_from_cms(list: Vec) -> Vec { list.into_iter().map(|w| Swatch { name: w.name, paint: Paint::solid(color_from_cms(w.color)), global: w.global, spot: w.spot }).collect() } -/// The most colors and groups one swatch exchange file holds, read or written (craft-cms reads -/// as many). -const ASE_MAX_ENTRIES: usize = 100_000; - fn to_cms_palette(lib: &SwatchLibrary) -> Palette { Palette { name: lib.name.clone(), @@ -152,17 +148,7 @@ pub fn write(lib: &SwatchLibrary, format: PaletteFormat) -> Result, Stri serde_json::to_string_pretty(&file).unwrap_or_default() } PaletteFormat::Gpl => return cms_palette::write_palette(&to_cms_palette(lib), cms_palette::PaletteFormat::Gpl), - PaletteFormat::Ase => { - let p = to_cms_palette(lib); - // Counted here, so the message is VectorCraft's own and its translations apply. - let entries = p.swatches.len() + p.groups.iter().map(|g| 1 + g.swatches.len()).sum::(); - if entries > ASE_MAX_ENTRIES { - return Err(format!( - "VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries}" - )); - } - return cms_palette::write_palette(&p, cms_palette::PaletteFormat::Ase); - } + PaletteFormat::Ase => return cms_palette::write_palette(&to_cms_palette(lib), cms_palette::PaletteFormat::Ase), PaletteFormat::Css => write_css(lib, keep), }; Ok(text.into_bytes()) diff --git a/crates/color/src/palette_io/tests.rs b/crates/color/src/palette_io/tests.rs index 43f7ae79cc..0e6adb90ed 100644 --- a/crates/color/src/palette_io/tests.rs +++ b/crates/color/src/palette_io/tests.rs @@ -2,11 +2,12 @@ use super::*; use crate::{Gradient, GradientPaint, GradientStop}; use proptest::prelude::*; -// The swatch exchange file's signature and block types, which craft-cms keeps private. +// The swatch exchange file's signature, block types and entry cap, which craft-cms keeps private. const ASE_SIGNATURE: &[u8] = b"ASEF"; const ASE_GROUP_START: u16 = 0xC001; const ASE_GROUP_END: u16 = 0xC002; const ASE_COLOR: u16 = 0x0001; +const ASE_MAX_ENTRIES: usize = 100_000; #[test] fn gpl_blank_name_keeps_fallback() { From ed0fde6593c3dcd812a0e3eb3f08755ddc5d6a5c Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 19 Nov 2026 08:21:29 +0700 Subject: [PATCH 7/9] Revert "color: the palette tests define the swatch exchange constants craft-cms keeps private" This reverts commit 4e63316d9a93c893135c5cc0f08e96ddbc03eaf8. --- crates/color/src/palette_io/tests.rs | 7 ------- 1 file changed, 7 deletions(-) diff --git a/crates/color/src/palette_io/tests.rs b/crates/color/src/palette_io/tests.rs index 0e6adb90ed..bbbae16a53 100644 --- a/crates/color/src/palette_io/tests.rs +++ b/crates/color/src/palette_io/tests.rs @@ -2,13 +2,6 @@ use super::*; use crate::{Gradient, GradientPaint, GradientStop}; use proptest::prelude::*; -// The swatch exchange file's signature, block types and entry cap, which craft-cms keeps private. -const ASE_SIGNATURE: &[u8] = b"ASEF"; -const ASE_GROUP_START: u16 = 0xC001; -const ASE_GROUP_END: u16 = 0xC002; -const ASE_COLOR: u16 = 0x0001; -const ASE_MAX_ENTRIES: usize = 100_000; - #[test] fn gpl_blank_name_keeps_fallback() { let blank = "GIMP Palette\nName: \nColumns: 0\n#\n 1 2 3\tx\n"; From bd23b310ef1ee4f89c6b746e360908bc3f2bc83e Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 19 Nov 2026 08:21:30 +0700 Subject: [PATCH 8/9] Revert "color: cut over palette_io GPL/ASE/ACB to craft-cms (#8627)" This reverts commit 0087be0452c90653cf73a076e26c65170b861f48. --- Cargo.lock | 10 - Cargo.toml | 1 - crates/color/Cargo.toml | 1 - crates/color/src/palette_io.rs | 502 +++++++++++++++++++++++++++++---- 4 files changed, 450 insertions(+), 64 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e7a0ffe1c3..0d32cc52e4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1009,15 +1009,6 @@ dependencies = [ "ruzstd", ] -[[package]] -name = "craft-cms" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e7873217287876f76a045550369c90a541693c33#e7873217287876f76a045550369c90a541693c33" -dependencies = [ - "md-5", - "rayon", -] - [[package]] name = "craft-codepage" version = "0.1.0" @@ -6736,7 +6727,6 @@ dependencies = [ name = "vectorcraft-color" version = "0.24.1" dependencies = [ - "craft-cms", "kurbo 0.13.1", "moxcms", "proptest", diff --git a/Cargo.toml b/Cargo.toml index c33e3b1cfc..6d2ab9e37b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,7 +11,6 @@ rust-version = "1.95" repository = "https://github.com/storytold/vectorcraft" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "e7873217287876f76a045550369c90a541693c33" } craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", default-features = false, features = ["interpret", "write"] } craft-print = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } diff --git a/crates/color/Cargo.toml b/crates/color/Cargo.toml index 1273b5d0ad..a007ede39f 100644 --- a/crates/color/Cargo.toml +++ b/crates/color/Cargo.toml @@ -9,7 +9,6 @@ description = "VectorCraft color" workspace = true [dependencies] -craft-cms = { workspace = true } kurbo = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } diff --git a/crates/color/src/palette_io.rs b/crates/color/src/palette_io.rs index cb8e0b3950..9be00b4b21 100644 --- a/crates/color/src/palette_io.rs +++ b/crates/color/src/palette_io.rs @@ -6,8 +6,6 @@ use std::collections::{HashMap, HashSet}; -pub use craft_cms::palette::css_property; -use craft_cms::palette::{self as cms_palette, Palette, PaletteColor, PaletteGroup, PaletteSwatch}; use serde::{Deserialize, Serialize}; use crate::{Color, GradientKind, Paint, Swatch, SwatchGroup, SwatchLibrary}; @@ -85,50 +83,18 @@ struct NativeFile { const NATIVE_FORMAT: &str = "vcswatches"; const GPL_HEADER: &str = "GIMP Palette"; - -fn color_to_cms(c: Color) -> PaletteColor { - match c { - Color::Rgb { r, g, b } => PaletteColor::Rgb { r, g, b }, - Color::Cmyk { c, m, y, k } => PaletteColor::Cmyk { c, m, y, k }, - Color::Lab { l, a, b } => PaletteColor::Lab { l, a, b }, - Color::Gray { k } => PaletteColor::Gray { k }, - } -} - -fn color_from_cms(c: PaletteColor) -> Color { - match c { - PaletteColor::Rgb { r, g, b } => Color::rgb(r, g, b), - PaletteColor::Cmyk { c, m, y, k } => Color::cmyk(c, m, y, k), - PaletteColor::Lab { l, a, b } => Color::lab(l, a, b), - PaletteColor::Gray { k } => Color::gray(k), - } -} - -fn swatches_to_cms(list: &[Swatch]) -> Vec { - list.iter() - .filter_map(|w| w.paint.color().map(|c| PaletteSwatch { name: w.name.clone(), color: color_to_cms(c), global: w.global, spot: w.spot })) - .collect() -} - -fn swatches_from_cms(list: Vec) -> Vec { - list.into_iter().map(|w| Swatch { name: w.name, paint: Paint::solid(color_from_cms(w.color)), global: w.global, spot: w.spot }).collect() -} - -fn to_cms_palette(lib: &SwatchLibrary) -> Palette { - Palette { - name: lib.name.clone(), - swatches: swatches_to_cms(&lib.swatches), - groups: lib.groups.iter().map(|g| PaletteGroup { name: g.name.clone(), swatches: swatches_to_cms(&g.swatches) }).collect(), - } -} - -fn from_cms_palette(p: Palette) -> SwatchLibrary { - SwatchLibrary { - name: p.name, - swatches: swatches_from_cms(p.swatches), - groups: p.groups.into_iter().map(|g| SwatchGroup { name: g.name, swatches: swatches_from_cms(g.swatches) }).collect(), - } -} +const GPL_GROUP: &str = "# Group:"; +const ASE_SIGNATURE: &[u8] = b"ASEF"; +const ASE_GROUP_START: u16 = 0xC001; +const ASE_GROUP_END: u16 = 0xC002; +const ASE_COLOR: u16 = 0x0001; +/// The most colors and groups read from one `.ase` file. +const ASE_MAX_ENTRIES: usize = 100_000; +/// The most UTF-16 code units of a name that are kept. +const ASE_MAX_NAME: usize = 1024; +const ASE_CUT_SHORT: &str = "the swatch exchange file is cut short"; +const ACB_SIGNATURE: &[u8] = b"8BCB"; +const ACB_CUT_SHORT: &str = "the color book is cut short"; /// Write `lib` in `format` → the file's bytes. Pattern swatches (their tiles live in a document) /// and None are left out; `.gpl` keeps solid colours only, as 8-bit RGB, and `.ase` keeps solid @@ -147,8 +113,8 @@ pub fn write(lib: &SwatchLibrary, format: PaletteFormat) -> Result, Stri let file = NativeFile { format: NATIVE_FORMAT.into(), version: 1, library }; serde_json::to_string_pretty(&file).unwrap_or_default() } - PaletteFormat::Gpl => return cms_palette::write_palette(&to_cms_palette(lib), cms_palette::PaletteFormat::Gpl), - PaletteFormat::Ase => return cms_palette::write_palette(&to_cms_palette(lib), cms_palette::PaletteFormat::Ase), + PaletteFormat::Gpl => write_gpl(lib), + PaletteFormat::Ase => return write_ase(lib), PaletteFormat::Css => write_css(lib, keep), }; Ok(text.into_bytes()) @@ -159,6 +125,49 @@ fn one_line(s: &str) -> String { s.split(['\n', '\r', '\t']).collect::>().join(" ").trim().to_string() } +fn write_gpl(lib: &SwatchLibrary) -> String { + let mut out = format!("{GPL_HEADER}\nName: {}\nColumns: 0\n#\n", one_line(&lib.name)); + let colors = |out: &mut String, list: &[Swatch]| { + for w in list { + if let Some(c) = w.paint.color() { + let [r, g, b, _] = c.to_rgba8(1.0); + out.push_str(&format!("{r:3} {g:3} {b:3}\t{}\n", one_line(&w.name))); + } + } + }; + colors(&mut out, &lib.swatches); + for g in &lib.groups { + out.push_str(&format!("{GPL_GROUP} {}\n", one_line(&g.name))); + colors(&mut out, &g.swatches); + } + out +} + +/// `name` as a CSS custom property (`--` and an escaped identifier): lower case, spaces as +/// hyphens, other characters an identifier can't hold escaped with a backslash. +pub fn css_property(name: &str) -> String { + let mut out = String::from("--"); + for word in name.split_whitespace() { + if out.len() > 2 { + out.push('-'); + } + for ch in word.chars().flat_map(char::to_lowercase) { + if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' || !ch.is_ascii() { + out.push(ch); + } else if ch.is_ascii_graphic() { + out.push('\\'); + out.push(ch); + } else { + out.push_str(&format!("\\{:x} ", ch as u32)); + } + } + } + if out.len() == 2 { + out.push_str("swatch"); + } + out +} + /// A colour as CSS (`#rrggbb`, or `#rrggbbaa` below full opacity). fn css_color(c: &Color, opacity: f32) -> String { let [r, g, b, a] = c.to_rgba8(opacity); @@ -267,10 +276,97 @@ fn write_css(lib: &SwatchLibrary, keep: impl Fn(&&Swatch) -> bool) -> String { /// a tint swatch is written as the color it shows, a process color without its link to its base. /// The file has no library name ([`read_ase`] names a library after its file). More than /// [`ASE_MAX_ENTRIES`] colors and groups is an error. +fn write_ase(lib: &SwatchLibrary) -> Result, String> { + let solid = |list: &[Swatch]| list.iter().filter(|w| w.paint.color().is_some()).count(); + let entries = solid(&lib.swatches) + lib.groups.iter().map(|g| 1 + solid(&g.swatches)).sum::(); + if entries > ASE_MAX_ENTRIES { + return Err(format!( + "VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries}" + )); + } + let mut body = vec![]; + let mut blocks = put_ase_colors(&mut body, &lib.swatches)?; + for g in &lib.groups { + let mut name = vec![]; + put_ase_name(&mut name, &g.name)?; + put_ase_block(&mut body, ASE_GROUP_START, &name)?; + blocks += 2 + put_ase_colors(&mut body, &g.swatches)?; + put_ase_block(&mut body, ASE_GROUP_END, &[])?; + } + let blocks = u32::try_from(blocks).map_err(|_| "too many swatch exchange blocks".to_string())?; + let mut out = ASE_SIGNATURE.to_vec(); + out.extend(1u16.to_be_bytes()); + out.extend(0u16.to_be_bytes()); + out.extend(blocks.to_be_bytes()); + out.extend(body); + Ok(out) +} + +/// The color blocks of the solid colors in `list` → how many were written. +fn put_ase_colors(out: &mut Vec, list: &[Swatch]) -> Result { + let unit = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; + let ab = |v: f32| if v.is_finite() { v.clamp(-128.0, 127.0) } else { 0.0 }; + let mut n = 0; + for (w, color) in list.iter().filter_map(|w| Some((w, w.paint.color()?))) { + let mut body = vec![]; + put_ase_name(&mut body, &w.name)?; + let (model, values): (&[u8; 4], Vec) = match color { + Color::Rgb { r, g, b } => (b"RGB ", vec![unit(r), unit(g), unit(b)]), + Color::Cmyk { c, m, y, k } => (b"CMYK", vec![unit(c), unit(m), unit(y), unit(k)]), + Color::Lab { l, a, b } => (b"LAB ", vec![unit(l / 100.0), ab(a), ab(b)]), + Color::Gray { k } => (b"Gray", vec![1.0 - unit(k)]), + }; + body.extend(model); + body.extend(values.iter().flat_map(|v| v.to_be_bytes())); + let kind: u16 = if w.spot { + 1 + } else if w.global { + 0 + } else { + 2 + }; + body.extend(kind.to_be_bytes()); + put_ase_block(out, ASE_COLOR, &body)?; + n += 1; + } + Ok(n) +} + +/// A block: its type, the length of its body and the body. +fn put_ase_block(out: &mut Vec, kind: u16, body: &[u8]) -> Result<(), String> { + let len = u32::try_from(body.len()).map_err(|_| "a swatch exchange block is too long".to_string())?; + out.extend(kind.to_be_bytes()); + out.extend(len.to_be_bytes()); + out.extend_from_slice(body); + Ok(()) +} + +/// A name as `.ase` stores it: a `u16` count of UTF-16 code units, the terminating zero included, +/// then the units. NUL characters are left out, and a name longer than [`ASE_MAX_NAME`] code units +/// is cut before the character that would pass that limit. +fn put_ase_name(out: &mut Vec, name: &str) -> Result<(), String> { + let mut units: Vec = vec![]; + for c in name.chars().filter(|&c| c != '\0') { + let mut buf = [0; 2]; + let encoded = c.encode_utf16(&mut buf); + if units.len() + encoded.len() > ASE_MAX_NAME { + break; + } + units.extend_from_slice(encoded); + } + units.push(0); + let count = u16::try_from(units.len()).map_err(|_| "a swatch exchange name is too long".to_string())?; + out.extend(count.to_be_bytes()); + out.extend(units.iter().flat_map(|u| u.to_be_bytes())); + Ok(()) +} + +/// Read a `.vcswatches` or `.gpl` library (detected from its content). `name` names it when the +/// file doesn't. pub fn read(text: &str, name: &str) -> Result { let text = text.trim_start_matches('\u{feff}').trim_start(); if text.starts_with(GPL_HEADER) { - return cms_palette::read_palette(text.as_bytes(), name).map(from_cms_palette); + return Ok(read_gpl(text, name)); } if text.starts_with('{') { let f: NativeFile = serde_json::from_str(text).map_err(|e| format!("not a swatch library: {e}"))?; @@ -295,8 +391,11 @@ pub fn sniff(text: &str) -> bool { /// Read the bytes of a library file: a swatch exchange `.ase` file, else a `.vcswatches` or /// `.gpl` library ([`read`]). `name` names it when the file doesn't. pub fn read_bytes(bytes: &[u8], name: &str) -> Result { - if cms_palette::sniff_palette(bytes) { - return cms_palette::read_palette(bytes, name).map(from_cms_palette); + if bytes.starts_with(ASE_SIGNATURE) { + return read_ase(bytes, name); + } + if bytes.starts_with(ACB_SIGNATURE) { + return read_acb(bytes, name).map_err(|e| if e == ASE_CUT_SHORT { ACB_CUT_SHORT.into() } else { e }); } read(&String::from_utf8_lossy(bytes), name) } @@ -304,10 +403,309 @@ pub fn read_bytes(bytes: &[u8], name: &str) -> Result { /// Are `bytes` a library [`read_bytes`] understands? Text that isn't valid UTF-8 is checked as /// [`read_bytes`] reads it, with the invalid bytes replaced (its first KiB is enough). pub fn sniff_bytes(bytes: &[u8]) -> bool { - cms_palette::sniff_palette(bytes) + bytes.starts_with(ASE_SIGNATURE) + || bytes.starts_with(ACB_SIGNATURE) || std::str::from_utf8(bytes).is_ok_and(sniff) || sniff(&String::from_utf8_lossy(bytes.get(..1024).unwrap_or(bytes))) } +/// `.gpl`: `Name:` names the library, `# Group: name` starts a colour group, other `#` lines and +/// headers (`Columns:`) are skipped, as are lines that aren't `r g b [name]`. Unnamed colors are +/// named by their values and unnamed groups "Color Group"; a name a color or group already has gets +/// a number ([`UniqueNames`]). +fn read_gpl(text: &str, fallback: &str) -> SwatchLibrary { + let mut lib = SwatchLibrary { name: fallback.into(), ..Default::default() }; + let mut names = UniqueNames::default(); + for line in text.lines().skip(1) { + let line = line.trim(); + if let Some(g) = line.strip_prefix(GPL_GROUP) { + lib.groups.push(SwatchGroup { name: names.unique(group_name(g)), swatches: vec![] }); + continue; + } + if let Some(n) = line.strip_prefix("Name:") { + if !n.trim().is_empty() { + lib.name = n.trim().to_string(); + } + continue; + } + // Comments, headers (`Columns: 4`) and anything else that isn't a colour are skipped. + let words: Vec<&str> = line.split_whitespace().collect(); + let rgb: Vec = words.iter().take(3).map_while(|v| v.parse().ok()).collect(); + let [r, g, b] = rgb[..] else { continue }; + let rest = words[3..].join(" "); + let base = if rest.is_empty() { format!("R={r} G={g} B={b}") } else { rest }; + let w = Swatch { name: names.unique(base), paint: Paint::solid(Color::rgb8(r, g, b)), global: false, spot: false }; + match lib.groups.last_mut() { + Some(grp) => grp.swatches.push(w), + None => lib.swatches.push(w), + } + } + lib +} + +/// `.ase`, from public descriptions of the format: the layout from +/// , the component ranges from +/// . After the signature come, big-endian, a `u16` major (1) and +/// minor version, a `u32` block count and the blocks, each a `u16` type, a `u32` body length and +/// the body. A group start's body is a name. A color's body is a name, a four-character model +/// (`RGB `, `CMYK`, `LAB `, `Gray`), its components as `f32` (3, 4, 3 and 1 of them) and a `u16` +/// color type (0 global, 1 spot, 2 process). RGB, CMYK and gray components run from 0 to 1 (a +/// gray level of 1 is white), Lab lightness from 0 to 1 and a and b from −128 to 127. A lightness +/// above 1 is read as L* itself. A name is a `u16` count of UTF-16 code units, the terminating zero +/// included, then the units. +/// +/// Color groups become groups: a group start inside an open group ends that group, and a group +/// left open ends with the file. Blocks of other types and colors in other models are skipped. +/// Unnamed colors are named by their values and unnamed groups "Color Group"; a name a color or +/// group already has gets a number ([`UniqueNames`]). A truncated file, a major version other than +/// 1 or more than [`ASE_MAX_ENTRIES`] colors and groups is an error. +fn read_ase(bytes: &[u8], fallback: &str) -> Result { + let mut data = AseData(bytes); + data.bytes(ASE_SIGNATURE.len())?; + let (major, minor) = (data.u16()?, data.u16()?); + if major != 1 { + return Err(format!("swatch exchange version {major}.{minor} isn't supported (only 1.x)")); + } + let blocks = data.u32()?; + let mut lib = SwatchLibrary { name: fallback.into(), ..Default::default() }; + let mut names = UniqueNames::default(); + let (mut in_group, mut entries) = (false, 0usize); + for _ in 0..blocks { + let kind = data.u16()?; + let len = usize::try_from(data.u32()?).unwrap_or(usize::MAX); + let mut body = AseData(data.bytes(len)?); + if matches!(kind, ASE_GROUP_START | ASE_COLOR) { + entries += 1; + if entries > ASE_MAX_ENTRIES { + return Err(format!("the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups")); + } + } + match kind { + ASE_GROUP_START => { + lib.groups.push(SwatchGroup { name: names.unique(group_name(&body.name()?)), swatches: vec![] }); + in_group = true; + } + ASE_GROUP_END => in_group = false, + ASE_COLOR => { + let Some(mut w) = ase_swatch(&mut body)? else { continue }; + w.name = names.unique(std::mem::take(&mut w.name)); + match lib.groups.last_mut().filter(|_| in_group) { + Some(g) => g.swatches.push(w), + None => lib.swatches.push(w), + } + } + // Other blocks are skipped. + _ => {} + } + } + Ok(lib) +} + +/// `.acb` (a color book, read only), from public descriptions of the format: after the signature +/// come, big-endian, a `u16` version (1) and book id, the title, prefix, suffix and description +/// as strings, a `u16` color count, page size and page selector offset, a `u16` color space (0 +/// RGB, 2 CMYK, 7 Lab) and the colors: each a name, a six-character catalog code and its +/// components as bytes. RGB runs from 0 to 255, CMYK ink is stored inverted (255 is no ink), Lab +/// lightness is 0 to 255 for 0 to 100 and a and b are offset by 128. A string is a `u32` count of +/// UTF-16 code units, then the units; a `$$$/key=Text` string means `Text`, and `^R`, `^C` stand +/// for ® and ©. An optional `spflspot` or `spflproc` at the end says whether the colors are spot +/// or process colors (a book without it is a spot color book). +/// +/// The book's colors are named with its prefix and suffix ("PANTONE 185 C"); colors without a +/// name (the padding of a book's pages) are left out. A version other than 1, a color space other +/// than those three or more than [`ASE_MAX_ENTRIES`] colors is an error. +fn read_acb(bytes: &[u8], fallback: &str) -> Result { + let mut data = AseData(bytes); + data.bytes(ACB_SIGNATURE.len())?; + let version = data.u16()?; + if version != 1 { + return Err(format!("color book version {version} isn't supported (only 1)")); + } + let _book_id = data.u16()?; + let [title, prefix, suffix, _description] = [data.acb_string()?, data.acb_string()?, data.acb_string()?, data.acb_string()?]; + let count = usize::from(data.u16()?); + if count > ASE_MAX_ENTRIES { + return Err(format!("the color book holds more than {ASE_MAX_ENTRIES} colors")); + } + let (_page_size, _page_offset) = (data.u16()?, data.u16()?); + let space = data.u16()?; + let mut colors = Vec::with_capacity(count); + for _ in 0..count { + let name = data.acb_string()?; + let _code = data.bytes(6)?; + let color = match space { + 0 => { + let [r, g, b] = data.array::<3>()?; + Color::rgb8(r, g, b) + } + 2 => { + let ink = |v: u8| f32::from(255 - v) / 255.0; + let [c, m, y, k] = data.array::<4>()?; + Color::cmyk(ink(c), ink(m), ink(y), ink(k)) + } + 7 => { + let [l, a, b] = data.array::<3>()?; + Color::lab(f32::from(l) * 100.0 / 255.0, f32::from(a) - 128.0, f32::from(b) - 128.0) + } + other => return Err(format!("color books in color space {other} aren't supported (only RGB, CMYK and Lab)")), + }; + colors.push((name, color)); + } + // Spot colors unless the book says process ones. + let spot = data.0.windows(8).last() != Some(b"spflproc".as_slice()); + let mut lib = SwatchLibrary { name: if title.is_empty() { fallback.into() } else { title }, ..Default::default() }; + let mut names = UniqueNames::default(); + // Every name gets the prefix and the suffix, and is kept twice (the swatch's and the set of + // names taken): a megabyte book of long affixes and many colors came to hundreds of MB. + let mut kept = 0usize; + for (name, color) in colors.into_iter().filter(|(n, _)| !n.trim().is_empty()) { + kept = kept.saturating_add(2 * (prefix.len() + name.len() + suffix.len())); + if kept > ACB_MAX_NAME_BYTES { + return Err(format!("the color book's names take more than {} MB", ACB_MAX_NAME_BYTES >> 20)); + } + let name = names.unique(format!("{prefix}{name}{suffix}").trim().to_string()); + lib.swatches.push(Swatch { name, paint: Paint::solid(color), global: spot, spot }); + } + Ok(lib) +} + +/// Most bytes a color book's full color names (with its prefix and suffix) may take, counted +/// twice as they are kept twice. +const ACB_MAX_NAME_BYTES: usize = 64 << 20; + +/// The swatch of an `.ase` color block, `None` for a model other than RGB, CMYK, Lab and Gray. +/// Components are clamped to their ranges. +fn ase_swatch(body: &mut AseData) -> Result, String> { + let name = body.name()?; + let unit = |v: f32| v.clamp(0.0, 1.0); + let color = match &body.array::<4>()? { + b"RGB " => { + let [r, g, b] = [body.f32()?, body.f32()?, body.f32()?]; + Color::rgb(unit(r), unit(g), unit(b)) + } + b"CMYK" => { + let [c, m, y, k] = [body.f32()?, body.f32()?, body.f32()?, body.f32()?]; + Color::cmyk(unit(c), unit(m), unit(y), unit(k)) + } + // Lightness is stored as a fraction of 100. Some writers store L* itself, which shows as a + // value above 1. + b"LAB " => { + let [l, a, b] = [body.f32()?, body.f32()?, body.f32()?]; + let l = if l > 1.0 { l.min(100.0) } else { unit(l) * 100.0 }; + Color::lab(l, a.clamp(-128.0, 127.0), b.clamp(-128.0, 127.0)) + } + // A gray level (1 is white); a gray color holds its ink. + b"Gray" => Color::gray(1.0 - unit(body.f32()?)), + _ => return Ok(None), + }; + // Some writers leave the color type out, which makes a process color. + let kind = if body.0.len() >= 2 { body.u16()? } else { 2 }; + // Spot colors are global. + let (global, spot) = match kind { + 0 => (true, false), + 1 => (true, true), + _ => (false, false), + }; + let name = if name.is_empty() { value_name(color) } else { name }; + Ok(Some(Swatch { name, paint: Paint::solid(color), global, spot })) +} + +/// A color's values in its own model, as new swatches are named ("C=10 M=20 Y=30 K=0", +/// "R=255 G=128 B=0", "Gray K=40", "L=52 a=70 b=-30"). +fn value_name(c: Color) -> String { + let pct = |v: f32| (v * 100.0).round(); + let byte = |v: f32| (v * 255.0).round(); + match c { + Color::Cmyk { c, m, y, k } => format!("C={} M={} Y={} K={}", pct(c), pct(m), pct(y), pct(k)), + Color::Rgb { r, g, b } => format!("R={} G={} B={}", byte(r), byte(g), byte(b)), + Color::Gray { k } => format!("Gray K={}", pct(k)), + // `+ 0.0` turns a rounded -0 into 0. + Color::Lab { l, a, b } => format!("L={} a={} b={}", l.round() + 0.0, a.round() + 0.0, b.round() + 0.0), + } +} + +/// `.ase` data, read field by field; reading past its end is an error. +struct AseData<'a>(&'a [u8]); + +impl<'a> AseData<'a> { + fn bytes(&mut self, n: usize) -> Result<&'a [u8], String> { + let (head, rest) = self.0.split_at_checked(n).ok_or(ASE_CUT_SHORT)?; + self.0 = rest; + Ok(head) + } + fn array(&mut self) -> Result<[u8; N], String> { + let (head, rest) = self.0.split_first_chunk::().ok_or(ASE_CUT_SHORT)?; + self.0 = rest; + Ok(*head) + } + fn u16(&mut self) -> Result { + self.array().map(u16::from_be_bytes) + } + fn u32(&mut self) -> Result { + self.array().map(u32::from_be_bytes) + } + /// A component; one that isn't a finite number reads as 0. + fn f32(&mut self) -> Result { + let v = f32::from_be_bytes(self.array()?); + Ok(if v.is_finite() { v } else { 0.0 }) + } + /// A color book string ([`read_acb`]): a `u32` count of UTF-16 code units, then the units, + /// with `$$$/key=Text` read as `Text` and `^R`, `^C` as ®, ©; at most [`ASE_MAX_NAME`] units + /// are kept. + fn acb_string(&mut self) -> Result { + let n = usize::try_from(self.u32()?).unwrap_or(usize::MAX); + let (units, _) = self.bytes(n.checked_mul(2).ok_or(ASE_CUT_SHORT)?)?.as_chunks::<2>(); + let units: Vec = units.iter().take(ASE_MAX_NAME).map(|u| u16::from_be_bytes(*u)).take_while(|&u| u != 0).collect(); + let s = String::from_utf16_lossy(&units); + let s = match s.strip_prefix("$$$/") { + Some(key) => key.split_once('=').map_or("", |(_, text)| text).to_string(), + None => s, + }; + Ok(s.replace("^R", "®").replace("^C", "©")) + } + /// A name up to its terminating zero, trimmed. A block that ends before it has no name. + fn name(&mut self) -> Result { + if self.0.is_empty() { + return Ok(String::new()); + } + let n = usize::from(self.u16()?); + let (units, _) = self.bytes(n * 2)?.as_chunks::<2>(); + let units: Vec = units.iter().take(ASE_MAX_NAME).map(|u| u16::from_be_bytes(*u)).take_while(|&u| u != 0).collect(); + Ok(String::from_utf16_lossy(&units).trim().to_string()) + } +} + +/// A group's name as a file gives it, trimmed; "Color Group" when it has none. +fn group_name(name: &str) -> String { + let name = name.trim(); + if name.is_empty() { "Color Group".into() } else { name.to_string() } +} + +/// The swatch and group names a reader has handed out. Swatches and color groups share one set of +/// names, as in a document, and a name already taken gets the first free number ("Black 2"). +#[derive(Default)] +struct UniqueNames { + taken: HashSet, + /// The last number tried for each repeated name. + last: HashMap, +} + +impl UniqueNames { + fn unique(&mut self, base: String) -> String { + if self.taken.insert(base.clone()) { + return base; + } + // Each pass tries the next number, and only finitely many names are taken. + let n = self.last.entry(base.clone()).or_insert(1); + loop { + *n += 1; + let name = format!("{base} {n}"); + if self.taken.insert(name.clone()) { + return name; + } + } + } +} + #[cfg(test)] mod tests; From 8fcadbc3c15371db0ac2a4c94835735e90880839 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Thu, 19 Nov 2026 09:57:00 +0530 Subject: [PATCH 9/9] Fix #864: SVG export preserves the document unit in viewBox and width/height (#8610) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * SVG export: preserve document unit in viewBox and width/height (#864) When exporting SVG documents with physical units (mm, cm, in, pc), emit the physical unit suffix on the root attributes while keeping viewBox numbers and inner coordinates in 1:1 points per SVG 1.1 coords §7.10. This avoids the 75% scaling mismatch when opening drawings in external tools such as Inkscape or LightBurn, and preserves the document unit setting across save/open round trips. Unitless documents (points, pixels) continue to emit unitless dimensions. Tested via export_physical_units_writes_unit_suffixes in vectorcraft-svg and full round-trip svg_round_trip_preserves_document_units in vectorcraft-engine. Ran cargo xtask ci (fmt, clippy, tests, xtask gates). * SVG export: preserve nonzero width and viewBox on extreme small dimensions --- crates/doc/src/units.rs | 15 ++++++ crates/engine/src/cmd/fileio/tests_svg.rs | 45 ++++++++++++++++ crates/svg/src/export.rs | 25 +++++++-- crates/svg/tests/it/import_units.rs | 64 ++++++++++++++++++++++- docs/gaps.md | 10 ++-- docs/roadmap.md | 2 +- docs/target-app-parity.md | 5 +- 7 files changed, 156 insertions(+), 10 deletions(-) diff --git a/crates/doc/src/units.rs b/crates/doc/src/units.rs index f61319326c..728c8aa816 100644 --- a/crates/doc/src/units.rs +++ b/crates/doc/src/units.rs @@ -81,6 +81,21 @@ impl Unit { Unit::Ha => "H", } } + /// Whether this unit is a physical measurement unit (not points or pixels). + pub fn is_physical(self) -> bool { + self.svg_suffix().is_some() || matches!(self, Unit::FeetInches | Unit::Meters | Unit::Yards | Unit::Feet | Unit::Q | Unit::Ha) + } + /// The standard SVG length unit suffix, if this unit is a physical unit supported in SVG + /// (`mm`, `cm`, `in`, `pc`). + pub fn svg_suffix(self) -> Option<&'static str> { + match self { + Unit::Millimeters => Some("mm"), + Unit::Centimeters => Some("cm"), + Unit::Inches => Some("in"), + Unit::Picas => Some("pc"), + _ => None, + } + } pub const fn label(self) -> &'static str { match self { Unit::Points => "Points", diff --git a/crates/engine/src/cmd/fileio/tests_svg.rs b/crates/engine/src/cmd/fileio/tests_svg.rs index c7716940a1..7b5545ddca 100644 --- a/crates/engine/src/cmd/fileio/tests_svg.rs +++ b/crates/engine/src/cmd/fileio/tests_svg.rs @@ -437,3 +437,48 @@ fn svg_darkness_uses_rendered_shadow_in_non_srgb_working_space() { assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 8), "at {x}: {a:?} vs {b:?}"); } } + +/// #864 / G11: SVG export preserves the document's physical units on the root `width`/`height` so +/// that the unit setting survives a save/open round-trip. The engine-level test covers the full +/// stack (file.new → document.setUnits → document.serialize → document.open). +#[test] +fn svg_round_trip_preserves_document_units() { + // (unit name the engine accepts, expected unit after re-import) + let cases: &[(&str, vectorcraft_doc::Unit)] = &[ + ("millimeters", vectorcraft_doc::Unit::Millimeters), + ("centimeters", vectorcraft_doc::Unit::Centimeters), + ("inches", vectorcraft_doc::Unit::Inches), + ("picas", vectorcraft_doc::Unit::Picas), + // Points and pixels both serialise as bare user-unit numbers, so both import as Pixels. + ("pixels", vectorcraft_doc::Unit::Pixels), + ]; + for (name, expected) in cases { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 1})).unwrap(); + s.execute("document.setUnits", &json!({"units": name})).unwrap(); + let r = s.execute("document.serialize", &json!({"format": "svg"})).unwrap(); + let svg_text = r["text"].as_str().unwrap(); + match *expected { + vectorcraft_doc::Unit::Millimeters => assert!(svg_text.contains("mm\""), "mm suffix missing: {svg_text}"), + vectorcraft_doc::Unit::Centimeters => assert!(svg_text.contains("cm\""), "cm suffix missing: {svg_text}"), + vectorcraft_doc::Unit::Inches => assert!(svg_text.contains("in\""), "in suffix missing: {svg_text}"), + vectorcraft_doc::Unit::Picas => assert!(svg_text.contains("pc\""), "pc suffix missing: {svg_text}"), + _ => {} + } + let b64 = vectorcraft_format::base64_encode(svg_text.as_bytes()); + s.execute("document.open", &json!({"name": "test.svg", "dataBase64": b64})).unwrap(); + let doc_state = s.doc().unwrap(); + assert_eq!(doc_state.doc.units, *expected, "unit mismatch after round-trip for '{name}'"); + } + + // Points serialise without suffix and re-open as Pixels (equivalent in user units). + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 1})).unwrap(); + s.execute("document.setUnits", &json!({"units": "points"})).unwrap(); + let r = s.execute("document.serialize", &json!({"format": "svg"})).unwrap(); + let svg_text = r["text"].as_str().unwrap(); + assert!(svg_text.contains("width=\"200\" height=\"100\""), "{svg_text}"); + let b64 = vectorcraft_format::base64_encode(svg_text.as_bytes()); + s.execute("document.open", &json!({"name": "test.svg", "dataBase64": b64})).unwrap(); + assert_eq!(s.doc().unwrap().doc.units, vectorcraft_doc::Unit::Pixels); +} diff --git a/crates/svg/src/export.rs b/crates/svg/src/export.rs index ded9a037fe..84b2efa32b 100644 --- a/crates/svg/src/export.rs +++ b/crates/svg/src/export.rs @@ -78,6 +78,18 @@ fn update_editing_hash(svg: &mut String) { } } +/// Format physical dimensions (inches, mm, cm) with enough precision and significant digits +/// that small nonzero sizes do not round to zero or distort relative aspect ratio. +fn physical_num(v: f64) -> String { + if !v.is_finite() || v <= 0.0 { + return "0".into(); + } + let leading_zeros = (-v.log10().floor() as i32).max(0); + let decimals = (leading_zeros + 3).clamp(3, 14) as u8; + let s = fmt_num(v, decimals); + if s == "0" && v > 0.0 { format!("{v:.16}").trim_end_matches('0').trim_end_matches('.').to_string() } else { s } +} + /// `doc` as SVG with `opts`, the native file `native` embedded for Preserve Editing, its generated /// ids starting with `id_prefix`. fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: &str) -> Output { @@ -183,10 +195,17 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: root = root.attr("version", "1.2").attr("baseProfile", "tiny"); } if !opts.responsive { - // Unitless width/height stay in this one branch so #7105 (physical unit suffixes) can rebase here. - root = root.attr("width", &ww).attr("height", &hh); + if let Some(suffix) = doc.units.svg_suffix() { + let w_val = physical_num(doc.units.from_pt(rect.width())); + let h_val = physical_num(doc.units.from_pt(rect.height())); + root = root.attr("width", format_args!("{w_val}{suffix}")).attr("height", format_args!("{h_val}{suffix}")); + } else { + root = root.attr("width", &ww).attr("height", &hh); + } } - root.attr("viewBox", format_args!("0 0 {ww} {hh}")).open(); + let vb_w = if rect.width() > 0.0 && ww == "0" { physical_num(rect.width()) } else { ww.clone() }; + let vb_h = if rect.height() > 0.0 && hh == "0" { physical_num(rect.height()) } else { hh.clone() }; + root.attr("viewBox", format_args!("0 0 {vb_w} {vb_h}")).open(); let mut out = svg.as_str().to_string(); out.push_str(nl); let css = opts.styling == Styling::InternalCss && !w.classes.is_empty(); diff --git a/crates/svg/tests/it/import_units.rs b/crates/svg/tests/it/import_units.rs index 1ce01c7f07..0140741aeb 100644 --- a/crates/svg/tests/it/import_units.rs +++ b/crates/svg/tests/it/import_units.rs @@ -3,7 +3,7 @@ use vectorcraft_doc::{Document, Node, NodeKind, Unit}; use vectorcraft_geom::Rect; -use vectorcraft_svg::import; +use vectorcraft_svg::{ExportOptions, export, import}; fn art(d: &Document) -> Vec<&Node> { let mut v = Vec::new(); @@ -130,3 +130,65 @@ fn absolute_lengths_in_a_pixel_document_keep_their_size() { assert!(close_rect(n.geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 72.0, 720.0 / 25.4)), "{:?}", n.geometric_bounds()); assert!(close(n.appearance.stroke_width(), 2.0)); } + +#[test] +fn export_physical_units_writes_unit_suffixes() { + // Millimeters (#864 / G11: avoid 75% scale in external tools like LightBurn, LaserGRBL, Inkscape) + let mut d = Document::new(50.0 * 72.0 / 25.4, 30.0 * 72.0 / 25.4); + d.units = Unit::Millimeters; + let s = export(&d, &ExportOptions::default()); + assert!(s.contains("width=\"50mm\" height=\"30mm\""), "{s}"); + assert!(s.contains("viewBox=\"0 0 141.732 85.039\""), "{s}"); + + // Inches + let mut d = Document::new(8.5 * 72.0, 11.0 * 72.0); + d.units = Unit::Inches; + let s = export(&d, &ExportOptions::default()); + assert!(s.contains("width=\"8.5in\" height=\"11in\""), "{s}"); + assert!(s.contains("viewBox=\"0 0 612 792\""), "{s}"); + + // Centimeters + let mut d = Document::new(5.0 * 72.0 / 2.54, 3.0 * 72.0 / 2.54); + d.units = Unit::Centimeters; + let s = export(&d, &ExportOptions::default()); + assert!(s.contains("width=\"5cm\" height=\"3cm\""), "{s}"); + + // Picas + let mut d = Document::new(10.0 * 12.0, 20.0 * 12.0); + d.units = Unit::Picas; + let s = export(&d, &ExportOptions::default()); + assert!(s.contains("width=\"10pc\" height=\"20pc\""), "{s}"); + + // Points and pixels remain unitless + let mut d = Document::new(100.0, 200.0); + d.units = Unit::Points; + let s = export(&d, &ExportOptions::default()); + assert!(s.contains("width=\"100\" height=\"200\""), "{s}"); + + d.units = Unit::Pixels; + let s = export(&d, &ExportOptions::default()); + assert!(s.contains("width=\"100\" height=\"200\""), "{s}"); + + // Responsive export omits width and height even with physical units + d.units = Unit::Millimeters; + let s = export(&d, &ExportOptions { responsive: true, ..Default::default() }); + assert!(!s.contains("width="), "{s}"); + assert!(!s.contains("height="), "{s}"); + + // Non-zero small dimensions do not round to zero + let mut d = Document::new(0.001 * 72.0 / 25.4, 0.002 * 72.0 / 25.4); + d.units = Unit::Millimeters; + let s = export(&d, &ExportOptions::default()); + assert!(s.contains("width=\"0.001mm\" height=\"0.002mm\""), "{s}"); + + // Extreme small dimension below 8 decimal places preserves non-zero width and viewBox + let mut d = Document::new(1e-9 * 72.0 / 25.4, 1e-9 * 72.0 / 25.4); + d.units = Unit::Millimeters; + let s = export(&d, &ExportOptions::default()); + assert!(!s.contains("width=\"0mm\""), "{s}"); + assert!(!s.contains("viewBox=\"0 0 0 0\""), "{s}"); + + // Re-importing preserved physical units + let back = import(&s).unwrap(); + assert_eq!(back.units, Unit::Millimeters); +} diff --git a/docs/gaps.md b/docs/gaps.md index a8ba004253..a9ac95c05e 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > Selection update (2026-11-11): path and compound-path interiors follow enabled non-None fill rows, including lower fills beneath a top None row (#6625). Hidden-only interiors miss; zero-opacity fills remain selectable. Cap/join follow-up (2026-11-12): hidden-fill and no-fill stroke hits must respect cap and join geometry; focused cap/join CPU regressions passed. Scores and estimates unchanged. @@ -40,6 +40,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | G11: SVG export writes physical unit suffixes on the root for documents with physical units (mm, cm, in, pc), preventing drawings from scaling to 75% in external tools and preserving units across round-trips (#864; general unit preference on restart remains open under #864). Estimate 8–15 → 6–13 h. | | 2026-11-18 | minor | G12: Layers panel ruler guide and blend spine row context menus (#8592): Hide/Show, Lock/Unlock, Release Guides, Delete and Locate Object on guide rows; Select, Blend Options…, Reverse Spine, Reverse Front to Back, Expand, Release and Locate Object on blend spine rows. Scores and estimates unchanged. | | 2026-11-18 | minor | G19: PDF export writes the document language chosen in Document Setup as the catalog's `/Lang` (its BCP 47 tag, `en-US` by default) and the XMP packet's `dc:language`, in exported and printed PDFs (#3644); `/MarkInfo` stays with tagged PDF (#3643). Scores and estimates unchanged. | | 2026-11-16 | minor | G1: Recolor Artwork - native Lab entry in Color Picker, swatch libraries access in Color Picker, and row right-click context menu ("Pick from Swatches", "Limit to Library") (#4028); scores and estimates unchanged. | @@ -102,7 +103,7 @@ stage ([ROADMAP.md](../ROADMAP.md)). | 2 | [G9 Illustrator `.ai` and EPS files from real users](#g9-illustrator-ai-and-eps-files-from-real-users) | 10–20 | yes | [file-format-parity.md](file-format-parity.md) | | 3 | [G10 Launch and stability on real machines](#g10-launch-and-stability-on-real-machines) | 20–35 | yes | — | | 4 | [G8 Hardening at scale](#g8-hardening-at-scale) | 30–50 | yes (part) | — | -| 5 | [G11 Correctness bugs in core tools](#g11-correctness-bugs-in-core-tools) | 8–15 | yes | [target-app-parity.md](target-app-parity.md) | +| 5 | [G11 Correctness bugs in core tools](#g11-correctness-bugs-in-core-tools) | 6–13 | yes | [target-app-parity.md](target-app-parity.md) | | 6 | [G4 Advanced type](#g4-advanced-type) | 34–47 | core part | [type-parity.md](type-parity.md) | | 7 | [G12 Preferences and panels that don't act yet](#g12-preferences-and-panels-that-dont-act-yet) | 13–20 | yes | [ui-parity.md](ui-parity.md) | | 8 | [G2 Photoshop-style raster effects and the Effect Gallery](#g2-photoshop-style-raster-effects-and-the-effect-gallery) | 0 | no | [effects-parity.md](effects-parity.md) | @@ -403,7 +404,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi such stubs into one vertex (within 4× the sweep's tolerance up and down its frame and 1/16 of the 0.01 pt precision along it, bounded by each cluster's extent so a run of tiny level segments keeps its length); regression tests in `crates/pathops/src/planar.rs`. Estimate unchanged. -- **Missing:** SVG units reverting to points (#864). Shape Builder regions (#937, closed), PDF text placement +- **Done (#864):** SVG export writes physical unit suffixes on the root `` for documents with physical units (`mm`, `cm`, `in`, `pc`), so external vector tools (Inkscape, LightBurn) and browsers render drawings at their intended physical scale rather than scaling to 75% under point-based user-unit assumptions; unitless user coordinates in `viewBox` and path geometry remain in 1:1 internal points per SVG 1.1 coords §7.10, preserving document units on round trips (`export_physical_units_writes_unit_suffixes`, `svg_round_trip_preserves_document_units`). General document unit preferences across restarts remain tracked under #864. +- **Missing:** general document unit preference on restart (#864; SVG export physical units done). Shape Builder regions (#937, closed), PDF text placement (#722, above), the bezier drag preview (#834, #3065, #3729) and deleting an interior anchor of an open path (above) are done. - **Done (#722):** PDF text opens where the file draws it. Each line used to come in as point type laid out by the @@ -415,7 +417,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi boxes come back as justified area type. Fixtures written from ISO 32000-1 §9 (`tests_text_placement`). A font that is neither embedded nor installed still draws in a stand-in with the old fit. - **Impact:** wrong output in everyday work. -- **Estimate:** 8–15 h. +- **Estimate:** 6–13 h. ## G4 Advanced type diff --git a/docs/roadmap.md b/docs/roadmap.md index 4e23db3070..330cca0505 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -147,7 +147,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule Selection, smart guides and snapping first. 60–90 h, parallel by tool. 2. **`.ai` files from real users** (G9): layer structure (#951). 10–20 h. 3. **Launch and stability** (G10): the Windows and Linux start-up reports. 20–35 h. -4. **Core-tool bugs** (G11): SVG units reverting to points (#864) and a Transform effect in a fill's or stroke's own effects (#885). Shape Builder regions (#937), Asset Export ghost borders (#983 / #1037) and the stalling bezier drag preview (#834) are fixed. 8–15 h. +4. **Core-tool bugs** (G11): SVG units reverting to points (#864; SVG export physical units fixed) and a Transform effect in a fill's or stroke's own effects (#885). Shape Builder regions (#937), Asset Export ghost borders (#983 / #1037) and the stalling bezier drag preview (#834) are fixed. 6–13 h. 5. **Then:** advanced type (G4) and the Illustrator 2026 additions (G13), then 3D (G3). The Effect Gallery's filter thumbnails and in-dialog preview are in (G2). ## Next diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6c61e9f025..b1b68855fb 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -26,6 +26,8 @@ ## Feature submission evidence +SVG export preserves document units on the root `` for documents with physical units (`mm`, `cm`, `in`, `pc`) per SVG 1.1 coordinates §7.10, preventing exported drawings from scaling to 75% in external tools like Inkscape and LightBurn (#864). Internal user coordinates in `viewBox` and path geometry remain in 1:1 points, and unitless documents (pixels, points) omit unit suffixes. Evidence: `crates/svg/tests/it/import_units.rs::export_physical_units_writes_unit_suffixes` (asserts physical unit suffixes `mm`, `in`, `cm`, `pc`, unitless points/pixels, responsive export omission, and small decimal precision) and `crates/engine/src/cmd/fileio/tests_svg.rs::svg_round_trip_preserves_document_units` (verifies full round trip through engine commands `file.new` -> `document.setUnits` -> `document.serialize` -> `document.open`). G11 estimate 8–15 → 6–13 h; parity scores unchanged. + `window.panel.float` updates an existing native panel window's supplied position and size (#8391). Positions use the main window's content origin. Omitted coordinates and dimensions keep their current native values, including after an OS window move or resize. Evidence: `panel_docking::native_tests::an_explicit_float_command_updates_an_existing_native_windows_geometry` covers panel, group and column commands. Scores and estimates are unchanged. EPS embedded fonts, 2026-11-09 (#6023–#6067): the fonts an EPS carries draw their glyphs instead of being set as type in an installed font: composite (Type 0) fonts with the 8/8 mapping, plain Type 42 fonts (characters from their glyph names or character map, widths from the font), CID-keyed fonts over CMaps (Type 0 and Type 2 CIDFonts, CIDFonts in a FontSet's Compact Font Format data, base-font CMaps, named CIDFonts over predefined Unicode CMaps set as type) and embedded Type 1 fonts; the show operators' spacing along the baseline is kept as tracking, `kshow` included. Each step is charged to the interpreter's budgets. Hand-written test files only (no corpus file uses these fonts); scores and estimates unchanged. Evidence: `crates/eps/src/import/tests_composite.rs`, `tests_type42.rs`, `tests_cid.rs`, `tests_type1.rs`; details in [file-format-parity.md](file-format-parity.md). @@ -69,6 +71,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | G11: SVG export writes physical unit suffixes on the root for documents with physical units (mm, cm, in, pc), preventing drawings from scaling to 75% in external tools and preserving units across round-trips (#864; general unit preference on restart remains open under #864). Tests: export_physical_units_writes_unit_suffixes (crates/svg/tests/it/import_units.rs) and svg_round_trip_preserves_document_units (crates/engine/src/cmd/fileio/tests_svg.rs). G11 estimate 8–15 → 6–13 h. | | 2026-11-18 | minor | PDF import (#8543): type filled and stroked (text rendering modes 2 and 6) by a `TJ` whose kerning starts a new line part way through came in as four type objects, each part filled only and each part stroked only over it: the reader fills every glyph of the operator before it strokes them, and the line the first part was gathered on was finished before the stroke pass came back to it. Lines an operator's fill pass finishes while a stroke may still be drawn over them are now kept (up to 64 besides the open line, so a `TJ` over up to 65 lines: one over more stays a filled object and a stroked one for each part, as before) until the stroke pass goes past them, and the pass's strokes are held (up to 4096: a longer pass is matched a part at a time, each part to glyphs filled one right after another, never to one an operator before it filled) until it ends, then matched to the glyphs filled last, in the order they were filled, so each stroke finds the glyph it was filled as, also where the `TJ` draws a glyph again where it drew one (`[(A) -3500 (B) 4834 (A)] TJ`). Each part comes in as one type object filled and stroked, in the order drawn; also a `TJ` that jumps back and one whose kerning starts two new lines. In an `ActualText` span (whose stroke was lost) the replacement text stays one type object on the first glyph's line and in its style, now filled and stroked, also where the `TJ` draws a glyph again: the span's strokes are matched the same way. A stroke over no filled glyph (stroked type of its own) and the start and end of an `ActualText` span end a stroke pass: no stroke after them goes over a glyph filled before them, so none is drawn under type drawn after it, and a later span keeps its own replacement text. Stroke rendering stays stroke only, and translucent type stays a filled object and a stroked one. Tests: `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`, `a_tj_that_draws_a_glyph_again_where_it_drew_one_strokes_each_copy`, `a_stroked_tj_whose_kerning_starts_a_new_line_stays_stroke_only`, `a_translucent_tj_whose_kerning_starts_a_new_line_stays_fill_and_stroke_apart`, `a_long_stroke_pass_strokes_its_own_glyphs_not_one_filled_before`, `a_stroke_after_stroked_type_of_its_own_does_not_join_a_glyph_filled_before`, `a_stroke_in_an_actual_text_span_does_not_take_an_earlier_spans_glyph`, `a_tj_that_draws_a_glyph_again_in_an_actual_text_span_strokes_the_replacement`, `a_tj_over_more_lines_than_are_kept_comes_in_as_fill_and_stroke_apart`, `a_tj_over_more_lines_than_are_kept_that_ends_where_it_began_stays_fill_and_stroke_apart`, `type_after_a_tj_over_more_lines_than_are_kept_is_filled_and_stroked`; scores and estimates unchanged. | | 2026-11-18 | minor | Hardening: PDF export writes the document language (Document Setup) as the catalog's `/Lang` and XMP `dc:language` (#3644). Scores and estimates unchanged. | | 2026-11-17 | minor | Distort & Transform › Twist: handles follow the rotation's derivative, so a strongly twisted path is a smooth spiral instead of pieces meeting at kinks (#7069; `twist_joins_its_pieces_smoothly` in `crates/effects/src/tests.rs`). Scores and estimates unchanged. |