all: cleanup code issues
This commit is contained in:
@@ -18,6 +18,7 @@
|
||||
|
||||
package org.oxycblt.auxio
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.os.Bundle
|
||||
import android.view.LayoutInflater
|
||||
import android.view.ViewTreeObserver
|
||||
@@ -107,6 +108,7 @@ class MainFragment :
|
||||
|
||||
override fun onCreateBinding(inflater: LayoutInflater) = FragmentMainBinding.inflate(inflater)
|
||||
|
||||
@SuppressLint("PrivateResource")
|
||||
override fun onBindingCreated(binding: FragmentMainBinding, savedInstanceState: Bundle?) {
|
||||
super.onBindingCreated(binding, savedInstanceState)
|
||||
|
||||
@@ -761,7 +763,7 @@ class MainFragment :
|
||||
}
|
||||
}
|
||||
|
||||
private inner class SelectionBackPressedCallback(private val listModel: ListViewModel) :
|
||||
private class SelectionBackPressedCallback(private val listModel: ListViewModel) :
|
||||
OnBackPressedCallback(false) {
|
||||
override fun handleOnBackPressed() {
|
||||
if (listModel.dropSelection()) {
|
||||
|
||||
@@ -69,47 +69,35 @@ constructor(
|
||||
private val playbackSettings: PlaybackSettings,
|
||||
detailGeneratorFactory: DetailGenerator.Factory,
|
||||
) : ViewModel(), DetailGenerator.Invalidator {
|
||||
private val _toShow = MutableEvent<Show>()
|
||||
|
||||
/**
|
||||
* A [Show] command that is awaiting a view capable of responding to it. Null if none currently.
|
||||
*/
|
||||
val toShow: Event<Show>
|
||||
get() = _toShow
|
||||
field = MutableEvent<Show>()
|
||||
|
||||
// --- SONG ---
|
||||
|
||||
private val _currentSong = MutableStateFlow<Song?>(null)
|
||||
|
||||
/** The current [Song] to display. Null if there is nothing to show. */
|
||||
val currentSong: StateFlow<Song?>
|
||||
get() = _currentSong
|
||||
|
||||
private val _currentSongProperties = MutableStateFlow<List<SongProperty>>(listOf())
|
||||
field = MutableStateFlow<Song?>(null)
|
||||
|
||||
/** The current properties of [currentSong]. Empty if nothing to show. */
|
||||
val currentSongProperties: StateFlow<List<SongProperty>>
|
||||
get() = _currentSongProperties
|
||||
field = MutableStateFlow<List<SongProperty>>(listOf())
|
||||
|
||||
// --- ALBUM ---
|
||||
|
||||
private val _currentAlbum = MutableStateFlow<Album?>(null)
|
||||
|
||||
/** The current [Album] to display. Null if there is nothing to show. */
|
||||
val currentAlbum: StateFlow<Album?>
|
||||
get() = _currentAlbum
|
||||
|
||||
private val _albumSongList = MutableStateFlow(listOf<Item>())
|
||||
field = MutableStateFlow<Album?>(null)
|
||||
|
||||
/** The current list data derived from [currentAlbum]. */
|
||||
val albumSongList: StateFlow<List<Item>>
|
||||
get() = _albumSongList
|
||||
|
||||
private val _albumSongInstructions = MutableEvent<UpdateInstructions>()
|
||||
field = MutableStateFlow(listOf<Item>())
|
||||
|
||||
/** Instructions for updating [albumSongList] in the UI. */
|
||||
val albumSongInstructions: Event<UpdateInstructions>
|
||||
get() = _albumSongInstructions
|
||||
field = MutableEvent<UpdateInstructions>()
|
||||
|
||||
/** The current [Sort] used for [Song]s in [albumSongList]. */
|
||||
val albumSongSort: Sort
|
||||
@@ -121,22 +109,18 @@ constructor(
|
||||
|
||||
// --- ARTIST ---
|
||||
|
||||
private val _currentArtist = MutableStateFlow<Artist?>(null)
|
||||
|
||||
/** The current [Artist] to display. Null if there is nothing to show. */
|
||||
val currentArtist: StateFlow<Artist?>
|
||||
get() = _currentArtist
|
||||
field = MutableStateFlow<Artist?>(null)
|
||||
|
||||
private val _artistSongList = MutableStateFlow(listOf<Item>())
|
||||
|
||||
/** The current list derived from [currentArtist]. */
|
||||
val artistSongList: StateFlow<List<Item>> = _artistSongList
|
||||
|
||||
private val _artistSongInstructions = MutableEvent<UpdateInstructions>()
|
||||
|
||||
/** Instructions for updating [artistSongList] in the UI. */
|
||||
val artistSongInstructions: Event<UpdateInstructions>
|
||||
get() = _artistSongInstructions
|
||||
field = MutableEvent<UpdateInstructions>()
|
||||
|
||||
/** The current [Sort] used for [Song]s in [artistSongList]. */
|
||||
val artistSongSort: Sort
|
||||
@@ -148,22 +132,18 @@ constructor(
|
||||
|
||||
// --- GENRE ---
|
||||
|
||||
private val _currentGenre = MutableStateFlow<Genre?>(null)
|
||||
|
||||
/** The current [Genre] to display. Null if there is nothing to show. */
|
||||
val currentGenre: StateFlow<Genre?>
|
||||
get() = _currentGenre
|
||||
field = MutableStateFlow<Genre?>(null)
|
||||
|
||||
private val _genreSongList = MutableStateFlow(listOf<Item>())
|
||||
|
||||
/** The current list data derived from [currentGenre]. */
|
||||
val genreSongList: StateFlow<List<Item>> = _genreSongList
|
||||
|
||||
private val _genreSongInstructions = MutableEvent<UpdateInstructions>()
|
||||
|
||||
/** Instructions for updating [artistSongList] in the UI. */
|
||||
val genreSongInstructions: Event<UpdateInstructions>
|
||||
get() = _genreSongInstructions
|
||||
field = MutableEvent<UpdateInstructions>()
|
||||
|
||||
/** The current [Sort] used for [Song]s in [genreSongList]. */
|
||||
val genreSongSort: Sort
|
||||
@@ -175,31 +155,25 @@ constructor(
|
||||
|
||||
// --- PLAYLIST ---
|
||||
|
||||
private val _currentPlaylist = MutableStateFlow<Playlist?>(null)
|
||||
|
||||
/** The current [Playlist] to display. Null if there is nothing to do. */
|
||||
val currentPlaylist: StateFlow<Playlist?>
|
||||
get() = _currentPlaylist
|
||||
field = MutableStateFlow<Playlist?>(null)
|
||||
|
||||
private val _playlistSongList = MutableStateFlow(listOf<Item>())
|
||||
|
||||
/** The current list data derived from [currentPlaylist] */
|
||||
val playlistSongList: StateFlow<List<Item>> = _playlistSongList
|
||||
|
||||
private val _playlistSongInstructions = MutableEvent<UpdateInstructions>()
|
||||
|
||||
/** Instructions for updating [playlistSongList] in the UI. */
|
||||
val playlistSongInstructions: Event<UpdateInstructions>
|
||||
get() = _playlistSongInstructions
|
||||
|
||||
private val _editedPlaylist = MutableStateFlow<List<Song>?>(null)
|
||||
field = MutableEvent<UpdateInstructions>()
|
||||
|
||||
/**
|
||||
* The new playlist songs created during the current editing session. Null if no editing session
|
||||
* is occurring.
|
||||
*/
|
||||
val editedPlaylist: StateFlow<List<Song>?>
|
||||
get() = _editedPlaylist
|
||||
field = MutableStateFlow<List<Song>?>(null)
|
||||
|
||||
/** The [PlaySong] instructions to use when playing a [Song] from [Genre] details. */
|
||||
val playInPlaylistWith
|
||||
@@ -221,21 +195,21 @@ constructor(
|
||||
when (type) {
|
||||
MusicType.ALBUMS -> {
|
||||
val album = detailGenerator.album(currentAlbum.value?.uid ?: return)
|
||||
refreshDetail(album, _currentAlbum, _albumSongList, _albumSongInstructions, replace)
|
||||
refreshDetail(album, currentAlbum, albumSongList, albumSongInstructions, replace)
|
||||
}
|
||||
MusicType.ARTISTS -> {
|
||||
val artist = detailGenerator.artist(currentArtist.value?.uid ?: return)
|
||||
refreshDetail(
|
||||
artist,
|
||||
_currentArtist,
|
||||
currentArtist,
|
||||
_artistSongList,
|
||||
_artistSongInstructions,
|
||||
artistSongInstructions,
|
||||
replace,
|
||||
)
|
||||
}
|
||||
MusicType.GENRES -> {
|
||||
val genre = detailGenerator.genre(currentGenre.value?.uid ?: return)
|
||||
refreshDetail(genre, _currentGenre, _genreSongList, _genreSongInstructions, replace)
|
||||
refreshDetail(genre, currentGenre, _genreSongList, genreSongInstructions, replace)
|
||||
}
|
||||
MusicType.PLAYLISTS -> {
|
||||
refreshPlaylist(currentPlaylist.value?.uid ?: return)
|
||||
@@ -322,7 +296,7 @@ constructor(
|
||||
L.d("Already have pending show command $existing, ignoring $show")
|
||||
return
|
||||
}
|
||||
_toShow.put(show)
|
||||
toShow.put(show)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -333,8 +307,8 @@ constructor(
|
||||
*/
|
||||
fun setSong(uid: Music.UID) {
|
||||
L.d("Opening song $uid")
|
||||
_currentSong.value = musicRepository.library?.findSong(uid)?.also(::refreshAudioInfo)
|
||||
if (_currentSong.value == null) {
|
||||
currentSong.value = musicRepository.library?.findSong(uid)?.also(::refreshAudioInfo)
|
||||
if (currentSong.value == null) {
|
||||
L.w("Given song UID was invalid")
|
||||
}
|
||||
}
|
||||
@@ -347,12 +321,12 @@ constructor(
|
||||
*/
|
||||
fun setAlbum(uid: Music.UID) {
|
||||
L.d("Opening album $uid")
|
||||
if (uid === _currentAlbum.value?.uid) {
|
||||
if (uid === currentAlbum.value?.uid) {
|
||||
return
|
||||
}
|
||||
val album = detailGenerator.album(uid)
|
||||
refreshDetail(album, _currentAlbum, _albumSongList, _albumSongInstructions, null)
|
||||
if (_currentAlbum.value == null) {
|
||||
refreshDetail(album, currentAlbum, albumSongList, albumSongInstructions, null)
|
||||
if (currentAlbum.value == null) {
|
||||
L.w("Given album UID was invalid")
|
||||
}
|
||||
}
|
||||
@@ -374,11 +348,11 @@ constructor(
|
||||
*/
|
||||
fun setArtist(uid: Music.UID) {
|
||||
L.d("Opening artist $uid")
|
||||
if (uid === _currentArtist.value?.uid) {
|
||||
if (uid === currentArtist.value?.uid) {
|
||||
return
|
||||
}
|
||||
val artist = detailGenerator.artist(uid)
|
||||
refreshDetail(artist, _currentArtist, _artistSongList, _artistSongInstructions, null)
|
||||
refreshDetail(artist, currentArtist, _artistSongList, artistSongInstructions, null)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -398,11 +372,11 @@ constructor(
|
||||
*/
|
||||
fun setGenre(uid: Music.UID) {
|
||||
L.d("Opening genre $uid")
|
||||
if (uid === _currentGenre.value?.uid) {
|
||||
if (uid === currentGenre.value?.uid) {
|
||||
return
|
||||
}
|
||||
val genre = detailGenerator.genre(uid)
|
||||
refreshDetail(genre, _currentGenre, _genreSongList, _genreSongInstructions, null)
|
||||
refreshDetail(genre, currentGenre, _genreSongList, genreSongInstructions, null)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -422,7 +396,7 @@ constructor(
|
||||
*/
|
||||
fun setPlaylist(uid: Music.UID) {
|
||||
L.d("Opening playlist $uid")
|
||||
if (uid === _currentPlaylist.value?.uid) {
|
||||
if (uid === currentPlaylist.value?.uid) {
|
||||
return
|
||||
}
|
||||
refreshPlaylist(uid)
|
||||
@@ -430,9 +404,9 @@ constructor(
|
||||
|
||||
/** Start a playlist editing session. Does nothing if a playlist is not being shown. */
|
||||
fun startPlaylistEdit() {
|
||||
val playlist = _currentPlaylist.value ?: return
|
||||
val playlist = currentPlaylist.value ?: return
|
||||
L.d("Starting playlist edit")
|
||||
_editedPlaylist.value = playlist.songs
|
||||
editedPlaylist.value = playlist.songs
|
||||
refreshPlaylist(playlist.uid)
|
||||
}
|
||||
|
||||
@@ -441,14 +415,14 @@ constructor(
|
||||
* prior editing session.
|
||||
*/
|
||||
fun savePlaylistEdit() {
|
||||
val playlist = _currentPlaylist.value ?: return
|
||||
val editedPlaylist = _editedPlaylist.value ?: return
|
||||
val playlist = currentPlaylist.value ?: return
|
||||
val editedPlaylist = editedPlaylist.value ?: return
|
||||
L.d("Committing playlist edits")
|
||||
viewModelScope.launch {
|
||||
musicRepository.rewritePlaylist(playlist, editedPlaylist)
|
||||
// TODO: The user could probably press some kind of button if they were fast enough.
|
||||
// Think of a better way to handle this state.
|
||||
_editedPlaylist.value = null
|
||||
this@DetailViewModel.editedPlaylist.value = null
|
||||
refreshPlaylist(playlist.uid)
|
||||
}
|
||||
}
|
||||
@@ -460,12 +434,12 @@ constructor(
|
||||
* @return true if the session was ended, false otherwise.
|
||||
*/
|
||||
fun dropPlaylistEdit(): Boolean {
|
||||
val playlist = _currentPlaylist.value ?: return false
|
||||
if (_editedPlaylist.value == null) {
|
||||
val playlist = currentPlaylist.value ?: return false
|
||||
if (editedPlaylist.value == null) {
|
||||
// Nothing to do.
|
||||
return false
|
||||
}
|
||||
_editedPlaylist.value = null
|
||||
editedPlaylist.value = null
|
||||
refreshPlaylist(playlist.uid)
|
||||
return true
|
||||
}
|
||||
@@ -476,8 +450,8 @@ constructor(
|
||||
* @param sort The [Sort] to apply.
|
||||
*/
|
||||
fun applyPlaylistSongSort(sort: Sort) {
|
||||
val playlist = _currentPlaylist.value ?: return
|
||||
_editedPlaylist.value = sort.songs(_editedPlaylist.value ?: return)
|
||||
val playlist = currentPlaylist.value ?: return
|
||||
editedPlaylist.value = sort.songs(editedPlaylist.value ?: return)
|
||||
refreshPlaylist(playlist.uid, UpdateInstructions.Replace(1))
|
||||
}
|
||||
|
||||
@@ -489,8 +463,8 @@ constructor(
|
||||
* @return true if the song was moved, false otherwise.
|
||||
*/
|
||||
fun movePlaylistSongs(from: Int, to: Int): Boolean {
|
||||
val playlist = _currentPlaylist.value ?: return false
|
||||
val editedPlaylist = (_editedPlaylist.value ?: return false).toMutableList()
|
||||
val playlist = currentPlaylist.value ?: return false
|
||||
val editedPlaylist = (editedPlaylist.value ?: return false).toMutableList()
|
||||
val realFrom = from - 1
|
||||
val realTo = to - 1
|
||||
if (realFrom !in editedPlaylist.indices || realTo !in editedPlaylist.indices) {
|
||||
@@ -498,7 +472,7 @@ constructor(
|
||||
}
|
||||
L.d("Moving playlist song from $realFrom [$from] to $realTo [$to]")
|
||||
editedPlaylist.add(realFrom, editedPlaylist.removeAt(realTo))
|
||||
_editedPlaylist.value = editedPlaylist
|
||||
this.editedPlaylist.value = editedPlaylist
|
||||
refreshPlaylist(playlist.uid, UpdateInstructions.Move(from, to))
|
||||
return true
|
||||
}
|
||||
@@ -509,15 +483,15 @@ constructor(
|
||||
* @param at The position of the item to remove, in the list adapter data.
|
||||
*/
|
||||
fun removePlaylistSong(at: Int) {
|
||||
val playlist = _currentPlaylist.value ?: return
|
||||
val editedPlaylist = (_editedPlaylist.value ?: return).toMutableList()
|
||||
val playlist = currentPlaylist.value ?: return
|
||||
val editedPlaylist = (editedPlaylist.value ?: return).toMutableList()
|
||||
val realAt = at - 1
|
||||
if (realAt !in editedPlaylist.indices) {
|
||||
return
|
||||
}
|
||||
L.d("Removing playlist song at $realAt [$at]")
|
||||
editedPlaylist.removeAt(realAt)
|
||||
_editedPlaylist.value = editedPlaylist
|
||||
this.editedPlaylist.value = editedPlaylist
|
||||
refreshPlaylist(
|
||||
playlist.uid,
|
||||
if (editedPlaylist.isNotEmpty()) {
|
||||
@@ -530,7 +504,7 @@ constructor(
|
||||
}
|
||||
|
||||
private fun refreshAudioInfo(song: Song) {
|
||||
_currentSongProperties.value = buildList {
|
||||
currentSongProperties.value = buildList {
|
||||
add(SongProperty(R.string.lbl_name, SongProperty.Value.MusicName(song)))
|
||||
add(SongProperty(R.string.lbl_album, SongProperty.Value.MusicName(song.album)))
|
||||
add(SongProperty(R.string.lbl_artists, SongProperty.Value.MusicNames(song.artists)))
|
||||
@@ -630,9 +604,9 @@ constructor(
|
||||
val playlist = detailGenerator.playlist(uid)
|
||||
refreshDetail(
|
||||
playlist,
|
||||
_currentPlaylist,
|
||||
currentPlaylist,
|
||||
_playlistSongList,
|
||||
_playlistSongInstructions,
|
||||
playlistSongInstructions,
|
||||
null,
|
||||
) {
|
||||
EditHeader(it)
|
||||
@@ -645,7 +619,7 @@ constructor(
|
||||
list.add(header)
|
||||
list.addAll(edited)
|
||||
}
|
||||
_playlistSongInstructions.put(instructions)
|
||||
playlistSongInstructions.put(instructions)
|
||||
_playlistSongList.value = list
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,6 @@ package org.oxycblt.auxio.detail
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.util.AttributeSet
|
||||
import android.view.View
|
||||
import androidx.appcompat.R
|
||||
import com.google.android.material.textfield.TextInputEditText
|
||||
|
||||
@@ -44,7 +43,7 @@ constructor(
|
||||
// Enable selection, but still disable focus (i.e Keyboard opening)
|
||||
setTextIsSelectable(true)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
focusable = View.FOCUSABLE_AUTO
|
||||
focusable = FOCUSABLE_AUTO
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -40,17 +40,15 @@ import timber.log.Timber as L
|
||||
@HiltViewModel
|
||||
class DetailPickerViewModel @Inject constructor(private val musicRepository: MusicRepository) :
|
||||
ViewModel(), MusicRepository.UpdateListener {
|
||||
private val _artistChoices = MutableStateFlow<ArtistShowChoices?>(null)
|
||||
/** The current set of [Artist] choices to show in the picker, or null if to show nothing. */
|
||||
val artistChoices: StateFlow<ArtistShowChoices?>
|
||||
get() = _artistChoices
|
||||
field = MutableStateFlow<ArtistShowChoices?>(null)
|
||||
|
||||
init {
|
||||
musicRepository.addUpdateListener(this)
|
||||
}
|
||||
|
||||
override fun onCleared() {
|
||||
super.onCleared()
|
||||
musicRepository.removeUpdateListener(this)
|
||||
}
|
||||
|
||||
@@ -58,8 +56,8 @@ class DetailPickerViewModel @Inject constructor(private val musicRepository: Mus
|
||||
if (!changes.deviceLibrary) return
|
||||
val library = musicRepository.library ?: return
|
||||
// Need to sanitize different items depending on the current set of choices.
|
||||
_artistChoices.value = _artistChoices.value?.sanitize(library)
|
||||
L.d("Updated artist choices: ${_artistChoices.value}")
|
||||
artistChoices.value = artistChoices.value?.sanitize(library)
|
||||
L.d("Updated artist choices: ${artistChoices.value}")
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -70,7 +68,7 @@ class DetailPickerViewModel @Inject constructor(private val musicRepository: Mus
|
||||
fun setArtistChoiceUid(itemUid: Music.UID) {
|
||||
L.d("Opening navigation choices for $itemUid")
|
||||
// Support Songs and Albums, which have parent artists.
|
||||
_artistChoices.value =
|
||||
artistChoices.value =
|
||||
when (val music = musicRepository.find(itemUid)) {
|
||||
is Song -> {
|
||||
L.d("Creating navigation choices for song")
|
||||
|
||||
@@ -86,12 +86,14 @@ class AlbumDetailListAdapter(private val listener: Listener<Song>) :
|
||||
val DIFF_CALLBACK =
|
||||
object : SimpleDiffCallback<Item>() {
|
||||
override fun areContentsTheSame(oldItem: Item, newItem: Item) =
|
||||
when {
|
||||
oldItem is Disc && newItem is Disc ->
|
||||
when (oldItem) {
|
||||
is Disc if newItem is Disc ->
|
||||
DiscHeaderViewHolder.DIFF_CALLBACK.areContentsTheSame(oldItem, newItem)
|
||||
oldItem is DiscDivider && newItem is DiscDivider ->
|
||||
|
||||
is DiscDivider if newItem is DiscDivider ->
|
||||
DiscDividerViewHolder.DIFF_CALLBACK.areContentsTheSame(oldItem, newItem)
|
||||
oldItem is Song && newItem is Song ->
|
||||
|
||||
is Song if newItem is Song ->
|
||||
AlbumSongViewHolder.DIFF_CALLBACK.areContentsTheSame(oldItem, newItem)
|
||||
|
||||
// Fall back to DetailAdapter's differ to handle other headers.
|
||||
|
||||
@@ -73,11 +73,13 @@ class ArtistDetailListAdapter(private val listener: Listener<Music>) :
|
||||
val DIFF_CALLBACK =
|
||||
object : SimpleDiffCallback<Item>() {
|
||||
override fun areContentsTheSame(oldItem: Item, newItem: Item) =
|
||||
when {
|
||||
oldItem is Album && newItem is Album ->
|
||||
when (oldItem) {
|
||||
is Album if newItem is Album ->
|
||||
ArtistAlbumViewHolder.DIFF_CALLBACK.areContentsTheSame(oldItem, newItem)
|
||||
oldItem is Song && newItem is Song ->
|
||||
|
||||
is Song if newItem is Song ->
|
||||
ArtistSongViewHolder.DIFF_CALLBACK.areContentsTheSame(oldItem, newItem)
|
||||
|
||||
else -> DetailListAdapter.DIFF_CALLBACK.areContentsTheSame(oldItem, newItem)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,13 +89,16 @@ abstract class DetailListAdapter(
|
||||
val DIFF_CALLBACK =
|
||||
object : SimpleDiffCallback<Item>() {
|
||||
override fun areContentsTheSame(oldItem: Item, newItem: Item): Boolean {
|
||||
return when {
|
||||
oldItem is PlainDivider && newItem is PlainDivider ->
|
||||
return when (oldItem) {
|
||||
is PlainDivider if newItem is PlainDivider ->
|
||||
DividerViewHolder.DIFF_CALLBACK.areContentsTheSame(oldItem, newItem)
|
||||
oldItem is BasicHeader && newItem is BasicHeader ->
|
||||
|
||||
is BasicHeader if newItem is BasicHeader ->
|
||||
BasicHeaderViewHolder.DIFF_CALLBACK.areContentsTheSame(oldItem, newItem)
|
||||
oldItem is SortHeader && newItem is SortHeader ->
|
||||
|
||||
is SortHeader if newItem is SortHeader ->
|
||||
SortHeaderViewHolder.DIFF_CALLBACK.areContentsTheSame(oldItem, newItem)
|
||||
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,11 +64,13 @@ class GenreDetailListAdapter(private val listener: Listener<Music>) :
|
||||
val DIFF_CALLBACK =
|
||||
object : SimpleDiffCallback<Item>() {
|
||||
override fun areContentsTheSame(oldItem: Item, newItem: Item) =
|
||||
when {
|
||||
oldItem is Artist && newItem is Artist ->
|
||||
when (oldItem) {
|
||||
is Artist if newItem is Artist ->
|
||||
ArtistViewHolder.DIFF_CALLBACK.areContentsTheSame(oldItem, newItem)
|
||||
oldItem is Song && newItem is Song ->
|
||||
|
||||
is Song if newItem is Song ->
|
||||
SongViewHolder.DIFF_CALLBACK.areContentsTheSame(oldItem, newItem)
|
||||
|
||||
else -> DetailListAdapter.DIFF_CALLBACK.areContentsTheSame(oldItem, newItem)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,14 +128,16 @@ class PlaylistDetailListAdapter(private val listener: Listener) :
|
||||
val DIFF_CALLBACK =
|
||||
object : SimpleDiffCallback<Item>() {
|
||||
override fun areContentsTheSame(oldItem: Item, newItem: Item) =
|
||||
when {
|
||||
oldItem is Song && newItem is Song ->
|
||||
when (oldItem) {
|
||||
is Song if newItem is Song ->
|
||||
PlaylistSongViewHolder.DIFF_CALLBACK.areContentsTheSame(
|
||||
oldItem,
|
||||
newItem,
|
||||
)
|
||||
oldItem is EditHeader && newItem is EditHeader ->
|
||||
|
||||
is EditHeader if newItem is EditHeader ->
|
||||
EditHeaderViewHolder.DIFF_CALLBACK.areContentsTheSame(oldItem, newItem)
|
||||
|
||||
else -> DetailListAdapter.DIFF_CALLBACK.areContentsTheSame(oldItem, newItem)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,13 +75,11 @@ class HomeSettingsImpl @Inject constructor(@ApplicationContext context: Context)
|
||||
val oldTabs =
|
||||
Tab.fromIntCode(sharedPreferences.getInt(OLD_KEY_LIB_TABS, Tab.SEQUENCE_DEFAULT))
|
||||
?: unlikelyToBeNull(Tab.fromIntCode(Tab.SEQUENCE_DEFAULT))
|
||||
L.d("Old tabs: $oldTabs")
|
||||
|
||||
// The playlist tab is now parsed, but it needs to be made visible.
|
||||
val playlistIndex = oldTabs.indexOfFirst { it.type == MusicType.PLAYLISTS }
|
||||
check(playlistIndex > -1) // This should exist, otherwise we are in big trouble
|
||||
oldTabs[playlistIndex] = Tab.Visible(MusicType.PLAYLISTS)
|
||||
L.d("New tabs: $oldTabs")
|
||||
|
||||
sharedPreferences.edit {
|
||||
putInt(getString(R.string.set_key_home_tabs), Tab.toIntCode(oldTabs))
|
||||
|
||||
@@ -52,15 +52,13 @@ constructor(
|
||||
private val playbackSettings: PlaybackSettings,
|
||||
homeGeneratorFactory: HomeGenerator.Factory,
|
||||
) : ViewModel(), HomeGenerator.Invalidator {
|
||||
private val _songList = MutableStateFlow(listOf<Song>())
|
||||
/** A list of [Song]s, sorted by the preferred [Sort], to be shown in the home view. */
|
||||
val songList: StateFlow<List<Song>>
|
||||
get() = _songList
|
||||
field = MutableStateFlow(listOf<Song>())
|
||||
|
||||
private val _songInstructions = MutableEvent<UpdateInstructions>()
|
||||
/** Instructions for how to update [songList] in the UI. */
|
||||
val songInstructions: Event<UpdateInstructions>
|
||||
get() = _songInstructions
|
||||
field = MutableEvent<UpdateInstructions>()
|
||||
|
||||
/** The current [Sort] used for [songList]. */
|
||||
val songSort: Sort
|
||||
@@ -70,15 +68,13 @@ constructor(
|
||||
val playWith
|
||||
get() = playbackSettings.playInListWith
|
||||
|
||||
private val _albumList = MutableStateFlow(listOf<Album>())
|
||||
/** A list of [Album]s, sorted by the preferred [Sort], to be shown in the home view. */
|
||||
val albumList: StateFlow<List<Album>>
|
||||
get() = _albumList
|
||||
field = MutableStateFlow(listOf<Album>())
|
||||
|
||||
private val _albumInstructions = MutableEvent<UpdateInstructions>()
|
||||
/** Instructions for how to update [albumList] in the UI. */
|
||||
val albumInstructions: Event<UpdateInstructions>
|
||||
get() = _albumInstructions
|
||||
field = MutableEvent<UpdateInstructions>()
|
||||
|
||||
/** The current [Sort] used for [albumList]. */
|
||||
val albumSort: Sort
|
||||
@@ -92,42 +88,36 @@ constructor(
|
||||
val artistList: MutableStateFlow<List<Artist>>
|
||||
get() = _artistList
|
||||
|
||||
private val _artistInstructions = MutableEvent<UpdateInstructions>()
|
||||
/** Instructions for how to update [artistList] in the UI. */
|
||||
val artistInstructions: Event<UpdateInstructions>
|
||||
get() = _artistInstructions
|
||||
field = MutableEvent<UpdateInstructions>()
|
||||
|
||||
/** The current [Sort] used for [artistList]. */
|
||||
val artistSort: Sort
|
||||
get() = listSettings.artistSort
|
||||
|
||||
private val _genreList = MutableStateFlow(listOf<Genre>())
|
||||
/** A list of [Genre]s, sorted by the preferred [Sort], to be shown in the home view. */
|
||||
val genreList: StateFlow<List<Genre>>
|
||||
get() = _genreList
|
||||
field = MutableStateFlow(listOf<Genre>())
|
||||
|
||||
private val _genreInstructions = MutableEvent<UpdateInstructions>()
|
||||
/** Instructions for how to update [genreList] in the UI. */
|
||||
val genreInstructions: Event<UpdateInstructions>
|
||||
get() = _genreInstructions
|
||||
field = MutableEvent<UpdateInstructions>()
|
||||
|
||||
/** The current [Sort] used for [genreList]. */
|
||||
val genreSort: Sort
|
||||
get() = listSettings.genreSort
|
||||
|
||||
private val _playlistList = MutableStateFlow(listOf<Playlist>())
|
||||
/** A list of [Playlist]s, sorted by the preferred [Sort], to be shown in the home view. */
|
||||
val playlistList: StateFlow<List<Playlist>>
|
||||
get() = _playlistList
|
||||
field = MutableStateFlow(listOf<Playlist>())
|
||||
|
||||
private val _empty = MutableStateFlow(false)
|
||||
val empty: StateFlow<Boolean>
|
||||
get() = _empty
|
||||
field = MutableStateFlow(false)
|
||||
|
||||
private val _playlistInstructions = MutableEvent<UpdateInstructions>()
|
||||
/** Instructions for how to update [genreList] in the UI. */
|
||||
val playlistInstructions: Event<UpdateInstructions>
|
||||
get() = _playlistInstructions
|
||||
field = MutableEvent<UpdateInstructions>()
|
||||
|
||||
/** The current [Sort] used for [genreList]. */
|
||||
val playlistSort: Sort
|
||||
@@ -146,68 +136,64 @@ constructor(
|
||||
/** The [MusicType] of the currently shown [Tab]. */
|
||||
val currentTabType: StateFlow<MusicType> = _currentTabType
|
||||
|
||||
private val _shouldRecreate = MutableEvent<Unit>()
|
||||
/**
|
||||
* A marker to re-create all library tabs, usually initiated by a settings change. When this
|
||||
* flag is true, all tabs (and their respective ViewPager2 fragments) will be re-created from
|
||||
* scratch.
|
||||
*/
|
||||
val recreateTabs: Event<Unit>
|
||||
get() = _shouldRecreate
|
||||
field = MutableEvent<Unit>()
|
||||
|
||||
private val _isFastScrolling = MutableStateFlow(false)
|
||||
/** A marker for whether the user is fast-scrolling in the home view or not. */
|
||||
val isFastScrolling: StateFlow<Boolean> = _isFastScrolling
|
||||
|
||||
private val _showOuter = MutableEvent<Outer>()
|
||||
val showOuter: Event<Outer>
|
||||
get() = _showOuter
|
||||
field = MutableEvent<Outer>()
|
||||
|
||||
private val _chooseMusicLocations = MutableEvent<Unit>()
|
||||
val chooseMusicLocations: Event<Unit>
|
||||
get() = _chooseMusicLocations
|
||||
field = MutableEvent<Unit>()
|
||||
|
||||
init {
|
||||
homeGenerator.attach()
|
||||
}
|
||||
|
||||
override fun onCleared() {
|
||||
super.onCleared()
|
||||
homeGenerator.release()
|
||||
}
|
||||
|
||||
override fun invalidateEmpty() {
|
||||
_empty.value = homeGenerator.empty()
|
||||
empty.value = homeGenerator.empty()
|
||||
}
|
||||
|
||||
override fun invalidateMusic(type: MusicType, instructions: UpdateInstructions) {
|
||||
when (type) {
|
||||
MusicType.SONGS -> {
|
||||
_songInstructions.put(instructions)
|
||||
_songList.value = homeGenerator.songs()
|
||||
songInstructions.put(instructions)
|
||||
songList.value = homeGenerator.songs()
|
||||
}
|
||||
MusicType.ALBUMS -> {
|
||||
_albumInstructions.put(instructions)
|
||||
_albumList.value = homeGenerator.albums()
|
||||
albumInstructions.put(instructions)
|
||||
albumList.value = homeGenerator.albums()
|
||||
}
|
||||
MusicType.ARTISTS -> {
|
||||
_artistInstructions.put(instructions)
|
||||
artistInstructions.put(instructions)
|
||||
_artistList.value = homeGenerator.artists()
|
||||
}
|
||||
MusicType.GENRES -> {
|
||||
_genreInstructions.put(instructions)
|
||||
_genreList.value = homeGenerator.genres()
|
||||
genreInstructions.put(instructions)
|
||||
genreList.value = homeGenerator.genres()
|
||||
}
|
||||
MusicType.PLAYLISTS -> {
|
||||
_playlistInstructions.put(instructions)
|
||||
_playlistList.value = homeGenerator.playlists()
|
||||
playlistInstructions.put(instructions)
|
||||
playlistList.value = homeGenerator.playlists()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun invalidateTabs() {
|
||||
currentTabTypes = homeGenerator.tabs()
|
||||
_shouldRecreate.put(Unit)
|
||||
recreateTabs.put(Unit)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -276,15 +262,15 @@ constructor(
|
||||
}
|
||||
|
||||
fun startChooseMusicLocations() {
|
||||
_chooseMusicLocations.put(Unit)
|
||||
chooseMusicLocations.put(Unit)
|
||||
}
|
||||
|
||||
fun showSettings() {
|
||||
_showOuter.put(Outer.Settings)
|
||||
showOuter.put(Outer.Settings)
|
||||
}
|
||||
|
||||
fun showAbout() {
|
||||
_showOuter.put(Outer.About)
|
||||
showOuter.put(Outer.About)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
package org.oxycblt.auxio.home
|
||||
|
||||
import android.animation.ArgbEvaluator
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.content.res.ColorStateList
|
||||
import android.graphics.Canvas
|
||||
@@ -33,6 +34,7 @@ import android.util.AttributeSet
|
||||
import android.widget.TextView
|
||||
import androidx.annotation.AttrRes
|
||||
import androidx.annotation.FloatRange
|
||||
import androidx.core.graphics.withRotation
|
||||
import androidx.core.os.BundleCompat
|
||||
import androidx.core.view.setMargins
|
||||
import androidx.core.view.updateLayoutParams
|
||||
@@ -66,6 +68,7 @@ import org.oxycblt.auxio.util.getDimenPixels
|
||||
*
|
||||
* @author Hai Zhang, Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
@SuppressLint("PrivateResource")
|
||||
class ThemedSpeedDialView : SpeedDialView {
|
||||
private var mainFabAnimation: MainFabAnimation? = null
|
||||
private val spacingSmall = context.getDimenPixels(R.dimen.spacing_small)
|
||||
@@ -106,19 +109,12 @@ class ThemedSpeedDialView : SpeedDialView {
|
||||
}
|
||||
val context = context
|
||||
mainFabClosedBackgroundColor =
|
||||
context
|
||||
.getAttrColorCompat(com.google.android.material.R.attr.colorPrimaryContainer)
|
||||
.defaultColor
|
||||
context.getAttrColorCompat(MR.attr.colorPrimaryContainer).defaultColor
|
||||
mainFabClosedIconColor =
|
||||
context
|
||||
.getAttrColorCompat(com.google.android.material.R.attr.colorOnPrimaryContainer)
|
||||
.defaultColor
|
||||
context.getAttrColorCompat(MR.attr.colorOnPrimaryContainer).defaultColor
|
||||
mainFabOpenedBackgroundColor =
|
||||
context.getAttrColorCompat(androidx.appcompat.R.attr.colorPrimary).defaultColor
|
||||
mainFabOpenedIconColor =
|
||||
context
|
||||
.getAttrColorCompat(com.google.android.material.R.attr.colorOnPrimary)
|
||||
.defaultColor
|
||||
mainFabOpenedIconColor = context.getAttrColorCompat(MR.attr.colorOnPrimary).defaultColor
|
||||
|
||||
// Always use our own animation to fix the library issue that ripple is rotated as well.
|
||||
mainFabAnimationRotateAngle = 0f
|
||||
@@ -226,8 +222,7 @@ class ThemedSpeedDialView : SpeedDialView {
|
||||
|
||||
val overlayLayout = overlayLayout
|
||||
if (overlayLayout != null) {
|
||||
val surfaceColor =
|
||||
context.getAttrColorCompat(com.google.android.material.R.attr.colorSurface)
|
||||
val surfaceColor = context.getAttrColorCompat(MR.attr.colorSurface)
|
||||
val overlayColor = surfaceColor.defaultColor.withModulatedAlpha(0.87f)
|
||||
overlayLayout.setBackgroundColor(overlayColor)
|
||||
}
|
||||
@@ -249,13 +244,10 @@ class ThemedSpeedDialView : SpeedDialView {
|
||||
): FabWithLabelView? {
|
||||
val context = context
|
||||
val fabImageTintColor = context.getAttrColorCompat(androidx.appcompat.R.attr.colorPrimary)
|
||||
val fabBackgroundColor =
|
||||
context.getAttrColorCompat(com.google.android.material.R.attr.colorSurface)
|
||||
val fabBackgroundColor = context.getAttrColorCompat(MR.attr.colorSurface)
|
||||
val labelColor = context.getAttrColorCompat(android.R.attr.textColorSecondary)
|
||||
val labelBackgroundColor =
|
||||
context.getAttrColorCompat(com.google.android.material.R.attr.colorSurface)
|
||||
val labelElevation =
|
||||
context.getDimen(com.google.android.material.R.dimen.m3_card_elevated_elevation)
|
||||
val labelBackgroundColor = context.getAttrColorCompat(MR.attr.colorSurface)
|
||||
val labelElevation = context.getDimen(MR.dimen.m3_card_elevated_elevation)
|
||||
val cornerRadius = context.getDimenPixels(R.dimen.spacing_medium)
|
||||
val actionItem =
|
||||
SpeedDialActionItem.Builder(
|
||||
@@ -304,9 +296,7 @@ class ThemedSpeedDialView : SpeedDialView {
|
||||
(getChildAt(0) as TextView).apply {
|
||||
TextViewCompat.setTextAppearance(
|
||||
this,
|
||||
context.getAttrResourceId(
|
||||
com.google.android.material.R.attr.textAppearanceLabelLargeEmphasized
|
||||
),
|
||||
context.getAttrResourceId(MR.attr.textAppearanceLabelLargeEmphasized),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -397,10 +387,9 @@ private class RotatingDrawable(drawable: Drawable) : Drawable(), Drawable.Callba
|
||||
return
|
||||
}
|
||||
|
||||
val saveCount = canvas.save()
|
||||
canvas.rotate(rotationDegrees, bounds.exactCenterX(), bounds.exactCenterY())
|
||||
wrappedDrawable.draw(canvas)
|
||||
canvas.restoreToCount(saveCount)
|
||||
canvas.withRotation(rotationDegrees, bounds.exactCenterX(), bounds.exactCenterY()) {
|
||||
wrappedDrawable.draw(canvas)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onBoundsChange(bounds: Rect) {
|
||||
|
||||
@@ -31,7 +31,7 @@ class NullCovers(private val storage: CoverStorage) : MutableCovers<NullCover> {
|
||||
override suspend fun create(file: File, metadata: Metadata) = CoverResult.Hit(NullCover)
|
||||
|
||||
override suspend fun cleanup(excluding: Collection<Cover>) {
|
||||
storage.ls(setOf()).map { storage.rm(it) }
|
||||
storage.ls(setOf()).forEach { storage.rm(it) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -48,10 +48,9 @@ class ListViewModel
|
||||
@Inject
|
||||
constructor(private val listSettings: ListSettings, private val musicRepository: MusicRepository) :
|
||||
ViewModel(), MusicRepository.UpdateListener {
|
||||
private val _selected = MutableStateFlow(listOf<Music>())
|
||||
/** The currently selected items. These are ordered in earliest selected and latest selected. */
|
||||
val selected: StateFlow<List<Music>>
|
||||
get() = _selected
|
||||
field = MutableStateFlow(listOf<Music>())
|
||||
|
||||
private val _menu = MutableEvent<Menu>()
|
||||
/**
|
||||
@@ -67,8 +66,8 @@ constructor(private val listSettings: ListSettings, private val musicRepository:
|
||||
val library = musicRepository.library ?: return
|
||||
// Sanitize the selection to remove items that no longer exist and thus
|
||||
// won't appear in any list.
|
||||
_selected.value =
|
||||
_selected.value.mapNotNull {
|
||||
selected.value =
|
||||
selected.value.mapNotNull {
|
||||
when (it) {
|
||||
is Song -> library.findSong(it.uid)
|
||||
is Album -> library.findAlbum(it.uid)
|
||||
@@ -80,7 +79,6 @@ constructor(private val listSettings: ListSettings, private val musicRepository:
|
||||
}
|
||||
|
||||
override fun onCleared() {
|
||||
super.onCleared()
|
||||
musicRepository.removeUpdateListener(this)
|
||||
}
|
||||
|
||||
@@ -96,7 +94,7 @@ constructor(private val listSettings: ListSettings, private val musicRepository:
|
||||
return
|
||||
}
|
||||
|
||||
val selected = _selected.value.toMutableList()
|
||||
val selected = selected.value.toMutableList()
|
||||
if (!selected.remove(music)) {
|
||||
L.d("Adding $music to selection")
|
||||
selected.add(music)
|
||||
@@ -104,7 +102,7 @@ constructor(private val listSettings: ListSettings, private val musicRepository:
|
||||
L.d("Removed $music from selection")
|
||||
}
|
||||
|
||||
_selected.value = selected
|
||||
this.selected.value = selected
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -113,7 +111,7 @@ constructor(private val listSettings: ListSettings, private val musicRepository:
|
||||
* @return A list of [Song]s collated from each item selected.
|
||||
*/
|
||||
fun peekSelection() =
|
||||
_selected.value.flatMap {
|
||||
selected.value.flatMap {
|
||||
when (it) {
|
||||
is Song -> listOf(it)
|
||||
is Album -> listSettings.albumSongSort.songs(it.songs)
|
||||
@@ -130,7 +128,7 @@ constructor(private val listSettings: ListSettings, private val musicRepository:
|
||||
*/
|
||||
fun takeSelection(): List<Song> {
|
||||
L.d("Taking selection")
|
||||
return peekSelection().also { _selected.value = listOf() }
|
||||
return peekSelection().also { selected.value = listOf() }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -139,8 +137,8 @@ constructor(private val listSettings: ListSettings, private val musicRepository:
|
||||
* @return true if the prior selection was non-empty, false otherwise.
|
||||
*/
|
||||
fun dropSelection(): Boolean {
|
||||
L.d("Dropping selection [empty=${_selected.value.isEmpty()}]")
|
||||
return _selected.value.isNotEmpty().also { _selected.value = listOf() }
|
||||
L.d("Dropping selection [empty=${selected.value.isEmpty()}]")
|
||||
return selected.value.isNotEmpty().also { selected.value = listOf() }
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -100,6 +100,7 @@ abstract class MenuDialogFragment<M : Menu> :
|
||||
binding.menuOptionRecycler.adapter = null
|
||||
}
|
||||
|
||||
@SuppressLint("RestrictedApi")
|
||||
private fun updateMenu(menu: Menu?) {
|
||||
if (menu == null) {
|
||||
L.d("No menu to show, navigating away")
|
||||
|
||||
@@ -21,7 +21,6 @@ package org.oxycblt.auxio.list.recycler
|
||||
import android.content.Context
|
||||
import android.util.AttributeSet
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import androidx.annotation.AttrRes
|
||||
import androidx.core.view.isInvisible
|
||||
import androidx.core.view.updatePadding
|
||||
@@ -29,7 +28,6 @@ import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import com.google.android.material.divider.MaterialDivider
|
||||
import org.oxycblt.auxio.R
|
||||
import org.oxycblt.auxio.list.recycler.DialogRecyclerView.ViewHolder
|
||||
import org.oxycblt.auxio.util.getDimenPixels
|
||||
|
||||
/**
|
||||
@@ -82,13 +80,13 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
|
||||
|
||||
private fun measureDivider(divider: MaterialDivider) {
|
||||
val widthMeasureSpec =
|
||||
ViewGroup.getChildMeasureSpec(
|
||||
getChildMeasureSpec(
|
||||
MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
|
||||
0,
|
||||
divider.layoutParams.width,
|
||||
)
|
||||
val heightMeasureSpec =
|
||||
ViewGroup.getChildMeasureSpec(
|
||||
getChildMeasureSpec(
|
||||
MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY),
|
||||
0,
|
||||
divider.layoutParams.height,
|
||||
|
||||
@@ -30,6 +30,7 @@ import android.graphics.PixelFormat
|
||||
import android.graphics.Rect
|
||||
import android.graphics.RectF
|
||||
import android.graphics.drawable.Drawable
|
||||
import android.graphics.text.LineBreaker
|
||||
import android.os.Build
|
||||
import android.text.Layout
|
||||
import android.util.AttributeSet
|
||||
@@ -37,22 +38,18 @@ import android.util.TypedValue
|
||||
import android.view.Gravity
|
||||
import android.view.HapticFeedbackConstants
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import android.view.ViewConfiguration
|
||||
import android.view.ViewGroup
|
||||
import android.view.WindowInsets
|
||||
import android.widget.FrameLayout
|
||||
import androidx.annotation.AttrRes
|
||||
import androidx.core.graphics.withScale
|
||||
import androidx.core.view.isEmpty
|
||||
import androidx.core.view.isInvisible
|
||||
import androidx.core.view.updatePaddingRelative
|
||||
import androidx.core.widget.TextViewCompat
|
||||
import androidx.dynamicanimation.animation.FloatValueHolder
|
||||
import androidx.dynamicanimation.animation.SpringAnimation
|
||||
import androidx.dynamicanimation.animation.SpringForce
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import com.google.android.material.R as MR
|
||||
import com.google.android.material.motion.MotionUtils
|
||||
import com.google.android.material.textview.MaterialTextView
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.hypot
|
||||
@@ -101,6 +98,7 @@ import org.oxycblt.auxio.util.systemBarInsetsCompat
|
||||
*
|
||||
* @author Hai Zhang, Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
@SuppressLint("PrivateResource")
|
||||
class FastScrollRecyclerView
|
||||
@JvmOverloads
|
||||
constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr: Int = 0) :
|
||||
@@ -182,8 +180,8 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
|
||||
addView(
|
||||
popupTextView,
|
||||
FrameLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||
LayoutParams.MATCH_PARENT,
|
||||
LayoutParams.MATCH_PARENT,
|
||||
Gravity.CENTER,
|
||||
),
|
||||
)
|
||||
@@ -195,30 +193,8 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
|
||||
scale = 0.5f
|
||||
alpha = 0.0f
|
||||
}
|
||||
private val popupTextStaggerDelayMillis =
|
||||
MotionUtils.resolveThemeDuration(context, MR.attr.motionDurationShort2, 100).toLong()
|
||||
private val popupSpatialSpring =
|
||||
MotionUtils.resolveThemeSpringForce(
|
||||
context,
|
||||
MR.attr.motionSpringFastSpatial,
|
||||
MR.style.Motion_Material3_Spring_Standard_Fast_Spatial,
|
||||
)
|
||||
private val popupEffectsSpring =
|
||||
MotionUtils.resolveThemeSpringForce(
|
||||
context,
|
||||
MR.attr.motionSpringDefaultEffects,
|
||||
MR.style.Motion_Material3_Spring_Standard_Default_Effects,
|
||||
)
|
||||
private var popupShapeScaleAnimation: SpringAnimation? = null
|
||||
private var popupShapeAlphaAnimation: SpringAnimation? = null
|
||||
private var popupTextScaleAnimation: SpringAnimation? = null
|
||||
private var popupTextAlphaAnimation: SpringAnimation? = null
|
||||
private val popupTextRevealRunnable = Runnable {
|
||||
if (showingPopup) {
|
||||
popupShapeScaleAnimation?.cancel()
|
||||
popupShapeScaleAnimation = popupScaleSpring.scale(popupView, 0f)
|
||||
}
|
||||
}
|
||||
private var showingPopup = false
|
||||
|
||||
// Touch
|
||||
@@ -398,26 +374,26 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
|
||||
MeasureSpec.makeMeasureSpec(popupSize, MeasureSpec.EXACTLY),
|
||||
)
|
||||
|
||||
val popupWidth = popupSize
|
||||
val popupHeight = popupSize
|
||||
// val popupWidth = popupSize
|
||||
// val popupHeight = popupSize
|
||||
val popupLeft =
|
||||
if (layoutDirection == View.LAYOUT_DIRECTION_RTL) {
|
||||
if (layoutDirection == LAYOUT_DIRECTION_RTL) {
|
||||
thumbPadding.left + thumbWidth + popupLayoutParams.leftMargin
|
||||
} else {
|
||||
width - thumbPadding.right - thumbWidth - popupLayoutParams.rightMargin - popupWidth
|
||||
width - thumbPadding.right - thumbWidth - popupLayoutParams.rightMargin - popupSize
|
||||
}
|
||||
|
||||
val popupAnchorY = popupHeight / 2
|
||||
val popupAnchorY = popupSize / 2
|
||||
val thumbAnchorY = thumbView.height / 2
|
||||
|
||||
val popupTop =
|
||||
(thumbTop + thumbAnchorY - popupAnchorY)
|
||||
.coerceAtLeast(thumbPadding.top + popupLayoutParams.topMargin)
|
||||
.coerceAtMost(
|
||||
height - thumbPadding.bottom - popupLayoutParams.bottomMargin - popupHeight
|
||||
height - thumbPadding.bottom - popupLayoutParams.bottomMargin - popupSize
|
||||
)
|
||||
|
||||
popupView.layout(popupLeft, popupTop, popupLeft + popupWidth, popupTop + popupHeight)
|
||||
popupView.layout(popupLeft, popupTop, popupLeft + popupSize, popupTop + popupSize)
|
||||
}
|
||||
|
||||
override fun onScrolled(dx: Int, dy: Int) {
|
||||
@@ -600,13 +576,11 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
|
||||
)
|
||||
ellipsize = null
|
||||
gravity = Gravity.CENTER
|
||||
textAlignment = View.TEXT_ALIGNMENT_CENTER
|
||||
textAlignment = TEXT_ALIGNMENT_CENTER
|
||||
includeFontPadding = false
|
||||
setHorizontallyScrolling(false)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
breakStrategy = Layout.BREAK_STRATEGY_SIMPLE
|
||||
hyphenationFrequency = Layout.HYPHENATION_FREQUENCY_NONE
|
||||
}
|
||||
breakStrategy = LineBreaker.BREAK_STRATEGY_SIMPLE
|
||||
hyphenationFrequency = Layout.HYPHENATION_FREQUENCY_NONE
|
||||
}
|
||||
|
||||
private fun resetPopupTextAutoScaleConfig() {
|
||||
@@ -686,33 +660,6 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
|
||||
)
|
||||
}
|
||||
|
||||
private fun springTo(
|
||||
startValue: Float,
|
||||
finalValue: Float,
|
||||
springTemplate: SpringForce,
|
||||
minimumVisibleChange: Float,
|
||||
dampingOverride: Float? = null,
|
||||
update: (Float) -> Unit,
|
||||
): SpringAnimation {
|
||||
val animation =
|
||||
SpringAnimation(FloatValueHolder(startValue)).apply {
|
||||
spring =
|
||||
SpringForce().apply {
|
||||
dampingRatio = dampingOverride ?: springTemplate.dampingRatio
|
||||
stiffness = springTemplate.stiffness
|
||||
finalPosition = finalValue
|
||||
}
|
||||
setStartValue(startValue)
|
||||
setMinimumVisibleChange(minimumVisibleChange)
|
||||
addUpdateListener { _, value, _ -> update(value) }
|
||||
addEndListener { _, canceled, value, _ ->
|
||||
update(if (canceled) value else finalValue)
|
||||
}
|
||||
}
|
||||
animation.animateToFinalPosition(finalValue)
|
||||
return animation
|
||||
}
|
||||
|
||||
private fun doPopupVibration() {
|
||||
performHapticFeedback(
|
||||
if (Build.VERSION.SDK_INT >= 27) {
|
||||
@@ -756,8 +703,6 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
|
||||
|
||||
private companion object {
|
||||
const val AUTO_HIDE_SCROLLBAR_DELAY_MILLIS = 500
|
||||
const val POPUP_SHAPE_HIDDEN_SCALE = 0.62f
|
||||
const val POPUP_TEXT_HIDDEN_SCALE = 0.78f
|
||||
const val POPUP_TEXT_SINGLE_LINE_COUNT = 1
|
||||
}
|
||||
|
||||
@@ -771,10 +716,7 @@ private class SoftBurstPopupDrawable(context: Context) : Drawable() {
|
||||
private val pathBounds = RectF()
|
||||
private val paint =
|
||||
Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
color =
|
||||
context
|
||||
.getAttrColorCompat(com.google.android.material.R.attr.colorSecondary)
|
||||
.defaultColor
|
||||
color = context.getAttrColorCompat(MR.attr.colorSecondary).defaultColor
|
||||
style = Paint.Style.FILL
|
||||
}
|
||||
|
||||
@@ -850,15 +792,14 @@ private class SoftBurstPopupDrawable(context: Context) : Drawable() {
|
||||
return
|
||||
}
|
||||
|
||||
val checkpoint = canvas.save()
|
||||
canvas.scale(revealScale, revealScale, pathBounds.centerX(), pathBounds.centerY())
|
||||
canvas.rotate(
|
||||
baseRotationDegrees + scrollRotationDegrees,
|
||||
pathBounds.centerX(),
|
||||
pathBounds.centerY(),
|
||||
)
|
||||
canvas.drawPath(fittedPath, paint)
|
||||
canvas.restoreToCount(checkpoint)
|
||||
canvas.withScale(revealScale, revealScale, pathBounds.centerX(), pathBounds.centerY()) {
|
||||
canvas.rotate(
|
||||
baseRotationDegrees + scrollRotationDegrees,
|
||||
pathBounds.centerX(),
|
||||
pathBounds.centerY(),
|
||||
)
|
||||
canvas.drawPath(fittedPath, paint)
|
||||
}
|
||||
}
|
||||
|
||||
override fun setAlpha(alpha: Int) {
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
|
||||
package org.oxycblt.auxio.list.recycler
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.drawable.Drawable
|
||||
import android.view.View
|
||||
@@ -111,6 +112,7 @@ abstract class MaterialDragCallback : ItemTouchHelper.Callback() {
|
||||
return clampedAbsVelocity * sign(viewSizeOutOfBounds.toDouble()).toInt()
|
||||
}
|
||||
|
||||
@SuppressLint("PrivateResource")
|
||||
final override fun onChildDraw(
|
||||
c: Canvas,
|
||||
recyclerView: RecyclerView,
|
||||
|
||||
@@ -87,7 +87,6 @@ abstract class SortDialog :
|
||||
|
||||
private fun getCurrentSort(): Sort? {
|
||||
val binding = requireBinding()
|
||||
val initial = getInitialSort()
|
||||
val mode = modeAdapter.currentMode ?: return null
|
||||
val direction =
|
||||
if (binding.sortDirectionAsc.isChecked) Sort.Direction.ASCENDING
|
||||
|
||||
@@ -255,7 +255,7 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont
|
||||
.mapNotNull { Location.Unopened.from(context, it.toUri())?.open(context) }
|
||||
|
||||
private fun String.toUnopenedLocations(): List<Location.Unopened> =
|
||||
splitEscaped { it == ';' }.mapNotNull { Location.Unopened.from(context, it.toUri()) }
|
||||
splitEscaped { it == ';' }.map { Location.Unopened.from(context, it.toUri()) }
|
||||
|
||||
private inline fun String.splitEscaped(selector: (Char) -> Boolean): List<String> {
|
||||
val split = mutableListOf<String>()
|
||||
|
||||
@@ -62,24 +62,19 @@ constructor(
|
||||
/** The current music loading state, or null if no loading is going on. */
|
||||
val indexingState: StateFlow<IndexingState?> = _indexingState
|
||||
|
||||
private val _statistics = MutableStateFlow<Statistics?>(null)
|
||||
|
||||
/** [Statistics] about the last completed music load. */
|
||||
val statistics: StateFlow<Statistics?>
|
||||
get() = _statistics
|
||||
|
||||
private val _playlistDecision = MutableEvent<PlaylistDecision>()
|
||||
field = MutableStateFlow<Statistics?>(null)
|
||||
|
||||
/**
|
||||
* A [PlaylistDecision] command that is awaiting a view capable of responding to it. Null if
|
||||
* none currently.
|
||||
*/
|
||||
val playlistDecision: Event<PlaylistDecision>
|
||||
get() = _playlistDecision
|
||||
field = MutableEvent<PlaylistDecision>()
|
||||
|
||||
private val _playlistMessage = MutableEvent<PlaylistMessage>()
|
||||
val playlistMessage: Event<PlaylistMessage>
|
||||
get() = _playlistMessage
|
||||
field = MutableEvent<PlaylistMessage>()
|
||||
|
||||
init {
|
||||
musicRepository.addUpdateListener(this)
|
||||
@@ -94,7 +89,7 @@ constructor(
|
||||
override fun onMusicChanges(changes: MusicRepository.Changes) {
|
||||
if (!changes.deviceLibrary) return
|
||||
val library = musicRepository.library ?: return
|
||||
_statistics.value =
|
||||
statistics.value =
|
||||
Statistics(
|
||||
library.songs.size,
|
||||
library.albums.size,
|
||||
@@ -103,7 +98,7 @@ constructor(
|
||||
library.songs.sumOf { it.durationMs },
|
||||
library.songs.sumOf { it.size },
|
||||
)
|
||||
L.d("Updated statistics: ${_statistics.value}")
|
||||
L.d("Updated statistics: ${statistics.value}")
|
||||
}
|
||||
|
||||
override fun onIndexingStateChanged() {
|
||||
@@ -145,11 +140,11 @@ constructor(
|
||||
PlaylistDecision.New.Reason.ADD -> PlaylistMessage.AddSuccess
|
||||
PlaylistDecision.New.Reason.IMPORT -> PlaylistMessage.ImportSuccess
|
||||
}
|
||||
_playlistMessage.put(message)
|
||||
playlistMessage.put(message)
|
||||
}
|
||||
} else {
|
||||
L.d("Launching creation dialog for ${songs.size} songs")
|
||||
_playlistDecision.put(PlaylistDecision.New(songs, null, reason))
|
||||
playlistDecision.put(PlaylistDecision.New(songs, null, reason))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -168,7 +163,7 @@ constructor(
|
||||
val importedPlaylist = externalPlaylistManager.import(uri)
|
||||
if (importedPlaylist == null) {
|
||||
L.e("Could not import playlist")
|
||||
_playlistMessage.put(PlaylistMessage.ImportFailed)
|
||||
playlistMessage.put(PlaylistMessage.ImportFailed)
|
||||
return@launch
|
||||
}
|
||||
|
||||
@@ -180,13 +175,13 @@ constructor(
|
||||
|
||||
if (songs.isEmpty()) {
|
||||
L.e("No songs found")
|
||||
_playlistMessage.put(PlaylistMessage.ImportFailed)
|
||||
playlistMessage.put(PlaylistMessage.ImportFailed)
|
||||
return@launch
|
||||
}
|
||||
|
||||
if (target !== null) {
|
||||
if (importedPlaylist.name != null && importedPlaylist.name != target.name.raw) {
|
||||
_playlistDecision.put(
|
||||
playlistDecision.put(
|
||||
PlaylistDecision.Rename(
|
||||
target,
|
||||
importedPlaylist.name,
|
||||
@@ -196,10 +191,10 @@ constructor(
|
||||
)
|
||||
} else {
|
||||
musicRepository.rewritePlaylist(target, songs)
|
||||
_playlistMessage.put(PlaylistMessage.ImportSuccess)
|
||||
playlistMessage.put(PlaylistMessage.ImportSuccess)
|
||||
}
|
||||
} else {
|
||||
_playlistDecision.put(
|
||||
playlistDecision.put(
|
||||
PlaylistDecision.New(
|
||||
songs,
|
||||
importedPlaylist.name,
|
||||
@@ -210,7 +205,7 @@ constructor(
|
||||
}
|
||||
} else {
|
||||
L.d("Launching import picker")
|
||||
_playlistDecision.put(PlaylistDecision.Import(target))
|
||||
playlistDecision.put(PlaylistDecision.Import(target))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -225,14 +220,14 @@ constructor(
|
||||
L.d("Exporting playlist to $uri")
|
||||
viewModelScope.launch(Dispatchers.IO) {
|
||||
if (externalPlaylistManager.export(playlist, uri, config)) {
|
||||
_playlistMessage.put(PlaylistMessage.ExportSuccess)
|
||||
playlistMessage.put(PlaylistMessage.ExportSuccess)
|
||||
} else {
|
||||
_playlistMessage.put(PlaylistMessage.ExportFailed)
|
||||
playlistMessage.put(PlaylistMessage.ExportFailed)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
L.d("Launching export dialog")
|
||||
_playlistDecision.put(PlaylistDecision.Export(playlist))
|
||||
playlistDecision.put(PlaylistDecision.Export(playlist))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -264,11 +259,11 @@ constructor(
|
||||
PlaylistDecision.Rename.Reason.ACTION -> PlaylistMessage.RenameSuccess
|
||||
PlaylistDecision.Rename.Reason.IMPORT -> PlaylistMessage.ImportSuccess
|
||||
}
|
||||
_playlistMessage.put(message)
|
||||
playlistMessage.put(message)
|
||||
}
|
||||
} else {
|
||||
L.d("Launching rename dialog for $playlist")
|
||||
_playlistDecision.put(PlaylistDecision.Rename(playlist, null, applySongs, reason))
|
||||
playlistDecision.put(PlaylistDecision.Rename(playlist, null, applySongs, reason))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -285,11 +280,11 @@ constructor(
|
||||
L.d("Deleting $playlist")
|
||||
viewModelScope.launch(Dispatchers.IO) {
|
||||
musicRepository.deletePlaylist(playlist)
|
||||
_playlistMessage.put(PlaylistMessage.DeleteSuccess)
|
||||
playlistMessage.put(PlaylistMessage.DeleteSuccess)
|
||||
}
|
||||
} else {
|
||||
L.d("Launching deletion dialog for $playlist")
|
||||
_playlistDecision.put(PlaylistDecision.Delete(playlist))
|
||||
playlistDecision.put(PlaylistDecision.Delete(playlist))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -348,11 +343,11 @@ constructor(
|
||||
L.d("Adding ${songs.size} songs to $playlist")
|
||||
viewModelScope.launch(Dispatchers.IO) {
|
||||
musicRepository.addToPlaylist(songs, playlist)
|
||||
_playlistMessage.put(PlaylistMessage.AddSuccess)
|
||||
playlistMessage.put(PlaylistMessage.AddSuccess)
|
||||
}
|
||||
} else {
|
||||
L.d("Launching addition dialog for songs=${songs.size}")
|
||||
_playlistDecision.put(PlaylistDecision.Add(songs))
|
||||
playlistDecision.put(PlaylistDecision.Add(songs))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -43,45 +43,37 @@ import timber.log.Timber as L
|
||||
@HiltViewModel
|
||||
class PlaylistPickerViewModel @Inject constructor(private val musicRepository: MusicRepository) :
|
||||
ViewModel(), MusicRepository.UpdateListener {
|
||||
private val _currentPendingNewPlaylist = MutableStateFlow<PendingNewPlaylist?>(null)
|
||||
/** A new [Playlist] having it's name chosen by the user. Null if none yet. */
|
||||
val currentPendingNewPlaylist: StateFlow<PendingNewPlaylist?>
|
||||
get() = _currentPendingNewPlaylist
|
||||
field = MutableStateFlow<PendingNewPlaylist?>(null)
|
||||
|
||||
private val _currentPendingRenamePlaylist = MutableStateFlow<PendingRenamePlaylist?>(null)
|
||||
/** An existing [Playlist] that is being renamed. Null if none yet. */
|
||||
val currentPendingRenamePlaylist: StateFlow<PendingRenamePlaylist?>
|
||||
get() = _currentPendingRenamePlaylist
|
||||
field = MutableStateFlow<PendingRenamePlaylist?>(null)
|
||||
|
||||
private val _currentPlaylistToExport = MutableStateFlow<Playlist?>(null)
|
||||
/** An existing [Playlist] that is being exported. Null if none yet. */
|
||||
val currentPlaylistToExport: StateFlow<Playlist?>
|
||||
get() = _currentPlaylistToExport
|
||||
field = MutableStateFlow<Playlist?>(null)
|
||||
|
||||
private val _currentExportConfig = MutableStateFlow(DEFAULT_EXPORT_CONFIG)
|
||||
/** The current [ExportConfig] to use when exporting a playlist. */
|
||||
val currentExportConfig: StateFlow<ExportConfig>
|
||||
get() = _currentExportConfig
|
||||
field = MutableStateFlow(DEFAULT_EXPORT_CONFIG)
|
||||
|
||||
private val _currentPlaylistToDelete = MutableStateFlow<Playlist?>(null)
|
||||
/** The current [Playlist] that needs it's deletion confirmed. Null if none yet. */
|
||||
val currentPlaylistToDelete: StateFlow<Playlist?>
|
||||
get() = _currentPlaylistToDelete
|
||||
field = MutableStateFlow<Playlist?>(null)
|
||||
|
||||
private val _chosenName = MutableStateFlow<ChosenName>(ChosenName.Empty)
|
||||
/** The users chosen name for [currentPendingNewPlaylist] or [currentPendingRenamePlaylist]. */
|
||||
val chosenName: StateFlow<ChosenName>
|
||||
get() = _chosenName
|
||||
field = MutableStateFlow<ChosenName>(ChosenName.Empty)
|
||||
|
||||
private val _currentSongsToAdd = MutableStateFlow<List<Song>?>(null)
|
||||
/** A batch of [Song]s to add to a playlist chosen by the user. Null if none yet. */
|
||||
val currentSongsToAdd: StateFlow<List<Song>?>
|
||||
get() = _currentSongsToAdd
|
||||
field = MutableStateFlow<List<Song>?>(null)
|
||||
|
||||
private val _playlistAddChoices = MutableStateFlow<List<PlaylistChoice>>(listOf())
|
||||
/** The [Playlist]s that [currentSongsToAdd] could be added to. */
|
||||
val playlistAddChoices: StateFlow<List<PlaylistChoice>>
|
||||
get() = _playlistAddChoices
|
||||
field = MutableStateFlow<List<PlaylistChoice>>(listOf())
|
||||
|
||||
init {
|
||||
musicRepository.addUpdateListener(this)
|
||||
@@ -91,8 +83,8 @@ class PlaylistPickerViewModel @Inject constructor(private val musicRepository: M
|
||||
var refreshChoicesWith: List<Song>? = null
|
||||
val library = musicRepository.library
|
||||
if (changes.deviceLibrary && library != null) {
|
||||
_currentPendingNewPlaylist.value =
|
||||
_currentPendingNewPlaylist.value?.let { pendingPlaylist ->
|
||||
currentPendingNewPlaylist.value =
|
||||
currentPendingNewPlaylist.value?.let { pendingPlaylist ->
|
||||
PendingNewPlaylist(
|
||||
pendingPlaylist.preferredName,
|
||||
pendingPlaylist.songs.mapNotNull { library.findSong(it.uid) },
|
||||
@@ -100,19 +92,19 @@ class PlaylistPickerViewModel @Inject constructor(private val musicRepository: M
|
||||
pendingPlaylist.reason,
|
||||
)
|
||||
}
|
||||
L.d("Updated pending playlist: ${_currentPendingNewPlaylist.value?.preferredName}")
|
||||
L.d("Updated pending playlist: ${currentPendingNewPlaylist.value?.preferredName}")
|
||||
|
||||
_currentSongsToAdd.value =
|
||||
_currentSongsToAdd.value?.let { pendingSongs ->
|
||||
currentSongsToAdd.value =
|
||||
currentSongsToAdd.value?.let { pendingSongs ->
|
||||
pendingSongs
|
||||
.mapNotNull { library.findSong(it.uid) }
|
||||
.ifEmpty { null }
|
||||
.also { refreshChoicesWith = it }
|
||||
}
|
||||
L.d("Updated songs to add: ${_currentSongsToAdd.value?.size} songs")
|
||||
L.d("Updated songs to add: ${currentSongsToAdd.value?.size} songs")
|
||||
}
|
||||
|
||||
val chosenName = _chosenName.value
|
||||
val chosenName = chosenName.value
|
||||
if (changes.userLibrary) {
|
||||
when (chosenName) {
|
||||
is ChosenName.Valid -> updateChosenName(chosenName.value)
|
||||
@@ -122,15 +114,15 @@ class PlaylistPickerViewModel @Inject constructor(private val musicRepository: M
|
||||
}
|
||||
}
|
||||
L.d("Updated chosen name to $chosenName")
|
||||
refreshChoicesWith = refreshChoicesWith ?: _currentSongsToAdd.value
|
||||
refreshChoicesWith = refreshChoicesWith ?: currentSongsToAdd.value
|
||||
|
||||
// TODO: Add music syncing for other playlist states here
|
||||
|
||||
_currentPlaylistToExport.value =
|
||||
_currentPlaylistToExport.value?.let { playlist ->
|
||||
currentPlaylistToExport.value =
|
||||
currentPlaylistToExport.value?.let { playlist ->
|
||||
musicRepository.library?.findPlaylist(playlist.uid)
|
||||
}
|
||||
L.d("Updated playlist to export to ${_currentPlaylistToExport.value}")
|
||||
L.d("Updated playlist to export to ${currentPlaylistToExport.value}")
|
||||
}
|
||||
|
||||
refreshChoicesWith?.let(::refreshPlaylistChoices)
|
||||
@@ -174,7 +166,7 @@ class PlaylistPickerViewModel @Inject constructor(private val musicRepository: M
|
||||
possibleName
|
||||
}
|
||||
|
||||
_currentPendingNewPlaylist.value =
|
||||
currentPendingNewPlaylist.value =
|
||||
if (possibleName != null && songs != null) {
|
||||
PendingNewPlaylist(possibleName, songs, template, reason)
|
||||
} else {
|
||||
@@ -198,7 +190,7 @@ class PlaylistPickerViewModel @Inject constructor(private val musicRepository: M
|
||||
val playlist = musicRepository.library?.findPlaylist(playlistUid)
|
||||
val applySongs = musicRepository.library?.let { applySongUids.mapNotNull(it::findSong) }
|
||||
|
||||
_currentPendingRenamePlaylist.value =
|
||||
currentPendingRenamePlaylist.value =
|
||||
if (playlist != null && applySongs != null) {
|
||||
PendingRenamePlaylist(playlist, applySongs, template, reason)
|
||||
} else {
|
||||
@@ -215,12 +207,12 @@ class PlaylistPickerViewModel @Inject constructor(private val musicRepository: M
|
||||
fun setPlaylistToExport(playlistUid: Music.UID) {
|
||||
L.d("Opening playlist $playlistUid to export")
|
||||
// TODO: Add this guard to the rest of the methods here
|
||||
if (_currentPlaylistToExport.value?.uid == playlistUid) return
|
||||
_currentPlaylistToExport.value = musicRepository.library?.findPlaylist(playlistUid)
|
||||
if (_currentPlaylistToExport.value == null) {
|
||||
if (currentPlaylistToExport.value?.uid == playlistUid) return
|
||||
currentPlaylistToExport.value = musicRepository.library?.findPlaylist(playlistUid)
|
||||
if (currentPlaylistToExport.value == null) {
|
||||
L.w("Given playlist UID to export was invalid")
|
||||
} else {
|
||||
_currentExportConfig.value = DEFAULT_EXPORT_CONFIG
|
||||
currentExportConfig.value = DEFAULT_EXPORT_CONFIG
|
||||
}
|
||||
}
|
||||
|
||||
@@ -231,7 +223,7 @@ class PlaylistPickerViewModel @Inject constructor(private val musicRepository: M
|
||||
*/
|
||||
fun setExportConfig(exportConfig: ExportConfig) {
|
||||
L.d("Setting export config to $exportConfig")
|
||||
_currentExportConfig.value = exportConfig
|
||||
currentExportConfig.value = exportConfig
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -241,8 +233,8 @@ class PlaylistPickerViewModel @Inject constructor(private val musicRepository: M
|
||||
*/
|
||||
fun setPlaylistToDelete(playlistUid: Music.UID) {
|
||||
L.d("Opening playlist $playlistUid to delete")
|
||||
_currentPlaylistToDelete.value = musicRepository.library?.findPlaylist(playlistUid)
|
||||
if (_currentPlaylistToDelete.value == null) {
|
||||
currentPlaylistToDelete.value = musicRepository.library?.findPlaylist(playlistUid)
|
||||
if (currentPlaylistToDelete.value == null) {
|
||||
L.w("Given playlist UID to delete was invalid")
|
||||
}
|
||||
}
|
||||
@@ -254,7 +246,7 @@ class PlaylistPickerViewModel @Inject constructor(private val musicRepository: M
|
||||
*/
|
||||
fun updateChosenName(name: String?) {
|
||||
L.d("Updating chosen name to $name")
|
||||
_chosenName.value =
|
||||
chosenName.value =
|
||||
when {
|
||||
name.isNullOrEmpty() -> {
|
||||
L.e("Chosen name is empty")
|
||||
@@ -285,11 +277,11 @@ class PlaylistPickerViewModel @Inject constructor(private val musicRepository: M
|
||||
*/
|
||||
fun setSongsToAdd(songUids: Array<Music.UID>) {
|
||||
L.d("Opening ${songUids.size} songs to add to a playlist")
|
||||
_currentSongsToAdd.value =
|
||||
currentSongsToAdd.value =
|
||||
musicRepository.library
|
||||
?.let { songUids.mapNotNull(it::findSong).ifEmpty { null } }
|
||||
?.also(::refreshPlaylistChoices)
|
||||
if (_currentSongsToAdd.value == null || songUids.size != _currentSongsToAdd.value?.size) {
|
||||
if (currentSongsToAdd.value == null || songUids.size != currentSongsToAdd.value?.size) {
|
||||
L.w("Given song UIDs to add were (partially) invalid")
|
||||
}
|
||||
}
|
||||
@@ -297,7 +289,7 @@ class PlaylistPickerViewModel @Inject constructor(private val musicRepository: M
|
||||
private fun refreshPlaylistChoices(songs: List<Song>) {
|
||||
val library = musicRepository.library ?: return
|
||||
L.d("Refreshing playlist choices")
|
||||
_playlistAddChoices.value =
|
||||
playlistAddChoices.value =
|
||||
Sort(Sort.Mode.ByName, Sort.Direction.ASCENDING).playlists(library.playlists).map {
|
||||
val songSet = it.songs.toSet()
|
||||
PlaylistChoice(it, songs.all(songSet::contains))
|
||||
|
||||
@@ -36,7 +36,6 @@ import org.oxycblt.auxio.util.getPlural
|
||||
import org.oxycblt.musikr.Album
|
||||
import org.oxycblt.musikr.Artist
|
||||
import org.oxycblt.musikr.Genre
|
||||
import org.oxycblt.musikr.Music
|
||||
import org.oxycblt.musikr.Music.UID
|
||||
import org.oxycblt.musikr.MusicParent
|
||||
import org.oxycblt.musikr.Playlist
|
||||
@@ -47,7 +46,7 @@ sealed interface MediaSessionUID {
|
||||
override fun toString() = "$MICRO_ID_CATEGORY${node.microId}"
|
||||
}
|
||||
|
||||
data class SingleItem(val uid: Music.UID) : MediaSessionUID {
|
||||
data class SingleItem(val uid: UID) : MediaSessionUID {
|
||||
override fun toString() = "$MICRO_ID_ITEM$uid"
|
||||
}
|
||||
|
||||
@@ -76,8 +75,8 @@ sealed interface MediaSessionUID {
|
||||
}
|
||||
return when (parts[0]) {
|
||||
ID_CATEGORY -> Tab(TabNode.fromString(parts[1]) ?: return null)
|
||||
ID_ITEM -> SingleItem(Music.UID.fromString(parts[1]) ?: return null)
|
||||
else -> return null
|
||||
ID_ITEM -> SingleItem(UID.fromString(parts[1]) ?: return null)
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -183,7 +183,7 @@ private constructor(
|
||||
getChildMediaItems(mediaSessionUID.uid)
|
||||
}
|
||||
null -> {
|
||||
return null
|
||||
null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,7 +51,6 @@ class PlaybackBarFragment : ViewBindingFragment<FragmentPlaybackBarBinding>() {
|
||||
savedInstanceState: Bundle?,
|
||||
) {
|
||||
super.onBindingCreated(binding, savedInstanceState)
|
||||
val context = requireContext()
|
||||
|
||||
// --- UI SETUP ---
|
||||
binding.root.apply {
|
||||
|
||||
@@ -82,7 +82,6 @@ class PlaybackPanelFragment :
|
||||
private val queueModel: QueueViewModel by viewModels()
|
||||
private var equalizerLauncher: ActivityResultLauncher<Intent>? = null
|
||||
private var userAwarePagerCallback: UserAwarePagerCallback? = null
|
||||
private var currentPagerPosition = 0
|
||||
|
||||
override fun onCreateBinding(inflater: LayoutInflater) =
|
||||
FragmentPlaybackPanelBinding.inflate(inflater)
|
||||
@@ -396,6 +395,4 @@ class PlaybackPanelFragment :
|
||||
Direction.BACKWARDS -> playbackModel.stepBackwards()
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import javax.inject.Inject
|
||||
import kotlin.time.Duration.Companion.milliseconds
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
@@ -64,63 +65,55 @@ constructor(
|
||||
) : ViewModel(), PlaybackStateManager.Listener, PlaybackSettings.Listener {
|
||||
private var lastPositionJob: Job? = null
|
||||
|
||||
private val _song = MutableStateFlow<Song?>(null)
|
||||
/** The currently playing song. */
|
||||
val song: StateFlow<Song?>
|
||||
get() = _song
|
||||
field = MutableStateFlow<Song?>(null)
|
||||
|
||||
private val _parent = MutableStateFlow<MusicParent?>(null)
|
||||
/** The [MusicParent] currently being played. Null if playback is occurring from all songs. */
|
||||
val parent: StateFlow<MusicParent?> = _parent
|
||||
private val _isPlaying = MutableStateFlow(false)
|
||||
|
||||
/** Whether playback is ongoing or paused. */
|
||||
val isPlaying: StateFlow<Boolean>
|
||||
get() = _isPlaying
|
||||
field = MutableStateFlow(false)
|
||||
|
||||
private val _positionDs = MutableStateFlow(0L)
|
||||
/** The current position, in deci-seconds (1/10th of a second). */
|
||||
val positionDs: StateFlow<Long>
|
||||
get() = _positionDs
|
||||
field = MutableStateFlow(0L)
|
||||
|
||||
private val _repeatMode = MutableStateFlow(RepeatMode.NONE)
|
||||
/** The current [RepeatMode]. */
|
||||
val repeatMode: StateFlow<RepeatMode>
|
||||
get() = _repeatMode
|
||||
field = MutableStateFlow(RepeatMode.NONE)
|
||||
|
||||
private val _isShuffled = MutableStateFlow(false)
|
||||
/** Whether the queue is shuffled or not. */
|
||||
val isShuffled: StateFlow<Boolean>
|
||||
get() = _isShuffled
|
||||
field = MutableStateFlow(false)
|
||||
|
||||
private val _currentBarAction = MutableStateFlow(playbackSettings.barAction)
|
||||
/** The current secondary action to show alongside the play button in the playback bar. */
|
||||
val currentBarAction: StateFlow<ActionMode>
|
||||
get() = _currentBarAction
|
||||
field = MutableStateFlow(playbackSettings.barAction)
|
||||
|
||||
private val _openPanel = MutableEvent<OpenPanel>()
|
||||
/**
|
||||
* A [OpenPanel] command that is awaiting a view capable of responding to it. Null if none
|
||||
* currently.
|
||||
*/
|
||||
val openPanel: Event<OpenPanel>
|
||||
get() = _openPanel
|
||||
field = MutableEvent<OpenPanel>()
|
||||
|
||||
private val _pagerQueue = MutableStateFlow(PagerQueue(listOf(), 0))
|
||||
/** The current queue in a special bundled format suitable for the cover ViewPager2. */
|
||||
val pagerQueue: StateFlow<PagerQueue> = _pagerQueue
|
||||
|
||||
private val _pagerCommand = MutableEvent<PagerCommand>()
|
||||
/** Specialized ViewPager2-friendly queue commands */
|
||||
val pagerCommand: Event<PagerCommand>
|
||||
get() = _pagerCommand
|
||||
field = MutableEvent<PagerCommand>()
|
||||
|
||||
private val _playbackDecision = MutableEvent<PlaybackDecision>()
|
||||
/**
|
||||
* A [PlaybackDecision] command that is awaiting a view capable of responding to it. Null if
|
||||
* none currently.
|
||||
*/
|
||||
val playbackDecision: Event<PlaybackDecision>
|
||||
get() = _playbackDecision
|
||||
field = MutableEvent<PlaybackDecision>()
|
||||
|
||||
/**
|
||||
* The current audio session ID of the internal player. Null if no audio player is available.
|
||||
@@ -140,10 +133,10 @@ constructor(
|
||||
|
||||
override fun onIndexMoved(index: Int) {
|
||||
L.d("Index moved, updating current song")
|
||||
_positionDs.value = playbackManager.progression.calculateElapsedPositionMs().msToDs()
|
||||
_song.value = playbackManager.currentSong
|
||||
positionDs.value = playbackManager.progression.calculateElapsedPositionMs().msToDs()
|
||||
song.value = playbackManager.currentSong
|
||||
|
||||
_pagerCommand.put(PagerCommand(update = null, scroll = index))
|
||||
pagerCommand.put(PagerCommand(update = null, scroll = index))
|
||||
_pagerQueue.value = _pagerQueue.value.copy(index = index)
|
||||
}
|
||||
|
||||
@@ -151,10 +144,10 @@ constructor(
|
||||
// Other types of queue changes preserve the current song.
|
||||
if (change.type == QueueChange.Type.SONG) {
|
||||
L.d("Queue changed, updating current song")
|
||||
_song.value = playbackManager.currentSong
|
||||
song.value = playbackManager.currentSong
|
||||
}
|
||||
|
||||
_pagerCommand.put(
|
||||
pagerCommand.put(
|
||||
PagerCommand(
|
||||
update = change.instructions,
|
||||
scroll = index.takeIf { change.type != QueueChange.Type.MAPPING },
|
||||
@@ -165,9 +158,9 @@ constructor(
|
||||
|
||||
override fun onQueueReordered(queue: List<Song>, index: Int, isShuffled: Boolean) {
|
||||
L.d("Queue completely changed, updating current song")
|
||||
_isShuffled.value = isShuffled
|
||||
this.isShuffled.value = isShuffled
|
||||
|
||||
_pagerCommand.put(PagerCommand(update = UpdateInstructions.Replace(0), scroll = index))
|
||||
pagerCommand.put(PagerCommand(update = UpdateInstructions.Replace(0), scroll = index))
|
||||
_pagerQueue.value = PagerQueue(queue = queue, index = index)
|
||||
}
|
||||
|
||||
@@ -178,37 +171,37 @@ constructor(
|
||||
isShuffled: Boolean,
|
||||
) {
|
||||
L.d("New playback started, updating playback information")
|
||||
_song.value = playbackManager.currentSong
|
||||
song.value = playbackManager.currentSong
|
||||
_parent.value = parent
|
||||
_isShuffled.value = isShuffled
|
||||
this.isShuffled.value = isShuffled
|
||||
|
||||
_pagerCommand.put(PagerCommand(update = UpdateInstructions.Replace(0), scroll = index))
|
||||
pagerCommand.put(PagerCommand(update = UpdateInstructions.Replace(0), scroll = index))
|
||||
_pagerQueue.value = PagerQueue(queue = queue, index = index)
|
||||
}
|
||||
|
||||
override fun onProgressionChanged(progression: Progression) {
|
||||
L.d("Player state changed, starting new position polling")
|
||||
_isPlaying.value = progression.isPlaying
|
||||
isPlaying.value = progression.isPlaying
|
||||
// Still need to update the position now due to co-routine launch delays
|
||||
_positionDs.value = progression.calculateElapsedPositionMs().msToDs()
|
||||
positionDs.value = progression.calculateElapsedPositionMs().msToDs()
|
||||
// Replace the previous position co-routine with a new one that uses the new
|
||||
// state information.
|
||||
lastPositionJob?.cancel()
|
||||
lastPositionJob = viewModelScope.launch {
|
||||
while (true) {
|
||||
_positionDs.value = progression.calculateElapsedPositionMs().msToDs()
|
||||
positionDs.value = progression.calculateElapsedPositionMs().msToDs()
|
||||
// Wait a deci-second for the next position tick.
|
||||
delay(100)
|
||||
delay(100.milliseconds)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onRepeatModeChanged(repeatMode: RepeatMode) {
|
||||
_repeatMode.value = repeatMode
|
||||
this.repeatMode.value = repeatMode
|
||||
}
|
||||
|
||||
override fun onBarActionChanged() {
|
||||
_currentBarAction.value = playbackSettings.barAction
|
||||
currentBarAction.value = playbackSettings.barAction
|
||||
}
|
||||
|
||||
// --- PLAYING FUNCTIONS ---
|
||||
@@ -319,12 +312,12 @@ constructor(
|
||||
}
|
||||
|
||||
private fun startPlaybackDecision(decision: PlaybackDecision) {
|
||||
val existing = _playbackDecision.flow.value
|
||||
val existing = playbackDecision.flow.value
|
||||
if (existing != null) {
|
||||
L.d("Already handling decision $existing, ignoring $decision")
|
||||
return
|
||||
}
|
||||
_playbackDecision.put(decision)
|
||||
playbackDecision.put(decision)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -652,7 +645,7 @@ constructor(
|
||||
L.d("Already opening $existing, ignoring opening $panel")
|
||||
return
|
||||
}
|
||||
_openPanel.put(panel)
|
||||
openPanel.put(panel)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
|
||||
@@ -37,10 +37,9 @@ import timber.log.Timber as L
|
||||
@HiltViewModel
|
||||
class PlaybackPickerViewModel @Inject constructor(private val musicRepository: MusicRepository) :
|
||||
ViewModel(), MusicRepository.UpdateListener {
|
||||
private val _currentPickerSong = MutableStateFlow<Song?>(null)
|
||||
/** The current set of [Artist] choices to show in the picker, or null if to show nothing. */
|
||||
val currentPickerSong: StateFlow<Song?>
|
||||
get() = _currentPickerSong
|
||||
field = MutableStateFlow<Song?>(null)
|
||||
|
||||
init {
|
||||
musicRepository.addUpdateListener(this)
|
||||
@@ -49,11 +48,10 @@ class PlaybackPickerViewModel @Inject constructor(private val musicRepository: M
|
||||
override fun onMusicChanges(changes: MusicRepository.Changes) {
|
||||
if (!changes.deviceLibrary) return
|
||||
val library = musicRepository.library ?: return
|
||||
_currentPickerSong.value = _currentPickerSong.value?.run { library.findSong(uid) }
|
||||
currentPickerSong.value = currentPickerSong.value?.run { library.findSong(uid) }
|
||||
}
|
||||
|
||||
override fun onCleared() {
|
||||
super.onCleared()
|
||||
musicRepository.removeUpdateListener(this)
|
||||
}
|
||||
|
||||
@@ -64,8 +62,8 @@ class PlaybackPickerViewModel @Inject constructor(private val musicRepository: M
|
||||
*/
|
||||
fun setPickerSongUid(uid: Music.UID) {
|
||||
L.d("Opening picker for song $uid")
|
||||
_currentPickerSong.value = musicRepository.library?.findSong(uid)
|
||||
if (_currentPickerSong.value != null) {
|
||||
currentPickerSong.value = musicRepository.library?.findSong(uid)
|
||||
if (currentPickerSong.value != null) {
|
||||
L.w("Given song UID was invalid")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,15 +47,14 @@ class QueueViewModel @Inject constructor(private val playbackManager: PlaybackSt
|
||||
private val _queueInstructions = MutableEvent<UpdateInstructions>()
|
||||
/** Instructions for how to update [queue] in the UI. */
|
||||
val queueInstructions: Event<UpdateInstructions> = _queueInstructions
|
||||
private val _scrollTo = MutableEvent<Int>()
|
||||
|
||||
/** Controls whether the queue should be force-scrolled to a particular location. */
|
||||
val scrollTo: Event<Int>
|
||||
get() = _scrollTo
|
||||
field = MutableEvent<Int>()
|
||||
|
||||
private val _index = MutableStateFlow(playbackManager.index)
|
||||
/** The index of the currently playing song in the queue. */
|
||||
val index: StateFlow<Int>
|
||||
get() = _index
|
||||
field = MutableStateFlow(playbackManager.index)
|
||||
|
||||
init {
|
||||
playbackManager.addListener(this)
|
||||
@@ -63,8 +62,8 @@ class QueueViewModel @Inject constructor(private val playbackManager: PlaybackSt
|
||||
|
||||
override fun onIndexMoved(index: Int) {
|
||||
L.d("Index moved, synchronizing and scrolling to new position")
|
||||
_scrollTo.put(index)
|
||||
_index.value = index
|
||||
scrollTo.put(index)
|
||||
this.index.value = index
|
||||
}
|
||||
|
||||
override fun onQueueChanged(queue: List<Song>, index: Int, change: QueueChange) {
|
||||
@@ -75,7 +74,7 @@ class QueueViewModel @Inject constructor(private val playbackManager: PlaybackSt
|
||||
if (change.type != QueueChange.Type.MAPPING) {
|
||||
// Index changed, make sure it remains updated without actually scrolling to it.
|
||||
L.d("Index changed with queue, synchronizing new position")
|
||||
_index.value = index
|
||||
this.index.value = index
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,9 +82,9 @@ class QueueViewModel @Inject constructor(private val playbackManager: PlaybackSt
|
||||
// Queue changed completely -> Replace queue, update index
|
||||
L.d("Queue changed completely, replacing queue and position")
|
||||
_queueInstructions.put(UpdateInstructions.Replace(0))
|
||||
_scrollTo.put(index)
|
||||
scrollTo.put(index)
|
||||
_queue.value = queue
|
||||
_index.value = index
|
||||
this.index.value = index
|
||||
}
|
||||
|
||||
override fun onNewPlayback(
|
||||
@@ -97,13 +96,12 @@ class QueueViewModel @Inject constructor(private val playbackManager: PlaybackSt
|
||||
// Entirely new queue -> Replace queue, update index
|
||||
L.d("New playback, replacing queue and position")
|
||||
_queueInstructions.put(UpdateInstructions.Replace(0))
|
||||
_scrollTo.put(index)
|
||||
scrollTo.put(index)
|
||||
_queue.value = queue
|
||||
_index.value = index
|
||||
this.index.value = index
|
||||
}
|
||||
|
||||
override fun onCleared() {
|
||||
super.onCleared()
|
||||
playbackManager.removeListener(this)
|
||||
}
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ import androidx.media3.common.Format
|
||||
import androidx.media3.common.Player
|
||||
import androidx.media3.common.audio.AudioProcessor
|
||||
import androidx.media3.common.audio.BaseAudioProcessor
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import java.nio.ByteBuffer
|
||||
import javax.inject.Inject
|
||||
import kotlin.math.pow
|
||||
@@ -44,6 +45,7 @@ import timber.log.Timber as L
|
||||
*
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
@OptIn(markerClass = [UnstableApi::class])
|
||||
class ReplayGainAudioProcessor
|
||||
@Inject
|
||||
constructor(
|
||||
|
||||
@@ -40,6 +40,7 @@ import androidx.media3.exoplayer.source.MediaSource
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import javax.inject.Inject
|
||||
import kotlin.math.abs
|
||||
import kotlin.time.Duration.Companion.milliseconds
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
@@ -135,10 +136,10 @@ class ExoPlaybackStateHolder(
|
||||
get() = player.audioSessionId
|
||||
|
||||
override fun resolveQueue(): RawQueue {
|
||||
val library =
|
||||
musicRepository.library
|
||||
// No library, cannot do anything.
|
||||
?: return RawQueue(emptyList(), emptyList(), 0)
|
||||
if (musicRepository.library == null) {
|
||||
// No library, cannot do anything.
|
||||
return RawQueue(emptyList(), emptyList(), 0)
|
||||
}
|
||||
val heap = (0 until player.mediaItemCount).map { player.getMediaItemAt(it) }
|
||||
val shuffledMapping =
|
||||
if (player.shuffleModeEnabled) {
|
||||
@@ -574,7 +575,7 @@ class ExoPlaybackStateHolder(
|
||||
private fun deferSave() {
|
||||
saveJob {
|
||||
L.d("Waiting for save buffer")
|
||||
delay(SAVE_BUFFER)
|
||||
delay(SAVE_BUFFER.milliseconds)
|
||||
yield()
|
||||
L.d("Committing saved state")
|
||||
if (sessionOngoing) {
|
||||
|
||||
@@ -95,9 +95,8 @@ private constructor(
|
||||
val token: MediaSessionCompat.Token
|
||||
get() = mediaSession.sessionToken
|
||||
|
||||
private val _notification = PlaybackNotification(context, mediaSession.sessionToken)
|
||||
val notification: ForegroundServiceNotification
|
||||
get() = _notification
|
||||
field = PlaybackNotification(context, mediaSession.sessionToken)
|
||||
|
||||
fun attach() {
|
||||
playbackManager.addListener(this)
|
||||
@@ -172,7 +171,7 @@ private constructor(
|
||||
|
||||
override fun onProgressionChanged(progression: Progression) {
|
||||
invalidateSessionState()
|
||||
_notification.updatePlaying(playbackManager.progression.isPlaying)
|
||||
notification.updatePlaying(playbackManager.progression.isPlaying)
|
||||
if (!bitmapProvider.isBusy) {
|
||||
foregroundListener.updateForeground(ForegroundListener.Change.MEDIA_SESSION)
|
||||
}
|
||||
@@ -297,7 +296,7 @@ private constructor(
|
||||
}
|
||||
val metadata = builder.build()
|
||||
mediaSession.setMetadata(metadata)
|
||||
_notification.updateMetadata(metadata)
|
||||
notification.updateMetadata(metadata)
|
||||
foregroundListener.updateForeground(ForegroundListener.Change.MEDIA_SESSION)
|
||||
}
|
||||
},
|
||||
@@ -370,8 +369,8 @@ private constructor(
|
||||
L.d("Invalidating notification actions")
|
||||
invalidateSessionState()
|
||||
|
||||
_notification.updateRepeatMode(playbackManager.repeatMode)
|
||||
_notification.updateShuffled(playbackManager.isShuffled)
|
||||
notification.updateRepeatMode(playbackManager.repeatMode)
|
||||
notification.updateShuffled(playbackManager.isShuffled)
|
||||
|
||||
if (!bitmapProvider.isBusy) {
|
||||
L.d("Not loading a bitmap, post the notification")
|
||||
|
||||
@@ -83,10 +83,10 @@ constructor(
|
||||
playbackManager.play(requireNotNull(command) { "Invalid playback configuration" })
|
||||
}
|
||||
|
||||
override fun onPrepareFromSearch(query: String?, extras: Bundle?) {
|
||||
super.onPrepareFromSearch(query, extras)
|
||||
// STUB, can't tell when this is called
|
||||
}
|
||||
// override fun onPrepareFromSearch(query: String?, extras: Bundle?) {
|
||||
// super.onPrepareFromSearch(query, extras)
|
||||
// STUB, can't tell when this is called
|
||||
// }
|
||||
|
||||
override fun onPlayFromSearch(query: String, extras: Bundle) {
|
||||
super.onPlayFromSearch(query, extras)
|
||||
|
||||
@@ -22,6 +22,7 @@ import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.support.v4.media.session.MediaSessionCompat
|
||||
import javax.inject.Inject
|
||||
import kotlin.time.Duration.Companion.milliseconds
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
@@ -90,7 +91,7 @@ private constructor(
|
||||
private fun scheduleAutoStop() {
|
||||
autoStopJob?.cancel()
|
||||
autoStopJob = scope.launch {
|
||||
delay(AUTO_STOP_DELAY_MS)
|
||||
delay(AUTO_STOP_DELAY_MS.milliseconds)
|
||||
L.d("Auto-stop timer expired after ${AUTO_STOP_DELAY_MS / 60000} minutes of inactivity")
|
||||
playbackManager.endSession()
|
||||
}
|
||||
|
||||
@@ -20,7 +20,6 @@ package org.oxycblt.auxio.playback.ui
|
||||
|
||||
import android.content.Context
|
||||
import android.util.AttributeSet
|
||||
import android.view.View
|
||||
import android.widget.FrameLayout
|
||||
|
||||
/**
|
||||
@@ -41,6 +40,6 @@ constructor(
|
||||
override fun onFinishInflate() {
|
||||
super.onFinishInflate()
|
||||
check(childCount == 1) { "This layout should only contain one child" }
|
||||
getChildAt(0).layoutDirection = View.LAYOUT_DIRECTION_LTR
|
||||
getChildAt(0).layoutDirection = LAYOUT_DIRECTION_LTR
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,10 +77,10 @@ class StepperOverlay(context: Context, attrs: AttributeSet?) :
|
||||
LayoutInflater.from(context).inflate(R.layout.player_fast_seek_overlay, this, true)
|
||||
|
||||
// Set up shape appearance based on UISettings similar to CoverView
|
||||
context.withStyledAttributes(attrs, R.styleable.PlayerFastSeekOverlay) {
|
||||
context.withStyledAttributes(attrs, R.styleable.StepperOverlay) {
|
||||
val shapeAppearanceRes =
|
||||
getResourceId(
|
||||
R.styleable.PlayerFastSeekOverlay_shapeAppearance,
|
||||
R.styleable.StepperOverlay_shapeAppearance,
|
||||
com.google.android.material.R.style.ShapeAppearance_Material3_Corner_Medium,
|
||||
)
|
||||
|
||||
|
||||
@@ -89,21 +89,28 @@ class SearchAdapter(private val listener: SelectableListListener<Music>) :
|
||||
val DIFF_CALLBACK =
|
||||
object : SimpleDiffCallback<Item>() {
|
||||
override fun areContentsTheSame(oldItem: Item, newItem: Item) =
|
||||
when {
|
||||
oldItem is Song && newItem is Song ->
|
||||
when (oldItem) {
|
||||
is Song if newItem is Song ->
|
||||
SongViewHolder.DIFF_CALLBACK.areContentsTheSame(oldItem, newItem)
|
||||
oldItem is Album && newItem is Album ->
|
||||
|
||||
is Album if newItem is Album ->
|
||||
AlbumViewHolder.DIFF_CALLBACK.areContentsTheSame(oldItem, newItem)
|
||||
oldItem is Artist && newItem is Artist ->
|
||||
|
||||
is Artist if newItem is Artist ->
|
||||
ArtistViewHolder.DIFF_CALLBACK.areContentsTheSame(oldItem, newItem)
|
||||
oldItem is Genre && newItem is Genre ->
|
||||
|
||||
is Genre if newItem is Genre ->
|
||||
GenreViewHolder.DIFF_CALLBACK.areContentsTheSame(oldItem, newItem)
|
||||
oldItem is Playlist && newItem is Playlist ->
|
||||
|
||||
is Playlist if newItem is Playlist ->
|
||||
PlaylistViewHolder.DIFF_CALLBACK.areContentsTheSame(oldItem, newItem)
|
||||
oldItem is PlainDivider && newItem is PlainDivider ->
|
||||
|
||||
is PlainDivider if newItem is PlainDivider ->
|
||||
DividerViewHolder.DIFF_CALLBACK.areContentsTheSame(oldItem, newItem)
|
||||
oldItem is BasicHeader && newItem is BasicHeader ->
|
||||
|
||||
is BasicHeader if newItem is BasicHeader ->
|
||||
BasicHeaderViewHolder.DIFF_CALLBACK.areContentsTheSame(oldItem, newItem)
|
||||
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,10 +57,9 @@ constructor(
|
||||
private var lastQuery: String? = null
|
||||
private var currentSearchJob: Job? = null
|
||||
|
||||
private val _searchResults = MutableStateFlow(listOf<Item>())
|
||||
/** The results of the last [search] call, if any. */
|
||||
val searchResults: StateFlow<List<Item>>
|
||||
get() = _searchResults
|
||||
field = MutableStateFlow(listOf<Item>())
|
||||
|
||||
/** The [PlaySong] instructions to use when playing a [Song]. */
|
||||
val playWith
|
||||
@@ -71,7 +70,6 @@ constructor(
|
||||
}
|
||||
|
||||
override fun onCleared() {
|
||||
super.onCleared()
|
||||
musicRepository.removeUpdateListener(this)
|
||||
}
|
||||
|
||||
@@ -96,14 +94,14 @@ constructor(
|
||||
val library = musicRepository.library
|
||||
if (query.isNullOrEmpty() || library == null) {
|
||||
L.d("Cannot search for the current query, aborting")
|
||||
_searchResults.value = listOf()
|
||||
searchResults.value = listOf()
|
||||
return
|
||||
}
|
||||
|
||||
// Searching is time-consuming, so do it in the background.
|
||||
L.d("Searching music library for $query")
|
||||
currentSearchJob = viewModelScope.launch {
|
||||
_searchResults.value = searchImpl(library, query).also { yield() }
|
||||
searchResults.value = searchImpl(library, query).also { yield() }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ import android.util.AttributeSet
|
||||
import android.widget.ImageView
|
||||
import androidx.core.content.res.getResourceIdOrThrow
|
||||
import androidx.core.content.res.getTextArrayOrThrow
|
||||
import androidx.core.content.withStyledAttributes
|
||||
import androidx.preference.DialogPreference
|
||||
import androidx.preference.Preference
|
||||
import androidx.preference.PreferenceViewHolder
|
||||
@@ -58,36 +59,34 @@ constructor(
|
||||
private var currentValue: Int? = null
|
||||
|
||||
init {
|
||||
val prefAttrs =
|
||||
context.obtainStyledAttributes(
|
||||
attrs,
|
||||
R.styleable.IntListPreference,
|
||||
defStyleAttr,
|
||||
defStyleRes,
|
||||
)
|
||||
context.withStyledAttributes(
|
||||
attrs,
|
||||
R.styleable.IntListPreference,
|
||||
defStyleAttr,
|
||||
defStyleRes,
|
||||
) {
|
||||
|
||||
// Can't depend on ListPreference due to it working with strings we have to instead
|
||||
// define our own attributes for entries/values.
|
||||
entries = prefAttrs.getTextArrayOrThrow(R.styleable.IntListPreference_entries)
|
||||
values =
|
||||
context.resources.getIntArray(
|
||||
prefAttrs.getResourceIdOrThrow(R.styleable.IntListPreference_entryValues)
|
||||
)
|
||||
// Can't depend on ListPreference due to it working with strings we have to instead
|
||||
// define our own attributes for entries/values.
|
||||
val entries = getTextArrayOrThrow(R.styleable.IntListPreference_entries)
|
||||
val values =
|
||||
context.resources.getIntArray(
|
||||
getResourceIdOrThrow(R.styleable.IntListPreference_entryValues)
|
||||
)
|
||||
|
||||
// entryIcons defines an additional set of icons to use for each entry.
|
||||
val iconsId = prefAttrs.getResourceId(R.styleable.IntListPreference_entryIcons, -1)
|
||||
if (iconsId > -1) {
|
||||
entryIcons = context.resources.obtainTypedArray(iconsId)
|
||||
// entryIcons defines an additional set of icons to use for each entry.
|
||||
val iconsId = getResourceId(R.styleable.IntListPreference_entryIcons, -1)
|
||||
if (iconsId > -1) {
|
||||
entryIcons = context.resources.obtainTypedArray(iconsId)
|
||||
}
|
||||
|
||||
// offValue defines an value in which the preference should be disabled.
|
||||
val offValueId = getResourceId(R.styleable.IntListPreference_offValue, -1)
|
||||
if (offValueId > -1) {
|
||||
offValue = context.getInteger(offValueId)
|
||||
}
|
||||
}
|
||||
|
||||
// offValue defines an value in which the preference should be disabled.
|
||||
val offValueId = prefAttrs.getResourceId(R.styleable.IntListPreference_offValue, -1)
|
||||
if (offValueId > -1) {
|
||||
offValue = context.getInteger(offValueId)
|
||||
}
|
||||
|
||||
prefAttrs.recycle()
|
||||
|
||||
summaryProvider = IntListSummaryProvider()
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
|
||||
package org.oxycblt.auxio.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.graphics.drawable.Drawable
|
||||
import android.view.View
|
||||
@@ -123,6 +124,7 @@ class Spatial private constructor(@AttrRes val attr: Int, val defaultStyle: Int)
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("PrivateResource")
|
||||
companion object {
|
||||
val FAST =
|
||||
Spatial(
|
||||
@@ -134,11 +136,11 @@ class Spatial private constructor(@AttrRes val attr: Int, val defaultStyle: Int)
|
||||
MR.attr.motionSpringDefaultSpatial,
|
||||
MR.style.Motion_Material3_Spring_Standard_Default_Spatial,
|
||||
)
|
||||
val SLOW =
|
||||
Spatial(
|
||||
MR.attr.motionSpringSlowSpatial,
|
||||
MR.style.Motion_Material3_Spring_Standard_Slow_Spatial,
|
||||
)
|
||||
// val SLOW =
|
||||
// Spatial(
|
||||
// MR.attr.motionSpringSlowSpatial,
|
||||
// MR.style.Motion_Material3_Spring_Standard_Slow_Spatial,
|
||||
// )
|
||||
}
|
||||
}
|
||||
|
||||
@@ -190,11 +192,11 @@ class Effect private constructor(@AttrRes val attr: Int, @StyleRes val defaultSt
|
||||
MR.attr.motionSpringDefaultEffects,
|
||||
MR.style.Motion_Material3_Spring_Standard_Default_Effects,
|
||||
)
|
||||
val SLOW =
|
||||
Effect(
|
||||
MR.attr.motionSpringSlowEffects,
|
||||
MR.style.Motion_Material3_Spring_Standard_Slow_Effects,
|
||||
)
|
||||
// val SLOW =
|
||||
// Effect(
|
||||
// MR.attr.motionSpringSlowEffects,
|
||||
// MR.style.Motion_Material3_Spring_Standard_Slow_Effects,
|
||||
// )
|
||||
val FAST =
|
||||
Effect(
|
||||
MR.attr.motionSpringFastEffects,
|
||||
|
||||
@@ -26,7 +26,6 @@ import android.view.LayoutInflater
|
||||
import android.view.Menu
|
||||
import android.view.MenuItem
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.widget.FrameLayout
|
||||
import android.widget.LinearLayout
|
||||
import androidx.annotation.AttrRes
|
||||
@@ -39,10 +38,8 @@ import androidx.appcompat.widget.PopupMenu
|
||||
import androidx.appcompat.widget.Toolbar
|
||||
import androidx.appcompat.widget.TooltipCompat
|
||||
import androidx.core.view.children
|
||||
import androidx.core.view.get
|
||||
import androidx.core.view.isNotEmpty
|
||||
import androidx.core.view.isVisible
|
||||
import androidx.core.view.size
|
||||
import com.google.android.material.R as MR
|
||||
import org.oxycblt.auxio.R
|
||||
import org.oxycblt.auxio.databinding.ViewToolbarBinding
|
||||
@@ -62,16 +59,15 @@ constructor(
|
||||
attrs: AttributeSet? = null,
|
||||
@AttrRes defStyleAttr: Int = AR.attr.toolbarStyle,
|
||||
) : FrameLayout(context, attrs, defStyleAttr) {
|
||||
private var inflatingLayout: Boolean
|
||||
private val binding: ViewToolbarBinding
|
||||
private var inflatingLayout: Boolean = true
|
||||
private val binding: ViewToolbarBinding =
|
||||
ViewToolbarBinding.inflate(LayoutInflater.from(context), this, true)
|
||||
private var menuItemClickListener: Toolbar.OnMenuItemClickListener? = null
|
||||
private var overflowClickListener: OnClickListener? = null
|
||||
private val actionButtons = mutableMapOf<Int, RippleFixMaterialButton>()
|
||||
@SuppressLint("RestrictedApi") private var menuBuilder = MenuBuilder(context)
|
||||
|
||||
init {
|
||||
inflatingLayout = true
|
||||
binding = ViewToolbarBinding.inflate(LayoutInflater.from(context), this, true)
|
||||
inflatingLayout = false
|
||||
|
||||
clipChildren = false
|
||||
@@ -162,7 +158,7 @@ constructor(
|
||||
}
|
||||
}
|
||||
|
||||
override fun addView(child: View?, index: Int, params: ViewGroup.LayoutParams?) {
|
||||
override fun addView(child: View?, index: Int, params: LayoutParams?) {
|
||||
if (inflatingLayout) {
|
||||
super.addView(child, index, params)
|
||||
} else {
|
||||
@@ -174,10 +170,6 @@ constructor(
|
||||
}
|
||||
}
|
||||
|
||||
override fun onFinishInflate() {
|
||||
super.onFinishInflate()
|
||||
}
|
||||
|
||||
var title: CharSequence?
|
||||
get() = binding.toolbarTitle.text
|
||||
set(value) {
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
|
||||
package org.oxycblt.auxio.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.graphics.drawable.Drawable
|
||||
import android.util.AttributeSet
|
||||
@@ -96,6 +97,7 @@ abstract class BaseBottomSheetBehavior<V : View>(context: Context, attributeSet:
|
||||
override fun shouldExpandOnUpwardDrag(dragDurationMillis: Long, yPositionPercentage: Float) =
|
||||
true
|
||||
|
||||
@SuppressLint("PrivateResource")
|
||||
override fun onLayoutChild(parent: CoordinatorLayout, child: V, layoutDirection: Int): Boolean {
|
||||
val layout = super.onLayoutChild(parent, child, layoutDirection)
|
||||
// Don't repeat redundant initialization.
|
||||
|
||||
@@ -56,10 +56,11 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
|
||||
val index = children.indexOfFirst { it.id == viewId }
|
||||
if (index == currentlyVisible) return false
|
||||
L.d("Switching toolbar visibility from $currentlyVisible -> $index")
|
||||
return animateToolbarsVisibility(currentlyVisible, index).also { currentlyVisible = index }
|
||||
animateToolbarsVisibility(currentlyVisible, index).also { currentlyVisible = index }
|
||||
return true
|
||||
}
|
||||
|
||||
private fun animateToolbarsVisibility(from: Int, to: Int): Boolean {
|
||||
private fun animateToolbarsVisibility(from: Int, to: Int) {
|
||||
// Set up the target transitions for both the inner and selection toolbars.
|
||||
L.d("Changing toolbar visibility $from -> 0f, $to -> 1f")
|
||||
inAnimators?.forEach { it.cancel() }
|
||||
@@ -82,7 +83,5 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
|
||||
}
|
||||
}
|
||||
outAnimators = listOf(outScaleAnimation, outAlphaAnimation)
|
||||
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,7 +114,7 @@ abstract class ViewBindingBottomSheetDialogFragment<VB : ViewBinding> :
|
||||
L.d("Fragment destroyed")
|
||||
}
|
||||
|
||||
private inner class TweakedBottomSheetDialog
|
||||
private class TweakedBottomSheetDialog
|
||||
@JvmOverloads
|
||||
constructor(context: Context, @StyleRes theme: Int = 0) :
|
||||
BackportBottomSheetDialog(context, theme) {
|
||||
|
||||
@@ -63,48 +63,3 @@ fun lazyReflectedMethod(clazz: KClass<*>, method: String, vararg params: KClass<
|
||||
it.isAccessible = true
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Split a [String] by the given selector, automatically handling escaped characters that satisfy
|
||||
* the selector.
|
||||
*
|
||||
* @param selector A block that determines if the string should be split at a given character.
|
||||
* @return One or more [String]s split by the selector.
|
||||
*/
|
||||
internal fun String.splitEscaped(selector: Char): List<String> {
|
||||
val split = mutableListOf<String>()
|
||||
var currentString = ""
|
||||
var i = 0
|
||||
|
||||
while (i < length) {
|
||||
val a = get(i)
|
||||
val b = getOrNull(i + 1)
|
||||
|
||||
if (a == selector) {
|
||||
// Non-escaped separator, split the string here, making sure any stray whitespace
|
||||
// is removed.
|
||||
split.add(currentString)
|
||||
currentString = ""
|
||||
i++
|
||||
continue
|
||||
}
|
||||
|
||||
if (b != null && a == '\\' && a == selector) {
|
||||
// Is an escaped character, add the non-escaped variant and skip two
|
||||
// characters to move on to the next one.
|
||||
currentString += b
|
||||
i += 2
|
||||
} else {
|
||||
// Non-escaped, increment normally.
|
||||
currentString += a
|
||||
i++
|
||||
}
|
||||
}
|
||||
|
||||
if (currentString.isNotEmpty()) {
|
||||
// Had an in-progress split string that is now terminated, add it.
|
||||
split.add(currentString)
|
||||
}
|
||||
|
||||
return split
|
||||
}
|
||||
|
||||
@@ -119,7 +119,7 @@ class WidgetProvider : AppWidgetProvider() {
|
||||
|
||||
// Manually update AppWidgetManager with the new views.
|
||||
val component = ComponentName(context, this::class.java)
|
||||
while (victims.size > 0) {
|
||||
while (victims.isNotEmpty()) {
|
||||
try {
|
||||
awm.updateAppWidgetCompat(context, component, views)
|
||||
L.d("Successfully updated RemoteViews layout")
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
<attr name="enableSelectionBadge" format="boolean" />
|
||||
</declare-styleable>
|
||||
|
||||
<declare-styleable name="PlayerFastSeekOverlay">
|
||||
<declare-styleable name="StepperOverlay">
|
||||
<attr name="shapeAppearance" />
|
||||
</declare-styleable>
|
||||
|
||||
|
||||
@@ -19,7 +19,6 @@
|
||||
package org.oxycblt.musikr
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
@@ -115,7 +114,6 @@ private class MusikrImpl(
|
||||
) : Musikr {
|
||||
override suspend fun run(onProgress: suspend (IndexingProgress) -> Unit) = coroutineScope {
|
||||
onProgress(IndexingProgress.Songs(0, 0))
|
||||
val start = System.currentTimeMillis()
|
||||
var explored = 0
|
||||
var loaded = 0
|
||||
val exploredChannel = Channel<Explored>(Channel.UNLIMITED)
|
||||
@@ -143,7 +141,6 @@ private class MusikrImpl(
|
||||
}
|
||||
val library = evaluateStep.evaluate(trackedExtractedChannel)
|
||||
merge(exploredTask, extractedTask, trackedExploredTask, trackedExtractedTask).await()
|
||||
Log.d("Musikr", "Indexing took ${System.currentTimeMillis() - start}ms")
|
||||
LibraryResultImpl(config, library)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@ interface CoverIdentifier {
|
||||
}
|
||||
}
|
||||
|
||||
private class MD5CoverIdentifier() : CoverIdentifier {
|
||||
private class MD5CoverIdentifier : CoverIdentifier {
|
||||
@OptIn(ExperimentalStdlibApi::class)
|
||||
override suspend fun identify(data: ByteArray): String {
|
||||
val digest =
|
||||
|
||||
@@ -56,7 +56,7 @@ private constructor(
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
override suspend fun explore(files: Channel<File>): Deferred<Result<Unit>> = coroutineScope {
|
||||
tryAsyncWith(files, Dispatchers.IO) {
|
||||
tryAsyncWith(files, Dispatchers.IO) { _ ->
|
||||
val projection = BASE_PROJECTION + pathInterpreterFactory.projection
|
||||
var selector = BASE_SELECTOR
|
||||
val args = mutableListOf<String>()
|
||||
|
||||
@@ -22,6 +22,7 @@ import android.content.ContentUris
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.provider.DocumentsContract
|
||||
import androidx.core.net.toUri
|
||||
import java.io.File
|
||||
import org.oxycblt.musikr.fs.Components
|
||||
import org.oxycblt.musikr.fs.Path
|
||||
@@ -129,8 +130,8 @@ private class DocumentPathFactoryImpl(
|
||||
|
||||
private val POSSIBLE_CONTENT_URI_PREFIXES =
|
||||
arrayOf(
|
||||
Uri.parse("content://downloads/public_downloads"),
|
||||
Uri.parse("content://downloads/my_downloads"),
|
||||
"content://downloads/public_downloads".toUri(),
|
||||
"content://downloads/my_downloads".toUri(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ import android.os.Looper
|
||||
|
||||
internal class LocationObserver(
|
||||
private val context: Context,
|
||||
private val uri: Uri,
|
||||
uri: Uri,
|
||||
private val onUpdate: () -> Unit,
|
||||
) : ContentObserver(Handler(Looper.getMainLooper())), Runnable {
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
|
||||
@@ -285,10 +285,10 @@ private class MusicGraphBuilderImpl : MusicGraph.Builder {
|
||||
val canon = cluster.maxBy { it.songVertices.size }.preAlbum
|
||||
val same = cluster.all { it.preAlbum == canon }
|
||||
if (!same) {
|
||||
val noMbidPreAlbum = canon
|
||||
// canon is the no-mbid pre-album
|
||||
val simpleMbidVertex =
|
||||
albumVertices.getOrPut(noMbidPreAlbum) {
|
||||
AlbumVertex(noMbidPreAlbum, mutableListOf())
|
||||
albumVertices.getOrPut(canon) {
|
||||
AlbumVertex(canon, mutableListOf())
|
||||
}
|
||||
for (album in cluster) {
|
||||
meldAlbumVertices(album, simpleMbidVertex)
|
||||
|
||||
@@ -46,7 +46,7 @@ internal interface LibraryFactory {
|
||||
}
|
||||
}
|
||||
|
||||
private class LibraryFactoryImpl() : LibraryFactory {
|
||||
private class LibraryFactoryImpl : LibraryFactory {
|
||||
override fun create(
|
||||
graph: MusicGraph,
|
||||
storedPlaylists: StoredPlaylists,
|
||||
|
||||
@@ -19,7 +19,6 @@
|
||||
package org.oxycblt.musikr.pipeline
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import org.oxycblt.musikr.BuildConfig
|
||||
import org.oxycblt.musikr.Config
|
||||
@@ -69,7 +68,6 @@ private class EvaluateStepImpl(
|
||||
if (BuildConfig.DEBUG) {
|
||||
val fileName = "music_graph_debug.dot"
|
||||
graph.renderToGraphviz(context, fileName)
|
||||
val filePath = context.filesDir.resolve(fileName).absolutePath
|
||||
}
|
||||
|
||||
return libraryFactory.create(graph, storedPlaylists, playlistInterpreter)
|
||||
|
||||
@@ -18,50 +18,8 @@
|
||||
|
||||
package org.oxycblt.musikr.pipeline
|
||||
|
||||
import kotlin.coroutines.CoroutineContext
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.asFlow
|
||||
import kotlinx.coroutines.flow.buffer
|
||||
import kotlinx.coroutines.flow.flattenMerge
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import kotlinx.coroutines.flow.flowOn
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.receiveAsFlow
|
||||
import kotlinx.coroutines.flow.withIndex
|
||||
|
||||
/**
|
||||
* Equally "distributes" the values of some flow across n new flows.
|
||||
*
|
||||
* Note that this function requires the "manager" flow to be consumed alongside the split flows in
|
||||
* order to function. Without this, all of the newly split flows will simply block.
|
||||
*/
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
internal fun <T, R> Flow<T>.distributedMap(
|
||||
n: Int,
|
||||
on: CoroutineContext = Dispatchers.Main,
|
||||
buffer: Int = Channel.UNLIMITED,
|
||||
block: suspend (T) -> R,
|
||||
): Flow<R> {
|
||||
val posChannels = List(n) { Channel<T>(Channel.UNLIMITED) }
|
||||
val managerFlow =
|
||||
flow<Nothing> {
|
||||
withIndex().collect {
|
||||
val index = it.index % n
|
||||
posChannels[index].send(it.value)
|
||||
}
|
||||
for (channel in posChannels) {
|
||||
channel.close()
|
||||
}
|
||||
}
|
||||
.buffer()
|
||||
return (posChannels.map { it.receiveAsFlow() } + managerFlow)
|
||||
.asFlow()
|
||||
.map { it.tryMap(block).flowOn(on).buffer(buffer) }
|
||||
.flattenMerge(concurrency = n + 1)
|
||||
}
|
||||
|
||||
internal fun <T, R> Flow<T>.tryMap(transform: suspend (T) -> R): Flow<R> = flow {
|
||||
collect { value ->
|
||||
@@ -72,15 +30,3 @@ internal fun <T, R> Flow<T>.tryMap(transform: suspend (T) -> R): Flow<R> = flow
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal suspend fun <T, A> Flow<T>.tryFold(initial: A, operation: suspend (A, T) -> A): A {
|
||||
var accumulator = initial
|
||||
collect { value ->
|
||||
try {
|
||||
accumulator = operation(accumulator, value)
|
||||
} catch (e: Exception) {
|
||||
throw PipelineException(value, e)
|
||||
}
|
||||
}
|
||||
return accumulator
|
||||
}
|
||||
|
||||
@@ -264,17 +264,17 @@ private class M3UImpl(private val volumeManager: VolumeManager) : M3U() {
|
||||
var relativeComponents = Components.parseUnix(".")
|
||||
|
||||
// TODO: Simplify this logic
|
||||
when {
|
||||
commonIndex == components.size && commonIndex == workingDirectory.components.size -> {
|
||||
when (commonIndex) {
|
||||
components.size if commonIndex == workingDirectory.components.size -> {
|
||||
// The paths are the same. This shouldn't occur.
|
||||
}
|
||||
commonIndex == components.size -> {
|
||||
components.size -> {
|
||||
// The working directory is deeper in the path, backtrack.
|
||||
for (i in 0..<workingDirectory.components.size - commonIndex) {
|
||||
relativeComponents = relativeComponents.child("..")
|
||||
}
|
||||
}
|
||||
commonIndex == workingDirectory.components.size -> {
|
||||
workingDirectory.components.size -> {
|
||||
// Working directory is shallower than the path, can just append the
|
||||
// non-common remainder of the path
|
||||
relativeComponents = relativeComponents.child(depth(commonIndex))
|
||||
|
||||
@@ -91,7 +91,7 @@ private data class IntelligentKnownName(override val raw: String, override val s
|
||||
// Replace punctuation with spaces to create token boundaries, improving
|
||||
// sorting of names like "15-9" vs "15-10".
|
||||
.replace(punctRegex, " ")
|
||||
.let { if (it.isBlank()) name else it }
|
||||
.let { it.ifBlank { name } }
|
||||
.run {
|
||||
// Strip any english articles like "the" or "an" from the start, as music
|
||||
// sorting should ignore such when possible.
|
||||
|
||||
@@ -316,6 +316,6 @@ private fun Metadata.parseId3v23Date(): Date? {
|
||||
}
|
||||
} else {
|
||||
// Unable to parse month/day, just return a year
|
||||
return Date.from(year)
|
||||
Date.from(year)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,14 +34,15 @@ import org.oxycblt.musikr.tag.Date
|
||||
fun CoroutineScope.tryAsync(
|
||||
context: CoroutineContext,
|
||||
block: suspend () -> Unit,
|
||||
): Deferred<Result<Unit>> = async {
|
||||
try {
|
||||
block()
|
||||
Result.success(Unit)
|
||||
} catch (e: Throwable) {
|
||||
Result.failure(e)
|
||||
): Deferred<Result<Unit>> =
|
||||
async(context = context) {
|
||||
try {
|
||||
block()
|
||||
Result.success(Unit)
|
||||
} catch (e: Throwable) {
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun <T> CoroutineScope.tryAsyncWith(
|
||||
channel: Channel<T>,
|
||||
@@ -70,7 +71,6 @@ fun <T, R> CoroutineScope.map(
|
||||
block(item)?.let { output.send(it) }
|
||||
}
|
||||
output.close()
|
||||
Unit
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user