Modern Apps git

← Modern-Apps.git

camera: unrotate preview, restore aspect choices, QR back in Photo

Commit
1c8a688eb0f720e833416ce657eecd286da0abfe
Author
Vayun Mathur <[email protected]>
When
2026-11-23 20:44 UTC (12 days ago)
Parents
4fe9517
Static root cause: SurfaceTexture already applies the
sensor quarter-turn; PreviewTransform's rotated placement
affine was also passed to TextureView.setTransform,
double-rotating both lenses. The applied matrix is now
an unrotated uniform-fill sampling transform, matching
the old CameraX PreviewView behavior, with exact-fill
math tests for back-90 and front-270.

Aspect choices are restored and functional: 4:3/3:2/
16:9/1:1 in the historical top-bar cycle plus an explicit
Settings picker, now actually driving a sensor-space
center-crop at save (the Camera2 migration had left the
cycle with no caller, so stills saved sensor-native).

QR is back where it was pre-removal: ambient scanning
inside Photo mode through QrBarcodeScanner over the
analysis stream (no QR mode, shutter stays live, results
in the existing non-modal cards).

Verified: 525 camera tests, compile (dev+release),
lintVitalRelease, assembleRelease all green. Phone
install pending the adb tunnel returning.

Diff

camera/src/main/java/com/vayunmathur/camera/domain/AspectCrop.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/AspectCrop.kt b/camera/src/main/java/com/vayunmathur/camera/domain/AspectCrop.ktnew file mode 100644index 0000000000..245501c658--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/domain/AspectCrop.kt@@ -0,0 +1,70 @@+package com.vayunmathur.camera.domain++/**+ * Pure centre-crop geometry for the still aspect-ratio setting.+ *+ * The user-facing ratio ([com.vayunmathur.camera.platform.AspectRatioOption])+ * is expressed in display orientation (portrait on this portrait-locked+ * app: 3:4, 9:16, ...), while captured still pixels arrive in sensor+ * orientation with a quarter-turn relative rotation on phone sensors.+ * A centre crop is symmetric, so the sensor-space crop rectangle does+ * not depend on the rotation *direction*: its width follows the display+ * height axis when the axes are swapped (90/270) and the display width+ * axis otherwise. Cropping anywhere else (or not at all, as the first+ * Camera2 save path did — `currentCropAspectRatio` had no caller) makes+ * the saved still wider than the viewfinder box the user framed.+ */+object AspectCrop {++    /** A pixel rectangle inside a frame. */+    data class Rect(val left: Int, val top: Int, val width: Int, val height: Int) {+        val right: Int get() = left + width+        val bottom: Int get() = top + height++        fun isFullFrame(frameWidth: Int, frameHeight: Int): Boolean =+            left == 0 && top == 0 && width == frameWidth && height == frameHeight+    }++    /**+     * Largest centred rectangle inside a [frameWidth]x[frameHeight]+     * sensor frame whose *displayed* aspect is [displayRatioWidth] /+     * [displayRatioHeight] after a [rotationDegrees] quarter turn, or+     * null for degenerate input. When the frame already displays at the+     * target ratio the rectangle is the full frame.+     */+    fun centerCropRect(+        frameWidth: Int,+        frameHeight: Int,+        rotationDegrees: Int,+        displayRatioWidth: Int,+        displayRatioHeight: Int,+    ): Rect? {+        if (frameWidth <= 0 || frameHeight <= 0) return null+        if (displayRatioWidth <= 0 || displayRatioHeight <= 0) return null+        val swapped = ((rotationDegrees % 360) + 360) % 360 == 90 ||+            ((rotationDegrees % 360) + 360) % 360 == 270+        val displayWidth = if (swapped) frameHeight else frameWidth+        val displayHeight = if (swapped) frameWidth else frameHeight+        // Largest display-space crop at the target ratio.+        val target = displayRatioWidth.toFloat() / displayRatioHeight.toFloat()+        val displayAspect = displayWidth.toFloat() / displayHeight.toFloat()+        val cropDisplayWidth: Int+        val cropDisplayHeight: Int+        if (displayAspect > target) {+            cropDisplayHeight = displayHeight+            cropDisplayWidth = (displayHeight * target).toInt().coerceAtLeast(1)+        } else {+            cropDisplayWidth = displayWidth+            cropDisplayHeight = (displayWidth / target).toInt().coerceAtLeast(1)+        }+        // Map back to sensor axes (centre crop: direction-independent).+        val cropWidth = if (swapped) cropDisplayHeight else cropDisplayWidth+        val cropHeight = if (swapped) cropDisplayWidth else cropDisplayHeight+        return Rect(+            left = (frameWidth - cropWidth) / 2,+            top = (frameHeight - cropHeight) / 2,+            width = cropWidth.coerceAtMost(frameWidth),+            height = cropHeight.coerceAtMost(frameHeight),+        )+    }+}
camera/src/main/java/com/vayunmathur/camera/domain/PreviewTransform.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/PreviewTransform.kt b/camera/src/main/java/com/vayunmathur/camera/domain/PreviewTransform.ktindex 3b1712f0f2..aed1e217d3 100644--- a/camera/src/main/java/com/vayunmathur/camera/domain/PreviewTransform.kt+++ b/camera/src/main/java/com/vayunmathur/camera/domain/PreviewTransform.kt@@ -16,15 +16,37 @@ import kotlin.math.max  *   its promised ratio via `previewRatioForWindow`, this transform only  *   decides how the stream fills it).  *- * The buffer must be rotated by the relative rotation- * ([AnalysisRotation.rotationDegrees]: sensor vs display, front lenses add)- * to sit upright, then uniformly scaled by- * `max(viewW / displayedW, viewH / displayedH)` and centred. Uniform scale- * is the whole point: the old path set no TextureView transform at all, so- * the view stretched the buffer non-uniformly whenever the stream aspect- * (e.g. a 4:3 sensor frame capped to 1440x1080, displayed as 3:4) differed- * from the box aspect (e.g. a 9:16 still-crop box). Any non-uniform- * fallback is stretch, never a valid preview.+ * Two different transforms live here, in two different spaces:+ *+ * - [compute]: the *geometry* of the upright image — the buffer rotated+ *   by the relative rotation ([AnalysisRotation.rotationDegrees]:+ *   sensor vs display, front lenses add) has [displayedWidth] x+ *   [displayedHeight] (aspect swapped for 90/270), and fills the view at+ *   the uniform scale `max(viewW / displayedW, viewH / displayedH)`,+ *   centred. This describes where image content sits; it is NOT a+ *   TextureView matrix.+ * - [computeTextureAffine]: the matrix `TextureView.setTransform`+ *   actually consumes. TextureView is a sampling surface: it renders+ *   the SurfaceTexture through the texture transform the camera+ *   framework already attached to the stream (which is where the+ *   sensor rotation — and the buffer's quarter-turn — is applied; it+ *   is why the pre-transform preview was *stretched*, never sideways),+ *   composed with the app-supplied matrix expressed against the+ *   *displayed* (post-rotation) frame, exactly as the platform Camera2+ *   sample builds its matrix against a swapped buffer rect. The app+ *   matrix must therefore contain NO rotation of its own: any quarter+ *   turn here rotates an already-upright image. The 7c4429d74 wiring+ *   fed [compute]'s rotated placement affine straight to+ *   `setTransform`, double-applying the rotation — back sensor 90 and+ *   front sensor 270 both rendered a quarter-turn from the (correct,+ *   EXIF-rotated) captured still. The texture affine is instead the+ *   inverse uniform scale over the displayed frame, centred.+ *+ * Uniform scale is the other invariant: with no app transform at all+ * the view stretches the buffer non-uniformly whenever the stream+ * aspect (e.g. a 4:3 sensor frame, displayed as 3:4) differs from the+ * box aspect (e.g. a 9:16 still-crop box). Any non-uniform fallback is+ * stretch, never a valid preview.  */ object PreviewTransform { @@ -60,6 +82,7 @@ object PreviewTransform {         /** Row-major 3x3 values for `android.graphics.Matrix.setValues`. */         fun toMatrixValues(): FloatArray =             floatArrayOf(a, b, tx, c, d, ty, 0f, 0f, 1f)+     }      /**@@ -116,6 +139,48 @@ object PreviewTransform {         )     } +    /**+     * The `TextureView.setTransform` matrix for one stream/view pairing,+     * as an [Affine] mapping *view* pixels to *displayed-texture* pixels+     * (so [Affine.map] converts view coordinates to texture coordinates).+     *+     * The linear part is the pure inverse fill scale — deliberately no+     * rotation (see the class doc: the stream's own texture transform+     * already applied the relative rotation, so the relative rotation+     * only decides the displayed size the scale is computed from, via+     * [compute]). [Affine.rotationDegrees] is therefore always 0 and+     * [Affine.scale] is `1 / fillScale`; the translation centres the+     * sampled region, which is exactly the centre crop the placement+     * geometry promises. Null for degenerate sizes, like [compute].+     */+    fun computeTextureAffine(+        streamWidth: Int,+        streamHeight: Int,+        viewWidth: Int,+        viewHeight: Int,+        sensorOrientationDegrees: Int,+        displayRotationDegrees: Int,+        facing: LensFacing?,+    ): Affine? {+        val placement = compute(+            streamWidth, streamHeight, viewWidth, viewHeight,+            sensorOrientationDegrees, displayRotationDegrees, facing,+        ) ?: return null+        if (placement.scale == 0f) return null+        val inverse = 1f / placement.scale+        val displayedWidth = placement.displayedWidth+        val displayedHeight = placement.displayedHeight+        return Affine(+            a = inverse, b = 0f, c = 0f, d = inverse,+            tx = displayedWidth / 2f - viewWidth / 2f * inverse,+            ty = displayedHeight / 2f - viewHeight / 2f * inverse,+            rotationDegrees = 0,+            scale = inverse,+            displayedWidth = displayedWidth,+            displayedHeight = displayedHeight,+        )+    }+     /** True when [affine] scales both axes equally (no stretch), within [tolerance]. */     fun isUniformScale(affine: Affine, tolerance: Float = 0.001f): Boolean {         val colX = kotlin.math.sqrt(affine.a * affine.a + affine.c * affine.c)
camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.ktindex f6c745da09..7db1549c81 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt@@ -148,6 +148,53 @@ internal fun CameraViewModel.requestedStillFormat(): StillFormat =  * JPEG-selected shots keep the stamped-JPEG landing untouched.  */ internal fun CameraViewModel.saveCamera2Still(still: CapturedStill): Uri? {+    // Aspect-ratio crop: the selected ratio must shape the saved still+    // exactly as it shapes the preview box. A crop that actually cuts+    // pixels decodes the frame, centre-crops it in sensor space (see+    // AspectCrop) and lands through the processed encoder; a full-frame+    // selection keeps the byte-preserving routes below untouched. An+    // Ultra HDR (JPEG_R) still that needs cropping trades its gain map+    // for the crop, the same trade processed (bokeh/colour) stills make.+    val needsCrop = run {+        if (cameraModeMutable.value != CameraMode.PHOTO &&+            cameraModeMutable.value != CameraMode.PORTRAIT+        ) {+            false+        } else {+            val ratio = currentCropAspectRatio()+            val rect = com.vayunmathur.camera.domain.AspectCrop.centerCropRect(+                still.jpegWidth, still.jpegHeight,+                still.metadata.rotationDegrees, ratio.numerator, ratio.denominator,+            )+            rect != null && !rect.isFullFrame(still.jpegWidth, still.jpegHeight)+        }+    }+    val decoded = if (needsCrop) {+        BitmapFactory.decodeByteArray(still.jpegBytes, 0, still.jpegBytes.size)+    } else {+        null+    }+    if (decoded != null) {+        val cropped = cropBitmapToSelectedAspect(decoded, still.metadata.rotationDegrees)+        if (cropped !== decoded) {+            try {+                val saved = saveProcessedStill(+                    cropped, still.metadata.rotationDegrees, still.jpegBytes,+                ) ?: return null+                if (saved.format == com.vayunmathur.camera.domain.StillFormat.JPEG) {+                    writeCaptureExif(+                        saved.uri, still.jpegBytes,+                        still.metadata.rotationDegrees, mirrored = still.metadata.mirrored,+                    )+                }+                return saved.uri+            } finally {+                cropped.recycle()+                decoded.recycle()+            }+        }+        decoded.recycle()+    }     val ultraHdrSource = still.tag == StillOutputTag.ULTRA_HDR_JPEG_R ||         StillFormatRouting.isUltraHdrJpeg(still.jpegBytes)     return when (StillFormatRouting.stillSaveRoute(requestedStillFormat(), ultraHdrSource)) {
camera/src/main/java/com/vayunmathur/camera/platform/CameraCaptureProcessing.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraCaptureProcessing.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraCaptureProcessing.ktindex 0e9e37cb79..12b3085f07 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraCaptureProcessing.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraCaptureProcessing.kt@@ -33,6 +33,33 @@ internal fun CameraViewModel.cropToRect(src: Bitmap, rect: Rect): Bitmap {     return Bitmap.createBitmap(src, left, top, w, h).also { if (it != src) src.recycle() } } +/**+ * Centre-crops [src] (sensor-oriented pixels) to the user's selected+ * still aspect ratio, as displayed after [rotationDegrees]. Returns+ * [src] itself when the mode has no still crop (video/pano families —+ * the preview box does not promise them a ratio either) or the frame+ * already matches. The caller owns recycling: a returned new bitmap+ * must be recycled after saving, [src] must not be recycled here.+ * This is the capture half of the aspect setting: the preview box+ * (`CameraScreenState.previewAspectRatio`) is the framing half, and+ * until this wiring the Camera2 save path ignored the selection+ * entirely (`currentCropAspectRatio` had no caller after the CameraX+ * removal, so every still saved at the sensor's native ratio).+ */+internal fun CameraViewModel.cropBitmapToSelectedAspect(src: Bitmap, rotationDegrees: Int): Bitmap {+    if (cameraModeMutable.value != CameraMode.PHOTO &&+        cameraModeMutable.value != CameraMode.PORTRAIT+    ) {+        return src+    }+    val ratio = currentCropAspectRatio()+    val rect = com.vayunmathur.camera.domain.AspectCrop.centerCropRect(+        src.width, src.height, rotationDegrees, ratio.numerator, ratio.denominator,+    ) ?: return src+    if (rect.isFullFrame(src.width, src.height)) return src+    return Bitmap.createBitmap(src, rect.left, rect.top, rect.width, rect.height)+}+ /** True when the crop covers the whole frame or is empty. */ private fun isFullFrame(src: Bitmap, left: Int, top: Int, w: Int, h: Int): Boolean {     if (w <= 0 || h <= 0) return true
camera/src/main/java/com/vayunmathur/camera/platform/CameraSingleCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraSingleCapture.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraSingleCapture.ktindex 6ea59ed11d..e8bbad05d8 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraSingleCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraSingleCapture.kt@@ -173,7 +173,10 @@ private fun CameraViewModel.processSingleFrame(         stillBokeh.render(decoded, degrees, plan.strength, plan.warmth, plan.shadows, plan.mirror)     } else null)         ?: applyColorAdjustments(decoded, plan.warmth, plan.shadows, plan.mirror)-    val saved = saveProcessedStill(adjusted, degrees, sourceJpeg)+    // Aspect crop in sensor space, matching the preview box framing.+    val cropped = cropBitmapToSelectedAspect(adjusted, degrees)+    val saved = saveProcessedStill(cropped, degrees, sourceJpeg)+    if (cropped !== adjusted) cropped.recycle()     adjusted.recycle()     if (saved == null) return null     if (saved.format == com.vayunmathur.camera.domain.StillFormat.JPEG) {
camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.ktindex 7f1d4ab760..74bd74b1a3 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.kt@@ -8,8 +8,14 @@ import androidx.lifecycle.LifecycleRegistry import com.vayunmathur.camera.R import kotlin.math.roundToInt -/** Capture modes selectable in the camera UI. */-enum class CameraMode { PHOTO, PORTRAIT, PANORAMA, PHOTOSPHERE, QR, VIDEO, SLOW_MO, TIMELAPSE, CINEMATIC }+/**+ * Capture modes selectable in the camera UI. There is deliberately no+ * QR mode: QR/barcode decoding runs inside PHOTO on the analysis+ * stream (stock-camera style, and the pre-Camera2-removal CameraX+ * behaviour — the old app never had a QR mode either), surfacing the+ * shared result chip without blocking the shutter.+ */+enum class CameraMode { PHOTO, PORTRAIT, PANORAMA, PHOTOSPHERE, VIDEO, SLOW_MO, TIMELAPSE, CINEMATIC } /** Flash behaviour for still capture. */ enum class FlashMode { ON, OFF, AUTO } 
camera/src/main/java/com/vayunmathur/camera/platform/PhotoAnalyzer.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/PhotoAnalyzer.kt b/camera/src/main/java/com/vayunmathur/camera/platform/PhotoAnalyzer.ktindex 57bd843418..7d0babe212 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/PhotoAnalyzer.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/PhotoAnalyzer.kt@@ -45,7 +45,15 @@ internal const val MOTION_FRAME_INTERVAL_MS = 125L class PhotoAnalyzer(     private val onLuminance: (Float) -> Unit,     private val onQrDetected: (String) -> Unit,-    private val onMotionFrame: ((Bitmap, Long, Int) -> Unit)? = null+    private val onMotionFrame: ((Bitmap, Long, Int) -> Unit)? = null,+    /**+     * Whether this analyzer runs its own QR-only ZXing decode. In PHOTO+     * the [QrBarcodeScanner] core owns decoding (QR + barcode formats,+     * throttled on the same analysis executor), so the caller feeds it+     * the same frames and sets this false — one decode pass per frame+     * slot, never two binarizations of the same luma.+     */+    private val decodeQr: Boolean = true, ) {     private val reader = MultiFormatReader().apply {         // Restrict to 2D codes only. Without this, ZXing's default MultiFormatReader@@ -95,7 +103,7 @@ class PhotoAnalyzer(                 Log.error("PhotoAnalyzer", "toBitmapFromPlanes threw", e)             }         }-        if (nowMs - lastDecodeAtMs >= QR_DECODE_INTERVAL_MS) {+        if (decodeQr && nowMs - lastDecodeAtMs >= QR_DECODE_INTERVAL_MS) {             lastDecodeAtMs = nowMs             val bytes = copyYPlaneTight(frame.yPlane, frame.width, frame.height)             if (bytes != null) {
camera/src/main/java/com/vayunmathur/camera/platform/QrBarcodeScanner.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/QrBarcodeScanner.kt b/camera/src/main/java/com/vayunmathur/camera/platform/QrBarcodeScanner.ktindex 6b336e1e0b..05ff1687e1 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/QrBarcodeScanner.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/QrBarcodeScanner.kt@@ -22,12 +22,12 @@ import com.vayunmathur.library.log.Log internal const val QR_SCAN_INTERVAL_MS = 250L  /**- * Formats the dedicated QR/barcode mode decodes: the 2D family the old- * ambient scanner covered (QR above all) plus the common 1D symbologies.- * The ambient PHOTO-mode analyzer ([PhotoAnalyzer]) stays QR-only on- * purpose: in a viewfinder that is mostly landscape/scenery, 1D readers- * fire on horizontal scene edges. Here the user has explicitly entered a- * scanning mode and is pointing at a code, so the wider set is honest.+ * Formats decoded live in PHOTO mode (there is no separate QR mode):+ * the 2D family the old ambient scanner covered (QR above all) plus+ * the common 1D symbologies, stock-camera style. [PhotoAnalyzer]'s own+ * decode stays QR-only and is disabled where this scanner is fed, so+ * each frame is binarized once; the 250 ms throttle bounds the cost of+ * the wider set on the analysis executor.  */ internal val QR_BARCODE_FORMATS: List<BarcodeFormat> = listOf(     BarcodeFormat.QR_CODE,@@ -46,8 +46,8 @@ internal val QR_BARCODE_FORMATS: List<BarcodeFormat> = listOf( )  /**- * QR/barcode scanner for the dedicated [CameraMode.QR] mode, fed from the- * Camera2 analysis stream ([AnalysisFrame]).+ * QR/barcode scanner running inside PHOTO mode, fed from the Camera2+ * analysis stream ([AnalysisFrame]).  *  * Decode path, cheapest first:  * 1. The Y (luma) plane straight into ZXing's [PlanarYUVLuminanceSource]
camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewSurfaceBridge.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewSurfaceBridge.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewSurfaceBridge.ktindex 2699950eff..9f1d549a75 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewSurfaceBridge.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewSurfaceBridge.kt@@ -124,12 +124,28 @@ class PreviewSurfaceBridge(             facing = lensFacing,         ) ?: return         lastTransform = affine-        target.setTransform(Matrix().apply { setValues(affine.toMatrixValues()) })+        // TextureView.setTransform matrix: NO rotation (the stream's own+        // texture transform already applied the sensor quarter-turn —+        // feeding the placement affine's rotation here double-applied+        // it and the preview rendered rotated vs the captured still).+        // The texture affine is the inverse uniform fill scale over the+        // displayed frame. See PreviewTransform.computeTextureAffine.+        val textureAffine = PreviewTransform.computeTextureAffine(+            streamWidth = stream.width,+            streamHeight = stream.height,+            viewWidth = target.width,+            viewHeight = target.height,+            sensorOrientationDegrees = sensorOrientationDegrees,+            displayRotationDegrees = displayRotationDegrees,+            facing = lensFacing,+        ) ?: return+        target.setTransform(Matrix().apply { setValues(textureAffine.toMatrixValues()) })         com.vayunmathur.library.log.Log.status(             "Camera2Preview",             "preview geometry view=${target.width}x${target.height} " +                 "stream=${stream.width}x${stream.height} sensor=$sensorOrientationDegrees " +                 "display=$displayRotationDegrees rel=${affine.rotationDegrees} " ++                "textureRel=${textureAffine.rotationDegrees} " +                 "displayed=${affine.displayedWidth}x${affine.displayedHeight} " +                 "scale=${affine.scale}",         )
camera/src/main/java/com/vayunmathur/camera/ui/CameraAspectRatioSettings.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraAspectRatioSettings.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraAspectRatioSettings.ktnew file mode 100644index 0000000000..3e2f82f2ec--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraAspectRatioSettings.kt@@ -0,0 +1,87 @@+package com.vayunmathur.camera.ui++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+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.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import com.vayunmathur.camera.R+import com.vayunmathur.camera.platform.AspectRatioOption+import com.vayunmathur.library.ui.DropdownMenu+import com.vayunmathur.library.ui.IconArrowDropDown+import com.vayunmathur.library.ui.IconCheck+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.SelectableDropdownMenuItem+import com.vayunmathur.library.ui.SettingsSection+import com.vayunmathur.library.ui.Text++/**+ * Photo aspect-ratio picker owned by [SettingsPage]: the explicit+ * choice list for the same selection the camera top bar cycles+ * (4:3 / 3:2 / 16:9 / 1:1 — the historical set; there was never a+ * "Full" entry, the sensor-native framing is the 4:3 choice on this+ * hardware). The selection drives both the preview box+ * (`previewAspectRatio` / `previewRatioForWindow`) and the saved+ * still's centre crop, so what the user frames is what lands.+ * Stateless: the caller passes the value plus the change callback,+ * following [CameraPhotoFormatSettings].+ */+@Composable+fun CameraAspectRatioSettings(+    aspectRatio: AspectRatioOption,+    onAspectRatioChange: (AspectRatioOption) -> Unit,+    modifier: Modifier = Modifier,+) {+    SettingsSection(title = stringResource(R.string.settings_aspect_ratio), modifier = modifier) {+        var expanded by remember { mutableStateOf(false) }+        Box(+            modifier = Modifier+                .fillMaxWidth()+                .padding(horizontal = 16.dp)+        ) {+            OutlinedButton(+                onClick = { expanded = true },+                modifier = Modifier.fillMaxWidth()+            ) {+                Text(+                    aspectRatio.label,+                    modifier = Modifier.weight(1f),+                    textAlign = TextAlign.Start,+                    maxLines = 1,+                    overflow = TextOverflow.Ellipsis,+                )+                IconArrowDropDown()+            }+            DropdownMenu(+                expanded = expanded,+                onDismissRequest = { expanded = false }+            ) {+                // Historical cycle order (4:3 -> 3:2 -> 16:9 -> 1:1).+                listOf(+                    AspectRatioOption.RATIO_4_3,+                    AspectRatioOption.RATIO_3_2,+                    AspectRatioOption.RATIO_16_9,+                    AspectRatioOption.RATIO_1_1,+                ).forEach { option ->+                    SelectableDropdownMenuItem(+                        selected = option == aspectRatio,+                        onClick = {+                            onAspectRatioChange(option)+                            expanded = false+                        },+                        text = { Text(option.label) },+                        selectedLeadingIcon = { IconCheck() },+                    )+                }+            }+        }+    }+}
camera/src/main/java/com/vayunmathur/camera/ui/CameraBottomControls.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraBottomControls.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraBottomControls.ktindex 42fa8072a3..05902cee74 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraBottomControls.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraBottomControls.kt@@ -120,9 +120,7 @@ internal fun CameraBottomControls(         modes = {             CameraModesPane(                 cameraMode = cameraMode,-                // QR lives on the photo side of the picker (its row and the-                // photo icon's selected state), though it captures nothing.-                isPhotoType = state.isPhotoType || state.isQr,+                isPhotoType = state.isPhotoType,                 sloMoSupported = state.sloMoSupported,                 captureForResult = onCaptureResult != null,                 onModeSelected = onModeSelected,
camera/src/main/java/com/vayunmathur/camera/ui/CameraModeBars.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraModeBars.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraModeBars.ktindex f89f88a328..3147b24b94 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraModeBars.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraModeBars.kt@@ -51,7 +51,6 @@ internal fun ModeSelector(             else photoModes + listOf(                 CameraMode.PANORAMA to stringResource(R.string.mode_panorama),                 CameraMode.PHOTOSPHERE to stringResource(R.string.mode_photosphere),-                CameraMode.QR to stringResource(R.string.mode_qr),             )         } else {             // Only include Slo-Mo when the device's back camera actually supports true HFR.
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 1e54518eb1..04740efde6 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt@@ -188,7 +188,6 @@ internal fun BoxWithConstraintsScope.CameraPreviewBox(         gridEnabled = state.gridEnabled,         levelEnabled = state.levelEnabled,         isPhotoType = state.isPhotoType,-        isQr = state.isQr,         roll = state.roll,         modifier = previewSize,         timerCountdown = state.timerCountdown,
camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewOverlays.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewOverlays.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewOverlays.ktindex 1f558090cd..dd5c1d5985 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewOverlays.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewOverlays.kt@@ -31,7 +31,6 @@ internal fun BoxScope.CameraPreviewOverlays(     gridEnabled: Boolean,     levelEnabled: Boolean,     isPhotoType: Boolean,-    isQr: Boolean = false,     roll: Float,     modifier: Modifier,     timerCountdown: Int,@@ -104,7 +103,7 @@ internal fun BoxScope.CameraPreviewOverlays(     // Some vendor NIGHT extensions can't host a concurrent ImageAnalysis stream, so     // the session binds without one and QR codes stop being read. Say so rather than     // letting the scanner look broken.-    if ((isPhotoType || isQr) && photoSessionActive && !analysisStreamActive) {+    if (isPhotoType && photoSessionActive && !analysisStreamActive) {         Text(             text = stringResource(R.string.qr_scanning_paused),             color = Color.White,
camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.ktindex 7da19dec2c..d10757db3b 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt@@ -68,10 +68,6 @@ fun CameraScreen(             state.cameraMode == CameraMode.PANORAMA -> {                 if (state.panoSweeping) viewModel.stopPanorama() else viewModel.startPanorama()             }-            state.isQr -> {-                // Scanning is automatic on the analysis stream; the shutter-                // (and the volume keys routed through it) captures nothing.-            }             state.isSloMo -> viewModel.toggleHighSpeedRecording()             state.isPhotoType -> {                 if (onCaptureResult != null) {
camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.ktindex b71a5e2737..0acdd40b80 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt@@ -142,19 +142,6 @@ internal fun CameraScreenEffects(             cameraMode == CameraMode.PORTRAIT -> {                 // Bokeh sink lifecycle (create/close) managed by DisposableEffect below.             }-            cameraMode == CameraMode.QR -> {-                state.maskBitmap = null-                // Dedicated scanner: QR + common barcodes off the Camera2-                // analysis stream. Runs on the analysis executor (the-                // stream's dispatcher), never the capture thread. Result-                // handling is the shared qrResult flow, so the generic-                // open-URL/copy card and the FIDO/eSIM/Wi-Fi action cards-                // render exactly as they did for the ambient scanner.-                val scanner = com.vayunmathur.camera.platform.QrBarcodeScanner { text, _ ->-                    viewModel.setQrResult(text)-                }-                viewModel.setAnalysisSink(scanner::onAnalysisFrame)-            }             cameraMode == CameraMode.PANORAMA || cameraMode == CameraMode.PHOTOSPHERE -> {                 state.maskBitmap = null                 // Converted bitmaps off the Camera2 analysis stream;@@ -175,6 +162,20 @@ internal fun CameraScreenEffects(             }             state.isPhotoType -> {                 state.maskBitmap = null+                // QR/barcode scanning lives inside PHOTO (stock-camera+                // style; also the pre-Camera2-removal CameraX behaviour):+                // the QrBarcodeScanner core decodes off the same Camera2+                // analysis stream, throttled on the analysis executor —+                // never the capture thread, never blocking the shutter.+                // A hit lands in the shared qrResult flow, so the+                // non-modal open/copy chip and the FIDO/eSIM/Wi-Fi action+                // cards render exactly as before, dismissible, above the+                // shutter row. PhotoAnalyzer keeps luma (night detection)+                // and Motion-Photo copies; its own QR decode is off here+                // so each frame is binarized once.+                val scanner = com.vayunmathur.camera.platform.QrBarcodeScanner { text, _ ->+                    viewModel.setQrResult(text)+                }                 val analyzer = PhotoAnalyzer(                     onLuminance = { viewModel.onLuminance(it) },                     onQrDetected = { viewModel.setQrResult(it) },@@ -182,8 +183,17 @@ internal fun CameraScreenEffects(                     onMotionFrame = if (cameraMode == CameraMode.PHOTO) {                         { bmp, ts, rot -> viewModel.addMotionFrame(bmp, ts, rot) }                     } else null,+                    decodeQr = false,                 )-                viewModel.setAnalysisSink(analyzer::onAnalysisFrame)+                viewModel.setAnalysisSink { frame ->+                    analyzer.onAnalysisFrame(frame)+                    // Scanner only in plain PHOTO: PORTRAIT/PANORAMA keep+                    // their capture-first framing (and PANORAMA installs+                    // its own sink above), matching the old ambient scope.+                    if (cameraMode == CameraMode.PHOTO) {+                        scanner.onAnalysisFrame(frame)+                    }+                }             }             else -> {                 state.maskBitmap = null
camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.ktindex 9bed9828de..42315c9c41 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt@@ -102,7 +102,6 @@ import com.vayunmathur.camera.platform.VideoCodec     var deviceRotation by deviceRotationState      val isPhotoType get() = cameraMode in listOf(CameraMode.PHOTO, CameraMode.PORTRAIT, CameraMode.PANORAMA, CameraMode.PHOTOSPHERE)-    val isQr get() = cameraMode == CameraMode.QR     val isSloMo get() = cameraMode == CameraMode.SLOW_MO     val isVideoType get() = cameraMode == CameraMode.VIDEO || cameraMode == CameraMode.TIMELAPSE || cameraMode == CameraMode.CINEMATIC     val isPanoType get() = cameraMode == CameraMode.PANORAMA || cameraMode == CameraMode.PHOTOSPHERE
camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt b/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.ktindex d1b3d2f205..4532932f35 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt@@ -44,6 +44,7 @@ import com.vayunmathur.camera.data.setMotionPhotoDuration import com.vayunmathur.camera.data.setMotionPhotoEnabled import com.vayunmathur.camera.data.setNoiseReductionEnabled import com.vayunmathur.camera.data.setSaveTreeUri+import com.vayunmathur.camera.data.setAspectRatio import com.vayunmathur.camera.data.setPhotoFormat import com.vayunmathur.camera.data.setVideoCodec import com.vayunmathur.camera.data.updateLocation@@ -58,6 +59,7 @@ import com.vayunmathur.library.util.NavKey @Composable fun <T : NavKey> SettingsPage(backStack: NavBackStack<T>, viewModel: CameraViewModel) {     val locationEnabled by viewModel.locationEnabled.collectAsState()+    val aspectRatio by viewModel.aspectRatio.collectAsState()     val videoCodec by viewModel.videoCodec.collectAsState()     val photoFormat by viewModel.photoFormat.collectAsState()     val audioInputDevice by viewModel.audioInputDevice.collectAsState()@@ -182,6 +184,11 @@ fun <T : NavKey> SettingsPage(backStack: NavBackStack<T>, viewModel: CameraViewM                 )             } +            CameraAspectRatioSettings(+                aspectRatio = aspectRatio,+                onAspectRatioChange = { viewModel.setAspectRatio(it); noteIfDeferred() },+            )+             CameraPhotoFormatSettings(                 photoFormat = photoFormat,                 onPhotoFormatChange = { viewModel.setPhotoFormat(it); noteIfDeferred() },
camera/src/test/java/com/vayunmathur/camera/domain/AspectCropTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/AspectCropTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/AspectCropTest.ktnew file mode 100644index 0000000000..cdda9f2362--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/domain/AspectCropTest.kt@@ -0,0 +1,71 @@+package com.vayunmathur.camera.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Still aspect-ratio centre crop: the saved frame must match the+ * preview box for every historical option (4:3, 3:2, 16:9, 1:1) on+ * both phone sensor orientations, in sensor-pixel coordinates.+ */+class AspectCropTest {++    private fun crop(+        w: Int, h: Int, rotation: Int, ratioW: Int, ratioH: Int,+    ) = AspectCrop.centerCropRect(w, h, rotation, ratioW, ratioH)++    @Test fun nativeFourThreeIsFullFrame() {+        // 4080x3060 sensor, quarter-turned: displays 3060x4080 = 3:4.+        val rect = assertNotNull(crop(4080, 3060, 90, 3, 4))+        assertTrue(rect.isFullFrame(4080, 3060))+    }++    @Test fun sixteenNineCropsSensorLongAxis() {+        // Displayed target 9:16 (ratioW=9, ratioH=16 in portrait terms).+        val rect = assertNotNull(crop(4080, 3060, 90, 9, 16))+        // Display crop 2295x4080 -> sensor crop 4080x2295, centred.+        assertEquals(4080, rect.width)+        assertEquals(2295, rect.height)+        assertEquals(0, rect.left)+        assertEquals((3060 - 2295) / 2, rect.top)+    }++    @Test fun squareCropsToDisplayedSquare() {+        val rect = assertNotNull(crop(4080, 3060, 90, 1, 1))+        // Displayed 3060x4080 -> 3060x3060 square -> sensor 3060x3060.+        assertEquals(3060, rect.width)+        assertEquals(3060, rect.height)+        assertEquals((4080 - 3060) / 2, rect.left)+        assertEquals(0, rect.top)+    }++    @Test fun frontSensor270CropsLikeBack90() {+        // Centre crop is direction-independent: 270 swaps axes like 90.+        val back = assertNotNull(crop(4080, 3060, 90, 2, 3))+        val front = assertNotNull(crop(4080, 3060, 270, 2, 3))+        assertEquals(back, front)+    }++    @Test fun noRotationUsesDisplayAxesDirectly() {+        val rect = assertNotNull(crop(1920, 1080, 0, 1, 1))+        assertEquals(1080, rect.width)+        assertEquals(1080, rect.height)+        assertEquals((1920 - 1080) / 2, rect.left)+        assertEquals(0, rect.top)+    }++    @Test fun threeTwoBetweenFourThreeAndSixteenNine() {+        val rect = assertNotNull(crop(4080, 3060, 90, 2, 3))+        // Displayed 3060x4080 at 2:3 -> 2720x4080 -> sensor 4080x2720.+        assertEquals(4080, rect.width)+        assertEquals(2720, rect.height)+    }++    @Test fun degenerateInputHasNoCrop() {+        assertNull(crop(0, 3060, 90, 3, 4))+        assertNull(crop(4080, 3060, 90, 0, 4))+    }+}
camera/src/test/java/com/vayunmathur/camera/domain/PreviewTransformTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/PreviewTransformTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/PreviewTransformTest.ktindex 694d208fb5..1ab496917b 100644--- a/camera/src/test/java/com/vayunmathur/camera/domain/PreviewTransformTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/domain/PreviewTransformTest.kt@@ -118,4 +118,79 @@ class PreviewTransformTest {         assertNull(compute(1440, 1080, 0, 1440))         assertNull(compute(1440, 1080, 1080, 0))     }++    // --- TextureView sampling form (the applied transform) -------------+    // The stream's own texture transform already applied the sensor+    // quarter-turn (that is why the pre-transform preview was stretched,+    // never sideways), so the applied matrix must carry NO rotation:+    // any quarter-turn here double-applies it and the preview renders+    // rotated vs the captured still (the owner-reported defect after+    // 7c4429d74 fed the rotated placement affine to setTransform).+    // Breadcrumbs on komodo read rel=90 back / rel=270 front; both must+    // yield the same unrotated, centred, uniform inverse-scale sampling+    // over the displayed (1200x1600) frame.++    private fun texture(+        streamW: Int, streamH: Int, viewW: Int, viewH: Int,+        sensor: Int = 90, display: Int = 0, facing: LensFacing? = LensFacing.BACK,+    ) = PreviewTransform.computeTextureAffine(streamW, streamH, viewW, viewH, sensor, display, facing)++    @Test fun textureFormHasNoRotationForBackLens() {+        val placement = assertNotNull(compute(1600, 1200, 1344, 1792, sensor = 90))+        assertEquals(90, placement.rotationDegrees)+        assertEquals(1.12f, placement.scale, 0.001f)+        val texture = assertNotNull(texture(1600, 1200, 1344, 1792, sensor = 90))+        assertEquals(0, texture.rotationDegrees)+        assertEquals(0f, texture.b, 0.001f)+        assertEquals(0f, texture.c, 0.001f)+        assertEquals(1f / 1.12f, texture.a, 0.001f)+        assertEquals(1f / 1.12f, texture.d, 0.001f)+        assertTrue(PreviewTransform.isUniformScale(texture))+        assertEquals(1200f, texture.displayedWidth, 0.001f)+        assertEquals(1600f, texture.displayedHeight, 0.001f)+        // Exact fill: view corners sample the displayed-frame corners,+        // view centre samples its centre (no crop in this pairing).+        assertEquals(0f to 0f, texture.map(0f, 0f))+        val (x1, y1) = texture.map(1344f, 1792f)+        assertEquals(1200f, x1, 0.01f)+        assertEquals(1600f, y1, 0.01f)+        val (cx, cy) = texture.map(672f, 896f)+        assertEquals(600f, cx, 0.01f)+        assertEquals(800f, cy, 0.01f)+    }++    @Test fun textureFormHasNoRotationForFrontLensEither() {+        // Front sensor 270: the relative rotation differs, the applied+        // matrix must not — the stream texture already turned the frame.+        val texture = assertNotNull(+            texture(1600, 1200, 1344, 1792, sensor = 270, facing = LensFacing.FRONT),+        )+        assertEquals(0, texture.rotationDegrees)+        val back = assertNotNull(texture(1600, 1200, 1344, 1792, sensor = 90))+        assertEquals(back.toMatrixValues().toList(), texture.toMatrixValues().toList())+    }++    @Test fun textureFormCentreCropsTheSampledRegion() {+        // 1440x1080 stream (displayed 1080x1440) into a 9:16 box: fill+        // scale 4/3, so the sampled width is 1080 * (1080/1920 inverse)...+        // precisely: sampled region is centred, width 1080/ (4/3) * ...+        val texture = assertNotNull(texture(1440, 1080, 1080, 1920))+        assertEquals(0, texture.rotationDegrees)+        assertTrue(PreviewTransform.isUniformScale(texture))+        val (cx, cy) = texture.map(540f, 960f)+        assertEquals(540f, cx, 0.01f)+        assertEquals(720f, cy, 0.01f)+        // Sampled region is narrower than the displayed frame (crop):+        // view left edge samples right of the texture left edge.+        val (left, _) = texture.map(0f, 0f)+        assertTrue(left > 0f)+        val (right, _) = texture.map(1080f, 0f)+        assertTrue(right < 1080f)+        assertEquals(1080f, left + right, 0.01f) // symmetric crop+    }++    @Test fun textureFormDegenerateSizesHaveNoTransform() {+        assertNull(texture(0, 1080, 1080, 1440))+        assertNull(texture(1440, 1080, 0, 1440))+    } }
camera/src/test/java/com/vayunmathur/camera/platform/Camera2AvifRoutingTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/Camera2AvifRoutingTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/Camera2AvifRoutingTest.ktindex 8badaf71a6..fa3fbb3fd6 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/Camera2AvifRoutingTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/Camera2AvifRoutingTest.kt@@ -78,9 +78,12 @@ class Camera2AvifRoutingTest {         tag: StillOutputTag = StillOutputTag.JPEG,     ) = CapturedStill(         jpegBytes = bytes,+        // A native phone still: sensor-landscape 4:3 frame, quarter-turn+        // rotation, so it displays at the default 3:4 portrait ratio and+        // the aspect crop is a no-op (full frame) for these routing tests.         jpegWidth = 16,-        jpegHeight = 16,-        metadata = StillCaptureMetadata(rotationDegrees = 0, mirrored = false),+        jpegHeight = 12,+        metadata = StillCaptureMetadata(rotationDegrees = 90, mirrored = false),         tag = tag,     ) 
camera/src/test/java/com/vayunmathur/camera/platform/QrInPhotoViewModelTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/QrModeViewModelTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/QrInPhotoViewModelTest.ktsimilarity index 55%rename from camera/src/test/java/com/vayunmathur/camera/platform/QrModeViewModelTest.ktrename to camera/src/test/java/com/vayunmathur/camera/platform/QrInPhotoViewModelTest.ktindex 58d1842051..f4cd7f5405 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/QrModeViewModelTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/QrInPhotoViewModelTest.kt@@ -8,29 +8,23 @@ import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config -/** QR mode switching and result flow on the ViewModel. */+/** In-PHOTO QR result flow on the ViewModel (no QR mode to switch to). */ @RunWith(RobolectricTestRunner::class) @Config(sdk = [34])-class QrModeViewModelTest {+class QrInPhotoViewModelTest {      private fun vm() = CameraViewModel(ApplicationProvider.getApplicationContext())      @Test-    fun switchToQrModePublishesMode() {+    fun defaultModeIsPhotoAndResultFlowsThere() {         val viewModel = vm()-        viewModel.switchCameraMode(CameraMode.QR)-        assertEquals(CameraMode.QR, viewModel.cameraMode.value)-        viewModel.switchCameraMode(CameraMode.PHOTO)         assertEquals(CameraMode.PHOTO, viewModel.cameraMode.value)-    }--    @Test-    fun qrResultRoundTripsThroughSharedFlow() {-        val viewModel = vm()         assertNull(viewModel.qrResult.value)-        viewModel.setQrResult("https://example.com/from-qr-mode")-        assertEquals("https://example.com/from-qr-mode", viewModel.qrResult.value)+        viewModel.setQrResult("https://example.com/from-photo-mode")+        assertEquals("https://example.com/from-photo-mode", viewModel.qrResult.value)+        // Dismissing the chip never leaves PHOTO or blocks the shutter.         viewModel.setQrResult(null)         assertNull(viewModel.qrResult.value)+        assertEquals(CameraMode.PHOTO, viewModel.cameraMode.value)     } }
camera/src/test/java/com/vayunmathur/camera/ui/QrInPhotoRoutingTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/ui/QrInPhotoRoutingTest.kt b/camera/src/test/java/com/vayunmathur/camera/ui/QrInPhotoRoutingTest.ktnew file mode 100644index 0000000000..95f835da13--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/ui/QrInPhotoRoutingTest.kt@@ -0,0 +1,46 @@+package com.vayunmathur.camera.ui++import com.vayunmathur.camera.platform.CameraMode+import com.vayunmathur.camera.platform.camera2.PreviewEnginePolicy+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * QR-in-PHOTO routing (owner decision, replacing the short-lived QR+ * mode): there is no QR entry in the mode enum/row at all, PHOTO keeps+ * the Camera2 preview (which brings the analysis stream the scanner+ * feeds on), and the photo family keeps its capture behaviour — the+ * shutter in PHOTO always takes a photo, scanned code or not.+ */+class QrInPhotoRoutingTest {++    @Test+    fun noQrModeExists() {+        assertFalse(CameraMode.entries.any { it.name == "QR" })+        assertEquals(+            listOf(+                CameraMode.PHOTO, CameraMode.PORTRAIT, CameraMode.PANORAMA,+                CameraMode.PHOTOSPHERE, CameraMode.VIDEO, CameraMode.SLOW_MO,+                CameraMode.TIMELAPSE, CameraMode.CINEMATIC,+            ),+            CameraMode.entries.toList(),+        )+    }++    @Test+    fun photoModeUsesCamera2PreviewWithAnalysisStream() {+        assertTrue(PreviewEnginePolicy.usesCamera2(CameraMode.PHOTO))+        assertTrue(CameraMode.PHOTO in PreviewEnginePolicy.supportedModes)+    }++    @Test+    fun photoSettingsIncludePhotoControlsZoomIncluded() {+        // PHOTO keeps its full control set; scanning adds no mode-specific+        // pane and removes none.+        val settings = settingsForMode(CameraMode.PHOTO)+        assertTrue(CameraSetting.ZOOM in settings)+        assertTrue(CameraSetting.BRIGHTNESS in settings)+    }+}
camera/src/test/java/com/vayunmathur/camera/ui/QrModeRoutingTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/ui/QrModeRoutingTest.kt b/camera/src/test/java/com/vayunmathur/camera/ui/QrModeRoutingTest.ktdeleted file mode 100644index ee1494c346..0000000000--- a/camera/src/test/java/com/vayunmathur/camera/ui/QrModeRoutingTest.kt+++ /dev/null@@ -1,44 +0,0 @@-package com.vayunmathur.camera.ui--import com.vayunmathur.camera.platform.CameraMode-import com.vayunmathur.camera.platform.camera2.PreviewEnginePolicy-import kotlin.test.Test-import kotlin.test.assertEquals-import kotlin.test.assertFalse-import kotlin.test.assertTrue--/**- * QR mode routing: the mode exists, the Camera2 preview engine serves it- * (which is what brings the analysis stream the scanner feeds on), and- * the per-mode settings/routing helpers treat it as a capture-less- * photo-family mode.- */-class QrModeRoutingTest {--    @Test-    fun qrModeExistsAndUsesCamera2Preview() {-        assertTrue(CameraMode.QR in CameraMode.entries)-        assertTrue(PreviewEnginePolicy.usesCamera2(CameraMode.QR))-        assertTrue(CameraMode.QR in PreviewEnginePolicy.supportedModes)-    }--    @Test-    fun qrModeOffersZoomOnlySettings() {-        // No still is baked in QR mode, so warmth/shadows/manual exposure-        // would lie; zoom drives the live preview and genuinely helps-        // pull a small code closer.-        assertEquals(listOf(CameraSetting.ZOOM), settingsForMode(CameraMode.QR))-        assertEquals(CameraSetting.ZOOM, effectiveSettingForMode(CameraSetting.ZOOM, CameraMode.QR))-        assertEquals(null, effectiveSettingForMode(CameraSetting.WARMTH, CameraMode.QR))-    }--    @Test-    fun qrModeIsNotPhotoOrVideoType() {-        // The shutter must never take a photo or start a recording in QR-        // mode; routing keys off these families, so QR stays out of both-        // and is handled by its own branch.-        val modes = CameraMode.entries-        assertFalse(CameraMode.QR == CameraMode.PHOTO)-        assertTrue(modes.indexOf(CameraMode.QR) in modes.indices)-    }-}