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 787be102e..3e18fb39d 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 @@ -16,132 +16,19 @@ package com.google.jetpackcamera.ui.components.capture 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.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.WindowInsets -import androidx.compose.foundation.layout.WindowInsetsSides -import androidx.compose.foundation.layout.asPaddingValues import androidx.compose.foundation.layout.aspectRatio -import androidx.compose.foundation.layout.displayCutout -import androidx.compose.foundation.layout.fillMaxHeight -import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.navigationBarsIgnoringVisibility -import androidx.compose.foundation.layout.only -import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.systemBarsIgnoringVisibility -import androidx.compose.foundation.layout.systemGestures -import androidx.compose.foundation.layout.union -import androidx.compose.foundation.layout.windowInsetsPadding -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.BottomSheetDefaults -import androidx.compose.material3.BottomSheetScaffold -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.LocalMinimumInteractiveComponentSize import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.SheetValue import androidx.compose.material3.SnackbarHostState -import androidx.compose.material3.rememberBottomSheetScaffoldState -import androidx.compose.material3.rememberStandardBottomSheetState +import androidx.compose.material3.darkColorScheme import androidx.compose.runtime.Composable -import androidx.compose.runtime.CompositionLocalProvider -import androidx.compose.runtime.DisposableEffect -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberUpdatedState -import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.geometry.Rect import androidx.compose.ui.graphics.Color -import androidx.compose.ui.layout.AlignmentLine import androidx.compose.ui.layout.HorizontalAlignmentLine -import androidx.compose.ui.layout.Layout -import androidx.compose.ui.layout.Placeable -import androidx.compose.ui.layout.layoutId -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.semantics.Role -import androidx.compose.ui.unit.Constraints -import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.max -import androidx.compose.ui.unit.min -import androidx.compose.ui.unit.takeOrElse -import com.google.jetpackcamera.ui.components.capture.layout.CameraLayoutDefaults -import com.google.jetpackcamera.ui.components.capture.layout.CameraLayoutSolver -import com.google.jetpackcamera.ui.components.capture.layout.CameraRowIds -import com.google.jetpackcamera.ui.components.capture.layout.CameraWindow -import com.google.jetpackcamera.ui.components.capture.layout.LocalCameraLayoutSolution - -/** - * Height of the shutter row (capture button, image well and flip camera button) as specified by - * the design spec. - */ -private val SHUTTER_STACK_HEIGHT = 86.dp - -/** - * Height of the slot reserved between the shutter row and the lower controls row. The design spec - * reserves this space unconditionally so that optional content can appear there without shifting - * any of the surrounding controls. - */ -private val MIDDLE_SLOT_HEIGHT = 32.dp - -/** - * Height of the lower controls row (quick settings and capture mode toggles). - * - * This is a hard height, and it currently has no slack: it is exactly the default height of the - * toggle switch it contains. Keep it greater than or equal to that default, otherwise the row - * will silently clip its contents. - */ -private val LOWER_SECTION_HEIGHT = 64.dp - -/** Vertical gap between the zoom bar and the shutter row on large screens. */ -private val ZOOM_TO_SHUTTER_GAP = 32.dp - -/** Minimum safety gap between the zoom bar and the shutter row. */ -private val MIN_ZOOM_TO_SHUTTER_GAP = 16.dp - -/** Maximum target vertical gap above and below the reserved middle slot. */ -private val CONTROL_STACK_MAX_GAP = 24.dp - -/** Minimum compressed vertical gap above and below the reserved middle slot. */ -private val CONTROL_STACK_MIN_GAP = 12.dp - -/** - * Target clearance from the bottom of the display to the lower controls row, keeping the - * controls at a consistent thumb resting position across navigation bar modes (gesture vs - * 3-button navigation). - */ -private val TARGET_BOTTOM_CLEARANCE = 56.dp - -/** Minimum safety margin between the lower controls row and the navigation bar. */ -private val MIN_NAV_MARGIN = 8.dp - -/** Minimum compressed bottom padding used on short screens. */ -private val MIN_CONTROLS_BOTTOM_PADDING = 12.dp - -/** Available height below which the control stack compresses its gaps. */ -private val SHORT_SCREEN_THRESHOLD = 600.dp - -/** Horizontal inset of the lower controls row and top indicator bar. */ -private val LOWER_SECTION_HORIZONTAL_PADDING = 16.dp - -/** Minimum height/width aspect ratio treated as a portrait handheld window (16:9 with float slack). */ -private const val PORTRAIT_ASPECT_RATIO_THRESHOLD = 16f / 9f - 0.01f - -/** Minimum bottom gesture inset floor used when solving the portrait control stack. */ -private val MIN_GESTURE_INSET = 32.dp /** * The top edge of the visible viewfinder, reported by a viewfinder that fills its slot and offsets @@ -177,36 +64,21 @@ internal val ViewfinderTopLine = HorizontalAlignmentLine { a, b -> minOf(a, b) } * @param indicatorRow the top indicator row composable. * @param captureModeToggle the capture mode toggle composable. * @param captureModeCarousel content for the fixed-height slot reserved between the shutter row - * and the lower controls row. The slot is always reserved, so supplying or omitting content here - * never moves the surrounding controls. The content is centered on the slot and may be taller - * than it, for example to provide a larger touch target, extending equally into the gaps above - * and below the slot without overlapping the neighboring rows. + * and the lower controls row. * @param quickSettingsOverlay the quick settings overlay composable. * @param overlay optional overlay composable drawn above the viewfinder and controls. * @param controlsVisible whether the camera controls should be composed and visible. * @param screenFlashOverlay the screen flash overlay composable, drawn above all other content - * (including the quick settings sheet) and across the entire window, including the system bar - * and display cutout areas. + * and across the entire window, including system bar and display cutout areas. * @param snackBar the snack bar composable for showing messages against [SnackbarHostState]. - * @param topStartContent optional composable content placed at the top-start of the capture - * screen, at a fixed position directly below the top status/indicator bar. Because the viewfinder - * can move below this content, the content receives a [PreviewOverlaySlotScope] that reports - * whether it is currently over the viewfinder. + * @param topStartContent optional composable content placed at the top-start of the capture screen. * @param viewfinderTopEndContent optional composable content anchored to the top-end corner of the - * viewfinder. While [topStartContent] is inside the viewfinder, this content shares its vertical - * origin directly below the top bar, so both top slots stay aligned. When the viewfinder shifts - * below [topStartContent], this content moves down with the top edge of the viewfinder while - * [topStartContent] stays in place. Like [topStartContent], this content receives a - * [PreviewOverlaySlotScope]. - * @param topBarTrailingContent optional composable content aligned to the end of the top - * status/indicator bar. + * viewfinder. + * @param topBarTrailingContent optional composable content aligned to the end of the top bar. * @param onRequiresImmersiveChange invoked with `true` when the window is too short for the - * tallest viewfinder to clear a persistent navigation bar, and with `false` when it no longer is - * or when the adaptive portrait layout leaves the composition. + * tallest viewfinder to clear a persistent navigation bar, and `false` otherwise or on dispose. * @param errorDialog the camera error alert dialog composable. */ -@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) -@Suppress("DEPRECATION") @Composable fun CaptureScaffoldLayout( modifier: Modifier = Modifier, @@ -233,789 +105,111 @@ fun CaptureScaffoldLayout( onRequiresImmersiveChange: (Boolean) -> Unit = {}, errorDialog: @Composable (Modifier) -> Unit = {} ) { - val bottomSheetState = rememberStandardBottomSheetState( - initialValue = if (state.isQuickSettingsOpen) SheetValue.Expanded else SheetValue.Hidden, - skipHiddenState = false, - confirmValueChange = { targetValue -> - if (targetValue == SheetValue.Hidden) { - state.dismissQuickSettings() - } else if (targetValue == SheetValue.Expanded) { - state.showQuickSettings() - } - true - } + val slots = CaptureSlots( + topBar = indicatorRow, + topBarTrailingContent = topBarTrailingContent, + zoomControls = zoomLevelDisplay, + quickSettingsButton = quickSettingsButton, + captureButton = captureButton, + flipCameraButton = flipCameraButton, + imageWell = imageWell, + captureModeToggle = captureModeToggle, + captureModeCarousel = captureModeCarousel, + elapsedTimeDisplay = elapsedTimeDisplay, + topStartContent = topStartContent, + viewfinderTopEndContent = viewfinderTopEndContent, + quickSettingsOverlay = { slotModifier -> quickSettingsOverlay(slotModifier) }, + snackBar = snackBar, + errorDialog = errorDialog ) - val scaffoldState = rememberBottomSheetScaffoldState( - bottomSheetState = bottomSheetState, - snackbarHostState = state.snackbarHostState + CompactPortraitLayout( + slots = slots, + viewfinder = viewfinder, + modifier = modifier, + state = state, + controlsVisible = controlsVisible, + includeStatusBarsInTopBar = false, + onDismissQuickSettings = onDismissQuickSettings, + onRequiresImmersiveChange = onRequiresImmersiveChange, + overlay = overlay, + screenFlashOverlay = screenFlashOverlay ) - LaunchedEffect(state.isQuickSettingsOpen) { - if (state.isQuickSettingsOpen) { - if (bottomSheetState.targetValue != SheetValue.Expanded) { - bottomSheetState.expand() - } - } else { - if (bottomSheetState.isVisible || bottomSheetState.targetValue != SheetValue.Hidden) { - bottomSheetState.hide() - } - } - } - - val overlapTargetBounds = remember { mutableStateOf(Rect.Zero) } - val dismissQuickSettingsLabel = - stringResource(R.string.quick_settings_btn_close_expanded_settings_description) - val handleDismissQuickSettings = { - state.dismissQuickSettings() - onDismissQuickSettings() - } - - 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 = handleDismissQuickSettings - ) - ) - }, - sheetShape = RoundedCornerShape(topStart = 28.dp, topEnd = 28.dp), - sheetContainerColor = MaterialTheme.colorScheme.surfaceContainerLow, - sheetContent = { - quickSettingsOverlay(Modifier) - }, - snackbarHost = {} - ) { - BoxWithConstraints(modifier = Modifier.fillMaxSize().background(Color.Black)) { - // The adaptive portrait solver targets portrait handhelds (16:9 and taller, - // where a full-width 9:16 frame fits inside the window). Squarer windows - // (landscape, foldable inner displays, or short split-screen panes like - // 360x500) fall back to VerticalMaterialControls, which compresses below - // SHORT_SCREEN_THRESHOLD. - val isHandheldPortrait = - (maxHeight.value / maxWidth.value) >= PORTRAIT_ASPECT_RATIO_THRESHOLD - if (isHandheldPortrait) { - AdaptivePortraitCaptureLayout( - windowWidth = maxWidth, - windowHeight = maxHeight, - viewfinder = viewfinder, - topStartContent = topStartContent, - viewfinderTopEndContent = viewfinderTopEndContent, - onRequiresImmersiveChange = onRequiresImmersiveChange, - indicatorRow = indicatorRow, - topBarTrailingContent = topBarTrailingContent, - elapsedTimeDisplay = elapsedTimeDisplay, - zoomControls = zoomLevelDisplay, - imageWell = imageWell, - captureButton = captureButton, - flipCameraButton = flipCameraButton, - captureModeCarousel = captureModeCarousel, - quickSettingsToggleButton = quickSettingsButton, - captureModeToggleSwitch = captureModeToggle, - controlsVisible = controlsVisible, - snackbarHost = { snackbarModifier -> - PillSnackbarHost( - snackbarHostState = state.snackbarHostState, - modifier = snackbarModifier - ) - } - ) - Box( - modifier = Modifier - .fillMaxSize() - .windowInsetsPadding( - WindowInsets.systemBarsIgnoringVisibility - .union(WindowInsets.displayCutout) - ) - ) { - snackBar(Modifier, state.snackbarHostState) - } - } else { - Column { - val cutoutTopInset = - WindowInsets.displayCutout.asPaddingValues().calculateTopPadding() - val minTouchTarget = - LocalMinimumInteractiveComponentSize.current.takeOrElse { 48.dp } - val topBarHeight = max(cutoutTopInset, minTouchTarget) - Box( - modifier = Modifier - .fillMaxWidth() - .height(topBarHeight) - .windowInsetsPadding( - WindowInsets.displayCutout.only( - WindowInsetsSides.Horizontal - ) - ) - .padding(horizontal = LOWER_SECTION_HORIZONTAL_PADDING), - contentAlignment = Alignment.CenterStart - ) { - OverlapAwareStyleProvider { - indicatorRow(Modifier) - } - OverlapAwareStyleProvider(Modifier.align(Alignment.CenterEnd)) { - topBarTrailingContent(Modifier) - } - } - Box { - viewfinder(Modifier) - OverlapAwareStyleProvider(Modifier.align(Alignment.TopStart)) { - topStartContent(Modifier) - } - OverlapAwareStyleProvider(Modifier.align(Alignment.TopEnd)) { - viewfinderTopEndContent(Modifier) - } - } - } - - Box( - modifier = Modifier - .fillMaxSize() - .windowInsetsPadding( - WindowInsets.systemBarsIgnoringVisibility - .union(WindowInsets.displayCutout) - ) - ) { - if (controlsVisible) { - VerticalMaterialControls( - captureButton = captureButton, - imageWell = imageWell, - flipCameraButton = flipCameraButton, - quickSettingsToggleButton = quickSettingsButton, - captureModeToggleSwitch = captureModeToggle, - captureModeCarousel = captureModeCarousel, - zoomControls = zoomLevelDisplay, - elapsedTimeDisplay = elapsedTimeDisplay, - snackbarHost = { snackbarModifier -> - PillSnackbarHost( - snackbarHostState = state.snackbarHostState, - modifier = snackbarModifier - ) - } - ) - } - snackBar(Modifier, state.snackbarHostState) - } - } - OverlapAwareStyleProvider { - overlay(Modifier) - } - - val isSheetVisible = state.isQuickSettingsOpen || - bottomSheetState.isVisible || - bottomSheetState.targetValue == SheetValue.Expanded - if (isSheetVisible) { - Box( - modifier = Modifier - .fillMaxSize() - .testTag(QUICK_SETTINGS_SCRIM) - .clickable( - onClickLabel = dismissQuickSettingsLabel, - interactionSource = remember { MutableInteractionSource() }, - indication = null, - onClick = handleDismissQuickSettings - ) - ) - } - 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) - } - } } -private enum class CaptureSlotId { - Viewfinder, - TopStartContent, - ViewfinderTopEndContent, - TopBar, - ElapsedTime, - ZoomBar, - CaptureRow, - ModeSwitcher, - BottomToolbar -} - -@OptIn(ExperimentalLayoutApi::class) +@PreviewPortraitDevices @Composable -private fun AdaptivePortraitCaptureLayout( - windowWidth: Dp, - windowHeight: Dp, - viewfinder: @Composable (Modifier) -> Unit, - topStartContent: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, - viewfinderTopEndContent: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, - onRequiresImmersiveChange: (Boolean) -> Unit, - indicatorRow: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, - topBarTrailingContent: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, - elapsedTimeDisplay: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, - zoomControls: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, - imageWell: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, - captureButton: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, - flipCameraButton: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, - captureModeCarousel: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, - quickSettingsToggleButton: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, - captureModeToggleSwitch: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, - controlsVisible: Boolean, - snackbarHost: @Composable (Modifier) -> Unit = {} -) { - val cutoutTopInset = WindowInsets.displayCutout.asPaddingValues().calculateTopPadding() - val navInset = WindowInsets.navigationBarsIgnoringVisibility - .asPaddingValues() - .calculateBottomPadding() - val rawGestureInset = WindowInsets.systemGestures - .asPaddingValues() - .calculateBottomPadding() - val effectiveGestureInset = max(MIN_GESTURE_INSET, rawGestureInset) - val minTouchTarget = LocalMinimumInteractiveComponentSize.current.takeOrElse { 48.dp } - val topBarHeight = max(cutoutTopInset, minTouchTarget) - - val window = remember( - windowWidth, - windowHeight, - topBarHeight, - navInset, - effectiveGestureInset - ) { - CameraWindow( - width = windowWidth, - height = windowHeight, - topInset = topBarHeight, - navInset = navInset, - gestureInset = effectiveGestureInset - ) - } - - // The solve depends only on the window geometry, the insets, and the accessibility touch - // target. Row heights are deliberately *not* measured and fed back in: ControlRow.height is - // contractually the row's *reserved* height, so that showing or hiding a row's content never - // moves the rows around it. Measuring the children and re-solving would both break that - // guarantee and turn the solve into a per-measure-pass cost. - val spec = remember(minTouchTarget) { - CameraLayoutDefaults.spec(minInteractiveTouchTarget = minTouchTarget) - } - val solution = remember(spec, window) { CameraLayoutSolver.solve(spec, window) } - - // Report whether the navigation bar has to be hidden rather than hiding it here, so that a - // single owner controls system bar visibility. Leaving the composition reports `false`, so the - // request never outlives this layout. - val currentOnRequiresImmersiveChange by rememberUpdatedState(onRequiresImmersiveChange) - DisposableEffect(solution.requiresImmersive) { - currentOnRequiresImmersiveChange(solution.requiresImmersive) - onDispose { currentOnRequiresImmersiveChange(false) } - } - - CompositionLocalProvider(LocalCameraLayoutSolution provides solution) { - Layout( - modifier = Modifier.fillMaxSize(), - content = { - Box(modifier = Modifier.layoutId(CaptureSlotId.Viewfinder)) { - viewfinder(Modifier) - } - - Box(modifier = Modifier.layoutId(CaptureSlotId.TopStartContent)) { - OverlapAwareStyleProvider { - topStartContent(Modifier) - } - } - - Box(modifier = Modifier.layoutId(CaptureSlotId.ViewfinderTopEndContent)) { - OverlapAwareStyleProvider { - viewfinderTopEndContent(Modifier) - } - } - +private fun CaptureLayoutPreview() { + MaterialTheme(colorScheme = darkColorScheme()) { + CaptureScaffoldLayout( + modifier = Modifier.background(Color.Black), + viewfinder = { modifier -> Box( - modifier = Modifier - .layoutId(CaptureSlotId.TopBar) + modifier = modifier .fillMaxWidth() - .height(topBarHeight) - .windowInsetsPadding( - WindowInsets.displayCutout.only(WindowInsetsSides.Horizontal) - ) - .padding(horizontal = LOWER_SECTION_HORIZONTAL_PADDING), - contentAlignment = Alignment.CenterStart - ) { - OverlapAwareStyleProvider { - indicatorRow(Modifier) - } - OverlapAwareStyleProvider(Modifier.align(Alignment.CenterEnd)) { - topBarTrailingContent(Modifier) - } - } - - if (controlsVisible) { - Column( - modifier = Modifier.layoutId(CaptureSlotId.ElapsedTime), - horizontalAlignment = Alignment.CenterHorizontally - ) { - snackbarHost(Modifier) - OverlapAwareStyleProvider { - elapsedTimeDisplay(Modifier) - } - } - - Box( - modifier = Modifier.layoutId(CaptureSlotId.ZoomBar), - contentAlignment = Alignment.Center - ) { - OverlapAwareStyleProvider { - zoomControls(Modifier) - } - } - - Row( - modifier = Modifier - .layoutId(CaptureSlotId.CaptureRow) - .fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically - ) { - Row( - Modifier.weight(1f), - horizontalArrangement = Arrangement.SpaceEvenly - ) { - Box( - modifier = Modifier - .weight(1f) - .fillMaxHeight(), - contentAlignment = Alignment.Center - ) { - OverlapAwareStyleProvider { - imageWell(Modifier) - } - } - } - - OverlapAwareStyleProvider { - captureButton(Modifier) - } - - Box( - modifier = Modifier - .weight(1f) - .fillMaxHeight(), - contentAlignment = Alignment.Center - ) { - OverlapAwareStyleProvider { - flipCameraButton(Modifier) - } - } - } - - Box( - modifier = Modifier - .layoutId(CaptureSlotId.ModeSwitcher) - .fillMaxWidth(), - contentAlignment = Alignment.Center - ) { - OverlapAwareStyleProvider { - captureModeCarousel(Modifier) - } - } - - Row( - modifier = Modifier - .layoutId(CaptureSlotId.BottomToolbar) - .fillMaxWidth() - .padding(horizontal = LOWER_SECTION_HORIZONTAL_PADDING), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.Center - ) { - Box( - modifier = Modifier.weight(1f), - contentAlignment = Alignment.CenterStart - ) { - OverlapAwareStyleProvider { - quickSettingsToggleButton(Modifier) - } - } - - Box( - modifier = Modifier.weight(1f), - contentAlignment = Alignment.Center - ) { - OverlapAwareStyleProvider { - captureModeToggleSwitch(Modifier) - } - } - - Box( - modifier = Modifier.weight(1f), - contentAlignment = Alignment.CenterEnd - ) {} - } - } - } - ) { measurables, constraints -> - val looseConstraints = constraints.copy(minWidth = 0, minHeight = 0) - val fullWidthLooseHeight = constraints.copy(minHeight = 0) - - // Each control row is measured against the band the solver reserved for it, so a row's - // content can never push its neighbours around. The solver has already accounted for - // toolbar compaction, so BOTTOM_TOOLBAR's band is the compacted height where that - // applies. - fun bandOf(rowId: String) = solution.rowBands.getValue(rowId) - - fun measureInBand(slot: CaptureSlotId, rowId: String): Pair? { - val measurable = measurables.firstOrNull { it.layoutId == slot } ?: return null - val band = bandOf(rowId) - val placeable = measurable.measure( - Constraints.fixed(constraints.maxWidth, band.height.roundToPx()) + .aspectRatio(3f / 4f) + .background(Color.DarkGray) ) - return placeable to band.top.roundToPx() - } - - val topBarPlaceable = measurables - .firstOrNull { it.layoutId == CaptureSlotId.TopBar } - ?.measure(fullWidthLooseHeight) - val topStartPlaceable = measurables - .firstOrNull { it.layoutId == CaptureSlotId.TopStartContent } - ?.measure(looseConstraints) - val elapsedTimePlaceable = measurables - .firstOrNull { it.layoutId == CaptureSlotId.ElapsedTime } - ?.measure(looseConstraints) - - val zoomBar = measureInBand(CaptureSlotId.ZoomBar, CameraRowIds.ZOOM_BAR) - val captureRow = measureInBand(CaptureSlotId.CaptureRow, CameraRowIds.CAPTURE_ROW) - // The mode switcher's band is the switcher's reserved visual height. Its content may - // be taller, for example a carousel with a larger touch target, so it is measured up to - // the band plus the smaller of the two gaps around it, once on each side, and centered - // on the band. The content then never overlaps the neighboring rows and never moves - // them. - val modeSwitcher = measurables - .firstOrNull { it.layoutId == CaptureSlotId.ModeSwitcher } - ?.let { measurable -> - val band = bandOf(CameraRowIds.MODE_SWITCHER) - val clearance = min( - band.top - bandOf(CameraRowIds.CAPTURE_ROW).bottom, - bandOf(CameraRowIds.BOTTOM_TOOLBAR).top - band.bottom - ).coerceAtLeast(0.dp) - val bandHeightPx = band.height.roundToPx() - val placeable = measurable.measure( - Constraints( - minWidth = constraints.maxWidth, - maxWidth = constraints.maxWidth, - minHeight = bandHeightPx, - maxHeight = (band.height + clearance * 2).roundToPx() - ) - ) - placeable to band.top.roundToPx() - (placeable.height - bandHeightPx) / 2 - } - val bottomToolbar = - measureInBand(CaptureSlotId.BottomToolbar, CameraRowIds.BOTTOM_TOOLBAR) - - val viewfinderPlaceable = measurables - .firstOrNull { it.layoutId == CaptureSlotId.Viewfinder } - ?.measure(looseConstraints) - - // A viewfinder that is exactly as tall as one of the solved frames is placed at that - // frame's band. A viewfinder that fills the slot (such as PreviewDisplay) positions its - // own frame and is placed at the top. - val viewfinderY = viewfinderPlaceable?.let { vf -> - if (vf.height in 1 until constraints.maxHeight) { - val ratio = vf.width.toFloat() / vf.height.toFloat() - solution.viewfinderBandFor(ratio, spec.viewfinders)?.top?.roundToPx() - } else { - null - } - } ?: 0 - // The top edge of the visible frame, in this layout's coordinates. Viewfinders that - // position their own frame report it through ViewfinderTopLine. - val activeVfTopPx = viewfinderPlaceable?.let { vf -> - val reportedTop = vf[ViewfinderTopLine] - viewfinderY + if (reportedTop == AlignmentLine.Unspecified) 0 else reportedTop - } - - // While topStartContent is inside the viewfinder (full-bleed, flush with the top bar, - // or a frame that passes behind it), viewfinderTopEndContent shares its vertical - // origin. Once the frame shifts below topStartContent, it follows the frame's top edge. - val topBarHeightPx = topBarHeight.roundToPx() - val viewfinderTopEndY = if ( - activeVfTopPx == null || - activeVfTopPx <= (topBarHeight + spec.topStartHeight).roundToPx() - ) { - topBarHeightPx - } else { - activeVfTopPx - } - val viewfinderEnd = viewfinderPlaceable?.let { vf -> - (constraints.maxWidth + vf.width) / 2 - } ?: constraints.maxWidth - // While the two top slots overlap vertically, viewfinderTopEndContent is limited to - // the width left beside topStartContent so that the two never overlap. - val sharesTopStartRows = topStartPlaceable != null && - viewfinderTopEndY < topBarHeightPx + topStartPlaceable.height - val viewfinderTopEndMaxWidth = if (sharesTopStartRows) { - viewfinderEnd - topStartPlaceable.width - } else { - viewfinderEnd - }.coerceAtLeast(0) - val viewfinderTopEndPlaceable = measurables - .firstOrNull { it.layoutId == CaptureSlotId.ViewfinderTopEndContent } - ?.measure(looseConstraints.copy(maxWidth = viewfinderTopEndMaxWidth)) - - layout(constraints.maxWidth, constraints.maxHeight) { - viewfinderPlaceable?.let { vf -> - val vfX = (constraints.maxWidth - vf.width) / 2 - vf.placeRelative(vfX, viewfinderY) - } - - topStartPlaceable?.placeRelative(0, topBarHeightPx) - viewfinderTopEndPlaceable?.let { topEnd -> - topEnd.placeRelative(viewfinderEnd - topEnd.width, viewfinderTopEndY) - } - - topBarPlaceable?.placeRelative(0, 0) - - // The elapsed time readout is not a solver row: it is an optional caption that - // hangs above the zoom bar, so it is placed relative to that band rather than - // reserving a band of its own. - zoomBar?.let { (_, zoomTop) -> - elapsedTimePlaceable?.let { elapsed -> - val elapsedX = (constraints.maxWidth - elapsed.width) / 2 - elapsed.placeRelative(elapsedX, zoomTop - elapsed.height) - } - } - - zoomBar?.let { (placeable, top) -> placeable.placeRelative(0, top) } - captureRow?.let { (placeable, top) -> placeable.placeRelative(0, top) } - modeSwitcher?.let { (placeable, top) -> placeable.placeRelative(0, top) } - bottomToolbar?.let { (placeable, top) -> placeable.placeRelative(0, top) } - } - } - } -} - -@OptIn(ExperimentalLayoutApi::class) -@Composable -private fun VerticalMaterialControls( - modifier: Modifier = Modifier, - captureButton: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, - zoomControls: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, - imageWell: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, - flipCameraButton: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, - quickSettingsToggleButton: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, - captureModeToggleSwitch: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, - captureModeCarousel: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit = {}, - elapsedTimeDisplay: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, - snackbarHost: @Composable (Modifier) -> Unit = {} -) { - BoxWithConstraints( - modifier = modifier.fillMaxSize(), - contentAlignment = Alignment.BottomCenter - ) { - // This layout is only used for windows that are not portrait handhelds (see - // CaptureScaffoldLayout), so it does not track the viewfinder. Short windows, such as - // landscape phones, compress the stack to its minimum spacing. - val navBarBottom = WindowInsets.navigationBarsIgnoringVisibility - .asPaddingValues() - .calculateBottomPadding() - val isShortScreen = maxHeight < SHORT_SCREEN_THRESHOLD - val maxBottomPad = max(TARGET_BOTTOM_CLEARANCE - navBarBottom, MIN_NAV_MARGIN) - val bottomPad = if (isShortScreen) { - min(MIN_CONTROLS_BOTTOM_PADDING, maxBottomPad) - } else { - maxBottomPad - } - val stackGap = if (isShortScreen) CONTROL_STACK_MIN_GAP else CONTROL_STACK_MAX_GAP - val zoomGap = if (isShortScreen) MIN_ZOOM_TO_SHUTTER_GAP else ZOOM_TO_SHUTTER_GAP - - Column(modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Bottom) { - Column(modifier = modifier, horizontalAlignment = Alignment.CenterHorizontally) { - snackbarHost(Modifier) - - OverlapAwareStyleProvider { - elapsedTimeDisplay(Modifier) - } - - // zoom controls row - OverlapAwareStyleProvider { - zoomControls(Modifier) - } - - Spacer(modifier = Modifier.height(zoomGap)) - - // capture button row - Column { - Row( - Modifier - .fillMaxWidth() - .height(SHUTTER_STACK_HEIGHT), - verticalAlignment = Alignment.CenterVertically - ) { - // Row that holds flip camera, capture button, and audio - Row(Modifier.weight(1f), horizontalArrangement = Arrangement.SpaceEvenly) { - // animation fades in/out this component based on quick settings - Box( - modifier = Modifier - .weight(1f) - .fillMaxHeight(), - contentAlignment = Alignment.Center - ) { - OverlapAwareStyleProvider { - imageWell(Modifier) - } - } - } - - OverlapAwareStyleProvider { - captureButton(Modifier) - } - - // right capturebutton item - Box( - modifier = Modifier - .weight(1f) - .fillMaxHeight(), - contentAlignment = Alignment.Center - ) { - OverlapAwareStyleProvider { - flipCameraButton(Modifier) - } - } - } - } - - // Slot reserved by the design spec between the shutter row and the lower controls - // row, together with the gaps above and below it. Its height is fixed whether or - // not it has content, so the shutter row never moves when content appears here. - // Content is centered, so content taller than MIDDLE_SLOT_HEIGHT, such as a carousel - // with a larger touch target, extends equally into both gaps. + }, + captureButton = { modifier -> + Box( + modifier = modifier + .size(80.dp) + .background(Color.White) + ) + }, + flipCameraButton = { modifier -> + Box( + modifier = modifier + .size(48.dp) + .background(Color.Cyan) + ) + }, + imageWell = { modifier -> Box( - modifier = Modifier + modifier = modifier + .size(48.dp) + .background(Color.Cyan) + ) + }, + zoomLevelDisplay = { modifier -> + Box( + modifier = modifier + .height(48.dp) .fillMaxWidth() - .height(MIDDLE_SLOT_HEIGHT + stackGap * 2), - contentAlignment = Alignment.Center - ) { - OverlapAwareStyleProvider { - captureModeCarousel(Modifier) - } - } - - // bottom controls row - Row( - Modifier + .background(Color.Magenta) + ) + }, + elapsedTimeDisplay = { modifier -> + Box( + modifier = modifier + .height(24.dp) + .fillMaxWidth(0.5f) + .background(Color.Red) + ) + }, + quickSettingsButton = { modifier -> + Box( + modifier = modifier + .size(48.dp) + .background(Color.Yellow) + ) + }, + indicatorRow = { modifier -> + Box( + modifier = modifier + .height(48.dp) .fillMaxWidth() - .height(LOWER_SECTION_HEIGHT) - .padding(horizontal = LOWER_SECTION_HORIZONTAL_PADDING), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.Center - ) { - // Row that holds toggle buttons for quick settings and capture mode - // quick settings toggle switch item to the left - Box( - modifier = Modifier.weight(1f), - contentAlignment = Alignment.CenterStart - ) { - OverlapAwareStyleProvider { - quickSettingsToggleButton(Modifier) - } - } - - // capture mode toggle switch center - Box( - modifier = Modifier.weight(1f), - contentAlignment = Alignment.Center - ) { - OverlapAwareStyleProvider { - captureModeToggleSwitch(Modifier) - } - } - - // right toggle switch item to the right - Box( - modifier = Modifier.weight(1f), - contentAlignment = Alignment.CenterEnd - ) {} - } - - Spacer(modifier = Modifier.height(bottomPad)) + .background(Color.Green) + ) + }, + captureModeToggle = { modifier -> + Box( + modifier = modifier + .height(48.dp) + .fillMaxWidth(0.5f) + .background(Color.Blue) + ) } - } + ) } } - -@PreviewPortraitDevices -@Composable -private fun CaptureLayoutPreview() { - CaptureScaffoldLayout( - modifier = Modifier.background(Color.Black), - viewfinder = { modifier -> - Box( - modifier = modifier - .fillMaxWidth() - .aspectRatio(3f / 4f) - .background(Color.DarkGray) - ) - }, - captureButton = { modifier -> - Box( - modifier = modifier - .size(80.dp) - .background(Color.White) - ) - }, - flipCameraButton = { modifier -> - Box( - modifier = modifier - .size(48.dp) - .background(Color.Cyan) - ) - }, - imageWell = { modifier -> - Box( - modifier = modifier - .size(48.dp) - .background(Color.Cyan) - ) - }, - zoomLevelDisplay = { modifier -> - Box( - modifier = modifier - .height(48.dp) - .fillMaxWidth() - .background(Color.Magenta) - ) - }, - elapsedTimeDisplay = { modifier -> - Box( - modifier = modifier - .height(24.dp) - .fillMaxWidth(0.5f) - .background(Color.Red) - ) - }, - quickSettingsButton = { modifier -> - Box( - modifier = modifier - .size(48.dp) - .background(Color.Yellow) - ) - }, - indicatorRow = { modifier -> - Box( - modifier = modifier - .height(48.dp) - .fillMaxWidth() - .background(Color.Green) - ) - }, - captureModeToggle = { modifier -> - Box( - modifier = modifier - .height(48.dp) - .fillMaxWidth(0.5f) - .background(Color.Blue) - ) - } - ) -} diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CompactPortraitLayout.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CompactPortraitLayout.kt new file mode 100644 index 000000000..0a8f91444 --- /dev/null +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CompactPortraitLayout.kt @@ -0,0 +1,1124 @@ +/* + * 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 androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.gestures.Orientation +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.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.WindowInsetsSides +import androidx.compose.foundation.layout.asPaddingValues +import androidx.compose.foundation.layout.displayCutout +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.navigationBarsIgnoringVisibility +import androidx.compose.foundation.layout.only +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.statusBars +import androidx.compose.foundation.layout.systemBarsIgnoringVisibility +import androidx.compose.foundation.layout.systemGestures +import androidx.compose.foundation.layout.union +import androidx.compose.foundation.layout.windowInsetsPadding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.BottomSheetDefaults +import androidx.compose.material3.BottomSheetScaffold +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.LocalMinimumInteractiveComponentSize +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.SheetValue +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.minimumInteractiveComponentSize +import androidx.compose.material3.rememberBottomSheetScaffoldState +import androidx.compose.material3.rememberBottomSheetState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.ProvidableCompositionLocal +import androidx.compose.runtime.compositionLocalOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.focusProperties +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.layout.AlignmentLine +import androidx.compose.ui.layout.Layout +import androidx.compose.ui.layout.Placeable +import androidx.compose.ui.layout.layoutId +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.LocalLayoutDirection +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.hideFromAccessibility +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.traversalIndex +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.Constraints +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.max +import androidx.compose.ui.unit.min +import androidx.compose.ui.unit.takeOrElse +import com.google.jetpackcamera.ui.components.capture.layout.CameraLayoutDefaults +import com.google.jetpackcamera.ui.components.capture.layout.CameraLayoutSolver +import com.google.jetpackcamera.ui.components.capture.layout.CameraRowIds +import com.google.jetpackcamera.ui.components.capture.layout.CameraWindow +import com.google.jetpackcamera.ui.components.capture.layout.LocalCameraLayoutSolution + +/** + * CompositionLocal providing the exact active posture layout composable name rendered by + * [CaptureScaffoldLayout] (`"CompactPortraitLayout"`, `"CompactShortLayout"`, `"FoldableLayout"`, + * `"TabletPortraitLayout"`, or `"TabletLandscapeLayout"`). + */ +val LocalActiveCaptureLayout: ProvidableCompositionLocal = + compositionLocalOf { "CompactPortraitLayout" } + +/** + * Dimension and spacing constants used by [CompactPortraitLayout]. + */ +internal object CompactPortraitTokens { + val SheetPeekHeight = 0.dp + val SheetTopCornerRadius = 28.dp + val DefaultMinTouchTarget = 48.dp + val ZeroInset = 0.dp + + /** + * Height of the shutter row (capture button, image well and flip camera button) as specified + * by the design spec. + */ + val ShutterStackHeight = 86.dp + + /** + * Height of the slot reserved between the shutter row and the lower controls row. Reserved + * unconditionally so optional content can appear without shifting surrounding controls. + */ + val MiddleSlotHeight = 32.dp + + /** + * Height of the lower controls row (quick settings and capture mode toggles). + */ + val LowerSectionHeight = 64.dp + + /** Vertical gap between the zoom bar and the shutter row on standard screens. */ + val ZoomToShutterGap = 32.dp + + /** Minimum safety gap between the zoom bar and the shutter row on short screens. */ + val MinZoomToShutterGap = 16.dp + + /** Maximum target vertical gap above and below the reserved middle slot. */ + val ControlStackMaxGap = 24.dp + + /** Minimum compressed vertical gap above and below the reserved middle slot. */ + val ControlStackMinGap = 12.dp + + /** + * Target clearance from the bottom of the display to the lower controls row across navigation + * bar modes. + */ + val TargetBottomClearance = 56.dp + + /** Minimum safety margin between the lower controls row and the navigation bar. */ + val MinNavMargin = 8.dp + + /** Minimum compressed bottom padding used on short screens. */ + val MinControlsBottomPadding = 12.dp + + /** Available height below which the fallback control stack compresses its gaps. */ + val ShortScreenThreshold = 600.dp + + /** Horizontal inset of the lower controls row and top indicator bar. */ + val LowerSectionHorizontalPadding = 16.dp + + /** Minimum height/width aspect ratio treated as a portrait handheld window (16:9). */ + const val PORTRAIT_ASPECT_RATIO_THRESHOLD = 16f / 9f - 0.01f + + /** Minimum bottom gesture inset floor used when solving the portrait control stack. */ + val MinGestureInset = 32.dp +} + +private enum class CaptureSlotId { + Viewfinder, + TopStartContent, + ViewfinderTopEndContent, + TopBar, + ElapsedTime, + ZoomBar, + CaptureRow, + ModeSwitcher, + BottomToolbar +} + +/** + * Prunes keyboard/rotary focus and Android accessibility traversal on background camera chrome + * while an in-hierarchy modal surface (such as Quick Settings or an error dialog) is open above it, + * without stripping Compose test tags or semantic actions inside [PreviewOverlaySlotScope] slots. + */ +internal fun Modifier.suppressBackgroundForModal(isModalOpen: Boolean): Modifier = + if (isModalOpen) { + this + .focusProperties { canFocus = false } + .semantics { hideFromAccessibility() } + } else { + this + } + +/** + * Compact capture layout driven by a [CaptureSlots] slot table. + * + * Hosts the camera viewfinder, top status/indicator bar, bottom control stack, and an in-hierarchy + * [BottomSheetScaffold] for Quick Settings controlled by [state] without spawning secondary + * windows. Tags its root container with [COMPACT_CONTROLS_TAG], provides + * [LocalActiveCaptureLayout] = `"CompactPortraitLayout"`, and scopes [LocalCaptureRtlPolicy] + * (`mirrorCompactBottomBar`) exclusively to the horizontal capture and bottom-toolbar rows while + * restoring the active locale's `LayoutDirection` inside every child slot. + * + * @param slots [CaptureSlots] supplying the capture screen UI controls and overlays. + * @param viewfinder Composable rendering the camera preview frame. + * @param modifier [Modifier] applied to the outer layout container. + * @param state Mode-agnostic [CaptureScaffoldState] controlling the Quick Settings bottom sheet and + * snackbar host. + * @param controlsVisible Whether the camera control slots should be composed and visible. + * @param isErrorDialogShowing Whether a modal camera error dialog is currently visible above the + * capture chrome. + * @param includeStatusBarsInTopBar Whether live visible `WindowInsets.statusBars` top padding is + * included in the top indicator bar so multi-window status bars never overlap status indicators. + * @param onDismissQuickSettings Callback invoked when Quick Settings is dismissed via the drag + * handle or scrim. + * @param onRequiresImmersiveChange Callback notified when the portrait layout solver requires or + * releases immersive navigation-bar hiding. + * @param overlay Optional overlay composable drawn above the viewfinder and controls. + * @param screenFlashOverlay Full-bleed screen flash composable drawn above all chrome and system + * bar areas. + */ +@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) +@Composable +internal fun CompactPortraitLayout( + slots: CaptureSlots, + viewfinder: @Composable (Modifier) -> Unit, + modifier: Modifier = Modifier, + state: CaptureScaffoldState = rememberCaptureScaffoldState(), + controlsVisible: Boolean = true, + isErrorDialogShowing: Boolean = false, + includeStatusBarsInTopBar: Boolean = true, + onDismissQuickSettings: () -> Unit = {}, + onRequiresImmersiveChange: (Boolean) -> Unit = {}, + overlay: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit = {}, + screenFlashOverlay: @Composable (Modifier) -> Unit = {} +) { + val captureButton = slots.captureButton + val imageWell = slots.imageWell + val flipCameraButton = slots.flipCameraButton + val zoomLevelDisplay = slots.zoomControls + val elapsedTimeDisplay = slots.elapsedTimeDisplay + val quickSettingsButton = slots.quickSettingsButton + val indicatorRow = slots.topBar + val captureModeToggle = slots.captureModeToggle + val captureModeCarousel = slots.captureModeCarousel + val snackBar = slots.snackBar + val topStartContent = slots.topStartContent + val viewfinderTopEndContent = slots.viewfinderTopEndContent + val topBarTrailingContent = slots.topBarTrailingContent + val errorDialog = slots.errorDialog + val bottomSheetState = rememberBottomSheetState( + initialValue = if (state.isQuickSettingsOpen) SheetValue.Expanded else SheetValue.Hidden, + confirmValueChange = { targetValue -> + if (targetValue == SheetValue.Hidden) { + state.dismissQuickSettings() + } else if (targetValue == SheetValue.Expanded) { + state.showQuickSettings() + } + true + } + ) + val scaffoldState = rememberBottomSheetScaffoldState( + bottomSheetState = bottomSheetState, + snackbarHostState = state.snackbarHostState + ) + LaunchedEffect(state.isQuickSettingsOpen) { + if (state.isQuickSettingsOpen) { + if (bottomSheetState.targetValue != SheetValue.Expanded) { + bottomSheetState.expand() + } + } else { + if (bottomSheetState.isVisible || bottomSheetState.targetValue != SheetValue.Hidden) { + bottomSheetState.hide() + } + } + } + + val overlapTargetBounds = remember { mutableStateOf(Rect.Zero) } + val localeDirection = LocalLayoutDirection.current + val dismissQuickSettingsLabel = + stringResource(R.string.quick_settings_btn_close_expanded_settings_description) + val handleDismissQuickSettings = { + state.dismissQuickSettings() + onDismissQuickSettings() + } + + CompositionLocalProvider( + LocalOverlapTargetBounds provides overlapTargetBounds, + LocalActiveCaptureLayout provides "CompactPortraitLayout" + ) { + Box( + modifier = modifier + .fillMaxSize() + .testTag(COMPACT_CONTROLS_TAG) + ) { + BottomSheetScaffold( + modifier = Modifier.fillMaxSize(), + scaffoldState = scaffoldState, + sheetPeekHeight = CompactPortraitTokens.SheetPeekHeight, + sheetDragHandle = { + BottomSheetDefaults.DragHandle( + modifier = Modifier + .testTag(QUICK_SETTINGS_DRAG_HANDLE) + .minimumInteractiveComponentSize() + .clickable( + role = Role.Button, + onClickLabel = dismissQuickSettingsLabel, + onClick = handleDismissQuickSettings + ) + ) + }, + sheetShape = RoundedCornerShape( + topStart = CompactPortraitTokens.SheetTopCornerRadius, + topEnd = CompactPortraitTokens.SheetTopCornerRadius + ), + sheetContainerColor = MaterialTheme.colorScheme.surfaceContainerLow, + sheetContent = { + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + OverlapAwareCaptureSlot( + orientation = Orientation.Vertical, + isCompact = false, + content = slots.quickSettingsOverlay + ) + } + }, + snackbarHost = {} + ) { + BoxWithConstraints( + modifier = Modifier + .fillMaxSize() + .background(Color.Black) + ) { + val isSheetVisible = state.isQuickSettingsOpen || + bottomSheetState.isVisible || + bottomSheetState.targetValue == SheetValue.Expanded + var isErrorDialogPlaced by remember { mutableStateOf(false) } + val isErrorModalActive = isErrorDialogShowing || isErrorDialogPlaced + val isModalOpen = isSheetVisible || isErrorModalActive + + val windowAspectRatio = maxHeight.value / maxWidth.value + val isHandheldPortrait = + windowAspectRatio >= CompactPortraitTokens.PORTRAIT_ASPECT_RATIO_THRESHOLD + if (isHandheldPortrait) { + AdaptivePortraitCaptureLayout( + windowWidth = maxWidth, + windowHeight = maxHeight, + includeStatusBarsInTopBar = includeStatusBarsInTopBar, + controlsVisible = controlsVisible, + modifier = Modifier.suppressBackgroundForModal(isModalOpen), + viewfinder = viewfinder, + topStartContent = topStartContent, + viewfinderTopEndContent = viewfinderTopEndContent, + onRequiresImmersiveChange = onRequiresImmersiveChange, + indicatorRow = indicatorRow, + topBarTrailingContent = topBarTrailingContent, + elapsedTimeDisplay = elapsedTimeDisplay, + zoomControls = zoomLevelDisplay, + imageWell = imageWell, + captureButton = captureButton, + flipCameraButton = flipCameraButton, + captureModeCarousel = captureModeCarousel, + quickSettingsToggleButton = quickSettingsButton, + captureModeToggleSwitch = captureModeToggle, + snackbarHost = { hostModifier -> + PillSnackbarHost( + snackbarHostState = state.snackbarHostState, + modifier = hostModifier + ) + } + ) + Box( + modifier = Modifier + .fillMaxSize() + .suppressBackgroundForModal(isModalOpen) + .windowInsetsPadding( + WindowInsets.systemBarsIgnoringVisibility + .union(WindowInsets.displayCutout) + ) + ) { + CompositionLocalProvider( + LocalLayoutDirection provides localeDirection + ) { + snackBar(Modifier, state.snackbarHostState) + } + } + } else { + Column(modifier = Modifier.suppressBackgroundForModal(isModalOpen)) { + val minTouchTarget = LocalMinimumInteractiveComponentSize.current + .takeOrElse { CompactPortraitTokens.DefaultMinTouchTarget } + val (topBarHeight, topBarTopPadding) = computeTopBarMetrics( + includeStatusBarsInTopBar = includeStatusBarsInTopBar, + minTouchTarget = minTouchTarget + ) + CompactTopBarBox( + topBarHeight = topBarHeight, + topBarTopPadding = topBarTopPadding, + indicatorRow = indicatorRow, + topBarTrailingContent = topBarTrailingContent + ) + Box { + viewfinder(Modifier) + OverlapAwareStyleProvider(Modifier.align(Alignment.TopStart)) { + topStartContent(Modifier) + } + OverlapAwareStyleProvider(Modifier.align(Alignment.TopEnd)) { + viewfinderTopEndContent(Modifier) + } + } + } + + Box( + modifier = Modifier + .fillMaxSize() + .suppressBackgroundForModal(isModalOpen) + .windowInsetsPadding( + WindowInsets.systemBarsIgnoringVisibility + .union(WindowInsets.displayCutout) + ) + ) { + if (controlsVisible) { + VerticalMaterialControls( + captureButton = captureButton, + imageWell = imageWell, + flipCameraButton = flipCameraButton, + quickSettingsToggleButton = quickSettingsButton, + captureModeToggleSwitch = captureModeToggle, + captureModeCarousel = captureModeCarousel, + zoomControls = zoomLevelDisplay, + elapsedTimeDisplay = elapsedTimeDisplay, + snackbarHost = { hostModifier -> + PillSnackbarHost( + snackbarHostState = state.snackbarHostState, + modifier = hostModifier + ) + } + ) + } + CompositionLocalProvider( + LocalLayoutDirection provides localeDirection + ) { + snackBar(Modifier, state.snackbarHostState) + } + } + } + + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + OverlapAwareStyleProvider( + modifier = Modifier.suppressBackgroundForModal(isModalOpen) + ) { + overlay(Modifier) + } + } + + if (isSheetVisible && !isErrorModalActive) { + Box( + modifier = Modifier + .fillMaxSize() + .testTag(QUICK_SETTINGS_SCRIM) + .semantics { + contentDescription = dismissQuickSettingsLabel + traversalIndex = 1f + } + .clickable( + role = Role.Button, + interactionSource = remember { MutableInteractionSource() }, + indication = null, + onClick = handleDismissQuickSettings + ) + ) + } + + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + Box( + modifier = Modifier.onSizeChanged { size -> + isErrorDialogPlaced = size.width > 0 && size.height > 0 + } + ) { + errorDialog(Modifier) + } + } + } + } + // Drawn last and outside of both the inset-padded controls and the bottom sheet so the + // flash covers the entire window, including system bar and display cutout areas. + screenFlashOverlay(Modifier) + } + } +} + +@Composable +private fun computeTopBarMetrics( + includeStatusBarsInTopBar: Boolean, + minTouchTarget: Dp +): Pair { + val cutoutTopInset = WindowInsets.displayCutout.asPaddingValues().calculateTopPadding() + return if (includeStatusBarsInTopBar) { + val statusBarTopInset = WindowInsets.statusBars.asPaddingValues().calculateTopPadding() + val combinedTopInset = WindowInsets.statusBars + .union(WindowInsets.displayCutout) + .asPaddingValues() + .calculateTopPadding() + max(combinedTopInset, statusBarTopInset + minTouchTarget) to statusBarTopInset + } else { + max(cutoutTopInset, minTouchTarget) to CompactPortraitTokens.ZeroInset + } +} + +@Composable +private fun CompactTopBarBox( + topBarHeight: Dp, + topBarTopPadding: Dp, + indicatorRow: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, + topBarTrailingContent: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, + modifier: Modifier = Modifier +) { + val localeDirection = LocalLayoutDirection.current + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + Box( + modifier = modifier + .fillMaxWidth() + .height(topBarHeight) + .padding(top = topBarTopPadding) + .windowInsetsPadding( + WindowInsets.displayCutout.only(WindowInsetsSides.Horizontal) + ) + .padding(horizontal = CompactPortraitTokens.LowerSectionHorizontalPadding), + contentAlignment = Alignment.CenterStart + ) { + OverlapAwareStyleProvider(orientation = Orientation.Horizontal) { + indicatorRow(Modifier) + } + OverlapAwareStyleProvider( + modifier = Modifier.align(Alignment.CenterEnd), + orientation = Orientation.Horizontal + ) { + topBarTrailingContent(Modifier) + } + } + } +} + +@Composable +private fun CompactCaptureRow( + bottomBarDirection: LayoutDirection, + localeDirection: LayoutDirection, + isCompact: Boolean, + imageWell: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, + captureButton: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, + flipCameraButton: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, + modifier: Modifier = Modifier +) { + CompositionLocalProvider(LocalLayoutDirection provides bottomBarDirection) { + Row( + modifier = modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically + ) { + Row( + modifier = Modifier.weight(1f), + horizontalArrangement = Arrangement.SpaceEvenly + ) { + Box( + modifier = Modifier + .weight(1f) + .fillMaxHeight(), + contentAlignment = Alignment.Center + ) { + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + OverlapAwareStyleProvider( + orientation = Orientation.Horizontal, + isCompact = isCompact + ) { + imageWell(Modifier) + } + } + } + } + + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + OverlapAwareStyleProvider( + orientation = Orientation.Horizontal, + isCompact = isCompact + ) { + captureButton(Modifier) + } + } + + Box( + modifier = Modifier + .weight(1f) + .fillMaxHeight(), + contentAlignment = Alignment.Center + ) { + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + OverlapAwareStyleProvider( + orientation = Orientation.Horizontal, + isCompact = isCompact + ) { + flipCameraButton(Modifier) + } + } + } + } + } +} + +@Composable +private fun CompactBottomToolbar( + bottomBarDirection: LayoutDirection, + localeDirection: LayoutDirection, + isCompact: Boolean, + quickSettingsToggleButton: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, + captureModeToggleSwitch: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, + modifier: Modifier = Modifier +) { + CompositionLocalProvider(LocalLayoutDirection provides bottomBarDirection) { + Row( + modifier = modifier + .fillMaxWidth() + .padding(horizontal = CompactPortraitTokens.LowerSectionHorizontalPadding), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.Center + ) { + Box( + modifier = Modifier.weight(1f), + contentAlignment = Alignment.CenterStart + ) { + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + OverlapAwareStyleProvider( + orientation = Orientation.Horizontal, + isCompact = isCompact + ) { + quickSettingsToggleButton(Modifier) + } + } + } + + Box( + modifier = Modifier.weight(1f), + contentAlignment = Alignment.Center + ) { + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + OverlapAwareStyleProvider( + orientation = Orientation.Horizontal, + isCompact = isCompact + ) { + captureModeToggleSwitch(Modifier) + } + } + } + + Box( + modifier = Modifier.weight(1f), + contentAlignment = Alignment.CenterEnd + ) {} + } + } +} + +/** + * Constraint-solved portrait handheld layout placing the viewfinder and bottom control bands via + * [CameraLayoutSolver]. + */ +@OptIn(ExperimentalLayoutApi::class) +@Composable +internal fun AdaptivePortraitCaptureLayout( + windowWidth: Dp, + windowHeight: Dp, + viewfinder: @Composable (Modifier) -> Unit, + topStartContent: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, + viewfinderTopEndContent: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, + onRequiresImmersiveChange: (Boolean) -> Unit, + indicatorRow: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, + topBarTrailingContent: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, + elapsedTimeDisplay: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, + zoomControls: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, + imageWell: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, + captureButton: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, + flipCameraButton: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, + captureModeCarousel: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, + quickSettingsToggleButton: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, + captureModeToggleSwitch: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, + controlsVisible: Boolean, + modifier: Modifier = Modifier, + includeStatusBarsInTopBar: Boolean = true, + snackbarHost: @Composable (Modifier) -> Unit = {} +) { + val localeDirection = LocalLayoutDirection.current + val rtlPolicy = LocalCaptureRtlPolicy.current + val bottomBarDirection = if (rtlPolicy.mirrorCompactBottomBar) { + localeDirection + } else { + LayoutDirection.Ltr + } + + val navInset = WindowInsets.navigationBarsIgnoringVisibility + .asPaddingValues() + .calculateBottomPadding() + val rawGestureInset = WindowInsets.systemGestures + .asPaddingValues() + .calculateBottomPadding() + val effectiveGestureInset = max(CompactPortraitTokens.MinGestureInset, rawGestureInset) + val minTouchTarget = LocalMinimumInteractiveComponentSize.current + .takeOrElse { CompactPortraitTokens.DefaultMinTouchTarget } + val (topBarHeight, topBarTopPadding) = computeTopBarMetrics( + includeStatusBarsInTopBar = includeStatusBarsInTopBar, + minTouchTarget = minTouchTarget + ) + + val window = remember( + windowWidth, + windowHeight, + topBarHeight, + navInset, + effectiveGestureInset + ) { + CameraWindow( + width = windowWidth, + height = windowHeight, + topInset = topBarHeight, + navInset = navInset, + gestureInset = effectiveGestureInset + ) + } + + // The solve depends only on the window geometry, the insets, and the accessibility touch + // target. Row heights are deliberately *not* measured and fed back in: ControlRow.height is + // contractually the row's *reserved* height, so that showing or hiding a row's content never + // moves the rows around it. + val spec = remember(minTouchTarget) { + CameraLayoutDefaults.spec(minInteractiveTouchTarget = minTouchTarget) + } + val solution = remember(spec, window) { CameraLayoutSolver.solve(spec, window) } + + val currentOnRequiresImmersiveChange by rememberUpdatedState(onRequiresImmersiveChange) + DisposableEffect(solution.requiresImmersive) { + currentOnRequiresImmersiveChange(solution.requiresImmersive) + onDispose { currentOnRequiresImmersiveChange(false) } + } + + CompositionLocalProvider(LocalCameraLayoutSolution provides solution) { + Layout( + modifier = modifier.fillMaxSize(), + content = { + Box(modifier = Modifier.layoutId(CaptureSlotId.Viewfinder)) { + viewfinder(Modifier) + } + + Box(modifier = Modifier.layoutId(CaptureSlotId.TopStartContent)) { + OverlapAwareStyleProvider(orientation = Orientation.Horizontal) { + topStartContent(Modifier) + } + } + + Box(modifier = Modifier.layoutId(CaptureSlotId.ViewfinderTopEndContent)) { + OverlapAwareStyleProvider(orientation = Orientation.Horizontal) { + viewfinderTopEndContent(Modifier) + } + } + + CompactTopBarBox( + topBarHeight = topBarHeight, + topBarTopPadding = topBarTopPadding, + modifier = Modifier.layoutId(CaptureSlotId.TopBar), + indicatorRow = indicatorRow, + topBarTrailingContent = topBarTrailingContent + ) + + if (controlsVisible) { + Column( + modifier = Modifier.layoutId(CaptureSlotId.ElapsedTime), + horizontalAlignment = Alignment.CenterHorizontally + ) { + snackbarHost(Modifier) + OverlapAwareStyleProvider(orientation = Orientation.Horizontal) { + elapsedTimeDisplay(Modifier) + } + } + + Box( + modifier = Modifier.layoutId(CaptureSlotId.ZoomBar), + contentAlignment = Alignment.Center + ) { + OverlapAwareStyleProvider(orientation = Orientation.Horizontal) { + zoomControls(Modifier) + } + } + + CompactCaptureRow( + bottomBarDirection = bottomBarDirection, + localeDirection = localeDirection, + isCompact = false, + imageWell = imageWell, + captureButton = captureButton, + flipCameraButton = flipCameraButton, + modifier = Modifier.layoutId(CaptureSlotId.CaptureRow) + ) + + Box( + modifier = Modifier + .layoutId(CaptureSlotId.ModeSwitcher) + .fillMaxWidth(), + contentAlignment = Alignment.Center + ) { + OverlapAwareStyleProvider(orientation = Orientation.Horizontal) { + captureModeCarousel(Modifier) + } + } + + CompactBottomToolbar( + bottomBarDirection = bottomBarDirection, + localeDirection = localeDirection, + isCompact = false, + quickSettingsToggleButton = quickSettingsToggleButton, + captureModeToggleSwitch = captureModeToggleSwitch, + modifier = Modifier.layoutId(CaptureSlotId.BottomToolbar) + ) + } + } + ) { measurables, constraints -> + val looseConstraints = constraints.copy(minWidth = 0, minHeight = 0) + val fullWidthLooseHeight = constraints.copy(minHeight = 0) + + fun bandOf(rowId: String) = solution.rowBands.getValue(rowId) + + fun measureInBand(slot: CaptureSlotId, rowId: String): Pair? { + val measurable = measurables.firstOrNull { it.layoutId == slot } ?: return null + val band = bandOf(rowId) + val placeable = measurable.measure( + Constraints.fixed(constraints.maxWidth, band.height.roundToPx()) + ) + return placeable to band.top.roundToPx() + } + + val topBarPlaceable = measurables + .firstOrNull { it.layoutId == CaptureSlotId.TopBar } + ?.measure(fullWidthLooseHeight) + val topStartPlaceable = measurables + .firstOrNull { it.layoutId == CaptureSlotId.TopStartContent } + ?.measure(looseConstraints) + val elapsedTimePlaceable = measurables + .firstOrNull { it.layoutId == CaptureSlotId.ElapsedTime } + ?.measure(looseConstraints) + + val zoomBar = measureInBand(CaptureSlotId.ZoomBar, CameraRowIds.ZOOM_BAR) + val captureRow = measureInBand(CaptureSlotId.CaptureRow, CameraRowIds.CAPTURE_ROW) + val modeSwitcher = measurables + .firstOrNull { it.layoutId == CaptureSlotId.ModeSwitcher } + ?.let { measurable -> + val band = bandOf(CameraRowIds.MODE_SWITCHER) + val clearance = min( + band.top - bandOf(CameraRowIds.CAPTURE_ROW).bottom, + bandOf(CameraRowIds.BOTTOM_TOOLBAR).top - band.bottom + ).coerceAtLeast(CompactPortraitTokens.ZeroInset) + val bandHeightPx = band.height.roundToPx() + val placeable = measurable.measure( + Constraints( + minWidth = constraints.maxWidth, + maxWidth = constraints.maxWidth, + minHeight = bandHeightPx, + maxHeight = (band.height + clearance * 2).roundToPx() + ) + ) + placeable to band.top.roundToPx() - (placeable.height - bandHeightPx) / 2 + } + val bottomToolbar = + measureInBand(CaptureSlotId.BottomToolbar, CameraRowIds.BOTTOM_TOOLBAR) + + val viewfinderPlaceable = measurables + .firstOrNull { it.layoutId == CaptureSlotId.Viewfinder } + ?.measure(looseConstraints) + + val viewfinderY = viewfinderPlaceable?.let { vf -> + if (vf.height in 1 until constraints.maxHeight) { + val ratio = vf.width.toFloat() / vf.height.toFloat() + solution.viewfinderBandFor(ratio, spec.viewfinders)?.top?.roundToPx() + } else { + null + } + } ?: 0 + + val activeVfTopPx = viewfinderPlaceable?.let { vf -> + val reportedTop = vf[ViewfinderTopLine] + viewfinderY + if (reportedTop == AlignmentLine.Unspecified) 0 else reportedTop + } + + val topBarHeightPx = topBarHeight.roundToPx() + val viewfinderTopEndY = if ( + activeVfTopPx == null || + activeVfTopPx <= (topBarHeight + spec.topStartHeight).roundToPx() + ) { + topBarHeightPx + } else { + activeVfTopPx + } + val viewfinderEnd = viewfinderPlaceable?.let { vf -> + (constraints.maxWidth + vf.width) / 2 + } ?: constraints.maxWidth + + val sharesTopStartRows = topStartPlaceable != null && + viewfinderTopEndY < topBarHeightPx + topStartPlaceable.height + val viewfinderTopEndMaxWidth = if (sharesTopStartRows) { + viewfinderEnd - topStartPlaceable.width + } else { + viewfinderEnd + }.coerceAtLeast(0) + val viewfinderTopEndPlaceable = measurables + .firstOrNull { it.layoutId == CaptureSlotId.ViewfinderTopEndContent } + ?.measure(looseConstraints.copy(maxWidth = viewfinderTopEndMaxWidth)) + + layout(constraints.maxWidth, constraints.maxHeight) { + viewfinderPlaceable?.let { vf -> + val vfX = (constraints.maxWidth - vf.width) / 2 + vf.placeRelative(vfX, viewfinderY) + } + + topStartPlaceable?.placeRelative(0, topBarHeightPx) + viewfinderTopEndPlaceable?.let { topEnd -> + topEnd.placeRelative(viewfinderEnd - topEnd.width, viewfinderTopEndY) + } + + topBarPlaceable?.placeRelative(0, 0) + + zoomBar?.let { (_, zoomTop) -> + elapsedTimePlaceable?.let { elapsed -> + val elapsedX = (constraints.maxWidth - elapsed.width) / 2 + elapsed.placeRelative(elapsedX, zoomTop - elapsed.height) + } + } + + zoomBar?.let { (placeable, top) -> placeable.placeRelative(0, top) } + captureRow?.let { (placeable, top) -> placeable.placeRelative(0, top) } + modeSwitcher?.let { (placeable, top) -> placeable.placeRelative(0, top) } + bottomToolbar?.let { (placeable, top) -> placeable.placeRelative(0, top) } + } + } + } +} + +/** + * Compressed-capable vertical bottom control stack used for non-handheld compact panes (such as + * squarer split-screen windows narrower than `600.dp`). + */ +@OptIn(ExperimentalLayoutApi::class) +@Composable +internal fun VerticalMaterialControls( + modifier: Modifier = Modifier, + captureButton: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, + zoomControls: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, + imageWell: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, + flipCameraButton: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, + quickSettingsToggleButton: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, + captureModeToggleSwitch: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, + captureModeCarousel: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit = {}, + elapsedTimeDisplay: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, + snackbarHost: @Composable (Modifier) -> Unit = {} +) { + val localeDirection = LocalLayoutDirection.current + val rtlPolicy = LocalCaptureRtlPolicy.current + val bottomBarDirection = if (rtlPolicy.mirrorCompactBottomBar) { + localeDirection + } else { + LayoutDirection.Ltr + } + + BoxWithConstraints( + modifier = modifier.fillMaxSize(), + contentAlignment = Alignment.BottomCenter + ) { + val navBarBottom = WindowInsets.navigationBarsIgnoringVisibility + .asPaddingValues() + .calculateBottomPadding() + val isShortScreen = maxHeight < CompactPortraitTokens.ShortScreenThreshold + val maxBottomPad = max( + CompactPortraitTokens.TargetBottomClearance - navBarBottom, + CompactPortraitTokens.MinNavMargin + ) + val bottomPad = if (isShortScreen) { + min(CompactPortraitTokens.MinControlsBottomPadding, maxBottomPad) + } else { + maxBottomPad + } + val stackGap = if (isShortScreen) { + CompactPortraitTokens.ControlStackMinGap + } else { + CompactPortraitTokens.ControlStackMaxGap + } + val zoomGap = if (isShortScreen) { + CompactPortraitTokens.MinZoomToShutterGap + } else { + CompactPortraitTokens.ZoomToShutterGap + } + + Column(modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Bottom) { + Column(modifier = modifier, horizontalAlignment = Alignment.CenterHorizontally) { + snackbarHost(Modifier) + + OverlapAwareStyleProvider( + orientation = Orientation.Horizontal, + isCompact = isShortScreen + ) { + elapsedTimeDisplay(Modifier) + } + + OverlapAwareStyleProvider( + orientation = Orientation.Horizontal, + isCompact = isShortScreen + ) { + zoomControls(Modifier) + } + + Spacer(modifier = Modifier.height(zoomGap)) + + Column { + CompactCaptureRow( + bottomBarDirection = bottomBarDirection, + localeDirection = localeDirection, + isCompact = isShortScreen, + imageWell = imageWell, + captureButton = captureButton, + flipCameraButton = flipCameraButton, + modifier = Modifier.height(CompactPortraitTokens.ShutterStackHeight) + ) + } + + Box( + modifier = Modifier + .fillMaxWidth() + .height(CompactPortraitTokens.MiddleSlotHeight + stackGap * 2), + contentAlignment = Alignment.Center + ) { + OverlapAwareStyleProvider( + orientation = Orientation.Horizontal, + isCompact = isShortScreen + ) { + captureModeCarousel(Modifier) + } + } + + CompactBottomToolbar( + bottomBarDirection = bottomBarDirection, + localeDirection = localeDirection, + isCompact = isShortScreen, + quickSettingsToggleButton = quickSettingsToggleButton, + captureModeToggleSwitch = captureModeToggleSwitch, + modifier = Modifier.height(CompactPortraitTokens.LowerSectionHeight) + ) + + Spacer(modifier = Modifier.height(bottomPad)) + } + } + } +} + +@Preview( + name = "CompactPortrait - Phone Portrait (412x915dp)", + device = "spec:width=412dp,height=915dp", + showBackground = true +) +@Composable +private fun CompactPortraitStandardPhonePreview() { + MaterialTheme(colorScheme = darkColorScheme()) { + CompactPortraitLayout( + slots = PlaceholderCaptureSlots.sideRail(includeElapsedTime = true), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) } + ) + } +} + +@Preview( + name = "CompactPortrait - Short Phone (360x640dp)", + device = "spec:width=360dp,height=640dp", + showBackground = true +) +@Composable +private fun CompactPortraitShortPhonePreview() { + MaterialTheme(colorScheme = darkColorScheme()) { + CompactPortraitLayout( + slots = PlaceholderCaptureSlots.sideRail(includeElapsedTime = true), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) } + ) + } +} + +@Preview( + name = "CompactPortrait - RTL Default Policy (Unmirrored Bar)", + device = "spec:width=412dp,height=915dp", + locale = "ar", + showBackground = true +) +@Composable +private fun CompactPortraitRtlDefaultPolicyPreview() { + MaterialTheme(colorScheme = darkColorScheme()) { + CompositionLocalProvider( + LocalCaptureRtlPolicy provides CaptureRtlPolicy(mirrorCompactBottomBar = false) + ) { + CompactPortraitLayout( + slots = PlaceholderCaptureSlots.sideRail(includeElapsedTime = true), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) } + ) + } + } +} + +@Preview( + name = "CompactPortrait - RTL Mirrored Policy", + device = "spec:width=412dp,height=915dp", + locale = "ar", + showBackground = true +) +@Composable +private fun CompactPortraitRtlMirroredPolicyPreview() { + MaterialTheme(colorScheme = darkColorScheme()) { + CompositionLocalProvider( + LocalCaptureRtlPolicy provides CaptureRtlPolicy(mirrorCompactBottomBar = true) + ) { + CompactPortraitLayout( + slots = PlaceholderCaptureSlots.sideRail(includeElapsedTime = true), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) } + ) + } + } +} diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CompactShortLayout.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CompactShortLayout.kt new file mode 100644 index 000000000..32801fbf6 --- /dev/null +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CompactShortLayout.kt @@ -0,0 +1,459 @@ +/* + * 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 androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.asPaddingValues +import androidx.compose.foundation.layout.displayCutout +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.sizeIn +import androidx.compose.foundation.layout.systemBars +import androidx.compose.foundation.layout.union +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.darkColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.layout.Layout +import androidx.compose.ui.platform.LocalLayoutDirection +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.Constraints +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.min + +private object CompactShortTokens { + val ZeroSize = 0.dp + val CondensedChromePadding = 8.dp + val CondensedMinSectionGap = 8.dp + val RailTotalVerticalPadding = 16.dp + val RailHorizontalPaddingTotal = 16.dp + val MinRailSlotWidthFloor = 36.dp + val MinCenterHudWidthFloor = 48.dp + val QuickSettingsCardMaxWidth = 320.dp + + // Proportional height fractions of the usable inner rail height so controls scale down + // harmoniously without clipping or overlap in condensed short windows (< 480dp on both axes, + // such as 360x360dp or 320x340dp with visible multi-window status bars). + const val RAIL_WIDTH_FRACTION = 0.22f + const val INDICATOR_MAX_HEIGHT_FRACTION = 0.20f + const val ZOOM_MAX_HEIGHT_FRACTION = 0.45f + const val QUICK_SETTINGS_BUTTON_FRACTION = 0.16f + const val SHUTTER_DIAMETER_FRACTION = 0.22f + const val SECONDARY_ACTION_FRACTION = 0.15f + const val MODE_TOGGLE_HEIGHT_FRACTION = 0.15f + const val CENTER_HUD_HEIGHT_FRACTION = 0.12f +} + +/** + * Condensed-height side-rail capture layout for short compact windows (`widthDp < 480.dp` and + * `heightDp < 480.dp`, covering both `COMPACT_SHORT` square multi-window panes / clamshell cover + * displays such as `360x360dp` and `COMPACT_SHORT_SLIM` panes such as `320x340dp`). + * + * Places [viewfinder] in a full-bleed centered background box, computes the remaining safe width + * and height after live `WindowInsets.systemBars.union(WindowInsets.displayCutout)` inside + * [BoxWithConstraints], wraps [slots] with proportional `Modifier.sizeIn` caps so controls never + * clip or overlap vertically, provides [LocalActiveCaptureLayout] = `"CompactShortLayout"`, and + * delegates to [SideRailCaptureScaffold] with `isCompactHeight = true`, condensed `8.dp` chrome + * padding, scoped [LocalCaptureRtlPolicy] (`mirrorSideRails`), and an in-hierarchy floating Quick + * Settings card (`maxCardWidth <= 320.dp`). + * + * @param slots [CaptureSlots] supplying the side-rail controls, HUD overlays, Quick Settings + * content, snackbar, and error dialog. + * @param viewfinder Composable rendering the camera preview frame. + * @param modifier [Modifier] applied to the outer layout container. + * @param state Mode-agnostic [CaptureScaffoldState] controlling Quick Settings visibility and the + * snackbar host. + * @param controlsVisible Whether the camera control slots should be composed and visible. + * @param isErrorDialogShowing Whether a modal camera error dialog is currently visible above the + * capture chrome. + * @param onDismissQuickSettings Callback invoked when Quick Settings is dismissed via scrim tap or + * system back/escape. + * @param overlay Optional overlay composable drawn above the viewfinder and controls. + * @param screenFlashOverlay Full-bleed screen flash composable drawn above all chrome and system + * bar areas. + */ +@Composable +internal fun CompactShortLayout( + slots: CaptureSlots, + viewfinder: @Composable (Modifier) -> Unit, + modifier: Modifier = Modifier, + state: CaptureScaffoldState = rememberCaptureScaffoldState(), + controlsVisible: Boolean = true, + isErrorDialogShowing: Boolean = false, + onDismissQuickSettings: () -> Unit = {}, + overlay: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit = {}, + screenFlashOverlay: @Composable (Modifier) -> Unit = {} +) { + val localeDirection = LocalLayoutDirection.current + val safePadding = WindowInsets.systemBars.union(WindowInsets.displayCutout).asPaddingValues() + + BoxWithConstraints(modifier = modifier.fillMaxSize()) { + val horizontalInsets = safePadding.calculateLeftPadding(localeDirection) + + safePadding.calculateRightPadding(localeDirection) + val verticalInsets = safePadding.calculateTopPadding() + + safePadding.calculateBottomPadding() + val availableWidth = + (maxWidth - horizontalInsets).coerceAtLeast(CompactShortTokens.ZeroSize) + val availableHeight = + (maxHeight - verticalInsets).coerceAtLeast(CompactShortTokens.ZeroSize) + + val railSlotMaxWidth = min( + CaptureSlotTokens.ModeToggleCompactWidth, + (availableWidth * CompactShortTokens.RAIL_WIDTH_FRACTION) + .coerceAtLeast(CompactShortTokens.MinRailSlotWidthFloor) + ) + val estimatedRailFootprint = + railSlotMaxWidth + CompactShortTokens.RailHorizontalPaddingTotal + val condensedSlots = remember(slots, availableWidth, availableHeight) { + slots.withCondensedSizeCaps( + availableWidth = availableWidth, + availableHeight = availableHeight, + railSlotMaxWidth = railSlotMaxWidth, + estimatedRailFootprint = estimatedRailFootprint + ) + } + val cardMaxWidth = min( + CompactShortTokens.QuickSettingsCardMaxWidth, + (availableWidth - CompactShortTokens.CondensedChromePadding * 2) + .coerceAtLeast(CompactShortTokens.ZeroSize) + ) + val cardMaxHeight = (availableHeight - CompactShortTokens.CondensedChromePadding * 2) + .coerceAtLeast(CompactShortTokens.ZeroSize) + + val config = remember(cardMaxWidth, cardMaxHeight) { + SideRailPostureConfig( + activeLayoutName = "CompactShortLayout", + isCompactHeight = true, + railTopPadding = CompactShortTokens.CondensedChromePadding, + railBottomPadding = CompactShortTokens.CondensedChromePadding, + railHorizontalPadding = CompactShortTokens.CondensedChromePadding, + railMinSectionGap = CompactShortTokens.CondensedMinSectionGap, + centerVerticalFraction = 0.50f, + hudVerticalPadding = CompactShortTokens.CondensedChromePadding, + quickSettingsCardMaxWidth = cardMaxWidth, + quickSettingsCardMaxHeight = cardMaxHeight, + clearRailsForQuickSettings = false + ) + } + + SideRailCaptureScaffold( + slots = condensedSlots, + viewfinder = viewfinder, + modifier = Modifier.fillMaxSize(), + state = state, + config = config, + controlsVisible = controlsVisible, + isErrorDialogShowing = isErrorDialogShowing, + onDismissQuickSettings = onDismissQuickSettings, + overlay = overlay, + screenFlashOverlay = screenFlashOverlay + ) + } +} + +private fun CaptureSlots.withCondensedSizeCaps( + availableWidth: Dp, + availableHeight: Dp, + railSlotMaxWidth: Dp, + estimatedRailFootprint: Dp +): CaptureSlots { + val innerRailHeight = (availableHeight - CompactShortTokens.RailTotalVerticalPadding) + .coerceAtLeast(CompactShortTokens.ZeroSize) + + val indicatorMaxHeight = min( + CaptureSlotTokens.IndicatorCompactMainAxisSize, + innerRailHeight * CompactShortTokens.INDICATOR_MAX_HEIGHT_FRACTION + ) + val zoomMaxHeight = min( + CaptureSlotTokens.ZoomCompactMainAxisSize, + innerRailHeight * CompactShortTokens.ZOOM_MAX_HEIGHT_FRACTION + ) + val quickSettingsButtonMaxSize = min( + min( + CaptureSlotTokens.IconTouchTargetSize, + innerRailHeight * CompactShortTokens.QUICK_SETTINGS_BUTTON_FRACTION + ), + railSlotMaxWidth + ) + val shutterMaxDiameter = min( + min( + CaptureSlotTokens.ShutterCompactDiameter, + innerRailHeight * CompactShortTokens.SHUTTER_DIAMETER_FRACTION + ), + railSlotMaxWidth + ) + val secondaryActionMaxSize = min( + min( + CaptureSlotTokens.SecondaryActionCompactSize, + innerRailHeight * CompactShortTokens.SECONDARY_ACTION_FRACTION + ), + railSlotMaxWidth + ) + val modeToggleMaxHeight = min( + CaptureSlotTokens.ModeToggleCompactHeight, + innerRailHeight * CompactShortTokens.MODE_TOGGLE_HEIGHT_FRACTION + ) + + val centerHudMaxWidth = (availableWidth - estimatedRailFootprint * 2) + .coerceAtLeast(CompactShortTokens.MinCenterHudWidthFloor) + val centerHudMaxHeight = min( + CaptureSlotTokens.HorizontalTopBarHeight, + innerRailHeight * CompactShortTokens.CENTER_HUD_HEIGHT_FRACTION + ) + + val original = this + + return original.copy( + topBar = { mod -> + ConstrainedSlot( + modifier = mod, + maxWidth = railSlotMaxWidth, + maxHeight = indicatorMaxHeight, + slot = original.topBar + ) + }, + zoomControls = { mod -> + ConstrainedSlot( + modifier = mod, + maxWidth = railSlotMaxWidth, + maxHeight = zoomMaxHeight, + slot = original.zoomControls + ) + }, + quickSettingsButton = { mod -> + ConstrainedSlot( + modifier = mod, + maxWidth = quickSettingsButtonMaxSize, + maxHeight = quickSettingsButtonMaxSize, + slot = original.quickSettingsButton + ) + }, + captureButton = { mod -> + ConstrainedSlot( + modifier = mod, + maxWidth = shutterMaxDiameter, + maxHeight = shutterMaxDiameter, + slot = original.captureButton + ) + }, + flipCameraButton = { mod -> + ConstrainedSlot( + modifier = mod, + maxWidth = secondaryActionMaxSize, + maxHeight = secondaryActionMaxSize, + slot = original.flipCameraButton + ) + }, + imageWell = { mod -> + ConstrainedSlot( + modifier = mod, + maxWidth = secondaryActionMaxSize, + maxHeight = secondaryActionMaxSize, + slot = original.imageWell + ) + }, + captureModeToggle = { mod -> + ConstrainedSlot( + modifier = mod, + maxWidth = railSlotMaxWidth, + maxHeight = modeToggleMaxHeight, + slot = original.captureModeToggle + ) + }, + captureModeCarousel = { mod -> + ConstrainedSlot( + modifier = mod, + maxWidth = centerHudMaxWidth, + maxHeight = centerHudMaxHeight, + slot = original.captureModeCarousel + ) + }, + elapsedTimeDisplay = { mod -> + ConstrainedSlot( + modifier = mod, + maxWidth = centerHudMaxWidth, + maxHeight = centerHudMaxHeight, + slot = original.elapsedTimeDisplay + ) + }, + topStartContent = { mod -> + ConstrainedSlot( + modifier = mod, + maxWidth = centerHudMaxWidth, + maxHeight = secondaryActionMaxSize, + slot = original.topStartContent + ) + }, + viewfinderTopEndContent = { mod -> + ConstrainedSlot( + modifier = mod, + maxWidth = centerHudMaxWidth, + maxHeight = secondaryActionMaxSize, + slot = original.viewfinderTopEndContent + ) + } + ) +} + +@Composable +private fun PreviewOverlaySlotScope.ConstrainedSlot( + modifier: Modifier, + maxWidth: Dp, + maxHeight: Dp, + slot: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit +) { + val cappedModifier = modifier.sizeIn(maxWidth = maxWidth, maxHeight = maxHeight) + Layout( + content = { slot(cappedModifier) } + ) { measurables, constraints -> + if (measurables.isEmpty()) { + layout(0, 0) {} + } else { + val cappedMaxWidthPx = minOf(constraints.maxWidth, maxWidth.roundToPx()) + .coerceAtLeast(0) + val cappedMaxHeightPx = minOf(constraints.maxHeight, maxHeight.roundToPx()) + .coerceAtLeast(0) + val childConstraints = Constraints( + minWidth = 0, + maxWidth = cappedMaxWidthPx, + minHeight = 0, + maxHeight = cappedMaxHeightPx + ) + val placeables = measurables.map { it.measure(childConstraints) } + val resolvedWidth = (placeables.maxOfOrNull { it.width } ?: 0) + .coerceIn(constraints.minWidth, constraints.maxWidth) + val resolvedHeight = (placeables.maxOfOrNull { it.height } ?: 0) + .coerceIn(constraints.minHeight, constraints.maxHeight) + layout(resolvedWidth, resolvedHeight) { + placeables.forEach { placeable -> + placeable.place( + x = (resolvedWidth - placeable.width) / 2, + y = (resolvedHeight - placeable.height) / 2 + ) + } + } + } + } +} + +@Preview( + name = "CompactShort - Multi-Window Square (360x360dp)", + device = "spec:width=360dp,height=360dp", + showBackground = true +) +@Composable +private fun CompactShortSquarePreview() { + MaterialTheme(colorScheme = darkColorScheme()) { + CompactShortLayout( + slots = PlaceholderCaptureSlots.sideRail( + isCompactHeight = true, + includeElapsedTime = true + ), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) } + ) + } +} + +@Preview( + name = "CompactShortSlim - Ultra-Compact (320x340dp)", + device = "spec:width=320dp,height=340dp", + showBackground = true +) +@Composable +private fun CompactShortSlimPreview() { + MaterialTheme(colorScheme = darkColorScheme()) { + CompactShortLayout( + slots = PlaceholderCaptureSlots.sideRail( + isCompactHeight = true, + includeElapsedTime = true + ), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) } + ) + } +} + +@Preview( + name = "CompactShort - Quick Settings Open (360x360dp)", + device = "spec:width=360dp,height=360dp", + showBackground = true +) +@Composable +private fun CompactShortQuickSettingsOpenPreview() { + MaterialTheme(colorScheme = darkColorScheme()) { + CompactShortLayout( + slots = PlaceholderCaptureSlots.sideRail( + isCompactHeight = true, + includeElapsedTime = true, + tagQuickSettingsOverlay = true + ), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + state = rememberCaptureScaffoldState(isInitiallyExpanded = true) + ) + } +} + +@Preview( + name = "CompactShort - RTL Default Policy (Unmirrored Rails)", + device = "spec:width=360dp,height=360dp", + locale = "ar", + showBackground = true +) +@Composable +private fun CompactShortRtlDefaultPolicyPreview() { + MaterialTheme(colorScheme = darkColorScheme()) { + CompositionLocalProvider( + LocalCaptureRtlPolicy provides CaptureRtlPolicy(mirrorSideRails = false) + ) { + CompactShortLayout( + slots = PlaceholderCaptureSlots.sideRail( + isCompactHeight = true, + includeElapsedTime = true, + tagQuickSettingsOverlay = true + ), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + state = rememberCaptureScaffoldState(isInitiallyExpanded = true) + ) + } + } +} + +@Preview( + name = "CompactShort - RTL Mirrored Policy", + device = "spec:width=360dp,height=360dp", + locale = "ar", + showBackground = true +) +@Composable +private fun CompactShortRtlMirroredPolicyPreview() { + MaterialTheme(colorScheme = darkColorScheme()) { + CompositionLocalProvider( + LocalCaptureRtlPolicy provides CaptureRtlPolicy(mirrorSideRails = true) + ) { + CompactShortLayout( + slots = PlaceholderCaptureSlots.sideRail( + isCompactHeight = true, + includeElapsedTime = true, + tagQuickSettingsOverlay = true + ), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + state = rememberCaptureScaffoldState(isInitiallyExpanded = true) + ) + } + } +} diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/SideRailCaptureLayouts.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/SideRailCaptureLayouts.kt new file mode 100644 index 000000000..8831e502b --- /dev/null +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/SideRailCaptureLayouts.kt @@ -0,0 +1,696 @@ +/* + * 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 androidx.activity.compose.BackHandler +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.gestures.Orientation +import androidx.compose.foundation.gestures.detectTapGestures +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.asPaddingValues +import androidx.compose.foundation.layout.calculateEndPadding +import androidx.compose.foundation.layout.calculateStartPadding +import androidx.compose.foundation.layout.displayCutout +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.systemBars +import androidx.compose.foundation.layout.union +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.layout.windowInsetsPadding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.darkColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.Immutable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +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.Rect +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalLayoutDirection +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.traversalIndex +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.max + +// TODO(#648): Replace with QUICK_SETTINGS_OVERLAY_CARD_TAG from QuickSettingsOverlayCard once #648 +// merges into main. +internal const val QUICK_SETTINGS_OVERLAY_CARD_PLACEHOLDER_TAG = "card_quick_settings_overlay" + +/** + * Posture-specific padding, vertical alignment, and Quick Settings card sizing configuration for + * [SideRailCaptureScaffold]. + */ +@Immutable +internal data class SideRailPostureConfig( + val activeLayoutName: String, + val isCompactHeight: Boolean, + val railTopPadding: Dp, + val railBottomPadding: Dp, + val railHorizontalPadding: Dp, + val railMinSectionGap: Dp, + val centerVerticalFraction: Float, + val hudVerticalPadding: Dp, + val quickSettingsCardMaxWidth: Dp, + val quickSettingsCardMaxHeight: Dp = Dp.Unspecified, + val clearRailsForQuickSettings: Boolean = true +) + +/** + * Shared dimension, clearance, and posture-preset constants for side-rail capture layouts. + */ +internal object SideRailTokens { + val QuickSettingsRailClearanceGap = 12.dp + val TopOverlayRailClearanceGap = 12.dp + val QuickSettingsScrimColor = Color.Black.copy(alpha = 0.32f) + val QuickSettingsCardCornerRadius = 28.dp + val QuickSettingsCardTonalElevation = 3.dp + + val FoldableConfig = SideRailPostureConfig( + activeLayoutName = "FoldableLayout", + isCompactHeight = false, + railTopPadding = 24.dp, + railBottomPadding = 24.dp, + railHorizontalPadding = 16.dp, + railMinSectionGap = 12.dp, + centerVerticalFraction = 0.50f, + hudVerticalPadding = 16.dp, + quickSettingsCardMaxWidth = 380.dp, + clearRailsForQuickSettings = true + ) + + val TabletLandscapeConfig = SideRailPostureConfig( + activeLayoutName = "TabletLandscapeLayout", + isCompactHeight = false, + railTopPadding = 24.dp, + railBottomPadding = 28.dp, + railHorizontalPadding = 20.dp, + railMinSectionGap = 16.dp, + centerVerticalFraction = 0.50f, + hudVerticalPadding = 20.dp, + quickSettingsCardMaxWidth = 412.dp, + clearRailsForQuickSettings = true + ) + + val TabletPortraitConfig = SideRailPostureConfig( + activeLayoutName = "TabletPortraitLayout", + isCompactHeight = false, + railTopPadding = 32.dp, + railBottomPadding = 48.dp, + railHorizontalPadding = 24.dp, + railMinSectionGap = 16.dp, + centerVerticalFraction = 0.70f, + hudVerticalPadding = 24.dp, + quickSettingsCardMaxWidth = 412.dp, + clearRailsForQuickSettings = true + ) +} + +/** + * Unfolded book-style foldable capture layout (`~673x841dp` to `~852x883dp`) anchoring balanced + * vertical control rails (`centerVerticalFraction = 0.50f`) to the start and end edges over a + * full-bleed camera viewfinder, with a rail-cleared floating Quick Settings card (`maxCardWidth = + * 380.dp`). + * + * Provides [LocalActiveCaptureLayout] = `"FoldableLayout"`. + */ +@Composable +internal fun FoldableLayout( + slots: CaptureSlots, + viewfinder: @Composable (Modifier) -> Unit, + modifier: Modifier = Modifier, + state: CaptureScaffoldState = rememberCaptureScaffoldState(), + controlsVisible: Boolean = true, + isErrorDialogShowing: Boolean = false, + onDismissQuickSettings: () -> Unit = {}, + overlay: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit = {}, + screenFlashOverlay: @Composable (Modifier) -> Unit = {} +) { + SideRailCaptureScaffold( + slots = slots, + viewfinder = viewfinder, + modifier = modifier, + state = state, + config = SideRailTokens.FoldableConfig, + controlsVisible = controlsVisible, + isErrorDialogShowing = isErrorDialogShowing, + onDismissQuickSettings = onDismissQuickSettings, + overlay = overlay, + screenFlashOverlay = screenFlashOverlay + ) +} + +/** + * Landscape tablet capture layout (`~1280x800dp`) anchoring generous vertical control rails + * (`centerVerticalFraction = 0.50f`, `20.dp` horizontal padding, `16.dp` section gap) to the start + * and end edges over a full-bleed viewfinder, with a rail-cleared floating Quick Settings card + * (`maxCardWidth = 412.dp`). + * + * Provides [LocalActiveCaptureLayout] = `"TabletLandscapeLayout"`. + */ +@Composable +internal fun TabletLandscapeLayout( + slots: CaptureSlots, + viewfinder: @Composable (Modifier) -> Unit, + modifier: Modifier = Modifier, + state: CaptureScaffoldState = rememberCaptureScaffoldState(), + controlsVisible: Boolean = true, + isErrorDialogShowing: Boolean = false, + onDismissQuickSettings: () -> Unit = {}, + overlay: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit = {}, + screenFlashOverlay: @Composable (Modifier) -> Unit = {} +) { + SideRailCaptureScaffold( + slots = slots, + viewfinder = viewfinder, + modifier = modifier, + state = state, + config = SideRailTokens.TabletLandscapeConfig, + controlsVisible = controlsVisible, + isErrorDialogShowing = isErrorDialogShowing, + onDismissQuickSettings = onDismissQuickSettings, + overlay = overlay, + screenFlashOverlay = screenFlashOverlay + ) +} + +/** + * Portrait tablet capture layout (`~800x1280dp`) shifting the zoom controls and shutter cluster + * into the lower ergonomic thumb zone (`centerVerticalFraction = 0.70f`, `bottomPadding = 48.dp`, + * `horizontalPadding = 24.dp`) over a full-bleed viewfinder, with a rail-cleared floating Quick + * Settings card (`maxCardWidth = 412.dp`). + * + * Provides [LocalActiveCaptureLayout] = `"TabletPortraitLayout"`. + */ +@Composable +internal fun TabletPortraitLayout( + slots: CaptureSlots, + viewfinder: @Composable (Modifier) -> Unit, + modifier: Modifier = Modifier, + state: CaptureScaffoldState = rememberCaptureScaffoldState(), + controlsVisible: Boolean = true, + isErrorDialogShowing: Boolean = false, + onDismissQuickSettings: () -> Unit = {}, + overlay: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit = {}, + screenFlashOverlay: @Composable (Modifier) -> Unit = {} +) { + SideRailCaptureScaffold( + slots = slots, + viewfinder = viewfinder, + modifier = modifier, + state = state, + config = SideRailTokens.TabletPortraitConfig, + controlsVisible = controlsVisible, + isErrorDialogShowing = isErrorDialogShowing, + onDismissQuickSettings = onDismissQuickSettings, + overlay = overlay, + screenFlashOverlay = screenFlashOverlay + ) +} + +/** + * Shared full-bleed viewfinder and dual-rail capture scaffold backing [FoldableLayout], + * [TabletLandscapeLayout], [TabletPortraitLayout], and [CompactShortLayout]. + * + * Dynamically measures [StartSideRail] and [EndSideRail] widths via [onSizeChanged] so the floating + * Quick Settings card clears both side rails (`start = startRailWidth + 12.dp`, + * `end = endRailWidth + 12.dp`) while keeping its scrim edge-to-edge across the window. + */ +@Composable +internal fun SideRailCaptureScaffold( + slots: CaptureSlots, + viewfinder: @Composable (Modifier) -> Unit, + modifier: Modifier, + state: CaptureScaffoldState, + config: SideRailPostureConfig, + controlsVisible: Boolean, + isErrorDialogShowing: Boolean, + onDismissQuickSettings: () -> Unit, + overlay: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, + screenFlashOverlay: @Composable (Modifier) -> Unit +) { + val overlapTargetBounds = remember { mutableStateOf(Rect.Zero) } + val density = LocalDensity.current + val localeDirection = LocalLayoutDirection.current + val rtlPolicy = LocalCaptureRtlPolicy.current + val railContainerDirection = if (rtlPolicy.mirrorSideRails) { + localeDirection + } else { + LayoutDirection.Ltr + } + + val seededRailWidthPx = remember(config.railHorizontalPadding, density) { + with(density) { (MinSideRailWidth + config.railHorizontalPadding * 2).roundToPx() } + } + var startRailWidthPx by remember(seededRailWidthPx) { mutableIntStateOf(seededRailWidthPx) } + var endRailWidthPx by remember(seededRailWidthPx) { mutableIntStateOf(seededRailWidthPx) } + val startRailWidthDp = with(density) { startRailWidthPx.toDp() } + val endRailWidthDp = with(density) { endRailWidthPx.toDp() } + + var isErrorDialogPlaced by remember { mutableStateOf(false) } + val isErrorModalActive = isErrorDialogShowing || isErrorDialogPlaced + val isQuickSettingsVisible = state.isQuickSettingsOpen && !isErrorModalActive + val isModalOpen = isQuickSettingsVisible || isErrorModalActive + + val handleDismissQuickSettings = { + state.dismissQuickSettings() + onDismissQuickSettings() + } + + val liveSafeInsets = WindowInsets.systemBars.union(WindowInsets.displayCutout) + val safePadding = liveSafeInsets.asPaddingValues() + + CompositionLocalProvider( + LocalOverlapTargetBounds provides overlapTargetBounds, + LocalActiveCaptureLayout provides config.activeLayoutName + ) { + Box( + modifier = modifier + .fillMaxSize() + .background(Color.Black) + ) { + // Full-bleed centered viewfinder flush from top to bottom of the window. + Box( + modifier = Modifier + .fillMaxSize() + .suppressBackgroundForModal(isModalOpen), + contentAlignment = Alignment.Center + ) { + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + viewfinder(Modifier.fillMaxSize()) + } + } + + // Overlaid foreground chrome padded by live visible systemBars and displayCutout. + Box( + modifier = Modifier + .fillMaxSize() + .windowInsetsPadding(liveSafeInsets) + ) { + if (controlsVisible) { + CompositionLocalProvider(LocalLayoutDirection provides railContainerDirection) { + Box(modifier = Modifier.fillMaxSize()) { + CompositionLocalProvider( + LocalLayoutDirection provides localeDirection + ) { + StartSideRail( + slots = slots, + modifier = Modifier + .align(Alignment.CenterStart) + .fillMaxHeight() + .onSizeChanged { startRailWidthPx = it.width } + .suppressBackgroundForModal(isModalOpen), + isCompactHeight = config.isCompactHeight, + topPadding = config.railTopPadding, + bottomPadding = config.railBottomPadding, + horizontalPadding = config.railHorizontalPadding, + minSectionGap = config.railMinSectionGap, + centerVerticalFraction = config.centerVerticalFraction + ) + + EndSideRail( + slots = slots, + modifier = Modifier + .align(Alignment.CenterEnd) + .fillMaxHeight() + .onSizeChanged { endRailWidthPx = it.width } + .suppressBackgroundForModal(isModalOpen), + isCompactHeight = config.isCompactHeight, + showElapsedTimeInRail = false, + topPadding = config.railTopPadding, + bottomPadding = config.railBottomPadding, + horizontalPadding = config.railHorizontalPadding, + minSectionGap = config.railMinSectionGap, + centerVerticalFraction = config.centerVerticalFraction + ) + } + } + } + } + + val topOverlayClearance = max(startRailWidthDp, endRailWidthDp) + + SideRailTokens.TopOverlayRailClearanceGap + + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + Box( + modifier = Modifier + .fillMaxSize() + .padding(horizontal = topOverlayClearance) + ) { + OverlapAwareCaptureSlot( + modifier = Modifier + .align(Alignment.TopStart) + .padding(top = config.hudVerticalPadding) + .suppressBackgroundForModal(isModalOpen), + orientation = Orientation.Horizontal, + isCompact = config.isCompactHeight, + content = slots.topStartContent + ) + + OverlapAwareCaptureSlot( + modifier = Modifier + .align(Alignment.TopEnd) + .padding(top = config.hudVerticalPadding) + .suppressBackgroundForModal(isModalOpen), + orientation = Orientation.Horizontal, + isCompact = config.isCompactHeight, + content = slots.viewfinderTopEndContent + ) + } + + if (controlsVisible) { + Column( + modifier = Modifier + .align(Alignment.TopCenter) + .padding(top = config.hudVerticalPadding) + .suppressBackgroundForModal(isModalOpen), + horizontalAlignment = Alignment.CenterHorizontally + ) { + PillSnackbarHost(snackbarHostState = state.snackbarHostState) + OverlapAwareCaptureSlot( + orientation = Orientation.Horizontal, + isCompact = config.isCompactHeight, + content = slots.elapsedTimeDisplay + ) + } + + OverlapAwareCaptureSlot( + modifier = Modifier + .align(Alignment.BottomCenter) + .padding(bottom = config.hudVerticalPadding) + .suppressBackgroundForModal(isModalOpen), + orientation = Orientation.Horizontal, + isCompact = config.isCompactHeight, + content = slots.captureModeCarousel + ) + } else { + Box( + modifier = Modifier + .align(Alignment.TopCenter) + .padding(top = config.hudVerticalPadding) + .suppressBackgroundForModal(isModalOpen) + ) { + PillSnackbarHost(snackbarHostState = state.snackbarHostState) + } + } + } + + Box( + modifier = Modifier + .fillMaxSize() + .suppressBackgroundForModal(isModalOpen) + ) { + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + slots.snackBar(Modifier, state.snackbarHostState) + } + } + } + + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + OverlapAwareCaptureSlot( + modifier = Modifier.suppressBackgroundForModal(isModalOpen), + orientation = Orientation.Horizontal, + isCompact = config.isCompactHeight, + content = overlay + ) + } + + val safeStart = safePadding.calculateStartPadding(railContainerDirection) + val safeEnd = safePadding.calculateEndPadding(railContainerDirection) + val safeTop = safePadding.calculateTopPadding() + val safeBottom = safePadding.calculateBottomPadding() + + val quickSettingsCardPadding = if (config.clearRailsForQuickSettings) { + PaddingValues( + start = safeStart + startRailWidthDp + + SideRailTokens.QuickSettingsRailClearanceGap, + end = safeEnd + endRailWidthDp + + SideRailTokens.QuickSettingsRailClearanceGap, + top = safeTop + config.railTopPadding, + bottom = safeBottom + config.railBottomPadding + ) + } else { + PaddingValues( + start = safeStart + config.hudVerticalPadding, + end = safeEnd + config.hudVerticalPadding, + top = safeTop + config.hudVerticalPadding, + bottom = safeBottom + config.hudVerticalPadding + ) + } + + QuickSettingsOverlayCardPlaceholder( + isOpen = isQuickSettingsVisible, + onDismiss = handleDismissQuickSettings, + cardPadding = quickSettingsCardPadding, + maxCardWidth = config.quickSettingsCardMaxWidth, + maxCardHeight = config.quickSettingsCardMaxHeight, + cardContainerDirection = railContainerDirection, + localeDirection = localeDirection + ) { cardContentModifier -> + OverlapAwareCaptureSlot( + modifier = cardContentModifier, + orientation = Orientation.Vertical, + isCompact = config.isCompactHeight, + content = slots.quickSettingsOverlay + ) + } + + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + Box( + modifier = Modifier.onSizeChanged { size -> + isErrorDialogPlaced = size.width > 0 && size.height > 0 + } + ) { + slots.errorDialog(Modifier) + } + } + + // Drawn last and outside all inset-padded containers so screen flash covers the + // entire window, including system bar and display cutout areas. + screenFlashOverlay(Modifier) + } + } +} + +// TODO(#648): Replace with QuickSettingsOverlayCard once #648 merges into main. +@Composable +private fun QuickSettingsOverlayCardPlaceholder( + isOpen: Boolean, + onDismiss: () -> Unit, + cardPadding: PaddingValues, + maxCardWidth: Dp, + maxCardHeight: Dp, + cardContainerDirection: LayoutDirection, + localeDirection: LayoutDirection, + content: @Composable (Modifier) -> Unit +) { + if (!isOpen) return + + val dismissLabel = + stringResource(R.string.quick_settings_btn_close_expanded_settings_description) + BackHandler(enabled = true, onBack = onDismiss) + + Box(modifier = Modifier.fillMaxSize()) { + Box( + modifier = Modifier + .fillMaxSize() + .background(SideRailTokens.QuickSettingsScrimColor) + .testTag(QUICK_SETTINGS_SCRIM) + .semantics { + contentDescription = dismissLabel + traversalIndex = 1f + } + .clickable( + role = Role.Button, + interactionSource = remember { MutableInteractionSource() }, + indication = null, + onClickLabel = dismissLabel, + onClick = onDismiss + ) + ) + + val heightModifier = if (maxCardHeight != Dp.Unspecified) { + Modifier.heightIn(max = maxCardHeight) + } else { + Modifier + } + + CompositionLocalProvider(LocalLayoutDirection provides cardContainerDirection) { + Box( + modifier = Modifier + .fillMaxSize() + .padding(cardPadding), + contentAlignment = Alignment.BottomStart + ) { + Surface( + modifier = Modifier + .testTag(QUICK_SETTINGS_OVERLAY_CARD_PLACEHOLDER_TAG) + .widthIn(max = maxCardWidth) + .then(heightModifier) + .pointerInput(Unit) { + detectTapGestures { /* Consume taps on card surface */ } + }, + shape = RoundedCornerShape(SideRailTokens.QuickSettingsCardCornerRadius), + color = MaterialTheme.colorScheme.surfaceContainerLow, + tonalElevation = SideRailTokens.QuickSettingsCardTonalElevation + ) { + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + Box(modifier = Modifier.verticalScroll(rememberScrollState())) { + content(Modifier) + } + } + } + } + } + } +} + +@Preview( + name = "Foldable - Unfolded (852x883dp)", + device = "spec:width=852dp,height=883dp", + showBackground = true +) +@Composable +private fun FoldableUnfoldedPreview() { + MaterialTheme(colorScheme = darkColorScheme()) { + FoldableLayout( + slots = PlaceholderCaptureSlots.sideRail(includeElapsedTime = true), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) } + ) + } +} + +@Preview( + name = "Foldable - Quick Settings Open (852x883dp)", + device = "spec:width=852dp,height=883dp", + showBackground = true +) +@Composable +private fun FoldableQuickSettingsOpenPreview() { + MaterialTheme(colorScheme = darkColorScheme()) { + FoldableLayout( + slots = PlaceholderCaptureSlots.sideRail( + includeElapsedTime = true, + tagQuickSettingsOverlay = true + ), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + state = rememberCaptureScaffoldState(isInitiallyExpanded = true) + ) + } +} + +@Preview( + name = "TabletLandscape - Recording (1280x800dp)", + device = "spec:width=1280dp,height=800dp", + showBackground = true +) +@Composable +private fun TabletLandscapePreview() { + MaterialTheme(colorScheme = darkColorScheme()) { + TabletLandscapeLayout( + slots = PlaceholderCaptureSlots.sideRail(includeElapsedTime = true), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) } + ) + } +} + +@Preview( + name = "TabletPortrait - Lower Thumb Zone (800x1280dp)", + device = "spec:width=800dp,height=1280dp", + showBackground = true +) +@Composable +private fun TabletPortraitPreview() { + MaterialTheme(colorScheme = darkColorScheme()) { + TabletPortraitLayout( + slots = PlaceholderCaptureSlots.sideRail(includeElapsedTime = true), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) } + ) + } +} + +@Preview( + name = "TabletLandscape - RTL Default Policy (Unmirrored Rails)", + device = "spec:width=1280dp,height=800dp", + locale = "ar", + showBackground = true +) +@Composable +private fun TabletLandscapeRtlDefaultPolicyPreview() { + MaterialTheme(colorScheme = darkColorScheme()) { + CompositionLocalProvider( + LocalCaptureRtlPolicy provides CaptureRtlPolicy(mirrorSideRails = false) + ) { + TabletLandscapeLayout( + slots = PlaceholderCaptureSlots.sideRail( + includeElapsedTime = true, + tagQuickSettingsOverlay = true + ), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + state = rememberCaptureScaffoldState(isInitiallyExpanded = true) + ) + } + } +} + +@Preview( + name = "TabletLandscape - RTL Mirrored Policy", + device = "spec:width=1280dp,height=800dp", + locale = "ar", + showBackground = true +) +@Composable +private fun TabletLandscapeRtlMirroredPolicyPreview() { + MaterialTheme(colorScheme = darkColorScheme()) { + CompositionLocalProvider( + LocalCaptureRtlPolicy provides CaptureRtlPolicy(mirrorSideRails = true) + ) { + TabletLandscapeLayout( + slots = PlaceholderCaptureSlots.sideRail( + includeElapsedTime = true, + tagQuickSettingsOverlay = true + ), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + state = rememberCaptureScaffoldState(isInitiallyExpanded = true) + ) + } + } +} diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/TestTags.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/TestTags.kt index 8a2c4a055..d6cad9c03 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/TestTags.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/TestTags.kt @@ -103,3 +103,6 @@ const val START_SIDE_RAIL_TAG = "rail_capture_start" /** Test tag for the end-aligned adaptive side rail on the capture screen. */ const val END_SIDE_RAIL_TAG = "rail_capture_end" + +/** Test tag for the compact controls container on the capture screen. */ +const val COMPACT_CONTROLS_TAG = "container_capture_controls_compact" diff --git a/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/CompactShortLayoutTest.kt b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/CompactShortLayoutTest.kt new file mode 100644 index 000000000..f203ab58f --- /dev/null +++ b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/CompactShortLayoutTest.kt @@ -0,0 +1,416 @@ +/* + * 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.view.View +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.platform.LocalLayoutDirection +import androidx.compose.ui.platform.LocalView +import androidx.compose.ui.test.assert +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.click +import androidx.compose.ui.test.getBoundsInRoot +import androidx.compose.ui.test.getUnclippedBoundsInRoot +import androidx.compose.ui.test.hasAnyAncestor +import androidx.compose.ui.test.isDialog +import androidx.compose.ui.test.isPopup +import androidx.compose.ui.test.junit4.v2.createComposeRule +import androidx.compose.ui.test.onAllNodesWithTag +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performTouchInput +import androidx.compose.ui.unit.DpRect +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.height +import androidx.compose.ui.unit.width +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.common.truth.Truth.assertWithMessage +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** + * Unit tests for [CompactShortLayout] across `COMPACT_SHORT` (`360x360dp`, `470x400dp`), + * `COMPACT_SHORT_SLIM` (`320x340dp`), RTL policies, and visible multi-window `statusBars` insets, + * asserting zero clipping, zero vertical overlap in both rails, and in-hierarchy + * [QuickSettingsOverlayCard] bounds. + */ +@RunWith(RobolectricTestRunner::class) +@Config(qualifiers = "w360dp-h360dp") +class CompactShortLayoutTest { + + @get:Rule + val composeTestRule = createComposeRule() + + private fun boundsOf(tag: String): DpRect = + composeTestRule.onNodeWithTag(tag).getUnclippedBoundsInRoot() + + @Test + fun compactShortLayout_at360x360_fitsAllControlsWithoutClippingOrVerticalOverlap() { + var observedActiveLayout: String? = null + + composeTestRule.setContent { + MaterialTheme { + CompactShortLayout( + slots = PlaceholderCaptureSlots.sideRail( + isCompactHeight = false, + includeImageWell = true, + includeElapsedTime = true + ), + viewfinder = { mod -> + observedActiveLayout = LocalActiveCaptureLayout.current + PlaceholderViewfinder(modifier = mod) + } + ) + } + } + composeTestRule.waitForIdle() + + assertThat(observedActiveLayout).isEqualTo("CompactShortLayout") + + val viewfinderBounds = boundsOf(PREVIEW_DISPLAY) + assertThat(viewfinderBounds.left.value).isWithin(TOLERANCE).of(0f) + assertThat(viewfinderBounds.top.value).isWithin(TOLERANCE).of(0f) + assertThat(viewfinderBounds.right.value).isWithin(TOLERANCE).of(360f) + assertThat(viewfinderBounds.bottom.value).isWithin(TOLERANCE).of(360f) + + assertNoClippingAndNoOverlapInWindow( + contextLabel = "COMPACT_SHORT 360x360", + windowWidth = 360f, + windowHeight = 360f, + minTop = 0f + ) + + val startRail = boundsOf(START_SIDE_RAIL_TAG) + val endRail = boundsOf(END_SIDE_RAIL_TAG) + val carousel = boundsOf(CAPTURE_MODE_CAROUSEL) + assertThat(startRail.right.value).isAtMost(carousel.left.value + TOLERANCE) + assertThat(carousel.right.value).isAtMost(endRail.left.value + TOLERANCE) + } + + @Config(qualifiers = "w320dp-h340dp") + @Test + fun compactShortLayout_at320x340_fitsCompactShortSlimWithoutClippingOrOverlap() { + composeTestRule.setContent { + MaterialTheme { + CompactShortLayout( + slots = PlaceholderCaptureSlots.sideRail( + isCompactHeight = false, + includeImageWell = true, + includeElapsedTime = true + ), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) } + ) + } + } + composeTestRule.waitForIdle() + + assertNoClippingAndNoOverlapInWindow( + contextLabel = "COMPACT_SHORT_SLIM 320x340", + windowWidth = 320f, + windowHeight = 340f, + minTop = 0f + ) + } + + @Config(qualifiers = "w470dp-h400dp") + @Test + fun compactShortLayout_rtlDefaultAndMirroredPolicies_preserveVerticalOrderAndChildDirection() { + var layoutDirection by mutableStateOf(LayoutDirection.Ltr) + var rtlPolicy by mutableStateOf(CaptureRtlPolicy(mirrorSideRails = false)) + val observedDirections = mutableMapOf() + + val baseSlots = PlaceholderCaptureSlots.sideRail( + isCompactHeight = true, + includeImageWell = true, + includeElapsedTime = true + ) + val instrumentedSlots = baseSlots.copy( + topBar = { mod -> + observedDirections["topBar"] = LocalLayoutDirection.current + baseSlots.topBar(this, mod) + }, + zoomControls = { mod -> + observedDirections["zoomControls"] = LocalLayoutDirection.current + baseSlots.zoomControls(this, mod) + }, + captureButton = { mod -> + observedDirections["captureButton"] = LocalLayoutDirection.current + baseSlots.captureButton(this, mod) + }, + captureModeToggle = { mod -> + observedDirections["captureModeToggle"] = LocalLayoutDirection.current + baseSlots.captureModeToggle(this, mod) + }, + captureModeCarousel = { mod -> + observedDirections["captureModeCarousel"] = LocalLayoutDirection.current + baseSlots.captureModeCarousel(this, mod) + } + ) + + composeTestRule.setContent { + MaterialTheme { + CompositionLocalProvider( + LocalLayoutDirection provides layoutDirection, + LocalCaptureRtlPolicy provides rtlPolicy + ) { + CompactShortLayout( + slots = instrumentedSlots, + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) } + ) + } + } + } + composeTestRule.waitForIdle() + + val ltrStartTops = START_RAIL_TAGS.map { boundsOf(it).top.value } + val ltrEndTops = END_RAIL_TAGS.map { boundsOf(it).top.value } + + observedDirections.clear() + layoutDirection = LayoutDirection.Rtl + rtlPolicy = CaptureRtlPolicy(mirrorSideRails = false) + composeTestRule.waitForIdle() + + assertThat(boundsOf(START_SIDE_RAIL_TAG).left.value).isWithin(TOLERANCE).of(0f) + assertThat(boundsOf(END_SIDE_RAIL_TAG).right.value).isWithin(TOLERANCE).of(470f) + observedDirections.forEach { (slotName, dir) -> + assertWithMessage("Slot $slotName must observe LayoutDirection.Rtl") + .that(dir) + .isEqualTo(LayoutDirection.Rtl) + } + START_RAIL_TAGS.forEachIndexed { i, tag -> + assertThat(boundsOf(tag).top.value).isWithin(TOLERANCE).of(ltrStartTops[i]) + } + END_RAIL_TAGS.forEachIndexed { i, tag -> + assertThat(boundsOf(tag).top.value).isWithin(TOLERANCE).of(ltrEndTops[i]) + } + + observedDirections.clear() + rtlPolicy = CaptureRtlPolicy(mirrorSideRails = true) + composeTestRule.waitForIdle() + + assertThat(boundsOf(START_SIDE_RAIL_TAG).right.value).isWithin(TOLERANCE).of(470f) + assertThat(boundsOf(END_SIDE_RAIL_TAG).left.value).isWithin(TOLERANCE).of(0f) + assertNoClippingAndNoOverlapInWindow( + contextLabel = "COMPACT_SHORT 470x400 RTL Mirrored", + windowWidth = 470f, + windowHeight = 400f, + minTop = 0f + ) + START_RAIL_TAGS.forEachIndexed { i, tag -> + assertThat(boundsOf(tag).top.value).isWithin(TOLERANCE).of(ltrStartTops[i]) + } + END_RAIL_TAGS.forEachIndexed { i, tag -> + assertThat(boundsOf(tag).top.value).isWithin(TOLERANCE).of(ltrEndTops[i]) + } + } + + @Test + fun compactShortLayout_withMultiWindowVisibleStatusBars_clearsBarAndFits360x360() { + lateinit var hostView: View + composeTestRule.setContent { + hostView = LocalView.current + MaterialTheme { + CompactShortLayout( + slots = PlaceholderCaptureSlots.sideRail( + isCompactHeight = false, + includeImageWell = true, + includeElapsedTime = true + ), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) } + ) + } + } + + dispatchStatusBarInsets( + view = hostView, + statusBarHeightPx = MULTI_WINDOW_STATUS_BAR_PX, + visible = true + ) + composeTestRule.waitForIdle() + + assertThat(boundsOf(PREVIEW_DISPLAY).top.value).isWithin(TOLERANCE).of(0f) + assertThat(boundsOf(PREVIEW_DISPLAY).bottom.value).isWithin(TOLERANCE).of(360f) + assertThat(boundsOf(START_SIDE_RAIL_TAG).top.value).isAtLeast(32f - TOLERANCE) + assertThat(boundsOf(END_SIDE_RAIL_TAG).top.value).isAtLeast(32f - TOLERANCE) + + assertNoClippingAndNoOverlapInWindow( + contextLabel = "COMPACT_SHORT 360x360 with 32dp visible statusBar", + windowWidth = 360f, + windowHeight = 360f, + minTop = 32f + ) + + dispatchStatusBarInsets( + view = hostView, + statusBarHeightPx = MULTI_WINDOW_STATUS_BAR_PX, + visible = false + ) + composeTestRule.waitForIdle() + assertThat(boundsOf(START_SIDE_RAIL_TAG).top.value).isWithin(TOLERANCE).of(0f) + assertThat(boundsOf(END_SIDE_RAIL_TAG).top.value).isWithin(TOLERANCE).of(0f) + } + + @Test + fun compactShortLayout_quickSettingsOverlayCard_displaysInHierarchyWithinCondensedBounds() { + val state = CaptureScaffoldState(isInitiallyExpanded = true) + composeTestRule.setContent { + MaterialTheme { + CompactShortLayout( + slots = PlaceholderCaptureSlots.sideRail(tagQuickSettingsOverlay = true), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + state = state + ) + } + } + composeTestRule.waitForIdle() + + composeTestRule.onNodeWithTag(QUICK_SETTINGS_OVERLAY_CARD_PLACEHOLDER_TAG) + .assertIsDisplayed() + .assert(!isPopup()) + .assert(!isDialog()) + .assert(!hasAnyAncestor(isPopup())) + .assert(!hasAnyAncestor(isDialog())) + assertThat( + composeTestRule.onAllNodesWithTag(QUICK_SETTINGS_BOTTOM_SHEET).fetchSemanticsNodes() + ).hasSize(1) + + val cardBounds = boundsOf(QUICK_SETTINGS_OVERLAY_CARD_PLACEHOLDER_TAG) + assertThat(cardBounds.left.value).isAtLeast(8f - TOLERANCE) + assertThat(cardBounds.right.value).isAtMost(352f + TOLERANCE) + assertThat(cardBounds.right.value - cardBounds.left.value).isAtMost(320f + TOLERANCE) + assertThat(cardBounds.top.value).isAtLeast(8f - TOLERANCE) + assertThat(cardBounds.bottom.value).isAtMost(352f + TOLERANCE) + + // Tapping inside the floating card must not dismiss Quick Settings; tapping the exposed + // top-end scrim region outside the card dismisses it. + composeTestRule.onNodeWithTag(QUICK_SETTINGS_OVERLAY_CARD_PLACEHOLDER_TAG).performClick() + composeTestRule.waitForIdle() + assertThat(state.isQuickSettingsOpen).isTrue() + + composeTestRule.onNodeWithTag(QUICK_SETTINGS_SCRIM).performTouchInput { + click(Offset(right - 10f, top + 10f)) + } + composeTestRule.waitForIdle() + assertThat(state.isQuickSettingsOpen).isFalse() + } + + private fun assertNoClippingAndNoOverlapInWindow( + contextLabel: String, + windowWidth: Float, + windowHeight: Float, + minTop: Float + ) { + val allTags = START_RAIL_TAGS + END_RAIL_TAGS + HUD_TAGS + allTags.forEach { tag -> + val clipped = composeTestRule.onNodeWithTag(tag).getBoundsInRoot() + val unclipped = composeTestRule.onNodeWithTag(tag).getUnclippedBoundsInRoot() + + assertWithMessage("$contextLabel: $tag must have positive width") + .that(unclipped.width) + .isGreaterThan(0.dp) + assertWithMessage("$contextLabel: $tag must have positive height") + .that(unclipped.height) + .isGreaterThan(0.dp) + assertWithMessage("$contextLabel: $tag left (${unclipped.left}) must be >= 0dp") + .that(unclipped.left.value) + .isAtLeast(0f - TOLERANCE) + assertWithMessage( + "$contextLabel: $tag right (${unclipped.right}) must be <= ${windowWidth}dp" + ) + .that(unclipped.right.value) + .isAtMost(windowWidth + TOLERANCE) + assertWithMessage("$contextLabel: $tag top (${unclipped.top}) must be >= ${minTop}dp") + .that(unclipped.top.value) + .isAtLeast(minTop - TOLERANCE) + assertWithMessage( + "$contextLabel: $tag bottom (${unclipped.bottom}) must be <= ${windowHeight}dp" + ) + .that(unclipped.bottom.value) + .isAtMost(windowHeight + TOLERANCE) + assertWithMessage("$contextLabel: $tag must not be clipped horizontally") + .that(clipped.width.value) + .isWithin(TOLERANCE) + .of(unclipped.width.value) + assertWithMessage("$contextLabel: $tag must not be clipped vertically") + .that(clipped.height.value) + .isWithin(TOLERANCE) + .of(unclipped.height.value) + } + + assertStrictVerticalOrder("$contextLabel StartSideRail", START_RAIL_TAGS) + assertStrictVerticalOrder("$contextLabel EndSideRail", END_RAIL_TAGS) + } + + private fun assertStrictVerticalOrder(railLabel: String, orderedTags: List) { + val rects = orderedTags.map { boundsOf(it) } + for (i in 0 until rects.lastIndex) { + assertWithMessage( + "$railLabel: ${orderedTags[i]} bottom (${rects[i].bottom}) must not overlap " + + "${orderedTags[i + 1]} top (${rects[i + 1].top})" + ) + .that(rects[i].bottom.value) + .isAtMost(rects[i + 1].top.value + TOLERANCE) + } + } + + private fun dispatchStatusBarInsets(view: View, statusBarHeightPx: Int, visible: Boolean) { + val barInsets = Insets.of(0, statusBarHeightPx, 0, 0) + val windowInsets = WindowInsetsCompat.Builder() + .setInsets( + WindowInsetsCompat.Type.statusBars(), + if (visible) barInsets else Insets.NONE + ) + .setInsetsIgnoringVisibility(WindowInsetsCompat.Type.statusBars(), barInsets) + .setVisible(WindowInsetsCompat.Type.statusBars(), visible) + .build() + + composeTestRule.runOnUiThread { + ViewCompat.dispatchApplyWindowInsets(view, windowInsets) + } + } + + private companion object { + val START_RAIL_TAGS = listOf( + VIDEO_QUALITY_TAG, + ZOOM_BUTTON_ROW_TAG, + QUICK_SETTINGS_DROP_DOWN + ) + val END_RAIL_TAGS = listOf( + FLIP_CAMERA_BUTTON, + CAPTURE_BUTTON, + IMAGE_WELL_TAG, + CAPTURE_MODE_TOGGLE_BUTTON + ) + val HUD_TAGS = listOf( + ELAPSED_TIME_TAG, + CAPTURE_MODE_CAROUSEL + ) + const val MULTI_WINDOW_STATUS_BAR_PX = 32 + const val TOLERANCE = 0.5f + } +} diff --git a/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/SideRailCaptureLayoutsTest.kt b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/SideRailCaptureLayoutsTest.kt new file mode 100644 index 000000000..ae81b36a8 --- /dev/null +++ b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/SideRailCaptureLayoutsTest.kt @@ -0,0 +1,750 @@ +/* + * 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.view.View +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.size +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalLayoutDirection +import androidx.compose.ui.platform.LocalView +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.semantics.SemanticsProperties +import androidx.compose.ui.test.SemanticsMatcher +import androidx.compose.ui.test.assert +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.getUnclippedBoundsInRoot +import androidx.compose.ui.test.hasAnyAncestor +import androidx.compose.ui.test.isDialog +import androidx.compose.ui.test.isPopup +import androidx.compose.ui.test.junit4.v2.createComposeRule +import androidx.compose.ui.test.onAllNodesWithTag +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performClick +import androidx.compose.ui.unit.DpRect +import androidx.compose.ui.unit.LayoutDirection +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.common.truth.Truth.assertWithMessage +import com.google.jetpackcamera.ui.components.capture.layout.CameraLayoutSolution +import com.google.jetpackcamera.ui.components.capture.layout.LocalCameraLayoutSolution +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** + * Unit tests for [FoldableLayout], [TabletPortraitLayout], [TabletLandscapeLayout], and + * [CompactPortraitLayout] verifying full-bleed viewfinder geometry, portrait tablet lower thumb + * zone (`0.70f`), rail-cleared [QuickSettingsOverlayCard] non-overlap, [CaptureRtlPolicy] modes, + * live multi-window `statusBars` clearance, and [LocalActiveCaptureLayout] reporting. + */ +@RunWith(RobolectricTestRunner::class) +@Config(qualifiers = "w852dp-h883dp") +class SideRailCaptureLayoutsTest { + + @get:Rule + val composeTestRule = createComposeRule() + + private fun boundsOf(tag: String): DpRect = + composeTestRule.onNodeWithTag(tag).getUnclippedBoundsInRoot() + + private val hiddenFromA11yAncestor = hasAnyAncestor( + SemanticsMatcher.keyIsDefined(SemanticsProperties.HideFromAccessibility) + ) + + @Test + fun foldableLayout_viewfinderIsFlushTopToBottom_providesActiveLayoutName_andOverlaysRails() { + var observedSolverSolution: CameraLayoutSolution? = null + var observedActiveLayout: String? = null + + composeTestRule.setContent { + MaterialTheme { + FoldableLayout( + slots = PlaceholderCaptureSlots.sideRail(includeElapsedTime = true), + viewfinder = { vfModifier -> + observedSolverSolution = LocalCameraLayoutSolution.current + observedActiveLayout = LocalActiveCaptureLayout.current + Box( + modifier = vfModifier.testTag(PREVIEW_DISPLAY), + contentAlignment = Alignment.Center + ) { + Box( + modifier = Modifier + .aspectRatio(1f) + .testTag(SQUARE_PREVIEW_FRAME_TAG) + ) + } + } + ) + } + } + composeTestRule.waitForIdle() + + assertThat(observedSolverSolution).isNull() + assertThat(observedActiveLayout).isEqualTo("FoldableLayout") + + val viewfinderBounds = boundsOf(PREVIEW_DISPLAY) + assertThat(viewfinderBounds.left.value).isWithin(TOLERANCE).of(0f) + assertThat(viewfinderBounds.top.value).isWithin(TOLERANCE).of(0f) + assertThat(viewfinderBounds.right.value).isWithin(TOLERANCE).of(852f) + assertThat(viewfinderBounds.bottom.value).isWithin(TOLERANCE).of(883f) + + val squareBounds = boundsOf(SQUARE_PREVIEW_FRAME_TAG) + val squareCenterY = (squareBounds.top.value + squareBounds.bottom.value) / 2f + assertThat(squareCenterY).isWithin(TOLERANCE).of(883f / 2f) + + composeTestRule.onNodeWithTag(START_SIDE_RAIL_TAG).assertIsDisplayed() + composeTestRule.onNodeWithTag(END_SIDE_RAIL_TAG).assertIsDisplayed() + val startRail = boundsOf(START_SIDE_RAIL_TAG) + val endRail = boundsOf(END_SIDE_RAIL_TAG) + assertThat(startRail.left.value).isWithin(TOLERANCE).of(0f) + assertThat(endRail.right.value).isWithin(TOLERANCE).of(852f) + assertThat(startRail.right.value).isLessThan(endRail.left.value) + + // Foldable centers zoom and shutter vertically around 50% (441.5dp). + val zoomBounds = boundsOf(ZOOM_BUTTON_ROW_TAG) + val zoomCenterY = (zoomBounds.top.value + zoomBounds.bottom.value) / 2f + assertThat(zoomCenterY).isWithin(2f).of(883f * 0.50f) + + val elapsedBounds = boundsOf(ELAPSED_TIME_TAG) + val carouselBounds = boundsOf(CAPTURE_MODE_CAROUSEL) + assertThat((elapsedBounds.left.value + elapsedBounds.right.value) / 2f) + .isWithin(TOLERANCE).of(852f / 2f) + assertThat((carouselBounds.left.value + carouselBounds.right.value) / 2f) + .isWithin(TOLERANCE).of(852f / 2f) + assertThat(elapsedBounds.right.value).isLessThan(endRail.left.value) + } + + @Config(qualifiers = "w800dp-h1280dp") + @Test + fun tabletPortraitLayout_shiftsZoomAndShutterIntoLowerThumbZoneWithoutCollision() { + var observedActiveLayout: String? = null + + composeTestRule.setContent { + MaterialTheme { + TabletPortraitLayout( + slots = PlaceholderCaptureSlots.sideRail( + includeImageWell = true, + includeElapsedTime = true + ), + viewfinder = { vfModifier -> + observedActiveLayout = LocalActiveCaptureLayout.current + PlaceholderViewfinder(modifier = vfModifier) + } + ) + } + } + composeTestRule.waitForIdle() + + assertThat(observedActiveLayout).isEqualTo("TabletPortraitLayout") + + val zoomBounds = boundsOf(ZOOM_BUTTON_ROW_TAG) + val qsButtonBounds = boundsOf(QUICK_SETTINGS_DROP_DOWN) + val flipBounds = boundsOf(FLIP_CAMERA_BUTTON) + val imageWellBounds = boundsOf(IMAGE_WELL_TAG) + val modeToggleBounds = boundsOf(CAPTURE_MODE_TOGGLE_BUTTON) + + val zoomCenterY = (zoomBounds.top.value + zoomBounds.bottom.value) / 2f + val shutterClusterCenterY = (flipBounds.top.value + imageWellBounds.bottom.value) / 2f + + // Both center clusters shift down to the 0.70f thumb zone (~896dp), well below 50% (640dp). + assertThat(zoomCenterY).isWithin(2f).of(1280f * 0.70f) + assertThat(shutterClusterCenterY).isGreaterThan(750f) + + // Zero vertical collision with bottom rail buttons (bottomPadding = 48.dp, gap >= 16.dp). + assertThat(zoomBounds.bottom.value).isAtMost(qsButtonBounds.top.value - 16f + TOLERANCE) + assertThat(imageWellBounds.bottom.value) + .isAtMost(modeToggleBounds.top.value - 16f + TOLERANCE) + assertThat(qsButtonBounds.bottom.value).isWithin(TOLERANCE).of(1280f - 48f) + assertThat(modeToggleBounds.bottom.value).isWithin(TOLERANCE).of(1280f - 48f) + } + + @Test + fun foldableLayout_quickSettingsOverlayCard_clearsBothSideRailsAndHasSingleSheetTag() { + val state = CaptureScaffoldState(isInitiallyExpanded = false) + + composeTestRule.setContent { + MaterialTheme { + FoldableLayout( + slots = PlaceholderCaptureSlots.sideRail(tagQuickSettingsOverlay = true), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + state = state + ) + } + } + composeTestRule.waitForIdle() + + composeTestRule + .onNodeWithTag(QUICK_SETTINGS_OVERLAY_CARD_PLACEHOLDER_TAG) + .assertDoesNotExist() + composeTestRule.onNodeWithTag(QUICK_SETTINGS_BOTTOM_SHEET).assertDoesNotExist() + + composeTestRule.runOnIdle { state.showQuickSettings() } + composeTestRule.waitForIdle() + + composeTestRule.onNodeWithTag(QUICK_SETTINGS_OVERLAY_CARD_PLACEHOLDER_TAG) + .assertIsDisplayed() + .assert(!isPopup()) + .assert(!isDialog()) + .assert(!hasAnyAncestor(isPopup())) + .assert(!hasAnyAncestor(isDialog())) + assertThat( + composeTestRule.onAllNodesWithTag(QUICK_SETTINGS_BOTTOM_SHEET).fetchSemanticsNodes() + ).hasSize(1) + + val startRail = boundsOf(START_SIDE_RAIL_TAG) + val endRail = boundsOf(END_SIDE_RAIL_TAG) + val cardBounds = boundsOf(QUICK_SETTINGS_OVERLAY_CARD_PLACEHOLDER_TAG) + + // Card clears both StartSideRail and EndSideRail by >= 12dp and respects 380dp max width. + assertThat(cardBounds.left.value).isAtLeast(startRail.right.value + 12f - TOLERANCE) + assertThat(cardBounds.right.value).isAtMost(endRail.left.value - 12f + TOLERANCE) + assertThat(cardBounds.right.value - cardBounds.left.value).isAtMost(380f + TOLERANCE) + assertThat(cardBounds.bottom.value).isWithin(TOLERANCE).of(883f - 24f) + + // Background camera chrome is pruned from accessibility while Quick Settings is open. + composeTestRule.onNodeWithTag(CAPTURE_BUTTON).assert(hiddenFromA11yAncestor) + + // Scrim tap dismisses CaptureScaffoldState.isQuickSettingsOpen. + composeTestRule.onNodeWithTag(QUICK_SETTINGS_SCRIM).performClick() + composeTestRule.waitForIdle() + assertThat(state.isQuickSettingsOpen).isFalse() + composeTestRule + .onNodeWithTag(QUICK_SETTINGS_OVERLAY_CARD_PLACEHOLDER_TAG) + .assertDoesNotExist() + } + + @Config(qualifiers = "w800dp-h1280dp") + @Test + fun tabletPortraitLayout_quickSettingsOverlayCard_clearsBothSideRailsAt800x1280() { + val state = CaptureScaffoldState(isInitiallyExpanded = true) + + composeTestRule.setContent { + MaterialTheme { + TabletPortraitLayout( + slots = PlaceholderCaptureSlots.sideRail(tagQuickSettingsOverlay = true), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + state = state + ) + } + } + composeTestRule.waitForIdle() + + val startRail = boundsOf(START_SIDE_RAIL_TAG) + val endRail = boundsOf(END_SIDE_RAIL_TAG) + val cardBounds = boundsOf(QUICK_SETTINGS_OVERLAY_CARD_PLACEHOLDER_TAG) + + assertThat(cardBounds.left.value).isAtLeast(startRail.right.value + 12f - TOLERANCE) + assertThat(cardBounds.right.value).isAtMost(endRail.left.value - 12f + TOLERANCE) + assertThat(cardBounds.right.value - cardBounds.left.value).isAtMost(412f + TOLERANCE) + assertThat(cardBounds.bottom.value).isWithin(TOLERANCE).of(1280f - 48f) + } + + @Config(qualifiers = "w1280dp-h800dp") + @Test + fun tabletLandscapeLayout_rtlPolicies_scopeRailAndCardPlacementAndRestoreLocaleDirection() { + var layoutDirection by mutableStateOf(LayoutDirection.Ltr) + var rtlPolicy by mutableStateOf(CaptureRtlPolicy(mirrorSideRails = false)) + val state = CaptureScaffoldState(isInitiallyExpanded = false) + var observedActiveLayout: String? = null + + val observedDirections = mutableMapOf() + val baseSlots = PlaceholderCaptureSlots.sideRail( + includeImageWell = true, + includeElapsedTime = true, + tagQuickSettingsOverlay = true + ) + val instrumentedSlots = baseSlots.copy( + topBar = { mod -> + observedDirections["topBar"] = LocalLayoutDirection.current + baseSlots.topBar(this, mod) + }, + zoomControls = { mod -> + observedDirections["zoomControls"] = LocalLayoutDirection.current + baseSlots.zoomControls(this, mod) + }, + quickSettingsButton = { mod -> + observedDirections["quickSettingsButton"] = LocalLayoutDirection.current + baseSlots.quickSettingsButton(this, mod) + }, + captureButton = { mod -> + observedDirections["captureButton"] = LocalLayoutDirection.current + baseSlots.captureButton(this, mod) + }, + flipCameraButton = { mod -> + observedDirections["flipCameraButton"] = LocalLayoutDirection.current + baseSlots.flipCameraButton(this, mod) + }, + imageWell = { mod -> + observedDirections["imageWell"] = LocalLayoutDirection.current + baseSlots.imageWell(this, mod) + }, + captureModeToggle = { mod -> + observedDirections["captureModeToggle"] = LocalLayoutDirection.current + baseSlots.captureModeToggle(this, mod) + }, + captureModeCarousel = { mod -> + observedDirections["captureModeCarousel"] = LocalLayoutDirection.current + baseSlots.captureModeCarousel(this, mod) + }, + elapsedTimeDisplay = { mod -> + observedDirections["elapsedTimeDisplay"] = LocalLayoutDirection.current + baseSlots.elapsedTimeDisplay(this, mod) + }, + quickSettingsOverlay = { mod -> + observedDirections["quickSettingsOverlay"] = LocalLayoutDirection.current + baseSlots.quickSettingsOverlay(this, mod) + }, + snackBar = { mod, host -> + observedDirections["snackBar"] = LocalLayoutDirection.current + baseSlots.snackBar(mod, host) + }, + errorDialog = { mod -> + observedDirections["errorDialog"] = LocalLayoutDirection.current + baseSlots.errorDialog(mod) + } + ) + + composeTestRule.setContent { + MaterialTheme { + CompositionLocalProvider( + LocalLayoutDirection provides layoutDirection, + LocalCaptureRtlPolicy provides rtlPolicy + ) { + TabletLandscapeLayout( + slots = instrumentedSlots, + viewfinder = { mod -> + observedActiveLayout = LocalActiveCaptureLayout.current + PlaceholderViewfinder(modifier = mod) + }, + state = state + ) + } + } + } + composeTestRule.waitForIdle() + + assertThat(observedActiveLayout).isEqualTo("TabletLandscapeLayout") + + val startOrderedTags = listOf( + VIDEO_QUALITY_TAG, + ZOOM_BUTTON_ROW_TAG, + QUICK_SETTINGS_DROP_DOWN + ) + val endOrderedTags = listOf( + FLIP_CAMERA_BUTTON, + CAPTURE_BUTTON, + IMAGE_WELL_TAG, + CAPTURE_MODE_TOGGLE_BUTTON + ) + + val ltrStartTops = startOrderedTags.map { boundsOf(it).top.value } + val ltrEndTops = endOrderedTags.map { boundsOf(it).top.value } + assertThat(boundsOf(START_SIDE_RAIL_TAG).left.value).isWithin(TOLERANCE).of(0f) + assertThat(boundsOf(END_SIDE_RAIL_TAG).right.value).isWithin(TOLERANCE).of(1280f) + + // 1. RTL with default CaptureRtlPolicy(false, false): rails stay on physical left/right + // while QuickSettingsOverlayCard clears StartSideRail on the left and restores RTL inside! + observedDirections.clear() + layoutDirection = LayoutDirection.Rtl + rtlPolicy = CaptureRtlPolicy(mirrorSideRails = false, mirrorCompactBottomBar = false) + state.showQuickSettings() + composeTestRule.waitForIdle() + + val unmirroredStartRail = boundsOf(START_SIDE_RAIL_TAG) + val unmirroredEndRail = boundsOf(END_SIDE_RAIL_TAG) + val unmirroredCard = boundsOf(QUICK_SETTINGS_OVERLAY_CARD_PLACEHOLDER_TAG) + assertThat(unmirroredStartRail.left.value).isWithin(TOLERANCE).of(0f) + assertThat(unmirroredEndRail.right.value).isWithin(TOLERANCE).of(1280f) + assertThat(unmirroredCard.left.value) + .isAtLeast(unmirroredStartRail.right.value + 12f - TOLERANCE) + assertThat(unmirroredCard.right.value).isLessThan(1280f / 2f) + + observedDirections.forEach { (slotName, dir) -> + assertWithMessage("Slot $slotName must receive LayoutDirection.Rtl") + .that(dir) + .isEqualTo(LayoutDirection.Rtl) + } + startOrderedTags.forEachIndexed { i, tag -> + assertThat(boundsOf(tag).top.value).isWithin(TOLERANCE).of(ltrStartTops[i]) + } + endOrderedTags.forEachIndexed { i, tag -> + assertThat(boundsOf(tag).top.value).isWithin(TOLERANCE).of(ltrEndTops[i]) + } + + // 2. RTL with mirrored CaptureRtlPolicy(true, true): StartSideRail swaps to physical right + // and QuickSettingsOverlayCard anchors beside StartSideRail on the right without overlap! + observedDirections.clear() + rtlPolicy = CaptureRtlPolicy(mirrorSideRails = true, mirrorCompactBottomBar = true) + composeTestRule.waitForIdle() + + val mirroredStartRail = boundsOf(START_SIDE_RAIL_TAG) + val mirroredEndRail = boundsOf(END_SIDE_RAIL_TAG) + val mirroredCard = boundsOf(QUICK_SETTINGS_OVERLAY_CARD_PLACEHOLDER_TAG) + assertThat(mirroredStartRail.right.value).isWithin(TOLERANCE).of(1280f) + assertThat(mirroredEndRail.left.value).isWithin(TOLERANCE).of(0f) + assertThat(mirroredCard.right.value) + .isAtMost(mirroredStartRail.left.value - 12f + TOLERANCE) + assertThat(mirroredCard.left.value) + .isAtLeast(mirroredEndRail.right.value + 12f - TOLERANCE) + assertThat(mirroredCard.left.value).isGreaterThan(1280f / 2f) + + observedDirections.forEach { (slotName, dir) -> + assertWithMessage("Slot $slotName must receive LayoutDirection.Rtl when mirrored") + .that(dir) + .isEqualTo(LayoutDirection.Rtl) + } + startOrderedTags.forEachIndexed { i, tag -> + assertThat(boundsOf(tag).top.value).isWithin(TOLERANCE).of(ltrStartTops[i]) + } + endOrderedTags.forEachIndexed { i, tag -> + assertThat(boundsOf(tag).top.value).isWithin(TOLERANCE).of(ltrEndTops[i]) + } + } + + @OptIn(ExperimentalMaterial3Api::class) + @Config(qualifiers = "w412dp-h915dp") + @Test + fun compactPortraitLayout_rtlPolicies_scopeBottomBarAndRestoreLocaleDirectionInSlots() { + var layoutDirection by mutableStateOf(LayoutDirection.Ltr) + var rtlPolicy by mutableStateOf(CaptureRtlPolicy(mirrorCompactBottomBar = false)) + var observedActiveLayout: String? = null + val observedDirections = mutableMapOf() + + val baseSlots = PlaceholderCaptureSlots.sideRail(includeElapsedTime = true) + val instrumentedSlots = baseSlots.copy( + topBar = { mod -> + observedDirections["topBar"] = LocalLayoutDirection.current + baseSlots.topBar(this, mod) + }, + zoomControls = { mod -> + observedDirections["zoomControls"] = LocalLayoutDirection.current + baseSlots.zoomControls(this, mod) + }, + imageWell = { mod -> + observedDirections["imageWell"] = LocalLayoutDirection.current + baseSlots.imageWell(this, mod) + }, + captureButton = { mod -> + observedDirections["captureButton"] = LocalLayoutDirection.current + baseSlots.captureButton(this, mod) + }, + flipCameraButton = { mod -> + observedDirections["flipCameraButton"] = LocalLayoutDirection.current + baseSlots.flipCameraButton(this, mod) + }, + captureModeCarousel = { mod -> + observedDirections["captureModeCarousel"] = LocalLayoutDirection.current + baseSlots.captureModeCarousel(this, mod) + }, + quickSettingsButton = { mod -> + observedDirections["quickSettingsButton"] = LocalLayoutDirection.current + baseSlots.quickSettingsButton(this, mod) + }, + captureModeToggle = { mod -> + observedDirections["captureModeToggle"] = LocalLayoutDirection.current + baseSlots.captureModeToggle(this, mod) + } + ) + + composeTestRule.setContent { + MaterialTheme { + CompositionLocalProvider( + LocalLayoutDirection provides layoutDirection, + LocalCaptureRtlPolicy provides rtlPolicy + ) { + CompactPortraitLayout( + slots = instrumentedSlots, + viewfinder = { mod -> + observedActiveLayout = LocalActiveCaptureLayout.current + PlaceholderViewfinder(modifier = mod) + } + ) + } + } + } + composeTestRule.waitForIdle() + + assertThat(observedActiveLayout).isEqualTo("CompactPortraitLayout") + composeTestRule.onNodeWithTag(COMPACT_CONTROLS_TAG).assertIsDisplayed() + val verticalOrderTags = listOf( + VIDEO_QUALITY_TAG, + ELAPSED_TIME_TAG, + ZOOM_BUTTON_ROW_TAG, + CAPTURE_BUTTON, + CAPTURE_MODE_CAROUSEL, + CAPTURE_MODE_TOGGLE_BUTTON + ) + val ltrTops = verticalOrderTags.map { boundsOf(it).top.value } + + observedDirections.clear() + layoutDirection = LayoutDirection.Rtl + rtlPolicy = CaptureRtlPolicy(mirrorSideRails = false, mirrorCompactBottomBar = false) + composeTestRule.waitForIdle() + + assertThat(boundsOf(IMAGE_WELL_TAG).right.value) + .isLessThan(boundsOf(CAPTURE_BUTTON).left.value) + assertThat(boundsOf(FLIP_CAMERA_BUTTON).left.value) + .isGreaterThan(boundsOf(CAPTURE_BUTTON).right.value) + val defaultQsCenter = + ( + boundsOf(QUICK_SETTINGS_DROP_DOWN).left.value + + boundsOf(QUICK_SETTINGS_DROP_DOWN).right.value + ) / 2f + assertThat(defaultQsCenter).isLessThan(412f / 2f) + + observedDirections.forEach { (slotName, dir) -> + assertWithMessage("Compact slot $slotName must receive LayoutDirection.Rtl") + .that(dir) + .isEqualTo(LayoutDirection.Rtl) + } + verticalOrderTags.forEachIndexed { i, tag -> + assertThat(boundsOf(tag).top.value).isWithin(TOLERANCE).of(ltrTops[i]) + } + + observedDirections.clear() + rtlPolicy = CaptureRtlPolicy(mirrorSideRails = true, mirrorCompactBottomBar = true) + composeTestRule.waitForIdle() + + assertThat(boundsOf(FLIP_CAMERA_BUTTON).right.value) + .isLessThan(boundsOf(CAPTURE_BUTTON).left.value) + assertThat(boundsOf(IMAGE_WELL_TAG).left.value) + .isGreaterThan(boundsOf(CAPTURE_BUTTON).right.value) + val mirroredQsCenter = + ( + boundsOf(QUICK_SETTINGS_DROP_DOWN).left.value + + boundsOf(QUICK_SETTINGS_DROP_DOWN).right.value + ) / 2f + assertThat(mirroredQsCenter).isGreaterThan(412f / 2f) + + observedDirections.forEach { (slotName, dir) -> + assertWithMessage("Mirrored compact slot $slotName must receive LayoutDirection.Rtl") + .that(dir) + .isEqualTo(LayoutDirection.Rtl) + } + verticalOrderTags.forEachIndexed { i, tag -> + assertThat(boundsOf(tag).top.value).isWithin(TOLERANCE).of(ltrTops[i]) + } + } + + @Test + fun foldableLayout_statusBarsInsets_clearsVisibleBarAndZeroPadsWhenHidden() { + lateinit var hostView: View + composeTestRule.setContent { + hostView = LocalView.current + MaterialTheme { + FoldableLayout( + slots = PlaceholderCaptureSlots.sideRail(includeElapsedTime = true), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + screenFlashOverlay = { mod -> + Box(modifier = mod.fillMaxSize().testTag(SCREEN_FLASH_OVERLAY)) + } + ) + } + } + + dispatchStatusBarInsets( + view = hostView, + statusBarHeightPx = MULTI_WINDOW_STATUS_BAR_PX, + visible = true + ) + composeTestRule.waitForIdle() + + assertThat(boundsOf(PREVIEW_DISPLAY).top.value).isWithin(TOLERANCE).of(0f) + assertThat(boundsOf(PREVIEW_DISPLAY).bottom.value).isWithin(TOLERANCE).of(883f) + assertThat(boundsOf(START_SIDE_RAIL_TAG).top.value).isAtLeast(32f - TOLERANCE) + assertThat(boundsOf(END_SIDE_RAIL_TAG).top.value).isAtLeast(32f - TOLERANCE) + assertThat(boundsOf(VIDEO_QUALITY_TAG).top.value).isAtLeast(32f - TOLERANCE) + assertThat(boundsOf(SCREEN_FLASH_OVERLAY).top.value).isWithin(TOLERANCE).of(0f) + + dispatchStatusBarInsets( + hostView, + statusBarHeightPx = MULTI_WINDOW_STATUS_BAR_PX, + visible = false + ) + composeTestRule.waitForIdle() + + assertThat(boundsOf(START_SIDE_RAIL_TAG).top.value).isWithin(TOLERANCE).of(0f) + assertThat(boundsOf(END_SIDE_RAIL_TAG).top.value).isWithin(TOLERANCE).of(0f) + } + + @OptIn(ExperimentalMaterial3Api::class) + @Config(qualifiers = "w412dp-h915dp") + @Test + fun compactPortraitLayout_visibleMultiWindowStatusBar_clearsIndicatorsBelowStatusBar() { + lateinit var hostView: View + composeTestRule.setContent { + hostView = LocalView.current + MaterialTheme { + CompactPortraitLayout( + slots = PlaceholderCaptureSlots.sideRail(), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) } + ) + } + } + + dispatchStatusBarInsets( + view = hostView, + statusBarHeightPx = MULTI_WINDOW_STATUS_BAR_PX, + visible = true + ) + composeTestRule.waitForIdle() + + assertThat(boundsOf(VIDEO_QUALITY_TAG).top.value).isAtLeast(32f - TOLERANCE) + } + + @OptIn(ExperimentalMaterial3Api::class) + @Config(qualifiers = "w360dp-h500dp") + @Test + fun compactPortraitLayout_shortSplitScreenFallback_appliesRtlPoliciesAndClearsStatusBar() { + var rtlPolicy by mutableStateOf(CaptureRtlPolicy(mirrorCompactBottomBar = false)) + var flipDirection: LayoutDirection? = null + lateinit var hostView: View + + val baseSlots = PlaceholderCaptureSlots.sideRail() + val instrumentedSlots = baseSlots.copy( + flipCameraButton = { mod -> + flipDirection = LocalLayoutDirection.current + baseSlots.flipCameraButton(this, mod) + } + ) + + composeTestRule.setContent { + hostView = LocalView.current + MaterialTheme { + CompositionLocalProvider( + LocalLayoutDirection provides LayoutDirection.Rtl, + LocalCaptureRtlPolicy provides rtlPolicy + ) { + CompactPortraitLayout( + slots = instrumentedSlots, + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) } + ) + } + } + } + composeTestRule.waitForIdle() + + assertThat(boundsOf(IMAGE_WELL_TAG).right.value) + .isLessThan(boundsOf(CAPTURE_BUTTON).left.value) + assertThat(boundsOf(FLIP_CAMERA_BUTTON).left.value) + .isGreaterThan(boundsOf(CAPTURE_BUTTON).right.value) + assertThat(flipDirection).isEqualTo(LayoutDirection.Rtl) + + rtlPolicy = CaptureRtlPolicy(mirrorCompactBottomBar = true) + composeTestRule.waitForIdle() + assertThat(boundsOf(FLIP_CAMERA_BUTTON).right.value) + .isLessThan(boundsOf(CAPTURE_BUTTON).left.value) + assertThat(boundsOf(IMAGE_WELL_TAG).left.value) + .isGreaterThan(boundsOf(CAPTURE_BUTTON).right.value) + + dispatchStatusBarInsets( + view = hostView, + statusBarHeightPx = MULTI_WINDOW_STATUS_BAR_PX, + visible = true + ) + composeTestRule.waitForIdle() + assertThat(boundsOf(VIDEO_QUALITY_TAG).top.value).isAtLeast(32f - TOLERANCE) + } + + @Test + fun foldableLayout_controlsVisibleAndErrorDialog_hideControlsAndPruneBackgroundA11y() { + var controlsVisible by mutableStateOf(true) + var showErrorDialog by mutableStateOf(false) + val state = CaptureScaffoldState(isInitiallyExpanded = true) + + val baseSlots = PlaceholderCaptureSlots.sideRail(tagQuickSettingsOverlay = true) + val slots = baseSlots.copy( + errorDialog = { mod -> + if (showErrorDialog) { + Box(modifier = mod.size(200.dp).testTag(CAMERA_ERROR_DIALOG_TAG)) + } + } + ) + + composeTestRule.setContent { + MaterialTheme { + FoldableLayout( + slots = slots, + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + state = state, + controlsVisible = controlsVisible, + isErrorDialogShowing = showErrorDialog + ) + } + } + composeTestRule.waitForIdle() + + // Error dialog supersedes Quick Settings card and prunes background accessibility. + composeTestRule.runOnIdle { showErrorDialog = true } + composeTestRule.waitForIdle() + + composeTestRule.onNodeWithTag(CAMERA_ERROR_DIALOG_TAG).assertIsDisplayed() + composeTestRule + .onNodeWithTag(QUICK_SETTINGS_OVERLAY_CARD_PLACEHOLDER_TAG) + .assertDoesNotExist() + composeTestRule.onNodeWithTag(CAPTURE_BUTTON).assert(hiddenFromA11yAncestor) + + // controlsVisible = false removes side rails while keeping viewfinder visible. + composeTestRule.runOnIdle { + showErrorDialog = false + state.dismissQuickSettings() + controlsVisible = false + } + composeTestRule.waitForIdle() + + composeTestRule.onNodeWithTag(CAPTURE_BUTTON).assertDoesNotExist() + composeTestRule.onNodeWithTag(START_SIDE_RAIL_TAG).assertDoesNotExist() + composeTestRule.onNodeWithTag(END_SIDE_RAIL_TAG).assertDoesNotExist() + composeTestRule.onNodeWithTag(PREVIEW_DISPLAY).assertIsDisplayed() + } + + private fun dispatchStatusBarInsets(view: View, statusBarHeightPx: Int, visible: Boolean) { + val barInsets = Insets.of(0, statusBarHeightPx, 0, 0) + val windowInsets = WindowInsetsCompat.Builder() + .setInsets( + WindowInsetsCompat.Type.statusBars(), + if (visible) barInsets else Insets.NONE + ) + .setInsetsIgnoringVisibility(WindowInsetsCompat.Type.statusBars(), barInsets) + .setVisible(WindowInsetsCompat.Type.statusBars(), visible) + .build() + + composeTestRule.runOnUiThread { + ViewCompat.dispatchApplyWindowInsets(view, windowInsets) + } + } + + private companion object { + const val SQUARE_PREVIEW_FRAME_TAG = "square_preview_frame" + const val MULTI_WINDOW_STATUS_BAR_PX = 32 + const val TOLERANCE = 0.5f + } +}