ProCraft for Android: An Android native painting app written in Rust
Rust
feat(color): ColorDrop fills from the colour button, with Continue filling and a slid threshold
Josh1de3ef434b36
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 cd2f87b..230b7ed 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 }+ private enum class Mode { NONE, PEN, FINGER, IDLE, GESTURE, PICK, TRANSFORM, SELECT, ADJUST, PUCK, SHAPE, HOVER, TURN, POUR }/** The pen is hovering over the canvas. */private var penHovering = false@@ -217,6 +217,10 @@ class CanvasSurfaceView(context: Context, private val vm: CanvasViewModel) : Surprivate var lastSelectTime = 0Lprivate var threshold = 0f+ // Continue filling's touch: where it filled from, and whether it has slid past the slop+ private var pourStart = Offset.Zero+ private var pourMoved = false+// where the finger went down, for the hold that opens the eyedropperprivate var downX = 0fprivate var downY = 0f@@ -426,6 +430,16 @@ class CanvasSurfaceView(context: Context, private val vm: CanvasViewModel) : Survm.pickAt(e.x, e.y, pickSide)return true}+ if (vm.dropBand == CanvasViewModel.DropBand.FILLING) {+ // Continue filling: the touch fills where it lands; slid, it changes the threshold+ pourStart = Offset(e.x, e.y)+ pourMoved = false+ lastSelectX = e.x+ lastSelectTime = e.eventTime+ threshold = vm.dropThreshold+ mode = if (vm.pourBegin(pourStart)) Mode.POUR else Mode.IDLE+ return true+ }tapStart = e.eventTimetapPointers = 1tapMoved = 0f@@ -591,7 +605,9 @@ class CanvasSurfaceView(context: Context, private val vm: CanvasViewModel) : Survm.shapeDrag = nullvm.thresholdDrag?.let { (p, t) -> vm.selectByColour(p, t, live = false) }}- if (mode == Mode.FINGER || mode == Mode.IDLE || mode == Mode.TRANSFORM || mode == Mode.SELECT || mode == Mode.TURN) {+ // a second finger takes back the fill the first one made+ if (mode == Mode.POUR) vm.pourEnd(keep = false)+ if (mode == Mode.FINGER || mode == Mode.IDLE || mode == Mode.TRANSFORM || mode == Mode.SELECT || mode == Mode.TURN || mode == Mode.POUR) {gestureStart = e.eventTimegestureScale = 1f}@@ -635,6 +651,7 @@ class CanvasSurfaceView(context: Context, private val vm: CanvasViewModel) : SurMode.SHAPE -> vm.moveQuickShapeHandle(shapeHandle, Offset(e.x, e.y))Mode.GESTURE -> if (fingers >= 3) scrub(e) else moveGesture(e, s)Mode.SELECT -> select(e, done = false)+ Mode.POUR -> pour(e, done = false)Mode.ADJUST -> if (vm.adjustment == Adjustment.LIQUIFY) {vm.liquifyStroke(liquifyPoints(e), start = false)followLiquify(e)@@ -699,6 +716,7 @@ class CanvasSurfaceView(context: Context, private val vm: CanvasViewModel) : SurMode.PICK -> vm.finishPick()Mode.PUCK, Mode.SHAPE, Mode.IDLE, Mode.HOVER, Mode.TURN -> UnitMode.SELECT -> select(e, done = true)+ Mode.POUR -> pour(e, done = true)Mode.ADJUST -> if (vm.adjustment == Adjustment.LIQUIFY) {// still moving when it lifts, liquify carries onif (e.eventTime - liquifyTime <= LIQUIFY_STILL_MS) vm.liquifyLifted(liquifyVelocity.x, liquifyVelocity.y)@@ -742,6 +760,7 @@ class CanvasSurfaceView(context: Context, private val vm: CanvasViewModel) : Surif (mode == Mode.PEN || mode == Mode.FINGER) s.strokeCancel()restoreTool(s)if (mode == Mode.PICK) vm.cancelPick()+ if (mode == Mode.POUR) vm.pourEnd(keep = false)if (mode == Mode.TRANSFORM && transformGrabbed) vm.transformMoved(s.transformCancelDrag())vm.transformHeld = nulltransformGrabbed = false@@ -851,6 +870,21 @@ class CanvasSurfaceView(context: Context, private val vm: CanvasViewModel) : Sur}}+ /** Continue filling's touch slid across the screen changes the fill's threshold; lifted, the fill is kept. */+ private fun pour(e: MotionEvent, done: Boolean) {+ val p = Offset(e.x, e.y)+ if ((p - pourStart).getDistance() > transformSlop) pourMoved = true+ if (pourMoved) {+ // as a selection's threshold follows a drag, only more gently+ val dx = (p.x - lastSelectX) / resources.displayMetrics.density+ threshold = (threshold + dragStep(dx, e.eventTime - lastSelectTime) / POUR_SLIDE_GENTLER).coerceIn(0f, 1f)+ vm.pourThreshold(threshold)+ }+ lastSelectX = p.x+ lastSelectTime = e.eventTime+ if (done) vm.pourEnd(keep = true)+ }+/*** How much an amount dragged across the screen changes for a step of [dx] points over [ms]: more* for faster drags (the speed taken per 60 Hz frame), 200 points at a steady pace moving it most@@ -1036,5 +1070,8 @@ class CanvasSurfaceView(context: Context, private val vm: CanvasViewModel) : Sur/** The window the eyedropper shows (magnified twice), dp across. */const val PICK_WINDOW_DP = 54f++ /** How many times more gently a fill's threshold follows a slide than a selection's. */+ const val POUR_SLIDE_GENTLER = 2.7f}}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 b032925..e0521b6 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@@ -1580,6 +1580,7 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {/** Saves the open artwork and goes back to the gallery. */fun closeArtwork() {+ endFilling()endTransform(true)endAdjustment(true)val s = session ?: return@@ -4399,6 +4400,7 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {/** The adjustments button: closes an open adjustment (keeping it), or opens the menu. */fun adjustmentsPressed() {endQuickShape()+ endFilling()if (adjustment != null) endAdjustment(true) else toggle(Panel.ADJUSTMENTS)}@@ -4407,6 +4409,7 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {/** The selection button: opens or closes the selection tool (a selection made stays). */fun toggleSelecting() {endQuickShape()+ endFilling()if (selecting) {closeSelecting()return@@ -4494,6 +4497,119 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {selectionChanged(fill = !live)}+ // ColorDrop: the colour dragged from the colour button (or a swatch) and dropped on the canvas+ // fills the area around where it lands++ /** What the ColorDrop band under the top bar shows. */+ enum class DropBand { NONE, DRAGGING, DROPPED, FILLING }++ var dropBand by mutableStateOf(DropBand.NONE)+ private set++ /** The dragged colour's dot (window pixels) and its colour (0xRRGGBB), while it is dragged. */+ var dropDot by mutableStateOf<Pair<Offset, Int>?>(null)+ private set++ /** The threshold the colour fills with (0..1), kept from one drop to the next. */+ var dropThreshold by mutableFloatStateOf(transformPrefs.getFloat(DROP_THRESHOLD, 0.5f))+ private set++ /** Whether the threshold is being slid: its row shows under the band. */+ var dropSliding by mutableStateOf(false)+ private set++ /** The swatch's colour when a swatch was dropped (filling goes on with it); else the current colour. */+ private var dropSwatch: Int? = null+ private var dropBandTimer: kotlinx.coroutines.Job? = null++ /** A colour starts being dragged from the colour button, or [swatch] from the palette. */+ fun dropDragStart(at: Offset, swatch: Int? = null) {+ if (swatch == null) closePanels()+ dropBandTimer?.cancel()+ dropSwatch = swatch+ dropDot = at to (swatch ?: colorRgb())+ dropBand = DropBand.DRAGGING+ }++ fun dropDragMove(at: Offset) {+ dropDot = dropDot?.let { at to it.second }+ }++ /** The dragged colour let go at [at] (null: somewhere it doesn't fill, like the top bar). */+ fun dropDragEnd(at: Offset?) {+ dropDot = null+ if (at != null && pourBegin(at)) {+ pourEnd(keep = true)+ // the band offers to go on filling for a moment+ dropBand = DropBand.DROPPED+ dropBandTimer = viewModelScope.launch {+ kotlinx.coroutines.delay(DROP_BAND_MS)+ if (dropBand == DropBand.DROPPED) dropBand = DropBand.NONE+ }+ } else {+ dropBand = DropBand.NONE+ }+ }++ /** Continue filling: each touch on the canvas fills, until [endFilling]. */+ fun continueFilling() {+ dropBandTimer?.cancel()+ dropBand = DropBand.FILLING+ }++ fun endFilling() {+ dropBandTimer?.cancel()+ if (dropBand != DropBand.NONE) dropBand = DropBand.NONE+ dropSliding = false+ }++ /** Fills from window point [p] with the dropped colour; false if nothing was filled. */+ fun pourBegin(p: Offset): Boolean {+ val s = session ?: return false+ if (!currentTakesChanges()) return false+ // text takes no colour until it is rasterized+ if (currentIsText()) {+ askRasterize = true+ return false+ }+ val c = dropSwatch ?: colorRgb()+ val t = dropThreshold+ return pourNow { s.pourBegin(p.x, p.y, ((c shr 16) and 0xFF) / 255f, ((c shr 8) and 0xFF) / 255f, (c and 0xFF) / 255f, t) }+ }++ /** The fill under way redone with [threshold], which is kept for the next. */+ fun pourThreshold(threshold: Float) {+ val s = session ?: return+ dropThreshold = threshold.coerceIn(0f, 1f)+ dropSliding = true+ // redone away from the main thread, only ever with the latest threshold+ pourWanted = dropThreshold+ if (pourQueued.compareAndSet(false, true)) {+ pourThread.execute {+ pourQueued.set(false)+ s.pourThreshold(pourWanted)+ }+ }+ }++ /** The fill under way ends: [keep] makes it an undo step, else it is taken back. */+ fun pourEnd(keep: Boolean) {+ val s = session ?: return+ pourNow { s.pourEnd(keep) }+ if (dropSliding) transformPrefs.edit().putFloat(DROP_THRESHOLD, dropThreshold).apply()+ dropSliding = false+ refresh()+ }++ /** A fill's work, in order, off the main thread (a slid threshold redoes the whole fill). */+ private val pourThread = java.util.concurrent.Executors.newSingleThreadExecutor()+ @Volatile+ private var pourWanted = 0f+ private val pourQueued = java.util.concurrent.atomic.AtomicBoolean(false)++ /** Runs [block] on the fill's thread once what is queued there is done, and waits for it. */+ private fun <T> pourNow(block: () -> T): T = pourThread.submit(java.util.concurrent.Callable(block)).get()+fun invertSelection() {session?.selectInvert()selectionChanged(fill = false)@@ -4601,6 +4717,7 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {/** The transform button: opens transform on the current layer, or keeps it and closes. */fun toggleTransform() {endQuickShape()+ endFilling()if (transforming) {endTransform(true)return@@ -5161,6 +5278,7 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {override fun onCleared() {saveNow()session = null+ pourThread.shutdown()}companion object {@@ -5340,6 +5458,10 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {private const val ADVANCED_MESH = "advancedMesh"private const val SELECTION_KIND = "selectionKind"private const val SELECTION_THRESHOLD = "selectionThreshold"+ private const val DROP_THRESHOLD = "dropThreshold"++ /** How long the band offers Continue filling after a drop. */+ private const val DROP_BAND_MS = 2_500Lfun hsvToRgb(h: Float, s: Float, v: Float): Int {val hsv = floatArrayOf((h * 360f) % 360f, s, v)diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AppRoot.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AppRoot.ktindex 80c4e23..9a64e62 100644--- a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AppRoot.kt+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AppRoot.kt@@ -126,6 +126,7 @@ fun AppRoot(vm: CanvasViewModel) {}}NoticeBand(vm)+ DropBandUi(vm)// each panel hangs from its button: colour, layers, then the tool that opened the library;// it grows out of its arrow as it opens and fades as it closesPanelPresence(vm.panel, Panel.NONE, fading = vm.panelFading, onFaded = { vm.panelFading = false }) { shown, alpha, scale, origin ->@@ -271,6 +272,8 @@ fun AppRoot(vm: CanvasViewModel) {LightingStudio(vm)BrushStudio(vm)PadMenu(vm, maxWidth)+ // a colour dragged out goes over everything+ DropDot(vm)}}}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/Chrome.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/Chrome.ktindex 712ce32..f8fa74a 100644--- a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/Chrome.kt+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/Chrome.kt@@ -146,7 +146,8 @@ private fun ColorButton(vm: CanvasViewModel) {// on the light barval ringed = if (Pc.light) vm.brightness > LIGHT_RING_ABOVE else vm.brightness < DARK_RING_BELOW// held, the colour painted with before- Box(Modifier.size(Pc.BarButtonWidth, Pc.BarButtonHeight).tapOrHold({ vm.toggle(Panel.COLOR) }, { vm.previousColor() }), contentAlignment = Alignment.Center) {+ // dragged out onto the canvas, it fills there (ColorDrop)+ Box(Modifier.size(Pc.BarButtonWidth, Pc.BarButtonHeight).dropSource(vm, onHold = { vm.previousColor() }) { vm.toggle(Panel.COLOR) }, contentAlignment = Alignment.Center) {val dot = Modifier.size(Pc.ColorDot).clip(CircleShape).background(CanvasSpace.color(rgb))Box(if (ringed) dot.border(1.dp, Pc.ColorRing, CircleShape) else dot)}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/ColorDropUi.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/ColorDropUi.ktnew file mode 100644index 0000000..549f265--- /dev/null+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/ColorDropUi.kt@@ -0,0 +1,196 @@+package io.github.artcraftandroid.procraft.ui++import androidx.compose.animation.core.Animatable+import androidx.compose.foundation.Canvas+import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.interaction.MutableInteractionSource+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.composed+import androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.clipToBounds+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.StrokeCap+import androidx.compose.ui.graphics.StrokeJoin+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.onGloballyPositioned+import androidx.compose.ui.layout.positionInRoot+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import io.github.artcraftandroid.procraft.canvas.CanvasViewModel+import io.github.artcraftandroid.procraft.canvas.CanvasViewModel.DropBand+import kotlin.math.roundToInt++/** What a touch on a colour that can be dragged out turned out to be. */+private enum class DropTouch { TAP, HOLD, DRAG, GONE }++/**+ * A colour that can be dragged out onto the canvas to fill there (the colour button, or a swatch+ * with [swatch] giving its colour): tapped it does [onTap], held still [onHold]; dragged, its colour+ * goes with the finger as a dot and fills where it is let go below the top bar.+ */+internal fun Modifier.dropSource(vm: CanvasViewModel, swatch: (() -> Int)? = null, onHold: (() -> Unit)? = null, onTap: () -> Unit): Modifier = composed {+ val tap by rememberUpdatedState(onTap)+ val hold by rememberUpdatedState(onHold)+ val colour by rememberUpdatedState(swatch)+ var origin by remember { mutableStateOf(Offset.Zero) }+ onGloballyPositioned { origin = it.positionInRoot() }.pointerInput(vm) {+ awaitEachGesture {+ val down = awaitFirstDown()+ down.consume()+ // whichever comes first: lifted, moved past the slop, or (when holding does something) held+ val wait = if (hold != null) viewConfiguration.longPressTimeoutMillis else Long.MAX_VALUE+ val touch = withTimeoutOrNull(wait) {+ var seen: DropTouch? = null+ while (seen == null) {+ val c = awaitPointerEvent().changes.firstOrNull { it.id == down.id }+ seen = when {+ c == null -> DropTouch.GONE+ !c.pressed -> DropTouch.TAP.also { c.consume() }+ (c.position - down.position).getDistance() > viewConfiguration.touchSlop -> DropTouch.DRAG+ else -> null+ }+ }+ seen+ } ?: DropTouch.HOLD+ when (touch) {+ DropTouch.TAP -> tap()+ DropTouch.HOLD -> hold?.invoke()+ DropTouch.GONE -> Unit+ DropTouch.DRAG -> {+ var at = origin + down.position+ vm.dropDragStart(at, colour?.invoke())+ var lifted = false+ while (true) {+ val c = awaitPointerEvent().changes.firstOrNull { it.id == down.id } ?: break+ c.consume()+ at = origin + c.position+ if (!c.pressed) {+ lifted = true+ break+ }+ vm.dropDragMove(at)+ }+ // let go on the top bar, it is put back+ vm.dropDragEnd(at.takeIf { lifted && it.y > Pc.BarHeight.toPx() })+ }+ }+ }+ }+}++/** The colour being dragged out: a flat dot under the finger. */+@Composable+fun DropDot(vm: CanvasViewModel) {+ val (at, rgb) = vm.dropDot ?: return+ Box(+ Modifier.offset { IntOffset((at.x - DotSize.toPx() / 2).roundToInt(), (at.y - DotSize.toPx() / 2).roundToInt()) }+ .size(DotSize).clip(CircleShape).background(CanvasSpace.color(rgb)),+ )+}++/**+ * ColorDrop's band under the top bar, sliding down from behind it: while a colour is dragged and+ * while filling goes on, with the threshold as a blue line across the screen under it; after a+ * drop, for a moment, offering to continue filling. Sliding the threshold adds a row reading it.+ */+@Composable+fun DropBandUi(vm: CanvasViewModel) {+ val band = vm.dropBand+ val shown = remember { Animatable(0f) }+ // what it showed, kept while it slides away+ val kept = remember { arrayOf(DropBand.NONE) }+ if (band != DropBand.NONE) kept[0] = band+ LaunchedEffect(band == DropBand.NONE) {+ if (band == DropBand.NONE) shown.animateTo(0f, Motion.noticeOut()) else shown.animateTo(1f, Motion.noticeIn())+ }+ if (band == DropBand.NONE && shown.value <= 0f) return+ val what = kept[0]+ val ink = if (Pc.light) Color(0xFF222222) else Color(0xFFC5C5C5)+ val blue = if (Pc.light) Color(0xFF0A8CFD) else Color(0xFF0076FD)+ BoxWithConstraints(Modifier.offset(y = Pc.BarHeight).fillMaxWidth().clipToBounds()) {+ val width = maxWidth+ Column(Modifier.graphicsLayer { translationY = -(1f - shown.value) * size.height }) {+ Box(Modifier.fillMaxWidth().height(32.dp).background(if (Pc.light) BandLight else BandDark), contentAlignment = Alignment.Center) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ Text("ColorDrop", color = ink, fontSize = 16.5.sp, fontWeight = FontWeight.Bold, maxLines = 1)+ Spacer(Modifier.width(13.dp))+ if (what == DropBand.FILLING) {+ // the tick ends filling+ Box(Modifier.size(20.dp).clip(CircleShape).background(blue).press { vm.endFilling() }) {+ Canvas(Modifier.size(20.dp)) {+ val u = size.width / 20f+ val tick = Path().apply {+ moveTo(10f * u - 4.2f * u, 10f * u + 0.1f * u)+ lineTo(10f * u - 1.4f * u, 10f * u + 2.6f * u)+ lineTo(10f * u + 4f * u, 10f * u - 2.8f * u)+ }+ drawPath(tick, Color.White, style = Stroke(2f * u, cap = StrokeCap.Round, join = StrokeJoin.Round))+ }+ }+ } else {+ Box(+ Modifier.size(101.dp, 20.dp).clip(RoundedCornerShape(10.dp)).background(blue).press { vm.continueFilling() },+ contentAlignment = Alignment.Center,+ ) {+ Text("Continue filling", color = Color.White, fontSize = 11.7.sp, maxLines = 1)+ }+ }+ }+ }+ if (vm.dropSliding) {+ Box(Modifier.fillMaxWidth().height(24.dp).background(if (Pc.light) RowLight else RowDark), contentAlignment = Alignment.Center) {+ Text("Threshold ${(vm.dropThreshold * 100).roundToInt()}%", color = ink, fontSize = 14.4.sp, maxLines = 1)+ }+ }+ if (what == DropBand.DRAGGING || what == DropBand.FILLING) {+ Box(Modifier.width(width * vm.dropThreshold).height(4.dp).background(blue))+ }+ }+ }+}++/** A tap target without a ripple. */+private fun Modifier.press(onClick: () -> Unit): Modifier = composed {+ clickable(remember { MutableInteractionSource() }, indication = null, onClick = onClick)+}++/** The dragged colour's dot, across. */+private val DotSize = 55.5.dp++/** The band, translucent over the canvas, dark and light. */+private val BandDark = Color(0xD63B3B3B)+private val BandLight = Color(0xD6EEEEEE)++/** The threshold's row under it. */+private val RowDark = Color(0xCC4A4A4A)+private val RowLight = Color(0xCCDCDCDC)diff --git a/apps/procraft-android/src/layer_ops.rs b/apps/procraft-android/src/layer_ops.rsindex ace7d3e..4f00662 100644--- a/apps/procraft-android/src/layer_ops.rs+++ b/apps/procraft-android/src/layer_ops.rs@@ -9,7 +9,7 @@ use crate::{CanvasSession, State};impl State {/// A layer's pixels, everything queued drawn first.- fn layer_pixels(&mut self, id: LayerId) -> Option<Vec<u8>> {+ pub(crate) fn layer_pixels(&mut self, id: LayerId) -> Option<Vec<u8>> {self.finish_stroke();self.settle();self.flush();diff --git a/apps/procraft-android/src/lib.rs b/apps/procraft-android/src/lib.rsindex 21154d2..340cfd3 100644--- a/apps/procraft-android/src/lib.rs+++ b/apps/procraft-android/src/lib.rs@@ -21,6 +21,7 @@ mod guide;mod layer_ops;mod layers;mod pick;+mod pour;mod project;mod projection;mod quickshape;@@ -261,6 +262,8 @@ pub(crate) struct State {/// The steps finished text edits made (by [`Canvas::undo_step`]'s numbering) and their layers:/// undo and redo of one go back to editing that text.pub(crate) text_steps: Vec<(u64, procraft_engine::document::LayerId)>,+ /// A colour dropped on the canvas whose threshold can still change.+ pub(crate) pour: Option<pour::Pour>,/// The library as the user has it, and as it ships.library: Vec<brush_library::LibrarySet>,shipped: Vec<BrushSet>,@@ -687,6 +690,7 @@ impl CanvasSession {tool: ToolKind::Paint,text_edit: None,text_steps: Vec::new(),+ pour: None,crop_undo: None,selection_visibility: 0.25,brush_on_screen: false,diff --git a/apps/procraft-android/src/pour.rs b/apps/procraft-android/src/pour.rsnew file mode 100644index 0000000..6482f28--- /dev/null+++ b/apps/procraft-android/src/pour.rs@@ -0,0 +1,132 @@+//! Dropping a colour on the canvas: the colour poured into the area joined to a point whose colour+//! is near the point's own, measured on the reference layer if there is one. While the finger stays+//! down the threshold can change and the pour is redone from the layer as it was; it ends as one+//! undo step.++use procraft_engine::document::LayerId;+use procraft_engine::fill::{self, Flood};+use procraft_engine::geom::Vec2;+use procraft_engine::selection::Mask;++use crate::CanvasSession;++/// A pour under way.+pub(crate) struct Pour {+ layer: LayerId,+ /// The layer's pixels as the pour began.+ before: Vec<u8>,+ flood: Flood,+ /// Measured on another layer (the reference), so poured over this one.+ elsewhere: bool,+ colour: [f32; 3],+ selection: Option<Mask>,+ alpha_lock: bool,+ /// The threshold last poured, in thousandths.+ shown: i32,+}++impl Pour {+ /// The layer's pixels with the colour poured at `threshold`.+ fn poured(&self, threshold: f32) -> Vec<u8> {+ let mut mask = self.flood.mask(threshold);+ if let Some(sel) = &self.selection {+ for (m, &s) in mask.data.iter_mut().zip(&sel.data) {+ *m = ((u16::from(*m) * u16::from(s) + 127) / 255) as u8;+ }+ }+ let mut pixels = self.before.clone();+ if self.elsewhere {+ fill::pour_over(&mut pixels, &mask, self.colour, self.alpha_lock);+ } else {+ fill::pour(&mut pixels, &mask, self.flood.colour, self.colour, self.alpha_lock);+ }+ pixels+ }+}++fn thousandths(threshold: f32) -> i32 {+ (threshold.clamp(0.0, 1.0) * 1000.0).round() as i32+}++#[uniffi::export]+impl CanvasSession {+ /// Pours colour (`r`, `g`, `b`, 0..1) at window point (`x`, `y`) with `threshold` (0..1) on+ /// the current layer, within the selection if there is one. False if nothing was poured (off+ /// the canvas, or the layer locked or text). The pour stays open for+ /// [`CanvasSession::pour_threshold`] until [`CanvasSession::pour_end`].+ pub fn pour_begin(&self, x: f32, y: f32, r: f32, g: f32, b: f32, threshold: f32) -> bool {+ self.pour_end(true);+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let Some(p) = st.view.and_then(|v| v.screen_to_canvas(Vec2::new(x, y))) else { return false };+ let (w, h) = (st.doc.width(), st.doc.height());+ if !(p.x >= 0.0 && p.y >= 0.0 && p.x < w as f32 && p.y < h as f32) {+ return false;+ }+ let current = st.doc.current();+ let Some(layer) = st.doc.layer(current).cloned() else { return false };+ if layer.locked || layer.text.is_some() {+ return false;+ }+ let Some(before) = st.current_pixels() else { return false };+ let seed = (p.x as u32, p.y as u32);+ // measured on the reference layer when another layer is it+ let reference = st.doc.reference().filter(|&r| r != current);+ let flood = match reference {+ Some(r) => st.layer_pixels(r).and_then(|px| Flood::new(w, h, &px, seed)),+ None => Flood::new(w, h, &before, seed),+ };+ let Some(flood) = flood else { return false };+ let colour = [r, g, b].map(|c| if c.is_finite() { c.clamp(0.0, 1.0) } else { 0.0 });+ let pour = Pour {+ layer: current,+ before,+ flood,+ elsewhere: reference.is_some(),+ colour,+ selection: st.selection.clone(),+ alpha_lock: layer.alpha_lock,+ shown: thousandths(threshold),+ };+ let pixels = pour.poured(threshold);+ if let Some(canvas) = st.canvas.as_mut() {+ canvas.hold_layer(current);+ canvas.put_layer(current, pixels);+ }+ st.pour = Some(pour);+ self.shared.frame(st);+ true+ }++ /// The open pour redone at `threshold` (0..1).+ pub fn pour_threshold(&self, threshold: f32) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let Some(pour) = st.pour.as_mut() else { return };+ let t = thousandths(threshold);+ if t == pour.shown {+ return;+ }+ pour.shown = t;+ let (layer, pixels) = (pour.layer, pour.poured(threshold));+ if let Some(canvas) = st.canvas.as_mut() {+ canvas.put_layer(layer, pixels);+ }+ self.shared.frame(st);+ }++ /// Ends the open pour: `keep` makes it one undo step; otherwise the layer goes back to how it+ /// was.+ pub fn pour_end(&self, keep: bool) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ if st.pour.take().is_none() {+ return;+ }+ if let Some(canvas) = st.canvas.as_mut() {+ canvas.release_layer(keep, None);+ }+ st.revision += 1;+ self.shared.frame(st);+ }+}diff --git a/apps/procraft-android/src/tests.rs b/apps/procraft-android/src/tests.rsindex f2a68c4..cbad72b 100644--- a/apps/procraft-android/src/tests.rs+++ b/apps/procraft-android/src/tests.rs@@ -2572,3 +2572,39 @@ fn stock_images_a_file_names_are_kept_and_named_again() {assert_eq!(out.roughness, Texture::None);assert_eq!(out.shape, Texture::Stock { name: "Hard-Round.png".to_owned(), inverted: true });}++#[test]+fn a_dropped_colour_fills_up_to_lines_and_is_one_undo_step() {+ let Some(s) = session(100, 100) else { return };+ s.set_brush_size(0.4);+ // a line down the middle splits the canvas in two+ s.stroke_begin(PointerKind::Finger, vec![sample(50.0, -10.0, 0.0)]);+ s.stroke_add((1..30).map(|i| sample(50.0, -10.0 + i as f32 * 4.0, i as f64 * 8.0)).collect());+ s.stroke_end(vec![sample(50.0, 110.0, 250.0)]);+ let layer = s.layers().iter().find(|l| l.current).map(|l| l.id).unwrap();+ // off the canvas nothing is poured+ assert!(!s.pour_begin(-5.0, 50.0, 1.0, 0.0, 0.0, 0.5));+ // red on the left half only+ assert!(s.pour_begin(20.0, 50.0, 1.0, 0.0, 0.0, 0.5));+ assert_eq!(pixel(&s, 20, 50), [255, 0, 0, 255]);+ assert_eq!(pixel(&s, 80, 50), [255, 255, 255, 255]);+ // the threshold all the way: the right half too, the line kept+ s.pour_threshold(1.0);+ assert_eq!(pixel(&s, 80, 50), [255, 0, 0, 255]);+ assert_eq!(pixel(&s, 50, 50), [0, 0, 0, 255]);+ s.pour_threshold(0.5);+ assert_eq!(pixel(&s, 80, 50), [255, 255, 255, 255]);+ s.pour_end(true);+ assert_eq!(pixel(&s, 20, 50), [255, 0, 0, 255]);+ // one undo takes the pour back; the line stays+ s.undo();+ assert_eq!(pixel(&s, 20, 50), [255, 255, 255, 255]);+ assert_eq!(pixel(&s, 50, 50), [0, 0, 0, 255]);+ // a pour taken back leaves nothing to undo for it+ assert!(s.pour_begin(80.0, 50.0, 0.0, 0.0, 1.0, 0.5));+ s.pour_end(false);+ assert_eq!(pixel(&s, 80, 50), [255, 255, 255, 255]);+ // a locked layer takes none+ assert!(s.set_layer_locked(layer, true));+ assert!(!s.pour_begin(20.0, 50.0, 1.0, 0.0, 0.0, 0.5));+}diff --git a/crates/engine/src/fill.rs b/crates/engine/src/fill.rsnew file mode 100644index 0000000..992418d--- /dev/null+++ b/crates/engine/src/fill.rs@@ -0,0 +1,247 @@+//! Filling by colour (dropping a colour on the canvas): a flood from a point over the pixels whose+//! colour is near its own, and the colour poured into it so that soft edges stay soft.++use crate::selection::Mask;++/// How far past the threshold (as a colour distance, 0..1) the fill fades out.+pub const FADE: f32 = 0.09;++/// The pixels' colour distances from a seed pixel, kept to flood again at another threshold.+pub struct Flood {+ width: u32,+ height: u32,+ seed: (u32, u32),+ /// Each pixel's distance from the seed's colour: the largest difference of their+ /// premultiplied channels, 0..255.+ distance: Vec<u8>,+ /// The seed pixel's colour (premultiplied RGBA8).+ pub colour: [u8; 4],+}++impl Flood {+ /// `pixels` (premultiplied RGBA8, `width` x `height`) measured from the pixel at `seed`; None+ /// when the seed is off the picture.+ pub fn new(width: u32, height: u32, pixels: &[u8], seed: (u32, u32)) -> Option<Flood> {+ let count = width as usize * height as usize;+ if seed.0 >= width || seed.1 >= height || pixels.len() < count * 4 {+ return None;+ }+ let i = (seed.1 as usize * width as usize + seed.0 as usize) * 4;+ let colour: [u8; 4] = pixels.get(i..i + 4)?.try_into().ok()?;+ let distance = pixels.as_chunks::<4>().0.iter().take(count).map(|p| distance(p, &colour)).collect();+ Some(Flood { width, height, seed, distance, colour })+ }++ /// How much each pixel takes the fill at `threshold` (0..1): the pixels joined to the seed+ /// through pixels within reach, fully where the distance is within the threshold, fading out+ /// over [`FADE`] past it.+ pub fn mask(&self, threshold: f32) -> Mask {+ let t = threshold.clamp(0.0, 1.0) * 255.0;+ let fade = FADE * 255.0;+ let weights: [u8; 256] = std::array::from_fn(|d| {+ let d = d as f32;+ if d <= t { 255 } else { (((t + fade - d) / fade).clamp(0.0, 1.0) * 255.0).round() as u8 }+ });+ let reach = |i: usize| self.distance.get(i).map_or(0, |&d| weights.get(usize::from(d)).copied().unwrap_or(0));+ let mut m = Mask::empty(self.width, self.height);+ let (w, h) = (self.width as usize, self.height as usize);+ // a pixel not yet filled (reached ones are at least 1) that the fill can reach+ let open = |m: &Mask, i: usize| m.data.get(i) == Some(&0) && reach(i) > 0;+ // scanlines: each span filled whole, then the runs above and below it seeded+ let mut stack = vec![(self.seed.0 as usize, self.seed.1 as usize)];+ while let Some((x, y)) = stack.pop() {+ let row = y * w;+ if !open(&m, row + x) {+ continue;+ }+ let (mut l, mut r) = (x, x);+ while l > 0 && open(&m, row + l - 1) {+ l -= 1;+ }+ while r + 1 < w && open(&m, row + r + 1) {+ r += 1;+ }+ for i in row + l..=row + r {+ if let Some(v) = m.data.get_mut(i) {+ *v = reach(i);+ }+ }+ for ny in [y.wrapping_sub(1), y + 1] {+ if ny >= h {+ continue;+ }+ let next = ny * w;+ let mut xi = l;+ while xi <= r {+ if open(&m, next + xi) {+ stack.push((xi, ny));+ while xi <= r && open(&m, next + xi) {+ xi += 1;+ }+ } else {+ xi += 1;+ }+ }+ }+ }+ m+ }+}++/// The largest difference of two premultiplied pixels' channels.+fn distance(a: &[u8; 4], b: &[u8; 4]) -> u8 {+ a.iter().zip(b).map(|(x, y)| x.abs_diff(*y)).max().unwrap_or(0)+}++/// Pours `colour` (RGB, 0..1) into `pixels` (premultiplied RGBA8) as much as `mask` takes it,+/// where the flood was measured on these same pixels from a seed of colour `seed`. What there is+/// of the seed's colour becomes the new colour, each channel scaled so that black and white stay+/// as they are (the dark edge of a line on white keeps its darkness); where the seed is+/// see-through the colour goes behind what is there, so a line's soft edge stays over it.+/// `alpha_lock` keeps each pixel's coverage.+pub fn pour(pixels: &mut [u8], mask: &Mask, seed: [u8; 4], colour: [f32; 3], alpha_lock: bool) {+ let [sr, sg, sb, sa] = seed.map(f32::from);+ let seed_a = sa / 255.0;+ let seed_rgb = [sr, sg, sb].map(|c| if sa > 0.0 { c / sa } else { 0.0 });+ let colour = colour.map(|c| c.clamp(0.0, 1.0));+ pour_with(pixels, mask, alpha_lock, |[r, g, b, a]| {+ let mut out = [0.0; 4];+ for (((o, p), s), f) in out.iter_mut().zip([r, g, b]).zip(seed_rgb).zip(colour) {+ // behind: the colour under what is there+ let behind = p + (1.0 - a) * f;+ // recoloured: the seed's colour taken to the new one, coverage kept+ let recoloured = if a > 0.0 { recolour(p / a, s, f) * a } else { 0.0 };+ *o = behind + (recoloured - behind) * seed_a;+ }+ // opaque behind, as covered as it was recoloured+ let [r, g, b, _] = out;+ [r, g, b, 1.0 + (a - 1.0) * seed_a]+ });+}++/// Pours `colour` (RGB, 0..1) over `pixels` (premultiplied RGBA8) as much as `mask` takes it: for a+/// flood measured on another layer. `alpha_lock` keeps each pixel's coverage.+pub fn pour_over(pixels: &mut [u8], mask: &Mask, colour: [f32; 3], alpha_lock: bool) {+ let [r, g, b] = colour.map(|c| c.clamp(0.0, 1.0));+ pour_with(pixels, mask, alpha_lock, |_| [r, g, b, 1.0]);+}++/// Each pixel `mask` takes moved toward what `full` (from the pixel, premultiplied 0..1) makes of+/// it, as far as the mask goes.+fn pour_with(pixels: &mut [u8], mask: &Mask, alpha_lock: bool, full: impl Fn([f32; 4]) -> [f32; 4]) {+ for (px, &m) in pixels.as_chunks_mut::<4>().0.iter_mut().zip(&mask.data) {+ if m == 0 {+ continue;+ }+ let k = f32::from(m) / 255.0;+ let p = px.map(|v| f32::from(v) / 255.0);+ let mut out = p;+ for ((o, t), q) in out.iter_mut().zip(full(p)).zip(p) {+ *o = q + (t - q) * k;+ }+ let [mut r, mut g, mut b, mut a] = out;+ if alpha_lock {+ let was = p[3];+ let scale = if a > 0.0 { was / a } else { 0.0 };+ (r, g, b, a) = (r * scale, g * scale, b * scale, was);+ }+ let a = a.clamp(0.0, 1.0);+ *px = [r.clamp(0.0, a), g.clamp(0.0, a), b.clamp(0.0, a), a].map(|v| (v * 255.0).round() as u8);+ }+}++/// A channel `p` (0..1) with the seed's `s` taken to `f`: darker than the seed scaled toward+/// black, lighter toward white.+fn recolour(p: f32, s: f32, f: f32) -> f32 {+ if p <= s { if s > 0.0 { p / s * f } else { f } } else { f + (p - s) / (1.0 - s) * (1.0 - f) }+}++#[cfg(test)]+mod tests {+ use super::*;++ const ORANGE: [f32; 3] = [1.0, 136.0 / 255.0, 72.0 / 255.0];++ /// A row of pixels, each (grey, alpha) as premultiplied black or grey over nothing.+ fn row(px: &[[u8; 4]]) -> Vec<u8> {+ px.iter().flatten().copied().collect()+ }++ #[test]+ fn the_flood_stops_at_a_line_and_fades_past_the_threshold() {+ // empty, a soft edge (alpha 0.31), the line's near-solid edge (0.91), the line, empty+ let px = row(&[[0, 0, 0, 0], [0, 0, 0, 79], [0, 0, 0, 232], [0, 0, 0, 255], [0, 0, 0, 0]]);+ let f = Flood::new(5, 1, &px, (0, 0)).unwrap();+ let m = f.mask(0.867);+ assert_eq!(m.data[0], 255);+ assert_eq!(m.data[1], 255);+ // 0.91 is 0.043 past the threshold: about half way through the fade+ assert!((110..=140).contains(&m.data[2]), "{}", m.data[2]);+ assert_eq!(m.data[3], 0);+ // beyond the line it is not joined+ assert_eq!(m.data[4], 0);+ // at the most everything is joined+ assert!(f.mask(1.0).data.iter().all(|&v| v == 255));+ assert!(Flood::new(5, 1, &px, (5, 0)).is_none());+ }++ #[test]+ fn the_flood_goes_round_corners() {+ // a wall with a gap at the bottom: the fill gets round it+ #[rustfmt::skip]+ let wall = [+ 0, 1, 0,+ 0, 1, 0,+ 0, 0, 0,+ ];+ let px: Vec<u8> = wall.iter().flat_map(|&w| if w == 1 { [0, 0, 0, 255] } else { [0, 0, 0, 0] }).collect();+ let m = Flood::new(3, 3, &px, (0, 0)).unwrap().mask(0.5);+ assert_eq!(m.data, vec![255, 0, 255, 255, 0, 255, 255, 255, 255]);+ }++ #[test]+ fn colour_goes_behind_a_soft_edge() {+ // as measured: a line's edge at alpha 0.31 over white turns into the line over the fill+ let mut px = row(&[[0, 0, 0, 0], [0, 0, 0, 79]]);+ let mask = Mask { width: 2, height: 1, data: vec![255, 255] };+ pour(&mut px, &mask, [0, 0, 0, 0], ORANGE, false);+ assert_eq!(&px[0..4], &[255, 136, 72, 255]);+ // 255 * 0.69 and so on, opaque+ assert_eq!(&px[4..8], &[176, 94, 50, 255]);+ }++ #[test]+ fn a_coloured_area_is_recoloured_keeping_its_shading() {+ // white with a grey edge: the grey takes the new colour, as dark as it was+ let mut px = row(&[[255, 255, 255, 255], [128, 128, 128, 255], [0, 0, 0, 255]]);+ let mask = Mask { width: 3, height: 1, data: vec![255, 255, 255] };+ pour(&mut px, &mask, [255, 255, 255, 255], ORANGE, false);+ assert_eq!(&px[0..4], &[255, 136, 72, 255]);+ assert_eq!(&px[4..8], &[128, 68, 36, 255]);+ assert_eq!(&px[8..12], &[0, 0, 0, 255]);+ // on black, lighter greys stay lighter+ let mut px = row(&[[0, 0, 0, 255], [255, 255, 255, 255]]);+ pour(&mut px, &Mask { width: 2, height: 1, data: vec![255, 255] }, [0, 0, 0, 255], ORANGE, false);+ assert_eq!(&px[0..4], &[255, 136, 72, 255]);+ assert_eq!(&px[4..8], &[255, 255, 255, 255]);+ }++ #[test]+ fn the_mask_weighs_the_pour_and_alpha_lock_keeps_coverage() {+ let mut px = row(&[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 128]]);+ let mask = Mask { width: 3, height: 1, data: vec![0, 128, 255] };+ let mut locked = px.clone();+ pour(&mut px, &mask, [0, 0, 0, 0], ORANGE, false);+ assert_eq!(&px[0..4], &[0, 0, 0, 0]);+ assert_eq!(px[7], 128);+ // locked: nothing where there was nothing; the half covered pixel stays half covered+ pour(&mut locked, &mask, [0, 0, 0, 0], ORANGE, true);+ assert_eq!(&locked[4..8], &[0, 0, 0, 0]);+ assert_eq!(locked[11], 128);+ assert!(locked[8] > 0);+ // over: the colour as the mask takes it+ let mut over = row(&[[0, 0, 0, 0], [0, 0, 0, 255]]);+ pour_over(&mut over, &Mask { width: 2, height: 1, data: vec![255, 255] }, ORANGE, false);+ assert_eq!(over, row(&[[255, 136, 72, 255], [255, 136, 72, 255]]));+ }+}diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 468942e..945dd2f 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -13,6 +13,7 @@ pub mod crop;pub mod curve;pub mod document;pub mod environment;+pub mod fill;pub mod formats;pub mod geom;pub mod gltf;