Merge pull request #11221 from yoriswind/codex/transform-hit-zones-11097

Use whole-edge Free Transform handles and consistent rotate cursors
This commit is contained in:
David Mann authored and GitHub committed 2026-11-08 01:41:27 +01:00
commit ce517049a7
7 files changed
+684 -127

No files matched your search

+1 -1
View File
@@ -947,7 +947,7 @@ fn alt_over_the_box_shows_the_reference_point_pointer() {
for p in [[55.0, 52.0], [30.0, 30.0], [200.0, 200.0]] {
assert_eq!(crate::transform_tool::cursor(&app, &xf, p, alt), Some(egui::CursorIcon::Crosshair), "{p:?}");
}
assert_eq!(crate::transform_tool::cursor(&app, &xf, [55.0, 52.0], egui::Modifiers::NONE), Some(egui::CursorIcon::Move));
assert_eq!(crate::transform_tool::cursor(&app, &xf, [55.0, 52.0], egui::Modifiers::NONE), Some(egui::CursorIcon::Default));
assert_ne!(crate::transform_tool::cursor(&app, &xf, [40.0, 40.0], alt), Some(egui::CursorIcon::Crosshair), "a corner handle stays a handle");
}
+46 -39
View File
@@ -1,6 +1,6 @@
use super::selection::floating_outline;
use super::view_xform::ViewXform;
use super::{Color32, LayerContent, PhotocraftApp, Pos2, Rect, Stroke, Tool, Vec2, pos2, vec2};
use super::{Color32, LayerContent, PhotocraftApp, Pos2, Rect, Stroke, Tool, Vec2, vec2};
/// View › Show › Layer Edges: the colour of the active layer's outline.
pub(crate) const LAYER_EDGES: Color32 = Color32::from_rgb(0x2d, 0x8c, 0xeb);
@@ -75,50 +75,53 @@ pub(super) fn transform_controls_rect(app: &PhotocraftApp, xf: &ViewXform) -> Op
Some(Rect::from_two_pos(xf.to_screen(b.x0 as f32, b.y0 as f32), xf.to_screen(b.x1 as f32, b.y1 as f32)))
}
/// The Move tool shows transform handles even before a Free Transform session exists.
/// Use the same hit areas for pointer-down and hover, so a control never behaves like
/// resize/rotate while showing the ordinary four-arrow Move cursor (#2871).
/// Express the unopened screen rectangle in the same corner order as a transform quad.
fn controls_quad(r: Rect) -> [[f64; 2]; 4] {
[r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom()].map(|p| [f64::from(p.x), f64::from(p.y)])
}
/// Classify screen coordinates with the fixed screen-space tolerance, without a pivot.
fn controls_zone(r: Rect, p: Pos2) -> crate::transform_tool::Hit {
crate::state::TransformSession::box_hit(&controls_quad(r), [f64::from(p.x), f64::from(p.y)], crate::transform_tool::HANDLE_PX)
}
/// Share the open session's screen-sized zones before the first interaction (#11097).
pub(super) fn transform_controls_cursor(r: Rect, p: Pos2) -> Option<egui::CursorIcon> {
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()];
let grab = crate::transform_tool::HANDLE_PX as f32;
for (i, handle) in handles.into_iter().enumerate() {
if handle.distance(p) <= grab {
return Some(match i {
0 | 4 => egui::CursorIcon::ResizeNwSe,
2 | 6 => egui::CursorIcon::ResizeNeSw,
1 | 5 => egui::CursorIcon::ResizeVertical,
_ => egui::CursorIcon::ResizeHorizontal,
});
}
}
// The rotation band: the pointer gives way to the curved rotate arrow (`transform_controls_turn`).
in_rotation_band(r, p).then_some(egui::CursorIcon::None)
}
fn in_rotation_band(r: Rect, p: Pos2) -> bool {
r.expand(18.0).contains(p) && !r.expand(5.0).contains(p)
}
/// In the rotation band just outside the Move tool's transform controls, the screen direction the
/// curved rotate arrow bends round: into the box along the nearest corner's bisector, as Free
/// Transform draws it (#4658). Before, the band showed a plain alias pointer, so nothing said a
/// drag there rotates.
pub(super) fn transform_controls_turn(r: Rect, p: Pos2) -> Option<Vec2> {
if !in_rotation_band(r, p)
|| [r.left_top(), r.center_top(), r.right_top(), r.right_center(), r.right_bottom(), r.center_bottom(), r.left_bottom(), r.left_center()]
.into_iter()
.any(|h| h.distance(p) <= crate::transform_tool::HANDLE_PX as f32)
{
if !p.is_finite() {
return None;
}
let corner = pos2(if p.x < r.center().x { r.left() } else { r.right() }, if p.y < r.center().y { r.top() } else { r.bottom() });
Some(vec2((r.center().x - corner.x).signum(), (r.center().y - corner.y).signum()).normalized() * 16.0)
use crate::transform_tool::Hit;
Some(match controls_zone(r, p) {
Hit::Corner(0 | 2) => egui::CursorIcon::ResizeNwSe,
Hit::Corner(_) => egui::CursorIcon::ResizeNeSw,
Hit::Edge(0 | 2) => egui::CursorIcon::ResizeVertical,
Hit::Edge(_) => egui::CursorIcon::ResizeHorizontal,
Hit::Outside => egui::CursorIcon::None,
Hit::Inside | Hit::Pivot => egui::CursorIcon::Default,
})
}
/// A visible handle starts scaling; the narrow band just outside the box starts rotation.
/// The interior stays the normal Move-tool drag target.
/// At any distance outside the controls, the same edge/corner direction as Free Transform.
pub(super) fn transform_controls_turn(r: Rect, p: Pos2) -> Option<Vec2> {
if controls_zone(r, p) != crate::transform_tool::Hit::Outside {
return None;
}
let k = crate::state::TransformSession::box_turn_direction(&controls_quad(r), [f64::from(p.x), f64::from(p.y)])?;
Some(vec2(k[0] as f32, k[1] as f32) * 16.0)
}
/// Resize from the shared handle zones and keep Move's existing rotation press band.
/// Outside presses beyond that band still reach the Move tool, even where hover paints a turn arc.
pub(super) fn transform_controls_hit(r: Rect, p: Pos2) -> bool {
transform_controls_cursor(r, p).is_some()
if !p.is_finite() {
return false;
}
use crate::transform_tool::Hit;
match controls_zone(r, p) {
Hit::Corner(_) | Hit::Edge(_) => true,
Hit::Outside => r.expand(18.0).contains(p) && !r.expand(5.0).contains(p),
Hit::Inside | Hit::Pivot => false,
}
}
/// The reference application's alert when a Move-tool transform control is dragged on a frame
@@ -177,3 +180,7 @@ pub(super) fn draw_transform_controls(app: &mut PhotocraftApp, painter: &egui::P
painter.rect_stroke(h, 0.0, Stroke::new(1.0, accent), egui::StrokeKind::Inside);
}
}
#[cfg(test)]
#[path = "../transform_hit_zone_tests.rs"]
mod hit_zone_tests;
@@ -328,21 +328,20 @@ fn move_transform_controls_show_resize_and_rotate_cursors_before_first_interacti
(r.center_bottom(), egui::CursorIcon::ResizeVertical),
(r.right_center(), egui::CursorIcon::ResizeHorizontal),
(r.left_center(), egui::CursorIcon::ResizeHorizontal),
// Between handles: the rotation band (a point above the top-centre handle is that handle),
// where the curved rotate arrow replaces the pointer (#4658).
// Just beyond the outward edge band, the curved rotate arrow replaces the pointer (#4658).
(pos2(r.left() + r.width() * 0.25, r.top() - 12.0), egui::CursorIcon::None),
] {
assert_eq!(transform_controls_cursor(r, p), Some(expected), "hover at {p:?}");
assert!(transform_controls_hit(r, p), "same region must start a transform");
}
assert_eq!(transform_controls_cursor(r, r.center()), None, "interior stays Move");
assert_eq!(transform_controls_cursor(r, pos2(r.center().x, r.top() - 30.0)), None);
// The rotate arrow bends round the nearest corner, pointing into the box; handles and the
// interior have none.
let into = |p: Pos2| transform_controls_turn(r, p).map(|v| (v.x.signum(), v.y.signum()));
assert_eq!(into(pos2(r.left() + r.width() * 0.25, r.top() - 12.0)), Some((1.0, 1.0)), "top left");
assert_eq!(into(pos2(r.right() + 12.0, r.bottom() - r.height() * 0.25)), Some((-1.0, -1.0)), "bottom right");
assert_eq!(into(pos2(r.left() - 12.0, r.bottom() + 12.0)), Some((1.0, -1.0)), "beyond the bottom-left corner");
assert_eq!(transform_controls_cursor(r, r.center()), Some(egui::CursorIcon::Default), "interior uses the default arrow");
assert_eq!(transform_controls_cursor(r, pos2(r.center().x, r.top() - 30.0)), Some(egui::CursorIcon::None));
// The rotate arrow points into the nearest edge or corner. Handles and the interior have none.
let into = |p: Pos2| transform_controls_turn(r, p);
assert_eq!(into(pos2(r.left() + r.width() * 0.25, r.top() - 12.0)), Some(vec2(0.0, 16.0)), "top edge");
assert_eq!(into(pos2(r.right() + 12.0, r.bottom() - r.height() * 0.25)), Some(vec2(-16.0, 0.0)), "right edge");
let corner = into(pos2(r.left() - 12.0, r.bottom() + 12.0)).unwrap();
assert!(corner.x > 0.0 && corner.y < 0.0, "beyond the bottom-left corner");
assert_eq!(into(r.left_top()), None);
assert_eq!(into(r.center()), None);
@@ -351,7 +350,7 @@ fn move_transform_controls_show_resize_and_rotate_cursors_before_first_interacti
let next = transform_controls_rect(&app, &xf).expect("new active shape controls");
assert_ne!(r, next);
assert_eq!(transform_controls_cursor(next, next.right_bottom()), Some(egui::CursorIcon::ResizeNwSe));
assert_eq!(transform_controls_cursor(next, next.center()), None);
assert_eq!(transform_controls_cursor(next, next.center()), Some(egui::CursorIcon::Default));
}
#[test]
@@ -1,11 +1,11 @@
use super::begin::warps_type;
use super::drag_modes::{HandleIndicator, handle_indicator};
use super::options_bar::{quad_scale, readout};
use super::pointer::{Hit, handle_at, rotate_dir, rotation_degrees};
use super::pointer::{Hit, handle_at, rotation_degrees};
use super::warp::{on_section_edge, quick_split_kind, single_patch};
use super::{
BezierMesh, Color32, DocId, HANDLE_PX, Homography, LayerId, PhotocraftApp, Pos2, SplitTool, Stroke, TransformPreview, TransformSession, ViewXform, Warp,
WarpDrag, WarpStyle, corners, pos2, vec2,
BezierMesh, Color32, DocId, Homography, LayerId, PhotocraftApp, Pos2, SplitTool, Stroke, TransformPreview, TransformSession, ViewXform, Warp, WarpDrag,
WarpStyle, corners, pos2, vec2,
};
/// The distort or skew pointer at screen point `at`, where [`super::cursor`] hid the system
@@ -224,14 +224,6 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform
painter.line_segment([c - vec2(0.0, 8.0), c + vec2(0.0, 8.0)], Stroke::new(1.0, Color32::WHITE));
}
if let Some(at) = painter.ctx().pointer_hover_pos().filter(|p| xf.rect.contains(*p)) {
let p = xf.to_doc(at);
let tol = HANDLE_PX / f64::from(xf.zoom.max(0.01));
if let Some(k) = rotate_dir(t, Some(pv), p, tol) {
// Through the view, so the arc bends round the corner as it shows under a turned or
// flipped view.
let toward = xf.to_screen((p[0] + k[0] * 16.0) as f32, (p[1] + k[1] * 16.0) as f32) - at;
crate::crop_ui::draw_turn_cursor(painter.ctx(), at, toward);
}
// Preferences › Tools › Show Transformation Values off hides it, as in Photoshop (#204).
if let Some(r) = live_readout(app).filter(|_| app.session.prefs().tools.show_transformation_values) {
draw_live_readout(app, painter.ctx(), at, r);
@@ -3,8 +3,7 @@ use super::commit::{commit, committing, moves_type};
use super::drag_modes::{apply_drag, apply_mode_drag, drag_mods, handle_indicator, mode_allows, mode_mods};
use super::warp::{quick_split_kind, split_cursor, surface_at, warp_hit, warp_pointer};
use super::{
CursorIcon, HANDLE_PX, Homography, LayerContent, PhotocraftApp, ToolEvent, TransformMode, TransformPreview, TransformSession, ViewXform, WarpStyle,
handle_tolerance,
CursorIcon, HANDLE_PX, Homography, LayerContent, PhotocraftApp, ToolEvent, TransformMode, TransformSession, ViewXform, WarpStyle, handle_tolerance,
};
/// Which part of the box a document point hits.
@@ -17,8 +16,106 @@ pub(crate) enum Hit {
Outside,
}
/// The nearest handle within `tol` (on a small box their grab areas overlap), else inside or
/// outside the box.
/// Screen-sized corner and outward edge bands, shared with Move's unopened controls.
impl TransformSession {
/// Classify a document point with screen-sized corner and outward edge zones.
/// On and outward from an edge, the nearest corner or midpoint wins, with the corner
/// reach capped along the edge. Inside and beyond the edge ends use the corner radius.
pub(crate) fn box_hit(quad: &[[f64; 2]; 4], p: [f64; 2], tol: f64) -> Hit {
// `tol` is the existing 12 pt handle tolerance, divided by the view zoom.
let corner_radius = tol * (8.0 / HANDLE_PX);
let edge_width = tol * (11.0 / HANDLE_PX);
// Canvas coordinates round through f32. Treat only sub-pixel projection noise as
// the line itself; a point one screen pixel inside still belongs to the interior.
let line_epsilon = tol.abs() * (1e-3 / HANDLE_PX);
let distance = |q: [f64; 2]| (p[0] - q[0]).hypot(p[1] - q[1]);
let interior = inside(quad, p);
let edge = (0..4)
.filter_map(|i| {
let (u, q) = edge_projection(quad, i, p)?;
let d = distance(q);
(d <= edge_width && (!interior || d <= line_epsilon)).then_some((i, u, d))
})
.min_by(|a, b| a.2.total_cmp(&b.2));
if let Some((i, u, _)) = edge
&& (0.0..=1.0).contains(&u)
{
let next = (i + 1) % 4;
let (a, b) = (quad[i], quad[next]);
let length = (b[0] - a[0]).hypot(b[1] - a[1]);
let quarter = length * 0.25;
let tie_epsilon = line_epsilon.min(quarter * 0.5);
// Projected distances rank the handles along this edge. At the measured
// quarter-point ties, prefer the earlier handle in edge order.
let from_start = u * length;
let from_end = (1.0 - u) * length;
if from_start <= quarter + tie_epsilon && from_start <= edge_width + line_epsilon {
return Hit::Corner(i);
}
if from_end < quarter - tie_epsilon && from_end <= edge_width + line_epsilon {
return Hit::Corner(next);
}
return Hit::Edge(i);
}
if let Some((i, _)) = quad.iter().enumerate().map(|(i, &q)| (i, distance(q))).filter(|(_, d)| *d <= corner_radius).min_by(|a, b| a.1.total_cmp(&b.1)) {
return Hit::Corner(i);
}
match edge {
Some((i, _, _)) => Hit::Edge(i),
None if interior => Hit::Inside,
None => Hit::Outside,
}
}
/// Into the nearest edge or corner: eight orientations for an upright rectangle, following
/// the actual quad when it is rotated, flipped or distorted.
pub(crate) fn box_turn_direction(quad: &[[f64; 2]; 4], p: [f64; 2]) -> Option<[f64; 2]> {
if p.iter().chain(quad.iter().flatten()).any(|v| !v.is_finite()) {
return None;
}
let (i, u, _) = (0..4)
.filter_map(|i| {
let (u, q) = edge_projection(quad, i, p)?;
Some((i, u, (p[0] - q[0]).hypot(p[1] - q[1])))
})
.min_by(|a, b| a.2.total_cmp(&b.2))?;
let unit = |v: [f64; 2]| {
let len = v[0].hypot(v[1]);
(len.is_finite() && len > 1e-9).then(|| [v[0] / len, v[1] / len])
};
let toward = if u <= 0.0 || u >= 1.0 {
let i = if u >= 1.0 { (i + 1) % 4 } else { i };
let direction = |j: usize| unit([quad[j][0] - quad[i][0], quad[j][1] - quad[i][1]]);
let (a, b) = (direction((i + 1) % 4)?, direction((i + 3) % 4)?);
[a[0] + b[0], a[1] + b[1]]
} else {
let (a, b) = (quad[i], quad[(i + 1) % 4]);
let normal = [a[1] - b[1], b[0] - a[0]];
// Winding orients every edge, even when a concave quad's mean corner position
// lies on the wrong side of this edge. Translate before taking the area.
let cross = |i: usize, j: usize| (quad[i][0] - quad[0][0]) * (quad[j][1] - quad[0][1]) - (quad[i][1] - quad[0][1]) * (quad[j][0] - quad[0][0]);
let sign = (cross(1, 2) + cross(2, 3)).signum();
normal.map(|v| v * sign)
};
unit(toward)
}
}
/// The unclamped projection parameter and the nearest point on the segment. Degenerate
/// edges have no band or normal; the other edges and corner handles remain usable.
fn edge_projection(quad: &[[f64; 2]; 4], i: usize, p: [f64; 2]) -> Option<(f64, [f64; 2])> {
let (a, b) = (quad[i], quad[(i + 1) % 4]);
let d = [b[0] - a[0], b[1] - a[1]];
let len2 = d[0] * d[0] + d[1] * d[1];
if !len2.is_finite() || len2 <= 1e-18 {
return None;
}
let u = ((p[0] - a[0]) * d[0] + (p[1] - a[1]) * d[1]) / len2;
let on_segment = u.clamp(0.0, 1.0);
Some((u, [a[0] + on_segment * d[0], a[1] + on_segment * d[1]]))
}
/// The shared box zones, retaining the nearest pivot's existing grab priority on small boxes.
pub(crate) fn hit(t: &TransformSession, p: [f64; 2], tol: f64) -> Hit {
hit_with(t, p, tol, true)
}
@@ -35,22 +132,26 @@ fn hit_with(t: &TransformSession, p: [f64; 2], tol: f64, pivot: bool) -> Hit {
let (a, b) = (t.quad[i], t.quad[(i + 1) % 4]);
[(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0]
};
let h = TransformSession::box_hit(&t.quad, p, tol);
let handle_distance = match h {
Hit::Corner(i) => d(t.quad[i]),
Hit::Edge(i) => d(mid(i)),
_ => f64::INFINITY,
};
if pivot {
// A shown reference point wins ties with handles, including when it sits on one.
let distance = d(t.pivot);
return if distance < tol && distance <= handle_distance { Hit::Pivot } else { h };
}
// With the reference point hidden, the box centre is a move target in its place, so a press
// at the centre of a box smaller than two grab areas moves it instead of grabbing an edge.
let centre = [t.quad.iter().map(|q| q[0]).sum::<f64>() / 4.0, t.quad.iter().map(|q| q[1]).sum::<f64>() / 4.0];
// A shown reference point comes first: where it sits on a handle (the options bar's locator
// or its pull to the box's points put it there), a press drags the point, not the handle, as
// in the reference application.
let (first, last) = if pivot { (Some((t.pivot, Hit::Pivot)), None) } else { (None, Some((centre, Hit::Inside))) };
let handles = first.into_iter().chain((0..4).map(|i| (t.quad[i], Hit::Corner(i)))).chain((0..4).map(|i| (mid(i), Hit::Edge(i)))).chain(last);
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,
}
let distance = d(centre);
if distance < tol && distance < handle_distance { Hit::Inside } else { h }
}
/// Even-odd quad membership, independent of winding and valid for concave boxes.
/// Handles and edge-rounding tolerance are classified separately by the caller.
fn inside(q: &[[f64; 2]; 4], p: [f64; 2]) -> bool {
let mut c = false;
for i in 0..4 {
@@ -268,16 +369,12 @@ pub(super) fn carry_pivot(quad0: [[f64; 2]; 4], quad: [[f64; 2]; 4], pivot0: [f6
if x.is_finite() && y.is_finite() { [x, y] } else { pivot0 }
}
/// True just outside a corner: rotate handle feedback lives here, not over the entire
/// empty canvas. The actual rotation gesture continues to work farther away.
pub(super) fn near_rotate_corner(t: &TransformSession, p: [f64; 2], tol: f64) -> bool {
/// Rotation feedback uses the same hit as the gesture, including the held hit while dragging.
pub(super) fn near_rotate_corner(t: &TransformSession, h: Hit) -> bool {
t.warp.is_none()
&& t.mode != TransformMode::Distort
&& {
let h = hit(t, p, tol);
h == Hit::Outside || (t.mode == TransformMode::Rotate && matches!(h, Hit::Corner(_) | Hit::Edge(_)))
}
&& t.quad.iter().any(|q| (p[0] - q[0]).hypot(p[1] - q[1]) <= tol * 3.0)
&& t.content_aware.is_none()
&& !matches!(t.mode, TransformMode::Distort | TransformMode::Skew)
&& (h == Hit::Outside || (t.mode == TransformMode::Rotate && matches!(h, Hit::Corner(_) | Hit::Edge(_))))
}
/// Clockwise degrees in canvas coordinates (positive Y points down).
@@ -288,40 +385,18 @@ pub(super) fn rotation_degrees(quad: [[f64; 2]; 4]) -> f64 {
}
/// Where the rotate cursor's arc bends at document point `p`, or `None` outside the rotate zone:
/// just outside a corner, or anywhere while a rotate drag is on. It points into the box along the
/// bisector of the nearest corner, so each corner gets its own arrow and they turn with the box.
/// anywhere outside, or while a rotate drag is on. It follows the nearest edge or corner.
pub(crate) fn rotate_cursor_dir(app: &PhotocraftApp, p: [f64; 2]) -> Option<[f64; 2]> {
rotate_dir(app.ui.transform.as_ref()?, app.transform_preview.as_ref(), p, handle_tolerance(app))
let t = app.ui.transform.as_ref()?;
rotate_dir(t, handle_at(app, t, p, handle_tolerance(app)), p)
}
pub(super) fn rotate_dir(t: &TransformSession, pv: Option<&TransformPreview>, p: [f64; 2], tol: f64) -> Option<[f64; 2]> {
// Content-Aware Scale's box only scales, and Skew doesn't rotate: no rotate arrow.
if !(p[0].is_finite() && p[1].is_finite())
|| t.warp.is_some()
|| t.content_aware.is_some()
|| matches!(t.mode, TransformMode::Distort | TransformMode::Skew)
{
/// Follow the nearest edge or corner during a rotation hover or drag.
fn rotate_dir(t: &TransformSession, h: Hit, p: [f64; 2]) -> Option<[f64; 2]> {
if !near_rotate_corner(t, h) {
return None;
}
// During a drag the arrow shows only while it rotates: not when a handle that scales, skews
// or distorts strays past a corner (#5405).
match pv.and_then(|pv| pv.gesture) {
Some(g) if g.hit == Hit::Outside || (t.mode == TransformMode::Rotate && matches!(g.hit, Hit::Corner(_) | Hit::Edge(_))) => {}
Some(_) => return None,
None if !near_rotate_corner(t, p, tol) => return None,
None => {}
}
let dist = |q: [f64; 2]| (p[0] - q[0]).hypot(p[1] - q[1]);
let i = (0..4).min_by(|&a, &b| dist(t.quad[a]).total_cmp(&dist(t.quad[b])))?;
let unit = |to: [f64; 2]| {
let d = [to[0] - t.quad[i][0], to[1] - t.quad[i][1]];
let l = d[0].hypot(d[1]);
(l.is_finite() && l > 1e-9).then(|| [d[0] / l, d[1] / l])
};
let (a, b) = (unit(t.quad[(i + 1) % 4])?, unit(t.quad[(i + 3) % 4])?);
let s = [a[0] + b[0], a[1] + b[1]];
let l = s[0].hypot(s[1]);
(l.is_finite() && l > 1e-9).then(|| [s[0] / l, s[1] / l])
TransformSession::box_turn_direction(&t.quad, p)
}
/// The handle a drag in progress holds, else the one under document point `p`.
@@ -362,7 +437,7 @@ pub fn cursor(app: &PhotocraftApp, xf: &ViewXform, p: [f64; 2], mods: egui::Modi
return Some(CursorIcon::Default);
}
// A ⌘-drag outside the box still rotates, so ⌘ keeps the curved arrow there.
if rotate_cursor_dir(app, p).is_some() {
if rotate_dir(t, h, p).is_some() {
// The canvas draws the curved rotate arrow (`rotate_cursor_dir`), also during the drag.
return Some(CursorIcon::None);
}
@@ -382,7 +457,6 @@ pub fn cursor(app: &PhotocraftApp, xf: &ViewXform, p: [f64; 2], mods: egui::Modi
Hit::Corner(i) => crate::tool_cursor::corner_resize(&t.quad, i, xf),
Hit::Edge(i) => resize(edge_mid(i + 2), edge_mid(i)),
Hit::Pivot => CursorIcon::Crosshair,
Hit::Inside => CursorIcon::Move,
Hit::Outside => CursorIcon::Alias,
Hit::Inside | Hit::Outside => CursorIcon::Default,
})
}
@@ -79,14 +79,15 @@ fn a_click_near_rotation_handles_accepts_but_drags_and_option_pivot_do_not() {
}
#[test]
fn rotate_feedback_only_appears_just_outside_corners() {
fn rotate_feedback_covers_the_outside_zone() {
let mut t = session();
assert!(near_rotate_corner(&t, [-18.0, -18.0], 12.0));
assert!(!near_rotate_corner(&t, [50.0, 25.0], 12.0), "inside moves the box");
assert!(!near_rotate_corner(&t, [500.0, 500.0], 12.0), "far outside stays generic");
assert!(!near_rotate_corner(&t, [2.0, 2.0], 12.0), "corner handle resizes");
let rotates = |t: &TransformSession, p| near_rotate_corner(t, hit(t, p, 12.0));
assert!(rotates(&t, [-18.0, -18.0]));
assert!(!rotates(&t, [30.0, 25.0]), "inside moves the box");
assert!(rotates(&t, [500.0, 500.0]), "far outside also rotates");
assert!(!rotates(&t, [2.0, 2.0]), "corner handle resizes");
t.mode = TransformMode::Distort;
assert!(!near_rotate_corner(&t, [-18.0, -18.0], 12.0));
assert!(!rotates(&t, [-18.0, -18.0]));
}
#[test]
@@ -1771,7 +1772,7 @@ fn hovering_just_outside_a_corner_asks_for_the_rotate_cursor() {
assert_eq!(cursor(&app, &xf, tl, egui::Modifiers::NONE), Some(CursorIcon::None), "the arrow is drawn instead");
assert!(near2(rotate_cursor_dir(&app, tl), [h, h]), "{:?}", rotate_cursor_dir(&app, tl));
assert!(near2(rotate_cursor_dir(&app, br), [-h, -h]), "bends round the bottom-right corner");
assert_eq!(cursor(&app, &xf, [60.0, 60.0], egui::Modifiers::NONE), Some(CursorIcon::Move));
assert_eq!(cursor(&app, &xf, [60.0, 60.0], egui::Modifiers::NONE), Some(CursorIcon::Default));
assert_eq!(rotate_cursor_dir(&app, [60.0, 60.0]), None, "inside moves");
assert_eq!(rotate_cursor_dir(&app, [32.0, 32.0]), None, "the corner handle scales");
assert_eq!(rotate_cursor_dir(&app, [f64::NAN, 32.0]), None);
@@ -3568,9 +3569,10 @@ fn cursor_during_drag_stays_stable() {
// Release drag
crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 50.0, y: 60.0 }, command);
// Once released, dragging has ended: far outside returns the commit-on-click cursor,
// Once released, dragging has ended: far outside returns the custom rotate cursor,
// and hovering the corner without Command restores normal resize cursor.
assert_eq!(cursor(&app, &xf, [200.0, 200.0], command), Some(CursorIcon::Alias));
assert_eq!(cursor(&app, &xf, [200.0, 200.0], command), Some(CursorIcon::None));
assert!(rotate_cursor_dir(&app, [200.0, 200.0]).is_some());
assert_ne!(cursor(&app, &xf, [50.0, 60.0], egui::Modifiers::NONE), Some(CursorIcon::None));
}
@@ -0,0 +1,483 @@
use super::*;
use crate::state::{ContentAwareOptions, TransformMode, TransformSession};
use crate::transform_tool::{Hit, cursor, hit, rotate_cursor_dir};
use egui::{CursorIcon, Modifiers, pos2};
use egui_kittest::Harness;
use photocraft_doc::LayerId;
use serde_json::json;
const QUAD: [[f64; 2]; 4] = [[100.0, 100.0], [500.0, 100.0], [500.0, 300.0], [100.0, 300.0]];
fn session(quad: [[f64; 2]; 4]) -> TransformSession {
TransformSession {
session: 1,
layer: 1,
rect: [100.0, 100.0, 500.0, 300.0],
quad,
pivot: quad.iter().fold([0.0; 2], |c, p| [c[0] + p[0] / 4.0, c[1] + p[1] / 4.0]),
interpolation: "bicubic".into(),
warp: None,
selection: false,
target: None,
path: None,
made: None,
mode: TransformMode::Free,
content_aware: None,
skew_v: 0.0,
layers: Vec::new(),
}
}
fn app(quad: [[f64; 2]; 4], zoom: f32) -> PhotocraftApp {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.session.execute("file.new", serde_json::json!({"width": 32, "height": 32})).unwrap();
app.sync_views();
app.ui.views[0].zoom = zoom;
app.ui.transform = Some(session(quad));
app
}
fn view(zoom: f32) -> ViewXform {
ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(1000.0, 800.0)), zoom, center: [300.0, 200.0], flip: false, rotation: 0.0, aspect: 1.0 }
}
fn near(actual: Option<[f64; 2]>, expected: [f64; 2]) {
let actual = actual.expect("rotate direction");
assert!((actual[0] - expected[0]).hypot(actual[1] - expected[1]) < 1e-6, "{actual:?} != {expected:?}");
}
/// Screen-sized zones must survive zoom changes; the interior control rejects an all-sided edge grab area.
#[test]
fn whole_edge_and_corner_priority_table_at_100_and_200_percent() {
for zoom in [1.0, 2.0] {
let q = QUAD.map(|p| p.map(|v| v / zoom));
let t = session(q);
// Coordinates are screen pixels, so the same table must hold at both document zooms.
for (p, expected) in [
([100.0, 100.0], Hit::Corner(0)),
([105.0, 105.0], Hit::Corner(0)),
([95.0, 95.0], Hit::Corner(0)),
([500.0, 300.0], Hit::Corner(2)),
([180.0, 100.0], Hit::Edge(0)),
([180.0, 89.0], Hit::Edge(0)),
([500.0, 150.0], Hit::Edge(1)),
([511.0, 150.0], Hit::Edge(1)),
([420.0, 311.0], Hit::Edge(2)),
([89.0, 250.0], Hit::Edge(3)),
([180.0, 101.0], Hit::Inside),
([499.0, 150.0], Hit::Inside),
([180.0, 180.0], Hit::Inside),
([180.0, 88.0], Hit::Outside),
([620.0, 200.0], Hit::Outside),
] {
assert_eq!(hit(&t, p.map(|v| v / zoom), 12.0 / zoom), expected, "zoom {zoom}, screen {p:?}");
}
let tiny = session([[0.0, 0.0], [10.0, 0.0], [10.0, 10.0], [0.0, 10.0]]);
assert_eq!(TransformSession::box_hit(&tiny.quad, [1.0, -1.0], 12.0), Hit::Corner(0), "corners beat overlapping edge bands");
}
}
/// An overlapping corner zone must not steal a closer painted midpoint on a small box.
#[test]
fn small_boxes_keep_their_painted_mid_edge_handles() {
for side in [8.0, 16.0, 32.0] {
for zoom in [1.0, 2.0] {
let q = [[0.0, 0.0], [side, 0.0], [side, side], [0.0, side]].map(|p| p.map(|v| v / zoom));
let t = session(q);
for i in 0..4 {
let (a, b) = (q[i], q[(i + 1) % 4]);
let midpoint = [(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0];
assert_eq!(hit(&t, midpoint, 12.0 / zoom), Hit::Edge(i), "side {side}, zoom {zoom}, edge {i}");
assert_eq!(hit(&t, a, 12.0 / zoom), Hit::Corner(i));
}
}
}
}
/// Match the measured #11097 boundaries and ties on the top edge and one point outside it.
#[test]
fn measured_edge_corner_and_midpoint_zones_at_100_and_200_percent() {
use Hit::{Corner, Edge};
let matrix: &[(f64, &[(f64, Hit)])] = &[
(12.0, &[(3.0, Corner(0)), (4.0, Edge(0)), (5.0, Edge(0)), (6.0, Edge(0)), (9.0, Edge(0)), (10.0, Corner(1))]),
(24.0, &[(6.0, Corner(0)), (7.0, Edge(0)), (18.0, Edge(0)), (19.0, Corner(1))]),
(40.0, &[(10.0, Corner(0)), (11.0, Edge(0)), (30.0, Edge(0)), (31.0, Corner(1))]),
(100.0, &[(11.0, Corner(0)), (12.0, Edge(0))]),
];
for zoom in [1.0_f32, 2.0] {
let scale = |p: [f64; 2]| p.map(|v| v / f64::from(zoom));
let xf = view(zoom);
for &(side, samples) in matrix {
let quad = [[0.0, 0.0], [side, 0.0], [side, side], [0.0, side]].map(scale);
let mut app = app(quad, zoom);
app.ui.tool_options.transform_reference_point = false;
let t = app.ui.transform.as_ref().unwrap();
let rect = Rect::from_min_size(Pos2::ZERO, vec2(side as f32, side as f32));
for y in [0.0, -1.0] {
for &(x, expected) in samples {
let p = scale([x, y]);
let icon = match expected {
Corner(0) => CursorIcon::ResizeNwSe,
Corner(1) => CursorIcon::ResizeNeSw,
_ => CursorIcon::ResizeVertical,
};
assert_eq!(crate::transform_tool::box_hit(&app, t, p, 12.0 / f64::from(zoom)), expected, "{side}, {zoom}, {x}, {y}");
assert_eq!(cursor(&app, &xf, p, Modifiers::NONE), Some(icon));
assert_eq!(transform_controls_cursor(rect, pos2(x as f32, y as f32)), Some(icon));
}
}
}
}
}
/// Reproduce inward rounding through the view transform, with a one-pixel interior control.
#[test]
fn an_edge_survives_the_actual_f32_view_round_trip() {
for zoom in [1.0_f32, 2.0] {
let q = [[100.0, 100.00002], [500.0, 100.00002], [500.0, 300.0], [100.0, 300.0]].map(|p| p.map(|v| v / f64::from(zoom)));
let t = session(q);
let xf = view(zoom);
let p = xf.to_doc(xf.to_screen((180.0 / f64::from(zoom)) as f32, q[0][1] as f32));
let inward_rounding = (p[1] - q[0][1]) * f64::from(zoom);
assert!(inward_rounding > 0.0 && inward_rounding < 1e-3, "fixture must expose inward f32 rounding: {inward_rounding}");
assert_eq!(hit(&t, p, 12.0 / f64::from(zoom)), Hit::Edge(0));
assert_eq!(hit(&t, [p[0], q[0][1] + 1.0 / f64::from(zoom)], 12.0 / f64::from(zoom)), Hit::Inside, "a whole pixel inside still moves");
}
}
/// The same small-edge press moves the Distort edge and stretches one axis in legacy unlinked scaling.
#[test]
fn a_small_edge_keeps_distort_and_legacy_aspect_behavior() {
for mode in [TransformMode::Distort, TransformMode::Free] {
let mut app = app(QUAD, 1.0);
app.ui.transform = None;
app.ui.extras.snap = false;
app.ui.transform_unlinked = true;
app.session.edit_prefs(|p| p.general.use_legacy_free_transform = true);
app.session.execute("shape.create", serde_json::json!({"kind":"rect","rect":[8,8,16,16],"fill":"#ff0000"})).unwrap();
crate::transform_tool::begin(&mut app, &egui::Context::default()).unwrap();
app.ui.transform.as_mut().unwrap().mode = mode;
let before = app.ui.transform.as_ref().unwrap().quad;
for event in [
crate::canvas::ToolEvent::Down { x: 24.0, y: 16.0, pressure: 1.0 },
crate::canvas::ToolEvent::Move { x: 40.0, y: 20.0, pressure: 1.0 },
crate::canvas::ToolEvent::Up { x: 40.0, y: 20.0 },
] {
crate::canvas::tool_event(&mut app, event, Modifiers::NONE);
}
let q = app.ui.transform.as_ref().unwrap().quad;
if mode == TransformMode::Distort {
let mut expected = before;
for corner in [1, 2] {
expected[corner][0] += 16.0;
expected[corner][1] += 4.0;
}
assert_eq!(q, expected, "Distort moves the pressed edge and holds the opposite edge");
} else {
assert!((q[2][0] - q[0][0] - 32.0).abs() < 1e-6 && (q[2][1] - q[0][1] - 16.0).abs() < 1e-6, "a legacy edge stretches one axis: {q:?}");
}
}
}
/// At 45 degrees, corners and edges exchange cursor axis orientation at both tested zooms.
#[test]
fn turned_box_zones_and_resize_cursors_follow_the_quad() {
let turn = |p: [f64; 2]| {
let (x, y) = (p[0] - 300.0, p[1] - 200.0);
let k = std::f64::consts::FRAC_1_SQRT_2;
[300.0 + (x - y) * k, 200.0 + (x + y) * k]
};
for zoom in [1.0_f32, 2.0] {
let scale = |p: [f64; 2]| turn(p).map(|v| v / f64::from(zoom));
let q = QUAD.map(scale);
let app = app(q, zoom);
let xf = view(zoom);
let t = app.ui.transform.as_ref().unwrap();
for (p, expected, icon) in [
([500.0, 100.0], Hit::Corner(1), CursorIcon::ResizeHorizontal),
([111.0, 99.0], Hit::Corner(0), CursorIcon::ResizeVertical),
([112.0, 99.0], Hit::Edge(0), CursorIcon::ResizeNeSw),
([180.0, 95.0], Hit::Edge(0), CursorIcon::ResizeNeSw),
([505.0, 150.0], Hit::Edge(1), CursorIcon::ResizeNwSe),
([180.0, 101.0], Hit::Inside, CursorIcon::Default),
([180.0, -20.0], Hit::Outside, CursorIcon::None),
] {
assert_eq!(hit(t, scale(p), 12.0 / f64::from(zoom)), expected);
assert_eq!(cursor(&app, &xf, scale(p), Modifiers::NONE), Some(icon), "zoom {zoom}, {p:?}");
}
assert_eq!(hit(t, scale([100.0, 100.0]), 12.0 / f64::from(zoom)), Hit::Corner(0));
}
}
/// Skewed edges and reversed winding must use actual segment geometry for hits and turn direction.
#[test]
fn distorted_and_flipped_quads_use_their_edges_not_an_axis_aligned_box() {
let q = [[100.0, 100.0], [500.0, 140.0], [460.0, 300.0], [80.0, 260.0]];
for q in [q, [q[1], q[0], q[3], q[2]]] {
let t = session(q);
assert_eq!(hit(&t, [220.0, 112.0], 12.0), Hit::Edge(0));
assert_eq!(hit(&t, [220.0, 107.0], 12.0), Hit::Edge(0));
assert_eq!(hit(&t, [220.0, 113.0], 12.0), Hit::Inside);
assert_eq!(hit(&t, [220.0, 90.0], 12.0), Hit::Outside);
near(TransformSession::box_turn_direction(&q, [220.0, 90.0]), [-0.1 / 1.01_f64.sqrt(), 1.0 / 1.01_f64.sqrt()]);
}
}
/// A concave quad whose corner mean is beyond an edge rejects center-based normal orientation.
#[test]
fn concave_quad_edge_direction_uses_winding_in_both_orientations() {
let q = [[0.0, 0.0], [100.0, 0.0], [10.0, 10.0], [0.0, 100.0]];
for q in [q, [q[1], q[0], q[3], q[2]]] {
near(TransformSession::box_turn_direction(&q, [56.0, 14.0]), [-1.0 / 82.0_f64.sqrt(), -9.0 / 82.0_f64.sqrt()]);
}
}
/// Each outside position selects its inward turn orientation and hides the system cursor.
#[test]
fn outside_rotation_has_eight_edge_and_corner_orientations() {
let app = app(QUAD, 1.0);
let h = std::f64::consts::FRAC_1_SQRT_2;
for (p, direction) in [
([300.0, -20.0], [0.0, 1.0]),
([620.0, -20.0], [-h, h]),
([620.0, 200.0], [-1.0, 0.0]),
([620.0, 420.0], [-h, -h]),
([300.0, 420.0], [0.0, -1.0]),
([-20.0, 420.0], [h, -h]),
([-20.0, 200.0], [1.0, 0.0]),
([-20.0, -20.0], [h, h]),
] {
near(rotate_cursor_dir(&app, p), direction);
assert_eq!(cursor(&app, &view(1.0), p, Modifiers::NONE), Some(CursorIcon::None));
assert_eq!(cursor(&app, &view(1.0), p, Modifiers::COMMAND), Some(CursorIcon::None));
}
}
/// A hidden reference point outside the quad must leave both hover and the press free to rotate.
#[test]
fn outside_reference_point_owns_the_pointer_only_when_shown() {
let p = [80.0, 40.0];
let pivot = [76.0, 40.0];
let to = [80.0, 48.0];
for shown in [false, true] {
let mut app = app(QUAD, 1.0);
app.ui.transform = None;
app.ui.extras.snap = false;
app.session.execute("shape.create", serde_json::json!({"kind": "rect", "rect": [4, 4, 16, 16], "fill": "#ff0000"})).unwrap();
crate::transform_tool::begin(&mut app, &egui::Context::default()).unwrap();
let t = app.ui.transform.as_mut().unwrap();
t.pivot = pivot;
let quad = t.quad;
app.ui.tool_options.transform_reference_point = shown;
assert_eq!(rotate_cursor_dir(&app, p).is_some(), !shown);
let icon = if shown { CursorIcon::Crosshair } else { CursorIcon::None };
assert_eq!(cursor(&app, &view(1.0), p, Modifiers::NONE), Some(icon));
let down = crate::canvas::ToolEvent::Down { x: p[0], y: p[1], pressure: 1.0 };
crate::transform_tool::pointer(&mut app, down, Modifiers::NONE);
let drag = crate::canvas::ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 };
crate::transform_tool::pointer(&mut app, drag, Modifiers::NONE);
let t = app.ui.transform.as_ref().unwrap();
if shown {
assert_eq!(t.quad, quad, "the reference-point drag leaves the box in place");
assert_eq!(t.pivot, to);
} else {
assert_ne!(t.quad, quad, "the outside drag turns the box");
assert_eq!(t.pivot, pivot);
}
}
}
/// Compare unopened controls with an active session at identical points, including a free interior.
#[test]
fn unopened_move_controls_share_hover_but_keep_the_move_press_band() {
let app = app(QUAD, 1.0);
let r = Rect::from_min_max(pos2(100.0, 100.0), pos2(500.0, 300.0));
for (p, starts_transform) in [
(pos2(100.0, 100.0), true),
(pos2(180.0, 95.0), true),
(pos2(180.0, 89.0), true),
(pos2(505.0, 150.0), true),
(pos2(518.0, 150.0), true),
(pos2(519.0, 150.0), false),
(pos2(300.0, 70.0), false),
(pos2(180.0, 101.0), false),
(pos2(620.0, 200.0), false),
(pos2(-20.0, -20.0), false),
] {
let d = [f64::from(p.x), f64::from(p.y)];
assert_eq!(transform_controls_cursor(r, p), cursor(&app, &view(1.0), d, Modifiers::NONE), "{p:?}");
assert_eq!(transform_controls_hit(r, p), starts_transform, "{p:?}");
match (transform_controls_turn(r, p), rotate_cursor_dir(&app, d)) {
(None, None) => {}
(Some(a), Some(b)) => near(Some([f64::from(a.x) / 16.0, f64::from(a.y) / 16.0]), b),
pair => panic!("unopened/open rotation disagreement: {pair:?}"),
}
}
assert_eq!(transform_controls_cursor(r, r.center()), Some(CursorIcon::Default));
assert!(!transform_controls_hit(r, r.center()), "inside remains an ordinary Move drag");
}
fn move_controls_fixture() -> (Harness<'static, PhotocraftApp>, [LayerId; 2]) {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 400, "height": 300, "background": "transparent"})).unwrap();
let layers = [[60, 60, 80, 60], [230, 150, 40, 40]].map(|rect| {
app.run("shape.create", json!({"kind": "rect", "rect": rect, "fill": "#ff0000"})).unwrap();
app.session.active().unwrap().active_layer.unwrap()
});
app.run("layer.select", json!({"layer": layers[0].0, "mode": "replace"})).unwrap();
app.ui.tool = Tool::Move;
app.ui.tool_options.move_show_transform = true;
app.ui.tool_options.move_auto_select = true;
app.ui.tool_options.move_target = "layer".into();
app.ui.extras.snap = false;
let mut h = Harness::builder().with_size(vec2(1000.0, 800.0)).build_ui_state(
|ui, app: &mut PhotocraftApp| {
if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {
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);
(h, layers)
}
fn move_pointer(h: &mut Harness<'static, PhotocraftApp>, control: bool, kind: &str, [x, y]: [f32; 2]) {
if control {
use crate::control::{ControlRequest, Outcome};
let (request, _) = ControlRequest::new("ui.pointer", json!({"events": [{"kind": kind, "x": x, "y": y}]}));
let ctx = h.ctx.clone();
let Outcome::Done(reply) = crate::control::handle(h.state_mut(), &ctx, &request) else { panic!("expected pointer reply") };
assert_eq!(reply["ok"], true, "{reply}");
} else {
let xf = ViewXform::active(h.state()).unwrap();
let pos = xf.to_screen(x, y);
assert!(xf.rect.contains(pos));
h.hover_at(pos);
if kind != "move" {
h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: kind == "down", modifiers: Modifiers::NONE });
}
h.run_steps(2);
}
}
#[test]
fn move_controls_allow_auto_select_on_another_layer_outside_the_press_band() {
for control in [false, true] {
let (mut h, layers) = move_controls_fixture();
let at = [250.0, 170.0];
let xf = ViewXform::active(h.state()).unwrap();
let frame = transform_controls_rect(h.state(), &xf).expect("the first layer has visible transform controls");
assert!(!frame.expand(18.0).contains(xf.to_screen(at[0], at[1])));
assert_eq!(h.state().session.active().unwrap().selected_layers(), vec![layers[0]]);
let before = h.state().session.active().unwrap().doc.clone();
move_pointer(&mut h, control, "down", at);
move_pointer(&mut h, control, "up", at);
let state = h.state().session.active().unwrap();
assert!(h.state().ui.transform.is_none(), "control={control}: Auto-Select does not start Free Transform");
assert_eq!(state.selected_layers(), vec![layers[1]], "control={control}");
assert_eq!(state.doc, before);
}
}
#[test]
fn move_controls_allow_a_layer_marquee_from_empty_canvas_outside_the_press_band() {
for control in [false, true] {
let (mut h, layers) = move_controls_fixture();
let start = [190.0, 125.0];
let end = [285.0, 210.0];
let xf = ViewXform::active(h.state()).unwrap();
let frame = transform_controls_rect(h.state(), &xf).expect("the first layer has visible transform controls");
assert!(!frame.expand(18.0).contains(xf.to_screen(start[0], start[1])));
assert_eq!(h.state().session.active().unwrap().selected_layers(), vec![layers[0]]);
let before = h.state().session.active().unwrap().doc.clone();
move_pointer(&mut h, control, "down", start);
move_pointer(&mut h, control, "move", end);
assert!(h.state().layer_box.is_some(), "control={control}: the empty-canvas drag starts a layer marquee");
move_pointer(&mut h, control, "up", end);
let state = h.state().session.active().unwrap();
assert!(h.state().ui.transform.is_none(), "control={control}: the marquee does not start Free Transform");
assert!(h.state().layer_box.is_none(), "the marquee ends on release");
assert_eq!(state.selected_layers(), vec![layers[1]], "control={control}");
assert_eq!(state.doc, before);
}
}
/// A press away from midpoint handles must scale an anchored preview without creating a history edit.
#[test]
fn move_whole_edge_press_enters_scaling_at_both_zooms() {
for zoom in [1.0, 2.0] {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.session.execute("file.new", serde_json::json!({"width": 640, "height": 480})).unwrap();
app.session.execute("shape.create", serde_json::json!({"kind": "rect", "rect": [100, 100, 400, 200], "fill": "#ff0000"})).unwrap();
app.sync_views();
app.ui.views[0].zoom = zoom;
app.ui.tool = Tool::Move;
app.ui.tool_options.move_show_transform = true;
app.ui.extras.snap = false;
let xf = view(zoom);
let ctx = egui::Context::default();
let before = app.session.active().unwrap().doc.clone();
let steps = app.session.active().unwrap().history.past_len();
// Away from the top edge's midpoint and corners: the native canvas first opens the
// controls here, then forwards the same document-space press to the transform tool.
assert_eq!(begin_transform_controls_at(&mut app, &ctx, &xf, xf.to_screen(180.0, 100.0)), ControlsPress::Started);
for event in [
crate::canvas::ToolEvent::Down { x: 180.0, y: 100.0, pressure: 1.0 },
crate::canvas::ToolEvent::Move { x: 180.0, y: 90.0, pressure: 1.0 },
crate::canvas::ToolEvent::Up { x: 180.0, y: 90.0 },
] {
crate::canvas::tool_event(&mut app, event, Modifiers::SHIFT);
}
let t = app.ui.transform.as_ref().expect("a handle release retains the transform session");
assert!(t.quad[0][1] < 100.0, "the pressed edge scales");
assert!((t.quad[2][1] - 300.0).abs() < 1e-6, "the opposite edge anchors scaling instead of moving the whole box");
assert_eq!(app.session.active().unwrap().doc, before, "a preview does not commit pixels");
assert_eq!(app.session.active().unwrap().history.past_len(), steps);
}
}
/// Excluded modes retain cursor ownership, and non-finite coordinates cannot activate controls.
#[test]
fn modes_that_do_not_rotate_and_invalid_points_do_not_hide_the_pointer() {
let mut app = app(QUAD, 1.0);
for mode in [TransformMode::Distort, TransformMode::Skew] {
app.ui.transform.as_mut().unwrap().mode = mode;
assert_eq!(rotate_cursor_dir(&app, [620.0, 200.0]), None);
assert_eq!(cursor(&app, &view(1.0), [620.0, 200.0], Modifiers::NONE), Some(CursorIcon::Default));
}
app.ui.transform.as_mut().unwrap().mode = TransformMode::Free;
app.ui.transform.as_mut().unwrap().content_aware = Some(ContentAwareOptions::default());
assert_eq!(rotate_cursor_dir(&app, [620.0, 200.0]), None);
assert_eq!(cursor(&app, &view(1.0), [620.0, 200.0], Modifiers::NONE), Some(CursorIcon::Default));
app.ui.transform.as_mut().unwrap().content_aware = None;
let t = app.ui.transform.as_mut().unwrap();
t.warp = Some(photocraft_geom::warp::Warp::none(t.rect));
assert_eq!(rotate_cursor_dir(&app, [620.0, 200.0]), None);
assert_eq!(cursor(&app, &view(1.0), [620.0, 200.0], Modifiers::NONE), Some(CursorIcon::Crosshair), "Warp retains its own cursor");
app.ui.transform.as_mut().unwrap().warp = None;
assert_eq!(rotate_cursor_dir(&app, [f64::NAN, 200.0]), None);
assert_eq!(TransformSession::box_turn_direction(&[[0.0, 0.0]; 4], [20.0, 20.0]), None);
let r = Rect::from_min_max(pos2(100.0, 100.0), pos2(500.0, 300.0));
for p in [pos2(f32::NAN, 200.0), pos2(f32::INFINITY, 200.0)] {
assert_eq!(transform_controls_cursor(r, p), None, "invalid points cannot hide the pointer");
assert_eq!(transform_controls_turn(r, p), None);
assert!(!transform_controls_hit(r, p), "invalid points cannot activate the overlay");
}
}
/// Captured rotation must retain feedback after crossing into the box, independent of hover zones.
#[test]
fn rotate_drag_keeps_the_arrow_when_the_pointer_enters_the_box() {
let mut app = app(QUAD, 1.0);
app.ui.transform = None;
app.session.execute("shape.create", serde_json::json!({"kind": "rect", "rect": [4, 4, 16, 16], "fill": "#ff0000"})).unwrap();
let ctx = egui::Context::default();
crate::transform_tool::begin(&mut app, &ctx).unwrap();
crate::transform_tool::pointer(&mut app, crate::canvas::ToolEvent::Down { x: 80.0, y: 40.0, pressure: 1.0 }, Modifiers::NONE);
crate::transform_tool::pointer(&mut app, crate::canvas::ToolEvent::Move { x: 10.0, y: 10.0, pressure: 1.0 }, Modifiers::NONE);
assert!(rotate_cursor_dir(&app, [10.0, 10.0]).is_some(), "the held rotation gesture owns the arrow even inside");
assert_eq!(cursor(&app, &view(1.0), [10.0, 10.0], Modifiers::NONE), Some(CursorIcon::None));
}