Merge pull request #8436 from dotCooCoo/feat/save-for-web-delete-color

Save for Web: Delete Color removes colors from the color table
This commit is contained in:
BFlat
2026-11-18 13:11:21 +07:00
committed by GitHub
37 changed files with 593 additions and 38 deletions
+80 -15
View File
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Save for Web",
[],
None,
"{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/<slice name>.<ext>), output?: images (default)|html (an HTML page placing the image or slices, <stem>.html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself",
"{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity, deleted?: [\"#rrggbb\"…] (taken out of the table: their pixels take the nearest color left, and at least one color stays), customPalette?: [\"#rrggbb\"…] (a fixed palette used instead of the reduction's, at most `colors` entries; a new reduction without colorTable clears it and deleted)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/<slice name>.<ext>), output?: images (default)|html (an HTML page placing the image or slices, <stem>.html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself",
has_doc,
export
),
@@ -325,27 +325,39 @@ pub struct ColorTable {
pub web_shift: Vec<String>,
#[serde(serialize_with = "ser_key", deserialize_with = "de_key")]
pub sort: ColorSort,
/// Taken out of the table: their pixels take the nearest color left. A deleted color is no
/// longer locked, transparent or web-shifted.
pub deleted: Vec<String>,
/// A fixed palette (a Custom table) used instead of the reduction's own: the colors of the
/// table when the first color was deleted. Empty: the reduction makes the palette.
pub custom_palette: Vec<String>,
}
/// The most colours a colour table list holds.
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";
impl ColorTable {
/// Whether the table is a Custom one: a color was deleted or the palette is fixed.
pub fn is_custom(&self) -> bool {
!self.deleted.is_empty() || !self.custom_palette.is_empty()
}
fn colors(list: &[String], what: &str) -> std::result::Result<Vec<[u8; 3]>, String> {
if list.len() > MAX_TABLE {
return Err(format!("colorTable.{what}: at most {MAX_TABLE} colours"));
}
list.iter()
.map(|h| {
vectorcraft_color::Color::from_hex(h)
.filter(|_| !super::hex_with_alpha(h))
.map(|c| {
let [r, g, b, _] = c.to_rgba8(1.0);
[r, g, b]
})
.ok_or_else(|| format!("colorTable.{what}: `{h}` is not a colour such as \"#ff8800\""))
})
.collect()
list.iter().map(|h| Self::rgb(h).ok_or_else(|| format!("colorTable.{what}: `{h}` is not a colour such as \"#ff8800\""))).collect()
}
/// `h` as RGB; `None` when it is not a color such as `#ff8800`.
fn rgb(h: &str) -> Option<[u8; 3]> {
vectorcraft_color::Color::from_hex(h).filter(|_| !super::hex_with_alpha(h)).map(|c| {
let [r, g, b, _] = c.to_rgba8(1.0);
[r, g, b]
})
}
}
@@ -445,7 +457,13 @@ impl WebSettings {
}
}
}
let s: WebSettings = serde_json::from_value(v).map_err(|e| format!("Save for Web settings: {e}"))?;
let mut s: WebSettings = serde_json::from_value(v).map_err(|e| format!("Save for Web settings: {e}"))?;
// Another reduction makes a new palette: the deletions and the fixed palette go, unless
// the params give the color table too.
if p.get("reduction").is_some() && p.get("colorTable").is_none() && s.reduction != self.reduction {
s.color_table.deleted.clear();
s.color_table.custom_palette.clear();
}
s.checked()
}
@@ -463,11 +481,19 @@ impl WebSettings {
return Err("width and height are at least 1 pixel".into());
}
self.matte_rgb()?;
let table = &mut self.color_table;
for (list, what) in
[(&self.color_table.locked, "locked"), (&self.color_table.transparent, "transparent"), (&self.color_table.web_shift, "webShift")]
[(&table.locked, "locked"), (&table.transparent, "transparent"), (&table.web_shift, "webShift"), (&table.custom_palette, "customPalette")]
{
ColorTable::colors(list, what)?;
}
// A deleted color is no longer locked, transparent or web-shifted.
let deleted = ColorTable::colors(&table.deleted, "deleted")?;
if !deleted.is_empty() {
for list in [&mut table.locked, &mut table.transparent, &mut table.web_shift] {
list.retain(|h| ColorTable::rgb(h).is_none_or(|c| !deleted.contains(&c)));
}
}
Ok(self)
}
@@ -741,7 +767,7 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
transparency: s.transparency,
matte,
};
let mut ix = quantize::quantize_locked(rgba, w, h, &o, &locked);
let mut ix = reduced(rgba, w, h, s, &o, &locked)?;
// Map to transparent works on the colours the reduction made.
let before = ix.palette.clone();
let clear = ix.transparent.map(usize::from);
@@ -789,6 +815,45 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
Ok(PaletteImage { ix, colors, mapped })
}
/// The pixels reduced to the palette `s` gives: the reduction's own (`locked` kept), or the
/// color table's fixed one, without the deleted colors. The pixels of a deleted color take the
/// nearest color left, with `o`'s dither. A deletion has to leave a color that is not mapped to
/// transparent.
fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, locked: &[[u8; 3]]) -> std::result::Result<Indexed, String> {
let table = &s.color_table;
let deleted = ColorTable::colors(&table.deleted, "deleted")?;
let custom = ColorTable::colors(&table.custom_palette, "customPalette")?;
let to_clear = ColorTable::colors(&table.transparent, "transparent")?;
let opaque_left = |left: &[[u8; 3]]| left.iter().any(|c| !to_clear.contains(c));
if custom.is_empty() {
let ix = quantize::quantize_locked(rgba, w, h, o, locked);
let clear = ix.transparent.map(usize::from);
let gone = |i: usize, c: &[u8; 3]| Some(i) != clear && deleted.contains(c);
if !ix.palette.iter().enumerate().any(|(i, c)| gone(i, c)) {
return Ok(ix);
}
let left: Vec<[u8; 3]> = ix.palette.iter().enumerate().filter(|&(i, c)| Some(i) != clear && !deleted.contains(c)).map(|(_, c)| *c).collect();
if left.is_empty() || !opaque_left(&left) {
return Err(KEEP_ONE.into());
}
return Ok(quantize::quantize_to(rgba, w, h, o, &left));
}
// A fixed palette holds at most `colors` entries, the transparent one included.
let has_clear = s.transparency && rgba.as_chunks::<4>().0.iter().any(|p| p[3] < 128);
let removed = custom.iter().any(|c| deleted.contains(c));
let mut left: Vec<[u8; 3]> = vec![];
for c in custom {
if !deleted.contains(&c) && !left.contains(&c) {
left.push(c);
}
}
left.truncate(usize::from(s.colors.clamp(2, 256)) - usize::from(has_clear));
if left.is_empty() || (removed && !opaque_left(&left)) {
return Err(KEEP_ONE.into());
}
Ok(quantize::quantize_to(rgba, w, h, o, &left))
}
/// An optimised image as straight RGBA → `(pixels, width, height)` (the dialog's preview).
pub fn decode(o: &Optimized) -> std::result::Result<(Vec<u8>, u32, u32), String> {
let img = craft_image_codecs::decode(o.display()).map_err(|e| format!("the optimised image can't be read back: {e}"))?;
+86
View File
@@ -453,6 +453,92 @@ fn colour_table_lock_web_shift_snap_and_sort() {
assert!(lossy < plain, "{lossy} vs {plain}");
}
/// Delete Color: the deleted colors leave the table and the file, their pixels take the nearest
/// color left, and the edit stays with the settings until another reduction is chosen.
#[test]
fn colour_table_delete_maps_pixels_to_the_nearest_color_left() {
// 40×10: red, a near red and blue, and 10 px with nothing (transparent).
let mut s = session(40.0, 10.0);
rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#ff0000");
rect(&mut s, [10.0, 0.0, 10.0, 10.0], "#ee1100");
rect(&mut s, [20.0, 0.0, 10.0, 10.0], "#0000ff");
let preview = |s: &mut Session, p: Value| run(s, "document.exportForWeb.preview", p);
let sources = |v: &Value| -> Vec<String> {
let mut out: Vec<String> =
v["colors"].as_array().unwrap().iter().filter(|c| c["transparent"] == false).map(|c| c["source"].as_str().unwrap().to_string()).collect();
out.sort();
out
};
let base = preview(&mut s, json!({"dither": "none"}));
assert_eq!(base["colors"].as_array().unwrap().len(), 4, "{base}");
for format in ["gif", "png8"] {
let p = json!({"format": format, "dither": "none", "colorTable": {"deleted": ["#EE1100"]}});
let v = preview(&mut s, p.clone());
assert_eq!(v["colors"].as_array().unwrap().len(), 3, "{format}: {v}");
assert!(v["colors"].as_array().unwrap().iter().any(|c| c["transparent"] == true), "{format}: the transparent entry stays");
assert_eq!(sources(&v), ["#0000ff", "#ff0000"], "{format}");
let file = one(&mut s, p);
assert_eq!(v["bytes"].as_u64(), Some(file.len() as u64), "{format}: the preview is the file");
let img = pixels(&file);
assert_eq!(img.get_pixel(15, 5).0, [255, 0, 0, 255], "{format}: the nearest color left");
assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(25, 5).0, img.get_pixel(35, 5).0[3]), ([255, 0, 0, 255], [0, 0, 255, 255], 0));
assert_eq!(distinct(&img), 3, "{format}");
}
// A color the table does not hold is no edit; sorting does not bring a deleted one back.
assert_eq!(sources(&preview(&mut s, json!({"dither": "none", "colorTable": {"deleted": ["#123456"]}}))).len(), 3);
let sorted = preview(&mut s, json!({"dither": "none", "colorTable": {"deleted": ["#ee1100"], "sort": "luminance"}}));
assert_eq!(sources(&sorted), ["#0000ff", "#ff0000"]);
// A fixed palette: colors it lacks are not made again, and deletions come out of it.
let fixed = preview(&mut s, json!({"dither": "none", "colorTable": {"customPalette": ["#0000ff", "#ff0000"]}}));
assert_eq!(sources(&fixed), ["#0000ff", "#ff0000"]);
let fixed = preview(&mut s, json!({"dither": "none", "colorTable": {"customPalette": ["#0000ff", "#ff0000"], "deleted": ["#ff0000"]}}));
assert_eq!(sources(&fixed), ["#0000ff"]);
// At most `colors` entries of a fixed palette, the transparent one included.
let two = preview(&mut s, json!({"dither": "none", "colors": 2, "colorTable": {"customPalette": ["#0000ff", "#ff0000"]}}));
assert_eq!(sources(&two), ["#0000ff"]);
// Deleting every opaque color is refused: the pixels need a color.
// Colors mapped to transparent do not count as left.
for table in [
json!({"deleted": ["#ff0000", "#ee1100", "#0000ff"]}),
json!({"customPalette": ["#ff0000"], "deleted": ["#ff0000"]}),
json!({"deleted": ["#0000ff", "#ee1100"], "transparent": ["#ff0000"]}),
json!({"customPalette": ["#ff0000", "#0000ff"], "deleted": ["#0000ff"], "transparent": ["#ff0000"]}),
] {
let p = json!({"colorTable": table});
let e = s.execute("document.exportForWeb.preview", &p).err().map(|e| e.to_string()).unwrap_or_default();
assert!(e.contains(cmd::webexport::KEEP_ONE), "{p}: {e}");
assert!(s.execute("document.exportForWeb", &p).is_err(), "{p}");
}
for bad in [
json!({"colorTable": {"deleted": ["nope"]}}),
json!({"colorTable": {"customPalette": ["#ff000080"]}}),
json!({"colorTable": {"deleted": vec!["#ff0000"; 257]}}),
] {
assert!(s.execute("document.exportForWeb", &bad).is_err(), "{bad}");
assert!(s.execute("webExport.settings", &bad).is_err(), "{bad}");
}
// A deleted color leaves the other lists; JPEG and PNG-24 have no table to edit.
let table = json!({
"deleted": ["#ee1100"], "customPalette": ["#ff0000", "#ee1100", "#0000ff"], "locked": ["#EE1100", "#0000ff"],
"transparent": ["#ee1100"], "webShift": ["#ee1100"],
});
let r = run(&mut s, "webExport.settings", json!({ "colorTable": table }));
let t = r["settings"]["colorTable"].clone();
assert_eq!((&t["locked"], &t["transparent"], &t["webShift"]), (&json!(["#0000ff"]), &json!([]), &json!([])));
assert_eq!(t["deleted"], json!(["#ee1100"]));
for format in ["jpg", "png24"] {
assert!(preview(&mut s, json!({"format": format, "colorTable": t.clone()})).get("colors").is_none(), "{format}");
}
// The remembered edit survives other keys and a format change, and goes with another reduction.
let r = run(&mut s, "webExport.settings", json!({"colors": 64, "format": "png8"}));
assert_eq!(r["settings"]["colorTable"]["deleted"], json!(["#ee1100"]));
let r = run(&mut s, "webExport.settings", json!({"reduction": "adaptive"}));
assert_eq!((&r["settings"]["colorTable"]["deleted"], &r["settings"]["colorTable"]["customPalette"]), (&json!([]), &json!([])));
// A saved preset keeps the edit.
run(&mut s, "webExport.presets.save", json!({"name": "No near red", "dither": "none", "colorTable": {"deleted": ["#ee1100"]}}));
assert_eq!(sources(&preview(&mut s, json!({"preset": "No near red"}))), ["#0000ff", "#ff0000"]);
}
#[test]
fn presets_and_remembered_settings() {
let mut s = two_colours();