Modern Apps git

← Modern-Apps.git

photos: overlay selectable text on rotated OCR lines

Commit
93626613bec40078d688f0d9013c4fd27939dece
Author
vayun-mathur <[email protected]>
When
2026-08-20 19:24 UTC (3 months ago)
Parents
82e515e

Diff

photos/src/main/java/com/vayunmathur/photos/data/OcrLayout.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/OcrLayout.kt b/photos/src/main/java/com/vayunmathur/photos/data/OcrLayout.ktindex 1b691b0467..0a776d86d5 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/OcrLayout.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/OcrLayout.kt@@ -4,7 +4,15 @@ import android.util.Log import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json -/** One recognised text line, in the pixel coordinates of the OCR bitmap. */+/**+ * One recognised text line, in the pixel coordinates of the OCR bitmap.+ *+ * [quad] holds the line's oriented corners as `x0,y0,x1,y1,x2,y2,x3,y3` in+ * reading order (corner 0 -> 1 runs along the text, 0 -> 3 spans its height);+ * [left]/[top]/[right]/[bottom] are its axis-aligned bounds. Rows written before+ * the quad existed are cleared by the migration that introduced it, so a null+ * [quad] only ever means "not re-indexed yet".+ */ @Serializable data class OcrBox(     val text: String,@@ -12,6 +20,8 @@ data class OcrBox(     val top: Int,     val right: Int,     val bottom: Int,+    val quad: List<Float>? = null,+    val vertical: Boolean = false, )  /**
photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt b/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.ktindex 104eccce59..7cc49e10fb 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt@@ -117,13 +117,13 @@ data class PhotoEmbedding(     val clipEmbedding: ByteArray, ) -@Database(entities = [Photo::class, Person::class, PhotoFace::class], version = 14, exportSchema = false)+@Database(entities = [Photo::class, Person::class, PhotoFace::class], version = 15, exportSchema = false) abstract class PhotoDatabase : RoomDatabase() {     abstract fun photoDao(): PhotoDao     abstract fun faceDao(): FaceDao      companion object : com.vayunmathur.library.util.DatabaseMigrations {-        override val migrations: List<Migration> = listOf(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7, MIGRATION_7_8, MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11, MIGRATION_11_12, MIGRATION_12_13, MIGRATION_13_14)+        override val migrations: List<Migration> = listOf(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7, MIGRATION_7_8, MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11, MIGRATION_11_12, MIGRATION_12_13, MIGRATION_13_14, MIGRATION_14_15)     } } @@ -234,3 +234,15 @@ val MIGRATION_13_14 = Migration(13, 14) {     // viewer fills them in one photo at a time as they're opened.     it.execSQL("ALTER TABLE Photo ADD COLUMN ocrBoxes TEXT") }++val MIGRATION_14_15 = Migration(14, 15) {+    // The detector now returns oriented quads instead of axis-aligned boxes, and+    // recognises rotated text it previously returned garbage for, so the stored+    // geometry is stale and the text is incomplete. Clear the geometry and the+    // scanned flag and let the background indexer rebuild the library; it is+    // already throttled by OCR_INTER_ITEM_DELAY_MS / coolDownBetweenBatches.+    // ocrText is deliberately left in place so search keeps working on whatever+    // was already found while the re-index runs; each row's text is overwritten+    // as it is rescanned.+    it.execSQL("UPDATE Photo SET ocrScanned = 0, ocrBoxes = NULL")+}
photos/src/main/java/com/vayunmathur/photos/domain/PhotoOcr.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/domain/PhotoOcr.kt b/photos/src/main/java/com/vayunmathur/photos/domain/PhotoOcr.ktindex 3e0cc2b14a..9ec43c9732 100644--- a/photos/src/main/java/com/vayunmathur/photos/domain/PhotoOcr.kt+++ b/photos/src/main/java/com/vayunmathur/photos/domain/PhotoOcr.kt@@ -138,7 +138,17 @@ object OcrBoxStore { internal fun OcrEngine.OcrResult.toLayout(width: Int, height: Int) = OcrLayout(     w = width,     h = height,-    boxes = boxes.map { OcrBox(it.text, it.left, it.top, it.right, it.bottom) },+    boxes = boxes.map { box ->+        OcrBox(+            text = box.text,+            left = box.left,+            top = box.top,+            right = box.right,+            bottom = box.bottom,+            quad = box.corners.flatMap { listOf(it.x, it.y) },+            vertical = box.vertical,+        )+    }, )  private const val TAG = "PhotoOcr"
photos/src/main/java/com/vayunmathur/photos/ui/OcrTextLayer.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/OcrTextLayer.kt b/photos/src/main/java/com/vayunmathur/photos/ui/OcrTextLayer.ktindex dc45e1610e..a573172e54 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/OcrTextLayer.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/OcrTextLayer.kt@@ -14,23 +14,34 @@ import androidx.compose.foundation.text.selection.SelectionContainer import androidx.compose.foundation.text.selection.TextSelectionColors import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Rect import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.TransformOrigin import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.graphics.graphicsLayer-import androidx.compose.ui.geometry.Offset-import androidx.compose.ui.geometry.Size import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.platform.LocalTextToolbar+import androidx.compose.ui.platform.TextToolbar+import androidx.compose.ui.platform.TextToolbarStatus import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.rememberTextMeasurer import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp-import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.photos.data.OcrLayout+import kotlinx.coroutines.delay+import kotlin.math.PI+import kotlin.math.atan2+import kotlin.math.hypot import kotlin.math.roundToInt  /**@@ -43,12 +54,19 @@ import kotlin.math.roundToInt  * [containerSize] and the layout's own dimensions rather than [com.vayunmathur.photos.data.Photo.width].  * The caller passes the image's zoom/pan `graphicsLayer` in [modifier] so the  * text tracks pinch-zoom in lockstep.+ *+ * Everything drawn here has to stay legible on top of an arbitrary photo, which+ * rules out theme colours (a dynamic-colour primary is often a pale pastel that+ * disappears over a bright image) and hairline strokes. So the outlines are+ * drawn as a light line inside a dark halo, the selection uses a fixed vivid+ * hue, and while a selection is live the image is dimmed behind it.  */ @Composable fun OcrTextLayer(     layout: OcrLayout,     containerSize: IntSize,     showOutlines: Boolean,+    zoom: Float,     modifier: Modifier = Modifier, ) {     if (layout.boxes.isEmpty() || containerSize.width <= 0 || containerSize.height <= 0) return@@ -62,31 +80,74 @@ fun OcrTextLayer(     }     if (placements.isEmpty()) return -    val outlineColor = MaterialTheme.colorScheme.primary-    val selectionColors = TextSelectionColors(-        handleColor = outlineColor,-        backgroundColor = outlineColor.copy(alpha = 0.4f),-    )+    val selectionColors = remember {+        TextSelectionColors(+            handleColor = SELECTION_COLOR,+            backgroundColor = SELECTION_COLOR.copy(alpha = 0.5f),+        )+    }++    // Compose keeps selection state private to SelectionContainer, but it drives+    // the floating toolbar from it — so a toolbar that reports when it's asked to+    // appear tells us a selection is live.+    var toolbarShown by remember { mutableStateOf(false) }+    val platformToolbar = LocalTextToolbar.current+    val toolbar = remember(platformToolbar) {+        SelectionAwareTextToolbar(platformToolbar) { toolbarShown = it }+    }+    // Dragging a handle hides and re-shows the toolbar, so the dim can't follow it+    // directly or it would strobe during the one gesture it exists to support.+    var dimImage by remember { mutableStateOf(false) }+    LaunchedEffect(toolbarShown) {+        if (toolbarShown) {+            dimImage = true+        } else {+            delay(DIM_LINGER_MS)+            dimImage = false+        }+    }+     val density = LocalDensity.current      Box(modifier = modifier) {-        // Drawn under the selectable text so it can never intercept a touch. Makes-        // the feature discoverable without adding a control: the regions light up-        // whenever the metadata card is up.-        AnimatedVisibility(visible = showOutlines, enter = fadeIn(), exit = fadeOut()) {+        // Both of these sit under the selectable text in z-order so they can never+        // intercept a touch (a Canvas takes no pointer input either way).+        AnimatedVisibility(visible = dimImage, enter = fadeIn(), exit = fadeOut()) {+            Canvas(modifier = Modifier.fillMaxSize()) {+                drawRect(color = Color.Black.copy(alpha = 0.4f))+            }+        }++        // Shown with the metadata card, and whenever text is being selected, which+        // makes the feature discoverable without adding a control.+        AnimatedVisibility(visible = showOutlines || dimImage, enter = fadeIn(), exit = fadeOut()) {             Canvas(modifier = Modifier.fillMaxSize()) {+                // The whole layer is inside the image's zoom transform, so the+                // strokes are pre-divided by it to stay a constant thickness+                // on screen instead of ballooning as the photo is magnified.+                val halo = OUTLINE_HALO.toPx() / zoom+                val line = OUTLINE_STROKE.toPx() / zoom                 placements.forEach { p ->-                    drawRect(-                        color = outlineColor.copy(alpha = 0.5f),-                        topLeft = Offset(p.left, p.top),-                        size = Size(p.width, p.height),-                        style = Stroke(width = OUTLINE_STROKE.toPx()),+                    // Wide dark stroke first, narrow light stroke centred inside it:+                    // one of the two always contrasts, whatever is underneath.+                    drawPath(+                        path = p.outline,+                        color = Color.Black.copy(alpha = 0.55f),+                        style = Stroke(width = halo),+                    )+                    drawPath(+                        path = p.outline,+                        color = Color.White.copy(alpha = 0.9f),+                        style = Stroke(width = line),                     )                 }             }         } -        CompositionLocalProvider(LocalTextSelectionColors provides selectionColors) {+        CompositionLocalProvider(+            LocalTextSelectionColors provides selectionColors,+            LocalTextToolbar provides toolbar,+        ) {             SelectionContainer {                 Box(modifier = Modifier.fillMaxSize()) {                     placements.forEach { p ->@@ -96,9 +157,9 @@ fun OcrTextLayer(                             maxLines = 1,                             softWrap = false,                             modifier = Modifier-                                .offset { IntOffset(p.left.roundToInt(), p.top.roundToInt()) }+                                .offset { IntOffset(p.origin.x.roundToInt(), p.origin.y.roundToInt()) }                                 // Laid out at the glyph run's natural size, then-                                // stretched onto the box by the layer transform+                                // stretched onto the quad by the layer transform                                 // below. An OCR box's aspect ratio never matches a                                 // font's, so a font size alone can only match the                                 // box's width or its height, not both.@@ -107,9 +168,13 @@ fun OcrTextLayer(                                     height = with(density) { p.measured.height.toDp() },                                 )                                 .graphicsLayer {+                                    // Scale is applied to the content before the+                                    // rotation, so the run is stretched along its+                                    // own axes and then turned onto the quad.                                     transformOrigin = TransformOrigin(0f, 0f)                                     scaleX = p.scaleX                                     scaleY = p.scaleY+                                    rotationZ = p.angleDegrees                                 },                         )                     }@@ -119,16 +184,45 @@ fun OcrTextLayer(     } } -/** One OCR line resolved to on-screen pixels plus the stretch onto its box. */+/**+ * Forwards everything to the real [TextToolbar] while reporting whether it is+ * being shown, which is the only signal [SelectionContainer] gives out about+ * whether anything is currently selected.+ */+private class SelectionAwareTextToolbar(+    private val delegate: TextToolbar,+    private val onShownChange: (Boolean) -> Unit,+) : TextToolbar {+    override val status: TextToolbarStatus get() = delegate.status++    override fun showMenu(+        rect: Rect,+        onCopyRequested: (() -> Unit)?,+        onPasteRequested: (() -> Unit)?,+        onCutRequested: (() -> Unit)?,+        onSelectAllRequested: (() -> Unit)?,+    ) {+        onShownChange(true)+        delegate.showMenu(rect, onCopyRequested, onPasteRequested, onCutRequested, onSelectAllRequested)+    }++    override fun hide() {+        onShownChange(false)+        delegate.hide()+    }+}++/** One OCR line resolved to on-screen pixels plus the stretch onto its quad. */ private data class OcrPlacement(     val text: String,-    val left: Float,-    val top: Float,-    val width: Float,-    val height: Float,+    /** The quad's first corner: where the text run starts. */+    val origin: Offset,+    val outline: Path,     val measured: IntSize,     val scaleX: Float,     val scaleY: Float,+    /** Clockwise screen-space rotation of the run, from the quad's top edge. */+    val angleDegrees: Float, )  private fun placeBoxes(@@ -145,8 +239,25 @@ private fun placeBoxes(     val originY = (containerSize.height - layout.h * fit) / 2f      return layout.boxes.mapNotNull { box ->-        val width = (box.right - box.left) * fit-        val height = (box.bottom - box.top) * fit+        // The letterbox is a uniform scale, so mapping the corners through it+        // leaves the quad's angle intact. Rows stored before the detector+        // returned quads fall back to their axis-aligned box.+        val quad = box.quad+        val corners = if (quad != null && quad.size == 8) {+            List(4) { Offset(originX + quad[it * 2] * fit, originY + quad[it * 2 + 1] * fit) }+        } else {+            listOf(+                Offset(originX + box.left * fit, originY + box.top * fit),+                Offset(originX + box.right * fit, originY + box.top * fit),+                Offset(originX + box.right * fit, originY + box.bottom * fit),+                Offset(originX + box.left * fit, originY + box.bottom * fit),+            )+        }++        val runX = corners[1].x - corners[0].x+        val runY = corners[1].y - corners[0].y+        val width = hypot(runX, runY)+        val height = hypot(corners[3].x - corners[0].x, corners[3].y - corners[0].y)         if (width <= 0f || height <= 0f) return@mapNotNull null         // Compose concatenates each selectable's text with no separator, so every         // line has to carry its own newline or a multi-line copy comes out as one@@ -156,16 +267,24 @@ private fun placeBoxes(         if (measured.width <= 0 || measured.height <= 0) return@mapNotNull null         OcrPlacement(             text = text,-            left = originX + box.left * fit,-            top = originY + box.top * fit,-            width = width,-            height = height,+            origin = corners[0],+            outline = Path().apply {+                moveTo(corners[0].x, corners[0].y)+                lineTo(corners[1].x, corners[1].y)+                lineTo(corners[2].x, corners[2].y)+                lineTo(corners[3].x, corners[3].y)+                close()+            },             measured = measured,             scaleX = width / measured.width,             scaleY = height / measured.height,+            angleDegrees = (atan2(runY, runX) * 180f / PI).toFloat(),         )     } }  private val BASE_FONT_SIZE = 16.sp private val OUTLINE_STROKE = 1.dp+private val OUTLINE_HALO = 3.dp+private val SELECTION_COLOR = Color(0xFF448AFF)+private const val DIM_LINGER_MS = 250L
photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.ktindex c65b4baaa0..f9f9dfb012 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt@@ -497,6 +497,7 @@ fun PhotoDetailView(                         layout = layout,                         containerSize = size,                         showOutlines = isMetadataVisible,+                        zoom = currentZoom.scale,                         modifier = Modifier.fillMaxSize().then(zoomModifier)                 )             }