Unofficial YouTube Music / Spotify Premium client for Android, built in Liquid Glass. Audio effects, Spotify Connect, listening history, 8 languages. Rust core on librespot.
Kotlin alternativeandroidandroid-applicationclientglassmorphisminnertubelibrespotliquid-glassspotifyspotify-connectspotifyapiyoutube-musicyoutube-playerytdlnis
Stop the glass re-photographing a screen that is moving
Lelonio86c0f77f5ad2
diff --git a/app/src/main/java/dev/lelonio/square/ProfileReport.kt b/app/src/main/java/dev/lelonio/square/ProfileReport.ktnew file mode 100644index 0000000..d6a1e5a--- /dev/null+++ b/app/src/main/java/dev/lelonio/square/ProfileReport.kt@@ -0,0 +1,50 @@+package dev.lelonio.square++import android.util.Log+import androidx.profileinstaller.ProfileVerifier+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch++/**+ * Says, in the log, whether this install is actually compiled.+ *+ * The app ships a baseline profile so the code the bar and the player use is+ * compiled before it runs rather than while it runs. What it cannot do is+ * decide when: Android installs the profile at first launch and compiles it+ * later, with a system job that waits for the phone to be idle and charging.+ * Until that job runs, everything is interpreted and optimised on the fly,+ * which is exactly what "it gets smoother the longer the app is open" is.+ *+ * That makes the difference between a real performance problem and a phone that+ * has not compiled the app yet impossible to tell apart by feel. This removes+ * the guessing: one line at startup saying which of the two it is.+ */+fun reportProfileStatus(scope: CoroutineScope) {+ scope.launch(Dispatchers.IO) {+ runCatching {+ val status = ProfileVerifier.getCompilationStatusAsync().get()+ val state = when (status.profileInstallResultCode) {+ ProfileVerifier.CompilationStatus.RESULT_CODE_NO_PROFILE ->+ "no profile shipped"+ ProfileVerifier.CompilationStatus.RESULT_CODE_COMPILED_WITH_PROFILE ->+ "compiled with the profile"+ ProfileVerifier.CompilationStatus.RESULT_CODE_PROFILE_ENQUEUED_FOR_COMPILATION ->+ "profile installed, waiting for the system to compile it"+ ProfileVerifier.CompilationStatus.RESULT_CODE_COMPILED_WITH_PROFILE_NON_MATCHING ->+ "compiled with a profile from another build"+ ProfileVerifier.CompilationStatus.RESULT_CODE_ERROR_PACKAGE_NAME_DOES_NOT_EXIST ->+ "package not found"+ else -> "unknown (${status.profileInstallResultCode})"+ }+ Log.i(+ TAG,+ "baseline profile: $state" ++ " (compiled with a profile: ${status.isCompiledWithProfile}," ++ " waiting to be compiled: ${status.hasProfileEnqueuedForCompilation()})",+ )+ }.onFailure { Log.w(TAG, "could not read the profile status: $it") }+ }+}++private const val TAG = "SquareProfile"diff --git a/app/src/main/java/dev/lelonio/square/SquareApplication.kt b/app/src/main/java/dev/lelonio/square/SquareApplication.ktindex fe57e5e..6d16d76 100644--- a/app/src/main/java/dev/lelonio/square/SquareApplication.kt+++ b/app/src/main/java/dev/lelonio/square/SquareApplication.kt@@ -28,6 +28,12 @@ class SquareApplication : Application() {// exist by then and either can announce a default that would be saved// over what the listener had set.dev.lelonio.square.playback.AudioEffects.load(this)++ // Not a feature: a line in the log saying whether this install has been+ // compiled ahead of time yet. See reportProfileStatus.+ reportProfileStatus(+ kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.SupervisorJob()),+ )}val tokenStore: TokenStore by lazy { TokenStore(this) }diff --git a/app/src/main/java/dev/lelonio/square/data/GlassStore.kt b/app/src/main/java/dev/lelonio/square/data/GlassStore.ktindex 65a0e72..5a4fed4 100644--- a/app/src/main/java/dev/lelonio/square/data/GlassStore.kt+++ b/app/src/main/java/dev/lelonio/square/data/GlassStore.kt@@ -128,6 +128,7 @@ class GlassStore(context: Context) {/** How strongly the selected tab is washed; see [read]. */fun setPuckOpacity(value: Float) = putFloat(KEY_PUCK, value)+/*** Whether the bottom bar folds away as you scroll.*diff --git a/app/src/main/java/dev/lelonio/square/data/LocalLibrary.kt b/app/src/main/java/dev/lelonio/square/data/LocalLibrary.ktnew file mode 100644index 0000000..3f0a320--- /dev/null+++ b/app/src/main/java/dev/lelonio/square/data/LocalLibrary.kt@@ -0,0 +1,146 @@+package dev.lelonio.square.data++import android.Manifest+import android.content.ContentUris+import android.content.Context+import android.content.pm.PackageManager+import android.os.Build+import android.provider.MediaStore+import androidx.core.content.ContextCompat+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext++/**+ * The audio already on the phone.+ *+ * Square hands downloading to whatever app the user has for it, so what comes+ * back is a file somewhere on the device rather than anything this app placed.+ * MediaStore is therefore the only sensible way to find it: it answers "what+ * audio is on this phone", which is the actual question, while a hardcoded+ * folder answers "what audio is where I guessed", and every downloader lets its+ * user change that.+ *+ * It also means the tags the downloader wrote are already parsed. Title, artist,+ * album, duration and the embedded cover come back from the index rather than+ * from this app opening files and reading headers.+ *+ * Visible whichever source is selected. A file on the phone is not a third+ * streaming service to switch to; it is there in both.+ */+object LocalLibrary {++ /** The URI scheme local tracks carry, so every screen can tell them apart. */+ const val PREFIX = "local:track:"++ /**+ * The permission needed to read any of this.+ *+ * Split at Android 13, where the single storage permission was broken up by+ * media type. Asking for audio alone is the whole point of the newer one:+ * this app has no business seeing photographs.+ */+ val permission: String =+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ Manifest.permission.READ_MEDIA_AUDIO+ } else {+ Manifest.permission.READ_EXTERNAL_STORAGE+ }++ fun granted(context: Context): Boolean =+ ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED++ fun idOfUri(uri: String): Long = uri.removePrefix(PREFIX).toLongOrNull() ?: -1L++ fun isLocal(uri: String): Boolean = uri.startsWith(PREFIX)++ /**+ * The content URI a player can open.+ *+ * Built back from the id rather than stored: a `content://` URI is only+ * meaningful while the row it points at exists, and keeping one in a saved+ * queue would be keeping a handle to a file that may since have been+ * deleted.+ */+ fun contentUri(uri: String): android.net.Uri =+ ContentUris.withAppendedId(collection(), idOfUri(uri))++ /**+ * Everything the index calls music, newest first.+ *+ * Newest first because these arrive by download: what was fetched last is+ * what the user came looking for, and alphabetical order would bury it.+ */+ suspend fun tracks(context: Context): List<CatalogTrack> = withContext(Dispatchers.IO) {+ if (!granted(context)) return@withContext emptyList()++ val columns = arrayOf(+ MediaStore.Audio.Media._ID,+ MediaStore.Audio.Media.TITLE,+ MediaStore.Audio.Media.ARTIST,+ MediaStore.Audio.Media.ALBUM,+ MediaStore.Audio.Media.ALBUM_ID,+ MediaStore.Audio.Media.DURATION,+ )++ runCatching {+ context.contentResolver.query(+ collection(),+ columns,+ // Ringtones, notification sounds and voice recordings are all+ // in here too, and none of them belong in a music library.+ "${MediaStore.Audio.Media.IS_MUSIC} != 0",+ null,+ "${MediaStore.Audio.Media.DATE_ADDED} DESC",+ )?.use { cursor ->+ val id = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID)+ val title = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)+ val artist = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST)+ val album = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM)+ val albumId = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID)+ val duration = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION)++ buildList {+ while (cursor.moveToNext()) {+ add(+ CatalogTrack(+ uri = PREFIX + cursor.getLong(id),+ name = cursor.getString(title).orEmpty(),+ // MediaStore says "<unknown>" for an untagged+ // file, which is worse than saying nothing.+ artist = cursor.getString(artist)+ ?.takeUnless { it == MediaStore.UNKNOWN_STRING }+ .orEmpty(),+ album = cursor.getString(album).orEmpty(),+ durationMs = cursor.getLong(duration),+ artworkUrl = artworkUri(cursor.getLong(albumId)),+ ),+ )+ }+ }+ }.orEmpty()+ }.getOrElse {+ android.util.Log.w(TAG, "could not read the media store: $it")+ emptyList()+ }+ }++ /**+ * The album art, as something the image loader can fetch.+ *+ * The album's artwork rather than the file's own embedded picture: the+ * former is one URI the loader can cache, and the latter would mean opening+ * and decoding every file to build a list.+ */+ private fun artworkUri(albumId: Long): String? =+ if (albumId <= 0) null else "content://media/external/audio/albumart/$albumId"++ private fun collection() =+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {+ MediaStore.Audio.Media.getContentUri(MediaStore.VOLUME_EXTERNAL)+ } else {+ @Suppress("DEPRECATION")+ MediaStore.Audio.Media.EXTERNAL_CONTENT_URI+ }++ private const val TAG = "LocalLibrary"+}diff --git a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt b/app/src/main/java/dev/lelonio/square/ui/SquareApp.ktindex bc6b272..16ab70a 100644--- a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt+++ b/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt@@ -49,6 +49,9 @@ import dev.lelonio.square.ui.components.SharedTrackCardimport androidx.compose.foundation.gestures.awaitEachGestureimport androidx.compose.foundation.gestures.awaitFirstDownimport androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.draw.drawBehind+import androidx.compose.ui.graphics.drawOutline+import androidx.compose.ui.graphics.isSpecifiedimport androidx.compose.foundation.layout.imePaddingimport androidx.compose.foundation.text.BasicTextFieldimport androidx.compose.ui.focus.FocusRequester@@ -1067,17 +1070,22 @@ fun SquareApp(} else {glassConfig.copy(style = flat)}+ // Nothing special while the bar changes shape.+ //+ // Two things were tried there and both were worse than what+ // they fixed. Taking the glass away for the length of the+ // fold was the cheapest and you could see it go. Holding the+ // last capture instead was invisible while it lasted, but+ // the bar's two states are two different pieces of+ // composition, so the fresh capture arrives on a node that+ // has just been created and the correction is a cut nothing+ // can fade. The glass simply keeps working.+ val barShape = androidx.compose.foundation.shape.RoundedCornerShape(percent = 50)+val barGlass = Modifier.liquidGlass(config = barConfig,- shape = androidx.compose.foundation.shape.RoundedCornerShape(percent = 50),+ shape = barShape,highlightAlpha = 0.3f,- // Held still while the bar morphs. Its bounds animate- // across the whole fold, and without this every frame- // re-records the screen and runs the blur and the lens- // over it again — which is most of what made the- // animation crawl.- frozen = dev.lelonio.square.ui.glass.floatingtabbar- .LocalTabBarBackdropFrozen.current,)// The same pane, on the pill above it, unless the settings// have singled that one out.@@ -1086,10 +1094,8 @@ fun SquareApp(} else {Modifier.liquidGlass(config = pillConfig,- shape = androidx.compose.foundation.shape.RoundedCornerShape(percent = 50),+ shape = barShape,highlightAlpha = 0.3f,- frozen = dev.lelonio.square.ui.glass.floatingtabbar- .LocalTabBarBackdropFrozen.current,)}diff --git a/app/src/main/java/dev/lelonio/square/ui/glass/GlassEffect.kt b/app/src/main/java/dev/lelonio/square/ui/glass/GlassEffect.ktindex ff28d3b..75b8a21 100644--- a/app/src/main/java/dev/lelonio/square/ui/glass/GlassEffect.kt+++ b/app/src/main/java/dev/lelonio/square/ui/glass/GlassEffect.kt@@ -366,6 +366,14 @@ fun Modifier.liquidGlass(// bar's bounds animate and would otherwise force a full-screen re-capture// plus effect chain on every frame.frozen: () -> Boolean = LocalGlassFrozen.current,+ /**+ * Hold the capture even while this surface is moving.+ *+ * For a surface that is changing shape: see the use site in+ * `DrawBackdropModifier`. Off everywhere else, where a moved surface must+ * take a fresh capture or it reflects the place it used to be.+ */+ heldWhileMoving: () -> Boolean = { false },// Forwarded to drawBackdrop: see LocalBackdropLoopBucket's doc. Defaults to// whatever's provided in composition, so player control pills over a// looping video pick this up without every call site naming it explicitly.@@ -578,6 +586,7 @@ fun Modifier.liquidGlass(// every frame of its fold, was accepted and dropped.backdropScale = resolutionScale,frozen = heldStill,+ heldWhileMoving = heldWhileMoving,loopBucket = loopBucket,)}diff --git a/app/src/main/java/dev/lelonio/square/ui/glass/GlassWarmUp.kt b/app/src/main/java/dev/lelonio/square/ui/glass/GlassWarmUp.ktindex e666e34..7929ad0 100644--- a/app/src/main/java/dev/lelonio/square/ui/glass/GlassWarmUp.kt+++ b/app/src/main/java/dev/lelonio/square/ui/glass/GlassWarmUp.kt@@ -18,6 +18,7 @@ import dev.lelonio.square.ui.glass.backdrop.effects.lensimport dev.lelonio.square.ui.glass.backdrop.effects.vibrancyimport dev.lelonio.square.ui.glass.backdrop.highlight.Highlightimport dev.lelonio.square.ui.glass.backdrop.shadow.Shadow+import dev.lelonio.square.ui.glass.floatingtabbar.gooeyimport dev.lelonio.square.ui.glass.shapes.ContinuousCapsule/**@@ -35,6 +36,13 @@ import dev.lelonio.square.ui.glass.shapes.ContinuousCapsule* it folded. So it is drawn at a hundredth of its opacity, which is enough for* the shaders to be compiled for real and not enough for anyone to see, and it* stops being composed once the first frames it exists for have gone by.+ *+ * The fold has a shader of its own that no ordinary surface uses: the gooey+ * merge, a blur followed by a steep alpha threshold, which is what makes the+ * shapes bleed into one another and pinch off instead of cross-fading. It was+ * not warmed with the rest, so the very first fold still paid for compiling it —+ * which is a good part of "the first one stutters and then it is fine". It is+ * warmed here too, on the same invisible pixel.*/@Composablefun GlassWarmUp(backdrop: dev.lelonio.square.ui.glass.backdrop.Backdrop) {@@ -50,6 +58,10 @@ fun GlassWarmUp(backdrop: dev.lelonio.square.ui.glass.backdrop.Backdrop) {Modifier.size(1.dp).graphicsLayer { alpha = 0.01f }+ // The fold's own effect, around the pane rather than on it: that is+ // where it sits in the bar, and a shader is compiled for the way it+ // is used.+ .gooey { 6f }.drawBackdrop(backdrop = backdrop,shape = { ContinuousCapsule() },diff --git a/app/src/main/java/dev/lelonio/square/ui/glass/SquareBottomBar.kt b/app/src/main/java/dev/lelonio/square/ui/glass/SquareBottomBar.ktnew file mode 100644index 0000000..a85cc29--- /dev/null+++ b/app/src/main/java/dev/lelonio/square/ui/glass/SquareBottomBar.kt@@ -0,0 +1,416 @@+package dev.lelonio.square.ui.glass++import androidx.compose.animation.core.Animatable+import androidx.compose.animation.core.Spring+import androidx.compose.animation.core.spring+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.State+import androidx.compose.runtime.getValue+import androidx.compose.runtime.setValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.drawBehind+import androidx.compose.ui.graphics.graphicsLayer+import dev.lelonio.square.ui.glass.backdrop.drawBackdrop+import dev.lelonio.square.ui.glass.backdrop.effects.vibrancy+import dev.lelonio.square.ui.glass.backdrop.effects.blur+import dev.lelonio.square.ui.glass.backdrop.effects.lens+import dev.lelonio.square.ui.glass.backdrop.highlight.Highlight+import dev.lelonio.square.ui.glass.backdrop.shadow.Shadow+import dev.lelonio.square.ui.glass.shapes.ContinuousCapsule+import androidx.compose.foundation.gestures.detectHorizontalDragGestures+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.runtime.rememberCoroutineScope+import kotlinx.coroutines.launch+import androidx.compose.ui.layout.Layout+import androidx.compose.ui.layout.layoutId+import androidx.compose.ui.layout.layout+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.unit.Constraints+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import androidx.compose.ui.util.lerp+import kotlin.math.roundToInt++/**+ * The bottom bar, folded and unfolded by one number.+ *+ * Written rather than borrowed, and the reason is in the frame times. The+ * reference's own bar morphs by crossfading two separately composed bars and+ * matching their parts with shared elements: at rest it is cheaper than what+ * this app had before — 10% dropped frames against 15% — but every fold costs+ * 40% and a 90th percentile of 90ms, because for the length of the animation+ * both bars exist, both are measured, and both carry their own glass.+ *+ * This is the same shape with none of that. There is one bar. Folding is a+ * single [Animatable] that every part reads *inside* a `layout` or+ * `graphicsLayer` block, never in composition — so a frame of the fold costs a+ * measure and a draw, and nothing recomposes at all. It is the discipline the+ * player sheet and the playlist header in this app already use, applied to the+ * one thing that was still doing it the expensive way.+ *+ * What the parts do, from 0 (open) to 1 (folded):+ *+ * - the capsule keeps the tab you are on and gives up the other, its width+ * travelling from two tabs to one square;+ * - the labels fade in the first third of the travel, because they are the part+ * that stops being readable first;+ * - what is playing rises out of its own row and settles between the capsule and+ * the search button, which is where the row has just made space for it.+ */+@Composable+fun SquareBottomBar(+ /** 0 open, 1 folded. Held by the caller so the scroll can drive it. */+ fold: State<Float>,+ /** The tab the capsule keeps when it folds. */+ selectedIndex: Int,+ accessoryVisible: Boolean,+ modifier: Modifier = Modifier,+ tabSpacing: Dp = 8.dp,+ /** The row's own height when open, and when folded. */+ openHeight: Dp = 64.dp,+ foldedHeight: Dp = 52.dp,+ accessoryHeight: Dp = 48.dp,+ /** The gap between what is playing and the row below it, while open. */+ accessoryGap: Dp = 8.dp,+ capsule: @Composable (fold: () -> Float) -> Unit,+ standalone: @Composable () -> Unit,+ accessory: @Composable () -> Unit,+) {+ val density = LocalDensity.current+ val spacingPx = with(density) { tabSpacing.roundToPx() }+ val openPx = with(density) { openHeight.roundToPx() }+ val foldedPx = with(density) { foldedHeight.roundToPx() }+ val accessoryPx = with(density) { accessoryHeight.roundToPx() }+ val gapPx = with(density) { accessoryGap.roundToPx() }++ val foldState = rememberUpdatedState(fold.value)+ val readFold = remember { { foldState.value } }++ Layout(+ modifier = modifier,+ content = {+ Box(Modifier.layoutId(SlotCapsule)) { capsule(readFold) }+ Box(Modifier.layoutId(SlotStandalone)) { standalone() }+ if (accessoryVisible) {+ Box(Modifier.layoutId(SlotAccessory)) { accessory() }+ }+ },+ ) { measurables, constraints ->+ // Read here, in measure. Nothing above this line depends on the fold, so+ // nothing above this line runs again when it changes.+ val f = readFold()+ val width = constraints.maxWidth+ val rowHeight = lerp(openPx, foldedPx, f)++ val standaloneNode = measurables.first { it.layoutId == SlotStandalone }+ val standalonePlaceable = standaloneNode.measure(+ Constraints.fixed(rowHeight, rowHeight),+ )++ val capsuleNode = measurables.first { it.layoutId == SlotCapsule }+ // Open, the capsule is what is left of the row; folded, it is one+ // square. The tabs inside it are laid out by the caller against the+ // same number, so the two agree without either measuring the other.+ val capsuleOpen = width - standalonePlaceable.width - spacingPx+ val capsuleWidth = lerp(capsuleOpen, rowHeight, f)+ val capsulePlaceable = capsuleNode.measure(Constraints.fixed(capsuleWidth, rowHeight))++ val accessoryNode = measurables.firstOrNull { it.layoutId == SlotAccessory }+ // Open, it spans the whole width above the row. Folded, it is the middle+ // of the row: what the capsule gave up, less the two gaps.+ val accessoryOpenWidth = width+ val accessoryFoldedWidth =+ (width - capsuleWidth - standalonePlaceable.width - spacingPx * 2).coerceAtLeast(0)+ val accessoryWidth = lerp(accessoryOpenWidth, accessoryFoldedWidth, f)+ val accessoryPlaceable = accessoryNode?.measure(+ Constraints.fixed(accessoryWidth.coerceAtLeast(1), lerp(accessoryPx, rowHeight, f)),+ )++ val totalHeight = if (accessoryPlaceable != null) {+ lerp(accessoryPx + gapPx + openPx, foldedPx, f)+ } else {+ rowHeight+ }++ layout(width, totalHeight) {+ val rowTop = totalHeight - rowHeight+ capsulePlaceable.place(0, rowTop)+ standalonePlaceable.place(width - standalonePlaceable.width, rowTop)+ accessoryPlaceable?.place(+ // Open: hard left, above the row. Folded: in the middle of it.+ x = lerp(0, capsuleWidth + spacingPx, f),+ y = lerp(0, rowTop, f),+ )+ }+ }+}++/**+ * Drives [SquareBottomBar] from whatever is being scrolled.+ *+ * Folds on the way down and unfolds at the top of the page, and nowhere else:+ * scrolling back up is a request for what is further up, not for the bar, and a+ * bar that returns on the first upward pixel spends the whole page opening and+ * closing. What is left over at the end of an upward gesture is the part the+ * list could not use — which means there is no more page above it.+ */+@Composable+fun rememberBarFold(): BarFold {+ val fold = remember { Animatable(0f) }+ val target = remember { androidx.compose.runtime.mutableFloatStateOf(0f) }++ LaunchedEffect(fold) {+ androidx.compose.runtime.snapshotFlow { target.floatValue }.collect { wanted ->+ fold.animateTo(+ wanted,+ // Soft, and slightly slower closing than opening would be: this+ // is a bar settling, not a switch.+ spring(dampingRatio = 0.9f, stiffness = Spring.StiffnessMediumLow),+ )+ }+ }++ return remember(fold) { BarFold(fold.asState(), target) }+}++/** The fold, and the connection that moves it. */+class BarFold(+ val progress: State<Float>,+ private val target: androidx.compose.runtime.MutableFloatState,+) {+ val folded: Boolean get() = target.floatValue > 0.5f++ val connection = object : androidx.compose.ui.input.nestedscroll.NestedScrollConnection {+ override fun onPreScroll(+ available: androidx.compose.ui.geometry.Offset,+ source: androidx.compose.ui.input.nestedscroll.NestedScrollSource,+ ): androidx.compose.ui.geometry.Offset {+ // The finger only. A fling settles by reporting deltas of its own,+ // and the last of those points the other way.+ if (source == androidx.compose.ui.input.nestedscroll.NestedScrollSource.UserInput &&+ available.y < -6f+ ) {+ target.floatValue = 1f+ }+ return androidx.compose.ui.geometry.Offset.Zero+ }++ override fun onPostScroll(+ consumed: androidx.compose.ui.geometry.Offset,+ available: androidx.compose.ui.geometry.Offset,+ source: androidx.compose.ui.input.nestedscroll.NestedScrollSource,+ ): androidx.compose.ui.geometry.Offset {+ if (available.y > 0.5f) target.floatValue = 0f+ return androidx.compose.ui.geometry.Offset.Zero+ }+ }++ fun unfold() {+ target.floatValue = 0f+ }+}++private const val SlotCapsule = "capsule"+private const val SlotStandalone = "standalone"+private const val SlotAccessory = "accessory"++/** Fades a part out over the first [until] of the fold, and back in over it. */+fun Modifier.foldAlpha(fold: () -> Float, until: Float = 0.45f): Modifier =+ graphicsLayer { alpha = (1f - fold() / until).coerceIn(0f, 1f) }++/** Rounds a dp interpolation the way the layout above does, for callers. */+internal fun lerpPx(start: Int, stop: Int, fraction: Float): Int =+ (start + (stop - start) * fraction).roundToInt()++/**+ * The tabs inside the capsule, and the puck under the one you are on.+ *+ * Same rule as the bar around it: the fold is read in `layout` and in+ * `drawBehind`, so folding costs a measure and a draw. The unselected tab keeps+ * its place in the list and loses its width — which is what makes the capsule+ * close *onto* the tab you are on rather than sliding it sideways.+ */+@Composable+fun FoldingTabs(+ fold: () -> Float,+ selectedIndex: Int,+ padding: Dp = 4.dp,+ puckColor: androidx.compose.ui.graphics.Color,+ /** What the indicator refracts; null draws no indicator at all. */+ backdrop: dev.lelonio.square.ui.glass.backdrop.Backdrop? = null,+ /** How many tabs the capsule holds; the puck needs it before measuring. */+ tabCount: Int = 2,+ /** Called when the indicator is dragged onto another tab and let go. */+ onTabSelected: (Int) -> Unit = {},+ modifier: Modifier = Modifier,+ tabs: @Composable () -> Unit,+) {+ val density = LocalDensity.current+ val paddingPx = with(density) { padding.roundToPx() }+ val selected = rememberUpdatedState(selectedIndex)++ // Where the puck is, as a tab index that can sit between two of them.+ //+ // The old bar had one and this did not, and a bar without it says which tab+ // you are on with a tint alone — which is the difference between a control+ // that answers at a glance and one that has to be read. Animated as its own+ // value and drawn behind the tabs, so moving it costs a draw: nothing here+ // recomposes when it travels.+ val puck = remember { Animatable(selectedIndex.toFloat()) }+ var dragging by remember { mutableStateOf(false) }+ LaunchedEffect(selectedIndex) {+ if (!dragging) {+ puck.animateTo(+ selectedIndex.toFloat(),+ spring(dampingRatio = 0.8f, stiffness = Spring.StiffnessMediumLow),+ )+ }+ }++ // The indicator can be dragged between tabs, as the old bar's could.+ //+ // It is the one gesture a capsule of tabs invites — the puck looks like+ // something you could push — and losing it was the difference between a bar+ // that answers the hand and one that only answers taps. Released, it settles+ // on the nearest tab and that tab is the one opened, so a drag that changes+ // its mind halfway costs nothing.+ val scope = rememberCoroutineScope()+ val dragScope = rememberUpdatedState(onTabSelected)+ val puckDrag = if (tabCount > 1) {+ Modifier.pointerInput(tabCount) {+ detectHorizontalDragGestures(+ onDragStart = { dragging = true },+ onDragCancel = {+ dragging = false+ scope.launch { puck.animateTo(selected.value.toFloat()) }+ },+ onHorizontalDrag = { _, amount ->+ val step = (size.width - paddingPx * 2) / tabCount.toFloat()+ scope.launch {+ puck.snapTo(+ (puck.value + amount / step).coerceIn(0f, (tabCount - 1).toFloat()),+ )+ }+ },+ onDragEnd = {+ dragging = false+ val nearest = puck.value.roundToInt().coerceIn(0, tabCount - 1)+ scope.launch {+ puck.animateTo(+ nearest.toFloat(),+ spring(dampingRatio = 0.8f, stiffness = Spring.StiffnessMediumLow),+ )+ }+ if (nearest != selected.value) dragScope.value(nearest)+ },+ )+ }+ } else {+ Modifier+ }++ Box(modifier) {+ // The indicator, as the old bar drew it: a pane of glass over the tabs+ // with its own lens and rim, not a painted rectangle. Placed and sized+ // in a `graphicsLayer` and a `layout`, so it travels and grows without+ // recomposing anything.+ if (backdrop != null) {+ Box(+ Modifier+ .puckLayout(+ fold = fold,+ position = { puck.value },+ count = tabCount,+ paddingPx = paddingPx,+ )+ .then(puckDrag)+ .drawBackdrop(+ backdrop = backdrop,+ shape = { ContinuousCapsule() },+ effects = { lens(10f.dp.toPx(), 14f.dp.toPx(), chromaticAberration = true) },+ highlight = { Highlight.Default.copy(alpha = 0.35f) },+ shadow = { Shadow(alpha = 0.35f) },+ onDrawSurface = { drawRect(puckColor) },+ ),+ )+ }++ Layout(+ modifier = Modifier,+ content = tabs,+ ) { measurables, constraints ->+ val f = fold()+ val width = constraints.maxWidth+ val height = constraints.maxHeight+ val inner = width - paddingPx * 2+ val count = measurables.size+ val open = if (count > 0) inner / count else inner+ val chosen = selected.value.coerceIn(0, (count - 1).coerceAtLeast(0))++ val widths = IntArray(count) { index ->+ lerp(open, if (index == chosen) inner else 0, f)+ }+ val placeables = measurables.mapIndexed { index, measurable ->+ measurable.measure(+ Constraints.fixed(+ widths[index].coerceAtLeast(1),+ (height - paddingPx * 2).coerceAtLeast(1),+ ),+ )+ }++ layout(width, height) {+ var x = paddingPx+ placeables.forEachIndexed { index, placeable ->+ placeable.place(x, paddingPx)+ x += widths[index]+ }+ }+ }+ }+}++/**+ * Where the indicator sits: one tab wide and sliding while the bar is open, the+ * whole capsule once it has folded — so the tab you are left with *is* the+ * indicator rather than sitting inside it.+ */+private fun Modifier.puckLayout(+ fold: () -> Float,+ position: () -> Float,+ count: Int,+ paddingPx: Int,+): Modifier = layout { measurable, constraints ->+ val f = fold()+ val width = constraints.maxWidth+ val height = constraints.maxHeight+ val inner = width - paddingPx * 2+ val open = if (count > 0) inner / count else inner+ val puckWidth = lerp(open, inner, f)+ val placeable = measurable.measure(+ Constraints.fixed(+ puckWidth.coerceAtLeast(1),+ (height - paddingPx * 2).coerceAtLeast(1),+ ),+ )+ layout(width, height) {+ val x = paddingPx + lerp((position() * open).roundToInt(), 0, f)+ placeable.place(x, paddingPx)+ }+}++/** Lets a part give up its height as the bar folds; see [foldAlpha]. */+fun Modifier.foldHeight(fold: () -> Float, until: Float = 0.45f): Modifier =+ layout { measurable, constraints ->+ val placeable = measurable.measure(constraints)+ val keep = (1f - fold() / until).coerceIn(0f, 1f)+ val height = (placeable.height * keep).roundToInt()+ layout(placeable.width, height) { placeable.place(0, 0) }+ }diff --git a/app/src/main/java/dev/lelonio/square/ui/glass/backdrop/DrawBackdropModifier.kt b/app/src/main/java/dev/lelonio/square/ui/glass/backdrop/DrawBackdropModifier.ktindex 323bae0..4bab6b9 100644--- a/app/src/main/java/dev/lelonio/square/ui/glass/backdrop/DrawBackdropModifier.kt+++ b/app/src/main/java/dev/lelonio/square/ui/glass/backdrop/DrawBackdropModifier.kt@@ -30,6 +30,7 @@ import androidx.compose.ui.layout.Measurableimport androidx.compose.ui.layout.MeasureResultimport androidx.compose.ui.layout.MeasureScopeimport androidx.compose.ui.node.DrawModifierNode+import androidx.compose.ui.node.invalidateDrawimport androidx.compose.ui.node.GlobalPositionAwareModifierNodeimport androidx.compose.ui.node.LayoutModifierNodeimport androidx.compose.ui.node.ModifierNodeElement@@ -40,6 +41,7 @@ import androidx.compose.ui.platform.InspectorInfoimport androidx.compose.ui.unit.Constraintsimport androidx.compose.ui.unit.IntOffsetimport androidx.compose.ui.unit.IntSize+import androidx.compose.ui.util.fastCoerceInimport androidx.compose.ui.unit.toSizeimport dev.lelonio.square.ui.glass.backdrop.backdrops.LayerBackdropimport dev.lelonio.square.ui.glass.backdrop.highlight.Highlight@@ -54,6 +56,24 @@ import dev.lelonio.square.ui.glass.backdrop.shadow.ShadowElementprivate val DefaultHighlight = { Highlight.Default }private val DefaultShadow = { Shadow.Default }private val DefaultOnDrawBackdrop: DrawScope.(DrawScope.() -> Unit) -> Unit = { it() }+/**+ * How long the fresh capture takes to replace the held one.+ *+ * Long enough to read as the reflection settling rather than as a cut, short+ * enough that it is over before anyone looks for it. Two layers are alive for+ * this window and one of them is released at the end of it.+ */+private const val HandoverMillis = 180f++/**+ * How stale a held capture is allowed to get before it is taken again.+ *+ * Three or four recordings across a fold rather than one per frame, and a+ * reflection that is never more than this far behind — which is close enough+ * that the moment it catches up is not an event.+ */+private const val HoldRefreshMillis = 110f+private val NeverFrozen: () -> Boolean = { false }/** Defensive cap on a loop-bucket pool's size — see [DrawBackdropNode.drawBucketedLayer]. */@@ -83,7 +103,8 @@ fun Modifier.drawPlainBackdrop(// transition: 9 frames at a 250-450ms median with the nav bar's glass on,// versus 77 frames at 42ms with it off. The bar is moving and heavily// blurred for those ~300ms, so reusing the previous capture is not visible.- frozen: () -> Boolean = NeverFrozen+ frozen: () -> Boolean = NeverFrozen,+ heldWhileMoving: () -> Boolean = NeverFrozen): Modifier {val shapeProvider = ShapeProvider(shape)return this@@ -107,6 +128,7 @@ fun Modifier.drawPlainBackdrop(onDrawFront = onDrawFront,backdropScale = backdropScale.coerceIn(0.05f, 1f),frozen = frozen,+ heldWhileMoving = heldWhileMoving,loopBucket = null))@@ -140,6 +162,8 @@ fun Modifier.drawBackdrop(// versus 77 frames at 42ms with it off. The bar is moving and heavily// blurred for those ~300ms, so reusing the previous capture is not visible.frozen: () -> Boolean = NeverFrozen,+ /** See the use site: hold the capture even while this surface moves. */+ heldWhileMoving: () -> Boolean = NeverFrozen,// When set, this surface caches one recorded+effect-processed layer PER// bucket returned here instead of a single reused layer, and replays a// bucket's cached layer on repeat instead of re-recording. Meant for a@@ -202,6 +226,7 @@ fun Modifier.drawBackdrop(onDrawFront = onDrawFront,backdropScale = backdropScale.coerceIn(0.05f, 1f),frozen = frozen,+ heldWhileMoving = heldWhileMoving,loopBucket = loopBucket))@@ -219,6 +244,7 @@ private class DrawBackdropElement(val onDrawFront: (DrawScope.() -> Unit)?,val backdropScale: Float,val frozen: () -> Boolean,+ val heldWhileMoving: () -> Boolean,val loopBucket: (() -> Int)?) : ModifierNodeElement<DrawBackdropNode>() {@@ -235,6 +261,7 @@ private class DrawBackdropElement(onDrawFront = onDrawFront,backdropScale = backdropScale,frozen = frozen,+ heldWhileMoving = heldWhileMoving,loopBucket = loopBucket)}@@ -268,6 +295,7 @@ private class DrawBackdropElement(node.onDrawFront = onDrawFrontnode.backdropScale = backdropScalenode.frozen = frozen+ node.heldWhileMoving = heldWhileMovingif (node.loopBucket !== loopBucket) {// A different bucket function (or losing/gaining one) invalidates// whatever's pooled — the old buckets no longer mean anything under@@ -345,6 +373,7 @@ private class DrawBackdropNode(var onDrawFront: (DrawScope.() -> Unit)?,var backdropScale: Float,var frozen: () -> Boolean,+ var heldWhileMoving: () -> Boolean,var loopBucket: (() -> Int)?) : LayoutModifierNode, DrawModifierNode, GlobalPositionAwareModifierNode, ObserverModifierNode, Modifier.Node() {@@ -447,6 +476,16 @@ private class DrawBackdropNode(* resizing) invalidate every pooled bucket, since they were all captured at* the old size/offset.*/+ /** True on the previous frame; see the hand-over in [drawBackdropLayer]. */+ private var wasHolding = false++ /** When this surface last recorded, for the refresh while held. */+ private var lastRecordedAt = 0L++ /** The capture being faded out of, and when that fade began. */+ private var handoverLayer: GraphicsLayer? = null+ private var handoverStartedAt = 0L+private fun DrawScope.drawBucketedLayer(bucket: Int): Boolean {val padding = paddingval scale = backdropScale@@ -531,11 +570,68 @@ private class DrawBackdropNode(// old recording is reflecting somewhere else on the screen: the mini// player sliding as the bar folds showed the page from the position// it used to be in, not the one under it.- val needsRecord = if (frozen() && hasRecording && !geometryChanged) {- false- } else {- (geometryChanged || versionChanged) && !versionChangeIsElsewhere+ //+ // Unless the caller says it is worth it anyway, which is what+ // [heldWhileMoving] is for: a surface in the middle of changing+ // shape re-records on every frame of the animation, which is the+ // most expensive thing this app does at the busiest moment it does+ // it. A reflection that lags for the length of a morph is not+ // something anyone can see; the alternative, taking the glass away+ // and putting it back, is.+ // Held, but not indefinitely.+ //+ // A capture frozen for the whole of an animation is a reflection+ // that has to be corrected at the end of it, and that correction is+ // a visible jump however it is dressed up: the fade meant to cover+ // it belongs to a node the animation is about to throw away, since+ // the bar's two states are two different pieces of composition. The+ // answer is not to let it drift that far. While held, the capture is+ // still refreshed a few times a second, which costs three or four+ // recordings across a fold instead of one per frame, and leaves+ // nothing at the end big enough to see.+ val now = System.nanoTime()+ val heldLongEnough = (now - lastRecordedAt) / 1_000_000f >= HoldRefreshMillis+ val holding = frozen() &&+ hasRecording &&+ !heldLongEnough &&+ (!geometryChanged || heldWhileMoving())++ // Coming out of a hold always takes a fresh capture, whether or not+ // anything else says to.+ //+ // Without this the held reflection could last for good: the page+ // only bumps its version when it redraws, and a page that has+ // stopped scrolling does not redraw. So the surface sat on the+ // capture it took before the scroll — the bar showing a piece of+ // artwork that had long since moved on, in a screen where nothing+ // was moving to correct it.+ val refreshAfterHold = wasHolding && !holding+ val needsRecord = when {+ holding -> false+ refreshAfterHold -> true+ else -> (geometryChanged || versionChanged) && !versionChangeIsElsewhere+ }++ // The first capture after a hold is a jump: the reflection has been+ // still through a whole animation and then, in one frame, it is+ // right again. That cut is more noticeable than the staleness it+ // corrects, so the old capture is kept and the new one is brought up+ // over it. Only after a hold — an ordinary re-record during a scroll+ // is a small change from the frame before it, and crossing them+ // would only cost an extra layer for nothing.+ val endingHold = refreshAfterHold+ if (endingHold) {+ val keeper = handoverLayer+ ?: requireGraphicsContext().createGraphicsLayer().also { handoverLayer = it }+ // A copy of what is on screen right now, to fade out from.+ recordLayer(this@DrawBackdropNode, keeper, size = recordedBackdropSize) {+ drawLayer(layer)+ }+ keeper.renderEffect = null+ handoverStartedAt = System.nanoTime()}+ wasHolding = holding+if (needsRecord) {recordLayer(this@DrawBackdropNode,@@ -546,20 +642,52 @@ private class DrawBackdropNode(recordedBackdropVersion = versionrecordedBackdropOffset = offsetrecordedBackdropSize = recordSize+ lastRecordedAt = now}layer.topLeft =if (padding != 0f) IntOffset(-padding.toInt(), -padding.toInt())else IntOffset.Zero- if (scale != 1f) {- // Vendored addition: stretch the low resolution layer back over the- // full surface; the blur in the effect chain masks the upscaling.- scale(1f / scale, pivot = Offset.Zero) {- drawLayer(layer)++ val handover = handoverLayer+ val fade = if (handover != null && handoverStartedAt != 0L) {+ val elapsed = (System.nanoTime() - handoverStartedAt) / 1_000_000f+ (elapsed / HandoverMillis).fastCoerceIn(0f, 1f)+ } else {+ 1f+ }++ fun DrawScope.paint(target: GraphicsLayer) {+ if (scale != 1f) {+ // Vendored addition: stretch the low resolution layer back over+ // the full surface; the blur in the chain masks the upscaling.+ scale(1f / scale, pivot = Offset.Zero) {+ drawLayer(target)+ }+ } else {+ drawLayer(target)}+ }++ if (fade < 1f && handover != null) {+ handover.topLeft = layer.topLeft+ handover.alpha = 1f - fade+ paint(handover)+ layer.alpha = fade+ paint(layer)+ layer.alpha = 1f+ // Nothing else is changing, so the next frame has to be asked+ // for or the fade would stop on its first step.} else {- drawLayer(layer)+ if (handover != null) {+ requireGraphicsContext().releaseGraphicsLayer(handover)+ handoverLayer = null+ handoverStartedAt = 0L+ }+ paint(layer)}+needsRecord} else {false@@ -652,6 +780,10 @@ private class DrawBackdropNode(graphicsContext.releaseGraphicsLayer(layer)graphicsLayer = null}+ handoverLayer?.let { layer ->+ graphicsContext.releaseGraphicsLayer(layer)+ handoverLayer = null+ }clearLoopPool()effectScope.reset()diff --git a/app/src/main/java/dev/lelonio/square/ui/glass/floatingtabbar/FloatingTabBar.kt b/app/src/main/java/dev/lelonio/square/ui/glass/floatingtabbar/FloatingTabBar.ktindex 00d4a35..af485bd 100644--- a/app/src/main/java/dev/lelonio/square/ui/glass/floatingtabbar/FloatingTabBar.kt+++ b/app/src/main/java/dev/lelonio/square/ui/glass/floatingtabbar/FloatingTabBar.kt@@ -272,6 +272,18 @@ fun FloatingTabBar(val frozenWhileAnimating = remember(transition) {{ transition.currentState != transition.targetState }}+ // LOCAL CHANGE: and the same fact where the caller can see it.+ //+ // The composition local only reaches surfaces built inside this+ // composable — the selection puck. The bar's own pane and the pill above+ // it are built by the caller and passed in as `tabBarContentModifier`,+ // so reading the local there gave the default, "never frozen", and the+ // one moment the freeze exists for was the one it never covered. The+ // scroll connection is the object both sides already share.+ val morphing = transition.currentState != transition.targetState+ LaunchedEffect(scrollConnection, morphing) {+ scrollConnection.morphing = morphing+ }CompositionLocalProvider(LocalTabBarBackdropFrozen provides frozenWhileAnimating) {// Always applied: `gooey` is a no-op at radius 0 (no offscreen layer,// no filter), so there is nothing to gate on and nothing to recompose.@@ -371,6 +383,14 @@ class FloatingTabBarScrollConnection(*/var locked by mutableStateOf(false)+ /**+ * LOCAL CHANGE: true for exactly the frames the bar is changing shape.+ *+ * Published here rather than through a composition local because the bar's+ * glass is applied by whoever uses the bar, from outside its composition.+ */+ var morphing by mutableStateOf(false)+/*** LOCAL CHANGE: true while the page under the bar is moving.*diff --git a/app/src/main/java/dev/lelonio/square/ui/settings/GlassSettings.kt b/app/src/main/java/dev/lelonio/square/ui/settings/GlassSettings.ktindex e4ceae8..d2985b3 100644--- a/app/src/main/java/dev/lelonio/square/ui/settings/GlassSettings.kt+++ b/app/src/main/java/dev/lelonio/square/ui/settings/GlassSettings.kt@@ -261,6 +261,7 @@ fun GlassSection(backdrop: Backdrop) {onChange = store::setPlayerEnabled,)+SettingsDivider()GlassSwitch(label = stringResource(R.string.bar_folds),