diff --git a/crates/engine/src/cmd/webexport.rs b/crates/engine/src/cmd/webexport.rs index 14c5fa6ebd..5f2d2cbffd 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/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 f80c488fef..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 @@ -1,8 +1,9 @@ //! The Save for Web colour table model: the edits the table's buttons and menu make, applied to the //! engine's `colorTable` value (`webexport::ColorTable`), and the marks the table shows from it. //! -//! The value is user input (automation sets it), so every read skips what is not a `#rrggbb` -//! string. Lists hold lowercase `#rrggbb` and colours compare case-insensitively. +//! The value is user input (automation sets it), so every read skips what is not a colour. +//! Entries compare as the colours they name, however each is written (`#F00`, `#ff0000`), as the +//! engine reads them; the edits write lowercase `#rrggbb`. use serde_json::{Map, Value, json}; use vectorcraft_engine::cmd::webexport; @@ -15,14 +16,30 @@ fn hex(c: [u8; 3]) -> String { format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2]) } -/// The colour a `#rrggbb` string names. +/// The colour `s` names, read as the engine reads the table's colours: `None` for text that is not +/// a colour and for a spelling with alpha (four or eight hex digits). fn parse(s: &str) -> Option<[u8; 3]> { - let digits = s.strip_prefix('#')?; - if digits.len() != 6 || !digits.bytes().all(|b| b.is_ascii_hexdigit()) { + let t = s.trim(); + let digits = t.strip_prefix('#').unwrap_or(t); + if matches!(digits.len(), 4 | 8) && digits.bytes().all(|b| b.is_ascii_hexdigit()) { return None; } - let channel = |i: usize| u8::from_str_radix(digits.get(i..i + 2)?, 16).ok(); - Some([channel(0)?, channel(2)?, channel(4)?]) + let [r, g, b, _] = vectorcraft_color::Color::from_hex(t)?.to_rgba8(1.0); + Some([r, g, b]) +} + +/// Whether `a` and `b` name one colour, however each is written; text that names no colour matches +/// only the same text in any case. +fn same(a: &str, b: &str) -> bool { + match (parse(a), parse(b)) { + (Some(a), Some(b)) => a == b, + _ => a.eq_ignore_ascii_case(b), + } +} + +/// Whether `list` holds an entry that names `color`. +fn holds(list: &[String], color: &str) -> bool { + list.iter().any(|c| same(c, color)) } /// The strings of the table's list `key`, lowercase. @@ -50,30 +67,31 @@ fn toggle(table: &mut Value, key: &str, colors: &[String]) { return; } let mut v = list(table, key); - if colors.iter().all(|c| v.contains(c)) { - v.retain(|c| !colors.contains(c)); + if colors.iter().all(|c| holds(&v, c)) { + v.retain(|c| !holds(colors, c)); } else { - let missing: Vec = colors.iter().filter(|c| !v.contains(c)).cloned().collect(); + let missing: Vec = colors.iter().filter(|c| !holds(&v, c)).cloned().collect(); v.extend(missing); } set_table(table, key, json!(v)); } -/// Take `colors` out of the table's list `key`; the list is left alone when none is in it. +/// Take `colors` out of the table's list `key` (every entry that names one of them); the list is +/// left alone when none is in it. fn remove(table: &mut Value, key: &str, colors: &[String]) { let mut v = list(table, key); let before = v.len(); - v.retain(|c| !colors.contains(c)); + v.retain(|c| !holds(colors, c)); if v.len() != before { set_table(table, key, json!(v)); } } -/// Take the shift by hand of the source colour `source` away. +/// Take the shift by hand of the source colour `source` away: every key that names that colour. fn unshift(table: &mut Value, source: &str) { let mut map = shifts(table); let before = map.len(); - map.retain(|k, _| !k.eq_ignore_ascii_case(source)); + map.retain(|k, _| !same(k, source)); if map.len() != before { set_table(table, "shifted", Value::Object(map)); } @@ -111,7 +129,7 @@ pub(crate) fn apply(table: &mut Value, edit: &ColorTableEdit, colors: &[[u8; 3]] // first selected colour is shifted to. ColorTableEdit::Shift(to) => { if let Some(&from) = colors.first().filter(|c| shown.contains(c)) { - shift(table, from, *to); + return shift(table, from, *to); } return Ok(()); } @@ -130,12 +148,13 @@ pub(crate) fn apply(table: &mut Value, edit: &ColorTableEdit, colors: &[[u8; 3]] match edit { ColorTableEdit::Lock => { let by_hand = shifts(table); - let free: Vec = picked.into_iter().filter(|c| !by_hand.keys().any(|k| k.eq_ignore_ascii_case(c))).collect(); + let free: Vec = picked.into_iter().filter(|c| !by_hand.keys().any(|k| same(k, c))).collect(); toggle(table, "locked", &free); } ColorTableEdit::Transparent => toggle(table, "transparent", &picked), ColorTableEdit::WebShift => { - let adds = !picked.iter().all(|c| list(table, "webShift").contains(c)); + let web = list(table, "webShift"); + let adds = !picked.iter().all(|c| holds(&web, c)); toggle(table, "webShift", &picked); if adds { picked.iter().for_each(|c| unshift(table, c)); @@ -157,12 +176,12 @@ fn delete(table: &mut Value, picked: &[String], shown: &[[u8; 3]]) -> Result<(), } let mut deleted = list(table, "deleted"); for c in picked { - if !deleted.contains(c) { + if !holds(&deleted, c) { deleted.push(c.clone()); } } - let clear: Vec = list(table, "transparent").into_iter().filter(|c| !picked.contains(c)).collect(); - if custom.iter().all(|c| deleted.contains(c) || clear.contains(c)) { + let clear: Vec = list(table, "transparent").into_iter().filter(|c| !holds(picked, c)).collect(); + if custom.iter().all(|c| holds(&deleted, c) || holds(&clear, c)) { return Err(webexport::KEEP_ONE.into()); } for key in ["locked", "transparent", "webShift"] { @@ -177,16 +196,44 @@ 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. -pub(crate) fn shift(table: &mut Value, from: [u8; 3], to: [u8; 3]) { +/// 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 (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.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(); + 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); if to != source { let mut map = shifts(table); + map.retain(|k, v| live(k, v)); map.insert(source.clone(), json!(to)); set_table(table, "shifted", Value::Object(map)); } remove(table, "webShift", &[source]); + Ok(()) } /// Restore Generated Table: no deleted colours and no fixed palette; the reduction makes the @@ -197,9 +244,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 5b684406ed..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 @@ -31,7 +31,7 @@ fn every_table_edit_changes_the_lists_it_names() { run(&mut t, ColorTableEdit::Transparent, &[D], &shown).unwrap(); assert_eq!(t["transparent"], json!(["#333333"])); // A hand-shifted colour stays locked: Lock does nothing to it. - shift(&mut t, B, [255, 136, 0]); + shift(&mut t, B, [255, 136, 0]).unwrap(); run(&mut t, ColorTableEdit::Lock, &[B], &shown).unwrap(); assert_eq!(t["locked"], json!([])); // Web Shift takes the hand shift away; Unshift takes colours out of webShift only. @@ -40,9 +40,9 @@ fn every_table_edit_changes_the_lists_it_names() { run(&mut t, ColorTableEdit::Unshift, &[B], &shown).unwrap(); assert_eq!(t["webShift"], json!(["#222222"])); // A shift takes the colour out of webShift; one to the source colour takes it away. - shift(&mut t, C, [0, 255, 0]); + shift(&mut t, C, [0, 255, 0]).unwrap(); assert_eq!((&t["webShift"], &t["shifted"]), (&json!([]), &json!({"#222222": "#00ff00"}))); - shift(&mut t, C, C); + shift(&mut t, C, C).unwrap(); assert_eq!(t["shifted"], json!({})); // The Shift edit is a shift of the first selected colour. run(&mut t, ColorTableEdit::Shift([1, 2, 3]), &[A], &shown).unwrap(); @@ -110,6 +110,113 @@ fn an_edit_skips_selected_colors_the_table_does_not_show() { assert_eq!((&t["customPalette"], &t["deleted"]), (&json!(["#000000", "#111111"]), &json!(["#111111"]))); } +/// With 256 colours shifted, shifting another colour is refused with the engine's limit error and +/// changes nothing; a shifted colour can still be shifted again or have its shift taken away. +#[test] +fn a_shift_holds_at_most_256_colors() { + let full: serde_json::Map = (0..256).map(|i| (format!("#{i:06x}"), json!("#ffffff"))).collect(); + let mut t = json!({"shifted": full}); + let before = t.clone(); + let e = shift(&mut t, [0x12, 0x34, 0x56], A).unwrap_err(); + assert_eq!((e, &t), (webexport::too_many("shifted"), &before)); + // The Shift edit reports the same error. + let new = [0x12, 0x34, 0x56]; + assert_eq!(run(&mut t, ColorTableEdit::Shift(A), &[new], &[new]), Err(webexport::too_many("shifted"))); + assert_eq!(t, before); + shift(&mut t, [0, 0, 5], A).unwrap(); + assert_eq!((t["shifted"]["#000005"].as_str(), t["shifted"].as_object().map(|m| m.len())), (Some("#000000"), Some(256))); + shift(&mut t, [0, 0, 5], [0, 0, 5]).unwrap(); + shift(&mut t, new, A).unwrap(); + assert_eq!(t["shifted"]["#123456"], "#000000"); +} + +/// Entries the engine drops (a colour shifted to itself, a deleted colour) do not count toward the +/// 256 shifts, and a new shift writes the map without them. A map the engine refuses is kept whole. +#[test] +fn a_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 t = json!({"shifted": full, "deleted": ["#ABCDEF"]}); + shift(&mut t, [0x12, 0x34, 0x56], A).unwrap(); + assert_eq!(t["shifted"], json!({"#123456": "#000000"})); + for shifted in [json!({"nope": "NOPE"}), json!({"#abcdef": "nope"}), json!({"#f00": "#f00", "#FF0000": "#00ff00"})] { + let mut t = json!({"shifted": shifted.clone(), "deleted": ["#abcdef"]}); + shift(&mut t, [0x12, 0x34, 0x56], A).unwrap(); + let mut want = shifted.as_object().cloned().unwrap_or_default(); + want.insert("#123456".into(), json!("#000000")); + assert_eq!(t["shifted"], Value::Object(want), "{shifted}"); + } +} + +/// 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. +#[test] +fn table_edits_match_a_color_written_another_way() { + let (red, blue) = ([0xff, 0, 0], [0, 0, 0xff]); + let shown = [red, blue]; + let mut t = json!({"shifted": {"#F00": "#00ff00", "nope": "#000000"}, "webShift": ["#0000FF"]}); + shift(&mut t, red, [0x12, 0x34, 0x56]).unwrap(); + assert_eq!(t["shifted"], json!({"#ff0000": "#123456", "nope": "#000000"})); + shift(&mut t, blue, [0x65, 0x43, 0x21]).unwrap(); + assert_eq!(t["webShift"], json!([])); + // Lock leaves a colour shifted under another spelling alone. + let mut t = json!({"shifted": {"#F00": "#00ff00"}}); + run(&mut t, ColorTableEdit::Lock, &[red], &shown).unwrap(); + assert_eq!(t.get("locked"), None); + // Each list's button takes out an entry written another way, as Unlock, Restore and Unshift do. + for (list, edit) in [("locked", ColorTableEdit::Lock), ("transparent", ColorTableEdit::Transparent), ("webShift", ColorTableEdit::Unshift)] { + let mut t = json!({ list: ["#00F", " #0000FF "] }); + let m = marks(&t); + if list != "webShift" { + assert_eq!(if list == "locked" { m.locked } else { m.transparent }, vec![blue], "{list}"); + } + run(&mut t, edit, &[blue], &shown).unwrap(); + assert_eq!(t[list], json!([]), "{list}"); + } + // Web Shift of a colour in the list under another spelling takes it out. + let mut t = json!({"webShift": ["#00f"]}); + run(&mut t, ColorTableEdit::WebShift, &[blue], &shown).unwrap(); + assert_eq!(t["webShift"], json!([])); + // A spelling with alpha names no colour. + let mut t = json!({"locked": ["#0000ff80"]}); + assert_eq!(marks(&t).locked, Vec::<[u8; 3]>::new()); + run(&mut t, ColorTableEdit::Lock, &[blue], &shown).unwrap(); + assert_eq!(t["locked"], json!(["#0000ff80", "#0000ff"])); +} + +/// Delete Color compares the lists as colours: with blue mapped to transparent as `#00f`, deleting +/// red, the only other colour, is refused with nothing changed, and a deleted colour written +/// another way in `locked` (`blue`, ` #0000FF `) is taken out of the list. +#[test] +fn delete_color_compares_lists_written_another_way() { + let (red, blue) = ([0xff, 0, 0], [0, 0, 0xff]); + let shown = [blue, red]; + let mut t = json!({"transparent": ["#00f"]}); + let before = t.clone(); + assert_eq!(run(&mut t, ColorTableEdit::Delete, &[red], &shown), Err(webexport::KEEP_ONE.to_string())); + assert_eq!(t, before); + let mut t = json!({"locked": ["blue", " #0000FF ", "#ff0000"], "deleted": ["#00F"]}); + run(&mut t, ColorTableEdit::Delete, &[blue], &shown).unwrap(); + assert_eq!((&t["locked"], &t["deleted"]), (&json!(["#ff0000"]), &json!(["#00f"]))); +} + /// One app frame with `events`, a moment after the last. fn app_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) { let time = ctx.input(|i| i.time) + 0.05; @@ -188,6 +295,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"); diff --git a/docs/mcp.md b/docs/mcp.md index c16e80ba7b..edc2f952b6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10920,7 +10920,11 @@ 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 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 list entry written another +way also names its color: the table marks it, Lock, Transparent, Web Shift and Delete Color act on it, and new entries +are written as lowercase `#rrggbb`. A `#rrggbbaa` spelling names no table color. 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.