Merge main into fix/metafile-loss-warnings

# Conflicts:
#	Cargo.toml
This commit is contained in:
dotCooCoo
2026-11-17 07:25:38 -08:00
161 changed files with 13344 additions and 662 deletions
+9 -3
View File
@@ -53,7 +53,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Flare",
[],
None,
"{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?, ringSeed? (whole number below 2^53: places the rings along the path anew, keeping their count and sizes)} → {id}",
"{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?, ringSeed? (whole number below 2^53: deterministically places every ring along the path, including the first for small seed values, keeping their count and sizes)} → {id}",
has_doc,
flare
),
@@ -565,7 +565,7 @@ fn flare(s: &mut Session, p: &Value) -> Result<Value> {
None | Some(Value::Null) => Ok(None),
Some(v) => v.as_u64().map(Some).ok_or_else(|| bad("shape.flare", format!("`{key}` must be a whole number of at least 0, not {v}"))),
};
// The generator's state is odd (never 0).
// Xorshift64. Both streams start from a nonzero state.
let random = |mut state: u64| {
move || {
state ^= state << 13;
@@ -580,7 +580,13 @@ fn flare(s: &mut Session, p: &Value) -> Result<Value> {
Some(r) if r >= 1 << 53 => return Err(bad("shape.flare", format!("`ringSeed` must be below 2^53, not {r}"))),
r => r,
};
let mut ring_at = ring_seed.map(|r| random((r << 1) | 1));
let mut ring_at = ring_seed.map(|r| {
// SplitMix64 initializes the ring-position stream.
let mut z = r.wrapping_add(0x9e37_79b9_7f4a_7c15);
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
random(z ^ (z >> 31))
});
let stop = |offset: f32, opacity: f32| GradientStop { opacity, ..GradientStop::new(offset, vectorcraft_color::Color::WHITE) };
let radial = |centre: Point, radius: f64, stops: Vec<GradientStop>| {
let mut g = GradientPaint::new(Gradient::new(GradientKind::Radial, stops));
+2 -2
View File
@@ -11,7 +11,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Pencil",
[],
None,
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it",
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it. Any other style, extend end or connect end is an error, and nothing changes",
has_doc,
freehand
),
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Blob Brush",
[],
None,
"{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), sizeMode?: \"fixed\" (default) | \"pressure\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest, at least 0.1 pt; a stroke without pressure keeps the size), sizeVariation?: pt (0; from 0 to 1000, checked with Fixed too), angle?: ° (0, kept within −180–180: the tip's long axis counter-clockwise from horizontal, kept on the page along the stroke), roundness?: % (100, kept within 0–100: the tip's short axis in percent of its long one, 100 round; 0 is drawn as 0.1), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}",
"{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), sizeMode?: \"fixed\" (default) | \"pressure\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest, at least 0.1 pt; a stroke without pressure keeps the size), sizeVariation?: pt (0; from 0 to 1000, checked with Fixed too), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from horizontal, kept on the page along the stroke), roundness?: % (100, 0–100: the tip's short axis in percent of its long one, 100 round; 0 is drawn as 0.1), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}. An angle, roundness or fidelity outside its range is rejected with an error, and nothing changes",
has_doc,
blob
),
+25 -13
View File
@@ -200,14 +200,22 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
// The tolerance the stroke is fitted at; with `fit: false` it is not fitted.
let fit_tol = switch_or(p, "fit", true, C)?.then_some(tol);
let closed = switch_or(p, "closed", false, C)?;
let brush = str_param(p, "style") == Some("brush");
let brush = match p.get("style").filter(|v| !v.is_null()).map(Value::as_str) {
None | Some(Some("pencil")) => false,
Some(Some("brush")) => true,
Some(_) => return Err(bad(C, "style must be \"pencil\" or \"brush\"")),
};
// The undo step's name: a stroke painted with a brush is a Paintbrush stroke, whatever its style.
let label = if brush || brush_name.is_some() { "Paintbrush" } else { "Pencil" };
let keep_selected = switch_or(p, "keepSelected", true, C)?;
let filled = switch_or(p, "fill", false, C)?;
if let Some(ext) = p.get("extend").filter(|v| !v.is_null()) {
let id = object_param(ext, "id", C)?.ok_or_else(|| bad(C, "extend needs id"))?;
let at_start = str_param(ext, "end") == Some("start");
let at_start = match ext.get("end").filter(|v| !v.is_null()).map(Value::as_str) {
None | Some(Some("end")) => false,
Some(Some("start")) => true,
Some(_) => return Err(bad(C, "extend end must be \"start\" or \"end\"")),
};
let (pd, _) = path_of(&s.doc()?.doc, id)?;
let si = pd.subpaths.iter().rposition(|s| !s.closed && !s.anchors.is_empty()).ok_or_else(|| bad(C, "path has no open end"))?;
let target = brush_target(&s.doc()?.doc, id);
@@ -488,12 +496,23 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result<Value> {
let samples = samples_param(p, "points", C)?;
let size = ranged(p, "size", 10.0, SIZES, C)?;
let angle = number_or(p, "angle", 0.0, C)?;
if !(-180.0..=180.0).contains(&angle) {
return Err(bad(C, "`angle` must be from -180 to 180 degrees"));
}
let roundness = number_or(p, "roundness", 100.0, C)?;
if !angle.is_finite() || !roundness.is_finite() {
return Err(bad(C, "angle and roundness must be finite"));
if !(0.0..=100.0).contains(&roundness) {
return Err(bad(C, "`roundness` must be from 0 to 100%"));
}
// With `fidelity` (pt), the brush follows the stroke fitted by [`fit_freehand`], as a Pencil
// stroke is fitted. Without it, or when the fitted stroke has no length (a short stroke back to
// its start), the brush follows every point.
let fidelity = match p.get("fidelity") {
None | Some(Value::Null) => None,
Some(_) => Some(number_or(p, "fidelity", 0.0, C)?),
};
if fidelity.is_some_and(|f| !(vectorcraft_tools::draw2::MIN_FIDELITY..=100.0).contains(&f)) {
return Err(bad(C, "`fidelity` must be from 0.01 to 100 pt"));
}
let angle = angle.clamp(-180.0, 180.0);
let roundness = roundness.clamp(0.0, 100.0);
let tip = vectorcraft_tools::draw2::blob_tip(angle, roundness);
let squash = tip.inverse();
// Width profiles use distance along the spine, so measure pressure on the same squashed
@@ -515,13 +534,6 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result<Value> {
let mapped_pts: Vec<Point> = mapped_samples.into_iter().map(|s| s.pt).collect();
// The widest the brush gets: the area merges look in.
let reach = pressure.as_ref().map_or(size, |(_, v)| size + v);
// With `fidelity` (pt), the brush follows the stroke fitted by [`fit_freehand`], as a Pencil
// stroke is fitted. Without it, or when the fitted stroke has no length (a short stroke back to
// its start), the brush follows every point.
let fidelity = match p.get("fidelity") {
None | Some(Value::Null) => None,
Some(_) => Some(number_or(p, "fidelity", 0.0, C)?.clamp(vectorcraft_tools::draw2::MIN_FIDELITY, 100.0)),
};
let spine = |tol: Option<f64>| {
let path = match tol {
Some(tol) => PathData::single(fit_freehand(&pts, tol, false)),
File diff suppressed because one or more lines are too long
+22 -5
View File
@@ -241,7 +241,8 @@ struct RasterOptions {
width: Option<f64>,
/// The height of each file in pixels (wins over `ppi` and `scale`).
height: Option<f64>,
quality: Option<u8>,
/// JPEG and lossy WebP quality, read by [`RasterOptions::quality`].
quality: Option<Value>,
background: Option<Value>,
anti_alias: Option<String>,
interlaced: Option<bool>,
@@ -281,6 +282,19 @@ fn clamped_ppi(ppi: f64) -> f64 {
}
impl RasterOptions {
/// `quality` as given: `None` when absent or null, else a whole number 0–255 (JPEG caps it at
/// 100; WebP refuses more than 100), or an error naming it.
fn quality(&self) -> Result<Option<u8>> {
match &self.quality {
None | Some(Value::Null) => Ok(None),
Some(v) => v
.as_u64()
.and_then(|q| u8::try_from(q).ok())
.map(Some)
.ok_or_else(|| bad(C, format!("quality must be a whole number from 0 to 100, not {v}"))),
}
}
/// The pixel size each file is scaled to: `width`, else `height`; `None` when neither is set.
fn pixel_size(&self) -> Result<Option<ScreenSize>> {
let checked = |key: &str, n: f64| {
@@ -311,7 +325,8 @@ impl RasterOptions {
},
anti_alias: self.anti_alias.as_deref().map(anti_alias).transpose().map_err(|e| bad(C, e))?.unwrap_or_default(),
interlaced: self.interlaced.unwrap_or(false),
quality: self.quality.unwrap_or(90).min(100),
quality: self.quality()?.unwrap_or(90).min(100),
webp_lossless: self.lossless.unwrap_or(true),
jpeg: JpegOptions {
color_model,
method: parse(self.method.as_deref(), jpeg::Method::from_id, "method", "baseline, optimized or progressive")?,
@@ -1136,6 +1151,11 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
"psd" => RasterFormat::Psd,
_ => RasterFormat::WebP,
};
if format == RasterFormat::WebP
&& let Some(q) = o.quality()?.filter(|q| *q > 100)
{
return Err(bad(C, format!("quality {q}: WebP quality is 0–100")));
}
check_options(format, &settings)?;
// Use Artboards: one file per chosen artboard (default all); else the one chosen.
let chosen = match use_artboards {
@@ -1182,9 +1202,6 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
}
let regions: Vec<Rect> = enc.files.iter().filter_map(|(b, _)| b.and_then(|b| doc.artboards.get(b))).map(|a| a.rect).collect();
enc.warnings.extend(crate::cmd::fonts::export_overflow_warning(doc, &doc.layers, Some(&regions)));
if format == RasterFormat::WebP && o.lossless == Some(false) {
enc.setting_notes.push("lossy WebP isn't available yet: the file is lossless (exact, but larger)".into());
}
return Ok(enc);
}
_ => return Err(bad(C, format!("no encoder for {} yet", f.label))),
+7 -3
View File
@@ -206,11 +206,15 @@ const LOSSLESS: FormatOption = FormatOption {
name: "lossless",
ty: "boolean",
default: "true",
description: "lossless WebP; false asks for lossy, which isn't available yet (written lossless, with a warning)",
description: "lossless WebP (every pixel kept exactly); false writes lossy WebP at quality: a smaller file that loses some detail",
};
const WEBP_QUALITY: FormatOption =
FormatOption { name: "quality", ty: "integer", default: "90", description: "lossy quality 0–100 (for when lossy WebP is available)" };
const WEBP_QUALITY: FormatOption = FormatOption {
name: "quality",
ty: "integer",
default: "90",
description: "lossy WebP quality 0–100 (with lossless false; higher keeps more detail in a larger file; more than 100 is refused)",
};
/// The options of the palette formats (PNG-8, GIF).
const PALETTE_OPTIONS: &[FormatOption] = &[
@@ -135,26 +135,25 @@ fn formats_list_use_artboards() {
assert!(opts("vectorcraft").get("useArtboards").is_none());
}
/// An export's reply gives what the file loses before its notes on the options, whatever order
/// the encoder gave them: the WebP encoder notes that lossy WebP isn't applied before the export
/// notes the type it drew in the fallback font. With only notes on the options, they keep their
/// order.
/// An export's reply gives what the file loses before its notes on the options: the type the
/// export drew in the fallback font comes before the note on an option WebP doesn't read. With
/// only notes on the options, they keep their order.
#[test]
fn what_the_file_loses_comes_before_a_note_on_the_options() {
let lossy = "lossy WebP isn't available yet: the file is lossless (exact, but larger)";
let unused = "`interlaced` was not used: WebP files don't read it";
let warnings = |s: &mut Session, p: Value| -> Vec<String> {
let r = s.execute("document.export", &p).unwrap();
r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).map(str::to_string).collect()
};
let mut s = session(60.0, 40.0, 1);
assert_eq!(warnings(&mut s, json!({"format": "webp", "lossless": false})), [lossy]);
assert_eq!(warnings(&mut s, json!({"format": "webp", "interlaced": true})), [unused]);
s.execute("text.create", &json!({"x": 5, "y": 20, "text": "Ab", "font": "Nonexistent Sans Probe"})).unwrap();
let w = warnings(&mut s, json!({"format": "webp", "lossless": false}));
let w = warnings(&mut s, json!({"format": "webp", "interlaced": true}));
assert_eq!(w.len(), 2, "{w:?}");
assert!(w[0].contains("fallback font") && w[0].contains("Nonexistent Sans Probe"), "{w:?}");
assert_eq!(w[1], lossy);
assert_eq!(w[1], unused);
// document.serialize gives them in the same order.
let r = s.execute("document.serialize", &json!({"format": "webp", "lossless": false})).unwrap();
let r = s.execute("document.serialize", &json!({"format": "webp", "interlaced": true})).unwrap();
assert_eq!(r["warnings"], json!(w));
}
@@ -546,20 +546,19 @@ fn type_in_a_missing_family_is_named_once_for_every_format() {
assert!(fallback[0].contains("Nonexistent Sans Probe"), "{fallback:?}");
}
/// What a later file loses comes before a note on the options that an earlier file gave: the
/// first artboard's WebP gives only the lossy WebP note, the second's also says its type doesn't
/// fit.
/// What a later file loses comes before a note on the options: the second artboard's WebP says
/// its type doesn't fit, before the note on the row's option that WebP doesn't read.
#[test]
fn what_any_file_loses_comes_before_the_notes_on_the_options() {
let mut s = session(2);
let second = s.doc().unwrap().doc.artboards[1].rect;
let area = json!({"width": 30, "height": 8});
s.execute("text.create", &json!({"x": second.x0 + 2.0, "y": second.y0 + 2.0, "size": 12, "area": area, "text": "Ab\nCd\nEf\nGh"})).unwrap();
let r = export(&mut s, json!({"formats": [{"format": "webp", "lossless": false}]}));
let r = export(&mut s, json!({"formats": [{"format": "webp", "interlaced": true}]}));
let warnings: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
assert_eq!(warnings.len(), 2, "{warnings:?}");
assert!(warnings[0].contains("doesn't fit its frame"), "{warnings:?}");
assert!(warnings[1].starts_with("lossy WebP"), "{warnings:?}");
assert!(warnings[1].starts_with("`formats[0].interlaced` was not used"), "{warnings:?}");
}
#[test]
+106 -32
View File
@@ -53,41 +53,115 @@ fn text_export_writes_the_stories_in_stacking_order() {
let _ = std::fs::remove_dir_all(dir);
}
/// The chunk types of RIFF WebP file `file`, in order.
fn webp_chunks(file: &[u8]) -> Vec<[u8; 4]> {
assert_eq!((&file[..4], &file[8..12]), (&b"RIFF"[..], &b"WEBP"[..]));
let mut chunks = Vec::new();
let mut at = 12;
while at + 8 <= file.len() {
let len = u32::from_le_bytes([file[at + 4], file[at + 5], file[at + 6], file[at + 7]]) as usize;
chunks.push([file[at], file[at + 1], file[at + 2], file[at + 3]]);
at += 8 + len + len % 2;
}
chunks
}
/// The size and straight RGBA pixels of image file `file`.
fn rgba(file: &[u8]) -> (u32, u32, Vec<u8>) {
let img = craft_image_codecs::decode(file).unwrap();
let (w, h) = img.dimensions();
(w, h, img.to_rgba8())
}
/// A 120 × 80 pt document filled with a grid of rectangles in 96 colors.
fn varied_art() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 120, "height": 80})).unwrap();
for row in 0..8 {
for col in 0..12 {
s.execute("shape.rectangle", &json!({"x": col * 10, "y": row * 10, "width": 10, "height": 10})).unwrap();
let color = format!("#{:02x}{:02x}{:02x}", col * 21, row * 32, (col * 7 + row * 23) % 256);
s.execute("paint.setFill", &json!({"color": color})).unwrap();
}
}
s
}
#[test]
fn webp_is_lossless_and_says_so_when_lossy_is_asked_for() {
fn webp_is_lossless_by_default_and_lossy_when_asked() {
let mut s = varied_art();
let export = |s: &mut Session, p: Value| -> (Vec<u8>, Value) {
let r = s.execute("document.export", &merge(json!({"format": "webp", "background": "white"}), p)).unwrap();
(b64(&r), r["warnings"].clone())
};
let (lossless, warnings) = export(&mut s, json!({}));
assert_eq!(webp_chunks(&lossless), [*b"VP8L"], "lossless 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!(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.
let ((w, h, exact), (lw, lh, near)) = (rgba(&lossless), rgba(&lossy));
assert_eq!((lw, lh), (w, h));
assert_eq!((w, h), (120, 80));
let diff: u64 = exact.iter().zip(&near).map(|(a, b)| u64::from(a.abs_diff(*b))).sum();
let mean = diff as f64 / exact.len() as f64;
assert!(mean <= 4.0, "mean difference {mean}");
// 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!(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}");
}
}
#[test]
fn lossy_webp_keeps_translucent_pixels() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 30, "height": 20})).unwrap();
s.execute("shape.rectangle", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap();
let r = s.execute("document.export", &json!({"format": "webp"})).unwrap();
let file = b64(&r);
assert_eq!((&file[..4], &file[8..12], &file[12..16]), (&b"RIFF"[..], &b"WEBP"[..], &b"VP8L"[..]), "lossless bitstream");
assert_eq!(r["warnings"], json!([]));
let r = s.execute("document.export", &json!({"format": "webp", "lossless": false, "quality": 60, "background": "black"})).unwrap();
assert_eq!(&b64(&r)[12..16], b"VP8L");
assert!(r["warnings"][0].as_str().unwrap().contains("lossless"), "{r}");
assert_eq!(
craft_image_codecs::decode(&b64(&r))
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
.get_pixel(29, 19)
.0,
[0, 0, 0, 255]
);
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap();
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
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 "]);
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] {
let i = 4 * (y * w + x) as usize;
[px[i], px[i + 1], px[i + 2], px[i + 3]]
};
// The alpha is written exactly: half covered under the rectangle, clear past it.
let alphas = |px: &[u8]| px.chunks(4).map(|p| p[3]).collect::<Vec<u8>>();
assert_eq!(alphas(&near), alphas(&exact));
assert!((120..=135).contains(&at(&near, 5, 5)[3]), "{:?}", at(&near, 5, 5));
assert_eq!(at(&near, 28, 10)[3], 0);
}
#[test]
fn webp_quality_out_of_its_range_is_refused() {
let mut s = varied_art();
for q in [json!(101), json!(255), json!(256), json!(-1), json!(60.5), json!("high"), json!(true)] {
let p = json!({"format": "webp", "lossless": false, "quality": q});
let e = s.execute("document.export", &p).unwrap_err().to_string();
assert!(e.contains("quality"), "{q}: {e}");
// In Export for Screens too, in a row or in the format's settings.
let row = json!({"formats": [{"format": "webp", "lossless": false, "quality": q}]});
assert!(s.execute("document.exportForScreens", &row).is_err(), "{q}");
let settings = json!({"formats": [{"format": "webp"}], "settings": {"webp": {"lossless": false, "quality": q}}});
assert!(s.execute("document.exportForScreens", &settings).is_err(), "{q}");
}
// A lossless file refuses it as well: the value is not a WebP quality.
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 "]);
}
#[test]
+31 -20
View File
@@ -649,6 +649,7 @@ pub const UNCHECKED: &[&str] = &[
"transparency.setOpacityMask",
"transparency.unlinkOpacityMask",
"type.pathOptions",
"webExport.optimizeToFileSize",
"webExport.presets.save",
"webExport.settings",
];
@@ -663,18 +664,28 @@ fn pdf_option_tree() -> Value {
tree
}
/// The parameter error of command `id` for `key`, a key with the objects it is in (`marks.ofset`),
/// when a key those objects take is near it: `near`, written the same way (`marks.offset`). Each
/// is one value of the message, so a catalog can match the message and translate it.
fn misspelled(id: &str, key: &str, near: &str) -> crate::EngineError {
bad(id, format!("unknown parameter `{key}`; did you mean `{near}`?"))
}
/// `given`, the object at `within` (`marks.`), has only keys of `schema`, the objects inside it too.
fn check_option_tree(id: &str, within: &str, given: &serde_json::Map<String, Value>, schema: &serde_json::Map<String, Value>) -> Result<()> {
for (key, value) in given {
match (schema.get(key), value) {
(None, _) => {
let keys: Vec<&str> = schema.keys().map(String::as_str).collect();
let why = match nearest(key, &keys) {
Some(near) => format!("did you mean `{within}{near}`?"),
None => format!("`{}` takes: {}", within.trim_end_matches('.'), keys.join(", ")),
};
let key = shown_key(key);
return Err(bad(id, format!("unknown parameter `{within}{key}`; {why}")));
let near = nearest(key, &keys);
let key = format!("{within}{}", shown_key(key));
return Err(match near {
Some(near) => misspelled(id, &key, &format!("{within}{near}")),
None => {
let (object, keys) = (within.trim_end_matches('.'), keys.join(", "));
bad(id, format!("unknown parameter `{key}`; `{object}` takes: {keys}"))
}
});
}
(Some(Value::Object(inner)), Value::Object(value)) => check_option_tree(id, &format!("{within}{key}."), value, inner)?,
_ => {}
@@ -691,14 +702,11 @@ fn check_option_keys(id: &str, within: &str, given: &serde_json::Map<String, Val
for (key, value) in given {
if !keys.contains(&key.as_str()) {
let near = nearest(key, keys);
let key = shown_key(key);
return Err(bad(
id,
match near {
Some(near) => format!("unknown parameter `{within}{key}`; did you mean `{within}{near}`?"),
None => format!("unknown parameter `{within}{key}`; {why_not}"),
},
));
let key = format!("{within}{}", shown_key(key));
return Err(match near {
Some(near) => misspelled(id, &key, &format!("{within}{near}")),
None => bad(id, format!("unknown parameter `{key}`; {why_not}")),
});
}
if let (Some(Value::Object(schema)), Value::Object(value)) = (trees.get(key), value) {
check_option_tree(id, &format!("{within}{key}."), value, schema)?;
@@ -797,12 +805,15 @@ fn check_screen_rows(id: &str, within: &str, p: &serde_json::Map<String, Value>)
let formats = screen_formats();
for (format, options) in settings {
if !formats.contains(&format.as_str()) {
let why = match nearest(format, &formats) {
Some(near) => format!("did you mean `{within}settings.{near}`?"),
None => format!("`{within}settings` takes: {}", formats.join(", ")),
};
let format = shown_key(format);
return Err(bad(id, format!("unknown parameter `{within}settings.{format}`; {why}")));
let near = nearest(format, &formats);
let key = format!("{within}settings.{}", shown_key(format));
return Err(match near {
Some(near) => misspelled(id, &key, &format!("{within}settings.{near}")),
None => {
let (object, keys) = (format!("{within}settings"), formats.join(", "));
bad(id, format!("unknown parameter `{key}`; `{object}` takes: {keys}"))
}
});
}
if let Value::Object(options) = options {
check_option_keys(id, &format!("{within}settings.{format}."), options, &keys, NO_FORMAT, trees)?;
+2 -2
View File
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Print Setup",
[],
None,
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100 (1–1000 % with custom and tiling), linked: true (width and height stay equal: give one and the other follows, and turning it on sets the height to the width; a different width and height without linked turn it off, and with linked: true, or linked: null over a linked scale, are an error; a saved scale without linked reads it as false)}, overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one gray page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, overprintBlack: false (separations: solid 100% K or 100% gray fills, strokes and characters, to within half a percent, overprint in the printed copy, gradients when every stop is (every point of a freeform one); rich, RGB, spot-linked and lighter blacks knock out; composite ignores it), inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colors keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colors are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)",
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100 (1–1000 % with custom and tiling), linked: true (width and height stay equal: give one and the other follows, and turning it on sets the height to the width; a different width and height without linked turn it off, and with linked: true, or linked: null over a linked scale, are an error; a saved scale without linked reads it as false)}, overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one gray page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, overprintBlack: false (separations: solid 100% K or 100% gray fills, strokes and characters, to within half a percent, overprint in the printed copy, gradients when every stop is (every point of a freeform one); rich, RGB, spot-linked and lighter blacks are not marked, and paints already set to overprint keep it; composite ignores it), inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45), convertToProcess: false (a spot ink only: it prints on the process plates, with no plate of its own, and its print, frequency and angle are kept for when it prints as a spot ink again; spotsToProcess converts every spot ink whatever it says)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colors keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colors are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)",
has_doc,
setup
),
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Print Preview",
[],
None,
"{preset?: name (as print.setup's: its settings instead of the document's), settings?: {…settings of print.setup} (over the document's or the preset's)} → {pages (copies included), sheets: [{artboard (0-based; null with artboards ignored), tile? (1-based), ink? (separations), width, height (pt, the page), orientation, scale: [width %, height %], transform: [a, b, c, d, e, f] (document space → the page, pt, y down), area: [x0, y0, x1, y1] (the document region the page prints), trim: [x0, y0, x1, y1] (the artboard on the page; with copies per sheet, the box around every copy's), copies?: [[x0, y0, x1, y1]…] (copies per sheet: each copy's artboard on the page, across then down)}] (one copy, in order), tiles: [{artboard, columns, rows, printed: [1-based tiles], tiles: [[x0, y0, x1, y1]…] (document space)}], inks: [{name, spot, print, frequency, angle}] (separations), warnings (art larger than the imageable area, type that prints in the fallback font, type that doesn't fit its frame, options not applied yet…), settings} without printing",
"{preset?: name (as print.setup's: its settings instead of the document's), settings?: {…settings of print.setup} (over the document's or the preset's)} → {pages (copies included), sheets: [{artboard (0-based; null with artboards ignored), tile? (1-based), ink? (separations), width, height (pt, the page), orientation, scale: [width %, height %], transform: [a, b, c, d, e, f] (document space → the page, pt, y down), area: [x0, y0, x1, y1] (the document region the page prints), trim: [x0, y0, x1, y1] (the artboard on the page; with copies per sheet, the box around every copy's), copies?: [[x0, y0, x1, y1]…] (copies per sheet: each copy's artboard on the page, across then down)}] (one copy, in order), tiles: [{artboard, columns, rows, printed: [1-based tiles], tiles: [[x0, y0, x1, y1]…] (document space)}], inks: [{name, spot, print, frequency, angle}] (separations: the plates), documentInks: [{name, spot, print, frequency, angle, convertToProcess?: true (a spot ink printing as process, with no plate)}] (separations: every ink of the document), warnings (art larger than the imageable area, type that prints in the fallback font, type that doesn't fit its frame, options not applied yet…), settings} without printing",
has_doc,
preview
),
+26 -5
View File
@@ -66,11 +66,13 @@ impl FlattenReport {
lowest
.into_iter()
.map(|r| {
let name = r.name.map(|name| format!(" ({name})")).unwrap_or_default();
format!(
"raster effects on object {}{name}: requested {:.1} ppi, achieved {:.1} ppi due to the 64 million pixel cap",
r.id.0, self.requested_ppi, r.achieved_ppi
)
// The id and the name are one value of the message, so a catalog can match it.
let object = match r.name {
Some(name) => format!("{} ({name})", r.id.0),
None => r.id.0.to_string(),
};
let (requested, achieved) = (self.requested_ppi, r.achieved_ppi);
format!("raster effects on object {object}: requested {requested:.1} ppi, achieved {achieved:.1} ppi due to the 64 million pixel cap")
})
.collect()
}
@@ -127,4 +129,23 @@ mod tests {
assert_eq!(warnings.len(), 1);
assert!(warnings[0].contains(&format!("object {}", original.id.0)), "{:?}", warnings);
}
#[test]
fn a_warning_names_the_object_by_its_id_and_its_name() {
let mut doc = Document::new(100.0, 100.0);
doc.raster_effects_ppi = 300.0;
let mut named = Node::group(NodeId(7), vec![]);
named.name = Some("Logo".into());
let unnamed = Node::group(NodeId(8), vec![]);
let mut report = FlattenReport::new(Which::All, &doc);
report.record(&named, &image(72.0));
report.record(&unnamed, &image(150.0));
assert_eq!(
report.warnings(),
[
"raster effects on object 7 (Logo): requested 300.0 ppi, achieved 72.0 ppi due to the 64 million pixel cap",
"raster effects on object 8: requested 300.0 ppi, achieved 150.0 ppi due to the 64 million pixel cap",
]
);
}
}
+37 -14
View File
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New Swatch",
["Window", "Swatches"],
None,
"{name?, color? | colors?: [colour] (one swatch each, in one undo step; #rrggbbaa and #rgba are refused) | swatch? | gradient? | pattern?: name (default: the current fill), tint?: 0..100 (% of the global or spot `swatch`, or of the one the current fill links to), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour; lab: CIE L*a*b*, how spot colours are usually defined), global?, spot? (a spot colour, always global), group?: colour group name (solid colours only; default: ungrouped), none?: true (the None paint), paint?: paint.setFill params, keepModel?: bool (as paint.setFill)} save a colour, gradient or pattern as a swatch. A tint of a global or spot colour (below 100%, without mode, global or spot) becomes a tint swatch, \"Name 40%\", linked to its base: it follows edits to the base and applies as that tint of it. A gradient swatch keeps the gradient's aspect (with or without start/end) and holds no link to the swatch its gradient came from, and a pattern swatch holds the pattern untransformed. Names are unique (\"Sky 2\"); a colour's default name is its values (\"C=10 M=20 Y=30 K=0\", \"R=255 G=128 B=0\", \"Gray K=40\", \"L=55 a=60 b=40\") → {name, names: [every new swatch]}",
"{name?, color? | colors?: [colour | {swatch, tint?}] (one swatch each, in one undo step; #rrggbbaa and #rgba are refused; `{swatch, tint}` is the paint paint.setFill gives, so a tint of a global or spot color becomes a tint swatch) | swatch? | gradient? | pattern?: name (default: the current fill), tint?: 0..100 (% of the global or spot `swatch`, or of the one the current fill links to), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour; lab: CIE L*a*b*, how spot colours are usually defined), global?, spot? (a spot colour, always global), group?: colour group name (solid colours only; default: ungrouped), none?: true (the None paint), paint?: paint.setFill params, keepModel?: bool (as paint.setFill)} save a colour, gradient or pattern as a swatch. A tint of a global or spot colour (below 100%, without mode, global or spot) becomes a tint swatch, \"Name 40%\", linked to its base: it follows edits to the base and applies as that tint of it. A gradient swatch keeps the gradient's aspect (with or without start/end) and holds no link to the swatch its gradient came from, and a pattern swatch holds the pattern untransformed. Names are unique (\"Sky 2\"); a colour's default name is its values (\"C=10 M=20 Y=30 K=0\", \"R=255 G=128 B=0\", \"Gray K=40\", \"L=55 a=60 b=40\") → {name, names: [every new swatch]}",
has_doc,
swatch_new
),
@@ -37,7 +37,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New Color Group",
["Window", "Swatches"],
None,
"{name?, swatches?: [names] (solid colours move into the group; gradients, patterns and None stay), colors?: [colour] (added as new swatches; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), fromArtwork?: false (add the unique colours of the selected art: fills, strokes, text, gradient stops and mesh points; a colour linked to a global swatch moves that swatch into the group), toGlobal?: true (with fromArtwork: the new swatches are global and the selected art's matching unlinked colours link to them), includeTints?: false (with fromArtwork: tints of global swatches also get swatches of their own)} → {name, swatches: [names in the group], linked: paints linked}",
"{name?, swatches?: [names] (solid colours move into the group; gradients, patterns and None stay), colors?: [colour | {swatch, tint?}] (added as new swatches; #rrggbbaa and #rgba are refused; `{swatch, tint}` below 100% of a global or spot color adds a tint swatch, \"Name 40%\", linked to it, and any other `{swatch}` its color), keepModel?: bool (as paint.setFill), fromArtwork?: false (add the unique colours of the selected art: fills, strokes, text, gradient stops and mesh points; a colour linked to a global swatch moves that swatch into the group), toGlobal?: true (with fromArtwork: the new swatches are global and the selected art's matching unlinked colours link to them), includeTints?: false (with fromArtwork: tints of global swatches also get swatches of their own)} → {name, swatches: [names in the group], linked: paints linked}",
has_doc,
swatch_new_group
),
@@ -146,9 +146,11 @@ fn swatch_new(s: &mut Session, p: &Value) -> Result<Value> {
let stored = |c: Color| if mode.is_some() { c } else { super::paint::new_color(s, p, c) };
let cs: Vec<Paint> = cs
.iter()
.map(|c| color_value(c).map(|c| Paint::solid(stored(c))))
.collect::<Option<_>>()
.ok_or_else(|| bad(C, "bad colour in `colors`"))?;
.map(|c| match swatch_entry(s, c, C)? {
Some(paint) => Ok(paint),
None => color_value(c).map(|c| Paint::solid(stored(c))).ok_or_else(|| bad(C, "bad colour in `colors`")),
})
.collect::<Result<_>>()?;
if cs.is_empty() {
return Err(bad(C, "`colors` is empty"));
}
@@ -216,6 +218,16 @@ fn swatch_new(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "name": names[0], "names": names }))
}
/// A `colors` entry of `swatch.new` or `swatch.newGroup` that names a color swatch,
/// `{swatch, tint?}`: the paint `paint.setFill {swatch, tint}` applies (a tint of a global or spot
/// color stays linked to it). `None` for an entry without `swatch`.
fn swatch_entry(s: &Session, v: &Value, cmd: &str) -> Result<Option<Paint>> {
let Some(name) = v.get("swatch") else { return Ok(None) };
let name = name.as_str().ok_or_else(|| bad(cmd, format!("`swatch` in `colors` must be a swatch name, not {name}")))?;
let tint = super::paint::tint_param(v, cmd)?;
super::paint::swatch_solid(&s.doc()?.doc, name, tint).map(Some).map_err(|e| bad(cmd, e))
}
/// A gradient or pattern `paint`, parsed from the paint params `p`, as a new or edited swatch
/// stores it.
fn stored_paint(paint: Paint, p: &Value) -> Paint {
@@ -475,10 +487,20 @@ fn swatch_new_group(s: &mut Session, p: &Value) -> Result<Value> {
let mut names = str_list(p, "swatches");
super::paint::check_keep_model(p, C)?;
check_switches(p, &["fromArtwork", "toGlobal", "includeTints"], C)?;
let colors: Vec<Color> = p
// A `{swatch, tint}` entry below 100% becomes a tint swatch linked to its base; any other
// entry becomes a process color swatch.
let colors: Vec<Paint> = p
.get("colors")
.and_then(Value::as_array)
.map(|a| a.iter().map(|v| color_value(v).map(|c| super::paint::new_color(s, p, c)).ok_or_else(|| bad(C, format!("bad color {v}")))).collect())
.map(|a| {
a.iter()
.map(|v| match swatch_entry(s, v, C)? {
Some(paint @ Paint::Solid { swatch: Some(_), tint, .. }) if tint < 1.0 => Ok(paint),
Some(paint) => paint.color().map(Paint::solid).ok_or_else(|| bad(C, format!("bad color {v}"))),
None => color_value(v).map(|c| Paint::solid(super::paint::new_color(s, p, c))).ok_or_else(|| bad(C, format!("bad color {v}"))),
})
.collect::<Result<Vec<_>>>()
})
.transpose()?
.unwrap_or_default();
let from_art = bool_or(p, "fromArtwork", false);
@@ -486,15 +508,15 @@ fn swatch_new_group(s: &mut Session, p: &Value) -> Result<Value> {
let tints = bool_or(p, "includeTints", false);
let requested = name_param(p, "name");
let (name, members, linked) = s.edit("New Color Group", |d, sel| {
// New swatches: (colour, global).
let mut new: Vec<(Color, bool)> = colors.iter().map(|c| (*c, false)).collect();
// New swatches: (paint, global).
let mut new: Vec<(Paint, bool)> = colors.iter().map(|c| (c.clone(), false)).collect();
if from_art {
if sel.objects.is_empty() {
return Err(bad(C, "select artwork to make a group of its colours"));
}
let mut art = vec![];
artwork_colors(d, &sel.objects, tints, &mut names, &mut art);
new.extend(art.into_iter().map(|c| (c, to_global)));
new.extend(art.into_iter().map(|c| (Paint::solid(c), to_global)));
}
let name = d.free_swatch_name(requested.as_deref().unwrap_or("Color Group"));
// Colour groups hold solid colours only.
@@ -505,12 +527,13 @@ fn swatch_new_group(s: &mut Session, p: &Value) -> Result<Value> {
let mut free = d.free_swatch_names();
free.insert(&name);
group.swatches.iter().for_each(|sw| free.insert(&sw.name));
for (c, global) in new {
let nm = free.take(&color_name(c));
if global {
for (paint, global) in new {
// A tint swatch is named "Name 40%", a colour after its values.
let nm = free.take_new(&paint);
if global && let Some(c) = paint.color() {
links.push((c, nm.clone()));
}
group.swatches.push(Swatch { name: nm, paint: Paint::solid(c), global, spot: false });
group.swatches.push(Swatch { name: nm, paint, global, spot: false });
}
let members: Vec<String> = group.swatches.iter().map(|w| w.name.clone()).collect();
d.swatch_groups.push(group);
+300
View File
@@ -45,6 +45,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
preview
),
cmd!(
query "webExport.optimizeToFileSize",
"Optimize to File Size",
[],
None,
"{desiredK: the desired file size in K (1024 bytes; above 0, at most 1048576), startWith?: current (default: the format given, its JPEG quality or GIF/PNG-8 colors lowered; GIF then takes lossy 100)|auto (GIF for art with transparency or at most 256 colors (blended over the matte without transparency), else JPEG; the other one when the first can't reach the size and the art is opaque), use?: allSlices (default: the image, or the image slices' files together)|eachSlice (every image slice's file)|currentSlice (the `slice` given, else the selected image slice, else the first), slice?: n (1-based, from slice.list), preset?, …the settings of document.exportForWeb} the settings whose files fit in the size, searched by encoding at most 32 trial settings (each one encodes every image it measures); slices share one setting, which every scope changes → {targetBytes, achieved (false: no setting tried fits, and settings are the smallest one found), bytes (as use measures them), format, settings, trials, images, warnings}; writes nothing and changes no remembered setting",
has_doc,
optimize_to_file_size
),
cmd!(
query "webExport.settings",
"Save for Web Settings",
@@ -1054,6 +1063,297 @@ fn preview(s: &mut Session, p: &Value) -> Result<Value> {
Ok(out)
}
// ---------- Optimize to File Size ----------
/// The most trial settings `webExport.optimizeToFileSize` encodes. Each trial encodes every image
/// it measures once.
pub const OPTIMIZE_TRIALS: usize = 32;
/// The largest desired file size, in K (1 GiB).
pub const MAX_DESIRED_K: f64 = 1_048_576.0;
/// Where Optimize to File Size starts.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StartWith {
/// The current format, with its JPEG quality or palette colors lowered.
Current,
/// GIF or JPEG, by the image's content.
Auto,
}
/// The pixels `px` (`[x0, y0, x1, y1]`) of `r` as an image: borrowed when `px` is the whole render,
/// else a copy.
fn file_pixels(r: &WebRender, px: [u32; 4]) -> std::borrow::Cow<'_, [u8]> {
if px == [0, 0, r.width, r.height] { std::borrow::Cow::Borrowed(r.rgba.as_slice()) } else { std::borrow::Cow::Owned(crop(r, px)) }
}
/// The settings Optimize to File Size found.
#[derive(Clone, Debug)]
pub struct SizeFit {
pub settings: WebSettings,
/// The size the settings give the measured images.
pub bytes: usize,
/// Whether `bytes` is within the target.
pub achieved: bool,
/// The trial settings encoded.
pub trials: usize,
}
/// The files a search measures and the trials it has left.
struct Trials<'a> {
doc: &'a Document,
r: &'a WebRender,
/// The pixels (`[x0, y0, x1, y1]`) of each file in `r`.
files: &'a [[u32; 4]],
/// Measure the largest file (else the files together).
each: bool,
left: usize,
used: usize,
}
impl Trials<'_> {
/// The size `s` gives the files, encoded one at a time; `None` when no trial is left.
fn size(&mut self, s: &WebSettings) -> std::result::Result<Option<usize>, String> {
if self.left == 0 {
return Ok(None);
}
self.left -= 1;
self.used += 1;
let mut out = 0usize;
for &px in self.files {
let n = optimize(self.doc, &file_pixels(self.r, px), px[2] - px[0], px[3] - px[1], s)?.bytes.len();
out = if self.each { out.max(n) } else { out.saturating_add(n) };
}
Ok(Some(out))
}
}
/// `(settings, bytes)` of a trial.
pub type Trial = (WebSettings, usize);
/// Keep `(s, n)` in `smallest` when it is the smallest trial so far.
fn keep_smallest(smallest: &mut Option<Trial>, s: WebSettings, n: usize) {
if smallest.as_ref().is_none_or(|(_, b)| n < *b) {
*smallest = Some((s, n));
}
}
/// The values [`highest_within`] measures spread over its range before it narrows a step.
pub const OPTIMIZE_SAMPLES: u16 = 6;
/// Measures the size a setting gives; `None` when no trial is left.
pub type MeasureSize<'a> = dyn FnMut(&WebSettings) -> std::result::Result<Option<usize>, String> + 'a;
/// The highest value in `lo..hi` that `set` gives `start` whose size is within `target`, when the
/// value `hi` is over it. A lower value can give a larger file, so the search measures up to
/// [`OPTIMIZE_SAMPLES`] values spread over the range, from `hi - 1` down, stops at the first that
/// fits, and halves the step between it and the measured value above it, keeping the highest value
/// measured within `target`. `None` when no value measured fits or no trial is left; the trials over
/// the target go to `smallest`.
pub fn highest_within(
size: &mut MeasureSize,
start: &WebSettings,
(lo, hi): (u16, u16),
set: fn(&mut WebSettings, u16),
target: usize,
smallest: &mut Option<Trial>,
) -> std::result::Result<Option<Trial>, String> {
let with = |v: u16| {
let mut s = start.clone();
set(&mut s, v);
s
};
if lo >= hi {
return Ok(None);
}
let span = u32::from(hi - lo);
let samples = u32::from(OPTIMIZE_SAMPLES).min(span);
let (mut above, mut found) = (hi, None);
for i in (0..samples).rev() {
let step = if samples == 1 { 0 } else { (span - 1) * i / (samples - 1) };
let v = lo.saturating_add(u16::try_from(step).unwrap_or(0));
let s = with(v);
let Some(n) = size(&s)? else { return Ok(None) };
if n <= target {
found = Some((v, (s, n)));
break;
}
keep_smallest(smallest, s, n);
above = v;
}
let Some((mut lo, mut best)) = found else { return Ok(None) };
let mut hi = above;
while hi - lo > 1 {
let mid = lo + (hi - lo) / 2;
let s = with(mid);
let Some(n) = size(&s)? else { break };
if n <= target {
lo = mid;
best = (s, n);
} else {
keep_smallest(smallest, s, n);
hi = mid;
}
}
Ok(Some(best))
}
/// Sets the JPEG quality, for [`highest_within`].
pub fn set_quality(s: &mut WebSettings, v: u16) {
s.quality = u8::try_from(v).unwrap_or(100);
}
/// Sets the palette colors, for [`highest_within`].
pub fn set_colors(s: &mut WebSettings, v: u16) {
s.colors = v;
}
/// The best settings of `start`'s format within `target`: `start` when it fits, else the highest
/// JPEG quality or the most palette colors [`highest_within`] finds that fit, and for GIF, when none
/// is found, lossy 100 with the most colors that fit. When nothing tried fits, the smallest trial, not achieved.
/// `None` when no trial is left.
fn search_format(t: &mut Trials, start: &WebSettings, target: usize) -> std::result::Result<Option<SizeFit>, String> {
let fit = |(settings, bytes): Trial, achieved: bool| SizeFit { settings, bytes, achieved, trials: 0 };
let Some(n) = t.size(start)? else { return Ok(None) };
if n <= target {
return Ok(Some(fit((start.clone(), n), true)));
}
let mut smallest = Some((start.clone(), n));
let found = match start.format {
WebFormat::Jpg => highest_within(&mut |s: &WebSettings| t.size(s), start, (1, u16::from(start.quality)), set_quality, target, &mut smallest)?,
WebFormat::Gif | WebFormat::Png8 => {
match highest_within(&mut |s: &WebSettings| t.size(s), start, (2, start.colors), set_colors, target, &mut smallest)? {
None if start.format == WebFormat::Gif && start.lossy < 100 => {
let lossy = WebSettings { lossy: 100, ..start.clone() };
match t.size(&lossy)? {
Some(n) if n <= target => Some((lossy, n)),
Some(n) => {
keep_smallest(&mut smallest, lossy.clone(), n);
highest_within(&mut |s: &WebSettings| t.size(s), &lossy, (2, lossy.colors), set_colors, target, &mut smallest)?
}
None => None,
}
}
found => found,
}
}
WebFormat::Png24 => None,
};
Ok(match (found, smallest) {
(Some(f), _) => Some(fit(f, true)),
(None, Some(s)) => Some(fit(s, false)),
(None, None) => None,
})
}
/// The format Auto Select GIF/JPEG starts with, and whether the files (`[x0, y0, x1, y1]` of `r`)
/// are opaque: GIF for files with transparent pixels (when `transparency` keeps them) or at most
/// 256 colors, else JPEG. The colors counted are the ones the files are written with: without
/// `transparency`, the pixels blended over `matte`.
fn auto_format(r: &WebRender, files: &[[u32; 4]], transparency: bool, matte: [u8; 3]) -> (WebFormat, bool) {
let stride = r.width as usize * 4;
let row =
move |y: u32, x0: u32, x1: u32| r.rgba.get(y as usize * stride + x0 as usize * 4..y as usize * stride + x1 as usize * 4).unwrap_or_default();
let pixels = || files.iter().flat_map(move |&[x0, y0, x1, y1]| (y0..y1).flat_map(move |y| row(y, x0, x1).as_chunks::<4>().0.iter()));
let opaque = !transparency || pixels().all(|p| p[3] == 255);
if !opaque {
return (WebFormat::Gif, false);
}
let mut seen = HashSet::new();
// An opaque pixel blends to itself.
let few = pixels().all(|p| {
seen.insert(flatten(p, matte).next().unwrap_or_default());
seen.len() <= 256
});
(if few { WebFormat::Gif } else { WebFormat::Jpg }, true)
}
/// Optimize to File Size: the settings, from `s`, whose files (the pixels `[x0, y0, x1, y1]` of
/// `r`) fit in `target` bytes, measured together, or with `each` the largest one. At most
/// [`OPTIMIZE_TRIALS`] trial settings are encoded, and a trial encodes the files one at a time.
pub fn optimize_to_size(
doc: &Document,
r: &WebRender,
files: &[[u32; 4]],
s: &WebSettings,
start: StartWith,
each: bool,
target: usize,
) -> std::result::Result<SizeFit, String> {
let mut t = Trials { doc, r, files, each, left: OPTIMIZE_TRIALS, used: 0 };
let with = |format: WebFormat| WebSettings { format, ..s.clone() };
let found = match start {
_ if files.is_empty() => None,
StartWith::Current => search_format(&mut t, s, target)?,
StartWith::Auto => {
let (first, opaque) = auto_format(r, files, s.transparency, s.matte_rgb()?.unwrap_or([255; 3]));
let other = if first == WebFormat::Gif { WebFormat::Jpg } else { WebFormat::Gif };
match search_format(&mut t, &with(first), target)? {
Some(a) if !a.achieved && opaque => match search_format(&mut t, &with(other), target)? {
Some(b) if b.achieved || b.bytes < a.bytes => Some(b),
_ => Some(a),
},
a => a,
}
}
};
let mut best = found.ok_or("Optimize to File Size: there is no image to measure")?;
best.trials = t.used;
Ok(best)
}
fn optimize_to_file_size(s: &mut Session, p: &Value) -> Result<Value> {
const O: &str = "webExport.optimizeToFileSize";
let k = p
.get("desiredK")
.and_then(Value::as_f64)
.filter(|k| k.is_finite() && *k > 0.0 && *k <= MAX_DESIRED_K)
.ok_or_else(|| bad(O, "give `desiredK`, the desired file size in K (1024 bytes): a number above 0 and at most 1048576"))?;
let target = ((k * 1024.0).floor() as usize).max(1);
let start = match p.get("startWith").map(Value::as_str) {
None | Some(Some("current")) => StartWith::Current,
Some(Some("auto")) => StartWith::Auto,
Some(_) => return Err(bad(O, "`startWith` is `current` or `auto`")),
};
let scope = match p.get("use").map(Value::as_str) {
None if p.get("slice").is_some() => "currentSlice",
None => "allSlices",
Some(Some(u @ ("allSlices" | "eachSlice" | "currentSlice"))) => u,
Some(_) => return Err(bad(O, "`use` is `allSlices`, `eachSlice` or `currentSlice`")),
};
let slice = match p.get("slice").map(|v| v.as_u64().filter(|n| *n >= 1 && scope == "currentSlice")) {
None => None,
Some(Some(n)) => Some(n),
Some(None) => return Err(bad(O, "`slice` is a slice number from `slice.list`, with `use: currentSlice`")),
};
let settings = s.web_settings(p).map_err(|e| bad(O, e))?;
let st = s.doc()?;
let doc = &st.doc;
let failed = vectorcraft_render::decode_failures();
let r = render(doc, &settings).map_err(|e| bad(O, e))?;
let warnings = undecoded(failed);
let areas = doc.slice_layout();
let selected = super::slices::selected_slices(doc, &st.selection);
let cells = cells(&areas, &selected, &settings, &r).map_err(|e| bad(O, e))?;
let image_cells: Vec<&Cell> =
cells.iter().filter(|c| c.area.id.and_then(|id| doc.slice_options(id)).is_none_or(|o| o.kind == SliceKind::Image)).collect();
let picked: Vec<&Cell> = match (scope, slice) {
("currentSlice", Some(n)) => {
let c = image_cells.iter().find(|c| c.area.number as u64 == n);
vec![*c.ok_or_else(|| bad(O, format!("no slice {n} in the image (see slice.list)")))?]
}
("currentSlice", None) => {
image_cells.iter().find(|c| c.area.id.is_some_and(|id| selected.contains(&id))).or(image_cells.first()).copied().into_iter().collect()
}
_ => image_cells,
};
let files: Vec<[u32; 4]> = if cells.is_empty() { vec![[0, 0, r.width, r.height]] } else { picked.iter().map(|c| c.px).collect() };
let fit = optimize_to_size(doc, &r, &files, &settings, start, scope == "eachSlice", target).map_err(|e| bad(O, e))?;
Ok(json!({
"targetBytes": target, "achieved": fit.achieved, "bytes": fit.bytes, "format": fit.settings.format.id(),
"settings": fit.settings.to_json(), "trials": fit.trials, "images": files.len(), "warnings": warnings,
}))
}
fn settings(s: &mut Session, p: &Value) -> Result<Value> {
const S: &str = "webExport.settings";
let base = if bool_or(p, "reset", false) { WebSettings::default() } else { s.last_web_settings() };