Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

Snap: rotation lands on the other angle

Cameron Gilroy343b0de552ab
diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs
index 90a6a0f8f..4e7e9eefe 100644
--- a/crates/tools/src/select.rs
+++ b/crates/tools/src/select.rs
@@ -16,7 +16,7 @@ enum Drag {
Pending { start: Point, hit: bool },
Move { start: Point, origin_spread: SpreadRef, bounds0: Option<Rect>, exclude: Vec<ItemId> },
Resize { handle: usize, start: Point, from: Rect, spread: SpreadRef },
- Rotate { center: Point, start_angle: f64 },
+ Rotate { center: Point, start_angle: f64, start_rotation: Option<f64> },
Marquee { start: Point, cur: Point },
Anchor { id: u64, si: usize, ai: usize, handle: Option<&'static str>, start: Point },
}
@@ -344,7 +344,7 @@ impl Tool for SelectionTool {
&& handle_at(cx, p).is_none()
&& let Some(center) = rotate_zone(cx, p)
{
- self.drag = Drag::Rotate { center, start_angle: (p - center).atan2() };
+ self.drag = Drag::Rotate { center, start_angle: (p - center).atan2(), start_rotation: crate::snap::reference_rotation(cx) };
return vec![Action::Begin("Rotate".into())];
}
if let Some(h) = handle_at(cx, p).filter(|_| !self.direct)
@@ -525,36 +525,42 @@ impl Tool for SelectionTool {
self.drag = Drag::Marquee { start, cur: p };
vec![]
}
- Drag::Rotate { center, start_angle } => {
+ Drag::Rotate { center, start_angle, start_rotation } => {
let mut a = ((p - center).atan2() - start_angle).to_degrees();
self.guides.clear();
if ev.mods.shift {
// 45 degree steps. The rotation pass does not run while Shift is held.
a = (a / 45.0).round() * 45.0;
- } else {
- let spread = cx.selection.items.first().and_then(|id| cx.doc.find(*id)).map(|loc| loc.spread).unwrap_or(SpreadRef::Doc(0));
- let exclude = cx.selection.items.clone();
- // The rect is unused by the angle pass. It only has to be finite.
- let hit = crate::snap::snap(
- cx,
- SnapRequest {
- spread,
- gesture: Gesture::Rotate,
- rect: Rect::new(0.0, 0.0, 1.0, 1.0),
- x_edges: [false, false, false],
- y_edges: [false, false, false],
- exclude: &exclude,
- copying: false,
- lengths: [None, None],
- angle: Some(-a),
- radius: (p - center).hypot(),
- pointer: cx.layout.to_spread(spread, p),
- },
- );
- if let Some(snapped) = hit.angle {
- a = -snapped;
+ } else if let Some(start) = start_rotation {
+ let raw = -a;
+ if let Some(resulting) = crate::snap::folded_rotation(start + raw) {
+ let spread =
+ cx.selection.items.first().and_then(|id| cx.doc.find(*id)).map(|loc| loc.spread).unwrap_or(SpreadRef::Doc(0));
+ let exclude = cx.selection.items.clone();
+ // The rect is unused by the angle pass. It only has to be finite.
+ let hit = crate::snap::snap(
+ cx,
+ SnapRequest {
+ spread,
+ gesture: Gesture::Rotate,
+ rect: Rect::new(0.0, 0.0, 1.0, 1.0),
+ x_edges: [false, false, false],
+ y_edges: [false, false, false],
+ exclude: &exclude,
+ copying: false,
+ lengths: [None, None],
+ angle: Some(resulting),
+ radius: (p - center).hypot(),
+ pointer: cx.layout.to_spread(spread, p),
+ },
+ );
+ if let Some(snapped) = hit.angle
+ && let Some(delta) = crate::snap::rotation_command_delta(start, snapped, raw)
+ {
+ a = -delta;
+ }
+ self.guides = hit.guides;
}
- self.guides = hit.guides;
}
// Screen y points down: a positive screen angle is clockwise.
vec![Action::Preview("transform.rotate".into(), json!({"angle": -a}))]
diff --git a/crates/tools/src/snap.rs b/crates/tools/src/snap.rs
index 8168196c8..6ab2f8d47 100644
--- a/crates/tools/src/snap.rs
+++ b/crates/tools/src/snap.rs
@@ -329,6 +329,51 @@ fn own_rotation(item: &Item) -> Option<f64> {
rotation.is_finite().then_some(rotation)
}
+/// Decompose rotation of the first selected item, captured before a preview changes `xf`.
+/// None when nothing is selected.
+pub(crate) fn reference_rotation(cx: &ToolContext) -> Option<f64> {
+ let id = *cx.selection.items.first()?;
+ own_rotation(cx.doc.item(id)?)
+}
+
+/// Degrees folded into the range `decompose` reports, `(-180, 180]`.
+pub(crate) fn folded_rotation(deg: f64) -> Option<f64> {
+ if !deg.is_finite() {
+ return None;
+ }
+ let mut d = deg.rem_euclid(360.0);
+ if !d.is_finite() {
+ return None;
+ }
+ if d > 180.0 {
+ d -= 360.0;
+ }
+ if d <= -180.0 + 1e-9 {
+ d = 180.0;
+ }
+ d.is_finite().then_some(d)
+}
+
+/// Delta `transform.rotate` should apply so the reference lands on `snapped`.
+///
+/// `transform.rotate` composes, so the command is `snapped - start`, not `snapped`.
+/// Whole turns are added so the result stays nearest the raw command delta.
+pub(crate) fn rotation_command_delta(start: f64, snapped: f64, raw: f64) -> Option<f64> {
+ if !start.is_finite() || !snapped.is_finite() || !raw.is_finite() {
+ return None;
+ }
+ let base = snapped - start;
+ if !base.is_finite() {
+ return None;
+ }
+ let turns = ((raw - base) / 360.0).round();
+ if !turns.is_finite() {
+ return None;
+ }
+ let delta = base + turns * 360.0;
+ delta.is_finite().then_some(delta)
+}
+
/// Smallest absolute difference in degrees, folded into `0..=180`.
fn angular_distance(a: f64, b: f64) -> f64 {
let d = (a - b).rem_euclid(360.0);
diff --git a/crates/tools/src/tests.rs b/crates/tools/src/tests.rs
index dcbf815d1..01edf808a 100644
--- a/crates/tools/src/tests.rs
+++ b/crates/tools/src/tests.rs
@@ -481,3 +481,43 @@ fn dimension_guide_lies_on_the_committed_side() {
}
assert!(problems.is_empty(), "{}", problems.join(" | "));
}
+
+#[test]
+fn rotation_drag_lands_on_the_other_angle() {
+ // Reference starts at 10. A raw command delta of 18 would show 28.
+ // The other item is at 30, so the composed preview delta is 20, not 30.
+ let mut doc = Document::new(&NewDocument::default());
+ let moving = add_rotated(&mut doc, Rect::new(100.0, 100.0, 180.0, 140.0), 10.0);
+ add_rotated(&mut doc, Rect::new(300.0, 80.0, 380.0, 140.0), 30.0);
+ let sel = Selection::items(vec![moving]);
+ let cache = Cache::new();
+ let layout = CanvasLayout::new(&doc, false);
+ let cx = dims_ctx(&doc, &sel, &cache, &layout, false);
+ let center = cx.selection_bounds().unwrap().center();
+ let radius = 80.0;
+ let down = Point::new(center.x + radius, center.y);
+ let aim = (-18.0_f64).to_radians();
+ let drag_at = Point::new(center.x + radius * aim.cos(), center.y + radius * aim.sin());
+ let raw_command = -((drag_at - center).atan2() - (down - center).atan2()).to_degrees();
+ assert!((raw_command - 18.0).abs() < 1e-6, "unsnapped command {raw_command}");
+ let mut t = create("rotate");
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, down.x, down.y));
+ let actions = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, drag_at.x, drag_at.y));
+ let angle = match &actions[..] {
+ [Action::Preview(cmd, p)] => {
+ assert_eq!(cmd, "transform.rotate");
+ p["angle"].as_f64().unwrap()
+ }
+ other => panic!("{other:?}"),
+ };
+ assert!((angle - 20.0).abs() < 1e-4, "preview angle {angle}, want 20");
+}
+
+fn add_rotated(doc: &mut Document, rect: Rect, degrees: f64) -> ItemId {
+ let layer = doc.default_layer();
+ let id = ItemId(doc.alloc());
+ let mut item = Item::new(id, layer, Shape::Rectangle, shapes::rectangle(rect));
+ item.xf = designcraft_geom::Affine::rotate((-degrees).to_radians());
+ doc.insert_item(SpreadRef::Doc(0), item, None).unwrap();
+ id
+}
diff --git a/crates/tools/src/xform.rs b/crates/tools/src/xform.rs
index 3b4c66dc5..fbb1df9b8 100644
--- a/crates/tools/src/xform.rs
+++ b/crates/tools/src/xform.rs
@@ -12,11 +12,13 @@ pub struct XformTool {
id: &'static str,
drag: Option<(Point, Point)>,
guides: Vec<Overlay>,
+ /// First selected item's rotation at pointer down. Rotate only. Later samples see the preview.
+ start_rotation: Option<f64>,
}
impl XformTool {
pub fn new(id: &'static str) -> Self {
- Self { id, drag: None, guides: Vec::new() }
+ Self { id, drag: None, guides: Vec::new(), start_rotation: None }
}
}
@@ -59,7 +61,11 @@ impl Tool for XformTool {
match ev.kind {
PointerKind::Down => {
self.guides.clear();
+ self.start_rotation = None;
let Some(b) = cx.selection_bounds() else { return vec![] };
+ if self.id == "rotate" {
+ self.start_rotation = crate::snap::reference_rotation(cx);
+ }
self.drag = Some((b.center(), ev.pos));
vec![Action::Begin(match self.id {
"rotate" => "Rotate".into(),
@@ -77,31 +83,36 @@ impl Tool for XformTool {
if ev.mods.shift {
// 45 degree steps. The rotation pass does not run while Shift is held.
a = (a / 45.0).round() * 45.0;
- } else {
- let spread =
- cx.selection.items.first().and_then(|id| cx.doc.find(*id)).map(|loc| loc.spread).unwrap_or(SpreadRef::Doc(0));
- let exclude = cx.selection.items.clone();
- // The rect is unused by the angle pass. It only has to be finite.
- let hit = crate::snap::snap(
- cx,
- SnapRequest {
- spread,
- gesture: Gesture::Rotate,
- rect: Rect::new(0.0, 0.0, 1.0, 1.0),
- x_edges: [false, false, false],
- y_edges: [false, false, false],
- exclude: &exclude,
- copying: false,
- lengths: [None, None],
- angle: Some(-a),
- radius: (ev.pos - c).hypot(),
- pointer: cx.layout.to_spread(spread, ev.pos),
- },
- );
- if let Some(snapped) = hit.angle {
- a = -snapped;
+ } else if let Some(start) = self.start_rotation {
+ let raw = -a;
+ if let Some(resulting) = crate::snap::folded_rotation(start + raw) {
+ let spread =
+ cx.selection.items.first().and_then(|id| cx.doc.find(*id)).map(|loc| loc.spread).unwrap_or(SpreadRef::Doc(0));
+ let exclude = cx.selection.items.clone();
+ // The rect is unused by the angle pass. It only has to be finite.
+ let hit = crate::snap::snap(
+ cx,
+ SnapRequest {
+ spread,
+ gesture: Gesture::Rotate,
+ rect: Rect::new(0.0, 0.0, 1.0, 1.0),
+ x_edges: [false, false, false],
+ y_edges: [false, false, false],
+ exclude: &exclude,
+ copying: false,
+ lengths: [None, None],
+ angle: Some(resulting),
+ radius: (ev.pos - c).hypot(),
+ pointer: cx.layout.to_spread(spread, ev.pos),
+ },
+ );
+ if let Some(snapped) = hit.angle
+ && let Some(delta) = crate::snap::rotation_command_delta(start, snapped, raw)
+ {
+ a = -delta;
+ }
+ self.guides = hit.guides;
}
- self.guides = hit.guides;
}
vec![Action::Preview("transform.rotate".into(), json!({"angle": -a}))]
}
@@ -196,6 +207,7 @@ impl Tool for XformTool {
}
PointerKind::Up => {
self.guides.clear();
+ self.start_rotation = None;
if self.drag.take().is_some() { vec![Action::Commit] } else { vec![] }
}
_ => vec![],