Modern Apps git

← Modern-Apps.git

various fixes

Commit
b03fdaa3a316733279d9eab8ed56723db8bfd24b
Author
Vayun Mathur <[email protected]>
When
2026-08-01 04:38 UTC (4 months ago)
Parents
58adcb2

Diff

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 7048342b07..f751f8b424 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/ui/GraphPage.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/ui/GraphPage.kt@@ -4,8 +4,8 @@ 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.gestures.detectTapGestures import androidx.compose.foundation.gestures.detectTransformGestures-import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column@@ -17,18 +17,13 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items-import androidx.compose.foundation.rememberScrollState 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.remember-import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.geometry.Offset-import androidx.compose.ui.graphics.Color+import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.input.pointer.pointerInput@@ -38,12 +33,13 @@ import androidx.compose.ui.text.drawText import androidx.compose.ui.text.rememberTextMeasurer import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp-import com.vayunmathur.calculator.util.AnalysisKind import com.vayunmathur.calculator.util.AngleMode 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.GraphPoint import com.vayunmathur.calculator.util.formatResult-import com.vayunmathur.library.ui.AlertDialog import com.vayunmathur.library.ui.AssistChip import com.vayunmathur.library.ui.FilterChip import com.vayunmathur.library.ui.HorizontalDivider@@ -56,20 +52,15 @@ import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.OutlinedTextField import com.vayunmathur.library.ui.Scaffold import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.TextButton import com.vayunmathur.library.ui.TopAppBar-import kotlin.math.PI import kotlin.math.abs import kotlin.math.ceil-import kotlin.math.cos import kotlin.math.floor import kotlin.math.log10 import kotlin.math.pow-import kotlin.math.sin  @Composable fun GraphPage(viewModel: CalculatorViewModel) {-    var showResults by remember { mutableStateOf(false) }     Scaffold(         topBar = {             TopAppBar(@@ -85,48 +76,15 @@ fun GraphPage(viewModel: CalculatorViewModel) {         },     ) { padding ->         Column(Modifier.fillMaxSize().padding(padding)) {-            AnalysisBar(viewModel) { showResults = true }             GraphCanvas(viewModel, Modifier.fillMaxWidth().weight(1f))             HorizontalDivider()             FunctionEditors(viewModel)         }     }-    if (showResults) {-        AlertDialog(-            onDismissRequest = { showResults = false },-            title = { Text(stringResource(R.string.analysis)) },-            text = {-                LazyColumn(Modifier.heightIn(max = 320.dp)) {-                    items(viewModel.analysisSummary) { line -> Text(line, modifier = Modifier.padding(vertical = 3.dp)) }-                }-            },-            confirmButton = { TextButton({ showResults = false }) { Text(stringResource(R.string.done)) } },-            dismissButton = { TextButton({ viewModel.clearAnalysis(); showResults = false }) { Text(stringResource(R.string.clear_markers)) } },-        )-    } } -/** Horizontally-scrolling row of numeric-analysis actions over the visible window. */-@Composable-private fun AnalysisBar(viewModel: CalculatorViewModel, onResults: () -> Unit) {-    Row(-        Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(horizontal = 8.dp, vertical = 4.dp),-        horizontalArrangement = Arrangement.spacedBy(8.dp),-        verticalAlignment = Alignment.CenterVertically,-    ) {-        AnalysisKind.entries.forEach { kind ->-            val short = when (kind) {-                AnalysisKind.ROOTS -> "Roots"-                AnalysisKind.MINIMA -> "Min"-                AnalysisKind.MAXIMA -> "Max"-                AnalysisKind.INTERSECTIONS -> "Intersect"-                AnalysisKind.Y_INTERCEPT -> "y-int"-            }-            AssistChip(onClick = { viewModel.runAnalysis(kind); onResults() }, label = { Text(short) })-        }-        AssistChip(onClick = { viewModel.clearAnalysis() }, label = { Text(stringResource(R.string.clear)) })-    }-}+/** How close a touch has to land, in dp, for a notable point to be revealed. */+private val TouchSlop = 28.dp  @Composable private fun GraphCanvas(viewModel: CalculatorViewModel, modifier: Modifier) {@@ -134,9 +92,22 @@ private fun GraphCanvas(viewModel: CalculatorViewModel, modifier: Modifier) {     val gridColor = MaterialTheme.colorScheme.outlineVariant     val labelColor = MaterialTheme.colorScheme.onSurfaceVariant     val surface = MaterialTheme.colorScheme.surface+    // Marker text uses the theme's foreground colour, not the curve's, so it stays legible+    // against the background whatever colour the curve happens to be.+    val markerTextColor = MaterialTheme.colorScheme.onSurface     val textMeasurer = rememberTextMeasurer() -    // Compile each function once per edit; null means it doesn't parse yet.+    // Colour lookup for markers, and the localised kind names, resolved outside the draw scope.+    val colorOf = viewModel.functions.associate { it.id to it.color }+    val kindLabels = mapOf(+        FeatureKind.ROOT to stringResource(R.string.feature_root),+        FeatureKind.Y_INTERCEPT to stringResource(R.string.feature_y_intercept),+        FeatureKind.MINIMUM to stringResource(R.string.feature_minimum),+        FeatureKind.MAXIMUM to stringResource(R.string.feature_maximum),+        FeatureKind.INTERSECTION to stringResource(R.string.feature_intersection),+    )++    // Compile each function once per edit, not once per frame; null means it doesn't parse yet.     val compiled = viewModel.functions.map { fn ->         fn to if (fn.enabled && fn.text.isNotBlank()) runCatching { Expression.parse(fn.text) }.getOrNull() else null     }@@ -148,6 +119,13 @@ private fun GraphCanvas(viewModel: CalculatorViewModel, modifier: Modifier) {                 viewModel.viewWidthPx = it.width.toFloat()                 viewModel.viewHeightPx = it.height.toFloat()             }+            .pointerInput(Unit) {+                detectTapGestures { offset ->+                    val gx = viewModel.centerX + (offset.x - size.width / 2) / viewModel.scale+                    val gy = viewModel.centerY + (size.height / 2 - offset.y) / viewModel.scale+                    viewModel.tapGraph(GraphPoint(gx, gy), TouchSlop.toPx() / viewModel.scale)+                }+            }             .pointerInput(Unit) {                 detectTransformGestures { centroid, pan, zoom, _ ->                     val oldScale = viewModel.scale@@ -203,52 +181,44 @@ private fun GraphCanvas(viewModel: CalculatorViewModel, modifier: Modifier) {         drawLine(axisColor, Offset(0f, py(0.0)), Offset(w, py(0.0)), strokeWidth = 2.5f)          // ---- Curves -----        val jumpLimit = h * 4+        // Drawn from the same sampler the analysis uses, so markers land on the drawn line.         for ((fn, expr) in compiled) {             if (expr == null) continue+            val curve = GraphAnalysis.sample(+                fn.id, expr, fn.polar, viewModel.angleMode, minX, maxX, minY, maxY, w.toInt(),+            )             val path = Path()-            var penDown = false-            var prevSy = 0f-            if (fn.polar) {-                // r = f(θ): sample θ over [0, 2π] in radians (polar is inherently radian).-                val samples = 2000-                var k = 0-                while (k <= samples) {-                    val theta = 2 * PI * k / samples-                    val r = runCatching { expr.eval(theta, AngleMode.RADIANS) }.getOrNull()-                    if (r == null || r.isNaN() || r.isInfinite()) { penDown = false } else {-                        val sx = px(r * cos(theta)); val sy = py(r * sin(theta))-                        if (!penDown) { path.moveTo(sx, sy); penDown = true } else path.lineTo(sx, sy)-                    }-                    k++-                }-            } else {-                // y = f(x): one sample per horizontal pixel; break at undefined points / asymptotes.-                var pxCol = 0-                while (pxCol <= w.toInt()) {-                    val graphX = cx + (pxCol - w / 2) / scale-                    val yVal = runCatching { expr.eval(graphX, viewModel.angleMode) }.getOrNull()-                    if (yVal == null || yVal.isNaN() || yVal.isInfinite()) { penDown = false } else {-                        val sy = py(yVal)-                        if (!penDown) { path.moveTo(pxCol.toFloat(), sy); penDown = true }-                        else if (abs(sy - prevSy) > jumpLimit) path.moveTo(pxCol.toFloat(), sy)-                        else path.lineTo(pxCol.toFloat(), sy)-                        prevSy = sy-                    }-                    pxCol+++            for (run in curve.runs) {+                run.forEachIndexed { i, p ->+                    val sx = px(p.x)+                    val sy = py(p.y)+                    if (i == 0) path.moveTo(sx, sy) else path.lineTo(sx, sy)                 }             }             drawPath(path, fn.color, style = Stroke(width = 3f))         } -        // ---- Analysis markers -----        for (p in viewModel.analysisPoints) {-            val cxp = px(p.x); val cyp = py(p.y)-            if (cxp < -20 || cxp > w + 20 || cyp < -20 || cyp > h + 20) continue-            drawCircle(surface, radius = 7f, center = Offset(cxp, cyp))-            drawCircle(p.color, radius = 7f, center = Offset(cxp, cyp), style = Stroke(width = 3f))-            val layout = textMeasurer.measure(p.label, TextStyle(color = p.color, fontSize = 11.sp))-            drawText(layout, topLeft = Offset((cxp + 8f).coerceAtMost(w - layout.size.width), cyp - layout.size.height - 4f))+        // ---- Markers the user has revealed ----+        for (m in viewModel.markers) {+            val mx = px(m.point.x)+            val my = py(m.point.y)+            if (mx < -20 || mx > w + 20 || my < -20 || my > h + 20) continue+            // An intersection belongs to two curves, so it takes the neutral theme colour.+            val ringColor = m.curveIds.singleOrNull()?.let { colorOf[it] } ?: markerTextColor+            drawCircle(surface, radius = 7f, center = Offset(mx, my))+            drawCircle(ringColor, radius = 7f, center = Offset(mx, my), style = Stroke(width = 3f))++            val text = "${kindLabels[m.kind]} (${formatResult(m.point.x)}, ${formatResult(m.point.y)})"+            val layout = textMeasurer.measure(text, TextStyle(color = markerTextColor, fontSize = 11.sp))+            val tx = (mx + 10f).coerceIn(0f, (w - layout.size.width).coerceAtLeast(0f))+            val ty = (my - layout.size.height - 6f).coerceIn(0f, (h - layout.size.height).coerceAtLeast(0f))+            // A surface-coloured plate keeps the label readable where it overlaps a curve.+            drawRect(+                surface.copy(alpha = 0.85f),+                topLeft = Offset(tx - 3f, ty - 2f),+                size = Size(layout.size.width + 6f, layout.size.height + 4f),+            )+            drawText(layout, topLeft = Offset(tx, ty))         }     } }
calculator/src/main/java/com/vayunmathur/calculator/util/CalculatorViewModel.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/util/CalculatorViewModel.kt b/calculator/src/main/java/com/vayunmathur/calculator/util/CalculatorViewModel.ktindex 46104bdc3b..69634ae789 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/util/CalculatorViewModel.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/util/CalculatorViewModel.kt@@ -6,6 +6,7 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.graphics.Color import androidx.lifecycle.ViewModel+import kotlin.math.hypot  /** One plotted curve on the graph screen — Cartesian `y = f(x)` or polar `r = f(θ)`. */ data class GraphFunction(@@ -16,23 +17,17 @@ data class GraphFunction(     val polar: Boolean = false, ) -/** A point found by graph analysis (root, extremum, intersection…), drawn + listed. */-data class AnalysisPoint(-    val x: Double,-    val y: Double,-    val label: String,-    val color: Color,+/**+ * A notable point the user revealed by touching near it. Held as the feature itself rather+ * than as pre-rendered text so the UI can colour and localise the label.+ */+data class GraphMarker(+    val point: GraphPoint,+    val kind: FeatureKind,+    /** The curve it belongs to, or the two curves that cross there. */+    val curveIds: List<Long>, ) -/** The kinds of numeric analysis the graph screen can run over the visible window. */-enum class AnalysisKind(val title: String) {-    ROOTS("Roots (x-intercepts)"),-    MINIMA("Minima"),-    MAXIMA("Maxima"),-    INTERSECTIONS("Intersections"),-    Y_INTERCEPT("y-intercepts"),-}- /**  * Holds all calculator state at the Activity scope so it survives switching between the  * Calculator and Graph tabs (which reset the nav back stack).@@ -131,14 +126,25 @@ class CalculatorViewModel : ViewModel() {         functions.add(GraphFunction(id = nextId++, text = "", color = color))     } -    fun updateFunction(id: Long, text: String) = mutate(id) { it.copy(text = text) }-    fun toggleFunction(id: Long) = mutate(id) { it.copy(enabled = !it.enabled) }-    fun togglePolar(id: Long) = mutate(id) { it.copy(polar = !it.polar) }+    fun updateFunction(id: Long, text: String) {+        dropMarkersFor(id)+        mutate(id) { it.copy(text = text) }+    }++    fun toggleFunction(id: Long) {+        dropMarkersFor(id)+        mutate(id) { it.copy(enabled = !it.enabled) }+    }++    fun togglePolar(id: Long) {+        dropMarkersFor(id)+        mutate(id) { it.copy(polar = !it.polar) }+    }      fun removeFunction(id: Long) {         functions.removeAll { it.id == id }         if (functions.isEmpty()) addFunction()-        clearAnalysis()+        dropMarkersFor(id)     }      private inline fun mutate(id: Long, transform: (GraphFunction) -> GraphFunction) {@@ -153,62 +159,43 @@ class CalculatorViewModel : ViewModel() {     var viewWidthPx by mutableStateOf(0f)     var viewHeightPx by mutableStateOf(0f) -    val analysisPoints = mutableStateListOf<AnalysisPoint>()-    var analysisSummary by mutableStateOf<List<String>>(emptyList())-        private set+    /** Notable points the user has revealed by touching near them. */+    val markers = mutableStateListOf<GraphMarker>() -    fun clearAnalysis() {-        analysisPoints.clear()-        analysisSummary = emptyList()-    }+    private fun dropMarkersFor(id: Long) = markers.removeAll { id in it.curveIds }      /**-     * Run [kind] over the currently visible x-range for the enabled Cartesian functions-     * (polar curves are skipped — the analyses are Cartesian). Populates [analysisPoints]-     * (drawn on the graph) and [analysisSummary] (shown in a dialog).+     * Samples every visible curve over the current viewport. Drawing and analysis share this+     * so a marker always lands exactly on the line that was drawn.      */-    fun runAnalysis(kind: AnalysisKind) {-        analysisPoints.clear()-        if (viewWidthPx <= 0f) { analysisSummary = listOf("Open the graph first."); return }-        val xMin = centerX - (viewWidthPx / 2) / scale-        val xMax = centerX + (viewWidthPx / 2) / scale--        val cartesian = functions.filter { it.enabled && !it.polar && it.text.isNotBlank() }-            .mapNotNull { fn -> runCatching { fn to Expression.parse(fn.text) }.getOrNull() }--        val summary = mutableListOf<String>()-        when (kind) {-            AnalysisKind.INTERSECTIONS -> {-                for (i in cartesian.indices) for (j in i + 1 until cartesian.size) {-                    val (fa, ea) = cartesian[i]-                    val (_, eb) = cartesian[j]-                    for (x in GraphAnalysis.intersections(ea, eb, angleMode, xMin, xMax)) {-                        val y = ea.eval(x, angleMode)-                        analysisPoints.add(AnalysisPoint(x, y, "(${fmt(x)}, ${fmt(y)})", fa.color))-                        summary.add("Intersection: (${fmt(x)}, ${fmt(y)})")-                    }-                }-            }-            else -> for ((fn, expr) in cartesian) {-                val xs = when (kind) {-                    AnalysisKind.ROOTS -> GraphAnalysis.roots(expr, angleMode, xMin, xMax)-                    AnalysisKind.MINIMA -> GraphAnalysis.extrema(expr, angleMode, xMin, xMax, wantMax = false)-                    AnalysisKind.MAXIMA -> GraphAnalysis.extrema(expr, angleMode, xMin, xMax, wantMax = true)-                    AnalysisKind.Y_INTERCEPT -> if (0.0 in xMin..xMax) listOf(0.0) else emptyList()-                    AnalysisKind.INTERSECTIONS -> emptyList()-                }-                for (x in xs) {-                    val y = expr.eval(x, angleMode)-                    if (y.isNaN() || y.isInfinite()) continue-                    analysisPoints.add(AnalysisPoint(x, y, "(${fmt(x)}, ${fmt(y)})", fn.color))-                    summary.add("${kind.title.removeSuffix("s")}: (${fmt(x)}, ${fmt(y)})")-                }-            }+    fun sampleCurves(widthPx: Float, heightPx: Float): List<SampledCurve> {+        if (widthPx <= 0f || heightPx <= 0f) return emptyList()+        val xMin = centerX - (widthPx / 2) / scale+        val xMax = centerX + (widthPx / 2) / scale+        val yMin = centerY - (heightPx / 2) / scale+        val yMax = centerY + (heightPx / 2) / scale+        return functions.filter { it.enabled && it.text.isNotBlank() }.mapNotNull { fn ->+            val expr = runCatching { Expression.parse(fn.text) }.getOrNull() ?: return@mapNotNull null+            GraphAnalysis.sample(fn.id, expr, fn.polar, angleMode, xMin, xMax, yMin, yMax, widthPx.toInt())         }-        analysisSummary = if (summary.isEmpty()) listOf("None found in the visible window.") else summary     } -    private fun fmt(v: Double) = formatResult(v)+    /**+     * Handles a tap on the graph, [radius] being the touch slop in graph units. Touching a+     * marker removes it; touching anywhere else reveals the nearest notable point in range,+     * across every curve on screen — Cartesian, polar, and crossings between the two.+     */+    fun tapGraph(at: GraphPoint, radius: Double) {+        val hit = markers.minByOrNull { hypot(it.point.x - at.x, it.point.y - at.y) }+        if (hit != null && hypot(hit.point.x - at.x, hit.point.y - at.y) <= radius) {+            markers.remove(hit)+            return+        }+        val feature = GraphAnalysis+            .featuresNear(sampleCurves(viewWidthPx, viewHeightPx), at, radius, angleMode)+            .firstOrNull() ?: return+        markers.add(GraphMarker(feature.point, feature.kind, feature.curveIds))+    }      companion object {         /** Distinct, colour-blind-friendly curve colours, reused cyclically. */
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 7599c99d36..6d40de06a0 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/util/GraphAnalysis.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/util/GraphAnalysis.kt@@ -1,132 +1,375 @@ package com.vayunmathur.calculator.util +import kotlin.math.PI import kotlin.math.abs+import kotlin.math.cos+import kotlin.math.hypot+import kotlin.math.sin++/** A point in graph (not screen) coordinates. */+data class GraphPoint(val x: Double, val y: Double)++/** The kinds of notable point the grapher can find. */+enum class FeatureKind {+    ROOT,+    Y_INTERCEPT,+    MINIMUM,+    MAXIMUM,+    INTERSECTION,+}  /**- * Numeric analysis of graphed functions over the visible x-window: roots (x-intercepts),- * local minima/maxima, and intersections between two curves. All methods sample the range- * densely, bracket features by sign/slope changes, then refine — good enough for an- * on-device grapher without a symbolic engine.+ * A notable point on — or between — curves. [curveIds] holds the one curve the feature+ * belongs to, or the two curves that cross at an [FeatureKind.INTERSECTION].+ */+data class GraphFeature(+    val point: GraphPoint,+    val kind: FeatureKind,+    val curveIds: List<Long>,+)++/**+ * A curve reduced to connected polyline runs in graph space. A new run begins wherever the+ * curve is undefined or jumps (an asymptote), so runs never bridge a discontinuity — which+ * is what stops `tan(x)` from appearing to cross every horizontal line at its asymptotes.+ */+class SampledCurve(+    val id: Long,+    val expr: Expression,+    val polar: Boolean,+    val runs: List<List<GraphPoint>>,+)++/**+ * Numeric analysis of the graphed curves: roots, axis intercepts, local extrema, and+ * intersections. Everything is derived from the same polyline sampling used to draw the+ * curves, so a marker always sits on the line the user can see, and so Cartesian and polar+ * curves — including intersections *between* the two kinds — are handled uniformly.+ *+ * Exact values are recovered afterwards by bisection / ternary search wherever the curve is+ * Cartesian; polar features keep their (sub-pixel) polyline estimate.  */ object GraphAnalysis { -    private const val SAMPLES = 1000-    private const val REFINE_ITERS = 60--    private fun evalOrNaN(e: Expression, x: Double, angle: AngleMode): Double =-        try { e.eval(x, angle) } catch (ex: ExpressionError) { Double.NaN }--    /** x-values where `f(x) = 0` in `[xMin, xMax]`, via sign-change bracketing + bisection. */-    fun roots(e: Expression, angle: AngleMode, xMin: Double, xMax: Double): List<Double> {-        val out = ArrayList<Double>()-        val step = (xMax - xMin) / SAMPLES-        var prevX = xMin-        var prevY = evalOrNaN(e, prevX, angle)-        var i = 1-        while (i <= SAMPLES) {-            val x = xMin + i * step-            val y = evalOrNaN(e, x, angle)-            if (prevY.isFinite() && y.isFinite()) {-                if (prevY == 0.0) addUnique(out, prevX)-                // A sign change that isn't a discontinuity jump brackets a root.-                else if (prevY * y < 0 && abs(y - prevY) < 1e6) {-                    addUnique(out, bisect(e, angle, prevX, x))+    /** θ samples for a polar curve over [0, 2π]. */+    private const val POLAR_SAMPLES = 2000+    private const val REFINE_ITERS = 80++    private fun evalOrNaN(e: Expression, v: Double, angle: AngleMode): Double =+        try { e.eval(v, angle) } catch (ex: ExpressionError) { Double.NaN }++    // ---- Sampling ----++    /**+     * 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).+     */+    fun sample(+        id: Long,+        expr: Expression,+        polar: Boolean,+        angle: AngleMode,+        xMin: Double,+        xMax: Double,+        yMin: Double,+        yMax: Double,+        columns: Int,+    ): SampledCurve {+        val runs = ArrayList<List<GraphPoint>>()+        var current = ArrayList<GraphPoint>()+        // Treat a vertical leap of more than a few screens as a discontinuity, not a segment.+        val jumpLimit = (yMax - yMin) * 4++        fun breakRun() {+            if (current.size > 1) runs.add(current)+            current = ArrayList()+        }++        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 {+                    breakRun()+                }+                k+++            }+        } else {+            val steps = columns.coerceAtLeast(2)+            var i = 0+            var prevY = Double.NaN+            while (i <= steps) {+                val x = xMin + (xMax - xMin) * i / steps+                val y = evalOrNaN(expr, x, angle)+                if (y.isFinite()) {+                    if (prevY.isFinite() && abs(y - prevY) > jumpLimit) breakRun()+                    current.add(GraphPoint(x, y))+                } else {+                    breakRun()                 }+                prevY = y+                i++             }-            prevX = x; prevY = y; i++         }-        return out+        breakRun()+        return SampledCurve(id, expr, polar, runs)+    }++    // ---- Feature discovery ----++    /**+     * Every notable point within [radius] graph units of [at], nearest first.+     *+     * Only geometry near the tap is examined, so this stays cheap enough to run on each+     * touch no matter how many curves are on screen.+     */+    fun featuresNear(+        curves: List<SampledCurve>,+        at: GraphPoint,+        radius: Double,+        angle: AngleMode,+    ): List<GraphFeature> {+        val found = ArrayList<GraphFeature>()+        for (curve in curves) singleCurveFeatures(curve, at, radius, angle, found)+        for (i in curves.indices) {+            for (j in i + 1 until curves.size) {+                intersectionFeatures(curves[i], curves[j], at, radius, angle, found)+            }+        }+        return found+            .filter { distance(it.point, at) <= radius }+            .sortedBy { distance(it.point, at) }+            .let(::dedupe)     } -    /** Local minima (or maxima if [wantMax]) in `[xMin, xMax]`, via slope-sign changes. */-    fun extrema(e: Expression, angle: AngleMode, xMin: Double, xMax: Double, wantMax: Boolean): List<Double> {-        val out = ArrayList<Double>()-        val step = (xMax - xMin) / SAMPLES-        var a = xMin-        var fa = evalOrNaN(e, a, angle)-        var b = xMin + step-        var fb = evalOrNaN(e, b, angle)-        var i = 2-        while (i <= SAMPLES) {-            val c = xMin + i * step-            val fc = evalOrNaN(e, c, angle)-            if (fa.isFinite() && fb.isFinite() && fc.isFinite()) {-                val isMax = fb > fa && fb > fc-                val isMin = fb < fa && fb < fc-                if ((wantMax && isMax) || (!wantMax && isMin)) {-                    addUnique(out, ternary(e, angle, a, c, wantMax))+    /** Roots, y-intercepts and local extrema of a single curve. */+    private fun singleCurveFeatures(+        curve: SampledCurve,+        at: GraphPoint,+        radius: Double,+        angle: AngleMode,+        out: MutableList<GraphFeature>,+    ) {+        for (run in curve.runs) {+            for (i in 0 until run.size - 1) {+                val a = run[i]+                val b = run[i + 1]+                if (segmentDistance(at, a, b) > radius) continue++                // Axis crossings. `straddles` accepts an endpoint sitting exactly on the axis,+                // which a strict sign-change test misses whenever a sample lands on it.+                if (straddles(a.y, b.y)) {+                    val x = if (curve.polar) interpolateZero(a.y, b.y, a.x, b.x)+                    else refineZero({ evalOrNaN(curve.expr, it, angle) }, a.x, b.x)+                    out.add(GraphFeature(GraphPoint(x, 0.0), FeatureKind.ROOT, listOf(curve.id)))+                }+                if (straddles(a.x, b.x)) {+                    val y = if (curve.polar) interpolateZero(a.x, b.x, a.y, b.y)+                    else evalOrNaN(curve.expr, 0.0, angle)+                    if (y.isFinite()) {+                        out.add(GraphFeature(GraphPoint(0.0, y), FeatureKind.Y_INTERCEPT, listOf(curve.id)))+                    }                 }             }-            a = b; fa = fb; b = c; fb = fc; i+++            // Local extrema in y — geometrically the peaks and troughs of the drawn curve,+            // which is meaningful for polar curves too.+            for (i in 1 until run.size - 1) {+                val p = run[i]+                if (distance(p, at) > radius) continue+                val isMax = p.y > run[i - 1].y && p.y > run[i + 1].y+                val isMin = p.y < run[i - 1].y && p.y < run[i + 1].y+                if (!isMax && !isMin) continue+                val kind = if (isMax) FeatureKind.MAXIMUM else FeatureKind.MINIMUM+                val point = if (curve.polar) p else {+                    val x = refineExtremum({ evalOrNaN(curve.expr, it, angle) }, run[i - 1].x, run[i + 1].x, isMax)+                    val y = evalOrNaN(curve.expr, x, angle)+                    if (y.isFinite()) GraphPoint(x, y) else p+                }+                out.add(GraphFeature(point, kind, listOf(curve.id)))+            }         }-        return out     } -    /** x-values where `f(x) = g(x)` — the roots of `f - g`. */-    fun intersections(f: Expression, g: Expression, angle: AngleMode, xMin: Double, xMax: Double): List<Double> {-        val out = ArrayList<Double>()-        val step = (xMax - xMin) / SAMPLES-        fun diff(x: Double): Double {-            val a = evalOrNaN(f, x, angle); val b = evalOrNaN(g, x, angle)-            return a - b+    /**+     * Crossings between two curves. Works for any combination of Cartesian and polar because+     * it intersects the sampled polylines geometrically; Cartesian pairs are then refined on+     * `f - g`, and are additionally checked for tangential touches, which a purely geometric+     * crossing test cannot see.+     */+    private fun intersectionFeatures(+        a: SampledCurve,+        b: SampledCurve,+        at: GraphPoint,+        radius: Double,+        angle: AngleMode,+        out: MutableList<GraphFeature>,+    ) {+        val ids = listOf(a.id, b.id)+        for (runA in a.runs) {+            for (i in 0 until runA.size - 1) {+                val p1 = runA[i]+                val p2 = runA[i + 1]+                if (segmentDistance(at, p1, p2) > radius) continue+                for (runB in b.runs) {+                    for (j in 0 until runB.size - 1) {+                        val q1 = runB[j]+                        val q2 = runB[j + 1]+                        if (segmentDistance(at, q1, q2) > radius) continue+                        val hit = segmentIntersection(p1, p2, q1, q2) ?: continue+                        val point = if (!a.polar && !b.polar) {+                            val lo = minOf(p1.x, p2.x, q1.x, q2.x)+                            val hi = maxOf(p1.x, p2.x, q1.x, q2.x)+                            val diff = { x: Double -> evalOrNaN(a.expr, x, angle) - evalOrNaN(b.expr, x, angle) }+                            val x = refineZero(diff, lo, hi)+                            val y = evalOrNaN(a.expr, x, angle)+                            if (y.isFinite()) GraphPoint(x, y) else hit+                        } else hit+                        out.add(GraphFeature(point, FeatureKind.INTERSECTION, ids))+                    }+                }+            }         }-        var prevX = xMin-        var prevY = diff(prevX)-        var i = 1-        while (i <= SAMPLES) {-            val x = xMin + i * step-            val y = diff(x)-            if (prevY.isFinite() && y.isFinite() && prevY * y < 0 && abs(y - prevY) < 1e6) {-                out.add(bisectDiff(f, g, angle, prevX, x))+        if (!a.polar && !b.polar) tangentialTouches(a, b, at, radius, angle, out)+    }++    /**+     * Points where two Cartesian curves touch without crossing (`x²` and `2x-1` at x = 1).+     * `f - g` has a local minimum in absolute value there but never changes sign, so this+     * looks for those minima and accepts the ones that reach zero to within a fraction of a+     * pixel — [radius] stands in for the touch tolerance's scale.+     */+    private fun tangentialTouches(+        a: SampledCurve,+        b: SampledCurve,+        at: GraphPoint,+        radius: Double,+        angle: AngleMode,+        out: MutableList<GraphFeature>,+    ) {+        val diff = { x: Double -> evalOrNaN(a.expr, x, angle) - evalOrNaN(b.expr, x, angle) }+        val steps = 240+        val lo = at.x - radius+        val hi = at.x + radius+        val tolerance = radius * 1e-3+        var prev = diff(lo)+        var cur = diff(lo + (hi - lo) / steps)+        for (i in 2..steps) {+            val x = lo + (hi - lo) * i / steps+            val next = diff(x)+            if (prev.isFinite() && cur.isFinite() && next.isFinite()) {+                val xPrev = lo + (hi - lo) * (i - 2) / steps+                val isTrough = abs(cur) < abs(prev) && abs(cur) < abs(next)+                if (isTrough) {+                    val xt = refineExtremum({ -abs(diff(it)) }, xPrev, x, wantMax = true)+                    val dv = diff(xt)+                    if (dv.isFinite() && abs(dv) <= tolerance) {+                        val y = evalOrNaN(a.expr, xt, angle)+                        if (y.isFinite()) {+                            out.add(GraphFeature(GraphPoint(xt, y), FeatureKind.INTERSECTION, listOf(a.id, b.id)))+                        }+                    }+                }             }-            prevX = x; prevY = y; i+++            prev = cur+            cur = next         }-        return out     } -    // --- refinement ---+    // ---- Numeric helpers ---- -    private fun bisect(e: Expression, angle: AngleMode, lo0: Double, hi0: Double): Double {-        var lo = lo0; var hi = hi0-        var flo = evalOrNaN(e, lo, angle)-        repeat(REFINE_ITERS) {-            val mid = (lo + hi) / 2-            val fmid = evalOrNaN(e, mid, angle)-            if (fmid == 0.0 || !fmid.isFinite()) return mid-            if (flo * fmid < 0) hi = mid else { lo = mid; flo = fmid }-        }-        return (lo + hi) / 2+    /**+     * Whether a sign change happens between [a] and [b], *including* the case where one of+     * them is exactly zero. Requiring a strict `a * b < 0` was the long-standing bug here: a+     * viewport centred on the origin makes samples land exactly on the nice crossing points,+     * so the product is `0`, not negative, and the crossing was skipped every time.+     */+    private fun straddles(a: Double, b: Double): Boolean {+        if (!a.isFinite() || !b.isFinite()) return false+        return (a <= 0.0 && b >= 0.0) || (a >= 0.0 && b <= 0.0)+    }++    /** Linear interpolation of the parameter where `va → vb` crosses zero. */+    private fun interpolateZero(va: Double, vb: Double, pa: Double, pb: Double): Double {+        val d = vb - va+        if (d == 0.0) return pa+        return pa + (pb - pa) * (-va / d)     } -    private fun bisectDiff(f: Expression, g: Expression, angle: AngleMode, lo0: Double, hi0: Double): Double {-        var lo = lo0; var hi = hi0-        fun d(x: Double) = evalOrNaN(f, x, angle) - evalOrNaN(g, x, angle)-        var flo = d(lo)+    /** Bisection for `f(x) = 0` on a bracketing interval, tolerant of exact zeros. */+    private fun refineZero(f: (Double) -> Double, lo0: Double, hi0: Double): Double {+        var lo = lo0+        var hi = hi0+        var flo = f(lo)+        val fhi = f(hi)+        if (flo == 0.0) return lo+        if (fhi == 0.0) return hi+        if (!flo.isFinite() || !fhi.isFinite() || !straddles(flo, fhi)) return (lo + hi) / 2         repeat(REFINE_ITERS) {             val mid = (lo + hi) / 2-            val fmid = d(mid)+            val fmid = f(mid)             if (fmid == 0.0 || !fmid.isFinite()) return mid-            if (flo * fmid < 0) hi = mid else { lo = mid; flo = fmid }+            if (straddles(flo, fmid)) hi = mid else { lo = mid; flo = fmid }         }         return (lo + hi) / 2     } -    /** Ternary search for the extremum of a unimodal bracket `[lo, hi]`. */-    private fun ternary(e: Expression, angle: AngleMode, lo0: Double, hi0: Double, wantMax: Boolean): Double {-        var lo = lo0; var hi = hi0+    /** Ternary search for the extremum of a unimodal bracket. */+    private fun refineExtremum(f: (Double) -> Double, lo0: Double, hi0: Double, wantMax: Boolean): Double {+        var lo = lo0+        var hi = hi0         repeat(REFINE_ITERS) {             val m1 = lo + (hi - lo) / 3             val m2 = hi - (hi - lo) / 3-            val f1 = evalOrNaN(e, m1, angle)-            val f2 = evalOrNaN(e, m2, angle)+            val f1 = f(m1)+            val f2 = f(m2)+            if (!f1.isFinite() || !f2.isFinite()) return (lo + hi) / 2             val keepLeft = if (wantMax) f1 > f2 else f1 < f2             if (keepLeft) hi = m2 else lo = m1         }         return (lo + hi) / 2     } -    /** Add [x] unless a near-duplicate is already present (features found twice by sampling). */-    private fun addUnique(list: MutableList<Double>, x: Double) {-        if (list.none { abs(it - x) < 1e-4 * (1 + abs(x)) }) list.add(x)+    // ---- Geometry ----++    private fun distance(a: GraphPoint, b: GraphPoint) = hypot(a.x - b.x, a.y - b.y)++    /** Shortest distance from [p] to the segment `a→b`. */+    private fun segmentDistance(p: GraphPoint, a: GraphPoint, b: GraphPoint): Double {+        val dx = b.x - a.x+        val dy = b.y - a.y+        val lenSq = dx * dx + dy * dy+        if (lenSq == 0.0) return distance(p, a)+        val t = (((p.x - a.x) * dx + (p.y - a.y) * dy) / lenSq).coerceIn(0.0, 1.0)+        return hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy))+    }++    /** Where segments `p1→p2` and `q1→q2` cross, or null if they don't. */+    private fun segmentIntersection(p1: GraphPoint, p2: GraphPoint, q1: GraphPoint, q2: GraphPoint): GraphPoint? {+        val rx = p2.x - p1.x+        val ry = p2.y - p1.y+        val sx = q2.x - q1.x+        val sy = q2.y - q1.y+        val denom = rx * sy - ry * sx+        if (denom == 0.0) return null // parallel or collinear+        val qpx = q1.x - p1.x+        val qpy = q1.y - p1.y+        val t = (qpx * sy - qpy * sx) / denom+        val u = (qpx * ry - qpy * rx) / denom+        if (t < 0.0 || t > 1.0 || u < 0.0 || u > 1.0) return null+        return GraphPoint(p1.x + t * rx, p1.y + t * ry)+    }++    /** Collapses features that describe the same point, keeping the most specific kind. */+    private fun dedupe(sorted: List<GraphFeature>): List<GraphFeature> {+        val out = ArrayList<GraphFeature>()+        for (f in sorted) {+            val scale = 1e-6 * (1 + abs(f.point.x) + abs(f.point.y))+            if (out.none { distance(it.point, f.point) <= scale }) out.add(f)+        }+        return out     } }
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 f7e6cca56b..53b55c606f 100644--- a/calculator/src/main/res/values/strings.xml+++ b/calculator/src/main/res/values/strings.xml@@ -6,8 +6,15 @@     <string name="close">Close</string>     <string name="clear">Clear</string>     <string name="graph">Graph</string>-    <string name="analysis">Analysis</string>-    <string name="done">Done</string>-    <string name="clear_markers">Clear markers</string>     <string name="add_function">Add function</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)". -->+    <string name="feature_y_intercept">y-intercept</string>+    <!-- Graph: label on a marker at a curve's local low point. Lowercase noun, shown as "minimum (0, -2)". -->+    <string name="feature_minimum">minimum</string>+    <!-- Graph: label on a marker at a curve's local high point. Lowercase noun, shown as "maximum (1.57, 1)". -->+    <string name="feature_maximum">maximum</string>+    <!-- Graph: label on a marker where two curves cross. Lowercase noun, shown as "intersection (1, 1)". -->+    <string name="feature_intersection">intersection</string> </resources>
camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt b/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.ktindex ecc1a2fb1b..000a77a2ce 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt@@ -1199,7 +1199,8 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {      * Binds a manual Preview + ImageCapture + ImageAnalysis session for the photo modes      * (PHOTO / PORTRAIT / PANORAMA / PHOTOSPHERE / QR). ImageCapture requests the sensor's      * maximum resolution; if the 3-stream max-res combination exceeds a device's stream-config-     * limits, it falls back to a default ImageCapture resolution.+     * limits, it falls back to a default ImageCapture resolution. ImageAnalysis is always+     * capped (~1.2 MP) — see the note in [bind].      */     suspend fun setupPhotoSession(): Boolean {         Log.d("NightPreview", "setupPhotoSession() ENTRY thread=${Thread.currentThread().name} lens=${_lensFacing.value} surfaceBefore=${_surfaceRequest.value?.resolution}")@@ -1265,13 +1266,28 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {                     // Crop stills to the selected aspect ratio (1:1 / 16:9 / 4:3). CameraX crops                     // OutputFileOptions saves to this and exposes it as cropRect for in-memory shots.                     capture.setCropAspectRatio(currentCropAspectRatio())+                    // Cap the analysis stream at ~1.2 MP, independently of [maxRes] (which stays+                    // about ImageCapture — stills are unaffected and still come off the sensor at+                    // full resolution). Nothing reading this stream benefits from sensor+                    // resolution: PhotoAnalyzer samples average luminance, runs a ZXing decode+                    // over the whole Y plane, and copies each frame via toBitmap() for the+                    // Motion-Photo ring buffer, whose frames MotionPhotoEncoder then converts to+                    // I420 in a per-pixel loop. All of that is paid per frame and scales with+                    // area, so an uncapped stream made QR scanning and motion capture far more+                    // expensive on high-end sensors for no quality gain. Night mode is unaffected:+                    // captureNightBurst() shoots full-resolution frames through ImageCapture.                     val analysisBuilder = ImageAnalysis.Builder()                         .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)-                    if (maxRes) {-                        analysisBuilder.setResolutionSelector(-                            ResolutionSelector.Builder().setResolutionStrategy(ResolutionStrategy.HIGHEST_AVAILABLE_STRATEGY).build()+                        .setResolutionSelector(+                            ResolutionSelector.Builder()+                                .setResolutionStrategy(+                                    ResolutionStrategy(+                                        Size(1280, 960), // ~1.2 MP+                                        ResolutionStrategy.FALLBACK_RULE_CLOSEST_LOWER_THEN_HIGHER+                                    )+                                )+                                .build()                         )-                    }                     val analysis = analysisBuilder.build()                     imageAnalysis = analysis                     bindSession(provider, owner, selector, preview, capture, analysis).also {@@ -1557,7 +1573,7 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {      * Portrait session: full-resolution ImageCapture (final image stays max-res) but capped      * ImageAnalysis (~0.8 MP, 1024x768) for smooth preview segmentation. This fixes the      * "No supported surface combination" bind failures that happened when portrait reused-     * the max-res 3-stream photo path (Preview + max ImageCapture + max ImageAnalysis) for a+     * the then-uncapped 3-stream photo path (Preview + max ImageCapture + max ImageAnalysis) for a      * model that only needs 256x256.      *      * Fallback ladder prioritizes keeping max-res capture:
camera/src/main/java/com/vayunmathur/camera/util/PhotoAnalyzer.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/PhotoAnalyzer.kt b/camera/src/main/java/com/vayunmathur/camera/util/PhotoAnalyzer.ktindex 1a6a539cba..ba6b089cbb 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/PhotoAnalyzer.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/PhotoAnalyzer.kt@@ -43,7 +43,9 @@ class PhotoAnalyzer(     override fun analyze(imageProxy: ImageProxy) {         val startMs = System.currentTimeMillis()         try {-            val buffer = imageProxy.planes[0].buffer+            val plane = imageProxy.planes[0]+            val rowStride = plane.rowStride+            val buffer = plane.buffer             val bytes = ByteArray(buffer.remaining())             try {                 buffer.get(bytes)@@ -67,7 +69,7 @@ class PhotoAnalyzer(             }             if (count > 0) {                 val avg = sum.toFloat() / count-                Log.d("NightPreview", "PhotoAnalyzer luma avg=$avg sum=$sum count=$count bytesSize=${bytes.size} width=${imageProxy.width} height=${imageProxy.height} timestamp=${imageProxy.imageInfo.timestamp} rot=${imageProxy.imageInfo.rotationDegrees} took=${System.currentTimeMillis() - startMs}ms")+                Log.d("NightPreview", "PhotoAnalyzer luma avg=$avg sum=$sum count=$count bytesSize=${bytes.size} width=${imageProxy.width} height=${imageProxy.height} rowStride=$rowStride timestamp=${imageProxy.imageInfo.timestamp} rot=${imageProxy.imageInfo.rotationDegrees} took=${System.currentTimeMillis() - startMs}ms")                 try {                     onLuminance(avg)                 } catch (e: Exception) {@@ -98,9 +100,17 @@ class PhotoAnalyzer(                 }             } +            // dataWidth (arg 2) is the stride of the backing array, NOT the image width — the+            // two only coincide when the HAL packs Y rows tightly. Most camera HALs pad each+            // row out to a 32/64-byte boundary, so for a 1440-wide analysis frame rowStride+            // comes back as 1472 or 1536. Passing width there makes ZXing start each row+            // (rowStride - width) bytes early, shearing the frame progressively down the+            // image and destroying the finder patterns, so nothing ever decodes. It fails+            // silently and only on devices whose analysis width isn't already aligned, which+            // is why QR scanning worked on some phones and not others.             val source = PlanarYUVLuminanceSource(                 bytes,-                imageProxy.width,+                rowStride,                 imageProxy.height,                 0, 0,                 imageProxy.width,
camera/src/main/java/com/vayunmathur/camera/util/QrAnalyzer.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/QrAnalyzer.kt b/camera/src/main/java/com/vayunmathur/camera/util/QrAnalyzer.ktindex 9cf4b1dea6..06f1a7aa82 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/QrAnalyzer.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/QrAnalyzer.kt@@ -15,13 +15,17 @@ class QrAnalyzer(private val onQrDetected: (String) -> Unit) : ImageAnalysis.Ana      @OptIn(ExperimentalGetImage::class)     override fun analyze(imageProxy: ImageProxy) {-        val buffer = imageProxy.planes[0].buffer+        val plane = imageProxy.planes[0]+        val buffer = plane.buffer         val bytes = ByteArray(buffer.remaining())         buffer.get(bytes) +        // dataWidth (arg 2) is the backing array's row stride, not the image width; HALs pad+        // Y rows to an alignment boundary, and using width there shears the frame so no code+        // ever decodes. See the same fix in [PhotoAnalyzer].         val source = PlanarYUVLuminanceSource(             bytes,-            imageProxy.width,+            plane.rowStride,             imageProxy.height,             0, 0,             imageProxy.width,
games/wordmaker/src/main/assets/levels/100.txt
diff --git a/games/wordmaker/src/main/assets/levels/100.txt b/games/wordmaker/src/main/assets/levels/100.txtindex 8617a537c8..b5017b5996 100644--- a/games/wordmaker/src/main/assets/levels/100.txt+++ b/games/wordmaker/src/main/assets/levels/100.txt@@ -1,5 +1,6 @@-FORM      - FIRM R   +FORM++ FIRM R   O   IRON  INFORM  O F  R   FOR
library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.kt b/library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.ktindex a55dc93d04..3cc9da1658 100644--- a/library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.kt+++ b/library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.kt@@ -138,6 +138,14 @@ class DataStoreUtils private constructor(context: Context) {         return dataStore.data.map { it[stringSetPreferencesKey(key)] ?: emptySet() }     } +    /**+     * Suspend variant that awaits DataStore hydration. Use this rather than a snapshot read+     * when the caller may run before the store has loaded — e.g. a service started at boot.+     */+    suspend fun getStringSetAwait(name: String): Set<String> {+        return dataStore.data.first()[stringSetPreferencesKey(name)] ?: emptySet()+    }+     fun addStringToSet(string: String, id: String) {         scope.launch {             dataStore.edit {
vpn/src/main/java/com/vayunmathur/vpn/MainActivity.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/MainActivity.kt b/vpn/src/main/java/com/vayunmathur/vpn/MainActivity.ktindex d1bc78d1bc..4f4a67f941 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/MainActivity.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/MainActivity.kt@@ -23,6 +23,7 @@ import com.vayunmathur.vpn.data.ConnectionLogDao import com.vayunmathur.vpn.data.DB_NAME import com.vayunmathur.vpn.data.VpnConfigDao import com.vayunmathur.vpn.data.VpnDatabase+import com.vayunmathur.vpn.ui.BypassListPage import com.vayunmathur.vpn.ui.ConfigDetailPage import com.vayunmathur.vpn.ui.ConfigListPage import com.vayunmathur.vpn.ui.LoggingPage@@ -90,6 +91,8 @@ sealed interface Route : NavKey {     data object Logging : Route     @Serializable     data object Settings : Route+    @Serializable+    data object BypassList : Route }  @Composable@@ -117,5 +120,6 @@ fun Navigation(vm: VpnViewModel) {         entry<Route.Detail> { ConfigDetailPage(backStack, vm, it.id) }         entry<Route.Logging> { LoggingPage(backStack, vm) }         entry<Route.Settings> { SettingsPage(backStack, vm) }+        entry<Route.BypassList> { BypassListPage(backStack) }     } }
vpn/src/main/java/com/vayunmathur/vpn/service/VpnTunnelService.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/service/VpnTunnelService.kt b/vpn/src/main/java/com/vayunmathur/vpn/service/VpnTunnelService.ktindex 31e95c7467..873df08e14 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/service/VpnTunnelService.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/service/VpnTunnelService.kt@@ -7,6 +7,7 @@ import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.content.Intent+import android.content.pm.PackageManager import android.content.pm.ServiceInfo import android.net.VpnService import android.os.Build@@ -21,6 +22,7 @@ import com.vayunmathur.vpn.data.VpnDatabase import com.vayunmathur.vpn.data.endpointHost import com.vayunmathur.vpn.data.endpointPort import com.vayunmathur.vpn.data.toModel+import com.vayunmathur.vpn.util.BypassList import com.vayunmathur.vpn.util.VpnNative import java.io.FileInputStream import java.io.FileOutputStream@@ -186,6 +188,19 @@ class VpnTunnelService : VpnService() {         }         try { b.setUnderlyingNetworks(null) } catch (_: Exception) {} +        // Split tunnelling. addDisallowedApplication throws if the package is gone (user+        // uninstalled it after adding it to the list), so each one is guarded individually+        // rather than losing the whole tunnel to one stale entry.+        for (pkg in BypassList.load(applicationContext)) {+            try {+                b.addDisallowedApplication(pkg)+            } catch (e: PackageManager.NameNotFoundException) {+                Log.w(TAG, "bypass: $pkg not installed, skipping")+            } catch (e: Exception) {+                Log.w(TAG, "bypass: $pkg", e)+            }+        }+         val pfd = try { b.establish() } catch (e: Exception) {             Log.e(TAG, "establish", e); VpnNative.freeTunnel(handle); stopVpn(); return         }
vpn/src/main/java/com/vayunmathur/vpn/ui/BypassListPage.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/ui/BypassListPage.kt b/vpn/src/main/java/com/vayunmathur/vpn/ui/BypassListPage.ktnew file mode 100644index 0000000000..069f90276a--- /dev/null+++ b/vpn/src/main/java/com/vayunmathur/vpn/ui/BypassListPage.kt@@ -0,0 +1,196 @@+package com.vayunmathur.vpn.ui++import android.content.Intent+import android.content.pm.ApplicationInfo+import android.content.pm.PackageManager+import android.graphics.drawable.Drawable+import android.provider.Settings+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.produceState+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.drawscope.drawIntoCanvas+import androidx.compose.ui.graphics.nativeCanvas+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.compose.runtime.collectAsState+import androidx.compose.foundation.Canvas+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.CardDefaults+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.IconNavigation+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.Switch+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TopAppBar+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.vpn.R+import com.vayunmathur.vpn.Route+import com.vayunmathur.vpn.util.BypassList+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext++/** One selectable row: an installed app the user can route around the tunnel. */+private data class BypassApp(+    val packageName: String,+    val label: String,+    val icon: Drawable?,+)++/**+ * Per-app split tunnelling. Anything switched on here is passed to+ * `VpnService.Builder.addDisallowedApplication` next time the tunnel is established.+ *+ * The list only offers apps that hold INTERNET — excluding the rest keeps it to apps where+ * the choice actually means something — and never offers this app itself, since bypassing+ * our own traffic has no useful meaning here.+ */+@Composable+fun BypassListPage(backStack: NavBackStack<Route>) {+    val context = LocalContext.current+    val bypassed by BypassList.flow(context).collectAsState(initial = emptySet())++    // PackageManager queries are slow enough to jank the first frame; do them off the main+    // thread and show a spinner until they land.+    val apps by produceState<List<BypassApp>?>(initialValue = null) {+        value = withContext(Dispatchers.IO) { loadApps(context.packageManager, context.packageName) }+    }++    Scaffold(+        topBar = {+            TopAppBar(+                title = { Text(stringResource(R.string.bypass_list_title)) },+                navigationIcon = { IconNavigation(backStack) },+            )+        },+    ) { pad ->+        val list = apps+        if (list == null) {+            Box(Modifier.fillMaxSize().padding(pad), contentAlignment = Alignment.Center) {+                Column(horizontalAlignment = Alignment.CenterHorizontally) {+                    CircularProgressIndicator()+                    Text(+                        stringResource(R.string.bypass_loading_apps),+                        Modifier.padding(top = 12.dp),+                        style = MaterialTheme.typography.bodyMedium,+                    )+                }+            }+            return@Scaffold+        }++        LazyColumn(Modifier.fillMaxSize().padding(pad)) {+            item {+                LockdownWarning()+            }+            item {+                Text(+                    stringResource(R.string.bypass_selected_count, bypassed.size),+                    Modifier.padding(horizontal = 16.dp, vertical = 8.dp),+                    style = MaterialTheme.typography.labelLarge,+                    color = MaterialTheme.colorScheme.onSurfaceVariant,+                )+            }+            items(list, key = { it.packageName }) { app ->+                val isBypassed = app.packageName in bypassed+                ListItem(+                    modifier = Modifier.fillMaxWidth(),+                    leadingContent = { AppIconImage(app.icon) },+                    trailingContent = {+                        Switch(+                            checked = isBypassed,+                            onCheckedChange = { BypassList.setBypassed(context, app.packageName, it) },+                        )+                    },+                    supportingContent = { Text(app.packageName) },+                    content = { Text(app.label) },+                )+            }+        }+    }+}++/**+ * Android has no public API for reading the "Block connections without VPN" flag, so this+ * states the interaction plainly instead of trying to detect it.+ */+@Composable+private fun LockdownWarning() {+    val context = LocalContext.current+    Card(+        modifier = Modifier.fillMaxWidth().padding(16.dp),+        colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.errorContainer),+    ) {+        Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+            Text(+                stringResource(R.string.bypass_lockdown_warning),+                style = MaterialTheme.typography.bodyMedium,+                color = MaterialTheme.colorScheme.onErrorContainer,+            )+            Button(onClick = { openVpnSettings(context) }) {+                Text(stringResource(R.string.open_system_vpn_settings))+            }+        }+    }+}++/** Draws a PackageManager Drawable without pulling in an image-loading dependency. */+@Composable+private fun AppIconImage(icon: Drawable?) {+    if (icon == null) {+        Box(Modifier.size(40.dp))+        return+    }+    Canvas(Modifier.size(40.dp)) {+        drawIntoCanvas { canvas ->+            icon.setBounds(0, 0, size.width.toInt(), size.height.toInt())+            icon.draw(canvas.nativeCanvas)+        }+    }+}++private fun loadApps(pm: PackageManager, selfPackage: String): List<BypassApp> {+    val installed = runCatching {+        pm.getInstalledApplications(PackageManager.GET_META_DATA)+    }.getOrDefault(emptyList())++    return installed+        .asSequence()+        .filter { it.packageName != selfPackage }+        // Only apps that can actually use the network; the rest would be noise.+        .filter { pm.checkPermission(android.Manifest.permission.INTERNET, it.packageName) == PackageManager.PERMISSION_GRANTED }+        .map { info: ApplicationInfo ->+            BypassApp(+                packageName = info.packageName,+                label = runCatching { pm.getApplicationLabel(info).toString() }+                    .getOrDefault(info.packageName),+                icon = runCatching { pm.getApplicationIcon(info) }.getOrNull(),+            )+        }+        .sortedBy { it.label.lowercase() }+        .toList()+}++internal fun openVpnSettings(context: android.content.Context) {+    try {+        context.startActivity(Intent(Settings.ACTION_VPN_SETTINGS))+    } catch (_: Exception) {+        try {+            context.startActivity(Intent(Settings.ACTION_SETTINGS))+        } catch (_: Exception) {}+    }+}
vpn/src/main/java/com/vayunmathur/vpn/ui/SettingsPage.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/ui/SettingsPage.kt b/vpn/src/main/java/com/vayunmathur/vpn/ui/SettingsPage.ktindex ed5ce0d264..3b7a31bb23 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/ui/SettingsPage.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/ui/SettingsPage.kt@@ -1,111 +1,48 @@ package com.vayunmathur.vpn.ui -import androidx.compose.ui.res.stringResource-import com.vayunmathur.vpn.R-import android.content.Intent-import android.provider.Settings-import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll-import androidx.compose.material3.Card-import androidx.compose.material3.CardDefaults-import androidx.compose.material3.MaterialTheme-import androidx.compose.material3.Scaffold-import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext-import androidx.compose.ui.text.font.FontFamily-import androidx.compose.ui.unit.dp-import androidx.compose.ui.unit.sp-import com.vayunmathur.library.ui.Button+import androidx.compose.ui.res.stringResource import com.vayunmathur.library.ui.IconNavigation+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TopAppBar+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.vpn.R import com.vayunmathur.vpn.Route import com.vayunmathur.vpn.util.VpnViewModel-import com.vayunmathur.library.util.NavBackStack  @Composable fun SettingsPage(backStack: NavBackStack<Route>, vm: VpnViewModel) {     val context = LocalContext.current     Scaffold(-        topBar = { TopAppBar(title = { Text(stringResource(R.string.settings_about)) }, navigationIcon = { IconNavigation(backStack) }) }+        topBar = {+            TopAppBar(+                title = { Text(stringResource(R.string.settings_about)) },+                navigationIcon = { IconNavigation(backStack) },+            )+        },     ) { pad ->         Column(-            Modifier.fillMaxSize().padding(pad).padding(16.dp)-                .verticalScroll(rememberScrollState()),-            verticalArrangement = Arrangement.spacedBy(16.dp),+            Modifier.fillMaxSize().padding(pad).verticalScroll(rememberScrollState()),         ) {-            // Always-On card-            Card(-                modifier = Modifier.fillMaxWidth(),-                colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.primaryContainer)-            ) {-                Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {-                    Text(stringResource(R.string.always_on_vpn), style = MaterialTheme.typography.titleMedium)-                    Text(-                        stringResource(R.string.enable_always_on_in_android_system_vpn_s) +-                        "Go to Settings → Network & Internet → VPN → gear next to this app → enable Always-On VPN.\n\n" +-                        "This app declares SUPPORTS_ALWAYS_ON and uses START_STICKY with last-used tunnel restore on null intent.",-                        fontSize = 12.sp,-                    )-                    Button(onClick = {-                        try {-                            context.startActivity(Intent(Settings.ACTION_VPN_SETTINGS))-                        } catch (_: Exception) {-                            try {-                                context.startActivity(Intent(Settings.ACTION_SETTINGS))-                            } catch (_: Exception) {}-                        }-                    }) {-                        Text(stringResource(R.string.open_system_vpn_settings))-                    }-                }-            }--            Card(colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant)) {-                Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {-                    Text(stringResource(R.string.vpn_wireguard_gotatun_boringtun_fork), style = MaterialTheme.typography.titleMedium)-                    Text(-                        stringResource(R.string.this_app_ships_a_pure_rust_implementatio) +-                        "Mullvad's gotatun repository (https://github.com/mullvad/gotatun), itself a " +-                        "fork of Cloudflare's boringtun.\n\n" +-                        "Gotatun implements the Noise IK handshake (X25519, ChaCha20-Poly1305, " +-                        "BLAKE2s), DoS-mitigation cookies (XChaCha20Poly1305), and session handling " +-                        "with rekey/keepalive timers and an anti-replay window. " +-                        "The Rust crate in vpn/src/main/rust vendores gotatun's noise/, packet/, " +-                        "crypto/, tun/ modules with ring/aws-lc-rs shimmed to " +-                        "pure chacha20poly1305 so the aarch64-linux-android cdylib compiles.\n\n" +-                        "Android side: a foreground VpnService (VpnTunnelService) drives the Rust Tunn " +-                        "via JNI. It owns a handle from VpnNative.newTunnel(...). " +-                        "The loop bridges TUN fd (plaintext IP) <-> encapsulate and UDP " +-                        "(encrypted WG) <-> consumeIncomingPacketDetailed. Timer ticks every 100ms emit " +-                        "keepalives and handshake retransmits.\n\n" +-                        "Logging: packet inspection in Kotlin on plaintext IP from TUN (IPv4/IPv6 UDP/TCP parsing), DNS snooping " +-                        "for UDP dport 53 to map IP→domain, SNI extraction from TLS ClientHello for DoH fallback, per-app " +-                        "attribution via ConnectivityManager.getConnectionOwnerUid(). Batched 1.5s upserts to encrypted Room.\n\n" +-                        "Config storage: Room encrypted db (vpn-db) via :library:room / SQLCipher — each " +-                        "config stores Interface Address/DNS/MTU and Peer PublicKey/PresharedKey/AllowedIPs/" +-                        "Endpoint/PersistentKeepalive plus device Private/Public keys. " +-                        "Import supports wg-quick .conf paste and export produces a valid wg-quick file.\n\n" +-                        "Licence: gotatun is MPL-2.0 (previously BSD-3 for older Cloudflare parts); " +-                        "this module is MPL-2.0.\n\n" +-                        "WireGuard is a registered trademark of Jason A. Donenfeld.",-                        fontSize = 12.sp,-                    )-                    Text(-                        stringResource(R.string.emulator_without_ndk_rust_built_so_will) +-                        ":vpn:assembleDev builds libvpn_wireguard.so into rustJniLibs/arm64-v8a.",-                        fontSize = 11.sp,-                        fontFamily = FontFamily.Monospace,-                        color = MaterialTheme.colorScheme.onSurfaceVariant,-                    )-                }-            }+            ListItem(+                modifier = Modifier.fillMaxWidth().clickable { openVpnSettings(context) },+                content = { Text(stringResource(R.string.always_on_vpn)) },+            )+            ListItem(+                modifier = Modifier.fillMaxWidth().clickable { backStack.add(Route.BypassList) },+                content = { Text(stringResource(R.string.bypass_list)) },+            )         }     } }
vpn/src/main/java/com/vayunmathur/vpn/util/BypassList.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/util/BypassList.kt b/vpn/src/main/java/com/vayunmathur/vpn/util/BypassList.ktnew file mode 100644index 0000000000..d4efe59766--- /dev/null+++ b/vpn/src/main/java/com/vayunmathur/vpn/util/BypassList.kt@@ -0,0 +1,34 @@+package com.vayunmathur.vpn.util++import android.content.Context+import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.coroutines.flow.Flow++/**+ * Packages the user has chosen to keep off the tunnel ("split tunnelling").+ *+ * Applied at tunnel setup via `VpnService.Builder.addDisallowedApplication`, which is+ * all-or-nothing per package and cannot be combined with `addAllowedApplication`.+ *+ * Caveat worth knowing about: if the user turns on **Block connections without VPN**+ * (lockdown) in Android's system VPN settings, the platform drops any traffic that isn't+ * inside the tunnel. Bypassed apps are by definition outside it, so they lose network+ * access entirely rather than falling back to the normal connection. There is no public+ * API to read the lockdown flag, so the UI warns rather than detects — see BypassListPage.+ */+object BypassList {+    /** DataStore key holding the set of bypassed package names. */+    const val KEY = "bypass_packages"++    fun flow(context: Context): Flow<Set<String>> =+        DataStoreUtils.getInstance(context).stringSetFlow(KEY)++    /** Await-based read: the tunnel service can start before DataStore has hydrated. */+    suspend fun load(context: Context): Set<String> =+        DataStoreUtils.getInstance(context).getStringSetAwait(KEY)++    fun setBypassed(context: Context, packageName: String, bypassed: Boolean) {+        val ds = DataStoreUtils.getInstance(context)+        if (bypassed) ds.addStringToSet(KEY, packageName) else ds.removeStringFromSet(KEY, packageName)+    }+}
vpn/src/main/res/values/strings.xml
diff --git a/vpn/src/main/res/values/strings.xml b/vpn/src/main/res/values/strings.xmlindex e0819987d8..2a0e32eed9 100644--- a/vpn/src/main/res/values/strings.xml+++ b/vpn/src/main/res/values/strings.xml@@ -1,5 +1,5 @@ <?xml version="1.0" encoding="utf-8"?>-<resources>+<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">     <string name="app_name">VPN</string>     <string name="vpn_wireguard_gotatun">VPN — WireGuard (gotatun)</string>     <string name="no_tunnels_yet">No tunnels yet</string>@@ -10,7 +10,16 @@     <string name="settings_about">Settings / About</string>     <string name="always_on_vpn">Always-On VPN</string>     <string name="open_system_vpn_settings">Open system VPN settings</string>-    <string name="vpn_wireguard_gotatun_boringtun_fork">VPN (WireGuard) — gotatun / BoringTun fork</string>+    <!-- SettingsPage: Row opening the per-app split-tunnel picker. Noun phrase -->+    <string name="bypass_list">Bypass list</string>+    <!-- BypassListPage: Screen title. Noun phrase -->+    <string name="bypass_list_title">Apps that bypass the VPN</string>+    <!-- BypassListPage: Warning about the interaction with system lockdown mode. Sentence -->+    <string name="bypass_lockdown_warning">If “Block connections without VPN” is turned on in Android\'s VPN settings, these apps get no internet at all instead of using your normal connection. Turn it off for bypass to work.</string>+    <!-- BypassListPage: Shown while the installed-app list is being loaded. Sentence fragment -->+    <string name="bypass_loading_apps">Loading apps…</string>+    <!-- BypassListPage: Count of currently bypassed apps. %1$d = number of apps, e.g. 3 -->+    <string name="bypass_selected_count"><xliff:g id="count" example="3">%1$d</xliff:g> bypassing the VPN</string>     <string name="logging">Logging</string>     <string name="delete_all_logs">Delete all logs?</string>     <string name="this_will_permanently_remove_all_connect">This will permanently remove all connection logs and cannot be undone.</string>@@ -29,8 +38,5 @@     <string name="privatekey">PrivateKey: %1$s…</string>     <string name="publickey">PublicKey: %1$s</string>     <string name="peer_publickey">Peer PublicKey: %1$s</string>-    <string name="enable_always_on_in_android_system_vpn_s">Enable Always-On in Android system VPN settings to keep the VPN connected even after reboot. </string>-    <string name="this_app_ships_a_pure_rust_implementatio">This app ships a pure Rust implementation of the WireGuard protocol from </string>-    <string name="emulator_without_ndk_rust_built_so_will">Emulator without NDK Rust built .so will not have keygen available until </string>     <string name="vpn_channel_name">VPN Tunnel</string> </resources>
weather/src/main/rust/src/lib.rs
diff --git a/weather/src/main/rust/src/lib.rs b/weather/src/main/rust/src/lib.rsindex 367d3b7812..8e5e7eecf9 100644--- a/weather/src/main/rust/src/lib.rs+++ b/weather/src/main/rust/src/lib.rs@@ -25,28 +25,14 @@ mod om;  use crate::om::{OmBackend, OmReader}; -use jni::JavaVM;- // ----------------------------------------------------------------------------// Global VM + block caching helpers+// Block caching helpers // --------------------------------------------------------------------------- -static GLOBAL_VM: OnceLock<JavaVM> = OnceLock::new();- /// Size of the HTTP Range block cache, aligned so nearby chunk reads reuse bytes. /// Mirrors old `BLOCK = 64 * 1024`. const BLOCK: u64 = 64 * 1024; -/// Ensure GLOBAL_VM is populated from the current JNIEnv (called on first-/// entry from Java). Subsequent `get_bytes` calls attach via this VM.-fn ensure_global_vm(env: &mut jni::JNIEnv) {-    if GLOBAL_VM.get().is_none() {-        if let Ok(vm) = env.get_java_vm() {-            let _ = GLOBAL_VM.set(vm);-        }-    }-}- // --------------------------------------------------------------------------- // Backends // ---------------------------------------------------------------------------@@ -119,10 +105,7 @@ impl OmBackend for RangeBackend { // Process-wide cache of open RangeBackends keyed by .om URL, so panning / // measure / time scrubbing reuse file size + already-fetched blocks. Matches // old `cached_backend` cap of 12.-fn cached_backend(-    url: &str,-    env: &mut jni::JNIEnv,-) -> Result<Arc<RangeBackend>, String> {+fn cached_backend(url: &str) -> Result<Arc<RangeBackend>, String> {     static CACHE: OnceLock<Mutex<HashMap<String, Arc<RangeBackend>>>> = OnceLock::new();     let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));     {@@ -287,7 +270,6 @@ fn decode_region_url_inner(     north: f64,     out_w: usize,     out_h: usize,-    env: &mut jni::JNIEnv, ) -> Result<Vec<f32>, String> {     if out_w == 0 || out_h == 0 {         return Err("empty output size".to_string());@@ -298,7 +280,7 @@ fn decode_region_url_inner(     let sub_nx = win.x1 - win.x0;     let sub_ny = win.y1 - win.y0; -    let backend = cached_backend(url, env)?;+    let backend = cached_backend(url)?;     let root = OmReader::new(backend).map_err(|e| format!("open failed: {e}"))?;      let data = read_subgrid_generic(&root, variable, &win)?;@@ -382,6 +364,10 @@ mod jni_bindings {     ) -> jfloatArray {         let null = std::ptr::null_mut(); +        // Resolves the bridge class while we still hold a JNIEnv; the range fetches below run+        // through it. Harmless to repeat.+        jni_http::init(&mut env);+         let url: String = match env.get_string(&om_url) {             Ok(s) => s.into(),             Err(_) => return null,@@ -411,7 +397,6 @@ mod jni_bindings {                 north,                 out_w.max(0) as usize,                 out_h.max(0) as usize,-                &mut env,             )         }))         .unwrap_or_else(|_| Err("panic in decode_region".to_string()));
youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabr/YoutubeSabrSession.kt
diff --git a/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabr/YoutubeSabrSession.kt b/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabr/YoutubeSabrSession.ktindex 044ee2f378..bd8c029609 100644--- a/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabr/YoutubeSabrSession.kt+++ b/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabr/YoutubeSabrSession.kt@@ -1098,9 +1098,25 @@ class YoutubeSabrSession {         val initializationUrl = format.initializationUrl         val start = format.initRangeStart         val end = format.initRangeEnd-        if (initializationUrl.isNullOrEmpty() || start < 0 || end < start || end - start >= MAX_INITIALIZATION_BYTES) {+        // Reported per clause: the range is almost always fine and the URL is what is missing,+        // so a combined message sends you looking in the wrong place. The two ways the URL ends+        // up null need different fixes, so name which one it was — a format with no template at+        // all is SABR-only (no per-format URL exists, nothing to fix here), whereas a template+        // that survived resolution unresolved means the signature decode came back empty.+        if (initializationUrl.isNullOrEmpty()) {+            val reason = if (format.initializationUrlTemplate.isNullOrEmpty()) {+                "no per-format URL in adaptiveFormats (SABR-only format)"+            } else {+                "template present but unresolved, sig=${format.obfuscatedSignature != null} n=${format.obfuscatedNParameter != null}"+            }+            throw IOException("Missing SABR initialization URL: itag=${format.itag}, $reason")+        }+        if (start < 0 || end < start) {             throw IOException("Invalid SABR initialization range: itag=${format.itag}, start=$start, end=$end")         }+        if (end - start >= MAX_INITIALIZATION_BYTES) {+            throw IOException("SABR initialization range too large: itag=${format.itag}, bytes=${end - start + 1}, max=$MAX_INITIALIZATION_BYTES")+        }         if (poToken.isEmpty()) throw IOException("Missing PO token for SABR initialization range: itag=${format.itag}")         val url = appendQueryParameterIfMissing(initializationUrl, "pot", Base64.getUrlEncoder().withoutPadding().encodeToString(poToken))         val length = (end - start + 1).toInt()