Modern Apps git

← Modern-Apps.git

photos: use androidx.ink

Commit
fb7fdf54d10aa476e3d93de01aee2935feca5083
Author
Vayun Mathur <[email protected]>
When
2026-06-12 21:05 UTC (5 months ago)
Parents
e13e818

Diff

gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex 0ca77a1e51..423c5bb514 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -58,6 +58,7 @@ libphonenumber = "9.0.32" material3AdaptiveNavigationSuite = "1.4.0" maplibre = "0.13.0" foundation = "1.11.2"+ink = "1.0.0" protobuf = "4.35.0" keepassJava2 = "2.2.4" zxing = "3.5.4"@@ -78,6 +79,7 @@ androidx-camera-core = { group = "androidx.camera", name = "camera-core", versio androidx-camera-camera2 = { group = "androidx.camera", name = "camera-camera2", version.ref = "camerax" } androidx-camera-lifecycle = { group = "androidx.camera", name = "camera-lifecycle", version.ref = "camerax" } androidx-camera-view = { group = "androidx.camera", name = "camera-view", version.ref = "camerax" }+androidx-camera-video = { group = "androidx.camera", name = "camera-video", version.ref = "camerax" } androidx-webkit = { group = "androidx.webkit", name = "webkit", version.ref = "webkit" } geckoview = { module = "org.mozilla.geckoview:geckoview-arm64-v8a", version.ref = "geckoview" } jsoup = { module = "org.jsoup:jsoup", version.ref = "jsoup" }@@ -159,6 +161,11 @@ kotlin-serialization-gradle = { module = "org.jetbrains.kotlin:kotlin-serializat sqlcipher-android = { module = "net.zetetic:sqlcipher-android", version.ref = "sqlcipherAndroid" } symbol-processing-gradle-plugin = { module = "com.google.devtools.ksp:symbol-processing-gradle-plugin", version.ref = "ksp" } androidx-compose-foundation = { group = "androidx.compose.foundation", name = "foundation", version.ref = "foundation" }+androidx-ink-authoring = { group = "androidx.ink", name = "ink-authoring", version.ref = "ink" }+androidx-ink-brush = { group = "androidx.ink", name = "ink-brush", version.ref = "ink" }+androidx-ink-strokes = { group = "androidx.ink", name = "ink-strokes", version.ref = "ink" }+androidx-ink-rendering = { group = "androidx.ink", name = "ink-rendering", version.ref = "ink" }+androidx-ink-geometry = { group = "androidx.ink", name = "ink-geometry", version.ref = "ink" } protobuf-java = { module = "com.google.protobuf:protobuf-java", version.ref = "protobuf" } zxing-core = { module = "com.google.zxing:core", version.ref = "zxing" } keepassjava2-dom = { module = "org.linguafranca.pwdb:KeePassJava2-dom", version.ref = "keepassJava2" }
library/build.gradle.kts
diff --git a/library/build.gradle.kts b/library/build.gradle.ktsindex 2d7c68b9f5..a69d4109f1 100644--- a/library/build.gradle.kts+++ b/library/build.gradle.kts@@ -24,4 +24,11 @@ dependencies {     implementation(libs.androidx.webkit)      api(libs.material)++    // Ink+    api(libs.androidx.ink.authoring)+    api(libs.androidx.ink.brush)+    api(libs.androidx.ink.strokes)+    api(libs.androidx.ink.rendering)+    api(libs.androidx.ink.geometry) }\ No newline at end of file
library/src/main/java/com/vayunmathur/library/ui/InkCanvasView.kt
diff --git a/library/src/main/java/com/vayunmathur/library/ui/InkCanvasView.kt b/library/src/main/java/com/vayunmathur/library/ui/InkCanvasView.ktnew file mode 100644index 0000000000..b6d12da402--- /dev/null+++ b/library/src/main/java/com/vayunmathur/library/ui/InkCanvasView.kt@@ -0,0 +1,216 @@+package com.vayunmathur.library.ui++import android.annotation.SuppressLint+import android.content.Context+import android.graphics.Matrix+import android.graphics.Paint+import android.graphics.RectF+import android.view.MotionEvent+import android.view.View+import android.widget.FrameLayout+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.viewinterop.AndroidView+import androidx.ink.authoring.InProgressStrokesFinishedListener+import androidx.ink.authoring.InProgressStrokesView+import androidx.ink.brush.Brush+import androidx.ink.rendering.android.canvas.CanvasStrokeRenderer+import androidx.ink.strokes.Stroke++data class CanvasTextElement(+    val text: String,+    val x: Float,+    val y: Float,+    val rotation: Float,+    val color: Int,+    val fontSize: Float,+)++private class FinishedStrokesView(context: Context) : View(context) {+    var strokes: List<Stroke> = emptyList()+    var textElements: List<CanvasTextElement> = emptyList()+    var selectedStrokeIndex: Int? = null+    var selectedTextIndex: Int? = null+    private val renderer = CanvasStrokeRenderer.create()+    private val identityMatrix = Matrix()+    private val textPaint = Paint().apply { isAntiAlias = true }+    private val selectionPaint = Paint().apply {+        style = Paint.Style.STROKE+        strokeWidth = 3f+        color = android.graphics.Color.WHITE+    }+    private val selectionFillPaint = Paint().apply {+        style = Paint.Style.FILL+        color = android.graphics.Color.argb(40, 255, 255, 255)+    }++    override fun onDraw(canvas: android.graphics.Canvas) {+        super.onDraw(canvas)+        strokes.forEachIndexed { index, stroke ->+            renderer.draw(canvas, stroke, identityMatrix)+            if (selectedStrokeIndex == index) {+                stroke.shape.computeBoundingBox()?.let { box ->+                    val rect = RectF(box.xMin - 4f, box.yMin - 4f, box.xMax + 4f, box.yMax + 4f)+                    canvas.drawRect(rect, selectionFillPaint)+                    canvas.drawRect(rect, selectionPaint)+                }+            }+        }++        textElements.forEachIndexed { index, elem ->+            canvas.save()+            canvas.translate(elem.x, elem.y)+            canvas.rotate(elem.rotation)++            textPaint.color = elem.color+            textPaint.textSize = elem.fontSize * resources.displayMetrics.density++            canvas.drawText(elem.text, 0f, textPaint.textSize, textPaint)++            if (selectedTextIndex == index) {+                val textWidth = textPaint.measureText(elem.text)+                val textHeight = textPaint.textSize+                val rect = RectF(-4f, -4f, textWidth + 4f, textHeight + 8f)+                canvas.drawRect(rect, selectionFillPaint)+                canvas.drawRect(rect, selectionPaint)+            }++            canvas.restore()+        }+    }+}++private class InkState {+    var currentBrush: Brush? = null+    var enabled: Boolean = true+    var eraserMode: Boolean = false+    var onStrokeErased: ((Stroke) -> Unit)? = null+    var onStrokeFinished: ((Stroke) -> Unit)? = null+}++@Composable+fun InkCanvasView(+    currentBrush: Brush,+    finishedStrokes: List<Stroke>,+    onStrokeFinished: (Stroke) -> Unit,+    onStrokeErased: ((Stroke) -> Unit)? = null,+    eraserMode: Boolean = false,+    enabled: Boolean = true,+    textElements: List<CanvasTextElement> = emptyList(),+    selectedStrokeIndex: Int? = null,+    selectedTextIndex: Int? = null,+    modifier: Modifier = Modifier,+) {+    AndroidView(+        factory = { context ->+            val frameLayout = FrameLayout(context)+            val state = InkState()++            val inProgressStrokesView = InProgressStrokesView(context)+            frameLayout.addView(inProgressStrokesView)++            val finishedStrokesView = FinishedStrokesView(context)+            frameLayout.addView(finishedStrokesView)++            @SuppressLint("ClickableViewAccessibility")+            val touchView = View(context).apply {+                setOnTouchListener(StrokeTouchListener(+                    inProgressStrokesView = inProgressStrokesView,+                    finishedStrokesView = finishedStrokesView,+                    state = state,+                ))+            }+            frameLayout.addView(touchView)++            inProgressStrokesView.addFinishedStrokesListener(object : InProgressStrokesFinishedListener {+                override fun onStrokesFinished(strokes: Map<androidx.ink.authoring.InProgressStrokeId, Stroke>) {+                    strokes.values.forEach { stroke ->+                        state.onStrokeFinished?.invoke(stroke)+                    }+                    inProgressStrokesView.removeFinishedStrokes(strokes.keys)+                }+            })++            frameLayout.tag = arrayOf(finishedStrokesView, state)+            frameLayout+        },+        update = { frameLayout ->+            val tags = frameLayout.tag as Array<*>+            val finishedStrokesView = tags[0] as FinishedStrokesView+            val state = tags[1] as InkState++            state.currentBrush = currentBrush+            state.enabled = enabled+            state.eraserMode = eraserMode+            state.onStrokeErased = onStrokeErased+            state.onStrokeFinished = onStrokeFinished++            finishedStrokesView.strokes = finishedStrokes+            finishedStrokesView.textElements = textElements+            finishedStrokesView.selectedStrokeIndex = selectedStrokeIndex+            finishedStrokesView.selectedTextIndex = selectedTextIndex+            finishedStrokesView.invalidate()+        },+        modifier = modifier.fillMaxSize(),+    )+}++private class StrokeTouchListener(+    private val inProgressStrokesView: InProgressStrokesView,+    private val finishedStrokesView: FinishedStrokesView,+    private val state: InkState,+) : View.OnTouchListener {++    @SuppressLint("ClickableViewAccessibility")+    override fun onTouch(v: View, event: MotionEvent): Boolean {+        if (!state.enabled) return false++        if (state.eraserMode) {+            if (event.actionMasked == MotionEvent.ACTION_DOWN ||+                event.actionMasked == MotionEvent.ACTION_MOVE+            ) {+                val touchX = event.x+                val touchY = event.y+                val hitRadius = 20f+                finishedStrokesView.strokes.lastOrNull { stroke ->+                    stroke.shape.computeBoundingBox()?.let { box ->+                        box.xMin <= touchX + hitRadius && box.xMax >= touchX - hitRadius &&+                            box.yMin <= touchY + hitRadius && box.yMax >= touchY - hitRadius+                    } ?: false+                }?.let { hitStroke ->+                    state.onStrokeErased?.invoke(hitStroke)+                }+            }+            return true+        }++        val brush = state.currentBrush ?: return false+        val pointerId = event.getPointerId(event.actionIndex)++        return when (event.actionMasked) {+            MotionEvent.ACTION_DOWN -> {+                v.requestUnbufferedDispatch(event)+                inProgressStrokesView.startStroke(event, pointerId, brush)+                true+            }++            MotionEvent.ACTION_MOVE -> {+                inProgressStrokesView.addToStroke(event, pointerId)+                true+            }++            MotionEvent.ACTION_UP -> {+                inProgressStrokesView.finishStroke(event, pointerId)+                true+            }++            MotionEvent.ACTION_CANCEL -> {+                inProgressStrokesView.cancelStroke(event, pointerId)+                true+            }++            else -> false+        }+    }+}
library/src/main/java/com/vayunmathur/library/util/InkSerialization.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/InkSerialization.kt b/library/src/main/java/com/vayunmathur/library/util/InkSerialization.ktnew file mode 100644index 0000000000..7dc85a1dfd--- /dev/null+++ b/library/src/main/java/com/vayunmathur/library/util/InkSerialization.kt@@ -0,0 +1,121 @@+package com.vayunmathur.library.util++import androidx.ink.brush.Brush+import androidx.ink.brush.BrushFamily+import androidx.ink.brush.InputToolType+import androidx.ink.brush.StockBrushes+import androidx.ink.strokes.MutableStrokeInputBatch+import androidx.ink.strokes.Stroke+import androidx.ink.strokes.StrokeInput+import kotlinx.serialization.Serializable+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++@Serializable+data class SerializedStroke(+    val brushFamily: String,+    val brushSize: Float,+    val brushColor: Int,+    val brushEpsilon: Float,+    val points: List<SerializedPoint>,+)++@Serializable+data class SerializedPoint(+    val x: Float,+    val y: Float,+    val timeMillis: Long,+    val pressure: Float = 1f,+    val tiltRadians: Float = 0f,+    val orientationRadians: Float = 0f,+)++private val brushFamilyMap: Map<String, BrushFamily> by lazy {+    mapOf(+        "pressurePen" to StockBrushes.pressurePen(),+        "highlighter" to StockBrushes.highlighter(),+        "marker" to StockBrushes.marker(),+    )+}++private val reverseBrushFamilyMap: Map<BrushFamily, String> by lazy {+    brushFamilyMap.entries.associate { (k, v) -> v to k }+}++fun BrushFamily.toName(): String = reverseBrushFamilyMap[this] ?: "pressurePen"++fun String.toBrushFamily(): BrushFamily = brushFamilyMap[this] ?: StockBrushes.pressurePen()++fun Stroke.serialize(): SerializedStroke {+    val inputs = this.inputs+    val points = (0 until inputs.size).map { i ->+        val si = inputs[i]+        SerializedPoint(+            x = si.x,+            y = si.y,+            timeMillis = si.elapsedTimeMillis,+            pressure = si.pressure,+            tiltRadians = si.tiltRadians,+            orientationRadians = si.orientationRadians,+        )+    }+    return SerializedStroke(+        brushFamily = brush.family.toName(),+        brushSize = brush.size,+        brushColor = brush.colorIntArgb,+        brushEpsilon = brush.epsilon,+        points = points,+    )+}++fun SerializedStroke.deserialize(): Stroke {+    val family = brushFamily.toBrushFamily()+    val brush = Brush.createWithColorIntArgb(+        family = family,+        colorIntArgb = brushColor,+        size = brushSize,+        epsilon = brushEpsilon,+    )+    val batch = MutableStrokeInputBatch()+    val input = StrokeInput()+    points.forEach { p ->+        input.update(+            x = p.x,+            y = p.y,+            elapsedTimeMillis = p.timeMillis,+            toolType = InputToolType.TOUCH,+            pressure = p.pressure,+            tiltRadians = p.tiltRadians,+            orientationRadians = p.orientationRadians,+        )+        batch.add(input)+    }+    return Stroke(brush, batch)+}++private val json = Json { ignoreUnknownKeys = true }++fun SerializedStroke.toBytes(): ByteArray = json.encodeToString(this).encodeToByteArray()++fun ByteArray.toSerializedStroke(): SerializedStroke =+    json.decodeFromString(this.decodeToString())++fun Stroke.translate(dx: Float, dy: Float): Stroke {+    val inputs = this.inputs+    val batch = MutableStrokeInputBatch()+    val input = StrokeInput()+    for (i in 0 until inputs.size) {+        val si = inputs[i]+        input.update(+            x = si.x + dx,+            y = si.y + dy,+            elapsedTimeMillis = si.elapsedTimeMillis,+            toolType = InputToolType.TOUCH,+            pressure = si.pressure,+            tiltRadians = si.tiltRadians,+            orientationRadians = si.orientationRadians,+        )+        batch.add(input)+    }+    return Stroke(brush, batch)+}
photos/src/main/java/com/vayunmathur/photos/data/Drawing.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/Drawing.kt b/photos/src/main/java/com/vayunmathur/photos/data/Drawing.ktindex 10a06c527b..ea6c6fcb62 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/Drawing.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/Drawing.kt@@ -1,20 +1,28 @@ package com.vayunmathur.photos.data  import androidx.compose.ui.geometry.Offset+import androidx.ink.brush.Brush+import androidx.ink.brush.StockBrushes import kotlinx.serialization.Serializable  @Serializable enum class DrawingTool { Pointer, Pen, Highlighter, Eraser, Text } -@Serializable-data class Drawing(-    val id: String,-    val points: List<SerializableOffset>,-    val tool: DrawingTool,-    val color: Int,-    val strokeWidth: Float,-    val opacity: Float,-)+fun DrawingTool.toBrush(color: Int, size: Float): Brush? = when (this) {+    DrawingTool.Pen -> Brush.createWithColorIntArgb(+        family = StockBrushes.pressurePen(),+        colorIntArgb = color,+        size = size,+        epsilon = 0.1f,+    )+    DrawingTool.Highlighter -> Brush.createWithColorIntArgb(+        family = StockBrushes.highlighter(),+        colorIntArgb = color,+        size = size,+        epsilon = 0.1f,+    )+    else -> null+}  @Serializable data class TextElement(
photos/src/main/java/com/vayunmathur/photos/ui/DrawingSettingsPage.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/DrawingSettingsPage.kt b/photos/src/main/java/com/vayunmathur/photos/ui/DrawingSettingsPage.ktindex 3e7fdb8ba2..f9a932afde 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/DrawingSettingsPage.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/DrawingSettingsPage.kt@@ -90,7 +90,7 @@ fun DrawingSettingsPage(                 Slider(                     value = thickness,                     onValueChange = { thickness = it },-                    valueRange = 1f..100f,+                    valueRange = if (tool == DrawingTool.Highlighter) 5f..80f else 1f..50f,                     modifier = Modifier.weight(1f)                 )                 Text(thickness.roundToInt().toString(), color = Color.White, modifier = Modifier.padding(start = 8.dp))
photos/src/main/java/com/vayunmathur/photos/ui/EditPhotoPage.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/EditPhotoPage.kt b/photos/src/main/java/com/vayunmathur/photos/ui/EditPhotoPage.ktindex f5c7a0d172..90a8dbdeb9 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/EditPhotoPage.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/EditPhotoPage.kt@@ -1,7 +1,6 @@ package com.vayunmathur.photos.ui  import androidx.activity.compose.LocalActivity-import androidx.compose.foundation.Canvas import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.gestures.detectDragGestures@@ -23,6 +22,7 @@ import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.IconButton+import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text@@ -32,36 +32,34 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue-import androidx.compose.runtime.key import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember-import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier-import androidx.compose.ui.draw.rotate import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect-import androidx.compose.ui.graphics.BlendMode+import androidx.compose.ui.graphics.Canvas import androidx.compose.ui.graphics.Color-import androidx.compose.ui.graphics.CompositingStrategy import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.PathFillType-import androidx.compose.ui.graphics.StrokeCap-import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.drawscope.Stroke-import androidx.compose.ui.graphics.drawscope.drawIntoCanvas import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.graphics.toArgb-import com.vayunmathur.photos.data.Drawing import com.vayunmathur.photos.data.DrawingTool import com.vayunmathur.photos.data.TextElement-import com.vayunmathur.photos.data.toSerializable+import com.vayunmathur.photos.data.toBrush import com.vayunmathur.library.util.ResultEffect+import com.vayunmathur.library.util.SerializedStroke+import com.vayunmathur.library.util.deserialize+import com.vayunmathur.library.util.serialize+import com.vayunmathur.library.ui.CanvasTextElement+import com.vayunmathur.library.ui.InkCanvasView+import com.vayunmathur.library.util.translate import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.stringResource@@ -73,6 +71,9 @@ import androidx.compose.ui.window.Dialog import androidx.core.net.toUri import androidx.compose.foundation.Image import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.ink.brush.Brush+import androidx.ink.brush.StockBrushes+import androidx.ink.strokes.Stroke as InkStroke import com.vayunmathur.library.ui.IconBrush import com.vayunmathur.library.ui.IconCheck import com.vayunmathur.library.ui.IconClose@@ -94,27 +95,6 @@ import com.vayunmathur.photos.util.PhotoEditViewModel import java.util.UUID import kotlin.math.roundToInt -fun Drawing.computeBoundingBox(width: Float, height: Float): Rect {-    if (points.isEmpty()) return Rect.Zero-    var minX = points[0].x-    var maxX = points[0].x-    var minY = points[0].y-    var maxY = points[0].y-    points.forEach { p ->-        minX = minOf(minX, p.x)-        maxX = maxOf(maxX, p.x)-        minY = minOf(minY, p.y)-        maxY = maxOf(maxY, p.y)-    }-    val padding = 0.02f-    return Rect(-        (minX - padding) * width,-        (minY - padding) * height,-        (maxX + padding) * width,-        (maxY + padding) * height-    )-}- @OptIn(ExperimentalMaterial3Api::class) @Composable fun EditPhotoPage(@@ -143,7 +123,6 @@ fun EditPhotoPage(             )         }     }-    val scope = rememberCoroutineScope()      var isCropping by remember { mutableStateOf(false) }     var rotation by remember { mutableFloatStateOf(0f) }@@ -152,19 +131,18 @@ fun EditPhotoPage(     var showSaveMenu by remember { mutableStateOf(false) }      var isDrawing by remember { mutableStateOf(false) }-    val currentDrawingPoints = remember { mutableStateListOf<Offset>() }-    val drawings = remember { mutableStateListOf<Drawing>() }+    val inkStrokes = remember { mutableStateListOf<InkStroke>() }      var activeTool by remember { mutableStateOf(DrawingTool.Pointer) }      var penColor by remember { mutableStateOf(Color.Red) }-    var penWidth by remember { mutableFloatStateOf(10f) }+    var penSize by remember { mutableFloatStateOf(10f) }      var highlighterColor by remember { mutableStateOf(Color.Yellow) }-    var highlighterWidth by remember { mutableFloatStateOf(40f) }+    var highlighterSize by remember { mutableFloatStateOf(40f) }     var highlighterOpacity by remember { mutableFloatStateOf(0.5f) } -    var eraserWidth by remember { mutableFloatStateOf(30f) }+    var textFontSize by remember { mutableFloatStateOf(40f) }      var scale by remember { mutableFloatStateOf(1f) }     var offset by remember { mutableStateOf(Offset.Zero) }@@ -176,24 +154,52 @@ fun EditPhotoPage(     }      val texts = remember { mutableStateListOf<TextElement>() }-    var selectedDrawingId by remember { mutableStateOf<String?>(null) }     var selectedTextId by remember { mutableStateOf<String?>(null) }+    var selectedStrokeIndex by remember { mutableStateOf<Int?>(null) }+    var selectedTextIndex by remember { mutableStateOf<Int?>(null) }     var textToEdit by remember { mutableStateOf<TextElement?>(null) }-    var textFontSize by remember { mutableFloatStateOf(40f) }     var currentViewportWidth by remember { mutableFloatStateOf(1f) }     var currentViewportHeight by remember { mutableFloatStateOf(1f) } +    val currentBrush: Brush = remember(activeTool, penColor, penSize, highlighterColor, highlighterSize, highlighterOpacity) {+        when (activeTool) {+            DrawingTool.Pen -> Brush.createWithColorIntArgb(+family = StockBrushes.pressurePen(),+                colorIntArgb = penColor.toArgb(),+                size = penSize,+                epsilon = 0.1f,+            )+            DrawingTool.Highlighter -> {+                val argb = highlighterColor.toArgb()+                val alpha = (highlighterOpacity * 255).roundToInt()+                val colorWithAlpha = (alpha shl 24) or (argb and 0x00FFFFFF)+                Brush.createWithColorIntArgb(+                    family = StockBrushes.highlighter(),+                    colorIntArgb = colorWithAlpha,+                    size = highlighterSize,+                    epsilon = 0.1f,+                )+            }+            else -> Brush.createWithColorIntArgb(+family = StockBrushes.pressurePen(),+                colorIntArgb = penColor.toArgb(),+                size = penSize,+                epsilon = 0.1f,+            )+        }+    }+     data class EditState(         val rotation: Float,         val cropRect: Rect,-        val drawings: List<Drawing>,+        val strokes: List<SerializedStroke>,         val texts: List<TextElement>     )      val history = remember { mutableStateListOf<EditState>() }      fun pushState() {-        history.add(EditState(rotation, cropRect, drawings.toList(), texts.toList()))+        history.add(EditState(rotation, cropRect, inkStrokes.map { it.serialize() }, texts.toList()))     }      fun undo() {@@ -201,46 +207,15 @@ fun EditPhotoPage(             val lastState = history.removeAt(history.size - 1)             rotation = lastState.rotation             cropRect = lastState.cropRect-            drawings.clear()-            drawings.addAll(lastState.drawings)+            inkStrokes.clear()+            inkStrokes.addAll(lastState.strokes.mapNotNull { try { it.deserialize() } catch (_: Exception) { null } })             texts.clear()             texts.addAll(lastState.texts)         }     } -    val currentStrokeColor = when (activeTool) {-        DrawingTool.Pen -> penColor-        DrawingTool.Highlighter -> highlighterColor-        DrawingTool.Eraser -> Color.Transparent-        DrawingTool.Text -> penColor-        DrawingTool.Pointer -> Color.Transparent-    }--    val currentStrokeWidth = when (activeTool) {-        DrawingTool.Pen -> penWidth-        DrawingTool.Highlighter -> highlighterWidth-        DrawingTool.Eraser -> eraserWidth-        DrawingTool.Text -> 0f-        DrawingTool.Pointer -> 0f-    }--    val currentStrokeOpacity = if (activeTool == DrawingTool.Highlighter) highlighterOpacity else 1f-     ResultEffect<DrawingSettingsResult>("drawing_settings") { result ->         var changed = false-        selectedDrawingId?.let { id ->-            val index = drawings.indexOfFirst { it.id == id }-            if (index != -1) {-                pushState()-                drawings[index] = drawings[index].copy(-                    tool = result.tool,-                    color = result.color,-                    strokeWidth = result.thickness,-                    opacity = result.opacity-                )-                changed = true-            }-        }          selectedTextId?.let { id ->             val index = texts.indexOfFirst { it.id == id }@@ -259,24 +234,18 @@ fun EditPhotoPage(             when (result.tool) {                 DrawingTool.Pen -> {                     penColor = Color(result.color)-                    penWidth = result.thickness+                    penSize = result.thickness                 }-                 DrawingTool.Highlighter -> {                     highlighterColor = Color(result.color)-                    highlighterWidth = result.thickness+                    highlighterSize = result.thickness                     highlighterOpacity = result.opacity                 }--                DrawingTool.Eraser -> {-                    eraserWidth = result.thickness-                }-+                DrawingTool.Eraser -> {}                 DrawingTool.Text -> {                     penColor = Color(result.color)                     textFontSize = result.thickness                 }-                 DrawingTool.Pointer -> {}             }         }@@ -311,7 +280,7 @@ fun EditPhotoPage(                                     EditState(                                         rotation,                                         startCropRect,-                                        drawings.toList(),+                                        inkStrokes.map { it.serialize() },                                         texts.toList()                                     )                                 )@@ -333,20 +302,8 @@ fun EditPhotoPage(                         ) {                             IconUndo()                         }-                        if (selectedDrawingId != null || selectedTextId != null) {+                        if (selectedTextId != null) {                             IconButton(onClick = {-                                selectedDrawingId?.let { id ->-                                    drawings.find { it.id == id }?.let { drawing ->-                                        backStack.add(-                                            EditRoute.DrawingSettings(-                                                drawing.tool,-                                                drawing.color,-                                                drawing.strokeWidth,-                                                drawing.opacity-                                            )-                                        )-                                    }-                                }                                 selectedTextId?.let { id ->                                     texts.find { it.id == id }?.let { textElement ->                                         backStack.add(@@ -407,7 +364,7 @@ fun EditPhotoPage(                                                 it,                                                 rotation,                                                 cropRect,-                                                drawings.toList(),+                                                inkStrokes.map { s -> s.serialize() },                                                 texts.toList(),                                                 currentViewportWidth,                                                 false,@@ -424,7 +381,7 @@ fun EditPhotoPage(                                                 it,                                                 rotation,                                                 cropRect,-                                                drawings.toList(),+                                                inkStrokes.map { s -> s.serialize() },                                                 texts.toList(),                                                 currentViewportWidth,                                                 true,@@ -449,7 +406,7 @@ fun EditPhotoPage(                 modifier = Modifier                     .weight(1f)                     .fillMaxWidth()-                    .padding(32.dp),+                    .padding(8.dp),                 contentAlignment = Alignment.Center             ) {                 val maxWidth = constraints.maxWidth.toFloat()@@ -479,9 +436,11 @@ fun EditPhotoPage(                     currentViewportHeight = viewportHeight                      val density = LocalDensity.current+                    val densityFloat = density.density                     val viewportWidthDp = with(density) { viewportWidth.toDp() }                     val viewportHeightDp = with(density) { viewportHeight.toDp() } +                    val isInkDrawing = isDrawing && activeTool != DrawingTool.Pointer && activeTool != DrawingTool.Text                     Box(                         modifier = Modifier                             .size(viewportWidthDp, viewportHeightDp)@@ -492,32 +451,32 @@ fun EditPhotoPage(                                 translationY = offset.y                                 clip = false                             }-                            .transformable(state = transformState)-                            .pointerInput(activeTool) {-                                detectTapGestures { tapOffset ->-                                    if (activeTool == DrawingTool.Pointer) {-                                        selectedTextId = null-                                        selectedDrawingId = null-                                    } else if (activeTool == DrawingTool.Text) {-                                        pushState()-                                        val id = UUID.randomUUID().toString()-                                        texts.add(-                                            TextElement(-                                                id = id,-                                                text = "New Text",-                                                x = tapOffset.x / size.width,-                                                y = tapOffset.y / size.height,-                                                rotation = 0f,-                                                color = penColor.toArgb(),-                                                fontSize = textFontSize+                            .then(+                                if (activeTool == DrawingTool.Text) Modifier+                                    .pointerInput(activeTool) {+                                        detectTapGestures { tapOffset ->+                                            pushState()+                                            val newId = UUID.randomUUID().toString()+                                            texts.add(+                                                TextElement(+                                                    id = newId,+                                                    text = "New Text",+                                                    x = tapOffset.x / size.width,+                                                    y = tapOffset.y / size.height,+                                                    rotation = 0f,+                                                    color = penColor.toArgb(),+                                                    fontSize = textFontSize+                                                )                                             )-                                        )-                                        selectedTextId = id-                                        selectedDrawingId = null-                                        textToEdit = texts.last()+                                            selectedTextId = newId+                                            selectedTextIndex = texts.size - 1+                                            textToEdit = texts.last()+                                        }                                     }-                                }-                            },+                                else if (!isInkDrawing && activeTool != DrawingTool.Pointer) Modifier+                                    .transformable(state = transformState)+                                else Modifier+                            ),                         contentAlignment = Alignment.Center                     ) {                         transformedBitmap?.let { bitmap ->@@ -528,287 +487,132 @@ fun EditPhotoPage(                             )                         } -                        if (isDrawing) {-                            Canvas(+                        val canvasTextElements = remember(texts.toList(), currentViewportWidth, currentViewportHeight) {+                            texts.map { te ->+                                CanvasTextElement(+                                    text = te.text,+                                    x = te.x * currentViewportWidth,+                                    y = te.y * currentViewportHeight,+                                    rotation = te.rotation,+                                    color = te.color,+                                    fontSize = te.fontSize,+                                )+                            }+                        }++                        InkCanvasView(+                            currentBrush = currentBrush,+                            finishedStrokes = inkStrokes.toList(),+                            onStrokeFinished = { stroke ->+                                pushState()+                                inkStrokes.add(stroke)+                            },+                            onStrokeErased = { stroke ->+                                pushState()+                                inkStrokes.remove(stroke)+                            },+                            eraserMode = activeTool == DrawingTool.Eraser,+                            enabled = isDrawing && activeTool != DrawingTool.Pointer && activeTool != DrawingTool.Text,+                            textElements = canvasTextElements,+                            selectedStrokeIndex = selectedStrokeIndex,+                            selectedTextIndex = selectedTextIndex,+                            modifier = Modifier.fillMaxSize(),+                        )++                        if (isDrawing && activeTool == DrawingTool.Pointer) {+                            Box(                                 modifier = Modifier                                     .fillMaxSize()-                                    .pointerInput(activeTool) {-                                        if (activeTool == DrawingTool.Pointer) {-                                            detectTapGestures { tapOffset ->-                                                val hitDrawing = drawings.findLast { drawing ->-                                                    val bounds = drawing.computeBoundingBox(-                                                        size.width.toFloat(),-                                                        size.height.toFloat()-                                                    )-                                                    bounds.contains(tapOffset)-                                                }-                                                if (hitDrawing != null) {-                                                    selectedDrawingId = hitDrawing.id-                                                    selectedTextId = null-                                                }-                                            }-                                        }-                                    }-                                    .then(-                                        if (activeTool == DrawingTool.Pen || activeTool == DrawingTool.Highlighter || activeTool == DrawingTool.Eraser) {-                                            Modifier.pointerInput(-                                                activeTool,-                                                currentStrokeColor,-                                                currentStrokeWidth,-                                                currentStrokeOpacity-                                            ) {-                                                detectDragGestures(-                                                    onDragStart = { offset ->-                                                        currentDrawingPoints.add(-                                                            Offset(-                                                                offset.x / size.width,-                                                                offset.y / size.height-                                                            )-                                                        )-                                                    },-                                                    onDragEnd = {-                                                        if (currentDrawingPoints.isNotEmpty()) {-                                                            pushState()-                                                            val id = UUID.randomUUID().toString()-                                                            drawings.add(-                                                                Drawing(-                                                                    id = id,-                                                                    points = currentDrawingPoints.map { it.toSerializable() },-                                                                    tool = activeTool,-                                                                    color = currentStrokeColor.toArgb(),-                                                                    strokeWidth = currentStrokeWidth,-                                                                    opacity = currentStrokeOpacity-                                                                )-                                                            )-                                                            selectedDrawingId = id-                                                            selectedTextId = null-                                                            currentDrawingPoints.clear()-                                                        }-                                                    },-                                                    onDragCancel = {-                                                        currentDrawingPoints.clear()-                                                    },-                                                    onDrag = { change, dragAmount ->-                                                        change.consume()-                                                        val last = currentDrawingPoints.lastOrNull()-                                                            ?: Offset.Zero-                                                        currentDrawingPoints.add(-                                                            last + Offset(-                                                                dragAmount.x / size.width,-                                                                dragAmount.y / size.height-                                                            )-                                                        )-                                                    }+                                    .pointerInput(+                                        inkStrokes.toList(),+                                        texts.toList(),+                                        selectedStrokeIndex,+                                        selectedTextIndex,+                                        currentViewportWidth,+                                        currentViewportHeight+                                    ) {+                                        detectTapGestures(+                                            onDoubleTap = { tapOffset ->+                                                val textIdx = hitTestText(+                                                    tapOffset.x,+                                                    tapOffset.y,+                                                    texts,+                                                    currentViewportWidth,+                                                    currentViewportHeight,+                                                    densityFloat                                                 )-                                            }-                                        } else if (activeTool == DrawingTool.Pointer) {-                                            Modifier.pointerInput(selectedDrawingId) {-                                                detectDragGestures(-                                                    onDragStart = { if (selectedDrawingId != null) pushState() },-                                                    onDrag = { change, dragAmount ->-                                                        selectedDrawingId?.let { id ->-                                                            val index =-                                                                drawings.indexOfFirst { it.id == id }-                                                            if (index != -1) {-                                                                change.consume()-                                                                val d = drawings[index]-                                                                drawings[index] = d.copy(-                                                                    points = d.points.map {-                                                                        it.copy(-                                                                            x = it.x + dragAmount.x / size.width,-                                                                            y = it.y + dragAmount.y / size.height-                                                                        )-                                                                    }-                                                                )-                                                            }-                                                        }-                                                    }+                                                if (textIdx != null) {+                                                    pushState()+                                                    textToEdit = texts.getOrNull(textIdx)+                                                }+                                            },+                                            onTap = { tapOffset ->+                                                val textIdx = hitTestText(+                                                    tapOffset.x,+                                                    tapOffset.y,+                                                    texts,+                                                    currentViewportWidth,+                                                    currentViewportHeight,+                                                    densityFloat                                                 )-                                            }-                                        } else Modifier-                                    )-                                    .graphicsLayer(compositingStrategy = CompositingStrategy.Offscreen)-                            ) {-                                drawIntoCanvas {-                                    drawings.forEach { drawing ->-                                        val path = Path().apply {-                                            drawing.points.firstOrNull()?.let { first ->-                                                moveTo(first.x * size.width, first.y * size.height)-                                                drawing.points.drop(1).forEach { next ->-                                                    lineTo(-                                                        next.x * size.width,-                                                        next.y * size.height+                                                if (textIdx != null) {+                                                    selectedTextIndex = textIdx+                                                    selectedStrokeIndex = null+                                                    selectedTextId = texts.getOrNull(textIdx)?.id+                                                } else {+                                                    val strokeIdx = hitTestStroke(+                                                        tapOffset.x,+                                                        tapOffset.y,+                                                        inkStrokes                                                     )+                                                    if (strokeIdx != null) {+                                                        selectedStrokeIndex = strokeIdx+                                                        selectedTextIndex = null+                                                        selectedTextId = null+                                                    } else {+                                                        selectedStrokeIndex = null+                                                        selectedTextIndex = null+                                                        selectedTextId = null+                                                    }                                                 }                                             }-                                        }--                                        drawPath(-                                            path = path,-                                            color = Color(drawing.color),-                                            alpha = drawing.opacity,-                                            style = Stroke(-                                                width = drawing.strokeWidth,-                                                cap = StrokeCap.Round,-                                                join = StrokeJoin.Round-                                            ),-                                            blendMode = if (drawing.tool == DrawingTool.Eraser) BlendMode.Clear else BlendMode.SrcOver                                         )--                                        if (selectedDrawingId == drawing.id && activeTool == DrawingTool.Pointer) {-                                            val bounds =-                                                drawing.computeBoundingBox(size.width, size.height)-                                            drawRect(-                                                color = Color.White,-                                                topLeft = Offset(-                                                    bounds.left - 1.dp.toPx(),-                                                    bounds.top - 1.dp.toPx()-                                                ),-                                                size = androidx.compose.ui.geometry.Size(-                                                    bounds.width + 2.dp.toPx(),-                                                    bounds.height + 2.dp.toPx()-                                                ),-                                                style = Stroke(width = 1.dp.toPx())-                                            )-                                            drawRect(-                                                color = Color.Black,-                                                topLeft = Offset(bounds.left, bounds.top),-                                                size = androidx.compose.ui.geometry.Size(-                                                    bounds.width,-                                                    bounds.height-                                                ),-                                                style = Stroke(width = 1.dp.toPx())-                                            )-                                        }                                     }--                                    if (currentDrawingPoints.isNotEmpty()) {-                                        val path = Path().apply {-                                            moveTo(-                                                currentDrawingPoints.first().x * size.width,-                                                currentDrawingPoints.first().y * size.height-                                            )-                                            currentDrawingPoints.drop(1).forEach { next ->-                                                lineTo(next.x * size.width, next.y * size.height)-                                            }-                                        }-                                        drawPath(-                                            path = path,-                                            color = currentStrokeColor,-                                            alpha = currentStrokeOpacity,-                                            style = Stroke(-                                                width = currentStrokeWidth,-                                                cap = StrokeCap.Round,-                                                join = StrokeJoin.Round-                                            ),-                                            blendMode = if (activeTool == DrawingTool.Eraser) BlendMode.Clear else BlendMode.SrcOver-                                        )-                                    }-                                }-                            }-                        }--                        Box(modifier = Modifier.fillMaxSize()) {-                            texts.forEach { textElement ->-                                key(textElement.id) {-                                    val isSelected = selectedTextId == textElement.id-                                    Box(-                                        modifier = Modifier-                                            .offset {-                                                IntOffset(-                                                    (textElement.x * currentViewportWidth).roundToInt(),-                                                    (textElement.y * currentViewportHeight).roundToInt()-                                                )-                                            }-                                            .rotate(textElement.rotation)-                                            .then(-                                                if (isSelected && activeTool == DrawingTool.Pointer) {-                                                    Modifier-                                                        .border(1.dp, Color.White)-                                                        .padding(1.dp)-                                                        .border(1.dp, Color.Black)-                                                } else Modifier-                                            )-                                            .pointerInput(activeTool) {-                                                if (activeTool == DrawingTool.Pointer) {-                                                    detectTapGestures(-                                                        onTap = {-                                                            if (selectedTextId == textElement.id) {-                                                                pushState()-                                                                textToEdit =-                                                                    texts.find { it.id == textElement.id }-                                                            } else {-                                                                selectedTextId = textElement.id-                                                                selectedDrawingId = null-                                                            }-                                                        }-                                                    )+                                    .pointerInput(+                                        selectedStrokeIndex,+                                        selectedTextIndex,+                                        currentViewportWidth,+                                        currentViewportHeight+                                    ) {+                                        detectDragGestures(+                                            onDragStart = {+                                                if (selectedStrokeIndex != null || selectedTextIndex != null) {+                                                    pushState()                                                 }-                                            }-                                            .pointerInput(activeTool) {-                                                if (activeTool == DrawingTool.Pointer) {-                                                    detectDragGestures(-                                                        onDragStart = {-                                                            if (selectedTextId == textElement.id) {-                                                                pushState()-                                                            }-                                                        },-                                                        onDrag = { change, dragAmount ->-                                                            if (selectedTextId == textElement.id) {-                                                                change.consume()-                                                                val idx =-                                                                    texts.indexOfFirst { it.id == textElement.id }-                                                                if (idx != -1) {-                                                                    val current = texts[idx]-                                                                    texts[idx] = current.copy(-                                                                        x = current.x + dragAmount.x / currentViewportWidth,-                                                                        y = current.y + dragAmount.y / currentViewportHeight-                                                                    )-                                                                }-                                                            }-                                                        }-                                                    )+                                            },+                                            onDrag = { change, dragAmount ->+                                                change.consume()+                                                selectedStrokeIndex?.let { idx ->+                                                    if (idx in inkStrokes.indices) {+                                                        inkStrokes[idx] = inkStrokes[idx].translate(+                                                            dragAmount.x,+                                                            dragAmount.y+                                                        )+                                                    }                                                 }-                                            }-                                            .padding(4.dp)-                                    ) {-                                        Text(-                                            text = textElement.text,-                                            color = Color(textElement.color),-                                            fontSize = textElement.fontSize.sp-                                        )--                                        if (isSelected && activeTool == DrawingTool.Pointer) {-                                            Box(-                                                modifier = Modifier-                                                    .align(Alignment.TopCenter)-                                                    .offset(y = (-30).dp)-                                                    .size(20.dp)-                                                    .background(Color.White, CircleShape)-                                                    .border(1.dp, Color.Black, CircleShape)-                                                    .pointerInput(activeTool) {-                                                        detectDragGestures(-                                                            onDragStart = { pushState() },-                                                            onDrag = { change, dragAmount ->-                                                                if (selectedTextId == textElement.id) {-                                                                    change.consume()-                                                                    val idx =-                                                                        texts.indexOfFirst { it.id == textElement.id }-                                                                    if (idx != -1) {-                                                                        val current = texts[idx]-                                                                        texts[idx] = current.copy(-                                                                            rotation = current.rotation + dragAmount.x-                                                                        )-                                                                    }-                                                                }-                                                            }+                                                selectedTextIndex?.let { idx ->+                                                    if (idx in texts.indices) {+                                                        val current = texts[idx]+                                                        texts[idx] = current.copy(+                                                            x = current.x + dragAmount.x / currentViewportWidth,+                                                            y = current.y + dragAmount.y / currentViewportHeight                                                         )                                                     }-                                            )-                                        }+                                                }+                                            }+                                        )                                     }-                                }-                            }+                            )                         }                          if (isCropping) {@@ -831,76 +635,105 @@ fun EditPhotoPage(                 ) {                     IconButton(onClick = {                         activeTool = DrawingTool.Pointer-                        selectedDrawingId = null                         selectedTextId = null+                        selectedStrokeIndex = null+                        selectedTextIndex = null                     }) {-                        IconVisible(tint = if (activeTool == DrawingTool.Pointer) Color.Yellow else Color.White)+                        Box(+                            modifier = Modifier+                                .size(40.dp)+                                .then(+                                    if (activeTool == DrawingTool.Pointer) Modifier.background(+                                        MaterialTheme.colorScheme.secondaryContainer,+                                        CircleShape+                                    ) else Modifier+                                ),+                            contentAlignment = Alignment.Center+                        ) {+                            IconVisible()+                        }                     }                     IconButton(onClick = {-                        val isSelectedMatch =-                            selectedDrawingId?.let { id -> drawings.find { it.id == id }?.tool == DrawingTool.Pen }-                                ?: false-                        if (isSelectedMatch || activeTool == DrawingTool.Pen) {-                            val drawing = drawings.find { it.id == selectedDrawingId }+                        if (activeTool == DrawingTool.Pen) {                             backStack.add(                                 EditRoute.DrawingSettings(                                     DrawingTool.Pen,-                                    drawing?.color ?: penColor.toArgb(),-                                    drawing?.strokeWidth ?: penWidth,+                                    penColor.toArgb(),+                                    penSize,                                     1f                                 )                             )                         } else {-                            activeTool = DrawingTool.Pen-                            selectedDrawingId = null+                        activeTool = DrawingTool.Pen                             selectedTextId = null+                            selectedStrokeIndex = null+                            selectedTextIndex = null                         }                     }) {-                        IconDraw(tint = if (activeTool == DrawingTool.Pen) penColor else Color.White)+                        Box(+                            modifier = Modifier+                                .size(40.dp)+                                .then(+                                    if (activeTool == DrawingTool.Pen) Modifier.background(+                                        MaterialTheme.colorScheme.secondaryContainer,+                                        CircleShape+                                    ) else Modifier+                                ),+                            contentAlignment = Alignment.Center+                        ) {+                            IconDraw()+                        }                     }                     IconButton(onClick = {-                        val isSelectedMatch =-                            selectedDrawingId?.let { id -> drawings.find { it.id == id }?.tool == DrawingTool.Highlighter }-                                ?: false-                        if (isSelectedMatch || activeTool == DrawingTool.Highlighter) {-                            val drawing = drawings.find { it.id == selectedDrawingId }+                        if (activeTool == DrawingTool.Highlighter) {                             backStack.add(                                 EditRoute.DrawingSettings(                                     DrawingTool.Highlighter,-                                    drawing?.color ?: highlighterColor.toArgb(),-                                    drawing?.strokeWidth ?: highlighterWidth,-                                    drawing?.opacity ?: highlighterOpacity+                                    highlighterColor.toArgb(),+                                    highlighterSize,+                                    highlighterOpacity                                 )                             )                         } else {                             activeTool = DrawingTool.Highlighter-                            selectedDrawingId = null                             selectedTextId = null+                            selectedStrokeIndex = null+                            selectedTextIndex = null                         }                     }) {-                        IconBrush(tint = if (activeTool == DrawingTool.Highlighter) highlighterColor else Color.White)+                        Box(+                            modifier = Modifier+                                .size(40.dp)+                                .then(+                                    if (activeTool == DrawingTool.Highlighter) Modifier.background(+                                        MaterialTheme.colorScheme.secondaryContainer,+                                        CircleShape+                                    ) else Modifier+                                ),+                            contentAlignment = Alignment.Center+                        ) {+                            IconBrush()+                        }                     }                     IconButton(onClick = {-                        val isSelectedMatch =-                            selectedDrawingId?.let { id -> drawings.find { it.id == id }?.tool == DrawingTool.Eraser }-                                ?: false-                        if (isSelectedMatch || activeTool == DrawingTool.Eraser) {-                            val drawing = drawings.find { it.id == selectedDrawingId }-                            backStack.add(-                                EditRoute.DrawingSettings(-                                    DrawingTool.Eraser,-                                    Color.Transparent.toArgb(),-                                    drawing?.strokeWidth ?: eraserWidth,-                                    1f-                                )-                            )-                        } else {-                            activeTool = DrawingTool.Eraser-                            selectedDrawingId = null-                            selectedTextId = null-                        }+                        activeTool = DrawingTool.Eraser+                        selectedTextId = null+                        selectedStrokeIndex = null+                        selectedTextIndex = null                     }) {-                        IconEraser(tint = if (activeTool == DrawingTool.Eraser) Color.Yellow else Color.White)+                        Box(+                            modifier = Modifier+                                .size(40.dp)+                                .then(+                                    if (activeTool == DrawingTool.Eraser) Modifier.background(+                                        MaterialTheme.colorScheme.secondaryContainer,+                                        CircleShape+                                    ) else Modifier+                                ),+                            contentAlignment = Alignment.Center+                        ) {+                            IconEraser()+                        }                     }                     IconButton(onClick = {                         if (selectedTextId != null || activeTool == DrawingTool.Text) {@@ -927,16 +760,28 @@ fun EditPhotoPage(                             }                         } else {                             activeTool = DrawingTool.Text-                            selectedDrawingId = null                             selectedTextId = null+                            selectedStrokeIndex = null+                            selectedTextIndex = null                         }                     }) {-                        Text(-                            "T",-                            color = if (activeTool == DrawingTool.Text) penColor else Color.White,-                            fontSize = 24.sp,-                            fontWeight = androidx.compose.ui.text.font.FontWeight.Bold-                        )+                        Box(+                            modifier = Modifier+                                .size(40.dp)+                                .then(+                                    if (activeTool == DrawingTool.Text) Modifier.background(+                                        MaterialTheme.colorScheme.secondaryContainer,+                                        CircleShape+                                    ) else Modifier+                                ),+                            contentAlignment = Alignment.Center+                        ) {+                            Text(+                                "T",+                                fontSize = 24.sp,+                                fontWeight = androidx.compose.ui.text.font.FontWeight.Bold+                            )+                        }                     }                 }             }@@ -980,7 +825,7 @@ fun CropOverlay(cropRect: Rect, onCropRectChange: (Rect) -> Unit) {     BoxWithConstraints(modifier = Modifier.fillMaxSize()) {         val width = constraints.maxWidth.toFloat()         val height = constraints.maxHeight.toFloat()-        Canvas(modifier = Modifier.fillMaxSize()) {+        androidx.compose.foundation.Canvas(modifier = Modifier.fillMaxSize()) {             val rect = Rect(                 cropRect.left * width,                 cropRect.top * height,@@ -1081,4 +926,37 @@ fun Handle(offset: Offset, onDrag: (Offset) -> Unit) {                 }             }     )-}\ No newline at end of file+}++private fun hitTestText(+    x: Float,+    y: Float,+    texts: List<TextElement>,+    viewportWidth: Float,+    viewportHeight: Float,+    density: Float,+): Int? {+    val paint = android.graphics.Paint().apply { isAntiAlias = true }+    for (i in texts.indices.reversed()) {+        val elem = texts[i]+        paint.textSize = elem.fontSize * density+        val textWidth = paint.measureText(elem.text)+        val textHeight = paint.textSize+        val ex = elem.x * viewportWidth+        val ey = elem.y * viewportHeight+        if (x in ex..(ex + textWidth) && y in ey..(ey + textHeight + 4f)) return i+    }+    return null+}++private fun hitTestStroke(x: Float, y: Float, strokes: List<InkStroke>): Int? {+    val hitRadius = 20f+    for (i in strokes.indices.reversed()) {+        strokes[i].shape.computeBoundingBox()?.let { box ->+            if (box.xMin <= x + hitRadius && box.xMax >= x - hitRadius &&+                box.yMin <= y + hitRadius && box.yMax >= y - hitRadius+            ) return i+        }+    }+    return null+}
photos/src/main/java/com/vayunmathur/photos/util/PhotoEditViewModel.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/util/PhotoEditViewModel.kt b/photos/src/main/java/com/vayunmathur/photos/util/PhotoEditViewModel.ktindex dd957d0e20..8d66699382 100644--- a/photos/src/main/java/com/vayunmathur/photos/util/PhotoEditViewModel.kt+++ b/photos/src/main/java/com/vayunmathur/photos/util/PhotoEditViewModel.kt@@ -15,8 +15,8 @@ import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope-import com.vayunmathur.photos.data.Drawing-import com.vayunmathur.photos.data.DrawingTool+import com.vayunmathur.library.util.SerializedStroke+import com.vayunmathur.library.util.deserialize import com.vayunmathur.photos.data.Photo import com.vayunmathur.photos.data.TextElement import kotlinx.coroutines.Dispatchers@@ -28,19 +28,6 @@ import kotlinx.coroutines.withContext import java.io.InputStream import kotlin.math.roundToInt -/**- * ViewModel for the photo edit screen.- *- * Owns:- *  - decoded source bitmap (LRU cache, keyed by URI)- *  - transformed bitmap reflecting rotation + (final) crop- *  - persisting the result back to MediaStore- *- * All bitmap work runs on [Dispatchers.Default] (CPU-bound: decode + Matrix +- * compress; not I/O latency-bound).- *- * Bitmaps are recycled in [onCleared] to release native memory promptly.- */ class PhotoEditViewModel(     application: Application, ) : AndroidViewModel(application) {@@ -51,9 +38,6 @@ class PhotoEditViewModel(     private val _transformedBitmap = MutableStateFlow<Bitmap?>(null)     val transformedBitmap: StateFlow<Bitmap?> = _transformedBitmap.asStateFlow() -    // Bounded LRU cache for decoded source bitmaps. Editing the same photo-    // multiple times within a session reuses the decoded data. Eldest entries-    // are recycled on eviction unless still referenced as the current original.     private val decodedCache = object : LinkedHashMap<String, Bitmap>(32, 0.75f, true) {         override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, Bitmap>): Boolean {             if (size > 32) {@@ -69,10 +53,6 @@ class PhotoEditViewModel(      private var lastDecodedUri: String? = null -    /**-     * Decode the photo at [uri]. Result is published to [originalBitmap].-     * Uses [Dispatchers.Default] since BitmapFactory work is CPU-bound.-     */     fun decode(uri: Uri) {         val uriStr = uri.toString()         if (uriStr == lastDecodedUri && _originalBitmap.value != null) return@@ -85,9 +65,17 @@ class PhotoEditViewModel(         val ctx: Context = getApplication()         viewModelScope.launch(Dispatchers.Default) {             try {-                val bmp = ctx.contentResolver.openInputStream(uri)?.use { stream ->-                    decodeSampledStream(stream, ctx, uri)-                } ?: return@launch+                val source = android.graphics.ImageDecoder.createSource(ctx.contentResolver, uri)+                val bmp = android.graphics.ImageDecoder.decodeBitmap(source) { decoder, info, _ ->+                    val w = info.size.width+                    val h = info.size.height+                    val target = 2048+                    if (w > target || h > target) {+                        val scale = target.toFloat() / maxOf(w, h)+                        decoder.setTargetSize((w * scale).roundToInt(), (h * scale).roundToInt())+                    }+                    decoder.allocator = android.graphics.ImageDecoder.ALLOCATOR_SOFTWARE+                }                 synchronized(decodedCache) { decodedCache[uriStr] = bmp }                 lastDecodedUri = uriStr                 _originalBitmap.value = bmp@@ -97,33 +85,6 @@ class PhotoEditViewModel(         }     } -    private fun decodeSampledStream(stream: InputStream, ctx: Context, uri: Uri): Bitmap? {-        val options = BitmapFactory.Options().apply { inJustDecodeBounds = true }-        BitmapFactory.decodeStream(stream, null, options)--        var inSampleSize = 1-        val targetW = 2048-        val targetH = 2048-        if (options.outHeight > targetH || options.outWidth > targetW) {-            val halfHeight = options.outHeight / 2-            val halfWidth = options.outWidth / 2-            while (halfHeight / inSampleSize >= targetH && halfWidth / inSampleSize >= targetW) {-                inSampleSize *= 2-            }-        }-        options.inJustDecodeBounds = false-        options.inSampleSize = inSampleSize--        return ctx.contentResolver.openInputStream(uri)?.use { input2 ->-            BitmapFactory.decodeStream(input2, null, options)-        }-    }--    /**-     * Produce a rotated (and, when not actively cropping, cropped) bitmap from-     * the currently decoded source. The previous transformed bitmap is-     * recycled if it was not the source itself.-     */     fun applyTransform(rotation: Float, cropRect: Rect, isCropping: Boolean) {         val original = _originalBitmap.value ?: return         viewModelScope.launch(Dispatchers.Default) {@@ -154,16 +115,11 @@ class PhotoEditViewModel(         }     } -    /**-     * Save the edited photo to MediaStore. Mirrors the previously inline-     * `savePhoto` function but runs through [viewModelScope] so the work is-     * tied to the VM lifecycle.-     */     fun savePhoto(         photo: Photo,         rotation: Float,         cropRect: Rect,-        drawings: List<Drawing>,+        strokes: List<SerializedStroke>,         texts: List<TextElement>,         viewportWidth: Float,         asCopy: Boolean,@@ -172,7 +128,7 @@ class PhotoEditViewModel(         val ctx: Context = getApplication()         viewModelScope.launch {             withContext(Dispatchers.Default) {-                writeEdited(ctx, photo, rotation, cropRect, drawings, texts, viewportWidth, asCopy)+                writeEdited(ctx, photo, rotation, cropRect, strokes, texts, viewportWidth, asCopy)             }             onComplete()         }@@ -203,13 +159,17 @@ class PhotoEditViewModel(             photo: Photo,             rotation: Float,             cropRect: Rect,-            drawings: List<Drawing>,+            strokes: List<SerializedStroke>,             texts: List<TextElement>,             viewportWidth: Float,             asCopy: Boolean,         ) {-            val inputStream: InputStream? = context.contentResolver.openInputStream(Uri.parse(photo.uri))-            val originalBitmap = BitmapFactory.decodeStream(inputStream) ?: return+            val photoUri = Uri.parse(photo.uri)+            val source = android.graphics.ImageDecoder.createSource(context.contentResolver, photoUri)+            var originalBitmap = android.graphics.ImageDecoder.decodeBitmap(source) { decoder, _, _ ->+                decoder.allocator = android.graphics.ImageDecoder.ALLOCATOR_SOFTWARE+            }+             val matrix = Matrix().apply { postRotate(rotation) }             var transformedBitmap = Bitmap.createBitmap(                 originalBitmap, 0, 0, originalBitmap.width, originalBitmap.height, matrix, true,@@ -227,34 +187,23 @@ class PhotoEditViewModel(             }             val resultBitmap = transformedBitmap.copy(Bitmap.Config.ARGB_8888, true)             val canvas = android.graphics.Canvas(resultBitmap)-            val paint = android.graphics.Paint().apply {-                isAntiAlias = true-                strokeCap = android.graphics.Paint.Cap.ROUND-                strokeJoin = android.graphics.Paint.Join.ROUND-                style = android.graphics.Paint.Style.STROKE-            }-            if (drawings.isNotEmpty()) {-                val saveCount = canvas.saveLayer(-                    0f, 0f, resultBitmap.width.toFloat(), resultBitmap.height.toFloat(), null,-                )-                drawings.forEach { drawing ->-                    paint.color = drawing.color-                    paint.strokeWidth = drawing.strokeWidth-                    paint.alpha = (drawing.opacity * 255).roundToInt()-                    paint.xfermode = if (drawing.tool == DrawingTool.Eraser) {-                        android.graphics.PorterDuffXfermode(android.graphics.PorterDuff.Mode.CLEAR)-                    } else null-                    val path = android.graphics.Path()-                    drawing.points.firstOrNull()?.let { first ->-                        path.moveTo(first.x * resultBitmap.width, first.y * resultBitmap.height)-                        drawing.points.drop(1).forEach { next ->-                            path.lineTo(next.x * resultBitmap.width, next.y * resultBitmap.height)-                        }-                    }-                    canvas.drawPath(path, paint)++            if (strokes.isNotEmpty()) {+                val renderer = androidx.ink.rendering.android.canvas.CanvasStrokeRenderer.create()+                val scaleMatrix = Matrix().apply {+                    setScale(+                        resultBitmap.width / viewportWidth,+                        resultBitmap.width / viewportWidth,+                    )+                }+                strokes.forEach { serialized ->+                    try {+                        val stroke = serialized.deserialize()+                        renderer.draw(canvas, stroke, scaleMatrix)+                    } catch (_: Exception) {}                 }-                canvas.restoreToCount(saveCount)             }+             if (texts.isNotEmpty()) {                 val textPaint = android.graphics.Paint().apply {                     isAntiAlias = true