Open-source Android PDF and document toolkit with PDF tools, Office viewing, XLSX editing, scanning, and image editing. Built with Kotlin and Jetpack Compose.
Rust androiddocument-scannerdocximage-editorjetpack-composekotlinliquid-glassofflineopen-sourcepdfpdf-compressorpdf-editorpdf-mergerpdf-readerpdf-splitterpdf-toolspdf-viewerpptxspreadsheet-editorxlsx
UI Modernization: Remove tool card arrows and finalize Liquid Glass entrance animations
Chethan6163f5d0276ef65
diff --git a/app/src/main/java/com/chethan616/clearpdf/data/repository/Preferences.kt b/app/src/main/java/com/chethan616/clearpdf/data/repository/Preferences.ktindex 29e2296..65fe3bd 100644--- a/app/src/main/java/com/chethan616/clearpdf/data/repository/Preferences.kt+++ b/app/src/main/java/com/chethan616/clearpdf/data/repository/Preferences.kt@@ -146,6 +146,12 @@ object AppSettingsManager {fun setThemeMode(context: Context, value: Int) =prefs(context).edit().putInt(KEY_THEME_MODE, value).apply()++ fun getScrollOrientation(context: Context): Int =+ prefs(context).getInt("scroll_orientation", 0)++ fun setScrollOrientation(context: Context, value: Int) =+ prefs(context).edit().putInt("scroll_orientation", value).apply()}/**diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/DocsApp.kt b/app/src/main/java/com/chethan616/clearpdf/ui/DocsApp.ktindex 8aec9e4..57147b2 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/DocsApp.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/DocsApp.kt@@ -16,7 +16,6 @@ import androidx.compose.foundation.layout.heightimport androidx.compose.foundation.layout.navigationBarsPaddingimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.size-import androidx.compose.foundation.layout.widthimport androidx.compose.foundation.text.BasicTextimport androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.rounded.Star@@ -61,7 +60,7 @@ import kotlinx.coroutines.flow.collectLatest/*** Root composable for the Docs app.- * Provides the wallpaper backdrop, bottom tabs, and navigation host.+ * Provides the wallpaper backdrop, floating bottom tabs, and navigation host.*/@Composablefun DocsApp(shortcutRoute: String? = null, incomingPdfUri: android.net.Uri? = null) {@@ -94,7 +93,7 @@ fun DocsApp(shortcutRoute: String? = null, incomingPdfUri: android.net.Uri? = nu}}}-+Box(Modifier.fillMaxSize(),contentAlignment = Alignment.TopCenter@@ -153,8 +152,7 @@ fun DocsApp(shortcutRoute: String? = null, incomingPdfUri: android.net.Uri? = nu)CompositionLocalProvider(LocalIsDarkMode provides isDarkMode) {- Column(Modifier.fillMaxSize()) {- Box(Modifier.weight(1f)) {+ Box(Modifier.fillMaxSize()) {DocsNavGraph(navController = navController,backdrop = backdrop,@@ -163,90 +161,121 @@ fun DocsApp(shortcutRoute: String? = null, incomingPdfUri: android.net.Uri? = nuisDarkMode = isDarkMode,onDarkModeChanged = { /* unused */ },themeMode = themeMode,- onThemeModeChanged = {+ onThemeModeChanged = {themeMode = itAppSettingsManager.setThemeMode(context, it)},incomingPdfUri = incomingPdfUri)- }-- if (showStarPrompt) {- val uiSensor = rememberUISensor()- val starText = if (!isDarkMode) Color(0xFF1A1A1A) else Color(0xFFF0F0F0)- val starSub = if (!isDarkMode) Color(0xFF666666) else Color(0xFFAAAAAA)- val starAccent = Color(0xFFFFC107)- Dialog(- onDismissRequest = {- GitHubStarPromptManager.onPromptDismissed(context)- showStarPrompt = false- },- properties = DialogProperties(usePlatformDefaultWidth = false)- ) {- Column(- Modifier- .fillMaxWidth(0.88f)- .liquidGlassPanel(backdrop, uiSensor)- .padding(28.dp),- horizontalAlignment = Alignment.CenterHorizontally,- verticalArrangement = Arrangement.spacedBy(16.dp)- ) {- Icon(- Icons.Rounded.Star, null,- Modifier.size(52.dp), starAccent- )- BasicText(- "Support ClearPDF",- style = TextStyle(starText, 20.sp, FontWeight.Bold, textAlign = TextAlign.Center)+ androidx.compose.animation.AnimatedVisibility(+ visible = showBottomTabs,+ modifier = Modifier+ .align(Alignment.BottomCenter)+ .navigationBarsPadding(),+ enter = androidx.compose.animation.fadeIn(+ // EaseInOut tween: opacity arrives slightly after the slide,+ // giving a sequential layered feel.+ animationSpec = androidx.compose.animation.core.tween(+ durationMillis = 320,+ delayMillis = 40,+ easing = androidx.compose.animation.core.EaseInOut)- BasicText(- "ClearPDF is open source on GitHub.\nWould you like to star the project?",- style = TextStyle(starSub, 14.sp, textAlign = TextAlign.Center)+ ) + androidx.compose.animation.slideInVertically(+ // Critically-overdamped spring = no bounce, pure fluid glide.+ animationSpec = androidx.compose.animation.core.spring(+ dampingRatio = androidx.compose.animation.core.Spring.DampingRatioNoBouncy,+ stiffness = androidx.compose.animation.core.Spring.StiffnessMediumLow+ ),+ initialOffsetY = { it }+ ),+ exit = androidx.compose.animation.fadeOut(+ animationSpec = androidx.compose.animation.core.tween(+ durationMillis = 200,+ easing = androidx.compose.animation.core.EaseInOut)- Spacer(Modifier.height(4.dp))- LiquidButton(- onClick = {- GitHubStarPromptManager.onPromptAccepted(context)- showStarPrompt = false- openRepo()- },- backdrop = backdrop,- tint = starAccent,- modifier = Modifier.fillMaxWidth()+ ) + androidx.compose.animation.slideOutVertically(+ animationSpec = androidx.compose.animation.core.spring(+ dampingRatio = androidx.compose.animation.core.Spring.DampingRatioNoBouncy,+ stiffness = androidx.compose.animation.core.Spring.StiffnessMediumLow+ ),+ targetOffsetY = { it }+ )+ ) {+ DocsBottomTabs(+ selectedTab = { selectedTab },+ onTabSelected = onBottomTabSelected,+ backdrop = backdrop,+ modifier = Modifier+ .padding(horizontal = 24.dp, vertical = 12.dp)+ )+ }++ if (showStarPrompt) {+ val uiSensor = rememberUISensor()+ val starText = if (!isDarkMode) Color(0xFF1A1A1A) else Color(0xFFF0F0F0)+ val starSub = if (!isDarkMode) Color(0xFF666666) else Color(0xFFAAAAAA)+ val starAccent = Color(0xFFFFC107)+ Dialog(+ onDismissRequest = {+ GitHubStarPromptManager.onPromptDismissed(context)+ showStarPrompt = false+ },+ properties = DialogProperties(usePlatformDefaultWidth = false)+ ) {+ Column(+ Modifier+ .fillMaxWidth(0.88f)+ .liquidGlassPanel(backdrop, uiSensor)+ .padding(28.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(16.dp)) {- Row(- horizontalArrangement = Arrangement.spacedBy(8.dp),- verticalAlignment = Alignment.CenterVertically+ Icon(+ Icons.Rounded.Star, null,+ Modifier.size(52.dp), starAccent+ )+ BasicText(+ "Support ClearPDF",+ style = TextStyle(starText, 20.sp, FontWeight.Bold, textAlign = TextAlign.Center)+ )+ BasicText(+ "ClearPDF is open source on GitHub.\nWould you like to star the project?",+ style = TextStyle(starSub, 14.sp, textAlign = TextAlign.Center)+ )+ Spacer(Modifier.height(4.dp))+ LiquidButton(+ onClick = {+ GitHubStarPromptManager.onPromptAccepted(context)+ showStarPrompt = false+ openRepo()+ },+ backdrop = backdrop,+ tint = starAccent,+ modifier = Modifier.fillMaxWidth()) {- Icon(Icons.Rounded.Star, null, Modifier.size(18.dp), Color.White)- BasicText("Yes, Star It", style = TextStyle(Color.White, 15.sp, FontWeight.SemiBold))+ Row(+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ Icon(Icons.Rounded.Star, null, Modifier.size(18.dp), Color.White)+ BasicText("Yes, Star It", style = TextStyle(Color.White, 15.sp, FontWeight.SemiBold))+ }}+ BasicText(+ "Not Now",+ style = TextStyle(starSub, 14.sp, FontWeight.Medium, textAlign = TextAlign.Center),+ modifier = Modifier+ .clickable {+ GitHubStarPromptManager.onPromptDismissed(context)+ showStarPrompt = false+ }+ .padding(vertical = 8.dp)+ )}- BasicText(- "Not Now",- style = TextStyle(starSub, 14.sp, FontWeight.Medium, textAlign = TextAlign.Center),- modifier = Modifier- .clickable {- GitHubStarPromptManager.onPromptDismissed(context)- showStarPrompt = false- }- .padding(vertical = 8.dp)- )}}}- if (showBottomTabs) {- DocsBottomTabs(- selectedTab = { selectedTab },- onTabSelected = onBottomTabSelected,- backdrop = backdrop,- modifier = Modifier- .padding(horizontal = 24.dp, vertical = 8.dp)- .navigationBarsPadding()- )- }- }}}}diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/components/LiquidBottomTabs.kt b/app/src/main/java/com/chethan616/clearpdf/ui/components/LiquidBottomTabs.ktindex 8a94792..24fbc4c 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/components/LiquidBottomTabs.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/components/LiquidBottomTabs.kt@@ -67,8 +67,12 @@ fun LiquidBottomTabs() {val isDarkMode = LocalIsDarkMode.currentval isLightTheme = !isDarkMode- val accentColor = if (isLightTheme) Color(0xFF0088FF) else Color(0xFF0091FF)- val containerColor = if (isLightTheme) Color(0xFFFAFAFA).copy(0.40f) else Color(0xFF121212).copy(0.40f)+ val accentColor =+ if (isLightTheme) Color(0xFF0088FF)+ else Color(0xFF0091FF)+ val containerColor =+ if (isLightTheme) Color(0xFFFAFAFA).copy(0.4f)+ else Color(0xFF121212).copy(0.4f)val tabsBackdrop = rememberLayerBackdrop()@@ -93,10 +97,9 @@ fun LiquidBottomTabs(val isLtr = LocalLayoutDirection.current == LayoutDirection.Ltrval animationScope = rememberCoroutineScope()- // Keep the animation state stable when the parent recomposes. The- // selected-tab lambda is intentionally observed through snapshotFlow- // below instead of being used as a remember key.- var currentIndex by remember { mutableIntStateOf(selectedTabIndex()) }+ var currentIndex by remember(selectedTabIndex) {+ mutableIntStateOf(selectedTabIndex())+ }val dampedDragAnimation = remember(animationScope) {DampedDragAnimation(animationScope = animationScope,@@ -128,9 +131,11 @@ fun LiquidBottomTabs(})}- LaunchedEffect(Unit) {+ LaunchedEffect(selectedTabIndex) {snapshotFlow { selectedTabIndex() }- .collectLatest { index -> currentIndex = index }+ .collectLatest { index ->+ currentIndex = index+ }}LaunchedEffect(dampedDragAnimation) {snapshotFlow { currentIndex }@@ -144,7 +149,7 @@ fun LiquidBottomTabs(val interactiveHighlight = remember(animationScope) {InteractiveHighlight(animationScope = animationScope,- position = { size, _ ->+ position = { size, offset ->Offset(if (isLtr) (dampedDragAnimation.value + 0.5f) * tabWidth + panelOffsetelse size.width - (dampedDragAnimation.value + 0.5f) * tabWidth + panelOffset,@@ -154,10 +159,11 @@ fun LiquidBottomTabs()}- // Container rowRow(Modifier- .graphicsLayer { translationX = panelOffset }+ .graphicsLayer {+ translationX = panelOffset+ }.drawBackdrop(backdrop = backdrop,shape = { Capsule },@@ -182,7 +188,6 @@ fun LiquidBottomTabs(content = content)- // Hidden tinted rowCompositionLocalProvider(LocalLiquidBottomTabScale provides {lerp(1f, 1.2f, dampedDragAnimation.pressProgress)@@ -193,7 +198,9 @@ fun LiquidBottomTabs(.clearAndSetSemantics {}.alpha(0f).layerBackdrop(tabsBackdrop)- .graphicsLayer { translationX = panelOffset }+ .graphicsLayer {+ translationX = panelOffset+ }.drawBackdrop(backdrop = backdrop,shape = { Capsule },@@ -222,7 +229,6 @@ fun LiquidBottomTabs()}- // IndicatorBox(Modifier.padding(horizontal = 4f.dp)@@ -269,7 +275,8 @@ fun LiquidBottomTabs(onDrawSurface = {val progress = dampedDragAnimation.pressProgressdrawRect(- if (isLightTheme) Color.Black.copy(0.1f) else Color.White.copy(0.1f),+ if (isLightTheme) Color.Black.copy(0.1f)+ else Color.White.copy(0.1f),alpha = 1f - progress)drawRect(Color.Black.copy(alpha = 0.03f * progress))diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/components/LiquidGlassCard.kt b/app/src/main/java/com/chethan616/clearpdf/ui/components/LiquidGlassCard.ktindex 9639e8d..8f7bf39 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/components/LiquidGlassCard.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/components/LiquidGlassCard.kt@@ -50,6 +50,10 @@ import kotlin.math.cosimport kotlin.math.sinimport kotlin.math.tanh+import androidx.compose.foundation.layout.aspectRatio+import androidx.compose.material.icons.automirrored.rounded.ArrowForward+import androidx.compose.ui.text.style.TextOverflow+@Composablefun LiquidGlassCard(title: String,@@ -63,7 +67,7 @@ fun LiquidGlassCard() {val isDarkMode = LocalIsDarkMode.currentval isLight = !isDarkMode- val container = if (isLight) Color.White.copy(0.34f) else Color(0xFF111216).copy(0.46f)+ val container = if (isLight) Color.White.copy(0.36f) else Color(0xFF13151B).copy(0.52f)val titleColor = LiquidGlassColors.text(!isLight)val subtitleColor = LiquidGlassColors.secondary(!isLight)@@ -74,19 +78,21 @@ fun LiquidGlassCard(Column(modifier+ .fillMaxWidth()+ .aspectRatio(1f).drawBackdrop(backdrop = backdrop,- shape = { RoundedRectangle(24f.dp) },+ shape = { RoundedRectangle(28f.dp) },effects = {vibrancy()- blur(6f.dp.toPx())- lens(18f.dp.toPx(), 34f.dp.toPx(), depthEffect = true)+ blur(7f.dp.toPx())+ lens(20f.dp.toPx(), 38f.dp.toPx(), depthEffect = true)},highlight = {Highlight(style = HighlightStyle.Default(angle = uiSensor.gravityAngle, falloff = 2f))},- shadow = { Shadow(radius = 7f.dp, color = Color.Black.copy(alpha = 0.10f)) },- innerShadow = { InnerShadow(radius = 3f.dp, alpha = 0.32f) },+ shadow = { Shadow(radius = 8f.dp, color = Color.Black.copy(alpha = 0.12f)) },+ innerShadow = { InnerShadow(radius = 3.5f.dp, alpha = 0.35f) },layerBlock = {val progress = interactiveHighlight.pressProgressval scale = lerp(1f, 1f + 4f.dp.toPx() / size.height, progress)@@ -99,27 +105,48 @@ fun LiquidGlassCard(scaleX = scale + maxDragScale * abs(cos(offsetAngle) * offset.x / size.maxDimension)scaleY = scale + maxDragScale * abs(sin(offsetAngle) * offset.y / size.maxDimension)},- onDrawSurface = { drawRect(container) }- )+ onDrawSurface = { drawRect(container) }+ ).clickable(interactionSource = null, indication = null, role = Role.Button, onClick = onClick).then(interactiveHighlight.modifier).then(interactiveHighlight.gestureModifier)- .height(160.dp)- .padding(20.dp),+ .padding(18.dp),verticalArrangement = Arrangement.SpaceBetween) {+ // Icon pillBox(Modifier- .size(48.dp)- .clip(CircleShape)- .background(accentColor.copy(alpha = 0.12f)),+ .size(52.dp)+ .clip(RoundedCornerShape(16.dp))+ .background(accentColor.copy(alpha = if (isLight) 0.14f else 0.22f)),contentAlignment = Alignment.Center) {icon()}- Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {- BasicText(title, style = TextStyle(titleColor, 16.sp, FontWeight.Bold))- BasicText(subtitle, style = TextStyle(subtitleColor, 12.sp))++ // Bottom text content+ Column(verticalArrangement = Arrangement.spacedBy(3.dp)) {+ BasicText(+ title,+ style = TextStyle(+ color = titleColor,+ fontSize = 16.5.sp,+ fontWeight = FontWeight.SemiBold,+ letterSpacing = (-0.3).sp+ ),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis+ )+ BasicText(+ subtitle,+ style = TextStyle(+ color = subtitleColor,+ fontSize = 12.sp,+ fontWeight = FontWeight.Normal+ ),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis+ )}}}diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/components/LiquidSlider.kt b/app/src/main/java/com/chethan616/clearpdf/ui/components/LiquidSlider.ktindex 4c603bf..a85b194 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/components/LiquidSlider.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/components/LiquidSlider.kt@@ -13,8 +13,8 @@ import androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScope-import androidx.compose.runtime.rememberUpdatedStateimport androidx.compose.runtime.setValue+import androidx.compose.runtime.snapshotFlowimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clip@@ -43,7 +43,7 @@ import com.kyant.backdrop.highlight.Highlightimport com.kyant.backdrop.shadow.InnerShadowimport com.kyant.backdrop.shadow.Shadowimport com.kyant.shapes.Capsule-import kotlin.math.abs+import kotlinx.coroutines.flow.collectLatest@Composablefun LiquidSlider(@@ -62,61 +62,47 @@ fun LiquidSlider(val trackBackdrop = rememberLayerBackdrop()BoxWithConstraints(- modifier = modifier.fillMaxWidth(),+ modifier.fillMaxWidth(),contentAlignment = Alignment.CenterStart) {- val trackWidth = constraints.maxWidth.coerceAtLeast(1)+ val trackWidth = constraints.maxWidth+val isLtr = LocalLayoutDirection.current == LayoutDirection.Ltrval animationScope = rememberCoroutineScope()- val currentValue = value().coerceIn(valueRange.start, valueRange.endInclusive)- val onValueChangeState = rememberUpdatedState(onValueChange)var didDrag by remember { mutableStateOf(false) }- var isDragging by remember { mutableStateOf(false) }-- val dampedDragAnimation = remember(- animationScope,- isLtr,- trackWidth,- valueRange.start,- valueRange.endInclusive,- visibilityThreshold- ) {+ val dampedDragAnimation = remember(animationScope) {DampedDragAnimation(animationScope = animationScope,- initialValue = currentValue,+ initialValue = value(),valueRange = valueRange,visibilityThreshold = visibilityThreshold,initialScale = 1f,pressedScale = 1.5f,- onDragStarted = {- didDrag = false- isDragging = true- },+ onDragStarted = {},onDragStopped = {- isDragging = falseif (didDrag) {- onValueChangeState.value(targetValue.coerceIn(valueRange.start, valueRange.endInclusive))+ onValueChange(targetValue)}- didDrag = false},onDrag = { _, dragAmount ->- val delta = (valueRange.endInclusive - valueRange.start) * (dragAmount.x / trackWidth.toFloat())- if (delta != 0f) {- didDrag = true- val nextValue =- if (isLtr) (targetValue + delta).coerceIn(valueRange.start, valueRange.endInclusive)- else (targetValue - delta).coerceIn(valueRange.start, valueRange.endInclusive)- updateValue(nextValue)- onValueChangeState.value(nextValue)+ if (!didDrag) {+ didDrag = dragAmount.x != 0f}+ val delta = (valueRange.endInclusive - valueRange.start) * (dragAmount.x / trackWidth)+ onValueChange(+ if (isLtr) (targetValue + delta).coerceIn(valueRange)+ else (targetValue - delta).coerceIn(valueRange)+ )})}-- LaunchedEffect(currentValue, isDragging, dampedDragAnimation) {- if (!isDragging && abs(dampedDragAnimation.targetValue - currentValue) > visibilityThreshold) {- dampedDragAnimation.updateValue(currentValue)- }+ LaunchedEffect(dampedDragAnimation) {+ snapshotFlow { value() }+ .collectLatest { value ->+ if (dampedDragAnimation.targetValue != value) {+ dampedDragAnimation.updateValue(value)+ }+ }}Box(Modifier.layerBackdrop(trackBackdrop)) {@@ -124,16 +110,15 @@ fun LiquidSlider(Modifier.clip(Capsule).background(trackColor)- .pointerInput(trackWidth, isLtr, valueRange.start, valueRange.endInclusive) {+ .pointerInput(animationScope) {detectTapGestures { position ->- val delta =- (valueRange.endInclusive - valueRange.start) * (position.x / trackWidth.toFloat())+ val delta = (valueRange.endInclusive - valueRange.start) * (position.x / trackWidth)val targetValue =(if (isLtr) valueRange.start + deltaelse valueRange.endInclusive - delta).coerceIn(valueRange)dampedDragAnimation.animateToValue(targetValue)- onValueChangeState.value(targetValue)+ onValueChange(targetValue)}}.height(6f.dp)@@ -170,13 +155,14 @@ fun LiquidSlider(val progress = dampedDragAnimation.pressProgressval scaleX = lerp(2f / 3f, 1f, progress)val scaleY = lerp(0f, 1f, progress)- scale(scaleX, scaleY) { drawBackdrop() }+ scale(scaleX, scaleY) {+ drawBackdrop()+ }}),shape = { Capsule },effects = {val progress = dampedDragAnimation.pressProgress- // Reference catalog recipe: soft blur at rest, refraction on press.blur(8f.dp.toPx() * (1f - progress))lens(10f.dp.toPx() * progress,@@ -193,11 +179,17 @@ fun LiquidSlider()},shadow = {- Shadow(radius = 4f.dp, color = Color.Black.copy(alpha = 0.05f))+ Shadow(+ radius = 4f.dp,+ color = Color.Black.copy(alpha = 0.05f)+ )},innerShadow = {val progress = dampedDragAnimation.pressProgress- InnerShadow(radius = 4f.dp * progress, alpha = progress)+ InnerShadow(+ radius = 4f.dp * progress,+ alpha = progress+ )},layerBlock = {scaleX = dampedDragAnimation.scaleXdiff --git a/app/src/main/java/com/chethan616/clearpdf/ui/components/LiquidToggle.kt b/app/src/main/java/com/chethan616/clearpdf/ui/components/LiquidToggle.ktindex 4de0268..478d7f0 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/components/LiquidToggle.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/components/LiquidToggle.kt@@ -1,6 +1,5 @@package com.chethan616.clearpdf.ui.components-import androidx.compose.foundation.isSystemInDarkThemeimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.sizeimport androidx.compose.runtime.Composable@@ -10,7 +9,6 @@ import androidx.compose.runtime.mutableFloatStateOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScope-import androidx.compose.runtime.rememberUpdatedStateimport androidx.compose.runtime.setValueimport androidx.compose.runtime.snapshotFlowimport androidx.compose.ui.Alignment@@ -55,8 +53,12 @@ fun LiquidToggle() {val isDarkMode = LocalIsDarkMode.currentval isLightTheme = !isDarkMode- val accentColor = if (isLightTheme) Color(0xFF34C759) else Color(0xFF30D158)- val trackColor = if (isLightTheme) Color(0xFF787878).copy(0.2f) else Color(0xFF787880).copy(0.36f)+ val accentColor =+ if (isLightTheme) Color(0xFF34C759)+ else Color(0xFF30D158)+ val trackColor =+ if (isLightTheme) Color(0xFF787878).copy(0.2f)+ else Color(0xFF787880).copy(0.36f)val density = LocalDensity.currentval isLtr = LocalLayoutDirection.current == LayoutDirection.Ltr@@ -64,12 +66,6 @@ fun LiquidToggle(val animationScope = rememberCoroutineScope()var didDrag by remember { mutableStateOf(false) }var fraction by remember { mutableFloatStateOf(if (selected()) 1f else 0f) }-- // Keep references to callbacks up-to-date so the remembered DampedDragAnimation- // always calls through to the latest lambda even after recomposition.- val currentSelected by rememberUpdatedState(selected)- val currentOnSelect by rememberUpdatedState(onSelect)-val dampedDragAnimation = remember(animationScope) {DampedDragAnimation(animationScope = animationScope,@@ -82,15 +78,17 @@ fun LiquidToggle(onDragStopped = {if (didDrag) {fraction = if (targetValue >= 0.5f) 1f else 0f- currentOnSelect(fraction == 1f)+ onSelect(fraction == 1f)didDrag = false} else {- fraction = if (currentSelected()) 0f else 1f- currentOnSelect(fraction == 1f)+ fraction = if (selected()) 0f else 1f+ onSelect(fraction == 1f)}},onDrag = { _, dragAmount ->- if (!didDrag) { didDrag = dragAmount.x != 0f }+ if (!didDrag) {+ didDrag = dragAmount.x != 0f+ }val delta = dragAmount.x / dragWidthfraction =if (isLtr) (fraction + delta).fastCoerceIn(0f, 1f)@@ -100,7 +98,9 @@ fun LiquidToggle(}LaunchedEffect(dampedDragAnimation) {snapshotFlow { fraction }- .collectLatest { dampedDragAnimation.updateValue(it) }+ .collectLatest { fraction ->+ dampedDragAnimation.updateValue(fraction)+ }}LaunchedEffect(selected) {snapshotFlow { selected() }@@ -115,13 +115,17 @@ fun LiquidToggle(val trackBackdrop = rememberLayerBackdrop()- Box(modifier, contentAlignment = Alignment.CenterStart) {+ Box(+ modifier,+ contentAlignment = Alignment.CenterStart+ ) {Box(Modifier.layerBackdrop(trackBackdrop).clip(Capsule).drawBehind {- drawRect(lerp(trackColor, accentColor, dampedDragAnimation.value))+ val fraction = dampedDragAnimation.value+ drawRect(lerp(trackColor, accentColor, fraction))}.size(64f.dp, 28f.dp))@@ -129,40 +133,58 @@ fun LiquidToggle(Box(Modifier.graphicsLayer {- val f = dampedDragAnimation.value+ val fraction = dampedDragAnimation.valueval padding = 2f.dp.toPx()translationX =- if (isLtr) lerp(padding, padding + dragWidth, f)- else lerp(-padding, -(padding + dragWidth), f)+ if (isLtr) lerp(padding, padding + dragWidth, fraction)+ else lerp(-padding, -(padding + dragWidth), fraction)+ }+ .semantics {+ role = Role.Switch}- .semantics { role = Role.Switch }.then(dampedDragAnimation.modifier).drawBackdrop(backdrop = rememberCombinedBackdrop(backdrop,rememberBackdrop(trackBackdrop) { drawBackdrop ->- val p = dampedDragAnimation.pressProgress- scale(lerp(2f / 3f, 0.75f, p), lerp(0f, 0.75f, p)) { drawBackdrop() }+ val progress = dampedDragAnimation.pressProgress+ val scaleX = lerp(2f / 3f, 0.75f, progress)+ val scaleY = lerp(0f, 0.75f, progress)+ scale(scaleX, scaleY) {+ drawBackdrop()+ }}),shape = { Capsule },effects = {- val p = dampedDragAnimation.pressProgress- blur(8f.dp.toPx() * (1f - p))- lens(5f.dp.toPx() * p, 10f.dp.toPx() * p, chromaticAberration = true)+ val progress = dampedDragAnimation.pressProgress+ blur(8f.dp.toPx() * (1f - progress))+ lens(+ 5f.dp.toPx() * progress,+ 10f.dp.toPx() * progress,+ chromaticAberration = true+ )},highlight = {- val p = dampedDragAnimation.pressProgress+ val progress = dampedDragAnimation.pressProgressHighlight.Ambient.copy(width = Highlight.Ambient.width / 1.5f,blurRadius = Highlight.Ambient.blurRadius / 1.5f,- alpha = p+ alpha = progress+ )+ },+ shadow = {+ Shadow(+ radius = 4f.dp,+ color = Color.Black.copy(alpha = 0.05f))},- shadow = { Shadow(radius = 4f.dp, color = Color.Black.copy(alpha = 0.05f)) },innerShadow = {- val p = dampedDragAnimation.pressProgress- InnerShadow(radius = 4f.dp * p, alpha = p)+ val progress = dampedDragAnimation.pressProgress+ InnerShadow(+ radius = 4f.dp * progress,+ alpha = progress+ )},layerBlock = {scaleX = dampedDragAnimation.scaleX@@ -172,7 +194,8 @@ fun LiquidToggle(scaleY *= 1f - (velocity * 0.25f).fastCoerceIn(-0.2f, 0.2f)},onDrawSurface = {- drawRect(Color.White.copy(alpha = 1f - dampedDragAnimation.pressProgress))+ val progress = dampedDragAnimation.pressProgress+ drawRect(Color.White.copy(alpha = 1f - progress))}).size(40f.dp, 24f.dp)diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/navigation/DocsNavGraph.kt b/app/src/main/java/com/chethan616/clearpdf/ui/navigation/DocsNavGraph.ktindex 860cb2e..42c76b2 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/navigation/DocsNavGraph.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/navigation/DocsNavGraph.kt@@ -2,6 +2,8 @@ package com.chethan616.clearpdf.ui.navigationimport androidx.compose.animation.EnterTransitionimport androidx.compose.animation.ExitTransition+import androidx.compose.animation.core.EaseInOut+import androidx.compose.animation.core.tweenimport androidx.compose.runtime.Composableimport androidx.lifecycle.ViewModelProviderimport androidx.lifecycle.viewmodel.compose.viewModel@@ -76,6 +78,15 @@ private fun NavHostController.navigateToPdfViewer(uri: Uri? = null) {navigate(route) { launchSingleTop = true }}+private val MAIN_TAB_ROUTES = setOf(ROUTE_HOME, ROUTE_TOOLS, ROUTE_SETTINGS)++private fun routeToTabIdx(route: String?): Int = when (route) {+ ROUTE_HOME -> 0+ ROUTE_TOOLS -> 1+ ROUTE_SETTINGS -> 2+ else -> 0+}+@Composablefun DocsNavGraph(navController: NavHostController,@@ -88,35 +99,88 @@ fun DocsNavGraph(onThemeModeChanged: (Int) -> Unit,incomingPdfUri: Uri? = null) {- // Disable NavHost transition animations - the LiquidBottomTabs already- // handles its own spring-based animation. Removing crossfade transitions- // eliminates GPU work that competes with the backdrop rendering pipeline.NavHost(navController = navController,startDestination = ROUTE_HOME,enterTransition = {- androidx.compose.animation.slideInHorizontally(- animationSpec = androidx.compose.animation.core.spring(dampingRatio = 0.82f, stiffness = 380f),- initialOffsetX = { (it * 0.35f).toInt() }- ) + androidx.compose.animation.fadeIn(animationSpec = androidx.compose.animation.core.spring(stiffness = 380f)) + androidx.compose.animation.scaleIn(initialScale = 0.95f)+ val isMainTabSwitch = initialState.destination.route in MAIN_TAB_ROUTES && targetState.destination.route in MAIN_TAB_ROUTES+ if (isMainTabSwitch) {+ val dist = kotlin.math.abs(routeToTabIdx(targetState.destination.route) - routeToTabIdx(initialState.destination.route))+ val fadeDuration = if (dist >= 2) 520 else 350+ androidx.compose.animation.fadeIn(+ animationSpec = tween(durationMillis = fadeDuration, easing = androidx.compose.animation.core.FastOutSlowInEasing)+ )+ } else {+ androidx.compose.animation.fadeIn(+ animationSpec = tween(durationMillis = 280, easing = EaseInOut)+ ) + androidx.compose.animation.slideInHorizontally(+ animationSpec = androidx.compose.animation.core.spring(+ dampingRatio = androidx.compose.animation.core.Spring.DampingRatioNoBouncy,+ stiffness = androidx.compose.animation.core.Spring.StiffnessMedium+ ),+ initialOffsetX = { (it * 0.06f).toInt() }+ )+ }},exitTransition = {- androidx.compose.animation.slideOutHorizontally(- animationSpec = androidx.compose.animation.core.spring(dampingRatio = 0.82f, stiffness = 380f),- targetOffsetX = { (-it * 0.25f).toInt() }- ) + androidx.compose.animation.fadeOut(animationSpec = androidx.compose.animation.core.spring(stiffness = 380f)) + androidx.compose.animation.scaleOut(targetScale = 0.95f)+ val isMainTabSwitch = initialState.destination.route in MAIN_TAB_ROUTES && targetState.destination.route in MAIN_TAB_ROUTES+ if (isMainTabSwitch) {+ val dist = kotlin.math.abs(routeToTabIdx(targetState.destination.route) - routeToTabIdx(initialState.destination.route))+ val fadeDuration = if (dist >= 2) 520 else 350+ androidx.compose.animation.fadeOut(+ animationSpec = tween(durationMillis = fadeDuration, easing = androidx.compose.animation.core.FastOutSlowInEasing)+ )+ } else {+ androidx.compose.animation.fadeOut(+ animationSpec = tween(durationMillis = 180, easing = EaseInOut)+ ) + androidx.compose.animation.slideOutHorizontally(+ animationSpec = androidx.compose.animation.core.spring(+ dampingRatio = androidx.compose.animation.core.Spring.DampingRatioNoBouncy,+ stiffness = androidx.compose.animation.core.Spring.StiffnessMedium+ ),+ targetOffsetX = { (-it * 0.06f).toInt() }+ )+ }},popEnterTransition = {- androidx.compose.animation.slideInHorizontally(- animationSpec = androidx.compose.animation.core.spring(dampingRatio = 0.82f, stiffness = 380f),- initialOffsetX = { (-it * 0.25f).toInt() }- ) + androidx.compose.animation.fadeIn(animationSpec = androidx.compose.animation.core.spring(stiffness = 380f)) + androidx.compose.animation.scaleIn(initialScale = 0.95f)+ val isMainTabSwitch = initialState.destination.route in MAIN_TAB_ROUTES && targetState.destination.route in MAIN_TAB_ROUTES+ if (isMainTabSwitch) {+ val dist = kotlin.math.abs(routeToTabIdx(targetState.destination.route) - routeToTabIdx(initialState.destination.route))+ val fadeDuration = if (dist >= 2) 520 else 350+ androidx.compose.animation.fadeIn(+ animationSpec = tween(durationMillis = fadeDuration, easing = androidx.compose.animation.core.FastOutSlowInEasing)+ )+ } else {+ androidx.compose.animation.fadeIn(+ animationSpec = tween(durationMillis = 280, easing = EaseInOut)+ ) + androidx.compose.animation.slideInHorizontally(+ animationSpec = androidx.compose.animation.core.spring(+ dampingRatio = androidx.compose.animation.core.Spring.DampingRatioNoBouncy,+ stiffness = androidx.compose.animation.core.Spring.StiffnessMedium+ ),+ initialOffsetX = { (-it * 0.06f).toInt() }+ )+ }},popExitTransition = {- androidx.compose.animation.slideOutHorizontally(- animationSpec = androidx.compose.animation.core.spring(dampingRatio = 0.82f, stiffness = 380f),- targetOffsetX = { (it * 0.35f).toInt() }- ) + androidx.compose.animation.fadeOut(animationSpec = androidx.compose.animation.core.spring(stiffness = 380f)) + androidx.compose.animation.scaleOut(targetScale = 0.95f)+ val isMainTabSwitch = initialState.destination.route in MAIN_TAB_ROUTES && targetState.destination.route in MAIN_TAB_ROUTES+ if (isMainTabSwitch) {+ val dist = kotlin.math.abs(routeToTabIdx(targetState.destination.route) - routeToTabIdx(initialState.destination.route))+ val fadeDuration = if (dist >= 2) 520 else 350+ androidx.compose.animation.fadeOut(+ animationSpec = tween(durationMillis = fadeDuration, easing = androidx.compose.animation.core.FastOutSlowInEasing)+ )+ } else {+ androidx.compose.animation.fadeOut(+ animationSpec = tween(durationMillis = 180, easing = EaseInOut)+ ) + androidx.compose.animation.slideOutHorizontally(+ animationSpec = androidx.compose.animation.core.spring(+ dampingRatio = androidx.compose.animation.core.Spring.DampingRatioNoBouncy,+ stiffness = androidx.compose.animation.core.Spring.StiffnessMedium+ ),+ targetOffsetX = { (it * 0.06f).toInt() }+ )+ }}) {diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/CompressPdfScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/CompressPdfScreen.ktindex b881da3..e51fb68 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/CompressPdfScreen.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/CompressPdfScreen.kt@@ -4,7 +4,6 @@ import android.net.Uriimport androidx.activity.compose.rememberLauncherForActivityResultimport androidx.activity.result.contract.ActivityResultContractsimport androidx.compose.foundation.background-import androidx.compose.foundation.clickableimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Column@@ -31,10 +30,14 @@ import androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.collectAsStateimport androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.graphicsLayerimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.text.TextStyleimport androidx.compose.ui.text.font.FontWeight@@ -48,7 +51,6 @@ import com.chethan616.clearpdf.ui.components.liquidGlassPanelimport com.chethan616.clearpdf.ui.theme.LocalIsDarkModeimport com.chethan616.clearpdf.ui.utils.rememberUISensorimport com.chethan616.clearpdf.ui.viewmodel.CompressPdfViewModel-import com.kyant.pdfcore.model.CompressionQualityimport com.kyant.backdrop.backdrops.LayerBackdropimport kotlinx.coroutines.delay@@ -81,196 +83,202 @@ fun CompressPdfScreen(if (uri != null) viewModel.onSelectFile(context, uri)}- Column(- Modifier- .fillMaxSize()- .statusBarsPadding()- .padding(16.dp)- .verticalScroll(rememberScrollState()),- verticalArrangement = Arrangement.spacedBy(16.dp)- ) {- Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {- LiquidButton(onClick = onBack, backdrop = backdrop, surfaceColor = Color.White.copy(0.08f)) {- Icon(Icons.Rounded.ArrowBackIosNew, "Back", Modifier.size(18.dp), text)- }- LiquidGlassTopBar(title = "Compress PDF", backdrop = backdrop, uiSensor = uiSensor, modifier = Modifier.weight(1f))- }+ var isVisible by remember { mutableStateOf(false) }+ LaunchedEffect(Unit) { isVisible = true }+ val density = androidx.compose.ui.platform.LocalDensity.current.density++ val topBarAlpha by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 1f else 0f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 500, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "compressTopBarAlpha"+ )+ val topBarOffsetY by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 0f else 16f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 500, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "compressTopBarOffsetY"+ )+ val contentAlpha by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 1f else 0f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 600, delayMillis = 100, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "compressContentAlpha"+ )+ val contentOffsetY by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 0f else 24f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 600, delayMillis = 100, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "compressContentOffsetY"+ )++ Box(Modifier.fillMaxSize()) {+ // ── Scrollable Content (scrolls underneath floating nav bar) ──Column(Modifier- .fillMaxWidth()- .liquidGlassPanel(backdrop, uiSensor)- .padding(28.dp),- horizontalAlignment = Alignment.CenterHorizontally,+ .fillMaxSize()+ .graphicsLayer {+ alpha = contentAlpha+ translationY = contentOffsetY * density+ }+ .verticalScroll(rememberScrollState())+ .padding(top = 76.dp, start = 16.dp, end = 16.dp, bottom = 16.dp),verticalArrangement = Arrangement.spacedBy(16.dp)) {- Icon(Icons.Rounded.Compress, null, Modifier.size(56.dp), accent)- BasicText("Reduce File Size", style = TextStyle(text, 20.sp, fontWeight = FontWeight.SemiBold))- BasicText("Compress your PDF while preserving quality", style = TextStyle(sub, 14.sp, textAlign = TextAlign.Center))+ Spacer(Modifier.height(8.dp))- LiquidButton(- onClick = { filePicker.launch(arrayOf("application/pdf")) },- backdrop = backdrop, tint = accent- ) {- Row(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically) {- Icon(Icons.Rounded.UploadFile, null, Modifier.size(18.dp), Color.White)- BasicText("Select PDF", style = TextStyle(Color.White, 15.sp, fontWeight = FontWeight.Medium))- }- }- }-- if (state.sourceFileName.isNotEmpty()) {- // File infoColumn(Modifier.fillMaxWidth().liquidGlassPanel(backdrop, uiSensor)- .padding(20.dp),- verticalArrangement = Arrangement.spacedBy(8.dp)+ .padding(28.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(16.dp)) {- BasicText(state.sourceFileName, style = TextStyle(text, 15.sp, fontWeight = FontWeight.Medium))- BasicText("Size: ${state.originalSizeBytes / 1024} KB", style = TextStyle(sub, 13.sp))- }+ Icon(Icons.Rounded.Compress, null, Modifier.size(56.dp), accent)+ BasicText("Reduce File Size", style = TextStyle(text, 20.sp, fontWeight = FontWeight.SemiBold))+ BasicText("Compress your PDF while preserving quality", style = TextStyle(sub, 14.sp, textAlign = TextAlign.Center))- // One focused control surface: preset first, fine-tuning second.- Column(- Modifier- .fillMaxWidth()- .liquidGlassPanel(backdrop, uiSensor)- .padding(20.dp),- verticalArrangement = Arrangement.spacedBy(12.dp)- ) {- BasicText("Compression Level", style = TextStyle(text, 15.sp, fontWeight = FontWeight.Medium))- BasicText(- "Start with a preset, then fine-tune the size and quality balance.",- style = TextStyle(sub, 12.sp)- )+ LiquidButton(+ onClick = { filePicker.launch(arrayOf("application/pdf")) },+ backdrop = backdrop, tint = accent+ ) {+ Row(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically) {+ Icon(Icons.Rounded.UploadFile, null, Modifier.size(18.dp), Color.White)+ BasicText("Select PDF", style = TextStyle(Color.White, 15.sp, fontWeight = FontWeight.Medium))+ }+ }+ }- val qualities = listOf(- Triple(CompressionQuality.LOW, "Maximum Compression", "Smallest file, lower quality"),- Triple(CompressionQuality.MEDIUM, "Balanced", "Good balance of size and quality"),- Triple(CompressionQuality.HIGH, "Minimum Compression", "Best quality, larger file")- )+ if (state.sourceFileName.isNotEmpty()) {+ // File info+ Column(+ Modifier+ .fillMaxWidth()+ .liquidGlassPanel(backdrop, uiSensor)+ .padding(20.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp)+ ) {+ BasicText(state.sourceFileName, style = TextStyle(text, 15.sp, fontWeight = FontWeight.Medium))+ BasicText("Size: ${state.originalSizeBytes / 1024} KB", style = TextStyle(sub, 13.sp))+ }- qualities.forEach { (quality, title, desc) ->- val isSelected = state.selectedQuality == quality+ // Un-nested slider control for maximum performance (no glass card lag)+ Column(+ Modifier+ .fillMaxWidth()+ .padding(horizontal = 4.dp, vertical = 4.dp),+ verticalArrangement = Arrangement.spacedBy(12.dp)+ ) {Row(- Modifier- .fillMaxWidth()- .clip(RoundedCornerShape(12.dp))- .background(if (isSelected) accent.copy(0.15f) else Color.Transparent)- .clickable {- viewModel.onQualityChanged(quality)- }- .padding(12.dp),+ Modifier.fillMaxWidth(),verticalAlignment = Alignment.CenterVertically,- horizontalArrangement = Arrangement.spacedBy(12.dp)+ horizontalArrangement = Arrangement.SpaceBetween) {+ Row(+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(8.dp)+ ) {+ Icon(Icons.Rounded.HighQuality, null, Modifier.size(22.dp), accent)+ BasicText("Compression Quality", style = TextStyle(text, 16.sp, fontWeight = FontWeight.SemiBold))+ }Box(Modifier- .size(20.dp)- .clip(RoundedCornerShape(10.dp))- .background(if (isSelected) accent else sub.copy(0.3f)),- contentAlignment = Alignment.Center+ .clip(RoundedCornerShape(6.dp))+ .background(accent.copy(0.12f))+ .padding(horizontal = 8.dp, vertical = 2.dp)) {- if (isSelected) {- Box(- Modifier- .size(8.dp)- .clip(RoundedCornerShape(4.dp))- .background(Color.White)- )- }- }- Column {- BasicText(title, style = TextStyle(text, 14.sp, fontWeight = FontWeight.Medium))- BasicText(desc, style = TextStyle(sub, 12.sp))+ BasicText(+ "${(state.qualitySlider * 100).toInt()}%",+ style = TextStyle(accent, 13.sp, fontWeight = FontWeight.Bold)+ )}}- }- Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {- Icon(Icons.Rounded.HighQuality, null, Modifier.size(22.dp), accent)- BasicText("Fine-tune quality", style = TextStyle(text, 14.sp, fontWeight = FontWeight.Medium))- val qualityLabel = when (state.selectedQuality) {- CompressionQuality.LOW -> "Low"- CompressionQuality.MEDIUM -> "Balanced"- CompressionQuality.HIGH -> "High"- }- BasicText(- qualityLabel,- style = TextStyle(accent, 12.sp, fontWeight = FontWeight.SemiBold),- modifier = Modifier.weight(1f),- maxLines = 1- )- BasicText(- "${(state.qualitySlider * 100).toInt()}%",- style = TextStyle(text, 13.sp, fontWeight = FontWeight.SemiBold)++ LiquidSlider(+ value = { state.qualitySlider },+ onValueChange = { v ->+ viewModel.onQualitySliderChanged(v)+ },+ valueRange = 0f..1f,+ visibilityThreshold = 0.005f,+ backdrop = backdrop,+ modifier = Modifier.fillMaxWidth())++ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {+ BasicText("Smaller file", style = TextStyle(sub, 12.sp))+ BasicText("Better quality", style = TextStyle(sub, 12.sp))+ }++ if (state.estimatedSizeBytes > 0) {+ val currentKb = state.originalSizeBytes / 1024+ val estimateKb = state.estimatedSizeBytes / 1024+ BasicText(+ "Estimated output $currentKb KB -> about $estimateKb KB",+ style = TextStyle(sub, 12.sp, fontWeight = FontWeight.Medium)+ )+ }}- Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {- BasicText("Smaller file", style = TextStyle(sub, 13.sp))- BasicText("Better quality", style = TextStyle(sub, 13.sp))++ // Compress button+ LiquidButton(+ onClick = { viewModel.onCompress(context) },+ backdrop = backdrop, tint = accent,+ isInteractive = !state.isCompressing+ ) {+ Row(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically) {+ if (state.isCompressing) {+ CircularProgressIndicator(Modifier.size(18.dp), Color.White, strokeWidth = 2.dp)+ } else {+ Icon(Icons.Rounded.Compress, null, Modifier.size(18.dp), Color.White)+ }+ BasicText(+ if (state.isCompressing) "Compressing..." else "Compress Now",+ style = TextStyle(Color.White, 15.sp, fontWeight = FontWeight.Medium)+ )+ }}- LiquidSlider(- value = { state.qualitySlider },- onValueChange = { v ->- viewModel.onQualitySliderChanged(v)- },- valueRange = 0f..1f,- visibilityThreshold = 0.005f,+ }++ if (state.errorMessage != null) {+ com.chethan616.clearpdf.ui.components.LiquidGlassErrorCard(+ message = state.errorMessage!!,backdrop = backdrop,- modifier = Modifier.fillMaxWidth()+ uiSensor = uiSensor,+ onDismiss = { viewModel.clearFeedback() })- if (state.estimatedSizeBytes > 0) {- val currentKb = state.originalSizeBytes / 1024- val estimateKb = state.estimatedSizeBytes / 1024- BasicText(- "Estimated output $currentKb KB -> about $estimateKb KB",- style = TextStyle(sub, 12.sp, fontWeight = FontWeight.Medium)- )- }}- // Compress button- LiquidButton(- onClick = { viewModel.onCompress(context) },- backdrop = backdrop, tint = accent,- isInteractive = !state.isCompressing- ) {- Row(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically) {- if (state.isCompressing) {- CircularProgressIndicator(Modifier.size(18.dp), Color.White, strokeWidth = 2.dp)- } else {- Icon(Icons.Rounded.Compress, null, Modifier.size(18.dp), Color.White)- }- BasicText(- if (state.isCompressing) "Compressing..." else "Compress Now",- style = TextStyle(Color.White, 15.sp, fontWeight = FontWeight.Medium)- )+ state.lastOutputUri?.let { outputUri ->+ LiquidButton(+ onClick = { onViewOutput(outputUri) },+ backdrop = backdrop,+ tint = Color(0xFF1976D2),+ modifier = Modifier.fillMaxWidth()+ ) {+ BasicText("View PDF", style = TextStyle(Color.White, 15.sp, fontWeight = FontWeight.SemiBold))}}- }- if (state.errorMessage != null) {- com.chethan616.clearpdf.ui.components.LiquidGlassErrorCard(- message = state.errorMessage!!,- backdrop = backdrop,- uiSensor = uiSensor,- onDismiss = { viewModel.clearFeedback() }- )+ Spacer(Modifier.height(80.dp))}- state.lastOutputUri?.let { outputUri ->- LiquidButton(- onClick = { onViewOutput(outputUri) },- backdrop = backdrop,- tint = Color(0xFF1976D2),- modifier = Modifier.fillMaxWidth()- ) {- BasicText("View PDF", style = TextStyle(Color.White, 15.sp, fontWeight = FontWeight.SemiBold))+ // ── Floating Liquid Glass Top Bar ──+ Row(+ Modifier+ .fillMaxWidth()+ .align(Alignment.TopCenter)+ .statusBarsPadding()+ .padding(horizontal = 16.dp, vertical = 8.dp)+ .graphicsLayer {+ alpha = topBarAlpha+ translationY = topBarOffsetY * density+ },+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(12.dp)+ ) {+ LiquidButton(onClick = onBack, backdrop = backdrop, surfaceColor = Color.White.copy(0.08f)) {+ Icon(Icons.Rounded.ArrowBackIosNew, "Back", Modifier.size(18.dp), text)}+ LiquidGlassTopBar(title = "Compress PDF", backdrop = backdrop, uiSensor = uiSensor, modifier = Modifier.weight(1f))}-- Spacer(Modifier.height(80.dp))}}diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/CreatePdfScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/CreatePdfScreen.ktindex 09deabc..cd30000 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/CreatePdfScreen.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/CreatePdfScreen.kt@@ -77,6 +77,9 @@ import com.google.mlkit.vision.documentscanner.GmsDocumentScanningResultimport com.kyant.backdrop.backdrops.LayerBackdropimport kotlinx.coroutines.delay+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.platform.LocalDensity+@Composablefun CreatePdfScreen(backdrop: LayerBackdrop,@@ -146,6 +149,32 @@ fun CreatePdfScreen(}}+ var isVisible by remember { mutableStateOf(false) }+ LaunchedEffect(Unit) { isVisible = true }+ val density = LocalDensity.current.density++ val topBarAlpha by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 1f else 0f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 500, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "createTopBarAlpha"+ )+ val topBarOffsetY by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 0f else 16f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 500, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "createTopBarOffsetY"+ )++ val contentAlpha by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 1f else 0f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 600, delayMillis = 100, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "createContentAlpha"+ )+ val contentOffsetY by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 0f else 24f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 600, delayMillis = 100, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "createContentOffsetY"+ )+Column(Modifier.fillMaxSize()@@ -155,13 +184,30 @@ fun CreatePdfScreen(.verticalScroll(rememberScrollState()),verticalArrangement = Arrangement.spacedBy(14.dp)) {- Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {+ Row(+ Modifier.graphicsLayer {+ alpha = topBarAlpha+ translationY = topBarOffsetY * density+ },+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(12.dp)+ ) {LiquidButton(onClick = onBack, backdrop = backdrop, surfaceColor = Color.White.copy(0.08f)) {Icon(Icons.Rounded.ArrowBackIosNew, "Back", Modifier.size(18.dp), text)}LiquidGlassTopBar(title = "Create PDF", backdrop = backdrop, uiSensor = uiSensor, modifier = Modifier.weight(1f))}+ Column(+ Modifier+ .fillMaxWidth()+ .graphicsLayer {+ alpha = contentAlpha+ translationY = contentOffsetY * density+ },+ verticalArrangement = Arrangement.spacedBy(14.dp)+ ) {+Column(Modifier.fillMaxWidth()@@ -460,6 +506,7 @@ fun CreatePdfScreen(}Spacer(Modifier.height(4.dp))+ }}if (showSaveDialog) {diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/ExtractTextScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/ExtractTextScreen.ktindex b690607..2dc6c06 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/ExtractTextScreen.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/ExtractTextScreen.kt@@ -46,6 +46,12 @@ import com.chethan616.clearpdf.ui.utils.rememberUISensorimport com.chethan616.clearpdf.ui.viewmodel.ExtractTextViewModelimport com.kyant.backdrop.backdrops.LayerBackdrop+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.platform.LocalDensity+@Composablefun ExtractTextScreen(backdrop: LayerBackdrop,@@ -65,61 +71,105 @@ fun ExtractTextScreen(uri?.let { viewModel.onSelectFile(context, it) }}+ var isVisible by remember { mutableStateOf(false) }+ androidx.compose.runtime.LaunchedEffect(Unit) { isVisible = true }+ val density = LocalDensity.current.density++ val topBarAlpha by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 1f else 0f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 500, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "extractTopBarAlpha"+ )+ val topBarOffsetY by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 0f else 16f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 500, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "extractTopBarOffsetY"+ )++ val contentAlpha by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 1f else 0f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 600, delayMillis = 100, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "extractContentAlpha"+ )+ val contentOffsetY by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 0f else 24f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 600, delayMillis = 100, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "extractContentOffsetY"+ )+Column(Modifier.fillMaxSize().statusBarsPadding().padding(16.dp),verticalArrangement = Arrangement.spacedBy(12.dp)) {- Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {+ Row(+ Modifier.graphicsLayer {+ alpha = topBarAlpha+ translationY = topBarOffsetY * density+ },+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(12.dp)+ ) {LiquidButton(onClick = onBack, backdrop = backdrop, surfaceColor = Color.White.copy(0.08f)) {Icon(Icons.Rounded.ArrowBackIosNew, "Back", Modifier.size(18.dp), text)}LiquidGlassTopBar("Extract Text", backdrop, uiSensor, Modifier.weight(1f), titleFontSize = 18.sp)}- Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) {- LiquidButton(onClick = { picker.launch(arrayOf("application/pdf")) }, backdrop = backdrop, tint = accent) {- Icon(Icons.Rounded.UploadFile, null, Modifier.size(18.dp), Color.White)- BasicText("Pick a PDF", style = TextStyle(Color.White, 14.sp, FontWeight.Medium))- }- if (state.text.isNotEmpty()) {- LiquidButton(onClick = { clipboard.setText(AnnotatedString(state.text)) }, backdrop = backdrop) {- Icon(Icons.Rounded.ContentCopy, null, Modifier.size(16.dp), text)- BasicText("Copy", style = TextStyle(text, 14.sp, FontWeight.Medium))+ Column(+ Modifier+ .fillMaxWidth()+ .weight(1f)+ .graphicsLayer {+ alpha = contentAlpha+ translationY = contentOffsetY * density+ },+ verticalArrangement = Arrangement.spacedBy(12.dp)+ ) {+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) {+ LiquidButton(onClick = { picker.launch(arrayOf("application/pdf")) }, backdrop = backdrop, tint = accent) {+ Icon(Icons.Rounded.UploadFile, null, Modifier.size(18.dp), Color.White)+ BasicText("Pick a PDF", style = TextStyle(Color.White, 14.sp, FontWeight.Medium))}- LiquidButton(onClick = {- val send = Intent(Intent.ACTION_SEND).apply {- type = "text/plain"- putExtra(Intent.EXTRA_TEXT, state.text)+ if (state.text.isNotEmpty()) {+ LiquidButton(onClick = { clipboard.setText(AnnotatedString(state.text)) }, backdrop = backdrop) {+ Icon(Icons.Rounded.ContentCopy, null, Modifier.size(16.dp), text)+ BasicText("Copy", style = TextStyle(text, 14.sp, FontWeight.Medium))+ }+ LiquidButton(onClick = {+ val send = Intent(Intent.ACTION_SEND).apply {+ type = "text/plain"+ putExtra(Intent.EXTRA_TEXT, state.text)+ }+ context.startActivity(Intent.createChooser(send, "Share text"))+ }, backdrop = backdrop) {+ Icon(Icons.Rounded.Share, null, Modifier.size(16.dp), text)+ BasicText("Share", style = TextStyle(text, 14.sp, FontWeight.Medium))}- context.startActivity(Intent.createChooser(send, "Share text"))- }, backdrop = backdrop) {- Icon(Icons.Rounded.Share, null, Modifier.size(16.dp), text)- BasicText("Share", style = TextStyle(text, 14.sp, FontWeight.Medium))}}- }- state.sourceFileName.takeIf { it.isNotBlank() }?.let {- BasicText(it, style = TextStyle(sub, 12.sp))- }- state.errorMessage?.let { BasicText(it, style = TextStyle(Color(0xFFFFB300), 12.sp)) }+ state.sourceFileName.takeIf { it.isNotBlank() }?.let {+ BasicText(it, style = TextStyle(sub, 12.sp))+ }+ state.errorMessage?.let { BasicText(it, style = TextStyle(Color(0xFFFFB300), 12.sp)) }- Box(Modifier.fillMaxWidth().weight(1f).liquidGlassPanel(backdrop, uiSensor).padding(14.dp)) {- when {- state.isExtracting -> Box(Modifier.fillMaxSize(), Alignment.Center) {- CircularProgressIndicator(color = accent, strokeWidth = 2.dp)- }- state.text.isNotEmpty() -> SelectionContainer(Modifier.fillMaxSize().verticalScroll(rememberScrollState())) {- BasicText(state.text, style = TextStyle(text, 14.sp))- }- state.hasResult -> Box(Modifier.fillMaxSize(), Alignment.Center) {- BasicText("No text layer in this PDF.", style = TextStyle(sub, 13.sp))- }- else -> Box(Modifier.fillMaxSize(), Alignment.Center) {- BasicText("Pick a PDF to pull its text.", style = TextStyle(sub, 13.sp))+ Box(Modifier.fillMaxWidth().weight(1f).liquidGlassPanel(backdrop, uiSensor).padding(14.dp)) {+ when {+ state.isExtracting -> Box(Modifier.fillMaxSize(), Alignment.Center) {+ CircularProgressIndicator(color = accent, strokeWidth = 2.dp)+ }+ state.text.isNotEmpty() -> SelectionContainer(Modifier.fillMaxSize().verticalScroll(rememberScrollState())) {+ BasicText(state.text, style = TextStyle(text, 14.sp))+ }+ state.hasResult -> Box(Modifier.fillMaxSize(), Alignment.Center) {+ BasicText("No text layer in this PDF.", style = TextStyle(sub, 13.sp))+ }+ else -> Box(Modifier.fillMaxSize(), Alignment.Center) {+ BasicText("Pick a PDF to pull its text.", style = TextStyle(sub, 13.sp))+ }}}+ Spacer(Modifier.height(8.dp))}- Spacer(Modifier.height(8.dp))}}diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/HomeScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/HomeScreen.ktindex 32c2164..f3e7b42 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/HomeScreen.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/HomeScreen.kt@@ -78,6 +78,8 @@ import java.util.Localeimport com.chethan616.clearpdf.ui.components.CloseCrossIcon+import androidx.compose.ui.graphics.graphicsLayer+@Composablefun HomeScreen(backdrop: LayerBackdrop,@@ -111,6 +113,47 @@ fun HomeScreen(onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }}+ var isVisible by remember { mutableStateOf(false) }+ androidx.compose.runtime.LaunchedEffect(Unit) {+ isVisible = true+ }++ val density = androidx.compose.ui.platform.LocalDensity.current.density++ // Progressive staggered component animations (slow fade-in)+ val topBarAlpha by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 1f else 0f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 550, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "topBarAlpha"+ )+ val topBarOffsetY by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 0f else 18f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 550, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "topBarOffsetY"+ )++ val cardAlpha by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 1f else 0f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 620, delayMillis = 100, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "cardAlpha"+ )+ val cardOffsetY by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 0f else 24f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 620, delayMillis = 100, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "cardOffsetY"+ )++ val recentsAlpha by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 1f else 0f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 700, delayMillis = 200, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "recentsAlpha"+ )+ val recentsOffsetY by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 0f else 30f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 700, delayMillis = 200, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "recentsOffsetY"+ )+Box(Modifier.fillMaxSize()) {Column(Modifier@@ -120,30 +163,41 @@ fun HomeScreen(.verticalScroll(rememberScrollState()),verticalArrangement = Arrangement.spacedBy(16.dp)) {- LiquidGlassTopBar(- title = "ClearPDF",- backdrop = backdrop,- uiSensor = uiSensor,- actions = {- Box(- Modifier- .clip(RoundedCornerShape(50))- .background(accent.copy(alpha = if (isLight) 0.12f else 0.18f))- .padding(horizontal = 10.dp, vertical = 6.dp)- ) {- BasicText(- "ON DEVICE",- style = TextStyle(accent, 10.sp, FontWeight.Bold)- )- }+ Box(+ Modifier.graphicsLayer {+ alpha = topBarAlpha+ translationY = topBarOffsetY * density}- )+ ) {+ LiquidGlassTopBar(+ title = "ClearPDF",+ backdrop = backdrop,+ uiSensor = uiSensor,+ actions = {+ Box(+ Modifier+ .clip(RoundedCornerShape(50))+ .background(accent.copy(alpha = if (isLight) 0.12f else 0.18f))+ .padding(horizontal = 10.dp, vertical = 6.dp)+ ) {+ BasicText(+ "ON DEVICE",+ style = TextStyle(accent, 10.sp, FontWeight.Bold)+ )+ }+ }+ )+ }// Welcome cardColumn(Modifier- .fillMaxWidth()- .liquidGlassPanel(backdrop, uiSensor)+ .fillMaxWidth()+ .graphicsLayer {+ alpha = cardAlpha+ translationY = cardOffsetY * density+ }+ .liquidGlassPanel(backdrop, uiSensor).padding(horizontal = 22.dp, vertical = 24.dp),horizontalAlignment = Alignment.CenterHorizontally) {@@ -207,6 +261,10 @@ fun HomeScreen(Column(Modifier.fillMaxWidth()+ .graphicsLayer {+ alpha = recentsAlpha+ translationY = recentsOffsetY * density+ }.liquidGlassPanel(backdrop, uiSensor).padding(20.dp),verticalArrangement = Arrangement.spacedBy(8.dp)diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/ImagesToPdfScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/ImagesToPdfScreen.ktindex d980783..421c62c 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/ImagesToPdfScreen.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/ImagesToPdfScreen.kt@@ -53,6 +53,9 @@ import com.chethan616.clearpdf.ui.viewmodel.ImagesToPdfViewModelimport com.chethan616.clearpdf.ui.components.LiquidSaveDialogimport com.kyant.backdrop.backdrops.LayerBackdrop+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.platform.LocalDensity+@Composablefun ImagesToPdfScreen(backdrop: LayerBackdrop,@@ -74,99 +77,143 @@ fun ImagesToPdfScreen(viewModel.onPickImages(uris)}+ var isVisible by remember { mutableStateOf(false) }+ androidx.compose.runtime.LaunchedEffect(Unit) { isVisible = true }+ val density = LocalDensity.current.density++ val topBarAlpha by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 1f else 0f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 500, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "imagesTopBarAlpha"+ )+ val topBarOffsetY by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 0f else 16f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 500, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "imagesTopBarOffsetY"+ )++ val contentAlpha by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 1f else 0f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 600, delayMillis = 100, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "imagesContentAlpha"+ )+ val contentOffsetY by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 0f else 24f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 600, delayMillis = 100, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "imagesContentOffsetY"+ )+Column(Modifier.fillMaxSize().statusBarsPadding().padding(16.dp),verticalArrangement = Arrangement.spacedBy(12.dp)) {- Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {+ Row(+ Modifier.graphicsLayer {+ alpha = topBarAlpha+ translationY = topBarOffsetY * density+ },+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(12.dp)+ ) {LiquidButton(onClick = onBack, backdrop = backdrop, surfaceColor = Color.White.copy(0.08f)) {Icon(Icons.Rounded.ArrowBackIosNew, "Back", Modifier.size(18.dp), text)}LiquidGlassTopBar("Images → PDF", backdrop, uiSensor, Modifier.weight(1f), titleFontSize = 18.sp)}- Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) {- LiquidButton(onClick = { picker.launch("image/*") }, backdrop = backdrop, tint = accent) {- Icon(Icons.Rounded.AddPhotoAlternate, null, Modifier.size(18.dp), Color.White)- BasicText("Add images", style = TextStyle(Color.White, 14.sp, FontWeight.Medium))- }- if (state.imageUris.isNotEmpty()) {- LiquidButton(onClick = { viewModel.clearImages() }, backdrop = backdrop) {- BasicText("Clear", style = TextStyle(text, 14.sp, FontWeight.Medium))+ Column(+ Modifier+ .fillMaxWidth()+ .weight(1f)+ .graphicsLayer {+ alpha = contentAlpha+ translationY = contentOffsetY * density+ },+ verticalArrangement = Arrangement.spacedBy(12.dp)+ ) {+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) {+ LiquidButton(onClick = { picker.launch("image/*") }, backdrop = backdrop, tint = accent) {+ Icon(Icons.Rounded.AddPhotoAlternate, null, Modifier.size(18.dp), Color.White)+ BasicText("Add images", style = TextStyle(Color.White, 14.sp, FontWeight.Medium))+ }+ if (state.imageUris.isNotEmpty()) {+ LiquidButton(onClick = { viewModel.clearImages() }, backdrop = backdrop) {+ BasicText("Clear", style = TextStyle(text, 14.sp, FontWeight.Medium))+ }}}- }- // Page-size toggle- Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {- LiquidButton(- onClick = { viewModel.setFitToA4(true) }, backdrop = backdrop,- surfaceColor = if (state.fitToA4) accent.copy(0.30f) else Color.White.copy(0.06f)- ) { BasicText("Fit to A4", style = TextStyle(text, 13.sp, FontWeight.Medium)) }- LiquidButton(- onClick = { viewModel.setFitToA4(false) }, backdrop = backdrop,- surfaceColor = if (!state.fitToA4) accent.copy(0.30f) else Color.White.copy(0.06f)- ) { BasicText("Original size", style = TextStyle(text, 13.sp, FontWeight.Medium)) }- }+ // Page-size toggle+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ LiquidButton(+ onClick = { viewModel.setFitToA4(true) }, backdrop = backdrop,+ surfaceColor = if (state.fitToA4) accent.copy(0.30f) else Color.White.copy(0.06f)+ ) { BasicText("Fit to A4", style = TextStyle(text, 13.sp, FontWeight.Medium)) }+ LiquidButton(+ onClick = { viewModel.setFitToA4(false) }, backdrop = backdrop,+ surfaceColor = if (!state.fitToA4) accent.copy(0.30f) else Color.White.copy(0.06f)+ ) { BasicText("Original size", style = TextStyle(text, 13.sp, FontWeight.Medium)) }+ }- Box(Modifier.fillMaxWidth().weight(1f)) {- if (state.imageUris.isEmpty()) {- Box(Modifier.fillMaxSize(), Alignment.Center) {- BasicText("Add photos to build a PDF.", style = TextStyle(sub, 13.sp))- }- } else {- LazyVerticalGrid(- columns = GridCells.Fixed(3),- horizontalArrangement = Arrangement.spacedBy(8.dp),- verticalArrangement = Arrangement.spacedBy(8.dp),- modifier = Modifier.fillMaxSize()- ) {- itemsIndexed(state.imageUris) { index, uri ->- Box(Modifier.aspectRatio(0.75f).clip(RoundedCornerShape(8.dp)).background(Color.White.copy(0.06f))) {- AsyncImage(- model = uri,- contentDescription = "Image ${index + 1}",- contentScale = ContentScale.Crop,- modifier = Modifier.fillMaxSize()- )- Box(- Modifier.align(Alignment.TopEnd).padding(4.dp).size(22.dp)- .clip(CircleShape).background(Color.Black.copy(0.55f))- .clickable { viewModel.removeImage(index) },- Alignment.Center- ) {- Icon(Icons.Rounded.Close, "Remove", Modifier.size(14.dp), Color.White)+ Box(Modifier.fillMaxWidth().weight(1f)) {+ if (state.imageUris.isEmpty()) {+ Box(Modifier.fillMaxSize(), Alignment.Center) {+ BasicText("Add photos to build a PDF.", style = TextStyle(sub, 13.sp))+ }+ } else {+ LazyVerticalGrid(+ columns = GridCells.Fixed(3),+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp),+ modifier = Modifier.fillMaxSize()+ ) {+ itemsIndexed(state.imageUris) { index, uri ->+ Box(Modifier.aspectRatio(0.75f).clip(RoundedCornerShape(8.dp)).background(Color.White.copy(0.06f))) {+ AsyncImage(+ model = uri,+ contentDescription = "Image ${index + 1}",+ contentScale = ContentScale.Crop,+ modifier = Modifier.fillMaxSize()+ )+ Box(+ Modifier.align(Alignment.TopEnd).padding(4.dp).size(22.dp)+ .clip(CircleShape).background(Color.Black.copy(0.55f))+ .clickable { viewModel.removeImage(index) },+ Alignment.Center+ ) {+ Icon(Icons.Rounded.Close, "Remove", Modifier.size(14.dp), Color.White)+ }}}}}}- }- state.errorMessage?.let { BasicText(it, style = TextStyle(Color(0xFFEF5350), 12.sp)) }- state.resultMessage?.let { msg ->- Row(Modifier.fillMaxWidth().liquidGlassPanel(backdrop, uiSensor).padding(12.dp),- horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {- BasicText(msg, style = TextStyle(Color(0xFFB9F6CA), 12.sp), modifier = Modifier.weight(1f))- state.lastOutputUri?.let { uri ->- LiquidButton(onClick = { onViewOutput(uri) }, backdrop = backdrop, tint = accent) {- BasicText("Open", style = TextStyle(Color.White, 12.sp, FontWeight.Medium))+ state.errorMessage?.let { BasicText(it, style = TextStyle(Color(0xFFEF5350), 12.sp)) }+ state.resultMessage?.let { msg ->+ Row(Modifier.fillMaxWidth().liquidGlassPanel(backdrop, uiSensor).padding(12.dp),+ horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {+ BasicText(msg, style = TextStyle(Color(0xFFB9F6CA), 12.sp), modifier = Modifier.weight(1f))+ state.lastOutputUri?.let { uri ->+ LiquidButton(onClick = { onViewOutput(uri) }, backdrop = backdrop, tint = accent) {+ BasicText("Open", style = TextStyle(Color.White, 12.sp, FontWeight.Medium))+ }}}}- }- LiquidButton(- onClick = { if (!state.isSaving && state.imageUris.isNotEmpty()) showSaveDialog = true },- backdrop = backdrop, tint = accent, modifier = Modifier.fillMaxWidth()- ) {- BasicText(- if (state.isSaving) "Creating…" else "Create PDF (${state.imageUris.size})",- style = TextStyle(Color.White, 15.sp, FontWeight.Medium),- modifier = Modifier.padding(vertical = 8.dp)- )+ LiquidButton(+ onClick = { if (!state.isSaving && state.imageUris.isNotEmpty()) showSaveDialog = true },+ backdrop = backdrop, tint = accent, modifier = Modifier.fillMaxWidth()+ ) {+ BasicText(+ if (state.isSaving) "Creating…" else "Create PDF (${state.imageUris.size})",+ style = TextStyle(Color.White, 15.sp, FontWeight.Medium),+ modifier = Modifier.padding(vertical = 8.dp)+ )+ }+ Spacer(Modifier.height(8.dp))}- Spacer(Modifier.height(8.dp))}if (showSaveDialog) {diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/MergePdfScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/MergePdfScreen.ktindex b76fb28..16b2264 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/MergePdfScreen.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/MergePdfScreen.kt@@ -52,6 +52,12 @@ import com.chethan616.clearpdf.ui.viewmodel.MergePdfViewModelimport com.kyant.backdrop.backdrops.LayerBackdropimport kotlinx.coroutines.delay+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.platform.LocalDensity+@Composablefun MergePdfScreen(backdrop: LayerBackdrop,@@ -82,6 +88,32 @@ fun MergePdfScreen(if (uris.isNotEmpty()) viewModel.addFiles(context, uris)}+ var isVisible by remember { mutableStateOf(false) }+ LaunchedEffect(Unit) { isVisible = true }+ val density = LocalDensity.current.density++ val topBarAlpha by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 1f else 0f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 500, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "mergeTopBarAlpha"+ )+ val topBarOffsetY by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 0f else 16f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 500, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "mergeTopBarOffsetY"+ )++ val contentAlpha by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 1f else 0f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 600, delayMillis = 100, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "mergeContentAlpha"+ )+ val contentOffsetY by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 0f else 24f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 600, delayMillis = 100, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "mergeContentOffsetY"+ )+Column(Modifier.fillMaxSize()@@ -90,13 +122,30 @@ fun MergePdfScreen(.verticalScroll(rememberScrollState()),verticalArrangement = Arrangement.spacedBy(16.dp)) {- Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {+ Row(+ Modifier.graphicsLayer {+ alpha = topBarAlpha+ translationY = topBarOffsetY * density+ },+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(12.dp)+ ) {LiquidButton(onClick = onBack, backdrop = backdrop, surfaceColor = Color.White.copy(0.08f)) {Icon(Icons.Rounded.ArrowBackIosNew, "Back", Modifier.size(18.dp), text)}LiquidGlassTopBar(title = "Merge PDFs", backdrop = backdrop, uiSensor = uiSensor, modifier = Modifier.weight(1f))}+ Column(+ Modifier+ .fillMaxWidth()+ .graphicsLayer {+ alpha = contentAlpha+ translationY = contentOffsetY * density+ },+ verticalArrangement = Arrangement.spacedBy(16.dp)+ ) {+Column(Modifier.fillMaxWidth()@@ -213,5 +262,6 @@ fun MergePdfScreen(}Spacer(Modifier.height(80.dp))+ }}}diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PageOrganizerScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PageOrganizerScreen.ktindex 9f7da05..c320050 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PageOrganizerScreen.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PageOrganizerScreen.kt@@ -73,6 +73,8 @@ import com.kyant.backdrop.backdrops.LayerBackdropimport kotlinx.coroutines.delayimport kotlin.math.roundToInt+import androidx.compose.ui.graphics.graphicsLayer+@Composablefun PageOrganizerScreen(backdrop: LayerBackdrop,@@ -91,6 +93,31 @@ fun PageOrganizerScreen(var showSaveDialog by remember { mutableStateOf(false) }+ var isVisible by remember { mutableStateOf(false) }+ androidx.compose.runtime.LaunchedEffect(Unit) { isVisible = true }++ val topBarAlpha by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 1f else 0f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 500, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "organizerTopBarAlpha"+ )+ val topBarOffsetY by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 0f else 16f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 500, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "organizerTopBarOffsetY"+ )++ val contentAlpha by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 1f else 0f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 600, delayMillis = 100, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "organizerContentAlpha"+ )+ val contentOffsetY by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 0f else 24f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 600, delayMillis = 100, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "organizerContentOffsetY"+ )+// Drag-reorder stateval listState = rememberLazyListState()var draggingIds by remember { mutableStateOf<List<Int>>(emptyList()) }@@ -122,13 +149,31 @@ fun PageOrganizerScreen(Modifier.fillMaxSize().statusBarsPadding().padding(16.dp),verticalArrangement = Arrangement.spacedBy(12.dp)) {- Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {+ Row(+ Modifier.graphicsLayer {+ alpha = topBarAlpha+ translationY = topBarOffsetY * density.density+ },+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(12.dp)+ ) {LiquidButton(onClick = onBack, backdrop = backdrop, surfaceColor = Color.White.copy(0.08f)) {Icon(Icons.Rounded.ArrowBackIosNew, "Back", Modifier.size(18.dp), text)}LiquidGlassTopBar("Organize Pages", backdrop, uiSensor, Modifier.weight(1f), titleFontSize = 18.sp)}+ Column(+ Modifier+ .fillMaxWidth()+ .weight(1f)+ .graphicsLayer {+ alpha = contentAlpha+ translationY = contentOffsetY * density.density+ },+ verticalArrangement = Arrangement.spacedBy(12.dp)+ ) {+if (state.sourceUri == null) {Column(Modifier.fillMaxWidth().weight(1f),@@ -362,6 +407,7 @@ fun PageOrganizerScreen()}Spacer(Modifier.height(8.dp))+ }}if (showSaveDialog) {diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerScreen.ktindex 54245f8..abc13e2 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerScreen.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerScreen.kt@@ -7,6 +7,8 @@ import androidx.activity.result.contract.ActivityResultContractsimport androidx.compose.animation.AnimatedVisibilityimport androidx.compose.animation.fadeInimport androidx.compose.animation.fadeOut+import androidx.compose.animation.scaleIn+import androidx.compose.animation.scaleOutimport androidx.compose.animation.core.Animatableimport androidx.compose.animation.core.Springimport androidx.compose.animation.core.VectorConverter@@ -25,6 +27,7 @@ import androidx.compose.foundation.gestures.calculateZoomimport androidx.compose.foundation.gestures.detectDragGesturesimport androidx.compose.foundation.gestures.detectDragGesturesAfterLongPressimport androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.gestures.detectVerticalDragGesturesimport androidx.compose.foundation.horizontalScrollimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Box@@ -34,11 +37,21 @@ import androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.Spacerimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.heightimport androidx.compose.foundation.layout.navigationBarsPadding+import androidx.compose.foundation.layout.offsetimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.sizeimport androidx.compose.foundation.layout.statusBarsPadding+import androidx.compose.foundation.layout.widthimport androidx.compose.foundation.pager.HorizontalPager+import androidx.compose.foundation.pager.VerticalPager+import androidx.compose.material.icons.rounded.FormatListNumbered+import androidx.compose.material.icons.rounded.SwapHoriz+import androidx.compose.material.icons.rounded.SwapVert+import kotlin.math.roundToInt+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.ui.window.Dialogimport androidx.compose.foundation.pager.rememberPagerStateimport androidx.compose.foundation.rememberScrollStateimport androidx.compose.foundation.shape.CircleShape@@ -159,6 +172,8 @@ fun PdfViewerScreen(var controlsVisible by rememberSaveable { mutableStateOf(true) }var controlsPinned by rememberSaveable { mutableStateOf(false) }var lastInteractionAtMs by rememberSaveable { mutableStateOf(System.currentTimeMillis()) }+ var scrollOrientation by rememberSaveable { mutableStateOf(if (com.chethan616.clearpdf.data.repository.AppSettingsManager.getScrollOrientation(context) == 1) ScrollOrientation.Horizontal else ScrollOrientation.Vertical) }+ var showPageJumpDialog by rememberSaveable { mutableStateOf(false) }// ── Zoom / pan – backed by Animatable for smooth transitions ─────────────val zoomAnim = remember { Animatable(1f) }@@ -373,11 +388,11 @@ fun PdfViewerScreen(viewModel.renderPage(context, pagerState.currentPage + 1, renderWidthPx)}- HorizontalPager(- state = pagerState,- userScrollEnabled = pagerScrollEnabled,- modifier = Modifier.fillMaxSize()- ) { page ->+ val pageContent: @Composable (Int) -> Unit = pageContent@ { page ->++++val bitmap = state.pageBitmaps.getOrNull(page)val marks = getPageMarks(page)@@ -394,7 +409,7 @@ fun PdfViewerScreen(Box(Modifier.fillMaxSize().background(Color(0xFF0E1218)), Alignment.Center) {CircularProgressIndicator(color = accent, strokeWidth = 2.dp)}- return@HorizontalPager+ return@pageContent}pageBitmapSizes[page] = Size(bitmap.width.toFloat(), bitmap.height.toFloat())@@ -423,7 +438,7 @@ fun PdfViewerScreen(// 1 finger 1× vertical → ignore (doc scroll)// 1 finger zoomed-in → pan + fling on lift// ─────────────────────────────────────────────────────- .pointerInput(page, activeTool) {+ .pointerInput(page, activeTool, scrollOrientation) {if (activeTool != PdfEditTool.None) return@pointerInputawaitEachGesture {@@ -551,7 +566,9 @@ fun PdfViewerScreen(val isHoriz = angleDeg <= SWIPE_ANGLE_DEG|| angleDeg >= (180f - SWIPE_ANGLE_DEG)- if (isHoriz && zoomAnim.value <= 1.02f) {+ val isSwipeForPager = if (scrollOrientation == ScrollOrientation.Horizontal) isHoriz else !isHoriz++ if (isSwipeForPager && zoomAnim.value <= 1.02f) {// Horizontal swipe at 1× → yield to pagerisOurGesture = falsebreak@loop@@ -964,7 +981,54 @@ fun PdfViewerScreen(}} // outer sizing Box- } // HorizontalPager+ }++ if (scrollOrientation == ScrollOrientation.Vertical) {+ VerticalPager(+ state = pagerState,+ userScrollEnabled = pagerScrollEnabled,+ modifier = Modifier.fillMaxSize(),+ pageContent = { page -> pageContent(page) }+ )+ } else {+ HorizontalPager(+ state = pagerState,+ userScrollEnabled = pagerScrollEnabled,+ modifier = Modifier.fillMaxSize(),+ pageContent = { page -> pageContent(page) }+ )+ }++ // ── Controls overlay ──────────────────────────────────────────────────+ // ── Page Scrubber Minimap (Tied to Controls Visibility) ───────────────+ AnimatedVisibility(+ visible = controlsVisible && safePageCount > 1,+ enter = fadeIn(animationSpec = spring(stiffness = Spring.StiffnessMedium)) ++ scaleIn(initialScale = 0.92f, animationSpec = spring(dampingRatio = Spring.DampingRatioMediumBouncy)),+ exit = fadeOut(animationSpec = spring(stiffness = Spring.StiffnessMedium)) ++ scaleOut(targetScale = 0.92f),+ modifier = Modifier+ .align(Alignment.CenterEnd)+ .navigationBarsPadding()+ .statusBarsPadding()+ .padding(end = 8.dp)+ ) {+ PageScrubber(+ currentPage = pagerState.currentPage,+ pageCount = safePageCount,+ pageBitmaps = state.pageBitmaps,+ backdrop = backdrop,+ uiSensor = uiSensor,+ onPageChange = { page ->+ pagerScope.launch { pagerState.animateScrollToPage(page) }+ lastInteractionAtMs = System.currentTimeMillis()+ },+ onPageScrubbing = { page ->+ viewModel.renderPage(context, page, 400)+ lastInteractionAtMs = System.currentTimeMillis()+ }+ )+ }// ── Controls overlay ──────────────────────────────────────────────────AnimatedVisibility(@@ -993,10 +1057,13 @@ fun PdfViewerScreen(title = "Page ${state.currentPage + 1} / ${state.pageCount}",backdrop = backdrop,uiSensor = uiSensor,- modifier = Modifier.weight(1f),+ modifier = Modifier+ .weight(1f)+ .clickable { showPageJumpDialog = true },titleFontSize = 12.sp,fontWeight = FontWeight.Medium)+LiquidButton(onClick = {val t = (pagerState.currentPage - 1).coerceAtLeast(0)if (t != pagerState.currentPage) pagerScope.launch { pagerState.animateScrollToPage(t) }@@ -1354,14 +1421,343 @@ fun PdfViewerScreen(})}++ if (showPageJumpDialog) {+ LiquidPageJumpDialog(+ currentPage = pagerState.currentPage,+ pageCount = safePageCount,+ backdrop = backdrop,+ uiSensor = uiSensor,+ onDismiss = { showPageJumpDialog = false },+ onJumpToPage = { targetPage ->+ showPageJumpDialog = false+ pagerScope.launch { pagerState.animateScrollToPage(targetPage) }+ }+ )+ }}// ─────────────────────────────────────────────────────────────────────────────// Enums & sealed classes// ─────────────────────────────────────────────────────────────────────────────+private enum class ScrollOrientation { Vertical, Horizontal }+private enum class PdfEditTool { None, Draw, Highlight, Rect, Ellipse, Line, Arrow, SelectText, Image, Eraser }+/**+ * Floating vertical liquid-glass page scrubber minimap with Live PDF Page Preview Window.+ * Features auto-hiding track, physics-based 120Hz spring motion, and a bouncy jelly glass preview window.+ */+@Composable+private fun PageScrubber(+ currentPage: Int,+ pageCount: Int,+ pageBitmaps: List<android.graphics.Bitmap?>,+ backdrop: com.kyant.backdrop.backdrops.LayerBackdrop,+ uiSensor: com.chethan616.clearpdf.ui.utils.UISensor,+ onPageChange: (Int) -> Unit,+ onPageScrubbing: (Int) -> Unit,+ modifier: Modifier = Modifier+) {+ val isDarkMode = LocalIsDarkMode.current+ val accent = Color(0xFF0088FF)++ var isDragging by remember { mutableStateOf(false) }+ var isHoveredOrActive by remember { mutableStateOf(false) }+ var dragPage by remember { mutableIntStateOf(currentPage) }+ var lastTouchTime by remember { mutableLongStateOf(System.currentTimeMillis()) }++ // Auto-hide controller+ LaunchedEffect(currentPage) {+ if (!isDragging) {+ dragPage = currentPage+ isHoveredOrActive = true+ lastTouchTime = System.currentTimeMillis()+ }+ }++ LaunchedEffect(lastTouchTime, isDragging) {+ if (!isDragging) {+ delay(2200)+ isHoveredOrActive = false+ }+ }++ LaunchedEffect(dragPage, isDragging) {+ if (isDragging) {+ onPageScrubbing(dragPage)+ }+ }++ val targetFraction = (currentPage.toFloat() / (pageCount - 1).coerceAtLeast(1)).coerceIn(0f, 1f)+ val animatedFraction by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isDragging) (dragPage.toFloat() / (pageCount - 1).coerceAtLeast(1)).coerceIn(0f, 1f) else targetFraction,+ animationSpec = spring(stiffness = Spring.StiffnessMediumLow, dampingRatio = Spring.DampingRatioNoBouncy),+ label = "thumbFraction"+ )++ val scrubberHeightDp = 280.dp++ // Track width expansion on drag+ val trackWidthDp by androidx.compose.animation.core.animateDpAsState(+ targetValue = if (isDragging) 12.dp else 6.dp,+ animationSpec = spring(stiffness = Spring.StiffnessLow),+ label = "trackWidth"+ )++ Box(+ modifier = modifier.padding(end = 8.dp),+ contentAlignment = Alignment.CenterEnd+ ) {+ // Scrubber Touch & Track Area+ Box(+ modifier = Modifier+ .width(40.dp)+ .height(scrubberHeightDp)+ .pointerInput(pageCount) {+ detectDragGestures(+ onDragStart = { offset ->+ isDragging = true+ isHoveredOrActive = true+ val totalPx = size.height.toFloat()+ val frac = (offset.y / totalPx).coerceIn(0f, 1f)+ val target = (frac * (pageCount - 1)).roundToInt()+ dragPage = target+ onPageScrubbing(target)+ onPageChange(target)+ },+ onDragEnd = {+ isDragging = false+ lastTouchTime = System.currentTimeMillis()+ onPageChange(dragPage)+ },+ onDragCancel = {+ isDragging = false+ lastTouchTime = System.currentTimeMillis()+ },+ onDrag = { change, _ ->+ isHoveredOrActive = true+ val totalPx = size.height.toFloat()+ val frac = (change.position.y / totalPx).coerceIn(0f, 1f)+ val target = (frac * (pageCount - 1)).roundToInt()+ if (target != dragPage) {+ dragPage = target+ onPageScrubbing(target)+ onPageChange(target)+ }+ }+ )+ }+ .pointerInput(pageCount) {+ detectTapGestures { offset ->+ isHoveredOrActive = true+ lastTouchTime = System.currentTimeMillis()+ val totalPx = size.height.toFloat()+ val frac = (offset.y / totalPx).coerceIn(0f, 1f)+ val target = (frac * (pageCount - 1)).roundToInt()+ dragPage = target+ onPageScrubbing(target)+ onPageChange(target)+ }+ },+ contentAlignment = Alignment.Center+ ) {+ // Thin Glass Pillar Track+ Box(+ modifier = Modifier+ .width(trackWidthDp)+ .height(scrubberHeightDp)+ .clip(RoundedCornerShape(50))+ .background(if (isDarkMode) Color.White.copy(0.12f) else Color.Black.copy(0.08f)),+ contentAlignment = Alignment.TopCenter+ ) {+ // Glow Thumb Pill Handle+ Box(+ Modifier+ .padding(top = (scrubberHeightDp * animatedFraction - 16.dp).coerceIn(0.dp, scrubberHeightDp - 32.dp))+ .size(width = if (isDragging) 16.dp else 10.dp, height = 32.dp)+ .clip(RoundedCornerShape(16.dp))+ .background(if (isDragging) accent else Color.White.copy(alpha = 0.95f))+ .border(+ width = 1.dp,+ color = if (isDragging) Color.White.copy(0.6f) else Color.Black.copy(0.1f),+ shape = RoundedCornerShape(16.dp)+ )+ )+ }+ }++ // Animated Floating Live Page Minimap Window+ AnimatedVisibility(+ visible = isDragging,+ enter = fadeIn(animationSpec = spring(stiffness = Spring.StiffnessMedium)) ++ scaleIn(initialScale = 0.85f, animationSpec = spring(dampingRatio = Spring.DampingRatioMediumBouncy, stiffness = Spring.StiffnessMediumLow)),+ exit = fadeOut(animationSpec = spring(stiffness = Spring.StiffnessMedium)) ++ scaleOut(targetScale = 0.9f)+ ) {+ val previewBitmap = pageBitmaps.getOrNull(dragPage)+ val yOffsetDp = (scrubberHeightDp * animatedFraction - scrubberHeightDp / 2).coerceIn(-115.dp, 115.dp)++ Column(+ modifier = Modifier+ .align(Alignment.CenterEnd)+ .offset(x = (-46).dp, y = yOffsetDp)+ .width(145.dp)+ .liquidGlassPanel(backdrop, uiSensor)+ .padding(10.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(8.dp)+ ) {+ // Liquid Glass Header Pill+ Row(+ Modifier+ .clip(RoundedCornerShape(50))+ .background(accent.copy(0.22f))+ .padding(horizontal = 10.dp, vertical = 4.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(4.dp)+ ) {+ Box(+ Modifier+ .size(6.dp)+ .clip(CircleShape)+ .background(accent)+ )+ BasicText(+ "${dragPage + 1} / $pageCount",+ style = TextStyle(Color.White, 12.sp, FontWeight.Bold)+ )+ }++ // Mini PDF Page Bitmap Paper Card+ Box(+ Modifier+ .fillMaxWidth()+ .height(160.dp)+ .clip(RoundedCornerShape(10.dp))+ .background(if (isDarkMode) Color(0xFF1E1E1E) else Color.White)+ .border(+ width = 1.dp,+ color = if (isDarkMode) Color.White.copy(0.12f) else Color.Black.copy(0.08f),+ shape = RoundedCornerShape(10.dp)+ ),+ contentAlignment = Alignment.Center+ ) {+ if (previewBitmap != null && !previewBitmap.isRecycled) {+ Image(+ bitmap = previewBitmap.asImageBitmap(),+ contentDescription = "Page ${dragPage + 1} Minimap Preview",+ modifier = Modifier+ .fillMaxSize()+ .padding(4.dp),+ contentScale = ContentScale.Fit+ )+ } else {+ Column(+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(8.dp)+ ) {+ CircularProgressIndicator(+ Modifier.size(24.dp),+ accent,+ strokeWidth = 2.5.dp+ )+ BasicText(+ "Rendering...",+ style = TextStyle(+ if (isDarkMode) Color.LightGray else Color.DarkGray,+ 11.sp,+ FontWeight.Medium+ )+ )+ }+ }+ }+ }+ }+ }+}++@Composable+private fun LiquidPageJumpDialog(+ currentPage: Int,+ pageCount: Int,+ backdrop: com.kyant.backdrop.backdrops.LayerBackdrop,+ uiSensor: com.chethan616.clearpdf.ui.utils.UISensor,+ onDismiss: () -> Unit,+ onJumpToPage: (Int) -> Unit+) {+ var targetPage by remember { mutableIntStateOf(currentPage) }+ Dialog(onDismissRequest = onDismiss) {+ Column(+ modifier = Modifier+ .fillMaxWidth(0.92f)+ .liquidGlassPanel(backdrop, uiSensor)+ .padding(24.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(16.dp)+ ) {+ Icon(Icons.Rounded.FormatListNumbered, null, Modifier.size(36.dp), Color(0xFF1976D2))+ BasicText(+ "Jump to Page",+ style = TextStyle(Color.White, 18.sp, FontWeight.SemiBold)+ )+ BasicText(+ "Page ${targetPage + 1} of $pageCount",+ style = TextStyle(Color.White.copy(0.7f), 14.sp, FontWeight.Medium)+ )++ if (pageCount > 1) {+ com.chethan616.clearpdf.ui.components.LiquidSlider(+ value = { targetPage.toFloat() },+ onValueChange = { targetPage = it.toInt().coerceIn(0, pageCount - 1) },+ valueRange = 0f..(pageCount - 1).toFloat(),+ visibilityThreshold = 0.5f,+ backdrop = backdrop,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp)+ )+ }++ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceEvenly,+ verticalAlignment = Alignment.CenterVertically+ ) {+ listOf(-5, -1, 1, 5).forEach { step ->+ LiquidButton(+ onClick = {+ targetPage = (targetPage + step).coerceIn(0, pageCount - 1)+ },+ backdrop = backdrop+ ) {+ BasicText(+ if (step > 0) "+$step" else "$step",+ style = TextStyle(Color.White, 12.sp, FontWeight.Medium)+ )+ }+ }+ }++ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(12.dp, Alignment.End)+ ) {+ LiquidButton(onClick = onDismiss, backdrop = backdrop) {+ BasicText("Cancel", style = TextStyle(Color.White.copy(0.7f), 13.sp, FontWeight.Medium))+ }+ LiquidButton(+ onClick = { onJumpToPage(targetPage) },+ backdrop = backdrop,+ tint = Color(0xFF1976D2)+ ) {+ BasicText("Go to Page", style = TextStyle(Color.White, 13.sp, FontWeight.SemiBold))+ }+ }+ }+ }+}+private sealed class PdfMarkup {data class StrokeMarkup(val points: List<Offset>, val color: Color, val width: Float, val alpha: Float) : PdfMarkup()data class RectMarkup(val start: Offset, val end: Offset, val color: Color, val alpha: Float, val filled: Boolean) : PdfMarkup()diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/ScanDocumentScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/ScanDocumentScreen.ktindex fd68149..9073ff1 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/ScanDocumentScreen.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/ScanDocumentScreen.kt@@ -100,6 +100,12 @@ import java.text.SimpleDateFormatimport java.util.Dateimport java.util.Locale+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.runtime.LaunchedEffect+@Composablefun ScanDocumentScreen(backdrop: LayerBackdrop,@@ -117,6 +123,32 @@ fun ScanDocumentScreen(val activity = context as Activityval scope = rememberCoroutineScope()+ var isVisible by remember { mutableStateOf(false) }+ LaunchedEffect(Unit) { isVisible = true }+ val density = LocalDensity.current.density++ val topBarAlpha by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 1f else 0f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 500, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "scanTopBarAlpha"+ )+ val topBarOffsetY by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 0f else 16f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 500, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "scanTopBarOffsetY"+ )++ val contentAlpha by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 1f else 0f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 600, delayMillis = 100, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "scanContentAlpha"+ )+ val contentOffsetY by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 0f else 24f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 600, delayMillis = 100, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "scanContentOffsetY"+ )+// ── ML Kit Document Scanner (created lazily to avoid composition crash) ──val scannerLauncher = rememberLauncherForActivityResult(contract = ActivityResultContracts.StartIntentSenderForResult()@@ -175,9 +207,25 @@ fun ScanDocumentScreen(title = "Scan Document",backdrop = backdrop,uiSensor = uiSensor,- modifier = Modifier.fillMaxWidth()+ modifier = Modifier+ .fillMaxWidth()+ .graphicsLayer {+ alpha = topBarAlpha+ translationY = topBarOffsetY * density+ })+ Column(+ Modifier+ .fillMaxWidth()+ .weight(1f)+ .graphicsLayer {+ alpha = contentAlpha+ translationY = contentOffsetY * density+ },+ verticalArrangement = Arrangement.spacedBy(16.dp)+ ) {+// Error displayAnimatedVisibility(visible = state.error != null,@@ -519,6 +567,7 @@ fun ScanDocumentScreen(}}}+ }}}diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/SettingsScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/SettingsScreen.ktindex 41a1d17..bb97bf5 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/SettingsScreen.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/SettingsScreen.kt@@ -69,6 +69,8 @@ import com.chethan616.clearpdf.ui.utils.rememberUISensorimport com.kyant.backdrop.backdrops.LayerBackdropimport kotlinx.coroutines.delay+import androidx.compose.ui.graphics.graphicsLayer+@Composablefun SettingsScreen(backdrop: LayerBackdrop,@@ -118,6 +120,57 @@ fun SettingsScreen(}}+ var isVisible by remember { mutableStateOf(false) }+ LaunchedEffect(Unit) {+ isVisible = true+ }++ val density = androidx.compose.ui.platform.LocalDensity.current.density++ val topBarAlpha by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 1f else 0f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 550, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "settingsTopBarAlpha"+ )+ val topBarOffsetY by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 0f else 18f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 550, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "settingsTopBarOffsetY"+ )++ val panel1Alpha by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 1f else 0f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 600, delayMillis = 80, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "settingsPanel1Alpha"+ )+ val panel1OffsetY by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 0f else 22f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 600, delayMillis = 80, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "settingsPanel1OffsetY"+ )++ val panel2Alpha by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 1f else 0f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 650, delayMillis = 160, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "settingsPanel2Alpha"+ )+ val panel2OffsetY by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 0f else 26f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 650, delayMillis = 160, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "settingsPanel2OffsetY"+ )++ val panel3Alpha by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 1f else 0f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 700, delayMillis = 240, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "settingsPanel3Alpha"+ )+ val panel3OffsetY by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 0f else 30f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 700, delayMillis = 240, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "settingsPanel3OffsetY"+ )+Column(Modifier.fillMaxSize()@@ -126,11 +179,25 @@ fun SettingsScreen(.verticalScroll(rememberScrollState()),verticalArrangement = Arrangement.spacedBy(16.dp)) {- LiquidGlassTopBar(title = "Settings", backdrop = backdrop, uiSensor = uiSensor, modifier = Modifier.fillMaxWidth())+ Box(+ Modifier.graphicsLayer {+ alpha = topBarAlpha+ translationY = topBarOffsetY * density+ }+ ) {+ LiquidGlassTopBar(title = "Settings", backdrop = backdrop, uiSensor = uiSensor, modifier = Modifier.fillMaxWidth())+ }// ── Theme Mode Selector ──Column(- Modifier.fillMaxWidth().liquidGlassPanel(backdrop, uiSensor).padding(20.dp),+ Modifier+ .fillMaxWidth()+ .graphicsLayer {+ alpha = panel1Alpha+ translationY = panel1OffsetY * density+ }+ .liquidGlassPanel(backdrop, uiSensor)+ .padding(20.dp),verticalArrangement = Arrangement.spacedBy(16.dp)) {Row(@@ -204,7 +271,14 @@ fun SettingsScreen(// ── Save Location ──Column(- Modifier.fillMaxWidth().liquidGlassPanel(backdrop, uiSensor).padding(20.dp),+ Modifier+ .fillMaxWidth()+ .graphicsLayer {+ alpha = panel2Alpha+ translationY = panel2OffsetY * density+ }+ .liquidGlassPanel(backdrop, uiSensor)+ .padding(20.dp),verticalArrangement = Arrangement.spacedBy(14.dp)) {Row(@@ -268,7 +342,14 @@ fun SettingsScreen(// ── File Handling ──Column(- Modifier.fillMaxWidth().liquidGlassPanel(backdrop, uiSensor).padding(20.dp),+ Modifier+ .fillMaxWidth()+ .graphicsLayer {+ alpha = panel3Alpha+ translationY = panel3OffsetY * density+ }+ .liquidGlassPanel(backdrop, uiSensor)+ .padding(20.dp),verticalArrangement = Arrangement.spacedBy(4.dp)) {Row(diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/SplitPdfScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/SplitPdfScreen.ktindex 7f231e2..e4a3a86 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/SplitPdfScreen.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/SplitPdfScreen.kt@@ -58,6 +58,12 @@ import com.chethan616.clearpdf.ui.viewmodel.SplitPdfViewModelimport com.kyant.backdrop.backdrops.LayerBackdropimport kotlinx.coroutines.delay+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.platform.LocalDensity+@OptIn(ExperimentalLayoutApi::class)@Composablefun SplitPdfScreen(@@ -90,6 +96,32 @@ fun SplitPdfScreen(}}+ var isVisible by remember { mutableStateOf(false) }+ LaunchedEffect(Unit) { isVisible = true }+ val density = LocalDensity.current.density++ val topBarAlpha by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 1f else 0f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 500, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "splitTopBarAlpha"+ )+ val topBarOffsetY by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 0f else 16f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 500, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "splitTopBarOffsetY"+ )++ val contentAlpha by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 1f else 0f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 600, delayMillis = 100, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "splitContentAlpha"+ )+ val contentOffsetY by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 0f else 24f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 600, delayMillis = 100, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "splitContentOffsetY"+ )+Column(Modifier.fillMaxSize()@@ -98,13 +130,30 @@ fun SplitPdfScreen(.verticalScroll(rememberScrollState()),verticalArrangement = Arrangement.spacedBy(14.dp)) {- Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {+ Row(+ Modifier.graphicsLayer {+ alpha = topBarAlpha+ translationY = topBarOffsetY * density+ },+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(12.dp)+ ) {LiquidButton(onClick = onBack, backdrop = backdrop, surfaceColor = Color.White.copy(0.08f)) {Icon(Icons.Rounded.ArrowBackIosNew, "Back", Modifier.size(18.dp), text)}LiquidGlassTopBar(title = "Split PDF", backdrop = backdrop, uiSensor = uiSensor, modifier = Modifier.weight(1f))}+ Column(+ Modifier+ .fillMaxWidth()+ .graphicsLayer {+ alpha = contentAlpha+ translationY = contentOffsetY * density+ },+ verticalArrangement = Arrangement.spacedBy(14.dp)+ ) {+Column(Modifier.fillMaxWidth()@@ -313,6 +362,7 @@ fun SplitPdfScreen(}Spacer(Modifier.height(60.dp))+ }}}diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/ToolsScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/ToolsScreen.ktindex 66ab814..ee8ea36 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/ToolsScreen.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/ToolsScreen.kt@@ -1,9 +1,11 @@package com.chethan616.clearpdf.ui.screenimport androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.PaddingValuesimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.sizeimport androidx.compose.foundation.layout.statusBarsPaddingimport androidx.compose.foundation.lazy.grid.GridCellsimport androidx.compose.foundation.lazy.grid.GridItemSpan@@ -21,7 +23,10 @@ import androidx.compose.material.icons.rounded.Reorderimport androidx.compose.material.icons.rounded.TextSnippetimport androidx.compose.material3.Iconimport androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.remember+import androidx.compose.runtime.setValueimport androidx.compose.ui.Modifierimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.graphics.vector.ImageVector@@ -37,6 +42,8 @@ import com.chethan616.clearpdf.ui.theme.LocalIsDarkModeimport com.chethan616.clearpdf.ui.utils.rememberUISensorimport com.kyant.backdrop.backdrops.LayerBackdrop+import androidx.compose.ui.graphics.graphicsLayer+private data class ToolSpec(val id: String,val title: String,@@ -83,42 +90,93 @@ fun ToolsScreen()}+ var isVisible by remember { mutableStateOf(false) }+ androidx.compose.runtime.LaunchedEffect(Unit) {+ isVisible = true+ }++ val density = androidx.compose.ui.platform.LocalDensity.current.density++ val topBarAlpha by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 1f else 0f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 550, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "toolsTopBarAlpha"+ )+ val topBarOffsetY by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 0f else 18f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 550, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "toolsTopBarOffsetY"+ )++ val gridAlpha by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 1f else 0f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 650, delayMillis = 120, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "toolsGridAlpha"+ )+ val gridOffsetY by androidx.compose.animation.core.animateFloatAsState(+ targetValue = if (isVisible) 0f else 26f,+ animationSpec = androidx.compose.animation.core.tween(durationMillis = 650, delayMillis = 120, easing = androidx.compose.animation.core.FastOutSlowInEasing),+ label = "toolsGridOffsetY"+ )+LazyVerticalGrid(columns = GridCells.Fixed(2),modifier = Modifier.fillMaxSize().statusBarsPadding(),contentPadding = PaddingValues(start = 16.dp, top = 16.dp, end = 16.dp, bottom = 96.dp),- horizontalArrangement = Arrangement.spacedBy(12.dp),- verticalArrangement = Arrangement.spacedBy(12.dp)+ horizontalArrangement = Arrangement.spacedBy(14.dp),+ verticalArrangement = Arrangement.spacedBy(14.dp)) {item(span = { GridItemSpan(maxLineSpan) }) {- LiquidGlassTopBar(title = "Tools", backdrop = backdrop, uiSensor = uiSensor)+ Box(+ Modifier.graphicsLayer {+ alpha = topBarAlpha+ translationY = topBarOffsetY * density+ }+ ) {+ LiquidGlassTopBar(title = "Tools", backdrop = backdrop, uiSensor = uiSensor)+ }}item(span = { GridItemSpan(maxLineSpan) }) {- BasicText(- "Everything you need to work with PDFs.",- style = TextStyle(- color = secondary,- fontSize = 14.sp,- fontWeight = FontWeight.Medium,- textAlign = TextAlign.Center- ),- modifier = Modifier.padding(vertical = 4.dp)- )+ Box(+ Modifier.graphicsLayer {+ alpha = topBarAlpha+ translationY = topBarOffsetY * density+ }+ ) {+ BasicText(+ "Everything you need to work with PDFs.",+ style = TextStyle(+ color = secondary,+ fontSize = 14.sp,+ fontWeight = FontWeight.Medium,+ textAlign = TextAlign.Center+ ),+ modifier = Modifier.padding(vertical = 4.dp)+ )+ }}items(toolItems, key = { it.id }) { tool ->- LiquidGlassCard(- title = tool.title,- subtitle = tool.subtitle,- accentColor = tool.accent,- backdrop = backdrop,- uiSensor = uiSensor,- onClick = tool.onClick+ Box(+ Modifier.graphicsLayer {+ alpha = gridAlpha+ translationY = gridOffsetY * density+ }) {- Icon(tool.icon, contentDescription = tool.title, tint = tool.accent)+ LiquidGlassCard(+ title = tool.title,+ subtitle = tool.subtitle,+ accentColor = tool.accent,+ backdrop = backdrop,+ uiSensor = uiSensor,+ onClick = tool.onClick,+ icon = {+ Icon(tool.icon, contentDescription = tool.title, modifier = Modifier.size(26.dp), tint = tool.accent)+ }+ )}}}diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/utils/AppDispatchers.kt b/app/src/main/java/com/chethan616/clearpdf/ui/utils/AppDispatchers.ktnew file mode 100644index 0000000..04437fc--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/ui/utils/AppDispatchers.kt@@ -0,0 +1,28 @@+package com.chethan616.clearpdf.ui.utils++import kotlinx.coroutines.CoroutineDispatcher+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.asCoroutineDispatcher+import java.util.concurrent.Executors++/**+ * Dedicated thread-pool dispatcher for heavy PDF I/O and rendering tasks.+ *+ * Using a separate executor pool instead of the shared [Dispatchers.IO] ensures that+ * PDF rendering / compression / thumbnail generation never blocks coroutines that other+ * parts of the app (e.g. ViewModels) are waiting on — preventing UI-thread starvation.+ *+ * Pool size = min(4, available CPU cores). PDF tasks are mostly I/O-bound so we cap+ * the pool to avoid excessive context-switching on mid-range devices.+ */+object AppDispatchers {+ /** Use for PDF rendering, compression, split, merge, and thumbnail tasks. */+ val pdf: CoroutineDispatcher = Executors.newFixedThreadPool(+ minOf(4, Runtime.getRuntime().availableProcessors())+ ) { runnable ->+ Thread(runnable, "clearpdf-io").also { it.isDaemon = true }+ }.asCoroutineDispatcher()++ /** Standard IO — used for lightweight file-system queries (file names, sizes, permissions). */+ val io: CoroutineDispatcher get() = Dispatchers.IO+}diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/utils/DampedDragAnimation.kt b/app/src/main/java/com/chethan616/clearpdf/ui/utils/DampedDragAnimation.ktindex d9d8ab2..86c2dea 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/utils/DampedDragAnimation.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/utils/DampedDragAnimation.kt@@ -3,7 +3,6 @@ package com.chethan616.clearpdf.ui.utilsimport androidx.compose.animation.core.Animatableimport androidx.compose.animation.core.springimport androidx.compose.foundation.MutatorMutex-import androidx.compose.runtime.Stableimport androidx.compose.runtime.snapshotFlowimport androidx.compose.ui.Modifierimport androidx.compose.ui.geometry.Offset@@ -11,14 +10,12 @@ import androidx.compose.ui.input.pointer.pointerInputimport androidx.compose.ui.input.pointer.util.VelocityTrackerimport androidx.compose.ui.unit.IntSizeimport kotlinx.coroutines.CoroutineScope-import kotlinx.coroutines.Jobimport kotlinx.coroutines.android.awaitFrameimport kotlinx.coroutines.flow.filterimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.launchimport kotlin.math.abs-@Stableclass DampedDragAnimation(private val animationScope: CoroutineScope,val initialValue: Float,@@ -30,35 +27,36 @@ class DampedDragAnimation(val onDragStopped: DampedDragAnimation.() -> Unit,val onDrag: DampedDragAnimation.(size: IntSize, dragAmount: Offset) -> Unit,) {- private companion object {- const val VELOCITY_RANGE_EPSILON = 0.0001f- const val VELOCITY_DELTA_EPSILON = 0.01f- }- private val valueAnimationSpec = spring(1f, 1000f, visibilityThreshold)- private val velocityAnimationSpec = spring(0.5f, 300f, visibilityThreshold * 10f)- private val pressProgressAnimationSpec = spring(1f, 1000f, 0.001f)- private val scaleXAnimationSpec = spring(0.6f, 250f, 0.001f)- private val scaleYAnimationSpec = spring(0.7f, 250f, 0.001f)+ private val valueAnimationSpec =+ spring(1f, 1000f, visibilityThreshold)+ private val velocityAnimationSpec =+ spring(0.5f, 300f, visibilityThreshold * 10f)+ private val pressProgressAnimationSpec =+ spring(1f, 1000f, 0.001f)+ private val scaleXAnimationSpec =+ spring(0.6f, 250f, 0.001f)+ private val scaleYAnimationSpec =+ spring(0.7f, 250f, 0.001f)- private val valueAnimation = Animatable(initialValue, visibilityThreshold)- private val velocityAnimation = Animatable(0f, 5f)- private val pressProgressAnimation = Animatable(0f, 0.001f)- private val scaleXAnimation = Animatable(initialScale, 0.001f)- private val scaleYAnimation = Animatable(initialScale, 0.001f)+ private val valueAnimation =+ Animatable(initialValue, visibilityThreshold)+ private val velocityAnimation =+ Animatable(0f, 5f)+ private val pressProgressAnimation =+ Animatable(0f, 0.001f)+ private val scaleXAnimation =+ Animatable(initialScale, 0.001f)+ private val scaleYAnimation =+ Animatable(initialScale, 0.001f)private val mutatorMutex = MutatorMutex()+private val velocityTracker = VelocityTracker()- private var lastVelocityTarget = 0f- private var valueUpdateJob: Job? = null- private var velocityUpdateJob: Job? = null- private var inputTargetValue = initialValueval value: Float get() = valueAnimation.valueval progress: Float get() = (value - valueRange.start) / (valueRange.endInclusive - valueRange.start)- // Keep the touch target synchronous even though Animatable updates on the- // animation scope. This prevents a fast drag from reading a stale target.- val targetValue: Float get() = inputTargetValue+ val targetValue: Float get() = valueAnimation.targetValueval pressProgress: Float get() = pressProgressAnimation.valueval scaleX: Float get() = scaleXAnimation.valueval scaleY: Float get() = scaleYAnimation.value@@ -85,7 +83,6 @@ class DampedDragAnimation(fun press() {velocityTracker.resetTracking()- lastVelocityTarget = 0fanimationScope.launch {launch { pressProgressAnimation.animateTo(1f, pressProgressAnimationSpec) }launch { scaleXAnimation.animateTo(pressedScale, scaleXAnimationSpec) }@@ -99,7 +96,7 @@ class DampedDragAnimation(if (value != targetValue) {val threshold = (valueRange.endInclusive - valueRange.start) * 0.025fsnapshotFlow { valueAnimation.value }- .filter { abs(it - targetValue) < threshold }+ .filter { abs(it - valueAnimation.targetValue) < threshold }.first()}launch { pressProgressAnimation.animateTo(0f, pressProgressAnimationSpec) }@@ -110,25 +107,17 @@ class DampedDragAnimation(fun updateValue(value: Float) {val targetValue = value.coerceIn(valueRange)- inputTargetValue = targetValue- valueUpdateJob?.cancel()- valueUpdateJob = animationScope.launch {- // A drag is already a continuous gesture. Animating every sample- // creates a queue of spring jobs and makes the thumb trail behind.- valueAnimation.snapTo(targetValue)- updateVelocity()+ animationScope.launch {+ launch { valueAnimation.animateTo(targetValue, valueAnimationSpec) { updateVelocity() } }}}fun animateToValue(value: Float) {- val target = value.coerceIn(valueRange)- inputTargetValue = target- valueUpdateJob?.cancel()- velocityUpdateJob?.cancel()animationScope.launch {mutatorMutex.mutate {press()- launch { valueAnimation.animateTo(target, valueAnimationSpec) }+ val targetValue = value.coerceIn(valueRange)+ launch { valueAnimation.animateTo(targetValue, valueAnimationSpec) }if (velocity != 0f) {launch { velocityAnimation.animateTo(0f, velocityAnimationSpec) }}@@ -138,16 +127,11 @@ class DampedDragAnimation(}private fun updateVelocity() {- velocityTracker.addPosition(System.currentTimeMillis(), Offset(value, 0f))- val range = (valueRange.endInclusive - valueRange.start).coerceAtLeast(VELOCITY_RANGE_EPSILON)- val targetVelocity = velocityTracker.calculateVelocity().x / range- if (abs(targetVelocity - lastVelocityTarget) < VELOCITY_DELTA_EPSILON) return- lastVelocityTarget = targetVelocity- velocityUpdateJob?.cancel()- velocityUpdateJob = animationScope.launch {- // Velocity is visual feedback during a gesture; snapping to the- // newest sample is smoother than stacking spring animations.- velocityAnimation.snapTo(targetVelocity)- }+ velocityTracker.addPosition(+ System.currentTimeMillis(),+ Offset(value, 0f)+ )+ val targetVelocity = velocityTracker.calculateVelocity().x / (valueRange.endInclusive - valueRange.start)+ animationScope.launch { velocityAnimation.animateTo(targetVelocity, velocityAnimationSpec) }}}diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/CompressPdfViewModel.kt b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/CompressPdfViewModel.ktindex 01db589..3056d52 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/CompressPdfViewModel.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/CompressPdfViewModel.kt@@ -18,6 +18,7 @@ import com.chethan616.clearpdf.domain.usecase.CompressPdfUseCaseimport com.chethan616.clearpdf.ui.utils.StarPromptEventBusimport com.kyant.pdfcore.model.CompressionQualityimport com.kyant.pdfcore.model.PdfDocument+import com.chethan616.clearpdf.ui.utils.AppDispatchersimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.StateFlow@@ -50,21 +51,19 @@ class CompressPdfViewModel(private val compressPdfUseCase: CompressPdfUseCase) :fun onSelectFile(context: Context, uri: Uri) {viewModelScope.launch {try {- try {- context.contentResolver.takePersistableUriPermission(- uri,- Intent.FLAG_GRANT_READ_URI_PERMISSION- )- } catch (_: Exception) {- // Some providers do not support persistable grants.+ val (name, size, estimate) = withContext(AppDispatchers.pdf) {+ try {+ context.contentResolver.takePersistableUriPermission(+ uri, Intent.FLAG_GRANT_READ_URI_PERMISSION+ )+ } catch (_: Exception) {}+ val fileName = queryFileName(context, uri) ?: "Unknown.pdf"+ val fileSize = context.contentResolver.openFileDescriptor(uri, "r")+ ?.use { it.statSize } ?: -1L+ val source = PdfDocument(uri = uri, name = fileName, sizeBytes = fileSize)+ val est = compressPdfUseCase.estimateSize(source, CompressionQuality.MEDIUM)+ Triple(fileName, fileSize, est)}-- val name = queryFileName(context, uri) ?: "Unknown.pdf"- val size = context.contentResolver.openFileDescriptor(uri, "r")?.use { it.statSize } ?: -1L-- val source = PdfDocument(uri = uri, name = name, sizeBytes = size)- val estimate = compressPdfUseCase.estimateSize(source, CompressionQuality.MEDIUM)-_uiState.value = CompressPdfUiState(sourceFileName = name,sourceUri = uri,@@ -112,23 +111,25 @@ class CompressPdfViewModel(private val compressPdfUseCase: CompressPdfUseCase) :else -> CompressionQuality.HIGH}val sourceUri = current.sourceUri- val estimate = if (quality != current.selectedQuality && sourceUri != null) {- compressPdfUseCase.estimateSize(- source = PdfDocument(- uri = sourceUri,- name = current.sourceFileName,- sizeBytes = current.originalSizeBytes- ),- quality = quality- )- } else {- current.estimatedSizeBytes- }_uiState.value = current.copy(qualitySlider = value,- selectedQuality = quality,- estimatedSizeBytes = estimate+ selectedQuality = quality)+ if (quality != current.selectedQuality && sourceUri != null) {+ viewModelScope.launch(Dispatchers.IO) {+ try {+ val estimate = compressPdfUseCase.estimateSize(+ source = PdfDocument(+ uri = sourceUri,+ name = current.sourceFileName,+ sizeBytes = current.originalSizeBytes+ ),+ quality = quality+ )+ _uiState.value = _uiState.value.copy(estimatedSizeBytes = estimate)+ } catch (_: Exception) {}+ }+ }}fun onCompress(context: Context) {@@ -161,7 +162,7 @@ class CompressPdfViewModel(private val compressPdfUseCase: CompressPdfUseCase) :compressedSizeBytes = result.sizeBytes,lastOutputUri = outUri,saveLocationLabel = saveLabel,- resultMessage = "Compressed: ${origKb}KB → ${compKb}KB (${reduction}% smaller)\nSaved to $saveLabel"+ resultMessage = "Compressed: ${origKb}KB → ${compKb}KB (${reduction}% smaller)\nSaved to $saveLabel")if (GitHubStarPromptManager.recordPdfInteraction(context)) {@@ -179,7 +180,6 @@ class CompressPdfViewModel(private val compressPdfUseCase: CompressPdfUseCase) :fun clearFeedback() {_uiState.value = _uiState.value.copy(resultMessage = null, errorMessage = null)}-private fun queryFileName(context: Context, uri: Uri): String? {return try {context.contentResolver.query(uri, null, null, null, null)?.use { cursor ->diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/MergePdfViewModel.kt b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/MergePdfViewModel.ktindex b79b612..f89553e 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/MergePdfViewModel.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/MergePdfViewModel.kt@@ -17,6 +17,7 @@ import com.chethan616.clearpdf.data.repository.SaveLocationManagerimport com.chethan616.clearpdf.domain.usecase.MergePdfUseCaseimport com.chethan616.clearpdf.ui.utils.StarPromptEventBusimport com.kyant.pdfcore.model.PdfDocument+import com.chethan616.clearpdf.ui.utils.AppDispatchersimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.StateFlow@@ -44,17 +45,19 @@ class MergePdfViewModel(private val mergePdfUseCase: MergePdfUseCase) : ViewModefun addFiles(context: Context, uris: List<Uri>) {viewModelScope.launch {- uris.forEach { uri ->- try {- context.contentResolver.takePersistableUriPermission(- uri,- Intent.FLAG_GRANT_READ_URI_PERMISSION- )- } catch (_: Exception) {- // Some providers do not support persistable grants.+ val newNames = withContext(Dispatchers.IO) {+ uris.forEach { uri ->+ try {+ context.contentResolver.takePersistableUriPermission(+ uri,+ Intent.FLAG_GRANT_READ_URI_PERMISSION+ )+ } catch (_: Exception) {+ // Some providers do not support persistable grants.+ }}+ uris.map { uri -> queryFileName(context, uri) ?: "Unknown.pdf" }}- val newNames = uris.map { uri -> queryFileName(context, uri) ?: "Unknown.pdf" }_uiState.value = _uiState.value.copy(selectedFiles = _uiState.value.selectedFiles + newNames,selectedUris = _uiState.value.selectedUris + uris,@@ -101,7 +104,7 @@ class MergePdfViewModel(private val mergePdfUseCase: MergePdfUseCase) : ViewModeval sources = uris.map { uri ->PdfDocument(uri = uri, name = queryFileName(context, uri) ?: "file.pdf")}- val outputUri = withContext(Dispatchers.IO) {+ val outputUri = withContext(AppDispatchers.pdf) {val outUri = createOutputUri(context, "Merged")mergePdfUseCase.merge(context, sources, outUri)outUridiff --git a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/PageOrganizerViewModel.kt b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/PageOrganizerViewModel.ktindex 597e7f1..85ff7d4 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/PageOrganizerViewModel.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/PageOrganizerViewModel.kt@@ -164,19 +164,22 @@ class PageOrganizerViewModel(private val editor: PdfEditor) : ViewModel() {val rotations = pages.associate { it.originalIndex to it.rotation }.filterValues { it != 0 }withContext(Dispatchers.IO) { editor.applyPageEdits(context, source, order, rotations, outUri) }- RecentFilesManager.addRecent(context, RecentFile(- name = queryFileName(context, outUri) ?: target,- uriString = outUri.toString(),- timestamp = System.currentTimeMillis(),- pageCount = pages.size- ))+ withContext(Dispatchers.IO) {+ RecentFilesManager.addRecent(context, RecentFile(+ name = queryFileName(context, outUri) ?: target,+ uriString = outUri.toString(),+ timestamp = System.currentTimeMillis(),+ pageCount = pages.size+ ))+ }_uiState.value = _uiState.value.copy(isSaving = false,lastOutputUri = outUri,saveLocationLabel = saveLabel,resultMessage = "Saved ${pages.size} pages\nSaved to $saveLabel")- if (GitHubStarPromptManager.recordPdfInteraction(context)) StarPromptEventBus.requestPrompt()+ val shouldPrompt = withContext(Dispatchers.IO) { GitHubStarPromptManager.recordPdfInteraction(context) }+ if (shouldPrompt) StarPromptEventBus.requestPrompt()} catch (e: Exception) {_uiState.value = _uiState.value.copy(isSaving = false, errorMessage = e.message ?: "Save failed")}diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/PdfViewerViewModel.kt b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/PdfViewerViewModel.ktindex 45149dd..95d9f1b 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/PdfViewerViewModel.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/PdfViewerViewModel.kt@@ -25,6 +25,7 @@ import com.google.mlkit.vision.common.InputImageimport com.google.mlkit.vision.text.TextRecognitionimport com.google.mlkit.vision.text.latin.TextRecognizerOptionsimport com.kyant.pdfcore.model.PdfDocument+import com.chethan616.clearpdf.ui.utils.AppDispatchersimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.StateFlow@@ -287,7 +288,7 @@ class PdfViewerViewModel(private val openPdfUseCase: OpenPdfUseCase) : ViewModelviewModelScope.launch {try {- val bitmap = withContext(Dispatchers.IO) {+ val bitmap = withContext(AppDispatchers.pdf) {openPdfUseCase.renderPage(doc, pageIndex, renderWidth)}diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/SplitPdfViewModel.kt b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/SplitPdfViewModel.ktindex 5226ea7..973cec9 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/SplitPdfViewModel.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/SplitPdfViewModel.kt@@ -18,6 +18,7 @@ import com.chethan616.clearpdf.data.repository.SaveLocationManagerimport com.chethan616.clearpdf.ui.utils.StarPromptEventBusimport com.kyant.pdfcore.model.PdfDocumentimport com.kyant.pdfcore.splitter.PdfSplitter+import com.chethan616.clearpdf.ui.utils.AppDispatchersimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.StateFlow@@ -55,23 +56,22 @@ class SplitPdfViewModel(private val splitter: PdfSplitter) : ViewModel() {fun onSelectFile(context: Context, uri: Uri) {viewModelScope.launch {try {- try {- context.contentResolver.takePersistableUriPermission(- uri,- Intent.FLAG_GRANT_READ_URI_PERMISSION- )- } catch (_: Exception) {- // Some providers do not support persistable grants.- }+ val (name, count, thumbnails) = withContext(AppDispatchers.pdf) {+ try {+ context.contentResolver.takePersistableUriPermission(+ uri,+ Intent.FLAG_GRANT_READ_URI_PERMISSION+ )+ } catch (_: Exception) {+ // Some providers do not support persistable grants.+ }- val fd = context.contentResolver.openFileDescriptor(uri, "r") ?: return@launch- val renderer = withContext(Dispatchers.IO) { android.graphics.pdf.PdfRenderer(fd) }- val name = queryFileName(context, uri) ?: "Unknown.pdf"- val count = renderer.pageCount+ val fd = context.contentResolver.openFileDescriptor(uri, "r") ?: return@withContext Triple("", 0, emptyList<Bitmap?>())+ val renderer = android.graphics.pdf.PdfRenderer(fd)+ val fileName = queryFileName(context, uri) ?: "Unknown.pdf"+ val pageCount = renderer.pageCount- // Render small thumbnails for all pages- val thumbnails = withContext(Dispatchers.IO) {- (0 until count).map { i ->+ val thumbs = (0 until pageCount).map { i ->try {val page = renderer.openPage(i)val thumbWidth = 300@@ -84,10 +84,14 @@ class SplitPdfViewModel(private val splitter: PdfSplitter) : ViewModel() {bmp} catch (_: Exception) { null }}++ renderer.close()+ fd.close()+ Triple(fileName, pageCount, thumbs)}- renderer.close()- fd.close()+ if (count == 0) return@launch+_uiState.value = SplitPdfUiState(sourceFileName = name,sourceUri = uri,@@ -142,11 +146,11 @@ class SplitPdfViewModel(private val splitter: PdfSplitter) : ViewModel() {val saveLabel = SaveLocationManager.getSavePathDisplay(context)val outDir = Uri.fromFile(context.cacheDir)val source = PdfDocument(uri = srcUri, name = _uiState.value.sourceFileName)- val results = withContext(Dispatchers.IO) { splitter.splitAll(context, source, outDir) }+ val results = withContext(AppDispatchers.pdf) { splitter.splitAll(context, source, outDir) }var firstOutputUri: Uri? = null// Copy split pages to Downloads- withContext(Dispatchers.IO) {+ withContext(AppDispatchers.pdf) {for (doc in results) {val outUri = createOutputUri(context, doc.name)if (firstOutputUri == null) firstOutputUri = outUri@@ -191,7 +195,7 @@ class SplitPdfViewModel(private val splitter: PdfSplitter) : ViewModel() {val saveLabel = SaveLocationManager.getSavePathDisplay(context)val outUri = createOutputUri(context, "ClearPDF_Extract_${System.currentTimeMillis()}.pdf")val source = PdfDocument(uri = srcUri, name = _uiState.value.sourceFileName)- withContext(Dispatchers.IO) { splitter.extractPages(context, source, pages, outUri) }+ withContext(AppDispatchers.pdf) { splitter.extractPages(context, source, pages, outUri) }RecentFilesManager.addRecent(context, RecentFile(name = queryFileName(context, outUri) ?: "Extracted.pdf",uriString = outUri.toString(),diff --git a/backdrop/build.gradle.kts b/backdrop/build.gradle.ktsindex b37350c..1ba642e 100644--- a/backdrop/build.gradle.kts+++ b/backdrop/build.gradle.kts@@ -5,29 +5,25 @@ plugins {android {namespace = "com.kyant.backdrop"- compileSdk {- version = release(36)- }+ compileSdk = 36buildToolsVersion = "36.1.0"defaultConfig {- minSdk = 21- consumerProguardFiles("consumer-rules.pro")+ minSdk = 23}- buildTypes {- release {- isMinifyEnabled = false- proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")- }- }buildFeatures {compose = true}++ compileOptions {+ sourceCompatibility = JavaVersion.VERSION_17+ targetCompatibility = JavaVersion.VERSION_17+ }}kotlin {- jvmToolchain(21)+ jvmToolchain(17)compilerOptions {freeCompilerArgs.addAll("-Xcontext-parameters"@@ -36,6 +32,7 @@ kotlin {}dependencies {+ implementation(libs.androidx.core.ktx)implementation(libs.androidx.compose.foundation)implementation(libs.androidx.compose.ui)implementation(libs.androidx.compose.ui.graphics)diff --git a/backdrop/src/androidMain/kotlin/com/kyant/backdrop/Platform.kt b/backdrop/src/androidMain/kotlin/com/kyant/backdrop/Platform.ktnew file mode 100644index 0000000..4d0e924--- /dev/null+++ b/backdrop/src/androidMain/kotlin/com/kyant/backdrop/Platform.kt@@ -0,0 +1,10 @@+package com.kyant.backdrop++import android.os.Build+import androidx.annotation.ChecksSdkIntAtLeast++@ChecksSdkIntAtLeast(Build.VERSION_CODES.S)+actual fun isRenderEffectSupported(): Boolean = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S++@ChecksSdkIntAtLeast(Build.VERSION_CODES.TIRAMISU)+actual fun isRuntimeShaderSupported(): Boolean = Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISUdiff --git a/backdrop/src/androidMain/kotlin/com/kyant/backdrop/RuntimeShader.kt b/backdrop/src/androidMain/kotlin/com/kyant/backdrop/RuntimeShader.ktnew file mode 100644index 0000000..433ad70--- /dev/null+++ b/backdrop/src/androidMain/kotlin/com/kyant/backdrop/RuntimeShader.kt@@ -0,0 +1,70 @@+package com.kyant.backdrop++import android.os.Build+import androidx.annotation.RequiresApi+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Shader+import androidx.compose.ui.graphics.toArgb+import org.intellij.lang.annotations.Language++@RequiresApi(Build.VERSION_CODES.TIRAMISU)+actual fun RuntimeShader(@Language("AGSL") shaderString: String): RuntimeShader {+ val shader = android.graphics.RuntimeShader(shaderString)+ return AndroidRuntimeShader(shader)+}++actual fun RuntimeShader.asComposeShader(): Shader {+ return this.asAndroidRuntimeShader()+}++fun RuntimeShader.asAndroidRuntimeShader(): android.graphics.RuntimeShader {+ return (this as AndroidRuntimeShader).shader+}++@RequiresApi(Build.VERSION_CODES.TIRAMISU)+internal class AndroidRuntimeShader(val shader: android.graphics.RuntimeShader) : RuntimeShader {++ override fun setFloatUniform(name: String, value: Float) {+ shader.setFloatUniform(name, value)+ }++ override fun setFloatUniform(name: String, value1: Float, value2: Float) {+ shader.setFloatUniform(name, value1, value2)+ }++ override fun setFloatUniform(name: String, value1: Float, value2: Float, value3: Float) {+ shader.setFloatUniform(name, value1, value2, value3)+ }++ override fun setFloatUniform(name: String, value1: Float, value2: Float, value3: Float, value4: Float) {+ shader.setFloatUniform(name, value1, value2, value3, value4)+ }++ override fun setFloatUniform(name: String, values: FloatArray) {+ shader.setFloatUniform(name, values)+ }++ override fun setIntUniform(name: String, value: Int) {+ shader.setIntUniform(name, value)+ }++ override fun setIntUniform(name: String, value1: Int, value2: Int) {+ shader.setIntUniform(name, value1, value2)+ }++ override fun setIntUniform(name: String, value1: Int, value2: Int, value3: Int) {+ shader.setIntUniform(name, value1, value2, value3)+ }++ override fun setIntUniform(name: String, value1: Int, value2: Int, value3: Int, value4: Int) {+ shader.setIntUniform(name, value1, value2, value3, value4)+ }++ override fun setIntUniform(name: String, values: IntArray) {+ shader.setIntUniform(name, values)+ }++ override fun setColorUniform(name: String, color: Color) {+ shader.setColorUniform(name, color.toArgb())+ }+}diff --git a/backdrop/src/androidMain/kotlin/com/kyant/backdrop/internal/Paint.kt b/backdrop/src/androidMain/kotlin/com/kyant/backdrop/internal/Paint.ktnew file mode 100644index 0000000..081428b--- /dev/null+++ b/backdrop/src/androidMain/kotlin/com/kyant/backdrop/internal/Paint.kt@@ -0,0 +1,16 @@+package com.kyant.backdrop.internal++import android.graphics.BlurMaskFilter+import androidx.compose.ui.graphics.Paint+import com.kyant.backdrop.RuntimeShader+import com.kyant.backdrop.asAndroidRuntimeShader++internal actual fun Paint.blur(radius: Float) {+ this.asFrameworkPaint().maskFilter =+ if (radius > 0f) BlurMaskFilter(radius, BlurMaskFilter.Blur.NORMAL)+ else null+}++internal actual fun Paint.setRuntimeShader(runtimeShader: RuntimeShader?) {+ this.asFrameworkPaint().shader = runtimeShader?.asAndroidRuntimeShader()+}diff --git a/backdrop/src/androidMain/kotlin/com/kyant/backdrop/internal/RenderEffect.kt b/backdrop/src/androidMain/kotlin/com/kyant/backdrop/internal/RenderEffect.ktnew file mode 100644index 0000000..22048e9--- /dev/null+++ b/backdrop/src/androidMain/kotlin/com/kyant/backdrop/internal/RenderEffect.kt@@ -0,0 +1,50 @@+package com.kyant.backdrop.internal++import android.os.Build+import androidx.annotation.RequiresApi+import androidx.compose.ui.graphics.ColorFilter+import androidx.compose.ui.graphics.RenderEffect+import androidx.compose.ui.graphics.asAndroidColorFilter+import androidx.compose.ui.graphics.asComposeRenderEffect+import com.kyant.backdrop.RuntimeShader+import com.kyant.backdrop.asAndroidRuntimeShader++@RequiresApi(Build.VERSION_CODES.S)+internal actual fun RenderEffect?.chain(other: RenderEffect): RenderEffect {+ return if (this != null) {+ android.graphics.RenderEffect.createChainEffect(+ other.asAndroidRenderEffect(),+ this.asAndroidRenderEffect()+ ).asComposeRenderEffect()+ } else {+ other+ }+}++@RequiresApi(Build.VERSION_CODES.TIRAMISU)+internal actual fun RuntimeShaderEffect(+ runtimeShader: RuntimeShader,+ uniformShaderName: String+): RenderEffect {+ return android.graphics.RenderEffect.createRuntimeShaderEffect(+ runtimeShader.asAndroidRuntimeShader(),+ uniformShaderName+ ).asComposeRenderEffect()+}++@RequiresApi(Build.VERSION_CODES.S)+internal actual fun ColorFilterEffect(+ renderEffect: RenderEffect?,+ colorFilter: ColorFilter+): RenderEffect {+ return if (renderEffect != null) {+ android.graphics.RenderEffect.createColorFilterEffect(+ colorFilter.asAndroidColorFilter(),+ renderEffect.asAndroidRenderEffect()+ ).asComposeRenderEffect()+ } else {+ android.graphics.RenderEffect.createColorFilterEffect(+ colorFilter.asAndroidColorFilter(),+ ).asComposeRenderEffect()+ }+}diff --git a/backdrop/src/commonMain/kotlin/com/kyant/backdrop/Backdrop.kt b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/Backdrop.ktnew file mode 100644index 0000000..a617938--- /dev/null+++ b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/Backdrop.kt@@ -0,0 +1,17 @@+package com.kyant.backdrop++import androidx.compose.ui.graphics.GraphicsLayerScope+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.layout.LayoutCoordinates+import androidx.compose.ui.unit.Density++interface Backdrop {++ val isCoordinatesDependent: Boolean++ fun DrawScope.drawBackdrop(+ density: Density,+ coordinates: LayoutCoordinates?,+ layerBlock: (GraphicsLayerScope.() -> Unit)? = null+ )+}diff --git a/backdrop/src/commonMain/kotlin/com/kyant/backdrop/BackdropEffectScope.kt b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/BackdropEffectScope.ktnew file mode 100644index 0000000..dc42af3--- /dev/null+++ b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/BackdropEffectScope.kt@@ -0,0 +1,74 @@+package com.kyant.backdrop++import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.RenderEffect+import androidx.compose.ui.graphics.Shape+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.unit.Density+import androidx.compose.ui.unit.LayoutDirection++sealed interface BackdropEffectScope : Density, RuntimeShaderCache {++ val size: Size++ val layoutDirection: LayoutDirection++ val shape: Shape++ var padding: Float++ var renderEffect: RenderEffect?+}++internal abstract class BackdropEffectScopeImpl : BackdropEffectScope, RuntimeShaderCache {++ override var density: Float = 1f+ override var fontScale: Float = 1f+ override var size: Size = Size.Unspecified+ override var layoutDirection: LayoutDirection = LayoutDirection.Ltr+ override var padding: Float = 0f+ override var renderEffect: RenderEffect? = null++ private val runtimeShaderCache = RuntimeShaderCacheImpl()++ override fun obtainRuntimeShader(key: String, string: String): RuntimeShader {+ return runtimeShaderCache.obtainRuntimeShader(key, string)+ }++ fun update(scope: DrawScope): Boolean {+ val newDensity = scope.density+ val newFontScale = scope.fontScale+ val newSize = scope.size+ val newLayoutDirection = scope.layoutDirection++ val changed = newDensity != density ||+ newFontScale != fontScale ||+ newSize != size ||+ newLayoutDirection != layoutDirection++ if (changed) {+ density = newDensity+ fontScale = newFontScale+ size = newSize+ layoutDirection = newLayoutDirection+ }++ return changed+ }++ fun apply(effects: BackdropEffectScope.() -> Unit) {+ padding = 0f+ renderEffect = null+ effects()+ }++ fun reset() {+ density = 1f+ fontScale = 1f+ size = Size.Unspecified+ layoutDirection = LayoutDirection.Ltr+ padding = 0f+ renderEffect = null+ runtimeShaderCache.clear()+ }+}diff --git a/backdrop/src/commonMain/kotlin/com/kyant/backdrop/DrawBackdropModifier.kt b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/DrawBackdropModifier.ktnew file mode 100644index 0000000..d91d6ad--- /dev/null+++ b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/DrawBackdropModifier.kt@@ -0,0 +1,388 @@+package com.kyant.backdrop++import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.neverEqualPolicy+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.GraphicsLayerScope+import androidx.compose.ui.graphics.Shape+import androidx.compose.ui.graphics.drawscope.ContentDrawScope+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.graphics.layer.GraphicsLayer+import androidx.compose.ui.graphics.layer.drawLayer+import androidx.compose.ui.layout.LayoutCoordinates+import androidx.compose.ui.layout.Measurable+import androidx.compose.ui.layout.MeasureResult+import androidx.compose.ui.layout.MeasureScope+import androidx.compose.ui.node.DrawModifierNode+import androidx.compose.ui.node.GlobalPositionAwareModifierNode+import androidx.compose.ui.node.LayoutModifierNode+import androidx.compose.ui.node.ModifierNodeElement+import androidx.compose.ui.node.ObserverModifierNode+import androidx.compose.ui.node.observeReads+import androidx.compose.ui.node.requireGraphicsContext+import androidx.compose.ui.platform.InspectorInfo+import androidx.compose.ui.unit.Constraints+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.IntSize+import com.kyant.backdrop.backdrops.LayerBackdrop+import com.kyant.backdrop.highlight.Highlight+import com.kyant.backdrop.highlight.HighlightElement+import com.kyant.backdrop.internal.ShapeProvider+import com.kyant.backdrop.internal.recordLayer+import com.kyant.backdrop.shadow.InnerShadow+import com.kyant.backdrop.shadow.InnerShadowElement+import com.kyant.backdrop.shadow.Shadow+import com.kyant.backdrop.shadow.ShadowElement++private val DefaultHighlight = { Highlight.Default }+private val DefaultShadow = { Shadow.Default }+private val DefaultOnDrawBackdrop: DrawScope.(DrawScope.() -> Unit) -> Unit = { it() }++fun Modifier.drawPlainBackdrop(+ backdrop: Backdrop,+ shape: () -> Shape,+ effects: BackdropEffectScope.() -> Unit,+ layerBlock: (GraphicsLayerScope.() -> Unit)? = null,+ exportedBackdrop: LayerBackdrop? = null,+ onDrawBehind: (DrawScope.() -> Unit)? = null,+ onDrawBackdrop: DrawScope.(drawBackdrop: DrawScope.() -> Unit) -> Unit = DefaultOnDrawBackdrop,+ onDrawSurface: (DrawScope.() -> Unit)? = null,+ onDrawFront: (DrawScope.() -> Unit)? = null+): Modifier {+ val shapeProvider = ShapeProvider(shape)+ return this+ .then(+ if (layerBlock != null) {+ Modifier.graphicsLayer(layerBlock)+ } else {+ Modifier+ }+ )+ .then(+ DrawBackdropElement(+ backdrop = backdrop,+ shapeProvider = shapeProvider,+ effects = effects,+ layerBlock = layerBlock,+ exportedBackdrop = exportedBackdrop,+ onDrawBehind = onDrawBehind,+ onDrawBackdrop = onDrawBackdrop,+ onDrawSurface = onDrawSurface,+ onDrawFront = onDrawFront+ )+ )+}++fun Modifier.drawBackdrop(+ backdrop: Backdrop,+ shape: () -> Shape,+ effects: BackdropEffectScope.() -> Unit,+ highlight: (() -> Highlight?)? = DefaultHighlight,+ shadow: (() -> Shadow?)? = DefaultShadow,+ innerShadow: (() -> InnerShadow?)? = null,+ layerBlock: (GraphicsLayerScope.() -> Unit)? = null,+ exportedBackdrop: LayerBackdrop? = null,+ onDrawBehind: (DrawScope.() -> Unit)? = null,+ onDrawBackdrop: DrawScope.(drawBackdrop: DrawScope.() -> Unit) -> Unit = DefaultOnDrawBackdrop,+ onDrawSurface: (DrawScope.() -> Unit)? = null,+ onDrawFront: (DrawScope.() -> Unit)? = null+): Modifier {+ val shapeProvider = ShapeProvider(shape)+ return this+ .then(+ if (layerBlock != null) {+ Modifier.graphicsLayer(layerBlock)+ } else {+ Modifier+ }+ )+ .then(+ if (innerShadow != null) {+ InnerShadowElement(+ shapeProvider = shapeProvider,+ shadow = innerShadow+ )+ } else {+ Modifier+ }+ )+ .then(+ if (shadow != null) {+ ShadowElement(+ shapeProvider = shapeProvider,+ shadow = shadow+ )+ } else {+ Modifier+ }+ )+ .then(+ if (highlight != null) {+ HighlightElement(+ shapeProvider = shapeProvider,+ highlight = highlight+ )+ } else {+ Modifier+ }+ )+ .then(+ DrawBackdropElement(+ backdrop = backdrop,+ shapeProvider = shapeProvider,+ effects = effects,+ layerBlock = layerBlock,+ exportedBackdrop = exportedBackdrop,+ onDrawBehind = onDrawBehind,+ onDrawBackdrop = onDrawBackdrop,+ onDrawSurface = onDrawSurface,+ onDrawFront = onDrawFront+ )+ )+}++private class DrawBackdropElement(+ val backdrop: Backdrop,+ val shapeProvider: ShapeProvider,+ val effects: BackdropEffectScope.() -> Unit,+ val layerBlock: (GraphicsLayerScope.() -> Unit)?,+ val exportedBackdrop: LayerBackdrop?,+ val onDrawBehind: (DrawScope.() -> Unit)?,+ val onDrawBackdrop: DrawScope.(drawBackdrop: DrawScope.() -> Unit) -> Unit,+ val onDrawSurface: (DrawScope.() -> Unit)?,+ val onDrawFront: (DrawScope.() -> Unit)?+) : ModifierNodeElement<DrawBackdropNode>() {++ override fun create(): DrawBackdropNode {+ return DrawBackdropNode(+ backdrop = backdrop,+ shapeProvider = shapeProvider,+ effects = effects,+ layerBlock = layerBlock,+ exportedBackdrop = exportedBackdrop,+ onDrawBehind = onDrawBehind,+ onDrawBackdrop = onDrawBackdrop,+ onDrawSurface = onDrawSurface,+ onDrawFront = onDrawFront+ )+ }++ override fun update(node: DrawBackdropNode) {+ node.backdrop = backdrop+ node.shapeProvider = shapeProvider+ node.effects = effects+ node.layerBlock = layerBlock+ if (node.exportedBackdrop != exportedBackdrop) {+ node.exportedBackdrop?.layerCoordinates = null+ node.exportedBackdrop = exportedBackdrop+ }+ node.onDrawBehind = onDrawBehind+ node.onDrawBackdrop = onDrawBackdrop+ node.onDrawSurface = onDrawSurface+ node.onDrawFront = onDrawFront+ node.invalidateDrawCache()+ }++ override fun InspectorInfo.inspectableProperties() {+ name = "drawBackdrop"+ properties["backdrop"] = backdrop+ properties["shapeProvider"] = shapeProvider+ properties["effects"] = effects+ properties["layerBlock"] = layerBlock+ properties["exportedBackdrop"] = exportedBackdrop+ properties["onDrawBehind"] = onDrawBehind+ properties["onDrawBackdrop"] = onDrawBackdrop+ properties["onDrawSurface"] = onDrawSurface+ properties["onDrawFront"] = onDrawFront+ }++ override fun equals(other: Any?): Boolean {+ if (this === other) return true+ if (other !is DrawBackdropElement) return false++ if (backdrop != other.backdrop) return false+ if (shapeProvider != other.shapeProvider) return false+ if (effects != other.effects) return false+ if (layerBlock != other.layerBlock) return false+ if (exportedBackdrop != other.exportedBackdrop) return false+ if (onDrawBehind != other.onDrawBehind) return false+ if (onDrawBackdrop != other.onDrawBackdrop) return false+ if (onDrawSurface != other.onDrawSurface) return false+ if (onDrawFront != other.onDrawFront) return false++ return true+ }++ override fun hashCode(): Int {+ var result = backdrop.hashCode()+ result = 31 * result + shapeProvider.hashCode()+ result = 31 * result + effects.hashCode()+ result = 31 * result + (layerBlock?.hashCode() ?: 0)+ result = 31 * result + (exportedBackdrop?.hashCode() ?: 0)+ result = 31 * result + (onDrawBehind?.hashCode() ?: 0)+ result = 31 * result + onDrawBackdrop.hashCode()+ result = 31 * result + (onDrawSurface?.hashCode() ?: 0)+ result = 31 * result + (onDrawFront?.hashCode() ?: 0)+ return result+ }+}++private class DrawBackdropNode(+ var backdrop: Backdrop,+ var shapeProvider: ShapeProvider,+ var effects: BackdropEffectScope.() -> Unit,+ var layerBlock: (GraphicsLayerScope.() -> Unit)?,+ var exportedBackdrop: LayerBackdrop?,+ var onDrawBehind: (DrawScope.() -> Unit)?,+ var onDrawBackdrop: DrawScope.(drawBackdrop: DrawScope.() -> Unit) -> Unit,+ var onDrawSurface: (DrawScope.() -> Unit)?,+ var onDrawFront: (DrawScope.() -> Unit)?+) : LayoutModifierNode, DrawModifierNode, GlobalPositionAwareModifierNode, ObserverModifierNode, Modifier.Node() {++ private val effectScope =+ object : BackdropEffectScopeImpl() {++ override val shape: Shape get() = shapeProvider.innerShape+ }++ private var graphicsLayer: GraphicsLayer? = null++ private val layoutLayerBlock: GraphicsLayerScope.() -> Unit = {+ clip = true+ shape = shapeProvider.shape+ compositingStrategy = androidx.compose.ui.graphics.CompositingStrategy.Offscreen+ }++ private var layoutCoordinates: LayoutCoordinates? by mutableStateOf(null, neverEqualPolicy())++ private var padding by mutableFloatStateOf(0f)++ private val recordBackdropBlock: (DrawScope.() -> Unit) = {+ val canvas = drawContext.canvas+ val padding = padding++ if (padding != 0f) {+ canvas.translate(padding, padding)+ }+ onDrawBackdrop {+ with(backdrop) {+ drawBackdrop(+ density = effectScope,+ coordinates = layoutCoordinates,+ layerBlock = layerBlock+ )+ }+ }+ if (padding != 0f) {+ canvas.translate(-padding, -padding)+ }+ }++ private val drawBackdropLayer: DrawScope.() -> Unit = {+ val layer = graphicsLayer+ if (layer != null) {+ val padding = padding++ recordLayer(+ layer,+ size = IntSize(+ size.width.toInt() + padding.toInt() * 2,+ size.height.toInt() + padding.toInt() * 2+ ),+ block = recordBackdropBlock+ )++ layer.topLeft =+ if (padding != 0f) IntOffset(-padding.toInt(), -padding.toInt())+ else IntOffset.Zero+ drawLayer(layer)+ }+ }++ override fun MeasureScope.measure(+ measurable: Measurable,+ constraints: Constraints+ ): MeasureResult {+ val placeable = measurable.measure(constraints)+ return layout(placeable.width, placeable.height) {+ placeable.placeWithLayer(IntOffset.Zero, layerBlock = layoutLayerBlock)+ }+ }++ override fun ContentDrawScope.draw() {+ if (effectScope.update(this)) {+ updateEffects()+ }++ onDrawBehind?.invoke(this)+ drawBackdropLayer()+ onDrawSurface?.invoke(this)+ drawContent()+ onDrawFront?.invoke(this)++ exportedBackdrop?.graphicsLayer?.let { layer ->+ recordLayer(layer) {+ onDrawBehind?.invoke(this)+ drawBackdropLayer()+ onDrawSurface?.invoke(this)+ onDrawFront?.invoke(this)+ }+ }+ }++ override fun onGloballyPositioned(coordinates: LayoutCoordinates) {+ if (coordinates.isAttached) {+ if (backdrop.isCoordinatesDependent) {+ layoutCoordinates = coordinates+ } else {+ if (layoutCoordinates != null) {+ layoutCoordinates = null+ }+ }+ exportedBackdrop?.layerCoordinates = coordinates+ }+ }++ override fun onObservedReadsChanged() {+ invalidateDrawCache()+ }++ fun invalidateDrawCache() {+ observeEffects()+ }++ private fun observeEffects() {+ observeReads { updateEffects() }+ }++ private fun updateEffects() {+ if (!isRenderEffectSupported()) return++ effectScope.apply(effects)+ graphicsLayer?.renderEffect = effectScope.renderEffect+ padding = effectScope.padding+ }++ override fun onAttach() {+ val graphicsContext = requireGraphicsContext()+ graphicsLayer = graphicsContext.createGraphicsLayer()++ observeEffects()+ }++ override fun onDetach() {+ val graphicsContext = requireGraphicsContext()+ graphicsLayer?.let { layer ->+ graphicsContext.releaseGraphicsLayer(layer)+ graphicsLayer = null+ }++ effectScope.reset()+ layoutCoordinates = null+ exportedBackdrop?.layerCoordinates = null+ }+}diff --git a/backdrop/src/commonMain/kotlin/com/kyant/backdrop/Platform.kt b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/Platform.ktnew file mode 100644index 0000000..38e2b6f--- /dev/null+++ b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/Platform.kt@@ -0,0 +1,5 @@+package com.kyant.backdrop++expect fun isRenderEffectSupported(): Boolean++expect fun isRuntimeShaderSupported(): Booleandiff --git a/backdrop/src/commonMain/kotlin/com/kyant/backdrop/RuntimeShader.kt b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/RuntimeShader.ktnew file mode 100644index 0000000..6f318f2--- /dev/null+++ b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/RuntimeShader.kt@@ -0,0 +1,26 @@+package com.kyant.backdrop++import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Shader+import org.intellij.lang.annotations.Language++expect fun RuntimeShader(@Language("AGSL") shaderString: String): RuntimeShader++expect fun RuntimeShader.asComposeShader(): Shader++interface RuntimeShader {++ fun setFloatUniform(name: String, value: Float)+ fun setFloatUniform(name: String, value1: Float, value2: Float)+ fun setFloatUniform(name: String, value1: Float, value2: Float, value3: Float)+ fun setFloatUniform(name: String, value1: Float, value2: Float, value3: Float, value4: Float)+ fun setFloatUniform(name: String, values: FloatArray)++ fun setIntUniform(name: String, value: Int)+ fun setIntUniform(name: String, value1: Int, value2: Int)+ fun setIntUniform(name: String, value1: Int, value2: Int, value3: Int)+ fun setIntUniform(name: String, value1: Int, value2: Int, value3: Int, value4: Int)+ fun setIntUniform(name: String, values: IntArray)++ fun setColorUniform(name: String, color: Color)+}diff --git a/backdrop/src/commonMain/kotlin/com/kyant/backdrop/RuntimeShaderCache.kt b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/RuntimeShaderCache.ktnew file mode 100644index 0000000..f7067c1--- /dev/null+++ b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/RuntimeShaderCache.kt@@ -0,0 +1,21 @@+package com.kyant.backdrop++import org.intellij.lang.annotations.Language++sealed interface RuntimeShaderCache {++ fun obtainRuntimeShader(key: String, @Language("AGSL") string: String): RuntimeShader+}++internal class RuntimeShaderCacheImpl : RuntimeShaderCache {++ private val runtimeShaders = mutableMapOf<String, RuntimeShader>()++ override fun obtainRuntimeShader(key: String, string: String): RuntimeShader {+ return runtimeShaders.getOrPut(key) { RuntimeShader(string) }+ }++ fun clear() {+ runtimeShaders.clear()+ }+}diff --git a/backdrop/src/commonMain/kotlin/com/kyant/backdrop/backdrops/Backdrop.kt b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/backdrops/Backdrop.ktnew file mode 100644index 0000000..92bf6ea--- /dev/null+++ b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/backdrops/Backdrop.kt@@ -0,0 +1,37 @@+package com.kyant.backdrop.backdrops++import androidx.compose.runtime.Composable+import androidx.compose.runtime.Immutable+import androidx.compose.runtime.remember+import androidx.compose.ui.graphics.GraphicsLayerScope+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.layout.LayoutCoordinates+import androidx.compose.ui.unit.Density+import com.kyant.backdrop.Backdrop++@Composable+fun rememberBackdrop(+ backdrop: Backdrop,+ onDraw: DrawScope.(drawBackdrop: DrawScope.() -> Unit) -> Unit+): Backdrop {+ return remember(backdrop, onDraw) {+ Backdrop(backdrop, onDraw)+ }+}++@Immutable+private class Backdrop(+ val backdrop: Backdrop,+ val onDraw: DrawScope.(drawBackdrop: DrawScope.() -> Unit) -> Unit+) : Backdrop {++ override val isCoordinatesDependent: Boolean = backdrop.isCoordinatesDependent++ override fun DrawScope.drawBackdrop(+ density: Density,+ coordinates: LayoutCoordinates?,+ layerBlock: (GraphicsLayerScope.() -> Unit)?+ ) {+ onDraw { with(backdrop) { drawBackdrop(density, coordinates, layerBlock) } }+ }+}diff --git a/backdrop/src/commonMain/kotlin/com/kyant/backdrop/backdrops/CanvasBackdrop.kt b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/backdrops/CanvasBackdrop.ktnew file mode 100644index 0000000..74156eb--- /dev/null+++ b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/backdrops/CanvasBackdrop.kt@@ -0,0 +1,35 @@+package com.kyant.backdrop.backdrops++import androidx.compose.runtime.Composable+import androidx.compose.runtime.Immutable+import androidx.compose.runtime.remember+import androidx.compose.ui.graphics.GraphicsLayerScope+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.layout.LayoutCoordinates+import androidx.compose.ui.unit.Density+import com.kyant.backdrop.Backdrop++@Composable+fun rememberCanvasBackdrop(+ onDraw: DrawScope.() -> Unit+): Backdrop {+ return remember(onDraw) {+ CanvasBackdrop(onDraw)+ }+}++@Immutable+private class CanvasBackdrop(+ val onDraw: DrawScope.() -> Unit+) : Backdrop {++ override val isCoordinatesDependent: Boolean = false++ override fun DrawScope.drawBackdrop(+ density: Density,+ coordinates: LayoutCoordinates?,+ layerBlock: (GraphicsLayerScope.() -> Unit)?+ ) {+ onDraw()+ }+}diff --git a/backdrop/src/commonMain/kotlin/com/kyant/backdrop/backdrops/CombinedBackdrop.kt b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/backdrops/CombinedBackdrop.ktnew file mode 100644index 0000000..943d3d7--- /dev/null+++ b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/backdrops/CombinedBackdrop.kt@@ -0,0 +1,99 @@+package com.kyant.backdrop.backdrops++import androidx.compose.runtime.Composable+import androidx.compose.runtime.Immutable+import androidx.compose.runtime.remember+import androidx.compose.ui.graphics.GraphicsLayerScope+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.layout.LayoutCoordinates+import androidx.compose.ui.unit.Density+import com.kyant.backdrop.Backdrop++@Composable+fun rememberCombinedBackdrop(+ backdrop1: Backdrop,+ backdrop2: Backdrop+): Backdrop {+ return remember(backdrop1, backdrop2) {+ Combined2Backdrops(backdrop1, backdrop2)+ }+}++@Composable+fun rememberCombinedBackdrop(+ backdrop1: Backdrop,+ backdrop2: Backdrop,+ backdrop3: Backdrop+): Backdrop {+ return remember(backdrop1, backdrop2, backdrop3) {+ Combined3Backdrops(backdrop1, backdrop2, backdrop3)+ }+}++@Composable+fun rememberCombinedBackdrop(vararg backdrops: Backdrop): Backdrop {+ return remember(*backdrops) {+ CombinedBackdrops(*backdrops)+ }+}++@Immutable+private class Combined2Backdrops(+ val backdrop1: Backdrop,+ val backdrop2: Backdrop+) : Backdrop {++ override val isCoordinatesDependent: Boolean =+ backdrop1.isCoordinatesDependent || backdrop2.isCoordinatesDependent++ override fun DrawScope.drawBackdrop(+ density: Density,+ coordinates: LayoutCoordinates?,+ layerBlock: (GraphicsLayerScope.() -> Unit)?+ ) {+ with(backdrop1) { drawBackdrop(density, coordinates, layerBlock) }+ with(backdrop2) { drawBackdrop(density, coordinates, layerBlock) }+ }+}++@Immutable+private class Combined3Backdrops(+ val backdrop1: Backdrop,+ val backdrop2: Backdrop,+ val backdrop3: Backdrop+) : Backdrop {++ override val isCoordinatesDependent: Boolean =+ backdrop1.isCoordinatesDependent ||+ backdrop2.isCoordinatesDependent ||+ backdrop3.isCoordinatesDependent++ override fun DrawScope.drawBackdrop(+ density: Density,+ coordinates: LayoutCoordinates?,+ layerBlock: (GraphicsLayerScope.() -> Unit)?+ ) {+ with(backdrop1) { drawBackdrop(density, coordinates, layerBlock) }+ with(backdrop2) { drawBackdrop(density, coordinates, layerBlock) }+ with(backdrop3) { drawBackdrop(density, coordinates, layerBlock) }+ }+}++@Immutable+private class CombinedBackdrops(+ vararg val backdrops: Backdrop+) : Backdrop {++ override val isCoordinatesDependent: Boolean =+ backdrops.any { it.isCoordinatesDependent }++ override fun DrawScope.drawBackdrop(+ density: Density,+ coordinates: LayoutCoordinates?,+ layerBlock: (GraphicsLayerScope.() -> Unit)?+ ) {+ backdrops.forEach { backdrop ->+ with(backdrop) { drawBackdrop(density, coordinates, layerBlock) }+ }+ }+}diff --git a/backdrop/src/commonMain/kotlin/com/kyant/backdrop/backdrops/EmptyBackdrop.kt b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/backdrops/EmptyBackdrop.ktnew file mode 100644index 0000000..7701a8c--- /dev/null+++ b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/backdrops/EmptyBackdrop.kt@@ -0,0 +1,25 @@+package com.kyant.backdrop.backdrops++import androidx.compose.runtime.Immutable+import androidx.compose.runtime.Stable+import androidx.compose.ui.graphics.GraphicsLayerScope+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.layout.LayoutCoordinates+import androidx.compose.ui.unit.Density+import com.kyant.backdrop.Backdrop++@Stable+fun emptyBackdrop(): Backdrop = EmptyBackdrop++@Immutable+private object EmptyBackdrop : Backdrop {++ override val isCoordinatesDependent: Boolean = false++ override fun DrawScope.drawBackdrop(+ density: Density,+ coordinates: LayoutCoordinates?,+ layerBlock: (GraphicsLayerScope.() -> Unit)?+ ) {+ }+}diff --git a/backdrop/src/commonMain/kotlin/com/kyant/backdrop/backdrops/LayerBackdrop.kt b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/backdrops/LayerBackdrop.ktnew file mode 100644index 0000000..787f532--- /dev/null+++ b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/backdrops/LayerBackdrop.kt@@ -0,0 +1,74 @@+package com.kyant.backdrop.backdrops++import androidx.compose.runtime.Composable+import androidx.compose.runtime.Stable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.graphics.GraphicsLayerScope+import androidx.compose.ui.graphics.drawscope.ContentDrawScope+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.graphics.drawscope.withTransform+import androidx.compose.ui.graphics.layer.GraphicsLayer+import androidx.compose.ui.graphics.layer.drawLayer+import androidx.compose.ui.graphics.rememberGraphicsLayer+import androidx.compose.ui.layout.LayoutCoordinates+import androidx.compose.ui.layout.positionInWindow+import androidx.compose.ui.unit.Density+import com.kyant.backdrop.Backdrop+import com.kyant.backdrop.internal.InverseLayerScope++private val DefaultOnDraw: ContentDrawScope.() -> Unit = { drawContent() }++@Composable+fun rememberLayerBackdrop(+ graphicsLayer: GraphicsLayer = rememberGraphicsLayer(),+ onDraw: ContentDrawScope.() -> Unit = DefaultOnDraw+): LayerBackdrop {+ return remember(graphicsLayer, onDraw) {+ LayerBackdrop(graphicsLayer, onDraw)+ }+}++@Stable+class LayerBackdrop internal constructor(+ val graphicsLayer: GraphicsLayer,+ internal val onDraw: ContentDrawScope.() -> Unit+) : Backdrop {++ override val isCoordinatesDependent: Boolean = true++ internal var layerCoordinates: LayoutCoordinates? by mutableStateOf(null)++ private var inverseLayerScope: InverseLayerScope? = null++ override fun DrawScope.drawBackdrop(+ density: Density,+ coordinates: LayoutCoordinates?,+ layerBlock: (GraphicsLayerScope.() -> Unit)?+ ) {+ val coordinates = coordinates ?: return+ val layerCoordinates = layerCoordinates ?: return+ withTransform({+ if (layerBlock != null) {+ with(obtainInverseLayerScope()) { inverseTransform(density, layerBlock) }+ }+ val offset =+ try {+ layerCoordinates.localPositionOf(coordinates)+ } catch (_: Exception) {+ // TODO: outer transformations lead to wrong position calculation+ coordinates.positionInWindow() - layerCoordinates.positionInWindow()+ }+ translate(-offset.x, -offset.y)+ }) {+ drawLayer(graphicsLayer)+ }+ }++ private fun obtainInverseLayerScope(): InverseLayerScope {+ return inverseLayerScope?.apply { reset() }+ ?: InverseLayerScope().also { inverseLayerScope = it }+ }+}diff --git a/backdrop/src/commonMain/kotlin/com/kyant/backdrop/backdrops/LayerBackdropModifier.kt b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/backdrops/LayerBackdropModifier.ktnew file mode 100644index 0000000..98bd21f--- /dev/null+++ b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/backdrops/LayerBackdropModifier.kt@@ -0,0 +1,69 @@+package com.kyant.backdrop.backdrops++import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.drawscope.ContentDrawScope+import androidx.compose.ui.layout.LayoutCoordinates+import androidx.compose.ui.node.DrawModifierNode+import androidx.compose.ui.node.GlobalPositionAwareModifierNode+import androidx.compose.ui.node.ModifierNodeElement+import androidx.compose.ui.node.invalidateDraw+import androidx.compose.ui.platform.InspectorInfo+import com.kyant.backdrop.internal.recordLayer++fun Modifier.layerBackdrop(backdrop: LayerBackdrop): Modifier =+ this then LayerBackdropElement(backdrop)++private class LayerBackdropElement(+ val backdrop: LayerBackdrop+) : ModifierNodeElement<LayerBackdropNode>() {++ override fun create(): LayerBackdropNode {+ return LayerBackdropNode(backdrop)+ }++ override fun update(node: LayerBackdropNode) {+ if (node.backdrop != backdrop) {+ node.backdrop.layerCoordinates = null+ node.backdrop = backdrop+ }+ node.invalidateDraw()+ }++ override fun InspectorInfo.inspectableProperties() {+ name = "layerBackdrop"+ properties["backdrop"] = backdrop+ }++ override fun equals(other: Any?): Boolean {+ if (this === other) return true+ if (other !is LayerBackdropElement) return false++ if (backdrop != other.backdrop) return false++ return true+ }++ override fun hashCode(): Int {+ return backdrop.hashCode()+ }+}++private class LayerBackdropNode(+ var backdrop: LayerBackdrop+) : DrawModifierNode, GlobalPositionAwareModifierNode, Modifier.Node() {++ override fun ContentDrawScope.draw() {+ drawContent()+ recordLayer(backdrop.graphicsLayer) { backdrop.onDraw(this@draw) }+ }++ override fun onGloballyPositioned(coordinates: LayoutCoordinates) {+ if (coordinates.isAttached) {+ backdrop.layerCoordinates = coordinates+ }+ }++ override fun onDetach() {+ backdrop.layerCoordinates = null+ }+}diff --git a/backdrop/src/commonMain/kotlin/com/kyant/backdrop/effects/Blur.kt b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/effects/Blur.ktnew file mode 100644index 0000000..39d85ba--- /dev/null+++ b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/effects/Blur.kt@@ -0,0 +1,29 @@+package com.kyant.backdrop.effects++import androidx.annotation.FloatRange+import androidx.compose.ui.graphics.BlurEffect+import androidx.compose.ui.graphics.TileMode+import com.kyant.backdrop.BackdropEffectScope+import com.kyant.backdrop.isRenderEffectSupported++fun BackdropEffectScope.blur(+ @FloatRange(from = 0.0) radius: Float,+ edgeTreatment: TileMode = TileMode.Clamp+) {+ if (!isRenderEffectSupported()) return+ if (radius <= 0f) return++ if (edgeTreatment != TileMode.Clamp || renderEffect != null) {+ if (radius > padding) {+ padding = radius+ }+ }++ renderEffect =+ BlurEffect(+ renderEffect,+ radius,+ radius,+ edgeTreatment+ )+}diff --git a/backdrop/src/commonMain/kotlin/com/kyant/backdrop/effects/ColorFilter.kt b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/effects/ColorFilter.ktnew file mode 100644index 0000000..0d9712b--- /dev/null+++ b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/effects/ColorFilter.kt@@ -0,0 +1,75 @@+package com.kyant.backdrop.effects++import androidx.annotation.FloatRange+import androidx.compose.ui.graphics.ColorFilter+import androidx.compose.ui.graphics.ColorMatrix+import androidx.compose.ui.graphics.ColorMatrixColorFilter+import com.kyant.backdrop.BackdropEffectScope+import com.kyant.backdrop.internal.ColorFilterEffect+import com.kyant.backdrop.isRenderEffectSupported++fun BackdropEffectScope.colorFilter(colorFilter: ColorFilter) {+ if (!isRenderEffectSupported()) return++ renderEffect = ColorFilterEffect(renderEffect, colorFilter)+}++fun BackdropEffectScope.opacity(@FloatRange(from = 0.0, to = 1.0) alpha: Float) {+ val colorMatrix = ColorMatrix(+ floatArrayOf(+ 1f, 0f, 0f, 0f, 0f,+ 0f, 1f, 0f, 0f, 0f,+ 0f, 0f, 1f, 0f, 0f,+ 0f, 0f, 0f, alpha, 0f+ )+ )+ colorFilter(ColorMatrixColorFilter(colorMatrix))+}++fun BackdropEffectScope.colorControls(+ brightness: Float = 0f,+ contrast: Float = 1f,+ saturation: Float = 1f+) {+ if (brightness == 0f && contrast == 1f && saturation == 1f) {+ return+ }++ colorFilter(colorControlsColorFilter(brightness, contrast, saturation))+}++private val VibrantColorFilter = colorControlsColorFilter(saturation = 1.5f)++fun BackdropEffectScope.vibrancy() {+ colorFilter(VibrantColorFilter)+}++private fun colorControlsColorFilter(+ brightness: Float = 0f,+ contrast: Float = 1f,+ saturation: Float = 1f+): ColorFilter {+ val invSat = 1f - saturation+ val r = 0.213f * invSat+ val g = 0.715f * invSat+ val b = 0.072f * invSat++ val c = contrast+ val t = (0.5f - c * 0.5f + brightness) * 255f+ val s = saturation++ val cr = c * r+ val cg = c * g+ val cb = c * b+ val cs = c * s++ val colorMatrix = ColorMatrix(+ floatArrayOf(+ cr + cs, cg, cb, 0f, t,+ cr, cg + cs, cb, 0f, t,+ cr, cg, cb + cs, 0f, t,+ 0f, 0f, 0f, 1f, 0f+ )+ )+ return ColorMatrixColorFilter(colorMatrix)+}diff --git a/backdrop/src/commonMain/kotlin/com/kyant/backdrop/effects/Lens.kt b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/effects/Lens.ktnew file mode 100644index 0000000..10af02d--- /dev/null+++ b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/effects/Lens.kt@@ -0,0 +1,120 @@+package com.kyant.backdrop.effects++import androidx.annotation.FloatRange+import androidx.compose.foundation.shape.AbsoluteRoundedCornerShape+import androidx.compose.foundation.shape.CornerBasedShape+import androidx.compose.ui.unit.LayoutDirection+import androidx.compose.ui.util.fastCoerceAtLeast+import androidx.compose.ui.util.fastCoerceAtMost+import com.kyant.backdrop.BackdropEffectScope+import com.kyant.backdrop.internal.RoundedRectRefractionShaderString+import com.kyant.backdrop.internal.RoundedRectRefractionWithDispersionShaderString+import com.kyant.backdrop.internal.RuntimeShaderEffect+import com.kyant.backdrop.isRuntimeShaderSupported+import com.kyant.shapes.RoundedRectangularShape++fun BackdropEffectScope.lens(+ @FloatRange(from = 0.0) refractionHeight: Float,+ @FloatRange(from = 0.0) refractionAmount: Float,+ depthEffect: Boolean = false,+ chromaticAberration: Boolean = false+) {+ if (!isRuntimeShaderSupported()) return+ if (refractionHeight <= 0f || refractionAmount <= 0f) return++ if (padding > 0f) {+ padding = (padding - refractionHeight).fastCoerceAtLeast(0f)+ }++ val cornerRadii = cornerRadii+ val effect =+ if (cornerRadii != null) {+ val shader =+ if (!chromaticAberration) {+ obtainRuntimeShader(+ "Refraction",+ RoundedRectRefractionShaderString+ )+ } else {+ obtainRuntimeShader(+ "RefractionWithDispersion",+ RoundedRectRefractionWithDispersionShaderString+ )+ }+ shader.apply {+ setFloatUniform("size", size.width, size.height)+ setFloatUniform("offset", -padding, -padding)+ setFloatUniform("cornerRadii", cornerRadii)+ setFloatUniform("refractionHeight", refractionHeight)+ setFloatUniform("refractionAmount", -refractionAmount)+ setFloatUniform("depthEffect", if (depthEffect) 1f else 0f)+ if (chromaticAberration) {+ setFloatUniform("chromaticAberration", 1f)+ }+ }+ RuntimeShaderEffect(shader, "content")+ } else {+ throwUnsupportedSDFException()+ }+ effect(effect)+}++private val BackdropEffectScope.cornerRadii: FloatArray?+ get() = when (val shape = shape) {+ is RoundedRectangularShape -> {+ val corners = shape.corners(size, layoutDirection, this)+ floatArrayOf(+ corners.topLeft,+ corners.topRight,+ corners.bottomRight,+ corners.bottomLeft+ )+ }++ is AbsoluteRoundedCornerShape -> {+ val size = size+ val maxRadius = size.minDimension / 2f+ val topLeft = shape.topStart.toPx(size, this)+ val topRight = shape.topEnd.toPx(size, this)+ val bottomRight = shape.bottomEnd.toPx(size, this)+ val bottomLeft = shape.bottomStart.toPx(size, this)+ floatArrayOf(+ topLeft.fastCoerceAtMost(maxRadius),+ topRight.fastCoerceAtMost(maxRadius),+ bottomRight.fastCoerceAtMost(maxRadius),+ bottomLeft.fastCoerceAtMost(maxRadius)+ )+ }++ is CornerBasedShape -> {+ val size = size+ val maxRadius = size.minDimension / 2f+ val isLtr = layoutDirection == LayoutDirection.Ltr+ val topLeft =+ if (isLtr) shape.topStart.toPx(size, this)+ else shape.topEnd.toPx(size, this)+ val topRight =+ if (isLtr) shape.topEnd.toPx(size, this)+ else shape.topStart.toPx(size, this)+ val bottomRight =+ if (isLtr) shape.bottomEnd.toPx(size, this)+ else shape.bottomStart.toPx(size, this)+ val bottomLeft =+ if (isLtr) shape.bottomStart.toPx(size, this)+ else shape.bottomEnd.toPx(size, this)+ floatArrayOf(+ topLeft.fastCoerceAtMost(maxRadius),+ topRight.fastCoerceAtMost(maxRadius),+ bottomRight.fastCoerceAtMost(maxRadius),+ bottomLeft.fastCoerceAtMost(maxRadius)+ )+ }++ else -> null+ }++private fun throwUnsupportedSDFException(): Nothing {+ throw UnsupportedOperationException(+ "Only RoundedRectangularShape or CornerBasedShape is supported in lens effects."+ )+}diff --git a/backdrop/src/commonMain/kotlin/com/kyant/backdrop/effects/RenderEffect.kt b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/effects/RenderEffect.ktnew file mode 100644index 0000000..0c6be84--- /dev/null+++ b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/effects/RenderEffect.kt@@ -0,0 +1,34 @@+package com.kyant.backdrop.effects++import androidx.compose.ui.graphics.RenderEffect+import com.kyant.backdrop.BackdropEffectScope+import com.kyant.backdrop.RuntimeShader+import com.kyant.backdrop.internal.RuntimeShaderEffect+import com.kyant.backdrop.internal.chain+import com.kyant.backdrop.isRenderEffectSupported+import com.kyant.backdrop.isRuntimeShaderSupported+import org.intellij.lang.annotations.Language+import kotlin.contracts.ExperimentalContracts++fun BackdropEffectScope.effect(effect: RenderEffect) {+ if (!isRenderEffectSupported()) return++ renderEffect = renderEffect.chain(effect)+}++@OptIn(ExperimentalContracts::class)+fun BackdropEffectScope.runtimeShaderEffect(+ key: String,+ @Language("AGSL") shaderString: String,+ uniformShaderName: String,+ block: RuntimeShader.() -> Unit+) {+ if (!isRuntimeShaderSupported()) return++ val effect =+ RuntimeShaderEffect(+ runtimeShader = obtainRuntimeShader(key, shaderString).apply(block),+ uniformShaderName = uniformShaderName+ )+ renderEffect = renderEffect.chain(effect)+}diff --git a/backdrop/src/commonMain/kotlin/com/kyant/backdrop/highlight/Highlight.kt b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/highlight/Highlight.ktnew file mode 100644index 0000000..eda956f--- /dev/null+++ b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/highlight/Highlight.kt@@ -0,0 +1,28 @@+package com.kyant.backdrop.highlight++import androidx.annotation.FloatRange+import androidx.compose.runtime.Immutable+import androidx.compose.runtime.Stable+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp++@Immutable+data class Highlight(+ val width: Dp = 0.5f.dp,+ val blurRadius: Dp = width / 2f,+ @param:FloatRange(from = 0.0, to = 1.0) val alpha: Float = 1f,+ val style: HighlightStyle = HighlightStyle.Default+) {++ companion object {++ @Stable+ val Default: Highlight = Highlight()++ @Stable+ val Ambient: Highlight = Highlight(style = HighlightStyle.Ambient)++ @Stable+ val Plain: Highlight = Highlight(style = HighlightStyle.Plain)+ }+}diff --git a/backdrop/src/commonMain/kotlin/com/kyant/backdrop/highlight/HighlightModifier.kt b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/highlight/HighlightModifier.ktnew file mode 100644index 0000000..60dfe39--- /dev/null+++ b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/highlight/HighlightModifier.kt@@ -0,0 +1,166 @@+package com.kyant.backdrop.highlight++import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Outline+import androidx.compose.ui.graphics.Paint+import androidx.compose.ui.graphics.PaintingStyle+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.drawOutline+import androidx.compose.ui.graphics.drawscope.ContentDrawScope+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.graphics.drawscope.translate+import androidx.compose.ui.graphics.layer.GraphicsLayer+import androidx.compose.ui.graphics.layer.drawLayer+import androidx.compose.ui.node.DrawModifierNode+import androidx.compose.ui.node.ModifierNodeElement+import androidx.compose.ui.node.invalidateDraw+import androidx.compose.ui.node.requireGraphicsContext+import androidx.compose.ui.platform.InspectorInfo+import androidx.compose.ui.unit.Density+import androidx.compose.ui.unit.IntSize+import androidx.compose.ui.util.fastCoerceAtMost+import com.kyant.backdrop.RuntimeShaderCacheImpl+import com.kyant.backdrop.internal.ShapeProvider+import com.kyant.backdrop.internal.blur+import com.kyant.backdrop.internal.clipOutline+import com.kyant.backdrop.internal.setRuntimeShader+import com.kyant.backdrop.isRuntimeShaderSupported+import kotlin.math.ceil++internal class HighlightElement(+ val shapeProvider: ShapeProvider,+ val highlight: () -> Highlight?+) : ModifierNodeElement<HighlightNode>() {++ override fun create(): HighlightNode {+ return HighlightNode(shapeProvider, highlight)+ }++ override fun update(node: HighlightNode) {+ node.shapeProvider = shapeProvider+ node.highlight = highlight+ node.invalidateDraw()+ }++ override fun InspectorInfo.inspectableProperties() {+ name = "highlight"+ properties["shapeProvider"] = shapeProvider+ properties["highlight"] = highlight+ }++ override fun equals(other: Any?): Boolean {+ if (this === other) return true+ if (other !is HighlightElement) return false++ if (shapeProvider != other.shapeProvider) return false+ if (highlight != other.highlight) return false++ return true+ }++ override fun hashCode(): Int {+ var result = shapeProvider.hashCode()+ result = 31 * result + highlight.hashCode()+ return result+ }+}++internal class HighlightNode(+ var shapeProvider: ShapeProvider,+ var highlight: () -> Highlight?+) : DrawModifierNode, Modifier.Node() {++ override val shouldAutoInvalidate: Boolean = false++ private var highlightLayer: GraphicsLayer? = null++ private val paint =+ Paint().apply {+ style = PaintingStyle.Stroke+ }+ private var clipPath: Path? = null++ private val runtimeShaderCache = RuntimeShaderCacheImpl()++ private var prevStyle: HighlightStyle? = null++ override fun ContentDrawScope.draw() {+ val highlight = highlight()+ if (highlight == null || highlight.width.value <= 0f) {+ return drawContent()+ }++ drawContent()++ val highlightLayer = highlightLayer+ if (highlightLayer != null) {+ val size = size+ val density: Density = this+ val layoutDirection = layoutDirection++ val safeSize =+ IntSize(+ ceil(size.width).toInt() + 2,+ ceil(size.height).toInt() + 2+ )++ val outline = shapeProvider.shape.createOutline(size, layoutDirection, density)+ val clipPath =+ if (outline is Outline.Rounded) {+ clipPath ?: Path().also { clipPath = it }+ } else {+ null+ }++ configurePaint(highlight)++ highlightLayer.alpha = highlight.alpha+ highlightLayer.blendMode = highlight.style.blendMode+ highlightLayer.record(safeSize) {+ translate(1f, 1f) {+ val canvas = drawContext.canvas+ canvas.save()+ canvas.clipOutline(outline, clipPath)+ canvas.drawOutline(outline, paint)+ canvas.restore()+ }+ }++ translate(-1f, -1f) {+ drawLayer(highlightLayer)+ }+ }+ }++ override fun onAttach() {+ val graphicsContext = requireGraphicsContext()+ highlightLayer = graphicsContext.createGraphicsLayer()+ }++ override fun onDetach() {+ val graphicsContext = requireGraphicsContext()+ highlightLayer?.let { layer ->+ graphicsContext.releaseGraphicsLayer(layer)+ highlightLayer = null+ }+ clipPath = null+ runtimeShaderCache.clear()+ prevStyle = null+ }++ private fun DrawScope.configurePaint(highlight: Highlight) {+ paint.color = highlight.style.color+ paint.strokeWidth = ceil(highlight.width.toPx().fastCoerceAtMost(size.minDimension / 2f)) * 2f+ paint.blur(highlight.blurRadius.toPx())+ if (isRuntimeShaderSupported()) {+ val shader =+ with(highlight.style) {+ createShader(+ shape = shapeProvider.shape,+ runtimeShaderCache = runtimeShaderCache+ )+ }+ paint.setRuntimeShader(shader)+ }+ }+}diff --git a/backdrop/src/commonMain/kotlin/com/kyant/backdrop/highlight/HighlightStyle.kt b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/highlight/HighlightStyle.ktnew file mode 100644index 0000000..209f5b5--- /dev/null+++ b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/highlight/HighlightStyle.kt@@ -0,0 +1,138 @@+package com.kyant.backdrop.highlight++import androidx.annotation.FloatRange+import androidx.compose.foundation.shape.CornerBasedShape+import androidx.compose.runtime.Immutable+import androidx.compose.runtime.Stable+import androidx.compose.ui.graphics.BlendMode+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Shape+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.unit.LayoutDirection+import androidx.compose.ui.util.fastCoerceAtMost+import com.kyant.backdrop.RuntimeShader+import com.kyant.backdrop.RuntimeShaderCache+import com.kyant.backdrop.internal.AmbientHighlightShaderString+import com.kyant.backdrop.internal.DefaultHighlightShaderString+import com.kyant.backdrop.isRuntimeShaderSupported+import kotlin.math.PI++@Immutable+interface HighlightStyle {++ val color: Color++ val blendMode: BlendMode++ fun DrawScope.createShader(+ shape: Shape,+ runtimeShaderCache: RuntimeShaderCache+ ): RuntimeShader?++ @Immutable+ data class Plain(+ override val color: Color = Color.White.copy(alpha = 0.38f),+ override val blendMode: BlendMode = BlendMode.Plus+ ) : HighlightStyle {++ override fun DrawScope.createShader(+ shape: Shape,+ runtimeShaderCache: RuntimeShaderCache+ ): RuntimeShader? = null+ }++ @Immutable+ data class Default(+ override val color: Color = Color.White.copy(alpha = 0.5f),+ override val blendMode: BlendMode = BlendMode.Plus,+ val angle: Float = 45f,+ @param:FloatRange(from = 0.0) val falloff: Float = 1f+ ) : HighlightStyle {++ override fun DrawScope.createShader(+ shape: Shape,+ runtimeShaderCache: RuntimeShaderCache+ ): RuntimeShader? {+ return if (isRuntimeShaderSupported()) {+ runtimeShaderCache.obtainRuntimeShader(+ "Default",+ DefaultHighlightShaderString+ ).apply {+ setFloatUniform("size", size.width, size.height)+ setFloatUniform("cornerRadii", getCornerRadii(shape))+ setColorUniform("color", color.copy(alpha = 1f))+ setFloatUniform("angle", angle * (PI / 180f).toFloat())+ setFloatUniform("falloff", falloff)+ }+ } else {+ null+ }+ }+ }++ @Immutable+ data class Ambient(+ @param:FloatRange(from = 0.0, to = 1.0) val intensity: Float = 0.38f+ ) : HighlightStyle {++ override val color: Color = Color.White.copy(alpha = intensity)++ override val blendMode: BlendMode = DrawScope.DefaultBlendMode++ override fun DrawScope.createShader(+ shape: Shape,+ runtimeShaderCache: RuntimeShaderCache+ ): RuntimeShader? {+ return if (isRuntimeShaderSupported()) {+ runtimeShaderCache.obtainRuntimeShader(+ "Ambient",+ AmbientHighlightShaderString+ ).apply {+ setFloatUniform("size", size.width, size.height)+ setFloatUniform("cornerRadii", getCornerRadii(shape))+ setFloatUniform("angle", 45f * (PI / 180f).toFloat())+ setFloatUniform("falloff", 1f)+ }+ } else {+ null+ }+ }+ }++ companion object {++ @Stable+ val Default: Default = Default()++ @Stable+ val Ambient: Ambient = Ambient()++ @Stable+ val Plain: Plain = Plain()+ }+}++private fun DrawScope.getCornerRadii(shape: Shape): FloatArray {+ val size = size+ val maxRadius = size.minDimension / 2f+ val shape = shape as? CornerBasedShape ?: return FloatArray(4) { maxRadius }+ val isLtr = layoutDirection == LayoutDirection.Ltr+ val topLeft =+ if (isLtr) shape.topStart.toPx(size, this)+ else shape.topEnd.toPx(size, this)+ val topRight =+ if (isLtr) shape.topEnd.toPx(size, this)+ else shape.topStart.toPx(size, this)+ val bottomRight =+ if (isLtr) shape.bottomEnd.toPx(size, this)+ else shape.bottomStart.toPx(size, this)+ val bottomLeft =+ if (isLtr) shape.bottomStart.toPx(size, this)+ else shape.bottomEnd.toPx(size, this)+ return floatArrayOf(+ topLeft.fastCoerceAtMost(maxRadius),+ topRight.fastCoerceAtMost(maxRadius),+ bottomRight.fastCoerceAtMost(maxRadius),+ bottomLeft.fastCoerceAtMost(maxRadius)+ )+}diff --git a/backdrop/src/commonMain/kotlin/com/kyant/backdrop/internal/InverseLayerScope.kt b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/internal/InverseLayerScope.ktnew file mode 100644index 0000000..f6827ff--- /dev/null+++ b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/internal/InverseLayerScope.kt@@ -0,0 +1,130 @@+package com.kyant.backdrop.internal++import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.BlendMode+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.ColorFilter+import androidx.compose.ui.graphics.CompositingStrategy+import androidx.compose.ui.graphics.DefaultCameraDistance+import androidx.compose.ui.graphics.DefaultShadowColor+import androidx.compose.ui.graphics.GraphicsLayerScope+import androidx.compose.ui.graphics.Matrix+import androidx.compose.ui.graphics.RectangleShape+import androidx.compose.ui.graphics.RenderEffect+import androidx.compose.ui.graphics.Shape+import androidx.compose.ui.graphics.TransformOrigin+import androidx.compose.ui.graphics.drawscope.DrawTransform+import androidx.compose.ui.unit.Density+import kotlin.math.PI+import kotlin.math.cos+import kotlin.math.sin++internal class InverseLayerScope : GraphicsLayerScope {++ override var size: Size = Size.Unspecified+ override var density: Float = 1f+ override var fontScale: Float = 1f++ override var scaleX: Float = 1f+ override var scaleY: Float = 1f+ override var alpha: Float = 0f+ override var translationX: Float = 0f+ override var translationY: Float = 0f+ override var shadowElevation: Float = 0f+ override var ambientShadowColor: Color = DefaultShadowColor+ override var spotShadowColor: Color = DefaultShadowColor+ override var rotationX: Float = 0f+ override var rotationY: Float = 0f+ override var rotationZ: Float = 0f+ override var cameraDistance: Float = DefaultCameraDistance+ override var transformOrigin: TransformOrigin = TransformOrigin.Center+ override var shape: Shape = RectangleShape+ override var clip: Boolean = false+ override var renderEffect: RenderEffect? = null+ override var blendMode: BlendMode = BlendMode.SrcOver+ override var colorFilter: ColorFilter? = null+ override var compositingStrategy: CompositingStrategy = CompositingStrategy.Auto++ private var matrix: Matrix? = null++ fun DrawTransform.inverseTransform(+ density: Density,+ layerBlock: GraphicsLayerScope.() -> Unit+ ) {+ [email protected] = size+ [email protected] = density.density+ fontScale = density.fontScale++ layerBlock()++ inverseTransformAtTopLeft(+ rotationZ = rotationZ,+ scaleX = scaleX,+ scaleY = scaleY+ )+ }++ fun reset() {+ size = Size.Unspecified+ density = 1f+ fontScale = 1f++ scaleX = 1f+ scaleY = 1f+ alpha = 1f+ translationX = 0f+ translationY = 0f+ shadowElevation = 0f+ ambientShadowColor = DefaultShadowColor+ spotShadowColor = DefaultShadowColor+ rotationX = 0f+ rotationY = 0f+ rotationZ = 0f+ cameraDistance = DefaultCameraDistance+ transformOrigin = TransformOrigin.Center+ shape = RectangleShape+ clip = false+ renderEffect = null+ blendMode = BlendMode.SrcOver+ colorFilter = null+ compositingStrategy = CompositingStrategy.Auto++ matrix = null+ }++ private fun DrawTransform.inverseTransformAtTopLeft(+ rotationZ: Float = 0f,+ scaleX: Float = 1f,+ scaleY: Float = 1f+ ) {+ if (rotationZ == 0f) {+ if (scaleX != 0f && scaleY != 0f) {+ scale(1f / scaleX, 1f / scaleY, Offset.Zero)+ }+ return+ }++ val matrix = matrix ?: Matrix().also { matrix = it }+ if (matrix.values.size < 16) return++ val rz = rotationZ * (PI / 180.0)+ val rsz = sin(rz).toFloat()+ val rcz = cos(rz).toFloat()++ val a00 = rcz * scaleX+ val a01 = rsz * scaleY+ val a10 = -rsz * scaleX+ val a11 = rcz * scaleY++ val det = a00 * a11 - a01 * a10+ if (det == 0f) return+ val invDet = 1f / det+ matrix[0, 0] = a11 * invDet+ matrix[0, 1] = -a01 * invDet+ matrix[1, 0] = -a10 * invDet+ matrix[1, 1] = a00 * invDet++ transform(matrix)+ }+}diff --git a/backdrop/src/commonMain/kotlin/com/kyant/backdrop/internal/LayerRecorder.kt b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/internal/LayerRecorder.ktnew file mode 100644index 0000000..6876c11--- /dev/null+++ b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/internal/LayerRecorder.kt@@ -0,0 +1,26 @@+package com.kyant.backdrop.internal++import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.graphics.layer.GraphicsLayer+import androidx.compose.ui.node.DelegatableNode+import androidx.compose.ui.node.requireDensity+import androidx.compose.ui.unit.IntSize+import androidx.compose.ui.unit.toIntSize++context(node: DelegatableNode)+internal fun DrawScope.recordLayer(+ layer: GraphicsLayer,+ size: IntSize = this.size.toIntSize(),+ block: DrawScope.() -> Unit+) {+ val density = node.requireDensity()+ layer.record(size) {+ val prevDensity = drawContext.density+ drawContext.density = density+ try {+ this.block()+ } finally {+ drawContext.density = prevDensity+ }+ }+}diff --git a/backdrop/src/commonMain/kotlin/com/kyant/backdrop/internal/Outline.kt b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/internal/Outline.ktnew file mode 100644index 0000000..1a55526--- /dev/null+++ b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/internal/Outline.kt@@ -0,0 +1,18 @@+package com.kyant.backdrop.internal++import androidx.compose.ui.graphics.Canvas+import androidx.compose.ui.graphics.Outline+import androidx.compose.ui.graphics.Path++internal fun Canvas.clipOutline(outline: Outline, path: Path?) {+ when (outline) {+ is Outline.Rectangle -> clipRect(outline.rect)+ is Outline.Rounded -> {+ path!!.rewind()+ path.addRoundRect(outline.roundRect)+ clipPath(path)+ }++ is Outline.Generic -> clipPath(outline.path)+ }+}diff --git a/backdrop/src/commonMain/kotlin/com/kyant/backdrop/internal/Paint.kt b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/internal/Paint.ktnew file mode 100644index 0000000..8274d69--- /dev/null+++ b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/internal/Paint.kt@@ -0,0 +1,8 @@+package com.kyant.backdrop.internal++import androidx.compose.ui.graphics.Paint+import com.kyant.backdrop.RuntimeShader++internal expect fun Paint.blur(radius: Float)++internal expect fun Paint.setRuntimeShader(runtimeShader: RuntimeShader?)diff --git a/backdrop/src/commonMain/kotlin/com/kyant/backdrop/internal/RenderEffect.kt b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/internal/RenderEffect.ktnew file mode 100644index 0000000..2e94022--- /dev/null+++ b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/internal/RenderEffect.kt@@ -0,0 +1,17 @@+package com.kyant.backdrop.internal++import androidx.compose.ui.graphics.ColorFilter+import androidx.compose.ui.graphics.RenderEffect+import com.kyant.backdrop.RuntimeShader++internal expect fun RenderEffect?.chain(other: RenderEffect): RenderEffect++internal expect fun RuntimeShaderEffect(+ runtimeShader: RuntimeShader,+ uniformShaderName: String+): RenderEffect++internal expect fun ColorFilterEffect(+ renderEffect: RenderEffect? = null,+ colorFilter: ColorFilter+): RenderEffectdiff --git a/backdrop/src/commonMain/kotlin/com/kyant/backdrop/internal/Shaders.kt b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/internal/Shaders.ktnew file mode 100644index 0000000..a96e900--- /dev/null+++ b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/internal/Shaders.kt@@ -0,0 +1,204 @@+/*+ Copyright 2025 Kyant++ 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.kyant.backdrop.internal++import org.intellij.lang.annotations.Language++@Language("AGSL")+private const val RoundedRectSDF = """+float radiusAt(float2 coord, float4 radii) {+ if (coord.x >= 0.0) {+ if (coord.y <= 0.0) return radii.y;+ else return radii.z;+ } else {+ if (coord.y <= 0.0) return radii.x;+ else return radii.w;+ }+}++float sdRoundedRect(float2 coord, float2 halfSize, float radius) {+ float2 cornerCoord = abs(coord) - (halfSize - float2(radius));+ float outside = length(max(cornerCoord, 0.0)) - radius;+ float inside = min(max(cornerCoord.x, cornerCoord.y), 0.0);+ return outside + inside;+}++float2 gradSdRoundedRect(float2 coord, float2 halfSize, float radius) {+ float2 cornerCoord = abs(coord) - (halfSize - float2(radius));+ if (cornerCoord.x >= 0.0 || cornerCoord.y >= 0.0) {+ return sign(coord) * normalize(max(cornerCoord, 0.0));+ } else {+ float gradX = step(cornerCoord.y, cornerCoord.x);+ return sign(coord) * float2(gradX, 1.0 - gradX);+ }+}"""++@Language("AGSL")+internal const val RoundedRectRefractionShaderString = """+uniform shader content;++uniform float2 size;+uniform float2 offset;+uniform float4 cornerRadii;+uniform float refractionHeight;+uniform float refractionAmount;+uniform float depthEffect;++$RoundedRectSDF++float circleMap(float x) {+ return 1.0 - sqrt(1.0 - x * x);+}++half4 main(float2 coord) {+ float2 halfSize = size * 0.5;+ float2 centeredCoord = (coord + offset) - halfSize;+ float radius = radiusAt(coord, cornerRadii);++ float sd = sdRoundedRect(centeredCoord, halfSize, radius);+ if (-sd >= refractionHeight) {+ return content.eval(coord);+ }+ sd = min(sd, 0.0);++ float d = circleMap(1.0 - -sd / refractionHeight) * refractionAmount;+ float gradRadius = min(radius * 1.5, min(halfSize.x, halfSize.y));+ float2 grad = normalize(gradSdRoundedRect(centeredCoord, halfSize, gradRadius) + depthEffect * normalize(centeredCoord));++ float2 refractedCoord = coord + d * grad;+ return content.eval(refractedCoord);+}"""++@Language("AGSL")+internal val RoundedRectRefractionWithDispersionShaderString = """+uniform shader content;++uniform float2 size;+uniform float2 offset;+uniform float4 cornerRadii;+uniform float refractionHeight;+uniform float refractionAmount;+uniform float depthEffect;+uniform float chromaticAberration;++$RoundedRectSDF++float circleMap(float x) {+ return 1.0 - sqrt(1.0 - x * x);+}++half4 main(float2 coord) {+ float2 halfSize = size * 0.5;+ float2 centeredCoord = (coord + offset) - halfSize;+ float radius = radiusAt(coord, cornerRadii);++ float sd = sdRoundedRect(centeredCoord, halfSize, radius);+ if (-sd >= refractionHeight) {+ return content.eval(coord);+ }+ sd = min(sd, 0.0);++ float d = circleMap(1.0 - -sd / refractionHeight) * refractionAmount;+ float gradRadius = min(radius * 1.5, min(halfSize.x, halfSize.y));+ float2 grad = normalize(gradSdRoundedRect(centeredCoord, halfSize, gradRadius) + depthEffect * normalize(centeredCoord));++ float2 refractedCoord = coord + d * grad;+ float dispersionIntensity = chromaticAberration * ((centeredCoord.x * centeredCoord.y) / (halfSize.x * halfSize.y));+ float2 dispersedCoord = d * grad * dispersionIntensity;++ half4 color = half4(0.0);++ half4 red = content.eval(refractedCoord + dispersedCoord);+ color.r += red.r / 3.5;+ color.a += red.a / 7.0;++ half4 orange = content.eval(refractedCoord + dispersedCoord * (2.0 / 3.0));+ color.r += orange.r / 3.5;+ color.g += orange.g / 7.0;+ color.a += orange.a / 7.0;++ half4 yellow = content.eval(refractedCoord + dispersedCoord * (1.0 / 3.0));+ color.r += yellow.r / 3.5;+ color.g += yellow.g / 3.5;+ color.a += yellow.a / 7.0;++ half4 green = content.eval(refractedCoord);+ color.g += green.g / 3.5;+ color.a += green.a / 7.0;++ half4 cyan = content.eval(refractedCoord - dispersedCoord * (1.0 / 3.0));+ color.g += cyan.g / 3.5;+ color.b += cyan.b / 3.0;+ color.a += cyan.a / 7.0;++ half4 blue = content.eval(refractedCoord - dispersedCoord * (2.0 / 3.0));+ color.b += blue.b / 3.0;+ color.a += blue.a / 7.0;++ half4 purple = content.eval(refractedCoord - dispersedCoord);+ color.r += purple.r / 7.0;+ color.b += purple.b / 3.0;+ color.a += purple.a / 7.0;++ return color;+}"""++@Language("AGSL")+internal const val DefaultHighlightShaderString = """+uniform float2 size;+uniform float4 cornerRadii;+layout(color) uniform half4 color;+uniform float angle;+uniform float falloff;++$RoundedRectSDF++half4 main(float2 coord) {+ float2 halfSize = size * 0.5;+ float2 centeredCoord = coord - halfSize;+ float radius = radiusAt(coord, cornerRadii);++ float gradRadius = min(radius * 1.5, min(halfSize.x, halfSize.y));+ float2 grad = gradSdRoundedRect(centeredCoord, halfSize, gradRadius);+ float2 normal = float2(cos(angle), sin(angle));+ float d = dot(grad, normal);+ float intensity = pow(abs(d), falloff);+ return color * intensity;+}"""++@Language("AGSL")+internal const val AmbientHighlightShaderString = """+uniform float2 size;+uniform float4 cornerRadii;+uniform float angle;+uniform float falloff;++$RoundedRectSDF++half4 main(float2 coord) {+ float2 halfSize = size * 0.5;+ float2 centeredCoord = coord - halfSize;+ float radius = radiusAt(coord, cornerRadii);++ float gradRadius = min(radius * 1.5, min(halfSize.x, halfSize.y));+ float2 grad = gradSdRoundedRect(centeredCoord, halfSize, gradRadius);+ float2 normal = float2(cos(angle), sin(angle));+ float d = dot(grad, normal);+ float intensity = pow(abs(d), falloff);+ float t = step(0.0, d);+ return half4(t, t, t, 1.0) * intensity;+}"""diff --git a/backdrop/src/commonMain/kotlin/com/kyant/backdrop/internal/ShapeProvider.kt b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/internal/ShapeProvider.ktnew file mode 100644index 0000000..7728916--- /dev/null+++ b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/internal/ShapeProvider.kt@@ -0,0 +1,44 @@+package com.kyant.backdrop.internal++import androidx.compose.runtime.Immutable+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.Outline+import androidx.compose.ui.graphics.Shape+import androidx.compose.ui.unit.Density+import androidx.compose.ui.unit.LayoutDirection++@Immutable+internal class ShapeProvider(val shapeBlock: () -> Shape) {++ private var _shape: Shape? = null+ private var _outline: Outline? = null+ private var _size: Size = Size.Unspecified+ private var _layoutDirection: LayoutDirection? = null+ private var _density: Float? = null++ val innerShape+ get() = shapeBlock()++ val shape = object : Shape {++ override fun createOutline(+ size: Size,+ layoutDirection: LayoutDirection,+ density: Density+ ): Outline {+ val shape = shapeBlock()+ if (_shape != shape) {+ _shape = shape+ _outline = null+ }+ if (_outline == null || _size != size || _layoutDirection != layoutDirection || _density != density.density) {+ _size = size+ _layoutDirection = layoutDirection+ _density = density.density+ _outline = shape.createOutline(size, layoutDirection, density)+ }++ return _outline!!+ }+ }+}diff --git a/backdrop/src/commonMain/kotlin/com/kyant/backdrop/shadow/InnerShadow.kt b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/shadow/InnerShadow.ktnew file mode 100644index 0000000..1475bec--- /dev/null+++ b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/shadow/InnerShadow.kt@@ -0,0 +1,41 @@+package com.kyant.backdrop.shadow++import androidx.annotation.FloatRange+import androidx.compose.runtime.Immutable+import androidx.compose.runtime.Stable+import androidx.compose.ui.graphics.BlendMode+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.graphics.lerp+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.DpOffset+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.lerp+import androidx.compose.ui.util.lerp++@Immutable+data class InnerShadow(+ val radius: Dp = 24f.dp,+ val offset: DpOffset = DpOffset(0f.dp, radius),+ val color: Color = Color.Black.copy(alpha = 0.15f),+ @param:FloatRange(from = 0.0, to = 1.0) val alpha: Float = 1f,+ val blendMode: BlendMode = DrawScope.DefaultBlendMode+) {++ companion object {++ @Stable+ val Default: InnerShadow = InnerShadow()+ }+}++@Stable+fun lerp(start: InnerShadow, stop: InnerShadow, fraction: Float): InnerShadow {+ return InnerShadow(+ radius = lerp(start.radius, stop.radius, fraction),+ offset = lerp(start.offset, stop.offset, fraction),+ color = lerp(start.color, stop.color, fraction),+ alpha = lerp(start.alpha, stop.alpha, fraction),+ blendMode = if (fraction < 0.5f) start.blendMode else stop.blendMode+ )+}diff --git a/backdrop/src/commonMain/kotlin/com/kyant/backdrop/shadow/InnerShadowModifier.kt b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/shadow/InnerShadowModifier.ktnew file mode 100644index 0000000..a8aecbf--- /dev/null+++ b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/shadow/InnerShadowModifier.kt@@ -0,0 +1,158 @@+package com.kyant.backdrop.shadow++import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.BlendMode+import androidx.compose.ui.graphics.BlurEffect+import androidx.compose.ui.graphics.Outline+import androidx.compose.ui.graphics.Paint+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.TileMode+import androidx.compose.ui.graphics.drawOutline+import androidx.compose.ui.graphics.drawscope.ContentDrawScope+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.graphics.layer.CompositingStrategy+import androidx.compose.ui.graphics.layer.GraphicsLayer+import androidx.compose.ui.graphics.layer.drawLayer+import androidx.compose.ui.node.DrawModifierNode+import androidx.compose.ui.node.ModifierNodeElement+import androidx.compose.ui.node.invalidateDraw+import androidx.compose.ui.node.requireGraphicsContext+import androidx.compose.ui.platform.InspectorInfo+import androidx.compose.ui.unit.Density+import com.kyant.backdrop.internal.ShapeProvider+import com.kyant.backdrop.internal.clipOutline+import com.kyant.backdrop.isRenderEffectSupported++internal class InnerShadowElement(+ val shapeProvider: ShapeProvider,+ val shadow: () -> InnerShadow?+) : ModifierNodeElement<InnerShadowNode>() {++ override fun create(): InnerShadowNode {+ return InnerShadowNode(shapeProvider, shadow)+ }++ override fun update(node: InnerShadowNode) {+ node.shapeProvider = shapeProvider+ node.shadow = shadow+ node.invalidateDraw()+ }++ override fun InspectorInfo.inspectableProperties() {+ name = "innerShadow"+ properties["shapeProvider"] = shapeProvider+ properties["shadow"] = shadow+ }++ override fun equals(other: Any?): Boolean {+ if (this === other) return true+ if (other !is InnerShadowElement) return false++ if (shapeProvider != other.shapeProvider) return false+ if (shadow != other.shadow) return false++ return true+ }++ override fun hashCode(): Int {+ var result = shapeProvider.hashCode()+ result = 31 * result + shadow.hashCode()+ return result+ }+}++internal class InnerShadowNode(+ var shapeProvider: ShapeProvider,+ var shadow: () -> InnerShadow?+) : DrawModifierNode, Modifier.Node() {++ override val shouldAutoInvalidate: Boolean = false++ private var shadowLayer: GraphicsLayer? = null++ private val paint = Paint()+ private var clipPath: Path? = null++ private var prevRadius = Float.NaN++ override fun ContentDrawScope.draw() {+ drawContent()++ if (!isRenderEffectSupported()) return++ val shadow = shadow() ?: return++ val shadowLayer = shadowLayer+ if (shadowLayer != null) {+ val size = size+ val density: Density = this+ val layoutDirection = layoutDirection++ val radius = shadow.radius.toPx()+ val offsetX = shadow.offset.x.toPx()+ val offsetY = shadow.offset.y.toPx()++ val outline = shapeProvider.shape.createOutline(size, layoutDirection, density)+ val clipPath =+ if (outline is Outline.Rounded) {+ clipPath ?: Path().also { clipPath = it }+ } else {+ null+ }++ configurePaint(shadow)++ shadowLayer.alpha = shadow.alpha+ shadowLayer.blendMode = shadow.blendMode+ if (prevRadius != radius) {+ shadowLayer.renderEffect =+ if (radius > 0f) {+ BlurEffect(radius, radius, TileMode.Decal)+ } else {+ null+ }+ prevRadius = radius+ }+ shadowLayer.record {+ val canvas = drawContext.canvas+ canvas.save()+ canvas.clipOutline(outline, clipPath)+ canvas.drawOutline(outline, paint)+ canvas.translate(offsetX, offsetY)+ canvas.drawOutline(outline, ShadowMaskPaint)+ canvas.translate(-offsetX, -offsetY)+ canvas.restore()+ }++ val canvas = drawContext.canvas+ canvas.save()+ canvas.clipOutline(outline, clipPath)+ drawLayer(shadowLayer)+ canvas.restore()+ }+ }++ override fun onAttach() {+ val graphicsContext = requireGraphicsContext()+ shadowLayer =+ graphicsContext.createGraphicsLayer().apply {+ compositingStrategy = CompositingStrategy.Offscreen+ }+ }++ override fun onDetach() {+ val graphicsContext = requireGraphicsContext()+ shadowLayer?.let { layer ->+ graphicsContext.releaseGraphicsLayer(layer)+ shadowLayer = null+ }+ }++ private fun DrawScope.configurePaint(shadow: InnerShadow) {+ paint.color = shadow.color+ }+}++private val ShadowMaskPaint = Paint().apply {+ blendMode = BlendMode.Clear+}diff --git a/backdrop/src/commonMain/kotlin/com/kyant/backdrop/shadow/Shadow.kt b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/shadow/Shadow.ktnew file mode 100644index 0000000..24684f8--- /dev/null+++ b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/shadow/Shadow.kt@@ -0,0 +1,27 @@+package com.kyant.backdrop.shadow++import androidx.annotation.FloatRange+import androidx.compose.runtime.Immutable+import androidx.compose.runtime.Stable+import androidx.compose.ui.graphics.BlendMode+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.DpOffset+import androidx.compose.ui.unit.dp++@Immutable+data class Shadow(+ val radius: Dp = 24f.dp,+ val offset: DpOffset = DpOffset(0f.dp, radius / 6f),+ val color: Color = Color.Black.copy(alpha = 0.1f),+ @param:FloatRange(from = 0.0, to = 1.0) val alpha: Float = 1f,+ val blendMode: BlendMode = DrawScope.DefaultBlendMode+) {++ companion object {++ @Stable+ val Default: Shadow = Shadow()+ }+}diff --git a/backdrop/src/commonMain/kotlin/com/kyant/backdrop/shadow/ShadowModifier.kt b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/shadow/ShadowModifier.ktnew file mode 100644index 0000000..cd4b6e3--- /dev/null+++ b/backdrop/src/commonMain/kotlin/com/kyant/backdrop/shadow/ShadowModifier.kt@@ -0,0 +1,137 @@+package com.kyant.backdrop.shadow++import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.BlendMode+import androidx.compose.ui.graphics.Paint+import androidx.compose.ui.graphics.drawOutline+import androidx.compose.ui.graphics.drawscope.ContentDrawScope+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.graphics.drawscope.translate+import androidx.compose.ui.graphics.layer.CompositingStrategy+import androidx.compose.ui.graphics.layer.GraphicsLayer+import androidx.compose.ui.graphics.layer.drawLayer+import androidx.compose.ui.node.DrawModifierNode+import androidx.compose.ui.node.ModifierNodeElement+import androidx.compose.ui.node.invalidateDraw+import androidx.compose.ui.node.requireGraphicsContext+import androidx.compose.ui.platform.InspectorInfo+import androidx.compose.ui.unit.Density+import androidx.compose.ui.unit.IntSize+import com.kyant.backdrop.internal.ShapeProvider+import com.kyant.backdrop.internal.blur+import kotlin.math.ceil++internal class ShadowElement(+ val shapeProvider: ShapeProvider,+ val shadow: () -> Shadow?+) : ModifierNodeElement<ShadowNode>() {++ override fun create(): ShadowNode {+ return ShadowNode(shapeProvider, shadow)+ }++ override fun update(node: ShadowNode) {+ node.shapeProvider = shapeProvider+ node.shadow = shadow+ node.invalidateDraw()+ }++ override fun InspectorInfo.inspectableProperties() {+ name = "shadow"+ properties["shapeProvider"] = shapeProvider+ properties["shadow"] = shadow+ }++ override fun equals(other: Any?): Boolean {+ if (this === other) return true+ if (other !is ShadowElement) return false++ if (shapeProvider != other.shapeProvider) return false+ if (shadow != other.shadow) return false++ return true+ }++ override fun hashCode(): Int {+ var result = shapeProvider.hashCode()+ result = 31 * result + shadow.hashCode()+ return result+ }+}++internal class ShadowNode(+ var shapeProvider: ShapeProvider,+ var shadow: () -> Shadow?+) : DrawModifierNode, Modifier.Node() {++ override val shouldAutoInvalidate: Boolean = false++ private var shadowLayer: GraphicsLayer? = null++ private val paint = Paint()++ override fun ContentDrawScope.draw() {+ val shadow = shadow() ?: return drawContent()++ val shadowLayer = shadowLayer+ if (shadowLayer != null) {+ val size = size+ val density: Density = this+ val layoutDirection = layoutDirection++ val radius = shadow.radius.toPx()+ val offsetX = shadow.offset.x.toPx()+ val offsetY = shadow.offset.y.toPx()+ val shadowSize = IntSize(+ ceil(size.width + radius * 4f + offsetX).toInt(),+ ceil(size.height + radius * 4f + offsetY).toInt()+ )+ val outline = shapeProvider.shape.createOutline(size, layoutDirection, density)++ configurePaint(shadow)++ shadowLayer.alpha = shadow.alpha+ shadowLayer.blendMode = shadow.blendMode+ shadowLayer.record(shadowSize) {+ translate(radius * 2f + offsetX, radius * 2f + offsetY) {+ val canvas = drawContext.canvas+ canvas.drawOutline(outline, paint)+ canvas.translate(-offsetX, -offsetY)+ canvas.drawOutline(outline, ShadowMaskPaint)+ canvas.translate(offsetX, offsetY)+ }+ }++ translate(-radius * 2f, -radius * 2f) {+ drawLayer(shadowLayer)+ }+ }++ drawContent()+ }++ override fun onAttach() {+ val graphicsContext = requireGraphicsContext()+ shadowLayer =+ graphicsContext.createGraphicsLayer().apply {+ compositingStrategy = CompositingStrategy.Offscreen+ }+ }++ override fun onDetach() {+ val graphicsContext = requireGraphicsContext()+ shadowLayer?.let { layer ->+ graphicsContext.releaseGraphicsLayer(layer)+ shadowLayer = null+ }+ }++ private fun DrawScope.configurePaint(shadow: Shadow) {+ paint.color = shadow.color+ paint.blur(shadow.radius.toPx())+ }+}++private val ShadowMaskPaint = Paint().apply {+ blendMode = BlendMode.Clear+}diff --git a/backdrop/src/skikoMain/kotlin/com/kyant/backdrop/Platform.kt b/backdrop/src/skikoMain/kotlin/com/kyant/backdrop/Platform.ktnew file mode 100644index 0000000..319c228--- /dev/null+++ b/backdrop/src/skikoMain/kotlin/com/kyant/backdrop/Platform.kt@@ -0,0 +1,5 @@+package com.kyant.backdrop++actual fun isRenderEffectSupported(): Boolean = true++actual fun isRuntimeShaderSupported(): Boolean = truediff --git a/backdrop/src/skikoMain/kotlin/com/kyant/backdrop/RuntimeShader.kt b/backdrop/src/skikoMain/kotlin/com/kyant/backdrop/RuntimeShader.ktnew file mode 100644index 0000000..ec33d6b--- /dev/null+++ b/backdrop/src/skikoMain/kotlin/com/kyant/backdrop/RuntimeShader.kt@@ -0,0 +1,71 @@+package com.kyant.backdrop++import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Shader+import androidx.compose.ui.graphics.asComposeShader+import androidx.compose.ui.graphics.colorspace.ColorSpaces+import org.intellij.lang.annotations.Language+import org.jetbrains.skia.RuntimeEffect+import org.jetbrains.skia.RuntimeShaderBuilder++actual fun RuntimeShader(@Language("AGSL") shaderString: String): RuntimeShader {+ val shader = RuntimeShaderBuilder(RuntimeEffect.makeForShader(shaderString))+ return SkikoRuntimeShader(shader)+}++actual fun RuntimeShader.asComposeShader(): Shader {+ return this.asSkikoRuntimeShader().makeShader().asComposeShader()+}++fun RuntimeShader.asSkikoRuntimeShader(): RuntimeShaderBuilder {+ return (this as SkikoRuntimeShader).shader+}++internal class SkikoRuntimeShader(val shader: RuntimeShaderBuilder) : RuntimeShader {++ override fun setFloatUniform(name: String, value: Float) {+ shader.uniform(name, value)+ }++ override fun setFloatUniform(name: String, value1: Float, value2: Float) {+ shader.uniform(name, value1, value2)+ }++ override fun setFloatUniform(name: String, value1: Float, value2: Float, value3: Float) {+ shader.uniform(name, value1, value2, value3)+ }++ override fun setFloatUniform(name: String, value1: Float, value2: Float, value3: Float, value4: Float) {+ shader.uniform(name, value1, value2, value3, value4)+ }++ override fun setFloatUniform(name: String, values: FloatArray) {+ shader.uniform(name, values)+ }++ override fun setIntUniform(name: String, value: Int) {+ shader.uniform(name, value)+ }++ override fun setIntUniform(name: String, value1: Int, value2: Int) {+ shader.uniform(name, value1, value2)+ }++ override fun setIntUniform(name: String, value1: Int, value2: Int, value3: Int) {+ shader.uniform(name, value1, value2, value3)+ }++ override fun setIntUniform(name: String, value1: Int, value2: Int, value3: Int, value4: Int) {+ shader.uniform(name, value1, value2, value3, value4)+ }++ override fun setIntUniform(name: String, values: IntArray) {+ throw UnsupportedOperationException("Setting int array uniforms is not supported on Skia RuntimeShader.")+ }++ override fun setColorUniform(name: String, color: Color) {+ val srgb = color.convert(ColorSpaces.Srgb)+ val a = srgb.alpha+ shader.uniform(name, srgb.red * a, srgb.green * a, srgb.blue * a, a)+ }+}diff --git a/backdrop/src/skikoMain/kotlin/com/kyant/backdrop/internal/Paint.kt b/backdrop/src/skikoMain/kotlin/com/kyant/backdrop/internal/Paint.ktnew file mode 100644index 0000000..0bdd1c3--- /dev/null+++ b/backdrop/src/skikoMain/kotlin/com/kyant/backdrop/internal/Paint.kt@@ -0,0 +1,18 @@+package com.kyant.backdrop.internal++import androidx.compose.ui.graphics.Paint+import androidx.compose.ui.graphics.skiaPaint+import com.kyant.backdrop.RuntimeShader+import com.kyant.backdrop.asSkikoRuntimeShader+import org.jetbrains.skia.FilterBlurMode+import org.jetbrains.skia.MaskFilter++internal actual fun Paint.blur(radius: Float) {+ this.skiaPaint.maskFilter =+ if (radius > 0f) MaskFilter.makeBlur(FilterBlurMode.NORMAL, radius)+ else null+}++internal actual fun Paint.setRuntimeShader(runtimeShader: RuntimeShader?) {+ this.skiaPaint.shader = runtimeShader?.asSkikoRuntimeShader()?.makeShader()+}diff --git a/backdrop/src/skikoMain/kotlin/com/kyant/backdrop/internal/RenderEffect.kt b/backdrop/src/skikoMain/kotlin/com/kyant/backdrop/internal/RenderEffect.ktnew file mode 100644index 0000000..ee1de05--- /dev/null+++ b/backdrop/src/skikoMain/kotlin/com/kyant/backdrop/internal/RenderEffect.kt@@ -0,0 +1,40 @@+package com.kyant.backdrop.internal++import androidx.compose.ui.graphics.ColorFilter+import androidx.compose.ui.graphics.RenderEffect+import androidx.compose.ui.graphics.asComposeRenderEffect+import androidx.compose.ui.graphics.asSkiaColorFilter+import androidx.compose.ui.graphics.skiaImageFilter+import com.kyant.backdrop.RuntimeShader+import com.kyant.backdrop.asSkikoRuntimeShader+import org.jetbrains.skia.ImageFilter++internal actual fun RenderEffect?.chain(other: RenderEffect): RenderEffect {+ return if (this != null) {+ ImageFilter.makeCompose(other.skiaImageFilter, this.skiaImageFilter).asComposeRenderEffect()+ } else {+ other+ }+}++internal actual fun RuntimeShaderEffect(+ runtimeShader: RuntimeShader,+ uniformShaderName: String+): RenderEffect {+ return ImageFilter.makeRuntimeShader(+ runtimeShader.asSkikoRuntimeShader(),+ uniformShaderName,+ null+ ).asComposeRenderEffect()+}++internal actual fun ColorFilterEffect(+ renderEffect: RenderEffect?,+ colorFilter: ColorFilter+): RenderEffect {+ return ImageFilter.makeColorFilter(+ colorFilter.asSkiaColorFilter(),+ renderEffect?.skiaImageFilter,+ null+ ).asComposeRenderEffect()+}