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 0926fe121d..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 @@ -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.MainThread import androidx.annotation.OptIn import androidx.camera.camera2.interop.Camera2CameraControl @@ -877,6 +878,13 @@ 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, 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..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 @@ -49,7 +49,49 @@ 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 { + /** 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 + 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..ca27cfd372 --- /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 fromUiSurfaceRotation_isInverseOfToUiSurfaceRotation() { + for (rotation in DeviceRotation.entries) { + val surfaceRotation = rotation.toUiSurfaceRotation() + assertThat(DeviceRotation.fromUiSurfaceRotation(surfaceRotation)).isEqualTo(rotation) + } + assertThat(DeviceRotation.fromUiSurfaceRotation(Surface.ROTATION_0)) + .isEqualTo(DeviceRotation.Natural) + assertThat(DeviceRotation.fromUiSurfaceRotation(Surface.ROTATION_90)) + .isEqualTo(DeviceRotation.Rotated270) + assertThat(DeviceRotation.fromUiSurfaceRotation(Surface.ROTATION_180)) + .isEqualTo(DeviceRotation.Rotated180) + 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 99251cff4a..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 @@ -15,6 +15,10 @@ */ 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 import androidx.activity.compose.BackHandler @@ -38,6 +42,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 @@ -190,13 +195,6 @@ fun PreviewScreen( } } - val context = LocalContext.current - LaunchedEffect(Unit) { - debouncedOrientationFlow(context).collect( - viewModel.cameraController::setDisplayRotation - ) - } - ContentScreen( modifier = modifier, captureUiStateProvider = readyStateProvider, @@ -254,6 +252,33 @@ private fun ContentScreen( currentCaptureUiStateProvider().videoRecordingState is VideoRecordingState.Active } } + val isVideoRecordingInProgress = remember { + derivedStateOf { + currentCaptureUiStateProvider().videoRecordingState !is VideoRecordingState.Inactive + } + } + + val context = LocalContext.current + 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) { + if (!isVideoRecordingInProgress.value) { + cameraController?.let { controller -> + debouncedOrientationFlow(context).collect(controller::setDisplayRotation) + } + } + } val scope = rememberCoroutineScope() val zoomStateManager = remember(zoomController) { @@ -1039,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/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 ac83f5d7bb..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 @@ -15,11 +15,16 @@ */ 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 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 @@ -33,6 +38,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 @@ -52,19 +58,34 @@ 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 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 +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. @@ -118,119 +139,268 @@ 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? = null ) { - val overlapTargetBounds = remember { mutableStateOf(Rect.Zero) } - val dismissQuickSettingsLabel = - stringResource(R.string.quick_settings_btn_close_expanded_settings_description) + val windowRotation = rememberWindowRotation() + 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) } - CompositionLocalProvider(LocalOverlapTargetBounds provides overlapTargetBounds) { - Box(modifier = modifier.fillMaxSize()) { - 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 - ) + LaunchedEffect(uiRotation, isSheetVisible, disableAnimations) { + if (displayedSheetRotation != uiRotation) { + if (isSheetVisible && !disableAnimations) { + sheetContentAlpha.animateTo( + targetValue = 0f, + animationSpec = tween( + durationMillis = QUICK_SETTINGS_FADE_DURATION_MS, + easing = FastOutSlowInEasing + ) ) - }, - sheetShape = RoundedCornerShape(topStart = 28.dp, topEnd = 28.dp), - sheetContainerColor = MaterialTheme.colorScheme.surfaceContainerLow, - sheetContent = { - quickSettingsOverlay(Modifier) - }, - snackbarHost = {} + 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 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 + } + } + + CompositionLocalProvider( + LocalOverlapTargetBounds provides overlapTargetBounds, + LocalDeviceRotation provides uiRotation, + LocalWindowRotation provides effectiveWindowRotation + ) { + Box( + modifier = Modifier + .fillMaxSize() + .counterRotateToPortrait(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 = - WindowInsets.displayCutout.asPaddingValues().calculateTopPadding() - val minTouchTarget = - LocalMinimumInteractiveComponentSize.current.takeOrElse { 48.dp } - val topBarHeight = max(cutoutTopInset, minTouchTarget) - Box( + BottomSheetScaffold( + modifier = Modifier.fillMaxSize(), + scaffoldState = scaffoldState, + sheetPeekHeight = 0.dp, + sheetDragHandle = { + BottomSheetDefaults.DragHandle( modifier = Modifier - .fillMaxWidth() - .height(topBarHeight) - .windowInsetsPadding( - WindowInsets.displayCutout.only(WindowInsetsSides.Horizontal) + .testTag(QUICK_SETTINGS_DRAG_HANDLE) + .clickable( + role = Role.Button, + onClickLabel = dismissQuickSettingsLabel, + onClick = onDismissQuickSettings ) - .padding(horizontal = 16.dp), - contentAlignment = Alignment.CenterStart + ) + }, + sheetShape = RoundedCornerShape(topStart = 28.dp, topEnd = 28.dp), + sheetContainerColor = MaterialTheme.colorScheme.surfaceContainerLow, + sheetContent = { + CompositionLocalProvider( + LocalDeviceRotation provides displayedSheetRotation ) { - indicatorRow(Modifier) - } - Box { - viewfinder(Modifier) - topStartContent(Modifier.align(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) + } + } } - } - - Box( - modifier = Modifier - .fillMaxSize() - .windowInsetsPadding( - WindowInsets.systemBarsIgnoringVisibility - .union(WindowInsets.displayCutout) - ) + }, + snackbarHost = {} + ) { + val portraitCutoutInsets = WindowInsets.displayCutout.toPortraitWindowInsets( + effectiveWindowRotation + ) + val portraitSystemBarsAndCutoutInsets = + WindowInsets.systemBarsIgnoringVisibility + .union(WindowInsets.displayCutout) + .toPortraitWindowInsets(effectiveWindowRotation) - ) { - debugVisibilityWrapper { - VerticalMaterialControls( - captureButton = captureButton, - imageWell = imageWell, - flipCameraButton = flipCameraButton, - quickSettingsToggleButton = quickSettingsButton, - captureModeToggleSwitch = captureModeToggle, - zoomControls = zoomLevelDisplay, - elapsedTimeDisplay = elapsedTimeDisplay, - snackbarHost = { modifier -> - PillSnackbarHost( - snackbarHostState = scaffoldState.snackbarHostState, - modifier = modifier + 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 { + Alignment.TopStart + } + Box { + viewfinder(Modifier) + topStartContent( + Modifier + .align(topStartAlignment) + .animateToUpright(uiRotation) + ) + } } - // controls overlay - snackBar(Modifier, scaffoldState.snackbarHostState) - } - debugOverlay(Modifier) - val isSheetVisible = scaffoldState.bottomSheetState.isVisible || - scaffoldState.bottomSheetState.targetValue == SheetValue.Expanded - if (isSheetVisible) { Box( modifier = Modifier .fillMaxSize() - .testTag(QUICK_SETTINGS_SCRIM) - .clickable( - onClickLabel = dismissQuickSettingsLabel, - interactionSource = remember { MutableInteractionSource() }, - indication = null, - onClick = onDismissQuickSettings + .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) + } + }, + snackbarHost = { snackbarModifier -> + if (!uiRotation.isLandscape) { + PillSnackbarHost( + snackbarHostState = scaffoldState.snackbarHostState, + modifier = snackbarModifier + ) + } + } + ) + 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) + } + debugOverlay(Modifier) + + 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) } } } @@ -326,7 +496,6 @@ private fun VerticalMaterialControls( // capture mode toggle switch center Box( - modifier = Modifier.weight(1f), contentAlignment = Alignment.Center ) { OverlapAwareStyleProvider { 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 0ea0f6c894..a9b5182449 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 @@ -482,7 +482,9 @@ fun PauseResumeToggleButton( currentRecordingState !is VideoRecordingState.Active.Paused ) }, - modifier = modifier.size(size) + modifier = modifier + .size(size) + .animateToUpright() ) { Icon( modifier = Modifier @@ -538,6 +540,7 @@ fun AmplitudeToggleButton( FilledIconToggleButton( modifier = modifier .size(buttonSize) + .animateToUpright() .testTag(AUDIO_INPUT_TOGGLE) .semantics { stateDescription = if (audioUiState is AudioUiState.Enabled.On) { @@ -861,10 +864,7 @@ fun PreviewDisplay( contentAlignment = Alignment.Center ) { if (surfaceRequest != null) { - val implementationMode = when { - Build.VERSION.SDK_INT > 24 -> ImplementationMode.EXTERNAL - else -> ImplementationMode.EMBEDDED - } + val implementationMode = ImplementationMode.EMBEDDED DetectWindowColorModeChanges( surfaceRequest = surfaceRequest, @@ -993,7 +993,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 -> @@ -1075,7 +1077,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 -> @@ -1161,7 +1165,8 @@ fun FlipCameraButton( } val backgroundStyle = LocalCameraControlBackgroundStyle.current FilledIconButton( - modifier = modifier.size(56.dp), + modifier = modifier + .size(56.dp), onClick = onClick, enabled = enabled, shape = RoundedCornerShape(12.dp), @@ -1185,6 +1190,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 c862b47873..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 @@ -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,10 @@ fun CutoutAwareRow( ?.displayCutout?.boundingRects.orEmpty(), rowBoundsInWindow = rowBoundsInWindow, isRtl = isRtl, - rtlReferenceWidth = rtlReferenceWidth + rtlReferenceWidth = rtlReferenceWidth, + windowRotation = windowRotation, + fallbackViewWidth = view.width, + fallbackViewHeight = view.height ) // Convert vertically overlapping cutout rects into sorted horizontal keep-out ranges. @@ -226,23 +231,61 @@ internal fun resolveLocalCutoutRects( windowCutoutRects: List, rowBoundsInWindow: IntRect?, isRtl: Boolean, - rtlReferenceWidth: Int + rtlReferenceWidth: Int, + windowRotation: DeviceRotation = DeviceRotation.Natural, + fallbackViewWidth: Int = 0, + fallbackViewHeight: Int = 0 ): 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 ?: fallbackViewHeight + 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 ?: fallbackViewWidth + IntRect( + left = rect.top - refTop, + top = refRight - rect.right, + right = rect.bottom - refTop, + bottom = refRight - rect.left + ) + } + DeviceRotation.Rotated180 -> { + val refRight = bounds?.right ?: fallbackViewWidth + val refBottom = bounds?.bottom ?: fallbackViewHeight + 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 2f1a48a6fc..16028ddbb5 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 @@ -135,7 +135,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 new file mode 100644 index 0000000000..9c26efa96a --- /dev/null +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/RotationModifiers.kt @@ -0,0 +1,286 @@ +/* + * 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.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 +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 + +private const val UI_ROTATION_DURATION_MS = 250 + +/** + * Provides the current UI [DeviceRotation] 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.fromUiSurfaceRotation(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 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 && constraints.maxWidth > constraints.maxHeight + val placeable = measurable.measure( + if (isLandscape) { + constraints.copy( + minWidth = constraints.minHeight, + maxWidth = constraints.maxHeight, + minHeight = constraints.minWidth, + maxHeight = constraints.maxWidth + ) + } else { + constraints + } + ) + + val layoutWidth = if (isLandscape) { + placeable.height + } else { + placeable.width + } + val layoutHeight = if (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 = if (isLandscape) { + windowRotation.toWindowCounterRotationDegrees() + } else { + 0f + } + } + } + } + +/** + * 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 +): State { + 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) { + rememberUpdatedState(targetDegrees) + } else { + animatable.asState() + } +} + +/** + * 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.value + } + } + +/** + * 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..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 @@ -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.value, 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..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 @@ -158,7 +158,8 @@ private fun ZoomButton( ToggleButton( checked = isSelected, onCheckedChange = { onChangeZoom(targetZoom) }, - modifier = modifier.heightIn(buttonSize) + modifier = modifier + .heightIn(buttonSize) .semantics { testTag = getZoomButtonTestTag(targetZoom) // todo(kc): move to text resource @@ -179,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 4d60ff240d..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 @@ -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,16 @@ fun QuickSettingsScaffoldContent( showMoreSettingsButton: Boolean = true ) { if (quickSettingsUiState is QuickSettingsUiState.Available) { + val deviceRotation = LocalDeviceRotation.current Column( modifier = modifier .fillMaxWidth() + .verticalScroll(rememberScrollState()) .windowInsetsPadding(WindowInsets.navigationBarsIgnoringVisibility) - .padding(bottom = 24.dp) + .padding( + top = if (deviceRotation.isLandscape) 24.dp else 0.dp, + 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 f1cee35d32..14463b7ca6 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 @@ -88,6 +88,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.containerColor import com.google.jetpackcamera.ui.components.capture.quicksettings.CameraAspectRatio import com.google.jetpackcamera.ui.components.capture.quicksettings.CameraCaptureMode @@ -130,6 +131,7 @@ fun ToggleQuickSettingsButton( IconButton( modifier = modifier .size(buttonSize) + .animateToUpright() .testTag(QUICK_SETTINGS_DROP_DOWN) .semantics { testTag = QUICK_SETTINGS_DROP_DOWN @@ -541,7 +543,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()) ) @@ -593,6 +597,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/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, 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)) } }