Skip to content

Unofficial YouTube Music / Spotify Premium client for Android, built in Liquid Glass. Audio effects, Spotify Connect, listening history, 8 languages. Rust core on librespot.

Ask about an update the way the app asks about everything else

Lelonioc8bf184189d4
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 13f6180..10a5b88 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -8,6 +8,7 @@
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<!-- Required from API 33 for the playback notification to be visible. -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<!--
@@ -96,6 +97,15 @@
</intent-filter>
</activity>
+ <!--
+ The download of a new version, which has to be allowed to finish:
+ see UpdateService.
+ -->
+ <service
+ android:name=".update.UpdateService"
+ android:exported="false"
+ android:foregroundServiceType="dataSync" />
+
<service
android:name=".playback.PlaybackService"
android:exported="true"
diff --git a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt b/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
index f61a865..bacd4e0 100644
--- a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
@@ -121,7 +121,7 @@ import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.unit.IntOffset
import dev.lelonio.square.ui.components.TrackSheet
import dev.lelonio.square.ui.components.TrackSheetAction
-import dev.lelonio.square.ui.components.UpdateDialog
+import dev.lelonio.square.ui.components.UpdateSheet
import dev.lelonio.square.update.Updater
import dev.lelonio.square.ui.library.openLink
import com.adamglin.phosphoricons.regular.Download
@@ -252,8 +252,6 @@ fun SquareApp(
val playlist by viewModel.playlist.collectAsStateWithLifecycle()
val context = LocalContext.current
- UpdatePrompt()
-
// The session as it was left, so the player has something to draw before
// the media controller connects. Read once, off the saved queue.
val seed = remember(context) { savedPlaybackSeed(context) }
@@ -894,8 +892,13 @@ fun SquareApp(
// it refracts was not being recorded while it was the only
// thing open, so the glass had nothing behind it and the sheet
// came up as a transparent panel with no depth at all.
+ // The update sheet is glass like the rest, so it has to be
+ // counted here too: the layer below is only recorded while
+ // something is reading it, and a panel over an unrecorded
+ // backdrop has nothing to refract — it came out flat.
+ var updateOpen by remember { mutableStateOf(false) }
val sheetsOpen = trackMenu != null || addToPlaylist.open || playlistMenu != null ||
- sharedTrack != null || friendsOpen
+ sharedTrack != null || friendsOpen || updateOpen
// Kept on a little past the close, or the layer would stop
// being recorded while the sheet is still fading out over it
// and the panel would go black on the way down.
@@ -1932,6 +1935,11 @@ fun SquareApp(
// Over everything, including the player: the same sheet is
// opened from a track row in the library and from the plus in
// the player, and it is one sheet with one state.
+ // Here rather than at the top of the app: a sheet made of
+ // glass has to be drawn where there is a layer to refract, and
+ // this is the layer the other sheets use.
+ UpdatePrompt(overlayBackdrop, onOpenChange = { updateOpen = it })
+
AddToPlaylistSheet(
state = addToPlaylist,
backdrop = overlayBackdrop,
@@ -2333,7 +2341,10 @@ private fun Player.cycleRepeatMode() {
* asked for, so a failure is not something to tell them about.
*/
@Composable
-private fun UpdatePrompt() {
+private fun UpdatePrompt(
+ backdrop: dev.lelonio.square.ui.glass.backdrop.Backdrop,
+ onOpenChange: (Boolean) -> Unit,
+) {
val context = LocalContext.current
val updater = remember(context) {
(context.applicationContext as dev.lelonio.square.SquareApplication).updater
@@ -2352,10 +2363,16 @@ private fun UpdatePrompt() {
runCatching { updater.check() }
}
- val available = state as? Updater.State.Available ?: return
- // Already offered, and turned down. The version is remembered rather than
- // a flag, so the next release is news again.
- if (available.version == prefs.skippedUpdate()) return
+ // Held while the download runs: the state moves on from Available the
+ // moment the fetch starts, and the sheet has to stay to show it happening.
+ var offered by remember { mutableStateOf<Updater.State.Available?>(null) }
+ var dismissed by remember { mutableStateOf(false) }
+ (state as? Updater.State.Available)?.let { found ->
+ // Already offered, and turned down. The version is remembered rather
+ // than a flag, so the next release is news again.
+ if (found.version != prefs.skippedUpdate()) offered = found
+ }
+ val available = offered ?: return
// Held across the trip to the system settings, so granting the permission
// continues the install instead of dropping it.
@@ -2365,24 +2382,39 @@ private fun UpdatePrompt() {
) {
val update = pending ?: return@rememberLauncherForActivityResult
pending = null
- scope.launch { if (updater.canInstall()) updater.install(update) }
+ if (updater.canInstall()) updater.install(update)
}
- UpdateDialog(
+ val downloading = state is Updater.State.Downloading
+ val installing = state is Updater.State.Installing
+
+ // What the layer below is recorded for; see [sheetsOpen].
+ val showing = !dismissed && !installing
+ LaunchedEffect(showing) { onOpenChange(showing) }
+ DisposableEffect(Unit) { onDispose { onOpenChange(false) } }
+
+ UpdateSheet(
version = available.version,
size = available.bytes.takeIf { it > 0 }?.let { "%.1f MB".format(it / 1_000_000.0) },
+ notes = available.notes,
+ progress = (state as? Updater.State.Downloading)?.progress,
+ downloading = downloading,
onInstall = {
- prefs.setSkippedUpdate(available.version)
- scope.launch {
- if (updater.canInstall()) {
- updater.install(available)
- } else {
- pending = available
- permission.launch(updater.permissionIntent())
- }
+ if (updater.canInstall()) {
+ updater.install(available)
+ } else {
+ pending = available
+ permission.launch(updater.permissionIntent())
}
},
- onDismiss = { prefs.setSkippedUpdate(available.version) },
+ onDismiss = {
+ prefs.setSkippedUpdate(available.version)
+ dismissed = true
+ },
+ backdrop = backdrop,
+ // Gone once the system installer has it: what happens next is Android's
+ // dialog, and two things asking about the same install is one too many.
+ visible = showing,
)
}
diff --git a/app/src/main/java/dev/lelonio/square/ui/components/UpdateDialog.kt b/app/src/main/java/dev/lelonio/square/ui/components/UpdateDialog.kt
deleted file mode 100644
index d441c5f..0000000
--- a/app/src/main/java/dev/lelonio/square/ui/components/UpdateDialog.kt
+++ /dev/null
@@ -1,89 +0,0 @@
-package dev.lelonio.square.ui.components
-
-import androidx.compose.foundation.background
-import androidx.compose.foundation.clickable
-import androidx.compose.foundation.layout.Arrangement
-import androidx.compose.foundation.layout.Column
-import androidx.compose.foundation.layout.Row
-import androidx.compose.foundation.layout.fillMaxWidth
-import androidx.compose.foundation.layout.padding
-import androidx.compose.foundation.shape.RoundedCornerShape
-import androidx.compose.material3.MaterialTheme
-import androidx.compose.material3.Text
-import androidx.compose.runtime.Composable
-import androidx.compose.ui.Alignment
-import androidx.compose.ui.Modifier
-import androidx.compose.ui.draw.clip
-import androidx.compose.ui.graphics.Color
-import androidx.compose.ui.res.stringResource
-import androidx.compose.ui.unit.dp
-import androidx.compose.ui.window.Dialog
-import dev.lelonio.square.R
-import dev.lelonio.square.ui.theme.Ink
-import dev.lelonio.square.ui.theme.InkDim
-
-/**
- * Says that a newer build exists, and offers to fetch it.
- *
- * An install that no store can reach only learns about a release if something
- * says so, and the settings row that used to be the only way to find out is a
- * place nobody visits to check. Shown once per release: dismissing it records
- * the version, so the same news is never delivered twice.
- */
-@Composable
-fun UpdateDialog(
- version: String,
- /** Download size, already formatted, or null when the release did not say. */
- size: String?,
- onInstall: () -> Unit,
- onDismiss: () -> Unit,
-) {
- Dialog(onDismissRequest = onDismiss) {
- Column(
- Modifier
- .fillMaxWidth()
- .menuSkin(RoundedCornerShape(24.dp))
- .padding(22.dp),
- ) {
- Text(
- stringResource(R.string.update_available, version),
- style = MaterialTheme.typography.titleMedium,
- color = Ink,
- )
- Text(
- if (size != null) {
- stringResource(R.string.update_prompt_size, size)
- } else {
- stringResource(R.string.update_prompt)
- },
- style = MaterialTheme.typography.bodyMedium,
- color = InkDim,
- modifier = Modifier.padding(top = 6.dp),
- )
-
- Row(
- Modifier
- .padding(top = 20.dp)
- .fillMaxWidth(),
- horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End),
- ) {
- DialogAction(stringResource(R.string.update_later), InkDim, onDismiss)
- DialogAction(stringResource(R.string.update_install), Ink, onInstall)
- }
- }
- }
-}
-
-@Composable
-private fun DialogAction(label: String, color: Color, onClick: () -> Unit) {
- Text(
- label,
- style = MaterialTheme.typography.bodyLarge,
- color = color,
- modifier = Modifier
- .clip(RoundedCornerShape(50))
- .clickable(onClick = onClick)
- .padding(horizontal = 16.dp, vertical = 8.dp),
- )
-}
-
diff --git a/app/src/main/java/dev/lelonio/square/ui/components/UpdateSheet.kt b/app/src/main/java/dev/lelonio/square/ui/components/UpdateSheet.kt
new file mode 100644
index 0000000..fb9d774
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/ui/components/UpdateSheet.kt
@@ -0,0 +1,305 @@
+package dev.lelonio.square.ui.components
+
+import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.core.tween
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.scaleIn
+import androidx.compose.animation.scaleOut
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.LinearProgressIndicator
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.remember
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.AnnotatedString
+import androidx.compose.ui.text.SpanStyle
+import androidx.compose.ui.text.buildAnnotatedString
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.withStyle
+import androidx.compose.ui.unit.dp
+import dev.lelonio.square.R
+import dev.lelonio.square.ui.glass.LocalGlassEffectConfig
+import dev.lelonio.square.ui.glass.backdrop.Backdrop
+import dev.lelonio.square.ui.glass.liquidGlass
+import dev.lelonio.square.ui.glass.pressable
+import dev.lelonio.square.ui.glass.shapes.ContinuousCapsule
+import dev.lelonio.square.ui.glass.shapes.ContinuousRoundedRectangle
+import dev.lelonio.square.ui.player.GlassInk
+import dev.lelonio.square.ui.player.GlassInkDim
+
+/**
+ * What a new version is, and what it changes, before anything is downloaded.
+ *
+ * Drawn inside the app's own window rather than as a system dialog, which is
+ * the difference between glass and a grey card: a dialog is its own window and
+ * cannot sample what is behind it, so it can only imitate the material. This
+ * sits over the page it dims, refracts it, and is the same pane as the rest of
+ * the app.
+ *
+ * The shape of it is the library's own dialog — the wide corner, the dim, the
+ * two capsule actions of equal weight — but the material is the app's, read
+ * from the same setting the bottom bar reads. A dialog with glass of its own
+ * would be the one surface here that ignores what the user asked for.
+ *
+ * It shows what the release says about itself. An update is a thing to agree
+ * to, and "there is a new version" is not enough to agree to: what changed is
+ * the whole of the argument for pressing the button.
+ */
+@Composable
+fun UpdateSheet(
+ version: String,
+ /** Download size, already formatted, or null when the release did not say. */
+ size: String?,
+ /** What the release says about itself, as written on the releases page. */
+ notes: String,
+ /** 0f..1f while fetching, null when the length is unknown; absent at rest. */
+ progress: Float?,
+ downloading: Boolean,
+ onInstall: () -> Unit,
+ onDismiss: () -> Unit,
+ backdrop: Backdrop,
+ visible: Boolean,
+) {
+ AnimatedVisibility(
+ visible = visible,
+ enter = fadeIn(tween(220)),
+ exit = fadeOut(tween(180)),
+ ) {
+ Box(
+ Modifier
+ .fillMaxSize()
+ // The page goes back rather than away: turned down, and left
+ // where it was. Blurring it too was tried and read as the app
+ // going out of focus rather than as one panel coming forward —
+ // the sharp panel over the dark page says it on its own.
+ // Behind what this holds, not over it: drawn after the
+ // content it would dim the panel too, which is the one thing on
+ // the screen that has to stay lit.
+ .background(DIM)
+ // Swallows what lands outside the panel. Dismissing by tapping
+ // there is deliberately not offered while a download is
+ // running, since there would be nothing to come back to.
+ .pressable(onClick = { if (!downloading) onDismiss() }),
+ contentAlignment = Alignment.Center,
+ ) {
+ AnimatedVisibility(
+ visible = visible,
+ enter = scaleIn(tween(240), initialScale = 0.92f) + fadeIn(tween(240)),
+ exit = scaleOut(tween(160), targetScale = 0.94f) + fadeOut(tween(160)),
+ ) {
+ Column(
+ Modifier
+ .padding(horizontal = 28.dp)
+ .fillMaxWidth()
+ .liquidGlass(
+ // Every parameter of the material comes from here:
+ // the frost, the edge, the film, the colour. A
+ // dialog is not a special surface, and one with
+ // glass of its own would be the only thing in the
+ // app that ignores what the user set.
+ config = LocalGlassEffectConfig.current,
+ shape = PANEL,
+ ownBackdrop = backdrop,
+ // Not the material: what makes the panel the lit
+ // thing on a screen that has gone dark. It samples
+ // the page as it was — sharp, and never dimmed —
+ // so it already comes through brighter than its
+ // own surroundings, and this lifts it the rest of
+ // the way.
+ onDrawTint = { drawRect(LIFT) },
+ )
+ // Nothing behind the panel takes a tap through it.
+ .pressable(onClick = {}),
+ ) {
+ Text(
+ stringResource(R.string.update_available, version),
+ style = MaterialTheme.typography.titleLarge,
+ fontWeight = FontWeight.Medium,
+ color = GlassInk,
+ modifier = Modifier.padding(start = 28.dp, end = 28.dp, top = 24.dp),
+ )
+ size?.let {
+ Text(
+ it,
+ style = MaterialTheme.typography.bodySmall,
+ color = GlassInkDim,
+ modifier = Modifier.padding(start = 28.dp, end = 28.dp, top = 4.dp),
+ )
+ }
+
+ if (notes.isNotBlank()) {
+ val text = remember(notes) { releaseNotes(notes) }
+ Text(
+ text,
+ style = MaterialTheme.typography.bodyMedium,
+ color = GlassInkDim,
+ modifier = Modifier
+ .padding(start = 24.dp, end = 24.dp, top = 14.dp)
+ // Capped and scrolled: a release with a long
+ // list of changes should not push its own
+ // buttons off the screen.
+ .heightIn(max = 240.dp)
+ .verticalScroll(rememberScrollState()),
+ )
+ }
+
+ if (downloading) {
+ LinearProgressIndicator(
+ progress = { progress ?: 0f },
+ color = MaterialTheme.colorScheme.primary,
+ trackColor = GlassInk.copy(alpha = 0.18f),
+ modifier = Modifier
+ .padding(start = 24.dp, end = 24.dp, top = 24.dp)
+ .fillMaxWidth(),
+ )
+ Text(
+ progress
+ ?.let { "${(it * 100).toInt()}%" }
+ ?: stringResource(R.string.update_downloading),
+ style = MaterialTheme.typography.bodySmall,
+ color = GlassInkDim,
+ modifier = Modifier.padding(
+ start = 24.dp,
+ end = 24.dp,
+ top = 10.dp,
+ bottom = 24.dp,
+ ),
+ )
+ } else {
+ Row(
+ Modifier
+ .padding(start = 24.dp, end = 24.dp, top = 20.dp, bottom = 24.dp)
+ .fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(16.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ DialogAction(
+ label = stringResource(R.string.later),
+ container = FILM.copy(alpha = 0.2f),
+ content = GlassInk,
+ onClick = onDismiss,
+ modifier = Modifier.weight(1f),
+ )
+ DialogAction(
+ label = stringResource(R.string.update_now),
+ container = MaterialTheme.colorScheme.primary,
+ content = Color.White,
+ onClick = onInstall,
+ modifier = Modifier.weight(1f),
+ )
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun DialogAction(
+ label: String,
+ container: Color,
+ content: Color,
+ onClick: () -> Unit,
+ modifier: Modifier = Modifier,
+) {
+ Box(
+ modifier
+ .clip(ContinuousCapsule)
+ .background(container)
+ .pressable(onClick, pressedScale = 0.96f)
+ .height(48.dp),
+ contentAlignment = Alignment.Center,
+ ) {
+ Text(
+ label,
+ style = MaterialTheme.typography.bodyLarge,
+ fontWeight = FontWeight.Medium,
+ color = content,
+ )
+ }
+}
+
+/**
+ * The release notes as prose rather than as their source.
+ *
+ * They are written as Markdown, because that is what the releases page renders,
+ * and read here as `## New` and `- **Lyrics**` — the punctuation of a format
+ * nobody is reading in. This is not a Markdown renderer: it handles the four
+ * things release notes are actually written with, and leaves anything else as
+ * the text it already is.
+ */
+private fun releaseNotes(source: String): AnnotatedString = buildAnnotatedString {
+ val lines = source.trim().lines()
+ lines.forEachIndexed { index, raw ->
+ val line = raw.trim()
+ if (line.isEmpty()) {
+ // One blank line between paragraphs, never a run of them.
+ if (index > 0 && lines[index - 1].isNotBlank() && index < lines.lastIndex) {
+ append('\n')
+ }
+ return@forEachIndexed
+ }
+ if (index > 0) append('\n')
+
+ val heading = line.startsWith("#")
+ val bullet = line.startsWith("- ") || line.startsWith("* ")
+ val body = line
+ .removePrefix("#").removePrefix("#").removePrefix("#").trimStart()
+ .let { if (bullet) it.drop(2) else it }
+
+ if (bullet) append("• ")
+ if (heading) {
+ withStyle(SpanStyle(color = GlassInk, fontWeight = FontWeight.SemiBold)) {
+ appendInline(body)
+ }
+ } else {
+ appendInline(body)
+ }
+ }
+}
+
+/** Bold spans and code ticks, which is all the emphasis the notes ever use. */
+private fun AnnotatedString.Builder.appendInline(text: String) {
+ var rest = text
+ while (true) {
+ val open = rest.indexOf("**")
+ if (open < 0) break
+ val close = rest.indexOf("**", open + 2)
+ if (close < 0) break
+ append(rest.substring(0, open).replace("`", ""))
+ withStyle(SpanStyle(color = GlassInk, fontWeight = FontWeight.SemiBold)) {
+ append(rest.substring(open + 2, close).replace("`", ""))
+ }
+ rest = rest.substring(close + 2)
+ }
+ append(rest.replace("`", ""))
+}
+
+/** What is left of the page behind. */
+private val DIM = Color(0xFF121212).copy(alpha = 0.62f)
+
+/** The panel's own light, over the glass. */
+private val LIFT = Color.White.copy(alpha = 0.08f)
+
+/** What the resting action is filled with, over the panel's own glass. */
+private val FILM = Color(0xFF121212).copy(alpha = 0.4f)
+
+private val PANEL = ContinuousRoundedRectangle(48.dp)
diff --git a/app/src/main/java/dev/lelonio/square/ui/glass/backdrop/BackdropEffectScope.kt b/app/src/main/java/dev/lelonio/square/ui/glass/backdrop/BackdropEffectScope.kt
index 681652a..82d0636 100644
--- a/app/src/main/java/dev/lelonio/square/ui/glass/backdrop/BackdropEffectScope.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/glass/backdrop/BackdropEffectScope.kt
@@ -24,6 +24,17 @@ sealed interface BackdropEffectScope : Density, RuntimeShaderCache {
val shape: Shape
+ /**
+ * Vendored addition: the fraction of the surface's real size the effects are
+ * working on, when the backdrop was recorded at a reduced resolution.
+ *
+ * [size] is already reported in that reduced grid. Anything an effect
+ * derives from [shape] is not — a corner radius in dp converts at the full
+ * density — so a shape's geometry has to be brought into the same grid by
+ * hand. See the lens.
+ */
+ val contentScale: Float
+
var padding: Float
var renderEffect: RenderEffect?
@@ -36,6 +47,7 @@ internal abstract class BackdropEffectScopeImpl : BackdropEffectScope, RuntimeSh
override var size: Size = Size.Unspecified
override var layoutDirection: LayoutDirection = LayoutDirection.Ltr
override var padding: Float = 0f
+ override var contentScale: Float = 1f
override var renderEffect: RenderEffect? = null
private val runtimeShaderCache = RuntimeShaderCacheImpl()
@@ -56,13 +68,15 @@ internal abstract class BackdropEffectScopeImpl : BackdropEffectScope, RuntimeSh
val changed = newDensity != density ||
newFontScale != fontScale ||
newSize != size ||
- newLayoutDirection != layoutDirection
+ newLayoutDirection != layoutDirection ||
+ contentScale != this.contentScale
if (changed) {
density = newDensity
fontScale = newFontScale
size = newSize
layoutDirection = newLayoutDirection
+ this.contentScale = contentScale
}
return changed
diff --git a/app/src/main/java/dev/lelonio/square/ui/glass/backdrop/effects/Lens.kt b/app/src/main/java/dev/lelonio/square/ui/glass/backdrop/effects/Lens.kt
index db805bf..8bc4a37 100644
--- a/app/src/main/java/dev/lelonio/square/ui/glass/backdrop/effects/Lens.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/glass/backdrop/effects/Lens.kt
@@ -70,6 +70,13 @@ fun BackdropEffectScope.lens(
// Vendored change: support for io.github.kyant0:shapes' RoundedRectangularShape was
// dropped so the vendored sources have no external dependency; this app only passes
// CornerBasedShape here.
+// Vendored change: radii are brought into the recorded layer's pixel grid.
+//
+// [size] arrives already multiplied by the resolution the backdrop was recorded
+// at, but a corner in dp converts at the full density, so a half-resolution
+// layer refracted as if the corners were twice as round — invisible on a
+// capsule, whose radius is clamped to half its height anyway, and plain on a
+// large panel with a fixed corner: the arc swept an inch into the middle of it.
private val BackdropEffectScope.cornerRadii: FloatArray?
get() = when (val shape = shape) {
is AbsoluteRoundedCornerShape -> {
@@ -80,10 +87,10 @@ private val BackdropEffectScope.cornerRadii: FloatArray?
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)
+ (topLeft * contentScale).fastCoerceAtMost(maxRadius),
+ (topRight * contentScale).fastCoerceAtMost(maxRadius),
+ (bottomRight * contentScale).fastCoerceAtMost(maxRadius),
+ (bottomLeft * contentScale).fastCoerceAtMost(maxRadius)
)
}
@@ -104,10 +111,10 @@ private val BackdropEffectScope.cornerRadii: FloatArray?
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)
+ (topLeft * contentScale).fastCoerceAtMost(maxRadius),
+ (topRight * contentScale).fastCoerceAtMost(maxRadius),
+ (bottomRight * contentScale).fastCoerceAtMost(maxRadius),
+ (bottomLeft * contentScale).fastCoerceAtMost(maxRadius)
)
}
diff --git a/app/src/main/java/dev/lelonio/square/update/UpdateService.kt b/app/src/main/java/dev/lelonio/square/update/UpdateService.kt
new file mode 100644
index 0000000..e61e8b3
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/update/UpdateService.kt
@@ -0,0 +1,118 @@
+package dev.lelonio.square.update
+
+import android.app.Notification
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.app.Service
+import android.content.Context
+import android.content.Intent
+import android.os.Build
+import android.os.IBinder
+import dev.lelonio.square.R
+import dev.lelonio.square.SquareApplication
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.launch
+
+/**
+ * Fetches the new version while the listener does something else.
+ *
+ * A twenty-megabyte download tied to a screen is a download that dies when the
+ * screen does: the old one lived in the composition, so leaving the app — or
+ * merely opening the player — took it with it, and there was nothing to say how
+ * far it had got. A foreground service is what Android gives an app for work it
+ * must be allowed to finish, and the notification is not decoration but the
+ * price of the permission: it says what is happening and how far along it is.
+ *
+ * The service does the fetching and nothing else. Installing is still the
+ * system's dialog and still cannot be skipped, which is the right shape for a
+ * thing that replaces the app.
+ */
+class UpdateService : Service() {
+
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+ private var running = false
+
+ override fun onBind(intent: Intent?): IBinder? = null
+
+ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
+ val url = intent?.getStringExtra(EXTRA_URL)
+ val version = intent?.getStringExtra(EXTRA_VERSION).orEmpty()
+ val bytes = intent?.getLongExtra(EXTRA_BYTES, 0L) ?: 0L
+
+ if (url.isNullOrEmpty() || running) return START_NOT_STICKY
+ running = true
+
+ channel()
+ startForeground(NOTIFICATION_ID, notification(version, null))
+
+ val updater = (applicationContext as SquareApplication).updater
+ scope.launch {
+ updater.fetchAndInstall(url, version, bytes) { progress ->
+ notify(version, progress)
+ }
+ stopSelf()
+ }
+ return START_NOT_STICKY
+ }
+
+ override fun onDestroy() {
+ scope.cancel()
+ super.onDestroy()
+ }
+
+ private fun notify(version: String, progress: Float?) {
+ manager().notify(NOTIFICATION_ID, notification(version, progress))
+ }
+
+ private fun notification(version: String, progress: Float?): Notification {
+ val percent = progress?.let { (it * 100).toInt().coerceIn(0, 100) }
+ return Notification.Builder(this, CHANNEL_ID)
+ .setContentTitle(getString(R.string.update_downloading))
+ .setContentText(
+ listOfNotNull(version.takeIf { it.isNotEmpty() }, percent?.let { "$it%" })
+ .joinToString(" · "),
+ )
+ .setSmallIcon(android.R.drawable.stat_sys_download)
+ .setOngoing(true)
+ // Indeterminate until the server says how much there is to fetch.
+ .setProgress(100, percent ?: 0, percent == null)
+ .build()
+ }
+
+ private fun channel() {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
+ val channel = NotificationChannel(
+ CHANNEL_ID,
+ getString(R.string.update_channel),
+ // Low: this is a progress bar, not news. It belongs in the shade
+ // without a sound or a heads-up card over what the listener is
+ // doing.
+ NotificationManager.IMPORTANCE_LOW,
+ )
+ manager().createNotificationChannel(channel)
+ }
+
+ private fun manager(): NotificationManager =
+ getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
+
+ companion object {
+ private const val CHANNEL_ID = "square_update"
+ private const val NOTIFICATION_ID = 4_201
+
+ private const val EXTRA_URL = "url"
+ private const val EXTRA_VERSION = "version"
+ private const val EXTRA_BYTES = "bytes"
+
+ /** Starts the download; safe to call twice, the second is ignored. */
+ fun start(context: Context, update: Updater.State.Available) {
+ val intent = Intent(context, UpdateService::class.java)
+ .putExtra(EXTRA_URL, update.url)
+ .putExtra(EXTRA_VERSION, update.version)
+ .putExtra(EXTRA_BYTES, update.bytes)
+ context.startForegroundService(intent)
+ }
+ }
+}
diff --git a/app/src/main/java/dev/lelonio/square/update/Updater.kt b/app/src/main/java/dev/lelonio/square/update/Updater.kt
index 6863548..5061cb3 100644
--- a/app/src/main/java/dev/lelonio/square/update/Updater.kt
+++ b/app/src/main/java/dev/lelonio/square/update/Updater.kt
@@ -40,6 +40,9 @@ class Updater(context: Context) {
private val json = Json { ignoreUnknownKeys = true }
private val client = OkHttpClient()
+ /** The last whole percent handed to the notification; see [download]. */
+ private var lastReported = -1
+
private val _state = MutableStateFlow<State>(State.Idle)
val state: StateFlow<State> = _state.asStateFlow()
@@ -47,7 +50,21 @@ class Updater(context: Context) {
data object Idle : State
data object Checking : State
data object UpToDate : State
- data class Available(val version: String, val url: String, val bytes: Long) : State
+ data class Available(
+ val version: String,
+ val url: String,
+ val bytes: Long,
+ /**
+ * What the release says about itself, as written on the releases
+ * page.
+ *
+ * An update is a thing being asked for rather than announced, and
+ * "there is a new version" is not enough to answer with. Empty when
+ * the release carries no text, which is a release worth showing
+ * anyway.
+ */
+ val notes: String = "",
+ ) : State
/** 0f..1f, or null while the server sends no length to measure against. */
data class Downloading(val progress: Float?) : State
/** Handed to the system installer; the dialog is Android's, not ours. */
@@ -76,7 +93,8 @@ class Updater(context: Context) {
_state.value = State.UpToDate
return
}
- _state.value = State.Available(result.version, result.url, result.bytes)
+ _state.value =
+ State.Available(result.version, result.url, result.bytes, result.notes)
}
/**
@@ -101,7 +119,12 @@ class Updater(context: Context) {
return null
}
- private data class Release(val version: String, val url: String, val bytes: Long)
+ private data class Release(
+ val version: String,
+ val url: String,
+ val bytes: Long,
+ val notes: String,
+ )
private fun latestRelease(): Release? {
val request = Request.Builder()
@@ -120,7 +143,8 @@ class Updater(context: Context) {
?: return null
val url = asset["browser_download_url"]?.jsonPrimitive?.content ?: return null
val size = asset["size"]?.jsonPrimitive?.content?.toLongOrNull() ?: 0L
- return Release(tag, url, size)
+ val notes = body["body"]?.jsonPrimitive?.content.orEmpty().trim()
+ return Release(tag, url, size, notes)
}
}
@@ -132,19 +156,43 @@ class Updater(context: Context) {
* replace itself unattended is one the user has to trust rather more than
* this one asks to be trusted.
*/
- suspend fun install(update: State.Available) {
+ fun install(update: State.Available) {
if (!canInstall()) {
_state.value = State.Failed(REASON_PERMISSION)
return
}
+ // Handed to a service rather than done here.
+ //
+ // This used to run in whatever scope the screen gave it, so leaving the
+ // app — or merely opening the player — cancelled the download halfway
+ // with nothing to show for it. See UpdateService.
+ _state.value = State.Downloading(null)
+ UpdateService.start(app, update)
+ }
+ /**
+ * The download itself, called by the service that is allowed to finish it.
+ *
+ * @param onProgress told as often as the bytes arrive, so the notification
+ * can say how far along it is; null while the server sends no length.
+ */
+ suspend fun fetchAndInstall(
+ url: String,
+ version: String,
+ bytes: Long,
+ onProgress: (Float?) -> Unit,
+ ) {
+ val update = State.Available(version, url, bytes)
_state.value = State.Downloading(null)
- val apk = runCatching { withContext(Dispatchers.IO) { download(update) } }
- .getOrElse {
- android.util.Log.w(TAG, "download failed: $it")
- _state.value = State.Failed(it.message ?: "download")
- return
- }
+ onProgress(null)
+
+ val apk = runCatching {
+ withContext(Dispatchers.IO) { download(update, onProgress) }
+ }.getOrElse {
+ android.util.Log.w(TAG, "download failed: $it")
+ _state.value = State.Failed(it.message ?: "download")
+ return
+ }
runCatching { withContext(Dispatchers.IO) { commit(apk) } }
.onSuccess { _state.value = State.Installing }
@@ -155,12 +203,13 @@ class Updater(context: Context) {
}
}
- private fun download(update: State.Available): File {
+ private fun download(update: State.Available, onProgress: (Float?) -> Unit): File {
// cacheDir, not filesDir: once the installer has read it the file is
// dead weight, and twenty megabytes is worth letting the system reclaim
// if the install never happens.
val target = File(app.cacheDir, "update.apk")
target.delete()
+ lastReported = -1
val request = Request.Builder().url(update.url).build()
client.newCall(request).execute().use { response ->
@@ -178,7 +227,17 @@ class Updater(context: Context) {
output.write(buffer, 0, read)
written += read
if (total > 0) {
- _state.value = State.Downloading(written.toFloat() / total)
+ val progress = written.toFloat() / total
+ _state.value = State.Downloading(progress)
+ // Rounded to a percent before it is reported: a
+ // notification redrawn on every sixty-fourth
+ // kilobyte is three hundred redraws for a number
+ // that changed a hundred times.
+ val step = (progress * 100).toInt()
+ if (step != lastReported) {
+ lastReported = step
+ onProgress(progress)
+ }
}
}
}
diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml
index 0109cac..1a1c0c0 100644
--- a/app/src/main/res/values-de/strings.xml
+++ b/app/src/main/res/values-de/strings.xml
@@ -227,7 +227,9 @@
<string name="update_checking">Wird geprüft…</string>
<string name="update_none">Aktuell</string>
<string name="update_available">%1$s verfügbar</string>
+ <string name="update_now">Aktualisieren</string>
<string name="update_downloading">Wird geladen…</string>
+ <string name="update_channel">App-Updates</string>
<string name="update_installing">Warte auf deine Bestätigung</string>
<string name="update_needs_permission">Installation erlauben — tippen</string>
<string name="update_failed">Gerade nicht — zum Wiederholen tippen</string>
diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml
index 901e7d3..e484ca1 100644
--- a/app/src/main/res/values-es/strings.xml
+++ b/app/src/main/res/values-es/strings.xml
@@ -227,7 +227,9 @@
<string name="update_checking">Comprobando…</string>
<string name="update_none">Ya está al día</string>
<string name="update_available">%1$s disponible</string>
+ <string name="update_now">Actualizar</string>
<string name="update_downloading">Descargando…</string>
+ <string name="update_channel">Actualizaciones</string>
<string name="update_installing">Esperando tu confirmación</string>
<string name="update_needs_permission">Permite la instalación — toca</string>
<string name="update_failed">Ahora no — toca para reintentar</string>
diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml
index e12d778..13e9325 100644
--- a/app/src/main/res/values-fr/strings.xml
+++ b/app/src/main/res/values-fr/strings.xml
@@ -227,7 +227,9 @@
<string name="update_checking">Vérification…</string>
<string name="update_none">À jour</string>
<string name="update_available">%1$s disponible</string>
+ <string name="update_now">Mettre à jour</string>
<string name="update_downloading">Téléchargement…</string>
+ <string name="update_channel">Mises à jour</string>
<string name="update_installing">En attente de votre confirmation</string>
<string name="update_needs_permission">Autorisez l\'installation — touchez</string>
<string name="update_failed">Pas maintenant — touchez pour réessayer</string>
diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml
index 9fcaf0b..755cc3e 100644
--- a/app/src/main/res/values-hi/strings.xml
+++ b/app/src/main/res/values-hi/strings.xml
@@ -242,7 +242,9 @@
<string name="update_checking">देखा जा रहा है…</string>
<string name="update_none">अप टू डेट</string>
<string name="update_available">%1$s उपलब्ध</string>
+ <string name="update_now">अपडेट करें</string>
<string name="update_downloading">डाउनलोड हो रहा है…</string>
+ <string name="update_channel">ऐप अपडेट</string>
<string name="update_installing">आपकी पुष्टि का इंतज़ार</string>
<string name="update_needs_permission">इंस्टॉल की अनुमति दें — टैप करें</string>
<string name="update_failed">अभी नहीं — फिर कोशिश के लिए टैप करें</string>
diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml
index df73c96..687870b 100644
--- a/app/src/main/res/values-it/strings.xml
+++ b/app/src/main/res/values-it/strings.xml
@@ -228,7 +228,9 @@
<string name="update_checking">Controllo…</string>
<string name="update_none">Già aggiornata</string>
<string name="update_available">%1$s disponibile</string>
+ <string name="update_now">Aggiorna</string>
<string name="update_downloading">Scarico…</string>
+ <string name="update_channel">Aggiornamenti dell\'app</string>
<string name="update_installing">Aspetto la tua conferma</string>
<string name="update_needs_permission">Consenti l\'installazione — tocca</string>
<string name="update_failed">Non adesso — tocca per riprovare</string>
diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml
index f88ac16..077d0fa 100644
--- a/app/src/main/res/values-pt/strings.xml
+++ b/app/src/main/res/values-pt/strings.xml
@@ -227,7 +227,9 @@
<string name="update_checking">A verificar…</string>
<string name="update_none">Já atualizada</string>
<string name="update_available">%1$s disponível</string>
+ <string name="update_now">Atualizar</string>
<string name="update_downloading">A transferir…</string>
+ <string name="update_channel">Atualizações</string>
<string name="update_installing">À espera da tua confirmação</string>
<string name="update_needs_permission">Permite a instalação — toca</string>
<string name="update_failed">Agora não — toca para tentar de novo</string>
diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml
index 4347457..bbf6a02 100644
--- a/app/src/main/res/values-tr/strings.xml
+++ b/app/src/main/res/values-tr/strings.xml
@@ -242,7 +242,9 @@
<string name="update_checking">Denetleniyor…</string>
<string name="update_none">Güncel</string>
<string name="update_available">%1$s hazır</string>
+ <string name="update_now">Güncelle</string>
<string name="update_downloading">İndiriliyor…</string>
+ <string name="update_channel">Uygulama güncellemeleri</string>
<string name="update_installing">Onayın bekleniyor</string>
<string name="update_needs_permission">Yüklemeye izin ver — dokun</string>
<string name="update_failed">Şimdi olmadı — yeniden denemek için dokun</string>
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 335a1a5..9904135 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -248,7 +248,9 @@
<string name="update_checking">Checking…</string>
<string name="update_none">Up to date</string>
<string name="update_available">%1$s available</string>
+ <string name="update_now">Update</string>
<string name="update_downloading">Downloading…</string>
+ <string name="update_channel">App updates</string>
<string name="update_installing">Waiting for you to confirm</string>
<string name="update_needs_permission">Allow installing — tap</string>
<string name="update_failed">Not now — tap to retry</string>