ProCraft for Android: An Android native painting app written in Rust
Rust
feat(color): Recolor from the QuickMenu, a reticle that fills as it moves
Josh16914f101c9d
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 4240c68..9fe2ef7 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 }+ private enum class Mode { NONE, PEN, FINGER, IDLE, GESTURE, PICK, TRANSFORM, SELECT, ADJUST, PUCK, SHAPE, HOVER, TURN, POUR, OPACITY, RECOLOR }/** The pen is hovering over the canvas. */private var penHovering = false@@ -178,6 +178,9 @@ class CanvasSurfaceView(context: Context, private val vm: CanvasViewModel) : Surprivate var chromaDragging = false/** Where on the clone source it was taken (window pixels from its centre). */private var puckGrab = Offset.Zero+ /** Recolor's touch has moved too far for a tap: it drags the reticle, from here (window pixels). */+ private var recolorDragging = false+ private var recolorLast = Offset.Zero// the two fingers a gesture follows (pointer ids) and where they wereprivate var gestureA = -1@@ -450,6 +453,13 @@ class CanvasSurfaceView(context: Context, private val vm: CanvasViewModel) : SurtapStart = e.eventTimetapPointers = 1tapMoved = 0f+ if (vm.recoloring) {+ // Recolor: a drag anywhere moves the reticle (the fill following); a tap fills from where it lands+ mode = Mode.RECOLOR+ recolorDragging = false+ recolorLast = Offset(e.x, e.y)+ return true+ }val a = vm.adjustmentif (a != null) {vm.adjustMenuAt = null@@ -615,7 +625,7 @@ class CanvasSurfaceView(context: Context, private val vm: CanvasViewModel) : Sur// a second finger takes back the fill the first one madeif (mode == Mode.POUR) vm.pourEnd(keep = false)if (mode == Mode.OPACITY) vm.liftLayerOpacity()- if (mode == Mode.FINGER || mode == Mode.IDLE || mode == Mode.TRANSFORM || mode == Mode.SELECT || mode == Mode.TURN || mode == Mode.POUR) {+ if (mode == Mode.FINGER || mode == Mode.IDLE || mode == Mode.TRANSFORM || mode == Mode.SELECT || mode == Mode.TURN || mode == Mode.POUR || mode == Mode.RECOLOR) {gestureStart = e.eventTimegestureScale = 1f}@@ -660,6 +670,14 @@ class CanvasSurfaceView(context: Context, private val vm: CanvasViewModel) : SurMode.GESTURE -> if (fingers >= 3) scrub(e) else moveGesture(e, s)Mode.SELECT -> select(e, done = false)Mode.POUR -> pour(e, done = false)+ Mode.RECOLOR -> {+ if (!recolorDragging && hypot(e.x - downX, e.y - downY) > tapSlop) recolorDragging = true+ if (recolorDragging) {+ val p = Offset(e.x, e.y)+ vm.recolorDrag(p - recolorLast)+ recolorLast = p+ }+ }Mode.OPACITY -> {val dx = (e.x - lastSelectX) / resources.displayMetrics.densityvm.dragLayerOpacity(dragStep(dx, e.eventTime - lastSelectTime))@@ -731,6 +749,7 @@ class CanvasSurfaceView(context: Context, private val vm: CanvasViewModel) : SurMode.PUCK, Mode.SHAPE, Mode.IDLE, Mode.HOVER, Mode.TURN -> UnitMode.SELECT -> select(e, done = true)Mode.POUR -> pour(e, done = true)+ Mode.RECOLOR -> if (!recolorDragging) vm.recolorTap(Offset(e.x, e.y))Mode.OPACITY -> vm.liftLayerOpacity()Mode.ADJUST -> if (vm.adjustment == Adjustment.LIQUIFY) {// still moving when it lifts, liquify carries ondiff --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 f59eb8b..5d0e811 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@@ -1940,6 +1940,7 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {fun select(tool: ToolKind) {feedback()+ endRecolor()session?.setTool(tool)this.tool = toolreadSliders()@@ -2218,7 +2219,8 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {QuickAction.REFERENCE -> changeReferenceOn(!referenceOn)QuickAction.COMPANION_MOVE -> toggleCompanionMode(CompanionMode.MOVE)QuickAction.COMPANION_ZOOM -> toggleCompanionMode(CompanionMode.ZOOM)- // nothing, Recolor (not built yet), and the adjustments (done above)+ QuickAction.RECOLOR -> toggleRecolor()+ // nothing, and the adjustments (done above)else -> Unit}}@@ -2508,8 +2510,8 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {fun toolPressed(tool: ToolKind) {endQuickShape()- if (transforming || selecting || adjustment != null) {- // leaving transform, selection or an adjustment for a tool keeps what they made, and only picks the tool+ if (transforming || selecting || adjustment != null || recoloring) {+ // leaving transform, selection, an adjustment or Recolor for a tool keeps what they made, and only picks the toolendTransform(true)closeSelecting()endAdjustment(true)@@ -4110,8 +4112,12 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {private fun applyColor() {val c = colorRgb()- session?.setColor(((c shr 16) and 0xFF) / 255f, ((c shr 8) and 0xFF) / 255f, (c and 0xFF) / 255f)+ val (r, g, b) = Triple(((c shr 16) and 0xFF) / 255f, ((c shr 8) and 0xFF) / 255f, (c and 0xFF) / 255f)+ session?.setColor(r, g, b)if (colorNames) nameColorSoon()+ // recoloring, the area under the reticle takes the new colour+ val s = session+ if (recolorOpen && s != null) pourLater("colour") { s.pourColour(r, g, b) }}private var naming: kotlinx.coroutines.Job? = null@@ -4149,6 +4155,7 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {}feedback()endQuickShape()+ if (p != Panel.COLOR) endRecolor()if (transforming) endTransform(true)endAdjustment(true)closeSelecting()@@ -4189,6 +4196,14 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {if (adjustment == Adjustment.CLONE) {puckBefore.removeLastOrNull()?.let { before -> clonePuck?.let { puckAfter.addLast(it) }; clonePuck = before }}+ // recoloring, the fill under the reticle is taken back first+ if (recolorOpen) {+ session?.let { s -> pourNow { s.pourEnd(false, null) } }+ recolorOpen = false+ showNotice("Undo $RECOLOR_STEP")+ refresh()+ return+ }val could = canUndoval name = session?.undo()if (could) showNotice("Undo" + name?.let { " $it" }.orEmpty())@@ -4222,6 +4237,17 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {if (adjustment == Adjustment.CLONE) {puckAfter.removeLastOrNull()?.let { after -> clonePuck?.let { puckBefore.addLast(it) }; clonePuck = after }}+ // recoloring, the open fill steps aside for the redo and is made again over what it brings back+ if (recolorOpen) {+ session?.let { s -> pourNow { s.pourEnd(false, null) } }+ recolorOpen = false+ val could = canRedo+ val name = session?.redo()+ if (could) showNotice("Redo" + name?.let { " $it" }.orEmpty())+ recolorPoint?.let { recolorOpen = recolorBegin(canvasToWindow(it)) }+ refresh()+ return+ }val could = canRedo// a text edit redone is edited againval text = if (textInfo == null) session?.textRedoLayer() else null@@ -4237,6 +4263,7 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {fun startAdjustment(a: Adjustment) {val s = session ?: returnif (!currentTakesChanges()) return+ endRecolor()endAdjustment(true)endTransform(true)closeSelecting()@@ -4708,11 +4735,15 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {fun adjustmentsPressed() {endQuickShape()endFilling()- // in Layer opacity, the button ends it+ // in Layer opacity or Recolor, the button ends itif (opacityLayer != null) {endLayerOpacity()return}+ if (recoloring) {+ endRecolor()+ return+ }if (adjustment != null) endAdjustment(true) else toggle(Panel.ADJUSTMENTS)}@@ -4873,10 +4904,12 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {dropBand = DropBand.FILLING}+ /** ColorDrop's filling ends, and Recolor with it. */fun endFilling() {dropBandTimer?.cancel()if (dropBand != DropBand.NONE) dropBand = DropBand.NONEdropSliding = false+ endRecolor()}/** Fills from window point [p] with the dropped colour; false if nothing was filled. */@@ -4896,22 +4929,16 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {/** 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)+ val t = threshold.coerceIn(0f, 1f)+ dropThreshold = tdropSliding = 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)- }- }+ pourLater("threshold") { s.pourThreshold(t) }}/** 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) }+ pourNow { s.pourEnd(keep, null) }if (dropSliding) transformPrefs.edit().putFloat(DROP_THRESHOLD, dropThreshold).apply()dropSliding = falserefresh()@@ -4919,13 +4946,112 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {/** 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)++ /** The latest of each kind of change waiting for the fill's thread (a threshold, a point, a colour). */+ private val pourLatest = java.util.concurrent.ConcurrentHashMap<String, () -> Unit>()++ /** Runs [block] on the fill's thread, unless another of its [kind] is given before it gets there. */+ private fun pourLater(kind: String, block: () -> Unit) {+ if (pourLatest.put(kind, block) == null) pourThread.execute { pourLatest.remove(kind)?.invoke() }+ }/** 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()+ // Recolor: the area under a reticle takes the current colour. Dragged about, the fill follows it;+ // a tap keeps the fill and starts again where it lands++ /** Recolor is on. */+ var recoloring by mutableStateOf(false)+ private set++ /** Where the reticle is, canvas pixels. */+ var recolorPoint by mutableStateOf<Offset?>(null)+ private set++ /** Recolor's threshold (its Flood slider, 0..1), kept from one time to the next. */+ var recolorThreshold by mutableFloatStateOf(transformPrefs.getFloat(RECOLOR_THRESHOLD, 0f))+ private set++ /** A fill is open under the reticle (none while the reticle is off the canvas, or once undone). */+ private var recolorOpen = false++ /** Recolor on, the reticle in the middle of the screen, or off (keeping what it filled). */+ fun toggleRecolor() {+ if (recoloring) {+ endRecolor()+ return+ }+ if (session == null || !currentTakesChanges()) return+ // text takes no colour until it is rasterized+ if (currentIsText()) {+ askRasterize = true+ return+ }+ endQuickShape()+ endFilling()+ endLayerOpacity()+ if (transforming) endTransform(true)+ endAdjustment(true)+ closeSelecting()+ closePanels()+ recoloring = true+ recolorPoint = windowToCanvas(screenCentre)+ recolorOpen = recolorBegin(screenCentre)+ refresh()+ }++ /** A fill under the reticle at window point [at]; false where there is nothing to fill. */+ private fun recolorBegin(at: Offset): Boolean {+ val s = session ?: return false+ val c = colorRgb()+ val t = recolorThreshold+ return pourNow { s.pourBegin(at.x, at.y, ((c shr 16) and 0xFF) / 255f, ((c shr 8) and 0xFF) / 255f, (c and 0xFF) / 255f, t) }+ }++ /** The reticle dragged by [by] window pixels: the fill follows it. */+ fun recolorDrag(by: Offset) {+ val s = session ?: return+ val from = recolorPoint?.let(::canvasToWindow) ?: screenCentre+ val at = from + by+ recolorPoint = windowToCanvas(at) ?: return+ if (!recolorOpen) {+ recolorOpen = recolorBegin(at)+ return+ }+ pourLater("point") { s.pourMove(at.x, at.y) }+ }++ /** A tap while recoloring: the fill so far is kept, and the reticle starts again at [p]. */+ fun recolorTap(p: Offset) {+ val s = session ?: return+ if (recolorOpen) pourNow { s.pourEnd(true, RECOLOR_STEP) }+ recolorOpen = false+ recolorPoint = windowToCanvas(p) ?: return+ recolorOpen = recolorBegin(p)+ refresh()+ }++ /** The Flood slider moved to [t]: the fill redone with it. */+ fun recolorThresholdTo(t: Float) {+ val s = session ?: return+ val v = t.coerceIn(0f, 1f)+ recolorThreshold = v+ if (recolorOpen) pourLater("threshold") { s.pourThreshold(v) }+ }++ /** Recolor ends, keeping what it filled. */+ fun endRecolor() {+ if (!recoloring) return+ val s = session+ if (recolorOpen && s != null) pourNow { s.pourEnd(true, RECOLOR_STEP) }+ recolorOpen = false+ recoloring = false+ recolorPoint = null+ transformPrefs.edit().putFloat(RECOLOR_THRESHOLD, recolorThreshold).apply()+ refresh()+ }+fun invertSelection() {session?.selectInvert()selectionChanged(fill = false)@@ -5778,6 +5904,10 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {private const val SELECTION_KIND = "selectionKind"private const val SELECTION_THRESHOLD = "selectionThreshold"private const val DROP_THRESHOLD = "dropThreshold"+ private const val RECOLOR_THRESHOLD = "recolorThreshold"++ /** What undo and redo call a Recolor fill. */+ private const val RECOLOR_STEP = "Recolor"/** A video's frames come in at Animation Assist's starting frame rate unless it is on. */private const val DEFAULT_FPS = 15diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/QuickActions.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/QuickActions.ktindex eac79de..a524cfc 100644--- a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/QuickActions.kt+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/QuickActions.kt@@ -52,7 +52,7 @@ enum class QuickAction(val label: String, val adjustment: Adjustment? = null, vaQUICKSHAPE_ON("QuickShape"),QUICKSHAPE("QuickShape stroke"),// not built yet: left out of the picker- RECOLOR("Recolor", ready = false),+ RECOLOR("Recolor"),REDO("Redo"),REFERENCE("Reference"),BRUSHES("Select brush"),diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AdjustmentsUi.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AdjustmentsUi.ktindex 82ebd55..cfaef16 100644--- a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AdjustmentsUi.kt+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AdjustmentsUi.kt@@ -908,6 +908,34 @@ fun AdjustModes(vm: CanvasViewModel, modifier: Modifier = Modifier) {}}+/**+ * Recolor's reticle: four short bars around the point it fills from, 44 across, black over a light+ * colour and white over a dark one.+ */+@Composable+fun RecolorReticle(vm: CanvasViewModel) {+ val at = vm.recolorPoint?.let(vm::canvasToWindow) ?: return+ val c = vm.colorRgb()+ val light = 0.2126f * ((c shr 16) and 0xFF) + 0.7152f * ((c shr 8) and 0xFF) + 0.0722f * (c and 0xFF) > 0.5f * 255f+ val ink = if (light) Color.Black else Color.White+ androidx.compose.foundation.Canvas(Modifier.fillMaxSize()) {+ val gap = 2.5.dp.toPx()+ val reach = 11.5.dp.toPx()+ val w = 1.dp.toPx()+ for ((dx, dy) in listOf(1f to 0f, -1f to 0f, 0f to 1f, 0f to -1f)) {+ drawLine(ink, at + Offset(dx * gap, dy * gap), at + Offset(dx * reach, dy * reach), w)+ }+ }+}++/** Recolor's toolbar: the Flood slider, how far from the colour under the reticle the fill reaches. */+@Composable+fun RecolorPanel(vm: CanvasViewModel, modifier: Modifier = Modifier) {+ OptionsPanel(332.dp, 70.dp, modifier, 8.dp) {+ OptionSlider("Flood", vm.recolorThreshold, "${(vm.recolorThreshold * 100).roundToInt()}%", 300.dp) { vm.recolorThresholdTo(it) }+ }+}+/** The clone source: a dark ring with a light edge, so it shows on any colour. */@Composablefun ClonePuck(vm: CanvasViewModel) {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 dcb74cd..cb91f62 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@@ -223,6 +223,7 @@ fun AppRoot(vm: CanvasViewModel) {ZoomingGallery(vm, overlay = true)GuideOverlay(vm)if (vm.adjustment == Adjustment.CLONE) ClonePuck(vm)+ if (vm.recoloring) RecolorReticle(vm)QuickShapeHandles(vm)if (!vm.barsHidden) AnimationBar(vm)CopyPastePanel(vm)@@ -261,6 +262,12 @@ fun AppRoot(vm: CanvasViewModel) {}}}+ androidx.compose.animation.AnimatedVisibility(+ vm.recoloring && !vm.barsHidden,+ Modifier.align(Alignment.BottomCenter),+ enter = Motion.toolbarIn(),+ exit = Motion.toolbarOut(),+ ) { RecolorPanel(vm, Modifier) }androidx.compose.animation.AnimatedVisibility(vm.selecting && !vm.barsHidden,Modifier.align(Alignment.BottomCenter),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 e0d395c..6e08a04 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@@ -79,7 +79,7 @@ fun TopBar(vm: CanvasViewModel, modifier: Modifier = Modifier) {Text("Gallery", color = Pc.BarText, fontSize = 18.sp, fontWeight = FontWeight.Medium, maxLines = 1, softWrap = false, modifier = Modifier.offset(y = (-1).dp))}ActionButton(PcIcons.Actions, "Actions", selected = vm.panel == Panel.ACTIONS) { vm.toggle(Panel.ACTIONS) }- ActionButton(PcIcons.Adjustments, "Adjustments", selected = vm.panel == Panel.ADJUSTMENTS || vm.adjustment != null || vm.opacityLayer != null) { vm.adjustmentsPressed() }+ ActionButton(PcIcons.Adjustments, "Adjustments", selected = vm.panel == Panel.ADJUSTMENTS || vm.adjustment != null || vm.opacityLayer != null || vm.recoloring) { vm.adjustmentsPressed() }ActionButton(PcIcons.Selection, "Selection", selected = vm.selecting, glyph = 33.dp) { vm.toggleSelecting() }ActionButton(PcIcons.Transform, "Transform", selected = vm.transforming, glyph = 44.dp) { vm.toggleTransform() }}diff --git a/apps/procraft-android/src/pour.rs b/apps/procraft-android/src/pour.rsindex 6482f28..7acf5ee 100644--- a/apps/procraft-android/src/pour.rs+++ b/apps/procraft-android/src/pour.rs@@ -1,7 +1,7 @@//! 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.+//! undo step. Recolor keeps a pour open while its point moves and its colour changes.use procraft_engine::document::LayerId;use procraft_engine::fill::{self, Flood};@@ -15,9 +15,10 @@ 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,+ /// The area measured from the point; none while the point is off the canvas.+ flood: Option<Flood>,+ /// The reference layer's pixels when measured on it, so poured over this one.+ elsewhere: Option<Vec<u8>>,colour: [f32; 3],selection: Option<Mask>,alpha_lock: bool,@@ -28,26 +29,50 @@ pub(crate) struct Pour {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);+ let Some(flood) = &self.flood else { return self.before.clone() };+ let mut mask = 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 {+ if self.elsewhere.is_some() {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);+ fill::pour(&mut pixels, &mask, flood.colour, self.colour, self.alpha_lock);}pixels}++ /// The area measured again from canvas point `seed`, on the reference layer or the layer as+ /// it was.+ fn measure(&mut self, width: u32, height: u32, seed: (u32, u32)) {+ let sample = self.elsewhere.as_deref().unwrap_or(&self.before);+ self.flood = Flood::new(width, height, sample, seed);+ }++ /// The pour as it now is, for the layer.+ fn shown(&self) -> Vec<u8> {+ self.poured(self.shown as f32 / 1000.0)+ }}fn thousandths(threshold: f32) -> i32 {(threshold.clamp(0.0, 1.0) * 1000.0).round() as i32}+fn unit(c: f32) -> f32 {+ if c.is_finite() { c.clamp(0.0, 1.0) } else { 0.0 }+}++/// The canvas pixel under window point (`x`, `y`), if it is on the canvas.+fn seed_at(st: &crate::State, x: f32, y: f32) -> Option<(u32, u32)> {+ let p = st.view.and_then(|v| v.screen_to_canvas(Vec2::new(x, y)))?;+ let (w, h) = (st.doc.width(), st.doc.height());+ (p.x >= 0.0 && p.y >= 0.0 && p.x < w as f32 && p.y < h as f32).then_some((p.x as u32, p.y as u32))+}+#[uniffi::export]impl CanvasSession {/// Pours colour (`r`, `g`, `b`, 0..1) at window point (`x`, `y`) with `threshold` (0..1) on@@ -55,39 +80,33 @@ impl CanvasSession {/// 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);+ self.pour_end(true, None);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 Some(seed) = seed_at(st, 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 {+ let elsewhere = st.doc.reference().filter(|&r| r != current).and_then(|r| st.layer_pixels(r));+ let mut pour = Pour {layer: current,before,- flood,- elsewhere: reference.is_some(),- colour,+ flood: None,+ elsewhere,+ colour: [r, g, b].map(unit),selection: st.selection.clone(),alpha_lock: layer.alpha_lock,shown: thousandths(threshold),};+ pour.measure(w, h, seed);+ if pour.flood.is_none() {+ return false;+ }let pixels = pour.poured(threshold);if let Some(canvas) = st.canvas.as_mut() {canvas.hold_layer(current);@@ -98,6 +117,43 @@ impl CanvasSession {true}+ /// The open pour redone from window point (`x`, `y`) instead, from the layer as it was: off+ /// the canvas it pours nothing until it comes back. False if no pour is open.+ pub fn pour_move(&self, x: f32, y: f32) -> bool {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let seed = seed_at(st, x, y);+ let (w, h) = (st.doc.width(), st.doc.height());+ let Some(pour) = st.pour.as_mut() else { return false };+ match seed {+ Some(seed) => pour.measure(w, h, seed),+ None => pour.flood = None,+ }+ let (layer, pixels) = (pour.layer, pour.shown());+ if let Some(canvas) = st.canvas.as_mut() {+ canvas.put_layer(layer, pixels);+ }+ self.shared.frame(st);+ true+ }++ /// The open pour redone with colour (`r`, `g`, `b`, 0..1).+ pub fn pour_colour(&self, r: f32, g: f32, b: f32) {+ let mut guard = self.shared.lock();+ let st = &mut *guard;+ let Some(pour) = st.pour.as_mut() else { return };+ let colour = [r, g, b].map(unit);+ if colour == pour.colour {+ return;+ }+ pour.colour = colour;+ let (layer, pixels) = (pour.layer, pour.shown());+ if let Some(canvas) = st.canvas.as_mut() {+ canvas.put_layer(layer, pixels);+ }+ self.shared.frame(st);+ }+/// The open pour redone at `threshold` (0..1).pub fn pour_threshold(&self, threshold: f32) {let mut guard = self.shared.lock();@@ -108,22 +164,24 @@ impl CanvasSession {return;}pour.shown = t;- let (layer, pixels) = (pour.layer, pour.poured(threshold));+ let (layer, pixels) = (pour.layer, pour.shown());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) {+ /// Ends the open pour: `keep` makes it one undo step, called `name` if given; otherwise (or+ /// with nothing poured) the layer goes back to how it was.+ pub fn pour_end(&self, keep: bool, name: Option<String>) {let mut guard = self.shared.lock();let st = &mut *guard;- if st.pour.take().is_none() {- return;- }+ let Some(pour) = st.pour.take() else { return };+ let keep = keep && pour.flood.is_some();if let Some(canvas) = st.canvas.as_mut() {+ if let Some(name) = name.filter(|_| keep) {+ canvas.name_next_step(&name);+ }canvas.release_layer(keep, None);}st.revision += 1;diff --git a/apps/procraft-android/src/tests.rs b/apps/procraft-android/src/tests.rsindex f93118f..2e04faf 100644--- a/apps/procraft-android/src/tests.rs+++ b/apps/procraft-android/src/tests.rs@@ -2609,7 +2609,7 @@ fn a_dropped_colour_fills_up_to_lines_and_is_one_undo_step() {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);+ s.pour_end(true, None);assert_eq!(pixel(&s, 20, 50), [255, 0, 0, 255]);// one undo takes the pour back; the line stayss.undo();@@ -2617,13 +2617,49 @@ fn a_dropped_colour_fills_up_to_lines_and_is_one_undo_step() {assert_eq!(pixel(&s, 50, 50), [0, 0, 0, 255]);// a pour taken back leaves nothing to undo for itassert!(s.pour_begin(80.0, 50.0, 0.0, 0.0, 1.0, 0.5));- s.pour_end(false);+ s.pour_end(false, None);assert_eq!(pixel(&s, 80, 50), [255, 255, 255, 255]);// a locked layer takes noneassert!(s.set_layer_locked(layer, true));assert!(!s.pour_begin(20.0, 50.0, 1.0, 0.0, 0.0, 0.5));}+#[test]+fn recolor_follows_its_point_and_colour_and_is_a_named_step() {+ let Some(s) = session(100, 100) else { return };+ s.set_brush_size(0.4);+ 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)]);+ // nothing open, nothing to move+ assert!(!s.pour_move(80.0, 50.0));+ assert!(s.pour_begin(20.0, 50.0, 1.0, 0.0, 0.0, 0.0));+ assert_eq!(pixel(&s, 20, 50), [255, 0, 0, 255]);+ // moved across the line: the left half as it was, the right half filled+ assert!(s.pour_move(80.0, 50.0));+ assert_eq!(pixel(&s, 20, 50), [255, 255, 255, 255]);+ assert_eq!(pixel(&s, 80, 50), [255, 0, 0, 255]);+ // a new colour refills+ s.pour_colour(0.0, 0.0, 1.0);+ assert_eq!(pixel(&s, 80, 50), [0, 0, 255, 255]);+ // off the canvas nothing is filled, back on it is again+ assert!(s.pour_move(-5.0, 50.0));+ assert_eq!(pixel(&s, 80, 50), [255, 255, 255, 255]);+ assert!(s.pour_move(80.0, 50.0));+ s.pour_end(true, Some("Recolor".to_owned()));+ assert_eq!(pixel(&s, 80, 50), [0, 0, 255, 255]);+ assert_eq!(s.undo().as_deref(), Some("Recolor"));+ assert_eq!(pixel(&s, 80, 50), [255, 255, 255, 255]);+ s.redo();+ // ended off the canvas, it makes no step+ assert!(s.pour_begin(20.0, 50.0, 0.0, 1.0, 0.0, 0.0));+ assert!(s.pour_move(-5.0, 50.0));+ s.pour_end(true, Some("Recolor".to_owned()));+ assert_eq!(pixel(&s, 20, 50), [255, 255, 255, 255]);+ assert_eq!(s.undo().as_deref(), Some("Recolor"));+ assert_eq!(pixel(&s, 80, 50), [255, 255, 255, 255]);+}+#[test]fn a_layered_psd_comes_in_as_an_artwork() {use procraft_engine::document::BlendMode;