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:
dotCooCoo
2026-11-15 07:26:01 -08:00
parent 2607a98c1f
commit 34e52df5de
23 changed files with 661 additions and 53 deletions
+279 -15
View File
@@ -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<String, Value>, max: Option<f64>) -> 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<Rect> {
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<Box<dyn Tool>> {
(id == ID).then(|| Box::new(CropImageTool::default()) as Box<dyn Tool>)
@@ -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<Drag>,
/// 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<f64>,
/// 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<Action> {
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);