Add a shuffle toggle to Android Auto's player

Also give the Shuffle row in track lists an icon, so it no longer
reads as a heading.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
yuriy.pandClaude Opus 5.5 committed 2026-11-04 15:20:14 +06:00
1 parent 9ff5c92650
commit 82a31acd8c
4 files changed
+50 -15

No files matched your search

@@ -1,11 +1,13 @@
// Covers for Android Auto. Auto loads browse artwork only from content:// URIs, so each https // Covers for Android Auto. Auto loads browse artwork only from content:// URIs, so each https
// cover is fetched once into the cache and served from there. // cover is fetched once into the cache and served from there, as are the app's own icons.
package it.panov.musyx.mobile package it.panov.musyx.mobile
import android.content.ContentProvider import android.content.ContentProvider
import android.content.ContentValues import android.content.ContentValues
import android.content.Context import android.content.Context
import android.database.Cursor import android.database.Cursor
import android.graphics.Bitmap
import android.graphics.Canvas
import android.net.Uri import android.net.Uri
import android.os.ParcelFileDescriptor import android.os.ParcelFileDescriptor
import it.panov.musyx.data.Downloads import it.panov.musyx.data.Downloads
@@ -21,6 +23,7 @@ class ArtworkProvider : ContentProvider() {
override fun onCreate(): Boolean = true override fun onCreate(): Boolean = true
override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor { override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor {
if (uri.lastPathSegment == SHUFFLE) return ParcelFileDescriptor.open(icon(R.drawable.ic_shuffle, "shuffle"), ParcelFileDescriptor.MODE_READ_ONLY)
val url = uri.lastPathSegment?.let(Uri::parse) ?: throw FileNotFoundException("$uri") val url = uri.lastPathSegment?.let(Uri::parse) ?: throw FileNotFoundException("$uri")
// Exported for the car, so it fetches only Yandex covers, never an arbitrary URL. // Exported for the car, so it fetches only Yandex covers, never an arbitrary URL.
val host = url.host.orEmpty() val host = url.host.orEmpty()
@@ -50,7 +53,23 @@ class ArtworkProvider : ContentProvider() {
} }
} }
override fun getType(uri: Uri): String = "image/jpeg" /** A white icon on clear ground, drawn once into the cache as a PNG; the car can't draw vectors. */
private fun icon(id: Int, name: String): File {
val file = File(requireNotNull(context).cacheDir, "artwork/icon-$name.png")
if (file.exists()) return file
val drawable = requireNotNull(requireNotNull(context).getDrawable(id))
val bitmap = Bitmap.createBitmap(ICON_PX, ICON_PX, Bitmap.Config.ARGB_8888)
val inset = ICON_PX / 5
drawable.setBounds(inset, inset, ICON_PX - inset, ICON_PX - inset)
drawable.draw(Canvas(bitmap))
file.parentFile?.mkdirs()
val part = File(file.path + ".part")
part.outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
if (!part.renameTo(file)) throw FileNotFoundException(file.path)
return file
}
override fun getType(uri: Uri): String = if (uri.lastPathSegment == SHUFFLE) "image/png" else "image/jpeg"
override fun query(uri: Uri, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor? = null override fun query(uri: Uri, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor? = null
override fun insert(uri: Uri, values: ContentValues?): Uri? = null override fun insert(uri: Uri, values: ContentValues?): Uri? = null
@@ -58,6 +77,10 @@ class ArtworkProvider : ContentProvider() {
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int = 0 override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int = 0
companion object { companion object {
/** The path of the Shuffle row's icon, in place of a cover's URL. */
const val SHUFFLE = "icon:shuffle"
private const val ICON_PX = 192
/** The content URI the car loads `url` from. */ /** The content URI the car loads `url` from. */
fun uri(context: Context, url: String): Uri = fun uri(context: Context, url: String): Uri =
Uri.Builder().scheme("content").authority("${context.packageName}.artwork").appendPath(url).build() Uri.Builder().scheme("content").authority("${context.packageName}.artwork").appendPath(url).build()
@@ -80,9 +80,10 @@ private const val OFFLINE_ALL = "offline"
/** A downloaded album, playlist or Liked tracks, by its [it.panov.musyx.data.OfflineSet] key. */ /** A downloaded album, playlist or Liked tracks, by its [it.panov.musyx.data.OfflineSet] key. */
private const val OFFLINE = "offline:" private const val OFFLINE = "offline:"
// The buttons beside the car's transport: the heart, and "don't recommend". // The buttons beside the car's transport: the heart, "don't recommend", and shuffle.
private val LIKE = SessionCommand("it.panov.musyx.LIKE", Bundle.EMPTY) private val LIKE = SessionCommand("it.panov.musyx.LIKE", Bundle.EMPTY)
private val DISLIKE = SessionCommand("it.panov.musyx.DISLIKE", Bundle.EMPTY) private val DISLIKE = SessionCommand("it.panov.musyx.DISLIKE", Bundle.EMPTY)
private val SHUFFLE_MODE = SessionCommand("it.panov.musyx.SHUFFLE", Bundle.EMPTY)
@OptIn(UnstableApi::class) @OptIn(UnstableApi::class)
class Library(private val context: Context, private val state: AppState, private val scope: CoroutineScope) : class Library(private val context: Context, private val state: AppState, private val scope: CoroutineScope) :
@@ -96,7 +97,7 @@ class Library(private val context: Context, private val state: AppState, private
/** /**
* Has the car reload whenever someone signs in or out, or the app goes offline or back, so * Has the car reload whenever someone signs in or out, or the app goes offline or back, so
* it never keeps showing "Sign in" (or someone else's music, or music it can't reach), and * it never keeps showing "Sign in" (or someone else's music, or music it can't reach), and
* keeps the heart in step with the track. Returns what stops watching. * keeps the heart and shuffle in step with the player. Returns what stops watching.
*/ */
fun watch(session: MediaLibrarySession): () -> Unit { fun watch(session: MediaLibrarySession): () -> Unit {
// snapshotFlow hears about changes through Compose's apply notifications, which only the // snapshotFlow hears about changes through Compose's apply notifications, which only the
@@ -124,8 +125,9 @@ class Library(private val context: Context, private val state: AppState, private
} }
val buttons = scope.launch { val buttons = scope.launch {
snapshotFlow { snapshotFlow {
val track = state.playback.state.track val p = state.playback.state
Triple(track?.id, track?.let { state.liked.contains(it.id) }, track?.let { it.id in state.likes.dislikedTracks }) val track = p.track
listOf(track?.id, track?.let { state.liked.contains(it.id) }, track?.let { it.id in state.likes.dislikedTracks }, p.shuffle, p.waveStation)
} }
.distinctUntilChanged() .distinctUntilChanged()
.collect { session.setMediaButtonPreferences(buttons()) } .collect { session.setMediaButtonPreferences(buttons()) }
@@ -137,7 +139,7 @@ class Library(private val context: Context, private val state: AppState, private
} }
} }
/** Every controller may like and dislike, and starts with the buttons for what's playing. */ /** Every controller may like, dislike and shuffle, and starts with the buttons for what's playing. */
override fun onConnect(session: MediaSession, controller: MediaSession.ControllerInfo): MediaSession.ConnectionResult { override fun onConnect(session: MediaSession, controller: MediaSession.ControllerInfo): MediaSession.ConnectionResult {
// The library commands must stay: without "get root" a car's browser connection is refused. // The library commands must stay: without "get root" a car's browser connection is refused.
val library = if (controller.isTrusted) { val library = if (controller.isTrusted) {
@@ -146,7 +148,7 @@ class Library(private val context: Context, private val state: AppState, private
MediaSession.ConnectionResult.DEFAULT_UNTRUSTED_SESSION_AND_LIBRARY_COMMANDS MediaSession.ConnectionResult.DEFAULT_UNTRUSTED_SESSION_AND_LIBRARY_COMMANDS
} }
return MediaSession.ConnectionResult.AcceptedResultBuilder(session) return MediaSession.ConnectionResult.AcceptedResultBuilder(session)
.setAvailableSessionCommands(library.buildUpon().add(LIKE).add(DISLIKE).build()) .setAvailableSessionCommands(library.buildUpon().add(LIKE).add(DISLIKE).add(SHUFFLE_MODE).build())
.setMediaButtonPreferences(buttons()) .setMediaButtonPreferences(buttons())
.build() .build()
} }
@@ -163,32 +165,38 @@ class Library(private val context: Context, private val state: AppState, private
LIKE.customAction -> state.likeTrack(track, !state.liked.contains(track.id)) LIKE.customAction -> state.likeTrack(track, !state.liked.contains(track.id))
// Disliking the playing track also skips it, as from the app's menu. // Disliking the playing track also skips it, as from the app's menu.
DISLIKE.customAction -> state.dislikeTrack(track, track.id !in state.likes.dislikedTracks) DISLIKE.customAction -> state.dislikeTrack(track, track.id !in state.likes.dislikedTracks)
SHUFFLE_MODE.customAction -> state.playback.toggleShuffle()
else -> return Futures.immediateFuture(SessionResult(SessionError.ERROR_NOT_SUPPORTED)) else -> return Futures.immediateFuture(SessionResult(SessionError.ERROR_NOT_SUPPORTED))
} }
return Futures.immediateFuture(SessionResult(SessionResult.RESULT_SUCCESS)) return Futures.immediateFuture(SessionResult(SessionResult.RESULT_SUCCESS))
} }
/** /**
* The heart and "don't recommend" for what's playing, asked for right after next; previous * The heart, "don't recommend" and shuffle for what's playing, asked for right after next;
* and next keep their slots. Android Auto ignores the slot and puts them at the right edge. * previous and next keep their slots. Android Auto ignores the slot and puts them at the
* Speech has nothing to recommend. * right edge. Speech has nothing to recommend, and a station decides its own order.
*/ */
private fun buttons(): List<CommandButton> { private fun buttons(): List<CommandButton> {
val track = state.playback.state.track ?: return emptyList() val p = state.playback.state
val track = p.track ?: return emptyList()
val liked = state.liked.contains(track.id) val liked = state.liked.contains(track.id)
val heart = CommandButton.Builder(if (liked) CommandButton.ICON_HEART_FILLED else CommandButton.ICON_HEART_UNFILLED) val heart = CommandButton.Builder(if (liked) CommandButton.ICON_HEART_FILLED else CommandButton.ICON_HEART_UNFILLED)
.setDisplayName(context.getString(if (liked) R.string.menu_unlike else R.string.menu_like)) .setDisplayName(context.getString(if (liked) R.string.menu_unlike else R.string.menu_like))
.setSessionCommand(LIKE) .setSessionCommand(LIKE)
.setSlots(CommandButton.SLOT_FORWARD_SECONDARY, CommandButton.SLOT_OVERFLOW) .setSlots(CommandButton.SLOT_FORWARD_SECONDARY, CommandButton.SLOT_OVERFLOW)
.build() .build()
if (track.spoken) return listOf(heart)
val disliked = track.id in state.likes.dislikedTracks val disliked = track.id in state.likes.dislikedTracks
val block = CommandButton.Builder(CommandButton.ICON_BLOCK) val block = if (track.spoken) null else CommandButton.Builder(CommandButton.ICON_BLOCK)
.setDisplayName(context.getString(if (disliked) R.string.menu_undislike else R.string.menu_dislike)) .setDisplayName(context.getString(if (disliked) R.string.menu_undislike else R.string.menu_dislike))
.setSessionCommand(DISLIKE) .setSessionCommand(DISLIKE)
.setSlots(CommandButton.SLOT_FORWARD_SECONDARY, CommandButton.SLOT_OVERFLOW) .setSlots(CommandButton.SLOT_FORWARD_SECONDARY, CommandButton.SLOT_OVERFLOW)
.build() .build()
return listOf(heart, block) val shuffle = if (p.waveStation != null) null else CommandButton.Builder(if (p.shuffle) CommandButton.ICON_SHUFFLE_ON else CommandButton.ICON_SHUFFLE_OFF)
.setDisplayName(context.getString(if (p.shuffle) R.string.action_shuffle_off else R.string.action_shuffle))
.setSessionCommand(SHUFFLE_MODE)
.setSlots(CommandButton.SLOT_FORWARD_SECONDARY, CommandButton.SLOT_OVERFLOW)
.build()
return listOfNotNull(heart, block, shuffle)
} }
override fun onGetLibraryRoot( override fun onGetLibraryRoot(
@@ -418,6 +426,8 @@ class Library(private val context: Context, private val state: AppState, private
.setMediaMetadata( .setMediaMetadata(
MediaMetadata.Builder() MediaMetadata.Builder()
.setTitle(context.getString(R.string.action_shuffle)) .setTitle(context.getString(R.string.action_shuffle))
// Without an icon the row reads as a heading.
.setArtworkUri(ArtworkProvider.uri(context, ArtworkProvider.SHUFFLE))
.setIsBrowsable(false) .setIsBrowsable(false)
.setIsPlayable(true) .setIsPlayable(true)
.setMediaType(MediaMetadata.MEDIA_TYPE_PLAYLIST) .setMediaType(MediaMetadata.MEDIA_TYPE_PLAYLIST)
@@ -25,6 +25,7 @@
<string name="signin_token_placeholder">Вставьте OAuth-токен</string> <string name="signin_token_placeholder">Вставьте OAuth-токен</string>
<string name="action_play">Слушать</string> <string name="action_play">Слушать</string>
<string name="action_shuffle">Вперемешку</string> <string name="action_shuffle">Вперемешку</string>
<string name="action_shuffle_off">Выключить перемешивание</string>
<string name="action_pause">Пауза</string> <string name="action_pause">Пауза</string>
<string name="action_resume">Продолжить</string> <string name="action_resume">Продолжить</string>
<string name="action_try_again">Повторить</string> <string name="action_try_again">Повторить</string>
+1
View File
@@ -26,6 +26,7 @@
<string name="signin_token_placeholder">Paste OAuth token</string> <string name="signin_token_placeholder">Paste OAuth token</string>
<string name="action_play">Play</string> <string name="action_play">Play</string>
<string name="action_shuffle">Shuffle</string> <string name="action_shuffle">Shuffle</string>
<string name="action_shuffle_off">Turn off shuffle</string>
<string name="action_pause">Pause</string> <string name="action_pause">Pause</string>
<string name="action_resume">Resume</string> <string name="action_resume">Resume</string>
<string name="action_try_again">Try again</string> <string name="action_try_again">Try again</string>