Merge pull request #7768 from dotCooCoo/feat/recolor-add-remove-color-tools

Recolor Artwork: the Edit tab's Add Color and Remove Color tools add and remove colors
This commit is contained in:
BFlat
2026-11-16 12:55:34 +07:00
committed by GitHub
37 changed files with 663 additions and 63 deletions
+59 -16
View File
@@ -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], 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)}] | {\"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] (what `group` is rewritten with; default: the rows' new colours, in order, excluded and empty 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] (what `group` is rewritten with, a null removing the group's swatch at its place; 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
),
@@ -1384,6 +1384,9 @@ struct Row {
tint: f32,
/// The row's own `model`, which takes the place of the command's for its colors.
model: Option<ModelRule>,
/// `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,
}
/// The color model a row's colors take (`model`): each color's own, the new color's, or the
@@ -1437,9 +1440,10 @@ fn parse_rows(p: &Value, cmd: &str) -> Result<Vec<Row>> {
};
let cur = |v: &Value| Match::of(v).ok_or_else(|| bad(cmd, format!("bad current colour {v}")));
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 })).collect()
}
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 }))
.collect(),
Some(Value::Array(rows)) => rows
.iter()
.map(|r| {
@@ -1450,7 +1454,8 @@ 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)?;
Ok(Row { from, to: new(r.get("to"))?, exclude: switch_or(r, "exclude", false, cmd)?, tint, model })
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 })
})
.collect(),
_ => Err(bad(cmd, "missing `map` (rows [{from, to}] or {current: new})")),
@@ -1487,6 +1492,10 @@ struct ColorMap {
group: Vec<GroupSwatch>,
keys: HashMap<ColorKey, usize>,
hexes: HashMap<String, usize>,
/// The current colors of the rows whose new color was removed (`to: null`, not excluded),
/// which keep their colors.
removed_keys: std::collections::HashSet<ColorKey>,
removed_hexes: std::collections::HashSet<String>,
/// Set when a colour took a new colour of another model in its own model.
converted: std::cell::Cell<bool>,
/// The Global Adjust every mapped colour takes after its row's new colour.
@@ -1505,11 +1514,23 @@ impl ColorMap {
group,
keys: HashMap::new(),
hexes: HashMap::new(),
removed_keys: Default::default(),
removed_hexes: Default::default(),
converted: Default::default(),
adjust,
};
for (n, r) in rows.iter().enumerate().filter(|(_, r)| !r.from.is_empty()) {
let Some(to) = r.new_color() else { continue };
let Some(to) = r.new_color() else {
if !r.exclude {
for m in &r.from {
match m {
Match::Key(k) => out.removed_keys.insert(*k),
Match::Hex(h) => out.removed_hexes.insert(h.clone()),
};
}
}
continue;
};
let i = out.rows.len();
let colors: Vec<Color> = r.from.iter().map(Match::color).collect();
let link = links.get(n).cloned().flatten();
@@ -1550,9 +1571,18 @@ impl ColorMap {
/// the row gives it the new color in that color's model and the Global Adjust gives it the
/// swatch's new color at that tint;
/// other rows map the colour, which loses its link when it changes or when the group's rewrite
/// would change it. True when anything changed.
/// would change it; a color of a row whose new color was removed keeps its color and loses its
/// link to a swatch of the group whose rewrite would change it. True when anything changed.
fn map_link(&self, c: &mut Color, link: &mut Option<String>, tint: &mut f32) -> bool {
let Some(i) = self.row_of(*c) else { return false };
let Some(i) = self.row_of(*c) else {
let removed = self.removed_keys.contains(&ColorKey::of(c)) || self.removed_hexes.contains(&c.to_hex());
let rewritten = link.as_deref().and_then(|n| self.group.iter().find(|g| g.name == n)).is_some_and(|g| g.shown.tinted(*tint) != *c);
if removed && rewritten {
*link = None;
return true;
}
return false;
};
let (Some(row), Some(l)) = (self.rows.get(i), self.links.get(i)) else { return false };
if l.is_none()
&& let Some(g) = link.as_deref().and_then(|n| self.group.iter().find(|g| g.name == n))
@@ -1650,18 +1680,27 @@ 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")),
};
let new: Vec<Color> = match group_colors {
// A null in groupColors removes the group's swatch at its place.
let new: Vec<Option<Color>> = match group_colors {
Some(cs) => cs
.iter()
.map(|v| {
color_value(v)
.map(|v| match v {
Value::Null => Ok(None),
v => color_value(v)
.map(|c| adjust.apply(c))
.map(|c| in_doc_model(palette.as_ref().map_or(c, |pl| pl.nearest(c))))
.ok_or_else(|| bad(C, format!("bad colour {v} in groupColors")))
.map(|c| Some(in_doc_model(palette.as_ref().map_or(c, |pl| pl.nearest(c)))))
.ok_or_else(|| bad(C, format!("bad colour {v} in groupColors"))),
})
.collect::<Result<_>>()?,
// A row with no current colors gives the group no color.
None => rows.iter().filter(|r| !r.from.is_empty()).filter_map(Row::new_color).map(|c| mapped_adjust.apply(c)).collect(),
// A row with no current colors gives the group no color, unless it is a color added to
// the group: those follow the colors of the rows with current colors.
None => rows
.iter()
.filter(|r| !r.from.is_empty())
.chain(rows.iter().filter(|r| r.from.is_empty() && r.added))
.filter_map(Row::new_color)
.map(|c| Some(mapped_adjust.apply(c)))
.collect(),
};
let rename = text_param(p, "rename", C)?;
let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok();
@@ -1696,7 +1735,8 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
.iter()
.zip(&new)
.filter(|(w, _)| w.global && !w.is_reserved())
.map(|(w, c)| GroupSwatch { name: w.name.clone(), color: *c, shown: d.linked_color(*c, w.spot) })
.filter_map(|(w, c)| Some((w, (*c)?)))
.map(|(w, c)| GroupSwatch { name: w.name.clone(), color: c, shown: d.linked_color(c, w.spot) })
.collect()
})
.unwrap_or_default();
@@ -1779,6 +1819,9 @@ fn randomize(_: &mut Session, p: &Value) -> Result<Value> {
if let Some(m) = model {
row["model"] = json!(m.id());
}
if r.added {
row["added"] = json!(true);
}
row
})
.collect();
+27 -15
View File
@@ -1255,43 +1255,54 @@ impl GroupEdit {
}
/// Rewrite colour group `group` with `colors`: its swatches take them in order (keeping their
/// names, kinds and global or spot flags), extra colours are added as new swatches and swatches
/// past the end are removed. 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: &[Color], rename: Option<&str>, cmd: &str) -> Result<GroupEdit> {
/// 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
/// 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> {
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;
if let Some(w) = old.iter().enumerate().find(|(i, w)| w.is_reserved() && colors.get(*i).is_none_or(|c| w.paint.color() != Some(*c))).map(|x| x.1)
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)
{
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 mut swatches = std::mem::take(&mut d.swatch_groups[gi].swatches);
for gone in swatches.split_off(colors.len().min(swatches.len())) {
if gone.global {
relinks.push(Relink { from: gone.name.clone(), to: gone.name, color: None, keep: false });
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 => {}
}
}
for (w, c) in swatches.iter_mut().zip(colors) {
if w.paint.color() != Some(*c) {
let mut swatches = Vec::with_capacity(kept.len());
for (mut w, c) in kept {
if w.paint.color() != Some(c) {
// A tint swatch becomes a colour of its own.
w.paint = Paint::solid(*c);
w.paint = Paint::solid(c);
if w.global {
// Art linked to a Lab spot shows it as the Spot Colors options say.
relinks.push(Relink { from: w.name.clone(), to: w.name.clone(), color: Some(d.linked_color(*c, w.spot)), keep: true });
relinks.push(Relink { from: w.name.clone(), to: w.name.clone(), color: Some(d.linked_color(c, w.spot)), keep: true });
}
}
swatches.push(w);
}
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(swatches.len()) {
for c in colors.iter().skip(old_len).flatten() {
let nm = free.take(&color_name(*c));
swatches.push(Swatch { name: nm, paint: Paint::solid(*c), global: false, spot: false });
}
@@ -1320,6 +1331,7 @@ fn swatch_edit_group(s: &mut Session, p: &Value) -> Result<Value> {
let colors: Vec<Color> =
colors.into_iter().enumerate().map(|(i, c)| if old.get(i) == Some(&Some(c)) { c } else { super::paint::new_color(s, p, c) }).collect();
let rename = str_param(p, "rename");
let colors: Vec<Option<Color>> = colors.into_iter().map(Some).collect();
let e = s.edit("Edit Color Group", |d, _| rewrite_group(d, group, &colors, rename, C))?;
e.defaults(s)?;
Ok(json!({"name": e.name, "swatches": e.swatches, "relinked": e.relinked}))
+88
View File
@@ -359,6 +359,35 @@ fn an_empty_row_adds_no_swatch_and_no_group_color() {
assert_eq!(hexes, ["#ff0000", "#0000ff"]);
}
/// An empty row with `added` (a color the Add Color tool added) recolors nothing, and without
/// `groupColors` gives a rewritten group its new color after the colors of the rows with current
/// colors; randomize keeps the flag, and an `added` that is not true or false is refused.
#[test]
fn an_added_empty_row_gives_the_group_its_color_after_the_others() {
let mut s = session();
let red = rect(&mut s, json!("#ff0000"));
let blue = rect(&mut s, json!("#0000ff"));
run(&mut s, "swatch.newGroup", json!({"name": "Pair", "colors": ["#ff0000", "#0000ff"]}));
select_all(&mut s);
let map = json!([
{"from": [], "to": "rgb 0 255 0", "added": true},
{"from": [], "to": "rgb 9 9 9"},
{"from": ["rgb 255 0 0"], "to": "rgb 255 0 0"},
{"from": ["rgb 0 0 255"], "to": "rgb 0 0 255"},
]);
let shuffled = run(&mut s, "recolor.randomize", json!({"map": map, "seed": 1}));
assert_eq!(shuffled["map"][0]["added"], json!(true), "{shuffled}");
assert_eq!(shuffled["map"][1].get("added"), None, "{shuffled}");
run(&mut s, "recolor.apply", json!({"map": map, "group": "Pair"}));
let d = &s.doc().unwrap().doc;
let g = d.swatch_groups.iter().find(|g| g.name == "Pair").unwrap();
let hexes: Vec<String> = g.swatches.iter().map(|w| w.paint.color().unwrap().to_hex()).collect();
assert_eq!(hexes, ["#ff0000", "#0000ff", "#00ff00"]);
assert_eq!((fill(&s, red).to_hex(), fill(&s, blue).to_hex()), ("#ff0000".into(), "#0000ff".into()), "no art is recolored");
let bad = json!([{"from": [], "to": "rgb 0 255 0", "added": "yes"}]);
assert!(s.execute("recolor.apply", &json!({"map": bad})).is_err());
}
#[test]
fn randomize_shuffles_new_colours_and_skips_excluded_rows() {
let mut s = session();
@@ -765,6 +794,65 @@ fn recolor_of_everything_counts_locked_art_that_only_loses_its_group_swatch_link
assert_eq!(r["notChanged"], json!({"locked": 1, "hidden": 0}), "{r}");
}
#[test]
fn a_null_in_group_colors_removes_that_swatch_and_the_ones_after_it_keep_their_places() {
let mut s = session();
run(&mut s, "swatch.newGroup", json!({"name": "Brand", "colors": ["#2878f0", "#ff0000", "#00ff00"]}));
let group = |s: &Session| -> Vec<(String, 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().unwrap().to_hex())).collect()
};
let names: Vec<String> = group(&s).into_iter().map(|(n, _)| n).collect();
for name in &names {
run(&mut s, "swatch.edit", json!({"name": name, "global": true}));
}
let red = rect(&mut s, json!("#000000"));
let green = rect(&mut s, json!("#000000"));
run(&mut s, "paint.setFill", json!({"ids": [red.0], "swatch": names[1]}));
run(&mut s, "paint.setFill", json!({"ids": [green.0], "swatch": names[2]}));
select_all(&mut s);
// The middle swatch goes; the last keeps its name and color, and a color added after them is new.
run(&mut s, "recolor.apply", json!({"map": [], "group": "Brand", "groupColors": ["#2878f0", null, "#00ff00", "#123456"]}));
let g = group(&s);
assert_eq!(g.len(), 3, "{g:?}");
assert_eq!(g[..2], [(names[0].clone(), "#2878f0".into()), (names[2].clone(), "#00ff00".into())]);
assert_eq!(g[2].1, "#123456");
let link = |s: &Session, id: NodeId| match s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint() {
vectorcraft_color::Paint::Solid { color, swatch, .. } => (color.to_hex(), swatch),
p => panic!("{p:?}"),
};
assert_eq!(link(&s, red), ("#ff0000".into(), None), "art linked to the removed swatch keeps its color, unlinked");
assert_eq!(link(&s, green), ("#00ff00".into(), Some(names[2].clone())), "art linked to a swatch that stays keeps its link");
}
/// 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]
fn art_of_a_row_without_a_new_color_keeps_its_color_when_its_swatch_takes_another() {
let mut s = session();
run(&mut s, "swatch.newGroup", json!({"name": "Brand", "colors": ["#ff0000", "#0000ff", "#00ff00"]}));
let names: Vec<String> =
s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Brand").unwrap().swatches.iter().map(|w| w.name.clone()).collect();
for name in &names {
run(&mut s, "swatch.edit", json!({"name": name, "global": true}));
}
let blue = rect(&mut s, json!("#000000"));
let green = rect(&mut s, json!("#000000"));
run(&mut s, "paint.setFill", json!({"ids": [blue.0], "swatch": names[1]}));
run(&mut s, "paint.setFill", json!({"ids": [green.0], "swatch": names[2]}));
select_all(&mut s);
// The rows are blue, red and green; the blue row's new color is removed, so the group's first
// swatch goes and its second takes the red row's new color.
let map = json!([{"from": ["#0000ff"], "to": null}, {"from": ["#ff0000"], "to": "#ff0000"}, {"from": ["#00ff00"], "to": "#00ff00"}]);
run(&mut s, "recolor.apply", json!({"map": map, "group": "Brand", "groupColors": [null, "#ff0000", "#00ff00"]}));
let link = |s: &Session, id: NodeId| match s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint() {
vectorcraft_color::Paint::Solid { color, swatch, .. } => (color.to_hex(), swatch),
p => panic!("{p:?}"),
};
assert_eq!(link(&s, blue), ("#0000ff".into(), None), "the art keeps its color, unlinked");
assert_eq!(link(&s, green), ("#00ff00".into(), Some(names[2].clone())), "art of another row keeps its link");
}
#[test]
fn recolor_of_everything_does_not_count_locked_art_whose_pattern_the_group_rewrite_recolors() {
let mut s = session();
+212 -26
View File
@@ -24,7 +24,13 @@
//! show the new colors on the smooth wheel, on a segmented wheel (solid patches of 24 hues by 5
//! saturations; its markers move as freely) or as color bars (one per new color, in row order: click
//! one to select it for the sliders, drag one to move its row, which changes no color); the dialog
//! opens on the smooth wheel. With art, the Prominent Colors bar under the wheel shows the new
//! opens on the smooth wheel. Under them, the Add Color tool adds a click on either wheel as a new
//! color (the hue and saturation clicked, at the wheel's brightness; on the segmented wheel the
//! patch's color) in a new row with no current colors, which becomes the selected one, and the
//! Remove Color tool removes the color whose marker is clicked; a bar's right-click menu has Remove
//! Color too. The base color can't be removed. A removed color's row goes, unless it has current
//! colors and art or a group is open: it then keeps them, with no new color, so that art keeps its
//! colors and the group's swatch at that place goes. With art, the Prominent Colors bar under the wheel shows the new
//! colors, each part as wide as its row's share of the art's uses, the largest first; dragging the
//! edge between two parts moves width between them, and when the drag ends the rows' current
//! colors move toward those widths (`recolor.weigh`), and the art previews them. The New Color
@@ -39,19 +45,22 @@
//! The Color Theme Picker button beside the tabs turns on picking from the canvas: a click on an
//! object takes the palette of the object a Selection tool click takes, a drag takes the palette
//! of the art inside its marquee, and Shift adds to the picks so far (`recolor.pickTheme`). The
//! rows that aren't excluded and hold current colors take the picked colors as their new colors,
//! rows that aren't excluded and hold current colors (or were added on the Edit tab) take the
//! picked colors as their new colors,
//! the most used color first and repeating when the rows outnumber them, and the art previews
//! them; OK keeps them as one undo step. A new count of Colors keeps the picks: the new rows take them again.
//!
//! Fields (`ui.dialog.set`): `rows` ([{from: [keys], to: key, exclude?, tint?: percent of a spot
//! color}]), `colors` (null: Auto, or a count), `method`, `preserveWhite`, `preserveBlack`,
//! color, added?}]; 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), `colors` (null: Auto, or a count), `method`, `preserveWhite`, `preserveBlack`,
//! `preserveGrays`, `limitTo` (library id, "document" for the document's swatches, "" for none),
//! `group`, `groupName`, `tab` (`assign` or `edit`), `rule` (harmony id), `linked`, `preview`,
//! `sliderMode` (`hsb`, `rgb`, `cmyk`, `lab` or `tint`; unset: the row color's own model, HSB for
//! a gray and Tint for a spot color; `global`: Global Adjust, on the Edit tab), `globalAdjust`
//! (`{saturation, brightness, temperature, luminosity}` in percent, sent as `recolor.apply`'s
//! `globalAdjust` in every slider mode), `display` (the Edit tab's `smooth`, `segmented` or `bars`;
//! unset: `smooth`), `themePicker` (the Color Theme Picker is on), `themePicks` (its picks, as
//! unset: `smooth`), `wheelTool` (`add`: the Add Color tool, `remove`: the Remove Color tool;
//! unset: neither, a click on the wheel selects a marker), `themePicker` (the Color Theme Picker is on), `themePicks` (its picks, as
//! `recolor.pickTheme`'s `picks`; a new list recolors the rows), `weights` (one per row, as
//! `recolor.weigh`'s; a new list moves the rows' current colors toward them), `findColors` (Find is
//! on; it shows the art so on the Assign tab, with art and rows selected). Changing `colors`, a
@@ -393,7 +402,7 @@ fn group_colors<'a>(app: &VectorcraftApp, d: &Dialog, rs: impl Iterator<Item = &
}
/// The New Color Group menu's request: save the new colors of the rows that aren't excluded and
/// hold current colors (Save All Colors, in row order; a row without one gives its first current
/// hold current colors or were added on the Edit tab (Save All Colors, in row order; a row without one gives its first current
/// color) or of the Prominent Colors bar (Save Prominent Colors, in its order) as a new color
/// group, a step of its own (`swatch.newGroup`).
fn save_group(app: &mut VectorcraftApp, d: &mut Dialog, which: &str) {
@@ -420,7 +429,7 @@ const THEME_PICKS: &str = "themePicks";
const THEME_DONE: &str = "__themePicked";
/// When the picks of the Color Theme Picker changed, give the rows that aren't excluded and hold
/// current colors the palette of the art picked (`recolor.pickTheme`, as many colors as those
/// current colors or were added on the Edit tab the palette of the art picked (`recolor.pickTheme`, as many colors as those
/// rows), in row order; with fewer colors than rows, the colors repeat. Picks that touch no art
/// leave the rows as they are.
fn sync_theme(app: &mut VectorcraftApp, d: &mut Dialog) {
@@ -561,14 +570,25 @@ fn excluded(row: &Value) -> bool {
row["exclude"].as_bool().unwrap_or(false)
}
/// Whether `row` holds no current colors: a row made with New Row, until colors are merged into it.
/// Its new color recolors nothing and is no color of a color group, the wheel or the harmony rules.
/// Whether `row` has no current colors (a row made with New Row, or a color added on the Edit tab).
fn no_current(row: &Value) -> bool {
row["from"].as_array().is_none_or(Vec::is_empty)
}
/// Whether `row` is a color added on the Edit tab (`added`), which joins the color group.
fn is_added(row: &Value) -> bool {
row["added"].as_bool().unwrap_or(false)
}
/// Whether `row` is a row made with New Row that holds no current colors, until colors are merged
/// into it. Its new color recolors nothing and is no color of a color group, the wheel or the
/// harmony rules. A color added on the Edit tab (`added`) is not empty: it joins the color group.
fn empty(row: &Value) -> bool {
row["from"].as_array().is_some_and(Vec::is_empty)
row["from"].as_array().is_some_and(Vec::is_empty) && !is_added(row)
}
/// Whether `row`'s new color is one of the colors a color group takes: the row isn't excluded and
/// holds current colors.
/// holds current colors or is a color added on the Edit tab.
fn in_group(row: &Value) -> bool {
!excluded(row) && !empty(row)
}
@@ -583,15 +603,19 @@ fn selection(d: &Dialog) -> Vec<usize> {
}
/// `recolor.apply` parameters: the rows, method, library and the group with its new name and
/// colours: the rows' new colours, then (with art) the group's colours no row took.
/// colors: the new colors of the rows with current colors, each in its swatch's place (`null`
/// for a row whose new color was removed, which removes its swatch), then (with art) the group's
/// colors no row took, then the colors added on the Edit tab.
fn apply_params(d: &Dialog) -> Value {
let rs = rows(d);
let group = d.fields.get("group").and_then(Value::as_str).map(|g| {
// A row made with New Row that holds no current colors gives the group no color.
let filled: Vec<&Value> = rs.iter().filter(|r| !empty(r)).map(|r| &r["to"]).collect();
// A row made with New Row that holds no current colors gives the group no color; a color
// added on the Edit tab (`added`) joins it after the others.
let took: Vec<&Value> = rs.iter().filter(|r| !no_current(r)).map(|r| &r["to"]).collect();
let assign = d.fields.get("__assign").and_then(Value::as_array).filter(|_| d.bool("__art"));
let rest = assign.map_or(&[][..], |a| a.get(filled.len()..).unwrap_or_default());
let colors: Vec<&Value> = filled.into_iter().chain(rest).collect();
let rest = assign.map_or(&[][..], |a| a.get(took.len()..).unwrap_or_default());
let added = rs.iter().filter(|r| no_current(r) && is_added(r) && !excluded(r)).map(|r| &r["to"]).filter(|c| !c.is_null());
let colors: Vec<&Value> = took.into_iter().chain(rest).chain(added).collect();
let name = d.str("groupName");
let rename = (!name.trim().is_empty() && name != g).then_some(name);
json!({"group": g, "groupColors": colors, "rename": rename})
@@ -921,15 +945,21 @@ fn assign_tab(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut
let (nr, _) = ui.allocate_exact_size(vec2(46.0, 20.0), Sense::hover());
let nresp = ui.interact(nr, egui::Id::unique((NEW_CHIP, i)), Sense::click());
let to = to_color(row).unwrap_or_default();
chip(ui, nr, shown.get(i).copied().unwrap_or_default(), off);
// A row whose new color was removed shows an empty frame and an empty hex field.
let has_new = to_color(row).is_some();
if has_new {
chip(ui, nr, shown.get(i).copied().unwrap_or_default(), off);
} else {
ui.painter().rect_stroke(nr, 1.0, egui::Stroke::new(1.0, t.border), egui::StrokeKind::Inside);
}
if nresp.clicked() {
clicked = Some(i);
}
if nresp.double_clicked() {
if nresp.double_clicked() && has_new {
pick = Some(i);
}
ui.add_space(6.0);
let hex = crate::panels::color::hex_digits(&to);
let hex = if has_new { crate::panels::color::hex_digits(&to) } else { String::new() };
let hex_name = format!("{} {}", tl!("Color"), i + 1);
if let Some(h) = widgets::hex_field_named(ui, ("recolor-hex", i), Some(&hex_name), &hex)
&& let Some(c) = crate::panels::color::parse_hex(&h)
@@ -1383,7 +1413,7 @@ fn new_row(rows: &mut Vec<Value>, sel: &[usize]) -> usize {
}
/// The rows the Edit tab shows, the harmony rules fill and the Color Theme Picker recolors: those
/// with a new colour that aren't excluded and hold current colors.
/// with a new colour that aren't excluded and hold current colors or were added on the Edit tab.
fn active_rows(rows: &[Value]) -> Vec<usize> {
(0..rows.len()).filter(|i| in_group(&rows[*i]) && to_color(&rows[*i]).is_some()).collect()
}
@@ -1413,8 +1443,61 @@ fn move_color(rows: &mut [Value], i: usize, hsb: [f32; 3], linked: bool) {
/// The rows when a drag on the Edit tab's wheel started.
const DRAG: &str = "__drag";
/// The field of the Edit tab's wheel tools: `add` (Add Color) or `remove` (Remove Color).
const WHEEL_TOOL: &str = "wheelTool";
/// The new color the Add Color tool gives a click at hue `h` (degrees) and saturation `s`: at the
/// brightness of `base` (the base color, whose brightness the wheel shows; full without one), the
/// segmented wheel's patch color with `segmented`, in `base`'s model.
fn added_color(base: Option<Color>, h: f32, s: f32, segmented: bool) -> Color {
let v = base.map_or(1.0, |b| b.to_hsb()[2]);
let c = if segmented { widgets::segment_color(h, s, v) } else { Color::from_hsb(h, s, v) };
base.map_or(c, |b| keep_model(b, c))
}
/// Add new color `c` as a row with no current colors, marked `added`, after the others. Returns
/// its index.
fn add_color(rows: &mut Vec<Value>, c: &Color) -> usize {
rows.push(json!({"from": [], "to": key(c), "added": true}));
rows.len() - 1
}
/// Remove row `i`'s new color: a row with no current colors (or, without `keep`, any row) goes,
/// and with `keep` (art, or a color group whose swatches the rows are) a row with current colors
/// stays with no new color, so that its art keeps its colors and its group swatch is removed in
/// its place. The base row `base` stays. Returns the base row's index afterwards, or `None` when
/// nothing changed.
fn remove_color(rows: &mut Vec<Value>, i: usize, base: Option<usize>, keep: bool) -> Option<usize> {
if Some(i) == base || i >= rows.len() || to_color(&rows[i]).is_none() {
return None;
}
if keep && !no_current(&rows[i]) {
rows[i]["to"] = Value::Null;
if let Some(r) = rows[i].as_object_mut() {
r.remove("tint");
r.remove("model");
}
return Some(base.unwrap_or(0));
}
rows.remove(i);
Some(base.map_or(0, |b| if b > i { b - 1 } else { b }))
}
/// Whether Remove Color keeps a row with current colors (see [`remove_color`]): with art, or with a
/// color group.
fn keeps_rows(d: &Dialog) -> bool {
d.bool("__art") || d.fields.get("group").is_some_and(Value::is_string)
}
/// After Remove Color: select the base row at `base`; the slider values held were for a row index
/// that may now hold another row.
fn removed(d: &mut Dialog, base: usize) {
d.fields.insert("__sel".into(), json!([base]));
d.fields.remove(COMPS);
}
/// The Edit tab. Returns true when the rows changed.
fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value]) -> bool {
fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut Vec<Value>) -> bool {
let top = ui.cursor().top();
let t = Tokens::get(ui.ctx());
let mut changed = false;
@@ -1468,6 +1551,9 @@ fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value
let colors: Vec<Color> = active.iter().filter_map(|&i| to_color(&rows[i])).collect();
let marked = base.and_then(|b| active.iter().position(|&i| i == b));
let display = d.str("display");
let tool = d.str(WHEEL_TOOL);
// The tools act on either wheel, not on the color bars.
let on_wheel = display != "bars";
let mut w = widgets::WheelResponse::default();
ui.horizontal(|ui| {
// The display buttons, beside the wheel so the tab keeps its height.
@@ -1482,6 +1568,14 @@ fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value
d.fields.insert("display".into(), json!(id));
}
}
// The wheel tools: a click on the button turns its tool on, or off again.
ui.add_space(8.0);
for (id, icon, tip) in [("add", "plus", tl!("Add Color Tool")), ("remove", "minus", tl!("Remove Color Tool"))] {
let on = tool == id;
if widgets::icon_button_enabled(ui, icon, tip, on && on_wheel, on_wheel, 24.0).clicked() {
d.fields.insert(WHEEL_TOOL.into(), if on { Value::Null } else { json!(id) });
}
}
});
ui.vertical(|ui| match display.as_str() {
"segmented" => w = widgets::segmented_wheel(ui, "recolor-wheel", WHEEL, &colors, marked),
@@ -1489,17 +1583,33 @@ fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value
_ => w = widgets::harmony_wheel(ui, "recolor-wheel", WHEEL, &colors, marked),
});
});
// A click with a wheel tool adds a color there, or removes the color of the marker clicked.
let clicked = w.clicked.filter(|_| on_wheel && matches!(tool.as_str(), "add" | "remove"));
if let Some((hit, [h, s])) = clicked {
if tool == "add" {
let c = added_color(base.and_then(|b| to_color(&rows[b])), h, s, display == "segmented");
let i = add_color(rows, &c);
d.fields.insert("__sel".into(), json!([i]));
d.fields.remove(COMPS);
changed = true;
} else if let Some(b) = hit.and_then(|k| remove_color(rows, active[k], base, keeps_rows(d))) {
removed(d, b);
changed = true;
}
}
// Prominent Colors: the art's new colors, each as wide as its share of the art.
if art {
prominent_bar(ui, d, rows);
}
if let Some(k) = w.pressed {
// A tool's click selects no marker: Add Color selects the new row, and Remove Color keeps the
// base color.
if let Some(k) = w.pressed.filter(|_| clicked.is_none()) {
d.fields.insert("__sel".into(), json!([active[k]]));
}
// A drag (of a marker or the brightness slider) moves the rows as they were when it started:
// a new colour read back from its model (CMYK through the colour profile) isn't exactly the
// colour written, so building on last frame's rows drifted the linked colours (#1733).
if let Some((k, set)) = w.moved {
if let Some((k, set)) = w.moved.filter(|_| clicked.is_none()) {
let start = match d.fields.get(DRAG).and_then(Value::as_array) {
Some(s) if s.len() == rows.len() => s.clone(),
_ => rows.to_vec(),
@@ -1519,6 +1629,9 @@ fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value
if !art {
ui.add_space(SLIDERS_GAP);
}
// A color added or removed above changed the rows, so the sliders and chips read them afresh.
let active = active_rows(rows);
let base = selection(d).into_iter().find(|i| active.contains(i)).or(active.first().copied());
if d.str("sliderMode") == GLOBAL {
let sample = base.and_then(|b| to_color(&rows[b])).unwrap_or(Color::rgb(0.8, 0.45, 0.25));
global_sliders(ui, d, sample);
@@ -1549,11 +1662,12 @@ fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value
/// The Edit tab's color bars: a solid bar per row of `active` with its new color, in row order, the
/// base row's framed, scrolling past the wheel's height. A click on a bar selects its row (the
/// sliders under it edit that row's new color); a drag moves the bar's row to where the line under
/// the pointer shows, keeping every new color. Returns true when the rows moved.
fn color_bars(ui: &mut Ui, d: &mut Dialog, rows: &mut [Value], active: &[usize], base: Option<usize>) -> bool {
/// the pointer shows, keeping every new color. A bar's right-click menu has Remove Color (not for the
/// base row's). Returns true when the rows moved or a color was removed.
fn color_bars(ui: &mut Ui, d: &mut Dialog, rows: &mut Vec<Value>, active: &[usize], base: Option<usize>) -> bool {
let t = Tokens::get(ui.ctx());
let mut rects: Vec<Rect> = Vec::with_capacity(active.len());
let (mut dragging, mut released, mut dropped) = (None, None, None);
let (mut dragging, mut released, mut dropped, mut remove) = (None, None, None, None);
// The area is given its full height first: in the row beside the display buttons a scroll area
// alone is only as tall as the room the row has.
let area = vec2(ui.available_width(), BARS_H);
@@ -1584,7 +1698,12 @@ fn color_bars(ui: &mut Ui, d: &mut Dialog, rows: &mut [Value], active: &[usize],
released = Some(n);
}
rects.push(r);
resp.on_hover_text(rows[i]["to"].as_str().unwrap_or_default());
let resp = resp.on_hover_text(rows[i]["to"].as_str().unwrap_or_default());
resp.context_menu(|ui| {
if widgets::menu_item_name(ui, tl!("Remove Color"), Some(i) != base, false) {
remove = Some(i);
}
});
}
// The place a dragged bar goes: before the first bar whose middle is below the pointer.
let at = ui.input(|i| i.pointer.latest_pos()).map(|p| rects.iter().filter(|r| r.center().y < p.y).count());
@@ -1599,6 +1718,10 @@ fn color_bars(ui: &mut Ui, d: &mut Dialog, rows: &mut [Value], active: &[usize],
dropped = released.zip(at);
});
});
if let Some(b) = remove.and_then(|i| remove_color(rows, i, base, keeps_rows(d))) {
removed(d, b);
return true;
}
let Some(moved) = dropped.and_then(|(n, to)| move_bar(rows, active, n, to)) else { return false };
d.fields.insert("__sel".into(), json!([moved]));
// The slider values held are those of a row index that may now hold another row.
@@ -1689,6 +1812,58 @@ mod tests {
assert!(c.to_hsb()[1] < 1e-3, "{c:?}");
}
/// Remove Color: a row with no current colors goes, with art or a group a row's current colors
/// stay with no new color, without either the row goes, and the base row stays; the base row's
/// index follows.
#[test]
fn remove_color_drops_added_rows_and_empties_rows_of_art() {
let mut r = rows();
assert_eq!(add_color(&mut r, &Color::rgb(0.0, 1.0, 1.0)), 3);
assert_eq!(r[3], json!({"from": [], "to": "rgb 0 255 255", "added": true}));
assert_eq!(remove_color(&mut r, 0, Some(0), true), None, "the base row stays");
r[1]["tint"] = json!(50);
assert_eq!(remove_color(&mut r, 1, Some(2), true), Some(2));
assert_eq!(r[1], json!({"from": ["rgb 0 0 255", "rgb 0 0 128"], "to": null}), "the art's colors stay, without a tint");
assert_eq!(remove_color(&mut r, 1, Some(2), true), None, "no new color left to remove");
assert_eq!(remove_color(&mut r, 3, Some(2), true), Some(2));
assert_eq!(r.len(), 3, "the added row goes");
assert_eq!(remove_color(&mut r, 9, Some(2), true), None);
let mut r = rows();
assert_eq!(remove_color(&mut r, 0, Some(2), false), Some(1), "without art the row goes, and the base row moves up");
assert_eq!(r.len(), 2);
assert_eq!(r[1]["from"], json!(["rgb 0 255 0"]));
}
/// An added color is the hue and saturation clicked at the base color's brightness (full without
/// one), the patch's color on the segmented wheel, in the base color's model.
#[test]
fn an_added_color_takes_the_base_colors_brightness_and_model() {
let near = |a: [f32; 3], b: [f32; 3]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-3);
let base = Color::from_hsb(10.0, 0.8, 0.6);
assert!(near(added_color(Some(base), 120.0, 0.5, false).to_hsb(), [120.0, 0.5, 0.6]));
assert!(near(added_color(None, 200.0, 0.25, false).to_hsb(), [200.0, 0.25, 1.0]));
assert!(near(added_color(None, 7.0, 0.95, true).to_hsb(), [0.0, 0.9, 1.0]), "the patch's color");
let cmyk = color_value(&json!("cmyk 0 100 100 0")).unwrap();
assert!(matches!(added_color(Some(cmyk), 120.0, 0.5, false), Color::Cmyk { .. }));
}
/// With a color group and art, a row without a new color removes its swatch in its place, the
/// group's colors no row of art took stay in theirs, and a color added on the Edit tab adds its
/// new color after them; a row made with New Row, which holds no current colors, adds none.
#[test]
fn apply_params_give_the_group_added_colors_and_keep_its_other_colors() {
let mut d = Dialog::new(KIND, json!({"group": "G", "groupName": "G", "__art": true, "__assign": ["rgb 1 1 1", "rgb 2 2 2", "rgb 3 3 3"]}));
let mut rs = vec![json!({"from": ["rgb 255 0 0"], "to": "rgb 1 1 1"}), json!({"from": ["rgb 0 0 255"], "to": null})];
new_row(&mut rs, &[]);
add_color(&mut rs, &Color::rgb(9.0 / 255.0, 9.0 / 255.0, 9.0 / 255.0));
d.fields.insert("rows".into(), json!(rs));
assert_eq!(apply_params(&d)["groupColors"], json!(["rgb 1 1 1", null, "rgb 3 3 3", "rgb 9 9 9"]));
// An added color whose row is excluded joins no group.
rs[3]["exclude"] = json!(true);
d.fields.insert("rows".into(), json!(rs));
assert_eq!(apply_params(&d)["groupColors"], json!(["rgb 1 1 1", null, "rgb 3 3 3"]));
}
#[test]
fn merge_and_separate_rows() {
let mut r = rows();
@@ -1816,6 +1991,17 @@ mod tests {
assert_eq!(edit_slider_row(&sel(json!([0])), &r, &[], None), None, "no row to edit");
}
/// A color added on the Edit tab holds no current colors but is not an empty row: the Edit tab
/// shows it and a color group takes it.
#[test]
fn an_added_color_is_not_an_empty_row() {
let added = json!({"from": [], "to": "rgb 0 255 255", "added": true});
assert!(!empty(&added) && in_group(&added));
let mut r = rows();
r.push(added);
assert_eq!(active_rows(&r), [0, 1, 2, 3]);
}
/// A rule or a wheel move that gives a row a new color drops the row's tint; a row whose
/// color stays keeps it.
#[test]
+3
View File
@@ -1504,6 +1504,9 @@ font-technology Variable Променливи
Show smooth color wheel Показване на плавно цветово колело
Show segmented color wheel Показване на сегментирано цветово колело
Show color bars Показване на цветни ленти
Add Color Tool Инструмент „Добавяне на цвят“
Remove Color Tool Инструмент „Премахване на цвят“
Remove Color Премахване на цвят
Find the selected colors in the artwork Намиране на избраните цветове в илюстрацията
Harmony Sets Набори от хармонии
Height Височина
Can't render this file because it is too large.
+3
View File
@@ -2927,6 +2927,9 @@ digits Malayalam Malajalam
Show smooth color wheel Prikaži glatki kotač boja
Show segmented color wheel Prikaži segmentirani kotač boja
Show color bars Prikaži trake boja
Add Color Tool Alat za dodavanje boje
Remove Color Tool Alat za uklanjanje boje
Remove Color Ukloni boju
Find the selected colors in the artwork Pronađi odabrane boje u crtežu
Harmony Rules Pravila harmonije
Keep this row's colors (exclude) Zadrži boje ovog reda (isključi)
Can't render this file because it contains an unexpected character in line 2 and column 73.
+3
View File
@@ -2044,6 +2044,9 @@ digits Malayalam Malaiàlam
Show smooth color wheel Mostra la roda de color contínua
Show segmented color wheel Mostra la roda de color segmentada
Show color bars Mostra les barres de color
Add Color Tool Eina Afegeix color
Remove Color Tool Eina Elimina color
Remove Color Elimina el color
Find the selected colors in the artwork Troba els colors seleccionats a l’obra
Harmony Sets Conjunts d’harmonia
HDTV 1080p HDTV 1080p
Can't render this file because it contains an unexpected character in line 2 and column 73.
+3
View File
@@ -3012,6 +3012,9 @@ digits Malayalam Malajálamské
Show smooth color wheel Zobrazit plynulé barevné kolo
Show segmented color wheel Zobrazit segmentované barevné kolo
Show color bars Zobrazit barevné pruhy
Add Color Tool Nástroj Přidat barvu
Remove Color Tool Nástroj Odstranit barvu
Remove Color Odstranit barvu
Find the selected colors in the artwork Najít vybrané barvy v kresbě
Harmony Rules Pravidla harmonie
Keep this row's colors (exclude) Ponechat barvy tohoto řádku (vyloučit)
Can't render this file because it is too large.
+3
View File
@@ -5460,6 +5460,9 @@ digits Malayalam Malayalam
Show smooth color wheel Vis glat farvehjul
Show segmented color wheel Vis segmenteret farvehjul
Show color bars Vis farvebjælker
Add Color Tool Værktøjet Tilføj farve
Remove Color Tool Værktøjet Fjern farve
Remove Color Fjern farve
Find the selected colors in the artwork Find de valgte farver i grafikken
Harmony Rules Harmoniregler
Keep this row's colors (exclude) Behold farverne i denne række (ekskludér)
Can't render this file because it is too large.
+3
View File
@@ -1554,6 +1554,9 @@ file-filter Templates Vorlagen
Show smooth color wheel Stufenlosen Farbkreis anzeigen
Show segmented color wheel Segmentierten Farbkreis anzeigen
Show color bars Farbbalken anzeigen
Add Color Tool Farbe-hinzufügen-Werkzeug
Remove Color Tool Farbe-entfernen-Werkzeug
Remove Color Farbe entfernen
Find the selected colors in the artwork Ausgewählte Farben in der Grafik finden
Harmony Sets Harmoniesätze
Height Höhe
Can't render this file because it is too large.
+3
View File
@@ -1486,6 +1486,9 @@ font-technology Variable Μεταβλητές
Show smooth color wheel Εμφάνιση ομαλού χρωματικού τροχού
Show segmented color wheel Εμφάνιση τμηματοποιημένου χρωματικού τροχού
Show color bars Εμφάνιση χρωματικών ράβδων
Add Color Tool Εργαλείο προσθήκης χρώματος
Remove Color Tool Εργαλείο αφαίρεσης χρώματος
Remove Color Αφαίρεση χρώματος
Find the selected colors in the artwork Εύρεση των επιλεγμένων χρωμάτων στο σχέδιο
Harmony Sets Σύνολα χρωματικής αρμονίας
Height Ύψος
Can't render this file because it is too large.
+3
View File
@@ -1569,6 +1569,9 @@ font-technology Variable Variables
Show smooth color wheel Mostrar rueda de color continua
Show segmented color wheel Mostrar rueda de color segmentada
Show color bars Mostrar barras de color
Add Color Tool Herramienta Añadir color
Remove Color Tool Herramienta Eliminar color
Remove Color Eliminar color
Find the selected colors in the artwork Buscar los colores seleccionados en la ilustración
Harmony Sets Conjuntos de armonía
Height Altura
Can't render this file because it contains an unexpected character in line 2 and column 73.
+3
View File
@@ -2956,6 +2956,9 @@ digits Malayalam Malajalam
Show smooth color wheel Näytä liukuva väriympyrä
Show segmented color wheel Näytä segmentoitu väriympyrä
Show color bars Näytä väripalkit
Add Color Tool Lisää väri -työkalu
Remove Color Tool Poista väri -työkalu
Remove Color Poista väri
Find the selected colors in the artwork Etsi valitut värit kuvituksesta
Harmony Rules Harmoniasäännöt
Keep this row's colors (exclude) Säilytä tämän rivin värit (jätä pois)
Can't render this file because it contains an unexpected character in line 2 and column 73.
+3
View File
@@ -1558,6 +1558,9 @@ font-technology Variable Variables
Show smooth color wheel Afficher la roue chromatique continue
Show segmented color wheel Afficher la roue chromatique segmentée
Show color bars Afficher les barres de couleur
Add Color Tool Outil Ajouter une couleur
Remove Color Tool Outil Supprimer une couleur
Remove Color Supprimer la couleur
Find the selected colors in the artwork Rechercher les couleurs sélectionnées dans l’illustration
Harmony Rules: Règles d’harmonie :
Harmony Sets Ensembles d’harmonies
Can't render this file because it is too large.
+3
View File
@@ -3607,6 +3607,9 @@
Show all plates બધી પ્લેટ બતાવો
Show axis અક્ષ બતાવો
Show color bars રંગ બાર બતાવો
Add Color Tool રંગ ઉમેરો સાધન
Remove Color Tool રંગ દૂર કરો સાધન
Remove Color રંગ દૂર કરો
Find the selected colors in the artwork પસંદ કરેલા રંગો આર્ટવર્કમાં શોધો
Show handles when multiple anchors are selected બહુવિધ એન્કર પસંદ હોય ત્યારે હૅન્ડલ બતાવો
Show in Folder ફોલ્ડરમાં બતાવો
Can't render this file because it contains an unexpected character in line 72 and column 5.
+3
View File
@@ -4687,6 +4687,9 @@ antiAlias Sharp शार्प
Show Center Mark शो सेंटर मार्क
Show Code कोड दिखाएं
Show color bars रंग सलाखों दिखाएँ
Add Color Tool रंग जोड़ें टूल
Remove Color Tool रंग हटाएँ टूल
Remove Color रंग हटाएँ
Find the selected colors in the artwork चयनित रंगों को आर्टवर्क में खोजें
Show Color Groups रंग समूह दिखाएँ
Show Color Swatches रंग स्वॉचेस दिखाएँ
Can't render this file because it is too large.
+3
View File
@@ -1972,6 +1972,9 @@ file-filter Templates Sablonok
Show smooth color wheel Folytonos színkör megjelenítése
Show segmented color wheel Szegmentált színkör megjelenítése
Show color bars Színsávok megjelenítése
Add Color Tool Szín hozzáadása eszköz
Remove Color Tool Szín eltávolítása eszköz
Remove Color Szín eltávolítása
Find the selected colors in the artwork A kijelölt színek keresése a grafikában
Harmony Sets Harmóniakészletek
HDTV 1080p HDTV 1080p
Can't render this file because it is too large.
+3
View File
@@ -2737,6 +2737,9 @@ digits Malayalam Malayalam
Show smooth color wheel Tampilkan roda warna halus
Show segmented color wheel Tampilkan roda warna bersegmen
Show color bars Tampilkan bilah warna
Add Color Tool Alat Tambah Warna
Remove Color Tool Alat Hapus Warna
Remove Color Hapus Warna
Find the selected colors in the artwork Temukan warna yang dipilih di karya seni
Harmony Rules Aturan harmoni
Keep this row's colors (exclude) Pertahankan warna baris ini (kecualikan)
Can't render this file because it contains an unexpected character in line 2490 and column 5.
+3
View File
@@ -1588,6 +1588,9 @@ file-filter Templates Modelli
Show smooth color wheel Mostra ruota dei colori continua
Show segmented color wheel Mostra ruota dei colori segmentata
Show color bars Mostra barre di colore
Add Color Tool Strumento Aggiungi colore
Remove Color Tool Strumento Rimuovi colore
Remove Color Rimuovi colore
Find the selected colors in the artwork Trova i colori selezionati nella grafica
Harmony Sets Gruppi di armonia
Height Altezza
Can't render this file because it is too large.
+3
View File
@@ -1959,6 +1959,9 @@ antiAlias Sharp シャープ
Show smooth color wheel 滑らかなカラーホイールを表示
Show segmented color wheel 分割カラーホイールを表示
Show color bars カラーバーを表示
Add Color Tool カラー追加ツール
Remove Color Tool カラー削除ツール
Remove Color カラーを削除
Find the selected colors in the artwork 選択したカラーをアートワーク内で検索
Height 高さ
Height: 高さ:
Can't render this file because it is too large.
+3
View File
@@ -4788,6 +4788,9 @@ digits Malayalam მალაიალამური
Show smooth color wheel გლუვი ფერთა წრის ჩვენება
Show segmented color wheel სეგმენტირებული ფერთა წრის ჩვენება
Show color bars ფერთა ზოლების ჩვენება
Add Color Tool ფერის დამატების ხელსაწყო
Remove Color Tool ფერის წაშლის ხელსაწყო
Remove Color ფერის წაშლა
Find the selected colors in the artwork არჩეული ფერების პოვნა ნახატში
Keep this row's colors (exclude) ამ სტრიქონის ფერების შენარჩუნება (გამორიცხვა)
Limit to Library: ბიბლიოთეკით შეზღუდვა:
Can't render this file because it is too large.
+3
View File
@@ -1949,6 +1949,9 @@ antiAlias Sharp 날카롭게
Show smooth color wheel 부드러운 색상환 표시
Show segmented color wheel 분할 색상환 표시
Show color bars 색상 막대 표시
Add Color Tool 색상 추가 도구
Remove Color Tool 색상 제거 도구
Remove Color 색상 제거
Find the selected colors in the artwork 선택한 색상을 아트웍에서 찾기
Height 높이
Height: 높이:
Can't render this file because it is too large.
+3
View File
@@ -3354,6 +3354,9 @@ digits Malayalam Malayalam
Show smooth color wheel Vloeiend kleurenwiel tonen
Show segmented color wheel Gesegmenteerd kleurenwiel tonen
Show color bars Kleurbalken tonen
Add Color Tool Gereedschap Kleur toevoegen
Remove Color Tool Gereedschap Kleur verwijderen
Remove Color Kleur verwijderen
Find the selected colors in the artwork De geselecteerde kleuren zoeken in de artwork
Harmony Rules Harmonieregels
Keep this row's colors (exclude) De kleuren van deze rij behouden (uitsluiten)
Can't render this file because it is too large.
+3
View File
@@ -2922,6 +2922,9 @@ digits Malayalam Malajalam
Show smooth color wheel Pokaż płynne koło kolorów
Show segmented color wheel Pokaż segmentowe koło kolorów
Show color bars Pokaż paski kolorów
Add Color Tool Narzędzie Dodaj kolor
Remove Color Tool Narzędzie Usuń kolor
Remove Color Usuń kolor
Find the selected colors in the artwork Znajdź zaznaczone kolory w kompozycji
Keep this row's colors (exclude) Zachowaj kolory tego wiersza (wyklucz)
Limit to Library: Ogranicz do biblioteki:
Can't render this file because it is too large.
+3
View File
@@ -1354,6 +1354,9 @@ antiAlias Sharp Nítido
Show smooth color wheel Mostrar roda de cores contínua
Show segmented color wheel Mostrar roda de cores segmentada
Show color bars Mostrar barras de cores
Add Color Tool Ferramenta Adicionar cor
Remove Color Tool Ferramenta Remover cor
Remove Color Remover cor
Find the selected colors in the artwork Localizar as cores selecionadas na arte
Harmony Sets Conjuntos de Harmonia
Height Altura
Can't render this file because it is too large.
+3
View File
@@ -1579,6 +1579,9 @@ file-filter Templates Шаблоны
Show smooth color wheel Показать плавный цветовой круг
Show segmented color wheel Показать сегментированный цветовой круг
Show color bars Показать цветовые полосы
Add Color Tool Инструмент «Добавить цвет»
Remove Color Tool Инструмент «Удалить цвет»
Remove Color Удалить цвет
Find the selected colors in the artwork Найти выбранные цвета в рисунке
Harmony Sets Наборы гармонии
Height Высота
Can't render this file because it is too large.
+3
View File
@@ -1522,6 +1522,9 @@ font-technology Variable Variabla
Show smooth color wheel Visa steglöst färghjul
Show segmented color wheel Visa segmenterat färghjul
Show color bars Visa färgstaplar
Add Color Tool Verktyget Lägg till färg
Remove Color Tool Verktyget Ta bort färg
Remove Color Ta bort färg
Find the selected colors in the artwork Hitta de markerade färgerna i teckningen
Harmony Sets Harmoniuppsättningar
Height Höjd
Can't render this file because it is too large.
+3
View File
@@ -1479,6 +1479,9 @@ font-technology Variable Değişken
Show smooth color wheel Kesintisiz renk tekerleğini göster
Show segmented color wheel Bölümlü renk tekerleğini göster
Show color bars Renk çubuklarını göster
Add Color Tool Renk Ekle aracı
Remove Color Tool Renk Kaldır aracı
Remove Color Rengi kaldır
Find the selected colors in the artwork Seçili renkleri resimde bul
Harmony Sets Armoni Setleri
Height Yükseklik
Can't render this file because it is too large.
+3
View File
@@ -1582,6 +1582,9 @@ file-filter Templates Шаблони
Show smooth color wheel Показати плавне колірне коло
Show segmented color wheel Показати сегментоване колірне коло
Show color bars Показати колірні смуги
Add Color Tool Інструмент «Додати колір»
Remove Color Tool Інструмент «Вилучити колір»
Remove Color Вилучити колір
Find the selected colors in the artwork Знайти вибрані кольори в малюнку
Harmony Sets Набори гармонії
Height Висота
Can't render this file because it is too large.
+3
View File
@@ -1819,6 +1819,9 @@ file-filter Templates Mẫu
Show smooth color wheel Hiện bánh xe màu liền mạch
Show segmented color wheel Hiện bánh xe màu phân đoạn
Show color bars Hiện các thanh màu
Add Color Tool Công cụ Thêm màu
Remove Color Tool Công cụ Xóa màu
Remove Color Xóa màu
Find the selected colors in the artwork Tìm các màu đã chọn trong tác phẩm
Harmony Sets Bộ hài hòa màu
Height Chiều cao
Can't render this file because it contains an unexpected character in line 205 and column 5.
+3
View File
@@ -1516,6 +1516,9 @@ file-filter Templates 模板
Show smooth color wheel 显示平滑色轮
Show segmented color wheel 显示分段色轮
Show color bars 显示颜色条
Add Color Tool 添加颜色工具
Remove Color Tool 删除颜色工具
Remove Color 删除颜色
Find the selected colors in the artwork 在图稿中查找所选颜色
Harmony Sets 色彩调和组
Height 高度
Can't render this file because it is too large.
+3
View File
@@ -1553,6 +1553,9 @@ file-filter Templates 範本
Show smooth color wheel 顯示平滑色輪
Show segmented color wheel 顯示分段色輪
Show color bars 顯示顏色條
Add Color Tool 新增顏色工具
Remove Color Tool 移除顏色工具
Remove Color 移除顏色
Find the selected colors in the artwork 在圖稿中尋找所選顏色
Harmony Sets 色彩調和組
Height 高度
Can't render this file because it is too large.
+168 -1
View File
@@ -1,7 +1,7 @@
//! Recolor Artwork (M3.78) and Edit or Apply Color Group (M3.79), drawn headlessly.
use egui::{Event, Modifiers, PointerButton, Pos2, Rect, vec2};
use egui_kittest::kittest::Queryable;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::{Value, json};
use vectorcraft_color::Color;
use vectorcraft_color::recolor::ColorKey;
@@ -1172,3 +1172,170 @@ fn color_bars_scroll_and_show_when_nothing_is_recolored() {
assert!(h.query_by_role_and_label(egui::accesskit::Role::Button, "Color 1").is_none());
let _ = h.get_by_label("No colors to recolor (preserved colors are left out).");
}
/// Where the Edit tab's wheel draws a marker for hue `hue` and saturation `s`.
fn wheel_at(h: &egui_kittest::Harness<'_, VectorcraftApp>, hue: f32, s: f32) -> Pos2 {
let c = widget_of_size(h, vec2(220.0, 220.0)).center();
c + vec2(hue.to_radians().cos(), -hue.to_radians().sin()) * 100.0 * s
}
/// Clicks the Edit tab's button named `name` and lets the dialog settle.
fn click_button(h: &mut egui_kittest::Harness<'_, VectorcraftApp>, name: &str) {
h.get_by_role_and_label(egui::accesskit::Role::Button, name).click();
h.run_steps(3);
}
/// The Add Color tool: a click on the smooth wheel adds the hue and saturation under it, at the
/// base color's brightness, as a row with no current colors that becomes the selected row; the art
/// keeps its colors, and the Assign tab shows the row without current colors. A second click on the
/// button turns the tool off, and a click on the wheel then adds nothing.
#[test]
fn the_add_color_tool_adds_a_row_with_no_current_colors() {
let mut h = edit_harness(&["rgb 200 100 100", "rgb 100 200 200"]);
set(h.state_mut(), "__sel", json!([0]));
h.run_steps(4);
let (fills_before, v) = (fills(h.state()), new_hsb(h.state())[0][2]);
click_button(&mut h, "Add Color Tool");
assert_eq!(field(h.state(), "wheelTool"), json!("add"));
let at = wheel_at(&h, 120.0, 0.5);
h.input_mut().events.extend(press(at, 1));
h.run_steps(3);
let rows = field(h.state(), "rows");
assert_eq!(rows.as_array().unwrap().len(), 3, "a new row: {rows}");
assert_eq!(rows[2]["from"], json!([]), "with no current colors");
assert_eq!(rows[2]["added"], json!(true), "marked as an added color");
let [hue, s, b] = new_hsb(h.state())[2];
assert!((hue - 120.0).abs() < 1.0 && (s - 0.5).abs() < 0.01 && (b - v).abs() < 0.01, "{:?}", [hue, s, b]);
assert_eq!(field(h.state(), "__sel"), json!([2]), "the new color is selected");
assert_eq!(fills(h.state()), fills_before, "a color with no current colors recolors no art");
// A second click adds another color; the tool stays on.
let next = wheel_at(&h, 240.0, 0.75);
h.input_mut().events.extend(press(next, 1));
h.run_steps(3);
assert_eq!(field(h.state(), "rows").as_array().unwrap().len(), 4);
click_button(&mut h, "Add Color Tool");
assert_eq!(field(h.state(), "wheelTool"), Value::Null, "a second click turns the tool off");
h.input_mut().events.extend(press(at, 1));
h.run_steps(3);
assert_eq!(field(h.state(), "rows").as_array().unwrap().len(), 4, "without the tool a click adds nothing");
assert_eq!(field(h.state(), "__sel"), json!([2]), "it selects the marker clicked");
set(h.state_mut(), "tab", json!("assign"));
h.run_steps(3);
let _ = h.get_by_label("Current Colors (2)");
assert!(h.query_by_label("Color 4").is_some(), "the Assign tab has a row for each added color");
let app = h.state_mut();
let undo = app.session.doc().unwrap().history.undo.len();
dialogs::confirm(app).unwrap();
assert_eq!(fills(app), fills_before, "OK leaves the art's colors");
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo, "and records no undo step");
}
/// On the segmented wheel the Add Color tool adds the patch's color. Opened on a color group without
/// art, OK adds the added color to the group, as one undo step.
#[test]
fn an_added_color_joins_the_color_group() {
let app = app();
let before = group_keys(&app, "Brights");
let mut h = assign_harness(app, json!({"group": "Brights"}));
set(h.state_mut(), "tab", json!("edit"));
h.run_steps(4);
show_display(&mut h, "Show segmented color wheel");
let v = new_hsb(h.state())[0][2];
click_button(&mut h, "Add Color Tool");
let patch = wheel_at(&h, 187.0, 0.95);
h.input_mut().events.extend(press(patch, 1));
h.run_steps(3);
let added = field(h.state(), "rows").as_array().unwrap().last().unwrap()["to"].clone();
let [hue, s, b] = vectorcraft_engine::cmd::color_value(&added).unwrap().to_hsb();
assert!((hue - 180.0).abs() < 1.0 && (s - 0.9).abs() < 0.01 && (b - v).abs() < 0.01, "the patch's color: {:?}", [hue, s, b]);
let app = h.state_mut();
let undo = app.session.doc().unwrap().history.undo.len();
dialogs::confirm(app).unwrap();
let mut want = before.clone();
want.push(added);
assert_eq!(group_keys(app, "Brights"), want);
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
}
/// The Remove Color tool: a click on the base color's marker removes nothing; a click on another
/// marker leaves its row of art's colors with no new color, so OK leaves that art's colors as they
/// were while the other rows recolor theirs. The tools are off for the color bars.
#[test]
fn the_remove_color_tool_removes_a_marker_but_not_the_base_colors() {
let mut h = edit_harness(&["rgb 200 100 100", "rgb 100 200 200", "rgb 20 160 20"]);
let fills_before = fills(h.state());
let mut rows = field(h.state(), "rows");
let tos = ["rgb 255 0 0", "rgb 0 255 0", "rgb 0 0 255"];
for (r, to) in rows.as_array_mut().unwrap().iter_mut().zip(tos) {
r["to"] = json!(to);
}
set(h.state_mut(), "rows", rows.clone());
set(h.state_mut(), "linked", json!(false));
set(h.state_mut(), "__sel", json!([0]));
h.run_steps(4);
click_button(&mut h, "Remove Color Tool");
assert_eq!(field(h.state(), "wheelTool"), json!("remove"));
let (red, green) = (wheel_at(&h, 0.0, 1.0), wheel_at(&h, 120.0, 1.0));
h.input_mut().events.extend(press(red, 1));
h.run_steps(3);
assert_eq!(field(h.state(), "rows"), rows, "the base color stays");
h.input_mut().events.extend(press(green, 1));
h.run_steps(3);
let now = field(h.state(), "rows");
assert_eq!(now.as_array().unwrap().len(), 3, "the row of art's colors stays");
assert_eq!((&now[0], &now[1]["to"], &now[2]), (&rows[0], &Value::Null, &rows[2]), "with no new color: {now}");
assert_eq!(field(h.state(), "__sel"), json!([0]), "the base color stays selected");
show_display(&mut h, "Show color bars");
let tool = h.get_by_role_and_label(egui::accesskit::Role::Button, "Remove Color Tool");
assert!(tool.accesskit_node().is_disabled(), "the tools are for the wheels");
let kept = rows[1]["from"][0].clone();
let app = h.state_mut();
dialogs::confirm(app).unwrap();
let after = fills(app);
for (b, a) in fills_before.iter().zip(&after) {
let was = json!(ColorKey::of(&b.unwrap()).to_string());
if was == kept {
assert_eq!(a, b, "the art of the removed color keeps it");
} else {
assert_ne!(a, b, "the other art takes its new color");
}
}
}
/// Right-clicks the color bar named `name`.
fn right_click_bar(h: &mut egui_kittest::Harness<'_, VectorcraftApp>, name: &str) {
let at = h.get_by_role_and_label(egui::accesskit::Role::Button, name).rect().center();
h.event(Event::PointerMoved(at));
h.event(Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE });
h.event(Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE });
h.run_steps(2);
}
/// A color bar's right-click menu has Remove Color: off for the base color's bar; on an added
/// color's bar it removes the row, and on a bar of art's colors it leaves the row with no new color
/// and no bar.
#[test]
fn a_color_bars_menu_removes_its_color() {
let mut h = edit_harness(&["#ff0000", "#0000ff", "#00ff00"]);
let mut rows = field(h.state(), "rows");
rows.as_array_mut().unwrap().push(json!({"from": [], "to": "rgb 10 20 30", "added": true}));
set(h.state_mut(), "rows", rows.clone());
set(h.state_mut(), "__sel", json!([0]));
h.run_steps(4);
show_display(&mut h, "Show color bars");
right_click_bar(&mut h, "Color 1");
assert!(h.get_by_label(" Remove Color").accesskit_node().is_disabled(), "the base color can't be removed");
h.key_press(egui::Key::Escape);
h.run_steps(2);
right_click_bar(&mut h, "Color 4");
h.get_by_label(" Remove Color").click();
h.run_steps(3);
assert_eq!(field(h.state(), "rows").as_array().unwrap()[..], rows.as_array().unwrap()[..3], "the added row goes");
right_click_bar(&mut h, "Color 2");
h.get_by_label(" Remove Color").click();
h.run_steps(3);
let now = field(h.state(), "rows");
assert_eq!((&now[1]["from"], &now[1]["to"]), (&rows[1]["from"], &Value::Null), "{now}");
assert!(h.query_by_role_and_label(egui::accesskit::Role::Button, "Color 2").is_none(), "its bar goes");
assert_eq!(field(h.state(), "__sel"), json!([0]));
}
+9
View File
@@ -923,6 +923,9 @@ pub struct WheelResponse {
/// A colour moved by dragging its marker (a new hue and saturation) or, the selected colour,
/// the brightness slider (a new brightness): `[h°, s, v]`, `None` where the control kept it.
pub moved: Option<(usize, [Option<f32>; 3])>,
/// A click on the wheel: the color whose marker is within reach of it (if any), and the hue
/// (degrees) and saturation under the pointer (1 for a marker past the wheel's edge).
pub clicked: Option<(Option<usize>, [f32; 2])>,
}
/// The harmony wheel of Recolor Artwork's Edit tab and the Color Themes panel: a hue and saturation
@@ -971,6 +974,12 @@ fn wheel(ui: &mut Ui, id: &str, size: f32, colors: &[Color], base: Option<usize>
let near = colors.iter().map(at).enumerate().map(|(i, m)| (i, m.distance(p))).filter(|x| x.1 <= 14.0).min_by(|a, b| a.1.total_cmp(&b.1));
out.pressed = near.map(|x| x.0);
ui.data_mut(|m| m.insert_temp(drag, out.pressed));
// A click inside the wheel, or on a marker, gives the hue and saturation under it.
let dv = p - c;
if resp.clicked() && (dv.length() <= r || out.pressed.is_some()) {
let h = (-dv.y).atan2(dv.x).to_degrees().rem_euclid(360.0);
out.clicked = Some((out.pressed, [h, (dv.length() / r).clamp(0.0, 1.0)]));
}
}
if resp.dragged()
&& let (Some(i), Some(p)) = (ui.data(|m| m.get_temp::<Option<usize>>(drag)).flatten(), resp.interact_pointer_pos())
+9 -2
View File
@@ -290,8 +290,15 @@ luminosity}`, percent from -100 to 100, 0 by default). The dialog sends a non-ze
colors; colors opened alone are saved as a group with the change. `display` sets how the Edit tab shows the new
colors: `smooth` (the smooth wheel, also when unset; each opening starts there), `segmented` (a wheel of solid patches,
24 hues by 5 saturations, whose markers move as freely) or `bars` (a solid bar per recolored color in row order; a click
selects its row for the sliders and a drag moves the row without changing a color). Setting
`colors`, a preserve flag or `limitTo` reduces the rows again (also on `ui.dialog.confirm`). The dialog previews
selects its row for the sliders and a drag moves the row without changing a color). `wheelTool` turns on a wheel tool
on either wheel: `add` (the Add Color tool) adds a click as a new color, the hue and saturation clicked at the base
color's brightness (the patch's color on the segmented wheel), in a new row with no current colors (`from: []`) and
`added: true` that becomes the selected row; `remove` (the Remove Color tool) removes the color of the marker clicked. A color bar's
right-click menu has Remove Color too. The base color can't be removed. A removed color's row is dropped, unless it
has current colors and art or a group is open: it then keeps them with `to: null`, that art keeps its colors, and the
group's swatch at that place is removed. A row with no current colors recolors no art; with a group, the new color of
one with `added: true` that is not excluded is added to the group after the group's other colors, and a row made with New Row adds none.
Setting `colors`, a preserve flag or `limitTo` reduces the rows again (also on `ui.dialog.confirm`). The dialog previews
`recolor.apply` on the canvas; confirm keeps it as one undo step (with a group, the group is rewritten in the same
step; with no art selected only the group changes). In the Swatches panel, double-clicking a colour group's folder,
or the options button while a group is selected, opens it.
+6 -3
View File
@@ -4665,8 +4665,10 @@ darker than the row's average become tints and shades) or `hueShift` (the most s
the others turn by the same hue). `limitTo` snaps new colours to a swatch library's nearest colour;
`recolor.randomize {map, order?, saturationBrightness?, seed?}` shuffles or varies new colours; a row with
`exclude: true` keeps its colours. A row's `from` may be an empty list: the row recolors nothing, adds no library swatch with
`limitTo` and gives `group` no color, and `recolor.randomize` and `recolor.weigh` keep it; `recolor.randomize` leaves its
new color as it is and shuffles only the rows that hold current colors. A row without `from`, or with
`limitTo` and gives `group` no color, unless it has `added: true` (a color the Edit tab's Add Color tool added):
without `groupColors`, its new color then joins `group` after the new colors of the rows with current colors.
`recolor.randomize` leaves a row without current colors as it is and shuffles only the rows that hold current colors.
`recolor.randomize` and `recolor.weigh` keep such a row, and `recolor.randomize` keeps its `added`. A row without `from`, or with
a current color that is not a color, is refused. With art selected, the Recolor Artwork dialog's New Row button (beside
Merge) adds such a row above the first selected row, or at the top, with that row's new color, and selects it; Shift-click a row below it and Merge to move that row's colors into it (Merge keeps the topmost selected row's new color). An
empty row does not count toward Colors. While it is empty, the dialog's Edit tab does not show it (its sliders edit
@@ -4676,7 +4678,8 @@ from colors alone leave its new color out. With `limitTo`, a row's `tint` (a per
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
step (art linked to its global swatches follows), and `recolor.apply` with `group` recolours the art and rewrites the
group together. Art linked to one of the group's global swatches stays linked when the swatch is rewritten with its
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. 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
+1
View File
@@ -1672,6 +1672,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **Document Color Mode for effects and graphs:** File › Document Color Mode and `document.open {colorMode}` convert the colors of effects (Drop Shadow, Inner Glow, Outer Glow and the other effects with a color, on objects, their fills and strokes and in graphic styles) and the series paints and label styles that a graph keeps, so a graph drawn again from new data keeps the converted colors; File › Document Color Mode also converts the fill and stroke that new art takes. Undo restores the original new-art fill and stroke and Redo applies the conversion again.
- **Recolor Artwork layout (#3416):** the Edit chip list uses the modal scroll helper and its actual remaining height; the tab's minimum-height space scrolls with the chips. `tests_recolor` covers 5/20/200/400 colors, window resizing, 100/125/150/200% UI scaling, scrolling to and editing the final chip, Preview, Cancel, Confirm and Undo, alongside the existing #1733 drag regressions. Scores and estimates unchanged.
- **Recolor Artwork Edit displays:** buttons beside the Edit tab's wheel show the colors on a smooth color wheel, a segmented color wheel or as color bars ([Edit colors using Recolor Artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/edit-colors-using-edit-colors-dialog.html)). The segmented wheel draws 24 hues by 5 saturations as solid patches, and its markers move freely as on the smooth wheel. The bars show one solid bar per recolored color in row order: a click selects a bar for the color sliders, and a drag moves its row without changing a color ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). The dialog opens on the smooth wheel; `display` (`smooth`, `segmented`, `bars`) is the dialog field. `tests_recolor` covers switching, the dialog height, segmented dragging and Brightness, and bar selection, editing, reordering, scrolling, Preview, Cancel and OK. Scores and estimates unchanged.
- **Recolor Artwork Add Color and Remove Color tools:** under the display buttons beside the Edit tab's wheel, the Add Color tool adds the color clicked on either wheel to the color group, and the Remove Color tool removes the color whose marker is clicked; a color bar's right-click menu has Remove Color, and the base color can't be removed ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html), [Edit swatch groups using the color wheel](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/edit-color-groups-using-the-color-wheel.html)). An added color is a new row with no current colors and `added: true`; unlike a row made with New Row, it adds its new color to a rewritten color group, after the group's other colors. VectorCraft's own rules: an added color takes the base color's brightness, and with art or a group a removed color's row stays with its current colors and no new color, so that art keeps its colors and the group's swatch at that place is removed. `wheelTool` (`add`, `remove`) is the dialog field. Tests: `the_add_color_tool_adds_a_row_with_no_current_colors`, `an_added_color_joins_the_color_group`, `the_remove_color_tool_removes_a_marker_but_not_the_base_colors` and `a_color_bars_menu_removes_its_color` in `crates/ui-egui/src/tests/recolor.rs`, `apply_params_give_the_group_added_colors_and_keep_its_other_colors` in `crates/ui-egui/src/dialogs/recolor.rs`, and `an_added_empty_row_gives_the_group_its_color_after_the_others` in `crates/engine/src/tests/recolor.rs`. Scores and estimates unchanged.
- **Recolor Artwork Find:** the Assign tab's Find button finds the colors of the selected rows in the art ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)): while it is on, their art shows as the preview shows it and the rest of the selected art shows dimmed, until a second click ([archived help, Recolor Artwork](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=149)). VectorCraft's own rules: a dimmed color is a 25% tint of its current color (or the nearest lighter tint when that one is a color a selected row lists), a color a selected row also lists is not dimmed, and Find records no undo step. `findColors` is the dialog field. Tests: `find_dims_the_colors_of_the_rows_not_selected` and `find_shows_the_selected_rows_art_and_dims_the_rest` in `crates/ui-egui/src/dialogs/recolor.rs`. Scores and estimates unchanged.
- **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`.
- **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.