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 351c078c37..b4664561fb 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 @@ -420,11 +420,14 @@ internal suspend fun runSingleCameraSession( .collectLatest { zoomState -> // TODO(b/405987189): remove checks after buggy zoomState is fixed if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { + // Ignore the initial 1.0f zoomState emitted on camera bind + // unless 1.0f is the actual target zoom for this lens. + val targetZoomRatio = + (transientSettings.value ?: currentTransientSettings) + .zoomRatios[camera.cameraInfo.appLensFacing] + ?: 1.0f if (zoomState.zoomRatio != 1.0f || - zoomState.zoomRatio == currentTransientSettings - .zoomRatios[ - currentTransientSettings.primaryLensFacing - ] + zoomState.zoomRatio == targetZoomRatio ) { currentCameraState.update { old -> old.copy( @@ -1503,9 +1506,28 @@ private fun Preview.Builder.updateCameraStateWithCaptureResults( ) { // update camerastate with zoom ratio val newZoomRatio = result.get(CaptureResult.CONTROL_ZOOM_RATIO) + val targetZoomRatio = + transientSettings.value?.zoomRatios?.get(targetCameraInfo.appLensFacing) + ?: 1.0f + val zoomState = targetCameraInfo.zoomState.value + val minZoom = zoomState?.minZoomRatio ?: 1.0f + val maxZoom = zoomState?.maxZoomRatio ?: 1.0f + val clampedTarget = targetZoomRatio.coerceIn(minZoom, maxZoom) + val isTargetEssentiallyOne = abs(clampedTarget - 1.0f) < 0.01f currentCameraState.update { old -> + val currentZoomRatio = old.zoomRatios[targetCameraInfo.appLensFacing] + // When a lens is newly bound, initial capture results emit the hardware + // default 1.0f before cameraControl.setZoomRatio(initialZoomRatio) takes + // effect in the repeating request. Ignore those initial 1.0f frames if + // the lens is restoring a non-1.0f target zoom so the UI doesn't flash 1x. + val isInitialDefaultEmission = + currentZoomRatio == null && + newZoomRatio != null && + abs(newZoomRatio - 1.0f) < 0.001f && + !isTargetEssentiallyOne if (newZoomRatio != null && - old.zoomRatios[targetCameraInfo.appLensFacing] != newZoomRatio + !isInitialDefaultEmission && + currentZoomRatio != newZoomRatio ) { old.copy( zoomRatios = old.zoomRatios 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 9fc7aebd88..3f12674ece 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 @@ -89,7 +89,7 @@ import com.google.jetpackcamera.ui.components.capture.StabilizationIcon import com.google.jetpackcamera.ui.components.capture.TestableSnackbar import com.google.jetpackcamera.ui.components.capture.VIDEO_QUALITY_TAG import com.google.jetpackcamera.ui.components.capture.VideoQualityIcon -import com.google.jetpackcamera.ui.components.capture.ZoomButtonRow +import com.google.jetpackcamera.ui.components.capture.ZoomBar import com.google.jetpackcamera.ui.components.capture.ZoomStateManager import com.google.jetpackcamera.ui.components.capture.debouncedOrientationFlow import com.google.jetpackcamera.ui.components.capture.quicksettings.QuickSettingsScaffoldContent @@ -526,7 +526,7 @@ internal fun ContentScreen( val zoomLevelDisplayLambda = remember(zoomControlState) { @Composable { modifier: Modifier -> Column(modifier = modifier, horizontalAlignment = Alignment.CenterHorizontally) { - ZoomButtonRow( + ZoomBar( zoomControlUiState = zoomControlState.value, onChangeZoom = { targetZoom -> scope.launch { 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 9fbedb4790..382daec52e 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 @@ -257,7 +257,9 @@ private fun VerticalMaterialControls( elapsedTimeDisplay(Modifier) // zoom controls row - zoomControls(Modifier) + OverlapAwareStyleProvider { + zoomControls(Modifier) + } // capture button row Column { Row( 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..42590e4793 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 @@ -15,22 +15,29 @@ */ package com.google.jetpackcamera.ui.components.capture -import androidx.compose.animation.animateContentSize +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.core.snap import androidx.compose.foundation.background +import androidx.compose.foundation.gestures.Orientation +import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.wrapContentSize +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.text.BasicText import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text -import androidx.compose.material3.ToggleButton -import androidx.compose.material3.ToggleButtonDefaults import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.Immutable import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.remember @@ -38,155 +45,461 @@ import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color -import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.graphics.lerp +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.onClick import androidx.compose.ui.semantics.semantics -import androidx.compose.ui.semantics.stateDescription import androidx.compose.ui.semantics.testTag +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.times import com.google.jetpackcamera.model.LensFacing import com.google.jetpackcamera.ui.uistate.capture.ZoomControlUiState -import java.math.RoundingMode -import java.text.DecimalFormat +import java.text.DecimalFormatSymbols +import java.util.Locale +import kotlin.math.abs +import kotlin.math.floor /** - * A composable that displays a row of zoom buttons. + * Styling configuration for [ZoomBar]. + * + * @param trackColor Background color of the stadium track capsule (e.g. 60% black over + * viewfinder, 20% white off viewfinder). + * @param selectedIndicatorColor Background color of the indicator pill behind the active stop (e.g. + * primaryFixed). + * @param selectedContentColor Text color for the currently selected stop (e.g. onPrimaryFixed). + * @param unselectedContentColor Text color for unselected stops (e.g. Color.White). + */ +@Immutable +data class ZoomBarColors( + val trackColor: Color, + val selectedIndicatorColor: Color, + val selectedContentColor: Color, + val unselectedContentColor: Color +) + +/** + * Default color palettes and dimensions for [ZoomBar]. + */ +object ZoomBarDefaults { + val SlotSize = 48.dp + val IndicatorHeight = ButtonDefaults.MinHeight // 40.dp + val Inset = (SlotSize - IndicatorHeight) / 2 // 4.dp + val TrackShape = CircleShape + const val MAX_LABEL_FONT_SCALE = 1.3f + + /** + * Default dynamic colors adapting to viewfinder overlap via [LocalCameraControlBackgroundStyle] + * and Material 3 theme color tokens. + */ + @Composable + fun colors( + trackColor: Color = LocalCameraControlBackgroundStyle.current.containerColor, + selectedIndicatorColor: Color = MaterialTheme.colorScheme.primaryFixed, + selectedContentColor: Color = MaterialTheme.colorScheme.onPrimaryFixed, + unselectedContentColor: Color = Color.White + ) = ZoomBarColors( + trackColor = trackColor, + selectedIndicatorColor = selectedIndicatorColor, + selectedContentColor = selectedContentColor, + unselectedContentColor = unselectedContentColor + ) + + /** + * Colors for overlapping the viewfinder (60% black background). + */ + @Composable + fun black60Colors( + trackColor: Color = CameraControlBackgroundStyle.BLACK_60.containerColor, + selectedIndicatorColor: Color = MaterialTheme.colorScheme.primaryFixed, + selectedContentColor: Color = MaterialTheme.colorScheme.onPrimaryFixed, + unselectedContentColor: Color = Color.White + ) = ZoomBarColors( + trackColor = trackColor, + selectedIndicatorColor = selectedIndicatorColor, + selectedContentColor = selectedContentColor, + unselectedContentColor = unselectedContentColor + ) + + /** + * Colors when not overlapping the viewfinder (lighter translucent background). + */ + @Composable + fun white20Colors( + trackColor: Color = CameraControlBackgroundStyle.WHITE_20.containerColor, + selectedIndicatorColor: Color = MaterialTheme.colorScheme.primaryFixed, + selectedContentColor: Color = MaterialTheme.colorScheme.onPrimaryFixed, + unselectedContentColor: Color = Color.White + ) = ZoomBarColors( + trackColor = trackColor, + selectedIndicatorColor = selectedIndicatorColor, + selectedContentColor = selectedContentColor, + unselectedContentColor = unselectedContentColor + ) +} + +/** + * Rounds a zoom ratio half-up to the nearest tenth. + */ +internal fun toTenths(value: Float): Int = floor(value * 10f + 0.5f).toInt() + +/** + * Determines the index of the selected zoom stop for a given [zoomRatio]. + * + * Stops are matched against the half-up rounded tenth of [zoomRatio]. If adjacent stops round + * to the same tenth (e.g. 0.96x and 1.0x both round to 1.0x), the stop closest in absolute + * difference to [zoomRatio] is selected. + */ +internal fun selectedZoomStopIndex(zoomLevels: List, zoomRatio: Float): Int { + if (zoomLevels.isEmpty()) return 0 + val checkTenths = toTenths(zoomRatio) + val index = zoomLevels.indexOfLast { zoomLevelOption -> + toTenths(zoomLevelOption) <= checkTenths + } + return if (index >= 0) { + if (index > 0 && + toTenths(zoomLevels[index]) == toTenths(zoomLevels[index - 1]) + ) { + val distCurrent = abs(zoomLevels[index] - zoomRatio) + val distPrev = abs(zoomLevels[index - 1] - zoomRatio) + if (distPrev < distCurrent) index - 1 else index + } else { + index + } + } else { + 0 + } +} + +/** + * Formats a zoom value for speech / accessibility announcements (e.g. "0.5", "1", "2"). * - * @param onChangeZoom the callback for when the zoom changes - * @param modifier the modifier for this component - * @param zoomControlUiState the [ZoomControlUiState] for this component - * @param buttonSize the size of the buttons - * @param spacing the spacing between the buttons + * Keeps the leading zero for speech clarity and respects the given [locale]'s decimal separator. + */ +internal fun formatAccessibleZoomLabel(value: Float, locale: Locale = Locale.getDefault()): String { + val tenths = toTenths(value) + val whole = tenths / 10 + val fraction = tenths % 10 + val decimalSeparator = DecimalFormatSymbols.getInstance(locale).decimalSeparator + return if (fraction == 0) { + whole.toString() + } else { + "$whole$decimalSeparator$fraction" + } +} + +/** + * Formats zoom ratios for camera controls: + * - Unselected stops: ".5", "1", "2", "5" (no leading zero, no multiplication symbol). + * - Selected stop: ".5×", "1×", "2×", "5×" (with Unicode multiplication symbol \u00D7). + * - In-between ratios (e.g. while pinching): "1.4×". + * Respects the given [locale]'s decimal separator. + */ +internal fun formatZoomLabel( + targetZoom: Float, + currentRatio: Float, + isSelected: Boolean, + locale: Locale = Locale.getDefault() +): String { + val valueToFormat = if (isSelected) currentRatio else targetZoom + val tenths = toTenths(valueToFormat) + val whole = tenths / 10 + val fraction = tenths % 10 + val decimalSeparator = DecimalFormatSymbols.getInstance(locale).decimalSeparator + val formattedNumber = if (whole == 0) { + "$decimalSeparator$fraction" + } else if (fraction == 0) { + whole.toString() + } else { + "$whole$decimalSeparator$fraction" + } + return if (isSelected) { + "$formattedNumber\u00D7" + } else { + formattedNumber + } +} + +private fun ZoomControlUiState.Enabled.displayZoomRatio(): Float = + primarySettingZoomRatio ?: primaryZoomRatio ?: initialZoomRatio ?: 1f + +/** + * A composable that displays zoom controls formatted as a unified capsule track + * with a sliding indicator pill that smoothly tracks the active zoom stop. + * + * @param zoomControlUiState The [ZoomControlUiState] providing available zoom levels and + * current ratio. + * @param onChangeZoom Callback when a zoom level is tapped. + * @param modifier Modifier for the component. + * @param orientation Layout orientation ([Orientation.Horizontal] or [Orientation.Vertical]), + * allowing flexible placement across portrait phones, landscape mode, and open foldables/tablets. + * @param colors Styling configuration for track and indicator colors. */ @OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable -fun ZoomButtonRow( +fun ZoomBar( + zoomControlUiState: ZoomControlUiState, onChangeZoom: (Float) -> Unit, modifier: Modifier = Modifier, - zoomControlUiState: ZoomControlUiState, - buttonSize: Dp = ButtonDefaults.ExtraSmallContainerHeight, - spacing: Dp = 16.dp + orientation: Orientation = Orientation.Horizontal, + colors: ZoomBarColors = ZoomBarDefaults.colors() ) { if (zoomControlUiState is ZoomControlUiState.Enabled) { val currentZoomState by rememberUpdatedState(zoomControlUiState) val selectedOptionIndex: Int by remember(zoomControlUiState.primaryLensFacing) { - // todo(kc): checkValue will flash to 1.0 when flipping between camera lenses on API 30+. - // cameraState (cameraState's zoom value) should have an intermediate, "unknown", state when - // camera flip is in progress. Then we can ensure that the zoom controls don't flash to 1.0 - // when cameraState is in this intermediate state. - derivedStateOf { - // if animating towards a value, then that option will be selected - // otherwise, select the closest option that is less than the current zoom ratio - - val checkValue = - currentZoomState.animatingToValue ?: currentZoomState.primaryZoomRatio ?: 1f - if (checkValue >= 1f) { - // -1 if no index is found - currentZoomState.zoomLevels.indexOfLast { zoomLevelOption -> - checkValue >= zoomLevelOption - } - } else { - 0 - } + val checkValue = currentZoomState.animatingToValue + ?: currentZoomState.displayZoomRatio() + selectedZoomStopIndex(currentZoomState.zoomLevels, checkValue) } } - Row( + val zoomLevels = zoomControlUiState.zoomLevels + if (zoomLevels.isEmpty()) return + + val validIndex = selectedOptionIndex.coerceIn(0, zoomLevels.size - 1) + val disableAnimations = LocalDisableAnimations.current + val indicatorPosition by animateFloatAsState( + targetValue = validIndex.toFloat(), + animationSpec = if (disableAnimations) { + snap() + } else { + MaterialTheme.motionScheme.defaultSpatialSpec() + }, + label = "zoomIndicatorPosition" + ) + + val currentRatioProvider = remember { + { currentZoomState.animatingToValue ?: currentZoomState.displayZoomRatio() } + } + + val totalAlongTrack = ZoomBarDefaults.SlotSize * zoomLevels.size + ZoomBarDefaults.Inset * 2 + val totalAcrossTrack = ZoomBarDefaults.SlotSize + + val totalWidth = + if (orientation == Orientation.Horizontal) totalAlongTrack else totalAcrossTrack + val totalHeight = + if (orientation == Orientation.Horizontal) totalAcrossTrack else totalAlongTrack + + Box( modifier = modifier - .background( - color = Color.Black.copy(alpha = 0.32f), - shape = CircleShape - ) - .padding(horizontal = spacing / 2, vertical = spacing / 2) + .size(totalWidth, totalHeight) + .background(color = colors.trackColor, shape = ZoomBarDefaults.TrackShape) .semantics { testTag = ZOOM_BUTTON_ROW_TAG - stateDescription = zoomControlUiState.primaryZoomRatio.toString() } - .height(buttonSize), - verticalAlignment = Alignment.CenterVertically ) { - zoomControlUiState.zoomLevels.forEachIndexed { index, value -> + if (orientation == Orientation.Horizontal) { Box( - modifier = Modifier.width(buttonSize + spacing + 8.dp), - contentAlignment = Alignment.Center + modifier = Modifier + .offset { + IntOffset( + x = ( + ZoomBarDefaults.Inset + + indicatorPosition * ZoomBarDefaults.SlotSize + ).roundToPx(), + y = ZoomBarDefaults.Inset.roundToPx() + ) + } + .size(ZoomBarDefaults.SlotSize, ZoomBarDefaults.IndicatorHeight) + .background(colors.selectedIndicatorColor, MaterialTheme.shapes.medium) + ) + + Row( + modifier = Modifier + .fillMaxSize() + .selectableGroup() + .padding(horizontal = ZoomBarDefaults.Inset), + verticalAlignment = Alignment.CenterVertically ) { - ZoomButton( - targetZoom = value, - zoomRatio = zoomControlUiState.primaryZoomRatio ?: 1f, - isSelected = selectedOptionIndex == index, - onChangeZoom = onChangeZoom - ) + zoomLevels.forEachIndexed { index, value -> + ZoomBarItem( + value = value, + currentRatioProvider = currentRatioProvider, + isSelected = index == validIndex, + indicatorPositionProvider = { indicatorPosition }, + itemIndex = index, + colors = colors, + onClick = { onChangeZoom(value) } + ) + } + } + } else { + Box( + modifier = Modifier + .offset { + IntOffset( + x = 0, + y = ( + ZoomBarDefaults.Inset + + indicatorPosition * ZoomBarDefaults.SlotSize + + ZoomBarDefaults.Inset + ).roundToPx() + ) + } + .size(ZoomBarDefaults.SlotSize, ZoomBarDefaults.IndicatorHeight) + .background(colors.selectedIndicatorColor, MaterialTheme.shapes.medium) + ) + + Column( + modifier = Modifier + .fillMaxSize() + .selectableGroup() + .padding(vertical = ZoomBarDefaults.Inset), + horizontalAlignment = Alignment.CenterHorizontally + ) { + zoomLevels.forEachIndexed { index, value -> + ZoomBarItem( + value = value, + currentRatioProvider = currentRatioProvider, + isSelected = index == validIndex, + indicatorPositionProvider = { indicatorPosition }, + itemIndex = index, + colors = colors, + onClick = { onChangeZoom(value) } + ) + } } } } } } -@OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable -private fun ZoomButton( +private fun ZoomBarItem( + value: Float, + currentRatioProvider: () -> Float, + isSelected: Boolean, + indicatorPositionProvider: () -> Float, + itemIndex: Int, + colors: ZoomBarColors, modifier: Modifier = Modifier, - buttonSize: Dp = ButtonDefaults.ExtraSmallContainerHeight, - targetZoom: Float, - zoomRatio: Float, - isSelected: Boolean = false, - onChangeZoom: (Float) -> Unit + onClick: () -> Unit ) { - val selectedFormat = remember { DecimalFormat("#.0") } - val formatter = remember(targetZoom) { - DecimalFormat("#.#").apply { - minimumIntegerDigits = 0 - roundingMode = if (targetZoom >= 1) { - RoundingMode.DOWN - } else { - RoundingMode.UP - } + val displayText by remember(value, isSelected) { + derivedStateOf { + formatZoomLabel( + targetZoom = value, + currentRatio = if (isSelected) currentRatioProvider() else value, + isSelected = isSelected + ) } } - val displayText by remember(isSelected, zoomRatio) { - derivedStateOf { - if (!isSelected) { - formatter.format(targetZoom) - } else { - "${selectedFormat.format(zoomRatio)}x" + + val labelText = remember(displayText) { + if (displayText.endsWith('×')) { + buildAnnotatedString { + append(displayText.dropLast(1)) + pushStyle(SpanStyle(fontWeight = FontWeight.Bold)) + append('×') + pop() } + } else { + AnnotatedString(displayText) } } - ToggleButton( - checked = isSelected, - onCheckedChange = { onChangeZoom(targetZoom) }, - modifier = modifier.heightIn(buttonSize) + + val accessibleZoomLabel = formatAccessibleZoomLabel(value) + + val density = LocalDensity.current + + val onClickLabel = stringResource(R.string.zoom_stop_click_label, accessibleZoomLabel) + + Box( + modifier = modifier + .size(ZoomBarDefaults.SlotSize) + .selectable( + selected = isSelected, + role = Role.RadioButton, + interactionSource = remember { MutableInteractionSource() }, + indication = null, + onClick = onClick + ) .semantics { - testTag = getZoomButtonTestTag(targetZoom) - // todo(kc): move to text resource - contentDescription = if (isSelected) "selected" else "not selected" + testTag = getZoomButtonTestTag(value) + onClick(label = onClickLabel) { + onClick() + true + } }, - shapes = ToggleButtonDefaults.shapesFor(buttonSize), - contentPadding = ButtonDefaults.contentPaddingFor(buttonSize), - colors = if (isSelected) { - ToggleButtonDefaults.colors( - containerColor = MaterialTheme.colorScheme.primaryFixed, - contentColor = MaterialTheme.colorScheme.onPrimaryFixed + contentAlignment = Alignment.Center + ) { + CompositionLocalProvider( + LocalDensity provides Density( + density = density.density, + fontScale = density.fontScale.coerceAtMost(ZoomBarDefaults.MAX_LABEL_FONT_SCALE) ) - } else { - ToggleButtonDefaults.colors( - containerColor = Color.White.copy(alpha = .16f), - contentColor = Color.White + ) { + // TODO(#619): Apply Modifier.animateToUpright() to keep labels upright on rotation + // (https://github.com/google/jetpack-camera-app/pull/619). + BasicText( + text = labelText, + style = MaterialTheme.typography.labelLarge.copy( + textAlign = TextAlign.Center + ), + color = { + lerp( + colors.unselectedContentColor, + colors.selectedContentColor, + (1f - abs(indicatorPositionProvider() - itemIndex)).coerceIn(0f, 1f) + ) + }, + modifier = Modifier + .wrapContentSize(unbounded = true) + .padding(horizontal = 2.dp), + softWrap = false ) } - ) { - Text( - modifier = Modifier.animateContentSize(), - text = displayText, - style = MaterialTheme.typography.labelSmall, - textAlign = TextAlign.Center - ) } } +/** + * A composable that displays a row of zoom buttons. + * + * @deprecated Use [ZoomBar] directly. + */ +@Deprecated( + message = "Use ZoomBar directly.", + replaceWith = ReplaceWith( + "ZoomBar(" + + "zoomControlUiState = zoomControlUiState, " + + "onChangeZoom = onChangeZoom, " + + "modifier = modifier, " + + "orientation = orientation, " + + "colors = colors" + + ")", + "com.google.jetpackcamera.ui.components.capture.ZoomBar" + ) +) +@Composable +fun ZoomButtonRow( + onChangeZoom: (Float) -> Unit, + modifier: Modifier = Modifier, + zoomControlUiState: ZoomControlUiState, + buttonSize: Dp = ButtonDefaults.ExtraSmallContainerHeight, + spacing: Dp = 16.dp, + orientation: Orientation = Orientation.Horizontal, + colors: ZoomBarColors = ZoomBarDefaults.colors() +) { + ZoomBar( + zoomControlUiState = zoomControlUiState, + onChangeZoom = onChangeZoom, + modifier = modifier, + orientation = orientation, + colors = colors + ) +} + private fun getZoomButtonTestTag(buttonValue: Float): String { return if (buttonValue < 1 && buttonValue > 0) { ZOOM_BUTTON_MIN_TAG @@ -197,78 +510,152 @@ private fun getZoomButtonTestTag(buttonValue: Float): String { } else if (buttonValue == 5f) { ZOOM_BUTTON_5_TAG } else { - TODO("Zoom button with value $buttonValue needs a test tag") + "ZoomButton_${buttonValue}Tag" } } -@Preview(showBackground = true) +// --------------------------------------------------------------------------- +// Previews +// --------------------------------------------------------------------------- + +@Preview(name = "Horizontal 60% Black (Overlapping Viewfinder)", showBackground = true) @Composable -fun ZoomButtonPreview() { +private fun ZoomBarHorizontalDarkPreview() { Box( - Modifier - .padding(16.dp) - .background(Color.DarkGray) + modifier = Modifier + .background(Color(0xFF2B2B2B)) .padding(16.dp), contentAlignment = Alignment.Center ) { - Row { - ZoomButton( - targetZoom = 1f, - onChangeZoom = {}, - isSelected = false, - zoomRatio = 2f - ) + ZoomBar( + zoomControlUiState = ZoomControlUiState.Enabled( + zoomLevels = listOf(0.5f, 1.0f, 2.0f, 5.0f), + primaryLensFacing = LensFacing.BACK, + primaryZoomRatio = 1.0f + ), + onChangeZoom = {}, + orientation = Orientation.Horizontal, + colors = ZoomBarDefaults.black60Colors() + ) + } +} - ZoomButton( - targetZoom = 3f, - onChangeZoom = {}, - zoomRatio = 3.3f, - isSelected = true - ) - } +@Preview(name = "Horizontal 20% White (Not Overlapping Viewfinder)", showBackground = true) +@Composable +private fun ZoomBarHorizontalTranslucentPreview() { + Box( + modifier = Modifier + .background(Color(0xFF2B2B2B)) + .padding(16.dp), + contentAlignment = Alignment.Center + ) { + ZoomBar( + zoomControlUiState = ZoomControlUiState.Enabled( + zoomLevels = listOf(0.5f, 1.0f, 2.0f, 5.0f), + primaryLensFacing = LensFacing.BACK, + primaryZoomRatio = 1.0f + ), + onChangeZoom = {}, + orientation = Orientation.Horizontal, + colors = ZoomBarDefaults.white20Colors() + ) } } -@Preview(showBackground = true) +@Preview(name = "Horizontal - Fraction (.5x Selected)", showBackground = true) @Composable -fun ZoomBarPreviewOneSelected() { - val sampleValues = listOf(0.5f, 1.0f, 2.0f, 5.0f) +private fun ZoomBarHorizontalFractionPreview() { Box( - Modifier - .background(Color.DarkGray), + modifier = Modifier + .background(Color(0xFF2B2B2B)) + .padding(16.dp), contentAlignment = Alignment.Center ) { - ZoomButtonRow( + ZoomBar( zoomControlUiState = ZoomControlUiState.Enabled( - sampleValues, - primaryLensFacing = LensFacing.FRONT, - primaryZoomRatio = 1f + zoomLevels = listOf(0.5f, 1.0f, 2.0f, 5.0f), + primaryLensFacing = LensFacing.BACK, + primaryZoomRatio = 0.5f ), - onChangeZoom = { - println("Clicked value: $it") - } + onChangeZoom = {}, + orientation = Orientation.Horizontal, + colors = ZoomBarDefaults.black60Colors() ) } } -@Preview(showBackground = true) +@Preview(name = "Vertical 60% Black - Flush Sides", showBackground = true) @Composable -fun ZoomBarPreviewFractionSelected() { - val sampleValues = listOf(0.5f, 1.0f, 2.0f, 5.0f, 25.0f) +private fun ZoomBarVerticalDarkPreview() { Box( - Modifier - .background(Color.DarkGray), + modifier = Modifier + .background(Color(0xFF2B2B2B)) + .padding(16.dp), contentAlignment = Alignment.Center ) { - ZoomButtonRow( + ZoomBar( zoomControlUiState = ZoomControlUiState.Enabled( - sampleValues, - primaryLensFacing = LensFacing.FRONT, - primaryZoomRatio = .6f + zoomLevels = listOf(0.5f, 1.0f, 2.0f, 5.0f), + primaryLensFacing = LensFacing.BACK, + primaryZoomRatio = 1.0f ), - onChangeZoom = { - println("Clicked value: $it") - } + onChangeZoom = {}, + orientation = Orientation.Vertical, + colors = ZoomBarDefaults.black60Colors() ) } } + +@Preview(name = "Single Stop (1x Only)", showBackground = true) +@Composable +private fun ZoomBarSingleStopPreview() { + Box( + modifier = Modifier + .background(Color(0xFF2B2B2B)) + .padding(16.dp), + contentAlignment = Alignment.Center + ) { + ZoomBar( + zoomControlUiState = ZoomControlUiState.Enabled( + zoomLevels = listOf(1.0f), + primaryLensFacing = LensFacing.BACK, + primaryZoomRatio = 1.0f + ), + onChangeZoom = {}, + orientation = Orientation.Horizontal + ) + } +} + +@Preview(name = "Extended Telephoto Range (2x Selected)", showBackground = true) +@Composable +private fun ZoomBarExtendedRangePreview() { + Box( + modifier = Modifier + .background(Color(0xFF2B2B2B)) + .padding(16.dp), + contentAlignment = Alignment.Center + ) { + ZoomBar( + zoomControlUiState = ZoomControlUiState.Enabled( + zoomLevels = listOf(0.5f, 1.0f, 2.0f, 5.0f, 10.0f), + primaryLensFacing = LensFacing.BACK, + primaryZoomRatio = 2.0f + ), + onChangeZoom = {}, + orientation = Orientation.Horizontal + ) + } +} + +@Preview(name = "Legacy Delegate - One Selected", showBackground = true) +@Composable +private fun ZoomBarPreviewOneSelected() { + ZoomBarHorizontalDarkPreview() +} + +@Preview(name = "Legacy Delegate - Fraction Selected", showBackground = true) +@Composable +private fun ZoomBarPreviewFractionSelected() { + ZoomBarHorizontalFractionPreview() +} diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomStateManager.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomStateManager.kt index cf85a44c41..5d03f3a450 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomStateManager.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomStateManager.kt @@ -52,6 +52,9 @@ class ZoomStateManager( // The valid zoom range for the current camera lens. private var functionalZoomRange = zoomRange + // Tracks the active animated zoom target and lens to avoid restarting an identical animation. + private var currentAnimationTarget: Pair? = null + // A mutex to ensure that zoom operations are atomic and thread-safe. This is crucial for // preventing race conditions, as multiple zoom actions (e.g., pinch-to-zoom and button // clicks) can be triggered concurrently. By using a MutatorMutex, we can ensure that @@ -77,13 +80,14 @@ class ZoomStateManager( */ suspend fun absoluteZoom(targetZoomLevel: Float, lensToZoom: LensToZoom) { mutateZoom { + val coercedZoom = targetZoomLevel.coerceIn(functionalZoomRange.toClosedRange()) if (lensToZoom == LensToZoom.PRIMARY) { - functionalZoom = targetZoomLevel.coerceIn(functionalZoomRange.toClosedRange()) + functionalZoom = coercedZoom } zoomController.setZoomRatio( CameraZoomRatio( ZoomStrategy.Absolute( - targetZoomLevel.coerceIn(functionalZoomRange.toClosedRange()), + coercedZoom, lensToZoom = lensToZoom ) ) @@ -131,23 +135,38 @@ class ZoomStateManager( animationSpec: AnimationSpec = tween(durationMillis = 500), lensToZoom: LensToZoom ) { + if (currentAnimationTarget == + lensToZoom to targetZoomLevel.coerceIn(functionalZoomRange.toClosedRange()) + ) { + return + } mutatorMutex.mutate { - zoomController.setZoomAnimationState(targetZoomLevel) - - Animatable(initialValue = functionalZoom).animateTo( - targetValue = targetZoomLevel, - animationSpec = animationSpec - ) { - // this is called every animation frame - functionalZoom = value.coerceIn(functionalZoomRange.toClosedRange()) - zoomController.setZoomRatio( - CameraZoomRatio( - ZoomStrategy.Absolute( - functionalZoom, - lensToZoom + val coercedTarget = targetZoomLevel.coerceIn(functionalZoomRange.toClosedRange()) + if (lensToZoom == LensToZoom.PRIMARY && coercedTarget == functionalZoom) { + zoomController.setZoomAnimationState(null) + return@mutate + } + currentAnimationTarget = lensToZoom to coercedTarget + zoomController.setZoomAnimationState(coercedTarget) + try { + Animatable(initialValue = functionalZoom).animateTo( + targetValue = coercedTarget, + animationSpec = animationSpec + ) { + // this is called every animation frame + functionalZoom = value.coerceIn(functionalZoomRange.toClosedRange()) + zoomController.setZoomRatio( + CameraZoomRatio( + ZoomStrategy.Absolute( + functionalZoom, + lensToZoom + ) ) ) - ) + } + zoomController.setZoomAnimationState(null) + } finally { + currentAnimationTarget = null } } } @@ -163,6 +182,7 @@ class ZoomStateManager( */ suspend fun onChangeLens(newInitialZoomLevel: Float, newZoomRange: Range) { mutatorMutex.mutate(MutatePriority.PreventUserInput) { + zoomController.setZoomAnimationState(null) functionalZoom = newInitialZoomLevel functionalZoomRange = newZoomRange } diff --git a/ui/components/capture/src/main/res/values/strings.xml b/ui/components/capture/src/main/res/values/strings.xml index e7858b6a28..4106fac29a 100644 --- a/ui/components/capture/src/main/res/values/strings.xml +++ b/ui/components/capture/src/main/res/values/strings.xml @@ -183,4 +183,7 @@ Dismiss + + + Zoom to %1$s× \ No newline at end of file diff --git a/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponentsTest.kt b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponentsTest.kt new file mode 100644 index 0000000000..2f876d37b1 --- /dev/null +++ b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponentsTest.kt @@ -0,0 +1,212 @@ +/* + * Copyright (C) 2026 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 com.google.common.truth.Truth.assertThat +import java.util.Locale +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 + +@RunWith(JUnit4::class) +class ZoomBarComponentsTest { + + @Test + fun formatZoomLabel_unselectedStops_formatsWithoutMultiplierOrLeadingZero() { + assertThat( + formatZoomLabel( + targetZoom = 0.5f, + currentRatio = 1.0f, + isSelected = false, + locale = Locale.US + ) + ).isEqualTo(".5") + assertThat( + formatZoomLabel( + targetZoom = 1.0f, + currentRatio = 1.0f, + isSelected = false, + locale = Locale.US + ) + ).isEqualTo("1") + assertThat( + formatZoomLabel( + targetZoom = 2.0f, + currentRatio = 1.0f, + isSelected = false, + locale = Locale.US + ) + ).isEqualTo("2") + assertThat( + formatZoomLabel( + targetZoom = 5.0f, + currentRatio = 1.0f, + isSelected = false, + locale = Locale.US + ) + ).isEqualTo("5") + assertThat( + formatZoomLabel( + targetZoom = 10.0f, + currentRatio = 1.0f, + isSelected = false, + locale = Locale.US + ) + ).isEqualTo("10") + } + + @Test + fun formatZoomLabel_selectedStops_formatsWithMultiplier() { + assertThat( + formatZoomLabel( + targetZoom = 0.5f, + currentRatio = 0.5f, + isSelected = true, + locale = Locale.US + ) + ).isEqualTo(".5\u00D7") + assertThat( + formatZoomLabel( + targetZoom = 1.0f, + currentRatio = 1.0f, + isSelected = true, + locale = Locale.US + ) + ).isEqualTo("1\u00D7") + assertThat( + formatZoomLabel( + targetZoom = 2.0f, + currentRatio = 2.0f, + isSelected = true, + locale = Locale.US + ) + ).isEqualTo("2\u00D7") + assertThat( + formatZoomLabel( + targetZoom = 5.0f, + currentRatio = 5.0f, + isSelected = true, + locale = Locale.US + ) + ).isEqualTo("5\u00D7") + } + + @Test + fun formatZoomLabel_inBetweenPinchRatio_formatsCurrentRatio() { + assertThat( + formatZoomLabel( + targetZoom = 1.0f, + currentRatio = 1.4f, + isSelected = true, + locale = Locale.US + ) + ).isEqualTo("1.4\u00D7") + assertThat( + formatZoomLabel( + targetZoom = 0.5f, + currentRatio = 0.7f, + isSelected = true, + locale = Locale.US + ) + ).isEqualTo(".7\u00D7") + assertThat( + formatZoomLabel( + targetZoom = 0.5f, + currentRatio = 0.99f, + isSelected = true, + locale = Locale.US + ) + ).isEqualTo("1\u00D7") + } + + @Test + fun formatZoomLabel_halfUpBoundaryCases_roundsCorrectly() { + assertThat( + formatZoomLabel( + targetZoom = 1.0f, + currentRatio = 0.95f, + isSelected = true, + locale = Locale.US + ) + ).isEqualTo("1\u00D7") + assertThat( + formatZoomLabel( + targetZoom = 5.0f, + currentRatio = 4.95f, + isSelected = true, + locale = Locale.US + ) + ).isEqualTo("5\u00D7") + } + + @Test + fun formatZoomLabel_localeWithCommaSeparator_usesLocalizedDecimalSeparator() { + assertThat( + formatZoomLabel( + targetZoom = 0.5f, + currentRatio = 0.5f, + isSelected = true, + locale = Locale.GERMANY + ) + ).isEqualTo(",5\u00D7") + assertThat( + formatZoomLabel( + targetZoom = 1.0f, + currentRatio = 1.4f, + isSelected = true, + locale = Locale.GERMANY + ) + ).isEqualTo("1,4\u00D7") + assertThat( + formatZoomLabel( + targetZoom = 0.5f, + currentRatio = 1.0f, + isSelected = false, + locale = Locale.GERMANY + ) + ).isEqualTo(",5") + } + + @Test + fun selectedZoomStopIndex_roundsToTenthsAndResolvesTieBreak() { + val stops = listOf(0.5f, 1.0f, 2.0f, 5.0f) + + // 0.95 rounds half-up to 1.0 tenth -> selects index 1 (1.0x stop) + assertThat(selectedZoomStopIndex(stops, 0.95f)).isEqualTo(1) + + // 4.94 rounds to 4.9 tenths -> stays on index 2 (2.0x stop) + assertThat(selectedZoomStopIndex(stops, 4.94f)).isEqualTo(2) + + // 5.0f selects index 3 (5.0x stop) + assertThat(selectedZoomStopIndex(stops, 5.0f)).isEqualTo(3) + + // Adjacent stops rounding to same tenth: picks the closer stop + val adjacentStops = listOf(0.5f, 0.96f, 1.0f, 2.0f) + assertThat(selectedZoomStopIndex(adjacentStops, 0.97f)).isEqualTo(1) + assertThat(selectedZoomStopIndex(adjacentStops, 0.99f)).isEqualTo(2) + } + + @Test + fun formatAccessibleZoomLabel_roundsAndKeepsLeadingZero() { + // Pixel minimum zoom ~0.507 rounds to 0.5 with leading zero for speech + assertThat(formatAccessibleZoomLabel(0.50783783f, Locale.US)).isEqualTo("0.5") + assertThat(formatAccessibleZoomLabel(1.0f, Locale.US)).isEqualTo("1") + assertThat(formatAccessibleZoomLabel(2.0f, Locale.US)).isEqualTo("2") + assertThat(formatAccessibleZoomLabel(5.0f, Locale.US)).isEqualTo("5") + // Respects locale decimal separator + assertThat(formatAccessibleZoomLabel(0.50783783f, Locale.GERMANY)).isEqualTo("0,5") + } +} diff --git a/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/ZoomStateManagerTest.kt b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/ZoomStateManagerTest.kt new file mode 100644 index 0000000000..8a749c4bf2 --- /dev/null +++ b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/ZoomStateManagerTest.kt @@ -0,0 +1,115 @@ +/* + * Copyright (C) 2026 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.util.Range +import androidx.compose.animation.core.snap +import androidx.compose.runtime.MonotonicFrameClock +import com.google.common.truth.Truth.assertThat +import com.google.jetpackcamera.model.CameraZoomRatio +import com.google.jetpackcamera.model.LensToZoom +import com.google.jetpackcamera.model.ZoomStrategy +import com.google.jetpackcamera.ui.controller.testing.FakeZoomController +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.withContext +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner + +@OptIn(ExperimentalCoroutinesApi::class) +@RunWith(RobolectricTestRunner::class) +class ZoomStateManagerTest { + + private val appliedRatios = mutableListOf() + private val animationStates = mutableListOf() + private lateinit var zoomController: FakeZoomController + private lateinit var zoomStateManager: ZoomStateManager + + private val testFrameClock = object : MonotonicFrameClock { + private var frameTimeNanos = 0L + override suspend fun withFrameNanos(onFrame: (frameTimeNanos: Long) -> R): R { + frameTimeNanos += 16_000_000L + return onFrame(frameTimeNanos) + } + } + + @Before + fun setUp() { + appliedRatios.clear() + animationStates.clear() + zoomController = FakeZoomController( + setZoomRatioAction = { appliedRatios.add(it) }, + setZoomAnimationStateAction = { animationStates.add(it) } + ) + zoomStateManager = ZoomStateManager( + initialZoomLevel = 1.0f, + zoomRange = Range(0.5f, 10.0f), + zoomController = zoomController + ) + } + + @Test + fun animatedZoom_setsAndClearsZoomAnimationStateOnCompletion() = runTest { + animationStates.clear() + + withContext(testFrameClock) { + zoomStateManager.animatedZoom( + targetZoomLevel = 5.0f, + animationSpec = snap(), + lensToZoom = LensToZoom.PRIMARY + ) + } + + assertThat(animationStates).containsExactly(5.0f, null).inOrder() + assertThat(appliedRatios.last()).isEqualTo( + CameraZoomRatio(ZoomStrategy.Absolute(5.0f, LensToZoom.PRIMARY)) + ) + } + + @Test + fun animatedZoom_whenAlreadyAtTargetZoom_shortCircuits() = runTest { + animationStates.clear() + + withContext(testFrameClock) { + zoomStateManager.animatedZoom( + targetZoomLevel = 1.0f, + animationSpec = snap(), + lensToZoom = LensToZoom.PRIMARY + ) + } + + assertThat(appliedRatios).isEmpty() + assertThat(animationStates).containsExactly(null) + } + + @Test + fun onChangeLens_resetsZoomAnimationStateAndUpdatesRange() = runTest { + animationStates.clear() + + zoomStateManager.onChangeLens( + newInitialZoomLevel = 2.0f, + newZoomRange = Range(1.0f, 4.0f) + ) + zoomStateManager.scaleZoom(scalingFactor = 3.0f, lensToZoom = LensToZoom.PRIMARY) + + assertThat(animationStates).contains(null) + assertThat(appliedRatios.last()).isEqualTo( + CameraZoomRatio(ZoomStrategy.Absolute(4.0f, LensToZoom.PRIMARY)) + ) + } +} diff --git a/ui/controller/impl/src/main/java/com/google/jetpackcamera/ui/controller/impl/ZoomControllerImpl.kt b/ui/controller/impl/src/main/java/com/google/jetpackcamera/ui/controller/impl/ZoomControllerImpl.kt index b54b4f6a1a..01124a8b56 100644 --- a/ui/controller/impl/src/main/java/com/google/jetpackcamera/ui/controller/impl/ZoomControllerImpl.kt +++ b/ui/controller/impl/src/main/java/com/google/jetpackcamera/ui/controller/impl/ZoomControllerImpl.kt @@ -17,6 +17,8 @@ package com.google.jetpackcamera.ui.controller.impl import com.google.jetpackcamera.core.camera.CameraSystem import com.google.jetpackcamera.model.CameraZoomRatio +import com.google.jetpackcamera.model.LensToZoom +import com.google.jetpackcamera.model.ZoomStrategy import com.google.jetpackcamera.ui.controller.ZoomController import com.google.jetpackcamera.ui.uistate.capture.TrackedCaptureUiState import kotlin.coroutines.CoroutineContext @@ -41,12 +43,35 @@ class ZoomControllerImpl( ) : ZoomController { private val job = Job(parent = coroutineContext[Job]) private val scope = CoroutineScope(coroutineContext + job) + private var primaryZoomJob: Job? = null + private var secondaryZoomJob: Job? = null override fun setZoomRatio(zoomRatio: CameraZoomRatio) { - scope.launch { - cameraSystemProvider().changeZoomRatio( - newZoomState = zoomRatio - ) + if (zoomRatio.changeType is ZoomStrategy.Absolute) { + when (zoomRatio.changeType.lensToZoom) { + LensToZoom.PRIMARY -> { + // Drop pending zoom updates while the camera system is still initializing; + // once cameraSystemProvider() resolves, launches on Dispatchers.Main.immediate + // execute synchronously. + primaryZoomJob?.cancel() + primaryZoomJob = scope.launch { + cameraSystemProvider().changeZoomRatio(newZoomState = zoomRatio) + } + } + LensToZoom.SECONDARY -> { + // Drop pending zoom updates while the camera system is still initializing. + secondaryZoomJob?.cancel() + secondaryZoomJob = scope.launch { + cameraSystemProvider().changeZoomRatio(newZoomState = zoomRatio) + } + } + } + } else { + scope.launch { + cameraSystemProvider().changeZoomRatio( + newZoomState = zoomRatio + ) + } } } diff --git a/ui/controller/impl/src/test/java/com/google/jetpackcamera/ui/controller/impl/ZoomControllerImplTest.kt b/ui/controller/impl/src/test/java/com/google/jetpackcamera/ui/controller/impl/ZoomControllerImplTest.kt new file mode 100644 index 0000000000..5bd6f56fd5 --- /dev/null +++ b/ui/controller/impl/src/test/java/com/google/jetpackcamera/ui/controller/impl/ZoomControllerImplTest.kt @@ -0,0 +1,115 @@ +/* + * Copyright (C) 2026 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.controller.impl + +import com.google.common.truth.Truth.assertThat +import com.google.jetpackcamera.core.camera.CameraSystem +import com.google.jetpackcamera.core.camera.testing.FakeCameraSystem +import com.google.jetpackcamera.model.CameraZoomRatio +import com.google.jetpackcamera.model.LensToZoom +import com.google.jetpackcamera.model.ZoomStrategy +import com.google.jetpackcamera.ui.uistate.capture.TrackedCaptureUiState +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runTest +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 + +@OptIn(ExperimentalCoroutinesApi::class) +@RunWith(JUnit4::class) +internal class ZoomControllerImplTest { + private val testScope = TestScope() + private val testDispatcher = StandardTestDispatcher(testScope.testScheduler) + + private class RecordingCameraSystem : CameraSystem by FakeCameraSystem() { + val zoomChanges = mutableListOf() + + override fun changeZoomRatio(newZoomState: CameraZoomRatio) { + zoomChanges.add(newZoomState) + } + } + + private val cameraSystem = RecordingCameraSystem() + private val trackedCaptureUiState = MutableStateFlow(TrackedCaptureUiState()) + private lateinit var controller: ZoomControllerImpl + + @Before + fun setup() { + controller = ZoomControllerImpl( + cameraSystemProvider = { cameraSystem }, + trackedCaptureUiState = trackedCaptureUiState, + coroutineContext = testDispatcher + ) + } + + @Test + fun setZoomRatio_conflatesPendingAbsoluteUpdatesForSameLens() = testScope.runTest { + val deferredCameraSystem = CompletableDeferred() + val delayedController = ZoomControllerImpl( + cameraSystemProvider = { deferredCameraSystem.await() }, + trackedCaptureUiState = trackedCaptureUiState, + coroutineContext = testDispatcher + ) + + delayedController.setZoomRatio( + CameraZoomRatio(ZoomStrategy.Absolute(0.5f, LensToZoom.PRIMARY)) + ) + delayedController.setZoomRatio( + CameraZoomRatio(ZoomStrategy.Absolute(2.0f, LensToZoom.PRIMARY)) + ) + delayedController.setZoomRatio( + CameraZoomRatio(ZoomStrategy.Absolute(5.0f, LensToZoom.PRIMARY)) + ) + + deferredCameraSystem.complete(cameraSystem) + advanceUntilIdle() + + assertThat(cameraSystem.zoomChanges).containsExactly( + CameraZoomRatio(ZoomStrategy.Absolute(5.0f, LensToZoom.PRIMARY)) + ) + } + + @Test + fun setZoomRatio_primaryAndSecondaryDoNotCancelEachOther() = testScope.runTest { + controller.setZoomRatio( + CameraZoomRatio(ZoomStrategy.Absolute(2.0f, LensToZoom.PRIMARY)) + ) + controller.setZoomRatio( + CameraZoomRatio(ZoomStrategy.Absolute(1.0f, LensToZoom.SECONDARY)) + ) + advanceUntilIdle() + + assertThat(cameraSystem.zoomChanges).containsExactly( + CameraZoomRatio(ZoomStrategy.Absolute(2.0f, LensToZoom.PRIMARY)), + CameraZoomRatio(ZoomStrategy.Absolute(1.0f, LensToZoom.SECONDARY)) + ).inOrder() + } + + @Test + fun setZoomAnimationState_updatesTrackedCaptureUiState() { + controller.setZoomAnimationState(5.0f) + assertThat(trackedCaptureUiState.value.zoomAnimationTarget).isEqualTo(5.0f) + + controller.setZoomAnimationState(null) + assertThat(trackedCaptureUiState.value.zoomAnimationTarget).isNull() + } +}