From b2e390f18f0ec48f0125920e70fd73a8149f7445 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 21:40:50 -0800 Subject: [PATCH 1/4] Save for Web: Transparency Dither makes a share of partly transparent pixels clear With Transparency on, GIF and PNG-8 now offer Transparency Dither: No Transparency Dither (the default, the half-opacity cut as before), Diffusion with an Amount, Pattern and Noise. The help page describes the four methods and the Diffusion amount: https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=400 - render: `clear_mask` decides which pixels take the transparent entry. Diffusion spreads the opacity error Floyd-Steinberg style over two rows, scaled by the amount; Pattern uses the 8x8 ordered matrix and Noise a fixed coordinate hash, so the same art always gives the same file. Fully clear and fully opaque pixels do not change. `quantize_locked`, `quantize_to`, `nearest_entries` and the fixed-palette path use it. - engine: `document.exportForWeb`, its preview, `webExport.settings` and presets take `transparencyDither` (none, diffusion, pattern, noise) and `transparencyDitherAmount` (0 to 100, default 100). An unknown method or an amount over 100 is refused; settings saved without the keys take the defaults. - ui: the Transparency Dither row sits under Transparency, with an Amount slider for Diffusion; both are disabled while Transparency is off and keep their values. Rows for the five labels are in every complete catalog. The matrix, the noise, the amount mapping and the defaults' combination with the matte are VectorCraft's own rules. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/colorcmds.rs | 11 +- crates/engine/src/cmd/fileio/encode.rs | 1 + crates/engine/src/cmd/webexport.rs | 20 ++- crates/engine/src/tests/webexport.rs | 86 +++++++++++++ crates/render/src/encode/quantize.rs | 119 ++++++++++++++---- crates/render/src/encode/tests_palette.rs | 78 +++++++++++- crates/ui-egui/src/dialogs/save_for_web.rs | 22 +++- .../ui-egui/src/dialogs/tests_save_for_web.rs | 55 ++++++++ crates/ui-egui/src/i18n/bg.tsv | 5 + crates/ui-egui/src/i18n/bs.tsv | 5 + crates/ui-egui/src/i18n/ca.tsv | 5 + crates/ui-egui/src/i18n/cs.tsv | 5 + crates/ui-egui/src/i18n/da.tsv | 5 + crates/ui-egui/src/i18n/de.tsv | 5 + crates/ui-egui/src/i18n/el.tsv | 5 + crates/ui-egui/src/i18n/es.tsv | 5 + crates/ui-egui/src/i18n/fi.tsv | 5 + crates/ui-egui/src/i18n/fr.tsv | 5 + crates/ui-egui/src/i18n/gu.tsv | 5 + crates/ui-egui/src/i18n/hi.tsv | 5 + crates/ui-egui/src/i18n/hu.tsv | 5 + crates/ui-egui/src/i18n/id.tsv | 5 + crates/ui-egui/src/i18n/it.tsv | 5 + crates/ui-egui/src/i18n/ja.tsv | 5 + crates/ui-egui/src/i18n/ka.tsv | 5 + crates/ui-egui/src/i18n/ko.tsv | 5 + crates/ui-egui/src/i18n/nl.tsv | 5 + crates/ui-egui/src/i18n/pl.tsv | 5 + crates/ui-egui/src/i18n/pt-br.tsv | 5 + crates/ui-egui/src/i18n/ru.tsv | 5 + crates/ui-egui/src/i18n/sv.tsv | 5 + crates/ui-egui/src/i18n/tests.rs | 12 ++ crates/ui-egui/src/i18n/tr.tsv | 5 + crates/ui-egui/src/i18n/uk.tsv | 5 + crates/ui-egui/src/i18n/vi.tsv | 5 + crates/ui-egui/src/i18n/zh-hans.tsv | 5 + crates/ui-egui/src/i18n/zh-hant.tsv | 5 + docs/mcp.md | 13 +- docs/target-app-parity.md | 1 + 39 files changed, 522 insertions(+), 36 deletions(-) diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index a9dee00af3..4be925b0cd 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -701,8 +701,15 @@ impl Indexing { v.as_f64().filter(|x| (0.0..=100.0).contains(x)).ok_or_else(|| bad(C, "`ditherAmount` must be a number from 0 to 100"))?.round() as u8 } }; - let options = - |r: Reduction| PaletteOptions { colors: colors.unwrap_or(256), reduction: r, dither, dither_amount, transparency: true, matte: None }; + let options = |r: Reduction| PaletteOptions { + colors: colors.unwrap_or(256), + reduction: r, + dither, + dither_amount, + transparency: true, + matte: None, + ..PaletteOptions::default() + }; let refuse_colors = |name: &str| match colors { Some(_) => Err(bad(C, format!("`colors` does not apply to the {name} reduction"))), None => Ok(()), diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 1ecb41290e..23b7a1c13f 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -348,6 +348,7 @@ impl RasterOptions { Some(v) => background(v).map_err(|e| bad(C, format!("matte: {e}")))?, None => Some([255; 3]), }, + ..PaletteOptions::default() }, tiff: TiffOptions { color_model, diff --git a/crates/engine/src/cmd/webexport.rs b/crates/engine/src/cmd/webexport.rs index 498982a7f9..e9d480c5eb 100644 --- a/crates/engine/src/cmd/webexport.rs +++ b/crates/engine/src/cmd/webexport.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "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, 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, its transparent colors taking one slot together; a new reduction without colorTable clears it and deleted), shifted?: {\"#source\": \"#rrggbb\"…} (each source color is written as the color given, wherever it is in the image; kept when reducing as a locked color is, before the locked ones, while one palette slot is left for the reduction; at most 256; a source the table does not hold shifts nothing; a color shifted to itself is removed; a shifted color is not web-shifted, and a transparent one stays transparent; GIF lossy moves no pixel into or out of a shifted color)} (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/.), output?: images (default)|html (an HTML page placing the image or slices, .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, its transparent colors taking one slot together; a new reduction without colorTable clears it and deleted), shifted?: {\"#source\": \"#rrggbb\"…} (each source color is written as the color given, wherever it is in the image; kept when reducing as a locked color is, before the locked ones, while one palette slot is left for the reduction; at most 256; a source the table does not hold shifts nothing; a color shifted to itself is removed; a shifted color is not web-shifted, and a transparent one stays transparent; GIF lossy moves no pixel into or out of a shifted color)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (gif/png8 with transparency: partly transparent pixels become transparent or keep their color in a dither, about as many keeping it as their opacity says with pattern, noise or diffusion at amount 100; fully transparent and opaque pixels do not change), transparencyDitherAmount?: 100 (0–100: the diffusion dither's strength, a lower amount closer to none, 0 as none), 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/.), output?: images (default)|html (an HTML page placing the image or slices, .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 ), @@ -398,6 +398,12 @@ pub struct WebSettings { pub dither_amount: u8, /// Keep transparent pixels transparent (GIF, PNG-8, PNG-24). pub transparency: bool, + /// GIF and PNG-8 with `transparency`: how partly transparent pixels are split between the + /// transparent entry and their color (`none`: under half opacity is transparent). + #[serde(serialize_with = "ser_key", deserialize_with = "de_key")] + pub transparency_dither: Dither, + /// 0–100: the strength of the `diffusion` transparency dither. + pub transparency_dither_amount: u8, /// What partly transparent edges blend into (JPEG and opaque PNG-24: the background): `white`, /// `black`, `none` or `#rrggbb`. pub matte: String, @@ -444,6 +450,8 @@ impl Default for WebSettings { dither: Dither::Diffusion, dither_amount: 100, transparency: true, + transparency_dither: Dither::None, + transparency_dither_amount: 100, matte: "white".into(), interlaced: false, web_snap: 0, @@ -492,6 +500,10 @@ impl WebSettings { fn checked(mut self) -> std::result::Result { self.colors = self.colors.clamp(2, 256); self.dither_amount = self.dither_amount.min(100); + if self.transparency_dither_amount > 100 { + let key = "transparencyDitherAmount"; + return Err(format!("`{key}` must be from 0 to 100")); + } self.web_snap = self.web_snap.min(100); self.lossy = self.lossy.min(100); self.quality = self.quality.min(100); @@ -799,6 +811,8 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8 dither_amount: s.dither_amount, transparency: s.transparency, matte, + transparency_dither: s.transparency_dither, + transparency_dither_amount: s.transparency_dither_amount, }; let mut ix = reduced(rgba, w, h, s, &o, &kept)?; // Map to transparent works on the colours the reduction made. @@ -889,7 +903,7 @@ fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, loc 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 has_clear = quantize::clear_mask(rgba, w, o).contains(&true); let removed = custom.iter().any(|c| deleted.contains(c)); let mut left: Vec<[u8; 3]> = vec![]; for c in custom { @@ -941,7 +955,7 @@ fn clear_dropped(ix: &mut Indexed, rgba: &[u8], o: &PaletteOptions, kept: &[[u8; return; } let all: Vec<[u8; 3]> = kept.iter().chain(&dropped).copied().collect(); - let near = quantize::nearest_entries(rgba, o, &all); + let near = quantize::nearest_entries(rgba, ix.width, o, &all); if !near.iter().any(|n| n.is_some_and(|n| n >= kept.len())) { return; } diff --git a/crates/engine/src/tests/webexport.rs b/crates/engine/src/tests/webexport.rs index fe3deecbef..34d8cd41dd 100644 --- a/crates/engine/src/tests/webexport.rs +++ b/crates/engine/src/tests/webexport.rs @@ -163,6 +163,92 @@ fn gif_transparency_index_and_map_to_transparent() { assert_eq!(pixels(&gif).get_pixel(25, 15)[3], 0, "index {i}"); } +/// 40×30: red at 25% opacity on the left half, blue at 75% on the right, nothing behind them. +fn see_through() -> Session { + let mut s = session(40.0, 30.0); + rect(&mut s, [0.0, 0.0, 20.0, 30.0], "#ff0000"); + run(&mut s, "transparency.set", json!({"opacity": 25})); + rect(&mut s, [20.0, 0.0, 20.0, 30.0], "#0000ff"); + run(&mut s, "transparency.set", json!({"opacity": 75})); + s +} + +/// The shares of the left and right halves' pixels that are opaque. +fn opaque_halves(img: &image::RgbaImage) -> [f64; 2] { + [0, 20].map(|x0| (x0..x0 + 20).flat_map(|x| (0..30).map(move |y| (x, y))).filter(|&(x, y)| img.get_pixel(x, y)[3] == 255).count() as f64 / 600.0) +} + +#[test] +fn transparency_dither_keeps_a_share_of_partly_transparent_pixels() { + let mut s = see_through(); + for format in ["gif", "png8"] { + let file = |s: &mut Session, extra: Value| { + let mut p = json!({"format": format, "antiAlias": "none"}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + one(s, p) + }; + // By default the pixels under half opacity are transparent and the others opaque. + let none = file(&mut s, json!({})); + assert_eq!(opaque_halves(&pixels(&none)), [0.0, 1.0], "{format}"); + assert_eq!(file(&mut s, json!({"transparencyDither": "none"})), none, "{format}"); + assert_eq!(file(&mut s, json!({"transparencyDither": "diffusion", "transparencyDitherAmount": 0})), none, "{format}"); + for method in ["diffusion", "pattern", "noise"] { + let p = json!({"transparencyDither": method}); + let dithered = file(&mut s, p.clone()); + let [left, right] = opaque_halves(&pixels(&dithered)); + assert!((left - 0.25).abs() < 0.1 && (right - 0.75).abs() < 0.1, "{format} {method}: {left} {right}"); + if format == "gif" { + assert_eq!(gif_transparent_index(&dithered), Some(0), "{method}"); + } + assert_eq!(file(&mut s, p.clone()), dithered, "{format} {method}: the same art gives the same file"); + // The preview shows what Save writes. + let mut pv = json!({"format": format, "antiAlias": "none", "image": true}); + pv["transparencyDither"] = json!(method); + let shown = run(&mut s, "document.exportForWeb.preview", pv); + assert_eq!(vectorcraft_format::base64_decode(shown["dataBase64"].as_str().unwrap()).unwrap(), dithered, "{format} {method}"); + // Without transparency the dither does nothing. + let opaque = file(&mut s, json!({"transparencyDither": method, "transparency": false})); + assert_eq!(opaque, file(&mut s, json!({"transparency": false})), "{format} {method}"); + } + // A fixed palette keeps the transparent entry for the dithered pixels. + let fixed = file(&mut s, json!({"transparencyDither": "pattern", "colorTable": {"customPalette": ["#ffbfbf", "#4040ff"]}})); + let [left, right] = opaque_halves(&pixels(&fixed)); + assert!(left > 0.0 && left < 1.0 && right > 0.0 && right < 1.0, "{format}: {left} {right}"); + } +} + +#[test] +fn transparency_dither_settings_are_checked_and_remembered() { + let mut s = see_through(); + for bad in [ + json!({"transparencyDither": "spray"}), + json!({"transparencyDither": 3}), + json!({"transparencyDitherAmount": 101}), + json!({"transparencyDitherAmount": -1}), + ] { + assert!(s.execute("document.exportForWeb", &bad).is_err(), "{bad}"); + assert!(s.execute("webExport.settings", &bad).is_err(), "{bad}"); + } + let e = s.execute("document.exportForWeb", &json!({"transparencyDitherAmount": 101})).unwrap_err().to_string(); + assert!(e.contains("`transparencyDitherAmount` must be from 0 to 100"), "{e}"); + assert_eq!(defaults()["transparencyDither"], "none"); + assert_eq!(defaults()["transparencyDitherAmount"], 100); + // The remembered settings and a saved preset keep both. + let set = run(&mut s, "webExport.settings", json!({"transparencyDither": "diffusion", "transparencyDitherAmount": 40})); + assert_eq!((&set["settings"]["transparencyDither"], &set["settings"]["transparencyDitherAmount"]), (&json!("diffusion"), &json!(40))); + let read = run(&mut s, "webExport.settings", json!({})); + assert_eq!(read["settings"], set["settings"]); + run(&mut s, "webExport.presets.save", json!({"name": "Soft edges", "transparencyDither": "noise", "transparencyDitherAmount": 60})); + let list = run(&mut s, "webExport.presets.list", json!({})); + let saved = list["presets"].as_array().unwrap().iter().find(|p| p["name"] == "Soft edges").unwrap(); + assert_eq!((&saved["settings"]["transparencyDither"], &saved["settings"]["transparencyDitherAmount"]), (&json!("noise"), &json!(60))); + let by_preset = one(&mut s, json!({"preset": "Soft edges", "format": "gif", "antiAlias": "none"})); + assert_eq!(by_preset, one(&mut s, json!({"format": "gif", "antiAlias": "none", "transparencyDither": "noise", "transparencyDitherAmount": 60}))); + // Settings saved before the keys existed take the defaults. + let old: cmd::webexport::WebSettings = serde_json::from_value(json!({"format": "png8", "dither": "pattern"})).unwrap(); + assert_eq!((old.transparency_dither.id(), old.transparency_dither_amount), ("none", 100)); +} + #[test] fn jpeg_size_grows_with_quality() { let mut s = many_colours(); diff --git a/crates/render/src/encode/quantize.rs b/crates/render/src/encode/quantize.rs index fff66aa142..96b9ffe338 100644 --- a/crates/render/src/encode/quantize.rs +++ b/crates/render/src/encode/quantize.rs @@ -1,8 +1,9 @@ //! Colour reduction for palette formats (PNG-8, GIF): a palette of at most 256 colours chosen by //! median cut over a 15-bit histogram (refined by a few k-means passes) or a fixed palette, then //! each pixel mapped to its nearest entry with optional dithering (Floyd–Steinberg diffusion, an -//! 8×8 ordered pattern, or noise). Pixels under half opacity can become one transparent entry; -//! the others are blended over the matte colour. +//! 8×8 ordered pattern, or noise). Pixels under half opacity can become one transparent entry, or +//! with a transparency dither a share of the partly transparent pixels that follows their +//! opacity; the others are blended over the matte color. use std::collections::HashMap; @@ -111,11 +112,18 @@ pub struct PaletteOptions { pub dither: Dither, /// Dither strength 0–100. pub dither_amount: u8, - /// Pixels under half opacity become a transparent entry; otherwise every pixel is opaque. + /// Pixels under half opacity become a transparent entry (see `transparency_dither`); + /// otherwise every pixel is opaque. pub transparency: bool, /// The colour partly transparent pixels are blended over. `None`: with transparency, they /// keep their own colour (hard edges); without, white. pub matte: Option<[u8; 3]>, + /// With `transparency`, how partly transparent pixels are split between the transparent entry + /// and their color ([`clear_mask`]); `Dither::None` cuts them at half opacity. + pub transparency_dither: Dither, + /// The strength of the diffusion transparency dither, 0–100 (0 cuts at half opacity); the + /// pattern and noise methods do not use it. + pub transparency_dither_amount: u8, } impl Default for PaletteOptions { @@ -127,6 +135,8 @@ impl Default for PaletteOptions { dither_amount: 100, transparency: true, matte: Some([255; 3]), + transparency_dither: Dither::None, + transparency_dither_amount: 100, } } } @@ -153,12 +163,12 @@ pub fn quantize(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions) -> Ind /// them all anyway; locked colours no pixel ends up using are left out. pub fn quantize_locked(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, locked: &[[u8; 3]]) -> Indexed { let px = rgba.as_chunks::<4>().0; - let clear = |p: &[u8; 4]| o.transparency && p[3] < 128; + let clear = clear_mask(rgba, width, o); let matte = o.matte.unwrap_or([255; 3]); let colors = opaque_colors(px, o, matches!(o.reduction, Reduction::Gray | Reduction::BlackWhite)); - let has_clear = px.iter().any(clear); + let has_clear = clear.contains(&true); let k = (o.colors.clamp(2, 256) as usize - usize::from(has_clear)).max(1); - let opaque = || colors.iter().zip(px).filter(|(_, p)| !clear(p)).map(|(c, _)| *c); + let opaque = || colors.iter().zip(&clear).filter(|(_, c)| !**c).map(|(c, _)| *c); // Locked colours take their slots first (at least one is left for the reduction). let mut lock: Vec<[u8; 3]> = Vec::with_capacity(locked.len().min(k)); for c in locked { @@ -185,7 +195,7 @@ pub fn quantize_locked(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, if palette.is_empty() { palette.push(matte); } - finish(px, &colors, width, height, &palette, o, if exact { Dither::None } else { o.dither }) + finish(&clear, &colors, width, height, &palette, o, if exact { Dither::None } else { o.dither }) } /// [`quantize`] to the fixed `palette`: each pixel takes its nearest entry, with `o`'s dither, @@ -195,27 +205,82 @@ pub fn quantize_locked(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, pub fn quantize_to(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, palette: &[[u8; 3]]) -> Indexed { let px = rgba.as_chunks::<4>().0; let colors = opaque_colors(px, o, false); - let has_clear = o.transparency && px.iter().any(|p| p[3] < 128); + let clear = clear_mask(rgba, width, o); + let has_clear = clear.contains(&true); let mut palette: Vec<[u8; 3]> = palette.iter().take(256 - usize::from(has_clear)).copied().collect(); if palette.is_empty() { palette.push(o.matte.unwrap_or([255; 3])); } - finish(px, &colors, width, height, &palette, o, o.dither) + finish(&clear, &colors, width, height, &palette, o, o.dither) } -/// For each pixel of `rgba`, the entry of `palette` nearest its color, as [`quantize_to`] measures -/// it (the matte, transparency and `o.reduction`'s distance weights) without dither; `None` for a -/// pixel that becomes transparent, and for every pixel when `palette` is empty. -pub fn nearest_entries(rgba: &[u8], o: &PaletteOptions, palette: &[[u8; 3]]) -> Vec> { +/// For each pixel of `rgba` (`width` pixels a row), the entry of `palette` nearest its color, as +/// [`quantize_to`] measures it (the matte, transparency and `o.reduction`'s distance weights) +/// without dither; `None` for a pixel that becomes transparent ([`clear_mask`]), and for every +/// pixel when `palette` is empty. +pub fn nearest_entries(rgba: &[u8], width: u32, o: &PaletteOptions, palette: &[[u8; 3]]) -> Vec> { let px = rgba.as_chunks::<4>().0; let colors = opaque_colors(px, o, false); + let clear = clear_mask(rgba, width, o); let pal: Vec<[f32; 3]> = palette.iter().map(|c| c.map(f32::from)).collect(); let index = PaletteIndex::new(&pal, o.reduction.weights()); - colors - .iter() - .zip(px) - .map(|(c, p)| if pal.is_empty() || (o.transparency && p[3] < 128) { None } else { Some(index.nearest(c.map(f32::from))) }) - .collect() + colors.iter().zip(&clear).map(|(c, &clear)| if pal.is_empty() || clear { None } else { Some(index.nearest(c.map(f32::from))) }).collect() +} + +/// Which pixels of `rgba` (`width` pixels a row) become the transparent entry. Without +/// `o.transparency`, none. Otherwise fully transparent pixels always do and opaque ones never; a +/// partly transparent pixel does under half opacity with no transparency dither, and else by +/// `o.transparency_dither`. With pattern, noise, or diffusion at amount 100, about as many of an +/// area's pixels stay opaque as its opacity says; a lower diffusion amount moves the result toward +/// the cut at half opacity. Diffusion spreads each pixel's opacity error to the pixels right of it +/// and below it (Floyd–Steinberg, scaled by `o.transparency_dither_amount`), pattern compares the +/// opacity with the 8×8 ordered pattern and noise with a noise threshold. The result depends only +/// on the pixels and the options, so exports are reproducible. +pub fn clear_mask(rgba: &[u8], width: u32, o: &PaletteOptions) -> Vec { + let px = rgba.as_chunks::<4>().0; + if !o.transparency { + return vec![false; px.len()]; + } + let width = (width as usize).min(px.len()).max(1); + let amount = f32::from(o.transparency_dither_amount.min(100)) / 100.0; + let dither = match o.transparency_dither { + Dither::Diffusion if amount == 0.0 => Dither::None, + d => d, + }; + // Two rows of opacity error for diffusion (the current one and the next), one pixel of margin + // on each side. + let mut err = vec![0f32; if dither == Dither::Diffusion { 2 * (width + 2) } else { 0 }]; + let half = err.len() / 2; + let mut out = Vec::with_capacity(px.len()); + for (y, row) in px.chunks(width).enumerate() { + let (cur, next) = err.split_at_mut(half); + next.fill(0.0); + for (x, p) in row.iter().enumerate() { + let a = f32::from(p[3]); + let clear = match (p[3], dither) { + (0, _) => true, + (255, _) => false, + (_, Dither::None) => p[3] < 128, + (_, Dither::Pattern) => a < 255.0 * bayer(x % 8, y % 8), + // Another noise than the color dither's, so the two do not line up. + (_, Dither::Noise) => a < 255.0 * noise(x ^ 0x5a5a, y ^ 0xa5a5), + (_, Dither::Diffusion) => { + let v = a + cur[x + 1]; + let clear = v < 127.5; + let e = (v - if clear { 0.0 } else { 255.0 }) * amount; + // 7/16 right, 3/16 below left, 5/16 below, 1/16 below right. + cur[x + 2] += e * 7.0 / 16.0; + next[x] += e * 3.0 / 16.0; + next[x + 1] += e * 5.0 / 16.0; + next[x + 2] += e / 16.0; + clear + } + }; + out.push(clear); + } + cur.copy_from_slice(next); + } + out } /// The color of each pixel when opaque: blended over the matte, and gray when `gray`. @@ -231,20 +296,20 @@ fn opaque_colors(px: &[[u8; 4]], o: &PaletteOptions, gray: bool) -> Vec<[u8; 3]> .collect() } -/// Map the pixels `px` (their opaque `colors`) to `palette` with `dither`, then drop the entries -/// no pixel uses and put the transparent entry first when a pixel is transparent. -fn finish(px: &[[u8; 4]], colors: &[[u8; 3]], width: u32, height: u32, palette: &[[u8; 3]], o: &PaletteOptions, dither: Dither) -> Indexed { - let clear = |p: &[u8; 4]| o.transparency && p[3] < 128; +/// Map the pixels (their opaque `colors`, transparent where `clear` says) to `palette` with +/// `dither`, then drop the entries no pixel uses and put the transparent entry first when a pixel +/// is transparent. +fn finish(clear: &[bool], colors: &[[u8; 3]], width: u32, height: u32, palette: &[[u8; 3]], o: &PaletteOptions, dither: Dither) -> Indexed { + let clear = |i: usize| clear.get(i).copied().unwrap_or(false); let matte = o.matte.unwrap_or([255; 3]); - let has_clear = px.iter().any(clear); + let has_clear = (0..colors.len()).any(clear); let weights = o.reduction.weights(); // (A width past the pixels there are would size the error rows from a number nothing checked.) - let mut indices = - map(colors, (width as usize).min(colors.len()), palette, weights, dither, f32::from(o.dither_amount.min(100)) / 100.0, |i| clear(&px[i])); + let mut indices = map(colors, (width as usize).min(colors.len()), palette, weights, dither, f32::from(o.dither_amount.min(100)) / 100.0, clear); // Drop the entries no pixel uses (fixed palettes), keeping the order. let mut used = [false; 256]; for (i, &ix) in indices.iter().enumerate() { - if !clear(&px[i]) { + if !clear(i) { used[ix as usize] = true; } } @@ -260,7 +325,7 @@ fn finish(px: &[[u8; 4]], colors: &[[u8; 3]], width: u32, height: u32, palette: } } for (i, ix) in indices.iter_mut().enumerate() { - *ix = if clear(&px[i]) { 0 } else { remap[*ix as usize] }; + *ix = if clear(i) { 0 } else { remap[*ix as usize] }; } Indexed { width, height, palette: kept, transparent: has_clear.then_some(0), indices } } diff --git a/crates/render/src/encode/tests_palette.rs b/crates/render/src/encode/tests_palette.rs index d9a8a2fc0f..8a377190f8 100644 --- a/crates/render/src/encode/tests_palette.rs +++ b/crates/render/src/encode/tests_palette.rs @@ -3,7 +3,7 @@ use vectorcraft_doc::{Appearance, Node}; use vectorcraft_geom::shapes; use super::png::{PngOptions, encode_indexed}; -use super::quantize::{Dither, Indexed, PaletteOptions, Reduction, quantize, quantize_to}; +use super::quantize::{Dither, Indexed, PaletteOptions, Reduction, clear_mask, nearest_entries, quantize, quantize_to}; use super::*; /// A `w`×`h` opaque image of `f(x, y)` colours. @@ -252,3 +252,79 @@ fn ids_round_trip() { assert_eq!(Dither::from_id(d.id()), Some(d)); } } + +/// A `w`×`h` red image whose pixels have the opacity `alpha(x, y)`. +fn see_through(w: u32, h: u32, alpha: impl Fn(u32, u32) -> u8) -> Vec { + (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).flat_map(|(x, y)| [255, 0, 0, alpha(x, y)]).collect() +} + +/// The share of the pixels of `ix` that are not transparent. +fn opaque_share(ix: &Indexed) -> f64 { + ix.indices.iter().filter(|&&i| ix.transparent != Some(i)).count() as f64 / ix.indices.len() as f64 +} + +fn alpha_dither(d: Dither, amount: u8) -> PaletteOptions { + PaletteOptions { transparency_dither: d, transparency_dither_amount: amount, ..Default::default() } +} + +#[test] +fn transparency_dither_keeps_about_as_many_pixels_as_their_opacity() { + let (w, h) = (32, 32); + for alpha in [64u8, 128, 191] { + let px = see_through(w, h, |_, _| alpha); + // No transparency dither cuts at half opacity, and so does Diffusion at 0. + let none = quantize(&px, w, h, &alpha_dither(Dither::None, 100)); + assert_eq!(opaque_share(&none), if alpha < 128 { 0.0 } else { 1.0 }, "none at {alpha}"); + assert_eq!(quantize(&px, w, h, &alpha_dither(Dither::Diffusion, 0)), none, "diffusion at 0, {alpha}"); + for d in [Dither::Diffusion, Dither::Pattern, Dither::Noise] { + let ix = quantize(&px, w, h, &alpha_dither(d, 100)); + let share = opaque_share(&ix); + assert!((share - f64::from(alpha) / 255.0).abs() < 0.08, "{d:?} at {alpha}: {share}"); + assert_eq!(ix.transparent, Some(0), "{d:?} at {alpha}"); + // The same pixels and options give the same image. + assert_eq!(quantize(&px, w, h, &alpha_dither(d, 100)), ix, "{d:?} at {alpha}"); + // A fixed palette and the nearest entries make the same pixels transparent. + let fixed = quantize_to(&px, w, h, &alpha_dither(d, 100), &[[255, 0, 0], [0, 0, 255]]); + assert_eq!(opaque_share(&fixed), share, "{d:?} at {alpha}, fixed palette"); + let near = nearest_entries(&px, w, &alpha_dither(d, 100), &[[255, 0, 0]]); + let mask = clear_mask(&px, w, &alpha_dither(d, 100)); + assert_eq!(near.iter().map(Option::is_none).collect::>(), mask, "{d:?} at {alpha}"); + } + // Diffusion at half strength keeps fewer pixels of a light area opaque than at full. + if alpha < 128 { + let half = opaque_share(&quantize(&px, w, h, &alpha_dither(Dither::Diffusion, 50))); + let full = opaque_share(&quantize(&px, w, h, &alpha_dither(Dither::Diffusion, 100))); + assert!(0.0 < half && half < full, "{alpha}: {half} {full}"); + } + } + // The methods arrange the pixels differently. + let px = see_through(w, h, |_, _| 96); + let masks: Vec> = [Dither::Diffusion, Dither::Pattern, Dither::Noise].map(|d| clear_mask(&px, w, &alpha_dither(d, 100))).into(); + assert!(masks[0] != masks[1] && masks[1] != masks[2] && masks[0] != masks[2]); +} + +#[test] +fn transparency_dither_leaves_clear_and_opaque_pixels_and_needs_transparency() { + let (w, h) = (16, 8); + // Fully transparent on the left, opaque on the right: every method keeps them as they are. + let hard = see_through(w, h, |x, _| if x < 8 { 0 } else { 255 }); + let none = clear_mask(&hard, w, &alpha_dither(Dither::None, 100)); + assert_eq!(none.iter().filter(|c| **c).count(), 64); + for d in Dither::ALL { + assert_eq!(clear_mask(&hard, w, &alpha_dither(d, 100)), none, "{d:?}"); + } + // Without transparency nothing is transparent, whatever the transparency dither. + let soft = see_through(w, h, |x, _| (x * 16) as u8); + for d in Dither::ALL { + let o = PaletteOptions { transparency: false, ..alpha_dither(d, 100) }; + assert!(!clear_mask(&soft, w, &o).contains(&true), "{d:?}"); + assert_eq!(quantize(&soft, w, h, &o).transparent, None, "{d:?}"); + } + // A palette of two entries keeps one for the transparent pixels and one for the others. + let o = PaletteOptions { colors: 2, ..alpha_dither(Dither::Pattern, 100) }; + let ix = quantize(&see_through(w, h, |_, _| 128), w, h, &o); + assert_eq!((ix.palette.len(), ix.transparent), (2, Some(0))); + // No pixels, and a width past the pixels there are. + assert!(clear_mask(&[], 0, &alpha_dither(Dither::Diffusion, 100)).is_empty()); + assert_eq!(clear_mask(&see_through(3, 1, |_, _| 200), 1000, &alpha_dither(Dither::Diffusion, 100)).len(), 3); +} diff --git a/crates/ui-egui/src/dialogs/save_for_web.rs b/crates/ui-egui/src/dialogs/save_for_web.rs index 7376973d6f..f141e4bef8 100644 --- a/crates/ui-egui/src/dialogs/save_for_web.rs +++ b/crates/ui-egui/src/dialogs/save_for_web.rs @@ -1,7 +1,7 @@ //! File → Export → Save for Web (Legacy) (`saveForWeb`, Ctrl/Cmd+Alt+Shift+S): the art previewed //! as the web image Save writes, beside the original (Original, Optimized, 2-Up and 4-Up views, //! each with its file size and download time), and the settings: format (GIF, JPEG, PNG-8, -//! PNG-24), colour reduction, colours, dither, transparency and matte, interlacing, web snap, +//! PNG-24), color reduction, colors, dither, transparency and its dither, matte, interlacing, web snap, //! lossy, JPEG quality, the colour table (lock, map to transparent, web shift, sort, Delete Color, //! Restore Generated Table, a double-click that shifts a color to one picked in the Color Picker, //! and Unshift All Colors), image size and anti-aliasing, Clip to Artboard, sRGB, metadata, @@ -823,6 +823,7 @@ fn side(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, s: Option<& slider_row(ui, d, "ditherAmount", tl!("Amount:"), "%"); } check_pair(ui, d, ("transparency", tl!("Transparency")), ("interlaced", tl!("Interlaced"))); + transparency_dither_rows(ui, d); matte_row(ui, d); slider_row(ui, d, "webSnap", tl!("Web Snap:"), "%"); if format == WebFormat::Gif { @@ -1083,6 +1084,25 @@ fn slider_row(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, suffix: }); } +/// The Transparency Dither choices of GIF and PNG-8, as (`transparencyDither` value, label). +pub(crate) const TRANSPARENCY_DITHERS: [(&str, &str); 4] = [ + ("none", "No Transparency Dither"), + ("diffusion", "Diffusion Transparency Dither"), + ("pattern", "Pattern Transparency Dither"), + ("noise", "Noise Transparency Dither"), +]; + +/// Transparency Dither and, for Diffusion, its Amount; both are disabled while Transparency is off +/// and keep their values. +fn transparency_dither_rows(ui: &mut egui::Ui, d: &mut Dialog) { + ui.add_enabled_ui(d.bool("transparency"), |ui| { + form::choice(ui, d, "transparencyDither", &crate::i18n::colon(tl!("Transparency Dither")), (LABEL_W, FIELD_W), &TRANSPARENCY_DITHERS); + if Dither::from_id(&d.str("transparencyDither")) == Some(Dither::Diffusion) { + slider_row(ui, d, "transparencyDitherAmount", tl!("Amount:"), "%"); + } + }); +} + /// The palette size: the usual counts, or any 2–256. fn colors_row(ui: &mut egui::Ui, d: &mut Dialog) { widgets::label_row(ui, tl!("Colors:"), LABEL_W, |ui| { 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..69de7dd031 100644 --- a/crates/ui-egui/src/dialogs/tests_save_for_web.rs +++ b/crates/ui-egui/src/dialogs/tests_save_for_web.rs @@ -255,6 +255,61 @@ fn every_view_and_format_draws() { assert_eq!(kind(&app), Some(save_for_web::KIND)); } +/// GIF and PNG-8 show Transparency Dither under Transparency, with an Amount slider for Diffusion; +/// both are disabled while Transparency is off and keep their values, PNG-24 does not show them, and +/// Done remembers them. +#[test] +fn transparency_dither_rows_follow_transparency_and_the_method() { + use egui::accesskit::Role; + use egui_kittest::kittest::{By, NodeT, Queryable}; + type H<'a> = egui_kittest::Harness<'a, VectorcraftApp>; + let dir = vectorcraft_testkit::temp_dir("sfw-transparency-dither"); + let (mut app, _) = app(&dir, false); + app.run("file.saveForWeb", json!({})).unwrap(); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1200.0, 1200.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + show(app, ui.ctx()); + }, + app, + ); + h.run_steps(4); + let disabled = |h: &H, value: &'static str| h.query(By::new().role(Role::ComboBox).value(value)).map(|n| n.accesskit_node().is_disabled()); + let sliders = |h: &H| h.query_all(By::new().role(Role::Slider)).count(); + let field = |h: &H, key: &str| h.state().ui.dialog.as_ref().unwrap().fields[key].clone(); + assert_eq!(disabled(&h, "No Transparency Dither"), Some(false)); + let before = sliders(&h); + h.get(By::new().role(Role::ComboBox).value("No Transparency Dither")).click(); + h.run(); + h.get_by_label("Diffusion Transparency Dither").click(); + h.run(); + assert_eq!(field(&h, "transparencyDither"), json!("diffusion")); + assert_eq!(sliders(&h), before + 1, "Diffusion has an Amount"); + // Transparency off: the rows are disabled and keep their values. + set(h.state_mut(), "transparency", json!(false)); + h.run(); + assert_eq!(disabled(&h, "Diffusion Transparency Dither"), Some(true)); + assert_eq!(field(&h, "transparencyDither"), json!("diffusion")); + // PNG-24 has no transparency dither; PNG-8 has it again. + set(h.state_mut(), "format", json!("png24")); + h.run(); + assert_eq!(disabled(&h, "Diffusion Transparency Dither"), None); + set(h.state_mut(), "format", json!("png8")); + set(h.state_mut(), "transparency", json!(true)); + set(h.state_mut(), "transparencyDitherAmount", json!(35)); + h.run(); + assert_eq!(disabled(&h, "Diffusion Transparency Dither"), Some(false)); + // Done remembers them. + set(h.state_mut(), "discard", json!(true)); + confirm(h.state_mut()).unwrap(); + let s = h.state().session.last_web_settings(); + assert_eq!((s.transparency_dither, s.transparency_dither_amount), (vectorcraft_render::encode::quantize::Dither::Diffusion, 35)); +} + #[test] fn save_remembers_and_writes_and_done_only_remembers() { let dir = vectorcraft_testkit::temp_dir("sfw-save"); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 167737554d..25745dd946 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -919,6 +919,11 @@ font-technology Variable Променливи Distribute Spacing Разпределение на разстоянията Distribute Spacing: Разпределение на разстоянията: Dither: Дитъринг: + Transparency Dither Дитъринг на прозрачността + No Transparency Dither Без дитъринг на прозрачността + Diffusion Transparency Dither Дифузен дитъринг на прозрачността + Pattern Transparency Dither Дитъринг на прозрачността с мостра + Noise Transparency Dither Шумов дитъринг на прозрачността Divide Разделяне Divide Horizontally Into Разделяне хоризонтално на Divide Objects Below Разделяне на обектите отдолу diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a9d6e35ed8..7fe312238e 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3174,6 +3174,11 @@ antiAlias Sharp Oštro Convert to sRGB Pretvori u sRGB Delete this saved preset Izbriši ovaj sačuvani predložak Dither: Dithering: + Transparency Dither Dithering prozirnosti + No Transparency Dither Bez ditheringa prozirnosti + Diffusion Transparency Dither Difuzijski dithering prozirnosti + Pattern Transparency Dither Dithering prozirnosti uzorkom + Noise Transparency Dither Dithering prozirnosti šumom Fit in View Uklopi u prikaz Format: Format: WebP WebP diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..8d41f90f4a 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1360,6 +1360,11 @@ arrowhead Target Diana Distribute Spacing: Distribueix l’espaiat: Dither Tramatge Dither: Tramatge: + Transparency Dither Tramatge de transparència + No Transparency Dither Sense tramatge de transparència + Diffusion Transparency Dither Tramatge de transparència per difusió + Pattern Transparency Dither Tramatge de transparència per motiu + Noise Transparency Dither Tramatge de transparència per soroll Divide Divideix Divide and Outline Will Remove Unpainted Artwork Divideix i contorneja eliminarà l’art no pintat Divide Horizontally Into Divideix horitzontalment en diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..616c0c91dc 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3257,6 +3257,11 @@ antiAlias Sharp Ostré Convert to sRGB Převést na sRGB Delete this saved preset Odstranit toto uložené přednastavení Dither: Rozptýlení: + Transparency Dither Rozptýlení průhlednosti + No Transparency Dither Bez rozptylu průhlednosti + Diffusion Transparency Dither Difuzní rozptýlení průhlednosti + Pattern Transparency Dither Rozptýlení průhlednosti vzorkem + Noise Transparency Dither Rozptýlení průhlednosti šumem Fit in View Přizpůsobit zobrazení Format: Formát: WebP WebP diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..330aa68fa8 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5786,6 +5786,11 @@ antiAlias Sharp Skarp Convert to sRGB Konvertér til sRGB Delete this saved preset Slet denne gemte forudindstilling Dither: Dither: + Transparency Dither Gennemsigtighedsdithering + No Transparency Dither Ingen gennemsigtighedsdithering + Diffusion Transparency Dither Diffusionsdithering af gennemsigtighed + Pattern Transparency Dither Mønsterdithering af gennemsigtighed + Noise Transparency Dither Støjdithering af gennemsigtighed Fit in View Tilpas i visning Format: Format: WebP WebP diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..31c86fbf0d 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -940,6 +940,11 @@ font-technology Variable Variabel Distribute Spacing Abstand verteilen Distribute Spacing: Abstand verteilen: Dither: Dithering: + Transparency Dither Transparenz-Dithering + No Transparency Dither Kein Transparenz-Dithering + Diffusion Transparency Dither Diffusion-Transparenz-Dithering + Pattern Transparency Dither Muster-Transparenz-Dithering + Noise Transparency Dither Rauschen-Transparenz-Dithering Divide Fläche aufteilen Divide Horizontally Into Horizontal teilen in Divide Objects Below Darunterliegende Objekte aufteilen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..8edcff954f 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -903,6 +903,11 @@ font-technology Variable Μεταβλητές Distribute Spacing Κατανομή αποστάσεων Distribute Spacing: Κατανομή αποστάσεων: Dither: Πρόσθεση θορύβου: + Transparency Dither Πρόσμειξη θορύβου διαφάνειας + No Transparency Dither Χωρίς πρόσμειξη θορύβου διαφάνειας + Diffusion Transparency Dither Πρόσμειξη θορύβου διαφάνειας με διάχυση + Pattern Transparency Dither Πρόσμειξη θορύβου διαφάνειας με μοτίβο + Noise Transparency Dither Πρόσμειξη θορύβου διαφάνειας με θόρυβο Divide Διαίρεση Divide Horizontally Into Οριζόντια διαίρεση σε Divide Objects Below Διαίρεση αντικειμένων από κάτω diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..75d9333bbb 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -950,6 +950,11 @@ font-technology Variable Variables Distribute Spacing Distribuir espaciado Distribute Spacing: Distribuir espaciado: Dither: Tramado: + Transparency Dither Tramado de transparencia + No Transparency Dither Sin tramado de transparencia + Diffusion Transparency Dither Tramado de transparencia por difusión + Pattern Transparency Dither Tramado de transparencia por motivo + Noise Transparency Dither Tramado de transparencia por ruido Divide Dividir Divide Horizontally Into Dividir horizontalmente en Divide Objects Below Dividir objetos inferiores diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..10bb86e8f9 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3199,6 +3199,11 @@ antiAlias Sharp Terävä Convert to sRGB Muunna sRGB:ksi Delete this saved preset Poista tämä tallennettu esiasetus Dither: Rasterointi: + Transparency Dither Läpinäkyvyyden rasterointi + No Transparency Dither Ei läpinäkyvyyden rasterointia + Diffusion Transparency Dither Läpinäkyvyyden diffuusiorasterointi + Pattern Transparency Dither Läpinäkyvyyden kuviorasterointi + Noise Transparency Dither Läpinäkyvyyden kohinarasterointi Fit in View Sovita näkymään Format: Muoto: WebP WebP diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..0261b73594 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -953,6 +953,11 @@ font-technology Variable Variables Distribute Spacing Répartir l’espacement Distribute Spacing: Répartition de l’espacement : Dither: Simulation : + Transparency Dither Simulation de transparence + No Transparency Dither Sans simulation de transparence + Diffusion Transparency Dither Simulation de transparence par diffusion + Pattern Transparency Dither Simulation de transparence par motif + Noise Transparency Dither Simulation de transparence par bruit Divide Division Divide Horizontally Into Diviser horizontalement en Divide Objects Below Diviser les objets inférieurs diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 0bb7c9b71f..151f169a95 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -1101,6 +1101,11 @@ Distribute Spacing: અંતર વિતરિત કરો: Dither ડિથર Dither: ડિથર: + Transparency Dither પારદર્શિતા ડિથર + No Transparency Dither પારદર્શિતા ડિથર નહીં + Diffusion Transparency Dither ડિફ્યુઝન પારદર્શિતા ડિથર + Pattern Transparency Dither પેટર્ન પારદર્શિતા ડિથર + Noise Transparency Dither નોઇઝ પારદર્શિતા ડિથર Divide વિભાજિત કરો Divide Horizontally Into આડી રીતે આમાં વિભાજિત કરો Divide Objects Below નીચેના ઑબ્જેક્ટ્સ વિભાજિત કરો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..907abfef3f 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -1776,6 +1776,11 @@ arrowhead Feather पंख Distribute Spacing: स्पेसिंग वितरित करें: Dither डिथर Dither: डिथर: + Transparency Dither पारदर्शिता डिथर + No Transparency Dither कोई पारदर्शिता डिथर नहीं + Diffusion Transparency Dither डिफ़्यूज़न पारदर्शिता डिथर + Pattern Transparency Dither पैटर्न पारदर्शिता डिथर + Noise Transparency Dither नॉइज़ पारदर्शिता डिथर Divide विभाजित करें Divide and Outline Will Remove Unpainted Artwork डिवाइड और आउटलाइन अनपेंटेड आर्टवर्क को हटा देगा Divide Horizontally Into क्षैतिज रूप से विभाजित करें diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..79f4344a92 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1222,6 +1222,11 @@ arrowhead Target Céltábla Distribute Spacing Térköz elosztása Distribute Spacing: Térköz elosztása: Dither: Árnyalatkeverés: + Transparency Dither Átlátszóság-árnyalatkeverés + No Transparency Dither Nincs átlátszóság-árnyalatkeverés + Diffusion Transparency Dither Diffúziós átlátszóság-árnyalatkeverés + Pattern Transparency Dither Mintázatos átlátszóság-árnyalatkeverés + Noise Transparency Dither Zajos átlátszóság-árnyalatkeverés Divide Felosztás Divide Horizontally Into Vízszintes felosztás Divide Objects Below Alatta lévő objektumok felosztása diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..b092c3d6b0 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3658,6 +3658,11 @@ antiAlias Sharp Tajam Convert to sRGB Konversi ke sRGB Delete this saved preset Hapus preset tersimpan ini Dither: Dither: + Transparency Dither Dither transparansi + No Transparency Dither Tanpa dither transparansi + Diffusion Transparency Dither Dither transparansi difusi + Pattern Transparency Dither Dither transparansi pola + Noise Transparency Dither Dither transparansi derau Fit in View Sesuaikan ke tampilan Format: Format: WebP WebP diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..dadbe02d68 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -961,6 +961,11 @@ font-technology Variable Variabili Distribute Spacing Distribuisci spaziatura Distribute Spacing: Distribuisci spaziatura: Dither: Dithering: + Transparency Dither Dithering trasparenza + No Transparency Dither Nessun dithering trasparenza + Diffusion Transparency Dither Dithering trasparenza a diffusione + Pattern Transparency Dither Dithering trasparenza a motivo + Noise Transparency Dither Dithering trasparenza a disturbo Divide Dividi Divide Horizontally Into Dividi orizzontalmente in Divide Objects Below Dividi oggetti sottostanti diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..9c5097f0bd 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1722,6 +1722,11 @@ antiAlias Sharp シャープ Distribute Spacing 等間隔に分布 Distribute Spacing: 間隔の分布: Dither: ディザ: + Transparency Dither 透明部分のディザ + No Transparency Dither 透明部分のディザなし + Diffusion Transparency Dither 拡散の透明部分のディザ + Pattern Transparency Dither パターンの透明部分のディザ + Noise Transparency Dither ノイズの透明部分のディザ Divide Horizontally Into 水平方向に分割 Divide Slices スライスを分割 Divide Vertically Into 垂直方向に分割 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..39d76a3bf8 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5137,6 +5137,11 @@ antiAlias Sharp მკვეთრი Convert to sRGB sRGB-ად გარდაქმნა Delete this saved preset ამ შენახული პრესეტის წაშლა Dither: დიზერინგი: + Transparency Dither გამჭვირვალობის დიზერინგი + No Transparency Dither გამჭვირვალობის დიზერინგის გარეშე + Diffusion Transparency Dither გამჭვირვალობის დიფუზიური დიზერინგი + Pattern Transparency Dither გამჭვირვალობის პატერნული დიზერინგი + Noise Transparency Dither გამჭვირვალობის ხმაურის დიზერინგი Fit in View ხედში ჩატევა Format: ფორმატი: High მაღალი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..22b851fa09 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1712,6 +1712,11 @@ antiAlias Sharp 날카롭게 Distribute Spacing 간격 분포 Distribute Spacing: 간격 분포: Dither: 디더: + Transparency Dither 투명도 디더 + No Transparency Dither 투명도 디더 없음 + Diffusion Transparency Dither 확산 투명도 디더 + Pattern Transparency Dither 패턴 투명도 디더 + Noise Transparency Dither 노이즈 투명도 디더 Divide Horizontally Into 가로로 나누기 Divide Slices 슬라이스 나누기 Divide Vertically Into 세로로 나누기 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..eedf44f8dc 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3652,6 +3652,11 @@ antiAlias Sharp Scherp Convert to sRGB Converteren naar sRGB Delete this saved preset Deze opgeslagen voorinstelling verwijderen Dither: Dither: + Transparency Dither Transparantiedithering + No Transparency Dither Geen transparantiedithering + Diffusion Transparency Dither Transparantiedithering met diffusie + Pattern Transparency Dither Transparantiedithering met patroon + Noise Transparency Dither Transparantiedithering met ruis Fit in View In beeld passen Format: Indeling: WebP WebP diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..2590d6d969 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3165,6 +3165,11 @@ antiAlias Sharp Ostre Convert to sRGB Konwertuj na sRGB Delete this saved preset Usuń to zapisane ustawienie Dither: Rozpraszanie: + Transparency Dither Rozpraszanie przezroczystości + No Transparency Dither Bez rozpraszania przezroczystości + Diffusion Transparency Dither Dyfuzyjne rozpraszanie przezroczystości + Pattern Transparency Dither Rozpraszanie przezroczystości wzorkiem + Noise Transparency Dither Rozpraszanie przezroczystości szumem Fit in View Dopasuj do widoku Format: Format: High Wysoka diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..ca4f7be8d8 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -876,6 +876,11 @@ antiAlias Sharp Nítido Distribute Spacing Distribuir Espaçamento Distribute Spacing: Distribuir Espaçamento: Dither: Dither: + Transparency Dither Dither de transparência + No Transparency Dither Sem dither de transparência + Diffusion Transparency Dither Dither de transparência por difusão + Pattern Transparency Dither Dither de transparência por padrão + Noise Transparency Dither Dither de transparência por ruído Divide Dividir Divide Horizontally Into Dividir Horizontalmente Em Divide Objects Below Dividir Objetos Abaixo diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..56e0c410e2 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -948,6 +948,11 @@ font-technology Variable Вариативные Distribute Spacing Распределить интервалы Distribute Spacing: Распределение интервалов: Dither: Дизеринг: + Transparency Dither Дизеринг прозрачности + No Transparency Dither Без дизеринга прозрачности + Diffusion Transparency Dither Диффузный дизеринг прозрачности + Pattern Transparency Dither Дизеринг прозрачности узором + Noise Transparency Dither Шумовой дизеринг прозрачности Divide Разделить Divide Horizontally Into Разделить по горизонтали на Divide Objects Below Разделить объекты ниже diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..bf3bd8b9d4 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -933,6 +933,11 @@ font-technology Variable Variabla Distribute Spacing Fördela avstånd Distribute Spacing: Fördela avstånd: Dither: Dithering: + Transparency Dither Transparensdithering + No Transparency Dither Ingen transparensdithering + Diffusion Transparency Dither Transparensdithering med diffusion + Pattern Transparency Dither Transparensdithering med mönster + Noise Transparency Dither Transparensdithering med brus Divide Dela upp Divide Horizontally Into Dela horisontellt i Divide Objects Below Dela objekt nedanför diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..096fe7403d 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1128,6 +1128,18 @@ fn anti_aliasing_method_labels_are_in_complete_catalogs() { } } +/// Save for Web's Transparency Dither label and its choices (drawn translated by the dropdown, not +/// through `tl!`). +#[test] +fn transparency_dither_labels_are_in_complete_catalogs() { + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + let cat = lang.catalog(); + for label in std::iter::once("Transparency Dither").chain(crate::dialogs::save_for_web::TRANSPARENCY_DITHERS.map(|(_, l)| l)) { + assert!(cat.plain(label).is_some(), "{} is missing {label}", lang.code); + } + } +} + /// Each row in the `search` context, which adds a language's words to a group of words with the same /// meaning for the command palette, names a group and adds single words of no other group, and no /// two rows of a catalog add one word to different groups. No catalog has to have these rows. diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..940ad83291 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -929,6 +929,11 @@ font-technology Variable Değişken Distribute Spacing Aralığı Dağıt Distribute Spacing: Aralığı Dağıt: Dither: Titreme: + Transparency Dither Saydamlık titremesi + No Transparency Dither Saydamlık titremesi yok + Diffusion Transparency Dither Difüzyon saydamlık titremesi + Pattern Transparency Dither Desen saydamlık titremesi + Noise Transparency Dither Gürültü saydamlık titremesi Divide Böl Divide Horizontally Into Yatay Olarak Böl Divide Objects Below Aşağıdaki Nesneleri Böl diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..721abf78de 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -955,6 +955,11 @@ font-technology Variable Варіативні Distribute Spacing Розподілити інтервали Distribute Spacing: Розподіл інтервалів: Dither: Дизеринг: + Transparency Dither Дизеринг прозорості + No Transparency Dither Без дизерингу прозорості + Diffusion Transparency Dither Дифузійний дизеринг прозорості + Pattern Transparency Dither Дизеринг прозорості візерунком + Noise Transparency Dither Шумовий дизеринг прозорості Divide Розділити Divide Horizontally Into Розділити по горизонталі на Divide Objects Below Розділити об’єкти нижче diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..5d0f31a3fe 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1122,6 +1122,11 @@ font-technology Variable Biến thiên Distribute Spacing Phân bố khoảng cách Distribute Spacing: Phân bố khoảng cách: Dither: Dither: + Transparency Dither Dither độ trong suốt + No Transparency Dither Không dither độ trong suốt + Diffusion Transparency Dither Dither độ trong suốt khuếch tán + Pattern Transparency Dither Dither độ trong suốt họa tiết + Noise Transparency Dither Dither độ trong suốt nhiễu Divide Chia Divide Horizontally Into Chia ngang thành Divide Objects Below Chia đối tượng bên dưới diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..3b80618a3d 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -893,6 +893,11 @@ antiAlias Sharp 锐利 Distribute Spacing 按间距分布 Distribute Spacing: 分布间距: Dither: 仿色: + Transparency Dither 透明度仿色 + No Transparency Dither 无透明度仿色 + Diffusion Transparency Dither 扩散透明度仿色 + Pattern Transparency Dither 图案透明度仿色 + Noise Transparency Dither 杂色透明度仿色 Divide 分割 Divide Horizontally Into 水平分割为 Divide Objects Below 分割下方对象 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..fb9ab8441d 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -923,6 +923,11 @@ font-technology Variable 可變 Distribute Spacing 均分間距 Distribute Spacing: 均分間距: Dither: 仿色: + Transparency Dither 透明度仿色 + No Transparency Dither 無透明度仿色 + Diffusion Transparency Dither 擴散透明度仿色 + Pattern Transparency Dither 圖樣透明度仿色 + Noise Transparency Dither 雜訊透明度仿色 Divide 分割 Divide Horizontally Into 水平分割為 Divide Objects Below 分割下方物件 diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..9e83056ee9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10531,8 +10531,8 @@ every option. File → Export → Save for Web (Legacy) writes optimised web images: `document.exportForWeb {format: gif|jpg|png8|png24, …}` renders the artboard (`clipToArtboard`, the default; `artboard` picks one) or the visible art and the slices, at `width`, `height` or `percent`, and encodes it with the format's settings: for GIF and PNG-8 `reduction`, `colors`, -`dither`, `ditherAmount`, `transparency`, `matte`, `interlaced`, `webSnap`, `lossy` (GIF) and `colorTable {locked, -transparent, webShift, sort, deleted, customPalette, shifted}`; for JPEG `quality`, `progressive`, `optimized`, `embedProfile` and `matte`; for PNG-24 +`dither`, `ditherAmount`, `transparency`, `transparencyDither`, `transparencyDitherAmount`, `matte`, `interlaced`, +`webSnap`, `lossy` (GIF) and `colorTable {locked, transparent, webShift, sort, deleted, customPalette, shifted}`; for JPEG `quality`, `progressive`, `optimized`, `embedProfile` and `matte`; for PNG-24 `transparency`, `matte` and `interlaced`. `metadata` (none, copyright, contact, all) writes File Info as PNG text or a GIF/JPEG comment; `convertToSrgb` marks PNGs as sRGB. `` is the name of `path` without its extension, or without `path` the document's title with the characters Windows does not allow in a file name as `-` and a `-` after @@ -10543,6 +10543,15 @@ after a Windows device name such as `aux` (`slices: selected` writes the selecte Without `path` the files come back as `{name, dataBase64}`. As in the raster exports, `warnings` says when an image couldn't be decoded and is missing from the image; the files are written all the same. +With `transparency` on, `transparencyDither` sets how GIF and PNG-8 treat partly transparent pixels: `none` (the +default) makes the pixels under half opacity transparent and keeps the others; `diffusion`, `pattern` and `noise` make +some of them transparent and keep the rest in a diffusion pattern, an 8×8 ordered pattern or noise. With `pattern`, +`noise`, or `diffusion` at amount 100, about as many are kept as their opacity says. `transparencyDitherAmount` (0 to +100, default 100) sets the strength of `diffusion`: a lower amount comes closer to `none`, and 0 gives the same file as +`none`. Fully transparent and fully opaque pixels do not change, the same art and settings +always give the same file, and a kept pixel is blended over `matte` as before. Without `transparency` both keys are +kept and do not change the file. An unknown method or an amount outside 0 to 100 is refused. + `document.exportForWeb.preview` returns what Save writes for the same settings without writing it: `bytes` (the exact file size), `seconds` to download at `kbps` (default 56.6), the size, and for palette formats the colour table (`colors: [{color, source, transparent, locked, webShifted, shifted, webSafe}]`). The colour table's lists name colours by diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..3b3a0b1fcc 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1003,6 +1003,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - SVG Options: Show in Browser opens the SVG in the default web browser, beside Show Code, which shows the code instead; the SVG export options on the help page (https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/export-file-format-options-in-illustrator.html) list both. VectorCraft writes the SVG of the dialog's current choices for one page to a new folder inside `VectorCraft SVG Preview` in the system's temporary folder, which is kept and cleaned up as Save for Web's previews are, and the dialog stays open without remembering the choices or writing the chosen file. The page is VectorCraft's own choice: under Export Selection the selection's crop, otherwise the first artboard the options choose, and a range the document does not have is an error. The web build disables the button, and control and MCP requests for `file.export.svg.browser` are refused. `crates/ui-egui/src/dialogs/svg_options.rs` (`show_in_browser_opens_what_ok_writes_without_confirming`, `show_in_browser_is_refused_on_the_web_and_for_automation`, `svg_preview_folders_leave_save_for_web_previews_alone`). - Save for Web: Optimize to File Size… opens rows for a desired file size in K, Start With (Current Settings, Auto Select GIF/JPEG) and, with slices, Use (Total of All Slices, Each Slice, Current Slice); OK takes the settings whose files fit and shows the size found, or says that no setting tried fits ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=395)). The search lowers JPEG quality or palette colors (GIF then lossy) and encodes at most 32 trial settings; Auto Select chooses GIF for transparent art or art of at most 256 colors and JPEG otherwise. The slices share one setting, so every Use choice changes all of them (`webExport.optimizeToFileSize`). Scores and estimates are unchanged. - Save for Web: while Alt (Option on macOS) is held, the dialog's Cancel button reads Reset, which puts the remembered settings back on the document's active artboard and leaves the dialog open (`ui.dialogReset`). + - Save for Web: with Transparency on, GIF and PNG-8 offer Transparency Dither (No Transparency Dither, Diffusion, Pattern and Noise), which makes part of the partly transparent pixels transparent and keeps the rest instead of cutting them at half opacity, with an Amount for Diffusion ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=400)). These rules are VectorCraft's own: the default is No Transparency Dither with Amount 100; with Pattern, Noise, or Diffusion at Amount 100, about as many pixels stay opaque as their opacity says, and a lower Diffusion Amount comes closer to No Transparency Dither; Pattern uses an 8×8 ordered pattern and Noise a fixed noise, so the same art always gives the same file; Amount 0 gives the same file as No Transparency Dither; fully transparent and fully opaque pixels do not change, and a kept pixel is blended over the matte as before; both rows are disabled while Transparency is off and keep their values; presets and the remembered settings keep them (`transparencyDither`, `transparencyDitherAmount`). - Save for Web: the color table's trash button and Delete Color in its menu remove the selected GIF or PNG-8 colors, and their pixels take the nearest color left in the palette ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=404)). Click selects one color, Shift-click a range and Ctrl-click (Command-click on macOS) adds or removes one ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=398)). After the first deletion the table is a fixed Custom palette, so deleted colors stay out when the preview updates. These rules are VectorCraft's own: a deleted color is no longer locked, transparent or web-shifted; deleting every opaque color is refused; Restore Generated Table in the menu, or another reduction, goes back to the generated palette; presets and the remembered settings keep the edit (`colorTable.deleted`, `colorTable.customPalette`). Fixed palettes can also use all 256 entries when nothing is transparent. Scores and estimates are unchanged. - Save for Web: double-clicking a GIF or PNG-8 color-table swatch opens the Color Picker, and its OK changes that color to the one picked everywhere it appears in the image. The swatch then shows the original color in its upper-left half and the new one in its lower-right half, with the lock mark, and the color stays through a lower color count. Double-clicking a changed swatch opens the picker on the original color, and OK on it changes the color back; Unshift All Colors in the table's menu undoes every change, web shifts included ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=398)). These rules are VectorCraft's own: Cancel changes nothing; a changed color wins over Web Shift, Web Snap and Lock, and pressing Web Shift replaces it; a color mapped to transparent stays transparent; two colors may change to the same color; a changed color takes a kept palette slot before a locked one, and one slot always stays for the reduction; the change is kept by source color when the reduction changes and applies only while that source is in the table; presets and the remembered settings keep it; the picker opens with Only Web Colors off (`colorTable.shifted`). GIF lossy compression moves no pixel into or out of a changed color. Scores and estimates are unchanged. - Export for Screens, Save for Web (slice images, and files named after the document's title) and the Libraries panel name files with the characters Windows does not allow written as `-` and with a `-` after a Windows device name such as `CON`, on every platform (`document.exportForScreens`, `document.exportForWeb`, `library.create`). From c8fb7729e5ff0d8291e9f4ab37076eb550ab58a3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:08:27 -0800 Subject: [PATCH 2/4] Save for Web: diffusion transparency dither keeps its error past fully clear pixels Fully transparent and fully opaque pixels keep their state but now pass on the opacity error they receive. Before, that error was dropped, so a row alternating half-opaque and fully transparent pixels kept every half-opaque pixel opaque at amount 100. About half of them stay opaque now, in a single row and in a checkerboard. --- crates/render/src/encode/quantize.rs | 33 ++++++++++++++--------- crates/render/src/encode/tests_palette.rs | 18 +++++++++++++ 2 files changed, 38 insertions(+), 13 deletions(-) diff --git a/crates/render/src/encode/quantize.rs b/crates/render/src/encode/quantize.rs index 96b9ffe338..6167526655 100644 --- a/crates/render/src/encode/quantize.rs +++ b/crates/render/src/encode/quantize.rs @@ -232,8 +232,9 @@ pub fn nearest_entries(rgba: &[u8], width: u32, o: &PaletteOptions, palette: &[[ /// partly transparent pixel does under half opacity with no transparency dither, and else by /// `o.transparency_dither`. With pattern, noise, or diffusion at amount 100, about as many of an /// area's pixels stay opaque as its opacity says; a lower diffusion amount moves the result toward -/// the cut at half opacity. Diffusion spreads each pixel's opacity error to the pixels right of it -/// and below it (Floyd–Steinberg, scaled by `o.transparency_dither_amount`), pattern compares the +/// the cut at half opacity. Diffusion spreads each partly transparent pixel's opacity error to the +/// pixels right of it and below it (Floyd–Steinberg, scaled by `o.transparency_dither_amount`), and +/// fully transparent and opaque pixels pass on the error they receive; pattern compares the /// opacity with the 8×8 ordered pattern and noise with a noise threshold. The result depends only /// on the pixels and the options, so exports are reproducible. pub fn clear_mask(rgba: &[u8], width: u32, o: &PaletteOptions) -> Vec { @@ -264,18 +265,24 @@ pub fn clear_mask(rgba: &[u8], width: u32, o: &PaletteOptions) -> Vec { (_, Dither::Pattern) => a < 255.0 * bayer(x % 8, y % 8), // Another noise than the color dither's, so the two do not line up. (_, Dither::Noise) => a < 255.0 * noise(x ^ 0x5a5a, y ^ 0xa5a5), - (_, Dither::Diffusion) => { - let v = a + cur[x + 1]; - let clear = v < 127.5; - let e = (v - if clear { 0.0 } else { 255.0 }) * amount; - // 7/16 right, 3/16 below left, 5/16 below, 1/16 below right. - cur[x + 2] += e * 7.0 / 16.0; - next[x] += e * 3.0 / 16.0; - next[x + 1] += e * 5.0 / 16.0; - next[x + 2] += e / 16.0; - clear - } + (_, Dither::Diffusion) => a + cur[x + 1] < 127.5, }; + if dither == Dither::Diffusion { + // A partly transparent pixel spreads its own opacity error. A fully transparent or + // opaque pixel keeps its state and passes on the error it received unchanged, so + // the partly transparent pixels around it keep their share of opacity + // (VectorCraft's own rule). + let got = cur[x + 1]; + let e = match p[3] { + 0 | 255 => got, + _ => (a + got - if clear { 0.0 } else { 255.0 }) * amount, + }; + // 7/16 right, 3/16 below left, 5/16 below, 1/16 below right. + cur[x + 2] += e * 7.0 / 16.0; + next[x] += e * 3.0 / 16.0; + next[x + 1] += e * 5.0 / 16.0; + next[x + 2] += e / 16.0; + } out.push(clear); } cur.copy_from_slice(next); diff --git a/crates/render/src/encode/tests_palette.rs b/crates/render/src/encode/tests_palette.rs index 8a377190f8..0a280e9d32 100644 --- a/crates/render/src/encode/tests_palette.rs +++ b/crates/render/src/encode/tests_palette.rs @@ -328,3 +328,21 @@ fn transparency_dither_leaves_clear_and_opaque_pixels_and_needs_transparency() { assert!(clear_mask(&[], 0, &alpha_dither(Dither::Diffusion, 100)).is_empty()); assert_eq!(clear_mask(&see_through(3, 1, |_, _| 200), 1000, &alpha_dither(Dither::Diffusion, 100)).len(), 3); } + +#[test] +fn transparency_diffusion_passes_error_through_clear_and_opaque_pixels() { + // Half-opaque pixels between fully transparent or fully opaque ones, in one row and in a + // checkerboard: about half of them stay opaque, and the others keep their state. + for other in [0u8, 255] { + for (w, h, half) in [(64, 1, (|x, _| x % 2 == 0) as fn(u32, u32) -> bool), (32, 32, |x, y| (x + y) % 2 == 0)] { + let px = see_through(w, h, |x, y| if half(x, y) { 128 } else { other }); + let mask = clear_mask(&px, w, &alpha_dither(Dither::Diffusion, 100)); + let at = |x: u32, y: u32| mask[(y * w + x) as usize]; + let cells: Vec<(u32, u32)> = (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).collect(); + assert!(cells.iter().filter(|&&(x, y)| !half(x, y)).all(|&(x, y)| at(x, y) == (other == 0)), "{other} {w}x{h}"); + let halves: Vec<_> = cells.iter().filter(|&&(x, y)| half(x, y)).collect(); + let share = halves.iter().filter(|&&&(x, y)| !at(x, y)).count() as f64 / halves.len() as f64; + assert!((share - 128.0 / 255.0).abs() < 0.1, "{other} {w}x{h}: {share}"); + } + } +} From 7c376a58da2808a3d6b42d85f8e8bfb90eacde09 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 21:54:44 -0800 Subject: [PATCH 3/4] Save for Web: Black & White keeps to the color count with transparent pixels With two colors and some pixels transparent, Black & White still built both black and white entries next to the transparent one, so the palette held three entries. When only one entry is left, Black & White now takes black or white, whichever leaves the opaque pixels nearer the palette with the locked colors included, and skips an end that is already locked. --- crates/render/src/encode/quantize.rs | 16 ++++++++++++++++ crates/render/src/encode/tests_palette.rs | 8 +++++++- crates/render/src/encode/tests_web.rs | 9 +++++++++ 3 files changed, 32 insertions(+), 1 deletion(-) diff --git a/crates/render/src/encode/quantize.rs b/crates/render/src/encode/quantize.rs index 885196f11b..ae2a5c2fdc 100644 --- a/crates/render/src/encode/quantize.rs +++ b/crates/render/src/encode/quantize.rs @@ -178,6 +178,22 @@ pub fn quantize_locked(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, } let free = k - lock.len(); let (mut palette, exact) = match o.reduction { + // With one entry left (two colors and a transparent entry, or the others locked): black or + // white, whichever leaves the opaque pixels nearer the palette, the locked colors included. + Reduction::BlackWhite if free < 2 => { + let mut hist = [0u64; 256]; + for c in opaque() { + hist[c[0] as usize] += 1; + } + let w = o.reduction.weights(); + let cost = |end: [u8; 3]| -> f32 { + let entries: Vec<[f32; 3]> = lock.iter().chain([&end]).map(|c| c.map(f32::from)).collect(); + let near = |g: f32| entries.iter().map(|&e| dist([g; 3], e, w)).fold(f32::INFINITY, f32::min); + hist.iter().enumerate().filter(|(_, n)| **n > 0).map(|(g, &n)| n as f32 * near(g as f32)).sum() + }; + let ends = [[0; 3], [255; 3]].into_iter().filter(|c| !lock.contains(c)); + (ends.min_by(|a, b| cost(*a).total_cmp(&cost(*b))).into_iter().collect(), false) + } Reduction::BlackWhite => (vec![[0; 3], [255; 3]], false), Reduction::Gray => ((0..free).map(|i| [(i * 255 / (free - 1).max(1)) as u8; 3]).collect(), false), Reduction::Web => (web(opaque(), free), false), diff --git a/crates/render/src/encode/tests_palette.rs b/crates/render/src/encode/tests_palette.rs index fbb59dc42c..837c62f359 100644 --- a/crates/render/src/encode/tests_palette.rs +++ b/crates/render/src/encode/tests_palette.rs @@ -71,7 +71,7 @@ fn colours_cap_the_palette() { let px = ramps(64, 48); for colors in [2, 16, 64, 256] { for dither in Dither::ALL { - for reduction in [Reduction::Perceptual, Reduction::Selective, Reduction::Adaptive, Reduction::Web, Reduction::Gray] { + for reduction in Reduction::ALL { let ix = quantize(&px, 64, 48, &PaletteOptions { colors, dither, reduction, ..Default::default() }); assert!(ix.palette.len() <= colors as usize, "{colors} {dither:?} {reduction:?}: {}", ix.palette.len()); assert!(ix.indices.iter().all(|&i| (i as usize) < ix.palette.len())); @@ -325,6 +325,12 @@ fn transparency_dither_leaves_clear_and_opaque_pixels_and_needs_transparency() { let o = PaletteOptions { colors: 2, ..alpha_dither(Dither::Pattern, 100) }; let ix = quantize(&see_through(w, h, |_, _| 128), w, h, &o); assert_eq!((ix.palette.len(), ix.transparent), (2, Some(0))); + // So does Black & White, with black and white pixels both left opaque. + let bw = PaletteOptions { reduction: Reduction::BlackWhite, matte: None, ..o }; + let px: Vec = (0..64u32).flat_map(|i| if i % 8 < 4 { [0, 0, 0, 128] } else { [255, 255, 255, 128] }).collect(); + let ix = quantize(&px, 8, 8, &bw); + assert_eq!(ix.transparent, Some(0)); + assert!(ix.palette.len() <= 2, "{:?}", ix.palette); // No pixels, and a width past the pixels there are. assert!(clear_mask(&[], 0, &alpha_dither(Dither::Diffusion, 100)).is_empty()); assert_eq!(clear_mask(&see_through(3, 1, |_, _| 200), 1000, &alpha_dither(Dither::Diffusion, 100)).len(), 3); diff --git a/crates/render/src/encode/tests_web.rs b/crates/render/src/encode/tests_web.rs index 79e36b3f5f..3eb10c364b 100644 --- a/crates/render/src/encode/tests_web.rs +++ b/crates/render/src/encode/tests_web.rs @@ -22,6 +22,15 @@ fn locked_colours_survive_a_reduction() { let ix = quantize_locked(&px, 64, 16, &o, &[rare]); assert!(ix.palette.contains(&rare) && ix.palette.len() <= 4, "{:?}", ix.palette); assert_eq!(colours(&ix)[0], rare); + // Black & White with black locked and one entry left: white takes it, though most pixels are black. + let px = image(8, 8, |x, _| if x == 7 { [255; 3] } else { [0; 3] }); + let o = PaletteOptions { colors: 2, dither: Dither::None, reduction: Reduction::BlackWhite, ..Default::default() }; + let ix = quantize_locked(&px, 8, 8, &o, &[[0; 3]]); + assert_eq!(ix.palette, [[0; 3], [255; 3]]); + // With a light gray locked, black takes the entry left, though most pixels are white. + let px = image(10, 1, |x, _| if x < 4 { [0; 3] } else { [255; 3] }); + let ix = quantize_locked(&px, 10, 1, &o, &[[200; 3]]); + assert_eq!(ix.palette, [[200; 3], [0; 3]]); } #[test] From c2dc2e8999590beb74561086480396bb09508e34 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 04:47:35 -0800 Subject: [PATCH 4/4] Save for Web: the dialog keeps the remembered Transparency Dither The dialog has no Transparency Dither rows, so its previews, Save, Optimize to File Size and saved presets carry the remembered transparencyDither and transparencyDitherAmount instead of resetting them to none. A preset picked in the dialog does not change them. --- crates/ui-egui/src/dialogs/save_for_web.rs | 45 +++++++++++++------ .../ui-egui/src/dialogs/save_for_web/tests.rs | 25 +++++++++++ docs/target-app-parity.md | 2 +- 3 files changed, 58 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/dialogs/save_for_web.rs b/crates/ui-egui/src/dialogs/save_for_web.rs index aaaf3d4e1c..0dd9edc19b 100644 --- a/crates/ui-egui/src/dialogs/save_for_web.rs +++ b/crates/ui-egui/src/dialogs/save_for_web.rs @@ -49,6 +49,19 @@ pub(crate) struct WebExport { optimized: Option, /// The engine's `colorTable` value: the edits the colour table's buttons made. table: Value, + /// The engine's settings the dialog has no option for ([`KEPT`]), as the dialog opened on them + /// or Optimize to File Size found them: the previews, Save… and the presets use them. A preset + /// picked in the dialog does not change them. + kept: Value, +} + +/// The engine's settings keys the dialog does not show; they pass through it unchanged. +const KEPT: [&str; 2] = ["transparencyDither", "transparencyDitherAmount"]; + +/// The [`KEPT`] keys of the engine's settings `s`. +fn kept_of(s: &WebSettings) -> Value { + let engine = s.to_json(); + Value::Object(KEPT.iter().filter_map(|k| engine.get(*k).map(|v| ((*k).to_string(), v.clone()))).collect()) } /// The key of the Original pane's texture in the pump's [`TextureStore`]; the panes use their index. @@ -129,11 +142,15 @@ pub(super) fn options_of(s: &WebSettings, natural: Option) -> SaveFor serde_json::from_value(v).unwrap_or_default() } -/// The engine's settings JSON for the dialog's `options`, the edited colour `table` and an optional -/// `path`: what `webExport.settings`, `document.exportForWeb` and `file.saveForWeb` read. -fn settings_of(options: &SaveForWebOptions, table: &Value, path: Option<&str>) -> Value { +/// The engine's settings JSON for the dialog's `options`, the edited colour `table`, the `kept` +/// settings the dialog does not show ([`WebExport::kept`]) and an optional `path`: what +/// `webExport.settings`, `document.exportForWeb` and `file.saveForWeb` read. +fn settings_of(options: &SaveForWebOptions, table: &Value, kept: &Value, path: Option<&str>) -> Value { let mut v = serde_json::to_value(options).unwrap_or(Value::Null); if let Some(o) = v.as_object_mut() { + if let Some(kept) = kept.as_object() { + o.extend(kept.clone()); + } let [r, g, b] = options.matte; o.insert("matte".into(), json!(format!("#{r:02x}{g:02x}{b:02x}"))); o.remove("colorTable"); @@ -170,7 +187,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { let host = app.dialogs().ok_or("no window")?; let ctx = app.ui_ctx.clone().ok_or("no window")?; let s = remembered(app); - app.web_export = WebExport { table: serde_json::to_value(&s.color_table).unwrap_or_default(), ..WebExport::default() }; + app.web_export = WebExport { table: serde_json::to_value(&s.color_table).unwrap_or_default(), kept: kept_of(&s), ..WebExport::default() }; let (name, artboards, slices) = { let st = app.session.active().ok_or("no document")?; let slices: Vec = st @@ -472,7 +489,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { on_dialog(&host, |d| d.answer_optimize(answer.map_err(Into::into))); } if asked.browser { - let p = settings_of(&asked.options, &app.web_export.table, None); + let p = settings_of(&asked.options, &app.web_export.table, &app.web_export.kept, None); if let Err(e) = browser_preview(app, &p) { app.status(e); } @@ -488,11 +505,11 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { /// The encodes the dialog wants, as pictures, and the Original pane's picture when the rendering is new. fn answer_variants(app: &mut VectorcraftApp, ctx: &egui::Context, host: &craft::ui::shell::WindowDialogs, wanted: &[WantedVariant]) { - let table = app.web_export.table.clone(); + let (table, kept) = (app.web_export.table.clone(), app.web_export.kept.clone()); let mut answers = Vec::with_capacity(wanted.len()); for w in wanted { let (index, revision) = (w.index, w.request.revision); - let settings = app.session.web_settings(&settings_of(&w.request.options, &table, None)); + let settings = app.session.web_settings(&settings_of(&w.request.options, &table, &kept, None)); let rendered = settings.and_then(|s| render_for(app, &s).map(|(key, r)| (s, key, r))); answers.push(match (rendered, app.session.active()) { (Ok((s, key, r)), Some(st)) => optimise(ctx, &st.doc, &r, &key, &s, w), @@ -532,7 +549,7 @@ 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))?; + let settings = app.session.web_settings(&settings_of(options, &app.web_export.table, &app.web_export.kept, None))?; Ok(encoded(app, &settings)?.colors.iter().map(|c| c.source).collect()) } @@ -565,7 +582,7 @@ fn store_presets(app: &mut VectorcraftApp, events: Vec) { for event in events { let r = match event { WebPresetEvent::Saved(p) => { - let mut v = settings_of(&p.options, &app.web_export.table, None); + let mut v = settings_of(&p.options, &app.web_export.table, &app.web_export.kept, None); v["name"] = json!(p.name); app.run("webExport.presets.save", v) } @@ -596,7 +613,7 @@ fn has_slices(app: &VectorcraftApp) -> bool { /// The `webExport.optimizeToFileSize` params: `options`, the desired size and, with slices, what it covers. fn optimize_params(app: &VectorcraftApp, options: &SaveForWebOptions, desired_k: f64, start: Option<&str>, scope: &str) -> Value { - let mut p = settings_of(options, &app.web_export.table, None); + let mut p = settings_of(options, &app.web_export.table, &app.web_export.kept, None); if let Some(o) = p.as_object_mut() { o.insert("desiredK".into(), json!(desired_k)); if let Some(start) = start { @@ -617,7 +634,7 @@ fn optimize_start(app: &mut VectorcraftApp, options: &SaveForWebOptions) -> Opti let r = app.run("webExport.optimizeToFileSize", p).ok()?; return r["achieved"].as_bool().filter(|a| *a).and_then(|_| r["bytes"].as_u64()); } - let s = app.session.web_settings(&settings_of(options, &app.web_export.table, None)).ok()?; + let s = app.session.web_settings(&settings_of(options, &app.web_export.table, &app.web_export.kept, None)).ok()?; encoded(app, &s).ok().map(|o| o.bytes.len() as u64) } @@ -637,6 +654,7 @@ fn run_optimize(app: &mut VectorcraftApp, req: &OptimizeRequest) -> Result Result s, Err(e) => { on_dialog(host, HostedSaveForWeb::cancel_requests); @@ -698,8 +716,9 @@ fn answer_path(app: &VectorcraftApp, id: DialogId, key: &str, path: PathBuf) { /// written. Failures show in the status line; the dialog has closed. fn finish(app: &mut VectorcraftApp, result: SaveForWebResult) { let table = std::mem::take(&mut app.web_export.table); + let kept = std::mem::take(&mut app.web_export.kept); app.web_export = WebExport::default(); - let params = settings_of(&result.options, &table, None); + let params = settings_of(&result.options, &table, &kept, None); if let Err(e) = app.run("webExport.settings", params.clone()) { return app.status(e); } diff --git a/crates/ui-egui/src/dialogs/save_for_web/tests.rs b/crates/ui-egui/src/dialogs/save_for_web/tests.rs index 400e43fe82..85cba5810d 100644 --- a/crates/ui-egui/src/dialogs/save_for_web/tests.rs +++ b/crates/ui-egui/src/dialogs/save_for_web/tests.rs @@ -312,6 +312,31 @@ fn save_remembers_and_writes_and_done_only_remembers() { assert!(!dir.join("Untitled-1.png").exists()); } +/// The remembered Transparency Dither, which the dialog does not show, reaches the file Save writes +/// and stays remembered after Done. +#[test] +fn save_keeps_the_remembered_transparency_dither() { + let dir = vectorcraft_testkit::temp_dir("sfw-tdither"); + let (mut app, _) = app(&dir, false); + let mut written = vec![]; + for method in ["none", "noise"] { + app.run("webExport.settings", json!({"format": "gif", "transparency": true, "transparencyDither": method})).unwrap(); + app.run("file.saveForWeb", json!({})).unwrap(); + save(&mut app); + let path = dir.join("Untitled-1.gif"); + written.push(std::fs::read(&path).unwrap()); + std::fs::remove_file(&path).unwrap(); + assert_eq!(app.session.last_web_settings().transparency_dither.id(), method, "remembered"); + let expected = app.session.execute("document.exportForWeb", &json!({"format": "gif", "transparencyDither": method})).unwrap(); + assert_eq!(expected["files"][0]["dataBase64"].as_str().and_then(vectorcraft_format::base64_decode).as_ref(), written.last()); + } + assert_ne!(written[0], written[1], "the partly transparent edge is dithered"); + app.run("file.saveForWeb", json!({})).unwrap(); + set(&mut app, "choice", json!("done")); + confirm(&mut app); + assert_eq!(app.session.last_web_settings().transparency_dither.id(), "noise"); +} + #[test] fn html_output_with_slices_saves_the_page_and_images() { let dir = vectorcraft_testkit::temp_dir("sfw-html"); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6b6829de5a..02833f1005 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1013,7 +1013,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - SVG Options: Show in Browser opens the SVG in the default web browser, beside Show Code, which shows the code instead; the SVG export options on the help page (https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/export-file-format-options-in-illustrator.html) list both. VectorCraft writes the SVG of the dialog's current choices for one page to a new folder inside `VectorCraft SVG Preview` in the system's temporary folder, which is kept and cleaned up as Save for Web's previews are, and the dialog stays open without remembering the choices or writing the chosen file. The page is VectorCraft's own choice: under Export Selection the selection's crop, otherwise the first artboard the options choose, and a range the document does not have is an error. The web build disables the button, and control and MCP requests for `file.export.svg.browser` are refused. `crates/ui-egui/src/dialogs/svg_options.rs` (`show_in_browser_opens_what_ok_writes_without_confirming`, `show_in_browser_is_refused_on_the_web_and_for_automation`, `svg_preview_folders_leave_save_for_web_previews_alone`). - Save for Web: Optimize to File Size… opens rows for a desired file size in K, Start With (Current Settings, Auto Select GIF/JPEG) and, with slices, Use (Total of All Slices, Each Slice, Current Slice); OK takes the settings whose files fit and shows the size found, or says that no setting tried fits ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=395)). The search lowers JPEG quality or palette colors (GIF then lossy) and encodes at most 32 trial settings; Auto Select chooses GIF for transparent art or art of at most 256 colors and JPEG otherwise. The slices share one setting, so every Use choice changes all of them (`webExport.optimizeToFileSize`). Scores and estimates are unchanged. - Save for Web: while Alt (Option on macOS) is held, the dialog's Cancel button reads Reset, which puts the remembered settings back on the document's active artboard and leaves the dialog open (`ui.dialogReset`). - - Save for Web: with Transparency on, GIF and PNG-8 exports take a Transparency Dither (none, diffusion, pattern and noise), which makes part of the partly transparent pixels transparent and keeps the rest instead of cutting them at half opacity, with an amount for diffusion ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=400)). These rules are VectorCraft's own: the default is none with amount 100; with pattern, noise, or diffusion at amount 100, about as many pixels stay opaque as their opacity says, and a lower diffusion amount comes closer to none; pattern uses an 8×8 ordered pattern and noise a fixed noise, so the same art always gives the same file; amount 0 gives the same file as none; fully transparent and fully opaque pixels do not change, and a kept pixel is blended over the matte as before; without Transparency both settings are kept and do not change the file; presets and the remembered settings keep them (`document.exportForWeb`, `webExport.settings`: `transparencyDither`, `transparencyDitherAmount`). The Save for Web dialog does not show these settings yet. + - Save for Web: with Transparency on, GIF and PNG-8 exports take a Transparency Dither (none, diffusion, pattern and noise), which makes part of the partly transparent pixels transparent and keeps the rest instead of cutting them at half opacity, with an amount for diffusion ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=400)). These rules are VectorCraft's own: the default is none with amount 100; with pattern, noise, or diffusion at amount 100, about as many pixels stay opaque as their opacity says, and a lower diffusion amount comes closer to none; pattern uses an 8×8 ordered pattern and noise a fixed noise, so the same art always gives the same file; amount 0 gives the same file as none; fully transparent and fully opaque pixels do not change, and a kept pixel is blended over the matte as before; without Transparency both settings are kept and do not change the file; presets and the remembered settings keep them (`document.exportForWeb`, `webExport.settings`: `transparencyDither`, `transparencyDitherAmount`). The Save for Web dialog does not show these settings yet; its previews and Save… use the remembered ones, and a preset picked in the dialog does not change them. - Save for Web: the color table's trash button and Delete Color in its menu remove the selected GIF or PNG-8 colors, and their pixels take the nearest color left in the palette ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=404)). Click selects one color, Shift-click a range and Ctrl-click (Command-click on macOS) adds or removes one ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=398)). After the first deletion the table is a fixed Custom palette, so deleted colors stay out when the preview updates. These rules are VectorCraft's own: a deleted color is no longer locked, transparent or web-shifted; deleting every opaque color is refused; Restore Generated Table in the menu, or another reduction, goes back to the generated palette; presets and the remembered settings keep the edit (`colorTable.deleted`, `colorTable.customPalette`). Fixed palettes can also use all 256 entries when nothing is transparent. Scores and estimates are unchanged. - Save for Web: double-clicking a GIF or PNG-8 color-table swatch opens the Color Picker, and its OK changes that color to the one picked everywhere it appears in the image. The swatch then shows the original color in its upper-left half and the new one in its lower-right half, with the lock mark, and the color stays through a lower color count. Double-clicking a changed swatch opens the picker on the original color, and OK on it changes the color back; Unshift All Colors in the table's menu undoes every change, web shifts included ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=398)). These rules are VectorCraft's own: Cancel changes nothing; a changed color wins over Web Shift, Web Snap and Lock, and pressing Web Shift replaces it; a color mapped to transparent stays transparent; two colors may change to the same color; a changed color takes a kept palette slot before a locked one, and one slot always stays for the reduction; the change is kept by source color when the reduction changes and applies only while that source is in the table; presets and the remembered settings keep it; the picker opens with Only Web Colors off (`colorTable.shifted`). GIF lossy compression moves no pixel into or out of a changed color. Scores and estimates are unchanged. - Export for Screens, Save for Web (slice images, and files named after the document's title) and the Libraries panel name files with the characters Windows does not allow written as `-` and with a `-` after a Windows device name such as `CON`, on every platform (`document.exportForScreens`, `document.exportForWeb`, `library.create`).