diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 94565b3ce8..8873048c27 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Export Document", [], None, - "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|cmx|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, units, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), …cmx writes one file with a page for the artboard (useArtboards: true a page for each chosen artboard, false the bounds of the visible art; a layer for each layer with art on the page, holding the art's fills and strokes as curves in their colors: CMYK, RGB, gray, spot colors at their tints, Registration; type as outlines, gradients and patterns as one color, nonzero fills as even-odd, dashes in whole stroke widths, no miter limit, art across a page's edge written whole, without images, clipping masks or transparency; warnings name each of these losses), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), preserveText?: false (with layers: horizontal and vertical point type in solid colors, with left-to-right paragraphs that set only their alignment, without strokes, effects or an appearance of its own, becomes editable type layers with their pixels; a layer holding it becomes a group, unless other art in it blends in a mode other than normal; refused with layers: false), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked). Never changes the document's path", + "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|cmx|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), embedIcc?: true (webp: the sRGB profile in an ICCP chunk), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, units, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), …cmx writes one file with a page for the artboard (useArtboards: true a page for each chosen artboard, false the bounds of the visible art; a layer for each layer with art on the page, holding the art's fills and strokes as curves in their colors: CMYK, RGB, gray, spot colors at their tints, Registration; type as outlines, gradients and patterns as one color, nonzero fills as even-odd, dashes in whole stroke widths, no miter limit, art across a page's edge written whole, without images, clipping masks or transparency; warnings name each of these losses), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), preserveText?: false (with layers: horizontal and vertical point type in solid colors, with left-to-right paragraphs that set only their alignment, without strokes, effects or an appearance of its own, becomes editable type layers with their pixels; a layer holding it becomes a group, unless other art in it blends in a mode other than normal; refused with layers: false), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked). Never changes the document's path", has_doc, export::export ), diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 96e5d2210f..8940407aff 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -352,6 +352,7 @@ impl RasterOptions { interlaced: self.interlaced.unwrap_or(false), quality: self.quality()?.unwrap_or(90).min(100), webp_lossless: self.lossless.unwrap_or(true), + webp_embed_icc: embed_icc, jpeg: JpegOptions { color_model, method: parse(self.method.as_deref(), jpeg::Method::from_id, "method", "baseline, optimized or progressive")?, diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index f8da5b941c..ada5aaa903 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -159,7 +159,7 @@ const EMBED_ICC: FormatOption = FormatOption { name: "embedIcc", ty: "boolean", default: "true", - description: "embed the colour profile: sRGB (RGB), the working CMYK space (CMYK) or gray with sRGB's tone curve; PNG: mark the file as sRGB (an sRGB chunk)", + description: "embed the colour profile: sRGB (RGB), the working CMYK space (CMYK) or gray with sRGB's tone curve; PNG: mark the file as sRGB (an sRGB chunk); WebP: the sRGB profile in an ICCP chunk", }; const IMAGE_MAP: FormatOption = FormatOption { @@ -470,7 +470,22 @@ pub const FORMATS: &[Format] = &[ read: true, write: true, raster: true, - options: &[ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, RECT, PPI, SCALE, WIDTH, HEIGHT, BACKGROUND, ANTI_ALIAS, LOSSLESS, WEBP_QUALITY], + options: &[ + ARTBOARD, + ARTBOARDS, + RANGE, + USE_ARTBOARDS, + RECT, + PPI, + SCALE, + WIDTH, + HEIGHT, + BACKGROUND, + ANTI_ALIAS, + LOSSLESS, + WEBP_QUALITY, + EMBED_ICC, + ], }, Format { id: "tiff", diff --git a/crates/engine/src/cmd/fileio/tests_raster.rs b/crates/engine/src/cmd/fileio/tests_raster.rs index 93e875b35a..79a66c812e 100644 --- a/crates/engine/src/cmd/fileio/tests_raster.rs +++ b/crates/engine/src/cmd/fileio/tests_raster.rs @@ -229,6 +229,31 @@ fn png_says_it_is_srgb_unless_embed_icc_is_false() { assert!(f["options"].get("embedIcc").is_some(), "png lists embedIcc"); } +/// WebP, lossless or lossy, holds the sRGB profile in an `ICCP` chunk unless `embedIcc` is false, +/// in Export As and in Export for Screens' `settings.webp`, without a note on an unused option. +#[test] +fn webp_embeds_the_srgb_profile_unless_embed_icc_is_false() { + let mut s = session(40.0, 30.0, 1); + s.execute("shape.rectangle", &json!({"x": 5, "y": 5, "width": 20, "height": 10})).unwrap(); + let has_iccp = |file: &[u8]| file.windows(4).any(|w| w == b"ICCP"); + for lossless in [true, false] { + let on = s.execute("document.export", &json!({"format": "webp", "lossless": lossless})).unwrap(); + assert!(has_iccp(&b64(&on)), "lossless {lossless}"); + let off = s.execute("document.export", &json!({"format": "webp", "lossless": lossless, "embedIcc": false})).unwrap(); + assert!(!has_iccp(&b64(&off)), "lossless {lossless}"); + assert_eq!(off["warnings"], json!([]), "lossless {lossless}: embedIcc is a WebP option"); + } + let screens = |s: &mut Session, settings: Value| { + let r = s.execute("document.exportForScreens", &json!({"formats": [{"format": "webp"}], "settings": settings})).unwrap(); + b64(&r["files"][0]) + }; + assert!(has_iccp(&screens(&mut s, json!({})))); + assert!(!has_iccp(&screens(&mut s, json!({"webp": {"embedIcc": false}})))); + let r = s.execute("document.formats", &json!({})).unwrap(); + let f = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "webp").unwrap(); + assert!(f["options"].get("embedIcc").is_some(), "webp lists embedIcc"); +} + #[test] fn formats_list_the_raster_options() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/fileio/tests_text.rs b/crates/engine/src/cmd/fileio/tests_text.rs index d8ac6ec33d..69dcca2082 100644 --- a/crates/engine/src/cmd/fileio/tests_text.rs +++ b/crates/engine/src/cmd/fileio/tests_text.rs @@ -95,13 +95,13 @@ fn webp_is_lossless_by_default_and_lossy_when_asked() { (b64(&r), r["warnings"].clone()) }; let (lossless, warnings) = export(&mut s, json!({})); - assert_eq!(webp_chunks(&lossless), [*b"VP8L"], "lossless by default"); + assert_eq!(webp_chunks(&lossless), [*b"VP8X", *b"ICCP", *b"VP8L"], "lossless with the profile by default"); assert_eq!(warnings, json!([])); // Quality doesn't change a lossless file. assert_eq!(export(&mut s, json!({"lossless": true, "quality": 10})).0, lossless); let (lossy, warnings) = export(&mut s, json!({"lossless": false})); - assert_eq!(webp_chunks(&lossy), [*b"VP8 "], "opaque art is a plain lossy file"); + assert_eq!(webp_chunks(&lossy), [*b"VP8X", *b"ICCP", *b"VP8 "], "opaque art has no alpha chunk"); assert_eq!(warnings, json!([]), "no note: the file is lossy"); assert_eq!(export(&mut s, json!({"lossless": false, "quality": 90})).0, lossy, "quality 90 by default"); // At quality 90 each channel stays within 4 levels of the exact pixels on average. @@ -114,10 +114,11 @@ fn webp_is_lossless_by_default_and_lossy_when_asked() { // Lower quality, smaller file. let low = export(&mut s, json!({"lossless": false, "quality": 10})).0; let high = export(&mut s, json!({"lossless": false, "quality": 95})).0; - assert_eq!(webp_chunks(&low), [*b"VP8 "]); + assert_eq!(webp_chunks(&low), [*b"VP8X", *b"ICCP", *b"VP8 "]); assert!(low.len() < high.len(), "{} vs {} bytes", low.len(), high.len()); for q in [0, 100] { - assert_eq!(webp_chunks(&export(&mut s, json!({"lossless": false, "quality": q})).0), [*b"VP8 "], "quality {q}"); + let file = export(&mut s, json!({"lossless": false, "quality": q, "embedIcc": false})).0; + assert_eq!(webp_chunks(&file), [*b"VP8 "], "quality {q}: a plain lossy file without the profile"); } } @@ -130,7 +131,7 @@ fn lossy_webp_keeps_translucent_pixels() { s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); let file = |s: &mut Session, lossless: bool| b64(&s.execute("document.export", &json!({"format": "webp", "lossless": lossless})).unwrap()); let (lossless, lossy) = (file(&mut s, true), file(&mut s, false)); - assert_eq!(webp_chunks(&lossy), [*b"VP8X", *b"ALPH", *b"VP8 "]); + assert_eq!(webp_chunks(&lossy), [*b"VP8X", *b"ICCP", *b"ALPH", *b"VP8 "]); let ((w, h, exact), (lw, lh, near)) = (rgba(&lossless), rgba(&lossy)); assert_eq!((lw, lh), (w, h)); let at = |px: &[u8], x: u32, y: u32| -> [u8; 4] { @@ -161,7 +162,7 @@ fn webp_quality_out_of_its_range_is_refused() { assert!(s.execute("document.export", &json!({"format": "webp", "quality": 101})).is_err()); let r = s.execute("document.exportForScreens", &json!({"formats": [{"format": "webp", "lossless": false, "quality": 100}]})).unwrap(); let file = b64(&r["files"][0]); - assert_eq!(webp_chunks(&file), [*b"VP8 "]); + assert_eq!(webp_chunks(&file), [*b"VP8X", *b"ICCP", *b"VP8 "]); } #[test] diff --git a/crates/render/src/encode.rs b/crates/render/src/encode.rs index 8b0ae4d74f..49c7e35555 100644 --- a/crates/render/src/encode.rs +++ b/crates/render/src/encode.rs @@ -53,6 +53,8 @@ pub struct RasterExportOptions { pub quality: u8, /// WebP: lossless (`true`), or lossy at [`Self::quality`]. pub webp_lossless: bool, + /// WebP: the sRGB profile in an `ICCP` chunk. + pub webp_embed_icc: bool, /// JPEG colour model, coding and profile. pub jpeg: jpeg::JpegOptions, /// PNG-8 and GIF: the colour reduction (also BMP's at 1, 4 and 8 bits). @@ -79,6 +81,7 @@ impl Default for RasterExportOptions { interlaced: false, quality: 90, webp_lossless: true, + webp_embed_icc: true, jpeg: jpeg::JpegOptions::default(), palette: quantize::PaletteOptions::default(), tiff: tiff::TiffOptions::default(), @@ -128,7 +131,7 @@ impl RasterExportOptions { }; jpeg::encode(&px, img.width, img.height, self.quality, Some(self.ppi), &self.jpeg) } - RasterFormat::WebP => webp(img, (!self.webp_lossless).then_some(self.quality)), + RasterFormat::WebP => webp(img, (!self.webp_lossless).then_some(self.quality), self.webp_embed_icc), RasterFormat::Png8 | RasterFormat::Gif => { let ix = quantize::quantize(&img.to_straight(), img.width, img.height, &self.palette); match format { @@ -188,8 +191,14 @@ pub fn on_white(p: &[u8; 4]) -> [u8; 3] { } /// WebP: lossless (`VP8L`) when `lossy_quality` is `None`, else lossy (`VP8 `, with an `ALPH` -/// chunk when some pixels are not opaque) at that quality 0–100. -pub(crate) fn webp(img: &Rendered, lossy_quality: Option) -> Result, String> { +/// chunk when some pixels are not opaque) at that quality 0–100. With `embed_icc` the file is +/// extended (`VP8X`) and holds the sRGB profile in an `ICCP` chunk. +pub(crate) fn webp(img: &Rendered, lossy_quality: Option, embed_icc: bool) -> Result, String> { + let icc = if embed_icc { + Some(vectorcraft_color::cms::icc_bytes(vectorcraft_color::cms::SRGB).map_err(|e| format!("WebP colour profile: {e}"))?.to_vec()) + } else { + None + }; let src = craft_image_codecs::Image::from_raw( img.width, img.height, @@ -197,10 +206,12 @@ pub(crate) fn webp(img: &Rendered, lossy_quality: Option) -> Result, craft_image_codecs::SampleType::U8, img.to_straight(), ) - .map_err(|e| format!("WebP encoding failed: {e}"))?; + .map_err(|e| format!("WebP encoding failed: {e}"))? + .with_icc(icc); let opts = craft_image_codecs::EncodeOptions { webp_lossless: lossy_quality.is_none(), webp_quality: lossy_quality.unwrap_or(100).min(100), + embed_icc, ..craft_image_codecs::EncodeOptions::default() }; let file = craft_image_codecs::encode(&src, craft_image_codecs::Format::WebP, &opts).map_err(|e| format!("WebP encoding failed: {e}"))?; diff --git a/crates/render/src/encode/tests.rs b/crates/render/src/encode/tests.rs index d6a41d8ec8..8a8cd840e7 100644 --- a/crates/render/src/encode/tests.rs +++ b/crates/render/src/encode/tests.rs @@ -220,9 +220,10 @@ fn webp_chunks(file: &[u8]) -> Vec<[u8; 4]> { #[test] fn lossy_webp_keeps_transparent_pixels_transparent() { let d = circle_doc(); - let lossless = Renderer::new().export_region(&d, d.artboards[0].rect, RasterFormat::WebP, &RasterExportOptions::default()).unwrap(); + let no_icc = RasterExportOptions { webp_embed_icc: false, ..Default::default() }; + let lossless = Renderer::new().export_region(&d, d.artboards[0].rect, RasterFormat::WebP, &no_icc).unwrap(); assert_eq!(webp_chunks(&lossless), [*b"VP8L"], "lossless by default"); - let o = RasterExportOptions { webp_lossless: false, quality: 75, ..Default::default() }; + let o = RasterExportOptions { webp_lossless: false, quality: 75, ..no_icc }; let file = Renderer::new().export_region(&d, d.artboards[0].rect, RasterFormat::WebP, &o).unwrap(); assert_eq!(webp_chunks(&file), [*b"VP8X", *b"ALPH", *b"VP8 "]); let img = export(&d, RasterFormat::WebP, &o); @@ -236,6 +237,35 @@ fn lossy_webp_keeps_transparent_pixels_transparent() { assert_eq!(webp_chunks(&file), [*b"VP8 "]); } +/// The payload of the first chunk of type `ty` in RIFF WebP `file`. +fn webp_chunk<'a>(file: &'a [u8], ty: &[u8; 4]) -> &'a [u8] { + let at = chunk_offset(file, ty); + let len = u32::from_le_bytes(file[at + 4..at + 8].try_into().unwrap()) as usize; + &file[at + 8..at + 8 + len] +} + +/// By default a WebP file, lossless or lossy, holds the sRGB profile in an `ICCP` chunk that its +/// `VP8X` header flags, and a decoder reads the profile back; with `webp_embed_icc` off it holds +/// none. +#[test] +fn webp_embeds_the_srgb_profile_unless_told_not_to() { + let d = circle_doc(); + let srgb = vectorcraft_color::cms::icc_bytes(vectorcraft_color::cms::SRGB).unwrap(); + for lossless in [true, false] { + let o = RasterExportOptions { webp_lossless: lossless, ..Default::default() }; + let file = Renderer::new().export_region(&d, d.artboards[0].rect, RasterFormat::WebP, &o).unwrap(); + let chunks = webp_chunks(&file); + assert_eq!(chunks[..2], [*b"VP8X", *b"ICCP"], "lossless {lossless}: {chunks:?}"); + assert_ne!(webp_chunk(&file, b"VP8X")[0] & 0x20, 0, "lossless {lossless}: the VP8X ICC flag"); + assert_eq!(webp_chunk(&file, b"ICCP"), &*srgb, "lossless {lossless}"); + let mut dec = image::codecs::webp::WebPDecoder::new(std::io::Cursor::new(&file)).unwrap(); + assert_eq!(image::ImageDecoder::icc_profile(&mut dec).unwrap().as_deref(), Some(&*srgb), "lossless {lossless}"); + let off = RasterExportOptions { webp_embed_icc: false, ..o }; + let file = Renderer::new().export_region(&d, d.artboards[0].rect, RasterFormat::WebP, &off).unwrap(); + assert!(!webp_chunks(&file).contains(b"ICCP"), "lossless {lossless}"); + } +} + /// A lossy frame's tag (RFC 6386 §9.1) holds its first partition's size in 19 bits. A frame whose /// size field is at that limit may hold a larger partition, so it is refused; frames below it /// decode with another decoder at every quality, a 1 × 1 image and transparent pixels included. diff --git a/crates/render/src/options.rs b/crates/render/src/options.rs index 6f0f7cde99..31f21c60e3 100644 --- a/crates/render/src/options.rs +++ b/crates/render/src/options.rs @@ -421,7 +421,7 @@ impl Rendered { } /// Encode as lossless WebP. pub fn to_webp(&self) -> Result, String> { - encode::webp(self, None) + encode::webp(self, None, false) } /// Straight-alpha RGBA at (x, y). pub fn pixel(&self, x: u32, y: u32) -> [u8; 4] { diff --git a/crates/ui-egui/src/dialogs/png_options.rs b/crates/ui-egui/src/dialogs/png_options.rs index 44990cf783..c96b696759 100644 --- a/crates/ui-egui/src/dialogs/png_options.rs +++ b/crates/ui-egui/src/dialogs/png_options.rs @@ -1,6 +1,6 @@ //! The raster export options: PNG Options (resolution, background, anti-aliasing, interlaced), //! JPEG Options (no transparency; colour model, quality 0–10, method and scans, profile, image -//! map), WebP Options (lossless, or lossy at a quality 0–100), and PNG-8 and GIF Options (the palette: colour reduction, colours, dither, +//! map), WebP Options (lossless, or lossy at a quality 0–100, and the profile), and PNG-8 and GIF Options (the palette: colour reduction, colours, dither, //! transparency and its dither, matte), TIFF, BMP and Targa Options ([`super::tiff_bmp_tga`]) and PSD Options //! ([`super::psd_options`]). Fields //! are `document.export` params (format, path, artboard choice…); `__`-prefixed ones are the @@ -115,7 +115,7 @@ pub(super) fn defaults(app: &VectorcraftApp, f: &Format) -> Map { o.insert("interlaced".into(), json!(false)); } "webp" => { - o.extend([("lossless".into(), json!(true)), ("quality".into(), json!(WEBP_QUALITY))]); + o.extend([("lossless".into(), json!(true)), ("quality".into(), json!(WEBP_QUALITY)), ("embedIcc".into(), json!(true))]); } "jpg" => { let model = if cmyk { ColorModel::Cmyk } else { ColorModel::Rgb }; @@ -337,7 +337,7 @@ fn quality_row() -> Param { } /// The WebP Options rows: Lossless or Lossy compression, and the quality 0–100 that Lossy uses -/// (disabled while Lossless is chosen, keeping its value). +/// (disabled while Lossless is chosen, keeping its value), and Embed ICC Profile (sRGB). fn webp_rows() -> Vec { let [lossless, lossy] = WEBP_COMPRESSION_LABELS; let compression = ParamKind::radio(vec![("true".into(), tl!(lossless).into()), ("false".into(), tl!(lossy).into())], Some("true".into())); @@ -345,6 +345,7 @@ fn webp_rows() -> Vec { Param::new("lossless", tl!("Compression:"), compression), Param::new("quality", tl!("Quality:"), ParamKind::range(0.0, 100.0, f64::from(WEBP_QUALITY), SliderScale::Linear)) .enabled_when("lossless", "false"), + check("embedIcc", tl!("Embed ICC Profile"), true), ] } diff --git a/crates/ui-egui/src/dialogs/tests_raster_formats.rs b/crates/ui-egui/src/dialogs/tests_raster_formats.rs index be2d65a5cf..7a55edb7eb 100644 --- a/crates/ui-egui/src/dialogs/tests_raster_formats.rs +++ b/crates/ui-egui/src/dialogs/tests_raster_formats.rs @@ -45,8 +45,9 @@ fn raster_option_rows_reach_the_export_params() { assert_eq!(gif[10] & 0x07, 1, "a global colour table of 4 entries"); }), ("png8", &[("reduction", json!("gray"))], |png| assert_eq!(png[25], 3, "indexed")), - ("webp", &[("lossless", json!("false")), ("quality", json!(40))], |file| { + ("webp", &[("lossless", json!("false")), ("quality", json!(40)), ("embedIcc", json!(false))], |file| { assert!(file.windows(4).any(|w| w == b"VP8 ") && !file.windows(4).any(|w| w == b"VP8L"), "lossy"); + assert!(!file.windows(4).any(|w| w == b"ICCP"), "no profile"); }), ("tiff", &[("byteOrder", json!("big")), ("colorModel", json!("cmyk")), ("lzw", json!(false))], |tiff| assert_eq!(&tiff[..4], b"MM\0*")), ("tga", &[("depth", json!("32"))], |tga| assert_eq!((tga[16], tga[17]), (32, 8))), @@ -165,7 +166,8 @@ fn text_export_options_write_the_stories() { assert_eq!((path.as_str(), bytes.as_slice()), ("/out/Untitled-1.txt", &b"Hello\r\nthere\r\n"[..])); } -/// WebP is lossless by default, and OK writes a lossless file without a note. +/// WebP is lossless with the sRGB profile by default, and OK writes a lossless file holding the +/// profile, without a note. #[test] fn webp_is_lossless_by_default() { let (mut app, written) = app(1); @@ -175,7 +177,9 @@ fn webp_is_lossless_by_default() { frame(&mut app); confirm(&mut app); assert!(!app.ui.status.contains("note"), "{}", app.ui.status); - assert_eq!(&written.borrow()[0].1[12..16], b"VP8L", "lossless by default"); + let file = written.borrow()[0].1.clone(); + assert!(file.windows(4).any(|w| w == b"VP8L"), "lossless by default"); + assert!(file.windows(4).any(|w| w == b"ICCP"), "the profile by default"); } #[test] diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 31f0da4316..c20f2ee24c 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -378,7 +378,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's | PSD | open, place, export | yes (open: layers as layers, or the merged image with `layers: false`; place: merged image, or the layers embedded as a group of objects with `layers: true`; the merged image comes in clipped by the file's clipping path; every mode and depth; `.psd` and `.pdd`) | yes (layered, max editability, point type as editable type layers with `preserveText`; `tests_psd.rs`) | PSD Import Options on File › Open and on File › Place without Link (Convert Layers to Objects, Flatten Layers to a Single Image, Import Hidden Layers, Import Slices; `tests_psdlayers.rs`, `dialogs/psd_import.rs`); slices (image resource 1050, version 6 and the version 7 and 8 descriptor) open and embed as user slices with `importSlices` (`tests_psdslices.rs`); layer comps aren't read; the embedded ICC profile's tags are 4-byte aligned (#1584) | | PSB | open | yes (layers as layers, or the merged image; the merged image comes in clipped by the file's clipping path) | no | | | PNG / JPEG / GIF / BMP / TIFF / Targa | open, place, export | yes (PNG: `.png` and `.pns`; BMP: `.bmp`, `.dib` and `.rle`; Targa: `.tga`, `.vda`, `.icb` and `.vst`, raw or run-length encoded, with a 16-bit file's one-bit alpha) | yes; TIFF is also selectable in Export for Screens and Asset Export with its existing options | Targa: `tests_tiffbmp.rs`, `tests/links.rs`; TIFF: grayscale with an alpha channel or other extra channels reads (#1466 in part), and so do files that store each channel as its own plane (PlanarConfiguration 2), CMYK ones with their ink amounts, and 1-bit files compressed with CCITT Group 3 (Compression 2 and 3, one- and two-dimensional rows); the ICC profiles embedded in JPEG and TIFF have 4-byte aligned tags (#1584); PNG export marks its colours as sRGB (`embedIcc`, an `sRGB` chunk; no ICC profile is embedded, #2221) | -| WebP | export (Export for Screens) | yes | yes (lossless by default; `lossless: false` writes lossy WebP at `quality` 0–100, default 90) | lossy files are `VP8 `, with an `ALPH` chunk when some pixels are not opaque; `tests_text.rs` | +| WebP | export (Export for Screens) | yes | yes (lossless by default; `lossless: false` writes lossy WebP at `quality` 0–100, default 90; `embedIcc`, default on, writes the sRGB profile in an `ICCP` chunk) | lossy files are `VP8 `, with an `ALPH` chunk when some pixels are not opaque; `tests_text.rs` | | JPEG XL `.jxl` | — | yes (first frame; 16-bit and floating-point samples as 8 bits, alpha kept; CMYK refused) | no | decoded with jxl-oxide; the size is checked from the header before decoding; container Exif resolution sizes opened and placed images; tests in `crates/engine/src/cmd/fileio/tests_jxlread.rs` and `crates/engine/tests/import_fuzz.rs` | | HEIC / HEIF | open, place | yes (HEVC-coded still images: single pictures and grids of tiles, 8 to 10 bits, with an alpha image; image sequences, other codings and grids of cropped tiles are refused) | no | `.heic`, `.heif`; decoded by heic-rs in the engine's default `heif` feature (a build without it refuses the files with a message); the container's rotation, mirror and crop are applied; without an `nclx` box the HEVC stream's video signal type gives the matrix and range; an RGB ICC profile, or Display P3 with the sRGB curve named by an `nclx` box or, without a color box, by the stream, is converted to sRGB; EXIF resolution tags size the image, or 72 ppi; bounded decoding; `tests_heifread.rs` | | Layered raster `.pcraft` | open, place | yes (as one image: the full-size composite when the file has one; else the layers combined at the canvas size when the document is RGB at 8 or 16 bits and every visible layer is a Normal raster layer without clipping, layer effects, a vector mask, a frame, advanced blending or a feathered layer mask; else the composite preview, with a warning when it is smaller than the canvas) | no | read with craft-doc; sized by the document's resolution, the preview at the canvas's size (at least 1 ppi); a linked file is read the same way again when it is updated; a missing or damaged full-size composite or preview is an error; `tests_pcraftread.rs` | diff --git a/docs/mcp.md b/docs/mcp.md index 2fd8648262..69bfdf3aab 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1634,8 +1634,8 @@ their own size (`scale: "512w"`). WebP is lossless by default (`lossless: true`). `{"format": "webp", "lossless": false, "quality": 60}` writes a lossy WebP file: `quality` runs from 0 to 100 (default 90, VectorCraft's own value), and a higher value keeps more detail in a larger file. A lossy file keeps the alpha exactly when some pixels are not opaque. A WebP `quality` above 100, or one -that is not a whole number, is refused; a lossless file ignores `quality`. Export for Screens takes both in a WebP row -or in `settings.webp`. +that is not a whole number, is refused; a lossless file ignores `quality`. A WebP file holds the sRGB profile in an +`ICCP` chunk unless `embedIcc` is false. Export for Screens takes these options in a WebP row or in `settings.webp`. GIF and PNG-8 exports take Save for Web's `transparencyDither` (`none`, the default, `diffusion`, `pattern` or `noise`) and `transparencyDitherAmount` (0 to 100, default 100) next to `dither` and `ditherAmount`, and they change the file as