ProCraft for Android: An Android native painting app written in Rust
Rust
feat(quickshape): drag an edited shape's outline to turn it, elsewhere to move it
Josh52ba2d0da557
diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/CanvasSurfaceView.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/CanvasSurfaceView.ktindex a962dc8..0ab56f1 100644--- a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/CanvasSurfaceView.kt+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/CanvasSurfaceView.kt@@ -45,7 +45,7 @@ class CanvasSurfaceView(context: Context, private val vm: CanvasViewModel) : Sur// IDLE: a finger that doesn't paint, waiting for a hold or more fingers; HOVER: fingers// setting the brush while the pen hovers- private enum class Mode { NONE, PEN, FINGER, IDLE, GESTURE, PICK, TRANSFORM, SELECT, ADJUST, PUCK, SHAPE, HOVER, TURN, POUR, OPACITY, RECOLOR }+ private enum class Mode { NONE, PEN, FINGER, IDLE, GESTURE, PICK, TRANSFORM, SELECT, ADJUST, PUCK, SHAPE, SHAPE_PIN, SHAPE_MOVE, HOVER, TURN, POUR, OPACITY, RECOLOR }/** The pen is hovering over the canvas. */private var penHovering = false@@ -540,6 +540,17 @@ class CanvasSurfaceView(context: Context, private val vm: CanvasViewModel) : SurshapeHandle = handlereturn true}+ // while it is edited, a drag on its outline turns and resizes it, one elsewhere moves+ // it; a tap ends the editing+ if (vm.quickShape != null && vm.quickShapeEditing) {+ strokePointer = e.getPointerId(0)+ tapStart = e.eventTime+ lastX = e.x+ lastY = e.y+ mode = if (vm.quickShapeNearEdge(Offset(e.x, e.y))) Mode.SHAPE_PIN else Mode.SHAPE_MOVE+ if (mode == Mode.SHAPE_PIN) vm.quickShapePin(Offset(e.x, e.y), begin = true)+ return true+ }vm.endQuickShape()val kind = kindOf(e, 0)val pen = kind == PointerKind.STYLUS || kind == PointerKind.STYLUS_ERASER@@ -616,7 +627,7 @@ class CanvasSurfaceView(context: Context, private val vm: CanvasViewModel) : SurremoveCallbacks(holdToPick)removeCallbacks(quickShapeHold)// a finger down while the stroke is held as a snapped shape snaps it, until lifted- if ((mode == Mode.PEN || mode == Mode.FINGER) && vm.quickShape != null) {+ if ((mode == Mode.PEN || mode == Mode.FINGER || mode == Mode.SHAPE_PIN) && vm.quickShape != null) {if (e.getToolType(e.actionIndex) == MotionEvent.TOOL_TYPE_FINGER) vm.quickShapeFinger(true)return true}@@ -675,6 +686,15 @@ class CanvasSurfaceView(context: Context, private val vm: CanvasViewModel) : Sur}Mode.PUCK -> vm.moveClonePuck(Offset(e.x, e.y) - puckGrab)Mode.SHAPE -> vm.moveQuickShapeHandle(shapeHandle, Offset(e.x, e.y))+ Mode.SHAPE_PIN, Mode.SHAPE_MOVE -> {+ val i = e.findPointerIndex(strokePointer)+ if (i >= 0) {+ val p = Offset(e.getX(i), e.getY(i))+ if (mode == Mode.SHAPE_PIN) vm.quickShapePin(p, begin = false) else vm.quickShapeMove(Offset(lastX, lastY), p)+ lastX = p.x+ lastY = p.y+ }+ }Mode.GESTURE -> if (fingers >= 3) scrub(e) else moveGesture(e, s)Mode.SELECT -> select(e, done = false)Mode.POUR -> pour(e, done = false)@@ -726,7 +746,7 @@ class CanvasSurfaceView(context: Context, private val vm: CanvasViewModel) : Surfingers = e.pointerCount - 1if (mode == Mode.GESTURE) followFingers(e, exclude = e.actionIndex)// the last finger other than the stroke's lifted from a held snapped shape- if ((mode == Mode.PEN || mode == Mode.FINGER) && vm.quickShape != null && e.getPointerId(e.actionIndex) != strokePointer) {+ if ((mode == Mode.PEN || mode == Mode.FINGER || mode == Mode.SHAPE_PIN) && vm.quickShape != null && e.getPointerId(e.actionIndex) != strokePointer) {val strokeDown = e.findPointerIndex(strokePointer).let { it >= 0 && it != e.actionIndex }if (e.pointerCount - 1 - (if (strokeDown) 1 else 0) == 0) vm.quickShapeFinger(false)}@@ -760,6 +780,9 @@ class CanvasSurfaceView(context: Context, private val vm: CanvasViewModel) : Sur}Mode.PICK -> vm.finishPick()Mode.PUCK, Mode.SHAPE, Mode.IDLE, Mode.HOVER, Mode.TURN -> Unit+ Mode.SHAPE_PIN -> vm.quickShapeUnpin()+ // a tap ends the editing; a drag only moved it+ Mode.SHAPE_MOVE -> if (e.eventTime - tapStart <= TAP_MS && hypot(e.x - downX, e.y - downY) <= tapSlop) vm.endQuickShape()Mode.SELECT -> select(e, done = true)Mode.POUR -> pour(e, done = true)Mode.RECOLOR -> if (!recolorDragging) vm.recolorTap(Offset(e.x, e.y))diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/CanvasViewModel.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/CanvasViewModel.ktindex 3d62adc..65d65dd 100644--- a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/CanvasViewModel.kt+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/CanvasViewModel.kt@@ -2595,7 +2595,24 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {val h = quickShape?.handles ?: return nullif (!quickShapeEditing) return nullreturn (0 until h.size / 2).minByOrNull { (Offset(h[it * 2], h[it * 2 + 1]) - p).getDistance() }- ?.takeIf { (Offset(h[it * 2], h[it * 2 + 1]) - p).getDistance() <= QUICKSHAPE_REACH_DP * density }+ ?.takeIf { (Offset(h[it * 2], h[it * 2 + 1]) - p).getDistance() <= QUICKSHAPE_GRAB_DP * density }+ }++ /** Whether a drag from [p] on the edited shape turns and resizes it (on its outline) rather than moving it. */+ fun quickShapeNearEdge(p: Offset): Boolean = session?.quickshapeNearEdge(p.x, p.y, QUICKSHAPE_GRAB_DP * density) == true++ /** A drag on the edited shape's outline begins at [p] ([begin]) or goes on to it. */+ fun quickShapePin(p: Offset, begin: Boolean) {+ quickShape = session?.quickshapePin(p.x, p.y, begin) ?: quickShape+ }++ fun quickShapeUnpin() {+ quickShape = session?.quickshapeUnpin() ?: quickShape+ }++ /** The edited shape dragged from [from] to [to]. */+ fun quickShapeMove(from: Offset, to: Offset) {+ quickShape = session?.quickshapeMove(from.x, from.y, to.x, to.y) ?: quickShape}/** Keeps the snapped shape as drawn. */@@ -6071,6 +6088,9 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {const val QUICKSHAPE_MS = 650Lconst val QUICKSHAPE_STILL_DP = 6fconst val QUICKSHAPE_REACH_DP = 30f++ /** A snapped shape being edited: a handle within this takes a drag, and its outline within this. */+ const val QUICKSHAPE_GRAB_DP = 22f/** The drawing pad's colours (0xRRGGBB), the white one, and its background's grey. */val PAD_COLORS = listOf(0xF83045, 0xFCBD03, 0x85D921, 0x2BB5E6, 0x4956A5, 0xDA3D92, 0xFFFFFF, 0x000000)const val PAD_WHITE = 6diff --git a/apps/procraft-android/src/quickshape.rs b/apps/procraft-android/src/quickshape.rsindex 8739032..274e181 100644--- a/apps/procraft-android/src/quickshape.rs+++ b/apps/procraft-android/src/quickshape.rs@@ -342,6 +342,51 @@ impl CanvasSession {st.shape_info()}+ /// Whether window point (`x`, `y`) is within `reach` (window pixels) of the snapped shape's+ /// outline, where a drag turns and resizes it while it is edited.+ pub fn quickshape_near_edge(&self, x: f32, y: f32, reach: f32) -> bool {+ let st = self.shared.lock();+ let (Some(edit), Some(view)) = (st.shape.as_ref(), st.view) else { return false };+ let Some(p) = view.screen_to_canvas(Vec2::new(x, y)) else { return false };+ edit.shape.turns_from_edge() && edit.shape.edge_distance(p) * view.zoom() <= reach+ }++ /// A drag on the edited shape's outline, from window point (`x`, `y`) (`begin`) or on to it:+ /// the shape turns and resizes about its pivot as a held pen turns it.+ pub fn quickshape_pin(&self, x: f32, y: f32, begin: bool) -> Option<QuickShapeInfo> {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let at = st.view?.screen_to_canvas(Vec2::new(x, y))?;+ let edit = st.shape.as_mut()?;+ if begin {+ edit.held = Some(Held { snapped: edit.shape.clone(), from: at, at, finger: false });+ } else if st.follow_shape(at) {+ self.shared.frame(st);+ }+ st.shape_info()+ }++ /// The drag on the outline (or the pen) let go: the shape stays as it shows.+ pub fn quickshape_unpin(&self) -> Option<QuickShapeInfo> {+ let mut guard = self.shared.lock();+ guard.let_go_shape();+ guard.shape_info()+ }++ /// The edited shape dragged from window point (`fx`, `fy`) to (`tx`, `ty`): it moves along.+ pub fn quickshape_move(&self, fx: f32, fy: f32, tx: f32, ty: f32) -> Option<QuickShapeInfo> {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let view = st.view?;+ let by = view.screen_to_canvas(Vec2::new(tx, ty))? - view.screen_to_canvas(Vec2::new(fx, fy))?;+ let edit = st.shape.as_mut()?;+ edit.held = None;+ edit.shape = edit.shape.translated(by);+ st.draw_shape();+ self.shared.frame(st);+ st.shape_info()+ }+/// Keeps the snapped shape as drawn.pub fn quickshape_done(&self) {let mut guard = self.shared.lock();diff --git a/apps/procraft-android/src/tests.rs b/apps/procraft-android/src/tests.rsindex 922ca4a..60e58dc 100644--- a/apps/procraft-android/src/tests.rs+++ b/apps/procraft-android/src/tests.rs@@ -1004,6 +1004,40 @@ fn a_held_stroke_snaps_to_a_shape_and_is_edited() {s.stroke_end(vec![]);}+#[test]+fn an_edited_shape_is_turned_by_its_outline_and_moved_elsewhere() {+ use crate::quickshape::QuickShapeKind;+ let Some(s) = session(200, 200) else { return };+ s.set_brush_size(0.2);+ let pts: Vec<PenSample> = (0..=60)+ .map(|i| {+ let t = i as f32 / 60.0 * std::f32::consts::TAU;+ sample(100.0 + 60.0 * t.cos(), 100.0 + 40.0 * t.sin(), f64::from(i) * 8.0)+ })+ .collect();+ s.stroke_begin(PointerKind::Finger, pts[..1].to_vec());+ s.stroke_add(pts[1..].to_vec());+ assert_eq!(s.quickshape_hold().unwrap().kind, QuickShapeKind::Ellipse);+ s.stroke_end(vec![]);+ let before = s.quickshape_info().unwrap();+ // on its outline (the first axis end), not in its middle+ let (ex, ey) = (before.handles[0], before.handles[1]);+ assert!(s.quickshape_near_edge(ex, ey - 5.0, 22.0));+ assert!(!s.quickshape_near_edge(100.0, 100.0, 22.0));+ // the outline dragged half as far out again: half as big again about its centre+ s.quickshape_pin(ex, ey, true);+ let grown = s.quickshape_pin(100.0 + (ex - 100.0) * 1.5, 100.0 + (ey - 100.0) * 1.5, false).unwrap();+ assert!((grown.handles[0] - (100.0 + (ex - 100.0) * 1.5)).abs() < 1.0, "{:?}", grown.handles);+ s.quickshape_unpin();+ // dragged elsewhere: it moves along+ let moved = s.quickshape_move(100.0, 100.0, 110.0, 95.0).unwrap();+ for (i, (a, b)) in grown.handles.iter().zip(&moved.handles).enumerate() {+ let d = if i % 2 == 0 { 10.0 } else { -5.0 };+ assert!((b - a - d).abs() < 0.5, "{i}: {a} -> {b}");+ }+ s.quickshape_done();+}+#[test]fn a_shape_still_held_follows_the_pen_and_a_finger_snaps_it() {use crate::quickshape::QuickShapeKind;diff --git a/crates/engine/src/quickshape.rs b/crates/engine/src/quickshape.rsindex 056d50a..fca6d2b 100644--- a/crates/engine/src/quickshape.rs+++ b/crates/engine/src/quickshape.rs@@ -153,6 +153,28 @@ impl Shape {}}+ /// How far `p` is from the shape's outline.+ pub fn edge_distance(&self, p: Vec2) -> f32 {+ self.outline()+ .windows(2)+ .filter_map(|w| match w {+ [a, b] => Some(distance_to_segment(p, *a, *b)),+ _ => None,+ })+ .fold(f32::INFINITY, f32::min)+ }++ /// Whether a drag on its outline turns and resizes it while it is edited; lines and+ /// polylines are only moved.+ pub fn turns_from_edge(&self) -> bool {+ !matches!(self.kind, ShapeKind::Line | ShapeKind::Polyline)+ }++ /// The shape moved by `by`.+ pub fn translated(&self, by: Vec2) -> Shape {+ Shape { kind: self.kind, nodes: self.nodes.iter().map(|&p| p + by).collect() }+ }+/// What a shape still held turns and grows about: an open shape's start, a closed shape's/// centre.pub fn pivot(&self) -> Vec2 {@@ -827,6 +849,21 @@ mod tests {assert_eq!(tri.moved_with(tri.pivot(), tri.pivot(), Vec2::new(5.0, 5.0)), tri);}+ #[test]+ fn shapes_are_moved_and_found_by_their_outline() {+ let rect = Shape {+ kind: ShapeKind::Rectangle,+ nodes: vec![Vec2::new(0.0, 0.0), Vec2::new(100.0, 0.0), Vec2::new(100.0, 50.0), Vec2::new(0.0, 50.0)],+ };+ assert!((rect.edge_distance(Vec2::new(50.0, 10.0)) - 10.0).abs() < 1e-3);+ // the closing side counts too+ assert!((rect.edge_distance(Vec2::new(-4.0, 25.0)) - 4.0).abs() < 1e-3);+ let moved = rect.translated(Vec2::new(5.0, -5.0));+ assert_eq!(moved.nodes[2], Vec2::new(105.0, 45.0));+ assert!(rect.turns_from_edge());+ assert!(!Shape { kind: ShapeKind::Line, nodes: vec![Vec2::ZERO, Vec2::new(1.0, 0.0)] }.turns_from_edge());+ }+#[test]fn a_finger_snaps_a_held_shape() {// near round: a circle of the mean radius, still starting where the ellipse did