Skip to content

Open-source Android PDF and document toolkit with PDF tools, Office viewing, XLSX editing, scanning, and image editing. Built with Kotlin and Jetpack Compose.

Glass perf: quiet the gravity sensor, lazy press shader, idle toggle/slider thumbs skip hidden blur

Chethan616c55379066f0d
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.kt
index 9c60586..3adb35b 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
@@ -186,7 +186,9 @@ fun LiquidSlider(
shape = { Capsule },
effects = {
val progress = dampedDragAnimation.pressProgress
- blur(8f.dp.toPx() * (1f - progress))
+ // At rest the thumb is an opaque white capsule (see onDrawSurface), so a blur
+ // of what is under it would be invisible work. Only refract once pressed.
+ if (progress > 0f) blur(8f.dp.toPx() * (1f - progress))
lens(
10f.dp.toPx() * progress,
14f.dp.toPx() * progress,
@@ -195,7 +197,9 @@ fun LiquidSlider(
},
highlight = {
val progress = dampedDragAnimation.pressProgress
- Highlight.Ambient.copy(
+ // Alpha 0 at rest: skip it outright, so an idle thumb never builds the
+ // highlight shader at all.
+ if (progress <= 0f) null else Highlight.Ambient.copy(
width = Highlight.Ambient.width / 1.5f,
blurRadius = Highlight.Ambient.blurRadius / 1.5f,
alpha = progress
@@ -206,7 +210,11 @@ fun LiquidSlider(
},
innerShadow = {
val progress = dampedDragAnimation.pressProgress
- InnerShadow(radius = 4f.dp * progress, alpha = progress)
+ if (progress <= 0f) null else InnerShadow(radius = 4f.dp * progress, alpha = progress)
+ },
+ // Fully covered by the opaque white surface at rest — see LiquidToggle.
+ onDrawBackdrop = { drawBackdrop ->
+ if (dampedDragAnimation.pressProgress > 0f) drawBackdrop()
},
layerBlock = {
scaleX = dampedDragAnimation.scaleX
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/components/LiquidToggle.kt b/app/src/main/java/com/chethan616/clearpdf/ui/components/LiquidToggle.kt
index 59405b5..3d26f92 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
@@ -178,7 +178,9 @@ fun LiquidToggle(
shape = { Capsule },
effects = {
val progress = dampedDragAnimation.pressProgress
- blur(8f.dp.toPx() * (1f - progress))
+ // At rest the thumb is an opaque white capsule (see onDrawSurface), so a blur
+ // of what is under it would be invisible work. Only refract once pressed.
+ if (progress > 0f) blur(8f.dp.toPx() * (1f - progress))
lens(
5f.dp.toPx() * progress,
10f.dp.toPx() * progress,
@@ -187,7 +189,9 @@ fun LiquidToggle(
},
highlight = {
val progress = dampedDragAnimation.pressProgress
- Highlight.Ambient.copy(
+ // Alpha 0 at rest: skip it outright, so an idle thumb never builds the
+ // highlight shader at all.
+ if (progress <= 0f) null else Highlight.Ambient.copy(
width = Highlight.Ambient.width / 1.5f,
blurRadius = Highlight.Ambient.blurRadius / 1.5f,
alpha = progress
@@ -201,11 +205,17 @@ fun LiquidToggle(
},
innerShadow = {
val progress = dampedDragAnimation.pressProgress
- InnerShadow(
+ if (progress <= 0f) null else InnerShadow(
radius = 4f.dp * progress,
alpha = progress
)
},
+ // The backdrop is fully covered by the opaque white surface at rest; don't even
+ // record it then. A scrolling list re-samples every visible glass node per frame,
+ // and a page of idle toggles was paying for blurs nobody could see.
+ onDrawBackdrop = { drawBackdrop ->
+ if (dampedDragAnimation.pressProgress > 0f) drawBackdrop()
+ },
layerBlock = {
scaleX = dampedDragAnimation.scaleX
scaleY = dampedDragAnimation.scaleY
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/utils/InteractiveHighlight.kt b/app/src/main/java/com/chethan616/clearpdf/ui/utils/InteractiveHighlight.kt
index e298cc8..dbc8f57 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/utils/InteractiveHighlight.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/utils/InteractiveHighlight.kt
@@ -35,7 +35,11 @@ class InteractiveHighlight(
val pressProgress: Float get() = pressProgressAnimation.value
val offset: Offset get() = positionAnimation.value - startPosition
- private val shader =
+ // Built on first press, not at construction. Every LiquidButton / LiquidIconButton / glass card
+ // owns one of these, and `RuntimeShader(...)` compiles its AGSL on the calling thread — so a
+ // screen of buttons used to pay one shader compile per button during composition (and a list
+ // paid it again for every row it scrolled in), for a highlight most buttons never show.
+ private val shader: RuntimeShader? by lazy(LazyThreadSafetyMode.NONE) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
RuntimeShader(
"""
@@ -53,11 +57,13 @@ half4 main(float2 coord) {
} else {
null
}
+ }
val modifier: Modifier =
Modifier.drawWithContent {
val progress = pressProgressAnimation.value
if (progress > 0f) {
+ val shader = [email protected]
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && shader != null) {
drawRect(Color.White.copy(0.08f * progress), blendMode = BlendMode.Plus)
shader.apply {
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/utils/UISensor.kt b/app/src/main/java/com/chethan616/clearpdf/ui/utils/UISensor.kt
index 2947ebd..961cf4c 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/utils/UISensor.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/utils/UISensor.kt
@@ -14,27 +14,71 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.platform.LocalContext
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.LifecycleEventObserver
+import androidx.lifecycle.compose.LocalLifecycleOwner
import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.atan2
import kotlin.math.sqrt
+/**
+ * The gravity source behind every glass surface's specular rim ([HighlightStyle.Default]'s angle).
+ *
+ * Listens only while the hosting lifecycle is RESUMED. Inside the NavHost that lifecycle is the
+ * back-stack entry's, so the sensor is off while a screen is in the back stack, while its enter or
+ * exit transition is still running, and while the app is in the background — previously it kept
+ * firing (and invalidating every glass panel) from first composition until the screen was disposed.
+ */
@Composable
fun rememberUISensor(): UISensor {
val context = LocalContext.current
+ val lifecycleOwner = LocalLifecycleOwner.current
val uiSensor = remember { UISensor(context) }
- DisposableEffect(Unit) {
- uiSensor.start()
- onDispose { uiSensor.stop() }
+ DisposableEffect(lifecycleOwner, uiSensor) {
+ val observer = LifecycleEventObserver { _, event ->
+ when (event) {
+ Lifecycle.Event.ON_RESUME -> uiSensor.start()
+ Lifecycle.Event.ON_PAUSE -> uiSensor.stop()
+ else -> Unit
+ }
+ }
+ // addObserver replays the events up to the current state, so an already-resumed screen
+ // starts listening immediately.
+ lifecycleOwner.lifecycle.addObserver(observer)
+ onDispose {
+ lifecycleOwner.lifecycle.removeObserver(observer)
+ uiSensor.stop()
+ }
}
return uiSensor
}
+/**
+ * Why this is more than a raw `atan2`:
+ *
+ * [gravityAngle] is read in the *draw* phase of every `liquidGlassPanel`, search pill and capsule
+ * menu, and each write re-records that surface and re-runs its blur + lens on the GPU — plus the
+ * header and tab bar that sample the content under them. The old filter (alpha 0.5, 0.35 deg
+ * threshold) let ordinary hand tremor through on nearly every sample, so an idle Home or Tools
+ * screen re-rendered all of its glass ~15 times a second. Worse, on a phone lying flat the in-plane
+ * gravity is pure noise, `atan2` of noise is a random angle, and the highlight spun continuously.
+ *
+ * Now: the angle is only derived when the device is tilted enough for it to mean something, it is
+ * filtered along the shortest arc (no 359 -> 0 sweep), and it is published only once it has moved
+ * past a [ANGLE_DEADBAND_DEG] dead band. A steady hand or a phone on a desk publishes nothing; a
+ * deliberate tilt still sweeps the highlight round smoothly.
+ */
class UISensor(context: Context) {
private companion object {
- const val SMOOTHING_ALPHA = 0.5f
- const val ANGLE_DELTA_THRESHOLD_DEG = 0.35f
- const val GRAVITY_DELTA_THRESHOLD = 0.004f
+ /** Low-pass weight of each new sample. Lower = steadier, slower to follow a tilt. */
+ const val SMOOTHING_ALPHA = 0.25f
+ /** The published angle only moves once the filtered one has drifted this far. */
+ const val ANGLE_DEADBAND_DEG = 1.5f
+ /** Below this in-plane gravity (m/s^2, ~9 deg from flat) the angle is noise: hold it. */
+ const val MIN_PLANAR_GRAVITY = 1.5f
+ const val GRAVITY_DELTA_THRESHOLD = 0.02f
+ const val RAD_TO_DEG = (180.0 / PI).toFloat()
}
var gravityAngle: Float by mutableFloatStateOf(45f)
@@ -42,39 +86,56 @@ class UISensor(context: Context) {
var gravity: Offset by mutableStateOf(Offset.Zero)
private set
+ /** The filtered angle, tracked privately so only dead-band crossings reach snapshot state. */
+ private var filteredAngle = 45f
+ private var filteredGravity = Offset.Zero
+ private var listening = false
+
private val sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
- private val accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
+ private val accelerometer: Sensor? = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
private val listener = object : SensorEventListener {
override fun onSensorChanged(event: SensorEvent?) {
- if (event == null) return
- if (event.sensor.type == Sensor.TYPE_ACCELEROMETER) {
- val x = event.values[0]
- val y = event.values[1]
- val norm = sqrt(x * x + y * y + 9.81f * 9.81f).coerceAtLeast(0.001f)
+ if (event == null || event.sensor.type != Sensor.TYPE_ACCELEROMETER) return
+ val x = event.values[0]
+ val y = event.values[1]
- val rawAngle = atan2(y, x) * (180f / PI).toFloat()
- val filteredAngle = gravityAngle * (1f - SMOOTHING_ALPHA) + rawAngle * SMOOTHING_ALPHA
- if (abs(filteredAngle - gravityAngle) >= ANGLE_DELTA_THRESHOLD_DEG) {
+ val planar = sqrt(x * x + y * y)
+ if (planar >= MIN_PLANAR_GRAVITY) {
+ val raw = atan2(y, x) * RAD_TO_DEG
+ filteredAngle = wrap(filteredAngle + wrap(raw - filteredAngle) * SMOOTHING_ALPHA)
+ if (abs(wrap(filteredAngle - gravityAngle)) >= ANGLE_DEADBAND_DEG) {
gravityAngle = filteredAngle
}
+ }
- val normalizedGravity = Offset(x / norm, y / norm)
- val filteredGravity = gravity * (1f - SMOOTHING_ALPHA) + normalizedGravity * SMOOTHING_ALPHA
- val dx = filteredGravity.x - gravity.x
- val dy = filteredGravity.y - gravity.y
- if (dx * dx + dy * dy >= GRAVITY_DELTA_THRESHOLD * GRAVITY_DELTA_THRESHOLD) {
- gravity = filteredGravity
- }
+ val norm = sqrt(x * x + y * y + 9.81f * 9.81f).coerceAtLeast(0.001f)
+ filteredGravity = filteredGravity * (1f - SMOOTHING_ALPHA) + Offset(x / norm, y / norm) * SMOOTHING_ALPHA
+ val dx = filteredGravity.x - gravity.x
+ val dy = filteredGravity.y - gravity.y
+ if (dx * dx + dy * dy >= GRAVITY_DELTA_THRESHOLD * GRAVITY_DELTA_THRESHOLD) {
+ gravity = filteredGravity
}
}
+
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) = Unit
}
fun start() {
- sensorManager.registerListener(listener, accelerometer, SensorManager.SENSOR_DELAY_UI)
+ if (listening || accelerometer == null) return
+ listening = sensorManager.registerListener(listener, accelerometer, SensorManager.SENSOR_DELAY_UI)
}
fun stop() {
+ if (!listening) return
sensorManager.unregisterListener(listener)
+ listening = false
+ }
+
+ /** Maps any angle in degrees onto (-180, 180]. */
+ private fun wrap(deg: Float): Float {
+ var d = deg % 360f
+ if (d > 180f) d -= 360f
+ if (d <= -180f) d += 360f
+ return d
}
}