From c51fc47b30b1a3dc429fa6c069f19b77b95dd2fc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 21:14:38 -0800 Subject: [PATCH 1/5] Save for Web: a color shift survives Done right after the Color Picker, stops at 256 colors and matches keys written another way - Done or Save right after the Color Picker's OK, before the dialog draws again, now applies the picked shift, so the saved and remembered settings keep it. - Shifting a 257th color now changes nothing and the status bar shows the engine's limit; shifting an already shifted color again, or taking a shift away, still works. - Unshift, a new shift and the Lock, Transparent and Web Shift lists compare colors rather than text, so a key such as `#F00` is replaced instead of left beside `#ff0000`. Docs: docs/mcp.md. --- crates/engine/src/cmd/webexport.rs | 9 ++- crates/ui-egui/src/dialogs/save_for_web.rs | 44 +++++++++---- .../ui-egui/src/dialogs/tests_save_for_web.rs | 66 +++++++++++++++++-- docs/mcp.md | 4 +- 4 files changed, 103 insertions(+), 20 deletions(-) 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. From c0f91bc8203dbdce1ffd840065d8c489b741aa7f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 09:17:09 -0800 Subject: [PATCH 2/5] Save for Web: the color table's selection matches a color written another way - A selected color or list entry written another way (`#00F` for `#0000ff`) now names its table color: Lock, Transparent, Web Shift and Delete Color act on it and write it as the table does, and the ring and button labels follow it. - Delete Color compares the table's lists as colors, so deleting the only color left is refused when the selection or a list is written another way, and a deleted color is taken out of the Lock, Transparent and Web Shift lists however they write it. - A Ctrl-click on a selected color takes out every selection entry that names it. - A spelling with alpha (`#rrggbbaa`) names no table color, as the engine reads the table. Docs: docs/mcp.md. --- crates/ui-egui/src/dialogs/save_for_web.rs | 66 ++++++++++------ .../ui-egui/src/dialogs/tests_save_for_web.rs | 76 +++++++++++++++++++ docs/mcp.md | 4 +- 3 files changed, 123 insertions(+), 23 deletions(-) diff --git a/crates/ui-egui/src/dialogs/save_for_web.rs b/crates/ui-egui/src/dialogs/save_for_web.rs index 120025c416..4ba055b558 100644 --- a/crates/ui-egui/src/dialogs/save_for_web.rs +++ b/crates/ui-egui/src/dialogs/save_for_web.rs @@ -1219,7 +1219,7 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) -> Re } // The transparent entry itself isn't a colour to edit. let pickable = !c.transparent || *mapped; - let ringed = pickable && picked.iter().any(|h| h.eq_ignore_ascii_case(&hex(c.source))); + let ringed = pickable && picked.iter().any(|h| same_color(h, &hex(c.source))); p.rect_stroke(r, 0.0, egui::Stroke::new(if ringed { 2.0 } else { 1.0 }, if ringed { t.accent } else { t.border }), egui::StrokeKind::Outside); if !pickable { continue; @@ -1242,14 +1242,17 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) -> Re d.fields.insert("__editColor".into(), json!(source)); d.fields.insert("__editStart".into(), json!(start)); } - let shifted = |c: &str| table.shifted.keys().any(|k| k.eq_ignore_ascii_case(c)); + let shifted = |c: &str| table.shifted.keys().any(|k| same_color(k, c)); // The colors the table shows, by source: Lock, Transparent, Web Shift and Delete Color act only // on these. let palette: Vec = shot.colors.iter().filter(|c| !c.transparent).map(|c| hex(c.source)).chain(shot.mapped.iter().map(|c| hex(*c))).collect(); - let shown = palette.iter().any(|p| p.eq_ignore_ascii_case(&selected)); + // The selected color as the table writes it; the buttons act on that spelling. + let shown_as = palette.iter().find(|p| same_color(p, &selected)).map(|p| p.to_ascii_lowercase()); + let shown = shown_as.is_some(); + let selected = shown_as.unwrap_or(selected); ui.add_space(4.0); - let on = |list: &[String]| list.iter().any(|h| h.eq_ignore_ascii_case(&selected)); + let on = |list: &[String]| list.iter().any(|h| same_color(h, &selected)); ui.horizontal(|ui| { ui.add_enabled_ui(shown, |ui| { for (list, on_label, off_label) in [ @@ -1320,9 +1323,18 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) -> Re Ok(()) } -/// The selected colors (by source) that `palette`, the colors the table shows, holds. +/// The selected colors (by source) that `palette`, the colors the table shows, holds, each as +/// `palette` writes it, once. pub(super) fn selected_in(d: &Dialog, palette: &[String]) -> Vec { - selection(d).into_iter().filter(|c| palette.iter().any(|p| p.eq_ignore_ascii_case(c))).collect() + let mut out: Vec = Vec::new(); + for c in selection(d) { + if let Some(p) = palette.iter().find(|p| same_color(p, &c)).map(|p| p.to_ascii_lowercase()) + && !out.contains(&p) + { + out.push(p); + } + } + out } /// The colour table's selected colors, by source: `__colors`, else `__color`. @@ -1342,7 +1354,7 @@ pub(super) fn selection(d: &Dialog) -> Vec { /// or taken out, and the anchor moves to the last color left in the selection. pub(super) fn pick(d: &mut Dialog, order: &[String], color: &str, shift: bool, command: bool) { let color = color.to_ascii_lowercase(); - let at = |c: &str| order.iter().position(|o| o.eq_ignore_ascii_case(c)); + let at = |c: &str| order.iter().position(|o| same_color(o, c)); if shift && let (Some(a), Some(b)) = (at(&d.str("__color")), at(&color)) { let range: Vec = order[a.min(b)..=a.max(b)].iter().map(|c| c.to_ascii_lowercase()).collect(); d.fields.insert("__colors".into(), json!(range)); @@ -1350,15 +1362,13 @@ pub(super) fn pick(d: &mut Dialog, order: &[String], color: &str, shift: bool, c } let mut set = selection(d); let anchor = if command { - match set.iter().position(|c| *c == color) { - Some(i) => { - set.remove(i); - set.last().cloned() - } - None => { - set.push(color.clone()); - Some(color) - } + if set.iter().any(|c| same_color(c, &color)) { + // Every entry that names the color, however it is written. + set.retain(|c| !same_color(c, &color)); + set.last().cloned() + } else { + set.push(color.clone()); + Some(color) } } else { set = vec![color.clone()]; @@ -1384,6 +1394,9 @@ pub(super) fn delete_colors(d: &mut Dialog, palette: &[String]) -> Result<(), St d.fields.remove("__color"); return Ok(()); } + // Each entry as `#rrggbb` when it names a color, so entries written another way compare equal. + let norm = |c: &str| table_rgb(c).unwrap_or_else(|| c.to_ascii_lowercase()); + let picked: Vec = picked.iter().map(|c| norm(c)).collect(); let list = |d: &Dialog, key: &str| -> Vec { d.fields .get("colorTable") @@ -1392,12 +1405,12 @@ pub(super) fn delete_colors(d: &mut Dialog, palette: &[String]) -> Result<(), St .into_iter() .flatten() .filter_map(Value::as_str) - .map(str::to_ascii_lowercase) + .map(norm) .collect() }; let mut custom = list(d, "customPalette"); if custom.is_empty() { - custom = palette.iter().map(|c| c.to_ascii_lowercase()).collect(); + custom = palette.iter().map(|c| norm(c)).collect(); } let mut deleted = list(d, "deleted"); for c in &picked { @@ -1491,16 +1504,25 @@ fn shifts(d: &Dialog) -> Map { d.fields.get("colorTable").and_then(|t| t.get("shifted")).and_then(Value::as_object).cloned().unwrap_or_default() } -/// Whether `a` and `b` name one color, however each is written; text that is not a color matches -/// the same text in any case. +/// Whether `a` and `b` name one color, however each is written, as the engine reads the table's +/// colors; other text, a spelling with alpha included (four or eight hex digits), matches only 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)) { + match (table_rgb(a), table_rgb(b)) { (Some(a), Some(b)) => a == b, _ => a.eq_ignore_ascii_case(b), } } +/// The color `h` names as `#rrggbb`, read as the engine reads the table's colors: `None` for text +/// that is not a color and for a spelling with alpha (four or eight hex digits). +fn table_rgb(h: &str) -> Option { + let t = h.trim(); + let digits = t.strip_prefix('#').unwrap_or(t); + let alpha = matches!(digits.len(), 4 | 8) && digits.chars().all(|c| c.is_ascii_hexdigit()); + if alpha { None } else { vectorcraft_color::Color::from_hex(t).map(|c| c.to_hex()) } +} + /// 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); 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 b93c36def8..1c8c6f17be 100644 --- a/crates/ui-egui/src/dialogs/tests_save_for_web.rs +++ b/crates/ui-egui/src/dialogs/tests_save_for_web.rs @@ -798,6 +798,51 @@ fn colour_table_selection_and_delete_color() { assert_eq!((&d.fields["colorTable"]["deleted"], &d.fields["colorTable"]["customPalette"]), (&json!([]), &json!([]))); } +/// A selection written another way (`#00F`) is deleted as the table writes it, so deleting the +/// table's only color is refused with nothing changed; a spelling with alpha names no table color. +#[test] +fn delete_color_matches_a_selection_written_another_way() { + let mut d = Dialog::new(save_for_web::KIND, json!({})); + let shown: Vec = ["#0000ff"].map(String::from).to_vec(); + d.fields.insert("__colors".into(), json!(["#00F", "#0000FF"])); + assert_eq!(save_for_web::selected_in(&d, &shown), ["#0000ff"]); + let before = d.fields.clone(); + assert_eq!(save_for_web::delete_colors(&mut d, &shown), Err(vectorcraft_engine::cmd::webexport::KEEP_ONE.to_string())); + assert_eq!(d.fields, before); + d.fields.insert("__colors".into(), json!(["#0000ff80"])); + assert!(save_for_web::selected_in(&d, &shown).is_empty()); +} + +/// A Ctrl-click on a selected color takes out every selection entry that names it, however each is +/// written (`#00F`, `#0000ff`). +#[test] +fn command_click_deselects_every_spelling_of_a_color() { + let order: Vec = ["#0000ff", "#ff0000"].map(String::from).to_vec(); + let mut d = Dialog::new(save_for_web::KIND, json!({})); + d.fields.insert("__colors".into(), json!(["#ff0000", "#00F", "#0000ff"])); + save_for_web::pick(&mut d, &order, "#0000ff", false, true); + assert_eq!(save_for_web::selection(&d), ["#ff0000"]); + assert_eq!(d.fields["__color"], json!("#ff0000")); +} + +/// Delete Color compares the table's lists as colors: with blue mapped to transparent as `#00f`, +/// deleting red (selected as `#f00`), the only other color, is refused with nothing changed, and a +/// deleted color written another way in `locked` (`blue`, ` #0000FF `) is taken out of the list. +#[test] +fn delete_color_compares_lists_written_another_way() { + let shown: Vec = ["#0000ff", "#ff0000"].map(String::from).to_vec(); + let mut d = Dialog::new(save_for_web::KIND, json!({"colorTable": {"transparent": ["#00f"]}})); + d.fields.insert("__color".into(), json!("#f00")); + let before = d.fields.clone(); + assert_eq!(save_for_web::delete_colors(&mut d, &shown), Err(vectorcraft_engine::cmd::webexport::KEEP_ONE.to_string())); + assert_eq!(d.fields, before); + let mut d = Dialog::new(save_for_web::KIND, json!({"colorTable": {"locked": ["blue", " #0000FF ", "#ff0000"]}})); + d.fields.insert("__color".into(), json!("#00F")); + save_for_web::delete_colors(&mut d, &shown).unwrap(); + assert_eq!(d.fields["colorTable"]["locked"], json!(["#ff0000"])); + assert_eq!(d.fields["colorTable"]["deleted"], json!(["#0000ff"])); +} + /// Delete Color takes only selected colors the table shows: a selection the table no longer holds /// (after a change of reduction or color count, or set through `ui.dialog.set`) deletes nothing, /// fixes no palette and is cleared, and a selection partly in the table deletes only what it shows. @@ -1023,6 +1068,37 @@ fn table_buttons_skip_a_selected_color_the_table_does_not_show() { assert!(has(&app, "locked", "#0000ff"), "{}", table(&app)); } +/// A list entry written another way (`#00F`) names the selected color: the buttons show Unlock, +/// Unshift and Restore, and a click takes the color out of the list. +#[test] +fn table_buttons_match_a_color_written_another_way() { + let dir = vectorcraft_testkit::temp_dir("sfw-short-hex"); + 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(); + for (k, v) in [("format", json!("gif")), ("antiAlias", json!("none")), ("dither", json!("none"))] { + set(&mut app, k, v); + } + let table = |app: &VectorcraftApp| app.ui.dialog.as_ref().and_then(|d| d.fields.get("colorTable").cloned()).unwrap_or_default(); + for (list, label) in [("locked", "Unlock"), ("webShift", "Unshift"), ("transparent", "Restore")] { + set(&mut app, "colorTable", json!({ list: ["#00F"] })); + set(&mut app, "__color", json!("#0000ff")); + click_text(&mut app, label); + assert_eq!(table(&app)[list], json!([]), "{list}"); + } + // Selected as `#00F`, a click adds the color as the table writes it. + set(&mut app, "colorTable", json!({})); + set(&mut app, "__color", json!("#00F")); + click_text(&mut app, "Lock"); + assert_eq!(table(&app)["locked"], json!(["#0000ff"])); + // A spelling with alpha names no table color: the buttons stay off and nothing is added. + set(&mut app, "colorTable", json!({})); + set(&mut app, "__color", json!("#0000ff80")); + click_text(&mut app, "Lock"); + assert_eq!(table(&app).get("locked"), None, "{}", table(&app)); +} + /// Click the dialog's text `label` with the pointer (frames a quarter second apart). fn click_text(app: &mut VectorcraftApp, label: &str) { let ctx = egui::Context::default(); diff --git a/docs/mcp.md b/docs/mcp.md index af2a1514ff..32ae51c7cd 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10568,7 +10568,9 @@ included), and two keys that name one color are errors. Presets and `webExport.s 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. 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 +limit. A key written another way (`#F00`) still names its color, so a new shift or Unshift replaces it. A selected +color (`__color`, `__colors`) or list entry written another way also names its table color: Lock, Transparent, Web +Shift and Delete Color act on it and write it as the table does, and a `#rrggbbaa` spelling names no table color. 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. From 76c4689e02334fb4ff0e8af844862dbba4727bf8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 11:33:29 -0800 Subject: [PATCH 3/5] Save for Web: shifts the engine drops do not count toward the 256 limit A key shifted to itself or a deleted color no longer counts toward the 256 shifts, and a new shift writes `shifted` without those entries. A map the engine refuses (a key or value that is not a color, two keys naming one color) is kept whole, so the engine still reports it. Docs: docs/mcp.md. --- crates/ui-egui/src/dialogs/save_for_web.rs | 31 +++++++++++++++++-- .../ui-egui/src/dialogs/tests_save_for_web.rs | 20 ++++++++++++ docs/mcp.md | 2 +- 3 files changed, 50 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/save_for_web.rs b/crates/ui-egui/src/dialogs/save_for_web.rs index 4ba055b558..6256881398 100644 --- a/crates/ui-egui/src/dialogs/save_for_web.rs +++ b/crates/ui-egui/src/dialogs/save_for_web.rs @@ -1479,17 +1479,44 @@ fn take_shift(d: &mut Dialog) -> Result<(), String> { /// 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, and a new source when 256 -/// colors are already shifted is an error that changes nothing. +/// colors are already shifted is an error that changes nothing. Entries the engine drops (a color +/// shifted to itself, a deleted color) do not count, and a new shift writes the map without them. 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 Ok(()) }; + let deleted: Vec = d + .fields + .get("colorTable") + .and_then(|t| t.get("deleted")) + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(Value::as_str) + .map(String::from) + .collect(); let map = shifts(d); - if to != source && map.len() >= webexport::MAX_TABLE && !map.keys().any(|k| same_color(k, &source)) { + // Entries are dropped only from a map the engine accepts (every key and value a color, no two + // keys naming one color); any other map is kept whole for the engine to refuse. + let mut keys: Vec = Vec::new(); + let valid = map.iter().all(|(k, v)| match (table_rgb(k), v.as_str().and_then(table_rgb)) { + (Some(k), Some(_)) if !keys.contains(&k) => { + keys.push(k); + true + } + _ => false, + }); + let live = |k: &str, v: &Value| { + let (true, Some(key), Some(to)) = (valid, table_rgb(k), v.as_str().and_then(table_rgb)) else { return true }; + to != key && !deleted.iter().any(|x| table_rgb(x).is_some_and(|x| x == key)) + }; + let count = map.iter().filter(|(k, v)| live(k, v)).count(); + if to != source && count >= webexport::MAX_TABLE && !map.iter().any(|(k, v)| live(k, v) && same_color(k, &source)) { return Err(webexport::too_many("shifted")); } unshift(d, &source); if to != source { let mut map = shifts(d); + map.retain(|k, v| live(k, v)); map.insert(source.clone(), json!(to)); set_table(d, "shifted", Value::Object(map)); } 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 1c8c6f17be..c8bbd9526b 100644 --- a/crates/ui-egui/src/dialogs/tests_save_for_web.rs +++ b/crates/ui-egui/src/dialogs/tests_save_for_web.rs @@ -921,6 +921,26 @@ fn colour_table_shift_holds_at_most_256_colors() { assert_eq!(d.fields["colorTable"]["shifted"]["#123456"], "#000000"); } +/// Entries the engine drops (a color shifted to itself, a deleted color) do not count toward the +/// 256 shifts, and a new shift writes the map without them. +#[test] +fn colour_table_shift_skips_entries_the_engine_drops() { + let mut full: serde_json::Map = (0..255).map(|i| (format!("#{i:06x}"), json!(format!("#{i:06x}")))).collect(); + full.insert("#abcdef".into(), json!("#000000")); + let mut d = Dialog::new(save_for_web::KIND, json!({"colorTable": {"shifted": full, "deleted": ["#ABCDEF"]}})); + save_for_web::shift_color(&mut d, "#123456", "#000000").unwrap(); + assert_eq!(d.fields["colorTable"]["shifted"], json!({"#123456": "#000000"})); + // A map the engine refuses (a value that is not a color, two keys naming one color) is kept + // whole for the engine to refuse. + for shifted in [json!({"nope": "NOPE"}), json!({"#abcdef": "nope"}), json!({"#f00": "#f00", "#FF0000": "#00ff00"})] { + let mut d = Dialog::new(save_for_web::KIND, json!({"colorTable": {"shifted": shifted.clone(), "deleted": ["#abcdef"]}})); + save_for_web::shift_color(&mut d, "#123456", "#000000").unwrap(); + let mut want = shifted.as_object().cloned().unwrap_or_default(); + want.insert("#123456".into(), json!("#000000")); + assert_eq!(d.fields["colorTable"]["shifted"], serde_json::Value::Object(want), "{shifted}"); + } +} + /// 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; diff --git a/docs/mcp.md b/docs/mcp.md index 32ae51c7cd..641f705089 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10568,7 +10568,7 @@ included), and two keys that name one color are errors. Presets and `webExport.s 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. 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. A selected +limit; a key shifted to itself or a deleted color does not count, and a new shift writes `shifted` without them. A key written another way (`#F00`) still names its color, so a new shift or Unshift replaces it. A selected color (`__color`, `__colors`) or list entry written another way also names its table color: Lock, Transparent, Web Shift and Delete Color act on it and write it as the table does, and a `#rrggbbaa` spelling names no table color. 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 From c5c54e15f25d6fe10f3160ee87eb6582f63255ec Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 18:07:00 -0800 Subject: [PATCH 4/5] Save for Web: a color shift survives Done right after the Color Picker The Color Picker's OK for a color table cell now shifts the color in the table at once, so Done or Save before the dialog draws again keeps the shift. The table marks list a color written twice in one list once. --- crates/ui-egui/src/dialogs/color_picker.rs | 9 +++- crates/ui-egui/src/dialogs/save_for_web.rs | 43 +++++++++++++++---- .../src/dialogs/save_for_web/color_table.rs | 12 +++++- .../src/dialogs/save_for_web/tests_table.rs | 29 +++++++++++++ 4 files changed, 81 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index 0c1f50cbb1..af1b318728 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -6,7 +6,8 @@ //! `artboard.setProps {index, color}`. //! //! A command dialog's colour row raises a `ColorRequest`; [`pump`] opens a picker over that dialog -//! and answers the row with its OK. +//! and answers the row with its OK. The OK for a Save for Web colour table cell shifts the cell's +//! colour in the table instead ([`super::save_for_web::take_palette_pick`]). //! //! Fields agents set with `ui.dialog.set`: the framework picker's (`color`, `mode`, `webColors`, //! `swatches`, `library`). `stroke`, `artboard` and `color` come from the opener. @@ -253,7 +254,11 @@ fn finish( ) { let preview = std::mem::take(&mut open.preview); match (result, &open.target) { - (Some(DialogResult::Ok(r)), Target::Answer { parent, key }) => dialogs.with(|h| h.answer_color(*parent, key, r.picked.color)), + (Some(DialogResult::Ok(r)), Target::Answer { parent, key }) => { + if !super::save_for_web::take_palette_pick(app, *parent, key, open.start, r.picked.color) { + dialogs.with(|h| h.answer_color(*parent, key, r.picked.color)); + } + } (Some(DialogResult::Ok(r)), _) => { if let Err(e) = commit(app, open, preview, &r.picked) { app.status(e); diff --git a/crates/ui-egui/src/dialogs/save_for_web.rs b/crates/ui-egui/src/dialogs/save_for_web.rs index b338d45611..aaaf3d4e1c 100644 --- a/crates/ui-egui/src/dialogs/save_for_web.rs +++ b/crates/ui-egui/src/dialogs/save_for_web.rs @@ -19,10 +19,12 @@ use vectorcraft_render::encode::quantize::Reduction; use craft::behavior::PixelSize; use craft::host::PickRequest; +use craft::theme::Srgba; use craft::ui::dialog::{DialogId, DialogResult, StackDialog}; use craft::ui::patterns::form_dialogs::{ BrowserPreview, ColorTable, ColorTableEdit, ColorTableEvent, HostedSaveForWeb, OptimizeAnswer, OptimizeRequest, OptimizeScope, OptimizeStart, - SaveForWebOptions, SaveForWebResult, WantedVariant, WebDocument, WebFormat, WebPreset, WebPresetEvent, WebSlice, WebSlices, WebVariant, + PALETTE_COLOR_KEY, SaveForWebOptions, SaveForWebResult, WantedVariant, WebDocument, WebFormat, WebPreset, WebPresetEvent, WebSlice, WebSlices, + WebVariant, }; use craft::ui::primitives::{Revision, TextureStore, TextureStoreOptions}; use craft::ui::runtime::requests::PathRequest; @@ -432,7 +434,7 @@ fn on_dialog(host: &craft::ui::shell::WindowDialogs, f: impl FnOnce(&mut Host /// Answers the open dialog once per frame: its result when it closed, else its requests. /// Colour requests (the matte, a palette cell) are routed by the host-wide colour picker routing; -/// a palette answer comes back as a `Shift` table event. +/// a palette cell's pick is applied to the table by [`take_palette_pick`]. pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(host) = app.dialogs() else { return }; match host.with(|h| h.take::()) { @@ -511,12 +513,7 @@ fn answer_variants(app: &mut VectorcraftApp, ctx: &egui::Context, host: &craft:: /// Applies the colour table edits the dialog filed. A Delete clears the dialog's colour selection. fn edit_table(app: &mut VectorcraftApp, ctx: &egui::Context, host: &craft::ui::shell::WindowDialogs, asked: &Asked) { - let shown = app - .session - .web_settings(&settings_of(&asked.options, &app.web_export.table, None)) - .and_then(|s| encoded(app, &s)) - .map(|o| o.colors.iter().map(|c| c.source).collect::>()); - let shown = match shown { + let shown = match shown_colors(app, &asked.options) { Ok(shown) => shown, Err(e) => return app.status(e), }; @@ -533,6 +530,36 @@ fn edit_table(app: &mut VectorcraftApp, ctx: &egui::Context, host: &craft::ui::s } } +/// The source colours of the palette the dialog's settings `options` show, with the table as it stands. +fn shown_colors(app: &mut VectorcraftApp, options: &SaveForWebOptions) -> Result, String> { + let settings = app.session.web_settings(&settings_of(options, &app.web_export.table, None))?; + Ok(encoded(app, &settings)?.colors.iter().map(|c| c.source).collect()) +} + +/// The Color Picker's OK for the colour table cell `key` of the open dialog `parent`: the cell's colour `from` +/// is shifted to `to` in the table at once, so Done or Save in the dialog's next pass keeps the shift. A colour +/// the palette no longer shows is not shifted, and a refused shift shows in the status line. `false` when +/// `parent` is not Save for Web or `key` is not its palette, and the picker answers the row instead. +pub(crate) fn take_palette_pick(app: &mut VectorcraftApp, parent: DialogId, key: &str, from: Srgba, to: Srgba) -> bool { + let Some(host) = app.dialogs() else { return false }; + if key != PALETTE_COLOR_KEY { + return false; + } + let Some(options) = host.with(|h| h.get_mut_by_id::(parent).map(|d| d.current().clone())) else { + return false; + }; + let rgb = |c: Srgba| { + let [r, g, b, _] = c.to_rgba().0; + [r, g, b] + }; + let edit = ColorTableEdit::Shift(rgb(to)); + let shifted = shown_colors(app, &options).and_then(|shown| color_table::apply(&mut app.web_export.table, &edit, &[rgb(from)], &shown)); + if let Err(e) = shifted { + app.status(e); + } + true +} + /// Runs what the preset list asked for and shows a failure in the status line. fn store_presets(app: &mut VectorcraftApp, events: Vec) { for event in events { diff --git a/crates/ui-egui/src/dialogs/save_for_web/color_table.rs b/crates/ui-egui/src/dialogs/save_for_web/color_table.rs index 280fcae18a..39b03bc9d9 100644 --- a/crates/ui-egui/src/dialogs/save_for_web/color_table.rs +++ b/crates/ui-egui/src/dialogs/save_for_web/color_table.rs @@ -241,9 +241,17 @@ pub(crate) fn restore(table: &mut Value) { } /// What the table shows of `table`: its locked, transparent and shifted colours. An entry that is -/// not a colour is skipped. +/// not a colour is skipped, and a colour written more than once in a list is listed once. pub(crate) fn marks(table: &Value) -> TableMarks { - let colors = |key: &str| list(table, key).iter().filter_map(|c| parse(c)).collect(); + let colors = |key: &str| { + let mut out: Vec<[u8; 3]> = Vec::new(); + for c in list(table, key).iter().filter_map(|c| parse(c)) { + if !out.contains(&c) { + out.push(c); + } + } + out + }; let shifted = shifts(table).iter().filter_map(|(k, v)| Some((parse(k)?, parse(v.as_str()?)?))).collect(); // PLAN: TableMarks lacks `web_shifted` (ex.W9 request); the Web Shift/Unshift label needs it. let mut marks = TableMarks::default(); diff --git a/crates/ui-egui/src/dialogs/save_for_web/tests_table.rs b/crates/ui-egui/src/dialogs/save_for_web/tests_table.rs index 60b12ec807..6dabd4c119 100644 --- a/crates/ui-egui/src/dialogs/save_for_web/tests_table.rs +++ b/crates/ui-egui/src/dialogs/save_for_web/tests_table.rs @@ -279,6 +279,35 @@ fn a_picked_color_becomes_a_shift_and_cancel_shifts_nothing() { assert_eq!(app.web_export.table["shifted"], json!({"#0000ff": "#00ff00"})); } +/// Done right after the Color Picker's OK, before the dialog draws again, remembers the picked 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(); + for (k, v) in [("format", json!("gif")), ("antiAlias", json!("none")), ("dither", json!("none"))] { + set(&mut app, k, v); + } + let ctx = app.ui_ctx.clone().expect("the app has a window"); + crate::dialogs::host::pump(&mut app, &ctx); + let picker = open_cell(&mut app, &ctx, "#0000ff"); + host(&app).with(|h| h.set_json_field(&ctx, picker, "color", json!("#00ff00"))).unwrap(); + host(&app).with(|h| h.confirm_by_id(&ctx, picker)); + // The frame that settles the picker, then Done before the dialog's next pass. + app_frame(&mut app, &ctx, vec![]); + set(&mut app, "choice", json!("done")); + let dialog = id(&app); + host(&app).with(|h| h.confirm_by_id(&ctx, dialog)); + for _ in 0..3 { + app_frame(&mut app, &ctx, vec![]); + } + assert!(host(&app).with(|h| h.get::().is_none()), "Done closes the dialog"); + let remembered = app.session.last_web_settings().color_table.shifted; + assert_eq!(remembered.get("#0000ff").map(String::as_str), Some("#00ff00")); +} + #[test] fn restore_brings_back_a_preview_that_failed() { let dir = vectorcraft_testkit::temp_dir("sfw-restore-table"); From b9f6233c69d917a9f630fd1c17e6ea70d237605d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 20:19:58 -0800 Subject: [PATCH 5/5] Save for Web: a shift map over 256 entries is kept whole A `shifted` map with more than 256 entries is one the engine refuses, so the shift edit no longer drops its self-shifts and deleted colors. A shift that would leave more than 256 colors shifted, including a new target for a color that is already shifted, is refused with the limit error. --- .../src/dialogs/save_for_web/color_table.rs | 27 ++++++++++--------- .../src/dialogs/save_for_web/tests_table.rs | 16 +++++++++++ 2 files changed, 31 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/dialogs/save_for_web/color_table.rs b/crates/ui-egui/src/dialogs/save_for_web/color_table.rs index 39b03bc9d9..cbeedbe224 100644 --- a/crates/ui-egui/src/dialogs/save_for_web/color_table.rs +++ b/crates/ui-egui/src/dialogs/save_for_web/color_table.rs @@ -196,30 +196,33 @@ fn delete(table: &mut Value, picked: &[String], shown: &[[u8; 3]]) -> Result<(), } /// Shift the source colour `from` to `to`, wherever it is in the image; it is no longer -/// web-shifted. Shifting a colour to itself takes its shift away. A new source when 256 colours -/// are already shifted is refused with the engine's limit error, and nothing changes. Entries the +/// web-shifted. Shifting a colour to itself takes its shift away. A shift that would leave more +/// than 256 colours shifted is refused with the engine's limit error, and nothing changes. Entries the /// engine drops (a colour shifted to itself, a deleted colour) do not count, and a new shift writes /// the map without them. pub(crate) fn shift(table: &mut Value, from: [u8; 3], to: [u8; 3]) -> Result<(), String> { let (source, to) = (hex(from), hex(to)); let deleted: Vec<[u8; 3]> = list(table, "deleted").iter().filter_map(|c| parse(c)).collect(); let map = shifts(table); - // Entries are dropped only from a map the engine accepts (every key and value a colour, no two - // keys naming one colour); any other map is kept whole for the engine to refuse. + // Entries are dropped only from a map the engine accepts (at most 256 entries, every key and + // value a colour, no two keys naming one colour); any other map is kept whole for the engine to + // refuse. let mut keys: Vec<[u8; 3]> = Vec::new(); - let valid = map.iter().all(|(k, v)| match (parse(k), v.as_str().and_then(parse)) { - (Some(k), Some(_)) if !keys.contains(&k) => { - keys.push(k); - true - } - _ => false, - }); + let valid = map.len() <= webexport::MAX_TABLE + && map.iter().all(|(k, v)| match (parse(k), v.as_str().and_then(parse)) { + (Some(k), Some(_)) if !keys.contains(&k) => { + keys.push(k); + true + } + _ => false, + }); let live = |k: &str, v: &Value| { let (true, Some(key), Some(to)) = (valid, parse(k), v.as_str().and_then(parse)) else { return true }; to != key && !deleted.contains(&key) }; let count = map.iter().filter(|(k, v)| live(k, v)).count(); - if to != source && count >= webexport::MAX_TABLE && !map.iter().any(|(k, v)| live(k, v) && same(k, &source)) { + let held = usize::from(map.iter().any(|(k, v)| live(k, v) && same(k, &source))); + if to != source && count - held >= webexport::MAX_TABLE { return Err(webexport::too_many("shifted")); } unshift(table, &source); diff --git a/crates/ui-egui/src/dialogs/save_for_web/tests_table.rs b/crates/ui-egui/src/dialogs/save_for_web/tests_table.rs index 6dabd4c119..6f8d414185 100644 --- a/crates/ui-egui/src/dialogs/save_for_web/tests_table.rs +++ b/crates/ui-egui/src/dialogs/save_for_web/tests_table.rs @@ -148,6 +148,22 @@ fn a_shift_skips_entries_the_engine_drops() { } } +/// A map with more than 256 entries is one the engine refuses, so none of its entries are dropped: +/// with 257 colours shifted to themselves, a new shift and a new target for a shifted colour are +/// refused with the limit error and nothing changes. Taking a shift away still works. +#[test] +fn a_shift_keeps_a_map_over_the_limit_whole() { + let over: serde_json::Map = (0..257).map(|i| (format!("#{i:06x}"), json!(format!("#{i:06x}")))).collect(); + let mut t = json!({"shifted": over}); + let before = t.clone(); + let e = shift(&mut t, [0x12, 0x34, 0x56], A).unwrap_err(); + assert_eq!((e, &t), (webexport::too_many("shifted"), &before)); + let e = shift(&mut t, [0, 0, 5], [0x12, 0x34, 0x56]).unwrap_err(); + assert_eq!((e, &t), (webexport::too_many("shifted"), &before)); + shift(&mut t, [0, 0, 5], [0, 0, 5]).unwrap(); + assert_eq!(t["shifted"].as_object().map(|m| m.len()), Some(256)); +} + /// A key or list entry written another way (`#F00`, upper case, `blue`) still names its colour: /// a new shift replaces it, Unshift and the buttons take it out, the marks show it, and a /// spelling with alpha names no colour.