Recolor Artwork: a swatch picked for a row keeps the art linked to it

A spot or global swatch picked for a row's new color in the Color
Picker's swatch list now stays that swatch: with Scale Tints or
Preserve Tints the row's art becomes tints of the swatch linked to it,
also with no Limit to Library, so editing the swatch recolors the art.
A process swatch gives its color, as before. Before this change the
picker passed only the color, and the art took unlinked tints.

recolor.apply rows take swatch: {name, library?}. Of the swatches with
that name, the first with the row's new color is used; when it is a
global or spot swatch and no Global Adjust applies without Limit to
Library, the row's art links to it. A process swatch, or a swatch or
library that is not there, links nothing, and the result lists the
names that are not there in swatchesNotFound; a malformed swatch is an
error. Rows that pick two library swatches of one name each link to
their own added swatch. recolor.randomize moves a row's swatch with its
color.

In the dialog, the Tint slider shows for a row whose picked swatch is a
spot color, a row's swatch goes when its new color changes or a process
swatch is picked for it, and a row whose swatch no longer links its art
shows the full color. Over Recolor Artwork, the picker lists the
document's swatches as they were before the preview.

The rows of the picker's swatch list are now buttons named for their
swatch, so screen readers can read them.
This commit is contained in:
dotCooCoo
2026-11-22 09:21:26 -08:00
parent db9acab4da
commit d199b0d257
7 changed files with 681 additions and 36 deletions
+81 -21
View File
@@ -43,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Recolor Artwork",
["Edit", "Edit Colors"],
None,
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null | \"keep\"] (what the color swatches of `group` are rewritten with, in order: a gradient, pattern or None swatch keeps its place and paint; a null removing the color swatch at its place and \"keep\" leaving that swatch its colour, without the Global Adjust (past the color swatches it adds nothing); default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}",
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo or swatch, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`), swatch?: {name, library?: swatch library id or name; \"document\" (default)} (the swatch the new color was picked from: of the swatches with the name, the first with the row's new color (as a color key); while it is a global or spot swatch and there is no globalAdjust (or limitTo is given), the row's art takes the swatch as with limitTo, linked to it at its tints; a process swatch, or a swatch or library that is not there, links nothing; a `swatch` that is not {name, library?} is an error)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null | \"keep\"] (what the color swatches of `group` are rewritten with, in order: a gradient, pattern or None swatch keeps its place and paint; a null removing the color swatch at its place and \"keep\" leaving that swatch its colour, without the Global Adjust (past the color swatches it adds nothing); default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], swatchesNotFound?: [names of rows' `swatch` that are not there, which linked nothing], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}",
has_doc,
apply
),
@@ -61,7 +61,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Randomize Colors",
[],
None,
"{map: rows as recolor.apply (an excluded row, or a row whose from is empty, keeps its new color), order?: true (shuffle the new colours among the rows that aren't excluded and hold current colors), saturationBrightness?: false (random saturation and brightness, hue kept), seed?: 0} → {map: the rows with their new colours as keys}",
"{map: rows as recolor.apply (an excluded row, or a row whose from is empty, keeps its new color), order?: true (shuffle the new colours among the rows that aren't excluded and hold current colors), saturationBrightness?: false (random saturation and brightness, hue kept), seed?: 0} → {map: the rows with their new colours as keys; a row's tint and swatch move with its new color and are dropped when the color changes}",
always,
randomize
),
@@ -1457,6 +1457,9 @@ struct Row {
/// `added`: with no current colors, the new color is a color added to the group, which it
/// joins after the colors of the rows with current colors.
added: bool,
/// `swatch`: the library key ("document" for the document's swatches) and the name of the
/// swatch the new color was picked from.
swatch: Option<(String, String)>,
}
/// The color model a row's colors take (`model`): each color's own, the new color's, or the
@@ -1512,7 +1515,9 @@ fn parse_rows(p: &Value, cmd: &str) -> Result<Vec<Row>> {
match p.get("map") {
Some(Value::Object(m)) => m
.iter()
.map(|(k, v)| Ok(Row { from: vec![cur(&json!(k))?], to: new(Some(v))?, exclude: false, tint: 1.0, model: None, added: false }))
.map(|(k, v)| {
Ok(Row { from: vec![cur(&json!(k))?], to: new(Some(v))?, exclude: false, tint: 1.0, model: None, added: false, swatch: None })
})
.collect(),
Some(Value::Array(rows)) => rows
.iter()
@@ -1525,7 +1530,21 @@ fn parse_rows(p: &Value, cmd: &str) -> Result<Vec<Row>> {
let tint = (super::number_or(r, "tint", 100.0, cmd)? / 100.0).clamp(0.0, 1.0) as f32;
let model = ModelRule::param(r, cmd)?;
let added = switch_or(r, "added", false, cmd)?;
Ok(Row { from, to: new(r.get("to"))?, exclude: switch_or(r, "exclude", false, cmd)?, tint, model, added })
let swatch = match r.get("swatch") {
None | Some(Value::Null) => None,
Some(w) => {
let name = w.get("name").and_then(Value::as_str).filter(|n| !n.is_empty());
let library = match w.get("library") {
None | Some(Value::Null) => Some(super::swatchlib::DOCUMENT_SWATCHES),
Some(l) => l.as_str().filter(|l| !l.is_empty()),
};
match (name, library) {
(Some(n), Some(l)) => Some((l.to_string(), n.to_string())),
_ => return Err(bad(cmd, format!("a row's `swatch` must be {{name, library?}} with a name and a library id: {w}"))),
}
}
};
Ok(Row { from, to: new(r.get("to"))?, exclude: switch_or(r, "exclude", false, cmd)?, tint, model, added, swatch })
})
.collect(),
_ => Err(bad(cmd, "missing `map` (rows [{from, to}] or {current: new})")),
@@ -1714,10 +1733,33 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
Some(k) => super::swatchlib::library_swatches(s, k).unwrap_or_default(),
None => vec![],
};
// A row's own `swatch`, the one its new color was picked from: of the swatches with its name, the
// first with the row's new color (as a color key, which rounds), when that one is a global or
// spot swatch and no Global Adjust changes the colors the row maps. A swatch or library that is
// not there (deleted since the pick) links nothing, and the result names it. Limit to Library's
// swatch of that color comes first.
let same = |a: Color, b: Color| ColorKey::of(&a) == ColorKey::of(&b);
let mut not_found: Vec<String> = vec![];
let picked: Vec<Option<Swatch>> = rows
.iter()
.map(|r| {
let (lib, name) = r.swatch.as_ref()?;
let list = super::swatchlib::library_swatches(s, lib).filter(|l| l.iter().any(|w| w.name == *name));
if list.is_none() {
not_found.push(name.clone());
}
let to = r.new_color()?;
let w = list?.into_iter().find(|w| w.name == *name && w.paint.color().is_some_and(|c| same(c, to)))?;
Some(w).filter(|w| (w.global || w.spot) && mapped_adjust.is_identity())
})
.collect();
// A row with no current colors recolors nothing, so its swatch does not join the document.
let row_swatches: Vec<Option<Swatch>> = rows
.iter()
.map(|r| r.new_color().filter(|_| !r.from.is_empty()).and_then(|c| lib_swatches.iter().find(|w| w.paint.color() == Some(c)).cloned()))
.zip(picked)
.map(|(r, own)| {
r.new_color().filter(|_| !r.from.is_empty()).and_then(|c| lib_swatches.iter().find(|w| w.paint.color() == Some(c)).cloned().or(own))
})
.collect();
// While an object of a dynamic symbol instance's art is selected, the selection is refused, as
// `selected_roots` refuses it.
@@ -1794,19 +1836,28 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
// The rows' library swatches join the document (one it has with that name and colour is
// used as it is).
let mut added = vec![];
// Each library swatch added under a free name, with its library name: rows that took two
// library swatches of one name both find theirs again.
let mut renamed: Vec<(String, Swatch)> = vec![];
let links: Vec<Option<Link>> = row_swatches
.iter()
.zip(&rows)
.map(|(w, row)| {
let w = w.as_ref()?;
// A swatch is the same one when its paint, Global and spot are.
let alike = |x: &Swatch| x.paint == w.paint && x.global == w.global && x.spot == w.spot;
let name = match d.swatch(&w.name) {
Some(x) if x.paint == w.paint => w.name.clone(),
_ => {
let name = d.free_swatch_name(&w.name);
d.swatches.push(Swatch { name: name.clone(), ..w.clone() });
added.push(name.clone());
name
}
Some(x) if alike(x) => w.name.clone(),
_ => match renamed.iter().find(|(_, x)| x.name == w.name && alike(x)) {
Some((name, _)) => name.clone(),
None => {
let name = d.free_swatch_name(&w.name);
d.swatches.push(Swatch { name: name.clone(), ..w.clone() });
added.push(name.clone());
renamed.push((name.clone(), w.clone()));
name
}
},
};
let color = d.global_color(&name).filter(|_| w.global).or(w.paint.color())?;
Some(Link { name, global: w.global, color, tint: row.tint })
@@ -1854,6 +1905,9 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
})?;
let mut out = json!({ "changed": changed, "swatches": added });
not_changed.report(&mut out);
if !not_found.is_empty() {
out["swatchesNotFound"] = json!(not_found);
}
if let Some(e) = edit {
e.defaults(s)?;
out["relinked"] = json!(e.relinked());
@@ -1872,21 +1926,21 @@ fn randomize(_: &mut Session, p: &Value) -> Result<Value> {
let rows = parse_rows(p, C)?;
let mut rng = Rng::new(super::menucmds::whole_or(p, "seed", 0, C)?);
let (order, saturation_brightness) = (switch_or(p, "order", true, C)?, switch_or(p, "saturationBrightness", false, C)?);
// Each new color with its row's tint and model: a tint moves with its color, and goes when
// the color changes; a model moves with its color. A row with no current colors recolors
// nothing, so it keeps its new color and takes no other row's.
// Each new color with its row's tint, model and swatch: a tint and a swatch move with their
// color, and go when the color changes; a model moves with its color. A row with no current
// colors recolors nothing, so it keeps its new color and takes no other row's.
let takes = |r: &Row| !r.from.is_empty() && r.new_color().is_some();
let mut news: Vec<(Color, f32, Option<ModelRule>)> =
rows.iter().filter(|r| takes(r)).filter_map(|r| r.new_color().map(|c| (c, r.tint, r.model))).collect();
type New = (Color, f32, Option<ModelRule>, Option<(String, String)>);
let mut news: Vec<New> = rows.iter().filter(|r| takes(r)).filter_map(|r| r.new_color().map(|c| (c, r.tint, r.model, r.swatch.clone()))).collect();
if order {
rng.shuffle(&mut news);
}
if saturation_brightness {
news = news
.into_iter()
.map(|(c, tint, model)| {
.map(|(c, tint, model, swatch)| {
let n = rng.saturation_brightness(c);
(n, if ColorKey::of(&n) == ColorKey::of(&c) { tint } else { 1.0 }, model)
if ColorKey::of(&n) == ColorKey::of(&c) { (n, tint, model, swatch) } else { (n, 1.0, model, None) }
})
.collect();
}
@@ -1894,8 +1948,11 @@ fn randomize(_: &mut Session, p: &Value) -> Result<Value> {
let map: Vec<Value> = rows
.iter()
.map(|r| {
let (to, tint, model) =
if takes(r) { news.next().map_or((None, 1.0, None), |(c, t, m)| (Some(c), t, m)) } else { (r.to, r.tint, r.model) };
let (to, tint, model, swatch) = if takes(r) {
news.next().map_or((None, 1.0, None, None), |(c, t, m, w)| (Some(c), t, m, w))
} else {
(r.to, r.tint, r.model, r.swatch.clone())
};
let mut row = json!({"from": r.from.iter().map(Match::to_json).collect::<Vec<_>>(), "to": to.as_ref().map(key_str)});
if r.exclude {
row["exclude"] = json!(true);
@@ -1906,6 +1963,9 @@ fn randomize(_: &mut Session, p: &Value) -> Result<Value> {
if let Some(m) = model {
row["model"] = json!(m.id());
}
if let Some((library, name)) = swatch {
row["swatch"] = json!({"name": name, "library": library});
}
if r.added {
row["added"] = json!(true);
}
+198
View File
@@ -855,6 +855,204 @@ fn a_rows_tint_tints_the_spot_color_the_art_links_to() {
assert!(e.to_string().contains("`tint` must be a number"), "{e}");
}
/// A row's `swatch` (the swatch its new color was picked from) links its art to that swatch without
/// Limit to Library: a spot or global swatch gives linked tints, and a process swatch, a swatch
/// whose color is not the row's new color and a swatch that is not there link nothing. A `swatch`
/// that is not `{name, library?}` is refused. Randomize moves the swatch with its color.
#[test]
fn a_rows_swatch_links_its_art_without_limit_to_library() {
for (options, linked) in [(json!({"spot": true}), true), (json!({"global": true}), true), (json!({}), false)] {
let mut s = session();
let mut w = json!({"name": "Ink", "color": "cmyk 0 100 0 0"});
w.as_object_mut().unwrap().extend(options.as_object().unwrap().clone());
run(&mut s, "swatch.new", w);
let dark = rect(&mut s, json!("gray 80"));
let light = rect(&mut s, json!("gray 40"));
select_all(&mut s);
let row = |swatch: Value| json!([{"from": ["gray 80", "gray 40"], "to": "cmyk 0 100 0 0", "swatch": swatch}]);
run(&mut s, "recolor.apply", json!({"map": row(json!({"name": "Ink"})), "method": "scaleTints"}));
let d = &s.doc().unwrap().doc;
let paint = |id: NodeId| match d.node(id).unwrap().appearance.fill_paint() {
vectorcraft_color::Paint::Solid { color, swatch, tint } => (color, swatch, tint),
p => panic!("{p:?}"),
};
let ((c1, l1, t1), (c2, l2, t2)) = (paint(dark), paint(light));
assert_eq!(l1.is_some() && l2.is_some(), linked, "{options}: {l1:?} {l2:?}");
// A process swatch's row keeps the art's gray model (see the next test).
if linked {
assert!(t1 > t2 && t2 > 0.0, "{options}: the lighter gray is a lighter tint: {t1} {t2}");
assert!(close(c1, Color::cmyk(0.0, 1.0, 0.0, 0.0)), "{options}: {c1:?}");
}
assert!(!close(c2, c1), "{options}: {c1:?} {c2:?}");
// Without the swatch the same row gives tints with no link.
run(&mut s, "edit.undo", json!({}));
select_all(&mut s);
run(&mut s, "recolor.apply", json!({"map": row(Value::Null), "method": "scaleTints"}));
assert_eq!(paint_link(&s, dark), None, "{options}: no swatch, no link");
run(&mut s, "edit.undo", json!({}));
select_all(&mut s);
// A swatch of another color than the row's new color links nothing.
let other = json!([{"from": ["gray 80", "gray 40"], "to": "#00ff00", "swatch": {"name": "Ink", "library": "document"}}]);
run(&mut s, "recolor.apply", json!({"map": other, "method": "scaleTints"}));
assert_eq!(paint_link(&s, dark), None, "{options}: another color");
run(&mut s, "edit.undo", json!({}));
select_all(&mut s);
// With a Global Adjust the art takes the adjusted colors, not the swatch.
let adjust = json!({"saturation": -40});
run(&mut s, "recolor.apply", json!({"map": row(json!({"name": "Ink"})), "method": "scaleTints", "globalAdjust": adjust}));
assert_eq!(paint_link(&s, dark), None, "{options}: adjusted");
assert!(!close(fill(&s, dark), Color::cmyk(0.0, 1.0, 0.0, 0.0)), "{options}: the adjustment applies");
run(&mut s, "edit.undo", json!({}));
select_all(&mut s);
// A swatch or library that is not there (deleted since the pick) links nothing, and the result
// names it.
for gone in [json!({"name": "Missing"}), json!({"name": "Ink", "library": "nowhere"})] {
let r = run(&mut s, "recolor.apply", json!({"map": row(gone.clone()), "method": "scaleTints"}));
assert_eq!(paint_link(&s, dark), None, "{options}: {gone}");
assert_eq!(r["swatchesNotFound"], json!([gone["name"]]), "{options}: {r}");
run(&mut s, "edit.undo", json!({}));
select_all(&mut s);
}
for bad in [json!("Ink"), json!({"name": ""}), json!({"name": "Ink", "library": 3})] {
let e = s.execute("recolor.apply", &json!({"map": row(bad.clone())})).unwrap_err();
assert!(e.to_string().contains("`swatch` must be"), "{bad}: {e}");
}
let two = json!([
{"from": ["gray 80"], "to": "cmyk 0 100 0 0", "swatch": {"name": "Ink"}},
{"from": ["gray 40"], "to": "#00ff00"},
]);
let r = run(&mut s, "recolor.randomize", json!({"map": two, "seed": 3}));
let rows = r["map"].as_array().unwrap();
let ink = rows.iter().find(|r| r["to"] == "cmyk 0 100 0 0").unwrap();
let green = rows.iter().find(|r| r["to"] == "rgb 0 255 0").unwrap();
assert_eq!(ink["swatch"], json!({"name": "Ink", "library": "document"}), "{r}");
assert!(green.get("swatch").is_none(), "{r}");
let r = run(&mut s, "recolor.randomize", json!({"map": two, "order": false, "saturationBrightness": true, "seed": 3}));
assert!(r["map"].as_array().unwrap().iter().all(|r| r.get("swatch").is_none()), "a changed color drops its swatch: {r}");
}
}
/// A swatch whose components are finer than a color key's hundredths still links the art of the row
/// whose new color is its key.
#[test]
fn a_rows_swatch_with_a_finer_color_than_its_key_still_links() {
let mut s = session();
let ink = Color::cmyk(0.123_456, 0.876_543, 0.0, 0.0);
run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0.123_456, "m": 0.876_543, "y": 0.0, "k": 0.0}, "spot": true}));
let id = rect(&mut s, json!("gray 50"));
select_all(&mut s);
let to = vectorcraft_color::recolor::ColorKey::of(&ink).to_string();
run(&mut s, "recolor.apply", json!({"map": [{"from": ["gray 50"], "to": to, "swatch": {"name": "Ink"}}], "method": "scaleTints"}));
assert_eq!(paint_link(&s, id).as_deref(), Some("Ink"));
assert!(close(fill(&s, id), ink), "the swatch's own color: {:?}", fill(&s, id));
}
/// A row's `swatch` from a loaded library links the art to it and adds it to the document's
/// swatches; of two library swatches with the same name, the one with the row's new color is used,
/// and rows that pick the same one link to one added swatch; of a process and a spot swatch with
/// one name and color, the first is used; and a process swatch recolors as the row's new color
/// alone does, in the color model `model` gives.
#[test]
fn a_rows_library_swatch_joins_the_document_and_a_process_swatch_changes_nothing() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "cmyk 0 100 0 0", "spot": true}));
run(&mut s, "swatch.new", json!({"name": "Twin", "color": "cmyk 100 0 0 0", "spot": true}));
let data = run(&mut s, "swatch.library.save", json!({"names": ["Ink", "Twin"], "name": "Inks"}))["data"].as_str().unwrap().to_string();
// Both of the library's swatches are named Ink.
let data = data.replace("\"Twin\"", "\"Ink\"");
let lib = run(&mut s, "swatch.library.load", json!({"data": data, "name": "inks.vcswatches"}))["library"].as_str().unwrap().to_string();
run(&mut s, "swatch.delete", json!({"names": ["Ink", "Twin"]}));
let id = rect(&mut s, json!("gray 50"));
select_all(&mut s);
let row = |to: &str| json!([{"from": ["gray 50"], "to": to, "swatch": {"name": "Ink", "library": lib}}]);
let r = run(&mut s, "recolor.apply", json!({"map": row("cmyk 100 0 0 0"), "method": "scaleTints"}));
assert_eq!(r["swatches"], json!(["Ink"]), "{r}");
let d = &s.doc().unwrap().doc;
let w = d.swatch("Ink").unwrap();
assert!(w.spot && close(w.paint.color().unwrap(), Color::cmyk(1.0, 0.0, 0.0, 0.0)), "the swatch of the row's color joined: {w:?}");
assert_eq!(paint_link(&s, id).as_deref(), Some("Ink"));
assert!(close(fill(&s, id), Color::cmyk(1.0, 0.0, 0.0, 0.0)), "{:?}", fill(&s, id));
run(&mut s, "edit.undo", json!({}));
// Three rows that pick the magenta, the cyan and again the cyan Ink: the two cyan rows link to
// one swatch added to the document.
let more = [rect(&mut s, json!("gray 20")), rect(&mut s, json!("gray 80"))];
select_all(&mut s);
let three = json!([
{"from": ["gray 50"], "to": "cmyk 0 100 0 0", "swatch": {"name": "Ink", "library": lib}},
{"from": ["gray 20"], "to": "cmyk 100 0 0 0", "swatch": {"name": "Ink", "library": lib}},
{"from": ["gray 80"], "to": "cmyk 100 0 0 0", "swatch": {"name": "Ink", "library": lib}},
]);
let r = run(&mut s, "recolor.apply", json!({"map": three, "method": "scaleTints"}));
assert_eq!(r["swatches"].as_array().map(Vec::len), Some(2), "{r}");
let (a, b, c) = (paint_link(&s, id), paint_link(&s, more[0]), paint_link(&s, more[1]));
assert!(a.is_some() && b.is_some() && a != b && b == c, "{a:?} {b:?} {c:?}");
run(&mut s, "edit.undo", json!({}));
// Of a process and a spot swatch with one name and color, the first, the process one, is used.
run(&mut s, "swatch.new", json!({"name": "Pair", "color": "cmyk 0 0 100 0"}));
run(&mut s, "swatch.new", json!({"name": "Pear", "color": "cmyk 0 0 100 0", "spot": true}));
let data = run(&mut s, "swatch.library.save", json!({"names": ["Pair", "Pear"], "name": "Pairs"}))["data"]
.as_str()
.unwrap()
.replace("\"Pear\"", "\"Pair\"");
let pairs = run(&mut s, "swatch.library.load", json!({"data": data, "name": "pairs.vcswatches"}))["library"].as_str().unwrap().to_string();
run(&mut s, "swatch.delete", json!({"names": ["Pair", "Pear"]}));
select_all(&mut s);
let map = json!([{"from": ["gray 50"], "to": "cmyk 0 0 100 0", "swatch": {"name": "Pair", "library": pairs}}]);
run(&mut s, "recolor.apply", json!({"map": map, "method": "scaleTints"}));
assert_eq!(paint_link(&s, id), None, "the process swatch");
run(&mut s, "edit.undo", json!({}));
// A global process Ink and a spot Ink of one color, from two libraries, while the document's Ink
// is another color: each row links to its own added swatch.
let mut libraries = vec![];
for (file, kind) in [("global.vcswatches", json!({"global": true})), ("spot.vcswatches", json!({"spot": true}))] {
let mut w = json!({"name": "Ink", "color": "cmyk 0 0 0 100"});
w.as_object_mut().unwrap().extend(kind.as_object().unwrap().clone());
run(&mut s, "swatch.new", w);
let data = run(&mut s, "swatch.library.save", json!({"names": ["Ink"], "name": file}))["data"].as_str().unwrap().to_string();
libraries.push(run(&mut s, "swatch.library.load", json!({"data": data, "name": file}))["library"].as_str().unwrap().to_string());
run(&mut s, "swatch.delete", json!({"names": ["Ink"]}));
}
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#00ff00"}));
select_all(&mut s);
let two = json!([
{"from": ["gray 50"], "to": "cmyk 0 0 0 100", "swatch": {"name": "Ink", "library": libraries[0]}},
{"from": ["gray 20"], "to": "cmyk 0 0 0 100", "swatch": {"name": "Ink", "library": libraries[1]}},
]);
let r = run(&mut s, "recolor.apply", json!({"map": two, "method": "scaleTints"}));
assert_eq!(r["swatches"].as_array().map(Vec::len), Some(2), "{r}");
let (global, spot) = (paint_link(&s, id).unwrap(), paint_link(&s, more[0]).unwrap());
let d = &s.doc().unwrap().doc;
assert!(global != spot && !d.swatch(&global).unwrap().spot && d.swatch(&spot).unwrap().spot, "{global} {spot}");
run(&mut s, "edit.undo", json!({}));
run(&mut s, "swatch.delete", json!({"names": ["Ink"]}));
select_all(&mut s);
run(&mut s, "swatch.new", json!({"name": "Leaf", "color": "cmyk 60 0 100 10"}));
select_all(&mut s);
let fills = |s: &mut Session, swatch: Value, model: &str| {
let map = json!([{"from": ["gray 50"], "to": "cmyk 60 0 100 10", "swatch": swatch}]);
let r = run(s, "recolor.apply", json!({"map": map, "method": "scaleTints", "model": model}));
let paint = s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint();
run(s, "edit.undo", json!({}));
select_all(s);
(paint, r.get("note").cloned())
};
for model in ["keep", "new", "document"] {
let alone = fills(&mut s, Value::Null, model);
assert_eq!(fills(&mut s, json!({"name": "Leaf"}), model), alone, "{model}: a process swatch is its color");
}
}
fn paint_link(s: &Session, id: NodeId) -> Option<String> {
match s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint() {
vectorcraft_color::Paint::Solid { swatch, .. } => swatch,
p => panic!("{p:?}"),
}
}
/// Randomize order moves a row's tint with its new color; changing saturation and brightness
/// drops the tint of every color it changes.
#[test]
+38 -6
View File
@@ -707,7 +707,23 @@ fn value_fields(ui: &mut Ui, p: &Picked, channel: Channel) -> (Option<Picked>, O
(edit, chosen)
}
/// The field holding the swatch last clicked in the list: `{name, library, color, keep}` (see
/// [`picked_swatch`]).
const PICKED_SWATCH: &str = "__pickedSwatch";
/// The swatch the dialog's color was picked from, while the color is still that swatch's: for a
/// global or spot swatch `{name, library}` for a `recolor.apply` row's `swatch` and its color, and
/// for a process swatch or a swatch linked to another swatch (a tint swatch) `None` and its color.
fn picked_swatch(d: &Dialog) -> Option<(Option<Value>, Color)> {
let w = d.fields.get(PICKED_SWATCH)?;
let c = w.get("color").and_then(color_value)?;
let swatch = w["keep"].as_bool().unwrap_or(false).then(|| json!({"name": w["name"], "library": w["library"]}));
(picked(d).color == c).then_some((swatch, c))
}
/// The document's colour swatches or a swatch library as a list; returns the clicked swatch's colour.
/// A click also records the swatch in [`PICKED_SWATCH`], with `keep` for a global or spot swatch
/// that is not linked to another one.
fn swatch_list(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, current: &Color, side: f32) -> Option<Color> {
let t = Tokens::get(ui.ctx());
let mut chosen = None;
@@ -740,10 +756,16 @@ fn swatch_list(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, current: &Colo
widgets::dim_label(ui, tl!("Open a document to see its swatches."));
return;
};
let doc = &st.doc;
// Over Recolor Artwork, the swatches as they were before its preview, which
// `recolor.apply` reads: a library swatch the preview added is not listed.
let doc = match &st.interaction {
Some(it) if d.fields.contains_key(RECOLOR_ROW) => &it.doc,
_ => &st.doc,
};
for s in doc.swatches.iter().chain(doc.swatch_groups.iter().flat_map(|g| g.swatches.iter())) {
let Some(color) = s.paint.color() else { continue };
let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 20.0), Sense::click());
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, color == *current, &s.name));
if resp.hovered() {
ui.painter().rect_filled(r, 0.0, t.hover);
}
@@ -757,13 +779,14 @@ fn swatch_list(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, current: &Colo
t.text,
);
if resp.clicked() {
chosen = Some(color);
chosen = Some((color, s.name.clone(), (s.global || s.spot) && matches!(s.paint, Paint::Solid { swatch: None, .. })));
}
}
} else if let Some((_, lib)) = swatchlib::library(&app.session, &cur) {
for s in lib.swatches.iter().chain(lib.groups.iter().flat_map(|g| g.swatches.iter())) {
let Some(color) = s.paint.color() else { continue };
let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 20.0), Sense::click());
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, color == *current, &s.name));
if resp.hovered() {
ui.painter().rect_filled(r, 0.0, t.hover);
}
@@ -777,14 +800,17 @@ fn swatch_list(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, current: &Colo
t.text,
);
if resp.clicked() {
chosen = Some(color);
chosen = Some((color, s.name.clone(), (s.global || s.spot) && matches!(s.paint, Paint::Solid { swatch: None, .. })));
}
}
}
});
});
});
chosen
let (color, name, keep) = chosen?;
let library = Some(d.str("library")).filter(|l| !l.is_empty()).unwrap_or_else(|| swatchlib::DOCUMENT_SWATCHES.to_string());
d.fields.insert(PICKED_SWATCH.into(), json!({"name": name, "library": library, "color": color_json(&color), "keep": keep}));
Some(color)
}
/// OK: apply the colour to the proxy, keeping the live preview as one undo step. For an artboard,
@@ -818,8 +844,14 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
}
if let Some(row) = d.fields.get(RECOLOR_ROW).and_then(Value::as_u64) {
let parent = super::parent(d).ok_or("Recolor Artwork is no longer open")?;
let c = in_document_model(app, picked(d).color);
app.ui.dialog = Some(super::recolor::with_new_color(app, parent, usize::try_from(row).unwrap_or(usize::MAX), c));
let row = usize::try_from(row).unwrap_or(usize::MAX);
// A color picked from a global or spot swatch is that swatch, in its own color model; one
// picked from another swatch takes the row's swatch away.
app.ui.dialog = Some(match picked_swatch(d) {
Some((Some(swatch), c)) => super::recolor::with_new_swatch(app, parent, row, c, Some(swatch)),
Some((None, _)) => super::recolor::with_new_swatch(app, parent, row, in_document_model(app, picked(d).color), None),
None => super::recolor::with_new_color(app, parent, row, in_document_model(app, picked(d).color)),
});
return Ok(Value::Null);
}
if d.bool("keep") && !app.session.in_interaction() && d.fields.get("original").and_then(color_value) == Some(picked(d).color) {
+172 -7
View File
@@ -84,7 +84,9 @@
//! or redo.
//!
//! Fields (`ui.dialog.set`): `rows` ([{from: [keys], to: key, exclude?, tint?: percent of a spot
//! color, added?}]; a row with no current colors, `from: []`, recolors no art, and with `added: true`
//! color, added?, swatch?: {name, library} of the global or spot swatch the Color Picker's
//! swatches gave the new color, which links the row's art to it}]; a row with no current colors,
//! `from: []`, recolors no art, and with `added: true`
//! (a color the Add Color tool added) adds its new color to the color group; `to: null`, no new color;
//! `base: true`, the base color, else the first color the Edit tab shows; `tie: n` on a marker and
//! `follows: n` on a color added on its line, which moves with it; the dialog sends `recolor.apply`
@@ -1082,21 +1084,26 @@ fn set_to(row: &mut Value, c: &Color) {
if let Some(r) = row.as_object_mut() {
r.remove("tint");
r.remove("model");
r.remove(SWATCH);
}
}
/// A row's `swatch`: the swatch its new color was picked from (`recolor.apply`'s row `swatch`).
const SWATCH: &str = "swatch";
/// Set for the frame in which Randomly change color order shuffled the rows' new colors.
const SHUFFLED: &str = "__shuffled";
/// Give each row of `rows` whose current colors and new color are those of the same row of
/// `before` that row's tint and model again, when it has none: a change that snaps back to the
/// same new color keeps the tint of it and the model a slider edit gave it.
/// `before` that row's tint, model and swatch again, when it has none: a change that snaps back to
/// the same new color keeps the tint of it, the model a slider edit gave it and the swatch it was
/// picked from.
fn keep_tints(before: &[Value], rows: &mut [Value]) {
for (r, b) in rows.iter_mut().zip(before) {
if r["from"] != b["from"] || r["to"] != b["to"] {
continue;
}
for k in ["tint", "model"] {
for k in ["tint", "model", SWATCH] {
if r.get(k).is_none()
&& let Some(v) = b.get(k)
{
@@ -1481,6 +1488,33 @@ pub(super) fn with_new_color(app: &VectorcraftApp, mut d: Dialog, i: usize, c: C
d
}
/// `d` with row `i`'s new color set to color `c` of a swatch picked from the Color Picker's
/// swatches: for a global or spot swatch, `swatch` (`{name, library}`), which the row keeps, so
/// `recolor.apply` links its art to it, unless Limit to Library snaps the color to another one
/// (colors compare as [`ColorKey`]s, as the row holds them); for another swatch, `None`, which
/// takes away a swatch picked for the row before, and without Limit to Library the tint it gave.
pub(super) fn with_new_swatch(app: &VectorcraftApp, d: Dialog, i: usize, c: Color, swatch: Option<Value>) -> Dialog {
let mut d = with_new_color(app, d, i, c);
let keeps_tint = !d.str("limitTo").is_empty();
let mut rs = rows(&d);
let Some(r) = rs.get_mut(i) else { return d };
match swatch {
Some(w) if to_color(r).is_some_and(|t| ColorKey::of(&t) == ColorKey::of(&c)) => r[SWATCH] = w,
Some(_) => return d,
None => {
let Some(o) = r.as_object_mut() else { return d };
if o.remove(SWATCH).is_none() {
return d;
}
if !keeps_tint {
o.remove("tint");
}
}
}
d.fields.insert("rows".into(), Value::Array(rs));
d
}
/// The fields a step of Undo Changes and Redo Changes restores: what the art is recolored with.
const STEP_FIELDS: [&str; 11] =
["rows", "colors", "method", "preserveWhite", "preserveBlack", "preserveGrays", "limitTo", "rule", "globalAdjust", THEME_PICKS, WEIGHTS];
@@ -2030,10 +2064,13 @@ fn spot_tinted(app: &VectorcraftApp, c: Color, t: f32) -> Color {
fn new_shown(app: &VectorcraftApp, d: &Dialog, row: &Value) -> Color {
let to = to_color(row).unwrap_or_default();
// Only a Lab spot color can show another color; the library lookup is skipped for the rest.
if matches!(to, Color::Lab { .. }) && d.bool("__art") && spot_of(app, d, &to).is_some() {
if matches!(to, Color::Lab { .. }) && d.bool("__art") && (spot_of(app, d, &to).is_some() || own_spot(app, d, row, &to).is_some()) {
spot_tinted(app, to, row_tint(row))
} else {
} else if row_tint(row) < 1.0 && tint_applies(app, d, row, &to) {
to.tinted(row_tint(row))
} else {
// The swatch the tint was for no longer links the art, which takes the full color.
to
}
}
@@ -2053,6 +2090,59 @@ fn spot_of(app: &VectorcraftApp, d: &Dialog, c: &Color) -> Option<String> {
swatchlib::library_swatches(&app.session, &lib)?.into_iter().find(|w| w.paint.color() == Some(near)).filter(|w| w.spot).map(|w| w.name)
}
/// The name of the spot swatch `row`'s new color `c` was picked from (its `swatch`), while that
/// swatch has color `c` and no Global Adjust applies without Limit to Library, as `recolor.apply`
/// reads it.
fn own_spot(app: &VectorcraftApp, d: &Dialog, row: &Value, c: &Color) -> Option<String> {
if d.str("limitTo").is_empty() && !global_adjust(adjust_values(d)).is_identity() {
return None;
}
let (name, _) = swatch_ref(row)?;
row_swatch(app, row, c).filter(|spot| *spot).map(|_| name.to_string())
}
/// The name and library key of `row`'s `swatch` when it is `{name, library?}` with a name, as
/// `recolor.apply` reads it.
fn swatch_ref(row: &Value) -> Option<(&str, &str)> {
let w = row.get(SWATCH)?;
let name = w.get("name")?.as_str().filter(|n| !n.is_empty())?;
let library = match w.get("library") {
None | Some(Value::Null) => swatchlib::DOCUMENT_SWATCHES,
Some(l) => l.as_str().filter(|l| !l.is_empty())?,
};
Some((name, library))
}
/// Whether the swatch `row`'s `swatch` names, with color `c` (as a color key), is a spot color,
/// when it is a global or spot swatch; `None` when it is a process swatch or not there (deleted
/// since the pick). Of several swatches with that name, the first with that color counts, as
/// `recolor.apply` finds it. The document's swatches are read as they were before the preview,
/// which `recolor.apply` runs on.
fn row_swatch(app: &VectorcraftApp, row: &Value, c: &Color) -> Option<bool> {
let (name, lib) = swatch_ref(row)?;
let fits = |s: &&vectorcraft_color::swatch::Swatch| {
s.name == name
&& matches!(s.paint, vectorcraft_color::Paint::Solid { swatch: None, .. })
&& s.paint.color().is_some_and(|w| ColorKey::of(&w) == ColorKey::of(c))
};
let found = if lib == swatchlib::DOCUMENT_SWATCHES {
let st = app.session.active()?;
let doc = st.interaction.as_ref().map_or(&st.doc, |it| &it.doc);
doc.swatches_iter().find(fits).map(|s| (s.global || s.spot, s.spot))
} else {
let (_, l) = swatchlib::library(&app.session, lib)?;
l.swatches.iter().chain(l.groups.iter().flat_map(|g| g.swatches.iter())).find(fits).map(|s| (s.global || s.spot, s.spot))
};
found.filter(|(links, _)| *links).map(|(_, spot)| spot)
}
/// Whether the new color chip shows `row`'s tint: with Limit to Library, when the row has no
/// `swatch`, or when its `swatch` links the art ([`row_swatch`], with no Global Adjust). A row whose
/// `swatch` links nothing recolors its art with the full color.
fn tint_applies(app: &VectorcraftApp, d: &Dialog, row: &Value, c: &Color) -> bool {
!d.str("limitTo").is_empty() || swatch_ref(row).is_none() || (global_adjust(adjust_values(d)).is_identity() && row_swatch(app, row, c).is_some())
}
/// The mode the sliders show new color `c` in, `None` for Tint: the mode picked in the menu, else
/// `c`'s own model (HSB for a gray), or Tint for a spot color (`spot`).
fn slider_mode(d: &Dialog, c: &Color, spot: bool) -> Option<Mode> {
@@ -2098,7 +2188,7 @@ impl SliderTarget {
let row = row.filter(|i| *i < rows.len());
let color = row.and_then(|i| to_color(&rows[i]));
// A row tint acts only on art, so without art a spot color shows the process modes.
let spot = color.filter(|_| d.bool("__art")).and_then(|c| spot_of(app, d, &c));
let spot = color.filter(|_| d.bool("__art")).and_then(|c| spot_of(app, d, &c).or_else(|| own_spot(app, d, &rows[row?], &c)));
Self { row, color, spot }
}
@@ -2431,6 +2521,7 @@ fn remove_color(rows: &mut Vec<Value>, i: usize, base: Option<usize>, keep: bool
if let Some(r) = rows[i].as_object_mut() {
r.remove("tint");
r.remove("model");
r.remove(SWATCH);
}
return Some(base.unwrap_or(0));
}
@@ -3511,6 +3602,80 @@ mod tests {
assert!(super::rows(&other)[0].get("tint").is_none(), "{:?}", super::rows(&other));
}
/// A spot swatch picked for a row with no Limit to Library gives the row the swatch and the
/// sliders its Tint; another new color drops the swatch, and a Global Adjust, under which
/// `recolor.apply` does not use the swatch, shows the color modes instead of Tint.
#[test]
fn a_picked_spot_swatch_gives_its_row_the_tint_slider() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
app.run("swatch.new", json!({"name": "Ink", "color": "cmyk 0 100 0 0", "spot": true})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone();
app.run("paint.setFill", json!({"ids": [id], "color": "#808080"})).unwrap();
app.run("ui.recolorDialog", json!({"colors": 1})).unwrap();
let mut d = app.ui.dialog.clone().unwrap();
d.fields.insert("rows".into(), json!([{"from": ["rgb 128 128 128"], "to": "rgb 128 128 128"}]));
let ink = Color::cmyk(0.0, 1.0, 0.0, 0.0);
let picked = with_new_swatch(&app, d.clone(), 0, ink, Some(json!({"name": "Ink", "library": "document"})));
let rs = super::rows(&picked);
assert_eq!(rs[0][SWATCH], json!({"name": "Ink", "library": "document"}));
assert_eq!(SliderTarget::at(&app, &picked, &rs, Some(0)).spot.as_deref(), Some("Ink"), "the Tint slider");
let other = with_new_color(&app, picked.clone(), 0, Color::rgb(0.0, 1.0, 0.0));
assert!(super::rows(&other)[0].get(SWATCH).is_none(), "{:?}", super::rows(&other));
let mut adjusted = picked;
adjusted.fields.insert("globalAdjust".into(), json!({"saturation": 20.0, "brightness": 0.0, "temperature": 0.0, "luminosity": 0.0}));
assert_eq!(SliderTarget::at(&app, &adjusted, &rs, Some(0)).spot, None, "no Tint under a Global Adjust");
}
/// A row's chip shows its tint while its picked swatch links the art, also while a preview
/// changes that swatch; once the swatch is deleted the chip shows the full color the art takes
/// and OK recolors with it. A process swatch picked in its place takes the row's swatch and tint
/// away.
#[test]
fn a_picked_swatch_that_is_gone_links_nothing() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
app.run("swatch.new", json!({"name": "Ink", "color": "cmyk 0 100 0 0", "spot": true})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone();
app.run("paint.setFill", json!({"ids": [id], "color": "#808080"})).unwrap();
app.run("ui.recolorDialog", json!({"colors": 1})).unwrap();
let mut d = app.ui.dialog.clone().unwrap();
d.fields.insert("rows".into(), json!([{"from": ["rgb 128 128 128"], "to": "rgb 128 128 128"}]));
let ink = Color::cmyk(0.0, 1.0, 0.0, 0.0);
let mut picked = with_new_swatch(&app, d, 0, ink, Some(json!({"name": "Ink", "library": "document"})));
let mut rs = super::rows(&picked);
rs[0]["tint"] = json!(40.0);
picked.fields.insert("rows".into(), Value::Array(rs));
let rs = super::rows(&picked);
let tinted = new_shown(&app, &picked, &rs[0]);
assert!(tinted != ink && tinted.to_rgb()[1] > ink.to_rgb()[1], "the chip at 40%: {tinted:?}");
// A process swatch of the same color picked for the row.
let process = with_new_swatch(&app, picked.clone(), 0, ink, None);
let r = &super::rows(&process)[0];
assert!(r.get(SWATCH).is_none() && r.get("tint").is_none(), "{r}");
// A preview that gives the swatch another color: the row still links to it.
let _ = app.session.cancel_interaction();
app.session.begin_interaction("Swatch Options").unwrap();
app.session.preview("swatch.edit", &json!({"name": "Ink", "color": "cmyk 100 0 0 0"})).unwrap();
assert_eq!(SliderTarget::at(&app, &picked, &rs, Some(0)).spot.as_deref(), Some("Ink"), "the swatch as it was before the preview");
assert_eq!(new_shown(&app, &picked, &rs[0]), tinted);
let _ = app.session.cancel_interaction();
app.run("swatch.delete", json!({"names": ["Ink"]})).unwrap();
assert_eq!(SliderTarget::at(&app, &picked, &rs, Some(0)).spot, None, "no Tint slider");
assert_eq!(new_shown(&app, &picked, &rs[0]), ink, "the full color the art takes");
let r = app.session.execute(CMD, &apply_params(&picked)).unwrap();
assert_eq!(r["swatchesNotFound"], json!(["Ink"]), "{r}");
let doc = &app.session.doc().unwrap().doc;
match doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap().appearance.fill_paint() {
vectorcraft_color::Paint::Solid { color, swatch, .. } => {
assert_eq!(swatch, None, "no link");
let [r, g, b] = color.to_rgb();
assert!(r > 0.9 && g < 0.1 && b > 0.4, "the full ink, not a 40% tint or the gray: {color:?}");
}
p => panic!("{p:?}"),
}
}
/// With the Spot Colors options on CMYK values, a row whose new color is a Lab spot color of the
/// library shows the art's color at its tint: the working-CMYK equivalent with its inks scaled.
#[test]
+179
View File
@@ -1749,6 +1749,185 @@ fn row_context_menu_pick_from_swatches_and_limit_to_library() {
}
}
/// Each paint under `v`: where it is (`stop` for a gradient stop, `stroke`, `type` for the
/// characters of a text object, else `fill`), its color, the swatch it is linked to and its tint.
fn picked_paints(v: &Value, at: &str, out: &mut Vec<(String, Color, Option<String>, f64)>) {
match v {
Value::Object(m) => {
if let Some(c) = m.get("color").and_then(|c| serde_json::from_value::<Color>(c.clone()).ok()) {
let (swatch, tint) =
(m.get("swatch").and_then(Value::as_str).map(String::from), m.get("tint").and_then(Value::as_f64).unwrap_or(1.0));
out.push((at.to_string(), c, swatch, tint));
}
// An appearance item is tagged with its `kind`; a text object's characters are its runs.
let at = if m.get("kind").and_then(Value::as_str) == Some("stroke") { "stroke" } else { at };
for (k, x) in m {
let here = match k.as_str() {
"stops" if at != "type" => "stop",
"runs" => "type",
_ => at,
};
picked_paints(x, here, out);
}
}
Value::Array(a) => a.iter().for_each(|x| picked_paints(x, at, out)),
_ => {}
}
}
fn paints_now(app: &VectorcraftApp) -> Vec<(String, Color, Option<String>, f64)> {
let d = &app.session.doc().unwrap().doc;
let mut out = vec![];
for c in d.layers.iter().filter_map(|l| l.children()) {
picked_paints(&serde_json::to_value(c).unwrap(), "fill", &mut out);
}
out
}
/// Every number under an `opacity` key under `v`.
fn opacities_under(v: &Value, out: &mut Vec<f64>) {
match v {
Value::Object(m) => {
out.extend(m.get("opacity").and_then(Value::as_f64));
m.values().for_each(|x| opacities_under(x, out));
}
Value::Array(a) => a.iter().for_each(|x| opacities_under(x, out)),
_ => {}
}
}
fn opacities_now(app: &VectorcraftApp) -> Vec<f64> {
let mut out = vec![];
for c in app.session.doc().unwrap().doc.layers.iter().filter_map(|l| l.children()) {
opacities_under(&serde_json::to_value(c).unwrap(), &mut out);
}
out
}
/// The lightness of a gray other than black and white.
fn mid_gray(c: &Color) -> Option<f32> {
let [r, g, b] = c.to_rgb();
((r - g).abs() < 1e-3 && (g - b).abs() < 1e-3 && r > 0.01 && r < 0.99).then_some(r)
}
/// Gray art placed from an SVG file (fills, a stroke, a group at 50% opacity, `fill-opacity`, an
/// even-odd compound path, a gradient's stops and type), recolored with one color, Scale Tints or
/// Preserve Tints and no Limit to Library, takes the swatch picked for its row in the Color Picker's
/// swatch list: a spot or global swatch gives tints of it linked to it, darker grays at higher
/// tints, with the opacities kept, and editing the swatch recolors every one of them at the same
/// tints; a process swatch gives tints of its color with no link, as a color picked any other way. With Preserve Black on, black stays black; with it
/// off, black takes the full ink.
#[test]
fn a_swatch_picked_for_a_row_links_the_art_to_it_without_a_library() {
use egui::accesskit::Role;
let svg = r##"<svg xmlns="http://www.w3.org/2000/svg" width="240" height="80"><rect x="0" y="0" width="20" height="20" fill="#000000"/><rect x="25" y="0" width="20" height="20" fill="#333333" stroke="#808080" stroke-width="2"/><g opacity="0.5"><rect x="50" y="0" width="20" height="20" fill="#808080"/></g><rect x="75" y="0" width="20" height="20" fill="#cccccc" fill-opacity="0.7"/><rect x="100" y="0" width="20" height="20" fill="#ffffff"/><path d="M130 0 L150 0 L150 20 Z M135 5 L145 5 L145 15 Z" fill="#666666" fill-rule="evenodd"/><defs><linearGradient id="g"><stop offset="0" stop-color="#222222"/><stop offset="1" stop-color="#dddddd"/></linearGradient></defs><rect x="160" y="0" width="20" height="20" fill="url(#g)"/><text x="0" y="60" font-size="18" fill="#555555">Gray</text></svg>"##;
let path = std::env::temp_dir().join(format!("vectorcraft-recolor-picked-swatch-{}.svg", std::process::id()));
std::fs::write(&path, svg).unwrap();
let cases = [
("spot", json!({"spot": true}), true, true, "scaleTints"),
("spot, Preserve Black off", json!({"spot": true}), true, false, "scaleTints"),
("spot, Preserve Tints", json!({"spot": true}), true, true, "preserveTints"),
("global", json!({"global": true}), true, true, "scaleTints"),
("process", json!({}), false, true, "scaleTints"),
];
for (kind, options, linked, preserve_black, method) in cases {
let mut app = app();
// The swatch list then shows Ink without scrolling.
let doc = &app.session.doc().unwrap().doc;
let names: Vec<_> = doc
.swatches
.iter()
.filter(|s| !s.is_reserved())
.map(|s| s.name.clone())
.chain(doc.swatch_groups.iter().map(|g| g.name.clone()))
.collect();
app.run("swatch.delete", json!({"names": names})).unwrap();
let mut swatch = json!({"name": "Ink", "color": "cmyk 0 100 0 0"});
swatch.as_object_mut().unwrap().extend(options.as_object().unwrap().clone());
app.run("swatch.new", swatch).unwrap();
app.run("file.place", json!({"path": path.to_string_lossy(), "at": [120, 50]})).unwrap();
app.run("select.all", json!({})).unwrap();
let before = paints_now(&app);
let opacities = opacities_now(&app);
assert!(opacities.iter().any(|o| (o - 0.5).abs() < 1e-6) && opacities.iter().any(|o| (o - 0.7).abs() < 1e-6), "{opacities:?}");
let black = |c: &Color| c.to_rgb().iter().all(|v| *v < 0.01);
// The paints the ink takes: every mid gray, and black too without Preserve Black.
let inked: Vec<usize> = (0..before.len()).filter(|&i| mid_gray(&before[i].1).is_some() || !preserve_black && black(&before[i].1)).collect();
for at in ["fill", "stroke", "stop", "type"] {
assert!(inked.iter().any(|&i| before[i].0 == at), "{kind}: gray {at} paints came in: {before:?}");
}
let mut h = assign_harness(app, json!({"colors": 1}));
set(h.state_mut(), "method", json!(method));
set(h.state_mut(), "preserveBlack", json!(preserve_black));
h.run_steps(3);
let rows = field(h.state(), "rows");
let rows = rows.as_array().unwrap();
let row = rows.iter().position(|r| !r["exclude"].as_bool().unwrap_or(false)).unwrap();
assert_eq!(rows.iter().filter(|r| !r["exclude"].as_bool().unwrap_or(false)).count(), 1, "{kind}: one row: {rows:?}");
assert_eq!(field(h.state(), "limitTo"), json!(""), "no library");
row_context_menu(&mut h, row);
h.get_by_label(" Pick from Swatches").click();
h.run_steps(3);
h.get_by_role_and_label(Role::Button, "Ink").click();
h.run_steps(2);
let picker = h.state().ui.dialog.as_ref().unwrap();
assert_eq!(
picker.fields.get("color").and_then(vectorcraft_engine::cmd::color_value),
Some(Color::cmyk(0.0, 1.0, 0.0, 0.0)),
"{:?}",
picker.fields
);
h.get_by_role_and_label(Role::Button, "OK").click();
h.run_steps(3);
assert_eq!(h.state().ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("recolor"));
// A process swatch gives the row its color alone.
let swatch = linked.then(|| json!({"name": "Ink", "library": "document"}));
assert_eq!(field(h.state(), "rows")[row].get("swatch").cloned(), swatch, "{kind}: the row keeps a global or spot swatch");
let app = h.state_mut();
dialogs::confirm(app).unwrap();
assert!(app.ui.dialog.is_none());
let after = paints_now(app);
assert_eq!(after.len(), before.len(), "{kind}: the art has the same paints");
assert_eq!(opacities_now(app), opacities, "{kind}: the opacities are kept");
for (i, (b, a)) in before.iter().zip(&after).enumerate() {
if !inked.contains(&i) {
assert_eq!(a.1, b.1, "{kind}: paint {i} keeps its color");
}
}
for &i in &inked {
assert!(mid_gray(&after[i].1).is_none() && !black(&after[i].1), "{kind}: paint {i} took the ink: {:?}", after[i]);
assert_eq!(after[i].2.as_deref(), linked.then_some("Ink"), "{kind}: paint {i} linked");
}
if linked {
// Darker grays take higher tints.
for &i in &inked {
for &j in &inked {
let (li, lj) = (mid_gray(&before[i].1).unwrap_or(0.0), mid_gray(&before[j].1).unwrap_or(0.0));
if li < lj - 0.02 {
assert!(after[i].3 >= after[j].3, "{kind}: paint {i} is darker than {j} and at a higher tint");
}
}
}
let r = app.run("swatch.edit", json!({"name": "Ink", "color": "cmyk 100 0 0 0"})).unwrap();
let edited = paints_now(app);
for &i in &inked {
let (at, c, link, tint) = &edited[i];
assert_eq!((link.as_deref(), *tint), (Some("Ink"), after[i].3), "{kind}: paint {i} ({at}) keeps its link and tint");
assert!(c.to_rgb()[0] < after[i].1.to_rgb()[0] && c != &after[i].1, "{kind}: paint {i} ({at}) shows the edited ink: {c:?}");
}
// swatch.edit counts every paint that follows it, a gradient as one paint however many
// of its stops follow (the art holds one gradient).
let stops = inked.iter().filter(|&&i| before[i].0 == "stop").count();
let paints = inked.len() - stops + usize::from(stops > 0);
assert_eq!(r["relinked"].as_u64(), u64::try_from(paints).ok(), "{kind}: every inked paint follows the swatch: {r}");
}
}
let _ = std::fs::remove_file(&path);
}
/// Whether the dialog's button `name` is disabled.
fn disabled(h: &egui_kittest::Harness<'_, VectorcraftApp>, name: &str) -> bool {
h.get_by_role_and_label(egui::accesskit::Role::Button, name).accesskit_node().is_disabled()
+12 -2
View File
@@ -5566,8 +5566,18 @@ empty row does not count toward Colors. While it is empty and not `added`, the d
the base color when the empty row is selected), the harmony rules,
linked moves and the Color Theme Picker leave its new color as it is, and Save All Colors and a new color group saved
from colors alone leave its new color out. With `limitTo`, a row's `tint` (a percentage, default 100) gives the art
linked to the global or spot swatch its new color is that share of its tint; `tint` must be a number. `recolor.randomize`
moves a row's `tint` with its new color and removes it from a color it changes, and moves a row's `model` with its new color. `swatch.editGroup {group, colors, rename?}` rewrites a colour group in one undo
linked to the global or spot swatch its new color is that share of its tint; `tint` must be a number. A row's
`swatch: {name, library?}` names the swatch its new color was picked from (`library` is a swatch library id or name,
default `"document"`): of the swatches with that name, the first with the row's new color (compared as color keys,
which round) is used. While it is a global or spot swatch and there is no Global Adjust (or `limitTo` is given), the
row's art takes the swatch as it would with `limitTo`, linked to it at its tints (and its `tint` applies), and a library
swatch joins the document's swatches. A process swatch, or a swatch or library that is not there (such as a swatch
deleted after it was picked), links nothing, and the row recolors as its new color alone does; the result's
`swatchesNotFound` lists the names of the swatches that are not there. A row whose new color is
picked from a global or spot swatch in the Color Picker's swatch list in Recolor Artwork carries it, so with no Limit to
Library the art still takes the swatch picked; the dialog drops a row's `swatch` when the row's new color changes. A
`swatch` that is not `{name, library?}` is an error. `recolor.randomize`
moves a row's `tint` and `swatch` with its new color and removes them from a color it changes, and moves a row's `model` with its new color. `swatch.editGroup {group, colors, rename?}` rewrites a colour group in one undo
step (art linked to its global swatches follows); a `null` in `colors` removes the group's swatch at that place, and
given the group's own colors in order and no new name, it records no undo step. A color key (`recolor.colors`) that
names a swatch's color, rounded to the key's steps, counts as that color, and the swatch keeps its color unrounded. And `recolor.apply` with `group` recolours the art and rewrites the
+1
View File
@@ -2033,6 +2033,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **Recolor Artwork color groups list:** a list on the right of the dialog shows the document's color groups, and the Show Color Groups button beside the tabs shows or hides it. A click on a group makes it the group being edited, and the rows take its colors. Save Changes rewrites the selected group with the new colors, New Color Group saves them as a new group, and Delete removes the selected group; the Swatches panel shows each change ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). VectorCraft's own rules: when the art has colors of the group, Save Changes and OK keep the group's swatches in order, and a swatch no row lists keeps its color; an excluded row leaves its swatch its own color; after a save with art, the rows' new colors take the Global Adjust, which goes back to 0%. `group`, `groupStorage` and `groupAction` are the dialog fields. Tests: `the_color_groups_list_selects_saves_and_deletes_groups`, `a_group_picked_in_the_list_recolors_the_art` and the `saving_a_group_` tests in `crates/ui-egui/src/dialogs/recolor.rs`, and `edit_color_group_with_its_own_colors_records_no_undo_step` and `edit_color_group_with_its_own_color_keys_keeps_the_colors` in `crates/engine/src/tests/swatchcmds.rs`.
- **Recolor Artwork New Row:** the Assign tab's New Row button adds a row with no current colors, so current colors can be moved into it and take its new color ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html), [Assign new colors to selected artworks](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/assign-new-colors-to-selected-artwork.html)). VectorCraft's own rules: the row goes above the first selected row (at the top when none is selected) with that row's new color and becomes the selection, and Merge with it as the first selected row moves the other rows' colors into it. The button needs selected art. An empty row recolors nothing, does not count toward Colors, adds no library swatch and gives a rewritten color group no color. While it is empty, Save All Colors and a new color group saved from colors alone leave its new color out, the Edit tab's wheel, bars and chips do not show it and its sliders edit the base color instead, the harmony rules and linked moves leave its new color as it is, and the Color Theme Picker gives it no color. Tests: `a_new_row_goes_above_the_selection_and_takes_merged_colors`, `an_empty_row_gives_the_group_no_color`, `an_empty_row_gives_a_new_group_no_color`, `an_empty_row_takes_no_harmony_or_wheel_color`, `theme_picks_leave_an_empty_row_out`, `save_all_colors_leaves_an_empty_row_out` and `colors_merged_into_a_new_row_take_its_new_color` in `crates/ui-egui/src/dialogs/recolor.rs`, `an_empty_row_recolors_nothing` and `an_empty_row_adds_no_swatch_and_no_group_color` in `crates/engine/src/tests/recolor.rs`.
- **Recolor Artwork Undo Changes and Redo Changes:** two buttons beside the Color Theme Picker go back and forward one color edit made in the open dialog, and Undo Changes has nothing to undo after the dialog is opened again ([Recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/recolor-options-overview.html)); `ui.recolorUndo` and `ui.recolorRedo` run them. VectorCraft's own rules: the dialog's history is separate from the document's, which changes when OK records one undo step and when Save All Colors or Save Prominent Colors adds a color group at once as its own undo step, which Cancel and Undo Changes leave in place; a drag is one step, fields set with `ui.dialog.set` before the next frame with the pointer up or the next step are one step, Reset is a step of its own, a new edit leaves nothing to redo, selecting another color group or Save Changes leaves nothing to undo or redo and an edit after either is a step back to the fields as they were then, a button with no step to go to is disabled, and the dialog keeps at most 64 steps and 4 MiB of them, always keeping the newest step. Tests: `undo_and_redo_changes_step_through_the_dialogs_own_edits`, `a_drag_is_one_step_of_undo_changes`, `undo_changes_reverses_reset`, `the_recolor_undo_and_redo_commands_step_the_open_dialog`, `the_recolor_undo_and_redo_commands_preview_the_step`, `an_edit_with_the_pointer_down_from_the_first_frame_is_a_step` and `rows_and_weights_set_before_the_art_is_read_are_no_step` in `crates/ui-egui/src/tests/recolor.rs`, and `undo_changes_keeps_a_bounded_history` and `another_group_or_save_changes_leaves_nothing_to_undo` and `an_edit_right_after_another_group_is_a_step` and `an_unchanged_save_changes_leaves_nothing_to_redo` in `crates/ui-egui/src/dialogs/recolor.rs`. Scores and estimates unchanged.
- **Recolor Artwork: a swatch picked for a row stays that swatch:** a row's new color is changed in the Color Picker ([Assign new colors to selected artworks](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/assign-new-colors-to-selected-artwork.html)), Scale Tints gives a row's lighter current colors lighter tints of its new color, and Preserve Tints gives a spot or global current color's tint to the new color ([CS5 help, Colorize Method](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=151), [2021 reference, Colorize Method](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=252)). VectorCraft's own rule: a spot or global swatch picked in the Color Picker's swatch list stays that swatch, so the row's art takes tints of it linked to it, also with no Limit to Library, and editing the swatch recolors the art; a process swatch gives its color as before, the row drops the swatch when its new color changes, and a swatch deleted after the pick links nothing. `recolor.apply` rows take `swatch: {name, library?}`. Tests: `a_swatch_picked_for_a_row_links_the_art_to_it_without_a_library` in `crates/ui-egui/src/tests/recolor.rs`, `a_picked_spot_swatch_gives_its_row_the_tint_slider` and `a_picked_swatch_that_is_gone_links_nothing` in `crates/ui-egui/src/dialogs/recolor.rs`, and `a_rows_swatch_links_its_art_without_limit_to_library`, `a_rows_swatch_with_a_finer_color_than_its_key_still_links` and `a_rows_library_swatch_joins_the_document_and_a_process_swatch_changes_nothing` in `crates/engine/src/tests/recolor.rs`. Scores and estimates unchanged.
- **Edit Colors parameters:** `edit.colors.saturate` needs a number `intensity`, the value from -100% to 100% that Saturate takes ([Adjusting colors](https://web.archive.org/web/20230128232631/https://helpx.adobe.com/illustrator/using/adjusting-colors.html)), and answers "missing number `intensity`" without one; a number outside the range counts as its nearest end. A value that is not a number, such as `"40"`, is refused with `` `intensity` must be a number, not "40" ``, as in every command that needs a number (`tests::params::a_malformed_required_number_is_not_reported_as_missing`). `edit.colors.adjustBalance` refuses a channel and `color.harmony` refuses `steps` or `amount` that is not a number; both read `null` as a value left out. `tests::editcolors` and `tests::colorguide` cover them.
- **Convert to Indexed Color:** Edit › Edit Colors › Convert to Indexed Color… (`edit.colors.toIndexed`) stores the embedded images in the selection as indexed-color PNGs of at most 256 colors. The palette is chosen as for a PNG-8 export, as evenly spaced levels of red, green and blue, or from the document's swatches, with diffusion, pattern or noise dithering; pixels under half opacity become transparent. The dialog previews live, and OK is one undo step. This is VectorCraft's own command and counts toward no score. `tests::editcolors` and `encode::tests_palette` cover it. Scores and estimates unchanged.
- **Working RGB numeric controls:** the Color panel and Color Picker read RGB, HSB, hex and Web Safe RGB values in the active working RGB space. Editing one RGB channel preserves the other native channels, including colors outside display sRGB. Regressions cover sRGB, Display P3, Wide Gamut RGB and ProPhoto RGB, picker initialization, native numeric round trips, and a slider click with one Undo step. Scores and estimates unchanged.