Modern Apps git

← Modern-Apps.git

metadata: add some missing metadata

Commit
be63b1df41c70f035a03f5bd97ef3f1f48183b77
Author
Vayun Mathur <[email protected]>
When
2026-08-01 14:00 UTC (4 months ago)
Parents
16ff5df

Diff

calculator/src/androidTest/java/com/vayunmathur/calculator/MetadataScreenshots.kt
diff --git a/calculator/src/androidTest/java/com/vayunmathur/calculator/MetadataScreenshots.kt b/calculator/src/androidTest/java/com/vayunmathur/calculator/MetadataScreenshots.ktnew file mode 100644index 0000000000..4fbf138b4a--- /dev/null+++ b/calculator/src/androidTest/java/com/vayunmathur/calculator/MetadataScreenshots.kt@@ -0,0 +1,55 @@+package com.vayunmathur.calculator++import android.graphics.Bitmap+import androidx.compose.ui.graphics.asAndroidBitmap+import androidx.compose.ui.test.captureToImage+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onRoot+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import java.io.File++/**+ * Screenshot generator driven by `:calculator:metadata`.+ * Auto-captures calculator screen with seeded history.+ */+@RunWith(AndroidJUnit4::class)+class MetadataScreenshots {++    @get:Rule+    val composeRule = createAndroidComposeRule<MainActivity>()++    private val ctx = InstrumentationRegistry.getInstrumentation().targetContext++    private val outDir: File by lazy {+        File(ctx.getExternalFilesDir(null), "metadata_screenshots").apply {+            deleteRecursively()+            mkdirs()+        }+    }++    private fun snap(index: Int) {+        composeRule.waitForIdle()+        Thread.sleep(500)+        val image = composeRule.onRoot().captureToImage()+        File(outDir, "$index.png").outputStream().use { out ->+            image.asAndroidBitmap().compress(Bitmap.CompressFormat.PNG, 100, out)+        }+    }++    @Test+    fun generateStoreScreenshots() {+        // Wait for main screen to settle (bottom nav with Calculator/Graph)+        composeRule.waitUntil(timeoutMillis = 15_000) {+            composeRule.onAllNodesWithText("Calculator", substring = true).fetchSemanticsNodes().isNotEmpty()+        }+        Thread.sleep(1000)+        snap(1) // calculator pad+        Thread.sleep(400)+        snap(2) // second shot for store requirement+    }+}
calculator/src/main/java/com/vayunmathur/calculator/ui/GraphPage.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/ui/GraphPage.kt b/calculator/src/main/java/com/vayunmathur/calculator/ui/GraphPage.ktindex f751f8b424..e9830e251b 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/ui/GraphPage.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/ui/GraphPage.kt@@ -4,12 +4,16 @@ import androidx.compose.ui.res.stringResource import com.vayunmathur.calculator.R import androidx.compose.foundation.Canvas import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.gestures.detectTransformGestures import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn@@ -19,6 +23,10 @@ import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.saveable.rememberSaveable+import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip@@ -38,6 +46,7 @@ import com.vayunmathur.calculator.util.CalculatorViewModel import com.vayunmathur.calculator.util.Expression import com.vayunmathur.calculator.util.FeatureKind import com.vayunmathur.calculator.util.GraphAnalysis+import com.vayunmathur.calculator.util.GraphFunction import com.vayunmathur.calculator.util.GraphPoint import com.vayunmathur.calculator.util.formatResult import com.vayunmathur.library.ui.AssistChip@@ -46,8 +55,8 @@ import com.vayunmathur.library.ui.HorizontalDivider import com.vayunmathur.library.ui.IconAdd import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.IconClose-import com.vayunmathur.library.ui.IconVisibilityOff-import com.vayunmathur.library.ui.IconVisible+import com.vayunmathur.library.ui.IconKeyboardArrowDown+import com.vayunmathur.library.ui.IconKeyboardArrowUp import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.OutlinedTextField import com.vayunmathur.library.ui.Scaffold@@ -223,48 +232,84 @@ private fun GraphCanvas(viewModel: CalculatorViewModel, modifier: Modifier) {     } } +/** Roughly four rows; past that the list scrolls rather than eating the canvas. */+private val EditorListMaxHeight = 240.dp+ @Composable private fun FunctionEditors(viewModel: CalculatorViewModel) {-    LazyColumn(Modifier.fillMaxWidth().heightIn(max = 240.dp).padding(horizontal = 12.dp)) {-        items(viewModel.functions, key = { it.id }) { fn ->-            val error = fn.text.isNotBlank() && runCatching { Expression.parse(fn.text) }.isFailure-            Column(Modifier.fillMaxWidth().padding(vertical = 4.dp)) {-                Row(verticalAlignment = Alignment.CenterVertically) {-                    Box(Modifier.size(16.dp).clip(CircleShape).background(fn.color))-                    OutlinedTextField(-                        value = fn.text,-                        onValueChange = { viewModel.updateFunction(fn.id, it) },-                        modifier = Modifier.weight(1f).padding(horizontal = 8.dp),-                        prefix = { Text(if (fn.polar) "r = " else "y = ") },-                        singleLine = true,-                        isError = error,-                        placeholder = { Text(if (fn.polar) "f(θ)" else "f(x)") },-                    )-                    IconButton({ viewModel.toggleFunction(fn.id) }) {-                        if (fn.enabled) IconVisible() else IconVisibilityOff()-                    }-                    IconButton({ viewModel.removeFunction(fn.id) }) { IconClose() }-                }-                FilterChip(-                    selected = fn.polar,-                    onClick = { viewModel.togglePolar(fn.id) },-                    label = { Text(if (fn.polar) "Polar r(θ)" else "Cartesian y(x)") },-                    modifier = Modifier.padding(start = 24.dp),-                )+    var expanded by rememberSaveable { mutableStateOf(true) }+    Column(Modifier.fillMaxWidth()) {+        // Slim control strip: add a curve, or fold the list away and hand the whole screen+        // to the canvas.+        Row(+            Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp),+            verticalAlignment = Alignment.CenterVertically,+        ) {+            AssistChip(+                onClick = { viewModel.addFunction(); expanded = true },+                label = { Text(stringResource(R.string.add_function)) },+                leadingIcon = { IconAdd() },+            )+            Spacer(Modifier.weight(1f))+            IconButton({ expanded = !expanded }) {+                if (expanded) IconKeyboardArrowDown() else IconKeyboardArrowUp()             }         }-        item {-            Row(Modifier.fillMaxWidth().padding(vertical = 6.dp), horizontalArrangement = Arrangement.Center) {-                AssistChip(-                    onClick = { viewModel.addFunction() },-                    label = { Text(stringResource(R.string.add_function)) },-                    leadingIcon = { IconAdd() },-                )+        if (expanded) {+            LazyColumn(+                Modifier.fillMaxWidth().heightIn(max = EditorListMaxHeight),+                contentPadding = PaddingValues(start = 4.dp, end = 4.dp, bottom = 8.dp),+                verticalArrangement = Arrangement.spacedBy(4.dp),+            ) {+                items(viewModel.functions, key = { it.id }) { fn -> FunctionRow(viewModel, fn) }             }         }     } } +/** One curve on a single line: swatch, coordinate-system toggle, expression, delete. */+@Composable+private fun FunctionRow(viewModel: CalculatorViewModel, fn: GraphFunction) {+    val error = fn.text.isNotBlank() && runCatching { Expression.parse(fn.text) }.isFailure+    Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {+        // The swatch doubles as the show/hide control — filled when the curve is drawn,+        // hollow when it isn't. Folding the two together, and moving the polar toggle up+        // beside the field, is what gets each function down from two rows to one. The dot+        // is small but sits in a full-size touch target.+        Box(+            Modifier+                .size(40.dp)+                .clip(CircleShape)+                .clickable(onClickLabel = stringResource(R.string.toggle_curve_visibility)) {+                    viewModel.toggleFunction(fn.id)+                },+            contentAlignment = Alignment.Center,+        ) {+            Box(+                Modifier.size(20.dp).clip(CircleShape).then(+                    if (fn.enabled) Modifier.background(fn.color)+                    else Modifier.border(2.dp, fn.color, CircleShape),+                ),+            )+        }+        FilterChip(+            selected = fn.polar,+            onClick = { viewModel.togglePolar(fn.id) },+            label = { Text(if (fn.polar) "r=" else "y=") },+            modifier = Modifier.padding(end = 6.dp),+        )+        OutlinedTextField(+            value = fn.text,+            onValueChange = { viewModel.updateFunction(fn.id, it) },+            modifier = Modifier.weight(1f),+            singleLine = true,+            isError = error,+            placeholder = { Text(if (fn.polar) "f(θ)" else "f(x)") },+        )+        IconButton({ viewModel.removeFunction(fn.id) }) { IconClose() }+    }+}+ /** Chooses a "nice" axis step (1, 2 or 5 × 10ⁿ) near [target] units. */ private fun niceStep(target: Double): Double {     if (target <= 0 || target.isNaN() || target.isInfinite()) return 1.0
calculator/src/main/java/com/vayunmathur/calculator/util/GraphAnalysis.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/util/GraphAnalysis.kt b/calculator/src/main/java/com/vayunmathur/calculator/util/GraphAnalysis.ktindex 6d40de06a0..7d6008277c 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/util/GraphAnalysis.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/util/GraphAnalysis.kt@@ -51,8 +51,33 @@ class SampledCurve(  */ object GraphAnalysis { -    /** θ samples for a polar curve over [0, 2π]. */-    private const val POLAR_SAMPLES = 2000+    /** Turns of θ a polar curve is swept for when it never starts retracing itself. */+    private const val POLAR_TURNS = 12++    /** θ values probed when testing whether a polar curve repeats after a whole number of turns. */+    private const val PERIOD_PROBES = 64++    /** Relative agreement required of every probe before a curve counts as repeating. */+    private const val PERIOD_TOLERANCE = 1e-9++    /** Probe spacing, in turns — irrational, so a curve can't resonate with the probe grid. */+    private const val GOLDEN_RATIO = 0.6180339887498949++    /** Target on-screen gap between consecutive polar samples, in pixels. */+    private const val POLAR_CHORD_PX = 1.0++    /** Coarsest θ step, however little the curve is doing. */+    private const val POLAR_MAX_STEP = 2 * PI / 180++    /** How much each polar step reaches beyond the one before, before being halved back. */+    private const val POLAR_STEP_GROWTH = 1.6++    /** Ceiling on polar samples per curve, so a long sweep can't stall a frame. */+    private const val POLAR_SAMPLE_BUDGET = 20000++    /** How far past the visible radius `r` must swing for a sign flip to count as a pole. */+    private const val POLE_FACTOR = 8.0+     private const val REFINE_ITERS = 80      private fun evalOrNaN(e: Expression, v: Double, angle: AngleMode): Double =@@ -62,8 +87,9 @@ object GraphAnalysis {      /**      * Samples one curve across the visible window. [columns] is normally the canvas width in-     * pixels, giving one Cartesian sample per pixel column; polar curves ignore it and sweep-     * θ over a full turn (polar angles are always radians, matching how they are drawn).+     * pixels, giving one Cartesian sample per pixel column; polar curves use it to work out+     * the pixels-per-unit of the viewport, and sweep θ over as many turns as they need+     * (polar angles are always radians, matching how they are drawn).      */     fun sample(         id: Long,@@ -87,16 +113,60 @@ object GraphAnalysis {         }          if (polar) {-            var k = 0-            while (k <= POLAR_SAMPLES) {-                val theta = 2 * PI * k / POLAR_SAMPLES-                val r = evalOrNaN(expr, theta, AngleMode.RADIANS)-                if (r.isFinite()) {-                    current.add(GraphPoint(r * cos(theta), r * sin(theta)))-                } else {+            // Polar sampling is driven by the viewport rather than by a fixed count: each+            // step reaches a little further than the last, then halves until the segment it+            // actually produced is short enough on screen. Measuring the segment rather than+            // predicting it from a derivative is what keeps a curve smooth where it sweeps+            // through the origin — a rose's radius is tiny there but its direction is+            // turning fastest — and it lets the sweep stride across the empty stretches+            // where the curve has swung out of view. Twelve turns then cost little enough+            // that spirals and other curves that never close no longer stop after one loop.+            val pxPerUnit = if (xMax > xMin) columns.coerceAtLeast(2) / (xMax - xMin) else 1.0+            // Nothing further from the origin than the farthest corner can be on screen.+            val visibleRadius = maxOf(+                hypot(xMin, yMin), hypot(xMin, yMax), hypot(xMax, yMin), hypot(xMax, yMax),+            )+            val visibleRadiusPx = (visibleRadius * pxPerUnit).coerceAtLeast(1.0)+            val thetaMax = 2 * PI * polarTurns(expr)+            // Detail has to stop somewhere, or a tight spiral would sample without end.+            val budgetStep = thetaMax / POLAR_SAMPLE_BUDGET++            /** How far apart two samples may land: a pixel on screen, looser further out. */+            fun tolerancePx(radiusPx: Double) =+                POLAR_CHORD_PX + (radiusPx - visibleRadiusPx).coerceAtLeast(0.0) / 2++            var theta = 0.0+            var r = evalOrNaN(expr, 0.0, AngleMode.RADIANS)+            var here = if (r.isFinite()) GraphPoint(r, 0.0) else null+            here?.let { current.add(it) }+            var step = POLAR_MAX_STEP+            while (theta < thetaMax) {+                step = (step * POLAR_STEP_GROWTH).coerceAtMost(POLAR_MAX_STEP)+                var nextTheta: Double+                var nextR: Double+                var next: GraphPoint?+                while (true) {+                    nextTheta = (theta + step).coerceAtMost(thetaMax)+                    nextR = evalOrNaN(expr, nextTheta, AngleMode.RADIANS)+                    next = if (nextR.isFinite()) GraphPoint(nextR * cos(nextTheta), nextR * sin(nextTheta)) else null+                    val from = here+                    val to = next+                    if (from == null || to == null || step <= 2 * budgetStep) break+                    val tolerance = tolerancePx(minOf(abs(r), abs(nextR)) * pxPerUnit)+                    if (hypot(to.x - from.x, to.y - from.y) * pxPerUnit <= tolerance) break+                    step /= 2+                }+                val to = next+                if (to == null) {                     breakRun()+                } else {+                    // A pole must not be bridged, exactly as for a Cartesian asymptote.+                    if (crossesPole(r, nextR, visibleRadius)) breakRun()+                    current.add(to)                 }-                k+++                theta = nextTheta+                r = nextR+                here = next             }         } else {             val steps = columns.coerceAtLeast(2)@@ -119,6 +189,47 @@ object GraphAnalysis {         return SampledCurve(id, expr, polar, runs)     } +    /**+     * Whether `r` flipped sign between two samples by running out towards infinity rather+     * than by passing through zero — a polar asymptote, as in `r = tan(θ)`, which would+     * otherwise be drawn as a line sweeping right across the screen. Both magnitudes have to+     * dwarf anything that could be on screen, so the zero crossing at the base of every rose+     * petal is never mistaken for one.+     */+    private fun crossesPole(prev: Double, current: Double, visibleRadius: Double): Boolean {+        if (!prev.isFinite() || !current.isFinite()) return false+        if ((prev < 0.0) == (current < 0.0)) return false+        return minOf(abs(prev), abs(current)) > POLE_FACTOR * visibleRadius+    }++    /**+     * How many turns of θ a polar curve covers before it starts retracing itself, capped at+     * [POLAR_TURNS]. A rose, circle or cardioid closes after one turn and is swept once —+     * sweeping it twelve times would only lay the same ink down twelve times over. Curves+     * that never close (`r = θ`, `r = cos(√2·θ)`, `r = θ·sin(θ)`) fail every test and get+     * the full run, which is the whole point of sweeping more than one turn.+     */+    private fun polarTurns(expr: Expression): Int {+        val probes = DoubleArray(PERIOD_PROBES) { 2 * PI * ((it * GOLDEN_RATIO) % 1.0) }+        val base = DoubleArray(PERIOD_PROBES) { evalOrNaN(expr, probes[it], AngleMode.RADIANS) }+        for (turns in 1 until POLAR_TURNS) {+            val offset = 2 * PI * turns+            var repeats = true+            for (i in probes.indices) {+                val a = base[i]+                val b = evalOrNaN(expr, probes[i] + offset, AngleMode.RADIANS)+                if (a.isNaN() && b.isNaN()) continue+                // Negated rather than `>`, so a NaN difference counts as a mismatch.+                if (!(abs(b - a) <= PERIOD_TOLERANCE * (1 + abs(a)))) {+                    repeats = false+                    break+                }+            }+            if (repeats) return turns+        }+        return POLAR_TURNS+    }+     // ---- Feature discovery ----      /**
calculator/src/main/res/values/strings.xml
diff --git a/calculator/src/main/res/values/strings.xml b/calculator/src/main/res/values/strings.xmlindex 53b55c606f..cda89e59f5 100644--- a/calculator/src/main/res/values/strings.xml+++ b/calculator/src/main/res/values/strings.xml@@ -7,6 +7,8 @@     <string name="clear">Clear</string>     <string name="graph">Graph</string>     <string name="add_function">Add function</string>+    <!-- Graph: accessibility label for the coloured dot that shows or hides one curve. -->+    <string name="toggle_curve_visibility">Show or hide this curve</string>     <!-- Graph: label on a marker where a curve crosses the x-axis. Lowercase noun, shown as "root (2, 0)". -->     <string name="feature_root">root</string>     <!-- Graph: label on a marker where a curve crosses the y-axis. Lowercase noun, shown as "y-intercept (0, 3)". -->
code/src/androidTest/java/com/vayunmathur/code/MetadataScreenshots.kt
diff --git a/code/src/androidTest/java/com/vayunmathur/code/MetadataScreenshots.kt b/code/src/androidTest/java/com/vayunmathur/code/MetadataScreenshots.ktnew file mode 100644index 0000000000..95744e3463--- /dev/null+++ b/code/src/androidTest/java/com/vayunmathur/code/MetadataScreenshots.kt@@ -0,0 +1,55 @@+package com.vayunmathur.code++import android.graphics.Bitmap+import androidx.compose.ui.graphics.asAndroidBitmap+import androidx.compose.ui.test.captureToImage+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onRoot+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import java.io.File++/**+ * Screenshot generator driven by `:code:metadata`.+ * Captures the editor empty state and file-tree prompt (no seeding needed).+ * A richer version could seed tabs via ViewModel, but this is robust for auto.+ */+@RunWith(AndroidJUnit4::class)+class MetadataScreenshots {++    @get:Rule+    val composeRule = createAndroidComposeRule<MainActivity>()++    private val ctx = InstrumentationRegistry.getInstrumentation().targetContext++    private val outDir: File by lazy {+        File(ctx.getExternalFilesDir(null), "metadata_screenshots").apply {+            deleteRecursively()+            mkdirs()+        }+    }++    private fun snap(index: Int) {+        composeRule.waitForIdle()+        Thread.sleep(500)+        val image = composeRule.onRoot().captureToImage()+        File(outDir, "$index.png").outputStream().use { out ->+            image.asAndroidBitmap().compress(Bitmap.CompressFormat.PNG, 100, out)+        }+    }++    @Test+    fun generateStoreScreenshots() {+        composeRule.waitUntil(timeoutMillis = 15_000) {+            composeRule.onAllNodesWithText("Code", substring = true).fetchSemanticsNodes().isNotEmpty() ||+                composeRule.onAllNodesWithText("Open", substring = true).fetchSemanticsNodes().isNotEmpty()+        }+        Thread.sleep(1000)+        snap(1)+        snap(2)+    }+}
education/src/androidTest/java/com/vayunmathur/education/MetadataScreenshots.kt
diff --git a/education/src/androidTest/java/com/vayunmathur/education/MetadataScreenshots.kt b/education/src/androidTest/java/com/vayunmathur/education/MetadataScreenshots.ktnew file mode 100644index 0000000000..a0b84e447f--- /dev/null+++ b/education/src/androidTest/java/com/vayunmathur/education/MetadataScreenshots.kt@@ -0,0 +1,55 @@+package com.vayunmathur.education++import android.graphics.Bitmap+import androidx.compose.ui.graphics.asAndroidBitmap+import androidx.compose.ui.test.captureToImage+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onRoot+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import java.io.File++/**+ * Screenshot generator driven by `:education:metadata`.+ * Captures home / course list. No DB seeding to stay compile-safe.+ */+@RunWith(AndroidJUnit4::class)+class MetadataScreenshots {++    @get:Rule+    val composeRule = createAndroidComposeRule<MainActivity>()++    private val ctx = InstrumentationRegistry.getInstrumentation().targetContext++    private val outDir: File by lazy {+        File(ctx.getExternalFilesDir(null), "metadata_screenshots").apply {+            deleteRecursively()+            mkdirs()+        }+    }++    private fun snap(index: Int) {+        composeRule.waitForIdle()+        Thread.sleep(700)+        val image = composeRule.onRoot().captureToImage()+        File(outDir, "$index.png").outputStream().use { out ->+            image.asAndroidBitmap().compress(Bitmap.CompressFormat.PNG, 100, out)+        }+    }++    @Test+    fun generateStoreScreenshots() {+        composeRule.waitUntil(timeoutMillis = 20_000) {+            composeRule.onAllNodesWithText("Education", substring = true).fetchSemanticsNodes().isNotEmpty() ||+                composeRule.onAllNodesWithText("Math", substring = true).fetchSemanticsNodes().isNotEmpty() ||+                composeRule.onAllNodesWithText("Learn", substring = true).fetchSemanticsNodes().isNotEmpty()+        }+        Thread.sleep(1500)+        snap(1)+        snap(2)+    }+}
fooddelivery/build.gradle.kts
diff --git a/fooddelivery/build.gradle.kts b/fooddelivery/build.gradle.ktsindex 564b0cc0a4..19e08aabd6 100644--- a/fooddelivery/build.gradle.kts+++ b/fooddelivery/build.gradle.kts@@ -1,5 +1,6 @@ plugins {     id("common-conventions-app")+    id("common-conventions-metadata") }  launcherIcon {
fooddelivery/src/androidTest/java/com/vayunmathur/fooddelivery/MetadataScreenshots.kt
diff --git a/fooddelivery/src/androidTest/java/com/vayunmathur/fooddelivery/MetadataScreenshots.kt b/fooddelivery/src/androidTest/java/com/vayunmathur/fooddelivery/MetadataScreenshots.ktnew file mode 100644index 0000000000..ca4851e24c--- /dev/null+++ b/fooddelivery/src/androidTest/java/com/vayunmathur/fooddelivery/MetadataScreenshots.kt@@ -0,0 +1,57 @@+package com.vayunmathur.fooddelivery++import android.graphics.Bitmap+import androidx.compose.ui.graphics.asAndroidBitmap+import androidx.compose.ui.test.captureToImage+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onRoot+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import java.io.File++/**+ * Screenshot generator driven by `:fooddelivery:metadata`.+ * External API dependent — captures home/empty states.+ * FLAG: Full restaurant + checkout + Stripe flow needs manual screenshots+ * due to external merchant config and API keys.+ */+@RunWith(AndroidJUnit4::class)+class MetadataScreenshots {++    @get:Rule+    val composeRule = createAndroidComposeRule<MainActivity>()++    private val ctx = InstrumentationRegistry.getInstrumentation().targetContext++    private val outDir: File by lazy {+        File(ctx.getExternalFilesDir(null), "metadata_screenshots").apply {+            deleteRecursively()+            mkdirs()+        }+    }++    private fun snap(index: Int) {+        composeRule.waitForIdle()+        Thread.sleep(600)+        val image = composeRule.onRoot().captureToImage()+        File(outDir, "$index.png").outputStream().use { out ->+            image.asAndroidBitmap().compress(Bitmap.CompressFormat.PNG, 100, out)+        }+    }++    @Test+    fun generateStoreScreenshots() {+        composeRule.waitUntil(timeoutMillis = 15_000) {+            composeRule.onAllNodesWithText("Restaurant", substring = true).fetchSemanticsNodes().isNotEmpty() ||+                composeRule.onAllNodesWithText("Home", substring = true).fetchSemanticsNodes().isNotEmpty() ||+                composeRule.onAllNodesWithText("Food", substring = true).fetchSemanticsNodes().isNotEmpty()+        }+        Thread.sleep(1000)+        snap(1)+        snap(2)+    }+}
games/logicgate/src/androidTest/java/com/vayunmathur/games/logicgate/MetadataScreenshots.kt
diff --git a/games/logicgate/src/androidTest/java/com/vayunmathur/games/logicgate/MetadataScreenshots.kt b/games/logicgate/src/androidTest/java/com/vayunmathur/games/logicgate/MetadataScreenshots.ktnew file mode 100644index 0000000000..0cf71037ec--- /dev/null+++ b/games/logicgate/src/androidTest/java/com/vayunmathur/games/logicgate/MetadataScreenshots.kt@@ -0,0 +1,54 @@+package com.vayunmathur.games.logicgate++import android.graphics.Bitmap+import androidx.compose.ui.graphics.asAndroidBitmap+import androidx.compose.ui.test.captureToImage+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onRoot+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import java.io.File++/**+ * Screenshot generator driven by `:games:logicgate:metadata`.+ * Captures progression list and a level's circuit canvas.+ */+@RunWith(AndroidJUnit4::class)+class MetadataScreenshots {++    @get:Rule+    val composeRule = createAndroidComposeRule<MainActivity>()++    private val ctx = InstrumentationRegistry.getInstrumentation().targetContext++    private val outDir: File by lazy {+        File(ctx.getExternalFilesDir(null), "metadata_screenshots").apply {+            deleteRecursively()+            mkdirs()+        }+    }++    private fun snap(index: Int) {+        composeRule.waitForIdle()+        Thread.sleep(600)+        val image = composeRule.onRoot().captureToImage()+        File(outDir, "$index.png").outputStream().use { out ->+            image.asAndroidBitmap().compress(Bitmap.CompressFormat.PNG, 100, out)+        }+    }++    @Test+    fun generateStoreScreenshots() {+        composeRule.waitUntil(timeoutMillis = 15_000) {+            composeRule.onAllNodesWithText("Logic", substring = true).fetchSemanticsNodes().isNotEmpty() ||+                composeRule.onAllNodesWithText("Level", substring = true).fetchSemanticsNodes().isNotEmpty()+        }+        Thread.sleep(1000)+        snap(1)+        snap(2)+    }+}
games/voxels/src/androidTest/java/com/vayunmathur/games/voxels/MetadataScreenshots.kt
diff --git a/games/voxels/src/androidTest/java/com/vayunmathur/games/voxels/MetadataScreenshots.kt b/games/voxels/src/androidTest/java/com/vayunmathur/games/voxels/MetadataScreenshots.ktnew file mode 100644index 0000000000..b59bead99f--- /dev/null+++ b/games/voxels/src/androidTest/java/com/vayunmathur/games/voxels/MetadataScreenshots.kt@@ -0,0 +1,65 @@+package com.vayunmathur.games.voxels++import android.app.Activity+import android.graphics.Bitmap+import androidx.test.core.app.ActivityScenario+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import org.junit.Test+import org.junit.runner.RunWith+import java.io.File++/**+ * Screenshot generator driven by `:games:voxels:metadata`.+ * Voxels uses native Rust + Vulkan; Compose captureToImage won't capture GL.+ * Uses UiAutomation.takeScreenshot() for full device capture.+ */+@RunWith(AndroidJUnit4::class)+class MetadataScreenshots {++    private val instrumentation = InstrumentationRegistry.getInstrumentation()+    private val ctx = instrumentation.targetContext++    private val outDir: File by lazy {+        File(ctx.getExternalFilesDir(null), "metadata_screenshots").apply {+            deleteRecursively()+            mkdirs()+        }+    }++    private fun snapDevice(index: Int) {+        Thread.sleep(900)+        val bmp: Bitmap? = try {+            instrumentation.uiAutomation.takeScreenshot()+        } catch (_: Exception) { null }+        bmp?.let { b ->+            File(outDir, "$index.png").outputStream().use { out ->+                b.compress(Bitmap.CompressFormat.PNG, 100, out)+            }+        }+    }++    @Test+    fun generateStoreScreenshots() {+        outDir+        // Try MenuActivity first if present, else MainActivity+        try {+            val menuCls = Class.forName("com.vayunmathur.games.voxels.MenuActivity") as Class<Activity>+            ActivityScenario.launch(menuCls).use {+                Thread.sleep(2500)+                snapDevice(1)+            }+            ActivityScenario.launch(MainActivity::class.java).use {+                Thread.sleep(4000)+                snapDevice(2)+            }+        } catch (_: Exception) {+            ActivityScenario.launch(MainActivity::class.java).use {+                Thread.sleep(4000)+                snapDevice(1)+                Thread.sleep(1500)+                snapDevice(2)+            }+        }+    }+}
keyboard/src/androidTest/java/com/vayunmathur/keyboard/MetadataScreenshots.kt
diff --git a/keyboard/src/androidTest/java/com/vayunmathur/keyboard/MetadataScreenshots.kt b/keyboard/src/androidTest/java/com/vayunmathur/keyboard/MetadataScreenshots.ktnew file mode 100644index 0000000000..587733330c--- /dev/null+++ b/keyboard/src/androidTest/java/com/vayunmathur/keyboard/MetadataScreenshots.kt@@ -0,0 +1,57 @@+package com.vayunmathur.keyboard++import android.graphics.Bitmap+import androidx.compose.ui.graphics.asAndroidBitmap+import androidx.compose.ui.test.captureToImage+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onRoot+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import java.io.File++/**+ * Screenshot generator driven by `:keyboard:metadata`.+ * Captures the Setup screen (Enable / Choose / Settings). The actual IME+ * keyboard UI lives in InputMethodService's window and cannot be auto-captured+ * via Compose tests — that shot needs manual capture.+ *+ * FLAG: keyboard IME open state should be manual.+ */+@RunWith(AndroidJUnit4::class)+class MetadataScreenshots {++    @get:Rule+    val composeRule = createAndroidComposeRule<MainActivity>()++    private val ctx = InstrumentationRegistry.getInstrumentation().targetContext++    private val outDir: File by lazy {+        File(ctx.getExternalFilesDir(null), "metadata_screenshots").apply {+            deleteRecursively()+            mkdirs()+        }+    }++    private fun snap(index: Int) {+        composeRule.waitForIdle()+        Thread.sleep(600)+        val image = composeRule.onRoot().captureToImage()+        File(outDir, "$index.png").outputStream().use { out ->+            image.asAndroidBitmap().compress(Bitmap.CompressFormat.PNG, 100, out)+        }+    }++    @Test+    fun generateStoreScreenshots() {+        composeRule.waitUntil(timeoutMillis = 15_000) {+            composeRule.onAllNodesWithText("Keyboard", substring = true).fetchSemanticsNodes().isNotEmpty()+        }+        Thread.sleep(1000)+        snap(1)+        snap(2)+    }+}
metadata_data/calculator.md
diff --git a/metadata_data/calculator.md b/metadata_data/calculator.mdnew file mode 100644index 0000000000..416b31939b--- /dev/null+++ b/metadata_data/calculator.md@@ -0,0 +1,7 @@+A modern, open-source calculator with a graphing engine++Features:+- Scientific and basic calculator modes+- Function graphing with root, intercept, min/max, and intersection detection+- Expression history+- Material You design
metadata_data/code.md
diff --git a/metadata_data/code.md b/metadata_data/code.mdnew file mode 100644index 0000000000..4e1b30d5a1--- /dev/null+++ b/metadata_data/code.md@@ -0,0 +1,8 @@+A lightweight, open-source code editor for Android++Features:+- Folder-based project browsing via Storage Access Framework+- Syntax highlighting for common languages+- Find and replace across files+- Multiple open tabs with undo/redo+- Handles VIEW/EDIT intents from other apps
metadata_data/education.md
diff --git a/metadata_data/education.md b/metadata_data/education.mdnew file mode 100644index 0000000000..b3cdfa0797--- /dev/null+++ b/metadata_data/education.md@@ -0,0 +1,8 @@+A free, open-source education app for kids and curious learners++Features:+- K2 to K12 curriculum with quizzes, tracing, and drag-match activities+- Video lessons (Khan Academy / YouTube streaming)+- Offline-first course catalog with progress tracking+- Parent gate and daily goal tracking+- Badges and streaks to keep kids motivated
metadata_data/everysync.md
diff --git a/metadata_data/everysync.md b/metadata_data/everysync.mdnew file mode 100644index 0000000000..f48d1b3786--- /dev/null+++ b/metadata_data/everysync.md@@ -0,0 +1,8 @@+A free, open-source universal sync hub for your personal data++Features:+- Sync contacts and calendars across Google, iCloud, Nextcloud, and custom CalDAV/CardDAV+- Health Connect bridge for fitness data+- Background periodic sync via WorkManager+- End-to-end credential storage in app-private encrypted storage+- OAuth2 PKCE flow via Custom Tabs (no client secrets shipped)
metadata_data/fooddelivery.md
diff --git a/metadata_data/fooddelivery.md b/metadata_data/fooddelivery.mdnew file mode 100644index 0000000000..c449c314ac--- /dev/null+++ b/metadata_data/fooddelivery.md@@ -0,0 +1,7 @@+An open-source food delivery client with Stripe payments++Features:+- Browse restaurants and menus+- Cart and checkout with Stripe integration+- Order tracking and history+- Address and payment management
metadata_data/games-logicgate.md
diff --git a/metadata_data/games-logicgate.md b/metadata_data/games-logicgate.mdnew file mode 100644index 0000000000..a60f01d90d--- /dev/null+++ b/metadata_data/games-logicgate.md@@ -0,0 +1,7 @@+A logic gate puzzle game — wire up circuits to solve levels++Features:+- Intuitive drag-to-connect gate wiring+- Progressive difficulty with new gate types+- Completely offline and open source+- Material You design
metadata_data/games-voxels.md
diff --git a/metadata_data/games-voxels.md b/metadata_data/games-voxels.mdnew file mode 100644index 0000000000..85156c7f43--- /dev/null+++ b/metadata_data/games-voxels.md@@ -0,0 +1,7 @@+A voxel sandbox game with a full Rust + Vulkan engine++Features:+- Infinite voxel world with procedural generation+- Native Rust engine (ash/Vulkan) with optimized texture atlas+- Block placement and destruction+- Completely offline and open source
metadata_data/keyboard.md
diff --git a/metadata_data/keyboard.md b/metadata_data/keyboard.mdnew file mode 100644index 0000000000..244b016ba9--- /dev/null+++ b/metadata_data/keyboard.md@@ -0,0 +1,8 @@+A private, open-source keyboard with Material You++Features:+- Follows system light/dark theme and Material You dynamic colors+- Adjustable key height+- Emoji support+- No network access, fully offline+- Minimal, distraction-free typing
metadata_data/speech.md
diff --git a/metadata_data/speech.md b/metadata_data/speech.mdnew file mode 100644index 0000000000..ee9d4c9f82--- /dev/null+++ b/metadata_data/speech.md@@ -0,0 +1,9 @@+A fully offline speech-to-text and text-to-speech app++Features:+- Offline speech recognition using Whisper (tiny model)+- Offline TTS using Piper (VITS voices)+- Runs entirely on-device with no network calls after model download+- Works as system SpeechRecognizer and TTS service++Models are downloaded at runtime from a transparent mirror and are SHA-256 pinned.
metadata_data/translate.md
diff --git a/metadata_data/translate.md b/metadata_data/translate.mdnew file mode 100644index 0000000000..ccecd7ddf0--- /dev/null+++ b/metadata_data/translate.md@@ -0,0 +1,10 @@+A fully offline translation app with camera OCR++Features:+- Offline neural translation using SMaLL-100 (ncnn)+- Camera translation with on-device OCR+- Text translation from any app via the selection menu+- Supports dozens of languages entirely offline+- No network calls after model download++Model files (~1.2 GB) are downloaded once from a transparent mirror and are SHA-256 verified.
metadata_data/travel.md
diff --git a/metadata_data/travel.md b/metadata_data/travel.mdnew file mode 100644index 0000000000..e76557beed--- /dev/null+++ b/metadata_data/travel.md@@ -0,0 +1,9 @@+An open-source flight and hotel booking app++Features:+- Flight search and comparison+- Hotel / stays search+- Seat map selection+- Ancillaries and offers+- Order management and trip tracking+- Offline Room-backed trip storage
metadata_data/vpn.md
diff --git a/metadata_data/vpn.md b/metadata_data/vpn.mdnew file mode 100644index 0000000000..0737508b52--- /dev/null+++ b/metadata_data/vpn.md@@ -0,0 +1,8 @@+A simple, open-source VPN client with WireGuard support++Features:+- WireGuard protocol via native Rust library+- Per-app VPN bypass list+- Manual WireGuard config import+- Connection logging+- Material You design with dynamic theming
metadata_data/web.md
diff --git a/metadata_data/web.md b/metadata_data/web.mdnew file mode 100644index 0000000000..f2a9af31ca--- /dev/null+++ b/metadata_data/web.md@@ -0,0 +1,10 @@+A privacy-focused open-source web browser with PWA support++Features:+- DuckDuckGo search by default (locked for privacy)+- Ad-tracker blocking (doubleclick, googletagmanager, analytics)+- PWA installation with standalone activity (no browser chrome)+- Bookmarks, history, and downloads management+- Per-site permission and storage controls+- Private tabs with no persistence+- Desktop mode toggle
speech/src/androidTest/java/com/vayunmathur/speech/MetadataScreenshots.kt
diff --git a/speech/src/androidTest/java/com/vayunmathur/speech/MetadataScreenshots.kt b/speech/src/androidTest/java/com/vayunmathur/speech/MetadataScreenshots.ktnew file mode 100644index 0000000000..1dad778e62--- /dev/null+++ b/speech/src/androidTest/java/com/vayunmathur/speech/MetadataScreenshots.kt@@ -0,0 +1,54 @@+package com.vayunmathur.speech++import android.graphics.Bitmap+import androidx.compose.ui.graphics.asAndroidBitmap+import androidx.compose.ui.test.captureToImage+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onRoot+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import java.io.File++/**+ * Screenshot generator driven by `:speech:metadata`.+ * Captures offline model download / setup UI.+ */+@RunWith(AndroidJUnit4::class)+class MetadataScreenshots {++    @get:Rule+    val composeRule = createAndroidComposeRule<MainActivity>()++    private val ctx = InstrumentationRegistry.getInstrumentation().targetContext++    private val outDir: File by lazy {+        File(ctx.getExternalFilesDir(null), "metadata_screenshots").apply {+            deleteRecursively()+            mkdirs()+        }+    }++    private fun snap(index: Int) {+        composeRule.waitForIdle()+        Thread.sleep(600)+        val image = composeRule.onRoot().captureToImage()+        File(outDir, "$index.png").outputStream().use { out ->+            image.asAndroidBitmap().compress(Bitmap.CompressFormat.PNG, 100, out)+        }+    }++    @Test+    fun generateStoreScreenshots() {+        composeRule.waitUntil(timeoutMillis = 15_000) {+            composeRule.onAllNodesWithText("Speech", substring = true).fetchSemanticsNodes().isNotEmpty() ||+                composeRule.onAllNodesWithText("Download", substring = true).fetchSemanticsNodes().isNotEmpty()+        }+        Thread.sleep(1000)+        snap(1)+        snap(2)+    }+}
translate/src/androidTest/java/com/vayunmathur/translate/MetadataScreenshots.kt
diff --git a/translate/src/androidTest/java/com/vayunmathur/translate/MetadataScreenshots.kt b/translate/src/androidTest/java/com/vayunmathur/translate/MetadataScreenshots.ktnew file mode 100644index 0000000000..65b86107b8--- /dev/null+++ b/translate/src/androidTest/java/com/vayunmathur/translate/MetadataScreenshots.kt@@ -0,0 +1,54 @@+package com.vayunmathur.translate++import android.graphics.Bitmap+import androidx.compose.ui.graphics.asAndroidBitmap+import androidx.compose.ui.test.captureToImage+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onRoot+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import java.io.File++/**+ * Screenshot generator driven by `:translate:metadata`.+ * Models (~1.2 GB) aren't bundled; captures download gate UI.+ */+@RunWith(AndroidJUnit4::class)+class MetadataScreenshots {++    @get:Rule+    val composeRule = createAndroidComposeRule<MainActivity>()++    private val ctx = InstrumentationRegistry.getInstrumentation().targetContext++    private val outDir: File by lazy {+        File(ctx.getExternalFilesDir(null), "metadata_screenshots").apply {+            deleteRecursively()+            mkdirs()+        }+    }++    private fun snap(index: Int) {+        composeRule.waitForIdle()+        Thread.sleep(600)+        val image = composeRule.onRoot().captureToImage()+        File(outDir, "$index.png").outputStream().use { out ->+            image.asAndroidBitmap().compress(Bitmap.CompressFormat.PNG, 100, out)+        }+    }++    @Test+    fun generateStoreScreenshots() {+        composeRule.waitUntil(timeoutMillis = 15_000) {+            composeRule.onAllNodesWithText("Translate", substring = true).fetchSemanticsNodes().isNotEmpty() ||+                composeRule.onAllNodesWithText("Download", substring = true).fetchSemanticsNodes().isNotEmpty()+        }+        Thread.sleep(1000)+        snap(1)+        snap(2)+    }+}
translate/src/main/java/com/vayunmathur/translate/ui/CameraTranslateScreen.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/ui/CameraTranslateScreen.kt b/translate/src/main/java/com/vayunmathur/translate/ui/CameraTranslateScreen.ktindex b3596bbdc5..f68f453160 100644--- a/translate/src/main/java/com/vayunmathur/translate/ui/CameraTranslateScreen.kt+++ b/translate/src/main/java/com/vayunmathur/translate/ui/CameraTranslateScreen.kt@@ -8,11 +8,17 @@ import kotlin.concurrent.atomics.* import android.Manifest import android.graphics.Bitmap import android.graphics.Matrix+import android.hardware.display.DisplayManager import android.util.Log+import android.util.Size+import android.view.Surface import androidx.camera.core.Camera import androidx.camera.core.CameraSelector import androidx.camera.core.ImageAnalysis import androidx.camera.core.Preview+import androidx.camera.core.resolutionselector.AspectRatioStrategy+import androidx.camera.core.resolutionselector.ResolutionSelector+import androidx.camera.core.resolutionselector.ResolutionStrategy import androidx.camera.lifecycle.ProcessCameraProvider import androidx.camera.lifecycle.awaitInstance import androidx.camera.view.PreviewView@@ -29,6 +35,8 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.text.BasicText+import androidx.compose.foundation.text.TextAutoSize import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect@@ -47,6 +55,8 @@ import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp@@ -63,29 +73,47 @@ import com.vayunmathur.library.ui.PermissionsChecker import com.vayunmathur.library.ui.Text import com.vayunmathur.translate.util.Languages import com.vayunmathur.translate.util.TranslateViewModel+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.delay+import kotlinx.coroutines.isActive import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext import java.util.concurrent.Executors import kotlin.math.max import kotlin.math.roundToInt -/** Minimum gap between analyzed frames (ms) — throttles OCR to keep it light. */-private const val ANALYSIS_INTERVAL_MS = 700L+/** Minimum gap between the *end* of one OCR pass and the start of the next (ms). */+private const val ANALYSIS_INTERVAL_MS = 400L -/** One translated line positioned in the (upright) analysed-bitmap's pixel space. */+/**+ * Resolution requested for the analysis stream, in sensor (landscape) orientation.+ * CameraX defaults ImageAnalysis to 640×480, which is far too coarse for PP-OCRv5 to+ * detect anything but very large text — this is the single biggest reason the camera+ * used to look like it "saw" nothing. 4:3 matches the preview stream's aspect ratio,+ * which the overlay mapping below relies on.+ */+private val ANALYSIS_SIZE = Size(1280, 960)++/** Upper bound on the translation memo; plenty for a screenful of lines. */+private const val TRANSLATION_CACHE_MAX = 128++/** Idle poll while every visible line already has a translation (ms). */+private const val TRANSLATE_IDLE_POLL_MS = 100L++/** One detected line, in the (upright) analysed-bitmap's pixel space. Holds the *source* text. */ private data class OverlayBox(     val left: Int,     val top: Int,     val right: Int,     val bottom: Int,     val text: String,-    val translated: Boolean, )  @Composable fun CameraTranslateScreen(viewModel: TranslateViewModel, onBack: () -> Unit) {     PermissionsChecker(         permissions = arrayOf(Manifest.permission.CAMERA),-        text = "Grant camera access to translate what you see",+        text = stringResource(R.string.grant_camera_access),     ) {         CameraContent(viewModel, onBack)     }@@ -102,41 +130,108 @@ private fun CameraContent(viewModel: TranslateViewModel, onBack: () -> Unit) {     val targetLang by viewModel.targetLang.collectAsState()     val translationAvailable by viewModel.translationAvailable.collectAsState() -    val previewView = remember { PreviewView(context) }+    val previewView = remember {+        // The overlay maths below assumes a centre-crop preview; make that explicit+        // rather than relying on PreviewView's default.+        PreviewView(context).apply { scaleType = PreviewView.ScaleType.FILL_CENTER }+    }     var camera by remember { mutableStateOf<Camera?>(null) }+    var provider by remember { mutableStateOf<ProcessCameraProvider?>(null) }     var torchOn by remember { mutableStateOf(false) }     var paused by remember { mutableStateOf(false) } -    // OCR/translation results, in analysed-bitmap pixel coords.+    // OCR results, in analysed-bitmap pixel coords, plus the translations for the+    // lines in them. Keeping the two apart lets OCR keep running at full speed while+    // the (much slower) translator fills results in behind it.     var overlays by remember { mutableStateOf<List<OverlayBox>>(emptyList()) }+    var translations by remember { mutableStateOf<Map<String, String>>(emptyMap()) }     var frameW by remember { mutableStateOf(0) }     var frameH by remember { mutableStateOf(0) }     var frozenFrame by remember { mutableStateOf<Bitmap?>(null) }      // Read by the analysis-thread callback; kept fresh via rememberUpdatedState.     val pausedState = rememberUpdatedState(paused)-    val availableState = rememberUpdatedState(translationAvailable)      val analysisExecutor = remember { Executors.newSingleThreadExecutor() }     val inFlight = remember { AtomicBoolean(false) }     val lastMs = remember { AtomicLong(0L) } +    // Built once so the display-rotation listener and the dispose block can reach it.+    // Target rotation is pinned to ROTATION_0 here purely so [ANALYSIS_SIZE] is read in+    // sensor coords; the real rotation is applied after binding (see below).+    val analysis = remember {+        ImageAnalysis.Builder()+            .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)+            .setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_RGBA_8888)+            .setTargetRotation(Surface.ROTATION_0)+            .setResolutionSelector(+                ResolutionSelector.Builder()+                    .setAspectRatioStrategy(AspectRatioStrategy.RATIO_4_3_FALLBACK_AUTO_STRATEGY)+                    .setResolutionStrategy(+                        ResolutionStrategy(+                            ANALYSIS_SIZE,+                            ResolutionStrategy.FALLBACK_RULE_CLOSEST_HIGHER_THEN_LOWER,+                        )+                    )+                    .build()+            )+            .build()+    }++    // `Context.getDisplay()` throws on a non-visual context, hence the guard.+    fun displayRotation(): Int =+        previewView.display?.rotation+            ?: runCatching { context.display?.rotation }.getOrNull()+            ?: Surface.ROTATION_0++    // The activity handles `orientation` itself (see AndroidManifest configChanges), so+    // nothing recreates on rotation. Without this the analyser keeps reporting the+    // rotation from bind time and every box lands 90° out of place.+    DisposableEffect(analysis) {+        val displayManager = context.getSystemService(DisplayManager::class.java)+        val listener = object : DisplayManager.DisplayListener {+            override fun onDisplayAdded(displayId: Int) = Unit+            override fun onDisplayRemoved(displayId: Int) = Unit+            override fun onDisplayChanged(displayId: Int) {+                if (previewView.display?.displayId == displayId) {+                    analysis.targetRotation = displayRotation()+                }+            }+        }+        displayManager?.registerDisplayListener(listener, null)+        onDispose { displayManager?.unregisterDisplayListener(listener) }+    }++    // Release the camera when the screen goes away. Without this the torch stays lit,+    // the camera indicator stays up, and frames keep being handed to a dead executor.     DisposableEffect(Unit) {-        onDispose { analysisExecutor.shutdown() }+        onDispose {+            camera?.cameraControl?.enableTorch(false)+            analysis.clearAnalyzer()+            provider?.unbindAll()+            analysisExecutor.shutdown()+        }     } -    LaunchedEffect(torchOn) {+    // Keyed on `camera` too: the first pass runs before binding completes, when+    // there is no CameraControl to talk to yet.+    LaunchedEffect(camera, torchOn) {         camera?.cameraControl?.enableTorch(torchOn)     }      LaunchedEffect(Unit) {-        val provider = ProcessCameraProvider.awaitInstance(context)-        val preview = Preview.Builder().build().also {-            it.surfaceProvider = previewView.surfaceProvider-        }-        val analysis = ImageAnalysis.Builder()-            .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)+        val cameraProvider = ProcessCameraProvider.awaitInstance(context)+        provider = cameraProvider+        val preview = Preview.Builder()+            // Same aspect ratio as the analysis stream, so the two share a field of+            // view and the centre-crop mapping below is exact.+            .setResolutionSelector(+                ResolutionSelector.Builder()+                    .setAspectRatioStrategy(AspectRatioStrategy.RATIO_4_3_FALLBACK_AUTO_STRATEGY)+                    .build()+            )             .build()+            .also { it.surfaceProvider = previewView.surfaceProvider }          analysis.setAnalyzer(analysisExecutor) { proxy ->             val now = System.currentTimeMillis()@@ -144,7 +239,6 @@ private fun CameraContent(viewModel: TranslateViewModel, onBack: () -> Unit) {                 proxy.close()                 return@setAnalyzer             }-            lastMs.store(now)             inFlight.store(true)             val bmp = try {                 proxy.toBitmap()@@ -156,69 +250,100 @@ private fun CameraContent(viewModel: TranslateViewModel, onBack: () -> Unit) {             proxy.close()             if (bmp == null) {                 inFlight.store(false)+                lastMs.store(System.currentTimeMillis())                 return@setAnalyzer             }-            // Heavy work off the analysis thread; OCR/translate suspend internally-            // onto Dispatchers.Default. State writes happen back on the main thread.+            // Only the state writes belong on the main thread; the rotate is a+            // full-frame copy and OCR suspends onto Dispatchers.Default itself.             scope.launch {                 try {-                    val upright = rotateBitmap(bmp, rotation)-                    val result = viewModel.ocr.recognizeDetailed(upright)-                    val boxes = result.boxes.map { box ->-                        val translation =-                            if (availableState.value) viewModel.translate(box.text) else null-                        OverlayBox(-                            left = box.left,-                            top = box.top,-                            right = box.right,-                            bottom = box.bottom,-                            text = translation ?: box.text,-                            translated = translation != null,-                        )+                    val upright = withContext(Dispatchers.Default) {+                        rotateBitmap(bmp, rotation).also { if (it !== bmp) bmp.recycle() }                     }+                    val result = viewModel.ocr.recognizeDetailed(upright)                     frameW = upright.width                     frameH = upright.height-                    overlays = boxes+                    overlays = result.boxes.map {+                        OverlayBox(it.left, it.top, it.right, it.bottom, it.text)+                    }                     frozenFrame = upright+                } catch (t: Throwable) {+                    Log.e(TAG, "Frame analysis failed", t)                 } finally {+                    // Measure the gap from the *end* of the pass, so a slow OCR run+                    // doesn't immediately trigger the next one.+                    lastMs.store(System.currentTimeMillis())                     inFlight.store(false)                 }             }         }          try {-            provider.unbindAll()-            camera = provider.bindToLifecycle(+            cameraProvider.unbindAll()+            camera = cameraProvider.bindToLifecycle(                 lifecycleOwner,                 CameraSelector.DEFAULT_BACK_CAMERA,                 preview,                 analysis,             )+            // Safe (and required) only after binding — setting it on the builder would+            // change the frame [ANALYSIS_SIZE] is resolved in.+            analysis.targetRotation = displayRotation()         } catch (t: Throwable) {             Log.e(TAG, "Camera bind failed", t)         }     } +    // One background translator, decoupled from the OCR loop. SMaLL-100 takes on the+    // order of a second per line, so translating every line of every frame inline (as+    // this screen used to) meant the overlay updated once every several seconds, always+    // against a frame the camera had long since moved off. Instead we memo per source+    // line: repeat lines are free, and OCR keeps redrawing boxes at full rate.+    LaunchedEffect(targetLang, translationAvailable) {+        translations = emptyMap()+        if (!translationAvailable) return@LaunchedEffect+        while (isActive) {+            val next = overlays.firstOrNull { it.text !in translations }+            if (next == null) {+                delay(TRANSLATE_IDLE_POLL_MS)+                continue+            }+            // Memo failures as the source text so a line that can't be translated+            // isn't retried on every frame forever.+            val translated = viewModel.translate(next.text) ?: next.text+            translations = (translations + (next.text to translated)).let { updated ->+                if (updated.size <= TRANSLATION_CACHE_MAX) {+                    updated+                } else {+                    updated.entries.drop(updated.size - TRANSLATION_CACHE_MAX)+                        .associate { it.key to it.value }+                }+            }+        }+    }+     Box(modifier = Modifier.fillMaxSize().background(Color.Black)) {         BoxWithConstraints(modifier = Modifier.fillMaxSize()) {             val viewW = constraints.maxWidth.toFloat()             val viewH = constraints.maxHeight.toFloat() -            // Live preview, or the frozen last frame while paused.+            // The preview stays composed even while paused — swapping it out tears the+            // camera surface down and back up, which flashes black on every toggle.+            AndroidView(factory = { previewView }, modifier = Modifier.fillMaxSize())+             val frozen = frozenFrame-            if (paused && frozen != null) {+            if (paused && frozen != null && !frozen.isRecycled) {                 Image(                     bitmap = frozen.asImageBitmap(),                     contentDescription = null,                     modifier = Modifier.fillMaxSize(),                     contentScale = ContentScale.Crop,                 )-            } else {-                AndroidView(factory = { previewView }, modifier = Modifier.fillMaxSize())             } -            // Map analysed-bitmap coords -> view coords assuming PreviewView's default-            // FILL_CENTER (center-crop): scale by the larger ratio, then centre.+            // Map analysed-bitmap coords -> view coords. PreviewView is FILL_CENTER+            // (centre-crop) and both streams are 4:3, so: scale by the larger ratio,+            // then centre.             if (frameW > 0 && frameH > 0) {                 val scale = max(viewW / frameW, viewH / frameH)                 val dx = (viewW - frameW * scale) / 2f@@ -229,7 +354,6 @@ private fun CameraContent(viewModel: TranslateViewModel, onBack: () -> Unit) {                     val w = (ob.right - ob.left) * scale                     val h = (ob.bottom - ob.top) * scale                     if (w <= 0f || h <= 0f) return@forEach-                    val fontSp = (with(density) { h.toDp().value } * 0.5f).coerceIn(9f, 22f)                     Box(                         modifier = Modifier                             .offset { IntOffset(l.roundToInt(), t.roundToInt()) }@@ -239,15 +363,22 @@ private fun CameraContent(viewModel: TranslateViewModel, onBack: () -> Unit) {                             )                             .clip(RoundedCornerShape(4.dp))                             .background(Color(0xF2000000))-                            .padding(horizontal = 3.dp),+                            .padding(horizontal = 3.dp, vertical = 1.dp),                         contentAlignment = Alignment.Center,                     ) {-                        Text(-                            text = ob.text,-                            color = Color.White,-                            fontSize = fontSp.sp,-                            maxLines = 1,+                        // A translation is usually longer than the source line it has to+                        // sit on top of, so a fixed font size + maxLines=1 ellipsised+                        // nearly every label down to "…". Shrink to fit instead.+                        BasicText(+                            text = translations[ob.text] ?: ob.text,+                            style = TextStyle(color = Color.White, textAlign = TextAlign.Center),+                            maxLines = 2,                             overflow = TextOverflow.Ellipsis,+                            autoSize = TextAutoSize.StepBased(+                                minFontSize = 6.sp,+                                maxFontSize = 24.sp,+                                stepSize = 0.5.sp,+                            ),                         )                     }                 }
translate/src/main/res/values/strings.xml
diff --git a/translate/src/main/res/values/strings.xml b/translate/src/main/res/values/strings.xmlindex 4d3e1220e1..b8ca613c29 100644--- a/translate/src/main/res/values/strings.xml+++ b/translate/src/main/res/values/strings.xml@@ -7,4 +7,5 @@     <string name="speak">Speak</string>     <string name="translation">Translation</string>     <string name="translation_model_not_installed_showing">Translation model not installed — showing detected text only</string>+    <string name="grant_camera_access">Grant camera access to translate what you see</string> </resources>
travel/src/androidTest/java/com/vayunmathur/travel/MetadataScreenshots.kt
diff --git a/travel/src/androidTest/java/com/vayunmathur/travel/MetadataScreenshots.kt b/travel/src/androidTest/java/com/vayunmathur/travel/MetadataScreenshots.ktnew file mode 100644index 0000000000..8bf41a7e04--- /dev/null+++ b/travel/src/androidTest/java/com/vayunmathur/travel/MetadataScreenshots.kt@@ -0,0 +1,55 @@+package com.vayunmathur.travel++import android.graphics.Bitmap+import androidx.compose.ui.graphics.asAndroidBitmap+import androidx.compose.ui.test.captureToImage+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onRoot+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import java.io.File++/**+ * Screenshot generator driven by `:travel:metadata`.+ * Captures home search form. No DB seeding to keep it compile-safe;+ * a richer version could seed RecentSearch via TravelDatabase.+ */+@RunWith(AndroidJUnit4::class)+class MetadataScreenshots {++    @get:Rule+    val composeRule = createAndroidComposeRule<MainActivity>()++    private val ctx = InstrumentationRegistry.getInstrumentation().targetContext++    private val outDir: File by lazy {+        File(ctx.getExternalFilesDir(null), "metadata_screenshots").apply {+            deleteRecursively()+            mkdirs()+        }+    }++    private fun snap(index: Int) {+        composeRule.waitForIdle()+        Thread.sleep(600)+        val image = composeRule.onRoot().captureToImage()+        File(outDir, "$index.png").outputStream().use { out ->+            image.asAndroidBitmap().compress(Bitmap.CompressFormat.PNG, 100, out)+        }+    }++    @Test+    fun generateStoreScreenshots() {+        composeRule.waitUntil(timeoutMillis = 15_000) {+            composeRule.onAllNodesWithText("Travel", substring = true).fetchSemanticsNodes().isNotEmpty() ||+                composeRule.onAllNodesWithText("Search", substring = true).fetchSemanticsNodes().isNotEmpty()+        }+        Thread.sleep(1200)+        snap(1)+        snap(2)+    }+}
vpn/src/androidTest/java/com/vayunmathur/vpn/MetadataScreenshots.kt
diff --git a/vpn/src/androidTest/java/com/vayunmathur/vpn/MetadataScreenshots.kt b/vpn/src/androidTest/java/com/vayunmathur/vpn/MetadataScreenshots.ktnew file mode 100644index 0000000000..81ead9a902--- /dev/null+++ b/vpn/src/androidTest/java/com/vayunmathur/vpn/MetadataScreenshots.kt@@ -0,0 +1,54 @@+package com.vayunmathur.vpn++import android.graphics.Bitmap+import androidx.compose.ui.graphics.asAndroidBitmap+import androidx.compose.ui.test.captureToImage+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onRoot+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import java.io.File++/**+ * Screenshot generator driven by `:vpn:metadata`.+ * Captures config list / empty state.+ */+@RunWith(AndroidJUnit4::class)+class MetadataScreenshots {++    @get:Rule+    val composeRule = createAndroidComposeRule<MainActivity>()++    private val ctx = InstrumentationRegistry.getInstrumentation().targetContext++    private val outDir: File by lazy {+        File(ctx.getExternalFilesDir(null), "metadata_screenshots").apply {+            deleteRecursively()+            mkdirs()+        }+    }++    private fun snap(index: Int) {+        composeRule.waitForIdle()+        Thread.sleep(600)+        val image = composeRule.onRoot().captureToImage()+        File(outDir, "$index.png").outputStream().use { out ->+            image.asAndroidBitmap().compress(Bitmap.CompressFormat.PNG, 100, out)+        }+    }++    @Test+    fun generateStoreScreenshots() {+        composeRule.waitUntil(timeoutMillis = 15_000) {+            composeRule.onAllNodesWithText("VPN", substring = true).fetchSemanticsNodes().isNotEmpty() ||+                composeRule.onAllNodesWithText("Config", substring = true).fetchSemanticsNodes().isNotEmpty()+        }+        Thread.sleep(1000)+        snap(1)+        snap(2)+    }+}
web/src/androidTest/java/com/vayunmathur/web/MetadataScreenshots.kt
diff --git a/web/src/androidTest/java/com/vayunmathur/web/MetadataScreenshots.kt b/web/src/androidTest/java/com/vayunmathur/web/MetadataScreenshots.ktnew file mode 100644index 0000000000..f0be6b8298--- /dev/null+++ b/web/src/androidTest/java/com/vayunmathur/web/MetadataScreenshots.kt@@ -0,0 +1,54 @@+package com.vayunmathur.web++import android.graphics.Bitmap+import androidx.compose.ui.graphics.asAndroidBitmap+import androidx.compose.ui.test.captureToImage+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onRoot+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import java.io.File++/**+ * Screenshot generator driven by `:web:metadata`.+ * No seeding — captures browser UI states (new tab, bookmarks prompt).+ */+@RunWith(AndroidJUnit4::class)+class MetadataScreenshots {++    @get:Rule+    val composeRule = createAndroidComposeRule<MainActivity>()++    private val ctx = InstrumentationRegistry.getInstrumentation().targetContext++    private val outDir: File by lazy {+        File(ctx.getExternalFilesDir(null), "metadata_screenshots").apply {+            deleteRecursively()+            mkdirs()+        }+    }++    private fun snap(index: Int) {+        composeRule.waitForIdle()+        Thread.sleep(600)+        val image = composeRule.onRoot().captureToImage()+        File(outDir, "$index.png").outputStream().use { out ->+            image.asAndroidBitmap().compress(Bitmap.CompressFormat.PNG, 100, out)+        }+    }++    @Test+    fun generateStoreScreenshots() {+        composeRule.waitUntil(timeoutMillis = 15_000) {+            composeRule.onAllNodesWithText("Web", substring = true).fetchSemanticsNodes().isNotEmpty() ||+                composeRule.onAllNodesWithText("Search", substring = true).fetchSemanticsNodes().isNotEmpty()+        }+        Thread.sleep(1200)+        snap(1)+        snap(2)+    }+}