Skip to content

LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust

Engine: crop.drag command; validate custom crop ratios (#295)

Nathaniel Ledford8d8178dc0aca
diff --git a/crates/engine/src/cmd/develop.rs b/crates/engine/src/cmd/develop.rs
index 8f197429c..e0aaaf957 100644
--- a/crates/engine/src/cmd/develop.rs
+++ b/crates/engine/src/cmd/develop.rs
@@ -2,7 +2,7 @@
use lightcraft_catalog::{Op, PhotoId, Version};
use lightcraft_develop::{DevelopSettings, Preset, Section, SettingsGroup, Treatment, Upright, WbMode, controls};
-use lightcraft_geom::{CropGeometry, Point, Rect, crop_fit_angle};
+use lightcraft_geom::{CropGeometry, CropHandle, Point, Rect, crop_fit_angle, drag_crop};
use serde_json::{Value, json};
use super::{CommandSpec, always, bad, bool_or, cmd, f64_or, f64_req, has_active, has_clipboard, has_selection, ok, str_param};
@@ -37,6 +37,32 @@ fn crop_dims(s: &Session, id: PhotoId) -> (f64, f64) {
if o.swaps_axes() { (h, w) } else { (w, h) }
}
+/// `v` as a list of numbers; `None` unless it is an array of nothing but numbers.
+fn numbers(v: Option<&Value>) -> Option<Vec<f64>> {
+ v?.as_array()?.iter().map(Value::as_f64).collect()
+}
+
+/// A width × height lock stored as hundredths. Rejects non-finite, non-positive and
+/// extreme (beyond 20:1) shapes, which would give an empty or unusable crop.
+fn aspect_tuple(c: &str, x: f64, y: f64) -> Result<(u32, u32)> {
+ let ratio = x / y;
+ if !(x.is_finite()
+ && y.is_finite()
+ && x > 0.0
+ && y > 0.0
+ && ratio.is_finite()
+ && (1.0 / lightcraft_geom::MAX_RATIO..=lightcraft_geom::MAX_RATIO).contains(&ratio))
+ {
+ return Err(bad(c, "aspect needs two positive numbers with a ratio between 1:20 and 20:1"));
+ }
+ let to = |v: f64| (v * 100.0).round();
+ let (a, b) = (to(x), to(y));
+ if a < 1.0 || b < 1.0 || a > f64::from(u32::MAX) || b > f64::from(u32::MAX) {
+ return Err(bad(c, "aspect numbers are out of range"));
+ }
+ Ok((a as u32, b as u32))
+}
+
fn set_aspect(d: &mut DevelopSettings, w: f64, h: f64, aspect: Option<(u32, u32)>) {
d.crop.aspect = aspect;
let a = aspect.map(|(aw, ah)| {
@@ -395,6 +421,46 @@ pub fn specs() -> Vec<CommandSpec> {
Ok(())
})
}),
+ cmd!(
+ "crop.drag",
+ "Drag Crop Handle",
+ [],
+ None,
+ "{handle: topLeft|topRight|bottomRight|bottomLeft|top|right|bottom|left|move | 0..8, from: [x,y], to: [x,y] (normalized, straightened frame), start?: [x0,y0,x1,y1] (default: the current crop)} — drags a crop handle; stops at the image edge, keeps the opposite edges, honours the aspect lock",
+ has_active,
+ |s, p| {
+ let id = active(s, "crop.drag")?;
+ let (w, h) = crop_dims(s, id);
+ let handle = match p.get("handle") {
+ Some(Value::String(n)) => CropHandle::from_name(n),
+ Some(v) => v.as_u64().and_then(|i| u8::try_from(i).ok()).and_then(CropHandle::from_index),
+ None => None,
+ }
+ .ok_or_else(|| bad("crop.drag", "unknown handle"))?;
+ let point = |k: &str| -> Result<Point> {
+ match numbers(p.get(k)).as_deref() {
+ Some([x, y]) if x.is_finite() && y.is_finite() => Ok(Point::new(*x, *y)),
+ _ => Err(bad("crop.drag", format!("`{k}` needs [x, y]"))),
+ }
+ };
+ let (from, to) = (point("from")?, point("to")?);
+ let given = match (p.get("start"), numbers(p.get("start")).as_deref()) {
+ (None | Some(Value::Null), _) => None,
+ (_, Some(&[x0, y0, x1, y1])) if [x0, y0, x1, y1].iter().all(|v| v.is_finite()) => {
+ Some(Rect::new(x0.min(x1), y0.min(y1), x0.max(x1), y0.max(y1)))
+ }
+ _ => return Err(bad("crop.drag", "`start` needs 4 numbers")),
+ };
+ edit(s, "crop.drag", "Crop", |d| {
+ let start = CropGeometry { rect: given.unwrap_or(d.crop.geometry.rect), angle: d.crop.geometry.angle };
+ // A locked crop keeps the shape it has: the lock stores a width:height tuple whose
+ // orientation is reinterpreted per image, so the frame itself is the truth.
+ let ratio = d.crop.aspect.and(Some(start.rect_px(w, h).aspect())).filter(|a| a.is_finite() && *a > 0.0);
+ d.crop.geometry = drag_crop(start, handle, from, to, w, h, ratio);
+ Ok(())
+ })
+ }
+ ),
cmd!(
"crop.straighten",
"Straighten",
@@ -470,11 +536,12 @@ pub fn specs() -> Vec<CommandSpec> {
let (x, y) = a.split_once('x').ok_or_else(|| bad("crop.aspect", "use WxH"))?;
let (x, y): (f64, f64) =
(x.parse().map_err(|_| bad("crop.aspect", "bad number"))?, y.parse().map_err(|_| bad("crop.aspect", "bad number"))?);
- Some(((x * 100.0) as u32, (y * 100.0) as u32))
- }
- Some(Value::Array(a)) if a.len() == 2 => {
- Some(((a[0].as_f64().unwrap_or(1.0) * 100.0) as u32, (a[1].as_f64().unwrap_or(1.0) * 100.0) as u32))
+ Some(aspect_tuple("crop.aspect", x, y)?)
}
+ Some(v @ Value::Array(_)) => match numbers(Some(v)).as_deref() {
+ Some(&[x, y]) => Some(aspect_tuple("crop.aspect", x, y)?),
+ _ => return Err(bad("crop.aspect", "use [w, h] with two numbers")),
+ },
_ => return Err(bad("crop.aspect", "missing aspect")),
};
edit(s, "crop.aspect", "Crop Aspect", |d| {
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index d005d5082..afcf29b49 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -382,6 +382,61 @@ fn crop_aspect_lock_current_and_toggle() {
assert!(active_dev(&s).crop.aspect.is_none(), "toggle unlocks");
}
+// Feature: dragging crop handles (issue 295)
+#[test]
+fn crop_drag_stops_at_the_image_edge_and_keeps_the_anchor() {
+ let mut s = demo();
+ s.execute("crop.set", &json!({"rect": [0.2, 0.2, 0.8, 0.8]})).unwrap();
+ s.execute("crop.drag", &json!({"handle": "bottomRight", "from": [0.8, 0.8], "to": [1.4, 0.7]})).unwrap();
+ let r = active_dev(&s).crop.geometry.rect;
+ assert!((r.x0 - 0.2).abs() < 1e-6 && (r.y0 - 0.2).abs() < 1e-6, "anchor moved: {r:?}");
+ assert!((r.x1 - 1.0).abs() < 1e-6 && (r.y1 - 0.7).abs() < 1e-6, "{r:?}");
+}
+
+#[test]
+fn crop_drag_keeps_a_locked_ratio_on_every_handle() {
+ let mut s = demo();
+ s.execute("crop.aspect", &json!({"aspect": "16x9"})).unwrap();
+ let d = active_dev(&s);
+ assert!(d.crop.aspect.is_some());
+ let want = d.crop.geometry.rect.aspect();
+ let r = d.crop.geometry.rect;
+ for (handle, to) in [("left", [r.x0 + 0.1, 0.5]), ("top", [0.5, r.y0 + 0.05]), ("bottomRight", [1.3, 1.3]), ("right", [0.9, 0.5])] {
+ s.execute("crop.drag", &json!({"handle": handle, "from": [0.5, 0.5], "to": to, "start": [r.x0, r.y0, r.x1, r.y1]})).unwrap();
+ let g = active_dev(&s).crop.geometry.rect;
+ assert!((g.aspect() - want).abs() < 1e-6, "{handle}: {} vs {want}", g.aspect());
+ }
+}
+
+#[test]
+fn crop_drag_rejects_unknown_handles_and_bad_points() {
+ let mut s = demo();
+ assert!(s.execute("crop.drag", &json!({"handle": "sideways", "from": [0.5, 0.5], "to": [0.6, 0.6]})).is_err());
+ assert!(s.execute("crop.drag", &json!({"handle": "move", "from": [0.5], "to": [0.6, 0.6]})).is_err());
+ assert!(s.execute("crop.drag", &json!({"handle": "move", "to": [0.6, 0.6]})).is_err());
+}
+
+#[test]
+fn crop_aspect_rejects_degenerate_custom_ratios() {
+ let mut s = demo();
+ let before = active_dev(&s).crop;
+ for bad in [json!([0.004, 3]), json!([3, 0]), json!([-1, 2]), json!([1000, 0.01]), json!(["a", 2]), json!([1, 2, 3])] {
+ assert!(s.execute("crop.aspect", &json!({"aspect": bad.clone()})).is_err(), "{bad}");
+ }
+ assert!(s.execute("crop.aspect", &json!({"aspect": "0x5"})).is_err());
+ let after = active_dev(&s).crop;
+ assert_eq!(before.geometry, after.geometry, "a rejected ratio leaves the crop alone");
+ s.execute("crop.aspect", &json!({"aspect": [2.5, 1]})).unwrap();
+ assert!(!active_dev(&s).crop.geometry.rect.is_empty());
+}
+
+#[test]
+fn crop_drag_rejects_non_numeric_points() {
+ let mut s = demo();
+ assert!(s.execute("crop.drag", &json!({"handle": "move", "from": ["a", 0.5, 0.5], "to": [0.6, 0.6]})).is_err());
+ assert!(s.execute("crop.drag", &json!({"handle": "move", "from": [0.5, 0.5], "to": [0.6, 0.6], "start": [0.1, "x", 0.5, 0.5]})).is_err());
+}
+
#[test]
fn paste_from_previous_and_copy_paste_metadata() {
let mut s = demo();