all: reformat

This commit is contained in:
Alexander Capehart
2025-12-31 20:39:55 -07:00
parent a69908e986
commit 5cda3b08d4
195 changed files with 2054 additions and 836 deletions
+9 -4
View File
@@ -47,8 +47,10 @@ class Auxio : Application() {
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
@Suppress("KotlinConstantConditions") @Suppress("KotlinConstantConditions")
if (BuildConfig.APPLICATION_ID != "org.oxycblt.auxio" && if (
BuildConfig.APPLICATION_ID != "org.oxycblt.auxio.debug") { BuildConfig.APPLICATION_ID != "org.oxycblt.auxio" &&
BuildConfig.APPLICATION_ID != "org.oxycblt.auxio.debug"
) {
Timber.plant(CopyleftNoticeTree()) Timber.plant(CopyleftNoticeTree())
} else if (BuildConfig.DEBUG) { } else if (BuildConfig.DEBUG) {
Timber.plant(Timber.DebugTree()) Timber.plant(Timber.DebugTree())
@@ -72,8 +74,11 @@ class Auxio : Application() {
.setIcon(IconCompat.createWithResource(this, R.drawable.ic_shortcut_shuffle_24)) .setIcon(IconCompat.createWithResource(this, R.drawable.ic_shortcut_shuffle_24))
.setIntent( .setIntent(
Intent(this, MainActivity::class.java) Intent(this, MainActivity::class.java)
.setAction(INTENT_KEY_SHORTCUT_SHUFFLE)) .setAction(INTENT_KEY_SHORTCUT_SHUFFLE)
.build())) )
.build()
),
)
} }
companion object { companion object {
@@ -94,7 +94,7 @@ class AuxioService :
override fun onGetRoot( override fun onGetRoot(
clientPackageName: String, clientPackageName: String,
clientUid: Int, clientUid: Int,
rootHints: Bundle? rootHints: Bundle?,
): BrowserRoot { ): BrowserRoot {
return musicFragment.getRoot() return musicFragment.getRoot()
} }
@@ -111,7 +111,7 @@ class AuxioService :
override fun onLoadChildren( override fun onLoadChildren(
parentId: String, parentId: String,
result: Result<MutableList<MediaItem>>, result: Result<MutableList<MediaItem>>,
options: Bundle options: Bundle,
) { ) {
val maximumRootChildLimit = getRootChildrenLimit() val maximumRootChildLimit = getRootChildrenLimit()
musicFragment.getChildren(parentId, maximumRootChildLimit, result, options.getPage()) musicFragment.getChildren(parentId, maximumRootChildLimit, result, options.getPage())
@@ -123,7 +123,9 @@ class AuxioService :
private fun getRootChildrenLimit(): Int { private fun getRootChildrenLimit(): Int {
return browserRootHints?.getInt( return browserRootHints?.getInt(
MediaConstants.BROWSER_ROOT_HINTS_KEY_ROOT_CHILDREN_LIMIT, 4) ?: 4 MediaConstants.BROWSER_ROOT_HINTS_KEY_ROOT_CHILDREN_LIMIT,
4,
) ?: 4
} }
private fun Bundle.getPage(): MusicServiceFragment.Page? { private fun Bundle.getPage(): MusicServiceFragment.Page? {
@@ -175,7 +177,7 @@ interface ForegroundListener {
enum class Change { enum class Change {
MEDIA_SESSION, MEDIA_SESSION,
INDEXER INDEXER,
} }
} }
@@ -71,7 +71,8 @@ class MainActivity : AppCompatActivity() {
startService( startService(
Intent(this, AuxioService::class.java) Intent(this, AuxioService::class.java)
.setAction(AuxioService.ACTION_START) .setAction(AuxioService.ACTION_START)
.putExtra(AuxioService.INTENT_KEY_START_ID, IntegerTable.START_ID_ACTIVITY)) .putExtra(AuxioService.INTENT_KEY_START_ID, IntegerTable.START_ID_ACTIVITY)
)
if (!startIntentAction(intent)) { if (!startIntentAction(intent)) {
// No intent action to do, just restore the previously saved state. // No intent action to do, just restore the previously saved state.
@@ -126,7 +126,8 @@ class MainFragment :
sheetBackCallback = sheetBackCallback =
SheetBackPressedCallback( SheetBackPressedCallback(
playbackSheetBehavior = playbackSheetBehavior, playbackSheetBehavior = playbackSheetBehavior,
queueSheetBehavior = queueSheetBehavior) queueSheetBehavior = queueSheetBehavior,
)
val detailBackCallback = val detailBackCallback =
DetailBackPressedCallback(detailModel).also { detailBackCallback = it } DetailBackPressedCallback(detailModel).also { detailBackCallback = it }
val selectionBackCallback = val selectionBackCallback =
@@ -145,9 +146,13 @@ class MainFragment :
// Send meaningful accessibility events for bottom sheets // Send meaningful accessibility events for bottom sheets
ViewCompat.setAccessibilityPaneTitle( ViewCompat.setAccessibilityPaneTitle(
binding.playbackSheet, context.getString(R.string.lbl_playback)) binding.playbackSheet,
context.getString(R.string.lbl_playback),
)
ViewCompat.setAccessibilityPaneTitle( ViewCompat.setAccessibilityPaneTitle(
binding.queueSheet, context.getString(R.string.lbl_queue)) binding.queueSheet,
context.getString(R.string.lbl_queue),
)
if (queueSheetBehavior != null) { if (queueSheetBehavior != null) {
// In portrait mode, set up click listeners on the stacked sheets. // In portrait mode, set up click listeners on the stacked sheets.
@@ -166,7 +171,8 @@ class MainFragment :
ShapeAppearanceModel.builder( ShapeAppearanceModel.builder(
context, context,
MR.style.ShapeAppearance_Material3_Corner_ExtraLarge, MR.style.ShapeAppearance_Material3_Corner_ExtraLarge,
MR.style.ShapeAppearanceOverlay_Material3_Corner_Top) MR.style.ShapeAppearanceOverlay_Material3_Corner_Top,
)
.build() .build()
fillColor = context.getAttrColorCompat(MR.attr.colorSurfaceContainerHigh) fillColor = context.getAttrColorCompat(MR.attr.colorSurfaceContainerHigh)
} }
@@ -194,7 +200,8 @@ class MainFragment :
binding, binding,
homeModel.songList.value, homeModel.songList.value,
homeModel.isFastScrolling.value, homeModel.isFastScrolling.value,
homeModel.currentTabType.value) homeModel.currentTabType.value,
)
// --- VIEWMODEL SETUP --- // --- VIEWMODEL SETUP ---
// This has to be done here instead of the playback panel to make sure that it's prioritized // This has to be done here instead of the playback panel to make sure that it's prioritized
@@ -281,7 +288,8 @@ class MainFragment :
binding, binding,
homeModel.songList.value, homeModel.songList.value,
homeModel.isFastScrolling.value, homeModel.isFastScrolling.value,
homeModel.currentTabType.value) homeModel.currentTabType.value,
)
} }
val playbackOutRatio = 1 - min(playbackRatio * 2, 1f) val playbackOutRatio = 1 - min(playbackRatio * 2, 1f)
@@ -295,7 +303,8 @@ class MainFragment :
binding.mainSheetScrim.alpha = playbackLastStretchRatio binding.mainSheetScrim.alpha = playbackLastStretchRatio
playbackSheetBehavior.sheetBackgroundDrawable.setCornerSize( playbackSheetBehavior.sheetBackgroundDrawable.setCornerSize(
normalCornerSize * (1 - playbackLastStretchRatio)) normalCornerSize * (1 - playbackLastStretchRatio)
)
binding.exploreNavHost.isInvisible = playbackLastStretchRatio == 1f binding.exploreNavHost.isInvisible = playbackLastStretchRatio == 1f
binding.playbackSheet.translationZ = (1 - playbackLastStretchRatio) * elevationNormal binding.playbackSheet.translationZ = (1 - playbackLastStretchRatio) * elevationNormal
@@ -398,13 +407,18 @@ class MainFragment :
requireBinding(), requireBinding(),
homeModel.songList.value, homeModel.songList.value,
homeModel.isFastScrolling.value, homeModel.isFastScrolling.value,
homeModel.currentTabType.value) homeModel.currentTabType.value,
)
} }
private fun updateCurrentTab(tabType: MusicType) { private fun updateCurrentTab(tabType: MusicType) {
val binding = requireBinding() val binding = requireBinding()
updateFabVisibility( updateFabVisibility(
binding, homeModel.songList.value, homeModel.isFastScrolling.value, tabType) binding,
homeModel.songList.value,
homeModel.isFastScrolling.value,
tabType,
)
} }
private fun updateIndexerState(state: IndexingState?) { private fun updateIndexerState(state: IndexingState?) {
@@ -415,7 +429,8 @@ class MainFragment :
binding, binding,
homeModel.songList.value, homeModel.songList.value,
homeModel.isFastScrolling.value, homeModel.isFastScrolling.value,
homeModel.currentTabType.value) homeModel.currentTabType.value,
)
} }
} }
@@ -428,7 +443,7 @@ class MainFragment :
binding: FragmentMainBinding, binding: FragmentMainBinding,
songs: List<Song>, songs: List<Song>,
isFastScrolling: Boolean, isFastScrolling: Boolean,
tabType: MusicType tabType: MusicType,
) { ) {
// If there are no songs, it's likely that the library has not been loaded, so // If there are no songs, it's likely that the library has not been loaded, so
// displaying the shuffle FAB makes no sense. We also don't want the fast scroll // displaying the shuffle FAB makes no sense. We also don't want the fast scroll
@@ -448,15 +463,19 @@ class MainFragment :
object : FloatingActionButton.OnVisibilityChangedListener() { object : FloatingActionButton.OnVisibilityChangedListener() {
override fun onHidden(fab: FloatingActionButton) { override fun onHidden(fab: FloatingActionButton) {
super.onHidden(fab) super.onHidden(fab)
if (shouldHideAllFabs( if (
binding, shouldHideAllFabs(
homeModel.songList.value, binding,
homeModel.isFastScrolling.value)) { homeModel.songList.value,
homeModel.isFastScrolling.value,
)
) {
return return
} }
binding.homeShuffleFab.show() binding.homeShuffleFab.show()
} }
}) }
)
} else { } else {
L.d("Showing immediately") L.d("Showing immediately")
binding.homeShuffleFab.show() binding.homeShuffleFab.show()
@@ -473,15 +492,19 @@ class MainFragment :
object : FloatingActionButton.OnVisibilityChangedListener() { object : FloatingActionButton.OnVisibilityChangedListener() {
override fun onHidden(fab: FloatingActionButton) { override fun onHidden(fab: FloatingActionButton) {
super.onHidden(fab) super.onHidden(fab)
if (shouldHideAllFabs( if (
binding, shouldHideAllFabs(
homeModel.songList.value, binding,
homeModel.isFastScrolling.value)) { homeModel.songList.value,
homeModel.isFastScrolling.value,
)
) {
return return
} }
binding.homeNewPlaylistFab.show() binding.homeNewPlaylistFab.show()
} }
}) }
)
} else { } else {
L.d("Showing immediately") L.d("Showing immediately")
binding.homeNewPlaylistFab.show() binding.homeNewPlaylistFab.show()
@@ -493,7 +516,7 @@ class MainFragment :
private fun shouldHideAllFabs( private fun shouldHideAllFabs(
binding: FragmentMainBinding, binding: FragmentMainBinding,
songs: List<Song>, songs: List<Song>,
isFastScrolling: Boolean isFastScrolling: Boolean,
) = ) =
binding.exploreNavHost.findNavController().currentDestination?.id != R.id.home_fragment || binding.exploreNavHost.findNavController().currentDestination?.id != R.id.home_fragment ||
sheetRising == true || sheetRising == true ||
@@ -579,8 +602,10 @@ class MainFragment :
val queueSheetBehavior = val queueSheetBehavior =
(binding.queueSheet.coordinatorLayoutBehavior ?: return) as QueueBottomSheetBehavior (binding.queueSheet.coordinatorLayoutBehavior ?: return) as QueueBottomSheetBehavior
if (playbackSheetBehavior.state == BackportBottomSheetBehavior.STATE_EXPANDED && if (
queueSheetBehavior.targetState == BackportBottomSheetBehavior.STATE_EXPANDED) { playbackSheetBehavior.state == BackportBottomSheetBehavior.STATE_EXPANDED &&
queueSheetBehavior.targetState == BackportBottomSheetBehavior.STATE_EXPANDED
) {
// Queue sheet and playback sheet is expanded, close the queue sheet so the // Queue sheet and playback sheet is expanded, close the queue sheet so the
// playback panel can shown. // playback panel can shown.
L.d("Collapsing queue sheet") L.d("Collapsing queue sheet")
@@ -608,8 +633,10 @@ class MainFragment :
binding.playbackSheet.coordinatorLayoutBehavior as PlaybackBottomSheetBehavior binding.playbackSheet.coordinatorLayoutBehavior as PlaybackBottomSheetBehavior
val queueSheetBehavior = val queueSheetBehavior =
(binding.queueSheet.coordinatorLayoutBehavior ?: return) as QueueBottomSheetBehavior (binding.queueSheet.coordinatorLayoutBehavior ?: return) as QueueBottomSheetBehavior
if (playbackSheetBehavior.state == BackportBottomSheetBehavior.STATE_EXPANDED && if (
queueSheetBehavior.targetState == BackportBottomSheetBehavior.STATE_COLLAPSED) { playbackSheetBehavior.state == BackportBottomSheetBehavior.STATE_EXPANDED &&
queueSheetBehavior.targetState == BackportBottomSheetBehavior.STATE_COLLAPSED
) {
// Playback sheet is expanded and queue sheet is collapsed, we can expand it. // Playback sheet is expanded and queue sheet is collapsed, we can expand it.
queueSheetBehavior.state = BackportBottomSheetBehavior.STATE_EXPANDED queueSheetBehavior.state = BackportBottomSheetBehavior.STATE_EXPANDED
} }
@@ -658,7 +685,7 @@ class MainFragment :
private class SheetBackPressedCallback( private class SheetBackPressedCallback(
private val playbackSheetBehavior: PlaybackBottomSheetBehavior<*>, private val playbackSheetBehavior: PlaybackBottomSheetBehavior<*>,
private val queueSheetBehavior: QueueBottomSheetBehavior<*>? private val queueSheetBehavior: QueueBottomSheetBehavior<*>?,
) : OnBackPressedCallback(false) { ) : OnBackPressedCallback(false) {
override fun handleOnBackStarted(backEvent: BackEventCompat) { override fun handleOnBackStarted(backEvent: BackEventCompat) {
if (queueSheetShown()) { if (queueSheetShown()) {
@@ -766,6 +793,7 @@ class MainFragment :
FloatingActionButton::class, FloatingActionButton::class,
"hide", "hide",
FloatingActionButton.OnVisibilityChangedListener::class, FloatingActionButton.OnVisibilityChangedListener::class,
Boolean::class) Boolean::class,
)
} }
} }
@@ -76,7 +76,11 @@ class AlbumDetailFragment : DetailFragment<Album, Song>() {
collect(musicModel.playlistDecision.flow, ::handlePlaylistDecision) collect(musicModel.playlistDecision.flow, ::handlePlaylistDecision)
collect(musicModel.playlistMessage.flow, ::handlePlaylistMessage) collect(musicModel.playlistMessage.flow, ::handlePlaylistMessage)
collectImmediately( collectImmediately(
playbackModel.song, playbackModel.parent, playbackModel.isPlaying, ::updatePlayback) playbackModel.song,
playbackModel.parent,
playbackModel.isPlaying,
::updatePlayback,
)
collect(playbackModel.playbackDecision.flow, ::handlePlaybackDecision) collect(playbackModel.playbackDecision.flow, ::handlePlaybackDecision)
} }
@@ -152,7 +156,10 @@ class AlbumDetailFragment : DetailFragment<Album, Song>() {
playbackModel.shuffle(unlikelyToBeNull(detailModel.currentAlbum.value)) playbackModel.shuffle(unlikelyToBeNull(detailModel.currentAlbum.value))
} }
updatePlayback( updatePlayback(
playbackModel.song.value, playbackModel.parent.value, playbackModel.isPlaying.value) playbackModel.song.value,
playbackModel.parent.value,
playbackModel.isPlaying.value,
)
} }
private fun updateList(list: List<Item>) { private fun updateList(list: List<Item>) {
@@ -251,7 +258,8 @@ class AlbumDetailFragment : DetailFragment<Album, Song>() {
is PlaylistDecision.Add -> { is PlaylistDecision.Add -> {
L.d("Adding ${decision.songs.size} songs to a playlist") L.d("Adding ${decision.songs.size} songs to a playlist")
AlbumDetailFragmentDirections.addToPlaylist( AlbumDetailFragmentDirections.addToPlaylist(
decision.songs.map { it.uid }.toTypedArray()) decision.songs.map { it.uid }.toTypedArray()
)
} }
is PlaylistDecision.New, is PlaylistDecision.New,
is PlaylistDecision.Import, is PlaylistDecision.Import,
@@ -270,7 +278,9 @@ class AlbumDetailFragment : DetailFragment<Album, Song>() {
private fun updatePlayback(song: Song?, parent: MusicParent?, isPlaying: Boolean) { private fun updatePlayback(song: Song?, parent: MusicParent?, isPlaying: Boolean) {
albumListAdapter.setPlaying( albumListAdapter.setPlaying(
song.takeIf { parent == detailModel.currentAlbum.value }, isPlaying) song.takeIf { parent == detailModel.currentAlbum.value },
isPlaying,
)
} }
private fun handlePlaybackDecision(decision: PlaybackDecision?) { private fun handlePlaybackDecision(decision: PlaybackDecision?) {
@@ -318,7 +328,7 @@ class AlbumDetailFragment : DetailFragment<Album, Song>() {
viewEnd: Int, viewEnd: Int,
boxStart: Int, boxStart: Int,
boxEnd: Int, boxEnd: Int,
snapPreference: Int snapPreference: Int,
) = ) =
(boxStart + (boxEnd - boxStart) / 2) - (boxStart + (boxEnd - boxStart) / 2) -
(viewStart + (viewEnd - viewStart) / 2) (viewStart + (viewEnd - viewStart) / 2)
@@ -75,7 +75,11 @@ class ArtistDetailFragment : DetailFragment<Artist, Music>() {
collect(musicModel.playlistDecision.flow, ::handlePlaylistDecision) collect(musicModel.playlistDecision.flow, ::handlePlaylistDecision)
collect(musicModel.playlistMessage.flow, ::handlePlaylistMessage) collect(musicModel.playlistMessage.flow, ::handlePlaylistMessage)
collectImmediately( collectImmediately(
playbackModel.song, playbackModel.parent, playbackModel.isPlaying, ::updatePlayback) playbackModel.song,
playbackModel.parent,
playbackModel.isPlaying,
::updatePlayback,
)
collect(playbackModel.playbackDecision.flow, ::handlePlaybackDecision) collect(playbackModel.playbackDecision.flow, ::handlePlaybackDecision)
} }
@@ -138,7 +142,8 @@ class ArtistDetailFragment : DetailFragment<Artist, Music>() {
context.getPlural(R.plurals.fmt_song_count, artist.songs.size) context.getPlural(R.plurals.fmt_song_count, artist.songs.size)
} else { } else {
context.getString(R.string.def_song_count) context.getString(R.string.def_song_count)
}) },
)
if (artist.songs.isNotEmpty()) { if (artist.songs.isNotEmpty()) {
// Information about the artist's genre(s) map to the sub-head text // Information about the artist's genre(s) map to the sub-head text
@@ -178,7 +183,10 @@ class ArtistDetailFragment : DetailFragment<Artist, Music>() {
playbackModel.shuffle(unlikelyToBeNull(detailModel.currentArtist.value)) playbackModel.shuffle(unlikelyToBeNull(detailModel.currentArtist.value))
} }
updatePlayback( updatePlayback(
playbackModel.song.value, playbackModel.parent.value, playbackModel.isPlaying.value) playbackModel.song.value,
playbackModel.parent.value,
playbackModel.isPlaying.value,
)
} }
private fun updateList(list: List<Item>) { private fun updateList(list: List<Item>) {
@@ -274,7 +282,8 @@ class ArtistDetailFragment : DetailFragment<Artist, Music>() {
is PlaylistDecision.Add -> { is PlaylistDecision.Add -> {
L.d("Adding ${decision.songs.size} songs to a playlist") L.d("Adding ${decision.songs.size} songs to a playlist")
ArtistDetailFragmentDirections.addToPlaylist( ArtistDetailFragmentDirections.addToPlaylist(
decision.songs.map { it.uid }.toTypedArray()) decision.songs.map { it.uid }.toTypedArray()
)
} }
is PlaylistDecision.New, is PlaylistDecision.New,
is PlaylistDecision.Import, is PlaylistDecision.Import,
@@ -38,7 +38,7 @@ constructor(context: Context? = null, attrs: AttributeSet? = null) :
override fun onInterceptTouchEvent( override fun onInterceptTouchEvent(
parent: CoordinatorLayout, parent: CoordinatorLayout,
child: AppBarLayout, child: AppBarLayout,
ev: MotionEvent ev: MotionEvent,
): Boolean { ): Boolean {
val consumed = super.onInterceptTouchEvent(parent, child, ev) val consumed = super.onInterceptTouchEvent(parent, child, ev)
when (ev.actionMasked) { when (ev.actionMasked) {
@@ -60,7 +60,7 @@ constructor(context: Context? = null, attrs: AttributeSet? = null) :
override fun onTouchEvent( override fun onTouchEvent(
parent: CoordinatorLayout, parent: CoordinatorLayout,
child: AppBarLayout, child: AppBarLayout,
ev: MotionEvent ev: MotionEvent,
): Boolean { ): Boolean {
val consumed = super.onTouchEvent(parent, child, ev) val consumed = super.onTouchEvent(parent, child, ev)
when (ev.actionMasked) { when (ev.actionMasked) {
@@ -71,7 +71,7 @@ constructor(private val listSettings: ListSettings, private val musicRepository:
private class DetailGeneratorImpl( private class DetailGeneratorImpl(
private val invalidator: DetailGenerator.Invalidator, private val invalidator: DetailGenerator.Invalidator,
private val listSettings: ListSettings, private val listSettings: ListSettings,
private val musicRepository: MusicRepository private val musicRepository: MusicRepository,
) : DetailGenerator, MusicRepository.UpdateListener, ListSettings.Listener { ) : DetailGenerator, MusicRepository.UpdateListener, ListSettings.Listener {
override fun attach() { override fun attach() {
listSettings.registerListener(this) listSettings.registerListener(this)
@@ -225,7 +225,7 @@ sealed interface DetailSection {
DEMOS(R.string.lbl_demos), DEMOS(R.string.lbl_demos),
APPEARANCES(R.string.lbl_appears_on), APPEARANCES(R.string.lbl_appears_on),
LIVE(R.string.lbl_live_group), LIVE(R.string.lbl_live_group),
REMIXES(R.string.lbl_remix_group) REMIXES(R.string.lbl_remix_group),
} }
} }
@@ -67,7 +67,7 @@ constructor(
private val listSettings: ListSettings, private val listSettings: ListSettings,
private val musicRepository: MusicRepository, private val musicRepository: MusicRepository,
private val playbackSettings: PlaybackSettings, private val playbackSettings: PlaybackSettings,
detailGeneratorFactory: DetailGenerator.Factory detailGeneratorFactory: DetailGenerator.Factory,
) : ViewModel(), DetailGenerator.Invalidator { ) : ViewModel(), DetailGenerator.Invalidator {
private val _toShow = MutableEvent<Show>() private val _toShow = MutableEvent<Show>()
@@ -226,7 +226,12 @@ constructor(
MusicType.ARTISTS -> { MusicType.ARTISTS -> {
val artist = detailGenerator.artist(currentArtist.value?.uid ?: return) val artist = detailGenerator.artist(currentArtist.value?.uid ?: return)
refreshDetail( refreshDetail(
artist, _currentArtist, _artistSongList, _artistSongInstructions, replace) artist,
_currentArtist,
_artistSongList,
_artistSongInstructions,
replace,
)
} }
MusicType.GENRES -> { MusicType.GENRES -> {
val genre = detailGenerator.genre(currentGenre.value?.uid ?: return) val genre = detailGenerator.genre(currentGenre.value?.uid ?: return)
@@ -272,7 +277,8 @@ constructor(
Show.SongArtistDecision(song) Show.SongArtistDecision(song)
} else { } else {
Show.ArtistDetails(song.artists.first()) Show.ArtistDetails(song.artists.first())
}) }
)
/** /**
* Navigate to the details of one of the [Artist]s of an [Album] using the corresponding choice * Navigate to the details of one of the [Artist]s of an [Album] using the corresponding choice
@@ -286,7 +292,8 @@ constructor(
Show.AlbumArtistDecision(album) Show.AlbumArtistDecision(album)
} else { } else {
Show.ArtistDetails(album.artists.first()) Show.ArtistDetails(album.artists.first())
}) }
)
/** /**
* Navigate to the details of an [Artist]. * Navigate to the details of an [Artist].
@@ -518,7 +525,8 @@ constructor(
} else { } else {
L.d("Playlist will be empty after removal, removing header") L.d("Playlist will be empty after removal, removing header")
UpdateInstructions.Remove(at - 1, 3) UpdateInstructions.Remove(at - 1, 3)
}) },
)
} }
private fun refreshAudioInfo(song: Song) { private fun refreshAudioInfo(song: Song) {
@@ -541,7 +549,10 @@ constructor(
add(SongProperty(R.string.lbl_bitrate, SongProperty.Value.Bitrate(song.bitrateKbps))) add(SongProperty(R.string.lbl_bitrate, SongProperty.Value.Bitrate(song.bitrateKbps)))
add( add(
SongProperty( SongProperty(
R.string.lbl_sample_rate, SongProperty.Value.SampleRate(song.sampleRateHz))) R.string.lbl_sample_rate,
SongProperty.Value.SampleRate(song.sampleRateHz),
)
)
song.replayGainAdjustment.track?.let { song.replayGainAdjustment.track?.let {
add(SongProperty(R.string.lbl_replaygain_track, SongProperty.Value.Decibels(it))) add(SongProperty(R.string.lbl_replaygain_track, SongProperty.Value.Decibels(it)))
} }
@@ -557,7 +568,7 @@ constructor(
list: MutableStateFlow<List<Item>>, list: MutableStateFlow<List<Item>>,
instructions: MutableEvent<UpdateInstructions>, instructions: MutableEvent<UpdateInstructions>,
replace: Int?, replace: Int?,
songHeader: (Int) -> PlainHeader = { SortHeader(it) } songHeader: (Int) -> PlainHeader = { SortHeader(it) },
) { ) {
if (detail == null) { if (detail == null) {
parent.value = null parent.value = null
@@ -611,16 +622,21 @@ constructor(
private fun refreshPlaylist( private fun refreshPlaylist(
uid: Music.UID, uid: Music.UID,
instructions: UpdateInstructions = UpdateInstructions.Diff instructions: UpdateInstructions = UpdateInstructions.Diff,
) { ) {
L.d("Refreshing playlist list") L.d("Refreshing playlist list")
val edited = editedPlaylist.value val edited = editedPlaylist.value
if (edited == null) { if (edited == null) {
val playlist = detailGenerator.playlist(uid) val playlist = detailGenerator.playlist(uid)
refreshDetail( refreshDetail(
playlist, _currentPlaylist, _playlistSongList, _playlistSongInstructions, null) { playlist,
EditHeader(it) _currentPlaylist,
} _playlistSongList,
_playlistSongInstructions,
null,
) {
EditHeader(it)
}
return return
} }
val list = mutableListOf<Item>() val list = mutableListOf<Item>()
@@ -74,7 +74,11 @@ class GenreDetailFragment : DetailFragment<Genre, Music>() {
collect(musicModel.playlistDecision.flow, ::handlePlaylistDecision) collect(musicModel.playlistDecision.flow, ::handlePlaylistDecision)
collect(musicModel.playlistMessage.flow, ::handlePlaylistMessage) collect(musicModel.playlistMessage.flow, ::handlePlaylistMessage)
collectImmediately( collectImmediately(
playbackModel.song, playbackModel.parent, playbackModel.isPlaying, ::updatePlayback) playbackModel.song,
playbackModel.parent,
playbackModel.isPlaying,
::updatePlayback,
)
collect(playbackModel.playbackDecision.flow, ::handlePlaybackDecision) collect(playbackModel.playbackDecision.flow, ::handlePlaybackDecision)
} }
@@ -129,7 +133,8 @@ class GenreDetailFragment : DetailFragment<Genre, Music>() {
context.getString( context.getString(
R.string.fmt_two, R.string.fmt_two,
context.getPlural(R.plurals.fmt_artist_count, genre.artists.size), context.getPlural(R.plurals.fmt_artist_count, genre.artists.size),
context.getPlural(R.plurals.fmt_song_count, genre.songs.size)) context.getPlural(R.plurals.fmt_song_count, genre.songs.size),
)
binding.detailPlayButton?.setOnClickListener { binding.detailPlayButton?.setOnClickListener {
playbackModel.play(unlikelyToBeNull(detailModel.currentGenre.value)) playbackModel.play(unlikelyToBeNull(detailModel.currentGenre.value))
} }
@@ -143,7 +148,10 @@ class GenreDetailFragment : DetailFragment<Genre, Music>() {
playbackModel.shuffle(unlikelyToBeNull(detailModel.currentGenre.value)) playbackModel.shuffle(unlikelyToBeNull(detailModel.currentGenre.value))
} }
updatePlayback( updatePlayback(
playbackModel.song.value, playbackModel.parent.value, playbackModel.isPlaying.value) playbackModel.song.value,
playbackModel.parent.value,
playbackModel.isPlaying.value,
)
} }
private fun updateList(list: List<Item>) { private fun updateList(list: List<Item>) {
@@ -234,7 +242,8 @@ class GenreDetailFragment : DetailFragment<Genre, Music>() {
is PlaylistDecision.Add -> { is PlaylistDecision.Add -> {
L.d("Adding ${decision.songs.size} songs to a playlist") L.d("Adding ${decision.songs.size} songs to a playlist")
GenreDetailFragmentDirections.addToPlaylist( GenreDetailFragmentDirections.addToPlaylist(
decision.songs.map { it.uid }.toTypedArray()) decision.songs.map { it.uid }.toTypedArray()
)
} }
is PlaylistDecision.New, is PlaylistDecision.New,
is PlaylistDecision.Import, is PlaylistDecision.Import,
@@ -106,7 +106,10 @@ class PlaylistDetailFragment :
// DetailViewModel handles most initialization from the navigation argument. // DetailViewModel handles most initialization from the navigation argument.
detailModel.setPlaylist(args.playlistUid) detailModel.setPlaylist(args.playlistUid)
collectImmediately( collectImmediately(
detailModel.currentPlaylist, detailModel.editedPlaylist, ::updatePlaylist) detailModel.currentPlaylist,
detailModel.editedPlaylist,
::updatePlaylist,
)
collectImmediately(detailModel.playlistSongList, ::updateList) collectImmediately(detailModel.playlistSongList, ::updateList)
collectImmediately(detailModel.editedPlaylist, ::updateEditedList) collectImmediately(detailModel.editedPlaylist, ::updateEditedList)
collect(detailModel.toShow.flow, ::handleShow) collect(detailModel.toShow.flow, ::handleShow)
@@ -115,7 +118,11 @@ class PlaylistDetailFragment :
collect(musicModel.playlistDecision.flow, ::handlePlaylistDecision) collect(musicModel.playlistDecision.flow, ::handlePlaylistDecision)
collect(musicModel.playlistMessage.flow, ::handlePlaylistMessage) collect(musicModel.playlistMessage.flow, ::handlePlaylistMessage)
collectImmediately( collectImmediately(
playbackModel.song, playbackModel.parent, playbackModel.isPlaying, ::updatePlayback) playbackModel.song,
playbackModel.parent,
playbackModel.isPlaying,
::updatePlayback,
)
collect(playbackModel.playbackDecision.flow, ::handlePlaybackDecision) collect(playbackModel.playbackDecision.flow, ::handlePlaybackDecision)
} }
@@ -171,7 +178,9 @@ class PlaylistDetailFragment :
override fun onOpenParentMenu() { override fun onOpenParentMenu() {
listModel.openMenu( listModel.openMenu(
R.menu.detail_playlist, unlikelyToBeNull(detailModel.currentPlaylist.value)) R.menu.detail_playlist,
unlikelyToBeNull(detailModel.currentPlaylist.value),
)
} }
override fun onOpenMenu(item: Song) { override fun onOpenMenu(item: Song) {
@@ -198,7 +207,8 @@ class PlaylistDetailFragment :
binding.detailCover.bind( binding.detailCover.bind(
editedPlaylist, editedPlaylist,
binding.context.getString(R.string.desc_playlist_image, playlist.name), binding.context.getString(R.string.desc_playlist_image, playlist.name),
R.drawable.ic_playlist_24) R.drawable.ic_playlist_24,
)
} else { } else {
binding.detailCover.bind(playlist) binding.detailCover.bind(playlist)
} }
@@ -216,7 +226,8 @@ class PlaylistDetailFragment :
binding.context.getString( binding.context.getString(
R.string.fmt_two, R.string.fmt_two,
binding.context.getPlural(R.plurals.fmt_song_count, songs.size), binding.context.getPlural(R.plurals.fmt_song_count, songs.size),
durationMs.formatDurationMs(true)) durationMs.formatDurationMs(true),
)
} else { } else {
binding.context.getString(R.string.def_song_count) binding.context.getString(R.string.def_song_count)
} }
@@ -251,7 +262,10 @@ class PlaylistDetailFragment :
} }
} }
updatePlayback( updatePlayback(
playbackModel.song.value, playbackModel.parent.value, playbackModel.isPlaying.value) playbackModel.song.value,
playbackModel.parent.value,
playbackModel.isPlaying.value,
)
} }
private fun updateList(list: List<Item>) { private fun updateList(list: List<Item>) {
@@ -303,7 +317,8 @@ class PlaylistDetailFragment :
L.d("Navigating to artist choices for ${show.album}") L.d("Navigating to artist choices for ${show.album}")
findNavController() findNavController()
.navigateSafe( .navigateSafe(
PlaylistDetailFragmentDirections.showArtistChoices(show.album.uid)) PlaylistDetailFragmentDirections.showArtistChoices(show.album.uid)
)
} }
is Show.PlaylistDetails -> { is Show.PlaylistDetails -> {
L.d("Navigated to this playlist") L.d("Navigated to this playlist")
@@ -362,7 +377,8 @@ class PlaylistDetailFragment :
decision.playlist.uid, decision.playlist.uid,
decision.template, decision.template,
decision.applySongs.map { it.uid }.toTypedArray(), decision.applySongs.map { it.uid }.toTypedArray(),
decision.reason) decision.reason,
)
} }
is PlaylistDecision.Export -> { is PlaylistDecision.Export -> {
L.d("Exporting ${decision.playlist}") L.d("Exporting ${decision.playlist}")
@@ -375,7 +391,8 @@ class PlaylistDetailFragment :
is PlaylistDecision.Add -> { is PlaylistDecision.Add -> {
L.d("Adding ${decision.songs.size} songs to a playlist") L.d("Adding ${decision.songs.size} songs to a playlist")
PlaylistDetailFragmentDirections.addToPlaylist( PlaylistDetailFragmentDirections.addToPlaylist(
decision.songs.map { it.uid }.toTypedArray()) decision.songs.map { it.uid }.toTypedArray()
)
} }
is PlaylistDecision.New -> error("Unexpected playlist decision $decision") is PlaylistDecision.New -> error("Unexpected playlist decision $decision")
} }
@@ -391,7 +408,9 @@ class PlaylistDetailFragment :
private fun updatePlayback(song: Song?, parent: MusicParent?, isPlaying: Boolean) { private fun updatePlayback(song: Song?, parent: MusicParent?, isPlaying: Boolean) {
// Prefer songs that are playing from this playlist. // Prefer songs that are playing from this playlist.
playlistListAdapter.setPlaying( playlistListAdapter.setPlaying(
song.takeIf { parent == detailModel.currentPlaylist.value }, isPlaying) song.takeIf { parent == detailModel.currentPlaylist.value },
isPlaying,
)
} }
private fun handlePlaybackDecision(decision: PlaybackDecision?) { private fun handlePlaybackDecision(decision: PlaybackDecision?) {
@@ -38,7 +38,7 @@ class ReadOnlyTextInput
constructor( constructor(
context: Context, context: Context,
attrs: AttributeSet? = null, attrs: AttributeSet? = null,
defStyleAttr: Int = R.attr.editTextStyle defStyleAttr: Int = R.attr.editTextStyle,
) : TextInputEditText(context, attrs, defStyleAttr) { ) : TextInputEditText(context, attrs, defStyleAttr) {
init { init {
// Enable selection, but still disable focus (i.e Keyboard opening) // Enable selection, but still disable focus (i.e Keyboard opening)
@@ -50,8 +50,10 @@ constructor(
// Make text immutable // Make text immutable
override fun getFreezesText() = false override fun getFreezesText() = false
// Prevent editing by default // Prevent editing by default
override fun getDefaultEditable() = false override fun getDefaultEditable() = false
// Remove the movement method that allows cursor scrolling // Remove the movement method that allows cursor scrolling
override fun getDefaultMovementMethod() = null override fun getDefaultMovementMethod() = null
} }
@@ -38,7 +38,8 @@ import org.oxycblt.musikr.Artist
*/ */
class ArtistShowChoice(private val listener: ClickableListListener<Artist>) : class ArtistShowChoice(private val listener: ClickableListListener<Artist>) :
FlexibleListAdapter<Artist, ArtistNavigationChoiceViewHolder>( FlexibleListAdapter<Artist, ArtistNavigationChoiceViewHolder>(
ArtistNavigationChoiceViewHolder.DIFF_CALLBACK) { ArtistNavigationChoiceViewHolder.DIFF_CALLBACK
) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
ArtistNavigationChoiceViewHolder.from(parent) ArtistNavigationChoiceViewHolder.from(parent)
@@ -78,7 +79,8 @@ private constructor(private val binding: ItemPickerChoiceBinding) :
*/ */
fun from(parent: View) = fun from(parent: View) =
ArtistNavigationChoiceViewHolder( ArtistNavigationChoiceViewHolder(
ItemPickerChoiceBinding.inflate(parent.context.inflater)) ItemPickerChoiceBinding.inflate(parent.context.inflater)
)
/** A comparator that can be used with DiffUtil. */ /** A comparator that can be used with DiffUtil. */
val DIFF_CALLBACK = val DIFF_CALLBACK =
@@ -98,6 +98,7 @@ sealed interface ArtistShowChoices {
val uid: Music.UID val uid: Music.UID
/** The current [Artist] choices. */ /** The current [Artist] choices. */
val choices: List<Artist> val choices: List<Artist>
/** Sanitize this instance with a [Library]. */ /** Sanitize this instance with a [Library]. */
fun sanitize(newLibrary: Library): ArtistShowChoices? fun sanitize(newLibrary: Library): ArtistShowChoices?
@@ -49,7 +49,7 @@ import org.oxycblt.musikr.Music
*/ */
abstract class DetailListAdapter( abstract class DetailListAdapter(
private val listener: Listener<*>, private val listener: Listener<*>,
private val diffCallback: DiffUtil.ItemCallback<Item> private val diffCallback: DiffUtil.ItemCallback<Item>,
) : SelectionIndicatorAdapter<Item, RecyclerView.ViewHolder>(diffCallback) { ) : SelectionIndicatorAdapter<Item, RecyclerView.ViewHolder>(diffCallback) {
override fun getItemViewType(position: Int) = override fun getItemViewType(position: Int) =
@@ -77,7 +77,7 @@ class PlaylistDetailListAdapter(private val listener: Listener) :
override fun onBindViewHolder( override fun onBindViewHolder(
holder: RecyclerView.ViewHolder, holder: RecyclerView.ViewHolder,
position: Int, position: Int,
payloads: List<Any> payloads: List<Any>,
) { ) {
super.onBindViewHolder(holder, position, payloads) super.onBindViewHolder(holder, position, payloads)
@@ -131,7 +131,9 @@ class PlaylistDetailListAdapter(private val listener: Listener) :
when { when {
oldItem is Song && newItem is Song -> oldItem is Song && newItem is Song ->
PlaylistSongViewHolder.DIFF_CALLBACK.areContentsTheSame( PlaylistSongViewHolder.DIFF_CALLBACK.areContentsTheSame(
oldItem, newItem) oldItem,
newItem,
)
oldItem is EditHeader && newItem is EditHeader -> oldItem is EditHeader && newItem is EditHeader ->
EditHeaderViewHolder.DIFF_CALLBACK.areContentsTheSame(oldItem, newItem) EditHeaderViewHolder.DIFF_CALLBACK.areContentsTheSame(oldItem, newItem)
else -> DetailListAdapter.DIFF_CALLBACK.areContentsTheSame(oldItem, newItem) else -> DetailListAdapter.DIFF_CALLBACK.areContentsTheSame(oldItem, newItem)
@@ -242,7 +244,9 @@ private constructor(private val binding: ItemEditableSongBinding) :
MaterialShapeDrawable.createWithElevationOverlay(binding.context).apply { MaterialShapeDrawable.createWithElevationOverlay(binding.context).apply {
fillColor = binding.context.getAttrColorCompat(MR.attr.colorSurface) fillColor = binding.context.getAttrColorCompat(MR.attr.colorSurface)
}, },
background)) background,
)
)
} }
/** /**
@@ -31,10 +31,12 @@ class PlaylistDragCallback(private val detailModel: DetailViewModel) : MaterialD
override fun onMove( override fun onMove(
recyclerView: RecyclerView, recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder, viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder target: RecyclerView.ViewHolder,
) = ) =
detailModel.movePlaylistSongs( detailModel.movePlaylistSongs(
viewHolder.bindingAdapterPosition, target.bindingAdapterPosition) viewHolder.bindingAdapterPosition,
target.bindingAdapterPosition,
)
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
detailModel.removePlaylistSong(viewHolder.bindingAdapterPosition) detailModel.removePlaylistSong(viewHolder.bindingAdapterPosition)
@@ -46,7 +46,8 @@ import org.oxycblt.musikr.tag.Date
*/ */
class SongPropertyAdapter : class SongPropertyAdapter :
FlexibleListAdapter<SongProperty, SongPropertyViewHolder>( FlexibleListAdapter<SongProperty, SongPropertyViewHolder>(
SongPropertyViewHolder.DIFF_CALLBACK) { SongPropertyViewHolder.DIFF_CALLBACK
) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
SongPropertyViewHolder.from(parent) SongPropertyViewHolder.from(parent)
@@ -115,7 +116,8 @@ class SongPropertyViewHolder private constructor(private val binding: ItemSongPr
context.getString(R.string.fmt_zipped_names, value, subtitle) context.getString(R.string.fmt_zipped_names, value, subtitle)
} else { } else {
value value
}) }
)
} }
is SongProperty.Value.ItemDate -> { is SongProperty.Value.ItemDate -> {
val date = property.value.date val date = property.value.date
@@ -58,7 +58,8 @@ class GenreSongSortDialog : SortDialog() {
Sort.Mode.ByArtist, Sort.Mode.ByArtist,
Sort.Mode.ByAlbum, Sort.Mode.ByAlbum,
Sort.Mode.ByDate, Sort.Mode.ByDate,
Sort.Mode.ByDuration) Sort.Mode.ByDuration,
)
private fun updateGenre(genre: Genre?) { private fun updateGenre(genre: Genre?) {
if (genre == null) { if (genre == null) {
@@ -58,7 +58,8 @@ class PlaylistSongSortDialog : SortDialog() {
Sort.Mode.ByArtist, Sort.Mode.ByArtist,
Sort.Mode.ByAlbum, Sort.Mode.ByAlbum,
Sort.Mode.ByDate, Sort.Mode.ByDate,
Sort.Mode.ByDuration) Sort.Mode.ByDuration,
)
private fun updatePlaylist(genre: Playlist?) { private fun updatePlaylist(genre: Playlist?) {
if (genre == null) { if (genre == null) {
@@ -77,7 +77,8 @@ class ErrorDetailsDialog : ViewBindingMaterialDialogFragment<DialogErrorDetailsB
private fun copyStackTrace() { private fun copyStackTrace() {
requireNotNull(clipboardManager) { "Clipboard was unavailable" } requireNotNull(clipboardManager) { "Clipboard was unavailable" }
.setPrimaryClip( .setPrimaryClip(
ClipData.newPlainText("Exception Stack Trace", args.error.stackTraceToString())) ClipData.newPlainText("Exception Stack Trace", args.error.stackTraceToString())
)
// A copy notice is shown by the system from Android 13 onwards // A copy notice is shown by the system from Android 13 onwards
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
requireContext().showToast(R.string.lbl_copied) requireContext().showToast(R.string.lbl_copied)
@@ -143,7 +143,8 @@ class HomeFragment :
override fun onPageSelected(position: Int) { override fun onPageSelected(position: Int) {
homeModel.synchronizeTabPosition(position) homeModel.synchronizeTabPosition(position)
} }
}) }
)
// ViewPager2 will nominally consume window insets, which will then break the window // ViewPager2 will nominally consume window insets, which will then break the window
// insets applied to the indexing view before API 30. Fix this by overriding the // insets applied to the indexing view before API 30. Fix this by overriding the
@@ -198,7 +199,8 @@ class HomeFragment :
// when the AppBarLayout is only at half-collapsed. // when the AppBarLayout is only at half-collapsed.
binding.homeToolbar.alpha = 1f - (abs(verticalOffset.toFloat()) / (range.toFloat() / 2)) binding.homeToolbar.alpha = 1f - (abs(verticalOffset.toFloat()) / (range.toFloat() / 2))
binding.homeContent.updatePadding( binding.homeContent.updatePadding(
bottom = binding.homeAppbar.totalScrollRange + verticalOffset) bottom = binding.homeAppbar.totalScrollRange + verticalOffset
)
} }
override fun onMenuItemClick(item: MenuItem): Boolean { override fun onMenuItemClick(item: MenuItem): Boolean {
@@ -266,7 +268,10 @@ class HomeFragment :
// Set up the mapping between the ViewPager and TabLayout. // Set up the mapping between the ViewPager and TabLayout.
TabLayoutMediator( TabLayoutMediator(
binding.homeTabs, binding.homePager, NamedTabStrategy(homeModel.currentTabTypes)) binding.homeTabs,
binding.homePager,
NamedTabStrategy(homeModel.currentTabTypes),
)
.attach() .attach()
} }
@@ -353,7 +358,8 @@ class HomeFragment :
HomeFragmentDirections.newPlaylist( HomeFragmentDirections.newPlaylist(
decision.songs.map { it.uid }.toTypedArray(), decision.songs.map { it.uid }.toTypedArray(),
decision.template, decision.template,
decision.reason) decision.reason,
)
} }
is PlaylistDecision.Import -> { is PlaylistDecision.Import -> {
L.d("Importing playlist") L.d("Importing playlist")
@@ -371,7 +377,8 @@ class HomeFragment :
decision.playlist.uid, decision.playlist.uid,
decision.template, decision.template,
decision.applySongs.map { it.uid }.toTypedArray(), decision.applySongs.map { it.uid }.toTypedArray(),
decision.reason) decision.reason,
)
} }
is PlaylistDecision.Export -> { is PlaylistDecision.Export -> {
L.d("Exporting ${decision.playlist}") L.d("Exporting ${decision.playlist}")
@@ -384,7 +391,8 @@ class HomeFragment :
is PlaylistDecision.Add -> { is PlaylistDecision.Add -> {
L.d("Adding ${decision.songs.size} to a playlist") L.d("Adding ${decision.songs.size} to a playlist")
HomeFragmentDirections.addToPlaylist( HomeFragmentDirections.addToPlaylist(
decision.songs.map { it.uid }.toTypedArray()) decision.songs.map { it.uid }.toTypedArray()
)
} }
} }
findNavController().navigateSafe(directions) findNavController().navigateSafe(directions)
@@ -491,7 +499,7 @@ class HomeFragment :
private class HomePagerAdapter( private class HomePagerAdapter(
private val tabs: List<MusicType>, private val tabs: List<MusicType>,
fragmentManager: FragmentManager, fragmentManager: FragmentManager,
lifecycleOwner: LifecycleOwner lifecycleOwner: LifecycleOwner,
) : FragmentStateAdapter(fragmentManager, lifecycleOwner.lifecycle) { ) : FragmentStateAdapter(fragmentManager, lifecycleOwner.lifecycle) {
override fun getItemCount() = tabs.size override fun getItemCount() = tabs.size
@@ -43,6 +43,7 @@ interface HomeSettings : Settings<HomeSettings.Listener> {
interface Listener { interface Listener {
/** Called when the [homeTabs] configuration changes. */ /** Called when the [homeTabs] configuration changes. */
fun onTabsChanged() {} fun onTabsChanged() {}
/** Called when the [shouldHideCollaborators] configuration changes. */ /** Called when the [shouldHideCollaborators] configuration changes. */
fun onHideCollaboratorsChanged() {} fun onHideCollaboratorsChanged() {}
} }
@@ -54,8 +55,10 @@ class HomeSettingsImpl @Inject constructor(@ApplicationContext context: Context)
get() = get() =
Tab.fromIntCode( Tab.fromIntCode(
sharedPreferences.getInt( sharedPreferences.getInt(
getString(R.string.set_key_home_tabs), Tab.SEQUENCE_DEFAULT)) getString(R.string.set_key_home_tabs),
?: unlikelyToBeNull(Tab.fromIntCode(Tab.SEQUENCE_DEFAULT)) Tab.SEQUENCE_DEFAULT,
)
) ?: unlikelyToBeNull(Tab.fromIntCode(Tab.SEQUENCE_DEFAULT))
set(value) { set(value) {
sharedPreferences.edit { sharedPreferences.edit {
putInt(getString(R.string.set_key_home_tabs), Tab.toIntCode(value)) putInt(getString(R.string.set_key_home_tabs), Tab.toIntCode(value))
@@ -50,7 +50,7 @@ class HomeViewModel
constructor( constructor(
private val listSettings: ListSettings, private val listSettings: ListSettings,
private val playbackSettings: PlaybackSettings, private val playbackSettings: PlaybackSettings,
homeGeneratorFactory: HomeGenerator.Factory homeGeneratorFactory: HomeGenerator.Factory,
) : ViewModel(), HomeGenerator.Invalidator { ) : ViewModel(), HomeGenerator.Invalidator {
private val _songList = MutableStateFlow(listOf<Song>()) private val _songList = MutableStateFlow(listOf<Song>())
/** A list of [Song]s, sorted by the preferred [Sort], to be shown in the home view. */ /** A list of [Song]s, sorted by the preferred [Sort], to be shown in the home view. */
@@ -75,7 +75,7 @@ class ThemedSpeedDialView : SpeedDialView {
constructor( constructor(
context: Context, context: Context,
attrs: AttributeSet?, attrs: AttributeSet?,
@AttrRes defStyleAttr: Int @AttrRes defStyleAttr: Int,
) : super(context, attrs, defStyleAttr) ) : super(context, attrs, defStyleAttr)
private val stationaryConfig = AnimConfig.of(context, AnimConfig.STANDARD, AnimConfig.MEDIUM2) private val stationaryConfig = AnimConfig.of(context, AnimConfig.STANDARD, AnimConfig.MEDIUM2)
@@ -121,10 +121,12 @@ class ThemedSpeedDialView : SpeedDialView {
mainFab.backgroundTintList = mainFab.backgroundTintList =
ColorStateList.valueOf( ColorStateList.valueOf(
if (isOpen) mainFabClosedBackgroundColor if (isOpen) mainFabClosedBackgroundColor
else mainFabOpenedBackgroundColor) else mainFabOpenedBackgroundColor
)
mainFab.imageTintList = mainFab.imageTintList =
ColorStateList.valueOf( ColorStateList.valueOf(
if (isOpen) mainFabClosedIconColor else mainFabOpenedIconColor) if (isOpen) mainFabClosedIconColor else mainFabOpenedIconColor
)
mainFabAnimator?.cancel() mainFabAnimator?.cancel()
mainFabAnimator = mainFabAnimator =
createMainFabAnimator(isOpen).apply { createMainFabAnimator(isOpen).apply {
@@ -133,12 +135,14 @@ class ThemedSpeedDialView : SpeedDialView {
override fun onAnimationEnd(animation: Animator) { override fun onAnimationEnd(animation: Animator) {
mainFabAnimator = null mainFabAnimator = null
} }
}) }
)
start() start()
} }
innerChangeListener?.invoke(isOpen) innerChangeListener?.invoke(isOpen)
} }
}) }
)
} }
private fun createMainFabAnimator(isOpen: Boolean): Animator { private fun createMainFabAnimator(isOpen: Boolean): Animator {
@@ -150,7 +154,8 @@ class ThemedSpeedDialView : SpeedDialView {
ObjectAnimator.ofArgb( ObjectAnimator.ofArgb(
mainFab, mainFab,
VIEW_PROPERTY_BACKGROUND_TINT, VIEW_PROPERTY_BACKGROUND_TINT,
if (isOpen) mainFabOpenedBackgroundColor else mainFabClosedBackgroundColor) if (isOpen) mainFabOpenedBackgroundColor else mainFabClosedBackgroundColor,
)
.apply { .apply {
startDelay = delay startDelay = delay
duration = partialDuration duration = partialDuration
@@ -160,7 +165,8 @@ class ThemedSpeedDialView : SpeedDialView {
ObjectAnimator.ofArgb( ObjectAnimator.ofArgb(
mainFab, mainFab,
IMAGE_VIEW_PROPERTY_IMAGE_TINT, IMAGE_VIEW_PROPERTY_IMAGE_TINT,
if (isOpen) mainFabOpenedIconColor else mainFabClosedIconColor) if (isOpen) mainFabOpenedIconColor else mainFabClosedIconColor,
)
.apply { .apply {
startDelay = delay startDelay = delay
duration = partialDuration duration = partialDuration
@@ -168,7 +174,10 @@ class ThemedSpeedDialView : SpeedDialView {
val levelAnimator = val levelAnimator =
ObjectAnimator.ofInt( ObjectAnimator.ofInt(
mainFab.drawable, DRAWABLE_PROPERTY_LEVEL, if (isOpen) 10000 else 0) mainFab.drawable,
DRAWABLE_PROPERTY_LEVEL,
if (isOpen) 10000 else 0,
)
.apply { duration = totalDuration } .apply { duration = totalDuration }
val animatorSet = val animatorSet =
@@ -204,7 +213,7 @@ class ThemedSpeedDialView : SpeedDialView {
override fun addActionItem( override fun addActionItem(
actionItem: SpeedDialActionItem, actionItem: SpeedDialActionItem,
position: Int, position: Int,
animate: Boolean animate: Boolean,
): FabWithLabelView? { ): FabWithLabelView? {
val context = context val context = context
val fabImageTintColor = context.getAttrColorCompat(androidx.appcompat.R.attr.colorPrimary) val fabImageTintColor = context.getAttrColorCompat(androidx.appcompat.R.attr.colorPrimary)
@@ -220,7 +229,8 @@ class ThemedSpeedDialView : SpeedDialView {
SpeedDialActionItem.Builder( SpeedDialActionItem.Builder(
actionItem.id, actionItem.id,
// Should not be a resource, pass null to fail fast. // Should not be a resource, pass null to fail fast.
actionItem.getFabImageDrawable(null)) actionItem.getFabImageDrawable(null),
)
.setLabel(actionItem.getLabel(context)) .setLabel(actionItem.getLabel(context))
.setFabImageTintColor(fabImageTintColor.defaultColor) .setFabImageTintColor(fabImageTintColor.defaultColor)
.setFabBackgroundColor(fabBackgroundColor.defaultColor) .setFabBackgroundColor(fabBackgroundColor.defaultColor)
@@ -269,7 +279,10 @@ class ThemedSpeedDialView : SpeedDialView {
override fun onSaveInstanceState(): Parcelable { override fun onSaveInstanceState(): Parcelable {
val superState = val superState =
BundleCompat.getParcelable( BundleCompat.getParcelable(
super.onSaveInstanceState() as Bundle, "superState", Parcelable::class.java) super.onSaveInstanceState() as Bundle,
"superState",
Parcelable::class.java,
)
return State(superState, isOpen) return State(superState, isOpen)
} }
@@ -94,7 +94,11 @@ class AlbumListFragment :
collectImmediately(homeModel.empty, musicModel.indexingState, ::updateNoMusicIndicator) collectImmediately(homeModel.empty, musicModel.indexingState, ::updateNoMusicIndicator)
collectImmediately(listModel.selected, ::updateSelection) collectImmediately(listModel.selected, ::updateSelection)
collectImmediately( collectImmediately(
playbackModel.song, playbackModel.parent, playbackModel.isPlaying, ::updatePlayback) playbackModel.song,
playbackModel.parent,
playbackModel.isPlaying,
::updatePlayback,
)
} }
override fun onDestroyBinding(binding: FragmentHomeListBinding) { override fun onDestroyBinding(binding: FragmentHomeListBinding) {
@@ -134,7 +138,8 @@ class AlbumListFragment :
formatter, formatter,
dateAddedMillis, dateAddedMillis,
dateAddedMillis, dateAddedMillis,
DateUtils.FORMAT_ABBREV_ALL) DateUtils.FORMAT_ABBREV_ALL,
)
.toString() .toString()
} }
@@ -89,7 +89,11 @@ class ArtistListFragment :
collectImmediately(homeModel.empty, musicModel.indexingState, ::updateNoMusicIndicator) collectImmediately(homeModel.empty, musicModel.indexingState, ::updateNoMusicIndicator)
collectImmediately(listModel.selected, ::updateSelection) collectImmediately(listModel.selected, ::updateSelection)
collectImmediately( collectImmediately(
playbackModel.song, playbackModel.parent, playbackModel.isPlaying, ::updatePlayback) playbackModel.song,
playbackModel.parent,
playbackModel.isPlaying,
::updatePlayback,
)
} }
override fun onDestroyBinding(binding: FragmentHomeListBinding) { override fun onDestroyBinding(binding: FragmentHomeListBinding) {
@@ -88,7 +88,11 @@ class GenreListFragment :
collectImmediately(homeModel.empty, musicModel.indexingState, ::updateNoMusicIndicator) collectImmediately(homeModel.empty, musicModel.indexingState, ::updateNoMusicIndicator)
collectImmediately(listModel.selected, ::updateSelection) collectImmediately(listModel.selected, ::updateSelection)
collectImmediately( collectImmediately(
playbackModel.song, playbackModel.parent, playbackModel.isPlaying, ::updatePlayback) playbackModel.song,
playbackModel.parent,
playbackModel.isPlaying,
::updatePlayback,
)
} }
override fun onDestroyBinding(binding: FragmentHomeListBinding) { override fun onDestroyBinding(binding: FragmentHomeListBinding) {
@@ -85,10 +85,15 @@ class PlaylistListFragment :
homeModel.empty, homeModel.empty,
homeModel.playlistList, homeModel.playlistList,
musicModel.indexingState, musicModel.indexingState,
::updateNoMusicIndicator) ::updateNoMusicIndicator,
)
collectImmediately(listModel.selected, ::updateSelection) collectImmediately(listModel.selected, ::updateSelection)
collectImmediately( collectImmediately(
playbackModel.song, playbackModel.parent, playbackModel.isPlaying, ::updatePlayback) playbackModel.song,
playbackModel.parent,
playbackModel.isPlaying,
::updatePlayback,
)
} }
override fun onDestroyBinding(binding: FragmentHomeListBinding) { override fun onDestroyBinding(binding: FragmentHomeListBinding) {
@@ -137,7 +142,7 @@ class PlaylistListFragment :
private fun updateNoMusicIndicator( private fun updateNoMusicIndicator(
empty: Boolean, empty: Boolean,
playlists: List<Playlist>, playlists: List<Playlist>,
indexingState: IndexingState? indexingState: IndexingState?,
) { ) {
val binding = requireBinding() val binding = requireBinding()
binding.homeRecycler.isInvisible = empty binding.homeRecycler.isInvisible = empty
@@ -92,7 +92,11 @@ class SongListFragment :
collectImmediately(homeModel.empty, musicModel.indexingState, ::updateNoMusicIndicator) collectImmediately(homeModel.empty, musicModel.indexingState, ::updateNoMusicIndicator)
collectImmediately(listModel.selected, ::updateSelection) collectImmediately(listModel.selected, ::updateSelection)
collectImmediately( collectImmediately(
playbackModel.song, playbackModel.parent, playbackModel.isPlaying, ::updatePlayback) playbackModel.song,
playbackModel.parent,
playbackModel.isPlaying,
::updatePlayback,
)
} }
override fun onDestroyBinding(binding: FragmentHomeListBinding) { override fun onDestroyBinding(binding: FragmentHomeListBinding) {
@@ -134,7 +138,8 @@ class SongListFragment :
formatter, formatter,
dateAddedMillis, dateAddedMillis,
dateAddedMillis, dateAddedMillis,
DateUtils.FORMAT_ABBREV_ALL) DateUtils.FORMAT_ABBREV_ALL,
)
.toString() .toString()
} }
@@ -46,5 +46,6 @@ class AlbumSortDialog : SortDialog() {
Sort.Mode.ByDate, Sort.Mode.ByDate,
Sort.Mode.ByDuration, Sort.Mode.ByDuration,
Sort.Mode.ByCount, Sort.Mode.ByCount,
Sort.Mode.ByDateAdded) Sort.Mode.ByDateAdded,
)
} }
@@ -46,5 +46,6 @@ class SongSortDialog : SortDialog() {
Sort.Mode.ByAlbum, Sort.Mode.ByAlbum,
Sort.Mode.ByDate, Sort.Mode.ByDate,
Sort.Mode.ByDuration, Sort.Mode.ByDuration,
Sort.Mode.ByDateAdded) Sort.Mode.ByDateAdded,
)
} }
@@ -73,7 +73,8 @@ sealed class Tab(open val type: MusicType) {
MusicType.ALBUMS, MusicType.ALBUMS,
MusicType.ARTISTS, MusicType.ARTISTS,
MusicType.GENRES, MusicType.GENRES,
MusicType.PLAYLISTS) MusicType.PLAYLISTS,
)
/** /**
* Convert an array of [Tab]s into it's integer representation. * Convert an array of [Tab]s into it's integer representation.
@@ -86,7 +87,8 @@ sealed class Tab(open val type: MusicType) {
val distinct = tabs.distinctBy { it.type } val distinct = tabs.distinctBy { it.type }
if (tabs.size != distinct.size) { if (tabs.size != distinct.size) {
L.w( L.w(
"Tab sequences should not have duplicates [old: ${tabs.size} new: ${distinct.size}]") "Tab sequences should not have duplicates [old: ${tabs.size} new: ${distinct.size}]"
)
} }
var sequence = 0 var sequence = 0
@@ -133,7 +135,8 @@ sealed class Tab(open val type: MusicType) {
val distinct = tabs.distinctBy { it.type } val distinct = tabs.distinctBy { it.type }
if (tabs.size != distinct.size) { if (tabs.size != distinct.size) {
L.w( L.w(
"Tab sequences should not have duplicates [old: ${tabs.size} new: ${distinct.size}]") "Tab sequences should not have duplicates [old: ${tabs.size} new: ${distinct.size}]"
)
} }
// For safety, return null if we have an empty or larger-than-expected tab array. // For safety, return null if we have an empty or larger-than-expected tab array.
@@ -117,7 +117,8 @@ class TabViewHolder private constructor(private val binding: ItemTabBinding) :
MusicType.ARTISTS -> R.string.lbl_artists MusicType.ARTISTS -> R.string.lbl_artists
MusicType.GENRES -> R.string.lbl_genres MusicType.GENRES -> R.string.lbl_genres
MusicType.PLAYLISTS -> R.string.lbl_playlists MusicType.PLAYLISTS -> R.string.lbl_playlists
}) }
)
// Unlike in other adapters, we update the checked state alongside // Unlike in other adapters, we update the checked state alongside
// the tab data since they are in the same data structure (Tab) // the tab data since they are in the same data structure (Tab)
@@ -30,7 +30,7 @@ import androidx.recyclerview.widget.RecyclerView
class TabDragCallback(private val adapter: TabAdapter) : ItemTouchHelper.Callback() { class TabDragCallback(private val adapter: TabAdapter) : ItemTouchHelper.Callback() {
override fun getMovementFlags( override fun getMovementFlags(
recyclerView: RecyclerView, recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder viewHolder: RecyclerView.ViewHolder,
) = // Allow dragging up and down only ) = // Allow dragging up and down only
makeFlag(ItemTouchHelper.ACTION_STATE_DRAG, ItemTouchHelper.UP or ItemTouchHelper.DOWN) makeFlag(ItemTouchHelper.ACTION_STATE_DRAG, ItemTouchHelper.UP or ItemTouchHelper.DOWN)
@@ -41,7 +41,7 @@ class TabDragCallback(private val adapter: TabAdapter) : ItemTouchHelper.Callbac
dX: Float, dX: Float,
dY: Float, dY: Float,
actionState: Int, actionState: Int,
isCurrentlyActive: Boolean isCurrentlyActive: Boolean,
) { ) {
viewHolder.itemView.translationX = dX viewHolder.itemView.translationX = dX
viewHolder.itemView.translationY = dY viewHolder.itemView.translationY = dY
@@ -55,7 +55,7 @@ class TabDragCallback(private val adapter: TabAdapter) : ItemTouchHelper.Callbac
override fun onMove( override fun onMove(
recyclerView: RecyclerView, recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder, viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder target: RecyclerView.ViewHolder,
): Boolean { ): Boolean {
// I don't think it's possible to jump more than one position at a time, so a swap // I don't think it's possible to jump more than one position at a time, so a swap
// will work just fine. // will work just fine.
@@ -44,7 +44,7 @@ class BitmapProvider
@Inject @Inject
constructor( constructor(
@ApplicationContext private val context: Context, @ApplicationContext private val context: Context,
private val imageLoader: ImageLoader private val imageLoader: ImageLoader,
) { ) {
/** /**
* An extension of [Disposable] with an additional [Target] to deliver the final [Bitmap] to. * An extension of [Disposable] with an additional [Target] to deliver the final [Bitmap] to.
@@ -96,7 +96,8 @@ constructor(
ImageRequest.Builder(context) ImageRequest.Builder(context)
.data(song.cover) .data(song.cover)
// Use ORIGINAL sizing, as we are not loading into any View-like component. // Use ORIGINAL sizing, as we are not loading into any View-like component.
.size(Size.ORIGINAL)) .size(Size.ORIGINAL)
)
.target( .target(
onSuccess = { onSuccess = {
synchronized(this) { synchronized(this) {
@@ -111,7 +112,8 @@ constructor(
target.onCompleted(null) target.onCompleted(null)
} }
} }
}) },
)
currentRequest = Request(imageLoader.enqueue(imageRequest.build()), target) currentRequest = Request(imageLoader.enqueue(imageRequest.build()), target)
} }
@@ -56,7 +56,7 @@ class CoverProvider : ContentProvider() {
projection: Array<out String>?, projection: Array<out String>?,
selection: String?, selection: String?,
selectionArgs: Array<out String>?, selectionArgs: Array<out String>?,
sortOrder: String? sortOrder: String?,
): Cursor = throw UnsupportedOperationException() ): Cursor = throw UnsupportedOperationException()
override fun insert(uri: Uri, values: ContentValues?): Uri? = null override fun insert(uri: Uri, values: ContentValues?): Uri? = null
@@ -67,7 +67,7 @@ class CoverProvider : ContentProvider() {
uri: Uri, uri: Uri,
values: ContentValues?, values: ContentValues?,
selection: String?, selection: String?,
selectionArgs: Array<out String>? selectionArgs: Array<out String>?,
): Int = 0 ): Int = 0
companion object { companion object {
@@ -90,7 +90,7 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
private data class PlaybackIndicator( private data class PlaybackIndicator(
val view: ImageView, val view: ImageView,
val playingDrawable: AnimationDrawable, val playingDrawable: AnimationDrawable,
val pausedDrawable: Drawable val pausedDrawable: Drawable,
) )
private val playbackIndicator: PlaybackIndicator? private val playbackIndicator: PlaybackIndicator?
@@ -120,7 +120,8 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
context, context,
com.google.android.material.R.style com.google.android.material.R.style
.ShapeAppearance_Material3_Corner_Medium, .ShapeAppearance_Material3_Corner_Medium,
-1) -1,
)
.build() .build()
} }
} else { } else {
@@ -147,11 +148,14 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
ImageView(context).apply { ImageView(context).apply {
scaleType = ImageView.ScaleType.MATRIX scaleType = ImageView.ScaleType.MATRIX
ImageViewCompat.setImageTintList( ImageViewCompat.setImageTintList(
this, context.getColorCompat(R.color.sel_on_cover_bg)) this,
context.getColorCompat(R.color.sel_on_cover_bg),
)
}, },
context.getDrawableCompat(R.drawable.ic_playing_indicator_24) context.getDrawableCompat(R.drawable.ic_playing_indicator_24)
as AnimationDrawable, as AnimationDrawable,
context.getDrawableCompat(R.drawable.ic_paused_indicator_24)) context.getDrawableCompat(R.drawable.ic_paused_indicator_24),
)
} else { } else {
null null
} }
@@ -193,7 +197,8 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
gravity = Gravity.BOTTOM or Gravity.END gravity = Gravity.BOTTOM or Gravity.END
val spacing = context.getDimenPixels(R.dimen.spacing_tiny) val spacing = context.getDimenPixels(R.dimen.spacing_tiny)
updateMarginsRelative(bottom = spacing, end = spacing) updateMarginsRelative(bottom = spacing, end = spacing)
}) },
)
} }
} }
@@ -214,14 +219,20 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
0f, 0f,
0f, 0f,
drawable.intrinsicWidth.toFloat(), drawable.intrinsicWidth.toFloat(),
drawable.intrinsicHeight.toFloat()) drawable.intrinsicHeight.toFloat(),
)
indicatorMatrixDst.set(0f, 0f, iconSize.toFloat(), iconSize.toFloat()) indicatorMatrixDst.set(0f, 0f, iconSize.toFloat(), iconSize.toFloat())
indicatorMatrix.setRectToRect( indicatorMatrix.setRectToRect(
indicatorMatrixSrc, indicatorMatrixDst, Matrix.ScaleToFit.CENTER) indicatorMatrixSrc,
indicatorMatrixDst,
Matrix.ScaleToFit.CENTER,
)
// Then actually center it into the icon. // Then actually center it into the icon.
indicatorMatrix.postTranslate( indicatorMatrix.postTranslate(
(measuredWidth - iconSize) / 2f, (measuredHeight - iconSize) / 2f) (measuredWidth - iconSize) / 2f,
(measuredHeight - iconSize) / 2f,
)
} }
} }
} }
@@ -319,7 +330,8 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
bindImpl( bindImpl(
song.cover, song.cover,
context.getString(R.string.desc_album_cover, song.album.name), context.getString(R.string.desc_album_cover, song.album.name),
R.drawable.ic_album_24) R.drawable.ic_album_24,
)
/** /**
* Bind an [Album]'s image to this view. * Bind an [Album]'s image to this view.
@@ -341,7 +353,8 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
bindImpl( bindImpl(
mostProminentCover, mostProminentCover,
context.getString(R.string.desc_album_cover, album.name), context.getString(R.string.desc_album_cover, album.name),
R.drawable.ic_album_24) R.drawable.ic_album_24,
)
} }
/** /**
@@ -353,7 +366,8 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
bindImpl( bindImpl(
artist.covers, artist.covers,
context.getString(R.string.desc_artist_image, artist.name), context.getString(R.string.desc_artist_image, artist.name),
R.drawable.ic_artist_24) R.drawable.ic_artist_24,
)
/** /**
* Bind a [Genre]'s image to this view. * Bind a [Genre]'s image to this view.
@@ -364,7 +378,8 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
bindImpl( bindImpl(
genre.covers, genre.covers,
context.getString(R.string.desc_genre_image, genre.name), context.getString(R.string.desc_genre_image, genre.name),
R.drawable.ic_genre_24) R.drawable.ic_genre_24,
)
/** /**
* Bind a [Playlist]'s image to this view. * Bind a [Playlist]'s image to this view.
@@ -375,7 +390,8 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
bindImpl( bindImpl(
playlist.covers, playlist.covers,
context.getString(R.string.desc_playlist_image, playlist.name), context.getString(R.string.desc_playlist_image, playlist.name),
R.drawable.ic_playlist_24) R.drawable.ic_playlist_24,
)
/** /**
* Bind the covers of a generic list of [Song]s. * Bind the covers of a generic list of [Song]s.
@@ -392,14 +408,16 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
ImageRequest.Builder(context) ImageRequest.Builder(context)
.data(cover) .data(cover)
.error( .error(
StyledDrawable(context, context.getDrawableCompat(errorRes), iconSize) StyledDrawable(context, context.getDrawableCompat(errorRes), iconSize).asImage()
.asImage()) )
.target(image) .target(image)
val cornersTransformation = val cornersTransformation =
RoundedRectTransformation( RoundedRectTransformation(
shapeAppearance.topLeftCornerSize.getCornerSize( shapeAppearance.topLeftCornerSize.getCornerSize(
RectF(left.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat()))) RectF(left.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat())
)
)
if (imageSettings.forceSquareCovers) { if (imageSettings.forceSquareCovers) {
request.transformations(SquareCropTransformation.INSTANCE, cornersTransformation) request.transformations(SquareCropTransformation.INSTANCE, cornersTransformation)
} else { } else {
@@ -419,7 +437,7 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
private class StyledDrawable( private class StyledDrawable(
context: Context, context: Context,
private val inner: Drawable, private val inner: Drawable,
@Px val iconSize: Int? @Px val iconSize: Int?,
) : Drawable() { ) : Drawable() {
init { init {
// Re-tint the drawable to use the analogous "on surface" color for // Re-tint the drawable to use the analogous "on surface" color for
@@ -48,16 +48,18 @@ class ImageSettingsImpl @Inject constructor(@ApplicationContext context: Context
override val coverMode: CoverMode override val coverMode: CoverMode
get() = get() =
CoverMode.fromIntCode( CoverMode.fromIntCode(
sharedPreferences.getInt(getString(R.string.set_key_cover_mode), Int.MIN_VALUE)) sharedPreferences.getInt(getString(R.string.set_key_cover_mode), Int.MIN_VALUE)
?: CoverMode.BALANCED ) ?: CoverMode.BALANCED
override val forceSquareCovers: Boolean override val forceSquareCovers: Boolean
get() = sharedPreferences.getBoolean(getString(R.string.set_key_square_covers), false) get() = sharedPreferences.getBoolean(getString(R.string.set_key_square_covers), false)
override fun migrate() { override fun migrate() {
// Show album covers and Ignore MediaStore covers were unified in 3.0.0 // Show album covers and Ignore MediaStore covers were unified in 3.0.0
if (sharedPreferences.contains(OLD_KEY_SHOW_COVERS) || if (
sharedPreferences.contains(OLD_KEY_QUALITY_COVERS)) { sharedPreferences.contains(OLD_KEY_SHOW_COVERS) ||
sharedPreferences.contains(OLD_KEY_QUALITY_COVERS)
) {
L.d("Migrating cover settings") L.d("Migrating cover settings")
val mode = val mode =
@@ -95,8 +97,10 @@ class ImageSettingsImpl @Inject constructor(@ApplicationContext context: Context
} }
override fun onSettingChanged(key: String, listener: ImageSettings.Listener) { override fun onSettingChanged(key: String, listener: ImageSettings.Listener) {
if (key == getString(R.string.set_key_cover_mode) || if (
key == getString(R.string.set_key_square_covers)) { key == getString(R.string.set_key_cover_mode) ||
key == getString(R.string.set_key_square_covers)
) {
L.d("Dispatching image setting change") L.d("Dispatching image setting change")
listener.onImageSettingsChanged() listener.onImageSettingsChanged()
} }
@@ -39,7 +39,7 @@ class CoilModule {
coverKeyer: CoverKeyer, coverKeyer: CoverKeyer,
coverFactory: CoverFetcher.Factory, coverFactory: CoverFetcher.Factory,
coverCollectionKeyer: CoverCollectionKeyer, coverCollectionKeyer: CoverCollectionKeyer,
coverCollectionFactory: CoverCollectionFetcher.Factory coverCollectionFactory: CoverCollectionFetcher.Factory,
) = ) =
ImageLoader.Builder(context) ImageLoader.Builder(context)
.components { .components {
@@ -80,7 +80,8 @@ private constructor(
return SourceFetchResult( return SourceFetchResult(
source = ImageSource(first.source().buffer(), FileSystem.SYSTEM, null), source = ImageSource(first.source().buffer(), FileSystem.SYSTEM, null),
mimeType = null, mimeType = null,
dataSource = DataSource.DISK) dataSource = DataSource.DISK,
)
} }
/** Derived from phonograph: https://github.com/kabouzeid/Phonograph */ /** Derived from phonograph: https://github.com/kabouzeid/Phonograph */
@@ -107,7 +108,9 @@ private constructor(
// TODO: Work around this // TODO: Work around this
val bitmap = val bitmap =
SquareCropTransformation.INSTANCE.transform( SquareCropTransformation.INSTANCE.transform(
BitmapFactory.decodeStream(stream), mosaicFrameSize) BitmapFactory.decodeStream(stream),
mosaicFrameSize,
)
canvas.drawBitmap(bitmap, x.toFloat(), y.toFloat(), null) canvas.drawBitmap(bitmap, x.toFloat(), y.toFloat(), null)
x += bitmap.width x += bitmap.width
@@ -123,7 +126,8 @@ private constructor(
return ImageFetchResult( return ImageFetchResult(
image = mosaicBitmap.toDrawable(context.resources).asImage(), image = mosaicBitmap.toDrawable(context.resources).asImage(),
isSampled = true, isSampled = true,
dataSource = DataSource.DISK) dataSource = DataSource.DISK,
)
} }
private fun Dimension.mosaicSize(): Int { private fun Dimension.mosaicSize(): Int {
@@ -37,7 +37,8 @@ class CoverFetcher private constructor(private val cover: Cover) : Fetcher {
return SourceFetchResult( return SourceFetchResult(
source = ImageSource(stream.source().buffer(), FileSystem.SYSTEM, null), source = ImageSource(stream.source().buffer(), FileSystem.SYSTEM, null),
mimeType = null, mimeType = null,
dataSource = DataSource.DISK) dataSource = DataSource.DISK,
)
} }
class Factory @Inject constructor() : Fetcher.Factory<Cover> { class Factory @Inject constructor() : Fetcher.Factory<Cover> {
@@ -47,7 +47,7 @@ class RoundedRectTransformation(
@Px private val topLeft: Float = 0f, @Px private val topLeft: Float = 0f,
@Px private val topRight: Float = 0f, @Px private val topRight: Float = 0f,
@Px private val bottomLeft: Float = 0f, @Px private val bottomLeft: Float = 0f,
@Px private val bottomRight: Float = 0f @Px private val bottomRight: Float = 0f,
) : Transformation() { ) : Transformation() {
constructor(@Px radius: Float) : this(radius, radius, radius, radius) constructor(@Px radius: Float) : this(radius, radius, radius, radius)
@@ -69,7 +69,8 @@ class RoundedRectTransformation(
createBitmap( createBitmap(
outputWidth, outputWidth,
outputHeight, outputHeight,
requireNotNull(input.config) { "unsupported bitmap format" }) requireNotNull(input.config) { "unsupported bitmap format" },
)
output.applyCanvas { output.applyCanvas {
drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR) drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR)
@@ -80,7 +81,8 @@ class RoundedRectTransformation(
srcHeight = input.height, srcHeight = input.height,
dstWidth = outputWidth, dstWidth = outputWidth,
dstHeight = outputHeight, dstHeight = outputHeight,
scale = Scale.FILL) scale = Scale.FILL,
)
.toFloat() .toFloat()
val dx = (outputWidth - multiplier * input.width) / 2 val dx = (outputWidth - multiplier * input.width) / 2
val dy = (outputHeight - multiplier * input.height) / 2 val dy = (outputHeight - multiplier * input.height) / 2
@@ -121,7 +123,8 @@ class RoundedRectTransformation(
srcHeight = input.height, srcHeight = input.height,
dstWidth = size.width.pxOrElse { Int.MIN_VALUE }, dstWidth = size.width.pxOrElse { Int.MIN_VALUE },
dstHeight = size.height.pxOrElse { Int.MIN_VALUE }, dstHeight = size.height.pxOrElse { Int.MIN_VALUE },
scale = Scale.FIT) scale = Scale.FIT,
)
val outputWidth = (multiplier * input.width).roundToInt() val outputWidth = (multiplier * input.width).roundToInt()
val outputHeight = (multiplier * input.height).roundToInt() val outputHeight = (multiplier * input.height).roundToInt()
return outputWidth to outputHeight return outputWidth to outputHeight
@@ -64,7 +64,10 @@ class SettingCoversImpl @Inject constructor(private val imageSettings: ImageSett
val revisionedTranscoding = RevisionedTranscoding(revision, transcoding) val revisionedTranscoding = RevisionedTranscoding(revision, transcoding)
val storedCovers = val storedCovers =
MutableStoredCovers( MutableStoredCovers(
EmbeddedCovers(CoverIdentifier.md5()), coverStorage, revisionedTranscoding) EmbeddedCovers(CoverIdentifier.md5()),
coverStorage,
revisionedTranscoding,
)
val fsCovers = MutableFSCovers(context) val fsCovers = MutableFSCovers(context)
return MutableChainedCovers(storedCovers, fsCovers) return MutableChainedCovers(storedCovers, fsCovers)
} }
@@ -68,8 +68,8 @@ class ListSettingsImpl @Inject constructor(@ApplicationContext val context: Cont
override var songSort: Sort override var songSort: Sort
get() = get() =
Sort.fromIntCode( Sort.fromIntCode(
sharedPreferences.getInt(getString(R.string.set_key_songs_sort), Int.MIN_VALUE)) sharedPreferences.getInt(getString(R.string.set_key_songs_sort), Int.MIN_VALUE)
?: Sort(Sort.Mode.ByName, Sort.Direction.ASCENDING) ) ?: Sort(Sort.Mode.ByName, Sort.Direction.ASCENDING)
set(value) { set(value) {
sharedPreferences.edit { sharedPreferences.edit {
putInt(getString(R.string.set_key_songs_sort), value.intCode) putInt(getString(R.string.set_key_songs_sort), value.intCode)
@@ -80,8 +80,8 @@ class ListSettingsImpl @Inject constructor(@ApplicationContext val context: Cont
override var albumSort: Sort override var albumSort: Sort
get() = get() =
Sort.fromIntCode( Sort.fromIntCode(
sharedPreferences.getInt(getString(R.string.set_key_albums_sort), Int.MIN_VALUE)) sharedPreferences.getInt(getString(R.string.set_key_albums_sort), Int.MIN_VALUE)
?: Sort(Sort.Mode.ByName, Sort.Direction.ASCENDING) ) ?: Sort(Sort.Mode.ByName, Sort.Direction.ASCENDING)
set(value) { set(value) {
sharedPreferences.edit { sharedPreferences.edit {
putInt(getString(R.string.set_key_albums_sort), value.intCode) putInt(getString(R.string.set_key_albums_sort), value.intCode)
@@ -92,8 +92,8 @@ class ListSettingsImpl @Inject constructor(@ApplicationContext val context: Cont
override var artistSort: Sort override var artistSort: Sort
get() = get() =
Sort.fromIntCode( Sort.fromIntCode(
sharedPreferences.getInt(getString(R.string.set_key_artists_sort), Int.MIN_VALUE)) sharedPreferences.getInt(getString(R.string.set_key_artists_sort), Int.MIN_VALUE)
?: Sort(Sort.Mode.ByName, Sort.Direction.ASCENDING) ) ?: Sort(Sort.Mode.ByName, Sort.Direction.ASCENDING)
set(value) { set(value) {
sharedPreferences.edit { sharedPreferences.edit {
putInt(getString(R.string.set_key_artists_sort), value.intCode) putInt(getString(R.string.set_key_artists_sort), value.intCode)
@@ -104,8 +104,8 @@ class ListSettingsImpl @Inject constructor(@ApplicationContext val context: Cont
override var genreSort: Sort override var genreSort: Sort
get() = get() =
Sort.fromIntCode( Sort.fromIntCode(
sharedPreferences.getInt(getString(R.string.set_key_genres_sort), Int.MIN_VALUE)) sharedPreferences.getInt(getString(R.string.set_key_genres_sort), Int.MIN_VALUE)
?: Sort(Sort.Mode.ByName, Sort.Direction.ASCENDING) ) ?: Sort(Sort.Mode.ByName, Sort.Direction.ASCENDING)
set(value) { set(value) {
sharedPreferences.edit { sharedPreferences.edit {
putInt(getString(R.string.set_key_genres_sort), value.intCode) putInt(getString(R.string.set_key_genres_sort), value.intCode)
@@ -116,8 +116,8 @@ class ListSettingsImpl @Inject constructor(@ApplicationContext val context: Cont
override var playlistSort: Sort override var playlistSort: Sort
get() = get() =
Sort.fromIntCode( Sort.fromIntCode(
sharedPreferences.getInt(getString(R.string.set_key_playlists_sort), Int.MIN_VALUE)) sharedPreferences.getInt(getString(R.string.set_key_playlists_sort), Int.MIN_VALUE)
?: Sort(Sort.Mode.ByName, Sort.Direction.ASCENDING) ) ?: Sort(Sort.Mode.ByName, Sort.Direction.ASCENDING)
set(value) { set(value) {
sharedPreferences.edit { sharedPreferences.edit {
putInt(getString(R.string.set_key_playlists_sort), value.intCode) putInt(getString(R.string.set_key_playlists_sort), value.intCode)
@@ -129,8 +129,10 @@ class ListSettingsImpl @Inject constructor(@ApplicationContext val context: Cont
get() = get() =
Sort.fromIntCode( Sort.fromIntCode(
sharedPreferences.getInt( sharedPreferences.getInt(
getString(R.string.set_key_album_songs_sort), Int.MIN_VALUE)) getString(R.string.set_key_album_songs_sort),
?: Sort(Sort.Mode.ByDisc, Sort.Direction.ASCENDING) Int.MIN_VALUE,
)
) ?: Sort(Sort.Mode.ByDisc, Sort.Direction.ASCENDING)
set(value) { set(value) {
sharedPreferences.edit { sharedPreferences.edit {
putInt(getString(R.string.set_key_album_songs_sort), value.intCode) putInt(getString(R.string.set_key_album_songs_sort), value.intCode)
@@ -142,8 +144,10 @@ class ListSettingsImpl @Inject constructor(@ApplicationContext val context: Cont
get() = get() =
Sort.fromIntCode( Sort.fromIntCode(
sharedPreferences.getInt( sharedPreferences.getInt(
getString(R.string.set_key_artist_songs_sort), Int.MIN_VALUE)) getString(R.string.set_key_artist_songs_sort),
?: Sort(Sort.Mode.ByDate, Sort.Direction.DESCENDING) Int.MIN_VALUE,
)
) ?: Sort(Sort.Mode.ByDate, Sort.Direction.DESCENDING)
set(value) { set(value) {
sharedPreferences.edit { sharedPreferences.edit {
putInt(getString(R.string.set_key_artist_songs_sort), value.intCode) putInt(getString(R.string.set_key_artist_songs_sort), value.intCode)
@@ -155,8 +159,10 @@ class ListSettingsImpl @Inject constructor(@ApplicationContext val context: Cont
get() = get() =
Sort.fromIntCode( Sort.fromIntCode(
sharedPreferences.getInt( sharedPreferences.getInt(
getString(R.string.set_key_genre_songs_sort), Int.MIN_VALUE)) getString(R.string.set_key_genre_songs_sort),
?: Sort(Sort.Mode.ByName, Sort.Direction.ASCENDING) Int.MIN_VALUE,
)
) ?: Sort(Sort.Mode.ByName, Sort.Direction.ASCENDING)
set(value) { set(value) {
sharedPreferences.edit { sharedPreferences.edit {
putInt(getString(R.string.set_key_genre_songs_sort), value.intCode) putInt(getString(R.string.set_key_genre_songs_sort), value.intCode)
@@ -98,7 +98,7 @@ interface EditClickListListener<in T> : ClickableListListener<T>, EditableListLi
item: T, item: T,
viewHolder: RecyclerView.ViewHolder, viewHolder: RecyclerView.ViewHolder,
bodyView: View = viewHolder.itemView, bodyView: View = viewHolder.itemView,
dragHandle: View dragHandle: View,
) { ) {
bind(item, viewHolder, bodyView) bind(item, viewHolder, bodyView)
bind(viewHolder, dragHandle) bind(viewHolder, dragHandle)
@@ -138,7 +138,7 @@ interface SelectableListListener<in T> : ClickableListListener<T> {
item: T, item: T,
viewHolder: RecyclerView.ViewHolder, viewHolder: RecyclerView.ViewHolder,
bodyView: View = viewHolder.itemView, bodyView: View = viewHolder.itemView,
menuButton: View menuButton: View,
) { ) {
bind(item, viewHolder, bodyView) bind(item, viewHolder, bodyView)
// Map long clicks to the selection listener. // Map long clicks to the selection listener.
@@ -39,9 +39,11 @@ abstract class FlexibleListAdapter<T, VH : RecyclerView.ViewHolder>(
@Suppress("LeakingThis") private val differ = FlexibleListDiffer(this, diffCallback) @Suppress("LeakingThis") private val differ = FlexibleListDiffer(this, diffCallback)
final override fun getItemCount() = differ.currentList.size final override fun getItemCount() = differ.currentList.size
/** The current list stored by the adapter's differ instance. */ /** The current list stored by the adapter's differ instance. */
val currentList: List<T> val currentList: List<T>
get() = differ.currentList get() = differ.currentList
/** @see currentList */ /** @see currentList */
fun getItem(at: Int) = differ.currentList[at] fun getItem(at: Int) = differ.currentList[at]
@@ -55,7 +57,7 @@ abstract class FlexibleListAdapter<T, VH : RecyclerView.ViewHolder>(
fun update( fun update(
newList: List<T>, newList: List<T>,
instructions: UpdateInstructions?, instructions: UpdateInstructions?,
callback: (() -> Unit)? = null callback: (() -> Unit)? = null,
) { ) {
L.d("Updating list to ${newList.size} items with $instructions") L.d("Updating list to ${newList.size} items with $instructions")
differ.update(newList, instructions, callback) differ.update(newList, instructions, callback)
@@ -111,7 +113,7 @@ sealed interface UpdateInstructions {
*/ */
private class FlexibleListDiffer<T>( private class FlexibleListDiffer<T>(
adapter: RecyclerView.Adapter<*>, adapter: RecyclerView.Adapter<*>,
diffCallback: DiffUtil.ItemCallback<T> diffCallback: DiffUtil.ItemCallback<T>,
) { ) {
private val updateCallback = AdapterListUpdateCallback(adapter) private val updateCallback = AdapterListUpdateCallback(adapter)
private val config = AsyncDifferConfig.Builder(diffCallback).build() private val config = AsyncDifferConfig.Builder(diffCallback).build()
@@ -167,7 +169,7 @@ private class FlexibleListDiffer<T>(
oldList: List<T>, oldList: List<T>,
newList: List<T>, newList: List<T>,
runGeneration: Int, runGeneration: Int,
callback: (() -> Unit)? callback: (() -> Unit)?,
) { ) {
// fast simple remove all // fast simple remove all
if (newList.isEmpty()) { if (newList.isEmpty()) {
@@ -204,7 +206,7 @@ private class FlexibleListDiffer<T>(
override fun areItemsTheSame( override fun areItemsTheSame(
oldItemPosition: Int, oldItemPosition: Int,
newItemPosition: Int newItemPosition: Int,
): Boolean { ): Boolean {
val oldItem: T? = oldList[oldItemPosition] val oldItem: T? = oldList[oldItemPosition]
val newItem: T? = newList[newItemPosition] val newItem: T? = newList[newItemPosition]
@@ -216,7 +218,7 @@ private class FlexibleListDiffer<T>(
override fun areContentsTheSame( override fun areContentsTheSame(
oldItemPosition: Int, oldItemPosition: Int,
newItemPosition: Int newItemPosition: Int,
): Boolean { ): Boolean {
val oldItem: T? = oldList[oldItemPosition] val oldItem: T? = oldList[oldItemPosition]
val newItem: T? = newList[newItemPosition] val newItem: T? = newList[newItemPosition]
@@ -231,7 +233,7 @@ private class FlexibleListDiffer<T>(
override fun getChangePayload( override fun getChangePayload(
oldItemPosition: Int, oldItemPosition: Int,
newItemPosition: Int newItemPosition: Int,
): Any? { ): Any? {
val oldItem: T? = oldList[oldItemPosition] val oldItem: T? = oldList[oldItemPosition]
val newItem: T? = newList[newItemPosition] val newItem: T? = newList[newItemPosition]
@@ -240,7 +242,8 @@ private class FlexibleListDiffer<T>(
} }
throw AssertionError() throw AssertionError()
} }
}) }
)
mainThreadExecutor.execute { mainThreadExecutor.execute {
if (maxScheduledGeneration == runGeneration) { if (maxScheduledGeneration == runGeneration) {
@@ -51,6 +51,7 @@ abstract class PlayingIndicatorAdapter<T, VH : RecyclerView.ViewHolder>(
onBindViewHolder(holder, position) onBindViewHolder(holder, position)
} }
} }
/** /**
* Update the currently playing item in the list. * Update the currently playing item in the list.
* *
@@ -64,7 +64,7 @@ sealed interface Menu {
val res: Int, val res: Int,
val songUid: Music.UID, val songUid: Music.UID,
val playWithCode: Int, val playWithCode: Int,
val playWithUid: Music.UID? val playWithUid: Music.UID?,
) : Menu.Parcel ) : Menu.Parcel
} }
@@ -166,7 +166,8 @@ class ArtistMenuDialogFragment : MenuDialogFragment<Menu.ForArtist>() {
R.id.action_play_next, R.id.action_play_next,
R.id.action_queue_add, R.id.action_queue_add,
R.id.action_playlist_add, R.id.action_playlist_add,
R.id.action_share) R.id.action_share,
)
} else { } else {
setOf() setOf()
} }
@@ -188,7 +189,8 @@ class ArtistMenuDialogFragment : MenuDialogFragment<Menu.ForArtist>() {
context.getPlural(R.plurals.fmt_song_count, menu.artist.songs.size) context.getPlural(R.plurals.fmt_song_count, menu.artist.songs.size)
} else { } else {
getString(R.string.def_song_count) getString(R.string.def_song_count)
}) },
)
} }
override fun onClick(item: MenuItem, menu: Menu.ForArtist) { override fun onClick(item: MenuItem, menu: Menu.ForArtist) {
@@ -239,7 +241,8 @@ class GenreMenuDialogFragment : MenuDialogFragment<Menu.ForGenre>() {
getString( getString(
R.string.fmt_two, R.string.fmt_two,
context.getPlural(R.plurals.fmt_artist_count, menu.genre.artists.size), context.getPlural(R.plurals.fmt_artist_count, menu.genre.artists.size),
context.getPlural(R.plurals.fmt_song_count, menu.genre.songs.size)) context.getPlural(R.plurals.fmt_song_count, menu.genre.songs.size),
)
} }
override fun onClick(item: MenuItem, menu: Menu.ForGenre) { override fun onClick(item: MenuItem, menu: Menu.ForGenre) {
@@ -290,7 +293,8 @@ class PlaylistMenuDialogFragment : MenuDialogFragment<Menu.ForPlaylist>() {
R.id.action_queue_add, R.id.action_queue_add,
R.id.action_playlist_add, R.id.action_playlist_add,
R.id.action_export, R.id.action_export,
R.id.action_share) R.id.action_share,
)
} else { } else {
setOf() setOf()
} }
@@ -352,7 +356,10 @@ class SelectionMenuDialogFragment : MenuDialogFragment<Menu.ForSelection>() {
override fun updateMenu(binding: DialogMenuBinding, menu: Menu.ForSelection) { override fun updateMenu(binding: DialogMenuBinding, menu: Menu.ForSelection) {
binding.menuCover.bind( binding.menuCover.bind(
menu.songs, getString(R.string.desc_selection_image), R.drawable.ic_song_24) menu.songs,
getString(R.string.desc_selection_image),
R.drawable.ic_song_24,
)
binding.menuType.text = getString(R.string.lbl_selection) binding.menuType.text = getString(R.string.lbl_selection)
binding.menuName.text = binding.menuName.text =
requireContext().getPlural(R.plurals.fmt_song_count, menu.songs.size) requireContext().getPlural(R.plurals.fmt_song_count, menu.songs.size)
@@ -85,12 +85,14 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
ViewGroup.getChildMeasureSpec( ViewGroup.getChildMeasureSpec(
MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
0, 0,
divider.layoutParams.width) divider.layoutParams.width,
)
val heightMeasureSpec = val heightMeasureSpec =
ViewGroup.getChildMeasureSpec( ViewGroup.getChildMeasureSpec(
MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY),
0, 0,
divider.layoutParams.height) divider.layoutParams.height,
)
divider.measure(widthMeasureSpec, heightMeasureSpec) divider.measure(widthMeasureSpec, heightMeasureSpec)
} }
@@ -114,7 +114,8 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
TextViewCompat.setTextAppearance(this, R.style.TextAppearance_Auxio_HeadlineMedium) TextViewCompat.setTextAppearance(this, R.style.TextAppearance_Auxio_HeadlineMedium)
setTextColor( setTextColor(
context.getAttrColorCompat(com.google.android.material.R.attr.colorOnSecondary)) context.getAttrColorCompat(com.google.android.material.R.attr.colorOnSecondary)
)
ellipsize = TextUtils.TruncateAt.MIDDLE ellipsize = TextUtils.TruncateAt.MIDDLE
gravity = Gravity.CENTER gravity = Gravity.CENTER
includeFontPadding = false includeFontPadding = false
@@ -129,7 +130,9 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
updatePaddingRelative(start = paddingStart, end = paddingEnd) updatePaddingRelative(start = paddingStart, end = paddingEnd)
layoutParams = layoutParams =
FrameLayout.LayoutParams( FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
)
.apply { .apply {
marginEnd = context.getDimenPixels(R.dimen.size_touchable_small) marginEnd = context.getDimenPixels(R.dimen.size_touchable_small)
gravity = Gravity.CENTER_HORIZONTAL or Gravity.TOP gravity = Gravity.CENTER_HORIZONTAL or Gravity.TOP
@@ -208,7 +211,8 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
override fun onDraw(canvas: Canvas, parent: RecyclerView, state: State) { override fun onDraw(canvas: Canvas, parent: RecyclerView, state: State) {
onPreDraw() onPreDraw()
} }
}) }
)
// We use a listener instead of overriding onTouchEvent so that we don't conflict with // We use a listener instead of overriding onTouchEvent so that we don't conflict with
// RecyclerView touch events. // RecyclerView touch events.
@@ -220,11 +224,12 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
override fun onInterceptTouchEvent( override fun onInterceptTouchEvent(
recyclerView: RecyclerView, recyclerView: RecyclerView,
event: MotionEvent event: MotionEvent,
): Boolean { ): Boolean {
return onItemTouch(event) return onItemTouch(event)
} }
}) }
)
} }
// --- RECYCLERVIEW EVENT MANAGEMENT --- // --- RECYCLERVIEW EVENT MANAGEMENT ---
@@ -235,7 +240,8 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
thumbView.layoutDirection = layoutDirection thumbView.layoutDirection = layoutDirection
thumbView.measure( thumbView.measure(
MeasureSpec.makeMeasureSpec(thumbWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(thumbWidth, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(thumbHeight, MeasureSpec.EXACTLY)) MeasureSpec.makeMeasureSpec(thumbHeight, MeasureSpec.EXACTLY),
)
val thumbTop = thumbPadding.top + thumbOffset val thumbTop = thumbPadding.top + thumbOffset
val thumbLeft = val thumbLeft =
if (isRtl) { if (isRtl) {
@@ -278,7 +284,8 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
thumbWidth + thumbWidth +
popupLayoutParams.leftMargin + popupLayoutParams.leftMargin +
popupLayoutParams.rightMargin, popupLayoutParams.rightMargin,
popupLayoutParams.width) popupLayoutParams.width,
)
val heightMeasureSpec = val heightMeasureSpec =
ViewGroup.getChildMeasureSpec( ViewGroup.getChildMeasureSpec(
@@ -287,7 +294,8 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
thumbPadding.bottom + thumbPadding.bottom +
popupLayoutParams.topMargin + popupLayoutParams.topMargin +
popupLayoutParams.bottomMargin, popupLayoutParams.bottomMargin,
popupLayoutParams.height) popupLayoutParams.height,
)
popupView.measure(widthMeasureSpec, heightMeasureSpec) popupView.measure(widthMeasureSpec, heightMeasureSpec)
if (showingPopup) { if (showingPopup) {
@@ -311,7 +319,8 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
(thumbTop + thumbAnchorY - popupAnchorY) (thumbTop + thumbAnchorY - popupAnchorY)
.coerceAtLeast(thumbPadding.top + popupLayoutParams.topMargin) .coerceAtLeast(thumbPadding.top + popupLayoutParams.topMargin)
.coerceAtMost( .coerceAtMost(
height - thumbPadding.bottom - popupLayoutParams.bottomMargin - popupHeight) height - thumbPadding.bottom - popupLayoutParams.bottomMargin - popupHeight
)
popupView.layout(popupLeft, popupTop, popupLeft + popupWidth, popupTop + popupHeight) popupView.layout(popupLeft, popupTop, popupLeft + popupWidth, popupTop + popupHeight)
} }
@@ -383,9 +392,11 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
} }
} }
MotionEvent.ACTION_MOVE -> { MotionEvent.ACTION_MOVE -> {
if (!dragging && if (
thumbView.isUnder(downX, thumbView.top.toFloat(), minTouchTargetSize) && !dragging &&
abs(eventY - downY) > touchSlop) { thumbView.isUnder(downX, thumbView.top.toFloat(), minTouchTargetSize) &&
abs(eventY - downY) > touchSlop
) {
if (thumbView.isUnder(downX, downY, minTouchTargetSize)) { if (thumbView.isUnder(downX, downY, minTouchTargetSize)) {
dragStartY = lastY dragStartY = lastY
dragStartThumbOffset = thumbOffset dragStartThumbOffset = thumbOffset
@@ -487,7 +498,8 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
HapticFeedbackConstants.TEXT_HANDLE_MOVE HapticFeedbackConstants.TEXT_HANDLE_MOVE
} else { } else {
HapticFeedbackConstants.KEYBOARD_TAP HapticFeedbackConstants.KEYBOARD_TAP
}) }
)
} }
// --- LAYOUT STATE --- // --- LAYOUT STATE ---
@@ -48,12 +48,13 @@ abstract class MaterialDragCallback : ItemTouchHelper.Callback() {
final override fun getMovementFlags( final override fun getMovementFlags(
recyclerView: RecyclerView, recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder viewHolder: RecyclerView.ViewHolder,
) = ) =
if (viewHolder is ViewHolder && viewHolder.enabled) { if (viewHolder is ViewHolder && viewHolder.enabled) {
makeFlag( makeFlag(
ItemTouchHelper.ACTION_STATE_DRAG, ItemTouchHelper.UP or ItemTouchHelper.DOWN) or ItemTouchHelper.ACTION_STATE_DRAG,
makeFlag(ItemTouchHelper.ACTION_STATE_SWIPE, ItemTouchHelper.START) ItemTouchHelper.UP or ItemTouchHelper.DOWN,
) or makeFlag(ItemTouchHelper.ACTION_STATE_SWIPE, ItemTouchHelper.START)
} else { } else {
0 0
} }
@@ -63,18 +64,24 @@ abstract class MaterialDragCallback : ItemTouchHelper.Callback() {
viewSize: Int, viewSize: Int,
viewSizeOutOfBounds: Int, viewSizeOutOfBounds: Int,
totalSize: Int, totalSize: Int,
msSinceStartScroll: Long msSinceStartScroll: Long,
): Int { ): Int {
// Clamp the scroll speed to prevent the lists from freaking out // Clamp the scroll speed to prevent the lists from freaking out
// Adapted from NewPipe: https://github.com/TeamNewPipe/NewPipe // Adapted from NewPipe: https://github.com/TeamNewPipe/NewPipe
val standardSpeed = val standardSpeed =
super.interpolateOutOfBoundsScroll( super.interpolateOutOfBoundsScroll(
recyclerView, viewSize, viewSizeOutOfBounds, totalSize, msSinceStartScroll) recyclerView,
viewSize,
viewSizeOutOfBounds,
totalSize,
msSinceStartScroll,
)
val clampedAbsVelocity = val clampedAbsVelocity =
max( max(
MINIMUM_INITIAL_DRAG_VELOCITY, MINIMUM_INITIAL_DRAG_VELOCITY,
min(abs(standardSpeed), MAXIMUM_INITIAL_DRAG_VELOCITY)) min(abs(standardSpeed), MAXIMUM_INITIAL_DRAG_VELOCITY),
)
return clampedAbsVelocity * sign(viewSizeOutOfBounds.toDouble()).toInt() return clampedAbsVelocity * sign(viewSizeOutOfBounds.toDouble()).toInt()
} }
@@ -86,7 +93,7 @@ abstract class MaterialDragCallback : ItemTouchHelper.Callback() {
dX: Float, dX: Float,
dY: Float, dY: Float,
actionState: Int, actionState: Int,
isCurrentlyActive: Boolean isCurrentlyActive: Boolean,
) { ) {
val holder = viewHolder as ViewHolder val holder = viewHolder as ViewHolder
@@ -101,7 +108,8 @@ abstract class MaterialDragCallback : ItemTouchHelper.Callback() {
.animate() .animate()
.translationZ(elevation) .translationZ(elevation)
.setDuration( .setDuration(
recyclerView.context.getInteger(R.integer.anim_fade_exit_duration).toLong()) recyclerView.context.getInteger(R.integer.anim_fade_exit_duration).toLong()
)
.setUpdateListener { .setUpdateListener {
bg.alpha = ((holder.root.translationZ / elevation) * 255).toInt() bg.alpha = ((holder.root.translationZ / elevation) * 255).toInt()
} }
@@ -143,7 +151,8 @@ abstract class MaterialDragCallback : ItemTouchHelper.Callback() {
.animate() .animate()
.translationZ(0f) .translationZ(0f)
.setDuration( .setDuration(
recyclerView.context.getInteger(R.integer.anim_fade_exit_duration).toLong()) recyclerView.context.getInteger(R.integer.anim_fade_exit_duration).toLong()
)
.setUpdateListener { .setUpdateListener {
bg.alpha = ((holder.root.translationZ / elevation) * 255).toInt() bg.alpha = ((holder.root.translationZ / elevation) * 255).toInt()
} }
@@ -175,7 +175,8 @@ class ArtistViewHolder private constructor(private val binding: ItemParentBindin
binding.context.getPlural(R.plurals.fmt_song_count, artist.songs.size) binding.context.getPlural(R.plurals.fmt_song_count, artist.songs.size)
} else { } else {
binding.context.getString(R.string.def_song_count) binding.context.getString(R.string.def_song_count)
}) },
)
} }
override fun updatePlayingIndicator(isActive: Boolean, isPlaying: Boolean) { override fun updatePlayingIndicator(isActive: Boolean, isPlaying: Boolean) {
@@ -232,7 +233,8 @@ class GenreViewHolder private constructor(private val binding: ItemParentBinding
binding.context.getString( binding.context.getString(
R.string.fmt_two, R.string.fmt_two,
binding.context.getPlural(R.plurals.fmt_artist_count, genre.artists.size), binding.context.getPlural(R.plurals.fmt_artist_count, genre.artists.size),
binding.context.getPlural(R.plurals.fmt_song_count, genre.songs.size)) binding.context.getPlural(R.plurals.fmt_song_count, genre.songs.size),
)
} }
override fun updatePlayingIndicator(isActive: Boolean, isPlaying: Boolean) { override fun updatePlayingIndicator(isActive: Boolean, isPlaying: Boolean) {
@@ -394,7 +394,7 @@ data class Sort(val mode: Mode, val direction: Direction) {
/** The direction to sort items in. */ /** The direction to sort items in. */
enum class Direction { enum class Direction {
ASCENDING, ASCENDING,
DESCENDING DESCENDING,
} }
companion object { companion object {
@@ -89,7 +89,7 @@ abstract class SortDialog :
override fun onButtonChecked( override fun onButtonChecked(
group: MaterialButtonToggleGroup?, group: MaterialButtonToggleGroup?,
checkedId: Int, checkedId: Int,
isChecked: Boolean isChecked: Boolean,
) { ) {
updateButtons() updateButtons()
} }
@@ -244,7 +244,7 @@ constructor(
private val cache: MutableCache, private val cache: MutableCache,
private val storedPlaylists: StoredPlaylists, private val storedPlaylists: StoredPlaylists,
private val settingCovers: SettingCovers, private val settingCovers: SettingCovers,
private val musicSettings: MusicSettings private val musicSettings: MusicSettings,
) : MusicRepository { ) : MusicRepository {
private val updateListeners = mutableListOf<MusicRepository.UpdateListener>() private val updateListeners = mutableListOf<MusicRepository.UpdateListener>()
private val indexingListeners = mutableListOf<MusicRepository.IndexingListener>() private val indexingListeners = mutableListOf<MusicRepository.IndexingListener>()
@@ -117,7 +117,9 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont
get() { get() {
val mode = val mode =
sharedPreferences.getInt( sharedPreferences.getInt(
getString(R.string.set_key_locations_mode), IntegerTable.LOCATION_MODE_SAF) getString(R.string.set_key_locations_mode),
IntegerTable.LOCATION_MODE_SAF,
)
return LocationMode.fromInt(mode) ?: LocationMode.SAF return LocationMode.fromInt(mode) ?: LocationMode.SAF
} }
set(value) { set(value) {
@@ -131,18 +133,24 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont
get() { get() {
val locations = val locations =
unlikelyToBeNull( unlikelyToBeNull(
sharedPreferences.getString( sharedPreferences.getString(getString(R.string.set_key_music_locations), "")
getString(R.string.set_key_music_locations), "")) )
.toOpenedLocations() .toOpenedLocations()
val excludedLocations = val excludedLocations =
unlikelyToBeNull( unlikelyToBeNull(
sharedPreferences.getString( sharedPreferences.getString(
getString(R.string.set_key_excluded_locations), "")) getString(R.string.set_key_excluded_locations),
"",
)
)
.toUnopenedLocations() .toUnopenedLocations()
val withHidden = val withHidden =
sharedPreferences.getBoolean(getString(R.string.set_key_with_hidden), false) sharedPreferences.getBoolean(getString(R.string.set_key_with_hidden), false)
return SAF.Query( return SAF.Query(
source = locations, exclude = excludedLocations, withHidden = withHidden) source = locations,
exclude = excludedLocations,
withHidden = withHidden,
)
} }
set(value) { set(value) {
sharedPreferences.edit { sharedPreferences.edit {
@@ -157,11 +165,16 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont
get() { get() {
val filterMode = val filterMode =
sharedPreferences.getInt( sharedPreferences.getInt(
getString(R.string.set_key_filter_mode), IntegerTable.FILTER_MODE_EXCLUDE) getString(R.string.set_key_filter_mode),
IntegerTable.FILTER_MODE_EXCLUDE,
)
val filteredLocations = val filteredLocations =
unlikelyToBeNull( unlikelyToBeNull(
sharedPreferences.getString( sharedPreferences.getString(
getString(R.string.set_key_filtered_locations), "")) getString(R.string.set_key_filtered_locations),
"",
)
)
.toUnopenedLocations() .toUnopenedLocations()
val excludeNonMusic = val excludeNonMusic =
sharedPreferences.getBoolean(getString(R.string.set_key_exclude_non_music), true) sharedPreferences.getBoolean(getString(R.string.set_key_exclude_non_music), true)
@@ -173,7 +186,8 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont
else -> MediaStore.FilterMode.EXCLUDE else -> MediaStore.FilterMode.EXCLUDE
}, },
filtered = filteredLocations, filtered = filteredLocations,
excludeNonMusic = excludeNonMusic) excludeNonMusic = excludeNonMusic,
)
} }
set(value) { set(value) {
sharedPreferences.edit { sharedPreferences.edit {
@@ -184,7 +198,9 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont
} }
putInt(getString(R.string.set_key_filter_mode), filterMode) putInt(getString(R.string.set_key_filter_mode), filterMode)
putString( putString(
getString(R.string.set_key_filtered_locations), value.filtered.stringify()) getString(R.string.set_key_filtered_locations),
value.filtered.stringify(),
)
putBoolean(getString(R.string.set_key_exclude_non_music), value.excludeNonMusic) putBoolean(getString(R.string.set_key_exclude_non_music), value.excludeNonMusic)
apply() apply()
} }
@@ -215,7 +231,7 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont
getString(R.string.set_key_filtered_locations), getString(R.string.set_key_filtered_locations),
getString(R.string.set_key_exclude_non_music), getString(R.string.set_key_exclude_non_music),
getString(R.string.set_key_separators), getString(R.string.set_key_separators),
getString(R.string.set_key_auto_sort_names), -> { getString(R.string.set_key_auto_sort_names) -> {
L.d("Dispatching indexing setting change for $key") L.d("Dispatching indexing setting change for $key")
listener.onIndexingSettingChanged() listener.onIndexingSettingChanged()
} }
@@ -53,7 +53,7 @@ class MusicViewModel
constructor( constructor(
@ApplicationContext context: Context, @ApplicationContext context: Context,
private val listSettings: ListSettings, private val listSettings: ListSettings,
private val musicRepository: MusicRepository private val musicRepository: MusicRepository,
) : ViewModel(), MusicRepository.UpdateListener, MusicRepository.IndexingListener { ) : ViewModel(), MusicRepository.UpdateListener, MusicRepository.IndexingListener {
private val externalPlaylistManager = ExternalPlaylistManager.from(context) private val externalPlaylistManager = ExternalPlaylistManager.from(context)
@@ -102,6 +102,7 @@ constructor(
library.genres.size, library.genres.size,
library.songs.sumOf { it.durationMs }, library.songs.sumOf { it.durationMs },
library.songs.sumOf { it.size }) library.songs.sumOf { it.size })
)
L.d("Updated statistics: ${_statistics.value}") L.d("Updated statistics: ${_statistics.value}")
} }
@@ -132,7 +133,7 @@ constructor(
fun createPlaylist( fun createPlaylist(
name: String? = null, name: String? = null,
songs: List<Song> = listOf(), songs: List<Song> = listOf(),
reason: PlaylistDecision.New.Reason = PlaylistDecision.New.Reason.NEW reason: PlaylistDecision.New.Reason = PlaylistDecision.New.Reason.NEW,
) { ) {
if (name != null) { if (name != null) {
L.d("Creating $name with ${songs.size} songs]") L.d("Creating $name with ${songs.size} songs]")
@@ -190,7 +191,9 @@ constructor(
target, target,
importedPlaylist.name, importedPlaylist.name,
songs, songs,
PlaylistDecision.Rename.Reason.IMPORT)) PlaylistDecision.Rename.Reason.IMPORT,
)
)
} else { } else {
musicRepository.rewritePlaylist(target, songs) musicRepository.rewritePlaylist(target, songs)
_playlistMessage.put(PlaylistMessage.ImportSuccess) _playlistMessage.put(PlaylistMessage.ImportSuccess)
@@ -198,7 +201,11 @@ constructor(
} else { } else {
_playlistDecision.put( _playlistDecision.put(
PlaylistDecision.New( PlaylistDecision.New(
songs, importedPlaylist.name, PlaylistDecision.New.Reason.IMPORT)) songs,
importedPlaylist.name,
PlaylistDecision.New.Reason.IMPORT,
)
)
} }
} }
} else { } else {
@@ -243,7 +250,7 @@ constructor(
playlist: Playlist, playlist: Playlist,
name: String? = null, name: String? = null,
applySongs: List<Song> = listOf(), applySongs: List<Song> = listOf(),
reason: PlaylistDecision.Rename.Reason = PlaylistDecision.Rename.Reason.ACTION reason: PlaylistDecision.Rename.Reason = PlaylistDecision.Rename.Reason.ACTION,
) { ) {
if (name != null) { if (name != null) {
L.d("Renaming $playlist to $name") L.d("Renaming $playlist to $name")
@@ -388,7 +395,7 @@ sealed interface PlaylistDecision {
enum class Reason { enum class Reason {
NEW, NEW,
ADD, ADD,
IMPORT IMPORT,
} }
} }
@@ -409,11 +416,11 @@ sealed interface PlaylistDecision {
val playlist: Playlist, val playlist: Playlist,
val template: String?, val template: String?,
val applySongs: List<Song>, val applySongs: List<Song>,
val reason: Reason val reason: Reason,
) : PlaylistDecision { ) : PlaylistDecision {
enum class Reason { enum class Reason {
ACTION, ACTION,
IMPORT IMPORT,
} }
} }
@@ -100,7 +100,11 @@ class AddToPlaylistDialog :
findNavController() findNavController()
.navigateSafe( .navigateSafe(
AddToPlaylistDialogDirections.newPlaylist( AddToPlaylistDialogDirections.newPlaylist(
songs.map { it.uid }.toTypedArray(), null, PlaylistDecision.New.Reason.ADD)) songs.map { it.uid }.toTypedArray(),
null,
PlaylistDecision.New.Reason.ADD,
)
)
} }
private fun updatePendingSongs(songs: List<Song>?) { private fun updatePendingSongs(songs: List<Song>?) {
@@ -58,7 +58,9 @@ class DeletePlaylistDialog : ViewBindingMaterialDialogFragment<DialogDeletePlayl
findNavController().navigateUp() findNavController().navigateUp()
// Now we can delete the playlist for-real this time. // Now we can delete the playlist for-real this time.
musicModel.deletePlaylist( musicModel.deletePlaylist(
unlikelyToBeNull(pickerModel.currentPlaylistToDelete.value), rude = true) unlikelyToBeNull(pickerModel.currentPlaylistToDelete.value),
rude = true,
)
} }
.setNegativeButton(R.string.lbl_cancel, null) .setNegativeButton(R.string.lbl_cancel, null)
} }
@@ -68,7 +70,7 @@ class DeletePlaylistDialog : ViewBindingMaterialDialogFragment<DialogDeletePlayl
override fun onBindingCreated( override fun onBindingCreated(
binding: DialogDeletePlaylistBinding, binding: DialogDeletePlaylistBinding,
savedInstanceState: Bundle? savedInstanceState: Bundle?,
) { ) {
super.onBindingCreated(binding, savedInstanceState) super.onBindingCreated(binding, savedInstanceState)
@@ -66,7 +66,7 @@ class ExportPlaylistDialog : ViewBindingMaterialDialogFragment<DialogPlaylistExp
override fun onBindingCreated( override fun onBindingCreated(
binding: DialogPlaylistExportBinding, binding: DialogPlaylistExportBinding,
savedInstanceState: Bundle? savedInstanceState: Bundle?,
) { ) {
// --- UI SETUP --- // --- UI SETUP ---
createDocumentLauncher = createDocumentLauncher =
@@ -93,7 +93,8 @@ class ExportPlaylistDialog : ViewBindingMaterialDialogFragment<DialogPlaylistExp
if (!isChecked) return@addOnButtonCheckedListener if (!isChecked) return@addOnButtonCheckedListener
val current = pickerModel.currentExportConfig.value val current = pickerModel.currentExportConfig.value
pickerModel.setExportConfig( pickerModel.setExportConfig(
current.copy(absolute = checkedId == R.id.export_absolute_paths)) current.copy(absolute = checkedId == R.id.export_absolute_paths)
)
} }
binding.exportWindowsPaths.setOnClickListener { _ -> binding.exportWindowsPaths.setOnClickListener { _ ->
@@ -142,7 +143,8 @@ class ExportPlaylistDialog : ViewBindingMaterialDialogFragment<DialogPlaylistExp
R.id.export_absolute_paths R.id.export_absolute_paths
} else { } else {
R.id.export_relative_paths R.id.export_relative_paths
}) }
)
if (config.absolute) { if (config.absolute) {
binding.exportRelativePaths.icon = null binding.exportRelativePaths.icon = null
binding.exportAbsolutePaths.setIconResource(R.drawable.ic_check_24) binding.exportAbsolutePaths.setIconResource(R.drawable.ic_check_24)
@@ -58,7 +58,8 @@ class NewPlaylistDialog : ViewBindingMaterialDialogFragment<DialogPlaylistNameBi
PlaylistDecision.New.Reason.NEW, PlaylistDecision.New.Reason.NEW,
PlaylistDecision.New.Reason.ADD -> R.string.lbl_new_playlist PlaylistDecision.New.Reason.ADD -> R.string.lbl_new_playlist
PlaylistDecision.New.Reason.IMPORT -> R.string.lbl_import_playlist PlaylistDecision.New.Reason.IMPORT -> R.string.lbl_import_playlist
}) }
)
.setPositiveButton(R.string.lbl_ok) { _, _ -> .setPositiveButton(R.string.lbl_ok) { _, _ ->
val pendingPlaylist = unlikelyToBeNull(pickerModel.currentPendingNewPlaylist.value) val pendingPlaylist = unlikelyToBeNull(pickerModel.currentPendingNewPlaylist.value)
val name = val name =
@@ -78,6 +78,7 @@ private constructor(private val binding: ItemNewPlaylistChoiceBinding) :
*/ */
fun from(parent: View) = fun from(parent: View) =
NewPlaylistFooterViewHolder( NewPlaylistFooterViewHolder(
ItemNewPlaylistChoiceBinding.inflate(parent.context.inflater)) ItemNewPlaylistChoiceBinding.inflate(parent.context.inflater)
)
} }
} }
@@ -37,7 +37,8 @@ import org.oxycblt.auxio.util.inflater
*/ */
class PlaylistChoiceAdapter(val listener: ClickableListListener<PlaylistChoice>) : class PlaylistChoiceAdapter(val listener: ClickableListListener<PlaylistChoice>) :
FlexibleListAdapter<PlaylistChoice, PlaylistChoiceViewHolder>( FlexibleListAdapter<PlaylistChoice, PlaylistChoiceViewHolder>(
PlaylistChoiceViewHolder.DIFF_CALLBACK) { PlaylistChoiceViewHolder.DIFF_CALLBACK
) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
PlaylistChoiceViewHolder.from(parent) PlaylistChoiceViewHolder.from(parent)
@@ -97,7 +97,8 @@ class PlaylistPickerViewModel @Inject constructor(private val musicRepository: M
pendingPlaylist.preferredName, pendingPlaylist.preferredName,
pendingPlaylist.songs.mapNotNull { library.findSong(it.uid) }, pendingPlaylist.songs.mapNotNull { library.findSong(it.uid) },
pendingPlaylist.template, pendingPlaylist.template,
pendingPlaylist.reason) pendingPlaylist.reason,
)
} }
L.d("Updated pending playlist: ${_currentPendingNewPlaylist.value?.preferredName}") L.d("Updated pending playlist: ${_currentPendingNewPlaylist.value?.preferredName}")
@@ -150,7 +151,7 @@ class PlaylistPickerViewModel @Inject constructor(private val musicRepository: M
context: Context, context: Context,
songUids: Array<Music.UID>, songUids: Array<Music.UID>,
template: String?, template: String?,
reason: PlaylistDecision.New.Reason reason: PlaylistDecision.New.Reason,
) { ) {
L.d("Opening ${songUids.size} songs to create a playlist from") L.d("Opening ${songUids.size} songs to create a playlist from")
val library = musicRepository.library ?: return val library = musicRepository.library ?: return
@@ -191,7 +192,7 @@ class PlaylistPickerViewModel @Inject constructor(private val musicRepository: M
playlistUid: Music.UID, playlistUid: Music.UID,
applySongUids: Array<Music.UID>, applySongUids: Array<Music.UID>,
template: String?, template: String?,
reason: PlaylistDecision.Rename.Reason reason: PlaylistDecision.Rename.Reason,
) { ) {
L.d("Opening playlist $playlistUid to rename") L.d("Opening playlist $playlistUid to rename")
val playlist = musicRepository.library?.findPlaylist(playlistUid) val playlist = musicRepository.library?.findPlaylist(playlistUid)
@@ -320,14 +321,14 @@ data class PendingNewPlaylist(
val preferredName: String, val preferredName: String,
val songs: List<Song>, val songs: List<Song>,
val template: String?, val template: String?,
val reason: PlaylistDecision.New.Reason val reason: PlaylistDecision.New.Reason,
) )
data class PendingRenamePlaylist( data class PendingRenamePlaylist(
val playlist: Playlist, val playlist: Playlist,
val applySongs: List<Song>, val applySongs: List<Song>,
val template: String?, val template: String?,
val reason: PlaylistDecision.Rename.Reason val reason: PlaylistDecision.Rename.Reason,
) )
/** /**
@@ -338,10 +339,13 @@ data class PendingRenamePlaylist(
sealed interface ChosenName { sealed interface ChosenName {
/** The current name is valid. */ /** The current name is valid. */
data class Valid(val value: String) : ChosenName data class Valid(val value: String) : ChosenName
/** The current name already exists. */ /** The current name already exists. */
data class AlreadyExists(val prior: String) : ChosenName data class AlreadyExists(val prior: String) : ChosenName
/** The current name is empty. */ /** The current name is empty. */
data object Empty : ChosenName data object Empty : ChosenName
/** The current name only consists of whitespace. */ /** The current name only consists of whitespace. */
data object Blank : ChosenName data object Blank : ChosenName
} }
@@ -61,7 +61,8 @@ class RenamePlaylistDialog : ViewBindingMaterialDialogFragment<DialogPlaylistNam
pendingRenamePlaylist.playlist, pendingRenamePlaylist.playlist,
chosenName.value, chosenName.value,
pendingRenamePlaylist.applySongs, pendingRenamePlaylist.applySongs,
pendingRenamePlaylist.reason) pendingRenamePlaylist.reason,
)
findNavController().navigateUp() findNavController().navigateUp()
} }
.setNegativeButton(R.string.lbl_cancel, null) .setNegativeButton(R.string.lbl_cancel, null)
@@ -79,7 +80,11 @@ class RenamePlaylistDialog : ViewBindingMaterialDialogFragment<DialogPlaylistNam
// --- VIEWMODEL SETUP --- // --- VIEWMODEL SETUP ---
musicModel.playlistDecision.consume() musicModel.playlistDecision.consume()
pickerModel.setPlaylistToRename( pickerModel.setPlaylistToRename(
args.playlistUid, args.applySongUids, args.template, args.reason) args.playlistUid,
args.applySongUids,
args.template,
args.reason,
)
collectImmediately(pickerModel.currentPendingRenamePlaylist, ::updatePlaylistToRename) collectImmediately(pickerModel.currentPendingRenamePlaylist, ::updatePlaylistToRename)
collectImmediately(pickerModel.chosenName, ::updateChosenName) collectImmediately(pickerModel.chosenName, ::updateChosenName)
} }
@@ -134,7 +134,8 @@ class LocationViewHolder<T : Location>(private val binding: ItemMusicLocationBin
*/ */
fun <T : Location> from(parent: ViewGroup) = fun <T : Location> from(parent: ViewGroup) =
LocationViewHolder<T>( LocationViewHolder<T>(
ItemMusicLocationBinding.inflate(parent.context.inflater, parent, false)) ItemMusicLocationBinding.inflate(parent.context.inflater, parent, false)
)
} }
} }
@@ -154,6 +155,7 @@ class EmptyLocationViewHolder(private val binding: ItemNoLocationsBinding) :
*/ */
fun from(parent: ViewGroup) = fun from(parent: ViewGroup) =
EmptyLocationViewHolder( EmptyLocationViewHolder(
ItemNoLocationsBinding.inflate(parent.context.inflater, parent, false)) ItemNoLocationsBinding.inflate(parent.context.inflater, parent, false)
)
} }
} }
@@ -100,7 +100,7 @@ class LocationsDialog : ViewBindingMaterialDialogFragment<DialogMusicLocationsBi
override fun onBindingCreated( override fun onBindingCreated(
binding: DialogMusicLocationsBinding, binding: DialogMusicLocationsBinding,
savedInstanceState: Bundle? savedInstanceState: Bundle?,
) { ) {
openDocumentTreeLauncher = openDocumentTreeLauncher =
registerForActivityResult(ActivityResultContracts.OpenDocumentTree()) { uri -> registerForActivityResult(ActivityResultContracts.OpenDocumentTree()) { uri ->
@@ -257,7 +257,8 @@ class LocationsDialog : ViewBindingMaterialDialogFragment<DialogMusicLocationsBi
isIncludeMode = query.mode == MediaStore.FilterMode.INCLUDE isIncludeMode = query.mode == MediaStore.FilterMode.INCLUDE
binding.locationsExcludeModeGroup.check( binding.locationsExcludeModeGroup.check(
if (isIncludeMode) R.id.locations_exclude_mode_exclude if (isIncludeMode) R.id.locations_exclude_mode_exclude
else R.id.locations_exclude_mode_include) else R.id.locations_exclude_mode_include
)
} }
} }
@@ -397,9 +398,11 @@ class LocationsDialog : ViewBindingMaterialDialogFragment<DialogMusicLocationsBi
// File Picker mode - use secondary colors // File Picker mode - use secondary colors
setCardBackgroundColor(context.getAttrColorCompat(MR.attr.colorSecondaryContainer)) setCardBackgroundColor(context.getAttrColorCompat(MR.attr.colorSecondaryContainer))
binding.locationsPermsDesc.setTextColor( binding.locationsPermsDesc.setTextColor(
context.getAttrColorCompat(MR.attr.colorOnSecondaryContainer)) context.getAttrColorCompat(MR.attr.colorOnSecondaryContainer)
)
binding.locationsPermsSubtitle.setTextColor( binding.locationsPermsSubtitle.setTextColor(
context.getAttrColorCompat(MR.attr.colorSecondary)) context.getAttrColorCompat(MR.attr.colorSecondary)
)
binding.locationsPermsOpen.imageTintList = binding.locationsPermsOpen.imageTintList =
context.getAttrColorCompat(MR.attr.colorOnSecondaryContainer) context.getAttrColorCompat(MR.attr.colorOnSecondaryContainer)
} else { } else {
@@ -408,19 +411,24 @@ class LocationsDialog : ViewBindingMaterialDialogFragment<DialogMusicLocationsBi
if (hasStoragePermission) { if (hasStoragePermission) {
// Has permission - use secondary colors // Has permission - use secondary colors
setCardBackgroundColor( setCardBackgroundColor(
context.getAttrColorCompat(MR.attr.colorSecondaryContainer)) context.getAttrColorCompat(MR.attr.colorSecondaryContainer)
)
binding.locationsPermsDesc.setTextColor( binding.locationsPermsDesc.setTextColor(
context.getAttrColorCompat(MR.attr.colorOnSecondaryContainer)) context.getAttrColorCompat(MR.attr.colorOnSecondaryContainer)
)
binding.locationsPermsSubtitle.setTextColor( binding.locationsPermsSubtitle.setTextColor(
context.getAttrColorCompat(MR.attr.colorSecondary)) context.getAttrColorCompat(MR.attr.colorSecondary)
)
binding.locationsPermsOpen.imageTintList = binding.locationsPermsOpen.imageTintList =
context.getAttrColorCompat(MR.attr.colorOnSecondaryContainer) context.getAttrColorCompat(MR.attr.colorOnSecondaryContainer)
} else { } else {
setCardBackgroundColor(context.getAttrColorCompat(MR.attr.colorErrorContainer)) setCardBackgroundColor(context.getAttrColorCompat(MR.attr.colorErrorContainer))
binding.locationsPermsDesc.setTextColor( binding.locationsPermsDesc.setTextColor(
context.getAttrColorCompat(MR.attr.colorOnErrorContainer)) context.getAttrColorCompat(MR.attr.colorOnErrorContainer)
)
binding.locationsPermsSubtitle.setTextColor( binding.locationsPermsSubtitle.setTextColor(
context.getAttrColorCompat(androidx.appcompat.R.attr.colorError)) context.getAttrColorCompat(androidx.appcompat.R.attr.colorError)
)
binding.locationsPermsOpen.imageTintList = binding.locationsPermsOpen.imageTintList =
context.getAttrColorCompat(MR.attr.colorOnErrorContainer) context.getAttrColorCompat(MR.attr.colorOnErrorContainer)
} }
@@ -525,7 +533,8 @@ class LocationsDialog : ViewBindingMaterialDialogFragment<DialogMusicLocationsBi
SAF.Query( SAF.Query(
source = includeLocationAdapter.locations, source = includeLocationAdapter.locations,
exclude = excludeLocationAdapter.locations, exclude = excludeLocationAdapter.locations,
withHidden = binding.locationsWithHiddenSwitch.isChecked) withHidden = binding.locationsWithHiddenSwitch.isChecked,
)
if (!modeChanged && currentMode == LocationMode.SAF) { if (!modeChanged && currentMode == LocationMode.SAF) {
configChanged = currentSafQuery != newSafQuery configChanged = currentSafQuery != newSafQuery
@@ -546,7 +555,8 @@ class LocationsDialog : ViewBindingMaterialDialogFragment<DialogMusicLocationsBi
MediaStore.Query( MediaStore.Query(
mode = filterMode, mode = filterMode,
filtered = filterLocationAdapter.locations, filtered = filterLocationAdapter.locations,
excludeNonMusic = binding.locationsExcludeNonMusicSwitch.isChecked) excludeNonMusic = binding.locationsExcludeNonMusicSwitch.isChecked,
)
if (!modeChanged && currentMode == LocationMode.MEDIA_STORE) { if (!modeChanged && currentMode == LocationMode.MEDIA_STORE) {
configChanged = currentMediaStoreQuery != newMediaStoreQuery configChanged = currentMediaStoreQuery != newMediaStoreQuery
@@ -83,7 +83,8 @@ class IndexingNotification(private val context: Context) :
lastUpdateTime = SystemClock.elapsedRealtime() lastUpdateTime = SystemClock.elapsedRealtime()
L.d("Updating state to $progress") L.d("Updating state to $progress")
setContentText( setContentText(
context.getString(R.string.fmt_indexing, progress.loaded, progress.explored)) context.getString(R.string.fmt_indexing, progress.loaded, progress.explored)
)
setProgress(progress.loaded, progress.explored, false) setProgress(progress.loaded, progress.explored, false)
return true return true
} }
@@ -117,4 +118,6 @@ class ObservingNotification(context: Context) :
/** Notification channel shared by [IndexingNotification] and [ObservingNotification]. */ /** Notification channel shared by [IndexingNotification] and [ObservingNotification]. */
private val indexerChannel = private val indexerChannel =
ForegroundServiceNotification.ChannelInfo( ForegroundServiceNotification.ChannelInfo(
id = BuildConfig.APPLICATION_ID + ".channel.INDEXER", nameRes = R.string.lbl_indexer) id = BuildConfig.APPLICATION_ID + ".channel.INDEXER",
nameRes = R.string.lbl_indexer,
)
@@ -47,7 +47,7 @@ private constructor(
private val playbackManager: PlaybackStateManager, private val playbackManager: PlaybackStateManager,
private val musicRepository: MusicRepository, private val musicRepository: MusicRepository,
private val musicSettings: MusicSettings, private val musicSettings: MusicSettings,
private val imageLoader: ImageLoader private val imageLoader: ImageLoader,
) : ) :
MusicRepository.IndexingWorker, MusicRepository.IndexingWorker,
MusicRepository.IndexingListener, MusicRepository.IndexingListener,
@@ -59,11 +59,17 @@ private constructor(
private val playbackManager: PlaybackStateManager, private val playbackManager: PlaybackStateManager,
private val musicRepository: MusicRepository, private val musicRepository: MusicRepository,
private val musicSettings: MusicSettings, private val musicSettings: MusicSettings,
private val imageLoader: ImageLoader private val imageLoader: ImageLoader,
) { ) {
fun create(context: Context, listener: ForegroundListener) = fun create(context: Context, listener: ForegroundListener) =
IndexingHolder( IndexingHolder(
context, listener, playbackManager, musicRepository, musicSettings, imageLoader) context,
listener,
playbackManager,
musicRepository,
musicSettings,
imageLoader,
)
} }
private val indexJob = Job() private val indexJob = Job()
@@ -75,7 +81,9 @@ private constructor(
workerContext workerContext
.getSystemServiceCompat(PowerManager::class) .getSystemServiceCompat(PowerManager::class)
.newWakeLock( .newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK, BuildConfig.APPLICATION_ID + ":IndexingComponent") PowerManager.PARTIAL_WAKE_LOCK,
BuildConfig.APPLICATION_ID + ":IndexingComponent",
)
private var trackingJob: Job? = null private var trackingJob: Job? = null
fun attach() { fun attach() {
@@ -154,8 +162,10 @@ private constructor(
savedState.copy( savedState.copy(
parent = parent =
savedState.parent?.let { musicRepository.find(it.uid) as? MusicParent? }, savedState.parent?.let { musicRepository.find(it.uid) as? MusicParent? },
heap = savedState.heap.map { song -> song?.let { library.findSong(it.uid) } }), heap = savedState.heap.map { song -> song?.let { library.findSong(it.uid) } },
true) ),
true,
)
} }
} }
@@ -72,7 +72,9 @@ typealias Sugar = Bundle.(Context) -> Unit
fun header(@StringRes nameRes: Int): Sugar = { fun header(@StringRes nameRes: Int): Sugar = {
putString( putString(
MediaConstants.DESCRIPTION_EXTRAS_KEY_CONTENT_STYLE_GROUP_TITLE, it.getString(nameRes)) MediaConstants.DESCRIPTION_EXTRAS_KEY_CONTENT_STYLE_GROUP_TITLE,
it.getString(nameRes),
)
} }
fun header(name: String): Sugar = { fun header(name: String): Sugar = {
@@ -95,7 +97,8 @@ fun TabNode.toMediaItem(context: Context): MediaItem {
val extras = val extras =
makeExtras( makeExtras(
context, context,
style(MediaConstants.DESCRIPTION_EXTRAS_VALUE_CONTENT_STYLE_CATEGORY_LIST_ITEM)) style(MediaConstants.DESCRIPTION_EXTRAS_VALUE_CONTENT_STYLE_CATEGORY_LIST_ITEM),
)
val mediaSessionUID = MediaSessionUID.Tab(this) val mediaSessionUID = MediaSessionUID.Tab(this)
val description = val description =
MediaDescriptionCompat.Builder() MediaDescriptionCompat.Builder()
@@ -140,7 +143,8 @@ fun Album.toMediaItem(context: Context, vararg sugar: Sugar): MediaItem {
.setIconUri( .setIconUri(
covers.covers.firstOrNull()?.let { covers.covers.firstOrNull()?.let {
Uri.withAppendedPath(CoverProvider.CONTENT_URI, it.id) Uri.withAppendedPath(CoverProvider.CONTENT_URI, it.id)
}) }
)
.setExtras(extras) .setExtras(extras)
.build() .build()
return MediaItem(description, MediaItem.FLAG_BROWSABLE) return MediaItem(description, MediaItem.FLAG_BROWSABLE)
@@ -160,7 +164,8 @@ fun Artist.toMediaItem(context: Context, vararg sugar: Sugar): MediaItem {
context.getPlural(R.plurals.fmt_song_count, songs.size) context.getPlural(R.plurals.fmt_song_count, songs.size)
} else { } else {
context.getString(R.string.def_song_count) context.getString(R.string.def_song_count)
}) },
)
val extras = makeExtras(context, *sugar) val extras = makeExtras(context, *sugar)
val description = val description =
MediaDescriptionCompat.Builder() MediaDescriptionCompat.Builder()
@@ -171,7 +176,8 @@ fun Artist.toMediaItem(context: Context, vararg sugar: Sugar): MediaItem {
.setIconUri( .setIconUri(
covers.covers.firstOrNull()?.let { covers.covers.firstOrNull()?.let {
Uri.withAppendedPath(CoverProvider.CONTENT_URI, it.id) Uri.withAppendedPath(CoverProvider.CONTENT_URI, it.id)
}) }
)
.setExtras(extras) .setExtras(extras)
.build() .build()
return MediaItem(description, MediaItem.FLAG_BROWSABLE) return MediaItem(description, MediaItem.FLAG_BROWSABLE)
@@ -194,7 +200,8 @@ fun Genre.toMediaItem(context: Context, vararg sugar: Sugar): MediaItem {
.setIconUri( .setIconUri(
covers.covers.firstOrNull()?.let { covers.covers.firstOrNull()?.let {
Uri.withAppendedPath(CoverProvider.CONTENT_URI, it.id) Uri.withAppendedPath(CoverProvider.CONTENT_URI, it.id)
}) }
)
.setExtras(extras) .setExtras(extras)
.build() .build()
return MediaItem(description, MediaItem.FLAG_BROWSABLE) return MediaItem(description, MediaItem.FLAG_BROWSABLE)
@@ -218,7 +225,8 @@ fun Playlist.toMediaItem(context: Context, vararg sugar: Sugar): MediaItem {
.setIconUri( .setIconUri(
covers.covers.firstOrNull()?.let { covers.covers.firstOrNull()?.let {
Uri.withAppendedPath(CoverProvider.CONTENT_URI, it.id) Uri.withAppendedPath(CoverProvider.CONTENT_URI, it.id)
}) }
)
.setExtras(extras) .setExtras(extras)
.build() .build()
return MediaItem(description, MediaItem.FLAG_BROWSABLE) return MediaItem(description, MediaItem.FLAG_BROWSABLE)
@@ -45,7 +45,7 @@ private constructor(
private val musicRepository: MusicRepository, private val musicRepository: MusicRepository,
private val searchEngine: SearchEngine, private val searchEngine: SearchEngine,
homeGeneratorFactory: HomeGenerator.Factory, homeGeneratorFactory: HomeGenerator.Factory,
detailGeneratorFactory: DetailGenerator.Factory detailGeneratorFactory: DetailGenerator.Factory,
) : HomeGenerator.Invalidator, DetailGenerator.Invalidator { ) : HomeGenerator.Invalidator, DetailGenerator.Invalidator {
class Factory class Factory
@@ -54,7 +54,7 @@ private constructor(
private val musicRepository: MusicRepository, private val musicRepository: MusicRepository,
private val searchEngine: SearchEngine, private val searchEngine: SearchEngine,
private val homeGeneratorFactory: HomeGenerator.Factory, private val homeGeneratorFactory: HomeGenerator.Factory,
private val detailGeneratorFactory: DetailGenerator.Factory private val detailGeneratorFactory: DetailGenerator.Factory,
) { ) {
fun create(context: Context, invalidator: Invalidator): MusicBrowser = fun create(context: Context, invalidator: Invalidator): MusicBrowser =
MusicBrowser( MusicBrowser(
@@ -63,7 +63,8 @@ private constructor(
musicRepository, musicRepository,
searchEngine, searchEngine,
homeGeneratorFactory, homeGeneratorFactory,
detailGeneratorFactory) detailGeneratorFactory,
)
} }
interface Invalidator { interface Invalidator {
@@ -143,7 +144,12 @@ private constructor(
val library = musicRepository.library ?: return mutableListOf() val library = musicRepository.library ?: return mutableListOf()
val items = val items =
SearchEngine.Items( SearchEngine.Items(
library.songs, library.albums, library.artists, library.genres, library.playlists) library.songs,
library.albums,
library.artists,
library.genres,
library.playlists,
)
return searchEngine.search(items, query).toMediaItems() return searchEngine.search(items, query).toMediaItems()
} }
@@ -41,7 +41,7 @@ constructor(
private val invalidator: Invalidator, private val invalidator: Invalidator,
indexingHolderFactory: IndexingHolder.Factory, indexingHolderFactory: IndexingHolder.Factory,
musicBrowserFactory: MusicBrowser.Factory, musicBrowserFactory: MusicBrowser.Factory,
private val musicRepository: MusicRepository private val musicRepository: MusicRepository,
) : MusicBrowser.Invalidator { ) : MusicBrowser.Invalidator {
private val indexer = indexingHolderFactory.create(context, foregroundListener) private val indexer = indexingHolderFactory.create(context, foregroundListener)
private val musicBrowser = musicBrowserFactory.create(context, this) private val musicBrowser = musicBrowserFactory.create(context, this)
@@ -55,12 +55,12 @@ constructor(
constructor( constructor(
private val indexingHolderFactory: IndexingHolder.Factory, private val indexingHolderFactory: IndexingHolder.Factory,
private val musicBrowserFactory: MusicBrowser.Factory, private val musicBrowserFactory: MusicBrowser.Factory,
private val musicRepository: MusicRepository private val musicRepository: MusicRepository,
) { ) {
fun create( fun create(
context: Context, context: Context,
foregroundListener: ForegroundListener, foregroundListener: ForegroundListener,
invalidator: Invalidator invalidator: Invalidator,
): MusicServiceFragment = ): MusicServiceFragment =
MusicServiceFragment( MusicServiceFragment(
context, context,
@@ -68,7 +68,8 @@ constructor(
invalidator, invalidator,
indexingHolderFactory, indexingHolderFactory,
musicBrowserFactory, musicBrowserFactory,
musicRepository) musicRepository,
)
} }
interface Invalidator { interface Invalidator {
@@ -104,17 +105,13 @@ constructor(
fun getRoot() = BrowserRoot(MediaSessionUID.Tab(TabNode.Root).toString(), Bundle()) fun getRoot() = BrowserRoot(MediaSessionUID.Tab(TabNode.Root).toString(), Bundle())
fun getItem(mediaId: String, result: Result<MediaItem>) = fun getItem(mediaId: String, result: Result<MediaItem>) =
result.dispatch { result.dispatch { musicBrowser.getItem(mediaId) }
musicBrowser.getItem(
mediaId,
)
}
fun getChildren( fun getChildren(
mediaId: String, mediaId: String,
maxTabs: Int, maxTabs: Int,
result: Result<MutableList<MediaItem>>, result: Result<MutableList<MediaItem>>,
page: Page? page: Page?,
) = result.dispatch { musicBrowser.getChildren(mediaId, maxTabs)?.expose(page) } ) = result.dispatch { musicBrowser.getChildren(mediaId, maxTabs)?.expose(page) }
fun search(query: String, result: Result<MutableList<MediaItem>>, page: Page?) = fun search(query: String, result: Result<MutableList<MediaItem>>, page: Page?) =
@@ -51,7 +51,7 @@ class PlaybackBarFragment : ViewBindingFragment<FragmentPlaybackBarBinding>() {
override fun onBindingCreated( override fun onBindingCreated(
binding: FragmentPlaybackBarBinding, binding: FragmentPlaybackBarBinding,
savedInstanceState: Bundle? savedInstanceState: Bundle?,
) { ) {
super.onBindingCreated(binding, savedInstanceState) super.onBindingCreated(binding, savedInstanceState)
val context = requireContext() val context = requireContext()
@@ -84,7 +84,8 @@ class PlaybackBarFragment : ViewBindingFragment<FragmentPlaybackBarBinding>() {
playbackModel.currentBarAction, playbackModel.currentBarAction,
playbackModel.repeatMode, playbackModel.repeatMode,
playbackModel.isShuffled, playbackModel.isShuffled,
::updateBarAction) ::updateBarAction,
)
} }
override fun onDestroyBinding(binding: FragmentPlaybackBarBinding) { override fun onDestroyBinding(binding: FragmentPlaybackBarBinding) {
@@ -119,7 +120,7 @@ class PlaybackBarFragment : ViewBindingFragment<FragmentPlaybackBarBinding>() {
private fun updateBarAction( private fun updateBarAction(
actionMode: ActionMode, actionMode: ActionMode,
repeatMode: RepeatMode, repeatMode: RepeatMode,
isShuffled: Boolean isShuffled: Boolean,
) { ) {
val binding = requireBinding() val binding = requireBinding()
when (actionMode) { when (actionMode) {
@@ -54,7 +54,8 @@ class PlaybackBottomSheetBehavior<V : View>(context: Context, attributeSet: Attr
ShapeAppearanceModel.builder( ShapeAppearanceModel.builder(
context, context,
R.style.ShapeAppearance_Auxio_BottomSheet, R.style.ShapeAppearance_Auxio_BottomSheet,
MR.style.ShapeAppearanceOverlay_Material3_Corner_Top) MR.style.ShapeAppearanceOverlay_Material3_Corner_Top,
)
.build() .build()
} else { } else {
ShapeAppearanceModel.Builder().build() ShapeAppearanceModel.Builder().build()
@@ -85,7 +86,9 @@ class PlaybackBottomSheetBehavior<V : View>(context: Context, attributeSet: Attr
MaterialShapeDrawable(sheetBackgroundDrawable.shapeAppearanceModel).apply { MaterialShapeDrawable(sheetBackgroundDrawable.shapeAppearanceModel).apply {
fillColor = sheetBackgroundDrawable.fillColor fillColor = sheetBackgroundDrawable.fillColor
}, },
sheetBackgroundDrawable)) sheetBackgroundDrawable,
)
)
override fun applyWindowInsets(child: View, insets: WindowInsets): WindowInsets { override fun applyWindowInsets(child: View, insets: WindowInsets): WindowInsets {
super.applyWindowInsets(child, insets) super.applyWindowInsets(child, insets)
@@ -94,6 +97,10 @@ class PlaybackBottomSheetBehavior<V : View>(context: Context, attributeSet: Attr
val bars = insets.systemBarInsetsCompat val bars = insets.systemBarInsetsCompat
expandedOffset = bars.top expandedOffset = bars.top
return insets.replaceSystemBarInsetsCompat( return insets.replaceSystemBarInsetsCompat(
bars.left, bars.top, bars.right, expandedOffset + bars.bottom) bars.left,
bars.top,
bars.right,
expandedOffset + bars.bottom,
)
} }
} }
@@ -75,7 +75,7 @@ class PlaybackPanelFragment :
override fun onBindingCreated( override fun onBindingCreated(
binding: FragmentPlaybackPanelBinding, binding: FragmentPlaybackPanelBinding,
savedInstanceState: Bundle? savedInstanceState: Bundle?,
) { ) {
super.onBindingCreated(binding, savedInstanceState) super.onBindingCreated(binding, savedInstanceState)
@@ -64,10 +64,13 @@ interface PlaybackSettings : Settings<PlaybackSettings.Listener> {
interface Listener { interface Listener {
/** Called when one of the ReplayGain configurations have changed. */ /** Called when one of the ReplayGain configurations have changed. */
fun onReplayGainSettingsChanged() {} fun onReplayGainSettingsChanged() {}
/** Called when [notificationAction] has changed. */ /** Called when [notificationAction] has changed. */
fun onNotificationActionChanged() {} fun onNotificationActionChanged() {}
/** Called when [barAction] has changed. */ /** Called when [barAction] has changed. */
fun onBarActionChanged() {} fun onBarActionChanged() {}
/** Called when [pauseOnRepeat] has changed. */ /** Called when [pauseOnRepeat] has changed. */
fun onPauseOnRepeatChanged() {} fun onPauseOnRepeatChanged() {}
} }
@@ -79,26 +82,31 @@ class PlaybackSettingsImpl @Inject constructor(@ApplicationContext context: Cont
get() = get() =
PlaySong.fromIntCode( PlaySong.fromIntCode(
sharedPreferences.getInt( sharedPreferences.getInt(
getString(R.string.set_key_play_in_list_with), Int.MIN_VALUE)) getString(R.string.set_key_play_in_list_with),
?: PlaySong.FromAll Int.MIN_VALUE,
)
) ?: PlaySong.FromAll
override val inParentPlaybackMode: PlaySong? override val inParentPlaybackMode: PlaySong?
get() = get() =
PlaySong.fromIntCode( PlaySong.fromIntCode(
sharedPreferences.getInt( sharedPreferences.getInt(
getString(R.string.set_key_play_in_parent_with), Int.MIN_VALUE)) getString(R.string.set_key_play_in_parent_with),
Int.MIN_VALUE,
)
)
override val barAction: ActionMode override val barAction: ActionMode
get() = get() =
ActionMode.fromIntCode( ActionMode.fromIntCode(
sharedPreferences.getInt(getString(R.string.set_key_bar_action), Int.MIN_VALUE)) sharedPreferences.getInt(getString(R.string.set_key_bar_action), Int.MIN_VALUE)
?: ActionMode.NEXT ) ?: ActionMode.NEXT
override val notificationAction: ActionMode override val notificationAction: ActionMode
get() = get() =
ActionMode.fromIntCode( ActionMode.fromIntCode(
sharedPreferences.getInt(getString(R.string.set_key_notif_action), Int.MIN_VALUE)) sharedPreferences.getInt(getString(R.string.set_key_notif_action), Int.MIN_VALUE)
?: ActionMode.REPEAT ) ?: ActionMode.REPEAT
override val headsetAutoplay: Boolean override val headsetAutoplay: Boolean
get() = sharedPreferences.getBoolean(getString(R.string.set_key_headset_autoplay), false) get() = sharedPreferences.getBoolean(getString(R.string.set_key_headset_autoplay), false)
@@ -106,14 +114,15 @@ class PlaybackSettingsImpl @Inject constructor(@ApplicationContext context: Cont
override val replayGainMode: ReplayGainMode override val replayGainMode: ReplayGainMode
get() = get() =
ReplayGainMode.fromIntCode( ReplayGainMode.fromIntCode(
sharedPreferences.getInt(getString(R.string.set_key_replay_gain), Int.MIN_VALUE)) sharedPreferences.getInt(getString(R.string.set_key_replay_gain), Int.MIN_VALUE)
?: ReplayGainMode.DYNAMIC ) ?: ReplayGainMode.DYNAMIC
override var replayGainPreAmp: ReplayGainPreAmp override var replayGainPreAmp: ReplayGainPreAmp
get() = get() =
ReplayGainPreAmp( ReplayGainPreAmp(
sharedPreferences.getFloat(getString(R.string.set_key_pre_amp_with), 0f), sharedPreferences.getFloat(getString(R.string.set_key_pre_amp_with), 0f),
sharedPreferences.getFloat(getString(R.string.set_key_pre_amp_without), 0f)) sharedPreferences.getFloat(getString(R.string.set_key_pre_amp_without), 0f),
)
set(value) { set(value) {
sharedPreferences.edit { sharedPreferences.edit {
putFloat(getString(R.string.set_key_pre_amp_with), value.with) putFloat(getString(R.string.set_key_pre_amp_with), value.with)
@@ -155,7 +164,9 @@ class PlaybackSettingsImpl @Inject constructor(@ApplicationContext context: Cont
sharedPreferences.edit { sharedPreferences.edit {
putInt( putInt(
getString(R.string.set_key_play_in_list_with), mode?.intCode ?: Int.MIN_VALUE) getString(R.string.set_key_play_in_list_with),
mode?.intCode ?: Int.MIN_VALUE,
)
remove(OLD_KEY_LIB_MUSIC_PLAYBACK_MODE) remove(OLD_KEY_LIB_MUSIC_PLAYBACK_MODE)
apply() apply()
} }
@@ -171,7 +182,9 @@ class PlaybackSettingsImpl @Inject constructor(@ApplicationContext context: Cont
sharedPreferences.edit { sharedPreferences.edit {
putInt( putInt(
getString(R.string.set_key_play_in_parent_with), mode?.intCode ?: Int.MIN_VALUE) getString(R.string.set_key_play_in_parent_with),
mode?.intCode ?: Int.MIN_VALUE,
)
remove(OLD_KEY_DETAIL_MUSIC_PLAYBACK_MODE) remove(OLD_KEY_DETAIL_MUSIC_PLAYBACK_MODE)
apply() apply()
} }
@@ -150,7 +150,7 @@ constructor(
parent: MusicParent?, parent: MusicParent?,
queue: List<Song>, queue: List<Song>,
index: Int, index: Int,
isShuffled: Boolean isShuffled: Boolean,
) { ) {
L.d("New playback started, updating playback information") L.d("New playback started, updating playback information")
_song.value = playbackManager.currentSong _song.value = playbackManager.currentSong
@@ -242,7 +242,8 @@ constructor(
playbackManager.play( playbackManager.play(
requireNotNull(commandFactory.song(song, shuffle)) { requireNotNull(commandFactory.song(song, shuffle)) {
"Invalid playback parameters [$song $shuffle]" "Invalid playback parameters [$song $shuffle]"
}) }
)
} }
private fun playFromAllImpl(song: Song?, shuffle: ShuffleMode) { private fun playFromAllImpl(song: Song?, shuffle: ShuffleMode) {
@@ -268,7 +269,8 @@ constructor(
return return
} }
L.d( L.d(
"Cannot use given artist parameter for $song [$artist from ${song.artists}], showing choice dialog") "Cannot use given artist parameter for $song [$artist from ${song.artists}], showing choice dialog"
)
startPlaybackDecision(PlaybackDecision.PlayFromArtist(song)) startPlaybackDecision(PlaybackDecision.PlayFromArtist(song))
} }
@@ -279,7 +281,8 @@ constructor(
return return
} }
L.d( L.d(
"Cannot use given genre parameter for $song [$genre from ${song.genres}], showing choice dialog") "Cannot use given genre parameter for $song [$genre from ${song.genres}], showing choice dialog"
)
startPlaybackDecision(PlaybackDecision.PlayFromArtist(song)) startPlaybackDecision(PlaybackDecision.PlayFromArtist(song))
} }
@@ -639,7 +642,7 @@ enum class OpenPanel {
* Open the queue panel, assuming that it exists in the current layout, is collapsed, and with * Open the queue panel, assuming that it exists in the current layout, is collapsed, and with
* the playback panel already being expanded. Do nothing if these conditions are not met. * the playback panel already being expanded. Do nothing if these conditions are not met.
*/ */
QUEUE QUEUE,
} }
/** /**
@@ -650,8 +653,10 @@ enum class OpenPanel {
sealed interface PlaybackDecision { sealed interface PlaybackDecision {
/** The [Song] currently attempting to be played from. */ /** The [Song] currently attempting to be played from. */
val song: Song val song: Song
/** Navigate to a dialog to determine which [Artist] a [Song] should be played from. */ /** Navigate to a dialog to determine which [Artist] a [Song] should be played from. */
class PlayFromArtist(override val song: Song) : PlaybackDecision class PlayFromArtist(override val song: Song) : PlaybackDecision
/** Navigate to a dialog to determine which [Genre] a [Song] should be played from. */ /** Navigate to a dialog to determine which [Genre] a [Song] should be played from. */
class PlayFromGenre(override val song: Song) : PlaybackDecision class PlayFromGenre(override val song: Song) : PlaybackDecision
} }
@@ -38,7 +38,8 @@ import org.oxycblt.musikr.Artist
*/ */
class ArtistPlaybackChoiceAdapter(private val listener: ClickableListListener<Artist>) : class ArtistPlaybackChoiceAdapter(private val listener: ClickableListListener<Artist>) :
FlexibleListAdapter<Artist, ArtistPlaybackChoiceViewHolder>( FlexibleListAdapter<Artist, ArtistPlaybackChoiceViewHolder>(
ArtistPlaybackChoiceViewHolder.DIFF_CALLBACK) { ArtistPlaybackChoiceViewHolder.DIFF_CALLBACK
) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
ArtistPlaybackChoiceViewHolder.from(parent) ArtistPlaybackChoiceViewHolder.from(parent)
@@ -38,7 +38,8 @@ import org.oxycblt.musikr.Genre
*/ */
class GenrePlaybackChoiceAdapter(private val listener: ClickableListListener<Genre>) : class GenrePlaybackChoiceAdapter(private val listener: ClickableListListener<Genre>) :
FlexibleListAdapter<Genre, GenrePlaybackChoiceViewHolder>( FlexibleListAdapter<Genre, GenrePlaybackChoiceViewHolder>(
GenrePlaybackChoiceViewHolder.DIFF_CALLBACK) { GenrePlaybackChoiceViewHolder.DIFF_CALLBACK
) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
GenrePlaybackChoiceViewHolder.from(parent) GenrePlaybackChoiceViewHolder.from(parent)
@@ -39,7 +39,8 @@ import org.oxycblt.musikr.Music
@Database( @Database(
entities = [PlaybackState::class, QueueHeapItem::class, QueueShuffledMappingItem::class], entities = [PlaybackState::class, QueueHeapItem::class, QueueShuffledMappingItem::class],
version = 38, version = 38,
exportSchema = false) exportSchema = false,
)
@TypeConverters(Music.UID.TypeConverters::class) @TypeConverters(Music.UID.TypeConverters::class)
abstract class PersistenceDatabase : RoomDatabase() { abstract class PersistenceDatabase : RoomDatabase() {
/** /**
@@ -144,7 +145,7 @@ data class PlaybackState(
val positionMs: Long, val positionMs: Long,
val repeatMode: RepeatMode, val repeatMode: RepeatMode,
val songUid: Music.UID, val songUid: Music.UID,
val parentUid: Music.UID? val parentUid: Music.UID?,
) )
@Entity data class QueueHeapItem(@PrimaryKey val id: Int, val uid: Music.UID) @Entity data class QueueHeapItem(@PrimaryKey val id: Int, val uid: Music.UID)
@@ -43,7 +43,8 @@ class PersistenceRoomModule {
Room.databaseBuilder( Room.databaseBuilder(
context.applicationContext, context.applicationContext,
PersistenceDatabase::class.java, PersistenceDatabase::class.java,
"playback_persistence.db") "playback_persistence.db",
)
.fallbackToDestructiveMigration() .fallbackToDestructiveMigration()
.addMigrations(PersistenceDatabase.MIGRATION_27_32) .addMigrations(PersistenceDatabase.MIGRATION_27_32)
.build() .build()
@@ -46,7 +46,7 @@ class PersistenceRepositoryImpl
constructor( constructor(
private val playbackStateDao: PlaybackStateDao, private val playbackStateDao: PlaybackStateDao,
private val queueDao: QueueDao, private val queueDao: QueueDao,
private val musicRepository: MusicRepository private val musicRepository: MusicRepository,
) : PersistenceRepository { ) : PersistenceRepository {
override suspend fun readState(): PlaybackStateManager.SavedState? { override suspend fun readState(): PlaybackStateManager.SavedState? {
@@ -75,7 +75,8 @@ constructor(
heap = heap, heap = heap,
shuffledMapping = shuffledMapping, shuffledMapping = shuffledMapping,
index = playbackState.index, index = playbackState.index,
songUid = playbackState.songUid) songUid = playbackState.songUid,
)
} }
override suspend fun saveState(state: PlaybackStateManager.SavedState?): Boolean { override suspend fun saveState(state: PlaybackStateManager.SavedState?): Boolean {
@@ -99,7 +100,8 @@ constructor(
positionMs = state.positionMs, positionMs = state.positionMs,
repeatMode = state.repeatMode, repeatMode = state.repeatMode,
songUid = state.songUid, songUid = state.songUid,
parentUid = state.parent?.uid) parentUid = state.parent?.uid,
)
// Convert the remaining queue information do their database-specific counterparts. // Convert the remaining queue information do their database-specific counterparts.
val heap = val heap =
@@ -63,7 +63,7 @@ class QueueAdapter(private val listener: EditClickListListener<Song>) :
override fun onBindViewHolder( override fun onBindViewHolder(
viewHolder: QueueSongViewHolder, viewHolder: QueueSongViewHolder,
position: Int, position: Int,
payload: List<Any> payload: List<Any>,
) { ) {
if (payload.isEmpty()) { if (payload.isEmpty()) {
viewHolder.bind(getItem(position), listener) viewHolder.bind(getItem(position), listener)
@@ -143,7 +143,9 @@ class QueueSongViewHolder private constructor(private val binding: ItemEditableS
fillColor = fillColor =
binding.context.getAttrColorCompat(MR.attr.colorSurfaceContainerHigh) binding.context.getAttrColorCompat(MR.attr.colorSurfaceContainerHigh)
}, },
background)) background,
)
)
} }
/** /**
@@ -59,7 +59,7 @@ class QueueBottomSheetBehavior<V : View>(context: Context, attributeSet: Attribu
override fun onDependentViewChanged( override fun onDependentViewChanged(
parent: CoordinatorLayout, parent: CoordinatorLayout,
child: V, child: V,
dependency: View dependency: View,
): Boolean { ): Boolean {
barHeight = dependency.height barHeight = dependency.height
// No change, just grabbed the height // No change, just grabbed the height
@@ -75,7 +75,8 @@ class QueueBottomSheetBehavior<V : View>(context: Context, attributeSet: Attribu
ShapeAppearanceModel.builder( ShapeAppearanceModel.builder(
context, context,
R.style.ShapeAppearance_Auxio_BottomSheet, R.style.ShapeAppearance_Auxio_BottomSheet,
MR.style.ShapeAppearanceOverlay_Material3_Corner_Top) MR.style.ShapeAppearanceOverlay_Material3_Corner_Top,
)
.build() .build()
} }
} }
@@ -89,6 +90,10 @@ class QueueBottomSheetBehavior<V : View>(context: Context, attributeSet: Attribu
val effectiveBarHeight = if (barHeight > 0) barHeight else getIdealBarHeight(child.context) val effectiveBarHeight = if (barHeight > 0) barHeight else getIdealBarHeight(child.context)
expandedOffset = effectiveBarHeight + barSpacing expandedOffset = effectiveBarHeight + barSpacing
return insets.replaceSystemBarInsetsCompat( return insets.replaceSystemBarInsetsCompat(
bars.left, bars.top, bars.right, expandedOffset + bars.bottom) bars.left,
bars.top,
bars.right,
expandedOffset + bars.bottom,
)
} }
} }
@@ -32,10 +32,12 @@ class QueueDragCallback(private val queueModel: QueueViewModel) : MaterialDragCa
override fun onMove( override fun onMove(
recyclerView: RecyclerView, recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder, viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder target: RecyclerView.ViewHolder,
) = ) =
queueModel.moveQueueDataItems( queueModel.moveQueueDataItems(
viewHolder.bindingAdapterPosition, target.bindingAdapterPosition) viewHolder.bindingAdapterPosition,
target.bindingAdapterPosition,
)
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
queueModel.removeQueueDataItem(viewHolder.bindingAdapterPosition) queueModel.removeQueueDataItem(viewHolder.bindingAdapterPosition)
@@ -71,12 +71,17 @@ class QueueFragment : ViewBindingFragment<FragmentQueueBinding>(), EditClickList
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
updateDivider() updateDivider()
} }
}) }
)
} }
// --- VIEWMODEL SETUP ---- // --- VIEWMODEL SETUP ----
collectImmediately( collectImmediately(
queueModel.queue, queueModel.index, playbackModel.isPlaying, ::updateQueue) queueModel.queue,
queueModel.index,
playbackModel.isPlaying,
::updateQueue,
)
} }
override fun onDestroyBinding(binding: FragmentQueueBinding) { override fun onDestroyBinding(binding: FragmentQueueBinding) {
@@ -92,7 +92,7 @@ class QueueViewModel @Inject constructor(private val playbackManager: PlaybackSt
parent: MusicParent?, parent: MusicParent?,
queue: List<Song>, queue: List<Song>,
index: Int, index: Int,
isShuffled: Boolean isShuffled: Boolean,
) { ) {
// Entirely new queue -> Replace queue, update index // Entirely new queue -> Replace queue, update index
L.d("New playback, replacing queue and position") L.d("New playback, replacing queue and position")
@@ -48,7 +48,7 @@ class ReplayGainAudioProcessor
@Inject @Inject
constructor( constructor(
private val playbackManager: PlaybackStateManager, private val playbackManager: PlaybackStateManager,
private val playbackSettings: PlaybackSettings private val playbackSettings: PlaybackSettings,
) : BaseAudioProcessor(), PlaybackStateManager.Listener, PlaybackSettings.Listener { ) : BaseAudioProcessor(), PlaybackStateManager.Listener, PlaybackSettings.Listener {
private var volume = 1f private var volume = 1f
set(value) { set(value) {
@@ -86,7 +86,7 @@ constructor(
parent: MusicParent?, parent: MusicParent?,
queue: List<Song>, queue: List<Song>,
index: Int, index: Int,
isShuffled: Boolean isShuffled: Boolean,
) { ) {
L.d("New playback started, updating playback information") L.d("New playback started, updating playback information")
applyReplayGain(playbackManager.currentSong) applyReplayGain(playbackManager.currentSong)
@@ -33,7 +33,9 @@ class BluetoothHeadsetReceiver : BroadcastReceiver() {
if (intent.action == android.bluetooth.BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED) { if (intent.action == android.bluetooth.BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED) {
val newState = val newState =
intent.getIntExtra( intent.getIntExtra(
BluetoothProfile.EXTRA_STATE, BluetoothProfile.STATE_DISCONNECTED) BluetoothProfile.EXTRA_STATE,
BluetoothProfile.STATE_DISCONNECTED,
)
if (newState == BluetoothProfile.STATE_CONNECTED) { if (newState == BluetoothProfile.STATE_CONNECTED) {
// TODO: Initialize the service (Permission workflow must be figured out) // TODO: Initialize the service (Permission workflow must be figured out)
// Perhaps move this to the internal receivers? // Perhaps move this to the internal receivers?
@@ -74,7 +74,7 @@ class ExoPlaybackStateHolder(
private val commandFactory: PlaybackCommand.Factory, private val commandFactory: PlaybackCommand.Factory,
private val replayGainProcessor: ReplayGainAudioProcessor, private val replayGainProcessor: ReplayGainAudioProcessor,
private val musicRepository: MusicRepository, private val musicRepository: MusicRepository,
private val imageSettings: ImageSettings private val imageSettings: ImageSettings,
) : ) :
PlaybackStateHolder, PlaybackStateHolder,
Player.Listener, Player.Listener,
@@ -180,7 +180,8 @@ class ExoPlaybackStateHolder(
playbackManager.play( playbackManager.play(
requireNotNull(commandFactory.all(ShuffleMode.ON)) { requireNotNull(commandFactory.all(ShuffleMode.ON)) {
"Invalid playback parameters" "Invalid playback parameters"
}) }
)
} }
// Open -> Try to find the Song for the given file and then play it from all songs // Open -> Try to find the Song for the given file and then play it from all songs
is DeferredPlayback.Open -> { is DeferredPlayback.Open -> {
@@ -191,7 +192,8 @@ class ExoPlaybackStateHolder(
arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE), arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE),
null, null,
null, null,
null) null,
)
?.use { cursor -> ?.use { cursor ->
val displayNameIndex = val displayNameIndex =
cursor.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME) cursor.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME)
@@ -206,9 +208,10 @@ class ExoPlaybackStateHolder(
if (song != null) { if (song != null) {
val command = val command =
requireNotNull( requireNotNull(
commandFactory.songFromAll(song, ShuffleMode.IMPLICIT)) { commandFactory.songFromAll(song, ShuffleMode.IMPLICIT)
"Invalid playback command" ) {
} "Invalid playback command"
}
playbackManager.play(command) playbackManager.play(command)
} }
} }
@@ -265,7 +268,8 @@ class ExoPlaybackStateHolder(
if (player.shuffleModeEnabled) { if (player.shuffleModeEnabled) {
// Have to manually refresh the shuffle seed and anchor it to the new current songs // Have to manually refresh the shuffle seed and anchor it to the new current songs
player.setShuffleOrder( player.setShuffleOrder(
BetterShuffleOrder(player.mediaItemCount, player.currentMediaItemIndex)) BetterShuffleOrder(player.mediaItemCount, player.currentMediaItemIndex)
)
} }
playbackManager.ack(this, StateAck.QueueReordered) playbackManager.ack(this, StateAck.QueueReordered)
deferSave() deferSave()
@@ -282,7 +286,9 @@ class ExoPlaybackStateHolder(
} }
} else { } else {
player.seekTo( player.seekTo(
player.currentTimeline.getFirstWindowIndex(player.shuffleModeEnabled), C.TIME_UNSET) player.currentTimeline.getFirstWindowIndex(player.shuffleModeEnabled),
C.TIME_UNSET,
)
// TODO: Dislike the UX implications of this, I feel should I bite the bullet // TODO: Dislike the UX implications of this, I feel should I bite the bullet
// and switch to dynamic skip enable/disable? // and switch to dynamic skip enable/disable?
if (!playbackSettings.rememberPause) { if (!playbackSettings.rememberPause) {
@@ -330,7 +336,10 @@ class ExoPlaybackStateHolder(
C.INDEX_UNSET C.INDEX_UNSET
} else { } else {
currTimeline.getNextWindowIndex( currTimeline.getNextWindowIndex(
player.currentMediaItemIndex, Player.REPEAT_MODE_OFF, player.shuffleModeEnabled) player.currentMediaItemIndex,
Player.REPEAT_MODE_OFF,
player.shuffleModeEnabled,
)
} }
if (nextIndex == C.INDEX_UNSET) { if (nextIndex == C.INDEX_UNSET) {
@@ -393,7 +402,7 @@ class ExoPlaybackStateHolder(
rawQueue: RawQueue, rawQueue: RawQueue,
positionMs: Long, positionMs: Long,
repeatMode: RepeatMode, repeatMode: RepeatMode,
ack: StateAck.NewPlayback? ack: StateAck.NewPlayback?,
) { ) {
var sendNewPlaybackEvent = false var sendNewPlaybackEvent = false
var shouldSeek = false var shouldSeek = false
@@ -498,10 +507,13 @@ class ExoPlaybackStateHolder(
// So many actions trigger progression changes that it becomes easier just to handle it // So many actions trigger progression changes that it becomes easier just to handle it
// in an ExoPlayer callback anyway. This doesn't really cause issues anywhere. // in an ExoPlayer callback anyway. This doesn't really cause issues anywhere.
if (events.containsAny( if (
Player.EVENT_PLAY_WHEN_READY_CHANGED, events.containsAny(
Player.EVENT_IS_PLAYING_CHANGED, Player.EVENT_PLAY_WHEN_READY_CHANGED,
Player.EVENT_POSITION_DISCONTINUITY)) { Player.EVENT_IS_PLAYING_CHANGED,
Player.EVENT_POSITION_DISCONTINUITY,
)
) {
L.d("Player state changed, must synchronize state") L.d("Player state changed, must synchronize state")
playbackManager.ack(this, StateAck.ProgressionChanged) playbackManager.ack(this, StateAck.ProgressionChanged)
} }
@@ -521,7 +533,8 @@ class ExoPlaybackStateHolder(
Intent(event) Intent(event)
.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, context.packageName) .putExtra(AudioEffect.EXTRA_PACKAGE_NAME, context.packageName)
.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, audioSessionId) .putExtra(AudioEffect.EXTRA_AUDIO_SESSION, audioSessionId)
.putExtra(AudioEffect.EXTRA_CONTENT_TYPE, AudioEffect.CONTENT_TYPE_MUSIC)) .putExtra(AudioEffect.EXTRA_CONTENT_TYPE, AudioEffect.CONTENT_TYPE_MUSIC)
)
} }
// --- MUSICREPOSITORY METHODS --- // --- MUSICREPOSITORY METHODS ---
@@ -601,7 +614,10 @@ class ExoPlaybackStateHolder(
if (lastMediaItemIndex != C.INDEX_UNSET) { if (lastMediaItemIndex != C.INDEX_UNSET) {
lastMediaItemIndex = lastMediaItemIndex =
timeline.getNextWindowIndex( timeline.getNextWindowIndex(
lastMediaItemIndex, Player.REPEAT_MODE_OFF, shuffleModeEnabled) lastMediaItemIndex,
Player.REPEAT_MODE_OFF,
shuffleModeEnabled,
)
if (lastMediaItemIndex != C.INDEX_UNSET) { if (lastMediaItemIndex != C.INDEX_UNSET) {
queue.add(lastMediaItemIndex) queue.add(lastMediaItemIndex)
} }
@@ -609,7 +625,10 @@ class ExoPlaybackStateHolder(
if (firstMediaItemIndex != C.INDEX_UNSET) { if (firstMediaItemIndex != C.INDEX_UNSET) {
firstMediaItemIndex = firstMediaItemIndex =
timeline.getPreviousWindowIndex( timeline.getPreviousWindowIndex(
firstMediaItemIndex, Player.REPEAT_MODE_OFF, shuffleModeEnabled) firstMediaItemIndex,
Player.REPEAT_MODE_OFF,
shuffleModeEnabled,
)
if (firstMediaItemIndex != C.INDEX_UNSET) { if (firstMediaItemIndex != C.INDEX_UNSET) {
queue.add(0, firstMediaItemIndex) queue.add(0, firstMediaItemIndex)
} }
@@ -645,7 +664,9 @@ class ExoPlaybackStateHolder(
audioListener, audioListener,
DefaultAudioSink.Builder(context) DefaultAudioSink.Builder(context)
.setAudioProcessors(arrayOf(replayGainProcessor)) .setAudioProcessors(arrayOf(replayGainProcessor))
.build())) .build(),
),
)
} }
val exoPlayer = val exoPlayer =
@@ -659,7 +680,8 @@ class ExoPlaybackStateHolder(
.setUsage(C.USAGE_MEDIA) .setUsage(C.USAGE_MEDIA)
.setContentType(C.AUDIO_CONTENT_TYPE_MUSIC) .setContentType(C.AUDIO_CONTENT_TYPE_MUSIC)
.build(), .build(),
true) true,
)
.build() .build()
return ExoPlaybackStateHolder( return ExoPlaybackStateHolder(
@@ -671,7 +693,8 @@ class ExoPlaybackStateHolder(
commandFactory, commandFactory,
replayGainProcessor, replayGainProcessor,
musicRepository, musicRepository,
imageSettings) imageSettings,
)
} }
} }
@@ -68,7 +68,7 @@ private constructor(
private val playbackSettings: PlaybackSettings, private val playbackSettings: PlaybackSettings,
private val bitmapProvider: BitmapProvider, private val bitmapProvider: BitmapProvider,
private val imageSettings: ImageSettings, private val imageSettings: ImageSettings,
private val mediaSessionInterface: MediaSessionInterface private val mediaSessionInterface: MediaSessionInterface,
) : PlaybackStateManager.Listener, ImageSettings.Listener, PlaybackSettings.Listener { ) : PlaybackStateManager.Listener, ImageSettings.Listener, PlaybackSettings.Listener {
class Factory class Factory
@@ -78,7 +78,7 @@ private constructor(
private val playbackSettings: PlaybackSettings, private val playbackSettings: PlaybackSettings,
private val bitmapProvider: BitmapProvider, private val bitmapProvider: BitmapProvider,
private val imageSettings: ImageSettings, private val imageSettings: ImageSettings,
private val mediaSessionInterface: MediaSessionInterface private val mediaSessionInterface: MediaSessionInterface,
) { ) {
fun create(context: Context, foregroundListener: ForegroundListener) = fun create(context: Context, foregroundListener: ForegroundListener) =
MediaSessionHolder( MediaSessionHolder(
@@ -88,7 +88,8 @@ private constructor(
playbackSettings, playbackSettings,
bitmapProvider, bitmapProvider,
imageSettings, imageSettings,
mediaSessionInterface) mediaSessionInterface,
)
} }
private val mediaSession = MediaSessionCompat(context, context.packageName) private val mediaSession = MediaSessionCompat(context, context.packageName)
@@ -156,7 +157,8 @@ private constructor(
PlaybackStateCompat.SHUFFLE_MODE_ALL PlaybackStateCompat.SHUFFLE_MODE_ALL
} else { } else {
PlaybackStateCompat.SHUFFLE_MODE_NONE PlaybackStateCompat.SHUFFLE_MODE_NONE
}) }
)
invalidateSecondaryAction() invalidateSecondaryAction()
} }
@@ -164,7 +166,7 @@ private constructor(
parent: MusicParent?, parent: MusicParent?,
queue: List<Song>, queue: List<Song>,
index: Int, index: Int,
isShuffled: Boolean isShuffled: Boolean,
) { ) {
updateMediaMetadata(playbackManager.currentSong, parent) updateMediaMetadata(playbackManager.currentSong, parent)
updateQueue(queue) updateQueue(queue)
@@ -185,7 +187,8 @@ private constructor(
RepeatMode.NONE -> PlaybackStateCompat.REPEAT_MODE_NONE RepeatMode.NONE -> PlaybackStateCompat.REPEAT_MODE_NONE
RepeatMode.TRACK -> PlaybackStateCompat.REPEAT_MODE_ONE RepeatMode.TRACK -> PlaybackStateCompat.REPEAT_MODE_ONE
RepeatMode.ALL -> PlaybackStateCompat.REPEAT_MODE_ALL RepeatMode.ALL -> PlaybackStateCompat.REPEAT_MODE_ALL
}) }
)
invalidateSecondaryAction() invalidateSecondaryAction()
} }
@@ -238,7 +241,8 @@ private constructor(
.putText(MediaMetadataCompat.METADATA_KEY_ARTIST, artist) .putText(MediaMetadataCompat.METADATA_KEY_ARTIST, artist)
.putText( .putText(
MediaMetadataCompat.METADATA_KEY_ALBUM_ARTIST, MediaMetadataCompat.METADATA_KEY_ALBUM_ARTIST,
song.album.artists.resolveNames(context)) song.album.artists.resolveNames(context),
)
.putText(MediaMetadataCompat.METADATA_KEY_AUTHOR, artist) .putText(MediaMetadataCompat.METADATA_KEY_AUTHOR, artist)
.putText(MediaMetadataCompat.METADATA_KEY_COMPOSER, artist) .putText(MediaMetadataCompat.METADATA_KEY_COMPOSER, artist)
.putText(MediaMetadataCompat.METADATA_KEY_WRITER, artist) .putText(MediaMetadataCompat.METADATA_KEY_WRITER, artist)
@@ -249,13 +253,16 @@ private constructor(
.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, song.durationMs) .putLong(MediaMetadataCompat.METADATA_KEY_DURATION, song.durationMs)
.putText( .putText(
PlaybackNotification.KEY_PARENT, PlaybackNotification.KEY_PARENT,
parent?.name?.resolve(context) ?: context.getString(R.string.lbl_all_songs)) parent?.name?.resolve(context) ?: context.getString(R.string.lbl_all_songs),
)
.putText( .putText(
MetadataExtras.KEY_SUBTITLE_LINK_MEDIA_ID, MetadataExtras.KEY_SUBTITLE_LINK_MEDIA_ID,
MediaSessionUID.SingleItem(song.artists[0].uid).toString()) MediaSessionUID.SingleItem(song.artists[0].uid).toString(),
)
.putText( .putText(
MetadataExtras.KEY_DESCRIPTION_LINK_MEDIA_ID, MetadataExtras.KEY_DESCRIPTION_LINK_MEDIA_ID,
MediaSessionUID.SingleItem(song.album.uid).toString()) MediaSessionUID.SingleItem(song.album.uid).toString(),
)
// These fields are nullable and so we must check first before adding them to the fields. // These fields are nullable and so we must check first before adding them to the fields.
song.track?.let { song.track?.let {
L.d("Adding track information") L.d("Adding track information")
@@ -288,7 +295,8 @@ private constructor(
_notification.updateMetadata(metadata) _notification.updateMetadata(metadata)
foregroundListener.updateForeground(ForegroundListener.Change.MEDIA_SESSION) foregroundListener.updateForeground(ForegroundListener.Change.MEDIA_SESSION)
} }
}) },
)
} }
/** /**
@@ -301,7 +309,9 @@ private constructor(
queue.mapIndexed { i, song -> queue.mapIndexed { i, song ->
val description = val description =
song.toMediaDescription( song.toMediaDescription(
context, { putInt(MediaSessionInterface.KEY_QUEUE_POS, i) }) context,
{ putInt(MediaSessionInterface.KEY_QUEUE_POS, i) },
)
// Store the item index so we can then use the analogous index in the // Store the item index so we can then use the analogous index in the
// playback state. // playback state.
MediaSessionCompat.QueueItem(description, i.toLong()) MediaSessionCompat.QueueItem(description, i.toLong())
@@ -336,14 +346,16 @@ private constructor(
R.drawable.ic_shuffle_on_24 R.drawable.ic_shuffle_on_24
} else { } else {
R.drawable.ic_shuffle_off_24 R.drawable.ic_shuffle_off_24
}) },
)
} }
else -> { else -> {
L.d("Using repeat mode MediaSession action") L.d("Using repeat mode MediaSession action")
PlaybackStateCompat.CustomAction.Builder( PlaybackStateCompat.CustomAction.Builder(
PlaybackActions.ACTION_INC_REPEAT_MODE, PlaybackActions.ACTION_INC_REPEAT_MODE,
context.getString(R.string.desc_change_repeat), context.getString(R.string.desc_change_repeat),
playbackManager.repeatMode.icon) playbackManager.repeatMode.icon,
)
} }
} }
state.addCustomAction(secondaryAction.build()) state.addCustomAction(secondaryAction.build())
@@ -353,7 +365,8 @@ private constructor(
PlaybackStateCompat.CustomAction.Builder( PlaybackStateCompat.CustomAction.Builder(
PlaybackActions.ACTION_EXIT, PlaybackActions.ACTION_EXIT,
context.getString(R.string.desc_exit), context.getString(R.string.desc_exit),
R.drawable.ic_close_24) R.drawable.ic_close_24,
)
.build() .build()
state.addCustomAction(exitAction) state.addCustomAction(exitAction)
@@ -396,7 +409,7 @@ private constructor(
@SuppressLint("RestrictedApi") @SuppressLint("RestrictedApi")
private class PlaybackNotification( private class PlaybackNotification(
private val context: Context, private val context: Context,
sessionToken: MediaSessionCompat.Token sessionToken: MediaSessionCompat.Token,
) : ForegroundServiceNotification(context, CHANNEL_INFO) { ) : ForegroundServiceNotification(context, CHANNEL_INFO) {
init { init {
setSmallIcon(R.drawable.ic_auxio_24) setSmallIcon(R.drawable.ic_auxio_24)
@@ -408,14 +421,17 @@ private class PlaybackNotification(
addAction(buildRepeatAction(context, RepeatMode.NONE)) addAction(buildRepeatAction(context, RepeatMode.NONE))
addAction( addAction(
buildAction(context, PlaybackActions.ACTION_SKIP_PREV, R.drawable.ic_skip_prev_24)) buildAction(context, PlaybackActions.ACTION_SKIP_PREV, R.drawable.ic_skip_prev_24)
)
addAction(buildPlayPauseAction(context, true)) addAction(buildPlayPauseAction(context, true))
addAction( addAction(
buildAction(context, PlaybackActions.ACTION_SKIP_NEXT, R.drawable.ic_skip_next_24)) buildAction(context, PlaybackActions.ACTION_SKIP_NEXT, R.drawable.ic_skip_next_24)
)
addAction(buildAction(context, PlaybackActions.ACTION_EXIT, R.drawable.ic_close_24)) addAction(buildAction(context, PlaybackActions.ACTION_EXIT, R.drawable.ic_close_24))
setStyle( setStyle(
MediaStyle(this).setMediaSession(sessionToken).setShowActionsInCompactView(1, 2, 3)) MediaStyle(this).setMediaSession(sessionToken).setShowActionsInCompactView(1, 2, 3)
)
} }
override val code: Int override val code: Int
@@ -470,7 +486,7 @@ private class PlaybackNotification(
private fun buildPlayPauseAction( private fun buildPlayPauseAction(
context: Context, context: Context,
isPlaying: Boolean isPlaying: Boolean,
): NotificationCompat.Action { ): NotificationCompat.Action {
val drawableRes = val drawableRes =
if (isPlaying) { if (isPlaying) {
@@ -483,14 +499,14 @@ private class PlaybackNotification(
private fun buildRepeatAction( private fun buildRepeatAction(
context: Context, context: Context,
repeatMode: RepeatMode repeatMode: RepeatMode,
): NotificationCompat.Action { ): NotificationCompat.Action {
return buildAction(context, PlaybackActions.ACTION_INC_REPEAT_MODE, repeatMode.icon) return buildAction(context, PlaybackActions.ACTION_INC_REPEAT_MODE, repeatMode.icon)
} }
private fun buildShuffleAction( private fun buildShuffleAction(
context: Context, context: Context,
isShuffled: Boolean isShuffled: Boolean,
): NotificationCompat.Action { ): NotificationCompat.Action {
val drawableRes = val drawableRes =
if (isShuffled) { if (isShuffled) {
@@ -503,7 +519,10 @@ private class PlaybackNotification(
private fun buildAction(context: Context, actionName: String, @DrawableRes iconRes: Int) = private fun buildAction(context: Context, actionName: String, @DrawableRes iconRes: Int) =
NotificationCompat.Action.Builder( NotificationCompat.Action.Builder(
iconRes, actionName, context.newBroadcastPendingIntent(actionName)) iconRes,
actionName,
context.newBroadcastPendingIntent(actionName),
)
.build() .build()
companion object { companion object {
@@ -513,6 +532,7 @@ private class PlaybackNotification(
private val CHANNEL_INFO = private val CHANNEL_INFO =
ChannelInfo( ChannelInfo(
id = BuildConfig.APPLICATION_ID + ".channel.PLAYBACK", id = BuildConfig.APPLICATION_ID + ".channel.PLAYBACK",
nameRes = R.string.lbl_playback) nameRes = R.string.lbl_playback,
)
} }
} }
@@ -168,13 +168,15 @@ constructor(
PlaybackStateCompat.REPEAT_MODE_GROUP -> RepeatMode.ALL PlaybackStateCompat.REPEAT_MODE_GROUP -> RepeatMode.ALL
PlaybackStateCompat.REPEAT_MODE_ONE -> RepeatMode.TRACK PlaybackStateCompat.REPEAT_MODE_ONE -> RepeatMode.TRACK
else -> RepeatMode.NONE else -> RepeatMode.NONE
}) }
)
} }
override fun onSetShuffleMode(shuffleMode: Int) { override fun onSetShuffleMode(shuffleMode: Int) {
playbackManager.shuffled( playbackManager.shuffled(
shuffleMode == PlaybackStateCompat.SHUFFLE_MODE_ALL || shuffleMode == PlaybackStateCompat.SHUFFLE_MODE_ALL ||
shuffleMode == PlaybackStateCompat.SHUFFLE_MODE_GROUP) shuffleMode == PlaybackStateCompat.SHUFFLE_MODE_GROUP
)
} }
override fun onStop() { override fun onStop() {
@@ -191,7 +193,7 @@ constructor(
private fun expandUidIntoCommand( private fun expandUidIntoCommand(
uid: MediaSessionUID, uid: MediaSessionUID,
parentUid: MediaSessionUID? parentUid: MediaSessionUID?,
): PlaybackCommand? { ): PlaybackCommand? {
val unwrappedUid = (uid as? MediaSessionUID.SingleItem)?.uid ?: return null val unwrappedUid = (uid as? MediaSessionUID.SingleItem)?.uid ?: return null
val unwrappedParentUid = (parentUid as? MediaSessionUID.SingleItem)?.uid val unwrappedParentUid = (parentUid as? MediaSessionUID.SingleItem)?.uid
@@ -204,7 +206,7 @@ constructor(
private fun expandSearchInfoCommand( private fun expandSearchInfoCommand(
query: String?, query: String?,
extras: Bundle, extras: Bundle,
library: Library library: Library,
): PlaybackCommand? { ): PlaybackCommand? {
if (query == null) { if (query == null) {
// User just wanted to 'play some music', shuffle all // User just wanted to 'play some music', shuffle all
@@ -59,7 +59,8 @@ private constructor(
exoHolderFactory, exoHolderFactory,
sessionHolderFactory, sessionHolderFactory,
widgetComponentFactory, widgetComponentFactory,
systemReceiverFactory) systemReceiverFactory,
)
} }
private val waitJob = Job() private val waitJob = Job()
@@ -94,12 +95,16 @@ private constructor(
IntegerTable.START_ID_ACTIVITY -> null IntegerTable.START_ID_ACTIVITY -> null
IntegerTable.START_ID_TASKER -> IntegerTable.START_ID_TASKER ->
DeferredPlayback.RestoreState( DeferredPlayback.RestoreState(
play = true, fallback = DeferredPlayback.ShuffleAll) play = true,
fallback = DeferredPlayback.ShuffleAll,
)
IntegerTable.START_ID_MEDIA_BUTTON -> { IntegerTable.START_ID_MEDIA_BUTTON -> {
if (!sessionHolder.tryMediaButtonIntent(intent)) { if (!sessionHolder.tryMediaButtonIntent(intent)) {
// Malformed intent, need to restore state immediately // Malformed intent, need to restore state immediately
DeferredPlayback.RestoreState( DeferredPlayback.RestoreState(
play = true, fallback = DeferredPlayback.ShuffleAll) play = true,
fallback = DeferredPlayback.ShuffleAll,
)
} else { } else {
null null
} }
@@ -48,7 +48,7 @@ class SystemModule {
@Provides @Provides
fun mediaSourceFactory( fun mediaSourceFactory(
dataSourceFactory: DataSource.Factory, dataSourceFactory: DataSource.Factory,
extractorsFactory: ExtractorsFactory extractorsFactory: ExtractorsFactory,
): MediaSource.Factory = ProgressiveMediaSource.Factory(dataSourceFactory, extractorsFactory) ): MediaSource.Factory = ProgressiveMediaSource.Factory(dataSourceFactory, extractorsFactory)
@Provides @Provides
@@ -70,6 +70,7 @@ class SystemModule {
MatroskaExtractor(DefaultSubtitleParserFactory.UNSUPPORTED), MatroskaExtractor(DefaultSubtitleParserFactory.UNSUPPORTED),
// Enable constant bitrate seeking so that certain MP3s/AACs are seekable // Enable constant bitrate seeking so that certain MP3s/AACs are seekable
AdtsExtractor(AdtsExtractor.FLAG_ENABLE_CONSTANT_BITRATE_SEEKING), AdtsExtractor(AdtsExtractor.FLAG_ENABLE_CONSTANT_BITRATE_SEEKING),
Mp3Extractor(Mp3Extractor.FLAG_ENABLE_CONSTANT_BITRATE_SEEKING)) Mp3Extractor(Mp3Extractor.FLAG_ENABLE_CONSTANT_BITRATE_SEEKING),
)
} }
} }
@@ -40,7 +40,7 @@ private constructor(
private val context: Context, private val context: Context,
private val playbackManager: PlaybackStateManager, private val playbackManager: PlaybackStateManager,
private val playbackSettings: PlaybackSettings, private val playbackSettings: PlaybackSettings,
private val widgetComponent: WidgetComponent private val widgetComponent: WidgetComponent,
) : BroadcastReceiver() { ) : BroadcastReceiver() {
private var initialHeadsetPlugEventHandled = false private var initialHeadsetPlugEventHandled = false
@@ -48,7 +48,7 @@ private constructor(
@Inject @Inject
constructor( constructor(
private val playbackManager: PlaybackStateManager, private val playbackManager: PlaybackStateManager,
private val playbackSettings: PlaybackSettings private val playbackSettings: PlaybackSettings,
) { ) {
fun create(context: Context, widgetComponent: WidgetComponent) = fun create(context: Context, widgetComponent: WidgetComponent) =
SystemPlaybackReceiver(context, playbackManager, playbackSettings, widgetComponent) SystemPlaybackReceiver(context, playbackManager, playbackSettings, widgetComponent)
@@ -57,7 +57,11 @@ private constructor(
@Suppress("WrongConstant") @Suppress("WrongConstant")
fun attach() { fun attach() {
ContextCompat.registerReceiver( ContextCompat.registerReceiver(
context, this, INTENT_FILTER, ContextCompat.RECEIVER_EXPORTED) context,
this,
INTENT_FILTER,
ContextCompat.RECEIVER_EXPORTED,
)
} }
fun release() { fun release() {
@@ -125,9 +129,11 @@ private constructor(
// ACTION_HEADSET_PLUG will fire when this BroadcastReceiver is initially attached, // ACTION_HEADSET_PLUG will fire when this BroadcastReceiver is initially attached,
// which would result in unexpected playback. Work around it by dropping the first // which would result in unexpected playback. Work around it by dropping the first
// call to this function, which should come from that Intent. // call to this function, which should come from that Intent.
if (playbackSettings.headsetAutoplay && if (
playbackManager.currentSong != null && playbackSettings.headsetAutoplay &&
initialHeadsetPlugEventHandled) { playbackManager.currentSong != null &&
initialHeadsetPlugEventHandled
) {
L.d("Device connected, resuming") L.d("Device connected, resuming")
playbackManager.playing(true) playbackManager.playing(true)
} }
@@ -78,7 +78,7 @@ interface PlaybackCommand {
enum class ShuffleMode { enum class ShuffleMode {
ON, ON,
OFF, OFF,
IMPLICIT IMPLICIT,
} }
class PlaybackCommandFactoryImpl class PlaybackCommandFactoryImpl
@@ -87,13 +87,13 @@ constructor(
val playbackManager: PlaybackStateManager, val playbackManager: PlaybackStateManager,
val playbackSettings: PlaybackSettings, val playbackSettings: PlaybackSettings,
val listSettings: ListSettings, val listSettings: ListSettings,
val musicRepository: MusicRepository val musicRepository: MusicRepository,
) : PlaybackCommand.Factory { ) : PlaybackCommand.Factory {
data class PlaybackCommandImpl( data class PlaybackCommandImpl(
override val song: Song?, override val song: Song?,
override val parent: MusicParent?, override val parent: MusicParent?,
override val queue: List<Song>, override val queue: List<Song>,
override val shuffled: Boolean override val shuffled: Boolean,
) : PlaybackCommand { ) : PlaybackCommand {
// Only show queue count to reduce memory use // Only show queue count to reduce memory use
override fun toString() = override fun toString() =
@@ -139,7 +139,7 @@ constructor(
parent: T?, parent: T?,
parents: List<T>, parents: List<T>,
sort: Sort, sort: Sort,
shuffle: ShuffleMode shuffle: ShuffleMode,
): PlaybackCommand? { ): PlaybackCommand? {
return if (parent != null) { return if (parent != null) {
newCommand(song, parent, sort, shuffle) newCommand(song, parent, sort, shuffle)
@@ -159,7 +159,7 @@ constructor(
song: Song?, song: Song?,
parent: MusicParent, parent: MusicParent,
sort: Sort, sort: Sort,
shuffle: ShuffleMode shuffle: ShuffleMode,
): PlaybackCommand? { ): PlaybackCommand? {
val songs = sort.songs(parent.songs) val songs = sort.songs(parent.songs)
return newCommand(song, parent, songs, sort, shuffle) return newCommand(song, parent, songs, sort, shuffle)
@@ -170,7 +170,7 @@ constructor(
parent: MusicParent?, parent: MusicParent?,
queue: Collection<Song>, queue: Collection<Song>,
sort: Sort, sort: Sort,
shuffle: ShuffleMode shuffle: ShuffleMode,
): PlaybackCommand? { ): PlaybackCommand? {
if (queue.isEmpty() || (song != null && song !in queue)) { if (queue.isEmpty() || (song != null && song !in queue)) {
return null return null
@@ -182,7 +182,7 @@ constructor(
song: Song?, song: Song?,
parent: MusicParent?, parent: MusicParent?,
queue: List<Song>, queue: List<Song>,
shuffle: ShuffleMode shuffle: ShuffleMode,
): PlaybackCommand { ): PlaybackCommand {
return PlaybackCommandImpl(song, parent, queue, isShuffled(shuffle)) return PlaybackCommandImpl(song, parent, queue, isShuffled(shuffle))
} }
@@ -150,7 +150,7 @@ interface PlaybackStateHolder {
rawQueue: RawQueue, rawQueue: RawQueue,
positionMs: Long, positionMs: Long,
repeatMode: RepeatMode, repeatMode: RepeatMode,
ack: StateAck.NewPlayback? ack: StateAck.NewPlayback?,
) )
/** End whatever ongoing playback session may be going on */ /** End whatever ongoing playback session may be going on */
@@ -219,11 +219,7 @@ sealed interface StateAck {
* nonsensical value that cannot be used to obtain next and last songs without first resolving the * nonsensical value that cannot be used to obtain next and last songs without first resolving the
* queue. * queue.
*/ */
data class RawQueue( data class RawQueue(val heap: List<Song>, val shuffledMapping: List<Int>, val heapIndex: Int) {
val heap: List<Song>,
val shuffledMapping: List<Int>,
val heapIndex: Int,
) {
/** Whether the queue is currently shuffled. */ /** Whether the queue is currently shuffled. */
val isShuffled = shuffledMapping.isNotEmpty() val isShuffled = shuffledMapping.isNotEmpty()
@@ -275,7 +271,7 @@ data class QueueChange(val type: Type, val instructions: UpdateInstructions) {
* The current song has changed, possibly alongside the mapping and index depending on the * The current song has changed, possibly alongside the mapping and index depending on the
* context. * context.
*/ */
SONG SONG,
} }
} }
@@ -308,7 +304,7 @@ private constructor(
/** The position when this instance was created, in milliseconds. */ /** The position when this instance was created, in milliseconds. */
private val initPositionMs: Long, private val initPositionMs: Long,
/** The time this instance was created, as a unix epoch timestamp. */ /** The time this instance was created, as a unix epoch timestamp. */
private val creationTime: Long private val creationTime: Long,
) { ) {
/** /**
* Calculate the "real" playback position this instance contains, in milliseconds. * Calculate the "real" playback position this instance contains, in milliseconds.
@@ -347,7 +343,8 @@ private constructor(
// Not advancing, so don't move the position. // Not advancing, so don't move the position.
0f 0f
}, },
creationTime) creationTime,
)
// Equality ignores the creation time to prevent functionally identical states // Equality ignores the creation time to prevent functionally identical states
// from being non-equal. // from being non-equal.
@@ -380,13 +377,15 @@ private constructor(
// Minor sanity check: Make sure that advancing can't occur if already paused. // Minor sanity check: Make sure that advancing can't occur if already paused.
isPlaying && isAdvancing, isPlaying && isAdvancing,
positionMs, positionMs,
SystemClock.elapsedRealtime()) SystemClock.elapsedRealtime(),
)
fun nil() = fun nil() =
Progression( Progression(
isPlaying = false, isPlaying = false,
isAdvancing = false, isAdvancing = false,
initPositionMs = 0, initPositionMs = 0,
creationTime = SystemClock.elapsedRealtime()) creationTime = SystemClock.elapsedRealtime(),
)
} }
} }
@@ -296,7 +296,7 @@ interface PlaybackStateManager {
parent: MusicParent?, parent: MusicParent?,
queue: List<Song>, queue: List<Song>,
index: Int, index: Int,
isShuffled: Boolean isShuffled: Boolean,
) {} ) {}
/** /**
@@ -342,7 +342,7 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
val queue: List<Song>, val queue: List<Song>,
val index: Int, val index: Int,
val isShuffled: Boolean, val isShuffled: Boolean,
val rawQueue: RawQueue val rawQueue: RawQueue,
) )
private val listeners = mutableListOf<Listener>() private val listeners = mutableListOf<Listener>()
@@ -356,7 +356,8 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
queue = emptyList(), queue = emptyList(),
index = -1, index = -1,
isShuffled = false, isShuffled = false,
rawQueue = RawQueue.nil()) rawQueue = RawQueue.nil(),
)
@Volatile private var stateHolder: PlaybackStateHolder? = null @Volatile private var stateHolder: PlaybackStateHolder? = null
@Volatile private var pendingDeferredPlayback: DeferredPlayback? = null @Volatile private var pendingDeferredPlayback: DeferredPlayback? = null
@Volatile private var isInitialized = false @Volatile private var isInitialized = false
@@ -393,7 +394,11 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
if (isInitialized) { if (isInitialized) {
L.d("Sending initial state to $listener") L.d("Sending initial state to $listener")
listener.onNewPlayback( listener.onNewPlayback(
stateMirror.parent, stateMirror.queue, stateMirror.index, stateMirror.isShuffled) stateMirror.parent,
stateMirror.queue,
stateMirror.index,
stateMirror.isShuffled,
)
listener.onProgressionChanged(stateMirror.progression) listener.onProgressionChanged(stateMirror.progression)
listener.onRepeatModeChanged(stateMirror.repeatMode) listener.onRepeatModeChanged(stateMirror.repeatMode)
} }
@@ -421,7 +426,8 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
stateMirror.rawQueue, stateMirror.rawQueue,
stateMirror.progression.calculateElapsedPositionMs(), stateMirror.progression.calculateElapsedPositionMs(),
stateMirror.repeatMode, stateMirror.repeatMode,
null) null,
)
} }
pendingDeferredPlayback?.let(stateHolder::handleDeferred) pendingDeferredPlayback?.let(stateHolder::handleDeferred)
} }
@@ -592,11 +598,7 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
val rawQueue = stateHolder.resolveQueue() val rawQueue = stateHolder.resolveQueue()
val change = val change =
QueueChange(QueueChange.Type.MAPPING, UpdateInstructions.Add(ack.at, ack.size)) QueueChange(QueueChange.Type.MAPPING, UpdateInstructions.Add(ack.at, ack.size))
stateMirror = stateMirror = stateMirror.copy(queue = rawQueue.resolveSongs(), rawQueue = rawQueue)
stateMirror.copy(
queue = rawQueue.resolveSongs(),
rawQueue = rawQueue,
)
listeners.forEach { listeners.forEach {
it.onQueueChanged(stateMirror.queue, stateMirror.index, change) it.onQueueChanged(stateMirror.queue, stateMirror.index, change)
} }
@@ -605,11 +607,7 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
val rawQueue = stateHolder.resolveQueue() val rawQueue = stateHolder.resolveQueue()
val change = val change =
QueueChange(QueueChange.Type.MAPPING, UpdateInstructions.Add(ack.at, ack.size)) QueueChange(QueueChange.Type.MAPPING, UpdateInstructions.Add(ack.at, ack.size))
stateMirror = stateMirror = stateMirror.copy(queue = rawQueue.resolveSongs(), rawQueue = rawQueue)
stateMirror.copy(
queue = rawQueue.resolveSongs(),
rawQueue = rawQueue,
)
listeners.forEach { listeners.forEach {
it.onQueueChanged(stateMirror.queue, stateMirror.index, change) it.onQueueChanged(stateMirror.queue, stateMirror.index, change)
} }
@@ -621,7 +619,8 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
QueueChange( QueueChange(
if (stateMirror.index != newIndex) QueueChange.Type.INDEX if (stateMirror.index != newIndex) QueueChange.Type.INDEX
else QueueChange.Type.MAPPING, else QueueChange.Type.MAPPING,
UpdateInstructions.Move(ack.from, ack.to)) UpdateInstructions.Move(ack.from, ack.to),
)
stateMirror = stateMirror =
stateMirror.copy( stateMirror.copy(
@@ -644,7 +643,8 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
stateMirror.index != newIndex -> QueueChange.Type.INDEX stateMirror.index != newIndex -> QueueChange.Type.INDEX
else -> QueueChange.Type.MAPPING else -> QueueChange.Type.MAPPING
}, },
UpdateInstructions.Remove(ack.index, 1)) UpdateInstructions.Remove(ack.index, 1),
)
stateMirror = stateMirror =
stateMirror.copy( stateMirror.copy(
@@ -664,10 +664,14 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
queue = rawQueue.resolveSongs(), queue = rawQueue.resolveSongs(),
index = rawQueue.resolveIndex(), index = rawQueue.resolveIndex(),
isShuffled = rawQueue.isShuffled, isShuffled = rawQueue.isShuffled,
rawQueue = rawQueue) rawQueue = rawQueue,
)
listeners.forEach { listeners.forEach {
it.onQueueReordered( it.onQueueReordered(
stateMirror.queue, stateMirror.index, stateMirror.isShuffled) stateMirror.queue,
stateMirror.index,
stateMirror.isShuffled,
)
} }
} }
is StateAck.NewPlayback -> { is StateAck.NewPlayback -> {
@@ -678,27 +682,23 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
queue = rawQueue.resolveSongs(), queue = rawQueue.resolveSongs(),
index = rawQueue.resolveIndex(), index = rawQueue.resolveIndex(),
isShuffled = rawQueue.isShuffled, isShuffled = rawQueue.isShuffled,
rawQueue = rawQueue) rawQueue = rawQueue,
)
listeners.forEach { listeners.forEach {
it.onNewPlayback( it.onNewPlayback(
stateMirror.parent, stateMirror.parent,
stateMirror.queue, stateMirror.queue,
stateMirror.index, stateMirror.index,
stateMirror.isShuffled) stateMirror.isShuffled,
)
} }
} }
is StateAck.ProgressionChanged -> { is StateAck.ProgressionChanged -> {
stateMirror = stateMirror = stateMirror.copy(progression = stateHolder.progression)
stateMirror.copy(
progression = stateHolder.progression,
)
listeners.forEach { it.onProgressionChanged(stateMirror.progression) } listeners.forEach { it.onProgressionChanged(stateMirror.progression) }
} }
is StateAck.RepeatModeChanged -> { is StateAck.RepeatModeChanged -> {
stateMirror = stateMirror = stateMirror.copy(repeatMode = stateHolder.repeatMode)
stateMirror.copy(
repeatMode = stateHolder.repeatMode,
)
listeners.forEach { it.onRepeatModeChanged(stateMirror.repeatMode) } listeners.forEach { it.onRepeatModeChanged(stateMirror.repeatMode) }
} }
is StateAck.SessionEnded -> { is StateAck.SessionEnded -> {
@@ -726,7 +726,7 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
@Synchronized @Synchronized
override fun applySavedState( override fun applySavedState(
savedState: PlaybackStateManager.SavedState, savedState: PlaybackStateManager.SavedState,
destructive: Boolean destructive: Boolean,
) { ) {
if (isInitialized && !destructive) { if (isInitialized && !destructive) {
L.w("Already initialized, cannot apply saved state") L.w("Already initialized, cannot apply saved state")
@@ -795,14 +795,16 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
shuffledMapping[index] shuffledMapping[index]
} else { } else {
index index
}) },
)
stateHolder.applySavedState( stateHolder.applySavedState(
savedState.parent, savedState.parent,
rawQueue, rawQueue,
savedState.positionMs, savedState.positionMs,
savedState.repeatMode, savedState.repeatMode,
StateAck.NewPlayback) StateAck.NewPlayback,
)
isInitialized = true isInitialized = true
} }

Some files were not shown because too many files have changed in this diff Show More