Skip to content

ProCraft for Android: An Android native painting app written in Rust

Rust

fix(quickshape): a finger snaps a held shape only while it is down

Joshf5b30114a9a6
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.kt
index 4495652..a962dc8 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
@@ -615,9 +615,9 @@ class CanvasSurfaceView(context: Context, private val vm: CanvasViewModel) : Sur
}
removeCallbacks(holdToPick)
removeCallbacks(quickShapeHold)
- // a finger put down while the stroke is held as a snapped shape makes it perfect
+ // 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 (e.getToolType(e.actionIndex) == MotionEvent.TOOL_TYPE_FINGER) vm.quickShapePerfect()
+ if (e.getToolType(e.actionIndex) == MotionEvent.TOOL_TYPE_FINGER) vm.quickShapeFinger(true)
return true
}
if (mode == Mode.PEN || mode == Mode.PICK) return true
@@ -725,6 +725,11 @@ class CanvasSurfaceView(context: Context, private val vm: CanvasViewModel) : Sur
MotionEvent.ACTION_POINTER_UP -> {
fingers = e.pointerCount - 1
if (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) {
+ val strokeDown = e.findPointerIndex(strokePointer).let { it >= 0 && it != e.actionIndex }
+ if (e.pointerCount - 1 - (if (strokeDown) 1 else 0) == 0) vm.quickShapeFinger(false)
+ }
}
MotionEvent.ACTION_UP -> {
vm.showCursor(null)
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.kt
index 0bd5ab8..3d62adc 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
@@ -2577,9 +2577,9 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {
refreshFlags()
}
- /** A finger put down while the pen still holds the snapped shape makes it perfect. */
- fun quickShapePerfect() {
- quickShape = session?.quickshapePerfect() ?: quickShape
+ /** A finger down ([down]) or lifted while the pen still holds the snapped shape. */
+ fun quickShapeFinger(down: Boolean) {
+ quickShape = session?.quickshapeFinger(down) ?: quickShape
}
fun chooseQuickShape(kind: QuickShapeKind) {
diff --git a/apps/procraft-android/src/quickshape.rs b/apps/procraft-android/src/quickshape.rs
index 43fff4e..8739032 100644
--- a/apps/procraft-android/src/quickshape.rs
+++ b/apps/procraft-android/src/quickshape.rs
@@ -76,11 +76,20 @@ pub(crate) struct ShapeEdit {
/// The stroke as drawn (canvas points), which other kinds are fitted to.
drawn: Vec<Vec2>,
pressure: f32,
- /// While the pen that drew it is still down: the shape as it snapped and where the pen was
- /// then (canvas point), which the pen's moves turn and resize it from.
- held: Option<(Shape, Vec2)>,
- /// A finger was put down while it was held: it is shown made perfect.
- perfect: bool,
+ /// While the pen that drew it is still down.
+ held: Option<Held>,
+}
+
+/// A snapped shape whose pen is still down: shown as worked out afresh from the shape as it
+/// snapped, at each move.
+struct Held {
+ snapped: Shape,
+ /// Where the pen was when it snapped, and where it is (canvas points): the shape turns and
+ /// grows about its pivot as the one goes to the other.
+ from: Vec2,
+ at: Vec2,
+ /// A finger is down: the kind as [`Shape::snapped`] makes it, the turn in whole steps.
+ finger: bool,
}
/// A stroke as it began (and, once kept, what it drew), so that QuickShape can redraw it as a
@@ -135,11 +144,19 @@ impl State {
/// The pen still down after a snap moved to `to` (canvas point): the shape turns and grows
/// with it, about its start (open shapes) or centre (closed ones). Whether it changed.
pub(crate) fn follow_shape(&mut self, to: Vec2) -> bool {
+ let Some(held) = self.shape.as_mut().and_then(|e| e.held.as_mut()) else { return false };
+ held.at = to;
+ self.reshape_held()
+ }
+
+ /// Works the held shape out again from the shape as it snapped. Whether it changed.
+ fn reshape_held(&mut self) -> bool {
let Some(edit) = self.shape.as_mut() else { return false };
- let Some((snapped, from)) = edit.held.as_ref() else { return false };
- let mut shape = snapped.moved_with(snapped.pivot(), *from, to);
- if edit.perfect {
- shape = shape.perfected();
+ let Some(held) = edit.held.as_ref() else { return false };
+ let base = if held.finger { held.snapped.snapped(&edit.drawn) } else { held.snapped.clone() };
+ let mut shape = base.moved_with(base.pivot(), held.from, held.at);
+ if held.finger {
+ shape = shape.turned_to_step();
}
if shape == edit.shape {
return false;
@@ -234,15 +251,9 @@ impl CanvasSession {
let found = recognise(&st.drawn);
let first = found.first()?.clone();
let choices = found.iter().map(|s| s.kind).collect();
- let held = st.drawn.last().map(|&at| (first.clone(), at));
- st.shape = Some(ShapeEdit {
- shape: first,
- choices,
- drawn: st.drawn.clone(),
- pressure: st.mean_pressure(),
- held,
- perfect: false,
- });
+ let held = st.drawn.last().map(|&at| Held { snapped: first.clone(), from: at, at, finger: false });
+ st.shape =
+ Some(ShapeEdit { shape: first, choices, drawn: st.drawn.clone(), pressure: st.mean_pressure(), held });
st.began = None;
st.draw_shape();
self.shared.frame(st);
@@ -270,14 +281,7 @@ impl CanvasSession {
canvas.undo();
canvas.begin_stroke(last.layer, last.style);
st.stroke = Some(StrokeBuilder::with_seed(last.brush, last.diameter, last.pointer.into(), 0x5eed_1234));
- st.shape = Some(ShapeEdit {
- shape: first,
- choices,
- drawn: last.drawn,
- pressure: last.pressure,
- held: None,
- perfect: false,
- });
+ st.shape = Some(ShapeEdit { shape: first, choices, drawn: last.drawn, pressure: last.pressure, held: None });
st.draw_shape();
self.shared.frame(st);
st.shape_info()
@@ -319,16 +323,20 @@ impl CanvasSession {
st.shape_info()
}
- /// A finger put down while the pen still holds the snapped shape: it is made perfect (see
- /// [`Shape::perfected`]) and stays so as the pen moves on.
- pub fn quickshape_perfect(&self) -> Option<QuickShapeInfo> {
+ /// A finger put down (`down`) or lifted while the pen still holds the snapped shape: while
+ /// it is down the shape is shown as [`Shape::snapped`] makes it, its turn in whole steps;
+ /// lifted, as before. Whatever shows when the pen lifts is kept.
+ pub fn quickshape_finger(&self, down: bool) -> Option<QuickShapeInfo> {
let mut guard = self.shared.lock();
let st = &mut *guard;
- let edit = st.shape.as_mut()?;
- if edit.held.is_some() && !edit.perfect {
- edit.perfect = true;
- edit.shape = edit.shape.perfected();
- st.draw_shape();
+ let changed = match st.shape.as_mut()?.held.as_mut() {
+ Some(held) if held.finger != down => {
+ held.finger = down;
+ true
+ }
+ _ => false,
+ };
+ if changed && st.reshape_held() {
self.shared.frame(st);
}
st.shape_info()
diff --git a/apps/procraft-android/src/tests.rs b/apps/procraft-android/src/tests.rs
index 56017aa..922ca4a 100644
--- a/apps/procraft-android/src/tests.rs
+++ b/apps/procraft-android/src/tests.rs
@@ -1005,10 +1005,13 @@ fn a_held_stroke_snaps_to_a_shape_and_is_edited() {
}
#[test]
-fn a_shape_still_held_follows_the_pen_and_a_finger_makes_it_perfect() {
+fn a_shape_still_held_follows_the_pen_and_a_finger_snaps_it() {
use crate::quickshape::QuickShapeKind;
let Some(s) = session(200, 200) else { return };
s.set_brush_size(0.2);
+ let angle = |i: &crate::quickshape::QuickShapeInfo| {
+ (i.handles[3] - i.handles[1]).atan2(i.handles[2] - i.handles[0]).to_degrees()
+ };
// a line, held at its end
let pts: Vec<PenSample> = (0..=40).map(|i| sample(20.0 + i as f32 * 2.0, 100.0, f64::from(i) * 8.0)).collect();
s.stroke_begin(PointerKind::Finger, pts[..1].to_vec());
@@ -1020,22 +1023,23 @@ fn a_shape_still_held_follows_the_pen_and_a_finger_makes_it_perfect() {
let moved = s.quickshape_info().unwrap();
assert!((moved.handles[2] - 80.0).abs() < 1.0 && (moved.handles[3] - 160.0).abs() < 1.0, "{:?}", moved.handles);
assert!((moved.handles[0] - 20.0).abs() < 1.0 && (moved.handles[1] - 100.0).abs() < 1.0);
- // a finger: its angle in 15 degree steps from then on (here 45 degrees, nearest to 45)
- let stepped = s.quickshape_perfect().unwrap();
- let (dx, dy) = (stepped.handles[2] - stepped.handles[0], stepped.handles[3] - stepped.handles[1]);
- assert!((dy.atan2(dx).to_degrees() - 45.0).abs() < 0.5, "{:?}", stepped.handles);
+ // a finger down: the angle in 15 degree steps (45 already is one)
+ assert!((angle(&s.quickshape_finger(true).unwrap()) - 45.0).abs() < 0.5);
s.stroke_add(vec![sample(150.0, 130.0, 450.0)]);
- let on = s.quickshape_info().unwrap();
- let (dx, dy) = (on.handles[2] - on.handles[0], on.handles[3] - on.handles[1]);
- assert!((dy.atan2(dx).to_degrees() - 15.0).abs() < 0.5, "{:?}", on.handles);
- s.stroke_end(vec![]);
- // let go, it stays put
+ assert!((angle(&s.quickshape_info().unwrap()) - 15.0).abs() < 0.5);
+ // lifted: back to following the pen freely (about 13 degrees)
+ let free = s.quickshape_finger(false).unwrap();
+ assert!((free.handles[2] - 150.0).abs() < 1.0 && (free.handles[3] - 130.0).abs() < 1.0, "{:?}", free.handles);
+ // down again, and the pen lifts first: the stepped line is kept
+ let on = s.quickshape_finger(true).unwrap();
+ assert!((angle(&on) - 15.0).abs() < 0.5);
+ s.stroke_end(vec![]);
+ // let go, it stays put, fingers or not
s.stroke_add(vec![sample(30.0, 30.0, 500.0)]);
assert_eq!(s.quickshape_info().unwrap().handles, on.handles);
- // and a finger then (the pen lifted) changes nothing
- assert_eq!(s.quickshape_perfect().unwrap().handles, on.handles);
+ assert_eq!(s.quickshape_finger(false).unwrap().handles, on.handles);
s.quickshape_done();
- // a held ellipse a finger makes a circle
+ // a held ellipse near round is a circle while a finger is down
let pts: Vec<PenSample> = (0..=60)
.map(|i| {
let t = i as f32 / 60.0 * std::f32::consts::TAU;
@@ -1045,9 +1049,11 @@ fn a_shape_still_held_follows_the_pen_and_a_finger_makes_it_perfect() {
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);
- let circle = s.quickshape_perfect().unwrap();
- assert_eq!(circle.kind, QuickShapeKind::Circle);
+ assert_eq!(s.quickshape_finger(true).unwrap().kind, QuickShapeKind::Circle);
+ assert_eq!(s.quickshape_finger(false).unwrap().kind, QuickShapeKind::Ellipse);
+ assert_eq!(s.quickshape_finger(true).unwrap().kind, QuickShapeKind::Circle);
s.stroke_end(vec![]);
+ assert_eq!(s.quickshape_info().unwrap().kind, QuickShapeKind::Circle);
s.quickshape_done();
}
diff --git a/crates/engine/src/quickshape.rs b/crates/engine/src/quickshape.rs
index 662649d..056d50a 100644
--- a/crates/engine/src/quickshape.rs
+++ b/crates/engine/src/quickshape.rs
@@ -39,6 +39,12 @@ const CLOSED: f32 = 0.18;
const CORNER_TOLERANCE: f32 = 0.08;
/// Points sampled around a curved outline.
const OUTLINE_STEPS: usize = 128;
+/// A held finger turns an ellipse into a circle when its axes' ratio is within this of 1, and a
+/// rectangle into a square within this.
+const ROUND_ENOUGH: f32 = 0.5;
+const SQUARE_ENOUGH: f32 = 0.25;
+/// The steps a held finger keeps a shape's turn to: 15 degrees.
+pub const TURN_STEP: f32 = std::f32::consts::PI / 12.0;
impl Shape {
/// The shape's outline, from where the stroke began, as the brush should redraw it.
@@ -178,19 +184,57 @@ impl Shape {
Shape { kind: self.kind, nodes }
}
- /// The shape made perfect, as a finger put down while the pen still holds it makes it: an
- /// ellipse a circle, a quadrilateral or rectangle a square, a triangle equilateral, a line
- /// turned to a whole number of 15 degree steps. Arcs and polylines stay as they are.
- pub fn perfected(&self) -> Shape {
+ /// The kind a finger down makes of a shape still held, from the shape as it snapped (the
+ /// `stroke` it was drawn from): an ellipse whose axes are within half of each other a circle,
+ /// a triangle equilateral, a quadrilateral a rectangle, and a rectangle whose sides are within
+ /// a quarter of each other a square. Other kinds stay as they are; the finger also keeps the
+ /// turn to whole steps (see [`Shape::turned_to_step`]).
+ pub fn snapped(&self, stroke: &[Vec2]) -> Shape {
match self.kind {
- ShapeKind::Ellipse => self.as_kind(ShapeKind::Circle, &[]),
- ShapeKind::Quadrilateral | ShapeKind::Rectangle => squared(self),
+ ShapeKind::Ellipse => {
+ let (_, a, b) = self.ellipse_frame();
+ if b.length() > 0.0 && (1.0 - a.length() / b.length()).abs() < ROUND_ENOUGH {
+ self.as_kind(ShapeKind::Circle, stroke)
+ } else {
+ self.clone()
+ }
+ }
ShapeKind::Triangle => equilateral(self),
- ShapeKind::Line => stepped_line(self),
+ ShapeKind::Quadrilateral | ShapeKind::Rectangle => {
+ let rect = self.as_kind(ShapeKind::Rectangle, if stroke.is_empty() { &self.nodes } else { stroke });
+ let get = |i: usize| rect.nodes.get(i).copied().unwrap_or(Vec2::ZERO);
+ let (w, h) = (get(0).distance(get(1)), get(0).distance(get(3)));
+ if h > 0.0 && (1.0 - w / h).abs() < SQUARE_ENOUGH { squared(&rect) } else { rect }
+ }
_ => self.clone(),
}
}
+ /// The point whose direction from the pivot a finger keeps to whole steps: an open shape's
+ /// end, an ellipse's first axis end, a polygon's first corner.
+ fn reference(&self) -> Vec2 {
+ match self.kind {
+ ShapeKind::Line | ShapeKind::Polyline | ShapeKind::Arc => self.nodes.last(),
+ ShapeKind::Ellipse | ShapeKind::Circle => self.nodes.get(1),
+ _ => self.nodes.first(),
+ }
+ .copied()
+ .unwrap_or(Vec2::ZERO)
+ }
+
+ /// The shape turned about its pivot to the nearest whole step of [`TURN_STEP`]: a line's
+ /// angle, an ellipse's axes, a polygon's first corner seen from its centre.
+ pub fn turned_to_step(&self) -> Shape {
+ let pivot = self.pivot();
+ let from = self.reference();
+ let d = from - pivot;
+ if d.length() < 1.0 {
+ return self.clone();
+ }
+ let angle = (d.y.atan2(d.x) / TURN_STEP).round() * TURN_STEP;
+ self.moved_with(pivot, from, pivot + Vec2::new(angle.cos(), angle.sin()) * d.length())
+ }
+
/// An ellipse's centre and its two half-axes.
fn ellipse_frame(&self) -> (Vec2, Vec2, Vec2) {
let get = |i: usize| self.nodes.get(i).copied().unwrap_or(Vec2::ZERO);
@@ -531,15 +575,6 @@ fn squared(quad: &Shape) -> Shape {
Shape { kind: ShapeKind::Square, nodes: vec![c - u - v, c + u - v, c + u + v, c - u + v] }
}
-/// A line turned about its start to the nearest 15 degree step, its length kept.
-fn stepped_line(line: &Shape) -> Shape {
- let (Some(&a), Some(&b)) = (line.nodes.first(), line.nodes.get(1)) else { return line.clone() };
- let d = b - a;
- let step = 15f32.to_radians();
- let angle = (d.y.atan2(d.x) / step).round() * step;
- Shape { kind: ShapeKind::Line, nodes: vec![a, a + Vec2::new(angle.cos(), angle.sin()) * d.length()] }
-}
-
fn centroid(pts: &[Vec2]) -> Vec2 {
pts.iter().fold(Vec2::ZERO, |a, &p| a + p) * (1.0 / pts.len().max(1) as f32)
}
@@ -793,43 +828,52 @@ mod tests {
}
#[test]
- fn a_finger_makes_a_held_shape_perfect() {
- let ellipse = axes_shape(ShapeKind::Ellipse, Vec2::ZERO, Vec2::new(0.0, 40.0), Vec2::new(-20.0, 0.0));
- let circle = ellipse.perfected();
+ fn a_finger_snaps_a_held_shape() {
+ // near round: a circle of the mean radius, still starting where the ellipse did
+ let ellipse = axes_shape(ShapeKind::Ellipse, Vec2::ZERO, Vec2::new(0.0, 40.0), Vec2::new(-30.0, 0.0));
+ let circle = ellipse.snapped(&[]);
assert_eq!(circle.kind, ShapeKind::Circle);
- // its radius the mean half-axis, and it still starts where the ellipse did
- assert!(
- circle.nodes[1].distance(Vec2::new(0.0, 30.0)) < 1e-3
- && circle.nodes[2].distance(Vec2::new(-30.0, 0.0)) < 1e-3,
- "{circle:?}"
- );
- let quad = Shape {
- kind: ShapeKind::Quadrilateral,
- nodes: vec![Vec2::new(0.0, 0.0), Vec2::new(100.0, 10.0), Vec2::new(110.0, 60.0), Vec2::new(-10.0, 50.0)],
- };
- let square = quad.perfected();
+ assert!(circle.nodes[1].distance(Vec2::new(0.0, 35.0)) < 1e-3, "{circle:?}");
+ // too long and thin (axes 3 to 1) stays an ellipse
+ let long = axes_shape(ShapeKind::Ellipse, Vec2::ZERO, Vec2::new(60.0, 0.0), Vec2::new(0.0, 20.0));
+ assert_eq!(long.snapped(&[]).kind, ShapeKind::Ellipse);
+ // a nearly square quadrilateral a square; a long one a rectangle
+ let square_ish = [Vec2::new(0.0, 0.0), Vec2::new(100.0, 5.0), Vec2::new(95.0, 95.0), Vec2::new(-5.0, 90.0)];
+ let quad = Shape { kind: ShapeKind::Quadrilateral, nodes: square_ish.to_vec() };
+ let square = quad.snapped(&polygon_path(&square_ish, 20));
assert_eq!(square.kind, ShapeKind::Square);
let sides: Vec<f32> = (0..4).map(|i| square.nodes[i].distance(square.nodes[(i + 1) % 4])).collect();
assert!(sides.iter().all(|s| (s - sides[0]).abs() < 1e-3), "{sides:?}");
assert!((square.nodes[1] - square.nodes[0]).dot(square.nodes[3] - square.nodes[0]).abs() < 1e-2);
- // turning as the quadrilateral did, its first corner nearest the quadrilateral's
- assert!((square.nodes[1] - square.nodes[0]).cross(square.nodes[2] - square.nodes[1]) > 0.0);
- assert!(square.nodes[0].distance(quad.nodes[0]) < square.nodes[2].distance(quad.nodes[0]));
+ let long = [Vec2::new(0.0, 0.0), Vec2::new(200.0, 5.0), Vec2::new(195.0, 95.0), Vec2::new(-5.0, 90.0)];
+ let quad = Shape { kind: ShapeKind::Quadrilateral, nodes: long.to_vec() };
+ assert_eq!(quad.snapped(&polygon_path(&long, 20)).kind, ShapeKind::Rectangle);
let tri =
Shape { kind: ShapeKind::Triangle, nodes: vec![Vec2::ZERO, Vec2::new(90.0, 0.0), Vec2::new(0.0, 90.0)] };
- let eq = tri.perfected();
+ let eq = tri.snapped(&[]);
assert_eq!(eq.kind, ShapeKind::EquilateralTriangle);
assert!((eq.nodes[0].distance(eq.nodes[1]) - eq.nodes[1].distance(eq.nodes[2])).abs() < 1e-2);
+ let arc = Shape { kind: ShapeKind::Arc, nodes: vec![Vec2::ZERO, Vec2::new(50.0, 20.0), Vec2::new(100.0, 0.0)] };
+ assert_eq!(arc.snapped(&[]), arc);
+ }
+
+ #[test]
+ fn a_finger_keeps_the_turn_to_whole_steps() {
+ // a line about its start, its length kept
let line = Shape { kind: ShapeKind::Line, nodes: vec![Vec2::new(10.0, 10.0), Vec2::new(110.0, 30.0)] };
- let stepped = line.perfected();
+ let stepped = line.turned_to_step();
let d = stepped.nodes[1] - stepped.nodes[0];
assert_eq!(stepped.nodes[0], Vec2::new(10.0, 10.0));
- assert!(
- (d.y.atan2(d.x).to_degrees() - 15.0).abs() < 1e-3
- && (d.length() - line.nodes[0].distance(line.nodes[1])).abs() < 1e-3
- );
- let arc = Shape { kind: ShapeKind::Arc, nodes: vec![Vec2::ZERO, Vec2::new(50.0, 20.0), Vec2::new(100.0, 0.0)] };
- assert_eq!(arc.perfected(), arc);
+ assert!((d.y.atan2(d.x).to_degrees() - 15.0).abs() < 1e-3, "{d:?}");
+ assert!((d.length() - line.nodes[0].distance(line.nodes[1])).abs() < 1e-3);
+ // an ellipse about its centre: its first axis on a step
+ let ellipse = axes_shape(ShapeKind::Ellipse, Vec2::new(5.0, 5.0), Vec2::new(40.0, 4.0), Vec2::new(-1.0, 10.0));
+ let (c, a, _) = ellipse.turned_to_step().ellipse_frame();
+ assert!(c.distance(Vec2::new(5.0, 5.0)) < 1e-3);
+ assert!(a.y.abs() < 1e-3 && (a.x - Vec2::new(40.0, 4.0).length()).abs() < 1e-3, "{a:?}");
+ // already on a step: unchanged
+ let flat = Shape { kind: ShapeKind::Line, nodes: vec![Vec2::ZERO, Vec2::new(50.0, 0.0)] };
+ assert_eq!(flat.turned_to_step(), flat);
}
#[test]