mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 02:03:02 +00:00
Merge pull request #8556 from dotCooCoo/fix/recolor-group-keeps-gradient-swatches
Recolor Artwork: OK keeps a color group's gradient and pattern swatches
This commit is contained in:
@@ -34,7 +34,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 `group` is rewritten with, a null removing the group's swatch at its place and \"keep\" leaving that swatch its colour, without the Global Adjust (past the swatches it adds nothing; refused for a swatch that is not a colour); 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, 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}",
|
||||
has_doc,
|
||||
apply
|
||||
),
|
||||
@@ -1680,12 +1680,18 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(Value::Array(cs)) => Some(cs),
|
||||
Some(_) => return Err(bad(C, "`groupColors` must be an array")),
|
||||
};
|
||||
// A null in groupColors removes the group's swatch at its place, and "keep" leaves the swatch
|
||||
// at its place its color, without the Global Adjust.
|
||||
let own: Vec<Option<Color>> = match group {
|
||||
Some(g) => {
|
||||
s.doc()?.doc.swatch_groups.iter().find(|x| x.name == g).map(|g| g.swatches.iter().map(|w| w.paint.color()).collect()).unwrap_or_default()
|
||||
}
|
||||
// The places of groupColors are those of the group's color swatches: a gradient, pattern or
|
||||
// None swatch keeps its place and paint. A null removes the color swatch at its place, and
|
||||
// "keep" leaves it its color, without the Global Adjust.
|
||||
let own: Vec<Color> = match group {
|
||||
Some(g) => s
|
||||
.doc()?
|
||||
.doc
|
||||
.swatch_groups
|
||||
.iter()
|
||||
.find(|x| x.name == g)
|
||||
.map(|g| g.swatches.iter().filter_map(|w| w.paint.color()).collect())
|
||||
.unwrap_or_default(),
|
||||
None => vec![],
|
||||
};
|
||||
let new: Vec<Option<Color>> = match group_colors {
|
||||
@@ -1694,12 +1700,8 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.enumerate()
|
||||
.map(|(i, v)| match v {
|
||||
Value::Null => Ok(None),
|
||||
// Past the group's swatches it adds nothing.
|
||||
Value::String(k) if k == "keep" => match own.get(i) {
|
||||
Some(Some(c)) => Ok(Some(*c)),
|
||||
Some(None) => Err(bad(C, format!("the swatch at place {i} of groupColors is not a colour to keep"))),
|
||||
None => Ok(None),
|
||||
},
|
||||
// Past the group's color swatches it adds nothing.
|
||||
Value::String(k) if k == "keep" => Ok(own.get(i).copied()),
|
||||
v => color_value(v)
|
||||
.map(|c| adjust.apply(c))
|
||||
.map(|c| Some(in_doc_model(palette.as_ref().map_or(c, |pl| pl.nearest(c)))))
|
||||
@@ -1747,6 +1749,7 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.map(|g| {
|
||||
g.swatches
|
||||
.iter()
|
||||
.filter(|w| w.paint.color().is_some())
|
||||
.zip(&new)
|
||||
.filter(|(w, _)| w.global && !w.is_reserved())
|
||||
.filter_map(|(w, c)| Some((w, (*c)?)))
|
||||
@@ -1766,7 +1769,7 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.collect();
|
||||
map.converted.set(false);
|
||||
let changed = keeping_series_paint(d, &ids, |d| Ok(Recolor::with_links(scope, &f, &lf).run(d, &ids)))?;
|
||||
let edit = group.map(|g| super::swatch::rewrite_group(d, g, &new, rename, C)).transpose()?;
|
||||
let edit = group.map(|g| super::swatch::rewrite_group(d, g, &new, true, rename, C)).transpose()?;
|
||||
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?;
|
||||
// Rewriting the group's swatches can change the colors of art linked to them, left out or
|
||||
// not, and of the patterns it uses. Art that only loses its link keeps its colors and is
|
||||
|
||||
@@ -1279,40 +1279,63 @@ impl GroupEdit {
|
||||
|
||||
/// Rewrite colour group `group` with `colors`: its swatches take them in order (keeping their
|
||||
/// names, kinds and global or spot flags), a `None` removes the swatch at its place, extra colors
|
||||
/// are added as new swatches and swatches past the end are removed. Paints linked to its global
|
||||
/// are added as new swatches and swatches past the end are removed. With `colors_only`, a swatch
|
||||
/// that is not a color (a gradient, pattern or None swatch) keeps its place and paint and takes no
|
||||
/// entry of `colors`, which go to the group's color swatches in order. Paints linked to its global
|
||||
/// swatches follow (a removed swatch's are unlinked); `rename` renames the group. A built-in swatch
|
||||
/// (None, Registration) it would change or remove is refused.
|
||||
pub(super) fn rewrite_group(d: &mut Document, group: &str, colors: &[Option<Color>], rename: Option<&str>, cmd: &str) -> Result<GroupEdit> {
|
||||
pub(super) fn rewrite_group(
|
||||
d: &mut Document,
|
||||
group: &str,
|
||||
colors: &[Option<Color>],
|
||||
colors_only: bool,
|
||||
rename: Option<&str>,
|
||||
cmd: &str,
|
||||
) -> Result<GroupEdit> {
|
||||
let gi = d.swatch_groups.iter().position(|g| g.name == group).ok_or_else(|| bad(cmd, format!("no colour group `{group}`")))?;
|
||||
let name = match rename.map(str::trim).filter(|n| !n.is_empty() && *n != group) {
|
||||
Some(n) => d.free_swatch_name(n),
|
||||
None => group.to_string(),
|
||||
};
|
||||
let old = &d.swatch_groups[gi].swatches;
|
||||
// The place in `colors` of each swatch's new color; none for a swatch kept as it is.
|
||||
let mut taken = 0;
|
||||
let places: Vec<Option<usize>> = old
|
||||
.iter()
|
||||
.map(|w| {
|
||||
(!colors_only || w.paint.color().is_some()).then(|| {
|
||||
taken += 1;
|
||||
taken - 1
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let new_color = |place: Option<usize>| place.and_then(|i| colors.get(i).copied().flatten());
|
||||
if let Some(w) = old
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find(|(i, w)| w.is_reserved() && colors.get(*i).copied().flatten().is_none_or(|c| w.paint.color() != Some(c)))
|
||||
.map(|x| x.1)
|
||||
.zip(&places)
|
||||
.find(|(w, place)| place.is_some() && w.is_reserved() && new_color(**place).is_none_or(|c| w.paint.color() != Some(c)))
|
||||
.map(|x| x.0)
|
||||
{
|
||||
return Err(bad(cmd, format!("`{}` can't be edited or removed", w.name)));
|
||||
}
|
||||
let colorized_ok = super::paint::check_colorized(d).is_ok();
|
||||
let mut relinks = vec![];
|
||||
let old = std::mem::take(&mut d.swatch_groups[gi].swatches);
|
||||
let old_len = old.len();
|
||||
// The swatches that stay, each with its new color.
|
||||
let mut kept: Vec<(Swatch, Color)> = vec![];
|
||||
for (i, w) in old.into_iter().enumerate() {
|
||||
match colors.get(i).copied().flatten() {
|
||||
Some(c) => kept.push((w, c)),
|
||||
None if w.global => relinks.push(Relink { from: w.name.clone(), to: w.name, color: None, keep: false }),
|
||||
None => {}
|
||||
// The swatches that stay, each with its new color (none for one kept as it is).
|
||||
let mut kept: Vec<(Swatch, Option<Color>)> = vec![];
|
||||
for (w, place) in old.into_iter().zip(places) {
|
||||
match (place, new_color(place)) {
|
||||
(None, _) => kept.push((w, None)),
|
||||
(_, Some(c)) => kept.push((w, Some(c))),
|
||||
(_, None) if w.global => relinks.push(Relink { from: w.name.clone(), to: w.name, color: None, keep: false }),
|
||||
(_, None) => {}
|
||||
}
|
||||
}
|
||||
let mut swatches = Vec::with_capacity(kept.len());
|
||||
for (mut w, c) in kept {
|
||||
if w.paint.color() != Some(c) {
|
||||
if let Some(c) = c
|
||||
&& w.paint.color() != Some(c)
|
||||
{
|
||||
// A tint swatch becomes a colour of its own.
|
||||
w.paint = Paint::solid(c);
|
||||
if w.global {
|
||||
@@ -1325,7 +1348,7 @@ pub(super) fn rewrite_group(d: &mut Document, group: &str, colors: &[Option<Colo
|
||||
let mut free = d.free_swatch_names();
|
||||
free.insert(&name);
|
||||
swatches.iter().for_each(|w| free.insert(&w.name));
|
||||
for c in colors.iter().skip(old_len).flatten() {
|
||||
for c in colors.iter().skip(taken).flatten() {
|
||||
let nm = free.take(&color_name(*c));
|
||||
swatches.push(Swatch { name: nm, paint: Paint::solid(*c), global: false, spot: false });
|
||||
}
|
||||
@@ -1379,7 +1402,7 @@ fn swatch_edit_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
{
|
||||
return Ok(json!({"name": group, "swatches": g.swatches.iter().map(|w| w.name.clone()).collect::<Vec<_>>(), "relinked": 0}));
|
||||
}
|
||||
let e = s.edit("Edit Color Group", |d, _| rewrite_group(d, group, &colors, rename, C))?;
|
||||
let e = s.edit("Edit Color Group", |d, _| rewrite_group(d, group, &colors, false, rename, C))?;
|
||||
e.defaults(s)?;
|
||||
Ok(json!({"name": e.name, "swatches": e.swatches, "relinked": e.relinked}))
|
||||
}
|
||||
|
||||
@@ -836,6 +836,49 @@ fn a_null_in_group_colors_removes_that_swatch_and_the_ones_after_it_keep_their_p
|
||||
assert_eq!(link(&s, green), ("#00ff00".into(), Some(names[2].clone())), "art linked to a swatch that stays keeps its link");
|
||||
}
|
||||
|
||||
/// A gradient or pattern swatch of the group keeps its place and its paint when `recolor.apply`
|
||||
/// rewrites the group: the group's colors, from the rows or from `groupColors`, go to its color
|
||||
/// swatches in order.
|
||||
#[test]
|
||||
fn apply_with_a_group_keeps_its_gradient_swatch() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.newGroup", json!({"name": "Brand", "colors": ["#ff0000", "#0000ff"]}));
|
||||
let fade = vectorcraft_color::Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(vectorcraft_color::Gradient::default())));
|
||||
s.edit("test", |d, _| {
|
||||
let w = vectorcraft_color::Swatch { name: "Fade".into(), paint: fade.clone(), global: false, spot: false };
|
||||
d.swatch_groups.iter_mut().find(|g| g.name == "Brand").unwrap().swatches.insert(1, w);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let group = |s: &Session| -> Vec<(String, Option<String>)> {
|
||||
let g = s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Brand").unwrap().swatches.clone();
|
||||
g.iter().map(|w| (w.name.clone(), w.paint.color().map(|c| c.to_hex()))).collect()
|
||||
};
|
||||
let names: Vec<String> = group(&s).into_iter().map(|(n, _)| n).collect();
|
||||
rect(&mut s, json!("#ff0000"));
|
||||
rect(&mut s, json!("#0000ff"));
|
||||
select_all(&mut s);
|
||||
// The rows' new colors go to the red and blue swatches; the gradient stays between them.
|
||||
let map = json!([{"from": ["#ff0000"], "to": "#00ff00"}, {"from": ["#0000ff"], "to": "#ffff00"}]);
|
||||
run(&mut s, "recolor.apply", json!({"map": map, "group": "Brand"}));
|
||||
let want = |a: &str, b: &str| vec![(names[0].clone(), Some(a.to_string())), (names[1].clone(), None), (names[2].clone(), Some(b.to_string()))];
|
||||
assert_eq!(group(&s), want("#00ff00", "#ffff00"));
|
||||
assert_eq!(gradient_at(&s, 1), fade, "the gradient swatch keeps its paint");
|
||||
// `groupColors` counts the color swatches only: "keep" is the first, and the second color is
|
||||
// the blue swatch's.
|
||||
run(&mut s, "recolor.apply", json!({"map": [], "group": "Brand", "groupColors": ["keep", "#123456"]}));
|
||||
assert_eq!(group(&s), want("#00ff00", "#123456"));
|
||||
// A null removes the color swatch at its place and leaves the gradient.
|
||||
run(&mut s, "recolor.apply", json!({"map": [], "group": "Brand", "groupColors": [null, "#123456"]}));
|
||||
assert_eq!(group(&s), [(names[1].clone(), None), (names[2].clone(), Some("#123456".into()))]);
|
||||
assert_eq!(gradient_at(&s, 0), fade);
|
||||
}
|
||||
|
||||
/// The paint of the swatch at place `i` of the group "Brand".
|
||||
fn gradient_at(s: &Session, i: usize) -> vectorcraft_color::Paint {
|
||||
s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Brand").unwrap().swatches[i].paint.clone()
|
||||
}
|
||||
|
||||
/// A row whose new color was removed keeps its art's colors: art in it linked to another swatch of
|
||||
/// the group, which the rewrite gives another color, loses the link instead of following it.
|
||||
#[test]
|
||||
|
||||
@@ -3600,7 +3600,7 @@ mod tests {
|
||||
vectorcraft_color::Swatch { name: "Fade".into(), paint, global: false, spot: false }
|
||||
}
|
||||
|
||||
/// With art, the preview rewrites the group being edited, its other swatch included; Save
|
||||
/// With art, the preview rewrites the group being edited and keeps its other swatch; Save
|
||||
/// Changes is still refused, as the group is without the preview, and Cancel leaves it as it was.
|
||||
#[test]
|
||||
fn saving_a_group_with_a_swatch_that_is_not_a_color_is_refused_while_previewing() {
|
||||
@@ -3623,8 +3623,9 @@ mod tests {
|
||||
d.fields.insert("rows".into(), Value::Array(rs));
|
||||
frame(&mut app, &ctx, 0.1, vec![], 0);
|
||||
assert!(app.session.in_interaction(), "the art previews");
|
||||
let previewed = app.session.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Mixed").map(|g| g.swatches.len());
|
||||
assert_eq!(previewed, Some(2), "the preview's rewrite of the group leaves out its other swatch");
|
||||
let previewed = app.session.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Mixed").map(|g| g.swatches.clone());
|
||||
assert_eq!(previewed.as_ref().map(Vec::len), Some(3), "the preview's rewrite of the group keeps its other swatch");
|
||||
assert_eq!(previewed.and_then(|s| s.last().cloned()), Some(fade_swatch()), "with its paint");
|
||||
let refused: Result<(), String> = Err("color group `Mixed` holds swatches that are not colors, which Save Changes can't keep".into());
|
||||
assert_eq!(act(&mut app, &ctx, 0.2, "save"), refused);
|
||||
crate::dialogs::cancel(&mut app);
|
||||
|
||||
+5
-4
@@ -5150,10 +5150,11 @@ moves a row's `tint` with its new color and removes it from a color it changes,
|
||||
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
|
||||
group together. A `null` in `groupColors` removes the group's swatch at that place, and the swatches after it keep
|
||||
their colors and names; art linked to a removed global swatch keeps its color and is no longer linked to it. `"keep"` in
|
||||
`groupColors` leaves the swatch at that place its color, without the Global Adjust; past the group's swatches it adds
|
||||
nothing, and it is refused for a swatch that is not a color. Art linked to one of the group's global swatches stays linked when the swatch is rewritten with its
|
||||
group together. The group's colors, from the rows or from `groupColors`, go to its color swatches in order; a gradient,
|
||||
pattern or None swatch in the group keeps its place and its paint. A `null` in `groupColors` removes the color swatch at
|
||||
that place, and the swatches after it keep their colors and names; art linked to a removed global swatch keeps its color
|
||||
and is no longer linked to it. `"keep"` in `groupColors` leaves the color swatch at that place its color, without the
|
||||
Global Adjust; past the group's color swatches it adds nothing. Art linked to one of the group's global swatches stays linked when the swatch is rewritten with its
|
||||
row's new color (the default without `groupColors` when the rows follow the group's order), so a later `swatch.edit` still
|
||||
reaches it; the reply's `relinked` counts the other linked paints that took the group's new colors. Art in a row that
|
||||
is linked to a swatch rewritten with another color keeps its row's new color, even an unchanged one, and is no longer
|
||||
|
||||
Reference in New Issue
Block a user