diff --git a/crates/engine/src/cmd/webexport.rs b/crates/engine/src/cmd/webexport.rs index 498982a7f9..a38d584966 100644 --- a/crates/engine/src/cmd/webexport.rs +++ b/crates/engine/src/cmd/webexport.rs @@ -340,11 +340,16 @@ pub struct ColorTable { type Shift = ([u8; 3], [u8; 3]); /// The most colours a colour table list holds. -const MAX_TABLE: usize = 256; +pub const MAX_TABLE: usize = 256; /// The error for a deletion that would leave the color table no color for the pixels. pub const KEEP_ONE: &str = "colorTable.deleted: at least one color has to stay in the color table"; +/// The error for a colour table list `what` (`colorTable.`) with more than [`MAX_TABLE`] colours. +pub fn too_many(what: &str) -> String { + format!("colorTable.{what}: at most {MAX_TABLE} colours") +} + impl ColorTable { /// Whether the table is a Custom one: a color was deleted or the palette is fixed. pub fn is_custom(&self) -> bool { @@ -353,7 +358,7 @@ impl ColorTable { fn colors(list: &[String], what: &str) -> std::result::Result, String> { if list.len() > MAX_TABLE { - return Err(format!("colorTable.{what}: at most {MAX_TABLE} colours")); + return Err(too_many(what)); } list.iter().map(|h| Self::rgb(h).ok_or_else(|| format!("colorTable.{what}: `{h}` is not a colour such as \"#ff8800\""))).collect() } diff --git a/crates/ui-egui/src/dialogs/save_for_web.rs b/crates/ui-egui/src/dialogs/save_for_web.rs index 7376973d6f..120025c416 100644 --- a/crates/ui-egui/src/dialogs/save_for_web.rs +++ b/crates/ui-egui/src/dialogs/save_for_web.rs @@ -154,6 +154,8 @@ fn settings_of(app: &VectorcraftApp, d: &Dialog) -> Result fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let mut d = d.clone(); apply_preset(app, &mut d)?; + // A Color Picker OK the dialog has not drawn since still shifts its color. + take_shift(&mut d)?; let p = params(&d); // Done remembers the settings; Save… remembers them and writes the files. app.run("webExport.settings", p.clone())?; @@ -568,7 +570,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { { app.status(e); } - take_shift(d); + if let Err(e) = take_shift(d) { + app.status(e); + } let settings = settings_of(app, d); let mut browser = false; // In a window too narrow for both, the panes are narrower, so the settings beside them and the @@ -1447,22 +1451,29 @@ pub(super) fn edit_color(d: &mut Dialog, source: &str, start: &str) { *d = super::color_picker::over_effect(d, SHIFT_TO, c); } -/// Back from the Color Picker: its OK's color shifts the color it was opened for. -fn take_shift(d: &mut Dialog) { +/// Back from the Color Picker: its OK's color shifts the color it was opened for. An error is the +/// one [`shift_color`] gives. +fn take_shift(d: &mut Dialog) -> Result<(), String> { let source = d.fields.remove("__shiftSource"); if let (Some(to), Some(source)) = (d.fields.remove(SHIFT_TO), source) && let (Some(to), Some(source)) = (to.as_str(), source.as_str()) { - shift_color(d, source, to); + return shift_color(d, source, to); } + Ok(()) } /// Shift the source color `source` to `to` (`colorTable.shifted`), wherever it is in the image; it /// is no longer web-shifted. Picking the source color itself takes the shift away. The color -/// becomes the selection. Nothing changes when either is not a color. -pub(super) fn shift_color(d: &mut Dialog, source: &str, to: &str) { +/// becomes the selection. Nothing changes when either is not a color, and a new source when 256 +/// colors are already shifted is an error that changes nothing. +pub(super) fn shift_color(d: &mut Dialog, source: &str, to: &str) -> Result<(), String> { let hex = |h: &str| vectorcraft_color::Color::from_hex(h).map(|c| c.to_hex()); - let (Some(source), Some(to)) = (hex(source), hex(to)) else { return }; + let (Some(source), Some(to)) = (hex(source), hex(to)) else { return Ok(()) }; + let map = shifts(d); + if to != source && map.len() >= webexport::MAX_TABLE && !map.keys().any(|k| same_color(k, &source)) { + return Err(webexport::too_many("shifted")); + } unshift(d, &source); if to != source { let mut map = shifts(d); @@ -1472,6 +1483,7 @@ pub(super) fn shift_color(d: &mut Dialog, source: &str, to: &str) { toggle(d, "webShift", &source, false); d.fields.insert("__colors".into(), json!([source])); d.fields.insert("__color".into(), json!(source)); + Ok(()) } /// The `colorTable.shifted` field. @@ -1479,11 +1491,21 @@ fn shifts(d: &Dialog) -> Map { d.fields.get("colorTable").and_then(|t| t.get("shifted")).and_then(Value::as_object).cloned().unwrap_or_default() } -/// Take the shift by hand of the source color `source` away. +/// Whether `a` and `b` name one color, however each is written; text that is not a color matches +/// the same text in any case. +fn same_color(a: &str, b: &str) -> bool { + let rgb = |h: &str| vectorcraft_color::Color::from_hex(h).map(|c| c.to_hex()); + match (rgb(a), rgb(b)) { + (Some(a), Some(b)) => a == b, + _ => a.eq_ignore_ascii_case(b), + } +} + +/// Take the shift by hand of the source color `source` away: every key that names that color. pub(super) fn unshift(d: &mut Dialog, source: &str) { let mut map = shifts(d); let before = map.len(); - map.retain(|k, _| !k.eq_ignore_ascii_case(source)); + map.retain(|k, _| !same_color(k, source)); if map.len() != before { set_table(d, "shifted", Value::Object(map)); } @@ -1495,10 +1517,10 @@ pub(super) fn unshift_all_colors(d: &mut Dialog) { set_table(d, "webShift", json!([])); } -/// Add `color` to the colour table's `list`, or take it out. +/// Add `color` to the colour table's `list`, or take it out (every entry that names that color). pub(super) fn toggle(d: &mut Dialog, list: &str, color: &str, add: bool) { let mut v: Vec = d.fields.get("colorTable").and_then(|t| t.get(list)).and_then(Value::as_array).cloned().unwrap_or_default(); - v.retain(|c| !c.as_str().is_some_and(|c| c.eq_ignore_ascii_case(color))); + v.retain(|c| !c.as_str().is_some_and(|c| same_color(c, color))); if add { v.push(json!(color.to_ascii_lowercase())); } diff --git a/crates/ui-egui/src/dialogs/tests_save_for_web.rs b/crates/ui-egui/src/dialogs/tests_save_for_web.rs index 63ed3e2ded..b93c36def8 100644 --- a/crates/ui-egui/src/dialogs/tests_save_for_web.rs +++ b/crates/ui-egui/src/dialogs/tests_save_for_web.rs @@ -824,26 +824,58 @@ fn delete_color_skips_selected_colors_the_table_does_not_show() { fn colour_table_shift_unshift_and_unshift_all() { let mut d = Dialog::new(save_for_web::KIND, json!({})); save_for_web::toggle(&mut d, "webShift", "#123456", true); - save_for_web::shift_color(&mut d, "#123456", "#FF8800"); + save_for_web::shift_color(&mut d, "#123456", "#FF8800").unwrap(); assert_eq!(d.fields["colorTable"], json!({"webShift": [], "shifted": {"#123456": "#ff8800"}})); assert_eq!(save_for_web::selection(&d), ["#123456"]); // Not a color: nothing changes. let before = d.fields.clone(); - save_for_web::shift_color(&mut d, "nope", "#000000"); - save_for_web::shift_color(&mut d, "#123456", "nope"); + save_for_web::shift_color(&mut d, "nope", "#000000").unwrap(); + save_for_web::shift_color(&mut d, "#123456", "nope").unwrap(); assert_eq!(d.fields, before); - save_for_web::shift_color(&mut d, "#ABCDEF", "#00ff00"); - save_for_web::shift_color(&mut d, "#123456", "#123456"); + save_for_web::shift_color(&mut d, "#ABCDEF", "#00ff00").unwrap(); + save_for_web::shift_color(&mut d, "#123456", "#123456").unwrap(); assert_eq!(d.fields["colorTable"]["shifted"], json!({"#abcdef": "#00ff00"})); save_for_web::toggle(&mut d, "webShift", "#222222", true); save_for_web::unshift_all_colors(&mut d); assert_eq!((&d.fields["colorTable"]["shifted"], &d.fields["colorTable"]["webShift"]), (&json!({}), &json!([]))); let order: Vec = ["#000000", "#222222"].map(String::from).to_vec(); - save_for_web::shift_color(&mut d, "#222222", "#ffffff"); + save_for_web::shift_color(&mut d, "#222222", "#ffffff").unwrap(); save_for_web::delete_colors(&mut d, &order).unwrap(); assert_eq!((&d.fields["colorTable"]["shifted"], &d.fields["colorTable"]["deleted"]), (&json!({}), &json!(["#222222"]))); } +/// A key or list entry written another way (`#F00`, upper case) still names its color: a new shift +/// of that color replaces it, taking the shift away removes it, and a web shift of it is taken away. +#[test] +fn colour_table_shift_matches_a_color_written_another_way() { + let mut d = Dialog::new(save_for_web::KIND, json!({"colorTable": {"shifted": {"#F00": "#00ff00", "nope": "#000000"}, "webShift": ["#0000FF"]}})); + save_for_web::shift_color(&mut d, "#ff0000", "#123456").unwrap(); + assert_eq!(d.fields["colorTable"]["shifted"], json!({"#ff0000": "#123456", "nope": "#000000"})); + save_for_web::shift_color(&mut d, "#0000ff", "#654321").unwrap(); + assert_eq!(d.fields["colorTable"]["webShift"], json!([])); + save_for_web::unshift(&mut d, "#FF0000"); + assert_eq!(d.fields["colorTable"]["shifted"], json!({"#0000ff": "#654321", "nope": "#000000"})); +} + +/// With 256 colors shifted, shifting another color is refused and changes nothing; a shifted color +/// can still be shifted again or have its shift taken away. +#[test] +fn colour_table_shift_holds_at_most_256_colors() { + let full: serde_json::Map = (0..256).map(|i| (format!("#{i:06x}"), json!("#ffffff"))).collect(); + let mut d = Dialog::new(save_for_web::KIND, json!({"colorTable": {"shifted": full}, "__color": "#000001", "__colors": ["#000001"]})); + let before = d.fields.clone(); + let e = save_for_web::shift_color(&mut d, "#123456", "#000000").unwrap_err(); + assert_eq!((e.as_str(), &d.fields), ("colorTable.shifted: at most 256 colours", &before)); + save_for_web::shift_color(&mut d, "#000005", "#000000").unwrap(); + assert_eq!( + (d.fields["colorTable"]["shifted"]["#000005"].as_str(), d.fields["colorTable"]["shifted"].as_object().map(|m| m.len())), + (Some("#000000"), Some(256)) + ); + save_for_web::shift_color(&mut d, "#000005", "#000005").unwrap(); + save_for_web::shift_color(&mut d, "#123456", "#000000").unwrap(); + assert_eq!(d.fields["colorTable"]["shifted"]["#123456"], "#000000"); +} + /// One frame of `app` in `ctx`, 50 ms after the last. fn tick(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) { let time = ctx.input(|i| i.time) + 0.05; @@ -943,6 +975,28 @@ fn dialog_set_edit_color_opens_the_color_picker() { assert_eq!((kind(&app), shifted), (Some(save_for_web::KIND), Some(json!({"#0000ff": "#00ff00"})))); } +/// Done right after the Color Picker's OK, before the dialog draws again, remembers the shift. +#[test] +fn done_right_after_the_color_picker_remembers_the_shift() { + let dir = vectorcraft_testkit::temp_dir("sfw-shift-done"); + let (mut app, _) = app(&dir, false); + app.run("shape.rectangle", json!({"x": 40, "y": 0, "width": 20, "height": 40})).unwrap(); + app.run("paint.setFill", json!({"color": "#0000ff"})).unwrap(); + app.run("file.saveForWeb", json!({})).unwrap(); + set(&mut app, "format", json!("gif")); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + set(&mut app, "__editColor", json!("#0000ff")); + tick(&mut app, &ctx, vec![]); + assert_eq!(picker_color(&app).as_deref(), Some("#0000ff")); + set(&mut app, "color", json!("#00ff00")); + confirm(&mut app).unwrap(); + set(&mut app, "discard", json!(true)); + confirm(&mut app).unwrap(); + let remembered = app.session.last_web_settings().color_table; + assert_eq!(remembered.shifted.get("#0000ff").map(String::as_str), Some("#00ff00")); +} + /// Lock, Transparent and Web Shift are off while the selected color (`__color`) is one the table /// no longer shows, so a click adds it to no list; with a color the table shows, Lock locks it. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 85247a0c87..af2a1514ff 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10567,7 +10567,9 @@ of a color shifted by hand. More than 256 entries, a key or value that is not a included), and two keys that name one color are errors. Presets and `webExport.settings` keep the map. In the dialog a double-click on an opaque swatch opens the Color Picker on the color shown (on the source color for a color already shifted; an agent sets `__editColor: "#source"`). Its OK shifts the color (picking the source color takes the shift away), and Cancel -leaves the table as it was. A shifted swatch shows the source color at its upper left and the new color at its lower +leaves the table as it was. An OK that would shift a 257th color changes nothing, and the status bar shows the +limit. A key written another way (`#F00`) still names its color, so a new shift or Unshift replaces it. Done or Save +right after the OK keeps the shift. A shifted swatch shows the source color at its upper left and the new color at its lower right, with the lock mark, and Lock stays on until the color is unshifted. Web Shift replaces a shift by hand, and Unshift All Colors in the table's menu clears `shifted` and `webShift`. Only Web Colors in the picker starts off.