diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index b51bb4a97d..cb179148cc 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -34,7 +34,7 @@ pub fn specs() -> Vec { "Recolor Artwork", ["Edit", "Edit Colors"], None, - "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null] (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}", + "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null | \"keep\"] (what `group` is rewritten with, a null removing the group's swatch at its place and \"keep\" leaving that swatch its colour, without the Global Adjust (past the swatches it adds nothing; refused for a swatch that is not a colour); default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}", has_doc, apply ), @@ -1680,12 +1680,26 @@ fn apply(s: &mut Session, p: &Value) -> Result { Some(Value::Array(cs)) => Some(cs), Some(_) => return Err(bad(C, "`groupColors` must be an array")), }; - // A null in groupColors removes the group's swatch at its place. + // A null in groupColors removes the group's swatch at its place, and "keep" leaves the swatch + // at its place its color, without the Global Adjust. + let own: Vec> = match group { + Some(g) => { + s.doc()?.doc.swatch_groups.iter().find(|x| x.name == g).map(|g| g.swatches.iter().map(|w| w.paint.color()).collect()).unwrap_or_default() + } + None => vec![], + }; let new: Vec> = match group_colors { Some(cs) => cs .iter() - .map(|v| match v { + .enumerate() + .map(|(i, v)| match v { Value::Null => Ok(None), + // Past the group's swatches it adds nothing. + Value::String(k) if k == "keep" => match own.get(i) { + Some(Some(c)) => Ok(Some(*c)), + Some(None) => Err(bad(C, format!("the swatch at place {i} of groupColors is not a colour to keep"))), + None => Ok(None), + }, v => color_value(v) .map(|c| adjust.apply(c)) .map(|c| Some(in_doc_model(palette.as_ref().map_or(c, |pl| pl.nearest(c))))) diff --git a/crates/engine/src/cmd/swatch.rs b/crates/engine/src/cmd/swatch.rs index 59c13d9603..2b746b7634 100644 --- a/crates/engine/src/cmd/swatch.rs +++ b/crates/engine/src/cmd/swatch.rs @@ -129,7 +129,7 @@ pub fn specs() -> Vec { "Edit Color Group", ["Window", "Swatches"], None, - "{group: colour group, colors: [colour] (hex, key, {c,m,y,k} or {l,a,b}; #rrggbbaa and #rgba are refused; the group's swatches take them in order, extra colours become new swatches, swatches past the end are removed; built-in swatches can't change; a color the swatch already has keeps its model), keepModel?: bool (as paint.setFill), rename?: new group name} rewrite a colour group as one undo step; art linked to its global swatches takes their new colours (and keeps its colour, unlinked, when its swatch goes) → {name, swatches: [names], relinked}", + "{group: colour group, colors: [colour] (hex, key, {c,m,y,k} or {l,a,b}; #rrggbbaa and #rgba are refused; the group's swatches take them in order, extra colours become new swatches, swatches past the end are removed; a null removes the swatch at that place; built-in swatches can't change; a color the swatch already has keeps its model, and a key that names the swatch's color, rounded to the key's steps, keeps the swatch's color unrounded), keepModel?: bool (as paint.setFill), rename?: new group name} rewrite a colour group as one undo step; art linked to its global swatches takes their new colours (and keeps its colour, unlinked, when its swatch goes) → {name, swatches: [names], relinked}", has_doc, swatch_edit_group ), @@ -1340,21 +1340,45 @@ pub(super) fn rewrite_group(d: &mut Document, group: &str, colors: &[Option Result { const C: &str = "swatch.editGroup"; let group = str_param(p, "group").ok_or_else(|| bad(C, "missing `group`"))?; - let colors: Vec = p + // A null removes the swatch at that place. + let colors: Vec> = p .get("colors") .and_then(Value::as_array) .ok_or_else(|| bad(C, "missing `colors`"))? .iter() - .map(|v| color_value(v).ok_or_else(|| bad(C, format!("bad colour {v}")))) + .map(|v| if v.is_null() { Ok(None) } else { color_value(v).map(Some).ok_or_else(|| bad(C, format!("bad colour {v}"))) }) .collect::>()?; super::paint::check_keep_model(p, C)?; - // A color its swatch already has keeps its model. The others take the document's. + // A color its swatch already has keeps its model. The others take the document's. A color key + // (`recolor.colors`) names a color rounded to its steps, so a key of the swatch's own color + // gives the swatch that color, unrounded. let old: Vec> = s.doc()?.doc.swatch_groups.iter().find(|g| g.name == group).map(|g| g.swatches.iter().map(|w| w.paint.color()).collect()).unwrap_or_default(); - let colors: Vec = - 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 entries = p.get("colors").and_then(Value::as_array); + let is_key = |i: usize| entries.and_then(|a| a.get(i)).and_then(Value::as_str).and_then(vectorcraft_color::recolor::ColorKey::parse); + let mut colors: Vec> = colors + .into_iter() + .enumerate() + .map(|(i, c)| { + c.map(|c| match old.get(i).copied().flatten() { + Some(o) if o == c || is_key(i).is_some_and(|k| k == vectorcraft_color::recolor::ColorKey::of(&o)) => o, + _ => super::paint::new_color(s, p, c), + }) + }) + .collect(); + // A null past the group's swatches removes nothing. + while colors.len() > old.len() && colors.last() == Some(&None) { + colors.pop(); + } let rename = str_param(p, "rename"); - let colors: Vec> = colors.into_iter().map(Some).collect(); + // The group's own colors, in order, under its own name change nothing: no undo step. + if let Some(g) = s.doc()?.doc.swatch_groups.iter().find(|g| g.name == group) + && rename.map(str::trim).is_none_or(|n| n.is_empty() || n == group) + && old.len() == colors.len() + && old.iter().zip(&colors).all(|(o, c)| c.is_some() && o == c) + { + return Ok(json!({"name": group, "swatches": g.swatches.iter().map(|w| w.name.clone()).collect::>(), "relinked": 0})); + } 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})) diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs index 4bb0bdf3fe..dae6a1729f 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -489,6 +489,17 @@ fn edit_group_relinks_art_and_apply_rewrites_the_group_with_the_art() { run(&mut s, "recolor.apply", json!({"map": [], "group": "Theme", "groupColors": ["#010203", "cmyk 0 0 0 20"]})); let g = s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Theme").unwrap().clone(); assert_eq!(g.swatches.iter().map(|w| w.paint.color().unwrap()).collect::>(), [Color::rgb8(1, 2, 3), Color::cmyk(0.0, 0.0, 0.0, 0.2)]); + // "keep" leaves a swatch its color, without the Global Adjust that the other colors take. + let adjust = json!({"brightness": -50}); + run(&mut s, "recolor.apply", json!({"map": [], "group": "Theme", "groupColors": ["keep", "#ffffff"], "globalAdjust": adjust})); + let g = s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Theme").unwrap().clone(); + let colors: Vec = g.swatches.iter().map(|w| w.paint.color().unwrap()).collect(); + assert_eq!(colors[0], Color::rgb8(1, 2, 3)); + assert_ne!(colors[1].to_hex(), "#ffffff", "the other color takes the Global Adjust"); + // Past the group's swatches it adds nothing. + run(&mut s, "recolor.apply", json!({"map": [], "group": "Theme", "groupColors": ["keep", "keep", "keep"]})); + let g = s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Theme").unwrap().clone(); + assert_eq!(g.swatches.iter().map(|w| w.paint.color().unwrap()).collect::>(), colors); } /// Art linked to a global swatch of the group that `recolor.apply` rewrites stays linked when the diff --git a/crates/engine/src/tests/swatchcmds.rs b/crates/engine/src/tests/swatchcmds.rs index af059e5e33..306d6b71ad 100644 --- a/crates/engine/src/tests/swatchcmds.rs +++ b/crates/engine/src/tests/swatchcmds.rs @@ -423,6 +423,71 @@ fn edit_color_group_numbers_extra_colors_after_the_names_it_keeps() { assert_eq!(*doc(&s), before); } +/// `swatch.editGroup` with the group's own colors, in order, and its own name (or a blank one) +/// records no undo step; a new order, a new color or a new name records one. +#[test] +fn edit_color_group_with_its_own_colors_records_no_undo_step() { + let mut s = session(); + run(&mut s, "swatch.newGroup", json!({"name": "Mine", "colors": ["#ff0000", "#00ff00"], "keepModel": true})); + let undo = undo_len(&s); + for p in [ + json!({"group": "Mine", "colors": ["#ff0000", "#00ff00"]}), + json!({"group": "Mine", "colors": ["#ff0000", "#00ff00"], "rename": "Mine"}), + json!({"group": "Mine", "colors": ["#ff0000", "#00ff00"], "rename": " "}), + ] { + let r = run(&mut s, "swatch.editGroup", p.clone()); + assert_eq!(r, json!({"name": "Mine", "swatches": ["R=255 G=0 B=0", "R=0 G=255 B=0"], "relinked": 0}), "{p}"); + assert_eq!(undo_len(&s), undo, "{p}: no undo step"); + } + run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": ["#00ff00", "#ff0000"]})); + assert_eq!(undo_len(&s), undo + 1, "a new order is a step"); + run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": ["#00ff00", "#ff0000"], "rename": "Yours"})); + assert_eq!(undo_len(&s), undo + 2, "a new name is a step"); +} + +/// `swatch.editGroup` with the color keys of the group's own colors records no undo step when a +/// color lies between the keys' steps, and a rename keeps that color unrounded; a color given as a +/// value is taken as it is. +#[test] +fn edit_color_group_with_its_own_color_keys_keeps_the_colors() { + let mut s = session(); + run(&mut s, "swatch.newGroup", json!({"name": "Mine", "colors": [{"c": 60.005, "m": 0, "y": 0, "k": 0}, "#00ff00"], "keepModel": true})); + let colors = |s: &Session| -> Vec { + doc(s).swatch_groups.iter().find(|g| g.name == "Mine" || g.name == "Yours").unwrap().swatches.iter().filter_map(|w| w.paint.color()).collect() + }; + let own = colors(&s); + let keys: Vec = own.iter().map(|c| vectorcraft_color::recolor::ColorKey::of(c).to_string()).collect(); + assert_ne!(crate::cmd::color_value(&json!(keys[0])), Some(own[0]), "the key rounds the color"); + let undo = undo_len(&s); + run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": keys})); + assert_eq!(undo_len(&s), undo, "the group's own colors record no step"); + run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": keys, "rename": "Yours"})); + assert_eq!(undo_len(&s), undo + 1, "a new name is a step"); + assert_eq!(colors(&s), own, "the colors are kept unrounded"); + // A color given as a value, not a key, is taken exactly, also within a key's step. + let Color::Cmyk { c, .. } = own[0] else { panic!("a CMYK swatch: {:?}", own[0]) }; + let nudged = Color::cmyk(c - 0.000_002, 0.0, 0.0, 0.0); + assert_eq!(vectorcraft_color::recolor::ColorKey::of(&nudged), vectorcraft_color::recolor::ColorKey::of(&own[0])); + let p = json!({"group": "Yours", "colors": [{"c": c - 0.000_002, "m": 0, "y": 0, "k": 0}, "#00ff00"], "keepModel": true}); + run(&mut s, "swatch.editGroup", p); + assert_eq!(undo_len(&s), undo + 2, "a new value is a step"); + assert_eq!(colors(&s)[0], nudged); +} + +#[test] +fn edit_color_group_with_a_null_removes_that_swatch() { + let mut s = session(); + run(&mut s, "swatch.newGroup", json!({"name": "Mine", "colors": ["#ff0000", "#00ff00", "#0000ff"], "keepModel": true})); + let undo = undo_len(&s); + let r = run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": ["#ff0000", null, "#0000ff"]})); + assert_eq!(r["swatches"], json!(["R=255 G=0 B=0", "R=0 G=0 B=255"])); + assert_eq!(names(&s, Some("Mine")), ["R=255 G=0 B=0", "R=0 G=0 B=255"]); + assert_eq!(undo_len(&s), undo + 1, "a removed swatch is a step"); + run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": ["#ff0000", "#0000ff", null]})); + assert_eq!(undo_len(&s), undo + 1, "a null past the swatches removes nothing and records no step"); + assert!(s.execute("swatch.editGroup", &json!({"group": "Mine", "colors": ["#ff0000", "nope"]})).is_err()); +} + #[test] fn unused_leaves_out_linked_colours_gradients_and_patterns_in_use() { let mut s = session(); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 9e54eb12f6..805a2f69e9 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -658,13 +658,17 @@ pub(crate) fn parent(d: &Dialog) -> Option { /// `ui.dialog.set` changed `field` of the open dialog from `old`: a choice that sets other fields /// sets them as choosing it in the dialog does (Export for Screens' `exportPreset`), a change /// to Export for Screens' sub-folder controls ends an applied preset's item folders, as it does in -/// the dialog, and Transform Each's Relative / Absolute keeps the Scale fields' size. A value +/// the dialog, Transform Each's Relative / Absolute keeps the Scale fields' size, and Recolor +/// Artwork's `group` selects that color group and its `groupAction` runs the button at once. A value /// Composite Fonts' Show Sample can't take is refused. pub(crate) fn field_set(app: &mut VectorcraftApp, field: &str, old: Option<&Value>) -> Result<(), String> { if app.ui.dialog.as_ref().is_some_and(|d| d.kind == transform_each::KIND) { transform_each::field_set(app, field, old); return Ok(()); } + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == recolor::KIND) { + return recolor::field_set(app, field); + } if let Some(d) = app.ui.dialog.as_ref().filter(|d| d.kind == composite_fonts::KIND) { return composite_fonts::field_set(d, field); } diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index e3829f92b5..ff57bd6817 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -46,6 +46,22 @@ //! Opened on colours alone (the Color Guide's Edit or Apply Colors without art), OK saves the new //! colours as a colour group named `groupName`. //! +//! The Color Groups list on the right (under the tabs in a window too narrow for both; the Show +//! Color Groups button beside the tabs shows or hides it, and it opens shown) lists the document's color groups with their colors. A click on one makes it +//! the group being edited, as opening on it would: with art the art is reduced to as many rows as +//! it has colors, which become their new colors, and without art the rows are its colors. Save +//! Changes rewrites the selected group with the rows' new colors (`swatch.editGroup`, renamed by +//! `groupName`), New Color Group saves them as a new group (`swatch.newGroup`), and Delete removes +//! the selected group with its swatches (`swatch.delete`); each is a step of its own, which the +//! Swatches panel shows. When the art has colors of the group, Save Changes keeps the group's +//! swatches in order: a swatch whose color a row lists takes that row's new color (its own color +//! when the row is excluded), and every other swatch keeps its color. After a save with art the +//! rows' new colors take the Global Adjust, which goes back to 0%. When the save recolors art +//! linked to the group's global swatches, the rows are read from the art again (a color the save +//! gave the art is excluded, and a color the art had before keeps its row's new color). Until the +//! rows or the Global Adjust change, OK changes the saved group only by its name. After a Delete +//! without art, OK saves the rows as a new color group. +//! //! 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 @@ -68,8 +84,11 @@ //! show hue and brightness; `hueSaturation`, unset or any other value: hue and saturation), `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 -//! preserve flag or `limitTo` reduces the rows again (and drops `weights`). +//! on; it shows the art so on the Assign tab, with art and rows selected), `groupStorage` (the +//! Color Groups list is shown), `groupAction` (`save`, `new` or `delete`: the list's buttons, +//! checked as the field is set and run by the next frame, or by OK first). Setting `group` to a color group's name selects it in the list, and null +//! selects none. Changing `colors`, a preserve flag or `limitTo` reduces the rows again (and drops +//! `weights`). use egui::{Rect, Sense, Ui, pos2, vec2}; use serde_json::{Value, json}; @@ -96,10 +115,25 @@ pub(super) const SPEC: DialogSpec = DialogSpec { confirm, preview: true, min_width: 540.0, - max_width: Some(560.0), + max_width: Some(MAIN_W + STORAGE_GAP + STORAGE_W), + inputs: |_| &[GROUP_ACTION], ..DialogSpec::FORM }; +/// Widths of the dialog's main part (the tabs), of the Color Groups list and of the gap between +/// them; the height of a group's row in the list. +const MAIN_W: f32 = 560.0; +const STORAGE_W: f32 = 170.0; +const STORAGE_GAP: f32 = 12.0; +const GROUP_ROW_H: f32 = 34.0; +/// The fields of the Color Groups list: whether it is shown, a request from its buttons, and the +/// group whose colors the rows were last given. +const GROUP_STORAGE: &str = "groupStorage"; +const GROUP_ACTION: &str = "groupAction"; +const GROUP_LOADED: &str = "__groupLoaded"; +/// The `recolor.reduce` parameters the art's rows were last reduced with. +const REDUCED: &str = "__reduced"; + const CMD: &str = "recolor.apply"; /// Width of the current colours of a row. const CURRENT_W: f32 = 250.0; @@ -182,6 +216,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { "preserveGrays": kept("preserveGrays", false), "limitTo": limit, "group": group, "groupName": if new_group { Some(NEW_GROUP) } else { group }, "tab": "assign", "rule": Harmony::Complementary.id(), "linked": true, "preview": true, THEME_PICKER: false, THEME_PICKS: [], WEIGHTS: null, FIND: false, "__art": art, "__assign": assign, "__newGroup": new_group, + GROUP_STORAGE: true, GROUP_LOADED: group, }); let mut d = Dialog::new(KIND, fields); // Without art the rows are there from the start: limit them now (art's rows snap as they reduce). @@ -215,7 +250,7 @@ fn reduce_params(d: &Dialog) -> Value { /// Reduce the art's colours into rows again when the count, preserve flags or library changed /// (assigning a group's colours or the opener's colours as the new colours). fn sync(app: &mut VectorcraftApp, d: &mut Dialog) { - const DONE: &str = "__reduced"; + const DONE: &str = REDUCED; let sig = reduce_params(d); if !d.bool("__art") || d.fields.get(DONE) == Some(&sig) { return; @@ -397,7 +432,7 @@ fn group_colors<'a>(app: &VectorcraftApp, d: &Dialog, rs: impl Iterator from_colors(r).first().map(key), - Some(_) if adjust.is_identity() => Some(r["to"].clone()), + Some(_) if adjust.is_identity() && palette.is_none() => Some(r["to"].clone()), Some(c) => { let c = adjust.apply(c); Some(key(&palette.as_ref().map_or(c, |p| p.nearest(c)))) @@ -410,7 +445,7 @@ fn group_colors<'a>(app: &VectorcraftApp, d: &Dialog, rs: impl Iterator Result<(), String> { let rs = rows(d); let order: Vec = match which { "prominent" => prominent_parts(d, &rs).into_iter().map(|p| p.0).collect(), @@ -418,12 +453,483 @@ fn save_group(app: &mut VectorcraftApp, d: &mut Dialog, which: &str) { }; let colors = group_colors(app, d, order.iter().filter_map(|&i| rs.get(i))); if colors.is_empty() { - return; + return Ok(()); } // The group is added to the document itself, not to the preview, which runs again afterwards. cancel_preview(app, d); - if let Err(e) = app.run("swatch.newGroup", json!({"colors": colors, "keepModel": true})) { - app.status(e); + app.run("swatch.newGroup", json!({"colors": colors, "keepModel": true})).map(|_| ()) +} + +/// The colors of the document's color groups, by name, in the Swatches panel's order. +fn doc_groups(app: &VectorcraftApp) -> Vec<(String, Vec)> { + let Some(st) = app.session.active() else { return vec![] }; + st.doc.swatch_groups.iter().map(|g| (g.name.clone(), g.swatches.iter().filter_map(|w| w.paint.color()).collect())).collect() +} + +/// Make the `group` field's color group (none when it is null) the group being edited, when its +/// colors aren't the rows' yet: with art the art is reduced again to as many rows as the group has +/// colors, which become their new colors (as [`open`] does); without art the rows are its colors. +/// A name no color group has is refused, and the field goes back to the group being edited. +fn select_group(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + let want = d.fields.get("group").cloned().unwrap_or(Value::Null); + let loaded = d.fields.get(GROUP_LOADED).cloned().unwrap_or(Value::Null); + if want == loaded { + return Ok(()); + } + // The preview gives the group being edited the name in `groupName`, which the list shows: unless + // the document (without the preview) has another group of that name, it is the same group. + if let Value::String(n) = &want + && loaded.is_string() + && *n == d.str("groupName") + && d.fields.contains_key(super::form::PREVIEWED) + { + cancel_preview(app, d); + if !doc_groups(app).iter().any(|(g, _)| g == n) { + d.fields.insert("group".into(), loaded); + return Ok(()); + } + } + let art = d.bool("__art"); + let name = match &want { + Value::Null => { + // No group: without art OK saves the rows as a new color group. + d.fields.insert(GROUP_LOADED.into(), Value::Null); + if !art { + d.fields.insert("__newGroup".into(), json!(true)); + d.fields.insert("groupName".into(), json!(NEW_GROUP)); + } + return Ok(()); + } + Value::String(n) => n.clone(), + v => { + d.fields.insert("group".into(), loaded); + return Err(format!("`group` must be a color group name, not {v}")); + } + }; + // The group's own colors, not those the preview (which rewrites the group being edited) shows. + if doc_groups(app).iter().any(|(n, _)| *n == name) { + cancel_preview(app, d); + } + let Some((_, colors)) = doc_groups(app).into_iter().find(|(n, _)| *n == name) else { + d.fields.insert("group".into(), loaded); + return Err(format!("no colour group `{name}`")); + }; + let assign: Vec = colors.iter().map(key).collect(); + d.fields.insert(GROUP_LOADED.into(), json!(name)); + d.fields.insert("groupName".into(), json!(name)); + d.fields.insert("__newGroup".into(), json!(false)); + // The group's colors take the place of colors picked with the Color Theme Picker, and the same + // picks made again apply to its rows. + d.fields.insert(THEME_PICKS.into(), json!([])); + d.fields.remove(THEME_DONE); + d.fields.remove(SAVED_ROWS); + d.fields.remove(SAVED_COLORS); + d.fields.remove(SWATCH_ROWS); + if art { + // The art is reduced again (`sync`) into a row per color of the group. + d.fields.insert("colors".into(), json!(assign.len().max(1))); + d.fields.remove(REDUCED); + } else { + let mut rs: Vec = assign.iter().map(|k| json!({"from": [k], "to": k})).collect(); + snap(app, d, &mut rs); + d.fields.insert("rows".into(), Value::Array(rs)); + d.fields.insert("__sel".into(), json!([])); + d.fields.remove(COMPS); + } + d.fields.insert("__assign".into(), Value::Array(assign)); + Ok(()) +} + +/// Run a button of the Color Groups list: `save` rewrites the selected group with the rows' new +/// colors as OK gives them to it (with art, followed by the group's colors no row took) and the +/// name in `groupName`; `new` saves the new colors of the rows that aren't excluded as a new group; +/// `delete` removes the selected group and its swatches. Each is an undo step of its own on the +/// document, not on the preview, which runs again afterwards. +fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Result<(), String> { + check_group_action(app, d, action)?; + let group = d.fields.get("group").and_then(Value::as_str).map(str::to_owned); + // The rows as OK reads them (a group just selected reduces the art again). + sync(app, d); + sync_theme(app, d); + sync_weights(app, d); + match action.as_str() { + Some("new") => save_group(app, d, "all"), + Some("save") if unchanged_since_save(d) => { + // Nothing changed since the last save but perhaps the name. + let name = d.str("groupName"); + if name.trim().is_empty() || group.as_deref() == Some(name.as_str()) { + return Ok(()); + } + cancel_preview(app, d); + let colors: Vec = doc_groups(app) + .into_iter() + .find(|(n, _)| group.as_deref() == Some(n.as_str())) + .map(|g| g.1.iter().map(key).collect()) + .unwrap_or_default(); + let r = app.run("swatch.editGroup", json!({"group": group, "colors": colors, "rename": name}))?; + let name = r["name"].clone(); + d.fields.insert("group".into(), name.clone()); + d.fields.insert(GROUP_LOADED.into(), name.clone()); + d.fields.insert("groupName".into(), name); + Ok(()) + } + Some("save") => { + let rs = rows(d); + let p = apply_params(d); + // With art, the group's colors no row took follow, adjusted and snapped as OK gives them, + // then the colors added on the Edit tab; a row made with New Row that holds no current + // colors gives the group no color. + cancel_preview(app, d); + let own: Vec = doc_groups(app) + .into_iter() + .find(|(n, _)| group.as_deref() == Some(n.as_str())) + .map(|g| g.1.iter().map(key).collect()) + .unwrap_or_default(); + // An excluded row leaves its swatch the color it has now, as OK's `"keep"` does: with + // art, the swatch's color in `__assign`; without art, the swatch's color in the group, + // which an earlier Save Changes may have changed. + let filled: Vec<&Value> = rs.iter().filter(|r| !no_current(r)).collect(); + let rest: Vec = + p["groupColors"].as_array().map(|a| a.iter().skip(filled.len()).map(|k| json!({"from": [k], "to": k})).collect()).unwrap_or_default(); + let assign: Vec = + if d.bool("__art") { d.fields.get("__assign").and_then(Value::as_array).cloned().unwrap_or_default() } else { own.clone() }; + let mut colors: Vec = filled + .iter() + .enumerate() + .filter_map(|(i, r)| if excluded(r) { Some(kept_color(&assign, i)) } else { saved_color(app, d, r) }) + .chain(group_colors(app, d, rest.iter())) + .collect(); + // With art in a color of the group, the group keeps its swatch order: a swatch whose row + // ([`swatch_row`]) is found takes that row's new color (its own color when the row is + // excluded), so the art linked to it takes the color its row shows, and every other + // swatch keeps its color. The colors added on the Edit tab follow. + let found: Vec> = (0..own.len()).map(|i| swatch_row(d, &rs, &own, i)).collect(); + let mut links = None; + if d.bool("__art") && found.iter().any(Option::is_some) { + let added = rs.iter().filter(|r| no_current(r) && is_added(r) && !excluded(r) && !r["to"].is_null()); + let mut saved_links = vec![]; + colors = vec![]; + for (k, f) in own.iter().zip(&found) { + let c = match f { + Some((_, r)) if !excluded(r) => saved_color(app, d, r).unwrap_or_else(|| k.clone()), + _ => k.clone(), + }; + // A removed swatch leaves the saved group. + if !c.is_null() { + saved_links.push(f.as_ref().map_or(Value::Null, |f| f.0.clone())); + } + colors.push(c); + } + let added = group_colors(app, d, added); + saved_links.extend(added.iter().map(|_| Value::Null)); + colors.extend(added); + links = Some(saved_links); + } + let before = art_colors(app); + let r = app.run("swatch.editGroup", json!({"group": group, "colors": colors, "keepModel": true, "rename": p["rename"]}))?; + let name = r["name"].clone(); + d.fields.insert("group".into(), name.clone()); + d.fields.insert(GROUP_LOADED.into(), name.clone()); + d.fields.insert("groupName".into(), name); + // The rows follow the saved group, so a later edit or OK does not remove or add a color + // again: a removed color's row goes (its art keeps its colors). Without art, a color added + // on the Edit tab becomes a row of its own color, after the rows of the group's other + // colors; with art, its row goes and the color is one of the group's colors no row takes. + let art = d.bool("__art"); + let joins = |r: &Value| no_current(r) && is_added(r) && !excluded(r) && !r["to"].is_null(); + let gone: Vec = + rows(d).iter().filter(|r| color_removed(r)).flat_map(|r| r["from"].as_array().cloned().unwrap_or_default()).collect(); + let (mut joined, mut rs): (Vec, Vec) = rows(d).into_iter().filter(|r| !color_removed(r)).partition(|r| joins(r)); + if art { + joined.clear(); + } + for r in &mut joined { + r["from"] = json!([r["to"].clone()]); + if let Some(o) = r.as_object_mut() { + o.remove("added"); + } + } + // The save added them after the group's other colors, whatever the rows' order. + rs.extend(joined); + if rs != rows(d) { + d.fields.insert("__sel".into(), json!([])); + } + d.fields.insert("rows".into(), Value::Array(rs)); + if art { + // The group's colors no row takes are those of the saved group. + let saved: Vec = doc_groups(app) + .into_iter() + .find(|(n, _)| Some(n.as_str()) == r["name"].as_str()) + .map(|g| g.1.iter().map(key).collect()) + .unwrap_or_default(); + d.fields.insert("__assign".into(), Value::Array(saved)); + match links { + Some(l) => d.fields.insert(SWATCH_ROWS.into(), Value::Array(l)), + None => d.fields.remove(SWATCH_ROWS), + }; + // The saved group holds the Global Adjust: the rows' new colors take it, and it goes + // back to 0%, so neither the preview nor OK applies it again. + bake_adjust(app, d); + let rs = rows(d); + if art_colors(app) == before { + mark_saved(app, d); + } else { + reread_rows(app, d, &rs, &before, &gone); + } + } + Ok(()) + } + Some("delete") => { + cancel_preview(app, d); + app.run("swatch.delete", json!({"names": [group]}))?; + d.fields.insert("group".into(), Value::Null); + select_group(app, d) + } + _ => Ok(()), + } +} + +/// The color Save Changes gives the group's swatch for `row`: `null` when the row's color was +/// removed, which removes the swatch as OK does, otherwise its new color as OK gives it. +fn saved_color(app: &VectorcraftApp, d: &Dialog, row: &Value) -> Option { + if color_removed(row) { Some(Value::Null) } else { group_colors(app, d, std::iter::once(row)).into_iter().next() } +} + +/// After Save Changes recolored the art linked to the group's global swatches, read the rows from +/// the art again. A row that lists a color the save gave the art (a paint of a selected object +/// that differs from `before`, [`art_colors`] before the save) is excluded with its first color, +/// so the art keeps it, also when other art has that color: `recolor.apply` recolors every use +/// of a color alike, so the row cannot keep that art's earlier new color without undoing the save. Any other row whose first current color one of the `old` rows listed takes +/// that row's new color and exclusion (art the save left as it was keeps its recolor); the rest +/// are excluded too. A row that lists only `gone` colors (those of swatches the save removed) is +/// left out: its art keeps its colors, and the row gives the group no color. +fn reread_rows(app: &mut VectorcraftApp, d: &mut Dialog, old: &[Value], before: &[Vec], gone: &[Value]) { + let given: Vec = + art_colors(app).iter().zip(before).flat_map(|(now, was)| now.iter().zip(was).filter(|(n, w)| n != w).map(|(n, _)| n.clone())).collect(); + // A swatch whose color the save gave the art is found by that color again: the row its old + // color found lists other art now. + let group = d.fields.get("group").and_then(Value::as_str).map(str::to_owned); + let saved: Vec = + doc_groups(app).into_iter().find(|(n, _)| group.as_deref() == Some(n.as_str())).map(|g| g.1.iter().map(key).collect()).unwrap_or_default(); + if let Some(Value::Array(links)) = d.fields.get_mut(SWATCH_ROWS) { + for (l, c) in links.iter_mut().zip(&saved) { + if given.contains(c) { + *l = Value::Null; + } + } + } + d.fields.insert(THEME_PICKS.into(), json!([])); + d.fields.remove(REDUCED); + sync(app, d); + let mut rs = rows(d); + for r in &mut rs { + let Some(first) = r["from"].as_array().and_then(|f| f.first()).cloned() else { continue }; + let from_save = r["from"].as_array().is_some_and(|f| f.iter().any(|c| given.contains(c))); + match row_listing(old, &first).filter(|_| !from_save) { + Some(o) => { + r["to"] = o["to"].clone(); + r["exclude"] = json!(excluded(o)); + } + None => { + r["to"] = first; + r["exclude"] = json!(true); + } + } + } + rs.retain(|r| r["from"].as_array().is_none_or(|f| f.is_empty() || !f.iter().all(|c| gone.contains(c)))); + d.fields.insert("rows".into(), Value::Array(rs)); + mark_saved(app, d); +} + +/// Give each row's new color the Global Adjust (and Limit to Library) as OK would, and set the +/// Global Adjust back to 0%; nothing changes when it is 0%. +fn bake_adjust(app: &VectorcraftApp, d: &mut Dialog) { + if global_adjust(adjust_values(d)).is_identity() { + return; + } + let mut rs = rows(d); + for r in &mut rs { + if to_color(r).is_some() + && let Some(c) = group_colors(app, d, std::iter::once(&*r)).into_iter().next() + { + r["to"] = c; + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + d.fields.insert("globalAdjust".into(), Value::Object(ADJUSTS.iter().map(|k| (k.to_string(), json!(0.0))).collect())); +} + +/// After Save Changes with art: until the rows or the Global Adjust change, OK and the preview +/// leave the selected group's colors as they were saved. +fn mark_saved(app: &VectorcraftApp, d: &mut Dialog) { + let group = d.fields.get("group").and_then(Value::as_str).map(str::to_owned); + let saved: Vec = + doc_groups(app).into_iter().find(|(n, _)| group.as_deref() == Some(n.as_str())).map(|g| g.1.iter().map(key).collect()).unwrap_or_default(); + d.fields.insert(SAVED_COLORS.into(), Value::Array(saved)); + d.fields.insert(SAVED_ROWS.into(), Value::Array(rows(d))); + d.fields.insert(SAVED_ADJUST.into(), json!(adjust_values(d))); +} + +/// Whether the rows and the Global Adjust are as [`mark_saved`] recorded them. +fn unchanged_since_save(d: &Dialog) -> bool { + d.fields.get(SAVED_ROWS).and_then(Value::as_array).is_some_and(|s| *s == rows(d)) + && d.fields.get(SAVED_ADJUST).is_some_and(|a| *a == json!(adjust_values(d))) +} + +/// The Global Adjust amounts [`mark_saved`] recorded. +const SAVED_ADJUST: &str = "__savedAdjust"; + +/// The colors of each selected object and what is inside it, as row keys, in paint order. +fn art_colors(app: &VectorcraftApp) -> Vec> { + let Some(st) = app.session.active() else { return vec![] }; + st.selection + .objects + .iter() + .map(|id| { + let mut cs = vec![]; + if let Some(n) = st.doc.node(*id) { + vectorcraft_doc::swatches::node_colors(n, &mut |c, _| cs.push(key(c))); + } + cs + }) + .collect() +} + +/// The rows [`mark_saved`] recorded after Save Changes; while the rows are these, OK and the preview +/// leave the group's colors as saved ([`SAVED_COLORS`]) and change only its name. +const SAVED_ROWS: &str = "__savedRows"; + +/// The selected group's colors after Save Changes. OK with a new name keeps the color of each of +/// those swatches (`"keep"`). +const SAVED_COLORS: &str = "__savedColors"; + +/// With art, for each swatch of the selected group after Save Changes, the color that found the row +/// that gave it its new color (`null` for a swatch no row gave one), so a later Save Changes or OK +/// finds that row again when the row still lists its old current color. +const SWATCH_ROWS: &str = "__swatchRows"; + +/// The row that gives the swatch at place `i` of `own` (the group's colors) its new color, with the +/// color that finds it: the row listing the color [`SWATCH_ROWS`] holds for that swatch, else the +/// first row listing the swatch's own color. +fn swatch_row<'a>(d: &Dialog, rs: &'a [Value], own: &[Value], i: usize) -> Option<(Value, &'a Value)> { + let links = d.fields.get(SWATCH_ROWS).and_then(Value::as_array).filter(|l| l.len() == own.len()); + let link = links.and_then(|l| l.get(i)).filter(|l| !l.is_null()); + link.and_then(|l| row_listing(rs, l).map(|r| (l.clone(), r))).or_else(|| own.get(i).and_then(|k| row_listing(rs, k).map(|r| (k.clone(), r)))) +} + +/// The color an excluded row leaves its swatch, the row being the `i`th of the rows with current +/// colors: the swatch's own color in `assign` (the group's colors), else `null`, which adds no +/// swatch past the group's, as OK's `"keep"` does. +fn kept_color(assign: &[Value], i: usize) -> Value { + assign.get(i).cloned().unwrap_or(Value::Null) +} + +/// Refuse a `groupAction` other than `save`, `new` or `delete`, `save` or `delete` with no group +/// selected, and `save` on a group with a swatch that is not a color (a gradient, pattern or None +/// swatch): the rows hold only the group's colors, so the save would replace or remove it. +fn check_group_action(app: &VectorcraftApp, d: &Dialog, action: &Value) -> Result<(), String> { + let group = d.fields.get("group").and_then(Value::as_str); + match (action.as_str(), group) { + (Some("new"), _) => Ok(()), + (Some("save"), Some(g)) if holds_other_paints(app, g) => { + Err(format!("color group `{g}` holds swatches that are not colors, which Save Changes can't keep")) + } + (Some("save" | "delete"), Some(_)) => Ok(()), + (Some("save" | "delete"), None) => Err("missing `group`".into()), + _ => Err(format!("`{GROUP_ACTION}` must be \"save\", \"new\" or \"delete\", not {action}")), + } +} + +/// Whether color group `group` has a swatch that is not a color, in the document as it is without +/// the preview (which can rewrite or rename the group). +fn holds_other_paints(app: &VectorcraftApp, group: &str) -> bool { + let Some(st) = app.session.active() else { return false }; + let doc = st.interaction.as_ref().map_or(&st.doc, |it| &it.doc); + doc.swatch_groups.iter().any(|g| g.name == group && g.swatches.iter().any(|w| w.paint.color().is_none())) +} + +/// Run the button of the Color Groups list that `groupAction` holds, if any. +fn run_group_action(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + match d.fields.remove(GROUP_ACTION) { + Some(a) => group_action(app, d, &a), + None => Ok(()), + } +} + +/// `ui.dialog.set` of `group`, `groupStorage` or `groupAction`: select the group, or check the +/// button, which the next frame (or OK) runs. +pub(super) fn field_set(app: &mut VectorcraftApp, field: &str) -> Result<(), String> { + let Some(mut d) = app.ui.dialog.take() else { return Ok(()) }; + let r = match field { + "group" => select_group(app, &mut d), + GROUP_ACTION => match d.fields.get(GROUP_ACTION).cloned() { + Some(a) => check_group_action(app, &d, &a), + None => Ok(()), + }, + GROUP_STORAGE if !d.fields.get(GROUP_STORAGE).is_some_and(Value::is_boolean) => Err(format!("`{GROUP_STORAGE}` must be true or false")), + _ => Ok(()), + }; + app.ui.dialog = Some(d); + r +} + +/// The Color Groups list: a row per color group of the document with its name and colors (a click +/// selects it), and the Save Changes, New Color Group and Delete buttons under it. +fn group_storage(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, max_h: f32) { + let t = Tokens::get(ui.ctx()); + let groups = doc_groups(app); + let mut current = d.fields.get("group").and_then(Value::as_str).map(str::to_owned); + // While the art previews, the group being edited shows under its new name. + if current.is_some() && d.fields.contains_key(super::form::PREVIEWED) && !groups.iter().any(|(n, _)| Some(n) == current.as_ref()) { + current = Some(d.str("groupName")); + } + let mut picked = None; + egui::ScrollArea::vertical().id_salt("recolor-groups").max_height(max_h).auto_shrink([false, true]).show(ui, |ui| { + for (name, colors) in &groups { + let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), GROUP_ROW_H), Sense::click()); + let on = current.as_deref() == Some(name.as_str()); + if on { + ui.painter().rect_filled(r, 2.0, t.row_selected); + } else if resp.hovered() { + ui.painter().rect_filled(r, 2.0, t.hover); + } + let inner = r.shrink2(vec2(4.0, 3.0)); + ui.painter().text(inner.left_top(), egui::Align2::LEFT_TOP, name, egui::FontId::proportional(12.0), t.text); + let fit = ((inner.width() + 2.0) / 12.0).floor().max(0.0) as usize; + for (n, c) in colors.iter().take(fit).enumerate() { + let x = inner.left() + n as f32 * 12.0; + chip(ui, Rect::from_min_size(pos2(x, inner.bottom() - 10.0), vec2(10.0, 10.0)), *c, false); + } + let resp = resp.on_hover_text(name); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, ui.is_enabled(), on, name)); + if resp.clicked() { + picked = Some(name.clone()); + } + } + }); + if let Some(name) = picked { + d.fields.insert("group".into(), json!(name)); + if let Err(e) = select_group(app, d) { + app.status(e); + } + } + ui.add_space(4.0); + let selected = current.is_some(); + let any = rows(d).iter().any(|r| !excluded(r)); + let mut action = None; + ui.horizontal(|ui| { + if widgets::icon_button_enabled(ui, "save", tl!("Save Changes"), false, selected, 24.0).clicked() { + action = Some("save"); + } + if widgets::icon_button_enabled(ui, "dc-folder", tl!("New Color Group"), false, any, 24.0).clicked() { + action = Some("new"); + } + if widgets::icon_button_enabled(ui, "trash-2", tl!("Delete"), false, selected, 24.0).clicked() { + action = Some("delete"); + } + }); + if let Some(a) = action { + d.fields.insert(GROUP_ACTION.into(), json!(a)); } } @@ -580,6 +1086,12 @@ fn no_current(row: &Value) -> bool { row["from"].as_array().is_none_or(Vec::is_empty) } +/// Whether `row` holds current colors and its new color was removed (`to: null`) and isn't excluded: +/// its swatch in the color group is removed. +fn color_removed(row: &Value) -> bool { + !excluded(row) && !no_current(row) && row["to"].is_null() +} + /// 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) @@ -609,21 +1121,47 @@ fn selection(d: &Dialog) -> Vec { /// `recolor.apply` parameters: the rows, method, library and the group with its new name and /// 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. +/// for a row whose new color was removed, which removes its swatch, and `"keep"` for an excluded +/// row, which leaves its swatch its color), then (with art) the group's colors no row took, then the +/// colors added on the Edit tab. With art in a color of the group, each swatch whose row +/// ([`swatch_row`]) is found takes that row's new color instead, and every other swatch keeps its +/// color, as Save Changes gives them. 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; 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(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(); + // The rows and Global Adjust unchanged since Save Changes: the group keeps its saved colors. + let saved = unchanged_since_save(d); + let assign = d.fields.get("__assign").and_then(Value::as_array).filter(|_| d.bool("__art")).map_or(&[][..], Vec::as_slice); + let found: Vec> = (0..assign.len()).map(|i| swatch_row(d, &rs, assign, i)).collect(); + let keep = json!("keep"); + let group = d.fields.get("group").and_then(Value::as_str).and_then(|g| { let name = d.str("groupName"); let rename = (!name.trim().is_empty() && name != g).then_some(name); - json!({"group": g, "groupColors": colors, "rename": rename}) + let colors: Vec<&Value> = if saved { + // Only a new name changes the group: each swatch keeps its exact color. + rename.as_ref()?; + d.fields.get(SAVED_COLORS).and_then(Value::as_array).map(|a| a.iter().map(|_| &keep).collect())? + } else { + // 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 added = rs.iter().filter(|r| no_current(r) && is_added(r) && !excluded(r)).map(|r| &r["to"]).filter(|c| !c.is_null()); + // A swatch that keeps its color takes no Global Adjust. + if found.iter().any(Option::is_some) { + found + .iter() + .map(|f| match f { + Some((_, r)) if !excluded(r) => &r["to"], + _ => &keep, + }) + .chain(added) + .collect() + } else { + let filled: Vec<&Value> = rs.iter().filter(|r| !no_current(r)).collect(); + let rest = assign.get(filled.len()..).unwrap_or_default(); + let took = filled.iter().map(|r| if excluded(r) { &keep } else { &r["to"] }); + took.chain(rest).chain(added).collect() + } + }; + Some(json!({"group": g, "groupColors": colors, "rename": rename})) }); // A row edited with the sliders carries `model: "new"`: its art takes the mode they showed. let mut p = json!({"map": rs, "method": d.str("method"), "limitTo": d.str("limitTo")}); @@ -661,6 +1199,26 @@ fn find_entry(k: &Value) -> Option { } } +/// The first of `rows` that lists the color entry `k`, as `recolor.apply` reads entries: rows that +/// list it as an exact color (by key, whatever its case or spacing) come before rows whose +/// "#rrggbb" entry matches it by its hex. Rows that give the color a new color (not excluded, `to` +/// not `null`) come first, since `recolor.apply` maps the color with them; an excluded row or one +/// that removes the color is found only when no such row lists it. +fn row_listing<'a>(rows: &'a [Value], k: &Value) -> Option<&'a Value> { + let want = find_entry(k)?; + let hex = |e: &FindEntry| e.as_ref().map_or_else(Clone::clone, |k| k.color().to_hex()); + let lists = |r: &Value, by_hex: bool| { + r["from"].as_array().is_some_and(|f| { + f.iter().filter_map(find_entry).any(|e| match (&e, &want) { + (Ok(a), Ok(b)) => !by_hex && a == b, + _ => by_hex && hex(&e) == hex(&want), + }) + }) + }; + let find = |live: bool, by_hex: bool| rows.iter().filter(|r| !live || (!excluded(r) && !r["to"].is_null())).find(|r| lists(r, by_hex)); + find(true, false).or_else(|| find(true, true)).or_else(|| find(false, false)).or_else(|| find(false, true)) +} + /// While Find is on, on the Assign tab with art and rows selected: what the art previews instead of /// [`apply_params`], as `command.batch` parameters. A first `recolor.apply` gives each current color /// of the rows that aren't selected, and each preserved color, its [`FIND_DIM`] tint, or the nearest lighter one when that is a @@ -734,10 +1292,57 @@ fn find_params(d: &Dialog) -> Option { (!commands.is_empty()).then(|| json!({"commands": commands})) } +/// The tabs, and the Color Groups list on their right while it is shown. fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { + if let Err(e) = select_group(app, d) { + app.status(e); + } + let room = ui.available_width(); + // Without the room for both side by side (a narrow window), the list goes under the tabs. + let beside = room >= SPEC.min_width + STORAGE_GAP + STORAGE_W; + // The Color Picker that a double-click on a new color or Pick from Swatches asks for opens over + // the dialog after the list is drawn, so the window keeps its size while the picker is open. + let mut picker = None; + if !d.bool(GROUP_STORAGE) || !beside { + ui.vertical(|ui| { + ui.set_width(room.min(MAIN_W)); + picker = main(app, ui, d); + if d.bool(GROUP_STORAGE) { + ui.add_space(6.0); + group_storage(app, ui, d, 3.0 * GROUP_ROW_H); + } + }); + } else { + ui.horizontal_top(|ui| { + ui.vertical(|ui| { + ui.set_width((room - STORAGE_GAP - STORAGE_W).clamp(0.0, MAIN_W)); + picker = main(app, ui, d); + }); + ui.add_space(STORAGE_GAP); + ui.vertical(|ui| { + ui.set_width(STORAGE_W); + group_storage(app, ui, d, TAB_H - 30.0); + }); + }); + } + if let Some((i, swatches)) = picker + && let Some(row) = rows(d).get(i) + { + let c = to_color(row).or_else(|| from_colors(row).first().copied()).unwrap_or_default(); + *d = super::color_picker::over_recolor(d, c, i, swatches); + } + false +} + +/// The tabs and the controls under them. Returns the row whose new color a double-click or Pick +/// from Swatches asked to pick in the Color Picker, with `true` for Pick from Swatches. +fn main(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> Option<(usize, bool)> { sync(app, d); sync_theme(app, d); sync_weights(app, d); + if let Err(e) = run_group_action(app, d) { + app.status(e); + } let t = Tokens::get(ui.ctx()); let picking = d.bool(THEME_PICKER); ui.horizontal(|ui| { @@ -751,6 +1356,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { if widgets::icon_button(ui, "pipette", tl!("Color Theme Picker"), picking, 24.0).clicked() { d.fields.insert(THEME_PICKER.into(), json!(!picking)); } + let storage = d.bool(GROUP_STORAGE); + if widgets::icon_button(ui, "library", tl!("Show Color Groups"), storage, 24.0).clicked() { + d.fields.insert(GROUP_STORAGE.into(), json!(!storage)); + } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { // The label is drawn after the menu (right-to-left), so it cannot name it by adjacency. if let Some(i) = widgets::dropdown_named(ui, "recolor-preset", Some(tl!("Preset:")), PRESETS[preset_of(d)], &PRESETS, 130.0) { @@ -782,8 +1391,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { d.fields.insert("rows".into(), Value::Array(rs)); } sync_weights(app, d); - if let Some(which) = d.fields.remove(SAVE_GROUP) { - save_group(app, d, which.as_str().unwrap_or_default()); + if let Some(which) = d.fields.remove(SAVE_GROUP) + && let Err(e) = save_group(app, d, which.as_str().unwrap_or_default()) + { + app.status(e); } if d.fields.get("group").is_some_and(Value::is_string) || d.bool("__newGroup") { ui.add_space(6.0); @@ -804,13 +1415,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { None => form::preview(app, ui, d, "Recolor Artwork", CMD, apply_params(d)), } } - if let Some((i, swatches)) = pick - && let Some(row) = rows(d).get(i) - { - let c = to_color(row).or_else(|| from_colors(row).first().copied()).unwrap_or_default(); - *d = super::color_picker::over_recolor(d, c, i, swatches); - } - false + pick } /// `d` with row `i`'s new colour set to `c` (the Color Picker's OK), snapped to Limit to Library. @@ -829,9 +1434,19 @@ pub(super) fn with_new_color(app: &VectorcraftApp, mut d: Dialog, i: usize, c: C /// save colours opened alone as a new colour group). fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let mut d = d.clone(); + select_group(app, &mut d)?; sync(app, &mut d); sync_theme(app, &mut d); sync_weights(app, &mut d); + // A Color Groups button set with OK in one request runs first, once: the open dialog takes + // its result, so an OK that fails afterwards does not run it again. + if d.fields.contains_key(GROUP_ACTION) { + let r = run_group_action(app, &mut d); + if let Some(live) = app.ui.dialog.as_mut().filter(|x| x.kind == KIND) { + *live = d.clone(); + } + r?; + } if d.bool("__newGroup") { let colors = group_colors(app, &d, rows(&d).iter().filter(|r| in_group(r))); return form::commit_preview(app, "swatch.newGroup", json!({"name": d.str("groupName"), "colors": colors, "keepModel": true})); @@ -2000,14 +2615,14 @@ mod tests { } /// Opened on a color group, OK rewrites it with the new colors of the rows that hold current - /// colors, then the group's colors no such row took: an empty row gives it no color. + /// colors, and the group's color no such row lists keeps its color: an empty row gives it no color. #[test] fn an_empty_row_gives_the_group_no_color() { let mut r = rows(); new_row(&mut r, &[]); let fields = json!({"rows": r, "group": "Trio", "__art": true, "__assign": ["rgb 255 0 0", "rgb 0 0 255", "rgb 0 255 0", "rgb 9 9 9"]}); let p = apply_params(&Dialog::new("recolor", fields)); - assert_eq!(p["groupColors"], json!(["rgb 255 0 0", "rgb 0 0 255", "rgb 0 255 0", "rgb 9 9 9"])); + assert_eq!(p["groupColors"], json!(["rgb 255 0 0", "rgb 0 0 255", "rgb 0 255 0", "keep"])); } /// Opened on colors alone, OK saves the new colors of the rows that hold current colors as the @@ -2032,6 +2647,37 @@ mod tests { } /// Randomize after a seed past `u64::MAX` keeps the largest seed. + /// A row that lists a color exactly comes before an earlier row whose "#rrggbb" entry matches + /// it, as `recolor.apply` reads them; a hex entry matches a key of the same hex. + #[test] + fn a_row_listing_a_color_exactly_comes_before_a_hex_match() { + let rs = + [json!({"from": ["#0000ff"], "to": "rgb 0 255 0"}), json!({"from": ["RGB 0 0 255"], "to": "rgb 255 0 0"}), json!({"from": ["#ff0000"]})]; + assert_eq!(row_listing(&rs, &json!("rgb 0 0 255")), Some(&rs[1])); + assert_eq!(row_listing(&rs, &json!("rgb 255 0 0")), Some(&rs[2])); + assert_eq!(row_listing(&rs, &json!("#ff0000")), Some(&rs[2])); + assert_eq!(row_listing(&rs, &json!("rgb 0 255 0")), None); + assert_eq!(row_listing(&rs, &json!("cmyk 0 0 0 0")), None); + } + + /// A row that gives a color a new color comes before an earlier row that removes it or is + /// excluded, exact or by hex, as `recolor.apply` maps the color with it; those rows are found + /// only when no such row lists the color. + #[test] + fn a_row_giving_a_color_a_new_color_comes_before_one_removing_it() { + let rs = [ + json!({"from": ["rgb 0 0 255"], "to": null}), + json!({"from": ["rgb 0 0 255"], "to": "rgb 0 0 0", "exclude": true}), + json!({"from": ["#0000ff"], "to": "rgb 0 255 0"}), + json!({"from": ["rgb 0 0 255"], "to": "rgb 255 0 0"}), + json!({"from": ["rgb 255 255 0"], "to": null}), + ]; + assert_eq!(row_listing(&rs, &json!("rgb 0 0 255")), Some(&rs[3])); + assert_eq!(row_listing(&rs[..3], &json!("rgb 0 0 255")), Some(&rs[2]), "by hex"); + assert_eq!(row_listing(&rs[..2], &json!("rgb 0 0 255")), Some(&rs[0])); + assert_eq!(row_listing(&rs, &json!("rgb 255 255 0")), Some(&rs[4])); + } + #[test] fn next_seed_holds_at_the_largest() { assert_eq!(next_seed(&Dialog::new("recolor", json!({}))), 1); @@ -2801,4 +3447,844 @@ mod tests { let g = app.session.doc().unwrap().doc.swatch_groups.last().expect("a new color group"); assert_eq!(g.swatches.iter().filter_map(|w| w.paint.color()).collect::>(), [Color::rgb8(255, 128, 0)]); } + + /// Sets `field` of the open dialog to `value` as `ui.dialog.set` does: a refused value leaves + /// the dialog as it was. + fn set(app: &mut VectorcraftApp, field: &str, value: Value) -> Result<(), String> { + let before = app.ui.dialog.clone(); + let old = app.ui.dialog.as_ref().and_then(|d| d.fields.get(field).cloned()); + if let Some(d) = app.ui.dialog.as_mut() { + crate::dialogs::set_field(d, field.into(), value); + } + let r = crate::dialogs::field_set(app, field, old.as_ref()); + if r.is_err() { + app.ui.dialog = before; + } + r + } + + fn group_hex(app: &VectorcraftApp, name: &str) -> Option> { + let doc = &app.session.doc().unwrap().doc; + doc.swatch_groups.iter().find(|g| g.name == name).map(|g| g.swatches.iter().filter_map(|w| w.paint.color()).map(|c| c.to_hex()).collect()) + } + + fn undo_len(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() + } + + /// Sets `groupAction` to `a` as `ui.dialog.set` does and draws the frame that runs it. + fn act(app: &mut VectorcraftApp, ctx: &egui::Context, t: f64, a: &str) -> Result<(), String> { + set(app, GROUP_ACTION, json!(a))?; + frame(app, ctx, t, vec![], 0); + Ok(()) + } + + /// Without art: a group picked in the Color Groups list (the `group` field) gives the rows its + /// colors, and a name no group has is refused. Save Changes rewrites the selected group with the + /// rows' new colors and the name field, as one step, and records none when nothing changes; + /// Delete removes it, after which OK saves the rows as a new group; New Color Group adds one. + #[test] + fn the_color_groups_list_selects_saves_and_deletes_groups() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "A", "colors": ["#ff0000", "#00ff00"], "keepModel": true})).unwrap(); + app.run("swatch.newGroup", json!({"name": "B", "colors": ["#0000ff", "#ffff00", "#ffffff"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "A"})).unwrap(); + assert_eq!(new_colors(&app), [json!("rgb 255 0 0"), json!("rgb 0 255 0")]); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields[GROUP_STORAGE], true, "the list opens shown"); + + set(&mut app, "group", json!("B")).unwrap(); + assert_eq!(new_colors(&app), [json!("rgb 0 0 255"), json!("rgb 255 255 0"), json!("rgb 255 255 255")]); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("groupName"), "B"); + assert_eq!(set(&mut app, "group", json!("Nope")), Err("no colour group `Nope`".into())); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["group"], "B", "a refused name leaves B selected"); + assert!(set(&mut app, GROUP_STORAGE, json!("yes")).is_err()); + assert!(set(&mut app, GROUP_ACTION, json!("rename")).is_err()); + + let undo = undo_len(&app); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + rs[0]["to"] = json!("rgb 0 0 0"); + d.fields.insert("rows".into(), Value::Array(rs)); + d.fields.insert("groupName".into(), json!("Night")); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(group_hex(&app, "Night"), Some(vec!["#000000".into(), "#ffff00".into(), "#ffffff".into()])); + assert_eq!(group_hex(&app, "B"), None, "renamed"); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["group"], "Night"); + assert_eq!(undo_len(&app), undo + 1, "one step"); + act(&mut app, &ctx, 0.2, "save").unwrap(); + assert_eq!(undo_len(&app), undo + 1, "saving the same colors again records no step"); + + act(&mut app, &ctx, 0.3, "delete").unwrap(); + assert_eq!(group_hex(&app, "Night"), None); + assert_eq!(undo_len(&app), undo + 2); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(d.fields["group"].is_null() && d.bool("__newGroup"), "{:?}", d.fields); + assert_eq!(act(&mut app, &ctx, 0.4, "delete"), Err("missing `group`".into())); + assert_eq!(act(&mut app, &ctx, 0.5, "save"), Err("missing `group`".into())); + assert_eq!(undo_len(&app), undo + 2, "a refused button records no step"); + + let n = app.session.doc().unwrap().doc.swatch_groups.len(); + act(&mut app, &ctx, 0.6, "new").unwrap(); + let doc = &app.session.doc().unwrap().doc; + assert_eq!(doc.swatch_groups.len(), n + 1); + let last: Vec = doc.swatch_groups.last().unwrap().swatches.iter().filter_map(|w| w.paint.color()).map(|c| c.to_hex()).collect(); + assert_eq!(last, ["#000000", "#ffff00", "#ffffff"]); + assert_eq!(group_hex(&app, "A"), Some(vec!["#ff0000".into(), "#00ff00".into()]), "other groups are left as they are"); + } + + /// Without art: after a group is picked in the list, the same Color Theme Picker picks that gave + /// the group before it its colors give the new group's rows the palette of the art picked too. + #[test] + fn theme_picks_apply_again_after_another_group_is_picked() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + square(&mut app, 100.0, "#00ff00"); + app.run("select.set", json!({"ids": []})).unwrap(); + app.run("swatch.newGroup", json!({"name": "A", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + app.run("swatch.newGroup", json!({"name": "B", "colors": ["#0000ff", "#ffff00", "#ffffff"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "A"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![], 0); + let picks = json!([{"at": [107, 17]}]); + app.ui.dialog.as_mut().unwrap().fields.insert(THEME_PICKS.into(), picks.clone()); + frame(&mut app, &ctx, 0.1, vec![], 0); + assert_eq!(new_colors(&app), [json!("rgb 0 255 0"), json!("rgb 0 255 0")]); + set(&mut app, "group", json!("B")).unwrap(); + frame(&mut app, &ctx, 0.2, vec![], 0); + assert_eq!(new_colors(&app), [json!("rgb 0 0 255"), json!("rgb 255 255 0"), json!("rgb 255 255 255")]); + app.ui.dialog.as_mut().unwrap().fields.insert(THEME_PICKS.into(), picks); + frame(&mut app, &ctx, 0.3, vec![], 0); + assert_eq!(new_colors(&app), [json!("rgb 0 255 0"), json!("rgb 0 255 0"), json!("rgb 0 255 0")], "the picks apply to B's rows"); + } + + /// Save Changes on a group with a swatch that is not a color is refused, renamed or not, and + /// leaves the group as it is: the rows hold only its colors. + #[test] + fn saving_a_group_with_a_swatch_that_is_not_a_color_is_refused() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Mixed", "colors": ["#ff0000", "#00ff00"], "keepModel": true})).unwrap(); + let doc = std::sync::Arc::make_mut(&mut app.session.doc_mut().unwrap().doc); + let g = doc.swatch_groups.iter_mut().find(|g| g.name == "Mixed").unwrap(); + g.swatches.insert(1, fade_swatch()); + app.run("ui.recolorDialog", json!({"group": "Mixed"})).unwrap(); + assert_eq!(new_colors(&app), [json!("rgb 255 0 0"), json!("rgb 0 255 0")]); + let undo = undo_len(&app); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + rs[0]["to"] = json!("rgb 0 0 0"); + d.fields.insert("rows".into(), Value::Array(rs)); + let refused: Result<(), String> = Err("color group `Mixed` holds swatches that are not colors, which Save Changes can't keep".into()); + assert_eq!(act(&mut app, &ctx, 0.1, "save"), refused); + app.ui.dialog.as_mut().unwrap().fields.insert("groupName".into(), json!("Renamed")); + assert_eq!(act(&mut app, &ctx, 0.2, "save"), refused); + // OK first runs a save set together with it, and the dialog stays open. + app.ui.dialog.as_mut().unwrap().fields.insert(GROUP_ACTION.into(), json!("save")); + assert!(crate::dialogs::confirm(&mut app).is_err()); + assert!(app.ui.dialog.is_some()); + let g = app.session.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Mixed").unwrap(); + assert_eq!(g.swatches[1], fade_swatch(), "the swatch is kept"); + assert_eq!(group_hex(&app, "Mixed"), Some(vec!["#ff0000".into(), "#00ff00".into()])); + assert_eq!(undo_len(&app), undo, "no step"); + } + + /// A gradient swatch, for a color group. + fn fade_swatch() -> vectorcraft_color::Swatch { + let paint = vectorcraft_color::Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(Default::default()))); + vectorcraft_color::Swatch { name: "Fade".into(), paint, global: false, spot: false } + } + + /// With art, the preview rewrites the group being edited, its other swatch included; Save + /// Changes is still refused, as the group is without the preview, and Cancel leaves it as it was. + #[test] + fn saving_a_group_with_a_swatch_that_is_not_a_color_is_refused_while_previewing() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Mixed", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + let doc = std::sync::Arc::make_mut(&mut app.session.doc_mut().unwrap().doc); + let g = doc.swatch_groups.iter_mut().find(|g| g.name == "Mixed").unwrap(); + g.swatches.push(fade_swatch()); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Mixed"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![], 0); + let undo = undo_len(&app); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + rs[0]["to"] = json!("rgb 0 0 0"); + d.fields.insert("rows".into(), Value::Array(rs)); + frame(&mut app, &ctx, 0.1, vec![], 0); + assert!(app.session.in_interaction(), "the art previews"); + let previewed = app.session.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Mixed").map(|g| g.swatches.len()); + assert_eq!(previewed, Some(2), "the preview's rewrite of the group leaves out its other swatch"); + let refused: Result<(), String> = Err("color group `Mixed` holds swatches that are not colors, which Save Changes can't keep".into()); + assert_eq!(act(&mut app, &ctx, 0.2, "save"), refused); + crate::dialogs::cancel(&mut app); + let g = app.session.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Mixed").unwrap(); + assert_eq!(g.swatches.last(), Some(&fade_swatch()), "the swatch is kept"); + assert_eq!(group_hex(&app, "Mixed"), Some(vec!["#ff0000".into(), "#0000ff".into()])); + assert_eq!(undo_len(&app), undo, "no step"); + } + + /// Save Changes on a group whose global swatches the selected art is linked to: the art takes + /// the group's new colors, and the rows are read from the art again, so they list its colors as + /// they are now. A color the art had before keeps its row's new color; a color the save gave + /// it stays as it is. + #[test] + fn saving_a_group_the_art_links_to_reads_the_rows_again() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + if r["from"].as_array().is_some_and(|f| f.contains(&json!("rgb 255 0 0"))) { + r["to"] = json!("rgb 0 128 0"); + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + frame(&mut app, &ctx, 0.2, vec![], 0); + // The rows took the group's colors in their order, so one of the swatches is now green. + let saved = group_hex(&app, "Linked").unwrap(); + assert!(saved.len() == 2 && saved.contains(&"#008000".to_string()), "{saved:?}"); + let mut want = saved.clone(); + want.sort(); + assert_eq!(fill_hex(&app, red), "#008000", "the red square keeps the new color its row gave it"); + for r in super::rows(app.ui.dialog.as_ref().unwrap()) { + if !from_colors(&r).iter().any(|c| ["#ff0000", "#0000ff"].contains(&c.to_hex().as_str())) { + assert!(excluded(&r) && r["to"] == r["from"][0], "a color the save gave the art stays: {r}"); + } + } + let mut froms: Vec = super::rows(app.ui.dialog.as_ref().unwrap()).iter().flat_map(from_colors).map(|c| c.to_hex()).collect(); + froms.sort(); + assert_eq!(froms, want, "the rows list the art's colors as they are now"); + assert!(apply_params(app.ui.dialog.as_ref().unwrap()).get("group").is_none(), "OK leaves the saved group as it is"); + // OK with only a new name keeps the preview as one step and renames the group, keeping its + // saved colors. + let undo = undo_len(&app); + let mut d = app.ui.dialog.clone().unwrap(); + d.fields.insert("groupName".into(), json!("Renamed")); + confirm(&mut app, &d).unwrap(); + assert_eq!(group_hex(&app, "Renamed"), Some(saved)); + assert_eq!(group_hex(&app, "Linked"), None); + assert_eq!(fill_hex(&app, red), "#008000"); + assert_eq!(undo_len(&app), undo + 1); + } + + /// OK with only a new name after Save Changes leaves every swatch of the group its exact color: + /// a CMYK swatch no row lists keeps components finer than a hundredth of a percent. + #[test] + fn renaming_a_saved_group_keeps_its_exact_colors() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + let fine = Color::cmyk(0.123_456, 0.654_321, 0.0, 0.010_101); + let doc = std::sync::Arc::make_mut(&mut app.session.doc_mut().unwrap().doc); + let g = doc.swatch_groups.iter_mut().find(|g| g.name == "Linked").unwrap(); + g.swatches.push(vectorcraft_color::Swatch { name: "Fine".into(), paint: vectorcraft_color::Paint::solid(fine), global: false, spot: false }); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + if r["from"].as_array().is_some_and(|f| f.contains(&json!("rgb 255 0 0"))) { + r["to"] = json!("rgb 0 128 0"); + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + frame(&mut app, &ctx, 0.2, vec![], 0); + let swatches = |app: &VectorcraftApp, name: &str| { + let doc = &app.session.doc().unwrap().doc; + doc.swatch_groups.iter().find(|g| g.name == name).map(|g| g.swatches.iter().map(|w| w.paint.color()).collect::>()) + }; + let saved = swatches(&app, "Linked").unwrap(); + assert_eq!(saved.last(), Some(&Some(fine)), "Save Changes keeps the swatch no row lists"); + let mut d = app.ui.dialog.clone().unwrap(); + d.fields.insert("groupName".into(), json!("Renamed")); + confirm(&mut app, &d).unwrap(); + assert_eq!(swatches(&app, "Renamed"), Some(saved), "the rename keeps every color exactly"); + } + + /// Save Changes where one row's new color is another row's current color: the art linked to the + /// group keeps the colors the save gave it, and is not recolored again by the other row; a + /// Global Adjust set afterwards gives OK the group again. + #[test] + fn saving_a_group_keeps_the_colors_it_gave_the_linked_art() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + let from = from_colors(r).first().map(|c| c.to_hex()); + r["to"] = match from.as_deref() { + Some("#ff0000") => json!("rgb 0 0 255"), + _ => json!("rgb 0 128 0"), + }; + } + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + frame(&mut app, &ctx, 0.2, vec![], 0); + let mut group = group_hex(&app, "Linked").unwrap(); + group.sort(); + let mut fills = vec![fill_hex(&app, red), fill_hex(&app, blue)]; + fills.sort(); + assert_eq!(fills, group, "the art shows the saved group's colors, not a second recolor"); + assert!(apply_params(app.ui.dialog.as_ref().unwrap()).get("group").is_none()); + app.ui.dialog.as_mut().unwrap().fields.insert("globalAdjust".into(), json!({"brightness": -50.0})); + assert!(apply_params(app.ui.dialog.as_ref().unwrap()).get("group").is_some(), "a new Global Adjust rewrites the group at OK"); + } + + /// Save Changes with art in only some colors of the group: the swatches keep their order, and a + /// swatch no row lists keeps its color. + #[test] + fn saving_a_group_keeps_the_swatches_the_art_does_not_use() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let red = square(&mut app, 10.0, "#ff0000"); + let blue = square(&mut app, 40.0, "#0000ff"); + let yellow = square(&mut app, 70.0, "#ffff00"); + app.run("select.set", json!({"ids": [red, blue, yellow]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + let order = group_hex(&app, "Linked").unwrap(); + app.run("select.set", json!({"ids": [blue, yellow]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + let to = match from_colors(r).first().map(|c| c.to_hex()).as_deref() { + Some("#0000ff") => json!("rgb 0 128 0"), + _ => r["from"][0].clone(), + }; + r["to"] = to; + } + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + let want: Vec = order.iter().map(|h| if h == "#0000ff" { "#008000".into() } else { h.clone() }).collect(); + assert_eq!(group_hex(&app, "Linked"), Some(want), "the swatches keep their order and the red one its color"); + assert_eq!(fill_hex(&app, red), "#ff0000", "art linked to a swatch no row lists is left as it is"); + } + + /// Save Changes with art in colors of the group keeps the Edit tab's changes: a removed color's + /// swatch is removed, and a color added on the Edit tab joins the group after the others. + #[test] + fn saving_a_group_keeps_added_and_removed_colors() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let red = square(&mut app, 10.0, "#ff0000"); + let blue = square(&mut app, 40.0, "#0000ff"); + let yellow = square(&mut app, 70.0, "#ffff00"); + app.run("select.set", json!({"ids": [red, blue, yellow]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + let order = group_hex(&app, "Linked").unwrap(); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + let to = match from_colors(r).first().map(|c| c.to_hex()).as_deref() { + Some("#0000ff") => Value::Null, + _ => r["from"][0].clone(), + }; + r["to"] = to; + } + rs.push(json!({"from": [], "to": "rgb 0 128 0", "added": true})); + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + let mut want: Vec = order.into_iter().filter(|h| h != "#0000ff").collect(); + want.push("#008000".into()); + assert_eq!(group_hex(&app, "Linked"), Some(want.clone()), "the removed swatch goes and the added color follows the others"); + assert_eq!(fill_hex(&app, blue), "#0000ff", "art linked to a removed swatch keeps its color"); + let rs = super::rows(app.ui.dialog.as_ref().unwrap()); + assert!(rs.iter().all(|r| !r["to"].is_null() && !is_added(r)), "the rows follow the saved group: {rs:?}"); + let assign = app.ui.dialog.as_ref().unwrap().fields["__assign"].clone(); + let assign: Vec = assign.as_array().unwrap().iter().filter_map(color_value).map(|c| c.to_hex()).collect(); + assert_eq!(Some(assign), group_hex(&app, "Linked"), "a later edit gives the group no removed swatch back"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(group_hex(&app, "Linked"), Some(want), "OK removes and adds nothing more"); + } + + /// Save Changes that recolors linked art reads the rows from the art again; a color added on the + /// Edit tab stays one of the group's colors and a removed one does not come back, so OK after a + /// further edit keeps them as saved. + #[test] + fn saving_a_group_that_reads_the_rows_again_keeps_an_added_color() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let red = square(&mut app, 10.0, "#ff0000"); + let blue = square(&mut app, 40.0, "#0000ff"); + let lime = square(&mut app, 70.0, "#00ff00"); + app.run("select.set", json!({"ids": [red, blue, lime]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + let to = match from_colors(r).first().map(|c| c.to_hex()).as_deref() { + Some("#ff0000") => json!("rgb 0 128 0"), + Some("#00ff00") => Value::Null, + _ => r["from"][0].clone(), + }; + r["to"] = to; + } + rs.push(json!({"from": [], "to": "rgb 255 255 0", "added": true})); + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(fill_hex(&app, red), "#008000", "the save recolored the linked art"); + assert_eq!(fill_hex(&app, lime), "#00ff00", "art linked to the removed swatch keeps its color"); + let group = group_hex(&app, "Linked").unwrap(); + assert!(group.contains(&"#ffff00".to_string()) && !group.contains(&"#00ff00".to_string()), "{group:?}"); + let mut d = app.ui.dialog.clone().unwrap(); + let mut rs = super::rows(&d); + assert!(rs.iter().all(|r| !is_added(r)), "{rs:?}"); + if let Some(r) = rs.last_mut() { + r["to"] = json!("rgb 10 10 10"); + } + d.fields.insert("rows".into(), Value::Array(rs)); + let colors = sent_by(&app, &d); + assert_eq!(colors.iter().filter(|c| *c == "#ffff00").count(), 1, "OK after a further edit keeps the added color once: {colors:?}"); + assert!(!colors.contains(&"#00ff00".to_string()), "nor brings the removed color back: {colors:?}"); + } + + /// Save Changes where the rows list their current colors as "#rrggbb": a row matches the swatch + /// of the same color, so the swatches keep their order and the one a row lists takes its new + /// color; read again afterwards, a row whose old entry was a hex keeps its new color. + #[test] + fn saving_a_group_matches_rows_that_list_hex_colors() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let red = square(&mut app, 10.0, "#ff0000"); + let blue = square(&mut app, 40.0, "#0000ff"); + let yellow = square(&mut app, 70.0, "#ffff00"); + app.run("select.set", json!({"ids": [red, blue, yellow]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + let order = group_hex(&app, "Linked").unwrap(); + let orange = square(&mut app, 100.0, "#ff8000"); + app.run("select.set", json!({"ids": [blue, yellow, orange]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + let hex: Vec = from_colors(r).iter().map(|c| c.to_hex()).collect(); + r["to"] = match hex.first().map(String::as_str) { + Some("#0000ff") => json!("rgb 0 128 0"), + Some("#ff8000") => json!("rgb 128 0 128"), + _ => r["from"][0].clone(), + }; + r["from"] = json!(hex); + } + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + let want: Vec = order.iter().map(|h| if h == "#0000ff" { "#008000".into() } else { h.clone() }).collect(); + assert_eq!(group_hex(&app, "Linked"), Some(want), "the blue swatch takes the green, the red one keeps its color"); + assert_eq!((fill_hex(&app, red), fill_hex(&app, blue)), ("#ff0000".into(), "#008000".into())); + let rs = super::rows(app.ui.dialog.as_ref().unwrap()); + let o = rs.iter().find(|r| from_colors(r).iter().any(|c| c.to_hex() == "#ff8000")).unwrap(); + assert!(!excluded(o) && o["to"] == json!("rgb 128 0 128"), "the orange row keeps its new color: {o}"); + } + + /// Save Changes with art in the group's colors that is not linked to its swatches: the art is + /// left to the preview, and OK leaves the saved group as it is until the rows change. + #[test] + fn saving_a_group_with_unlinked_art_keeps_the_saved_group_at_ok() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + let to = match from_colors(r).first().map(|c| c.to_hex()).as_deref() { + Some("#0000ff") => json!("rgb 0 128 0"), + _ => r["from"][0].clone(), + }; + r["to"] = to; + } + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ff0000".into(), "#008000".into()])); + frame(&mut app, &ctx, 0.2, vec![], 0); + assert_eq!(fill_hex(&app, blue), "#008000", "the art previews its row's new color"); + assert!(apply_params(app.ui.dialog.as_ref().unwrap()).get("group").is_none(), "OK leaves the saved group as it is"); + } + + /// The colors `d`'s OK gives the selected group, as hex, `"keep"` read as the color the swatch + /// at its place has. + fn sent_by(app: &VectorcraftApp, d: &Dialog) -> Vec { + let own = group_hex(app, &d.str("group")).unwrap_or_default(); + let p = apply_params(d); + let hex = |(i, k): (usize, &Value)| if *k == json!("keep") { own.get(i).cloned() } else { color_value(k).map(|c| c.to_hex()) }; + p["groupColors"].as_array().unwrap().iter().enumerate().filter_map(hex).collect() + } + + /// The colors OK gives the selected group, as [`sent_by`] reads them. + fn sent_hex(app: &VectorcraftApp) -> Vec { + sent_by(app, app.ui.dialog.as_ref().unwrap()) + } + + /// Sets the new color of the rows whose first current color is `hex` to `to`. + fn set_row(app: &mut VectorcraftApp, hex: &str, to: Value) { + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + if from_colors(r).first().map(|c| c.to_hex()).as_deref() == Some(hex) { + r["to"] = to.clone(); + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + } + + /// With unlinked art in some of the group's colors, a second Save Changes after a further edit of + /// a row gives the swatch the first save gave that row's color the row's new color, and OK does + /// too; the swatch no row lists keeps its color both times. + #[test] + fn saving_a_group_twice_with_unlinked_art_gives_a_row_its_swatch_again() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff", "#ffff00"], "keepModel": true})).unwrap(); + let (blue, yellow) = (square(&mut app, 10.0, "#0000ff"), square(&mut app, 40.0, "#ffff00")); + app.run("select.set", json!({"ids": [blue, yellow]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + set_row(&mut app, "#0000ff", json!("rgb 0 128 0")); + set_row(&mut app, "#ffff00", json!("rgb 255 255 0")); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ff0000".into(), "#008000".into(), "#ffff00".into()])); + frame(&mut app, &ctx, 0.2, vec![], 0); + set_row(&mut app, "#0000ff", json!("rgb 128 0 128")); + let sent = sent_hex(&app); + assert_eq!(sent, ["#ff0000", "#800080", "#ffff00"], "OK gives the blue row's swatch its new color"); + act(&mut app, &ctx, 0.3, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ff0000".into(), "#800080".into(), "#ffff00".into()]), "the second save does too"); + } + + /// Without art, an excluded row leaves its swatch its own color at Save Changes and at OK, even + /// when its new color was changed before it was excluded. + #[test] + fn saving_a_group_without_art_keeps_an_excluded_rows_color() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + if from_colors(r).first().map(|c| c.to_hex()).as_deref() == Some("#ff0000") { + r["to"] = json!("rgb 0 128 0"); + r["exclude"] = json!(true); + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + let sent = sent_hex(&app); + assert_eq!(sent, ["#ff0000", "#0000ff"], "OK keeps the excluded row's swatch"); + let p = apply_params(app.ui.dialog.as_ref().unwrap()); + assert_eq!(p["groupColors"][0], "keep", "so the Global Adjust leaves it as it is too: {p}"); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ff0000".into(), "#0000ff".into()]), "so does Save Changes"); + } + + /// With art in more colors than the group has swatches, an excluded row past the swatches adds + /// no color at Save Changes, as at OK. + #[test] + fn saving_a_group_with_art_adds_no_color_for_an_excluded_row_past_its_swatches() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000"], "keepModel": true})).unwrap(); + let (blue, yellow) = (square(&mut app, 10.0, "#0000ff"), square(&mut app, 40.0, "#ffff00")); + app.run("select.set", json!({"ids": [blue, yellow]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("method".into(), json!(Method::Exact.id())); + d.fields.insert("colors".into(), json!(2)); + d.fields.remove(REDUCED); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + assert_eq!(rs.len(), 2, "a row for each color of the art: {rs:?}"); + for r in &mut rs { + r["exclude"] = json!(true); + } + d.fields.insert("rows".into(), Value::Array(rs)); + // `recolor.apply` adds nothing for a "keep" past the group's swatches. + assert_eq!(apply_params(app.ui.dialog.as_ref().unwrap())["groupColors"], json!(["keep", "keep"]), "OK adds no color"); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ff0000".into()]), "Save Changes adds none either"); + } + + /// Without art, a row excluded after Save Changes gave its swatch a new color leaves the swatch + /// that saved color at a second Save Changes, as OK does. + #[test] + fn saving_a_group_without_art_keeps_a_saved_color_when_its_row_is_excluded() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![], 0); + set_row(&mut app, "#ff0000", json!("rgb 0 128 0")); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#008000".into(), "#0000ff".into()])); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + if r["to"] == json!("rgb 0 128 0") { + r["exclude"] = json!(true); + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + assert_eq!(sent_hex(&app), ["#008000", "#0000ff"], "OK keeps the saved color"); + act(&mut app, &ctx, 0.2, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#008000".into(), "#0000ff".into()]), "so does a second Save Changes"); + } + + /// Save Changes that recolors linked art so that one swatch takes another swatch's old color: + /// read again, the row of the second swatch's new color gives that swatch a later new color. + #[test] + fn saving_a_group_twice_with_linked_art_finds_the_row_of_a_swatchs_new_color() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + assert_eq!(group_hex(&app, "Linked"), Some(vec!["#ff0000".into(), "#0000ff".into()])); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + set_row(&mut app, "#ff0000", json!("rgb 0 0 255")); + set_row(&mut app, "#0000ff", json!("rgb 0 128 0")); + act(&mut app, &ctx, 0.1, "save").unwrap(); + frame(&mut app, &ctx, 0.2, vec![], 0); + assert_eq!(group_hex(&app, "Linked"), Some(vec!["#0000ff".into(), "#008000".into()])); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + if from_colors(r).first().map(|c| c.to_hex()).as_deref() == Some("#008000") { + r["to"] = json!("rgb 128 0 128"); + r["exclude"] = json!(false); + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + assert_eq!(sent_hex(&app), ["#0000ff", "#800080"], "OK gives the green swatch the green row's new color"); + act(&mut app, &ctx, 0.3, "save").unwrap(); + assert_eq!(group_hex(&app, "Linked"), Some(vec!["#0000ff".into(), "#800080".into()]), "so does Save Changes"); + } + + /// Save Changes with a Global Adjust: the saved group holds it, the rows' new colors take it and + /// it goes back to 0%, so OK with a new name renames the group without adjusting it again. + #[test] + fn saving_a_group_with_a_global_adjust_applies_it_once() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("method".into(), json!(Method::Exact.id())); + d.fields.insert("globalAdjust".into(), json!({"brightness": -50.0})); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + act(&mut app, &ctx, 0.1, "save").unwrap(); + let saved = group_hex(&app, "Plain").unwrap(); + assert!(!saved.contains(&"#ff0000".to_string()), "the save darkened the group: {saved:?}"); + frame(&mut app, &ctx, 0.2, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(adjust_values(d), [0.0; 4]); + d.fields.insert("groupName".into(), json!("Dark")); + let p = apply_params(app.ui.dialog.as_ref().unwrap()); + assert!(p.get("globalAdjust").is_none(), "{p}"); + assert_eq!(p["groupColors"], json!(vec!["keep"; saved.len()]), "OK keeps each saved color"); + let d = app.ui.dialog.clone().unwrap(); + confirm(&mut app, &d).unwrap(); + assert_eq!(group_hex(&app, "Dark"), Some(saved), "OK renames the group with its saved colors"); + } + + /// Without art, Save Changes with a Global Adjust gives the group the rows' new colors with the + /// adjustment, and OK gives it the same colors again: the adjustment applies to the rows' new + /// colors, not to the saved group. + #[test] + fn saving_a_group_without_art_with_a_global_adjust_applies_it_once() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("globalAdjust".into(), json!({"brightness": -50.0})); + frame(&mut app, &ctx, 0.0, vec![], 0); + act(&mut app, &ctx, 0.1, "save").unwrap(); + let saved = group_hex(&app, "Plain").unwrap(); + assert!(!saved.contains(&"#ff0000".to_string()), "the save darkened the group: {saved:?}"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(group_hex(&app, "Plain").unwrap(), saved, "OK does not darken the group again"); + } + + /// With Limit to Library, Save Changes gives the group the library's nearest color to a row's + /// new color, as OK does, also when the rows were set without being snapped. + #[test] + fn saving_a_group_snaps_its_colors_to_the_library() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let doc = &app.session.doc().unwrap().doc; + let names: Vec<_> = doc + .swatches + .iter() + .filter(|s| !s.is_reserved()) + .map(|s| s.name.clone()) + .chain(doc.swatch_groups.iter().map(|g| g.name.clone())) + .collect(); + app.run("swatch.delete", json!({"names": names})).unwrap(); + app.run("swatch.new", json!({"name": "Only Yellow", "color": "#ffff00"})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ffff00"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("limitTo".into(), json!("document")); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + rs[0]["to"] = json!("rgb 250 250 10"); + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ffff00".into()]), "the saved color is the library's"); + } + + /// Without art, Save Changes removes a removed color's swatch and adds a color added on the Edit + /// tab, and OK afterwards gives the group the same colors: it removes and adds nothing more. + #[test] + fn saving_a_group_without_art_with_added_and_removed_colors_keeps_them_at_ok() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#00ff00", "#0000ff"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + if from_colors(r).first().map(|c| c.to_hex()).as_deref() == Some("#00ff00") { + r["to"] = Value::Null; + } + } + // The added color's row was moved ahead of the others. + rs.insert(0, json!({"from": [], "to": "rgb 255 255 0", "added": true})); + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + let want: Vec = ["#ff0000", "#0000ff", "#ffff00"].map(String::from).to_vec(); + assert_eq!(group_hex(&app, "Plain"), Some(want.clone()), "the save removes green and adds yellow"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(want), "OK gives the group the same colors"); + } + + /// With art: a group picked in the list reduces the art to a row per color of the group, which + /// become the rows' new colors, and the art previews them; the list draws beside the tabs and + /// hides with `groupStorage`. + #[test] + fn a_group_picked_in_the_list_recolors_the_art() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Warm", "colors": ["#ffff00", "#00ff00"], "keepModel": true})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Cool", "colors": ["#0000ff"], "keepModel": true})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("ui.recolorDialog", json!({})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + assert_eq!(fill_hex(&app, red), "#ff0000"); + // A button set with the group, before a frame, saves the rows the group gives the art. + let n = app.session.doc().unwrap().doc.swatch_groups.len(); + set(&mut app, "group", json!("Warm")).unwrap(); + act(&mut app, &ctx, 0.1, "new").unwrap(); + let doc = &app.session.doc().unwrap().doc; + let mut saved: Vec = doc.swatch_groups.last().unwrap().swatches.iter().filter_map(|w| w.paint.color()).map(|c| c.to_hex()).collect(); + saved.sort(); + assert_eq!((doc.swatch_groups.len(), saved), (n + 1, vec!["#00ff00".to_string(), "#ffff00".to_string()])); + frame(&mut app, &ctx, 0.2, vec![], 0); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(super::rows(d).len(), 2); + assert_eq!(d.str("groupName"), "Warm"); + let mut shown = [fill_hex(&app, red), fill_hex(&app, blue)]; + shown.sort(); + assert_eq!(shown, ["#00ff00", "#ffff00"], "the art previews the group's colors"); + // The name the preview gives the group being edited picks that group in the list. + app.ui.dialog.as_mut().unwrap().fields.insert("groupName".into(), json!("Sunny")); + frame(&mut app, &ctx, 0.21, vec![], 0); + set(&mut app, "group", json!("Sunny")).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((&d.fields["group"], &d.fields[GROUP_LOADED], d.str("groupName")), (&json!("Warm"), &json!("Warm"), "Sunny".into())); + // A group the document has under that name is picked instead. + app.ui.dialog.as_mut().unwrap().fields.insert("groupName".into(), json!("Cool")); + frame(&mut app, &ctx, 0.22, vec![], 0); + set(&mut app, "group", json!("Cool")).unwrap(); + frame(&mut app, &ctx, 0.23, vec![], 0); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((&d.fields[GROUP_LOADED], super::rows(d).len()), (&json!("Cool"), 1)); + set(&mut app, GROUP_STORAGE, json!(false)).unwrap(); + frame(&mut app, &ctx, 0.3, vec![], 0); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields[GROUP_STORAGE], false); + } } diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index f4d2d6e85a..0d5bacd77c 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -1585,3 +1585,29 @@ fn row_context_menu_pick_from_swatches_and_limit_to_library() { assert_eq!(colors(h.state_mut()), 2, "Recolor Cancel restores the original artwork"); } } + +/// With the Color Groups list shown, the Color Picker opened from a row and closed with Cancel +/// leaves Recolor Artwork the size it was and where it was, in every frame. +#[test] +fn the_color_picker_leaves_the_dialog_in_place() { + use egui::accesskit::Role; + + let mut app = app(); + art(&mut app, &["#ff0000", "#0000ff"]); + let mut h = assign_harness(app, json!({})); + assert_eq!(field(h.state(), "groupStorage"), json!(true), "the list is shown"); + let window = egui::Id::unique(("dialog", "recolor")); + let rect = |h: &egui_kittest::Harness<'_, VectorcraftApp>| h.ctx.memory(|m| m.area_rect(window)); + let before = rect(&h).expect("dialog drawn"); + row_context_menu(&mut h, 1); + h.get_by_label(" Pick from Swatches").click(); + h.run_steps(3); + assert_eq!(h.state().ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("colorPicker")); + assert_eq!(rect(&h), Some(before), "the dialog keeps its size while the picker is open"); + h.get_by_role_and_label(Role::Button, "Cancel").click(); + for step in 0..4 { + h.run_steps(1); + assert_eq!(rect(&h), Some(before), "frame {step} after Cancel"); + } + assert_eq!(h.state().ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("recolor")); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index adac088a13..51a3f0e797 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -302,7 +302,11 @@ right-click menu has Remove Color too. The base color can't be removed. A remove 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 +`groupStorage` shows the Color Groups list (true when the dialog opens); setting `group` to a color group's name makes +it the group being edited, as opening on it does, and refuses a name no group has; `groupAction` (`save`, `new` or +`delete`) runs the list's Save Changes, New Color Group or Delete button on the next frame, or first on confirm (see +`docs/mcp.md`). 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. diff --git a/docs/mcp.md b/docs/mcp.md index 7aef0559ff..487f16794c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4772,9 +4772,13 @@ linked moves and the Color Theme Picker leave its new color as it is, and Save A from colors alone leave its new color out. With `limitTo`, a row's `tint` (a percentage, default 100) gives the art linked to the global or spot swatch its new color is that share of its tint; `tint` must be a number. `recolor.randomize` moves a row's `tint` with its new color and removes it from a color it changes, and moves a row's `model` with its new color. `swatch.editGroup {group, colors, rename?}` rewrites a colour group in one undo -step (art linked to its global swatches follows), and `recolor.apply` with `group` recolours the art and rewrites the +step (art linked to its global swatches follows); a `null` in `colors` removes the group's swatch at that place, and +given the group's own colors in order and no new name, it records no undo step. A color key (`recolor.colors`) that +names a swatch's color, rounded to the key's steps, counts as that color, and the swatch keeps its color unrounded. And `recolor.apply` with `group` recolours the art and rewrites the group together. A `null` in `groupColors` removes the group's swatch at that place, and the swatches after it keep -their colors and names; art linked to a removed global swatch keeps its color and is no longer linked to it. Art linked to one of the group's global swatches stays linked when the swatch is rewritten with its +their colors and names; art linked to a removed global swatch keeps its color and is no longer linked to it. `"keep"` in +`groupColors` leaves the swatch at that place its color, without the Global Adjust; past the group's swatches it adds +nothing, and it is refused for a swatch that is not a color. Art linked to one of the group's global swatches stays linked when the swatch is rewritten with its 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 @@ -4840,6 +4844,35 @@ become the `weights` field, which moves the rows' current colors and previews th beside the link button runs `swatch.newGroup` right away, as its own undo step: Save All Colors saves the new colors of the rows that are not excluded and hold current colors, in row order, and Save Prominent Colors saves the bar's colors in the bar's order. +The Recolor Artwork dialog lists the document's color groups on its right, or under the tabs in a window too narrow +for both ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). +The Show Color Groups button beside the tabs shows or hides the list (the `groupStorage` field, true when the dialog +opens). A click on a group, or `ui.dialog.set` of the `group` field to a group's name, makes it the group being +edited: with art the art is reduced again to a row per color of the group, which become the rows' new colors, and +without art the rows are the group's colors. A name that no group has is refused with `` no colour group `` ``, +and a `group` of null selects none. The buttons under the list are the `groupAction` field. Setting it checks the value, and the next frame of the +dialog runs it (OK with it set in the same request runs it first): +`save` (Save Changes) runs `swatch.editGroup` on the selected group with the colors OK would give it and the name in +`groupName`, `new` (New Color Group) saves the new colors of the rows that are not excluded as `swatch.newGroup` does, +and `delete` (Delete) runs `swatch.delete` on the selected group. Each is its own undo step, and the art keeps its +preview. An excluded row leaves its swatch its own color, with or without art, and an excluded row past the group's +swatches adds none. When several rows list a swatch's color, the swatch follows a row that gives the color a new color +before an excluded row or one that removes the color, as `recolor.apply` maps the art. When the art has colors of the group, +`save` and OK keep the group's swatches in order: a swatch whose color a row lists, or to which an earlier `save` gave +a row's new color, takes that row's new color (its own color when the row is +excluded), so art linked to the swatch takes the color its row shows, and every other swatch keeps its color. A row whose color was removed (`to: null`) and is not excluded +removes its swatch, and the colors added on the Edit tab follow the group's other colors, as at OK. After a `save` with art, the rows' new colors take the Global +Adjust and it goes back to 0%; when the save recolored linked art, the rows are read from the art again and a row with a +color the save gave the art is excluded, also when other art has that color, since a row recolors every use of its +colors alike. Until the rows or the Global Adjust change, OK changes the saved group only by the name +in `groupName`. `save` and `delete` with no group selected answer `` missing `group` ``. `save` on a group with a +swatch that is not a color (a gradient, pattern or None swatch) is refused, because the rows hold only the group's +colors. Any other value is refused. After a Delete without art, OK saves the rows as a new color group. + +```json +{"name":"answer_dialog","arguments":{"set":[{"field":"group","value":"Brights"},{"field":"groupAction","value":"save"}]}} +``` + ```json {"name":"run_command","arguments":{"command":"recolor.weigh","params":{"map":[{"from":["rgb 255 0 0","rgb 128 0 204"],"to":"#00ff00"},{"from":["rgb 0 0 255"],"to":"#ffff00"}],"weights":[1,1]}}} ``` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 1fc103d64a..3b576e874a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1767,6 +1767,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **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 brightness and hue wheel:** a button under the Edit tab's wheel tools switches the wheel between hue with saturation and hue with brightness; a marker's angle sets its hue, and its distance from the center sets the component the wheel shows ([Recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/recolor-options-overview.html), [archived help, Edit colors](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=144)). VectorCraft's own rules: brightness runs from black at the center to full at the edge, the segmented wheel's five rings become brightness steps, the slider under the wheel edits the component the wheel leaves out (Saturation on the brightness wheel), Add Color takes the hue and brightness clicked at the base color's saturation, the choice holds for both wheels while the dialog is open and the button is off for the color bars, and each opening shows hue and saturation. `wheelAxes` (`hueSaturation`, `hueBrightness`) is the dialog field. Tests: `the_brightness_and_hue_wheel_swaps_the_wheel_axis_and_the_slider`, `a_marker_on_the_brightness_wheel_sets_hue_and_brightness`, `the_add_color_tool_on_the_brightness_wheel_adds_the_brightness_clicked` and `the_segmented_brightness_wheel_has_24_hues_by_5_brightnesses` in `crates/ui-egui/src/tests/recolor.rs`, and `an_added_color_on_the_brightness_wheel_takes_the_base_colors_saturation` in `crates/ui-egui/src/dialogs/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 color groups list:** a list on the right of the dialog shows the document's color groups, and the Show Color Groups button beside the tabs shows or hides it. A click on a group makes it the group being edited, and the rows take its colors. Save Changes rewrites the selected group with the new colors, New Color Group saves them as a new group, and Delete removes the selected group; the Swatches panel shows each change ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). VectorCraft's own rules: when the art has colors of the group, Save Changes and OK keep the group's swatches in order, and a swatch no row lists keeps its color; an excluded row leaves its swatch its own color; after a save with art, the rows' new colors take the Global Adjust, which goes back to 0%. `group`, `groupStorage` and `groupAction` are the dialog fields. Tests: `the_color_groups_list_selects_saves_and_deletes_groups`, `a_group_picked_in_the_list_recolors_the_art` and the `saving_a_group_` tests in `crates/ui-egui/src/dialogs/recolor.rs`, and `edit_color_group_with_its_own_colors_records_no_undo_step` and `edit_color_group_with_its_own_color_keys_keeps_the_colors` in `crates/engine/src/tests/swatchcmds.rs`. - **Recolor Artwork New Row:** the Assign tab's New Row button adds a row with no current colors, so current colors can be moved into it and take its new color ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html), [Assign new colors to selected artworks](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/assign-new-colors-to-selected-artwork.html)). VectorCraft's own rules: the row goes above the first selected row (at the top when none is selected) with that row's new color and becomes the selection, and Merge with it as the first selected row moves the other rows' colors into it. The button needs selected art. An empty row recolors nothing, does not count toward Colors, adds no library swatch and gives a rewritten color group no color. While it is empty, Save All Colors and a new color group saved from colors alone leave its new color out, the Edit tab's wheel, bars and chips do not show it and its sliders edit the base color instead, the harmony rules and linked moves leave its new color as it is, and the Color Theme Picker gives it no color. Tests: `a_new_row_goes_above_the_selection_and_takes_merged_colors`, `an_empty_row_gives_the_group_no_color`, `an_empty_row_gives_a_new_group_no_color`, `an_empty_row_takes_no_harmony_or_wheel_color`, `theme_picks_leave_an_empty_row_out`, `save_all_colors_leaves_an_empty_row_out` and `colors_merged_into_a_new_row_take_its_new_color` in `crates/ui-egui/src/dialogs/recolor.rs`, `an_empty_row_recolors_nothing` and `an_empty_row_adds_no_swatch_and_no_group_color` in `crates/engine/src/tests/recolor.rs`. - **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.