From 6635cd77486ba4ac655f83ade33705d4d744faa9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 07:43:03 -0800 Subject: [PATCH 01/12] Recolor Artwork: a Color Groups list selects, saves, adds and deletes color groups The dialog lists the document's color groups on its right, or under the tabs in a narrow window, and the Show Color Groups button beside the tabs shows or hides the list. A click on a group 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; without art, the rows are the group's colors. Save Changes rewrites the selected group with the colors OK would give it and the name in the name field, New Color Group saves the rows' new colors as a new group, and Delete removes the selected group. Each is its own undo step, and the Swatches panel shows it. 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, and the others keep theirs. After a save with art the rows' new colors take the Global Adjust, which goes back to 0%, and when the save recolored linked art the rows are read from the art again. The dialog fields are group, groupStorage and groupAction (save, new or delete). A name no group has, a groupAction of another value, and save or delete with no group selected are refused. swatch.editGroup given a group's own colors in order and no new name records no undo step. --- crates/engine/src/cmd/swatch.rs | 8 + crates/engine/src/tests/swatchcmds.rs | 22 + crates/ui-egui/src/dialogs.rs | 6 +- crates/ui-egui/src/dialogs/recolor.rs | 806 +++++++++++++++++++++++++- docs/control-protocol.md | 5 +- docs/mcp.md | 27 +- docs/target-app-parity.md | 1 + 7 files changed, 856 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/cmd/swatch.rs b/crates/engine/src/cmd/swatch.rs index 3388b8344b..77d7aab06e 100644 --- a/crates/engine/src/cmd/swatch.rs +++ b/crates/engine/src/cmd/swatch.rs @@ -1291,6 +1291,14 @@ fn swatch_edit_group(s: &mut Session, p: &Value) -> Result { 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 rename = str_param(p, "rename"); + // 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)| *o == Some(*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/swatchcmds.rs b/crates/engine/src/tests/swatchcmds.rs index af059e5e33..88276a9e31 100644 --- a/crates/engine/src/tests/swatchcmds.rs +++ b/crates/engine/src/tests/swatchcmds.rs @@ -423,6 +423,28 @@ 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"); +} + #[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 4ac6da2fbe..55a4b9c79d 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -636,12 +636,16 @@ 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. +/// 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. 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); + } let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == export_for_screens::KIND) else { return Ok(()) }; match field { "exportPreset" => export_for_screens::preset_set(app), diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index d2bbeb3013..dee96dfe08 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -31,6 +31,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 @@ -48,8 +64,11 @@ //! `globalAdjust` in every slider mode), `display` (the Edit tab's `smooth`, `segmented` or `bars`; //! unset: `smooth`), `themePicker` (the Color Theme Picker is on), `themePicks` (its picks, as //! `recolor.pickTheme`'s `picks`; a new list recolors the rows), `weights` (one per row, as -//! `recolor.weigh`'s; a new list moves the rows' current colors toward them). Changing `colors`, a -//! preserve flag or `limitTo` reduces the rows again (and drops `weights`). +//! `recolor.weigh`'s; a new list moves the rows' current colors toward them), `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}; @@ -76,10 +95,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; @@ -162,6 +196,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, "__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). @@ -195,7 +230,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; @@ -387,7 +422,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(), @@ -395,12 +430,364 @@ 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. + d.fields.insert(THEME_PICKS.into(), json!([])); + d.fields.remove(SAVED_ROWS); + d.fields.remove(SAVED_COLORS); + 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(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. + let rest: Vec = + p["groupColors"].as_array().map(|a| a.iter().skip(rs.len()).map(|k| json!({"from": [k], "to": k})).collect()).unwrap_or_default(); + let mut colors = group_colors(app, d, rs.iter().chain(&rest)); + cancel_preview(app, d); + // With art in a color of the group, the group keeps its swatch order: a swatch whose color + // a row lists 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. + 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(); + let row_of = |k: &Value| rs.iter().find(|r| r["from"].as_array().is_some_and(|f| f.contains(k))); + if d.bool("__art") && own.iter().any(|k| row_of(k).is_some()) { + colors = own + .iter() + .map(|k| match row_of(k) { + Some(r) if !excluded(r) => group_colors(app, d, std::iter::once(r)).into_iter().next().unwrap_or_else(|| k.clone()), + _ => k.clone(), + }) + .collect(); + } + 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); + if d.bool("__art") { + // 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); + } + } + 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(()), + } +} + +/// 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. +fn reread_rows(app: &mut VectorcraftApp, d: &mut Dialog, old: &[Value], before: &[Vec]) { + 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(); + 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 old.iter().find(|o| o["from"].as_array().is_some_and(|f| f.contains(&first))).filter(|_| !from_save) { + Some(o) => { + r["to"] = o["to"].clone(); + r["exclude"] = json!(excluded(o)); + } + None => { + r["to"] = first; + r["exclude"] = json!(true); + } + } + } + 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, which OK gives it again with a new name. +const SAVED_COLORS: &str = "__savedColors"; + +/// Refuse a `groupAction` other than `save`, `new` or `delete`, and `save` or `delete` with no +/// group selected. +fn check_group_action(d: &Dialog, action: &Value) -> Result<(), String> { + match action.as_str() { + Some("new") => Ok(()), + Some("save" | "delete") if d.fields.get("group").is_some_and(Value::is_string) => Ok(()), + Some("save" | "delete") => Err("missing `group`".into()), + _ => Err(format!("`{GROUP_ACTION}` must be \"save\", \"new\" or \"delete\", not {action}")), + } +} + +/// 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(&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)); } } @@ -565,13 +952,25 @@ fn selection(d: &Dialog) -> Vec { /// colours: the rows' new colours, then (with art) the group's colours no row took. fn apply_params(d: &Dialog) -> Value { let rs = rows(d); - let group = d.fields.get("group").and_then(Value::as_str).map(|g| { - let rest = - d.fields.get("__assign").and_then(Value::as_array).filter(|_| d.bool("__art")).map_or(&[][..], |a| a.get(rs.len()..).unwrap_or_default()); - let colors: Vec<&Value> = rs.iter().map(|r| &r["to"]).chain(rest).collect(); + // The rows and Global Adjust unchanged since Save Changes: the group keeps its saved colors. + let saved = unchanged_since_save(d); + 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. + rename.as_ref()?; + d.fields.get(SAVED_COLORS).and_then(Value::as_array).map(|a| a.iter().collect())? + } else { + let rest = d + .fields + .get("__assign") + .and_then(Value::as_array) + .filter(|_| d.bool("__art")) + .map_or(&[][..], |a| a.get(rs.len()..).unwrap_or_default()); + rs.iter().map(|r| &r["to"]).chain(rest).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")}); @@ -586,10 +985,49 @@ fn apply_params(d: &Dialog) -> Value { p } +/// 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; + if !d.bool(GROUP_STORAGE) || !beside { + ui.vertical(|ui| { + ui.set_width(room.min(MAIN_W)); + main(app, ui, d); + if d.kind == KIND && d.bool(GROUP_STORAGE) { + ui.add_space(6.0); + group_storage(app, ui, d, 3.0 * GROUP_ROW_H); + } + }); + return false; + } + ui.horizontal_top(|ui| { + ui.vertical(|ui| { + ui.set_width((room - STORAGE_GAP - STORAGE_W).clamp(0.0, MAIN_W)); + main(app, ui, d); + }); + // A double-click on a new color turns the dialog into the Color Picker. + if d.kind == KIND { + ui.add_space(STORAGE_GAP); + ui.vertical(|ui| { + ui.set_width(STORAGE_W); + group_storage(app, ui, d, TAB_H - 30.0); + }); + } + }); + false +} + +fn main(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) { 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| { @@ -603,6 +1041,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) { @@ -634,8 +1076,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); @@ -651,7 +1095,6 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { if let Some(c) = pick.and_then(|i| Some((i, to_color(rows(d).get(i)?)?))) { *d = super::color_picker::over_recolor(d, c.1, c.0); } - false } /// `d` with row `i`'s new colour set to `c` (the Color Picker's OK), snapped to Limit to Library. @@ -670,9 +1113,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| !excluded(r))); return form::commit_preview(app, "swatch.newGroup", json!({"name": d.str("groupName"), "colors": colors, "keepModel": true})); @@ -2031,4 +2484,325 @@ 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"); + } + + /// 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); + } + + /// 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 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"); + } + + /// 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}"); + let sent: Vec = p["groupColors"].as_array().unwrap().iter().map(|k| to_color(&json!({"to": k})).unwrap().to_hex()).collect(); + assert_eq!(sent, saved, "OK renames the group with its saved 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/docs/control-protocol.md b/docs/control-protocol.md index e6f3621e8e..a4e8da06bd 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -290,7 +290,10 @@ luminosity}`, percent from -100 to 100, 0 by default). The dialog sends a non-ze colors; colors opened alone are saved as a group with the change. `display` sets how the Edit tab shows the new colors: `smooth` (the smooth wheel, also when unset; each opening starts there), `segmented` (a wheel of solid patches, 24 hues by 5 saturations, whose markers move as freely) or `bars` (a solid bar per recolored color in row order; a click -selects its row for the sliders and a drag moves the row without changing a color). Setting +selects its row for the sliders and a drag moves the row without changing a color). `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, diff --git a/docs/mcp.md b/docs/mcp.md index 8ca4121032..a043dd9178 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4337,7 +4337,8 @@ the others turn by the same hue). `limitTo` snaps new colours to a swatch librar `exclude: true` keeps its colours. 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); given the group's own colors in order and no new name, it records no +undo step. And `recolor.apply` with `group` recolours the art and rewrites the group together. Art linked to one of the group's global swatches stays linked when the swatch is rewritten with its 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 @@ -4404,6 +4405,30 @@ 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, 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. When the art has colors of the group, `save` 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), so art linked to the swatch takes the color +its row shows, and every other swatch keeps its color. 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` ``, and 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 f4424700be..41f49aed06 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1591,6 +1591,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Document Color Mode for effects and graphs:** File › Document Color Mode and `document.open {colorMode}` convert the colors of effects (Drop Shadow, Inner Glow, Outer Glow and the other effects with a color, on objects, their fills and strokes and in graphic styles) and the series paints and label styles that a graph keeps, so a graph drawn again from new data keeps the converted colors; File › Document Color Mode also converts the fill and stroke that new art takes. Undo restores the original new-art fill and stroke and Redo applies the conversion again. - **Recolor Artwork layout (#3416):** the Edit chip list uses the modal scroll helper and its actual remaining height; the tab's minimum-height space scrolls with the chips. `tests_recolor` covers 5/20/200/400 colors, window resizing, 100/125/150/200% UI scaling, scrolling to and editing the final chip, Preview, Cancel, Confirm and Undo, alongside the existing #1733 drag regressions. Scores and estimates unchanged. - **Recolor Artwork Edit displays:** buttons beside the Edit tab's wheel show the colors on a smooth color wheel, a segmented color wheel or as color bars ([Edit colors using Recolor Artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/edit-colors-using-edit-colors-dialog.html)). The segmented wheel draws 24 hues by 5 saturations as solid patches, and its markers move freely as on the smooth wheel. The bars show one solid bar per recolored color in row order: a click selects a bar for the color sliders, and a drag moves its row without changing a color ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). The dialog opens on the smooth wheel; `display` (`smooth`, `segmented`, `bars`) is the dialog field. `tests_recolor` covers switching, the dialog height, segmented dragging and Brightness, and bar selection, editing, reordering, scrolling, Preview, Cancel and OK. Scores and estimates unchanged. + - **Recolor Artwork 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)). `group`, `groupStorage` and `groupAction` are the dialog fields. Tests: `the_color_groups_list_selects_saves_and_deletes_groups` and `a_group_picked_in_the_list_recolors_the_art` in `crates/ui-egui/src/dialogs/recolor.rs`, and `edit_color_group_with_its_own_colors_records_no_undo_step` in `crates/engine/src/tests/swatchcmds.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. - **Working RGB numeric controls:** the Color panel and Color Picker read RGB, HSB, hex and Web Safe RGB values in the active working RGB space. Editing one RGB channel preserves the other native channels, including colors outside display sRGB. Regressions cover sRGB, Display P3, Wide Gamut RGB and ProPhoto RGB, picker initialization, native numeric round trips, and a slider click with one Undo step. Scores and estimates unchanged. From 828ac640d2ae8d2d2a711b553206849bdcc9d060 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 12:22:18 -0800 Subject: [PATCH 02/12] Recolor Artwork: Save Changes refuses a color group with a swatch that is not a color The rows hold only a group's colors, so a save would replace or remove its gradient or pattern swatches. Save Changes on such a group is refused when groupAction is set and when the button runs, checked on the document without the preview, which can rewrite the group. --- crates/ui-egui/src/dialogs/recolor.rs | 103 +++++++++++++++++++++++--- docs/mcp.md | 5 +- 2 files changed, 97 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index caf7229bee..dba2c1ac9c 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -527,7 +527,7 @@ fn select_group(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> /// `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(d, action)?; + 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); @@ -704,17 +704,30 @@ const SAVED_ROWS: &str = "__savedRows"; /// The selected group's colors after Save Changes, which OK gives it again with a new name. const SAVED_COLORS: &str = "__savedColors"; -/// Refuse a `groupAction` other than `save`, `new` or `delete`, and `save` or `delete` with no -/// group selected. -fn check_group_action(d: &Dialog, action: &Value) -> Result<(), String> { - match action.as_str() { - Some("new") => Ok(()), - Some("save" | "delete") if d.fields.get("group").is_some_and(Value::is_string) => Ok(()), - Some("save" | "delete") => Err("missing `group`".into()), +/// 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) { @@ -730,7 +743,7 @@ pub(super) fn field_set(app: &mut VectorcraftApp, field: &str) -> Result<(), Str let r = match field { "group" => select_group(app, &mut d), GROUP_ACTION => match d.fields.get(GROUP_ACTION).cloned() { - Some(a) => check_group_action(&d, &a), + 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")), @@ -2933,6 +2946,78 @@ mod tests { assert_eq!(group_hex(&app, "A"), Some(vec!["#ff0000".into(), "#00ff00".into()]), "other groups are left as they are"); } + /// 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 diff --git a/docs/mcp.md b/docs/mcp.md index 55e3362d35..f92618fae6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4599,8 +4599,9 @@ its row shows, and every other swatch keeps its color. After a `save` with art, 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` ``, and any other value is -refused. After a Delete without art, OK saves the rows as a new color group. +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"}]}} From 71734d417ece963770b96e4c6943b82d58d6646c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 12:31:14 -0800 Subject: [PATCH 03/12] Recolor Artwork: test that a save without art applies the Global Adjust once --- crates/ui-egui/src/dialogs/recolor.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index dba2c1ac9c..c7205d7910 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -3202,6 +3202,26 @@ mod tests { assert_eq!(sent, 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 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`. From 2b4845b070e431e51399068442a30b1868bc3533 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 13:31:48 -0800 Subject: [PATCH 04/12] Recolor Artwork: Save Changes matches hex rows, and theme picks apply after a group change Save Changes now finds the row for each swatch of the group as recolor.apply does: a row that lists the color exactly comes first, then a row whose "#rrggbb" entry has the same hex. A row listing "#0000ff" used to match no swatch, so the save rewrote the group from the rows in order and changed a swatch the art does not use. Reading the rows again after the save uses the same matching, so such a row keeps its new color. Picking a group in the Color Groups list also forgets the Color Theme Picker picks the rows last took, so the same picks made again give the new group's rows the palette, with or without art. --- crates/ui-egui/src/dialogs/recolor.rs | 105 +++++++++++++++++++++++++- 1 file changed, 102 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index c7205d7910..902cbd3a49 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -502,8 +502,10 @@ fn select_group(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> 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. + // 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); if art { @@ -572,7 +574,7 @@ fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Res .find(|(n, _)| group.as_deref() == Some(n.as_str())) .map(|g| g.1.iter().map(key).collect()) .unwrap_or_default(); - let row_of = |k: &Value| rs.iter().find(|r| r["from"].as_array().is_some_and(|f| f.contains(k))); + let row_of = |k: &Value| row_listing(&rs, k); if d.bool("__art") && own.iter().any(|k| row_of(k).is_some()) { colors = own .iter() @@ -628,7 +630,7 @@ fn reread_rows(app: &mut VectorcraftApp, d: &mut Dialog, old: &[Value], before: 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 old.iter().find(|o| o["from"].as_array().is_some_and(|f| f.contains(&first))).filter(|_| !from_save) { + match row_listing(old, &first).filter(|_| !from_save) { Some(o) => { r["to"] = o["to"].clone(); r["exclude"] = json!(excluded(o)); @@ -1028,6 +1030,23 @@ 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. +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), + }) + }) + }; + rows.iter().find(|r| lists(r, false)).or_else(|| rows.iter().find(|r| lists(r, 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 @@ -2173,6 +2192,19 @@ 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); + } + #[test] fn next_seed_holds_at_the_largest() { assert_eq!(next_seed(&Dialog::new("recolor", json!({}))), 1); @@ -2946,6 +2978,32 @@ mod tests { 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] @@ -3142,6 +3200,47 @@ mod tests { assert_eq!(fill_hex(&app, red), "#ff0000", "art linked to a swatch no row lists is left as it is"); } + /// 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] From 8bc2d29d45f858bcdc7a073acecaad6e37711eb7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 00:21:37 -0800 Subject: [PATCH 05/12] Recolor Artwork: Save Changes keeps colors added and removed on the Edit tab Save Changes now gives the group the same colors OK would: a color removed with the Remove Color tool removes its swatch, and a color added with the Add Color tool joins the group after its other colors, also when the art holds colors of the group. `swatch.editGroup` takes `null` in `colors` to remove the swatch at that place. After the save, the rows follow the saved group, so a later edit or OK does not remove or add a color a second time. --- crates/engine/src/cmd/swatch.rs | 21 ++- crates/engine/src/tests/swatchcmds.rs | 14 ++ crates/ui-egui/src/dialogs/recolor.rs | 183 ++++++++++++++++++++++++-- docs/mcp.md | 7 +- 4 files changed, 206 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/cmd/swatch.rs b/crates/engine/src/cmd/swatch.rs index 6f2137d6d6..088c7d74c5 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), 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 ), @@ -1317,29 +1317,36 @@ 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. 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 mut colors: Vec> = colors + .into_iter() + .enumerate() + .map(|(i, c)| c.map(|c| if old.get(i) == Some(&Some(c)) { c } else { 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"); // 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)| *o == Some(*c)) + && 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 colors: Vec> = colors.into_iter().map(Some).collect(); let e = s.edit("Edit Color Group", |d, _| rewrite_group(d, group, &colors, rename, C))?; e.defaults(s)?; Ok(json!({"name": e.name, "swatches": e.swatches, "relinked": e.relinked})) diff --git a/crates/engine/src/tests/swatchcmds.rs b/crates/engine/src/tests/swatchcmds.rs index 88276a9e31..03ab5fdbe2 100644 --- a/crates/engine/src/tests/swatchcmds.rs +++ b/crates/engine/src/tests/swatchcmds.rs @@ -445,6 +445,20 @@ fn edit_color_group_with_its_own_colors_records_no_undo_step() { assert_eq!(undo_len(&s), undo + 2, "a new name is a step"); } +#[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/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index cd3c41206d..42e42eb768 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -570,16 +570,18 @@ fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Res 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; a - // row made with New Row that holds no current colors gives the group no color. - let filled: Vec<&Value> = rs.iter().filter(|r| !r["from"].as_array().is_some_and(Vec::is_empty)).collect(); + // 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. + 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 mut colors = group_colors(app, d, filled.into_iter().chain(&rest)); + let mut colors: Vec = filled.iter().filter_map(|r| saved_color(app, d, r)).chain(group_colors(app, d, rest.iter())).collect(); cancel_preview(app, d); // With art in a color of the group, the group keeps its swatch order: a swatch whose color // a row lists 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 own: Vec = doc_groups(app) .into_iter() .find(|(n, _)| group.as_deref() == Some(n.as_str())) @@ -587,12 +589,14 @@ fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Res .unwrap_or_default(); let row_of = |k: &Value| row_listing(&rs, k); if d.bool("__art") && own.iter().any(|k| row_of(k).is_some()) { + let added = rs.iter().filter(|r| no_current(r) && is_added(r) && !excluded(r) && !r["to"].is_null()); colors = own .iter() .map(|k| match row_of(k) { - Some(r) if !excluded(r) => group_colors(app, d, std::iter::once(r)).into_iter().next().unwrap_or_else(|| k.clone()), + Some(r) if !excluded(r) => saved_color(app, d, r).unwrap_or_else(|| k.clone()), _ => k.clone(), }) + .chain(group_colors(app, d, added)) .collect(); } let before = art_colors(app); @@ -601,7 +605,38 @@ fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Res d.fields.insert("group".into(), name.clone()); d.fields.insert(GROUP_LOADED.into(), name.clone()); d.fields.insert("groupName".into(), name); - if d.bool("__art") { + // 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)); // 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); @@ -609,7 +644,7 @@ fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Res if art_colors(app) == before { mark_saved(app, d); } else { - reread_rows(app, d, &rs, &before); + reread_rows(app, d, &rs, &before, &gone); } } Ok(()) @@ -624,14 +659,21 @@ fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Res } } +/// 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. -fn reread_rows(app: &mut VectorcraftApp, d: &mut Dialog, old: &[Value], before: &[Vec]) { +/// 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(); d.fields.insert(THEME_PICKS.into(), json!([])); @@ -652,6 +694,7 @@ fn reread_rows(app: &mut VectorcraftApp, d: &mut Dialog, old: &[Value], before: } } } + 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); } @@ -979,6 +1022,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) @@ -3506,6 +3555,94 @@ mod tests { 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: Vec = apply_params(&d)["groupColors"].as_array().unwrap().iter().filter_map(color_value).map(|c| c.to_hex()).collect(); + 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. @@ -3627,6 +3764,34 @@ mod tests { assert_eq!(group_hex(&app, "Plain").unwrap(), saved, "OK does not darken the group again"); } + /// 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`. diff --git a/docs/mcp.md b/docs/mcp.md index 3d884d5c66..754de2aea3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4685,8 +4685,8 @@ 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); given the group's own colors in order and no new name, it records no -undo step. 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. 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 row's new color (the default without `groupColors` when the rows follow the group's order), so a later `swatch.edit` still @@ -4767,7 +4767,8 @@ dialog runs it (OK with it set in the same request runs it first): and `delete` (Delete) runs `swatch.delete` on the selected group. Each is its own undo step, and the art keeps its preview. When the art has colors of the group, `save` 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), so art linked to the swatch takes the color -its row shows, and every other swatch keeps its color. After a `save` with art, the rows' new colors take the Global +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 From 68685ab2f18d255bfbdf8e2310176579b70fa3ea Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 02:20:08 -0800 Subject: [PATCH 06/12] Recolor Artwork: Save Changes and OK keep each swatch with its row and excluded rows' colors - With art in some of the group's colors, a second Save Changes after another edit of a row kept the color the first save gave that row's swatch, and OK gave the group's colors by row order, which could overwrite a swatch no row lists. Both now match each swatch to its row, also through the color that row listed when an earlier save gave the swatch its color. - An excluded row leaves its swatch its own color at Save Changes and at OK, with or without art. `recolor.apply` takes "keep" in `groupColors` for a swatch that keeps its color without the Global Adjust. - `swatch.editGroup` given the color keys of the group's own colors keeps those colors unrounded and records no undo step. --- crates/engine/src/cmd/recolor.rs | 20 ++- crates/engine/src/cmd/swatch.rs | 15 +- crates/engine/src/tests/recolor.rs | 11 ++ crates/engine/src/tests/swatchcmds.rs | 29 ++++ crates/ui-egui/src/dialogs/recolor.rs | 188 ++++++++++++++++++++++---- docs/mcp.md | 14 +- docs/target-app-parity.md | 2 +- 7 files changed, 244 insertions(+), 35 deletions(-) diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index 566a87b22f..8cba055c9f 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 088c7d74c5..b66442a47f 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; a null removes the swatch at that place; 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 ), @@ -1326,13 +1326,22 @@ fn swatch_edit_group(s: &mut Session, p: &Value) -> Result { .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 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| if old.get(i) == Some(&Some(c)) { c } else { super::paint::new_color(s, p, c) })) + .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) { diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs index 8a950fcbb3..11c3418ff3 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 03ab5fdbe2..306d6b71ad 100644 --- a/crates/engine/src/tests/swatchcmds.rs +++ b/crates/engine/src/tests/swatchcmds.rs @@ -445,6 +445,35 @@ fn edit_color_group_with_its_own_colors_records_no_undo_step() { 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(); diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 42e42eb768..f3c0dde0bf 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -519,6 +519,7 @@ fn select_group(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> 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))); @@ -573,31 +574,48 @@ fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Res // 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. + // An excluded row leaves its swatch its own color. 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 mut colors: Vec = filled.iter().filter_map(|r| saved_color(app, d, r)).chain(group_colors(app, d, rest.iter())).collect(); + let assign: Vec = d.fields.get("__assign").and_then(Value::as_array).filter(|_| d.bool("__art")).cloned().unwrap_or_default(); + let mut colors: Vec = filled + .iter() + .enumerate() + .filter_map(|(i, r)| if excluded(r) { kept_color(&assign, i, r).cloned() } else { saved_color(app, d, r) }) + .chain(group_colors(app, d, rest.iter())) + .collect(); cancel_preview(app, d); - // With art in a color of the group, the group keeps its swatch order: a swatch whose color - // a row lists 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. + // 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 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(); - let row_of = |k: &Value| row_listing(&rs, k); - if d.bool("__art") && own.iter().any(|k| row_of(k).is_some()) { + 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()); - colors = own - .iter() - .map(|k| match row_of(k) { - Some(r) if !excluded(r) => saved_color(app, d, r).unwrap_or_else(|| k.clone()), + 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(), - }) - .chain(group_colors(app, d, added)) - .collect(); + }; + // 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"]}))?; @@ -637,6 +655,10 @@ fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Res .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); @@ -760,6 +782,27 @@ const SAVED_ROWS: &str = "__savedRows"; /// The selected group's colors after Save Changes, which OK gives it again with a new name. 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, with art), else the row's first +/// current color, which is its swatch's color without art. +fn kept_color<'a>(assign: &'a [Value], i: usize, row: &'a Value) -> Option<&'a Value> { + assign.get(i).or_else(|| row["from"].as_array().and_then(|f| f.first())) +} + /// 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. @@ -1057,12 +1100,18 @@ 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); // 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); @@ -1073,11 +1122,23 @@ fn apply_params(d: &Dialog) -> Value { } 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 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()); - took.into_iter().chain(rest).chain(added).collect() + // 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})) }); @@ -2439,14 +2500,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 @@ -3638,7 +3699,7 @@ mod tests { r["to"] = json!("rgb 10 10 10"); } d.fields.insert("rows".into(), Value::Array(rs)); - let colors: Vec = apply_params(&d)["groupColors"].as_array().unwrap().iter().filter_map(color_value).map(|c| c.to_hex()).collect(); + 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:?}"); } @@ -3715,6 +3776,87 @@ mod tests { 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"); + } + /// 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] diff --git a/docs/mcp.md b/docs/mcp.md index 754de2aea3..e3b19730e7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4686,9 +4686,12 @@ from colors alone leave its new color out. With `limitTo`, a row's `tint` (a per linked to the global or spot swatch its new color is that share of its tint; `tint` must be a number. `recolor.randomize` moves a row's `tint` with its new color and removes it from a color it changes, and moves a row's `model` with its new color. `swatch.editGroup {group, colors, rename?}` rewrites a colour group in one undo step (art linked to its global swatches follows); 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. And `recolor.apply` with `group` recolours the art and rewrites the +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 @@ -4765,9 +4768,10 @@ 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. When the art has colors of the group, `save` 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), 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 +preview. An excluded row leaves its swatch its own color, with or without 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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 50eeb91a22..a10d6876ac 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1676,7 +1676,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Recolor Artwork Edit displays:** buttons beside the Edit tab's wheel show the colors on a smooth color wheel, a segmented color wheel or as color bars ([Edit colors using Recolor Artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/edit-colors-using-edit-colors-dialog.html)). The segmented wheel draws 24 hues by 5 saturations as solid patches, and its markers move freely as on the smooth wheel. The bars show one solid bar per recolored color in row order: a click selects a bar for the color sliders, and a drag moves its row without changing a color ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). The dialog opens on the smooth wheel; `display` (`smooth`, `segmented`, `bars`) is the dialog field. `tests_recolor` covers switching, the dialog height, segmented dragging and Brightness, and bar selection, editing, reordering, scrolling, Preview, Cancel and OK. Scores and estimates unchanged. - **Recolor Artwork Add Color and Remove Color tools:** under the display buttons beside the Edit tab's wheel, the Add Color tool adds the color clicked on either wheel to the color group, and the Remove Color tool removes the color whose marker is clicked; a color bar's right-click menu has Remove Color, and the base color can't be removed ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html), [Edit swatch groups using the color wheel](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/edit-color-groups-using-the-color-wheel.html)). An added color is a new row with no current colors and `added: true`; unlike a row made with New Row, it adds its new color to a rewritten color group, after the group's other colors. VectorCraft's own rules: an added color takes the base color's brightness, and with art or a group a removed color's row stays with its current colors and no new color, so that art keeps its colors and the group's swatch at that place is removed. `wheelTool` (`add`, `remove`) is the dialog field. Tests: `the_add_color_tool_adds_a_row_with_no_current_colors`, `an_added_color_joins_the_color_group`, `the_remove_color_tool_removes_a_marker_but_not_the_base_colors` and `a_color_bars_menu_removes_its_color` in `crates/ui-egui/src/tests/recolor.rs`, `apply_params_give_the_group_added_colors_and_keep_its_other_colors` in `crates/ui-egui/src/dialogs/recolor.rs`, and `an_added_empty_row_gives_the_group_its_color_after_the_others` in `crates/engine/src/tests/recolor.rs`. Scores and estimates unchanged. - **Recolor Artwork Find:** the Assign tab's Find button finds the colors of the selected rows in the art ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)): while it is on, their art shows as the preview shows it and the rest of the selected art shows dimmed, until a second click ([archived help, Recolor Artwork](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=149)). VectorCraft's own rules: a dimmed color is a 25% tint of its current color (or the nearest lighter tint when that one is a color a selected row lists), a color a selected row also lists is not dimmed, and Find records no undo step. `findColors` is the dialog field. Tests: `find_dims_the_colors_of_the_rows_not_selected` and `find_shows_the_selected_rows_art_and_dims_the_rest` in `crates/ui-egui/src/dialogs/recolor.rs`. Scores and estimates unchanged. - - **Recolor Artwork 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 keeps the group's swatches in order, and a swatch no row lists keeps its 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` in `crates/engine/src/tests/swatchcmds.rs`. + - **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. From 1121d6fff4d220c82aabcdc35727dc438494e256 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 02:50:06 -0800 Subject: [PATCH 07/12] Recolor Artwork: a second Save Changes keeps saved colors and finds rows read again Without art, a row excluded after Save Changes gave its swatch a new color now leaves the swatch that saved color, as OK does, instead of giving it back the row's old current color. With art linked to the group, after a save reads the rows from the art again, a swatch whose new color the save gave the art is found by that color, so a later edit of its row reaches it at Save Changes and OK. --- crates/ui-egui/src/dialogs/recolor.rs | 96 ++++++++++++++++++++++++--- 1 file changed, 86 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index f3c0dde0bf..32d5492f56 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -574,27 +574,30 @@ fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Res // 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. - // An excluded row leaves its swatch its own 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 = d.fields.get("__assign").and_then(Value::as_array).filter(|_| d.bool("__art")).cloned().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) { kept_color(&assign, i, r).cloned() } else { saved_color(app, d, r) }) .chain(group_colors(app, d, rest.iter())) .collect(); - cancel_preview(app, d); // 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 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(); 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) { @@ -698,6 +701,18 @@ fn saved_color(app: &VectorcraftApp, d: &Dialog, row: &Value) -> Option { 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); @@ -797,8 +812,8 @@ fn swatch_row<'a>(d: &Dialog, rs: &'a [Value], own: &[Value], i: usize) -> Optio } /// 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, with art), else the row's first -/// current color, which is its swatch's color without art. +/// colors: the swatch's own color in `assign` (the group's colors), else the row's first current +/// color. fn kept_color<'a>(assign: &'a [Value], i: usize, row: &'a Value) -> Option<&'a Value> { assign.get(i).or_else(|| row["from"].as_array().and_then(|f| f.first())) } @@ -3857,6 +3872,67 @@ mod tests { assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ff0000".into(), "#0000ff".into()]), "so does Save Changes"); } + /// 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] From 86ed096f82f4c4f4a740d9e94bd73a470dc546c8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 12:42:28 -0800 Subject: [PATCH 08/12] Recolor Artwork: the Color Picker leaves the dialog in place with the Color Groups list shown A double-click on a new color or Pick from Swatches turned the dialog into the Color Picker before the Color Groups list was drawn, so that frame drew the window without the list. The window then remembered the narrower size, and when the picker closed it came back off center for one frame and moved 95 points to the side. A right-click on a row in that frame missed the row. The picker now opens after the list is drawn, and the window keeps its size and position. A new test checks the window's rectangle while the picker is open and in each frame after its Cancel. --- crates/ui-egui/src/dialogs/recolor.rs | 43 ++++++++++++++------------- crates/ui-egui/src/tests/recolor.rs | 26 ++++++++++++++++ 2 files changed, 49 insertions(+), 20 deletions(-) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index f44b1a166b..01c621bebf 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -1296,35 +1296,43 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { 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)); - main(app, ui, d); - if d.kind == KIND && d.bool(GROUP_STORAGE) { + 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); } }); - return false; - } - ui.horizontal_top(|ui| { - ui.vertical(|ui| { - ui.set_width((room - STORAGE_GAP - STORAGE_W).clamp(0.0, MAIN_W)); - main(app, ui, d); - }); - // A double-click on a new color turns the dialog into the Color Picker. - if d.kind == KIND { + } 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 } -fn main(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) { +/// 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); @@ -1403,12 +1411,7 @@ fn main(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) { 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); - } + pick } /// `d` with row `i`'s new colour set to `c` (the Color Picker's OK), snapped to Limit to Library. 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")); +} From 63e7bf0719b2cbc29aeed3edf73ec9556408be70 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 13:15:05 -0800 Subject: [PATCH 09/12] Recolor Artwork: OK with a new name after Save Changes keeps the group's exact colors After Save Changes, OK with only a new name sent the group's saved colors as color keys, which hold hundredths of a unit. A swatch with finer components, such as a CMYK swatch no row lists, was rewritten with the rounded color. OK now sends `"keep"` for each saved swatch, so the rename leaves every color as it is. --- crates/ui-egui/src/dialogs/recolor.rs | 53 ++++++++++++++++++++++++--- 1 file changed, 48 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 01c621bebf..47a128cc8b 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -799,7 +799,8 @@ fn art_colors(app: &VectorcraftApp) -> Vec> { /// 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, which OK gives it again with a new name. +/// 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 @@ -1136,9 +1137,9 @@ fn apply_params(d: &Dialog) -> Value { let name = d.str("groupName"); let rename = (!name.trim().is_empty() && name != g).then_some(name); let colors: Vec<&Value> = if saved { - // Only a new name changes the group. + // 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().collect())? + 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. @@ -3664,6 +3665,46 @@ mod tests { 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. @@ -4062,8 +4103,10 @@ mod tests { d.fields.insert("groupName".into(), json!("Dark")); let p = apply_params(app.ui.dialog.as_ref().unwrap()); assert!(p.get("globalAdjust").is_none(), "{p}"); - let sent: Vec = p["groupColors"].as_array().unwrap().iter().map(|k| to_color(&json!({"to": k})).unwrap().to_hex()).collect(); - assert_eq!(sent, saved, "OK renames the group with its saved colors"); + 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 From 1061d645ea2f761cb825ef29aa96c41730ed6418 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 13:26:54 -0800 Subject: [PATCH 10/12] Recolor Artwork: Save Changes snaps the group's colors to Limit to Library With Limit to Library set and the Global Adjust at 0%, Save Changes and New Color Group gave a group each row's new color as it was, while OK gives the library's nearest color. A row set without being snapped, for example through `ui.dialog.set`, saved a color outside the library. Both now give the group the library's nearest color, as OK does. --- crates/ui-egui/src/dialogs/recolor.rs | 32 ++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 47a128cc8b..e516ba8cc7 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -432,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)))) @@ -4129,6 +4129,36 @@ mod tests { 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] From 7c60eb472fd780bbf64d483e36b01a89d3ceed71 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 16:14:53 -0800 Subject: [PATCH 11/12] Recolor Artwork: Save Changes adds no color for an excluded row past the group's swatches An excluded row with no swatch of the group gave Save Changes its current color, which joined the group, while OK adds nothing for it. It now sends a null in that place, which adds no swatch. The row found for a swatch's color is now a row that gives the color a new color, before an excluded row or one that removes the color, as recolor.apply maps the color with that row. Save Changes and OK no longer remove a swatch, or keep its color, while the art takes another row's new color. --- crates/ui-egui/src/dialogs/recolor.rs | 65 ++++++++++++++++++++++++--- 1 file changed, 58 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index e516ba8cc7..ff57bd6817 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -596,7 +596,7 @@ fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Res let mut colors: Vec = filled .iter() .enumerate() - .filter_map(|(i, r)| if excluded(r) { kept_color(&assign, i, r).cloned() } else { saved_color(app, d, r) }) + .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 @@ -818,10 +818,10 @@ fn swatch_row<'a>(d: &Dialog, rs: &'a [Value], own: &[Value], i: usize) -> Optio } /// 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 the row's first current -/// color. -fn kept_color<'a>(assign: &'a [Value], i: usize, row: &'a Value) -> Option<&'a Value> { - assign.get(i).or_else(|| row["from"].as_array().and_then(|f| f.first())) +/// 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 @@ -1201,7 +1201,9 @@ 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. +/// "#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()); @@ -1213,7 +1215,8 @@ fn row_listing<'a>(rows: &'a [Value], k: &Value) -> Option<&'a Value> { }) }) }; - rows.iter().find(|r| lists(r, false)).or_else(|| rows.iter().find(|r| lists(r, true))) + 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 @@ -2657,6 +2660,24 @@ mod tests { 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); @@ -4017,6 +4038,36 @@ mod tests { 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] From 5fa4d879dd5377b5779001145b142694ea476fb9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 16:18:59 -0800 Subject: [PATCH 12/12] MCP: describe Save Changes for excluded rows past the swatches and rows that share a color --- docs/mcp.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/mcp.md b/docs/mcp.md index 872a9257ce..95d8027b31 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4810,7 +4810,9 @@ 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. When the art has colors of the group, +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