mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-18 16:37:32 +00:00
Merge upstream/main into fix/8237-layers-alt-drop-copy-beside-itself
This commit is contained in:
@@ -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));
|
||||
|
||||
@@ -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
|
||||
),
|
||||
|
||||
@@ -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)),
|
||||
|
||||
@@ -417,9 +417,13 @@ fn encode_carrying_at(
|
||||
}
|
||||
let (flat, flattened) = flatten_for(cmd, doc, set, p)?;
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
if flattened {
|
||||
if let Some(o) = flattened {
|
||||
let kind = if set.standard.flattens() { set.standard.label() } else { set.compatibility.label() };
|
||||
notes.push(Note::loss(format!("transparency is flattened into opaque art and images ({kind} files have none): see the flattener preset")));
|
||||
let line_ppi = o.line_art_ppi.round() as u32;
|
||||
let grad_ppi = o.gradient_ppi.round() as u32;
|
||||
notes.push(Note::loss(format!(
|
||||
"transparency is flattened into opaque art and images ({kind} files have none) at {line_ppi} ppi line art and text, {grad_ppi} ppi gradients and meshes: see the flattener preset"
|
||||
)));
|
||||
}
|
||||
let r = super::super::rasterfx::export_pdf_with_report(flat.as_ref().unwrap_or(doc), &opts).map_err(|e| pdf_error(cmd, e))?;
|
||||
notes.extend(r.warnings.into_iter().map(Note::loss));
|
||||
@@ -438,9 +442,9 @@ pub const DEFAULT_FLATTENER: &str = "High Resolution";
|
||||
/// discarded overprints are dropped. Layers the pages leave out (non-printing ones, unless asked
|
||||
/// for) are left out of the flattening, hidden. → the document to write (`None`: `doc` as it is)
|
||||
/// and whether its transparency was flattened.
|
||||
fn flatten_for(cmd: &str, doc: &Document, set: &PdfSettings, p: &Value) -> Result<(Option<Document>, bool)> {
|
||||
fn flatten_for(cmd: &str, doc: &Document, set: &PdfSettings, p: &Value) -> Result<(Option<Document>, Option<FlattenOptions>)> {
|
||||
if !set.pdf13() {
|
||||
return Ok((None, false));
|
||||
return Ok((None, None));
|
||||
}
|
||||
let printed = if set.include_non_printing || set.create_layers { None } else { without_non_printing(&doc.layers) };
|
||||
let shown = printed.map(|layers| {
|
||||
@@ -456,8 +460,8 @@ fn flatten_for(cmd: &str, doc: &Document, set: &PdfSettings, p: &Value) -> Resul
|
||||
// its art: it is clipped to its regions (opaque inside them).
|
||||
o.clip_complex_regions = true;
|
||||
Ok(match flatten_document(shown.as_ref().unwrap_or(doc), &o)? {
|
||||
Some(flat) => (Some(flat), true),
|
||||
None => (shown, false),
|
||||
Some(flat) => (Some(flat), Some(o)),
|
||||
None => (shown, None),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -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)?;
|
||||
|
||||
@@ -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 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)}]}, 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
|
||||
),
|
||||
|
||||
@@ -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",
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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() };
|
||||
|
||||
Reference in New Issue
Block a user