From 34e52df5de9d0544513ae703dec0b0ad2910cecb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 07:26:01 -0800 Subject: [PATCH] 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. --- crates/engine/src/cmd/menucmds.rs | 131 ++++++++++--- crates/engine/src/tests/menucmds.rs | 160 +++++++++++++++ crates/engine/src/tooling.rs | 12 ++ crates/tools/src/cropimage.rs | 294 ++++++++++++++++++++++++++-- crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/de.tsv | 2 + crates/ui-egui/src/i18n/fr.tsv | 2 + crates/ui-egui/src/i18n/hi.tsv | 2 + crates/ui-egui/src/i18n/hu.tsv | 2 + crates/ui-egui/src/i18n/it.tsv | 2 + crates/ui-egui/src/i18n/ja.tsv | 2 + crates/ui-egui/src/i18n/ko.tsv | 2 + crates/ui-egui/src/i18n/nl.tsv | 2 + crates/ui-egui/src/i18n/pl.tsv | 2 + crates/ui-egui/src/i18n/pt-br.tsv | 2 + crates/ui-egui/src/i18n/sv.tsv | 2 + crates/ui-egui/src/i18n/tr.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + crates/ui-egui/src/toolbar.rs | 69 +++++-- docs/mcp.md | 15 ++ docs/target-app-parity.md | 1 + 23 files changed, 661 insertions(+), 53 deletions(-) diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 1ab0e0b670..e7163c13d7 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -133,7 +133,7 @@ pub fn specs() -> Vec { "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, 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> { + 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> { 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 { @@ -1014,9 +1069,13 @@ fn crop_image(s: &mut Session, p: &Value) -> Result { 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 = a.iter().filter_map(Value::as_f64).collect(); @@ -1038,16 +1097,40 @@ fn crop_image(s: &mut Session, p: &Value) -> Result { 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 { 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(()) })?; diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index 1151f83910..841f6184f8 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -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] diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index f6bc163e65..a5b9958e93 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -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) { diff --git a/crates/tools/src/cropimage.rs b/crates/tools/src/cropimage.rs index 0245f75112..abc2b55b53 100644 --- a/crates/tools/src/cropimage.rs +++ b/crates/tools/src/cropimage.rs @@ -2,10 +2,12 @@ //! its artboard (the whole image when it lies inside one); its handles and its inside drag it, //! always within the image, and the part outside it is dimmed. Enter (or the Control bar's Apply) //! crops the image to it (`object.cropImage {rect}`), Escape (or Cancel) leaves it as it was; both -//! go back to the Selection tool. The Control bar edits the box through the `rect` option. +//! go back to the Selection tool. The Control bar edits the box through the `rect` option, the +//! point its X and Y name through `reference`, whether its W and H keep their proportions through +//! `linked`, and the cropped image's resolution through `ppi`. use serde_json::{Value, json}; -use vectorcraft_doc::{Document, NodeId, NodeKind, Selection}; +use vectorcraft_doc::{Document, ImageObject, NodeId, NodeKind, Selection}; use vectorcraft_geom::{Point, Rect, Vec2}; use crate::bbox::{Handle, hit_handle}; @@ -18,6 +20,103 @@ pub const ID: &str = "cropImage"; /// The smallest the box gets, in points. const MIN: f64 = 1.0; +/// The resolutions the Control bar's PPI list offers; those above the image's own are disabled. +pub const PPI_CHOICES: [f64; 5] = [72.0, 96.0, 150.0, 200.0, 300.0]; + +/// The highest resolution a linked image can be cropped to. +pub const LINKED_MAX_PPI: f64 = 300.0; + +/// The reference point the box's X and Y name by default: its center (of the nine points of +/// [`vectorcraft_geom::reference_point`], left to right and top to bottom). +pub const CENTER: usize = 4; + +/// An image's own resolution in pixels per inch (along its denser side, measured on its pixel +/// grid, so turning it changes nothing), and the highest resolution it can be cropped to: its own, +/// or [`LINKED_MAX_PPI`] for a linked image. +pub fn image_ppi(im: &ImageObject) -> (f64, f64) { + let [a, b, c, d, _, _] = im.xf.as_coeffs(); + // The document lengths of one pixel's sides. + let (sx, sy) = (a.hypot(b), c.hypot(d)); + let own = 72.0 / sx.min(sy).max(1e-9); + (own, if im.link.is_some() { LINKED_MAX_PPI } else { own }) +} + +/// Whether cropping `im` at `ppi` keeps its pixels as they are: its pixels are square (the same +/// resolution across and down) and at that resolution, within `tolerance` ppi. +pub fn keeps_resolution(im: &ImageObject, ppi: f64, tolerance: f64) -> bool { + let [a, b, c, d, _, _] = im.xf.as_coeffs(); + let (x, y) = (72.0 / a.hypot(b).max(1e-9), 72.0 / c.hypot(d).max(1e-9)); + (x - ppi).abs() <= tolerance && (y - ppi).abs() <= tolerance +} + +/// Checks the values `tool.setOption` gives the tool before any is set: `ppi` a number from 1 to +/// 2400, and no more than `max` (the selected image's limit, from [`image_ppi`]), or null; +/// `reference` a whole number from 0 to 8; `linked` true or false. +pub fn check_options(values: &serde_json::Map, max: Option) -> Result<(), String> { + for (key, v) in values { + let error = match key.as_str() { + "ppi" if v.is_null() => None, + "ppi" => match v.as_f64().filter(|n| (1.0..=2400.0).contains(n)) { + None => Some(format!("`ppi` must be a number from 1 to 2400 or null, not {v}")), + Some(n) => { + max.filter(|m| n > m + 1e-6).map(|m| format!("`ppi` can't be more than {} for this image", (m * 100.0 + 1e-6).floor() / 100.0)) + } + }, + "reference" => (!v.as_u64().is_some_and(|n| n <= 8)).then(|| format!("`reference` must be a whole number from 0 to 8, not {v}")), + "linked" => (!v.is_boolean()).then(|| format!("`linked` must be true or false, not {v}")), + _ => None, + }; + if let Some(e) = error { + return Err(e); + } + } + Ok(()) +} + +/// The box `r` over an image with bounds `image`, with one Control bar field set: `x` or `y` moves +/// the box so its `reference` point is there; `width` or `height` resizes it about that point, the +/// other side following in proportion when `linked`. Sizes below [`MIN`] are raised to it. A +/// linked size is held to the image with both sides scaled together, and a box that fits is slid +/// back within the image, so its proportions survive being kept within it. `None` for another key +/// or a value that isn't finite. +pub fn edited_box(r: Rect, image: Rect, reference: usize, linked: bool, key: &str, v: f64) -> Option { + if !v.is_finite() { + return None; + } + let p = vectorcraft_geom::reference_point(r, reference); + let (mut w, mut h) = (r.width(), r.height()); + let fit = |b: Rect| if b.width() <= image.width() + 1e-9 && b.height() <= image.height() + 1e-9 { slid_within(b, image) } else { b }; + match key { + "x" => return Some(fit(r + Vec2::new(v - p.x, 0.0))), + "y" => return Some(fit(r + Vec2::new(0.0, v - p.y))), + "width" => { + let nw = v.max(MIN); + if linked && w > 0.0 { + h = (h * nw / w).max(MIN); + } + w = nw; + } + "height" => { + let nh = v.max(MIN); + if linked && h > 0.0 { + w = (w * nh / h).max(MIN); + } + h = nh; + } + _ => return None, + } + if linked { + let k = (image.width() / w).min(image.height() / h).min(1.0); + if k.is_finite() && k > 0.0 { + (w, h) = (w * k, h * k); + } + } + // The reference point keeps its place: it sits at the same fraction of the new box. + let (fx, fy) = ((reference % 3) as f64 / 2.0, (reference / 3).min(2) as f64 / 2.0); + let (x0, y0) = (p.x - w * fx, p.y - h * fy); + Some(fit(Rect::new(x0, y0, x0 + w, y0 + h))) +} + /// Create the Crop Image tool by id (None = not ours). pub fn create(id: &str) -> Option> { (id == ID).then(|| Box::new(CropImageTool::default()) as Box) @@ -75,7 +174,6 @@ enum Drag { Move(Point, Rect), } -#[derive(Default)] pub struct CropImageTool { /// The box, for the image it was made for (None: set from outside, for the selected image); /// None until it's dragged or set. @@ -83,6 +181,18 @@ pub struct CropImageTool { drag: Option, /// Where the pointer last was on the canvas (measurement label during a drag). last: Point, + /// The cropped image's resolution in pixels per inch (None: the image's own). + ppi: Option, + /// The point of the box the Control bar's X and Y name (0..=8, [`CENTER`] by default). + reference: usize, + /// Whether the Control bar's W and H keep the box's proportions. + linked: bool, +} + +impl Default for CropImageTool { + fn default() -> Self { + Self { rect: None, drag: None, last: Point::ZERO, ppi: None, reference: CENTER, linked: false } + } } impl CropImageTool { @@ -93,24 +203,39 @@ impl CropImageTool { crop_box(cx.doc, cx.selection, set) } - /// Crop to the box and go back to the Selection tool (only back when it covers the image). + /// Crop to the box at the chosen resolution and go back to the Selection tool (only back when + /// the box covers the image and the resolution is the image's own). fn apply(&mut self, cx: &ToolContext) -> Vec { let current = self.current(cx); + let ppi = self.ppi; self.reset(); let mut out = vec![]; - if let Some((_, image, r)) = current - && !same(r, image) - { - out.push(Action::Exec("object.cropImage".into(), json!({ "rect": [r.x0, r.y0, r.width(), r.height()] }))); + if let Some((id, image, r)) = current { + let im = match cx.doc.node(id).map(|n| &n.kind) { + Some(NodeKind::Image(im)) => Some(&**im), + _ => None, + }; + let max = im.map_or(f64::INFINITY, |im| image_ppi(im).1); + // A resolution set before this image was selected is held to this image's limit. + let resample = ppi.map(|v| v.min(max)).filter(|v| im.is_none_or(|im| !keeps_resolution(im, *v, 1e-3))); + if !same(r, image) || resample.is_some() { + let mut p = json!({ "rect": [r.x0, r.y0, r.width(), r.height()] }); + if let Some(v) = resample { + p["ppi"] = json!(v); + } + out.push(Action::Exec("object.cropImage".into(), p)); + } } out.push(Action::SwitchTool("selection".into())); out } + /// Forget the box and the resolution; the reference point and the link stay as they were set. fn reset(&mut self) { self.rect = None; self.drag = None; self.last = Point::ZERO; + self.ppi = None; } } @@ -242,19 +367,40 @@ impl Tool for CropImageTool { } /// `rect`: the box as `[x, y, width, height]` once it's been dragged or set (until then it's - /// [`initial_box`]). + /// [`initial_box`]); `ppi` once it's been set (until then the image's own); `reference` (0..=8) + /// and `linked`. fn options(&self) -> Value { - match self.rect { - Some((_, r)) => json!({ "rect": [r.x0, r.y0, r.width(), r.height()] }), - None => json!({}), + let mut o = json!({ "reference": self.reference, "linked": self.linked }); + if let Some((_, r)) = self.rect { + o["rect"] = json!([r.x0, r.y0, r.width(), r.height()]); } + if let Some(v) = self.ppi { + o["ppi"] = json!(v); + } + o } /// `rect` `[x, y, width, height]` sets the box (kept within the selected image when used); - /// anything else puts it back where it starts. + /// anything else puts it back where it starts. `ppi` a positive number sets the cropped + /// image's resolution (null: the image's own). `reference` a whole number 0..=8 sets the point X and Y name, and `linked` + /// true or false the link of W and H. `tool.setOption` refuses other values of those three + /// ([`check_options`]); one that reaches the tool anyway puts that setting back to its default. fn set_option(&mut self, key: &str, value: &Value) { - if key != "rect" { - return; + match key { + "ppi" => { + self.ppi = value.as_f64().filter(|v| v.is_finite() && *v > 0.0); + return; + } + "reference" => { + self.reference = value.as_u64().filter(|v| *v <= 8).map_or(CENTER, |v| v as usize); + return; + } + "linked" => { + self.linked = value.as_bool().unwrap_or(false); + return; + } + "rect" => {} + _ => return, } // Invalid components must discard the whole box, not silently shift the // coordinates by dropping a non-numeric entry. @@ -411,6 +557,124 @@ mod tests { assert_eq!(tool.options()["rect"], json!([10.0, 20.0, 30.0, 40.0])); } + /// The Control bar's fields: X and Y place the reference point, W and H resize about it, and + /// the link keeps the proportions. + #[test] + fn fields_move_and_resize_the_box_about_its_reference_point() { + let r = Rect::new(10.0, 20.0, 110.0, 70.0); + let big = Rect::new(0.0, 0.0, 1000.0, 1000.0); + // The center (the default): today's behavior. + assert_eq!(edited_box(r, big, CENTER, false, "x", 100.0), Some(Rect::new(50.0, 20.0, 150.0, 70.0))); + assert_eq!(edited_box(r, big, CENTER, false, "width", 50.0), Some(Rect::new(35.0, 20.0, 85.0, 70.0))); + // The top-left corner: X and Y name it, and a new size keeps it where it is. + assert_eq!(edited_box(r, big, 0, false, "x", 0.0), Some(Rect::new(0.0, 20.0, 100.0, 70.0))); + assert_eq!(edited_box(r, big, 0, false, "y", 5.0), Some(Rect::new(10.0, 5.0, 110.0, 55.0))); + assert_eq!(edited_box(r, big, 0, false, "height", 10.0), Some(Rect::new(10.0, 20.0, 110.0, 30.0))); + // The bottom-right corner keeps its place too. + assert_eq!(edited_box(r, big, 8, false, "width", 40.0), Some(Rect::new(70.0, 20.0, 110.0, 70.0))); + // Linked: the other side follows in proportion (100 × 50 → 40 × 20, then 60 × 30). + assert_eq!(edited_box(r, big, 0, true, "width", 40.0), Some(Rect::new(10.0, 20.0, 50.0, 40.0))); + assert_eq!(edited_box(r, big, 8, true, "height", 30.0), Some(Rect::new(50.0, 40.0, 110.0, 70.0))); + // A size below a point is raised to one; other keys and values that aren't finite change nothing. + assert_eq!(edited_box(r, big, 0, false, "width", -5.0), Some(Rect::new(10.0, 20.0, 11.0, 70.0))); + assert_eq!(edited_box(r, big, 0, false, "angle", 5.0), None); + assert_eq!(edited_box(r, big, 0, false, "x", f64::NAN), None); + // Within a 120 × 80 image: a linked size is held to the image with both sides scaled + // (200 × 100 → 120 × 60), and the box slides back within it, keeping its 2:1 proportions. + let image = Rect::new(0.0, 0.0, 120.0, 80.0); + assert_eq!(edited_box(r, image, 0, true, "width", 200.0), Some(Rect::new(0.0, 20.0, 120.0, 80.0))); + assert_eq!(edited_box(r, image, 0, true, "height", 70.0), Some(Rect::new(0.0, 20.0, 120.0, 80.0))); + // A move past the edge slides the box back without changing its size. + assert_eq!(edited_box(r, image, 0, false, "x", 50.0), Some(Rect::new(20.0, 20.0, 120.0, 70.0))); + // Unlinked, a side larger than the image is left for the box's own limit to cut. + assert_eq!(edited_box(r, image, 0, false, "width", 200.0), Some(Rect::new(10.0, 20.0, 210.0, 70.0))); + } + + #[test] + fn reference_link_and_resolution_are_tool_options() { + let mut t = CropImageTool::default(); + assert_eq!(t.options(), json!({ "reference": 4, "linked": false })); + t.set_option("reference", &json!(0)); + t.set_option("linked", &json!(true)); + t.set_option("ppi", &json!(150)); + assert_eq!(t.options(), json!({ "reference": 0, "linked": true, "ppi": 150.0 })); + // Values that don't read put each back to its default. + for (k, v) in [("reference", json!(9)), ("linked", json!("yes")), ("ppi", json!(0)), ("ppi", json!(-72)), ("ppi", json!("high"))] { + t.set_option(k, &v); + } + assert_eq!(t.options(), json!({ "reference": 4, "linked": false })); + } + + #[test] + fn option_values_are_checked_before_they_are_set() { + let values = |v: Value| v.as_object().cloned().unwrap(); + assert_eq!(check_options(&values(json!({ "ppi": 150.5, "reference": 8, "linked": true, "rect": [0, 0, 1, 1] })), None), Ok(())); + assert_eq!(check_options(&values(json!({ "ppi": null })), Some(36.0)), Ok(())); + assert_eq!(check_options(&values(json!({ "ppi": 36 })), Some(36.0)), Ok(())); + for (v, want) in [ + (json!({ "ppi": 0.5 }), "`ppi` must be a number from 1 to 2400 or null, not 0.5"), + (json!({ "ppi": 2401 }), "`ppi` must be a number from 1 to 2400 or null, not 2401"), + (json!({ "ppi": "high" }), "`ppi` must be a number from 1 to 2400 or null, not \"high\""), + (json!({ "ppi": 72 }), "`ppi` can't be more than 36 for this image"), + (json!({ "reference": 9 }), "`reference` must be a whole number from 0 to 8, not 9"), + (json!({ "reference": 1.5 }), "`reference` must be a whole number from 0 to 8, not 1.5"), + (json!({ "linked": "yes" }), "`linked` must be true or false, not \"yes\""), + ] { + assert_eq!(check_options(&values(v.clone()), Some(36.0)), Err(want.to_string()), "{v}"); + } + } + + /// An image's own resolution, and the most it can be cropped to. + #[test] + fn image_resolution_and_its_limit() { + let (d, s) = doc_with_image((50.0, 60.0)); + let (id, _) = selected_image(&d, &s).unwrap(); + let Some(NodeKind::Image(im)) = d.node(id).map(|n| n.kind.clone()) else { panic!("an image") }; + // 100 px over 200 pt: half a pixel per point, 36 ppi. + assert_eq!(image_ppi(&im), (36.0, 36.0)); + // Turned, it is the same image: 36 ppi, not the density across its bounding box. + let turned = ImageObject { xf: Affine::rotate(0.5) * im.xf, ..(*im).clone() }; + assert!((image_ppi(&turned).0 - 36.0).abs() < 1e-9); + // Stretched to 3 pt a pixel across, its denser side counts. + let stretched = ImageObject { xf: Affine::scale_non_uniform(3.0, 2.0), ..(*im).clone() }; + assert_eq!(image_ppi(&stretched).0, 36.0); + // Its own resolution keeps its pixels; pixels that are not square are resampled at any resolution. + assert!(keeps_resolution(&im, 36.0, 1e-6) && !keeps_resolution(&im, 18.0, 1e-6)); + assert!(!keeps_resolution(&stretched, 36.0, 1e-6) && !keeps_resolution(&stretched, 24.0, 1e-6)); + let linked = ImageObject { link: Some("photo.png".into()), ..*im }; + assert_eq!(image_ppi(&linked), (36.0, LINKED_MAX_PPI)); + } + + /// Apply sends the chosen resolution with the box, even for a box over the whole image; the + /// image's own resolution sends nothing new, and one above the image's limit is held to it. + #[test] + fn apply_sends_the_chosen_resolution() { + let (d, s) = doc_with_image((50.0, 60.0)); + let p = paint(); + let cx = cx(&d, &s, &p); + let exec = |acts: &[Action]| { + acts.iter().find_map(|a| match a { + Action::Exec(c, v) if c == "object.cropImage" => Some(v.clone()), + _ => None, + }) + }; + let mut t = CropImageTool::default(); + t.set_option("ppi", &json!(20)); + assert_eq!(exec(&t.key(&cx, ToolKey::Enter, Mods::default())), Some(json!({ "rect": [50.0, 60.0, 200.0, 100.0], "ppi": 20.0 }))); + assert!(t.options().get("ppi").is_none(), "the next crop starts at the image's own"); + t.set_option("ppi", &json!(36)); + assert_eq!(exec(&t.key(&cx, ToolKey::Enter, Mods::default())), None, "the image's own over the whole image: nothing to do"); + t.set_option("ppi", &json!(36)); + t.set_option("rect", &json!([60, 70, 100, 50])); + assert_eq!(exec(&t.key(&cx, ToolKey::Enter, Mods::default())), Some(json!({ "rect": [60.0, 70.0, 100.0, 50.0] }))); + // A resolution set before this image was selected is held to its limit: 300 → its own 36. + t.set_option("ppi", &json!(300)); + t.set_option("rect", &json!([60, 70, 100, 50])); + assert_eq!(exec(&t.key(&cx, ToolKey::Enter, Mods::default())), Some(json!({ "rect": [60.0, 70.0, 100.0, 50.0] }))); + t.set_option("ppi", &json!(300)); + assert_eq!(exec(&t.key(&cx, ToolKey::Enter, Mods::default())), None, "held to its own over the whole image: nothing to do"); + } + #[test] fn the_tool_is_made_by_its_id() { assert_eq!(crate::create(ID).id(), ID); diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 7eae56c39f..5daa997a5e 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -8899,7 +8899,9 @@ breakText Glyphs Glyfy @msg position must be normal, superscript or subscript position musí být normal, superscript nebo subscript @msg position must be topLeft, topRight, bottomLeft or bottomRight position musí být topLeft, topRight, bottomLeft nebo bottomRight @msg positions must be between 0 and 100000 pt positions musí být mezi 0 a 100000 pt +@msg ppi can't be more than {max} for this image ppi nemůže být pro tento obrázek víc než {max} @msg ppi must be a positive number, not {ppi} ppi musí být kladné číslo, ne {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim ponechává pixely obrázku beze změny: vynechte ppi @msg ppi must be between 1 and 2400 ppi musí být mezi 1 a 2400 @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` není transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape musí být clippingMask|transparency diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 741cba9b6f..410a5f6e24 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -8483,7 +8483,9 @@ breakText Glyphs Glyphen @msg position must be normal, superscript or subscript position muss normal, superscript oder subscript sein @msg position must be topLeft, topRight, bottomLeft or bottomRight position muss topLeft, topRight, bottomLeft oder bottomRight sein @msg positions must be between 0 and 100000 pt positions müssen zwischen 0 und 100000 pt liegen +@msg ppi can't be more than {max} for this image ppi darf für dieses Bild nicht mehr als {max} sein @msg ppi must be a positive number, not {ppi} ppi muss eine positive Zahl sein, nicht {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim lässt die Pixel des Bildes unverändert: Lassen Sie ppi weg @msg ppi must be between 1 and 2400 ppi muss zwischen 1 und 2400 liegen @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` ist nicht transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape muss clippingMask|transparency sein diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 4a1e376475..9da0e3c7b3 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -8760,7 +8760,9 @@ breakText Glyphs Glyphes @msg position must be normal, superscript or subscript position doit valoir normal, superscript ou subscript @msg position must be topLeft, topRight, bottomLeft or bottomRight position doit valoir topLeft, topRight, bottomLeft ou bottomRight @msg positions must be between 0 and 100000 pt les positions doivent être comprises entre 0 et 100000 pt +@msg ppi can't be more than {max} for this image ppi ne peut pas dépasser {max} pour cette image @msg ppi must be a positive number, not {ppi} ppi doit être un nombre positif, pas {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim conserve les pixels de l’image tels quels : omettez ppi @msg ppi must be between 1 and 2400 ppi doit être compris entre 1 et 2400 @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` n’est pas transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape doit valoir clippingMask|transparency diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 658f534db9..7da4fe412b 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7744,7 +7744,9 @@ antiAlias Sharp शार्प @msg position must be normal, superscript or subscript position normal, superscript या subscript होना चाहिए @msg position must be topLeft, topRight, bottomLeft or bottomRight position को topLeft, topRight, bottomLeft या bottomRight होना चाहिए @msg positions must be between 0 and 100000 pt positions 0 और 100000 pt के बीच होनी चाहिए +@msg ppi can't be more than {max} for this image इस छवि के लिए ppi {max} से अधिक नहीं हो सकता @msg ppi must be a positive number, not {ppi} ppi एक धनात्मक संख्या होनी चाहिए, {ppi} नहीं +@msg trim keeps the image's pixels as they are: leave out ppi trim छवि के पिक्सेल जैसे हैं वैसे ही रखता है: ppi न दें @msg ppi must be between 1 and 2400 ppi 1 और 2400 के बीच होना चाहिए @msg precision must be from 0.001 to 10 pt precision 0.001 से 10 pt तक होनी चाहिए @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}`, transforms|bounds|fileDimensions|fit|fill में से नहीं है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index eb7a229c66..09ec92ad47 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -8769,7 +8769,9 @@ breakText Glyphs Glifák @msg position must be normal, superscript or subscript position: normal, superscript vagy subscript kell @msg position must be topLeft, topRight, bottomLeft or bottomRight position: topLeft, topRight, bottomLeft vagy bottomRight kell @msg positions must be between 0 and 100000 pt positions: 0 és 100000 pt közötti értékek kellenek +@msg ppi can't be more than {max} for this image ppi: ennél a képnél legfeljebb {max} lehet @msg ppi must be a positive number, not {ppi} ppi: pozitív szám kell, ez nem az: {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi a trim változatlanul hagyja a kép képpontjait: hagyja el a ppi értéket @msg ppi must be between 1 and 2400 ppi: 1 és 2400 közötti érték kell @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}`: nem transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape: clippingMask|transparency kell diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 19c2fd35a0..04da7049ba 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -8531,7 +8531,9 @@ breakText Glyphs Glifi @msg position must be normal, superscript or subscript position deve essere normal, superscript o subscript @msg position must be topLeft, topRight, bottomLeft or bottomRight position deve essere topLeft, topRight, bottomLeft o bottomRight @msg positions must be between 0 and 100000 pt le posizioni devono essere comprese tra 0 e 100000 pt +@msg ppi can't be more than {max} for this image ppi non può superare {max} per questa immagine @msg ppi must be a positive number, not {ppi} ppi deve essere un numero positivo, non {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim mantiene i pixel dell'immagine così come sono: ometti ppi @msg ppi must be between 1 and 2400 ppi deve essere compreso tra 1 e 2400 @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` non è transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape deve essere clippingMask|transparency diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 6a24933f11..9d0047041b 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7732,7 +7732,9 @@ axis Y Axis Y 軸 @msg position must be normal, superscript or subscript position には normal、superscript、subscript のいずれかを指定してください @msg position must be topLeft, topRight, bottomLeft or bottomRight position には topLeft、topRight、bottomLeft、bottomRight のいずれかを指定してください @msg positions must be between 0 and 100000 pt positions には 0 から 100000 pt までの値を指定してください +@msg ppi can't be more than {max} for this image この画像の ppi には {max} 以下の値を指定してください @msg ppi must be a positive number, not {ppi} ppi には正の数値を指定してください ({ppi} は指定できません) +@msg trim keeps the image's pixels as they are: leave out ppi trim は画像のピクセルをそのまま残します: ppi は指定しないでください @msg ppi must be between 1 and 2400 ppi には 1 から 2400 までの値を指定してください @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` は transforms|bounds|fileDimensions|fit|fill のいずれでもありません @msg preserveShape must be clippingMask|transparency preserveShape には clippingMask|transparency のいずれかを指定してください diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 77a0172143..917c66ad3e 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -8495,7 +8495,9 @@ breakText Glyphs 글리프 @msg position must be normal, superscript or subscript position은 normal, superscript 또는 subscript여야 합니다 @msg position must be topLeft, topRight, bottomLeft or bottomRight position은 topLeft, topRight, bottomLeft 또는 bottomRight여야 합니다 @msg positions must be between 0 and 100000 pt positions는 0에서 100000 pt 사이여야 합니다 +@msg ppi can't be more than {max} for this image 이 이미지의 ppi는 {max}보다 클 수 없습니다 @msg ppi must be a positive number, not {ppi} ppi는 양수여야 합니다: {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim은 이미지의 픽셀을 그대로 유지합니다: ppi를 지정하지 마세요 @msg ppi must be between 1 and 2400 ppi는 1에서 2400 사이여야 합니다 @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}`은(는) transforms|bounds|fileDimensions|fit|fill이 아닙니다 @msg preserveShape must be clippingMask|transparency preserveShape는 clippingMask|transparency여야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index a6ca78f597..b410962eb7 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6834,7 +6834,9 @@ imageTrace Outline Contour @msg position must be normal, superscript or subscript position moet normal, superscript of subscript zijn @msg position must be topLeft, topRight, bottomLeft or bottomRight position moet topLeft, topRight, bottomLeft of bottomRight zijn @msg positions must be between 0 and 100000 pt positions moeten tussen 0 en 100000 pt liggen +@msg ppi can't be more than {max} for this image ppi kan voor deze afbeelding niet hoger zijn dan {max} @msg ppi must be a positive number, not {ppi} ppi moet een positief getal zijn, niet {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim laat de pixels van de afbeelding zoals ze zijn: laat ppi weg @msg ppi must be between 1 and 2400 ppi moet tussen 1 en 2400 liggen @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` is niet transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape moet clippingMask|transparency zijn diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index ba909ca1a3..a5951e8c37 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -8769,7 +8769,9 @@ breakText Glyphs Glify @msg position must be normal, superscript or subscript position musi mieć wartość normal, superscript lub subscript @msg position must be topLeft, topRight, bottomLeft or bottomRight position musi mieć wartość topLeft, topRight, bottomLeft lub bottomRight @msg positions must be between 0 and 100000 pt positions musi mieścić się w zakresie od 0 do 100000 pt +@msg ppi can't be more than {max} for this image ppi nie może przekraczać {max} dla tego obrazu @msg ppi must be a positive number, not {ppi} ppi musi być liczbą dodatnią, a nie {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim zachowuje piksele obrazu bez zmian: pomiń ppi @msg ppi must be between 1 and 2400 ppi musi mieścić się w zakresie od 1 do 2400 @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` nie jest jedną z wartości transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape musi mieć wartość clippingMask|transparency diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index d891622c53..3a752fba4a 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -8962,7 +8962,9 @@ swatch Yellow Green Verde-amarelado @msg position must be normal, superscript or subscript position deve ser normal, superscript ou subscript @msg position must be topLeft, topRight, bottomLeft or bottomRight position deve ser topLeft, topRight, bottomLeft ou bottomRight @msg positions must be between 0 and 100000 pt positions deve estar entre 0 e 100000 pt +@msg ppi can't be more than {max} for this image ppi não pode ser maior que {max} para esta imagem @msg ppi must be a positive number, not {ppi} ppi deve ser um número positivo, não {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim mantém os pixels da imagem como estão: omita ppi @msg ppi must be between 1 and 2400 ppi deve estar entre 1 e 2400 @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` não é transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape deve ser clippingMask|transparency diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 6f72fd5a38..fdce0cc732 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -8465,7 +8465,9 @@ digits Hindi Hindi @msg position must be normal, superscript or subscript position måste vara normal, superscript eller subscript @msg position must be topLeft, topRight, bottomLeft or bottomRight position måste vara topLeft, topRight, bottomLeft eller bottomRight @msg positions must be between 0 and 100000 pt positionerna måste vara mellan 0 och 100 000 pt +@msg ppi can't be more than {max} for this image ppi kan inte vara mer än {max} för den här bilden @msg ppi must be a positive number, not {ppi} ppi måste vara ett positivt tal, inte {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim behåller bildens pixlar som de är: utelämna ppi @msg ppi must be between 1 and 2400 ppi måste vara mellan 1 och 2400 @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` är inte transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape måste vara clippingMask|transparency diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 62e389747f..0cbd41f929 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -8115,7 +8115,9 @@ axis Y Axis Y ekseni @msg position must be normal, superscript or subscript position normal, superscript veya subscript olmalıdır @msg position must be topLeft, topRight, bottomLeft or bottomRight position topLeft, topRight, bottomLeft veya bottomRight olmalıdır @msg positions must be between 0 and 100000 pt konumlar 0 ile 100000 pt arasında olmalıdır +@msg ppi can't be more than {max} for this image bu görüntü için ppi {max} değerinden büyük olamaz @msg ppi must be a positive number, not {ppi} ppi pozitif bir sayı olmalıdır, {ppi} değil +@msg trim keeps the image's pixels as they are: leave out ppi trim görüntünün piksellerini olduğu gibi korur: ppi belirtmeyin @msg ppi must be between 1 and 2400 ppi 1 ile 2400 arasında olmalıdır @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}`, transforms|bounds|fileDimensions|fit|fill değerlerinden biri değil @msg preserveShape must be clippingMask|transparency preserveShape clippingMask|transparency olmalıdır diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 7991931baf..6d0012567e 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -8496,7 +8496,9 @@ breakText Glyphs Гліфи @msg position must be normal, superscript or subscript position має бути normal, superscript або subscript @msg position must be topLeft, topRight, bottomLeft or bottomRight position має бути topLeft, topRight, bottomLeft або bottomRight @msg positions must be between 0 and 100000 pt positions мають бути від 0 до 100000 pt +@msg ppi can't be more than {max} for this image ppi для цього зображення не може перевищувати {max} @msg ppi must be a positive number, not {ppi} ppi має бути додатним числом, а не {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim залишає пікселі зображення без змін: не вказуйте ppi @msg ppi must be between 1 and 2400 ppi має бути від 1 до 2400 @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` не є transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape має бути clippingMask|transparency diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 85f3986759..d004cceb16 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -8755,7 +8755,9 @@ breakText Glyphs 字形 @msg position must be normal, superscript or subscript position 必须是 normal、superscript 或 subscript @msg position must be topLeft, topRight, bottomLeft or bottomRight position 必须是 topLeft、topRight、bottomLeft 或 bottomRight @msg positions must be between 0 and 100000 pt positions 必须介于 0 到 100000 pt 之间 +@msg ppi can't be more than {max} for this image 此图像的 ppi 不能超过 {max} @msg ppi must be a positive number, not {ppi} ppi 必须是正数,不能是 {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim 会保持图像像素不变:请省略 ppi @msg ppi must be between 1 and 2400 ppi 必须介于 1 到 2400 之间 @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` 不是 transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape 必须是 clippingMask|transparency diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 3bf87d3eb2..f0747e0b80 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -8683,7 +8683,9 @@ breakText Glyphs 字符 @msg position must be normal, superscript or subscript position 必須是 normal、superscript 或 subscript @msg position must be topLeft, topRight, bottomLeft or bottomRight position 必須是 topLeft、topRight、bottomLeft 或 bottomRight @msg positions must be between 0 and 100000 pt positions 必須介於 0 到 100000 pt 之間 +@msg ppi can't be more than {max} for this image 此影像的 ppi 不能超過 {max} @msg ppi must be a positive number, not {ppi} ppi 必須是正數,而非 {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim 會保持影像像素不變:請勿指定 ppi @msg ppi must be between 1 and 2400 ppi 必須介於 1 和 2400 之間 @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` 不是 transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape 必須是 clippingMask|transparency diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 29d89ebf6d..77d1b537f9 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -533,29 +533,66 @@ pub fn control_bar_options(app: &mut VectorcraftApp, ui: &mut Ui) { crate::chrome::group_separator(ui); } -/// Crop Image's box: its centre (X, Y) and size (W, H) in the general unit, set through the tool's -/// `rect` option, then Apply (Enter) and Cancel (Escape). +/// Crop Image's cropping options: the cropped image's resolution (PPI: a list, with the +/// resolutions above what the image allows disabled, or a typed value), the reference point, the +/// box's X and Y (that point) and size (W, H) in the general unit with the link that keeps their +/// proportions, all set through the tool's options; then Apply (Enter) and Cancel (Escape). fn crop_options(app: &mut VectorcraftApp, ui: &mut Ui) { - let set = app.session.tool_options()["rect"].as_array().and_then(|v| match v.iter().filter_map(Value::as_f64).collect::>()[..] { + use vectorcraft_tools::cropimage::{self as crop, PPI_CHOICES}; + let opts = app.session.tool_options(); + let set = opts["rect"].as_array().and_then(|v| match v.iter().filter_map(Value::as_f64).collect::>()[..] { [x, y, w, h] => Some(vectorcraft_geom::Rect::new(x, y, x + w, y + h)), _ => None, }); - let Some((_, _, r)) = app.session.active().and_then(|st| vectorcraft_tools::cropimage::crop_box(&st.doc, &st.selection, set)) else { return }; + let Some((r, image, own, max)) = app.session.active().and_then(|st| { + let (id, image, r) = crop::crop_box(&st.doc, &st.selection, set)?; + let vectorcraft_doc::NodeKind::Image(im) = &st.doc.node(id)?.kind else { return None }; + let (own, max) = crop::image_ppi(im); + Some((r, image, own, max.min(2400.0))) + }) else { + return; + }; + let reference = opts["reference"].as_u64().filter(|v| *v <= 8).map_or(crop::CENTER, |v| v as usize); + let linked = opts["linked"].as_bool().unwrap_or(false); let t = Tokens::get(ui.ctx()); + let set_option = |app: &mut VectorcraftApp, key: &str, value: Value| { + app.run("tool.setOption", json!({ "key": key, "value": value })).ok(); + }; + // Resolution: the list's choices above the image's limit are disabled; a typed value is held to it. + let ppi = opts["ppi"].as_f64().unwrap_or(own); + let label = |v: f64| crate::i18n::fill_once(tl!("{n} ppi"), &[("n", &format!("{}", (v * 100.0).round() / 100.0))]); + let labels: Vec = PPI_CHOICES.iter().map(|v| label(*v)).collect(); + let names: Vec<&str> = labels.iter().map(String::as_str).collect(); + widgets::field_label(ui, egui::RichText::new(tl!("PPI")).size(12.0).color(t.text_dim)); + let current = label(ppi); + if let Some(v) = + widgets::dropdown_with(ui, ("cb-crop", "ppi-list"), ¤t, &names, 80.0, |i| PPI_CHOICES.get(i).is_some_and(|v| *v <= max + 1e-6)) + .and_then(|i| PPI_CHOICES.get(i)) + { + set_option(app, "ppi", json!(v)); + } + // An image's own resolution above the limit (a linked image's, or one past 2400 ppi) still shows + // as it is; an edit there sets at most the limit. + if let Some(v) = widgets::range_field(ui, ("cb-crop", "ppi"), ppi, 1.0..=max.max(ppi).max(1.0), "", 2, 56.0) { + set_option(app, "ppi", json!(v.min(max.max(1.0)))); + } + ui.separator(); + if let Some(i) = widgets::reference_point(ui, reference) { + set_option(app, "reference", json!(i)); + } let units = app.session.general_unit(); - let c = r.center(); - for (k, lbl, v) in [("x", "X:", c.x), ("y", "Y:", c.y), ("width", "W:", r.width()), ("height", "H:", r.height())] { + let p = vectorcraft_geom::reference_point(r, reference); + for (k, lbl, v) in [("x", "X:", p.x), ("y", "Y:", p.y), ("width", "W:", r.width()), ("height", "H:", r.height())] { + if k == "height" + && widgets::icon_button(ui, if linked { "link" } else { "unlink" }, tl!("Constrain Width and Height Proportions"), linked, 22.0).clicked() + { + set_option(app, "linked", json!(!linked)); + } widgets::field_label(ui, egui::RichText::new(tl!(lbl)).size(12.0).color(t.text_dim)); - if let Some(nv) = widgets::num_field(ui, ("cb-crop", k), Some(v), units, 80.0) { - let (mut c, mut w, mut h) = (c, r.width(), r.height()); - match k { - "x" => c.x = nv, - "y" => c.y = nv, - "width" => w = nv.max(0.0), - _ => h = nv.max(0.0), - } - let rect = [c.x - w / 2.0, c.y - h / 2.0, w, h]; - app.run("tool.setOption", json!({ "key": "rect", "value": rect })).ok(); + if let Some(nv) = widgets::num_field(ui, ("cb-crop", k), Some(v), units, 80.0) + && let Some(b) = crop::edited_box(r, image, reference, linked, k, nv) + { + set_option(app, "rect", json!([b.x0, b.y0, b.width(), b.height()])); } } ui.separator(); diff --git a/docs/mcp.md b/docs/mcp.md index 6484c32fea..7330def4ea 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1882,6 +1882,21 @@ and `rotate` in `object.transformEach`; `ppi` in `object.rasterize`; `width`, `h four numbers, such as a string, with `rect must be [x, y, width, height]`; a null `rect` crops to the artboard, as a missing one does. +`object.cropImage {ppi}` sets the cropped image's resolution in pixels per inch: the cut pixels are resampled to it, +and the image keeps the size of the crop box. A `rect` over the whole image with a new `ppi` only resamples the image. +An image scaled differently across and down is resampled on both sides, so its pixels come out square at `ppi`. +The most it takes is the image's own resolution (along the denser side of its pixel grid, however it is turned), or +300 ppi for a linked image; above that it is refused with `ppi can't be more than {max} for this image`. A value +outside 1 to 2400 is refused with `ppi must be between 1 and 2400`, and a value that is not a positive number with +`ppi must be a positive number, not {ppi}`. A null `ppi` keeps the image's own, as a missing one does, and `ppi` with +`trim` is refused. While the Crop Image tool is chosen, `tool.setOption` sets `ppi` (the resolution Apply sends), +`reference` (0 to 8, left to right and top to bottom: the point of the box that the Control bar's X and Y name and +that its W and H resize about; 4, the center, by default) and `linked` (W and H keep the box's proportions; false by +default). It refuses another value of those three, such as a `ppi` of `"high"`, a `ppi` above what the selected +image allows or a `reference` of 9, and changes nothing; a null `ppi` goes back to the image's own. `tool.options` reads them back with `rect`. +Apply holds a `ppi` set before the image was selected to that image's limit. With `linked` on, a new W or H that would +not fit the image is reduced with the other side in proportion, and the box slides back within the image. + `object.createObjectMosaic` (`columns`, `rows`), `object.transformEach` (`reference`, `seed`) and `artboard.rearrange` (`columns`) take whole numbers, written `4` or `4.0`. A fraction or a negative number is refused with `` `columns` must be a whole number ``. A string or another value that is not a number is refused with diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4c27883d11..2ce2603750 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1523,6 +1523,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Image Trace, Flat Logo with a color between two others:** an anti-aliased edge pixel between black and white is read as a blend of black and white, not of black and a gray that lies between them, when the flat areas around it and the pixels beside it show that edge, so a black disc beside a gray square on white, with sharp edges or edges blurred by up to about half a pixel, traces with one gray path, the square, instead of the square plus 8 to 24 gray slivers around the disc with the colors found or named exactly (an edge blurred by a pixel or more, or pixel noise of a level or more, can still leave gray slivers); gray strokes two and three pixels wide beside black stay gray (a soft-edged gray stroke about two pixels wide that touches black traces as black and white, and a short one about three pixels wide can lose most or all of its gray), and a one-pixel gray line of at least 13 touching pixels between black and white stays gray (a shorter one, or one that falls between pixels or is blurred, traces as black and white); code-drawn tests in `crates/trace`. - **Image Trace, Keep Colors:** `"keepColors": ["#rrggbb", …]` traces only the palette colors near a listed color (Abutting: each with the paths the trace of every color gives it; Overlapping: not reaching under the colors left out), in Black and White, Grayscale and Color; code-drawn tests in `crates/trace` and `crates/engine`. - **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own, and regions they bound merge without seams where the lines cross at rounded coordinates (#893); filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets, colour layers traced in parallel; a trace past two million anchor points is refused with advice rather than running out of memory, an image over 64 megapixels is traced scaled down to that size (aspect kept, paths at the image's own size) and one over 192 megapixels is refused, and a selection too large to outline shows its bounds (#525); Object › Image Trace › Make and Make and Expand trace at once with the Default preset, #543; with an image selected the Control bar and the Properties panel show Image Trace, whose arrow traces with any preset, Mask (`object.maskImage`: a clipping path on the image's outline, selected so its handles crop), Crop Image (a crop box on the image, starting on its part over the artboard, dragged by its handles or inside it, the outside dimmed, with X/Y/W/H, Apply and Cancel in the Control bar, Enter and Escape, #734; an image that isn't turned or skewed, isn't CMYK and can be read at its recorded size is cut from its own pixels when the crop edges fall on its pixel grid, copied as they are without resampling; any other image is drawn, #5534; `object.cropImage {rect}` for agents, `{trim: true}` cuts an image to its pixels that aren't fully transparent, pixel for pixel) and Embed or Unembed in place of Fill and Stroke; with an Image Trace object selected, its Preset (choosing another traces again), View, the Image Trace panel and Expand, plus Release in Properties; the five View modes (Tracing Result, with Outlines, Outlines, Outlines with Source Image, Source Image) redraw a trace on screen without tracing again, are saved with it and `imageTrace.setView` sets them, while exports and Expand keep the result; the panel's Advanced section is a header that stays open or closed as it was left (part of #641); Color mode's Palette: Limited, Full Tone (as many colours as the tones need, Less … More), Automatic (flat art with its own colours, else Full Tone; a heuristic) and Document Library (the most used colours of the document's swatches or a swatch library, filled with the swatch colours as they are), part of #641; Advanced › Create: Fills and/or Strokes, where lines up to the Stroke width trace as stroked centre lines (distance transform, thinning, a skeleton graph with spurs pruned, curve fitting; one width per line; without Fills, wider areas become stroked outlines), part of #641), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror). A single selected mirror repeat shows a prominent axis with a center move handle and two rotation handles. Drag the line or center to change spacing, or an end to change angle; Shift snaps rotation to 45°. The original artwork stays in place, the reflected copy previews live, Escape cancels and each drag takes one undo step through `object.repeat.options`. Controls follow zoom/view rotation and hide with edges or the bounding box. Engine and headless canvas regressions passed for gestures, history and visibility; native move, rotation and Escape screenshots were reviewed. [Public mirror-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-mirror-repeat-options.html). A single selected grid repeat shows a handle below the grid for rows, one right of it for columns and one past its bottom-right corner for both, and sliders between its first two columns and rows for the horizontal and vertical spacing; the source keeps its size, each drag is one undo step and Escape cancels it ([public grid-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html), #2691). Object › Expand turns radial, grid and mirror repeats into groups of their instances (#1765, #1756). + While Crop Image shows its box, the Control bar also sets the cropped image's resolution (PPI: a list of 72, 96, 150, 200 and 300 ppi with the ones above the image's own disabled, or a typed value; at most the image's own, or 300 ppi for a linked image ([Crop Image](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=352))), a reference point that X and Y name and that W and H resize about, and a link that keeps W and H in proportion; `object.cropImage {ppi}` resamples the cut pixels and refuses a resolution above the limit, and `tool.setOption` sets `ppi`, `reference` and `linked` ([Crop images](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/crop-images-in-illustrator.html)). The list's resolutions and the default (the image's own resolution, the center, unlinked) are VectorCraft's own. Choosing the Blend tool again while it is active (its toolbar button, W or `tool.select`) finishes the blend: the object clicked first is dropped and the next click no longer adds to the blend just made, so the click after it starts a new blend ([Blending objects](https://web.archive.org/web/20241217212108/https://helpx.adobe.com/illustrator/using/blending-objects.html)). Window › Blend exposes easing Type, Ramp and independent color Shift through `object.blend.options`. Smooth Color counts the steps of each pair of keys from their color change, or from the distance between their visible bounding-box edges when their colors match or they hold gradients or patterns ([Blend Options](https://web.archive.org/web/20241217212108/https://helpx.adobe.com/illustrator/using/blending-objects.html)); the step counts, their caps and the colors compared are VectorCraft's own.