Skip to content

Commit

Permalink
Allow for a smooth rotation while running the app. Replaced the quick…
Browse files Browse the repository at this point in the history
…-settings lazy grid with a FlowRow as the grid was depending on screenWidth instead of constraints.

Open issues:
- Surface aspect ratio breaks when in non-initial orientation.
- small flash sometimes when doing orientation change
  • Loading branch information
JolandaVerhoef committed Mar 29, 2024
1 parent 46a3b36 commit 297999f
Show file tree
Hide file tree
Showing 9 changed files with 234 additions and 173 deletions.
2 changes: 1 addition & 1 deletion app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@
<profileable android:shell="true"/>
<activity
android:name=".MainActivity"
android:configChanges="orientation|screenSize|screenLayout|keyboard|keyboardHidden|navigation|uiMode|smallestScreenSize"
android:exported="true"
android:screenOrientation="nosensor"
android:theme="@style/Theme.JetpackCamera">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
Expand Down
4 changes: 3 additions & 1 deletion app/src/main/java/com/google/jetpackcamera/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
Expand Down Expand Up @@ -102,6 +103,7 @@ class MainActivity : ComponentActivity() {
}

is Success -> {
val previewMode = remember { getPreviewMode() }
// TODO(kimblebee@): add app setting to enable/disable dynamic color
JetpackCameraTheme(
darkTheme = isInDarkMode(uiState = uiState),
Expand All @@ -117,7 +119,7 @@ class MainActivity : ComponentActivity() {
) {
JcaApp(
onPreviewViewModel = { previewViewModel = it },
previewMode = getPreviewMode()
previewMode = previewMode
)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,24 +31,27 @@ import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.darkColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.LifecycleStartEffect
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.google.jetpackcamera.feature.preview.ui.BlinkState
import com.google.jetpackcamera.feature.preview.ui.CameraControlsOverlay
import com.google.jetpackcamera.feature.preview.ui.PreviewDisplay
import com.google.jetpackcamera.feature.preview.ui.ScreenFlashScreen
import com.google.jetpackcamera.feature.preview.ui.SmoothImmersiveRotationEffect
import com.google.jetpackcamera.feature.preview.ui.TestableToast
import com.google.jetpackcamera.feature.preview.ui.rotatedLayout
import com.google.jetpackcamera.feature.quicksettings.QuickSettingsScreenOverlay
import com.google.jetpackcamera.settings.model.AspectRatio
import com.google.jetpackcamera.settings.model.CaptureMode
Expand All @@ -71,13 +74,16 @@ fun PreviewScreen(
Log.d(TAG, "PreviewScreen")
onPreviewViewModel(viewModel)

val previewUiState: PreviewUiState by viewModel.previewUiState.collectAsState()
// For this screen, force an immersive view with smooth rotation.
SmoothImmersiveRotationEffect(LocalContext.current)

val previewUiState: PreviewUiState by viewModel.previewUiState.collectAsStateWithLifecycle()

val screenFlashUiState: ScreenFlash.ScreenFlashUiState
by viewModel.screenFlash.screenFlashUiState.collectAsState()
by viewModel.screenFlash.screenFlashUiState.collectAsStateWithLifecycle()

val surfaceRequest: SurfaceRequest?
by viewModel.surfaceRequest.collectAsState()
by viewModel.surfaceRequest.collectAsStateWithLifecycle()

LifecycleStartEffect(Unit) {
viewModel.startCamera()
Expand Down Expand Up @@ -163,7 +169,7 @@ private fun ContentScreen(
)

QuickSettingsScreenOverlay(
modifier = Modifier,
modifier = Modifier.rotatedLayout(),
isOpen = previewUiState.quickSettingsIsOpen,
toggleIsOpen = onToggleQuickSettings,
currentCameraSettings = previewUiState.currentCameraSettings,
Expand All @@ -175,6 +181,7 @@ private fun ContentScreen(
)
// relative-grid style overlay on top of preview display
CameraControlsOverlay(
modifier = Modifier.rotatedLayout(),
previewUiState = previewUiState,
onNavigateToSettings = onNavigateToSettings,
previewMode = previewMode,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,10 @@ import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.gestures.rememberTransformableState
import androidx.compose.foundation.gestures.transformable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Refresh
Expand All @@ -56,17 +54,20 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.layout
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.google.jetpackcamera.feature.preview.R
import com.google.jetpackcamera.feature.preview.VideoRecordingState
import com.google.jetpackcamera.settings.model.AspectRatio
import com.google.jetpackcamera.settings.model.Stabilization
import com.google.jetpackcamera.settings.model.SupportedStabilizationMode
import kotlin.math.roundToInt
import kotlinx.coroutines.CoroutineScope

private const val TAG = "PreviewScreen"
Expand Down Expand Up @@ -132,11 +133,12 @@ fun PreviewDisplay(
val currentOnFlipCamera by rememberUpdatedState(onFlipCamera)

surfaceRequest?.let {
BoxWithConstraints(
Modifier
Box(
modifier
.testTag(PREVIEW_DISPLAY)
.fillMaxSize()
.background(Color.Black)
.wrapContentSize()
.pointerInput(Unit) {
detectTapGestures(
onDoubleTap = { offset ->
Expand All @@ -145,28 +147,46 @@ fun PreviewDisplay(
currentOnFlipCamera()
}
)
},
}
.layout { measurable, constraints ->
val maxWidth = constraints.maxWidth.toFloat()
val maxHeight = constraints.maxHeight.toFloat()
val maxAspectRatio: Float = maxWidth / maxHeight
val aspectRatioFloat: Float = aspectRatio.ratio.toFloat()

val correctAspectRation = if (
(maxAspectRatio > 1 && aspectRatioFloat < 1) ||
(maxAspectRatio < 1 && aspectRatioFloat > 1)
) {
1 / aspectRatioFloat
} else {
aspectRatioFloat
}
val shouldUseMaxWidth = maxAspectRatio <= correctAspectRation
val width = if (shouldUseMaxWidth) maxWidth else maxHeight * correctAspectRation
val height =
if (!shouldUseMaxWidth) maxHeight else maxWidth / correctAspectRation

val placeable = measurable.measure(
Constraints.fixed(
width.roundToInt(),
height.roundToInt()
)
)

layout(placeable.width, placeable.height) {
placeable.place(0, 0)
}
}
.transformable(state = transformableState)
.alpha(blinkState.alpha),

contentAlignment = Alignment.Center
) {
val maxAspectRatio: Float = maxWidth / maxHeight
val aspectRatioFloat: Float = aspectRatio.ratio.toFloat()
val shouldUseMaxWidth = maxAspectRatio <= aspectRatioFloat
val width = if (shouldUseMaxWidth) maxWidth else maxHeight * aspectRatioFloat
val height = if (!shouldUseMaxWidth) maxHeight else maxWidth / aspectRatioFloat
Box(
modifier = Modifier
.width(width)
.height(height)
.transformable(state = transformableState)
.alpha(blinkState.alpha)

) {
CameraXViewfinder(
modifier = Modifier.fillMaxSize(),
surfaceRequest = it
)
}
CameraXViewfinder(
modifier = Modifier.fillMaxSize(),
surfaceRequest = it
)
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/*
* Copyright (C) 2024 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.feature.preview.ui

import android.content.Context
import android.content.ContextWrapper
import android.os.Build
import android.view.Surface
import android.view.WindowManager
import android.view.WindowManager.LayoutParams.ROTATION_ANIMATION_JUMPCUT
import android.view.WindowManager.LayoutParams.ROTATION_ANIMATION_SEAMLESS
import androidx.activity.ComponentActivity
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.layout
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.unit.Constraints
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat

/**
* As long as this composable is active, the window will go into immersive mode and prevents the
* rotation animation on configuration change. This will prevent the UI items from visually changing.
*
* When used in combination with a composable that renders the same UI in both landscape and portrait,
* it can create a smooth continuous feel between those two orientations.
*/
@Composable
fun SmoothImmersiveRotationEffect(context: Context) = DisposableEffect(context) {
var currentRotationAnimation: Int? = null
context.getActivity()?.window?.let { window ->
window.attributes = window.attributes.apply {
currentRotationAnimation = rotationAnimation
rotationAnimation = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
ROTATION_ANIMATION_SEAMLESS
} else {
ROTATION_ANIMATION_JUMPCUT
}
}
WindowCompat.getInsetsController(window, window.decorView).apply {
systemBarsBehavior =
WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
hide(WindowInsetsCompat.Type.systemBars())
}
}
onDispose {
context.getActivity()?.window?.let { window ->
if (currentRotationAnimation != null) {
window.attributes = window.attributes.apply {
rotationAnimation = WindowManager.LayoutParams.ROTATION_ANIMATION_ROTATE
}
}
WindowCompat.getInsetsController(window, window.decorView).apply {
show(WindowInsetsCompat.Type.systemBars())
}
}
}
}

/**
* Rotate a layout based on the current screen orientation. The UI will always be laid out in a way
* that width <= height, and rotated afterwards.
*/
@Composable
fun Modifier.rotatedLayout(): Modifier {
var currentOrientation by remember { mutableIntStateOf(Surface.ROTATION_0) }
val currentDegrees = currentOrientation * 90f
val newOrientation = LocalConfiguration.current.orientation
val display = LocalView.current.display
LaunchedEffect(newOrientation, display) {
val newRotation = display.rotation
if (currentOrientation != newRotation) {
currentOrientation = newRotation
}
}
return this then Modifier.fillMaxSize().layout { measurable, constraints ->
val height = maxOf(constraints.maxWidth, constraints.maxHeight)
val width = minOf(constraints.maxWidth, constraints.maxHeight)
val placeable = measurable.measure(
Constraints.fixed(width, height)
)
layout(placeable.width, placeable.height) {
placeable.placeWithLayer(0, 0) {
if (constraints.maxWidth > constraints.maxHeight) {
rotationZ = -currentDegrees
}
}
}
}
}

private fun Context.getActivity(): ComponentActivity? = when (this) {
is ComponentActivity -> this
is ContextWrapper -> baseContext.getActivity()
else -> null
}
Loading

0 comments on commit 297999f

Please sign in to comment.