PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Free Transform: Undo steps through the transform; handles are easier to grab (#365)
reese25d198ceb151
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex 62712de6f..5ef369a01 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -869,6 +869,7 @@ pub(crate) fn retain_gpu_documents(app: &mut PhotocraftApp) {/// Tabs + canvas for the active document, or the start screen.pub fn document_area(app: &mut PhotocraftApp, ui: &mut egui::Ui) {retain_gpu_documents(app);+ crate::transform_tool::track_steps(app, ui.ctx());let n = app.session.documents().len();// Files opening in the background (#210) have tabs before they have documents.let opening = !app.jobs.opens.is_empty();@@ -1960,7 +1961,8 @@ fn transform_controls_rect(app: &PhotocraftApp, xf: &ViewXform) -> Option<Rect>/// The interior stays the normal Move-tool drag target.fn transform_controls_hit(r: Rect, p: Pos2) -> bool {let handles = [r.left_top(), r.center_top(), r.right_top(), r.right_center(), r.right_bottom(), r.center_bottom(), r.left_bottom(), r.left_center()];- handles.iter().any(|h| h.distance(p) <= 8.0) || (r.expand(18.0).contains(p) && !r.expand(5.0).contains(p))+ let grab = crate::transform_tool::HANDLE_PX as f32;+ handles.iter().any(|h| h.distance(p) <= grab) || (r.expand(18.0).contains(p) && !r.expand(5.0).contains(p))}/// Enter the existing Free Transform session when a Move-tool transform control is pressed.diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex d8bb503d0..09ed12346 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -519,6 +519,9 @@ impl PhotocraftApp {{authorize(id, ¶ms)?;}+ if let Some(r) = transform_tool::intercept(self, id) {+ return r;+ }let suppress_events = self.automation_input && self.session.prefs().script_events.enabled;if suppress_events {self.session.edit_prefs(|prefs| prefs.script_events.enabled = false);@@ -1267,6 +1270,9 @@ mod input_tests;#[cfg(test)]mod pencil_tests;+#[cfg(test)]+mod transform_undo_tests;+#[cfg(test)]mod move_auto_select_tests;diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rsindex 7dbec1344..d4dd34e02 100644--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@ -453,6 +453,9 @@ pub fn is_enabled(app: &PhotocraftApp, id: &str) -> bool {if let Some(e) = crate::plugin_ui::is_enabled(app, id) {return e;}+ if let Some(e) = crate::transform_tool::is_enabled(app, id) {+ return e;+ }match id {"file.open" | "file.exit" | "file.clearRecent" | "help.about" | "help.systemInfo" | "edit.search" => true,i if i.starts_with("file.openRecent.") => true,diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rsindex 00e77c4a5..754d4a4a3 100644--- a/crates/ui-egui/src/panels.rs+++ b/crates/ui-egui/src/panels.rs@@ -1871,7 +1871,9 @@ fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) {});});}- if let Some(delta) = target {+ // An open Free Transform owns Undo (transform_tool::intercept): stepping the document's history under+ // its box would leave it transforming pixels that changed.+ if let Some(delta) = target.filter(|_| app.ui.transform.is_none()) {let (cmd, n) = if delta < 0 { ("edit.undo", -delta) } else { ("edit.redo", delta) };for _ in 0..n {if app.run(cmd, json!({})).is_err() {@@ -2432,6 +2434,52 @@ mod color_tests {}}+#[cfg(test)]+mod history_transform_tests {+ use super::*;+ use egui_kittest::Harness;++ fn click(h: &mut Harness<'static, PhotocraftApp>, p: egui::Pos2) {+ h.hover_at(p);+ h.run_steps(1);+ for pressed in [true, false] {+ h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE });+ h.run_steps(1);+ }+ }++ /// While Free Transform is open, clicking a History state leaves the document alone: the+ /// transform owns Undo. Without a transform the same click steps back as usual.+ #[test]+ fn history_rows_wait_for_an_open_transform() {+ for transforming in [true, false] {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"width": 200, "height": 150})).unwrap();+ app.run("layer.new.layer", json!({})).unwrap();+ app.run("select.rect", json!({"x": 20, "y": 20, "width": 60, "height": 40})).unwrap();+ app.run("edit.fill", json!({"color": "#ff0000"})).unwrap();+ app.run("select.deselect", json!({})).unwrap();+ let mut h = Harness::builder().with_size(vec2(300.0, 400.0)).build_ui_state(|ui, app: &mut PhotocraftApp| history(app, ui), app);+ h.run_steps(2);+ if transforming {+ let ctx = h.ctx.clone();+ crate::transform_tool::begin(h.state_mut(), &ctx).unwrap();+ }+ let steps = h.state().session.active().unwrap().history.entries().len();+ // The first state's row, below the 38 pt snapshot row.+ let row = h.ctx.input(|i| i.viewport_rect()).min + vec2(60.0, 60.0);+ click(&mut h, row);+ let after = h.state().session.active().unwrap().history.entries().len();+ if transforming {+ assert_eq!(after, steps, "the document's history is untouched");+ assert!(h.state().ui.transform.is_some());+ } else {+ assert!(after < steps, "the click steps back: {steps} -> {after}");+ }+ }+ }+}+#[cfg(test)]mod lock_tests {use super::*;diff --git a/crates/ui-egui/src/snap_ui.rs b/crates/ui-egui/src/snap_ui.rsindex b96d3529e..27f5dc9a2 100644--- a/crates/ui-egui/src/snap_ui.rs+++ b/crates/ui-egui/src/snap_ui.rs@@ -115,7 +115,7 @@ fn in_quad(q: &[[f64; 2]; 4], p: [f64; 2]) -> bool {inside}-/// Near a Free Transform corner or edge handle (within 8 screen px)?+/// Near a Free Transform corner or edge handle (within its grab radius)?fn near_handle(q: &[[f64; 2]; 4], p: [f64; 2], tol: f64) -> bool {(0..4).any(|i| {let (a, b) = (q[i], q[(i + 1) % 4]);@@ -141,7 +141,7 @@ fn begin(app: &mut PhotocraftApp, p: [f64; 2]) {let tool = app.ui.tool;let tol = tolerance(app);let gesture = if let Some(t) = &app.ui.transform {- if near_handle(&t.quad, p, tol) {+ if near_handle(&t.quad, p, crate::transform_tool::handle_tolerance(app)) {Some((Gesture::Point, vec![LayerId(t.layer)]))} else if in_quad(&t.quad, p) {Some((Gesture::TransformMove { rect: quad_rect(&t.quad) }, vec![LayerId(t.layer)]))diff --git a/crates/ui-egui/src/transform_tool.rs b/crates/ui-egui/src/transform_tool.rsindex a55952404..93c007e02 100644--- a/crates/ui-egui/src/transform_tool.rs+++ b/crates/ui-egui/src/transform_tool.rs@@ -5,7 +5,8 @@//! axis, ⌥ scales about the reference point, ⌘-drag a corner distorts (⌘⌥⇧: perspective), ⌘-drag//! an edge skews (⇧ along the edge), drag outside rotates (⇧ snaps to 15°), drag inside moves//! (⇧ locks to 8 directions), the reference point can be dragged and ⌥-click puts it under the-//! pointer. Arrow keys nudge the box (move_mods.rs). ↩ commits, Esc cancels.+//! pointer. Arrow keys nudge the box (move_mods.rs). ↩ commits, Esc cancels. Undo and Redo step+//! through the session's own changes (`Steps`), not the document's history.use std::sync::Arc;@@ -29,6 +30,63 @@ pub struct TransformPreview {gesture: Option<Gesture>,/// Warp-mode drag: (control point, pointer start, mesh points at the start).warp_drag: Option<(usize, [f64; 2], Vec<[f64; 2]>)>,+ steps: Steps,+}++/// Grab radius of the box's handles, in screen points. Generous, so a corner is easy to catch;+/// just beyond it, outside the box, a drag rotates.+pub const HANDLE_PX: f64 = 12.0;++/// [`HANDLE_PX`] in document pixels at the current zoom.+pub fn handle_tolerance(app: &PhotocraftApp) -> f64 {+ HANDLE_PX / app.current_zoom().max(0.01) as f64+}++/// The box as one undo step restores it.+#[derive(Clone, Debug, PartialEq)]+struct Step {+ rect: [f64; 4],+ quad: [[f64; 2]; 4],+ pivot: [f64; 2],+ warp: Option<Warp>,+}++impl Step {+ fn of(t: &TransformSession) -> Self {+ Step { rect: t.rect, quad: t.quad, pivot: t.pivot, warp: t.warp.clone() }+ }++ fn restore(self, t: &mut TransformSession) {+ (t.rect, t.quad, t.pivot, t.warp) = (self.rect, self.quad, self.pivot, self.warp);+ }+}++/// The session's own history: inside Free Transform, Undo steps back through the+/// handle drags, nudges and option edits rather than the document's history.+#[derive(Default)]+struct Steps {+ /// The box when it last came to rest (set when the session starts).+ settled: Option<Step>,+ undo: Vec<Step>,+ redo: Vec<Step>,+}++impl Steps {+ /// Record a step if the box changed since it last came to rest.+ fn settle(&mut self, now: Step) {+ if self.settled.as_ref() == Some(&now) {+ return;+ }+ if let Some(prev) = self.settled.replace(now) {+ self.undo.push(prev);+ self.redo.clear();+ }+ }++ /// Something to undo, counting a change not yet recorded (a nudge this frame).+ fn can_undo(&self, now: &Step) -> bool {+ !self.undo.is_empty() || self.settled.as_ref().is_some_and(|p| p != now)+ }}fn corners(r: [f64; 4]) -> [[f64; 2]; 4] {@@ -73,8 +131,15 @@ pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String>let max_side = ctx.input(|i| i.max_texture_side).max(app.gpu.as_ref().map_or(1, |g| g.max_texture_side()));let (image, uv) = preview_image(&doc, id, lifted.as_ref(), b, max_side);let texture = crate::transform_tex::PreviewTextures::new(ctx, format!("transform-{session}"), image, uv);- app.transform_preview =- Some(TransformPreview { session, doc: Arc::new(pd), texture, opacity: layer.opacity * layer.fill_opacity, gesture: None, warp_drag: None });+ app.transform_preview = Some(TransformPreview {+ session,+ doc: Arc::new(pd),+ texture,+ opacity: layer.opacity * layer.fill_opacity,+ gesture: None,+ warp_drag: None,+ steps: Steps::default(),+ });app.ui.transform = Some(TransformSession {session,layer: id.0,@@ -87,6 +152,7 @@ pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String>target: None,copy: false,});+ start_steps(app);Ok(())}@@ -159,7 +225,8 @@ fn begin_lone(let max_side = ctx.input(|i| i.max_texture_side).max(app.gpu.as_ref().map_or(1, |g| g.max_texture_side()));let (image, uv) = crate::transform_tex::read_surface(&lifted, None, b, max_side);let texture = crate::transform_tex::PreviewTextures::new(ctx, format!("transform-{session}"), image, uv);- app.transform_preview = Some(TransformPreview { session, doc: Arc::new(pd), texture, opacity: 0.6, gesture: None, warp_drag: None });+ app.transform_preview =+ Some(TransformPreview { session, doc: Arc::new(pd), texture, opacity: 0.6, gesture: None, warp_drag: None, steps: Steps::default() });app.ui.transform = Some(TransformSession {session,layer,@@ -172,6 +239,7 @@ fn begin_lone(target: Some(target),copy: false,});+ start_steps(app);Ok(())}@@ -203,7 +271,8 @@ pub fn begin_selection(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(let texture = crate::transform_tex::PreviewTextures::new(ctx, format!("transform-{session}"), egui::ColorImage::new([tw, th], px), uv);let mut pd = (*doc).clone();pd.selection = None;- app.transform_preview = Some(TransformPreview { session, doc: Arc::new(pd), texture, opacity: 1.0, gesture: None, warp_drag: None });+ app.transform_preview =+ Some(TransformPreview { session, doc: Arc::new(pd), texture, opacity: 1.0, gesture: None, warp_drag: None, steps: Steps::default() });app.ui.transform = Some(TransformSession {session,layer: layer.0,@@ -216,15 +285,21 @@ pub fn begin_selection(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(target: None,copy: false,});+ start_steps(app);Ok(())}/// Start (or switch an active Free Transform into) Warp mode.pub fn begin_warp(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> {- if app.ui.transform.is_none() {+ let fresh = app.ui.transform.is_none();+ if fresh {begin(app, ctx)?;}enter_warp(app);+ // Started in Warp: that is where Undo stops. Switching an open transform to Warp is a step.+ if fresh {+ start_steps(app);+ }Ok(())}@@ -375,6 +450,65 @@ pub fn cancel(app: &mut PhotocraftApp) {}}+/// The session's starting box: where Undo stops.+fn start_steps(app: &mut PhotocraftApp) {+ if let (Some(t), Some(pv)) = (&app.ui.transform, app.transform_preview.as_mut()) {+ pv.steps = Steps { settled: Some(Step::of(t)), ..Steps::default() };+ }+}++/// Record the box as an undo step whenever it comes to rest in a new state: once per drag (on+/// release), nudge or option edit (once typing in its field ends). Call once per frame.+pub fn track_steps(app: &mut PhotocraftApp, ctx: &egui::Context) {+ let (Some(t), Some(pv)) = (&app.ui.transform, app.transform_preview.as_mut()) else { return };+ if pv.gesture.is_some() || pv.warp_drag.is_some() || ctx.input(|i| i.pointer.any_down()) || ctx.text_edit_focused() {+ return;+ }+ pv.steps.settle(Step::of(t));+}++/// While transforming, Undo and Redo apply to the box: `Some(enabled)` for those commands (and+/// Toggle Last State, which would change the document under the box), `None` for the rest.+pub fn is_enabled(app: &PhotocraftApp, id: &str) -> Option<bool> {+ let t = app.ui.transform.as_ref()?;+ let steps = app.transform_preview.as_ref().map(|pv| &pv.steps);+ match id {+ "edit.undo" => Some(steps.is_some_and(|s| s.can_undo(&Step::of(t)))),+ "edit.redo" => Some(steps.is_some_and(|s| !s.redo.is_empty())),+ "edit.toggleLastState" => Some(false),+ _ => None,+ }+}++/// While transforming, the box owns the history for every caller (menus, shortcuts, the control+/// channel, MCP): Undo and Redo step through it, and Toggle Last State, which would change the+/// document under the box, is refused. `None` for other commands or when not transforming.+pub fn intercept(app: &mut PhotocraftApp, id: &str) -> Option<Result<serde_json::Value, String>> {+ app.ui.transform.as_ref()?;+ match id {+ "edit.undo" => Some(Ok(step(app, false))),+ "edit.redo" => Some(Ok(step(app, true))),+ "edit.toggleLastState" => Some(Err("Commit or cancel the transform first".into())),+ _ => None,+ }+}++/// Undo (or redo) one step of the open session; nothing mid-drag or with no step to take.+fn step(app: &mut PhotocraftApp, redo: bool) -> serde_json::Value {+ let Some(t) = app.ui.transform.as_mut() else { return serde_json::Value::Null };+ let Some(pv) = app.transform_preview.as_mut().filter(|pv| pv.gesture.is_none() && pv.warp_drag.is_none()) else {+ return serde_json::Value::Null;+ };+ let s = &mut pv.steps;+ s.settle(Step::of(t));+ let (from, to) = if redo { (&mut s.redo, &mut s.undo) } else { (&mut s.undo, &mut s.redo) };+ let Some(step) = from.pop() else { return serde_json::Value::Null };+ to.push(Step::of(t));+ s.settled = Some(step.clone());+ step.restore(t);+ json!({"transform": t})+}+/// Which part of the box a document point hits.#[derive(Clone, Copy, Debug, PartialEq)]enum Hit {@@ -385,23 +519,21 @@ enum Hit {Outside,}+/// The nearest handle within `tol` (on a small box their grab areas overlap), else inside or+/// outside the box.fn hit(t: &TransformSession, p: [f64; 2], tol: f64) -> Hit {let d = |a: [f64; 2]| ((a[0] - p[0]).powi(2) + (a[1] - p[1]).powi(2)).sqrt();- if d(t.pivot) < tol {- return Hit::Pivot;- }- for i in 0..4 {- if d(t.quad[i]) < tol {- return Hit::Corner(i);- }- }- for i in 0..4 {+ let mid = |i: usize| {let (a, b) = (t.quad[i], t.quad[(i + 1) % 4]);- if d([(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0]) < tol {- return Hit::Edge(i);- }+ [(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0]+ };+ let handles = (0..4).map(|i| (t.quad[i], Hit::Corner(i))).chain((0..4).map(|i| (mid(i), Hit::Edge(i)))).chain([(t.pivot, Hit::Pivot)]);+ let nearest = handles.map(|(q, h)| (d(q), h)).filter(|(dist, _)| *dist < tol).min_by(|a, b| a.0.total_cmp(&b.0));+ match nearest {+ Some((_, h)) => h,+ None if inside(&t.quad, p) => Hit::Inside,+ None => Hit::Outside,}- if inside(&t.quad, p) { Hit::Inside } else { Hit::Outside }}fn inside(q: &[[f64; 2]; 4], p: [f64; 2]) -> bool {@@ -427,7 +559,7 @@ struct Gesture {/// Pointer input while transforming. Returns false when no transform is active.pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> bool {let Some(t) = app.ui.transform.clone() else { return false };- let tol = 8.0 / app.current_zoom().max(0.01) as f64;+ let tol = handle_tolerance(app);if t.warp.is_some() {warp_pointer(app, ev, tol);return true;@@ -639,11 +771,12 @@ fn warp_pointer(app: &mut PhotocraftApp, ev: ToolEvent, tol: f64) {let Some(w) = t.warp.as_mut() else { return };match ev {ToolEvent::Down { x, y, .. } => {- if w.mesh.is_none() || w.style != WarpStyle::Custom {- let mesh = w.to_mesh(1, 1);- *w = Warp::custom(mesh, w.bounds);+ // A preset warp becomes a custom mesh only when the press grabs one of its points.+ let custom = if w.mesh.is_none() || w.style != WarpStyle::Custom { Warp::custom(w.to_mesh(1, 1), w.bounds) } else { w.clone() };+ pv.warp_drag = warp_hit(&custom, [x, y], tol).map(|i| (i, [x, y], custom.mesh.as_ref().map(|m| m.points.clone()).unwrap_or_default()));+ if pv.warp_drag.is_some() {+ *w = custom;}- pv.warp_drag = warp_hit(w, [x, y], tol).map(|i| (i, [x, y], w.mesh.as_ref().map(|m| m.points.clone()).unwrap_or_default()));}ToolEvent::Move { x, y, .. } | ToolEvent::Up { x, y } => {if let (Some((i, start, pts0)), Some(m)) = (&pv.warp_drag, w.mesh.as_mut()) {@@ -689,7 +822,7 @@ pub fn split(app: &mut PhotocraftApp, id: &str, at: Option<[f64; 2]>) -> Result</// Cursor for hovering a document point while transforming.pub fn cursor(app: &PhotocraftApp, p: [f64; 2]) -> Option<CursorIcon> {let t = app.ui.transform.as_ref()?;- let tol = 8.0 / app.current_zoom().max(0.01) as f64;+ let tol = handle_tolerance(app);if let Some(w) = &t.warp {return Some(if w.style != WarpStyle::Custom || warp_hit(w, p, tol).is_some() { CursorIcon::Crosshair } else { CursorIcon::Default });}@@ -1057,6 +1190,20 @@ mod tests {a.iter().flatten().zip(b.iter().flatten()).all(|(x, y)| (x - y).abs() < 1e-6)}+ /// On a box smaller than the handles' grab areas the nearest handle wins, so the reference+ /// point at the centre doesn't take presses on the corners and edges.+ #[test]+ fn the_nearest_handle_wins_on_a_small_box() {+ let mut s = session();+ s.quad = corners([0.0, 0.0, 16.0, 16.0]);+ s.pivot = [8.0, 8.0];+ assert_eq!(hit(&s, [0.0, 0.0], 12.0), Hit::Corner(0));+ assert_eq!(hit(&s, [16.0, 17.0], 12.0), Hit::Corner(2));+ assert_eq!(hit(&s, [8.0, -1.0], 12.0), Hit::Edge(0));+ assert_eq!(hit(&s, [8.0, 8.0], 12.0), Hit::Pivot);+ assert_eq!(hit(&s, [40.0, 40.0], 12.0), Hit::Outside);+ }+#[test]fn corner_drag_scales_proportionally_about_opposite_corner() {let mut s = session();@@ -1330,6 +1477,32 @@ mod tests {assert!(app.ui.transform.as_ref().unwrap().warp.is_none());}+ /// A press on a preset warp that misses its points leaves the preset alone (no invisible undo+ /// step); grabbing a point turns it into a custom mesh.+ #[test]+ fn a_press_on_a_preset_warp_converts_it_only_when_it_grabs_a_point() {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap();+ app.sync_views();+ app.session.execute("layer.new.layer", json!({})).unwrap();+ app.session+ .edit("paint", |doc, a| {+ doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(8, 8, 32, 32), &[1.0, 0.0, 0.0, 1.0]);+ Ok(())+ })+ .unwrap();+ begin_warp(&mut app, &egui::Context::default()).unwrap();+ let t = app.ui.transform.as_mut().unwrap();+ let preset = Warp::preset(WarpStyle::Arc, 50.0, t.rect);+ t.warp = Some(preset.clone());+ warp_pointer(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, 2.0);+ warp_pointer(&mut app, ToolEvent::Up { x: 20.0, y: 20.0 }, 2.0);+ assert_eq!(app.ui.transform.as_ref().unwrap().warp.as_ref(), Some(&preset), "a miss changes nothing");+ let corner = preset.to_mesh(1, 1).points[15];+ warp_pointer(&mut app, ToolEvent::Down { x: corner[0], y: corner[1], pressure: 1.0 }, 2.0);+ assert_eq!(app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap().style, WarpStyle::Custom);+ }+// ---- Layer masks (#205) ----/// `app_with_square` (red over 8..24) plus a reveal-all mask hiding x < 16.diff --git a/crates/ui-egui/src/transform_undo_tests.rs b/crates/ui-egui/src/transform_undo_tests.rsnew file mode 100644index 000000000..0d39fe87b--- /dev/null+++ b/crates/ui-egui/src/transform_undo_tests.rs@@ -0,0 +1,212 @@+//! Free Transform through the real canvas: Undo and Redo step through the box's own changes (each+//! drag one step) and never reach the document under the open box; and the+//! handles have a generous grab radius, so a press just off a corner scales instead of rotating.++use egui::{Key, Modifiers, PointerButton, Pos2, vec2};+use egui_kittest::Harness;+use serde_json::json;++use crate::PhotocraftApp;+use crate::canvas::ViewXform;+use crate::state::Tool;++/// A 400 × 300 document with a 100 × 60 red rectangle on its own layer at (100, 100), the Move+/// tool active, at 100 %.+fn harness() -> Harness<'static, PhotocraftApp> {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"width": 400, "height": 300})).unwrap();+ app.run("layer.new.layer", json!({})).unwrap();+ app.run("select.rect", json!({"x": 100, "y": 100, "width": 100, "height": 60})).unwrap();+ app.run("edit.fill", json!({"color": "#ff0000"})).unwrap();+ app.run("select.deselect", json!({})).unwrap();+ app.sync_views();+ app.ui.extras.rulers = false;+ app.ui.tool = Tool::Move;+ let mut h = Harness::builder().with_size(vec2(1000.0, 700.0)).build_ui_state(+ |ui, app: &mut PhotocraftApp| {+ let ctx = ui.ctx().clone();+ if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {+ return;+ }+ crate::shortcuts::handle(app, &ctx);+ egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui));+ },+ app,+ );+ PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);+ h.run_steps(4);+ let v = &mut h.state_mut().ui.views[0];+ v.zoom = 1.0;+ v.center = [200.0, 150.0];+ v.fit_pending = false;+ h.run_steps(2);+ h+}++fn screen(h: &Harness<'static, PhotocraftApp>, p: [f64; 2]) -> Pos2 {+ let app = h.state();+ let v = &app.ui.views[0];+ let xf = ViewXform { rect: crate::rulers::content_rect(app, app.last_canvas_rect), zoom: v.zoom, center: v.center, flip: app.ui.view.flip_horizontal };+ xf.to_screen(p[0] as f32, p[1] as f32)+}++/// Press at document point `from`, drag to `to` in a few steps and release.+fn drag(h: &mut Harness<'static, PhotocraftApp>, from: [f64; 2], to: [f64; 2]) {+ let (a, b) = (screen(h, from), screen(h, to));+ h.event(egui::Event::PointerMoved(a));+ h.run_steps(1);+ h.event(egui::Event::PointerButton { pos: a, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });+ h.run_steps(1);+ for k in 1..=6 {+ h.event(egui::Event::PointerMoved(a + (b - a) * (k as f32 / 6.0)));+ h.run_steps(1);+ }+ h.event(egui::Event::PointerButton { pos: b, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });+ h.run_steps(3);+}++fn begin(h: &mut Harness<'static, PhotocraftApp>) {+ let ctx = h.ctx.clone();+ crate::menus::invoke(h.state_mut(), &ctx, "edit.freeTransform", json!({})).unwrap();+ h.run_steps(2);+}++fn quad(h: &Harness<'static, PhotocraftApp>) -> [[f64; 2]; 4] {+ h.state().ui.transform.as_ref().expect("transforming").quad+}++fn history(h: &Harness<'static, PhotocraftApp>) -> usize {+ h.state().session.active().unwrap().history.entries().len()+}++fn key(h: &mut Harness<'static, PhotocraftApp>, m: Modifiers, k: Key) {+ h.key_press_modifiers(m, k);+ h.run_steps(2);+}++fn close(a: [[f64; 2]; 4], b: [[f64; 2]; 4]) -> bool {+ a.iter().flatten().zip(b.iter().flatten()).all(|(x, y)| (x - y).abs() < 1e-6)+}++/// Scale ×2, then down again, then ⌘Z: back to the ×2 box, not the fill before the transform.+#[test]+fn undo_steps_back_through_the_transform_not_the_document() {+ let mut h = harness();+ let steps = history(&h);+ begin(&mut h);+ let q0 = quad(&h);+ assert!(close(q0, [[100.0, 100.0], [200.0, 100.0], [200.0, 160.0], [100.0, 160.0]]), "{q0:?}");+ drag(&mut h, q0[2], [300.0, 220.0]);+ let q1 = quad(&h);+ assert!(!close(q1, q0), "the first drag scaled the box");+ drag(&mut h, q1[2], [150.0, 130.0]);+ let q2 = quad(&h);+ assert!(!close(q2, q1), "the second drag scaled it again");++ key(&mut h, Modifiers::COMMAND, Key::Z);+ assert!(close(quad(&h), q1), "⌘Z undoes the second drag: {:?}", quad(&h));+ key(&mut h, Modifiers::COMMAND, Key::Z);+ assert!(close(quad(&h), q0), "⌘Z again undoes the first");+ // Nothing left to undo in the session: the document under the box is left alone.+ key(&mut h, Modifiers::COMMAND, Key::Z);+ assert!(close(quad(&h), q0));+ assert_eq!(history(&h), steps, "the fill is still there");+ assert_eq!(width(&h), 100);++ key(&mut h, Modifiers::COMMAND | Modifiers::SHIFT, Key::Z);+ assert!(close(quad(&h), q1), "⇧⌘Z redoes the first drag");+ // A new change drops the redo; ↩ commits the session as one document step.+ key(&mut h, Modifiers::NONE, Key::ArrowRight);+ key(&mut h, Modifiers::COMMAND | Modifiers::SHIFT, Key::Z);+ assert!(close(quad(&h), q1.map(|p| [p[0] + 1.0, p[1]])), "nudged, nothing to redo: {:?}", quad(&h));+ key(&mut h, Modifiers::COMMAND, Key::Z);+ assert!(close(quad(&h), q1), "a nudge is a step too");+ key(&mut h, Modifiers::NONE, Key::Enter);+ assert!(h.state().ui.transform.is_none());+ assert_eq!(history(&h), steps + 1);+ assert_ne!(width(&h), 100);+ // Outside the transform, ⌘Z is the document's Undo again.+ key(&mut h, Modifiers::COMMAND, Key::Z);+ assert_eq!(width(&h), 100, "the committed transform is undone");+}++/// `engine.execute` over the control channel (and MCP, which goes through it) as a programmatic+/// caller: the result's `ok` flag.+fn execute(h: &mut Harness<'static, PhotocraftApp>, command: &str) -> bool {+ let ctx = h.ctx.clone();+ let (req, _rx) = crate::control::ControlRequest::new("engine.execute", json!({"command": command}));+ let crate::control::Outcome::Done(reply) = crate::control::handle(h.state_mut(), &ctx, &req) else {+ panic!("{command}: expected an immediate reply");+ };+ h.run_steps(2);+ reply["ok"].as_bool().unwrap()+}++/// Undo and Redo sent over the control channel step through the open box like ⌘Z, never the+/// document under it, and Toggle Last State is refused until the transform ends.+#[test]+fn automation_undo_steps_through_the_transform() {+ let mut h = harness();+ let steps = history(&h);+ begin(&mut h);+ let q0 = quad(&h);+ drag(&mut h, q0[2], [300.0, 220.0]);+ let q1 = quad(&h);+ assert!(execute(&mut h, "edit.undo"));+ assert!(close(quad(&h), q0), "undid the drag: {:?}", quad(&h));+ assert!(execute(&mut h, "edit.undo"), "nothing left in the session: a no-op");+ assert!(close(quad(&h), q0));+ assert_eq!(history(&h), steps, "the fill is still there");+ assert_eq!(width(&h), 100);+ assert!(execute(&mut h, "edit.redo"));+ assert!(close(quad(&h), q1), "redid the drag");+ assert!(!execute(&mut h, "edit.toggleLastState"), "refused while transforming");+ assert!(close(quad(&h), q1));+ assert_eq!(history(&h), steps);+ // Once the transform ends, they reach the document again.+ key(&mut h, Modifiers::NONE, Key::Escape);+ assert!(h.state().ui.transform.is_none());+ assert!(execute(&mut h, "edit.undo"));+ assert_eq!(history(&h), steps - 1, "the fill is undone");+}++fn width(h: &Harness<'static, PhotocraftApp>) -> u32 {+ let st = h.state().session.active().unwrap();+ st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds().width()+}++/// A press 10 pt diagonally off a corner (outside the old 8 pt radius) grabs the corner and+/// scales, whether the transform is already open or starts from the Move tool's controls.+#[test]+fn a_press_just_off_a_corner_scales_rather_than_rotates() {+ for via_controls in [false, true] {+ let mut h = harness();+ if via_controls {+ h.state_mut().ui.tool_options.move_show_transform = true;+ h.run_steps(1);+ } else {+ begin(&mut h);+ }+ drag(&mut h, [207.0, 167.0], [257.0, 197.0]);+ let q = quad(&h);+ assert!((q[0][1] - q[1][1]).abs() < 1e-6 && (q[1][0] - q[2][0]).abs() < 1e-6, "via controls {via_controls}: not rotated: {q:?}");+ assert!(q[2][0] > 230.0, "via controls {via_controls}: scaled: {q:?}");+ // Well outside the box still rotates.+ let before = quad(&h);+ drag(&mut h, [before[2][0] + 30.0, before[2][1] + 30.0], [before[2][0] - 10.0, before[2][1] + 60.0]);+ let r = quad(&h);+ assert!((r[0][1] - r[1][1]).abs() > 1.0, "via controls {via_controls}: rotated: {r:?}");+ }+}++/// A transform started by dragging a Move-tool control: that first drag is undoable too.+#[test]+fn the_first_drag_from_the_move_tools_controls_undoes() {+ let mut h = harness();+ h.state_mut().ui.tool_options.move_show_transform = true;+ h.run_steps(1);+ drag(&mut h, [200.0, 160.0], [260.0, 196.0]);+ assert!(!close(quad(&h), [[100.0, 100.0], [200.0, 100.0], [200.0, 160.0], [100.0, 160.0]]));+ key(&mut h, Modifiers::COMMAND, Key::Z);+ assert!(close(quad(&h), [[100.0, 100.0], [200.0, 100.0], [200.0, 160.0], [100.0, 160.0]]), "{:?}", quad(&h));+}