mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-16 17:46:59 +00:00
Crop Image: the Control bar sets the cropped image's resolution, reference point and linked size
While Crop Image shows its box, the Control bar has a PPI list (72, 96, 150, 200 and 300 ppi, with the ones above the image's own disabled) and a PPI field, a reference point that X and Y name and that W and H resize about, and a link icon that keeps W and H in proportion. A linked size that would not fit the image is reduced with the other side in proportion. object.cropImage takes ppi: the cut pixels are resampled to it, with colors weighted by their alpha, and the image keeps the box's size. A box over the whole image with a new ppi only resamples it, and an image scaled differently across and down comes out with square pixels. ppi is refused outside 1 to 2400, above the image's own resolution (300 ppi for a linked image), and with trim. tool.setOption sets ppi, reference and linked for the Crop Image tool and refuses values it can't use. Docs: docs/mcp.md, docs/target-app-parity.md.
This commit is contained in:
@@ -133,7 +133,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Crop Image",
|
||||
["Object"],
|
||||
None,
|
||||
"{rect?: [x, y, width, height] | trim?: true (to the pixels that aren't fully transparent, pixel for pixel; an image with none to cut is left as it is, trimmed: false)} crop the selected image (default: to the artboard it sits on) → {id, width, height, trimmed? (with trim), warning? (without trim: the image couldn't be decoded, as object.rasterize says)}",
|
||||
"{rect?: [x, y, width, height] | trim?: true (to the pixels that aren't fully transparent, pixel for pixel; an image with none to cut is left as it is, trimmed: false), ppi?: number (without trim: the cropped image's resolution in pixels per inch, resampled from the cut pixels; 1 to 2400, at most the image's own, or 300 for a linked image; default the image's own; a rect over the whole image with a new ppi only resamples it)} crop the selected image (default: to the artboard it sits on) → {id, width, height, trimmed? (with trim), warning? (without trim: the image couldn't be decoded, as object.rasterize says)}",
|
||||
has_image,
|
||||
crop_image
|
||||
),
|
||||
@@ -967,10 +967,10 @@ fn polygon_path(pts: &[Point]) -> PathData {
|
||||
PathData::single(vectorcraft_geom::SubPath::new(pts.iter().map(|p| Anchor::corner(*p)).collect(), true))
|
||||
}
|
||||
|
||||
/// The part of an image under `r` (in document space) copied out of its pixels, as PNG bytes, with its size and
|
||||
/// placement. `None` when the image can't be cut that way (turned or skewed, CMYK, pixels that can't be read, or
|
||||
/// `r` not on the pixel grid), so the caller draws it instead.
|
||||
fn crop_pixels(doc: &vectorcraft_doc::Document, im: &ImageObject, r: Rect) -> Option<(Vec<u8>, u32, u32, Affine)> {
|
||||
/// The part of an image under `r` (in document space) copied out of its pixels, with its placement. `None` when
|
||||
/// the image can't be cut that way (turned or skewed, CMYK, pixels that can't be read, or `r` not on the pixel
|
||||
/// grid), so the caller draws it instead.
|
||||
fn crop_pixels(doc: &vectorcraft_doc::Document, im: &ImageObject, r: Rect) -> Option<(image::RgbaImage, Affine)> {
|
||||
let blob = doc.images.get(&im.key)?;
|
||||
let [a, b, c, d, _, _] = im.xf.as_coeffs();
|
||||
if blob.is_cmyk() || b.abs() > 1e-9 || c.abs() > 1e-9 || a.abs() < 1e-9 || d.abs() < 1e-9 {
|
||||
@@ -996,9 +996,64 @@ fn crop_pixels(doc: &vectorcraft_doc::Document, im: &ImageObject, r: Rect) -> Op
|
||||
return None;
|
||||
}
|
||||
let cut = image::imageops::crop_imm(&px, x0, y0, x1 - x0, y1 - y0).to_image();
|
||||
Some((cut, im.xf * Affine::translate((f64::from(x0), f64::from(y0)))))
|
||||
}
|
||||
|
||||
/// Crop Image's `ppi`: the resolution the cropped image is resampled to, in pixels per point, or `None` to keep
|
||||
/// the image's own. Refuses a resolution that isn't a positive number or is above what the image allows: its own,
|
||||
/// or 300 ppi for a linked image, within 1 to 2400 ppi as Rasterize's.
|
||||
fn crop_resolution(p: &Value, im: &ImageObject) -> Result<Option<f64>> {
|
||||
const C: &str = "object.cropImage";
|
||||
let Some(ppi) = p.get("ppi").filter(|v| !v.is_null()) else { return Ok(None) };
|
||||
let ppi = ppi.as_f64().filter(|v| v.is_finite() && *v > 0.0).ok_or_else(|| bad(C, format!("ppi must be a positive number, not {ppi}")))?;
|
||||
if !(1.0..=2400.0).contains(&ppi) {
|
||||
return Err(bad(C, "ppi must be between 1 and 2400"));
|
||||
}
|
||||
let (_, max) = vectorcraft_tools::cropimage::image_ppi(im);
|
||||
if ppi > max + 1e-6 {
|
||||
let max = (max * 100.0 + 1e-6).floor() / 100.0;
|
||||
return Err(bad(C, format!("ppi can't be more than {max} for this image")));
|
||||
}
|
||||
// An image whose pixels are not square is resampled on both sides, even at its denser side's resolution.
|
||||
Ok((!vectorcraft_tools::cropimage::keeps_resolution(im, ppi, 1e-6)).then_some(ppi / 72.0))
|
||||
}
|
||||
|
||||
/// A `w` × `h` image resampled at a resolution asked for, held to the size a drawing may have ([`MAX_PIXELS`], and
|
||||
/// no side past the renderer's).
|
||||
fn check_crop_size(w: f64, h: f64) -> Result<()> {
|
||||
let side = f64::from(vectorcraft_render::MAX_RASTER_SIDE);
|
||||
if w * h > MAX_PIXELS || w > side || h > side {
|
||||
let (w, h) = (w as u64, h as u64);
|
||||
return Err(bad("object.cropImage", format!("an image of {w} × {h} pixels is too large to draw")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `img` resampled to `w` × `h` with its colors weighted by their alpha, so the color of a fully
|
||||
/// transparent pixel does not show at the edges of what is opaque.
|
||||
fn resize_premultiplied(img: &image::RgbaImage, w: u32, h: u32) -> image::RgbaImage {
|
||||
let mut pre = img.clone();
|
||||
for p in pre.pixels_mut() {
|
||||
let a = u32::from(p[3]);
|
||||
for c in &mut p.0[..3] {
|
||||
*c = ((u32::from(*c) * a + 127) / 255) as u8;
|
||||
}
|
||||
}
|
||||
let mut out = image::imageops::resize(&pre, w, h, image::imageops::FilterType::Lanczos3);
|
||||
for p in out.pixels_mut() {
|
||||
let a = u32::from(p[3]);
|
||||
for c in &mut p.0[..3] {
|
||||
*c = (u32::from(*c) * 255 + a / 2).checked_div(a).unwrap_or(0).min(255) as u8;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `img` as PNG bytes.
|
||||
fn encode_png(img: &image::RgbaImage) -> Result<Vec<u8>> {
|
||||
let mut png = Vec::new();
|
||||
cut.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
|
||||
Some((png, x1 - x0, y1 - y0, im.xf * Affine::translate((f64::from(x0), f64::from(y0)))))
|
||||
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| bad("object.cropImage", e.to_string()))?;
|
||||
Ok(png)
|
||||
}
|
||||
|
||||
fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -1014,9 +1069,13 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let node = st.doc.node(id).cloned().ok_or(EngineError::NoNode(id))?;
|
||||
let NodeKind::Image(im) = &node.kind else { return Err(bad(C, "select an image")) };
|
||||
if switch_or(p, "trim", false, C)? {
|
||||
if p.get("ppi").is_some_and(|v| !v.is_null()) {
|
||||
return Err(bad(C, "trim keeps the image's pixels as they are: leave out ppi"));
|
||||
}
|
||||
return trim_image(s, id, (**im).clone());
|
||||
}
|
||||
let ib = node.geometric_bounds().ok_or_else(|| bad(C, "image has no bounds"))?;
|
||||
let target = crop_resolution(p, im)?;
|
||||
let rect = match p.get("rect").filter(|v| !v.is_null()) {
|
||||
Some(Value::Array(a)) if a.len() == 4 => {
|
||||
let v: Vec<f64> = a.iter().filter_map(Value::as_f64).collect();
|
||||
@@ -1038,16 +1097,40 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if r.width() <= 0.0 || r.height() <= 0.0 {
|
||||
return Err(bad(C, "crop rectangle doesn't overlap the image"));
|
||||
}
|
||||
if (r.x0 - ib.x0).abs() < 1e-6 && (r.y0 - ib.y0).abs() < 1e-6 && (r.x1 - ib.x1).abs() < 1e-6 && (r.y1 - ib.y1).abs() < 1e-6 {
|
||||
// A box over the whole image still resamples it to a new resolution.
|
||||
let whole = (r.x0 - ib.x0).abs() < 1e-6 && (r.y0 - ib.y0).abs() < 1e-6 && (r.x1 - ib.x1).abs() < 1e-6 && (r.y1 - ib.y1).abs() < 1e-6;
|
||||
if whole && target.is_none() {
|
||||
return Err(bad(C, "nothing to crop"));
|
||||
}
|
||||
// A plain, axis-aligned raster is cut straight from its pixels, so nothing is resampled.
|
||||
if let Some((png, cw, ch, xf)) = crop_pixels(&st.doc, im, r) {
|
||||
put_pixels(s, id, png, cw, ch, xf)?;
|
||||
if let Some(t) = target {
|
||||
check_crop_size((r.width() * t).round().max(1.0), (r.height() * t).round().max(1.0))?;
|
||||
}
|
||||
// A plain, axis-aligned raster is cut straight from its pixels, so nothing is resampled unless a
|
||||
// resolution is asked for.
|
||||
if let Some((cut, xf)) = crop_pixels(&st.doc, im, r) {
|
||||
let (cut, xf) = match target {
|
||||
Some(t) => {
|
||||
let (cw, ch) = cut.dimensions();
|
||||
let (w, h) = ((r.width() * t).round().max(1.0) as u32, (r.height() * t).round().max(1.0) as u32);
|
||||
let resized = resize_premultiplied(&cut, w, h);
|
||||
(resized, xf * Affine::scale_non_uniform(f64::from(cw) / f64::from(w), f64::from(ch) / f64::from(h)))
|
||||
}
|
||||
None => (cut, xf),
|
||||
};
|
||||
let (cw, ch) = cut.dimensions();
|
||||
put_pixels(s, id, encode_png(&cut)?, cw, ch, xf)?;
|
||||
return Ok(json!({ "id": id.0, "width": cw, "height": ch }));
|
||||
}
|
||||
// Keep the image's pixel density.
|
||||
let scale = (im.width as f64 / ib.width().max(1e-9)).max(im.height as f64 / ib.height().max(1e-9));
|
||||
// Drawn at the image's pixel density, or for a resolution asked for at up to twice that (no more
|
||||
// than the image's own, measured on its pixel grid however it is turned, nor past the size a
|
||||
// drawing may have), and resampled to it.
|
||||
let native = (im.width as f64 / ib.width().max(1e-9)).max(im.height as f64 / ib.height().max(1e-9));
|
||||
let scale = target.map_or(native, |t| {
|
||||
let own = native.max(vectorcraft_tools::cropimage::image_ppi(im).0 / 72.0);
|
||||
let side = f64::from(vectorcraft_render::MAX_RASTER_SIDE);
|
||||
let budget = (MAX_PIXELS / (r.width() * r.height()).max(1e-9)).sqrt().min(side / r.width().max(1e-9)).min(side / r.height().max(1e-9));
|
||||
(2.0 * t).min(own).min(budget).max(t.min(own))
|
||||
});
|
||||
let mut bare = node.clone();
|
||||
bare.opacity = 1.0;
|
||||
bare.blend = Default::default();
|
||||
@@ -1062,19 +1145,23 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let region = Rect::new(r.x0, r.y0, r.x0 + (r.width() * scale).round().max(1.0) / scale, r.y0 + (r.height() * scale).round().max(1.0) / scale);
|
||||
let (png, w, h, warning) =
|
||||
render_png(&tmp, region, scale, &RasterExportOptions::default().render_options(RasterFormat::Png), RasterColorModel::Document)?;
|
||||
// At a resolution asked for, the drawing is resampled to the box's size at that resolution and
|
||||
// fitted to the box, so the image keeps its size.
|
||||
let (png, w, h, xf) = match target {
|
||||
Some(t) => {
|
||||
let drawn = image::load_from_memory(&png).map_err(|e| bad(C, e.to_string()))?.to_rgba8();
|
||||
let (tw, th) = ((r.width() * t).round().max(1.0) as u32, (r.height() * t).round().max(1.0) as u32);
|
||||
let resized = resize_premultiplied(&drawn, tw, th);
|
||||
let xf = Affine::translate(r.origin().to_vec2()) * Affine::scale_non_uniform(r.width() / f64::from(tw), r.height() / f64::from(th));
|
||||
(encode_png(&resized)?, tw, th, xf)
|
||||
}
|
||||
None => (png, w, h, Affine::translate(region.origin().to_vec2()) * Affine::scale(1.0 / scale)),
|
||||
};
|
||||
s.edit("Crop Image", |d, _| {
|
||||
let key = unique_key(d, "crop");
|
||||
d.images.insert(key.clone(), vectorcraft_doc::ImageBlob::new("image/png", png));
|
||||
if let Some(n) = d.node_mut(id) {
|
||||
n.kind = NodeKind::Image(Box::new(ImageObject {
|
||||
key,
|
||||
width: w,
|
||||
height: h,
|
||||
xf: Affine::translate(region.origin().to_vec2()) * Affine::scale(1.0 / scale),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
}));
|
||||
n.kind = NodeKind::Image(Box::new(ImageObject { key, width: w, height: h, xf, link: None, placement: Default::default(), pixels: None }));
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
@@ -1588,6 +1588,166 @@ fn crop_image_to_a_rect_between_pixels_keeps_the_rect() {
|
||||
assert!(close(b.x0, 21.0) && close(b.y0, 11.0) && close(b.width(), 60.0) && close(b.height(), 40.0), "{b:?}");
|
||||
}
|
||||
|
||||
/// Crop Image's `ppi` resamples the cut pixels to that resolution; the image keeps the box's size.
|
||||
#[test]
|
||||
fn crop_image_resamples_the_cut_to_the_resolution_asked_for() {
|
||||
let (mut s, img, px) = busy_image_at_two_points_a_pixel();
|
||||
// The image is 36 ppi (2 pt a pixel); 18 ppi halves the cut's 30 × 20 pixels.
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": 18})).unwrap();
|
||||
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (15, 10), "{r}");
|
||||
let b = bounds(&s, img);
|
||||
assert!(close(b.x0, 20.0) && close(b.y0, 10.0) && close(b.width(), 60.0) && close(b.height(), 40.0), "{b:?}");
|
||||
let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") };
|
||||
let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8();
|
||||
let cut = image::imageops::crop_imm(&px, 10, 5, 30, 20).to_image();
|
||||
assert_eq!(out, image::imageops::resize(&cut, 15, 10, image::imageops::FilterType::Lanczos3));
|
||||
}
|
||||
|
||||
/// Resampling weights colors by their alpha: the color hidden in fully transparent pixels does not
|
||||
/// tint the partly transparent edge of what is opaque.
|
||||
#[test]
|
||||
fn crop_image_resampling_keeps_hidden_colors_out_of_the_edges() {
|
||||
// Opaque white on the left half, fully transparent red on the right.
|
||||
let px = image::RgbaImage::from_fn(40, 20, |x, _| if x < 20 { image::Rgba([255, 255, 255, 255]) } else { image::Rgba([255, 0, 0, 0]) });
|
||||
let mut png = Vec::new();
|
||||
px.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.execute("document.open", &json!({"name": "edge.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
let img = selected(&s)[0];
|
||||
s.execute("object.scale", &json!({"sx": 200, "origin": [0, 0]})).unwrap();
|
||||
// 36 ppi to 15 ppi over pixels 5 to 35 across: the edge pixels mix white and clear.
|
||||
s.execute("object.cropImage", &json!({"rect": [10, 0, 60, 40], "ppi": 15})).unwrap();
|
||||
let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") };
|
||||
let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8();
|
||||
assert!(out.pixels().any(|p| p[3] > 0 && p[3] < 255), "the edge is partly transparent");
|
||||
for p in out.pixels().filter(|p| p[3] > 0) {
|
||||
assert!(p[1] >= 250 && p[2] >= 250, "white, not tinted red: {p:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A box between pixels is drawn at the resolution asked for, and lands on the box.
|
||||
#[test]
|
||||
fn crop_image_between_pixels_draws_at_the_resolution_asked_for() {
|
||||
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [21, 11, 60, 40], "ppi": 18})).unwrap();
|
||||
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (15, 10), "{r}");
|
||||
let b = bounds(&s, img);
|
||||
assert!(close(b.x0, 21.0) && close(b.y0, 11.0) && close(b.width(), 60.0) && close(b.height(), 40.0), "{b:?}");
|
||||
// 100 × 30 pt at 20 ppi is 27.8 × 8.3 px: the 28 × 8 px drawn are fitted to the box.
|
||||
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [21, 11, 100, 30], "ppi": 20})).unwrap();
|
||||
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (28, 8), "{r}");
|
||||
let b = bounds(&s, img);
|
||||
assert!(close(b.x0, 21.0) && close(b.y0, 11.0) && close(b.width(), 100.0) && close(b.height(), 30.0), "{b:?}");
|
||||
}
|
||||
|
||||
/// A box over the whole image with a new resolution resamples it; with the image's own there is
|
||||
/// nothing to do.
|
||||
#[test]
|
||||
fn crop_image_over_the_whole_image_only_resamples_it() {
|
||||
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
|
||||
let before = undo_len(&s);
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [0, 0, 200, 160], "ppi": 36}));
|
||||
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "nothing to crop"), "{r:?}");
|
||||
assert_eq!(undo_len(&s), before);
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [0, 0, 200, 160], "ppi": 9})).unwrap();
|
||||
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (25, 20), "{r}");
|
||||
assert_eq!(undo_len(&s), before + 1, "one undo step");
|
||||
let b = bounds(&s, img);
|
||||
assert!(close(b.x0, 0.0) && close(b.y0, 0.0) && close(b.width(), 200.0) && close(b.height(), 160.0), "{b:?}");
|
||||
}
|
||||
|
||||
/// An image scaled more down than across is resampled on both sides at the resolution of its denser
|
||||
/// side, so its pixels come out square.
|
||||
#[test]
|
||||
fn crop_image_resamples_pixels_that_are_not_square() {
|
||||
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
|
||||
// 2 pt a pixel across (36 ppi) and 1 pt a pixel down (72 ppi), 200 × 80 pt.
|
||||
s.execute("object.scale", &json!({"sx": 100, "sy": 50, "origin": [0, 0]})).unwrap();
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [0, 0, 200, 80], "ppi": 72})).unwrap();
|
||||
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (200, 80), "{r}");
|
||||
let b = bounds(&s, img);
|
||||
assert!(close(b.x0, 0.0) && close(b.y0, 0.0) && close(b.width(), 200.0) && close(b.height(), 80.0), "{b:?}");
|
||||
}
|
||||
|
||||
/// Crop Image refuses a resolution that isn't a positive number, one above the image's own, and one
|
||||
/// with trim; the image stays as it was.
|
||||
#[test]
|
||||
fn crop_image_refuses_a_resolution_it_cannot_give() {
|
||||
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
|
||||
let before = (undo_len(&s), node(&s, img));
|
||||
let refused = |s: &mut Session, p: Value, want: &str| {
|
||||
let r = s.execute("object.cropImage", &p);
|
||||
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == want), "{p}: {r:?}");
|
||||
};
|
||||
for v in [json!(0), json!(-72), json!("high"), json!(true)] {
|
||||
refused(&mut s, json!({"rect": [20, 10, 60, 40], "ppi": v}), &format!("ppi must be a positive number, not {v}"));
|
||||
}
|
||||
for v in [0.5, 1e-310, 2401.0] {
|
||||
refused(&mut s, json!({"rect": [20, 10, 60, 40], "ppi": v}), "ppi must be between 1 and 2400");
|
||||
}
|
||||
refused(&mut s, json!({"rect": [20, 10, 60, 40], "ppi": 72}), "ppi can't be more than 36 for this image");
|
||||
refused(&mut s, json!({"trim": true, "ppi": 18}), "trim keeps the image's pixels as they are: leave out ppi");
|
||||
assert_eq!((undo_len(&s), node(&s, img)), before);
|
||||
// A null ppi keeps the image's own, as a missing one does.
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": null})).unwrap();
|
||||
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (30, 20), "{r}");
|
||||
}
|
||||
|
||||
/// A turned image keeps its own resolution as the limit (not the density across its bounding box),
|
||||
/// and its drawn cut is resampled to the box's size at the resolution asked for.
|
||||
#[test]
|
||||
fn crop_image_of_a_turned_image_resamples_its_drawing() {
|
||||
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
|
||||
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
|
||||
let b = bounds(&s, img);
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [b.x0 + 40.0, b.y0 + 40.0, 72, 36], "ppi": 37}));
|
||||
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "ppi can't be more than 36 for this image"), "{r:?}");
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [b.x0 + 40.0, b.y0 + 40.0, 72, 36], "ppi": 18})).unwrap();
|
||||
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (18, 9), "{r}");
|
||||
let c = bounds(&s, img);
|
||||
assert!(close(c.x0, b.x0 + 40.0) && close(c.y0, b.y0 + 40.0) && close(c.width(), 72.0) && close(c.height(), 36.0), "{c:?}");
|
||||
}
|
||||
|
||||
/// A linked image can be cropped to up to 300 ppi, even above its own; the crop embeds it.
|
||||
#[test]
|
||||
fn crop_image_takes_a_linked_image_up_to_300_ppi() {
|
||||
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
|
||||
s.edit("Link", |d, _| {
|
||||
let NodeKind::Image(im) = &mut d.node_mut(img).unwrap().kind else { panic!("not an image") };
|
||||
im.link = Some(vectorcraft_doc::LinkInfo::new("art.png"));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": 301}));
|
||||
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "ppi can't be more than 300 for this image"), "{r:?}");
|
||||
// 72 ppi: a pixel a point.
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": 72})).unwrap();
|
||||
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (60, 40), "{r}");
|
||||
let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") };
|
||||
assert!(im.link.is_none());
|
||||
}
|
||||
|
||||
/// `tool.setOption` refuses a Crop Image resolution, reference point or link it can't use, and
|
||||
/// changes nothing.
|
||||
#[test]
|
||||
fn crop_image_tool_options_refuse_values_they_cannot_use() {
|
||||
let (mut s, _, _) = busy_image_at_two_points_a_pixel();
|
||||
s.select_tool("cropImage", ViewInfo::default()).unwrap();
|
||||
s.set_tool_option_cmd(&json!({"values": {"ppi": 18, "reference": 0, "linked": true}})).unwrap();
|
||||
// 72 ppi is above the selected 36 ppi image's own.
|
||||
for (key, value) in
|
||||
[("ppi", json!("high")), ("ppi", json!(-1)), ("ppi", json!(0.5)), ("ppi", json!(72)), ("reference", json!(9)), ("linked", json!(1))]
|
||||
{
|
||||
assert!(s.set_tool_option_cmd(&json!({"key": key, "value": value})).is_err(), "{key}: {value}");
|
||||
}
|
||||
let o = s.tool_options();
|
||||
assert_eq!((o["ppi"].clone(), o["reference"].clone(), o["linked"].clone()), (json!(18.0), json!(0), json!(true)), "{o}");
|
||||
s.set_tool_option_cmd(&json!({"key": "ppi", "value": null})).unwrap();
|
||||
assert!(s.tool_options().get("ppi").is_none());
|
||||
}
|
||||
|
||||
/// Crop Image refuses a `rect` that is not an array, such as text, and the image stays as it was; a
|
||||
/// null `rect` crops to the artboard as a missing one does.
|
||||
#[test]
|
||||
|
||||
@@ -1324,6 +1324,18 @@ impl Session {
|
||||
}
|
||||
// Every value is checked before any is set, so an invalid one changes nothing.
|
||||
vectorcraft_tools::builder::check_builder_options(tool.unwrap_or(self.tool.id()), &values)?;
|
||||
if tool.unwrap_or(self.tool.id()) == vectorcraft_tools::cropimage::ID {
|
||||
use vectorcraft_tools::cropimage as crop;
|
||||
// The most the selected image can be cropped to, when one is selected.
|
||||
let max = self.doc().ok().and_then(|st| {
|
||||
let (id, _) = crop::selected_image(&st.doc, &st.selection)?;
|
||||
match &st.doc.node(id)?.kind {
|
||||
vectorcraft_doc::NodeKind::Image(im) => Some(crop::image_ppi(im).1),
|
||||
_ => None,
|
||||
}
|
||||
});
|
||||
crop::check_options(&values, max)?;
|
||||
}
|
||||
// The Place queue is read later, by a click outside any automation scope: its files must
|
||||
// be readable now, under the roots of whoever sets it.
|
||||
if let Some(entries) = values.get("queue").and_then(|q| q.get("entries")).and_then(Value::as_array) {
|
||||
|
||||
Reference in New Issue
Block a user