feat: blur for camera UI panels

This commit is contained in:
zhoubinjia committed 2026-11-20 12:43:33 +08:00
1 parent fc878f22f4
commit 7ef15e5744
10 files changed
+649 -233

No files matched your search

@@ -0,0 +1,127 @@
package com.hinnka.mycamera.ui.camera
import android.graphics.Bitmap
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.view.PixelCopy
import android.view.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.unit.IntSize
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.compose.currentStateAsState
import com.hinnka.mycamera.ui.components.LiquidGlassBackdrop
import com.hinnka.mycamera.ui.components.LiquidGlassImageFrame
import com.hinnka.mycamera.ui.components.rememberLiquidGlassImageBackdrop
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
import kotlin.math.roundToInt
private const val BackdropLongEdge = 256
private const val BackdropFrameIntervalMillis = 40L
/**
* Samples the camera's separate SurfaceView for the sheet materials while it is visible.
* The sampled frames are only drawn inside the panels, leaving the viewfinder itself unchanged.
*/
@Composable
internal fun rememberCameraPanelBackdrop(
surfaceView: CameraGLSurfaceView?,
enabled: Boolean,
): LiquidGlassBackdrop {
val backdrop = rememberLiquidGlassImageBackdrop()
val rootView = LocalView.current
val lifecycleState by LocalLifecycleOwner.current.lifecycle.currentStateAsState()
val captureEnabled = enabled && lifecycleState.isAtLeast(Lifecycle.State.RESUMED) &&
Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
val captureMutex = remember { Mutex() }
LaunchedEffect(backdrop, captureEnabled, surfaceView, rootView) {
backdrop.imageFrame = null
if (!captureEnabled || surfaceView == null) return@LaunchedEffect
val handler = Handler(Looper.getMainLooper())
val previewLocation = IntArray(2)
val rootLocation = IntArray(2)
// Keep ownership until an in-flight PixelCopy finishes, even if this effect is cancelled.
captureMutex.withLock {
while (isActive) {
val startedAt = SystemClock.uptimeMillis()
val width = surfaceView.width
val height = surfaceView.height
val surface = surfaceView.holder.surface
if (!surfaceView.isAttachedToWindow || !surface.isValid ||
width <= 0 || height <= 0
) {
backdrop.imageFrame = null
} else {
val bitmap = surface.copyBackdropFrame(width, height, handler)
if (bitmap != null && surfaceView.isAttachedToWindow && surface.isValid &&
surfaceView.width == width && surfaceView.height == height
) {
surfaceView.getLocationInWindow(previewLocation)
rootView.getLocationInWindow(rootLocation)
backdrop.imageFrame = LiquidGlassImageFrame(
image = bitmap.asImageBitmap(),
positionInRoot = Offset(
(previewLocation[0] - rootLocation[0]).toFloat(),
(previewLocation[1] - rootLocation[1]).toFloat(),
),
size = IntSize(width, height),
)
} else {
bitmap?.recycle()
backdrop.imageFrame = null
}
}
val elapsed = SystemClock.uptimeMillis() - startedAt
delay((BackdropFrameIntervalMillis - elapsed).coerceAtLeast(1L))
}
}
}
return backdrop
}
private suspend fun Surface.copyBackdropFrame(
width: Int,
height: Int,
handler: Handler,
): Bitmap? {
val scale = minOf(1f, BackdropLongEdge.toFloat() / maxOf(width, height))
val bitmap = Bitmap.createBitmap(
(width * scale).roundToInt().coerceAtLeast(1),
(height * scale).roundToInt().coerceAtLeast(1),
Bitmap.Config.ARGB_8888,
)
var delivered = false
try {
// Older Android releases copy synchronously before posting the callback.
val result = withContext(Dispatchers.IO) {
// The bitmap is still in use by PixelCopy until the callback arrives.
suspendCoroutine { continuation ->
PixelCopy.request(this@copyBackdropFrame, bitmap, { continuation.resume(it) }, handler)
}
}
delivered = result == PixelCopy.SUCCESS
return bitmap.takeIf { delivered }
} catch (_: IllegalArgumentException) {
// The surface can disappear between the validity check and the copy request.
return null
} finally {
if (!delivered) bitmap.recycle()
}
}
@@ -0,0 +1,145 @@
package com.hinnka.mycamera.ui.camera
import androidx.activity.compose.BackHandler
import androidx.compose.animation.core.tween
import androidx.compose.foundation.gestures.AnchoredDraggableState
import androidx.compose.foundation.gestures.DraggableAnchors
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.anchoredDraggable
import androidx.compose.foundation.gestures.animateTo
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.displayCutout
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.layout.statusBarsIgnoringVisibility
import androidx.compose.foundation.layout.union
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.material3.LocalContentColor
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.semantics.dismiss
import androidx.compose.ui.semantics.isTraversalGroup
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import com.hinnka.mycamera.ui.components.CameraPanelGlassStyle
import com.hinnka.mycamera.ui.components.LiquidGlassBackdrop
import com.hinnka.mycamera.ui.components.liquidGlassBackground
import kotlin.math.roundToInt
import kotlinx.coroutines.flow.first
private val CameraPanelMaxHeight = 544.dp
private enum class PanelAnchor { Open, Closed }
@OptIn(ExperimentalLayoutApi::class)
@Composable
internal fun CameraPanelBottomSheet(
backdrop: LiquidGlassBackdrop,
onDismissRequest: () -> Unit,
modifier: Modifier = Modifier,
dragHandle: @Composable (() -> Unit)? = null,
content: @Composable ColumnScope.() -> Unit,
) {
val dragState = remember { AnchoredDraggableState(PanelAnchor.Closed) }
val currentOnDismissRequest by rememberUpdatedState(onDismissRequest)
var opened by remember { mutableStateOf(false) }
var closing by remember { mutableStateOf(false) }
fun dismissPanel() {
if (closing) return
closing = true
if (!opened) {
currentOnDismissRequest()
}
}
val dismissOnTap by rememberUpdatedState(::dismissPanel)
LaunchedEffect(dragState) {
snapshotFlow { dragState.offset.isFinite() }.first { it }
dragState.animateTo(PanelAnchor.Open, tween(250))
opened = true
snapshotFlow { dragState.settledValue }.first { it == PanelAnchor.Closed }
currentOnDismissRequest()
}
LaunchedEffect(closing) {
if (closing && opened) {
dragState.animateTo(PanelAnchor.Closed, tween(220))
}
}
BackHandler(onBack = ::dismissPanel)
Box(Modifier.fillMaxSize().clipToBounds()) {
Box(Modifier.matchParentSize().pointerInput(Unit) {
detectTapGestures { dismissOnTap() }
})
Column(
modifier = modifier
.align(Alignment.BottomCenter)
.windowInsetsPadding(WindowInsets.safeDrawing.only(WindowInsetsSides.Horizontal))
.windowInsetsPadding(
WindowInsets.statusBarsIgnoringVisibility.union(WindowInsets.displayCutout)
.only(WindowInsetsSides.Top)
)
.imePadding()
.fillMaxWidth()
.heightIn(max = CameraPanelMaxHeight)
.offset { IntOffset(0, dragState.offset.takeIf { it.isFinite() }?.roundToInt() ?: 0) }
.onSizeChanged { size ->
dragState.updateAnchors(
DraggableAnchors {
PanelAnchor.Open at 0f
PanelAnchor.Closed at size.height.toFloat()
},
newTarget = dragState.targetValue
)
}
.anchoredDraggable(dragState, Orientation.Vertical, enabled = opened && !closing)
.liquidGlassBackground(
backdrop = backdrop,
cornerRadius = 28.dp,
openBottomEdge = true,
style = CameraPanelGlassStyle
)
.semantics {
isTraversalGroup = true
dismiss {
dismissPanel()
true
}
}
.windowInsetsPadding(WindowInsets.safeDrawing.only(WindowInsetsSides.Bottom)),
) {
CompositionLocalProvider(LocalContentColor provides Color.White) {
if (dragHandle != null) {
Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) { dragHandle() }
}
content()
}
}
}
}
@@ -191,7 +191,6 @@ private fun Bitmap.recycleIfAlive() {
private fun PanelDismissPreviewOverlay(
bounds: Rect?,
parentBounds: Rect?,
dimBackground: Boolean,
onDismiss: () -> Unit,
modifier: Modifier = Modifier
) {
@@ -214,13 +213,6 @@ private fun PanelDismissPreviewOverlay(
)
}
.size(width = width, height = height)
.then(
if (dimBackground) {
Modifier.background(Color.Black.copy(alpha = 0.4f))
} else {
Modifier
}
)
.pointerInput(Unit) {
detectTapGestures {
currentOnDismiss()
@@ -350,6 +342,7 @@ fun CameraScreen(
// Surface may become ready while persisted camera settings are still being restored.
// Retain the exact instance and open only after initialization has completed.
var previewSurfaceTexture by remember { mutableStateOf<SurfaceTexture?>(null) }
var previewSurfaceView by remember { mutableStateOf<CameraGLSurfaceView?>(null) }
var isCameraPrepared by remember { mutableStateOf(false) }
LaunchedEffect(isCameraInitialized) {
@@ -368,6 +361,13 @@ fun CameraScreen(
// UI State
var activePanel by remember { mutableStateOf(ActivePanel.NONE) }
fun closeRecipeEditor() {
discardTransientLookEdits()
activePanel = ActivePanel.FILTERS
}
LaunchedEffect(activePanel, canEditCurrentLut) {
if (activePanel == ActivePanel.EDIT && !canEditCurrentLut) closeRecipeEditor()
}
val filterPanelTransition = updateTransition(
targetState = activePanel == ActivePanel.FILTERS,
label = "cameraFilterPanel"
@@ -375,10 +375,17 @@ fun CameraScreen(
val settingsPanelVisibility = remember { MutableTransitionState(false) }.apply {
targetState = activePanel == ActivePanel.SETTINGS
}
// Restore controls only after both the panel exit and its size transition have settled.
val showNormalControls = activePanel == ActivePanel.NONE &&
!filterPanelTransition.currentState && !filterPanelTransition.targetState && !filterPanelTransition.isRunning &&
settingsPanelVisibility.isIdle && !settingsPanelVisibility.currentState && !settingsPanelVisibility.targetState
// The look browser changes the space below the viewfinder. Quick settings overlay it from above.
val filterPanelVisible = filterPanelTransition.currentState ||
filterPanelTransition.targetState || filterPanelTransition.isRunning
val showShootingControls = (activePanel == ActivePanel.NONE || activePanel == ActivePanel.SETTINGS) &&
!filterPanelVisible
val glassPanelVisible = activePanel != ActivePanel.NONE || filterPanelVisible ||
settingsPanelVisibility.currentState || !settingsPanelVisibility.isIdle
val panelBackdrop = rememberCameraPanelBackdrop(
surfaceView = previewSurfaceView,
enabled = state.isPreviewActive && glassPanelVisible,
)
val meteringModeFeedback = rememberMeteringModeFeedbackState()
fun updateMeteringMode(mode: MeteringMode) {
viewModel.setMeteringMode(mode)
@@ -1017,11 +1024,11 @@ fun CameraScreen(
}
val zoomBar = @Composable {
if (!showNormalControls || isXpan) {
if (!showShootingControls || isXpan) {
SideEffect { zoomBarBounds = null }
}
AnimatedVisibility(
visible = showNormalControls && !isXpan,
visible = showShootingControls && !isXpan,
enter = fadeIn(tween(120)),
exit = ExitTransition.None
) {
@@ -1376,6 +1383,7 @@ fun CameraScreen(
},
onFirstPreviewFrame = viewModel::onFirstPreviewFrame,
onGLSurfaceViewReady = {
previewSurfaceView = it
viewModel.glSurfaceView = it
},
livePhotoRecorder = viewModel.livePhotoRecorder,
@@ -1714,6 +1722,7 @@ fun CameraScreen(
onExpandedChange = { expanded ->
if (expanded) filtersExpanded = true else collapseFilters()
},
cameraBackdrop = panelBackdrop,
modifier = Modifier
.fillMaxWidth()
.pointerInput(Unit) { detectTapGestures { } }
@@ -1785,10 +1794,15 @@ fun CameraScreen(
)
}
Box(
Modifier
.matchParentSize()
.liquidGlassBackdropSource(panelBackdrop)
.paint(backgroundPainter, contentScale = ContentScale.Crop)
)
Box(
modifier = Modifier
.fillMaxSize()
.paint(backgroundPainter, contentScale = ContentScale.Crop)
.navigationBarsPadding(),
) {
// The viewfinder is always the bottom layer. Its selected aspect ratio is fitted
@@ -1816,12 +1830,18 @@ fun CameraScreen(
)
}
// Keep dismissal behind the controls, including the inline look browser.
if (activePanel == ActivePanel.FILTERS) {
// Keep dismissal below shooting controls, including the XPAN side bars for settings.
if (activePanel == ActivePanel.FILTERS || activePanel == ActivePanel.SETTINGS ||
activePanel == ActivePanel.PRESETS
) {
val dismissBounds = if (isXpan && activePanel != ActivePanel.SETTINGS) {
viewfinderAreaBounds ?: previewBounds
} else {
previewBounds
}
PanelDismissPreviewOverlay(
bounds = if (isXpan) viewfinderAreaBounds ?: previewBounds else previewBounds,
bounds = dismissBounds,
parentBounds = cameraScreenBounds,
dimBackground = false,
onDismiss = { activePanel = ActivePanel.NONE }
)
}
@@ -1865,7 +1885,7 @@ fun CameraScreen(
},
parameterBar = {
AnimatedVisibility(
visible = showNormalControls && !isXpan,
visible = showShootingControls && !isXpan,
enter = fadeIn(tween(120)),
exit = ExitTransition.None
) {
@@ -1877,24 +1897,10 @@ fun CameraScreen(
}
)
}
val panelDismissBounds = if (isXpan) {
viewfinderAreaBounds ?: previewBounds
} else {
previewBounds
}
if (activePanel != ActivePanel.NONE && activePanel != ActivePanel.FILTERS) {
PanelDismissPreviewOverlay(
bounds = panelDismissBounds,
parentBounds = cameraScreenBounds,
dimBackground = activePanel == ActivePanel.SETTINGS,
onDismiss = { activePanel = ActivePanel.NONE }
)
}
// TopSheet for settings
CameraTopSheet(
visible = activePanel == ActivePanel.SETTINGS,
backdrop = panelBackdrop,
visibilityState = settingsPanelVisibility,
captureMode = state.captureMode,
aspectRatio = state.aspectRatio,
@@ -1998,10 +2004,8 @@ fun CameraScreen(
initialParams = previewRecipeParams,
onParamsPreviewChange = { previewRecipeParamsOverride = it },
showEffects = true,
onDismiss = {
previewRecipeParamsOverride = null
activePanel = ActivePanel.FILTERS
}
backdrop = panelBackdrop,
onDismiss = ::closeRecipeEditor,
)
}
}
@@ -59,9 +59,11 @@ import com.hinnka.mycamera.raw.HncsFilmCurveMode
import com.hinnka.mycamera.raw.RawRenderingEngine
import com.hinnka.mycamera.raw.RawToneMappingParameters
import com.hinnka.mycamera.raw.SpectralFilmSelection
import com.hinnka.mycamera.ui.components.AppModalBottomSheet
import com.hinnka.mycamera.ui.components.CameraPanelGlassStyle
import com.hinnka.mycamera.ui.components.LiquidGlassBackdrop
import com.hinnka.mycamera.ui.components.RawDcpLensOption
import com.hinnka.mycamera.ui.components.RawRenderingEngineSettingsPanel
import com.hinnka.mycamera.ui.components.liquidGlassBackground
import com.hinnka.mycamera.video.*
import com.hinnka.mycamera.video.VideoCodec
import com.hinnka.mycamera.ui.icons.AppIcons
@@ -92,6 +94,7 @@ private object QuickSettingDropdownScrollConnection : NestedScrollConnection {
@Composable
fun CameraTopSheet(
visible: Boolean,
backdrop: LiquidGlassBackdrop,
captureMode: CaptureMode,
aspectRatio: AspectRatio,
topSheetAspectRatios: List<AspectRatio>,
@@ -167,7 +170,10 @@ fun CameraTopSheet(
LaunchedEffect(visible, captureMode) {
showContentManagementOptions = false
if (!visible) expandedMenu = null
if (!visible) {
expandedMenu = null
showRenderingEngineSheet = false
}
}
BackHandler(enabled = visible && expandedMenu != null) { expandedMenu = null }
@@ -180,8 +186,9 @@ fun CameraTopSheet(
AnimatedVisibility(
visibleState = panelVisibility,
enter = slideInVertically(initialOffsetY = { -it }) + fadeIn(),
exit = slideOutVertically(targetOffsetY = { -it }) + fadeOut(),
// Reveal the sheet at its final coordinates so the glass samples a stationary area.
enter = expandVertically(expandFrom = Alignment.Top),
exit = shrinkVertically(shrinkTowards = Alignment.Top),
modifier = modifier
) {
val panelScrollState = rememberScrollState()
@@ -194,7 +201,11 @@ fun CameraTopSheet(
.fillMaxWidth()
.aspectRatio(1f)
.clip(RoundedCornerShape(bottomStart = 24.dp, bottomEnd = 24.dp))
.background(Color.Black.copy(alpha = 0.88f))
.liquidGlassBackground(
backdrop = backdrop,
openTopEdge = true,
style = CameraPanelGlassStyle,
)
// Keep the screen's top inset fixed, but measure content and side padding
// in the rotated viewport so landscape controls stay inside the sheet.
.padding(top = contentTopPadding)
@@ -417,8 +428,9 @@ fun CameraTopSheet(
}
}
if (showRenderingEngineSheet) {
AppModalBottomSheet(
if (visible && showRenderingEngineSheet) {
CameraPanelBottomSheet(
backdrop = backdrop,
onDismissRequest = { showRenderingEngineSheet = false },
dragHandle = { BottomSheetDefaults.DragHandle(color = Color.White.copy(alpha = 0.2f)) }
) {
@@ -1,21 +1,26 @@
package com.hinnka.mycamera.ui.camera
import com.hinnka.mycamera.ui.components.AppModalBottomSheet
import com.hinnka.mycamera.ui.components.AppSheetStyle
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.hinnka.mycamera.lut.BaselineColorCorrectionTarget
import com.hinnka.mycamera.model.ColorRecipeParams
import com.hinnka.mycamera.model.toEffectParams
import com.hinnka.mycamera.ui.components.AppModalBottomSheet
import com.hinnka.mycamera.ui.components.AppSheetStyle
import com.hinnka.mycamera.ui.components.ColorRecipePanel
import com.hinnka.mycamera.ui.components.CurveChannel
import com.hinnka.mycamera.ui.components.DefaultColorRecipePanelContainerColor
import com.hinnka.mycamera.ui.components.ImageHistogram
import com.hinnka.mycamera.ui.components.LiquidGlassBackdrop
import com.hinnka.mycamera.viewmodel.LutEditViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
@@ -40,10 +45,10 @@ fun LutEditBottomSheet(
showEffects: Boolean = false,
editorTarget: LutEditorTarget = LutEditorTarget.CREATIVE_GLOBAL,
containerColor: Color = Color.Transparent,
modifier: Modifier = Modifier
modifier: Modifier = Modifier,
backdrop: LiquidGlassBackdrop? = null,
) {
val lutEditViewModel: LutEditViewModel = viewModel()
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
val coroutineScope = rememberCoroutineScope()
var editingParams by remember { mutableStateOf(ColorRecipeParams.DEFAULT) }
@@ -91,57 +96,64 @@ fun LutEditBottomSheet(
}
}
AppModalBottomSheet(
containerColor = containerColor,
style = AppSheetStyle.Translucent,
onDismissRequest = {
flushLutSave()
onDismiss()
},
sheetState = sheetState,
modifier = modifier,
dragHandle = null,
) {
Column(
modifier = Modifier
.fillMaxWidth()
.navigationBarsPadding()
val dismissEditor: () -> Unit = {
flushLutSave()
onDismiss()
}
val editorContent: @Composable (Modifier) -> Unit = { contentModifier ->
ColorRecipePanel(
currentParams = editingParams,
onParamChange = { param, value ->
onParamsUpdated(param.setValue(editingParams, value))
},
onParamsChange = ::onParamsUpdated,
onRemarksChange = {
onParamsUpdated(editingParams.copy(remarks = it))
},
onCurveChange = { channel, points ->
onParamsUpdated(
when (channel) {
CurveChannel.MASTER -> editingParams.copy(masterCurvePoints = points)
CurveChannel.RED -> editingParams.copy(redCurvePoints = points)
CurveChannel.GREEN -> editingParams.copy(greenCurvePoints = points)
CurveChannel.BLUE -> editingParams.copy(blueCurvePoints = points)
}
)
},
imageHistogram = imageHistogram,
showLutIntensity = editorTarget == LutEditorTarget.CREATIVE_GLOBAL && lutId != "none",
currentEffects = editingParams.toEffectParams().takeIf { showEffects },
onEffectsChange = if (showEffects) {
{ effects -> onParamsUpdated(effects.applyTo(editingParams)) }
} else {
null
},
containerColor = if (backdrop != null) Color.Transparent else DefaultColorRecipePanelContainerColor,
modifier = contentModifier
)
}
if (backdrop == null) {
AppModalBottomSheet(
containerColor = containerColor,
style = AppSheetStyle.Translucent,
onDismissRequest = dismissEditor,
sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true),
modifier = modifier,
dragHandle = null,
) {
ColorRecipePanel(
currentParams = editingParams,
onParamChange = { param, value ->
onParamsUpdated(param.setValue(editingParams, value))
},
onParamsChange = { newParams ->
onParamsUpdated(newParams)
},
onRemarksChange = {
onParamsUpdated(editingParams.copy(remarks = it))
},
onCurveChange = { channel, points ->
onParamsUpdated(
when (channel) {
com.hinnka.mycamera.ui.components.CurveChannel.MASTER ->
editingParams.copy(masterCurvePoints = points)
com.hinnka.mycamera.ui.components.CurveChannel.RED ->
editingParams.copy(redCurvePoints = points)
com.hinnka.mycamera.ui.components.CurveChannel.GREEN ->
editingParams.copy(greenCurvePoints = points)
com.hinnka.mycamera.ui.components.CurveChannel.BLUE ->
editingParams.copy(blueCurvePoints = points)
}
)
},
imageHistogram = imageHistogram,
showLutIntensity = editorTarget == LutEditorTarget.CREATIVE_GLOBAL && lutId != "none",
currentEffects = editingParams.toEffectParams().takeIf { showEffects },
onEffectsChange = if (showEffects) {
{ effects -> onParamsUpdated(effects.applyTo(editingParams)) }
} else {
null
},
modifier = Modifier.fillMaxWidth()
)
Column(Modifier.fillMaxWidth().navigationBarsPadding()) {
editorContent(Modifier.fillMaxWidth())
}
}
} else {
CameraPanelBottomSheet(
backdrop = backdrop,
onDismissRequest = dismissEditor,
modifier = modifier,
) {
val scrollState = rememberScrollState()
editorContent(Modifier.fillMaxWidth().verticalScroll(scrollState, enabled = scrollState.maxValue > 0))
}
}
}
@@ -112,6 +112,8 @@ private val exposureSteps = listOf(
0.3f, 0.7f, 1.0f, 1.3f, 1.7f, 2.0f
)
internal val DefaultColorRecipePanelContainerColor = Color(0xF2121316)
/**
* 色彩配方控制面板
*
@@ -132,7 +134,7 @@ fun ColorRecipePanel(
onEffectsChange: ((EffectParams) -> Unit)? = null,
headerControls: (@Composable () -> Unit)? = null,
containerShape: Shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp),
containerColor: Color = Color(0xF2121316),
containerColor: Color = DefaultColorRecipePanelContainerColor,
onResetAll: (() -> Unit)? = null,
modifier: Modifier = Modifier
) {
@@ -12,7 +12,11 @@ import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawWithCache
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.CompositingStrategy
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.unit.dp
import com.hinnka.mycamera.ui.theme.AccentColor
import kotlinx.coroutines.launch
@@ -77,16 +81,20 @@ internal fun <T> CompactLookCarousel(
contentPadding = PaddingValues(horizontal = (maxWidth - slot) / 2),
flingBehavior = PagerDefaults.flingBehavior(pager, pagerSnapDistance = PagerSnapDistance.atMost(5)),
key = { ids[it] },
modifier = Modifier.fillMaxWidth().drawWithCache {
val clear = CameraLookPanelSurface.copy(alpha = 0f)
val edges = Brush.horizontalGradient(
0f to CameraLookPanelSurface, 0.16f to clear, 0.84f to clear, 1f to CameraLookPanelSurface
)
onDrawWithContent {
drawContent()
drawRect(edges)
modifier = Modifier.fillMaxWidth()
.graphicsLayer { compositingStrategy = CompositingStrategy.Offscreen }
.drawWithCache {
val mask = Brush.horizontalGradient(
0f to Color.Transparent,
0.16f to Color.Black,
0.84f to Color.Black,
1f to Color.Transparent
)
onDrawWithContent {
drawContent()
drawRect(mask, blendMode = BlendMode.DstIn)
}
}
}
) { index ->
val centered = pager.currentPage == index && !pager.isScrollInProgress
Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
@@ -8,11 +8,14 @@ import android.graphics.RuntimeShader
import android.graphics.Shader
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
@@ -27,6 +30,8 @@ import androidx.compose.ui.geometry.RoundRect
import androidx.compose.ui.geometry.isSpecified
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.FilterQuality
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.Paint
import androidx.compose.ui.graphics.PaintingStyle
@@ -76,19 +81,45 @@ data class LiquidGlassStyle(
val fallbackColor: Color = Color(0xF0141414),
)
internal val CameraPanelGlassStyle = LiquidGlassStyle(
blurRadius = 24.dp,
refractionAmount = 0.dp,
saturation = 1f,
tint = AppPanelMaterial.Tint.copy(alpha = 0.4f),
highlightAlpha = 0f,
fallbackColor = AppPanelMaterial.Tint.copy(alpha = 0.70f),
)
/** Backdrop captured by [liquidGlassBackdropSource] and sampled by [LiquidGlassSurface]. */
@Stable
class LiquidGlassBackdrop internal constructor(internal val layer: GraphicsLayer) {
class LiquidGlassBackdrop internal constructor(
internal val layer: GraphicsLayer,
internal val usesImageFrames: Boolean = false,
) {
internal var positionInRoot by mutableStateOf(Offset.Unspecified)
internal var size by mutableStateOf(IntSize.Zero)
internal var imageFrame by mutableStateOf<LiquidGlassImageFrame?>(null)
}
/** Frame from an external surface, positioned over the recorded Compose background. */
internal data class LiquidGlassImageFrame(
val image: ImageBitmap,
val positionInRoot: Offset,
val size: IntSize,
)
@Composable
fun rememberLiquidGlassBackdrop(): LiquidGlassBackdrop {
val layer = rememberGraphicsLayer()
return remember(layer) { LiquidGlassBackdrop(layer) }
}
@Composable
internal fun rememberLiquidGlassImageBackdrop(): LiquidGlassBackdrop {
val layer = rememberGraphicsLayer()
return remember(layer) { LiquidGlassBackdrop(layer, usesImageFrames = true) }
}
/** Records this node's content into [backdrop] while drawing it unchanged. */
fun Modifier.liquidGlassBackdropSource(backdrop: LiquidGlassBackdrop): Modifier {
if (!BACKDROP_SUPPORTED) return this
@@ -116,117 +147,172 @@ fun LiquidGlassSurface(
style: LiquidGlassStyle = LiquidGlassStyle(),
content: @Composable BoxScope.() -> Unit,
) {
val glassStyle = style
var positionInRoot by remember { mutableStateOf(Offset.Unspecified) }
val shaders = remember { if (LENS_SUPPORTED) GlassShaders() else null }
Box(
modifier = modifier
.onGloballyPositioned { positionInRoot = it.positionInRoot() }
// Like Surface: the panel never lets touches fall through to the content underneath.
.pointerInput(Unit) {}
.drawWithCache {
val width = size.width
val height = size.height
val radius = cornerRadius.toPx().coerceAtMost(minOf(width, height) / 2f)
// Same rounding as FrameLiquidGlass: whole-pixel half width, doubled for the clipped inner stroke.
val highlightStroke = ceil(minOf(style.highlightWidth.toPx(), minOf(width, height) / 2f)) * 2f
val refractionHeight = style.refractionHeight.toPx()
// Extend the geometry below the bounds so its bottom edge stays out of view.
val geometryHeight = if (openBottomEdge) height + refractionHeight + highlightStroke else height
val bottomRadius = if (openBottomEdge) 0f else radius
val outline = Path().apply {
addRoundRect(
RoundRect(
rect = Rect(0f, 0f, width, geometryHeight),
topLeft = CornerRadius(radius),
topRight = CornerRadius(radius),
bottomRight = CornerRadius(bottomRadius),
bottomLeft = CornerRadius(bottomRadius),
)
)
}
val backdropPosition = backdrop.positionInRoot
val backdropSize = backdrop.size
if (!BACKDROP_SUPPORTED || !positionInRoot.isSpecified || !backdropPosition.isSpecified ||
backdropSize == IntSize.Zero
) {
return@drawWithCache onDrawBehind {
clipRect { drawPath(outline, style.fallbackColor) }
}
}
if (width <= 0f || height <= 0f) {
return@drawWithCache onDrawBehind {}
}
// Glass layer covers the surface plus blur padding (the lens only samples inward), limited to the backdrop bounds so
// clamped blur edges come from real content instead of transparent pixels.
val blurRadius = style.blurRadius.toPx()
val padding = blurRadius * 2f
val backdropOrigin = backdropPosition - positionInRoot
val captureRect = Rect(-padding, -padding, width + padding, height + padding)
.intersect(Rect(backdropOrigin, backdropSize.toSize()))
val layerOffset = IntOffset(floor(captureRect.left).toInt(), floor(captureRect.top).toInt())
val layerSize = IntSize(
ceil(captureRect.right).toInt() - layerOffset.x,
ceil(captureRect.bottom).toInt() - layerOffset.y,
)
if (layerSize.width <= 0 || layerSize.height <= 0) {
return@drawWithCache onDrawBehind {
clipRect { drawPath(outline, style.fallbackColor) }
}
}
val glassLayer = obtainGraphicsLayer().apply {
topLeft = layerOffset
renderEffect = glassEffect(
style = style,
blurRadius = blurRadius,
refractionHeight = refractionHeight,
refractionAmount = style.refractionAmount.toPx(),
shapeOffset = Offset(-layerOffset.x.toFloat(), -layerOffset.y.toFloat()),
shapeWidth = width,
shapeHeight = geometryHeight,
radius = radius,
bottomRadius = bottomRadius,
shaders = shaders,
).asComposeRenderEffect()
record(size = layerSize) {
translate(backdropOrigin.x - layerOffset.x, backdropOrigin.y - layerOffset.y) {
drawLayer(backdrop.layer)
}
}
}
val highlightPaint = Paint().apply {
this.style = PaintingStyle.Stroke
strokeWidth = highlightStroke
blendMode = BlendMode.Plus
if (shaders != null) {
shaders.setHighlightUniforms(width, geometryHeight, radius, bottomRadius, glassStyle.highlightAlpha)
shader = shaders.highlight
} else {
color = Color.White.copy(alpha = glassStyle.highlightAlpha * 0.3f)
}
val highlightBlur = glassStyle.highlightBlur.toPx()
if (highlightBlur > 0f) {
asFrameworkPaint().maskFilter = BlurMaskFilter(highlightBlur, BlurMaskFilter.Blur.NORMAL)
}
}
onDrawBehind {
clipRect {
clipPath(outline) {
drawLayer(glassLayer)
drawRect(style.tint)
drawIntoCanvas { it.drawPath(outline, highlightPaint) }
}
}
}
},
modifier = modifier.liquidGlassBackground(
backdrop = backdrop,
cornerRadius = cornerRadius,
openBottomEdge = openBottomEdge,
style = style,
),
content = content,
)
}
/** Draws glass within the existing layout bounds. An open edge continues past the clip. */
@Composable
internal fun Modifier.liquidGlassBackground(
backdrop: LiquidGlassBackdrop,
cornerRadius: Dp = 24.dp,
openBottomEdge: Boolean = false,
openTopEdge: Boolean = false,
style: LiquidGlassStyle = LiquidGlassStyle(),
): Modifier {
var positionInRoot by remember { mutableStateOf(Offset.Unspecified) }
val shaders = remember { if (LENS_SUPPORTED) GlassShaders() else null }
val imageAlpha = if (backdrop.usesImageFrames && BACKDROP_SUPPORTED) {
val hasImage by remember(backdrop) { derivedStateOf { backdrop.imageFrame != null } }
animateFloatAsState(
targetValue = if (hasImage) 1f else 0f,
animationSpec = tween(120),
label = "glassPreviewFadeIn",
)
} else {
null
}
return this
.onGloballyPositioned { positionInRoot = it.positionInRoot() }
// Like Surface: the panel never lets touches fall through to the content underneath.
.pointerInput(Unit) {}
.drawWithCache {
val width = size.width
val height = size.height
val radius = cornerRadius.toPx().coerceAtMost(minOf(width, height) / 2f)
// Same rounding as FrameLiquidGlass: whole-pixel half width, doubled for the clipped inner stroke.
val highlightStroke = ceil(minOf(style.highlightWidth.toPx(), minOf(width, height) / 2f)) * 2f
val refractionHeight = style.refractionHeight.toPx()
val edgeExtension = refractionHeight + highlightStroke
val geometryTop = if (openTopEdge) -edgeExtension else 0f
val geometryBottom = if (openBottomEdge) height + edgeExtension else height
val geometryHeight = geometryBottom - geometryTop
val topRadius = if (openTopEdge) 0f else radius
val bottomRadius = if (openBottomEdge) 0f else radius
val outline = Path().apply {
addRoundRect(
RoundRect(
rect = Rect(0f, geometryTop, width, geometryBottom),
topLeft = CornerRadius(topRadius),
topRight = CornerRadius(topRadius),
bottomRight = CornerRadius(bottomRadius),
bottomLeft = CornerRadius(bottomRadius),
)
)
}
val backdropPosition = backdrop.positionInRoot
val backdropSize = backdrop.size
val surfacePosition = positionInRoot
if (!BACKDROP_SUPPORTED || !surfacePosition.isSpecified || !backdropPosition.isSpecified ||
backdropSize == IntSize.Zero
) {
return@drawWithCache onDrawBehind {
clipRect { drawPath(outline, style.fallbackColor) }
}
}
if (width <= 0f || height <= 0f) {
return@drawWithCache onDrawBehind {}
}
// Glass layer covers the surface plus blur padding (the lens only samples inward), limited to the backdrop bounds so
// clamped blur edges come from real content instead of transparent pixels.
val blurRadius = style.blurRadius.toPx()
val padding = blurRadius * 2f
val backdropOrigin = backdropPosition - surfacePosition
val captureRect = Rect(-padding, -padding, width + padding, height + padding)
.intersect(Rect(backdropOrigin, backdropSize.toSize()))
val layerOffset = IntOffset(floor(captureRect.left).toInt(), floor(captureRect.top).toInt())
val layerSize = IntSize(
ceil(captureRect.right).toInt() - layerOffset.x,
ceil(captureRect.bottom).toInt() - layerOffset.y,
)
if (layerSize.width <= 0 || layerSize.height <= 0) {
return@drawWithCache onDrawBehind {
clipRect { drawPath(outline, style.fallbackColor) }
}
}
val glassLayer = obtainGraphicsLayer().apply {
topLeft = layerOffset
renderEffect = glassEffect(
style = style,
blurRadius = blurRadius,
refractionHeight = refractionHeight,
refractionAmount = style.refractionAmount.toPx(),
shapeOffset = Offset(-layerOffset.x.toFloat(), geometryTop - layerOffset.y),
shapeWidth = width,
shapeHeight = geometryHeight,
topRadius = topRadius,
bottomRadius = bottomRadius,
shaders = shaders,
).asComposeRenderEffect()
}
fun recordBackdrop(frame: LiquidGlassImageFrame?, frameAlpha: Float = 1f) {
glassLayer.record(size = layerSize) {
// Use the recorded page background before the first camera frame arrives.
// The panel should never briefly reveal the sharp controls underneath it.
if (backdrop.usesImageFrames) drawRect(Color.Black)
val backgroundOffset = backdropOrigin - Offset(layerOffset.x.toFloat(), layerOffset.y.toFloat())
translate(backgroundOffset.x, backgroundOffset.y) {
drawLayer(backdrop.layer)
}
if (frame != null) {
val frameOffset = frame.positionInRoot - surfacePosition
drawImage(
image = frame.image,
dstOffset = IntOffset(
frameOffset.x.toInt() - layerOffset.x,
frameOffset.y.toInt() - layerOffset.y,
),
dstSize = frame.size,
alpha = frameAlpha,
filterQuality = FilterQuality.Low,
)
}
}
}
if (!backdrop.usesImageFrames) recordBackdrop(null)
val highlightPaint = Paint().apply {
this.style = PaintingStyle.Stroke
strokeWidth = highlightStroke
blendMode = BlendMode.Plus
if (shaders != null) {
shaders.setHighlightUniforms(width, geometryHeight, geometryTop, topRadius, bottomRadius, style.highlightAlpha)
shader = shaders.highlight
} else {
color = Color.White.copy(alpha = style.highlightAlpha * 0.3f)
}
val highlightBlur = style.highlightBlur.toPx()
if (highlightBlur > 0f) {
asFrameworkPaint().maskFilter = BlurMaskFilter(highlightBlur, BlurMaskFilter.Blur.NORMAL)
}
}
onDrawBehind {
if (backdrop.usesImageFrames) {
recordBackdrop(backdrop.imageFrame, imageAlpha?.value ?: 1f)
}
clipRect {
clipPath(outline) {
drawLayer(glassLayer)
drawRect(style.tint)
drawIntoCanvas { it.drawPath(outline, highlightPaint) }
}
}
}
}
}
private fun IntSize.toSize() = androidx.compose.ui.geometry.Size(width.toFloat(), height.toFloat())
@RequiresApi(Build.VERSION_CODES.S)
@@ -238,7 +324,7 @@ private fun glassEffect(
shapeOffset: Offset,
shapeWidth: Float,
shapeHeight: Float,
radius: Float,
topRadius: Float,
bottomRadius: Float,
shaders: GlassShaders?,
): RenderEffect {
@@ -254,7 +340,7 @@ private fun glassEffect(
if (refractionAmount == 0f || refractionHeight == 0f || shaders == null ||
Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU
) return blur
return shaders.lensEffect(blur, shapeOffset, shapeWidth, shapeHeight, radius, bottomRadius,
return shaders.lensEffect(blur, shapeOffset, shapeWidth, shapeHeight, topRadius, bottomRadius,
refractionHeight, refractionAmount)
}
@@ -269,14 +355,14 @@ private class GlassShaders {
shapeOffset: Offset,
width: Float,
height: Float,
radius: Float,
topRadius: Float,
bottomRadius: Float,
refractionHeight: Float,
refractionAmount: Float,
): RenderEffect {
lens.setFloatUniform("shapeOffset", shapeOffset.x, shapeOffset.y)
lens.setFloatUniform("size", width, height)
lens.setFloatUniform("cornerRadii", radius, radius, bottomRadius, bottomRadius)
lens.setFloatUniform("cornerRadii", topRadius, topRadius, bottomRadius, bottomRadius)
lens.setFloatUniform("refractionHeight", refractionHeight)
// Negative amount samples inward, matching FrameGlassGpu.setUniforms.
lens.setFloatUniform("refractionAmount", -refractionAmount)
@@ -284,9 +370,12 @@ private class GlassShaders {
return RenderEffect.createChainEffect(RenderEffect.createRuntimeShaderEffect(lens, "content"), input)
}
fun setHighlightUniforms(width: Float, height: Float, radius: Float, bottomRadius: Float, alpha: Float) {
fun setHighlightUniforms(
width: Float, height: Float, top: Float, topRadius: Float, bottomRadius: Float, alpha: Float
) {
highlight.setFloatUniform("size", width, height)
highlight.setFloatUniform("cornerRadii", radius, radius, bottomRadius, bottomRadius)
highlight.setFloatUniform("top", top)
highlight.setFloatUniform("cornerRadii", topRadius, topRadius, bottomRadius, bottomRadius)
highlight.setFloatUniform("angle", HIGHLIGHT_ANGLE)
highlight.setFloatUniform("falloff", HIGHLIGHT_FALLOFF)
highlight.setFloatUniform("alpha", alpha)
@@ -361,6 +450,7 @@ half4 main(float2 fragCoord) {
private const val HIGHLIGHT_SHADER = """
uniform float2 size;
uniform float top;
uniform float4 cornerRadii;
uniform float angle;
uniform float falloff;
@@ -368,7 +458,7 @@ uniform float alpha;
$SDF_FUNCTIONS
half4 main(float2 coord) {
float2 halfSize = size * 0.5;
float2 centered = coord - halfSize;
float2 centered = coord - float2(0.0, top) - halfSize;
float radius = radiusAt(centered, cornerRadii);
float gradRadius = min(radius * 1.5, min(halfSize.x, halfSize.y));
float2 grad = gradSdRoundedRect(centered, halfSize, gradRadius);
@@ -63,6 +63,11 @@ internal fun lutCategoryTitle(category: String): String = when (category) {
}
private val LutPanelSurface = Color.Black.copy(alpha = 0.15f)
private val CameraLookPanelCornerRadius = 16.dp
private val CameraLookPanelShape = RoundedCornerShape(
topStart = CameraLookPanelCornerRadius,
topEnd = CameraLookPanelCornerRadius
)
internal val LutPanelOptionSize = 64.dp
internal val LutPanelOptionShape = RoundedCornerShape(8.dp)
internal val LutPanelOptionSurface = Color.Black.copy(alpha = 0.2f)
@@ -199,6 +204,7 @@ fun LutSelector(
onEditPreset: ((String) -> Unit)? = null,
presetLookActive: Boolean = false,
showHorizontalHeader: Boolean = true,
cameraBackdrop: LiquidGlassBackdrop? = null,
) {
val favoriteText = stringResource(R.string.favorite)
val uncategorizedText = stringResource(R.string.uncategorized)
@@ -401,6 +407,16 @@ fun LutSelector(
}
val activePreset = allPresets.firstOrNull { it.id == activePresetId }
val cameraPanelBackground = if (cameraBackdrop != null && (compact || expanded)) {
Modifier.liquidGlassBackground(
backdrop = cameraBackdrop,
cornerRadius = CameraLookPanelCornerRadius,
openBottomEdge = true,
style = CameraPanelGlassStyle
)
} else {
Modifier.background(CameraLookPanelSurface)
}
val cameraModeRail = @Composable {
CameraLookModeRail(
selectedMode = actualMode,
@@ -418,8 +434,8 @@ fun LutSelector(
Box(
modifier = Modifier.fillMaxWidth()
.heightIn(min = if (supportsPresets) 84.dp else 64.dp)
.clip(RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp))
.background(CameraLookPanelSurface),
.clip(CameraLookPanelShape)
.then(cameraPanelBackground),
contentAlignment = Alignment.Center
) {
Column(
@@ -500,8 +516,8 @@ fun LutSelector(
headerContent?.invoke()
ExpandedCameraLookLayout(
modifier = Modifier.fillMaxWidth()
.clip(RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp))
.background(CameraLookPanelSurface),
.clip(CameraLookPanelShape)
.then(cameraPanelBackground),
modeRail = cameraModeRail
) {
Column(
@@ -145,11 +145,11 @@ private val EditPanelMaxHeight = 544.dp
private val EditPanelCornerRadius = 24.dp
private val EditPanelShape = RoundedCornerShape(topStart = EditPanelCornerRadius, topEnd = EditPanelCornerRadius)
private val EditPanelGlassStyle = LiquidGlassStyle(
blurRadius = 36.dp,
blurRadius = 24.dp,
refractionAmount = 0.dp,
saturation = 1f,
tint = AppPanelMaterial.Tint.copy(alpha = 0.15f),
highlightAlpha = 0.3f,
highlightAlpha = 0f,
fallbackColor = AppPanelMaterial.Tint.copy(alpha = 0.55f),
)