LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust
LR-CROP-ASPECT: defer remembered ratio until a crop gesture starts
Daniel Sprucefd5d05e25661
diff --git a/crates/ui-egui/src/headless.rs b/crates/ui-egui/src/headless.rsindex ca422c352..5c5efce35 100644--- a/crates/ui-egui/src/headless.rs+++ b/crates/ui-egui/src/headless.rs@@ -1573,31 +1573,46 @@ mod tests {}#[test]- fn crop_remembers_last_aspect_across_photos() {+ fn crop_default_browsing_is_read_only_and_drag_is_one_edit() {let mut h = demo([1200.0, 800.0]);- let photos = h.app.session.visible_cloned();+ let photos: Vec<_> = h.app.session.visible_cloned().into_iter().filter(|id| !h.app.session.catalog.photo(*id).unwrap().is_edited()).collect();+ h.app.run("library.select", json!({"ids": [photos[0].0]})).unwrap();h.app.ui.right = crate::state::RightPanel::Crop;- h.app.run("crop.aspect", json!({"aspect": "original"})).unwrap();+ h.app.run("crop.aspect", json!({"aspect": "1x1"})).unwrap();let saved = serde_json::to_value(&h.app.ui).unwrap();- assert_eq!(saved["cropDefaultAspect"], "original");for &photo in &photos[1..3] {h.app.run("library.select", json!({"ids": [photo.0]})).unwrap();- h.app.apply_crop_default();- let p = h.app.session.catalog.photo(photo).unwrap();- assert_eq!(p.develop.crop.aspect, Some((p.width * 100, p.height * 100)));- }- h.app.run("crop.aspect", json!({"aspect": "1x1"})).unwrap();- let existing = h.app.session.develop_of(photos[2]).unwrap().crop;- h.app.run("library.select", json!({"ids": [photos[3].0]})).unwrap();- h.app.apply_crop_default();- assert_eq!(h.app.session.develop_of(photos[3]).unwrap().crop.aspect, Some((100, 100)));- h.app.run("crop.aspect", json!({"aspect": "free"})).unwrap();- h.app.run("library.select", json!({"ids": [photos[2].0]})).unwrap();- h.app.apply_crop_default();- assert_eq!(h.app.session.develop_of(photos[2]).unwrap().crop, existing);+ let before = h.app.session.catalog.photo(photo).unwrap().clone();+ let undo = h.app.session.undo.len();+ h.settle(SETTLE);+ let after = h.app.session.catalog.photo(photo).unwrap();+ assert_eq!(after.develop, before.develop);+ assert_eq!(after.history.len(), before.history.len());+ assert!(!after.is_edited());+ assert_eq!(h.app.session.undo.len(), undo);+ assert_eq!(h.app.crop_tool_aspect(), Some((100, 100)));+ }+ let photo = photos[2];+ let before = h.app.session.develop_of(photo).unwrap();+ let undo = h.app.session.undo.len();+ h.app.run("develop.beginInteraction", json!({"label": "Crop"})).unwrap();+ h.app.begin_crop().unwrap();+ h.app.run("crop.drag", json!({"handle": "bottomRight", "from": [0.8, 0.8], "to": [0.7, 0.7]})).unwrap();+ h.app.run("develop.endInteraction", json!({})).unwrap();+ assert_eq!(h.app.session.develop_of(photo).unwrap().crop.aspect, Some((100, 100)));+ assert_eq!(h.app.session.undo.len(), undo + 1);+ h.app.run("edit.undo", json!({})).unwrap();+ assert_eq!(h.app.session.develop_of(photo).unwrap(), before);h.app.ui = serde_json::from_value(saved).unwrap();- assert_eq!(h.app.ui.crop_default_aspect, Some(json!("original")));- h.settle(SETTLE);+ assert_eq!(h.app.crop_tool_aspect(), Some((100, 100)));+ h.app.run("crop.aspect", json!({"aspect": "toggle"})).unwrap();+ assert_eq!(h.app.ui.crop_default_aspect, Some(json!("free")));+ assert_eq!(h.app.session.develop_of(photo).unwrap(), before);+ h.app.ui.crop_default_aspect = Some(json!("original"));+ let p = h.app.session.catalog.photo(photo).unwrap();+ assert_eq!(h.app.crop_tool_aspect(), Some((p.width * 100, p.height * 100)));+ h.settle(SETTLE);+ assert_eq!(h.app.session.develop_of(photo).unwrap(), before);}/// While cropping: O cycles the guides, ⇧O mirrors them, A locks / unlocks the aspect.diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 523e5a066..5da45c938 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -348,6 +348,15 @@ impl LightcraftApp {if let Some(r) = menus::run_ui_command(self, id, ¶ms) {return r;}+ let params = if id == "crop.aspect"+ && params.get("aspect").and_then(Value::as_str) == Some("toggle")+ && self.crop_tool_aspect().is_some()+ && self.session.active().and_then(|id| self.session.develop_of(id)).is_some_and(|d| d.crop == lightcraft_develop::Crop::default())+ {+ serde_json::json!({"aspect": "free"})+ } else {+ params+ };let r = self.session.execute(id, ¶ms).map_err(|e| e.to_string());if r.is_ok() && matches!(id, "crop.aspect" | "crop.rotateAspect") {self.ui.crop_default_aspect = if id == "crop.aspect" && params.get("aspect").and_then(Value::as_str) == Some("original") {@@ -358,7 +367,6 @@ impl LightcraftApp {.and_then(|photo| self.session.develop_of(photo)).map(|d| d.crop.aspect.map_or(serde_json::json!("free"), |(w, h)| serde_json::json!([w as f64 / 100.0, h as f64 / 100.0])))};- self.ui.crop_default_photo = self.session.active();}if r.is_ok() && id == "photo.label" {let label = params.get("label").and_then(Value::as_str).and_then(lightcraft_catalog::ColorLabel::parse);@@ -389,25 +397,40 @@ impl LightcraftApp {r}- /// Initialize the crop tool on untouched photos without replacing existing crops.- pub(crate) fn apply_crop_default(&mut self) {- if self.ui.right != state::RightPanel::Crop {- self.ui.crop_default_photo = None;- return;- }- let photo = self.session.active();- if self.ui.crop_default_photo == photo {- return;+ /// The remembered ratio belongs to the tool until the user starts editing the crop.+ pub(crate) fn crop_tool_aspect(&self) -> Option<(u32, u32)> {+ let photo = self.session.active()?;+ let d = self.session.develop_of(photo)?;+ if d.crop != lightcraft_develop::Crop::default() {+ return d.crop.aspect;+ }+ match self.ui.crop_default_aspect.as_ref()? {+ Value::String(s) if s == "original" => {+ let p = self.session.catalog.photo(photo)?;+ let (w, h) = (p.width.max(1).saturating_mul(100), p.height.max(1).saturating_mul(100));+ Some(if d.orientation.swaps_axes() { (h, w) } else { (w, h) })+ }+ Value::Array(a) => {+ let number = |i: usize| {+ let v = a.get(i)?.as_f64()? * 100.0;+ (v.is_finite() && v >= 1.0 && v <= f64::from(u32::MAX)).then_some(v.round() as u32)+ };+ Some((number(0)?, number(1)?))+ }+ _ => None,}- self.ui.crop_default_photo = photo;- if let Some(photo) = photo- && self.session.develop_of(photo).is_some_and(|d| d.crop == lightcraft_develop::Crop::default())+ }++ /// Called only after a crop gesture begins, inside its undo transaction.+ pub(crate) fn begin_crop(&mut self) -> Result<(), String> {+ if self.session.interaction.is_some()+ && self.session.active().and_then(|id| self.session.develop_of(id)).is_some_and(|d| d.crop == lightcraft_develop::Crop::default())&& let Some(aspect) = self.ui.crop_default_aspect.clone()&& aspect != serde_json::json!("free")- && let Err(e) = self.session.execute("crop.aspect", &serde_json::json!({"aspect": aspect})){- self.ui.status = e.to_string();+ self.session.execute("crop.aspect", &serde_json::json!({"aspect": aspect})).map_err(|e| e.to_string())?;}+ Ok(())}/// Show a transient toast at the bottom of the canvas (like the reference app's HUD).@@ -727,7 +750,6 @@ impl LightcraftApp {}fn logic_inner(&mut self, ctx: &egui::Context) {- self.apply_crop_default();if !self.styled {theme::install_fonts_with_chinese(ctx, self.chinese_font.as_ref());theme::apply(ctx);diff --git a/crates/ui-egui/src/panels/detail.rs b/crates/ui-egui/src/panels/detail.rsindex 2e708da66..bc8d8202c 100644--- a/crates/ui-egui/src/panels/detail.rs+++ b/crates/ui-egui/src/panels/detail.rs@@ -1271,7 +1271,13 @@ fn crop_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Responsif resp.drag_started()&& let Some(q) = resp.interact_pointer_pos(){- let _ = app.run("develop.beginInteraction", json!({"label": "Crop"}));+ if let Err(e) = app.run("develop.beginInteraction", json!({"label": "Crop"})).and_then(|_| app.begin_crop().map(|_| serde_json::Value::Null))+ {+ app.ui.status = e;+ let _ = app.session.cancel_interaction();+ return;+ }+ let d = app.session.develop_of(id).unwrap_or_default();app.gesture = Some(match handles.iter().position(|h| h.distance(q) < 12.0) {Some(h) => Gesture::CropHandle { handle: h as u8, start: d.crop.geometry.rect, angle: d.crop.geometry.angle },None if inside(q) => Gesture::CropHandle { handle: 8, start: d.crop.geometry.rect, angle: d.crop.geometry.angle },diff --git a/crates/ui-egui/src/panels/right.rs b/crates/ui-egui/src/panels/right.rsindex 76b8f3984..8080f7517 100644--- a/crates/ui-egui/src/panels/right.rs+++ b/crates/ui-egui/src/panels/right.rs@@ -129,7 +129,6 @@ fn custom_aspect(app: &mut LightcraftApp, ui: &mut egui::Ui) {}fn crop(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) {- app.apply_crop_default();let d = app.session.develop_of(id).unwrap_or_default();header(ui, "Crop");padded(ui, |ui| {@@ -139,7 +138,7 @@ fn crop(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) {});ui.horizontal(|ui| {ui.label(crate::i18n::tr("Aspect Ratio"));- let cur = aspect_label(d.crop.aspect, original);+ let cur = aspect_label(app.crop_tool_aspect(), original);let t = Tokens::get(ui.ctx());let r = crate::widgets::dropdown(ui, "cropAspect", crate::i18n::tr(&cur), t.font(12.5), t.text);@@ -152,7 +151,7 @@ fn crop(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) {ui.separator();custom_aspect(app, ui);});- let locked = d.crop.aspect.is_some();+ let locked = app.crop_tool_aspect().is_some();if text_button(ui, "cropLock", if locked { "Locked" } else { "Lock" }, locked).clicked() {let _ = app.run("crop.aspect", json!({"aspect": "toggle"}));}diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rsindex a85e17b4f..992c176f9 100644--- a/crates/ui-egui/src/state.rs+++ b/crates/ui-egui/src/state.rs@@ -323,8 +323,6 @@ pub struct UiState {pub crop_overlay: CropOverlay,/// Last explicitly chosen aspect, retained across photos and app launches.pub crop_default_aspect: Option<serde_json::Value>,- #[serde(skip)]- pub crop_default_photo: Option<lightcraft_catalog::PhotoId>,pub show_filenames: bool,/// What the square grid's caption shows: `filename`, `exposure` (shutter · aperture · ISO ·/// focal length) or `date`.@@ -708,7 +706,6 @@ impl Default for UiState {mask_pins: true,crop_overlay: CropOverlay::Thirds,crop_default_aspect: None,- crop_default_photo: None,crop_overlay_orient: 0,show_filenames: true,grid_info: "filename".into(),diff --git a/crates/ui-egui/src/tests_masking.rs b/crates/ui-egui/src/tests_masking.rsindex 6a5f59e17..e2a2c0cfa 100644--- a/crates/ui-egui/src/tests_masking.rs+++ b/crates/ui-egui/src/tests_masking.rs@@ -308,6 +308,32 @@ fn command_drag_straightens_in_crop() {h.settle(SETTLE);}+#[test]+fn crop_drag_activates_the_remembered_ratio_and_undo_restores_the_photo() {+ let mut h = detail("panel.crop");+ h.app.ui.crop_default_aspect = Some(json!([1, 1]));+ h.settle(SETTLE);+ let before = develop(&h);+ let undo = h.app.session.undo.len();+ assert!(before.crop.aspect.is_none());+ let r = h.request(+ "ui.pointer",+ json!({"events": [+ {"kind": "down", "x": 0.995, "y": 0.995},+ {"kind": "drag", "x": 0.85, "y": 0.85},+ {"kind": "drag", "x": 0.75, "y": 0.75},+ {"kind": "up", "x": 0.75, "y": 0.75}+ ]}),+ T,+ );+ assert_eq!(r["ok"], true, "{r}");+ h.settle(SETTLE);+ assert_eq!(develop(&h).crop.aspect, Some((100, 100)));+ assert_eq!(h.app.session.undo.len(), undo + 1);+ exec(&mut h, "edit.undo", json!({}));+ assert_eq!(develop(&h), before);+}+#[test]fn double_click_in_crop_box_applies_the_crop() {let mut h = detail("panel.crop");diff --git a/docs/parity.md b/docs/parity.mdindex 948f5df98..8ced3e553 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -308,7 +308,7 @@ under the UI command that wraps it (a no-op error); the UI command now wins.| Id | Feature | Tier | Status | Evidence | Missing / notes ||---|---|---|---|---|---|| LR-CROP-RECT | Crop rectangle | P0 | ✅ | `cmd:crop.set`, `cmd:crop.drag`, `crates/geom/src/crop_drag.rs`, `crates/ui-egui/src/panels/detail.rs` | double-click inside the box applies the crop (like Return) |-| LR-CROP-ASPECT | Aspect ratios | P0 | ✅ | `cmd:crop.aspect`, `cmd:crop.rotateAspect`, `crates/ui-egui/src/panels/right.rs` | menu with presets + custom W × H, visible Lock toggle (also A), button names the active ratio; every handle honours the lock and the drag stops at the image edge instead of shifting the frame (issue #295); "Original" is the photo's own shape (no separate As Shot); the last chosen aspect is saved as the default for untouched photos in Crop, resolving Original per photo and preserving existing crops |+| LR-CROP-ASPECT | Aspect ratios | P0 | ✅ | `cmd:crop.aspect`, `cmd:crop.rotateAspect`, `crates/ui-egui/src/panels/right.rs` | menu with presets + custom W × H, visible Lock toggle (also A), button names the active ratio; every handle honours the lock and the drag stops at the image edge instead of shifting the frame (issue #295); "Original" is the photo's own shape (no separate As Shot); the last chosen aspect is saved as a crop tool default, resolving Original per photo and preserving existing crops; opening Crop or browsing never edits a photo: the default applies only when a crop gesture starts, within its single undo step || LR-CROP-STRAIGHTEN | Straighten tool | P0 | ✅ | `cmd:crop.straighten`, `cmd:crop.autoStraighten` | Straighten Tool button: drag along a horizon/vertical; double-click or Auto levels automatically || LR-CROP-AUTO | Auto straighten | P1 | ✅ | `cmd:crop.autoStraighten` | crop-angle leveling from detected horizon/plumb lines (consensus required) || LR-CROP-ANGLE | Angle slider | P0 | ✅ | `ctl:crop.angle` | |