From 19ed97506c9de7b2ae41b928e3eb80be9cc434aa Mon Sep 17 00:00:00 2001 From: davidjiagoogle Date: Tue, 20 Oct 2026 02:34:21 +0000 Subject: [PATCH 1/4] Implement phone landscape mode with counter-rotation and upright icon animations --- app/src/main/AndroidManifest.xml | 3 +- .../com/google/jetpackcamera/MainActivity.kt | 4 + .../core/camera/CameraSession.kt | 2 + .../jetpackcamera/model/DeviceRotation.kt | 41 +++ .../jetpackcamera/model/DeviceRotationTest.kt | 75 +++++ .../feature/preview/PreviewScreen.kt | 33 +- .../components/capture/CameraErrorDialog.kt | 1 + .../capture/CaptureButtonComponents.kt | 5 +- .../ui/components/capture/CaptureLayout.kt | 104 +++++-- .../capture/CaptureScreenComponents.kt | 23 +- .../ui/components/capture/CutoutAwareRow.kt | 61 +++- .../ui/components/capture/ImageWell.kt | 1 + .../components/capture/RotationModifiers.kt | 287 ++++++++++++++++++ .../ui/components/capture/ToggleSwitch.kt | 29 +- .../components/capture/ZoomBarComponents.kt | 4 +- .../quicksettings/QuickSettingsScreen.kt | 16 +- .../ui/QuickSettingsComponents.kt | 7 +- .../capture/compound/CaptureUiState.kt | 4 +- .../capture/compound/CaptureUiStateAdapter.kt | 16 +- .../capture/CaptureUiStateAdapterTest.kt | 44 +++ 20 files changed, 706 insertions(+), 54 deletions(-) create mode 100644 core/model/src/test/java/com/google/jetpackcamera/model/DeviceRotationTest.kt create mode 100644 ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/RotationModifiers.kt diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 5d50ebb448..ac4aa55c81 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -70,9 +70,10 @@ diff --git a/app/src/main/java/com/google/jetpackcamera/MainActivity.kt b/app/src/main/java/com/google/jetpackcamera/MainActivity.kt index d230426a61..515ce9c27c 100644 --- a/app/src/main/java/com/google/jetpackcamera/MainActivity.kt +++ b/app/src/main/java/com/google/jetpackcamera/MainActivity.kt @@ -25,6 +25,7 @@ import android.os.Bundle import android.provider.MediaStore import android.provider.Settings import android.util.Log +import android.view.WindowManager import androidx.activity.ComponentActivity import androidx.activity.SystemBarStyle import androidx.activity.compose.setContent @@ -103,6 +104,9 @@ class MainActivity : ComponentActivity() { navigationBarStyle = SystemBarStyle.dark(android.graphics.Color.TRANSPARENT) ) super.onCreate(savedInstanceState) + window.attributes = window.attributes.apply { + rotationAnimation = WindowManager.LayoutParams.ROTATION_ANIMATION_SEAMLESS + } cameraLaunchConfigProvider.setIntent(intent) var uiState: MainActivityUiState by mutableStateOf(Loading) diff --git a/core/camera/src/main/java/com/google/jetpackcamera/core/camera/CameraSession.kt b/core/camera/src/main/java/com/google/jetpackcamera/core/camera/CameraSession.kt index 4b99c794c2..115071b6c8 100644 --- a/core/camera/src/main/java/com/google/jetpackcamera/core/camera/CameraSession.kt +++ b/core/camera/src/main/java/com/google/jetpackcamera/core/camera/CameraSession.kt @@ -34,6 +34,7 @@ import android.util.Log import android.util.Range import android.util.Rational import android.util.Size +import android.view.Surface import androidx.annotation.OptIn import androidx.camera.camera2.interop.Camera2CameraControl import androidx.camera.camera2.interop.Camera2CameraInfo @@ -786,6 +787,7 @@ private fun createPreviewUseCase( stabilizationMode: StabilizationMode, captureResults: MutableStateFlow? = null ): Preview = Preview.Builder().apply { + setTargetRotation(Surface.ROTATION_0) updateCameraStateWithCaptureResults( targetCameraInfo = cameraInfo, captureResults = captureResults diff --git a/core/model/src/main/java/com/google/jetpackcamera/model/DeviceRotation.kt b/core/model/src/main/java/com/google/jetpackcamera/model/DeviceRotation.kt index 82bfe6c5c8..d2f6e7d937 100644 --- a/core/model/src/main/java/com/google/jetpackcamera/model/DeviceRotation.kt +++ b/core/model/src/main/java/com/google/jetpackcamera/model/DeviceRotation.kt @@ -49,7 +49,48 @@ enum class DeviceRotation { } } + /** + * Returns the clockwise rotation in degrees needed to orient UI elements upright within a + * natural-portrait coordinate frame. + * + * [Rotated180] (reverse portrait) is mapped to `0f` so camera controls do not flip upside-down. + */ + fun toUiRotationDegrees(): Float { + return when (this) { + Natural, Rotated180 -> 0f + Rotated90 -> -90f + Rotated270 -> 90f + } + } + + /** + * Returns the clockwise rotation in degrees needed to counter-rotate a root container back to + * the device's natural portrait coordinate frame when the OS window is rotated to `this` + * orientation. + */ + fun toWindowCounterRotationDegrees(): Float { + return when (this) { + Natural -> 0f + Rotated90 -> 90f + Rotated180 -> 180f + Rotated270 -> -90f + } + } + + val isLandscape: Boolean + get() = this == Rotated90 || this == Rotated270 + companion object { + fun fromSurfaceRotation(surfaceRotation: Int): DeviceRotation { + return when (surfaceRotation) { + Surface.ROTATION_0 -> Natural + Surface.ROTATION_90 -> Rotated270 + Surface.ROTATION_180 -> Rotated180 + Surface.ROTATION_270 -> Rotated90 + else -> Natural + } + } + fun snapFrom(degrees: Int): DeviceRotation { check(degrees in 0..359) { "Degrees must be in the range [0, 360)" diff --git a/core/model/src/test/java/com/google/jetpackcamera/model/DeviceRotationTest.kt b/core/model/src/test/java/com/google/jetpackcamera/model/DeviceRotationTest.kt new file mode 100644 index 0000000000..c73bd2027b --- /dev/null +++ b/core/model/src/test/java/com/google/jetpackcamera/model/DeviceRotationTest.kt @@ -0,0 +1,75 @@ +/* + * Copyright (C) 2025 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.jetpackcamera.model + +import android.view.Surface +import com.google.common.truth.Truth.assertThat +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 + +@RunWith(JUnit4::class) +class DeviceRotationTest { + + @Test + fun toUiRotationDegrees_mapsRotated180ToZeroAndLandscapesToOppositeSign() { + assertThat(DeviceRotation.Natural.toUiRotationDegrees()).isEqualTo(0f) + assertThat(DeviceRotation.Rotated180.toUiRotationDegrees()).isEqualTo(0f) + assertThat(DeviceRotation.Rotated90.toUiRotationDegrees()).isEqualTo(-90f) + assertThat(DeviceRotation.Rotated270.toUiRotationDegrees()).isEqualTo(90f) + } + + @Test + fun toWindowCounterRotationDegrees_cancelsOutUiRotationInLandscape() { + assertThat(DeviceRotation.Natural.toWindowCounterRotationDegrees()).isEqualTo(0f) + assertThat(DeviceRotation.Rotated90.toWindowCounterRotationDegrees()).isEqualTo(90f) + assertThat(DeviceRotation.Rotated180.toWindowCounterRotationDegrees()).isEqualTo(180f) + assertThat(DeviceRotation.Rotated270.toWindowCounterRotationDegrees()).isEqualTo(-90f) + + assertThat( + DeviceRotation.Rotated90.toWindowCounterRotationDegrees() + + DeviceRotation.Rotated90.toUiRotationDegrees() + ).isEqualTo(0f) + assertThat( + DeviceRotation.Rotated270.toWindowCounterRotationDegrees() + + DeviceRotation.Rotated270.toUiRotationDegrees() + ).isEqualTo(0f) + } + + @Test + fun isLandscape_isTrueOnlyForRotated90AndRotated270() { + assertThat(DeviceRotation.Natural.isLandscape).isFalse() + assertThat(DeviceRotation.Rotated180.isLandscape).isFalse() + assertThat(DeviceRotation.Rotated90.isLandscape).isTrue() + assertThat(DeviceRotation.Rotated270.isLandscape).isTrue() + } + + @Test + fun fromSurfaceRotation_isInverseOfToUiSurfaceRotation() { + for (rotation in DeviceRotation.entries) { + val surfaceRotation = rotation.toUiSurfaceRotation() + assertThat(DeviceRotation.fromSurfaceRotation(surfaceRotation)).isEqualTo(rotation) + } + assertThat(DeviceRotation.fromSurfaceRotation(Surface.ROTATION_0)) + .isEqualTo(DeviceRotation.Natural) + assertThat(DeviceRotation.fromSurfaceRotation(Surface.ROTATION_90)) + .isEqualTo(DeviceRotation.Rotated270) + assertThat(DeviceRotation.fromSurfaceRotation(Surface.ROTATION_180)) + .isEqualTo(DeviceRotation.Rotated180) + assertThat(DeviceRotation.fromSurfaceRotation(Surface.ROTATION_270)) + .isEqualTo(DeviceRotation.Rotated90) + } +} diff --git a/feature/preview/src/main/java/com/google/jetpackcamera/feature/preview/PreviewScreen.kt b/feature/preview/src/main/java/com/google/jetpackcamera/feature/preview/PreviewScreen.kt index 28bf9be5a0..0cce298baa 100644 --- a/feature/preview/src/main/java/com/google/jetpackcamera/feature/preview/PreviewScreen.kt +++ b/feature/preview/src/main/java/com/google/jetpackcamera/feature/preview/PreviewScreen.kt @@ -15,6 +15,8 @@ */ package com.google.jetpackcamera.feature.preview +import android.app.Activity +import android.content.pm.ActivityInfo import android.util.Log import android.util.Range import androidx.activity.compose.BackHandler @@ -43,6 +45,7 @@ import androidx.compose.material3.darkColorScheme import androidx.compose.material3.rememberBottomSheetScaffoldState import androidx.compose.material3.rememberStandardBottomSheetState import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.derivedStateOf @@ -70,6 +73,7 @@ import com.google.jetpackcamera.core.camera.VideoRecordingState import com.google.jetpackcamera.model.CameraError import com.google.jetpackcamera.model.CaptureEvent import com.google.jetpackcamera.model.CaptureMode +import com.google.jetpackcamera.model.DeviceRotation import com.google.jetpackcamera.model.ExternalCaptureMode import com.google.jetpackcamera.model.ImageCaptureEvent import com.google.jetpackcamera.model.LensToZoom @@ -271,6 +275,28 @@ private fun ContentScreen( currentCaptureUiStateProvider().videoRecordingState is VideoRecordingState.Active } } + val deviceRotation by remember { + derivedStateOf { + currentCaptureUiStateProvider().deviceRotation + } + } + + val context = LocalContext.current + DisposableEffect(context) { + val activity = context as? Activity + onDispose { + activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_USER + } + } + + LaunchedEffect(isVideoRecordingActive.value) { + val activity = context as? Activity + if (isVideoRecordingActive.value) { + activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LOCKED + } else { + activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_USER + } + } val scope = rememberCoroutineScope() val zoomStateManager = remember(zoomController) { @@ -821,7 +847,8 @@ private fun ContentScreen( snackBar = snackBarLambda, pauseToggleButton = pauseToggleButtonLambda, imageWell = imageWellLambda, - errorDialog = errorDialogLambda + errorDialog = errorDialogLambda, + deviceRotation = deviceRotation ) } @@ -918,7 +945,8 @@ private fun LayoutWrapper( debugVisibilityWrapper: (@Composable (@Composable () -> Unit) -> Unit), screenFlashOverlay: @Composable (modifier: Modifier) -> Unit, snackBar: @Composable (modifier: Modifier, snackbarHostState: SnackbarHostState) -> Unit, - errorDialog: @Composable (modifier: Modifier) -> Unit = {} + errorDialog: @Composable (modifier: Modifier) -> Unit = {}, + deviceRotation: DeviceRotation = DeviceRotation.Natural ) { PreviewLayout( modifier = modifier, @@ -933,6 +961,7 @@ private fun LayoutWrapper( quickSettingsButton = quickSettingsButton, captureModeToggle = captureModeToggle, quickSettingsOverlay = quickSettingsOverlay, + deviceRotation = deviceRotation, indicatorRow = { modifier -> if (!isErrorDialogShowing) { CutoutAwareRow( diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CameraErrorDialog.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CameraErrorDialog.kt index eeedec2c5d..b12f79f872 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CameraErrorDialog.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CameraErrorDialog.kt @@ -85,6 +85,7 @@ fun CameraErrorDialog( ) { Surface( modifier = Modifier + .rotatedLayout(LocalDeviceRotation.current) .padding(horizontal = 24.dp) .widthIn(min = 280.dp, max = 560.dp) .pointerInput(Unit) { diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CaptureButtonComponents.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CaptureButtonComponents.kt index e6c3179871..4831579fe2 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CaptureButtonComponents.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CaptureButtonComponents.kt @@ -813,7 +813,10 @@ private fun LockSwitchCaptureButtonNucleus( } ) { Icon( - modifier = Modifier.size(switchHeight * .75f).align(Alignment.Center), + modifier = Modifier + .size(switchHeight * .75f) + .align(Alignment.Center) + .animateToUpright(), tint = Color.White, painter = if (shouldBeLocked()) { painterResource(R.drawable.ic_lock) diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CaptureLayout.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CaptureLayout.kt index 687700089c..00511ffe55 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CaptureLayout.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CaptureLayout.kt @@ -33,6 +33,7 @@ import androidx.compose.foundation.layout.displayCutout import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.only import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size @@ -56,15 +57,23 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.graphics.Color +import androidx.compose.ui.input.nestedscroll.NestedScrollConnection +import androidx.compose.ui.input.nestedscroll.NestedScrollSource +import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.Role import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.Velocity import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.max import androidx.compose.ui.unit.takeOrElse +import com.google.jetpackcamera.model.DeviceRotation + +private val QuickSettingsLandscapeMaxSheetHeight = 380.dp /** * The base layout for the camera capture screen. @@ -116,13 +125,33 @@ fun PreviewLayout( screenFlashOverlay: @Composable (Modifier) -> Unit, snackBar: @Composable (Modifier, snackbarHostState: SnackbarHostState) -> Unit, topStartContent: @Composable (Modifier) -> Unit = {}, - errorDialog: @Composable (Modifier) -> Unit = {} + errorDialog: @Composable (Modifier) -> Unit = {}, + deviceRotation: DeviceRotation = DeviceRotation.Natural ) { + val windowRotation = rememberWindowRotation() val overlapTargetBounds = remember { mutableStateOf(Rect.Zero) } + val consumeRemainingScrollConnection = remember { + object : NestedScrollConnection { + override fun onPostScroll( + consumed: Offset, + available: Offset, + source: NestedScrollSource + ): Offset = available - CompositionLocalProvider(LocalOverlapTargetBounds provides overlapTargetBounds) { + override suspend fun onPostFling(consumed: Velocity, available: Velocity): Velocity = + available + } + } + + CompositionLocalProvider( + LocalOverlapTargetBounds provides overlapTargetBounds, + LocalDeviceRotation provides deviceRotation, + LocalWindowRotation provides windowRotation + ) { BottomSheetScaffold( - modifier = modifier.fillMaxSize(), + modifier = modifier + .fillMaxSize() + .counterRotateToPortrait(windowRotation), scaffoldState = scaffoldState, sheetPeekHeight = 0.dp, sheetDragHandle = { @@ -141,10 +170,30 @@ fun PreviewLayout( sheetShape = RoundedCornerShape(topStart = 28.dp, topEnd = 28.dp), sheetContainerColor = MaterialTheme.colorScheme.surfaceContainerLow, sheetContent = { - quickSettingsOverlay(Modifier) + if (deviceRotation.isLandscape) { + Box( + modifier = Modifier + .fillMaxWidth() + .heightIn(max = QuickSettingsLandscapeMaxSheetHeight) + .nestedScroll(consumeRemainingScrollConnection) + .rotatedLayout(deviceRotation), + contentAlignment = Alignment.TopStart + ) { + quickSettingsOverlay(Modifier) + } + } else { + quickSettingsOverlay(Modifier) + } }, snackbarHost = {} ) { + val portraitCutoutInsets = WindowInsets.displayCutout.toPortraitWindowInsets( + windowRotation + ) + val portraitSystemBarsAndCutoutInsets = WindowInsets.systemBarsIgnoringVisibility + .union(WindowInsets.displayCutout) + .toPortraitWindowInsets(windowRotation) + Box(modifier = Modifier.fillMaxSize().background(Color.Black)) { Column { // The indicator row occupies the top bar real estate in the hidden status bar @@ -152,7 +201,7 @@ fun PreviewLayout( // minimum interactive touch target (defaulting to 48dp), while CutoutAwareRow // shifts individual indicator icons around any intersecting cutout bounds. val cutoutTopInset = - WindowInsets.displayCutout.asPaddingValues().calculateTopPadding() + portraitCutoutInsets.asPaddingValues().calculateTopPadding() val minTouchTarget = LocalMinimumInteractiveComponentSize.current.takeOrElse { 48.dp } val topBarHeight = max(cutoutTopInset, minTouchTarget) @@ -161,27 +210,32 @@ fun PreviewLayout( .fillMaxWidth() .height(topBarHeight) .windowInsetsPadding( - WindowInsets.displayCutout.only(WindowInsetsSides.Horizontal) + portraitCutoutInsets.only(WindowInsetsSides.Horizontal) ) .padding(horizontal = 16.dp), contentAlignment = Alignment.CenterStart ) { indicatorRow(Modifier) } + val topStartAlignment = if (deviceRotation == DeviceRotation.Rotated270) { + Alignment.TopEnd + } else { + Alignment.TopStart + } Box { viewfinder(Modifier) - topStartContent(Modifier.align(Alignment.TopStart)) + topStartContent( + Modifier + .align(topStartAlignment) + .animateToUpright(deviceRotation) + ) } } Box( modifier = Modifier .fillMaxSize() - .windowInsetsPadding( - WindowInsets.systemBarsIgnoringVisibility - .union(WindowInsets.displayCutout) - ) - + .windowInsetsPadding(portraitSystemBarsAndCutoutInsets) ) { debugVisibilityWrapper { VerticalMaterialControls( @@ -192,13 +246,29 @@ fun PreviewLayout( captureModeToggleSwitch = captureModeToggle, zoomControls = zoomLevelDisplay, elapsedTimeDisplay = elapsedTimeDisplay, - snackbarHost = { modifier -> - PillSnackbarHost( - snackbarHostState = scaffoldState.snackbarHostState, - modifier = modifier - ) + snackbarHost = { snackbarModifier -> + if (!deviceRotation.isLandscape) { + PillSnackbarHost( + snackbarHostState = scaffoldState.snackbarHostState, + modifier = snackbarModifier + ) + } } ) + if (deviceRotation.isLandscape) { + val landscapeSnackbarAlignment = + if (deviceRotation == DeviceRotation.Rotated270) { + Alignment.CenterStart + } else { + Alignment.CenterEnd + } + PillSnackbarHost( + snackbarHostState = scaffoldState.snackbarHostState, + modifier = Modifier + .align(landscapeSnackbarAlignment) + .rotatedLayout(deviceRotation) + ) + } } // controls overlay snackBar(Modifier, scaffoldState.snackbarHostState) diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CaptureScreenComponents.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CaptureScreenComponents.kt index 519da73ce0..251cab0400 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CaptureScreenComponents.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CaptureScreenComponents.kt @@ -415,6 +415,7 @@ fun ElapsedTimeText( val accessibilityText = stringResource(accessibilityRes, minutes, seconds) Box( modifier = modifier + .rotatedLayout(LocalDeviceRotation.current) .testTag(ELAPSED_TIME_TAG) .semantics(mergeDescendants = true) { contentDescription = accessibilityText @@ -467,7 +468,9 @@ fun PauseResumeToggleButton( currentRecordingState !is VideoRecordingState.Active.Paused ) }, - modifier = modifier.size(size) + modifier = modifier + .size(size) + .animateToUpright() ) { Icon( modifier = Modifier @@ -523,6 +526,7 @@ fun AmplitudeToggleButton( FilledIconToggleButton( modifier = modifier .size(buttonSize) + .animateToUpright() .testTag(AUDIO_INPUT_TOGGLE) .semantics { stateDescription = if (audioUiState is AudioUiState.Enabled.On) { @@ -843,10 +847,7 @@ fun PreviewDisplay( .alpha(imageAlpha) .clip(RoundedCornerShape(16.dp)) ) { - val implementationMode = when { - Build.VERSION.SDK_INT > 24 -> ImplementationMode.EXTERNAL - else -> ImplementationMode.EMBEDDED - } + val implementationMode = ImplementationMode.EMBEDDED DetectWindowColorModeChanges( surfaceRequest = surfaceRequest, @@ -970,7 +971,9 @@ fun StabilizationIcon(stabilizationUiState: StabilizationUiState, modifier: Modi CompositionLocalProvider(LocalContentColor provides contentColor) { if (stabilizationUiState.stabilizationMode != StabilizationMode.OFF) { Icon( - modifier = modifier.size(IconButtonDefaults.smallIconSize), + modifier = modifier + .size(IconButtonDefaults.smallIconSize) + .animateToUpright(), painter = when (stabilizationUiState) { is StabilizationUiState.Specific -> @@ -1052,7 +1055,9 @@ fun VideoQualityIcon(videoQuality: VideoQuality, modifier: Modifier = Modifier) CompositionLocalProvider(LocalContentColor provides Color.White) { if (videoQuality != VideoQuality.UNSPECIFIED) { Icon( - modifier = modifier.size(IconButtonDefaults.smallIconSize), + modifier = modifier + .size(IconButtonDefaults.smallIconSize) + .animateToUpright(), painter = when (videoQuality) { VideoQuality.SD -> @@ -1138,7 +1143,9 @@ fun FlipCameraButton( } val backgroundStyle = LocalCameraControlBackgroundStyle.current FilledIconButton( - modifier = modifier.size(56.dp), + modifier = modifier + .size(56.dp) + .animateToUpright(), onClick = onClick, enabled = enabled, shape = RoundedCornerShape(12.dp), diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CutoutAwareRow.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CutoutAwareRow.kt index c862b47873..4ad07787a8 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CutoutAwareRow.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CutoutAwareRow.kt @@ -40,6 +40,7 @@ import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import androidx.core.view.ViewCompat import com.google.jetpackcamera.core.common.ignoreResult +import com.google.jetpackcamera.model.DeviceRotation import kotlin.math.max import kotlin.math.roundToInt @@ -80,6 +81,7 @@ fun CutoutAwareRow( content: @Composable RowScope.() -> Unit ) { val view = LocalView.current + val windowRotation = LocalWindowRotation.current val cutoutInsets = WindowInsets.displayCutout var rowBoundsInWindow by remember { mutableStateOf(null) } val lockedMinX = remember { mutableMapOf() } @@ -134,7 +136,8 @@ fun CutoutAwareRow( ?.displayCutout?.boundingRects.orEmpty(), rowBoundsInWindow = rowBoundsInWindow, isRtl = isRtl, - rtlReferenceWidth = rtlReferenceWidth + rtlReferenceWidth = rtlReferenceWidth, + windowRotation = windowRotation ) // Convert vertically overlapping cutout rects into sorted horizontal keep-out ranges. @@ -226,23 +229,59 @@ internal fun resolveLocalCutoutRects( windowCutoutRects: List, rowBoundsInWindow: IntRect?, isRtl: Boolean, - rtlReferenceWidth: Int + rtlReferenceWidth: Int, + windowRotation: DeviceRotation = DeviceRotation.Natural ): List { val ltrRects = cutoutRectsOverride ?: run { - val offsetX = rowBoundsInWindow?.left ?: 0 - val offsetY = rowBoundsInWindow?.top ?: 0 + val bounds = rowBoundsInWindow windowCutoutRects.map { rect -> - IntRect( - left = rect.left - offsetX, - top = rect.top - offsetY, - right = rect.right - offsetX, - bottom = rect.bottom - offsetY - ) + when (windowRotation) { + DeviceRotation.Natural -> { + val offsetX = bounds?.left ?: 0 + val offsetY = bounds?.top ?: 0 + IntRect( + left = rect.left - offsetX, + top = rect.top - offsetY, + right = rect.right - offsetX, + bottom = rect.bottom - offsetY + ) + } + DeviceRotation.Rotated270 -> { + val refBottom = bounds?.bottom ?: 0 + val refLeft = bounds?.left ?: 0 + IntRect( + left = refBottom - rect.bottom, + top = rect.left - refLeft, + right = refBottom - rect.top, + bottom = rect.right - refLeft + ) + } + DeviceRotation.Rotated90 -> { + val refTop = bounds?.top ?: 0 + val refRight = bounds?.right ?: 0 + IntRect( + left = rect.top - refTop, + top = refRight - rect.right, + right = rect.bottom - refTop, + bottom = refRight - rect.left + ) + } + DeviceRotation.Rotated180 -> { + val refRight = bounds?.right ?: 0 + val refBottom = bounds?.bottom ?: 0 + IntRect( + left = refRight - rect.right, + top = refBottom - rect.bottom, + right = refRight - rect.left, + bottom = refBottom - rect.top + ) + } + } } } return if (isRtl) { val startEdgeX = if (cutoutRectsOverride == null && rowBoundsInWindow != null) { - rowBoundsInWindow.width + if (windowRotation.isLandscape) rowBoundsInWindow.height else rowBoundsInWindow.width } else { rtlReferenceWidth } diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ImageWell.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ImageWell.kt index 7ad63c800f..b533996e6e 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ImageWell.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ImageWell.kt @@ -79,6 +79,7 @@ fun ImageWell( modifier = modifier .testTag(IMAGE_WELL_TAG) .size(IconButtonDefaults.mediumContainerSize()) + .animateToUpright() .border(2.dp, Color.White, shape) .clip(shape) .clickable(onClick = onClick, enabled = enabled) diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/RotationModifiers.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/RotationModifiers.kt new file mode 100644 index 0000000000..5f8663ccc1 --- /dev/null +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/RotationModifiers.kt @@ -0,0 +1,287 @@ +/* + * Copyright (C) 2025 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.jetpackcamera.ui.components.capture + +import android.content.Context +import android.hardware.display.DisplayManager +import android.os.Build +import android.view.Surface +import android.view.WindowManager +import androidx.compose.animation.core.Animatable +import androidx.compose.animation.core.FastOutSlowInEasing +import androidx.compose.animation.core.tween +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.compositionLocalOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.composed +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.layout.layout +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.unit.Density +import androidx.compose.ui.unit.LayoutDirection +import com.google.jetpackcamera.model.DeviceRotation +import kotlin.math.abs +import kotlin.math.max +import kotlin.math.min + +private const val UI_ROTATION_DURATION_MS = 250 + +/** + * Provides the current physical [DeviceRotation] (from [debouncedOrientationFlow], or frozen while + * video recording is active) to descendant composables in the capture screen. + */ +internal val LocalDeviceRotation = compositionLocalOf { DeviceRotation.Natural } + +/** + * Provides the current OS window [DeviceRotation] so child composables (such as [PreviewDisplay]) + * know whether the host window is currently rotated away from natural portrait. + */ +internal val LocalWindowRotation = compositionLocalOf { DeviceRotation.Natural } + +/** + * Tracks the current OS display rotation synchronously with configuration changes and + * [DisplayManager.DisplayListener] callbacks (including 180-degree landscape-to-landscape flips). + */ +@Composable +internal fun rememberWindowRotation(): DeviceRotation { + val context = LocalContext.current + val configuration = LocalConfiguration.current + var surfaceRotation by remember(configuration) { + mutableIntStateOf(context.currentDisplayRotation()) + } + + DisposableEffect(context) { + val displayManager = context.getSystemService(Context.DISPLAY_SERVICE) as? DisplayManager + val listener = object : DisplayManager.DisplayListener { + override fun onDisplayAdded(displayId: Int) {} + override fun onDisplayRemoved(displayId: Int) {} + override fun onDisplayChanged(displayId: Int) { + surfaceRotation = context.currentDisplayRotation() + } + } + displayManager?.registerDisplayListener(listener, null) + onDispose { + displayManager?.unregisterDisplayListener(listener) + } + } + + return DeviceRotation.fromSurfaceRotation(surfaceRotation) +} + +@Suppress("DEPRECATION") +private fun Context.currentDisplayRotation(): Int { + return try { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + display?.rotation ?: Surface.ROTATION_0 + } else { + val windowManager = getSystemService(Context.WINDOW_SERVICE) as? WindowManager + windowManager?.defaultDisplay?.rotation ?: Surface.ROTATION_0 + } + } catch (_: UnsupportedOperationException) { + Surface.ROTATION_0 + } +} + +/** + * Counter-rotates the root phone camera layout back to the device's canonical Portrait (`0°`) + * coordinate system whenever the OS window rotates. + * + * Includes a synchronous window-bounds check so the counter-rotation is only applied when the + * incoming layout constraints match the display rotation's aspect orientation. + */ +internal fun Modifier.counterRotateToPortrait(windowRotation: DeviceRotation): Modifier = + layout { measurable, constraints -> + val isConstraintsLandscape = constraints.maxWidth > constraints.maxHeight + val effectiveWindowRotation = when { + !isConstraintsLandscape && windowRotation.isLandscape -> DeviceRotation.Natural + isConstraintsLandscape && !windowRotation.isLandscape -> DeviceRotation.Rotated270 + else -> windowRotation + } + + val portraitMinWidth = min(constraints.minWidth, constraints.minHeight) + val portraitMaxWidth = min(constraints.maxWidth, constraints.maxHeight) + val portraitMinHeight = max(constraints.minWidth, constraints.minHeight) + val portraitMaxHeight = max(constraints.maxWidth, constraints.maxHeight) + + val placeable = measurable.measure( + constraints.copy( + minWidth = portraitMinWidth, + maxWidth = portraitMaxWidth, + minHeight = portraitMinHeight, + maxHeight = portraitMaxHeight + ) + ) + + val layoutWidth = if (effectiveWindowRotation.isLandscape) { + placeable.height + } else { + placeable.width + } + val layoutHeight = if (effectiveWindowRotation.isLandscape) { + placeable.width + } else { + placeable.height + } + + layout(layoutWidth, layoutHeight) { + val offsetX = (layoutWidth - placeable.width) / 2 + val offsetY = (layoutHeight - placeable.height) / 2 + placeable.placeWithLayer(offsetX, offsetY) { + rotationZ = effectiveWindowRotation.toWindowCounterRotationDegrees() + } + } + } + +/** + * Computes and animates the clockwise rotation in degrees needed to keep a UI element upright in a + * canonical portrait coordinate frame: + * - [DeviceRotation.Rotated180] (reverse portrait) maps to `0f` (never upside-down). + * - `90°` transitions animate over `250ms` with [FastOutSlowInEasing]. + * - `180°` transitions (`Rotated90 <-> Rotated270`) or [LocalDisableAnimations] snap (`0ms`). + */ +@Composable +internal fun rememberAnimatedUiRotationDegrees( + deviceRotation: DeviceRotation = LocalDeviceRotation.current +): Float { + val disableAnimations = LocalDisableAnimations.current + val targetDegrees = deviceRotation.toUiRotationDegrees() + val animatable = remember { Animatable(targetDegrees) } + + LaunchedEffect(targetDegrees, disableAnimations) { + val current = animatable.value + val rotationDiff = (((targetDegrees - current) % 360f) + 540f) % 360f - 180f + val newTarget = current + rotationDiff + if (disableAnimations || abs(rotationDiff) > 90f) { + animatable.snapTo(newTarget) + } else if (rotationDiff != 0f) { + animatable.animateTo( + targetValue = newTarget, + animationSpec = tween( + durationMillis = UI_ROTATION_DURATION_MS, + easing = FastOutSlowInEasing + ) + ) + } + } + + return if (disableAnimations) targetDegrees else animatable.value +} + +/** + * Smoothly rotates a square/circular icon or button in-place around its center so it remains + * upright as [deviceRotation] changes. + */ +internal fun Modifier.animateToUpright(deviceRotation: DeviceRotation? = null): Modifier = + composed { + val effectiveRotation = deviceRotation ?: LocalDeviceRotation.current + val rotationDegrees = rememberAnimatedUiRotationDegrees(effectiveRotation) + graphicsLayer { + rotationZ = rotationDegrees + } + } + +/** + * Measures and places a rectangular composable with swapped width and height constraints when + * [deviceRotation] is landscape ([DeviceRotation.Rotated90] or [DeviceRotation.Rotated270]), + * rotating its layer so the content renders upright without clipping. + */ +internal fun Modifier.rotatedLayout(deviceRotation: DeviceRotation): Modifier = + layout { measurable, constraints -> + val isLandscape = deviceRotation.isLandscape + val placeable = measurable.measure( + if (isLandscape) { + constraints.copy( + minWidth = constraints.minHeight, + maxWidth = constraints.maxHeight, + minHeight = constraints.minWidth, + maxHeight = constraints.maxWidth + ) + } else { + constraints + } + ) + layout( + width = if (isLandscape) placeable.height else placeable.width, + height = if (isLandscape) placeable.width else placeable.height + ) { + val offsetX = if (isLandscape) (placeable.height - placeable.width) / 2 else 0 + val offsetY = if (isLandscape) (placeable.width - placeable.height) / 2 else 0 + placeable.placeWithLayer(offsetX, offsetY) { + rotationZ = deviceRotation.toUiRotationDegrees() + } + } + } + +/** + * Remaps [WindowInsets] from the host OS window's coordinate frame into the canonical Portrait + * (`0°`) coordinate frame used inside [counterRotateToPortrait]. + */ +internal fun WindowInsets.toPortraitWindowInsets(windowRotation: DeviceRotation): WindowInsets = + object : WindowInsets { + override fun getLeft(density: Density, layoutDirection: LayoutDirection): Int = + when (windowRotation) { + DeviceRotation.Natural -> + this@toPortraitWindowInsets.getLeft(density, LayoutDirection.Ltr) + DeviceRotation.Rotated270 -> + this@toPortraitWindowInsets.getBottom(density) + DeviceRotation.Rotated90 -> + this@toPortraitWindowInsets.getTop(density) + DeviceRotation.Rotated180 -> + this@toPortraitWindowInsets.getRight(density, LayoutDirection.Ltr) + } + + override fun getTop(density: Density): Int = when (windowRotation) { + DeviceRotation.Natural -> + this@toPortraitWindowInsets.getTop(density) + DeviceRotation.Rotated270 -> + this@toPortraitWindowInsets.getLeft(density, LayoutDirection.Ltr) + DeviceRotation.Rotated90 -> + this@toPortraitWindowInsets.getRight(density, LayoutDirection.Ltr) + DeviceRotation.Rotated180 -> + this@toPortraitWindowInsets.getBottom(density) + } + + override fun getRight(density: Density, layoutDirection: LayoutDirection): Int = + when (windowRotation) { + DeviceRotation.Natural -> + this@toPortraitWindowInsets.getRight(density, LayoutDirection.Ltr) + DeviceRotation.Rotated270 -> + this@toPortraitWindowInsets.getTop(density) + DeviceRotation.Rotated90 -> + this@toPortraitWindowInsets.getBottom(density) + DeviceRotation.Rotated180 -> + this@toPortraitWindowInsets.getLeft(density, LayoutDirection.Ltr) + } + + override fun getBottom(density: Density): Int = when (windowRotation) { + DeviceRotation.Natural -> + this@toPortraitWindowInsets.getBottom(density) + DeviceRotation.Rotated270 -> + this@toPortraitWindowInsets.getRight(density, LayoutDirection.Ltr) + DeviceRotation.Rotated90 -> + this@toPortraitWindowInsets.getLeft(density, LayoutDirection.Ltr) + DeviceRotation.Rotated180 -> + this@toPortraitWindowInsets.getTop(density) + } + } diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ToggleSwitch.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ToggleSwitch.kt index b66948dc8a..a6a87da54b 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ToggleSwitch.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ToggleSwitch.kt @@ -43,6 +43,7 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.drawscope.clipRect +import androidx.compose.ui.graphics.drawscope.rotate import androidx.compose.ui.graphics.drawscope.translate import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.input.pointer.pointerInput @@ -140,6 +141,7 @@ fun ToggleSwitch( // --- 4. Icon Painters --- val offIconPainter = leftIcon?.let { painterResource(id = it) } val onIconPainter = rightIcon?.let { painterResource(id = it) } + val iconRotationDegrees = rememberAnimatedUiRotationDegrees() // --- 5. Gesture Handlers --- val draggableState = rememberDraggableState { delta -> @@ -221,6 +223,7 @@ fun ToggleSwitch( thumbRect = thumbRect, iconSizePx = dims.iconSizePx, iconPadding = iconPadding, + iconRotationDegrees = iconRotationDegrees, leftIconPainter = offIconPainter, rightIconPainter = onIconPainter, offIconColor = if (enabled) { @@ -312,6 +315,7 @@ private fun DrawScope.drawClippedSwitchIcons( thumbRect: Rect, iconSizePx: Float, iconPadding: Float, + iconRotationDegrees: Float, leftIconPainter: Painter?, rightIconPainter: Painter?, offIconColor: Color, @@ -319,6 +323,7 @@ private fun DrawScope.drawClippedSwitchIcons( ) { val iconY = iconPadding val iconDrawSize = Size(iconSizePx, iconSizePx) + val iconPivot = Offset(iconSizePx / 2f, iconSizePx / 2f) // --- Draw the OFF Icon (Left Side) --- if (leftIconPainter != null) { @@ -327,8 +332,10 @@ private fun DrawScope.drawClippedSwitchIcons( // Draw the base (unselected) icon first translate(left = offIconX, top = iconY) { - with(leftIconPainter) { - draw(size = iconDrawSize, colorFilter = ColorFilter.tint(offIconColor)) + rotate(degrees = iconRotationDegrees, pivot = iconPivot) { + with(leftIconPainter) { + draw(size = iconDrawSize, colorFilter = ColorFilter.tint(offIconColor)) + } } } @@ -340,8 +347,10 @@ private fun DrawScope.drawClippedSwitchIcons( bottom = offIconRect.bottom ) { translate(left = offIconX, top = iconY) { - with(leftIconPainter) { - draw(size = iconDrawSize, colorFilter = ColorFilter.tint(onIconColor)) + rotate(degrees = iconRotationDegrees, pivot = iconPivot) { + with(leftIconPainter) { + draw(size = iconDrawSize, colorFilter = ColorFilter.tint(onIconColor)) + } } } } @@ -353,8 +362,10 @@ private fun DrawScope.drawClippedSwitchIcons( // Draw the base (unselected) icon first translate(left = onIconX, top = iconY) { - with(rightIconPainter) { - draw(size = iconDrawSize, colorFilter = ColorFilter.tint(offIconColor)) + rotate(degrees = iconRotationDegrees, pivot = iconPivot) { + with(rightIconPainter) { + draw(size = iconDrawSize, colorFilter = ColorFilter.tint(offIconColor)) + } } } @@ -366,8 +377,10 @@ private fun DrawScope.drawClippedSwitchIcons( bottom = onIconRect.bottom ) { translate(left = onIconX, top = iconY) { - with(rightIconPainter) { - draw(size = iconDrawSize, colorFilter = ColorFilter.tint(onIconColor)) + rotate(degrees = iconRotationDegrees, pivot = iconPivot) { + with(rightIconPainter) { + draw(size = iconDrawSize, colorFilter = ColorFilter.tint(onIconColor)) + } } } } diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt index a04151f010..d4c948b7ba 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt @@ -158,7 +158,9 @@ private fun ZoomButton( ToggleButton( checked = isSelected, onCheckedChange = { onChangeZoom(targetZoom) }, - modifier = modifier.heightIn(buttonSize) + modifier = modifier + .heightIn(buttonSize) + .animateToUpright() .semantics { testTag = getZoomButtonTestTag(targetZoom) // todo(kc): move to text resource diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/quicksettings/QuickSettingsScreen.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/quicksettings/QuickSettingsScreen.kt index 4d60ff240d..10db04687d 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/quicksettings/QuickSettingsScreen.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/quicksettings/QuickSettingsScreen.kt @@ -22,6 +22,8 @@ import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.navigationBarsIgnoringVisibility import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.windowInsetsPadding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable @@ -36,6 +38,7 @@ import com.google.jetpackcamera.model.DynamicRange import com.google.jetpackcamera.model.FlashMode import com.google.jetpackcamera.model.ImageOutputFormat import com.google.jetpackcamera.model.LensFacing +import com.google.jetpackcamera.ui.components.capture.LocalDeviceRotation import com.google.jetpackcamera.ui.components.capture.QUICK_SETTINGS_BOTTOM_SHEET import com.google.jetpackcamera.ui.components.capture.R import com.google.jetpackcamera.ui.components.capture.quicksettings.ui.AspectRatioRow @@ -71,11 +74,20 @@ fun QuickSettingsScaffoldContent( showMoreSettingsButton: Boolean = true ) { if (quickSettingsUiState is QuickSettingsUiState.Available) { + val deviceRotation = LocalDeviceRotation.current Column( modifier = modifier .fillMaxWidth() - .windowInsetsPadding(WindowInsets.navigationBarsIgnoringVisibility) - .padding(bottom = 24.dp) + .verticalScroll(rememberScrollState()) + .then( + if (deviceRotation.isLandscape) { + Modifier.padding(top = 24.dp, bottom = 24.dp) + } else { + Modifier + .windowInsetsPadding(WindowInsets.navigationBarsIgnoringVisibility) + .padding(bottom = 24.dp) + } + ) .testTag(QUICK_SETTINGS_BOTTOM_SHEET) ) { QuickSettingsContent( diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/quicksettings/ui/QuickSettingsComponents.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/quicksettings/ui/QuickSettingsComponents.kt index 3c06c3192d..6e2c936fba 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/quicksettings/ui/QuickSettingsComponents.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/quicksettings/ui/QuickSettingsComponents.kt @@ -87,6 +87,7 @@ import com.google.jetpackcamera.ui.components.capture.ROW_QUICK_SETTINGS_CAPTURE import com.google.jetpackcamera.ui.components.capture.ROW_QUICK_SETTINGS_FLASH import com.google.jetpackcamera.ui.components.capture.ROW_QUICK_SETTINGS_HDR import com.google.jetpackcamera.ui.components.capture.SETTINGS_BUTTON +import com.google.jetpackcamera.ui.components.capture.animateToUpright import com.google.jetpackcamera.ui.components.capture.quicksettings.CameraAspectRatio import com.google.jetpackcamera.ui.components.capture.quicksettings.CameraCaptureMode import com.google.jetpackcamera.ui.components.capture.quicksettings.CameraDynamicRange @@ -121,6 +122,7 @@ fun ToggleQuickSettingsButton(isOpen: Boolean, onClick: () -> Unit, modifier: Mo IconButton( modifier = modifier .size(buttonSize) + .animateToUpright() .testTag(QUICK_SETTINGS_DROP_DOWN) .semantics { testTag = QUICK_SETTINGS_DROP_DOWN @@ -529,7 +531,9 @@ fun HdrIndicator(hdrUiState: HdrUiState, modifier: Modifier = Modifier) { CameraDynamicRange.SDR } Icon( - modifier = modifier.size(IconButtonDefaults.smallIconSize), + modifier = modifier + .size(IconButtonDefaults.smallIconSize) + .animateToUpright(), painter = enum.getPainter(), contentDescription = stringResource(enum.getDescriptionResId()) ) @@ -581,6 +585,7 @@ private fun TopBarQuickSettingIcon( contentDescription = stringResource(id = enum.getDescriptionResId()), modifier = modifier .size(IconButtonDefaults.smallIconSize) + .animateToUpright() .clickable( interactionSource = remember { MutableInteractionSource() }, indication = null, diff --git a/ui/uistate/capture/src/main/java/com/google/jetpackcamera/ui/uistate/capture/compound/CaptureUiState.kt b/ui/uistate/capture/src/main/java/com/google/jetpackcamera/ui/uistate/capture/compound/CaptureUiState.kt index 018ca4d91e..91bf235b33 100644 --- a/ui/uistate/capture/src/main/java/com/google/jetpackcamera/ui/uistate/capture/compound/CaptureUiState.kt +++ b/ui/uistate/capture/src/main/java/com/google/jetpackcamera/ui/uistate/capture/compound/CaptureUiState.kt @@ -16,6 +16,7 @@ package com.google.jetpackcamera.ui.uistate.capture.compound import com.google.jetpackcamera.core.camera.VideoRecordingState +import com.google.jetpackcamera.model.DeviceRotation import com.google.jetpackcamera.model.ExternalCaptureMode import com.google.jetpackcamera.model.VideoQuality import com.google.jetpackcamera.ui.uistate.capture.AspectRatioUiState @@ -97,7 +98,8 @@ sealed interface CaptureUiState { val hdrUiState: HdrUiState = HdrUiState.Unavailable, val focusMeteringUiState: FocusMeteringUiState = FocusMeteringUiState.Unspecified, val screenFlashUiState: ScreenFlashUiState = ScreenFlashUiState(), - val cameraErrorUiState: CameraErrorUiState = CameraErrorUiState.Hidden + val cameraErrorUiState: CameraErrorUiState = CameraErrorUiState.Hidden, + val deviceRotation: DeviceRotation = DeviceRotation.Natural ) : CaptureUiState companion object diff --git a/ui/uistateadapter/capture/src/main/java/com/google/jetpackcamera/ui/uistateadapter/capture/compound/CaptureUiStateAdapter.kt b/ui/uistateadapter/capture/src/main/java/com/google/jetpackcamera/ui/uistateadapter/capture/compound/CaptureUiStateAdapter.kt index 222f1bc348..726016dca4 100644 --- a/ui/uistateadapter/capture/src/main/java/com/google/jetpackcamera/ui/uistateadapter/capture/compound/CaptureUiStateAdapter.kt +++ b/ui/uistateadapter/capture/src/main/java/com/google/jetpackcamera/ui/uistateadapter/capture/compound/CaptureUiStateAdapter.kt @@ -17,6 +17,7 @@ package com.google.jetpackcamera.ui.uistateadapter.capture.compound import com.google.jetpackcamera.core.camera.CameraState import com.google.jetpackcamera.core.camera.VideoRecordingState +import com.google.jetpackcamera.model.DeviceRotation import com.google.jetpackcamera.model.ExternalCaptureMode import com.google.jetpackcamera.settings.model.CameraAppSettings import com.google.jetpackcamera.settings.model.CameraFeaturePolicy @@ -80,6 +81,7 @@ fun captureUiState( ): Flow { var flashModeUiState: FlashModeUiState? = null var focusMeteringUiState: FocusMeteringUiState? = null + var lockedDeviceRotation: DeviceRotation? = null return combine( currentSettings.filterNotNull(), @@ -92,6 +94,17 @@ fun captureUiState( roundVideoRecordingState(videoRecordingState, timePrecision) val roundedCameraState = cameraState.copy(videoRecordingState = roundedVideoRecordingState) + val effectiveDeviceRotation = if ( + roundedVideoRecordingState !is VideoRecordingState.Inactive + ) { + lockedDeviceRotation ?: cameraAppSettings.deviceRotation.also { + lockedDeviceRotation = it + } + } else { + lockedDeviceRotation = null + cameraAppSettings.deviceRotation + } + val captureModeUiState = CaptureModeUiState.from( systemConstraints = systemConstraints, cameraAppSettings = cameraAppSettings, @@ -195,7 +208,8 @@ fun captureUiState( roundedVideoRecordingState ), screenFlashUiState = ScreenFlashUiState.from(trackedUiState), - cameraErrorUiState = CameraErrorUiState.from(roundedCameraState) + cameraErrorUiState = CameraErrorUiState.from(roundedCameraState), + deviceRotation = effectiveDeviceRotation ) } } diff --git a/ui/uistateadapter/capture/src/test/java/com/google/jetpackcamera/ui/uistateadapter/capture/CaptureUiStateAdapterTest.kt b/ui/uistateadapter/capture/src/test/java/com/google/jetpackcamera/ui/uistateadapter/capture/CaptureUiStateAdapterTest.kt index 96fe41f544..4d14922528 100644 --- a/ui/uistateadapter/capture/src/test/java/com/google/jetpackcamera/ui/uistateadapter/capture/CaptureUiStateAdapterTest.kt +++ b/ui/uistateadapter/capture/src/test/java/com/google/jetpackcamera/ui/uistateadapter/capture/CaptureUiStateAdapterTest.kt @@ -17,10 +17,12 @@ package com.google.jetpackcamera.ui.uistateadapter.capture import com.google.common.truth.Truth.assertThat import com.google.jetpackcamera.core.camera.AudioStreamState +import com.google.jetpackcamera.core.camera.CameraState import com.google.jetpackcamera.core.camera.VideoRecordingState import com.google.jetpackcamera.core.camera.testing.FakeCameraSystem import com.google.jetpackcamera.model.AspectRatio import com.google.jetpackcamera.model.CaptureMode +import com.google.jetpackcamera.model.DeviceRotation import com.google.jetpackcamera.model.DynamicRange import com.google.jetpackcamera.model.ExternalCaptureMode import com.google.jetpackcamera.model.FlashMode @@ -307,6 +309,48 @@ internal class CaptureUiStateAdapterTest { ) } + @Test + fun captureUiState_deviceRotation_freezesWhileRecordingAndUnlocksWhenInactive() = runTest { + val uiStateFlow = createCaptureUiStateFlow() + val states = mutableListOf() + backgroundScope.launch { + uiStateFlow.collect { states.add(it) } + } + + runCurrent() + assertThat(assertIsReady(states.last()).deviceRotation).isEqualTo(DeviceRotation.Natural) + + // Rotate to landscape while idle -> updates immediately + cameraSystem.setDeviceRotation(DeviceRotation.Rotated270) + runCurrent() + assertThat(assertIsReady(states.last()).deviceRotation).isEqualTo(DeviceRotation.Rotated270) + + // Start video recording -> locks at Rotated270 + cameraSystem.setCurrentCameraState( + CameraState( + videoRecordingState = VideoRecordingState.Active.Recording( + maxDurationMillis = 0L, + audioStreamState = AudioStreamState.Active(0.0), + elapsedTimeNanos = 1_000_000_000L + ) + ) + ) + runCurrent() + assertThat(assertIsReady(states.last()).deviceRotation).isEqualTo(DeviceRotation.Rotated270) + + // Rotate physical device to Natural during active recording -> UI state stays Rotated270 + cameraSystem.setDeviceRotation(DeviceRotation.Natural) + runCurrent() + assertThat(assertIsReady(states.last()).deviceRotation).isEqualTo(DeviceRotation.Rotated270) + + // Stop video recording -> unlocks and updates to Natural + cameraSystem.setCurrentCameraState( + CameraState(videoRecordingState = VideoRecordingState.Inactive()) + ) + runCurrent() + assertThat(assertIsReady(states.last()).deviceRotation).isEqualTo(DeviceRotation.Natural) + } + private fun assertIsReady(uiState: CaptureUiState): CaptureUiState.Ready = when (uiState) { is CaptureUiState.Ready -> uiState else -> throw AssertionError( From 30fb73ffebf90b3b6bad1702a3582e272ecfd7e8 Mon Sep 17 00:00:00 2001 From: davidjiagoogle Date: Thu, 22 Oct 2026 23:49:05 +0000 Subject: [PATCH 2/4] Address landscape mode review feedback --- .../feature/preview/PreviewScreen.kt | 26 ++-- .../ui/components/capture/CaptureLayout.kt | 128 ++++++++++++++---- .../capture/CaptureScreenComponents.kt | 5 +- .../ui/components/capture/CutoutAwareRow.kt | 16 ++- .../ui/components/capture/ImageWell.kt | 5 +- .../components/capture/RotationModifiers.kt | 55 ++++---- .../ui/components/capture/ToggleSwitch.kt | 29 ++-- .../components/capture/ZoomBarComponents.kt | 5 +- .../quicksettings/QuickSettingsScreen.kt | 12 +- .../components/capture/CutoutAwareRowTest.kt | 29 ++++ .../capture/compound/CaptureUiState.kt | 4 +- .../capture/compound/CaptureUiStateAdapter.kt | 16 +-- .../capture/CaptureUiStateAdapterTest.kt | 44 ------ 13 files changed, 208 insertions(+), 166 deletions(-) diff --git a/feature/preview/src/main/java/com/google/jetpackcamera/feature/preview/PreviewScreen.kt b/feature/preview/src/main/java/com/google/jetpackcamera/feature/preview/PreviewScreen.kt index 0cce298baa..01eb9c75dd 100644 --- a/feature/preview/src/main/java/com/google/jetpackcamera/feature/preview/PreviewScreen.kt +++ b/feature/preview/src/main/java/com/google/jetpackcamera/feature/preview/PreviewScreen.kt @@ -73,7 +73,6 @@ import com.google.jetpackcamera.core.camera.VideoRecordingState import com.google.jetpackcamera.model.CameraError import com.google.jetpackcamera.model.CaptureEvent import com.google.jetpackcamera.model.CaptureMode -import com.google.jetpackcamera.model.DeviceRotation import com.google.jetpackcamera.model.ExternalCaptureMode import com.google.jetpackcamera.model.ImageCaptureEvent import com.google.jetpackcamera.model.LensToZoom @@ -208,13 +207,6 @@ fun PreviewScreen( } } - val context = LocalContext.current - LaunchedEffect(Unit) { - debouncedOrientationFlow(context).collect( - viewModel.cameraController::setDisplayRotation - ) - } - ContentScreen( modifier = modifier, captureUiStateProvider = readyStateProvider, @@ -275,9 +267,9 @@ private fun ContentScreen( currentCaptureUiStateProvider().videoRecordingState is VideoRecordingState.Active } } - val deviceRotation by remember { + val isVideoRecordingInProgress = remember { derivedStateOf { - currentCaptureUiStateProvider().deviceRotation + currentCaptureUiStateProvider().videoRecordingState !is VideoRecordingState.Inactive } } @@ -289,12 +281,15 @@ private fun ContentScreen( } } - LaunchedEffect(isVideoRecordingActive.value) { + LaunchedEffect(isVideoRecordingInProgress.value, cameraController) { val activity = context as? Activity - if (isVideoRecordingActive.value) { + if (isVideoRecordingInProgress.value) { activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LOCKED } else { activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_USER + cameraController?.let { controller -> + debouncedOrientationFlow(context).collect(controller::setDisplayRotation) + } } } @@ -847,8 +842,7 @@ private fun ContentScreen( snackBar = snackBarLambda, pauseToggleButton = pauseToggleButtonLambda, imageWell = imageWellLambda, - errorDialog = errorDialogLambda, - deviceRotation = deviceRotation + errorDialog = errorDialogLambda ) } @@ -945,8 +939,7 @@ private fun LayoutWrapper( debugVisibilityWrapper: (@Composable (@Composable () -> Unit) -> Unit), screenFlashOverlay: @Composable (modifier: Modifier) -> Unit, snackBar: @Composable (modifier: Modifier, snackbarHostState: SnackbarHostState) -> Unit, - errorDialog: @Composable (modifier: Modifier) -> Unit = {}, - deviceRotation: DeviceRotation = DeviceRotation.Natural + errorDialog: @Composable (modifier: Modifier) -> Unit = {} ) { PreviewLayout( modifier = modifier, @@ -961,7 +954,6 @@ private fun LayoutWrapper( quickSettingsButton = quickSettingsButton, captureModeToggle = captureModeToggle, quickSettingsOverlay = quickSettingsOverlay, - deviceRotation = deviceRotation, indicatorRow = { modifier -> if (!isErrorDialogShowing) { CutoutAwareRow( diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CaptureLayout.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CaptureLayout.kt index 00511ffe55..e6a6c79303 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CaptureLayout.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CaptureLayout.kt @@ -15,6 +15,10 @@ */ package com.google.jetpackcamera.ui.components.capture +import androidx.compose.animation.animateContentSize +import androidx.compose.animation.core.Animatable +import androidx.compose.animation.core.FastOutSlowInEasing +import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource @@ -53,13 +57,17 @@ import androidx.compose.material3.rememberBottomSheetScaffoldState import androidx.compose.material3.rememberStandardBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.LaunchedEffect +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.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.input.nestedscroll.NestedScrollConnection import androidx.compose.ui.input.nestedscroll.NestedScrollSource import androidx.compose.ui.input.nestedscroll.nestedScroll @@ -72,8 +80,11 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.max import androidx.compose.ui.unit.takeOrElse import com.google.jetpackcamera.model.DeviceRotation +import kotlinx.coroutines.delay private val QuickSettingsLandscapeMaxSheetHeight = 380.dp +private const val QUICK_SETTINGS_FADE_DURATION_MS = 150 +private const val QUICK_SETTINGS_RESIZE_DURATION_MS = 250 /** * The base layout for the camera capture screen. @@ -126,9 +137,44 @@ fun PreviewLayout( snackBar: @Composable (Modifier, snackbarHostState: SnackbarHostState) -> Unit, topStartContent: @Composable (Modifier) -> Unit = {}, errorDialog: @Composable (Modifier) -> Unit = {}, - deviceRotation: DeviceRotation = DeviceRotation.Natural + deviceRotation: DeviceRotation? = null ) { val windowRotation = rememberWindowRotation() + val uiRotation = deviceRotation ?: windowRotation + val disableAnimations = LocalDisableAnimations.current + val isSheetVisible = scaffoldState.bottomSheetState.isVisible || + scaffoldState.bottomSheetState.targetValue == SheetValue.Expanded + var displayedSheetRotation by remember { mutableStateOf(uiRotation) } + val sheetContentAlpha = remember { Animatable(1f) } + + LaunchedEffect(uiRotation, isSheetVisible, disableAnimations) { + if (displayedSheetRotation != uiRotation) { + if (isSheetVisible && !disableAnimations) { + sheetContentAlpha.animateTo( + targetValue = 0f, + animationSpec = tween( + durationMillis = QUICK_SETTINGS_FADE_DURATION_MS, + easing = FastOutSlowInEasing + ) + ) + displayedSheetRotation = uiRotation + delay(QUICK_SETTINGS_RESIZE_DURATION_MS.toLong()) + sheetContentAlpha.animateTo( + targetValue = 1f, + animationSpec = tween( + durationMillis = QUICK_SETTINGS_FADE_DURATION_MS, + easing = FastOutSlowInEasing + ) + ) + } else { + displayedSheetRotation = uiRotation + sheetContentAlpha.snapTo(1f) + } + } else if (sheetContentAlpha.value < 1f && (!isSheetVisible || disableAnimations)) { + sheetContentAlpha.snapTo(1f) + } + } + val overlapTargetBounds = remember { mutableStateOf(Rect.Zero) } val consumeRemainingScrollConnection = remember { object : NestedScrollConnection { @@ -145,7 +191,7 @@ fun PreviewLayout( CompositionLocalProvider( LocalOverlapTargetBounds provides overlapTargetBounds, - LocalDeviceRotation provides deviceRotation, + LocalDeviceRotation provides uiRotation, LocalWindowRotation provides windowRotation ) { BottomSheetScaffold( @@ -170,19 +216,41 @@ fun PreviewLayout( sheetShape = RoundedCornerShape(topStart = 28.dp, topEnd = 28.dp), sheetContainerColor = MaterialTheme.colorScheme.surfaceContainerLow, sheetContent = { - if (deviceRotation.isLandscape) { + CompositionLocalProvider(LocalDeviceRotation provides displayedSheetRotation) { Box( modifier = Modifier .fillMaxWidth() - .heightIn(max = QuickSettingsLandscapeMaxSheetHeight) - .nestedScroll(consumeRemainingScrollConnection) - .rotatedLayout(deviceRotation), - contentAlignment = Alignment.TopStart + .then( + if (disableAnimations) { + Modifier + } else { + Modifier.animateContentSize( + animationSpec = tween( + durationMillis = QUICK_SETTINGS_RESIZE_DURATION_MS, + easing = FastOutSlowInEasing + ) + ) + } + ) + .graphicsLayer { + alpha = sheetContentAlpha.value + } ) { - quickSettingsOverlay(Modifier) + if (displayedSheetRotation.isLandscape) { + Box( + modifier = Modifier + .fillMaxWidth() + .heightIn(max = QuickSettingsLandscapeMaxSheetHeight) + .nestedScroll(consumeRemainingScrollConnection) + .rotatedLayout(displayedSheetRotation), + contentAlignment = Alignment.TopStart + ) { + quickSettingsOverlay(Modifier) + } + } else { + quickSettingsOverlay(Modifier) + } } - } else { - quickSettingsOverlay(Modifier) } }, snackbarHost = {} @@ -217,7 +285,7 @@ fun PreviewLayout( ) { indicatorRow(Modifier) } - val topStartAlignment = if (deviceRotation == DeviceRotation.Rotated270) { + val topStartAlignment = if (uiRotation == DeviceRotation.Rotated270) { Alignment.TopEnd } else { Alignment.TopStart @@ -227,7 +295,7 @@ fun PreviewLayout( topStartContent( Modifier .align(topStartAlignment) - .animateToUpright(deviceRotation) + .animateToUpright(uiRotation) ) } } @@ -235,7 +303,9 @@ fun PreviewLayout( Box( modifier = Modifier .fillMaxSize() - .windowInsetsPadding(portraitSystemBarsAndCutoutInsets) + .windowInsetsPadding( + portraitSystemBarsAndCutoutInsets.only(WindowInsetsSides.Vertical) + ) ) { debugVisibilityWrapper { VerticalMaterialControls( @@ -245,9 +315,13 @@ fun PreviewLayout( quickSettingsToggleButton = quickSettingsButton, captureModeToggleSwitch = captureModeToggle, zoomControls = zoomLevelDisplay, - elapsedTimeDisplay = elapsedTimeDisplay, + elapsedTimeDisplay = { elapsedTimeModifier -> + if (!uiRotation.isLandscape) { + elapsedTimeDisplay(elapsedTimeModifier) + } + }, snackbarHost = { snackbarModifier -> - if (!deviceRotation.isLandscape) { + if (!uiRotation.isLandscape) { PillSnackbarHost( snackbarHostState = scaffoldState.snackbarHostState, modifier = snackbarModifier @@ -255,19 +329,24 @@ fun PreviewLayout( } } ) - if (deviceRotation.isLandscape) { - val landscapeSnackbarAlignment = - if (deviceRotation == DeviceRotation.Rotated270) { + if (uiRotation.isLandscape) { + val landscapeTopAlignment = + if (uiRotation == DeviceRotation.Rotated270) { Alignment.CenterStart } else { Alignment.CenterEnd } - PillSnackbarHost( - snackbarHostState = scaffoldState.snackbarHostState, + Column( modifier = Modifier - .align(landscapeSnackbarAlignment) - .rotatedLayout(deviceRotation) - ) + .align(landscapeTopAlignment) + .rotatedLayout(uiRotation), + horizontalAlignment = Alignment.CenterHorizontally + ) { + PillSnackbarHost( + snackbarHostState = scaffoldState.snackbarHostState + ) + elapsedTimeDisplay(Modifier) + } } } // controls overlay @@ -276,8 +355,6 @@ fun PreviewLayout( } debugOverlay(Modifier) - val isSheetVisible = scaffoldState.bottomSheetState.isVisible || - scaffoldState.bottomSheetState.targetValue == SheetValue.Expanded if (isSheetVisible) { Box( modifier = Modifier @@ -390,7 +467,6 @@ private fun VerticalMaterialControls( // capture mode toggle switch center Box( - modifier = Modifier.weight(1f), contentAlignment = Alignment.Center ) { captureModeToggleSwitch(Modifier) diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CaptureScreenComponents.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CaptureScreenComponents.kt index 251cab0400..add95b2b78 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CaptureScreenComponents.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CaptureScreenComponents.kt @@ -415,7 +415,6 @@ fun ElapsedTimeText( val accessibilityText = stringResource(accessibilityRes, minutes, seconds) Box( modifier = modifier - .rotatedLayout(LocalDeviceRotation.current) .testTag(ELAPSED_TIME_TAG) .semantics(mergeDescendants = true) { contentDescription = accessibilityText @@ -1144,8 +1143,7 @@ fun FlipCameraButton( val backgroundStyle = LocalCameraControlBackgroundStyle.current FilledIconButton( modifier = modifier - .size(56.dp) - .animateToUpright(), + .size(56.dp), onClick = onClick, enabled = enabled, shape = RoundedCornerShape(12.dp), @@ -1169,6 +1167,7 @@ fun FlipCameraButton( contentDescription = contentDescription, modifier = Modifier .size(IconButtonDefaults.largeIconSize) + .animateToUpright() .rotate(animatedRotation.value) ) } diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CutoutAwareRow.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CutoutAwareRow.kt index 4ad07787a8..1fbbe8659c 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CutoutAwareRow.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CutoutAwareRow.kt @@ -137,7 +137,9 @@ fun CutoutAwareRow( rowBoundsInWindow = rowBoundsInWindow, isRtl = isRtl, rtlReferenceWidth = rtlReferenceWidth, - windowRotation = windowRotation + windowRotation = windowRotation, + fallbackViewWidth = view.width, + fallbackViewHeight = view.height ) // Convert vertically overlapping cutout rects into sorted horizontal keep-out ranges. @@ -230,7 +232,9 @@ internal fun resolveLocalCutoutRects( rowBoundsInWindow: IntRect?, isRtl: Boolean, rtlReferenceWidth: Int, - windowRotation: DeviceRotation = DeviceRotation.Natural + windowRotation: DeviceRotation = DeviceRotation.Natural, + fallbackViewWidth: Int = 0, + fallbackViewHeight: Int = 0 ): List { val ltrRects = cutoutRectsOverride ?: run { val bounds = rowBoundsInWindow @@ -247,7 +251,7 @@ internal fun resolveLocalCutoutRects( ) } DeviceRotation.Rotated270 -> { - val refBottom = bounds?.bottom ?: 0 + val refBottom = bounds?.bottom ?: fallbackViewHeight val refLeft = bounds?.left ?: 0 IntRect( left = refBottom - rect.bottom, @@ -258,7 +262,7 @@ internal fun resolveLocalCutoutRects( } DeviceRotation.Rotated90 -> { val refTop = bounds?.top ?: 0 - val refRight = bounds?.right ?: 0 + val refRight = bounds?.right ?: fallbackViewWidth IntRect( left = rect.top - refTop, top = refRight - rect.right, @@ -267,8 +271,8 @@ internal fun resolveLocalCutoutRects( ) } DeviceRotation.Rotated180 -> { - val refRight = bounds?.right ?: 0 - val refBottom = bounds?.bottom ?: 0 + val refRight = bounds?.right ?: fallbackViewWidth + val refBottom = bounds?.bottom ?: fallbackViewHeight IntRect( left = refRight - rect.right, top = refBottom - rect.bottom, diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ImageWell.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ImageWell.kt index b533996e6e..fbdd868f52 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ImageWell.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ImageWell.kt @@ -79,7 +79,6 @@ fun ImageWell( modifier = modifier .testTag(IMAGE_WELL_TAG) .size(IconButtonDefaults.mediumContainerSize()) - .animateToUpright() .border(2.dp, Color.White, shape) .clip(shape) .clickable(onClick = onClick, enabled = enabled) @@ -107,7 +106,9 @@ fun ImageWell( val imageBitmap = remember(bitmap) { bitmap.asImageBitmap() } Image( bitmap = imageBitmap, - modifier = Modifier.fillMaxSize(), + modifier = Modifier + .fillMaxSize() + .animateToUpright(), contentDescription = stringResource( id = R.string.image_well_content_description ), diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/RotationModifiers.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/RotationModifiers.kt index 5f8663ccc1..aa69024510 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/RotationModifiers.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/RotationModifiers.kt @@ -27,10 +27,12 @@ import androidx.compose.foundation.layout.WindowInsets import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.State import androidx.compose.runtime.compositionLocalOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.composed @@ -42,14 +44,11 @@ import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.LayoutDirection import com.google.jetpackcamera.model.DeviceRotation import kotlin.math.abs -import kotlin.math.max -import kotlin.math.min private const val UI_ROTATION_DURATION_MS = 250 /** - * Provides the current physical [DeviceRotation] (from [debouncedOrientationFlow], or frozen while - * video recording is active) to descendant composables in the capture screen. + * Provides the current UI [DeviceRotation] to descendant composables in the capture screen. */ internal val LocalDeviceRotation = compositionLocalOf { DeviceRotation.Natural } @@ -106,39 +105,29 @@ private fun Context.currentDisplayRotation(): Int { /** * Counter-rotates the root phone camera layout back to the device's canonical Portrait (`0°`) * coordinate system whenever the OS window rotates. - * - * Includes a synchronous window-bounds check so the counter-rotation is only applied when the - * incoming layout constraints match the display rotation's aspect orientation. */ internal fun Modifier.counterRotateToPortrait(windowRotation: DeviceRotation): Modifier = layout { measurable, constraints -> - val isConstraintsLandscape = constraints.maxWidth > constraints.maxHeight - val effectiveWindowRotation = when { - !isConstraintsLandscape && windowRotation.isLandscape -> DeviceRotation.Natural - isConstraintsLandscape && !windowRotation.isLandscape -> DeviceRotation.Rotated270 - else -> windowRotation - } - - val portraitMinWidth = min(constraints.minWidth, constraints.minHeight) - val portraitMaxWidth = min(constraints.maxWidth, constraints.maxHeight) - val portraitMinHeight = max(constraints.minWidth, constraints.minHeight) - val portraitMaxHeight = max(constraints.maxWidth, constraints.maxHeight) - + val isLandscape = windowRotation.isLandscape val placeable = measurable.measure( - constraints.copy( - minWidth = portraitMinWidth, - maxWidth = portraitMaxWidth, - minHeight = portraitMinHeight, - maxHeight = portraitMaxHeight - ) + if (isLandscape) { + constraints.copy( + minWidth = constraints.minHeight, + maxWidth = constraints.maxHeight, + minHeight = constraints.minWidth, + maxHeight = constraints.maxWidth + ) + } else { + constraints + } ) - val layoutWidth = if (effectiveWindowRotation.isLandscape) { + val layoutWidth = if (isLandscape) { placeable.height } else { placeable.width } - val layoutHeight = if (effectiveWindowRotation.isLandscape) { + val layoutHeight = if (isLandscape) { placeable.width } else { placeable.height @@ -148,7 +137,7 @@ internal fun Modifier.counterRotateToPortrait(windowRotation: DeviceRotation): M val offsetX = (layoutWidth - placeable.width) / 2 val offsetY = (layoutHeight - placeable.height) / 2 placeable.placeWithLayer(offsetX, offsetY) { - rotationZ = effectiveWindowRotation.toWindowCounterRotationDegrees() + rotationZ = windowRotation.toWindowCounterRotationDegrees() } } } @@ -163,7 +152,7 @@ internal fun Modifier.counterRotateToPortrait(windowRotation: DeviceRotation): M @Composable internal fun rememberAnimatedUiRotationDegrees( deviceRotation: DeviceRotation = LocalDeviceRotation.current -): Float { +): State { val disableAnimations = LocalDisableAnimations.current val targetDegrees = deviceRotation.toUiRotationDegrees() val animatable = remember { Animatable(targetDegrees) } @@ -185,7 +174,11 @@ internal fun rememberAnimatedUiRotationDegrees( } } - return if (disableAnimations) targetDegrees else animatable.value + return if (disableAnimations) { + rememberUpdatedState(targetDegrees) + } else { + animatable.asState() + } } /** @@ -197,7 +190,7 @@ internal fun Modifier.animateToUpright(deviceRotation: DeviceRotation? = null): val effectiveRotation = deviceRotation ?: LocalDeviceRotation.current val rotationDegrees = rememberAnimatedUiRotationDegrees(effectiveRotation) graphicsLayer { - rotationZ = rotationDegrees + rotationZ = rotationDegrees.value } } diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ToggleSwitch.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ToggleSwitch.kt index a6a87da54b..540aff9986 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ToggleSwitch.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ToggleSwitch.kt @@ -107,13 +107,16 @@ fun ToggleSwitch( // --- 2. Drag and Animation State --- var dragOffset by remember { mutableFloatStateOf(0f) } + var canvasWidthPx by remember(dims.switchWidthPx) { mutableFloatStateOf(dims.switchWidthPx) } + val effectiveDragRange = + (canvasWidthPx - dims.paddingPx - dims.thumbRadiusPx - dims.startX).coerceAtLeast(1f) val targetPosition = if (checked) 1f else 0f val disableAnimations = LocalDisableAnimations.current // Animate the thumb position. // This snaps (0ms) during drag and animates (300ms) on tap or drag release. val animatedPosition by animateFloatAsState( - targetValue = (targetPosition + (dragOffset / dims.dragRange)).coerceIn(0f, 1f), + targetValue = (targetPosition + (dragOffset / effectiveDragRange)).coerceIn(0f, 1f), animationSpec = if (disableAnimations) { snap() } else { @@ -123,7 +126,7 @@ fun ToggleSwitch( }, label = "thumbPosition" ) - val initialThumbX = dims.startX + dims.dragRange * animatedPosition + val initialThumbX = dims.startX + effectiveDragRange * animatedPosition // --- 3. Color Animations --- // color changes if togglemode is off (to indicate on/off state) @@ -147,8 +150,8 @@ fun ToggleSwitch( val draggableState = rememberDraggableState { delta -> val newOffset = dragOffset + delta // Constrain drag within the allowed range based on the *current* state - val dragMin = if (checked) -dims.dragRange else 0f - val dragMax = if (checked) 0f else dims.dragRange + val dragMin = if (checked) -effectiveDragRange else 0f + val dragMax = if (checked) 0f else effectiveDragRange dragOffset = newOffset.coerceIn(dragMin, dragMax) } @@ -169,7 +172,7 @@ fun ToggleSwitch( onDragStopped = { // Determine new state based on final drag position val finalThumbPos = initialThumbX - dims.startX - val newCheckedState = finalThumbPos > (dims.dragRange / 2) + val newCheckedState = finalThumbPos > (effectiveDragRange / 2) if (newCheckedState != checked) { onCheckedChange(newCheckedState) } @@ -195,6 +198,12 @@ fun ToggleSwitch( .size(dims.switchWidthDp, dims.switchHeightDp) .then(gestureModifier) ) { + if (canvasWidthPx != size.width && size.width > 0f) { + canvasWidthPx = size.width + } + val endX = (size.width - dims.paddingPx - dims.thumbRadiusPx).coerceAtLeast(dims.startX) + val thumbX = dims.startX + (endX - dims.startX) * animatedPosition + // 1. Draw the Track drawSwitchTrack( color = trackAnimatedColor, @@ -203,16 +212,16 @@ fun ToggleSwitch( // 2. Calculate Thumb Rect and Icon Padding val thumbRect = Rect( - left = initialThumbX - dims.thumbRadiusPx, + left = thumbX - dims.thumbRadiusPx, top = thumbY - dims.thumbRadiusPx, - right = initialThumbX + dims.thumbRadiusPx, + right = thumbX + dims.thumbRadiusPx, bottom = thumbY + dims.thumbRadiusPx ) val iconPadding = (dims.switchHeightPx - dims.iconSizePx) / 2 // 4. Draw the Thumb (under Icons) drawSwitchThumb( - center = Offset(initialThumbX, thumbY), + center = Offset(thumbX, thumbY), radius = dims.thumbRadiusPx, color = thumbAnimatedColor ) @@ -223,7 +232,7 @@ fun ToggleSwitch( thumbRect = thumbRect, iconSizePx = dims.iconSizePx, iconPadding = iconPadding, - iconRotationDegrees = iconRotationDegrees, + iconRotationDegrees = iconRotationDegrees.value, leftIconPainter = offIconPainter, rightIconPainter = onIconPainter, offIconColor = if (enabled) { @@ -256,6 +265,7 @@ private class SwitchDimensions( val switchWidthPx: Float, val switchHeightPx: Float, val thumbRadiusPx: Float, + val paddingPx: Float, val iconSizePx: Float, val startX: Float, val dragRange: Float @@ -289,6 +299,7 @@ private fun rememberSwitchDimensions( switchWidthPx = switchWidthPx, switchHeightPx = switchHeightPx, thumbRadiusPx = thumbRadiusPx, + paddingPx = paddingPx, iconSizePx = iconSizePx, startX = startX, dragRange = dragRange diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt index d4c948b7ba..aee57298ee 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt @@ -160,7 +160,6 @@ private fun ZoomButton( onCheckedChange = { onChangeZoom(targetZoom) }, modifier = modifier .heightIn(buttonSize) - .animateToUpright() .semantics { testTag = getZoomButtonTestTag(targetZoom) // todo(kc): move to text resource @@ -181,7 +180,9 @@ private fun ZoomButton( } ) { Text( - modifier = Modifier.animateContentSize(), + modifier = Modifier + .animateContentSize() + .animateToUpright(), text = displayText, style = MaterialTheme.typography.labelSmall, textAlign = TextAlign.Center diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/quicksettings/QuickSettingsScreen.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/quicksettings/QuickSettingsScreen.kt index 10db04687d..c0acbab378 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/quicksettings/QuickSettingsScreen.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/quicksettings/QuickSettingsScreen.kt @@ -79,14 +79,10 @@ fun QuickSettingsScaffoldContent( modifier = modifier .fillMaxWidth() .verticalScroll(rememberScrollState()) - .then( - if (deviceRotation.isLandscape) { - Modifier.padding(top = 24.dp, bottom = 24.dp) - } else { - Modifier - .windowInsetsPadding(WindowInsets.navigationBarsIgnoringVisibility) - .padding(bottom = 24.dp) - } + .windowInsetsPadding(WindowInsets.navigationBarsIgnoringVisibility) + .padding( + top = if (deviceRotation.isLandscape) 24.dp else 0.dp, + bottom = 24.dp ) .testTag(QUICK_SETTINGS_BOTTOM_SHEET) ) { diff --git a/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/CutoutAwareRowTest.kt b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/CutoutAwareRowTest.kt index eec8c5a6ba..67c16117d5 100644 --- a/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/CutoutAwareRowTest.kt +++ b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/CutoutAwareRowTest.kt @@ -304,5 +304,34 @@ class CutoutAwareRowTest { rtlReferenceWidth = 360 ) ).containsExactly(IntRect(left = 310, top = 0, right = 350, bottom = 40)) + + // Verify fallbackViewWidth / fallbackViewHeight when rowBoundsInWindow is null on first pass + val landscapeLeftCutout = listOf(android.graphics.Rect(0, 300, 48, 340)) + assertThat( + resolveLocalCutoutRects( + cutoutRectsOverride = null, + windowCutoutRects = landscapeLeftCutout, + rowBoundsInWindow = null, + isRtl = false, + rtlReferenceWidth = 360, + windowRotation = com.google.jetpackcamera.model.DeviceRotation.Rotated270, + fallbackViewWidth = 800, + fallbackViewHeight = 360 + ) + ).containsExactly(IntRect(left = 20, top = 0, right = 60, bottom = 48)) + + val landscapeRightCutout = listOf(android.graphics.Rect(752, 20, 800, 60)) + assertThat( + resolveLocalCutoutRects( + cutoutRectsOverride = null, + windowCutoutRects = landscapeRightCutout, + rowBoundsInWindow = null, + isRtl = false, + rtlReferenceWidth = 360, + windowRotation = com.google.jetpackcamera.model.DeviceRotation.Rotated90, + fallbackViewWidth = 800, + fallbackViewHeight = 360 + ) + ).containsExactly(IntRect(left = 20, top = 0, right = 60, bottom = 48)) } } diff --git a/ui/uistate/capture/src/main/java/com/google/jetpackcamera/ui/uistate/capture/compound/CaptureUiState.kt b/ui/uistate/capture/src/main/java/com/google/jetpackcamera/ui/uistate/capture/compound/CaptureUiState.kt index 91bf235b33..018ca4d91e 100644 --- a/ui/uistate/capture/src/main/java/com/google/jetpackcamera/ui/uistate/capture/compound/CaptureUiState.kt +++ b/ui/uistate/capture/src/main/java/com/google/jetpackcamera/ui/uistate/capture/compound/CaptureUiState.kt @@ -16,7 +16,6 @@ package com.google.jetpackcamera.ui.uistate.capture.compound import com.google.jetpackcamera.core.camera.VideoRecordingState -import com.google.jetpackcamera.model.DeviceRotation import com.google.jetpackcamera.model.ExternalCaptureMode import com.google.jetpackcamera.model.VideoQuality import com.google.jetpackcamera.ui.uistate.capture.AspectRatioUiState @@ -98,8 +97,7 @@ sealed interface CaptureUiState { val hdrUiState: HdrUiState = HdrUiState.Unavailable, val focusMeteringUiState: FocusMeteringUiState = FocusMeteringUiState.Unspecified, val screenFlashUiState: ScreenFlashUiState = ScreenFlashUiState(), - val cameraErrorUiState: CameraErrorUiState = CameraErrorUiState.Hidden, - val deviceRotation: DeviceRotation = DeviceRotation.Natural + val cameraErrorUiState: CameraErrorUiState = CameraErrorUiState.Hidden ) : CaptureUiState companion object diff --git a/ui/uistateadapter/capture/src/main/java/com/google/jetpackcamera/ui/uistateadapter/capture/compound/CaptureUiStateAdapter.kt b/ui/uistateadapter/capture/src/main/java/com/google/jetpackcamera/ui/uistateadapter/capture/compound/CaptureUiStateAdapter.kt index 726016dca4..222f1bc348 100644 --- a/ui/uistateadapter/capture/src/main/java/com/google/jetpackcamera/ui/uistateadapter/capture/compound/CaptureUiStateAdapter.kt +++ b/ui/uistateadapter/capture/src/main/java/com/google/jetpackcamera/ui/uistateadapter/capture/compound/CaptureUiStateAdapter.kt @@ -17,7 +17,6 @@ package com.google.jetpackcamera.ui.uistateadapter.capture.compound import com.google.jetpackcamera.core.camera.CameraState import com.google.jetpackcamera.core.camera.VideoRecordingState -import com.google.jetpackcamera.model.DeviceRotation import com.google.jetpackcamera.model.ExternalCaptureMode import com.google.jetpackcamera.settings.model.CameraAppSettings import com.google.jetpackcamera.settings.model.CameraFeaturePolicy @@ -81,7 +80,6 @@ fun captureUiState( ): Flow { var flashModeUiState: FlashModeUiState? = null var focusMeteringUiState: FocusMeteringUiState? = null - var lockedDeviceRotation: DeviceRotation? = null return combine( currentSettings.filterNotNull(), @@ -94,17 +92,6 @@ fun captureUiState( roundVideoRecordingState(videoRecordingState, timePrecision) val roundedCameraState = cameraState.copy(videoRecordingState = roundedVideoRecordingState) - val effectiveDeviceRotation = if ( - roundedVideoRecordingState !is VideoRecordingState.Inactive - ) { - lockedDeviceRotation ?: cameraAppSettings.deviceRotation.also { - lockedDeviceRotation = it - } - } else { - lockedDeviceRotation = null - cameraAppSettings.deviceRotation - } - val captureModeUiState = CaptureModeUiState.from( systemConstraints = systemConstraints, cameraAppSettings = cameraAppSettings, @@ -208,8 +195,7 @@ fun captureUiState( roundedVideoRecordingState ), screenFlashUiState = ScreenFlashUiState.from(trackedUiState), - cameraErrorUiState = CameraErrorUiState.from(roundedCameraState), - deviceRotation = effectiveDeviceRotation + cameraErrorUiState = CameraErrorUiState.from(roundedCameraState) ) } } diff --git a/ui/uistateadapter/capture/src/test/java/com/google/jetpackcamera/ui/uistateadapter/capture/CaptureUiStateAdapterTest.kt b/ui/uistateadapter/capture/src/test/java/com/google/jetpackcamera/ui/uistateadapter/capture/CaptureUiStateAdapterTest.kt index 4d14922528..96fe41f544 100644 --- a/ui/uistateadapter/capture/src/test/java/com/google/jetpackcamera/ui/uistateadapter/capture/CaptureUiStateAdapterTest.kt +++ b/ui/uistateadapter/capture/src/test/java/com/google/jetpackcamera/ui/uistateadapter/capture/CaptureUiStateAdapterTest.kt @@ -17,12 +17,10 @@ package com.google.jetpackcamera.ui.uistateadapter.capture import com.google.common.truth.Truth.assertThat import com.google.jetpackcamera.core.camera.AudioStreamState -import com.google.jetpackcamera.core.camera.CameraState import com.google.jetpackcamera.core.camera.VideoRecordingState import com.google.jetpackcamera.core.camera.testing.FakeCameraSystem import com.google.jetpackcamera.model.AspectRatio import com.google.jetpackcamera.model.CaptureMode -import com.google.jetpackcamera.model.DeviceRotation import com.google.jetpackcamera.model.DynamicRange import com.google.jetpackcamera.model.ExternalCaptureMode import com.google.jetpackcamera.model.FlashMode @@ -309,48 +307,6 @@ internal class CaptureUiStateAdapterTest { ) } - @Test - fun captureUiState_deviceRotation_freezesWhileRecordingAndUnlocksWhenInactive() = runTest { - val uiStateFlow = createCaptureUiStateFlow() - val states = mutableListOf() - backgroundScope.launch { - uiStateFlow.collect { states.add(it) } - } - - runCurrent() - assertThat(assertIsReady(states.last()).deviceRotation).isEqualTo(DeviceRotation.Natural) - - // Rotate to landscape while idle -> updates immediately - cameraSystem.setDeviceRotation(DeviceRotation.Rotated270) - runCurrent() - assertThat(assertIsReady(states.last()).deviceRotation).isEqualTo(DeviceRotation.Rotated270) - - // Start video recording -> locks at Rotated270 - cameraSystem.setCurrentCameraState( - CameraState( - videoRecordingState = VideoRecordingState.Active.Recording( - maxDurationMillis = 0L, - audioStreamState = AudioStreamState.Active(0.0), - elapsedTimeNanos = 1_000_000_000L - ) - ) - ) - runCurrent() - assertThat(assertIsReady(states.last()).deviceRotation).isEqualTo(DeviceRotation.Rotated270) - - // Rotate physical device to Natural during active recording -> UI state stays Rotated270 - cameraSystem.setDeviceRotation(DeviceRotation.Natural) - runCurrent() - assertThat(assertIsReady(states.last()).deviceRotation).isEqualTo(DeviceRotation.Rotated270) - - // Stop video recording -> unlocks and updates to Natural - cameraSystem.setCurrentCameraState( - CameraState(videoRecordingState = VideoRecordingState.Inactive()) - ) - runCurrent() - assertThat(assertIsReady(states.last()).deviceRotation).isEqualTo(DeviceRotation.Natural) - } - private fun assertIsReady(uiState: CaptureUiState): CaptureUiState.Ready = when (uiState) { is CaptureUiState.Ready -> uiState else -> throw AssertionError( From 93bb408ffb8df02872da1382e161aaf77b339cbf Mon Sep 17 00:00:00 2001 From: davidjiagoogle Date: Fri, 23 Oct 2026 00:20:25 +0000 Subject: [PATCH 3/4] Keep ToggleSwitch thumb position aligned with switchWidthPx --- .../ui/components/capture/ToggleSwitch.kt | 27 ++++++------------- 1 file changed, 8 insertions(+), 19 deletions(-) diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ToggleSwitch.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ToggleSwitch.kt index 540aff9986..471c8f969d 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ToggleSwitch.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ToggleSwitch.kt @@ -107,16 +107,13 @@ fun ToggleSwitch( // --- 2. Drag and Animation State --- var dragOffset by remember { mutableFloatStateOf(0f) } - var canvasWidthPx by remember(dims.switchWidthPx) { mutableFloatStateOf(dims.switchWidthPx) } - val effectiveDragRange = - (canvasWidthPx - dims.paddingPx - dims.thumbRadiusPx - dims.startX).coerceAtLeast(1f) val targetPosition = if (checked) 1f else 0f val disableAnimations = LocalDisableAnimations.current // Animate the thumb position. // This snaps (0ms) during drag and animates (300ms) on tap or drag release. val animatedPosition by animateFloatAsState( - targetValue = (targetPosition + (dragOffset / effectiveDragRange)).coerceIn(0f, 1f), + targetValue = (targetPosition + (dragOffset / dims.dragRange)).coerceIn(0f, 1f), animationSpec = if (disableAnimations) { snap() } else { @@ -126,7 +123,7 @@ fun ToggleSwitch( }, label = "thumbPosition" ) - val initialThumbX = dims.startX + effectiveDragRange * animatedPosition + val initialThumbX = dims.startX + dims.dragRange * animatedPosition // --- 3. Color Animations --- // color changes if togglemode is off (to indicate on/off state) @@ -150,8 +147,8 @@ fun ToggleSwitch( val draggableState = rememberDraggableState { delta -> val newOffset = dragOffset + delta // Constrain drag within the allowed range based on the *current* state - val dragMin = if (checked) -effectiveDragRange else 0f - val dragMax = if (checked) 0f else effectiveDragRange + val dragMin = if (checked) -dims.dragRange else 0f + val dragMax = if (checked) 0f else dims.dragRange dragOffset = newOffset.coerceIn(dragMin, dragMax) } @@ -172,7 +169,7 @@ fun ToggleSwitch( onDragStopped = { // Determine new state based on final drag position val finalThumbPos = initialThumbX - dims.startX - val newCheckedState = finalThumbPos > (effectiveDragRange / 2) + val newCheckedState = finalThumbPos > (dims.dragRange / 2) if (newCheckedState != checked) { onCheckedChange(newCheckedState) } @@ -198,12 +195,6 @@ fun ToggleSwitch( .size(dims.switchWidthDp, dims.switchHeightDp) .then(gestureModifier) ) { - if (canvasWidthPx != size.width && size.width > 0f) { - canvasWidthPx = size.width - } - val endX = (size.width - dims.paddingPx - dims.thumbRadiusPx).coerceAtLeast(dims.startX) - val thumbX = dims.startX + (endX - dims.startX) * animatedPosition - // 1. Draw the Track drawSwitchTrack( color = trackAnimatedColor, @@ -212,16 +203,16 @@ fun ToggleSwitch( // 2. Calculate Thumb Rect and Icon Padding val thumbRect = Rect( - left = thumbX - dims.thumbRadiusPx, + left = initialThumbX - dims.thumbRadiusPx, top = thumbY - dims.thumbRadiusPx, - right = thumbX + dims.thumbRadiusPx, + right = initialThumbX + dims.thumbRadiusPx, bottom = thumbY + dims.thumbRadiusPx ) val iconPadding = (dims.switchHeightPx - dims.iconSizePx) / 2 // 4. Draw the Thumb (under Icons) drawSwitchThumb( - center = Offset(thumbX, thumbY), + center = Offset(initialThumbX, thumbY), radius = dims.thumbRadiusPx, color = thumbAnimatedColor ) @@ -265,7 +256,6 @@ private class SwitchDimensions( val switchWidthPx: Float, val switchHeightPx: Float, val thumbRadiusPx: Float, - val paddingPx: Float, val iconSizePx: Float, val startX: Float, val dragRange: Float @@ -299,7 +289,6 @@ private fun rememberSwitchDimensions( switchWidthPx = switchWidthPx, switchHeightPx = switchHeightPx, thumbRadiusPx = thumbRadiusPx, - paddingPx = paddingPx, iconSizePx = iconSizePx, startX = startX, dragRange = dragRange From 8108b9104d7d95dde258d1e9b870f78dd8169f5e Mon Sep 17 00:00:00 2001 From: davidjiagoogle Date: Tue, 10 Nov 2026 01:36:17 +0000 Subject: [PATCH 4/4] Address PR review feedback for phone landscape mode --- .../core/camera/CameraSession.kt | 6 + .../jetpackcamera/model/DeviceRotation.kt | 3 +- .../jetpackcamera/model/DeviceRotationTest.kt | 12 +- .../feature/preview/PreviewScreen.kt | 28 +- .../ui/components/capture/CaptureLayout.kt | 425 +++++++++--------- .../components/capture/RotationModifiers.kt | 14 +- .../capture/CaptureLayoutInsetsTest.kt | 45 ++ 7 files changed, 311 insertions(+), 222 deletions(-) diff --git a/core/camera/src/main/java/com/google/jetpackcamera/core/camera/CameraSession.kt b/core/camera/src/main/java/com/google/jetpackcamera/core/camera/CameraSession.kt index 858edc805f..d76bd06086 100644 --- a/core/camera/src/main/java/com/google/jetpackcamera/core/camera/CameraSession.kt +++ b/core/camera/src/main/java/com/google/jetpackcamera/core/camera/CameraSession.kt @@ -878,6 +878,12 @@ private fun createPreviewUseCase( stabilizationMode: StabilizationMode, captureResults: MutableStateFlow? = null ): Preview = Preview.Builder().apply { + // Phone landscape counter-rotates the UI and PreviewDisplay back into a canonical portrait + // (ROTATION_0) coordinate frame. Pin Preview's target rotation to ROTATION_0 so ViewPort crop + // rects and StreamSharing buffers remain aligned with the portrait viewfinder even when bound + // while the OS window is in landscape. Upright large-screen / multi-window layouts will drive + // Preview and ViewPort from a dedicated window/viewfinder rotation distinct from the sensor- + // based deviceRotation used for ImageCapture and VideoCapture EXIF orientation. setTargetRotation(Surface.ROTATION_0) updateCameraStateWithCaptureResults( targetCameraInfo = cameraInfo, diff --git a/core/model/src/main/java/com/google/jetpackcamera/model/DeviceRotation.kt b/core/model/src/main/java/com/google/jetpackcamera/model/DeviceRotation.kt index d2f6e7d937..7dbf993ce5 100644 --- a/core/model/src/main/java/com/google/jetpackcamera/model/DeviceRotation.kt +++ b/core/model/src/main/java/com/google/jetpackcamera/model/DeviceRotation.kt @@ -81,7 +81,8 @@ enum class DeviceRotation { get() = this == Rotated90 || this == Rotated270 companion object { - fun fromSurfaceRotation(surfaceRotation: Int): DeviceRotation { + /** Returns the [DeviceRotation] corresponding to a UI [Surface] rotation constant. */ + fun fromUiSurfaceRotation(surfaceRotation: Int): DeviceRotation { return when (surfaceRotation) { Surface.ROTATION_0 -> Natural Surface.ROTATION_90 -> Rotated270 diff --git a/core/model/src/test/java/com/google/jetpackcamera/model/DeviceRotationTest.kt b/core/model/src/test/java/com/google/jetpackcamera/model/DeviceRotationTest.kt index c73bd2027b..ca27cfd372 100644 --- a/core/model/src/test/java/com/google/jetpackcamera/model/DeviceRotationTest.kt +++ b/core/model/src/test/java/com/google/jetpackcamera/model/DeviceRotationTest.kt @@ -58,18 +58,18 @@ class DeviceRotationTest { } @Test - fun fromSurfaceRotation_isInverseOfToUiSurfaceRotation() { + fun fromUiSurfaceRotation_isInverseOfToUiSurfaceRotation() { for (rotation in DeviceRotation.entries) { val surfaceRotation = rotation.toUiSurfaceRotation() - assertThat(DeviceRotation.fromSurfaceRotation(surfaceRotation)).isEqualTo(rotation) + assertThat(DeviceRotation.fromUiSurfaceRotation(surfaceRotation)).isEqualTo(rotation) } - assertThat(DeviceRotation.fromSurfaceRotation(Surface.ROTATION_0)) + assertThat(DeviceRotation.fromUiSurfaceRotation(Surface.ROTATION_0)) .isEqualTo(DeviceRotation.Natural) - assertThat(DeviceRotation.fromSurfaceRotation(Surface.ROTATION_90)) + assertThat(DeviceRotation.fromUiSurfaceRotation(Surface.ROTATION_90)) .isEqualTo(DeviceRotation.Rotated270) - assertThat(DeviceRotation.fromSurfaceRotation(Surface.ROTATION_180)) + assertThat(DeviceRotation.fromUiSurfaceRotation(Surface.ROTATION_180)) .isEqualTo(DeviceRotation.Rotated180) - assertThat(DeviceRotation.fromSurfaceRotation(Surface.ROTATION_270)) + assertThat(DeviceRotation.fromUiSurfaceRotation(Surface.ROTATION_270)) .isEqualTo(DeviceRotation.Rotated90) } } diff --git a/feature/preview/src/main/java/com/google/jetpackcamera/feature/preview/PreviewScreen.kt b/feature/preview/src/main/java/com/google/jetpackcamera/feature/preview/PreviewScreen.kt index 7fb6db9410..124c1af5ae 100644 --- a/feature/preview/src/main/java/com/google/jetpackcamera/feature/preview/PreviewScreen.kt +++ b/feature/preview/src/main/java/com/google/jetpackcamera/feature/preview/PreviewScreen.kt @@ -16,6 +16,8 @@ package com.google.jetpackcamera.feature.preview import android.app.Activity +import android.content.Context +import android.content.ContextWrapper import android.content.pm.ActivityInfo import android.util.Log import android.util.Range @@ -257,19 +259,21 @@ private fun ContentScreen( } val context = LocalContext.current - DisposableEffect(context) { - val activity = context as? Activity - onDispose { - activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_USER + DisposableEffect(context, isVideoRecordingInProgress.value) { + val activity = context.findActivity() + if (activity != null && isVideoRecordingInProgress.value) { + val previousOrientation = activity.requestedOrientation + activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LOCKED + onDispose { + activity.requestedOrientation = previousOrientation + } + } else { + onDispose {} } } LaunchedEffect(isVideoRecordingInProgress.value, cameraController) { - val activity = context as? Activity - if (isVideoRecordingInProgress.value) { - activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LOCKED - } else { - activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_USER + if (!isVideoRecordingInProgress.value) { cameraController?.let { controller -> debouncedOrientationFlow(context).collect(controller::setDisplayRotation) } @@ -1060,3 +1064,9 @@ private val FAKE_PREVIEW_UI_STATE_LOCKED_RECORDING = FAKE_PREVIEW_UI_STATE_READY captureButtonUiState = CaptureButtonUiState.Enabled.Recording.LockedRecording, audioUiState = AudioUiState.Enabled.On(1.0, true) ) + +private tailrec fun Context.findActivity(): Activity? = when (this) { + is Activity -> this + is ContextWrapper -> baseContext.findActivity() + else -> null +} diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CaptureLayout.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CaptureLayout.kt index 72ee6339f6..9f18771f08 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CaptureLayout.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CaptureLayout.kt @@ -24,6 +24,7 @@ import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.IntrinsicSize @@ -142,244 +143,264 @@ fun PreviewLayout( deviceRotation: DeviceRotation? = null ) { val windowRotation = rememberWindowRotation() - val uiRotation = deviceRotation ?: windowRotation - val disableAnimations = LocalDisableAnimations.current - val isSheetVisible = scaffoldState.bottomSheetState.isVisible || - scaffoldState.bottomSheetState.targetValue == SheetValue.Expanded - var displayedSheetRotation by remember { mutableStateOf(uiRotation) } - val sheetContentAlpha = remember { Animatable(1f) } + BoxWithConstraints(modifier = modifier.fillMaxSize()) { + val windowWidth = maxWidth + val windowHeight = maxHeight + // Only counter-rotate when the window itself is landscape-shaped (width > height) so that + // portrait multi-window panes on a landscape display stay upright. + val effectiveWindowRotation = + if (windowWidth > windowHeight && windowRotation.isLandscape) { + windowRotation + } else { + DeviceRotation.Natural + } + val uiRotation = deviceRotation ?: effectiveWindowRotation + val disableAnimations = LocalDisableAnimations.current + val isSheetVisible = scaffoldState.bottomSheetState.isVisible || + scaffoldState.bottomSheetState.targetValue == SheetValue.Expanded + var displayedSheetRotation by remember { mutableStateOf(uiRotation) } + val sheetContentAlpha = remember { Animatable(1f) } - LaunchedEffect(uiRotation, isSheetVisible, disableAnimations) { - if (displayedSheetRotation != uiRotation) { - if (isSheetVisible && !disableAnimations) { - sheetContentAlpha.animateTo( - targetValue = 0f, - animationSpec = tween( - durationMillis = QUICK_SETTINGS_FADE_DURATION_MS, - easing = FastOutSlowInEasing + LaunchedEffect(uiRotation, isSheetVisible, disableAnimations) { + if (displayedSheetRotation != uiRotation) { + if (isSheetVisible && !disableAnimations) { + sheetContentAlpha.animateTo( + targetValue = 0f, + animationSpec = tween( + durationMillis = QUICK_SETTINGS_FADE_DURATION_MS, + easing = FastOutSlowInEasing + ) ) - ) - displayedSheetRotation = uiRotation - delay(QUICK_SETTINGS_RESIZE_DURATION_MS.toLong()) - sheetContentAlpha.animateTo( - targetValue = 1f, - animationSpec = tween( - durationMillis = QUICK_SETTINGS_FADE_DURATION_MS, - easing = FastOutSlowInEasing + displayedSheetRotation = uiRotation + delay(QUICK_SETTINGS_RESIZE_DURATION_MS.toLong()) + sheetContentAlpha.animateTo( + targetValue = 1f, + animationSpec = tween( + durationMillis = QUICK_SETTINGS_FADE_DURATION_MS, + easing = FastOutSlowInEasing + ) ) - ) - } else { - displayedSheetRotation = uiRotation + } else { + displayedSheetRotation = uiRotation + sheetContentAlpha.snapTo(1f) + } + } else if (sheetContentAlpha.value < 1f && (!isSheetVisible || disableAnimations)) { sheetContentAlpha.snapTo(1f) } - } else if (sheetContentAlpha.value < 1f && (!isSheetVisible || disableAnimations)) { - sheetContentAlpha.snapTo(1f) } - } - val overlapTargetBounds = remember { mutableStateOf(Rect.Zero) } - val dismissQuickSettingsLabel = - stringResource(R.string.quick_settings_btn_close_expanded_settings_description) - val consumeRemainingScrollConnection = remember { - object : NestedScrollConnection { - override fun onPostScroll( - consumed: Offset, - available: Offset, - source: NestedScrollSource - ): Offset = available + val overlapTargetBounds = remember { mutableStateOf(Rect.Zero) } + val dismissQuickSettingsLabel = + stringResource(R.string.quick_settings_btn_close_expanded_settings_description) + val consumeRemainingScrollConnection = remember { + object : NestedScrollConnection { + override fun onPostScroll( + consumed: Offset, + available: Offset, + source: NestedScrollSource + ): Offset = available - override suspend fun onPostFling(consumed: Velocity, available: Velocity): Velocity = - available + override suspend fun onPostFling( + consumed: Velocity, + available: Velocity + ): Velocity = available + } } - } - CompositionLocalProvider( - LocalOverlapTargetBounds provides overlapTargetBounds, - LocalDeviceRotation provides uiRotation, - LocalWindowRotation provides windowRotation - ) { - Box( - modifier = modifier - .fillMaxSize() - .counterRotateToPortrait(windowRotation) + CompositionLocalProvider( + LocalOverlapTargetBounds provides overlapTargetBounds, + LocalDeviceRotation provides uiRotation, + LocalWindowRotation provides effectiveWindowRotation ) { - BottomSheetScaffold( - modifier = Modifier.fillMaxSize(), - scaffoldState = scaffoldState, - sheetPeekHeight = 0.dp, - sheetDragHandle = { - BottomSheetDefaults.DragHandle( - modifier = Modifier - .testTag(QUICK_SETTINGS_DRAG_HANDLE) - .clickable( - role = Role.Button, - onClickLabel = dismissQuickSettingsLabel, - onClick = onDismissQuickSettings - ) - ) - }, - sheetShape = RoundedCornerShape(topStart = 28.dp, topEnd = 28.dp), - sheetContainerColor = MaterialTheme.colorScheme.surfaceContainerLow, - sheetContent = { - CompositionLocalProvider(LocalDeviceRotation provides displayedSheetRotation) { - Box( + Box( + modifier = Modifier + .fillMaxSize() + .counterRotateToPortrait(effectiveWindowRotation) + ) { + BottomSheetScaffold( + modifier = Modifier.fillMaxSize(), + scaffoldState = scaffoldState, + sheetPeekHeight = 0.dp, + sheetDragHandle = { + BottomSheetDefaults.DragHandle( modifier = Modifier - .fillMaxWidth() - .then( - if (disableAnimations) { - Modifier - } else { - Modifier.animateContentSize( - animationSpec = tween( - durationMillis = QUICK_SETTINGS_RESIZE_DURATION_MS, - easing = FastOutSlowInEasing - ) - ) - } + .testTag(QUICK_SETTINGS_DRAG_HANDLE) + .clickable( + role = Role.Button, + onClickLabel = dismissQuickSettingsLabel, + onClick = onDismissQuickSettings ) - .graphicsLayer { - alpha = sheetContentAlpha.value - } + ) + }, + sheetShape = RoundedCornerShape(topStart = 28.dp, topEnd = 28.dp), + sheetContainerColor = MaterialTheme.colorScheme.surfaceContainerLow, + sheetContent = { + CompositionLocalProvider( + LocalDeviceRotation provides displayedSheetRotation ) { - if (displayedSheetRotation.isLandscape) { - Box( - modifier = Modifier - .fillMaxWidth() - .heightIn(max = QuickSettingsLandscapeMaxSheetHeight) - .nestedScroll(consumeRemainingScrollConnection) - .rotatedLayout(displayedSheetRotation), - contentAlignment = Alignment.TopStart - ) { + Box( + modifier = Modifier + .fillMaxWidth() + .then( + if (disableAnimations) { + Modifier + } else { + Modifier.animateContentSize( + animationSpec = tween( + durationMillis = + QUICK_SETTINGS_RESIZE_DURATION_MS, + easing = FastOutSlowInEasing + ) + ) + } + ) + .graphicsLayer { + alpha = sheetContentAlpha.value + } + ) { + if (displayedSheetRotation.isLandscape) { + Box( + modifier = Modifier + .fillMaxWidth() + .heightIn(max = QuickSettingsLandscapeMaxSheetHeight) + .nestedScroll(consumeRemainingScrollConnection) + .rotatedLayout(displayedSheetRotation), + contentAlignment = Alignment.TopStart + ) { + quickSettingsOverlay(Modifier) + } + } else { quickSettingsOverlay(Modifier) } + } + } + }, + snackbarHost = {} + ) { + val portraitCutoutInsets = WindowInsets.displayCutout.toPortraitWindowInsets( + effectiveWindowRotation + ) + val portraitSystemBarsAndCutoutInsets = + WindowInsets.systemBarsIgnoringVisibility + .union(WindowInsets.displayCutout) + .toPortraitWindowInsets(effectiveWindowRotation) + + Box(modifier = Modifier.fillMaxSize().background(Color.Black)) { + Column { + // The indicator row occupies the top bar real estate in the hidden + // status bar region. We size the top bar to accommodate any top display + // cutout or the minimum interactive touch target (defaulting to 48dp), + // while CutoutAwareRow shifts individual indicator icons around any + // intersecting cutout bounds. + val cutoutTopInset = + portraitCutoutInsets.asPaddingValues().calculateTopPadding() + val minTouchTarget = + LocalMinimumInteractiveComponentSize.current.takeOrElse { 48.dp } + val topBarHeight = max(cutoutTopInset, minTouchTarget) + Box( + modifier = Modifier + .fillMaxWidth() + .height(topBarHeight) + .windowInsetsPadding( + portraitCutoutInsets.only(WindowInsetsSides.Horizontal) + ) + .padding(horizontal = 16.dp), + contentAlignment = Alignment.CenterStart + ) { + indicatorRow(Modifier) + } + val topStartAlignment = if (uiRotation == DeviceRotation.Rotated270) { + Alignment.TopEnd } else { - quickSettingsOverlay(Modifier) + Alignment.TopStart + } + Box { + viewfinder(Modifier) + topStartContent( + Modifier + .align(topStartAlignment) + .animateToUpright(uiRotation) + ) } } - } - }, - snackbarHost = {} - ) { - val portraitCutoutInsets = WindowInsets.displayCutout.toPortraitWindowInsets( - windowRotation - ) - val portraitSystemBarsAndCutoutInsets = WindowInsets.systemBarsIgnoringVisibility - .union(WindowInsets.displayCutout) - .toPortraitWindowInsets(windowRotation) - Box(modifier = Modifier.fillMaxSize().background(Color.Black)) { - Column { - // The indicator row occupies the top bar real estate in the hidden status - // bar region. We size the top bar to accommodate any top display cutout or - // the minimum interactive touch target (defaulting to 48dp), while - // CutoutAwareRow shifts individual indicator icons around any intersecting - // cutout bounds. - val cutoutTopInset = - portraitCutoutInsets.asPaddingValues().calculateTopPadding() - val minTouchTarget = - LocalMinimumInteractiveComponentSize.current.takeOrElse { 48.dp } - val topBarHeight = max(cutoutTopInset, minTouchTarget) Box( modifier = Modifier - .fillMaxWidth() - .height(topBarHeight) + .fillMaxSize() .windowInsetsPadding( - portraitCutoutInsets.only(WindowInsetsSides.Horizontal) + portraitSystemBarsAndCutoutInsets.only( + WindowInsetsSides.Vertical + ) ) - .padding(horizontal = 16.dp), - contentAlignment = Alignment.CenterStart ) { - indicatorRow(Modifier) - } - val topStartAlignment = if (uiRotation == DeviceRotation.Rotated270) { - Alignment.TopEnd - } else { - Alignment.TopStart - } - Box { - viewfinder(Modifier) - topStartContent( - Modifier - .align(topStartAlignment) - .animateToUpright(uiRotation) - ) - } - } - - Box( - modifier = Modifier - .fillMaxSize() - .windowInsetsPadding( - portraitSystemBarsAndCutoutInsets.only(WindowInsetsSides.Vertical) - ) - ) { - debugVisibilityWrapper { - VerticalMaterialControls( - captureButton = captureButton, - imageWell = imageWell, - flipCameraButton = flipCameraButton, - quickSettingsToggleButton = quickSettingsButton, - captureModeToggleSwitch = captureModeToggle, - zoomControls = zoomLevelDisplay, - elapsedTimeDisplay = { elapsedTimeModifier -> - if (!uiRotation.isLandscape) { - elapsedTimeDisplay(elapsedTimeModifier) + debugVisibilityWrapper { + VerticalMaterialControls( + captureButton = captureButton, + imageWell = imageWell, + flipCameraButton = flipCameraButton, + quickSettingsToggleButton = quickSettingsButton, + captureModeToggleSwitch = captureModeToggle, + zoomControls = zoomLevelDisplay, + elapsedTimeDisplay = { elapsedTimeModifier -> + if (!uiRotation.isLandscape) { + elapsedTimeDisplay(elapsedTimeModifier) + } + }, + snackbarHost = { snackbarModifier -> + if (!uiRotation.isLandscape) { + PillSnackbarHost( + snackbarHostState = scaffoldState.snackbarHostState, + modifier = snackbarModifier + ) + } } - }, - snackbarHost = { snackbarModifier -> - if (!uiRotation.isLandscape) { + ) + if (uiRotation.isLandscape) { + val landscapeTopAlignment = + if (uiRotation == DeviceRotation.Rotated270) { + Alignment.CenterStart + } else { + Alignment.CenterEnd + } + Column( + modifier = Modifier + .align(landscapeTopAlignment) + .rotatedLayout(uiRotation), + horizontalAlignment = Alignment.CenterHorizontally + ) { PillSnackbarHost( - snackbarHostState = scaffoldState.snackbarHostState, - modifier = snackbarModifier + snackbarHostState = scaffoldState.snackbarHostState ) + elapsedTimeDisplay(Modifier) } } - ) - if (uiRotation.isLandscape) { - val landscapeTopAlignment = - if (uiRotation == DeviceRotation.Rotated270) { - Alignment.CenterStart - } else { - Alignment.CenterEnd - } - Column( - modifier = Modifier - .align(landscapeTopAlignment) - .rotatedLayout(uiRotation), - horizontalAlignment = Alignment.CenterHorizontally - ) { - PillSnackbarHost( - snackbarHostState = scaffoldState.snackbarHostState - ) - elapsedTimeDisplay(Modifier) - } } + // controls overlay + snackBar(Modifier, scaffoldState.snackbarHostState) } - // controls overlay - snackBar(Modifier, scaffoldState.snackbarHostState) - } - debugOverlay(Modifier) + debugOverlay(Modifier) - if (isSheetVisible) { - Box( - modifier = Modifier - .fillMaxSize() - .testTag(QUICK_SETTINGS_SCRIM) - .clickable( - onClickLabel = dismissQuickSettingsLabel, - interactionSource = remember { MutableInteractionSource() }, - indication = null, - onClick = onDismissQuickSettings - ) - ) + if (isSheetVisible) { + Box( + modifier = Modifier + .fillMaxSize() + .testTag(QUICK_SETTINGS_SCRIM) + .clickable( + onClickLabel = dismissQuickSettingsLabel, + interactionSource = remember { MutableInteractionSource() }, + indication = null, + onClick = onDismissQuickSettings + ) + ) + } + errorDialog(Modifier) } - errorDialog(Modifier) } + // Drawn last and outside of both the inset-padded controls and the bottom sheet + // so that the flash covers the entire window, including the system bar and display + // cutout areas. + screenFlashOverlay(Modifier) } - // Drawn last and outside of both the inset-padded controls and the bottom sheet - // so that the flash covers the entire window, including the system bar and display - // cutout areas. - screenFlashOverlay(Modifier) } } } diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/RotationModifiers.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/RotationModifiers.kt index aa69024510..9c26efa96a 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/RotationModifiers.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/RotationModifiers.kt @@ -85,7 +85,7 @@ internal fun rememberWindowRotation(): DeviceRotation { } } - return DeviceRotation.fromSurfaceRotation(surfaceRotation) + return DeviceRotation.fromUiSurfaceRotation(surfaceRotation) } @Suppress("DEPRECATION") @@ -104,11 +104,13 @@ private fun Context.currentDisplayRotation(): Int { /** * Counter-rotates the root phone camera layout back to the device's canonical Portrait (`0°`) - * coordinate system whenever the OS window rotates. + * coordinate system whenever a landscape-shaped OS window (`width > height`) is rotated to a + * landscape orientation. */ internal fun Modifier.counterRotateToPortrait(windowRotation: DeviceRotation): Modifier = layout { measurable, constraints -> - val isLandscape = windowRotation.isLandscape + val isLandscape = + windowRotation.isLandscape && constraints.maxWidth > constraints.maxHeight val placeable = measurable.measure( if (isLandscape) { constraints.copy( @@ -137,7 +139,11 @@ internal fun Modifier.counterRotateToPortrait(windowRotation: DeviceRotation): M val offsetX = (layoutWidth - placeable.width) / 2 val offsetY = (layoutHeight - placeable.height) / 2 placeable.placeWithLayer(offsetX, offsetY) { - rotationZ = windowRotation.toWindowCounterRotationDegrees() + rotationZ = if (isLandscape) { + windowRotation.toWindowCounterRotationDegrees() + } else { + 0f + } } } } diff --git a/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/CaptureLayoutInsetsTest.kt b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/CaptureLayoutInsetsTest.kt index daf5612cf9..98dff93f55 100644 --- a/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/CaptureLayoutInsetsTest.kt +++ b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/CaptureLayoutInsetsTest.kt @@ -21,6 +21,7 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.statusBarsPadding import androidx.compose.ui.Modifier +import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalView import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.getUnclippedBoundsInRoot @@ -28,11 +29,13 @@ import androidx.compose.ui.test.junit4.v2.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onRoot import androidx.compose.ui.unit.DpRect +import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp import androidx.core.graphics.Insets import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import com.google.common.truth.Truth.assertThat +import com.google.jetpackcamera.model.DeviceRotation import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @@ -161,6 +164,48 @@ class CaptureLayoutInsetsTest { assertThat(overlayBounds).isEqualTo(rootBounds) } + @Test + fun counterRotateToPortrait_doesNotSwapConstraints_whenWindowIsPortraitShapedInLandscape() { + var measuredChildSize = IntSize.Zero + composeTestRule.setContent { + Box( + Modifier + .size(width = 300.dp, height = 500.dp) + .counterRotateToPortrait(DeviceRotation.Rotated270) + ) { + Box( + Modifier + .fillMaxSize() + .onSizeChanged { measuredChildSize = it } + ) + } + } + composeTestRule.waitForIdle() + + assertThat(measuredChildSize).isEqualTo(IntSize(300, 500)) + } + + @Test + fun counterRotateToPortrait_swapsConstraints_whenWindowIsLandscapeShapedInLandscape() { + var measuredChildSize = IntSize.Zero + composeTestRule.setContent { + Box( + Modifier + .size(width = 500.dp, height = 300.dp) + .counterRotateToPortrait(DeviceRotation.Rotated270) + ) { + Box( + Modifier + .fillMaxSize() + .onSizeChanged { measuredChildSize = it } + ) + } + } + composeTestRule.waitForIdle() + + assertThat(measuredChildSize).isEqualTo(IntSize(300, 500)) + } + private fun boundsOf( tag: String, view: View,