Modern Apps git

← Modern-Apps.git

camera: persist zoom and add selfie mirroring toggle (#631, #632)

Commit
b9c9b9d2e5ba50237edd91f9050442b56a7115e2
Author
vayun-mathur <[email protected]>
When
2026-08-31 16:59 UTC (3 months ago)
Parents
b207f3b

Diff

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 20c93c39b7..8c2f6538ff 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt@@ -189,6 +189,7 @@ fun CameraScreen(     val qrResult by viewModel.qrResult.collectAsState()     val aspectRatio by viewModel.aspectRatio.collectAsState()     val zoomRatio by viewModel.zoomRatio.collectAsState()+    val mirrorFront by viewModel.mirrorFront.collectAsState()     val timerDuration by viewModel.timerDuration.collectAsState()     val isCapturing by viewModel.isCapturing.collectAsState()     val burstActive by viewModel.burstActive.collectAsState()@@ -557,7 +558,12 @@ fun CameraScreen(                     } else {                         Modifier.fillMaxHeight().aspectRatio(previewAspectRatio)                     }+                    val mirrorPreview =+                        lensFacing == CameraSelector.LENS_FACING_FRONT && !mirrorFront                     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).+                        .graphicsLayer { scaleX = if (mirrorPreview) -1f else 1f }                         .clip(RoundedCornerShape(12.dp))                         .then(                             run {
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 93f4286550..aa68ae2975 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 @@ fun <T : NavKey> SettingsPage(backStack: NavBackStack<T>, viewModel: CameraViewM     val locationEnabled by viewModel.locationEnabled.collectAsState()     val videoCodec by viewModel.videoCodec.collectAsState()     val audioInputSource by viewModel.audioInputSource.collectAsState()+    val mirrorFront by viewModel.mirrorFront.collectAsState()      val requestLocation = rememberPermissionRequest(         Manifest.permission.ACCESS_FINE_LOCATION@@ -158,6 +159,14 @@ fun <T : NavKey> SettingsPage(backStack: NavBackStack<T>, viewModel: CameraViewM                 }             } +            SettingsSection(title = stringResource(R.string.settings_mirror_front)) {+                SettingsSwitchRow(+                    title = stringResource(R.string.settings_mirror_front_description),+                    checked = mirrorFront,+                    onCheckedChange = { viewModel.setMirrorFront(it) },+                )+            }+             SettingsSection(title = stringResource(R.string.settings_location)) {                 SettingsSwitchRow(                     title = stringResource(R.string.settings_location_description),
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 ea4e873608..485727572a 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt@@ -267,6 +267,11 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {     private val _availableZoomLevels = MutableStateFlow(listOf("1x" to 1f))     val availableZoomLevels = _availableZoomLevels.asStateFlow() +    // Whether the front-camera preview and saved selfie are horizontally mirrored (issue #632).+    // Default true preserves the long-standing mirror-like selfie behavior.+    private val _mirrorFront = MutableStateFlow(true)+    val mirrorFront = _mirrorFront.asStateFlow()+     private val _isCapturing = MutableStateFlow(false)     val isCapturing = _isCapturing.asStateFlow() @@ -700,6 +705,8 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {         ds.getString("camera_grid")?.let { _gridEnabled.value = it.toBoolean() }         ds.getString("camera_level")?.let { _levelEnabled.value = it.toBoolean() }         ds.getString("camera_mic_muted")?.let { _micMuted.value = it.toBoolean() }+        ds.getString("camera_zoom_ratio")?.toFloatOrNull()?.let { _zoomRatio.value = it }+        ds.getString("camera_mirror_front")?.let { _mirrorFront.value = it.toBoolean() }         if (_levelEnabled.value) registerLevelSensor()     } @@ -708,6 +715,15 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {         viewModelScope.launch { ds.setString("camera_flash", mode.name) }     } +    /**+     * Toggle horizontal mirroring of the front-camera preview and saved photo/video (issue #632).+     * Takes effect on the next capture; the preview updates immediately via the UI layer.+     */+    fun setMirrorFront(enabled: Boolean) {+        _mirrorFront.value = enabled+        viewModelScope.launch { ds.setString("camera_mirror_front", enabled.toString()) }+    }+     fun toggleTorch() {         _torchEnabled.value = !_torchEnabled.value     }@@ -982,9 +998,11 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {     /**      * Whether captures should be horizontally mirrored to match the preview. CameraX mirrors the      * front-camera preview but saves un-mirrored by default, so selfies otherwise come out flipped.+     * Controlled by the user-facing "mirror selfie" setting (issue #632); only ever applies to the+     * front lens.      */     private val mirrorCaptures: Boolean-        get() = _lensFacing.value == CameraSelector.LENS_FACING_FRONT+        get() = _lensFacing.value == CameraSelector.LENS_FACING_FRONT && _mirrorFront.value      fun setQrResult(text: String?) {         _qrResult.value = text@@ -997,6 +1015,7 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {      */     fun onViewfinderZoomRatio(ratio: Float) {         _zoomRatio.value = ratio+        viewModelScope.launch { ds.setString("camera_zoom_ratio", ratio.toString()) }     }      fun setZoomRatio(ratio: Float) {@@ -1008,6 +1027,7 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {         } ?: ratio         if (clamped != ratio) Log.w("NightPreview", "setZoomRatio() CLAMPED $ratio -> $clamped due to zoomState min/max – vendor NIGHT often reports max=1x, causing bar to show only 1x")         _zoomRatio.value = clamped+        viewModelScope.launch { ds.setString("camera_zoom_ratio", clamped.toString()) }         try {             cam?.cameraControl?.setZoomRatio(clamped)         } catch (e: Exception) {@@ -1015,6 +1035,22 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {         }     } +    /**+     * Restore the previously selected zoom after a (re)bind instead of snapping back to the+     * hardware default. [_zoomRatio] holds the last value the user picked (kept in memory across+     * teardown/rebind and loaded from DataStore on process restart); clamp it to the new lens'+     * supported range and re-apply it to the camera. Fixes issue #631 (zoom reset on resume).+     */+    private fun restoreZoom(minZoom: Float, maxZoom: Float) {+        val desired = _zoomRatio.value.coerceIn(minZoom, maxZoom)+        _zoomRatio.value = desired+        try {+            boundCamera?.cameraControl?.setZoomRatio(desired)+        } catch (e: Exception) {+            Log.e("NightPreview", "restoreZoom() setZoomRatio() threw", e)+        }+    }+     fun updateZoomLevels(minZoom: Float, maxZoom: Float) {         Log.d("NightPreview", "updateZoomLevels() min=$minZoom max=$maxZoom nightPreviewActive=${_nightPreviewActive.value} photoActive=${_photoSessionActive.value} currentRatio=${_zoomRatio.value} thread=${Thread.currentThread().name}")         val levels = mutableListOf<Pair<String, Float>>()@@ -1197,8 +1233,8 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {              boundCamera?.cameraInfo?.zoomState?.value?.let {                 updateZoomLevels(it.minZoomRatio, it.maxZoomRatio)-                _zoomRatio.value = it.zoomRatio-            }+                restoreZoom(it.minZoomRatio, it.maxZoomRatio)+                Log.d("NightPreview", "setupPhotoSession() after levels=             _sloMoSupported.value = true             _highSpeedActive.value = true             true@@ -1359,8 +1395,8 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {             boundCamera?.cameraInfo?.zoomState?.value?.let {                 Log.d("NightPreview", "setupPhotoSession() calling updateZoomLevels min=${it.minZoomRatio} max=${it.maxZoomRatio} – should show .5,1x,2x,5x if >1x else only 1x")                 updateZoomLevels(it.minZoomRatio, it.maxZoomRatio)-                _zoomRatio.value = it.zoomRatio-                Log.d("NightPreview", "setupPhotoSession() after levels=${_availableZoomLevels.value} ratio=${_zoomRatio.value}")+                restoreZoom(it.minZoomRatio, it.maxZoomRatio)+                Log.d("NightPreview", "setupNightPreviewSession() updated zoomRatio=             }             readManualControlRanges()             applyManualControls()@@ -1474,8 +1510,8 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {             boundCamera?.cameraInfo?.zoomState?.value?.let {                 Log.d("NightPreview", "setupNightPreviewSession() calling updateZoomLevels min=${it.minZoomRatio} max=${it.maxZoomRatio}")                 updateZoomLevels(it.minZoomRatio, it.maxZoomRatio)-                _zoomRatio.value = it.zoomRatio-                Log.d("NightPreview", "setupNightPreviewSession() updated zoomRatio=${_zoomRatio.value} levels=${_availableZoomLevels.value}")+                restoreZoom(it.minZoomRatio, it.maxZoomRatio)+                Log.d("NightPreview", "setupPanoramaSession() levels=             }             // Do NOT observe getNightModeIndicator() on the extension camera: it reports             // UNKNOWN/NOT_RECOMMENDED there, which fights the normal session's RECOMMENDED reading@@ -1587,8 +1623,8 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {             boundCamera?.cameraInfo?.zoomState?.value?.let {                 Log.d("NightPreview", "setupPanoramaSession() updateZoomLevels min=${it.minZoomRatio} max=${it.maxZoomRatio}")                 updateZoomLevels(it.minZoomRatio, it.maxZoomRatio)-                _zoomRatio.value = it.zoomRatio-                Log.d("NightPreview", "setupPanoramaSession() levels=${_availableZoomLevels.value}")+                restoreZoom(it.minZoomRatio, it.maxZoomRatio)+                Log.d("NightPreview", "setupPortraitSession() after update levels=             }             _photoSessionActive.value = true             Log.d("NightPreview", "setupPanoramaSession() SUCCESS photoActive=true surface=${_surfaceRequest.value?.resolution}")@@ -1744,9 +1780,9 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {             boundCamera?.cameraInfo?.zoomState?.value?.let {                 Log.d("NightPreview", "setupPortraitSession() updateZoomLevels min=${it.minZoomRatio} max=${it.maxZoomRatio}")                 updateZoomLevels(it.minZoomRatio, it.maxZoomRatio)-                _zoomRatio.value = it.zoomRatio-                Log.d("NightPreview", "setupPortraitSession() after update levels=${_availableZoomLevels.value} ratio=${_zoomRatio.value}")+                restoreZoom(it.minZoomRatio, it.maxZoomRatio)             }+            _sloMoSupported.value = true             readManualControlRanges()             applyManualControls()             _photoSessionActive.value = true@@ -1844,7 +1880,10 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {                 else if (hevc) recorderBuilder.setVideoMimeType(MediaFormat.MIMETYPE_VIDEO_HEVC)                 if (opus) recorderBuilder.setAudioMimeType(MediaFormat.MIMETYPE_AUDIO_OPUS)                 val captureBuilder = VideoCapture.Builder(recorderBuilder.build())-                    .setMirrorMode(MirrorMode.MIRROR_MODE_ON_FRONT_ONLY)+                    .setMirrorMode(+                        if (_mirrorFront.value) MirrorMode.MIRROR_MODE_ON_FRONT_ONLY+                        else MirrorMode.MIRROR_MODE_OFF+                    )                     .setDynamicRange(dynamicRange)                 applyVideoCaptureRequestOptions(captureBuilder, bestFpsRange, stabilizationMode)                 val capture = captureBuilder.build()@@ -1890,7 +1929,7 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {              boundCamera?.cameraInfo?.zoomState?.value?.let {                 updateZoomLevels(it.minZoomRatio, it.maxZoomRatio)-                _zoomRatio.value = it.zoomRatio+                restoreZoom(it.minZoomRatio, it.maxZoomRatio)             }             _videoSessionActive.value = true             true
camera/src/main/res/values/strings.xml
diff --git a/camera/src/main/res/values/strings.xml b/camera/src/main/res/values/strings.xmlindex d8a317fb9e..3903cff800 100644--- a/camera/src/main/res/values/strings.xml+++ b/camera/src/main/res/values/strings.xml@@ -30,6 +30,11 @@     <!-- SettingsPage: summary explaining save location in EXIF metadata -->     <string name="settings_location_description">Save location in photo metadata</string> +    <!-- SettingsPage: section title for selfie (front camera) mirroring -->+    <string name="settings_mirror_front">Selfie mirroring</string>+    <!-- SettingsPage: summary explaining front-camera mirroring toggle -->+    <string name="settings_mirror_front_description">Mirror the front camera preview and saved selfies</string>+     <!-- Video codec settings (SettingsPage) -->     <!-- SettingsPage: section header for video codec selection -->     <string name="settings_video_codec">Video codec</string>