Skip to content

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

Rust

feat(quickshape): a held shape follows the pen and a finger makes it perfect

Josh5ec2a01fed07
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 024a98f..4495652 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,6 +615,11 @@ 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
+ if ((mode == Mode.PEN || mode == Mode.FINGER) && vm.quickShape != null) {
+ if (e.getToolType(e.actionIndex) == MotionEvent.TOOL_TYPE_FINGER) vm.quickShapePerfect()
+ return true
+ }
if (mode == Mode.PEN || mode == Mode.PICK) return true
vm.showCursor(null)
if (mode == Mode.FINGER) s.strokeCancel()
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 31b8bd4..b321749 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,6 +2577,11 @@ 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
+ }
+
fun chooseQuickShape(kind: QuickShapeKind) {
quickShape = session?.quickshapeChoose(kind) ?: quickShape
}
@@ -5448,6 +5453,8 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {
/** A stroke finished: its layer's thumbnail and the undo state changed. */
fun strokeEnded() {
+ // a snapped shape the pen moved: its handles where it now is
+ if (quickShape != null) quickShape = session?.quickshapeInfo() ?: quickShape
// a stroke on a locked or hidden layer drew nothing: say why (text layers ask to rasterize instead)
if (adjustment == null && !currentIsText()) currentTakesChanges()
refreshFlags()
diff --git a/apps/procraft-android/src/lib.rs b/apps/procraft-android/src/lib.rs
index edafe2f..dcb4e54 100644
--- a/apps/procraft-android/src/lib.rs
+++ b/apps/procraft-android/src/lib.rs
@@ -1120,8 +1120,13 @@ impl CanvasSession {
}
st.keep_pad_input(&samples);
let canvas_samples = st.assisted(st.to_canvas(&samples));
- // a snapped shape follows the held finger no further
+ // a snapped shape turns and grows with the pen still holding it
if st.shape.is_some() {
+ if let Some(to) = canvas_samples.iter().rev().find(|s| s.is_finite()).map(|s| s.pos)
+ && st.follow_shape(to)
+ {
+ self.shared.frame(st);
+ }
return;
}
st.remember_input(&canvas_samples);
@@ -1140,6 +1145,10 @@ impl CanvasSession {
if st.scene_shown() {
return;
}
+ // a snapped shape is drawn whole: nothing runs ahead of it
+ if st.shape.is_some() {
+ return;
+ }
let canvas_samples = st.to_canvas(&samples);
let (Some(builder), Some(canvas)) = (st.stroke.as_ref(), st.canvas.as_mut()) else { return };
let guide = st.doc.stroke_guide();
@@ -1165,6 +1174,10 @@ impl CanvasSession {
let canvas_samples = st.assisted(st.to_canvas(&samples));
// a snapped shape stays open to be edited, until the next thing done keeps it
if st.shape.is_some() {
+ if let Some(to) = canvas_samples.iter().rev().find(|s| s.is_finite()).map(|s| s.pos) {
+ st.follow_shape(to);
+ }
+ st.let_go_shape();
self.shared.frame(st);
return;
}
diff --git a/apps/procraft-android/src/quickshape.rs b/apps/procraft-android/src/quickshape.rs
index 5c48a43..43fff4e 100644
--- a/apps/procraft-android/src/quickshape.rs
+++ b/apps/procraft-android/src/quickshape.rs
@@ -76,6 +76,11 @@ 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,
}
/// A stroke as it began (and, once kept, what it drew), so that QuickShape can redraw it as a
@@ -119,11 +124,38 @@ impl State {
builder.add(&samples);
let stamps = builder.finish();
if let Some(canvas) = self.canvas.as_mut() {
+ // nothing drawn ahead of the pen before it snapped stays over the shape
+ canvas.set_prediction(&[]);
+ canvas.set_tip(&[]);
canvas.replace_stamps(&stamps);
}
self.stroke = Some(builder);
}
+ /// 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(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();
+ }
+ if shape == edit.shape {
+ return false;
+ }
+ edit.shape = shape;
+ self.draw_shape();
+ true
+ }
+
+ /// The pen that drew the snapped shape lifted: it stays where it is, open to be edited.
+ pub(crate) fn let_go_shape(&mut self) {
+ if let Some(edit) = self.shape.as_mut() {
+ edit.held = None;
+ }
+ }
+
/// The stroke just kept is remembered, for QuickShape on the last stroke.
pub(crate) fn remember_last_stroke(&mut self) {
let Some(mut last) = self.began.take() else { return };
@@ -202,7 +234,15 @@ impl CanvasSession {
let found = recognise(&st.drawn);
let first = found.first()?.clone();
let choices = found.iter().map(|s| s.kind).collect();
- st.shape = Some(ShapeEdit { shape: first, choices, drawn: st.drawn.clone(), pressure: st.mean_pressure() });
+ 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,
+ });
st.began = None;
st.draw_shape();
self.shared.frame(st);
@@ -230,7 +270,14 @@ 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 });
+ st.shape = Some(ShapeEdit {
+ shape: first,
+ choices,
+ drawn: last.drawn,
+ pressure: last.pressure,
+ held: None,
+ perfect: false,
+ });
st.draw_shape();
self.shared.frame(st);
st.shape_info()
@@ -246,6 +293,8 @@ impl CanvasSession {
let mut guard = self.shared.lock();
let st = &mut *guard;
let edit = st.shape.as_mut()?;
+ // a kind chosen is kept: the pen, if still down, no longer moves it
+ edit.held = None;
let current = edit.shape.kind;
// a kind already shown keeps its edits; another is fitted to the stroke as drawn
edit.shape = edit.shape.as_kind(kind.into(), &edit.drawn);
@@ -262,12 +311,29 @@ impl CanvasSession {
let mut guard = self.shared.lock();
let st = &mut *guard;
let to = st.view?.screen_to_canvas(Vec2::new(x, y))?;
- st.shape.as_mut()?.shape.move_handle(index as usize, to);
+ let edit = st.shape.as_mut()?;
+ edit.held = None;
+ edit.shape.move_handle(index as usize, to);
st.draw_shape();
self.shared.frame(st);
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> {
+ 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();
+ 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.rs
index e06e042..56017aa 100644
--- a/apps/procraft-android/src/tests.rs
+++ b/apps/procraft-android/src/tests.rs
@@ -1004,6 +1004,53 @@ fn a_held_stroke_snaps_to_a_shape_and_is_edited() {
s.stroke_end(vec![]);
}
+#[test]
+fn a_shape_still_held_follows_the_pen_and_a_finger_makes_it_perfect() {
+ use crate::quickshape::QuickShapeKind;
+ let Some(s) = session(200, 200) else { return };
+ s.set_brush_size(0.2);
+ // 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());
+ s.stroke_add(pts[1..].to_vec());
+ let info = s.quickshape_hold().expect("a shape");
+ assert_eq!(info.kind, QuickShapeKind::Line);
+ // the pen moves on: the line's end goes with it, turning about its start
+ s.stroke_add(vec![sample(80.0, 160.0, 400.0)]);
+ 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);
+ 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
+ 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);
+ s.quickshape_done();
+ // a held ellipse a finger makes a circle
+ 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() + 2.0 * (7.0 * t).sin(), 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);
+ let circle = s.quickshape_perfect().unwrap();
+ assert_eq!(circle.kind, QuickShapeKind::Circle);
+ s.stroke_end(vec![]);
+ s.quickshape_done();
+}
+
#[test]
fn copy_cut_paste_and_flip() {
let Some(s) = session(100, 100) else { return };
diff --git a/crates/engine/src/quickshape.rs b/crates/engine/src/quickshape.rs
index 7ea6565..662649d 100644
--- a/crates/engine/src/quickshape.rs
+++ b/crates/engine/src/quickshape.rs
@@ -126,7 +126,13 @@ impl Shape {
ShapeKind::Circle => {
let (c, a, b) = self.ellipse_frame();
let r = (a.length() + b.length()) * 0.5;
- axes_shape(ShapeKind::Circle, c, Vec2::new(r, 0.0), Vec2::new(0.0, r))
+ // along the ellipse's axes, so the outline still starts where the stroke began
+ axes_shape(
+ ShapeKind::Circle,
+ c,
+ a.normalized_or(Vec2::new(1.0, 0.0)) * r,
+ b.normalized_or(Vec2::new(0.0, 1.0)) * r,
+ )
}
ShapeKind::Ellipse => fit_ellipse(stroke),
ShapeKind::Square | ShapeKind::Rectangle => {
@@ -141,6 +147,50 @@ impl Shape {
}
}
+ /// What a shape still held turns and grows about: an open shape's start, a closed shape's
+ /// centre.
+ pub fn pivot(&self) -> Vec2 {
+ match self.kind {
+ ShapeKind::Line | ShapeKind::Polyline | ShapeKind::Arc => self.nodes.first().copied().unwrap_or(Vec2::ZERO),
+ ShapeKind::Ellipse | ShapeKind::Circle => self.ellipse_frame().0,
+ _ => centroid(&self.nodes),
+ }
+ }
+
+ /// The shape turned and scaled about `pivot` so that the point `from` lands on `to`, as the
+ /// pen still down after a snap turns and resizes it.
+ pub fn moved_with(&self, pivot: Vec2, from: Vec2, to: Vec2) -> Shape {
+ let (f, t) = (from - pivot, to - pivot);
+ let len2 = f.dot(f);
+ if !t.is_finite() || len2 < 1.0 {
+ return self.clone();
+ }
+ // t / f as complex numbers: the turn and the scale in one
+ let (re, im) = (t.dot(f) / len2, f.cross(t) / len2);
+ let nodes = self
+ .nodes
+ .iter()
+ .map(|&p| {
+ let d = p - pivot;
+ pivot + Vec2::new(d.x * re - d.y * im, d.x * im + d.y * re)
+ })
+ .collect();
+ 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 {
+ match self.kind {
+ ShapeKind::Ellipse => self.as_kind(ShapeKind::Circle, &[]),
+ ShapeKind::Quadrilateral | ShapeKind::Rectangle => squared(self),
+ ShapeKind::Triangle => equilateral(self),
+ ShapeKind::Line => stepped_line(self),
+ _ => self.clone(),
+ }
+ }
+
/// 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);
@@ -468,18 +518,34 @@ fn fit_rect(pts: &[Vec2]) -> Shape {
Shape { kind: ShapeKind::Rectangle, nodes: from_nearest(nodes, start) }
}
-fn squared(rect: &Shape) -> Shape {
- let get = |i: usize| rect.nodes.get(i).copied().unwrap_or(Vec2::ZERO);
- let (p0, p1, p3) = (get(0), get(1), get(3));
- let side = (p0.distance(p1) + p0.distance(p3)) * 0.5;
- let c = p0.lerp(get(2), 0.5);
+/// The square with a quadrilateral's centre and mean side, along its first side and turning the
+/// same way.
+fn squared(quad: &Shape) -> Shape {
+ let get = |i: usize| quad.nodes.get(i).copied().unwrap_or(Vec2::ZERO);
+ let (p0, p1, p2, p3) = (get(0), get(1), get(2), get(3));
+ let side = (p0.distance(p1) + p1.distance(p2) + p2.distance(p3) + p3.distance(p0)) * 0.25;
+ let c = centroid(&[p0, p1, p2, p3]);
+ let turn = if (p1 - p0).cross(p2 - p1) >= 0.0 { 1.0 } else { -1.0 };
let u = (p1 - p0).normalized_or(Vec2::new(1.0, 0.0)) * (side * 0.5);
- let v = (p3 - p0).normalized_or(Vec2::new(0.0, 1.0)) * (side * 0.5);
+ let v = Vec2::new(-u.y, u.x) * turn;
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)
+}
+
fn equilateral(t: &Shape) -> Shape {
- let c = t.nodes.iter().fold(Vec2::ZERO, |a, &p| a + p) * (1.0 / t.nodes.len().max(1) as f32);
+ let c = centroid(&t.nodes);
let first = t.nodes.first().copied().unwrap_or(c) - c;
let r = t.nodes.iter().map(|p| p.distance(c)).sum::<f32>() / t.nodes.len().max(1) as f32;
let a0 = first.y.atan2(first.x);
@@ -704,6 +770,68 @@ mod tests {
assert_eq!(line.nodes[0], Vec2::ZERO);
}
+ #[test]
+ fn a_held_shape_turns_and_grows_with_the_pen() {
+ let line = Shape { kind: ShapeKind::Line, nodes: vec![Vec2::ZERO, Vec2::new(100.0, 0.0)] };
+ assert_eq!(line.pivot(), Vec2::ZERO);
+ let moved = line.moved_with(line.pivot(), Vec2::new(100.0, 0.0), Vec2::new(0.0, 200.0));
+ assert!(
+ moved.nodes[0].distance(Vec2::ZERO) < 1e-3 && moved.nodes[1].distance(Vec2::new(0.0, 200.0)) < 1e-3,
+ "{moved:?}"
+ );
+ let ellipse = axes_shape(ShapeKind::Ellipse, Vec2::new(50.0, 50.0), Vec2::new(40.0, 0.0), Vec2::new(0.0, 20.0));
+ assert_eq!(ellipse.pivot(), Vec2::new(50.0, 50.0));
+ let moved = ellipse.moved_with(ellipse.pivot(), Vec2::new(90.0, 50.0), Vec2::new(50.0, 130.0));
+ let (c, a, b) = moved.ellipse_frame();
+ assert!(c.distance(Vec2::new(50.0, 50.0)) < 1e-3);
+ assert!(a.distance(Vec2::new(0.0, 80.0)) < 1e-3 && b.distance(Vec2::new(-40.0, 0.0)) < 1e-3, "{a:?} {b:?}");
+ let tri =
+ Shape { kind: ShapeKind::Triangle, nodes: vec![Vec2::ZERO, Vec2::new(90.0, 0.0), Vec2::new(0.0, 90.0)] };
+ assert_eq!(tri.pivot(), Vec2::new(30.0, 30.0));
+ // a pen on the pivot itself leaves the shape alone
+ assert_eq!(tri.moved_with(tri.pivot(), tri.pivot(), Vec2::new(5.0, 5.0)), tri);
+ }
+
+ #[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();
+ 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_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 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();
+ 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 line = Shape { kind: ShapeKind::Line, nodes: vec![Vec2::new(10.0, 10.0), Vec2::new(110.0, 30.0)] };
+ let stepped = line.perfected();
+ 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);
+ }
+
#[test]
fn shapes_change_kind() {
let pts = wobbly_circle(100.0, 0.6, 80);