Recolor Artwork: the Edit tab's Add Color and Remove Color tools add and remove colors

Two buttons under the display buttons beside the Edit tab's wheel turn on
the Add Color and Remove Color tools. With Add Color, a click on either
wheel adds a color in a new row with no current colors, at the base
color's brightness. With Remove Color, a click on a marker removes that
color; a color bar's right-click menu has Remove Color too. The base
color can't be removed. With art or a color group open, a removed
color's row keeps its current colors with no new color, so the art keeps
its colors and the group's swatch at that place is removed.

recolor.apply's groupColors accepts null, which removes the group's
swatch at that place; the swatches after it keep their colors and names,
and art linked to a removed global swatch keeps its color, unlinked.
This commit is contained in:
dotCooCoo committed 2026-11-14 22:12:58 -08:00
1 parent 0c1ac3bdc5
commit 42fab2ea2a
37 files changed
+529 -44

No files matched your search

+11 -8
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)], 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 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 (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)], 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 | null] (what `group` is rewritten with, a null removing the group's swatch at its place; default: the rows' new colours, in order, 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 (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
),
@@ -1647,17 +1647,19 @@ 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<_>>()?,
None => rows.iter().filter_map(Row::new_color).map(|c| mapped_adjust.apply(c)).collect(),
None => rows.iter().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();
@@ -1692,7 +1694,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();
+27 -15
View File
@@ -1226,43 +1226,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 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: &[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 colour.
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 });
}
@@ -1291,6 +1302,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}))
+31
View File
@@ -688,6 +688,37 @@ 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");
}
#[test]
fn recolor_of_everything_does_not_count_locked_art_whose_pattern_the_group_rewrite_recolors() {
let mut s = session();
+188 -17
View File
@@ -19,7 +19,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,14 +45,16 @@
//! 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}]; a row with no current colors, `from: []`, recolors no art and 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). Changing `colors`, a
//! preserve flag or `limitTo` reduces the rows again (and drops `weights`).
@@ -552,6 +560,11 @@ fn excluded(row: &Value) -> bool {
row["exclude"].as_bool().unwrap_or(false)
}
/// Whether `row` has no current colors (a color added on the Edit tab).
fn no_current(row: &Value) -> bool {
row["from"].as_array().is_none_or(Vec::is_empty)
}
/// The seed for the next Randomize: one past the last, held at `u64::MAX`.
fn next_seed(d: &Dialog) -> u64 {
(d.f64("__seed", 0.0) as u64).saturating_add(1)
@@ -562,13 +575,21 @@ 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.
/// colours: the new colours of the rows with current colours, each in its swatch's place (`null`
/// for a row whose new colour was removed, which removes its swatch), then (with art) the group's
/// colours no row took, then the colours 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| {
let rest =
d.fields.get("__assign").and_then(Value::as_array).filter(|_| d.bool("__art")).map_or(&[][..], |a| a.get(rs.len()..).unwrap_or_default());
let colors: Vec<&Value> = rs.iter().map(|r| &r["to"]).chain(rest).collect();
let (added, took): (Vec<&Value>, Vec<&Value>) = rs.iter().partition(|r| no_current(r));
let rest = d
.fields
.get("__assign")
.and_then(Value::as_array)
.filter(|_| d.bool("__art"))
.map_or(&[][..], |a| a.get(took.len()..).unwrap_or_default());
let added = added.into_iter().map(|r| &r["to"]).filter(|c| !c.is_null());
let colors: Vec<&Value> = took.iter().map(|r| &r["to"]).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})
@@ -790,15 +811,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)
@@ -1241,8 +1268,60 @@ 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, after the others. Returns its index.
fn add_color(rows: &mut Vec<Value>, c: &Color) -> usize {
rows.push(json!({"from": [], "to": key(c)}));
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;
@@ -1295,6 +1374,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.
@@ -1309,6 +1391,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),
@@ -1316,17 +1406,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(),
@@ -1346,6 +1452,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);
@@ -1376,11 +1485,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);
@@ -1411,7 +1521,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());
@@ -1426,6 +1541,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.
@@ -1516,6 +1635,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"}));
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 row with no current colors adds its
/// new color after them.
#[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"]}));
d.fields.insert(
"rows".into(),
json!([
{"from": ["rgb 255 0 0"], "to": "rgb 1 1 1"},
{"from": ["rgb 0 0 255"], "to": null},
{"from": [], "to": "rgb 9 9 9"},
]),
);
assert_eq!(apply_params(&d)["groupColors"], json!(["rgb 1 1 1", null, "rgb 3 3 3", "rgb 9 9 9"]));
}
#[test]
fn merge_and_separate_rows() {
let mut r = rows();
+3
View File
@@ -1446,6 +1446,9 @@ font-technology Variable Променливи
Show smooth color wheel Показване на плавно цветово колело
Show segmented color wheel Показване на сегментирано цветово колело
Show color bars Показване на цветни ленти
Add Color Tool Инструмент „Добавяне на цвят“
Remove Color Tool Инструмент „Премахване на цвят“
Remove Color Премахване на цвят
Harmony Sets Набори от хармонии
Height Височина
Height: Височина:
Can't render this file because it contains an unexpected character in line 2 and column 73.
+3
View File
@@ -2881,6 +2881,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
Harmony Rules Pravila harmonije
Keep this row's colors (exclude) Zadrži boje ovog reda (isključi)
Limit to Library: Ograniči na biblioteku:
Can't render this file because it contains an unexpected character in line 2 and column 73.
+3
View File
@@ -1977,6 +1977,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
Harmony Sets Conjunts d’harmonia
HDTV 1080p HDTV 1080p
HDTV 720p HDTV 720p
Can't render this file because it contains an unexpected character in line 2 and column 73.
+3
View File
@@ -2917,6 +2917,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
Harmony Rules Pravidla harmonie
Keep this row's colors (exclude) Ponechat barvy tohoto řádku (vyloučit)
Limit to Library: Omezit na knihovnu:
Can't render this file because it is too large.
+3
View File
@@ -3308,6 +3308,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
Harmony Rules Harmoniregler
Keep this row's colors (exclude) Behold farverne i denne række (ekskludér)
Limit to Library: Begræns til bibliotek:
Can't render this file because it contains an unexpected character in line 2 and column 73.
+3
View File
@@ -1491,6 +1491,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
Harmony Sets Harmoniesätze
Height Höhe
Height: Höhe:
Can't render this file because it is too large.
+3
View File
@@ -1421,6 +1421,9 @@ font-technology Variable Μεταβλητές
Show smooth color wheel Εμφάνιση ομαλού χρωματικού τροχού
Show segmented color wheel Εμφάνιση τμηματοποιημένου χρωματικού τροχού
Show color bars Εμφάνιση χρωματικών ράβδων
Add Color Tool Εργαλείο προσθήκης χρώματος
Remove Color Tool Εργαλείο αφαίρεσης χρώματος
Remove Color Αφαίρεση χρώματος
Harmony Sets Σύνολα χρωματικής αρμονίας
Height Ύψος
Height: Ύψος:
Can't render this file because it is too large.
+3
View File
@@ -1500,6 +1500,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
Harmony Sets Conjuntos de armonía
Height Altura
Height: Altura:
Can't render this file because it contains an unexpected character in line 2 and column 73.
+3
View File
@@ -2861,6 +2861,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
Harmony Rules Harmoniasäännöt
Keep this row's colors (exclude) Säilytä tämän rivin värit (jätä pois)
Limit to Library: Rajoita kirjastoon:
Can't render this file because it contains an unexpected character in line 2 and column 73.
+3
View File
@@ -1493,6 +1493,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
Harmony Rules: Règles d’harmonie :
Harmony Sets Ensembles d’harmonies
Height Hauteur
Can't render this file because it is too large.
+3
View File
@@ -3504,6 +3504,9 @@
Show all plates બધી પ્લેટ બતાવો
Show axis અક્ષ બતાવો
Show color bars રંગ બાર બતાવો
Add Color Tool રંગ ઉમેરો સાધન
Remove Color Tool રંગ દૂર કરો સાધન
Remove Color રંગ દૂર કરો
Show handles when multiple anchors are selected બહુવિધ એન્કર પસંદ હોય ત્યારે હૅન્ડલ બતાવો
Show in Folder ફોલ્ડરમાં બતાવો
Show its progress, see Cancel and write log lines તેની પ્રગતિ બતાવવી, રદ કરવાની વિનંતી જોવી અને લૉગ લાઇનો લખવી
Can't render this file because it contains an unexpected character in line 72 and column 5.
+3
View File
@@ -4590,6 +4590,9 @@ antiAlias Sharp शार्प
Show Center Mark शो सेंटर मार्क
Show Code कोड दिखाएं
Show color bars रंग सलाखों दिखाएँ
Add Color Tool रंग जोड़ें टूल
Remove Color Tool रंग हटाएँ टूल
Remove Color रंग हटाएँ
Show Color Groups रंग समूह दिखाएँ
Show Color Swatches रंग स्वॉचेस दिखाएँ
Show Corner Widget शो कॉर्नर विजेट
Can't render this file because it is too large.
+3
View File
@@ -1899,6 +1899,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
Harmony Sets Harmóniakészletek
HDTV 1080p HDTV 1080p
HDTV 720p HDTV 720p
Can't render this file because it is too large.
+3
View File
@@ -2699,6 +2699,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
Harmony Rules Aturan harmoni
Keep this row's colors (exclude) Pertahankan warna baris ini (kecualikan)
Limit to Library: Batasi ke pustaka:
Can't render this file because it contains an unexpected character in line 2454 and column 5.
+3
View File
@@ -1521,6 +1521,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
Harmony Sets Gruppi di armonia
Height Altezza
Height: Altezza:
Can't render this file because it is too large.
+3
View File
@@ -1925,6 +1925,9 @@ antiAlias Sharp シャープ
Show smooth color wheel 滑らかなカラーホイールを表示
Show segmented color wheel 分割カラーホイールを表示
Show color bars カラーバーを表示
Add Color Tool カラー追加ツール
Remove Color Tool カラー削除ツール
Remove Color カラーを削除
Height 高さ
Height: 高さ:
Help › Search Commands… ヘルプ › コマンドを検索…
Can't render this file because it is too large.
+3
View File
@@ -2616,6 +2616,9 @@ digits Malayalam მალაიალამური
Show smooth color wheel გლუვი ფერთა წრის ჩვენება
Show segmented color wheel სეგმენტირებული ფერთა წრის ჩვენება
Show color bars ფერთა ზოლების ჩვენება
Add Color Tool ფერის დამატების ხელსაწყო
Remove Color Tool ფერის წაშლის ხელსაწყო
Remove Color ფერის წაშლა
Keep this row's colors (exclude) ამ სტრიქონის ფერების შენარჩუნება (გამორიცხვა)
Limit to Library: ბიბლიოთეკით შეზღუდვა:
Link harmony colors ჰარმონიის ფერების დაკავშირება
Can't render this file because it is too large.
+3
View File
@@ -1915,6 +1915,9 @@ antiAlias Sharp 날카롭게
Show smooth color wheel 부드러운 색상환 표시
Show segmented color wheel 분할 색상환 표시
Show color bars 색상 막대 표시
Add Color Tool 색상 추가 도구
Remove Color Tool 색상 제거 도구
Remove Color 색상 제거
Height 높이
Height: 높이:
Help › Search Commands… 도움말 › 명령 검색…
Can't render this file because it is too large.
+3
View File
@@ -3217,6 +3217,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
Harmony Rules Harmonieregels
Keep this row's colors (exclude) De kleuren van deze rij behouden (uitsluiten)
Limit to Library: Beperken tot bibliotheek:
Can't render this file because it is too large.
+3
View File
@@ -2827,6 +2827,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
Keep this row's colors (exclude) Zachowaj kolory tego wiersza (wyklucz)
Limit to Library: Ogranicz do biblioteki:
Link harmony colors Połącz kolory harmonii
Can't render this file because it is too large.
+3
View File
@@ -1323,6 +1323,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
Harmony Sets Conjuntos de Harmonia
Height Altura
Height: Altura:
Can't render this file because it is too large.
+3
View File
@@ -1510,6 +1510,9 @@ file-filter Templates Шаблоны
Show smooth color wheel Показать плавный цветовой круг
Show segmented color wheel Показать сегментированный цветовой круг
Show color bars Показать цветовые полосы
Add Color Tool Инструмент «Добавить цвет»
Remove Color Tool Инструмент «Удалить цвет»
Remove Color Удалить цвет
Harmony Sets Наборы гармонии
Height Высота
Height: Высота:
Can't render this file because it is too large.
+3
View File
@@ -1459,6 +1459,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
Harmony Sets Harmoniuppsättningar
Height Höjd
Height: Höjd:
Can't render this file because it is too large.
+3
View File
@@ -1422,6 +1422,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
Harmony Sets Armoni Setleri
Height Yükseklik
Height: Yükseklik:
Can't render this file because it is too large.
+3
View File
@@ -1515,6 +1515,9 @@ file-filter Templates Шаблони
Show smooth color wheel Показати плавне колірне коло
Show segmented color wheel Показати сегментоване колірне коло
Show color bars Показати колірні смуги
Add Color Tool Інструмент «Додати колір»
Remove Color Tool Інструмент «Вилучити колір»
Remove Color Вилучити колір
Harmony Sets Набори гармонії
Height Висота
Height: Висота:
Can't render this file because it is too large.
+3
View File
@@ -1746,6 +1746,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
Harmony Sets Bộ hài hòa màu
Height Chiều cao
Height: Chiều cao:
Can't render this file because it contains an unexpected character in line 204 and column 5.
+3
View File
@@ -1449,6 +1449,9 @@ file-filter Templates 模板
Show smooth color wheel 显示平滑色轮
Show segmented color wheel 显示分段色轮
Show color bars 显示颜色条
Add Color Tool 添加颜色工具
Remove Color Tool 删除颜色工具
Remove Color 删除颜色
Harmony Sets 色彩调和组
Height 高度
Height: 高度:
Can't render this file because it is too large.
+3
View File
@@ -1486,6 +1486,9 @@ file-filter Templates 範本
Show smooth color wheel 顯示平滑色輪
Show segmented color wheel 顯示分段色輪
Show color bars 顯示顏色條
Add Color Tool 新增顏色工具
Remove Color Tool 移除顏色工具
Remove Color 移除顏色
Harmony Sets 色彩調和組
Height 高度
Height: 高度:
Can't render this file because it is too large.
+167 -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,169 @@ 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");
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 click on the new marker 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"}));
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 colour 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: []`) 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, its new color is
added to the group after the group's other colors.
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.
+2 -1
View File
@@ -4338,7 +4338,8 @@ the others turn by the same hue). `limitTo` snaps new colours to a swatch librar
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
@@ -1591,6 +1591,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. 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`. Scores and estimates unchanged.
- **Edit Colors parameters:** `edit.colors.saturate` needs a number `intensity`, the value from -100% to 100% that Saturate takes ([Adjusting colors](https://web.archive.org/web/20230128232631/https://helpx.adobe.com/illustrator/using/adjusting-colors.html)), and answers "missing number `intensity`" without one; a number outside the range counts as its nearest end. A value that is not a number, such as `"40"`, is refused with `` `intensity` must be a number, not "40" ``, as in every command that needs a number (`tests::params::a_malformed_required_number_is_not_reported_as_missing`). `edit.colors.adjustBalance` refuses a channel and `color.harmony` refuses `steps` or `amount` that is not a number; both read `null` as a value left out. `tests::editcolors` and `tests::colorguide` cover them.
- **Convert to Indexed Color:** Edit › Edit Colors › Convert to Indexed Color… (`edit.colors.toIndexed`) stores the embedded images in the selection as indexed-color PNGs of at most 256 colors. The palette is chosen as for a PNG-8 export, as evenly spaced levels of red, green and blue, or from the document's swatches, with diffusion, pattern or noise dithering; pixels under half opacity become transparent. The dialog previews live, and OK is one undo step. This is VectorCraft's own command and counts toward no score. `tests::editcolors` and `encode::tests_palette` cover it. Scores and estimates unchanged.
- **Working RGB numeric controls:** the Color panel and Color Picker read RGB, HSB, hex and Web Safe RGB values in the active working RGB space. Editing one RGB channel preserves the other native channels, including colors outside display sRGB. Regressions cover sRGB, Display P3, Wide Gamut RGB and ProPhoto RGB, picker initialization, native numeric round trips, and a slider click with one Undo step. Scores and estimates unchanged.