Modern Apps git

← Modern-Apps.git

camera: move tap-to-focus into its own file

Commit
231cca61805f1590143dee20519947cf601c7876
Author
Vayun Mathur <[email protected]>
When
2026-11-20 00:21 UTC (16 days ago)
Parents
6eec0a5
The tap-to-focus work in cc942ec2c pushed CameraPreviewBox.kt
to 426 lines, over the 350-line FileLength limit, so
:camera:lint failed.

The whole tap-to-focus responsibility - metering-coordinate
conversion with centre fallback, the single tap/long-press
detector, focus state, and hosting the FocusIndicator with its
expiry - moves to TapToFocus.kt, whose one composable is named
as the file. CameraPreviewBox (296 lines) just creates the
state, chains the modifier, and renders the indicator host.
No behaviour change; no lint config touched.

Verified: :camera:lint and :camera:testDevUnitTest pass.

Diff

camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.ktindex ba44bc1c32..a53f695eb8 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt@@ -8,13 +8,10 @@ import android.graphics.RuntimeShader import android.graphics.Shader import android.os.Build import androidx.camera.core.DynamicRange-import androidx.camera.core.FocusMeteringAction-import androidx.camera.core.SurfaceOrientedMeteringPointFactory import androidx.camera.compose.CameraXViewfinder import androidx.camera.viewfinder.compose.MutableCoordinateTransformer import androidx.camera.viewfinder.core.ImplementationMode import androidx.compose.foundation.background-import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.BoxWithConstraintsScope@@ -25,21 +22,14 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect-import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableIntStateOf-import androidx.compose.runtime.mutableLongStateOf-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.draw.clipToBounds-import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.asComposeRenderEffect import androidx.compose.ui.graphics.graphicsLayer-import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.unit.dp import com.vayunmathur.library.log.Log@@ -79,36 +69,6 @@ internal fun previewRatioForWindow(baseRatio: Float, maxWidth: Float, maxHeight:     return if (isLandscape && baseRatio > 0f) 1f / baseRatio else baseRatio } -/** Minimum gap between two tap-to-focus requests; faster repeats are one gesture, not two. */-private const val FOCUS_TAP_DEBOUNCE_MS = 120L--/** How long the focus ring stays up (its own fade runs inside [FocusIndicator]). */-private const val FOCUS_INDICATOR_LIFETIME_MS = 1_350L--/**- * Normalises a coordinate-transformer output (surface-buffer pixels) into the- * 0..1 range [androidx.camera.core.MeteringPoint] expects, clamped to the- * surface. Pure so it stays unit-testable.- *- * The clamp matters: with `ContentScale.Crop` a tap at the box edge can map- * just outside the buffer, and CameraX rejects an out-of-range point — the- * future then fails and, before this fix, was discarded unread, so the tap- * silently did nothing. A non-finite transform (matrix not populated yet) or- * a degenerate surface falls back to the centre rather than dropping the tap.- */-internal fun normalizedMeteringCoordinates(-    transformedX: Float,-    transformedY: Float,-    surfaceWidth: Float,-    surfaceHeight: Float,-): Pair<Float, Float> {-    if (!transformedX.isFinite() || !transformedY.isFinite() || surfaceWidth <= 0f || surfaceHeight <= 0f) {-        return 0.5f to 0.5f-    }-    return (transformedX / surfaceWidth).coerceIn(0f, 1f) to-        (transformedY / surfaceHeight).coerceIn(0f, 1f)-}- /**  * The letterboxed viewfinder plus its gesture handling, bokeh/color RenderEffects,  * grid/level/night overlays, settings column and panorama overlay. Extracted verbatim@@ -144,18 +104,7 @@ internal fun BoxWithConstraintsScope.CameraPreviewBox(         null     }     val coordinateTransformer = remember { MutableCoordinateTransformer() }-    // Tap-to-focus indicator: small in-screen sub-state (deliberately NOT-    // navigation — a focus point is transient state of this one screen).-    var focusPoint by remember { mutableStateOf<Offset?>(null) }-    var focusTapId by remember { mutableIntStateOf(0) }-    var focusPointLocked by remember { mutableStateOf(false) }-    var lastFocusTapMs by remember { mutableLongStateOf(0L) }-    LaunchedEffect(focusTapId) {-        if (focusTapId > 0) {-            kotlinx.coroutines.delay(FOCUS_INDICATOR_LIFETIME_MS)-            focusPoint = null-        }-    }+    val tapToFocusState = remember { TapToFocusState() }     val previewModifier = previewSize         // CameraX mirrors the front-camera preview by default; counter it when the         // user turns selfie mirroring off so the preview matches the saved image (#632).@@ -221,88 +170,17 @@ internal fun BoxWithConstraintsScope.CameraPreviewBox(                 }             }         )-            // Tap-to-focus is handled HERE, on the preview surface itself, in-            // the same single detector as long-press-to-lock. CameraXViewfinder's-            // built-in tap gesture is disabled below: it raced this detector,-            // gave no tap indicator (its onTapToFocus callback was never wired),-            // silently returned when the transformed point left 0..1, and its-            // result was invisible to the app. Pinch-to-zoom stays built-in.-            //-            // Keyed on surfaceRequest + mirrorPreview, NOT only on-            // activeSetting as before: with the old key the block captured the-            // first-composed surfaceRequest (null before the session binds)-            // for as long as the settings pane stayed closed, so every-            // long-press metering point came back null and was dropped.-            .pointerInput(surfaceRequest, state.mirrorPreview) {-                fun meteringPoint(tapOffset: Offset): androidx.camera.core.MeteringPoint? {-                    val request = surfaceRequest ?: return null-                    return try {-                        val transformed = with(coordinateTransformer) { tapOffset.transform() }-                        val width = request.resolution.width.toFloat()-                        val height = request.resolution.height.toFloat()-                        val (nx, ny) = normalizedMeteringCoordinates(transformed.x, transformed.y, width, height)-                        val factory = if (width > 0f && height > 0f) {-                            SurfaceOrientedMeteringPointFactory(width, height)-                        } else {-                            SurfaceOrientedMeteringPointFactory(1f, 1f)-                        }-                        val surfaceW = if (width > 0f) width else 1f-                        val surfaceH = if (height > 0f) height else 1f-                        factory.createPoint(nx * surfaceW, ny * surfaceH)-                    } catch (e: Exception) {-                        Log.status("TapToFocus", "metering-point conversion failed; using centre point", e)-                        try {-                            SurfaceOrientedMeteringPointFactory(1f, 1f).createPoint(0.5f, 0.5f)-                        } catch (_: Exception) {-                            null-                        }-                    }-                }--                fun showIndicator(tapOffset: Offset, locked: Boolean) {-                    // tapOffset is in the (possibly extra-mirrored) preview-                    // layer's coordinates; the indicator is drawn by a sibling-                    // outside that layer, so flip back into visual coordinates.-                    focusPoint = if (state.mirrorPreview) {-                        Offset(size.width - tapOffset.x, tapOffset.y)-                    } else {-                        tapOffset-                    }-                    focusPointLocked = locked-                    focusTapId++-                }-                detectTapGestures(-                    onTap = { tapOffset ->-                        val now = android.os.SystemClock.uptimeMillis()-                        if (now - lastFocusTapMs < FOCUS_TAP_DEBOUNCE_MS) return@detectTapGestures-                        lastFocusTapMs = now-                        // Indicator first, regardless of AF outcome: it proves-                        // the tap registered even if metering then fails.-                        showIndicator(tapOffset, locked = false)-                        val point = meteringPoint(tapOffset)-                        if (point == null) {-                            Log.status("TapToFocus", "tap with no surface request; falling back to default metering")-                            viewModel.fallbackToDefaultMetering()-                        } else {-                            viewModel.startFocusAndMetering(-                                FocusMeteringAction.Builder(point).build()-                            )-                        }-                    },-                    onLongPress = { tapOffset ->-                        showIndicator(tapOffset, locked = true)-                        val point = meteringPoint(tapOffset)-                        if (point == null) {-                            Log.status("TapToFocus", "long-press with no surface request; cannot lock metering")-                            viewModel.fallbackToDefaultMetering()-                        } else {-                            viewModel.lockFocusAndMetering(-                                FocusMeteringAction.Builder(point).disableAutoCancel().build()-                            )-                        }-                    }-                )-            }+            // Tap-to-focus (gesture, metering, indicator) is owned by+            // TapToFocus.kt; pinch-to-zoom stays built-in below.+            .tapToFocus(+                state = tapToFocusState,+                surfaceRequest = surfaceRequest,+                mirrorPreview = state.mirrorPreview,+                coordinateTransformer = coordinateTransformer,+                onFocus = { viewModel.startFocusAndMetering(it) },+                onLockFocus = { viewModel.lockFocusAndMetering(it) },+                onFallback = { viewModel.fallbackToDefaultMetering() },+            )      surfaceRequest?.let { request ->         LaunchedEffect(request) {@@ -337,7 +215,7 @@ internal fun BoxWithConstraintsScope.CameraPreviewBox(             contentScale = ContentScale.Crop,             // Pinch-to-zoom stays built-in (1.7.0-alpha02); we just sync the             // displayed zoom ratio so the zoom bar stays in step. Tap-to-focus-            // is DISABLED here — it is handled by the pointerInput on+            // is DISABLED here — it is handled by the tapToFocus modifier on             // previewModifier above, which shows the focus ring and observes             // (and falls back from) the metering result. Leaving both enabled             // double-metered every tap and let the built-in detector swallow@@ -374,16 +252,8 @@ internal fun BoxWithConstraintsScope.CameraPreviewBox(     )      // Above the grid/level overlays so the ring is never drawn under them;-    // below the settings column so its controls stay visually on top. The-    // Canvas carries no pointer input, so it never eats the next tap.-    focusPoint?.let { point ->-        FocusIndicator(-            point = point,-            tapId = focusTapId,-            locked = focusPointLocked,-            modifier = previewSize,-        )-    }+    // below the settings column so its controls stay visually on top.+    TapToFocus(state = tapToFocusState, modifier = previewSize)      CameraSettingsColumn(         activeSetting = state.activeSetting,
camera/src/main/java/com/vayunmathur/camera/ui/TapToFocus.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/TapToFocus.kt b/camera/src/main/java/com/vayunmathur/camera/ui/TapToFocus.ktnew file mode 100644index 0000000000..dd12b70cf6--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/ui/TapToFocus.kt@@ -0,0 +1,190 @@+package com.vayunmathur.camera.ui++import android.os.SystemClock+import androidx.camera.core.FocusMeteringAction+import androidx.camera.core.MeteringPoint+import androidx.camera.core.SurfaceOrientedMeteringPointFactory+import androidx.camera.core.SurfaceRequest+import androidx.camera.viewfinder.compose.MutableCoordinateTransformer+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.input.pointer.pointerInput+import com.vayunmathur.library.log.Log+import kotlinx.coroutines.delay++/** Minimum gap between two tap-to-focus requests; faster repeats are one gesture, not two. */+private const val FOCUS_TAP_DEBOUNCE_MS = 120L++/** How long the focus ring stays up (its own fade runs inside [FocusIndicator]). */+private const val FOCUS_INDICATOR_LIFETIME_MS = 1_350L++/**+ * Normalises a coordinate-transformer output (surface-buffer pixels) into the+ * 0..1 range [MeteringPoint] expects, clamped to the+ * surface. Pure so it stays unit-testable.+ *+ * The clamp matters: with `ContentScale.Crop` a tap at the box edge can map+ * just outside the buffer, and CameraX rejects an out-of-range point — the+ * future then fails and, before this fix, was discarded unread, so the tap+ * silently did nothing. A non-finite transform (matrix not populated yet) or+ * a degenerate surface falls back to the centre rather than dropping the tap.+ */+internal fun normalizedMeteringCoordinates(+    transformedX: Float,+    transformedY: Float,+    surfaceWidth: Float,+    surfaceHeight: Float,+): Pair<Float, Float> {+    if (!transformedX.isFinite() || !transformedY.isFinite() || surfaceWidth <= 0f || surfaceHeight <= 0f) {+        return 0.5f to 0.5f+    }+    return (transformedX / surfaceWidth).coerceIn(0f, 1f) to+        (transformedY / surfaceHeight).coerceIn(0f, 1f)+}++/**+ * In-screen tap-to-focus state for one preview: where the ring is, whether+ * the tap locked metering, and the debounce clock. Deliberately NOT+ * navigation — a focus point is transient state of this one screen.+ */+internal class TapToFocusState {+    var point by mutableStateOf<Offset?>(null)+        private set+    var tapId by mutableIntStateOf(0)+        private set+    var locked by mutableStateOf(false)+        private set+    var lastTapMs by mutableLongStateOf(0L)++    fun show(point: Offset, locked: Boolean) {+        this.point = point+        this.locked = locked+        tapId+++    }++    fun clear() {+        point = null+    }+}++private fun meteringPoint(+    tapOffset: Offset,+    surfaceRequest: SurfaceRequest?,+    coordinateTransformer: MutableCoordinateTransformer,+): MeteringPoint? {+    val request = surfaceRequest ?: return null+    return try {+        val transformed = with(coordinateTransformer) { tapOffset.transform() }+        val width = request.resolution.width.toFloat()+        val height = request.resolution.height.toFloat()+        val (nx, ny) = normalizedMeteringCoordinates(transformed.x, transformed.y, width, height)+        val factory = if (width > 0f && height > 0f) {+            SurfaceOrientedMeteringPointFactory(width, height)+        } else {+            SurfaceOrientedMeteringPointFactory(1f, 1f)+        }+        val surfaceW = if (width > 0f) width else 1f+        val surfaceH = if (height > 0f) height else 1f+        factory.createPoint(nx * surfaceW, ny * surfaceH)+    } catch (e: Exception) {+        Log.status("TapToFocus", "metering-point conversion failed; using centre point", e)+        try {+            SurfaceOrientedMeteringPointFactory(1f, 1f).createPoint(0.5f, 0.5f)+        } catch (_: Exception) {+            null+        }+    }+}++/**+ * Tap-to-focus gestures on the preview surface itself, in the same single+ * detector as long-press-to-lock. CameraXViewfinder's built-in tap gesture+ * stays disabled: it raced this detector, gave no tap indicator, silently+ * returned when the transformed point left 0..1, and its result was+ * invisible to the app.+ *+ * Keyed on [surfaceRequest] + [mirrorPreview], NOT only on a settings key:+ * with a stale key the block captured the first-composed surfaceRequest+ * (null before the session binds), so every metering point came back null.+ */+internal fun Modifier.tapToFocus(+    state: TapToFocusState,+    surfaceRequest: SurfaceRequest?,+    mirrorPreview: Boolean,+    coordinateTransformer: MutableCoordinateTransformer,+    onFocus: (FocusMeteringAction) -> Unit,+    onLockFocus: (FocusMeteringAction) -> Unit,+    onFallback: () -> Unit,+): Modifier = pointerInput(surfaceRequest, mirrorPreview) {+    fun showIndicator(tapOffset: Offset, locked: Boolean) {+        // tapOffset is in the (possibly extra-mirrored) preview layer's+        // coordinates; the indicator is drawn by a sibling outside that+        // layer, so flip back into visual coordinates.+        val visual = if (mirrorPreview) {+            Offset(size.width - tapOffset.x, tapOffset.y)+        } else {+            tapOffset+        }+        state.show(visual, locked)+    }+    detectTapGestures(+        onTap = { tapOffset ->+            val now = SystemClock.uptimeMillis()+            if (now - state.lastTapMs < FOCUS_TAP_DEBOUNCE_MS) return@detectTapGestures+            state.lastTapMs = now+            // Indicator first, regardless of AF outcome: it proves the tap+            // registered even if metering then fails.+            showIndicator(tapOffset, locked = false)+            val point = meteringPoint(tapOffset, surfaceRequest, coordinateTransformer)+            if (point == null) {+                Log.status("TapToFocus", "tap with no surface request; falling back to default metering")+                onFallback()+            } else {+                onFocus(FocusMeteringAction.Builder(point).build())+            }+        },+        onLongPress = { tapOffset ->+            showIndicator(tapOffset, locked = true)+            val point = meteringPoint(tapOffset, surfaceRequest, coordinateTransformer)+            if (point == null) {+                Log.status("TapToFocus", "long-press with no surface request; cannot lock metering")+                onFallback()+            } else {+                onLockFocus(FocusMeteringAction.Builder(point).disableAutoCancel().build())+            }+        }+    )+}++/**+ * Hosts the tap-to-focus ring above the preview overlays (below the+ * settings column) and expires it after [FOCUS_INDICATOR_LIFETIME_MS].+ * The Canvas carries no pointer input, so it never eats the next tap.+ */+@Composable+internal fun TapToFocus(+    state: TapToFocusState,+    modifier: Modifier = Modifier,+) {+    LaunchedEffect(state.tapId) {+        if (state.tapId > 0) {+            delay(FOCUS_INDICATOR_LIFETIME_MS)+            state.clear()+        }+    }+    val point = state.point ?: return+    FocusIndicator(+        point = point,+        tapId = state.tapId,+        locked = state.locked,+        modifier = modifier,+    )+}