mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 12:38:18 +00:00
Merge main into fix/issue-8568
This commit is contained in:
Generated
+10
@@ -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"
|
||||
@@ -6727,6 +6736,7 @@ dependencies = [
|
||||
name = "vectorcraft-color"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-cms",
|
||||
"kurbo 0.13.1",
|
||||
"moxcms",
|
||||
"proptest",
|
||||
|
||||
@@ -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" }
|
||||
|
||||
@@ -9,6 +9,7 @@ description = "VectorCraft color"
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-cms = { workspace = true }
|
||||
kurbo = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
+52
-450
@@ -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<PaletteSwatch> {
|
||||
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<PaletteSwatch>) -> Vec<Swatch> {
|
||||
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<Vec<u8>, 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::<Vec<_>>().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<Vec<u8>, 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::<usize>();
|
||||
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<u8>, list: &[Swatch]) -> Result<usize, String> {
|
||||
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<f32>) = 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<u8>, 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<u8>, name: &str) -> Result<(), String> {
|
||||
let mut units: Vec<u16> = 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<SwatchLibrary, String> {
|
||||
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<SwatchLibrary, String> {
|
||||
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<SwatchLibrary, String> {
|
||||
/// 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<u8> = 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
|
||||
/// <https://www.selapa.net/swatches/colors/fileformats.php>, the component ranges from
|
||||
/// <https://github.com/nsfmc/swatch>. 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<SwatchLibrary, String> {
|
||||
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<SwatchLibrary, String> {
|
||||
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<Option<Swatch>, 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<const N: usize>(&mut self) -> Result<[u8; N], String> {
|
||||
let (head, rest) = self.0.split_first_chunk::<N>().ok_or(ASE_CUT_SHORT)?;
|
||||
self.0 = rest;
|
||||
Ok(*head)
|
||||
}
|
||||
fn u16(&mut self) -> Result<u16, String> {
|
||||
self.array().map(u16::from_be_bytes)
|
||||
}
|
||||
fn u32(&mut self) -> Result<u32, String> {
|
||||
self.array().map(u32::from_be_bytes)
|
||||
}
|
||||
/// A component; one that isn't a finite number reads as 0.
|
||||
fn f32(&mut self) -> Result<f32, String> {
|
||||
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<String, String> {
|
||||
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<u16> = 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<String, String> {
|
||||
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<u16> = 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<String>,
|
||||
/// The last number tried for each repeated name.
|
||||
last: HashMap<String, usize>,
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -123,11 +123,13 @@ impl<'a> Reader<'a> {
|
||||
}
|
||||
// A group holding only clipping paths (`q … u <path> W n U … Q`) doesn't clip on its own: `u`/`U` don't save
|
||||
// the graphics state as `q`/`Q` do, so its paths clip the clipping group around it, as the file's PDF part draws it.
|
||||
// In a compound path (`*u u <path> W n … U *U`, possibly nested in other groups) they are the compound
|
||||
// path's subpaths, as its other grouped paths are: the compound clipping path, their union.
|
||||
if matches!(kind, Kind::Group)
|
||||
&& unread.is_empty()
|
||||
&& !clips.is_empty()
|
||||
&& clips.len() == kids.len()
|
||||
&& matches!(self.frames.last(), Some(Frame { kind: Kind::Clip, .. }))
|
||||
&& (matches!(self.frames.last(), Some(Frame { kind: Kind::Clip, .. })) || self.in_compound())
|
||||
{
|
||||
for kid in kids {
|
||||
if let Some(parent) = self.frames.last_mut() {
|
||||
@@ -212,6 +214,18 @@ impl<'a> Reader<'a> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Is the innermost open frame a compound path (`*u`), or a group in one with only groups between them?
|
||||
fn in_compound(&self) -> bool {
|
||||
for f in self.frames.iter().rev() {
|
||||
match f.kind {
|
||||
Kind::Group => {}
|
||||
Kind::Compound => return true,
|
||||
_ => return false,
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// The compound path of `kids`, painted and made transparent as its subpaths say.
|
||||
fn compound(&mut self, mut kids: Vec<Node>, gs: &GState) -> Option<Node> {
|
||||
// The compound path's paint is its last path's (a gradient's instance wraps only
|
||||
|
||||
@@ -1734,6 +1734,42 @@ fn a_clipping_path_alone_in_a_group_clips_its_clipping_group() {
|
||||
assert_eq!(fill(&children[1]).color(), Some(Color::rgb(1.0, 0.0, 0.0)));
|
||||
}
|
||||
|
||||
/// Clipping paths grouped in a compound path (`*u u <path> W n … U *U`, possibly nested in other groups) are
|
||||
/// the compound path's subpaths, as its other grouped paths are: the compound clipping path, their union, clips its
|
||||
/// clipping group, however many there are and wherever in the group it is written.
|
||||
#[test]
|
||||
fn clipping_paths_grouped_in_a_compound_path_are_its_subpaths() {
|
||||
let square = rect_path(0.0, 0.0, 80.0, 80.0);
|
||||
let (a, b, c) = (rect_path(0.0, 0.0, 10.0, 10.0), rect_path(30.0, 0.0, 40.0, 10.0), rect_path(60.0, 0.0, 70.0, 10.0));
|
||||
let clip = |p: &str| format!("{p}h\nW\nn\n");
|
||||
let bodies = [
|
||||
// One group of them, after the art.
|
||||
format!("0 Ae\nq\n{RED}{square}f\n*u\n0 Ae\nu\n{}{}{}U\n*U\nQ\n", clip(&a), clip(&b), clip(&c)),
|
||||
// Groups in a group, and one path straight in the compound path, before the art.
|
||||
format!("0 Ae\nq\n*u\n0 Ae\nu\n0 Ae\nu\n{}{}U\n0 Ae\nu\n{}U\nU\n*U\n{RED}{square}f\nQ\n", clip(&a), clip(&b), clip(&c)),
|
||||
format!("0 Ae\nq\n*u\n0 Ae\nu\n{}{}U\n{}*U\n{RED}{square}f\nQ\n", clip(&a), clip(&b), clip(&c)),
|
||||
];
|
||||
for body in &bodies {
|
||||
let doc = read_ok(&layer(body)).doc;
|
||||
let NodeKind::Group { children, clip: true } = &art(&doc)[0].kind else { panic!("{body}: {:?}", art(&doc)[0].kind) };
|
||||
assert_eq!(children.len(), 2, "{body}: {children:?}");
|
||||
let NodeKind::Compound { children: subpaths, .. } = &children[0].kind else { panic!("{body}: {:?}", children[0].kind) };
|
||||
assert_eq!(subpaths.len(), 3, "{body}: {subpaths:?}");
|
||||
assert!(subpaths.iter().all(|p| matches!(p.kind, NodeKind::Path { clipping: true, .. })), "{body}: {subpaths:?}");
|
||||
assert_eq!(fill(&children[1]).color(), Some(Color::rgb(1.0, 0.0, 0.0)), "{body}");
|
||||
}
|
||||
// Hundreds of them, one union: not clipping groups nested past the document's depth limit.
|
||||
let many = format!("0 Ae\nq\n{RED}{square}f\n*u\n0 Ae\nu\n{}U\n*U\nQ\n", clip(&a).repeat(300));
|
||||
let doc = read_ok(&layer(&many)).doc;
|
||||
let NodeKind::Group { children, clip: true } = &art(&doc)[0].kind else { panic!("{:?}", art(&doc)[0].kind) };
|
||||
let NodeKind::Compound { children: subpaths, .. } = &children[0].kind else { panic!("{:?}", children[0].kind) };
|
||||
assert_eq!(subpaths.len(), 300);
|
||||
// A group of clipping paths outside a compound path or a clipping group is read as before: a clipping group.
|
||||
let alone = format!("0 Ae\nu\n{}{}U\n{RED}{square}f\n", clip(&a), clip(&b));
|
||||
let doc = read_ok(&layer(&alone)).doc;
|
||||
assert!(matches!(art(&doc)[0].kind, NodeKind::Group { clip: true, .. }), "{:?}", art(&doc)[0].kind);
|
||||
}
|
||||
|
||||
/// #1410: a compound path shows its last path's paint, and paths grouped in it stay its paths.
|
||||
#[test]
|
||||
fn compound_path_takes_its_last_paths_paint() {
|
||||
|
||||
@@ -29,7 +29,7 @@
|
||||
|
||||
use craft_svg::tree::usvg;
|
||||
use std::borrow::Cow;
|
||||
use std::cell::RefCell;
|
||||
use std::cell::{OnceCell, RefCell};
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Write as _;
|
||||
use std::ops::{Range, RangeInclusive};
|
||||
@@ -774,6 +774,10 @@ struct Ctx {
|
||||
/// no usable one. The styles of a `<use>` instance share it, so each path is found and parsed
|
||||
/// once however many `<use>` elements show its text.
|
||||
paths: Rc<RefCell<HashMap<roxmltree::NodeId, Option<Rc<FollowedPath>>>>>,
|
||||
/// Each element id in the document and the first element in document order that carries it
|
||||
/// ([`Self::element`]). It is built when the first `<textPath>` names an element, and the
|
||||
/// styles of a `<use>` instance share it.
|
||||
ids: Rc<OnceCell<HashMap<Box<str>, roxmltree::NodeId>>>,
|
||||
}
|
||||
|
||||
/// The path a `<textPath>` follows ([`Ctx::text_path`]).
|
||||
@@ -788,6 +792,11 @@ struct FollowedPath {
|
||||
thread_local! {
|
||||
/// How many times [`Ctx::read_text_path`] has read a `<textPath>`'s path on this thread.
|
||||
static TEXT_PATH_READS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
/// How many times [`Ctx::element`] has walked a document's elements on this thread.
|
||||
static ID_WALKS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
/// When set, [`Ctx::element`] walks the document for each id instead of using the map, so
|
||||
/// tests can compare the two.
|
||||
static LINEAR_IDS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
impl Ctx {
|
||||
@@ -802,6 +811,7 @@ impl Ctx {
|
||||
elems: RefCell::default(),
|
||||
strong: RefCell::default(),
|
||||
paths: Rc::default(),
|
||||
ids: Rc::default(),
|
||||
};
|
||||
let root = xml.root_element();
|
||||
let dim = |a: &str| root.attribute(a).and_then(|v| cx.length(v, DEFAULT_FONT_SIZE, 0.0)).filter(|v| *v > 0.0);
|
||||
@@ -824,6 +834,7 @@ impl Ctx {
|
||||
elems: RefCell::default(),
|
||||
strong: RefCell::default(),
|
||||
paths: self.paths.clone(),
|
||||
ids: self.ids.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1219,7 +1230,7 @@ impl Ctx {
|
||||
Some(d) => BezPath::from_svg(d).ok()?,
|
||||
None => {
|
||||
let id = href(tp)?.trim().strip_prefix('#')?;
|
||||
let el = xml.descendants().find(|n| n.is_element() && n.attribute("id") == Some(id))?;
|
||||
let el = self.element(xml, id)?;
|
||||
let d = match el.tag_name().name() {
|
||||
"path" => el.attribute("d")?.to_string(),
|
||||
_ => self.shape_path(el)?,
|
||||
@@ -1238,6 +1249,32 @@ impl Ctx {
|
||||
usable.then_some(FollowedPath { path: bp, author_length })
|
||||
}
|
||||
|
||||
/// The first element in document order whose `id` is `id`, as the DOM's `getElementById`
|
||||
/// finds it (https://dom.spec.whatwg.org/#dom-nonelementparentnode-getelementbyid). The first
|
||||
/// call walks `xml` once to build [`Self::ids`]; later calls look the id up there. `xml` is
|
||||
/// the document [`Self::new`] read.
|
||||
fn element<'a, 'i>(&self, xml: &'a roxmltree::Document<'i>, id: &str) -> Option<XNode<'a, 'i>> {
|
||||
#[cfg(test)]
|
||||
if LINEAR_IDS.get() {
|
||||
ID_WALKS.set(ID_WALKS.get() + 1);
|
||||
return xml.descendants().find(|n| n.is_element() && n.attribute("id") == Some(id));
|
||||
}
|
||||
let ids = self.ids.get_or_init(|| {
|
||||
#[cfg(test)]
|
||||
ID_WALKS.set(ID_WALKS.get() + 1);
|
||||
let mut ids = HashMap::new();
|
||||
for n in xml.descendants().filter(|n| n.is_element()) {
|
||||
if let Some(id) = n.attribute("id") {
|
||||
ids.entry(Box::from(id)).or_insert(n.id());
|
||||
}
|
||||
}
|
||||
ids
|
||||
});
|
||||
let el = xml.get_node(*ids.get(id)?)?;
|
||||
debug_assert_eq!(el.attribute("id"), Some(id), "the id map was built from another document");
|
||||
Some(el)
|
||||
}
|
||||
|
||||
/// The equivalent path of a basic shape (SVG 2 › Basic Shapes), as path data: what a
|
||||
/// `<textPath>` that points at it follows. Circles and ellipses start at 3 o'clock and rounded
|
||||
/// rects at the end of the top-left corner, all running clockwise; lines and polylines follow
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::*;
|
||||
use vectorcraft_doc::Document;
|
||||
|
||||
/// The texts [`prepare`] builds from `body` and how many times it read a `<textPath>`'s path.
|
||||
fn prepared(body: &str) -> (usize, u64, Vec<String>) {
|
||||
@@ -27,3 +28,134 @@ fn uses_of_a_text_on_a_path_read_the_path_once() {
|
||||
));
|
||||
assert_eq!((texts, reads), (51, 1));
|
||||
}
|
||||
|
||||
/// How many times [`prepare`] walked the document's elements to find the element a
|
||||
/// `<textPath>` names.
|
||||
fn id_walks(body: &str) -> u64 {
|
||||
let svg = format!(r#"<svg xmlns="http://www.w3.org/2000/svg" width="400" height="400">{body}</svg>"#);
|
||||
let xml = roxmltree::Document::parse(&svg).unwrap();
|
||||
let before = ID_WALKS.get();
|
||||
prepare(&svg, &xml, None, 96.0, &mut vec![]);
|
||||
ID_WALKS.get() - before
|
||||
}
|
||||
|
||||
/// The texts on paths in one file find the elements they name through one walk of the document.
|
||||
#[test]
|
||||
fn text_paths_find_their_elements_in_one_walk() {
|
||||
let paths: String = (0..20).map(|i| format!(r#"<path id="p{i}" d="M0 {i}L150 {i}"/>"#)).collect();
|
||||
let texts: String = (0..20).map(|i| format!(r##"<text id="t{i}"><textPath href="#p{i}">Path</textPath></text>"##)).collect();
|
||||
assert_eq!(id_walks(&format!("<defs>{paths}</defs>{texts}")), 1);
|
||||
// Texts shown only through `<use>` elements share the walk, and a missing id needs no other.
|
||||
let uses: String = (0..20).map(|i| format!(r##"<use href="#t{i}" font-size="20"/>"##)).collect();
|
||||
let missing = r##"<text><textPath xlink:href="#none" xmlns:xlink="http://www.w3.org/1999/xlink">Path</textPath></text>"##;
|
||||
assert_eq!(id_walks(&format!("<defs>{paths}{texts}</defs>{uses}{missing}")), 1);
|
||||
// A file whose texts name no element is not walked.
|
||||
assert_eq!(id_walks(r#"<text>Plain</text><text><textPath path="M0 20L150 20">Inline</textPath></text>"#), 0);
|
||||
assert_eq!(id_walks(r#"<path id="p" d="M0 20L150 20"/><text><textPath href="p">No hash</textPath></text>"#), 0);
|
||||
}
|
||||
|
||||
/// The document and warnings [`crate::import`] gives for `body`, with each `<textPath>`'s
|
||||
/// element found through the map of ids or, with `linear`, by walking the document for each one.
|
||||
fn imported(body: &str, linear: bool) -> (Document, Vec<String>) {
|
||||
let svg = format!(r#"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="400" height="400">{body}</svg>"#);
|
||||
LINEAR_IDS.set(linear);
|
||||
let out = crate::import::import(&svg, &crate::ImportOptions::default(), crate::MAX_NODES);
|
||||
LINEAR_IDS.set(false);
|
||||
out.unwrap_or_else(|e| panic!("{e}"))
|
||||
}
|
||||
|
||||
/// The text objects of `d`, in paint order.
|
||||
fn text_objects(d: &Document) -> Vec<TextObject> {
|
||||
let mut v = vec![];
|
||||
d.walk(|n| {
|
||||
if let vectorcraft_doc::NodeKind::Text(t) = &n.kind {
|
||||
v.push((**t).clone());
|
||||
}
|
||||
});
|
||||
v
|
||||
}
|
||||
|
||||
/// The map of ids finds the element the document walk finds: the first element in document order
|
||||
/// with the id, whatever it is.
|
||||
#[test]
|
||||
fn text_paths_find_the_element_a_document_walk_finds() {
|
||||
let cases = [
|
||||
// Several paths, one of them named twice, and shapes.
|
||||
r##"<defs><path id="a" d="M0 20L150 20"/><path id="b" d="M0 50C50 0 100 100 150 50" pathLength="10"/><path id="a" d="M0 80L150 80"/>
|
||||
<circle id="c" cx="200" cy="200" r="80"/><rect id="r" x="10" y="10" width="200" height="100" rx="5"/></defs>
|
||||
<text font-size="12"><textPath href="#a">First</textPath></text>
|
||||
<text font-size="12"><textPath xlink:href=" #b " startOffset="5">Second</textPath></text>
|
||||
<text font-size="12"><textPath href="#c" side="right">Circle</textPath></text>
|
||||
<text font-size="12"><textPath href="#r" startOffset="50%">Rect</textPath></text>"##,
|
||||
// A missing id, an empty one, and one without a `#`.
|
||||
r##"<path id="p" d="M0 20L150 20"/><text><textPath href="#none">Missing</textPath></text>
|
||||
<text><textPath href="#">Empty</textPath></text><text><textPath href="p">Bare</textPath></text>"##,
|
||||
// The first element with the id has no path; the later path is not used.
|
||||
r##"<g id="p"><path d="M0 20L150 20"/></g><path id="p" d="M0 80L150 80"/><text><textPath href="#p">Group</textPath></text>"##,
|
||||
// Ids on texts and groups, one of them named twice.
|
||||
r##"<g id="g"><text id="t"><textPath href="#t">Self</textPath></text></g><text id="g">Later</text><text><textPath href="#g">Group</textPath></text>"##,
|
||||
// Uses of texts on paths, and an inline path beside an href.
|
||||
r##"<defs><path id="p" d="M0 20L150 20"/><text id="t"><textPath href="#p">Used</textPath></text></defs>
|
||||
<use href="#t" font-size="30"/><use href="#t" y="40"/><text><textPath href="#p" path="M0 90L150 90">Inline</textPath></text>"##,
|
||||
];
|
||||
for body in cases {
|
||||
let map = imported(body, false);
|
||||
assert_eq!(map, imported(body, true), "{body}");
|
||||
assert!(!text_objects(&map.0).is_empty(), "{body}");
|
||||
}
|
||||
}
|
||||
|
||||
/// With two elements of one id, a `<textPath>` follows the first.
|
||||
#[test]
|
||||
fn a_text_path_follows_the_first_element_with_its_id() {
|
||||
let text = r##"<text font-size="12"><textPath href="#p">Path</textPath></text>"##;
|
||||
let first = text_objects(&imported(&format!(r#"<path id="p" d="M0 20L150 20"/><path id="p" d="M0 80L150 80"/>{text}"#), false).0);
|
||||
let only = text_objects(&imported(&format!(r#"<path id="p" d="M0 20L150 20"/><path id="q" d="M0 80L150 80"/>{text}"#), false).0);
|
||||
let second = text_objects(&imported(&format!(r#"<path id="q" d="M0 20L150 20"/><path id="p" d="M0 80L150 80"/>{text}"#), false).0);
|
||||
assert!(matches!(first[0].kind, TextKind::OnPath { .. }), "{:?}", first[0].kind);
|
||||
assert_eq!(first, only);
|
||||
assert_ne!(first, second);
|
||||
// A first element with no path leaves the text without one.
|
||||
let (doc, warnings) = imported(&format!(r#"<g id="p"/><path id="p" d="M0 80L150 80"/>{text}"#), false);
|
||||
assert!(!matches!(text_objects(&doc)[0].kind, TextKind::OnPath { .. }), "{warnings:?}");
|
||||
}
|
||||
|
||||
/// Times importing a file with 20,000 paths and 2,000 texts on paths, finding each `<textPath>`'s
|
||||
/// element through the map of ids and by walking the document for each one, after checking that
|
||||
/// the two give the same document. Run it with
|
||||
/// `cargo test --release -p vectorcraft-svg --lib text_path_lookup_timing -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "timing; run by hand in a release build"]
|
||||
fn text_path_lookup_timing() {
|
||||
let mut body = String::new();
|
||||
for i in 0..20_000 {
|
||||
let _ = write!(body, r#"<path id="p{i}" d="M0 {}L300 {}"/>"#, i % 400, i % 400);
|
||||
if i % 10 == 9 {
|
||||
let k = (i * 7919) % 20_000;
|
||||
let _ = write!(body, r##"<text font-size="8"><textPath href="#p{k}">L{i}</textPath></text>"##);
|
||||
}
|
||||
}
|
||||
let svg = format!(r#"<svg xmlns="http://www.w3.org/2000/svg" width="400" height="400">{body}</svg>"#);
|
||||
let run = |linear: bool| {
|
||||
LINEAR_IDS.set(linear);
|
||||
let start = std::time::Instant::now();
|
||||
let out = crate::import::import(&svg, &crate::ImportOptions::default(), crate::MAX_NODES);
|
||||
let took = start.elapsed();
|
||||
LINEAR_IDS.set(false);
|
||||
(out.unwrap_or_else(|e| panic!("{e}")), took)
|
||||
};
|
||||
let (map, _) = run(false);
|
||||
let (walk, _) = run(true);
|
||||
assert_eq!(map, walk);
|
||||
assert_eq!(text_objects(&map.0).len(), 2_000);
|
||||
let (mut maps, mut walks) = (vec![], vec![]);
|
||||
for _ in 0..7 {
|
||||
walks.push(run(true).1);
|
||||
maps.push(run(false).1);
|
||||
}
|
||||
println!("walk per textPath: {walks:?}");
|
||||
println!("map of ids: {maps:?}");
|
||||
walks.sort();
|
||||
maps.sort();
|
||||
println!("median: walk {:?}, map {:?}", walks[3], maps[3]);
|
||||
}
|
||||
|
||||
@@ -1355,15 +1355,35 @@ fn palette_window_state(modal: bool, popup: bool, active: bool) -> (egui::Window
|
||||
(level, true)
|
||||
}
|
||||
|
||||
/// How long none of the app's windows has focus before the app counts as inactive. Focus moving
|
||||
/// between the app's own windows passes through a frame where none has it (a press on a palette's
|
||||
/// bar takes it from the main window): lowering the palettes then let the window system give the
|
||||
/// keyboard to another palette in the middle of the press. craft-ui's docking waits as long.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const AWAY_DELAY: f64 = 0.25;
|
||||
|
||||
/// Sends the palette windows of `layout` the level and visibility [`palette_window_state`] gives
|
||||
/// when they change. craft-ui varies a palette's level through the viewport builder, which egui
|
||||
/// applies when the window opens and not to one already on screen, so the commands go explicitly to
|
||||
/// the windows there are. A window that opens while the others are hidden (a panel floated under a
|
||||
/// dialog, a menu, a flyout or the drawer) opens shown at its palette level, so it gets the commands
|
||||
/// in its first frame.
|
||||
/// in its first frame. The app is active until none of its windows has had focus for
|
||||
/// [`AWAY_DELAY`], counted from the first frame that saw none.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn palette_window_levels(ctx: &egui::Context, layout: &Layout<String>, modal: bool, popup: bool) {
|
||||
let active = ctx.input(|i| i.focused || i.raw.viewports.values().any(|v| v.focused == Some(true)));
|
||||
let (focused, now) = ctx.input(|i| (i.focused || i.raw.viewports.values().any(|v| v.focused == Some(true)), i.time));
|
||||
let away_key = area_id().with("palette-levels-away");
|
||||
let active = if focused {
|
||||
ctx.data_mut(|d| d.remove::<f64>(away_key));
|
||||
true
|
||||
} else {
|
||||
let since = ctx.data_mut(|d| *d.get_temp_mut_or_insert_with(away_key, || now));
|
||||
let left = AWAY_DELAY - (now - since);
|
||||
if left > 0.0 {
|
||||
ctx.request_repaint_after(std::time::Duration::from_secs_f64(left));
|
||||
}
|
||||
left > 0.0
|
||||
};
|
||||
let key = area_id().with("palette-levels-state");
|
||||
let state = (modal, popup, active);
|
||||
let windows: Vec<u64> = layout.floating.iter().map(|window| window.id).collect();
|
||||
|
||||
@@ -735,6 +735,40 @@ fn a_palette_window_keeps_out_of_the_way_of_the_main_windows_dialog_and_menus()
|
||||
assert_ne!(inactive.0, WindowLevel::AlwaysOnTop, "and not above other applications' windows: {:?}", inactive.0);
|
||||
}
|
||||
|
||||
/// Focus moving between the app's own windows passes through a frame where none has it: the
|
||||
/// palettes keep their level then, or the window system hands the keyboard to another palette in
|
||||
/// the middle of a press on a palette's bar. They leave the top level once the app has had no
|
||||
/// focus for a while.
|
||||
#[test]
|
||||
fn focus_moving_between_the_apps_windows_leaves_the_palettes_on_top() {
|
||||
let mut h = Harness::new();
|
||||
let viewport = h.float("navigator");
|
||||
h.host.borrow_mut().focus = ViewportId::ROOT;
|
||||
h.frames(2);
|
||||
take_palette_commands(&h, viewport);
|
||||
let nowhere = ViewportId::from_hash_of("no window of the app");
|
||||
h.host.borrow_mut().focus = nowhere;
|
||||
h.frames(1);
|
||||
h.host.borrow_mut().focus = viewport;
|
||||
h.frames(2);
|
||||
assert_eq!(take_palette_commands(&h, viewport), (vec![], vec![]), "a frame without focus leaves the palette's level");
|
||||
// The wait starts again each time focus leaves: a second frame without focus, longer after
|
||||
// the first than the wait, leaves the level too.
|
||||
h.frames(6);
|
||||
h.host.borrow_mut().focus = nowhere;
|
||||
h.frames(1);
|
||||
h.host.borrow_mut().focus = ViewportId::ROOT;
|
||||
h.frames(2);
|
||||
assert_eq!(take_palette_commands(&h, viewport), (vec![], vec![]), "the wait is counted from when focus last left");
|
||||
h.host.borrow_mut().focus = nowhere;
|
||||
h.frames(8);
|
||||
let (_, levels) = take_palette_commands(&h, viewport);
|
||||
assert_eq!(levels.last(), Some(&palette_window_state(false, false, false).0), "the app left: the palette leaves the top level");
|
||||
h.host.borrow_mut().focus = ViewportId::ROOT;
|
||||
h.frames(2);
|
||||
assert_eq!(take_palette_commands(&h, viewport).1, [egui::WindowLevel::AlwaysOnTop], "and takes it again when the app is back");
|
||||
}
|
||||
|
||||
/// With a menu of the in-window menu bar open, the palettes take the normal level (still shown):
|
||||
/// the menu is drawn in the main window, or it would open under them.
|
||||
#[test]
|
||||
|
||||
@@ -177,6 +177,19 @@ fn guide_row(ui: &mut Ui, view: &View, item: &Row, i: usize, out: &mut Out) {
|
||||
}
|
||||
out.actions.push(("guide.select".into(), json!({"indexes": [i], "toggle": m.shift || m.command})));
|
||||
}
|
||||
if resp.secondary_clicked() {
|
||||
crate::panels::set_row_keys(ui.ctx(), ROW_KEYS, true);
|
||||
if editable && !selected {
|
||||
if !view.rows.is_empty() {
|
||||
out.actions.push(("layer.highlight".into(), json!({"ids": [], "mode": "set"})));
|
||||
out.rows_after_click = Some(vec![]);
|
||||
}
|
||||
out.actions.push(("guide.select".into(), json!({"indexes": [i]})));
|
||||
}
|
||||
}
|
||||
resp.context_menu(|ui| {
|
||||
guide_context_menu(ui, view, item, i, out);
|
||||
});
|
||||
// Dragged: the selected guides when this is one of them, else this one, to another layer's row.
|
||||
// Only the primary button drags a guide row, and not while a drag down a column passes it.
|
||||
if editable && resp.drag_started_by(egui::PointerButton::Primary) && view.column.is_none() {
|
||||
@@ -194,6 +207,46 @@ fn guide_row(ui: &mut Ui, view: &View, item: &Row, i: usize, out: &mut Out) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The right-click context menu of ruler guide row `i` (`item`).
|
||||
fn guide_context_menu(ui: &mut Ui, view: &View, item: &Row, i: usize, out: &mut Out) {
|
||||
let Some(g) = view.ruler_guides.get(i) else { return };
|
||||
let selected = view.guides.contains(&i);
|
||||
let editable = view.doc.guide_editable(g);
|
||||
let guides: Vec<usize> = if selected { view.guides.clone() } else { vec![i] };
|
||||
let node = g.id.and_then(|id| view.doc.node(id));
|
||||
let guide_nodes: Vec<u64> = if selected {
|
||||
guides.iter().filter_map(|&idx| view.ruler_guides.get(idx)?.id.map(|id| id.0)).collect()
|
||||
} else {
|
||||
node.map(|n| vec![n.id.0]).unwrap_or_default()
|
||||
};
|
||||
let visible = node.is_none_or(|n| n.visible);
|
||||
if widgets::menu_item(ui, if visible { "Hide" } else { "Show" }, !guide_nodes.is_empty(), false) {
|
||||
out.actions.push(("layer.setProps".into(), json!({ "ids": guide_nodes, "visible": !visible })));
|
||||
ui.close();
|
||||
}
|
||||
let locked = node.is_some_and(|n| n.locked);
|
||||
if widgets::menu_item(ui, if locked { "Unlock" } else { "Lock" }, !guide_nodes.is_empty(), false) {
|
||||
out.actions.push(("layer.setProps".into(), json!({ "ids": guide_nodes, "locked": !locked })));
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
if widgets::menu_item(ui, "Release Guides", editable, false) {
|
||||
let params = if guides.len() > 1 { json!({}) } else { json!({ "index": i }) };
|
||||
out.actions.push(("view.guides.release".into(), params));
|
||||
ui.close();
|
||||
}
|
||||
if widgets::menu_item(ui, "Delete", editable, false) {
|
||||
out.actions.push(("guide.remove".into(), json!({ "indexes": guides })));
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
let layers_only = view.opts.layers_only;
|
||||
if widgets::menu_item(ui, if layers_only { "Locate Layer" } else { "Locate Object" }, true, false) {
|
||||
out.actions.push(("layer.locate".into(), json!({ "id": item.node.id.0, "layersOnly": layers_only })));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
|
||||
/// The row of the spine of blend `item` (#4820): a path mark and `<Path>`, the selection square
|
||||
/// while the blend is selected. A click selects the blend, whose spine Direct Selection then edits
|
||||
/// on the canvas; Shift or Cmd adds it to (or takes it from) the selection. The spine of a hidden
|
||||
@@ -233,6 +286,64 @@ fn spine_row(ui: &mut Ui, view: &View, item: &Row, out: &mut Out) {
|
||||
let action = if m.shift || m.command { "select.toggle" } else { "select.set" };
|
||||
out.actions.push((action.into(), json!({"ids": [blend.0]})));
|
||||
}
|
||||
if resp.secondary_clicked() {
|
||||
crate::panels::set_row_keys(ui.ctx(), ROW_KEYS, true);
|
||||
if editable && !selected {
|
||||
out.actions.push(("select.set".into(), json!({"ids": [blend.0]})));
|
||||
}
|
||||
}
|
||||
resp.context_menu(|ui| {
|
||||
spine_context_menu(ui, view, item, out);
|
||||
});
|
||||
}
|
||||
|
||||
/// The right-click context menu of blend spine row `item`.
|
||||
fn spine_context_menu(ui: &mut Ui, view: &View, item: &Row, out: &mut Out) {
|
||||
let blend = item.node.id;
|
||||
let selected = view.sel.contains(&blend);
|
||||
let editable = (view.doc.editable())(blend);
|
||||
let has_spine = !matches!(&item.node.kind, NodeKind::Blend { spec, .. } if spec.no_spine);
|
||||
let ensure_selected = |out: &mut Out| {
|
||||
if !selected {
|
||||
out.actions.push(("select.set".into(), json!({ "ids": [blend.0] })));
|
||||
}
|
||||
};
|
||||
if widgets::menu_item(ui, "Select", editable, false) {
|
||||
out.actions.push(("select.set".into(), json!({ "ids": [blend.0] })));
|
||||
ui.close();
|
||||
}
|
||||
if widgets::menu_item(ui, "Blend Options…", editable, false) {
|
||||
ensure_selected(out);
|
||||
out.actions.push(("ui.blendOptions".into(), json!({})));
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
if widgets::menu_item(ui, "Reverse Spine", editable && has_spine, false) {
|
||||
ensure_selected(out);
|
||||
out.actions.push(("object.blend.reverseSpine".into(), json!({})));
|
||||
ui.close();
|
||||
}
|
||||
if widgets::menu_item(ui, "Reverse Front to Back", editable, false) {
|
||||
ensure_selected(out);
|
||||
out.actions.push(("object.blend.reverseFrontToBack".into(), json!({})));
|
||||
ui.close();
|
||||
}
|
||||
if widgets::menu_item(ui, "Expand", editable, false) {
|
||||
ensure_selected(out);
|
||||
out.actions.push(("object.blend.expand".into(), json!({})));
|
||||
ui.close();
|
||||
}
|
||||
if widgets::menu_item(ui, "Release", editable, false) {
|
||||
ensure_selected(out);
|
||||
out.actions.push(("object.blend.release".into(), json!({})));
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
let layers_only = view.opts.layers_only;
|
||||
if widgets::menu_item(ui, if layers_only { "Locate Layer" } else { "Locate Object" }, true, false) {
|
||||
out.actions.push(("layer.locate".into(), json!({ "id": blend.0, "layersOnly": layers_only })));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
|
||||
/// Guide rows `guides` dragged over row `r` (`resp`) of layer `layer`: the row lights up, and the
|
||||
|
||||
@@ -3006,3 +3006,206 @@ fn context_menu_others_actions_sublayer_state_enables_all_commands() {
|
||||
assert_eq!(lock_cmd, "layer.unlockAll");
|
||||
assert!(lock_enabled, "locked sublayer enables Unlock All Layers");
|
||||
}
|
||||
|
||||
/// One headless frame of the panel in a 300 × 600 window, returning every drawn text and its rect.
|
||||
fn frame_texts(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) -> Vec<(String, egui::Rect)> {
|
||||
let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::pos2(0.0, 0.0), vec2(300.0, 600.0))), events, ..Default::default() };
|
||||
let mut out = ctx.run_ui(raw, |ui| show(app, ui));
|
||||
out.textures_delta.clear();
|
||||
let mut texts = vec![];
|
||||
for s in out.shapes {
|
||||
if let egui::epaint::Shape::Text(t) = s.shape {
|
||||
texts.push((t.galley.text().to_string(), t.galley.rect.translate(t.pos.to_vec2())));
|
||||
}
|
||||
}
|
||||
texts
|
||||
}
|
||||
|
||||
/// Click `button` at `pos` (pressed in one frame, released in the next) and return the texts drawn
|
||||
/// on the frame after release.
|
||||
fn click_menu_at(app: &mut VectorcraftApp, ctx: &egui::Context, pos: egui::Pos2, button: egui::PointerButton) -> Vec<(String, egui::Rect)> {
|
||||
let ev = |pressed| egui::Event::PointerButton { pos, button, pressed, modifiers: Default::default() };
|
||||
frame_texts(app, ctx, vec![egui::Event::PointerMoved(pos), ev(true)]);
|
||||
frame_texts(app, ctx, vec![ev(false)]);
|
||||
frame_texts(app, ctx, vec![])
|
||||
}
|
||||
|
||||
/// The menu item labels in `texts` (which start with `" "`), ordered from top to bottom.
|
||||
fn menu_entries(texts: &[(String, egui::Rect)]) -> Vec<String> {
|
||||
let mut entries: Vec<_> = texts.iter().filter(|(t, _)| t.starts_with(" ")).map(|(t, r)| (t.trim().to_string(), r.top())).collect();
|
||||
entries.sort_by(|a, b| a.1.total_cmp(&b.1));
|
||||
entries.into_iter().map(|(t, _)| t).collect()
|
||||
}
|
||||
|
||||
fn text_rect(texts: &[(String, egui::Rect)], name: &str) -> egui::Rect {
|
||||
texts.iter().find(|(t, _)| t == name).map(|(_, r)| *r).unwrap_or_else(|| panic!("{name} not in {texts:?}"))
|
||||
}
|
||||
|
||||
/// Right-clicking a ruler guide row selects the guide (or keeps a multi-guide selection), opens its
|
||||
/// context menu (Hide/Show, Lock/Unlock, Release Guides, Delete, Locate Object), and each item
|
||||
/// dispatches its command with Undo/Redo registration (#8592).
|
||||
#[test]
|
||||
fn guide_row_context_menu_selects_and_runs_guide_actions() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
|
||||
run(&mut app, "file.new", json!({"width": 200, "height": 200}));
|
||||
run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20}));
|
||||
run(&mut app, "guide.add", json!({"vertical": true, "pos": 50}));
|
||||
run(&mut app, "guide.add", json!({"vertical": false, "pos": 80}));
|
||||
run(&mut app, "select.none", json!({}));
|
||||
let layer = app.session.active().unwrap().doc.layers[0].id;
|
||||
run(&mut app, "layer.highlight", json!({"ids": [layer.0], "mode": "set"}));
|
||||
expand(&mut app, &json!({})).unwrap();
|
||||
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let texts = frame_texts(&mut app, &ctx, vec![]);
|
||||
let h_guide_pos = text_rect(&texts, "<Horizontal Guide>").center();
|
||||
let v_guide_pos = text_rect(&texts, "<Vertical Guide>").center();
|
||||
let selected_guides = |app: &VectorcraftApp| {
|
||||
let st = app.session.active().unwrap();
|
||||
vectorcraft_engine::cmd::guide_indexes(&st.doc, &st.selection.guides)
|
||||
};
|
||||
|
||||
// Right-clicking an unselected guide row selects it, clears highlighted rows, and opens the menu.
|
||||
let menu = click_menu_at(&mut app, &ctx, v_guide_pos, egui::PointerButton::Secondary);
|
||||
assert_eq!(selected_guides(&app), [0], "right-click selects the guide");
|
||||
assert!(rows_of(&app).is_empty(), "highlighted rows cleared when selecting a guide");
|
||||
assert_eq!(menu_entries(&menu), ["Hide", "Lock", "Release Guides", "Delete", "Locate Object"]);
|
||||
|
||||
// Hide toggles the guide's visibility off in one undo step; right-clicking again shows "Show".
|
||||
let guide_node = app.session.active().unwrap().doc.ruler_guides()[0].id.unwrap();
|
||||
let undo_before = app.session.active().unwrap().history.undo.len();
|
||||
click_menu_at(&mut app, &ctx, text_rect(&menu, " Hide").center(), egui::PointerButton::Primary);
|
||||
assert!(!app.session.active().unwrap().doc.node(guide_node).unwrap().visible);
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), undo_before + 1);
|
||||
let menu = click_menu_at(&mut app, &ctx, v_guide_pos, egui::PointerButton::Secondary);
|
||||
assert_eq!(menu_entries(&menu), ["Show", "Lock", "Release Guides", "Delete", "Locate Object"]);
|
||||
click_menu_at(&mut app, &ctx, text_rect(&menu, " Show").center(), egui::PointerButton::Primary);
|
||||
assert!(app.session.active().unwrap().doc.node(guide_node).unwrap().visible);
|
||||
|
||||
// Lock toggles the guide's lock on in one undo step; right-clicking again shows "Unlock".
|
||||
let menu = click_menu_at(&mut app, &ctx, v_guide_pos, egui::PointerButton::Secondary);
|
||||
click_menu_at(&mut app, &ctx, text_rect(&menu, " Lock").center(), egui::PointerButton::Primary);
|
||||
assert!(app.session.active().unwrap().doc.node(guide_node).unwrap().locked);
|
||||
let menu = click_menu_at(&mut app, &ctx, v_guide_pos, egui::PointerButton::Secondary);
|
||||
assert_eq!(menu_entries(&menu), ["Hide", "Unlock", "Release Guides", "Delete", "Locate Object"]);
|
||||
click_menu_at(&mut app, &ctx, text_rect(&menu, " Unlock").center(), egui::PointerButton::Primary);
|
||||
assert!(!app.session.active().unwrap().doc.node(guide_node).unwrap().locked);
|
||||
|
||||
// Locate Object locates the guide's holding layer.
|
||||
let menu = click_menu_at(&mut app, &ctx, v_guide_pos, egui::PointerButton::Secondary);
|
||||
click_menu_at(&mut app, &ctx, text_rect(&menu, " Locate Object").center(), egui::PointerButton::Primary);
|
||||
assert_eq!(rows_of(&app), vec![layer]);
|
||||
|
||||
// Multi-guide selection is preserved when right-clicking an already-selected guide row.
|
||||
run(&mut app, "guide.select", json!({"indexes": [0, 1]}));
|
||||
let _menu = click_menu_at(&mut app, &ctx, h_guide_pos, egui::PointerButton::Secondary);
|
||||
assert_eq!(selected_guides(&app), [0, 1], "right-click on selected guide preserves multi-guide selection");
|
||||
|
||||
// Release Guides on a single guide converts it into a path in one undo step; Undo brings it back.
|
||||
run(&mut app, "guide.select", json!({"indexes": [0]}));
|
||||
let menu = click_menu_at(&mut app, &ctx, v_guide_pos, egui::PointerButton::Secondary);
|
||||
let undo_before = app.session.active().unwrap().history.undo.len();
|
||||
click_menu_at(&mut app, &ctx, text_rect(&menu, " Release Guides").center(), egui::PointerButton::Primary);
|
||||
assert_eq!(app.session.active().unwrap().doc.ruler_guides().len(), 1, "one guide released to a path");
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), undo_before + 1);
|
||||
run(&mut app, "edit.undo", json!({}));
|
||||
assert_eq!(app.session.active().unwrap().doc.ruler_guides().len(), 2, "Undo restores the released guide");
|
||||
|
||||
// Delete removes the guide in one undo step; Undo restores it.
|
||||
let texts = frame_texts(&mut app, &ctx, vec![]);
|
||||
let v_guide_pos = text_rect(&texts, "<Vertical Guide>").center();
|
||||
let menu = click_menu_at(&mut app, &ctx, v_guide_pos, egui::PointerButton::Secondary);
|
||||
let undo_before = app.session.active().unwrap().history.undo.len();
|
||||
click_menu_at(&mut app, &ctx, text_rect(&menu, " Delete").center(), egui::PointerButton::Primary);
|
||||
assert_eq!(app.session.active().unwrap().doc.ruler_guides().len(), 1, "Delete removes the guide");
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), undo_before + 1);
|
||||
run(&mut app, "edit.undo", json!({}));
|
||||
assert_eq!(app.session.active().unwrap().doc.ruler_guides().len(), 2, "Undo restores the deleted guide");
|
||||
}
|
||||
|
||||
/// Right-clicking a blend spine row selects the blend, opens its context menu (Select, Blend
|
||||
/// Options…, Reverse Spine, Reverse Front to Back, Expand, Release, Locate Object), and each item
|
||||
/// dispatches its command with Undo/Redo registration (#8592).
|
||||
#[test]
|
||||
fn spine_row_context_menu_selects_blend_and_runs_blend_actions() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
|
||||
run(&mut app, "file.new", json!({"width": 300, "height": 200}));
|
||||
let a = NodeId(run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20}))["id"].as_u64().unwrap());
|
||||
let b = NodeId(run(&mut app, "shape.rectangle", json!({"x": 200, "y": 0, "width": 20, "height": 20}))["id"].as_u64().unwrap());
|
||||
run(&mut app, "select.set", json!({"ids": [a.0, b.0]}));
|
||||
let blend = NodeId(run(&mut app, "object.blend.make", json!({}))["id"].as_u64().unwrap());
|
||||
run(&mut app, "select.none", json!({}));
|
||||
expand(&mut app, &json!({})).unwrap();
|
||||
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let spine_rect = |texts: &[(String, egui::Rect)]| {
|
||||
texts
|
||||
.iter()
|
||||
.filter(|(t, _)| t == "<Path>")
|
||||
.max_by(|x, y| x.1.top().total_cmp(&y.1.top()))
|
||||
.map(|(_, r)| *r)
|
||||
.unwrap_or_else(|| panic!("spine <Path> not in {texts:?}"))
|
||||
};
|
||||
let texts = frame_texts(&mut app, &ctx, vec![]);
|
||||
let spine_pos = spine_rect(&texts).center();
|
||||
let selected = |app: &VectorcraftApp| app.session.active().unwrap().selection.objects.to_vec();
|
||||
|
||||
// Right-clicking the unselected spine row selects the blend and opens the context menu.
|
||||
let menu = click_menu_at(&mut app, &ctx, spine_pos, egui::PointerButton::Secondary);
|
||||
assert_eq!(selected(&app), [blend], "right-clicking the spine row selects the blend");
|
||||
assert_eq!(menu_entries(&menu), ["Select", "Blend Options…", "Reverse Spine", "Reverse Front to Back", "Expand", "Release", "Locate Object"]);
|
||||
|
||||
// Blend Options… opens the Blend Options dialog.
|
||||
click_menu_at(&mut app, &ctx, text_rect(&menu, " Blend Options…").center(), egui::PointerButton::Primary);
|
||||
assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("blendOptions"));
|
||||
crate::dialogs::cancel(&mut app);
|
||||
|
||||
// Reverse Spine reverses the key positions along the spine in one undo step.
|
||||
let key_x = |app: &VectorcraftApp, id: NodeId| app.session.active().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap().x0;
|
||||
let a_x_before = key_x(&app, a);
|
||||
let b_x_before = key_x(&app, b);
|
||||
let undo_before = app.session.active().unwrap().history.undo.len();
|
||||
let menu = click_menu_at(&mut app, &ctx, spine_pos, egui::PointerButton::Secondary);
|
||||
click_menu_at(&mut app, &ctx, text_rect(&menu, " Reverse Spine").center(), egui::PointerButton::Primary);
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), undo_before + 1);
|
||||
assert!((key_x(&app, a) - b_x_before).abs() < 1e-6 && (key_x(&app, b) - a_x_before).abs() < 1e-6);
|
||||
|
||||
// Reverse Front to Back reverses the key stacking order in one undo step.
|
||||
let key_ids = |app: &VectorcraftApp| -> Vec<NodeId> {
|
||||
app.session.active().unwrap().doc.node(blend).unwrap().children().unwrap().iter().map(|c| c.id).collect()
|
||||
};
|
||||
assert_eq!(key_ids(&app), [a, b]);
|
||||
let menu = click_menu_at(&mut app, &ctx, spine_pos, egui::PointerButton::Secondary);
|
||||
click_menu_at(&mut app, &ctx, text_rect(&menu, " Reverse Front to Back").center(), egui::PointerButton::Primary);
|
||||
assert_eq!(key_ids(&app), [b, a]);
|
||||
|
||||
// Locate Object highlights the blend row.
|
||||
let menu = click_menu_at(&mut app, &ctx, spine_pos, egui::PointerButton::Secondary);
|
||||
click_menu_at(&mut app, &ctx, text_rect(&menu, " Locate Object").center(), egui::PointerButton::Primary);
|
||||
assert_eq!(rows_of(&app), vec![blend]);
|
||||
|
||||
// Expand replaces the blend with a group in one undo step; Undo brings the blend back.
|
||||
let menu = click_menu_at(&mut app, &ctx, spine_pos, egui::PointerButton::Secondary);
|
||||
let undo_before = app.session.active().unwrap().history.undo.len();
|
||||
click_menu_at(&mut app, &ctx, text_rect(&menu, " Expand").center(), egui::PointerButton::Primary);
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), undo_before + 1);
|
||||
assert!(matches!(app.session.active().unwrap().doc.node(blend).unwrap().kind, NodeKind::Group { .. }));
|
||||
run(&mut app, "edit.undo", json!({}));
|
||||
assert!(matches!(app.session.active().unwrap().doc.node(blend).unwrap().kind, NodeKind::Blend { .. }));
|
||||
|
||||
// Release releases the blend into its keys and spine path in one undo step; Undo restores it.
|
||||
expand(&mut app, &json!({})).unwrap();
|
||||
let texts = frame_texts(&mut app, &ctx, vec![]);
|
||||
let spine_pos = spine_rect(&texts).center();
|
||||
let menu = click_menu_at(&mut app, &ctx, spine_pos, egui::PointerButton::Secondary);
|
||||
let undo_before = app.session.active().unwrap().history.undo.len();
|
||||
click_menu_at(&mut app, &ctx, text_rect(&menu, " Release").center(), egui::PointerButton::Primary);
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), undo_before + 1);
|
||||
assert!(app.session.active().unwrap().doc.node(blend).is_none(), "blend released into keys and spine path");
|
||||
run(&mut app, "edit.undo", json!({}));
|
||||
assert!(matches!(app.session.active().unwrap().doc.node(blend).unwrap().kind, NodeKind::Blend { .. }));
|
||||
}
|
||||
|
||||
@@ -3781,7 +3781,22 @@ mod tests {
|
||||
let (csv_off, csv_on) = (String::from_utf8_lossy(csv_off), String::from_utf8_lossy(csv_on));
|
||||
assert!(!csv_off.contains(&hold), "off, the CSV file lists no hold");
|
||||
assert!(csv_on.contains(&swap[0].shortcut), "on, the CSV file lists it: {}", swap[0].shortcut);
|
||||
assert_eq!(sheet_off, sheet_off_again, "the sheet is the same each time");
|
||||
// The writer stamps each file with the clock: its dates and its ID (fixed width), which differ
|
||||
// between two exports a second apart. The rest of the file is the same each time.
|
||||
let unstamped = |pdf: &[u8]| {
|
||||
let mut b: Vec<u8> = pdf.iter().map(|&c| if c.is_ascii_digit() { b'0' } else { c }).collect();
|
||||
for key in [&b"InstanceID>"[..], b"DocumentID>", b"/ID["] {
|
||||
let mut at = 0;
|
||||
while let Some(i) = b[at..].windows(key.len()).position(|w| w == key) {
|
||||
let start = at + i + key.len();
|
||||
let end = b[start..].iter().position(|&c| c == b'<' || c == b']').map_or(b.len(), |e| start + e);
|
||||
b[start..end].fill(b'?');
|
||||
at = end;
|
||||
}
|
||||
}
|
||||
b
|
||||
};
|
||||
assert_eq!(unstamped(sheet_off), unstamped(sheet_off_again), "the sheet is the same each time");
|
||||
assert_ne!(sheet_off, sheet_on, "on, the sheet lists the hold");
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because one or more lines are too long
+3
-1
@@ -40,6 +40,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 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. |
|
||||
| 2026-11-15 | minor | G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `ui.checkSpelling`, #4936) with Not in Dictionary sentence context, suggestions, Ignore, Ignore All, Change, Change All, Add to Dictionary, Done/Cancel, keyboard navigation, and one-step Undo/Redo; spell check complete; scores and estimates unchanged. |
|
||||
@@ -534,12 +535,13 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
|
||||
run hyphenates in its own language (Character panel). English, eleven Indian languages, Bulgarian, Turkish
|
||||
and Russian have break points, and German, Polish, Portuguese and Italian have them in builds that embed
|
||||
their patterns; other languages stay whole apart from the Exceptions list (#394, #4947).
|
||||
- **Done (2026-11-18, #8592):** Layers panel guide and blend spine row context menus: right-clicking a ruler guide row shows Hide / Show, Lock / Unlock, Release Guides, Delete and Locate Object / Locate Layer (selecting an unselected editable guide or preserving a multi-guide selection); right-clicking a blend spine row selects the blend and shows Select, Blend Options…, Reverse Spine, Reverse Front to Back, Expand, Release and Locate Object / Locate Layer. Tests in `crates/ui-egui/src/panels/layers/tests.rs`.
|
||||
- **Done (2026-11-14):** Layers panel row context menu: right-clicking a layer, group, or object row shows a context menu (Options…, Duplicate, Delete, Lock Others / Unlock All, Hide Others / Show All, Locate Object, Collect for Export) with proper selection behavior and Undo/Redo tracking. Tests in `crates/ui-egui/src/panels/layers/tests.rs`.
|
||||
- **Missing:** 2 Preferences options stored but not acted on (#394), each waiting on a subsystem of its own:
|
||||
Plug-ins & Scratch Disks › Primary and Secondary (documents are kept in memory; nothing pages to
|
||||
disk), and Clipboard Handling › Legacy vector clipboard with its Preserve Paths / Preserve Appearance and
|
||||
Overprints choice (Illustrator's own clipboard flavour, which has no public specification). Also Properties
|
||||
panel per context, context menus in the panels that have none, and menus on guide and blend spine rows in the Layers panel.
|
||||
panel per context, and context menus in the panels that have none.
|
||||
- **Impact:** settings that silently do nothing erode trust.
|
||||
- **Estimate:** 13–20 h.
|
||||
|
||||
|
||||
+3
-2
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+5
-3
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user