From 27047a7514bdebc6ae6fa447eda27184bb229e30 Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Fri, 6 Nov 2026 05:25:57 -0800 Subject: [PATCH 1/3] feat(ui/capture): add CompactPortraitLayout, TwoSideRailLayout, and WideShortLayout --- .../ui/components/capture/CaptureLayout.kt | 839 +---------- .../capture/CompactPortraitLayout.kt | 1268 +++++++++++++++++ .../components/capture/TwoSideRailLayout.kt | 493 +++++++ .../ui/components/capture/WideShortLayout.kt | 482 +++++++ .../capture/TwoSideRailLayoutTest.kt | 655 +++++++++ .../components/capture/WideShortLayoutTest.kt | 413 ++++++ 6 files changed, 3357 insertions(+), 793 deletions(-) create mode 100644 ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CompactPortraitLayout.kt create mode 100644 ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/TwoSideRailLayout.kt create mode 100644 ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/WideShortLayout.kt create mode 100644 ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/TwoSideRailLayoutTest.kt create mode 100644 ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/WideShortLayoutTest.kt 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 5a2b0afb0..624f1caab 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,27 @@ 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.BottomSheetScaffoldState 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.runtime.Composable -import androidx.compose.runtime.CompositionLocalProvider -import androidx.compose.runtime.DisposableEffect -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 +private object PreviewLayoutTokens { + const val PREVIEW_VIEWFINDER_ASPECT_RATIO = 3f / 4f + val PreviewCaptureButtonSize = 80.dp + val PreviewControlSize = 48.dp + val PreviewElapsedHeight = 24.dp + const val PREVIEW_HALF_WIDTH_FRACTION = 0.5f +} /** * The top edge of the visible viewfinder, reported by a viewfinder that fills its slot and offsets @@ -201,17 +96,11 @@ internal val ViewfinderTopLine = HorizontalAlignmentLine { a, b -> minOf(a, b) } * does not change the system bars itself. * @param errorDialog the camera error alert dialog composable */ -@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) -@Suppress("DEPRECATION") +@OptIn(ExperimentalMaterial3Api::class) @Composable fun PreviewLayout( modifier: Modifier = Modifier, - scaffoldState: BottomSheetScaffoldState = rememberBottomSheetScaffoldState( - bottomSheetState = rememberStandardBottomSheetState( - initialValue = SheetValue.Hidden, - skipHiddenState = false - ) - ), + scaffoldState: BottomSheetScaffoldState = rememberCompactPortraitScaffoldState(), onDismissQuickSettings: () -> Unit = {}, viewfinder: @Composable (Modifier) -> Unit, captureButton: @Composable (Modifier) -> Unit, @@ -234,668 +123,32 @@ fun PreviewLayout( onRequiresImmersiveChange: (Boolean) -> Unit = {}, errorDialog: @Composable (Modifier) -> Unit = {} ) { - val overlapTargetBounds = remember { mutableStateOf(Rect.Zero) } - val dismissQuickSettingsLabel = - stringResource(R.string.quick_settings_btn_close_expanded_settings_description) - - CompositionLocalProvider(LocalOverlapTargetBounds provides overlapTargetBounds) { - Box(modifier = modifier.fillMaxSize()) { - BottomSheetScaffold( - modifier = Modifier.fillMaxSize(), - scaffoldState = scaffoldState, - sheetPeekHeight = 0.dp, - sheetDragHandle = { - BottomSheetDefaults.DragHandle( - modifier = Modifier - .testTag(QUICK_SETTINGS_DRAG_HANDLE) - .clickable( - role = Role.Button, - onClickLabel = dismissQuickSettingsLabel, - onClick = onDismissQuickSettings - ) - ) - }, - 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, - debugVisibilityWrapper = debugVisibilityWrapper, - snackbarHost = { modifier -> - PillSnackbarHost( - snackbarHostState = scaffoldState.snackbarHostState, - modifier = modifier - ) - } - ) - Box( - modifier = Modifier - .fillMaxSize() - .windowInsetsPadding( - WindowInsets.systemBarsIgnoringVisibility - .union(WindowInsets.displayCutout) - ) - ) { - snackBar(Modifier, scaffoldState.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 - ) { - indicatorRow(Modifier) - topBarTrailingContent(Modifier.align(Alignment.CenterEnd)) - } - 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) - ) - ) { - debugVisibilityWrapper { - VerticalMaterialControls( - captureButton = captureButton, - imageWell = imageWell, - flipCameraButton = flipCameraButton, - quickSettingsToggleButton = quickSettingsButton, - captureModeToggleSwitch = captureModeToggle, - captureModeCarousel = captureModeCarousel, - zoomControls = zoomLevelDisplay, - elapsedTimeDisplay = elapsedTimeDisplay, - snackbarHost = { modifier -> - PillSnackbarHost( - snackbarHostState = scaffoldState.snackbarHostState, - modifier = modifier - ) - } - ) - } - snackBar(Modifier, scaffoldState.snackbarHostState) - } - } - debugOverlay(Modifier) - - val isSheetVisible = scaffoldState.bottomSheetState.isVisible || - scaffoldState.bottomSheetState.targetValue == SheetValue.Expanded - if (isSheetVisible) { - Box( - modifier = Modifier - .fillMaxSize() - .testTag(QUICK_SETTINGS_SCRIM) - .clickable( - onClickLabel = dismissQuickSettingsLabel, - interactionSource = remember { MutableInteractionSource() }, - indication = null, - onClick = onDismissQuickSettings - ) - ) - } - 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) -@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 (Modifier) -> Unit, - topBarTrailingContent: @Composable (Modifier) -> Unit, - elapsedTimeDisplay: @Composable (Modifier) -> Unit, - zoomControls: @Composable (Modifier) -> Unit, - imageWell: @Composable (Modifier) -> Unit, - captureButton: @Composable (Modifier) -> Unit, - flipCameraButton: @Composable (Modifier) -> Unit, - captureModeCarousel: @Composable (Modifier) -> Unit, - quickSettingsToggleButton: @Composable (Modifier) -> Unit, - captureModeToggleSwitch: @Composable (Modifier) -> Unit, - debugVisibilityWrapper: (@Composable (@Composable () -> Unit) -> Unit), - 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) - } - } - - Box( - modifier = Modifier - .layoutId(CaptureSlotId.TopBar) - .fillMaxWidth() - .height(topBarHeight) - .windowInsetsPadding( - WindowInsets.displayCutout.only(WindowInsetsSides.Horizontal) - ) - .padding(horizontal = LOWER_SECTION_HORIZONTAL_PADDING), - contentAlignment = Alignment.CenterStart - ) { - indicatorRow(Modifier) - topBarTrailingContent(Modifier.align(Alignment.CenterEnd)) - } - - debugVisibilityWrapper { - Column( - modifier = Modifier.layoutId(CaptureSlotId.ElapsedTime), - horizontalAlignment = Alignment.CenterHorizontally - ) { - snackbarHost(Modifier) - 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()) - ) - 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 (Modifier) -> Unit, - zoomControls: @Composable (Modifier) -> Unit, - imageWell: @Composable (Modifier) -> Unit, - flipCameraButton: @Composable (Modifier) -> Unit, - quickSettingsToggleButton: @Composable (Modifier) -> Unit, - captureModeToggleSwitch: @Composable (Modifier) -> Unit, - captureModeCarousel: @Composable (Modifier) -> Unit = {}, - elapsedTimeDisplay: @Composable (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 - // PreviewLayout), 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) - - 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. - Box( - modifier = Modifier - .fillMaxWidth() - .height(MIDDLE_SLOT_HEIGHT + stackGap * 2), - contentAlignment = Alignment.Center - ) { - OverlapAwareStyleProvider { - captureModeCarousel(Modifier) - } - } - - // bottom controls row - Row( - Modifier - .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)) - } - } - } + CompactPortraitLayout( + modifier = modifier, + scaffoldState = scaffoldState, + onDismissQuickSettings = onDismissQuickSettings, + includeStatusBarsInTopBar = false, + viewfinder = viewfinder, + captureButton = captureButton, + imageWell = imageWell, + flipCameraButton = flipCameraButton, + zoomLevelDisplay = zoomLevelDisplay, + elapsedTimeDisplay = elapsedTimeDisplay, + quickSettingsButton = quickSettingsButton, + indicatorRow = indicatorRow, + captureModeToggle = captureModeToggle, + captureModeCarousel = captureModeCarousel, + quickSettingsOverlay = quickSettingsOverlay, + debugOverlay = debugOverlay, + debugVisibilityWrapper = debugVisibilityWrapper, + screenFlashOverlay = screenFlashOverlay, + snackBar = snackBar, + topStartContent = topStartContent, + viewfinderTopEndContent = viewfinderTopEndContent, + topBarTrailingContent = topBarTrailingContent, + onRequiresImmersiveChange = onRequiresImmersiveChange, + errorDialog = errorDialog + ) } @OptIn(ExperimentalMaterial3Api::class) @@ -908,35 +161,35 @@ private fun CaptureLayoutPreview() { Box( modifier = modifier .fillMaxWidth() - .aspectRatio(3f / 4f) + .aspectRatio(PreviewLayoutTokens.PREVIEW_VIEWFINDER_ASPECT_RATIO) .background(Color.DarkGray) ) }, captureButton = { modifier -> Box( modifier = modifier - .size(80.dp) + .size(PreviewLayoutTokens.PreviewCaptureButtonSize) .background(Color.White) ) }, flipCameraButton = { modifier -> Box( modifier = modifier - .size(48.dp) + .size(PreviewLayoutTokens.PreviewControlSize) .background(Color.Cyan) ) }, imageWell = { modifier -> Box( modifier = modifier - .size(48.dp) + .size(PreviewLayoutTokens.PreviewControlSize) .background(Color.Cyan) ) }, zoomLevelDisplay = { modifier -> Box( modifier = modifier - .height(48.dp) + .height(PreviewLayoutTokens.PreviewControlSize) .fillMaxWidth() .background(Color.Magenta) ) @@ -944,22 +197,22 @@ private fun CaptureLayoutPreview() { elapsedTimeDisplay = { modifier -> Box( modifier = modifier - .height(24.dp) - .fillMaxWidth(0.5f) + .height(PreviewLayoutTokens.PreviewElapsedHeight) + .fillMaxWidth(PreviewLayoutTokens.PREVIEW_HALF_WIDTH_FRACTION) .background(Color.Red) ) }, quickSettingsButton = { modifier -> Box( modifier = modifier - .size(48.dp) + .size(PreviewLayoutTokens.PreviewControlSize) .background(Color.Yellow) ) }, indicatorRow = { modifier -> Box( modifier = modifier - .height(48.dp) + .height(PreviewLayoutTokens.PreviewControlSize) .fillMaxWidth() .background(Color.Green) ) @@ -967,8 +220,8 @@ private fun CaptureLayoutPreview() { captureModeToggle = { modifier -> Box( modifier = modifier - .height(48.dp) - .fillMaxWidth(0.5f) + .height(PreviewLayoutTokens.PreviewControlSize) + .fillMaxWidth(PreviewLayoutTokens.PREVIEW_HALF_WIDTH_FRACTION) .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..208f8417d --- /dev/null +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CompactPortraitLayout.kt @@ -0,0 +1,1268 @@ +/* + * 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.BottomSheetScaffoldState +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.rememberBottomSheetState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.DisposableEffect +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.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.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.clearAndSetSemantics +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 + +private 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 +} + +/** + * Remembers a [BottomSheetScaffoldState] configured for [CompactPortraitLayout] and + * [PreviewLayout], backed by the non-deprecated Material 3 [rememberBottomSheetState] API. + * + * @param initialValue Initial [SheetValue] of the Quick Settings bottom sheet; defaults to + * [SheetValue.Hidden]. + * @return A remembered [BottomSheetScaffoldState] supporting hidden, partially expanded, and + * expanded sheet states. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun rememberCompactPortraitScaffoldState( + initialValue: SheetValue = SheetValue.Hidden +): BottomSheetScaffoldState = rememberBottomSheetScaffoldState( + bottomSheetState = rememberBottomSheetState(initialValue = initialValue) +) + +/** + * Suppresses keyboard/rotary focus and accessibility semantics on background camera chrome while an + * in-hierarchy modal surface (such as Quick Settings or an error dialog) is open above it. + */ +internal fun Modifier.suppressBackgroundForModal(isModalOpen: Boolean): Modifier = + if (isModalOpen) { + this + .focusProperties { canFocus = false } + .clearAndSetSemantics {} + } else { + this + } + +/** + * Compact portrait 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 without spawning secondary windows. Tags its root + * container with [COMPACT_CONTROLS_TAG] 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 scaffoldState [BottomSheetScaffoldState] controlling the Quick Settings sheet and snackbar + * host. + * @param isRecording Whether an active video recording session is in progress. + * @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 the user taps the Quick Settings drag handle + * or scrim, or triggers dismissal from a slot. + * @param onRequiresImmersiveChange Callback notified when the portrait layout solver requires or + * releases immersive navigation-bar hiding. + * @param debugOverlay Untouched pass-through composable for debug UI overlays. + * @param debugVisibilityWrapper Wrapper conditionally hiding camera chrome when debug component + * hiding is enabled. + * @param screenFlashOverlay Full-bleed screen flash composable drawn above all chrome and system + * bar areas. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun CompactPortraitLayout( + slots: CaptureSlots, + viewfinder: @Composable (Modifier) -> Unit, + modifier: Modifier = Modifier, + scaffoldState: BottomSheetScaffoldState = rememberCompactPortraitScaffoldState(), + isRecording: Boolean = false, + isErrorDialogShowing: Boolean = false, + includeStatusBarsInTopBar: Boolean = true, + onDismissQuickSettings: () -> Unit = {}, + onRequiresImmersiveChange: (Boolean) -> Unit = {}, + debugOverlay: @Composable (Modifier) -> Unit = {}, + debugVisibilityWrapper: @Composable (@Composable () -> Unit) -> Unit = { it() }, + screenFlashOverlay: @Composable (Modifier) -> Unit = {} +) { + CompactPortraitLayout( + modifier = modifier, + scaffoldState = scaffoldState, + onDismissQuickSettings = onDismissQuickSettings, + isErrorDialogShowing = isErrorDialogShowing, + includeStatusBarsInTopBar = includeStatusBarsInTopBar, + viewfinder = viewfinder, + captureButton = { slotModifier -> + OverlapAwareCaptureSlot( + modifier = slotModifier, + orientation = Orientation.Horizontal, + isCompact = false, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings, + content = slots.captureButton + ) + }, + imageWell = { slotModifier -> + OverlapAwareCaptureSlot( + modifier = slotModifier, + orientation = Orientation.Horizontal, + isCompact = false, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings, + content = slots.imageWell + ) + }, + flipCameraButton = { slotModifier -> + OverlapAwareCaptureSlot( + modifier = slotModifier, + orientation = Orientation.Horizontal, + isCompact = false, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings, + content = slots.flipCameraButton + ) + }, + zoomLevelDisplay = { slotModifier -> + OverlapAwareCaptureSlot( + modifier = slotModifier, + orientation = Orientation.Horizontal, + isCompact = false, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings, + content = slots.zoomControls + ) + }, + elapsedTimeDisplay = { slotModifier -> + OverlapAwareCaptureSlot( + modifier = slotModifier, + orientation = Orientation.Horizontal, + isCompact = false, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings, + content = slots.elapsedTimeDisplay + ) + }, + quickSettingsButton = { slotModifier -> + OverlapAwareCaptureSlot( + modifier = slotModifier, + orientation = Orientation.Horizontal, + isCompact = false, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings, + content = slots.quickSettingsButton + ) + }, + indicatorRow = { slotModifier -> + OverlapAwareCaptureSlot( + modifier = slotModifier, + orientation = Orientation.Horizontal, + isCompact = false, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings, + content = slots.topBar + ) + }, + captureModeToggle = { slotModifier -> + OverlapAwareCaptureSlot( + modifier = slotModifier, + orientation = Orientation.Horizontal, + isCompact = false, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings, + content = slots.captureModeToggle + ) + }, + captureModeCarousel = { slotModifier -> + OverlapAwareCaptureSlot( + modifier = slotModifier, + orientation = Orientation.Horizontal, + isCompact = false, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings, + content = slots.captureModeCarousel + ) + }, + quickSettingsOverlay = { slotModifier -> + OverlapAwareCaptureSlot( + modifier = slotModifier, + orientation = Orientation.Vertical, + isCompact = false, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings, + content = slots.quickSettingsOverlay + ) + }, + debugOverlay = debugOverlay, + debugVisibilityWrapper = debugVisibilityWrapper, + screenFlashOverlay = screenFlashOverlay, + snackBar = slots.snackBar, + topStartContent = { slotModifier -> + val slotScope = rememberCaptureSlotScope( + orientation = Orientation.Horizontal, + isCompact = false, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings + ) + slotScope.(slots.viewfinderTopStart)(slotModifier) + }, + viewfinderTopEndContent = { slotModifier -> + val slotScope = rememberCaptureSlotScope( + orientation = Orientation.Horizontal, + isCompact = false, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings + ) + slotScope.(slots.viewfinderTopEnd)(slotModifier) + }, + topBarTrailingContent = { slotModifier -> + OverlapAwareCaptureSlot( + modifier = slotModifier, + orientation = Orientation.Horizontal, + isCompact = false, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings, + content = slots.topBarTrailingContent + ) + }, + onRequiresImmersiveChange = onRequiresImmersiveChange, + errorDialog = slots.errorDialog + ) +} + +/** + * Compact portrait capture layout accepting individual control composables. + * + * Uses [AdaptivePortraitCaptureLayout] for handheld portrait aspect ratios (16:9 and taller) and + * falls back to [VerticalMaterialControls] for squarer compact panes (such as split-screen + * multi-window). Hosts Quick Settings inside an in-hierarchy [BottomSheetScaffold] and tags its + * root container with [COMPACT_CONTROLS_TAG]. + * + * @param modifier [Modifier] applied to the outer layout container. + * @param scaffoldState [BottomSheetScaffoldState] controlling the Quick Settings sheet and snackbar + * host. + * @param onDismissQuickSettings Callback invoked when the user taps the Quick Settings drag handle + * or scrim. + * @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 (`true` by default for multi-window clearance; `false` when + * called from legacy [PreviewLayout] to keep top-bar coordinates invariant across status-bar + * visibility transitions). + * @param viewfinder Composable rendering the camera preview frame. + * @param captureButton Primary photo/video shutter button composable. + * @param imageWell Media thumbnail button composable. + * @param flipCameraButton Lens-facing toggle button composable. + * @param zoomLevelDisplay Zoom control bar composable. + * @param elapsedTimeDisplay Recording duration readout composable. + * @param quickSettingsButton Button toggling the Quick Settings bottom sheet. + * @param indicatorRow Status indicator bar content placed in the top bar. + * @param captureModeToggle Photo/video mode toggle switch composable. + * @param captureModeCarousel Secondary sub-mode selector carousel placed in the reserved middle + * band. + * @param quickSettingsOverlay Content rendered inside the Quick Settings bottom sheet. + * @param debugOverlay Untouched pass-through composable for debug UI overlays. + * @param debugVisibilityWrapper Wrapper conditionally hiding camera chrome when debug component + * hiding is enabled. + * @param screenFlashOverlay Full-bleed screen flash composable drawn above all other content and + * system bar areas. + * @param snackBar Transient message composable paired with a [SnackbarHostState]. + * @param topStartContent Optional content anchored directly below the top bar at the start edge. + * @param viewfinderTopEndContent Optional content anchored to the top-end corner of the viewfinder. + * @param topBarTrailingContent Optional trailing content aligned to the end of the top bar. + * @param onRequiresImmersiveChange Callback notified when the portrait solver requires or releases + * immersive navigation-bar hiding. + * @param errorDialog In-hierarchy camera error dialog composable. + */ +@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) +@Composable +fun CompactPortraitLayout( + modifier: Modifier = Modifier, + scaffoldState: BottomSheetScaffoldState = rememberCompactPortraitScaffoldState(), + onDismissQuickSettings: () -> Unit = {}, + isErrorDialogShowing: Boolean = false, + includeStatusBarsInTopBar: Boolean = true, + viewfinder: @Composable (Modifier) -> Unit, + captureButton: @Composable (Modifier) -> Unit, + imageWell: @Composable (Modifier) -> Unit, + flipCameraButton: @Composable (Modifier) -> Unit, + zoomLevelDisplay: @Composable (Modifier) -> Unit, + elapsedTimeDisplay: @Composable (Modifier) -> Unit, + quickSettingsButton: @Composable (Modifier) -> Unit, + indicatorRow: @Composable (Modifier) -> Unit, + captureModeToggle: @Composable (Modifier) -> Unit, + captureModeCarousel: @Composable (Modifier) -> Unit = {}, + quickSettingsOverlay: @Composable (Modifier) -> Unit, + debugOverlay: @Composable (Modifier) -> Unit = {}, + debugVisibilityWrapper: @Composable (@Composable () -> Unit) -> Unit = { it() }, + screenFlashOverlay: @Composable (Modifier) -> Unit = {}, + snackBar: @Composable (Modifier, snackbarHostState: SnackbarHostState) -> Unit = { _, _ -> }, + topStartContent: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit = {}, + viewfinderTopEndContent: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit = {}, + topBarTrailingContent: @Composable (Modifier) -> Unit = {}, + onRequiresImmersiveChange: (Boolean) -> Unit = {}, + errorDialog: @Composable (Modifier) -> Unit = {} +) { + val overlapTargetBounds = remember { mutableStateOf(Rect.Zero) } + val localeDirection = LocalLayoutDirection.current + val dismissQuickSettingsLabel = + stringResource(R.string.quick_settings_btn_close_expanded_settings_description) + val isSheetVisible = scaffoldState.bottomSheetState.isVisible || + scaffoldState.bottomSheetState.targetValue == SheetValue.Expanded + val isModalOpen = isSheetVisible || isErrorDialogShowing + + CompositionLocalProvider(LocalOverlapTargetBounds provides overlapTargetBounds) { + 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) + .clickable( + role = Role.Button, + onClickLabel = dismissQuickSettingsLabel, + onClick = onDismissQuickSettings + ) + ) + }, + sheetShape = RoundedCornerShape( + topStart = CompactPortraitTokens.SheetTopCornerRadius, + topEnd = CompactPortraitTokens.SheetTopCornerRadius + ), + sheetContainerColor = MaterialTheme.colorScheme.surfaceContainerLow, + sheetContent = { + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + quickSettingsOverlay(Modifier) + } + }, + snackbarHost = {} + ) { + BoxWithConstraints( + modifier = Modifier + .fillMaxSize() + .background(Color.Black) + ) { + val windowAspectRatio = maxHeight.value / maxWidth.value + val isHandheldPortrait = + windowAspectRatio >= CompactPortraitTokens.PORTRAIT_ASPECT_RATIO_THRESHOLD + if (isHandheldPortrait) { + AdaptivePortraitCaptureLayout( + windowWidth = maxWidth, + windowHeight = maxHeight, + includeStatusBarsInTopBar = includeStatusBarsInTopBar, + isSheetVisible = isSheetVisible, + isModalOpen = 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, + debugVisibilityWrapper = debugVisibilityWrapper, + snackbarHost = { hostModifier -> + PillSnackbarHost( + snackbarHostState = scaffoldState.snackbarHostState, + modifier = hostModifier + ) + } + ) + Box( + modifier = Modifier + .fillMaxSize() + .suppressBackgroundForModal(isModalOpen) + .windowInsetsPadding( + WindowInsets.systemBarsIgnoringVisibility + .union(WindowInsets.displayCutout) + ) + ) { + CompositionLocalProvider( + LocalLayoutDirection provides localeDirection + ) { + snackBar(Modifier, scaffoldState.snackbarHostState) + } + } + } else { + Column { + val minTouchTarget = LocalMinimumInteractiveComponentSize.current + .takeOrElse { CompactPortraitTokens.DefaultMinTouchTarget } + val (topBarHeight, topBarTopPadding) = computeTopBarMetrics( + includeStatusBarsInTopBar = includeStatusBarsInTopBar, + minTouchTarget = minTouchTarget + ) + CompactTopBarBox( + topBarHeight = topBarHeight, + topBarTopPadding = topBarTopPadding, + modifier = Modifier.suppressBackgroundForModal(isModalOpen), + indicatorRow = indicatorRow, + topBarTrailingContent = topBarTrailingContent + ) + Box { + Box(modifier = Modifier.suppressBackgroundForModal(isModalOpen)) { + viewfinder(Modifier) + } + OverlapAwareStyleProvider( + Modifier + .align(Alignment.TopStart) + .suppressBackgroundForModal(isSheetVisible) + ) { + topStartContent(Modifier) + } + OverlapAwareStyleProvider( + Modifier + .align(Alignment.TopEnd) + .suppressBackgroundForModal(isModalOpen) + ) { + viewfinderTopEndContent(Modifier) + } + } + } + + Box( + modifier = Modifier + .fillMaxSize() + .suppressBackgroundForModal(isModalOpen) + .windowInsetsPadding( + WindowInsets.systemBarsIgnoringVisibility + .union(WindowInsets.displayCutout) + ) + ) { + debugVisibilityWrapper { + VerticalMaterialControls( + captureButton = captureButton, + imageWell = imageWell, + flipCameraButton = flipCameraButton, + quickSettingsToggleButton = quickSettingsButton, + captureModeToggleSwitch = captureModeToggle, + captureModeCarousel = captureModeCarousel, + zoomControls = zoomLevelDisplay, + elapsedTimeDisplay = elapsedTimeDisplay, + snackbarHost = { hostModifier -> + PillSnackbarHost( + snackbarHostState = scaffoldState.snackbarHostState, + modifier = hostModifier + ) + } + ) + } + CompositionLocalProvider( + LocalLayoutDirection provides localeDirection + ) { + snackBar(Modifier, scaffoldState.snackbarHostState) + } + } + } + + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + debugOverlay(Modifier) + } + + if (isSheetVisible) { + Box( + modifier = Modifier + .fillMaxSize() + .testTag(QUICK_SETTINGS_SCRIM) + .clickable( + onClickLabel = dismissQuickSettingsLabel, + interactionSource = remember { MutableInteractionSource() }, + indication = null, + onClick = onDismissQuickSettings + ) + ) + } + + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + 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 (Modifier) -> Unit, + topBarTrailingContent: @Composable (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 + ) { + indicatorRow(Modifier) + topBarTrailingContent(Modifier.align(Alignment.CenterEnd)) + } + } +} + +@Composable +private fun CompactCaptureRow( + bottomBarDirection: LayoutDirection, + localeDirection: LayoutDirection, + imageWell: @Composable (Modifier) -> Unit, + captureButton: @Composable (Modifier) -> Unit, + flipCameraButton: @Composable (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 { + imageWell(Modifier) + } + } + } + } + + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + OverlapAwareStyleProvider { + captureButton(Modifier) + } + } + + Box( + modifier = Modifier + .weight(1f) + .fillMaxHeight(), + contentAlignment = Alignment.Center + ) { + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + OverlapAwareStyleProvider { + flipCameraButton(Modifier) + } + } + } + } + } +} + +@Composable +private fun CompactBottomToolbar( + bottomBarDirection: LayoutDirection, + localeDirection: LayoutDirection, + quickSettingsToggleButton: @Composable (Modifier) -> Unit, + captureModeToggleSwitch: @Composable (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 { + quickSettingsToggleButton(Modifier) + } + } + } + + Box( + modifier = Modifier.weight(1f), + contentAlignment = Alignment.Center + ) { + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + OverlapAwareStyleProvider { + 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 (Modifier) -> Unit, + topBarTrailingContent: @Composable (Modifier) -> Unit, + elapsedTimeDisplay: @Composable (Modifier) -> Unit, + zoomControls: @Composable (Modifier) -> Unit, + imageWell: @Composable (Modifier) -> Unit, + captureButton: @Composable (Modifier) -> Unit, + flipCameraButton: @Composable (Modifier) -> Unit, + captureModeCarousel: @Composable (Modifier) -> Unit, + quickSettingsToggleButton: @Composable (Modifier) -> Unit, + captureModeToggleSwitch: @Composable (Modifier) -> Unit, + debugVisibilityWrapper: @Composable (@Composable () -> Unit) -> Unit, + includeStatusBarsInTopBar: Boolean = true, + isSheetVisible: Boolean = false, + isModalOpen: Boolean = false, + 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) + .suppressBackgroundForModal(isModalOpen) + ) { + viewfinder(Modifier) + } + + Box( + modifier = Modifier + .layoutId(CaptureSlotId.TopStartContent) + .suppressBackgroundForModal(isSheetVisible) + ) { + OverlapAwareStyleProvider { + topStartContent(Modifier) + } + } + + Box( + modifier = Modifier + .layoutId(CaptureSlotId.ViewfinderTopEndContent) + .suppressBackgroundForModal(isModalOpen) + ) { + OverlapAwareStyleProvider { + viewfinderTopEndContent(Modifier) + } + } + + CompactTopBarBox( + topBarHeight = topBarHeight, + topBarTopPadding = topBarTopPadding, + modifier = Modifier + .layoutId(CaptureSlotId.TopBar) + .suppressBackgroundForModal(isModalOpen), + indicatorRow = indicatorRow, + topBarTrailingContent = topBarTrailingContent + ) + + debugVisibilityWrapper { + Column( + modifier = Modifier + .layoutId(CaptureSlotId.ElapsedTime) + .suppressBackgroundForModal(isModalOpen), + horizontalAlignment = Alignment.CenterHorizontally + ) { + snackbarHost(Modifier) + elapsedTimeDisplay(Modifier) + } + + Box( + modifier = Modifier + .layoutId(CaptureSlotId.ZoomBar) + .suppressBackgroundForModal(isModalOpen), + contentAlignment = Alignment.Center + ) { + OverlapAwareStyleProvider { + zoomControls(Modifier) + } + } + + CompactCaptureRow( + bottomBarDirection = bottomBarDirection, + localeDirection = localeDirection, + imageWell = imageWell, + captureButton = captureButton, + flipCameraButton = flipCameraButton, + modifier = Modifier + .layoutId(CaptureSlotId.CaptureRow) + .suppressBackgroundForModal(isModalOpen) + ) + + Box( + modifier = Modifier + .layoutId(CaptureSlotId.ModeSwitcher) + .fillMaxWidth() + .suppressBackgroundForModal(isModalOpen), + contentAlignment = Alignment.Center + ) { + OverlapAwareStyleProvider { + captureModeCarousel(Modifier) + } + } + + CompactBottomToolbar( + bottomBarDirection = bottomBarDirection, + localeDirection = localeDirection, + quickSettingsToggleButton = quickSettingsToggleButton, + captureModeToggleSwitch = captureModeToggleSwitch, + modifier = Modifier + .layoutId(CaptureSlotId.BottomToolbar) + .suppressBackgroundForModal(isModalOpen) + ) + } + } + ) { 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 (Modifier) -> Unit, + zoomControls: @Composable (Modifier) -> Unit, + imageWell: @Composable (Modifier) -> Unit, + flipCameraButton: @Composable (Modifier) -> Unit, + quickSettingsToggleButton: @Composable (Modifier) -> Unit, + captureModeToggleSwitch: @Composable (Modifier) -> Unit, + captureModeCarousel: @Composable (Modifier) -> Unit = {}, + elapsedTimeDisplay: @Composable (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) + + elapsedTimeDisplay(Modifier) + + OverlapAwareStyleProvider { + zoomControls(Modifier) + } + + Spacer(modifier = Modifier.height(zoomGap)) + + Column { + CompactCaptureRow( + bottomBarDirection = bottomBarDirection, + localeDirection = localeDirection, + imageWell = imageWell, + captureButton = captureButton, + flipCameraButton = flipCameraButton, + modifier = Modifier.height(CompactPortraitTokens.ShutterStackHeight) + ) + } + + Box( + modifier = Modifier + .fillMaxWidth() + .height(CompactPortraitTokens.MiddleSlotHeight + stackGap * 2), + contentAlignment = Alignment.Center + ) { + OverlapAwareStyleProvider { + captureModeCarousel(Modifier) + } + } + + CompactBottomToolbar( + bottomBarDirection = bottomBarDirection, + localeDirection = localeDirection, + quickSettingsToggleButton = quickSettingsToggleButton, + captureModeToggleSwitch = captureModeToggleSwitch, + modifier = Modifier.height(CompactPortraitTokens.LowerSectionHeight) + ) + + Spacer(modifier = Modifier.height(bottomPad)) + } + } + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Preview( + name = "CompactPortrait - Phone Portrait (412x915dp)", + device = "spec:width=412dp,height=915dp", + showBackground = true +) +@Composable +private fun CompactPortraitStandardPhonePreview() { + MaterialTheme { + CompactPortraitLayout( + slots = PlaceholderCaptureSlots.sideRail(includeElapsedTime = true), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) } + ) + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Preview( + name = "CompactPortrait - Short Phone (360x640dp)", + device = "spec:width=360dp,height=640dp", + showBackground = true +) +@Composable +private fun CompactPortraitShortPhonePreview() { + MaterialTheme { + CompactPortraitLayout( + slots = PlaceholderCaptureSlots.sideRail(includeElapsedTime = true), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) } + ) + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Preview( + name = "CompactPortrait - RTL Default Policy (Unmirrored Bar)", + device = "spec:width=412dp,height=915dp", + locale = "ar", + showBackground = true +) +@Composable +private fun CompactPortraitRtlDefaultPolicyPreview() { + MaterialTheme { + CompositionLocalProvider( + LocalCaptureRtlPolicy provides CaptureRtlPolicy(mirrorCompactBottomBar = false) + ) { + CompactPortraitLayout( + slots = PlaceholderCaptureSlots.sideRail(includeElapsedTime = true), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) } + ) + } + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Preview( + name = "CompactPortrait - RTL Mirrored Policy", + device = "spec:width=412dp,height=915dp", + locale = "ar", + showBackground = true +) +@Composable +private fun CompactPortraitRtlMirroredPolicyPreview() { + MaterialTheme { + 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/TwoSideRailLayout.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/TwoSideRailLayout.kt new file mode 100644 index 000000000..067ff3737 --- /dev/null +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/TwoSideRailLayout.kt @@ -0,0 +1,493 @@ +/* + * 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.WindowInsets +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.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Surface +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.ui.AbsoluteAlignment +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.platform.LocalLayoutDirection +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.dp + +private object TwoSideRailTokens { + val StandardChromePadding = 16.dp + val StandardTopOverlayHorizontalClearance = 120.dp + val QuickSettingsCardMaxWidth = 360.dp + val QuickSettingsCardCornerRadius = 28.dp + val QuickSettingsCardTonalElevation = 6.dp + val QuickSettingsScrimColor = Color.Black.copy(alpha = 0.45f) +} + +/** + * Large-screen and foldable capture layout anchoring vertical control rails to the start and end + * edges over a full-bleed camera viewfinder. + * + * Places [viewfinder] in a full-screen centered background box without portrait solver offsets so + * previews sit flush from top to bottom. Overlays [StartSideRail], [EndSideRail] (with + * `showElapsedTimeInRail = false`), and center HUD slots inside live + * `WindowInsets.systemBars.union(WindowInsets.displayCutout)` safe bounds so visible multi-window + * status bars are cleared while hidden immersive bars introduce zero dead padding. + * + * Scopes [LocalCaptureRtlPolicy] (`mirrorSideRails`) solely to the spatial rail container and Quick + * Settings card anchor while immediately restoring the active locale's `LayoutDirection` inside + * both rails and every child slot. Hosts Quick Settings as an in-hierarchy floating [Surface] card + * (optionally tagged with [QUICK_SETTINGS_BOTTOM_SHEET]) without spawning secondary windows. + * + * @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 root layout box. + * @param snackbarHostState [SnackbarHostState] driving the top-center [PillSnackbarHost] and passed + * to [CaptureSlots.snackBar]. + * @param isQuickSettingsOpen Whether the in-hierarchy Quick Settings scrim and floating card are + * displayed. + * @param isRecording Whether an active video recording session is in progress. + * @param isErrorDialogShowing Whether a modal camera error dialog is currently visible above the + * capture chrome. + * @param tagQuickSettingsCard Whether the outer floating Quick Settings [Surface] card carries + * [QUICK_SETTINGS_BOTTOM_SHEET]; defaults to `true` so callers whose inner overlay is untagged + * preserve test-tag parity with compact sheets, and can be set to `false` when the inner overlay + * already attaches that tag. + * @param onDismissQuickSettings Callback invoked on scrim tap, system back press while Quick + * Settings is open, or [CaptureSlotScope.dismissQuickSettings]. + * @param debugOverlay Untouched pass-through composable for debug UI overlays. + * @param debugVisibilityWrapper Wrapper conditionally hiding camera chrome when debug component + * hiding is enabled. + * @param screenFlashOverlay Full-bleed screen flash composable drawn above all chrome and system + * bar areas. + */ +@Composable +fun TwoSideRailLayout( + slots: CaptureSlots, + viewfinder: @Composable (Modifier) -> Unit, + modifier: Modifier = Modifier, + snackbarHostState: SnackbarHostState = remember { SnackbarHostState() }, + isQuickSettingsOpen: Boolean = false, + isRecording: Boolean = false, + isErrorDialogShowing: Boolean = false, + tagQuickSettingsCard: Boolean = true, + onDismissQuickSettings: () -> Unit = {}, + debugOverlay: @Composable (Modifier) -> Unit = {}, + debugVisibilityWrapper: @Composable (@Composable () -> Unit) -> Unit = { it() }, + screenFlashOverlay: @Composable (Modifier) -> Unit = {} +) { + SideRailCaptureScaffold( + slots = slots, + viewfinder = viewfinder, + modifier = modifier, + snackbarHostState = snackbarHostState, + isCompactHeight = false, + chromePadding = TwoSideRailTokens.StandardChromePadding, + topOverlayHorizontalClearance = TwoSideRailTokens.StandardTopOverlayHorizontalClearance, + quickSettingsCardMaxWidth = TwoSideRailTokens.QuickSettingsCardMaxWidth, + quickSettingsCardMaxHeight = Dp.Unspecified, + isQuickSettingsOpen = isQuickSettingsOpen, + isRecording = isRecording, + isErrorDialogShowing = isErrorDialogShowing, + tagQuickSettingsCard = tagQuickSettingsCard, + onDismissQuickSettings = onDismissQuickSettings, + debugOverlay = debugOverlay, + debugVisibilityWrapper = debugVisibilityWrapper, + screenFlashOverlay = screenFlashOverlay + ) +} + +/** + * Shared full-bleed viewfinder and dual-rail capture scaffold backing [TwoSideRailLayout] and + * [WideShortLayout]. + */ +@Composable +internal fun SideRailCaptureScaffold( + slots: CaptureSlots, + viewfinder: @Composable (Modifier) -> Unit, + modifier: Modifier, + snackbarHostState: SnackbarHostState, + isCompactHeight: Boolean, + chromePadding: Dp, + topOverlayHorizontalClearance: Dp, + quickSettingsCardMaxWidth: Dp, + quickSettingsCardMaxHeight: Dp, + isQuickSettingsOpen: Boolean, + isRecording: Boolean, + isErrorDialogShowing: Boolean, + tagQuickSettingsCard: Boolean, + onDismissQuickSettings: () -> Unit, + debugOverlay: @Composable (Modifier) -> Unit, + debugVisibilityWrapper: @Composable (@Composable () -> Unit) -> Unit, + screenFlashOverlay: @Composable (Modifier) -> Unit +) { + val overlapTargetBounds = remember { mutableStateOf(Rect.Zero) } + val localeDirection = LocalLayoutDirection.current + val rtlPolicy = LocalCaptureRtlPolicy.current + val railContainerDirection = if (rtlPolicy.mirrorSideRails) { + localeDirection + } else { + LayoutDirection.Ltr + } + val isModalOpen = isQuickSettingsOpen || isErrorDialogShowing + val liveSafeInsets = WindowInsets.systemBars.union(WindowInsets.displayCutout) + val dismissQuickSettingsLabel = + stringResource(R.string.quick_settings_btn_close_expanded_settings_description) + + BackHandler(enabled = isQuickSettingsOpen, onBack = onDismissQuickSettings) + + CompositionLocalProvider(LocalOverlapTargetBounds provides overlapTargetBounds) { + 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) + ) { + debugVisibilityWrapper { + CompositionLocalProvider(LocalLayoutDirection provides railContainerDirection) { + Box(modifier = Modifier.fillMaxSize()) { + Box( + modifier = Modifier + .align(Alignment.CenterStart) + .fillMaxHeight() + .suppressBackgroundForModal(isModalOpen) + ) { + CompositionLocalProvider( + LocalLayoutDirection provides localeDirection + ) { + StartSideRail( + slots = slots, + modifier = Modifier.fillMaxHeight(), + isCompactHeight = isCompactHeight, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings + ) + } + } + + Box( + modifier = Modifier + .align(Alignment.CenterEnd) + .fillMaxHeight() + .suppressBackgroundForModal(isModalOpen) + ) { + CompositionLocalProvider( + LocalLayoutDirection provides localeDirection + ) { + EndSideRail( + slots = slots, + modifier = Modifier.fillMaxHeight(), + isCompactHeight = isCompactHeight, + isRecording = isRecording, + showElapsedTimeInRail = false, + onDismissQuickSettings = onDismissQuickSettings + ) + } + } + } + } + + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + Box( + modifier = Modifier + .fillMaxSize() + .padding(horizontal = topOverlayHorizontalClearance) + ) { + OverlapAwareCaptureSlot( + modifier = Modifier + .align(Alignment.TopStart) + .padding(top = chromePadding) + .suppressBackgroundForModal(isQuickSettingsOpen), + orientation = Orientation.Horizontal, + isCompact = isCompactHeight, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings, + content = slots.viewfinderTopStart + ) + + OverlapAwareCaptureSlot( + modifier = Modifier + .align(Alignment.TopEnd) + .padding(top = chromePadding) + .suppressBackgroundForModal(isModalOpen), + orientation = Orientation.Horizontal, + isCompact = isCompactHeight, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings, + content = slots.viewfinderTopEnd + ) + } + + Column( + modifier = Modifier + .align(Alignment.TopCenter) + .padding(top = chromePadding) + .suppressBackgroundForModal(isModalOpen), + horizontalAlignment = Alignment.CenterHorizontally + ) { + PillSnackbarHost(snackbarHostState = snackbarHostState) + OverlapAwareCaptureSlot( + orientation = Orientation.Horizontal, + isCompact = isCompactHeight, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings, + content = slots.elapsedTimeDisplay + ) + } + + OverlapAwareCaptureSlot( + modifier = Modifier + .align(Alignment.BottomCenter) + .padding(bottom = chromePadding) + .suppressBackgroundForModal(isModalOpen), + orientation = Orientation.Horizontal, + isCompact = isCompactHeight, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings, + content = slots.captureModeCarousel + ) + } + } + + Box( + modifier = Modifier + .fillMaxSize() + .suppressBackgroundForModal(isModalOpen) + ) { + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + slots.snackBar(Modifier, snackbarHostState) + } + } + } + + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + debugOverlay(Modifier) + } + + if (isQuickSettingsOpen) { + Box( + modifier = Modifier + .fillMaxSize() + .background(TwoSideRailTokens.QuickSettingsScrimColor) + .testTag(QUICK_SETTINGS_SCRIM) + .clickable( + onClickLabel = dismissQuickSettingsLabel, + interactionSource = remember { MutableInteractionSource() }, + indication = null, + onClick = onDismissQuickSettings + ) + ) + + val quickSettingsAlignment = if (rtlPolicy.mirrorSideRails) { + Alignment.BottomStart + } else { + AbsoluteAlignment.BottomLeft + } + val cardTagModifier = if (tagQuickSettingsCard) { + Modifier.testTag(QUICK_SETTINGS_BOTTOM_SHEET) + } else { + Modifier + } + val cardHeightModifier = if (quickSettingsCardMaxHeight != Dp.Unspecified) { + Modifier.heightIn(max = quickSettingsCardMaxHeight) + } else { + Modifier + } + + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + Box( + modifier = Modifier + .fillMaxSize() + .windowInsetsPadding(liveSafeInsets) + .padding(chromePadding) + ) { + Surface( + modifier = Modifier + .align(quickSettingsAlignment) + .then(cardTagModifier) + .widthIn(max = quickSettingsCardMaxWidth) + .then(cardHeightModifier) + .pointerInput(Unit) { + detectTapGestures { /* Consume card taps */ } + }, + shape = RoundedCornerShape( + TwoSideRailTokens.QuickSettingsCardCornerRadius + ), + color = MaterialTheme.colorScheme.surfaceContainerLow, + tonalElevation = TwoSideRailTokens.QuickSettingsCardTonalElevation + ) { + CompositionLocalProvider( + LocalLayoutDirection provides localeDirection + ) { + OverlapAwareCaptureSlot( + orientation = Orientation.Vertical, + isCompact = isCompactHeight, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings, + content = slots.quickSettingsOverlay + ) + } + } + } + } + } + + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + 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) + } + } +} + +@Preview( + name = "TwoSideRail - Foldable Unfolded (852x883dp)", + device = "spec:width=852dp,height=883dp", + showBackground = true +) +@Composable +private fun TwoSideRailFoldablePreview() { + MaterialTheme { + TwoSideRailLayout( + slots = PlaceholderCaptureSlots.sideRail(includeElapsedTime = true), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) } + ) + } +} + +@Preview( + name = "TwoSideRail - Tablet Landscape (1280x800dp)", + device = "spec:width=1280dp,height=800dp", + showBackground = true +) +@Composable +private fun TwoSideRailTabletLandscapePreview() { + MaterialTheme { + TwoSideRailLayout( + slots = PlaceholderCaptureSlots.sideRail( + includePauseSlot = true, + includeElapsedTime = true + ), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + isRecording = true + ) + } +} + +@Preview( + name = "TwoSideRail - Tablet Portrait (800x1280dp)", + device = "spec:width=800dp,height=1280dp", + showBackground = true +) +@Composable +private fun TwoSideRailTabletPortraitPreview() { + MaterialTheme { + TwoSideRailLayout( + slots = PlaceholderCaptureSlots.sideRail(includeElapsedTime = true), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) } + ) + } +} + +@Preview( + name = "TwoSideRail - RTL Default Policy (Unmirrored Rails)", + device = "spec:width=1280dp,height=800dp", + locale = "ar", + showBackground = true +) +@Composable +private fun TwoSideRailRtlDefaultPolicyPreview() { + MaterialTheme { + CompositionLocalProvider( + LocalCaptureRtlPolicy provides CaptureRtlPolicy(mirrorSideRails = false) + ) { + TwoSideRailLayout( + slots = PlaceholderCaptureSlots.sideRail(includeElapsedTime = true), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + isQuickSettingsOpen = true + ) + } + } +} + +@Preview( + name = "TwoSideRail - RTL Mirrored Policy", + device = "spec:width=1280dp,height=800dp", + locale = "ar", + showBackground = true +) +@Composable +private fun TwoSideRailRtlMirroredPolicyPreview() { + MaterialTheme { + CompositionLocalProvider( + LocalCaptureRtlPolicy provides CaptureRtlPolicy(mirrorSideRails = true) + ) { + TwoSideRailLayout( + slots = PlaceholderCaptureSlots.sideRail(includeElapsedTime = true), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + isQuickSettingsOpen = true + ) + } + } +} diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/WideShortLayout.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/WideShortLayout.kt new file mode 100644 index 000000000..02f818855 --- /dev/null +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/WideShortLayout.kt @@ -0,0 +1,482 @@ +/* + * 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.SnackbarHostState +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 WideShortTokens { + val ZeroSize = 0.dp + val CondensedChromePadding = 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 windows (< 480dp, e.g. 800x400dp or + // 360x360dp 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 SHUTTER_STACK_HEIGHT_FRACTION = 0.78f + const val CENTER_HUD_HEIGHT_FRACTION = 0.12f +} + +/** + * Condensed-height side-rail capture layout for short windows (`heightDp < 480.dp`, covering both + * `WIDE_SHORT` landscape/split-screen postures such as `800x400dp` and `COMPACT_SHORT` square + * multi-window panes such as `360x360dp`). + * + * 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, and delegates to [StartSideRail] and [EndSideRail] with + * `isCompactHeight = true`, `showElapsedTimeInRail = false`, condensed `8.dp` chrome padding, + * scoped [LocalCaptureRtlPolicy] (`mirrorSideRails`), and an in-hierarchy floating Quick Settings + * card. + * + * @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 snackbarHostState [SnackbarHostState] driving the top-center [PillSnackbarHost] and passed + * to [CaptureSlots.snackBar]. + * @param isQuickSettingsOpen Whether the in-hierarchy Quick Settings scrim and floating card are + * displayed. + * @param isRecording Whether an active video recording session is in progress. + * @param isErrorDialogShowing Whether a modal camera error dialog is currently visible above the + * capture chrome. + * @param tagQuickSettingsCard Whether the outer floating Quick Settings card carries + * [QUICK_SETTINGS_BOTTOM_SHEET]; defaults to `true`. + * @param onDismissQuickSettings Callback invoked on scrim tap, system back press while Quick + * Settings is open, or [CaptureSlotScope.dismissQuickSettings]. + * @param debugOverlay Untouched pass-through composable for debug UI overlays. + * @param debugVisibilityWrapper Wrapper conditionally hiding camera chrome when debug component + * hiding is enabled. + * @param screenFlashOverlay Full-bleed screen flash composable drawn above all chrome and system + * bar areas. + */ +@Composable +fun WideShortLayout( + slots: CaptureSlots, + viewfinder: @Composable (Modifier) -> Unit, + modifier: Modifier = Modifier, + snackbarHostState: SnackbarHostState = remember { SnackbarHostState() }, + isQuickSettingsOpen: Boolean = false, + isRecording: Boolean = false, + isErrorDialogShowing: Boolean = false, + tagQuickSettingsCard: Boolean = true, + onDismissQuickSettings: () -> Unit = {}, + debugOverlay: @Composable (Modifier) -> Unit = {}, + debugVisibilityWrapper: @Composable (@Composable () -> Unit) -> Unit = { it() }, + 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(WideShortTokens.ZeroSize) + val availableHeight = (maxHeight - verticalInsets).coerceAtLeast(WideShortTokens.ZeroSize) + + val railSlotMaxWidth = min( + CaptureSlotTokens.ModeToggleCompactWidth, + (availableWidth * WideShortTokens.RAIL_WIDTH_FRACTION) + .coerceAtLeast(WideShortTokens.MinRailSlotWidthFloor) + ) + val estimatedRailFootprint = railSlotMaxWidth + WideShortTokens.RailHorizontalPaddingTotal + val condensedSlots = remember(slots, availableWidth, availableHeight) { + slots.withCondensedSizeCaps( + availableWidth = availableWidth, + availableHeight = availableHeight, + railSlotMaxWidth = railSlotMaxWidth, + estimatedRailFootprint = estimatedRailFootprint + ) + } + val cardMaxWidth = min( + WideShortTokens.QuickSettingsCardMaxWidth, + (availableWidth - WideShortTokens.CondensedChromePadding * 2) + .coerceAtLeast(WideShortTokens.ZeroSize) + ) + val cardMaxHeight = (availableHeight - WideShortTokens.CondensedChromePadding * 2) + .coerceAtLeast(WideShortTokens.ZeroSize) + + SideRailCaptureScaffold( + slots = condensedSlots, + viewfinder = viewfinder, + modifier = Modifier.fillMaxSize(), + snackbarHostState = snackbarHostState, + isCompactHeight = true, + chromePadding = WideShortTokens.CondensedChromePadding, + topOverlayHorizontalClearance = estimatedRailFootprint, + quickSettingsCardMaxWidth = cardMaxWidth, + quickSettingsCardMaxHeight = cardMaxHeight, + isQuickSettingsOpen = isQuickSettingsOpen, + isRecording = isRecording, + isErrorDialogShowing = isErrorDialogShowing, + tagQuickSettingsCard = tagQuickSettingsCard, + onDismissQuickSettings = onDismissQuickSettings, + debugOverlay = debugOverlay, + debugVisibilityWrapper = debugVisibilityWrapper, + screenFlashOverlay = screenFlashOverlay + ) + } +} + +private fun CaptureSlots.withCondensedSizeCaps( + availableWidth: Dp, + availableHeight: Dp, + railSlotMaxWidth: Dp, + estimatedRailFootprint: Dp +): CaptureSlots { + val innerRailHeight = (availableHeight - WideShortTokens.RailTotalVerticalPadding) + .coerceAtLeast(WideShortTokens.ZeroSize) + + val indicatorMaxHeight = min( + CaptureSlotTokens.IndicatorCompactMainAxisSize, + innerRailHeight * WideShortTokens.INDICATOR_MAX_HEIGHT_FRACTION + ) + val zoomMaxHeight = min( + CaptureSlotTokens.ZoomCompactMainAxisSize, + innerRailHeight * WideShortTokens.ZOOM_MAX_HEIGHT_FRACTION + ) + val quickSettingsButtonMaxSize = min( + min( + CaptureSlotTokens.IconTouchTargetSize, + innerRailHeight * WideShortTokens.QUICK_SETTINGS_BUTTON_FRACTION + ), + railSlotMaxWidth + ) + val shutterMaxDiameter = min( + min( + CaptureSlotTokens.ShutterCompactDiameter, + innerRailHeight * WideShortTokens.SHUTTER_DIAMETER_FRACTION + ), + railSlotMaxWidth + ) + val secondaryActionMaxSize = min( + min( + CaptureSlotTokens.SecondaryActionCompactSize, + innerRailHeight * WideShortTokens.SECONDARY_ACTION_FRACTION + ), + railSlotMaxWidth + ) + val modeToggleMaxHeight = min( + CaptureSlotTokens.ModeToggleCompactHeight, + innerRailHeight * WideShortTokens.MODE_TOGGLE_HEIGHT_FRACTION + ) + val shutterStackMaxHeight = innerRailHeight * WideShortTokens.SHUTTER_STACK_HEIGHT_FRACTION + + val centerHudMaxWidth = (availableWidth - estimatedRailFootprint * 2) + .coerceAtLeast(WideShortTokens.MinCenterHudWidthFloor) + val centerHudMaxHeight = min( + CaptureSlotTokens.HorizontalTopBarHeight, + innerRailHeight * WideShortTokens.CENTER_HUD_HEIGHT_FRACTION + ) + val cardInnerMaxWidth = min( + WideShortTokens.QuickSettingsCardMaxWidth, + (availableWidth - WideShortTokens.CondensedChromePadding * 2) + .coerceAtLeast(WideShortTokens.ZeroSize) + ) + val cardInnerMaxHeight = (availableHeight - WideShortTokens.CondensedChromePadding * 2) + .coerceAtLeast(WideShortTokens.ZeroSize) + + val original = this + val originalShutterStack = original.shutterStack + + return original.copy( + indicatorColumn = { mod -> + ConstrainedSlot( + modifier = mod, + maxWidth = railSlotMaxWidth, + maxHeight = indicatorMaxHeight, + slot = original.indicatorColumn + ) + }, + 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 + ) + }, + pauseToggleButton = { mod -> + ConstrainedSlot( + modifier = mod, + maxWidth = secondaryActionMaxSize, + maxHeight = secondaryActionMaxSize, + slot = original.pauseToggleButton + ) + }, + audioToggleButton = { mod -> + ConstrainedSlot( + modifier = mod, + maxWidth = secondaryActionMaxSize, + maxHeight = secondaryActionMaxSize, + slot = original.audioToggleButton + ) + }, + shutterStack = if (originalShutterStack != null) { + { mod, _ -> + ConstrainedSlot( + modifier = mod, + maxWidth = railSlotMaxWidth, + maxHeight = shutterStackMaxHeight + ) { cappedMod -> + originalShutterStack(cappedMod, true) + } + } + } else { + null + }, + 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 + ) + }, + viewfinderTopStart = { mod -> + ConstrainedSlot( + modifier = mod, + maxWidth = centerHudMaxWidth, + maxHeight = secondaryActionMaxSize, + slot = original.viewfinderTopStart + ) + }, + viewfinderTopEnd = { mod -> + ConstrainedSlot( + modifier = mod, + maxWidth = centerHudMaxWidth, + maxHeight = secondaryActionMaxSize, + slot = original.viewfinderTopEnd + ) + }, + quickSettingsOverlay = { mod -> + ConstrainedSlot( + modifier = mod, + maxWidth = cardInnerMaxWidth, + maxHeight = cardInnerMaxHeight, + slot = original.quickSettingsOverlay + ) + } + ) +} + +@Composable +private fun CaptureSlotScope.ConstrainedSlot( + modifier: Modifier, + maxWidth: Dp, + maxHeight: Dp, + slot: @Composable CaptureSlotScope.(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 = "WideShort - Landscape (800x400dp)", + device = "spec:width=800dp,height=400dp", + showBackground = true +) +@Composable +private fun WideShortLandscapePreview() { + MaterialTheme { + WideShortLayout( + slots = PlaceholderCaptureSlots.sideRail( + isCompactHeight = true, + includePauseSlot = true, + includeElapsedTime = true + ), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + isRecording = true + ) + } +} + +@Preview( + name = "CompactShort - Multi-Window Square (360x360dp)", + device = "spec:width=360dp,height=360dp", + showBackground = true +) +@Composable +private fun CompactShortSquarePreview() { + MaterialTheme { + WideShortLayout( + slots = PlaceholderCaptureSlots.sideRail( + isCompactHeight = true, + includePauseSlot = true, + includeElapsedTime = true + ), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + isRecording = true + ) + } +} + +@Preview( + name = "WideShort - RTL Default Policy (800x400dp)", + device = "spec:width=800dp,height=400dp", + locale = "ar", + showBackground = true +) +@Composable +private fun WideShortRtlDefaultPolicyPreview() { + MaterialTheme { + CompositionLocalProvider( + LocalCaptureRtlPolicy provides CaptureRtlPolicy(mirrorSideRails = false) + ) { + WideShortLayout( + slots = PlaceholderCaptureSlots.sideRail( + isCompactHeight = true, + includeElapsedTime = true + ), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) } + ) + } + } +} + +@Preview( + name = "WideShort - RTL Mirrored Policy (800x400dp)", + device = "spec:width=800dp,height=400dp", + locale = "ar", + showBackground = true +) +@Composable +private fun WideShortRtlMirroredPolicyPreview() { + MaterialTheme { + CompositionLocalProvider( + LocalCaptureRtlPolicy provides CaptureRtlPolicy(mirrorSideRails = true) + ) { + WideShortLayout( + slots = PlaceholderCaptureSlots.sideRail( + isCompactHeight = true, + includeElapsedTime = true + ), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) } + ) + } + } +} diff --git a/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/TwoSideRailLayoutTest.kt b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/TwoSideRailLayoutTest.kt new file mode 100644 index 000000000..bf52e03a2 --- /dev/null +++ b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/TwoSideRailLayoutTest.kt @@ -0,0 +1,655 @@ +/* + * 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.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.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.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 [TwoSideRailLayout] and [CompactPortraitLayout] verifying full-bleed viewfinder + * geometry, [CaptureRtlPolicy] hand-placement vs. mirrored modes, live multi-window `statusBars` + * clearance, and in-hierarchy Quick Settings card behavior. + */ +@RunWith(RobolectricTestRunner::class) +@Config(qualifiers = "w852dp-h883dp") +class TwoSideRailLayoutTest { + + @get:Rule + val composeTestRule = createComposeRule() + + private fun boundsOf(tag: String): DpRect = + composeTestRule.onNodeWithTag(tag).getUnclippedBoundsInRoot() + + @Test + fun twoSideRailLayout_viewfinderIsFlushTopToBottom_andSideRailsOverlayEdges() { + var observedSolverSolution: CameraLayoutSolution? = null + + composeTestRule.setContent { + MaterialTheme { + TwoSideRailLayout( + slots = PlaceholderCaptureSlots.sideRail(includeElapsedTime = true), + viewfinder = { vfModifier -> + observedSolverSolution = LocalCameraLayoutSolution.current + Box( + modifier = vfModifier.testTag(PREVIEW_DISPLAY), + contentAlignment = Alignment.Center + ) { + Box( + modifier = Modifier + .aspectRatio(1f) + .testTag(SQUARE_PREVIEW_FRAME_TAG) + ) + } + } + ) + } + } + composeTestRule.waitForIdle() + + // Rail mode must not provide a portrait CameraLayoutSolver solution. + assertThat(observedSolverSolution).isNull() + + 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) + + // A 1:1 preview frame centers naturally inside the full-bleed background container. + val squareBounds = boundsOf(SQUARE_PREVIEW_FRAME_TAG) + val squareCenterY = (squareBounds.top.value + squareBounds.bottom.value) / 2f + assertThat(squareCenterY).isWithin(TOLERANCE).of(883f / 2f) + + // Start and End rails overlay the horizontal edges cleanly. + 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) + + // Elapsed time and capture mode carousel sit at the top/bottom center HUD rather than in + // EndSideRail. + 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 = "w1280dp-h800dp") + @Test + fun twoSideRailLayout_rtlPolicies_scopeRailPlacementAndRestoreLocaleDirectionInSlots() { + var layoutDirection by mutableStateOf(LayoutDirection.Ltr) + var rtlPolicy by mutableStateOf(CaptureRtlPolicy(mirrorSideRails = false)) + + val observedDirections = mutableMapOf() + val baseSlots = PlaceholderCaptureSlots.sideRail( + includeImageWell = true, + includePauseSlot = true, + includeElapsedTime = true + ) + val instrumentedSlots = baseSlots.copy( + indicatorColumn = { mod -> + observedDirections["indicatorColumn"] = LocalLayoutDirection.current + baseSlots.indicatorColumn(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) + }, + 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 + ) { + TwoSideRailLayout( + slots = instrumentedSlots, + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + isRecording = true + ) + } + } + } + composeTestRule.waitForIdle() + + 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, + AUDIO_INPUT_TOGGLE, + 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 preserve physical grip sides, + // while every inner slot receives LayoutDirection.Rtl! + observedDirections.clear() + layoutDirection = LayoutDirection.Rtl + rtlPolicy = CaptureRtlPolicy(mirrorSideRails = false, mirrorCompactBottomBar = 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(1280f) + 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 and EndSideRail swap + // horizontal sides while vertical Top -> Bottom order remains invariant! + observedDirections.clear() + rtlPolicy = CaptureRtlPolicy(mirrorSideRails = true, mirrorCompactBottomBar = true) + composeTestRule.waitForIdle() + + assertThat(boundsOf(START_SIDE_RAIL_TAG).right.value).isWithin(TOLERANCE).of(1280f) + assertThat(boundsOf(END_SIDE_RAIL_TAG).left.value).isWithin(TOLERANCE).of(0f) + 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)) + 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 -> PlaceholderViewfinder(modifier = mod) } + ) + } + } + } + composeTestRule.waitForIdle() + + 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 } + + // Default RTL policy: bottom rows stay unmirrored (ImageWell left, Flip right, Quick + // Settings left) while every child slot receives LayoutDirection.Rtl! + 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]) + } + + // Mirrored RTL policy: CaptureRow and BottomToolbar reflect horizontally while vertical + // Top -> Bottom order remains invariant! + 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 twoSideRailLayout_statusBarsInsets_clearsVisibleBarAndZeroPadsWhenHidden() { + lateinit var hostView: View + composeTestRule.setContent { + hostView = LocalView.current + MaterialTheme { + TwoSideRailLayout( + slots = PlaceholderCaptureSlots.sideRail(includeElapsedTime = true), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + screenFlashOverlay = { mod -> + Box(modifier = mod.fillMaxSize().testTag(SCREEN_FLASH_OVERLAY)) + } + ) + } + } + + // 1. Multi-window visible status bar (32px == 32dp at Robolectric default mdpi): + // rails and indicators clear >= 32dp while viewfinder and screen flash stay full-bleed. + 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) + + // 2. Immersive hidden status bar (0px live, 32px ignoring visibility): + // live WindowInsets.systemBars must collapse rail top offset to 0dp! + 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) + } + + @Config(qualifiers = "w1280dp-h800dp") + @Test + fun twoSideRailLayout_quickSettingsFloatingCard_isInHierarchyAndDismissesOnScrimClick() { + var isQuickSettingsOpen by mutableStateOf(false) + var overlayDirection: LayoutDirection? = null + var rtlPolicy by mutableStateOf(CaptureRtlPolicy(mirrorSideRails = false)) + + val baseSlots = PlaceholderCaptureSlots.default() + val instrumentedSlots = baseSlots.copy( + quickSettingsOverlay = { mod -> + overlayDirection = LocalLayoutDirection.current + baseSlots.quickSettingsOverlay(this, mod) + } + ) + + composeTestRule.setContent { + MaterialTheme { + CompositionLocalProvider( + LocalLayoutDirection provides LayoutDirection.Rtl, + LocalCaptureRtlPolicy provides rtlPolicy + ) { + TwoSideRailLayout( + slots = instrumentedSlots, + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + isQuickSettingsOpen = isQuickSettingsOpen, + onDismissQuickSettings = { isQuickSettingsOpen = false } + ) + } + } + } + composeTestRule.waitForIdle() + + composeTestRule.onNodeWithTag(QUICK_SETTINGS_BOTTOM_SHEET).assertDoesNotExist() + composeTestRule.onNodeWithTag(QUICK_SETTINGS_SCRIM).assertDoesNotExist() + composeTestRule.onNodeWithTag(CAPTURE_BUTTON).assertIsDisplayed() + + // Open Quick Settings floating card. + isQuickSettingsOpen = true + composeTestRule.waitForIdle() + + composeTestRule.onNodeWithTag(QUICK_SETTINGS_BOTTOM_SHEET) + .assertIsDisplayed() + .assert(!isPopup()) + .assert(!isDialog()) + .assert(!hasAnyAncestor(isPopup())) + .assert(!hasAnyAncestor(isDialog())) + assertThat(overlayDirection).isEqualTo(LayoutDirection.Rtl) + + // Default RTL policy anchors the floating card to BottomLeft matching StartSideRail. + val unmirroredCardBounds = boundsOf(QUICK_SETTINGS_BOTTOM_SHEET) + assertThat(unmirroredCardBounds.right.value).isLessThan(1280f / 2f) + + // Mirrored RTL policy anchors the floating card to BottomStart (physical right in RTL). + rtlPolicy = CaptureRtlPolicy(mirrorSideRails = true) + composeTestRule.waitForIdle() + val mirroredCardBounds = boundsOf(QUICK_SETTINGS_BOTTOM_SHEET) + assertThat(mirroredCardBounds.left.value).isGreaterThan(1280f / 2f) + + // Background camera chrome semantics are suppressed while modal card is open. + assertThat( + composeTestRule.onAllNodesWithTag(CAPTURE_BUTTON).fetchSemanticsNodes() + ).isEmpty() + + // Clicking the scrim dismisses Quick Settings and restores background semantics. + composeTestRule.onNodeWithTag(QUICK_SETTINGS_SCRIM) + .assertIsDisplayed() + .performClick() + composeTestRule.waitForIdle() + + assertThat(isQuickSettingsOpen).isFalse() + composeTestRule.onNodeWithTag(QUICK_SETTINGS_BOTTOM_SHEET).assertDoesNotExist() + composeTestRule.onNodeWithTag(CAPTURE_BUTTON).assertIsDisplayed() + } + + @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() + + // Default policy in VerticalMaterialControls fallback keeps ImageWell left and Flip right. + 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) + + // Mirrored policy reflects horizontal placement in VerticalMaterialControls fallback. + 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) + + // Visible multi-window status bar clears indicatorRow in non-handheld fallback too. + 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 twoSideRailLayout_tagQuickSettingsCardFalse_avoidsDuplicateSheetTagsAndErrorSuppressesBg() { + var isQuickSettingsOpen by mutableStateOf(true) + var isErrorDialogShowing by mutableStateOf(false) + + val slotsWithInnerSheetTag = PlaceholderCaptureSlots.sideRail( + tagQuickSettingsOverlay = true, + includeErrorDialog = true + ) + + composeTestRule.setContent { + MaterialTheme { + TwoSideRailLayout( + slots = slotsWithInnerSheetTag, + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + isQuickSettingsOpen = isQuickSettingsOpen, + isErrorDialogShowing = isErrorDialogShowing, + tagQuickSettingsCard = false, + onDismissQuickSettings = { isQuickSettingsOpen = false } + ) + } + } + composeTestRule.waitForIdle() + + // Exactly one QUICK_SETTINGS_BOTTOM_SHEET node exists (owned by inner overlay). + assertThat( + composeTestRule.onAllNodesWithTag(QUICK_SETTINGS_BOTTOM_SHEET).fetchSemanticsNodes() + ).hasSize(1) + + // Close Quick Settings and show error dialog: background controls are suppressed while + // CAMERA_ERROR_DIALOG_TAG is displayed. + isQuickSettingsOpen = false + isErrorDialogShowing = true + composeTestRule.waitForIdle() + + composeTestRule.onNodeWithTag(CAMERA_ERROR_DIALOG_TAG).assertIsDisplayed() + assertThat( + composeTestRule.onAllNodesWithTag(CAPTURE_BUTTON).fetchSemanticsNodes() + ).isEmpty() + } + + 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 + } +} diff --git a/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/WideShortLayoutTest.kt b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/WideShortLayoutTest.kt new file mode 100644 index 000000000..c1deaa9e4 --- /dev/null +++ b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/WideShortLayoutTest.kt @@ -0,0 +1,413 @@ +/* + * 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.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.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.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.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 [WideShortLayout] across `WIDE_SHORT` (`800x400dp`), `COMPACT_SHORT` + * (`360x360dp`), RTL policies, and visible multi-window `statusBars` insets, asserting zero + * clipping and zero vertical overlap in both rails. + */ +@RunWith(RobolectricTestRunner::class) +@Config(qualifiers = "w800dp-h400dp") +class WideShortLayoutTest { + + @get:Rule + val composeTestRule = createComposeRule() + + private fun boundsOf(tag: String): DpRect = + composeTestRule.onNodeWithTag(tag).getUnclippedBoundsInRoot() + + @Test + fun wideShortLayout_at800x400_fitsAllControlsWithoutClippingOrVerticalOverlap() { + composeTestRule.setContent { + MaterialTheme { + WideShortLayout( + slots = PlaceholderCaptureSlots.sideRail( + isCompactHeight = false, + includeImageWell = true, + includePauseSlot = true, + includeElapsedTime = true + ), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + isRecording = true + ) + } + } + composeTestRule.waitForIdle() + + 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(800f) + assertThat(viewfinderBounds.bottom.value).isWithin(TOLERANCE).of(400f) + + assertNoClippingAndNoOverlapInWindow( + contextLabel = "WIDE_SHORT 800x400", + windowWidth = 800f, + windowHeight = 400f, + minTop = 0f + ) + } + + @Config(qualifiers = "w360dp-h360dp") + @Test + fun wideShortLayout_at360x360_fitsAllControlsWithoutClippingOrVerticalOverlap() { + composeTestRule.setContent { + MaterialTheme { + WideShortLayout( + slots = PlaceholderCaptureSlots.sideRail( + isCompactHeight = false, + includeImageWell = true, + includePauseSlot = true, + includeElapsedTime = true + ), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + isRecording = true + ) + } + } + composeTestRule.waitForIdle() + + val viewfinderBounds = boundsOf(PREVIEW_DISPLAY) + assertThat(viewfinderBounds.top.value).isWithin(TOLERANCE).of(0f) + assertThat(viewfinderBounds.bottom.value).isWithin(TOLERANCE).of(360f) + + assertNoClippingAndNoOverlapInWindow( + contextLabel = "COMPACT_SHORT 360x360", + windowWidth = 360f, + windowHeight = 360f, + minTop = 0f + ) + + // StartSideRail, center HUD, and EndSideRail must not horizontally collide even at 360dp. + 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) + } + + @Test + fun wideShortLayout_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, + includePauseSlot = true, + includeElapsedTime = true + ) + val instrumentedSlots = baseSlots.copy( + indicatorColumn = { mod -> + observedDirections["indicatorColumn"] = LocalLayoutDirection.current + baseSlots.indicatorColumn(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 + ) { + WideShortLayout( + slots = instrumentedSlots, + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + isRecording = true + ) + } + } + } + composeTestRule.waitForIdle() + + val ltrStartTops = START_RAIL_TAGS.map { boundsOf(it).top.value } + val ltrEndTops = END_RAIL_TAGS.map { boundsOf(it).top.value } + + // Default RTL policy: rails stay on physical left/right while child slots observe RTL. + 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(800f) + 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]) + } + + // Mirrored RTL policy: rails swap horizontally while vertical bounds stay identical. + observedDirections.clear() + rtlPolicy = CaptureRtlPolicy(mirrorSideRails = true) + composeTestRule.waitForIdle() + + assertThat(boundsOf(START_SIDE_RAIL_TAG).right.value).isWithin(TOLERANCE).of(800f) + assertThat(boundsOf(END_SIDE_RAIL_TAG).left.value).isWithin(TOLERANCE).of(0f) + assertNoClippingAndNoOverlapInWindow( + contextLabel = "WIDE_SHORT 800x400 RTL Mirrored", + windowWidth = 800f, + 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]) + } + } + + @Config(qualifiers = "w360dp-h360dp") + @Test + fun wideShortLayout_withMultiWindowVisibleStatusBars_clearsBarAndFits360x360WithoutOverlap() { + lateinit var hostView: View + composeTestRule.setContent { + hostView = LocalView.current + MaterialTheme { + WideShortLayout( + slots = PlaceholderCaptureSlots.sideRail( + isCompactHeight = false, + includeImageWell = true, + includePauseSlot = true, + includeElapsedTime = true + ), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + isRecording = true + ) + } + } + + dispatchStatusBarInsets( + view = hostView, + statusBarHeightPx = MULTI_WINDOW_STATUS_BAR_PX, + visible = true + ) + composeTestRule.waitForIdle() + + // Viewfinder stays flush [0..360] while rails and all child slots fit in [32..360] with + // zero clipping and zero vertical overlap! + 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 + ) + + // Hiding the status bar collapses rail top padding back to 0dp. + 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) + } + + @Config(qualifiers = "w360dp-h360dp") + @Test + fun wideShortLayout_quickSettingsFloatingCard_displaysInHierarchyWithinCondensedBounds() { + var isQuickSettingsOpen by mutableStateOf(true) + composeTestRule.setContent { + MaterialTheme { + WideShortLayout( + slots = PlaceholderCaptureSlots.default(), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + isQuickSettingsOpen = isQuickSettingsOpen, + onDismissQuickSettings = { isQuickSettingsOpen = false } + ) + } + } + composeTestRule.waitForIdle() + + composeTestRule.onNodeWithTag(QUICK_SETTINGS_BOTTOM_SHEET) + .assertIsDisplayed() + .assert(!isPopup()) + .assert(!isDialog()) + .assert(!hasAnyAncestor(isPopup())) + .assert(!hasAnyAncestor(isDialog())) + + val cardBounds = boundsOf(QUICK_SETTINGS_BOTTOM_SHEET) + assertThat(cardBounds.left.value).isAtLeast(0f - TOLERANCE) + assertThat(cardBounds.right.value).isAtMost(360f + TOLERANCE) + assertThat(cardBounds.top.value).isAtLeast(0f - TOLERANCE) + assertThat(cardBounds.bottom.value).isAtMost(360f + TOLERANCE) + + composeTestRule.onNodeWithTag(QUICK_SETTINGS_SCRIM).performClick() + composeTestRule.waitForIdle() + assertThat(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, + AUDIO_INPUT_TOGGLE, + 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 + } +} From 066c240256bc324aa51211f3cde5d8c75f51ab99 Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Fri, 6 Nov 2026 05:25:57 -0800 Subject: [PATCH 2/3] feat(ui/capture): add CompactPortraitLayout, TwoSideRailLayout, and WideShortLayout --- .../ui/components/capture/CaptureLayout.kt | 907 +----------- .../capture/CompactPortraitLayout.kt | 1268 +++++++++++++++++ .../components/capture/TwoSideRailLayout.kt | 493 +++++++ .../ui/components/capture/WideShortLayout.kt | 482 +++++++ .../capture/TwoSideRailLayoutTest.kt | 655 +++++++++ .../components/capture/WideShortLayoutTest.kt | 413 ++++++ 6 files changed, 3338 insertions(+), 880 deletions(-) create mode 100644 ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CompactPortraitLayout.kt create mode 100644 ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/TwoSideRailLayout.kt create mode 100644 ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/WideShortLayout.kt create mode 100644 ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/TwoSideRailLayoutTest.kt create mode 100644 ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/WideShortLayoutTest.kt 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 5a2b0afb0..f7b8e1d6f 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CaptureLayout.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CaptureLayout.kt @@ -15,133 +15,12 @@ */ 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.BottomSheetScaffoldState 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.runtime.Composable -import androidx.compose.runtime.CompositionLocalProvider -import androidx.compose.runtime.DisposableEffect -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 @@ -201,17 +80,11 @@ internal val ViewfinderTopLine = HorizontalAlignmentLine { a, b -> minOf(a, b) } * does not change the system bars itself. * @param errorDialog the camera error alert dialog composable */ -@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) -@Suppress("DEPRECATION") +@OptIn(ExperimentalMaterial3Api::class) @Composable fun PreviewLayout( modifier: Modifier = Modifier, - scaffoldState: BottomSheetScaffoldState = rememberBottomSheetScaffoldState( - bottomSheetState = rememberStandardBottomSheetState( - initialValue = SheetValue.Hidden, - skipHiddenState = false - ) - ), + scaffoldState: BottomSheetScaffoldState = rememberCompactPortraitScaffoldState(), onDismissQuickSettings: () -> Unit = {}, viewfinder: @Composable (Modifier) -> Unit, captureButton: @Composable (Modifier) -> Unit, @@ -234,756 +107,30 @@ fun PreviewLayout( onRequiresImmersiveChange: (Boolean) -> Unit = {}, errorDialog: @Composable (Modifier) -> Unit = {} ) { - val overlapTargetBounds = remember { mutableStateOf(Rect.Zero) } - val dismissQuickSettingsLabel = - stringResource(R.string.quick_settings_btn_close_expanded_settings_description) - - CompositionLocalProvider(LocalOverlapTargetBounds provides overlapTargetBounds) { - Box(modifier = modifier.fillMaxSize()) { - BottomSheetScaffold( - modifier = Modifier.fillMaxSize(), - scaffoldState = scaffoldState, - sheetPeekHeight = 0.dp, - sheetDragHandle = { - BottomSheetDefaults.DragHandle( - modifier = Modifier - .testTag(QUICK_SETTINGS_DRAG_HANDLE) - .clickable( - role = Role.Button, - onClickLabel = dismissQuickSettingsLabel, - onClick = onDismissQuickSettings - ) - ) - }, - 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, - debugVisibilityWrapper = debugVisibilityWrapper, - snackbarHost = { modifier -> - PillSnackbarHost( - snackbarHostState = scaffoldState.snackbarHostState, - modifier = modifier - ) - } - ) - Box( - modifier = Modifier - .fillMaxSize() - .windowInsetsPadding( - WindowInsets.systemBarsIgnoringVisibility - .union(WindowInsets.displayCutout) - ) - ) { - snackBar(Modifier, scaffoldState.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 - ) { - indicatorRow(Modifier) - topBarTrailingContent(Modifier.align(Alignment.CenterEnd)) - } - 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) - ) - ) { - debugVisibilityWrapper { - VerticalMaterialControls( - captureButton = captureButton, - imageWell = imageWell, - flipCameraButton = flipCameraButton, - quickSettingsToggleButton = quickSettingsButton, - captureModeToggleSwitch = captureModeToggle, - captureModeCarousel = captureModeCarousel, - zoomControls = zoomLevelDisplay, - elapsedTimeDisplay = elapsedTimeDisplay, - snackbarHost = { modifier -> - PillSnackbarHost( - snackbarHostState = scaffoldState.snackbarHostState, - modifier = modifier - ) - } - ) - } - snackBar(Modifier, scaffoldState.snackbarHostState) - } - } - debugOverlay(Modifier) - - val isSheetVisible = scaffoldState.bottomSheetState.isVisible || - scaffoldState.bottomSheetState.targetValue == SheetValue.Expanded - if (isSheetVisible) { - Box( - modifier = Modifier - .fillMaxSize() - .testTag(QUICK_SETTINGS_SCRIM) - .clickable( - onClickLabel = dismissQuickSettingsLabel, - interactionSource = remember { MutableInteractionSource() }, - indication = null, - onClick = onDismissQuickSettings - ) - ) - } - 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) -@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 (Modifier) -> Unit, - topBarTrailingContent: @Composable (Modifier) -> Unit, - elapsedTimeDisplay: @Composable (Modifier) -> Unit, - zoomControls: @Composable (Modifier) -> Unit, - imageWell: @Composable (Modifier) -> Unit, - captureButton: @Composable (Modifier) -> Unit, - flipCameraButton: @Composable (Modifier) -> Unit, - captureModeCarousel: @Composable (Modifier) -> Unit, - quickSettingsToggleButton: @Composable (Modifier) -> Unit, - captureModeToggleSwitch: @Composable (Modifier) -> Unit, - debugVisibilityWrapper: (@Composable (@Composable () -> Unit) -> Unit), - 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) - } - } - - Box( - modifier = Modifier - .layoutId(CaptureSlotId.TopBar) - .fillMaxWidth() - .height(topBarHeight) - .windowInsetsPadding( - WindowInsets.displayCutout.only(WindowInsetsSides.Horizontal) - ) - .padding(horizontal = LOWER_SECTION_HORIZONTAL_PADDING), - contentAlignment = Alignment.CenterStart - ) { - indicatorRow(Modifier) - topBarTrailingContent(Modifier.align(Alignment.CenterEnd)) - } - - debugVisibilityWrapper { - Column( - modifier = Modifier.layoutId(CaptureSlotId.ElapsedTime), - horizontalAlignment = Alignment.CenterHorizontally - ) { - snackbarHost(Modifier) - 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()) - ) - 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 (Modifier) -> Unit, - zoomControls: @Composable (Modifier) -> Unit, - imageWell: @Composable (Modifier) -> Unit, - flipCameraButton: @Composable (Modifier) -> Unit, - quickSettingsToggleButton: @Composable (Modifier) -> Unit, - captureModeToggleSwitch: @Composable (Modifier) -> Unit, - captureModeCarousel: @Composable (Modifier) -> Unit = {}, - elapsedTimeDisplay: @Composable (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 - // PreviewLayout), 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) - - 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. - Box( - modifier = Modifier - .fillMaxWidth() - .height(MIDDLE_SLOT_HEIGHT + stackGap * 2), - contentAlignment = Alignment.Center - ) { - OverlapAwareStyleProvider { - captureModeCarousel(Modifier) - } - } - - // bottom controls row - Row( - Modifier - .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)) - } - } - } -} - -@OptIn(ExperimentalMaterial3Api::class) -@PreviewPortraitDevices -@Composable -private fun CaptureLayoutPreview() { - PreviewLayout( - 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) - ) - }, - quickSettingsOverlay = { - // No-op for preview - }, - debugOverlay = { - // No-op for preview - }, - screenFlashOverlay = { - // No-op for preview - }, - snackBar = { _, _ -> - // No-op for preview - }, - debugVisibilityWrapper = { content -> content() } + CompactPortraitLayout( + modifier = modifier, + scaffoldState = scaffoldState, + onDismissQuickSettings = onDismissQuickSettings, + includeStatusBarsInTopBar = false, + viewfinder = viewfinder, + captureButton = captureButton, + imageWell = imageWell, + flipCameraButton = flipCameraButton, + zoomLevelDisplay = zoomLevelDisplay, + elapsedTimeDisplay = elapsedTimeDisplay, + quickSettingsButton = quickSettingsButton, + indicatorRow = indicatorRow, + captureModeToggle = captureModeToggle, + captureModeCarousel = captureModeCarousel, + quickSettingsOverlay = quickSettingsOverlay, + debugOverlay = debugOverlay, + debugVisibilityWrapper = debugVisibilityWrapper, + screenFlashOverlay = screenFlashOverlay, + snackBar = snackBar, + topStartContent = topStartContent, + viewfinderTopEndContent = viewfinderTopEndContent, + topBarTrailingContent = topBarTrailingContent, + onRequiresImmersiveChange = onRequiresImmersiveChange, + errorDialog = errorDialog ) } 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..208f8417d --- /dev/null +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CompactPortraitLayout.kt @@ -0,0 +1,1268 @@ +/* + * 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.BottomSheetScaffoldState +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.rememberBottomSheetState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.DisposableEffect +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.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.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.clearAndSetSemantics +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 + +private 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 +} + +/** + * Remembers a [BottomSheetScaffoldState] configured for [CompactPortraitLayout] and + * [PreviewLayout], backed by the non-deprecated Material 3 [rememberBottomSheetState] API. + * + * @param initialValue Initial [SheetValue] of the Quick Settings bottom sheet; defaults to + * [SheetValue.Hidden]. + * @return A remembered [BottomSheetScaffoldState] supporting hidden, partially expanded, and + * expanded sheet states. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun rememberCompactPortraitScaffoldState( + initialValue: SheetValue = SheetValue.Hidden +): BottomSheetScaffoldState = rememberBottomSheetScaffoldState( + bottomSheetState = rememberBottomSheetState(initialValue = initialValue) +) + +/** + * Suppresses keyboard/rotary focus and accessibility semantics on background camera chrome while an + * in-hierarchy modal surface (such as Quick Settings or an error dialog) is open above it. + */ +internal fun Modifier.suppressBackgroundForModal(isModalOpen: Boolean): Modifier = + if (isModalOpen) { + this + .focusProperties { canFocus = false } + .clearAndSetSemantics {} + } else { + this + } + +/** + * Compact portrait 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 without spawning secondary windows. Tags its root + * container with [COMPACT_CONTROLS_TAG] 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 scaffoldState [BottomSheetScaffoldState] controlling the Quick Settings sheet and snackbar + * host. + * @param isRecording Whether an active video recording session is in progress. + * @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 the user taps the Quick Settings drag handle + * or scrim, or triggers dismissal from a slot. + * @param onRequiresImmersiveChange Callback notified when the portrait layout solver requires or + * releases immersive navigation-bar hiding. + * @param debugOverlay Untouched pass-through composable for debug UI overlays. + * @param debugVisibilityWrapper Wrapper conditionally hiding camera chrome when debug component + * hiding is enabled. + * @param screenFlashOverlay Full-bleed screen flash composable drawn above all chrome and system + * bar areas. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun CompactPortraitLayout( + slots: CaptureSlots, + viewfinder: @Composable (Modifier) -> Unit, + modifier: Modifier = Modifier, + scaffoldState: BottomSheetScaffoldState = rememberCompactPortraitScaffoldState(), + isRecording: Boolean = false, + isErrorDialogShowing: Boolean = false, + includeStatusBarsInTopBar: Boolean = true, + onDismissQuickSettings: () -> Unit = {}, + onRequiresImmersiveChange: (Boolean) -> Unit = {}, + debugOverlay: @Composable (Modifier) -> Unit = {}, + debugVisibilityWrapper: @Composable (@Composable () -> Unit) -> Unit = { it() }, + screenFlashOverlay: @Composable (Modifier) -> Unit = {} +) { + CompactPortraitLayout( + modifier = modifier, + scaffoldState = scaffoldState, + onDismissQuickSettings = onDismissQuickSettings, + isErrorDialogShowing = isErrorDialogShowing, + includeStatusBarsInTopBar = includeStatusBarsInTopBar, + viewfinder = viewfinder, + captureButton = { slotModifier -> + OverlapAwareCaptureSlot( + modifier = slotModifier, + orientation = Orientation.Horizontal, + isCompact = false, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings, + content = slots.captureButton + ) + }, + imageWell = { slotModifier -> + OverlapAwareCaptureSlot( + modifier = slotModifier, + orientation = Orientation.Horizontal, + isCompact = false, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings, + content = slots.imageWell + ) + }, + flipCameraButton = { slotModifier -> + OverlapAwareCaptureSlot( + modifier = slotModifier, + orientation = Orientation.Horizontal, + isCompact = false, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings, + content = slots.flipCameraButton + ) + }, + zoomLevelDisplay = { slotModifier -> + OverlapAwareCaptureSlot( + modifier = slotModifier, + orientation = Orientation.Horizontal, + isCompact = false, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings, + content = slots.zoomControls + ) + }, + elapsedTimeDisplay = { slotModifier -> + OverlapAwareCaptureSlot( + modifier = slotModifier, + orientation = Orientation.Horizontal, + isCompact = false, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings, + content = slots.elapsedTimeDisplay + ) + }, + quickSettingsButton = { slotModifier -> + OverlapAwareCaptureSlot( + modifier = slotModifier, + orientation = Orientation.Horizontal, + isCompact = false, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings, + content = slots.quickSettingsButton + ) + }, + indicatorRow = { slotModifier -> + OverlapAwareCaptureSlot( + modifier = slotModifier, + orientation = Orientation.Horizontal, + isCompact = false, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings, + content = slots.topBar + ) + }, + captureModeToggle = { slotModifier -> + OverlapAwareCaptureSlot( + modifier = slotModifier, + orientation = Orientation.Horizontal, + isCompact = false, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings, + content = slots.captureModeToggle + ) + }, + captureModeCarousel = { slotModifier -> + OverlapAwareCaptureSlot( + modifier = slotModifier, + orientation = Orientation.Horizontal, + isCompact = false, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings, + content = slots.captureModeCarousel + ) + }, + quickSettingsOverlay = { slotModifier -> + OverlapAwareCaptureSlot( + modifier = slotModifier, + orientation = Orientation.Vertical, + isCompact = false, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings, + content = slots.quickSettingsOverlay + ) + }, + debugOverlay = debugOverlay, + debugVisibilityWrapper = debugVisibilityWrapper, + screenFlashOverlay = screenFlashOverlay, + snackBar = slots.snackBar, + topStartContent = { slotModifier -> + val slotScope = rememberCaptureSlotScope( + orientation = Orientation.Horizontal, + isCompact = false, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings + ) + slotScope.(slots.viewfinderTopStart)(slotModifier) + }, + viewfinderTopEndContent = { slotModifier -> + val slotScope = rememberCaptureSlotScope( + orientation = Orientation.Horizontal, + isCompact = false, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings + ) + slotScope.(slots.viewfinderTopEnd)(slotModifier) + }, + topBarTrailingContent = { slotModifier -> + OverlapAwareCaptureSlot( + modifier = slotModifier, + orientation = Orientation.Horizontal, + isCompact = false, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings, + content = slots.topBarTrailingContent + ) + }, + onRequiresImmersiveChange = onRequiresImmersiveChange, + errorDialog = slots.errorDialog + ) +} + +/** + * Compact portrait capture layout accepting individual control composables. + * + * Uses [AdaptivePortraitCaptureLayout] for handheld portrait aspect ratios (16:9 and taller) and + * falls back to [VerticalMaterialControls] for squarer compact panes (such as split-screen + * multi-window). Hosts Quick Settings inside an in-hierarchy [BottomSheetScaffold] and tags its + * root container with [COMPACT_CONTROLS_TAG]. + * + * @param modifier [Modifier] applied to the outer layout container. + * @param scaffoldState [BottomSheetScaffoldState] controlling the Quick Settings sheet and snackbar + * host. + * @param onDismissQuickSettings Callback invoked when the user taps the Quick Settings drag handle + * or scrim. + * @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 (`true` by default for multi-window clearance; `false` when + * called from legacy [PreviewLayout] to keep top-bar coordinates invariant across status-bar + * visibility transitions). + * @param viewfinder Composable rendering the camera preview frame. + * @param captureButton Primary photo/video shutter button composable. + * @param imageWell Media thumbnail button composable. + * @param flipCameraButton Lens-facing toggle button composable. + * @param zoomLevelDisplay Zoom control bar composable. + * @param elapsedTimeDisplay Recording duration readout composable. + * @param quickSettingsButton Button toggling the Quick Settings bottom sheet. + * @param indicatorRow Status indicator bar content placed in the top bar. + * @param captureModeToggle Photo/video mode toggle switch composable. + * @param captureModeCarousel Secondary sub-mode selector carousel placed in the reserved middle + * band. + * @param quickSettingsOverlay Content rendered inside the Quick Settings bottom sheet. + * @param debugOverlay Untouched pass-through composable for debug UI overlays. + * @param debugVisibilityWrapper Wrapper conditionally hiding camera chrome when debug component + * hiding is enabled. + * @param screenFlashOverlay Full-bleed screen flash composable drawn above all other content and + * system bar areas. + * @param snackBar Transient message composable paired with a [SnackbarHostState]. + * @param topStartContent Optional content anchored directly below the top bar at the start edge. + * @param viewfinderTopEndContent Optional content anchored to the top-end corner of the viewfinder. + * @param topBarTrailingContent Optional trailing content aligned to the end of the top bar. + * @param onRequiresImmersiveChange Callback notified when the portrait solver requires or releases + * immersive navigation-bar hiding. + * @param errorDialog In-hierarchy camera error dialog composable. + */ +@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) +@Composable +fun CompactPortraitLayout( + modifier: Modifier = Modifier, + scaffoldState: BottomSheetScaffoldState = rememberCompactPortraitScaffoldState(), + onDismissQuickSettings: () -> Unit = {}, + isErrorDialogShowing: Boolean = false, + includeStatusBarsInTopBar: Boolean = true, + viewfinder: @Composable (Modifier) -> Unit, + captureButton: @Composable (Modifier) -> Unit, + imageWell: @Composable (Modifier) -> Unit, + flipCameraButton: @Composable (Modifier) -> Unit, + zoomLevelDisplay: @Composable (Modifier) -> Unit, + elapsedTimeDisplay: @Composable (Modifier) -> Unit, + quickSettingsButton: @Composable (Modifier) -> Unit, + indicatorRow: @Composable (Modifier) -> Unit, + captureModeToggle: @Composable (Modifier) -> Unit, + captureModeCarousel: @Composable (Modifier) -> Unit = {}, + quickSettingsOverlay: @Composable (Modifier) -> Unit, + debugOverlay: @Composable (Modifier) -> Unit = {}, + debugVisibilityWrapper: @Composable (@Composable () -> Unit) -> Unit = { it() }, + screenFlashOverlay: @Composable (Modifier) -> Unit = {}, + snackBar: @Composable (Modifier, snackbarHostState: SnackbarHostState) -> Unit = { _, _ -> }, + topStartContent: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit = {}, + viewfinderTopEndContent: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit = {}, + topBarTrailingContent: @Composable (Modifier) -> Unit = {}, + onRequiresImmersiveChange: (Boolean) -> Unit = {}, + errorDialog: @Composable (Modifier) -> Unit = {} +) { + val overlapTargetBounds = remember { mutableStateOf(Rect.Zero) } + val localeDirection = LocalLayoutDirection.current + val dismissQuickSettingsLabel = + stringResource(R.string.quick_settings_btn_close_expanded_settings_description) + val isSheetVisible = scaffoldState.bottomSheetState.isVisible || + scaffoldState.bottomSheetState.targetValue == SheetValue.Expanded + val isModalOpen = isSheetVisible || isErrorDialogShowing + + CompositionLocalProvider(LocalOverlapTargetBounds provides overlapTargetBounds) { + 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) + .clickable( + role = Role.Button, + onClickLabel = dismissQuickSettingsLabel, + onClick = onDismissQuickSettings + ) + ) + }, + sheetShape = RoundedCornerShape( + topStart = CompactPortraitTokens.SheetTopCornerRadius, + topEnd = CompactPortraitTokens.SheetTopCornerRadius + ), + sheetContainerColor = MaterialTheme.colorScheme.surfaceContainerLow, + sheetContent = { + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + quickSettingsOverlay(Modifier) + } + }, + snackbarHost = {} + ) { + BoxWithConstraints( + modifier = Modifier + .fillMaxSize() + .background(Color.Black) + ) { + val windowAspectRatio = maxHeight.value / maxWidth.value + val isHandheldPortrait = + windowAspectRatio >= CompactPortraitTokens.PORTRAIT_ASPECT_RATIO_THRESHOLD + if (isHandheldPortrait) { + AdaptivePortraitCaptureLayout( + windowWidth = maxWidth, + windowHeight = maxHeight, + includeStatusBarsInTopBar = includeStatusBarsInTopBar, + isSheetVisible = isSheetVisible, + isModalOpen = 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, + debugVisibilityWrapper = debugVisibilityWrapper, + snackbarHost = { hostModifier -> + PillSnackbarHost( + snackbarHostState = scaffoldState.snackbarHostState, + modifier = hostModifier + ) + } + ) + Box( + modifier = Modifier + .fillMaxSize() + .suppressBackgroundForModal(isModalOpen) + .windowInsetsPadding( + WindowInsets.systemBarsIgnoringVisibility + .union(WindowInsets.displayCutout) + ) + ) { + CompositionLocalProvider( + LocalLayoutDirection provides localeDirection + ) { + snackBar(Modifier, scaffoldState.snackbarHostState) + } + } + } else { + Column { + val minTouchTarget = LocalMinimumInteractiveComponentSize.current + .takeOrElse { CompactPortraitTokens.DefaultMinTouchTarget } + val (topBarHeight, topBarTopPadding) = computeTopBarMetrics( + includeStatusBarsInTopBar = includeStatusBarsInTopBar, + minTouchTarget = minTouchTarget + ) + CompactTopBarBox( + topBarHeight = topBarHeight, + topBarTopPadding = topBarTopPadding, + modifier = Modifier.suppressBackgroundForModal(isModalOpen), + indicatorRow = indicatorRow, + topBarTrailingContent = topBarTrailingContent + ) + Box { + Box(modifier = Modifier.suppressBackgroundForModal(isModalOpen)) { + viewfinder(Modifier) + } + OverlapAwareStyleProvider( + Modifier + .align(Alignment.TopStart) + .suppressBackgroundForModal(isSheetVisible) + ) { + topStartContent(Modifier) + } + OverlapAwareStyleProvider( + Modifier + .align(Alignment.TopEnd) + .suppressBackgroundForModal(isModalOpen) + ) { + viewfinderTopEndContent(Modifier) + } + } + } + + Box( + modifier = Modifier + .fillMaxSize() + .suppressBackgroundForModal(isModalOpen) + .windowInsetsPadding( + WindowInsets.systemBarsIgnoringVisibility + .union(WindowInsets.displayCutout) + ) + ) { + debugVisibilityWrapper { + VerticalMaterialControls( + captureButton = captureButton, + imageWell = imageWell, + flipCameraButton = flipCameraButton, + quickSettingsToggleButton = quickSettingsButton, + captureModeToggleSwitch = captureModeToggle, + captureModeCarousel = captureModeCarousel, + zoomControls = zoomLevelDisplay, + elapsedTimeDisplay = elapsedTimeDisplay, + snackbarHost = { hostModifier -> + PillSnackbarHost( + snackbarHostState = scaffoldState.snackbarHostState, + modifier = hostModifier + ) + } + ) + } + CompositionLocalProvider( + LocalLayoutDirection provides localeDirection + ) { + snackBar(Modifier, scaffoldState.snackbarHostState) + } + } + } + + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + debugOverlay(Modifier) + } + + if (isSheetVisible) { + Box( + modifier = Modifier + .fillMaxSize() + .testTag(QUICK_SETTINGS_SCRIM) + .clickable( + onClickLabel = dismissQuickSettingsLabel, + interactionSource = remember { MutableInteractionSource() }, + indication = null, + onClick = onDismissQuickSettings + ) + ) + } + + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + 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 (Modifier) -> Unit, + topBarTrailingContent: @Composable (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 + ) { + indicatorRow(Modifier) + topBarTrailingContent(Modifier.align(Alignment.CenterEnd)) + } + } +} + +@Composable +private fun CompactCaptureRow( + bottomBarDirection: LayoutDirection, + localeDirection: LayoutDirection, + imageWell: @Composable (Modifier) -> Unit, + captureButton: @Composable (Modifier) -> Unit, + flipCameraButton: @Composable (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 { + imageWell(Modifier) + } + } + } + } + + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + OverlapAwareStyleProvider { + captureButton(Modifier) + } + } + + Box( + modifier = Modifier + .weight(1f) + .fillMaxHeight(), + contentAlignment = Alignment.Center + ) { + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + OverlapAwareStyleProvider { + flipCameraButton(Modifier) + } + } + } + } + } +} + +@Composable +private fun CompactBottomToolbar( + bottomBarDirection: LayoutDirection, + localeDirection: LayoutDirection, + quickSettingsToggleButton: @Composable (Modifier) -> Unit, + captureModeToggleSwitch: @Composable (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 { + quickSettingsToggleButton(Modifier) + } + } + } + + Box( + modifier = Modifier.weight(1f), + contentAlignment = Alignment.Center + ) { + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + OverlapAwareStyleProvider { + 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 (Modifier) -> Unit, + topBarTrailingContent: @Composable (Modifier) -> Unit, + elapsedTimeDisplay: @Composable (Modifier) -> Unit, + zoomControls: @Composable (Modifier) -> Unit, + imageWell: @Composable (Modifier) -> Unit, + captureButton: @Composable (Modifier) -> Unit, + flipCameraButton: @Composable (Modifier) -> Unit, + captureModeCarousel: @Composable (Modifier) -> Unit, + quickSettingsToggleButton: @Composable (Modifier) -> Unit, + captureModeToggleSwitch: @Composable (Modifier) -> Unit, + debugVisibilityWrapper: @Composable (@Composable () -> Unit) -> Unit, + includeStatusBarsInTopBar: Boolean = true, + isSheetVisible: Boolean = false, + isModalOpen: Boolean = false, + 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) + .suppressBackgroundForModal(isModalOpen) + ) { + viewfinder(Modifier) + } + + Box( + modifier = Modifier + .layoutId(CaptureSlotId.TopStartContent) + .suppressBackgroundForModal(isSheetVisible) + ) { + OverlapAwareStyleProvider { + topStartContent(Modifier) + } + } + + Box( + modifier = Modifier + .layoutId(CaptureSlotId.ViewfinderTopEndContent) + .suppressBackgroundForModal(isModalOpen) + ) { + OverlapAwareStyleProvider { + viewfinderTopEndContent(Modifier) + } + } + + CompactTopBarBox( + topBarHeight = topBarHeight, + topBarTopPadding = topBarTopPadding, + modifier = Modifier + .layoutId(CaptureSlotId.TopBar) + .suppressBackgroundForModal(isModalOpen), + indicatorRow = indicatorRow, + topBarTrailingContent = topBarTrailingContent + ) + + debugVisibilityWrapper { + Column( + modifier = Modifier + .layoutId(CaptureSlotId.ElapsedTime) + .suppressBackgroundForModal(isModalOpen), + horizontalAlignment = Alignment.CenterHorizontally + ) { + snackbarHost(Modifier) + elapsedTimeDisplay(Modifier) + } + + Box( + modifier = Modifier + .layoutId(CaptureSlotId.ZoomBar) + .suppressBackgroundForModal(isModalOpen), + contentAlignment = Alignment.Center + ) { + OverlapAwareStyleProvider { + zoomControls(Modifier) + } + } + + CompactCaptureRow( + bottomBarDirection = bottomBarDirection, + localeDirection = localeDirection, + imageWell = imageWell, + captureButton = captureButton, + flipCameraButton = flipCameraButton, + modifier = Modifier + .layoutId(CaptureSlotId.CaptureRow) + .suppressBackgroundForModal(isModalOpen) + ) + + Box( + modifier = Modifier + .layoutId(CaptureSlotId.ModeSwitcher) + .fillMaxWidth() + .suppressBackgroundForModal(isModalOpen), + contentAlignment = Alignment.Center + ) { + OverlapAwareStyleProvider { + captureModeCarousel(Modifier) + } + } + + CompactBottomToolbar( + bottomBarDirection = bottomBarDirection, + localeDirection = localeDirection, + quickSettingsToggleButton = quickSettingsToggleButton, + captureModeToggleSwitch = captureModeToggleSwitch, + modifier = Modifier + .layoutId(CaptureSlotId.BottomToolbar) + .suppressBackgroundForModal(isModalOpen) + ) + } + } + ) { 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 (Modifier) -> Unit, + zoomControls: @Composable (Modifier) -> Unit, + imageWell: @Composable (Modifier) -> Unit, + flipCameraButton: @Composable (Modifier) -> Unit, + quickSettingsToggleButton: @Composable (Modifier) -> Unit, + captureModeToggleSwitch: @Composable (Modifier) -> Unit, + captureModeCarousel: @Composable (Modifier) -> Unit = {}, + elapsedTimeDisplay: @Composable (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) + + elapsedTimeDisplay(Modifier) + + OverlapAwareStyleProvider { + zoomControls(Modifier) + } + + Spacer(modifier = Modifier.height(zoomGap)) + + Column { + CompactCaptureRow( + bottomBarDirection = bottomBarDirection, + localeDirection = localeDirection, + imageWell = imageWell, + captureButton = captureButton, + flipCameraButton = flipCameraButton, + modifier = Modifier.height(CompactPortraitTokens.ShutterStackHeight) + ) + } + + Box( + modifier = Modifier + .fillMaxWidth() + .height(CompactPortraitTokens.MiddleSlotHeight + stackGap * 2), + contentAlignment = Alignment.Center + ) { + OverlapAwareStyleProvider { + captureModeCarousel(Modifier) + } + } + + CompactBottomToolbar( + bottomBarDirection = bottomBarDirection, + localeDirection = localeDirection, + quickSettingsToggleButton = quickSettingsToggleButton, + captureModeToggleSwitch = captureModeToggleSwitch, + modifier = Modifier.height(CompactPortraitTokens.LowerSectionHeight) + ) + + Spacer(modifier = Modifier.height(bottomPad)) + } + } + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Preview( + name = "CompactPortrait - Phone Portrait (412x915dp)", + device = "spec:width=412dp,height=915dp", + showBackground = true +) +@Composable +private fun CompactPortraitStandardPhonePreview() { + MaterialTheme { + CompactPortraitLayout( + slots = PlaceholderCaptureSlots.sideRail(includeElapsedTime = true), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) } + ) + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Preview( + name = "CompactPortrait - Short Phone (360x640dp)", + device = "spec:width=360dp,height=640dp", + showBackground = true +) +@Composable +private fun CompactPortraitShortPhonePreview() { + MaterialTheme { + CompactPortraitLayout( + slots = PlaceholderCaptureSlots.sideRail(includeElapsedTime = true), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) } + ) + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Preview( + name = "CompactPortrait - RTL Default Policy (Unmirrored Bar)", + device = "spec:width=412dp,height=915dp", + locale = "ar", + showBackground = true +) +@Composable +private fun CompactPortraitRtlDefaultPolicyPreview() { + MaterialTheme { + CompositionLocalProvider( + LocalCaptureRtlPolicy provides CaptureRtlPolicy(mirrorCompactBottomBar = false) + ) { + CompactPortraitLayout( + slots = PlaceholderCaptureSlots.sideRail(includeElapsedTime = true), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) } + ) + } + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Preview( + name = "CompactPortrait - RTL Mirrored Policy", + device = "spec:width=412dp,height=915dp", + locale = "ar", + showBackground = true +) +@Composable +private fun CompactPortraitRtlMirroredPolicyPreview() { + MaterialTheme { + 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/TwoSideRailLayout.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/TwoSideRailLayout.kt new file mode 100644 index 000000000..067ff3737 --- /dev/null +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/TwoSideRailLayout.kt @@ -0,0 +1,493 @@ +/* + * 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.WindowInsets +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.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Surface +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.ui.AbsoluteAlignment +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.platform.LocalLayoutDirection +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.dp + +private object TwoSideRailTokens { + val StandardChromePadding = 16.dp + val StandardTopOverlayHorizontalClearance = 120.dp + val QuickSettingsCardMaxWidth = 360.dp + val QuickSettingsCardCornerRadius = 28.dp + val QuickSettingsCardTonalElevation = 6.dp + val QuickSettingsScrimColor = Color.Black.copy(alpha = 0.45f) +} + +/** + * Large-screen and foldable capture layout anchoring vertical control rails to the start and end + * edges over a full-bleed camera viewfinder. + * + * Places [viewfinder] in a full-screen centered background box without portrait solver offsets so + * previews sit flush from top to bottom. Overlays [StartSideRail], [EndSideRail] (with + * `showElapsedTimeInRail = false`), and center HUD slots inside live + * `WindowInsets.systemBars.union(WindowInsets.displayCutout)` safe bounds so visible multi-window + * status bars are cleared while hidden immersive bars introduce zero dead padding. + * + * Scopes [LocalCaptureRtlPolicy] (`mirrorSideRails`) solely to the spatial rail container and Quick + * Settings card anchor while immediately restoring the active locale's `LayoutDirection` inside + * both rails and every child slot. Hosts Quick Settings as an in-hierarchy floating [Surface] card + * (optionally tagged with [QUICK_SETTINGS_BOTTOM_SHEET]) without spawning secondary windows. + * + * @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 root layout box. + * @param snackbarHostState [SnackbarHostState] driving the top-center [PillSnackbarHost] and passed + * to [CaptureSlots.snackBar]. + * @param isQuickSettingsOpen Whether the in-hierarchy Quick Settings scrim and floating card are + * displayed. + * @param isRecording Whether an active video recording session is in progress. + * @param isErrorDialogShowing Whether a modal camera error dialog is currently visible above the + * capture chrome. + * @param tagQuickSettingsCard Whether the outer floating Quick Settings [Surface] card carries + * [QUICK_SETTINGS_BOTTOM_SHEET]; defaults to `true` so callers whose inner overlay is untagged + * preserve test-tag parity with compact sheets, and can be set to `false` when the inner overlay + * already attaches that tag. + * @param onDismissQuickSettings Callback invoked on scrim tap, system back press while Quick + * Settings is open, or [CaptureSlotScope.dismissQuickSettings]. + * @param debugOverlay Untouched pass-through composable for debug UI overlays. + * @param debugVisibilityWrapper Wrapper conditionally hiding camera chrome when debug component + * hiding is enabled. + * @param screenFlashOverlay Full-bleed screen flash composable drawn above all chrome and system + * bar areas. + */ +@Composable +fun TwoSideRailLayout( + slots: CaptureSlots, + viewfinder: @Composable (Modifier) -> Unit, + modifier: Modifier = Modifier, + snackbarHostState: SnackbarHostState = remember { SnackbarHostState() }, + isQuickSettingsOpen: Boolean = false, + isRecording: Boolean = false, + isErrorDialogShowing: Boolean = false, + tagQuickSettingsCard: Boolean = true, + onDismissQuickSettings: () -> Unit = {}, + debugOverlay: @Composable (Modifier) -> Unit = {}, + debugVisibilityWrapper: @Composable (@Composable () -> Unit) -> Unit = { it() }, + screenFlashOverlay: @Composable (Modifier) -> Unit = {} +) { + SideRailCaptureScaffold( + slots = slots, + viewfinder = viewfinder, + modifier = modifier, + snackbarHostState = snackbarHostState, + isCompactHeight = false, + chromePadding = TwoSideRailTokens.StandardChromePadding, + topOverlayHorizontalClearance = TwoSideRailTokens.StandardTopOverlayHorizontalClearance, + quickSettingsCardMaxWidth = TwoSideRailTokens.QuickSettingsCardMaxWidth, + quickSettingsCardMaxHeight = Dp.Unspecified, + isQuickSettingsOpen = isQuickSettingsOpen, + isRecording = isRecording, + isErrorDialogShowing = isErrorDialogShowing, + tagQuickSettingsCard = tagQuickSettingsCard, + onDismissQuickSettings = onDismissQuickSettings, + debugOverlay = debugOverlay, + debugVisibilityWrapper = debugVisibilityWrapper, + screenFlashOverlay = screenFlashOverlay + ) +} + +/** + * Shared full-bleed viewfinder and dual-rail capture scaffold backing [TwoSideRailLayout] and + * [WideShortLayout]. + */ +@Composable +internal fun SideRailCaptureScaffold( + slots: CaptureSlots, + viewfinder: @Composable (Modifier) -> Unit, + modifier: Modifier, + snackbarHostState: SnackbarHostState, + isCompactHeight: Boolean, + chromePadding: Dp, + topOverlayHorizontalClearance: Dp, + quickSettingsCardMaxWidth: Dp, + quickSettingsCardMaxHeight: Dp, + isQuickSettingsOpen: Boolean, + isRecording: Boolean, + isErrorDialogShowing: Boolean, + tagQuickSettingsCard: Boolean, + onDismissQuickSettings: () -> Unit, + debugOverlay: @Composable (Modifier) -> Unit, + debugVisibilityWrapper: @Composable (@Composable () -> Unit) -> Unit, + screenFlashOverlay: @Composable (Modifier) -> Unit +) { + val overlapTargetBounds = remember { mutableStateOf(Rect.Zero) } + val localeDirection = LocalLayoutDirection.current + val rtlPolicy = LocalCaptureRtlPolicy.current + val railContainerDirection = if (rtlPolicy.mirrorSideRails) { + localeDirection + } else { + LayoutDirection.Ltr + } + val isModalOpen = isQuickSettingsOpen || isErrorDialogShowing + val liveSafeInsets = WindowInsets.systemBars.union(WindowInsets.displayCutout) + val dismissQuickSettingsLabel = + stringResource(R.string.quick_settings_btn_close_expanded_settings_description) + + BackHandler(enabled = isQuickSettingsOpen, onBack = onDismissQuickSettings) + + CompositionLocalProvider(LocalOverlapTargetBounds provides overlapTargetBounds) { + 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) + ) { + debugVisibilityWrapper { + CompositionLocalProvider(LocalLayoutDirection provides railContainerDirection) { + Box(modifier = Modifier.fillMaxSize()) { + Box( + modifier = Modifier + .align(Alignment.CenterStart) + .fillMaxHeight() + .suppressBackgroundForModal(isModalOpen) + ) { + CompositionLocalProvider( + LocalLayoutDirection provides localeDirection + ) { + StartSideRail( + slots = slots, + modifier = Modifier.fillMaxHeight(), + isCompactHeight = isCompactHeight, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings + ) + } + } + + Box( + modifier = Modifier + .align(Alignment.CenterEnd) + .fillMaxHeight() + .suppressBackgroundForModal(isModalOpen) + ) { + CompositionLocalProvider( + LocalLayoutDirection provides localeDirection + ) { + EndSideRail( + slots = slots, + modifier = Modifier.fillMaxHeight(), + isCompactHeight = isCompactHeight, + isRecording = isRecording, + showElapsedTimeInRail = false, + onDismissQuickSettings = onDismissQuickSettings + ) + } + } + } + } + + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + Box( + modifier = Modifier + .fillMaxSize() + .padding(horizontal = topOverlayHorizontalClearance) + ) { + OverlapAwareCaptureSlot( + modifier = Modifier + .align(Alignment.TopStart) + .padding(top = chromePadding) + .suppressBackgroundForModal(isQuickSettingsOpen), + orientation = Orientation.Horizontal, + isCompact = isCompactHeight, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings, + content = slots.viewfinderTopStart + ) + + OverlapAwareCaptureSlot( + modifier = Modifier + .align(Alignment.TopEnd) + .padding(top = chromePadding) + .suppressBackgroundForModal(isModalOpen), + orientation = Orientation.Horizontal, + isCompact = isCompactHeight, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings, + content = slots.viewfinderTopEnd + ) + } + + Column( + modifier = Modifier + .align(Alignment.TopCenter) + .padding(top = chromePadding) + .suppressBackgroundForModal(isModalOpen), + horizontalAlignment = Alignment.CenterHorizontally + ) { + PillSnackbarHost(snackbarHostState = snackbarHostState) + OverlapAwareCaptureSlot( + orientation = Orientation.Horizontal, + isCompact = isCompactHeight, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings, + content = slots.elapsedTimeDisplay + ) + } + + OverlapAwareCaptureSlot( + modifier = Modifier + .align(Alignment.BottomCenter) + .padding(bottom = chromePadding) + .suppressBackgroundForModal(isModalOpen), + orientation = Orientation.Horizontal, + isCompact = isCompactHeight, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings, + content = slots.captureModeCarousel + ) + } + } + + Box( + modifier = Modifier + .fillMaxSize() + .suppressBackgroundForModal(isModalOpen) + ) { + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + slots.snackBar(Modifier, snackbarHostState) + } + } + } + + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + debugOverlay(Modifier) + } + + if (isQuickSettingsOpen) { + Box( + modifier = Modifier + .fillMaxSize() + .background(TwoSideRailTokens.QuickSettingsScrimColor) + .testTag(QUICK_SETTINGS_SCRIM) + .clickable( + onClickLabel = dismissQuickSettingsLabel, + interactionSource = remember { MutableInteractionSource() }, + indication = null, + onClick = onDismissQuickSettings + ) + ) + + val quickSettingsAlignment = if (rtlPolicy.mirrorSideRails) { + Alignment.BottomStart + } else { + AbsoluteAlignment.BottomLeft + } + val cardTagModifier = if (tagQuickSettingsCard) { + Modifier.testTag(QUICK_SETTINGS_BOTTOM_SHEET) + } else { + Modifier + } + val cardHeightModifier = if (quickSettingsCardMaxHeight != Dp.Unspecified) { + Modifier.heightIn(max = quickSettingsCardMaxHeight) + } else { + Modifier + } + + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + Box( + modifier = Modifier + .fillMaxSize() + .windowInsetsPadding(liveSafeInsets) + .padding(chromePadding) + ) { + Surface( + modifier = Modifier + .align(quickSettingsAlignment) + .then(cardTagModifier) + .widthIn(max = quickSettingsCardMaxWidth) + .then(cardHeightModifier) + .pointerInput(Unit) { + detectTapGestures { /* Consume card taps */ } + }, + shape = RoundedCornerShape( + TwoSideRailTokens.QuickSettingsCardCornerRadius + ), + color = MaterialTheme.colorScheme.surfaceContainerLow, + tonalElevation = TwoSideRailTokens.QuickSettingsCardTonalElevation + ) { + CompositionLocalProvider( + LocalLayoutDirection provides localeDirection + ) { + OverlapAwareCaptureSlot( + orientation = Orientation.Vertical, + isCompact = isCompactHeight, + isRecording = isRecording, + onDismissQuickSettings = onDismissQuickSettings, + content = slots.quickSettingsOverlay + ) + } + } + } + } + } + + CompositionLocalProvider(LocalLayoutDirection provides localeDirection) { + 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) + } + } +} + +@Preview( + name = "TwoSideRail - Foldable Unfolded (852x883dp)", + device = "spec:width=852dp,height=883dp", + showBackground = true +) +@Composable +private fun TwoSideRailFoldablePreview() { + MaterialTheme { + TwoSideRailLayout( + slots = PlaceholderCaptureSlots.sideRail(includeElapsedTime = true), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) } + ) + } +} + +@Preview( + name = "TwoSideRail - Tablet Landscape (1280x800dp)", + device = "spec:width=1280dp,height=800dp", + showBackground = true +) +@Composable +private fun TwoSideRailTabletLandscapePreview() { + MaterialTheme { + TwoSideRailLayout( + slots = PlaceholderCaptureSlots.sideRail( + includePauseSlot = true, + includeElapsedTime = true + ), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + isRecording = true + ) + } +} + +@Preview( + name = "TwoSideRail - Tablet Portrait (800x1280dp)", + device = "spec:width=800dp,height=1280dp", + showBackground = true +) +@Composable +private fun TwoSideRailTabletPortraitPreview() { + MaterialTheme { + TwoSideRailLayout( + slots = PlaceholderCaptureSlots.sideRail(includeElapsedTime = true), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) } + ) + } +} + +@Preview( + name = "TwoSideRail - RTL Default Policy (Unmirrored Rails)", + device = "spec:width=1280dp,height=800dp", + locale = "ar", + showBackground = true +) +@Composable +private fun TwoSideRailRtlDefaultPolicyPreview() { + MaterialTheme { + CompositionLocalProvider( + LocalCaptureRtlPolicy provides CaptureRtlPolicy(mirrorSideRails = false) + ) { + TwoSideRailLayout( + slots = PlaceholderCaptureSlots.sideRail(includeElapsedTime = true), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + isQuickSettingsOpen = true + ) + } + } +} + +@Preview( + name = "TwoSideRail - RTL Mirrored Policy", + device = "spec:width=1280dp,height=800dp", + locale = "ar", + showBackground = true +) +@Composable +private fun TwoSideRailRtlMirroredPolicyPreview() { + MaterialTheme { + CompositionLocalProvider( + LocalCaptureRtlPolicy provides CaptureRtlPolicy(mirrorSideRails = true) + ) { + TwoSideRailLayout( + slots = PlaceholderCaptureSlots.sideRail(includeElapsedTime = true), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + isQuickSettingsOpen = true + ) + } + } +} diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/WideShortLayout.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/WideShortLayout.kt new file mode 100644 index 000000000..02f818855 --- /dev/null +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/WideShortLayout.kt @@ -0,0 +1,482 @@ +/* + * 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.SnackbarHostState +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 WideShortTokens { + val ZeroSize = 0.dp + val CondensedChromePadding = 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 windows (< 480dp, e.g. 800x400dp or + // 360x360dp 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 SHUTTER_STACK_HEIGHT_FRACTION = 0.78f + const val CENTER_HUD_HEIGHT_FRACTION = 0.12f +} + +/** + * Condensed-height side-rail capture layout for short windows (`heightDp < 480.dp`, covering both + * `WIDE_SHORT` landscape/split-screen postures such as `800x400dp` and `COMPACT_SHORT` square + * multi-window panes such as `360x360dp`). + * + * 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, and delegates to [StartSideRail] and [EndSideRail] with + * `isCompactHeight = true`, `showElapsedTimeInRail = false`, condensed `8.dp` chrome padding, + * scoped [LocalCaptureRtlPolicy] (`mirrorSideRails`), and an in-hierarchy floating Quick Settings + * card. + * + * @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 snackbarHostState [SnackbarHostState] driving the top-center [PillSnackbarHost] and passed + * to [CaptureSlots.snackBar]. + * @param isQuickSettingsOpen Whether the in-hierarchy Quick Settings scrim and floating card are + * displayed. + * @param isRecording Whether an active video recording session is in progress. + * @param isErrorDialogShowing Whether a modal camera error dialog is currently visible above the + * capture chrome. + * @param tagQuickSettingsCard Whether the outer floating Quick Settings card carries + * [QUICK_SETTINGS_BOTTOM_SHEET]; defaults to `true`. + * @param onDismissQuickSettings Callback invoked on scrim tap, system back press while Quick + * Settings is open, or [CaptureSlotScope.dismissQuickSettings]. + * @param debugOverlay Untouched pass-through composable for debug UI overlays. + * @param debugVisibilityWrapper Wrapper conditionally hiding camera chrome when debug component + * hiding is enabled. + * @param screenFlashOverlay Full-bleed screen flash composable drawn above all chrome and system + * bar areas. + */ +@Composable +fun WideShortLayout( + slots: CaptureSlots, + viewfinder: @Composable (Modifier) -> Unit, + modifier: Modifier = Modifier, + snackbarHostState: SnackbarHostState = remember { SnackbarHostState() }, + isQuickSettingsOpen: Boolean = false, + isRecording: Boolean = false, + isErrorDialogShowing: Boolean = false, + tagQuickSettingsCard: Boolean = true, + onDismissQuickSettings: () -> Unit = {}, + debugOverlay: @Composable (Modifier) -> Unit = {}, + debugVisibilityWrapper: @Composable (@Composable () -> Unit) -> Unit = { it() }, + 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(WideShortTokens.ZeroSize) + val availableHeight = (maxHeight - verticalInsets).coerceAtLeast(WideShortTokens.ZeroSize) + + val railSlotMaxWidth = min( + CaptureSlotTokens.ModeToggleCompactWidth, + (availableWidth * WideShortTokens.RAIL_WIDTH_FRACTION) + .coerceAtLeast(WideShortTokens.MinRailSlotWidthFloor) + ) + val estimatedRailFootprint = railSlotMaxWidth + WideShortTokens.RailHorizontalPaddingTotal + val condensedSlots = remember(slots, availableWidth, availableHeight) { + slots.withCondensedSizeCaps( + availableWidth = availableWidth, + availableHeight = availableHeight, + railSlotMaxWidth = railSlotMaxWidth, + estimatedRailFootprint = estimatedRailFootprint + ) + } + val cardMaxWidth = min( + WideShortTokens.QuickSettingsCardMaxWidth, + (availableWidth - WideShortTokens.CondensedChromePadding * 2) + .coerceAtLeast(WideShortTokens.ZeroSize) + ) + val cardMaxHeight = (availableHeight - WideShortTokens.CondensedChromePadding * 2) + .coerceAtLeast(WideShortTokens.ZeroSize) + + SideRailCaptureScaffold( + slots = condensedSlots, + viewfinder = viewfinder, + modifier = Modifier.fillMaxSize(), + snackbarHostState = snackbarHostState, + isCompactHeight = true, + chromePadding = WideShortTokens.CondensedChromePadding, + topOverlayHorizontalClearance = estimatedRailFootprint, + quickSettingsCardMaxWidth = cardMaxWidth, + quickSettingsCardMaxHeight = cardMaxHeight, + isQuickSettingsOpen = isQuickSettingsOpen, + isRecording = isRecording, + isErrorDialogShowing = isErrorDialogShowing, + tagQuickSettingsCard = tagQuickSettingsCard, + onDismissQuickSettings = onDismissQuickSettings, + debugOverlay = debugOverlay, + debugVisibilityWrapper = debugVisibilityWrapper, + screenFlashOverlay = screenFlashOverlay + ) + } +} + +private fun CaptureSlots.withCondensedSizeCaps( + availableWidth: Dp, + availableHeight: Dp, + railSlotMaxWidth: Dp, + estimatedRailFootprint: Dp +): CaptureSlots { + val innerRailHeight = (availableHeight - WideShortTokens.RailTotalVerticalPadding) + .coerceAtLeast(WideShortTokens.ZeroSize) + + val indicatorMaxHeight = min( + CaptureSlotTokens.IndicatorCompactMainAxisSize, + innerRailHeight * WideShortTokens.INDICATOR_MAX_HEIGHT_FRACTION + ) + val zoomMaxHeight = min( + CaptureSlotTokens.ZoomCompactMainAxisSize, + innerRailHeight * WideShortTokens.ZOOM_MAX_HEIGHT_FRACTION + ) + val quickSettingsButtonMaxSize = min( + min( + CaptureSlotTokens.IconTouchTargetSize, + innerRailHeight * WideShortTokens.QUICK_SETTINGS_BUTTON_FRACTION + ), + railSlotMaxWidth + ) + val shutterMaxDiameter = min( + min( + CaptureSlotTokens.ShutterCompactDiameter, + innerRailHeight * WideShortTokens.SHUTTER_DIAMETER_FRACTION + ), + railSlotMaxWidth + ) + val secondaryActionMaxSize = min( + min( + CaptureSlotTokens.SecondaryActionCompactSize, + innerRailHeight * WideShortTokens.SECONDARY_ACTION_FRACTION + ), + railSlotMaxWidth + ) + val modeToggleMaxHeight = min( + CaptureSlotTokens.ModeToggleCompactHeight, + innerRailHeight * WideShortTokens.MODE_TOGGLE_HEIGHT_FRACTION + ) + val shutterStackMaxHeight = innerRailHeight * WideShortTokens.SHUTTER_STACK_HEIGHT_FRACTION + + val centerHudMaxWidth = (availableWidth - estimatedRailFootprint * 2) + .coerceAtLeast(WideShortTokens.MinCenterHudWidthFloor) + val centerHudMaxHeight = min( + CaptureSlotTokens.HorizontalTopBarHeight, + innerRailHeight * WideShortTokens.CENTER_HUD_HEIGHT_FRACTION + ) + val cardInnerMaxWidth = min( + WideShortTokens.QuickSettingsCardMaxWidth, + (availableWidth - WideShortTokens.CondensedChromePadding * 2) + .coerceAtLeast(WideShortTokens.ZeroSize) + ) + val cardInnerMaxHeight = (availableHeight - WideShortTokens.CondensedChromePadding * 2) + .coerceAtLeast(WideShortTokens.ZeroSize) + + val original = this + val originalShutterStack = original.shutterStack + + return original.copy( + indicatorColumn = { mod -> + ConstrainedSlot( + modifier = mod, + maxWidth = railSlotMaxWidth, + maxHeight = indicatorMaxHeight, + slot = original.indicatorColumn + ) + }, + 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 + ) + }, + pauseToggleButton = { mod -> + ConstrainedSlot( + modifier = mod, + maxWidth = secondaryActionMaxSize, + maxHeight = secondaryActionMaxSize, + slot = original.pauseToggleButton + ) + }, + audioToggleButton = { mod -> + ConstrainedSlot( + modifier = mod, + maxWidth = secondaryActionMaxSize, + maxHeight = secondaryActionMaxSize, + slot = original.audioToggleButton + ) + }, + shutterStack = if (originalShutterStack != null) { + { mod, _ -> + ConstrainedSlot( + modifier = mod, + maxWidth = railSlotMaxWidth, + maxHeight = shutterStackMaxHeight + ) { cappedMod -> + originalShutterStack(cappedMod, true) + } + } + } else { + null + }, + 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 + ) + }, + viewfinderTopStart = { mod -> + ConstrainedSlot( + modifier = mod, + maxWidth = centerHudMaxWidth, + maxHeight = secondaryActionMaxSize, + slot = original.viewfinderTopStart + ) + }, + viewfinderTopEnd = { mod -> + ConstrainedSlot( + modifier = mod, + maxWidth = centerHudMaxWidth, + maxHeight = secondaryActionMaxSize, + slot = original.viewfinderTopEnd + ) + }, + quickSettingsOverlay = { mod -> + ConstrainedSlot( + modifier = mod, + maxWidth = cardInnerMaxWidth, + maxHeight = cardInnerMaxHeight, + slot = original.quickSettingsOverlay + ) + } + ) +} + +@Composable +private fun CaptureSlotScope.ConstrainedSlot( + modifier: Modifier, + maxWidth: Dp, + maxHeight: Dp, + slot: @Composable CaptureSlotScope.(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 = "WideShort - Landscape (800x400dp)", + device = "spec:width=800dp,height=400dp", + showBackground = true +) +@Composable +private fun WideShortLandscapePreview() { + MaterialTheme { + WideShortLayout( + slots = PlaceholderCaptureSlots.sideRail( + isCompactHeight = true, + includePauseSlot = true, + includeElapsedTime = true + ), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + isRecording = true + ) + } +} + +@Preview( + name = "CompactShort - Multi-Window Square (360x360dp)", + device = "spec:width=360dp,height=360dp", + showBackground = true +) +@Composable +private fun CompactShortSquarePreview() { + MaterialTheme { + WideShortLayout( + slots = PlaceholderCaptureSlots.sideRail( + isCompactHeight = true, + includePauseSlot = true, + includeElapsedTime = true + ), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + isRecording = true + ) + } +} + +@Preview( + name = "WideShort - RTL Default Policy (800x400dp)", + device = "spec:width=800dp,height=400dp", + locale = "ar", + showBackground = true +) +@Composable +private fun WideShortRtlDefaultPolicyPreview() { + MaterialTheme { + CompositionLocalProvider( + LocalCaptureRtlPolicy provides CaptureRtlPolicy(mirrorSideRails = false) + ) { + WideShortLayout( + slots = PlaceholderCaptureSlots.sideRail( + isCompactHeight = true, + includeElapsedTime = true + ), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) } + ) + } + } +} + +@Preview( + name = "WideShort - RTL Mirrored Policy (800x400dp)", + device = "spec:width=800dp,height=400dp", + locale = "ar", + showBackground = true +) +@Composable +private fun WideShortRtlMirroredPolicyPreview() { + MaterialTheme { + CompositionLocalProvider( + LocalCaptureRtlPolicy provides CaptureRtlPolicy(mirrorSideRails = true) + ) { + WideShortLayout( + slots = PlaceholderCaptureSlots.sideRail( + isCompactHeight = true, + includeElapsedTime = true + ), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) } + ) + } + } +} diff --git a/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/TwoSideRailLayoutTest.kt b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/TwoSideRailLayoutTest.kt new file mode 100644 index 000000000..bf52e03a2 --- /dev/null +++ b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/TwoSideRailLayoutTest.kt @@ -0,0 +1,655 @@ +/* + * 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.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.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.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 [TwoSideRailLayout] and [CompactPortraitLayout] verifying full-bleed viewfinder + * geometry, [CaptureRtlPolicy] hand-placement vs. mirrored modes, live multi-window `statusBars` + * clearance, and in-hierarchy Quick Settings card behavior. + */ +@RunWith(RobolectricTestRunner::class) +@Config(qualifiers = "w852dp-h883dp") +class TwoSideRailLayoutTest { + + @get:Rule + val composeTestRule = createComposeRule() + + private fun boundsOf(tag: String): DpRect = + composeTestRule.onNodeWithTag(tag).getUnclippedBoundsInRoot() + + @Test + fun twoSideRailLayout_viewfinderIsFlushTopToBottom_andSideRailsOverlayEdges() { + var observedSolverSolution: CameraLayoutSolution? = null + + composeTestRule.setContent { + MaterialTheme { + TwoSideRailLayout( + slots = PlaceholderCaptureSlots.sideRail(includeElapsedTime = true), + viewfinder = { vfModifier -> + observedSolverSolution = LocalCameraLayoutSolution.current + Box( + modifier = vfModifier.testTag(PREVIEW_DISPLAY), + contentAlignment = Alignment.Center + ) { + Box( + modifier = Modifier + .aspectRatio(1f) + .testTag(SQUARE_PREVIEW_FRAME_TAG) + ) + } + } + ) + } + } + composeTestRule.waitForIdle() + + // Rail mode must not provide a portrait CameraLayoutSolver solution. + assertThat(observedSolverSolution).isNull() + + 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) + + // A 1:1 preview frame centers naturally inside the full-bleed background container. + val squareBounds = boundsOf(SQUARE_PREVIEW_FRAME_TAG) + val squareCenterY = (squareBounds.top.value + squareBounds.bottom.value) / 2f + assertThat(squareCenterY).isWithin(TOLERANCE).of(883f / 2f) + + // Start and End rails overlay the horizontal edges cleanly. + 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) + + // Elapsed time and capture mode carousel sit at the top/bottom center HUD rather than in + // EndSideRail. + 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 = "w1280dp-h800dp") + @Test + fun twoSideRailLayout_rtlPolicies_scopeRailPlacementAndRestoreLocaleDirectionInSlots() { + var layoutDirection by mutableStateOf(LayoutDirection.Ltr) + var rtlPolicy by mutableStateOf(CaptureRtlPolicy(mirrorSideRails = false)) + + val observedDirections = mutableMapOf() + val baseSlots = PlaceholderCaptureSlots.sideRail( + includeImageWell = true, + includePauseSlot = true, + includeElapsedTime = true + ) + val instrumentedSlots = baseSlots.copy( + indicatorColumn = { mod -> + observedDirections["indicatorColumn"] = LocalLayoutDirection.current + baseSlots.indicatorColumn(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) + }, + 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 + ) { + TwoSideRailLayout( + slots = instrumentedSlots, + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + isRecording = true + ) + } + } + } + composeTestRule.waitForIdle() + + 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, + AUDIO_INPUT_TOGGLE, + 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 preserve physical grip sides, + // while every inner slot receives LayoutDirection.Rtl! + observedDirections.clear() + layoutDirection = LayoutDirection.Rtl + rtlPolicy = CaptureRtlPolicy(mirrorSideRails = false, mirrorCompactBottomBar = 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(1280f) + 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 and EndSideRail swap + // horizontal sides while vertical Top -> Bottom order remains invariant! + observedDirections.clear() + rtlPolicy = CaptureRtlPolicy(mirrorSideRails = true, mirrorCompactBottomBar = true) + composeTestRule.waitForIdle() + + assertThat(boundsOf(START_SIDE_RAIL_TAG).right.value).isWithin(TOLERANCE).of(1280f) + assertThat(boundsOf(END_SIDE_RAIL_TAG).left.value).isWithin(TOLERANCE).of(0f) + 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)) + 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 -> PlaceholderViewfinder(modifier = mod) } + ) + } + } + } + composeTestRule.waitForIdle() + + 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 } + + // Default RTL policy: bottom rows stay unmirrored (ImageWell left, Flip right, Quick + // Settings left) while every child slot receives LayoutDirection.Rtl! + 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]) + } + + // Mirrored RTL policy: CaptureRow and BottomToolbar reflect horizontally while vertical + // Top -> Bottom order remains invariant! + 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 twoSideRailLayout_statusBarsInsets_clearsVisibleBarAndZeroPadsWhenHidden() { + lateinit var hostView: View + composeTestRule.setContent { + hostView = LocalView.current + MaterialTheme { + TwoSideRailLayout( + slots = PlaceholderCaptureSlots.sideRail(includeElapsedTime = true), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + screenFlashOverlay = { mod -> + Box(modifier = mod.fillMaxSize().testTag(SCREEN_FLASH_OVERLAY)) + } + ) + } + } + + // 1. Multi-window visible status bar (32px == 32dp at Robolectric default mdpi): + // rails and indicators clear >= 32dp while viewfinder and screen flash stay full-bleed. + 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) + + // 2. Immersive hidden status bar (0px live, 32px ignoring visibility): + // live WindowInsets.systemBars must collapse rail top offset to 0dp! + 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) + } + + @Config(qualifiers = "w1280dp-h800dp") + @Test + fun twoSideRailLayout_quickSettingsFloatingCard_isInHierarchyAndDismissesOnScrimClick() { + var isQuickSettingsOpen by mutableStateOf(false) + var overlayDirection: LayoutDirection? = null + var rtlPolicy by mutableStateOf(CaptureRtlPolicy(mirrorSideRails = false)) + + val baseSlots = PlaceholderCaptureSlots.default() + val instrumentedSlots = baseSlots.copy( + quickSettingsOverlay = { mod -> + overlayDirection = LocalLayoutDirection.current + baseSlots.quickSettingsOverlay(this, mod) + } + ) + + composeTestRule.setContent { + MaterialTheme { + CompositionLocalProvider( + LocalLayoutDirection provides LayoutDirection.Rtl, + LocalCaptureRtlPolicy provides rtlPolicy + ) { + TwoSideRailLayout( + slots = instrumentedSlots, + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + isQuickSettingsOpen = isQuickSettingsOpen, + onDismissQuickSettings = { isQuickSettingsOpen = false } + ) + } + } + } + composeTestRule.waitForIdle() + + composeTestRule.onNodeWithTag(QUICK_SETTINGS_BOTTOM_SHEET).assertDoesNotExist() + composeTestRule.onNodeWithTag(QUICK_SETTINGS_SCRIM).assertDoesNotExist() + composeTestRule.onNodeWithTag(CAPTURE_BUTTON).assertIsDisplayed() + + // Open Quick Settings floating card. + isQuickSettingsOpen = true + composeTestRule.waitForIdle() + + composeTestRule.onNodeWithTag(QUICK_SETTINGS_BOTTOM_SHEET) + .assertIsDisplayed() + .assert(!isPopup()) + .assert(!isDialog()) + .assert(!hasAnyAncestor(isPopup())) + .assert(!hasAnyAncestor(isDialog())) + assertThat(overlayDirection).isEqualTo(LayoutDirection.Rtl) + + // Default RTL policy anchors the floating card to BottomLeft matching StartSideRail. + val unmirroredCardBounds = boundsOf(QUICK_SETTINGS_BOTTOM_SHEET) + assertThat(unmirroredCardBounds.right.value).isLessThan(1280f / 2f) + + // Mirrored RTL policy anchors the floating card to BottomStart (physical right in RTL). + rtlPolicy = CaptureRtlPolicy(mirrorSideRails = true) + composeTestRule.waitForIdle() + val mirroredCardBounds = boundsOf(QUICK_SETTINGS_BOTTOM_SHEET) + assertThat(mirroredCardBounds.left.value).isGreaterThan(1280f / 2f) + + // Background camera chrome semantics are suppressed while modal card is open. + assertThat( + composeTestRule.onAllNodesWithTag(CAPTURE_BUTTON).fetchSemanticsNodes() + ).isEmpty() + + // Clicking the scrim dismisses Quick Settings and restores background semantics. + composeTestRule.onNodeWithTag(QUICK_SETTINGS_SCRIM) + .assertIsDisplayed() + .performClick() + composeTestRule.waitForIdle() + + assertThat(isQuickSettingsOpen).isFalse() + composeTestRule.onNodeWithTag(QUICK_SETTINGS_BOTTOM_SHEET).assertDoesNotExist() + composeTestRule.onNodeWithTag(CAPTURE_BUTTON).assertIsDisplayed() + } + + @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() + + // Default policy in VerticalMaterialControls fallback keeps ImageWell left and Flip right. + 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) + + // Mirrored policy reflects horizontal placement in VerticalMaterialControls fallback. + 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) + + // Visible multi-window status bar clears indicatorRow in non-handheld fallback too. + 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 twoSideRailLayout_tagQuickSettingsCardFalse_avoidsDuplicateSheetTagsAndErrorSuppressesBg() { + var isQuickSettingsOpen by mutableStateOf(true) + var isErrorDialogShowing by mutableStateOf(false) + + val slotsWithInnerSheetTag = PlaceholderCaptureSlots.sideRail( + tagQuickSettingsOverlay = true, + includeErrorDialog = true + ) + + composeTestRule.setContent { + MaterialTheme { + TwoSideRailLayout( + slots = slotsWithInnerSheetTag, + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + isQuickSettingsOpen = isQuickSettingsOpen, + isErrorDialogShowing = isErrorDialogShowing, + tagQuickSettingsCard = false, + onDismissQuickSettings = { isQuickSettingsOpen = false } + ) + } + } + composeTestRule.waitForIdle() + + // Exactly one QUICK_SETTINGS_BOTTOM_SHEET node exists (owned by inner overlay). + assertThat( + composeTestRule.onAllNodesWithTag(QUICK_SETTINGS_BOTTOM_SHEET).fetchSemanticsNodes() + ).hasSize(1) + + // Close Quick Settings and show error dialog: background controls are suppressed while + // CAMERA_ERROR_DIALOG_TAG is displayed. + isQuickSettingsOpen = false + isErrorDialogShowing = true + composeTestRule.waitForIdle() + + composeTestRule.onNodeWithTag(CAMERA_ERROR_DIALOG_TAG).assertIsDisplayed() + assertThat( + composeTestRule.onAllNodesWithTag(CAPTURE_BUTTON).fetchSemanticsNodes() + ).isEmpty() + } + + 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 + } +} diff --git a/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/WideShortLayoutTest.kt b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/WideShortLayoutTest.kt new file mode 100644 index 000000000..c1deaa9e4 --- /dev/null +++ b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/WideShortLayoutTest.kt @@ -0,0 +1,413 @@ +/* + * 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.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.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.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.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 [WideShortLayout] across `WIDE_SHORT` (`800x400dp`), `COMPACT_SHORT` + * (`360x360dp`), RTL policies, and visible multi-window `statusBars` insets, asserting zero + * clipping and zero vertical overlap in both rails. + */ +@RunWith(RobolectricTestRunner::class) +@Config(qualifiers = "w800dp-h400dp") +class WideShortLayoutTest { + + @get:Rule + val composeTestRule = createComposeRule() + + private fun boundsOf(tag: String): DpRect = + composeTestRule.onNodeWithTag(tag).getUnclippedBoundsInRoot() + + @Test + fun wideShortLayout_at800x400_fitsAllControlsWithoutClippingOrVerticalOverlap() { + composeTestRule.setContent { + MaterialTheme { + WideShortLayout( + slots = PlaceholderCaptureSlots.sideRail( + isCompactHeight = false, + includeImageWell = true, + includePauseSlot = true, + includeElapsedTime = true + ), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + isRecording = true + ) + } + } + composeTestRule.waitForIdle() + + 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(800f) + assertThat(viewfinderBounds.bottom.value).isWithin(TOLERANCE).of(400f) + + assertNoClippingAndNoOverlapInWindow( + contextLabel = "WIDE_SHORT 800x400", + windowWidth = 800f, + windowHeight = 400f, + minTop = 0f + ) + } + + @Config(qualifiers = "w360dp-h360dp") + @Test + fun wideShortLayout_at360x360_fitsAllControlsWithoutClippingOrVerticalOverlap() { + composeTestRule.setContent { + MaterialTheme { + WideShortLayout( + slots = PlaceholderCaptureSlots.sideRail( + isCompactHeight = false, + includeImageWell = true, + includePauseSlot = true, + includeElapsedTime = true + ), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + isRecording = true + ) + } + } + composeTestRule.waitForIdle() + + val viewfinderBounds = boundsOf(PREVIEW_DISPLAY) + assertThat(viewfinderBounds.top.value).isWithin(TOLERANCE).of(0f) + assertThat(viewfinderBounds.bottom.value).isWithin(TOLERANCE).of(360f) + + assertNoClippingAndNoOverlapInWindow( + contextLabel = "COMPACT_SHORT 360x360", + windowWidth = 360f, + windowHeight = 360f, + minTop = 0f + ) + + // StartSideRail, center HUD, and EndSideRail must not horizontally collide even at 360dp. + 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) + } + + @Test + fun wideShortLayout_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, + includePauseSlot = true, + includeElapsedTime = true + ) + val instrumentedSlots = baseSlots.copy( + indicatorColumn = { mod -> + observedDirections["indicatorColumn"] = LocalLayoutDirection.current + baseSlots.indicatorColumn(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 + ) { + WideShortLayout( + slots = instrumentedSlots, + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + isRecording = true + ) + } + } + } + composeTestRule.waitForIdle() + + val ltrStartTops = START_RAIL_TAGS.map { boundsOf(it).top.value } + val ltrEndTops = END_RAIL_TAGS.map { boundsOf(it).top.value } + + // Default RTL policy: rails stay on physical left/right while child slots observe RTL. + 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(800f) + 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]) + } + + // Mirrored RTL policy: rails swap horizontally while vertical bounds stay identical. + observedDirections.clear() + rtlPolicy = CaptureRtlPolicy(mirrorSideRails = true) + composeTestRule.waitForIdle() + + assertThat(boundsOf(START_SIDE_RAIL_TAG).right.value).isWithin(TOLERANCE).of(800f) + assertThat(boundsOf(END_SIDE_RAIL_TAG).left.value).isWithin(TOLERANCE).of(0f) + assertNoClippingAndNoOverlapInWindow( + contextLabel = "WIDE_SHORT 800x400 RTL Mirrored", + windowWidth = 800f, + 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]) + } + } + + @Config(qualifiers = "w360dp-h360dp") + @Test + fun wideShortLayout_withMultiWindowVisibleStatusBars_clearsBarAndFits360x360WithoutOverlap() { + lateinit var hostView: View + composeTestRule.setContent { + hostView = LocalView.current + MaterialTheme { + WideShortLayout( + slots = PlaceholderCaptureSlots.sideRail( + isCompactHeight = false, + includeImageWell = true, + includePauseSlot = true, + includeElapsedTime = true + ), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + isRecording = true + ) + } + } + + dispatchStatusBarInsets( + view = hostView, + statusBarHeightPx = MULTI_WINDOW_STATUS_BAR_PX, + visible = true + ) + composeTestRule.waitForIdle() + + // Viewfinder stays flush [0..360] while rails and all child slots fit in [32..360] with + // zero clipping and zero vertical overlap! + 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 + ) + + // Hiding the status bar collapses rail top padding back to 0dp. + 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) + } + + @Config(qualifiers = "w360dp-h360dp") + @Test + fun wideShortLayout_quickSettingsFloatingCard_displaysInHierarchyWithinCondensedBounds() { + var isQuickSettingsOpen by mutableStateOf(true) + composeTestRule.setContent { + MaterialTheme { + WideShortLayout( + slots = PlaceholderCaptureSlots.default(), + viewfinder = { mod -> PlaceholderViewfinder(modifier = mod) }, + isQuickSettingsOpen = isQuickSettingsOpen, + onDismissQuickSettings = { isQuickSettingsOpen = false } + ) + } + } + composeTestRule.waitForIdle() + + composeTestRule.onNodeWithTag(QUICK_SETTINGS_BOTTOM_SHEET) + .assertIsDisplayed() + .assert(!isPopup()) + .assert(!isDialog()) + .assert(!hasAnyAncestor(isPopup())) + .assert(!hasAnyAncestor(isDialog())) + + val cardBounds = boundsOf(QUICK_SETTINGS_BOTTOM_SHEET) + assertThat(cardBounds.left.value).isAtLeast(0f - TOLERANCE) + assertThat(cardBounds.right.value).isAtMost(360f + TOLERANCE) + assertThat(cardBounds.top.value).isAtLeast(0f - TOLERANCE) + assertThat(cardBounds.bottom.value).isAtMost(360f + TOLERANCE) + + composeTestRule.onNodeWithTag(QUICK_SETTINGS_SCRIM).performClick() + composeTestRule.waitForIdle() + assertThat(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, + AUDIO_INPUT_TOGGLE, + 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 + } +} From 93cf6e8f1ddee3fe9e497da7b8f9618390f392db Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Fri, 13 Nov 2026 08:50:14 -0800 Subject: [PATCH 3/3] refactor(ui/capture): address PR review feedback on posture layouts --- .../capture/CompactPortraitLayout.kt | 3 + .../capture/SideRailCaptureLayouts.kt | 89 +++++++++---------- 2 files changed, 47 insertions(+), 45 deletions(-) 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 index 690dd713c..0a8f91444 100644 --- 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 @@ -104,6 +104,9 @@ import com.google.jetpackcamera.ui.components.capture.layout.LocalCameraLayoutSo val LocalActiveCaptureLayout: ProvidableCompositionLocal = compositionLocalOf { "CompactPortraitLayout" } +/** + * Dimension and spacing constants used by [CompactPortraitLayout]. + */ internal object CompactPortraitTokens { val SheetPeekHeight = 0.dp val SheetTopCornerRadius = 28.dp 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 index 21e1a0481..8831e502b 100644 --- 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 @@ -64,6 +64,7 @@ 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 @@ -74,6 +75,10 @@ import androidx.compose.ui.unit.max // 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, @@ -89,6 +94,9 @@ internal data class SideRailPostureConfig( 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 @@ -320,51 +328,39 @@ internal fun SideRailCaptureScaffold( if (controlsVisible) { CompositionLocalProvider(LocalLayoutDirection provides railContainerDirection) { Box(modifier = Modifier.fillMaxSize()) { - Box( - modifier = Modifier - .align(Alignment.CenterStart) - .fillMaxHeight() - .onSizeChanged { startRailWidthPx = it.width } - .suppressBackgroundForModal(isModalOpen) + CompositionLocalProvider( + LocalLayoutDirection provides localeDirection ) { - CompositionLocalProvider( - LocalLayoutDirection provides localeDirection - ) { - StartSideRail( - slots = slots, - modifier = Modifier.fillMaxHeight(), - isCompactHeight = config.isCompactHeight, - topPadding = config.railTopPadding, - bottomPadding = config.railBottomPadding, - horizontalPadding = config.railHorizontalPadding, - minSectionGap = config.railMinSectionGap, - centerVerticalFraction = config.centerVerticalFraction - ) - } - } - - Box( - modifier = Modifier - .align(Alignment.CenterEnd) - .fillMaxHeight() - .onSizeChanged { endRailWidthPx = it.width } - .suppressBackgroundForModal(isModalOpen) - ) { - CompositionLocalProvider( - LocalLayoutDirection provides localeDirection - ) { - EndSideRail( - slots = slots, - modifier = Modifier.fillMaxHeight(), - isCompactHeight = config.isCompactHeight, - showElapsedTimeInRail = false, - topPadding = config.railTopPadding, - bottomPadding = config.railBottomPadding, - horizontalPadding = config.railHorizontalPadding, - minSectionGap = config.railMinSectionGap, - centerVerticalFraction = config.centerVerticalFraction - ) - } + 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 + ) } } } @@ -538,7 +534,10 @@ private fun QuickSettingsOverlayCardPlaceholder( .fillMaxSize() .background(SideRailTokens.QuickSettingsScrimColor) .testTag(QUICK_SETTINGS_SCRIM) - .semantics { contentDescription = dismissLabel } + .semantics { + contentDescription = dismissLabel + traversalIndex = 1f + } .clickable( role = Role.Button, interactionSource = remember { MutableInteractionSource() },